# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-quarantine-a-policy-widening-drift-when-a-federated-peer-renegotiates-capability-scopes-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-quarantine-a-policy-widening-drift-when-a-federated-peer-renegotiates-capability-scopes-mid-session.warrant.json
# Markdown SHA-256:   adfd82cc7fbeb55f922cd385bb95d2718cd6cf0bb5581104c19eef5140edc7ca
# Code AST SHA-256:   533537885874b0f5904e3e99de36ab0315ea23eba0fcf2aa582e793bfdf0fe1e
# Verified Classes:   CapabilityDriftError, ConsentedGrant, GrantCache
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import hmac
from dataclasses import dataclass, field
from typing import FrozenSet


class CapabilityDriftError(RuntimeError):
    """Raised when a re-asserted grant preserves grant_id but changes effective scope."""


@dataclass(frozen=True)
class ConsentedGrant:
    grant_id: str
    issuer: str
    subject: str
    scopes: FrozenSet[str]
    scope_hash: str  # committed at consent time, stored out-of-band from the token

    @staticmethod
    def commit(grant_id: str, issuer: str, subject: str, scopes: FrozenSet[str]) -> "ConsentedGrant":
        canonical = "|".join(sorted(scopes)).encode()
        digest = hashlib.sha256(canonical).hexdigest()
        return ConsentedGrant(grant_id, issuer, subject, frozenset(scopes), digest)


@dataclass
class GrantCache:
    # Keyed on grant_id, but the *consented* hash lives in a separate durable store
    # so a re-asserted token cannot overwrite the value it is checked against.
    consented: dict[str, ConsentedGrant] = field(default_factory=dict)

    def record_consent(self, grant: ConsentedGrant) -> None:
        self.consented[grant.grant_id] = grant

    def accept_reassertion(
        self,
        grant_id: str,
        issuer: str,
        subject: str,
        asserted_scopes: FrozenSet[str],
        signature_valid: bool,
    ) -> ConsentedGrant:
        if not signature_valid:
            raise CapabilityDriftError(f"grant {grant_id}: signature chain invalid")

        prior = self.consented.get(grant_id)
        if prior is None:
            raise CapabilityDriftError(f"grant {grant_id}: no local consent on record")

        if prior.issuer != issuer or prior.subject != subject:
            raise CapabilityDriftError(
                f"grant {grant_id}: issuer/subject changed "
                f"({prior.issuer}->{issuer}, {prior.subject}->{subject})"
            )

        canonical = "|".join(sorted(asserted_scopes)).encode()
        asserted_hash = hashlib.sha256(canonical).hexdigest()

        if not hmac.compare_digest(prior.scope_hash, asserted_hash):
            widened = asserted_scopes - prior.scopes
            narrowed = prior.scopes - asserted_scopes
            raise CapabilityDriftError(
                f"grant {grant_id}: scope_hash drift "
                f"(widened={sorted(widened)}, narrowed={sorted(narrowed)}); "
                f"quarantine and renegotiate from local policy"
            )

        # Refresh path: identical scope set, same identity, still consented.
        return prior


def handle_peer_reassertion(
    cache: GrantCache,
    grant_id: str,
    issuer: str,
    subject: str,
    asserted_scopes: FrozenSet[str],
    signature_valid: bool,
) -> ConsentedGrant:
    try:
        return cache.accept_reassertion(
            grant_id, issuer, subject, asserted_scopes, signature_valid
        )
    except CapabilityDriftError:
        # Fail closed: suspend calls against this grant, do not persist any
        # response produced under it into semantic memory.
        raise
