# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-delegated-capability-token-whose-scope-was-narrowed-by-an-intermediary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-delegated-capability-token-whose-scope-was-narrowed-by-an-intermediary.warrant.json
# Markdown SHA-256:   18473a08c47c3643aa89b6aa0ec8c7da4b422f22f37d59f4b2c93f7b402e0f90
# Code AST SHA-256:   10e1674198b55178de2231a8032ad3d2b134d8f31c170510cba9e9db6698018e
# Verified Classes:   IllegitimateAttenuationError, CapabilityToken
# Defensive Guards:   9 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class IllegitimateAttenuationError(RuntimeError):
    """Raised when a narrowed token is not a legal descendant of its parent."""


@dataclass(frozen=True)
class CapabilityToken:
    token_id: str
    tools: FrozenSet[str]
    resource_tags: FrozenSet[str]
    delegation_depth: int
    not_before: int          # absolute epoch seconds
    expiry: int              # absolute epoch seconds
    attenuated_by: str       # identity that minted this token
    parent_id: str | None = None
    log_present: bool = True


def verify_attenuation(child: CapabilityToken, parent: CapabilityToken) -> None:
    """Enforce the full delegation lattice, not just tool-scope subset."""
    if child.parent_id != parent.token_id:
        raise IllegitimateAttenuationError(
            f"token {child.token_id} claims parent {child.parent_id!r} "
            f"but was checked against {parent.token_id!r}"
        )

    # 1. Tool monotonicity — the check everyone does.
    if not child.tools <= parent.tools:
        raise IllegitimateAttenuationError(
            f"tool escalation: {child.tools - parent.tools} not in parent grant"
        )

    # 2. Resource monotonicity — the check that catches tag bleed.
    if not child.resource_tags <= parent.resource_tags:
        raise IllegitimateAttenuationError(
            f"resource escalation: {child.resource_tags - parent.resource_tags} "
            f"not derivable from parent grant"
        )

    # 3. Depth monotonicity — a hop MUST consume a hop.
    if child.delegation_depth > parent.delegation_depth - 1:
        raise IllegitimateAttenuationError(
            f"depth not decremented: child={child.delegation_depth} "
            f"parent={parent.delegation_depth} (laundering path)"
        )

    # 4. Temporal monotonicity — compare absolute bounds, not remaining life.
    if child.not_before < parent.not_before or child.expiry > parent.expiry:
        raise IllegitimateAttenuationError(
            f"temporal widening: child window [{child.not_before},{child.expiry}] "
            f"not within parent [{parent.not_before},{parent.expiry}]"
        )

    # 5. Derivability — attenuation must be logged at the parent.
    if not child.log_present:
        raise IllegitimateAttenuationError(
            f"attenuation of {child.token_id} by {child.attenuated_by!r} "
            f"absent from parent delegation log (replay or forgery suspected)"
        )


def authorize_invocation(
    presented: CapabilityToken,
    parent: CapabilityToken | None,
    tool: str,
    resource: str,
    now: int,
) -> bool:
    """Gate a tool call behind lattice verification before scope check."""
    if not (presented.not_before <= now <= presented.expiry):
        raise IllegitimateAttenuationError(
            f"token {presented.token_id} outside validity window at t={now}"
        )
    if parent is not None:
        verify_attenuation(presented, parent)
    if tool not in presented.tools:
        raise IllegitimateAttenuationError(
            f"tool {tool!r} not in presented scope {presented.tools}"
        )
    if resource not in presented.resource_tags:
        raise IllegitimateAttenuationError(
            f"resource {resource!r} not in presented scope {presented.resource_tags}"
        )
    return True


if __name__ == "__main__":
    root = CapabilityToken(
        token_id="T_root",
        tools=frozenset({"fs.read", "fs.write", "net.fetch"}),
        resource_tags=frozenset({"/proj/a"}),
        delegation_depth=2,
        not_before=1_000,
        expiry=4_600,
        attenuated_by="orchestrator",
    )
    # The observed illegitimate child: narrower tools, wider resources,
    # undecremented depth, preserved expiry.
    child = CapabilityToken(
        token_id="T_child",
        tools=frozenset({"fs.read"}),
        resource_tags=frozenset({"/proj/a", "/proj/b"}),
        delegation_depth=2,
        not_before=1_000,
        expiry=4_600,
        attenuated_by="intermediary-M",
        parent_id="T_root",
        log_present=True,
    )
    try:
        authorize_invocation(child, root, "fs.read", "/proj/b", now=1_500)
    except IllegitimateAttenuationError as exc:
        print(f"QUARANTINED: {exc}")
