forked from ChelseaKR/fare-policy-assistant
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconsole.py
More file actions
941 lines (808 loc) · 36.9 KB
/
Copy pathconsole.py
File metadata and controls
941 lines (808 loc) · 36.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
"""Agency operator console (EXP-09, `docs/ideation/03-expansions.md`).
Today, reviewing corpus versions and the immutable rider release still requires
AWS-console knowledge. This module is the read-only operator experience for
those facts. Earlier versions also wrote pin and embed settings directly to the
rider Lambda's unqualified ``$LATEST`` configuration. Once production traffic
is routed through an immutable ``live`` alias, such a write cannot affect the
published version and a success response would be dangerously misleading.
Those mutation routes therefore fail closed until a durable approval store and
release-promotion workflow exist.
Deployment model (the design question EXP-09 names as central): this is its
own Lambda handler (`console_handler`), built and deployed by
`infra/deploy-console.sh` as a *second*, separate function with its own API
Gateway route and its own least-privilege IAM role — never merged into the
rider-facing `web/handler.py` Lambda, and granted only read access to the
configured rider alias and its resolved function configuration. No rider data
exists to expose here (no question or answer text ever reaches this module).
Authentication fails closed on every data and action API: requests must carry
`Authorization: Bearer <token>` matching the encrypted SSM parameter named by
`FPA_CONSOLE_TOKEN_PARAMETER_NAME`. If neither that parameter nor the local-dev
`FPA_CONSOLE_TOKEN` fallback resolves, the APIs refuse every request rather
than defaulting open.
The static `/console` HTML shell is public so an ordinary browser can render
the token-entry form; it contains no corpus data or configuration, and cannot
read or change anything until the operator supplies the token. A shared bearer
token is adequate for a single-operator pilot deploy but is not real identity
— anyone holding it has full console access. Production
deployments must put an API Gateway JWT or IAM authorizer in front, backed by
the agency's own SSO/IdP, exactly as `infra/deploy-console.sh` documents; that
step needs a live identity provider to wire up and is intentionally left as a
documented manual step (the same shape as the AWS Budget setup in
`infra/README.md`), not something this module can fake.
Corpus version history is git-backed but the console never shells out to git
at request time (the standard Lambda Python runtime ships no git binary): a
development/CI step (`make history`) walks git history into
`corpus/version_history.json` (see `assistant.corpus.version_history`), and
`infra/deploy-console.sh` bundles that static file. `list_versions` /
`version_diff` read it; if it is missing (e.g. running the console locally
from a full checkout without having generated it), they fall back to a live
git query for developer convenience only.
"""
from __future__ import annotations
import base64
import hmac
import json
import os
import re
import sys
from datetime import UTC, datetime, timedelta
from pathlib import Path
_ROOT = Path(__file__).resolve().parent.parent # bundle root mirrors the repo root
sys.path.insert(0, str(_ROOT / "src"))
from assistant import config # noqa: E402
from assistant.corpus import corpus_summary, diff_corpus # noqa: E402
from assistant.ingest import Chunk # noqa: E402
from assistant.promotion_evidence import ( # noqa: E402
PromotionEvidenceError,
verify_promotion_evidence,
)
MAX_BODY_BYTES = 16 * 1024
VERSION_HISTORY_PATH = config.CORPUS_DIR / "version_history.json"
PROMOTED_EVAL_SUMMARY_PATH = _ROOT / "evals" / "promoted" / "summary.json"
PROMOTED_EVAL_RESULTS_PATH = _ROOT / "evals" / "promoted" / "results.jsonl"
PROMOTED_EVAL_ATTESTATION_PATH = _ROOT / "evals" / "promoted" / "promotion.json"
PROMOTED_EVAL_MAX_AGE_SECONDS = 7 * 24 * 60 * 60
_SOURCE_REVISION = re.compile(r"^[0-9a-f]{40}$")
_SHA256 = re.compile(r"^[0-9a-f]{64}$")
_CORPUS_VERSION = re.compile(r"^[0-9a-f]{12}$")
_FUNCTION_VERSION = re.compile(r"^[1-9][0-9]*$")
_IDENTITY_ENVIRONMENT = {
"source_revision": "FPA_SOURCE_REVISION",
"config_version": "FPA_CONFIG_VERSION",
"content_version": "FPA_PINNED_CONTENT_VERSION",
"snapshot_version": "FPA_PINNED_SNAPSHOT_VERSION",
"release_version": "FPA_RELEASE_VERSION",
"corpus_version": "FPA_PINNED_CORPUS_VERSION",
"artifact_code_sha256": "FPA_ARTIFACT_CODE_SHA256",
}
_RELEASE_IDENTITY_FIELDS = tuple(_IDENTITY_ENVIRONMENT)
_SECURITY_HEADERS = {
"cache-control": "no-store",
"x-content-type-options": "nosniff",
"x-frame-options": "DENY",
"referrer-policy": "no-referrer",
"content-security-policy": (
"default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; "
"connect-src 'self'; form-action 'self'; base-uri 'none'"
),
}
# Test/dev hook: set to a zero-arg callable returning a fake "lambda" client
# (an object with get_alias / get_function_configuration methods) so the live
# release status is testable without AWS credentials.
_client_factory = None
_http_client_factory = None
_ssm_client_factory = None
_resolved_console_token: str | None = None
_console_token_resolved = False
def _clock() -> datetime:
return datetime.now(UTC)
class LiveIdentityError(RuntimeError):
"""One or more production observations cannot describe one live release."""
def __init__(self, *mismatches: str):
unique = tuple(dict.fromkeys(mismatches)) or ("live_identity",)
super().__init__("live rider identity observations are incoherent")
self.mismatches = unique
class PromotedEvalError(ValueError):
"""The fixed promoted receipt is absent, malformed, or non-promotable."""
def __init__(self, *mismatches: str):
unique = tuple(dict.fromkeys(mismatches)) or ("evaluation",)
super().__init__("promoted evaluation evidence is invalid")
self.mismatches = unique
def _response(status: int, body: str, content_type: str = "application/json") -> dict:
return {
"statusCode": status,
"headers": {"content-type": content_type, **_SECURITY_HEADERS},
"body": body,
}
def _json(status: int, payload: dict) -> dict:
return _response(status, json.dumps(payload, ensure_ascii=False))
# ── auth ─────────────────────────────────────────────────────────────────────
def _console_token() -> str | None:
"""Resolve the operator token once per warm container.
Production uses an encrypted SSM parameter; the literal environment value
remains only as a local/test fallback. A lookup error fails closed but is
not cached, so a transient SSM outage can recover on the next request.
"""
global _console_token_resolved, _resolved_console_token
if _console_token_resolved:
return _resolved_console_token
parameter_name = os.environ.get("FPA_CONSOLE_TOKEN_PARAMETER_NAME")
if parameter_name:
try:
if _ssm_client_factory is not None:
client = _ssm_client_factory()
else:
import boto3
client = boto3.client("ssm", region_name=os.environ.get("AWS_REGION", "us-west-2"))
value = client.get_parameter(Name=parameter_name, WithDecryption=True)
token = value.get("Parameter", {}).get("Value", "").strip()
_resolved_console_token = token or None
_console_token_resolved = True
return _resolved_console_token
except Exception: # noqa: BLE001 - authentication must fail closed on any AWS error
return None
token = os.environ.get("FPA_CONSOLE_TOKEN")
_resolved_console_token = token or None
_console_token_resolved = True
return _resolved_console_token
def _reset_console_token_for_tests() -> None:
global _console_token_resolved, _resolved_console_token
_resolved_console_token = None
_console_token_resolved = False
def _authorized(event: dict) -> bool:
token = _console_token()
if not token:
return False # unset means misconfigured: refuse everything, never default open
headers = {str(k).lower(): v for k, v in (event.get("headers") or {}).items()}
auth = headers.get("authorization", "")
if not auth.startswith("Bearer "):
return False
return hmac.compare_digest(auth[len("Bearer ") :], token)
# ── corpus version history + diff ───────────────────────────────────────────
def _chunks_from_dicts(raw: list[dict]) -> list[Chunk]:
return [Chunk(**c) for c in raw]
def _load_version_history() -> list[dict]:
if VERSION_HISTORY_PATH.exists():
data = json.loads(VERSION_HISTORY_PATH.read_text(encoding="utf-8"))
return data.get("versions", [])
# Developer-convenience fallback: no static file, but a live checkout with
# git is present. Never runs in the deployed Lambda (see module docstring).
from assistant.corpus import version_history
return version_history()
def list_versions() -> list[dict]:
"""The changelog view: every known version without its chunk payload
(kept out of the list response; `version_diff` loads it on demand)."""
return [{k: v for k, v in entry.items() if k != "chunks"} for entry in _load_version_history()]
def _find_version(versions: list[dict], ref: str) -> dict | None:
for entry in versions:
if ref in (entry.get("commit"), entry.get("corpus_version")):
return entry
return None
def version_diff(from_ref: str, to_ref: str) -> dict:
"""Diff two known versions, identified by either their commit id or their
corpus_version hash (either is a valid handle an operator might paste)."""
versions = _load_version_history()
old, new = _find_version(versions, from_ref), _find_version(versions, to_ref)
if old is None:
raise LookupError(f"unknown version: {from_ref}")
if new is None:
raise LookupError(f"unknown version: {to_ref}")
result = diff_corpus(_chunks_from_dicts(old["chunks"]), _chunks_from_dicts(new["chunks"]))
result["from"] = {"commit": old["commit"], "corpus_version": old["corpus_version"]}
result["to"] = {"commit": new["commit"], "corpus_version": new["corpus_version"]}
return result
# ── immutable rider release status ──────────────────────────────────────────
def _lambda_client():
if _client_factory is not None:
return _client_factory()
import boto3
return boto3.client("lambda", region_name=os.environ.get("AWS_REGION", "us-west-2"))
def _rider_function_name() -> str:
name = os.environ.get("FPA_RIDER_FUNCTION_NAME")
if not name:
raise LiveIdentityError("aws.function_name")
return name
def _rider_alias_name() -> str:
return os.environ.get("FPA_RIDER_ALIAS", "live")
def _rider_base_url() -> str:
base_url = os.environ.get("FPA_RIDER_BASE_URL", "").strip()
if not base_url:
raise LiveIdentityError("runtime.base_url")
if not base_url.startswith("https://"):
raise LiveIdentityError("runtime.base_url")
return base_url.rstrip("/")
def _http_client():
if _http_client_factory is not None:
return _http_client_factory()
import httpx
return httpx.Client(timeout=5.0, follow_redirects=False, trust_env=False)
def _canonical_artifact_digest(value: object) -> str | None:
if not isinstance(value, str) or value != value.strip():
return None
try:
decoded = base64.b64decode(value, validate=True)
except (TypeError, ValueError):
return None
if len(decoded) != 32 or base64.b64encode(decoded).decode("ascii") != value:
return None
return value
def _validated_alias(alias: object, *, observation: str) -> tuple[str, str | None]:
if not isinstance(alias, dict):
raise LiveIdentityError(f"alias.{observation}")
routing = alias.get("RoutingConfig", {})
if not isinstance(routing, dict):
raise LiveIdentityError("alias.routing_weights")
weights = routing.get("AdditionalVersionWeights", {})
if not isinstance(weights, dict) or weights:
raise LiveIdentityError("alias.routing_weights")
version = alias.get("FunctionVersion")
if not isinstance(version, str) or not _FUNCTION_VERSION.fullmatch(version):
raise LiveIdentityError("alias.function_version")
revision = alias.get("RevisionId")
if revision is not None and (not isinstance(revision, str) or not revision):
raise LiveIdentityError(f"alias.{observation}")
return version, revision
def _aws_release_observation(current: object, expected_version: str) -> tuple[dict, dict]:
if not isinstance(current, dict):
raise LiveIdentityError("aws.configuration")
configured_version = current.get("Version")
if configured_version != expected_version:
raise LiveIdentityError("aws.function_version")
environment = current.get("Environment", {})
if not isinstance(environment, dict):
raise LiveIdentityError("aws.environment")
variables = environment.get("Variables", {})
if not isinstance(variables, dict):
raise LiveIdentityError("aws.environment")
identity = {field: variables.get(name) for field, name in _IDENTITY_ENVIRONMENT.items()}
mismatches: list[str] = []
for field in ("source_revision",):
value = identity[field]
if not isinstance(value, str) or not _SOURCE_REVISION.fullmatch(value):
mismatches.append(f"aws.{field}")
for field in (
"config_version",
"content_version",
"snapshot_version",
"release_version",
):
value = identity[field]
if not isinstance(value, str) or not _SHA256.fullmatch(value):
mismatches.append(f"aws.{field}")
corpus_version = identity["corpus_version"]
if not isinstance(corpus_version, str) or not _CORPUS_VERSION.fullmatch(corpus_version):
mismatches.append("aws.corpus_version")
artifact = _canonical_artifact_digest(identity["artifact_code_sha256"])
if artifact is None:
mismatches.append("aws.artifact_code_sha256")
code_sha = _canonical_artifact_digest(current.get("CodeSha256"))
if code_sha is None:
mismatches.append("aws.CodeSha256")
elif artifact is not None and not hmac.compare_digest(code_sha, artifact):
mismatches.append("aws.CodeSha256")
if mismatches:
raise LiveIdentityError(*mismatches)
return identity, variables
def _runtime_release_observation(expected: dict, expected_version: str) -> dict:
client = _http_client()
try:
response = client.get(f"{_rider_base_url()}/version")
if getattr(response, "status_code", None) != 200:
raise LiveIdentityError("runtime.http_status")
try:
runtime = response.json()
except Exception as exc: # noqa: BLE001 - a non-JSON runtime is incoherent
raise LiveIdentityError("runtime.json") from exc
except LiveIdentityError:
raise
except Exception as exc: # noqa: BLE001 - network/TLS errors are one safe state
raise LiveIdentityError("runtime.unreachable") from exc
finally:
close = getattr(client, "close", None)
if callable(close):
close()
if not isinstance(runtime, dict):
raise LiveIdentityError("runtime.json")
mismatches: list[str] = []
if runtime.get("identity_status") != "verified":
mismatches.append("runtime.identity_status")
if runtime.get("function_version") != expected_version:
mismatches.append("runtime.function_version")
for field in _RELEASE_IDENTITY_FIELDS:
value = runtime.get(field)
if not isinstance(value, str) or value != expected[field]:
mismatches.append(f"runtime.{field}")
if mismatches:
raise LiveIdentityError(*mismatches)
return runtime
def live_release_status() -> dict:
"""Observe one immutable release through AWS and the public rider route.
The alias is read both before and after the public observation. A 200
console status therefore means the unweighted numeric alias, its qualified
configuration, its exact ZIP digest, and the rider-visible ``/version``
response all named the same release without a detected cutover race.
"""
try:
client = _lambda_client()
except Exception as exc: # noqa: BLE001 - AWS client failures are one safe state
raise LiveIdentityError("aws.client") from exc
fn = _rider_function_name()
alias_name = _rider_alias_name()
try:
before = client.get_alias(FunctionName=fn, Name=alias_name)
except Exception as exc: # noqa: BLE001 - AWS failures are a single safe state
raise LiveIdentityError("alias.initial") from exc
version, revision = _validated_alias(before, observation="initial")
try:
current = client.get_function_configuration(FunctionName=fn, Qualifier=version)
except Exception as exc: # noqa: BLE001 - AWS failures are a single safe state
raise LiveIdentityError("aws.configuration") from exc
identity, env = _aws_release_observation(current, version)
runtime = _runtime_release_observation(identity, version)
try:
after = client.get_alias(FunctionName=fn, Name=alias_name)
except Exception as exc: # noqa: BLE001 - AWS failures are a single safe state
raise LiveIdentityError("alias.final") from exc
final_version, final_revision = _validated_alias(after, observation="final")
alias_mismatches: list[str] = []
if final_version != version:
alias_mismatches.append("alias.function_version")
if revision is not None and final_revision is not None and revision != final_revision:
alias_mismatches.append("alias.revision")
if alias_mismatches:
raise LiveIdentityError(*alias_mismatches)
disabled_raw = env.get("FPA_DISABLED_DOC_IDS", "")
embed_ancestors = env.get("FPA_EMBED_ANCESTORS", "'self'")
if not isinstance(disabled_raw, str):
raise LiveIdentityError("aws.disabled_documents")
if not isinstance(embed_ancestors, str) or not embed_ancestors:
raise LiveIdentityError("aws.embed_ancestors")
return {
"alias": alias_name,
"function_version": version,
"identity_status": "verified",
**identity,
"pinned_corpus_version": identity["corpus_version"],
"disabled_documents": sorted(doc_id for doc_id in disabled_raw.split(",") if doc_id),
"embed_ancestors": embed_ancestors,
"runtime_as_of": runtime.get("as_of"),
}
# ── eval report ──────────────────────────────────────────────────────────────
def promoted_eval_status(live: dict, available_corpus: dict) -> tuple[dict, bool]:
"""Verify the exact evidence trio against one coherent live release.
The shared verifier is the sole parser for promotion evidence. The console
receives only its sanitized projection; raw questions, answers, rationales,
and retrieved passages never cross the API boundary.
"""
try:
evidence = verify_promotion_evidence(
summary_path=PROMOTED_EVAL_SUMMARY_PATH,
results_path=PROMOTED_EVAL_RESULTS_PATH,
promotion_path=PROMOTED_EVAL_ATTESTATION_PATH,
freshness_budget=timedelta(seconds=PROMOTED_EVAL_MAX_AGE_SECONDS),
clock=_clock,
)
except PromotionEvidenceError as exc:
raise PromotedEvalError(*exc.mismatches) from exc
mismatches: list[str] = []
runtime_release = evidence.attestation.runtime_release
for field in (
"source_revision",
"config_version",
"content_version",
"snapshot_version",
"release_version",
"corpus_version",
"artifact_code_sha256",
"function_version",
):
if getattr(runtime_release, field) != live.get(field):
mismatches.append(f"evaluation.runtime_release.{field}")
for field in ("content_version", "corpus_version"):
if available_corpus.get(field) != live.get(field):
mismatches.append(f"catalog.{field}")
if mismatches:
raise PromotedEvalError(*mismatches)
return evidence.as_dict(), not evidence.fresh
# ── routes ───────────────────────────────────────────────────────────────────
def _read_body(event: dict) -> dict:
body = event.get("body") or ""
if event.get("isBase64Encoded"):
import base64
body = base64.b64decode(body).decode("utf-8")
if len(body) > MAX_BODY_BYTES:
raise ValueError("request too large")
return json.loads(body) if body.strip() else {}
def _status(event: dict) -> dict:
try:
live = live_release_status()
except LiveIdentityError as exc:
return _json(
503,
{
"state": "invalid",
"status": "invalid",
"error": "Live rider identity observations are incoherent.",
"mismatches": list(exc.mismatches),
},
)
try:
available_corpus = corpus_summary()
except Exception: # noqa: BLE001 - the packaged catalog is one observed dependency
return _json(
503,
{
"state": "invalid",
"status": "invalid",
"error": "The console catalog bundle is unavailable.",
"mismatches": ["catalog.unavailable"],
},
)
common = {
"available_corpus": available_corpus,
"live": live,
"rider_function": os.environ.get("FPA_RIDER_FUNCTION_NAME"),
}
try:
evaluation, stale = promoted_eval_status(live, available_corpus)
except PromotedEvalError as exc:
return _json(
409,
{
**common,
"state": "invalid",
"status": "invalid",
"error": "Promoted evaluation evidence is absent, invalid, or non-promotable.",
"mismatches": list(exc.mismatches),
},
)
if stale:
return _json(
409,
{
**common,
"evaluation": evaluation,
"state": "warning",
"status": "stale",
"error": (
"The promoted evaluation matches live, but is older than its freshness budget."
),
"mismatches": ["evaluation.age"],
},
)
return _json(
200,
{
**common,
"evaluation": evaluation,
"state": "coherent",
"status": "verified",
"mismatches": [],
},
)
def _versions(event: dict) -> dict:
try:
return _json(200, {"versions": list_versions()})
except RuntimeError as exc:
return _json(503, {"error": f"Version history unavailable: {exc}"})
def _diff(event: dict) -> dict:
qs = event.get("queryStringParameters") or {}
from_ref, to_ref = qs.get("from"), qs.get("to")
if not from_ref or not to_ref:
return _json(400, {"error": "Provide ?from=<commit-or-version>&to=<commit-or-version>."})
try:
return _json(200, version_diff(from_ref, to_ref))
except LookupError as exc:
return _json(404, {"error": str(exc)})
except RuntimeError as exc:
return _json(503, {"error": f"Version history unavailable: {exc}"})
def _pin(event: dict) -> dict:
return _json(
409,
{
"error": (
"Live releases are immutable. Submit and approve the corpus change, "
"then promote it with the reviewed deployment workflow."
),
"code": "immutable_release_requires_promotion",
},
)
def _embed_config_get(event: dict) -> dict:
return _json(200, {"ancestors": live_release_status()["embed_ancestors"]})
def _embed_config_post(event: dict) -> dict:
return _json(
409,
{
"error": (
"Live releases are immutable. Submit and approve the embed change, "
"then promote it with the reviewed deployment workflow."
),
"code": "immutable_release_requires_promotion",
},
)
def _eval_report(event: dict) -> dict:
try:
live = live_release_status()
except LiveIdentityError as exc:
return _json(
503,
{
"state": "invalid",
"status": "invalid",
"error": "Live rider identity observations are incoherent.",
"mismatches": list(exc.mismatches),
},
)
try:
available_corpus = corpus_summary()
except Exception: # noqa: BLE001 - the packaged catalog is one observed dependency
return _json(
503,
{
"state": "invalid",
"status": "invalid",
"error": "The console catalog bundle is unavailable.",
"mismatches": ["catalog.unavailable"],
},
)
try:
evaluation, stale = promoted_eval_status(live, available_corpus)
except PromotedEvalError as exc:
return _json(
409,
{
"state": "invalid",
"status": "invalid",
"error": "Promoted evaluation evidence is absent, invalid, or non-promotable.",
"mismatches": list(exc.mismatches),
},
)
if stale:
return _json(
409,
{
"state": "warning",
"status": "stale",
"error": (
"The promoted evaluation matches live, but is older than its freshness budget."
),
"mismatches": ["evaluation.age"],
},
)
return _json(200, evaluation)
_ROUTES = {
("GET", "/console/api/status"): _status,
("GET", "/console/api/versions"): _versions,
("GET", "/console/api/diff"): _diff,
("POST", "/console/api/pin"): _pin,
("GET", "/console/api/embed-config"): _embed_config_get,
("POST", "/console/api/embed-config"): _embed_config_post,
("GET", "/console/api/eval-report"): _eval_report,
}
def console_handler(event: dict, context: object = None) -> dict:
http = event.get("requestContext", {}).get("http", {})
method = http.get("method", "GET")
path = event.get("rawPath", "/")
if path == "/console" and method == "GET":
return _response(200, CONSOLE_HTML, "text/html; charset=utf-8")
route = _ROUTES.get((method, path))
if route is None:
return _json(404, {"error": "Not found."})
if not _authorized(event):
return _json(401, {"error": "Unauthorized."})
try:
return route(event)
except Exception as exc: # never leak internals; never log content
print(json.dumps({"error": type(exc).__name__, "route": path}))
return _json(500, {"error": "Something went wrong on the console's side."})
CONSOLE_HTML = """<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Fare policy assistant — agency operator console</title>
<style>
* { box-sizing: border-box; }
body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI",
Roboto, Helvetica, Arial, sans-serif; color: #1a1f24; background: #fff; line-height: 1.5; }
main { max-width: 46rem; margin: 0 auto; padding: 1.2rem 1rem 3rem; }
h1 { font-size: 1.3rem; margin: 0 0 0.3rem; }
h2 { font-size: 1.05rem; margin: 1.6rem 0 0.5rem; }
.note { color: #4d5860; font-size: 0.9rem; }
section { border: 1px solid #d6d3cb; border-radius: 8px; padding: 1rem; margin-top: 1rem; }
label { display: block; font-weight: 600; margin-bottom: 0.3rem; }
input, textarea { width: 100%; font: inherit; padding: 0.5rem; border: 1px solid #d6d3cb;
border-radius: 6px; background: #fff; color: #1a1f24; }
input:focus-visible, textarea:focus-visible, button:focus-visible, a:focus-visible {
outline: 3px solid #1d4ed8; outline-offset: 2px; }
button { font: inherit; border: 1px solid #14532d; background: #14532d; color: #fff;
border-radius: 6px; padding: 0.5rem 1rem; min-height: 2.5rem; cursor: pointer;
margin-top: 0.5rem; }
button.secondary { background: #fff; color: #14532d; }
table { width: 100%; border-collapse: collapse; margin-top: 0.5rem; font-size: 0.9rem; }
th, td { text-align: left; padding: 0.4rem 0.5rem; border-bottom: 1px solid #e5e3db; }
code { background: #f4f2ea; padding: 0.1rem 0.3rem; border-radius: 4px; }
#status { color: #4d5860; min-height: 1.2rem; margin-top: 0.5rem; font-size: 0.85rem; }
#status.error { color: #991b1b; }
.pin-badge { display: inline-block; padding: 0.1rem 0.5rem; border-radius: 999px;
font-size: 0.8rem; background: #eef2e9; }
</style>
</head>
<body>
<main>
<h1>Agency operator console</h1>
<p class="note">Review the immutable live release, corpus history, and
evaluation evidence. Release-setting changes require the reviewed promotion
workflow; see <code>infra/README.md</code>.</p>
<section aria-labelledby="auth-h">
<h2 id="auth-h">Access token</h2>
<label for="token">Console access token</label>
<input id="token" type="password" autocomplete="off" placeholder="Bearer token">
<button id="save-token" type="button">Use this token</button>
<p class="note">Held in this tab only (sessionStorage), never sent anywhere
but this console's own API.</p>
</section>
<section aria-labelledby="status-h">
<h2 id="status-h">Live release</h2>
<div id="status-body">Load status to resolve the production alias.</div>
<button id="refresh-status" type="button">Refresh</button>
</section>
<section aria-labelledby="versions-h">
<h2 id="versions-h">Corpus versions</h2>
<div id="versions-body"></div>
<button id="refresh-versions" type="button">Load versions</button>
</section>
<section aria-labelledby="diff-h">
<h2 id="diff-h">Compare two versions</h2>
<label for="diff-from">From (commit or corpus_version)</label>
<input id="diff-from">
<label for="diff-to">To (commit or corpus_version)</label>
<input id="diff-to">
<button id="run-diff" type="button">Show diff</button>
<div id="diff-body"></div>
</section>
<section aria-labelledby="embed-h">
<h2 id="embed-h">Embed settings</h2>
<p class="note">The live allowlist is shown in release status. Changes are
immutable release inputs and cannot be applied from this console.</p>
</section>
<section aria-labelledby="eval-h">
<h2 id="eval-h">Promoted eval report</h2>
<div id="eval-body"></div>
<button id="refresh-eval" type="button">Load promoted eval report</button>
</section>
<p id="status" role="status" aria-live="polite"></p>
</main>
<script>
(function () {
"use strict";
var statusEl = document.getElementById("status");
function esc(s) {
return String(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
}
function say(msg, isError) {
statusEl.className = isError ? "error" : "";
statusEl.textContent = msg;
}
function failureText(r, fallback) {
var message = r.data && r.data.error ? String(r.data.error) : fallback;
var names = r.data && Array.isArray(r.data.mismatches) ? r.data.mismatches : [];
return names.length ? message + " Mismatches: " + names.map(String).join(", ") + "." : message;
}
function token() {
return sessionStorage.getItem("fpa_console_token") || "";
}
function api(path, opts) {
opts = opts || {};
opts.headers = Object.assign({ "authorization": "Bearer " + token() }, opts.headers || {});
return fetch(path, opts).then(function (resp) {
return resp.json().then(function (data) {
return { ok: resp.ok, status: resp.status, data: data };
});
});
}
document.getElementById("save-token").addEventListener("click", function () {
sessionStorage.setItem("fpa_console_token", document.getElementById("token").value.trim());
say("Token saved for this tab.");
});
document.getElementById("refresh-status").addEventListener("click", function () {
var body = document.getElementById("status-body");
body.textContent = "Checking AWS, the public rider runtime, and promoted evidence…";
api("/console/api/status").then(function (r) {
if (!r.ok) {
var problem = failureText(r, "Could not verify live status.");
body.textContent = problem;
say(problem, true);
return;
}
var d = r.data;
var live = d.live;
var pin = live.pinned_corpus_version || "no pin set";
body.innerHTML =
"<p><strong>Verified:</strong> AWS, the rider runtime, and the promoted eval agree.</p>" +
"<p>Alias <code>" + esc(live.alias) + "</code> points to immutable Lambda " +
"version <code>" + esc(live.function_version) + "</code>.</p>" +
"<p>Release: <code>" + esc(live.release_version) + "</code></p>" +
"<p>Approved corpus pin: <code>" + esc(pin) + "</code></p>" +
"<p>Disabled documents: <code>" +
esc(live.disabled_documents.join(", ") || "none") + "</code></p>" +
"<p>Embed origins: <code>" + esc(live.embed_ancestors) + "</code></p>" +
"<p>Console catalog bundle: <code>" +
esc(d.available_corpus.corpus_version) + "</code> as of " +
esc(d.available_corpus.as_of) + ".</p>";
say("Status refreshed.");
}).catch(function () { say("Could not reach the console API.", true); });
});
document.getElementById("refresh-versions").addEventListener("click", function () {
var versionsBody = document.getElementById("versions-body");
versionsBody.textContent = "Loading versions…";
api("/console/api/versions").then(function (r) {
if (!r.ok) {
versionsBody.textContent = failureText(r, "Could not load versions.");
say(versionsBody.textContent, true);
return;
}
var rows = r.data.versions.map(function (v) {
return "<tr><td><code>" + esc(v.corpus_version) + "</code></td><td>" + esc(v.commit) +
"</td><td>" + esc(v.committed_at) + "</td><td>" + esc(v.documents) +
"</td></tr>";
}).join("");
versionsBody.innerHTML =
"<table><thead><tr><th>corpus_version</th><th>commit</th><th>committed</th>" +
"<th>docs</th></tr></thead><tbody>" + rows + "</tbody></table>";
say("Versions loaded.");
}).catch(function () { say("Could not reach the console API.", true); });
});
document.getElementById("run-diff").addEventListener("click", function () {
var from = document.getElementById("diff-from").value.trim();
var to = document.getElementById("diff-to").value.trim();
var diffBody = document.getElementById("diff-body");
if (!from || !to) { say("Enter both a from and a to version.", true); return; }
diffBody.textContent = "Loading comparison…";
api("/console/api/diff?from=" + encodeURIComponent(from) + "&to=" + encodeURIComponent(to))
.then(function (r) {
if (!r.ok) {
diffBody.textContent = failureText(r, "Could not load diff.");
say(diffBody.textContent, true);
return;
}
var d = r.data;
function list(items) { return items.length ? "<ul>" + items.map(function (i) {
return "<li>" + esc(i) + "</li>"; }).join("") + "</ul>" : "<p>none</p>"; }
diffBody.innerHTML =
"<p><strong>Added</strong></p>" + list(d.added) +
"<p><strong>Removed</strong></p>" + list(d.removed) +
"<p><strong>Changed</strong></p>" + list(d.changed);
say("Diff loaded.");
}).catch(function () { say("Could not reach the console API.", true); });
});
document.getElementById("refresh-eval").addEventListener("click", function () {
var evalBody = document.getElementById("eval-body");
evalBody.textContent = "Loading promoted evaluation…";
api("/console/api/eval-report").then(function (r) {
if (!r.ok) {
evalBody.textContent = failureText(r, "No promoted eval report yet.");
say(evalBody.textContent, true);
return;
}
var d = r.data;
var rows = (d.suites || []).map(function (s) {
// The verifier's pass_rate is already a 0-100 percentage.
return "<tr><td>" + esc(s.name) + "</td><td>" + esc(s.passed) + "/" + esc(s.total) +
"</td><td>" + esc(Number(s.pass_rate).toFixed(1)) + "%</td></tr>";
}).join("");
evalBody.innerHTML =
"<p>Verified run <code>" + esc(d.run_id) + "</code> at " + esc(d.run_at) +
"; promotion receipt <code>" + esc(d.promotion_sha256) + "</code>.</p>" +
"<p>Total: " + esc(d.total.passed) + "/" + esc(d.total.total) + " (" +
esc(Number(d.total.pass_rate).toFixed(1)) + "%).</p>" +
"<table><thead><tr><th>suite</th><th>passed</th><th>rate</th></tr></thead><tbody>" +
rows + "</tbody></table>";
say("Eval report loaded.");
}).catch(function () { say("Could not reach the console API.", true); });
});
})();
</script>
</body>
</html>
"""