# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-whose-scope-was-narrowed-after-issuance.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-whose-scope-was-narrowed-after-issuance.warrant.json
# Markdown SHA-256:   64cc3fc53582d0890310bda509be863ecc37127ae2fa18797d4efa54569de8e0
# Code AST SHA-256:   4dc4ef74afb7219a4bd2fc6c18b9af5a7e05f152657a00722d45c936c0101588
# Verified Classes:   LineageResolutionError, Credential, TrustStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Dict, Set


class LineageResolutionError(RuntimeError):
    """Raised when a delegated credential's lineage does not resolve to a
    live, unrevoked ancestor, or when attenuation widened scope."""


@dataclass(frozen=True)
class Credential:
    cred_id: str
    lineage_root: str          # MUST be preserved across attenuation
    scope: Set[str]
    issued_at: float
    parent_id: str | None = None


@dataclass
class TrustStore:
    # lineage_root -> set of revoked credential ids under that root
    revoked: Dict[str, Set[str]] = field(default_factory=dict)
    last_refresh: Dict[str, float] = field(default_factory=dict)

    def is_revoked(self, cred: Credential) -> bool:
        return cred.cred_id in self.revoked.get(cred.lineage_root, set())

    def lineage_known(self, cred: Credential) -> bool:
        return cred.lineage_root in self.revoked


def attenuate(parent: Credential, child_id: str, new_scope: Set[str]) -> Credential:
    """Derive a narrowed credential. Preserves lineage_root; rejects widening."""
    if not new_scope.issubset(parent.scope):
        raise LineageResolutionError(
            f"attenuation widened scope: {new_scope} not subset of {parent.scope}"
        )
    return Credential(
        cred_id=child_id,
        lineage_root=parent.lineage_root,   # <-- the invariant
        scope=new_scope,
        issued_at=time.time(),
        parent_id=parent.cred_id,
    )


def authorize(
    cred: Credential,
    store: TrustStore,
    action: str,
    max_staleness: float,
) -> None:
    """Fail-closed authorization check. Must be called at use time."""
    if not store.lineage_known(cred):
        raise LineageResolutionError(
            f"credential {cred.cred_id} has dangling lineage_root "
            f"{cred.lineage_root!r}; likely re-minted during attenuation"
        )
    if store.is_revoked(cred):
        raise LineageResolutionError(
            f"credential {cred.cred_id} revoked under lineage {cred.lineage_root}"
        )
    age = time.time() - store.last_refresh.get(cred.lineage_root, 0.0)
    if age > max_staleness:
        raise LineageResolutionError(
            f"revocation set for lineage {cred.lineage_root} is stale "
            f"({age:.1f}s > {max_staleness:.1f}s); re-fetch before use"
        )
    if action not in cred.scope:
        raise LineageResolutionError(
            f"action {action!r} outside scope {cred.scope}"
        )
    # authorized
