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_webhook_endpoint.py · 7.3 KB · 179 lines
| 1 | """POST /webhooks/{name}: raw bytes for signature verification, and the |
| 2 | safelist that keeps a webhook object from becoming a credential tap. |
| 3 | |
| 4 | Provider signatures are HMACs over the exact bytes on the wire; every |
| 5 | other route parses the body before an object runs. This endpoint is the |
| 6 | one deliberate exception, and because it is unauthenticated BY NATURE |
| 7 | (the caller is a payment processor, not a user), the tests here are |
| 8 | mostly about what it refuses to do. |
| 9 | """ |
| 10 | |
| 11 | import asyncio |
| 12 | import json |
| 13 | import pathlib |
| 14 | |
| 15 | import pytest |
| 16 | |
| 17 | import object_credentials |
| 18 | import object_identity |
| 19 | import object_server |
| 20 | |
| 21 | |
| 22 | @pytest.fixture() |
| 23 | def env(tmp_path, monkeypatch): |
| 24 | objects_dir = tmp_path / "objects" |
| 25 | (objects_dir / "webhook").mkdir(parents=True) |
| 26 | (objects_dir / "webhook" / "echo.py").write_text( |
| 27 | "def POST(request):\n" |
| 28 | " return {'ok': True,\n" |
| 29 | " 'raw': request.get('_raw_body'),\n" |
| 30 | " 'headers': request.get('_headers'),\n" |
| 31 | " 'query': {k: v for k, v in request.items()\n" |
| 32 | " if not k.startswith('_') and k not in ('ok',)}}\n") |
| 33 | data_dir = tmp_path / "data" |
| 34 | (data_dir / "permissions").mkdir(parents=True) |
| 35 | (data_dir / "permissions" / "policy.json").write_text(json.dumps({ |
| 36 | "access_mode": "role_based", |
| 37 | "rules": [{"effect": "allow", "principal": "public", "actions": ["execute"], |
| 38 | "object_id": "webhook_echo", |
| 39 | "reason": "test webhook"}], |
| 40 | })) |
| 41 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_dir)) |
| 42 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 43 | monkeypatch.setenv("DBBASIC_ENABLE_PERMISSION_ENFORCEMENT", "true") |
| 44 | monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", "test-admin-token") |
| 45 | # Enforcement stays in SHADOW MODE unless readiness passes, which |
| 46 | # requires a non-admin identity path -- the deliberate lockout guard |
| 47 | # that stops a half-configured server from locking its owner out. |
| 48 | # Password login plus one active user satisfies it, same as the e2e |
| 49 | # fixture; without this, the no-permission test below would pass |
| 50 | # vacuously in shadow mode and prove nothing. |
| 51 | monkeypatch.setenv("DBBASIC_ENABLE_PASSWORD_LOGIN", "true") |
| 52 | object_identity.create_user( |
| 53 | {"user_id": "wh-user", "email": "wh@test.local"}, base_dir=data_dir) |
| 54 | object_credentials.set_password( |
| 55 | "wh-user", "a-long-enough-password-123", base_dir=data_dir) |
| 56 | return objects_dir, data_dir |
| 57 | |
| 58 | |
| 59 | def call(path, *, method="POST", body=b"", headers=None): |
| 60 | sent = {} |
| 61 | |
| 62 | async def run(): |
| 63 | scope = { |
| 64 | "type": "http", "method": method, "path": path, "query_string": b"", |
| 65 | "headers": [(k.lower().encode(), v.encode()) |
| 66 | for k, v in (headers or {}).items()], |
| 67 | } |
| 68 | received = {"done": False} |
| 69 | |
| 70 | async def receive(): |
| 71 | if received["done"]: |
| 72 | return {"type": "http.disconnect"} |
| 73 | received["done"] = True |
| 74 | return {"type": "http.request", "body": body, "more_body": False} |
| 75 | |
| 76 | async def send(message): |
| 77 | if message["type"] == "http.response.start": |
| 78 | sent["status"] = message["status"] |
| 79 | elif message["type"] == "http.response.body": |
| 80 | sent.setdefault("body", b"") |
| 81 | sent["body"] += message.get("body", b"") |
| 82 | |
| 83 | await object_server.app(scope, receive, send) |
| 84 | |
| 85 | asyncio.run(run()) |
| 86 | payload = {} |
| 87 | try: |
| 88 | payload = json.loads(sent.get("body", b"{}") or b"{}") |
| 89 | except ValueError: |
| 90 | pass |
| 91 | return sent.get("status"), payload |
| 92 | |
| 93 | |
| 94 | def test_raw_bytes_reach_the_object_unparsed(env): |
| 95 | # NOT valid JSON on purpose: any parse step would have destroyed it. |
| 96 | raw = b'{"amount": 100, "spacing-matters": true} \n trailing' |
| 97 | status, payload = call("/webhooks/echo", body=raw, |
| 98 | headers={"stripe-signature": "t=1,v1=abc", |
| 99 | "content-type": "application/json"}) |
| 100 | assert status == 200 |
| 101 | assert payload["raw"] == raw.decode() # byte-exact, whitespace intact |
| 102 | assert payload["headers"]["stripe-signature"] == "t=1,v1=abc" |
| 103 | |
| 104 | |
| 105 | def test_secret_bearing_headers_never_reach_the_object(env): |
| 106 | status, payload = call("/webhooks/echo", body=b"x", headers={ |
| 107 | "authorization": "Bearer super-secret-user-token", |
| 108 | "cookie": "dbbasic_session=super-secret-session", |
| 109 | "stripe-signature": "t=1,v1=abc", |
| 110 | }) |
| 111 | assert status == 200 |
| 112 | assert "authorization" not in payload["headers"] |
| 113 | assert "cookie" not in payload["headers"] |
| 114 | assert "super-secret" not in json.dumps(payload) |
| 115 | |
| 116 | |
| 117 | def test_unknown_webhook_is_404_not_a_probe_oracle(env): |
| 118 | status, payload = call("/webhooks/nonexistent", body=b"x") |
| 119 | assert status == 404 |
| 120 | status2, _ = call("/webhooks/../../etc/passwd", body=b"x") |
| 121 | assert status2 == 404 |
| 122 | status3, _ = call("/webhooks/", body=b"x") |
| 123 | assert status3 in (404, 405) |
| 124 | |
| 125 | |
| 126 | def test_get_is_refused(env): |
| 127 | status, _ = call("/webhooks/echo", method="GET") |
| 128 | assert status == 405 |
| 129 | |
| 130 | |
| 131 | def test_no_permission_rule_means_no_execution(env, tmp_path): |
| 132 | objects_dir, data_dir = env |
| 133 | (objects_dir / "webhook" / "locked.py").write_text( |
| 134 | "def POST(request):\n return {'ok': True}\n") |
| 135 | status, _ = call("/webhooks/locked", body=b"x") |
| 136 | # The object exists but nobody granted public execute: refused. A |
| 137 | # webhook endpoint must be an explicit opt-in per hook, never a blanket |
| 138 | # exposure of every webhook_* object anyone installs. |
| 139 | assert status in (401, 403) |
| 140 | |
| 141 | |
| 142 | def test_object_status_reaches_the_status_line(env): |
| 143 | """An object answering {"status": 4xx} must produce that HTTP status. |
| 144 | |
| 145 | This was broken: only content_type responses honored `status`, so a |
| 146 | webhook's signature failure -- and every action's refusal -- was |
| 147 | delivered as HTTP 200 with the rejection hidden in the body. Providers |
| 148 | retry on status alone, so a forgery answered 200 is a forgery |
| 149 | permanently accepted. |
| 150 | """ |
| 151 | objects_dir, _ = env |
| 152 | (objects_dir / "webhook" / "refuser.py").write_text( |
| 153 | "def POST(request):\n" |
| 154 | " return {'status': 400, 'error': 'Signature verification failed'}\n") |
| 155 | (objects_dir.parent / "data" / "permissions" / "policy.json").write_text(json.dumps({ |
| 156 | "access_mode": "role_based", |
| 157 | "rules": [{"effect": "allow", "principal": "public", "actions": ["execute"], |
| 158 | "object_id": "webhook_refuser", "reason": "test"}], |
| 159 | })) |
| 160 | status, payload = call("/webhooks/refuser", body=b"{}") |
| 161 | assert status == 400 |
| 162 | assert payload["error"] == "Signature verification failed" |
| 163 | |
| 164 | |
| 165 | def test_a_records_own_status_field_is_not_a_status_line(env): |
| 166 | """Collections carry a `status` of their own ("active", "posted"), and |
| 167 | an object echoing a record back must not have it read as HTTP.""" |
| 168 | objects_dir, _ = env |
| 169 | (objects_dir / "webhook" / "record.py").write_text( |
| 170 | "def POST(request):\n" |
| 171 | " return {'ok': True, 'record': {'id': 'x'}, 'status': 'active'}\n") |
| 172 | (objects_dir.parent / "data" / "permissions" / "policy.json").write_text(json.dumps({ |
| 173 | "access_mode": "role_based", |
| 174 | "rules": [{"effect": "allow", "principal": "public", "actions": ["execute"], |
| 175 | "object_id": "webhook_record", "reason": "test"}], |
| 176 | })) |
| 177 | status, payload = call("/webhooks/record", body=b"{}") |
| 178 | assert status == 200 |
| 179 | assert payload["status"] == "active" |