# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a-delegated-credential-chain-that-validates-end-to-end-but-authorizes-the-wrong-principal-after-an-intermediate-re-deleg.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a-delegated-credential-chain-that-validates-end-to-end-but-authorizes-the-wrong-principal-after-an-intermediate-re-deleg.warrant.json
# Markdown SHA-256:   d86426ac02be41a966b2972e567a20891be8836c54310adbff5c2a4349031e04
# Code AST SHA-256:   05a3f789ed1048c04a861951fd8de8b8a3856dd4e7b9ef47884e7251bdcf77c6
# Verified Classes:   DelegationLineageError, WarrantLink
# Defensive Guards:   9 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class DelegationLineageError(RuntimeError):
    """Raised when a delegated credential chain validates cryptographically
    but its principal lineage is discontinuous or unattested."""
    pass


@dataclass(frozen=True)
class WarrantLink:
    issuer: str
    subject: str
    tenant: str
    scope: frozenset
    may_delegate: bool
    subject_attestation_hash: Optional[str]  # hex digest or None
    signature_valid: bool


def authorize_request(
    chain: list[WarrantLink],
    request_scope: frozenset,
    presented_attestation_digest: str,
    resource_server: str,
) -> str:
    # Step 1: cryptographic and scope validation (necessary, not sufficient).
    for i, link in enumerate(chain):
        if not link.signature_valid:
            raise DelegationLineageError(f"link {i}: signature invalid")
        if i > 0 and chain[i - 1].subject != link.issuer:
            raise DelegationLineageError(f"link {i}: issuer/subject discontinuity")
        if i > 0 and not chain[i - 1].may_delegate:
            raise DelegationLineageError(f"link {i}: prior link lacks may_delegate")
        if i > 0 and not chain[i - 1].scope.issuperset(link.scope):
            raise DelegationLineageError(f"link {i}: scope not attenuated")
        if link.subject_attestation_hash is None:
            # Absence of attestation binding is a hard reject, not a warning.
            raise DelegationLineageError(
                f"link {i}: missing subject_attestation_hash; "
                f"principal lineage unverifiable"
            )

    if not chain[-1].scope.issuperset(request_scope):
        raise DelegationLineageError("requested scope exceeds terminal scope")

    # Step 2: principal lineage reconstruction (the invariant that catches
    # stale-template re-delegation across tenants).
    terminal = chain[-1]
    if terminal.subject_attestation_hash != presented_attestation_digest:
        raise DelegationLineageError(
            f"terminal attestation mismatch: warrant asserts "
            f"{terminal.subject_attestation_hash}, request presented "
            f"{presented_attestation_digest}; chain validates but "
            f"authorizes the wrong principal"
        )

    # Step 3: tenant continuity across the lineage. The terminal tenant must
    # equal the tenant under which the terminal subject was attested.
    tenants = {link.tenant for link in chain}
    if len(tenants) != 1:
        raise DelegationLineageError(
            f"lineage tenant discontinuity: {sorted(tenants)}; "
            f"re-delegation crossed principal boundaries"
        )

    return terminal.tenant


def verify_attestation_digest(attestation_blob: bytes, expected: str) -> str:
    digest = hashlib.sha256(attestation_blob).hexdigest()
    if digest != expected:
        raise DelegationLineageError(
            "attestation digest does not match warrant claim"
        )
    return digest
