# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-derives-a-delegated-capability-token-after-a-clock-skew-event-and-silently-widens-its-own-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-derives-a-delegated-capability-token-after-a-clock-skew-event-and-silently-widens-its-own-scope.warrant.json
# Markdown SHA-256:   9ef2e90e0a9340d7242ce807a7fbad78d4eb0a8f024e0c902ef4f87730cfc67f
# Code AST SHA-256:   95be2b85930e4e20341db47da197c951d04a8c42958a298156d18bdde7dc8c51
# Verified Classes:   ScopeWideningError, GrantEnvelope, CapabilityToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeWideningError(RuntimeError):
    """Raised when a re-derived token's scope exceeds the signed delegation intent."""


@dataclass(frozen=True)
class GrantEnvelope:
    parent_id: str
    delegated_scope: FrozenSet[str]   # signed, narrow, must be replayed verbatim
    available_scopes: FrozenSet[str]  # broad; MUST NOT be used as a refresh default
    not_after: float
    delegation_depth: int


@dataclass(frozen=True)
class CapabilityToken:
    subject: str
    scope: FrozenSet[str]
    not_after: float
    delegation_depth: int


SKEW_WINDOW = 120.0


def refresh_token(
    token: CapabilityToken,
    envelope: GrantEnvelope,
    now: float,
    requested_scope: FrozenSet[str] | None,
) -> CapabilityToken:
    # Skew-tolerant acceptance: if the token is only "expired" within skew, do not
    # enter the re-derivation path at all.
    if token.not_after > now - SKEW_WINDOW:
        return token

    # On the refresh path the narrowing constraint MUST come from signed state.
    # A missing narrow field is a hard failure, never a default to available_scopes.
    if requested_scope is None:
        raise ScopeWideningError(
            f"refresh for {token.subject} has no signed requested_scope; "
            f"refusing to default to available_scopes={sorted(envelope.available_scopes)}"
        )

    if not requested_scope.issubset(envelope.delegated_scope):
        raise ScopeWideningError(
            f"requested_scope {sorted(requested_scope)} not subset of "
            f"signed delegated_scope {sorted(envelope.delegated_scope)}"
        )

    # Monotonic narrowing invariant: new scope must be a subset of the original
    # token's scope AND of the signed delegation intent.
    if not requested_scope.issubset(token.scope):
        raise ScopeWideningError(
            f"refresh would widen scope from {sorted(token.scope)} to "
            f"{sorted(requested_scope)}"
        )

    return CapabilityToken(
        subject=token.subject,
        scope=requested_scope,
        not_after=now + 900.0,
        delegation_depth=envelope.delegation_depth,
    )
