# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-cross-org-attestation-replay-from-silently-widening-a-federated-agent-s-data-boundary-grant.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-cross-org-attestation-replay-from-silently-widening-a-federated-agent-s-data-boundary-grant.warrant.json
# Markdown SHA-256:   5b4817dadf7178def089191db3575ec28dcca14641b17c51a7a0d5a3f1ba1a77
# Code AST SHA-256:   2bbfdbc85f8ab63c41065186184ea6699cbcef14adf5c6a79a1c8ab19e5783aa
# Verified Classes:   StaleAttestationError, Warrant, PolicySnapshot
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import FrozenSet


class StaleAttestationError(RuntimeError):
    """Raised when a warrant's mint-time policy snapshot cannot be soundly
    reconciled with the receiving gateway's current policy snapshot."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    scope_fields: FrozenSet[str]
    policy_snapshot: str          # snapshot id under which scope was minted
    issued_at: float
    expires_at: float
    signature_ok: bool = True


@dataclass(frozen=True)
class PolicySnapshot:
    snapshot_id: str
    allowed_fields: FrozenSet[str]
    sensitive_fields: FrozenSet[str]


def resolve_grant(
    warrant: Warrant,
    current: PolicySnapshot,
    mint_snapshot: PolicySnapshot,
    now: float,
    sensitive_staleness_s: float = 900.0,
) -> FrozenSet[str]:
    # 1. Cryptographic and temporal validity.
    if not warrant.signature_ok:
        raise StaleAttestationError("warrant signature invalid")
    if now >= warrant.expires_at:
        raise StaleAttestationError(f"warrant expired at {warrant.expires_at}")

    # 2. Snapshot binding must be present and consistent.
    if warrant.policy_snapshot != mint_snapshot.snapshot_id:
        raise StaleAttestationError(
            f"warrant claims snapshot {warrant.policy_snapshot} but "
            f"mint record is {mint_snapshot.snapshot_id}"
        )

    # 3. Intersect mint-time scope with CURRENT policy, never trust the
    #    warrant string as an authoritative allowlist.
    effective = warrant.scope_fields & current.allowed_fields

    # 4. For sensitive fields, stale mint snapshots are rejected outright
    #    rather than narrowed, to avoid livelock-vs-leak ambiguity.
    stale = warrant.policy_snapshot != current.snapshot_id
    age = now - warrant.issued_at
    touched_sensitive = bool(warrant.scope_fields & current.sensitive_fields)
    if stale and touched_sensitive and age > sensitive_staleness_s:
        raise StaleAttestationError(
            f"warrant {warrant.policy_snapshot} is stale vs "
            f"{current.snapshot_id} and touches sensitive fields "
            f"(age={age:.0f}s > {sensitive_staleness_s:.0f}s); re-attest required"
        )
    if stale and touched_sensitive:
        # Narrow aggressively: sensitive fields from a superseded snapshot
        # are never honored, even within the staleness window.
        effective = effective - current.sensitive_fields

    return effective
