# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-federated-capability-attestation-whose-issuer-chain-re-signs-after-policy-narrowing.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-federated-capability-attestation-whose-issuer-chain-re-signs-after-policy-narrowing.warrant.json
# Markdown SHA-256:   f98bee0aafb2f02106407b88749bfc369abf1fc75a40fb3b134ae48492a07e1f
# Code AST SHA-256:   c49eada2c70bbd167abd69fa39d046a050de8aa9b632b5bdde98b83823cd8c18
# Verified Classes:   UnattributableAttestationError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class UnattributableAttestationError(RuntimeError):
    """Raised when a re-signed federated attestation cannot trace a scope
    to an authority that actually holds grant (not relay) for it."""
    pass


def accept_federated_attestation(attestation, trust_root, scope_authority_index):
    """
    attestation: {
        'issuer': key_id,
        'scopes': [str, ...],
        'derivation_chain': [ {issuer, scopes, transform}, ... ] or None,
        'signature': bytes,
    }
    scope_authority_index: maps scope -> key_id that holds GRANT authority.
    """
    if not verify_signature(attestation, trust_root):
        raise UnattributableAttestationError("signature invalid against trust root")

    chain = attestation.get("derivation_chain")
    for scope in attestation["scopes"]:
        authoritative_key = scope_authority_index.get(scope)
        if authoritative_key is None:
            raise UnattributableAttestationError(
                f"scope {scope!r} has no registered grant authority"
            )

        if attestation["issuer"] == authoritative_key:
            continue  # direct grant, provenance intact

        # Re-signed by a non-authoritative issuer: require derivation chain
        # that terminates at the authoritative key and marks each hop.
        if not chain:
            raise UnattributableAttestationError(
                f"scope {scope!r} emitted by relay {attestation['issuer']!r} "
                f"but true authority is {authoritative_key!r}; no derivation chain"
            )

        origin = None
        for hop in chain:
            if hop.get("transform") == "grant" and scope in hop["scopes"]:
                origin = hop["issuer"]
        if origin != authoritative_key:
            raise UnattributableAttestationError(
                f"scope {scope!r} derivation terminates at {origin!r}, "
                f"not authoritative {authoritative_key!r}"
            )

    return True
