# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-verify-a-peer-agent-s-workload-identity-when-the-spiffe-svid-it-presents-was-minted-for-a-different-trust-domain-than-the-one-n.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-verify-a-peer-agent-s-workload-identity-when-the-spiffe-svid-it-presents-was-minted-for-a-different-trust-domain-than-the-one-n.warrant.json
# Markdown SHA-256:   9894fb601e864753dd08169369adb96248f594b6bec157449608d02dfa851877
# Code AST SHA-256:   32d03656041c2c79916baf427c2327cbe0ddf59646329a15f294de1a8eae75df
# Verified Classes:   IdentityBindingError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class IdentityBindingError(RuntimeError):
    """Raised when SVID and VC verify independently but do not bind."""


def verify_agent_identity(
    svid: dict,
    vc: dict,
    active_trust_domains: set[str],
    retained_trust_domains: set[str],
    issuer_td_attestations: dict[str, set[str]],
) -> dict:
    # Plane 1: workload identity (SVID) — assume chain already verified upstream.
    td = svid["trust_domain"]
    spiffe_id = svid["spiffe_id"]  # full spiffe://td/path

    if td in retained_trust_domains and td not in active_trust_domains:
        raise IdentityBindingError(
            f"SVID trust domain {td!r} is retained but not active; "
            "rotation-window replay is not authorized for live handshakes"
        )
    if td not in active_trust_domains:
        raise IdentityBindingError(f"SVID trust domain {td!r} not in active bundle")

    # Plane 2: org identity (VC) — assume signature already verified upstream.
    issuer = vc["iss"]
    workload_claim = vc.get("credentialSubject", {}).get("workloadId")

    if workload_claim is None:
        # Valid but unbound: authorize as org-level, never as named agent.
        return {"mode": "unbound", "org": issuer, "agent": None}

    # Cross-attestation: issuer DID must be authorized for this trust domain.
    if td not in issuer_td_attestations.get(issuer, set()):
        raise IdentityBindingError(
            f"VC issuer {issuer!r} is not cross-attested for trust domain {td!r}"
        )

    # Binding: full SPIFFE ID equality, not host-string equality.
    if workload_claim != spiffe_id:
        raise IdentityBindingError(
            f"VC workloadId {workload_claim!r} does not bind to SVID {spiffe_id!r}"
        )

    # Channel-bound proof-of-possession asserted by caller's mTLS layer.
    if not svid.get("pop_verified"):
        raise IdentityBindingError("SVID key possession not proven on channel")

    return {"mode": "bound", "org": issuer, "agent": spiffe_id}
