# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-aaif-attestation-chains-from-collapsing-under-cross-issuer-delegation-depth-the-witness-gap-failure-at-the-third-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-aaif-attestation-chains-from-collapsing-under-cross-issuer-delegation-depth-the-witness-gap-failure-at-the-third-hop.warrant.json
# Markdown SHA-256:   b41a50a1d2c3ae3496921aaf6c820bd6abce136eb2bdc8796689e0a519ff45a0
# Code AST SHA-256:   448aa8559a94274f13fb0864ee9612d4dd54f14338074ea55d2dfde9a50ed7c4
# Verified Classes:   WitnessGapError, WitnessRecord, Credential
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Optional


class WitnessGapError(RuntimeError):
    """Raised when a delegation-chain edge cannot be witness-continuous.

    This is a fail-closed condition. It is NOT retryable: the credential
    held by the consumer is not the credential that was witnessed, and no
    re-fetch can repair the binding. The orchestrator must re-mint.
    """


@dataclass(frozen=True)
class WitnessRecord:
    credential_digest: str      # H(canonical(C_i) || witness_nonce)
    issuer_key_id: str
    canonicalization: str       # e.g. "aaif-jcs-v1"


@dataclass(frozen=True)
class Credential:
    subject: str
    parent_digest: Optional[str]
    witness: Optional[WitnessRecord]
    not_after: float


def canonicalize(obj: dict, scheme: str) -> bytes:
    if scheme != "aaif-jcs-v1":
        # Unknown canonicalization is itself a gap: we cannot recompute.
        raise WitnessGapError(f"unsupported canonicalization scheme: {scheme}")
    return json.dumps(obj, sort_keys=True, separators=(",", ":")).encode()


def recompute_digest(cred: Credential, nonce: bytes, scheme: str) -> str:
    body = {
        "subject": cred.subject,
        "parent_digest": cred.parent_digest,
        "not_after": cred.not_after,
    }
    return hashlib.sha256(canonicalize(body, scheme) + nonce).hexdigest()


def verify_edge(
    child: Credential,
    parent: Credential,
    nonce: bytes,
    current_jwks: set[str],
    grace_jwks: set[str],
    now: float,
) -> str:
    """Verify a single delegation edge.

    Returns 'ok' or 'degraded'. Raises WitnessGapError on any condition
    where the witness binding cannot be recomputed against the held
    credential. Re-fetch is deliberately NOT attempted here.
    """
    if child.witness is None:
        raise WitnessGapError(
            f"edge to {child.subject!r} has no witness record; "
            "chain is semantically orphaned at this hop"
        )

    if now > parent.not_after:
        # Expiry is a gap: the parent's authority lapsed before the child
        # was evaluated, so the witness may have been re-issued under a
        # rotated key. Fail closed rather than re-fetch.
        raise WitnessGapError(
            f"parent {parent.subject!r} expired at {parent.not_after}; "
            "witness continuity cannot be assumed across expiry"
        )

    expected = recompute_digest(
        parent, nonce, child.witness.canonicalization
    )
    if expected != child.witness.credential_digest:
        raise WitnessGapError(
            f"witness digest mismatch on edge to {child.subject!r}: "
            f"expected {expected[:12]}…, record holds "
            f"{child.witness.credential_digest[:12]}…; "
            "credential held != credential witnessed"
        )

    key = child.witness.issuer_key_id
    if key in current_jwks:
        return "ok"
    if key in grace_jwks:
        return "degraded"
    raise WitnessGapError(
        f"witness key {key!r} for {child.subject!r} is neither current "
        "nor in grace; re-fetch is prohibited (would substitute witness)"
    )


def execute_privileged_action(chain: list[Credential], nonces: list[bytes],
                              jwks: tuple[set[str], set[str]],
                              now: float) -> str:
    current, grace = jwks
    overall = "ok"
    for i in range(1, len(chain)):
        # nonces[i-1] is the nonce minted by the witness of chain[i-1]
        status = verify_edge(
            chain[i], chain[i - 1], nonces[i - 1],
            current, grace, now,
        )
        if status == "degraded":
            overall = "degraded"
    if overall == "degraded":
        # Degraded chains may not perform irreversible actions.
        return "requires_revalidation"
    return "authorized"
