# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-a-signed-agent-manifest-was-re-bound-to-a-different-runtime-identity-between-attestation-and-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-a-signed-agent-manifest-was-re-bound-to-a-different-runtime-identity-between-attestation-and-invocation.warrant.json
# Markdown SHA-256:   824ee2204b754e5cf5d067e6a5a51aef87167d749d8f6f675f7b044008f4e458
# Code AST SHA-256:   fb2f5b06079c4e672332eb0a9a9e6f21a1ad71ccec81d68f9c3b0af1d108b42c
# Verified Classes:   ManifestRebindError
# Defensive Guards:   7 fail-closed invariants (zero external deps)

class ManifestRebindError(RuntimeError):
    """Raised when a signed manifest is bound to a runtime other than the one attested."""
    pass


def verify_delegation(manifest, response_envelope, issuer_key, now_issuer, now_gateway):
    # 1. Signature is necessary but not sufficient.
    if not verify_signature(manifest, issuer_key):
        raise ManifestRebindError("manifest signature invalid")

    # 2. Freshness must be enforced on both clocks; fail closed on skew.
    if manifest.exp <= min(now_issuer, now_gateway):
        raise ManifestRebindError(
            f"manifest expired under issuer/gateway clock: exp={manifest.exp} "
            f"issuer={now_issuer} gateway={now_gateway}"
        )

    # 3. Runtime identity must be content-addressed and echoed back.
    resolved = response_envelope.get("resolved_digest")
    if resolved is None:
        raise ManifestRebindError("gateway did not echo resolved runtime digest")
    if resolved != manifest.runtime_digest:
        raise ManifestRebindError(
            f"runtime re-bound: attested={manifest.runtime_digest} resolved={resolved}"
        )

    # 4. Runtime must self-measure and quote; caller binds the quote.
    quote = response_envelope.get("attestation_quote")
    if quote is None or measure(quote) != manifest.runtime_digest:
        raise ManifestRebindError("runtime attestation quote does not match attested digest")

    # 5. Tenant binding guards against shared-key replay across tenants.
    if response_envelope.get("tenant_id") != manifest.tenant_id:
        raise ManifestRebindError(
            f"tenant mismatch: manifest={manifest.tenant_id} runtime={response_envelope.get('tenant_id')}"
        )

    # 6. Runtime tool grants must be a subset of attested capabilities.
    granted = set(response_envelope.get("tool_grants", []))
    attested = set(manifest.capabilities)
    if not granted.issubset(attested):
        raise ManifestRebindError(
            f"capability drift: runtime grants {granted - attested} not attested"
        )

    return True
