diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 4c90d7a..237e8fb 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -15,6 +15,22 @@ jobs: test: runs-on: ubuntu-latest timeout-minutes: 20 + # A real PostgreSQL for PostgresStore, the blueprint suite and the e2e suite. The tests FAIL (not skip) + # when it is missing under CI=true, which GitHub Actions sets. + services: + postgres: + image: postgres:16 + env: + POSTGRES_PASSWORD: postgres + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U postgres" + --health-interval 5s + --health-timeout 5s + --health-retries 10 + env: + BUG_REPORT_PG_DSN: postgresql://postgres:postgres@localhost:5432/postgres steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 diff --git a/CHANGELOG.md b/CHANGELOG.md index 42799c7..d2b53e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,44 @@ All notable changes to this monorepo. +## backends v3.0.0 โ€” 2026-11-14 (`bug-report-py` 3.0.0) + +One central store for every app's reports (design: `CENTRAL-STORE.md`). The Python library only; nothing is +deployed by this change. Contract v3 adds to v2 and removes nothing: a v2 record, and a v2 client, work as before. + +- **Contract v3** (`report-contract.json`, `contract.py`, `types.py`, `types.ts`, `openapi.yaml`): `product`, + stored `kind`, `area`, `priority` (`now|next|later`), `owner`, `parentId`, `duplicateOf` and `votes` on every + summary; `appProducts` maps app to product (stoppages, fleet, report: PikPak; placements: Placement; + sealviewer: Seal; leaphq: Internal). A v2 record reads back with the new fields null and `votes` 0. +- **PATCH takes the triage fields**, with or without a status change (`status` is optional when one is sent). + Each change writes an audit row whose note says what changed. `duplicateOf` also declines the report with the + note `duplicate of `. `parentId` may not make a cycle. +- **Votes:** `POST /bugs/{id}/vote` (any signed-in caller, one vote per person) and `DELETE`. +- **List filters:** `app`, `kind`, `area`, `priority`. +- **`bug_report.pg.PostgresStore`** (extra: `bug-report-py[postgres]`, psycopg 3), ported from the fleet + dashboard's store: `reports`, `report_audit`, `report_votes`; `record` jsonb is what `FilesystemStore` writes; + `ensure_schema()`; the constructor takes a connection factory (so a service can pass an Entra-token password). + The `Store` protocol gains `update_fields`, `add_vote`, `remove_vote`, `vote_counts`, `list_votes` and the + filter arguments to `list_bugs`; both file stores, `InMemoryStore` and `PostgresStore` implement them. +- **`import_reports(src, dst, app)`**: one run, at cutover, with the app's writes frozen. Keeps ids, audit, screenshots + and votes; `app` must be in `APP_PRODUCTS`. A second run copies nothing; if a report already there differs from the + source (status, triage fields, votes, audit length and last row) it raises `ImportMismatch` with the ids and writes nothing. +- **`create_proxy_blueprint(central_url, app, token_provider, person_provider)`**: an app's `/api/bugs` that + forwards every route to the central service as the app's own identity, naming the signed-in person in headers. + Refuses `..` path segments; its 502 bodies carry no exception text. +- **`TrustedCallers` / `trusted_caller(request, trusted_apps, verify_token)`**: the service side, with NO person path: + every request needs a bearer token (401 without; 403 from an untrusted app); the actor headers are believed only behind a + verified token from a trusted app. `verify_token` (the service's, PyJWT) must check signature, issuer, audience and expiry. +- **`bug_report.identity`**: `trusted_person` / `trusted_identity` moved in from the apps, for an app's own proxy; configured by + arguments (`trust_easyauth`, `loopback_headers`, default off) rather than environment reads. +- **Concurrent PATCHes** of different fields of one report both land: `Store.update_bug` is one atomic step + (`PostgresStore`: `SELECT ... FOR UPDATE` then one UPDATE; `FilesystemStore`: a lock per report). +- **`create_blueprint`** gains `app_stamp` and `guard`; the POST response carries `app`. +- **Node backend** (`backend-node`): the same v3 fields, PATCH triage, filters and votes, minimal (file and + in-memory stores; the Azure Tables store does not keep them yet and answers 501). +- **Tests:** a real PostgreSQL (`BUG_REPORT_PG_DSN`, else a throwaway Homebrew one) for the store, the + blueprint suite and the e2e suite; CI adds a `postgres:16` service and a missing Postgres fails there. + ## Ownership โ€” 2026-11-04 - The repository moved from `kmoy007/bug-report-widget` to `LeapAutomation/bug-report-widget`; GitHub diff --git a/docs/CENTRAL-STORE.md b/docs/CENTRAL-STORE.md index b1576eb..4ca3d24 100644 --- a/docs/CENTRAL-STORE.md +++ b/docs/CENTRAL-STORE.md @@ -1,7 +1,7 @@ # One store for every app's bug and feature reports **Status:** design, not built. **Decided (Ken, 2026-11-14):** one central store on Postgres (option A), not federation. -**Assumed, for Ken to confirm in review:** +**Still assumed (not yet confirmed by Ken):** - Product โ†’ App โ†’ Area as the levels, with products PikPak, Seal, Placement and Internal; - feature requests in the same store as bugs, with votes as a field. @@ -20,23 +20,23 @@ The survey behind this is in the hand-over note "bug-feature-reports-across-apps ``` browser ๐Ÿž / BugQueue โ”€โ”€โ–บ app's /api/bugs โ”€โ”€(proxy)โ”€โ”€โ–บ leaphq-reports /api/bugs โ”€โ”€โ–บ Postgres `reports` db -agents, MCP tools โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ leaphq-reports (leaphq-pg) -LeapHQ Review โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ leaphq-reports (one source, not five) +agents, MCP tools โ”€โ”€(through an app, or as their own app identity)โ”€โ”€โ–บ leaphq-reports (leaphq-pg) +LeapHQ Review โ”€โ”€(LeapHQ's own identity, a token)โ”€โ”€โ–บ leaphq-reports (one source, not five) ``` - **The central service, `leaphq-reports`.** - It is the `bug-report-py` blueprint plus a new `PostgresStore`, and nothing else app-specific. - - It is its own Container App with internal ingress, reached by people through the gateway at `/reports/`. + - It is its own Container App with internal ingress and **no gateway route**: nobody reaches it directly. Every caller is an app, with a token (Ken, 2026-11-14). - It is the only place reports are stored, emails are sent and triage rights are checked: one `BUG_ADMINS`, and one sending identity (`leaphq-bug-notify`). - **The apps keep their URL.** Each app's `/api/bugs` becomes `create_proxy_blueprint(central_url, app="placements")` from the library. - It forwards every route (POST, list, detail, PATCH and screenshot) with its body unchanged. - The widget, BugQueue and every page that links to a report keep working, with no front-end change. - The app stamps `app`; the caller cannot set it. -- **Who is asking.** The app calls the service as **its own managed identity** (an Entra token). - - It passes the signed-in person, from its own `trusted_person()`, in two headers. - - The service believes those headers only from identities on its `TRUSTED_APPS` list (client id โ†’ app name), so the app name comes from the token, not the request. - - A request through the gateway carries the gateway's principal as today. - - This replaces the near-identical `trusted_identity()` / `trusted_person()` / `is_admin()` copies in SV, PIV, seal and the fleet dashboard. `trusted_person()` moves into the library once, for the proxy to use. +- **Who is asking.** Every request carries a token: the calling app's **own managed identity** (an Entra token). There is no person path on the service, so a request with no token is 401 and the service never reads `X-Ms-Client-Principal` or Tailscale headers. + - The app passes the signed-in person, from its own `trusted_person()`, in two headers (`X-Leap-Actor-Email`, `X-Leap-Actor-Name`). + - The service verifies the token with **PyJWT** (signature, issuer, audience and expiry: a decode-only check would make every trusted client id spoofable), then believes those headers only from identities on its `TRUSTED_APPS` list (client id โ†’ app name). The app name comes from the token, not the request. + - **LeapHQ calls as its own identity** like every other app (it is `leaphq` in `TRUSTED_APPS`), not through a gateway route. + - This replaces the near-identical `trusted_identity()` / `trusted_person()` / `is_admin()` copies in SV, PIV, seal and the fleet dashboard. `trusted_person()` moves into the library once, for each app's proxy to use behind its own gateway. - **Seal laptops.** Their outbox forwards to the seal viewer's proxy exactly as it does today, so nothing changes on a station. ## Store @@ -83,7 +83,7 @@ Statuses stay at four. LeapHQ's feature-request `shipped` folds into `resolved`. ## Migration (one app at a time; order: seal, PIV, SV, report, fleet, LeapHQ) For each app: -1. `tools/import_reports.py ` copies its store into `reports`, keeping ids, audit rows and screenshots. It is idempotent, and a re-run copies only what is new. +1. `tools/import_reports.py ` copies its store into `reports`, keeping ids, audit rows, screenshots and votes. **It is one run, at cutover, with the app's writes frozen.** A second run copies nothing: it compares each report already there (status, triage fields, votes, audit length and last audit row) and, if anything differs, raises with the ids that differ and changes nothing. 2. It checks the counts per status match, and that every imported report reads back equal. 3. Deploy the app with the proxy. Its old store is kept read-only for 30 days, then deleted (Ken confirms each deletion). 4. LeapHQ drops that app from its federation list; when the last one goes, so does `plugin-bugs.js`. @@ -94,7 +94,7 @@ LeapHQ goes last. Its Azure Tables rows (bugs and feature requests) import the s - Create the managed identity `leaphq-reports` and the database `reports` with that identity as its owner. A one-off script, in the style of `pg-owner-step.sh`, will be written for him to run. - Give `leaphq-reports` the ACS sending role (or attach `leaphq-bug-notify` to it). -- Add `/reports/` to the gateway's routes and apply the excluded paths. +- Register each app's managed identity (and LeapHQ's) as a trusted client id in `TRUSTED_APPS`, and give the service its Entra audience and issuer. There is no gateway route to add. - Approve each old store's deletion after its 30 days. ## Not doing diff --git a/e2e/README.md b/e2e/README.md index 92224e1..b5d64b2 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -6,7 +6,7 @@ If the two backends ever drift (one returns a different status code, one orders ## What runs -Each test runs twice โ€” once against the Python backend, once against the Node backend. The fixture boots both as subprocesses on random ports and yields their base URLs. +Each test runs three times โ€” against the Python backend on files, the Python backend on PostgreSQL, and the Node backend. The fixture boots each as a subprocess on a random port and yields its base URL. The Postgres one needs a real server (`BUG_REPORT_PG_DSN`, or Homebrew's `postgresql@16`, started for you); without one it skips, and under `CI=true` it fails. `test_v3.py` covers contract v3 (triage fields, duplicates, votes, filters) on the same three, with servers that take the caller and app from test headers. ```bash cd e2e diff --git a/e2e/conftest.py b/e2e/conftest.py index 1f720d0..c3416e8 100644 --- a/e2e/conftest.py +++ b/e2e/conftest.py @@ -21,6 +21,24 @@ PY_PKG = ROOT / "packages" / "backend-python" NODE_PKG = ROOT / "packages" / "backend-node" +# The Postgres helper the backend-python tests use: one real server for the run. +sys.path.insert(0, str(PY_PKG / "tests")) +import pg_support # noqa: E402 + + +@pytest.fixture(scope="session") +def pg_dsn(): + """A real Postgres (BUG_REPORT_PG_DSN, or a throwaway local one); missing = skip, or FAIL under CI.""" + holder: list = [] + dsn = pg_support.server_dsn(holder) + try: + if dsn is None: + pg_support.missing_postgres() + yield dsn + finally: + for pg in holder: + pg.stop() + def _free_port() -> int: with contextlib.closing(socket.socket()) as s: @@ -52,33 +70,51 @@ def _wait_alive(url: str, timeout: float = 10) -> None: from flask import Flask from bug_report import create_blueprint, FilesystemStore +{store_init} + app = Flask(__name__) app.register_blueprint(create_blueprint( - store=FilesystemStore(r"{state}"), + store=store, is_admin=lambda req: True, + {hooks} )) app.run(host="127.0.0.1", port={port}, use_reloader=False) """ +FS_INIT = 'store = FilesystemStore(r"{state}")' +PG_INIT = """import psycopg +from bug_report.pg import PostgresStore +store = PostgresStore(lambda: psycopg.connect({dsn!r}, options="-c search_path={schema}")) +store.ensure_schema()""" +# v3 harness: who is calling and which app are test headers (a real service takes them from a verified token) +V3_HOOKS = """actor_identity=lambda r: {"email": r.headers.get("X-Test-User", ""), "name": ""}, + app_stamp=lambda r: r.headers.get("X-Test-App") or None,""" + + +def _boot_python(tmp_path_factory, label, store_init, hooks=""): + port = _free_port() + script = PY_SERVER_SCRIPT.format(pkg=str(PY_PKG), store_init=store_init, hooks=hooks, port=port) + log = tmp_path_factory.mktemp(f"{label}-log") / "out.log" + return port, script, log + @pytest.fixture(scope="session") def python_server(tmp_path_factory): - port = _free_port() - state = tmp_path_factory.mktemp("py-state") - script = PY_SERVER_SCRIPT.format(pkg=str(PY_PKG), state=str(state), port=port) - log = tmp_path_factory.mktemp("py-log") / "out.log" + yield from _serve_python(tmp_path_factory, "py", FS_INIT.format(state=tmp_path_factory.mktemp("py-state"))) + + +def _serve_python(tmp_path_factory, label, store_init, hooks=""): + """Boot a Python backend subprocess; yield its /bugs URL; stop it.""" + port, script, log = _boot_python(tmp_path_factory, label, store_init, hooks) with open(log, "w") as logf: - proc = subprocess.Popen( - [sys.executable, "-c", script], - stdout=logf, stderr=subprocess.STDOUT, - ) + proc = subprocess.Popen([sys.executable, "-c", script], stdout=logf, stderr=subprocess.STDOUT) base = f"http://127.0.0.1:{port}/bugs" try: try: _wait_alive(base) except RuntimeError: tail = log.read_text()[-2000:] if log.exists() else "(no log)" - raise RuntimeError(f"python backend failed to start. log tail:\n{tail}") + raise RuntimeError(f"python backend ({label}) failed to start. log tail:\n{tail}") yield base finally: proc.terminate() @@ -86,6 +122,32 @@ def python_server(tmp_path_factory): except subprocess.TimeoutExpired: proc.kill() +@pytest.fixture(scope="session") +def pg_schema_name(pg_dsn): + """Two fresh schemas' worth of names for the Postgres-backed servers (created now, dropped at the end).""" + schemas = [pg_support.Schema(pg_dsn), pg_support.Schema(pg_dsn)] + yield schemas + for s in schemas: + s.drop() + + +@pytest.fixture(scope="session") +def python_pg_server(tmp_path_factory, pg_dsn, pg_schema_name): + yield from _serve_python(tmp_path_factory, "pypg", PG_INIT.format(dsn=pg_dsn, schema=pg_schema_name[0].name)) + + +@pytest.fixture(scope="session") +def python_v3_server(tmp_path_factory): + yield from _serve_python(tmp_path_factory, "pyv3", FS_INIT.format(state=tmp_path_factory.mktemp("py-v3-state")), + V3_HOOKS) + + +@pytest.fixture(scope="session") +def python_pg_v3_server(tmp_path_factory, pg_dsn, pg_schema_name): + yield from _serve_python(tmp_path_factory, "pypgv3", + PG_INIT.format(dsn=pg_dsn, schema=pg_schema_name[1].name), V3_HOOKS) + + # --------------------------------------------------------------------------- # Python backend with a mailer โ€” the notify path over real HTTP (2.2.0) # --------------------------------------------------------------------------- @@ -152,22 +214,24 @@ def python_mailer_server(tmp_path_factory): app.use("/bugs", createBugsRouter({{ store: new FilesystemStore({state!r}), isAdmin: () => true, + {hooks} }})); app.listen({port}, "127.0.0.1", () => console.log("ready")); """ +NODE_V3_HOOKS = """actorIdentity: (req) => req.get("x-test-user") || "", + appStamp: (req) => req.get("x-test-app") || null,""" -@pytest.fixture(scope="session") -def node_server(tmp_path_factory): +def _serve_node(tmp_path_factory, label, hooks=""): """Boot the Node backend. Writes a launcher .mjs *inside* the package directory so Node's normal upward resolution finds `node_modules/express`. NODE_PATH doesn't help for ESM imports โ€” it's CommonJS-only.""" port = _free_port() - state = tmp_path_factory.mktemp("node-state") + state = tmp_path_factory.mktemp(f"{label}-state") # Tag the script with the PID so parallel runs don't collide. - script_path = NODE_PKG / f".e2e-server-{os.getpid()}.mjs" - script_path.write_text(NODE_SERVER_JS.format(state=str(state), port=port)) - log = tmp_path_factory.mktemp("node-log") / "out.log" + script_path = NODE_PKG / f".e2e-{label}-{os.getpid()}.mjs" + script_path.write_text(NODE_SERVER_JS.format(state=str(state), port=port, hooks=hooks)) + log = tmp_path_factory.mktemp(f"{label}-log") / "out.log" with open(log, "w") as logf: proc = subprocess.Popen( ["node", script_path.name], @@ -190,7 +254,25 @@ def node_server(tmp_path_factory): except FileNotFoundError: pass -@pytest.fixture(params=["python", "node"]) -def backend_url(request, python_server, node_server): - """Each test runs once per backend.""" - return python_server if request.param == "python" else node_server +@pytest.fixture(scope="session") +def node_server(tmp_path_factory): + yield from _serve_node(tmp_path_factory, "node") + + +@pytest.fixture(scope="session") +def node_v3_server(tmp_path_factory): + yield from _serve_node(tmp_path_factory, "nodev3", NODE_V3_HOOKS) + + +@pytest.fixture(params=["python", "python-postgres", "node"]) +def backend_url(request): + """Each test runs once per backend: Python on files, Python on Postgres, Node.""" + return request.getfixturevalue({"python": "python_server", "python-postgres": "python_pg_server", + "node": "node_server"}[request.param]) + + +@pytest.fixture(params=["python", "python-postgres", "node"]) +def v3_url(request): + """The v3 scenarios: the same three backends, each with a caller (X-Test-User) and an app stamp (X-Test-App).""" + return request.getfixturevalue({"python": "python_v3_server", "python-postgres": "python_pg_v3_server", + "node": "node_v3_server"}[request.param]) diff --git a/e2e/test_v3.py b/e2e/test_v3.py new file mode 100644 index 0000000..b4cd54b --- /dev/null +++ b/e2e/test_v3.py @@ -0,0 +1,130 @@ +"""Contract v3 over real HTTP, against every backend (Python on files, Python on +Postgres, Node): new summary fields, triage PATCH, duplicates, votes, filters. + +Each backend here is booted with a caller (`X-Test-User`) and an app stamp +(`X-Test-App`); a real service takes both from a verified token, see +bug_report.trust. Reports are found by a per-test marker in the title, because +the servers are shared across tests. +""" +from __future__ import annotations + +import uuid + +import requests + +ME = {"X-Test-User": "admin@example.com"} +V3_SUMMARY = ("kind", "app", "product", "area", "priority", "owner", "parentId", "duplicateOf", "votes") + + +def mark() -> str: + return "V3-" + uuid.uuid4().hex[:8] + + +def file(url, m, app=None, **kw): + h = {**ME, **({"X-Test-App": app} if app else {})} + r = requests.post(url, json={"details": f"{m} {kw.pop('d', 'x')}", **kw}, headers=h) + assert r.status_code == 201, r.text + return r.json()["id"] + + +def patch(url, bid, **body): + return requests.patch(f"{url}/{bid}", json=body, headers=ME) + + +def listing(url, m, q=""): + rows = requests.get(f"{url}?days=1{q}").json()["bugs"] + return [r["id"] for r in rows if m in r["title"]] + + +def test_a_new_report_carries_every_v3_field_with_defaults(v3_url): + bid = file(v3_url, mark()) + for rec in (requests.get(f"{v3_url}/{bid}").json(), + next(r for r in requests.get(f"{v3_url}?days=1").json()["bugs"] if r["id"] == bid)): + assert all(k in rec for k in V3_SUMMARY), rec + assert (rec["app"], rec["product"], rec["area"], rec["priority"], rec["owner"], + rec["parentId"], rec["duplicateOf"], rec["votes"], rec["kind"]) == ( + None, None, None, None, None, None, None, 0, "bug") + + +def test_the_app_stamp_comes_from_the_caller_and_product_follows(v3_url): + r = requests.post(v3_url, json={"details": "x", "app": "leaphq"}, headers={**ME, "X-Test-App": "sealviewer"}) + assert r.json()["app"] == "sealviewer" + rec = requests.get(f"{v3_url}/{r.json()['id']}").json() + assert (rec["app"], rec["product"]) == ("sealviewer", "Seal") + # the body's claim alone stamps nothing + bid = requests.post(v3_url, json={"details": "x", "app": "leaphq"}, headers=ME).json()["id"] + assert requests.get(f"{v3_url}/{bid}").json()["app"] is None + + +def test_kind_is_stored_or_derived(v3_url): + m = mark() + a = file(v3_url, m, tags=["feature-request"]) + b = file(v3_url, m, kind="feature", tags=["bug"]) + c = file(v3_url, m) + kinds = {r["id"]: r["kind"] for r in requests.get(f"{v3_url}?days=1").json()["bugs"]} + assert (kinds[a], kinds[b], kinds[c]) == ("feature", "feature", "bug") + + +def test_triage_patch_without_a_status_and_its_audit_row(v3_url): + bid = file(v3_url, mark()) + r = patch(v3_url, bid, area="Cutter", priority="now", owner="sam@example.com") + assert r.status_code == 200, r.text + rec = r.json() + assert (rec["area"], rec["priority"], rec["owner"], rec["status"]) == ("Cutter", "now", "sam@example.com", "open") + assert len(rec["audit"]) == 2 + assert rec["audit"][1]["note"] == "area: none -> Cutter; priority: none -> now; owner: none -> sam@example.com" + assert rec["audit"][1]["fromStatus"] == rec["audit"][1]["toStatus"] == "open" + # unchanged: no new row; cleared: says so + assert len(patch(v3_url, bid, area="Cutter").json()["audit"]) == 2 + assert patch(v3_url, bid, area=None).json()["audit"][-1]["note"] == "area: Cutter -> none" + + +def test_triage_patch_validation(v3_url): + bid = file(v3_url, mark()) + for body in ({"priority": "urgent"}, {"owner": "nobody"}, {"parentId": "junk"}, {"duplicateOf": bid}, {"parentId": bid}): + assert patch(v3_url, bid, **body).status_code == 400, body + assert patch(v3_url, bid, parentId="bug-20200101-000000-aaaaaa").status_code == 404 + assert requests.patch(f"{v3_url}/{bid}", json={"note": "x"}, headers=ME).status_code == 400 + + +def test_parent_chain_cannot_loop(v3_url): + a, b = file(v3_url, mark()), file(v3_url, mark()) + assert patch(v3_url, a, parentId=b).status_code == 200 + assert patch(v3_url, b, parentId=a).status_code == 400 + + +def test_duplicate_of_declines_with_the_note(v3_url): + a, b = file(v3_url, mark()), file(v3_url, mark()) + rec = patch(v3_url, b, duplicateOf=a).json() + assert (rec["status"], rec["duplicateOf"]) == ("declined", a) + assert rec["audit"][-1]["note"] == f"duplicate of {a}" and rec["audit"][-1]["toStatus"] == "declined" + assert patch(v3_url, file(v3_url, mark()), duplicateOf=a, status="triaged").status_code == 400 + + +def test_list_filters(v3_url): + m = mark() + a = file(v3_url, m, app="stoppages", tags=["feature"]) + b = file(v3_url, m, app="placements") + patch(v3_url, a, area="Clips", priority="now") + patch(v3_url, b, area="Belt", priority="later") + assert listing(v3_url, m, "&app=stoppages") == [a] + assert listing(v3_url, m, "&kind=feature") == [a] + assert listing(v3_url, m, "&kind=bug") == [b] + assert listing(v3_url, m, "&area=Belt") == [b] + assert listing(v3_url, m, "&priority=now") == [a] + assert listing(v3_url, m, "&app=stoppages&priority=later") == [] + assert requests.get(f"{v3_url}?kind=wat").status_code == 400 + assert requests.get(f"{v3_url}?priority=wat").status_code == 400 + + +def test_votes_one_per_person(v3_url): + bid = file(v3_url, mark()) + vote = lambda who, method="post": getattr(requests, method)( # noqa: E731 + f"{v3_url}/{bid}/vote", headers={"X-Test-User": who} if who else {}) + assert vote("a@example.com").json() == {"votes": 1, "voted": True} + assert vote("A@example.com").json()["votes"] == 1 + assert vote("b@example.com").json()["votes"] == 2 + assert requests.get(f"{v3_url}/{bid}").json()["votes"] == 2 + assert vote("a@example.com", "delete").json() == {"votes": 1, "voted": False} + assert vote("").status_code == 401 + assert requests.post(f"{v3_url}/bug-20200101-000000-aaaaaa/vote", headers=ME).status_code == 404 diff --git a/packages/backend-node/README.md b/packages/backend-node/README.md index 514540b..7d9734c 100644 --- a/packages/backend-node/README.md +++ b/packages/backend-node/README.md @@ -103,3 +103,12 @@ npm test ## Invariants enforced Identical to the Python side โ€” see the same list at [`../backend-python/README.md`](../backend-python/README.md#invariants-enforced). If a behavior differs between the two backends, that's a spec bug or a contract-test gap; the cross-stack suite in [`../../e2e`](../../e2e) hunts these. + +## Contract v3 (backends 3.0.0) + +The router stores and echoes the v3 fields (`kind`, `app`, `product`, `area`, `priority`, `owner`, `parentId`, +`duplicateOf`, `votes`), takes them on `PATCH` (audit row per change; `duplicateOf` declines with the note +`duplicate of `), filters the list by `app`, `kind`, `area` and `priority`, and serves `POST`/`DELETE /:id/vote`. +Options: `appStamp(req)` (the app a report is filed under; the body's `app` is never read) and `actorIdentity(req)` +(the signed-in email, who votes). `FilesystemStore` and `InMemoryStore` keep them; the Azure Tables store does not yet +and the router answers 501 for triage fields and votes on it. The Python library is the reference for the central store. diff --git a/packages/backend-node/src/index.js b/packages/backend-node/src/index.js index 2804b66..73df74e 100644 --- a/packages/backend-node/src/index.js +++ b/packages/backend-node/src/index.js @@ -14,6 +14,11 @@ import { BUG_DETAILS_MAX, BUG_SCREENSHOT_MAX, BUG_STATUSES, + APP_PRODUCTS, + KINDS, + PRIORITIES, + TRIAGE_FIELDS, + kindFromTags, newBugId, nowIso, screenshotContentType, @@ -28,6 +33,7 @@ import { export { InMemoryStore, FilesystemStore, NotFound, StoreError } from "./store.js"; export { BUG_DETAILS_MAX, BUG_SCREENSHOT_MAX, BUG_STATUSES, newBugId, validBugId } from "./models.js"; +export { APP_PRODUCTS, KINDS, PRIORITIES, TRIAGE_FIELDS, kindFromTags } from "./models.js"; const DEFAULT_ALLOW = () => true; @@ -40,6 +46,11 @@ export function createBugsRouter(opts = {}) { const isAdmin = opts.isAdmin || DEFAULT_ALLOW; const defaultActorEmail = opts.defaultActorEmail || ""; const buildShaSource = opts.buildSha || ""; + // Contract v3 hooks, same meaning as the Python blueprint's: appStamp(req) -> app + // (the body's `app` is never read); actorIdentity(req) -> the checked email, + // which is who votes. Without actorIdentity the voter is the body's actorEmail. + const appStamp = opts.appStamp || null; + const actorIdentity = opts.actorIdentity || null; function resolveBuildSha() { try { return typeof buildShaSource === "function" ? (buildShaSource() || "") : (buildShaSource || ""); } @@ -91,6 +102,11 @@ export function createBugsRouter(opts = {}) { let transcript = payload.transcript; if (transcript !== undefined && !Array.isArray(transcript)) transcript = null; + const kind = KINDS.includes(payload.kind) ? payload.kind : kindFromTags(tags); + let app = null; + if (appStamp) { try { app = appStamp(req) || null; } catch { app = null; } } + if (!(app in APP_PRODUCTS)) app = null; + const bug = { id: newBugId(), title, @@ -105,6 +121,8 @@ export function createBugsRouter(opts = {}) { metaUserAgent: String(payload.metaUserAgent || "").slice(0, 300), metaBuildSha: String(payload.metaBuildSha || resolveBuildSha()).slice(0, 40), transcript: transcript || null, + app, + kind, }; await store.putBug(bug, shotBytes); @@ -117,7 +135,7 @@ export function createBugsRouter(opts = {}) { note: "filed", }); - res.status(201).json({ id: bug.id }); + res.status(201).json({ id: bug.id, app }); }); // ----- GET / ------------------------------------------------------- @@ -132,8 +150,19 @@ export function createBugsRouter(opts = {}) { if (isNaN(days)) days = 30; days = Math.max(1, Math.min(365, days)); const since = sinceIso(days); + const q = (k) => (req.query[k] || "").toString().trim() || null; + const kind = q("kind"), priority = q("priority"); + if (kind && !KINDS.includes(kind)) return res.status(400).json({ error: `kind must be one of ${KINDS.join(", ")}` }); + if (priority && !PRIORITIES.includes(priority)) return res.status(400).json({ error: `priority must be one of ${PRIORITIES.join(", ")}` }); const rows = []; - for await (const r of store.listBugs({ status, sinceIso: since })) rows.push(toBugSummary(r)); + for await (const r of store.listBugs({ status, sinceIso: since })) { + const s = toBugSummary(r); + if (q("app") && s.app !== q("app")) continue; + if (kind && s.kind !== kind) continue; + if (q("area") && s.area !== q("area")) continue; + if (priority && s.priority !== priority) continue; + rows.push(s); + } rows.sort((a, b) => (a.addedAt < b.addedAt ? 1 : -1)); res.json({ bugs: rows }); }); @@ -166,38 +195,109 @@ export function createBugsRouter(opts = {}) { throw e; } const payload = req.body || {}; - const newStatus = String(payload.status || "").trim(); - if (!BUG_STATUSES.includes(newStatus)) { + let newStatus = String(payload.status || "").trim(); + const hasTriage = TRIAGE_FIELDS.some(f => f in payload); + if (!(hasTriage && !newStatus) && !BUG_STATUSES.includes(newStatus)) { return res.status(400).json({ error: `status must be one of ${BUG_STATUSES.join(", ")}` }); } - const note = String(payload.note || "").slice(0, 500); + let note = String(payload.note || "").slice(0, 500); const changedBy = String(payload.changedBy || defaultActorEmail || "admin").slice(0, 200); const changedByName = String(payload.changedByName || "").trim().slice(0, 200); // `notify` is accepted and ignored: no mailer here, so no `notified` either. + // triage fields: the same validation as the Python blueprint + const changes = {}; + for (const wire of TRIAGE_FIELDS) { + if (!(wire in payload)) continue; + const raw = payload[wire]; + const val = (raw === null || raw === undefined ? "" : String(raw).trim()) || null; + if (wire === "area" && val && val.length > 100) return res.status(400).json({ error: "area is at most 100 characters" }); + if (wire === "priority" && val && !PRIORITIES.includes(val)) return res.status(400).json({ error: `priority must be one of ${PRIORITIES.join(", ")}` }); + if (wire === "owner" && val && (!val.includes("@") || val.length > 200)) return res.status(400).json({ error: "owner must be an email address" }); + if ((wire === "parentId" || wire === "duplicateOf") && val) { + if (!validBugId(val)) return res.status(400).json({ error: `${wire} must be a report id` }); + if (val === rec.id) return res.status(400).json({ error: `${wire} cannot be the report itself` }); + try { await store.getBug(val); } + catch (e) { if (e instanceof NotFound) return res.status(404).json({ error: `${wire}: no such report` }); throw e; } + } + if (wire === "parentId" && val) { + const seen = new Set(); + for (let up = val; up && !seen.has(up);) { + if (up === rec.id) return res.status(400).json({ error: "parentId would make a cycle" }); + seen.add(up); + try { up = (await store.getBug(up)).parentId; } catch { break; } + } + } + if ((rec[wire] || null) !== val) changes[wire] = val; + } + if (Object.keys(changes).length && !store.updateFields) { + return res.status(501).json({ error: "this store does not keep triage fields" }); + } const oldStatus = rec.status; - if (newStatus === oldStatus) { + if (changes.duplicateOf) { + if (newStatus && newStatus !== "declined") return res.status(400).json({ error: "duplicateOf declines the report; status must be declined or omitted" }); + newStatus = "declined"; + note = `duplicate of ${changes.duplicateOf}` + (note.trim() ? `: ${note}` : ""); + if (oldStatus !== "declined" && !["open", "triaged"].includes(oldStatus)) { + return res.status(409).json({ error: `cannot transition ${oldStatus} -> declined` }); + } + } else if (!newStatus) { + newStatus = oldStatus; + } + + if (newStatus === oldStatus && !Object.keys(changes).length) { // No-op: skip audit. const full = toBugFull(rec); full.audit = (await store.listAudit(rec.id)).map(withChangedByName); return res.json(full); } - const updated = await store.updateStatus(rec.id, newStatus); - await store.appendAudit(rec.id, { - changedAt: nowIso(), - toStatus: newStatus, - fromStatus: oldStatus, - changedBy, - changedByName, - note, - }); + const shown = (v) => (v === null || v === undefined ? "none" : String(v)); + const declineRow = newStatus !== oldStatus; + const described = Object.entries(changes) + .filter(([k]) => !(declineRow && k === "duplicateOf")) + .map(([k, v]) => `${k}: ${shown(rec[k])} -> ${shown(v)}`).join("; ").slice(0, 500); + + let updated = rec; + if (Object.keys(changes).length) updated = await store.updateFields(rec.id, changes); + if (declineRow) { + updated = await store.updateStatus(rec.id, newStatus); + await store.appendAudit(rec.id, { + changedAt: nowIso(), toStatus: newStatus, fromStatus: oldStatus, changedBy, changedByName, note, + }); + } + if (described) { + await store.appendAudit(rec.id, { + changedAt: nowIso(), toStatus: updated.status, fromStatus: updated.status, changedBy, changedByName, + note: described, + }); + } const full = toBugFull(updated); full.audit = (await store.listAudit(rec.id)).map(withChangedByName); res.json(full); }); + // ----- POST / DELETE /:id/vote ------------------------------------- + + async function vote(req, res, adding) { + if (!validBugId(req.params.id)) return res.status(400).json({ error: "invalid id" }); + let voter = ""; + if (actorIdentity) { try { voter = String(actorIdentity(req) || "").trim(); } catch { voter = ""; } } + else voter = String((req.body || {}).actorEmail || req.query.actorEmail || defaultActorEmail || "").trim(); + if (!voter) return res.status(401).json({ error: "sign in to vote" }); + if (!store.setVote) return res.status(501).json({ error: "this store does not keep votes" }); + try { + const votes = await store.setVote(req.params.id, voter, adding); + res.json({ votes, voted: adding }); + } catch (e) { + if (e instanceof NotFound) return res.status(404).json({ error: "not found" }); + throw e; + } + } + router.post("/:id/vote", (req, res) => vote(req, res, true)); + router.delete("/:id/vote", (req, res) => vote(req, res, false)); + // ----- GET /:id/screenshot ----------------------------------------- router.get("/:id/screenshot", async (req, res) => { diff --git a/packages/backend-node/src/models.js b/packages/backend-node/src/models.js index 3414ab3..d0af182 100644 --- a/packages/backend-node/src/models.js +++ b/packages/backend-node/src/models.js @@ -8,6 +8,25 @@ export const BUG_SCREENSHOT_MAX = 5 * 1024 * 1024; // 5 MB decoded export const BUG_STATUSES = ["open", "triaged", "resolved", "declined"]; +// Contract v3 (report-contract.json; tests/contract-drift.test.js keeps these in step). +export const KINDS = ["bug", "feature"]; +export const KIND_TAGS = { + feature: ["feature", "feature-request", "capability", "capability-request"], + bug: ["bug", "bug-request"], +}; +export const PRIORITIES = ["now", "next", "later"]; +export const APP_PRODUCTS = { + stoppages: "PikPak", fleet: "PikPak", report: "PikPak", + placements: "Placement", sealviewer: "Seal", leaphq: "Internal", +}; +export const TRIAGE_FIELDS = ["area", "priority", "owner", "parentId", "duplicateOf"]; + +/** The kind a report is, from its tags: a feature tag outranks `bug`. */ +export function kindFromTags(tags) { + const norm = new Set((tags || []).map(t => String(t).trim().toLowerCase())); + return KIND_TAGS.feature.some(t => norm.has(t)) ? "feature" : "bug"; +} + // The widget serialises PNG when it fits and falls back down a JPEG ladder when // the capture would otherwise blow the cap above โ€” so "the screenshot" is not // always a PNG, and on an image-heavy page it usually is not. Serving every one diff --git a/packages/backend-node/src/store.js b/packages/backend-node/src/store.js index 07d99de..7b530eb 100644 --- a/packages/backend-node/src/store.js +++ b/packages/backend-node/src/store.js @@ -15,6 +15,7 @@ import { mkdir, readFile, readdir, writeFile, unlink, appendFile, open, rename, stat } from "node:fs/promises"; import { randomBytes } from "node:crypto"; import path from "node:path"; +import { APP_PRODUCTS, KINDS, kindFromTags } from "./models.js"; export class StoreError extends Error {} export class NotFound extends StoreError {} @@ -36,6 +37,15 @@ export function makeBugRecord(o) { metaBuildSha: o.metaBuildSha || "", screenshot: !!o.screenshot, transcript: o.transcript || null, + // contract v3: null / empty on a record written before it + app: o.app || null, + kind: KINDS.includes(o.kind) ? o.kind : null, + area: o.area || null, + priority: o.priority || null, + owner: o.owner || null, + parentId: o.parentId || null, + duplicateOf: o.duplicateOf || null, + votes: Array.isArray(o.votes) ? o.votes : [], // [{ voter, at }] }; } @@ -50,9 +60,34 @@ export function toBugSummary(rec) { actorName: rec.actorName || "", addedAt: rec.addedAt, screenshot: !!rec.screenshot, + kind: KINDS.includes(rec.kind) ? rec.kind : kindFromTags(rec.tags), + app: rec.app || null, + product: (rec.app && APP_PRODUCTS[rec.app]) || null, + area: rec.area || null, + priority: rec.priority || null, + owner: rec.owner || null, + parentId: rec.parentId || null, + duplicateOf: rec.duplicateOf || null, + votes: (rec.votes || []).length, }; } +const TRIAGE_ATTRS = ["area", "priority", "owner", "parentId", "duplicateOf"]; + +/** Apply triage changes / a vote to a record in place (shared by both stores). */ +export function applyChanges(rec, changes) { + for (const [k, v] of Object.entries(changes)) { + if (!TRIAGE_ATTRS.includes(k)) throw new StoreError(`not a triage field: ${k}`); + rec[k] = v; + } +} +export function toggleVote(rec, voter, adding) { + const v = String(voter).trim().toLowerCase(); + const has = rec.votes.some(x => x.voter === v); + if (adding && !has) rec.votes.push({ voter: v, at: new Date().toISOString() }); + if (!adding && has) rec.votes = rec.votes.filter(x => x.voter !== v); +} + export function toBugFull(rec) { return { ...toBugSummary(rec), @@ -96,6 +131,16 @@ export class InMemoryStore { r.status = newStatus; return r; } + async updateFields(id, changes) { + const r = await this.getBug(id); + applyChanges(r, changes); + return r; + } + async setVote(id, voter, adding) { + const r = await this.getBug(id); + toggleVote(r, voter, adding); + return r.votes.length; + } async appendAudit(id, entry) { if (!this._audits.has(id)) this._audits.set(id, []); this._audits.get(id).push(entry); @@ -169,6 +214,9 @@ export class FilesystemStore { this.root = root; this._readAttempts = readAttempts; this._ready = mkdir(root, { recursive: true }).then(() => this._sweepStaleTemps()); + // Nobody may ever await this (a store built and dropped, e.g. a test whose request never reaches it): + // mark it handled so a directory removed in the meantime is not an unhandledRejection. Callers that DO await it still see the error. + this._ready.catch(() => {}); } // A crash between creating a temp file and the rename leaves it behind. async _sweepStaleTemps() { @@ -214,6 +262,18 @@ export class FilesystemStore { await atomicWrite(this._path(rec.id, ".json"), JSON.stringify(rec, null, 2)); return rec; } + async updateFields(id, changes) { + const rec = await this.getBug(id); + applyChanges(rec, changes); + await atomicWrite(this._path(rec.id, ".json"), JSON.stringify(rec, null, 2)); + return rec; + } + async setVote(id, voter, adding) { + const rec = await this.getBug(id); + toggleVote(rec, voter, adding); + await atomicWrite(this._path(rec.id, ".json"), JSON.stringify(rec, null, 2)); + return rec.votes.length; + } async appendAudit(id, entry) { await appendFile(this._path(id, ".audit.jsonl"), JSON.stringify(entry) + "\n"); } diff --git a/packages/backend-node/tests/contract-drift.test.js b/packages/backend-node/tests/contract-drift.test.js new file mode 100644 index 0000000..7b6f15e --- /dev/null +++ b/packages/backend-node/tests/contract-drift.test.js @@ -0,0 +1,24 @@ +// The Node mirror of report-contract.json v3 agrees with the spec (practice T5): +// a constant that drifts here is a backend that answers differently from Python. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { APP_PRODUCTS, BUG_STATUSES, KINDS, KIND_TAGS, PRIORITIES, TRIAGE_FIELDS, kindFromTags } from "../src/models.js"; + +const SPEC = JSON.parse(readFileSync(new URL("../../spec/report-contract.json", import.meta.url), "utf8")); + +test("the mirror matches report-contract.json", () => { + assert.equal(SPEC.version, 3); + assert.deepEqual(BUG_STATUSES, SPEC.statuses); + assert.deepEqual(KINDS, SPEC.kinds); + assert.deepEqual(KIND_TAGS, SPEC.kindTags); + assert.deepEqual(PRIORITIES, SPEC.priorities); + assert.deepEqual(APP_PRODUCTS, SPEC.appProducts); + assert.deepEqual(TRIAGE_FIELDS, SPEC.triageFields); +}); + +test("kind is derived from tags as in the contract", () => { + assert.equal(kindFromTags([]), "bug"); + assert.equal(kindFromTags(["bug", "feature-request"]), "feature"); + assert.equal(kindFromTags(["capability-request"]), "feature"); +}); diff --git a/packages/backend-python/README.md b/packages/backend-python/README.md index e87ecda..295e486 100644 --- a/packages/backend-python/README.md +++ b/packages/backend-python/README.md @@ -1,6 +1,6 @@ # `bug-report-py` โ€” Python backend -Flask blueprint implementing the [bug-report API spec](../spec/openapi.yaml). Pluggable storage; two reference implementations ship in the box. +Flask blueprint implementing the [bug-report API spec](../spec/openapi.yaml). Pluggable storage; file, in-memory and PostgreSQL stores ship in the box. Version 3 adds the central-store pieces: triage fields, votes, `PostgresStore`, the proxy, the service-side trust helper and `import_reports` (sections below). ## Install @@ -37,6 +37,112 @@ Routes mounted (under the prefix you pass): | GET | /bugs/{id} | open | | PATCH | /bugs/{id} | `is_admin` | | GET | /bugs/{id}/screenshot | open | +| POST | /bugs/{id}/vote | signed in (3.0.0) | +| DELETE | /bugs/{id}/vote | signed in (3.0.0) | + +## Triage fields, votes and filters (3.0.0) + +`PATCH /bugs/{id}` takes `area`, `priority` (`now|next|later`), `owner` (an email), `parentId` and `duplicateOf` +with or without a `status` (a null or empty value clears a field). Each change writes an audit row whose note says +what changed (`area: none -> Cutter; priority: none -> now`); a value equal to the current one writes nothing. +`duplicateOf` also declines the report with the note `duplicate of `. A `parentId` that would make a cycle is 400. + +`POST /bugs/{id}/vote` and `DELETE /bugs/{id}/vote` need only a signed-in caller (the `actor_identity` email; without +that hook, the body's `actorEmail`), one vote per person, case-insensitively. `GET /bugs` filters by `app`, `kind`, +`area` and `priority` as well as `status` and `days`. Every summary carries `kind`, `app`, `product`, `area`, +`priority`, `owner`, `parentId`, `duplicateOf` and `votes`; a record written before v3 has them null and `votes` 0. +`create_blueprint(app_stamp=lambda req: "placements")` stamps the app a report is filed under (the body's `app` is +never read); `guard=` refuses a request before any route runs. + +## PostgresStore (3.0.0) + +```python +# pip install "bug-report-py[postgres]" # psycopg 3 +import psycopg +from bug_report import create_blueprint +from bug_report.pg import PostgresStore + +store = PostgresStore(lambda: psycopg.connect(dsn)) # a connection factory: one per operation +store.ensure_schema() # idempotent: reports, report_audit, report_votes +create_blueprint(store=store, ...) +``` + +The factory is called for every operation and the connection used as a context manager (commit, then close), so a +service whose password is a short-lived Entra token passes a factory that fetches a fresh one; a pool's +`pool.connection` works too. The `record` jsonb column holds what `FilesystemStore` writes (the same JSON, key for key; +jsonb does not keep key order or whitespace); `app`, `kind`, `status`, `added_at`, `area`, `priority`, `owner`, +`parent_id` and `duplicate_of` are copies lifted out for the list filters, and `kind` there is the effective kind +(stored, else derived from the tags). `since` is filtered on the `added_at` column. `update_bug` (what PATCH calls) is one +transaction: `SELECT ... FOR UPDATE` on the row, then one UPDATE, so two PATCHes of different fields both land. +Database errors surface as `StoreError`. + +## Moving an app's reports into the central store (3.0.0) + +```python +from bug_report import FilesystemStore, ImportMismatch, import_reports +from bug_report.pg import PostgresStore + +counts = import_reports(FilesystemStore("/data/bugs"), PostgresStore(connect), app="placements") +# {"copied": {"open": 12, "declined": 3}, "skipped": {}, "audit": 41, "screenshots": 9, "votes": 0} +``` + +**One run, at cutover, with the app's writes frozen.** It keeps ids, audit rows, screenshots and votes; a report that has +no `app` gets this one, which must be in `contract.APP_PRODUCTS` (else `ValueError`, nothing touched). A second run over +a finished import copies nothing (those reports are counted under `skipped`). It first compares every report already +in the destination with the source (status, triage fields, votes, audit length and last audit row); if any differs it raises +`ImportMismatch` with `.ids` and writes nothing, so a source edited after the first run is noticed, not half-merged. +There is no resume: a run that died half-way shows up as differing ids on the next. + +## An app's `/api/bugs` as a proxy to the central service (3.0.0) + +```python +from bug_report import create_proxy_blueprint +from bug_report.identity import person_provider + +app.register_blueprint(create_proxy_blueprint( + central_url="https://leaphq-reports.internal/api/bugs", + app="placements", + token_provider=lambda: credential.get_token(SCOPE).token, # the app's own managed identity + person_provider=person_provider(trust_easyauth=True), # the signed-in person +), url_prefix="/api") +``` + +Every route (POST, list, detail, PATCH, vote, screenshot) is forwarded with its method, query, body and content type, +and the service's status, body, content type and `Location` come back unchanged (a 302 to a signed screenshot URL is +not followed). Each forwarded request carries `Authorization: Bearer `, `X-Leap-Actor-Email` and +`X-Leap-Actor-Name` (percent-encoded) from `person_provider()`, and `X-Leap-App: `; the browser's own +`Authorization` and `X-Leap-*` headers are dropped. A `..` path segment is refused (400). A service that cannot be reached is a 502, and a token or identity that cannot be +produced is a 502 with nothing sent; the 502 bodies are generic (the reason goes to the log, not the browser). Standard library only (urllib). + +## The service side: who is calling (3.0.0) + +```python +from bug_report import TrustedCallers, create_blueprint + +callers = TrustedCallers( + trusted_apps={"": "placements", "": "sealviewer"}, + verify_token=verify_entra_token, # YOURS: raw bearer token -> claims dict, or raise. No JWT code here. +) +create_blueprint(store=store, actor_identity=callers.actor_identity, app_stamp=callers.app_stamp, + guard=callers.guard, is_admin=callers.is_admin_in(BUG_ADMINS)) +``` + +**`verify_token` must check the signature, the issuer, the audience and the expiry.** A verifier that only decodes the +token makes every trusted client id spoofable: anyone can write `azp` into a token they made up. (The service uses PyJWT +with the tenant's signing keys; this library has no JWT dependency, by design.) + +**Every request needs a valid app token; there is no person path** (Ken, 2026-11-14). `trusted_caller(request, +trusted_apps, verify_token)` is the function underneath. No bearer token is 401, and the service never reads +`X-Ms-Client-Principal` or Tailscale headers, whatever else the request carries. A verifier that raises or returns no claims +is 401; a token whose `azp` or `appid` claim is not in `trusted_apps` is 403; neither falls back to anything. Only behind a +good token from a trusted app are `X-Leap-Actor-Email` / `-Name` believed, and `app` is the mapped name. A disagreeing +`X-Leap-App` is ignored, and the response says which won: `X-Leap-App-Used` and `X-Leap-App-Ignored` headers, `app` and +`appIgnored` in the POST body. + +`bug_report.identity` holds the person logic for an APP behind its own gateway (its `trusted_person()`, handed to +`create_proxy_blueprint`): `trusted_person`, `trusted_identity`, `entra_claims`, `env_flag`. `trust_easyauth=True` believes +EasyAuth's `X-Ms-Client-Principal`; `loopback_headers=True` (off by default) believes Tailscale Serve's headers from a +loopback peer only. Nothing reads the environment for you. The central service does not use any of this. ## Emailing the reporter on close (2.2.0) @@ -66,9 +172,10 @@ Open-by-default for POST and single-bug GET is deliberate: any user (or agent) c | Class | Purpose | |---|---| | `InMemoryStore` | Tests, dev. Dict-backed; lost on process restart. | -| `FilesystemStore(root)` | Single-host production. One JSON per bug + audit JSONL + PNG. What `claude-tmux-dashboard` runs in production. | +| `FilesystemStore(root)` | Single-host production. One JSON per bug + audit JSONL + votes JSONL + PNG. What `claude-tmux-dashboard` runs in production. | +| `bug_report.pg.PostgresStore(connect)` | The central store (3.0.0); see above. Needs `bug-report-py[postgres]`. | -To plug in another backend (SQLite, Postgres, S3, โ€ฆ) implement the `Store` protocol โ€” see [`bug_report/store.py`](bug_report/store.py). The blueprint depends on the protocol only. +To plug in another backend (SQLite, S3, โ€ฆ) implement the `Store` protocol โ€” see [`bug_report/store.py`](bug_report/store.py). The blueprint depends on the protocol only. ## Tests @@ -78,7 +185,9 @@ pip install -e ".[test]" pytest ``` -The suite is parametrized over both built-in stores, so the same 21 scenarios run twice โ€” 42 tests total. Any new `Store` implementation should be added to the `store` fixture and will be exercised by the same contract. +The blueprint suite runs against every store (in-memory, filesystem, PostgreSQL). Any new `Store` implementation should be added to the `store` fixture in `test_blueprint.py` and the `any_store` fixture in `tests/conftest.py` and will be exercised by the same contract. + +The PostgreSQL tests use a real server: set `BUG_REPORT_PG_DSN` (a server you can create schemas on; each test gets its own schema), or have Homebrew's `postgresql@16` installed and a throwaway one is started on a free port in a temp directory. With neither, they skip and say why; under `CI=true` a missing Postgres fails instead. ## Invariants enforced diff --git a/packages/backend-python/bug_report/__init__.py b/packages/backend-python/bug_report/__init__.py index ccd0cf0..91a19d1 100644 --- a/packages/backend-python/bug_report/__init__.py +++ b/packages/backend-python/bug_report/__init__.py @@ -11,11 +11,19 @@ is_admin=lambda req: req.headers.get("X-Admin") == "yes", # your auth ), url_prefix="/api") +``PostgresStore`` (``bug_report.pg``) is an optional extra and is not imported +here: ``pip install "bug-report-py[postgres]"``, then +``from bug_report.pg import PostgresStore``. + Implements the contract in ../spec/openapi.yaml. Cross-stack contract tests in ../../e2e enforce that this and the Node backend stay honest. """ from .blueprint import create_blueprint +from .importer import ImportMismatch, import_reports +from .proxy import create_proxy_blueprint +from .trust import Caller, TrustedCallers, trusted_caller +from . import identity from .email import AcsNotifier, Notice, render from .store import ( Store, @@ -23,6 +31,8 @@ NotFound, InMemoryStore, FilesystemStore, + BugRecord, + AuditEntry, ) from .models import ( BUG_DETAILS_MAX, @@ -34,7 +44,7 @@ valid_bug_id, ) -__version__ = "1.0.0" +__version__ = "3.0.0" from . import contract from .contract import ( @@ -47,10 +57,23 @@ is_valid_transition, is_closed, with_kind, + effective_kind, + PRODUCTS, + APP_PRODUCTS, + PRIORITIES, + TRIAGE_FIELDS, + product_for_app, ) __all__ = [ "create_blueprint", + "create_proxy_blueprint", + "import_reports", + "ImportMismatch", + "trusted_caller", + "TrustedCallers", + "Caller", + "identity", "AcsNotifier", "Notice", "render", @@ -69,6 +92,8 @@ "NotFound", "InMemoryStore", "FilesystemStore", + "BugRecord", + "AuditEntry", "BUG_DETAILS_MAX", "BUG_SCREENSHOT_MAX", "BUG_STATUSES", diff --git a/packages/backend-python/bug_report/blueprint.py b/packages/backend-python/bug_report/blueprint.py index de343e2..28c9a8a 100644 --- a/packages/backend-python/bug_report/blueprint.py +++ b/packages/backend-python/bug_report/blueprint.py @@ -24,6 +24,7 @@ screenshot_content_type, valid_bug_id, ) +from .trust import ENVIRON_KEY from .store import ( AuditEntry, BugRecord, @@ -33,6 +34,9 @@ log = logging.getLogger(__name__) +#: the list filters a Store takes: the contract's, less the two the route itself reads +_STORE_FILTERS = tuple(f for f in contract.LIST_FILTERS if f not in ("status", "days")) + _last_now_ns = 0 @@ -65,6 +69,8 @@ def create_blueprint( is_admin: Callable | None = None, default_actor_email: str = "", actor_identity: Callable | None = None, + app_stamp: Callable | None = None, + guard: Callable | None = None, build_sha: str | Callable[[], str] = "", url_prefix: str = "/bugs", notifier: Callable | None = None, @@ -87,6 +93,15 @@ def create_blueprint( payload's value is used, as before. Added in 2.1.0. The same identity stamps ``changedBy``/``changedByName`` on a status change (2.2.0), replacing the request body's claim. + app_stamp: ``(request) -> str | None`` giving the app a new report is + filed under (contract v3 ``app``). The caller cannot set it: + the request body's ``app`` is never read here, only by a + hook that has checked who is asking (``TrustedCallers``). + Unknown apps (not in ``contract.APP_PRODUCTS``) are dropped. + Without the hook ``app`` stays null. Added in 3.0.0. + guard: ``(request) -> None | (status, message)`` run before every + route; a tuple refuses the request (``TrustedCallers.guard``: + a bad or untrusted bearer token). Added in 3.0.0. build_sha: String or zero-arg callable returning the current build SHA. Stamped on each report. Empty string means "unknown". url_prefix: Mount path within the blueprint. Outer app typically @@ -102,6 +117,27 @@ def create_blueprint( bp = Blueprint("bug_report", __name__) + @bp.before_request + def _guard(): + if guard is None: + return None + refused = guard(request) + if refused: + status, message = refused + return jsonify({"error": message}), status + return None + + @bp.after_request + def _say_which_app_won(resp): + # Set by TrustedCallers: the app the token says, and the one the caller + # claimed in X-Leap-App when the two disagreed (the claim lost). + caller = request.environ.get(ENVIRON_KEY) + if caller is not None and getattr(caller, "app", None): + resp.headers["X-Leap-App-Used"] = caller.app + if getattr(caller, "app_ignored", None): + resp.headers["X-Leap-App-Ignored"] = caller.app_ignored + return resp + def _resolve_build_sha() -> str: if callable(build_sha): try: @@ -155,6 +191,15 @@ def api_create(): if added_by == "agent" and "agent-self-report" not in tags: tags.append("agent-self-report") + kind = contract.effective_kind(payload.get("kind"), tags) + app = None + if app_stamp is not None: + try: + app = app_stamp(request) + except Exception: + app = None + app = app if app in contract.APP_PRODUCTS else None + shot_bytes: bytes | None = None raw = payload.get("screenshot") if raw and isinstance(raw, str): @@ -187,6 +232,8 @@ def api_create(): meta_user_agent=(payload.get("metaUserAgent") or payload.get("meta_user_agent") or "")[:300], meta_build_sha=(payload.get("metaBuildSha") or payload.get("meta_build_sha") or _resolve_build_sha())[:40], transcript=transcript, + app=app, + kind=kind, ) store.put_bug(bug, shot_bytes) store.append_audit(bug.id, AuditEntry( @@ -197,7 +244,11 @@ def api_create(): changed_by_name=actor_name, note="filed", )) - return jsonify({"id": bug.id}), 201 + out = {"id": bug.id, "app": app} + caller = request.environ.get(ENVIRON_KEY) + if getattr(caller, "app_ignored", None): + out["appIgnored"] = caller.app_ignored + return jsonify(out), 201 # ----- GET /bugs ---------------------------------------------------- @@ -212,11 +263,29 @@ def api_list(): days = max(1, min(365, int(request.args.get("days") or 30))) except ValueError: return jsonify({"error": "days must be an integer"}), 400 - rows = [contract.with_kind(b.to_summary()) - for b in store.list_bugs(status=status_filter, since_iso=_since_iso(days))] + # the store's filters are the contract's (`listFilters`) minus the two handled above + wanted = {f: (request.args.get(f) or "").strip() or None for f in _STORE_FILTERS} + if wanted.get("kind") and wanted["kind"] not in contract.KINDS: + return jsonify({"error": f"kind must be one of {contract.KINDS}"}), 400 + if wanted.get("priority") and wanted["priority"] not in contract.PRIORITIES: + return jsonify({"error": f"priority must be one of {contract.PRIORITIES}"}), 400 + bugs = list(store.list_bugs(status=status_filter, since_iso=_since_iso(days), **wanted)) + counts = _vote_counts([b.id for b in bugs]) + rows = [contract.with_kind({**b.to_summary(), "votes": counts.get(b.id, 0)}) for b in bugs] rows.sort(key=lambda r: r["addedAt"], reverse=True) return jsonify({"bugs": rows}) + def _vote_counts(ids): + """Votes per report; a store that predates votes counts none.""" + counter = getattr(store, "vote_counts", None) + return counter(ids) if counter and ids else {} + + def _detail(bug) -> dict: + full = contract.with_kind(bug.to_full()) + full["votes"] = _vote_counts([bug.id]).get(bug.id, 0) + full["audit"] = [a.to_dict() for a in store.list_audit(bug.id)] + return full + # ----- GET /bugs/ ---------------------------------------------- @bp.route(f"{url_prefix}/", methods=["GET"]) @@ -227,13 +296,61 @@ def api_get(bug_id: str): bug = store.get_bug(bug_id) except NotFound: return jsonify({"error": "not found"}), 404 - full = bug.to_full() + full = _detail(bug) full["canNotify"] = bool(notifier is not None and bug.actor_email) - full["audit"] = [a.to_dict() for a in store.list_audit(bug_id)] return jsonify(full) # ----- PATCH /bugs/ -------------------------------------------- + def _triage_changes(bug, payload): + """Validate the triage fields in a PATCH body and return + ``({attr: new value}, error)``: only fields that actually change, and a + ``(status, message)`` refusal for the first bad one. A null or empty + value clears a field.""" + changes: dict = {} + for wire in contract.TRIAGE_FIELDS: + if wire not in payload: + continue + raw = payload[wire] + val = None if raw is None else str(raw).strip() + val = val or None + attr = contract.TRIAGE_WIRE_TO_ATTR[wire] + if wire == "area" and val and len(val) > 100: + return None, (400, "area is at most 100 characters") + if wire == "priority" and val and val not in contract.PRIORITIES: + return None, (400, f"priority must be one of {contract.PRIORITIES}") + if wire == "owner" and val and ("@" not in val or len(val) > 200): + return None, (400, "owner must be an email address") + if wire in ("parentId", "duplicateOf") and val: + if not valid_bug_id(val): + return None, (400, f"{wire} must be a report id") + if val == bug.id: + return None, (400, f"{wire} cannot be the report itself") + try: + store.get_bug(val) + except NotFound: + return None, (404, f"{wire}: no such report") + if wire == "parentId" and val: + # an epic holds its children: a parent chain must never loop back + seen, up = set(), val + while up and up not in seen: + if up == bug.id: + return None, (400, "parentId would make a cycle") + seen.add(up) + try: + up = store.get_bug(up).parent_id + except NotFound: + break + if getattr(bug, attr) != val: + changes[attr] = val + return changes, None + + def _describe(bug, changes) -> str: + shown = lambda v: "none" if v is None else str(v) # noqa: E731 + return "; ".join( + f"{contract.TRIAGE_ATTR_TO_WIRE[a]}: {shown(getattr(bug, a))} -> {shown(v)}" for a, v in changes.items() + )[:500] + @bp.route(f"{url_prefix}/", methods=["PATCH"]) def api_patch(bug_id: str): if not is_admin(request): @@ -247,10 +364,24 @@ def api_patch(bug_id: str): payload = request.get_json(silent=True) or {} new_status = (payload.get("status") or "").strip() - if new_status not in BUG_STATUSES: + has_triage = any(f in payload for f in contract.TRIAGE_FIELDS) + if not (has_triage and not new_status) and new_status not in BUG_STATUSES: return jsonify({"error": f"status must be one of {BUG_STATUSES}"}), 400 note = (payload.get("note") or "")[:500] old = bug.status + changes, refused = _triage_changes(bug, payload) + if refused: + return jsonify({"error": refused[1]}), refused[0] + # A duplicate is a decline: setting `duplicateOf` closes the report with + # the note "duplicate of ". (Clearing it changes nothing else.) + dup = changes.get("duplicate_of") + if dup: + if new_status and new_status != "declined": + return jsonify({"error": "duplicateOf declines the report; status must be declined or omitted"}), 400 + new_status = "declined" + note = f"duplicate of {dup}" + (f": {note}" if note.strip() else "") + elif not new_status: + new_status = old # The lifecycle gate. This route used to check only that the # status was a member of the enum, which let `open -> resolved` # through here and 409 in a sibling app reading the same queue. @@ -279,26 +410,39 @@ def api_patch(bug_id: str): closer_email = changed_by if "@" in changed_by else "" old_status = old - if new_status == old_status: + if new_status == old_status and not changes: # No-op: don't write a meaningless audit row. - full = contract.with_kind(bug.to_full()) - full["audit"] = [a.to_dict() for a in store.list_audit(bug_id)] - return jsonify(full) - - bug = store.update_status(bug_id, new_status) - store.append_audit(bug_id, AuditEntry( - changed_at=_now_iso(), - to_status=new_status, - from_status=old_status, - changed_by=changed_by, - changed_by_name=changed_by_name, - note=note, - )) + return jsonify(_detail(bug)) + + # What the audit row for the fields says, worked out against the record as it is NOW. + decline_row = new_status != old_status + described = _describe(bug, {a: v for a, v in changes.items() + if not (decline_row and a == "duplicate_of")}) + if changes or decline_row: + # one atomic write of status and fields together (no lost update) + bug = store.update_bug(bug_id, status=new_status if decline_row else None, changes=changes) + if decline_row: + store.append_audit(bug_id, AuditEntry( + changed_at=_now_iso(), + to_status=new_status, + from_status=old_status, + changed_by=changed_by, + changed_by_name=changed_by_name, + note=note, + )) + if described: + store.append_audit(bug_id, AuditEntry( + changed_at=_now_iso(), + to_status=bug.status, + from_status=bug.status, + changed_by=changed_by, + changed_by_name=changed_by_name, + note=described, + )) notified = None if will_notify: notified = _notify(bug, new_status, note, closer_email, changed_by, changed_by_name) - full = contract.with_kind(bug.to_full()) - full["audit"] = [a.to_dict() for a in store.list_audit(bug_id)] + full = _detail(bug) if notified is not None: full["notified"] = notified return jsonify(full) @@ -339,6 +483,39 @@ def _notify(bug, new_status, note, closer_email, changed_by, changed_by_name) -> out["error"] = error return out + # ----- POST / DELETE /bugs//vote (3.0.0) ----------------------- + + def _voter(req) -> str: + """Who is voting: the checked identity when the app gave one, else (as + for filing) the request's own claim. "" means nobody is signed in.""" + if actor_identity is not None: + return _identity(req)[0] + body = req.get_json(silent=True) if req.is_json else None + claim = (body or {}).get("actorEmail") or req.args.get("actorEmail") or default_actor_email + return str(claim or "").strip()[:200] + + def _vote(bug_id: str, adding: bool): + if not valid_bug_id(bug_id): + return jsonify({"error": "invalid id"}), 400 + voter = _voter(request) + if not voter: + return jsonify({"error": "sign in to vote"}), 401 + if not hasattr(store, "add_vote"): + return jsonify({"error": "this store does not keep votes"}), 501 + try: + (store.add_vote if adding else store.remove_vote)(bug_id, voter) + except NotFound: + return jsonify({"error": "not found"}), 404 + return jsonify({"votes": store.vote_counts([bug_id]).get(bug_id, 0), "voted": adding}) + + @bp.route(f"{url_prefix}//vote", methods=["POST"]) + def api_vote(bug_id: str): + return _vote(bug_id, True) + + @bp.route(f"{url_prefix}//vote", methods=["DELETE"]) + def api_unvote(bug_id: str): + return _vote(bug_id, False) + # ----- GET /bugs//screenshot ----------------------------------- @bp.route(f"{url_prefix}//screenshot", methods=["GET"]) diff --git a/packages/backend-python/bug_report/contract.py b/packages/backend-python/bug_report/contract.py index 9bc4726..bc41590 100644 --- a/packages/backend-python/bug_report/contract.py +++ b/packages/backend-python/bug_report/contract.py @@ -86,7 +86,51 @@ def is_closed(status: str) -> bool: return (status or "open").lower() in CLOSED_STATUSES +def effective_kind(kind, tags) -> str: + """The stored kind when it is a declared one, else derived from the tags.""" + return kind if kind in KINDS else kind_from_tags(tags) + + def with_kind(payload: dict) -> dict: - """Stamp `kind` onto a wire payload. Idempotent.""" - payload["kind"] = kind_from_tags(payload.get("tags")) + """Stamp `kind` onto a wire payload: the kind it already carries when that + is a declared one (v3 stores it), else derived from its tags. Idempotent.""" + payload["kind"] = effective_kind(payload.get("kind"), payload.get("tags")) return payload + + +# --- v3 (2026-11-14) --------------------------------------------------------- +# Mirrors report-contract.json `products`, `appProducts`, `priorities`, +# `triageFields`, `listFilters`; tests/test_contract.py fails if they drift. + +PRODUCTS = ("PikPak", "Seal", "Placement", "Internal") + +#: app -> product. `product` is DERIVED from `app` by this table, never stored. +APP_PRODUCTS = { + "stoppages": "PikPak", + "fleet": "PikPak", + "report": "PikPak", + "placements": "Placement", + "sealviewer": "Seal", + "leaphq": "Internal", +} + +PRIORITIES = ("now", "next", "later") + +#: What PATCH may set besides the status: wire name -> the record's attribute. The ONE map; +#: everything else (the blueprint, the stores, audit notes) derives from it. +TRIAGE_WIRE_TO_ATTR = { + "area": "area", + "priority": "priority", + "owner": "owner", + "parentId": "parent_id", + "duplicateOf": "duplicate_of", +} +TRIAGE_ATTR_TO_WIRE = {a: w for w, a in TRIAGE_WIRE_TO_ATTR.items()} +TRIAGE_FIELDS = tuple(TRIAGE_WIRE_TO_ATTR) + +LIST_FILTERS = ("status", "days", "app", "kind", "area", "priority") + + +def product_for_app(app): + """The product an app belongs to, or None for no / an unknown app.""" + return APP_PRODUCTS.get(app) if app else None diff --git a/packages/backend-python/bug_report/identity.py b/packages/backend-python/bug_report/identity.py new file mode 100644 index 0000000..42fa5a5 --- /dev/null +++ b/packages/backend-python/bug_report/identity.py @@ -0,0 +1,118 @@ +"""Who is asking: the signed-in person behind a request, for an APP behind +its own gateway (its ``trusted_person()``, passed to ``create_proxy_blueprint``). +The central service does not use this: it requires an app token on every +request (``bug_report.trust``). + +Moved here from the apps (stoppageviewer's ``trusted_identity`` / +``trusted_person``, the near-identical copies in PIV, seal and the fleet +dashboard) so there is one. Nothing reads the environment: an app passes its +own flags, usually ``trust_easyauth=env_flag("TRUST_EASYAUTH")``. + +Two sources, both only when the app says to believe them: + +* **EasyAuth** (``trust_easyauth=True``): Container Apps / App Service + validates the sign-in and injects ``X-Ms-Client-Principal`` (base64 JSON, + claims), stripping any client-supplied copy. The flag is explicit rather + than inferred: believing that header when EasyAuth is NOT attached lets + anyone mint an identity. +* **Tailscale Serve** (``loopback_headers=True``, off by default): Serve injects + ``Tailscale-User-Login`` / ``-Name`` and dials the backend from loopback. + Apps bind 0.0.0.0 (WSL2), which also exposes the port to the LAN, so the + loopback peer is required as well. +""" +from __future__ import annotations + +import base64 +import json +import os + +LOOPBACK = ("127.0.0.1", "::1", "::ffff:127.0.0.1") +TAILSCALE_HEADERS = ("Tailscale-User-Login", "Tailscale-User-Name") + +#: Claim types EasyAuth may use for the signed-in address, in preference order. +EMAIL_CLAIMS = ( + "preferred_username", + "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", + "emails", + "email", + "name", +) + + +def env_flag(name: str, environ=None) -> bool: + """``1`` / ``true`` / ``yes`` in the environment variable ``name``.""" + return (environ if environ is not None else os.environ).get(name, "").strip().lower() in ( + "1", "true", "yes") + + +def entra_claims(request) -> dict: + """EasyAuth's ``X-Ms-Client-Principal`` decoded to ``{claim type: value}``; + ``{}`` when absent or malformed (a malformed header is "no identity").""" + raw = request.headers.get("X-Ms-Client-Principal") + if not raw: + return {} + try: + data = json.loads(base64.b64decode(raw).decode("utf-8")) + return {c.get("typ"): c.get("val") for c in data.get("claims", [])} + except Exception: # noqa: BLE001 + return {} + + +def entra_identity(request) -> str: + """The signed-in address from the EasyAuth principal, or "".""" + claims = entra_claims(request) + for typ in EMAIL_CLAIMS: + v = claims.get(typ) + if isinstance(v, str) and "@" in v: + return v.strip() + return "" + + +def _on_loopback(request) -> bool: + return (request.remote_addr or "") in LOOPBACK + + +def trusted_identity(request, *, trust_easyauth: bool = False, + loopback_headers: bool = False, + identity_headers=TAILSCALE_HEADERS) -> str: + """The caller's address, or "" when it cannot be trusted.""" + if trust_easyauth: + who = entra_identity(request) + if who: + return who + if loopback_headers and _on_loopback(request): + for h in identity_headers: + v = request.headers.get(h) + if v: + return v + return "" + + +def trusted_person(request, *, trust_easyauth: bool = False, + loopback_headers: bool = False, + identity_headers=TAILSCALE_HEADERS) -> dict: + """The trusted caller as ``{"email", "name"}``: who filed a report and who + moved it on, named. The name comes from the same sign-in as the address, + never from the page: Entra's ``name`` claim, or Tailscale's + ``Tailscale-User-Name``. "" when the sign-in carries none (the backend then + derives one from the address).""" + email = trusted_identity(request, trust_easyauth=trust_easyauth, + loopback_headers=loopback_headers, + identity_headers=identity_headers) + name = "" + if email: + if trust_easyauth and entra_identity(request) == email: + name = entra_claims(request).get("name") or "" + elif loopback_headers and _on_loopback(request) and len(identity_headers) > 1: + name = request.headers.get(identity_headers[1], "") + name = name.strip() if isinstance(name, str) else "" + return {"email": email, "name": "" if "@" in name else name} + + +def person_provider(**options): + """``() -> dict`` for ``create_proxy_blueprint``: the current Flask + request's trusted person, built from these options.""" + def provider() -> dict: + from flask import request + return trusted_person(request, **options) + return provider diff --git a/packages/backend-python/bug_report/importer.py b/packages/backend-python/bug_report/importer.py new file mode 100644 index 0000000..feb3979 --- /dev/null +++ b/packages/backend-python/bug_report/importer.py @@ -0,0 +1,82 @@ +"""Copy one store's reports into another (the migration into the central store). + + counts = import_reports(FilesystemStore("/data/bugs"), PostgresStore(connect), app="placements") + +**One run, at cutover, with the app's writes frozen** (Ken, 2026-11-14). It +keeps ids, audit rows, screenshots and votes. A second run over a finished +import copies nothing: each report already in the destination is compared with +the source (status, triage fields, votes, audit length and last audit row), +and if anything differs the run raises ``ImportMismatch`` listing the ids and +changes nothing. That is how a source edited after the first run is noticed +instead of silently half-merged. There is no resume: a run that died half-way +leaves reports the second run reports as differing. +""" +from __future__ import annotations + +import dataclasses + +from . import contract +from .store import NotFound + +_COMPARED = ("status",) + tuple(contract.TRIAGE_WIRE_TO_ATTR.values()) + + +class ImportMismatch(Exception): + """A report already in the destination differs from the source. ``ids`` lists them.""" + + def __init__(self, ids: list[str]): + self.ids = ids + super().__init__(f"{len(ids)} report(s) differ between source and destination: {', '.join(ids)}") + + +def _fingerprint(store, rec) -> tuple: + audit = store.list_audit(rec.id) + votes = sorted(v["voter"] for v in store.list_votes(rec.id)) if hasattr(store, "list_votes") else [] + return (tuple(getattr(rec, a) for a in _COMPARED), votes, len(audit), + audit[-1].to_dict() if audit else None) + + +def import_reports(src_store, dst_store, app: str) -> dict: + """Returns ``{"copied": {status: n}, "skipped": {status: n}, "audit": n, + "screenshots": n, "votes": n}``; the last three count what this run wrote. + A report that has no ``app`` gets ``app``, which must be one of + ``contract.APP_PRODUCTS`` (ValueError otherwise, before anything is read or written).""" + if app not in contract.APP_PRODUCTS: + raise ValueError(f"app must be one of {sorted(contract.APP_PRODUCTS)}, not {app!r}") + sources = sorted(src_store.list_bugs(status=None, since_iso=""), key=lambda r: r.added_at) + + # Pass 1: read-only. Which are already there, and do those still match? + present, differing = {}, [] + for src in sources: + try: + dst = dst_store.get_bug(src.id) + except NotFound: + continue + present[src.id] = True + if _fingerprint(src_store, src) != _fingerprint(dst_store, dst): + differing.append(src.id) + if differing: + raise ImportMismatch(differing) + + # Pass 2: copy what is not there. + out = {"copied": {}, "skipped": {}, "audit": 0, "screenshots": 0, "votes": 0} + for src in sources: + if src.id in present: + out["skipped"][src.status] = out["skipped"].get(src.status, 0) + 1 + continue + out["copied"][src.status] = out["copied"].get(src.status, 0) + 1 + try: + png = src_store.get_screenshot(src.id) + except NotFound: + png = None + # a copy: never alias the source's object + dst_store.put_bug(dataclasses.replace(src, screenshot=png is not None, app=src.app or app), png) + out["screenshots"] += 1 if png is not None else 0 + for entry in src_store.list_audit(src.id): + dst_store.append_audit(src.id, entry) + out["audit"] += 1 + if hasattr(src_store, "list_votes") and hasattr(dst_store, "add_vote"): + for v in src_store.list_votes(src.id): + if dst_store.add_vote(src.id, v["voter"], at=v.get("at")): + out["votes"] += 1 + return out diff --git a/packages/backend-python/bug_report/pg.py b/packages/backend-python/bug_report/pg.py new file mode 100644 index 0000000..87464a6 --- /dev/null +++ b/packages/backend-python/bug_report/pg.py @@ -0,0 +1,250 @@ +"""``PostgresStore``: the ``Store`` protocol over PostgreSQL (psycopg 3). + +An optional extra: ``pip install "bug-report-py[postgres]"``. Ported from the +fleet dashboard's ``bug_store_pg.py`` (in production since 2026-09-09), with +the central store's tables: + +* ``reports(id pk, app, kind, status, added_at timestamptz, area, priority, + owner, parent_id, duplicate_of, record jsonb, screenshot bytea)`` +* ``report_audit(id, seq, entry jsonb)`` +* ``report_votes(id, voter, at)`` + +``record`` is exactly what ``FilesystemStore`` writes to its JSON file +(``dataclasses.asdict(BugRecord)``), so a report reads back equal, and the +columns are copies lifted out of it only where a list filters or sorts on +them. The record stays the source: ``kind`` is the EFFECTIVE kind (stored, +else derived from the tags) so the filter agrees with the other stores. +jsonb does not keep key order or whitespace; "byte-equal" means the same JSON. + +Connections: the constructor takes ``connect``, a callable returning a psycopg +connection (or a pool's ``connection()`` context). One is taken per operation +and used as a context manager (commit, then close/return), so a service whose +password is a short-lived Entra token just passes a factory that fetches a +fresh one; this module has no token code. +""" +from __future__ import annotations + +import dataclasses +import datetime as dt +from typing import Callable + +try: + import psycopg + from psycopg.types.json import Jsonb +except ImportError as e: # pragma: no cover + raise ImportError( + 'PostgresStore needs psycopg 3: pip install "bug-report-py[postgres]"') from e + +from .store import (AuditEntry, BugRecord, NotFound, StoreError, apply_changes, + normal_voter, vote_time) + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS reports ( + id text PRIMARY KEY, + app text, + kind text, + status text NOT NULL, + added_at timestamptz, + area text, + priority text, + owner text, + parent_id text, + duplicate_of text, + record jsonb NOT NULL, + screenshot bytea +); +CREATE INDEX IF NOT EXISTS reports_status_added ON reports (status, added_at); +CREATE INDEX IF NOT EXISTS reports_app ON reports (app); +CREATE INDEX IF NOT EXISTS reports_parent ON reports (parent_id); +CREATE TABLE IF NOT EXISTS report_audit ( + id text NOT NULL, + seq integer NOT NULL, + entry jsonb NOT NULL, + PRIMARY KEY (id, seq) +); +CREATE TABLE IF NOT EXISTS report_votes ( + id text NOT NULL, + voter text NOT NULL, + at text NOT NULL, + PRIMARY KEY (id, voter) +); +""" + + +def _instant(s: str): + """The record's added_at as an instant for the column (the record keeps the + text it was given).""" + try: + return dt.datetime.fromisoformat(s.replace("Z", "+00:00")) if s else None + except ValueError: + return None + + +def _audit_entry(d: dict) -> AuditEntry: + return AuditEntry(changed_at=d.get("changedAt", ""), to_status=d.get("toStatus", ""), + from_status=d.get("fromStatus"), changed_by=d.get("changedBy", ""), + changed_by_name=d.get("changedByName", ""), note=d.get("note", "")) + + +class PostgresStore: + def __init__(self, connect: Callable): + self._connect = connect + + def ensure_schema(self) -> None: + """Create the tables and indexes if they are not there. Idempotent.""" + self._run(lambda cur: cur.execute(SCHEMA)) + + # -- plumbing ------------------------------------------------------------ + def _run(self, fn): + try: + with self._connect() as conn: + with conn.cursor() as cur: + return fn(cur) + except psycopg.Error as e: + raise StoreError(f"database error: {e}") from e + + # -- the Store protocol -------------------------------------------------- + def put_bug(self, bug: BugRecord, screenshot_png: bytes | None) -> None: + if screenshot_png is not None: + bug.screenshot = True + rec = dataclasses.asdict(bug) + cols = (bug.id, bug.app, bug.effective_kind(), bug.status, _instant(bug.added_at), + bug.area, bug.priority, bug.owner, bug.parent_id, bug.duplicate_of, Jsonb(rec)) + upsert = ( + "INSERT INTO reports(id, app, kind, status, added_at, area, priority, owner, " + "parent_id, duplicate_of, record{shot_col}) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s{shot_val}) " + "ON CONFLICT (id) DO UPDATE SET app=EXCLUDED.app, kind=EXCLUDED.kind, " + "status=EXCLUDED.status, added_at=EXCLUDED.added_at, area=EXCLUDED.area, " + "priority=EXCLUDED.priority, owner=EXCLUDED.owner, parent_id=EXCLUDED.parent_id, " + "duplicate_of=EXCLUDED.duplicate_of, record=EXCLUDED.record{shot_set}") + if screenshot_png is not None: + sql = upsert.format(shot_col=", screenshot", shot_val=",%s", + shot_set=", screenshot=EXCLUDED.screenshot") + args = cols + (screenshot_png,) + else: + # a status change or a re-save keeps the screenshot it has + sql = upsert.format(shot_col="", shot_val="", shot_set="") + args = cols + self._run(lambda cur: cur.execute(sql, args)) + + def get_bug(self, bug_id: str) -> BugRecord: + def go(cur): + cur.execute("SELECT record FROM reports WHERE id=%s", (bug_id,)) + return cur.fetchone() + row = self._run(go) + if row is None: + raise NotFound(bug_id) + return BugRecord.from_dict(row[0]) + + def list_bugs(self, *, status, since_iso, app=None, kind=None, area=None, priority=None): + # `since_iso` is an instant: compared on the `added_at` column (indexed), + # not as text. A report whose added_at will not parse has a NULL there + # and is not listed once a window is given. + where, args = [], [] + since = _instant(since_iso) + if since is not None: + where.append("added_at >= %s") + args.append(since) + for col, val in (("status", status), ("app", app), ("kind", kind), + ("area", area), ("priority", priority)): + if val: + where.append(f"{col} = %s") + args.append(val) + + def go(cur): + cur.execute("SELECT record FROM reports" + (" WHERE " + " AND ".join(where) if where else "") + + " ORDER BY added_at, id", args) + return cur.fetchall() + for (rec,) in self._run(go): + yield BugRecord.from_dict(rec) + + def update_status(self, bug_id: str, new_status: str) -> BugRecord: + return self.update_bug(bug_id, status=new_status) + + def update_fields(self, bug_id: str, changes: dict) -> BugRecord: + return self.update_bug(bug_id, changes=changes) + + def update_bug(self, bug_id: str, *, status: str | None = None, + changes: dict | None = None) -> BugRecord: + """One transaction: lock the row (``SELECT ... FOR UPDATE``), change the + record, write it back with one UPDATE. Two PATCHes of different fields + of one report queue behind each other instead of the second putting + back the first's old values.""" + def go(cur): + cur.execute("SELECT record FROM reports WHERE id=%s FOR UPDATE", (bug_id,)) + row = cur.fetchone() + if row is None: + raise NotFound(bug_id) + rec = BugRecord.from_dict(row[0]) + apply_changes(rec, changes or {}, status) + cur.execute( + "UPDATE reports SET app=%s, kind=%s, status=%s, added_at=%s, area=%s, priority=%s, " + "owner=%s, parent_id=%s, duplicate_of=%s, record=%s WHERE id=%s", + (rec.app, rec.effective_kind(), rec.status, _instant(rec.added_at), rec.area, + rec.priority, rec.owner, rec.parent_id, rec.duplicate_of, + Jsonb(dataclasses.asdict(rec)), bug_id)) + return rec + return self._run(go) + + def append_audit(self, bug_id: str, entry: AuditEntry) -> None: + def go(cur): + # one writer per report at a time, so `seq` never collides + cur.execute("SELECT pg_advisory_xact_lock(hashtext(%s))", (bug_id,)) + cur.execute("INSERT INTO report_audit(id, seq, entry) " + "SELECT %s, COALESCE(MAX(seq), 0) + 1, %s FROM report_audit WHERE id=%s", + (bug_id, Jsonb(entry.to_dict()), bug_id)) + self._run(go) + + def list_audit(self, bug_id: str) -> list: + def go(cur): + cur.execute("SELECT entry FROM report_audit WHERE id=%s ORDER BY seq", (bug_id,)) + return cur.fetchall() + return [_audit_entry(d) for (d,) in self._run(go)] + + def get_screenshot(self, bug_id: str) -> bytes: + def go(cur): + cur.execute("SELECT screenshot FROM reports WHERE id=%s", (bug_id,)) + return cur.fetchone() + row = self._run(go) + if row is None or row[0] is None: + raise NotFound(bug_id) + return bytes(row[0]) + + # -- votes --------------------------------------------------------------- + def _exists(self, cur, bug_id): + cur.execute("SELECT 1 FROM reports WHERE id=%s", (bug_id,)) + if cur.fetchone() is None: + raise NotFound(bug_id) + + def add_vote(self, bug_id: str, voter: str, at: str | None = None) -> bool: + def go(cur): + self._exists(cur, bug_id) + cur.execute("INSERT INTO report_votes(id, voter, at) VALUES(%s,%s,%s) " + "ON CONFLICT DO NOTHING", (bug_id, normal_voter(voter), at or vote_time())) + return cur.rowcount == 1 + return self._run(go) + + def remove_vote(self, bug_id: str, voter: str) -> bool: + def go(cur): + self._exists(cur, bug_id) + cur.execute("DELETE FROM report_votes WHERE id=%s AND voter=%s", + (bug_id, normal_voter(voter))) + return cur.rowcount == 1 + return self._run(go) + + def vote_counts(self, bug_ids: list[str]) -> dict[str, int]: + if not bug_ids: + return {} + + def go(cur): + cur.execute("SELECT id, count(*) FROM report_votes WHERE id = ANY(%s) GROUP BY id", + (list(bug_ids),)) + return dict(cur.fetchall()) + got = self._run(go) + return {i: int(got.get(i, 0)) for i in bug_ids} + + def list_votes(self, bug_id: str) -> list[dict]: + def go(cur): + cur.execute("SELECT voter, at FROM report_votes WHERE id=%s ORDER BY at, voter", (bug_id,)) + return cur.fetchall() + return [{"voter": v, "at": at} for v, at in self._run(go)] diff --git a/packages/backend-python/bug_report/proxy.py b/packages/backend-python/bug_report/proxy.py new file mode 100644 index 0000000..4684bec --- /dev/null +++ b/packages/backend-python/bug_report/proxy.py @@ -0,0 +1,110 @@ +"""An app's ``/api/bugs`` that forwards to the central reports service. + + from bug_report import create_proxy_blueprint + from bug_report.identity import person_provider + + app.register_blueprint(create_proxy_blueprint( + central_url="https://leaphq-reports.internal/api/bugs", + app="placements", + token_provider=lambda: credential.get_token(SCOPE).token, + person_provider=person_provider(trust_easyauth=True), + ), url_prefix="/api") + +Every route (POST, list, detail, PATCH, vote, screenshot) is forwarded with +its method, query, body and content type, and the service's status code, body +and content type come back unchanged. Each forwarded request carries +``Authorization: Bearer ``, ``X-Leap-Actor-Email`` / +``X-Leap-Actor-Name`` (percent-encoded; the service decodes) from +``person_provider()``, and ``X-Leap-App: ``. Any ``Authorization`` or +``X-Leap-*`` header the browser sent is dropped: the app's own identity, not +the page's claim, is what the service looks at. Standard library only. +""" +from __future__ import annotations + +import json +import logging +import urllib.error +import urllib.request +from typing import Callable +from urllib.parse import quote + +from flask import Blueprint, Response, request + +log = logging.getLogger(__name__) + + +class _NoRedirect(urllib.request.HTTPRedirectHandler): + """A 302 (a signed screenshot URL) goes back to the browser as it is.""" + def redirect_request(self, *a, **kw): + return None + + +_OPENER = urllib.request.build_opener(_NoRedirect) + +#: request headers passed on from the browser; everything else is dropped +_FORWARD = ("Content-Type", "Accept") +#: response headers passed back: the contract's, plus the redirect target +_BACK = ("Content-Type", "Location", "Cache-Control", "X-Leap-App-Used", "X-Leap-App-Ignored") + + +def create_proxy_blueprint( + central_url: str, + app: str, + token_provider: Callable[[], str], + person_provider: Callable[[], dict | None], + *, + url_prefix: str = "/bugs", + timeout: float = 30, +) -> Blueprint: + bp = Blueprint(f"bug_report_proxy_{app}", __name__) + base = central_url.rstrip("/") + + def _ascii(v: str) -> str: + return quote(v or "", safe=" @.+-_'") + + @bp.route(url_prefix, defaults={"rest": ""}, methods=["GET", "POST", "PATCH", "DELETE"]) + @bp.route(f"{url_prefix}/", methods=["GET", "POST", "PATCH", "DELETE"]) + def forward(rest: str): + if any(seg in ("..", ".") or "\\" in seg for seg in rest.split("/")): + return _err(400, "invalid path") + url = base + ("/" + rest if rest else "") + if request.query_string: + url += "?" + request.query_string.decode("latin-1") + try: + person = person_provider() or {} + headers = {h: request.headers[h] for h in _FORWARD if h in request.headers} + headers.update({ + "Authorization": f"Bearer {token_provider()}", + "X-Leap-Actor-Email": _ascii(person.get("email", "")), + "X-Leap-Actor-Name": _ascii(person.get("name", "")), + "X-Leap-App": app, + }) + except Exception as e: # noqa: BLE001 โ€” no token / identity: say so, do not guess + log.warning("reports proxy (%s): could not get a token or identity: %s", app, e) + return _err(502, "could not authenticate to the reports service") + data = request.get_data() if request.method in ("POST", "PATCH", "DELETE") else None + req = urllib.request.Request(url, data=data, headers=headers, method=request.method) + try: + with _OPENER.open(req, timeout=timeout) as r: + return _relay(r.status, r.read(), r.headers) + except urllib.error.HTTPError as e: # a 3xx/4xx/5xx from the service is its answer + try: + return _relay(e.code, e.read(), e.headers) + finally: + e.close() + except (urllib.error.URLError, OSError, TimeoutError) as e: + log.warning("reports proxy (%s): %s unreachable: %s", app, url, getattr(e, "reason", e)) + return _err(502, "the reports service is not reachable") + + def _relay(status, body, upstream_headers): + resp = Response(body, status=status) + for h in _BACK: + v = upstream_headers.get(h) + if v is not None: + resp.headers[h] = v + return resp + + def _err(status, message): + return Response(json.dumps({"error": message}), status=status, mimetype="application/json") + + return bp diff --git a/packages/backend-python/bug_report/store.py b/packages/backend-python/bug_report/store.py index 038166a..aff0e50 100644 --- a/packages/backend-python/bug_report/store.py +++ b/packages/backend-python/bug_report/store.py @@ -15,12 +15,15 @@ import json import logging import os +import threading import time import uuid -from dataclasses import asdict, dataclass, field +from dataclasses import asdict, dataclass, field, fields as dc_fields from pathlib import Path from typing import Iterable, Protocol +from . import contract + log = logging.getLogger(__name__) @@ -58,6 +61,26 @@ class BugRecord: # Display name of whoever filed it ("" when unknown). Added in 2.2.0; a # record on disk from before has no such key and loads with the default. actor_name: str = "" + # Contract v3 (backends 3.0.0). A record written before has none of these + # and loads with the defaults: null, and no votes. + app: str | None = None # stamped by the proxy from the caller's identity + kind: str | None = None # stored; derived from `tags` when None + area: str | None = None # triage + priority: str | None = None # triage: now | next | later + owner: str | None = None # triage: an email + parent_id: str | None = None # triage: a report id (an epic holds its children) + duplicate_of: str | None = None # triage: a report id + + @classmethod + def from_dict(cls, data: dict) -> "BugRecord": + """A record from its stored JSON. Keys this version does not know are + dropped (a newer writer's fields must not make the report unreadable); + keys it knows but the data lacks take their defaults.""" + known = {f.name for f in dc_fields(cls)} + return cls(**{k: v for k, v in data.items() if k in known}) + + def effective_kind(self) -> str: + return contract.effective_kind(self.kind, self.tags) def to_summary(self) -> dict: return { @@ -70,6 +93,14 @@ def to_summary(self) -> dict: "actorName": self.actor_name, "addedAt": self.added_at, "screenshot": bool(self.screenshot), + "kind": self.effective_kind(), + "app": self.app, + "product": contract.product_for_app(self.app), + "area": self.area, + "priority": self.priority, + "owner": self.owner, + "parentId": self.parent_id, + "duplicateOf": self.duplicate_of, } def to_full(self) -> dict: @@ -104,6 +135,37 @@ def to_dict(self) -> dict: } +def matches(rec: BugRecord, *, status=None, since_iso="", app=None, kind=None, + area=None, priority=None) -> bool: + """The list filters, in one place so every store agrees on them.""" + if rec.added_at < (since_iso or ""): + return False + if status and rec.status != status: + return False + if app and rec.app != app: + return False + if kind and rec.effective_kind() != kind: + return False + if area and rec.area != area: + return False + if priority and rec.priority != priority: + return False + return True + + +def vote_time() -> str: + return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + + +def normal_voter(voter: str) -> str: + """One vote per PERSON: addresses compare case-insensitively.""" + return (voter or "").strip().lower() + + +# Fields `update_fields` may set: the record's snake_case attributes. +TRIAGE_ATTRS = tuple(contract.TRIAGE_WIRE_TO_ATTR.values()) + + # --------------------------------------------------------------------------- # Store protocol # --------------------------------------------------------------------------- @@ -114,13 +176,43 @@ class Store(Protocol): def put_bug(self, bug: BugRecord, screenshot_png: bytes | None) -> None: ... def get_bug(self, bug_id: str) -> BugRecord: ... - def list_bugs(self, *, status: str | None, since_iso: str) -> Iterable[BugRecord]: ... + def list_bugs(self, *, status: str | None, since_iso: str, app: str | None = None, + kind: str | None = None, area: str | None = None, + priority: str | None = None) -> Iterable[BugRecord]: ... def update_status(self, bug_id: str, new_status: str) -> BugRecord: ... + # v3 (backends 3.0.0) + def update_fields(self, bug_id: str, changes: dict) -> BugRecord: + """Set triage attributes (``TRIAGE_ATTRS``: area, priority, owner, + parent_id, duplicate_of); a None value clears one.""" + ... + def update_bug(self, bug_id: str, *, status: str | None = None, + changes: dict | None = None) -> BugRecord: + """Set the status and/or triage attributes ATOMICALLY: read, change and + write as one step, so two concurrent PATCHes of different fields both + land (no lost update). What the PATCH route calls.""" + ... + def add_vote(self, bug_id: str, voter: str, at: str | None = None) -> bool: + """Record ``voter``'s vote (at ``at``, default now); False when they had already voted.""" + ... + def remove_vote(self, bug_id: str, voter: str) -> bool: ... + def vote_counts(self, bug_ids: list[str]) -> dict[str, int]: ... + def list_votes(self, bug_id: str) -> list[dict]: + """``[{"voter", "at"}]``, oldest first.""" + ... def append_audit(self, bug_id: str, entry: AuditEntry) -> None: ... def list_audit(self, bug_id: str) -> list[AuditEntry]: ... def get_screenshot(self, bug_id: str) -> bytes: ... +def apply_changes(rec: BugRecord, changes: dict, status: str | None = None) -> None: + for k, v in changes.items(): + if k not in TRIAGE_ATTRS: + raise StoreError(f"not a triage field: {k}") + setattr(rec, k, v) + if status is not None: + rec.status = status + + # --------------------------------------------------------------------------- # InMemoryStore โ€” for tests # --------------------------------------------------------------------------- @@ -132,6 +224,7 @@ def __init__(self) -> None: self._bugs: dict[str, BugRecord] = {} self._audits: dict[str, list[AuditEntry]] = {} self._screenshots: dict[str, bytes] = {} + self._votes: dict[str, dict[str, str]] = {} def put_bug(self, bug: BugRecord, screenshot_png: bytes | None) -> None: self._bugs[bug.id] = bug @@ -145,19 +238,46 @@ def get_bug(self, bug_id: str) -> BugRecord: except KeyError as e: raise NotFound(bug_id) from e - def list_bugs(self, *, status, since_iso): - for b in self._bugs.values(): - if b.added_at < since_iso: - continue - if status and b.status != status: - continue - yield b + def list_bugs(self, *, status, since_iso, app=None, kind=None, area=None, priority=None): + for b in list(self._bugs.values()): + if matches(b, status=status, since_iso=since_iso, app=app, kind=kind, + area=area, priority=priority): + yield b def update_status(self, bug_id, new_status): b = self.get_bug(bug_id) b.status = new_status return b + def update_fields(self, bug_id, changes): + b = self.get_bug(bug_id) + apply_changes(b, changes) + return b + + def update_bug(self, bug_id, *, status=None, changes=None): + b = self.get_bug(bug_id) + apply_changes(b, changes or {}, status) + return b + + def add_vote(self, bug_id, voter, at=None): + self.get_bug(bug_id) + v = normal_voter(voter) + votes = self._votes.setdefault(bug_id, {}) + if v in votes: + return False + votes[v] = at or vote_time() + return True + + def remove_vote(self, bug_id, voter): + self.get_bug(bug_id) + return self._votes.get(bug_id, {}).pop(normal_voter(voter), None) is not None + + def vote_counts(self, bug_ids): + return {i: len(self._votes.get(i, {})) for i in bug_ids} + + def list_votes(self, bug_id): + return [{"voter": v, "at": at} for v, at in self._votes.get(bug_id, {}).items()] + def append_audit(self, bug_id, entry): self._audits.setdefault(bug_id, []).append(entry) @@ -251,6 +371,16 @@ def __init__(self, root: str | Path) -> None: self.root = Path(root) self.root.mkdir(parents=True, exist_ok=True) self._sweep_stale_temps() + self._locks: dict[str, threading.Lock] = {} + self._locks_guard = threading.Lock() + + def _lock(self, bug_id: str) -> threading.Lock: + """One lock per report: a read-modify-write of its record (status, triage + fields, votes) must not interleave with another, or the later write + puts back the older value of whatever the other one changed. (One + process; across processes each write is still atomic, as before.)""" + with self._locks_guard: + return self._locks.setdefault(bug_id, threading.Lock()) def _sweep_stale_temps(self) -> None: """A crash between creating a temp file and the replace leaves it behind.""" @@ -271,6 +401,9 @@ def _audit_path(self, bug_id: str) -> Path: def _shot_path(self, bug_id: str) -> Path: return self.root / f"{bug_id}.png" + def _votes_path(self, bug_id: str) -> Path: + return self.root / f"{bug_id}.votes.jsonl" + def put_bug(self, bug, screenshot_png): if screenshot_png is not None: _atomic_write(self._shot_path(bug.id), screenshot_png) @@ -287,9 +420,9 @@ def get_bug(self, bug_id): data = _read_json(p) except (OSError, json.JSONDecodeError) as e: raise StoreError(f"could not read {bug_id}") from e - return BugRecord(**data) + return BugRecord.from_dict(data) - def list_bugs(self, *, status, since_iso): + def list_bugs(self, *, status, since_iso, app=None, kind=None, area=None, priority=None): for p in self.root.glob("bug-*.json"): if p.name.endswith(".audit.jsonl"): continue @@ -297,18 +430,66 @@ def list_bugs(self, *, status, since_iso): data = _read_json(p) except (OSError, json.JSONDecodeError): continue - rec = BugRecord(**data) - if rec.added_at < since_iso: - continue - if status and rec.status != status: - continue - yield rec + rec = BugRecord.from_dict(data) + if matches(rec, status=status, since_iso=since_iso, app=app, kind=kind, + area=area, priority=priority): + yield rec def update_status(self, bug_id, new_status): - rec = self.get_bug(bug_id) - rec.status = new_status - self.put_bug(rec, None) - return rec + return self.update_bug(bug_id, status=new_status) + + def update_fields(self, bug_id, changes): + return self.update_bug(bug_id, changes=changes) + + def update_bug(self, bug_id, *, status=None, changes=None): + with self._lock(bug_id): + rec = self.get_bug(bug_id) + apply_changes(rec, changes or {}, status) + self.put_bug(rec, None) + return rec + + def _read_votes(self, bug_id) -> dict[str, str]: + p = self._votes_path(bug_id) + out: dict[str, str] = {} + if not p.exists(): + return out + for ln in p.read_text().splitlines(): + try: + d = json.loads(ln) + out[d["voter"]] = d.get("at", "") + except (json.JSONDecodeError, KeyError, TypeError): + continue + return out + + def _write_votes(self, bug_id, votes: dict[str, str]) -> None: + body = "".join(json.dumps({"voter": v, "at": at}) + "\n" for v, at in votes.items()) + _atomic_write(self._votes_path(bug_id), body.encode()) + + def add_vote(self, bug_id, voter, at=None): + self.get_bug(bug_id) + v = normal_voter(voter) + with self._lock(bug_id): + votes = self._read_votes(bug_id) + if v in votes: + return False + votes[v] = at or vote_time() + self._write_votes(bug_id, votes) + return True + + def remove_vote(self, bug_id, voter): + self.get_bug(bug_id) + with self._lock(bug_id): + votes = self._read_votes(bug_id) + if votes.pop(normal_voter(voter), None) is None: + return False + self._write_votes(bug_id, votes) + return True + + def vote_counts(self, bug_ids): + return {i: len(self._read_votes(i)) for i in bug_ids} + + def list_votes(self, bug_id): + return [{"voter": v, "at": at} for v, at in self._read_votes(bug_id).items()] def append_audit(self, bug_id, entry): # An append, not a rewrite: it never truncates, and one short line is a diff --git a/packages/backend-python/bug_report/trust.py b/packages/backend-python/bug_report/trust.py new file mode 100644 index 0000000..786cc3f --- /dev/null +++ b/packages/backend-python/bug_report/trust.py @@ -0,0 +1,126 @@ +"""Service side of the proxy: who is calling, and which app. + +Every request to the central service carries a token: an app's proxy +(``create_proxy_blueprint``) calls it with the app's OWN identity as a bearer +token, and names the signed-in person in two headers. The service believes +those headers only from an app it trusts, and takes the app's NAME from the +token, never from the request. There is no person path: a request with no +token is refused, and the service never looks at ``X-Ms-Client-Principal`` or +Tailscale headers (Ken, 2026-11-14). Those belong to an APP's own +``identity.trusted_person()``, behind that app's gateway. + +The service injects ``verify_token``: a callable that takes the raw bearer +token and returns its claims dict, or raises. This library adds no JWT +dependency and does not validate tokens itself, so **``verify_token`` must +check the signature, the issuer, the audience and the expiry**. A verifier +that only decodes the token makes every trusted client id spoofable: anyone +can write ``azp`` into a token they made up. + +* **No bearer token:** 401. +* **A bad token** (the verifier raises, or returns no claims): 401. **A token + from an app not in ``trusted_apps``**: 403. Neither falls back to anything. +* **A good token from a trusted app:** the app is the token's ``azp`` or + ``appid`` claim, looked up in ``trusted_apps`` (client id -> app name); + ``X-Leap-Actor-Email`` / ``-Name`` are believed; a ``X-Leap-App`` header that + disagrees is ignored, and the response says which won (``X-Leap-App-Used`` / + ``X-Leap-App-Ignored``; the POST body carries ``app`` and ``appIgnored``). +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Callable +from urllib.parse import unquote + +#: where the resolved caller is cached for the life of one request +ENVIRON_KEY = "bug_report.caller" + + +@dataclass +class Caller: + email: str = "" + name: str = "" + app: str | None = None + #: the X-Leap-App value a trusted app sent that disagreed with its token (it lost) + app_ignored: str | None = None + #: (status, message) when the request must be refused + error: tuple[int, str] | None = None + + +def _bearer(request) -> str | None: + auth = request.headers.get("Authorization", "") + if auth[:7].lower() == "bearer ": + return auth[7:].strip() or "" + return None + + +def _header(request, name: str) -> str: + # The proxy percent-encodes (a name may not be latin-1); always decode. + return unquote(request.headers.get(name, "")).strip() + + +def trusted_caller(request, trusted_apps: dict, verify_token: Callable | None) -> Caller: + """Resolve who is calling (see the module docstring).""" + token = _bearer(request) + if token is None: + return Caller(error=(401, "a bearer token is required")) + if not token or verify_token is None: + return Caller(error=(401, "bearer token could not be verified")) + try: + claims = verify_token(token) + except Exception: # noqa: BLE001 โ€” any failure to verify is a bad token + return Caller(error=(401, "invalid bearer token")) + if not isinstance(claims, dict): + return Caller(error=(401, "invalid bearer token")) + client = claims.get("azp") or claims.get("appid") + app = trusted_apps.get(client) if isinstance(client, str) else None + if not app: + return Caller(error=(403, "caller is not a trusted app")) + claimed = request.headers.get("X-Leap-App", "").strip() + return Caller( + email=_header(request, "X-Leap-Actor-Email"), + name=_header(request, "X-Leap-Actor-Name"), + app=app, + app_ignored=claimed if claimed and claimed != app else None, + ) + + +class TrustedCallers: + """``trusted_caller`` made ready for ``create_blueprint``:: + + callers = TrustedCallers(TRUSTED_APPS, verify_token) + create_blueprint(store=store, actor_identity=callers.actor_identity, + app_stamp=callers.app_stamp, guard=callers.guard, + is_admin=callers.is_admin_in(BUG_ADMINS)) + """ + + def __init__(self, trusted_apps: dict, verify_token: Callable | None): + self.trusted_apps = dict(trusted_apps) + self.verify_token = verify_token + + def caller(self, request) -> Caller: + c = request.environ.get(ENVIRON_KEY) + if c is None: + c = trusted_caller(request, self.trusted_apps, self.verify_token) + request.environ[ENVIRON_KEY] = c + return c + + def guard(self, request): + """``create_blueprint(guard=...)``: refuse a missing, bad or untrusted token.""" + return self.caller(request).error + + def actor_identity(self, request) -> dict: + c = self.caller(request) + return {"email": c.email, "name": c.name} + + def app_stamp(self, request): + return self.caller(request).app + + def is_admin_in(self, admins) -> Callable: + """``is_admin`` for ``create_blueprint``: the person (not the proxying + app) is on the list. Fails closed on an empty list.""" + allow = {a.strip().lower() for a in admins if a and a.strip()} + + def is_admin(request) -> bool: + c = self.caller(request) + return c.error is None and bool(c.email) and c.email.lower() in allow + return is_admin diff --git a/packages/backend-python/pyproject.toml b/packages/backend-python/pyproject.toml index daf7bb2..d58a16b 100644 --- a/packages/backend-python/pyproject.toml +++ b/packages/backend-python/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "bug-report-py" -version = "2.2.0" +version = "3.0.0" description = "Flask blueprint + storage interface implementing the bug-report-widget API spec." readme = "README.md" license = { text = "MIT" } @@ -11,9 +11,11 @@ dependencies = [ ] [project.optional-dependencies] +postgres = ["psycopg[binary]>=3.1"] email = ["azure-communication-email>=1.0", "azure-identity>=1.15"] test = [ "pytest>=7.0", + "psycopg[binary]>=3.1", ] [build-system] diff --git a/packages/backend-python/tests/conftest.py b/packages/backend-python/tests/conftest.py new file mode 100644 index 0000000..83a1b6b --- /dev/null +++ b/packages/backend-python/tests/conftest.py @@ -0,0 +1,49 @@ +import os +import sys + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # pg_support, under any import mode +import pg_support + + +@pytest.fixture(scope="session") +def pg_dsn(): + holder: list = [] + dsn = pg_support.server_dsn(holder) + try: + if dsn is None: + pg_support.missing_postgres() + yield dsn + finally: + for pg in holder: + pg.stop() + + +@pytest.fixture +def pg_schema(pg_dsn): + """A fresh, empty schema (no tables yet) on the real server.""" + s = pg_support.Schema(pg_dsn) + try: + yield s + finally: + s.drop() + + +@pytest.fixture +def pg_store(pg_schema): + from bug_report.pg import PostgresStore + st = PostgresStore(pg_schema.connect) + st.ensure_schema() + return st + + +@pytest.fixture(params=["memory", "filesystem", "postgres"]) +def any_store(request, tmp_path): + """Every Store, for the scenarios all of them must agree on.""" + from bug_report import FilesystemStore, InMemoryStore + if request.param == "memory": + return InMemoryStore() + if request.param == "postgres": + return request.getfixturevalue("pg_store") + return FilesystemStore(tmp_path / "bugs") diff --git a/packages/backend-python/tests/pg_support.py b/packages/backend-python/tests/pg_support.py new file mode 100644 index 0000000..9629d4a --- /dev/null +++ b/packages/backend-python/tests/pg_support.py @@ -0,0 +1,109 @@ +"""A real PostgreSQL for the tests (practice: a store that talks to a database +is tested against one, never a fake). + +``BUG_REPORT_PG_DSN`` names a server (CI's ``postgres:16`` service container). +Without it, a throwaway Homebrew ``postgresql@16`` is started on a free port +in a temp data dir. Without either the tests SKIP with the recipe, except +under ``CI=true``, where a missing Postgres must FAIL: a skipped suite is +green with nothing run. + +Each test gets its own schema (``search_path``), created fresh and dropped +after, so tests never see each other's rows and need no TRUNCATE. +""" +from __future__ import annotations + +import contextlib +import os +import shutil +import socket +import subprocess +import tempfile +import uuid +from pathlib import Path + +import pytest + +RECIPE = ("set BUG_REPORT_PG_DSN=postgresql://user:pw@host:5432/db (a server you can create " + "schemas on), or `brew install postgresql@16` (initdb/pg_ctl are found in " + "/opt/homebrew/bin or /opt/homebrew/opt/postgresql@16/bin)") + + +def _bin(name: str): + for d in ("/opt/homebrew/bin", "/opt/homebrew/opt/postgresql@16/bin", + "/usr/local/opt/postgresql@16/bin", "/usr/lib/postgresql/16/bin"): + p = Path(d) / name + if p.exists(): + return str(p) + return shutil.which(name) + + +def _free_port() -> int: + with contextlib.closing(socket.socket()) as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +class TempPostgres: + """initdb + pg_ctl on a temp dir; stops and deletes it on exit.""" + + def __init__(self): + self.dir = tempfile.mkdtemp(prefix="brpg-") + self.port = _free_port() + self.dsn = f"postgresql://postgres@127.0.0.1:{self.port}/postgres" + + def start(self) -> str: + data = os.path.join(self.dir, "data") + env = {**os.environ, "LC_ALL": "C"} # macOS: "postmaster became multithreaded" without it + subprocess.run([_bin("initdb"), "-D", data, "-U", "postgres", "--auth=trust", + "-E", "UTF8", "--locale=C"], check=True, capture_output=True, env=env) + subprocess.run([_bin("pg_ctl"), "-D", data, "-w", "-l", os.path.join(self.dir, "log"), + "-o", f"-p {self.port} -c listen_addresses=127.0.0.1 -c unix_socket_directories= " + "-c fsync=off", "start"], check=True, capture_output=True, env=env) + return self.dsn + + def stop(self): + try: + subprocess.run([_bin("pg_ctl"), "-D", os.path.join(self.dir, "data"), "-m", "immediate", + "stop"], capture_output=True, env={**os.environ, "LC_ALL": "C"}) + finally: + shutil.rmtree(self.dir, ignore_errors=True) + + +def server_dsn(tmp_holder: list) -> str | None: + """The server's DSN, or None when there is no Postgres (caller skips/fails).""" + dsn = os.environ.get("BUG_REPORT_PG_DSN") + if dsn: + return dsn + if _bin("initdb") and _bin("pg_ctl"): + pg = TempPostgres() + tmp_holder.append(pg) # stopped (and its dir removed) even when start fails + return pg.start() + return None + + +def missing_postgres(): + """Skip, or FAIL under CI, because there is no Postgres.""" + msg = f"no PostgreSQL available: {RECIPE}" + if os.environ.get("CI", "").lower() in ("1", "true", "yes"): + pytest.fail(msg + " (CI=true: a missing Postgres must fail, not skip)", pytrace=False) + pytest.skip(msg) + + +class Schema: + """One fresh schema on the server, and a connection factory pinned to it.""" + + def __init__(self, dsn: str): + import psycopg + self.dsn = dsn + self.name = f"t_{uuid.uuid4().hex[:12]}" + with psycopg.connect(dsn, autocommit=True) as c: + c.execute(f"CREATE SCHEMA {self.name}") + + def connect(self): + import psycopg + return psycopg.connect(self.dsn, options=f"-c search_path={self.name}") + + def drop(self): + import psycopg + with psycopg.connect(self.dsn, autocommit=True) as c: + c.execute(f"DROP SCHEMA {self.name} CASCADE") diff --git a/packages/backend-python/tests/test_blueprint.py b/packages/backend-python/tests/test_blueprint.py index 675c22c..c5a0345 100644 --- a/packages/backend-python/tests/test_blueprint.py +++ b/packages/backend-python/tests/test_blueprint.py @@ -34,10 +34,12 @@ TINY_JPEG_B64 = base64.b64encode(TINY_JPEG).decode() -@pytest.fixture(params=["memory", "filesystem"]) +@pytest.fixture(params=["memory", "filesystem", "postgres"]) def store(request, tmp_path): if request.param == "memory": return InMemoryStore() + if request.param == "postgres": + return request.getfixturevalue("pg_store") return FilesystemStore(tmp_path / "bugs") diff --git a/packages/backend-python/tests/test_concurrent_patch.py b/packages/backend-python/tests/test_concurrent_patch.py new file mode 100644 index 0000000..8c0d4c3 --- /dev/null +++ b/packages/backend-python/tests/test_concurrent_patch.py @@ -0,0 +1,59 @@ +"""Two PATCHes of different fields of one report must both land (no lost update).""" +import threading + +from flask import Flask + +from bug_report import create_blueprint + +N = 60 + + +def client(store): + app = Flask(__name__) + app.register_blueprint(create_blueprint(store=store, is_admin=lambda r: True, + actor_identity=lambda r: {"email": "a@example.com", "name": ""}), + url_prefix="/api") + return app.test_client() + + +def test_concurrent_patches_of_different_fields_all_land(any_store): + c0 = client(any_store) + bid = c0.post("/api/bugs", json={"details": "race me"}).get_json()["id"] + problems, barrier = [], threading.Barrier(2) + + def worker(field, value_for): + c = client(any_store) + barrier.wait() + for i in range(N): + want = value_for(i) + r = c.patch(f"/api/bugs/{bid}", json={field: want}) + if r.status_code != 200: + problems.append((field, i, r.status_code, r.get_data(as_text=True)[:100])) + continue + # my write must still be there after the other thread's: a stale whole-record write puts the old value back + got = c.get(f"/api/bugs/{bid}").get_json()[field] + if got != want: + problems.append((field, i, "lost", got, want)) + + ts = [threading.Thread(target=worker, args=("area", lambda i: f"area-{i}")), + threading.Thread(target=worker, args=("owner", lambda i: f"owner{i}@example.com"))] + [t.start() for t in ts] + [t.join(60) for t in ts] + assert problems == [] + final = c0.get(f"/api/bugs/{bid}").get_json() + assert (final["area"], final["owner"]) == (f"area-{N-1}", f"owner{N-1}@example.com") + + +def test_concurrent_votes_all_count(any_store): + c0 = client(any_store) + bid = c0.post("/api/bugs", json={"details": "vote race"}).get_json()["id"] + barrier = threading.Barrier(8) + + def vote(n): + barrier.wait() + any_store.add_vote(bid, f"v{n}@example.com") + + ts = [threading.Thread(target=vote, args=(n,)) for n in range(8)] + [t.start() for t in ts] + [t.join(30) for t in ts] + assert any_store.vote_counts([bid])[bid] == 8 diff --git a/packages/backend-python/tests/test_contract.py b/packages/backend-python/tests/test_contract.py index 9e26f56..4f93acf 100644 --- a/packages/backend-python/tests/test_contract.py +++ b/packages/backend-python/tests/test_contract.py @@ -89,3 +89,40 @@ def test_closed_is_defined_by_exclusion(): def test_with_kind_is_idempotent(): payload = {"tags": ["bug", "feature-request"]} assert contract.with_kind(contract.with_kind(payload))["kind"] == "feature" + + +# ---- v3 (2026-11-14) ------------------------------------------------------- + +def test_the_v3_mirror_matches_the_spec(): + assert SPEC["version"] == 3 + assert list(contract.PRODUCTS) == SPEC["products"] + assert dict(contract.APP_PRODUCTS) == SPEC["appProducts"] + assert list(contract.PRIORITIES) == SPEC["priorities"] + assert list(contract.TRIAGE_FIELDS) == SPEC["triageFields"] + assert list(contract.LIST_FILTERS) == SPEC["listFilters"] + + +def test_every_app_maps_to_a_declared_product(): + assert set(SPEC["appProducts"].values()) <= set(SPEC["products"]) + assert SPEC["appProducts"] == {"stoppages": "PikPak", "fleet": "PikPak", "report": "PikPak", + "placements": "Placement", "sealviewer": "Seal", "leaphq": "Internal"} + assert contract.product_for_app("nope") is None and contract.product_for_app(None) is None + + +def test_v3_only_adds_to_v2(): + # nothing a v2 reader relied on is gone + for k in ("id", "title", "kind", "tags", "status", "addedBy", "addedAt", "actorEmail", "screenshot"): + assert k in SPEC["summaryFields"] + for k in ("details", "metaUrl", "metaUserAgent", "metaBuildSha", "audit"): + assert k in SPEC["detailFields"] + assert SPEC["statuses"] == ["open", "triaged", "resolved", "declined"] + assert SPEC["transitions"]["open"] == ["triaged", "declined"] + for k in ("app", "product", "area", "priority", "owner", "parentId", "duplicateOf", "votes"): + assert k in SPEC["summaryFields"] and k in SPEC["example"] + + +def test_a_stored_kind_beats_the_tags_and_an_undeclared_kind_does_not(): + assert contract.effective_kind("feature", ["bug"]) == "feature" + assert contract.effective_kind("capability", ["feature"]) == "feature" # not a kind: fall back to the tags + assert contract.effective_kind(None, []) == "bug" + assert contract.with_kind({"kind": "feature", "tags": ["bug"]})["kind"] == "feature" diff --git a/packages/backend-python/tests/test_identity.py b/packages/backend-python/tests/test_identity.py new file mode 100644 index 0000000..bef5735 --- /dev/null +++ b/packages/backend-python/tests/test_identity.py @@ -0,0 +1,61 @@ +"""bug_report.identity: who the signed-in person is (moved from the apps).""" +import base64 +import json + +import pytest +from flask import Flask + +from bug_report import identity + + +def principal(**claims): + body = {"claims": [{"typ": k, "val": v} for k, v in claims.items()]} + return base64.b64encode(json.dumps(body).encode()).decode() + + +def person(headers=None, remote="203.0.113.9", **opts): + with Flask(__name__).test_request_context("/", headers=headers or {}, + environ_base={"REMOTE_ADDR": remote}): + from flask import request + return identity.trusted_person(request, **opts) + + +def test_easyauth_header_is_believed_only_when_the_app_says_so(): + h = {"X-Ms-Client-Principal": principal(preferred_username="chris@example.com", name="Chris H")} + assert person(h) == {"email": "", "name": ""} # not attached: anyone could send it + assert person(h, trust_easyauth=True) == {"email": "chris@example.com", "name": "Chris H"} + + +def test_a_name_that_is_an_address_is_no_name(): + h = {"X-Ms-Client-Principal": principal(preferred_username="c@example.com", name="c@example.com")} + assert person(h, trust_easyauth=True) == {"email": "c@example.com", "name": ""} + + +def test_email_claim_preference_order_and_malformed_principal(): + h = {"X-Ms-Client-Principal": principal(email="b@example.com", preferred_username="a@example.com")} + assert person(h, trust_easyauth=True)["email"] == "a@example.com" + assert person({"X-Ms-Client-Principal": "%%%not-base64"}, trust_easyauth=True) == {"email": "", "name": ""} + + +def test_tailscale_headers_need_a_loopback_peer(): + h = {"Tailscale-User-Login": "ken@example.com", "Tailscale-User-Name": "Ken M"} + assert person(h, remote="203.0.113.9", loopback_headers=True) == {"email": "", "name": ""} # a LAN peer could forge them + assert person(h, remote="127.0.0.1", loopback_headers=True) == {"email": "ken@example.com", "name": "Ken M"} + assert person(h, remote="::1", loopback_headers=True)["email"] == "ken@example.com" + + +def test_tailscale_headers_are_off_by_default_even_from_loopback(): + h = {"Tailscale-User-Login": "ken@example.com"} + assert person(h, remote="127.0.0.1")["email"] == "" + + +def test_env_flag(): + assert identity.env_flag("X", {"X": "Yes"}) and identity.env_flag("X", {"X": "1"}) + assert not identity.env_flag("X", {"X": "0"}) and not identity.env_flag("X", {}) + + +def test_person_provider_reads_the_current_request(): + prov = identity.person_provider(trust_easyauth=True) + with Flask(__name__).test_request_context( + "/", headers={"X-Ms-Client-Principal": principal(preferred_username="z@example.com")}): + assert prov() == {"email": "z@example.com", "name": ""} diff --git a/packages/backend-python/tests/test_import.py b/packages/backend-python/tests/test_import.py new file mode 100644 index 0000000..97a6019 --- /dev/null +++ b/packages/backend-python/tests/test_import.py @@ -0,0 +1,140 @@ +"""import_reports: ids, audit, screenshots and votes survive; a second run copies nothing.""" +from __future__ import annotations + +import copy +import dataclasses + +import pytest + +from bug_report import FilesystemStore, ImportMismatch, InMemoryStore, import_reports +from bug_report.store import AuditEntry, BugRecord + +SHOT = b"\x89PNG\r\n\x1a\nfake" + + +def seeded(root): + src = FilesystemStore(root) + specs = [("bug-20261101-100000-aaaaaa", "open", True), ("bug-20261102-100000-bbbbbb", "triaged", False), + ("bug-20261103-100000-cccccc", "declined", False), ("bug-20261104-100000-dddddd", "open", False)] + for i, (bid, status, shot) in enumerate(specs): + src.put_bug(BugRecord(id=bid, title=bid, details="d", tags=["bug"], status=status, added_by="web", + actor_email="a@example.com", added_at=f"2026-11-0{i+1}T10:00:00.000000Z"), + SHOT if shot else None) + for j in range(i + 1): + src.append_audit(bid, AuditEntry(changed_at=f"2026-11-0{i+1}T10:0{j}:00Z", to_status=status, + from_status=None if j == 0 else status, note=f"row {j}")) + src.add_vote("bug-20261101-100000-aaaaaa", "v1@example.com") + src.add_vote("bug-20261101-100000-aaaaaa", "v2@example.com") + return src + + +def everything(store): + out = {} + for r in store.list_bugs(status=None, since_iso=""): + try: + shot = store.get_screenshot(r.id) + except Exception: + shot = None + out[r.id] = (dataclasses.asdict(r), [a.to_dict() for a in store.list_audit(r.id)], shot, + sorted(v["voter"] for v in store.list_votes(r.id))) + return out + + +def test_import_into_postgres_keeps_everything_and_a_second_run_copies_nothing(tmp_path, pg_store): + src = seeded(tmp_path / "bugs") + first = import_reports(src, pg_store, app="placements") + assert first["copied"] == {"open": 2, "triaged": 1, "declined": 1} + assert first["skipped"] == {} + assert (first["audit"], first["screenshots"], first["votes"]) == (1 + 2 + 3 + 4, 1, 2) + + got, want = everything(pg_store), everything(src) + snapshot = copy.deepcopy(got) + assert got.keys() == want.keys() + for bid in want: + rec_want, audit_want, shot_want, votes_want = want[bid] + rec_got, audit_got, shot_got, votes_got = got[bid] + assert rec_got.pop("app") == "placements" and rec_want.pop("app") is None # stamped, nothing else changed + assert (rec_got, audit_got, shot_got, votes_got) == (rec_want, audit_want, shot_want, votes_want) + + second = import_reports(src, pg_store, app="placements") + assert second["copied"] == {} + assert second["skipped"] == first["copied"] # the same counts, now all skipped + assert (second["audit"], second["screenshots"], second["votes"]) == (0, 0, 0) + assert everything(pg_store) == snapshot # and nothing changed under it + + +def test_a_source_edited_between_runs_raises_naming_the_ids_and_changes_nothing(tmp_path): + src = seeded(tmp_path / "bugs") + dst = InMemoryStore() + import_reports(src, dst, app="report") + before = everything(dst) + before = copy.deepcopy(before) + edits = { + "status": lambda i: src.update_status(i, "triaged"), + "triage field": lambda i: src.update_fields(i, {"area": "Belt"}), + "vote": lambda i: src.add_vote(i, "late@example.com"), + "audit row": lambda i: src.append_audit(i, AuditEntry(changed_at="2026-12-01T00:00:00Z", to_status="open", note="late")), + } + ids = ["bug-20261101-100000-aaaaaa", "bug-20261103-100000-cccccc", "bug-20261104-100000-dddddd", "bug-20261102-100000-bbbbbb"] + for (label, edit), bid in zip(edits.items(), ids): + edit(bid) + # a report added to the source after the first run would be new, not a difference + with pytest.raises(ImportMismatch) as e: + import_reports(src, dst, app="report") + assert sorted(e.value.ids) == sorted(ids) + assert all(i in str(e.value) for i in ids) + assert everything(dst) == before # nothing was written, new or old + + +def test_the_last_audit_row_is_compared_not_just_the_count(tmp_path): + src = seeded(tmp_path / "bugs") + dst = InMemoryStore() + import_reports(src, dst, app="report") + bid = "bug-20261103-100000-cccccc" + audit_path = src._audit_path(bid) + lines = audit_path.read_text().splitlines() + lines[-1] = lines[-1].replace("row 2", "row EDITED") # same number of rows, last one changed + audit_path.write_text("\n".join(lines) + "\n") + with pytest.raises(ImportMismatch) as e: + import_reports(src, dst, app="report") + assert e.value.ids == [bid] + + +def test_a_run_that_died_half_way_is_reported_not_silently_finished(tmp_path): + src = seeded(tmp_path / "bugs") + dst = InMemoryStore() + bid = "bug-20261104-100000-dddddd" + dst.put_bug(dataclasses.replace(src.get_bug(bid), app="report"), None) # the report, but no audit rows + with pytest.raises(ImportMismatch) as e: + import_reports(src, dst, app="report") + assert e.value.ids == [bid] + + +@pytest.mark.parametrize("bad", ["", "nope", "Placements", None]) +def test_the_app_must_be_one_the_contract_knows_and_nothing_is_touched(tmp_path, bad): + src = seeded(tmp_path / "bugs") + dst = InMemoryStore() + with pytest.raises(ValueError): + import_reports(src, dst, app=bad) + assert list(dst.list_bugs(status=None, since_iso="")) == [] + + +def test_an_app_already_on_a_report_is_kept(tmp_path): + src = seeded(tmp_path / "bugs") + rec = src.get_bug("bug-20261101-100000-aaaaaa") + rec.app = "leaphq" + src.put_bug(rec, None) + dst = InMemoryStore() + import_reports(src, dst, app="sealviewer") + assert dst.get_bug(rec.id).app == "leaphq" + assert dst.get_bug("bug-20261102-100000-bbbbbb").app == "sealviewer" + + +def test_the_copy_does_not_alias_the_source_record(): + src = InMemoryStore() + rec = BugRecord(id="bug-20261101-100000-aaaaaa", title="t", details="d", tags=[], status="open", + added_by="web", actor_email="", added_at="2026-11-01T10:00:00.000000Z") + src.put_bug(rec, None) + dst = InMemoryStore() + import_reports(src, dst, app="report") + assert src.get_bug(rec.id).app is None and dst.get_bug(rec.id).app == "report" diff --git a/packages/backend-python/tests/test_pg_store.py b/packages/backend-python/tests/test_pg_store.py new file mode 100644 index 0000000..5a77120 --- /dev/null +++ b/packages/backend-python/tests/test_pg_store.py @@ -0,0 +1,143 @@ +"""PostgresStore against a real Postgres (see pg_support.py).""" +from __future__ import annotations + +import dataclasses + +import pytest + +from bug_report import FilesystemStore +from bug_report.pg import PostgresStore +from bug_report.store import AuditEntry, BugRecord, NotFound, StoreError + + +def bug(i=1, **over): + r = BugRecord(id=f"bug-2026110{i}-120000-abc00{i}", title=f"bug {i}", details="it broke", + tags=["ui"], status="open", added_by="Ken", actor_email="ken@example.com", + added_at=f"2026-11-0{i}T12:00:00.000000Z", meta_url="https://hq/x", + transcript=[{"role": "user", "text": "hi"}], actor_name="Ken") + for k, v in over.items(): + setattr(r, k, v) + return r + + +def test_the_record_jsonb_is_what_the_filesystem_store_writes(pg_store, tmp_path): + b = bug(1, app="stoppages", area="Clips", priority="now", parent_id=None) + fs = FilesystemStore(tmp_path) + fs.put_bug(dataclasses.replace(b), b"\x89PNG..") + pg_store.put_bug(dataclasses.replace(b), b"\x89PNG..") + import json + on_disk = json.loads((tmp_path / f"{b.id}.json").read_text()) + with pg_store._connect() as conn: + (stored,) = conn.execute("SELECT record FROM reports WHERE id=%s", (b.id,)).fetchone() + assert stored == on_disk # same JSON, key for key + assert pg_store.get_bug(b.id) == fs.get_bug(b.id) + assert pg_store.get_screenshot(b.id) == b"\x89PNG.." + + +def test_lifted_columns_follow_the_record(pg_store): + b = bug(1, app="fleet", area="Belt", priority="later", owner="o@example.com", + parent_id="bug-20261102-120000-abc002", duplicate_of="bug-20261103-120000-abc003", + tags=["feature"]) + pg_store.put_bug(b, None) + with pg_store._connect() as conn: + row = conn.execute("SELECT app, kind, status, area, priority, owner, parent_id, duplicate_of " + "FROM reports WHERE id=%s", (b.id,)).fetchone() + assert row == ("fleet", "feature", "open", "Belt", "later", "o@example.com", + "bug-20261102-120000-abc002", "bug-20261103-120000-abc003") + + +def test_not_found(pg_store): + with pytest.raises(NotFound): + pg_store.get_bug("bug-20200101-000000-aaaaaa") + with pytest.raises(NotFound): + pg_store.get_screenshot("bug-20200101-000000-aaaaaa") + pg_store.put_bug(bug(1), None) + with pytest.raises(NotFound): + pg_store.get_screenshot(bug(1).id) # a report without one + with pytest.raises(NotFound): + pg_store.add_vote("bug-20200101-000000-aaaaaa", "a@example.com") + + +def test_a_resave_keeps_the_screenshot_it_has(pg_store): + b = bug(1) + pg_store.put_bug(b, b"shot") + pg_store.update_status(b.id, "triaged") + pg_store.update_fields(b.id, {"area": "x"}) + assert pg_store.get_screenshot(b.id) == b"shot" + assert pg_store.get_bug(b.id).screenshot is True + + +def test_list_filters_agree_with_the_filesystem_store(pg_store, tmp_path): + fs = FilesystemStore(tmp_path) + rows = [bug(1, app="fleet", area="A", priority="now"), + bug(2, status="triaged", app="sealviewer", tags=["feature"]), + bug(3, app="fleet", priority="later", kind="feature")] + for st in (pg_store, fs): + for r in rows: + st.put_bug(dataclasses.replace(r), None) + queries = [dict(status=None, since_iso=""), dict(status="open", since_iso=""), + dict(status=None, since_iso="2026-11-02T00:00:00Z"), + dict(status=None, since_iso="", app="fleet"), dict(status=None, since_iso="", kind="feature"), + dict(status=None, since_iso="", area="A"), dict(status=None, since_iso="", priority="later"), + dict(status="open", since_iso="", app="fleet", kind="feature")] + for q in queries: + assert sorted(r.id for r in pg_store.list_bugs(**q)) == sorted(r.id for r in fs.list_bugs(**q)), q + assert [r.id for r in pg_store.list_bugs(status=None, since_iso="")] == [r.id for r in rows] # oldest first + + +def test_audit_keeps_order_and_every_field(pg_store): + b = bug(1) + pg_store.put_bug(b, None) + entries = [AuditEntry(changed_at=f"2026-11-0{i}T00:00:00Z", to_status="open", from_status=None, + changed_by="a@example.com", changed_by_name="A", note=f"n{i}") for i in range(1, 6)] + for e in entries: + pg_store.append_audit(b.id, e) + assert pg_store.list_audit(b.id) == entries + assert pg_store.list_audit("bug-20200101-000000-aaaaaa") == [] + + +def test_votes_are_one_per_person_counted_and_listed(pg_store): + a, b = bug(1), bug(2) + pg_store.put_bug(a, None) + pg_store.put_bug(b, None) + assert pg_store.add_vote(a.id, "X@example.com") is True + assert pg_store.add_vote(a.id, "x@example.com") is False + assert pg_store.add_vote(a.id, "y@example.com", at="2026-01-01T00:00:00Z") is True + assert pg_store.vote_counts([a.id, b.id, "nope"]) == {a.id: 2, b.id: 0, "nope": 0} + assert pg_store.vote_counts([]) == {} + assert pg_store.list_votes(a.id)[0] == {"voter": "y@example.com", "at": "2026-01-01T00:00:00Z"} + assert pg_store.remove_vote(a.id, "Y@example.com") is True + assert pg_store.remove_vote(a.id, "y@example.com") is False + + +def test_update_fields_refuses_what_is_not_a_triage_field(pg_store): + pg_store.put_bug(bug(1), None) + with pytest.raises(StoreError): + pg_store.update_fields(bug(1).id, {"status": "resolved"}) + + +def test_ensure_schema_is_idempotent_and_keeps_rows(pg_store): + pg_store.put_bug(bug(1), None) + pg_store.ensure_schema() + pg_store.ensure_schema() + assert pg_store.get_bug(bug(1).id).title == "bug 1" + + +def test_a_connection_is_taken_per_operation_from_the_factory(pg_schema): + taken = [] + + def factory(): + taken.append(1) + return pg_schema.connect() + st = PostgresStore(factory) + st.ensure_schema() + st.put_bug(bug(1), None) + st.get_bug(bug(1).id) + assert len(taken) == 3 # so a service can hand out a fresh Entra-token password each time + + +def test_a_database_that_is_down_is_a_store_error_not_a_driver_exception(pg_dsn): + import psycopg + st = PostgresStore(lambda: psycopg.connect("postgresql://postgres@127.0.0.1:1/x", connect_timeout=1)) + with pytest.raises(StoreError): + st.get_bug("bug-20200101-000000-aaaaaa") diff --git a/packages/backend-python/tests/test_proxy.py b/packages/backend-python/tests/test_proxy.py new file mode 100644 index 0000000..4b3790d --- /dev/null +++ b/packages/backend-python/tests/test_proxy.py @@ -0,0 +1,255 @@ +"""create_proxy_blueprint, end to end: a real central blueprint served over HTTP, +the proxy app in front of it, fake token and person providers.""" +from __future__ import annotations + +import base64 +import json +import threading + +import pytest +from flask import Flask, request +from werkzeug.serving import make_server + +from bug_report import FilesystemStore, TrustedCallers, create_blueprint, create_proxy_blueprint + +PNG = bytes.fromhex("89504E470D0A1A0A0000000D49484452000000010000000108060000001F15C4890000000D" + "49444154789C6300010000000500010D0A2DB40000000049454E44AE426082") +JPEG = bytes.fromhex("FFD8FFE000104A46494600010100000100010000FFD9") +APP_CLIENTS = {"client-placements": "placements", "client-seal": "sealviewer"} +ADMINS = ["admin@example.com"] + + +def verify(token): + if not token.startswith("ok:"): + raise ValueError("bad token") + return {"azp": token[3:]} + + +class Serving: + def __init__(self, flask_app): + self.srv = make_server("127.0.0.1", 0, flask_app, threaded=True) + self.port = self.srv.server_port + self.t = threading.Thread(target=self.srv.serve_forever, daemon=True) + self.t.start() + + @property + def url(self): + return f"http://127.0.0.1:{self.port}" + + def stop(self): + self.srv.shutdown() + self.t.join(3) + + +@pytest.fixture +def central(tmp_path): + seen = [] + store = FilesystemStore(tmp_path / "central") + callers = TrustedCallers(APP_CLIENTS, verify) + app = Flask(__name__) + app.register_blueprint(create_blueprint( + store=store, is_admin=callers.is_admin_in(ADMINS), actor_identity=callers.actor_identity, + app_stamp=callers.app_stamp, guard=callers.guard)) + + @app.before_request + def spy(): + seen.append({k: v for k, v in request.headers.items()}) + + s = Serving(app) + yield s, store, seen + s.stop() + + +class Front: + """The app side: a proxy mounted at /api, with providers a test can change.""" + def __init__(self, central_url, app_name="placements"): + self.token = ["ok:client-placements"] + self.person = [{"email": "admin@example.com", "name": "Ann Admin"}] + flask_app = Flask(__name__) + flask_app.register_blueprint(create_proxy_blueprint( + central_url + "/bugs", app_name, lambda: self.token[0], lambda: self.person[0]), + url_prefix="/api") + self.c = flask_app.test_client() + + +@pytest.fixture +def front(central): + return Front(central[0].url) + + +def file(front, **kw): + r = front.c.post("/api/bugs", json={"details": "it broke", **kw}) + assert r.status_code == 201, r.data + return r.get_json()["id"] + + +def test_post_is_stamped_with_the_apps_name_and_the_signed_in_person(front, central): + _, store, _ = central + r = front.c.post("/api/bugs", json={"details": "it broke", "app": "leaphq", + "actorEmail": "liar@example.com"}) + assert r.status_code == 201 and r.content_type == "application/json" + assert r.get_json()["app"] == "placements" + rec = store.get_bug(r.get_json()["id"]) + assert (rec.app, rec.actor_email, rec.actor_name) == ("placements", "admin@example.com", "Ann Admin") + + +def test_the_forwarded_request_carries_the_four_headers(front, central): + _, _, seen = central + front.c.post("/api/bugs", json={"details": "x"}, + headers={"Authorization": "Bearer browser-claim", "X-Leap-Actor-Email": "liar@example.com", + "X-Leap-App": "leaphq"}) + h = seen[-1] + assert h["Authorization"] == "Bearer ok:client-placements" # the app's, not the page's + assert h["X-Leap-Actor-Email"] == "admin@example.com" + assert h["X-Leap-Actor-Name"] == "Ann Admin" + assert h["X-Leap-App"] == "placements" + + +def test_every_route_goes_through_with_status_body_and_content_type_unchanged(front, central): + bid = file(front, screenshot=base64.b64encode(JPEG).decode(), tags=["feature"]) + # list (admin) + r = front.c.get("/api/bugs?days=1&kind=feature&app=placements") + assert r.status_code == 200 and [b["id"] for b in r.get_json()["bugs"]] == [bid] + # detail + d = front.c.get(f"/api/bugs/{bid}").get_json() + assert d["app"] == "placements" and d["product"] == "Placement" and d["votes"] == 0 + # patch: status and triage fields + r = front.c.patch(f"/api/bugs/{bid}", json={"status": "triaged", "area": "Belt", "priority": "now"}) + assert r.status_code == 200 and r.get_json()["area"] == "Belt" + assert r.get_json()["audit"][-1]["changedBy"] == "admin@example.com" + # vote and unvote + assert front.c.post(f"/api/bugs/{bid}/vote").get_json() == {"votes": 1, "voted": True} + assert front.c.delete(f"/api/bugs/{bid}/vote").get_json() == {"votes": 0, "voted": False} + # screenshot: bytes and the sniffed type + r = front.c.get(f"/api/bugs/{bid}/screenshot") + assert (r.status_code, r.content_type, r.data) == (200, "image/jpeg", JPEG) + # errors keep their status and body + r = front.c.get("/api/bugs/bug-20200101-000000-aaaaaa") + assert (r.status_code, r.get_json()) == (404, {"error": "not found"}) + assert front.c.get("/api/bugs/junk").status_code == 400 + assert front.c.post("/api/bugs", json={}).status_code == 400 + big = front.c.post("/api/bugs", json={"details": "x" * (10 * 1024 + 1)}) + assert big.status_code == 413 + + +def test_a_non_admin_person_gets_the_central_403_through_the_proxy(front): + bid = file(front) + front.person[0] = {"email": "someone@example.com", "name": ""} + r = front.c.get("/api/bugs") + assert r.status_code == 403 + assert front.c.patch(f"/api/bugs/{bid}", json={"area": "x"}).status_code == 403 + assert front.c.post(f"/api/bugs/{bid}/vote").status_code == 200 # voting is for anyone signed in + + +def test_an_untrusted_app_token_is_refused_403_on_every_route(front): + bid = file(front) + front.token[0] = "ok:client-stranger" + for method, path in (("post", "/api/bugs"), ("get", "/api/bugs"), ("get", f"/api/bugs/{bid}"), + ("patch", f"/api/bugs/{bid}"), ("post", f"/api/bugs/{bid}/vote"), + ("get", f"/api/bugs/{bid}/screenshot")): + r = getattr(front.c, method)(path, json={"details": "x", "status": "triaged"} if method != "get" else None) + assert r.status_code == 403, (method, path) + assert r.get_json()["error"] == "caller is not a trusted app" + + +def test_a_token_that_does_not_verify_is_401(front): + front.token[0] = "forged" + r = front.c.post("/api/bugs", json={"details": "x"}) + assert r.status_code == 401 + + +def test_x_leap_app_that_disagrees_with_the_token_loses_and_the_response_says_so(central): + s, store, _ = central + f = Front(s.url, app_name="leaphq") # the proxy CLAIMS leaphq... + f.token[0] = "ok:client-seal" # ...but its token is the seal viewer's + r = f.c.post("/api/bugs", json={"details": "x"}) + assert r.status_code == 201 + body = r.get_json() + assert body["app"] == "sealviewer" and body["appIgnored"] == "leaphq" + assert r.headers["X-Leap-App-Used"] == "sealviewer" and r.headers["X-Leap-App-Ignored"] == "leaphq" + assert store.get_bug(body["id"]).app == "sealviewer" + + +def test_a_name_with_accents_survives_the_header(front, central): + _, store, _ = central + front.person[0] = {"email": "sean@example.com", "name": "Seรกn ร“ Briain"} + bid = file(front) + assert store.get_bug(bid).actor_name == "Seรกn ร“ Briain" + + +def test_a_central_that_is_down_is_a_502_with_a_message(): + f = Front("http://127.0.0.1:9") + r = f.c.post("/api/bugs", json={"details": "x"}) + assert r.status_code == 502 and r.get_json() == {"error": "the reports service is not reachable"} # no host, no reason + + +def test_a_token_provider_that_fails_is_a_502_never_an_unauthenticated_call(central): + s, _, seen = central + def boom(): + raise RuntimeError("no managed identity here") + app = Flask(__name__) + app.register_blueprint(create_proxy_blueprint(s.url + "/bugs", "placements", boom, lambda: {}), url_prefix="/api") + r = app.test_client().post("/api/bugs", json={"details": "x"}) + assert r.status_code == 502 and r.get_json() == {"error": "could not authenticate to the reports service"} + assert "managed identity" not in r.get_data(as_text=True) # the exception text stays in the log + assert seen == [] # nothing reached the service + + +def test_a_redirect_from_the_service_is_passed_on_not_followed(): + other = Flask(__name__) + + @other.route("/bugs//screenshot") + def shot(i): + from flask import redirect + return redirect("https://blob.example/signed?sig=1", 302) + + s = Serving(other) + try: + f = Front(s.url) + r = f.c.get("/api/bugs/bug-20261101-100000-aaaaaa/screenshot") + assert r.status_code == 302 and r.headers["Location"] == "https://blob.example/signed?sig=1" + finally: + s.stop() + + +def test_a_non_json_body_and_content_type_come_back_untouched(): + other = Flask(__name__) + + @other.route("/bugs") + def lst(): + return "plain text โœ“", 200, {"Content-Type": "text/plain; charset=utf-8"} + + s = Serving(other) + try: + r = Front(s.url).c.get("/api/bugs") + assert (r.status_code, r.content_type, r.data.decode()) == (200, "text/plain; charset=utf-8", "plain text โœ“") + finally: + s.stop() + + +def test_a_dot_dot_path_segment_is_refused_400_and_never_forwarded(front, central): + _, _, seen = central + n = len(seen) + for path in ("/api/bugs/../admin", "/api/bugs/bug-20261101-100000-aaaaaa/../../x", "/api/bugs/./x"): + r = front.c.get(path) + assert r.status_code in (400, 404), path # werkzeug may normalise `..` away before the route + r = front.c.open("/api/bugs/%2e%2e/admin") + assert r.status_code == 400 and r.get_json() == {"error": "invalid path"} + r = front.c.open("/api/bugs/x%5Cy") + assert r.status_code == 400 + assert len(seen) == n + + +def test_the_central_service_itself_refuses_a_request_with_no_token(central): + import urllib.error + import urllib.request + s, _, _ = central + for headers in ({}, {"X-Leap-Actor-Email": "admin@example.com", "X-Leap-App": "leaphq"}, + {"X-Ms-Client-Principal": base64.b64encode(json.dumps( + {"claims": [{"typ": "preferred_username", "val": "admin@example.com"}]}).encode()).decode()}): + req = urllib.request.Request(s.url + "/bugs", data=b'{"details": "x"}', headers={"Content-Type": "application/json", **headers}) + try: + urllib.request.urlopen(req) + raise AssertionError("expected 401") + except urllib.error.HTTPError as e: + assert e.code == 401 diff --git a/packages/backend-python/tests/test_spec_drift.py b/packages/backend-python/tests/test_spec_drift.py index dd5ad73..a293f90 100644 --- a/packages/backend-python/tests/test_spec_drift.py +++ b/packages/backend-python/tests/test_spec_drift.py @@ -56,6 +56,12 @@ def test_every_field_the_server_sends_is_in_the_spec(tmp_path): c = _client(tmp_path) bid = c.post("/api/bugs", json={"title": "t", "details": "d", "metaUrl": "https://x/"}).get_json()["id"] c.patch(f"/api/bugs/{bid}", json={"status": "triaged", "note": ""}) + other = c.post("/api/bugs", json={"details": "other"}).get_json()["id"] + triaged = c.patch(f"/api/bugs/{bid}", json={"area": "Belt", "priority": "now", "owner": "a@example.com", + "parentId": other}).get_json() + voted = c.post(f"/api/bugs/{bid}/vote").get_json() + dup = c.patch(f"/api/bugs/{other}", json={"duplicateOf": bid}).get_json() + created = c.post("/api/bugs", json={"details": "again"}).get_json() closed = c.patch(f"/api/bugs/{bid}", json={"status": "resolved", "note": "done", "notify": True}).get_json() detail = c.get(f"/api/bugs/{bid}").get_json() summary = c.get("/api/bugs?days=1").get_json()["bugs"][0] @@ -67,7 +73,58 @@ def test_every_field_the_server_sends_is_in_the_spec(tmp_path): assert set(summary) - summary_spec == set() assert set(detail) - bug_spec == set() + # and the other way: every property the spec names is one the server really sends + # (`notified` appears on a PATCH response only; `canNotify` on a detail read only) + assert summary_spec - set(summary) == set(), "the spec promises a summary field the server does not send" + assert bug_spec - {"notified"} - set(detail) == set(), "the spec promises a detail field the server does not send" + assert audit_spec - set(closed["audit"][0]) == set(), "the spec promises an audit field the server does not send" assert set(closed) - bug_spec == set() for row in closed["audit"]: assert set(row) - audit_spec == set() assert set(closed["notified"]) <= {"ok", "to", "error"} + # v3: the triage fields, the duplicate decline and the new response shapes + for resp in (triaged, dup): + assert set(resp) - bug_spec == set() + for row in resp["audit"]: + assert set(row) - audit_spec == set() + assert {"area", "priority", "owner", "parentId", "duplicateOf", "votes", "app", "product", "kind"} <= set(summary) + assert set(voted) == _schema_properties("Voted") + assert set(created) <= _schema_properties_of_created() + + +def _schema_properties_of_created() -> set[str]: + """The 201 body's properties, read from the createBug response (an inline schema).""" + text = SPEC.read_text() + block = text[text.index("operationId: createBug"):text.index('"400":')] + after = block[block.index('"201":'):] + return set(re.findall(r"^ {18}(\w+):\s*$", after, re.M)) + + +def test_every_contract_summary_field_is_a_bugsummary_property_in_the_spec(): + import json + contract_json = json.loads((SPEC.parent / "report-contract.json").read_text()) + assert set(contract_json["summaryFields"]) - _schema_properties("BugSummary") == set() + + +def test_the_vote_route_the_list_filters_and_the_patch_fields_are_in_the_spec(): + text = SPEC.read_text() + assert "/bugs/{id}/vote:" in text and "operationId: voteBug" in text and "operationId: unvoteBug" in text + for filt in ("app", "kind", "area", "priority"): + assert f"name: {filt}\n" in text + patch = text[text.index("operationId: patchBug"):text.index("/bugs/{id}/vote:")] + for field in ("area:", "priority:", "owner:", "parentId:", "duplicateOf:"): + assert field in patch + assert "required: [status]" not in patch + + +def test_types_py_and_types_ts_name_every_v3_summary_field(): + import json + fields = json.loads((SPEC.parent / "report-contract.json").read_text())["summaryFields"] + # inside BugSummary only: BugPatch and BugCreate name some of the same fields + py = (SPEC.parent / "types.py").read_text() + py = py[py.index("class BugSummary"):py.index("class AuditEntry")] + ts = (SPEC.parent / "types.ts").read_text() + ts = ts[ts.index("export interface BugSummary"):ts.index("export interface AuditEntry")] + for f in fields: + assert re.search(rf"^\s+{f}\??:", ts, re.M), f"types.ts BugSummary lacks {f}" + assert re.search(rf"^\s+{f}:", py, re.M), f"types.py BugSummary lacks {f}" diff --git a/packages/backend-python/tests/test_trust.py b/packages/backend-python/tests/test_trust.py new file mode 100644 index 0000000..566fbe4 --- /dev/null +++ b/packages/backend-python/tests/test_trust.py @@ -0,0 +1,160 @@ +"""trusted_caller: a trusted app's headers are believed only behind a verified token.""" +import base64 +import json + +import pytest +from flask import Flask, request + +from bug_report import contract +from bug_report.trust import TrustedCallers, trusted_caller + +PLACEMENTS_ID, SEAL_ID = "client-placements", "client-seal" +TRUSTED = {PLACEMENTS_ID: "placements", SEAL_ID: "sealviewer"} + + +def verify(token): + """A fake verifier: tokens are `ok:=`; anything else raises.""" + if not token.startswith("ok:"): + raise ValueError("bad signature") + k, v = token[3:].split("=", 1) + return {k: v} + + +def principal(**claims): + body = {"claims": [{"typ": k, "val": v} for k, v in claims.items()]} + return base64.b64encode(json.dumps(body).encode()).decode() + + +def caller(headers=None, json_body=None, method="POST", verifier=verify, trusted=TRUSTED, remote="203.0.113.9"): + with Flask(__name__).test_request_context("/", method=method, headers=headers or {}, json=json_body, + environ_base={"REMOTE_ADDR": remote}): + return trusted_caller(request, trusted, verifier) + + +def app_headers(azp=PLACEMENTS_ID, claim="azp", **extra): + return {"Authorization": f"Bearer ok:{claim}={azp}", "X-Leap-Actor-Email": "chris@example.com", + "X-Leap-Actor-Name": "Chris H", **extra} + + +def test_a_trusted_app_is_believed_and_the_app_name_comes_from_its_token(): + c = caller(app_headers(**{"X-Leap-App": "placements"})) + assert (c.error, c.app, c.email, c.name, c.app_ignored) == ( + None, "placements", "chris@example.com", "Chris H", None) + + +def test_the_appid_claim_spelling_works_too(): + c = caller(app_headers(azp=SEAL_ID, claim="appid")) + assert (c.error, c.app) == (None, "sealviewer") + + +def test_x_leap_app_loses_to_the_token_and_the_caller_says_which_won(): + c = caller(app_headers(**{"X-Leap-App": "leaphq"})) + assert c.app == "placements" and c.app_ignored == "leaphq" + + +def test_a_percent_encoded_name_is_decoded(): + c = caller({**app_headers(), "X-Leap-Actor-Name": "Se%C3%A1n O%27Brien"}) + assert c.name == "Seรกn O'Brien" + + + + + + +def test_a_token_for_an_untrusted_app_is_refused_403_and_never_falls_back(): + c = caller({**app_headers(azp="client-stranger"), + "X-Ms-Client-Principal": principal(preferred_username="real@example.com")}) + assert c.error[0] == 403 and c.email == "" and c.app is None + + +def test_a_verifier_that_raises_is_401_and_never_falls_back(): + c = caller({"Authorization": "Bearer forged", "X-Leap-Actor-Email": "boss@example.com", + "X-Ms-Client-Principal": principal(preferred_username="real@example.com")}) + assert c.error[0] == 401 and c.email == "" + + +@pytest.mark.parametrize("auth", ["Bearer ", "Bearer "]) +def test_an_empty_bearer_is_401(auth): + assert caller({"Authorization": auth}).error[0] == 401 + + +def test_a_verifier_answering_something_other_than_claims_is_401(): + assert caller(app_headers(), verifier=lambda t: "yes").error[0] == 401 + + +def test_a_bearer_with_no_verifier_configured_is_401_not_trusted(): + assert caller(app_headers(), verifier=None).error[0] == 401 + + +def test_a_token_with_no_azp_or_appid_is_403(): + assert caller({"Authorization": "Bearer ok:sub=someone"}).error[0] == 403 + + + + +def test_a_trusted_apps_body_app_is_ignored(): + assert caller(app_headers(), {"details": "x", "app": "leaphq"}).app == "placements" + + +def test_every_trusted_app_name_the_contract_knows_is_a_real_app(): + # the service's TRUSTED_APPS values must be apps with a product + for app in ("stoppages", "fleet", "report", "placements", "sealviewer", "leaphq"): + assert contract.product_for_app(app) + + +def test_trusted_callers_caches_per_request_and_exposes_the_hooks(): + calls = [] + tc = TrustedCallers(TRUSTED, lambda t: (calls.append(t), verify(t))[1]) + with Flask(__name__).test_request_context("/", headers=app_headers()): + assert tc.guard(request) is None + assert tc.app_stamp(request) == "placements" + assert tc.actor_identity(request) == {"email": "chris@example.com", "name": "Chris H"} + assert len(calls) == 1 # the token is verified once per request + + +def test_is_admin_in_is_about_the_person_not_the_app_and_fails_closed(): + tc = TrustedCallers(TRUSTED, verify) + admin = tc.is_admin_in(["Chris@Example.com"]) + with Flask(__name__).test_request_context("/", headers=app_headers()): + assert admin(request) is True + with Flask(__name__).test_request_context("/", headers={**app_headers(), "X-Leap-Actor-Email": "o@example.com"}): + assert admin(request) is False + with Flask(__name__).test_request_context("/", headers=app_headers(azp="client-stranger")): + assert admin(request) is False + with Flask(__name__).test_request_context("/", headers=app_headers()): + assert tc.is_admin_in([])(request) is False + + +# ---- no person path (Ken, 2026-11-14): every request needs an app token -------- + +def test_no_bearer_token_is_401_even_with_actor_headers_and_a_forged_gateway_principal(): + forged = {"X-Ms-Client-Principal": principal(preferred_username="boss@example.com", name="Boss"), + "X-Leap-Actor-Email": "boss@example.com", "X-Leap-Actor-Name": "Boss", "X-Leap-App": "leaphq", + "Tailscale-User-Login": "boss@example.com"} + for remote in ("203.0.113.9", "127.0.0.1"): # a loopback peer changes nothing either + c = caller(forged, remote=remote) + assert c.error[0] == 401 and (c.email, c.name, c.app) == ("", "", None), remote + assert caller({}).error[0] == 401 + + +def test_there_is_no_option_to_turn_the_gateway_principal_on(): + # `trust_easyauth` belongs to an app's own trusted_person(); asking the service for it is an error, not a no-op + with Flask(__name__).test_request_context("/", headers={"X-Ms-Client-Principal": principal(preferred_username="b@example.com")}): + with pytest.raises(TypeError): + trusted_caller(request, TRUSTED, verify, trust_easyauth=True) + with pytest.raises(TypeError): + TrustedCallers(TRUSTED, verify, trust_easyauth=True) + + +def test_the_guard_refuses_a_forged_principal_with_401_on_the_blueprint(): + from bug_report import InMemoryStore, create_blueprint + callers = TrustedCallers(TRUSTED, verify) + app = Flask(__name__) + app.register_blueprint(create_blueprint(store=InMemoryStore(), guard=callers.guard, + actor_identity=callers.actor_identity, app_stamp=callers.app_stamp)) + c = app.test_client() + r = c.post("/bugs", json={"details": "x"}, headers={"X-Ms-Client-Principal": principal(preferred_username="b@example.com")}) + assert r.status_code == 401 + for method, path in (("get", "/bugs"), ("get", "/bugs/bug-20261101-100000-aaaaaa"), ("get", "/bugs/bug-20261101-100000-aaaaaa/screenshot"), + ("post", "/bugs/bug-20261101-100000-aaaaaa/vote")): + assert getattr(c, method)(path).status_code == 401, path diff --git a/packages/backend-python/tests/test_v3_triage.py b/packages/backend-python/tests/test_v3_triage.py new file mode 100644 index 0000000..43f2ad5 --- /dev/null +++ b/packages/backend-python/tests/test_v3_triage.py @@ -0,0 +1,305 @@ +"""Contract v3 through the blueprint, on every store: triage fields, duplicates, +votes, filters, and a v2 record reading back.""" +from __future__ import annotations + +import json + +import pytest +from flask import Flask + +from bug_report import FilesystemStore, create_blueprint, contract +from bug_report.store import BugRecord + +ADMIN = "admin@example.com" + + +def make_client(store, *, who=ADMIN, app_stamp=None): + """A client whose caller is `who` (a mutable one-item list, so a test can switch person).""" + cur = [who] + app = Flask(__name__) + app.register_blueprint(create_blueprint( + store=store, is_admin=lambda r: True, + actor_identity=lambda r: {"email": cur[0], "name": ""} if cur[0] else "", + app_stamp=app_stamp, + ), url_prefix="/api") + c = app.test_client() + c.person = cur + return c + + +@pytest.fixture +def client(any_store): + return make_client(any_store) + + +def file_bug(c, **kw): + r = c.post("/api/bugs", json={"details": "something broke", **kw}) + assert r.status_code == 201, r.get_json() + return r.get_json()["id"] + + +def patch(c, bid, **body): + return c.patch(f"/api/bugs/{bid}", json=body) + + +# ---- triage fields --------------------------------------------------------- + +def test_triage_fields_set_without_a_status_change_and_audited(client): + bid = file_bug(client) + r = patch(client, bid, area="Cutter", priority="now", owner="sam@example.com") + assert r.status_code == 200, r.get_json() + d = r.get_json() + assert (d["area"], d["priority"], d["owner"], d["status"]) == ("Cutter", "now", "sam@example.com", "open") + rows = d["audit"] + assert len(rows) == 2 # filed + ONE row for the fields + assert rows[1]["note"] == "area: none -> Cutter; priority: none -> now; owner: none -> sam@example.com" + assert rows[1]["fromStatus"] == rows[1]["toStatus"] == "open" + assert rows[1]["changedBy"] == ADMIN + # read back through GET and the list + assert client.get(f"/api/bugs/{bid}").get_json()["area"] == "Cutter" + assert client.get("/api/bugs?days=1").get_json()["bugs"][0]["priority"] == "now" + + +def test_triage_fields_with_a_status_change_write_two_rows(client): + bid = file_bug(client) + d = patch(client, bid, status="triaged", note="looking", area="Belt").get_json() + assert [(a["toStatus"], a["note"]) for a in d["audit"][1:]] == [ + ("triaged", "looking"), ("triaged", "area: none -> Belt")] + + +def test_an_unchanged_triage_value_is_a_no_op_with_no_audit_row(client): + bid = file_bug(client) + patch(client, bid, area="Belt") + d = patch(client, bid, area="Belt").get_json() + assert len(d["audit"]) == 2 + + +def test_null_or_empty_clears_a_field_and_says_so(client): + bid = file_bug(client) + patch(client, bid, area="Belt", priority="later") + d = patch(client, bid, area=None, priority="").get_json() + assert d["area"] is None and d["priority"] is None + assert d["audit"][-1]["note"] == "area: Belt -> none; priority: later -> none" + + +@pytest.mark.parametrize("body", [ + {"priority": "urgent"}, {"owner": "not-an-email"}, {"area": "x" * 101}, + {"parentId": "nope"}, {"duplicateOf": "nope"}, +]) +def test_bad_triage_values_are_400(client, body): + bid = file_bug(client) + assert patch(client, bid, **body).status_code == 400 + + +def test_a_patch_with_neither_status_nor_triage_field_is_still_400(client): + bid = file_bug(client) + assert patch(client, bid, note="hi").status_code == 400 + + +def test_parent_must_exist_not_be_itself_and_not_loop(client): + a, b = file_bug(client), file_bug(client) + assert patch(client, a, parentId="bug-20200101-000000-aaaaaa").status_code == 404 + assert patch(client, a, parentId=a).status_code == 400 + assert patch(client, a, parentId=b).status_code == 200 # b is a's parent + r = patch(client, b, parentId=a) # a is b's parent too: a loop + assert r.status_code == 400 and "cycle" in r.get_json()["error"] + assert client.get(f"/api/bugs/{a}").get_json()["parentId"] == b + + +def test_duplicate_of_declines_with_the_note(client): + a, b = file_bug(client), file_bug(client) + d = patch(client, b, duplicateOf=a).get_json() + assert d["status"] == "declined" and d["duplicateOf"] == a + assert d["audit"][-1]["toStatus"] == "declined" + assert d["audit"][-1]["note"] == f"duplicate of {a}" + assert len(d["audit"]) == 2 # the decline row IS the record of the change + + +def test_duplicate_of_conflicting_status_is_400_and_a_resolved_report_cannot_be_declined(client): + a, b, c3 = file_bug(client), file_bug(client), file_bug(client) + assert patch(client, b, duplicateOf=a, status="triaged").status_code == 400 + assert client.get(f"/api/bugs/{b}").get_json()["status"] == "open" # nothing half-applied + patch(client, c3, status="triaged") + patch(client, c3, status="resolved") + r = patch(client, c3, duplicateOf=a) + assert r.status_code == 409 + assert client.get(f"/api/bugs/{c3}").get_json()["duplicateOf"] is None + + +def test_duplicate_of_on_an_already_declined_report_records_the_field(client): + a, b = file_bug(client), file_bug(client) + patch(client, b, status="declined", note="no") + d = patch(client, b, duplicateOf=a).get_json() + assert d["status"] == "declined" and d["duplicateOf"] == a + assert d["audit"][-1]["note"] == f"duplicateOf: none -> {a}" + + +# ---- kind, app, product ---------------------------------------------------- + +def test_kind_is_stored_when_given_and_derived_from_tags_when_not(client): + plain = file_bug(client) + tagged = file_bug(client, tags=["feature-request"]) + said = file_bug(client, kind="feature", tags=["bug"]) + kinds = {r["id"]: r["kind"] for r in client.get("/api/bugs?days=1").get_json()["bugs"]} + assert (kinds[plain], kinds[tagged], kinds[said]) == ("bug", "feature", "feature") + assert client.get(f"/api/bugs/{said}").get_json()["kind"] == "feature" + + +def test_app_comes_from_the_hook_never_the_body_and_product_follows(any_store): + c = make_client(any_store, app_stamp=lambda r: "sealviewer") + r = c.post("/api/bugs", json={"details": "x", "app": "leaphq"}) + assert r.get_json()["app"] == "sealviewer" + d = c.get(f"/api/bugs/{r.get_json()['id']}").get_json() + assert (d["app"], d["product"]) == ("sealviewer", "Seal") + # an app the contract does not know is dropped, not stored + c2 = make_client(any_store, app_stamp=lambda r: "made-up") + assert c2.post("/api/bugs", json={"details": "x"}).get_json()["app"] is None + # no hook: a body claim is ignored + c3 = make_client(any_store) + bid = c3.post("/api/bugs", json={"details": "x", "app": "leaphq"}).get_json()["id"] + assert c3.get(f"/api/bugs/{bid}").get_json()["app"] is None + + +# ---- list filters ---------------------------------------------------------- + +def test_list_filters_app_kind_area_priority(any_store): + apps = {"v": "stoppages"} + c = make_client(any_store, app_stamp=lambda r: apps["v"]) + a = file_bug(c, tags=["feature"]) + apps["v"] = "placements" + b = file_bug(c) + patch(c, a, area="Clips", priority="now") + patch(c, b, area="Belt", priority="later") + + def ids(q): + return {r["id"] for r in c.get(f"/api/bugs?days=1&{q}").get_json()["bugs"]} + assert ids("app=stoppages") == {a} + assert ids("app=placements") == {b} + assert ids("kind=feature") == {a} and ids("kind=bug") == {b} + assert ids("area=Belt") == {b} + assert ids("priority=now") == {a} + assert ids("app=stoppages&priority=later") == set() + assert c.get("/api/bugs?kind=wat").status_code == 400 + assert c.get("/api/bugs?priority=wat").status_code == 400 + + +# ---- votes ----------------------------------------------------------------- + +def test_one_vote_per_person_and_delete_takes_it_back(client): + bid = file_bug(client) + r = client.post(f"/api/bugs/{bid}/vote") + assert (r.status_code, r.get_json()) == (200, {"votes": 1, "voted": True}) + assert client.post(f"/api/bugs/{bid}/vote").get_json()["votes"] == 1 # twice = once + client.person[0] = "Chris@example.com" + assert client.post(f"/api/bugs/{bid}/vote").get_json()["votes"] == 2 + client.person[0] = "chris@EXAMPLE.com" # same person, other case + assert client.post(f"/api/bugs/{bid}/vote").get_json()["votes"] == 2 + assert client.get(f"/api/bugs/{bid}").get_json()["votes"] == 2 + assert client.get("/api/bugs?days=1").get_json()["bugs"][0]["votes"] == 2 + r = client.delete(f"/api/bugs/{bid}/vote") + assert r.get_json() == {"votes": 1, "voted": False} + assert client.delete(f"/api/bugs/{bid}/vote").get_json()["votes"] == 1 # nothing to take back + + +def test_voting_needs_someone_signed_in_and_a_real_report(client): + bid = file_bug(client) + client.person[0] = "" + assert client.post(f"/api/bugs/{bid}/vote").status_code == 401 + assert client.delete(f"/api/bugs/{bid}/vote").status_code == 401 + client.person[0] = ADMIN + assert client.post("/api/bugs/bug-20200101-000000-aaaaaa/vote").status_code == 404 + assert client.post("/api/bugs/junk/vote").status_code == 400 + + +def test_a_non_admin_can_still_vote(any_store): + app = Flask(__name__) + app.register_blueprint(create_blueprint( + store=any_store, is_admin=lambda r: False, actor_identity=lambda r: ADMIN)) + c = app.test_client() + bid = c.post("/bugs", json={"details": "x"}).get_json()["id"] + assert c.post(f"/bugs/{bid}/vote").status_code == 200 + assert c.patch(f"/bugs/{bid}", json={"area": "x"}).status_code == 403 + + +def test_without_an_identity_hook_the_voter_is_the_payload_claim(any_store): + app = Flask(__name__) + app.register_blueprint(create_blueprint(store=any_store)) + c = app.test_client() + bid = c.post("/bugs", json={"details": "x"}).get_json()["id"] + assert c.post(f"/bugs/{bid}/vote").status_code == 401 + assert c.post(f"/bugs/{bid}/vote", json={"actorEmail": "a@example.com"}).get_json()["votes"] == 1 + assert c.delete(f"/bugs/{bid}/vote?actorEmail=a@example.com").get_json()["votes"] == 0 + + +# ---- a v2 record ----------------------------------------------------------- + +V2 = { + "id": "bug-20261001-100000-abcdef", "title": "old one", "details": "from 2026-10", "tags": ["bug"], + "status": "open", "added_by": "web", "actor_email": "a@example.com", + "added_at": "2026-11-13T10:00:00.000000Z", + "meta_url": "", "meta_user_agent": "", "meta_build_sha": "", "screenshot": False, + "transcript": None, "actor_name": "A", +} + + +def seed_v2(store): + """A record exactly as a v2 store wrote it: none of the v3 keys.""" + if isinstance(store, FilesystemStore): + (store.root / f"{V2['id']}.json").write_text(json.dumps(V2)) + elif hasattr(store, "_connect"): + from psycopg.types.json import Jsonb + with store._connect() as conn: + conn.execute("INSERT INTO reports(id, status, added_at, record) VALUES(%s,%s,%s,%s)", + (V2["id"], "open", "2026-11-13T10:00:00Z", Jsonb(V2))) + else: + store.put_bug(BugRecord.from_dict(V2), None) + + +def test_a_v2_record_reads_back_with_the_new_fields_null_and_zero_votes(any_store): + seed_v2(any_store) + c = make_client(any_store) + for d in (c.get(f"/api/bugs/{V2['id']}").get_json(), + c.get("/api/bugs?days=3650").get_json()["bugs"][0]): + assert d["id"] == V2["id"] + assert [d[k] for k in ("app", "product", "area", "priority", "owner", "parentId", "duplicateOf")] == [None] * 7 + assert d["votes"] == 0 and d["kind"] == "bug" + # and it can be triaged like any other + assert patch(c, V2["id"], area="Old").get_json()["area"] == "Old" + + +def test_a_record_with_keys_this_version_does_not_know_still_loads(): + r = BugRecord.from_dict({**V2, "from_the_future": 1}) + assert r.id == V2["id"] and not hasattr(r, "from_the_future") + + +def test_every_triage_field_in_the_contract_has_a_record_attribute(): + assert tuple(contract.TRIAGE_WIRE_TO_ATTR) == contract.TRIAGE_FIELDS + for wire, attr in contract.TRIAGE_WIRE_TO_ATTR.items(): + assert attr in BugRecord.__dataclass_fields__ + assert contract.TRIAGE_ATTR_TO_WIRE[attr] == wire + + +# a value for each store-side list filter that matches NOTHING (the one report below has none of them set) +EXCLUDING = {"app": "leaphq", "kind": "feature", "area": "zzz", "priority": "later"} + + +def test_every_list_filter_in_the_contract_is_honoured_by_the_route(client): + file_bug(client) + assert len(client.get("/api/bugs?days=1").get_json()["bugs"]) == 1 + for name in contract.LIST_FILTERS: + if name in ("status", "days"): + continue + assert name in EXCLUDING, f"contract.LIST_FILTERS gained {name!r}: teach the route and this test" + rows = client.get(f"/api/bugs?days=1&{name}={EXCLUDING[name]}").get_json()["bugs"] + assert rows == [], f"?{name}= is in the contract but the route ignores it" + assert client.get("/api/bugs?days=1&status=resolved").get_json()["bugs"] == [] + + +def test_the_store_protocol_takes_exactly_the_contracts_filters(): + import inspect + from bug_report import InMemoryStore + from bug_report.store import FilesystemStore + want = set(contract.LIST_FILTERS) - {"status", "days"} + for cls in (InMemoryStore, FilesystemStore): + params = set(inspect.signature(cls.list_bugs).parameters) - {"self", "status", "since_iso"} + assert params == want, cls diff --git a/packages/spec/README.md b/packages/spec/README.md index 04cd5ce..cd97f2f 100644 --- a/packages/spec/README.md +++ b/packages/spec/README.md @@ -49,6 +49,17 @@ The field names are the ones the implementations already spoke, not the ones any single one of them used internally โ€” `screenshot` is a boolean ("is there one"), because that is what every backend here emits. +## Contract v3: one central store (backends 3.0.0) + +Additive; a v2 record and a v2 client work unchanged. See `report-contract.json` (`_v3`, `appProducts`, `priorities`, +`triageFields`, `listFilters`) and the PATCH/vote sections of `openapi.yaml`. + +- `product`, stored `kind`, `area`, `priority`, `owner`, `parentId`, `duplicateOf`, `votes` on every summary; null (and 0 votes) on a v2 record. +- `app` is stamped from the caller's identity, never the body; `product` is derived from it by `appProducts`. +- `PATCH` takes the triage fields with or without `status`; each change writes an audit row saying what changed; `duplicateOf` also declines with the note `duplicate of `. +- `POST` / `DELETE /bugs/{id}/vote`: any signed-in caller, one vote per person. +- `GET /bugs` filters `app`, `kind`, `area`, `priority`. + ## People are named; closing can email the reporter (backends 2.2.0) All additive and optional, so older data and older clients keep working: diff --git a/packages/spec/openapi.yaml b/packages/spec/openapi.yaml index 17851b3..50b86b1 100644 --- a/packages/spec/openapi.yaml +++ b/packages/spec/openapi.yaml @@ -1,7 +1,7 @@ openapi: 3.1.0 info: title: Bug Report API - version: 1.0.0 + version: 3.0.0 description: | The API contract every bug-report backend must honor. The widget (packages/widget) and the CLI (packages/cli) speak this protocol; @@ -46,6 +46,19 @@ paths: id: type: string example: bug-20260516-181523-a3b91f2 + app: + type: string + nullable: true + description: | + The app the report was filed under (backends 3.0.0): stamped + from the caller's identity, never from the body. Null when + the server does not stamp one. + appIgnored: + type: string + description: | + Only when a trusted app's `X-Leap-App` header disagreed with + its token: the claim that was ignored. (`X-Leap-App-Used` / + `X-Leap-App-Ignored` response headers say the same.) "400": $ref: "#/components/responses/BadRequest" "413": @@ -70,6 +83,26 @@ paths: type: integer minimum: 1 default: 30 + - in: query + name: app + description: Only reports filed under this app (backends 3.0.0). + schema: { type: string } + - in: query + name: kind + description: Only this kind, stored or derived from the tags (3.0.0). + schema: + type: string + enum: [bug, feature] + - in: query + name: area + description: Only this area (3.0.0). + schema: { type: string } + - in: query + name: priority + description: Only this priority (3.0.0). + schema: + type: string + enum: [now, next, later] responses: "200": description: A list of bugs sorted newest-first @@ -104,8 +137,19 @@ paths: $ref: "#/components/responses/NotFound" patch: - summary: Transition status (admin) + summary: Transition status and/or set triage fields (admin) description: | + Backends 3.0.0: `status` is optional when a triage field (`area`, + `priority`, `owner`, `parentId`, `duplicateOf`) is sent. A null or + empty value clears a field; a value equal to the current one is a + no-op. Each change writes an audit row (from = to = the current + status) whose `note` says what changed, e.g. `area: none -> Cutter`. + `duplicateOf` also DECLINES the report, with the status row's note + `duplicate of ` (409 when the lifecycle forbids declining, 400 when + `status` is given and is not `declined`). `parentId` must not make a + cycle. 404 when a referenced report does not exist. + + Implementations MUST write an audit row on every successful transition and MUST be no-op when status == current status. @@ -124,10 +168,27 @@ paths: application/json: schema: type: object - required: [status] properties: status: $ref: "#/components/schemas/Status" + area: + type: string + nullable: true + maxLength: 100 + priority: + type: string + nullable: true + enum: [now, next, later] + owner: + type: string + nullable: true + description: An email address. + parentId: + type: string + nullable: true + duplicateOf: + type: string + nullable: true note: type: string maxLength: 500 @@ -153,6 +214,43 @@ paths: "404": $ref: "#/components/responses/NotFound" + /bugs/{id}/vote: + parameters: + - $ref: "#/components/parameters/BugId" + post: + summary: Vote for a report (any signed-in caller; backends 3.0.0) + description: One vote per person; voting twice is a no-op. 401 when nobody is signed in. + operationId: voteBug + responses: + "200": + description: The report's vote count + content: + application/json: + schema: { $ref: "#/components/schemas/Voted" } + "401": + description: Nobody is signed in + content: + application/json: + schema: { $ref: "#/components/schemas/Error" } + "404": + $ref: "#/components/responses/NotFound" + delete: + summary: Take your vote back (backends 3.0.0) + operationId: unvoteBug + responses: + "200": + description: The report's vote count + content: + application/json: + schema: { $ref: "#/components/schemas/Voted" } + "401": + description: Nobody is signed in + content: + application/json: + schema: { $ref: "#/components/schemas/Error" } + "404": + $ref: "#/components/responses/NotFound" + /bugs/{id}/screenshot: parameters: - $ref: "#/components/parameters/BugId" @@ -273,6 +371,10 @@ components: was never answered. Servers MAY ignore it โ€” the reference backends do, so an app on them must not enable `idempotentSubmit` unless its own server dedupes. + kind: + type: string + enum: [bug, feature] + description: Optional (backends 3.0.0). Stored; derived from `tags` when absent. transcript: type: array items: @@ -316,7 +418,7 @@ components: kind: type: string enum: [bug, feature] - description: Derived from the tags (report-contract.json `kinds`, `kindTags`); a feature request is tagged `feature`. + description: Stored since 3.0.0; derived from the tags (report-contract.json `kinds`, `kindTags`) when the filer did not say. addedBy: { type: string } actorEmail: { type: string } actorName: @@ -326,6 +428,41 @@ components: screenshot: type: boolean description: True iff a screenshot was stored. + app: + type: string + nullable: true + enum: [stoppages, fleet, report, placements, sealviewer, leaphq] + description: Stamped from the caller's identity (backends 3.0.0); null on a v2 record. + product: + type: string + nullable: true + enum: [PikPak, Seal, Placement, Internal] + description: Derived from `app` by report-contract.json `appProducts`; not stored. + area: + type: string + nullable: true + description: Triage field (3.0.0). + priority: + type: string + nullable: true + enum: [now, next, later] + description: Triage field (3.0.0). + owner: + type: string + nullable: true + description: Triage field (3.0.0), an email. + parentId: + type: string + nullable: true + description: Triage field (3.0.0), a report id. + duplicateOf: + type: string + nullable: true + description: Triage field (3.0.0), a report id; setting it declines the report. + votes: + type: integer + minimum: 0 + description: Count of people who voted (3.0.0); 0 on a v2 record. Bug: allOf: @@ -374,6 +511,15 @@ components: toStatus: { $ref: "#/components/schemas/Status" } note: { type: string } + Voted: + type: object + required: [votes, voted] + properties: + votes: { type: integer, minimum: 0 } + voted: + type: boolean + description: Whether the caller's vote now stands. + Error: type: object required: [error] diff --git a/packages/spec/report-contract.json b/packages/spec/report-contract.json index 530a5b0..93a8992 100644 --- a/packages/spec/report-contract.json +++ b/packages/spec/report-contract.json @@ -22,9 +22,17 @@ "Changes from v1: `source` -> `app` with `source` reserved; `transitions`", "is what the server enforces EXACTLY (with `offered` split out as what the", "UI shows); `transcript` moved to optional and must be rendered where it", - "exists; `context`/`attachments` recorded as deliberately out of scope." + "exists; `context`/`attachments` recorded as deliberately out of scope.", + "", + "v3, 2026-11-14 โ€” ADDS, removes nothing: one central store for every app's", + "reports (design: leap-reports CENTRAL-STORE.md). New fields `product`,", + "stored `kind`, `area`, `priority`, `owner`, `parentId`, `duplicateOf`,", + "`votes`; `appProducts` (app -> product); PATCH takes the triage fields", + "with or without a status change; POST/DELETE //vote; list filters", + "`app`, `kind`, `area`, `priority`. A v2 record (none of the new fields)", + "reads back with them null, and `votes` 0." ], - "version": 2, + "version": 3, "_statuses": [ "The lifecycle every store shares. LeapHQ ran open|triaged|resolved until", @@ -140,8 +148,39 @@ "addedBy", "addedAt", "actorEmail", - "screenshot" + "screenshot", + "app", + "product", + "area", + "priority", + "owner", + "parentId", + "duplicateOf", + "votes" + ], + + "_v3": [ + "Added in v3. `app` is stamped by the proxy from the CALLER'S IDENTITY (the", + "app's managed identity), never by the filer. `product` is derived from", + "`app` by `appProducts`, so it is not stored. `kind` is now stored, and", + "still derived from tags when the filer does not say. `area`, `priority`,", + "`owner`, `parentId` and `duplicateOf` are TRIAGE fields (null until set);", + "setting `duplicateOf` declines the report with the note", + "'duplicate of '. `votes` is a count; one vote per signed-in person.", + "A v2 record carries none of these: they read back null, `votes` 0." ], + "products": ["PikPak", "Seal", "Placement", "Internal"], + "appProducts": { + "stoppages": "PikPak", + "fleet": "PikPak", + "report": "PikPak", + "placements": "Placement", + "sealviewer": "Seal", + "leaphq": "Internal" + }, + "priorities": ["now", "next", "later"], + "triageFields": ["area", "priority", "owner", "parentId", "duplicateOf"], + "listFilters": ["status", "days", "app", "kind", "area", "priority"], "_detailFields": [ "What a DETAIL read adds on top of the summary. Every store already keeps", @@ -200,6 +239,13 @@ "actorEmail": "ken.moynihan@helloleap.ai", "screenshot": true, "app": "leaphq", + "product": "Internal", + "area": "Time entry", + "priority": "next", + "owner": "ken.moynihan@helloleap.ai", + "parentId": null, + "duplicateOf": null, + "votes": 2, "details": "Tapping 7.5 twice leaves the picker open and the value unset.", "metaUrl": "https://hq.helloleap.ai/index.html?tab=entry", "metaUserAgent": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X)", diff --git a/packages/spec/types.py b/packages/spec/types.py index 7f0908a..af08279 100644 --- a/packages/spec/types.py +++ b/packages/spec/types.py @@ -9,6 +9,10 @@ from typing import Literal, NotRequired, TypedDict Status = Literal["open", "triaged", "resolved", "declined"] +Kind = Literal["bug", "feature"] +Priority = Literal["now", "next", "later"] +Product = Literal["PikPak", "Seal", "Placement", "Internal"] +App = Literal["stoppages", "fleet", "report", "placements", "sealviewer", "leaphq"] class TranscriptTurn(TypedDict, total=False): @@ -33,6 +37,7 @@ class BugCreate(TypedDict, total=False): screenshotError: str # why there is no screenshot (1.6.0+), or why part of it is blank (1.6.4+); <= 200 chars clientKey: str # idempotency key (widget 1.6.0+, opt-in); <= 64 chars transcript: list[TranscriptTurn] + kind: Kind # stored when given; derived from `tags` when not (contract v3) class BugSummary(TypedDict): @@ -45,6 +50,16 @@ class BugSummary(TypedDict): actorName: NotRequired[str] # "" when unknown (backends 2.2.0) addedAt: str screenshot: bool + # Contract v3 (backends 3.0.0). A v2 record reads back with these null and votes 0. + kind: NotRequired[Kind] + app: NotRequired[App | None] # stamped by the proxy from the caller's identity + product: NotRequired[Product | None] # derived from `app` (report-contract.json appProducts) + area: NotRequired[str | None] + priority: NotRequired[Priority | None] + owner: NotRequired[str | None] # an email + parentId: NotRequired[str | None] + duplicateOf: NotRequired[str | None] + votes: NotRequired[int] class AuditEntry(TypedDict): @@ -73,8 +88,24 @@ class Notified(TypedDict): error: NotRequired[str] +class Voted(TypedDict): + votes: int + voted: bool + + +class BugCreated(TypedDict): + id: str + app: App | None # the app the report was filed under (backends 3.0.0) + appIgnored: NotRequired[str] # the X-Leap-App a trusted app sent that lost to its token + + class BugPatch(TypedDict, total=False): - status: Status # required + status: Status # required unless a triage field is sent (backends 3.0.0) + area: str | None # triage fields (3.0.0); null or "" clears + priority: Priority | None + owner: str | None + parentId: str | None + duplicateOf: str | None # also declines the report: note "duplicate of " note: str changedBy: str changedByName: str diff --git a/packages/spec/types.ts b/packages/spec/types.ts index 95df4cd..7cd3c92 100644 --- a/packages/spec/types.ts +++ b/packages/spec/types.ts @@ -5,6 +5,10 @@ */ export type Status = "open" | "triaged" | "resolved" | "declined"; +export type Kind = "bug" | "feature"; +export type Priority = "now" | "next" | "later"; +export type Product = "PikPak" | "Seal" | "Placement" | "Internal"; +export type App = "stoppages" | "fleet" | "report" | "placements" | "sealviewer" | "leaphq"; export interface TranscriptTurn { ts?: string; @@ -32,6 +36,8 @@ export interface BugCreate { /** Idempotency key (widget 1.6.0+, opt-in): the same on every retry of one report. โ‰ค 64 chars. */ clientKey?: string; transcript?: TranscriptTurn[]; + /** Stored when given; derived from `tags` when not (contract v3). */ + kind?: Kind; } export interface BugSummary { @@ -45,6 +51,19 @@ export interface BugSummary { actorName?: string; addedAt: string; screenshot: boolean; + /** Contract v3 (backends 3.0.0). A v2 record reads back with these null and `votes` 0. */ + kind?: Kind; + /** Stamped by the proxy from the caller's identity. */ + app?: App | null; + /** Derived from `app` (report-contract.json appProducts). */ + product?: Product | null; + area?: string | null; + priority?: Priority | null; + /** An email. */ + owner?: string | null; + parentId?: string | null; + duplicateOf?: string | null; + votes?: number; } export interface AuditEntry { @@ -76,9 +95,30 @@ export interface Notified { error?: string; } +/** POST/DELETE /bugs/{id}/vote response (backends 3.0.0). */ +export interface Voted { + votes: number; + voted: boolean; +} + +/** POST /bugs 201 body. `app` is the app the report was filed under (backends 3.0.0). */ +export interface BugCreated { + id: string; + app: App | null; + /** The X-Leap-App a trusted app sent that lost to its token. */ + appIgnored?: string; +} + /** PATCH /bugs/{id} body. `notify` emails the reporter on a change to resolved/declined and needs `note`. */ export interface BugPatch { - status: Status; + /** Required unless a triage field is sent (backends 3.0.0). */ + status?: Status; + /** Triage fields (3.0.0); null or "" clears. `duplicateOf` also declines: note "duplicate of ". */ + area?: string | null; + priority?: Priority | null; + owner?: string | null; + parentId?: string | null; + duplicateOf?: string | null; note?: string; changedBy?: string; changedByName?: string;