Debian Codegraph @

tests/run_tests

raw
1 #!/usr/bin/env python3
2
3 """
4 Tests for kxd and kxc
5 ---------------------
6
7 This file contains various integration and validation tests for kxc and kxd.
8
9 It will create different test configurations and run the compiled server and
10 client under various conditions, to make sure they behave as intended.
11 """
12
13 # NOTE: Please run "black run_tests" after making changes, to to make sure the
14 # file has a reasonably uniform coding style.
15
16
17 import contextlib
18 import http.client
19 import os
20 import shutil
21 import socket
22 import ssl
23 import subprocess
24 import tempfile
25 import textwrap
26 import threading
27 import time
28 import tracemalloc
29 import unittest
30
31 tracemalloc.start()
32
33 ############################################################
34 # Test infrastructure.
35 #
36 # These functions and classes are used to make the individual tests easier to
37 # write. For the individual test cases, see below.
38
39 # Path to our built binaries; used to run the server and client for testing
40 # purposes.
41 BINS = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/../out")
42
43 TEMPDIR = "/does/not/exist"
44
45 # User the script is running as. Just informational, for troubleshooting
46 # purposes, so we don't care if it's missing.
47 LOGNAME = os.environ.get("LOGNAME", "unknown")
48
49
50 def setUpModule(): # pylint: disable=invalid-name
51 if not os.path.isfile(BINS + "/kxd"):
52 raise RuntimeError("kxd not found at " + BINS + "/kxd")
53 if not os.path.isfile(BINS + "/kxc"):
54 raise RuntimeError("kxc not found at " + BINS + "/kxc")
55 if not os.path.isfile(BINS + "/kxgencert"):
56 raise RuntimeError("kxgencert not found at " + BINS + "/kxgencert")
57
58 global TEMPDIR # pylint: disable=global-statement
59 TEMPDIR = tempfile.mkdtemp(prefix="kxdtest-")
60
61
62 def tearDownModule(): # pylint: disable=invalid-name
63 # Remove the temporary directory only on success.
64 # Be extra paranoid about removing.
65 # TODO: Only remove on success.
66 if os.environ.get("KEEPTMP"):
67 return
68 if len(TEMPDIR) > 10 and not TEMPDIR.startswith("/home"):
69 shutil.rmtree(TEMPDIR)
70
71
72 @contextlib.contextmanager
73 def pushd(path):
74 prev = os.getcwd()
75 os.chdir(path)
76 yield
77 os.chdir(prev)
78
79
80 class Config:
81 def __init__(self, name, host=""):
82 self.path = tempfile.mkdtemp(prefix="config-%s-" % name, dir=TEMPDIR)
83 self.name = name
84 self.host = host
85 self.keys = {}
86
87 def gen_cert(self):
88 try:
89 cmd = [
90 BINS + "/kxgencert",
91 "-organization=kxd-tests-%s" % self.name,
92 "-key=" + self.key_path(),
93 "-cert=" + self.cert_path(),
94 ]
95 if self.host:
96 cmd.append("-host=" + self.host)
97 subprocess.check_output(cmd, stderr=subprocess.STDOUT)
98 except subprocess.CalledProcessError as err:
99 print("kxgencert call failed, output: %r" % err.output)
100 raise
101
102 def cert_path(self):
103 return self.path + "/cert.pem"
104
105 def key_path(self):
106 return self.path + "/key.pem"
107
108 def cert(self):
109 return read_all(self.path + "/cert.pem")
110
111 def new_key(
112 self, name, allowed_clients=None, allowed_hosts=None, email_to=None
113 ):
114 self.keys[name] = os.urandom(1024)
115 key_path = self.path + "/data/" + name + "/"
116 if not os.path.isdir(key_path):
117 os.makedirs(key_path)
118 with open(key_path + "key", "bw") as key:
119 key.write(self.keys[name])
120
121 if allowed_clients is not None:
122 with open(key_path + "/allowed_clients", "a") as cfd:
123 for cli in allowed_clients:
124 cfd.write(cli)
125
126 if allowed_hosts is not None:
127 with open(key_path + "/allowed_hosts", "a") as hfd:
128 for host in allowed_hosts:
129 hfd.write(host + "\n")
130
131 if email_to is not None:
132 with open(key_path + "/email_to", "a") as efd:
133 efd.write(email_to + "\n")
134
135 def call(self, server_cert, url):
136 args = [
137 BINS + "/kxc",
138 "--client_cert=%s/cert.pem" % self.path,
139 "--client_key=%s/key.pem" % self.path,
140 "--server_cert=%s" % server_cert,
141 url,
142 ]
143 try:
144 print("Running client:", " ".join(args))
145 return subprocess.check_output(args, stderr=subprocess.STDOUT)
146 except subprocess.CalledProcessError as err:
147 print("Client call failed, output: %r" % err.output)
148 raise
149
150
151 class ServerConfig(Config):
152 def __init__(self, name="server", host="localhost"):
153 Config.__init__(self, name, host)
154 self.gen_cert()
155
156 def call(self, server_cert, url):
157 # To prevent accidental calls and to enforce that the test cases
158 # don't mix server and client.
159 return NotImplementedError("ServerConfig does not support call")
160
161
162 class ClientConfig(Config):
163 def __init__(self, name="client", host="localhost"):
164 Config.__init__(self, name, host)
165 self.gen_cert()
166
167 def new_key(self, name, allowed_clients=None, allowed_hosts=None):
168 # To prevent accidental calls and to enforce that the test cases
169 # don't mix server and client.
170 raise NotImplementedError("ClientConfig does not support new_key")
171
172
173 class StaticConfig(Config):
174 def __init__(self, path):
175 self.path = path
176 self.host = "localhost"
177 self.keys = {}
178
179 def gen_cert(self):
180 raise NotImplementedError("StaticConfig does not support gen_cert")
181
182
183 def launch_daemon(cfg, smtp_addr=None):
184 args = [
185 BINS + "/kxd",
186 "--data_dir=%s/data" % cfg,
187 "--key=%s/key.pem" % cfg,
188 "--cert=%s/cert.pem" % cfg,
189 "--logfile=%s/log" % cfg,
190 "--hook=%s/hook" % cfg,
191 ]
192 if smtp_addr:
193 args.append("--smtp_addr=%s:%s" % smtp_addr)
194 print("Launching server: ", " ".join(args))
195 return subprocess.Popen(args)
196
197
198 def read_all(fname):
199 with open(fname) as fd: # pylint: disable=invalid-name
200 return fd.read()
201
202
203 def receive_emails():
204 """Receive emails from the server.
205
206 Return:
207 - The server address.
208 - A list where we will put the emails: each email is a tuple of
209 (destination addresses, body).
210 """
211 server = socket.create_server(("localhost", 0))
212 server.listen(1)
213 addr = server.getsockname()
214
215 emails = []
216
217 def handler():
218 # Complete a simple SMTP transaction.
219 sock, addr = server.accept()
220 sock.sendall(b"220 localhost SMTP\n")
221 body = b""
222 rcpt_to = []
223 while True:
224 data = sock.recv(1024)
225 if not data:
226 break
227 if data.startswith(b"HELO"):
228 sock.sendall(b"250 localhost\n")
229 elif data.startswith(b"MAIL FROM"):
230 sock.sendall(b"250 OK\n")
231 elif data.startswith(b"RCPT TO"):
232 rcpt_to.append(data.split(b"<")[1].split(b">")[0].decode())
233 sock.sendall(b"250 OK\n")
234 elif data.startswith(b"DATA"):
235 sock.sendall(b"354 Start data\n")
236 body = b""
237 while True:
238 body += sock.recv(1024)
239 if body.endswith(b"\r\n.\r\n"):
240 sock.sendall(b"250 OK\n")
241 break
242 elif data.startswith(b"QUIT"):
243 sock.sendall(b"221 Chau\n")
244 break
245 else:
246 sock.sendall(b"500 Unknown command\n")
247
248 emails.append((rcpt_to, body))
249 sock.close()
250 server.close()
251
252 server_thread = threading.Thread(target=handler, daemon=True)
253 server_thread.start()
254
255 return addr, emails
256
257
258 class TestCase(unittest.TestCase):
259 def setUp(self):
260 self.server = ServerConfig()
261 self.client = ClientConfig()
262 self.daemon = None
263 self.ca = None # pylint: disable=invalid-name
264 self.launch_server(self.server)
265
266 def tearDown(self):
267 if self.daemon:
268 self.daemon.terminate()
269 self.daemon.wait()
270
271 def launch_server(self, server, smtp_addr=None):
272 self.daemon = launch_daemon(server.path, smtp_addr)
273
274 # Wait for the server to start accepting connections.
275 deadline = time.time() + 5
276 while time.time() < deadline:
277 try:
278 with socket.create_connection(("localhost", 19840), timeout=5):
279 break
280 except socket.error:
281 continue
282 else:
283 self.fail("Timeout waiting for the server")
284
285 # pylint: disable=invalid-name
286 def assertClientFails(self, url, regexp, client=None, cert_path=None):
287 if client is None:
288 client = self.client
289 if cert_path is None:
290 cert_path = self.server.cert_path()
291
292 try:
293 client.call(cert_path, url)
294 except subprocess.CalledProcessError as err:
295 self.assertRegex(err.output.decode(), regexp)
296 else:
297 self.fail("Client call did not fail as expected")
298
299
300 ############################################################
301 # Test cases.
302 #
303
304
305 class Simple(TestCase):
306 """Simple test cases for common (mis)configurations."""
307
308 def test_simple(self):
309 # There's no need to split these up; by doing all these within a
310 # single test, we speed things up significantly, as we avoid the
311 # overhead of creating the certificates and bringing up the server.
312
313 server_url = "kxd://" + self.server.host
314
315 # Normal successful case.
316 self.server.new_key(
317 "k1",
318 allowed_clients=[self.client.cert()],
319 # Depending on the self.server.host, the client may connect to it
320 # from localhost or from another IP; since it is unpredictable we
321 # should allow both.
322 allowed_hosts=["localhost", self.server.host],
323 )
324 key = self.client.call(self.server.cert_path(), server_url + "/k1")
325 self.assertEqual(key, self.server.keys["k1"])
326
327 # Unknown key -> 404.
328 self.assertClientFails(server_url + "/k2", "404 Not Found")
329
330 # No certificates allowed -> 403.
331 self.server.new_key("k3", allowed_hosts=["localhost", self.server.host])
332 self.assertClientFails(
333 server_url + "/k3", "403 Forbidden.*No allowed certificate found"
334 )
335
336 # Host not allowed -> 403.
337 self.server.new_key(
338 "k4", allowed_clients=[self.client.cert()], allowed_hosts=[]
339 )
340 self.assertClientFails(
341 server_url + "/k4", "403 Forbidden.*Host not allowed"
342 )
343
344 # Nothing allowed -> 403.
345 # We don't restrict the reason of failure, that's not defined in this
346 # case, as it could be either the host or the cert that are validated
347 # first.
348 self.server.new_key("k5")
349 self.assertClientFails(server_url + "/k5", "403 Forbidden")
350
351 # We tell the client to expect the server certificate to be the client
352 # one, which is never going to work.
353 self.assertClientFails(
354 server_url + "/k1",
355 "certificate signed by unknown authority",
356 cert_path=self.client.cert_path(),
357 )
358
359
360 class WildcardHostnamesKxgencert(Simple):
361 """Tests for certificates with DNSNames='*'.
362
363 In kxd <= 0.16, by default kxgencert (and before than, the equivalent
364 scripts) would generate certificates with DNSNames='*', and everything
365 worked okay.
366
367 But in Go 1.23, the Go TLS library started to reject such certificates (Go
368 commit 375031d8dcec9ae74d2dbc437b201107dba3bb5f).
369
370 We changed the defaults since then, but we still want to make sure that
371 the server can handle such certificates, as they might still be in use in
372 the wild.
373
374 This test uses static certificates generated with the old defaults, to
375 be absolutely sure they survive even through changes in the key generation
376 code.
377 """
378
379 _cert_dir = "wildcard_test_certs_kxgencert"
380
381 def setUp(self):
382 test_dir = os.path.dirname(os.path.realpath(__file__))
383 self.server = StaticConfig(test_dir + "/" + self._cert_dir + "/server")
384 self.client = StaticConfig(test_dir + "/" + self._cert_dir + "/client")
385
386 self.daemon = None
387 self.ca = None # pylint: disable=invalid-name
388 self.launch_server(self.server)
389
390 def test_minimal(self):
391 self.server.new_key(
392 "k1",
393 allowed_clients=[self.client.cert()],
394 allowed_hosts=["localhost"],
395 )
396 key = self.client.call(self.server.cert_path(), "kxd://localhost/k1")
397 self.assertEqual(key, self.server.keys["k1"])
398
399 # Reuse the rest of the Simple test cases.
400
401
402 class WildcardHostnamesOpenSSL(WildcardHostnamesKxgencert):
403 """Tests for certificates with DNSNames='*' generated with OpenSSL."""
404
405 _cert_dir = "wildcard_test_certs_openssl"
406
407
408 class SpecificHostnames(Simple):
409 """Tests for certificates with specific hostnames.
410
411 These tests check that the server ignores the client certificate's
412 hostname, and that the client validates the server certificate's hostname
413 in scenarios that it is different than `localhost`.
414 """
415
416 def setUp(self):
417 self.server = ServerConfig(host=socket.gethostname())
418 self.client = ClientConfig(host="client-" + os.urandom(8).hex())
419 self.daemon = None
420 self.ca = None # pylint: disable=invalid-name
421 self.launch_server(self.server)
422
423 def test_minimal(self):
424 self.server.new_key(
425 "k1",
426 allowed_clients=[self.client.cert()],
427 allowed_hosts=["localhost", self.server.host],
428 )
429 key = self.client.call(
430 self.server.cert_path(), "kxd://" + self.server.host + "/k1"
431 )
432 self.assertEqual(key, self.server.keys["k1"])
433
434
435 class CertFor127_0_0_1(Simple):
436 """Tests for server certificate for 127.0.0.1 (instead of a name)."""
437
438 def setUp(self):
439 self.server = ServerConfig(host="127.0.0.1")
440 self.client = ClientConfig(host="client-" + os.urandom(8).hex())
441 self.daemon = None
442 self.ca = None # pylint: disable=invalid-name
443 self.launch_server(self.server)
444
445 def test_minimal(self):
446 self.server.new_key(
447 "k1",
448 allowed_clients=[self.client.cert()],
449 allowed_hosts=["localhost"],
450 )
451 key = self.client.call(
452 self.server.cert_path(), "kxd://" + self.server.host + "/k1"
453 )
454 self.assertEqual(key, self.server.keys["k1"])
455
456
457 class CommonErrors(TestCase):
458 """Simple test cases for common errors."""
459
460 def test_invalid_schema(self):
461 self.assertClientFails("invalidschema://a/b", "unsupported URL schema")
462
463 def test_invalid_url(self):
464 self.assertClientFails(
465 " http://invalid/url",
466 "first path segment in URL cannot contain colon",
467 )
468
469 def test_empty_server_cert(self):
470 self.assertClientFails(
471 "kxd://localhost/k1",
472 "Failed to load server certs: error appending certificates",
473 cert_path="/dev/null",
474 )
475
476 def test_unknown_server_cert_file(self):
477 self.assertClientFails(
478 "kxd://localhost/k1",
479 "open /does/not/exist: no such file or directory",
480 cert_path="/does/not/exist",
481 )
482
483 def test_bad_server_cert_file(self):
484 test_dir = os.path.dirname(os.path.realpath(__file__))
485 self.assertClientFails(
486 "kxd://localhost/k1",
487 "x509: malformed certificate",
488 cert_path=test_dir + "/bad_cert/cert.pem",
489 )
490
491
492 class Multiples(TestCase):
493 """Tests for multiple clients and keys."""
494
495 def setUp(self):
496 TestCase.setUp(self)
497 self.client2 = ClientConfig(name="client2")
498
499 def test_two_clients(self):
500 self.server.new_key(
501 "k1",
502 allowed_clients=[self.client.cert(), self.client2.cert()],
503 allowed_hosts=["localhost"],
504 )
505 key = self.client.call(self.server.cert_path(), "kxd://localhost/k1")
506 self.assertEqual(key, self.server.keys["k1"])
507
508 key = self.client2.call(self.server.cert_path(), "kxd://localhost/k1")
509 self.assertEqual(key, self.server.keys["k1"])
510
511 # Only one client allowed.
512 self.server.new_key(
513 "k2",
514 allowed_clients=[self.client.cert()],
515 allowed_hosts=["localhost"],
516 )
517 key = self.client.call(self.server.cert_path(), "kxd://localhost/k2")
518 self.assertEqual(key, self.server.keys["k2"])
519
520 self.assertClientFails(
521 "kxd://localhost/k2",
522 "403 Forbidden.*No allowed certificate found",
523 client=self.client2,
524 )
525
526 def test_many_keys(self):
527 keys = ["a", "d/e", "a/b/c", "d/"]
528 for key in keys:
529 self.server.new_key(
530 key,
531 allowed_clients=[self.client.cert(), self.client2.cert()],
532 allowed_hosts=["localhost"],
533 )
534
535 for key in keys:
536 data = self.client.call(
537 self.server.cert_path(), "kxd://localhost/%s" % key
538 )
539 self.assertEqual(data, self.server.keys[key])
540
541 data = self.client2.call(
542 self.server.cert_path(), "kxd://localhost/%s" % key
543 )
544 self.assertEqual(data, self.server.keys[key])
545
546 self.assertClientFails("kxd://localhost/a/b", "404 Not Found")
547
548 def test_two_servers(self):
549 server1 = self.server
550 server1.new_key("k1", allowed_clients=[self.client.cert()])
551 server2 = ServerConfig(name="server2")
552 server2.new_key("k1", allowed_clients=[self.client.cert()])
553
554 # Write a file containing the certs of both servers.
555 server_certs_path = self.client.path + "/server_certs.pem"
556 server_certs = open(server_certs_path, "w")
557 server_certs.write(read_all(server1.cert_path()))
558 server_certs.write(read_all(server2.cert_path()))
559 server_certs.close()
560
561 key = self.client.call(server_certs_path, "kxd://localhost/k1")
562 self.assertEqual(key, server1.keys["k1"])
563
564 self.daemon.terminate()
565 self.daemon.wait()
566 time.sleep(0.5)
567 self.launch_server(server2)
568
569 key = self.client.call(server_certs_path, "kxd://localhost/k1")
570 self.assertEqual(key, server2.keys["k1"])
571
572
573 class TrickyRequests(TestCase):
574 """Tests for tricky requests."""
575
576 def https_connection(self, host, port, key_file=None, cert_file=None):
577 # Get an SSL context that can validate our server certificate.
578 context = ssl.create_default_context(cafile=self.server.cert_path())
579 context.check_hostname = False
580 if cert_file:
581 context.load_cert_chain(cert_file, key_file)
582 return http.client.HTTPSConnection(host, port, context=context)
583
584 def test_no_local_cert(self):
585 """No local certificate."""
586 conn = self.https_connection("localhost", 19840)
587 try:
588 conn.request("GET", "/v1/")
589 conn.getresponse()
590 conn.close()
591 except ssl.SSLError as err:
592 # Expect one of these errors (the specific one can change
593 # depending on the version of OpenSSL).
594 self.assertIn(
595 err.reason,
596 [
597 "SSLV3_ALERT_BAD_CERTIFICATE",
598 "TLSV13_ALERT_CERTIFICATE_REQUIRED",
599 ],
600 )
601 else:
602 self.fail("Client call did not fail as expected")
603
604 def test_path_with_dotdot(self):
605 """Requests with '..'."""
606 conn = self.https_connection(
607 "localhost",
608 19840,
609 key_file=self.client.key_path(),
610 cert_file=self.client.cert_path(),
611 )
612 conn.request("GET", "/v1/a/../b")
613 response = conn.getresponse()
614 conn.close()
615
616 # Go's http server intercepts these and gives us a 301 Moved
617 # Permanently.
618 self.assertEqual(response.status, 301)
619
620 def test_invalid_path(self):
621 conn = self.https_connection(
622 "localhost",
623 19840,
624 key_file=self.client.key_path(),
625 cert_file=self.client.cert_path(),
626 )
627 conn.request("GET", "/v1/a..b")
628 response = conn.getresponse()
629 conn.close()
630 self.assertEqual(response.status, 406)
631
632 def test_server_cert(self):
633 rawsock = socket.create_connection(("localhost", 19840))
634 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
635 context.load_verify_locations(self.server.cert_path())
636 context.check_hostname = False
637 sock = context.wrap_socket(rawsock)
638
639 # We don't check the cipher itself, as it depends on the environment,
640 # but we should be using >= 128 bit secrets.
641 self.assertTrue(sock.cipher()[2] >= 128)
642
643 server_cert = ssl.DER_cert_to_PEM_cert(
644 sock.getpeercert(binary_form=True)
645 )
646 self.assertEqual(server_cert, self.server.cert())
647 sock.close()
648
649
650 class BrokenServerConfig(TestCase):
651 """Tests for a broken server config."""
652
653 def test_broken_client_certs(self):
654 self.server.new_key(
655 "k1",
656 allowed_clients=[self.client.cert()],
657 allowed_hosts=["localhost"],
658 )
659
660 # Corrupt the client certificate.
661 with open(self.server.path + "/data/k1/allowed_clients", "tr+") as cfd:
662 cfd.seek(30)
663 cfd.write("+/+BROKEN+/+")
664
665 self.assertClientFails(
666 "kxd://localhost/k1",
667 "Error loading certs|No allowed certificate found",
668 )
669
670 def test_missing_key(self):
671 self.server.new_key(
672 "k1",
673 allowed_clients=[self.client.cert()],
674 allowed_hosts=["localhost"],
675 )
676
677 os.unlink(self.server.path + "/data/k1/key")
678 self.assertClientFails("kxd://localhost/k1", "404 Not Found")
679
680
681 EMAIL_TO_FILE = textwrap.dedent(
682 """
683 # Comment.
684 [email protected]
685 [email protected]
686 """.strip()
687 )
688
689
690 class Hook(TestCase):
691 """Test cases for hook support."""
692
693 HOOK_SCRIPT_TMPL = textwrap.dedent(
694 """
695 #!/bin/sh
696 pwd > hook-output
697 env >> hook-output
698 exit {exit_code}
699 """.strip()
700 )
701
702 def write_hook(self, exit_code):
703 path = self.server.path + "/hook"
704 script = self.HOOK_SCRIPT_TMPL.format(exit_code=exit_code)
705
706 with open(path, "w") as hook:
707 hook.write(script)
708 os.chmod(path, 0o770)
709
710 def test_simple(self):
711 self.write_hook(exit_code=0)
712
713 # Normal successful case.
714 self.server.new_key(
715 "k1",
716 allowed_clients=[self.client.cert()],
717 allowed_hosts=["localhost"],
718 )
719 key = self.client.call(self.server.cert_path(), "kxd://localhost/k1")
720 self.assertEqual(key, self.server.keys["k1"])
721
722 hook_out = read_all(self.server.path + "/data/hook-output")
723 self.assertIn("CLIENT_CERT_SUBJECT=O=kxd-tests-client", hook_out)
724 self.assertNotIn("EMAIL_TO=", hook_out)
725
726 # Failure caused by the hook exiting with error.
727 self.write_hook(exit_code=1)
728 self.assertClientFails("kxd://localhost/k1", "Prevented by hook")
729
730 # Failure caused by the hook not being executable.
731 self.write_hook(exit_code=0)
732 os.chmod(self.server.path + "/hook", 0o660)
733 self.assertClientFails("kxd://localhost/k1", "Prevented by hook")
734
735 def test_email_to(self):
736 self.write_hook(exit_code=0)
737 self.server.new_key(
738 "k2",
739 allowed_clients=[self.client.cert()],
740 allowed_hosts=["localhost"],
741 email_to=EMAIL_TO_FILE,
742 )
743 key = self.client.call(self.server.cert_path(), "kxd://localhost/k2")
744 self.assertEqual(key, self.server.keys["k2"])
745
746 hook_out = read_all(self.server.path + "/data/hook-output")
747 self.assertIn("CLIENT_CERT_SUBJECT=O=kxd-tests-client", hook_out)
748 self.assertIn("[email protected] [email protected]", hook_out)
749
750
751 class Emails(TestCase):
752 """Tests for email notifications."""
753
754 def setUp(self):
755 self.smtp_addr, self.emails = receive_emails()
756 self.server = ServerConfig()
757 self.client = ClientConfig()
758 self.daemon = None
759 self.ca = None # pylint: disable=invalid-name
760 self.launch_server(self.server, smtp_addr=self.smtp_addr)
761
762 def test_emails(self):
763 self.server.new_key(
764 "k1",
765 allowed_clients=[self.client.cert()],
766 allowed_hosts=["localhost", self.server.host],
767 email_to=EMAIL_TO_FILE,
768 )
769 key = self.client.call(
770 self.server.cert_path(), "kxd://" + self.server.host + "/k1"
771 )
772 self.assertEqual(key, self.server.keys["k1"])
773 self.assertEqual(len(self.emails), 1)
774 self.assertEqual(self.emails[0][0], ["[email protected]", "[email protected]"])
775 self.assertRegex(
776 self.emails[0][1].decode().replace("\r\n", "\n"),
777 textwrap.dedent(
778 """\
779 Date: .*
780 From: Key Exchange Daemon <[email protected]>
781 To: [email protected], [email protected]
782 Subject: Access to key k1
783
784 Key: k1
785 Accessed by: .*
786 On: .*
787
788 Client certificate:
789 Signature: .*
790 Subject: O=kxd-tests-client
791
792 Authorizing chains:
793 .*
794 """
795 ),
796 )
797
798 def test_no_emails(self):
799 self.server.new_key(
800 "k2",
801 allowed_clients=[self.client.cert()],
802 allowed_hosts=["localhost", self.server.host],
803 )
804 key = self.client.call(
805 self.server.cert_path(), "kxd://" + self.server.host + "/k2"
806 )
807 self.assertEqual(key, self.server.keys["k2"])
808 # Note that we did not set up email_to, so we don't expect any emails.
809 self.assertEqual(self.emails, [])
810
811
812 if __name__ == "__main__":
813 unittest.main()