# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-trust-domain-collapse-in-cross-org-agent-credential-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-trust-domain-collapse-in-cross-org-agent-credential-federation.warrant.json
# Markdown SHA-256:   aabe19a229fd07be683d57a877c3e0c1142b7a44cc882f46ca1bcf8ef6b97882
# Code AST SHA-256:   1cc037e5b03700aa40bf3e4febec920cb8ce3ed85562495bed1110f43b27413f
# Verified Classes:   TrustDomainCollapseError, DelegationChain, VerifiableCredential, FederationPolicy
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Mapping


class TrustDomainCollapseError(RuntimeError):
    """Raised when a federated credential is cryptographically valid but its
    claim semantics cannot be proven to match the issuer's intent at decision
    time. This is a fail-closed condition, not a recoverable retry."""


@dataclass(frozen=True)
class DelegationChain:
    root_workload: str
    links: tuple[str, ...]           # root -> ... -> leaf
    delegation_epoch: int            # issuer-incremented on any chain change
    valid_at_issuer: bool


@dataclass(frozen=True)
class VerifiableCredential:
    spiffe_id: str
    capability: str
    qualifiers: Mapping[str, str]
    ontology_version: str
    claim_hash: str                  # hash over (capability, sorted qualifiers)
    signed_body: bytes               # what the issuer actually signed


@dataclass
class FederationPolicy:
    pinned_ontology_versions: frozenset[str]
    known_delegation_epochs: frozenset[int]
    cache_ttl_seconds: int = 86_400


def _claim_hash(capability: str, qualifiers: Mapping[str, str]) -> str:
    payload = capability + "|" + "|".join(f"{k}={v}" for k, v in sorted(qualifiers.items()))
    return hashlib.sha256(payload.encode()).hexdigest()


def authorize(
    vc: VerifiableCredential,
    chain: DelegationChain,
    policy: FederationPolicy,
    *,
    now: datetime | None = None,
) -> bool:
    now = now or datetime.now(timezone.utc)

    # 1. Chain must be valid at the issuer *now*, not at cache time.
    if not chain.valid_at_issuer:
        raise TrustDomainCollapseError(
            f"delegation chain for {vc.spiffe_id} invalid at issuer; "
            f"reparenting likely — refusing to authorize"
        )
    if chain.links[-1] != vc.spiffe_id:
        raise TrustDomainCollapseError(
            f"leaf mismatch: chain ends at {chain.links[-1]}, VC presented for {vc.spiffe_id}"
        )

    # 2. Delegation epoch must be known — clock TTL is not a substitute.
    if chain.delegation_epoch not in policy.known_delegation_epochs:
        raise TrustDomainCollapseError(
            f"unknown delegation epoch {chain.delegation_epoch}; "
            f"issuer may have reparented since last sync — fail closed"
        )

    # 3. Ontology must be pinned. Unknown version is NOT forward-compatible
    #    for authorization: a minor bump may narrow scope.
    if vc.ontology_version not in policy.pinned_ontology_versions:
        raise TrustDomainCollapseError(
            f"ontology version {vc.ontology_version} not pinned; "
            f"cannot distinguish same-semantics from narrowed-semantics bump"
        )

    # 4. Claim hash must match the verifier's own parse. If the verifier's
    #    parser dropped a qualifier (e.g. scope: internal-only), the hash
    #    will mismatch and we fail closed instead of silently over-granting.
    recomputed = _claim_hash(vc.capability, vc.qualifiers)
    if recomputed != vc.claim_hash:
        raise TrustDomainCollapseError(
            f"claim hash mismatch for {vc.spiffe_id}: "
            f"signed={vc.claim_hash[:12]} parsed={recomputed[:12]} — "
            f"verifier likely truncated qualifiers (CLAIM_TRUNCATION)"
        )

    # Decision provenance is mandatory; a decision without it is not auditable.
    _record_decision(
        spiffe_id=vc.spiffe_id,
        ontology_version=vc.ontology_version,
        chain_root=chain.root_workload,
        claim_hash=vc.claim_hash,
        delegation_epoch=chain.delegation_epoch,
        decision="ALLOW",
        at=now,
    )
    return True


def _record_decision(**fields) -> None:
    # In production this writes to an append-only audit sink. The point is
    # that the record carries semantic provenance, not just "capability_match".
    if not fields.get("claim_hash") or not fields.get("ontology_version"):
        raise TrustDomainCollapseError(
            "refusing to emit decision without semantic provenance"
        )
