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
16 changes: 16 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
38 changes: 38 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <id>`. `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
Expand Down
22 changes: 11 additions & 11 deletions docs/CENTRAL-STORE.md
Original file line number Diff line number Diff line change
@@ -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.

Expand All @@ -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
Expand Down Expand Up @@ -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 <app>` 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 <app>` 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`.
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion e2e/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
122 changes: 102 additions & 20 deletions e2e/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -52,40 +70,84 @@ 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()
try: proc.wait(timeout=3)
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)
# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -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],
Expand All @@ -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])
Loading
Loading