# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-derive-delegated-scope-from-the-credential-chain-rather-than-trusting-the-asserted-scope-in-an-aaif-token-exchange.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-derive-delegated-scope-from-the-credential-chain-rather-than-trusting-the-asserted-scope-in-an-aaif-token-exchange.warrant.json
# Markdown SHA-256:   7edc47494e79816f26ab864809a0043a73b0838c3f9f34a84048d7e59f116712
# Code AST SHA-256:   4fe1177eb9ed96d715191a0b013b2186429672432ee1858c05583eb33d96c64e
# Verified Classes:   ScopeIntersectionViolation, MissingDelegableScope
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class ScopeIntersectionViolation(RuntimeError):
    """Raised when an asserted scope exceeds the recomputed credential-chain intersection."""
    pass


class MissingDelegableScope(RuntimeError):
    """Raised when a chain link omits delegable_scope; absence means empty, never unrestricted."""
    pass


def recompute_authorized_scope(chain, now):
    # chain: list of links ordered root -> leaf; each link is a dict with
    # 'granted_scope', 'delegable_scope', 'not_after', 'revoked'.
    if not chain:
        raise ScopeIntersectionViolation("empty credential chain: no authority to derive")

    authorized = None
    for index, link in enumerate(chain):
        if link.get("revoked", False):
            raise ScopeIntersectionViolation(f"link {index} revoked; chain invalid")
        if link["not_after"] < now:
            raise ScopeIntersectionViolation(f"link {index} expired at {link['not_after']}")

        granted = set(link["granted_scope"])
        if "delegable_scope" not in link:
            raise MissingDelegableScope(
                f"link {index} omits delegable_scope; treating as empty set, not unrestricted"
            )
        delegable = set(link["delegable_scope"])

        # What this link may pass downstream is granted ∩ delegable.
        passable = granted & delegable
        authorized = passable if authorized is None else (authorized & passable)

    return authorized


def validate_exchange(chain, asserted_scope, now):
    authorized = recompute_authorized_scope(chain, now)
    asserted = set(asserted_scope)

    overreach = asserted - authorized
    if overreach:
        raise ScopeIntersectionViolation(
            f"asserted scope {sorted(overreach)} not in chain intersection {sorted(authorized)}; "
            f"signature validity does not imply root authorization"
        )
    if not authorized:
        raise ScopeIntersectionViolation("recomputed intersection is empty; no authority to exchange")

    return {"admitted_scope": sorted(asserted & authorized), "chain_depth": len(chain)}
