atproto-attestation #

Utilities for creating and verifying AT Protocol record attestations using the CID-first workflow.

Overview #

A Rust library implementing the CID-first attestation specification for AT Protocol records. This crate provides cryptographic signature creation and verification for records, supporting both inline attestations (signatures embedded directly in records) and remote attestations (separate proof records with strongRef references).

It follows the badge.blue attestation specification, whose §9 ("Security properties") is where the curve rule require_attestation_curve applies, and the low-S rule, come from.

The attestation workflow ensures deterministic signing payloads and prevents replay attacks by:

  1. Automatically preparing records with $sig metadata containing $type and repository fields
  2. Generating content identifiers (CIDs) using DAG-CBOR serialization
  3. Signing CID bytes with elliptic curve cryptography (for inline attestations)
  4. Normalizing signatures to low-S form to prevent malleability attacks
  5. Embedding signatures or creating proof records with strongRef references

Critical Security Feature: The repository field in $sig metadata binds attestations to specific repositories, preventing replay attacks where an attacker might attempt to clone records from one repository into their own.

Features #

  • Inline attestations: Embed cryptographic signatures directly in record structures
  • Remote attestations: Create separate proof records with CID-based strongRef references
  • CID-first workflow: Deterministic signing based on content identifiers
  • Multi-curve support: P-256 and K-256 elliptic curves. badge.blue §9 also lists P-384, which this crate refuses by key type
  • Signature normalization: Automatic low-S normalization for ECDSA signatures to prevent malleability
  • Flexible input types: AnyInput takes a record either as a JSON string or as any Serialize value — a serde_json::Value, a typed lexicon, or your own struct
  • Repository binding: Automatic prevention of replay attacks

CLI Tools #

The following command-line tools are available when built with the clap and tokio features:

  • atproto-attestation-sign: Sign AT Protocol records with inline or remote attestations
  • atproto-attestation-verify: Verify cryptographic signatures on AT Protocol records

Library Usage #

Creating Inline Attestations #

Inline attestations embed the signature bytes directly in the record:

use atproto_attestation::{create_inline_attestation, input::AnyInput};
use atproto_identity::key::{KeyType, generate_key, to_public};
use serde_json::json;

fn main() -> anyhow::Result<()> {
    // Generate a signing key
    let private_key = generate_key(KeyType::K256Private)?;
    let public_key = to_public(&private_key)?;
    let key_reference = public_key.to_string();

    // The record to sign
    let record = json!({
        "$type": "app.bsky.feed.post",
        "text": "Hello world!",
        "createdAt": "2024-01-01T00:00:00.000Z"
    });

    // Repository housing this record (for replay attack prevention)
    let repository_did = "did:plc:repo123";

    // Attestation metadata (required: $type and key for inline attestations).
    // `key` names the key a verifier resolves: a did:key, which must be the
    // one signing; a DID-document reference (did:plc:example#atproto); or a
    // URI with a key id (https://example.com/jwks.json#kid1). Signing refuses
    // metadata whose key is missing, unreadable, or somebody else's.
    // Leave `repository` out: the CID takes it from repository_did, and
    // signing refuses metadata that sets it.
    let sig_metadata = json!({
        "$type": "com.example.inlineSignature",
        "key": &key_reference,
        "issuer": "did:plc:issuer123",
        "issuedAt": "2024-01-01T00:00:00.000Z"
    });

    // Create inline attestation (repository_did is bound into the CID)
    // Signature is automatically normalized to low-S form
    let signed_record = create_inline_attestation(
        AnyInput::Serialize(record),
        AnyInput::Serialize(sig_metadata),
        repository_did,
        &private_key,
    )?;

    println!("{}", serde_json::to_string_pretty(&signed_record)?);

    Ok(())
}

The resulting record will have a signatures array. Its cid is the content CID the signature covers — a convenience copy, not part of what is signed, since the signing record strips it before hashing. Verification recomputes the CID rather than trusting the field; append_inline_attestation compares the two and refuses a mismatch.

{
  "$type": "app.bsky.feed.post",
  "text": "Hello world!",
  "createdAt": "2024-01-01T00:00:00.000Z",
  "signatures": [
    {
      "$type": "com.example.inlineSignature",
      "key": "did:key:zQ3sh...",
      "issuer": "did:plc:issuer123",
      "issuedAt": "2024-01-01T00:00:00.000Z",
      "cid": "bafyrei...",
      "signature": {
        "$bytes": "base64-encoded-normalized-signature-bytes"
      }
    }
  ]
}

Creating Remote Attestations #

Remote attestations create a separate proof record that must be stored in a repository:

use atproto_attestation::{create_remote_attestation, input::AnyInput};
use serde_json::json;

fn main() -> anyhow::Result<()> {
    let record = json!({
        "$type": "app.bsky.feed.post",
        "text": "Hello world!"
    });

    // Repository housing the original record (for replay attack prevention)
    let repository_did = "did:plc:repo123";

    // DID of the entity creating the attestation (will store the proof record)
    let attestor_did = "did:plc:attestor456";

    let metadata = json!({
        "$type": "com.example.attestation",
        "issuer": "did:plc:issuer123",
        "purpose": "verification"
    });

    // Create both the attested record and proof record in one call.
    // The answer also says where the proof has to go.
    let attestation = create_remote_attestation(
        AnyInput::Serialize(record),
        AnyInput::Serialize(metadata),
        repository_did, // Repository housing the original record
        attestor_did,   // Repository that will store the proof record
    )?;

    // putRecord the proof at exactly this collection and record key.
    println!("repo:       {}", attestor_did);
    println!("collection: {}", attestation.proof_collection);
    println!("rkey:       {}", attestation.proof_rkey);
    println!("proof:\n{}", serde_json::to_string_pretty(&attestation.proof)?);

    // The attested record carries the strongRef to that address.
    println!("attested:\n{}", serde_json::to_string_pretty(&attestation.record)?);

    Ok(())
}

Storing the proof record #

The strongRef appended to the attested record names an address and pins a CID, so three things about the proof record are already decided:

collection attestation.proof_collection — the metadata's $type
record key attestation.proof_rkey — a TID minted when the attestation was created
bytes exactly attestation.proof, which is what the pinned CID covers

So write it with putRecord, not createRecord. createRecord mints a record key of the server's choosing, and the strongRef then points at a record that does not exist — nothing reports an error until somebody verifies the attested record, and the failure then looks like a missing proof rather than a bad write. For the same reason, store the proof exactly as returned: a client or server that reorders or adds a field changes its CID and breaks the pin.

To choose the address yourself, write the proof record first and use append_remote_attestation, which takes the AT-URI you stored it at.

Verifying Signatures #

Verification needs two resolvers: a KeyResolver for the key an inline signature names, and a RecordResolver for the proof record a remote attestation points at. This crate takes them as traits rather than implementations, which is why its default build carries no HTTP client — with the tokio feature, atproto_client::record_resolver::HttpRecordResolver is the HTTP RecordResolver, and atproto_identity::key::IdentityDocumentKeyResolver resolves keys through DID documents.

use atproto_attestation::{RecordResolver, input::AnyInput, verify_record};
use atproto_identity::key::KeyResolver;
use serde_json::json;

async fn report(
    key_resolver: impl KeyResolver,
    record_resolver: impl RecordResolver,
) -> anyhow::Result<()> {
    // A signed record carries a `signatures` array; `[]` stands in for one here.
    let signed_record = json!({
        "$type": "app.bsky.feed.post",
        "text": "Hello world!",
        "signatures": []
    });

    // The repository DID where this record is stored
    // CRITICAL: This must match the repository used during signing to prevent replay attacks
    let repository_did = "did:plc:repo123";

    // Verify all signatures with repository validation. The answer is the
    // signatures that verified: an unattested record is an empty list, not the
    // same success a checked one gives.
    let verified = verify_record(
        AnyInput::Serialize(signed_record),
        repository_did,
        key_resolver,
        record_resolver,
    )
    .await?;

    println!("✓ {} signature(s) valid for the keys they name", verified.len());

    // Each one names a key and claims an issuer. Verification does not tie
    // those together: anyone can sign with a key they made and name any
    // issuer. `require_issuer_holds_key` is the check that they belong
    // together, and it needs an identity resolver.
    for signature in &verified {
        if let Some(issuer) = &signature.issuer {
            println!("  claims {issuer}, binding unchecked");
        }
    }

    Ok(())
}

Command Line Usage #

Build the two tools once:

cargo build --package atproto-attestation --features clap,tokio --bins

The examples below run them by name. Every JSON parameter accepts a JSON string or a file path, and the record parameter also accepts - for stdin. The signing key is read from a file, stdin or an environment variable; see "Inline Attestation" below.

Signing Records #

Inline Attestation #

The metadata's key must name the public form of the signing key — signing refuses metadata that names anything else, rather than leaving a signature no verifier can check. The key pair below is an example; generate your own with atpdid key generate p256.

<signing_key> says where to read the private key: a path to a file holding it, - for stdin, or the name of an environment variable holding it, such as ATPROTO_SIGNING_KEY, the way atproto-oauth-service-token takes its key. What is read is trimmed, so a trailing newline does not matter. The key itself also works in that position, but do not pass a real key on the command line: any local user can read a command line through ps while it runs, and your shell keeps it in its history. Only one argument can read stdin, so - for both the record and the key is refused.

# inline <source_record> <repository_did> <signing_key> <metadata_record>
#
# signing.key holds did:key:z42tnbHmmnhF11nwSnp5kQJbcZQw2Vbw5WF3ABDSxPtDgU2o, a
# published example keypair reused from this repo's own tests. It is public:
# never sign anything you care about with it. Generate your own with
# `atpdid key generate p256`.
atproto-attestation-sign inline \
  record.json \
  did:plc:repo123 \
  signing.key \
  metadata.json

# The key from an environment variable, set by your secret manager, named in
# its place
atproto-attestation-sign inline \
  record.json \
  did:plc:repo123 \
  ATPROTO_SIGNING_KEY \
  metadata.json

# The key from stdin
cat signing.key | atproto-attestation-sign inline \
  record.json \
  did:plc:repo123 \
  - \
  metadata.json

# Using JSON strings instead of files. The key is passed as itself here only
# because it is the public example key
atproto-attestation-sign inline \
  '{"$type":"app.bsky.feed.post","text":"Hello!"}' \
  did:plc:repo123 \
  did:key:z42tnbHmmnhF11nwSnp5kQJbcZQw2Vbw5WF3ABDSxPtDgU2o \
  '{"$type":"com.example.sig","key":"did:key:zDnaeXduWbJ1b1Kgjf3uCdCpMDF1LEDizUiyxAxGwerou3Nh2"}'

# Read record from stdin
cat record.json | atproto-attestation-sign inline \
  - \
  did:plc:repo123 \
  signing.key \
  metadata.json

did:key:z42t… is a P-256 private key; did:key:zDnae… is its public form, which is what the metadata names. A did:key:zQ3sh… is a public secp256k1 key, so passing one as <signing_key> fails with error-atproto-identity-key-8 Private key required for signature.

Remote Attestation #

Note that remote takes the two repository DIDs around the record, not after it:

# remote <source_repository_did> <source_record> <attestation_repository_did> <metadata_record>
atproto-attestation-sign remote \
  did:plc:repo123 \
  record.json \
  did:plc:attestor456 \
  metadata.json

This outputs the proof record, the repo/collection/rkey to putRecord it at, and the source record carrying the strongRef to that address. The record key is fixed by the strongRef — see "Storing the proof record" above.

Verifying Signatures #

# Verify every attestation in a record, from a file
atproto-attestation-verify \
  ./signed_record.json \
  did:plc:repo123

# Verify from stdin
cat signed_record.json | atproto-attestation-verify \
  - \
  did:plc:repo123

# Verify from a JSON string
atproto-attestation-verify \
  "$(cat signed_record.json)" \
  did:plc:repo123

# Verify one inline signature, from a file, against a record
atproto-attestation-verify \
  ./record.json \
  did:plc:repo123 \
  ./signature.json

# Verify one remote attestation, named by its proof record's AT-URI
atproto-attestation-verify \
  ./record.json \
  did:plc:repo123 \
  at://did:plc:attestor456/com.example.attestation/abc123

The verifier prints one line per attestation, marked ✓ or ✗ with the reason, then a count:

✓ [0] inline com.example.attestation key did:key:zDnae…
✗ [1] inline com.example.attestation key did:key:zDnae…: error-atproto-attestation-signature-6 Signature verification failed: …
1 of 2 attestations verified.

It exits 0 only when there is at least one attestation and every one of them verified, so a record with no signatures exits 1. A proof record passed as JSON is refused: a copy of one proves nothing, so name it by its AT-URI or a strongRef, and it is fetched from the repository that holds it.

A record named by AT-URI is verified against the repository that stores it, so <repository_did> has to be the DID the AT-URI names. When it is not, the run is refused, naming both, before anything is fetched: a record copied from one repository into another would otherwise verify against the one it was copied from, the replay the repository binding exists to stop. The AT-URI has to name its repository by DID, since the verifier resolves no handles.

✓ means the signature is valid for the key the attestation names, or the proof record is the one its strongRef pins and names this content, over this record in this repository. It does not show that the key belongs to the attestation's issuer. An attestation named by AT-URI on the command line has no strongRef pinning it, and its line says (unpinned).

A did:plc — the DID in a key reference such as did:plc:…#atproto, or an AT-URI's repository — is resolved through the PLC directory PLC_HOSTNAME names, plc.directory when it is unset. An empty or malformed value is refused before anything is loaded.

Public API #

The crate exposes the following public functions:

Attestation Creation #

  • create_inline_attestation: Create a signed record with embedded signature

    • Signs in low-S form, and refuses a curve badge.blue does not allow
    • Binds attestation to repository DID
    • Returns the record with the signature appended to its signatures array
  • create_remote_attestation: Create separate proof record and strongRef

    • Returns a RemoteAttestation: both records, plus the AT-URI, collection and record key the proof must be stored at
    • Proof record must be stored in attestor's repository
  • append_inline_attestation: Append a signature made elsewhere to a record, after checking it

    • Checks the signature with the code verify_signature runs, curve rule included, so it appends nothing verification refuses
    • Also refuses a cid that is not this record's content CID, and a repository naming another repository, neither of which verification reads
  • append_remote_attestation: Append a strongRef to a proof record you have already stored

    • Refuses a proof whose cid is not this record's content CID, or whose repository names another repository
  • create_signature: Sign a record's content CID, without assembling the attestation

CID Generation #

  • cid::create_attestation_cid: The content CID: $sig metadata is prepared and bound to the repository automatically
  • create_dagcbor_cid: Generate CID for any serializable data
  • cid::validate_dagcbor_cid: Whether a CID string is a well-formed DAG-CBOR CID

Signature Operations #

  • normalize_signature: Normalize raw signature bytes to low-S form
    • Prevents signature malleability attacks
    • Supports P-256 and K-256 curves
  • require_attestation_curve: Refuse a key type badge.blue §9 does not allow

Verification #

  • verify_record: Verify all signatures in a record
    • Validates repository binding
    • Supports both inline and remote attestations
    • Requires key and record resolvers
  • verify_signature: Verify one entry of a record's signatures, to report on each one rather than stop at the first failure
  • verify_remote_attestation: Check a fetched proof record against the strongRef that pins it
  • require_issuer_holds_key: Check that an attestation's issuer holds the key its signature was checked against, which verification itself does not

Input Types #

  • AnyInput: Flexible input enum with two variants:
    • String: a JSON string, parsed on use
    • Serialize: any Serialize + Clone value — a serde_json::Value, an atproto_record::typed::TypedLexicon, or your own struct

Attestation Specification #

This crate implements the CID-first attestation specification, which ensures:

  1. Deterministic signing: Records are serialized to DAG-CBOR with $sig metadata, producing consistent CIDs
  2. Data-model encoding: The record is encoded as AT Protocol JSON, so {"$link": "..."} is a CBOR tag-42 CID link and {"$bytes": "..."} a byte string — the encoding a repository hashes. This matters only for records carrying a blob, a CID link or raw bytes; tests/vectors/blob-record.json is a vector for one. Before 0.15.0-rc.5 this crate encoded those sentinels structurally, as one-key maps, and verification still accepts signatures made under that rule (see "Verifying older attestations" below)
  3. Content addressing: Signatures are over CID bytes, not the full record
  4. Repository binding: Every attestation is bound to a specific repository DID to prevent replay attacks
  5. Signature normalization: ECDSA signatures are normalized to low-S form to prevent malleability
  6. Flexible metadata: Custom fields in $sig are preserved and included in the CID calculation
  7. Multiple attestations: Records can have multiple signatures in the signatures array

Verifying older attestations #

A record with no sentinel hashes identically under either encoding, so attested records without blobs, links or bytes are unaffected. Where they differ, an attestation signed before the change verifies through a fallback: each signature is checked against the data-model CID first, then the older structural one. Nothing signs with the old encoding, and the fallback is meant to be removed once existing attestations have been re-signed.

Other implementations need explicit tag-42 handling to agree: go-ipld-prime rather than a naive fxamacker/cbor configuration in Go, and the equivalent care with @ipld/dag-cbor in TypeScript.

Signature Structure #

Inline attestation entry:

{
  "$type": "com.example.signature",
  "key": "did:key:z...",
  "issuer": "did:plc:...",
  "cid": "bafyrei...",
  "signature": {
    "$bytes": "base64-normalized-signature"
  }
}

The signature is standard base64 with = padding, as badge.blue §5 and §9 specify; verification accepts it padded or unpadded. The atproto data model makes padding optional, and other encoders in this workspace, such as atproto-dasl's JSON projection, write unpadded.

Remote attestation entry (strongRef):

{
  "$type": "com.atproto.repo.strongRef",
  "uri": "at://did:plc:repo/com.example.attestation/tid",
  "cid": "bafyrei..."
}

Error Handling #

The crate provides structured error types via AttestationError. Every message starts with a code, error-atproto-attestation-<domain>-<n>, in one of six domains: input, entry, key, signature, remote and issuer. The errors module documentation gives each domain's range. The codes before 0.15.0 had no domain, and all of them are retired. The inputs:

  • RecordMustBeObject: Input must be a JSON object — carries the AnyInputError saying what reading it found instead
  • MetadataMustBeObject: Attestation metadata must be a JSON object — likewise
  • RecordNotSerializable: The record does not serialize to JSON, and create_dagcbor_cid reports its argument the same way. It is not a RecordMustBeObject: the value may well be an object
  • MetadataNotSerializable: The metadata does not serialize to JSON, which likewise is not a MetadataMustBeObject
  • RecordMissingType: The record has no string $type
  • MetadataMissingType: The metadata has no string $type, from whichever function it was handed to
  • MetadataRepositorySet: The metadata passed to signing sets repository, which comes from the repository argument instead
  • AttestationRepositoryMismatch: An attestation being appended sets repository to something other than the repository argument
  • SignaturesFieldInvalid: signatures is present but is not an array
  • SignatureEntryMissingType: An entry already in signatures has no string $type, which is what says whether it is an inline signature or a strongRef
  • SignatureMissingField: A signature entry is missing a field the check needs
  • SignatureBytesFormatInvalid: Signature bytes are not wrapped as {"$bytes": "..."}

Keys and signatures:

  • AttestationKeyInvalid: The key the metadata names cannot be read
  • AttestationKeyMismatch: The key the metadata names is not the key signing
  • UnsupportedKeyType: Key type not allowed for attestation signing or verification
  • SignatureCreationFailed: Key signing operation failed
  • SignatureValidationFailed: Signature verification failed
  • SignatureDecodingFailed: Signature bytes are not valid base64
  • SignatureLengthInvalid: Signature bytes have incorrect length
  • SignatureScalarOutOfRange: The signature is the right length, but its r or s is zero or not below the curve order
  • KeyResolutionFailed: Could not resolve verification key
  • RecordSerializationFailed: DAG-CBOR encoding failed

Issuer binding, which only require_issuer_holds_key checks:

  • IssuerDoesNotHoldKey: The issuer's DID document does not list the key that signed
  • IssuerBindingUncheckable: The binding cannot be decided here
  • IssuerResolutionFailed: The issuer's DID document could not be resolved

Remote attestations:

  • RemoteAttestationFetchFailed: Failed to fetch remote proof record
  • RemoteAttestationNotPinned: The record fetched is not the one the strongRef pins
  • RemoteAttestationCidMismatch: The proof record's CID is not the attested content's
  • RemoteAttestationMissingType: The proof record verify_signature fetched has no $type (as does one atproto-attestation-verify fetched by AT-URI)
  • AttestationCidMismatch: An inline attestation's cid is not the content it covers

Security Considerations #

Repository Binding and Replay Attack Prevention #

The most critical security feature of this attestation framework is repository binding. Every attestation includes the repository DID in the $sig metadata during CID generation, which:

  • Prevents replay attacks: An attacker cannot copy a signed record from one repository to another because the signature is bound to the original repository DID
  • Ensures context integrity: Attestations are only valid within their intended repository context
  • Automatic enforcement: The library automatically adds the repository field during CID generation

Important: Always verify signatures with the correct repository DID. Verifying with a different repository DID will (correctly) fail validation, as this would indicate a potential replay attack.

Signature Normalization #

All ECDSA signatures are automatically normalized to low-S form to prevent signature malleability attacks:

  • Signing emits low-S directly; normalize_signature is for signatures made elsewhere, by a library that may not
  • Verification accepts only low-S signatures
  • This prevents attackers from creating alternate valid signatures for the same content

Key Management Best Practices #

  • Private keys: Never log, transmit, or store private keys in plaintext. Give atproto-attestation-sign its key through a file, stdin or an environment variable, not on the command line
  • Key rotation: Plan for key rotation by using verification method references that can be updated in DID documents
  • Key types: The library supports P-256 and K-256 elliptic curves
  • did:key: For testing and simple use cases, did:key identifiers provide self-contained key references

CID Verification #

  • Always verify against CIDs: Signatures are over CID bytes, not the original record content
  • Deterministic generation: The same record with the same $sig metadata always produces the same CID
  • Content integrity: Any modification to the record will produce a different CID and invalidate signatures

Metadata Validation #

When creating attestations:

  • The $type field is always required in metadata to scope the attestation
  • The repository field comes from the repository argument when the content CID is computed, and is not stored in the attestation. Signing refuses metadata that sets it, whatever the value (MetadataRepositorySet): the CID would overwrite it, so the entry or proof record would name a repository the signature is not bound to
  • Appending an attestation made elsewhere, with append_inline_attestation or append_remote_attestation, accepts a repository equal to the repository argument, since that value is accurate, and refuses any other (AttestationRepositoryMismatch)
  • Verification ignores a repository in a stored entry or proof record and binds the check to its own repository argument, so an attestation written with a mismatched value, as this crate's signing allowed before 0.15.0, still verifies. Don't read the field as where the attestation belongs: the repository you verified against is
  • Custom metadata fields are preserved and included in CID calculation
  • The cid field is automatically added to inline attestation metadata

Remote Attestation Considerations #

  • Proof record storage: Store proof records in the attestor's repository with appropriate access controls
  • CID matching: Verify that the CID in the proof record matches the computed CID of the attested content
  • Record resolution: Use trusted record resolvers when fetching remote proof records

License #

MIT License