askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
test_site_cookies.py · 6.1 KB · 152 lines
| 1 | """Cookies across the object boundary: what goes in, and what comes back. |
| 2 | |
| 3 | A page object with no cookies cannot recognise a returning visitor at all |
| 4 | -- that is a whole class of feature (baskets, preferences, anything |
| 5 | remembered) that simply does not work. So cookies must cross. The |
| 6 | interesting question is which ones, and the answer is deliberately |
| 7 | lopsided: every app cookie goes IN, the identity session never does, and |
| 8 | exactly one header comes back OUT. |
| 9 | |
| 10 | None of this is testable in-process: `_cookies` is put on the payload by |
| 11 | the server's routing layer and `set_cookie` is read by its response |
| 12 | layer, so a test that calls the object directly proves nothing about |
| 13 | either. These drive the ASGI app, same as the webhook tests. |
| 14 | """ |
| 15 | |
| 16 | import asyncio |
| 17 | import json |
| 18 | |
| 19 | import pytest |
| 20 | |
| 21 | import object_server |
| 22 | |
| 23 | |
| 24 | @pytest.fixture() |
| 25 | def env(tmp_path, monkeypatch): |
| 26 | objects_dir = tmp_path / "objects" |
| 27 | (objects_dir / "site").mkdir(parents=True) |
| 28 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_dir)) |
| 29 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data")) |
| 30 | # Site routing is the surface under test: `/probe` -> `site_probe` by |
| 31 | # convention, no site_routes record needed. |
| 32 | monkeypatch.setenv("DBBASIC_ENABLE_SITE_ROUTES", "true") |
| 33 | return objects_dir |
| 34 | |
| 35 | |
| 36 | def stage(objects_dir, name, source): |
| 37 | (objects_dir / "site" / f"{name}.py").write_text(source) |
| 38 | |
| 39 | |
| 40 | def call(path, *, method="GET", headers=None): |
| 41 | sent = {} |
| 42 | |
| 43 | async def run(): |
| 44 | scope = { |
| 45 | "type": "http", "method": method, "path": path, "query_string": b"", |
| 46 | "headers": [(k.lower().encode(), v.encode()) |
| 47 | for k, v in (headers or {}).items()], |
| 48 | } |
| 49 | received = {"done": False} |
| 50 | |
| 51 | async def receive(): |
| 52 | if received["done"]: |
| 53 | return {"type": "http.disconnect"} |
| 54 | received["done"] = True |
| 55 | return {"type": "http.request", "body": b"", "more_body": False} |
| 56 | |
| 57 | async def send(message): |
| 58 | if message["type"] == "http.response.start": |
| 59 | sent["status"] = message["status"] |
| 60 | sent["headers"] = [(k.decode("latin-1"), v.decode("latin-1")) |
| 61 | for k, v in message["headers"]] |
| 62 | elif message["type"] == "http.response.body": |
| 63 | sent.setdefault("body", b"") |
| 64 | sent["body"] += message.get("body", b"") |
| 65 | |
| 66 | await object_server.app(scope, receive, send) |
| 67 | |
| 68 | asyncio.run(run()) |
| 69 | return sent |
| 70 | |
| 71 | |
| 72 | def header_values(sent, name): |
| 73 | return [value for key, value in sent.get("headers", []) if key.lower() == name] |
| 74 | |
| 75 | |
| 76 | def test_app_cookies_reach_the_object_and_the_session_cookie_does_not(env): |
| 77 | """The whole point, and the whole limit, in one request. |
| 78 | |
| 79 | Without the first half every visit mints a new basket, because the |
| 80 | `cart` cookie the browser sends never reaches the page. Without the |
| 81 | second half every public page any package installs becomes a place a |
| 82 | signed-in user's session can be read and sent somewhere else -- the |
| 83 | session cookie is not data, it IS the authentication, and it is the |
| 84 | same reasoning that keeps `cookie` out of the webhook safelist. |
| 85 | """ |
| 86 | stage(env, "probe", |
| 87 | "import json\n" |
| 88 | "def GET(request):\n" |
| 89 | " return {'status': 200, 'content_type': 'application/json',\n" |
| 90 | " 'body': json.dumps(request.get('_cookies'))}\n") |
| 91 | sent = call("/probe", headers={ |
| 92 | "cookie": "cart=abc; dbbasic_session=SECRET", |
| 93 | }) |
| 94 | assert sent["status"] == 200 |
| 95 | assert json.loads(sent["body"]) == {"cart": "abc"} |
| 96 | assert "SECRET" not in sent["body"].decode("utf-8") |
| 97 | |
| 98 | |
| 99 | def test_an_object_can_set_one_cookie_on_the_response(env): |
| 100 | """A basket token that is minted but never sent back is no token at |
| 101 | all: the shopper gets a new empty basket on every page.""" |
| 102 | stage(env, "setter", |
| 103 | "def GET(request):\n" |
| 104 | " return {'status': 200, 'content_type': 'text/html',\n" |
| 105 | " 'body': 'ok',\n" |
| 106 | " 'set_cookie': 'cart=xyz; Path=/; HttpOnly; SameSite=Lax'}\n") |
| 107 | sent = call("/setter") |
| 108 | assert sent["status"] == 200 |
| 109 | assert header_values(sent, "set-cookie") == [ |
| 110 | "cart=xyz; Path=/; HttpOnly; SameSite=Lax"] |
| 111 | |
| 112 | |
| 113 | def test_a_cookie_carrying_a_newline_is_not_emitted(env): |
| 114 | """Response splitting: a newline in the value would let an object append |
| 115 | headers of its own -- a redirect, a CORS grant -- to the wire. Dropped, |
| 116 | not raised: the page still renders, it just gets no cookie.""" |
| 117 | stage(env, "injector", |
| 118 | "def GET(request):\n" |
| 119 | " return {'status': 200, 'content_type': 'text/html',\n" |
| 120 | " 'body': 'ok',\n" |
| 121 | " 'set_cookie': 'a=b\\r\\nlocation: http://evil.test/'}\n") |
| 122 | sent = call("/injector") |
| 123 | assert sent["status"] == 200 |
| 124 | assert header_values(sent, "set-cookie") == [] |
| 125 | assert header_values(sent, "location") == [] |
| 126 | |
| 127 | |
| 128 | def test_no_cookie_header_is_an_empty_dict_not_a_missing_key(env): |
| 129 | """First-ever visitor. `_cookies` is always present so an object can |
| 130 | read it without guarding, and always a dict so `.get` is safe.""" |
| 131 | stage(env, "probe", |
| 132 | "import json\n" |
| 133 | "def GET(request):\n" |
| 134 | " return {'status': 200, 'content_type': 'application/json',\n" |
| 135 | " 'body': json.dumps(request.get('_cookies'))}\n") |
| 136 | sent = call("/probe") |
| 137 | assert json.loads(sent["body"]) == {} |
| 138 | |
| 139 | |
| 140 | def test_objects_cannot_set_headers_other_than_the_cookie(env): |
| 141 | """A safelist of ONE. `location`, CORS grants and cache directives are |
| 142 | the SERVER's security posture; a general headers passthrough would hand |
| 143 | every installed package the ability to rewrite it.""" |
| 144 | stage(env, "greedy", |
| 145 | "def GET(request):\n" |
| 146 | " return {'status': 200, 'content_type': 'text/html',\n" |
| 147 | " 'body': 'ok',\n" |
| 148 | " 'headers': {'location': 'http://evil.test/',\n" |
| 149 | " 'access-control-allow-origin': '*'}}\n") |
| 150 | sent = call("/greedy") |
| 151 | assert header_values(sent, "location") == [] |
| 152 | assert header_values(sent, "access-control-allow-origin") == [] |