# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-delegated-capability-attenuation-breach-across-a-cross-org-federation-trust-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-delegated-capability-attenuation-breach-across-a-cross-org-federation-trust-boundary.warrant.json
# Markdown SHA-256:   8e1462972f768f057631868d1ad94f8d33cfa1e84659af78720c932b199290ef
# Code AST SHA-256:   ea31d683171bbd8d56a2677d60a16056cf5b05fa036ede675ded00157427e61a
# Verified Classes:   AttenuationBreachError, RevocationWindowInvertedError, CapabilityToken, PolicyRoot
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import hmac
import time
from dataclasses import dataclass, field
from typing import Optional


class AttenuationBreachError(RuntimeError):
    """Raised when a delegated capability token's policy binding is not
    a member of the delegator's current published policy root, indicating
    a compositional attenuation breach across a federation trust boundary."""
    pass


class RevocationWindowInvertedError(RuntimeError):
    """Raised when token_lifetime exceeds revocation_ttl, which allows a
    revoked token to remain valid at the delegatee for the gap duration."""
    pass


@dataclass
class CapabilityToken:
    token_id: str
    delegator_org: str
    delegatee_org: str
    capability: str
    constraints: dict
    policy_hash: str          # hash of delegation policy at mint time
    minted_at: float
    expires_at: float
    signature: str = ""


@dataclass
class PolicyRoot:
    """Published Merkle root of the delegator's current delegation policy set."""
    root: str
    published_at: float
    members: set = field(default_factory=set)  # leaf hashes


def mint_token(delegator_policy_hash: str, delegatee_org: str,
               capability: str, constraints: dict, ttl_s: float,
               signing_key: bytes) -> CapabilityToken:
    now = time.time()
    tok = CapabilityToken(
        token_id=hashlib.sha256(f"{now}{delegatee_org}{capability}".encode()).hexdigest()[:16],
        delegator_org="orgA",
        delegatee_org=delegatee_org,
        capability=capability,
        constraints=constraints,
        policy_hash=delegator_policy_hash,
        minted_at=now,
        expires_at=now + ttl_s,
    )
    payload = f"{tok.token_id}|{tok.policy_hash}|{tok.expires_at}".encode()
    tok.signature = hmac.new(signing_key, payload, hashlib.sha256).hexdigest()
    return tok


def verify_at_invocation(token: CapabilityToken, policy_root: PolicyRoot,
                         revocation_ttl_s: float, signing_key: bytes) -> None:
    # 1. Signature integrity.
    payload = f"{token.token_id}|{token.policy_hash}|{token.expires_at}".encode()
    expected = hmac.new(signing_key, payload, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, token.signature):
        raise AttenuationBreachError(f"token {token.token_id}: signature invalid")

    # 2. Expiry.
    if time.time() > token.expires_at:
        raise AttenuationBreachError(f"token {token.token_id}: expired")

    # 3. Revocation window invariant: token lifetime must not exceed revocation TTL.
    token_lifetime = token.expires_at - token.minted_at
    if token_lifetime > revocation_ttl_s:
        raise RevocationWindowInvertedError(
            f"token {token.token_id}: lifetime {token_lifetime:.0f}s exceeds "
            f"revocation_ttl {revocation_ttl_s:.0f}s; revoked tokens may remain valid"
        )

    # 4. Policy-binding membership: the token's mint-time policy hash must be a
    #    member of the delegator's CURRENT published policy root. If the delegator's
    #    policy changed since mint, the hash is absent and the token is rejected.
    #    This is the compositional attenuation guardrail: it closes the breach
    #    window without requiring the delegatee to query the delegator's internals.
    if token.policy_hash not in policy_root.members:
        raise AttenuationBreachError(
            f"token {token.token_id}: policy_hash {token.policy_hash[:12]}... "
            f"not in current policy root {policy_root.root[:12]}...; "
            f"delegation policy changed since mint — compositional attenuation breach"
        )


def delegatee_invoke(token: CapabilityToken, policy_root: PolicyRoot,
                     revocation_ttl_s: float, signing_key: bytes) -> str:
    verify_at_invocation(token, policy_root, revocation_ttl_s, signing_key)
    return f"effect:{token.capability} on {token.constraints}"


# --- Demonstration of the breach and the guardrail ---
if __name__ == "__main__":
    key = b"federation-shared-secret"
    old_policy_hash = hashlib.sha256(b"policy-v1").hexdigest()
    new_policy_hash = hashlib.sha256(b"policy-v2-with-cross-org-invariant").hexdigest()

    # Delegator minted under v1 (stale checkpoint), then policy updated to v2.
    tok = mint_token(old_policy_hash, "orgB", "write:records",
                     {"data_class": "internal", "region": "eu"}, ttl_s=3600,
                     signing_key=key)

    # Current published policy root contains only v2 leaves.
    current_root = PolicyRoot(root=hashlib.sha256(b"root-v2").hexdigest(),
                              published_at=time.time(),
                              members={new_policy_hash})

    try:
        delegatee_invoke(tok, current_root, revocation_ttl_s=7200, signing_key=key)
    except AttenuationBreachError as e:
        print(f"BLOCKED: {e}")

    # Inverted revocation window also blocked.
    long_tok = mint_token(new_policy_hash, "orgB", "write:records",
                          {"data_class": "public"}, ttl_s=86400, signing_key=key)
    try:
        delegatee_invoke(long_tok, current_root, revocation_ttl_s=14400, signing_key=key)
    except RevocationWindowInvertedError as e:
        print(f"BLOCKED: {e}")
