Skip to content

security: enforce SEP-signed SIP/Full-Security MDA with bounded freshness (#302) - #327

Closed
anupsv wants to merge 11 commits into
masterfrom
security/issue-302-mda-sip-freshness
Closed

anupsv wants to merge 11 commits into
masterfrom
security/issue-302-mda-sip-freshness

Conversation

@anupsv

@anupsv anupsv commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Closes #302. Closes all three gaps in the APNs+MDA attestation construction, within the issue's stated trust model (kernel trusted when SIP-on; code-signing is the identity root). Verified every load-bearing claim in the issue against current master and against the live fleet (GET /v1/providers/attestation, 97/97 certs) before building.

Gap 2 — decode & enforce the SEP-signed bits

attestation/mda.go decoded the security OIDs with a bool/last-byte heuristic that inverted the SIP bit: live Apple certs carry .13.1 (SIP) and .13.3 (kexts) as DER INTEGERs (02 01 00) and .13.2 (boot) as a raw string ("Full Security"), so csr=0 (fully-on) read as SIPEnabled=false and every boot level read as secure. Now:

  • .13.1 → INTEGER, require == 0; .13.2 → require == "Full Security"; .13.3 → INTEGER != 0 means kexts allowed. All fail closed on absent/unparseable.
  • Pinned by TestMDADecodePinnedLiveBytes carrying the exact live bytes.
  • Fixed a latent FreshnessCode bug: the blind asn1.Unmarshal of the raw 32-byte nonce "parsed" for many leading bytes and silently truncated it; unwrapFreshnessCode now only unwraps an off-length whole-value OCTET STRING whose inner length is the full nonce size.

Gap 1 — bounded freshness (the replay fix)

The nonce was the constant sha256(SE pubkey); since the SE key survives reboots, a SIP-on cert captured once was replayable forever after a csrutil disable reboot. A per-connection random nonce isn't viable — Apple rate-limits fresh attestations to ~1/device/7d and returns the cached cert (previous nonce) otherwise (documented DeviceAttestationNonce behavior; confirmed by research). So the nonce now rotates per 7-day epoch: HMAC-SHA256(seed, epoch ‖ SE pubkey).

  • Secret seed (EIGENINFERENCE_MDA_NONCE_SEED) makes future-epoch nonces unpredictable → no pre-minting; the SE-key input binds the cert to the device's key.
  • Accept current + 2 previous epochs (Apple's cached-cert tolerance) + a 21-day mint-age cap (leaf NotBefore) re-checked at the routing chokepoint.
  • Replay window: forever → ≤21 days. A 12h periodic re-check keeps long-lived connections rotating across epochs; pre-deploy (legacy-nonce) certs classify key-bound-but-never-fresh during migration.

Gap 3 — gate routing on the unforgeable signal

The SIP input to routing was the provider-self-reported ChallengeVerifiedSIP. New per-connection MDASIPVerified verdict (valid chain + serial match + SIP-on + Full-Security + fresh nonce + mint-age) now feeds the single private-text chokepoint, behind EIGENINFERENCE_MDA_ENFORCE_AFTER (same grace→enforce rollout as the APNs gate; startup refuses enforcement without MDM + a stable seed, fails fast on a malformed knob).

  • Apple-signed violations (forged chain / serial mismatch / SIP-off / non-Full-Security) → MarkUntrusted under enforcement (serial mismatch stays unconditional, as before); stale/cached/timeout responses only withhold the verdict, never untrust.
  • RestoreProviderState no longer resurrects MDAVerified across reconnects — the stored flag had no cert chain behind it and bridged exactly the reboot a SIP downgrade requires.
  • Sync + late-arriving-cert (MDM webhook) paths share one verdict core; the late path collects matching providers under the registry read lock and applies after releasing it (avoids an RWMutex self-deadlock — caught in review).

Rollout

Ships off. Configure EIGENINFERENCE_MDA_NONCE_SEED (openssl rand -hex 32, KMS-managed, must be stable) and leave EIGENINFERENCE_MDA_ENFORCE_AFTER unset → grace mode (verify + measure + log, never deroute). Allow ≥14 days after deploy for the fleet to re-mint onto epoch nonces, then set the deadline to flip enforcement.

Tests (all revert-verified)

  • attestation: pinned live-byte decode, weakened-state matrix (SIP-off / Reduced / Permissive / kexts / garbage all fail closed), FreshnessCode unwrap, epoch-nonce determinism/rotation/separation, freshness classification incl. legacy + out-of-window, age/epoch consistency.
  • registry: MDA grace vs enforce gate, mint-age expiry, restore-no-resurrect.
  • api: evaluateMDA full matrix, replay-ages-out, legacy-never-routes, late-cert rejection, late-SIP-off-untrusts-without-deadlock.
  • Reverting each fix (SIP decode, boot decode, chokepoint clause, restore clamp, freshness check, deadlock fix) fails the corresponding test. go build, go vet, full ./api ./registry ./attestation ./mdm ./cmd suites, and -race ./registry green.

Out of scope (issue's optional/lower-priority + residual risks): OCSP/CRL on the Apple chain, reproducible-build cdhash transparency log, ARV enforcement.

Reviewed by an independent Go security auditor (caught the late-path deadlock, since fixed + regression-tested) and a general-purpose correctness pass. One pre-existing follow-up noted: document the two new env vars in the deploy runbook before flipping enforcement.


View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.

…ness (#302)

Closes the three gaps in the APNs+MDA attestation construction (issue #302):

Gap 2 — decode + enforce the SEP-signed bits. Live Apple certs encode .13.1
(SIP) and .13.3 (kexts) as DER INTEGERs and .13.2 (boot state) as a RAW string;
the old parseBoolOID bool/last-byte heuristic INVERTED the SIP bit (INTEGER 0 =
fully-on read as "disabled") and read every boot level as secure. Now: .13.1
must parse as INTEGER == 0, .13.2 must equal "Full Security", .13.3 INTEGER !=
0 means kexts allowed — all fail closed, pinned by regression tests carrying
the exact bytes from live fleet certs (97/97 uniform: 020100 / "Full
Security"). Also fixes a latent FreshnessCode mangling: the blind
asn1.Unmarshal of the raw 32-byte nonce "succeeded" for many leading bytes and
silently truncated it; the unwrap now only fires for an off-length,
whole-value OCTET STRING whose inner content is the full nonce length.

Gap 1 — bounded freshness. The MDA nonce was the CONSTANT sha256(SE pubkey):
since the SE key survives reboots, a SIP-on cert captured once stayed "fresh"
forever (reboot-to-SIP-off + replay). A per-connection nonce is not viable —
Apple rate-limits fresh attestations to ~1/device/7d and serves the CACHED
cert (previous nonce) otherwise — so the nonce now rotates per 7-day epoch:
HMAC-SHA256(seed, epoch || SE pubkey), secret seed via
EIGENINFERENCE_MDA_NONCE_SEED (unpredictable future epochs -> no pre-minting),
accept current+2 previous epochs (Apple cached-cert tolerance), plus a 21-day
mint-age cap (leaf NotBefore) re-checked at the routing chokepoint. Replay
window: forever -> <=21 days. The challenge loop re-runs MDA every 12h so
long-lived connections rotate across epochs; legacy-nonce certs classify as
key-bound-but-never-fresh during migration.

Gap 3 — gate on the unforgeable signal. New per-connection MDASIPVerified
verdict (valid chain + serial match + SIP-on + Full-Security + fresh nonce +
mint-age) feeds the single private-text routing chokepoint behind
EIGENINFERENCE_MDA_ENFORCE_AFTER (same grace->enforce shape as the APNs gate;
startup refuses enforcement without MDM + a stable seed). Apple-signed
violations (forged chain, serial mismatch, SIP-off, non-Full-Security) mark
the provider untrusted under enforcement — serial mismatch unconditionally,
as before; stale/cached responses only withhold the verdict (never untrust).
RestoreProviderState no longer resurrects MDAVerified across reconnects (the
stored flag had no chain behind it and bridged exactly the reboot a SIP
downgrade requires); like hardware trust, the MDA verdict is re-earned per
connection. The synchronous and late-arriving-cert (MDM webhook) paths share
one verdict core (applyMDAVerdict); the late path collects matching providers
under the registry read lock and applies the verdict AFTER releasing it
(applyMDAVerdict takes the registry write lock — collecting-then-acting avoids
a self-deadlock and matches the fanOutDesiredModels convention), and now holds
the provider lock for its writes.

Also: correct the mdm.go comment claiming Apple hashes the nonce (it embeds
the bytes verbatim; hashing is the ACME flow), update the threat model's MDA
freshness entries, and expose mda_sip_verified / mda_sip_enabled /
mda_boot_state / mda_minted_at in GET /v1/providers/attestation.
@vercel

vercel Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview Jun 15, 2026 8:18pm
d-inference-console-ui-dev Ready Ready Preview Jun 15, 2026 8:18pm
d-inference-landing Ready Ready Preview Jun 15, 2026 8:18pm

Request Review

@github-actions

github-actions Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

This PR substantially strengthens the MDA SIP/Full-Security routing gate (T-036, T-037) and fixes a real gap where providers promoted to TrustHardware via non-MDA paths were silently unroutable under enforcement, but introduces a new self-route exemption to the MDA gate that needs explicit threat-model sign-off.


Trust Boundaries Touched

  • TB-002 — Coordinator → Provider WebSocket (MDA verdict, routing gate, mdmVerificationLoop)
  • TB-005 — Coordinator → Apple MDM/MDA (late MDA webhook routing, nonce-seed lifecycle)
  • TB-006 — Admin → Coordinator (new env-var knobs: EIGENINFERENCE_MDA_NONCE_SEED, EIGENINFERENCE_MDA_ENFORCE_AFTER)
  • TB-009 — Apple attestation chain (cross-cutting; MDASIPVerified as routing prerequisite)

Threat-by-Threat Assessment

T-036 — Trust level elevated without completing full MDM/MDA chain

✅ Strengthens mitigation.
mdmVerificationLoop in provider.go now continues iterating after mdmVerifyGranted until provider.HasFreshMDAVerdict() is true (lines around +if provider.HasFreshMDAVerdict() { return }). Previously, hardware grant from the ACME leg or a late SecurityInfo callback left MDASIPVerified=false, making the provider silently unroutable under enforcement. The loop now correctly waits for the MDA verdict to land.

T-037 — SIP/SecureBoot state self-reported without independent verification between challenges

✅ Strengthens mitigation.
providerSupportsPrivateTextLocked (registry.go) now gates routing on mdaRoutableLocked(p) — which requires MDASIPVerified && time.Since(p.MDAMintedAt) <= attestation.MDAMaxCertAge — rather than relying solely on the provider-process-self-reported ChallengeVerifiedSIP. The mint-age re-check runs on every routing decision, so a stale verdict expires at routing time even if re-attestation stalls. This is the key improvement.

T-033 — Attestation blob replay

✅ Neutral → strengthened (incremental).
parseMDANonceSeed() enforces that enforcement mode requires a stable ≥32-byte seed (EIGENINFERENCE_MDA_NONCE_SEED). A random per-boot seed under enforcement would invalidate all nonces on every restart and block re-mints for up to 7 days; the startup guard at main.go (the !mdaDeadline.IsZero() && len(mdaSeed) == 0 check) makes this a hard failure rather than a silent operational hole.

T-021 / T-036 — Unauthenticated MDM webhook injection (SEC-004)

⚠️ Partially weakened (scope expansion).
main.go replaces the previous inline SetMDAProofIfHardware callback with srv.HandleLateMDA, routing late webhook MDA certs through the full server verdict path. This is architecturally correct. However, the webhook remains completely unauthenticated (SEC-004 is still open), and late MDA certs that pass applyMDAVerdict can now set MDASIPVerified=true on a provider — the same routing-gate flag that this PR makes the hard prerequisite for private-text routing under enforcement. The blast radius of a forged late webhook is now higher (it can satisfy the new gate, not just set display flags). No new code-level mitigation for SEC-004 is added here.

T-034 — Provider runs modified code while advertising trusted identity (APNs code-identity gate)

ℹ️ Neutral.
providerSupportsPrivateTextLocked now takes a selfRouteOwner bool parameter. The APNs code-identity gate (codeAttestationEnforcedLocked() && !p.CodeAttested) explicitly has no self-route exemption — the comment confirms this is intentional. No functional change to T-034 mitigations.

T-038 — Missing ReadHeaderTimeout / MaxHeaderBytes

ℹ️ Not addressed. main.go changes are only in the MDM/MDA configuration block. SEC-027 remains open.

T-032 — Solana wallet mnemonic

ℹ️ Not touched by this diff.

T-041 — Profile signing identity

ℹ️ Not touched by this diff.


New Attack Surface / Gaps Not Covered by Existing Threats

🚨 Self-route MDA exemption is an untested trust assumption

registry.go introduces:

if !selfRouteOwner && r.mdaEnforcedLocked() && !mdaRoutableLocked(p) {
    return false
}

The comment justifies this as "a personal Mac will not be MDM/MDA enrolled." This is correct operationally, but the selfRouteOwner flag is passed in by the caller — confirm that every call site of providerSupportsPrivateTextLocked passes selfRouteOwner only when the routing request is genuinely from the provider's own account and that this cannot be influenced by consumer-controlled input. A consumer who can trigger selfRouteOwner=true for their request would bypass the MDA gate entirely under enforcement. This is not covered by any existing threat entry.

Action required: trace all call sites of providerSupportsPrivateTextLocked in registry.go and scheduler.go to confirm selfRouteOwner is derived from registry state, not from the consumer request.

ℹ️ MDACheckedAt race window in SetMDACheckStarted

registry.go truncates at p.MDACheckedA — the diff is cut off. Confirm that SetMDACheckStarted stamps MDACheckedAt atomically under p.mu before the verification goroutine launches, so concurrent MDARecheckDue calls during the in-flight check return false. If the stamp happens after the goroutine is spawned, two concurrent re-checks can both pass MDARecheckDue and stack.

ℹ️ EIGENINFERENCE_MDA_ENFORCE_AFTER without MDM → hard fail (good)

The new guard in main.go:

} else if os.Getenv("EIGENINFERENCE_MDA_ENFORCE_AFTER") != "" {
    logger.Error("refusing to start: …")
    os.Exit(1)
}

This is correct fail-closed behaviour — flagging it positively. Ensures an operator who configures enforcement but forgets MDM doesn't silently deroute the entire fleet.


SEC-* Findings Addressed

  • SEC-035 (T-041 / cross-tenant prefix-cache timing oracle) — ℹ️ Not addressed by this PR.
  • No existing SEC-* findings are formally closed by this diff, but the MDASIPVerified gate + MDAMintedAt expiry check are the coordinator-side implementation required before EIGENINFERENCE_MDA_ENFORCE_AFTER can safely be set, which unblocks moving the MDA gate from grace to enforced (the gap documented in TB-005 / T-036 / T-037).

Summary of Required Follow-ups

Priority Item
Must Audit all providerSupportsPrivateTextLocked call sites — confirm selfRouteOwner cannot be set by consumer-controlled routing input
Must Verify SetMDACheckStarted stamps MDACheckedAt under lock before spawning the re-check goroutine (diff truncated)
Should SEC-004: the unauthenticated MDM webhook now gates MDASIPVerified (the new enforcement prerequisite) — priority for adding shared-secret or CommandUUID binding has increased
Should Add a threat entry for the self-route MDA exemption to the threat model (currently undocumented)

🔐 Threat model: docs/threat-model.yaml · Updates on each push to this PR

@blacksmith-sh

blacksmith-sh Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Found 1 test failure on Blacksmith runners:

Failure

Test View Logs
github.com/eigeninference/d-inference/e2e/TestProfile_SingleProviderNonStreaming View Logs

Fix with Codesmith
Need help on this PR? Tag /codesmith with what you need.

…erial residual (#302 audit)

Round-3 adversarial audit of the MDA branch:

FIXED — late-path UDID namespace bug. The webhook-UDID equality check (added in
8318210) compared the cert's .8.9.2 Device Provisioning UDID (00006041-…)
against the webhook's MDM-protocol Hardware UUID; those are different namespaces
on a Mac and never match (confirmed against 97 live fleet certs), so it dropped
EVERY late cert and silently killed the late-recovery path. Removed it. Device
binding on the late path is the solicited-command gate (webhook UDID == the UDID
the command was sent to) + serial + SE-key-derived nonce in evaluateMDA — the
same proof the synchronous path trusts.

DOCUMENTED — third-party kexts (.13.3) parsed but intentionally not separately
gated: a Full-Security boot (already required) cannot load third-party kexts on
Apple silicon, so SecureBootEnabled already excludes that vector.

DOCUMENTED RESIDUAL — self-asserted serial. The MDA SIP gate verifies the
provider's self-asserted attestation serial, not one Apple-rooted to the
connection's SE key. macOS has no App Attest, so an app-held SE key can't be
cryptographically tied to a device serial with current primitives: a malicious
owner with a second, genuinely-SIP-on enrolled Mac can claim that device's
serial while serving from a SIP-off box. A coordinator-only ACME serial check
was prototyped and reverted — the served ACME profile mints a P-384 key the
Secure Enclave can't hardware-bind (SE is P-256-only; fleet is 0% acme_verified),
and step-ca copies the cert CN from the unvalidated CSR, so the check is both
non-functional (would brick routing under enforcement) and bypassable (CN, not
the validated permanent-identifier SAN). The real fix — provider proves
possession of the Apple-attested ACME key (P-256, used as the connection
identity) and the coordinator reads the permanent-identifier SAN — is a
provider-swift + protocol change tracked as a follow-up. Recorded in
docs/threat-model.yaml.
ethenotethan

This comment was marked as outdated.

ethenotethan

This comment was marked as outdated.

@anupsv

anupsv commented Jun 15, 2026

Copy link
Copy Markdown
Contributor Author

@codex review this

Head 41d99624 fixes your self-route finding: the #302 MDA gate now exempts the self-route-owner path. providerSupportsPrivateTextLocked takes a selfRouteOwner flag and skips ONLY the MDA gate for an owner's own provider (routing call passes allowPrivate; snapshotProviderLocked passes selfRouteOwner; OwnedProviderSummary passes true). Public routing stays fully MDA-gated; every privacy-critical gate (RuntimeVerified, private-text, challenge freshness, ChallengeVerifiedSIP) still applies to self-route. The APNs code-attestation gate keeps its no-self-route-exemption (needs no MDM enrollment) — documented inline.

TestSelfRouteExemptFromMDAGate added (revert-verified). Full attestation/registry/mdm/api suites + go test -race ./api/ ./registry/ green.

Please confirm the exemption is scoped correctly (only the MDA gate, only owner self-route) and that public routing + the other gates are unaffected.

ethenotethan

This comment was marked as outdated.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 41d99624a9

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

…mda-sip-freshness

# Conflicts:
#	coordinator/api/server.go
ethenotethan

This comment was marked as outdated.

ethenotethan

This comment was marked as outdated.

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated Code Review — Layr-Labs/d-inference#

Verdict: REQUEST_CHANGES

Security — 1 finding(s)

  • 🔵 [INFO] coordinator/api/mda_verify.go:46-54 — Fallback MDA nonce seed uses crypto/rand without entropy validation
    • Suggestion: Add entropy validation or use a more robust entropy source with proper error handling

Performance — 4 finding(s) (3 blocking)

  • 🟡 [MEDIUM] coordinator/api/mda_verify.go:310-325 — attributeAndApplyMDA collects all matching providers in memory without bounds
    • Suggestion: Add a reasonable limit to the targets slice or use a streaming approach to avoid potential memory exhaustion with many providers
  • 🔵 [INFO] coordinator/api/mda_verify.go:326-330 — applyMDAVerdict called in loop without batching or deduplication
    • Suggestion: Consider batching MDA verdict applications or deduplicating providers with identical serials to reduce redundant work
  • 🟡 [MEDIUM] coordinator/api/mda_verify.go:175 — Synchronous MDM command send on hot path without timeout context
    • Suggestion: Use a context with timeout for SendDeviceAttestationCommand to prevent indefinite blocking
  • 🟡 [MEDIUM] coordinator/api/mda_verify.go:181 — 60-second synchronous wait for device attestation blocks caller
    • Suggestion: Consider making this asynchronous or using a shorter timeout to prevent long blocking on the challenge loop

Type_diligence — 3 finding(s) (1 blocking)

  • 🔵 [INFO] coordinator/api/mda_verify.go:76 — evaluateMDA uses interface{} parameter for nonceSeed
    • Suggestion: Change nonceSeed parameter from []byte to a more specific type or add type assertion with ok check
  • 🔵 [INFO] coordinator/api/mda_verify.go:318 — mdaTarget struct uses map-like pattern with string keys
    • Suggestion: Consider using a typed struct instead of the current string-keyed approach for better type safety
  • 🟡 [MEDIUM] coordinator/attestation/mda.go:194 — parseIntOID missing type assertion check in asn1.Unmarshal
    • Suggestion: Add proper error handling and type assertion validation for the asn1.Unmarshal result

Additive_complexity — 8 finding(s) (2 blocking)

  • 🔵 [INFO] coordinator/api/mda_verify.go:46-54 — randomMDANonceSeed generates fallback seed with panic on entropy failure
    • Suggestion: Consider returning an error instead of panicking, or use a simpler fallback like time-based seed
  • 🟡 [MEDIUM] coordinator/api/mda_verify.go:75-135 — evaluateMDA function has complex branching logic that could be simplified
    • Suggestion: Consider breaking this into smaller validation functions or using a validation chain pattern
  • 🔵 [INFO] coordinator/api/mda_verify.go:295-325 — mdaTarget struct and collection pattern duplicates registry iteration logic
    • Suggestion: Consider reusing existing registry iteration patterns or creating a shared helper for collect-then-act operations
  • 🔵 [INFO] coordinator/attestation/mda.go:155-220 — parseAppleAttestationExtensions mixes parsing and business logic
    • Suggestion: Consider separating raw OID parsing from security policy decisions (like fail-closed defaults)
  • 🔵 [INFO] coordinator/attestation/mda_nonce.go:84-97 — MDAEpochNonce function could be inlined or simplified
    • Suggestion: The HMAC construction is straightforward enough to inline at call sites
  • 🟡 [MEDIUM] coordinator/registry/registry.go:371-413 — providerSupportsPrivateTextLocked has complex conditional logic with multiple gates
    • Suggestion: Consider breaking into separate gate functions or using a gate chain pattern for better readability
  • 🔵 [INFO] coordinator/registry/registry.go:689-695 — mdaRoutableLocked duplicates age checking logic that exists elsewhere
    • Suggestion: Consider creating a shared time-based validation helper
  • 🔵 [INFO] coordinator/api/mda_verify_test.go:22-108 — Test setup creates multiple similar test result objects
    • Suggestion: Consider using a test builder pattern or factory function to reduce duplication

16 finding(s) total, 6 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment on lines +46 to +54
// for up to a week — a fail-closed window).
func randomMDANonceSeed(logger *slog.Logger) []byte {
seed := make([]byte, 32)
if _, err := rand.Read(seed); err != nil {
// Without entropy the process has bigger problems; fail loudly.
panic(fmt.Sprintf("mda: cannot generate fallback nonce seed: %v", err))
}
logger.Info("MDA nonce seed: using a random per-boot seed (set EIGENINFERENCE_MDA_NONCE_SEED for a stable one before enforcement)")
return seed

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🔒 Fallback MDA nonce seed uses crypto/rand without entropy validation

💡 Suggestion: Add entropy validation or use a more robust entropy source with proper error handling

📊 Score: 3×2 = 6 · Category: insecure-randomness

Comment on lines +310 to +325
serial string
seKey string
}

// attributeAndApplyMDA applies a verified MDA result to every provider whose
// attested serial it matches. Providers are COLLECTED under ForEachProvider's
// registry read lock, then the verdict is applied AFTER that lock is released:
// applyMDAVerdict calls registry write-lock methods (MDAEnforced,
// MarkUntrusted) which would self-deadlock the RWMutex if invoked inside the
// RLock'd callback. This mirrors the fanOutDesiredModels collect-then-act
// convention (registry/model_alias_handlers.go).
func (s *Server) attributeAndApplyMDA(mdaResult *attestation.MDAResult, certChain [][]byte) {
var targets []mdaTarget
s.registry.ForEachProvider(func(p *registry.Provider) {
var serial, seKey string
p.Mu().Lock()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] ⚡ attributeAndApplyMDA collects all matching providers in memory without bounds

💡 Suggestion: Add a reasonable limit to the targets slice or use a streaming approach to avoid potential memory exhaustion with many providers

📊 Score: 3×4 = 12 · Category: unbounded_goroutines

Comment on lines +326 to +330
if ar := p.AttestationResult; ar != nil {
serial, seKey = ar.SerialNumber, ar.PublicKey
}
p.Mu().Unlock()
if serial != "" && serial == mdaResult.DeviceSerial {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] ⚡ applyMDAVerdict called in loop without batching or deduplication

💡 Suggestion: Consider batching MDA verdict applications or deduplicating providers with identical serials to reduce redundant work

📊 Score: 2×3 = 6 · Category: repeated_work

}

// Wait for Apple's response (device contacts Apple's servers — may take longer).
attestResp, err := s.mdmClient.WaitForDeviceAttestation(ctx, udid, 60*time.Second)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] ⚡ Synchronous MDM command send on hot path without timeout context

💡 Suggestion: Use a context with timeout for SendDeviceAttestationCommand to prevent indefinite blocking

📊 Score: 2×4 = 8 · Category: blocking_io

"provider_id", providerID, "error", err)
s.ddIncr("attestation.mda_check", []string{"result:timeout"})
return
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] ⚡ 60-second synchronous wait for device attestation blocks caller

💡 Suggestion: Consider making this asynchronous or using a shorter timeout to prevent long blocking on the challenge loop

📊 Score: 3×3 = 9 · Category: blocking_io

Comment on lines 155 to 220
@@ -163,26 +194,29 @@ func VerifyMDADeviceAttestation(certChainDER [][]byte) (*MDAResult, error) {
case ext.Id.Equal(OIDLLBVersion):
result.LLBVersion = parseStringOID(ext.Value)

// Freshness (100.8.11.*)
// Freshness (100.8.11.*) — the raw nonce bytes.
case ext.Id.Equal(OIDFreshnessCode):
var raw asn1.RawValue
if _, err := asn1.Unmarshal(ext.Value, &raw); err == nil {
result.FreshnessCode = raw.Bytes
} else {
result.FreshnessCode = ext.Value
}

// ACME path OIDs (100.8.13.*) — may also be present
result.FreshnessCode = unwrapFreshnessCode(ext.Value)

// SEP-measured security OIDs (100.8.13.*, macOS 14.2+).
//
// Live Apple certs encode .13.1/.13.3 as DER INTEGERs (`02 01 00` = SIP
// fully on / no kexts) and .13.2 as a RAW unwrapped string
// ("Full Security"). The previous parseBoolOID treated all three as
// ASN.1 booleans with a last-byte!=0 fallback, which INVERTED .13.1
// (INTEGER 0 → false) and read every .13.2 boot level as true. All
// three now fail CLOSED on absent/unparseable values.
case ext.Id.Equal(OIDSIPStatus):
result.SIPEnabled = parseBoolOID(ext.Value)
v, ok := parseIntOID(ext.Value)
result.SIPEnabled = ok && v == 0
case ext.Id.Equal(OIDSecureBootStatus):
result.SecureBootEnabled = parseBoolOID(ext.Value)
result.BootState = parseStringOID(ext.Value)
result.SecureBootEnabled = result.BootState == "Full Security"
case ext.Id.Equal(OIDKextStatus):
result.ThirdPartyKexts = parseBoolOID(ext.Value)
v, ok := parseIntOID(ext.Value)
result.ThirdPartyKexts = !ok || v != 0
}
}

return result, nil
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🧩 parseAppleAttestationExtensions mixes parsing and business logic

💡 Suggestion: Consider separating raw OID parsing from security policy decisions (like fail-closed defaults)

📊 Score: 2×2 = 4 · Category: misplaced responsibility

Comment on lines +84 to +97
// MDANonceEpoch returns the epoch number for t.
func MDANonceEpoch(t time.Time) uint64 {
return uint64(t.Unix()) / uint64(MDANonceEpochLength/time.Second)
}

// MDAEpochNonce derives the 32-byte attestation nonce for (seed, epoch, SE key).
func MDAEpochNonce(seed []byte, epoch uint64, sePublicKey string) []byte {
mac := hmac.New(sha256.New, seed)
mac.Write([]byte(mdaNonceDomain))
var e [8]byte
binary.BigEndian.PutUint64(e[:], epoch)
mac.Write(e[:])
mac.Write([]byte(sePublicKey))
return mac.Sum(nil)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🧩 MDAEpochNonce function could be inlined or simplified

💡 Suggestion: The HMAC construction is straightforward enough to inline at call sites

📊 Score: 1×2 = 2 · Category: over-abstraction

Comment on lines 371 to +413
@@ -373,9 +386,32 @@ func (r *Registry) providerSupportsPrivateTextLocked(p *Provider) bool {
// v0.6.0 APNs code-identity gate — the SINGLE chokepoint, no self-route
// exemption (gate everyone). Enforced only once configured AND past the grace
// deadline, so the fleet keeps routing through the rollout; fail-closed after.
// NOTE this gate intentionally has NO self-route exemption (unlike the MDA gate
// below): the APNs code-identity challenge needs no MDM enrollment, so a
// personal Mac can satisfy it, and gating self-route too keeps a SIP-off owner
// box from serving even its own private prompts with un-attested code.
if r.codeAttestationEnforcedLocked() && !p.CodeAttested {
return false
}
// Issue #302: the SIP signal that gates routing must be the SEP-signed MDA
// verdict — fresh (epoch nonce), SE-key-bound, SIP-on, Full-Security — not
// just ChallengeVerifiedSIP above, which the provider PROCESS self-reports
// and a SIP-off root owner can forge. Same grace→enforce rollout shape as
// the code-attestation gate; the mint-age re-check makes a stale verdict
// expire at routing time.
//
// EXEMPT self-route: unlike the APNs gate, the MDA verdict REQUIRES MDM/MDA
// enrollment, and self-route deliberately drops MDM/MDA-requiring floors — "a
// personal Mac will not be MDM/MDA enrolled, so without this it would be
// unroutable to its own owner" (see anyEligibleProviderCanRouteLocked /
// scheduler.go). Enforcing MDA on an owner's own machine would lock them out of
// it under enforcement. The owner serving their OWN prompts on their OWN box is
// outside the threat the MDA gate addresses (routing a stranger's private text
// to a possibly-SIP-off provider); every privacy-critical gate above still
// applies, so plaintext is never exposed.
if !selfRouteOwner && r.mdaEnforcedLocked() && !mdaRoutableLocked(p) {
return false

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] 🧩 providerSupportsPrivateTextLocked has complex conditional logic with multiple gates

💡 Suggestion: Consider breaking into separate gate functions or using a gate chain pattern for better readability

📊 Score: 3×4 = 12 · Category: over-configuration

Comment on lines +689 to +695
// (e.g. MDM outage) — fail closed, recover on the next passing attestation.
//
// KNOWN RESIDUAL (issue #302 follow-up): the serial evaluateMDA compares is the
// provider's SELF-ASSERTED attestation serial, not an Apple-rooted one. A
// malicious owner with a second, genuinely-SIP-on enrolled Mac can claim that
// device's serial while serving from a SIP-off box. Cleanly closing this needs
// the connection to prove possession of the Apple-attested (ACME device-attest)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🧩 mdaRoutableLocked duplicates age checking logic that exists elsewhere

💡 Suggestion: Consider creating a shared time-based validation helper

📊 Score: 2×3 = 6 · Category: duplicate logic

Comment on lines +22 to +108
seed := []byte("test-seed-0123456789abcdef0123456789abcdef")
now := time.Unix(1_770_000_000, 0)
const serial = "DRXYPT2MKX"
const seKey = "se-public-key-b64"
freshNonce := attestation.MDAEpochNonce(seed, attestation.MDANonceEpoch(now), seKey)
prevNonce := attestation.MDAEpochNonce(seed, attestation.MDANonceEpoch(now)-1, seKey)
staleNonce := attestation.MDAEpochNonce(seed, attestation.MDANonceEpoch(now)-attestation.MDANonceAcceptedEpochs, seKey)

good := func() *attestation.MDAResult {
return &attestation.MDAResult{
Valid: true,
DeviceSerial: serial,
SIPEnabled: true,
SecureBootEnabled: true,
BootState: "Full Security",
FreshnessCode: freshNonce,
LeafNotBefore: now.Add(-24 * time.Hour),
}
}

cases := []struct {
name string
mutate func(*attestation.MDAResult)
verified bool
definitive bool
reason string
}{
{"all good — verdict granted", func(m *attestation.MDAResult) {}, true, false, "ok"},
{"previous-epoch nonce (Apple cached cert) still fresh", func(m *attestation.MDAResult) {
m.FreshnessCode = prevNonce
}, true, false, "ok"},
{"chain invalid is definitive", func(m *attestation.MDAResult) {
m.Valid = false
}, false, true, "chain_invalid"},
{"serial mismatch is definitive (impersonation)", func(m *attestation.MDAResult) {
m.DeviceSerial = "OTHER-DEVICE"
}, false, true, "serial_mismatch"},
{"empty MDA serial fails closed", func(m *attestation.MDAResult) {
m.DeviceSerial = ""
}, false, true, "serial_missing"},
{"SIP disabled is definitive — even on a cached cert", func(m *attestation.MDAResult) {
m.SIPEnabled = false
m.FreshnessCode = staleNonce
}, false, true, "sip_disabled"},
{"non-Full-Security boot is definitive", func(m *attestation.MDAResult) {
m.SecureBootEnabled = false
m.BootState = "Permissive Security"
}, false, true, "not_full_security"},
{"third-party kexts allowed is definitive — never a routable verdict", func(m *attestation.MDAResult) {
// Should be unreachable on a real Full-Security boot, but the .13.3
// fail-closed parse must actually gate (defense-in-depth): a cert that
// reads SIP-on + Full-Security yet allows kexts must NOT route.
m.ThirdPartyKexts = true
}, false, true, "third_party_kexts"},
{"legacy constant nonce — migration state, transient", func(m *attestation.MDAResult) {
m.FreshnessCode = attestation.LegacyMDANonce(seKey)
}, false, false, "legacy_nonce"},
{"out-of-window nonce — the replay bound, transient", func(m *attestation.MDAResult) {
m.FreshnessCode = staleNonce
}, false, false, "nonce_unrecognized"},
{"another device's fresh nonce does not bind", func(m *attestation.MDAResult) {
m.FreshnessCode = attestation.MDAEpochNonce(seed, attestation.MDANonceEpoch(now), "other-se-key")
}, false, false, "nonce_unrecognized"},
{"missing freshness code — transient", func(m *attestation.MDAResult) {
m.FreshnessCode = nil
}, false, false, "nonce_unrecognized"},
{"cert older than MDAMaxCertAge — age backstop", func(m *attestation.MDAResult) {
m.LeafNotBefore = now.Add(-attestation.MDAMaxCertAge - time.Hour)
}, false, false, "cert_too_old"},
}

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
m := good()
tc.mutate(m)
eval := evaluateMDA(m, serial, seKey, seed, now)
if eval.SIPVerified != tc.verified {
t.Errorf("SIPVerified = %v, want %v", eval.SIPVerified, tc.verified)
}
if eval.Definitive != tc.definitive {
t.Errorf("Definitive = %v, want %v", eval.Definitive, tc.definitive)
}
if eval.Reason != tc.reason {
t.Errorf("Reason = %q, want %q", eval.Reason, tc.reason)
}
})
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [INFO] 🧩 Test setup creates multiple similar test result objects

💡 Suggestion: Consider using a test builder pattern or factory function to reduce duplication

📊 Score: 2×2 = 4 · Category: duplicate logic

@arian-gogani

Copy link
Copy Markdown

the bounded-freshness attestation is the right property — the MDA stamp proves the agent was in a valid state at a specific time, and the bound prevents replay.

the receipt layer complements this: the attestation proves the runtime was valid when the agent started. the action receipt proves each individual inference call within that attested session stayed within scope.

action_ref = SHA-256(JCS({agent_id, action_type, scope, timestamp_ms})) where timestamp_ms is bounded within the attestation validity window. a verifier checks: is the receipt's timestamp_ms within the MDA attestation's freshness window? if yes, the inference call happened inside the attested runtime. if not, the receipt is stale relative to the attestation — the gap is detectable.

this gives you two independently verifiable facts: (1) the runtime was attested at time T (SEP-signed MDA), (2) this inference call was made at time T+n within the attestation window (action receipt). a compliance auditor can verify both without trusting the d-inference operator.

@Gajesh2007 Gajesh2007 closed this Sep 14, 2026
Gajesh2007 added a commit that referenced this pull request Oct 22, 2026
Layr-Labs/mlx-swift-lm#327 squash-merged as 1bee5728 ("perf(cbv2): one fused causal SDPA per full-attention prompt chunk (#327)").
Move the gitlink from the PR branch head fd17d026 to that commit on SDK main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Gajesh2007 added a commit that referenced this pull request Oct 22, 2026
* perf(native): fused causal SDPA for full-attention prompt chunks

Bump libs/mlx-swift-lm to the CBv2 change that attends a full-attention
prompt chunk with one `.causal` SDPA call whenever MLX serves the head
geometry with a fused kernel (head_dim 64/72/80/96/128 on every Apple
GPU; head_dim 256 on NAX from 1024 queries), instead of 128-query blocks
with explicit masks. GPT-OSS full layers and the Qwen full-attention
layers of M5 solo prefill stripes take the new route; Gemma 4 does not.

The SDK pin moves from 19634dd8 to ff327738: SDK main (#316, #312, #315,
#317, #318) plus the change. SDK main requires mlx-swift 81f58d79
(nested MLX 71271f08), so libs/mlx-swift moves from 6923a80f and
libs/mlx from cb77239b; the Metal library built from the nested MLX is
byte-identical.

Document the SDK-read kill switch DARKBLOOM_TTFT_FUSED_CAUSAL_PREFILL=0
in the configuration reference and the prompt-chunk attention route in
the inference architecture, and add a changelog fragment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(native): name the unmeasured models the fused causal route reaches

Refactor pass over the fused causal prefill change.

Pin libs/mlx-swift-lm to fd17d026, the head of the paired SDK branch: one
refactor commit over ff327738 that changes comments and the route's test,
not compiled code.

The route follows layer geometry, so it also reaches the Nemotron 3.5
Lightning attention layers (head_dim 128, every chip) and the head_dim
256 full-attention layers of the other Qwen-family models in M5 solo
prefill stripes. The changelog fragment now names them and says they were
not measured. The inference and configuration rows note that Qwen4 QSA
blocks build no absolute mask and that live packed paged KV keeps its own
prompt path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Pin libs/mlx-swift-lm to the SDK change on master's SDK commit

The paired SDK PR branch (ttft/fused-causal-prefill) was published on SDK main 0351444e, which
also carries mlx-swift-lm #323 and #325 that d-inference master does not pin
yet. Pin ttft/fused-causal-prefill-pin (6d1321ce) instead: the same commits cherry-picked onto
0351444e, the SDK commit master pins, so this PR adds only this change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Revert "Pin libs/mlx-swift-lm to the SDK change on master's SDK commit"

d-inference master now pins SDK main 0351444e (#1531), the base the paired SDK
PR branch (ttft/fused-causal-prefill) was published on, so the PR head is already the right pin and
the cherry-picked ttft/fused-causal-prefill-pin copy is redundant.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Re-pin libs/mlx-swift-lm to the merged SDK change (#327)

Layr-Labs/mlx-swift-lm#327 squash-merged as 1bee5728 ("perf(cbv2): one fused causal SDPA per full-attention prompt chunk (#327)").
Move the gitlink from the PR branch head fd17d026 to that commit on SDK main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(provider): document fused causal prefill memory in hardware support

The fused causal prompt-attention route lowers the prefill transient
(Qwen3.5-9B on M5 Ultra at 32K: 13.86 -> 12.03 GB peak) but only
inference.md described it. Record in hardware-support.md what the route
drops, and that the activation reserve, measured floors, minimum load KV
and slot grants intentionally stay unchanged, with the reasons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(provider): restamp the fused causal prefill docs

inference.md and configuration.md changed for the fused causal prompt
attention route; set their freshness stamps to the UTC date of the
change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference-console-ui-dev — d370deea Deployed Jun 15, 2026 by vercel[bot]
Preview – d-inference — d370deea Deployed Jun 15, 2026 by vercel[bot]
Preview – d-inference-landing — d370deea Deployed Jun 15, 2026 by vercel[bot]
benchmarks — d370deea Deployed Jun 15, 2026 by anupsv via E2E Benchmarks #950
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

APNs code-identity (v0.6.0): close the remaining attestation gaps — bind a fresh MDA per connection and enforce the SEP-signed SIP/Secure-Boot OIDs

4 participants