Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@

All notable changes to this monorepo.

## backends v3.2.0 - 2026-11-15 (`bug-report-py` 3.2.0)

What LeapHQ's move needs from the library (Ken's decisions 1 and 3). The report contract is unchanged.

- **Ids may end in 12 hex.** `valid_bug_id`, the Node backend's check and the spec's pattern accept `bug-YYYYMMDD-HHMMSS-` plus 6 or 12 lowercase hex, and nothing else; new ids stay 6 hex. A drift test keeps the spec and both backends on one pattern. (The spec's example id was 7 hex, which the code always refused; it is 6 now.)
- **A non-admin lists features and their own reports.** `GET /bugs` is no longer a 403 for a caller who is not an admin: it returns reports with `kind=feature` and reports whose `actor_email` is the caller. Detail, screenshot and vote on anyone else's report are 404, the same answer as a missing id, and `default_actor_email` never makes a caller anyone; PATCH stays admin-only. The open count a non-admin gets counts only what they see. Admins are unchanged. The person comes from `actor_identity`, as before. Python only: the Node backend's list stays admin-only (documented, not ported).

## backends v3.1.0 - 2026-11-15 (`bug-report-py` 3.1.0)

The proxy's core is a plain function. No contract change.
Expand Down
2 changes: 2 additions & 0 deletions docs/CENTRAL-STORE.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ LeapHQ Review ──(LeapHQ's own identity, a token)──► leaphq-reports (on
- 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.
- **Who sees what (3.2.0).** Triage is `BUG_ADMINS` only. A person who is not an admin lists only reports with `kind=feature` and their own (`actor_email` equals the person from `X-Leap-Actor-Email`, any kind); detail, screenshot and vote on another person's report are 404, as for a missing id. The open count they see counts only those. The person still comes from the trusted app's headers, so the trust model is unchanged.
- **Ids (3.2.0).** `bug-YYYYMMDD-HHMMSS-` plus 6 hex (new ids) or 12 hex (imported from LeapHQ); the store, the routes, the spec and the Node backend all accept exactly those two.
- **Seal laptops.** Their outbox forwards to the seal viewer's proxy exactly as it does today, so nothing changes on a station.

## Store
Expand Down
17 changes: 12 additions & 5 deletions e2e/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def _wait_alive(url: str, timeout: float = 10) -> None:
app = Flask(__name__)
app.register_blueprint(create_blueprint(
store=store,
is_admin=lambda req: True,
is_admin={admin},
{hooks}
))
app.run(host="127.0.0.1", port={port}, use_reloader=False)
Expand All @@ -91,9 +91,9 @@ def _wait_alive(url: str, timeout: float = 10) -> None:
app_stamp=lambda r: r.headers.get("X-Test-App") or None,"""


def _boot_python(tmp_path_factory, label, store_init, hooks=""):
def _boot_python(tmp_path_factory, label, store_init, hooks="", admin="lambda req: True"):
port = _free_port()
script = PY_SERVER_SCRIPT.format(pkg=str(PY_PKG), store_init=store_init, hooks=hooks, port=port)
script = PY_SERVER_SCRIPT.format(pkg=str(PY_PKG), store_init=store_init, hooks=hooks, admin=admin, port=port)
log = tmp_path_factory.mktemp(f"{label}-log") / "out.log"
return port, script, log

Expand All @@ -103,9 +103,9 @@ def python_server(tmp_path_factory):
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=""):
def _serve_python(tmp_path_factory, label, store_init, hooks="", admin="lambda req: True"):
"""Boot a Python backend subprocess; yield its /bugs URL; stop it."""
port, script, log = _boot_python(tmp_path_factory, label, store_init, hooks)
port, script, log = _boot_python(tmp_path_factory, label, store_init, hooks, admin)
with open(log, "w") as logf:
proc = subprocess.Popen([sys.executable, "-c", script], stdout=logf, stderr=subprocess.STDOUT)
base = f"http://127.0.0.1:{port}/bugs"
Expand Down Expand Up @@ -142,6 +142,13 @@ def python_v3_server(tmp_path_factory):
V3_HOOKS)


@pytest.fixture(scope="session")
def python_nonadmin_server(tmp_path_factory):
"""Python only: the caller is `X-Test-User`, and is an admin only with `X-Test-Admin: yes` (3.2.0)."""
yield from _serve_python(tmp_path_factory, "pyna", FS_INIT.format(state=tmp_path_factory.mktemp("py-na-state")),
V3_HOOKS, admin='lambda r: r.headers.get("X-Test-Admin") == "yes"')


@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",
Expand Down
2 changes: 1 addition & 1 deletion e2e/test_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
TINY_PNG_B64 = base64.b64encode(TINY_PNG).decode()
TINY_JPEG = bytes.fromhex("FFD8FFE000104A46494600010100000100010000FFD9")
TINY_JPEG_B64 = base64.b64encode(TINY_JPEG).decode()
ID_RE = re.compile(r"^bug-\d{8}-\d{6}-[a-f0-9]{6}$")
from bug_report.models import _BUG_ID_RE as ID_RE # the library's own pattern, not a copy


# ----- POST ----------------------------------------------------------
Expand Down
21 changes: 21 additions & 0 deletions e2e/test_v3.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,24 @@ def test_votes_one_per_person(v3_url):
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


def test_a_non_admin_sees_features_and_their_own_and_nothing_else_of_others(python_nonadmin_server):
"""PYTHON ONLY: the Node backend still gates its list by `isAdmin` alone (documented, not ported), so
this case has no Node twin and uses its own server rather than the three-backend `v3_url`."""
url, m = python_nonadmin_server, mark()
ann, bob = {"X-Test-User": "ann@example.com"}, {"X-Test-User": "bob@example.com"}

def mk(who, **kw):
r = requests.post(url, json={"details": f"{m} x", **kw}, headers=who)
assert r.status_code == 201, r.text
return r.json()["id"]

own, other, feat = mk(ann), mk(bob), mk(bob, kind="feature", tags=["feature"])
rows = requests.get(f"{url}?days=1", headers=ann).json()["bugs"]
assert {r["id"] for r in rows if m in r["title"]} == {own, feat}
assert requests.get(f"{url}/{other}", headers=ann).status_code == 404
assert requests.get(f"{url}/{other}/screenshot", headers=ann).status_code == 404
assert requests.get(f"{url}/{own}", headers=ann).status_code == 200
admin = {**ann, "X-Test-Admin": "yes"}
assert {r["id"] for r in requests.get(f"{url}?days=1", headers=admin).json()["bugs"] if m in r["title"]} == {own, other, feat}
2 changes: 2 additions & 0 deletions packages/backend-node/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ In practice the leap-timesheet migration plan is to lift `createBugsRouter` and
| PATCH | /:id | `isAdmin` |
| GET | /:id/screenshot | open |

**Not ported (backends 3.2.0).** The Python backend lets a non-admin list feature requests and their own reports, and answers 404 for a report they may not see. The Node backend does not: its list stays admin-only through `isAdmin`, and detail and screenshot stay open. Only the 6-or-12-hex id rule is shared.

## Stores

| Class | Purpose |
Expand Down
2 changes: 1 addition & 1 deletion packages/backend-node/src/models.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export function screenshotContentType(data) {
return "image/png";
}

const BUG_ID_RE = /^bug-\d{8}-\d{6}-[a-f0-9]{6}$/;
const BUG_ID_RE = /^bug-\d{8}-\d{6}-(?:[a-f0-9]{6}|[a-f0-9]{12})$/;

export function validBugId(id) {
return typeof id === "string" && BUG_ID_RE.test(id);
Expand Down
9 changes: 9 additions & 0 deletions packages/backend-node/tests/bug-id.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { validBugId } from "../src/index.js";

test("an id ends in 6 or 12 lowercase hex, and nothing else (3.2.0)", () => {
for (const n of [6, 12]) assert.equal(validBugId(`bug-20261115-101010-${"a1b2c3d4e5f6".slice(0, n)}`), true);
for (const n of [5, 7, 11, 13]) assert.equal(validBugId(`bug-20261115-101010-${"a1b2c3d4e5f60".slice(0, n)}`), false);
assert.equal(validBugId("bug-20261115-101010-A1B2C3"), false);
});
4 changes: 2 additions & 2 deletions packages/backend-node/tests/router.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { tmpdir } from "node:os";
import path from "node:path";

import express from "express";
import { createBugsRouter, InMemoryStore, FilesystemStore } from "../src/index.js";
import { createBugsRouter, InMemoryStore, FilesystemStore, validBugId } from "../src/index.js";

// 1x1 transparent PNG.
const TINY_PNG = Buffer.from(
Expand Down Expand Up @@ -76,7 +76,7 @@ for (const [name, makeStore] of STORES) {
});
assert.equal(r.status, 201);
const { id } = await r.json();
assert.match(id, /^bug-\d{8}-\d{6}-[a-f0-9]{6}$/);
assert.ok(validBugId(id), id);
});
});

Expand Down
18 changes: 13 additions & 5 deletions packages/backend-python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,20 @@ Routes mounted (under the prefix you pass):
| Method | Path | Auth-gated |
|--------|----------------------------|-----------------|
| POST | /bugs | open |
| GET | /bugs | `is_admin` |
| GET | /bugs/{id} | open |
| GET | /bugs | everyone; a non-admin sees only what they may (3.2.0) |
| GET | /bugs/{id} | admin, a feature, or the caller's own (3.2.0) |
| 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) |
| GET | /bugs/{id}/screenshot | admin, a feature, or the caller's own (3.2.0) |
| POST | /bugs/{id}/vote | signed in (3.0.0), on a report they may see |
| DELETE | /bugs/{id}/vote | signed in (3.0.0), on a report they may see |

**What a non-admin sees (3.2.0).** A caller for whom `is_admin` is false gets, from the list, only reports with `kind=feature`
(so people can see and vote on them) and their own reports (`actor_email` equals the caller, any kind). Detail, screenshot and vote
on anyone else's report are 404, the same answer as a missing id (nothing leaks); triage (PATCH) stays admin-only. A list with `status=open` therefore counts only what the caller can
see. The caller is the checked `actor_identity` when the app gave one (with `TrustedCallers`, the `X-Leap-Actor-*` headers), else the
request's own `actorEmail` (never `default_actor_email`), so without `actor_identity` this is advice, not a boundary. Admins see everything.

**Ids.** New ids are `bug-YYYYMMDD-HHMMSS-` plus 6 lowercase hex; 12 hex is accepted too (reports imported from LeapHQ), and nothing else.

## Triage fields, votes and filters (3.0.0)

Expand Down
2 changes: 1 addition & 1 deletion packages/backend-python/bug_report/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
valid_bug_id,
)

__version__ = "3.1.0"
__version__ = "3.2.0"

from . import contract
from .contract import (
Expand Down
33 changes: 30 additions & 3 deletions packages/backend-python/bug_report/blueprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,8 +259,7 @@ def api_create():

@bp.route(url_prefix, methods=["GET"])
def api_list():
if not is_admin(request):
abort(403)
admin = is_admin(request)
status_filter = (request.args.get("status") or "").strip() or None
if status_filter and status_filter not in BUG_STATUSES:
return jsonify({"error": f"status must be one of {BUG_STATUSES}"}), 400
Expand All @@ -275,11 +274,37 @@ def api_list():
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))
if not admin:
me = _caller_email(request)
bugs = [b for b in bugs if _visible(b, me)]
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 _caller_email(req) -> str:
"""The caller's address, for what a non-admin may see: the checked identity when the app
gave one, else the request's own claim. Never `default_actor_email`: that is who an unsigned
filing is credited to, and it must not make everyone that person when they ask what they may see."""
if actor_identity is not None:
return _identity(req)[0].lower()
body = req.get_json(silent=True) if req.is_json else None
return str((body or {}).get("actorEmail") or req.args.get("actorEmail") or "").strip()[:200].lower()

def _visible(bug, me: str) -> bool:
"""What a non-admin may see (3.2.0): every feature request, and the caller's own reports."""
return (bug.effective_kind() == "feature"
or bool(me and (bug.actor_email or "").strip().lower() == me))

def _may_see(bug) -> bool:
return bool(is_admin(request)) or _visible(bug, _caller_email(request))

def _seen(bug):
"""The report, or NotFound: one a caller may not see answers exactly as a missing one does."""
if not _may_see(bug):
raise NotFound()
return bug

def _vote_counts(ids):
"""Votes per report; a store that predates votes counts none."""
counter = getattr(store, "vote_counts", None)
Expand All @@ -298,7 +323,7 @@ def api_get(bug_id: str):
if not valid_bug_id(bug_id):
return jsonify({"error": "invalid id"}), 400
try:
bug = store.get_bug(bug_id)
bug = _seen(store.get_bug(bug_id))
except NotFound:
return jsonify({"error": "not found"}), 404
full = _detail(bug)
Expand Down Expand Up @@ -508,6 +533,7 @@ def _vote(bug_id: str, adding: bool):
if not hasattr(store, "add_vote"):
return jsonify({"error": "this store does not keep votes"}), 501
try:
_seen(store.get_bug(bug_id))
(store.add_vote if adding else store.remove_vote)(bug_id, voter)
except NotFound:
return jsonify({"error": "not found"}), 404
Expand All @@ -528,6 +554,7 @@ def api_screenshot(bug_id: str):
if not valid_bug_id(bug_id):
abort(400)
try:
_seen(store.get_bug(bug_id))
data = store.get_screenshot(bug_id)
except NotFound:
abort(404)
Expand Down
3 changes: 2 additions & 1 deletion packages/backend-python/bug_report/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def screenshot_content_type(data: bytes) -> str:
return "image/webp"
return "image/png"

_BUG_ID_RE = re.compile(r"^bug-\d{8}-\d{6}-[a-f0-9]{6}$")
_BUG_ID_RE = re.compile(r"^bug-\d{8}-\d{6}-(?:[a-f0-9]{6}|[a-f0-9]{12})$")


def new_bug_id() -> str:
Expand All @@ -52,6 +52,7 @@ def new_bug_id() -> str:


def valid_bug_id(bug_id: str) -> bool:
"""New ids end in 6 hex; 12 hex is accepted too (3.2.0), for reports imported from LeapHQ."""
return bool(_BUG_ID_RE.match(bug_id or ""))


Expand Down
2 changes: 1 addition & 1 deletion packages/backend-python/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "bug-report-py"
version = "3.1.0"
version = "3.2.0"
description = "Flask blueprint + storage interface implementing the bug-report-widget API spec."
readme = "README.md"
license = { text = "MIT" }
Expand Down
7 changes: 4 additions & 3 deletions packages/backend-python/tests/test_blueprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,13 +239,14 @@ def test_screenshot_404_when_missing(client):
# Auth gate
# ---------------------------------------------------------------------------

def test_admin_gate_blocks_list_and_patch(store, admin_deny):
"""`is_admin` returning False MUST 403 the admin routes; POST stays open."""
def test_admin_gate_blocks_patch_and_filters_list(store, admin_deny):
"""`is_admin` returning False MUST 403 PATCH; POST stays open; the list is filtered (3.2.0), not refused."""
app = Flask(__name__)
app.register_blueprint(create_blueprint(store=store, is_admin=admin_deny))
c = app.test_client()
bid = c.post("/bugs", json={"details": "anyone can file"}).get_json()["id"]
assert c.get("/bugs").status_code == 403
assert c.get("/bugs").get_json() == {"bugs": []} # a bug filed by nobody is no one's to see
assert c.get(f"/bugs/{bid}").status_code == 404
assert c.patch(f"/bugs/{bid}", json={"status": "triaged"}).status_code == 403


Expand Down
20 changes: 14 additions & 6 deletions packages/backend-python/tests/test_proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,13 +132,21 @@ def test_every_route_goes_through_with_status_body_and_content_type_unchanged(fr
assert big.status_code == 413


def test_a_non_admin_person_gets_the_central_403_through_the_proxy(front):
bid = file(front)
def test_a_non_admin_person_sees_features_and_their_own_through_the_proxy(front):
"""3.2.0: the list and the detail are filtered by the checked person; triage is still 403."""
mine = file(front) # filed by the admin
feat = file(front, tags=["feature"])
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
own = file(front)
ids = lambda r: {b["id"] for b in r.get_json()["bugs"]} # noqa: E731
r = front.c.get("/api/bugs?days=1")
assert r.status_code == 200 and ids(r) == {feat, own} # not the admin's bug
assert front.c.get(f"/api/bugs/{mine}").status_code == 404
assert front.c.get(f"/api/bugs/{own}").status_code == 200
assert front.c.post(f"/api/bugs/{feat}/vote").get_json()["voted"] is True
assert front.c.patch(f"/api/bugs/{own}", json={"area": "x"}).status_code == 403
front.person[0] = {"email": "admin@example.com", "name": ""}
assert ids(front.c.get("/api/bugs?days=1")) == {mine, feat, own} # admin unchanged


def test_an_untrusted_app_is_a_502_on_every_route_not_a_403(front):
Expand Down
4 changes: 2 additions & 2 deletions packages/backend-python/tests/test_proxy_forward.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,11 @@ def test_a_refusal_of_the_app_is_a_502_with_a_generic_body_and_the_real_one_is_l
assert c("POST", body=b'{"details": "x"}')[0] == 502


def test_a_persons_403_and_401_pass_through(central):
def test_a_persons_404_for_a_hidden_report_and_401_pass_through(central):
c = Caller(central[0].url)
bid = c.file()
c.person = {"email": "someone@example.com", "name": ""}
assert c("GET")[0] == 403
assert c("GET", bid)[0] == 404 # someone else's bug (3.2.0: the list is filtered, not refused)
c.person = {"email": "", "name": ""}
assert c("POST", f"{bid}/vote")[0] == 401

Expand Down
9 changes: 9 additions & 0 deletions packages/backend-python/tests/test_spec_drift.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,12 @@ def test_types_py_and_types_ts_name_every_v3_summary_field():
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}"


def test_the_id_pattern_is_the_same_in_the_spec_the_python_model_and_the_node_model():
"""3.2.0: ids end in 6 or 12 hex. The three places that match an id must carry one pattern."""
import re
from bug_report import models
spec = re.search(r"pattern: '(\^bug-[^']+)'", SPEC.read_text()).group(1)
node = re.search(r"BUG_ID_RE = /(.+)/;", (SPEC.parents[1] / "backend-node/src/models.js").read_text()).group(1)
assert models._BUG_ID_RE.pattern == spec == node
Loading
Loading