# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-warrant-scope-narrowing-forgery-at-the-second-hop-of-an-aaif-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-warrant-scope-narrowing-forgery-at-the-second-hop-of-an-aaif-chain.warrant.json
# Markdown SHA-256:   69e68d92fe09371f3531f22eafaf87937131cc357b2ca61aff81e43745ef86f8
# Code AST SHA-256:   f94da69e3a9709a22b22be358536c678b831a20b6fdb07ef5b933c05f905539d
# Verified Classes:   DelegationLogMismatch, Credential
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class DelegationLogMismatch(RuntimeError):
    """Raised when a credential's issuer is not the authorized attenuator in its parent's delegation log."""
    pass


@dataclass
class Credential:
    cred_id: str
    issuer: str
    parent_hash: str | None
    scope: frozenset[str]
    delegation_log: dict[str, str] = field(default_factory=dict)
    signature: str = ""

    def content_hash(self) -> str:
        payload = f"{self.cred_id}|{self.issuer}|{self.parent_hash}|{sorted(self.scope)}"
        return hashlib.sha256(payload.encode()).hexdigest()


def verify_chain(presented: Credential, parent: Credential) -> None:
    # Signature validity is assumed checked upstream; this function enforces
    # the delegation-log binding that signatures alone cannot.
    if presented.parent_hash != parent.content_hash():
        raise DelegationLogMismatch(
            f"credential {presented.cred_id} does not commit to parent {parent.cred_id}"
        )
    if presented.scope - parent.scope:
        raise DelegationLogMismatch(
            f"scope escalation: {presented.scope - parent.scope} not held by parent"
        )
    authorized = parent.delegation_log.get(presented.cred_id)
    if authorized is None:
        raise DelegationLogMismatch(
            f"credential {presented.cred_id} is unanchored: no delegation-log entry in {parent.cred_id}"
        )
    if authorized != presented.issuer:
        raise DelegationLogMismatch(
            f"credential {presented.cred_id} presented by {presented.issuer}, "
            f"but {parent.cred_id} authorizes {authorized} to attenuate"
        )


def admit_second_hop(presented: Credential, parent: Credential) -> str:
    verify_chain(presented, parent)
    return f"admitted {presented.issuer} with scope {sorted(presented.scope)}"


# Reproduction of the observed failure: A2 rewrites scope, re-signs with its own
# key, and points at the same parent C0 that A1's intended C1 pointed at.
c0 = Credential(
    cred_id="C0", issuer="P", parent_hash=None,
    scope=frozenset({"read:orders", "write:orders", "refund:orders"}),
    delegation_log={"C1": "A1"},
)
c1_forged = Credential(
    cred_id="C1", issuer="A2",
    parent_hash=c0.content_hash(),
    scope=frozenset({"read:orders", "write:orders", "refund:orders"}),
)
try:
    admit_second_hop(c1_forged, c0)
except DelegationLogMismatch as e:
    print(f"rejected: {e}")
    # rejected: credential C1 presented by A2, but C0 authorizes A1 to attenuate
