# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-cryptographically-valid-tool-manifest-because-the-signing-principal-is-not-the-provenance-root.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-cryptographically-valid-tool-manifest-because-the-signing-principal-is-not-the-provenance-root.warrant.json
# Markdown SHA-256:   f7ca33827dc14836f9b601280217046636ec366db58e40a904a5da5705017fe1
# Code AST SHA-256:   2133b4475ececd972589873776f80c9458becc917afc196731bd1de8f457032d
# Verified Classes:   ProvenanceAuthorityError, Delegation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class ProvenanceAuthorityError(RuntimeError):
    """Raised when a signature is valid but the signer lacks namespace authority."""


@dataclass(frozen=True)
class Delegation:
    signer: str
    granted_namespaces: frozenset[str]  # explicit namespaces, never wildcards
    expires_at: float


def authorize_manifest(
    provenance_root: str,
    signing_principal: str,
    delegation: Delegation | None,
    now: float | None = None,
) -> None:
    now = time.time() if now is None else now

    if signing_principal == provenance_root:
        return

    if delegation is None:
        raise ProvenanceAuthorityError(
            f"signer {signing_principal!r} != provenance_root {provenance_root!r} "
            "and no delegation chain is present"
        )

    if delegation.signer != signing_principal:
        raise ProvenanceAuthorityError(
            f"delegation is for {delegation.signer!r}, not signer {signing_principal!r}"
        )

    if now >= delegation.expires_at:
        raise ProvenanceAuthorityError(
            f"delegation for {signing_principal!r} expired at {delegation.expires_at}"
        )

    # Semantic check: exact namespace membership. A wildcard grant such as
    # "publish:*" is intentionally NOT in the set and must be rejected here.
    if provenance_root not in delegation.granted_namespaces:
        raise ProvenanceAuthorityError(
            f"signer {signing_principal!r} holds no explicit grant over "
            f"namespace {provenance_root!r}; generic publish scope is insufficient"
        )


def load_skill_manifest(manifest: dict, delegation: Delegation | None) -> dict:
    authorize_manifest(
        provenance_root=manifest["provenance_root"],
        signing_principal=manifest["signing_principal"],
        delegation=delegation,
    )
    return manifest
