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
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456 | from __future__ import annotations
import logging
import re
from collections import deque
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from hashlib import sha256
from html import escape
from ipaddress import ip_address
from pathlib import Path
from secrets import compare_digest
from typing import cast
from urllib.parse import ParseResult, urlparse
from uuid import uuid4
import asyncpg
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import FileResponse, HTMLResponse
from backend.app.core.config import config
from backend.app.core.request_id import safe_request_id
from backend.app.schemas.poc import (
CertificateRecordInput,
DemoMaterialsRequest,
DemoMaterialsResponse,
DemoSessionResponse,
IssuerVerificationStateInput,
NarrowedVerifierRequest,
NarrowedVerifierResponse,
NetworkOutboxOperatorStatusResponse,
QRCodeImageDecodeRequest,
QRCodeImageDecodeResponse,
ScannerDecisionAction,
ScannerDecisionContract,
ScannerDecisionContractCacheFreshness,
ScannerDecisionContractDestination,
ScannerDecisionContractHoldToOpen,
ScannerDecisionContractTrustPath,
ScannerDecisionContractTrustStep,
ScannerDecisionDestination,
ScannerDecisionGovernance,
ScannerDecisionIssuer,
ScannerDecisionOperatorStatusResponse,
ScannerDecisionRequest,
ScannerDecisionResponse,
ScannerDecisionSignal,
ScannerDecisionUX,
ScannerUXExperimentFixtureResponse,
ScannerUXEventLogEntry,
ScannerUXEventLogListResponse,
ScannerUXEventLogRequest,
ScannerUXEventLogResponse,
ScannedVerifierRequest,
SignedClaimsInput,
SignedEnvelopeInput,
RuntimeSafetyObservationOperatorStatusResponse,
VerifierAPIKeyIssueRequest,
VerifierAPIKeyIssueResponse,
VerifierAPIKeyListResponse,
VerifierAPIKeyRevokeResponse,
VerifierAPIKeyRotateRequest,
VerifierProfileState,
VerifierProviderProfileResponse,
VerifierStatusResponse,
)
from backend.app.services.qr_artifact_poc import (
QRArtifactAnalysis,
QRArtifactError,
analyze_qr_artifact_from_png_bytes,
decode_image_base64,
decode_envelope_from_qr_payload,
decode_qr_payload_from_png_bytes,
encode_envelope_as_qr_payload,
render_qr_png_base64,
)
from backend.app.services.narrowed_verifier_poc import (
IssuerVerificationState,
NarrowedVerifierService,
)
from backend.app.services.demo_session_store import InMemoryDemoSessionStore
from backend.app.services.governance_fixture_store import (
GovernanceTrustProjection,
load_governance_projection,
)
from backend.app.services.request_rate_limiter import RequestRateLimiter
from backend.app.services.redirect_policy_poc import (
RedirectPolicyVerdict,
evaluate_redirect_policy,
)
from backend.app.services.replay_guard_poc import InMemoryReplayGuard
from backend.app.services.runtime_safety_poc import (
RuntimeSafetyVerdict,
evaluate_runtime_safety,
)
from backend.app.services.trust_residuals_decision import (
Decision,
decide as decide_trust_residuals,
)
from backend.app.services.network_outbox_status import load_network_outbox_operator_status
from backend.app.services.network_evidence_recorder import record_scanner_evidence
from backend.app.services.management_auth import (
ManagementPrincipal,
ManagementUnauthorized,
load_management_principal,
require_scope,
)
from backend.app.services.runtime_observation_status import (
load_runtime_observation_operator_status,
)
from backend.app.services.scanner_decision_status import load_scanner_decision_operator_status
from backend.app.services.scanner_ux_ab_fixture import build_scanner_ux_ab_fixture
from backend.app.services.signed_schema_poc import (
CertificateAuthorityRecord,
SUPPORTED_ALGORITHM_ID,
USAGE_POLICY_ONE_TIME,
USAGE_POLICY_REUSABLE_PUBLIC,
USAGE_POLICY_TIME_LIMITED,
SignedQRCodeEnvelope,
SignedSchemaError,
build_demo_certificate,
create_signed_envelope,
parse_claims_mapping,
)
from backend.app.services.verifier_api_key_service import (
VerifierAPIKeyStoreUnavailable,
verifier_api_key_service,
)
from backend.app.services.redis_service import redis_service
router = APIRouter()
scanner_router = APIRouter()
logger = logging.getLogger(__name__)
_LAB_HTML_PATH = Path(__file__).resolve().parents[2] / "static" / "verifier_lab.html"
_QR_DISPLAY_HTML_PATH = Path(__file__).resolve().parents[2] / "static" / "verifier_qr_display.html"
_replay_guard = InMemoryReplayGuard()
_verifier = NarrowedVerifierService(_replay_guard)
_request_rate_limiter = RequestRateLimiter()
_demo_session_store = InMemoryDemoSessionStore()
_scanner_ux_event_log: deque[ScannerUXEventLogEntry] = deque(maxlen=500)
_LEGACY_VERIFIER_ADMIN_API_KEYS_DETAIL = (
"Verifier API key management moved to /admin/verifier-clients/api-keys. "
"Use the management API so verifier client key changes are scoped and audited."
)
_VALID_VERIFIER_PROFILE_STATES = frozenset({"active", "stale", "revoked"})
_OPERATOR_STATUS_READ_SCOPES = ("audit:read", "outbox:read", "runtime:read")
@dataclass(frozen=True)
class ScannerTrustRecord:
certificate: CertificateRecordInput
issuer_state: IssuerVerificationStateInput
governance: GovernanceTrustProjection | None = None
_scanner_trust_records: dict[str, ScannerTrustRecord] = {}
# Payload encoded into the rendered QR image for the payload-mismatch artifact
# profile. It stands in for an attacker sticker pasted over a legitimate print,
# so it must differ from any signed demo payload.
_ARTIFACT_MISMATCH_OVERLAY_PAYLOAD = "https://evil.example/pay"
_SUSPICIOUS_SCANNER_TLDS = frozenset({"zip", "mov", "click", "top", "xyz"})
_COMMON_MULTI_LABEL_PUBLIC_SUFFIXES = frozenset(
{
"ac.uk",
"co.in",
"co.jp",
"co.nz",
"co.uk",
"com.au",
"com.br",
"com.mx",
"gov.uk",
"ne.jp",
"net.au",
"org.au",
"org.uk",
}
)
_COMMON_SECOND_LEVEL_CCTLD_LABELS = frozenset(
{
"ac",
"co",
"com",
"edu",
"go",
"gov",
"mil",
"ne",
"net",
"or",
"org",
}
)
_LOCAL_KNOWN_BAD_SCANNER_DOMAINS = frozenset(
{"evil.example", "malware.example", "phish.example"}
)
_DOMAIN_TEXT_RE = re.compile(
r"(?<!@)\b(?:https?://)?([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"
r"(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+)\b",
re.IGNORECASE,
)
def _safe_request_id(value: str | None) -> str:
return safe_request_id(value)
def _request_id_for_context(request: Request) -> str:
request_id = getattr(request.state, "request_id", None)
if isinstance(request_id, str):
return _safe_request_id(request_id)
return _safe_request_id(request.headers.get("X-Request-ID"))
def _scanner_governance_response(
governance: GovernanceTrustProjection | None,
) -> ScannerDecisionGovernance | None:
if governance is None:
return None
return ScannerDecisionGovernance(
root_program_id=governance.root_program_id,
delegated_authority_id=governance.delegated_authority_id,
issuer_id=governance.issuer_id,
issuer_namespace_label=governance.issuer_namespace_label,
issuer_display_name=governance.issuer_display_name,
assurance_tier=governance.assurance_tier,
destination_policy_id=governance.destination_policy_id,
cache_entry_id=governance.cache_entry_id,
cache_freshness_state=governance.cache_freshness_state(),
cache_state_published_at=governance.cache_state_published_at,
cache_generated_at=governance.cache_generated_at,
cache_expires_at=governance.cache_expires_at,
max_staleness_seconds=governance.max_staleness_seconds,
stale_behavior=governance.stale_behavior,
source_artifacts=governance.source_artifacts,
)
def _configured_verifier_api_keys() -> list[str]:
return verifier_api_key_service.configured_api_keys()
def _configured_admin_tokens() -> list[str]:
return verifier_api_key_service.configured_admin_tokens()
def _configured_verifier_profile_state() -> VerifierProfileState:
state = config.VERIFIER_PROVIDER_PROFILE_STATE.strip().lower()
if state in _VALID_VERIFIER_PROFILE_STATES:
return cast(VerifierProfileState, state)
logger.warning(
"Ignoring invalid VERIFIER_PROVIDER_PROFILE_STATE=%r; falling back to active",
config.VERIFIER_PROVIDER_PROFILE_STATE,
)
return "active"
def _is_safe_request_base_host(host: str) -> bool:
normalized = host.strip().strip("[]").lower()
if normalized in {"localhost", "testserver"}:
return True
try:
address = ip_address(normalized)
except ValueError:
return False
return address.is_loopback or address.is_private
def _request_host_base_url(request: Request) -> str | None:
raw_host = request.headers.get("host", "").strip()
if not raw_host:
return None
parsed = _parse_url_with_valid_port(f"//{raw_host}")
if (
parsed is None
or parsed.username
or parsed.password
or parsed.hostname is None
or not _is_safe_request_base_host(parsed.hostname)
):
return None
scheme = str(request.scope.get("scheme") or request.url.scheme or "http")
return f"{scheme}://{parsed.netloc}"
def _request_public_base_url(request: Request) -> str:
configured = (config.VERIFIER_PUBLIC_BASE_URL or "").strip().rstrip("/")
if configured:
parsed = _parse_url_with_valid_port(configured)
if (
parsed is not None
and parsed.scheme in {"http", "https"}
and parsed.netloc
and not parsed.username
and not parsed.password
):
return f"{parsed.scheme}://{parsed.netloc}"
logger.warning(
"Ignoring invalid VERIFIER_PUBLIC_BASE_URL=%r; falling back to request base URL",
config.VERIFIER_PUBLIC_BASE_URL,
)
host_base_url = _request_host_base_url(request)
if host_base_url is not None:
return host_base_url
server = request.scope.get("server")
if isinstance(server, tuple) and server and server[0]:
host = str(server[0]).strip("[]")
port = int(server[1]) if len(server) > 1 and server[1] else None
scheme = str(request.scope.get("scheme") or request.url.scheme or "http")
default_port = (scheme == "http" and port == 80) or (
scheme == "https" and port == 443
)
port_label = "" if port is None or default_port else f":{port}"
return f"{scheme}://{host}{port_label}"
return "http://127.0.0.1"
def _parse_url_with_valid_port(value: str) -> ParseResult | None:
try:
parsed = urlparse(value)
_ = parsed.port
except ValueError:
return None
return parsed
async def _verifier_auth_enabled() -> bool:
return await verifier_api_key_service.auth_is_enabled()
async def _request_identity_key(request: Request) -> str:
provided_api_key = request.headers.get(config.VERIFIER_API_KEY_HEADER)
if provided_api_key:
try:
if await verifier_api_key_service.has_valid_key(provided_api_key):
digest = sha256(provided_api_key.encode("utf-8")).hexdigest()[:16]
return f"key:{digest}"
except Exception as exc:
logger.warning("verifier_api_key_identity_unavailable: %s", exc)
client = request.client.host if request.client else "unknown"
return f"ip:{client.strip() or 'unknown'}"
async def _enforce_verifier_api_key(request: Request) -> None:
if not await _verifier_auth_enabled():
return
provided_api_key = request.headers.get(config.VERIFIER_API_KEY_HEADER)
if not provided_api_key:
raise HTTPException(
status_code=401,
detail="Missing verifier API key",
)
try:
if await verifier_api_key_service.has_valid_key(provided_api_key):
return
except VerifierAPIKeyStoreUnavailable as exc:
logger.warning("verifier_api_key_store_unavailable: %s", exc)
raise HTTPException(
status_code=503,
detail="Verifier API key store unavailable",
) from exc
raise HTTPException(
status_code=403,
detail="Invalid verifier API key",
)
def _request_has_valid_admin_token(request: Request) -> bool:
provided_token = request.headers.get(config.VERIFIER_ADMIN_HEADER)
if not provided_token:
return False
return any(
compare_digest(provided_token, expected_token)
for expected_token in _configured_admin_tokens()
)
def _asyncpg_dsn(dsn: str) -> str:
if dsn.startswith("postgresql+asyncpg://"):
return dsn.replace("postgresql+asyncpg://", "postgresql://", 1)
return dsn
def _management_database_url() -> str | None:
return config.QRTRUST_NETWORK_DATABASE_URL or config.DATABASE_URL
def _management_principal_can_read_operator_status(
principal: ManagementPrincipal,
) -> bool:
for scope in _OPERATOR_STATUS_READ_SCOPES:
try:
require_scope(principal, scope)
return True
except ManagementUnauthorized:
continue
return False
async def _request_has_valid_management_credential(request: Request) -> bool:
provided_token = request.headers.get(config.VERIFIER_ADMIN_HEADER)
if not provided_token:
return False
if _request_has_valid_admin_token(request):
return True
dsn = _management_database_url()
if dsn is None:
return False
connection = None
try:
connection = await asyncpg.connect(_asyncpg_dsn(dsn))
principal = await load_management_principal(connection, provided_token)
except Exception as exc:
logger.warning("management_status_credential_unavailable: %s", exc)
return False
finally:
if connection is not None:
await connection.close()
if principal is None:
return False
return _management_principal_can_read_operator_status(principal)
async def _request_can_read_operator_status(request: Request) -> bool:
if not await _verifier_auth_enabled():
return True
return await _request_has_valid_management_credential(request)
def _enforce_verifier_admin_token(request: Request) -> None:
configured_admin_tokens = _configured_admin_tokens()
if not configured_admin_tokens:
raise HTTPException(
status_code=503,
detail="Verifier admin flow is not configured",
)
provided_token = request.headers.get(config.VERIFIER_ADMIN_HEADER)
if not provided_token:
raise HTTPException(
status_code=401,
detail="Missing verifier admin token",
)
if any(compare_digest(provided_token, expected_token) for expected_token in configured_admin_tokens):
return
raise HTTPException(
status_code=403,
detail="Invalid verifier admin token",
)
def _raise_legacy_verifier_admin_api_key_route() -> None:
raise HTTPException(status_code=410, detail=_LEGACY_VERIFIER_ADMIN_API_KEYS_DETAIL)
async def _enforce_verifier_rate_limit(request: Request, *, bucket: str) -> None:
limit = (
config.VERIFIER_DECODE_RATE_LIMIT_MAX_REQUESTS
if bucket == "decode_image"
else config.VERIFIER_RATE_LIMIT_MAX_REQUESTS
)
identity_key = await _request_identity_key(request)
decision = await _request_rate_limiter.check(
f"{bucket}:{identity_key}",
limit=limit,
window_seconds=config.VERIFIER_RATE_LIMIT_WINDOW_SECONDS,
)
if decision.allowed:
return
raise HTTPException(
status_code=429,
detail="Rate limit exceeded for verifier endpoint",
headers={"Retry-After": str(decision.retry_after_seconds or 1)},
)
def _build_demo_materials_response(
request: DemoMaterialsRequest,
) -> DemoMaterialsResponse:
certificate, private_key_pem = build_demo_certificate()
now = datetime.now(timezone.utc)
claims = parse_claims_mapping(
{
"version": "1",
"usage_policy": request.usage_policy,
"certificate_ref": certificate.certificate_ref,
"issued_at": (now + timedelta(minutes=request.issued_offset_minutes)).isoformat(),
"expires_at": (now + timedelta(minutes=request.expires_offset_minutes)).isoformat(),
"nonce": request.nonce,
"payload": request.payload,
}
)
envelope = create_signed_envelope(
claims,
private_key_pem,
code_algorithm_id=SUPPORTED_ALGORITHM_ID,
)
certificate_input = CertificateRecordInput(
certificate_ref=certificate.certificate_ref,
issuer_name=certificate.issuer_name,
algorithm_id=certificate.algorithm_id,
public_key_pem=certificate.public_key_pem,
)
issuer_state_input = IssuerVerificationStateInput(
verified_domains=request.verified_domains,
allow_subdomains=request.allow_subdomains,
certificate_active=request.certificate_active,
certificate_revoked=request.certificate_revoked,
certificate_revocation_reason=request.certificate_revocation_reason,
)
verify_request = NarrowedVerifierRequest(
envelope=SignedEnvelopeInput(
claims=SignedClaimsInput(**claims.__dict__),
signature=envelope.signature,
code_algorithm_id=envelope.code_algorithm_id,
),
certificate=certificate_input,
issuer_state=issuer_state_input,
)
qr_payload = encode_envelope_as_qr_payload(envelope)
governance = load_governance_projection(
certificate.certificate_ref,
cache_profile=request.governance_cache_profile,
)
# The rendered PNG normally matches the signed payload with a full quiet
# zone. The artifact profiles produce tampered prints for the lab: a
# low-quiet-zone render trips the visual artifact warning, and a
# payload-mismatch render encodes an attacker payload so the image no
# longer matches the submitted scanner payload.
if request.artifact_profile == "low-quiet-zone":
qr_png_base64 = render_qr_png_base64(qr_payload, border=0)
elif request.artifact_profile == "payload-mismatch":
qr_png_base64 = render_qr_png_base64(_ARTIFACT_MISMATCH_OVERLAY_PAYLOAD)
else:
qr_png_base64 = render_qr_png_base64(qr_payload)
response = DemoMaterialsResponse(
certificate=certificate_input,
issuer_state=issuer_state_input,
governance=_scanner_governance_response(governance),
verify_request=verify_request,
qr_payload=qr_payload,
qr_png_base64=qr_png_base64,
)
# Demo materials normally enroll the certificate in the scanner trust
# store; skipping enrollment yields a signed envelope whose issuer the
# scanner does not recognize (the signed_unknown_issuer path).
if request.register_scanner_trust:
_register_scanner_trust(
response.certificate,
response.issuer_state,
governance=governance,
)
else:
# The demo certificate_ref is shared across generations, so an earlier
# demo may have enrolled it; drop it so the ref is genuinely unknown.
_scanner_trust_records.pop(response.certificate.certificate_ref, None)
return response
def _build_demo_session_response(
demo_materials: DemoMaterialsResponse,
) -> DemoSessionResponse:
record = _demo_session_store.create(demo_materials)
return DemoSessionResponse(
session_id=record.session_id,
display_path=f"/verifier/demo-sessions/{record.session_id}/display",
**demo_materials.model_dump(),
)
def _register_scanner_trust(
certificate: CertificateRecordInput,
issuer_state: IssuerVerificationStateInput,
*,
governance: GovernanceTrustProjection | None = None,
) -> None:
_scanner_trust_records[certificate.certificate_ref] = ScannerTrustRecord(
certificate=certificate,
issuer_state=issuer_state,
governance=(
governance
if governance is not None
else load_governance_projection(certificate.certificate_ref)
),
)
def _parsed_http_url(value: str) -> ParseResult | None:
parsed = urlparse(value)
if parsed.scheme.lower() not in {"http", "https"}:
return None
return parsed
def _url_host(value: str) -> str | None:
parsed = _parsed_http_url(value)
if parsed is None or parsed.hostname is None:
return None
return parsed.hostname.strip(".").lower() or None
def _looks_like_url(value: str) -> bool:
return _url_host(value) is not None
def _scanner_destination(
value: str,
*,
binding: str,
resolver_url: str | None = None,
final_url: str | None = None,
redirect_hops: int | None = None,
redirect_policy: str | None = None,
) -> ScannerDecisionDestination:
return ScannerDecisionDestination(
display_url=value[:2048],
host=_url_host(value),
binding=binding,
resolver_url=resolver_url[:2048] if resolver_url else None,
final_url=final_url[:2048] if final_url else None,
redirect_hops=redirect_hops,
redirect_policy=redirect_policy,
)
def _scanner_actions(*, decision_state: str, open_allowed: bool) -> list[ScannerDecisionAction]:
if decision_state == "blocked":
return [
ScannerDecisionAction(id="dismiss", label="Do not open", style="danger"),
ScannerDecisionAction(id="copy_destination", label="Copy destination", style="secondary"),
]
if decision_state == "verified_issuer":
return [
ScannerDecisionAction(id="open_destination", label="Open verified destination", style="primary"),
ScannerDecisionAction(id="copy_destination", label="Copy destination", style="secondary"),
]
if open_allowed:
return [
ScannerDecisionAction(id="continue_caution", label="Continue with caution", style="warning"),
ScannerDecisionAction(id="copy_destination", label="Copy destination", style="secondary"),
]
return [
ScannerDecisionAction(id="dismiss", label="Do not open", style="danger"),
ScannerDecisionAction(id="copy_payload", label="Copy payload", style="secondary"),
]
def _registrable_domain(host: str | None) -> str | None:
if not host:
return None
normalized = host.strip().strip(".").lower()
if not normalized:
return None
if normalized == "localhost" or normalized.replace(".", "").isdigit():
return normalized
labels = [label for label in normalized.split(".") if label]
if len(labels) < 2:
return normalized
suffix = ".".join(labels[-2:])
if suffix in _COMMON_MULTI_LABEL_PUBLIC_SUFFIXES and len(labels) >= 3:
return ".".join(labels[-3:])
second_level = labels[-2]
tld = labels[-1]
if (
len(tld) == 2
and second_level in _COMMON_SECOND_LEVEL_CCTLD_LABELS
and len(labels) >= 3
):
return ".".join(labels[-3:])
return ".".join(labels[-2:])
def _domain_fingerprint(domain: str | None) -> str | None:
if not domain:
return None
labels = domain.split(".")
if len(labels) < 2:
return domain
tld = labels[-1]
body = ".".join(labels[:-1])
if len(body) <= 8:
return domain
return f"{body[:3]}...{body[-3:]}.{tld}"
def _is_https_absent(value: str) -> bool:
parsed = _parsed_http_url(value)
return parsed is not None and parsed.scheme.lower() == "http"
def _has_embedded_credentials(value: str) -> bool:
parsed = _parsed_http_url(value)
if parsed is None:
return False
return parsed.username is not None or parsed.password is not None
def _has_suspicious_tld(host: str | None) -> bool:
if not host:
return False
labels = [label for label in host.strip().strip(".").lower().split(".") if label]
return bool(labels and labels[-1] in _SUSPICIOUS_SCANNER_TLDS)
def _normalized_host(value: str | None) -> str | None:
if not value:
return None
parsed = _parsed_http_url(value)
host = parsed.hostname if parsed is not None else value
normalized = host.strip().strip(".").lower()
return normalized or None
def _host_identity_set(value: str | None) -> set[str]:
host = _normalized_host(value)
if not host:
return set()
return {item for item in {host, _registrable_domain(host)} if item}
def _request_host_set(values: list[str] | None) -> set[str]:
hosts: set[str] = set()
for value in values or []:
hosts.update(_host_identity_set(value))
return hosts
def _scanner_risk_hosts(response: ScannerDecisionResponse) -> list[str]:
hosts: list[str] = []
for value in _scanner_risk_urls(response):
hosts.extend(_host_identity_set(value))
hosts.extend(_host_identity_set(response.destination.host))
return list(dict.fromkeys(hosts))
def _caption_domains(value: str | None) -> set[str]:
domains: set[str] = set()
if not value:
return domains
for match in _DOMAIN_TEXT_RE.finditer(value):
domains.update(_host_identity_set(match.group(1)))
return domains
def _domain_age_for_host(
request: ScannerDecisionRequest | None,
host: str,
) -> int | None:
if request is None:
return None
for identity in _host_identity_set(host):
value = request.domain_age_days.get(identity)
if value is not None:
return value
return None
def _scanner_risk_urls(response: ScannerDecisionResponse) -> list[str]:
urls = [
response.destination.display_url,
response.destination.resolver_url,
response.destination.final_url,
]
return list(dict.fromkeys(url for url in urls if url))
_SCANNER_CONTRACT_LAYER_LABELS = {
"issuer_legitimacy": "Issuer legitimacy",
"destination_binding": "Destination binding",
"runtime_safety": "Runtime safety",
"scanner_decision": "Scanner decision",
}
_SCANNER_CONTRACT_DEFAULT_MESSAGES = {
"issuer_legitimacy": "Issuer enrollment was not confirmed.",
"destination_binding": "Destination binding was not evaluated.",
"runtime_safety": "Runtime safety was not evaluated.",
"scanner_decision": "Scanner-visible decision was produced.",
}
def _scanner_contract_color(risk_level: str) -> str:
if risk_level == "amber":
return "orange"
if risk_level == "red":
return "red"
return "green"
def _scanner_contract_cache_freshness(
response: ScannerDecisionResponse,
) -> ScannerDecisionContractCacheFreshness:
if response.governance is None:
return ScannerDecisionContractCacheFreshness(status="not_applicable")
status = response.governance.cache_freshness_state
if status not in {"fresh", "stale", "expired"}:
status = "unavailable"
return ScannerDecisionContractCacheFreshness(
status=status,
cache_generated_at=response.governance.cache_generated_at,
cache_expires_at=response.governance.cache_expires_at,
)
def _scanner_contract_step(
layer: str,
*,
response: ScannerDecisionResponse,
scanner_ux: ScannerDecisionUX,
) -> ScannerDecisionContractTrustStep:
signal = next((item for item in response.signals if item.layer == layer), None)
status = signal.state if signal else "not_evaluated"
message = (
signal.message
if signal and signal.message
else (
response.primary_message
if layer == "scanner_decision"
else _SCANNER_CONTRACT_DEFAULT_MESSAGES[layer]
)
)
return ScannerDecisionContractTrustStep(
status=status,
label=_SCANNER_CONTRACT_LAYER_LABELS[layer],
message=message,
reason_codes=scanner_ux.reason_codes if layer == "scanner_decision" else [],
)
def _scanner_decision_contract(
response: ScannerDecisionResponse,
*,
scanner_ux: ScannerDecisionUX,
decision_id: str,
) -> ScannerDecisionContract:
display_host = (
scanner_ux.destination_display
or response.destination.host
or _url_host(response.destination.display_url)
or "unreadable"
)
fingerprint = (
scanner_ux.destination_fingerprint
or _domain_fingerprint(display_host)
or display_host
)
return ScannerDecisionContract(
decision_id=decision_id,
decided_at=datetime.now(timezone.utc).isoformat(),
decision_color=_scanner_contract_color(scanner_ux.risk_level),
decision_state=response.decision_state,
reason_codes=scanner_ux.reason_codes,
risk_score=scanner_ux.risk_score,
destination=ScannerDecisionContractDestination(
display_host=display_host,
fingerprint=fingerprint,
url=response.destination.display_url,
resolver_url=response.destination.resolver_url,
final_url=response.destination.final_url,
),
trust_path=ScannerDecisionContractTrustPath(
issuer_legitimacy=_scanner_contract_step(
"issuer_legitimacy",
response=response,
scanner_ux=scanner_ux,
),
destination_binding=_scanner_contract_step(
"destination_binding",
response=response,
scanner_ux=scanner_ux,
),
runtime_safety=_scanner_contract_step(
"runtime_safety",
response=response,
scanner_ux=scanner_ux,
),
scanner_decision=_scanner_contract_step(
"scanner_decision",
response=response,
scanner_ux=scanner_ux,
),
),
hold_to_open=ScannerDecisionContractHoldToOpen(
required=scanner_ux.hold_required,
duration_ms=scanner_ux.hold_ms,
reason_codes=scanner_ux.reason_codes if scanner_ux.hold_required else [],
),
cache_freshness=_scanner_contract_cache_freshness(response),
governance=(
response.governance.model_dump(mode="json")
if response.governance is not None
else {}
),
)
def _scanner_ux_for_response(
response: ScannerDecisionResponse,
*,
request: ScannerDecisionRequest | None = None,
) -> ScannerDecisionUX:
reason_codes: list[str] = []
score = 0
runtime_signal = next(
(signal for signal in response.signals if signal.layer == "runtime_safety"),
None,
)
artifact_signal = next(
(signal for signal in response.signals if signal.layer == "artifact_integrity"),
None,
)
if response.decision_state == "verified_issuer":
score = 0
elif response.decision_state == "verified_issuer_destination_risky":
score += 35
runtime_state = runtime_signal.state if runtime_signal is not None else "risky"
if runtime_state in {"stale", "unavailable"}:
reason_codes.append(f"runtime_{runtime_state}")
else:
reason_codes.append("runtime_risky")
elif response.decision_state == "stale_trust_state":
score += 40
reason_codes.append("stale_trust_state")
elif response.decision_state == "profile_stale":
score += 40
reason_codes.append("verifier_profile_stale")
elif response.decision_state == "profile_revoked":
score += 80
reason_codes.append("verifier_profile_revoked")
elif response.decision_state == "signed_unknown_issuer":
score += 35
reason_codes.append("issuer_unknown")
elif response.decision_state == "unverified":
score += 30
reason_codes.append("plain_url" if response.open_allowed else "unreadable_payload")
elif response.decision_state == "blocked":
score += 60
if artifact_signal is not None:
if artifact_signal.state == "warn":
score += 30
reason_codes.append("artifact_warning")
elif artifact_signal.state == "block":
score += 60
reason_codes.append("artifact_integrity_block")
match response.verifier_stage:
case "payload_revalidation":
reason_codes.append("destination_mismatch")
case "replay_guard":
reason_codes.append("one_time_used")
case "redirect_policy":
reason_codes.append("redirect_policy_block")
case "runtime_safety":
if not any(reason.startswith("runtime_") for reason in reason_codes):
reason_codes.append("runtime_blocked")
case "governance_cache":
if "stale_trust_state" not in reason_codes:
reason_codes.append("trust_cache_unavailable")
case "signed_schema":
reason_codes.append("signature_invalid")
case "artifact_integrity":
if "artifact_integrity_block" not in reason_codes:
reason_codes.append("artifact_integrity_block")
if response.destination.redirect_hops and response.destination.redirect_hops > 1:
score += 10
reason_codes.append("redirect_chain")
risk_urls = _scanner_risk_urls(response)
if any(_is_https_absent(url) for url in risk_urls):
score += 15
reason_codes.append("https_absent")
if any(_has_embedded_credentials(url) for url in risk_urls):
score += 15
reason_codes.append("embedded_credentials")
if _has_suspicious_tld(response.destination.host) or any(
_has_suspicious_tld(_url_host(url)) for url in risk_urls
):
score += 15
reason_codes.append("suspicious_tld")
risk_hosts = _scanner_risk_hosts(response)
destination_identities: set[str] = set()
for host in risk_hosts:
destination_identities.update(_host_identity_set(host))
allow_client_domain_hints = response.decision_state in {
"signed_unknown_issuer",
"unverified",
}
caption_domains = _caption_domains(request.display_text if request else None)
if (
caption_domains
and destination_identities
and caption_domains.isdisjoint(destination_identities)
):
score += 25
reason_codes.append("caption_domain_mismatch")
request_known_bad_hosts = (
_request_host_set(request.known_bad_hosts if request else [])
if allow_client_domain_hints
else set()
)
known_bad_hosts = request_known_bad_hosts | set(_LOCAL_KNOWN_BAD_SCANNER_DOMAINS)
if destination_identities & known_bad_hosts:
score += 35
reason_codes.append("known_bad_domain")
newly_registered_hosts = _request_host_set(
request.newly_registered_hosts if request and allow_client_domain_hints else []
)
has_new_domain = bool(destination_identities & newly_registered_hosts)
if allow_client_domain_hints and not has_new_domain:
for host in destination_identities:
age_days = _domain_age_for_host(request, host)
if age_days is not None and age_days <= 14:
has_new_domain = True
break
if has_new_domain:
score += 35
reason_codes.append("newly_registered_domain")
if (
allow_client_domain_hints
and request is not None
and request.prior_opened_hosts is not None
):
prior_hosts = _request_host_set(request.prior_opened_hosts)
if destination_identities and destination_identities.isdisjoint(prior_hosts):
score += 10
reason_codes.append("net_new_domain")
score = min(score, 100)
if score >= 60:
risk_level = "red"
elif score >= 30:
risk_level = "amber"
else:
risk_level = "green"
destination_display = _registrable_domain(response.destination.host)
hold_required = response.open_allowed and score >= 30
primary_action = "Open"
if not response.open_allowed:
primary_action = "Do not open"
elif hold_required:
primary_action = "Open with caution"
return ScannerDecisionUX(
risk_score=score,
risk_level=risk_level,
risk_stripe=risk_level,
hold_required=hold_required,
hold_ms=800 if hold_required else 0,
reason_codes=sorted(set(reason_codes)),
destination_display=destination_display,
destination_fingerprint=_domain_fingerprint(destination_display),
primary_action=primary_action,
)
def _with_scanner_ux(
response: ScannerDecisionResponse,
*,
request: ScannerDecisionRequest | None = None,
) -> ScannerDecisionResponse:
request_id = _safe_request_id(response.request_id)
decision_id = f"scan_{uuid4().hex}"
response_with_id = response.model_copy(update={"request_id": request_id})
scanner_ux = _scanner_ux_for_response(response_with_id, request=request)
return response_with_id.model_copy(
update={
"scanner_ux": scanner_ux,
"contract": _scanner_decision_contract(
response_with_id,
scanner_ux=scanner_ux,
decision_id=decision_id,
),
},
)
def _unverified_scanner_decision(
payload: str,
*,
reason: str,
request_id: str | None,
) -> ScannerDecisionResponse:
trimmed_payload = payload.strip()
has_url_destination = _looks_like_url(trimmed_payload)
primary = (
"No recognized trust signal is available for this QR. Review the destination before continuing."
if has_url_destination
else "This QR does not contain a scanner-verifiable URL or signed trust envelope."
)
destination_message = (
"This is a regular URL QR. No issuer-approved destination binding was available."
if has_url_destination
else "This payload is neither a URL nor a signed QR Trust envelope."
)
verifier_reason = (
"Plain URL QR without a signed QR Trust envelope"
if has_url_destination
else reason
)
return ScannerDecisionResponse(
decision_state="unverified",
open_allowed=has_url_destination,
usage_policy=None,
primary_message=primary,
issuer=ScannerDecisionIssuer(status="none"),
destination=_scanner_destination(
trimmed_payload or "unreadable QR payload",
binding="unverified",
),
signals=[
ScannerDecisionSignal(layer="issuer_legitimacy", state="none", message="No signed trust path was found."),
ScannerDecisionSignal(layer="destination_binding", state="unverified", message=destination_message),
ScannerDecisionSignal(layer="runtime_safety", state="not_evaluated", message="Runtime safety is not evaluated without a trust path."),
ScannerDecisionSignal(layer="scanner_decision", state="caution" if has_url_destination else "blocked"),
],
actions=_scanner_actions(decision_state="unverified", open_allowed=has_url_destination),
verifier_stage="qr_decode",
verifier_reason=verifier_reason,
request_id=request_id,
)
def _signed_unknown_issuer_decision(
envelope: SignedQRCodeEnvelope,
*,
request_id: str | None,
) -> ScannerDecisionResponse:
destination = envelope.claims.payload
return ScannerDecisionResponse(
decision_state="signed_unknown_issuer",
open_allowed=_looks_like_url(destination),
usage_policy=envelope.claims.usage_policy,
primary_message=(
"The QR uses the signed-envelope format, but this verifier has no registered issuer state "
"for its certificate reference."
),
issuer=ScannerDecisionIssuer(
name=None,
tier=None,
status="unknown",
),
destination=_scanner_destination(destination, binding="unknown"),
signals=[
ScannerDecisionSignal(
layer="issuer_legitimacy",
state="unknown",
message=f"No trust record for {envelope.claims.certificate_ref}.",
),
ScannerDecisionSignal(layer="destination_binding", state="unknown", message="Destination policy was not available."),
ScannerDecisionSignal(layer="runtime_safety", state="not_evaluated"),
ScannerDecisionSignal(layer="scanner_decision", state="caution"),
],
actions=_scanner_actions(decision_state="signed_unknown_issuer", open_allowed=_looks_like_url(destination)),
verifier_stage="issuer_lookup",
verifier_reason="Signed envelope issuer is not enrolled in this verifier instance",
request_id=request_id,
)
def _scanner_claimed_destination_from_payload(
qr_payload: str,
) -> tuple[str, str | None]:
trimmed_payload = qr_payload.strip()
if _looks_like_url(trimmed_payload):
return trimmed_payload, None
try:
envelope = decode_envelope_from_qr_payload(trimmed_payload)
except QRArtifactError:
return trimmed_payload or "unreadable QR payload", None
return envelope.claims.payload, envelope.claims.usage_policy
def _verifier_profile_state_decision(
request: ScannerDecisionRequest,
*,
request_id: str | None,
) -> ScannerDecisionResponse | None:
client_profile_state = (
request.client.verifier_profile_state
if request.client is not None
else "active"
)
profile_state = _strictest_verifier_profile_state(
_configured_verifier_profile_state(),
client_profile_state,
)
if profile_state == "active":
return None
destination, usage_policy = _scanner_claimed_destination_from_payload(
request.qr_payload,
)
has_url_destination = _looks_like_url(destination)
is_revoked = profile_state == "revoked"
decision_state = "profile_revoked" if is_revoked else "profile_stale"
open_allowed = has_url_destination and not is_revoked
issuer_status = "profile_revoked" if is_revoked else "profile_stale"
destination_binding = "not_evaluated" if is_revoked else "unverified"
scanner_state = "blocked" if is_revoked else ("caution" if has_url_destination else "blocked")
primary_message = (
"This scanner's verifier profile has been revoked. Do not rely on this QR result until a trusted profile is installed."
if is_revoked
else (
"This scanner's verifier profile is stale. A destination was found, but current issuer and destination trust were not confirmed."
if has_url_destination
else "This scanner's verifier profile is stale, and this QR did not expose a safe destination to review."
)
)
verifier_reason = (
"Verifier profile is revoked"
if is_revoked
else "Verifier profile is stale"
)
return ScannerDecisionResponse(
decision_state=decision_state,
open_allowed=open_allowed,
usage_policy=usage_policy,
primary_message=primary_message,
issuer=ScannerDecisionIssuer(
name=None,
tier=None,
status=issuer_status,
),
destination=_scanner_destination(
destination,
binding=destination_binding,
),
signals=[
ScannerDecisionSignal(
layer="issuer_legitimacy",
state="profile_revoked" if is_revoked else "not_checked",
message=(
"The installed verifier profile is revoked, so issuer enrollment was not trusted."
if is_revoked
else "The verifier profile is stale, so current issuer enrollment was not confirmed."
),
),
ScannerDecisionSignal(
layer="destination_binding",
state=destination_binding,
message=(
"Destination binding was not evaluated because the verifier profile is revoked."
if is_revoked
else "A destination was read from the QR, but it was not checked against current issuer policy."
),
),
ScannerDecisionSignal(
layer="runtime_safety",
state="not_evaluated",
message=(
"Runtime safety is not evaluated with a revoked verifier profile."
if is_revoked
else "Current destination safety was not evaluated because the verifier profile is stale."
),
),
ScannerDecisionSignal(
layer="scanner_decision",
state=scanner_state,
),
],
actions=_scanner_actions(
decision_state=decision_state,
open_allowed=open_allowed,
),
verifier_stage="verifier_profile",
verifier_reason=verifier_reason,
request_id=request_id,
)
def _strictest_verifier_profile_state(
*states: VerifierProfileState,
) -> VerifierProfileState:
if "revoked" in states:
return "revoked"
if "stale" in states:
return "stale"
return "active"
def _redacted_network_outbox_status() -> NetworkOutboxOperatorStatusResponse:
return NetworkOutboxOperatorStatusResponse(
status="unavailable",
supervisor_state="unavailable",
summary="Network outbox status requires an authorized operator read.",
reasons=["operator_status_auth_required"],
database_configured=False,
database_dsn_label=None,
metrics=None,
error=None,
)
def _redacted_scanner_decision_status() -> ScannerDecisionOperatorStatusResponse:
return ScannerDecisionOperatorStatusResponse(
status="unavailable",
persistence_state="unavailable",
summary="Scanner-decision evidence requires an authorized operator read.",
reasons=["operator_status_auth_required"],
database_configured=False,
database_dsn_label=None,
report=None,
error=None,
)
def _redacted_runtime_observation_status() -> RuntimeSafetyObservationOperatorStatusResponse:
return RuntimeSafetyObservationOperatorStatusResponse(
status="unavailable",
observation_state="unavailable",
summary="Runtime observation evidence requires an authorized operator read.",
reasons=["operator_status_auth_required"],
database_configured=False,
database_dsn_label=None,
report=None,
error=None,
)
async def _build_verifier_status_response(
*,
include_operator_evidence: bool,
) -> VerifierStatusResponse:
if include_operator_evidence:
network_outbox = await load_network_outbox_operator_status()
scanner_decisions = await load_scanner_decision_operator_status()
runtime_observations = await load_runtime_observation_operator_status()
else:
network_outbox = _redacted_network_outbox_status()
scanner_decisions = _redacted_scanner_decision_status()
runtime_observations = _redacted_runtime_observation_status()
return VerifierStatusResponse(
verifier_profile_state=_configured_verifier_profile_state(),
api_key_auth_enabled=await _verifier_auth_enabled(),
admin_api_key_management_enabled=bool(_configured_admin_tokens()),
api_key_header=config.VERIFIER_API_KEY_HEADER,
admin_header=config.VERIFIER_ADMIN_HEADER,
redis_connected=redis_service.redis_client is not None,
distributed_rate_limiting_enabled=redis_service.redis_client is not None,
decode_image_fallback_enabled=True,
legacy_experimental_api_enabled=config.ENABLE_LEGACY_EXPERIMENTAL_API,
rate_limit_window_seconds=config.VERIFIER_RATE_LIMIT_WINDOW_SECONDS,
rate_limit_max_requests=config.VERIFIER_RATE_LIMIT_MAX_REQUESTS,
decode_rate_limit_max_requests=config.VERIFIER_DECODE_RATE_LIMIT_MAX_REQUESTS,
max_qr_payload_chars=config.MAX_QR_PAYLOAD_CHARS,
max_decode_image_bytes=config.MAX_DECODE_IMAGE_BYTES,
network_outbox=network_outbox,
scanner_decisions=scanner_decisions,
runtime_observations=runtime_observations,
)
def _scanner_binding_for_stage(stage: str, allowed: bool) -> str:
if allowed:
return "bound"
if stage == "payload_revalidation":
return "mismatch"
return "not_evaluated"
def _scanner_primary_message(
result: NarrowedVerifierResponse,
*,
redirect_verdict: RedirectPolicyVerdict | None = None,
runtime_verdict: RuntimeSafetyVerdict | None = None,
artifact_analysis: QRArtifactAnalysis | None = None,
) -> str:
if result.allowed:
if redirect_verdict and redirect_verdict.is_redirect_flow and redirect_verdict.is_blocked:
return "Resolver mismatch. The final destination is not approved by the issuer."
if runtime_verdict and runtime_verdict.state == "risky":
return (
"Verified issuer, but destination risk was detected at scan time. "
"Review before opening."
)
if runtime_verdict and runtime_verdict.state == "blocked":
return "Verified issuer, but runtime safety blocked this destination."
if runtime_verdict and runtime_verdict.state == "expired":
return (
"Verified issuer, but the runtime safety verdict has expired. "
"This destination is blocked until a fresh verdict is available."
)
if runtime_verdict and runtime_verdict.state == "unavailable":
return (
"Verified issuer and destination, but runtime safety could not be checked "
"right now. Continue only if you trust the context."
)
if runtime_verdict and runtime_verdict.state == "stale":
return (
"Verified issuer and destination, but runtime safety data is stale. "
"Review before opening."
)
if redirect_verdict and redirect_verdict.is_redirect_flow:
return "Verified resolver QR. The final destination is still approved by the issuer."
if artifact_analysis and artifact_analysis.artifact_integrity == "warn":
return (
"Verified issuer and destination, but the QR artifact has visual "
"or structural warnings. Review before opening."
)
if result.usage_policy == USAGE_POLICY_ONE_TIME:
return "Verified one-time QR. This destination can be opened."
if result.usage_policy == USAGE_POLICY_TIME_LIMITED:
return "Verified time-limited QR. This destination remains approved right now."
return "Verified reusable QR. This destination is still approved by the issuer."
match result.stage:
case "payload_revalidation":
return "Destination mismatch. The signed QR no longer points to an issuer-approved destination."
case "replay_guard":
return "One-time QR blocked. This QR has already been used or is currently reserved."
case "time_window":
return "Expired or not-yet-valid QR. The scanner stopped before destination evaluation."
case "certificate_status":
return "Issuer credential is inactive or revoked in the verifier state."
case "signed_schema":
return "Signature verification failed for the canonical signed claims."
case _:
return result.reason
def _scanner_issuer_legitimacy_message(record: ScannerTrustRecord) -> str:
if record.governance is None:
return "Issuer record resolved in verifier trust state."
return (
"Issuer resolved through fixture governance namespace "
f"{record.governance.issuer_namespace_label}."
)
def _scanner_destination_binding_message(
redirect_verdict: RedirectPolicyVerdict | None,
) -> str:
if redirect_verdict and redirect_verdict.is_redirect_flow:
return redirect_verdict.reason
return "Destination matches issuer policy."
def _governance_cache_blocking_decision(
envelope: SignedQRCodeEnvelope,
record: ScannerTrustRecord,
*,
request_id: str | None,
) -> ScannerDecisionResponse | None:
governance = record.governance
if governance is None:
return None
freshness_state = governance.cache_freshness_state()
if freshness_state == "fresh":
return None
is_expired = freshness_state == "expired"
decision_state = "blocked" if is_expired else "stale_trust_state"
open_allowed = not is_expired and _looks_like_url(envelope.claims.payload)
primary_message = (
"Required trust state has expired. Ask for a fresh or trusted QR before continuing."
if is_expired
else (
"The QR is signed by a previously recognized issuer, but the verifier's "
"trust cache is stale. Review before opening or refresh trust state."
)
)
verifier_reason = (
"Required governance cache state is expired"
if is_expired
else "Required governance cache state is stale"
)
return ScannerDecisionResponse(
decision_state=decision_state,
open_allowed=open_allowed,
usage_policy=envelope.claims.usage_policy,
primary_message=primary_message,
issuer=ScannerDecisionIssuer(
name=record.certificate.issuer_name,
tier=governance.assurance_tier,
status=freshness_state,
),
destination=_scanner_destination(
envelope.claims.payload,
binding="not_evaluated",
),
governance=_scanner_governance_response(governance),
signals=[
ScannerDecisionSignal(
layer="issuer_legitimacy",
state=freshness_state,
message=(
"The issuer namespace is known, but its required verifier cache "
f"entry is {freshness_state}."
),
),
ScannerDecisionSignal(
layer="destination_binding",
state="not_evaluated",
message=(
"Destination binding is not trusted because required governance "
f"cache state is {freshness_state}."
),
),
ScannerDecisionSignal(
layer="runtime_safety",
state="not_evaluated",
message="Runtime safety is not evaluated without fresh required trust state.",
),
ScannerDecisionSignal(
layer="scanner_decision",
state="blocked" if is_expired else "caution",
),
],
actions=_scanner_actions(
decision_state=decision_state,
open_allowed=open_allowed,
),
verifier_stage="governance_cache",
verifier_reason=verifier_reason,
request_id=request_id,
)
def _scanner_artifact_analysis_for_request(
request: ScannerDecisionRequest,
) -> QRArtifactAnalysis | None:
if request.image_base64 is None:
return None
image_bytes = decode_image_base64(request.image_base64)
return analyze_qr_artifact_from_png_bytes(image_bytes)
def _scanner_artifact_signal(
artifact_analysis: QRArtifactAnalysis,
*,
force_block: bool = False,
) -> ScannerDecisionSignal:
if force_block:
return ScannerDecisionSignal(
layer="artifact_integrity",
state="block",
message=(
"The decoded image artifact and submitted scanner payload do not match."
),
)
if artifact_analysis.artifact_integrity == "pass":
return ScannerDecisionSignal(
layer="artifact_integrity",
state="pass",
message="QR artifact inspection found no structural warning.",
)
indicators = ", ".join(artifact_analysis.tamper_indicators) or "artifact warning"
return ScannerDecisionSignal(
layer="artifact_integrity",
state="warn",
message=f"QR artifact inspection reported: {indicators}.",
)
def _with_artifact_signal(
signals: list[ScannerDecisionSignal],
artifact_analysis: QRArtifactAnalysis | None,
) -> list[ScannerDecisionSignal]:
if artifact_analysis is None:
return signals
scanner_index = next(
(index for index, signal in enumerate(signals) if signal.layer == "scanner_decision"),
len(signals),
)
return [
*signals[:scanner_index],
_scanner_artifact_signal(artifact_analysis),
*signals[scanner_index:],
]
def _artifact_payload_mismatch_decision(
request_payload: str,
artifact_analysis: QRArtifactAnalysis,
*,
request_id: str | None,
) -> ScannerDecisionResponse:
destination, usage_policy = _scanner_claimed_destination_from_payload(
artifact_analysis.payload,
)
return ScannerDecisionResponse(
decision_state="blocked",
open_allowed=False,
usage_policy=usage_policy,
primary_message=(
"The submitted scanner payload does not match the QR image artifact. "
"Do not open this destination."
),
issuer=ScannerDecisionIssuer(status="not_evaluated"),
destination=_scanner_destination(
destination or request_payload or "unreadable QR payload",
binding="not_evaluated",
),
signals=[
ScannerDecisionSignal(
layer="issuer_legitimacy",
state="not_evaluated",
message="Issuer trust was not evaluated because artifact integrity failed.",
),
ScannerDecisionSignal(
layer="destination_binding",
state="not_evaluated",
message="Destination binding was not evaluated because artifact integrity failed.",
),
ScannerDecisionSignal(
layer="runtime_safety",
state="not_evaluated",
message="Runtime safety was not evaluated because artifact integrity failed.",
),
_scanner_artifact_signal(artifact_analysis, force_block=True),
ScannerDecisionSignal(layer="scanner_decision", state="blocked"),
],
actions=_scanner_actions(decision_state="blocked", open_allowed=False),
verifier_stage="artifact_integrity",
verifier_reason="QR image artifact payload does not match submitted scanner payload",
request_id=request_id,
)
def _scanner_signals_for_result(
result: NarrowedVerifierResponse,
*,
record: ScannerTrustRecord,
redirect_verdict: RedirectPolicyVerdict | None = None,
runtime_verdict: RuntimeSafetyVerdict | None = None,
artifact_analysis: QRArtifactAnalysis | None = None,
) -> list[ScannerDecisionSignal]:
if result.allowed:
if redirect_verdict and redirect_verdict.is_redirect_flow and redirect_verdict.is_blocked:
return _with_artifact_signal([
ScannerDecisionSignal(
layer="issuer_legitimacy",
state="recognized",
message=_scanner_issuer_legitimacy_message(record),
),
ScannerDecisionSignal(
layer="destination_binding",
state="redirect_mismatch",
message=redirect_verdict.reason,
),
ScannerDecisionSignal(
layer="runtime_safety",
state="not_opened",
message="Runtime safety is not evaluated because redirect policy blocked the final destination.",
),
ScannerDecisionSignal(layer="scanner_decision", state="blocked"),
], artifact_analysis)
if runtime_verdict and not runtime_verdict.is_clean:
return _with_artifact_signal([
ScannerDecisionSignal(
layer="issuer_legitimacy",
state="recognized",
message=_scanner_issuer_legitimacy_message(record),
),
ScannerDecisionSignal(
layer="destination_binding",
state="bound",
message=_scanner_destination_binding_message(redirect_verdict),
),
ScannerDecisionSignal(
layer="runtime_safety",
state=runtime_verdict.state,
message=runtime_verdict.reason,
),
ScannerDecisionSignal(
layer="scanner_decision",
state=runtime_verdict.decision_state,
),
], artifact_analysis)
runtime_message = "Replay and validity checks passed."
if result.usage_policy == USAGE_POLICY_REUSABLE_PUBLIC:
runtime_message = (
"Reusable public QR does not consume a nonce; validity and destination checks passed."
)
elif result.usage_policy == USAGE_POLICY_TIME_LIMITED:
runtime_message = (
"Time-limited QR is inside its validity window; no per-user replay consumption."
)
return _with_artifact_signal([
ScannerDecisionSignal(
layer="issuer_legitimacy",
state="recognized",
message=_scanner_issuer_legitimacy_message(record),
),
ScannerDecisionSignal(
layer="destination_binding",
state="bound",
message=_scanner_destination_binding_message(redirect_verdict),
),
ScannerDecisionSignal(layer="runtime_safety", state="clean", message=runtime_message),
ScannerDecisionSignal(layer="scanner_decision", state="verified_issuer"),
], artifact_analysis)
if result.stage == "payload_revalidation":
return _with_artifact_signal([
ScannerDecisionSignal(
layer="issuer_legitimacy",
state="recognized",
message=_scanner_issuer_legitimacy_message(record),
),
ScannerDecisionSignal(layer="destination_binding", state="mismatch", message=result.reason),
ScannerDecisionSignal(layer="runtime_safety", state="not_opened", message="The destination is blocked before opening."),
ScannerDecisionSignal(layer="scanner_decision", state="blocked"),
], artifact_analysis)
if result.stage == "replay_guard":
return _with_artifact_signal([
ScannerDecisionSignal(
layer="issuer_legitimacy",
state="recognized",
message=_scanner_issuer_legitimacy_message(record),
),
ScannerDecisionSignal(layer="destination_binding", state="not_evaluated", message="One-time use check stopped the decision path."),
ScannerDecisionSignal(layer="runtime_safety", state="replay_blocked", message=result.reason),
ScannerDecisionSignal(layer="scanner_decision", state="blocked"),
], artifact_analysis)
if result.stage == "certificate_status":
return _with_artifact_signal([
ScannerDecisionSignal(layer="issuer_legitimacy", state="revoked", message=result.reason),
ScannerDecisionSignal(layer="destination_binding", state="not_evaluated"),
ScannerDecisionSignal(layer="runtime_safety", state="not_evaluated"),
ScannerDecisionSignal(layer="scanner_decision", state="blocked"),
], artifact_analysis)
return _with_artifact_signal([
ScannerDecisionSignal(
layer="issuer_legitimacy",
state="failed" if result.stage == "signed_schema" else "recognized",
message=(
result.reason
if result.stage == "signed_schema"
else _scanner_issuer_legitimacy_message(record)
),
),
ScannerDecisionSignal(layer="destination_binding", state="not_evaluated"),
ScannerDecisionSignal(layer="runtime_safety", state=result.stage, message=result.reason),
ScannerDecisionSignal(layer="scanner_decision", state="blocked"),
], artifact_analysis)
# The scanner pipeline is "bounded-online": it degrades boundedly when the
# runtime-safety provider is unavailable, but blocks expired verdicts outright
# where the bounded reference profile only cautions. It therefore matches no
# single corpus profile; ฮ evaluates it under bounded semantics, which the
# pipeline may exceed (block more) but never undercut.
_RUNTIME_DECISION_PROFILE = "bounded-online"
_RUNTIME_SAFETY_RESIDUAL_TIERS = {
"clean": "pass",
"risky": "warn",
"blocked": "block",
# An expired verdict is stale runtime-safety evidence owned by R_S (D14).
"expired": "stale",
"stale": "stale",
"unavailable": "unavailable",
}
# Failing verifier stages, keyed to the residual family that owns the evidence.
_FAILED_STAGE_RESIDUALS = {
"signed_schema": ("issuer_chain", "invalid-managed-claim"),
"certificate_status": ("issuer_chain", "revoked-issuer"),
"payload_revalidation": ("destination_policy", "fail"),
"time_window": ("freshness", "block"),
"replay_guard": ("freshness", "block"),
}
def _residual_vector_for_result(
result: NarrowedVerifierResponse,
*,
redirect_verdict: RedirectPolicyVerdict | None,
runtime_verdict: RuntimeSafetyVerdict | None,
artifact_analysis: QRArtifactAnalysis | None,
) -> dict[str, str]:
residuals = {
"issuer_chain": "pass",
"destination_policy": "pass" if result.allowed else "not-applicable",
"redirect_flow": "not-applicable",
"runtime_safety": "not-checked",
"freshness": "pass" if result.allowed else "not-applicable",
# A payload-only scan presents no artifact container, so there is no
# artifact-layer evidence to hold against it.
"artifact_integrity": "pass",
}
if not result.allowed and result.stage in _FAILED_STAGE_RESIDUALS:
family, tier = _FAILED_STAGE_RESIDUALS[result.stage]
residuals[family] = tier
if redirect_verdict is not None and redirect_verdict.is_redirect_flow:
residuals["redirect_flow"] = "fail" if redirect_verdict.is_blocked else "pass"
if runtime_verdict is not None:
residuals["runtime_safety"] = _RUNTIME_SAFETY_RESIDUAL_TIERS.get(
runtime_verdict.state,
runtime_verdict.state,
)
if artifact_analysis is not None:
residuals["artifact_integrity"] = artifact_analysis.artifact_integrity
return residuals
def _apply_trust_residual_gate(
decision_state: str,
residual_vector: dict[str, str],
) -> tuple[str, Decision]:
"""D15 totality on the live path: the positive terminal requires ฮ agreement.
Any residual tier outside the positive-eligible sets โ including verdict
states or verifier stages added later that the mapping above passes through
unmodeled โ fails closed to a caution instead of implicit trust. The gate is
one-way: it never upgrades a state the pipeline already decided to withhold.
"""
model_decision = decide_trust_residuals(
residual_vector,
profile=_RUNTIME_DECISION_PROFILE,
qr_decodable=True,
)
if decision_state == "verified_issuer" and model_decision.primary_state != "verified-issuer":
return "unverified", model_decision
return decision_state, model_decision
def _scanner_decision_from_result(
envelope: SignedQRCodeEnvelope,
result: NarrowedVerifierResponse,
record: ScannerTrustRecord,
*,
request_id: str | None,
artifact_analysis: QRArtifactAnalysis | None = None,
) -> ScannerDecisionResponse:
redirect_verdict = evaluate_redirect_policy(envelope.claims.payload) if result.allowed else None
effective_destination = (
redirect_verdict.effective_url
if redirect_verdict is not None
else envelope.claims.payload
)
runtime_verdict = (
evaluate_runtime_safety(effective_destination)
if result.allowed and not (redirect_verdict and redirect_verdict.is_blocked)
else None
)
decision_state = "verified_issuer" if result.allowed else "blocked"
open_allowed = result.allowed
verifier_stage = result.stage
verifier_reason = result.reason
destination_binding = _scanner_binding_for_stage(result.stage, result.allowed)
if redirect_verdict and redirect_verdict.is_redirect_flow:
if redirect_verdict.is_blocked:
decision_state = "blocked"
open_allowed = False
verifier_stage = "redirect_policy"
verifier_reason = redirect_verdict.reason
destination_binding = "redirect_mismatch"
else:
destination_binding = "bound"
if runtime_verdict is not None:
decision_state = runtime_verdict.decision_state
open_allowed = runtime_verdict.open_allowed
if not runtime_verdict.is_clean:
verifier_stage = "runtime_safety"
verifier_reason = runtime_verdict.reason
primary_message = _scanner_primary_message(
result,
redirect_verdict=redirect_verdict,
runtime_verdict=runtime_verdict,
artifact_analysis=artifact_analysis,
)
residual_vector = _residual_vector_for_result(
result,
redirect_verdict=redirect_verdict,
runtime_verdict=runtime_verdict,
artifact_analysis=artifact_analysis,
)
gated_state, model_decision = _apply_trust_residual_gate(decision_state, residual_vector)
if gated_state != decision_state:
decision_state = gated_state
verifier_stage = "trust_residuals"
verifier_reason = "Residual evidence outside positive-eligible tiers: " + ", ".join(
model_decision.reason_codes,
)
primary_message = (
"Verification evidence is incomplete for this QR code. "
"Proceed only with caution."
)
return ScannerDecisionResponse(
decision_state=decision_state,
open_allowed=open_allowed,
usage_policy=result.usage_policy,
primary_message=primary_message,
issuer=ScannerDecisionIssuer(
name=record.certificate.issuer_name,
tier=record.governance.assurance_tier if record.governance else "demo",
status="recognized" if result.stage != "certificate_status" else "revoked",
),
destination=_scanner_destination(
effective_destination,
binding=destination_binding,
resolver_url=redirect_verdict.resolver_url if redirect_verdict else None,
final_url=redirect_verdict.final_url if redirect_verdict else None,
redirect_hops=redirect_verdict.hop_count if redirect_verdict else None,
redirect_policy=redirect_verdict.policy_label if redirect_verdict else None,
),
governance=_scanner_governance_response(record.governance),
signals=_scanner_signals_for_result(
result,
record=record,
redirect_verdict=redirect_verdict,
runtime_verdict=runtime_verdict,
artifact_analysis=artifact_analysis,
),
actions=_scanner_actions(decision_state=decision_state, open_allowed=open_allowed),
verifier_stage=verifier_stage,
verifier_reason=verifier_reason,
request_id=request_id,
)
async def _run_scanner_decision(
request: ScannerDecisionRequest,
*,
request_id: str | None,
) -> ScannerDecisionResponse:
verifier_profile_decision = _verifier_profile_state_decision(
request,
request_id=request_id,
)
if verifier_profile_decision is not None:
return verifier_profile_decision
qr_payload = request.qr_payload.strip()
try:
artifact_analysis = _scanner_artifact_analysis_for_request(request)
except QRArtifactError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
if artifact_analysis is not None and artifact_analysis.payload.strip() != qr_payload:
return _artifact_payload_mismatch_decision(
qr_payload,
artifact_analysis,
request_id=request_id,
)
try:
envelope = decode_envelope_from_qr_payload(qr_payload)
except QRArtifactError as exc:
return _unverified_scanner_decision(
qr_payload,
reason=str(exc),
request_id=request_id,
)
record = _scanner_trust_records.get(envelope.claims.certificate_ref)
if record is None:
return _signed_unknown_issuer_decision(envelope, request_id=request_id)
governance_cache_decision = _governance_cache_blocking_decision(
envelope,
record,
request_id=request_id,
)
if governance_cache_decision is not None:
return governance_cache_decision
result = await _run_scanned_verifier(
ScannedVerifierRequest(
qr_payload=qr_payload,
certificate=record.certificate,
issuer_state=record.issuer_state,
)
)
return _scanner_decision_from_result(
envelope,
result,
record,
request_id=request_id,
artifact_analysis=artifact_analysis,
)
def _render_demo_session_display(session: DemoSessionResponse) -> str:
qr_image_src = f"data:image/png;base64,{session.qr_png_base64}"
usage_policy = escape(session.verify_request.envelope.claims.usage_policy)
nonce = escape(session.verify_request.envelope.claims.nonce)
payload = escape(session.verify_request.envelope.claims.payload)
stage_hint = "payload_revalidation" if "rogue.example" in payload else "accepted"
return f"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Verifier Demo Session</title>
<style>
:root {{
color-scheme: light;
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}}
body {{
margin: 0;
min-height: 100vh;
background: #f8f5ed;
color: #171717;
display: grid;
place-items: center;
}}
.shell {{
width: min(92vw, 880px);
display: grid;
gap: 24px;
padding: 24px;
}}
.frame {{
display: grid;
gap: 16px;
justify-items: center;
background: #fff;
border: 1px solid #e7e2d8;
border-radius: 28px;
padding: 32px;
box-shadow: 0 24px 80px rgba(18, 25, 20, 0.08);
}}
img {{
width: min(72vw, 520px);
height: auto;
image-rendering: pixelated;
}}
.meta {{
width: min(72vw, 520px);
display: grid;
gap: 10px;
}}
.label {{
font-size: 11px;
letter-spacing: 0.14em;
text-transform: uppercase;
color: #5d665d;
}}
.value {{
font-size: 16px;
word-break: break-word;
}}
.hint {{
color: #5d665d;
font-size: 14px;
line-height: 1.6;
}}
</style>
</head>
<body>
<main class="shell">
<section class="frame">
<img src="{qr_image_src}" alt="Verifier demo QR" />
<div class="meta">
<div>
<div class="label">Session</div>
<div class="value">{escape(session.session_id)}</div>
</div>
<div>
<div class="label">Usage policy</div>
<div class="value">{usage_policy}</div>
</div>
<div>
<div class="label">Nonce</div>
<div class="value">{nonce}</div>
</div>
<div>
<div class="label">Payload</div>
<div class="value">{payload}</div>
</div>
<div class="hint">
This QR belongs to the active verifier demo session. Scan it from the native iPhone verifier app that generated this session.
Expected first-pass stage: <strong>{stage_hint}</strong> only if the current scenario is a mismatch or block case.
</div>
</div>
</section>
</main>
</body>
</html>"""
async def _run_narrowed_verifier(
request: NarrowedVerifierRequest,
) -> NarrowedVerifierResponse:
try:
claims = parse_claims_mapping(request.envelope.claims.model_dump())
except SignedSchemaError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
envelope = SignedQRCodeEnvelope(
claims=claims,
signature=request.envelope.signature,
code_algorithm_id=request.envelope.code_algorithm_id,
)
certificate = CertificateAuthorityRecord(
certificate_ref=request.certificate.certificate_ref,
issuer_name=request.certificate.issuer_name,
algorithm_id=request.certificate.algorithm_id,
public_key_pem=request.certificate.public_key_pem,
)
issuer_state = IssuerVerificationState(
verified_domains=request.issuer_state.verified_domains,
allow_subdomains=request.issuer_state.allow_subdomains,
certificate_active=request.issuer_state.certificate_active,
certificate_revoked=request.issuer_state.certificate_revoked,
certificate_revocation_reason=request.issuer_state.certificate_revocation_reason,
)
result = await _verifier.verify_presented_code(
envelope,
certificate,
issuer_state,
reservation_ttl_seconds=request.reservation_ttl_seconds,
consumed_ttl_seconds=request.consumed_ttl_seconds,
)
return NarrowedVerifierResponse(
allowed=result.allowed,
stage=result.stage,
reason=result.reason,
usage_policy=result.usage_policy,
canonical_claims_sha256=result.canonical_claims_sha256,
matched_rule=result.matched_rule,
reservation_state=result.reservation_state,
)
async def _run_scanned_verifier(
request: ScannedVerifierRequest,
) -> NarrowedVerifierResponse:
try:
envelope = decode_envelope_from_qr_payload(request.qr_payload)
except QRArtifactError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
translated_request = NarrowedVerifierRequest(
envelope=SignedEnvelopeInput(
claims=SignedClaimsInput(**envelope.claims.__dict__),
signature=envelope.signature,
code_algorithm_id=envelope.code_algorithm_id,
),
certificate=request.certificate,
issuer_state=request.issuer_state,
reservation_ttl_seconds=request.reservation_ttl_seconds,
consumed_ttl_seconds=request.consumed_ttl_seconds,
)
return await _run_narrowed_verifier(translated_request)
@router.post("/demo-materials", response_model=DemoMaterialsResponse)
async def get_verifier_demo_materials(
request_context: Request,
request: DemoMaterialsRequest,
) -> DemoMaterialsResponse:
"""
Generate a self-contained certificate, keypair, and verification request
for the narrowed verifier reference endpoint.
"""
await _enforce_verifier_api_key(request_context)
await _enforce_verifier_rate_limit(request_context, bucket="demo_materials")
try:
return _build_demo_materials_response(request)
except SignedSchemaError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@router.post("/demo-sessions", response_model=DemoSessionResponse)
async def create_verifier_demo_session(
request_context: Request,
request: DemoMaterialsRequest,
) -> DemoSessionResponse:
await _enforce_verifier_api_key(request_context)
await _enforce_verifier_rate_limit(request_context, bucket="demo_materials")
try:
demo_materials = _build_demo_materials_response(request)
except SignedSchemaError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return _build_demo_session_response(demo_materials)
@router.get("/status", response_model=VerifierStatusResponse)
async def get_verifier_status(request_context: Request) -> VerifierStatusResponse:
await _enforce_verifier_rate_limit(request_context, bucket="status")
return await _build_verifier_status_response(
include_operator_evidence=await _request_can_read_operator_status(
request_context,
),
)
@router.get("/lab", include_in_schema=False)
async def get_verifier_lab() -> FileResponse:
"""
Serve the browser-based verifier lab used for local PoC testing.
"""
return FileResponse(_LAB_HTML_PATH, headers={"Cache-Control": "no-store"})
@router.get("/qr-display", include_in_schema=False)
async def get_verifier_qr_display() -> FileResponse:
"""
Serve the second-screen QR display used for cross-device camera testing.
"""
return FileResponse(_QR_DISPLAY_HTML_PATH, headers={"Cache-Control": "no-store"})
@router.get("/demo-sessions/{session_id}/display", include_in_schema=False)
async def get_verifier_demo_session_display(session_id: str) -> HTMLResponse:
session_record = _demo_session_store.get(session_id)
if session_record is None:
raise HTTPException(status_code=404, detail="Verifier demo session not found")
payload = DemoSessionResponse(
session_id=session_record.session_id,
display_path=f"/verifier/demo-sessions/{session_record.session_id}/display",
**session_record.demo_materials.model_dump(),
)
return HTMLResponse(
_render_demo_session_display(payload),
headers={"Cache-Control": "no-store"},
)
@router.post("/verify", response_model=NarrowedVerifierResponse)
async def verify_presented_code(
request_context: Request,
request: NarrowedVerifierRequest,
) -> NarrowedVerifierResponse:
"""
Run the narrowed verifier reference pipeline against a presented code.
"""
await _enforce_verifier_api_key(request_context)
await _enforce_verifier_rate_limit(request_context, bucket="verify")
return await _run_narrowed_verifier(request)
@router.post("/verify-scanned", response_model=NarrowedVerifierResponse)
async def verify_scanned_code(
request_context: Request,
request: ScannedVerifierRequest,
) -> NarrowedVerifierResponse:
"""
Run the narrowed verifier pipeline against a scanned QR payload string.
"""
await _enforce_verifier_api_key(request_context)
await _enforce_verifier_rate_limit(request_context, bucket="verify_scanned")
return await _run_scanned_verifier(request)
@scanner_router.get("/provider-profile", response_model=VerifierProviderProfileResponse)
async def get_scanner_provider_profile(
request_context: Request,
) -> VerifierProviderProfileResponse:
"""
Return the current scanner-side provider profile.
Production scanners should refresh this profile from app state so provider
staleness or revocation can change without rebuilding or reinstalling.
"""
endpoint = _request_public_base_url(request_context)
return VerifierProviderProfileResponse(
id="local-qrtrust-demo-provider",
name="QR Trust local provider",
summary=(
"A managed verifier profile served by the local QR Trust provider "
"for scanner-side issuer, destination, and runtime decisions."
),
trust_program="Demo issuer trust program",
policy=(
"Issuer legitimacy, destination binding, runtime safety, "
"and scanner decision state"
),
endpoints=[endpoint],
profile_state=_configured_verifier_profile_state(),
signature_status="Local reviewer profile; signature envelope not production-verified",
)
@scanner_router.post("/decisions", response_model=ScannerDecisionResponse)
async def decide_scanned_qr(
request_context: Request,
request: ScannerDecisionRequest,
) -> ScannerDecisionResponse:
"""
End-user scanner decision endpoint.
Unlike /verifier/verify-scanned, the client sends only the scanned QR
payload. The verifier resolves issuer state from its local trust cache and
returns a user-facing decision state.
"""
await _enforce_verifier_rate_limit(request_context, bucket="scanner_decisions")
response = await _run_scanner_decision(
request,
request_id=_request_id_for_context(request_context),
)
decorated_response = _with_scanner_ux(response, request=request)
recording_result = await record_scanner_evidence(decorated_response)
if recording_result is not None and recording_result.error:
logger.warning(
"scanner_evidence_recording_failed request_id=%s error=%s",
decorated_response.request_id,
recording_result.error,
)
return decorated_response
@scanner_router.post("/ux-events", response_model=ScannerUXEventLogResponse)
async def record_scanner_ux_event(
request_context: Request,
request: ScannerUXEventLogRequest,
) -> ScannerUXEventLogResponse:
"""
Record scanner preview, hold, open, and cancel events for PoC evaluation.
The first implementation is intentionally log-backed with an in-process
export buffer so the interaction contract can stabilize before adding
durable experiment storage.
"""
await _enforce_verifier_rate_limit(request_context, bucket="scanner_ux_events")
client_host = request_context.client.host if request_context.client else "unknown"
entry = ScannerUXEventLogEntry(
id=f"uxevt_{uuid4().hex}",
recorded_at=datetime.now(timezone.utc).isoformat(),
client_host=client_host,
event=request,
)
_scanner_ux_event_log.append(entry)
logger.info(
"scanner_ux_event",
extra={
"scanner_ux_event": entry.model_dump(mode="json"),
"client_host": client_host,
},
)
return ScannerUXEventLogResponse(recorded=True, event_type=request.event_type)
@scanner_router.get("/ux-ab-fixture", response_model=ScannerUXExperimentFixtureResponse)
async def get_scanner_ux_ab_fixture(
request_context: Request,
seed: str = "reviewer-demo",
) -> ScannerUXExperimentFixtureResponse:
"""
Return deterministic control/treatment scanner UX fixture logs.
This is a reviewer-facing scaffold for the hold-to-open experiment. It
keeps the user-study shape concrete without pretending local PoC fixtures
are production analytics storage.
"""
await _enforce_verifier_rate_limit(request_context, bucket="scanner_ux_events")
bounded_seed = seed.strip()[:128] or "reviewer-demo"
return build_scanner_ux_ab_fixture(bounded_seed)
@scanner_router.get("/ux-events", response_model=ScannerUXEventLogListResponse)
async def list_scanner_ux_events(
request_context: Request,
limit: int = 50,
request_id: str | None = None,
decision_id: str | None = None,
) -> ScannerUXEventLogListResponse:
"""Return recent scanner UX events for local demos and review packets."""
await _enforce_verifier_rate_limit(request_context, bucket="scanner_ux_events")
bounded_limit = max(1, min(limit, 200))
events = list(_scanner_ux_event_log)
if request_id:
events = [event for event in events if event.event.request_id == request_id]
if decision_id:
events = [event for event in events if event.event.decision_id == decision_id]
return ScannerUXEventLogListResponse(events=events[-bounded_limit:])
@router.post("/decode-image", response_model=QRCodeImageDecodeResponse)
async def decode_qr_image(
request_context: Request,
request: QRCodeImageDecodeRequest,
) -> QRCodeImageDecodeResponse:
"""
Decode a QR payload string from base64 image content.
"""
await _enforce_verifier_api_key(request_context)
await _enforce_verifier_rate_limit(request_context, bucket="decode_image")
try:
image_bytes = decode_image_base64(request.image_base64)
qr_payload = decode_qr_payload_from_png_bytes(image_bytes)
except QRArtifactError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return QRCodeImageDecodeResponse(qr_payload=qr_payload)
@router.get("/admin/api-keys", response_model=VerifierAPIKeyListResponse)
async def list_verifier_api_keys(request_context: Request) -> VerifierAPIKeyListResponse:
_raise_legacy_verifier_admin_api_key_route()
@router.post("/admin/api-keys/issue", response_model=VerifierAPIKeyIssueResponse)
async def issue_verifier_api_key(
request_context: Request,
request: VerifierAPIKeyIssueRequest,
) -> VerifierAPIKeyIssueResponse:
_raise_legacy_verifier_admin_api_key_route()
@router.post("/admin/api-keys/{key_id}/rotate", response_model=VerifierAPIKeyIssueResponse)
async def rotate_verifier_api_key(
key_id: str,
request_context: Request,
request: VerifierAPIKeyRotateRequest,
) -> VerifierAPIKeyIssueResponse:
_raise_legacy_verifier_admin_api_key_route()
@router.delete("/admin/api-keys/{key_id}", response_model=VerifierAPIKeyRevokeResponse)
async def revoke_verifier_api_key(
key_id: str,
request_context: Request,
) -> VerifierAPIKeyRevokeResponse:
_raise_legacy_verifier_admin_api_key_route()
|