# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-an-aaif-verifiable-credential-whose-issuer-chain-is-valid-but-whose-subject-binding-has-silently-re-anchored-to-a-new-wor.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-an-aaif-verifiable-credential-whose-issuer-chain-is-valid-but-whose-subject-binding-has-silently-re-anchored-to-a-new-wor.warrant.json
# Markdown SHA-256:   85e6db2665be595de50e7dffc44b56ff6ec6df5baf839b8c75b48c94d9ec4993
# Code AST SHA-256:   a4f3b01e3374a7f9a8b807e8dfa644c1d49fb957d23061f48c58b2bda08be6f6
# Verified Classes:   SubjectRebindError, AAIFAdmissionGate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SubjectRebindError(RuntimeError):
    """Raised when an AAIF credential's subject binding has re-anchored to a
    different workload than the one verified at acceptance time, despite a
    valid issuer chain. Terminal: no retry, no fallback to cached validity."""
    pass


class AAIFAdmissionGate:
    def __init__(self, resolve_binding, current_epoch, max_binding_ttl_s=5):
        # resolve_binding: subject_id -> (workload_key, binding_epoch)
        self.resolve_binding = resolve_binding
        self.current_epoch = current_epoch
        self.max_binding_ttl_s = max_binding_ttl_s
        self._chain_cache = {}  # jti -> bool (safe: credential immutable)

    def admit(self, cred, presenter_key, now):
        # Axis 1: issuer chain. Cacheable because the credential is immutable.
        if cred.jti not in self._chain_cache:
            self._chain_cache[cred.jti] = self._verify_chain(cred)
        if not self._chain_cache[cred.jti]:
            raise SubjectRebindError(f"chain invalid for jti={cred.jti}")

        # Axis 2: subject binding. NEVER cached across admissions.
        try:
            bound_key, bound_epoch = self.resolve_binding(cred.subject)
        except LookupError as e:
            # Resolution failure is terminal, not a transient retry.
            raise SubjectRebindError(
                f"subject {cred.subject} unresolvable; refusing rather than "
                f"falling back to cached validity: {e}"
            ) from e

        if bound_key != presenter_key:
            # The credential names a subject that now resolves to a different
            # live workload. This is the re-anchoring failure.
            raise SubjectRebindError(
                f"subject {cred.subject} re-anchored: bound={bound_key} "
                f"presenter={presenter_key}; credential must be re-issued"
            )

        if bound_epoch != self.current_epoch:
            raise SubjectRebindError(
                f"binding epoch drift for {cred.subject}: "
                f"bound={bound_epoch} current={self.current_epoch}"
            )

        # Record the epoch so downstream handoffs can detect rebind.
        return {"jti": cred.jti, "subject": cred.subject,
                "binding_epoch": bound_epoch, "admitted_at": now}

    def _verify_chain(self, cred):
        return cred.chain_verified  # signature check, issuer axis only
