# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-an-aaif-delegation-chain-silently-widen-privilege-when-a-credential-is-re-signed-rather-than-re-issued.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-an-aaif-delegation-chain-silently-widen-privilege-when-a-credential-is-re-signed-rather-than-re-issued.warrant.json
# Markdown SHA-256:   2f10bf1e53d827de17724e386ac932a7d70e5d114a4ade20dea3e7bd98903711
# Code AST SHA-256:   15e2c429ab6730591e5899b88f40329d9c17f2742f4b9ed5439221d6f960f6c4
# Verified Classes:   DelegationChainAuthorityError, Credential
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class DelegationChainAuthorityError(RuntimeError):
    """Raised when a chain hop's signer is not the subject of its parent credential."""


@dataclass(frozen=True)
class Credential:
    credential_id: str
    issuer: str
    subject: str
    parent_id: str | None
    scope: frozenset[str]
    delegation_depth: int
    signature: bytes

    def body_hash(self) -> str:
        h = hashlib.sha256()
        for field in (self.credential_id, self.issuer, self.subject,
                      self.parent_id or "", ",".join(sorted(self.scope)),
                      str(self.delegation_depth)):
            h.update(field.encode())
        return h.hexdigest()


def verify_chain(leaf: Credential, lookup) -> frozenset[str]:
    """Reconstruct the effective scope. `lookup(credential_id)` returns the
    signed parent credential from the issuer, never from the child's claims."""
    effective = set(leaf.scope)
    cursor = leaf
    depth = 0
    while cursor.parent_id is not None:
        parent = lookup(cursor.parent_id)
        if parent is None:
            raise DelegationChainAuthorityError(
                f"parent {cursor.parent_id} unresolvable for {cursor.credential_id}"
            )
        if cursor.issuer != parent.subject:
            raise DelegationChainAuthorityError(
                f"re-sign detected: {cursor.credential_id} signed by {cursor.issuer} "
                f"but parent {parent.credential_id} subject is {parent.subject}"
            )
        if not effective.issubset(parent.scope):
            raise DelegationChainAuthorityError(
                f"scope widening at {cursor.credential_id}: "
                f"{effective - parent.scope} not granted by {parent.credential_id}"
            )
        effective &= parent.scope
        cursor = parent
        depth += 1
        if depth > cursor.delegation_depth:
            raise DelegationChainAuthorityError(
                f"depth counter inconsistent at {cursor.credential_id}"
            )
    return frozenset(effective)
