EnergyVenom commited on
Commit
348eedc
·
verified ·
1 Parent(s): cdfb5de

Astra: security review, left-on-pod ledger, chosen scenarios all run, GL navigation and Create Order popup on 26D, health check (ed9256cd4029)

Browse files
automation/remote_runner/server.py CHANGED
@@ -591,6 +591,7 @@ def sweep() -> None:
591
 
592
  class H(BaseHTTPRequestHandler):
593
  server_version = "PatchwiseRunner/1"
 
594
 
595
  def log_message(self, fmt, *args): # one quiet line per call, never a header or a body
596
  print(time.strftime("%H:%M:%S"), self.command, self.path.split("?")[0], args[1] if len(args) > 1 else "", flush=True)
@@ -606,7 +607,8 @@ class H(BaseHTTPRequestHandler):
606
 
607
  def _auth(self) -> bool:
608
  h = self.headers.get("Authorization", "")
609
- ok = bool(TOKEN) and h.startswith("Bearer ") and hmac.compare_digest(h[7:].strip(), TOKEN)
 
610
  if not ok:
611
  self._send(401, {"error": "a valid runner token is needed"})
612
  return ok
@@ -650,7 +652,12 @@ class H(BaseHTTPRequestHandler):
650
  def do_POST(self):
651
  if not self._auth():
652
  return
653
- n = int(self.headers.get("Content-Length") or 0)
 
 
 
 
 
654
  if n > MAX_BODY:
655
  return self._send(413, {"error": "body too large"})
656
  if self.path in ("/v1/attempts", "/v1/screens"):
 
591
 
592
  class H(BaseHTTPRequestHandler):
593
  server_version = "PatchwiseRunner/1"
594
+ timeout = 120 # a client that stalls mid-request (slow headers or body) frees its thread instead of holding it for ever
595
 
596
  def log_message(self, fmt, *args): # one quiet line per call, never a header or a body
597
  print(time.strftime("%H:%M:%S"), self.command, self.path.split("?")[0], args[1] if len(args) > 1 else "", flush=True)
 
607
 
608
  def _auth(self) -> bool:
609
  h = self.headers.get("Authorization", "")
610
+ # bytes, so a non-ASCII header is a wrong token (compare_digest on str would raise); constant time
611
+ ok = bool(TOKEN) and h.startswith("Bearer ") and hmac.compare_digest(h[7:].strip().encode("utf-8", "replace"), TOKEN.encode("utf-8"))
612
  if not ok:
613
  self._send(401, {"error": "a valid runner token is needed"})
614
  return ok
 
652
  def do_POST(self):
653
  if not self._auth():
654
  return
655
+ try:
656
+ n = int(self.headers.get("Content-Length") or 0)
657
+ except ValueError:
658
+ n = -1
659
+ if n < 0:
660
+ return self._send(400, {"error": "Content-Length is not a length"})
661
  if n > MAX_BODY:
662
  return self._send(413, {"error": "body too large"})
663
  if self.path in ("/v1/attempts", "/v1/screens"):
automation/src/fusion/ui.ts CHANGED
@@ -350,9 +350,15 @@ export class FusionUi {
350
  const heading = this.page.getByRole('heading', { name: new RegExp(`^\\s*${esc(task)}\\b`, 'i') }).filter({ visible: true });
351
  const noun = /^create\s+(.+)$/i.exec(task.trim())?.[1];
352
  const editing = noun ? new RegExp(`(^|[-–:|]\\s*)${esc(noun)}\\s*[-–:]\\s*(Edit|Create)\\b`, 'i') : null;
 
 
 
 
 
353
  await expect.poll(async () => {
354
  const t = await this.page.title();
355
- return title.test(t) || (editing?.test(t) ?? false) || (await dialog.count()) > 0 || (await heading.count()) > 0;
 
356
  }, { message: `"${task}" should open (its page, its dialog or its heading)`, timeout: 60_000 }).toBe(true);
357
  }
358
 
@@ -424,9 +430,23 @@ export class FusionUi {
424
  const vp = this.page.viewportSize() ?? { width: 1440, height: 900 };
425
  if (box && (box.x < 0 || box.y < 0 || box.x + box.width > vp.width || box.y + box.height > vp.height)) {
426
  await el.evaluate((e) => (e as HTMLElement).click());
427
- } else {
428
- await el.click(timeout ? { timeout } : undefined);
 
 
 
 
 
 
 
 
 
 
 
 
 
429
  }
 
430
  }
431
 
432
  /** Close what a previous task left open (its dialog), with the dialog's own Cancel / Close / OK. Nothing is saved. */
@@ -449,6 +469,7 @@ export class FusionUi {
449
  await this.page.goto(`${base}/fscmUI/faces/AtkHomePageWelcome`, { waitUntil: 'domcontentloaded' }).catch(() => {});
450
  await this.settle(4000);
451
  await this.closeDialogs(); // a dialog a previous task left open would cover the springboard
 
452
  const groups = this.page.locator('a[id^="groupNode_"]').filter({ visible: true });
453
  if (await groups.first().isVisible().catch(() => false)) return;
454
  const homeLink = this.page.getByRole('link', { name: 'Home', exact: true }).filter({ visible: true }).first();
@@ -461,6 +482,19 @@ export class FusionUi {
461
  }
462
  }
463
 
 
 
 
 
 
 
 
 
 
 
 
 
 
464
  /** Open a work area ("Group > Page"): from the home page's springboard, as a user does; through Fusion's Navigator
465
  * menu when the springboard does not show the group (pods and roles differ in what the home page offers). */
466
  async openWorkArea(group: string, pageName: string) {
@@ -478,13 +512,25 @@ export class FusionUi {
478
  }
479
  await this.goHome();
480
  await this.openNavigator();
481
- const g = await this.target(group);
482
- if (await g.isVisible().catch(() => false)) { await g.click(); await this.settle(1500); } // expand the group
483
- await (await this.target(pageName)).click({ timeout: 30_000 });
 
 
 
 
 
484
  await this.settle(6000);
485
  this.workArea = `${group} > ${pageName}`;
486
  }
487
 
 
 
 
 
 
 
 
488
  /** The VISIBLE element a user would click for `name`: a link with exactly that name, else a button or menu entry,
489
  * else that exact text. Fusion pages hold hidden copies of many links (collapsed menus, the Navigator, Favorites);
490
  * the first match is often one of those, and clicking it only waits until it times out. Links come first so a
 
350
  const heading = this.page.getByRole('heading', { name: new RegExp(`^\\s*${esc(task)}\\b`, 'i') }).filter({ visible: true });
351
  const noun = /^create\s+(.+)$/i.exec(task.trim())?.[1];
352
  const editing = noun ? new RegExp(`(^|[-–:|]\\s*)${esc(noun)}\\s*[-–:]\\s*(Edit|Create)\\b`, 'i') : null;
353
+ // 26D's Create Order opens a small popup titled with the task's name (Style, Procurement BU, Create, Cancel) that
354
+ // has neither a dialog role nor a heading: its title text, outside the link that was clicked, with a Cancel button
355
+ const popupTitle = this.page.locator('div:not(a *), span:not(a *), td:not(a *)')
356
+ .filter({ hasText: new RegExp(`^\\s*${esc(task)}\\s*$`, 'i') }).filter({ visible: true });
357
+ const cancel = this.page.getByRole('button', { name: 'Cancel', exact: true }).filter({ visible: true });
358
  await expect.poll(async () => {
359
  const t = await this.page.title();
360
+ return title.test(t) || (editing?.test(t) ?? false) || (await dialog.count()) > 0 || (await heading.count()) > 0
361
+ || ((await popupTitle.count()) > 0 && (await cancel.count()) > 0);
362
  }, { message: `"${task}" should open (its page, its dialog or its heading)`, timeout: 60_000 }).toBe(true);
363
  }
364
 
 
430
  const vp = this.page.viewportSize() ?? { width: 1440, height: 900 };
431
  if (box && (box.x < 0 || box.y < 0 || box.x + box.width > vp.width || box.y + box.height > vp.height)) {
432
  await el.evaluate((e) => (e as HTMLElement).click());
433
+ return;
434
+ }
435
+ // a Fusion layer left open (the "Me" menu and its mask, seen over the 26D springboard) takes the click, and a plain
436
+ // click retries until it times out. A trial click (it clicks nothing) finds such a layer in seconds: it is closed
437
+ // with Escape as a user would, and if it stays the click goes to the element itself. The normal click keeps its
438
+ // full wait for an element that is still appearing.
439
+ const covered = async () => el.click({ trial: true, timeout: 5_000 }).then(() => false,
440
+ (e) => /intercepts pointer events/i.test(String((e as Error).message)));
441
+ if (await covered()) {
442
+ await this.page.keyboard.press('Escape').catch(() => {});
443
+ await this.settle(1500);
444
+ if (await covered()) {
445
+ await el.evaluate((x) => (x as HTMLElement).click());
446
+ return;
447
+ }
448
  }
449
+ await el.click(timeout ? { timeout } : undefined);
450
  }
451
 
452
  /** Close what a previous task left open (its dialog), with the dialog's own Cancel / Close / OK. Nothing is saved. */
 
469
  await this.page.goto(`${base}/fscmUI/faces/AtkHomePageWelcome`, { waitUntil: 'domcontentloaded' }).catch(() => {});
470
  await this.settle(4000);
471
  await this.closeDialogs(); // a dialog a previous task left open would cover the springboard
472
+ await this.closeNavigator();
473
  const groups = this.page.locator('a[id^="groupNode_"]').filter({ visible: true });
474
  if (await groups.first().isVisible().catch(() => false)) return;
475
  const homeLink = this.page.getByRole('link', { name: 'Home', exact: true }).filter({ visible: true }).first();
 
482
  }
483
  }
484
 
485
+ /** Fusion can show its Navigator drawer over the home page on arrival (seen on 26D: open before the run touched it);
486
+ * its mask then takes every click on the springboard. A click on the mask closes it, as for a user; Escape if not. */
487
+ async closeNavigator() {
488
+ const mask = this.page.locator('#navmenuMaskDiv').filter({ visible: true });
489
+ if (!(await mask.count().catch(() => 0))) return;
490
+ await mask.first().click({ timeout: 5_000 }).catch(() => {});
491
+ await this.settle(1000);
492
+ if (await mask.count().catch(() => 0)) {
493
+ await this.page.keyboard.press('Escape').catch(() => {});
494
+ await this.settle(1000);
495
+ }
496
+ }
497
+
498
  /** Open a work area ("Group > Page"): from the home page's springboard, as a user does; through Fusion's Navigator
499
  * menu when the springboard does not show the group (pods and roles differ in what the home page offers). */
500
  async openWorkArea(group: string, pageName: string) {
 
512
  }
513
  await this.goHome();
514
  await this.openNavigator();
515
+ // 26D: a group opens with its own "Expand <group>" link, and the drawer's sticky headers take clicks meant for entries
516
+ // under them; Escape would close the drawer itself, so a covered entry gets its own click instead
517
+ const expand = this.page.getByRole('link', { name: `Expand ${group}`, exact: true }).filter({ visible: true }).first();
518
+ const g = (await expand.count().catch(() => 0)) ? expand : await this.target(group);
519
+ if (await g.isVisible().catch(() => false)) { await this.drawerClick(g); await this.settle(1500); } // expand the group
520
+ const item = await this.target(pageName);
521
+ await item.waitFor({ state: 'visible', timeout: 30_000 });
522
+ await this.drawerClick(item);
523
  await this.settle(6000);
524
  this.workArea = `${group} > ${pageName}`;
525
  }
526
 
527
+ /** A click inside the open Navigator drawer: scrolled to its middle, and given to the element itself when a sticky
528
+ * header covers it (never Escape, which closes the drawer). */
529
+ private async drawerClick(el: Locator) {
530
+ await el.evaluate((e) => e.scrollIntoView({ block: 'center' })).catch(() => {});
531
+ await el.click({ timeout: 5_000 }).catch(() => el.evaluate((e) => (e as HTMLElement).click()));
532
+ }
533
+
534
  /** The VISIBLE element a user would click for `name`: a link with exactly that name, else a button or menu entry,
535
  * else that exact text. Fusion pages hold hidden copies of many links (collapsed menus, the Navigator, Favorites);
536
  * the first match is often one of those, and clicking it only waits until it times out. Links come first so a
coworker/__main__.py CHANGED
@@ -1,6 +1,6 @@
1
  """CLI: python -m coworker <command> (fpt.cmd <command> on Windows)
2
  setup | up | down | api | worker | temporal | mock | run | resume | create-user | selftest | test | purge | verify-audit | kill | unkill |
3
- research-fixtures | llm-ping | write-steps | web-dev | desktop | package
4
  Everything runs against the LOCAL MOCK app (mock-app/), never Oracle Fusion."""
5
  from __future__ import annotations
6
 
@@ -310,6 +310,24 @@ def cmd_verify_audit(a) -> int:
310
  return 0 if r["ok"] else 1
311
 
312
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
313
  def cmd_kill(a) -> int:
314
  p = get_settings().path("KILL")
315
  p.parent.mkdir(parents=True, exist_ok=True)
@@ -513,6 +531,7 @@ def main(argv=None) -> int:
513
  sp.add_parser("test").set_defaults(fn=cmd_test)
514
  sp.add_parser("purge").set_defaults(fn=cmd_purge)
515
  sp.add_parser("verify-audit").set_defaults(fn=cmd_verify_audit)
 
516
  s = sp.add_parser("kill"); s.add_argument("--reason"); s.set_defaults(fn=cmd_kill)
517
  sp.add_parser("unkill").set_defaults(fn=cmd_unkill)
518
  sp.add_parser("research-fixtures").set_defaults(fn=cmd_research_fixtures)
 
1
  """CLI: python -m coworker <command> (fpt.cmd <command> on Windows)
2
  setup | up | down | api | worker | temporal | mock | run | resume | create-user | selftest | test | purge | verify-audit | kill | unkill |
3
+ research-fixtures | left-on-pod | llm-ping | write-steps | web-dev | desktop | package
4
  Everything runs against the LOCAL MOCK app (mock-app/), never Oracle Fusion."""
5
  from __future__ import annotations
6
 
 
310
  return 0 if r["ok"] else 1
311
 
312
 
313
+ def cmd_left_on_pod(a) -> int:
314
+ """backfill: enter the test documents earlier runs left on a pod (their run folders' files) in the ledger; list: the open ones."""
315
+ from .graph.services import build_services
316
+ from .platform import left_on_pod
317
+ svc = build_services()
318
+ if a.action == "backfill":
319
+ out = left_on_pod.backfill(svc)
320
+ svc.db.kv_set("left_on_pod_backfilled", {"at": left_on_pod.now_iso(), **out})
321
+ print(f"{out['added']} test document(s) added from {out['runs']} run(s)")
322
+ return 0
323
+ rows = svc.db.q("SELECT l.*, p.name AS pod_name FROM left_on_pod l LEFT JOIN pods p ON p.id = l.pod_id WHERE l.status='open' "
324
+ "ORDER BY l.pod_id, l.id")
325
+ for r in rows:
326
+ print(f"{r['pod_name'] or r['pod_id']} {r['kind']} {r['reference']} {r['run_id']} {r['why']} -> {r['todo']}")
327
+ print(f"{len(rows)} open")
328
+ return 0
329
+
330
+
331
  def cmd_kill(a) -> int:
332
  p = get_settings().path("KILL")
333
  p.parent.mkdir(parents=True, exist_ok=True)
 
531
  sp.add_parser("test").set_defaults(fn=cmd_test)
532
  sp.add_parser("purge").set_defaults(fn=cmd_purge)
533
  sp.add_parser("verify-audit").set_defaults(fn=cmd_verify_audit)
534
+ s = sp.add_parser("left-on-pod"); s.add_argument("action", choices=["backfill", "list"]); s.set_defaults(fn=cmd_left_on_pod)
535
  s = sp.add_parser("kill"); s.add_argument("--reason"); s.set_defaults(fn=cmd_kill)
536
  sp.add_parser("unkill").set_defaults(fn=cmd_unkill)
537
  sp.add_parser("research-fixtures").set_defaults(fn=cmd_research_fixtures)
coworker/adapters/remote_runner.py CHANGED
@@ -17,6 +17,7 @@ import base64
17
  import io
18
  import json
19
  import logging
 
20
  import re
21
  import time
22
  import zipfile
@@ -87,8 +88,18 @@ def _append(dest: Path, data: bytes) -> None:
87
  fh.write(data if not data or data.endswith(b"\n") else data + b"\n")
88
 
89
 
 
 
 
 
 
 
 
 
 
 
90
  def _unpack(blob: bytes, out_file: Path, run_dir: Path, log_dir: Path, ledger: str, attempt: int | str) -> bool:
91
- with zipfile.ZipFile(io.BytesIO(blob)) as z:
92
  for info in z.infolist():
93
  name = info.filename
94
  if info.is_dir():
@@ -244,7 +255,7 @@ def run_screens_remote(egress, base_url: str, token: str, *, kind: str, env: dic
244
  out = Path(out_dir)
245
  out.mkdir(parents=True, exist_ok=True)
246
  lines: list[str] = []
247
- with zipfile.ZipFile(io.BytesIO(z.content)) as zf:
248
  for info in zf.infolist():
249
  name = info.filename
250
  if name == "playwright.log":
@@ -322,7 +333,7 @@ def _salvage(egress, base: str, hdr: dict, jid: str, log_dir: Path, ledger: str,
322
  z = _call(egress, base, hdr, "GET", f"/v1/attempts/{jid}/bundle", timeout=300)
323
  if z.status_code != 200:
324
  return False
325
- with zipfile.ZipFile(io.BytesIO(z.content)) as zf:
326
  if "created.jsonl" in zf.namelist():
327
  _append(Path(log_dir) / ledger, zf.read("created.jsonl"))
328
  return True
 
17
  import io
18
  import json
19
  import logging
20
+ import os
21
  import re
22
  import time
23
  import zipfile
 
88
  fh.write(data if not data or data.endswith(b"\n") else data + b"\n")
89
 
90
 
91
+ MAX_BUNDLE_BYTES = int(os.environ.get("FPT_RUNNER_BUNDLE_MAX_MB", "2048")) * 1024 * 1024 # what a bundle may unpack to
92
+
93
+
94
+ def _checked(zf: zipfile.ZipFile) -> zipfile.ZipFile:
95
+ """A runner's bundle is read as untrusted: its files may not unpack to more than FPT_RUNNER_BUNDLE_MAX_MB (a zip bomb)."""
96
+ if sum(i.file_size for i in zf.infolist()) > MAX_BUNDLE_BYTES:
97
+ raise RemoteRunnerError(f"the remote browser runner's bundle unpacks to more than {MAX_BUNDLE_BYTES // 1024 // 1024} MB: refused")
98
+ return zf
99
+
100
+
101
  def _unpack(blob: bytes, out_file: Path, run_dir: Path, log_dir: Path, ledger: str, attempt: int | str) -> bool:
102
+ with _checked(zipfile.ZipFile(io.BytesIO(blob))) as z:
103
  for info in z.infolist():
104
  name = info.filename
105
  if info.is_dir():
 
255
  out = Path(out_dir)
256
  out.mkdir(parents=True, exist_ok=True)
257
  lines: list[str] = []
258
+ with _checked(zipfile.ZipFile(io.BytesIO(z.content))) as zf:
259
  for info in zf.infolist():
260
  name = info.filename
261
  if name == "playwright.log":
 
333
  z = _call(egress, base, hdr, "GET", f"/v1/attempts/{jid}/bundle", timeout=300)
334
  if z.status_code != 200:
335
  return False
336
+ with _checked(zipfile.ZipFile(io.BytesIO(z.content))) as zf:
337
  if "created.jsonl" in zf.namelist():
338
  _append(Path(log_dir) / ledger, zf.read("created.jsonl"))
339
  return True
coworker/api/app.py CHANGED
@@ -14,9 +14,9 @@ from ..config import VERSION, Settings, get_settings
14
  from ..graph.services import Services, build_services
15
  from ..platform.scheduler import Scheduler
16
  from . import errors
17
- from .middleware import RequestContext, setup_logging
18
  from . import a2a, mcp
19
- from .routes import admin, agent_studio, ai_monitoring, assistant, auth, channels, chat, consultant, custom_cases, gates, heals, integrations, live, llm, notifications, pods, recordings, review, runs, screens, signin, tokens
20
  from .runner import RunManager
21
 
22
  log = logging.getLogger("fpt.api")
@@ -64,6 +64,11 @@ def create_app(svc: Services | None = None, cfg: Settings | None = None, *, back
64
  assisted_signin.sweep(svc) # captured sessions of runs that ended while the server was down, sign-in browser folders
65
  if recovered:
66
  log.warning("marked %d run(s) interrupted after restart", len(recovered))
 
 
 
 
 
67
  from ..platform.pods import PodRegistry
68
  cut = PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit).recover_screens()
69
  if cut:
@@ -123,14 +128,19 @@ def create_app(svc: Services | None = None, cfg: Settings | None = None, *, back
123
  app.state.sign_in = SignInSessions(svc, run_mgr) # assisted sign-in browsers (routes/signin.py)
124
  run_mgr.sign_in = app.state.sign_in # a run that ends closes its own and drops its captured session
125
  errors.install(app)
126
- app.add_middleware(CORSMiddleware, allow_origins=cfg.cors_origins, allow_credentials=True,
 
 
 
 
 
127
  allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
128
  allow_headers=["Authorization", "Content-Type", "X-CSRF-Token", "X-Request-ID", "Last-Event-ID"],
129
  expose_headers=["X-Request-ID"])
130
  app.add_middleware(RequestContext)
131
 
132
  api = APIRouter(prefix="/api")
133
- for r in (auth.router, runs.router, gates.router, review.router, admin.router, pods.router, screens.router, consultant.router, live.router, chat.router, assistant.router, llm.router, notifications.router, channels.router, integrations.router, tokens.router, custom_cases.router, recordings.router, heals.router, agent_studio.router, ai_monitoring.router, signin.router):
134
  api.include_router(r)
135
  app.include_router(api)
136
  app.include_router(agent_studio.oauth) # /oauth/token: the Oracle AI Agent Studio client (docs/AGENT_STUDIO.md)
 
14
  from ..graph.services import Services, build_services
15
  from ..platform.scheduler import Scheduler
16
  from . import errors
17
+ from .middleware import BodyLimit, RequestContext, setup_logging
18
  from . import a2a, mcp
19
+ from .routes import admin, agent_studio, ai_monitoring, assistant, auth, channels, chat, consultant, custom_cases, gates, heals, integrations, left_on_pod, live, llm, notifications, pods, recordings, review, runs, screens, signin, tokens
20
  from .runner import RunManager
21
 
22
  log = logging.getLogger("fpt.api")
 
64
  assisted_signin.sweep(svc) # captured sessions of runs that ended while the server was down, sign-in browser folders
65
  if recovered:
66
  log.warning("marked %d run(s) interrupted after restart", len(recovered))
67
+ try:
68
+ from ..platform import left_on_pod as left
69
+ left.backfill_once(svc) # test documents earlier runs left on a pod, once per database
70
+ except Exception: # noqa: BLE001
71
+ log.exception("left-on-pod backfill failed")
72
  from ..platform.pods import PodRegistry
73
  cut = PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit).recover_screens()
74
  if cut:
 
128
  app.state.sign_in = SignInSessions(svc, run_mgr) # assisted sign-in browsers (routes/signin.py)
129
  run_mgr.sign_in = app.state.sign_in # a run that ends closes its own and drops its captured session
130
  errors.install(app)
131
+ # a "*" origin with credentials would let any website act as a signed-in person: never honoured
132
+ origins = [o for o in cfg.cors_origins if o.strip() != "*"]
133
+ if len(origins) != len(cfg.cors_origins):
134
+ log.warning("FPT_CORS_ORIGINS contains '*': ignored (the API sends credentials; list the origins that may call it)")
135
+ app.add_middleware(BodyLimit, limit=cfg.max_body_bytes)
136
+ app.add_middleware(CORSMiddleware, allow_origins=origins, allow_credentials=True,
137
  allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
138
  allow_headers=["Authorization", "Content-Type", "X-CSRF-Token", "X-Request-ID", "Last-Event-ID"],
139
  expose_headers=["X-Request-ID"])
140
  app.add_middleware(RequestContext)
141
 
142
  api = APIRouter(prefix="/api")
143
+ for r in (auth.router, runs.router, gates.router, review.router, admin.router, pods.router, screens.router, consultant.router, live.router, chat.router, assistant.router, llm.router, notifications.router, channels.router, integrations.router, tokens.router, custom_cases.router, recordings.router, heals.router, left_on_pod.router, agent_studio.router, ai_monitoring.router, signin.router):
144
  api.include_router(r)
145
  app.include_router(api)
146
  app.include_router(agent_studio.oauth) # /oauth/token: the Oracle AI Agent Studio client (docs/AGENT_STUDIO.md)
coworker/api/auth.py CHANGED
@@ -1,68 +1,67 @@
1
- """Authentication + RBAC dependencies.
2
- - Web app: httpOnly session cookie `fpt_session` + CSRF double-submit (`fpt_csrf` cookie, X-CSRF-Token header) on
3
- every unsafe method.
4
- - Desktop/API clients: `Authorization: Bearer <token>` (POST /api/auth/token). Bearer requests are CSRF-exempt.
5
- Roles: viewer, consultant, qa_approver, admin (coworker/platform/users.PERMISSIONS). Enforced here, not in the UI."""
6
- from __future__ import annotations
7
-
8
- import hmac
9
- from dataclasses import dataclass
10
-
11
- from fastapi import Depends, Request
12
-
13
- from ..platform.users import PERMISSIONS
14
- from .errors import ApiError
15
-
16
- SESSION_COOKIE = "fpt_session"
17
- CSRF_COOKIE = "fpt_csrf"
18
- CSRF_HEADER = "x-csrf-token"
19
- UNSAFE = {"POST", "PUT", "PATCH", "DELETE"}
20
-
21
-
22
- @dataclass
23
- class Principal:
24
- id: int
25
- username: str
26
- role: str
27
- via: str # cookie | bearer
28
-
29
- def can(self, perm: str) -> bool:
30
- return self.role in PERMISSIONS.get(perm, ())
31
-
32
- def to_dict(self) -> dict:
33
- return {"id": self.id, "username": self.username, "role": self.role, "via": self.via,
34
- "permissions": sorted(p for p in PERMISSIONS if self.can(p))}
35
-
36
-
37
- def current_user(request: Request) -> Principal:
38
- svc = request.app.state.svc
39
- authz = request.headers.get("authorization", "")
40
- if authz.lower().startswith("bearer "):
41
- if authz[7:].strip().startswith("pwt_"): # personal access tokens are for the MCP and A2A connectors only
42
- raise ApiError(401, "UNAUTHENTICATED", "personal access tokens work only on /mcp and /a2a (the MCP and A2A connectors)")
43
- got = svc.users.session_user(authz[7:].strip())
44
- if not got:
45
- raise ApiError(401, "UNAUTHENTICATED", "invalid or expired bearer token")
46
- u, _ = got
47
- p = Principal(u["id"], u["username"], u["role"], "bearer")
48
- else:
49
- tok = request.cookies.get(SESSION_COOKIE)
50
- got = svc.users.session_user(tok) if tok else None
51
- if not got:
52
- raise ApiError(401, "UNAUTHENTICATED", "not signed in")
53
- u, s = got
54
- if request.method in UNSAFE:
55
- hdr = request.headers.get(CSRF_HEADER, "")
56
- if not hdr or not hmac.compare_digest(hdr, s["csrf"]):
57
- raise ApiError(403, "CSRF", "missing or invalid CSRF token")
58
- p = Principal(u["id"], u["username"], u["role"], "cookie")
59
- request.state.user = p
60
- return p
61
-
62
-
63
- def require(perm: str):
64
- def dep(user: Principal = Depends(current_user)) -> Principal:
65
- if not user.can(perm):
66
- raise ApiError(403, "FORBIDDEN", f"role '{user.role}' lacks permission '{perm}'")
67
- return user
68
- return dep
 
1
+ """Authentication + RBAC dependencies.
2
+ - Web app: httpOnly session cookie `fpt_session` + CSRF double-submit (`fpt_csrf` cookie, X-CSRF-Token header) on
3
+ every unsafe method.
4
+ - Desktop/API clients: `Authorization: Bearer <token>` (POST /api/auth/token). Bearer requests are CSRF-exempt.
5
+ Roles: viewer, consultant, qa_approver, admin (coworker/platform/users.PERMISSIONS). Enforced here, not in the UI."""
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass
9
+
10
+ from fastapi import Depends, Request
11
+
12
+ from ..platform.users import PERMISSIONS, consteq
13
+ from .errors import ApiError
14
+
15
+ SESSION_COOKIE = "fpt_session"
16
+ CSRF_COOKIE = "fpt_csrf"
17
+ CSRF_HEADER = "x-csrf-token"
18
+ UNSAFE = {"POST", "PUT", "PATCH", "DELETE"}
19
+
20
+
21
+ @dataclass
22
+ class Principal:
23
+ id: int
24
+ username: str
25
+ role: str
26
+ via: str # cookie | bearer
27
+
28
+ def can(self, perm: str) -> bool:
29
+ return self.role in PERMISSIONS.get(perm, ())
30
+
31
+ def to_dict(self) -> dict:
32
+ return {"id": self.id, "username": self.username, "role": self.role, "via": self.via,
33
+ "permissions": sorted(p for p in PERMISSIONS if self.can(p))}
34
+
35
+
36
+ def current_user(request: Request) -> Principal:
37
+ svc = request.app.state.svc
38
+ authz = request.headers.get("authorization", "")
39
+ if authz.lower().startswith("bearer "):
40
+ if authz[7:].strip().startswith("pwt_"): # personal access tokens are for the MCP and A2A connectors only
41
+ raise ApiError(401, "UNAUTHENTICATED", "personal access tokens work only on /mcp and /a2a (the MCP and A2A connectors)")
42
+ got = svc.users.session_user(authz[7:].strip())
43
+ if not got:
44
+ raise ApiError(401, "UNAUTHENTICATED", "invalid or expired bearer token")
45
+ u, _ = got
46
+ p = Principal(u["id"], u["username"], u["role"], "bearer")
47
+ else:
48
+ tok = request.cookies.get(SESSION_COOKIE)
49
+ got = svc.users.session_user(tok) if tok else None
50
+ if not got:
51
+ raise ApiError(401, "UNAUTHENTICATED", "not signed in")
52
+ u, s = got
53
+ if request.method in UNSAFE:
54
+ hdr = request.headers.get(CSRF_HEADER, "")
55
+ if not hdr or not consteq(hdr, s["csrf"]):
56
+ raise ApiError(403, "CSRF", "missing or invalid CSRF token")
57
+ p = Principal(u["id"], u["username"], u["role"], "cookie")
58
+ request.state.user = p
59
+ return p
60
+
61
+
62
+ def require(perm: str):
63
+ def dep(user: Principal = Depends(current_user)) -> Principal:
64
+ if not user.can(perm):
65
+ raise ApiError(403, "FORBIDDEN", f"role '{user.role}' lacks permission '{perm}'")
66
+ return user
67
+ return dep
 
coworker/api/middleware.py CHANGED
@@ -1,110 +1,169 @@
1
- """Request IDs + structured JSON access logs + security headers (CSP, frame/sniff/referrer policies, HSTS on https)."""
2
- from __future__ import annotations
3
-
4
- import json
5
- import logging
6
- import re
7
- import secrets
8
- import sys
9
- import time
10
-
11
- from starlette.middleware.base import BaseHTTPMiddleware
12
- from starlette.requests import Request
13
-
14
- CSP_APP = ("default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; "
15
- "font-src 'self' data:; connect-src 'self'; frame-src 'self'; frame-ancestors 'self'; object-src 'none'; "
16
- "base-uri 'self'; form-action 'self'")
17
- # Swagger UI (/api/docs) loads its assets from jsDelivr; relaxed only on the docs pages.
18
- CSP_DOCS = ("default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' "
19
- "https://cdn.jsdelivr.net; img-src 'self' data: https://fastapi.tiangolo.com; connect-src 'self'; frame-ancestors 'self'")
20
- # Reports are generated by generate_report.py with inline styles; served sandboxed inside the app.
21
- CSP_REPORT = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; frame-ancestors 'self'; sandbox"
22
-
23
-
24
- class JsonFormatter(logging.Formatter):
25
- def format(self, record: logging.LogRecord) -> str:
26
- d = {"ts": time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(record.created)) + "Z", "level": record.levelname,
27
- "logger": record.name, "msg": record.getMessage()}
28
- for k in ("request_id", "method", "path", "status", "ms", "user"):
29
- if hasattr(record, k):
30
- d[k] = getattr(record, k)
31
- if record.exc_info:
32
- d["exc"] = self.formatException(record.exc_info)[-2000:]
33
- return json.dumps(d, default=str)
34
-
35
-
36
- class _HideTokens(logging.Filter):
37
- """Personal access tokens (pwt_...) never reach a log line, whatever logged them."""
38
- _RE = re.compile(r"pwt_[A-Za-z0-9_-]{8,}")
39
-
40
- def filter(self, record: logging.LogRecord) -> bool:
41
- if isinstance(record.msg, str) and "pwt_" in record.msg:
42
- record.msg = self._RE.sub("pwt_(hidden)", record.msg)
43
- if record.args:
44
- args = record.args if isinstance(record.args, tuple) else (record.args,)
45
- if any(isinstance(x, str) and "pwt_" in x for x in args):
46
- record.args = tuple(self._RE.sub("pwt_(hidden)", x) if isinstance(x, str) else x for x in args)
47
- return True
48
-
49
-
50
- def setup_logging(level: str = "INFO", logfile=None) -> None:
51
- root = logging.getLogger()
52
- if getattr(root, "_fpt_configured", False):
53
- return
54
- h = logging.StreamHandler(sys.stderr)
55
- h.setFormatter(JsonFormatter())
56
- h.addFilter(_HideTokens())
57
- root.handlers = [h]
58
- if logfile:
59
- # rotated: 10 MB per file, 5 kept (the log volume is part of the saved state on hosts without a disk)
60
- from logging.handlers import RotatingFileHandler
61
- fh = RotatingFileHandler(logfile, maxBytes=10 * 1024 * 1024, backupCount=5, encoding="utf-8")
62
- fh.setFormatter(JsonFormatter())
63
- fh.addFilter(_HideTokens())
64
- root.addHandler(fh)
65
- root.setLevel(level)
66
- root._fpt_configured = True # type: ignore[attr-defined]
67
-
68
-
69
- access = logging.getLogger("fpt.access")
70
-
71
-
72
- class RequestContext(BaseHTTPMiddleware):
73
- async def dispatch(self, request: Request, call_next):
74
- rid = request.headers.get("x-request-id", "")[:64] or secrets.token_hex(8)
75
- request.state.request_id = rid
76
- t0 = time.time()
77
- resp = await call_next(request)
78
- path = request.url.path
79
- resp.headers["X-Request-ID"] = rid
80
- resp.headers["X-Content-Type-Options"] = "nosniff"
81
- resp.headers["Referrer-Policy"] = "no-referrer"
82
- resp.headers["Permissions-Policy"] = "camera=(), microphone=(), geolocation=()"
83
- resp.headers["Cross-Origin-Opener-Policy"] = "same-origin"
84
- if "/report/" in path and path.endswith(("/html", "/bundle")):
85
- resp.headers["Content-Security-Policy"] = CSP_REPORT
86
- resp.headers["X-Frame-Options"] = "SAMEORIGIN"
87
- elif path.startswith("/api/docs") or path.startswith("/api/redoc"):
88
- resp.headers["Content-Security-Policy"] = CSP_DOCS
89
- resp.headers["X-Frame-Options"] = "DENY"
90
- else:
91
- resp.headers.setdefault("Content-Security-Policy", CSP_APP)
92
- resp.headers.setdefault("X-Frame-Options", "SAMEORIGIN")
93
- svc = getattr(request.app.state, "svc", None)
94
- embed = svc.cfg.embed_origin if svc is not None else ""
95
- if embed and not path.startswith(("/api/docs", "/api/redoc")):
96
- # shown inside the configured site's page: that site joins the allowed frame ancestors
97
- resp.headers["Content-Security-Policy"] = resp.headers["Content-Security-Policy"].replace(
98
- "frame-ancestors 'self'", f"frame-ancestors 'self' {embed}")
99
- del resp.headers["X-Frame-Options"]
100
- # https as the browser sees it: directly, or through a trusted proxy (FPT_TRUST_PROXY), or a server that always
101
- # uses secure cookies (FPT_COOKIE_SECURE=always, which only makes sense behind https)
102
- if request.url.scheme == "https" or (svc is not None and svc.cfg.cookie_secure == "always"):
103
- resp.headers["Strict-Transport-Security"] = "max-age=31536000"
104
- if path.startswith("/api/"):
105
- resp.headers.setdefault("Cache-Control", "no-store")
106
- user = getattr(getattr(request.state, "user", None), "username", None)
107
- if not path.endswith("/stream"):
108
- access.info("request", extra={"request_id": rid, "method": request.method, "path": path,
109
- "status": resp.status_code, "ms": int((time.time() - t0) * 1000), "user": user})
110
- return resp
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Request IDs + structured JSON access logs + security headers (CSP, frame/sniff/referrer policies, HSTS on https)."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import logging
6
+ import re
7
+ import secrets
8
+ import sys
9
+ import time
10
+
11
+ from starlette.middleware.base import BaseHTTPMiddleware
12
+ from starlette.requests import Request
13
+
14
+ CSP_APP = ("default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; "
15
+ "font-src 'self' data:; connect-src 'self'; frame-src 'self'; frame-ancestors 'self'; object-src 'none'; "
16
+ "base-uri 'self'; form-action 'self'")
17
+ # Swagger UI (/api/docs) loads its assets from jsDelivr; relaxed only on the docs pages.
18
+ CSP_DOCS = ("default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' "
19
+ "https://cdn.jsdelivr.net; img-src 'self' data: https://fastapi.tiangolo.com; connect-src 'self'; frame-ancestors 'self'")
20
+ # Reports are generated by generate_report.py with inline styles; served sandboxed inside the app.
21
+ CSP_REPORT = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; frame-ancestors 'self'; sandbox"
22
+
23
+
24
+ class JsonFormatter(logging.Formatter):
25
+ def format(self, record: logging.LogRecord) -> str:
26
+ d = {"ts": time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(record.created)) + "Z", "level": record.levelname,
27
+ "logger": record.name, "msg": record.getMessage()}
28
+ for k in ("request_id", "method", "path", "status", "ms", "user"):
29
+ if hasattr(record, k):
30
+ d[k] = getattr(record, k)
31
+ if record.exc_info:
32
+ d["exc"] = self.formatException(record.exc_info)[-2000:]
33
+ return json.dumps(d, default=str)
34
+
35
+
36
+ class _HideTokens(logging.Filter):
37
+ """Personal access tokens (pwt_...) never reach a log line, whatever logged them."""
38
+ _RE = re.compile(r"pwt_[A-Za-z0-9_-]{8,}")
39
+
40
+ def filter(self, record: logging.LogRecord) -> bool:
41
+ if isinstance(record.msg, str) and "pwt_" in record.msg:
42
+ record.msg = self._RE.sub("pwt_(hidden)", record.msg)
43
+ if record.args:
44
+ args = record.args if isinstance(record.args, tuple) else (record.args,)
45
+ if any(isinstance(x, str) and "pwt_" in x for x in args):
46
+ record.args = tuple(self._RE.sub("pwt_(hidden)", x) if isinstance(x, str) else x for x in args)
47
+ return True
48
+
49
+
50
+ def setup_logging(level: str = "INFO", logfile=None) -> None:
51
+ root = logging.getLogger()
52
+ if getattr(root, "_fpt_configured", False):
53
+ return
54
+ h = logging.StreamHandler(sys.stderr)
55
+ h.setFormatter(JsonFormatter())
56
+ h.addFilter(_HideTokens())
57
+ root.handlers = [h]
58
+ if logfile:
59
+ # rotated: 10 MB per file, 5 kept (the log volume is part of the saved state on hosts without a disk)
60
+ from logging.handlers import RotatingFileHandler
61
+ fh = RotatingFileHandler(logfile, maxBytes=10 * 1024 * 1024, backupCount=5, encoding="utf-8")
62
+ fh.setFormatter(JsonFormatter())
63
+ fh.addFilter(_HideTokens())
64
+ root.addHandler(fh)
65
+ root.setLevel(level)
66
+ root._fpt_configured = True # type: ignore[attr-defined]
67
+
68
+
69
+ access = logging.getLogger("fpt.access")
70
+
71
+
72
+ class _TooLarge(Exception):
73
+ pass
74
+
75
+
76
+ class BodyLimit:
77
+ """Refuses a request body over `limit` bytes with 413: at once from Content-Length, or while streaming when the sender
78
+ gives no length (chunked), so nothing buffers an endless body. Plain ASGI so it sees the raw stream. 0 = no limit."""
79
+
80
+ def __init__(self, app, limit: int):
81
+ self.app, self.limit = app, limit
82
+
83
+ async def __call__(self, scope, receive, send):
84
+ if scope["type"] != "http" or self.limit <= 0:
85
+ return await self.app(scope, receive, send)
86
+ try:
87
+ declared = int(dict(scope["headers"]).get(b"content-length") or 0)
88
+ except ValueError:
89
+ declared = 0
90
+ started, seen, exceeded = False, 0, False
91
+
92
+ def refusal() -> tuple[dict, dict]:
93
+ body = json.dumps({"detail": f"the request is larger than the {self.limit:,} bytes this server accepts", "code": "TOO_LARGE"}).encode()
94
+ return ({"type": "http.response.start", "status": 413, "headers": [
95
+ (b"content-type", b"application/json"), (b"content-length", str(len(body)).encode()), (b"connection", b"close")]},
96
+ {"type": "http.response.body", "body": body})
97
+
98
+ async def wrapped_send(msg):
99
+ nonlocal started
100
+ if exceeded: # whatever the app made of the cut-off body (a 400 for "could not parse it") becomes the 413
101
+ if msg["type"] == "http.response.start" and not started:
102
+ started = True
103
+ for m in refusal():
104
+ await send(m)
105
+ return
106
+ started = started or msg["type"] == "http.response.start"
107
+ await send(msg)
108
+
109
+ async def wrapped_receive():
110
+ nonlocal seen, exceeded
111
+ msg = await receive()
112
+ if msg["type"] == "http.request":
113
+ seen += len(msg.get("body") or b"")
114
+ if seen > self.limit:
115
+ exceeded = True
116
+ raise _TooLarge
117
+ return msg
118
+
119
+ if declared > self.limit:
120
+ for m in refusal():
121
+ await send(m)
122
+ return
123
+ try:
124
+ await self.app(scope, wrapped_receive, wrapped_send)
125
+ except _TooLarge:
126
+ if not started:
127
+ for m in refusal():
128
+ await send(m)
129
+
130
+
131
+ class RequestContext(BaseHTTPMiddleware):
132
+ async def dispatch(self, request: Request, call_next):
133
+ rid = request.headers.get("x-request-id", "")[:64] or secrets.token_hex(8)
134
+ request.state.request_id = rid
135
+ t0 = time.time()
136
+ resp = await call_next(request)
137
+ path = request.url.path
138
+ resp.headers["X-Request-ID"] = rid
139
+ resp.headers["X-Content-Type-Options"] = "nosniff"
140
+ resp.headers["Referrer-Policy"] = "no-referrer"
141
+ resp.headers["Permissions-Policy"] = "camera=(), microphone=(), geolocation=()"
142
+ resp.headers["Cross-Origin-Opener-Policy"] = "same-origin"
143
+ if "/report/" in path and path.endswith(("/html", "/bundle")):
144
+ resp.headers["Content-Security-Policy"] = CSP_REPORT
145
+ resp.headers["X-Frame-Options"] = "SAMEORIGIN"
146
+ elif path.startswith("/api/docs") or path.startswith("/api/redoc"):
147
+ resp.headers["Content-Security-Policy"] = CSP_DOCS
148
+ resp.headers["X-Frame-Options"] = "DENY"
149
+ else:
150
+ resp.headers.setdefault("Content-Security-Policy", CSP_APP)
151
+ resp.headers.setdefault("X-Frame-Options", "SAMEORIGIN")
152
+ svc = getattr(request.app.state, "svc", None)
153
+ embed = svc.cfg.embed_origin if svc is not None else ""
154
+ if embed and not path.startswith(("/api/docs", "/api/redoc")):
155
+ # shown inside the configured site's page: that site joins the allowed frame ancestors
156
+ resp.headers["Content-Security-Policy"] = resp.headers["Content-Security-Policy"].replace(
157
+ "frame-ancestors 'self'", f"frame-ancestors 'self' {embed}")
158
+ del resp.headers["X-Frame-Options"]
159
+ # https as the browser sees it: directly, or through a trusted proxy (FPT_TRUST_PROXY), or a server that always
160
+ # uses secure cookies (FPT_COOKIE_SECURE=always, which only makes sense behind https)
161
+ if request.url.scheme == "https" or (svc is not None and svc.cfg.cookie_secure == "always"):
162
+ resp.headers["Strict-Transport-Security"] = "max-age=31536000"
163
+ if path.startswith("/api/"):
164
+ resp.headers.setdefault("Cache-Control", "no-store")
165
+ user = getattr(getattr(request.state, "user", None), "username", None)
166
+ if not path.endswith("/stream"):
167
+ access.info("request", extra={"request_id": rid, "method": request.method, "path": path,
168
+ "status": resp.status_code, "ms": int((time.time() - t0) * 1000), "user": user})
169
+ return resp
coworker/api/openapi_dump.py CHANGED
@@ -1,19 +1,23 @@
1
- """Print the API's OpenAPI JSON (used by web/scripts/gen-api.mjs and the drift test). Uses a throwaway FPT_HOME."""
2
- from __future__ import annotations
3
-
4
- import json
5
- import sys
6
-
7
-
8
- def openapi_json() -> str:
9
- from ..tests.fakes import temp_settings
10
- from .app import create_app
11
- from ..graph.services import build_services
12
- import logging
13
- logging.disable(logging.CRITICAL)
14
- app = create_app(build_services(temp_settings()), background=False)
15
- return json.dumps(app.openapi(), indent=1, sort_keys=True)
16
-
17
-
18
- if __name__ == "__main__":
19
- sys.stdout.write(openapi_json())
 
 
 
 
 
1
+ """Print the API's OpenAPI JSON (used by web/scripts/gen-api.mjs and the drift test). Uses a throwaway FPT_HOME."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import sys
6
+
7
+
8
+ def openapi_json() -> str:
9
+ from ..tests.fakes import temp_settings
10
+ from .app import create_app
11
+ from ..graph.services import build_services
12
+ import logging
13
+ before = logging.root.manager.disable # restored after: a caller in the same process (the test run) keeps its logs
14
+ logging.disable(logging.CRITICAL)
15
+ try:
16
+ app = create_app(build_services(temp_settings()), background=False)
17
+ return json.dumps(app.openapi(), indent=1, sort_keys=True)
18
+ finally:
19
+ logging.disable(before)
20
+
21
+
22
+ if __name__ == "__main__":
23
+ sys.stdout.write(openapi_json())
coworker/api/routes/admin.py CHANGED
@@ -330,11 +330,11 @@ def put_feature(key: str, body: FeatureIn, request: Request, user: Principal = D
330
  def metrics(request: Request):
331
  """Counts for monitoring. Readable by an admin session or with `Authorization: Bearer <FPT_METRICS_TOKEN>`
332
  (a secret, for a scraper). No names, addresses or run content."""
333
- import hmac
334
  svc, runs = request.app.state.svc, request.app.state.runs
335
  token = svc.vault.get("METRICS_TOKEN") or ""
336
  authz = request.headers.get("authorization", "")
337
- if not (token and authz.lower().startswith("bearer ") and hmac.compare_digest(authz[7:].strip(), token)):
338
  from ..auth import current_user
339
  if not current_user(request).can("admin"):
340
  raise ApiError(403, "FORBIDDEN", "metrics need the admin role or the metrics token")
 
330
  def metrics(request: Request):
331
  """Counts for monitoring. Readable by an admin session or with `Authorization: Bearer <FPT_METRICS_TOKEN>`
332
  (a secret, for a scraper). No names, addresses or run content."""
333
+ from ...platform.users import consteq
334
  svc, runs = request.app.state.svc, request.app.state.runs
335
  token = svc.vault.get("METRICS_TOKEN") or ""
336
  authz = request.headers.get("authorization", "")
337
+ if not (token and authz.lower().startswith("bearer ") and consteq(authz[7:].strip(), token)):
338
  from ..auth import current_user
339
  if not current_user(request).can("admin"):
340
  raise ApiError(403, "FORBIDDEN", "metrics need the admin role or the metrics token")
coworker/api/routes/agent_studio.py CHANGED
@@ -1,325 +1,344 @@
1
- """Oracle Fusion AI Agent Studio (docs/AGENT_STUDIO.md).
2
-
3
- For the Fusion side (OAuth 2.0 client credentials, scope patchwise.invoke):
4
- POST /oauth/token client_credentials -> bearer token (one hour)
5
- POST /api/agent-studio/v1/test-data/check is this test data acceptable (synthetic, well formed)?
6
- POST /api/agent-studio/v1/cycles approved synthetic test data starts a test cycle (a retry with the
7
- same Idempotency-Key or correlation_id returns that cycle)
8
- GET /api/agent-studio/v1/cycles/{cycle_id} where the cycle is
9
- POST /api/agent-studio/v1/cycles/{cycle_id}/approval the person's start-testing decision, made in Fusion
10
- POST /api/agent-studio/v1/events/claim delivery mode pull: pick up waiting events
11
- POST /api/agent-studio/v1/events/ack confirm them
12
-
13
- For Astra administrators (signed-in session): clients, cycles, callbacks sent (dead letters sent again), the release
14
- watch, the stand-in."""
15
- from __future__ import annotations
16
-
17
- import base64
18
- import json
19
- from typing import Any, Literal
20
-
21
- from fastapi import APIRouter, Depends, Request, Response
22
- from pydantic import BaseModel, Field
23
-
24
- from ...platform.agent_studio import AgentStudio, AgentStudioError, verify_signature
25
- from ...platform.rundb import now_iso
26
- from ..auth import Principal, require
27
- from ..errors import ApiError
28
-
29
- router = APIRouter(tags=["agent-studio"]) # mounted under /api
30
- oauth = APIRouter(tags=["agent-studio"]) # mounted at the root: /oauth/token
31
-
32
-
33
- def _studio(request: Request) -> AgentStudio:
34
- return AgentStudio(request.app.state.svc)
35
-
36
-
37
- def _fail(e: AgentStudioError):
38
- raise ApiError(e.status, e.code, str(e))
39
-
40
-
41
- def agent_client(request: Request) -> dict:
42
- """The calling Fusion client, from its bearer token (never a person's session)."""
43
- auth = request.headers.get("authorization", "")
44
- token = auth[7:].strip() if auth.lower().startswith("bearer ") else ""
45
- try:
46
- return _studio(request).client_for_token(token)
47
- except AgentStudioError as e:
48
- raise ApiError(401, e.code, str(e)) from e
49
-
50
-
51
- # ====================================================================== OAuth 2.0 (client credentials)
52
- @oauth.post("/oauth/token", summary="OAuth 2.0 token (client credentials, scope patchwise.invoke)")
53
- async def token(request: Request):
54
- """Form (application/x-www-form-urlencoded) or JSON: grant_type=client_credentials, client_id, client_secret
55
- (or HTTP Basic), scope=patchwise.invoke (optional)."""
56
- ctype = request.headers.get("content-type", "")
57
- if "json" in ctype:
58
- form: dict[str, Any] = await request.json()
59
- else:
60
- form = dict(await request.form())
61
- cid, secret = form.get("client_id"), form.get("client_secret")
62
- basic = request.headers.get("authorization", "")
63
- if basic.lower().startswith("basic "):
64
- try:
65
- cid, secret = base64.b64decode(basic[6:]).decode().split(":", 1)
66
- except Exception: # noqa: BLE001
67
- raise ApiError(401, "invalid_client", "malformed Basic credentials")
68
- if form.get("grant_type") != "client_credentials":
69
- raise ApiError(400, "unsupported_grant_type", "only grant_type=client_credentials")
70
- try:
71
- return _studio(request).issue_token(str(cid or ""), str(secret or ""), form.get("scope"))
72
- except AgentStudioError as e:
73
- raise ApiError(e.status, e.code, str(e)) from e
74
-
75
-
76
- # ====================================================================== the Fusion workflow's calls
77
- class CycleIn(BaseModel):
78
- test_data: dict[str, dict[str, Any]] = Field(description="{AREA: {key: value or [values]}}: SYNTHETIC values only")
79
- data_approved_by: str = Field(min_length=1, max_length=120, description="who approved the test data in Fusion")
80
- environment: str | None = Field(None, description="the Patchwise test environment's name; the default Fusion one otherwise")
81
- areas: list[str] | None = Field(None, description="business areas to test (AP, PO, AR, GL ...); the test data's areas otherwise")
82
- release: str | None = Field(None, description="the quarterly update under test, e.g. 26B")
83
- callback_url: str | None = Field(None, description="where Patchwise reports back; the client's callback address otherwise")
84
- correlation_id: str | None = Field(None, max_length=120, description="the Fusion workflow's own id, echoed in every callback")
85
- depth: str | None = Field(None, max_length=20, description="regression (default: every scenario and an end-to-end flow per "
86
- "business process), standard or smoke")
87
- generated_by: str | None = None
88
- masked: bool | None = None
89
- validated: bool | None = None
90
- module_space: dict[str, Any] | None = None
91
- package: dict[str, Any] | None = Field(None, description="the approved test data package (V3.6 workflows): kept with the cycle")
92
-
93
-
94
- class ApprovalIn(BaseModel):
95
- decision: Literal["approve", "reject"]
96
- approved_by: str = Field(min_length=1, max_length=120, description="who decided, in Fusion")
97
- scenario_ids: list[str] | None = Field(None, description="approve only these; all scenarios otherwise")
98
- comment: str | None = Field(None, max_length=300)
99
-
100
-
101
- @router.post("/agent-studio/v1/test-data/check", summary="Check test data before sending it (synthetic, well formed)")
102
- def check_test_data(body: dict, request: Request, client: dict = Depends(agent_client)):
103
- """Also picks up and confirms events for delivery mode pull: {"pickup": {"max": 1, "cycle_id"?}} answers as
104
- /events/claim, {"confirm": ["dlv_..."]} as /events/ack. The Fusion tool's checkTestData function then serves the
105
- callback workflow too, so the workflow needs no new tool functions."""
106
- if isinstance(body.get("pickup"), dict):
107
- p = body["pickup"]
108
- try:
109
- n = max(1, min(int(p.get("max") or 1), 20))
110
- except (TypeError, ValueError):
111
- n = 1
112
- cycle = str(p["cycle_id"])[:40] if p.get("cycle_id") else None
113
- return _studio(request).claim(client["client_id"], n, cycle)
114
- if isinstance(body.get("confirm"), list):
115
- return _studio(request).ack(client["client_id"], [str(x) for x in body["confirm"]][:50])
116
- from ...platform.agent_studio import validate_test_data
117
- try:
118
- td = validate_test_data(body.get("test_data"))
119
- except AgentStudioError as e:
120
- return {"ok": False, "code": e.code, "problem": str(e)}
121
- from ...platform import fusion_catalog
122
- from ...platform.agent_studio import AREA_ALIASES
123
- known = {x["code"] for x in fusion_catalog.areas(request.app.state.svc.cfg.home)}
124
- sent = [str(a).upper() for a in body.get("test_data") or {}]
125
- return {"ok": True, "areas": {a: sorted(k) for a, k in td.items()},
126
- "mapped": {a: AREA_ALIASES[a] for a in sent if a in AREA_ALIASES},
127
- "not_testable": sorted(a for a in td if a not in known)}
128
-
129
-
130
- @router.post("/agent-studio/v1/cycles", status_code=202, summary="Start a test cycle with approved synthetic test data")
131
- def start_cycle(body: CycleIn, request: Request, response: Response, client: dict = Depends(agent_client)):
132
- """Safe to send again: with the same Idempotency-Key header (optional), or the same correlation_id while that cycle
133
- is still going, it starts nothing and answers with the cycle the first call made (202, same body; the header
134
- Idempotent-Replayed: true says so)."""
135
- try:
136
- cycle, replayed = _studio(request).start_or_replay(client, body.model_dump(exclude_none=True), request.app.state.runs,
137
- request.headers.get("idempotency-key"))
138
- except AgentStudioError as e:
139
- _fail(e)
140
- if replayed:
141
- response.headers["Idempotent-Replayed"] = "true"
142
- return cycle
143
-
144
-
145
- @router.get("/agent-studio/v1/cycles/{cycle_id}", summary="Where a test cycle is")
146
- def get_cycle(cycle_id: str, request: Request, client: dict = Depends(agent_client)):
147
- try:
148
- return _studio(request).cycle(cycle_id, client["client_id"])
149
- except AgentStudioError as e:
150
- _fail(e)
151
-
152
-
153
- @router.get("/agent-studio/cycles/{cycle_id}/package")
154
- def cycle_package(cycle_id: str, request: Request, user: Principal = Depends(require("admin"))):
155
- """The test data package the Fusion side approved for this cycle."""
156
- try:
157
- return _studio(request).package(cycle_id)
158
- except AgentStudioError as e:
159
- _fail(e)
160
-
161
-
162
- @router.post("/agent-studio/v1/cycles/{cycle_id}/approval", summary="The person's start-testing decision, made in Fusion")
163
- def approval(cycle_id: str, body: ApprovalIn, request: Request, client: dict = Depends(agent_client)):
164
- try:
165
- return _studio(request).approve(cycle_id, client, body.model_dump(exclude_none=True), request.app.state.runs)
166
- except AgentStudioError as e:
167
- _fail(e)
168
-
169
-
170
- class ClaimIn(BaseModel):
171
- max: int = Field(5, ge=1, le=20, description="at most this many events")
172
- cycle_id: str | None = Field(None, max_length=40, description="only this cycle's events")
173
-
174
-
175
- class AckIn(BaseModel):
176
- delivery_ids: list[str] = Field(min_length=1, max_length=50)
177
-
178
-
179
- @router.post("/agent-studio/v1/events/claim", summary="Pick up waiting events (delivery mode pull)")
180
- def claim_events(body: ClaimIn, request: Request, client: dict = Depends(agent_client)):
181
- """The events Astra would have sent (scripts_ready, failures_need_review, results, stopped, paused, patch_update), oldest
182
- first. Confirm each with /events/ack; one not confirmed within confirm_within_s is handed out again (at least once:
183
- the same event keeps its delivery_id)."""
184
- return _studio(request).claim(client["client_id"], body.max, body.cycle_id)
185
-
186
-
187
- @router.post("/agent-studio/v1/events/ack", summary="Confirm picked-up events")
188
- def ack_events(body: AckIn, request: Request, client: dict = Depends(agent_client)):
189
- return _studio(request).ack(client["client_id"], body.delivery_ids)
190
-
191
-
192
- # ====================================================================== administration (signed-in admins)
193
- class ClientIn(BaseModel):
194
- name: str = Field(min_length=1, max_length=80)
195
- callback_url: str | None = None
196
- release_watch_url: str | None = None
197
-
198
-
199
- class ClientPatch(BaseModel):
200
- callback_url: str | None = None
201
- release_watch_url: str | None = None
202
-
203
-
204
- @router.get("/agent-studio/clients")
205
- def list_clients(request: Request, user: Principal = Depends(require("admin"))):
206
- return {"items": _studio(request).clients()}
207
-
208
-
209
- @router.post("/agent-studio/clients", status_code=201)
210
- def create_client(body: ClientIn, request: Request, user: Principal = Depends(require("admin"))):
211
- try:
212
- return _studio(request).create_client(body.name, user.username, body.callback_url, body.release_watch_url)
213
- except AgentStudioError as e:
214
- _fail(e)
215
-
216
-
217
- @router.patch("/agent-studio/clients/{client_id}")
218
- def update_client(client_id: str, body: ClientPatch, request: Request, user: Principal = Depends(require("admin"))):
219
- try:
220
- return _studio(request).update_client(client_id, user.username, body.callback_url, body.release_watch_url)
221
- except AgentStudioError as e:
222
- _fail(e)
223
-
224
-
225
- class FusionDeliveryIn(BaseModel):
226
- base_url: str = Field(min_length=8, max_length=300, description="https://<pod host>")
227
- token_url: str = Field(min_length=8, max_length=400, description="the OCI IAM token address of the identity domain")
228
- client_id: str = Field(min_length=1, max_length=200, description="the confidential app allowed to call invokeAsync")
229
- client_secret: str | None = Field(None, max_length=400, description="write-only: kept in the vault")
230
- scope: str | None = Field(None, max_length=300)
231
- workflow_code: str | None = Field(None, max_length=80, description="default PATCH_TEST_CALLBACK_V3_7")
232
- invocation_mode: Literal["END_USER", "ADMIN"] | None = None
233
- workflow_status: Literal["PUBLISHED", "DRAFT"] | None = None
234
- conversational: bool | None = None
235
-
236
-
237
- class DeliveryIn(BaseModel):
238
- mode: Literal["url", "fusion", "pull"]
239
- fusion: FusionDeliveryIn | None = None
240
-
241
-
242
- @router.put("/agent-studio/clients/{client_id}/delivery")
243
- def set_delivery(client_id: str, body: DeliveryIn, request: Request, user: Principal = Depends(require("admin"))):
244
- """Where this client's events go: signed POSTs to its callback address, straight to Oracle Fusion (invokeAsync), or
245
- nowhere until the Fusion workflow picks them up (pull)."""
246
- f = body.fusion.model_dump(exclude_none=True) if body.fusion else {}
247
- secret = f.pop("client_secret", None)
248
- try:
249
- return _studio(request).set_delivery(client_id, user.username, body.mode, f, secret)
250
- except AgentStudioError as e:
251
- _fail(e)
252
-
253
-
254
- @router.post("/agent-studio/clients/{client_id}/delivery/test")
255
- def test_delivery(client_id: str, request: Request, user: Principal = Depends(require("admin"))):
256
- """Signs in to the Oracle identity domain with the saved app (no workflow is started)."""
257
- try:
258
- return _studio(request).test_delivery(client_id, user.username)
259
- except AgentStudioError as e:
260
- _fail(e)
261
-
262
-
263
- @router.delete("/agent-studio/clients/{client_id}", status_code=204)
264
- def revoke_client(client_id: str, request: Request, user: Principal = Depends(require("admin"))):
265
- try:
266
- _studio(request).revoke_client(client_id, user.username)
267
- except AgentStudioError as e:
268
- _fail(e)
269
-
270
-
271
- @router.get("/agent-studio/cycles")
272
- def list_cycles(request: Request, user: Principal = Depends(require("read"))):
273
- return {"items": _studio(request).cycles()}
274
-
275
-
276
- @router.get("/agent-studio/deliveries")
277
- def list_deliveries(request: Request, state: Literal["dead"] | None = None, user: Principal = Depends(require("admin"))):
278
- """The callbacks, newest first, each with its state (queued, picked_up, retrying, delivered, superseded, dead).
279
- ?state=dead lists the dead letters only: events that ran out of tries; send one again with .../requeue."""
280
- studio = _studio(request)
281
- return {"items": studio.deliveries(state=state), "dead_letters": studio.dead_letters()}
282
-
283
-
284
- @router.post("/agent-studio/deliveries/{delivery_id}/requeue")
285
- def requeue_delivery(delivery_id: str, request: Request, user: Principal = Depends(require("admin"))):
286
- """Send a dead letter (or an event still retrying) again: its tries start over, with the same delivery_id."""
287
- try:
288
- return _studio(request).requeue(delivery_id, user.username)
289
- except AgentStudioError as e:
290
- _fail(e)
291
-
292
-
293
- @router.get("/agent-studio/release-watch")
294
- def release_watch(request: Request, user: Principal = Depends(require("read"))):
295
- return request.app.state.svc.db.kv_get("agent_studio.release_watch", {}) or {}
296
-
297
-
298
- @router.post("/agent-studio/release-watch/check")
299
- def release_watch_now(request: Request, user: Principal = Depends(require("admin"))):
300
- return _studio(request).check_releases(actor=user.username)
301
-
302
-
303
- # ====================================================================== the stand-in (plays the Fusion side for tests and demos)
304
- @router.post("/agent-studio/standin/inbox", status_code=204, include_in_schema=False)
305
- async def standin_inbox(request: Request):
306
- """Receives callbacks when a client's callback address points here; checks the signature against every client's key."""
307
- body = await request.body()
308
- if len(body) > 512_000:
309
- raise ApiError(413, "TOO_LARGE", "callback too large")
310
- svc = request.app.state.svc
311
- sig = request.headers.get("x-patchwise-signature")
312
- ok = any(verify_signature(svc.vault.get(f"agent_studio.{c['client_id']}.signing") or "", body, sig)
313
- for c in svc.db.q("SELECT client_id FROM agent_clients WHERE revoked_at IS NULL"))
314
- try:
315
- payload = json.loads(body)
316
- except ValueError:
317
- raise ApiError(400, "BAD_JSON", "not JSON")
318
- svc.db.insert("agent_standin_inbox", {"event": str(payload.get("event") or "")[:40], "delivery_id": request.headers.get("x-patchwise-delivery"),
319
- "signature_ok": int(ok), "payload": json.dumps(payload), "received_at": now_iso()})
320
-
321
-
322
- @router.get("/agent-studio/standin/inbox")
323
- def standin_messages(request: Request, user: Principal = Depends(require("admin"))):
324
- rows = request.app.state.svc.db.q("SELECT * FROM agent_standin_inbox ORDER BY id DESC LIMIT 100")
325
- return {"items": [{**r, "payload": json.loads(r["payload"]) if isinstance(r["payload"], str) else r["payload"], "signature_ok": bool(r["signature_ok"])} for r in rows]}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Oracle Fusion AI Agent Studio (docs/AGENT_STUDIO.md).
2
+
3
+ For the Fusion side (OAuth 2.0 client credentials, scope patchwise.invoke):
4
+ POST /oauth/token client_credentials -> bearer token (one hour)
5
+ POST /api/agent-studio/v1/test-data/check is this test data acceptable (synthetic, well formed)?
6
+ POST /api/agent-studio/v1/cycles approved synthetic test data starts a test cycle (a retry with the
7
+ same Idempotency-Key or correlation_id returns that cycle)
8
+ GET /api/agent-studio/v1/cycles/{cycle_id} where the cycle is
9
+ POST /api/agent-studio/v1/cycles/{cycle_id}/approval the person's start-testing decision, made in Fusion
10
+ POST /api/agent-studio/v1/events/claim delivery mode pull: pick up waiting events
11
+ POST /api/agent-studio/v1/events/ack confirm them
12
+
13
+ For Astra administrators (signed-in session): clients, cycles, callbacks sent (dead letters sent again), the release
14
+ watch, the stand-in."""
15
+ from __future__ import annotations
16
+
17
+ import base64
18
+ import json
19
+ from typing import Any, Literal
20
+
21
+ from fastapi import APIRouter, Depends, Request, Response
22
+ from pydantic import BaseModel, Field
23
+
24
+ from ...platform.agent_studio import AgentStudio, AgentStudioError, verify_signature
25
+ from ...platform.rundb import now_iso
26
+ from ...platform.users import RateLimited
27
+ from ..auth import Principal, require
28
+ from ..errors import ApiError
29
+
30
+ router = APIRouter(tags=["agent-studio"]) # mounted under /api
31
+ oauth = APIRouter(tags=["agent-studio"]) # mounted at the root: /oauth/token
32
+
33
+
34
+ def _studio(request: Request) -> AgentStudio:
35
+ return AgentStudio(request.app.state.svc)
36
+
37
+
38
+ def _fail(e: AgentStudioError):
39
+ raise ApiError(e.status, e.code, str(e))
40
+
41
+
42
+ def agent_client(request: Request) -> dict:
43
+ """The calling Fusion client, from its bearer token (never a person's session)."""
44
+ auth = request.headers.get("authorization", "")
45
+ token = auth[7:].strip() if auth.lower().startswith("bearer ") else ""
46
+ try:
47
+ return _studio(request).client_for_token(token)
48
+ except AgentStudioError as e:
49
+ raise ApiError(401, e.code, str(e)) from e
50
+
51
+
52
+ # ====================================================================== OAuth 2.0 (client credentials)
53
+ @oauth.post("/oauth/token", summary="OAuth 2.0 token (client credentials, scope patchwise.invoke)")
54
+ async def token(request: Request):
55
+ """Form (application/x-www-form-urlencoded) or JSON: grant_type=client_credentials, client_id, client_secret
56
+ (or HTTP Basic), scope=patchwise.invoke (optional)."""
57
+ ctype = request.headers.get("content-type", "")
58
+ if "json" in ctype:
59
+ form: dict[str, Any] = await request.json()
60
+ else:
61
+ form = dict(await request.form())
62
+ cid, secret = form.get("client_id"), form.get("client_secret")
63
+ basic = request.headers.get("authorization", "")
64
+ if basic.lower().startswith("basic "):
65
+ try:
66
+ cid, secret = base64.b64decode(basic[6:]).decode().split(":", 1)
67
+ except Exception: # noqa: BLE001
68
+ raise ApiError(401, "invalid_client", "malformed Basic credentials")
69
+ if form.get("grant_type") != "client_credentials":
70
+ raise ApiError(400, "unsupported_grant_type", "only grant_type=client_credentials")
71
+ users = request.app.state.svc.users
72
+ key = f"oauth|{request.client.host if request.client else '-'}|{str(cid or '')[:80]}" # wrong secrets, per client and visitor
73
+ try:
74
+ users.check_rate(key)
75
+ except RateLimited as e:
76
+ raise ApiError(429, "rate_limited", "too many wrong client secrets; try again in a few minutes",
77
+ headers={"Retry-After": str(e.retry_after)}) from e
78
+ try:
79
+ out = _studio(request).issue_token(str(cid or ""), str(secret or ""), form.get("scope"))
80
+ except AgentStudioError as e:
81
+ if e.code == "invalid_client":
82
+ users.note_attempt(key, False)
83
+ raise ApiError(e.status, e.code, str(e)) from e
84
+ return out
85
+
86
+
87
+ # ====================================================================== the Fusion workflow's calls
88
+ class CycleIn(BaseModel):
89
+ test_data: dict[str, dict[str, Any]] = Field(description="{AREA: {key: value or [values]}}: SYNTHETIC values only")
90
+ data_approved_by: str = Field(min_length=1, max_length=120, description="who approved the test data in Fusion")
91
+ environment: str | None = Field(None, description="the Patchwise test environment's name; the default Fusion one otherwise")
92
+ areas: list[str] | None = Field(None, description="business areas to test (AP, PO, AR, GL ...); the test data's areas otherwise")
93
+ release: str | None = Field(None, description="the quarterly update under test, e.g. 26B")
94
+ callback_url: str | None = Field(None, description="where Patchwise reports back; the client's callback address otherwise")
95
+ correlation_id: str | None = Field(None, max_length=120, description="the Fusion workflow's own id, echoed in every callback")
96
+ depth: str | None = Field(None, max_length=20, description="regression (default: every scenario and an end-to-end flow per "
97
+ "business process), standard or smoke")
98
+ generated_by: str | None = None
99
+ masked: bool | None = None
100
+ validated: bool | None = None
101
+ module_space: dict[str, Any] | None = None
102
+ package: dict[str, Any] | None = Field(None, description="the approved test data package (V3.6 workflows): kept with the cycle")
103
+
104
+
105
+ class ApprovalIn(BaseModel):
106
+ decision: Literal["approve", "reject"]
107
+ approved_by: str = Field(min_length=1, max_length=120, description="who decided, in Fusion")
108
+ scenario_ids: list[str] | None = Field(None, description="approve only these; all scenarios otherwise")
109
+ comment: str | None = Field(None, max_length=300)
110
+
111
+
112
+ @router.post("/agent-studio/v1/test-data/check", summary="Check test data before sending it (synthetic, well formed)")
113
+ def check_test_data(body: dict, request: Request, client: dict = Depends(agent_client)):
114
+ """Also picks up and confirms events for delivery mode pull: {"pickup": {"max": 1, "cycle_id"?}} answers as
115
+ /events/claim, {"confirm": ["dlv_..."]} as /events/ack. The Fusion tool's checkTestData function then serves the
116
+ callback workflow too, so the workflow needs no new tool functions."""
117
+ if isinstance(body.get("pickup"), dict):
118
+ p = body["pickup"]
119
+ try:
120
+ n = max(1, min(int(p.get("max") or 1), 20))
121
+ except (TypeError, ValueError):
122
+ n = 1
123
+ cycle = str(p["cycle_id"])[:40] if p.get("cycle_id") else None
124
+ return _studio(request).claim(client["client_id"], n, cycle)
125
+ if isinstance(body.get("confirm"), list):
126
+ return _studio(request).ack(client["client_id"], [str(x) for x in body["confirm"]][:50])
127
+ from ...platform.agent_studio import validate_test_data
128
+ try:
129
+ td = validate_test_data(body.get("test_data"))
130
+ except AgentStudioError as e:
131
+ return {"ok": False, "code": e.code, "problem": str(e)}
132
+ from ...platform import fusion_catalog
133
+ from ...platform.agent_studio import AREA_ALIASES
134
+ known = {x["code"] for x in fusion_catalog.areas(request.app.state.svc.cfg.home)}
135
+ sent = [str(a).upper() for a in body.get("test_data") or {}]
136
+ return {"ok": True, "areas": {a: sorted(k) for a, k in td.items()},
137
+ "mapped": {a: AREA_ALIASES[a] for a in sent if a in AREA_ALIASES},
138
+ "not_testable": sorted(a for a in td if a not in known)}
139
+
140
+
141
+ @router.post("/agent-studio/v1/cycles", status_code=202, summary="Start a test cycle with approved synthetic test data")
142
+ def start_cycle(body: CycleIn, request: Request, response: Response, client: dict = Depends(agent_client)):
143
+ """Safe to send again: with the same Idempotency-Key header (optional), or the same correlation_id while that cycle
144
+ is still going, it starts nothing and answers with the cycle the first call made (202, same body; the header
145
+ Idempotent-Replayed: true says so)."""
146
+ try:
147
+ cycle, replayed = _studio(request).start_or_replay(client, body.model_dump(exclude_none=True), request.app.state.runs,
148
+ request.headers.get("idempotency-key"))
149
+ except AgentStudioError as e:
150
+ _fail(e)
151
+ if replayed:
152
+ response.headers["Idempotent-Replayed"] = "true"
153
+ return cycle
154
+
155
+
156
+ @router.get("/agent-studio/v1/cycles/{cycle_id}", summary="Where a test cycle is")
157
+ def get_cycle(cycle_id: str, request: Request, client: dict = Depends(agent_client)):
158
+ try:
159
+ return _studio(request).cycle(cycle_id, client["client_id"])
160
+ except AgentStudioError as e:
161
+ _fail(e)
162
+
163
+
164
+ @router.get("/agent-studio/cycles/{cycle_id}/package")
165
+ def cycle_package(cycle_id: str, request: Request, user: Principal = Depends(require("admin"))):
166
+ """The test data package the Fusion side approved for this cycle."""
167
+ try:
168
+ return _studio(request).package(cycle_id)
169
+ except AgentStudioError as e:
170
+ _fail(e)
171
+
172
+
173
+ @router.post("/agent-studio/v1/cycles/{cycle_id}/approval", summary="The person's start-testing decision, made in Fusion")
174
+ def approval(cycle_id: str, body: ApprovalIn, request: Request, client: dict = Depends(agent_client)):
175
+ try:
176
+ return _studio(request).approve(cycle_id, client, body.model_dump(exclude_none=True), request.app.state.runs)
177
+ except AgentStudioError as e:
178
+ _fail(e)
179
+
180
+
181
+ class ClaimIn(BaseModel):
182
+ max: int = Field(5, ge=1, le=20, description="at most this many events")
183
+ cycle_id: str | None = Field(None, max_length=40, description="only this cycle's events")
184
+
185
+
186
+ class AckIn(BaseModel):
187
+ delivery_ids: list[str] = Field(min_length=1, max_length=50)
188
+
189
+
190
+ @router.post("/agent-studio/v1/events/claim", summary="Pick up waiting events (delivery mode pull)")
191
+ def claim_events(body: ClaimIn, request: Request, client: dict = Depends(agent_client)):
192
+ """The events Astra would have sent (scripts_ready, failures_need_review, results, stopped, paused, patch_update), oldest
193
+ first. Confirm each with /events/ack; one not confirmed within confirm_within_s is handed out again (at least once:
194
+ the same event keeps its delivery_id)."""
195
+ return _studio(request).claim(client["client_id"], body.max, body.cycle_id)
196
+
197
+
198
+ @router.post("/agent-studio/v1/events/ack", summary="Confirm picked-up events")
199
+ def ack_events(body: AckIn, request: Request, client: dict = Depends(agent_client)):
200
+ return _studio(request).ack(client["client_id"], body.delivery_ids)
201
+
202
+
203
+ # ====================================================================== administration (signed-in admins)
204
+ class ClientIn(BaseModel):
205
+ name: str = Field(min_length=1, max_length=80)
206
+ callback_url: str | None = None
207
+ release_watch_url: str | None = None
208
+
209
+
210
+ class ClientPatch(BaseModel):
211
+ callback_url: str | None = None
212
+ release_watch_url: str | None = None
213
+
214
+
215
+ @router.get("/agent-studio/clients")
216
+ def list_clients(request: Request, user: Principal = Depends(require("admin"))):
217
+ return {"items": _studio(request).clients()}
218
+
219
+
220
+ @router.post("/agent-studio/clients", status_code=201)
221
+ def create_client(body: ClientIn, request: Request, user: Principal = Depends(require("admin"))):
222
+ try:
223
+ return _studio(request).create_client(body.name, user.username, body.callback_url, body.release_watch_url)
224
+ except AgentStudioError as e:
225
+ _fail(e)
226
+
227
+
228
+ @router.patch("/agent-studio/clients/{client_id}")
229
+ def update_client(client_id: str, body: ClientPatch, request: Request, user: Principal = Depends(require("admin"))):
230
+ try:
231
+ return _studio(request).update_client(client_id, user.username, body.callback_url, body.release_watch_url)
232
+ except AgentStudioError as e:
233
+ _fail(e)
234
+
235
+
236
+ class FusionDeliveryIn(BaseModel):
237
+ base_url: str = Field(min_length=8, max_length=300, description="https://<pod host>")
238
+ token_url: str = Field(min_length=8, max_length=400, description="the OCI IAM token address of the identity domain")
239
+ client_id: str = Field(min_length=1, max_length=200, description="the confidential app allowed to call invokeAsync")
240
+ client_secret: str | None = Field(None, max_length=400, description="write-only: kept in the vault")
241
+ scope: str | None = Field(None, max_length=300)
242
+ workflow_code: str | None = Field(None, max_length=80, description="default PATCH_TEST_CALLBACK_V3_7")
243
+ invocation_mode: Literal["END_USER", "ADMIN"] | None = None
244
+ workflow_status: Literal["PUBLISHED", "DRAFT"] | None = None
245
+ conversational: bool | None = None
246
+
247
+
248
+ class DeliveryIn(BaseModel):
249
+ mode: Literal["url", "fusion", "pull"]
250
+ fusion: FusionDeliveryIn | None = None
251
+
252
+
253
+ @router.put("/agent-studio/clients/{client_id}/delivery")
254
+ def set_delivery(client_id: str, body: DeliveryIn, request: Request, user: Principal = Depends(require("admin"))):
255
+ """Where this client's events go: signed POSTs to its callback address, straight to Oracle Fusion (invokeAsync), or
256
+ nowhere until the Fusion workflow picks them up (pull)."""
257
+ f = body.fusion.model_dump(exclude_none=True) if body.fusion else {}
258
+ secret = f.pop("client_secret", None)
259
+ try:
260
+ return _studio(request).set_delivery(client_id, user.username, body.mode, f, secret)
261
+ except AgentStudioError as e:
262
+ _fail(e)
263
+
264
+
265
+ @router.post("/agent-studio/clients/{client_id}/delivery/test")
266
+ def test_delivery(client_id: str, request: Request, user: Principal = Depends(require("admin"))):
267
+ """Signs in to the Oracle identity domain with the saved app (no workflow is started)."""
268
+ try:
269
+ return _studio(request).test_delivery(client_id, user.username)
270
+ except AgentStudioError as e:
271
+ _fail(e)
272
+
273
+
274
+ @router.delete("/agent-studio/clients/{client_id}", status_code=204)
275
+ def revoke_client(client_id: str, request: Request, user: Principal = Depends(require("admin"))):
276
+ try:
277
+ _studio(request).revoke_client(client_id, user.username)
278
+ except AgentStudioError as e:
279
+ _fail(e)
280
+
281
+
282
+ @router.get("/agent-studio/cycles")
283
+ def list_cycles(request: Request, user: Principal = Depends(require("read"))):
284
+ return {"items": _studio(request).cycles()}
285
+
286
+
287
+ @router.get("/agent-studio/deliveries")
288
+ def list_deliveries(request: Request, state: Literal["dead"] | None = None, user: Principal = Depends(require("admin"))):
289
+ """The callbacks, newest first, each with its state (queued, picked_up, retrying, delivered, superseded, dead).
290
+ ?state=dead lists the dead letters only: events that ran out of tries; send one again with .../requeue."""
291
+ studio = _studio(request)
292
+ return {"items": studio.deliveries(state=state), "dead_letters": studio.dead_letters()}
293
+
294
+
295
+ @router.post("/agent-studio/deliveries/{delivery_id}/requeue")
296
+ def requeue_delivery(delivery_id: str, request: Request, user: Principal = Depends(require("admin"))):
297
+ """Send a dead letter (or an event still retrying) again: its tries start over, with the same delivery_id."""
298
+ try:
299
+ return _studio(request).requeue(delivery_id, user.username)
300
+ except AgentStudioError as e:
301
+ _fail(e)
302
+
303
+
304
+ @router.get("/agent-studio/release-watch")
305
+ def release_watch(request: Request, user: Principal = Depends(require("read"))):
306
+ return request.app.state.svc.db.kv_get("agent_studio.release_watch", {}) or {}
307
+
308
+
309
+ @router.post("/agent-studio/release-watch/check")
310
+ def release_watch_now(request: Request, user: Principal = Depends(require("admin"))):
311
+ return _studio(request).check_releases(actor=user.username)
312
+
313
+
314
+ # ====================================================================== the stand-in (plays the Fusion side for tests and demos)
315
+ @router.post("/agent-studio/standin/inbox", status_code=204, include_in_schema=False)
316
+ async def standin_inbox(request: Request):
317
+ """Receives callbacks when a client's callback address points here; checks the signature against every client's key."""
318
+ body = await request.body()
319
+ if len(body) > 512_000:
320
+ raise ApiError(413, "TOO_LARGE", "callback too large")
321
+ svc = request.app.state.svc
322
+ key = f"standin|{request.client.host if request.client else '-'}" # open to anyone: a visitor may not fill the table
323
+ try:
324
+ svc.users.check_rate(key)
325
+ except RateLimited as e:
326
+ raise ApiError(429, "RATE_LIMITED", "too many callbacks", headers={"Retry-After": str(e.retry_after)}) from e
327
+ sig = request.headers.get("x-patchwise-signature")
328
+ ok = any(verify_signature(svc.vault.get(f"agent_studio.{c['client_id']}.signing") or "", body, sig)
329
+ for c in svc.db.q("SELECT client_id FROM agent_clients WHERE revoked_at IS NULL"))
330
+ try:
331
+ payload = json.loads(body)
332
+ except ValueError:
333
+ raise ApiError(400, "BAD_JSON", "not JSON")
334
+ if not ok:
335
+ svc.users.note_attempt(key, False) # an unsigned callback counts: 5 in 5 minutes per visitor, then paused
336
+ svc.db.insert("agent_standin_inbox", {"event": str(payload.get("event") or "")[:40], "delivery_id": request.headers.get("x-patchwise-delivery"),
337
+ "signature_ok": int(ok), "payload": json.dumps(payload), "received_at": now_iso()})
338
+ svc.db.x("DELETE FROM agent_standin_inbox WHERE id NOT IN (SELECT id FROM agent_standin_inbox ORDER BY id DESC LIMIT 500)")
339
+
340
+
341
+ @router.get("/agent-studio/standin/inbox")
342
+ def standin_messages(request: Request, user: Principal = Depends(require("admin"))):
343
+ rows = request.app.state.svc.db.q("SELECT * FROM agent_standin_inbox ORDER BY id DESC LIMIT 100")
344
+ return {"items": [{**r, "payload": json.loads(r["payload"]) if isinstance(r["payload"], str) else r["payload"], "signature_ok": bool(r["signature_ok"])} for r in rows]}
coworker/api/routes/auth.py CHANGED
@@ -1,296 +1,305 @@
1
- """/api/auth: login (rate limited) -> httpOnly session cookie + CSRF token; logout; me; bearer tokens; OIDC hook (stub)."""
2
- from __future__ import annotations
3
-
4
- from fastapi import APIRouter, Depends, Request, Response
5
-
6
- from ...platform import supabase as sb
7
- from ...platform.users import AuthError, RateLimited, StubOIDCProvider, sha256
8
- from ..auth import CSRF_COOKIE, SESSION_COOKIE, Principal, current_user
9
- from ..errors import ApiError
10
- from ..schemas import ForgotIn, LoginIn, LoginOut, PasswordChangeIn, RegisterIn, ResetIn, SessionRow, TokenOut, UserOut
11
-
12
- router = APIRouter(prefix="/auth", tags=["auth"])
13
-
14
-
15
- def _public_base(request: Request) -> str:
16
- """This app's own address for links in e-mails: FPT_PUBLIC_URL when set (always, in production: request headers can
17
- be chosen by whoever sends the request), else the address as the browser sees it (hosting platforms put a proxy in front)."""
18
- if request.app.state.svc.cfg.public_url:
19
- return request.app.state.svc.cfg.public_url.rstrip("/")
20
- host = request.headers.get("x-forwarded-host") or request.headers.get("host") or request.url.netloc
21
- scheme = request.headers.get("x-forwarded-proto") or ("https" if _secure(request) else request.url.scheme)
22
- return f"{scheme}://{host}"
23
-
24
-
25
- @router.post("/forgot")
26
- def forgot(body: ForgotIn, request: Request):
27
- """E-mail a password-reset link (Supabase accounts). Same answer whether or not the address has an account."""
28
- svc = request.app.state.svc
29
- client = sb.of(svc)
30
- if not client.auth_enabled:
31
- raise ApiError(409, "RESET_BY_ADMIN", "Passwords here are reset by an administrator. Ask your administrator.")
32
- email = body.email.strip().lower()
33
- if not sb.EMAIL_RE.match(email):
34
- raise ApiError(422, "BAD_EMAIL", "Enter a valid e-mail address.")
35
- key = f"forgot|{_client(request)}"
36
- try:
37
- svc.users.check_rate(key)
38
- except RateLimited as e:
39
- raise ApiError(429, "RATE_LIMITED", "Too many attempts. Please try again in a few minutes.", headers={"Retry-After": str(e.retry_after)}) from e
40
- svc.users.note_attempt(key, False) # every request counts towards the limit
41
- try:
42
- client.recover(email, f"{_public_base(request)}/reset")
43
- except sb.SupabaseError as e:
44
- svc.audit.append("auth.reset_request_failed", actor=email[:64], summary=e.code)
45
- if e.code == "RATE_LIMITED":
46
- raise ApiError(429, e.code, str(e)) from e
47
- svc.audit.append("auth.reset_requested", actor=email[:64], summary=_client(request))
48
- return {"status": "sent", "message": "If an account exists for that address, a reset link is on its way."}
49
-
50
-
51
- @router.post("/reset")
52
- def reset(body: ResetIn, request: Request):
53
- """Set a new password with the token from the reset link. The person then signs in as usual."""
54
- svc = request.app.state.svc
55
- client = sb.of(svc)
56
- if not client.auth_enabled:
57
- raise ApiError(409, "RESET_BY_ADMIN", "Passwords here are reset by an administrator.")
58
- key = f"reset|{_client(request)}"
59
- try:
60
- svc.users.check_rate(key)
61
- except RateLimited as e:
62
- raise ApiError(429, "RATE_LIMITED", "Too many attempts. Please try again in a few minutes.", headers={"Retry-After": str(e.retry_after)}) from e
63
- try:
64
- email = client.update_password(body.access_token, body.password)
65
- except sb.SupabaseError as e:
66
- svc.users.note_attempt(key, False)
67
- svc.audit.append("auth.reset_failed", actor="password-reset", summary=e.code)
68
- raise ApiError(e.status, e.code, str(e)) from e
69
- ended = svc.users.end_sessions_of(email) if email else 0 # a stolen session must not outlive the reset
70
- svc.audit.append("auth.password_reset", actor=(email or "password-reset")[:64], summary=f"{_client(request)}; {ended} session(s) ended")
71
- return {"status": "changed", "message": "Your password has been changed. Sign in with the new password."}
72
-
73
-
74
- def _secure(request: Request) -> bool:
75
- mode = request.app.state.svc.cfg.cookie_secure
76
- if mode == "always":
77
- return True
78
- if mode == "never":
79
- return False
80
- host = (request.url.hostname or "").lower()
81
- return request.url.scheme == "https" or host in ("localhost", "127.0.0.1", "::1")
82
-
83
-
84
- def _client(request: Request) -> str:
85
- return request.client.host if request.client else "-"
86
-
87
-
88
- def _role_for(svc, email: str, confirmed: bool) -> str:
89
- """Starting role of a new account. The administrator list only applies to an address the identity provider has
90
- confirmed: otherwise whoever registered an admin's address first would become admin."""
91
- if confirmed and email.lower() in {e.lower() for e in svc.cfg.admin_emails}:
92
- return "admin"
93
- return svc.cfg.register_role
94
-
95
-
96
- def _supabase_login(request: Request, email: str, password: str) -> dict:
97
- """Sign in through Supabase, then use the product's own account record and session (roles, CSRF, audit unchanged)."""
98
- svc = request.app.state.svc
99
- key = f"{email}|{_client(request)}"
100
- svc.users.check_rate(key)
101
- try:
102
- who = sb.of(svc).sign_in(email, password)
103
- except sb.SupabaseError as e:
104
- svc.users.note_attempt(key, False)
105
- if e.code == "EMAIL_NOT_CONFIRMED":
106
- raise ApiError(403, e.code, str(e)) from e
107
- raise AuthError("invalid username or password", "BAD_CREDENTIALS") from e
108
- svc.users.note_attempt(key, True)
109
- return svc.users.upsert_external(who["email"], who["id"], "supabase", _role_for(svc, who["email"], who.get("confirmed", False)))
110
-
111
-
112
- def _login(request: Request, body: LoginIn) -> dict:
113
- svc = request.app.state.svc
114
- try:
115
- name = body.username.strip()
116
- local = svc.users.by_name(name)
117
- if sb.of(svc).auth_enabled and sb.EMAIL_RE.match(name) and not (local and (local.get("auth_provider") or "local") == "local"):
118
- u = _supabase_login(request, name.lower(), body.password)
119
- else:
120
- u = svc.users.authenticate(body.username, body.password, _client(request))
121
- except RateLimited as e:
122
- svc.audit.append("auth.rate_limited", actor=body.username[:64], summary=_client(request))
123
- raise ApiError(429, "RATE_LIMITED", "too many failed login attempts; try again later",
124
- headers={"Retry-After": str(e.retry_after)}) from e
125
- except AuthError as e:
126
- if e.code == "BUSY": # too many sign-ins being checked at once (password hashing is capped)
127
- raise ApiError(503, "BUSY", "The server is busy. Please try again in a moment.", headers={"Retry-After": "5"}) from e
128
- svc.audit.append("auth.login_failed", actor=body.username[:64], summary=_client(request))
129
- raise ApiError(401, e.code, "invalid username or password") from e
130
- return u
131
-
132
-
133
- REMEMBER_HOURS = 7 * 24
134
-
135
-
136
- def _start_session(request: Request, response: Response, u: dict, remember: bool = False) -> str:
137
- """A server-side session and its cookies. Without "keep me signed in" the cookies end when the browser closes (and the
138
- session after SESSION_TTL_HOURS at the latest); with it they last up to 7 days."""
139
- svc = request.app.state.svc
140
- hours = REMEMBER_HOURS if remember else svc.cfg.session_ttl_hours
141
- token, csrf = svc.users.new_session(u["id"], "cookie", hours)
142
- sec, ttl = _secure(request), (hours * 3600 if remember else None)
143
- # inside another site's page (FPT_EMBED_ORIGIN) the browser only sends cookies marked SameSite=None; Secure
144
- same = "none" if svc.cfg.embed_origin else "strict"
145
- sec = sec or same == "none"
146
- response.set_cookie(SESSION_COOKIE, token, max_age=ttl, httponly=True, secure=sec, samesite=same, path="/")
147
- response.set_cookie(CSRF_COOKIE, csrf, max_age=ttl, httponly=False, secure=sec, samesite=same, path="/")
148
- return csrf
149
-
150
-
151
- @router.get("/config")
152
- def auth_config(request: Request):
153
- """Public: how people sign in here, and whether they can create their own account."""
154
- svc = request.app.state.svc
155
- on = sb.of(svc).auth_enabled
156
- return {"provider": "supabase" if on else "local", "registration": bool(on and svc.cfg.registration_enabled),
157
- "new_account_role": svc.cfg.register_role if on else None}
158
-
159
-
160
- @router.post("/register")
161
- def register(body: RegisterIn, request: Request, response: Response):
162
- """Create an account through the identity provider. New accounts get the configured starting role (never admin,
163
- unless the address is on the administrator list). Supabase may ask the person to confirm the address first."""
164
- svc = request.app.state.svc
165
- client = sb.of(svc)
166
- if not (client.auth_enabled and svc.cfg.registration_enabled):
167
- raise ApiError(403, "REGISTRATION_OFF", "Creating accounts is switched off here. Ask an administrator for access.")
168
- email = body.email.strip().lower()
169
- if not sb.EMAIL_RE.match(email):
170
- raise ApiError(422, "BAD_EMAIL", "Enter a valid e-mail address.")
171
- local = svc.users.by_name(email)
172
- if local and (local.get("auth_provider") or "local") == "local":
173
- raise ApiError(409, "ACCOUNT_CONFLICT", "That address cannot be used. Ask an administrator for access.")
174
- key = f"register|{_client(request)}"
175
- try:
176
- svc.users.check_rate(key)
177
- except RateLimited as e:
178
- raise ApiError(429, "RATE_LIMITED", "Too many attempts. Please try again in a few minutes.", headers={"Retry-After": str(e.retry_after)}) from e
179
- svc.users.note_attempt(key, False) # every sign-up counts towards the limit, successful or not
180
- try:
181
- who = client.sign_up(email, body.password)
182
- except sb.SupabaseError as e:
183
- svc.audit.append("auth.register_failed", actor=email[:64], summary=e.code)
184
- raise ApiError(e.status, e.code, str(e)) from e
185
- svc.audit.append("auth.registered", actor=email[:64], summary="signed in" if who["signed_in"] else "confirmation e-mail sent")
186
- if not who["signed_in"]:
187
- return {"status": "confirm_email", "message": "Check your inbox and open the confirmation link, then sign in."}
188
- try:
189
- u = svc.users.upsert_external(email, who["id"], "supabase", _role_for(svc, email, who.get("confirmed", False)))
190
- except AuthError as e:
191
- raise ApiError(409, e.code, str(e)) from e
192
- csrf = _start_session(request, response, u)
193
- p = Principal(u["id"], u["username"], u["role"], "cookie")
194
- return {"status": "signed_in", "user": p.to_dict(), "csrf_token": csrf}
195
-
196
-
197
- @router.post("/login", response_model=LoginOut)
198
- def login(body: LoginIn, request: Request, response: Response):
199
- svc = request.app.state.svc
200
- u = _login(request, body)
201
- csrf = _start_session(request, response, u, body.remember)
202
- svc.audit.append("auth.login", actor=u["username"], summary="cookie session" + (", kept signed in" if body.remember else ""))
203
- p = Principal(u["id"], u["username"], u["role"], "cookie")
204
- return {"user": p.to_dict(), "csrf_token": csrf}
205
-
206
-
207
- @router.post("/token", response_model=TokenOut)
208
- def token(body: LoginIn, request: Request):
209
- """Bearer token for the desktop app / API clients (no cookies, CSRF-exempt)."""
210
- svc = request.app.state.svc
211
- u = _login(request, body)
212
- tok, _ = svc.users.new_session(u["id"], "bearer")
213
- svc.audit.append("auth.token", actor=u["username"], summary="bearer token issued")
214
- p = Principal(u["id"], u["username"], u["role"], "bearer")
215
- return {"access_token": tok, "token_type": "bearer", "expires_in": svc.cfg.session_ttl_hours * 3600, "user": p.to_dict()}
216
-
217
-
218
- @router.post("/logout")
219
- def logout(request: Request, response: Response, user: Principal = Depends(current_user)):
220
- svc = request.app.state.svc
221
- tok = request.cookies.get(SESSION_COOKIE)
222
- authz = request.headers.get("authorization", "")
223
- if authz.lower().startswith("bearer "):
224
- tok = authz[7:].strip()
225
- if tok:
226
- svc.users.end_session(tok)
227
- response.delete_cookie(SESSION_COOKIE, path="/")
228
- response.delete_cookie(CSRF_COOKIE, path="/")
229
- svc.audit.append("auth.logout", actor=user.username)
230
- return {"status": "signed_out"}
231
-
232
-
233
- @router.get("/me", response_model=UserOut)
234
- def me(user: Principal = Depends(current_user)):
235
- return user.to_dict()
236
-
237
-
238
- def _token_of(request: Request) -> str | None:
239
- authz = request.headers.get("authorization", "")
240
- return authz[7:].strip() if authz.lower().startswith("bearer ") else request.cookies.get(SESSION_COOKIE)
241
-
242
-
243
- @router.get("/sessions", response_model=list[SessionRow])
244
- def my_sessions(request: Request, user: Principal = Depends(current_user)):
245
- """Where this account is signed in (browsers and API tokens), newest first."""
246
- svc = request.app.state.svc
247
- mine = svc.users.sessions_of(user.id)
248
- cur = sha256(_token_of(request) or "")
249
- return [{"id": s["id_hash"][:12], "kind": s["kind"], "created_at": s["created_at"], "expires_at": s["expires_at"],
250
- "current": s["id_hash"] == cur} for s in mine]
251
-
252
-
253
- @router.post("/sessions/end-others")
254
- def end_other_sessions(request: Request, user: Principal = Depends(current_user)):
255
- """Sign out everywhere else (other browsers, API tokens); this session stays."""
256
- svc = request.app.state.svc
257
- n = svc.users.end_other_sessions(user.id, _token_of(request))
258
- svc.audit.append("auth.sessions_ended", actor=user.username, summary=f"{n} other session(s) ended")
259
- return {"ended": n}
260
-
261
-
262
- @router.post("/password")
263
- def change_password(body: PasswordChangeIn, request: Request, user: Principal = Depends(current_user)):
264
- """Change your own password (accounts of this app). Other sessions are signed out; this one stays."""
265
- svc = request.app.state.svc
266
- try:
267
- svc.users.change_password(user.id, body.current_password, body.new_password)
268
- except RateLimited as e:
269
- raise ApiError(429, "RATE_LIMITED", "Too many attempts. Please try again in a few minutes.", headers={"Retry-After": str(e.retry_after)}) from e
270
- except AuthError as e:
271
- if e.code == "EXTERNAL_ACCOUNT":
272
- raise ApiError(409, e.code, "Your password is managed by your sign-in provider. Use 'Forgot your password?' on the sign-in page.") from e
273
- raise ApiError(403, "BAD_CURRENT_PASSWORD", "The current password is not right.") from e
274
- except ValueError as e:
275
- raise ApiError(422, "WEAK_PASSWORD", str(e).capitalize() + ".") from e
276
- n = svc.users.end_other_sessions(user.id, _token_of(request))
277
- svc.audit.append("auth.password_changed", actor=user.username, summary=f"{n} other session(s) ended")
278
- return {"status": "changed", "other_sessions_ended": n}
279
-
280
-
281
- @router.get("/csrf")
282
- def csrf(request: Request, user: Principal = Depends(current_user)):
283
- """Re-read the CSRF token for the current cookie session (e.g. after a page reload)."""
284
- if user.via != "cookie":
285
- return {"csrf_token": None}
286
- _, s = request.app.state.svc.users.session_user(request.cookies.get(SESSION_COOKIE, ""))
287
- return {"csrf_token": s["csrf"]}
288
-
289
-
290
- @router.get("/oidc/login")
291
- def oidc_login(request: Request):
292
- """OIDC hook (STUB). Production: the client's IdP with PKCE; IdP groups mapped to roles."""
293
- try:
294
- return {"redirect": StubOIDCProvider(request.app.state.svc.cfg.oidc_issuer).authorization_url("state")}
295
- except Exception as e: # noqa: BLE001
296
- raise ApiError(501, "OIDC_NOT_CONFIGURED", str(e)) from e
 
 
 
 
 
 
 
 
 
 
1
+ """/api/auth: login (rate limited) -> httpOnly session cookie + CSRF token; logout; me; bearer tokens; OIDC hook (stub)."""
2
+ from __future__ import annotations
3
+
4
+ from fastapi import APIRouter, Depends, Request, Response
5
+
6
+ from ...platform import supabase as sb
7
+ from ...platform.users import AuthError, RateLimited, StubOIDCProvider, sha256
8
+ from ..auth import CSRF_COOKIE, SESSION_COOKIE, Principal, current_user
9
+ from ..errors import ApiError
10
+ from ..schemas import ForgotIn, LoginIn, LoginOut, PasswordChangeIn, RegisterIn, ResetIn, SessionRow, TokenOut, UserOut
11
+
12
+ router = APIRouter(prefix="/auth", tags=["auth"])
13
+
14
+
15
+ def _public_base(request: Request) -> str:
16
+ """This app's own address for links in e-mails: FPT_PUBLIC_URL when set (always, in production: request headers can
17
+ be chosen by whoever sends the request), else the address as the browser sees it (hosting platforms put a proxy in front)."""
18
+ if request.app.state.svc.cfg.public_url:
19
+ return request.app.state.svc.cfg.public_url.rstrip("/")
20
+ host = request.headers.get("x-forwarded-host") or request.headers.get("host") or request.url.netloc
21
+ scheme = request.headers.get("x-forwarded-proto") or ("https" if _secure(request) else request.url.scheme)
22
+ return f"{scheme}://{host}"
23
+
24
+
25
+ @router.post("/forgot")
26
+ def forgot(body: ForgotIn, request: Request):
27
+ """E-mail a password-reset link (Supabase accounts). Same answer whether or not the address has an account."""
28
+ svc = request.app.state.svc
29
+ client = sb.of(svc)
30
+ if not client.auth_enabled:
31
+ raise ApiError(409, "RESET_BY_ADMIN", "Passwords here are reset by an administrator. Ask your administrator.")
32
+ email = body.email.strip().lower()
33
+ if not sb.EMAIL_RE.match(email):
34
+ raise ApiError(422, "BAD_EMAIL", "Enter a valid e-mail address.")
35
+ key = f"forgot|{_client(request)}"
36
+ try:
37
+ svc.users.check_rate(key)
38
+ except RateLimited as e:
39
+ raise ApiError(429, "RATE_LIMITED", "Too many attempts. Please try again in a few minutes.", headers={"Retry-After": str(e.retry_after)}) from e
40
+ svc.users.note_attempt(key, False) # every request counts towards the limit
41
+ try:
42
+ client.recover(email, f"{_public_base(request)}/reset")
43
+ except sb.SupabaseError as e:
44
+ svc.audit.append("auth.reset_request_failed", actor=email[:64], summary=e.code)
45
+ if e.code == "RATE_LIMITED":
46
+ raise ApiError(429, e.code, str(e)) from e
47
+ svc.audit.append("auth.reset_requested", actor=email[:64], summary=_client(request))
48
+ return {"status": "sent", "message": "If an account exists for that address, a reset link is on its way."}
49
+
50
+
51
+ @router.post("/reset")
52
+ def reset(body: ResetIn, request: Request):
53
+ """Set a new password with the token from the reset link. The person then signs in as usual."""
54
+ svc = request.app.state.svc
55
+ client = sb.of(svc)
56
+ if not client.auth_enabled:
57
+ raise ApiError(409, "RESET_BY_ADMIN", "Passwords here are reset by an administrator.")
58
+ key = f"reset|{_client(request)}"
59
+ try:
60
+ svc.users.check_rate(key)
61
+ except RateLimited as e:
62
+ raise ApiError(429, "RATE_LIMITED", "Too many attempts. Please try again in a few minutes.", headers={"Retry-After": str(e.retry_after)}) from e
63
+ try:
64
+ email = client.update_password(body.access_token, body.password)
65
+ except sb.SupabaseError as e:
66
+ svc.users.note_attempt(key, False)
67
+ svc.audit.append("auth.reset_failed", actor="password-reset", summary=e.code)
68
+ raise ApiError(e.status, e.code, str(e)) from e
69
+ ended = svc.users.end_sessions_of(email) if email else 0 # a stolen session must not outlive the reset
70
+ svc.audit.append("auth.password_reset", actor=(email or "password-reset")[:64], summary=f"{_client(request)}; {ended} session(s) ended")
71
+ return {"status": "changed", "message": "Your password has been changed. Sign in with the new password."}
72
+
73
+
74
+ def _secure(request: Request) -> bool:
75
+ mode = request.app.state.svc.cfg.cookie_secure
76
+ if mode == "always":
77
+ return True
78
+ if mode == "never":
79
+ return False
80
+ host = (request.url.hostname or "").lower()
81
+ return request.url.scheme == "https" or host in ("localhost", "127.0.0.1", "::1")
82
+
83
+
84
+ def _client(request: Request) -> str:
85
+ return request.client.host if request.client else "-"
86
+
87
+
88
+ def _role_for(svc, email: str, confirmed: bool) -> str:
89
+ """Starting role of a new account. The administrator list only applies to an address the identity provider has
90
+ confirmed: otherwise whoever registered an admin's address first would become admin."""
91
+ if confirmed and email.lower() in {e.lower() for e in svc.cfg.admin_emails}:
92
+ return "admin"
93
+ return svc.cfg.register_role
94
+
95
+
96
+ def _supabase_login(request: Request, email: str, password: str) -> dict:
97
+ """Sign in through Supabase, then use the product's own account record and session (roles, CSRF, audit unchanged)."""
98
+ svc = request.app.state.svc
99
+ client = _client(request)
100
+ svc.users.check_login(email, client)
101
+ try:
102
+ who = sb.of(svc).sign_in(email, password)
103
+ except sb.SupabaseError as e:
104
+ svc.users.note_login(email, client, False)
105
+ if e.code == "EMAIL_NOT_CONFIRMED":
106
+ raise ApiError(403, e.code, str(e)) from e
107
+ raise AuthError("invalid username or password", "BAD_CREDENTIALS") from e
108
+ svc.users.note_login(email, client, True)
109
+ return svc.users.upsert_external(who["email"], who["id"], "supabase", _role_for(svc, who["email"], who.get("confirmed", False)))
110
+
111
+
112
+ def _who(svc, name: str) -> str:
113
+ """The name to audit for a failed sign-in: a real account or an e-mail address as typed, anything else only as a short
114
+ fingerprint (people paste a password into the name field; the audit log is append-only, so it must never hold one)."""
115
+ name = (name or "").strip()
116
+ if svc.users.by_name(name) or sb.EMAIL_RE.match(name):
117
+ return name[:64]
118
+ return "unknown:" + sha256(name.lower())[:10]
119
+
120
+
121
+ def _login(request: Request, body: LoginIn) -> dict:
122
+ svc = request.app.state.svc
123
+ try:
124
+ name = body.username.strip()
125
+ local = svc.users.by_name(name)
126
+ if sb.of(svc).auth_enabled and sb.EMAIL_RE.match(name) and not (local and (local.get("auth_provider") or "local") == "local"):
127
+ u = _supabase_login(request, name.lower(), body.password)
128
+ else:
129
+ u = svc.users.authenticate(body.username, body.password, _client(request))
130
+ except RateLimited as e:
131
+ svc.audit.append("auth.rate_limited", actor=_who(svc, body.username), summary=_client(request))
132
+ raise ApiError(429, "RATE_LIMITED", "too many failed login attempts; try again later",
133
+ headers={"Retry-After": str(e.retry_after)}) from e
134
+ except AuthError as e:
135
+ if e.code == "BUSY": # too many sign-ins being checked at once (password hashing is capped)
136
+ raise ApiError(503, "BUSY", "The server is busy. Please try again in a moment.", headers={"Retry-After": "5"}) from e
137
+ svc.audit.append("auth.login_failed", actor=_who(svc, body.username), summary=_client(request))
138
+ raise ApiError(401, e.code, "invalid username or password") from e
139
+ return u
140
+
141
+
142
+ REMEMBER_HOURS = 7 * 24
143
+
144
+
145
+ def _start_session(request: Request, response: Response, u: dict, remember: bool = False) -> str:
146
+ """A server-side session and its cookies. Without "keep me signed in" the cookies end when the browser closes (and the
147
+ session after SESSION_TTL_HOURS at the latest); with it they last up to 7 days."""
148
+ svc = request.app.state.svc
149
+ hours = REMEMBER_HOURS if remember else svc.cfg.session_ttl_hours
150
+ token, csrf = svc.users.new_session(u["id"], "cookie", hours)
151
+ sec, ttl = _secure(request), (hours * 3600 if remember else None)
152
+ # inside another site's page (FPT_EMBED_ORIGIN) the browser only sends cookies marked SameSite=None; Secure
153
+ same = "none" if svc.cfg.embed_origin else "strict"
154
+ sec = sec or same == "none"
155
+ response.set_cookie(SESSION_COOKIE, token, max_age=ttl, httponly=True, secure=sec, samesite=same, path="/")
156
+ response.set_cookie(CSRF_COOKIE, csrf, max_age=ttl, httponly=False, secure=sec, samesite=same, path="/")
157
+ return csrf
158
+
159
+
160
+ @router.get("/config")
161
+ def auth_config(request: Request):
162
+ """Public: how people sign in here, and whether they can create their own account."""
163
+ svc = request.app.state.svc
164
+ on = sb.of(svc).auth_enabled
165
+ return {"provider": "supabase" if on else "local", "registration": bool(on and svc.cfg.registration_enabled),
166
+ "new_account_role": svc.cfg.register_role if on else None}
167
+
168
+
169
+ @router.post("/register")
170
+ def register(body: RegisterIn, request: Request, response: Response):
171
+ """Create an account through the identity provider. New accounts get the configured starting role (never admin,
172
+ unless the address is on the administrator list). Supabase may ask the person to confirm the address first."""
173
+ svc = request.app.state.svc
174
+ client = sb.of(svc)
175
+ if not (client.auth_enabled and svc.cfg.registration_enabled):
176
+ raise ApiError(403, "REGISTRATION_OFF", "Creating accounts is switched off here. Ask an administrator for access.")
177
+ email = body.email.strip().lower()
178
+ if not sb.EMAIL_RE.match(email):
179
+ raise ApiError(422, "BAD_EMAIL", "Enter a valid e-mail address.")
180
+ local = svc.users.by_name(email)
181
+ if local and (local.get("auth_provider") or "local") == "local":
182
+ raise ApiError(409, "ACCOUNT_CONFLICT", "That address cannot be used. Ask an administrator for access.")
183
+ key = f"register|{_client(request)}"
184
+ try:
185
+ svc.users.check_rate(key)
186
+ except RateLimited as e:
187
+ raise ApiError(429, "RATE_LIMITED", "Too many attempts. Please try again in a few minutes.", headers={"Retry-After": str(e.retry_after)}) from e
188
+ svc.users.note_attempt(key, False) # every sign-up counts towards the limit, successful or not
189
+ try:
190
+ who = client.sign_up(email, body.password)
191
+ except sb.SupabaseError as e:
192
+ svc.audit.append("auth.register_failed", actor=email[:64], summary=e.code)
193
+ raise ApiError(e.status, e.code, str(e)) from e
194
+ svc.audit.append("auth.registered", actor=email[:64], summary="signed in" if who["signed_in"] else "confirmation e-mail sent")
195
+ if not who["signed_in"]:
196
+ return {"status": "confirm_email", "message": "Check your inbox and open the confirmation link, then sign in."}
197
+ try:
198
+ u = svc.users.upsert_external(email, who["id"], "supabase", _role_for(svc, email, who.get("confirmed", False)))
199
+ except AuthError as e:
200
+ raise ApiError(409, e.code, str(e)) from e
201
+ csrf = _start_session(request, response, u)
202
+ p = Principal(u["id"], u["username"], u["role"], "cookie")
203
+ return {"status": "signed_in", "user": p.to_dict(), "csrf_token": csrf}
204
+
205
+
206
+ @router.post("/login", response_model=LoginOut)
207
+ def login(body: LoginIn, request: Request, response: Response):
208
+ svc = request.app.state.svc
209
+ u = _login(request, body)
210
+ csrf = _start_session(request, response, u, body.remember)
211
+ svc.audit.append("auth.login", actor=u["username"], summary="cookie session" + (", kept signed in" if body.remember else ""))
212
+ p = Principal(u["id"], u["username"], u["role"], "cookie")
213
+ return {"user": p.to_dict(), "csrf_token": csrf}
214
+
215
+
216
+ @router.post("/token", response_model=TokenOut)
217
+ def token(body: LoginIn, request: Request):
218
+ """Bearer token for the desktop app / API clients (no cookies, CSRF-exempt)."""
219
+ svc = request.app.state.svc
220
+ u = _login(request, body)
221
+ tok, _ = svc.users.new_session(u["id"], "bearer")
222
+ svc.audit.append("auth.token", actor=u["username"], summary="bearer token issued")
223
+ p = Principal(u["id"], u["username"], u["role"], "bearer")
224
+ return {"access_token": tok, "token_type": "bearer", "expires_in": svc.cfg.session_ttl_hours * 3600, "user": p.to_dict()}
225
+
226
+
227
+ @router.post("/logout")
228
+ def logout(request: Request, response: Response, user: Principal = Depends(current_user)):
229
+ svc = request.app.state.svc
230
+ tok = request.cookies.get(SESSION_COOKIE)
231
+ authz = request.headers.get("authorization", "")
232
+ if authz.lower().startswith("bearer "):
233
+ tok = authz[7:].strip()
234
+ if tok:
235
+ svc.users.end_session(tok)
236
+ response.delete_cookie(SESSION_COOKIE, path="/")
237
+ response.delete_cookie(CSRF_COOKIE, path="/")
238
+ svc.audit.append("auth.logout", actor=user.username)
239
+ return {"status": "signed_out"}
240
+
241
+
242
+ @router.get("/me", response_model=UserOut)
243
+ def me(user: Principal = Depends(current_user)):
244
+ return user.to_dict()
245
+
246
+
247
+ def _token_of(request: Request) -> str | None:
248
+ authz = request.headers.get("authorization", "")
249
+ return authz[7:].strip() if authz.lower().startswith("bearer ") else request.cookies.get(SESSION_COOKIE)
250
+
251
+
252
+ @router.get("/sessions", response_model=list[SessionRow])
253
+ def my_sessions(request: Request, user: Principal = Depends(current_user)):
254
+ """Where this account is signed in (browsers and API tokens), newest first."""
255
+ svc = request.app.state.svc
256
+ mine = svc.users.sessions_of(user.id)
257
+ cur = sha256(_token_of(request) or "")
258
+ return [{"id": s["id_hash"][:12], "kind": s["kind"], "created_at": s["created_at"], "expires_at": s["expires_at"],
259
+ "current": s["id_hash"] == cur} for s in mine]
260
+
261
+
262
+ @router.post("/sessions/end-others")
263
+ def end_other_sessions(request: Request, user: Principal = Depends(current_user)):
264
+ """Sign out everywhere else (other browsers, API tokens); this session stays."""
265
+ svc = request.app.state.svc
266
+ n = svc.users.end_other_sessions(user.id, _token_of(request))
267
+ svc.audit.append("auth.sessions_ended", actor=user.username, summary=f"{n} other session(s) ended")
268
+ return {"ended": n}
269
+
270
+
271
+ @router.post("/password")
272
+ def change_password(body: PasswordChangeIn, request: Request, user: Principal = Depends(current_user)):
273
+ """Change your own password (accounts of this app). Other sessions are signed out; this one stays."""
274
+ svc = request.app.state.svc
275
+ try:
276
+ svc.users.change_password(user.id, body.current_password, body.new_password)
277
+ except RateLimited as e:
278
+ raise ApiError(429, "RATE_LIMITED", "Too many attempts. Please try again in a few minutes.", headers={"Retry-After": str(e.retry_after)}) from e
279
+ except AuthError as e:
280
+ if e.code == "EXTERNAL_ACCOUNT":
281
+ raise ApiError(409, e.code, "Your password is managed by your sign-in provider. Use 'Forgot your password?' on the sign-in page.") from e
282
+ raise ApiError(403, "BAD_CURRENT_PASSWORD", "The current password is not right.") from e
283
+ except ValueError as e:
284
+ raise ApiError(422, "WEAK_PASSWORD", str(e).capitalize() + ".") from e
285
+ n = svc.users.end_other_sessions(user.id, _token_of(request))
286
+ svc.audit.append("auth.password_changed", actor=user.username, summary=f"{n} other session(s) ended")
287
+ return {"status": "changed", "other_sessions_ended": n}
288
+
289
+
290
+ @router.get("/csrf")
291
+ def csrf(request: Request, user: Principal = Depends(current_user)):
292
+ """Re-read the CSRF token for the current cookie session (e.g. after a page reload)."""
293
+ if user.via != "cookie":
294
+ return {"csrf_token": None}
295
+ _, s = request.app.state.svc.users.session_user(request.cookies.get(SESSION_COOKIE, ""))
296
+ return {"csrf_token": s["csrf"]}
297
+
298
+
299
+ @router.get("/oidc/login")
300
+ def oidc_login(request: Request):
301
+ """OIDC hook (STUB). Production: the client's IdP with PKCE; IdP groups mapped to roles."""
302
+ try:
303
+ return {"redirect": StubOIDCProvider(request.app.state.svc.cfg.oidc_issuer).authorization_url("state")}
304
+ except Exception as e: # noqa: BLE001
305
+ raise ApiError(501, "OIDC_NOT_CONFIGURED", str(e)) from e
coworker/api/routes/left_on_pod.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """/api/left-on-pod: test documents a run left on a Fusion pod that only a person can undo (platform/left_on_pod.py).
2
+ Everyone signed in can read the list; marking one done or dismissed, and looking at the pod again (read-only), is for
3
+ the people who start runs. Nothing here changes anything on a pod."""
4
+ from __future__ import annotations
5
+
6
+ from fastapi import APIRouter, Depends, Query, Request
7
+
8
+ from ...platform import left_on_pod
9
+ from ...platform.killswitch import KillSwitchEngaged
10
+ from ..auth import Principal, require
11
+ from ..errors import ApiError
12
+ from ..schemas import LeftDecisionIn, LeftOnPodRow, Page
13
+
14
+ router = APIRouter(tags=["left-on-pod"])
15
+ SELECT = "SELECT l.*, p.name AS pod_name FROM left_on_pod l LEFT JOIN pods p ON p.id = l.pod_id"
16
+
17
+
18
+ def _err(e: left_on_pod.LeftError) -> ApiError:
19
+ return ApiError(e.status, e.code, str(e))
20
+
21
+
22
+ def _row(svc, row_id: int) -> dict:
23
+ return svc.db.one(f"{SELECT} WHERE l.id=?", (row_id,))
24
+
25
+
26
+ @router.get("/left-on-pod", response_model=Page[LeftOnPodRow])
27
+ def left_list(request: Request, pod_id: int | None = None, status: str | None = Query(None, pattern="^(open|done|dismissed)$"),
28
+ kind: str | None = Query(None, pattern="^(" + "|".join(left_on_pod.KINDS) + ")$"), run_id: str | None = None,
29
+ limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0), user: Principal = Depends(require("read"))):
30
+ db = request.app.state.svc.db
31
+ conds, args = [], []
32
+ for col, v in (("l.pod_id", pod_id), ("l.status", status), ("l.kind", kind), ("l.run_id", run_id)):
33
+ if v is not None:
34
+ conds.append(f"{col}=?")
35
+ args.append(v)
36
+ w = (" WHERE " + " AND ".join(conds)) if conds else ""
37
+ rows = db.q(f"{SELECT}{w} ORDER BY (l.status='open') DESC, l.id DESC LIMIT ? OFFSET ?", args + [limit, offset])
38
+ return {"items": rows, "total": db.one(f"SELECT COUNT(*) n FROM left_on_pod l{w}", args)["n"], "limit": limit, "offset": offset}
39
+
40
+
41
+ @router.post("/left-on-pod/{row_id}/decision", response_model=LeftOnPodRow)
42
+ def left_decide(row_id: int, body: LeftDecisionIn, request: Request, user: Principal = Depends(require("left.decide"))):
43
+ svc = request.app.state.svc
44
+ try:
45
+ left_on_pod.decide(svc, row_id, body.decision, user.username, body.note)
46
+ except left_on_pod.LeftError as e:
47
+ raise _err(e) from e
48
+ return _row(svc, row_id)
49
+
50
+
51
+ @router.post("/left-on-pod/{row_id}/recheck", response_model=LeftOnPodRow)
52
+ def left_recheck(row_id: int, request: Request, user: Principal = Depends(require("left.decide"))):
53
+ """Look at the pod again with GET requests only: still there, or looks resolved. Changes nothing on the pod."""
54
+ svc = request.app.state.svc
55
+ try:
56
+ left_on_pod.recheck(svc, row_id)
57
+ except left_on_pod.LeftError as e:
58
+ raise _err(e) from e
59
+ except KillSwitchEngaged as e:
60
+ raise ApiError(423, "KILL_SWITCH", str(e)) from e
61
+ return _row(svc, row_id)
coworker/api/routes/runs.py CHANGED
@@ -332,8 +332,13 @@ def evidence_file(evidence_id: int, request: Request, user: Principal = Depends(
332
  except FileNotFoundError as e: # a fixed sentence: the OS error text could show server paths
333
  raise ApiError(404, "NOT_FOUND", f"Screenshot or recording {evidence_id} is not available: it was removed by the "
334
  "retention clean-up, or it is no longer stored on this server.") from e
335
- return Response(content=data, media_type=ctype, headers={"Content-Disposition": f'inline; filename="evidence-{evidence_id}"',
336
- "Cache-Control": "no-store"})
 
 
 
 
 
337
 
338
 
339
  @router.get("/pod/profile")
 
332
  except FileNotFoundError as e: # a fixed sentence: the OS error text could show server paths
333
  raise ApiError(404, "NOT_FOUND", f"Screenshot or recording {evidence_id} is not available: it was removed by the "
334
  "retention clean-up, or it is no longer stored on this server.") from e
335
+ # Evidence comes from a browser run (possibly on another host). Pictures and videos show inline; anything else downloads,
336
+ # and nothing it holds can run as part of the app (own sandboxed policy).
337
+ shown = ctype.split(";")[0].strip().lower().startswith(("image/", "video/"))
338
+ return Response(content=data, media_type=ctype, headers={
339
+ "Content-Disposition": f'{"inline" if shown else "attachment"}; filename="evidence-{evidence_id}"', "Cache-Control": "no-store",
340
+ "Content-Security-Policy": "default-src 'none'; img-src 'self' data:; media-src 'self'; style-src 'unsafe-inline'; "
341
+ "frame-ancestors 'self'; sandbox"})
342
 
343
 
344
  @router.get("/pod/profile")
coworker/api/runner.py CHANGED
@@ -33,13 +33,19 @@ def end_sign_in(svc, run_id: str, sessions=None) -> None:
33
 
34
 
35
  def sweep_test_data(svc, run_id: str, reason: str) -> dict | None:
36
- """Cancel Fusion test invoices a run left behind (platform/cleanup.py); never raises."""
37
  from ..platform import cleanup
38
  try:
39
- return cleanup.sweep(svc, run_id, reason)
40
  except Exception: # noqa: BLE001
41
  log.exception("test data clean-up of run %s failed", run_id)
42
- return None
 
 
 
 
 
 
43
 
44
 
45
  class RunError(RuntimeError):
 
33
 
34
 
35
  def sweep_test_data(svc, run_id: str, reason: str) -> dict | None:
36
+ """Cancel Fusion test invoices a run left behind (platform/cleanup.py), then record what stays on the pod; never raises."""
37
  from ..platform import cleanup
38
  try:
39
+ out = cleanup.sweep(svc, run_id, reason)
40
  except Exception: # noqa: BLE001
41
  log.exception("test data clean-up of run %s failed", run_id)
42
+ out = None
43
+ try: # what stays on the pod for a person goes to the ledger (platform/left_on_pod.py), also when the sweep had nothing to do
44
+ from ..platform import left_on_pod
45
+ left_on_pod.record(svc, run_id)
46
+ except Exception: # noqa: BLE001
47
+ log.exception("recording the test documents run %s left on its pod failed", run_id)
48
+ return out
49
 
50
 
51
  class RunError(RuntimeError):
coworker/api/schemas.py CHANGED
@@ -223,6 +223,7 @@ class PodRow(BaseModel):
223
  credentials: list[PodCredentialRow]
224
  runnable: bool
225
  not_runnable_reason: str | None = None
 
226
 
227
 
228
  class PodCheck(BaseModel):
@@ -383,6 +384,32 @@ class RunNoteIn(Strict):
383
  text: str = Field(min_length=1, max_length=2000)
384
 
385
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
386
  class NoteIn(Strict):
387
  note: str | None = Field(default=None, max_length=1000)
388
 
 
223
  credentials: list[PodCredentialRow]
224
  runnable: bool
225
  not_runnable_reason: str | None = None
226
+ left_open: int = 0 # test documents left on the pod that a person still has to deal with (GET /left-on-pod)
227
 
228
 
229
  class PodCheck(BaseModel):
 
384
  text: str = Field(min_length=1, max_length=2000)
385
 
386
 
387
+ class LeftDecisionIn(Strict):
388
+ decision: Literal["done", "dismiss", "reopen"]
389
+ note: str | None = Field(default=None, max_length=1000)
390
+
391
+
392
+ class LeftOnPodRow(BaseModel):
393
+ id: int
394
+ pod_id: int
395
+ pod_name: str | None = None
396
+ run_id: str
397
+ scenario: str | None = None
398
+ kind: str
399
+ reference: str # the number or FPT- tag of the test document
400
+ why: str # why it was left
401
+ todo: str # what a person should do
402
+ created_at: str
403
+ recorded_at: str
404
+ status: Literal["open", "done", "dismissed"]
405
+ decided_by: str | None = None
406
+ decided_at: str | None = None
407
+ note: str | None = None
408
+ check_state: Literal["still_on_pod", "looks_resolved", "unknown"] | None = None # the last read-only look at the pod
409
+ check_detail: str | None = None
410
+ checked_at: str | None = None
411
+
412
+
413
  class NoteIn(Strict):
414
  note: str | None = Field(default=None, max_length=1000)
415
 
coworker/config.py CHANGED
@@ -53,6 +53,13 @@ class Settings(BaseSettings):
53
  session_ttl_hours: int = 12
54
  login_max_attempts: int = 5
55
  login_window_s: int = 300
 
 
 
 
 
 
 
56
  web_dist: Path = Field(default=ROOT / "web" / "dist", validation_alias=_alias("fpt_web_dist", "web_dist"))
57
  oidc_issuer: str = ""
58
  # shown in the menu and on the sign-in page (a reseller or customer can set its own)
 
53
  session_ttl_hours: int = 12
54
  login_max_attempts: int = 5
55
  login_window_s: int = 300
56
+ # Wider sign-in limits on top of the 5 per user and visitor (0 = off). Failed attempts in the window: from one visitor
57
+ # across all names (counted only behind a trusted proxy, FPT_TRUST_PROXY, else every visitor looks alike), and for one
58
+ # name across all visitors (so a spread-out guesser cannot keep trying one account).
59
+ login_max_attempts_per_ip: int = Field(30, validation_alias=_alias("fpt_login_max_per_ip", "login_max_attempts_per_ip"))
60
+ login_max_attempts_per_user: int = Field(50, validation_alias=_alias("fpt_login_max_per_user", "login_max_attempts_per_user"))
61
+ # largest request body the API reads (bytes); a bigger one is refused with 413 before it is read. 0 = no limit
62
+ max_body_bytes: int = Field(12_000_000, validation_alias=_alias("fpt_max_body_bytes", "max_body_bytes"))
63
  web_dist: Path = Field(default=ROOT / "web" / "dist", validation_alias=_alias("fpt_web_dist", "web_dist"))
64
  oidc_issuer: str = ""
65
  # shown in the menu and on the sign-in page (a reseller or customer can set its own)
coworker/graph/nodes/design.py CHANGED
@@ -68,7 +68,9 @@ def test_generator(state, config, svc) -> dict:
68
  else:
69
  active.append(c)
70
  depth = state.get("depth") or "standard"
71
- if depth == "full": # the whole regression pack of the areas: every priority, every approved scenario
 
 
72
  keep, out_of_scope = list(active), []
73
  else:
74
  keep, out_of_scope = select_scope(active, include_p2 and depth != "smoke")
 
68
  else:
69
  active.append(c)
70
  depth = state.get("depth") or "standard"
71
+ # the whole regression pack of the areas (full), or scenarios a person chose by name: every priority runs (a P2
72
+ # chosen by name was deferred by the depth rule, seen on a 26D run: 10 of 19 chosen scenarios never ran)
73
+ if depth == "full" or only:
74
  keep, out_of_scope = list(active), []
75
  else:
76
  keep, out_of_scope = select_scope(active, include_p2 and depth != "smoke")
coworker/graph/services.py CHANGED
@@ -122,7 +122,9 @@ def build_services(cfg: Settings | None = None, transport=None, frontier_transpo
122
  tickets = sinks[cfg.ticket_sink]()
123
  memory = SqliteFailureMemory(db)
124
  autonomy = AutonomyPolicy(db, memory, cfg, audit)
125
- users = UserStore(db, cfg.session_ttl_hours, cfg.login_max_attempts, cfg.login_window_s)
 
 
126
  svc = Services(cfg, db, audit, kill, vault, redactor, egress, stub, router, evidence, library, tickets, memory,
127
  autonomy, users)
128
  # AI model settings saved in the app (Settings > AI models) override the environment, here and in every process
 
122
  tickets = sinks[cfg.ticket_sink]()
123
  memory = SqliteFailureMemory(db)
124
  autonomy = AutonomyPolicy(db, memory, cfg, audit)
125
+ users = UserStore(db, cfg.session_ttl_hours, cfg.login_max_attempts, cfg.login_window_s,
126
+ max_per_ip=cfg.login_max_attempts_per_ip if cfg.trust_proxy else 0,
127
+ max_per_user=cfg.login_max_attempts_per_user)
128
  svc = Services(cfg, db, audit, kill, vault, redactor, egress, stub, router, evidence, library, tickets, memory,
129
  autonomy, users)
130
  # AI model settings saved in the app (Settings > AI models) override the environment, here and in every process
coworker/platform/agent_studio.py CHANGED
@@ -34,6 +34,7 @@ from datetime import datetime, timedelta, timezone
34
  from urllib.parse import urlparse
35
 
36
  from .rundb import now_iso
 
37
 
38
  log = logging.getLogger("fpt.agent_studio")
39
  _TOKENS: dict[str, tuple[str, float]] = {} # client_id -> (Oracle access token, expires at); never stored
@@ -171,7 +172,7 @@ def token_client_id(svc, token: str, now: float | None = None) -> str | None:
171
  if len(parts) != 5 or parts[0] != TOKEN_VERSION or not parts[2].isdigit():
172
  return None
173
  body = ".".join(parts[:4])
174
- if not hmac.compare_digest(_token_mac(svc, body), parts[4]) or int(parts[2]) < (now or time.time()):
175
  return None
176
  return parts[1]
177
 
@@ -436,7 +437,7 @@ class AgentStudio:
436
  def issue_token(self, client_id: str, client_secret: str, scope: str | None = None) -> dict:
437
  """client_credentials grant. Only the invoke scope exists: start cycles, forward approvals, read their status."""
438
  r = self.db.one("SELECT * FROM agent_clients WHERE client_id=?", (client_id or "",))
439
- if not r or r.get("revoked_at") or not hmac.compare_digest(r["secret_hash"], _hash(client_secret or "")):
440
  raise AgentStudioError("invalid_client", "unknown client or wrong secret", 401)
441
  if scope and scope.strip() != SCOPE:
442
  raise AgentStudioError("invalid_scope", f"the only scope is {SCOPE}", 400)
@@ -955,7 +956,7 @@ def verify_signature(key: str, body: bytes, header: str | None) -> bool:
955
  """What the Fusion side does with each callback: HMAC-SHA256 of the raw body with its signing key."""
956
  if not header or not header.startswith("sha256="):
957
  return False
958
- return hmac.compare_digest(header[7:], hmac.new(key.encode(), body, hashlib.sha256).hexdigest())
959
 
960
 
961
  class Courier:
 
34
  from urllib.parse import urlparse
35
 
36
  from .rundb import now_iso
37
+ from .users import consteq
38
 
39
  log = logging.getLogger("fpt.agent_studio")
40
  _TOKENS: dict[str, tuple[str, float]] = {} # client_id -> (Oracle access token, expires at); never stored
 
172
  if len(parts) != 5 or parts[0] != TOKEN_VERSION or not parts[2].isdigit():
173
  return None
174
  body = ".".join(parts[:4])
175
+ if not consteq(_token_mac(svc, body), parts[4]) or int(parts[2]) < (now or time.time()):
176
  return None
177
  return parts[1]
178
 
 
437
  def issue_token(self, client_id: str, client_secret: str, scope: str | None = None) -> dict:
438
  """client_credentials grant. Only the invoke scope exists: start cycles, forward approvals, read their status."""
439
  r = self.db.one("SELECT * FROM agent_clients WHERE client_id=?", (client_id or "",))
440
+ if not r or r.get("revoked_at") or not consteq(r["secret_hash"], _hash(client_secret or "")):
441
  raise AgentStudioError("invalid_client", "unknown client or wrong secret", 401)
442
  if scope and scope.strip() != SCOPE:
443
  raise AgentStudioError("invalid_scope", f"the only scope is {SCOPE}", 400)
 
956
  """What the Fusion side does with each callback: HMAC-SHA256 of the raw body with its signing key."""
957
  if not header or not header.startswith("sha256="):
958
  return False
959
+ return consteq(header[7:], hmac.new(key.encode(), body, hashlib.sha256).hexdigest())
960
 
961
 
962
  class Courier:
coworker/platform/health_check.py CHANGED
@@ -15,7 +15,8 @@ from ..config import server_commit
15
  from . import canary, llm_settings, preflight
16
 
17
  RUNNER_TIMEOUT = 8 # seconds: a slow runner is itself a finding
18
- STUCK_HOURS = 6 # a run still running or waiting this long after its last change
 
19
  SIGN_IN_MAX_HOURS = 24 # an older connection test says little about the pod now
20
  CANARY_MAX_DAYS = 3
21
  USAGE_MAX_DAYS = 30
@@ -123,11 +124,19 @@ def _canary(svc, now: datetime) -> dict:
123
 
124
 
125
  def _local_items(svc, now: datetime) -> list[dict]:
126
- rows = svc.db.q(f"SELECT run_id, updated_at FROM runs WHERE status IN ({','.join('?' * len(LIVE))})", LIVE)
127
- stuck = [r["run_id"] for r in rows if (_age(r["updated_at"], now) or 0) > STUCK_HOURS]
 
 
 
128
  out = [_item("runs", "No stuck runs", not stuck,
129
- f"{len(stuck)} run(s) unchanged for over {STUCK_HOURS} hours: {', '.join(stuck[:5])}." if stuck else f"No run has been running or waiting for over {STUCK_HOURS} hours.",
130
- "Open each run and cancel it or give it the answer it waits for: stuck runs hold the runner.")]
 
 
 
 
 
131
  v = llm_settings.view(svc)["active"]
132
  on = v["local"] != "built-in rules" or v["external"] != "off"
133
  out.append(_item("llm", "AI model configured", on, f"Local: {v['local']}; external: {v['external']}." if on
 
15
  from . import canary, llm_settings, preflight
16
 
17
  RUNNER_TIMEOUT = 8 # seconds: a slow runner is itself a finding
18
+ STUCK_HOURS = 6 # a run still working this long after its last change
19
+ WAIT_DAYS = 7 # a run waiting for a person's review or approval this long is worth a reminder
20
  SIGN_IN_MAX_HOURS = 24 # an older connection test says little about the pod now
21
  CANARY_MAX_DAYS = 3
22
  USAGE_MAX_DAYS = 30
 
124
 
125
 
126
  def _local_items(svc, now: datetime) -> list[dict]:
127
+ rows = svc.db.q(f"SELECT run_id, updated_at, status FROM runs WHERE status IN ({','.join('?' * len(LIVE))})", LIVE)
128
+ # a run paused at a gate waits for a person and holds nothing; only a run still working with no change is stuck
129
+ waiting = [r for r in rows if str(r["status"]).startswith("waiting")]
130
+ stuck = [r["run_id"] for r in rows if r not in waiting and (_age(r["updated_at"], now) or 0) > STUCK_HOURS]
131
+ old = [r["run_id"] for r in waiting if (_age(r["updated_at"], now) or 0) > WAIT_DAYS * 24]
132
  out = [_item("runs", "No stuck runs", not stuck,
133
+ f"{len(stuck)} run(s) working with no change for over {STUCK_HOURS} hours: {', '.join(stuck[:5])}." if stuck
134
+ else f"No run has been working without a change for over {STUCK_HOURS} hours.",
135
+ "Open each run and cancel it: a stuck run holds the runner."),
136
+ _item("waiting", "Runs waiting for a person", not old,
137
+ f"{len(old)} run(s) waiting for a review or approval for over {WAIT_DAYS} days: {', '.join(old[:5])}." if old
138
+ else f"{len(waiting)} run(s) waiting for a person, none for over {WAIT_DAYS} days.",
139
+ "Open each run and give the review or approval it waits for, or cancel it.")]
140
  v = llm_settings.view(svc)["active"]
141
  on = v["local"] != "built-in rules" or v["external"] != "off"
142
  out.append(_item("llm", "AI model configured", on, f"Local: {v['local']}; external: {v['external']}." if on
coworker/platform/left_on_pod.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test documents left on a Fusion pod that only a person can undo: one ledger for every run (table left_on_pod, migration 030).
2
+
3
+ What a run created is in its folder (platform/cleanup.py: created-test-data.jsonl, written by the fixtures before each save
4
+ and after each clean-up, and test-data-cleanup.json, the backend sweep's result). At the end of each run's clean-up record()
5
+ copies every document that stays on the pod into the ledger: a completed receivables transaction or a receipt, a received or
6
+ closed purchase order, a receipt of an order, a requisition pending approval, a posted journal the run did not reverse,
7
+ whatever a refused cancel left. One row per (pod, run, kind, reference), so the same run can be recorded again (a
8
+ restart, the backfill) without a duplicate or a lost decision. backfill() does the same for the runs that finished before the
9
+ ledger existed (at start-up once, and `python -m coworker left-on-pod backfill`).
10
+
11
+ Only the document's number or tag, the name of the test and our own sentences are kept: never a record of the client's.
12
+ recheck() looks at the pod again with GET requests only (through the egress gate) and says whether the document is still
13
+ there or looks resolved; it never changes anything on the pod."""
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import logging
18
+ from pathlib import Path
19
+
20
+ from . import cleanup
21
+ from .cleanup import _first, _q, _status
22
+ from .egress import EgressDenied
23
+ from .killswitch import KillSwitchEngaged
24
+ from .rundb import now_iso
25
+
26
+ log = logging.getLogger("fpt.left_on_pod")
27
+
28
+ KINDS = ("ap_invoice", "po_requisition", "po_order", "po_receipt", "gl_journal", "ar_transaction", "ar_receipt")
29
+ STATES = ("open", "done", "dismissed")
30
+ STILL, RESOLVED, UNKNOWN = "still_on_pod", "looks_resolved", "unknown"
31
+
32
+ # what a person does when the clean-up's own sentence ("<why>: <what to do>") does not say
33
+ TODO = {
34
+ "ap_invoice": "Cancel it on Payables > Invoices > Manage Invoices (Actions > Cancel Invoice).",
35
+ "po_requisition": "Cancel it on Purchasing > Manage Requisitions.",
36
+ "po_order": "Open it on Purchasing > Manage Orders, then cancel it (withdraw it first when it is pending approval).",
37
+ "po_receipt": "Correct or return the receipt on Receiving > Manage Receipts, then cancel or close the order.",
38
+ "gl_journal": "Delete it on General Accounting > Journals > Manage Journals when it is unposted; reverse it when it is posted.",
39
+ "ar_transaction": "Credit it on Receivables > Billing > Manage Transactions (Actions > Credit Transaction).",
40
+ "ar_receipt": "Reverse it on Receivables > Receipts > Manage Receipts (Actions > Reverse Receipt).",
41
+ }
42
+ # a document the clean-up reports as done that nevertheless stays on the pod: a posted journal the run did not reverse (a cancelled
43
+ # invoice is the clean-up working, nothing for a person to do)
44
+ KEPT = {
45
+ "gl_journal": ("it is posted, and Fusion never deletes a posted journal (its debit and credit are on one account, balances unchanged)",
46
+ "Reverse it on General Accounting > Journals > Manage Journals (Actions > Reverse) if it should not stay, then mark this done."),
47
+ }
48
+
49
+
50
+ def _kept(kind: str, done: str) -> bool:
51
+ d = done.lower()
52
+ return kind == "gl_journal" and "posted (" in d and "revers" not in d
53
+
54
+
55
+ def _split(kind: str, why: str) -> tuple[str, str]:
56
+ """The clean-up writes "<why>: <what to do>" where a person has to act; anything else gets the kind's usual action."""
57
+ head, sep, tail = why.partition(": ")
58
+ if sep and tail.strip():
59
+ return head.strip()[:400], (tail.strip()[:1].upper() + tail.strip()[1:])[:600]
60
+ return why.strip()[:400], TODO.get(kind, "Clean it up on the pod by hand.")
61
+
62
+
63
+ def _first_seen(run_dir: Path) -> dict[tuple[str, str], str]:
64
+ """(kind, number) -> the ts of the first ledger line, i.e. when the test registered it."""
65
+ out: dict[tuple[str, str], str] = {}
66
+ f = Path(run_dir) / cleanup.LEDGER
67
+ if f.exists():
68
+ for line in f.read_text(encoding="utf-8", errors="replace").splitlines():
69
+ try:
70
+ rec = json.loads(line)
71
+ except ValueError:
72
+ continue
73
+ key = (str(rec.get("kind") or "ap_invoice"), str(rec.get("number") or ""))
74
+ if key[1] and rec.get("ts"):
75
+ out.setdefault(key, str(rec["ts"]))
76
+ return out
77
+
78
+
79
+ def collect(run_dir: Path) -> list[dict]:
80
+ """Every document of this run that stays on the pod, from the run folder's own files."""
81
+ entries = cleanup.ledger_entries(run_dir)
82
+ swept = cleanup.result(run_dir) or {}
83
+ seen = _first_seen(run_dir)
84
+ found: dict[tuple[str, str], dict] = {}
85
+ for e in entries.values():
86
+ kind = e.get("kind") or "ap_invoice"
87
+ if e.get("cleaned"):
88
+ if _kept(kind, str(e["cleaned"])):
89
+ why, todo = KEPT[kind]
90
+ found[(kind, e["number"])] = {"kind": kind, "reference": e["number"], "scenario": e.get("test"), "why": why, "todo": todo}
91
+ else:
92
+ why, todo = _split(kind, str(e.get("left") or "not cleaned up yet: check it on the pod and clean it up by hand"))
93
+ found[(kind, e["number"])] = {"kind": kind, "reference": e["number"], "scenario": e.get("test"), "why": why, "todo": todo}
94
+ for x in swept.get("left") or []: # the sweep's own reason is newer than the fixture's
95
+ kind, number = x.get("kind") or "ap_invoice", str(x.get("number") or "")
96
+ if number:
97
+ why, todo = _split(kind, str(x.get("why") or "not cleaned up"))
98
+ found[(kind, number)] = {"kind": kind, "reference": number, "scenario": x.get("test") or (entries.get(number) or {}).get("test"),
99
+ "why": why, "todo": todo}
100
+ out = []
101
+ for (kind, number), r in found.items():
102
+ if kind in KINDS:
103
+ out.append({**r, "created_at": seen.get((kind, number)) or swept.get("at") or now_iso()})
104
+ return out
105
+
106
+
107
+ def record(svc, run_id: str) -> int:
108
+ """Enter this run's left documents in the ledger; returns how many are new. Never changes a row that is already there
109
+ (a person's decision stays), and does nothing for a run on the practice pod."""
110
+ pod = svc.fusion_pod_id(run_id)
111
+ if pod is None:
112
+ return 0
113
+ new = 0
114
+ for r in collect(svc.run_dir(run_id)):
115
+ ref = r["reference"][:200]
116
+ if svc.db.one("SELECT 1 AS x FROM left_on_pod WHERE pod_id=? AND run_id=? AND kind=? AND reference=?", (pod, run_id, r["kind"], ref)):
117
+ continue
118
+ svc.db.insert_once("left_on_pod", {"pod_id": pod, "run_id": run_id, "scenario": (r["scenario"] or "")[:300] or None, "kind": r["kind"],
119
+ "reference": ref, "why": r["why"], "todo": r["todo"], "created_at": r["created_at"],
120
+ "recorded_at": now_iso()}, ("pod_id", "run_id", "kind", "reference"))
121
+ new += 1
122
+ if new:
123
+ svc.audit.append("left_on_pod.recorded", actor="system", run_id=run_id, summary=f"{new} test document(s) left on pod {pod} for a person")
124
+ return new
125
+
126
+
127
+ def backfill(svc) -> dict:
128
+ """Record the runs that finished before the ledger existed (or whose clean-up was never recorded): every run on a Fusion
129
+ pod that has a ledger file. Safe to repeat."""
130
+ runs = added = 0
131
+ for r in svc.db.q("SELECT run_id FROM runs WHERE pod_id IS NOT NULL ORDER BY created_at"):
132
+ if not (svc.cfg.runs_dir / r["run_id"] / cleanup.LEDGER).exists():
133
+ continue
134
+ runs += 1
135
+ try:
136
+ added += record(svc, r["run_id"])
137
+ except Exception: # noqa: BLE001
138
+ log.exception("left-on-pod backfill of run %s failed", r["run_id"])
139
+ return {"runs": runs, "added": added}
140
+
141
+
142
+ def backfill_once(svc) -> None:
143
+ """At start-up: the backfill, once per database (a later start finds the flag; the CLI runs it again on request)."""
144
+ if svc.db.kv_get("left_on_pod_backfilled"):
145
+ return
146
+ out = backfill(svc)
147
+ svc.db.kv_set("left_on_pod_backfilled", {"at": now_iso(), **out})
148
+ if out["added"]:
149
+ log.info("left-on-pod backfill: %d document(s) from %d run(s)", out["added"], out["runs"])
150
+
151
+
152
+ # ------------------------------------------------------------------ the people's side
153
+ class LeftError(Exception):
154
+ def __init__(self, code: str, msg: str, status: int):
155
+ super().__init__(msg)
156
+ self.code, self.status = code, status
157
+
158
+
159
+ def get(svc, row_id: int) -> dict:
160
+ row = svc.db.one("SELECT * FROM left_on_pod WHERE id=?", (row_id,))
161
+ if not row:
162
+ raise LeftError("NOT_FOUND", f"left document {row_id} not found", 404)
163
+ return row
164
+
165
+
166
+ def decide(svc, row_id: int, decision: str, user: str, note: str | None = None) -> dict:
167
+ """Mark a left document done (a person undid it, or nothing is needed) or dismissed (not worth doing), or open it again;
168
+ audited."""
169
+ row = get(svc, row_id)
170
+ st = {"done": "done", "dismiss": "dismissed", "reopen": "open"}[decision]
171
+ if decision == "reopen" and row["status"] == "open":
172
+ raise LeftError("ALREADY_OPEN", "this document is open already", 409)
173
+ if decision != "reopen" and row["status"] != "open":
174
+ raise LeftError("ALREADY_DECIDED", f"this document is {row['status']}: open it again first", 409)
175
+ fields = {"status": st, "decided_by": None if st == "open" else user, "decided_at": None if st == "open" else now_iso(),
176
+ "note": (note or "").strip()[:1000] or None}
177
+ svc.db.update("left_on_pod", "id", row_id, **fields)
178
+ svc.audit.append(f"left_on_pod.{st if st != 'open' else 'reopened'}", actor=user, run_id=row["run_id"],
179
+ summary=f"{row['kind']} {row['reference']} on pod {row['pod_id']}",
180
+ payload={"id": row_id, "pod": row["pod_id"], "kind": row["kind"], "reference": row["reference"], "note": fields["note"]})
181
+ return get(svc, row_id)
182
+
183
+
184
+ def open_count(db, pod_id: int) -> int:
185
+ return db.one("SELECT COUNT(*) n FROM left_on_pod WHERE pod_id=? AND status='open'", (pod_id,))["n"]
186
+
187
+
188
+ # ------------------------------------------------------------------ read-only look at the pod
189
+ def _found(state: str, st: str, done: tuple[str, ...]) -> tuple[str, str]:
190
+ return (RESOLVED, f"its status is {st}") if st in done else (STILL, f"it is on the pod{f', {state} {st}' if st else ''}")
191
+
192
+
193
+ def _check(svc, base_url: str, auth, row: dict) -> tuple[str, str]:
194
+ """One kind's look-up. Every request is a GET: cleanup._first and the calls below never pass another method."""
195
+ kind, tag, run_id = row["kind"], _q(row["reference"]), row["run_id"]
196
+ gone = "it is not on the pod any more"
197
+
198
+ def look(resource: str, *queries: str):
199
+ return _first(svc, base_url, auth, run_id, resource, *queries)
200
+
201
+ if kind == "ar_transaction":
202
+ t = look("receivablesInvoices", f"TransactionNumber='{tag}'", f"Comments LIKE '{tag}%'", f"InternalNotes LIKE '{tag}%'")
203
+ if not t:
204
+ return RESOLVED, gone
205
+ st = _status(next((t[k] for k in ("InvoiceStatus", "TransactionStatus", "Status", "StatusMeaning") if t.get(k) not in (None, "")), ""))
206
+ return (RESOLVED, f"its status is {st}") if "credit" in st or "cancel" in st else (STILL, f"it is on the pod{f', status {st}' if st else ''}")
207
+ if kind == "ar_receipt":
208
+ r = look("standardReceipts", f"ReceiptNumber='{tag}'")
209
+ if not r:
210
+ return RESOLVED, gone
211
+ st = _status(next((r[k] for k in ("State", "StatusMeaning", "Status", "ReceiptStatus") if r.get(k)), ""))
212
+ return (RESOLVED, f"its state is {st}") if "revers" in st else (STILL, f"it is on the pod{f', state {st}' if st else ''}")
213
+ if kind == "po_order":
214
+ o = look("purchaseOrders", f"OrderNumber='{tag}'", f"Description LIKE '{tag}%'") or look("draftPurchaseOrders", f"OrderNumber='{tag}'", f"Description LIKE '{tag}%'")
215
+ if not o:
216
+ return RESOLVED, gone
217
+ return _found("status", _status(o.get("Status") or o.get("StatusCode")), ("canceled",))
218
+ if kind == "po_requisition":
219
+ r = look("purchaseRequisitions", f"Requisition='{tag}'", f"Description LIKE '{tag}%'")
220
+ if not r:
221
+ return RESOLVED, gone
222
+ return _found("status", _status(r.get("DocumentStatus") or r.get("DocumentStatusCode")), ("canceled", "withdrawn", "rejected"))
223
+ if kind == "gl_journal":
224
+ r = svc.egress.fusion_request(base_url, "GET", f"{cleanup.API}/journalBatches", auth=auth, run_id=run_id,
225
+ params={"q": f"BatchName LIKE '%{tag}%'", "onlyData": "true", "limit": "10"})
226
+ if r.status_code == 400: # a pod that refuses the name search: the batch itself
227
+ b = look("journalBatches", f"BatchName='{tag}'")
228
+ found = [b] if b else []
229
+ elif r.status_code == 200:
230
+ found = r.json().get("items") or []
231
+ else:
232
+ return UNKNOWN, f"the pod did not answer the look-up (HTTP {r.status_code})"
233
+ if not found:
234
+ return RESOLVED, gone
235
+ posted = any(str(b.get("Status") or "").strip().upper() == "P" or _status(b.get("StatusMeaning")) == "posted" for b in found)
236
+ return STILL, "it is on the pod, posted" if posted else "it is on the pod, not posted"
237
+ if kind == "ap_invoice":
238
+ inv = look("invoices", f"InvoiceNumber='{tag}'")
239
+ if not inv:
240
+ return RESOLVED, gone
241
+ return STILL, "it is on the pod, cancelled" if inv.get("CanceledFlag") else "it is on the pod, not cancelled"
242
+ if kind == "po_receipt":
243
+ answered = False
244
+ for resource in cleanup.RECEIPT_RESOURCES:
245
+ for q in (f"PackingSlip='{tag}'", f"Comments LIKE '{tag}%'", f"ShipmentNumber='{tag}'", f"ReceiptNumber='{tag}'"):
246
+ r = svc.egress.fusion_request(base_url, "GET", f"{cleanup.API}/{resource}", auth=auth, run_id=run_id,
247
+ params={"q": q, "onlyData": "true", "limit": "5"})
248
+ if r.status_code in (400, 404):
249
+ continue
250
+ if r.status_code != 200:
251
+ return UNKNOWN, f"the pod did not answer the look-up (HTTP {r.status_code})"
252
+ answered = True
253
+ if r.json().get("items"):
254
+ return STILL, "a receipt with this packing slip is on the pod"
255
+ return (RESOLVED, "no receipt with this packing slip is on the pod") if answered else (UNKNOWN, "this pod's REST answers none of the receipt queries")
256
+ return UNKNOWN, "the co-worker cannot look this kind up"
257
+
258
+
259
+ def recheck(svc, row_id: int) -> dict:
260
+ """Ask the pod again, read-only (GET through the egress gate), and keep the answer on the row. Nothing on the pod changes."""
261
+ from .pods import PodError, PodRegistry, assisted
262
+ row = get(svc, row_id)
263
+ reg = PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit)
264
+ try:
265
+ pod = reg.get(row["pod_id"])
266
+ auth = reg.fusion_auth(row["pod_id"])
267
+ except PodError:
268
+ state, detail = UNKNOWN, "the pod is no longer set up"
269
+ else:
270
+ if not auth:
271
+ state, detail = UNKNOWN, ("the pod uses assisted sign-in, so there is no password to look it up through Fusion REST"
272
+ if assisted(pod) else "the pod's test user is no longer set up")
273
+ else:
274
+ try:
275
+ state, detail = _check(svc, pod["base_url"], auth, row)
276
+ except (KillSwitchEngaged, EgressDenied):
277
+ raise
278
+ except Exception as e: # noqa: BLE001
279
+ name = type(e).__name__
280
+ state, detail = UNKNOWN, (str(e)[:300] if name == "RuntimeError" # our own sentences from the look-ups
281
+ else "Fusion could not be reached" if name in ("ServiceTimeout", "ServiceUnreachable")
282
+ else "an unexpected error (details in the server log)")
283
+ if name not in ("RuntimeError", "ServiceTimeout", "ServiceUnreachable"):
284
+ log.warning("re-check of left document %s failed: %s: %s", row_id, name, e)
285
+ svc.db.update("left_on_pod", "id", row_id, check_state=state, check_detail=detail, checked_at=now_iso())
286
+ return get(svc, row_id)
coworker/platform/links.py CHANGED
@@ -1,38 +1,40 @@
1
- """Download links that work without an Astra login, for the e-mails Oracle Fusion sends: each one is signed for one run
2
- and one file, read-only, and expires (7 days). The signing key is made once and kept in the vault (vault LINK_SIGNING_KEY,
3
- or FPT_SECRET_LINK_SIGNING_KEY); changing it ends every link already sent."""
4
- from __future__ import annotations
5
-
6
- import hashlib
7
- import hmac
8
- import secrets
9
- import time
10
-
11
- KEY = "LINK_SIGNING_KEY"
12
- DAYS = 7
13
-
14
-
15
- def _key(svc) -> bytes:
16
- k = svc.vault.get(KEY)
17
- if not k:
18
- if not hasattr(svc.vault, "set"):
19
- raise RuntimeError("the vault cannot keep a link signing key; set FPT_SECRET_LINK_SIGNING_KEY")
20
- k = secrets.token_urlsafe(32)
21
- svc.vault.set(KEY, k)
22
- return k.encode()
23
-
24
-
25
- def _mac(svc, run_id: str, what: str, exp: int) -> str:
26
- return hmac.new(_key(svc), f"{run_id}|{what}|{exp}".encode(), hashlib.sha256).hexdigest()[:40]
27
-
28
-
29
- def sign(svc, run_id: str, what: str, days: int = DAYS, now: float | None = None) -> str:
30
- """The query string (exp=...&sig=...) that opens `what` of `run_id` until it expires."""
31
- exp = int((now or time.time()) + days * 86400)
32
- return f"exp={exp}&sig={_mac(svc, run_id, what, exp)}"
33
-
34
-
35
- def verify(svc, run_id: str, what: str, exp: int, sig: str, now: float | None = None) -> bool:
36
- if exp < (now or time.time()):
37
- return False
38
- return hmac.compare_digest(_mac(svc, run_id, what, exp), str(sig or ""))
 
 
 
1
+ """Download links that work without an Astra login, for the e-mails Oracle Fusion sends: each one is signed for one run
2
+ and one file, read-only, and expires (7 days). The signing key is made once and kept in the vault (vault LINK_SIGNING_KEY,
3
+ or FPT_SECRET_LINK_SIGNING_KEY); changing it ends every link already sent."""
4
+ from __future__ import annotations
5
+
6
+ import hashlib
7
+ import hmac
8
+ import secrets
9
+ import time
10
+
11
+ from .users import consteq
12
+
13
+ KEY = "LINK_SIGNING_KEY"
14
+ DAYS = 7
15
+
16
+
17
+ def _key(svc) -> bytes:
18
+ k = svc.vault.get(KEY)
19
+ if not k:
20
+ if not hasattr(svc.vault, "set"):
21
+ raise RuntimeError("the vault cannot keep a link signing key; set FPT_SECRET_LINK_SIGNING_KEY")
22
+ k = secrets.token_urlsafe(32)
23
+ svc.vault.set(KEY, k)
24
+ return k.encode()
25
+
26
+
27
+ def _mac(svc, run_id: str, what: str, exp: int) -> str:
28
+ return hmac.new(_key(svc), f"{run_id}|{what}|{exp}".encode(), hashlib.sha256).hexdigest()[:40]
29
+
30
+
31
+ def sign(svc, run_id: str, what: str, days: int = DAYS, now: float | None = None) -> str:
32
+ """The query string (exp=...&sig=...) that opens `what` of `run_id` until it expires."""
33
+ exp = int((now or time.time()) + days * 86400)
34
+ return f"exp={exp}&sig={_mac(svc, run_id, what, exp)}"
35
+
36
+
37
+ def verify(svc, run_id: str, what: str, exp: int, sig: str, now: float | None = None) -> bool:
38
+ if exp < (now or time.time()):
39
+ return False
40
+ return consteq(_mac(svc, run_id, what, exp), str(sig or ""))
coworker/platform/migrations/030_left_on_pod.sql ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- 030: test documents a run left on a Fusion pod that only a person can undo (platform/left_on_pod.py): one row per
2
+ -- (pod, run, kind, reference), filled at the end of each run's clean-up and from the run folders' own files (backfill).
3
+ -- Only the document's number or tag and our own sentences are kept here, never the pod's records. The check_* columns
4
+ -- hold the last read-only look at the pod (GET only): still_on_pod | looks_resolved | unknown.
5
+ CREATE TABLE IF NOT EXISTS left_on_pod (
6
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
7
+ pod_id INTEGER NOT NULL,
8
+ run_id TEXT NOT NULL,
9
+ scenario TEXT, -- the test that created it
10
+ kind TEXT NOT NULL, -- ap_invoice | po_requisition | po_order | po_receipt | gl_journal | ar_transaction | ar_receipt
11
+ reference TEXT NOT NULL, -- the number or FPT- tag the test registered
12
+ why TEXT NOT NULL, -- why it was left
13
+ todo TEXT NOT NULL, -- what a person should do
14
+ created_at TEXT NOT NULL, -- when the test created it
15
+ recorded_at TEXT NOT NULL, -- when it was entered here
16
+ status TEXT NOT NULL DEFAULT 'open', -- open | done | dismissed
17
+ decided_by TEXT,
18
+ decided_at TEXT,
19
+ note TEXT,
20
+ check_state TEXT,
21
+ check_detail TEXT,
22
+ checked_at TEXT
23
+ );
24
+ CREATE UNIQUE INDEX IF NOT EXISTS left_on_pod_once ON left_on_pod (pod_id, run_id, kind, reference);
25
+ CREATE INDEX IF NOT EXISTS left_on_pod_pod_status ON left_on_pod (pod_id, status);
coworker/platform/pods.py CHANGED
@@ -178,7 +178,8 @@ class PodRegistry:
178
  "run_areas": self.run_areas({"kind": r["kind"], "discovery": disc}),
179
  "screens": _json(r.get("screens"), None),
180
  "last_check_ok": None if r["last_check_ok"] is None else bool(r["last_check_ok"]),
181
- "credentials": creds, "runnable": runnable, "not_runnable_reason": why}
 
182
 
183
  def list(self) -> list[dict]:
184
  return [self._row(r) for r in self.db.q("SELECT * FROM pods ORDER BY is_default DESC, name")]
 
178
  "run_areas": self.run_areas({"kind": r["kind"], "discovery": disc}),
179
  "screens": _json(r.get("screens"), None),
180
  "last_check_ok": None if r["last_check_ok"] is None else bool(r["last_check_ok"]),
181
+ "credentials": creds, "left_open": self.db.one("SELECT COUNT(*) n FROM left_on_pod WHERE pod_id=? AND status='open'", (r["id"],))["n"],
182
+ "runnable": runnable, "not_runnable_reason": why}
183
 
184
  def list(self) -> list[dict]:
185
  return [self._row(r) for r in self.db.q("SELECT * FROM pods ORDER BY is_default DESC, name")]
coworker/platform/users.py CHANGED
@@ -4,6 +4,8 @@ FPT_BOOTSTRAP_ADMIN_USER / FPT_BOOTSTRAP_ADMIN_PASSWORD at first start. OIDC is
4
  from __future__ import annotations
5
 
6
  import hashlib
 
 
7
  import os
8
  import secrets
9
  import threading
@@ -16,6 +18,8 @@ from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatc
16
 
17
  from .rundb import RunDB, now_iso
18
 
 
 
19
  ROLES = ("viewer", "consultant", "qa_approver", "admin")
20
  # Permission -> roles allowed. Enforced in the API (coworker/api/auth.py require()).
21
  PERMISSIONS: dict[str, tuple[str, ...]] = {
@@ -26,6 +30,7 @@ PERMISSIONS: dict[str, tuple[str, ...]] = {
26
  "run.signoff": ("qa_approver", "admin"),
27
  "gate.approve_cases": ("consultant", "admin"),
28
  "heal.decide": ("consultant", "admin"),
 
29
  "drafts.decide": ("consultant", "admin"),
30
  "gate.human_review": ("qa_approver", "admin"),
31
  "gate.sign_in": ("consultant", "qa_approver", "admin"), # assisted sign-in: sign in to the pod for a run
@@ -65,6 +70,14 @@ def sha256(s: str) -> str:
65
  return hashlib.sha256(s.encode()).hexdigest()
66
 
67
 
 
 
 
 
 
 
 
 
68
  class AuthError(PermissionError):
69
  def __init__(self, msg: str, code: str = "UNAUTHENTICATED"):
70
  super().__init__(msg)
@@ -78,8 +91,12 @@ class RateLimited(AuthError):
78
 
79
 
80
  class UserStore:
81
- def __init__(self, db: RunDB, session_ttl_hours: int = 12, max_attempts: int = 5, window_s: int = 300):
 
82
  self.db, self.ttl, self.max_attempts, self.window_s = db, session_ttl_hours, max_attempts, window_s
 
 
 
83
 
84
  # ------------------------------------------------------------ users
85
  @staticmethod
@@ -163,9 +180,13 @@ class UserStore:
163
  new = os.getenv("FPT_ADMIN_PASSWORD_RESET")
164
  if not new:
165
  return None
166
- import hashlib
167
- mark = hashlib.sha256(("fpt-admin-reset|" + new).encode()).hexdigest()
168
- if self.db.kv_get("admin_password_reset_applied") == mark:
 
 
 
 
169
  return None
170
  name = os.getenv("FPT_BOOTSTRAP_ADMIN_USER") or "admin"
171
  u = self.by_name(name)
@@ -173,19 +194,53 @@ class UserStore:
173
  self.update(u["id"], role="admin", disabled=False, password=new)
174
  else:
175
  self.create(name, new, "admin", created_by="admin-reset-env")
176
- self.db.kv_set("admin_password_reset_applied", mark)
 
177
  return name
178
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  # ------------------------------------------------------------ login + rate limit
180
- def _check_rate(self, key: str) -> None:
 
 
 
181
  since = time.time() - self.window_s
182
  rows = self.db.q("SELECT ts FROM login_attempts WHERE key=? AND ok=0 AND ts>? ORDER BY ts", (key, since))
183
- if len(rows) >= self.max_attempts:
184
  raise RateLimited(int(rows[0]["ts"] + self.window_s - time.time()) + 1)
185
 
186
- def authenticate(self, username: str, password: str, client: str = "-") -> dict:
187
- key = f"{(username or '').lower()}|{client}"
 
 
 
 
 
188
  self._check_rate(key)
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  u = self.by_name(username or "")
190
  ok = False
191
  if u and not u["disabled"]:
@@ -195,7 +250,7 @@ class UserStore:
195
  ok = False
196
  else:
197
  _ph.hash("timing-equaliser-not-a-password") # constant-ish time for unknown users
198
- self.db.insert("login_attempts", {"key": key, "ts": time.time(), "ok": int(ok)})
199
  if not ok:
200
  raise AuthError("invalid username or password", "BAD_CREDENTIALS")
201
  if _ph.check_needs_rehash(u["password_hash"]):
 
4
  from __future__ import annotations
5
 
6
  import hashlib
7
+ import hmac
8
+ import logging
9
  import os
10
  import secrets
11
  import threading
 
18
 
19
  from .rundb import RunDB, now_iso
20
 
21
+ log = logging.getLogger("fpt.users")
22
+
23
  ROLES = ("viewer", "consultant", "qa_approver", "admin")
24
  # Permission -> roles allowed. Enforced in the API (coworker/api/auth.py require()).
25
  PERMISSIONS: dict[str, tuple[str, ...]] = {
 
30
  "run.signoff": ("qa_approver", "admin"),
31
  "gate.approve_cases": ("consultant", "admin"),
32
  "heal.decide": ("consultant", "admin"),
33
+ "left.decide": ("consultant", "qa_approver", "admin"), # mark a test document left on a pod done or dismissed (like a run note)
34
  "drafts.decide": ("consultant", "admin"),
35
  "gate.human_review": ("qa_approver", "admin"),
36
  "gate.sign_in": ("consultant", "qa_approver", "admin"), # assisted sign-in: sign in to the pod for a run
 
70
  return hashlib.sha256(s.encode()).hexdigest()
71
 
72
 
73
+ def consteq(a: str | bytes | None, b: str | bytes | None) -> bool:
74
+ """Constant-time equality for secrets. Unlike hmac.compare_digest on str, a non-ASCII value (a header can carry one)
75
+ is just "not equal" instead of a TypeError that ends as a 500."""
76
+ ab = a.encode("utf-8", "surrogatepass") if isinstance(a, str) else (a or b"")
77
+ bb = b.encode("utf-8", "surrogatepass") if isinstance(b, str) else (b or b"")
78
+ return hmac.compare_digest(ab, bb)
79
+
80
+
81
  class AuthError(PermissionError):
82
  def __init__(self, msg: str, code: str = "UNAUTHENTICATED"):
83
  super().__init__(msg)
 
91
 
92
 
93
  class UserStore:
94
+ def __init__(self, db: RunDB, session_ttl_hours: int = 12, max_attempts: int = 5, window_s: int = 300,
95
+ max_per_ip: int = 0, max_per_user: int = 0):
96
  self.db, self.ttl, self.max_attempts, self.window_s = db, session_ttl_hours, max_attempts, window_s
97
+ # wider nets next to the per-user-and-visitor limit (0 = off): one visitor trying many names, and many visitors
98
+ # trying one name. Only counted failures; a success never adds to them.
99
+ self.max_per_ip, self.max_per_user = max_per_ip, max_per_user
100
 
101
  # ------------------------------------------------------------ users
102
  @staticmethod
 
180
  new = os.getenv("FPT_ADMIN_PASSWORD_RESET")
181
  if not new:
182
  return None
183
+ mark = self.db.kv_get("admin_password_reset_applied")
184
+ if self._reset_applied(mark, new):
185
+ return None
186
+ try:
187
+ self.validate_password(new)
188
+ except ValueError as e: # a bad secret must not stop the server from starting (nor lock anyone out): say so and carry on
189
+ log.error("FPT_ADMIN_PASSWORD_RESET was not applied: %s", e)
190
  return None
191
  name = os.getenv("FPT_BOOTSTRAP_ADMIN_USER") or "admin"
192
  u = self.by_name(name)
 
194
  self.update(u["id"], role="admin", disabled=False, password=new)
195
  else:
196
  self.create(name, new, "admin", created_by="admin-reset-env")
197
+ # kept as an argon2 hash, not a fast one: the saved state must not let anyone test guesses of the secret cheaply
198
+ self.db.kv_set("admin_password_reset_applied", _ph.hash("fpt-admin-reset|" + new))
199
  return name
200
 
201
+ @staticmethod
202
+ def _reset_applied(mark, new: str) -> bool:
203
+ """Was this value already applied? Marks written by earlier versions are a plain SHA-256 and still count."""
204
+ if not mark or not isinstance(mark, str):
205
+ return False
206
+ if mark.startswith("$argon2"):
207
+ try:
208
+ return _ph.verify(mark, "fpt-admin-reset|" + new)
209
+ except (VerifyMismatchError, VerificationError, InvalidHashError):
210
+ return False
211
+ return consteq(mark, hashlib.sha256(("fpt-admin-reset|" + new).encode()).hexdigest())
212
+
213
  # ------------------------------------------------------------ login + rate limit
214
+ def _check_rate(self, key: str, limit: int | None = None) -> None:
215
+ limit = self.max_attempts if limit is None else limit
216
+ if limit <= 0:
217
+ return
218
  since = time.time() - self.window_s
219
  rows = self.db.q("SELECT ts FROM login_attempts WHERE key=? AND ok=0 AND ts>? ORDER BY ts", (key, since))
220
+ if len(rows) >= limit:
221
  raise RateLimited(int(rows[0]["ts"] + self.window_s - time.time()) + 1)
222
 
223
+ def check_login(self, username: str, client: str) -> str:
224
+ """Refuse (RateLimited) a sign-in from a visitor or for a name that has failed too often lately, before any password
225
+ is hashed. Returns the per-user-and-visitor key."""
226
+ name = (username or "").lower()
227
+ self._check_rate(f"#ip|{client}", self.max_per_ip)
228
+ self._check_rate(f"#user|{name}", self.max_per_user)
229
+ key = f"{name}|{client}"
230
  self._check_rate(key)
231
+ return key
232
+
233
+ def note_login(self, username: str, client: str, ok: bool) -> None:
234
+ name = (username or "").lower()
235
+ self.note_attempt(f"{name}|{client}", ok)
236
+ if not ok:
237
+ if self.max_per_ip > 0:
238
+ self.note_attempt(f"#ip|{client}", False)
239
+ if self.max_per_user > 0:
240
+ self.note_attempt(f"#user|{name}", False)
241
+
242
+ def authenticate(self, username: str, password: str, client: str = "-") -> dict:
243
+ self.check_login(username, client)
244
  u = self.by_name(username or "")
245
  ok = False
246
  if u and not u["disabled"]:
 
250
  ok = False
251
  else:
252
  _ph.hash("timing-equaliser-not-a-password") # constant-ish time for unknown users
253
+ self.note_login(username, client, ok)
254
  if not ok:
255
  raise AuthError("invalid username or password", "BAD_CREDENTIALS")
256
  if _ph.check_needs_rehash(u["password_hash"]):
coworker/platform/vault.py CHANGED
@@ -1,113 +1,118 @@
1
- """Secrets vault. FileVault = var/secrets/vault.json (never versioned) + FPT_SECRET_<NAME> env overrides.
2
- Every secret value is registered as a redaction canary so it can never leave through egress or enter state.
3
- HashiCorpVault is a stub (not installed in this pilot)."""
4
- from __future__ import annotations
5
-
6
- import json
7
- import os
8
- from dataclasses import dataclass
9
- from pathlib import Path
10
- from typing import Protocol
11
-
12
-
13
- class NotConfigured(RuntimeError):
14
- pass
15
-
16
-
17
- @dataclass(frozen=True)
18
- class Credential:
19
- module: str
20
- persona: str
21
- username: str
22
- password: str
23
-
24
- def __repr__(self) -> str: # never print the secret
25
- return f"Credential(module={self.module!r}, persona={self.persona!r}, username={self.username!r}, password='***')"
26
-
27
- __str__ = __repr__
28
-
29
-
30
- class SecretsVault(Protocol):
31
- def get(self, name: str) -> str | None: ...
32
- def test_credential(self, module: str, persona: str) -> Credential | None: ...
33
- def secret_values(self) -> list[str]: ...
34
-
35
-
36
- class FileVault:
37
- ENV_PREFIX = "FPT_SECRET_"
38
-
39
- def __init__(self, path: Path):
40
- self.path = Path(path)
41
-
42
- def _load(self) -> dict:
43
- if not self.path.exists():
44
- return {}
45
- return json.loads(self.path.read_text(encoding="utf-8") or "{}")
46
-
47
- def _save(self, data: dict) -> None:
48
- self.path.parent.mkdir(parents=True, exist_ok=True)
49
- self.path.write_text(json.dumps(data, indent=1), encoding="utf-8")
50
- try:
51
- os.chmod(self.path, 0o600)
52
- except OSError:
53
- pass
54
-
55
- def ensure(self) -> None:
56
- data = self._load()
57
- if "EVIDENCE_KEY" not in data:
58
- from cryptography.fernet import Fernet
59
- data["EVIDENCE_KEY"] = Fernet.generate_key().decode()
60
- self._save(data)
61
-
62
- def get(self, name: str) -> str | None:
63
- env = os.getenv(self.ENV_PREFIX + name.upper().replace(".", "_"))
64
- if env:
65
- return env
66
- v = self._load().get(name)
67
- return str(v) if v is not None else None
68
-
69
- def set(self, name: str, value: str) -> None:
70
- data = self._load()
71
- data[name] = value
72
- self._save(data)
73
-
74
- def test_credential(self, module: str, persona: str) -> Credential | None:
75
- raw = self.get(f"creds.{module.lower()}.{persona}")
76
- if not raw:
77
- return None
78
- d = json.loads(raw) if raw.strip().startswith("{") else {"username": persona, "password": raw}
79
- return Credential(module, persona, d.get("username", persona), d.get("password", ""))
80
-
81
- def executor_env(self, module: str) -> dict[str, str]:
82
- """FPT_CRED_<PERSONA>_USER/PASS for one module; only the executor subprocess env receives these."""
83
- out = {}
84
- prefix = f"creds.{module.lower()}."
85
- for k in self._load():
86
- if k.startswith(prefix):
87
- c = self.test_credential(module, k[len(prefix):])
88
- if c:
89
- out[f"FPT_CRED_{c.persona.upper()}_USER"] = c.username
90
- out[f"FPT_CRED_{c.persona.upper()}_PASS"] = c.password
91
- return out
92
-
93
- def secret_values(self) -> list[str]:
94
- vals = [str(v) for v in self._load().values() if v]
95
- vals += [v for k, v in os.environ.items() if k.startswith(self.ENV_PREFIX) and v]
96
- out = []
97
- for v in vals:
98
- if v.strip().startswith("{"):
99
- try:
100
- out += [str(x) for x in json.loads(v).values() if len(str(x)) >= 6]
101
- continue
102
- except ValueError:
103
- pass
104
- if len(v) >= 6:
105
- out.append(v)
106
- return sorted(set(out))
107
-
108
-
109
- class HashiCorpVault:
110
- """STUB: production target is HashiCorp Vault (KV v2). Not installed in this pilot."""
111
-
112
- def __init__(self, *_, **__):
113
- raise NotConfigured("HashiCorp Vault is not available in this pilot; use FileVault")
 
 
 
 
 
 
1
+ """Secrets vault. FileVault = var/secrets/vault.json (never versioned) + FPT_SECRET_<NAME> env overrides.
2
+ Every secret value is registered as a redaction canary so it can never leave through egress or enter state.
3
+ HashiCorpVault is a stub (not installed in this pilot)."""
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import os
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+ from typing import Protocol
11
+
12
+
13
+ class NotConfigured(RuntimeError):
14
+ pass
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Credential:
19
+ module: str
20
+ persona: str
21
+ username: str
22
+ password: str
23
+
24
+ def __repr__(self) -> str: # never print the secret
25
+ return f"Credential(module={self.module!r}, persona={self.persona!r}, username={self.username!r}, password='***')"
26
+
27
+ __str__ = __repr__
28
+
29
+
30
+ class SecretsVault(Protocol):
31
+ def get(self, name: str) -> str | None: ...
32
+ def test_credential(self, module: str, persona: str) -> Credential | None: ...
33
+ def secret_values(self) -> list[str]: ...
34
+
35
+
36
+ class FileVault:
37
+ ENV_PREFIX = "FPT_SECRET_"
38
+
39
+ def __init__(self, path: Path):
40
+ self.path = Path(path)
41
+
42
+ def _load(self) -> dict:
43
+ if not self.path.exists():
44
+ return {}
45
+ return json.loads(self.path.read_text(encoding="utf-8") or "{}")
46
+
47
+ def _save(self, data: dict) -> None:
48
+ self.path.parent.mkdir(parents=True, exist_ok=True)
49
+ # written whole to a file only this user can read (created that way, never world-readable even for a moment), then moved in
50
+ tmp = self.path.with_name(self.path.name + ".tmp")
51
+ fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
52
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
53
+ fh.write(json.dumps(data, indent=1))
54
+ os.replace(tmp, self.path)
55
+ try:
56
+ os.chmod(self.path, 0o600)
57
+ except OSError:
58
+ pass
59
+
60
+ def ensure(self) -> None:
61
+ data = self._load()
62
+ if "EVIDENCE_KEY" not in data:
63
+ from cryptography.fernet import Fernet
64
+ data["EVIDENCE_KEY"] = Fernet.generate_key().decode()
65
+ self._save(data)
66
+
67
+ def get(self, name: str) -> str | None:
68
+ env = os.getenv(self.ENV_PREFIX + name.upper().replace(".", "_"))
69
+ if env:
70
+ return env
71
+ v = self._load().get(name)
72
+ return str(v) if v is not None else None
73
+
74
+ def set(self, name: str, value: str) -> None:
75
+ data = self._load()
76
+ data[name] = value
77
+ self._save(data)
78
+
79
+ def test_credential(self, module: str, persona: str) -> Credential | None:
80
+ raw = self.get(f"creds.{module.lower()}.{persona}")
81
+ if not raw:
82
+ return None
83
+ d = json.loads(raw) if raw.strip().startswith("{") else {"username": persona, "password": raw}
84
+ return Credential(module, persona, d.get("username", persona), d.get("password", ""))
85
+
86
+ def executor_env(self, module: str) -> dict[str, str]:
87
+ """FPT_CRED_<PERSONA>_USER/PASS for one module; only the executor subprocess env receives these."""
88
+ out = {}
89
+ prefix = f"creds.{module.lower()}."
90
+ for k in self._load():
91
+ if k.startswith(prefix):
92
+ c = self.test_credential(module, k[len(prefix):])
93
+ if c:
94
+ out[f"FPT_CRED_{c.persona.upper()}_USER"] = c.username
95
+ out[f"FPT_CRED_{c.persona.upper()}_PASS"] = c.password
96
+ return out
97
+
98
+ def secret_values(self) -> list[str]:
99
+ vals = [str(v) for v in self._load().values() if v]
100
+ vals += [v for k, v in os.environ.items() if k.startswith(self.ENV_PREFIX) and v]
101
+ out = []
102
+ for v in vals:
103
+ if v.strip().startswith("{"):
104
+ try:
105
+ out += [str(x) for x in json.loads(v).values() if len(str(x)) >= 6]
106
+ continue
107
+ except ValueError:
108
+ pass
109
+ if len(v) >= 6:
110
+ out.append(v)
111
+ return sorted(set(out))
112
+
113
+
114
+ class HashiCorpVault:
115
+ """STUB: production target is HashiCorp Vault (KV v2). Not installed in this pilot."""
116
+
117
+ def __init__(self, *_, **__):
118
+ raise NotConfigured("HashiCorp Vault is not available in this pilot; use FileVault")
coworker/tests/test_left_on_pod.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The ledger of test documents left on a Fusion pod for a person (platform/left_on_pod.py, /api/left-on-pod): filled at the end
2
+ of a run's clean-up from the run folder, once per (pod, run, kind, reference), backfilled for earlier runs, decided by people who
3
+ may, and looked at again with GET requests only."""
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import unittest
8
+
9
+ import httpx
10
+
11
+ from coworker.api.runner import sweep_test_data
12
+ from coworker.platform import cleanup, left_on_pod
13
+ from coworker.tests.fakes import REST, FakePod, bearer, make_app
14
+
15
+ BASE = "https://acme-test.fa.ocs.oraclecloud.com"
16
+ HOST = "acme-test.fa.ocs.oraclecloud.com"
17
+ CLIENT_NAME = "Contoso Holdings Ltd" # a client's data the pod answers with: it must never reach the ledger
18
+
19
+
20
+ class Pod(FakePod):
21
+ """The fake pod plus the few Fusion resources the clean-up and the re-check read; every call to it is kept."""
22
+
23
+ def __init__(self):
24
+ super().__init__()
25
+ self.transactions: dict[str, dict] = {}
26
+ self.orders: dict[str, dict] = {}
27
+ self.calls: list[tuple[str, str]] = []
28
+
29
+ def handler(self, req: httpx.Request) -> httpx.Response:
30
+ if req.url.host == HOST:
31
+ self.calls.append((req.method, req.url.path))
32
+ if req.method == "GET":
33
+ q = req.url.params.get("q", "")
34
+ tag = q.split("'")[1] if "'" in q else ""
35
+ for resource, table in (("receivablesInvoices", self.transactions), ("purchaseOrders", self.orders)):
36
+ if req.url.path == f"{REST}/{resource}":
37
+ hit = table.get(tag)
38
+ return httpx.Response(200, json={"items": [hit] if hit else []})
39
+ if req.url.path.startswith(REST + "/"):
40
+ return httpx.Response(200, json={"items": []})
41
+ return super().handler(req)
42
+
43
+
44
+ def _app():
45
+ import coworker.tests.fakes as F
46
+ real = F.FakePod
47
+ F.FakePod = Pod
48
+ try:
49
+ return make_app()
50
+ finally:
51
+ F.FakePod = real
52
+
53
+
54
+ def _txn(number: str, status: str = "Complete") -> dict:
55
+ return {"TransactionNumber": number, "InvoiceStatus": status, "BillToCustomerName": CLIENT_NAME, "EnteredAmount": 1234.5}
56
+
57
+
58
+ class LeftOnPodCase(unittest.TestCase):
59
+ def setUp(self):
60
+ self.app, self.c, self.svc, self.pod = _app()
61
+ self.admin = bearer(self.c, "admin")
62
+ self.pod_id = self.c.post("/api/pods", json={"name": "Acme test pod", "kind": "fusion", "base_url": BASE, "environment": "test",
63
+ "modules": ["AR"]}, headers=self.admin).json()["id"]
64
+ self.c.post(f"/api/pods/{self.pod_id}/credentials", json={"module": "ALL", "username": "zz.ar", "password": "S3cret-pod-password!"},
65
+ headers=self.admin)
66
+ self.pod.calls.clear()
67
+
68
+ def make_run(self, rid, pod_id, *records):
69
+ self.svc.db.create_run({"run_id": rid, "created_by": "consultant", "trigger": "manual", "modules": ["AR"], "include_p2": 0,
70
+ "playwright_mode": "live", "inputs": {}, "status": "completed", "orchestrator": "langgraph", "pod_id": pod_id})
71
+ with (self.svc.run_dir(rid) / cleanup.LEDGER).open("a", encoding="utf-8") as fh:
72
+ for r in records:
73
+ fh.write(json.dumps({"ts": "2026-11-01T10:00:00Z", **r}) + "\n")
74
+ return rid
75
+
76
+ def left_run(self, rid="20261101-000000-aaaaaa"):
77
+ """A run with a completed transaction (left), a closed order (left by the fixture), a posted journal (the clean-up's own
78
+ words), a posted journal the run reversed, an unposted journal that was deleted and a cancelled invoice (not left: that is the clean-up working)."""
79
+ self.pod.transactions["FPT-T-1"] = _txn("FPT-T-1")
80
+ self.pod.orders["FPT-O-1"] = {"OrderNumber": "4001", "Status": "Closed"}
81
+ return self.make_run(rid, self.pod_id,
82
+ {"kind": "ar_transaction", "number": "FPT-T-1", "test": "Create and complete an invoice"},
83
+ {"kind": "po_order", "number": "FPT-O-1", "test": "Close an order",
84
+ "left": "purchase order 4001 is closed: reopen it on Manage Orders (Actions > Open) and cancel it if it should go"},
85
+ {"kind": "gl_journal", "number": "FPT-J-1", "test": "Post a journal"},
86
+ {"kind": "gl_journal", "number": "FPT-J-1", "cleaned": "FPT-J-1: posted (debit and credit on one account, balances unchanged)"},
87
+ {"kind": "gl_journal", "number": "FPT-J-3", "test": "Post and reverse a journal"},
88
+ {"kind": "gl_journal", "number": "FPT-J-3", "cleaned": "FPT-J-3: posted (reversed by the run, balances unchanged)"},
89
+ {"kind": "gl_journal", "number": "FPT-J-2", "test": "Draft a journal"},
90
+ {"kind": "gl_journal", "number": "FPT-J-2", "cleaned": "FPT-J-2: deleted by clean-up (unposted)"},
91
+ {"kind": "ap_invoice", "number": "FPT-I-1", "test": "Cancel an invoice"},
92
+ {"kind": "ap_invoice", "number": "FPT-I-1", "cleaned": "FPT-I-1: cancelled by clean-up"},
93
+ {"kind": "ap_invoice", "number": "FPT-I-2", "test": "Never saved"},
94
+ {"kind": "ap_invoice", "number": "FPT-I-2", "cleaned": "FPT-I-2: not saved, nothing to clean up"})
95
+
96
+ def rows(self, **q):
97
+ r = self.c.get("/api/left-on-pod", params=q, headers=bearer(self.c, "viewer"))
98
+ self.assertEqual(r.status_code, 200, r.text)
99
+ return r.json()
100
+
101
+
102
+ class TestFill(LeftOnPodCase):
103
+ def test_fills_from_the_run_at_the_end_of_its_clean_up(self):
104
+ rid = self.left_run()
105
+ sweep_test_data(self.svc, rid, "completed")
106
+ got = {(x["kind"], x["reference"]): x for x in self.rows()["items"]}
107
+ self.assertEqual(sorted(got), [("ar_transaction", "FPT-T-1"), ("gl_journal", "FPT-J-1"), ("po_order", "FPT-O-1")])
108
+ t = got[("ar_transaction", "FPT-T-1")]
109
+ self.assertEqual((t["pod_id"], t["pod_name"], t["run_id"], t["status"], t["scenario"]),
110
+ (self.pod_id, "Acme test pod", rid, "open", "Create and complete an invoice"))
111
+ self.assertIn("complete", t["why"])
112
+ self.assertIn("Credit Transaction", t["todo"])
113
+ self.assertEqual(t["created_at"], "2026-11-01T10:00:00Z")
114
+ o = got[("po_order", "FPT-O-1")] # the fixture's own sentence, split into why and what to do
115
+ self.assertEqual(o["why"], "purchase order 4001 is closed")
116
+ self.assertTrue(o["todo"].startswith("Reopen it on Manage Orders"))
117
+ self.assertIn("posted", got[("gl_journal", "FPT-J-1")]["why"])
118
+ self.assertTrue(self.svc.audit.query(kind="left_on_pod.recorded", run_id=rid))
119
+
120
+ def test_idempotent_and_a_decision_is_kept(self):
121
+ rid = self.left_run()
122
+ self.assertEqual(left_on_pod.record(self.svc, rid), 3)
123
+ first = {x["id"] for x in self.rows()["items"]}
124
+ row = next(x for x in self.rows()["items"] if x["reference"] == "FPT-T-1")
125
+ self.c.post(f"/api/left-on-pod/{row['id']}/decision", json={"decision": "done", "note": "credited"}, headers=bearer(self.c, "consultant"))
126
+ sweep_test_data(self.svc, rid, "completed") # the clean-up runs again (a restart): the same rows, the decision stays
127
+ self.assertEqual(left_on_pod.record(self.svc, rid), 0)
128
+ again = self.rows()
129
+ self.assertEqual({x["id"] for x in again["items"]}, first)
130
+ self.assertEqual(again["total"], 3)
131
+ self.assertEqual(next(x for x in again["items"] if x["id"] == row["id"])["status"], "done")
132
+
133
+ def test_same_reference_in_another_run_is_its_own_row(self):
134
+ left_on_pod.record(self.svc, self.left_run("20261101-000000-aaaaaa"))
135
+ left_on_pod.record(self.svc, self.left_run("20261102-000000-bbbbbb"))
136
+ self.assertEqual(self.rows(kind="ar_transaction")["total"], 2)
137
+
138
+ def test_a_run_on_the_practice_pod_records_nothing(self):
139
+ rid = self.make_run("20261103-000000-cccccc", None, {"kind": "ap_invoice", "number": "FPT-M-1", "test": "t"})
140
+ self.assertEqual(left_on_pod.record(self.svc, rid), 0)
141
+
142
+ def test_filters(self):
143
+ left_on_pod.record(self.svc, self.left_run())
144
+ self.assertEqual(self.rows(kind="gl_journal")["total"], 1)
145
+ self.assertEqual(self.rows(pod_id=self.pod_id, status="open")["total"], 3)
146
+ self.assertEqual(self.rows(pod_id=self.pod_id + 99)["total"], 0)
147
+ self.assertEqual(self.rows(status="done")["total"], 0)
148
+ self.assertEqual(self.c.get("/api/left-on-pod?kind=bogus", headers=bearer(self.c, "viewer")).status_code, 422)
149
+
150
+ def test_pod_card_count(self):
151
+ left_on_pod.record(self.svc, self.left_run())
152
+ pods = self.c.get("/api/pods", headers=bearer(self.c, "viewer")).json()
153
+ self.assertEqual({p["id"]: p["left_open"] for p in pods}[self.pod_id], 3)
154
+
155
+ def test_only_numbers_and_our_own_sentences_are_kept(self):
156
+ rid = self.left_run()
157
+ sweep_test_data(self.svc, rid, "completed")
158
+ self.assertIn(CLIENT_NAME, json.dumps(self.pod.transactions)) # the pod answered with the client's name and amount
159
+ everything = json.dumps(self.svc.db.q("SELECT * FROM left_on_pod")) + json.dumps(self.rows()) + json.dumps(self.svc.audit.query(run_id=rid))
160
+ self.assertNotIn(CLIENT_NAME, everything)
161
+ self.assertNotIn("1234", everything)
162
+
163
+
164
+ class TestBackfill(LeftOnPodCase):
165
+ def test_backfill_from_the_run_folders_files(self):
166
+ a = self.left_run("20261101-000000-aaaaaa")
167
+ (self.svc.run_dir(a) / cleanup.RESULT).write_text(json.dumps({"at": "2026-11-01T11:00:00Z", "cleaned": [], "left": [
168
+ {"number": "FPT-T-1", "kind": "ar_transaction", "test": "Create and complete an invoice",
169
+ "why": "transaction FPT-T-1 is complete: credit it on Manage Transactions (Actions > Credit Transaction)"}]}), encoding="utf-8")
170
+ self.make_run("20261102-000000-bbbbbb", None, {"kind": "ap_invoice", "number": "FPT-M-1", "test": "mock"}) # practice pod: skipped
171
+ self.assertEqual(left_on_pod.backfill(self.svc), {"runs": 1, "added": 3})
172
+ self.assertEqual(left_on_pod.backfill(self.svc), {"runs": 1, "added": 0})
173
+ t = next(x for x in self.rows()["items"] if x["reference"] == "FPT-T-1")
174
+ self.assertEqual((t["why"], t["todo"]), ("transaction FPT-T-1 is complete", "Credit it on Manage Transactions (Actions > Credit Transaction)"))
175
+ self.assertFalse(self.pod.calls) # the files alone: the pod is not contacted
176
+
177
+ def test_start_up_backfills_once_and_the_cli_again(self):
178
+ self.left_run()
179
+ left_on_pod.backfill_once(self.svc)
180
+ self.assertEqual(self.rows()["total"], 3)
181
+ self.assertTrue(self.svc.db.kv_get("left_on_pod_backfilled"))
182
+ self.svc.db.x("DELETE FROM left_on_pod")
183
+ left_on_pod.backfill_once(self.svc) # the flag is set: not again
184
+ self.assertEqual(self.rows()["total"], 0)
185
+ import argparse
186
+ from unittest import mock
187
+
188
+ from coworker import __main__ as cli
189
+ with mock.patch("coworker.graph.services.build_services", return_value=self.svc):
190
+ self.assertEqual(cli.cmd_left_on_pod(argparse.Namespace(action="backfill")), 0)
191
+ self.assertEqual(cli.cmd_left_on_pod(argparse.Namespace(action="list")), 0)
192
+ self.assertEqual(self.rows()["total"], 3)
193
+
194
+
195
+ class TestDecide(LeftOnPodCase):
196
+ def setUp(self):
197
+ super().setUp()
198
+ self.rid = self.left_run()
199
+ left_on_pod.record(self.svc, self.rid)
200
+ self.id = self.rows(kind="ar_transaction")["items"][0]["id"]
201
+
202
+ def post(self, role, what, body=None):
203
+ return self.c.post(f"/api/left-on-pod/{self.id}/{what}", json=body, headers=bearer(self.c, role))
204
+
205
+ def test_who_may_decide(self):
206
+ self.assertEqual(self.post("viewer", "decision", {"decision": "done"}).status_code, 403)
207
+ self.assertEqual(self.post("viewer", "recheck").status_code, 403)
208
+ self.assertEqual(self.c.get("/api/left-on-pod").status_code, 401)
209
+ for role in ("consultant", "qa_approver", "admin"):
210
+ self.assertEqual(self.post(role, "decision", {"decision": "done"}).status_code, 200, role)
211
+ self.assertEqual(self.post(role, "decision", {"decision": "reopen"}).status_code, 200, role)
212
+
213
+ def test_done_with_a_note_is_audited(self):
214
+ r = self.post("consultant", "decision", {"decision": "done", "note": "credit memo 77 raised"})
215
+ self.assertEqual((r.json()["status"], r.json()["decided_by"], r.json()["note"]), ("done", "consultant", "credit memo 77 raised"))
216
+ self.assertTrue(r.json()["decided_at"])
217
+ ev = self.svc.audit.query(kind="left_on_pod.done", run_id=self.rid)
218
+ self.assertEqual((ev[0]["actor"], ev[0]["payload"]["reference"], ev[0]["payload"]["note"]), ("consultant", "FPT-T-1", "credit memo 77 raised"))
219
+ self.assertEqual(self.post("admin", "decision", {"decision": "dismiss"}).status_code, 409) # decided already
220
+ self.assertEqual(self.rows(status="done")["total"], 1)
221
+
222
+ def test_dismiss_reopen_and_unknown(self):
223
+ self.assertEqual(self.post("admin", "decision", {"decision": "dismiss", "note": "client keeps it"}).json()["status"], "dismissed")
224
+ self.assertTrue(self.svc.audit.query(kind="left_on_pod.dismissed"))
225
+ r = self.post("admin", "decision", {"decision": "reopen"}).json()
226
+ self.assertEqual((r["status"], r["decided_by"], r["note"]), ("open", None, None))
227
+ self.assertTrue(self.svc.audit.query(kind="left_on_pod.reopened"))
228
+ self.assertEqual(self.post("admin", "decision", {"decision": "reopen"}).status_code, 409)
229
+ self.assertEqual(self.post("admin", "decision", {"decision": "nope"}).status_code, 422)
230
+ self.assertEqual(self.c.post("/api/left-on-pod/99999/decision", json={"decision": "done"}, headers=bearer(self.c, "admin")).status_code, 404)
231
+
232
+
233
+ class TestRecheck(LeftOnPodCase):
234
+ def setUp(self):
235
+ super().setUp()
236
+ self.rid = self.left_run()
237
+ left_on_pod.record(self.svc, self.rid)
238
+ self.pod.calls.clear()
239
+
240
+ def ask(self, kind, role="consultant"):
241
+ row = next(x for x in self.rows(kind=kind)["items"])
242
+ r = self.c.post(f"/api/left-on-pod/{row['id']}/recheck", headers=bearer(self.c, role))
243
+ self.assertEqual(r.status_code, 200, r.text)
244
+ return r.json()
245
+
246
+ def test_only_get_requests_reach_the_pod(self):
247
+ out = self.ask("ar_transaction")
248
+ self.assertEqual((out["check_state"], out["status"]), ("still_on_pod", "open")) # a re-check decides nothing
249
+ self.assertIn("complete", out["check_detail"])
250
+ self.assertTrue(out["checked_at"])
251
+ for kind in ("po_order", "gl_journal"):
252
+ self.ask(kind)
253
+ self.assertTrue(self.pod.calls)
254
+ self.assertEqual({m for m, _ in self.pod.calls}, {"GET"})
255
+
256
+ def test_looks_resolved_when_the_document_is_gone_or_credited(self):
257
+ self.pod.transactions["FPT-T-1"] = _txn("FPT-T-1", "Credited")
258
+ self.assertEqual(self.ask("ar_transaction")["check_state"], "looks_resolved")
259
+ del self.pod.transactions["FPT-T-1"]
260
+ out = self.ask("ar_transaction")
261
+ self.assertEqual(out["check_state"], "looks_resolved")
262
+ self.assertIn("not on the pod", out["check_detail"])
263
+ self.assertEqual(self.ask("po_order")["check_state"], "still_on_pod")
264
+ self.pod.orders["FPT-O-1"]["Status"] = "Canceled"
265
+ self.assertEqual(self.ask("po_order")["check_state"], "looks_resolved")
266
+
267
+ def test_nothing_client_specific_is_stored(self):
268
+ self.ask("ar_transaction")
269
+ self.assertNotIn(CLIENT_NAME, json.dumps(self.svc.db.q("SELECT * FROM left_on_pod")))
270
+
271
+ def test_unknown_when_the_pod_cannot_be_asked(self):
272
+ self.svc.kill.engage("test", "admin")
273
+ row = self.rows(kind="ar_transaction")["items"][0]
274
+ self.assertEqual(self.c.post(f"/api/left-on-pod/{row['id']}/recheck", headers=bearer(self.c, "admin")).status_code, 423)
275
+ self.svc.kill.release("admin")
276
+ self.svc.db.x("DELETE FROM pod_credentials")
277
+ self.assertEqual(self.ask("ar_transaction")["check_state"], "unknown")
278
+
279
+
280
+ if __name__ == "__main__":
281
+ unittest.main()
coworker/tests/test_readiness_check.py CHANGED
@@ -155,12 +155,24 @@ class TestReadiness(unittest.TestCase):
155
  self.assertTrue(self.items()["runs"]["ok"])
156
  self.make_run("busy-one", None, ago(minutes=30), status="running")
157
  self.assertTrue(self.items()["runs"]["ok"])
158
- self.make_run("stuck-one", None, ago(hours=30), status="waiting_review")
159
  it = self.items()["runs"]
160
  self.assertFalse(it["ok"])
161
  self.assertIn("stuck-one", it["detail"])
162
  self.assertNotIn("busy-one", it["detail"])
163
 
 
 
 
 
 
 
 
 
 
 
 
 
164
  def test_llm_and_kill_switch_and_disk(self):
165
  it = self.items()
166
  self.assertFalse(it["llm"]["ok"]) # the test server runs on built-in rules
 
155
  self.assertTrue(self.items()["runs"]["ok"])
156
  self.make_run("busy-one", None, ago(minutes=30), status="running")
157
  self.assertTrue(self.items()["runs"]["ok"])
158
+ self.make_run("stuck-one", None, ago(hours=30), status="running")
159
  it = self.items()["runs"]
160
  self.assertFalse(it["ok"])
161
  self.assertIn("stuck-one", it["detail"])
162
  self.assertNotIn("busy-one", it["detail"])
163
 
164
+ def test_a_run_waiting_for_a_person_is_not_stuck_until_it_has_waited_a_week(self):
165
+ self.make_run("review-1", None, ago(hours=30), status="waiting_review")
166
+ it = self.items()
167
+ self.assertTrue(it["runs"]["ok"]) # paused at a gate: holds nothing
168
+ self.assertTrue(it["waiting"]["ok"])
169
+ self.assertIn("1 run(s) waiting for a person", it["waiting"]["detail"])
170
+ self.make_run("review-old", None, ago(hours=8 * 24), status="waiting_review")
171
+ it = self.items()["waiting"]
172
+ self.assertFalse(it["ok"])
173
+ self.assertIn("review-old", it["detail"])
174
+ self.assertNotIn("review-1", it["detail"])
175
+
176
  def test_llm_and_kill_switch_and_disk(self):
177
  it = self.items()
178
  self.assertFalse(it["llm"]["ok"]) # the test server runs on built-in rules
coworker/tests/test_run_depth.py CHANGED
@@ -1,41 +1,48 @@
1
- """Run depth: a quick check re-tests the Critical scenarios, standard adds the High ones the patch touches, a full
2
- regression re-tests every scenario of the areas at every priority (the whole regression pack)."""
3
- from __future__ import annotations
4
-
5
- import unittest
6
-
7
- from coworker.tests.fakes import bearer, make_app
8
-
9
-
10
- class TestRunDepth(unittest.TestCase):
11
- @classmethod
12
- def setUpClass(cls):
13
- cls.app, cls.c, cls.svc, _ = make_app()
14
- cls.h = bearer(cls.c, "consultant")
15
-
16
- def selected(self, depth: str | None) -> list[dict]:
17
- body = {"modules": ["P2P"], "playwright_mode": "stub", **({"depth": depth} if depth else {})}
18
- r = self.c.post("/api/runs", json=body, headers=self.h)
19
- self.assertEqual(r.status_code, 202, r.text)
20
- rid = r.json()["run_id"]
21
- self.app.state.runs.drain()
22
- st = self.app.state.runs.state(rid)
23
- self.assertEqual(st["depth"], depth or "standard")
24
- self.app.state.runs.cancel(rid, "test") # one waiting run per area set: free it for the next depth
25
- return st.get("test_cases") or []
26
-
27
- def test_each_depth_tests_more_of_the_library(self):
28
- smoke, standard, full = self.selected("smoke"), self.selected(None), self.selected("full")
29
- prio = lambda cs: {c["priority"] for c in cs if c.get("origin") == "library"} # noqa: E731
30
- self.assertEqual(prio(smoke), {"P1"})
31
- self.assertLessEqual(len(smoke), len(standard))
32
- self.assertLess(len(standard), len(full))
33
- self.assertTrue(prio(full) - {"P1"}, "a full regression also re-tests the lower priorities")
34
-
35
- def test_an_unknown_depth_is_refused(self):
36
- r = self.c.post("/api/runs", json={"modules": ["P2P"], "playwright_mode": "stub", "depth": "everything"}, headers=self.h)
37
- self.assertEqual(r.status_code, 422)
38
-
39
-
40
- if __name__ == "__main__":
41
- unittest.main()
 
 
 
 
 
 
 
 
1
+ """Run depth: a quick check re-tests the Critical scenarios, standard adds the High ones the patch touches, a full
2
+ regression re-tests every scenario of the areas at every priority (the whole regression pack)."""
3
+ from __future__ import annotations
4
+
5
+ import unittest
6
+
7
+ from coworker.tests.fakes import bearer, make_app
8
+
9
+
10
+ class TestRunDepth(unittest.TestCase):
11
+ @classmethod
12
+ def setUpClass(cls):
13
+ cls.app, cls.c, cls.svc, _ = make_app()
14
+ cls.h = bearer(cls.c, "consultant")
15
+
16
+ def selected(self, depth: str | None, case_ids: list[str] | None = None) -> list[dict]:
17
+ body = {"modules": ["P2P"], "playwright_mode": "stub", **({"depth": depth} if depth else {}), **({"case_ids": case_ids} if case_ids else {})}
18
+ r = self.c.post("/api/runs", json=body, headers=self.h)
19
+ self.assertEqual(r.status_code, 202, r.text)
20
+ rid = r.json()["run_id"]
21
+ self.app.state.runs.drain()
22
+ st = self.app.state.runs.state(rid)
23
+ self.assertEqual(st["depth"], depth or "standard")
24
+ self.app.state.runs.cancel(rid, "test") # one waiting run per area set: free it for the next depth
25
+ return st.get("test_cases") or []
26
+
27
+ def test_each_depth_tests_more_of_the_library(self):
28
+ smoke, standard, full = self.selected("smoke"), self.selected(None), self.selected("full")
29
+ prio = lambda cs: {c["priority"] for c in cs if c.get("origin") == "library"} # noqa: E731
30
+ self.assertEqual(prio(smoke), {"P1"})
31
+ self.assertLessEqual(len(smoke), len(standard))
32
+ self.assertLess(len(standard), len(full))
33
+ self.assertTrue(prio(full) - {"P1"}, "a full regression also re-tests the lower priorities")
34
+
35
+ def test_scenarios_chosen_by_name_all_run_whatever_their_priority(self):
36
+ """Seen on a 26D run: 10 of 19 scenarios chosen by name were P2 and the standard depth deferred them."""
37
+ lower = [c["id"] for c in self.selected("full") if c.get("origin") == "library" and c["priority"] != "P1"][:3]
38
+ self.assertTrue(lower)
39
+ chosen = {c["id"] for c in self.selected(None, lower)}
40
+ self.assertEqual(chosen & set(lower), set(lower))
41
+
42
+ def test_an_unknown_depth_is_refused(self):
43
+ r = self.c.post("/api/runs", json={"modules": ["P2P"], "playwright_mode": "stub", "depth": "everything"}, headers=self.h)
44
+ self.assertEqual(r.status_code, 422)
45
+
46
+
47
+ if __name__ == "__main__":
48
+ unittest.main()
coworker/tests/test_security_review.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Security review fixes: sign-in limits (per name across visitors, per visitor across names), constant-time compares that
2
+ survive odd input, the break-glass reset, request body limit, CORS, evidence headers, the open stand-in/OAuth endpoints, the
3
+ runner API, and a guard that every route is either public on purpose or needs a signed-in person."""
4
+ from __future__ import annotations
5
+
6
+ import hashlib
7
+ import http.client
8
+ import io
9
+ import os
10
+ import tempfile
11
+ import threading
12
+ import unittest
13
+ import zipfile
14
+ from http.server import ThreadingHTTPServer
15
+ from pathlib import Path
16
+ from unittest import mock
17
+
18
+ from fastapi.routing import APIRoute
19
+
20
+ from coworker.platform.users import RateLimited, consteq
21
+ from coworker.tests.fakes import PASSWORD, bearer, make_app
22
+ from coworker.tests.test_remote_runner import load_server
23
+
24
+
25
+ class TestSignInLimits(unittest.TestCase):
26
+ def test_one_name_from_many_visitors_is_paused(self):
27
+ _, _, svc, _ = make_app(login_max_attempts_per_user=6)
28
+ users = svc.users
29
+ for i in range(6): # each visitor stays under the per-visitor limit of 5
30
+ with self.assertRaises(PermissionError):
31
+ users.authenticate("admin", "wrong-password-xx", f"10.0.0.{i}")
32
+ with self.assertRaises(RateLimited): # a seventh visitor is refused before any password is checked
33
+ users.authenticate("admin", PASSWORD, "10.0.0.99")
34
+ self.assertTrue(users.authenticate("viewer", PASSWORD, "10.0.0.99")) # other accounts are untouched
35
+
36
+ def test_one_visitor_across_many_names_is_paused_behind_a_trusted_proxy(self):
37
+ _, c, svc, _ = make_app(login_max_attempts_per_ip=4, trust_proxy=True)
38
+ for i in range(4):
39
+ self.assertEqual(c.post("/api/auth/login", json={"username": f"nobody{i}", "password": "x" * 14}).status_code, 401)
40
+ r = c.post("/api/auth/login", json={"username": "admin", "password": PASSWORD})
41
+ self.assertEqual(r.status_code, 429)
42
+ self.assertIn("retry-after", r.headers)
43
+
44
+ def test_per_visitor_limit_is_off_without_a_trusted_proxy(self):
45
+ # every visitor shares the proxy's address there: counting per address would lock out everyone
46
+ _, c, _, _ = make_app(login_max_attempts_per_ip=2)
47
+ for i in range(4):
48
+ c.post("/api/auth/login", json={"username": f"nobody{i}", "password": "x" * 14})
49
+ self.assertEqual(c.post("/api/auth/login", json={"username": "admin", "password": PASSWORD}).status_code, 200)
50
+
51
+ def test_success_never_counts_and_limits_can_be_switched_off(self):
52
+ _, c, svc, _ = make_app(login_max_attempts_per_user=0)
53
+ for _ in range(8):
54
+ self.assertEqual(c.post("/api/auth/login", json={"username": "admin", "password": PASSWORD}).status_code, 200)
55
+
56
+ def test_a_pasted_password_never_reaches_the_audit_log(self):
57
+ _, c, svc, _ = make_app()
58
+ secret = "My-Real-Password-123!"
59
+ c.post("/api/auth/login", json={"username": secret, "password": "whatever-14-chars"})
60
+ c.post("/api/auth/login", json={"username": "admin", "password": "wrong-14-chars-x"})
61
+ rows = svc.audit.query(kind="auth.login_failed")
62
+ self.assertEqual(len(rows), 2)
63
+ self.assertNotIn(secret, " ".join(f"{r['actor']} {r['summary']} {r['payload']}" for r in rows))
64
+ self.assertEqual(rows[1]["actor"], "admin") # a real account is named
65
+
66
+
67
+ class TestConstantTime(unittest.TestCase):
68
+ def test_non_ascii_is_just_a_mismatch(self):
69
+ self.assertTrue(consteq("abc", "abc"))
70
+ self.assertFalse(consteq("abc", "abd"))
71
+ self.assertFalse(consteq("abcé", "abc"))
72
+ self.assertFalse(consteq(None, "abc"))
73
+
74
+ def test_odd_headers_are_refused_not_500(self):
75
+ _, c, svc, _ = make_app()
76
+ self.assertEqual(c.get("/api/metrics", headers={"Authorization": "Bearer tést".encode("utf-8")}).status_code, 401)
77
+ r = c.post("/api/auth/login", json={"username": "admin", "password": PASSWORD})
78
+ self.assertEqual(r.status_code, 200)
79
+ # cookie session + a CSRF header that is not ASCII
80
+ r = c.post("/api/auth/logout", headers={"x-csrf-token": "é".encode("utf-8")})
81
+ self.assertEqual(r.status_code, 403)
82
+ self.assertEqual(c.get("/api/share/runs/run-x/test-script.xlsx?exp=99999999999&sig=%C3%A9").status_code, 403)
83
+
84
+
85
+ class TestBreakGlassReset(unittest.TestCase):
86
+ def test_short_secret_is_refused_not_fatal(self):
87
+ _, _, svc, _ = make_app()
88
+ with mock.patch.dict(os.environ, {"FPT_ADMIN_PASSWORD_RESET": "short"}):
89
+ self.assertIsNone(svc.users.reset_admin_from_env())
90
+ self.assertTrue(svc.users.authenticate("admin", PASSWORD)) # nothing changed
91
+
92
+ def test_mark_is_slow_hash_and_old_marks_still_count(self):
93
+ _, _, svc, _ = make_app()
94
+ new = "Recovered-Pass-456!"
95
+ with mock.patch.dict(os.environ, {"FPT_ADMIN_PASSWORD_RESET": new}):
96
+ self.assertEqual(svc.users.reset_admin_from_env(), "admin")
97
+ mark = svc.db.kv_get("admin_password_reset_applied")
98
+ self.assertTrue(mark.startswith("$argon2"))
99
+ self.assertIsNone(svc.users.reset_admin_from_env())
100
+ # a mark an earlier version wrote (plain SHA-256 of the same value) is honoured: no second reset on upgrade
101
+ svc.db.kv_set("admin_password_reset_applied", hashlib.sha256(("fpt-admin-reset|" + new).encode()).hexdigest())
102
+ svc.users.update(svc.users.by_name("admin")["id"], password="Changed-After-Reset-1!")
103
+ self.assertIsNone(svc.users.reset_admin_from_env())
104
+ self.assertTrue(svc.users.authenticate("admin", "Changed-After-Reset-1!"))
105
+
106
+ def test_reset_ends_the_accounts_sessions(self):
107
+ _, c, svc, _ = make_app()
108
+ h = bearer(c, "admin")
109
+ with mock.patch.dict(os.environ, {"FPT_ADMIN_PASSWORD_RESET": "Recovered-Pass-456!"}):
110
+ svc.users.reset_admin_from_env()
111
+ self.assertEqual(c.get("/api/auth/me", headers=h).status_code, 401)
112
+
113
+
114
+ class TestHttpHardening(unittest.TestCase):
115
+ def test_body_limit(self):
116
+ _, c, _, _ = make_app(max_body_bytes=2000)
117
+ h = bearer(c, "admin")
118
+ r = c.post("/api/auth/login", json={"username": "a", "password": "b" * 100})
119
+ self.assertEqual(r.status_code, 401) # small: read as usual
120
+ r = c.post("/api/auth/login", json={"username": "a", "password": "b" * 50, "pad": "x" * 5000})
121
+ self.assertEqual(r.status_code, 413)
122
+ self.assertEqual(r.json()["code"], "TOO_LARGE")
123
+ r = c.post("/api/auth/login", content=iter([b'{"username":"a",', b"x" * 3000, b"}"]), headers={"content-type": "application/json"})
124
+ self.assertEqual(r.status_code, 413) # no Content-Length: refused while streaming
125
+ self.assertEqual(c.get("/api/auth/me", headers=h).status_code, 200)
126
+
127
+ def test_cors_wildcard_is_ignored(self):
128
+ _, c, _, _ = make_app(cors_origins=["*", "https://app.example"])
129
+ bad = c.get("/api/health", headers={"Origin": "https://evil.example"})
130
+ self.assertNotIn("access-control-allow-origin", bad.headers)
131
+ ok = c.get("/api/health", headers={"Origin": "https://app.example"})
132
+ self.assertEqual(ok.headers["access-control-allow-origin"], "https://app.example")
133
+
134
+ def test_security_headers(self):
135
+ _, c, _, _ = make_app()
136
+ r = c.get("/api/health")
137
+ self.assertEqual(r.headers["x-content-type-options"], "nosniff")
138
+ self.assertEqual(r.headers["referrer-policy"], "no-referrer")
139
+ csp = r.headers["content-security-policy"]
140
+ self.assertIn("frame-ancestors 'self'", csp)
141
+ self.assertNotIn("'unsafe-inline'", csp.split("script-src")[1].split(";")[0])
142
+ self.assertEqual(r.headers["x-frame-options"], "SAMEORIGIN")
143
+
144
+ def test_evidence_that_is_not_a_picture_downloads_and_is_sandboxed(self):
145
+ _, c, svc, _ = make_app()
146
+ with tempfile.TemporaryDirectory() as d:
147
+ f = Path(d) / "page.html"
148
+ f.write_text("<script>alert(1)</script>")
149
+ png = Path(d) / "shot.png"
150
+ png.write_bytes(b"\x89PNG")
151
+ html_ref = svc.evidence.ingest_file("run-sec", 1, f, None)
152
+ png_ref = svc.evidence.ingest_file("run-sec", 1, png, None)
153
+ h = bearer(c, "admin")
154
+ r = c.get(f"/api/evidence/{html_ref.evidence_id}", headers=h)
155
+ self.assertTrue(r.headers["content-disposition"].startswith("attachment"))
156
+ self.assertIn("sandbox", r.headers["content-security-policy"])
157
+ r = c.get(f"/api/evidence/{png_ref.evidence_id}", headers=h)
158
+ self.assertTrue(r.headers["content-disposition"].startswith("inline"))
159
+
160
+
161
+ class TestOpenEndpoints(unittest.TestCase):
162
+ def test_standin_inbox_is_paused_for_a_visitor_sending_unsigned_callbacks(self):
163
+ _, c, svc, _ = make_app()
164
+ codes = [c.post("/api/agent-studio/standin/inbox", json={"event": "x"}).status_code for _ in range(7)]
165
+ self.assertEqual(codes[:5], [204] * 5)
166
+ self.assertEqual(codes[5], 429)
167
+
168
+ def test_oauth_wrong_secrets_are_paused(self):
169
+ _, c, _, _ = make_app()
170
+ form = {"grant_type": "client_credentials", "client_id": "nobody", "client_secret": "nope"}
171
+ codes = [c.post("/oauth/token", data=form).status_code for _ in range(7)]
172
+ self.assertEqual(codes[:5], [401] * 5)
173
+ self.assertEqual(codes[5], 429)
174
+
175
+
176
+ class TestEveryRouteIsGuarded(unittest.TestCase):
177
+ # Public on purpose. Anything else must depend on a signed-in person (current_user / require) or its own credential.
178
+ PUBLIC = {
179
+ ("POST", "/api/auth/forgot"), ("POST", "/api/auth/reset"), ("GET", "/api/auth/config"), ("POST", "/api/auth/register"),
180
+ ("POST", "/api/auth/login"), ("POST", "/api/auth/token"), ("GET", "/api/auth/oidc/login"), # sign in (rate limited)
181
+ ("GET", "/api/health"), ("GET", "/api/ready"), # monitors, sign-in page: no internals
182
+ ("GET", "/api/metrics"), # admin session or metrics token, checked inside
183
+ ("GET", "/api/share/runs/{run_id}/test-script.xlsx"), # signed, expiring link
184
+ ("POST", "/api/agent-studio/standin/inbox"), # signature-checked demo receiver, rate limited
185
+ ("POST", "/oauth/token"), # client credentials, rate limited
186
+ ("GET", "/mcp"), ("POST", "/mcp"), ("DELETE", "/mcp"), ("POST", "/a2a"), ("GET", "/.well-known/agent-card.json"), # tokens checked inside
187
+ }
188
+
189
+ def test_no_route_is_open_by_accident(self):
190
+ from coworker.api import a2a, mcp
191
+ from coworker.api.routes import (admin, agent_studio, ai_monitoring, assistant, auth, channels, chat, consultant,
192
+ custom_cases, gates, heals, integrations, live, llm, notifications, pods, recordings,
193
+ review, runs, screens, signin, tokens)
194
+
195
+ def guarded(dependant) -> bool:
196
+ for s in dependant.dependencies:
197
+ name = getattr(s.call, "__name__", "")
198
+ if name in ("current_user", "agent_client") or getattr(s.call, "__qualname__", "").startswith("require.<locals>") or guarded(s):
199
+ return True
200
+ return False
201
+
202
+ routers = [(m.router, "/api") for m in (auth, runs, gates, review, admin, pods, screens, consultant, live, chat, assistant, llm,
203
+ notifications, channels, integrations, tokens, custom_cases, recordings, heals,
204
+ agent_studio, ai_monitoring, signin)]
205
+ routers += [(agent_studio.oauth, ""), (mcp.router, ""), (a2a.router, "")]
206
+ seen, open_ = 0, []
207
+ for router, prefix in routers:
208
+ for r in router.routes:
209
+ if isinstance(r, APIRoute):
210
+ seen += 1
211
+ for m in r.methods:
212
+ if not guarded(r.dependant) and (m, prefix + r.path) not in self.PUBLIC:
213
+ open_.append((m, prefix + r.path))
214
+ self.assertGreater(seen, 150)
215
+ self.assertEqual(open_, [], "routes with no sign-in or permission check that are not on the public list")
216
+
217
+
218
+ class TestRunnerApi(unittest.TestCase):
219
+ def setUp(self):
220
+ self.S = load_server()
221
+ self.S.TOKEN = "t" * 32
222
+ self.srv = ThreadingHTTPServer(("127.0.0.1", 0), self.S.H)
223
+ threading.Thread(target=self.srv.serve_forever, daemon=True).start()
224
+ self.port = self.srv.server_address[1]
225
+
226
+ def tearDown(self):
227
+ self.srv.shutdown()
228
+ self.srv.server_close()
229
+
230
+ def call(self, method, path, headers=None, body=b""):
231
+ c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
232
+ c.request(method, path, body=body, headers=headers or {})
233
+ r = c.getresponse()
234
+ out = r.status, r.read()
235
+ c.close()
236
+ return out
237
+
238
+ def test_every_endpoint_needs_the_token(self):
239
+ for method, path in (("GET", "/v1/attempts/job_000000000000"), ("GET", "/v1/attempts/job_000000000000/bundle"),
240
+ ("GET", "/v1/sign-in/si_000000000000"), ("POST", "/v1/attempts"), ("POST", "/v1/screens"),
241
+ ("POST", "/v1/sign-in"), ("POST", "/v1/sign-in/si_000000000000/finish"),
242
+ ("POST", "/v1/attempts/job_000000000000/cancel")):
243
+ self.assertEqual(self.call(method, path)[0], 401, (method, path))
244
+ self.assertEqual(self.call(method, path, {"Authorization": "Bearer " + "x" * 32})[0], 401, (method, path))
245
+ self.assertEqual(self.call("GET", "/v1/attempts/job_000000000000", {"Authorization": "Bearer " + "t" * 32})[0], 404)
246
+
247
+ def test_odd_tokens_and_lengths_are_answered_not_crashed(self):
248
+ self.assertEqual(self.call("GET", "/v1/attempts/job_000000000000", {"Authorization": "Bearer té"})[0], 401)
249
+ good = {"Authorization": "Bearer " + "t" * 32}
250
+ self.assertEqual(self.call("POST", "/v1/attempts", {**good, "Content-Length": "-5"})[0], 400)
251
+ self.assertEqual(self.call("POST", "/v1/attempts", {**good, "Content-Length": "abc"})[0], 400)
252
+ self.assertEqual(self.call("POST", "/v1/attempts", {**good, "Content-Length": str(self.S.MAX_BODY + 1)})[0], 413)
253
+
254
+ def test_health_shows_no_secrets(self):
255
+ status, body = self.call("GET", "/healthz")
256
+ self.assertEqual(status, 200)
257
+ self.assertNotIn(b"t" * 32, body)
258
+
259
+
260
+ class TestBundleLimit(unittest.TestCase):
261
+ def test_a_zip_bomb_is_refused(self):
262
+ from coworker.adapters import remote_runner as R
263
+ buf = io.BytesIO()
264
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
265
+ z.writestr("run/big.bin", b"\0" * 5_000_000)
266
+ with mock.patch.object(R, "MAX_BUNDLE_BYTES", 1_000_000), tempfile.TemporaryDirectory() as d:
267
+ d = Path(d)
268
+ with self.assertRaises(R.RemoteRunnerError):
269
+ R._unpack(buf.getvalue(), d / "report.json", d / "run", d / "logs", "created.jsonl", 1)
270
+
271
+
272
+ if __name__ == "__main__":
273
+ unittest.main()
deploy/docker-compose.yml CHANGED
@@ -17,6 +17,8 @@ services:
17
  TEMPORAL_ADDRESS: temporal:7233
18
  TEMPORAL_UI_URL: "" # the Temporal UI is not published; see DEPLOY.md to reach it over SSH
19
  FPT_COOKIE_SECURE: always # the app is only reachable through HTTPS
 
 
20
  FPT_CASE_WRITEBACK: "0" # approvals are kept in the database; the image itself is read-only content
21
  POD_BASE_URL: http://127.0.0.1:3100
22
  volumes:
 
17
  TEMPORAL_ADDRESS: temporal:7233
18
  TEMPORAL_UI_URL: "" # the Temporal UI is not published; see DEPLOY.md to reach it over SSH
19
  FPT_COOKIE_SECURE: always # the app is only reachable through HTTPS
20
+ FPT_TRUST_PROXY: ${FPT_TRUST_PROXY:-1} # the app is only reachable through Caddy, which sets the visitor address: sign-in limits count per visitor
21
+ FPT_API_DOCS: ${FPT_API_DOCS:-0} # the interactive API docs are off on a public server (FPT_API_DOCS=1 in .env to show them)
22
  FPT_CASE_WRITEBACK: "0" # approvals are kept in the database; the image itself is read-only content
23
  POD_BASE_URL: http://127.0.0.1:3100
24
  volumes:
docs/SECURITY-REVIEW.md ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Security review (production)
2
+
3
+ Scope: the FastAPI backend (`coworker/`), the React web app (`web/`), the Docker deployment behind Caddy (`deploy/`) and the
4
+ browser runner API (`automation/remote_runner/server.py`). Reviewed at `d52c9b9`; fixes are on branch `security-review`.
5
+ Nothing was deployed or contacted other than the dependency advisory databases.
6
+
7
+ Severity: High = exploitable by an outsider with real impact; Medium = needs a precondition or limited impact; Low =
8
+ hardening or defence in depth. Every new behaviour is a setting with a safe default (listed at the end).
9
+
10
+ ## Findings
11
+
12
+ | # | Area | Finding | Severity | Status |
13
+ |---|---|---|---|---|
14
+ | 1 | Sessions / sign-in | Limits were per user **and** visitor only: a guesser using many addresses had unlimited tries at one account, and one visitor could spray many names | Medium | Fixed: added a per-name limit across visitors (50 failures / 5 min) and a per-visitor limit across names (30 / 5 min, only behind a trusted proxy, see 2). Both counted on failures only; `0` switches off |
15
+ | 2 | Deployment | `deploy/docker-compose.yml` did not set `FPT_TRUST_PROXY`: behind Caddy every visitor shared the proxy's address, so "per visitor" limits were really global (5 bad tries on a name locked it for everyone) | Medium | Fixed in compose (default `1`; the app port is only exposed to the Caddy container). **Operator action**: redeploy, or set `FPT_TRUST_PROXY=1` in `.env` |
16
+ | 3 | Deployment | Interactive API docs (`/api/docs`, `/api/openapi.json`) are on by default and compose did not turn them off, although `docs/SECURITY.md` says they are off in production | Low | Fixed in compose (`FPT_API_DOCS` default `0`). Set `FPT_API_DOCS=1` in `.env` to show them |
17
+ | 4 | Break-glass reset | The "applied once" marker for `FPT_ADMIN_PASSWORD_RESET` was an unsalted SHA-256 of the secret, kept in the database (and in the saved state): a leaked copy let anyone test guesses of the reset password at full speed | Medium | Fixed: marker is now an argon2id hash; markers written by earlier versions still count, so an upgrade never re-applies a reset |
18
+ | 5 | Break-glass reset | A reset value shorter than 12 characters raised during start-up and stopped the server from booting | Low | Fixed: refused with a logged error, server starts. The reset only runs from a host environment variable, still audited (`users.admin_password_reset`) and ends the account's sessions |
19
+ | 6 | Audit log | A failed sign-in wrote the typed user name to the append-only audit log; people paste their password into the name field, and the log cannot be scrubbed | Medium | Fixed: a name is recorded only if it is a real account or an e-mail address; otherwise a short fingerprint (`unknown:<hash>`) |
20
+ | 7 | Constant-time compares | `hmac.compare_digest` on `str` raises `TypeError` for non-ASCII input: a crafted `X-CSRF-Token`, metrics bearer, signed-link `sig`, OAuth secret or callback signature gave a 500 | Low | Fixed: one helper (`users.consteq`) used everywhere. Runner token compared as bytes |
21
+ | 8 | Request size | No limit on request bodies: the recording and Excel checks looked at `Content-Length` only (chunked bodies bypassed them) and JSON bodies were unbounded | Medium | Fixed: `BodyLimit` middleware, 12 MB default (`FPT_MAX_BODY_BYTES`, `0` = off), 413 by `Content-Length` or while streaming. Caddy has no limit of its own |
22
+ | 9 | CORS | `FPT_CORS_ORIGINS=*` together with `allow_credentials=True` would let any website act as a signed-in person | Medium (config) | Fixed: `*` is ignored with a warning. Default origins are localhost only |
23
+ | 10 | Evidence serving | Evidence is served inline with a type guessed from the file name; a browser run can upload any file | Low | Fixed: only images and videos show inline; anything else downloads; every evidence response carries a `sandbox` CSP |
24
+ | 11 | Open endpoints | `POST /api/agent-studio/standin/inbox` (unauthenticated demo receiver) stored every body, signed or not: a table-filling DoS | Medium | Fixed: 5 unsigned callbacks / 5 min per visitor then 429, table kept to the last 500 rows |
25
+ | 12 | Open endpoints | `POST /oauth/token` had no limit on wrong client secrets | Low (secrets are random, 256-bit) | Fixed: 5 wrong secrets / 5 min per client and visitor |
26
+ | 13 | Runner API | A non-ASCII `Authorization` header raised in `compare_digest`; a negative or non-numeric `Content-Length` hung the handler (`rfile.read(-1)`) or raised; no socket timeout, so a stalled client held a thread | Medium (DoS on the runner) | Fixed: bytes compare, 400 on bad length, 120 s socket timeout |
27
+ | 14 | Runner bundle | The Astra side unpacked a runner's zip without a size cap (zip bomb from a compromised runner). Path traversal was already guarded | Low | Fixed: unpacked size cap 2 GB (`FPT_RUNNER_BUNDLE_MAX_MB`) |
28
+ | 15 | Secrets | The vault file was written with default permissions and `chmod` afterwards (a short world-readable window; a crash mid-write could corrupt it) | Low | Fixed: written to a 0600 temp file and moved into place |
29
+ | 16 | Authorization | Route inventory (194 routes): every route outside the public list needs `current_user`, `require(perm)` or its own credential | Info | Public on purpose: sign-in/register/forgot/reset/config, `health`, `ready` (internals hidden when anonymous), `metrics` (admin or metrics token inside), signed share link, stand-in inbox (signature + limit), `/oauth/token`, `/mcp`, `/a2a` and the agent card (personal tokens inside). A test (`TestEveryRouteIsGuarded`) fails if a new route is left open |
30
+ | 17 | Passwords / tokens | argon2id with a concurrency cap; sessions server-side, random 256-bit, SHA-256 at rest, 12 h (7 d with "keep me signed in"), ended by password change/reset/disable; personal tokens hashed, expiring, revocable, `/mcp` only; CSRF double submit; timing-equaliser hash for unknown names | Info | Reviewed, no change |
31
+ | 18 | HTTP headers | CSP (`script-src 'self'`, `frame-ancestors 'self'`, report pages sandboxed), nosniff, Referrer-Policy, COOP, X-Frame-Options (dropped only when `FPT_EMBED_ORIGIN` is set), HSTS when https or `FPT_COOKIE_SECURE=always`, `Cache-Control: no-store` on `/api` | Info | Reviewed, no change. `style-src 'unsafe-inline'` remains for the SPA's inline styles (script injection is not possible through it) |
32
+ | 19 | File serving | Reports: path comes from stored state and must be inside the runs folder; SPA files: resolved and checked against `web/dist`; evidence by numeric id; case YAML by strict id pattern | Info | Reviewed, no traversal found |
33
+ | 20 | Secrets in logs | Access log has paths only (no query strings, so signed links stay out); `pwt_` tokens filtered; egress audit logs descriptions, never headers; OCI PAR address is stored with `/p/***/` (`ocistore.shown`) and refused requests log the masked form; error handler returns the exception class name only | Info | Reviewed, no leaks found beyond #6 |
34
+ | 21 | Runner API | Token on every endpoint except `/healthz` (version and busy flag only); no shell (`Popen` with an argument list); config, env keys, file names and ids are allow-listed or pattern-checked; body 20 MB | Info | Reviewed |
35
+ | 22 | Runner API | The token is a long-lived bearer: anyone holding it can have the runner execute spec code (drafts/library are TypeScript run by Playwright) and receives the pod sign-in session on `finish`. There is no failed-token throttle (the runner sits behind Caddy, so per-address counting is not available there) | Medium (design) | Not changed. Mitigation: keep it behind HTTPS, restrict the runner's port to the Astra host (firewall or Caddy `remote_ip`), use 32+ random characters, rotate on staff change. The runner accepts 24+ characters; raising that would stop existing runners from starting |
36
+ | 23 | Vault | Secrets are plain JSON on the data volume (mode 600) | Low | Not changed (documented in `docs/SECURITY.md`): prefer `FPT_SECRET_*` environment values; the volume should be encrypted at rest (OCI block volume encryption) |
37
+ | 24 | Personal tokens | A personal access token keeps working after its owner's password is reset (it follows the owner's role, ends on disable/expiry/revoke) | Low | Not changed. After a break-glass reset or suspected compromise, revoke the owner's tokens in Settings |
38
+ | 25 | Dependencies (Python) | `pip-audit` on `coworker/requirements.txt` (and the architecture requirements it includes): no known vulnerabilities | Info | none needed |
39
+ | 26 | Dependencies (npm) | `automation/`: 0 advisories with `--omit=dev`. `web/`: `react-router-dom` / `react-router` 6.30.6 matches two moderate advisories (open redirect through a backslash in `<Link>`/`navigate`, GHSA-wrjc-x8rr-h8h6; `deserializeErrors` in SSR hydration, GHSA-337j-9hxr-rhxg) | Low here (the app is a client-only SPA, no SSR; paths passed to `navigate` are fixed in-app routes) | Not fixed: the only patched version is 7.18.x, a major upgrade (breaking). Plan it as its own change |
40
+
41
+ ## Settings added (all safe by default)
42
+
43
+ | Setting | Default | Meaning |
44
+ |---|---|---|
45
+ | `FPT_LOGIN_MAX_PER_USER` | 50 | failed sign-ins for one name from all visitors in the window (300 s) before it is paused; `0` off |
46
+ | `FPT_LOGIN_MAX_PER_IP` | 30 | failed sign-ins from one visitor across all names; only counted when `FPT_TRUST_PROXY=1`; `0` off |
47
+ | `FPT_MAX_BODY_BYTES` | 12000000 | largest request body; `0` off |
48
+ | `FPT_RUNNER_BUNDLE_MAX_MB` | 2048 | largest unpacked runner bundle |
49
+ | `FPT_TRUST_PROXY`, `FPT_API_DOCS` (compose) | `1`, `0` | see findings 2 and 3 |
50
+
51
+ A note on the per-name limit: it also pauses the real owner of the name while it is reached (at most the window, 5 minutes, after
52
+ the last failure), so someone who knows an account name can keep it paused by sending 50 bad tries per window (a denial of
53
+ service on one account, not a break-in). Raise `FPT_LOGIN_MAX_PER_USER` or set it to `0` if that trade is not wanted. The
54
+ break-glass reset (`FPT_ADMIN_PASSWORD_RESET`) is not affected.
55
+
56
+ ## Operator actions
57
+
58
+ 1. Redeploy with the updated `deploy/docker-compose.yml` (or add `FPT_TRUST_PROXY=1` and keep `FPT_API_DOCS` unset in `.env`).
59
+ A redeploy interrupts a running test run: check first.
60
+ 2. Restrict the runner's port to the Astra host and confirm its token is 32+ random characters.
61
+ 3. Delete `FPT_ADMIN_PASSWORD_RESET` from the environment once it has been used.
62
+ 4. Plan the `react-router-dom` 7 upgrade.
docs/SECURITY.md CHANGED
@@ -1,84 +1,87 @@
1
- # Security
2
-
3
- Report a vulnerability privately to the repository owner; do not open a public issue.
4
-
5
- ## Controls in place
6
-
7
- | Area | Control | Where |
8
- |---|---|---|
9
- | Passwords | argon2id; at most `FPT_HASH_CONCURRENCY` hashes at once (memory-exhaustion guard) | `platform/users.py` |
10
- | Sign-in | 5 failed attempts per user and visitor in 5 minutes, then paused; per-visitor through a trusted proxy (`FPT_TRUST_PROXY`) | `platform/users.py`, `__main__.py` |
11
- | Sessions | server-side, httpOnly cookie, SameSite Strict (None only when embedded), Secure behind https; browser-session cookie unless "keep me signed in" (7 days); password change or reset ends other sessions | `api/routes/auth.py` |
12
- | CSRF | double-submit token checked on every unsafe cookie request | `api/auth.py` |
13
- | Authorization | role permissions enforced server-side on every route (`require(perm)`) | `platform/users.py` PERMISSIONS |
14
- | Registration | new accounts are viewers; admin list applies only to confirmed addresses; can be switched off | `api/routes/auth.py`, feature switches |
15
- | Input | pydantic `Strict` models on all request bodies | `api/schemas.py` |
16
- | Output | errors in one format `{detail, code, request_id}`; 500s carry no stack trace | `api/errors.py` |
17
- | Headers | CSP, X-Frame-Options, nosniff, Referrer-Policy, Permissions-Policy, HSTS behind https | `api/middleware.py` |
18
- | CORS | none needed in production (`FPT_CORS_ORIGINS=[]`) | `config.py` |
19
- | Outbound calls | one egress gate, host-pinned, audited, kill switch | `platform/egress.py` |
20
- | Notifications | webhook to the configured host only (https), HMAC-SHA256 signed, retried then given up; payload is plain words, run names, area names and counts, never secrets, test data or screenshots; errors redacted | `platform/notify.py` |
21
- | Telegram notifications | sent only to api.telegram.org through the egress gate; the bot token is a secret (vault / Space secret) that is never logged or returned: the audit shows `api.telegram.org/bot(hidden)/...`, error texts have it removed, and refused requests are audited with the hidden address too; same message content rules as the webhook; only administrators choose the chat | `platform/notify.py` |
22
- | Two-way bot (Telegram, Teams next) | a chat is linked to one Astra account by a one-time code made by that signed-in person (hashed, single use, 10 minutes, 5 tries per 10 minutes); the bot then acts as that person with their role: free text and /run go through the Ask service (propose, then the person's button press re-checks RBAC and state through api/actions.py); buttons carry only a random id, stored server-side and bound to chat, person, 24-hour expiry and single use; sign-off, failure verdicts, the kill switch and administration are never offered (links only); every step audited as `channel.*`; notifications reach a linked person only for runs they may read, from when they linked; the bot token is masked in HTTP client logs as well | `channels/`, `api/routes/channels.py`, docs/CHANNELS.md |
23
- | MCP connector | personal access tokens (`pwt_`, shown once, SHA-256 at rest, compared in constant time, 1 to 365 days, revocable by the owner or an administrator), accepted only on `/mcp` and refused on `/api`; always the owner's current role (disabled owners refused); scopes `read` or `read,act`; acting is propose → `confirm` (single use, 10 minutes, same person and token, re-checks role, run state and the emergency stop); sign-off, verdicts, the emergency stop and administration never offered; 60 requests a minute per token, 64 KB bodies, foreign browser origins refused, no CORS, cookies ignored; tokens masked in logs, never in the audit (`token.*`, `mcp.*` events) | `api/mcp.py`, `platform/api_tokens.py`, docs/MCP.md |
24
- | A2A agent | the same personal access tokens, scopes, per-token rate limit (shared with `/mcp`), origin guard and propose → confirm path as MCP, at `/a2a` (bodies up to 256 KB, 20 parts, 8,000 characters of text, 50 cases); the agent card at `/.well-known/agent-card.json` is public and holds no secrets; tasks are bound to their owner and token (admins can read, not act); a caller can never approve custom cases, scenarios or failures, sign off, waive or touch the emergency stop; caller facts (pod, patch changes) are stored as untrusted data, never sent to an LLM as instructions, and their URLs are displayed only, never fetched; every task, state change, proposal, confirm, run, refusal and cancel is audited as `a2a.*` without tokens | `api/a2a.py`, docs/A2A.md |
25
- | Oracle AI Agent Studio | OAuth 2.0 client credentials (client secret kept as a hash; bearer tokens `pwa_`, one hour, hashed at rest, scope `patchwise.invoke` only: start cycles, forward approvals, read their status); test data must be synthetic and values that look like personal or payment data are refused; callbacks HMAC-signed with the client's signing key (kept in the vault), sent through the egress gate to the client's own address only | `platform/agent_studio.py`, docs/AGENT_STUDIO.md |
26
- | Secrets | `FPT_SECRET_*` environment values or the vault file (plain JSON, mode 600, encrypted only inside the state snapshot: see Residual risks); never in API answers, logs or child processes | `platform/vault.py`, `platform/procs.py` |
27
- | State snapshot | `FPT_HOME` archived and encrypted (Fernet, `FPT_STATE_KEY`) before it leaves; the bucket holds ciphertext only; the OCI pre-authenticated URL is read from the environment or the vault only and audited with its token replaced by `***` | `platform/statesync.py`, `platform/ocistore.py` |
28
- | Remote runner | HTTPS behind Caddy, bearer token compared in constant time, one job at a time, allow-listed environment keys, configs and file names; the token is never passed to Playwright; the Fusion session file is never returned | `automation/remote_runner/server.py`, docs/REMOTE_RUNNER.md |
29
- | AI calls | client data masked before a request leaves and restored in the answer; a payload that still looks like client data is not sent to the external model | `platform/step_writer.py`, `platform/redaction.py`, `llm/router.py` |
30
- | Fusion | production pods refused; read-only except seeding and cancelling test data; password kept out of traces | `platform/pods.py`, `automation/src/fusion/ui.ts` |
31
- | Audit | append-only, hash-chained, verifiable (`/api/audit/verify`) | `platform/audit.py` |
32
- | Public surface | anonymous `/api/ready` shows no internals; API docs off in production | `api/routes/admin.py` |
33
- | Exports | CSV cells that start with `= + - @` are neutralised | `api/routes/runs.py` |
34
-
35
- ## Residual risks
36
-
37
- Risks that remain in the running system, with what limits them today.
38
-
39
- | Risk | Detail | What limits it |
40
- |---|---|---|
41
- | Plain-text vault, and the evidence key in the same archive | The vault (`FPT_HOME/secrets/vault.json`) is a plain JSON file on the server's disk. It holds `EVIDENCE_KEY`, the pods' test-user passwords entered in the app, the AI model key saved in Settings, the link signing key, Agent Studio signing keys and Fusion client secrets, and the chat webhook addresses. The state snapshot and the Compose backup contain both the vault and the encrypted evidence, so whoever can open the archive can also read the evidence. | File mode 600; the snapshot is encrypted with `FPT_STATE_KEY` before it leaves; the Compose backup must be encrypted by the operator. Keep `FPT_STATE_KEY` apart from the bucket's credentials. |
42
- | Snapshot key | Unless `FPT_STATE_KEY` is set, the snapshot key is derived from the Supabase service key (S8). | Set `FPT_STATE_KEY` (required with OCI). |
43
- | Runner token and Fusion password on every attempt | Each attempt and screen read sends the runner token (header) and the Fusion test user's password (body) to the runner over HTTPS. On the runner the password is in the Playwright process's environment. | HTTPS only (egress gate, runner host pinned); the audit log never records the password; a test pod's test user only, never production. Rotate both if the runner host is compromised. |
44
- | Unencrypted job data on the runner | Screenshots, videos, traces, logs and the values tried stay unencrypted in the runner's job folders for `RUNNER_KEEP_HOURS` (24 h), including folders from before a runner restart (swept by age). A killed job may leave the Fusion session file there until the sweep. | The service listens on loopback only, behind Caddy. Keep the runner host single-purpose, with few logins and an encrypted disk. |
45
- | Signed Excel links need no login | The Excel test-script link in Agent Studio events (`/api/share/runs/{id}/test-script.xlsx?exp=...&sig=...`) opens without a login for 7 days. Anyone who has the link can download that one file. | HMAC-signed for one run and one file, read-only, expires; changing `LINK_SIGNING_KEY` in the vault ends every link already sent. |
46
- | Masking before AI calls is pattern-based | `platform/redaction.py` masks e-mail addresses, amounts, document numbers, numbers of 4 digits or more, the client names the scout registered (business units, ledgers, suppliers and other sampled test data) and vault secrets. A client name it does not know, or free text in an unusual shape, is not recognised. Oracle's own screen labels are sent as they are. | Only public or masked payloads go to the external model; a payload the leak check still flags is not sent there. Custom test cases never go to any model. Use a local model when the client does not agree to an external one. |
47
- | Supabase sign-up | Supabase "Confirm email" must stay on for the admin list to be safe (S5). | Keep it on in the Supabase project's settings. |
48
- | Personal tokens in shared agents | A Copilot Studio agent using a personal token acts as that one person for everyone who uses the agent. | Use a `read` token from a least-privileged account until OAuth (docs/MCP.md, phase 2). |
49
- | Dependencies | react-router 6 has two moderate advisories fixed only in 7.x; the open-redirect one is not reachable here (the return path after sign-in is checked). Python dependencies are pinned at top level only; base images are not digest-pinned. | `npm audit` in CI (QUALITY.md). |
50
-
51
- Decisions on the older findings are recorded in [AUDIT.md](AUDIT.md).
52
-
53
- ## Rotating secrets
54
-
55
- Set the new value in the platform's secret store and restart. For the Fusion test user also update the user in
56
- Fusion first. Exposed keys must be revoked at the provider (NVIDIA, Hugging Face, Supabase, OCI), not only replaced here.
57
- For the runner token and `OCI_STATE_PAR_URL`, see RUNBOOK "Rotating secrets".
58
-
59
- ## Incoming-webhook integrations (Slack, Teams, Google Chat, Discord)
60
-
61
- - The webhook address is a bearer credential. It is accepted only from administrators, validated against the service's own
62
- host and path (https, no user info, standard port), stored in the vault, registered with the redactor, and never returned.
63
- - The server log masks webhook paths and query strings for all four services (and Telegram bot tokens) in every line the
64
- HTTP client writes; the audit records only the host. Delivery errors are stored and printed with the address removed.
65
- - Message text from the app is neutralised per service: Slack `& < >` escaped, Google Chat angle brackets replaced, Discord
66
- `allowed_mentions` empty, so nothing the app writes can mention a whole channel or inject links.
67
- - Messages carry run names, areas and counts only (the same outbox rules as the other channels: no secrets, credentials,
68
- test data values or screenshots).
69
-
70
- ## Custom test cases (Excel, text, JSON)
71
-
72
- - Consultants and above only (`run.start`); approving or rejecting needs `gate.approve_cases`, the same as approving
73
- scenarios. Nothing runs before a person approves a scenario whose dry run passed; there is no automatic approval, also
74
- not for agents. A run accepts approved keys only and goes through the normal run path (kill switch included).
75
- - Uploads: `.xlsx` only, at most 2 MB, must be a zip container; opened read-only with cached values only, so formulas are
76
- never evaluated and macros never loaded. The uploaded file name is never used as a path; batch ids are checked against
77
- `[A-Za-z0-9_-]` and area codes against `[A-Z][A-Z0-9]{1,5}`, so staged and promoted paths can't be steered.
78
- - Limits: 50 scenarios × 40 steps per batch, 50,000 characters of text, 500 characters per step. JSON is strict (unknown
79
- fields refuse the batch).
80
- - Custom cases may contain client data, so they are never sent to an AI model (neither frontier nor local): steps are
81
- mapped by a fixed grammar, and steps it can't map are returned to be reworded. Text is stored and returned as data;
82
- the web app renders it escaped.
83
- - Drafts live in `FPT_HOME/staging` until approval. Parsing, building, the dry run, approval, rejection and runs are
84
- audited (`custom_cases.*`).
 
 
 
 
1
+ # Security
2
+
3
+ Report a vulnerability privately to the repository owner; do not open a public issue.
4
+
5
+ ## Controls in place
6
+
7
+ | Area | Control | Where |
8
+ |---|---|---|
9
+ | Passwords | argon2id; at most `FPT_HASH_CONCURRENCY` hashes at once (memory-exhaustion guard) | `platform/users.py` |
10
+ | Sign-in | 5 failed attempts per user and visitor in 5 minutes, then paused; also 50 per name across all visitors (`FPT_LOGIN_MAX_PER_USER`) and, behind a trusted proxy (`FPT_TRUST_PROXY`), 30 per visitor across all names (`FPT_LOGIN_MAX_PER_IP`); failed names that are not accounts are audited as a fingerprint only | `platform/users.py`, `api/routes/auth.py`, `__main__.py` |
11
+ | Request size | bodies over `FPT_MAX_BODY_BYTES` (12 MB) refused with 413, also while streaming; a runner bundle may unpack to at most `FPT_RUNNER_BUNDLE_MAX_MB` (2 GB); `*` in `FPT_CORS_ORIGINS` is ignored | `api/middleware.py`, `adapters/remote_runner.py`, `api/app.py` |
12
+ | Sessions | server-side, httpOnly cookie, SameSite Strict (None only when embedded), Secure behind https; browser-session cookie unless "keep me signed in" (7 days); password change or reset ends other sessions | `api/routes/auth.py` |
13
+ | CSRF | double-submit token checked on every unsafe cookie request | `api/auth.py` |
14
+ | Authorization | role permissions enforced server-side on every route (`require(perm)`) | `platform/users.py` PERMISSIONS |
15
+ | Registration | new accounts are viewers; admin list applies only to confirmed addresses; can be switched off | `api/routes/auth.py`, feature switches |
16
+ | Input | pydantic `Strict` models on all request bodies | `api/schemas.py` |
17
+ | Output | errors in one format `{detail, code, request_id}`; 500s carry no stack trace | `api/errors.py` |
18
+ | Headers | CSP, X-Frame-Options, nosniff, Referrer-Policy, Permissions-Policy, HSTS behind https | `api/middleware.py` |
19
+ | CORS | none needed in production (`FPT_CORS_ORIGINS=[]`) | `config.py` |
20
+ | Outbound calls | one egress gate, host-pinned, audited, kill switch | `platform/egress.py` |
21
+ | Notifications | webhook to the configured host only (https), HMAC-SHA256 signed, retried then given up; payload is plain words, run names, area names and counts, never secrets, test data or screenshots; errors redacted | `platform/notify.py` |
22
+ | Telegram notifications | sent only to api.telegram.org through the egress gate; the bot token is a secret (vault / Space secret) that is never logged or returned: the audit shows `api.telegram.org/bot(hidden)/...`, error texts have it removed, and refused requests are audited with the hidden address too; same message content rules as the webhook; only administrators choose the chat | `platform/notify.py` |
23
+ | Two-way bot (Telegram, Teams next) | a chat is linked to one Astra account by a one-time code made by that signed-in person (hashed, single use, 10 minutes, 5 tries per 10 minutes); the bot then acts as that person with their role: free text and /run go through the Ask service (propose, then the person's button press re-checks RBAC and state through api/actions.py); buttons carry only a random id, stored server-side and bound to chat, person, 24-hour expiry and single use; sign-off, failure verdicts, the kill switch and administration are never offered (links only); every step audited as `channel.*`; notifications reach a linked person only for runs they may read, from when they linked; the bot token is masked in HTTP client logs as well | `channels/`, `api/routes/channels.py`, docs/CHANNELS.md |
24
+ | MCP connector | personal access tokens (`pwt_`, shown once, SHA-256 at rest, compared in constant time, 1 to 365 days, revocable by the owner or an administrator), accepted only on `/mcp` and refused on `/api`; always the owner's current role (disabled owners refused); scopes `read` or `read,act`; acting is propose → `confirm` (single use, 10 minutes, same person and token, re-checks role, run state and the emergency stop); sign-off, verdicts, the emergency stop and administration never offered; 60 requests a minute per token, 64 KB bodies, foreign browser origins refused, no CORS, cookies ignored; tokens masked in logs, never in the audit (`token.*`, `mcp.*` events) | `api/mcp.py`, `platform/api_tokens.py`, docs/MCP.md |
25
+ | A2A agent | the same personal access tokens, scopes, per-token rate limit (shared with `/mcp`), origin guard and propose → confirm path as MCP, at `/a2a` (bodies up to 256 KB, 20 parts, 8,000 characters of text, 50 cases); the agent card at `/.well-known/agent-card.json` is public and holds no secrets; tasks are bound to their owner and token (admins can read, not act); a caller can never approve custom cases, scenarios or failures, sign off, waive or touch the emergency stop; caller facts (pod, patch changes) are stored as untrusted data, never sent to an LLM as instructions, and their URLs are displayed only, never fetched; every task, state change, proposal, confirm, run, refusal and cancel is audited as `a2a.*` without tokens | `api/a2a.py`, docs/A2A.md |
26
+ | Oracle AI Agent Studio | OAuth 2.0 client credentials (client secret kept as a hash; bearer tokens `pwa_`, one hour, hashed at rest, scope `patchwise.invoke` only: start cycles, forward approvals, read their status); test data must be synthetic and values that look like personal or payment data are refused; callbacks HMAC-signed with the client's signing key (kept in the vault), sent through the egress gate to the client's own address only | `platform/agent_studio.py`, docs/AGENT_STUDIO.md |
27
+ | Secrets | `FPT_SECRET_*` environment values or the vault file (plain JSON, mode 600, encrypted only inside the state snapshot: see Residual risks); never in API answers, logs or child processes | `platform/vault.py`, `platform/procs.py` |
28
+ | State snapshot | `FPT_HOME` archived and encrypted (Fernet, `FPT_STATE_KEY`) before it leaves; the bucket holds ciphertext only; the OCI pre-authenticated URL is read from the environment or the vault only and audited with its token replaced by `***` | `platform/statesync.py`, `platform/ocistore.py` |
29
+ | Remote runner | HTTPS behind Caddy, bearer token compared in constant time, one job at a time, allow-listed environment keys, configs and file names; the token is never passed to Playwright; the Fusion session file is never returned | `automation/remote_runner/server.py`, docs/REMOTE_RUNNER.md |
30
+ | AI calls | client data masked before a request leaves and restored in the answer; a payload that still looks like client data is not sent to the external model | `platform/step_writer.py`, `platform/redaction.py`, `llm/router.py` |
31
+ | Fusion | production pods refused; read-only except seeding and cancelling test data; password kept out of traces | `platform/pods.py`, `automation/src/fusion/ui.ts` |
32
+ | Audit | append-only, hash-chained, verifiable (`/api/audit/verify`) | `platform/audit.py` |
33
+ | Public surface | anonymous `/api/ready` shows no internals; API docs off in production | `api/routes/admin.py` |
34
+ | Exports | CSV cells that start with `= + - @` are neutralised | `api/routes/runs.py` |
35
+
36
+ The full review with findings and status: [SECURITY-REVIEW.md](SECURITY-REVIEW.md).
37
+
38
+ ## Residual risks
39
+
40
+ Risks that remain in the running system, with what limits them today.
41
+
42
+ | Risk | Detail | What limits it |
43
+ |---|---|---|
44
+ | Plain-text vault, and the evidence key in the same archive | The vault (`FPT_HOME/secrets/vault.json`) is a plain JSON file on the server's disk. It holds `EVIDENCE_KEY`, the pods' test-user passwords entered in the app, the AI model key saved in Settings, the link signing key, Agent Studio signing keys and Fusion client secrets, and the chat webhook addresses. The state snapshot and the Compose backup contain both the vault and the encrypted evidence, so whoever can open the archive can also read the evidence. | File mode 600; the snapshot is encrypted with `FPT_STATE_KEY` before it leaves; the Compose backup must be encrypted by the operator. Keep `FPT_STATE_KEY` apart from the bucket's credentials. |
45
+ | Snapshot key | Unless `FPT_STATE_KEY` is set, the snapshot key is derived from the Supabase service key (S8). | Set `FPT_STATE_KEY` (required with OCI). |
46
+ | Runner token and Fusion password on every attempt | Each attempt and screen read sends the runner token (header) and the Fusion test user's password (body) to the runner over HTTPS. On the runner the password is in the Playwright process's environment. | HTTPS only (egress gate, runner host pinned); the audit log never records the password; a test pod's test user only, never production. Rotate both if the runner host is compromised. |
47
+ | Unencrypted job data on the runner | Screenshots, videos, traces, logs and the values tried stay unencrypted in the runner's job folders for `RUNNER_KEEP_HOURS` (24 h), including folders from before a runner restart (swept by age). A killed job may leave the Fusion session file there until the sweep. | The service listens on loopback only, behind Caddy. Keep the runner host single-purpose, with few logins and an encrypted disk. |
48
+ | Signed Excel links need no login | The Excel test-script link in Agent Studio events (`/api/share/runs/{id}/test-script.xlsx?exp=...&sig=...`) opens without a login for 7 days. Anyone who has the link can download that one file. | HMAC-signed for one run and one file, read-only, expires; changing `LINK_SIGNING_KEY` in the vault ends every link already sent. |
49
+ | Masking before AI calls is pattern-based | `platform/redaction.py` masks e-mail addresses, amounts, document numbers, numbers of 4 digits or more, the client names the scout registered (business units, ledgers, suppliers and other sampled test data) and vault secrets. A client name it does not know, or free text in an unusual shape, is not recognised. Oracle's own screen labels are sent as they are. | Only public or masked payloads go to the external model; a payload the leak check still flags is not sent there. Custom test cases never go to any model. Use a local model when the client does not agree to an external one. |
50
+ | Supabase sign-up | Supabase "Confirm email" must stay on for the admin list to be safe (S5). | Keep it on in the Supabase project's settings. |
51
+ | Personal tokens in shared agents | A Copilot Studio agent using a personal token acts as that one person for everyone who uses the agent. | Use a `read` token from a least-privileged account until OAuth (docs/MCP.md, phase 2). |
52
+ | Dependencies | react-router 6 has two moderate advisories fixed only in 7.x; the open-redirect one is not reachable here (the return path after sign-in is checked). Python dependencies are pinned at top level only; base images are not digest-pinned. | `npm audit` in CI (QUALITY.md). |
53
+
54
+ Decisions on the older findings are recorded in [AUDIT.md](AUDIT.md).
55
+
56
+ ## Rotating secrets
57
+
58
+ Set the new value in the platform's secret store and restart. For the Fusion test user also update the user in
59
+ Fusion first. Exposed keys must be revoked at the provider (NVIDIA, Hugging Face, Supabase, OCI), not only replaced here.
60
+ For the runner token and `OCI_STATE_PAR_URL`, see RUNBOOK "Rotating secrets".
61
+
62
+ ## Incoming-webhook integrations (Slack, Teams, Google Chat, Discord)
63
+
64
+ - The webhook address is a bearer credential. It is accepted only from administrators, validated against the service's own
65
+ host and path (https, no user info, standard port), stored in the vault, registered with the redactor, and never returned.
66
+ - The server log masks webhook paths and query strings for all four services (and Telegram bot tokens) in every line the
67
+ HTTP client writes; the audit records only the host. Delivery errors are stored and printed with the address removed.
68
+ - Message text from the app is neutralised per service: Slack `& < >` escaped, Google Chat angle brackets replaced, Discord
69
+ `allowed_mentions` empty, so nothing the app writes can mention a whole channel or inject links.
70
+ - Messages carry run names, areas and counts only (the same outbox rules as the other channels: no secrets, credentials,
71
+ test data values or screenshots).
72
+
73
+ ## Custom test cases (Excel, text, JSON)
74
+
75
+ - Consultants and above only (`run.start`); approving or rejecting needs `gate.approve_cases`, the same as approving
76
+ scenarios. Nothing runs before a person approves a scenario whose dry run passed; there is no automatic approval, also
77
+ not for agents. A run accepts approved keys only and goes through the normal run path (kill switch included).
78
+ - Uploads: `.xlsx` only, at most 2 MB, must be a zip container; opened read-only with cached values only, so formulas are
79
+ never evaluated and macros never loaded. The uploaded file name is never used as a path; batch ids are checked against
80
+ `[A-Za-z0-9_-]` and area codes against `[A-Z][A-Z0-9]{1,5}`, so staged and promoted paths can't be steered.
81
+ - Limits: 50 scenarios × 40 steps per batch, 50,000 characters of text, 500 characters per step. JSON is strict (unknown
82
+ fields refuse the batch).
83
+ - Custom cases may contain client data, so they are never sent to an AI model (neither frontier nor local): steps are
84
+ mapped by a fixed grammar, and steps it can't map are returned to be reworded. Text is stored and returned as data;
85
+ the web app renders it escaped.
86
+ - Drafts live in `FPT_HOME/staging` until approval. Parsing, building, the dry run, approval, rejection and runs are
87
+ audited (`custom_cases.*`).
web/src/App.tsx CHANGED
@@ -1,116 +1,118 @@
1
- import { Center, Loader } from '@mantine/core';
2
- import { lazy, Suspense, type ReactNode } from 'react';
3
- import { Navigate, Route, Routes, useLocation, useSearchParams } from 'react-router-dom';
4
- import { AssistantPage } from './pages/insights/AssistantPage';
5
- import { AuthProvider, useAuth } from './auth/AuthContext';
6
- import { Layout } from './components/Layout';
7
- import { AdminOnly } from './components/AdminOnly';
8
- import { NotFoundPage } from './components/ErrorPages';
9
- import { PodsPage } from './pages/setup/PodsPage';
10
- import { ReadinessPage } from './pages/home/ReadinessPage';
11
- import { TicketsPage } from './pages/insights/QueuesPages';
12
- import { RunWorkspace } from './pages/run/RunWorkspace';
13
- import { RunsPage } from './pages/runs/RunsPage';
14
-
15
- // Pages opened less often load on demand, so the first visit downloads less (Home, test runs, environments and defects
16
- // stay in the main bundle: they are the daily path).
17
- const named = <T extends Record<string, unknown>>(load: () => Promise<T>, name: keyof T) =>
18
- lazy(() => load().then((m) => ({ default: m[name] as React.ComponentType })));
19
- const AgentTeamPage = named(() => import('./pages/insights/AgentTeamPage'), 'AgentTeamPage');
20
- const SettingsPage = named(() => import('./pages/setup/SettingsPage'), 'SettingsPage');
21
- const AutonomyPage = named(() => import('./pages/setup/AdminPages'), 'AutonomyPage');
22
- const KillSwitchPage = named(() => import('./pages/setup/AdminPages'), 'KillSwitchPage');
23
- const SchedulerPage = named(() => import('./pages/setup/AdminPages'), 'SchedulerPage');
24
- const UsersPage = named(() => import('./pages/setup/AdminPages'), 'UsersPage');
25
- const AuditPage = named(() => import('./pages/insights/InsightPages'), 'AuditPage');
26
- const LearnerPage = named(() => import('./pages/insights/InsightPages'), 'LearnerPage');
27
- const ReportsPage = named(() => import('./pages/library/LibraryPages'), 'ReportsPage');
28
- const ScenarioDetailPage = named(() => import('./pages/library/LibraryPages'), 'ScenarioDetailPage');
29
- const ScenariosLibraryPage = named(() => import('./pages/library/LibraryPages'), 'ScenariosLibraryPage');
30
- const HealPage = named(() => import('./pages/insights/QueuesPages'), 'HealPage');
31
- const ScriptsPage = named(() => import('./pages/insights/QueuesPages'), 'ScriptsPage');
32
- const AccountPage = named(() => import('./pages/account/AccountPage'), 'AccountPage');
33
- const IntegrationsPage = named(() => import('./pages/setup/IntegrationsPage'), 'IntegrationsPage');
34
- const AgentStudioPage = named(() => import('./pages/setup/AgentStudioPage'), 'AgentStudioPage');
35
- const AiMonitoringPage = named(() => import('./pages/setup/AiMonitoringPage'), 'AiMonitoringPage');
36
- const ImportCasesPage = named(() => import('./pages/library/ImportCasesPage'), 'ImportCasesPage');
37
- // the sign-in page carries the beUI animation library: only people who sign in download it
38
- const LoginPage = named(() => import('./pages/auth/LoginPage'), 'LoginPage');
39
- const RegisterPage = named(() => import('./pages/auth/RegisterPage'), 'RegisterPage');
40
- const ForgotPage = named(() => import('./pages/auth/PasswordPages'), 'ForgotPage');
41
- const ResetPage = named(() => import('./pages/auth/PasswordPages'), 'ResetPage');
42
-
43
- // Dev-only fixture screens for design review; the branch is removed from the production build.
44
- const DevFixtures = import.meta.env.DEV ? lazy(() => import('./pages/dev/DevFixtures').then((m) => ({ default: m.DevFixtures }))) : null;
45
- const DevApprovalFixtures = import.meta.env.DEV ? lazy(() => import('./pages/dev/DevFixtures').then((m) => ({ default: m.DevApprovalFixtures }))) : null;
46
- /** The fixture routes this build registers (none outside dev builds). */
47
- export const DEV_FIXTURE_PATHS: string[] = import.meta.env.DEV ? ['/dev/board-fixture', '/dev/approval-fixture'] : [];
48
-
49
- /** The account pages (sign in, register, forgot, reset) load on demand: they carry the beUI and 3D libraries. */
50
- function SignInRoute({ children }: { children: ReactNode }) {
51
- return <Suspense fallback={<Center h="100vh" bg="#0a0a0c"><Loader color="gray" aria-label="Loading" /></Center>}>{children}</Suspense>;
52
- }
53
-
54
- function RequireAuth({ children }: { children: ReactNode }) {
55
- const { user, loading } = useAuth();
56
- const loc = useLocation();
57
- if (loading) return <Center h="100vh"><Loader aria-label="loading" /></Center>;
58
- if (!user) return <Navigate to="/login" replace state={{ from: loc.pathname }} />;
59
- return <>{children}</>;
60
- }
61
-
62
- /** The old "new test run" page is now the Start sheet over the home page. */
63
- function NewRunRedirect() {
64
- const [p] = useSearchParams();
65
- const area = p.get('area');
66
- return <Navigate to={`/?new=1${area ? `&area=${encodeURIComponent(area)}` : ''}`} replace />;
67
- }
68
-
69
- export function AppRoutes() {
70
- return (
71
- <Routes>
72
- <Route path="/login" element={<SignInRoute><LoginPage /></SignInRoute>} />
73
- <Route path="/register" element={<SignInRoute><RegisterPage /></SignInRoute>} />
74
- <Route path="/forgot" element={<SignInRoute><ForgotPage /></SignInRoute>} />
75
- <Route path="/reset" element={<SignInRoute><ResetPage /></SignInRoute>} />
76
- <Route element={<RequireAuth><Layout /></RequireAuth>}>
77
- <Route index element={<ReadinessPage />} />
78
- <Route path="/runs" element={<RunsPage />} />
79
- <Route path="/runs/new" element={<NewRunRedirect />} />
80
- <Route path="/runs/:id" element={<RunWorkspace />} />
81
- <Route path="/runs/:id/:tab" element={<RunWorkspace />} />
82
- <Route path="/assistant" element={<AssistantPage />} />
83
- <Route path="/assistant/:id" element={<AssistantPage />} />
84
- <Route path="/scenarios" element={<ScenariosLibraryPage />} />
85
- <Route path="/scenarios/import" element={<ImportCasesPage />} />
86
- <Route path="/scenarios/:id" element={<ScenarioDetailPage />} />
87
- <Route path="/tickets" element={<TicketsPage />} />
88
- <Route path="/pods" element={<PodsPage />} />
89
- <Route path="/reports" element={<ReportsPage />} />
90
- <Route path="/account" element={<AccountPage />} />
91
- {/* Admin & under the hood (engineering views) */}
92
- <Route path="/admin" element={<AdminOnly><SettingsPage /></AdminOnly>} />
93
- <Route path="/agents" element={<AdminOnly title="Agent team"><AgentTeamPage /></AdminOnly>} />
94
- <Route path="/heal" element={<AdminOnly title="Self-heal review"><HealPage /></AdminOnly>} />
95
- <Route path="/scripts" element={<AdminOnly title="Scripts and drafts"><ScriptsPage /></AdminOnly>} />
96
- <Route path="/learner" element={<AdminOnly title="Learner"><LearnerPage /></AdminOnly>} />
97
- <Route path="/audit" element={<AdminOnly title="Audit log"><AuditPage /></AdminOnly>} />
98
- <Route path="/admin/kill-switch" element={<AdminOnly title="Emergency stop"><KillSwitchPage /></AdminOnly>} />
99
- <Route path="/admin/autonomy" element={<AdminOnly title="Automatic approval"><AutonomyPage /></AdminOnly>} />
100
- <Route path="/admin/scheduler" element={<AdminOnly title="Scheduled runs"><SchedulerPage /></AdminOnly>} />
101
- <Route path="/schedules" element={<AdminOnly title="Scheduled runs"><SchedulerPage /></AdminOnly>} />
102
- <Route path="/admin/users" element={<AdminOnly title="Users"><UsersPage /></AdminOnly>} />
103
- <Route path="/integrations" element={<AdminOnly title="Integrations"><IntegrationsPage /></AdminOnly>} />
104
- <Route path="/agent-studio" element={<AdminOnly title="Oracle AI Agent Studio"><AgentStudioPage /></AdminOnly>} />
105
- <Route path="/ai-monitoring" element={<AdminOnly title="AI monitoring"><AiMonitoringPage /></AdminOnly>} />
106
- {DevFixtures && DEV_FIXTURE_PATHS.includes('/dev/board-fixture') && <Route path="/dev/board-fixture" element={<Suspense fallback={null}><DevFixtures /></Suspense>} />}
107
- {DevApprovalFixtures && DEV_FIXTURE_PATHS.includes('/dev/approval-fixture') && <Route path="/dev/approval-fixture" element={<Suspense fallback={null}><DevApprovalFixtures /></Suspense>} />}
108
- <Route path="*" element={<NotFoundPage />} />
109
- </Route>
110
- </Routes>
111
- );
112
- }
113
-
114
- export function App() {
115
- return <AuthProvider><AppRoutes /></AuthProvider>;
116
- }
 
 
 
1
+ import { Center, Loader } from '@mantine/core';
2
+ import { lazy, Suspense, type ReactNode } from 'react';
3
+ import { Navigate, Route, Routes, useLocation, useSearchParams } from 'react-router-dom';
4
+ import { AssistantPage } from './pages/insights/AssistantPage';
5
+ import { AuthProvider, useAuth } from './auth/AuthContext';
6
+ import { Layout } from './components/Layout';
7
+ import { AdminOnly } from './components/AdminOnly';
8
+ import { NotFoundPage } from './components/ErrorPages';
9
+ import { PodsPage } from './pages/setup/PodsPage';
10
+ import { ReadinessPage } from './pages/home/ReadinessPage';
11
+ import { TicketsPage } from './pages/insights/QueuesPages';
12
+ import { RunWorkspace } from './pages/run/RunWorkspace';
13
+ import { RunsPage } from './pages/runs/RunsPage';
14
+
15
+ // Pages opened less often load on demand, so the first visit downloads less (Home, test runs, environments and defects
16
+ // stay in the main bundle: they are the daily path).
17
+ const named = <T extends Record<string, unknown>>(load: () => Promise<T>, name: keyof T) =>
18
+ lazy(() => load().then((m) => ({ default: m[name] as React.ComponentType })));
19
+ const AgentTeamPage = named(() => import('./pages/insights/AgentTeamPage'), 'AgentTeamPage');
20
+ const SettingsPage = named(() => import('./pages/setup/SettingsPage'), 'SettingsPage');
21
+ const AutonomyPage = named(() => import('./pages/setup/AdminPages'), 'AutonomyPage');
22
+ const KillSwitchPage = named(() => import('./pages/setup/AdminPages'), 'KillSwitchPage');
23
+ const SchedulerPage = named(() => import('./pages/setup/AdminPages'), 'SchedulerPage');
24
+ const UsersPage = named(() => import('./pages/setup/AdminPages'), 'UsersPage');
25
+ const AuditPage = named(() => import('./pages/insights/InsightPages'), 'AuditPage');
26
+ const LearnerPage = named(() => import('./pages/insights/InsightPages'), 'LearnerPage');
27
+ const ReportsPage = named(() => import('./pages/library/LibraryPages'), 'ReportsPage');
28
+ const ScenarioDetailPage = named(() => import('./pages/library/LibraryPages'), 'ScenarioDetailPage');
29
+ const ScenariosLibraryPage = named(() => import('./pages/library/LibraryPages'), 'ScenariosLibraryPage');
30
+ const HealPage = named(() => import('./pages/insights/QueuesPages'), 'HealPage');
31
+ const ScriptsPage = named(() => import('./pages/insights/QueuesPages'), 'ScriptsPage');
32
+ const AccountPage = named(() => import('./pages/account/AccountPage'), 'AccountPage');
33
+ const IntegrationsPage = named(() => import('./pages/setup/IntegrationsPage'), 'IntegrationsPage');
34
+ const LeftOnPodPage = named(() => import('./pages/setup/LeftOnPodPage'), 'LeftOnPodPage');
35
+ const AgentStudioPage = named(() => import('./pages/setup/AgentStudioPage'), 'AgentStudioPage');
36
+ const AiMonitoringPage = named(() => import('./pages/setup/AiMonitoringPage'), 'AiMonitoringPage');
37
+ const ImportCasesPage = named(() => import('./pages/library/ImportCasesPage'), 'ImportCasesPage');
38
+ // the sign-in page carries the beUI animation library: only people who sign in download it
39
+ const LoginPage = named(() => import('./pages/auth/LoginPage'), 'LoginPage');
40
+ const RegisterPage = named(() => import('./pages/auth/RegisterPage'), 'RegisterPage');
41
+ const ForgotPage = named(() => import('./pages/auth/PasswordPages'), 'ForgotPage');
42
+ const ResetPage = named(() => import('./pages/auth/PasswordPages'), 'ResetPage');
43
+
44
+ // Dev-only fixture screens for design review; the branch is removed from the production build.
45
+ const DevFixtures = import.meta.env.DEV ? lazy(() => import('./pages/dev/DevFixtures').then((m) => ({ default: m.DevFixtures }))) : null;
46
+ const DevApprovalFixtures = import.meta.env.DEV ? lazy(() => import('./pages/dev/DevFixtures').then((m) => ({ default: m.DevApprovalFixtures }))) : null;
47
+ /** The fixture routes this build registers (none outside dev builds). */
48
+ export const DEV_FIXTURE_PATHS: string[] = import.meta.env.DEV ? ['/dev/board-fixture', '/dev/approval-fixture'] : [];
49
+
50
+ /** The account pages (sign in, register, forgot, reset) load on demand: they carry the beUI and 3D libraries. */
51
+ function SignInRoute({ children }: { children: ReactNode }) {
52
+ return <Suspense fallback={<Center h="100vh" bg="#0a0a0c"><Loader color="gray" aria-label="Loading" /></Center>}>{children}</Suspense>;
53
+ }
54
+
55
+ function RequireAuth({ children }: { children: ReactNode }) {
56
+ const { user, loading } = useAuth();
57
+ const loc = useLocation();
58
+ if (loading) return <Center h="100vh"><Loader aria-label="loading" /></Center>;
59
+ if (!user) return <Navigate to="/login" replace state={{ from: loc.pathname }} />;
60
+ return <>{children}</>;
61
+ }
62
+
63
+ /** The old "new test run" page is now the Start sheet over the home page. */
64
+ function NewRunRedirect() {
65
+ const [p] = useSearchParams();
66
+ const area = p.get('area');
67
+ return <Navigate to={`/?new=1${area ? `&area=${encodeURIComponent(area)}` : ''}`} replace />;
68
+ }
69
+
70
+ export function AppRoutes() {
71
+ return (
72
+ <Routes>
73
+ <Route path="/login" element={<SignInRoute><LoginPage /></SignInRoute>} />
74
+ <Route path="/register" element={<SignInRoute><RegisterPage /></SignInRoute>} />
75
+ <Route path="/forgot" element={<SignInRoute><ForgotPage /></SignInRoute>} />
76
+ <Route path="/reset" element={<SignInRoute><ResetPage /></SignInRoute>} />
77
+ <Route element={<RequireAuth><Layout /></RequireAuth>}>
78
+ <Route index element={<ReadinessPage />} />
79
+ <Route path="/runs" element={<RunsPage />} />
80
+ <Route path="/runs/new" element={<NewRunRedirect />} />
81
+ <Route path="/runs/:id" element={<RunWorkspace />} />
82
+ <Route path="/runs/:id/:tab" element={<RunWorkspace />} />
83
+ <Route path="/assistant" element={<AssistantPage />} />
84
+ <Route path="/assistant/:id" element={<AssistantPage />} />
85
+ <Route path="/scenarios" element={<ScenariosLibraryPage />} />
86
+ <Route path="/scenarios/import" element={<ImportCasesPage />} />
87
+ <Route path="/scenarios/:id" element={<ScenarioDetailPage />} />
88
+ <Route path="/tickets" element={<TicketsPage />} />
89
+ <Route path="/pods" element={<PodsPage />} />
90
+ <Route path="/pods/left" element={<LeftOnPodPage />} />
91
+ <Route path="/reports" element={<ReportsPage />} />
92
+ <Route path="/account" element={<AccountPage />} />
93
+ {/* Admin & under the hood (engineering views) */}
94
+ <Route path="/admin" element={<AdminOnly><SettingsPage /></AdminOnly>} />
95
+ <Route path="/agents" element={<AdminOnly title="Agent team"><AgentTeamPage /></AdminOnly>} />
96
+ <Route path="/heal" element={<AdminOnly title="Self-heal review"><HealPage /></AdminOnly>} />
97
+ <Route path="/scripts" element={<AdminOnly title="Scripts and drafts"><ScriptsPage /></AdminOnly>} />
98
+ <Route path="/learner" element={<AdminOnly title="Learner"><LearnerPage /></AdminOnly>} />
99
+ <Route path="/audit" element={<AdminOnly title="Audit log"><AuditPage /></AdminOnly>} />
100
+ <Route path="/admin/kill-switch" element={<AdminOnly title="Emergency stop"><KillSwitchPage /></AdminOnly>} />
101
+ <Route path="/admin/autonomy" element={<AdminOnly title="Automatic approval"><AutonomyPage /></AdminOnly>} />
102
+ <Route path="/admin/scheduler" element={<AdminOnly title="Scheduled runs"><SchedulerPage /></AdminOnly>} />
103
+ <Route path="/schedules" element={<AdminOnly title="Scheduled runs"><SchedulerPage /></AdminOnly>} />
104
+ <Route path="/admin/users" element={<AdminOnly title="Users"><UsersPage /></AdminOnly>} />
105
+ <Route path="/integrations" element={<AdminOnly title="Integrations"><IntegrationsPage /></AdminOnly>} />
106
+ <Route path="/agent-studio" element={<AdminOnly title="Oracle AI Agent Studio"><AgentStudioPage /></AdminOnly>} />
107
+ <Route path="/ai-monitoring" element={<AdminOnly title="AI monitoring"><AiMonitoringPage /></AdminOnly>} />
108
+ {DevFixtures && DEV_FIXTURE_PATHS.includes('/dev/board-fixture') && <Route path="/dev/board-fixture" element={<Suspense fallback={null}><DevFixtures /></Suspense>} />}
109
+ {DevApprovalFixtures && DEV_FIXTURE_PATHS.includes('/dev/approval-fixture') && <Route path="/dev/approval-fixture" element={<Suspense fallback={null}><DevApprovalFixtures /></Suspense>} />}
110
+ <Route path="*" element={<NotFoundPage />} />
111
+ </Route>
112
+ </Routes>
113
+ );
114
+ }
115
+
116
+ export function App() {
117
+ return <AuthProvider><AppRoutes /></AuthProvider>;
118
+ }
web/src/api/hooks.ts CHANGED
@@ -163,6 +163,29 @@ export const usePods = () => useQuery({
163
  refetchInterval: (q) => ((q.state.data ?? []).some((p) => (p.screens as { state?: string } | null | undefined)?.state === 'running') ? 5000 : false),
164
  });
165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  // how the client uses each business area of a Fusion pod, and which used variants the scenario library covers
167
  export const usePodUsage = (id: number, enabled = true) => useQuery({
168
  queryKey: ['pod-usage', id], enabled, queryFn: () => unwrap(api.GET('/api/pods/{pod_id}/usage', { params: { path: { pod_id: id } } })),
 
163
  refetchInterval: (q) => ((q.state.data ?? []).some((p) => (p.screens as { state?: string } | null | undefined)?.state === 'running') ? 5000 : false),
164
  });
165
 
166
+ // test documents a run left on a Fusion pod that only a person can undo (the "Left on the pod" page)
167
+ export type LeftDoc = Schemas['LeftOnPodRow'];
168
+ export type LeftFilters = { pod_id?: number; status?: LeftDoc['status']; kind?: string };
169
+ export const useLeftOnPod = (f: LeftFilters) => useQuery({
170
+ queryKey: ['left-on-pod', f],
171
+ queryFn: () => unwrap(api.GET('/api/left-on-pod', { params: { query: { limit: 500, ...(f.pod_id ? { pod_id: f.pod_id } : {}), ...(f.status ? { status: f.status } : {}), ...(f.kind ? { kind: f.kind } : {}) } } })),
172
+ });
173
+ export function useLeftOnPodActions() {
174
+ const qc = useQueryClient();
175
+ const done = () => Promise.all([qc.invalidateQueries({ queryKey: ['left-on-pod'] }), qc.invalidateQueries({ queryKey: ['pods'] })]);
176
+ return {
177
+ decide: useMutation({
178
+ mutationFn: ({ id, decision, note }: { id: number; decision: 'done' | 'dismiss' | 'reopen'; note?: string }) =>
179
+ unwrap(api.POST('/api/left-on-pod/{row_id}/decision', { params: { path: { row_id: id } }, body: { decision, note: note || null } })),
180
+ onSuccess: done,
181
+ }),
182
+ recheck: useMutation({
183
+ mutationFn: (id: number) => unwrap(api.POST('/api/left-on-pod/{row_id}/recheck', { params: { path: { row_id: id } } })),
184
+ onSuccess: done,
185
+ }),
186
+ };
187
+ }
188
+
189
  // how the client uses each business area of a Fusion pod, and which used variants the scenario library covers
190
  export const usePodUsage = (id: number, enabled = true) => useQuery({
191
  queryKey: ['pod-usage', id], enabled, queryFn: () => unwrap(api.GET('/api/pods/{pod_id}/usage', { params: { path: { pod_id: id } } })),
web/src/api/openapi.json CHANGED
@@ -1587,6 +1587,193 @@
1587
  "title": "LastDelivery",
1588
  "type": "object"
1589
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1590
  "LeftTestData": {
1591
  "properties": {
1592
  "number": {
@@ -1871,6 +2058,37 @@
1871
  "title": "NotificationSettings",
1872
  "type": "object"
1873
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1874
  "Page_RunSummary_": {
1875
  "properties": {
1876
  "items": {
@@ -2445,6 +2663,11 @@
2445
  ],
2446
  "title": "Last Check Ok"
2447
  },
 
 
 
 
 
2448
  "modules": {
2449
  "items": {
2450
  "type": "string"
@@ -9257,6 +9480,223 @@
9257
  ]
9258
  }
9259
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9260
  "/api/library/log": {
9261
  "get": {
9262
  "operationId": "library_log_api_library_log_get",
 
1587
  "title": "LastDelivery",
1588
  "type": "object"
1589
  },
1590
+ "LeftDecisionIn": {
1591
+ "additionalProperties": false,
1592
+ "properties": {
1593
+ "decision": {
1594
+ "enum": [
1595
+ "done",
1596
+ "dismiss",
1597
+ "reopen"
1598
+ ],
1599
+ "title": "Decision",
1600
+ "type": "string"
1601
+ },
1602
+ "note": {
1603
+ "anyOf": [
1604
+ {
1605
+ "maxLength": 1000,
1606
+ "type": "string"
1607
+ },
1608
+ {
1609
+ "type": "null"
1610
+ }
1611
+ ],
1612
+ "title": "Note"
1613
+ }
1614
+ },
1615
+ "required": [
1616
+ "decision"
1617
+ ],
1618
+ "title": "LeftDecisionIn",
1619
+ "type": "object"
1620
+ },
1621
+ "LeftOnPodRow": {
1622
+ "properties": {
1623
+ "check_detail": {
1624
+ "anyOf": [
1625
+ {
1626
+ "type": "string"
1627
+ },
1628
+ {
1629
+ "type": "null"
1630
+ }
1631
+ ],
1632
+ "title": "Check Detail"
1633
+ },
1634
+ "check_state": {
1635
+ "anyOf": [
1636
+ {
1637
+ "enum": [
1638
+ "still_on_pod",
1639
+ "looks_resolved",
1640
+ "unknown"
1641
+ ],
1642
+ "type": "string"
1643
+ },
1644
+ {
1645
+ "type": "null"
1646
+ }
1647
+ ],
1648
+ "title": "Check State"
1649
+ },
1650
+ "checked_at": {
1651
+ "anyOf": [
1652
+ {
1653
+ "type": "string"
1654
+ },
1655
+ {
1656
+ "type": "null"
1657
+ }
1658
+ ],
1659
+ "title": "Checked At"
1660
+ },
1661
+ "created_at": {
1662
+ "title": "Created At",
1663
+ "type": "string"
1664
+ },
1665
+ "decided_at": {
1666
+ "anyOf": [
1667
+ {
1668
+ "type": "string"
1669
+ },
1670
+ {
1671
+ "type": "null"
1672
+ }
1673
+ ],
1674
+ "title": "Decided At"
1675
+ },
1676
+ "decided_by": {
1677
+ "anyOf": [
1678
+ {
1679
+ "type": "string"
1680
+ },
1681
+ {
1682
+ "type": "null"
1683
+ }
1684
+ ],
1685
+ "title": "Decided By"
1686
+ },
1687
+ "id": {
1688
+ "title": "Id",
1689
+ "type": "integer"
1690
+ },
1691
+ "kind": {
1692
+ "title": "Kind",
1693
+ "type": "string"
1694
+ },
1695
+ "note": {
1696
+ "anyOf": [
1697
+ {
1698
+ "type": "string"
1699
+ },
1700
+ {
1701
+ "type": "null"
1702
+ }
1703
+ ],
1704
+ "title": "Note"
1705
+ },
1706
+ "pod_id": {
1707
+ "title": "Pod Id",
1708
+ "type": "integer"
1709
+ },
1710
+ "pod_name": {
1711
+ "anyOf": [
1712
+ {
1713
+ "type": "string"
1714
+ },
1715
+ {
1716
+ "type": "null"
1717
+ }
1718
+ ],
1719
+ "title": "Pod Name"
1720
+ },
1721
+ "recorded_at": {
1722
+ "title": "Recorded At",
1723
+ "type": "string"
1724
+ },
1725
+ "reference": {
1726
+ "title": "Reference",
1727
+ "type": "string"
1728
+ },
1729
+ "run_id": {
1730
+ "title": "Run Id",
1731
+ "type": "string"
1732
+ },
1733
+ "scenario": {
1734
+ "anyOf": [
1735
+ {
1736
+ "type": "string"
1737
+ },
1738
+ {
1739
+ "type": "null"
1740
+ }
1741
+ ],
1742
+ "title": "Scenario"
1743
+ },
1744
+ "status": {
1745
+ "enum": [
1746
+ "open",
1747
+ "done",
1748
+ "dismissed"
1749
+ ],
1750
+ "title": "Status",
1751
+ "type": "string"
1752
+ },
1753
+ "todo": {
1754
+ "title": "Todo",
1755
+ "type": "string"
1756
+ },
1757
+ "why": {
1758
+ "title": "Why",
1759
+ "type": "string"
1760
+ }
1761
+ },
1762
+ "required": [
1763
+ "id",
1764
+ "pod_id",
1765
+ "run_id",
1766
+ "kind",
1767
+ "reference",
1768
+ "why",
1769
+ "todo",
1770
+ "created_at",
1771
+ "recorded_at",
1772
+ "status"
1773
+ ],
1774
+ "title": "LeftOnPodRow",
1775
+ "type": "object"
1776
+ },
1777
  "LeftTestData": {
1778
  "properties": {
1779
  "number": {
 
2058
  "title": "NotificationSettings",
2059
  "type": "object"
2060
  },
2061
+ "Page_LeftOnPodRow_": {
2062
+ "properties": {
2063
+ "items": {
2064
+ "items": {
2065
+ "$ref": "#/components/schemas/LeftOnPodRow"
2066
+ },
2067
+ "title": "Items",
2068
+ "type": "array"
2069
+ },
2070
+ "limit": {
2071
+ "title": "Limit",
2072
+ "type": "integer"
2073
+ },
2074
+ "offset": {
2075
+ "title": "Offset",
2076
+ "type": "integer"
2077
+ },
2078
+ "total": {
2079
+ "title": "Total",
2080
+ "type": "integer"
2081
+ }
2082
+ },
2083
+ "required": [
2084
+ "items",
2085
+ "total",
2086
+ "limit",
2087
+ "offset"
2088
+ ],
2089
+ "title": "Page[LeftOnPodRow]",
2090
+ "type": "object"
2091
+ },
2092
  "Page_RunSummary_": {
2093
  "properties": {
2094
  "items": {
 
2663
  ],
2664
  "title": "Last Check Ok"
2665
  },
2666
+ "left_open": {
2667
+ "default": 0,
2668
+ "title": "Left Open",
2669
+ "type": "integer"
2670
+ },
2671
  "modules": {
2672
  "items": {
2673
  "type": "string"
 
9480
  ]
9481
  }
9482
  },
9483
+ "/api/left-on-pod": {
9484
+ "get": {
9485
+ "operationId": "left_list_api_left_on_pod_get",
9486
+ "parameters": [
9487
+ {
9488
+ "in": "query",
9489
+ "name": "pod_id",
9490
+ "required": false,
9491
+ "schema": {
9492
+ "anyOf": [
9493
+ {
9494
+ "type": "integer"
9495
+ },
9496
+ {
9497
+ "type": "null"
9498
+ }
9499
+ ],
9500
+ "title": "Pod Id"
9501
+ }
9502
+ },
9503
+ {
9504
+ "in": "query",
9505
+ "name": "status",
9506
+ "required": false,
9507
+ "schema": {
9508
+ "anyOf": [
9509
+ {
9510
+ "pattern": "^(open|done|dismissed)$",
9511
+ "type": "string"
9512
+ },
9513
+ {
9514
+ "type": "null"
9515
+ }
9516
+ ],
9517
+ "title": "Status"
9518
+ }
9519
+ },
9520
+ {
9521
+ "in": "query",
9522
+ "name": "kind",
9523
+ "required": false,
9524
+ "schema": {
9525
+ "anyOf": [
9526
+ {
9527
+ "pattern": "^(ap_invoice|po_requisition|po_order|po_receipt|gl_journal|ar_transaction|ar_receipt)$",
9528
+ "type": "string"
9529
+ },
9530
+ {
9531
+ "type": "null"
9532
+ }
9533
+ ],
9534
+ "title": "Kind"
9535
+ }
9536
+ },
9537
+ {
9538
+ "in": "query",
9539
+ "name": "run_id",
9540
+ "required": false,
9541
+ "schema": {
9542
+ "anyOf": [
9543
+ {
9544
+ "type": "string"
9545
+ },
9546
+ {
9547
+ "type": "null"
9548
+ }
9549
+ ],
9550
+ "title": "Run Id"
9551
+ }
9552
+ },
9553
+ {
9554
+ "in": "query",
9555
+ "name": "limit",
9556
+ "required": false,
9557
+ "schema": {
9558
+ "default": 100,
9559
+ "maximum": 500,
9560
+ "minimum": 1,
9561
+ "title": "Limit",
9562
+ "type": "integer"
9563
+ }
9564
+ },
9565
+ {
9566
+ "in": "query",
9567
+ "name": "offset",
9568
+ "required": false,
9569
+ "schema": {
9570
+ "default": 0,
9571
+ "minimum": 0,
9572
+ "title": "Offset",
9573
+ "type": "integer"
9574
+ }
9575
+ }
9576
+ ],
9577
+ "responses": {
9578
+ "200": {
9579
+ "content": {
9580
+ "application/json": {
9581
+ "schema": {
9582
+ "$ref": "#/components/schemas/Page_LeftOnPodRow_"
9583
+ }
9584
+ }
9585
+ },
9586
+ "description": "Successful Response"
9587
+ },
9588
+ "422": {
9589
+ "content": {
9590
+ "application/json": {
9591
+ "schema": {
9592
+ "$ref": "#/components/schemas/HTTPValidationError"
9593
+ }
9594
+ }
9595
+ },
9596
+ "description": "Validation Error"
9597
+ }
9598
+ },
9599
+ "summary": "Left List",
9600
+ "tags": [
9601
+ "left-on-pod"
9602
+ ]
9603
+ }
9604
+ },
9605
+ "/api/left-on-pod/{row_id}/decision": {
9606
+ "post": {
9607
+ "operationId": "left_decide_api_left_on_pod__row_id__decision_post",
9608
+ "parameters": [
9609
+ {
9610
+ "in": "path",
9611
+ "name": "row_id",
9612
+ "required": true,
9613
+ "schema": {
9614
+ "title": "Row Id",
9615
+ "type": "integer"
9616
+ }
9617
+ }
9618
+ ],
9619
+ "requestBody": {
9620
+ "content": {
9621
+ "application/json": {
9622
+ "schema": {
9623
+ "$ref": "#/components/schemas/LeftDecisionIn"
9624
+ }
9625
+ }
9626
+ },
9627
+ "required": true
9628
+ },
9629
+ "responses": {
9630
+ "200": {
9631
+ "content": {
9632
+ "application/json": {
9633
+ "schema": {
9634
+ "$ref": "#/components/schemas/LeftOnPodRow"
9635
+ }
9636
+ }
9637
+ },
9638
+ "description": "Successful Response"
9639
+ },
9640
+ "422": {
9641
+ "content": {
9642
+ "application/json": {
9643
+ "schema": {
9644
+ "$ref": "#/components/schemas/HTTPValidationError"
9645
+ }
9646
+ }
9647
+ },
9648
+ "description": "Validation Error"
9649
+ }
9650
+ },
9651
+ "summary": "Left Decide",
9652
+ "tags": [
9653
+ "left-on-pod"
9654
+ ]
9655
+ }
9656
+ },
9657
+ "/api/left-on-pod/{row_id}/recheck": {
9658
+ "post": {
9659
+ "description": "Look at the pod again with GET requests only: still there, or looks resolved. Changes nothing on the pod.",
9660
+ "operationId": "left_recheck_api_left_on_pod__row_id__recheck_post",
9661
+ "parameters": [
9662
+ {
9663
+ "in": "path",
9664
+ "name": "row_id",
9665
+ "required": true,
9666
+ "schema": {
9667
+ "title": "Row Id",
9668
+ "type": "integer"
9669
+ }
9670
+ }
9671
+ ],
9672
+ "responses": {
9673
+ "200": {
9674
+ "content": {
9675
+ "application/json": {
9676
+ "schema": {
9677
+ "$ref": "#/components/schemas/LeftOnPodRow"
9678
+ }
9679
+ }
9680
+ },
9681
+ "description": "Successful Response"
9682
+ },
9683
+ "422": {
9684
+ "content": {
9685
+ "application/json": {
9686
+ "schema": {
9687
+ "$ref": "#/components/schemas/HTTPValidationError"
9688
+ }
9689
+ }
9690
+ },
9691
+ "description": "Validation Error"
9692
+ }
9693
+ },
9694
+ "summary": "Left Recheck",
9695
+ "tags": [
9696
+ "left-on-pod"
9697
+ ]
9698
+ }
9699
+ },
9700
  "/api/library/log": {
9701
  "get": {
9702
  "operationId": "library_log_api_library_log_get",
web/src/api/schema.d.ts CHANGED
@@ -1573,6 +1573,60 @@ export interface paths {
1573
  patch?: never;
1574
  trace?: never;
1575
  };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1576
  "/api/library/log": {
1577
  parameters: {
1578
  query?: never;
@@ -3556,6 +3610,58 @@ export interface components {
3556
  /** Status */
3557
  status?: number | null;
3558
  };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3559
  /** LeftTestData */
3560
  LeftTestData: {
3561
  /** Number */
@@ -3644,6 +3750,17 @@ export interface components {
3644
  /** Webhook Host */
3645
  webhook_host?: string | null;
3646
  };
 
 
 
 
 
 
 
 
 
 
 
3647
  /** Page[RunSummary] */
3648
  Page_RunSummary_: {
3649
  /** Items */
@@ -3843,6 +3960,11 @@ export interface components {
3843
  last_check_detail?: string | null;
3844
  /** Last Check Ok */
3845
  last_check_ok?: boolean | null;
 
 
 
 
 
3846
  /** Modules */
3847
  modules: string[];
3848
  /** Name */
@@ -7541,6 +7663,108 @@ export interface operations {
7541
  };
7542
  };
7543
  };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7544
  library_log_api_library_log_get: {
7545
  parameters: {
7546
  query?: {
 
1573
  patch?: never;
1574
  trace?: never;
1575
  };
1576
+ "/api/left-on-pod": {
1577
+ parameters: {
1578
+ query?: never;
1579
+ header?: never;
1580
+ path?: never;
1581
+ cookie?: never;
1582
+ };
1583
+ /** Left List */
1584
+ get: operations["left_list_api_left_on_pod_get"];
1585
+ put?: never;
1586
+ post?: never;
1587
+ delete?: never;
1588
+ options?: never;
1589
+ head?: never;
1590
+ patch?: never;
1591
+ trace?: never;
1592
+ };
1593
+ "/api/left-on-pod/{row_id}/decision": {
1594
+ parameters: {
1595
+ query?: never;
1596
+ header?: never;
1597
+ path?: never;
1598
+ cookie?: never;
1599
+ };
1600
+ get?: never;
1601
+ put?: never;
1602
+ /** Left Decide */
1603
+ post: operations["left_decide_api_left_on_pod__row_id__decision_post"];
1604
+ delete?: never;
1605
+ options?: never;
1606
+ head?: never;
1607
+ patch?: never;
1608
+ trace?: never;
1609
+ };
1610
+ "/api/left-on-pod/{row_id}/recheck": {
1611
+ parameters: {
1612
+ query?: never;
1613
+ header?: never;
1614
+ path?: never;
1615
+ cookie?: never;
1616
+ };
1617
+ get?: never;
1618
+ put?: never;
1619
+ /**
1620
+ * Left Recheck
1621
+ * @description Look at the pod again with GET requests only: still there, or looks resolved. Changes nothing on the pod.
1622
+ */
1623
+ post: operations["left_recheck_api_left_on_pod__row_id__recheck_post"];
1624
+ delete?: never;
1625
+ options?: never;
1626
+ head?: never;
1627
+ patch?: never;
1628
+ trace?: never;
1629
+ };
1630
  "/api/library/log": {
1631
  parameters: {
1632
  query?: never;
 
3610
  /** Status */
3611
  status?: number | null;
3612
  };
3613
+ /** LeftDecisionIn */
3614
+ LeftDecisionIn: {
3615
+ /**
3616
+ * Decision
3617
+ * @enum {string}
3618
+ */
3619
+ decision: "done" | "dismiss" | "reopen";
3620
+ /** Note */
3621
+ note?: string | null;
3622
+ };
3623
+ /** LeftOnPodRow */
3624
+ LeftOnPodRow: {
3625
+ /** Check Detail */
3626
+ check_detail?: string | null;
3627
+ /** Check State */
3628
+ check_state?: ("still_on_pod" | "looks_resolved" | "unknown") | null;
3629
+ /** Checked At */
3630
+ checked_at?: string | null;
3631
+ /** Created At */
3632
+ created_at: string;
3633
+ /** Decided At */
3634
+ decided_at?: string | null;
3635
+ /** Decided By */
3636
+ decided_by?: string | null;
3637
+ /** Id */
3638
+ id: number;
3639
+ /** Kind */
3640
+ kind: string;
3641
+ /** Note */
3642
+ note?: string | null;
3643
+ /** Pod Id */
3644
+ pod_id: number;
3645
+ /** Pod Name */
3646
+ pod_name?: string | null;
3647
+ /** Recorded At */
3648
+ recorded_at: string;
3649
+ /** Reference */
3650
+ reference: string;
3651
+ /** Run Id */
3652
+ run_id: string;
3653
+ /** Scenario */
3654
+ scenario?: string | null;
3655
+ /**
3656
+ * Status
3657
+ * @enum {string}
3658
+ */
3659
+ status: "open" | "done" | "dismissed";
3660
+ /** Todo */
3661
+ todo: string;
3662
+ /** Why */
3663
+ why: string;
3664
+ };
3665
  /** LeftTestData */
3666
  LeftTestData: {
3667
  /** Number */
 
3750
  /** Webhook Host */
3751
  webhook_host?: string | null;
3752
  };
3753
+ /** Page[LeftOnPodRow] */
3754
+ Page_LeftOnPodRow_: {
3755
+ /** Items */
3756
+ items: components["schemas"]["LeftOnPodRow"][];
3757
+ /** Limit */
3758
+ limit: number;
3759
+ /** Offset */
3760
+ offset: number;
3761
+ /** Total */
3762
+ total: number;
3763
+ };
3764
  /** Page[RunSummary] */
3765
  Page_RunSummary_: {
3766
  /** Items */
 
3960
  last_check_detail?: string | null;
3961
  /** Last Check Ok */
3962
  last_check_ok?: boolean | null;
3963
+ /**
3964
+ * Left Open
3965
+ * @default 0
3966
+ */
3967
+ left_open: number;
3968
  /** Modules */
3969
  modules: string[];
3970
  /** Name */
 
7663
  };
7664
  };
7665
  };
7666
+ left_list_api_left_on_pod_get: {
7667
+ parameters: {
7668
+ query?: {
7669
+ pod_id?: number | null;
7670
+ status?: string | null;
7671
+ kind?: string | null;
7672
+ run_id?: string | null;
7673
+ limit?: number;
7674
+ offset?: number;
7675
+ };
7676
+ header?: never;
7677
+ path?: never;
7678
+ cookie?: never;
7679
+ };
7680
+ requestBody?: never;
7681
+ responses: {
7682
+ /** @description Successful Response */
7683
+ 200: {
7684
+ headers: {
7685
+ [name: string]: unknown;
7686
+ };
7687
+ content: {
7688
+ "application/json": components["schemas"]["Page_LeftOnPodRow_"];
7689
+ };
7690
+ };
7691
+ /** @description Validation Error */
7692
+ 422: {
7693
+ headers: {
7694
+ [name: string]: unknown;
7695
+ };
7696
+ content: {
7697
+ "application/json": components["schemas"]["HTTPValidationError"];
7698
+ };
7699
+ };
7700
+ };
7701
+ };
7702
+ left_decide_api_left_on_pod__row_id__decision_post: {
7703
+ parameters: {
7704
+ query?: never;
7705
+ header?: never;
7706
+ path: {
7707
+ row_id: number;
7708
+ };
7709
+ cookie?: never;
7710
+ };
7711
+ requestBody: {
7712
+ content: {
7713
+ "application/json": components["schemas"]["LeftDecisionIn"];
7714
+ };
7715
+ };
7716
+ responses: {
7717
+ /** @description Successful Response */
7718
+ 200: {
7719
+ headers: {
7720
+ [name: string]: unknown;
7721
+ };
7722
+ content: {
7723
+ "application/json": components["schemas"]["LeftOnPodRow"];
7724
+ };
7725
+ };
7726
+ /** @description Validation Error */
7727
+ 422: {
7728
+ headers: {
7729
+ [name: string]: unknown;
7730
+ };
7731
+ content: {
7732
+ "application/json": components["schemas"]["HTTPValidationError"];
7733
+ };
7734
+ };
7735
+ };
7736
+ };
7737
+ left_recheck_api_left_on_pod__row_id__recheck_post: {
7738
+ parameters: {
7739
+ query?: never;
7740
+ header?: never;
7741
+ path: {
7742
+ row_id: number;
7743
+ };
7744
+ cookie?: never;
7745
+ };
7746
+ requestBody?: never;
7747
+ responses: {
7748
+ /** @description Successful Response */
7749
+ 200: {
7750
+ headers: {
7751
+ [name: string]: unknown;
7752
+ };
7753
+ content: {
7754
+ "application/json": components["schemas"]["LeftOnPodRow"];
7755
+ };
7756
+ };
7757
+ /** @description Validation Error */
7758
+ 422: {
7759
+ headers: {
7760
+ [name: string]: unknown;
7761
+ };
7762
+ content: {
7763
+ "application/json": components["schemas"]["HTTPValidationError"];
7764
+ };
7765
+ };
7766
+ };
7767
+ };
7768
  library_log_api_library_log_get: {
7769
  parameters: {
7770
  query?: {
web/src/pages/setup/LeftOnPodPage.tsx ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Anchor, Button, Group, Modal, SegmentedControl, Select, Stack, Table, Text, Textarea } from '@mantine/core';
2
+ import { useState } from 'react';
3
+ import { Link, useSearchParams } from 'react-router-dom';
4
+ import { useLeftOnPod, useLeftOnPodActions, usePods, type LeftDoc } from '../../api/hooks';
5
+ import { Can, ErrorAlert, fmtTs, PageHeader } from '../../components/common';
6
+ import { DataTable } from '../../components/states';
7
+ import { shortWhen } from '../../domain/runName';
8
+ import './admin.css';
9
+
10
+ /** The kinds of test document a run can leave on a pod (coworker/platform/left_on_pod.py KINDS), in words. */
11
+ export const LEFT_KINDS: Record<string, string> = {
12
+ ap_invoice: 'Payables invoice', po_requisition: 'Purchase requisition', po_order: 'Purchase order', po_receipt: 'Receipt of an order',
13
+ gl_journal: 'Journal', ar_transaction: 'Receivables transaction', ar_receipt: 'Receivables receipt',
14
+ };
15
+ const STATUS_FILTERS = [{ value: 'open', label: 'Open' }, { value: 'done', label: 'Done' }, { value: 'dismissed', label: 'Dismissed' }, { value: 'all', label: 'All' }];
16
+ const CHECK: Record<string, { tone: string; words: string }> = {
17
+ still_on_pod: { tone: 'amber', words: 'Still on the pod' }, looks_resolved: { tone: 'green', words: 'Looks resolved' }, unknown: { tone: 'neutral', words: 'Could not tell' },
18
+ };
19
+
20
+ function DecideSheet({ doc, decision, onClose }: { doc: LeftDoc | null; decision: 'done' | 'dismiss'; onClose: () => void }) {
21
+ const { decide } = useLeftOnPodActions();
22
+ const [note, setNote] = useState('');
23
+ const done = decision === 'done';
24
+ return (
25
+ <Modal opened={!!doc} onClose={onClose} title={done ? 'Mark this document done?' : 'Dismiss this document?'} size={480} centered>
26
+ <Stack gap="sm">
27
+ <Text size="sm"><b>{doc ? `${LEFT_KINDS[doc.kind] ?? doc.kind} ${doc.reference}` : ''}</b></Text>
28
+ <Text size="sm" c="dimmed">
29
+ {done ? 'Say that it has been dealt with on the pod, or that nothing is needed.' : 'Say that it does not need to be dealt with.'} It leaves the open list; the
30
+ name and the time are kept in the audit log.
31
+ </Text>
32
+ <Textarea label="Note (optional)" description="Kept with the document and in the audit log." autosize minRows={2} maxRows={5} maxLength={1000}
33
+ value={note} onChange={(e) => setNote(e.currentTarget.value)} data-autofocus />
34
+ <ErrorAlert error={decide.error} title="Could not save" />
35
+ <div className="trio-sheet-foot">
36
+ <Button variant="default" onClick={onClose}>Not yet</Button><span className="trio-sheet-sp" />
37
+ <Button loading={decide.isPending} data-testid="left-confirm"
38
+ onClick={() => doc && decide.mutate({ id: doc.id, decision, note: note.trim() }, { onSuccess: onClose })}>{done ? 'Mark done' : 'Dismiss'}</Button>
39
+ </div>
40
+ </Stack>
41
+ </Modal>
42
+ );
43
+ }
44
+
45
+ export function LeftOnPodPage() {
46
+ const pods = usePods();
47
+ const [params] = useSearchParams();
48
+ const [podId, setPodId] = useState<string | null>(() => params.get('pod'));
49
+ const [status, setStatus] = useState('open');
50
+ const [kind, setKind] = useState<string | null>(null);
51
+ const q = useLeftOnPod({ pod_id: podId ? Number(podId) : undefined, status: status === 'all' ? undefined : (status as LeftDoc['status']), kind: kind ?? undefined });
52
+ const { decide, recheck } = useLeftOnPodActions();
53
+ const [sheet, setSheet] = useState<{ doc: LeftDoc; decision: 'done' | 'dismiss' } | null>(null);
54
+ const items = q.data?.items ?? [];
55
+ const podOptions = (pods.data ?? []).filter((p) => p.kind !== 'mock').map((p) => ({ value: String(p.id), label: p.name }));
56
+ return (
57
+ <Stack gap="md">
58
+ <PageHeader crumbs={[{ label: 'Home', to: '/' }, { label: 'Test environments', to: '/pods' }, { label: 'Left on the pod' }]} title="Left on the pod"
59
+ extra={<span className="fpt-pagedesc">Test documents a run created on an Oracle Fusion pod that the co-worker could not undo. Each needs a person: what to do is written next to it.</span>} />
60
+ <Group gap="sm" align="flex-end" wrap="wrap">
61
+ <Select aria-label="Pod" placeholder="All pods" data={podOptions} value={podId} onChange={setPodId} clearable w={220} />
62
+ <Select aria-label="Kind of document" placeholder="All kinds" data={Object.entries(LEFT_KINDS).map(([value, label]) => ({ value, label }))}
63
+ value={kind} onChange={setKind} clearable w={220} />
64
+ <SegmentedControl aria-label="Status" value={status} onChange={setStatus} data={STATUS_FILTERS} />
65
+ </Group>
66
+ <ErrorAlert error={recheck.error || decide.error} />
67
+ <DataTable label="Test documents left on the pod" q={q} rowCount={items.length} minWidth={960} fz="sm"
68
+ columns={['Document', 'Pod and run', 'Why it was left, and what to do', 'On the pod now', { label: 'Actions', width: 190 }]}
69
+ empty={status === 'open' ? 'Nothing is left on the pod for a person to deal with.' : 'No documents match.'}>
70
+ {items.map((d) => {
71
+ const c = d.check_state ? CHECK[d.check_state] : null;
72
+ return (
73
+ <Table.Tr key={d.id} data-testid={`left-${d.id}`} data-status={d.status}>
74
+ <Table.Td>
75
+ <b>{d.reference}</b>
76
+ <Text size="xs" c="dimmed">{LEFT_KINDS[d.kind] ?? d.kind}{d.scenario ? `, from "${d.scenario}"` : ''}</Text>
77
+ <Text size="xs" c="dimmed" title={fmtTs(d.created_at)}>created {shortWhen(d.created_at)}</Text>
78
+ </Table.Td>
79
+ <Table.Td>
80
+ <Text size="sm">{d.pod_name ?? `Pod ${d.pod_id}`}</Text>
81
+ <Anchor component={Link} to={`/runs/${d.run_id}`} size="xs">{d.run_id}</Anchor>
82
+ </Table.Td>
83
+ <Table.Td>
84
+ <Text size="sm">{d.why}.</Text>
85
+ <Text size="sm"><b>To do:</b> {d.todo}</Text>
86
+ {d.status !== 'open' && (
87
+ <Text size="xs" c="dimmed">{d.status === 'done' ? 'Done' : 'Dismissed'} by {d.decided_by} {d.decided_at ? shortWhen(d.decided_at) : ''}{d.note ? `: ${d.note}` : ''}</Text>
88
+ )}
89
+ </Table.Td>
90
+ <Table.Td>
91
+ {c ? <span className="fpt-dotword" data-tone={c.tone} title={d.check_detail ?? undefined}>{c.words}</span> : <Text size="xs" c="dimmed">Not looked at yet</Text>}
92
+ {c && <Text size="xs" c="dimmed">{d.check_detail}, {d.checked_at ? shortWhen(d.checked_at) : ''}</Text>}
93
+ </Table.Td>
94
+ <Table.Td>
95
+ <Can perm="left.decide">
96
+ <Group gap={4}>
97
+ {d.status === 'open' ? (
98
+ <>
99
+ <Button size="compact-xs" onClick={() => setSheet({ doc: d, decision: 'done' })}>Mark done</Button>
100
+ <Button size="compact-xs" variant="default" onClick={() => setSheet({ doc: d, decision: 'dismiss' })}>Dismiss</Button>
101
+ </>
102
+ ) : (
103
+ <Button size="compact-xs" variant="default" loading={decide.isPending} onClick={() => decide.mutate({ id: d.id, decision: 'reopen' })}>Open again</Button>
104
+ )}
105
+ <Button size="compact-xs" variant="default" loading={recheck.isPending && recheck.variables === d.id} onClick={() => recheck.mutate(d.id)}
106
+ title="Looks at the pod again with read-only requests. Nothing on the pod is changed.">Look again</Button>
107
+ </Group>
108
+ </Can>
109
+ </Table.Td>
110
+ </Table.Tr>
111
+ );
112
+ })}
113
+ </DataTable>
114
+ <SheetHost sheet={sheet} onClose={() => setSheet(null)} />
115
+ </Stack>
116
+ );
117
+ }
118
+
119
+ // remounted per document, so a note typed for one never shows on another
120
+ function SheetHost({ sheet, onClose }: { sheet: { doc: LeftDoc; decision: 'done' | 'dismiss' } | null; onClose: () => void }) {
121
+ return <DecideSheet key={sheet ? `${sheet.doc.id}-${sheet.decision}` : 'none'} doc={sheet?.doc ?? null} decision={sheet?.decision ?? 'done'} onClose={onClose} />;
122
+ }
web/src/pages/setup/PodsPage.tsx CHANGED
@@ -1,7 +1,7 @@
1
  import { Alert, Button, Group, Modal, PasswordInput, Select, SimpleGrid, Skeleton, Stack, Switch, Text, TextInput, Textarea } from '@mantine/core';
2
  import { IconCircleCheck, IconCircleX, IconCloud, IconFileAnalytics, IconKey, IconPlugConnected, IconPlus, IconRadar, IconScan, IconShieldLock } from '@/components/icons';
3
  import { useEffect, useState } from 'react';
4
- import { useSearchParams } from 'react-router-dom';
5
  import { MODULE_NAMES } from '../../domain/agents';
6
  import { usePodCoverage, usePodMutations, usePods, type Pod } from '../../api/hooks';
7
  import type { Schemas } from '../../api/client';
@@ -366,6 +366,11 @@ function PodCard({ p, onCreds, onTestData }: { p: Pod; onCreds: (p: Pod) => void
366
  )}
367
  <Stack gap={4} mt="sm">
368
  <span className="fpt-dotword" data-tone={conn.tone} title={p.last_check_at ? fmtTs(p.last_check_at) : undefined}>{conn.words}</span>
 
 
 
 
 
369
  {p.runnable ? <Text size="xs">Ready for test runs.</Text> : <Text size="xs" style={{ color: 'var(--pill-amber-fg)' }}>Not available for test runs{p.not_runnable_reason ? `: ${p.not_runnable_reason}` : '.'}</Text>}
370
  <Text size="xs" c="dimmed">
371
  Sign-in details: {p.sign_in_mode === 'assisted' ? 'assisted sign-in: a person signs in at the start of each run (no password stored)'
@@ -428,6 +433,7 @@ export function PodsPage() {
428
  <Stack gap="md">
429
  <PageHeader crumbs={[{ label: 'Home', to: '/' }, { label: 'Test environments' }]} title="Test environments"
430
  extra={<span className="fpt-pagedesc">The Oracle Fusion test pods the agents test after a patch, and the practice environment. Production pods are never allowed.</span>}>
 
431
  <Can perm="admin"><Button variant="filled" onClick={() => setAdding(true)} leftSection={<IconPlus size={14} />}>Add an Oracle Fusion pod</Button></Can>
432
  </PageHeader>
433
  <details className="fpt-podhelp">
 
1
  import { Alert, Button, Group, Modal, PasswordInput, Select, SimpleGrid, Skeleton, Stack, Switch, Text, TextInput, Textarea } from '@mantine/core';
2
  import { IconCircleCheck, IconCircleX, IconCloud, IconFileAnalytics, IconKey, IconPlugConnected, IconPlus, IconRadar, IconScan, IconShieldLock } from '@/components/icons';
3
  import { useEffect, useState } from 'react';
4
+ import { Link, useSearchParams } from 'react-router-dom';
5
  import { MODULE_NAMES } from '../../domain/agents';
6
  import { usePodCoverage, usePodMutations, usePods, type Pod } from '../../api/hooks';
7
  import type { Schemas } from '../../api/client';
 
366
  )}
367
  <Stack gap={4} mt="sm">
368
  <span className="fpt-dotword" data-tone={conn.tone} title={p.last_check_at ? fmtTs(p.last_check_at) : undefined}>{conn.words}</span>
369
+ {fusion && (
370
+ <Link to={`/pods/left?pod=${p.id}`} className="fpt-dotword" data-testid={`pod-left-${p.id}`} data-tone={p.left_open ? 'amber' : 'green'}>
371
+ {p.left_open ? `${p.left_open} test document${p.left_open === 1 ? '' : 's'} left on the pod for a person` : 'Nothing left on the pod'}
372
+ </Link>
373
+ )}
374
  {p.runnable ? <Text size="xs">Ready for test runs.</Text> : <Text size="xs" style={{ color: 'var(--pill-amber-fg)' }}>Not available for test runs{p.not_runnable_reason ? `: ${p.not_runnable_reason}` : '.'}</Text>}
375
  <Text size="xs" c="dimmed">
376
  Sign-in details: {p.sign_in_mode === 'assisted' ? 'assisted sign-in: a person signs in at the start of each run (no password stored)'
 
433
  <Stack gap="md">
434
  <PageHeader crumbs={[{ label: 'Home', to: '/' }, { label: 'Test environments' }]} title="Test environments"
435
  extra={<span className="fpt-pagedesc">The Oracle Fusion test pods the agents test after a patch, and the practice environment. Production pods are never allowed.</span>}>
436
+ <Button component={Link} to="/pods/left" variant="default">Left on the pod</Button>
437
  <Can perm="admin"><Button variant="filled" onClick={() => setAdding(true)} leftSection={<IconPlus size={14} />}>Add an Oracle Fusion pod</Button></Can>
438
  </PageHeader>
439
  <details className="fpt-podhelp">