# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-spiffe-svid-because-its-own-workload-attestation-has-silently-drifted-from-the-selector-set-baked-into-the-tr.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-spiffe-svid-because-its-own-workload-attestation-has-silently-drifted-from-the-selector-set-baked-into-the-tr.warrant.json
# Markdown SHA-256:   5e793302a6157c000cf86b69e2821af5c432b54cec786527ca8cb23b77fa1467
# Code AST SHA-256:   6b0b7bd88127deef65a48c28bd0c9fdb574254377ecd6a17ccd133de454df094
# Verified Classes:   FederatedIdentityDriftError, AttestationSnapshot, FederationAgreement, IdentityAssertionGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from datetime import datetime, timezone


class FederatedIdentityDriftError(RuntimeError):
    """Raised when an agent's current attestation selectors no longer match
    the selector subset admitted by a federated peer's agreement."""
    pass


@dataclass(frozen=True)
class AttestationSnapshot:
    spiffe_id: str
    selectors: frozenset[str]
    svid_serial: str
    issued_at: datetime


@dataclass
class FederationAgreement:
    peer_org: str
    admitted_spiffe_id: str
    admitted_selectors: frozenset[str]   # the subset the peer agreed to
    signed_at: datetime


@dataclass
class IdentityAssertionGate:
    agreement: FederationAgreement
    last_good: AttestationSnapshot | None = None
    generation: int = 0
    drift_log: list[dict] = field(default_factory=list)

    def assert_identity(self, current: AttestationSnapshot) -> int:
        """Return the generation counter if the identity may be asserted to the
        federated peer; raise FederatedIdentityDriftError otherwise.

        Invariant: the current selector set must be a SUPERSET of the admitted
        subset (every agreed selector still present) AND unchanged from
        last_good (no widening, no sibling sharing the ID).
        """
        if current.spiffe_id != self.agreement.admitted_spiffe_id:
            raise FederatedIdentityDriftError(
                f"SPIFFE ID {current.spiffe_id!r} does not match admitted "
                f"{self.agreement.admitted_spiffe_id!r}"
            )

        missing = self.agreement.admitted_selectors - current.selectors
        if missing:
            self._record(current, reason="admitted_selector_missing", delta=sorted(missing))
            raise FederatedIdentityDriftError(
                f"selectors required by {self.agreement.peer_org} are absent: "
                f"{sorted(missing)}"
            )

        if self.last_good is not None:
            added = current.selectors - self.last_good.selectors
            removed = self.last_good.selectors - current.selectors
            if added or removed:
                # Any change to the selector set is a re-attestation, not a
                # renewal. Growth means the ID is now shared with a sibling
                # workload; shrink means this workload lost a property.
                self._record(
                    current,
                    reason="selector_set_changed",
                    delta={"added": sorted(added), "removed": sorted(removed)},
                )
                raise FederatedIdentityDriftError(
                    "re-attestation changed the selector set behind "
                    f"{current.spiffe_id!r}; refusing to present to "
                    f"{self.agreement.peer_org}. added={sorted(added)} "
                    f"removed={sorted(removed)}"
                )

            if current.svid_serial != self.last_good.svid_serial:
                # Same selectors, new cert => legitimate renewal.
                self.generation += 1

        self.last_good = current
        return self.generation

    def _record(self, current: AttestationSnapshot, *, reason: str, delta) -> None:
        self.drift_log.append(
            {
                "at": datetime.now(timezone.utc).isoformat(),
                "reason": reason,
                "peer": self.agreement.peer_org,
                "spiffe_id": current.spiffe_id,
                "svid_serial": current.svid_serial,
                "delta": delta,
            }
        )
