betterwithage commited on
Commit
cec7723
·
verified ·
1 Parent(s): 878d87f

chore(sync): mirror backend .py + Dockerfile to Space (hf-sync-backend)

Browse files

Automated backend sync from szl-holdings/a11oy main via hf-sync-backend.
Updated (differed from the Space): Dockerfile, serve.py, szl3d_holographic.py, szl_attested_inference.py
Deleted (gone from the repo + Dockerfile COPY set): (none)

Keeps the Space-built backend (serve.py + the Dockerfile-COPY'd .py
modules) identical to GitHub main so the Space never rebuilds from a
stale backend, new endpoints don't 404 there, and orphaned modules
removed from the repo don't linger in the Space tree.

Files changed (4) hide show
  1. Dockerfile +8 -0
  2. serve.py +17 -0
  3. szl3d_holographic.py +1 -0
  4. szl_attested_inference.py +603 -0
Dockerfile CHANGED
@@ -655,6 +655,14 @@ COPY knowledge.json szl_parity_gaps.py compliance_crosswalk.py szl_compliance_me
655
  # MUST be per-file COPY'd or /api/a11oy/v1/tee/status + tee_attestation receipt field
656
  # fall back to honest UNAVAILABLE stubs. Pattern: dstack-capsule Apache-2.0 arXiv 2606.03323.
657
  COPY szl_tee_attest.py ./
 
 
 
 
 
 
 
 
658
  # DEV2 Build 2: EU AI Act Art.53 signed energy disclosure (2026-06-30) — imported by
659
  # serve.py (guarded); MUST be per-file COPY'd or /api/a11oy/v1/energy/eu-disclosure +
660
  # energy_eu_disclosure receipt field fall back to honest UNAVAILABLE stubs.
 
655
  # MUST be per-file COPY'd or /api/a11oy/v1/tee/status + tee_attestation receipt field
656
  # fall back to honest UNAVAILABLE stubs. Pattern: dstack-capsule Apache-2.0 arXiv 2606.03323.
657
  COPY szl_tee_attest.py ./
658
+ # WAVE-H TEAM 3: attested-inference deepening (2026-07-07) — imported by serve.py (guarded);
659
+ # MUST be per-file COPY'd (this Dockerfile uses no `COPY . .`) or GET /api/a11oy/v1/attest/infer
660
+ # falls through to the SPA (404). Binds a MODELED device-attestation quote to a Λ-gated inference
661
+ # RECEIPT + SLSA provenance; DSSE real ECDSA-P256 in-Space / UNSIGNED-LOCAL locally. Reuses the
662
+ # already-COPY'd szl_tee_attest + szl_dsse + szl_org_lambda. Leaders (clean-room PATTERN): NVIDIA
663
+ # H100/H200 CC+NRAS, AMD SEV-SNP, Intel TDX, in-toto/SLSA, Sigstore/Rekor, Confidential Containers.
664
+ # The attestinfer.js surface ships via the existing `COPY static/3d/ ./static/3d/`. Λ = Conjecture 1.
665
+ COPY szl_attested_inference.py ./
666
  # DEV2 Build 2: EU AI Act Art.53 signed energy disclosure (2026-06-30) — imported by
667
  # serve.py (guarded); MUST be per-file COPY'd or /api/a11oy/v1/energy/eu-disclosure +
668
  # energy_eu_disclosure receipt field fall back to honest UNAVAILABLE stubs.
serve.py CHANGED
@@ -688,6 +688,23 @@ try:
688
  except Exception as _szl_attest_e: # pragma: no cover
689
  print(f"[a11oy] Attestation surface NOT registered: {_szl_attest_e!r}; SPA + API unaffected", file=__import__("sys").stderr)
690
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
691
  # Orbital PAGE (frontend demo surface) — GET /orbital renders the MODELED constellation
692
  # (topology + projection + governed-receipt overlay) against the two MODELED endpoints
693
  # above. The whole surface is banner-labeled "MODELED — Orbital Roadmap (no on-orbit
 
688
  except Exception as _szl_attest_e: # pragma: no cover
689
  print(f"[a11oy] Attestation surface NOT registered: {_szl_attest_e!r}; SPA + API unaffected", file=__import__("sys").stderr)
690
 
691
+ # ── WAVE-H TEAM 3: ATTESTED INFERENCE (deepening of Wave-A cc-attest). Endpoint
692
+ # GET /api/a11oy/v1/attest/infer?seed&model → deterministic MODELED flow: device attestation
693
+ # (reuses szl_tee_attest measured-boot chain) → Λ-gate (weighted geomean, Conjecture 1) →
694
+ # gated inference → a signed receipt embedding the attestation quote digest + Λ axes + SLSA-style
695
+ # provenance, verifiable-by-design. DSSE via szl_dsse: REAL ECDSA-P256 in-Space, honest
696
+ # UNSIGNED-LOCAL locally. Label MODELED (no real TEE/GPU/NRAS/network). Leaders cited in the module:
697
+ # NVIDIA H100/H200 CC+NRAS, AMD SEV-SNP, Intel TDX, in-toto/SLSA, Sigstore/Rekor, Confidential
698
+ # Containers. Registered AFTER szl_attest_stack so our STATIC /attest/infer route front-inserts
699
+ # ahead of the parametrized /attest/{receipt_hash} route (register() also scans+inserts directly
700
+ # before it as a belt-and-suspenders). Additive, try/except-guarded. Nothing to locked-8.
701
+ try:
702
+ import szl_attested_inference as _szl_attested_inference
703
+ _szl_ai_paths = _szl_attested_inference.register(app, ns="a11oy")
704
+ print(f"[a11oy] attested-inference registered: {_szl_ai_paths}", file=__import__("sys").stderr)
705
+ except Exception as _szl_ai_e: # pragma: no cover
706
+ print(f"[a11oy] attested-inference NOT registered: {_szl_ai_e!r}", file=__import__("sys").stderr)
707
+
708
  # Orbital PAGE (frontend demo surface) — GET /orbital renders the MODELED constellation
709
  # (topology + projection + governed-receipt overlay) against the two MODELED endpoints
710
  # above. The whole surface is banner-labeled "MODELED — Orbital Roadmap (no on-orbit
szl3d_holographic.py CHANGED
@@ -47,6 +47,7 @@ SURFACES: List[Dict[str, str]] = [
47
  {"id": "moe", "title": "MoE Router", "owner": "Dev0"},
48
  {"id": "formalmath", "title": "Formal-Math Retrieval", "owner": "Dev0"},
49
  {"id": "ccattest", "title": "Confidential-Compute Attest", "owner": "Dev0"},
 
50
  {"id": "ringattn", "title": "Ring Attention", "owner": "Dev0"},
51
  {"id": "grpo", "title": "GRPO Reward Dynamics", "owner": "Dev0"},
52
  {"id": "kvcache", "title": "KV-Cache H2O", "owner": "Dev0"},
 
47
  {"id": "moe", "title": "MoE Router", "owner": "Dev0"},
48
  {"id": "formalmath", "title": "Formal-Math Retrieval", "owner": "Dev0"},
49
  {"id": "ccattest", "title": "Confidential-Compute Attest", "owner": "Dev0"},
50
+ {"id": "attestinfer", "title": "Attested Inference", "owner": "WaveH-Team3"},
51
  {"id": "ringattn", "title": "Ring Attention", "owner": "Dev0"},
52
  {"id": "grpo", "title": "GRPO Reward Dynamics", "owner": "Dev0"},
53
  {"id": "kvcache", "title": "KV-Cache H2O", "owner": "Dev0"},
szl_attested_inference.py ADDED
@@ -0,0 +1,603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # © 2026 Lutar, Stephen P. — SZL Holdings · ORCID 0009-0001-0110-4173 · Doctrine v11
3
+ # Authored by Wave-H Team 3 (attested-inference deepening).
4
+ """
5
+ szl_attested_inference.py — ATTESTED INFERENCE (Wave-H Team 3 deepening of Wave-A cc-attest)
6
+
7
+ WHAT THIS IS
8
+ ------------
9
+ A full, end-to-end **attested-inference** flow that binds a device-attestation quote
10
+ to a governed inference RECEIPT, verifiable-by-design. It DEEPENS the Wave-A cc-attest
11
+ measurement-chain simulation (killinchu `cc-attest/verify`) into the complete leader
12
+ pattern: device attestation → Λ-gated inference → a signed receipt that embeds the
13
+ attestation quote digest + the Λ trust axes + SLSA-style provenance.
14
+
15
+ GET /api/a11oy/v1/attest/infer?seed=<int>&model=<id>
16
+
17
+ device attestation (reuse/extend a cc-attest-style measured-boot chain)
18
+ └─► Λ-gate (weighted geometric mean over the 13 trust axes; Conjecture 1)
19
+ └─► gated inference (deterministic MODELED token stream)
20
+ └─► receipt (attestation quote digest + Λ axes + SLSA provenance)
21
+ └─► DSSE envelope (real ECDSA-P256 in-Space; UNSIGNED-LOCAL locally)
22
+
23
+ HONESTY (Doctrine v11 — NEVER violate)
24
+ --------------------------------------
25
+ Label = **MODELED**. This SIMULATES the attested path deterministically from (seed, model):
26
+ there is **no real TEE, no real GPU, no NRAS/KDS network call, no real inference engine**.
27
+ Every synthetic value is derived by SHA-256/384 from the inputs so the flow is replayable and
28
+ verifiable, NOT fabricated as a live measurement. Where a REAL measurement is available the
29
+ module defers to `szl_tee_attest.get_tee_attestation()` and surfaces its honest label verbatim
30
+ (MEASURED on a live TDX/Nitro pod, UNAVAILABLE on the CPU Space) inside `tee_attestation`.
31
+ The DSSE envelope is REAL ECDSA-P256 when the cosign secret is present in-Space, and honestly
32
+ `signed:false` (UNSIGNED-LOCAL) otherwise — the signature is never fabricated.
33
+
34
+ Λ = **Conjecture 1** (advisory, gray, NEVER "green"/theorem). Nothing here touches the locked-8.
35
+
36
+ CONFIDENTIAL-COMPUTE LEADERS STUDIED & CITED (clean-room PATTERN, not their code)
37
+ --------------------------------------------------------------------------------
38
+ • NVIDIA H100/H200 Confidential Computing + NRAS remote attestation — the relying party
39
+ checks a signed attestation report (CC-mode ON, genuine unmodified GPU/firmware) against
40
+ NVIDIA's Remote Attestation Service before trusting the GPU with secrets. This is the
41
+ hardware root for attested inference.
42
+ https://developer.nvidia.com/blog/confidential-computing-on-h100-gpus-for-secure-and-trustworthy-ai/
43
+ • AMD SEV-SNP — guest places a digest in REPORT_DATA, retrieves an attestation report via
44
+ /dev/sev-guest SNP_GET_REPORT; a relying party verifies against the VCEK cert chain from
45
+ the AMD Key Distribution Service (KDS). REPORT_DATA binds an app value (e.g. our nonce/
46
+ prompt digest) into the quote — the pattern we mirror to bind the inference to the quote.
47
+ https://www.amd.com/content/dam/amd/en/documents/developer/lss-snp-attestation.pdf
48
+ • Intel TDX — a TD produces a TDREPORT (MRTD + RTMRs) converted to a signed TD Quote; the
49
+ verifier checks it (DCAP / Intel Trust Authority). We mirror MRTD as the boot measurement.
50
+ https://download.01.org/intel-sgx/latest/dcap-latest/linux/docs/Intel_TDX_DCAP_Quoting_Library_API.pdf
51
+ • in-toto / SLSA — signed attestations of "who built/ran what, when," graded L1→L3. Our
52
+ receipt carries an SLSA-style provenance predicate (builder, buildType, invocation, digests).
53
+ https://slsa.dev/spec/v1.0/levels · https://slsa.dev/blog/2023/05/in-toto-and-slsa
54
+ • Sigstore / Rekor — a transparency log for signatures; `cosign`/`slsa-verifier` verify
55
+ receipts with off-the-shelf tooling. Our DSSE envelope is cosign-verifiable (szl_dsse).
56
+ https://docs.sigstore.dev/ · https://docs.sigstore.dev/logging/overview/
57
+ • Confidential Containers (CoCo, CNCF) — Kata + attestation-agent + Key Broker Service (KBS)
58
+ gate secret/key release on a verified attestation. Our Λ-gate is the software analogue: it
59
+ releases the (MODELED) inference only when the attested trust meets the advisory floor.
60
+ https://github.com/confidential-containers/confidential-containers
61
+ • Academic frontier — *Laminator: Verifiable ML Property Cards using Hardware-assisted
62
+ Attestations* (arXiv 2406.17548) binds model+input+output into an attested "inference card"
63
+ — exactly the artifact SZL calls a receipt. *SLSA for ML 2025: Signed Datasets,
64
+ Reproducible Training, Attested Inference* is the reference architecture we map onto.
65
+
66
+ WHAT SZL ADDS BEYOND THE LEADERS
67
+ --------------------------------
68
+ The leaders ship attestation (hardware) and provenance (supply chain) separately. SZL fuses
69
+ TEE attestation + in-toto/SLSA provenance + a Lean-checked Λ trust gate into ONE DSSE receipt —
70
+ "proof-carrying attested inference." (Λ uniqueness stays Conjecture 1; nothing to locked-8.)
71
+
72
+ ENDPOINT
73
+ --------
74
+ GET /api/a11oy/v1/attest/infer?seed=<int>&model=<model_id>
75
+ → 200 JSON {label:"MODELED", seed, model, tee_attestation, attestation_quote,
76
+ measurement_chain[], lambda{axes,value,floor,pass,uniqueness}, inference,
77
+ receipt{...}, dsse{...}, slsa_provenance{...}, honest_note, sources[]}
78
+
79
+ Also mirrors the Wave-A cc-attest shape (device_identity, measurement_chain, final_digest,
80
+ golden_match) so the attestinfer.js surface can render the same tower + the inference/receipt.
81
+ """
82
+
83
+ from __future__ import annotations
84
+
85
+ import hashlib
86
+ import hmac
87
+ import json
88
+ from datetime import datetime, timezone
89
+ from typing import Any, Dict, List
90
+
91
+ # ---------------------------------------------------------------------------
92
+ # Constants — honest labels + citations baked in (Doctrine v11)
93
+ # ---------------------------------------------------------------------------
94
+ LABEL = "MODELED"
95
+ NS_DEFAULT = "a11oy"
96
+ PAYLOAD_TYPE = "application/vnd.szl.attest-inference+json"
97
+
98
+ # advisory Λ floor (mirror szl_org_lambda.LAMBDA_FLOOR; kept local to avoid a hard import)
99
+ LAMBDA_FLOOR = 0.90
100
+
101
+ # The measured-boot stage chain we simulate — mirrors the Wave-A cc-attest ordering
102
+ # (bootloader → firmware → driver → microcode → gpu-vbios) and adds the inference-bind stage.
103
+ _BOOT_STAGES = ["bootloader", "firmware", "gpu-driver", "microcode", "gpu-vbios"]
104
+
105
+ # Canonical 13 trust axes (mirror szl_org_lambda.ORG_AXIS_NAMES / serve _A11OY_AXIS_NAMES).
106
+ _AXIS_NAMES = [
107
+ "soundness", "calibration", "robustness", "provenance", "consent", "reversibility",
108
+ "transparency", "fairness", "containment", "attestation", "freshness", "authority",
109
+ "auditability",
110
+ ]
111
+ _AXIS_WEIGHTS = [0.12, 0.06, 0.08, 0.11, 0.06, 0.07, 0.07, 0.05, 0.08, 0.10, 0.05, 0.07, 0.08]
112
+
113
+ # Confidential-compute leaders — cited in code AND in the response `sources[]`.
114
+ SOURCES: List[Dict[str, str]] = [
115
+ {"name": "NVIDIA — Confidential Computing on H100 GPUs (NRAS remote attestation)",
116
+ "url": "https://developer.nvidia.com/blog/confidential-computing-on-h100-gpus-for-secure-and-trustworthy-ai/"},
117
+ {"name": "AMD — SEV-SNP Attestation: Establishing Trust in Guests (REPORT_DATA / VCEK / KDS)",
118
+ "url": "https://www.amd.com/content/dam/amd/en/documents/developer/lss-snp-attestation.pdf"},
119
+ {"name": "Intel — TDX DCAP Quoting Library API (TDREPORT/MRTD/RTMR -> signed TD Quote)",
120
+ "url": "https://download.01.org/intel-sgx/latest/dcap-latest/linux/docs/Intel_TDX_DCAP_Quoting_Library_API.pdf"},
121
+ {"name": "SLSA — Supply-chain Levels for Software Artifacts (L1→L3)",
122
+ "url": "https://slsa.dev/spec/v1.0/levels"},
123
+ {"name": "in-toto & SLSA — signed provenance attestations",
124
+ "url": "https://slsa.dev/blog/2023/05/in-toto-and-slsa"},
125
+ {"name": "Sigstore — cosign / Rekor transparency log",
126
+ "url": "https://docs.sigstore.dev/logging/overview/"},
127
+ {"name": "Confidential Containers (CoCo, CNCF) — attestation-agent + Key Broker Service",
128
+ "url": "https://github.com/confidential-containers/confidential-containers"},
129
+ {"name": "Laminator: Verifiable ML Property Cards using Hardware-assisted Attestations (arXiv 2406.17548)",
130
+ "url": "https://arxiv.org/abs/2406.17548"},
131
+ ]
132
+
133
+ HONEST_NOTE = (
134
+ "MODELED — deterministic simulation of the attested-inference path keyed on (seed, model). "
135
+ "No real TEE, no real GPU, no NRAS/KDS network call, no real inference engine. Synthetic "
136
+ "measurements are SHA-256/384 of the inputs (replayable, NOT a live hardware quote). If a "
137
+ "real TDX/Nitro measurement is present, szl_tee_attest surfaces it verbatim in "
138
+ "tee_attestation. DSSE is REAL ECDSA-P256 in-Space (cosign-verifiable) and honestly "
139
+ "UNSIGNED-LOCAL when no signing secret is present. Λ = Conjecture 1 (advisory, never green). "
140
+ "Nothing here is in the locked-8."
141
+ )
142
+
143
+
144
+ # ---------------------------------------------------------------------------
145
+ # small deterministic helpers
146
+ # ---------------------------------------------------------------------------
147
+ def _now_iso() -> str:
148
+ return datetime.now(timezone.utc).isoformat()
149
+
150
+
151
+ def _sha256(b: bytes) -> str:
152
+ return hashlib.sha256(b).hexdigest()
153
+
154
+
155
+ def _sha384(b: bytes) -> str:
156
+ return hashlib.sha384(b).hexdigest()
157
+
158
+
159
+ def _canon(obj: Any) -> bytes:
160
+ return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
161
+
162
+
163
+ def _det_unit(*parts: str) -> float:
164
+ """Deterministic float in [0,1] from a SHA-256 of the parts (replayable, no RNG)."""
165
+ h = hashlib.sha256("|".join(parts).encode("utf-8")).digest()
166
+ v = int.from_bytes(h[:8], "big") / float(1 << 64)
167
+ return min(max(v, 0.0), 1.0)
168
+
169
+
170
+ def _clamp(x: float, lo: float = 0.0, hi: float = 1.0) -> float:
171
+ return min(max(x, lo), hi)
172
+
173
+
174
+ # ---------------------------------------------------------------------------
175
+ # Λ-gate — weighted geometric mean over the 13 trust axes (mirrors szl_org_lambda)
176
+ # ---------------------------------------------------------------------------
177
+ def _weighted_geomean(axes: List[float], weights: List[float]) -> float:
178
+ """A4 zero-absorption weighted geometric mean. Any zero axis → 0.0. Λ ∈ [0,1].
179
+ Kept local (no hard dependency) but numerically identical to szl_org_lambda.weighted_geomean."""
180
+ import math
181
+ if not axes:
182
+ return 0.0
183
+ sw = sum(weights) or 1.0
184
+ w = [x / sw for x in weights]
185
+ acc = 0.0
186
+ for x, wi in zip(axes, w):
187
+ x = _clamp(float(x))
188
+ if x <= 0.0:
189
+ return 0.0
190
+ acc += wi * math.log(x)
191
+ return _clamp(math.exp(acc))
192
+
193
+
194
+ def _lambda_axes(seed: int, model: str, quote_digest: str, boot_matches: bool) -> Dict[str, Any]:
195
+ """Deterministic per-axis trust scores in [0,1] derived from (seed, model, quote).
196
+
197
+ The `attestation` axis is HARD-COUPLED to the measured-boot result: if the boot chain does
198
+ NOT match its golden reference, attestation collapses toward 0 and A4 zero-absorption pulls
199
+ Λ down — exactly the CoCo KBS behaviour (no secret/inference release without a good quote).
200
+ """
201
+ s = str(seed)
202
+ scores: Dict[str, float] = {}
203
+ for name in _AXIS_NAMES:
204
+ base = 0.90 + 0.09 * _det_unit(s, model, quote_digest, name) # in [0.90, 0.99]
205
+ scores[name] = _clamp(base, 0.0, 0.97) # trust ceiling 0.97 (Doctrine v11)
206
+ # attestation axis is gated on the boot measurement matching its golden reference
207
+ if not boot_matches:
208
+ scores["attestation"] = 0.0 # zero-absorption → Λ = 0 → gate BLOCKS
209
+ axes = [scores[n] for n in _AXIS_NAMES]
210
+ L = _weighted_geomean(axes, _AXIS_WEIGHTS)
211
+ return {
212
+ "trust_axes": len(_AXIS_NAMES),
213
+ "axes": [{"name": n, "score": round(scores[n], 4), "weight": _AXIS_WEIGHTS[i]}
214
+ for i, n in enumerate(_AXIS_NAMES)],
215
+ "value": round(L, 6),
216
+ "floor": LAMBDA_FLOOR,
217
+ "pass": bool(L >= LAMBDA_FLOOR),
218
+ "aggregator": "weighted geometric mean (F19 family), A4 zero-absorption, ceiling 0.97",
219
+ "uniqueness": "Λ = Conjecture 1 (advisory, gray — NOT a theorem, never green); nothing to locked-8.",
220
+ }
221
+
222
+
223
+ # ---------------------------------------------------------------------------
224
+ # device attestation — reuse/extend the cc-attest measured-boot chain
225
+ # ---------------------------------------------------------------------------
226
+ def _measurement_chain(seed: int, model: str) -> Dict[str, Any]:
227
+ """Deterministic measured-boot hash-chain (MODELED), mirroring Wave-A cc-attest.
228
+
229
+ device_identity (sha384) → stage digests chained → final_digest checked against a fixed
230
+ golden reference. This is the SEV-SNP/TDX/H100-CC measured-boot PATTERN — device identity
231
+ plus an ordered chain of stage measurements folded into a final attestation value — NOT a
232
+ real hardware quote.
233
+ """
234
+ device_identity = _sha384(f"szl-attested-device|{model}|seed={seed}".encode("utf-8"))
235
+ chain: List[Dict[str, str]] = []
236
+ acc = device_identity
237
+ for stage in _BOOT_STAGES:
238
+ stage_measure = _sha384(f"{stage}|{model}|seed={seed}".encode("utf-8"))
239
+ acc = _sha384(f"{acc}|{stage}:{stage_measure}".encode("utf-8"))
240
+ chain.append({"stage": stage, "measurement": stage_measure, "chained_digest": acc})
241
+ final_digest = acc
242
+ # Golden reference = the deterministic final digest for a "known-good" build of this model.
243
+ # In MODELED mode a known-good build is defined as seed with the low bit clear (even seed);
244
+ # odd seeds simulate a tampered/unknown boot so the surface can show a MISMATCH honestly.
245
+ golden_reference = _sha384(
246
+ f"golden|{model}|{_sha384(('|'.join(_BOOT_STAGES) + '|' + model).encode())}".encode("utf-8")
247
+ )
248
+ golden_match = (final_digest == _golden_final(seed, model, golden_reference))
249
+ return {
250
+ "device_identity": device_identity,
251
+ "measurement_chain": [{"stage": c["stage"], "digest": c["chained_digest"]} for c in chain],
252
+ "stage_measurements": chain,
253
+ "final_digest": final_digest,
254
+ "golden_reference": golden_reference,
255
+ "golden_match": golden_match,
256
+ "stages": len(_BOOT_STAGES),
257
+ }
258
+
259
+
260
+ def _golden_final(seed: int, model: str, golden_reference: str) -> str:
261
+ """MODELED golden final digest: for an even seed the boot matches (known-good build);
262
+ for an odd seed we return a different value so golden_match is False (simulated tamper)."""
263
+ if seed % 2 == 0:
264
+ # reconstruct the exact final_digest the good build would produce
265
+ acc = _sha384(f"szl-attested-device|{model}|seed={seed}".encode("utf-8"))
266
+ for stage in _BOOT_STAGES:
267
+ stage_measure = _sha384(f"{stage}|{model}|seed={seed}".encode("utf-8"))
268
+ acc = _sha384(f"{acc}|{stage}:{stage_measure}".encode("utf-8"))
269
+ return acc
270
+ return golden_reference # deliberately != final_digest for odd seeds → MISMATCH
271
+
272
+
273
+ def _attestation_quote(seed: int, model: str, mc: Dict[str, Any], prompt_digest: str) -> Dict[str, Any]:
274
+ """Build a MODELED attestation quote in the shape of the leaders' reports.
275
+
276
+ We mirror the SEV-SNP `REPORT_DATA` binding: the quote commits to an app-supplied value
277
+ (here the prompt/inference digest) so the quote is cryptographically bound to THIS inference.
278
+ We also mirror the TDX MRTD (boot measurement) and NVIDIA CC-mode fields. `quote_digest` is
279
+ the SHA-384 the receipt embeds. NO real hardware quote is produced.
280
+ """
281
+ report_data = _sha384(f"REPORT_DATA|{prompt_digest}|{mc['final_digest']}".encode("utf-8"))
282
+ quote_body = {
283
+ "tee_family": "MODELED-CC", # stands in for {sev-snp, tdx, h100-cc}
284
+ "cc_mode": "ON (MODELED)", # NVIDIA H100 CC-mode ON
285
+ "mrtd": mc["final_digest"], # TDX MRTD analogue = final boot measurement
286
+ "report_data": report_data, # SEV-SNP REPORT_DATA = binds this inference
287
+ "measurement_stages": [c["stage"] for c in mc["stage_measurements"]],
288
+ "vcek_kds": "MODELED (no AMD KDS / NVIDIA NRAS network call performed)",
289
+ "nonce": _sha256(f"nonce|{seed}|{model}".encode("utf-8"))[:32],
290
+ }
291
+ quote_digest = _sha384(_canon(quote_body))
292
+ return {
293
+ "quote_body": quote_body,
294
+ "quote_digest": quote_digest,
295
+ "verified_against": "MODELED golden reference (no NRAS/KDS/DCAP verifier contacted)",
296
+ "leaders_pattern": "NVIDIA NRAS · AMD SEV-SNP REPORT_DATA/VCEK · Intel TDX MRTD",
297
+ "label": LABEL,
298
+ }
299
+
300
+
301
+ # ---------------------------------------------------------------------------
302
+ # gated inference — deterministic MODELED token stream (no real engine)
303
+ # ---------------------------------------------------------------------------
304
+ def _tee_attestation() -> Dict[str, Any]:
305
+ """Defer to the real TEE probe; surface its honest label verbatim. Never fabricates."""
306
+ try:
307
+ import szl_tee_attest # per-file COPY'd, guarded import
308
+ return szl_tee_attest.get_tee_attestation()
309
+ except Exception as e: # pragma: no cover — additive, never breaks the request
310
+ return {
311
+ "present": False,
312
+ "label": "UNAVAILABLE",
313
+ "note": f"szl_tee_attest unavailable in this runtime ({type(e).__name__}); "
314
+ "no TEE probe performed; no measurement fabricated.",
315
+ }
316
+
317
+
318
+ def _gated_inference(seed: int, model: str, allowed: bool, quote_digest: str) -> Dict[str, Any]:
319
+ """MODELED inference. Deterministic pseudo-tokens from (seed, model). If the Λ-gate did NOT
320
+ pass, the inference is WITHHELD (mirrors CoCo KBS refusing key/secret release on a bad quote).
321
+ """
322
+ prompt = f"attested-inference probe seed={seed} model={model}"
323
+ prompt_digest = _sha384(prompt.encode("utf-8"))
324
+ if not allowed:
325
+ return {
326
+ "released": False,
327
+ "reason": "Λ-gate BLOCKED — attested trust below advisory floor; inference withheld "
328
+ "(CoCo KBS-style: no secret/inference release without a good attestation).",
329
+ "prompt_digest": prompt_digest,
330
+ "output_digest": None,
331
+ "tokens": [],
332
+ "label": LABEL,
333
+ }
334
+ # deterministic token stream: derive N pseudo-token ids from a keyed hash chain
335
+ n_tokens = 8 + (seed % 8)
336
+ key = f"{model}|{quote_digest}".encode("utf-8")
337
+ tokens: List[int] = []
338
+ acc = hmac.new(key, str(seed).encode("utf-8"), hashlib.sha256).digest()
339
+ for _ in range(n_tokens):
340
+ acc = hmac.new(key, acc, hashlib.sha256).digest()
341
+ tokens.append(int.from_bytes(acc[:2], "big") % 50257) # GPT-2-vocab-sized id space
342
+ output_digest = _sha384(_canon(tokens))
343
+ return {
344
+ "released": True,
345
+ "prompt": prompt,
346
+ "prompt_digest": prompt_digest,
347
+ "n_tokens": n_tokens,
348
+ "tokens": tokens,
349
+ "output_digest": output_digest,
350
+ "note": "MODELED token ids (HMAC-SHA256 chain keyed on model+quote); no real LM engine ran.",
351
+ "label": LABEL,
352
+ }
353
+
354
+
355
+ # ---------------------------------------------------------------------------
356
+ # SLSA-style provenance predicate (in-toto/SLSA v1) — embedded in the receipt
357
+ # ---------------------------------------------------------------------------
358
+ def _slsa_provenance(seed: int, model: str, mc: Dict[str, Any], quote_digest: str,
359
+ inference: Dict[str, Any]) -> Dict[str, Any]:
360
+ """Emit an in-toto/SLSA v1 provenance predicate for the attested inference.
361
+
362
+ Maps the run onto the SLSA predicate shape (builder, buildType, invocation, subject digests)
363
+ so the receipt is checkable with off-the-shelf `slsa-verifier`/`cosign` — the leader pattern.
364
+ """
365
+ subject_digest = inference.get("output_digest") or mc["final_digest"]
366
+ return {
367
+ "_type": "https://in-toto.io/Statement/v1",
368
+ "predicateType": "https://slsa.dev/provenance/v1",
369
+ "subject": [{
370
+ "name": f"attested-inference/{model}",
371
+ "digest": {"sha384": subject_digest},
372
+ }],
373
+ "predicate": {
374
+ "buildDefinition": {
375
+ "buildType": "https://a-11-oy.com/attested-inference/v1",
376
+ "externalParameters": {"seed": seed, "model": model},
377
+ "internalParameters": {
378
+ "mrtd": mc["final_digest"],
379
+ "attestation_quote_digest": quote_digest,
380
+ },
381
+ "resolvedDependencies": [{
382
+ "name": "device-measured-boot-chain",
383
+ "digest": {"sha384": mc["final_digest"]},
384
+ }],
385
+ },
386
+ "runDetails": {
387
+ "builder": {"id": "https://a-11-oy.com/builders/attested-inference-MODELED"},
388
+ "metadata": {
389
+ "invocationId": _sha256(f"{seed}|{model}|{quote_digest}".encode())[:24],
390
+ "startedOn": _now_iso(),
391
+ },
392
+ },
393
+ },
394
+ "slsa_level_claim": "L1 (honest) — provenance present + signed; NOT an L2/L3 claim.",
395
+ "verify_with": "cosign verify-blob / slsa-verifier against szl-holdings cosign.pub",
396
+ "label": LABEL,
397
+ }
398
+
399
+
400
+ # ---------------------------------------------------------------------------
401
+ # receipt + DSSE — real ECDSA-P256 in-Space; honest UNSIGNED-LOCAL locally
402
+ # ---------------------------------------------------------------------------
403
+ def _sign_receipt(receipt: Dict[str, Any]) -> Dict[str, Any]:
404
+ """DSSE-sign the receipt. Real ECDSA-P256 when the cosign secret is present in-Space;
405
+ honest UNSIGNED-LOCAL envelope otherwise (never fabricates a signature)."""
406
+ try:
407
+ import szl_dsse # per-file COPY'd, guarded
408
+ env = szl_dsse.sign_payload(receipt, payload_type=PAYLOAD_TYPE)
409
+ if not env.get("signed"):
410
+ # normalise the local (no-secret) honesty marker to the doctrine label
411
+ env.setdefault("honesty", "UNSIGNED-LOCAL — no cosign secret in this runtime; no signature fabricated.")
412
+ env["local_label"] = "UNSIGNED-LOCAL"
413
+ return env
414
+ except Exception as e: # pragma: no cover — additive
415
+ body = _canon(receipt)
416
+ return {
417
+ "payloadType": PAYLOAD_TYPE,
418
+ "signatures": [],
419
+ "signed": False,
420
+ "local_label": "UNSIGNED-LOCAL",
421
+ "honesty": f"UNSIGNED-LOCAL — szl_dsse unavailable ({type(e).__name__}); no signature fabricated.",
422
+ "_pae_sha256": _sha256(b"DSSEv1 " + str(len(PAYLOAD_TYPE)).encode() + b" " +
423
+ PAYLOAD_TYPE.encode() + b" " + str(len(body)).encode() + b" " + body),
424
+ }
425
+
426
+
427
+ def run_attested_inference(seed: int, model: str) -> Dict[str, Any]:
428
+ """The full attested-inference flow, deterministic + MODELED. Returns the response dict.
429
+
430
+ device attestation → Λ-gate → gated inference → receipt (quote digest + Λ axes + SLSA
431
+ provenance) → DSSE envelope. Verifiable-by-design: everything is recomputable from (seed,model).
432
+ """
433
+ seed = int(seed)
434
+ model = str(model or "szl-modeled-lm")
435
+
436
+ # 1) device attestation (measured-boot chain — extends Wave-A cc-attest)
437
+ mc = _measurement_chain(seed, model)
438
+ tee = _tee_attestation()
439
+
440
+ # 2) bind the (about-to-run) inference into the attestation quote (SEV-SNP REPORT_DATA style)
441
+ prompt_digest = _sha384(f"attested-inference probe seed={seed} model={model}".encode("utf-8"))
442
+ quote = _attestation_quote(seed, model, mc, prompt_digest)
443
+
444
+ # 3) Λ-gate over the 13 trust axes; attestation axis hard-coupled to the boot match
445
+ lam = _lambda_axes(seed, model, quote["quote_digest"], mc["golden_match"])
446
+
447
+ # 4) gated inference (withheld if Λ-gate blocks — CoCo KBS style)
448
+ inference = _gated_inference(seed, model, lam["pass"], quote["quote_digest"])
449
+
450
+ # 5) SLSA-style provenance predicate
451
+ slsa = _slsa_provenance(seed, model, mc, quote["quote_digest"], inference)
452
+
453
+ # 6) assemble the receipt (embeds attestation quote digest + Λ axes + SLSA provenance)
454
+ receipt_core: Dict[str, Any] = {
455
+ "schema": "szl.attested-inference/v1",
456
+ "label": LABEL,
457
+ "seed": seed,
458
+ "model": model,
459
+ "device_identity": mc["device_identity"],
460
+ "attestation_quote_digest": quote["quote_digest"],
461
+ "mrtd": mc["final_digest"],
462
+ "golden_match": mc["golden_match"],
463
+ "tee_attestation": {"present": tee.get("present"), "label": tee.get("label")},
464
+ "lambda": {"value": lam["value"], "floor": lam["floor"], "pass": lam["pass"],
465
+ "axes": lam["axes"], "uniqueness": lam["uniqueness"]},
466
+ "inference": {"released": inference["released"],
467
+ "output_digest": inference.get("output_digest"),
468
+ "prompt_digest": inference.get("prompt_digest")},
469
+ "slsa_provenance": slsa,
470
+ "issued_at": _now_iso(),
471
+ "honest_note": HONEST_NOTE,
472
+ "sources": SOURCES,
473
+ }
474
+ receipt_digest = _sha384(_canon(receipt_core))
475
+ receipt_core["receipt_digest"] = receipt_digest
476
+
477
+ # 7) DSSE envelope over the receipt (real ECDSA-P256 in-Space; UNSIGNED-LOCAL locally)
478
+ dsse = _sign_receipt(receipt_core)
479
+
480
+ # 8) forum ingest (additive, off the hot path, never raises) — attested-inference provenance
481
+ try:
482
+ import szl_org_lambda as _ol # noqa: F401 — presence check only; emit is best-effort
483
+ _ol.emit("a11oy", "attest/infer",
484
+ {"seed": seed, "model": model, "lambda": lam["value"],
485
+ "quote_digest": quote["quote_digest"], "label": LABEL},
486
+ decision="ALLOW" if lam["pass"] else "BLOCK")
487
+ except Exception:
488
+ pass
489
+
490
+ return {
491
+ "label": LABEL,
492
+ "seed": seed,
493
+ "model": model,
494
+ "stages": mc["stages"],
495
+ # Wave-A cc-attest compatible fields (so attestinfer.js can render the tower):
496
+ "device_identity": mc["device_identity"],
497
+ "measurement_chain": mc["measurement_chain"],
498
+ "final_digest": mc["final_digest"],
499
+ "golden_match": mc["golden_match"],
500
+ # attested-inference deepening:
501
+ "tee_attestation": tee,
502
+ "attestation_quote": quote,
503
+ "lambda": lam,
504
+ "inference": inference,
505
+ "slsa_provenance": slsa,
506
+ "receipt": receipt_core,
507
+ "dsse": dsse,
508
+ "verifiable_by_design": (
509
+ "Recompute the measured-boot chain + quote from (seed, model), recompute Λ from the "
510
+ "13 axes, recompute the receipt digest, then verify the DSSE envelope with "
511
+ "`cosign verify-blob --key cosign.pub` (in-Space) — every field is checkable."
512
+ ),
513
+ "honest_note": HONEST_NOTE,
514
+ "sources": SOURCES,
515
+ "ts": _now_iso(),
516
+ }
517
+
518
+
519
+ # ---------------------------------------------------------------------------
520
+ # HTTP handler + registration (front-inserted route, mirrors szl_tee_attest)
521
+ # ---------------------------------------------------------------------------
522
+ def _h_attest_infer(request):
523
+ from starlette.responses import JSONResponse # type: ignore[import]
524
+ qp = request.query_params
525
+ try:
526
+ seed = int(qp.get("seed", "42"))
527
+ except Exception:
528
+ seed = 42
529
+ model = qp.get("model", "szl-modeled-lm")
530
+ try:
531
+ result = run_attested_inference(seed, model)
532
+ return JSONResponse(result)
533
+ except Exception as e: # pragma: no cover — always return a renderable 200-shaped body
534
+ return JSONResponse({
535
+ "label": LABEL, "seed": seed, "model": model, "error": f"{type(e).__name__}: {e}",
536
+ "honest_note": HONEST_NOTE, "sources": SOURCES,
537
+ }, status_code=200)
538
+
539
+
540
+ def register(app, ns: str = NS_DEFAULT) -> dict:
541
+ """Wire GET /api/<ns>/v1/attest/infer onto the app.
542
+
543
+ Additive. Front-inserts the route (routes.insert(0, ...)) so it wins over the generic
544
+ /api/a11oy/{path:path} Node proxy catch-all — the proven pattern used by szl_tee_attest,
545
+ szl_e8, szl_compliance, etc. Never raises into the caller.
546
+ """
547
+ path = f"/api/{ns}/v1/attest/infer"
548
+ prefix = f"/api/{ns}/v1/attest/"
549
+ try:
550
+ from starlette.routing import Route # type: ignore[import]
551
+ except Exception as e:
552
+ return {"registered": [], "status": f"failed:starlette-absent:{e}"}
553
+ try:
554
+ _r = Route(path, _h_attest_infer, methods=["GET"])
555
+ routes = app.router.routes
556
+ # Belt-and-suspenders: a pre-existing PARAMETRIZED route
557
+ # /api/<ns>/v1/attest/{receipt_hash} (szl_attest_stack) would otherwise match
558
+ # "infer" as a receipt_hash. Insert our STATIC route immediately BEFORE the first
559
+ # such parametrized attest route so exact-path matching wins; else front-insert.
560
+ insert_at = 0
561
+ for i, rt in enumerate(routes):
562
+ p = getattr(rt, "path", "") or ""
563
+ if p.startswith(prefix) and ("{" in p) and p != path:
564
+ insert_at = i
565
+ break
566
+ routes.insert(insert_at, _r)
567
+ return {"registered": [path], "status": "ok", "inserted_at": insert_at}
568
+ except Exception as e:
569
+ return {"registered": [], "status": f"failed:{type(e).__name__}:{e}"}
570
+
571
+
572
+ # ---------------------------------------------------------------------------
573
+ # No-server self-test — determinism + honesty invariants
574
+ # ---------------------------------------------------------------------------
575
+ def _selftest() -> dict:
576
+ a = run_attested_inference(42, "szl-modeled-lm")
577
+ b = run_attested_inference(42, "szl-modeled-lm")
578
+ # determinism: same (seed, model) → identical measured-boot + quote + Λ (ignore timestamps)
579
+ assert a["final_digest"] == b["final_digest"], "measured-boot not deterministic"
580
+ assert a["attestation_quote"]["quote_digest"] == b["attestation_quote"]["quote_digest"]
581
+ assert a["lambda"]["value"] == b["lambda"]["value"], "Λ not deterministic"
582
+ # honesty invariants
583
+ assert a["label"] == "MODELED", a["label"]
584
+ assert a["lambda"]["value"] <= 0.97 + 1e-9, "trust ceiling 0.97 violated"
585
+ assert "Conjecture 1" in a["lambda"]["uniqueness"], "Λ must be Conjecture 1"
586
+ assert a["receipt"]["attestation_quote_digest"] == a["attestation_quote"]["quote_digest"], \
587
+ "receipt must embed the attestation quote digest"
588
+ # even seed → good boot → gate passes → inference released
589
+ assert a["golden_match"] is True and a["inference"]["released"] is True, a["golden_match"]
590
+ # odd seed → tampered boot → attestation axis 0 → Λ=0 → gate blocks → inference withheld
591
+ c = run_attested_inference(43, "szl-modeled-lm")
592
+ assert c["golden_match"] is False, "odd seed should simulate a boot mismatch"
593
+ assert c["lambda"]["value"] == 0.0, "zero-absorption should drive Λ to 0 on bad attestation"
594
+ assert c["inference"]["released"] is False, "inference must be withheld when Λ-gate blocks"
595
+ # DSSE present, honestly labeled (signed or UNSIGNED-LOCAL — never fabricated)
596
+ assert "dsse" in a and ("signed" in a["dsse"]), a["dsse"].keys()
597
+ return {"ok": True, "lambda_even": a["lambda"]["value"], "gate_even": a["lambda"]["pass"],
598
+ "lambda_odd": c["lambda"]["value"], "gate_odd": c["lambda"]["pass"],
599
+ "dsse_signed": a["dsse"].get("signed"), "quote_digest": a["attestation_quote"]["quote_digest"][:16]}
600
+
601
+
602
+ if __name__ == "__main__":
603
+ print(json.dumps(_selftest(), indent=2, default=str))