# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-capability-grant-whose-audit-warrant-chain-has-been-re-derived-under-a-peer-s-local-policy-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-capability-grant-whose-audit-warrant-chain-has-been-re-derived-under-a-peer-s-local-policy-epoch.warrant.json
# Markdown SHA-256:   9297fab38f3c874b90fb0db42b4cbdee740fc334d1418b839a883f34a86b11b4
# Code AST SHA-256:   6f034720dc844004eb6001a1dee17f3d2fe24f2247c16316534d0a6a01094395
# Verified Classes:   WarrantContinuityViolation, WarrantLink, WarrantChain
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from datetime import datetime


class WarrantContinuityViolation(RuntimeError):
    """Raised when a re-derived warrant chain cannot be proven continuous
    with the grantee's cached original issuance record."""


@dataclass(frozen=True)
class WarrantLink:
    signer: str
    derived_at: datetime
    scope: str
    namespace_version: str
    signature: bytes


@dataclass(frozen=True)
class WarrantChain:
    capability_id: str
    issued_at: datetime
    policy_epoch: str
    links: tuple[WarrantLink, ...]

    def digest(self) -> str:
        h = hashlib.sha256()
        h.update(self.capability_id.encode())
        h.update(self.policy_epoch.encode())
        for link in self.links:
            h.update(link.signer.encode())
            h.update(link.derived_at.isoformat().encode())
            h.update(link.scope.encode())
            h.update(link.namespace_version.encode())
        return h.hexdigest()


def verify_signatures(chain: WarrantChain, trusted_keys: dict[str, bytes]) -> bool:
    # Placeholder for real signature verification; returns True if every
    # link's signer is in the trusted set and the signature is well-formed.
    return all(link.signer in trusted_keys and link.signature for link in chain.links)


def resolve_scope(scope: str, namespace_version: str) -> frozenset[str]:
    # Namespace-versioned resolution. Unknown versions must NOT fall back to
    # a legacy literal -- that fallback is the exact bug that let the breach
    # through. Unknown versions raise instead.
    table = {
        ("telemetry_aggregate:v2", "e17"): frozenset({"tenant_a"}),
        ("telemetry_aggregate:v2", "e18"): frozenset({"tenant_a", "tenant_b"}),
    }
    key = (scope, namespace_version)
    if key not in table:
        raise WarrantContinuityViolation(
            f"scope {scope!r} has no resolution under namespace version "
            f"{namespace_version!r}; refusing to guess"
        )
    return table[key]


def accept_refreshed_grant(
    cached: WarrantChain,
    presented: WarrantChain,
    trusted_keys: dict[str, bytes],
    continuity_attestation: dict | None,
) -> None:
    if presented.capability_id != cached.capability_id:
        raise WarrantContinuityViolation(
            f"capability id mismatch: cached {cached.capability_id!r} "
            f"vs presented {presented.capability_id!r}"
        )

    if not verify_signatures(presented, trusted_keys):
        raise WarrantContinuityViolation(
            "presented warrant chain has an invalid signature; reject outright"
        )

    # Detect re-derivation: any link whose derived_at postdates the
    # capability's original issuance is a re-derivation, not a continuation.
    rederived = [
        link for link in presented.links
        if link.derived_at > cached.issued_at
    ]

    if not rederived:
        # No re-derivation. Benign refresh (e.g. key rotation, same epoch).
        return

    # Re-derivation detected. Require an epoch-continuity attestation that
    # explicitly authorizes the transition from cached.policy_epoch to
    # presented.policy_epoch for this capability class.
    if continuity_attestation is None:
        raise WarrantContinuityViolation(
            f"warrant chain re-derived under epoch {presented.policy_epoch!r} "
            f"(cached epoch {cached.policy_epoch!r}) with no continuity "
            f"attestation; refusing to treat re-derivation as continuation"
        )

    attested = (
        continuity_attestation.get("from_epoch") == cached.policy_epoch
        and continuity_attestation.get("to_epoch") == presented.policy_epoch
        and continuity_attestation.get("capability_id") == presented.capability_id
    )
    if not attested:
        raise WarrantContinuityViolation(
            "continuity attestation does not cover this epoch transition "
            "for this capability"
        )

    # Even with an attestation, scope must resolve identically under BOTH
    # namespace versions. A scope that widens across the epoch is a
    # re-authorization, not a continuation, and must go through a fresh
    # issuance handshake.
    cached_scope = resolve_scope(
        cached.links[-1].scope, cached.links[-1].namespace_version
    )
    presented_scope = resolve_scope(
        presented.links[-1].scope, presented.links[-1].namespace_version
    )
    if presented_scope != cached_scope:
        raise WarrantContinuityViolation(
            f"scope changed across re-derivation: cached resolves to "
            f"{sorted(cached_scope)}, presented resolves to "
            f"{sorted(presented_scope)}; require fresh issuance"
        )

    # Re-derivation is attested and scope-preserving: accept, but flag for
    # re-issuance at next opportunity.
    return
