py190 lines8.5 KB
| 1 | import http.client |
| 2 | import json |
| 3 | import threading |
| 4 | import unittest |
| 5 | from pathlib import Path |
| 6 | from tempfile import TemporaryDirectory |
| 7 | |
| 8 | from leads import local_server as D |
| 9 | |
| 10 | |
| 11 | class ServerCase(unittest.TestCase): |
| 12 | """A scratch asset directory served on a free loopback port.""" |
| 13 | |
| 14 | def setUp(self): |
| 15 | self._tmp = TemporaryDirectory() |
| 16 | self.addCleanup(self._tmp.cleanup) |
| 17 | self.static = Path(self._tmp.name) / "site" |
| 18 | self.static.mkdir() |
| 19 | (self.static / "index.html").write_text("<h1>Owner portfolios</h1>", encoding="utf-8") |
| 20 | (self.static / "app.js").write_text("console.log(1)", encoding="utf-8") |
| 21 | (self.static / "app.css").write_text("body{}", encoding="utf-8") |
| 22 | (self.static / "leak.py").write_text("SECRET", encoding="utf-8") |
| 23 | (Path(self._tmp.name) / "outside.txt").write_text("SECRET", encoding="utf-8") |
| 24 | self.start() |
| 25 | |
| 26 | def start(self): |
| 27 | self.app = D.Workspace(self.static) |
| 28 | self.server = D.DashboardServer(("127.0.0.1", 0), self.app) |
| 29 | self.port = self.server.server_address[1] |
| 30 | self.thread = threading.Thread( |
| 31 | target=lambda: self.server.serve_forever(poll_interval=0.02), daemon=True) |
| 32 | self.thread.start() |
| 33 | self.addCleanup(self.stop) |
| 34 | |
| 35 | def stop(self): |
| 36 | self.server.shutdown() |
| 37 | self.server.server_close() |
| 38 | self.thread.join(timeout=5) |
| 39 | |
| 40 | def request(self, method, path, body=None, headers=None, host=None): |
| 41 | conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=5) |
| 42 | try: |
| 43 | sent = {"Host": host if host is not None else f"127.0.0.1:{self.port}"} |
| 44 | sent.update(headers or {}) |
| 45 | conn.request(method, path, body=body, headers=sent) |
| 46 | response = conn.getresponse() |
| 47 | return response.status, dict(response.getheaders()), response.read() |
| 48 | finally: |
| 49 | conn.close() |
| 50 | |
| 51 | def note(self, *, token=None, origin=None, ctype="application/json", raw=None, host=None, |
| 52 | payload=None): |
| 53 | body = raw if raw is not None else json.dumps( |
| 54 | payload or {"subject_id": "P-001", "body": "checked the deed"}).encode("utf-8") |
| 55 | headers = { |
| 56 | "Origin": origin if origin is not None else f"http://127.0.0.1:{self.port}", |
| 57 | "X-CSRF-Token": token if token is not None else self.app.csrf_token, |
| 58 | "Content-Type": ctype, |
| 59 | "Content-Length": str(len(body)), |
| 60 | } |
| 61 | return self.request("POST", "/api/notes", body=body, headers=headers, host=host)[0] |
| 62 | |
| 63 | |
| 64 | class TestPages(ServerCase): |
| 65 | def test_the_index_page_is_served_with_a_locked_down_policy(self): |
| 66 | status, headers, body = self.request("GET", "/") |
| 67 | self.assertEqual(status, 200) |
| 68 | self.assertIn(b"Owner portfolios", body) |
| 69 | self.assertIn("connect-src 'self'", headers["Content-Security-Policy"]) |
| 70 | self.assertIn("frame-ancestors 'none'", headers["Content-Security-Policy"]) |
| 71 | self.assertEqual(headers["X-Content-Type-Options"], "nosniff") |
| 72 | self.assertEqual(headers["X-Frame-Options"], "DENY") |
| 73 | |
| 74 | def test_own_assets_are_served(self): |
| 75 | for path, expected in (("/static/app.js", "text/javascript"), |
| 76 | ("/static/app.css", "text/css")): |
| 77 | status, headers, _ = self.request("GET", path) |
| 78 | self.assertEqual(status, 200, path) |
| 79 | self.assertIn(expected, headers["Content-Type"]) |
| 80 | |
| 81 | def test_path_traversal_out_of_the_asset_directory_is_refused(self): |
| 82 | for path in ("/static/../outside.txt", "/static/%2e%2e/outside.txt", |
| 83 | "/static/%2e%2e%2foutside.txt", "/static/..%2foutside.txt", |
| 84 | "/static/subdir/app.js", "/static/", "/static/....//outside.txt"): |
| 85 | status, _, body = self.request("GET", path) |
| 86 | self.assertEqual(status, 404, path) |
| 87 | self.assertNotIn(b"SECRET", body) |
| 88 | |
| 89 | def test_a_python_file_next_to_the_assets_is_not_servable(self): |
| 90 | status, _, body = self.request("GET", "/static/leak.py") |
| 91 | self.assertEqual(status, 404) |
| 92 | self.assertNotIn(b"SECRET", body) |
| 93 | |
| 94 | |
| 95 | class TestOriginGuards(ServerCase): |
| 96 | """Binding to loopback keeps packets local; it does not keep browsers honest.""" |
| 97 | |
| 98 | def test_a_rebinding_host_header_is_refused(self): |
| 99 | for host in ("evil.example", "evil.example:80", f"attacker.test:{self.port}", |
| 100 | "127.0.0.1.nip.io", ""): |
| 101 | status, _, _ = self.request("GET", "/api/session", host=host) |
| 102 | self.assertEqual(status, 403, host) |
| 103 | |
| 104 | def test_loopback_hosts_are_accepted(self): |
| 105 | for host in (f"127.0.0.1:{self.port}", f"localhost:{self.port}", f"[::1]:{self.port}"): |
| 106 | status, _, _ = self.request("GET", "/api/session", host=host) |
| 107 | self.assertEqual(status, 200, host) |
| 108 | |
| 109 | def test_a_host_on_another_port_is_refused(self): |
| 110 | status, _, _ = self.request("GET", "/api/session", host=f"127.0.0.1:{self.port + 1}") |
| 111 | self.assertEqual(status, 403) |
| 112 | |
| 113 | def test_a_cross_site_fetch_is_refused_even_when_it_reaches_us(self): |
| 114 | status, _, _ = self.request("GET", "/api/session", |
| 115 | headers={"Sec-Fetch-Site": "cross-site"}) |
| 116 | self.assertEqual(status, 403) |
| 117 | |
| 118 | def test_the_preflight_is_refused_and_grants_nothing(self): |
| 119 | status, headers, _ = self.request("OPTIONS", "/api/notes") |
| 120 | self.assertEqual(status, 403) |
| 121 | self.assertFalse([h for h in headers if h.lower().startswith("access-control")]) |
| 122 | |
| 123 | def test_no_response_ever_grants_cors(self): |
| 124 | for path in ("/", "/static/app.js", "/api/session", "/nope"): |
| 125 | _, headers, _ = self.request("GET", path) |
| 126 | self.assertFalse([h for h in headers if h.lower().startswith("access-control")], path) |
| 127 | |
| 128 | |
| 129 | class TestWrites(ServerCase): |
| 130 | def test_a_note_with_origin_and_token_is_stored(self): |
| 131 | self.assertEqual(self.note(), 201) |
| 132 | self.assertEqual([n["body"] for n in self.app.notes], ["checked the deed"]) |
| 133 | |
| 134 | def test_a_write_without_the_token_is_refused(self): |
| 135 | self.assertEqual(self.note(token=""), 403) |
| 136 | self.assertEqual(self.note(token="wrong-token"), 403) |
| 137 | self.assertEqual(self.app.notes, []) |
| 138 | |
| 139 | def test_a_token_from_a_previous_process_is_refused(self): |
| 140 | stale = self.app.csrf_token |
| 141 | self.stop() |
| 142 | self.start() |
| 143 | self.assertEqual(self.note(token=stale), 403) |
| 144 | |
| 145 | def test_a_cross_origin_or_missing_origin_write_is_refused(self): |
| 146 | for origin in ("", "http://evil.example", "https://127.0.0.1:%d" % self.port, |
| 147 | "http://127.0.0.1:1", "null"): |
| 148 | self.assertEqual(self.note(origin=origin), 403, origin) |
| 149 | |
| 150 | def test_a_rebinding_host_cannot_write_either(self): |
| 151 | self.assertEqual(self.note(host="evil.example"), 403) |
| 152 | |
| 153 | def test_a_form_content_type_is_refused(self): |
| 154 | for ctype in ("application/x-www-form-urlencoded", "text/plain", "multipart/form-data"): |
| 155 | self.assertEqual(self.note(ctype=ctype), 415, ctype) |
| 156 | |
| 157 | def test_a_get_may_not_write(self): |
| 158 | status, _, body = self.request("GET", "/api/notes") |
| 159 | self.assertEqual(status, 405) |
| 160 | self.assertIn("POST", json.loads(body)["error"]) |
| 161 | |
| 162 | def test_an_oversized_body_is_refused_before_it_is_read(self): |
| 163 | big = json.dumps({"subject_id": "P-001", "body": "x" * (D.MAX_BODY_BYTES + 10)}).encode() |
| 164 | self.assertEqual(self.note(raw=big), 413) |
| 165 | |
| 166 | def test_a_missing_length_is_refused(self): |
| 167 | conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=5) |
| 168 | self.addCleanup(conn.close) |
| 169 | conn.putrequest("POST", "/api/notes", skip_accept_encoding=True) |
| 170 | conn.putheader("Host", f"127.0.0.1:{self.port}") |
| 171 | conn.putheader("Origin", f"http://127.0.0.1:{self.port}") |
| 172 | conn.putheader("X-CSRF-Token", self.app.csrf_token) |
| 173 | conn.putheader("Content-Type", "application/json") |
| 174 | conn.endheaders() |
| 175 | self.assertEqual(conn.getresponse().status, 411) |
| 176 | |
| 177 | def test_a_bad_body_is_a_readable_refusal(self): |
| 178 | self.assertEqual(self.note(raw=b"{not json"), 400) |
| 179 | self.assertEqual(self.note(raw=b"[1,2]"), 400) |
| 180 | self.assertEqual(self.note(raw=b""), 400) |
| 181 | self.assertEqual(self.note(payload={"subject_id": "P-001", "body": 42}), 422) |
| 182 | self.assertEqual(self.note(payload={"subject_id": "P-001", "body": ""}), 422) |
| 183 | self.assertEqual(self.app.notes, []) |
| 184 | |
| 185 | |
| 186 | class TestHelpers(unittest.TestCase): |
| 187 | def test_split_host_handles_ipv6_brackets(self): |
| 188 | self.assertEqual(D.split_host("[::1]:8765"), ("::1", "8765")) |
| 189 | self.assertEqual(D.split_host("[::1]x"), ("", "")) |
| 190 | self.assertEqual(D.split_host("LOCALHOST:80"), ("localhost", "80")) |