import http.client import json import threading import unittest from pathlib import Path from tempfile import TemporaryDirectory from leads import local_server as D class ServerCase(unittest.TestCase): """A scratch asset directory served on a free loopback port.""" def setUp(self): self._tmp = TemporaryDirectory() self.addCleanup(self._tmp.cleanup) self.static = Path(self._tmp.name) / "site" self.static.mkdir() (self.static / "index.html").write_text("

Owner portfolios

", encoding="utf-8") (self.static / "app.js").write_text("console.log(1)", encoding="utf-8") (self.static / "app.css").write_text("body{}", encoding="utf-8") (self.static / "leak.py").write_text("SECRET", encoding="utf-8") (Path(self._tmp.name) / "outside.txt").write_text("SECRET", encoding="utf-8") self.start() def start(self): self.app = D.Workspace(self.static) self.server = D.DashboardServer(("127.0.0.1", 0), self.app) self.port = self.server.server_address[1] self.thread = threading.Thread( target=lambda: self.server.serve_forever(poll_interval=0.02), daemon=True) self.thread.start() self.addCleanup(self.stop) def stop(self): self.server.shutdown() self.server.server_close() self.thread.join(timeout=5) def request(self, method, path, body=None, headers=None, host=None): conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=5) try: sent = {"Host": host if host is not None else f"127.0.0.1:{self.port}"} sent.update(headers or {}) conn.request(method, path, body=body, headers=sent) response = conn.getresponse() return response.status, dict(response.getheaders()), response.read() finally: conn.close() def note(self, *, token=None, origin=None, ctype="application/json", raw=None, host=None, payload=None): body = raw if raw is not None else json.dumps( payload or {"subject_id": "P-001", "body": "checked the deed"}).encode("utf-8") headers = { "Origin": origin if origin is not None else f"http://127.0.0.1:{self.port}", "X-CSRF-Token": token if token is not None else self.app.csrf_token, "Content-Type": ctype, "Content-Length": str(len(body)), } return self.request("POST", "/api/notes", body=body, headers=headers, host=host)[0] class TestPages(ServerCase): def test_the_index_page_is_served_with_a_locked_down_policy(self): status, headers, body = self.request("GET", "/") self.assertEqual(status, 200) self.assertIn(b"Owner portfolios", body) self.assertIn("connect-src 'self'", headers["Content-Security-Policy"]) self.assertIn("frame-ancestors 'none'", headers["Content-Security-Policy"]) self.assertEqual(headers["X-Content-Type-Options"], "nosniff") self.assertEqual(headers["X-Frame-Options"], "DENY") def test_own_assets_are_served(self): for path, expected in (("/static/app.js", "text/javascript"), ("/static/app.css", "text/css")): status, headers, _ = self.request("GET", path) self.assertEqual(status, 200, path) self.assertIn(expected, headers["Content-Type"]) def test_path_traversal_out_of_the_asset_directory_is_refused(self): for path in ("/static/../outside.txt", "/static/%2e%2e/outside.txt", "/static/%2e%2e%2foutside.txt", "/static/..%2foutside.txt", "/static/subdir/app.js", "/static/", "/static/....//outside.txt"): status, _, body = self.request("GET", path) self.assertEqual(status, 404, path) self.assertNotIn(b"SECRET", body) def test_a_python_file_next_to_the_assets_is_not_servable(self): status, _, body = self.request("GET", "/static/leak.py") self.assertEqual(status, 404) self.assertNotIn(b"SECRET", body) class TestOriginGuards(ServerCase): """Binding to loopback keeps packets local; it does not keep browsers honest.""" def test_a_rebinding_host_header_is_refused(self): for host in ("evil.example", "evil.example:80", f"attacker.test:{self.port}", "127.0.0.1.nip.io", ""): status, _, _ = self.request("GET", "/api/session", host=host) self.assertEqual(status, 403, host) def test_loopback_hosts_are_accepted(self): for host in (f"127.0.0.1:{self.port}", f"localhost:{self.port}", f"[::1]:{self.port}"): status, _, _ = self.request("GET", "/api/session", host=host) self.assertEqual(status, 200, host) def test_a_host_on_another_port_is_refused(self): status, _, _ = self.request("GET", "/api/session", host=f"127.0.0.1:{self.port + 1}") self.assertEqual(status, 403) def test_a_cross_site_fetch_is_refused_even_when_it_reaches_us(self): status, _, _ = self.request("GET", "/api/session", headers={"Sec-Fetch-Site": "cross-site"}) self.assertEqual(status, 403) def test_the_preflight_is_refused_and_grants_nothing(self): status, headers, _ = self.request("OPTIONS", "/api/notes") self.assertEqual(status, 403) self.assertFalse([h for h in headers if h.lower().startswith("access-control")]) def test_no_response_ever_grants_cors(self): for path in ("/", "/static/app.js", "/api/session", "/nope"): _, headers, _ = self.request("GET", path) self.assertFalse([h for h in headers if h.lower().startswith("access-control")], path) class TestWrites(ServerCase): def test_a_note_with_origin_and_token_is_stored(self): self.assertEqual(self.note(), 201) self.assertEqual([n["body"] for n in self.app.notes], ["checked the deed"]) def test_a_write_without_the_token_is_refused(self): self.assertEqual(self.note(token=""), 403) self.assertEqual(self.note(token="wrong-token"), 403) self.assertEqual(self.app.notes, []) def test_a_token_from_a_previous_process_is_refused(self): stale = self.app.csrf_token self.stop() self.start() self.assertEqual(self.note(token=stale), 403) def test_a_cross_origin_or_missing_origin_write_is_refused(self): for origin in ("", "http://evil.example", "https://127.0.0.1:%d" % self.port, "http://127.0.0.1:1", "null"): self.assertEqual(self.note(origin=origin), 403, origin) def test_a_rebinding_host_cannot_write_either(self): self.assertEqual(self.note(host="evil.example"), 403) def test_a_form_content_type_is_refused(self): for ctype in ("application/x-www-form-urlencoded", "text/plain", "multipart/form-data"): self.assertEqual(self.note(ctype=ctype), 415, ctype) def test_a_get_may_not_write(self): status, _, body = self.request("GET", "/api/notes") self.assertEqual(status, 405) self.assertIn("POST", json.loads(body)["error"]) def test_an_oversized_body_is_refused_before_it_is_read(self): big = json.dumps({"subject_id": "P-001", "body": "x" * (D.MAX_BODY_BYTES + 10)}).encode() self.assertEqual(self.note(raw=big), 413) def test_a_missing_length_is_refused(self): conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=5) self.addCleanup(conn.close) conn.putrequest("POST", "/api/notes", skip_accept_encoding=True) conn.putheader("Host", f"127.0.0.1:{self.port}") conn.putheader("Origin", f"http://127.0.0.1:{self.port}") conn.putheader("X-CSRF-Token", self.app.csrf_token) conn.putheader("Content-Type", "application/json") conn.endheaders() self.assertEqual(conn.getresponse().status, 411) def test_a_bad_body_is_a_readable_refusal(self): self.assertEqual(self.note(raw=b"{not json"), 400) self.assertEqual(self.note(raw=b"[1,2]"), 400) self.assertEqual(self.note(raw=b""), 400) self.assertEqual(self.note(payload={"subject_id": "P-001", "body": 42}), 422) self.assertEqual(self.note(payload={"subject_id": "P-001", "body": ""}), 422) self.assertEqual(self.app.notes, []) class TestHelpers(unittest.TestCase): def test_split_host_handles_ipv6_brackets(self): self.assertEqual(D.split_host("[::1]:8765"), ("::1", "8765")) self.assertEqual(D.split_host("[::1]x"), ("", "")) self.assertEqual(D.split_host("LOCALHOST:80"), ("localhost", "80"))