# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-replays-an-attenuated-capability-token-across-a-delegation-chain-and-the-provenance-receipt-diverges-from-the-live-warra.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-replays-an-attenuated-capability-token-across-a-delegation-chain-and-the-provenance-receipt-diverges-from-the-live-warra.warrant.json
# Markdown SHA-256:   24e62056471f56e65e607855c0d0eb756939d5e61e2dd9f6aefcda48a7c0287a
# Code AST SHA-256:   bc454e0fc0d5cc1839d867895859cb3201287808007c743307ac01e13a9c20a1
# Verified Classes:   ProvenanceDivergenceError, ScopeEscalationError, CapabilityToken, ProvenanceReceipt
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Optional


class ProvenanceDivergenceError(RuntimeError):
    """Raised when a presented capability token does not match the
    provenance receipt that is supposed to warrant it."""
    pass


class ScopeEscalationError(ProvenanceDivergenceError):
    """Raised when the presented token's scope is not a subset of the
    receipt's declared scope — a potential privilege escalation."""
    pass


@dataclass
class CapabilityToken:
    issuer: str
    subject: str
    scope: frozenset
    audience: str
    canon_scheme: str = "jcs-rfc8785-v1"

    def canonical_bytes(self) -> bytes:
        # Pinned canonicalization: sorted keys, no whitespace, stable types.
        payload = {
            "issuer": self.issuer,
            "subject": self.subject,
            "scope": sorted(self.scope),
            "audience": self.audience,
            "canon_scheme": self.canon_scheme,
        }
        return json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()

    def digest(self) -> str:
        return hashlib.sha256(self.canonical_bytes()).hexdigest()


@dataclass
class ProvenanceReceipt:
    issuer: str
    subject: str
    declared_scope: frozenset
    committed_token_hash: str          # MUST be inside the signed envelope
    parent_receipt_id: Optional[str]
    signature: str = ""                # covers committed_token_hash

    def signed_envelope(self) -> bytes:
        payload = {
            "issuer": self.issuer,
            "subject": self.subject,
            "declared_scope": sorted(self.declared_scope),
            "committed_token_hash": self.committed_token_hash,
            "parent_receipt_id": self.parent_receipt_id,
        }
        return json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()


def verify_hop(
    presented: CapabilityToken,
    receipt: ProvenanceReceipt,
    expected_audience: str,
) -> None:
    """Verify one hop of a delegation chain.

    Invariant enforced:
      - presented.scope must be a subset of receipt.declared_scope
      - presented.digest() must equal receipt.committed_token_hash
      - expected_audience must match the token's audience binding
    Any divergence halts the chain at THIS hop, not downstream.
    """
    if presented.audience != expected_audience:
        raise ProvenanceDivergenceError(
            f"audience mismatch: token bound to {presented.audience!r}, "
            f"presented to {expected_audience!r}"
        )

    # Escalation check first: a wider scope is never a benign divergence.
    wider = presented.scope - receipt.declared_scope
    if wider:
        raise ScopeEscalationError(
            f"scope escalation at hop issued by {receipt.issuer!r}: "
            f"token claims {sorted(wider)} outside declared scope "
            f"{sorted(receipt.declared_scope)}"
        )

    # Hash divergence: consistent with lawful attenuation but unverifiable.
    actual = presented.digest()
    if actual != receipt.committed_token_hash:
        raise ProvenanceDivergenceError(
            f"receipt/warrant divergence at hop issued by {receipt.issuer!r}: "
            f"receipt commits {receipt.committed_token_hash[:12]}..., "
            f"presented token hashes to {actual[:12]}... "
            f"(scope is subset, so likely un-recommitted attenuation — "
            f"require re-signed receipt before forwarding)"
        )


def attenuate_and_recommit(
    parent_token: CapabilityToken,
    parent_receipt: ProvenanceReceipt,
    new_scope: frozenset,
    new_subject: str,
    new_audience: str,
    signer,
) -> tuple:
    """Atomic attenuation: narrow the token AND re-commit its hash to a
    fresh receipt in the same operation. This is the only safe way to
    forward authority across a hop."""
    if not new_scope <= parent_token.scope:
        raise ScopeEscalationError(
            f"attenuation widened scope: {sorted(new_scope)} not subset of "
            f"{sorted(parent_token.scope)}"
        )
    if not new_scope <= parent_receipt.declared_scope:
        raise ProvenanceDivergenceError(
            "attenuation target exceeds parent receipt's declared scope"
        )

    child = CapabilityToken(
        issuer=parent_token.subject,   # child issuer is the attenuator
        subject=new_subject,
        scope=new_scope,
        audience=new_audience,
    )
    child_receipt = ProvenanceReceipt(
        issuer=parent_token.subject,
        subject=new_subject,
        declared_scope=new_scope,
        committed_token_hash=child.digest(),   # committed in same op
        parent_receipt_id=f"{parent_receipt.issuer}:{parent_receipt.subject}",
    )
    child_receipt.signature = signer(child_receipt.signed_envelope())
    return child, child_receipt
