# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-capability-warrant-whose-holder-did-resolves-to-a-different-verification-method-than-the-one-that-signed-the-p.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-capability-warrant-whose-holder-did-resolves-to-a-different-verification-method-than-the-one-that-signed-the-p.warrant.json
# Markdown SHA-256:   0765d911edab5346d642be01a8d8aa1816da0cc786826bde9d6396b88b776474
# Code AST SHA-256:   772352960015dfb1c0ff44cf4bf505c5f40456334e001e8765ea8a8c47c3bbc9
# Verified Classes:   DelegationChainViolation, Grant, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class DelegationChainViolation(RuntimeError):
    """Raised when a delegated warrant fails a binding or scope invariant."""
    pass


@dataclass
class Grant:
    issuer: str                      # DID of the grantor
    subject: str                     # DID of the delegate
    # Inline, issuance-time authorized verification methods for the subject.
    # MUST be present; absence is a hard reject, never a cue to re-resolve.
    authorized_vms: Optional[frozenset] = None
    scope: dict = field(default_factory=dict)
    iat: int = 0


@dataclass
class Warrant:
    delegating_did: str              # DID that signed this warrant
    signer_vm: str                   # full DID URL, e.g. did:agent:alpha#key-2
    holder_did: str                  # DID the warrant is issued to
    scope: dict = field(default_factory=dict)


def _scope_subset(child: dict, parent: dict) -> bool:
    """Stepwise subset: every key in child must be present in parent, and
    list-valued ops must be a subset. Missing parent key => violation."""
    for k, v in child.items():
        if k not in parent:
            return False
        pv = parent[k]
        if isinstance(v, list):
            if not isinstance(pv, list) or not set(v).issubset(set(pv)):
                return False
        elif isinstance(v, dict):
            if not isinstance(pv, dict) or not _scope_subset(v, pv):
                return False
        elif v != pv:
            return False
    return True


def verify_chain(grants: list, warrants: list, presenter_did: str) -> None:
    """grants[i] authorizes warrants[i]; warrants[i].holder should be
    grants[i+1].subject. Raises DelegationChainViolation on first breach."""
    if len(grants) != len(warrants):
        raise DelegationChainViolation(
            f"chain arity mismatch: {len(grants)} grants vs {len(warrants)} warrants"
        )

    for i, (g, w) in enumerate(zip(grants, warrants)):
        # Invariant 1: parent grant must carry inline VM set. Re-resolution
        # at verification time is the substitution vector; refuse it.
        if g.authorized_vms is None:
            raise DelegationChainViolation(
                f"hop {i}: parent grant from {g.issuer} carries no inline "
                f"authorized_vms; cannot bind signer without re-resolving DID"
            )
        # Invariant 2: signer of this hop must be inline-authorized by parent.
        if w.signer_vm not in g.authorized_vms:
            raise DelegationChainViolation(
                f"hop {i}: signer {w.signer_vm} not in issuance-time VM set "
                f"{sorted(g.authorized_vms)} authorized by {g.issuer}; "
                f"possible post-issuance key insertion (binding substitution)"
            )
        # Invariant 3: delegating DID must match the grant's subject.
        if w.delegating_did != g.subject:
            raise DelegationChainViolation(
                f"hop {i}: warrant signed by {w.delegating_did} but grant "
                f"authorized {g.subject}"
            )
        # Invariant 4: stepwise scope subset, not root-only subset.
        if not _scope_subset(w.scope, g.scope):
            raise DelegationChainViolation(
                f"hop {i}: scope {w.scope} not a subset of parent scope {g.scope}"
            )

    # Invariant 5: chain must terminate at the authenticated presenter.
    terminal_holder = warrants[-1].holder_did
    if terminal_holder != presenter_did:
        raise DelegationChainViolation(
            f"terminal holder {terminal_holder} != presenter {presenter_did}; "
            f"chain replay by non-holder"
        )
