From c23efc8798071a627a6aa7a7ba88e7d500abd48f Mon Sep 17 00:00:00 2001 From: kmoy007 Date: Fri, 13 Nov 2026 13:14:59 -0800 Subject: [PATCH 1/3] backends v2.2.0: closing a report can email the reporter; people are named (bug-20261112-124952) Adds create_blueprint(notifier=, app_url=), PATCH notify, notified/canNotify, bug_report.email (render, AcsNotifier behind the [email] extra), actorName and changedByName, and identity-stamped changedBy. Node passes the fields through. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 36 +++ e2e/test_contract.py | 36 +++ packages/backend-node/src/index.js | 16 +- packages/backend-node/src/store.js | 2 + .../backend-node/src/stores/azure-tables.js | 4 + packages/backend-node/tests/router.test.js | 39 +++ packages/backend-python/README.md | 21 ++ .../backend-python/bug_report/__init__.py | 8 + .../backend-python/bug_report/blueprint.py | 102 +++++- packages/backend-python/bug_report/email.py | 223 +++++++++++++ packages/backend-python/bug_report/models.py | 18 ++ packages/backend-python/bug_report/store.py | 7 + packages/backend-python/pyproject.toml | 3 +- packages/backend-python/tests/test_email.py | 270 ++++++++++++++++ packages/backend-python/tests/test_notify.py | 299 ++++++++++++++++++ packages/spec/README.md | 8 + packages/spec/openapi.yaml | 38 +++ packages/spec/report-contract.json | 11 + packages/spec/types.py | 19 ++ packages/spec/types.ts | 25 ++ 20 files changed, 1171 insertions(+), 14 deletions(-) create mode 100644 packages/backend-python/bug_report/email.py create mode 100644 packages/backend-python/tests/test_email.py create mode 100644 packages/backend-python/tests/test_notify.py diff --git a/CHANGELOG.md b/CHANGELOG.md index d069d84..198a347 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,42 @@ Simulator first. - No option and no wire change. The button is inert while the form is open (it was already under the backdrop). +## backends v2.2.0 — 2026-11-13 + +From Chris Hamblin's report bug-20261112-124952: it was fixed, and Ken had to tell Chris by hand. Closing +a report can now carry a note and email the person who filed it, and people are named throughout +(bug-report-py 2.2.0; bug-report-node passes the new fields through). All additive. + +- **New: `create_blueprint(notifier=…, app_url=…)`.** `PATCH` takes `notify: true` (default false). On a + change to `resolved` or `declined` the server emails the reporter once: subject `Fixed: ` or + `Your bug report: <title> — not taken forward`; "Hi <first name>,", the note (URLs made links), signed with + the closer's name, "You reported this on <date> from <page>", the report id. Reply-To is the closer. + Reopening never emails. `notify` needs a non-empty `note` (400 otherwise, nothing changed). The status + change and its audit row are written first and a failed send never undoes them; a second audit row + (from = to = the new status) says `emailed Chris Hamblin <address>` or `email to … failed: <reason>`. The + response gains `notified: {ok, to, error?}`; no notifier configured, or a report with no address, is + `ok: false` with the reason (and the audit row). `GET /bugs/<id>` gains `canNotify` (a notifier is + configured and the report has an address). An app that passes no notifier never emails. +- **New: `bug_report.email`** — `Notice`, `render(notice) -> (subject, html)` (everything escaped) and + `AcsNotifier`, an Azure Communication Services Email sender modelled on leap-daily-report's, behind + the `[email]` extra (`azure-communication-email`, `azure-identity`). `AcsNotifier.from_env()` reads + `ACS_ENDPOINT` (managed identity; `AZURE_CLIENT_ID` picks a user-assigned one) or `ACS_CONNECTION_STRING`, + `BUG_NOTIFY_SENDER` and `BUG_NOTIFY_DOMAINS`, and returns `None` when any is missing, so + `notifier=AcsNotifier.from_env()` just does not email when unset. Fails closed: an address outside + `BUG_NOTIFY_DOMAINS` is refused before anything is sent. SDK retries are off (`retry_total=0`) and the + wait on the send is bounded (60 s). +- **New: people are named.** Reports gain `actorName` and audit rows `changedByName` (`""` when unknown; + the UI derives "Chris Hamblin" from `chris.hamblin@…` the same way `bug_report.person_name` does). + `actor_identity` may return `{"email": …, "name": …}` as well as a bare address, and now also stamps + `changedBy`/`changedByName` on a status change, replacing the request body's claim, which read "admin" + on every close. Without the hook the body's `actorName`/`changedBy`/`changedByName` are used, as before. + `BugRecord.actor_name` and `AuditEntry.changed_by_name` default to `""`, so existing constructors and + files on disk work unchanged. +- **Node:** accepts and stores `actorName`/`changedByName` (Azure Tables: `ActorName`, `ChangedByName`), + serves `canNotify: false`, and ignores `notify` (no `notified`). +- Spec: `openapi.yaml`, `types.ts`, `types.py`, and `report-contract.json` (`optionalSummaryFields`, + `optionalAuditFields`) updated; e2e contract tests cover the names on both backends. + ## backends — bug-report-py 2.1.1, bug-report-node 1.1.1 — 2026-10-20 - **Fix: `FilesystemStore` wrote a report in place, so a concurrent read saw half of it.** `put_bug` diff --git a/e2e/test_contract.py b/e2e/test_contract.py index b9ea921..e589bbe 100644 --- a/e2e/test_contract.py +++ b/e2e/test_contract.py @@ -191,3 +191,39 @@ def test_screenshot_type_is_sniffed_not_trusted(backend_url): def test_screenshot_404_when_missing(backend_url): bid = requests.post(backend_url, json={"details": "no shot"}).json()["id"] assert requests.get(f"{backend_url}/{bid}/screenshot").status_code == 404 + + +# ----- names (backends 2.2.0) ---------------------------------------- +# Both backends keep and serve the display names; neither has a mailer in this +# harness, so `notify` must not produce a `notified` block and canNotify is false. + +def test_names_are_stored_and_served(backend_url): + bid = requests.post(backend_url, json={ + "details": "names", "actorEmail": "ana.reporter@example.com", "actorName": "Ana Reporter", + }).json()["id"] + requests.patch(f"{backend_url}/{bid}", json={ + "status": "triaged", "changedBy": "sam.closer@example.com", "changedByName": "Sam Closer", + }) + rec = requests.get(f"{backend_url}/{bid}").json() + assert rec["actorName"] == "Ana Reporter" + assert rec["audit"][0]["changedByName"] == "Ana Reporter" + assert (rec["audit"][1]["changedBy"], rec["audit"][1]["changedByName"]) == ( + "sam.closer@example.com", "Sam Closer") + row = next(r for r in requests.get(backend_url).json()["bugs"] if r["id"] == bid) + assert row["actorName"] == "Ana Reporter" + + +def test_unknown_names_are_empty_strings_not_missing(backend_url): + bid = requests.post(backend_url, json={"details": "no names"}).json()["id"] + rec = requests.get(f"{backend_url}/{bid}").json() + assert rec["actorName"] == "" + assert rec["audit"][0]["changedByName"] == "" + + +def test_without_a_mailer_can_notify_is_false_and_notify_is_inert(backend_url): + bid = requests.post(backend_url, json={"details": "no mailer", "actorEmail": "ana@example.com"}).json()["id"] + assert requests.get(f"{backend_url}/{bid}").json()["canNotify"] is False + assert "canNotify" not in requests.get(backend_url).json()["bugs"][0] + r = requests.patch(f"{backend_url}/{bid}", json={"status": "triaged", "note": "x", "notify": True}) + assert r.status_code == 200 and "notified" not in r.json() + assert len(r.json()["audit"]) == 2 # filed, triaged: no emailed row diff --git a/packages/backend-node/src/index.js b/packages/backend-node/src/index.js index 5b49112..2804b66 100644 --- a/packages/backend-node/src/index.js +++ b/packages/backend-node/src/index.js @@ -31,6 +31,9 @@ export { BUG_DETAILS_MAX, BUG_SCREENSHOT_MAX, BUG_STATUSES, newBugId, validBugId const DEFAULT_ALLOW = () => true; +// A row written before backends 2.2.0 has no name; the wire says "" then. +const withChangedByName = (a) => ({ ...a, changedByName: a.changedByName || "" }); + export function createBugsRouter(opts = {}) { const store = opts.store; if (!store) throw new Error("createBugsRouter: opts.store is required"); @@ -63,6 +66,7 @@ export function createBugsRouter(opts = {}) { let title = (payload.title || details.split("\n")[0]).slice(0, 100).trim(); let addedBy = String(payload.addedBy || "web").trim().slice(0, 32) || "web"; const actorEmail = String(payload.actorEmail || defaultActorEmail || "").trim().slice(0, 200); + const actorName = String(payload.actorName || "").trim().slice(0, 200); let tags = payload.tags || ["bug"]; if (typeof tags === "string") tags = tags.split(",").map(s => s.trim()).filter(Boolean); @@ -95,6 +99,7 @@ export function createBugsRouter(opts = {}) { status: "open", addedBy, actorEmail, + actorName, addedAt: nowIso(), metaUrl: String(payload.metaUrl || "").slice(0, 500), metaUserAgent: String(payload.metaUserAgent || "").slice(0, 300), @@ -108,6 +113,7 @@ export function createBugsRouter(opts = {}) { toStatus: "open", fromStatus: null, changedBy: actorEmail || addedBy, + changedByName: actorName, note: "filed", }); @@ -143,7 +149,8 @@ export function createBugsRouter(opts = {}) { throw e; } const full = toBugFull(rec); - full.audit = await store.listAudit(rec.id); + full.canNotify = false; // this backend has no mailer + full.audit = (await store.listAudit(rec.id)).map(withChangedByName); res.json(full); }); @@ -165,12 +172,14 @@ export function createBugsRouter(opts = {}) { } const 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. const oldStatus = rec.status; if (newStatus === oldStatus) { // No-op: skip audit. const full = toBugFull(rec); - full.audit = await store.listAudit(rec.id); + full.audit = (await store.listAudit(rec.id)).map(withChangedByName); return res.json(full); } @@ -180,11 +189,12 @@ export function createBugsRouter(opts = {}) { toStatus: newStatus, fromStatus: oldStatus, changedBy, + changedByName, note, }); const full = toBugFull(updated); - full.audit = await store.listAudit(rec.id); + full.audit = (await store.listAudit(rec.id)).map(withChangedByName); res.json(full); }); diff --git a/packages/backend-node/src/store.js b/packages/backend-node/src/store.js index 167961d..07d99de 100644 --- a/packages/backend-node/src/store.js +++ b/packages/backend-node/src/store.js @@ -29,6 +29,7 @@ export function makeBugRecord(o) { status: o.status || "open", addedBy: o.addedBy || "web", actorEmail: o.actorEmail || "", + actorName: o.actorName || "", addedAt: o.addedAt, metaUrl: o.metaUrl || "", metaUserAgent: o.metaUserAgent || "", @@ -46,6 +47,7 @@ export function toBugSummary(rec) { status: rec.status, addedBy: rec.addedBy, actorEmail: rec.actorEmail, + actorName: rec.actorName || "", addedAt: rec.addedAt, screenshot: !!rec.screenshot, }; diff --git a/packages/backend-node/src/stores/azure-tables.js b/packages/backend-node/src/stores/azure-tables.js index b84381a..1a76585 100644 --- a/packages/backend-node/src/stores/azure-tables.js +++ b/packages/backend-node/src/stores/azure-tables.js @@ -72,6 +72,7 @@ function entityToBugRecord(e) { status: e.Status || "open", addedBy: e.AddedBy || "web", actorEmail: e.ActorEmail || "", + actorName: e.ActorName || "", addedAt: e.AddedAt || "", metaUrl: e.MetaUrl || "", metaUserAgent: e.MetaUserAgent || "", @@ -92,6 +93,7 @@ function bugRecordToEntity(rec) { AddedBy: rec.addedBy, AddedAt: rec.addedAt, ActorEmail: rec.actorEmail || "", + ActorName: rec.actorName || "", MetaUrl: rec.metaUrl || "", MetaUserAgent: rec.metaUserAgent || "", MetaBuildSha: rec.metaBuildSha || "", @@ -244,6 +246,7 @@ export class AzureTablesStore { FromStatus: entry.fromStatus || "", ToStatus: entry.toStatus || "", ChangedBy: entry.changedBy || "", + ChangedByName: entry.changedByName || "", ChangedAt: entry.changedAt || new Date().toISOString(), Note: entry.note || "", Action: entry.fromStatus === null || entry.fromStatus === "" ? "create" : "transition", @@ -263,6 +266,7 @@ export class AzureTablesStore { fromStatus: e.FromStatus || null, toStatus: e.ToStatus || "", changedBy: e.ChangedBy || "", + changedByName: e.ChangedByName || "", note: e.Note || "", }); } diff --git a/packages/backend-node/tests/router.test.js b/packages/backend-node/tests/router.test.js index 5486473..0bb8d37 100644 --- a/packages/backend-node/tests/router.test.js +++ b/packages/backend-node/tests/router.test.js @@ -303,6 +303,45 @@ for (const [name, makeStore] of STORES) { }); } +// --------------------------------------------------------------------- +// Names (backends 2.2.0): passed through; no mailer, so notify is ignored +// --------------------------------------------------------------------- + +for (const [name, makeStore] of STORES) { + test(`[${name}] names are stored and served; notify is ignored (no notified, canNotify false)`, async () => { + await withApp(makeStore, null, async ({ server }) => { + const json = { "Content-Type": "application/json" }; + const id = (await (await fetch(url(server, "/bugs"), { + method: "POST", headers: json, + body: JSON.stringify({ details: "d", actorEmail: "ana@example.com", actorName: "Ana Reporter" }), + })).json()).id; + const patched = await (await fetch(url(server, `/bugs/${id}`), { + method: "PATCH", headers: json, + body: JSON.stringify({ status: "declined", note: "no", notify: true, changedBy: "sam@example.com", changedByName: "Sam Closer" }), + })).json(); + assert.equal("notified" in patched, false); + const got = await (await fetch(url(server, `/bugs/${id}`))).json(); + assert.equal(got.actorName, "Ana Reporter"); + assert.equal(got.canNotify, false); + assert.equal(got.audit[0].changedByName, "Ana Reporter"); + assert.deepEqual([got.audit[1].changedBy, got.audit[1].changedByName], ["sam@example.com", "Sam Closer"]); + const list = await (await fetch(url(server, "/bugs"))).json(); + assert.equal(list.bugs[0].actorName, "Ana Reporter"); + }); + }); + + test(`[${name}] a report filed without a name says "" and its audit rows say ""`, async () => { + await withApp(makeStore, null, async ({ server }) => { + const id = (await (await fetch(url(server, "/bugs"), { + method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ details: "d" }), + })).json()).id; + const got = await (await fetch(url(server, `/bugs/${id}`))).json(); + assert.equal(got.actorName, ""); + assert.equal(got.audit[0].changedByName, ""); + }); + }); +} + // --------------------------------------------------------------------- // Single-store sanity tests // --------------------------------------------------------------------- diff --git a/packages/backend-python/README.md b/packages/backend-python/README.md index 7f9ea26..4cd9923 100644 --- a/packages/backend-python/README.md +++ b/packages/backend-python/README.md @@ -38,6 +38,27 @@ Routes mounted (under the prefix you pass): | PATCH | /bugs/{id} | `is_admin` | | GET | /bugs/{id}/screenshot | open | +## Emailing the reporter on close (2.2.0) + +```python +# pip install "bug-report-py[email]" # azure-communication-email, azure-identity +from bug_report import create_blueprint, AcsNotifier + +create_blueprint( + store=store, + actor_identity=lambda req: {"email": signed_in_address(req), "name": signed_in_name(req)}, + notifier=AcsNotifier.from_env(), # None when not configured: no emails, no tick box + app_url="https://sv.example.com", # linked when the report has no page URL +) +``` + +`PATCH {status, note, notify: true}` on a change to `resolved`/`declined` writes the change and its audit row, then +emails the reporter and writes a second audit row with the outcome. A failed send never undoes the change; the +response carries `notified: {ok, to, error?}`. Environment for `AcsNotifier.from_env()`: `ACS_ENDPOINT` (managed +identity; `AZURE_CLIENT_ID` for a user-assigned one) or `ACS_CONNECTION_STRING`, `BUG_NOTIFY_SENDER`, +`BUG_NOTIFY_DOMAINS` (comma list; an address outside it is refused). Any `notifier(notice) -> message id` that +raises on failure works in its place. + Open-by-default for POST and single-bug GET is deliberate: any user (or agent) can file, and the user who filed should be able to read back their own report. Tighten in your own auth wrapper if your threat model needs it. ## Stores diff --git a/packages/backend-python/bug_report/__init__.py b/packages/backend-python/bug_report/__init__.py index dd9629d..ccd0cf0 100644 --- a/packages/backend-python/bug_report/__init__.py +++ b/packages/backend-python/bug_report/__init__.py @@ -16,6 +16,7 @@ """ from .blueprint import create_blueprint +from .email import AcsNotifier, Notice, render from .store import ( Store, StoreError, @@ -28,6 +29,8 @@ BUG_SCREENSHOT_MAX, BUG_STATUSES, new_bug_id, + person_name, + first_name, valid_bug_id, ) @@ -48,6 +51,9 @@ __all__ = [ "create_blueprint", + "AcsNotifier", + "Notice", + "render", "contract", "KINDS", "TRANSITIONS", @@ -68,4 +74,6 @@ "BUG_STATUSES", "new_bug_id", "valid_bug_id", + "person_name", + "first_name", ] diff --git a/packages/backend-python/bug_report/blueprint.py b/packages/backend-python/bug_report/blueprint.py index 451d7ca..de343e2 100644 --- a/packages/backend-python/bug_report/blueprint.py +++ b/packages/backend-python/bug_report/blueprint.py @@ -7,17 +7,20 @@ import base64 import io +import logging import time from typing import Callable from flask import Blueprint, abort, jsonify, request, send_file from . import contract +from .email import Notice from .models import ( BUG_DETAILS_MAX, BUG_SCREENSHOT_MAX, BUG_STATUSES, new_bug_id, + person_name, screenshot_content_type, valid_bug_id, ) @@ -28,6 +31,7 @@ Store, ) +log = logging.getLogger(__name__) _last_now_ns = 0 @@ -63,6 +67,8 @@ def create_blueprint( actor_identity: Callable | None = None, build_sha: str | Callable[[], str] = "", url_prefix: str = "/bugs", + notifier: Callable | None = None, + app_url: str = "", ) -> Blueprint: """Build a Flask blueprint that serves the bug-report API. @@ -71,17 +77,25 @@ def create_blueprint( is_admin: ``(request) -> bool`` gate for ``GET /bugs`` and ``PATCH``. Default: allow everything (suitable for single-user apps). default_actor_email: Email stamped on reports filed without one. - actor_identity: ``(request) -> str`` returning the CHECKED identity of - the person filing (e.g. from EasyAuth's principal). When + actor_identity: ``(request) -> str | dict`` returning the CHECKED identity + of the person filing (e.g. from EasyAuth's principal): an + address, or ``{"email": ..., "name": ...}`` (2.2.0). When given, it alone decides the report's ``actorEmail``: the payload's ``actorEmail`` is ignored, because a page can claim any address, and an empty answer files the report with no actor rather than with the claim. Without it the - payload's value is used, as before. Added in 2.1.0. + 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. 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 mounts the whole blueprint under ``/api``. + notifier: ``(Notice) -> str`` that emails the reporter when a PATCH + closes their report with ``notify: true``; returns a message + id, raises on failure (2.2.0). See ``bug_report.email``. + ``None``: no email is ever sent. + app_url: Link used in the email when the report has no page URL. """ if is_admin is None: is_admin = lambda req: True # noqa: E731 — single-user default @@ -96,6 +110,18 @@ def _resolve_build_sha() -> str: return "" return build_sha or "" + def _identity(req) -> tuple[str, str]: + """(email, name) from the identity hook; a str answer is an address + only. An unreadable identity is no identity, never a 500.""" + try: + who = actor_identity(req) + except Exception: + return "", "" + if isinstance(who, dict): + return (str(who.get("email") or "").strip()[:200], + str(who.get("name") or "").strip()[:200]) + return (who or "").strip()[:200], "" + # ----- POST /bugs --------------------------------------------------- @bp.route(url_prefix, methods=["POST"]) @@ -114,14 +140,12 @@ def api_create(): title = (payload.get("title") or details.splitlines()[0])[:100].strip() added_by = (payload.get("addedBy") or payload.get("added_by") or "web").strip()[:32] or "web" if actor_identity is not None: - try: - actor_email = (actor_identity(request) or "").strip()[:200] - except Exception: # an identity that cannot be read is no identity, never a 500 - actor_email = "" + actor_email, actor_name = _identity(request) else: actor_email = ( payload.get("actorEmail") or payload.get("actor_email") or default_actor_email ).strip()[:200] + actor_name = str(payload.get("actorName") or payload.get("actor_name") or "").strip()[:200] tags = payload.get("tags") or ["bug"] if isinstance(tags, str): @@ -157,6 +181,7 @@ def api_create(): status="open", added_by=added_by, actor_email=actor_email, + actor_name=actor_name, added_at=_now_iso(), meta_url=(payload.get("metaUrl") or payload.get("meta_url") or "")[:500], meta_user_agent=(payload.get("metaUserAgent") or payload.get("meta_user_agent") or "")[:300], @@ -169,6 +194,7 @@ def api_create(): to_status="open", from_status=None, changed_by=actor_email or added_by, + changed_by_name=actor_name, note="filed", )) return jsonify({"id": bug.id}), 201 @@ -202,6 +228,7 @@ def api_get(bug_id: str): except NotFound: return jsonify({"error": "not found"}), 404 full = bug.to_full() + 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) @@ -234,9 +261,22 @@ def api_patch(bug_id: str): if (new_status in contract.REASON_REQUIRED_FOR and new_status != old and not note.strip()): return jsonify({"error": f"a reason is required to mark a report {new_status}"}), 400 - changed_by = ( - payload.get("changedBy") or payload.get("changed_by") or default_actor_email or "admin" - )[:200] + will_notify = (payload.get("notify") is True and new_status != old + and new_status in ("resolved", "declined")) + if will_notify and not note.strip(): + return jsonify({"error": "a note for the reporter is required to email them"}), 400 + if actor_identity is not None: + # the checked identity, not the body's claim + closer_email, changed_by_name = _identity(request) + changed_by = (closer_email or default_actor_email or "admin")[:200] + else: + changed_by = ( + payload.get("changedBy") or payload.get("changed_by") or default_actor_email or "admin" + )[:200] + changed_by_name = str( + payload.get("changedByName") or payload.get("changed_by_name") or "" + ).strip()[:200] + closer_email = changed_by if "@" in changed_by else "" old_status = old if new_status == old_status: @@ -251,12 +291,54 @@ def api_patch(bug_id: str): to_status=new_status, from_status=old_status, changed_by=changed_by, + changed_by_name=changed_by_name, note=note, )) + 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)] + if notified is not None: + full["notified"] = notified return jsonify(full) + def _notify(bug, new_status, note, closer_email, changed_by, changed_by_name) -> dict: + """Email the reporter after the change is safely written. Never raises + and never undoes the change; the outcome is its own audit row.""" + to = bug.actor_email + who = person_name(bug.actor_name, to) or "the reporter" + error = "" + if notifier is None: + error = "email is not set up on this server" + elif not to: + error = "this report has no address to email" + else: + try: + notifier(Notice( + to_email=to, to_name=person_name(bug.actor_name, to), + title=bug.title, note=note.strip(), status=new_status, + bug_id=bug.id, filed_at=bug.added_at, page_url=bug.meta_url, + app_url=app_url, closer_email=closer_email, + closer_name=person_name(changed_by_name, closer_email), + )) + except Exception as e: + log.warning("bug notify: %s: %s", bug.id, e) + error = (str(e) or type(e).__name__)[:200] + label = f"{who} <{to}>" if to else who + store.append_audit(bug.id, AuditEntry( + changed_at=_now_iso(), + to_status=new_status, + from_status=new_status, + changed_by=changed_by, + changed_by_name=changed_by_name, + note=(f"email to {label} failed: {error}" if error else f"emailed {label}")[:500], + )) + out = {"ok": not error, "to": to} + if error: + out["error"] = error + return out + # ----- GET /bugs/<id>/screenshot ----------------------------------- @bp.route(f"{url_prefix}/<bug_id>/screenshot", methods=["GET"]) diff --git a/packages/backend-python/bug_report/email.py b/packages/backend-python/bug_report/email.py new file mode 100644 index 0000000..bd55200 --- /dev/null +++ b/packages/backend-python/bug_report/email.py @@ -0,0 +1,223 @@ +"""Telling the reporter their report was closed, by email. + +``create_blueprint(notifier=...)`` takes any ``notifier(notice) -> str`` that +returns a message id and raises on failure. This module ships the pieces a +Leap app needs: :class:`Notice` (what the blueprint hands over), :func:`render` +(subject + HTML, pure), and :class:`AcsNotifier` (Azure Communication Services +Email, behind the ``[email]`` extra, modelled on leap-daily-report's +``report_email.py``). + +Nothing here imports Azure at import time, so ``import bug_report`` works +without the extra; an app that passes no notifier never emails. + +Environment read by :meth:`AcsNotifier.from_env`: + +``ACS_ENDPOINT`` managed identity (``DefaultAzureCredential``; + ``AZURE_CLIENT_ID`` picks a user-assigned identity) +``ACS_CONNECTION_STRING`` fallback when there is no endpoint +``BUG_NOTIFY_SENDER`` the From address, e.g. ``bugs@helloleap.ai`` +``BUG_NOTIFY_DOMAINS`` comma list of domains it may write to; an address + outside it is refused (fail closed) +""" + +from __future__ import annotations + +import html as _html +import logging +import os +import re +from dataclasses import dataclass +from datetime import date + +from .models import first_name, person_name + +log = logging.getLogger(__name__) + +FROM_NAME = "Leap bug reports" +SEND_TIMEOUT = 60 # seconds the poller may be waited on; bounded, never forever + + +@dataclass +class Notice: + """One closed report, as the blueprint hands it to a notifier.""" + to_email: str + to_name: str + title: str + note: str + status: str # "resolved" | "declined" + bug_id: str + filed_at: str = "" # ISO timestamp + page_url: str = "" # the report's metaUrl + app_url: str = "" + closer_email: str = "" + closer_name: str = "" + + +# --------------------------------------------------------------------------- +# Rendering (pure) +# --------------------------------------------------------------------------- + +_URL_RE = re.compile(r"https?://[^\s<>\"']+") +_TRAILING = ".,;:!?)]}" + + +def _one_line(s: str) -> str: + return " ".join((s or "").split()) + + +def _subject(n: Notice) -> str: + title = _one_line(n.title) + if n.status == "resolved": + return f"Fixed: {title}" + if n.status == "declined": + return f"Your bug report: {title} — not taken forward" + raise ValueError(f"no email for status {n.status!r}") + + +def _note_html(note: str) -> str: + """Escape the note, make http(s) URLs links, keep its line breaks.""" + out = [] + pos = 0 + for m in _URL_RE.finditer(note): + url = m.group(0) + tail = "" + while url and url[-1] in _TRAILING: + tail = url[-1] + tail + url = url[:-1] + out.append(_html.escape(note[pos:m.start()])) + if url: + u = _html.escape(url, quote=True) + out.append(f'<a href="{u}">{u}</a>') + out.append(_html.escape(tail)) + pos = m.end() + out.append(_html.escape(note[pos:])) + return "".join(out).replace("\r\n", "\n").replace("\n", "<br>\n") + + +def _pretty_date(iso: str) -> str: + try: + d = date.fromisoformat((iso or "")[:10]) + except ValueError: + return "" + return f"{d.day} {d:%B} {d.year}" + + +def render(notice: Notice) -> tuple[str, str]: + """``(subject, html)`` for a closed report. Everything from the report is + HTML-escaped; only http(s) URLs become links.""" + subject = _subject(notice) + hi = first_name(notice.to_name, notice.to_email) + closer = person_name(notice.closer_name, notice.closer_email) + when = _pretty_date(notice.filed_at) + link = next((u for u in (notice.page_url, notice.app_url) + if (u or "").startswith(("http://", "https://"))), "") + + parts = [f"<p>Hi {_html.escape(hi)},</p>" if hi else "<p>Hello,</p>"] + parts.append(f"<p>{_note_html(notice.note.strip())}</p>") + parts.append(f"<p>— {_html.escape(closer or FROM_NAME)}</p>") + + said = "You reported this" + if when: + said += f" on {when}" + if link: + u = _html.escape(link, quote=True) + said += f' from <a href="{u}">{u}</a>' + parts.append(f'<p style="color:#666;font-size:13px">{said}.<br>' + f"Report {_html.escape(notice.bug_id)}</p>") + body = "\n".join(parts) + return subject, f'<div style="font-family:sans-serif;font-size:15px">\n{body}\n</div>' + + +# --------------------------------------------------------------------------- +# Sending (Azure Communication Services Email) +# --------------------------------------------------------------------------- + +def _domain(address: str) -> str: + return address.rsplit("@", 1)[-1].strip().lower() if "@" in address else "" + + +class AcsNotifier: + """``notifier(notice) -> message id`` over ACS Email. + + Fails closed: no sender, or an address outside ``domains``, raises before + anything is sent. ``retry_total=0`` because the SDK's own retry re-sends a + throttled request immediately, and each attempt counts against the quota + that refused it (the daily report's lesson, 2026-09-15). The wait on the + poller is bounded by ``timeout``. + """ + + def __init__(self, *, sender: str, domains, endpoint: str = "", + connection_string: str = "", client_id: str = "", + client=None, timeout: float = SEND_TIMEOUT) -> None: + self.sender = (sender or "").strip() + if isinstance(domains, str): + domains = domains.split(",") + self.domains = tuple(d.strip().lstrip("@").lower() for d in (domains or ()) if d.strip()) + self.endpoint = (endpoint or "").strip() + self.connection_string = (connection_string or "").strip() + self.client_id = (client_id or "").strip() + self.timeout = timeout + self._client = client + + @classmethod + def from_env(cls, env=None): + """The notifier the environment describes, or ``None`` when it does not + (no credential, no sender, or no allowed domains), so an app can write + ``notifier=AcsNotifier.from_env()`` and simply not email when unset.""" + env = os.environ if env is None else env + endpoint = env.get("ACS_ENDPOINT", "").strip() + conn = env.get("ACS_CONNECTION_STRING", "").strip() + sender = env.get("BUG_NOTIFY_SENDER", "").strip() + domains = env.get("BUG_NOTIFY_DOMAINS", "").strip() + if not (endpoint or conn) or not sender: + return None + if not domains: + log.warning("bug notify: BUG_NOTIFY_DOMAINS not set; emailing reporters is off (fail closed)") + return None + return cls(sender=sender, domains=domains, endpoint=endpoint, + connection_string=conn, client_id=env.get("AZURE_CLIENT_ID", "")) + + def _get_client(self): + if self._client is None: + from azure.communication.email import EmailClient # lazy: the [email] extra + if self.endpoint: + from azure.identity import DefaultAzureCredential + kw = {"managed_identity_client_id": self.client_id} if self.client_id else {} + self._client = EmailClient(self.endpoint, DefaultAzureCredential(**kw), retry_total=0) + elif self.connection_string: + self._client = EmailClient.from_connection_string(self.connection_string, retry_total=0) + else: + raise RuntimeError("neither ACS_ENDPOINT nor ACS_CONNECTION_STRING set (fail closed)") + return self._client + + def __call__(self, notice: Notice) -> str: + if not self.sender: + raise RuntimeError("BUG_NOTIFY_SENDER not set (fail closed)") + to = (notice.to_email or "").strip() + if not to: + raise RuntimeError("no address to send to") + if not self.domains: + raise RuntimeError("BUG_NOTIFY_DOMAINS not set (fail closed)") + if _domain(to) not in self.domains: + raise RuntimeError(f"{_domain(to) or to} is not an allowed domain; not sent") + subject, body = render(notice) + recipient = {"address": to} + if notice.to_name: + recipient["displayName"] = notice.to_name + message = { + "senderAddress": self.sender, + "content": {"subject": subject, "html": body}, + "recipients": {"to": [recipient]}, + } + if notice.closer_email: + reply = {"address": notice.closer_email} + name = person_name(notice.closer_name, notice.closer_email) + if name: + reply["displayName"] = name + message["replyTo"] = [reply] + result = self._get_client().begin_send(message).result(timeout=self.timeout) + get = result.get if isinstance(result, dict) else (lambda k, d=None: getattr(result, k, d)) + status = getattr(get("status"), "value", get("status")) + if status is not None and str(status).lower() != "succeeded": + raise RuntimeError(f"ACS reported {status}") + return str(get("id") or "") diff --git a/packages/backend-python/bug_report/models.py b/packages/backend-python/bug_report/models.py index d21373a..ad7d594 100644 --- a/packages/backend-python/bug_report/models.py +++ b/packages/backend-python/bug_report/models.py @@ -53,3 +53,21 @@ def new_bug_id() -> str: def valid_bug_id(bug_id: str) -> bool: return bool(_BUG_ID_RE.match(bug_id or "")) + + +def person_name(name: str | None, email: str | None) -> str: + """The display name of a person: the stored ``name``, else one derived from + the address's local part (``chris.hamblin@x`` -> ``Chris Hamblin``, ``ken@x`` + -> ``Ken``), else "". The same rule the UI uses; the two must agree.""" + name = (name or "").strip() + if name: + return name + local = (email or "").strip().split("@", 1)[0] + parts = [p for p in re.split(r"[._-]+", local) if p] + return " ".join(p[:1].upper() + p[1:] for p in parts) + + +def first_name(name: str | None, email: str | None = "") -> str: + """First word of :func:`person_name`.""" + full = person_name(name, email) + return full.split(None, 1)[0] if full else "" diff --git a/packages/backend-python/bug_report/store.py b/packages/backend-python/bug_report/store.py index ba6cb4e..038166a 100644 --- a/packages/backend-python/bug_report/store.py +++ b/packages/backend-python/bug_report/store.py @@ -55,6 +55,9 @@ class BugRecord: meta_build_sha: str = "" screenshot: bool = False transcript: list[dict] | None = None + # 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 = "" def to_summary(self) -> dict: return { @@ -64,6 +67,7 @@ def to_summary(self) -> dict: "status": self.status, "addedBy": self.added_by, "actorEmail": self.actor_email, + "actorName": self.actor_name, "addedAt": self.added_at, "screenshot": bool(self.screenshot), } @@ -87,11 +91,13 @@ class AuditEntry: from_status: str | None = None changed_by: str = "" note: str = "" + changed_by_name: str = "" # display name of changed_by; added in 2.2.0 def to_dict(self) -> dict: return { "changedAt": self.changed_at, "changedBy": self.changed_by, + "changedByName": self.changed_by_name, "fromStatus": self.from_status, "toStatus": self.to_status, "note": self.note, @@ -332,6 +338,7 @@ def list_audit(self, bug_id): from_status=d.get("fromStatus") if "fromStatus" in d else d.get("from_status"), changed_by=d.get("changedBy") or d.get("changed_by", ""), note=d.get("note", ""), + changed_by_name=d.get("changedByName") or d.get("changed_by_name", ""), )) return out diff --git a/packages/backend-python/pyproject.toml b/packages/backend-python/pyproject.toml index 97d8f47..daf7bb2 100644 --- a/packages/backend-python/pyproject.toml +++ b/packages/backend-python/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "bug-report-py" -version = "2.1.1" +version = "2.2.0" description = "Flask blueprint + storage interface implementing the bug-report-widget API spec." readme = "README.md" license = { text = "MIT" } @@ -11,6 +11,7 @@ dependencies = [ ] [project.optional-dependencies] +email = ["azure-communication-email>=1.0", "azure-identity>=1.15"] test = [ "pytest>=7.0", ] diff --git a/packages/backend-python/tests/test_email.py b/packages/backend-python/tests/test_email.py new file mode 100644 index 0000000..1bfd1b0 --- /dev/null +++ b/packages/backend-python/tests/test_email.py @@ -0,0 +1,270 @@ +"""bug_report.email: render() and AcsNotifier, with the Azure SDK stubbed. No network.""" + +from __future__ import annotations + +import sys +import types + +import pytest + +from bug_report.email import AcsNotifier, Notice, render +from bug_report.models import first_name, person_name + + +def notice(**kw): + base = dict(to_email="ana.reporter@example.com", to_name="Ana Reporter", title="Jam light stays on", + note="Fixed in build 41.", status="resolved", bug_id="bug-20261112-124952-abcdef", + filed_at="2026-11-12T12:49:52.000000Z", page_url="https://sv.example/day?x=1&y=2", + app_url="https://app.example/", closer_email="sam.closer@example.com", + closer_name="Sam Closer") + base.update(kw) + return Notice(**base) + + +# ----- names ----------------------------------------------------------------- + +@pytest.mark.parametrize("name,email,full,first", [ + ("Ana Reporter", "x@y", "Ana Reporter", "Ana"), + ("", "ana.reporter@x.com", "Ana Reporter", "Ana"), + ("", "sam@x.com", "Sam", "Sam"), + (None, "a_b-c.d@x.com", "A B C D", "A"), + ("", "", "", ""), +]) +def test_name_fallback_rule(name, email, full, first): + assert person_name(name, email) == full + assert first_name(name, email) == first + + +# ----- render ---------------------------------------------------------------- + +def test_subject_per_status(): + assert render(notice())[0] == "Fixed: Jam light stays on" + assert render(notice(status="declined"))[0] == \ + "Your bug report: Jam light stays on — not taken forward" + + +def test_other_statuses_have_no_email(): + with pytest.raises(ValueError): + render(notice(status="triaged")) + + +def test_body_has_first_name_note_signature_date_link_and_id(): + _, html = render(notice()) + assert "Hi Ana," in html + assert "Fixed in build 41." in html + assert "— Sam Closer" in html + assert "12 November 2026" in html + assert 'href="https://sv.example/day?x=1&y=2"' in html # the page they filed from + assert "bug-20261112-124952-abcdef" in html + + +def test_link_falls_back_to_the_app_when_there_is_no_page_url(): + _, html = render(notice(page_url="")) + assert 'href="https://app.example/"' in html + + +def test_no_link_when_neither_is_http(): + _, html = render(notice(page_url="javascript:alert(1)", app_url="")) + assert "href" not in html and "javascript" not in html + + +def test_everything_from_the_report_is_escaped(): + evil = "<script>alert(1)</script>" + sub, html = render(notice(to_name=evil + " Q", title=evil, note=evil, closer_name=evil, + bug_id=evil, page_url='https://x/"><img src=x>')) + assert "<script>" not in html and "<img" not in html + assert "<script>" in html + assert "<script>" in sub # a subject is plain text, not HTML + + +def test_urls_in_the_note_become_links_and_newlines_stay(): + _, html = render(notice(note='See https://git.example/pr/7, then\nreload "now"')) + assert '<a href="https://git.example/pr/7">https://git.example/pr/7</a>,' in html + assert "then<br>\nreload "now"" in html + + +def test_a_note_url_cannot_break_out_of_its_href(): + _, html = render(notice(note="https://a.example/x\"onmouseover=\"y")) + assert 'onmouseover="' not in html + + +def test_title_newlines_do_not_reach_the_subject(): + assert "\n" not in render(notice(title="a\r\nBcc: evil@example.com"))[0] + + +def test_first_name_from_the_address_when_the_name_is_missing(): + _, html = render(notice(to_name="")) + assert "Hi Ana," in html + + +def test_signed_by_the_derived_closer_name_or_the_service(): + assert "— Sam Closer" in render(notice(closer_name=""))[1] + assert "— Leap bug reports" in render(notice(closer_name="", closer_email=""))[1] + + +# ----- AcsNotifier -------------------------------------------------------------- + +class FakePoller: + def __init__(self, result): + self.result_value, self.timeout = result, "unset" + + def result(self, timeout=None): + self.timeout = timeout + return self.result_value + + +class FakeClient: + def __init__(self, result=None): + self.result = result if result is not None else {"id": "op-1", "status": "Succeeded"} + self.messages, self.poller = [], None + + def begin_send(self, message): + self.messages.append(message) + self.poller = FakePoller(self.result) + return self.poller + + +def make(client=None, **kw): + base = dict(sender="bugs@example.com", domains="example.com", client=client or FakeClient()) + base.update(kw) + return AcsNotifier(**base) + + +def test_send_builds_the_message_and_returns_the_id(): + c = FakeClient() + assert make(c)(notice()) == "op-1" + m = c.messages[0] + assert m["senderAddress"] == "bugs@example.com" + assert m["recipients"]["to"] == [{"address": "ana.reporter@example.com", "displayName": "Ana Reporter"}] + assert m["replyTo"] == [{"address": "sam.closer@example.com", "displayName": "Sam Closer"}] + assert m["content"]["subject"] == "Fixed: Jam light stays on" and "Hi Ana," in m["content"]["html"] + assert c.poller.timeout is not None # the wait is bounded + + +def test_no_reply_to_without_a_closer_address(): + c = FakeClient() + make(c)(notice(closer_email="", closer_name="")) + assert "replyTo" not in c.messages[0] + + +@pytest.mark.parametrize("to", ["ana@evil.test", "ana@example.com.evil.test", "nobody", ""]) +def test_an_address_outside_the_domains_is_refused_before_any_send(to): + c = FakeClient() + with pytest.raises(RuntimeError): + make(c)(notice(to_email=to)) + assert c.messages == [] + + +def test_domain_match_ignores_case_and_a_leading_at(): + c = FakeClient() + make(c, domains=" @Example.COM , other.com")(notice(to_email="Ana@EXAMPLE.com")) + assert len(c.messages) == 1 + + +def test_no_domains_refuses_everything_fail_closed(): + c = FakeClient() + with pytest.raises(RuntimeError, match="BUG_NOTIFY_DOMAINS"): + make(c, domains="")(notice()) + assert c.messages == [] + + +def test_no_sender_refuses_fail_closed(): + c = FakeClient() + with pytest.raises(RuntimeError, match="BUG_NOTIFY_SENDER"): + make(c, sender="")(notice()) + assert c.messages == [] + + +def test_a_send_that_does_not_succeed_raises(): + with pytest.raises(RuntimeError, match="Failed"): + make(FakeClient({"id": "x", "status": "Failed"}))(notice()) + + +def test_the_sdk_error_propagates_so_the_blueprint_can_audit_it(): + class Boom(FakeClient): + def begin_send(self, message): + raise OSError("429 slow down") + with pytest.raises(OSError, match="429"): + make(Boom())(notice()) + + +# --- from_env and the real client's construction, with the Azure modules stubbed + +GOOD = {"ACS_ENDPOINT": "https://comms.example", "BUG_NOTIFY_SENDER": "bugs@example.com", + "BUG_NOTIFY_DOMAINS": "example.com"} + + +@pytest.mark.parametrize("drop", ["BUG_NOTIFY_SENDER", "BUG_NOTIFY_DOMAINS", "ACS_ENDPOINT"]) +def test_from_env_is_none_when_not_fully_configured(drop): + env = {k: v for k, v in GOOD.items() if k != drop} + assert AcsNotifier.from_env(env) is None + + +def test_from_env_is_none_with_nothing_set(): + assert AcsNotifier.from_env({}) is None + + +def test_from_env_reads_the_config(): + n = AcsNotifier.from_env({**GOOD, "BUG_NOTIFY_DOMAINS": "a.com, b.com", "AZURE_CLIENT_ID": "cid"}) + assert (n.sender, n.domains, n.endpoint, n.client_id) == ( + "bugs@example.com", ("a.com", "b.com"), "https://comms.example", "cid") + + +@pytest.fixture +def azure(monkeypatch): + calls = {} + + class EmailClient: + def __init__(self, endpoint, credential, **kw): + calls["endpoint"] = (endpoint, credential, kw) + + @classmethod + def from_connection_string(cls, conn, **kw): + calls["conn"] = (conn, kw) + return types.SimpleNamespace(begin_send=lambda m: FakePoller({"id": "s", "status": "Succeeded"})) + + def begin_send(self, m): + calls["sent"] = m + return FakePoller({"id": "e", "status": "Succeeded"}) + + def dac(**kw): + calls["cred"] = kw + return "CRED" + + mods = {"azure": types.ModuleType("azure"), + "azure.communication": types.ModuleType("azure.communication"), + "azure.communication.email": types.SimpleNamespace(EmailClient=EmailClient), + "azure.identity": types.SimpleNamespace(DefaultAzureCredential=dac)} + for k, v in mods.items(): + monkeypatch.setitem(sys.modules, k, v) + return calls + + +def test_endpoint_uses_managed_identity_with_retries_off(azure): + n = AcsNotifier.from_env({**GOOD, "AZURE_CLIENT_ID": "cid"}) + assert n(notice()) == "e" + assert azure["cred"] == {"managed_identity_client_id": "cid"} + assert azure["endpoint"] == ("https://comms.example", "CRED", {"retry_total": 0}) + + +def test_endpoint_without_a_client_id_uses_the_default_credential(azure): + AcsNotifier.from_env(GOOD)(notice()) + assert azure["cred"] == {} + + +def test_connection_string_is_the_fallback_with_retries_off(azure): + env = {"ACS_CONNECTION_STRING": "endpoint=x;accesskey=y", "BUG_NOTIFY_SENDER": "bugs@example.com", + "BUG_NOTIFY_DOMAINS": "example.com"} + assert AcsNotifier.from_env(env)(notice()) == "s" + assert azure["conn"] == ("endpoint=x;accesskey=y", {"retry_total": 0}) + + +def test_the_endpoint_wins_over_the_connection_string(azure): + AcsNotifier.from_env({**GOOD, "ACS_CONNECTION_STRING": "endpoint=x"})(notice()) + assert "endpoint" in azure and "conn" not in azure + + +def test_a_refused_domain_never_builds_the_client(azure): + with pytest.raises(RuntimeError): + AcsNotifier.from_env(GOOD)(notice(to_email="x@evil.test")) + assert "endpoint" not in azure and "conn" not in azure diff --git a/packages/backend-python/tests/test_notify.py b/packages/backend-python/tests/test_notify.py new file mode 100644 index 0000000..227c9c2 --- /dev/null +++ b/packages/backend-python/tests/test_notify.py @@ -0,0 +1,299 @@ +"""Closing a report can email the reporter (2.2.0): the blueprint's side. + +A fake notifier stands in for ACS; nothing here touches a network.""" + +from __future__ import annotations + +import json + +import pytest +from flask import Flask + +from bug_report import FilesystemStore, InMemoryStore, create_blueprint +from bug_report.store import AuditEntry, BugRecord + +ANA = {"email": "ana.reporter@example.com", "name": "Ana Reporter"} +SAM = {"email": "sam.closer@example.com", "name": "Sam Closer"} + + +@pytest.fixture(params=["memory", "filesystem"]) +def store(request, tmp_path): + return InMemoryStore() if request.param == "memory" else FilesystemStore(tmp_path / "bugs") + + +class FakeNotifier: + def __init__(self, fail=None): + self.sent = [] + self.fail = fail + + def __call__(self, notice): + if self.fail: + raise self.fail + self.sent.append(notice) + return "msg-1" + + +def make(store, notifier): + """A client whose identity is read from the X-As header: 'ana' or 'sam'.""" + people = {"ana": ANA, "sam": SAM} + app = Flask(__name__) + app.register_blueprint(create_blueprint( + store=store, is_admin=lambda r: True, notifier=notifier, app_url="https://app.example/", + actor_identity=lambda r: people.get(r.headers.get("X-As", ""), ""))) + return app.test_client() + + +def file_as_ana(c): + r = c.post("/bugs", json={"details": "Jam light stays on\nmore", "metaUrl": "https://sv.example/day"}, + headers={"X-As": "ana"}) + return r.get_json()["id"] + + +def patch(c, bid, **body): + return c.patch(f"/bugs/{bid}", json=body, headers={"X-As": "sam"}) + + +def to_triaged(c, bid): + assert patch(c, bid, status="triaged").status_code == 200 + + +# ----- sending ------------------------------------------------------------- + +def test_notify_sends_once_to_the_reporter_with_the_closer_as_reply_to(store): + n = FakeNotifier() + c = make(store, n) + bid = file_as_ana(c) + to_triaged(c, bid) + r = patch(c, bid, status="resolved", note="Fixed in build 41, thanks Ana", notify=True) + assert r.status_code == 200 + assert len(n.sent) == 1 + s = n.sent[0] + assert (s.to_email, s.to_name) == (ANA["email"], "Ana Reporter") + assert (s.closer_email, s.closer_name) == (SAM["email"], "Sam Closer") + assert s.status == "resolved" and s.note == "Fixed in build 41, thanks Ana" + assert s.title == "Jam light stays on" and s.bug_id == bid + assert s.page_url == "https://sv.example/day" and s.app_url == "https://app.example/" + assert r.get_json()["notified"] == {"ok": True, "to": ANA["email"]} + + +def test_declined_sends_with_declined_status(store): + n = FakeNotifier() + c = make(store, n) + bid = file_as_ana(c) + patch(c, bid, status="declined", note="Works as designed", notify=True) + assert [s.status for s in n.sent] == ["declined"] + + +def test_the_change_and_its_audit_row_come_first_then_an_emailed_row(store): + c = make(store, FakeNotifier()) + bid = file_as_ana(c) + to_triaged(c, bid) + audit = patch(c, bid, status="resolved", note="done", notify=True).get_json()["audit"] + assert [(a["fromStatus"], a["toStatus"]) for a in audit] == [ + (None, "open"), ("open", "triaged"), ("triaged", "resolved"), ("resolved", "resolved")] + last = audit[-1] + assert last["note"] == "emailed Ana Reporter <ana.reporter@example.com>" + # who: the signed-in address and name, never the request body + assert (last["changedBy"], last["changedByName"]) == (SAM["email"], "Sam Closer") + assert (audit[2]["changedBy"], audit[2]["changedByName"]) == (SAM["email"], "Sam Closer") + + +def test_a_failing_send_still_resolves_and_writes_the_failure_row(store): + c = make(store, FakeNotifier(fail=RuntimeError("ACS said no"))) + bid = file_as_ana(c) + to_triaged(c, bid) + r = patch(c, bid, status="resolved", note="done", notify=True) + assert r.status_code == 200 + body = r.get_json() + assert body["status"] == "resolved" + assert body["notified"] == {"ok": False, "to": ANA["email"], "error": "ACS said no"} + assert body["audit"][-1]["note"] == "email to Ana Reporter <ana.reporter@example.com> failed: ACS said no" + assert store.get_bug(bid).status == "resolved" + + +def test_a_notifier_that_raises_with_no_message_still_gives_a_reason(store): + c = make(store, FakeNotifier(fail=RuntimeError())) + bid = file_as_ana(c) + to_triaged(c, bid) + assert patch(c, bid, status="resolved", note="x", notify=True).get_json()["notified"]["error"] == "RuntimeError" + + +# ----- when it must NOT send ----------------------------------------------- + +@pytest.mark.parametrize("body", [ + {"status": "resolved", "note": "done"}, # notify absent + {"status": "resolved", "note": "done", "notify": False}, + {"status": "resolved", "note": "done", "notify": "true"}, # only a real true counts +]) +def test_without_notify_true_nothing_is_sent_and_no_notified_key(store, body): + n = FakeNotifier() + c = make(store, n) + bid = file_as_ana(c) + to_triaged(c, bid) + r = patch(c, bid, **body) + assert n.sent == [] and "notified" not in r.get_json() + assert len(r.get_json()["audit"]) == 3 # filed, triaged, resolved: no emailed row + + +def test_reopening_never_emails_even_with_notify(store): + n = FakeNotifier() + c = make(store, n) + bid = file_as_ana(c) + patch(c, bid, status="declined", note="no") + r = patch(c, bid, status="open", note="back on", notify=True) + assert r.status_code == 200 + assert n.sent == [] and "notified" not in r.get_json() + + +def test_notify_on_a_status_that_is_not_a_close_is_ignored(store): + n = FakeNotifier() + c = make(store, n) + bid = file_as_ana(c) + r = patch(c, bid, status="triaged", notify=True) + assert r.status_code == 200 and n.sent == [] and "notified" not in r.get_json() + + +def test_the_same_status_is_a_no_op_and_sends_nothing(store): + n = FakeNotifier() + c = make(store, n) + bid = file_as_ana(c) + patch(c, bid, status="declined", note="no") + r = patch(c, bid, status="declined", note="again", notify=True) + assert n.sent == [] and "notified" not in r.get_json() + + +@pytest.mark.parametrize("note", [None, "", " "]) +def test_notify_needs_a_note_and_changes_nothing_without_one(store, note): + n = FakeNotifier() + c = make(store, n) + bid = file_as_ana(c) + to_triaged(c, bid) + body = {"status": "resolved", "notify": True} + if note is not None: + body["note"] = note + r = patch(c, bid, **body) + assert r.status_code == 400 + assert r.get_json() == {"error": "a note for the reporter is required to email them"} + assert store.get_bug(bid).status == "triaged" and n.sent == [] + + +# ----- no notifier / no address --------------------------------------------- + +def test_no_notifier_configured_gives_ok_false_and_an_audit_row(store): + c = make(store, None) + bid = file_as_ana(c) + to_triaged(c, bid) + r = patch(c, bid, status="resolved", note="done", notify=True) + body = r.get_json() + assert r.status_code == 200 and body["status"] == "resolved" + assert body["notified"]["ok"] is False and "not set up" in body["notified"]["error"] + assert body["audit"][-1]["note"].startswith("email to Ana Reporter <ana.reporter@example.com> failed:") + + +def test_a_report_with_no_address_cannot_be_emailed(store): + n = FakeNotifier() + c = make(store, n) + bid = c.post("/bugs", json={"details": "anonymous"}).get_json()["id"] # no X-As: no identity + patch(c, bid, status="triaged") + body = patch(c, bid, status="resolved", note="done", notify=True).get_json() + assert n.sent == [] + assert body["notified"] == {"ok": False, "to": "", "error": "this report has no address to email"} + assert "failed: this report has no address" in body["audit"][-1]["note"] + + +# ----- canNotify ------------------------------------------------------------- + +def test_can_notify_needs_a_notifier_and_an_address(store): + with_n = make(store, FakeNotifier()) + with_addr = file_as_ana(with_n) + no_addr = with_n.post("/bugs", json={"details": "x"}).get_json()["id"] + assert with_n.get(f"/bugs/{with_addr}").get_json()["canNotify"] is True + assert with_n.get(f"/bugs/{no_addr}").get_json()["canNotify"] is False + assert make(store, None).get(f"/bugs/{with_addr}").get_json()["canNotify"] is False + + +def test_can_notify_is_on_the_detail_not_the_list(store): + c = make(store, FakeNotifier()) + file_as_ana(c) + assert "canNotify" not in c.get("/bugs").get_json()["bugs"][0] + + +# ----- names ------------------------------------------------------------------ + +def test_actor_name_is_stored_at_filing_and_served(store): + c = make(store, None) + bid = file_as_ana(c) + assert store.get_bug(bid).actor_name == "Ana Reporter" + assert c.get(f"/bugs/{bid}").get_json()["actorName"] == "Ana Reporter" + assert c.get("/bugs").get_json()["bugs"][0]["actorName"] == "Ana Reporter" + assert c.get(f"/bugs/{bid}").get_json()["audit"][0]["changedByName"] == "Ana Reporter" + + +def test_a_str_returning_actor_identity_still_works(store): + app = Flask(__name__) + app.register_blueprint(create_blueprint(store=store, actor_identity=lambda r: "old.style@example.com")) + c = app.test_client() + bid = c.post("/bugs", json={"details": "d"}).get_json()["id"] + rec = store.get_bug(bid) + assert (rec.actor_email, rec.actor_name) == ("old.style@example.com", "") + r = c.patch(f"/bugs/{bid}", json={"status": "triaged", "changedBy": "claimed"}) + audit = r.get_json()["audit"][-1] + assert (audit["changedBy"], audit["changedByName"]) == ("old.style@example.com", "") + + +def test_the_identity_not_the_body_decides_changed_by(store): + c = make(store, None) + bid = file_as_ana(c) + r = c.patch(f"/bugs/{bid}", json={"status": "triaged", "changedBy": "mallory", "changedByName": "Mallory"}, + headers={"X-As": "sam"}) + a = r.get_json()["audit"][-1] + assert (a["changedBy"], a["changedByName"]) == (SAM["email"], "Sam Closer") + + +def test_without_a_hook_the_body_still_supplies_changed_by_and_its_name(store): + app = Flask(__name__) + app.register_blueprint(create_blueprint(store=store)) + c = app.test_client() + bid = c.post("/bugs", json={"details": "d", "actorName": "Pat Lee", "actorEmail": "pat@example.com"} + ).get_json()["id"] + a = c.patch(f"/bugs/{bid}", json={"status": "triaged", "changedBy": "sam@example.com", "changedByName": "Sam"} + ).get_json() + assert store.get_bug(bid).actor_name == "Pat Lee" + assert (a["audit"][-1]["changedBy"], a["audit"][-1]["changedByName"]) == ("sam@example.com", "Sam") + + +def test_the_name_falls_back_to_the_address_in_the_notice_and_the_audit_note(store): + n = FakeNotifier() + c = make(store, n) + # reporter with an address but no stored name (filed before 2.2.0) + store.put_bug(BugRecord(id="bug-20260101-000000-aaaaaa", title="t", details="d", tags=["bug"], + status="open", added_by="web", actor_email="ana.reporter@example.com", + added_at="2099-01-01T00:00:00.000000Z"), None) + body = patch(c, "bug-20260101-000000-aaaaaa", status="declined", note="no", notify=True).get_json() + assert n.sent[0].to_name == "Ana Reporter" + assert body["audit"][-1]["note"] == "emailed Ana Reporter <ana.reporter@example.com>" + + +# ----- old data ------------------------------------------------------------------ + +def test_a_report_and_audit_on_disk_without_the_new_fields_still_load(tmp_path): + st = FilesystemStore(tmp_path) + old = {"id": "bug-20260101-000000-bbbbbb", "title": "t", "details": "d", "tags": ["bug"], + "status": "open", "added_by": "web", "actor_email": "a@example.com", + "added_at": "2099-01-01T00:00:00.000000Z", "meta_url": "", "meta_user_agent": "", + "meta_build_sha": "", "screenshot": False, "transcript": None} + (tmp_path / "bug-20260101-000000-bbbbbb.json").write_text(json.dumps(old)) + (tmp_path / "bug-20260101-000000-bbbbbb.audit.jsonl").write_text(json.dumps( + {"changedAt": "2099-01-01T00:00:00.000000Z", "changedBy": "a@example.com", "fromStatus": None, + "toStatus": "open", "note": "filed"}) + "\n") + assert st.get_bug(old["id"]).actor_name == "" + assert st.list_audit(old["id"])[0].changed_by_name == "" + app = Flask(__name__) + app.register_blueprint(create_blueprint(store=st)) + full = app.test_client().get(f"/bugs/{old['id']}").get_json() + assert full["actorName"] == "" and full["audit"][0]["changedByName"] == "" + + +def test_the_old_constructors_still_work(): + BugRecord("i", "t", "d", [], "open", "web", "a@example.com", "2099") + AuditEntry("2099", "open") diff --git a/packages/spec/README.md b/packages/spec/README.md index 082c645..04cd5ce 100644 --- a/packages/spec/README.md +++ b/packages/spec/README.md @@ -48,3 +48,11 @@ consuming apps) with a test asserting the two agree. 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. + +## People are named; closing can email the reporter (backends 2.2.0) + +All additive and optional, so older data and older clients keep working: + +- `actorName` on a report and `changedByName` on an audit row: the display name beside the address. `""` when unknown. A reader derives a name from the address when it is empty (split the local part on `.` `_` `-`, capitalise each part: `chris.hamblin@x` is "Chris Hamblin", `ken@x` is "Ken"); the first name is the first word. +- `canNotify` on `GET /bugs/{id}` only: this server can email the reporter and the report has an `actorEmail`. +- `PATCH` takes `notify: true` (default false). It is acted on only when the status actually changes to `resolved` or `declined` (reopening never emails), needs a non-empty `note`, and writes the change and its audit row before the send. The response gains `notified: {ok, to, error?}`; a second audit row (from = to = the new status) records `emailed <name> <address>` or `email to <name> <address> failed: <reason>`. The Node backend has no mailer: it ignores `notify` and returns no `notified`. diff --git a/packages/spec/openapi.yaml b/packages/spec/openapi.yaml index 0b9ee1d..49bdee5 100644 --- a/packages/spec/openapi.yaml +++ b/packages/spec/openapi.yaml @@ -108,6 +108,15 @@ paths: description: | Implementations MUST write an audit row on every successful transition and MUST be no-op when status == current status. + + `notify` (backends 2.2.0, optional, default false) asks the server to + email the reporter. It is acted on only when the status actually + changes to `resolved` or `declined`; reopening never emails. It + requires a non-empty `note` (else 400). The change and its audit row + are written first; a failed send never undoes it. After the send a + second audit row (from = to = the new status) records the outcome. + The response carries `notified` when notify was requested. A server + with no mailer (the Node backend) ignores `notify`. operationId: patchBug requestBody: required: true @@ -125,6 +134,13 @@ paths: changedBy: type: string description: Admin identity, when not derivable from auth. + changedByName: + type: string + description: Display name for changedBy, when not derivable from auth. + notify: + type: boolean + default: false + description: Email the reporter (see above). Needs `note`. responses: "200": description: Updated bug @@ -216,6 +232,9 @@ components: actorEmail: type: string format: email + actorName: + type: string + description: Display name of the person filing, when not derivable from auth. metaUrl: type: string format: uri @@ -296,6 +315,9 @@ components: status: { $ref: "#/components/schemas/Status" } addedBy: { type: string } actorEmail: { type: string } + actorName: + type: string + description: Display name of whoever filed it ("" when unknown). Backends 2.2.0. addedAt: { type: string, format: date-time } screenshot: type: boolean @@ -311,6 +333,19 @@ components: metaUrl: { type: string } metaUserAgent: { type: string } metaBuildSha: { type: string } + canNotify: + type: boolean + description: | + GET /bugs/{id} only (backends 2.2.0). True when this server can + email the reporter and the report has an `actorEmail`. + notified: + type: object + description: PATCH response only, when `notify` was requested. + required: [ok, to] + properties: + ok: { type: boolean } + to: { type: string } + error: { type: string } transcript: type: array items: { $ref: "#/components/schemas/TranscriptTurn" } @@ -325,6 +360,9 @@ components: properties: changedAt: { type: string, format: date-time } changedBy: { type: string } + changedByName: + type: string + description: Display name of changedBy ("" when unknown). Backends 2.2.0. fromStatus: oneOf: - $ref: "#/components/schemas/Status" diff --git a/packages/spec/report-contract.json b/packages/spec/report-contract.json index 530a5b0..aea7cf6 100644 --- a/packages/spec/report-contract.json +++ b/packages/spec/report-contract.json @@ -165,6 +165,15 @@ ], "optionalDetailFields": ["transcript"], + "_optionalSummaryFields": [ + "Added by backends 2.2.0, kept OUT of summaryFields so a reader built before", + "it still passes. `actorName` is the display name of whoever filed it (\"\"", + "when unknown); readers derive one from `actorEmail` when it is empty.", + "`canNotify` (detail read only) and `notified` (PATCH response only) are", + "likewise optional: see openapi.yaml." + ], + "optionalSummaryFields": ["actorName"], + "_outOfScope": [ "The canonical pattern's v2 sketch also proposes a free-form", "`context: object` and an `attachments[]` array. Deliberately NOT here:", @@ -176,6 +185,8 @@ "_auditFields": ["One row per transition. The actor is the authenticated caller, never the body."], "auditFields": ["changedAt", "changedBy", "fromStatus", "toStatus", "note"], + "_optionalAuditFields": ["Added by backends 2.2.0; older rows and the Node backend may not have it. \"\" when unknown."], + "optionalAuditFields": ["changedByName"], "_limits": ["Server-enforced, not client. Shared by every store."], "limits": { diff --git a/packages/spec/types.py b/packages/spec/types.py index 3f1e7df..7f0908a 100644 --- a/packages/spec/types.py +++ b/packages/spec/types.py @@ -25,6 +25,7 @@ class BugCreate(TypedDict, total=False): tags: list[str] | str addedBy: str actorEmail: str + actorName: str # display name of the person filing, when not derivable from auth (backends 2.2.0) metaUrl: str metaUserAgent: str metaBuildSha: str @@ -41,6 +42,7 @@ class BugSummary(TypedDict): status: Status addedBy: str actorEmail: NotRequired[str] + actorName: NotRequired[str] # "" when unknown (backends 2.2.0) addedAt: str screenshot: bool @@ -48,6 +50,7 @@ class BugSummary(TypedDict): class AuditEntry(TypedDict): changedAt: str changedBy: NotRequired[str] + changedByName: NotRequired[str] # "" when unknown (backends 2.2.0) fromStatus: Status | None toStatus: Status note: NotRequired[str] @@ -59,8 +62,24 @@ class Bug(BugSummary): metaUserAgent: NotRequired[str] metaBuildSha: NotRequired[str] transcript: NotRequired[list[TranscriptTurn] | None] + canNotify: NotRequired[bool] # GET /bugs/<id> only (backends 2.2.0) + notified: NotRequired["Notified"] # PATCH response only, when notify was requested (backends 2.2.0) audit: list[AuditEntry] +class Notified(TypedDict): + ok: bool + to: str + error: NotRequired[str] + + +class BugPatch(TypedDict, total=False): + status: Status # required + note: str + changedBy: str + changedByName: str + notify: bool # email the reporter on resolved/declined; needs note (backends 2.2.0) + + class ApiError(TypedDict): error: str diff --git a/packages/spec/types.ts b/packages/spec/types.ts index 4aa0104..95df4cd 100644 --- a/packages/spec/types.ts +++ b/packages/spec/types.ts @@ -20,6 +20,8 @@ export interface BugCreate { tags?: string[] | string; addedBy?: string; actorEmail?: string; + /** Display name of the person filing, when not derivable from auth (backends 2.2.0). */ + actorName?: string; metaUrl?: string; metaUserAgent?: string; metaBuildSha?: string; @@ -39,6 +41,8 @@ export interface BugSummary { status: Status; addedBy: string; actorEmail?: string; + /** Display name of whoever filed it; "" when unknown (backends 2.2.0). */ + actorName?: string; addedAt: string; screenshot: boolean; } @@ -46,6 +50,8 @@ export interface BugSummary { export interface AuditEntry { changedAt: string; changedBy?: string; + /** Display name of changedBy; "" when unknown (backends 2.2.0). */ + changedByName?: string; fromStatus: Status | null; toStatus: Status; note?: string; @@ -57,9 +63,28 @@ export interface Bug extends BugSummary { metaUserAgent?: string; metaBuildSha?: string; transcript?: TranscriptTurn[] | null; + /** GET /bugs/{id} only: the server can email the reporter and the report has an address (backends 2.2.0). */ + canNotify?: boolean; + /** PATCH response only, when `notify` was requested (backends 2.2.0). */ + notified?: Notified; audit: AuditEntry[]; } +export interface Notified { + ok: boolean; + to: string; + error?: string; +} + +/** PATCH /bugs/{id} body. `notify` emails the reporter on a change to resolved/declined and needs `note`. */ +export interface BugPatch { + status: Status; + note?: string; + changedBy?: string; + changedByName?: string; + notify?: boolean; +} + export interface ApiError { error: string; } From 28d8de1aca4bb03ec76361893f1a32d26abcff4e Mon Sep 17 00:00:00 2001 From: kmoy007 <ken@kenmoynihan.com> Date: Fri, 13 Nov 2026 13:16:04 -0800 Subject: [PATCH 2/3] An ACS send not confirmed within the wait is a failure, not "emailed"; wait 30 s, not 60 LROPoller.result(timeout) returns what it last saw when the wait runs out (None or a Running status) instead of raising; check poller.done(). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- packages/backend-python/bug_report/email.py | 9 +++++++-- packages/backend-python/tests/test_email.py | 19 +++++++++++++++---- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/packages/backend-python/bug_report/email.py b/packages/backend-python/bug_report/email.py index bd55200..86e9ab0 100644 --- a/packages/backend-python/bug_report/email.py +++ b/packages/backend-python/bug_report/email.py @@ -34,7 +34,7 @@ log = logging.getLogger(__name__) FROM_NAME = "Leap bug reports" -SEND_TIMEOUT = 60 # seconds the poller may be waited on; bounded, never forever +SEND_TIMEOUT = 30 # seconds the poller may be waited on: bounded, and short enough for a click in the Bugs panel @dataclass @@ -215,7 +215,12 @@ def __call__(self, notice: Notice) -> str: if name: reply["displayName"] = name message["replyTo"] = [reply] - result = self._get_client().begin_send(message).result(timeout=self.timeout) + poller = self._get_client().begin_send(message) + result = poller.result(timeout=self.timeout) + # A wait that runs out returns whatever the poller last saw (None, or + # a "Running" status), not an error: never audit that as "emailed". + if not poller.done(): + raise RuntimeError(f"ACS had not confirmed the send after {self.timeout:g} s; it may still arrive") get = result.get if isinstance(result, dict) else (lambda k, d=None: getattr(result, k, d)) status = getattr(get("status"), "value", get("status")) if status is not None and str(status).lower() != "succeeded": diff --git a/packages/backend-python/tests/test_email.py b/packages/backend-python/tests/test_email.py index 1bfd1b0..aef9b8a 100644 --- a/packages/backend-python/tests/test_email.py +++ b/packages/backend-python/tests/test_email.py @@ -105,8 +105,11 @@ def test_signed_by_the_derived_closer_name_or_the_service(): # ----- AcsNotifier -------------------------------------------------------------- class FakePoller: - def __init__(self, result): - self.result_value, self.timeout = result, "unset" + def __init__(self, result, done=True): + self.result_value, self.timeout, self.finished = result, "unset", done + + def done(self): + return self.finished def result(self, timeout=None): self.timeout = timeout @@ -114,13 +117,14 @@ def result(self, timeout=None): class FakeClient: - def __init__(self, result=None): + def __init__(self, result=None, done=True): self.result = result if result is not None else {"id": "op-1", "status": "Succeeded"} + self.done = done self.messages, self.poller = [], None def begin_send(self, message): self.messages.append(message) - self.poller = FakePoller(self.result) + self.poller = FakePoller(self.result, self.done) return self.poller @@ -175,6 +179,13 @@ def test_no_sender_refuses_fail_closed(): assert c.messages == [] +@pytest.mark.parametrize("seen", [None, {"id": "x", "status": "Running"}]) +def test_a_send_not_confirmed_within_the_wait_is_a_failure_not_emailed(seen): + # LROPoller.result(timeout) returns, not raises, when the wait runs out. + with pytest.raises(RuntimeError, match="had not confirmed"): + make(FakeClient(seen or {}, done=False))(notice()) + + def test_a_send_that_does_not_succeed_raises(): with pytest.raises(RuntimeError, match="Failed"): make(FakeClient({"id": "x", "status": "Failed"}))(notice()) From d2c76237c6e888bf1df611127b07947a277d9227 Mon Sep 17 00:00:00 2001 From: kmoy007 <ken@kenmoynihan.com> Date: Fri, 13 Nov 2026 13:21:08 -0800 Subject: [PATCH 3/3] Review fixes: notify over real HTTP, spec drift guard, own identity variable - e2e/test_notify_http.py: a Python server with a stand-in mailer drives notify end to end (sent + audited, failed send still resolves, no notify sends nothing). Bites: dropping the _notify call fails 2 of 3. - tests/test_spec_drift.py: every field the server sends is in openapi.yaml. It found kind missing from BugSummary (older drift); added. Bites: renaming changedByName in the spec fails it. - report-contract.json reverted: it is mirrored byte-identically into five repos, and the new fields are optional; openapi.yaml carries them. - BUG_NOTIFY_CLIENT_ID picks the sending identity, not AZURE_CLIENT_ID, so it cannot change the identity the rest of an app signs in as. - CHANGELOG said the send wait was 60 s; it is 30. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- CHANGELOG.md | 5 +- e2e/conftest.py | 54 +++++++++++++ e2e/test_notify_http.py | 81 +++++++++++++++++++ packages/backend-python/README.md | 2 +- packages/backend-python/bug_report/email.py | 8 +- packages/backend-python/tests/test_email.py | 4 +- .../backend-python/tests/test_spec_drift.py | 73 +++++++++++++++++ packages/spec/openapi.yaml | 4 + packages/spec/report-contract.json | 11 --- 9 files changed, 223 insertions(+), 19 deletions(-) create mode 100644 e2e/test_notify_http.py create mode 100644 packages/backend-python/tests/test_spec_drift.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 198a347..42799c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -74,11 +74,12 @@ a report can now carry a note and email the person who filed it, and people are - **New: `bug_report.email`** — `Notice`, `render(notice) -> (subject, html)` (everything escaped) and `AcsNotifier`, an Azure Communication Services Email sender modelled on leap-daily-report's, behind the `[email]` extra (`azure-communication-email`, `azure-identity`). `AcsNotifier.from_env()` reads - `ACS_ENDPOINT` (managed identity; `AZURE_CLIENT_ID` picks a user-assigned one) or `ACS_CONNECTION_STRING`, + `ACS_ENDPOINT` (managed identity; `BUG_NOTIFY_CLIENT_ID` picks a user-assigned one, its own name so it never changes the identity the rest of the app uses) or `ACS_CONNECTION_STRING`, `BUG_NOTIFY_SENDER` and `BUG_NOTIFY_DOMAINS`, and returns `None` when any is missing, so `notifier=AcsNotifier.from_env()` just does not email when unset. Fails closed: an address outside `BUG_NOTIFY_DOMAINS` is refused before anything is sent. SDK retries are off (`retry_total=0`) and the - wait on the send is bounded (60 s). + wait on the send is bounded (30 s); a send ACS has not confirmed by then is audited as failed, not + sent. - **New: people are named.** Reports gain `actorName` and audit rows `changedByName` (`""` when unknown; the UI derives "Chris Hamblin" from `chris.hamblin@…` the same way `bug_report.person_name` does). `actor_identity` may return `{"email": …, "name": …}` as well as a bare address, and now also stamps diff --git a/e2e/conftest.py b/e2e/conftest.py index e89cce7..1f720d0 100644 --- a/e2e/conftest.py +++ b/e2e/conftest.py @@ -86,6 +86,60 @@ def python_server(tmp_path_factory): except subprocess.TimeoutExpired: proc.kill() +# --------------------------------------------------------------------------- +# Python backend with a mailer — the notify path over real HTTP (2.2.0) +# --------------------------------------------------------------------------- + +PY_MAILER_SCRIPT = """ +import json, sys +sys.path.insert(0, r"{pkg}") +from flask import Flask, request +from bug_report import create_blueprint, FilesystemStore + +def notifier(n): + # A stand-in for AcsNotifier: records what it was asked to send, and fails + # on cue so the failure path is driven over HTTP too. + if "FAIL" in n.note: + raise RuntimeError("mail server said no") + with open(r"{outbox}", "a") as f: + f.write(json.dumps(n.__dict__) + "\\n") + return "msg-1" + +def who(req): + return {{"email": req.headers.get("X-Test-User", ""), "name": req.headers.get("X-Test-Name", "")}} + +app = Flask(__name__) +app.register_blueprint(create_blueprint( + store=FilesystemStore(r"{state}"), is_admin=lambda req: True, + actor_identity=who, notifier=notifier, app_url="https://app.example/", +)) +app.run(host="127.0.0.1", port={port}, use_reloader=False) +""" + + +@pytest.fixture(scope="session") +def python_mailer_server(tmp_path_factory): + port = _free_port() + state = tmp_path_factory.mktemp("py-mail-state") + outbox = tmp_path_factory.mktemp("py-mail-out") / "outbox.jsonl" + script = PY_MAILER_SCRIPT.format(pkg=str(PY_PKG), state=str(state), port=port, outbox=str(outbox)) + log = tmp_path_factory.mktemp("py-mail-log") / "out.log" + 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" + try: + try: + _wait_alive(base) + except RuntimeError: + tail = log.read_text()[-2000:] if log.exists() else "(no log)" + raise RuntimeError(f"python mailer backend failed to start. log tail:\n{tail}") + yield base, outbox + finally: + proc.terminate() + try: proc.wait(timeout=3) + except subprocess.TimeoutExpired: proc.kill() + + # --------------------------------------------------------------------------- # Node backend — Express subprocess # --------------------------------------------------------------------------- diff --git a/e2e/test_notify_http.py b/e2e/test_notify_http.py new file mode 100644 index 0000000..8d1e744 --- /dev/null +++ b/e2e/test_notify_http.py @@ -0,0 +1,81 @@ +"""Closing a report emails the person who filed it — over real HTTP (2.2.0). + +Python only: the Node backend has no notifier (it answers ``canNotify: false`` +and ignores ``notify``; test_contract.py pins that on both stacks). This drives +the ``notifier=`` wiring through a running server with a stand-in mailer, so a +break between the blueprint and the notifier fails here, not in production. +""" +from __future__ import annotations + +import json + +import requests + +CHRIS = {"X-Test-User": "chris.hamblin@helloleap.ai", "X-Test-Name": "Chris Hamblin"} +KEN = {"X-Test-User": "ken.moynihan@helloleap.ai", "X-Test-Name": "Ken Moynihan"} + + +def _file_and_triage(base: str, title: str) -> str: + r = requests.post(base, json={"title": title, "details": "d", "metaUrl": "https://app.example/day"}, + headers=CHRIS, timeout=5) + assert r.status_code == 201, r.text + bid = r.json()["id"] + assert requests.patch(f"{base}/{bid}", json={"status": "triaged", "note": ""}, headers=KEN, + timeout=5).status_code == 200 + return bid + + +def _sent(outbox) -> list[dict]: + return [json.loads(line) for line in outbox.read_text().splitlines()] if outbox.exists() else [] + + +def test_resolving_with_notify_emails_the_filer_and_audits_it(python_mailer_server): + base, outbox = python_mailer_server + bid = _file_and_triage(base, "Time of issue not set") + assert requests.get(f"{base}/{bid}", headers=KEN, timeout=5).json()["canNotify"] is True + before = len(_sent(outbox)) + + r = requests.patch(f"{base}/{bid}", json={"status": "resolved", "note": "Fixed — it asks first now.", + "notify": True}, headers=KEN, timeout=5) + assert r.status_code == 200, r.text + body = r.json() + assert body["status"] == "resolved" + assert body["notified"] == {"ok": True, "to": "chris.hamblin@helloleap.ai"} + + sent = _sent(outbox)[before:] + assert len(sent) == 1 + n = sent[0] + assert (n["to_email"], n["to_name"], n["closer_email"], n["closer_name"]) == ( + "chris.hamblin@helloleap.ai", "Chris Hamblin", "ken.moynihan@helloleap.ai", "Ken Moynihan") + assert (n["status"], n["note"], n["page_url"], n["app_url"]) == ( + "resolved", "Fixed — it asks first now.", "https://app.example/day", "https://app.example/") + + change, outcome = body["audit"][-2:] + assert (change["fromStatus"], change["toStatus"], change["changedByName"]) == ("triaged", "resolved", "Ken Moynihan") + assert outcome["note"] == "emailed Chris Hamblin <chris.hamblin@helloleap.ai>" + + +def test_a_failed_send_still_resolves_and_says_so(python_mailer_server): + base, outbox = python_mailer_server + bid = _file_and_triage(base, "Send fails") + before = len(_sent(outbox)) + + r = requests.patch(f"{base}/{bid}", json={"status": "resolved", "note": "FAIL on purpose", "notify": True}, + headers=KEN, timeout=5) + assert r.status_code == 200, r.text + body = r.json() + assert body["status"] == "resolved" + assert body["notified"]["ok"] is False and "mail server said no" in body["notified"]["error"] + assert body["audit"][-1]["note"].startswith("email to Chris Hamblin <chris.hamblin@helloleap.ai> failed:") + assert len(_sent(outbox)) == before + # the change stuck: a fresh read agrees + assert requests.get(f"{base}/{bid}", headers=KEN, timeout=5).json()["status"] == "resolved" + + +def test_without_notify_nothing_is_sent(python_mailer_server): + base, outbox = python_mailer_server + bid = _file_and_triage(base, "Quiet close") + before = len(_sent(outbox)) + r = requests.patch(f"{base}/{bid}", json={"status": "resolved", "note": "done"}, headers=KEN, timeout=5) + assert r.status_code == 200 and "notified" not in r.json() + assert len(_sent(outbox)) == before diff --git a/packages/backend-python/README.md b/packages/backend-python/README.md index 4cd9923..e87ecda 100644 --- a/packages/backend-python/README.md +++ b/packages/backend-python/README.md @@ -55,7 +55,7 @@ create_blueprint( `PATCH {status, note, notify: true}` on a change to `resolved`/`declined` writes the change and its audit row, then emails the reporter and writes a second audit row with the outcome. A failed send never undoes the change; the response carries `notified: {ok, to, error?}`. Environment for `AcsNotifier.from_env()`: `ACS_ENDPOINT` (managed -identity; `AZURE_CLIENT_ID` for a user-assigned one) or `ACS_CONNECTION_STRING`, `BUG_NOTIFY_SENDER`, +identity; `BUG_NOTIFY_CLIENT_ID` for a user-assigned one) or `ACS_CONNECTION_STRING`, `BUG_NOTIFY_SENDER`, `BUG_NOTIFY_DOMAINS` (comma list; an address outside it is refused). Any `notifier(notice) -> message id` that raises on failure works in its place. diff --git a/packages/backend-python/bug_report/email.py b/packages/backend-python/bug_report/email.py index 86e9ab0..10bf314 100644 --- a/packages/backend-python/bug_report/email.py +++ b/packages/backend-python/bug_report/email.py @@ -12,8 +12,10 @@ Environment read by :meth:`AcsNotifier.from_env`: -``ACS_ENDPOINT`` managed identity (``DefaultAzureCredential``; - ``AZURE_CLIENT_ID`` picks a user-assigned identity) +``ACS_ENDPOINT`` managed identity (``DefaultAzureCredential``) +``BUG_NOTIFY_CLIENT_ID`` the user-assigned identity to send as; its own name, + not ``AZURE_CLIENT_ID``, so it cannot change which + identity the rest of the app signs in as ``ACS_CONNECTION_STRING`` fallback when there is no endpoint ``BUG_NOTIFY_SENDER`` the From address, e.g. ``bugs@helloleap.ai`` ``BUG_NOTIFY_DOMAINS`` comma list of domains it may write to; an address @@ -175,7 +177,7 @@ def from_env(cls, env=None): log.warning("bug notify: BUG_NOTIFY_DOMAINS not set; emailing reporters is off (fail closed)") return None return cls(sender=sender, domains=domains, endpoint=endpoint, - connection_string=conn, client_id=env.get("AZURE_CLIENT_ID", "")) + connection_string=conn, client_id=env.get("BUG_NOTIFY_CLIENT_ID", "")) def _get_client(self): if self._client is None: diff --git a/packages/backend-python/tests/test_email.py b/packages/backend-python/tests/test_email.py index aef9b8a..398364b 100644 --- a/packages/backend-python/tests/test_email.py +++ b/packages/backend-python/tests/test_email.py @@ -216,7 +216,7 @@ def test_from_env_is_none_with_nothing_set(): def test_from_env_reads_the_config(): - n = AcsNotifier.from_env({**GOOD, "BUG_NOTIFY_DOMAINS": "a.com, b.com", "AZURE_CLIENT_ID": "cid"}) + n = AcsNotifier.from_env({**GOOD, "BUG_NOTIFY_DOMAINS": "a.com, b.com", "BUG_NOTIFY_CLIENT_ID": "cid"}) assert (n.sender, n.domains, n.endpoint, n.client_id) == ( "bugs@example.com", ("a.com", "b.com"), "https://comms.example", "cid") @@ -252,7 +252,7 @@ def dac(**kw): def test_endpoint_uses_managed_identity_with_retries_off(azure): - n = AcsNotifier.from_env({**GOOD, "AZURE_CLIENT_ID": "cid"}) + n = AcsNotifier.from_env({**GOOD, "BUG_NOTIFY_CLIENT_ID": "cid"}) assert n(notice()) == "e" assert azure["cred"] == {"managed_identity_client_id": "cid"} assert azure["endpoint"] == ("https://comms.example", "CRED", {"retry_total": 0}) diff --git a/packages/backend-python/tests/test_spec_drift.py b/packages/backend-python/tests/test_spec_drift.py new file mode 100644 index 0000000..dd5ad73 --- /dev/null +++ b/packages/backend-python/tests/test_spec_drift.py @@ -0,0 +1,73 @@ +"""Every field the Python backend sends is in openapi.yaml (practice T5). + +The spec is the documentation the other stacks and the UI are built from; a +field the server sends but the spec never names is a field nobody else knows +about. Added with backends 2.2.0, whose new fields (actorName, canNotify, +notified, changedByName) were documented by hand. +""" +from __future__ import annotations + +import pathlib +import re + +from flask import Flask + +from bug_report import FilesystemStore, create_blueprint + +SPEC = pathlib.Path(__file__).resolve().parents[2] / "spec" / "openapi.yaml" + + +def _schema_properties(name: str) -> set[str]: + """Property names of one components/schemas entry, including those of an + allOf branch, read by indentation (no YAML dependency in this package).""" + lines = SPEC.read_text().splitlines() + start = lines.index(f" {name}:") + props: set[str] = set() + stack: list[int] = [] # key indents of the open `properties:` blocks; only the outermost counts + for line in lines[start + 1:]: + if re.match(r"^ {0,4}\S", line): + break # the next schema + if not line.strip(): + continue + indent = len(line) - len(line.lstrip()) + while stack and indent < stack[-1]: + stack.pop() + k = re.match(r"^\s+([A-Za-z_]\w*):", line) + if k and len(stack) == 1 and indent == stack[0]: + props.add(k.group(1)) + if re.match(r"^\s+properties:\s*$", line): + stack.append(indent + 2) + return props + + +def _client(tmp_path): + def notifier(n): + return "id-1" + + app = Flask(__name__) + app.register_blueprint(create_blueprint( + store=FilesystemStore(tmp_path), is_admin=lambda r: True, notifier=notifier, + actor_identity=lambda r: {"email": "chris.hamblin@helloleap.ai", "name": "Chris Hamblin"}, + ), url_prefix="/api") + return app.test_client() + + +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": ""}) + 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] + + summary_spec = _schema_properties("BugSummary") + bug_spec = summary_spec | _schema_properties("Bug") + audit_spec = _schema_properties("AuditEntry") + assert {"actorName", "changedByName"} & (summary_spec | audit_spec) == {"actorName", "changedByName"} + + assert set(summary) - summary_spec == set() + assert set(detail) - bug_spec == set() + assert set(closed) - bug_spec == set() + for row in closed["audit"]: + assert set(row) - audit_spec == set() + assert set(closed["notified"]) <= {"ok", "to", "error"} diff --git a/packages/spec/openapi.yaml b/packages/spec/openapi.yaml index 49bdee5..17851b3 100644 --- a/packages/spec/openapi.yaml +++ b/packages/spec/openapi.yaml @@ -313,6 +313,10 @@ components: type: array items: { type: string } status: { $ref: "#/components/schemas/Status" } + kind: + type: string + enum: [bug, feature] + description: Derived from the tags (report-contract.json `kinds`, `kindTags`); a feature request is tagged `feature`. addedBy: { type: string } actorEmail: { type: string } actorName: diff --git a/packages/spec/report-contract.json b/packages/spec/report-contract.json index aea7cf6..530a5b0 100644 --- a/packages/spec/report-contract.json +++ b/packages/spec/report-contract.json @@ -165,15 +165,6 @@ ], "optionalDetailFields": ["transcript"], - "_optionalSummaryFields": [ - "Added by backends 2.2.0, kept OUT of summaryFields so a reader built before", - "it still passes. `actorName` is the display name of whoever filed it (\"\"", - "when unknown); readers derive one from `actorEmail` when it is empty.", - "`canNotify` (detail read only) and `notified` (PATCH response only) are", - "likewise optional: see openapi.yaml." - ], - "optionalSummaryFields": ["actorName"], - "_outOfScope": [ "The canonical pattern's v2 sketch also proposes a free-form", "`context: object` and an `attachments[]` array. Deliberately NOT here:", @@ -185,8 +176,6 @@ "_auditFields": ["One row per transition. The actor is the authenticated caller, never the body."], "auditFields": ["changedAt", "changedBy", "fromStatus", "toStatus", "note"], - "_optionalAuditFields": ["Added by backends 2.2.0; older rows and the Node backend may not have it. \"\" when unknown."], - "optionalAuditFields": ["changedByName"], "_limits": ["Server-enforced, not client. Shared by every store."], "limits": {