c2pa

package module
v0.23.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 42 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

c2pa

Go Reference CI Go Report Card

Website: richardwooding.github.io/c2pa

A small, pure-Go (no cgo) library for C2PA / Content Credentials provenance manifests embedded in JPEG, PNG, BMFF (MP4, MOV, HEIC, HEIF, AVIF), RIFF (WebP, WAV, AVI), TIFF (and DNG), GIF, MP3, SVG and PDF files, with three modes:

  • Read — a fast, unverified reader. Surfaces what a file claims (creating tool, title, format, AI-generated flag, signer identity, signing time) like EXIF or an email From: header.
  • Validate — a full, opt-in verifier. Checks the COSE signature, the certificate chain against the C2PA trust list, assertion and hard-binding hashes, the RFC 3161 timestamp, revocation, and ingredients — reporting C2PA status codes. Pure Go, no c2pa-rs/CGO.
  • Sign — a writer. Embeds a signed c2pa.claim.v2 manifest into any of the nine containers with your key and certificate chain, optionally timestamped, chaining any manifest already there. Every container's output is checked against c2pa-rs's c2patool in CI.
go get github.com/richardwooding/c2pa

Read — fast, unverified triage

Read reports the file's claims; it does not authenticate them. Treat every field like EXIF: accurate-as-recorded, not proven. SignedBy is who the file claims signed it. Use it for search, indexing, triage, and inventory ("find images with Content Credentials", "find AI-generated assets") — not for trust decisions.

f, _ := os.Open("photo.jpg")
defer f.Close()

info := c2pa.Read(context.Background(), c2pa.JPEG, f) // or c2pa.PNG / c2pa.BMFF / c2pa.RIFF / c2pa.TIFF / c2pa.GIF / c2pa.MP3 / c2pa.SVG / c2pa.PDF
if !info.Present {
    return // no Content Credentials embedded
}

fmt.Println(info.ClaimGenerator) // e.g. "Adobe Firefly"
fmt.Println(info.Title)          // claim dc:title
fmt.Println(info.Format)         // claim dc:format
fmt.Println(info.AIGenerated)    // declared AI-generated?
fmt.Println(info.SoftwareAgent)  // tool that performed the action, e.g. "gpt-image/2.0"
fmt.Println(info.SignedBy)       // CLAIMED signer cert CN (unverified)
fmt.Println(info.SignedAt)       // RFC 3161 signing time (unverified)

Read is best-effort and never returns an error: a missing or malformed manifest yields Info{Present: false}. It reads at most c2pa.MaxScan (16 MiB) from the reader and honours the context — a cancelled call surrenders promptly mid-scan.

For RIFF (WebP, WAV, AVI), the store is a top-level C2PA chunk inside the outer RIFF container; a chunk declaring more bytes than the file holds is refused rather than read past.

For TIFF, BigTIFF and DNG, the store is IFD tag 0xCD41 with field type UNDEFINED; every IFD in the chain is checked, and the chain is hop-capped because a next-IFD offset may point backwards. Classic and BigTIFF are the same walk at different field widths — 4- vs 8-byte offsets, and three counts that classic TIFF deliberately does not share.

For GIF, the store is the application extension identified by C2PA_GIF, reassembled from its data sub-blocks; the block structure is walked rather than scanned, since LZW image data can spell the marker. For MP3, it is an ID3v2 GEOB frame with MIME type application/c2pa. For SVG, it is base64 in a <c2pa:manifest> element bound to http://c2pa.org/manifest, parsed as XML so a match in a comment or CDATA is not mistaken for it.

For PDF, the manifest store is the embedded file the document catalog associates with /AFRelationship /C2PA_Manifest (spec §A.4). The catalog is the one the last startxref names, so bytes appended after %%EOF cannot redirect the document; a catalog or file specification compressed into an object stream is recovered by inflating it, and a /FlateDecode stream is inflated under a bound. Where the catalog associates no store, one the spec's markers find is still surfaced. Where an object associates one of its own (§A.4.3 object-level manifests, attached to an image or font stream through its /AF entry) that association is resolved, so the manifest is reported as a claim about that resource — Info.Attribution is AttributionEmbedded, and its hard binding is not hashed against the document, which would be the wrong subject. Only a store nothing associates at all falls back to AttributionUnknown. Every store the document carries is resolved against as one, across incremental update sections and object levels alike, which is what §A.4.2.1 asks.

Info field Meaning
Present a C2PA manifest was found and parsed
Attribution who the manifest is a claim about. AttributionAsset when the asset's own structure associates it; AttributionEmbedded when the asset associates it with a resource it CARRIES rather than with itself (PDF §A.4.3); AttributionUnknown when only the C2PA markers identified it and nothing places it; AttributionNone (the zero value) when there is no manifest. For Embedded and Unknown, do not report its signer as the asset's
ClaimGenerator the tool that created/edited the asset
Title claim dc:title
Format claim dc:format (declared media type)
AIGenerated a c2pa.actions digitalSourceType declares trainedAlgorithmicMedia / compositeWithTrainedAlgorithmicMedia
SoftwareAgent the tool the first c2pa.actions action names, as name/version (e.g. gpt-image/2.0) — the model or app, where ClaimGenerator is often the signing service
SignedBy COSE signer leaf-cert common name — unverified; the proven counterpart is ValidationResult.VerifiedSigner()
SignedAt RFC 3161 signing time — unverified; the proven counterpart is ValidationResult.SignedAt

Validate — full cryptographic verification

Validate is the verified counterpart. It performs the complete C2PA validation algorithm in pure Go and returns a structured result with per-step status codes:

f, _ := os.Open("photo.jpg")
defer f.Close()

r := c2pa.Validate(context.Background(), c2pa.JPEG, f)
if r.Valid {
    fmt.Println("verified, signed at", r.SignedAt)
} else {
    fmt.Println("not valid:", r.FirstFailure().Code)
}

// Inspect individual outcomes:
fmt.Println("signature verified:", r.Has(c2pa.StatusClaimSignatureValidated))
fmt.Println("signer trusted:", r.Has(c2pa.StatusSigningCredentialTrusted))
for _, s := range r.Statuses {
    fmt.Printf("[%v] %s — %s\n", s.Severity, s.Code, s.Explanation)
}

What it verifies:

  • COSE signature — the COSE_Sign1 over the claim (ES256/384/512, PS256/384/512, EdDSA).
  • Certificate chain + C2PA profile — chains the signer to the trust list and enforces the C2PA certificate profile (EKU, key usage, no weak algorithms), at the verified signing time.
  • Hash bindings — the hard binding and each assertion's hashed_uri. The hard binding is c2pa.hash.data for every container but BMFF, c2pa.hash.bmff.v2/.v3 for BMFF assets, or the structural c2pa.hash.boxes, which is verified for JPEG segments, PNG chunks and GIF blocks — the containers whose box naming C2PA defines. A box hash may only exclude the manifest store and asset metadata; an exclusion reaching anywhere else is a mismatch, not a permitted edit.
  • Merkle BMFF — a c2pa.hash.bmff.v3 merkle array is verified in full wherever the bytes are in hand. A non-fragmented asset whose mdat is hashed piecewise has its leaves cut from the box and the tree rebuilt; a fragmented asset in one flat file has its initialization hash checked and every chunk checked against the Merkle proof in the chunk's own merkle box; an asset split across files (DASH/CMAF) is verified with ValidateFragmented — see below. An initialization segment read on its own through Validate proves or disproves its hash, and the fragments it binds — other files — are named rather than folded into a success.
  • RFC 3161 timestamp — full CMS signature verification, the TSA chain, and that the timestamp covers this signature.
  • Revocation — OCSP/CRL, opt-in (off by default), soft-fail.
  • CAWG identity assertions — a cawg.identity assertion is a named actor's own signature, with their own credential, over some of the manifest's assertions (always the hard binding), following the CAWG Identity Assertion spec. Its CBOR, zero padding and references are checked against the claim, and an X.509 credential (cawg.x509.cose) gets the full signature, time-stamp, certificate-profile and revocation treatment at the identity's own URI. Identity anchors are separate from the claim signer's and there is no default list, so a genuine identity is cawg.identity.well-formed until WithIdentityTrust names a CA that vouches for it, and cawg.identity.trusted after; WithIdentityIssuers does the same job for an aggregator's DID. An aggregator's credential (cawg.identity_claims_aggregation — a W3C Verifiable Credential listing the identity signals an aggregator verified) is checked in full when its issuer is a did:jwk: the tagged COSE_Sign1, its application/vc content type, the credential's context and type, the issuer's key, the signature, the time-stamp, the validity window (against now, the credential's own time-stamp and the manifest's), the verified identities and the match with the assertion's payload (cawg.ica.credential_valid or the cawg.ica.* failure). did:web issuers, which need the network, are reported as an unsupported method; there is no issuer trust list yet, so an aggregation credential is well-formed, never trusted.
  • Update manifests — a manifest that adds assertions without changing the content (spec §11.2.3) carries no hard binding of its own, so one is not demanded of it. What binds the content is the manifest it updates, reached through its single parentOf ingredient, and that binding is verified against the asset — with its exclusion extended to the manifest store's current length (spec §15.12.1.1), since the update was appended to the store after that manifest signed it. An update manifest carrying a hard binding, a thumbnail, or an action that would change content is reported as invalid. For BMFF the updated store stays in the file under purpose original and both are read as one.
  • Ingredients — recursive validation of nested manifests, with cycle detection.

r.Valid is true exactly when no failure-severity status was recorded. r.Binding answers the narrower question "were these the signed bytes?" directly — verified, failed, unevaluated (a binding exists but this call did not evaluate it against these bytes: an object-level PDF manifest, an asset past the scan cap, a fragmented asset with fragments missing, a cancelled call) or none (nothing bound the asset) — so a consumer need not enumerate status codes to ask it, and "unevaluated" never collapses into "failed" or "passed". Like Read, Validate never returns an error and never panics — malformed or untrusted input is reported as failure statuses. It reads up to c2pa.ValidateMaxScan (256 MiB) so it can hash the whole asset; an asset larger than the cap reports an informational status rather than a false hash mismatch. A cancelled or expired context stops the work promptly — every loop, every hash and every network request honours it — and is reported as general.error carrying the context's error: a cancelled result is never Valid, and never a false mismatch. Read and ReadAll return nothing when cancelled, ExtractStore returns the context's error, and Sign returns an error for which errors.Is(err, ctx.Err()) holds, having written nothing.

Trust anchors and options

By default Validate uses the official C2PA conformance trust lists, embedded in the binary (see trustlists/). These are a point-in-time snapshot — refresh them periodically. Supply your own anchors and tune behaviour with options:

r := c2pa.Validate(ctx, c2pa.JPEG, f,
    c2pa.WithSigningTrust(myPool),       // override signing-anchor *x509.CertPool
    c2pa.WithTimestampTrust(myTSAPool),  // override TSA-anchor pool
    c2pa.WithIdentityTrust(identityCAs), // CAWG X.509 identity anchors (none by default)
    c2pa.WithIdentityIssuers(dids...),   // aggregator DIDs to believe (none by default)
    c2pa.WithOnlineRevocation(true),     // enable OCSP/CRL (network; default off)
    c2pa.WithRequireClaimSigningEKU(),   // insist on the c2pa-kp-claimSigning EKU (default: legacy EKUs too)
    c2pa.WithClock(func() time.Time { return now }), // signing-time fallback
    c2pa.WithMaxIngredientDepth(16),     // bound nested-manifest recursion
    c2pa.WithMaxScan(64 << 20),          // cap bytes read
    c2pa.WithHTTPClient(client),         // HTTP client for OCSP/CRL
)

ValidationResult also exposes Info (the same fields Read returns), ActiveManifestLabel, and the parsed SignerChain. Status codes mirror the C2PA specification §15 (e.g. claimSignature.validated, signingCredential.untrusted, assertion.dataHash.mismatch) and the CAWG identity codes (cawg.identity.trusted, cawg.identity.well-formed, cawg.identity.assertion.mismatch, …); each StatusEntry has a Severity (success / informational / failure).

Who vouched for it

r.Identities lists the active manifest's CAWG identity assertions — one per named actor who signed over the content. Each says whether the assertion is Valid (genuine signature, references intact) and whether the actor is Trusted — the credential reaches an anchor given with WithIdentityTrust (X.509) or names an aggregator listed in WithIdentityIssuers (an aggregation credential). Name() answers only when proven, like VerifiedSigner. An aggregation credential fills Issuer (the aggregator's DID) and VerifiedIdentities (the signals it vouched for: type, name, account, provider, when) — as the aggregator presented them.

Neither trust list has a default, because CAWG publishes neither. Name the aggregators you believe and a credential from one becomes cawg.identity.trusted, while a credential from anyone else is cawg.ica.untrusted_issuer — a failure, as the spec asks. Say nothing and a genuine credential stays cawg.identity.well-formed: real, and from an aggregator you have expressed no opinion about.

r := c2pa.Validate(ctx, c2pa.JPEG, f, c2pa.WithIdentityIssuers("did:jwk:eyJrdHkiOi…"))
r := c2pa.Validate(ctx, c2pa.JPEG, f, c2pa.WithIdentityTrust(identityCAs))
for _, id := range r.Identities {
    fmt.Println(id.Label, id.SigType, id.Roles, "over", id.Referenced)
    fmt.Println("valid:", id.Valid, "trusted:", id.Trusted, "actor:", id.Name())
    fmt.Println("presented as:", id.Chain[0].Subject.CommonName) // a claim, not a fact, until Trusted
}
What the content says about itself — soft bindings

A hard binding is a hash of the bytes, so it dies the moment anything re-encodes the asset. A soft binding is the spec's answer (§9.3.1): a perceptual identifier — an embedded watermark, or a fingerprint computed from the content — so that a re-encoded copy can still be matched to its manifest, and a manifest stripped from an asset can be recovered from a provenance store elsewhere.

r.SoftBindings lists the active manifest's, and this is the honest part: they are reported, never verified. This library computes none of the 53 registered algorithms, and it does not intend to — checking a soft binding means recomputing it over the asset and comparing within a tolerance, and a tolerance is a policy rather than a fact. So there is no Matched field to read, and no Valid: WellFormed is about the structure alone.

r := c2pa.Validate(ctx, c2pa.JPEG, f, c2pa.WithSigningTrust(pool))
for _, sb := range r.SoftBindings {
    fmt.Println(sb.Algorithm, "registered:", sb.AlgorithmRegistered, sb.AlgorithmType)
    for _, b := range sb.Blocks {
        fmt.Printf("  %x over %+v\n", b.Value, b.Scope) // hand this to a matcher, or a resolution API
    }
}

AlgorithmRegistered says the algorithm appears in the C2PA soft binding algorithm list as embedded in this build — a point-in-time snapshot (c2pa.SoftBindingListSnapshot dates it), so false may mean "registered upstream since" as much as "registered by nobody". §9.3.2 requires a listed algorithm, but an unlisted one is reported informationally rather than failed, because the list grows by third-party pull request and the spec's own worked example uses an identifier that is not in it.

A soft binding is never a content binding: §9.1 allows any number of them but the hard binding is what proves these bytes, and r.Binding is that answer. A manifest bound only by a soft binding still reports hardBinding.missing and is not Valid.

Fragmented BMFF (DASH / CMAF)

A streaming asset ships as an initialization segment (init.mp4: ftyp + moov, carrying the manifest) and media fragments (.m4s: moof + mdat, each carrying the Merkle proof that binds it). ValidateFragmented runs the whole pipeline over the initialization segment and checks every fragment against its proof, reading one fragment at a time. Supplying a subset is a legitimate partial check: it is reported as informational, never as a false match, and a fragment that has been tampered with fails at its own index.

init, _ := os.Open("video/init.mp4")
paths, _ := filepath.Glob("video/*.m4s")
frags := make([]io.Reader, 0, len(paths))
for _, p := range paths {
    f, _ := os.Open(p)
    defer f.Close()
    frags = append(frags, f)
}
r := c2pa.ValidateFragmented(ctx, init, frags)
fmt.Println(r.Valid, r.Binding) // "verified" only if every fragment was supplied and verified; "unevaluated" for a subset
for _, s := range r.Statuses {
    fmt.Println(s.Code, s.URI, s.Explanation) // a fragment failure's URI ends in "#fragment=<i>"
}

Sign — write Content Credentials

NewSigner takes a crypto.Signer and its certificate chain, leaf first (the root may be left out); Sign writes a copy of the asset with a c2pa.claim.v2 manifest embedded at the container's canonical position, bound to the content with c2pa.hash.data (or c2pa.hash.bmff.v3 for BMFF). The COSE algorithm follows the key. Nothing reaches out until the output has passed Validate: a signed asset this library could not verify is a bug, not an output.

keyPEM, _ := os.ReadFile("signer.key")  // PKCS#8, unencrypted
crtPEM, _ := os.ReadFile("signer.crt")  // leaf first, then any intermediates
kb, _ := pem.Decode(keyPEM)
key, _ := x509.ParsePKCS8PrivateKey(kb.Bytes)
var chain []*x509.Certificate
for b, rest := pem.Decode(crtPEM); b != nil; b, rest = pem.Decode(rest) {
    c, _ := x509.ParseCertificate(b.Bytes)
    chain = append(chain, c)
}

signer, err := c2pa.NewSigner(key.(crypto.Signer), chain,
    c2pa.WithClaimGenerator("my-app", "1.2.0"))
if err != nil {
    return err // ErrSignerKey / ErrSignerChain: the key or chain would not verify
}

in, _ := os.Open("photo.jpg")
out, _ := os.Create("photo-signed.jpg")
err = signer.Sign(ctx, c2pa.JPEG, in, out, c2pa.Manifest{
    Title: "photo.jpg",
    Actions: []c2pa.Action{{
        Action:            c2pa.ActionCreated, // this asset has no earlier provenance
        DigitalSourceType: c2pa.DigitalSourceTypeDigitalCapture,
    }},
})

A key that can only sign whole messages — WebCrypto, some HSM or KMS APIs — implements the standard crypto.MessageSigner too; Sign then hands it the COSE structure instead of a digest, with the same options and signature encoding x509.CreateCertificate uses.

The first action must be c2pa.created (nothing preceded this asset) or c2pa.opened (something did) — c2pa-rs rejects a manifest without one. Assertions adds your own, each a CBOR-encodable Value or raw JSON under any label the generated assertions do not reserve. Verify the result with your own anchor:

pool := x509.NewCertPool()
pool.AddCert(chain[len(chain)-1])
r := c2pa.Validate(ctx, c2pa.JPEG, signed, c2pa.WithSigningTrust(pool))
fmt.Println(r.Valid, r.VerifiedSigner()) // true "My Signer"

A self-signed test chain that satisfies the C2PA certificate profile (digitalSignature, a constrained EKU, not a CA):

openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 365 \
  -keyout signer.key -out signer.crt -subj "/CN=My Signer/O=Example" \
  -addext "keyUsage=critical,digitalSignature" \
  -addext "extendedKeyUsage=emailProtection" \
  -addext "basicConstraints=critical,CA:FALSE"

What c2pa-rs says. Every container's output is run through c2pa-rs's c2patool in CI (sign_interop_test.go). With a private chain it reports Valid with signingCredential.untrusted — correct, it has never seen your root; with c2patool photo-signed.jpg trust --trust_anchors signer.crt it reports Trusted; a re-signed asset lists the previous manifest as a parentOf ingredient with no failure deltas; a timestamped one reaches timeStamp.trusted once the TSA is anchored.

Timestamping is opt-in. With a TSA configured, Sign timestamps the signature (RFC 3161) after signing and embeds the token as sigTst2; the reply is verified with the same code Validate uses — imprint, CMS signature, nonce echo — before it is embedded, and a TSA failure is ErrTimestamp with nothing written. It is the one path that touches the network.

signer, err := c2pa.NewSigner(key, chain,
    c2pa.WithTimestampAuthority("https://timestamp.digicert.com"),
    c2pa.WithTimestampHTTPClient(&http.Client{Timeout: 10 * time.Second}))

Who vouches for it: CAWG identity. The claim says which tool signed; a CAWG identity assertion says which named actor — a photographer, a newsroom — stands behind the content, with their own key. WithIdentitySigner adds one to every manifest the Signer writes: a second COSE signature inside the manifest over the hard binding (always) and whatever Manifest.Identity adds, listed under the claim's gathered_assertions as c2pa-rs does. The payload is written in the field order c2patool re-serialises before verifying, so c2patool reports it cawg.identity.well-formed; this library reports cawg.identity.trusted once the actor's CA is anchored with WithIdentityTrust. The identity key may be the claim key; with a TSA configured the identity signature is timestamped too. One identity per Sign.

signer, err := c2pa.NewSigner(key, chain,
    c2pa.WithIdentitySigner(actorKey, actorChain)) // the named actor's own credential
err = signer.Sign(ctx, c2pa.JPEG, in, out, c2pa.Manifest{
    Title:   "photo.jpg",
    Actions: []c2pa.Action{{Action: c2pa.ActionCreated, DigitalSourceType: c2pa.DigitalSourceTypeDigitalCapture}},
    Identity: c2pa.IdentityInfo{
        Roles:      []string{c2pa.RoleCreator},        // cawg.creator, cawg.editor, … or com.example.reviewer
        References: []string{"c2pa.actions.v2"},        // further assertions the actor signs over
    },
})

Re-signing chains provenance. An asset that already carries Content Credentials keeps them: every prior manifest is carried into the new store verbatim and the previous active one becomes the new manifest's parentOf ingredient, with its validation results recorded as c2pa-rs requires. Open it with ActionOpened; ActionCreated on such an asset is ErrManifestInvalid, because a prior manifest proves something preceded it. ExampleSigner_Sign_resign in example_test.go does this to the ChatGPT PDF and verifies both signers.

Fragmented BMFF (DASH/CMAF). A streaming asset ships as an initialization segment plus .m4s fragments, bound by a Merkle tree over the fragments (§A.5.4). SignFragmented writes that: a C2PA merkle box into every fragment (before its moof, padded to one size) and the manifest — with the tree's row and the segment's own hash — into the initialization segment. Fragments are io.ReadSeekers because each is visited three times (hashed, verified, written), one in memory at a time however long the stream is; nothing is written until the whole set has passed ValidateFragmented.

init, _ := os.Open("video/init.mp4")
paths, _ := filepath.Glob("video/*.m4s")
frags := make([]io.ReadSeeker, len(paths))
outs := make([]io.Writer, len(paths))
for i, p := range paths {
    f, _ := os.Open(p)
    defer f.Close()
    frags[i] = f
    o, _ := os.Create(filepath.Join("signed", filepath.Base(p)))
    defer o.Close()
    outs[i] = o
}
outInit, _ := os.Create("signed/init.mp4")
err = signer.SignFragmented(ctx, init, frags, outInit, outs, c2pa.Manifest{
    Title:   "clip.mp4",
    Actions: []c2pa.Action{{Action: c2pa.ActionCreated, DigitalSourceType: c2pa.DigitalSourceTypeDigitalCapture}},
})

One tree per call, so sign each rendition separately. The sidx and tfhd offsets the inserted box moves are re-anchored (c2pa-rs leaves them stale), and a set c2pa-rs signed can be re-signed here. What c2patool says: c2patool init.mp4 fragment --fragments_glob "*.m4s" reports Trusted with assertion.bmffHash.match when the root is anchored via --settings; its fragment mode prints no JSON at all on any failure, an untrusted signer included. Both directions are asserted in CI.

Flat single-file fragmented MP4. The other fragmented arrangement keeps everything in one file — ftyp, moov, then moof/mdat pairs — and Sign(BMFF) recognises it and binds it with a Merkle tree over its own chunks: the manifest after ftyp, one merkle box before every moof, initHash over everything before the first one. There is nothing extra to call and no reference implementation to match, since c2pa-rs writes only the split form; c2patool reads the result as Trusted with assertion.bmffHash.match, which the interop CI job asserts. The absolute offsets the insertions move are repaired in their own scopes: stco/co64/saio/iloc under moov, each moof's tfhd base_data_offset, every top-level sidx (first_offset and each referenced_size) and every tfra moof_offset under mfra. A bare fragment — no moov — is still ErrFragmentedBMFF: that is SignFragmented's input.

Soft bindings. Manifest.SoftBindings writes c2pa.soft-binding assertions, and the value is yours to compute: this library implements no soft binding algorithm, so it takes the algorithm's output from you — the same layering as WithIdentitySigner, which takes a key rather than minting one. That way every algorithm in the C2PA list works, including the proprietary watermarks this package could never implement.

m := c2pa.Manifest{
    Title:   "photo.jpg",
    Actions: []c2pa.Action{{Action: c2pa.ActionCreated, DigitalSourceType: c2pa.DigitalSourceTypeDigitalCapture}},
    SoftBindings: []c2pa.SoftBindingInfo{{
        Algorithm: "io.iscc.v0",                                  // must be in the embedded list
        Blocks:    []c2pa.SoftBindingBlockInfo{{Value: iscc}},     // you computed this
    }},
}

Sign refuses an algorithm the embedded snapshot does not name — strict in what it emits, where Validate is liberal in what it accepts — and refuses a block with no value.

What goes in Value? For an ISCC (io.iscc.v0, ISO 24138 — the one open algorithm on the list), the parts are fingerprint.ISCCPixels for the normalisation and iscc-lib for the code:

pixels, _ := fingerprint.ISCCPixelsFromReader(f)
code, _ := iscc.GenImageCodeV0(pixels, 64)   // ISCC:EEA4GQZQTY6J5DTH
dec, _ := iscc.IsccDecode(code.Iscc)

m.SoftBindings = []c2pa.SoftBindingInfo{{
    Algorithm: "io.iscc.v0",
    Name:      code.Iscc,                                    // the canonical string, for humans
    Blocks:    []c2pa.SoftBindingBlockInfo{{Value: dec.Digest}}, // the raw digest, for matchers
}}

The byte format is a choice, not a rule: the spec says only "algorithm specific format" and the registry entry for ISCC defines none. The raw digest is used because the CDDL asks for a bstr where a text identifier would have wanted a tstr, because the Resolution API base64s the value, and because alg plus the length already say what the bytes are — with the canonical string carried in Name so nothing is lost. It is unverified against any third-party resolver, there being none to verify against. The hard binding is still written, as §9.1 requires. c2patool reads the result and its verdict is unchanged, which the interop suite asserts.

That recipe is worth more than the sum of its parts: the same image as a PNG, as a JPEG at quality 75, as a JPEG at quality 40 and as a palette GIF all produce the identical ISCC: code, while every one of those files has a different hard binding. That is what a soft binding buys. If you would rather not assemble it yourself, c2pa-mcp runs it end to end — c2pa-mcp sign photo.jpg out.jpg --soft-binding iscc — and reports the soft bindings it finds on verify, with the same report-don't-verify caveat this library attaches to them.

Limits. No soft binding algorithm is implemented, so a value must come from the caller and Validate reports the ones it finds without checking them (see above); encrypted (/Encrypt) or certified (/Perms) PDFs and ID3v2.2 MP3 tags are refused; only standard c2pa.claim.v2 manifests are written (no update manifests); one CAWG identity per manifest, X.509 only (no aggregator credentials, no expected_* fields); the store must fit in 64 MiB and the asset under ValidateMaxScan. Every existing store is removed and the new one written at the container's canonical position — deterministic, and a deliberate difference from c2pa-rs's replace-in-place.

Key COSE algorithm
ECDSA P-256 ES256
ECDSA P-384 ES384
ECDSA P-521 ES512
RSA ≥ 2048 bits PS256
Ed25519 EdDSA

PDF

PDF is the container with the most to say, so it gets worked examples. All three run as Example functions against testdata/c2pa_chatgpt.pdf — a real document from ChatGPT's image pipeline whose signer chains to a production trust anchor — so the output below is checked by go test, not written by hand.

Read a PDF, and check what the manifest is about

A PDF can carry a manifest describing an image or font inside it rather than the document (§A.4.3). That manifest's signer is not the document's, so Attribution is checked before SignedBy is reported — skipping that check is how a file gets credited to whoever signed a picture inside it.

info := c2pa.Read(ctx, c2pa.PDF, f)
if !info.Present {
    return // no Content Credentials
}
fmt.Println("generator:", info.ClaimGenerator)     // ChatGPT
fmt.Println("title:", info.Title)                  // image.pdf
fmt.Println("ai-generated:", info.AIGenerated)     // true

switch info.Attribution {
case c2pa.AttributionAsset:
    // The document's own structure associates this manifest.
    fmt.Println("signed by (claimed):", info.SignedBy)  // OpenAI Media Service
default:
    // A claim about something the document carries, or one nothing places.
    fmt.Println("manifest describes:", info.Attribution)
}
Verify it

VerifiedSigner() is the proven identity — empty unless the claim signature verified and the chain reached a trust anchor. Info.SignedBy is only what the file claims.

r := c2pa.Validate(ctx, c2pa.PDF, f)
fmt.Println("valid:", r.Valid)                                        // true
fmt.Println("verified signer:", r.VerifiedSigner())                   // OpenAI Media Service
fmt.Println("binding:", r.Binding)                          // verified
// This document carries no RFC 3161 timestamp, so the signing time is
// unproven and r.SignedAt stays zero.
fmt.Println("trusted timestamp:", !r.Has(c2pa.StatusTimeStampMissing)) // false
Enumerate every store the document carries

Only PDF returns more than one entry today: §A.4.1 embeds the document's own store as an associated file, and §A.4.3 lets an object carry a manifest of its own, so a document and the image inside it can both bear provenance. The first entry is exactly what Read returns.

for i, info := range c2pa.ReadAll(ctx, c2pa.PDF, f) {
    fmt.Printf("%d: %s signed by %q (%s)\n",
        i, info.Attribution, info.SignedBy, info.ClaimGenerator)
}
// 0: asset signed by "OpenAI Media Service" (ChatGPT)

A signed attachment inside an unsigned document is the case this exists for: Read alone would report the document as carrying no provenance, and ReadAll shows the attachment's — with AttributionEmbedded, so it is never mistaken for the document's own.

Lower-level

c2pa.ReadAll(ctx, container, r) enumerates every store an asset carries — the asset's own first, then the object-level manifests an object associates with itself (AttributionEmbedded), such as a signed image inside a PDF, then anything the C2PA markers find that nothing places (AttributionUnknown). Read is the first entry's view.

c2pa.ExtractStore(ctx, container, r) reads as far as Validate does (not Read's 16 MiB triage cap, since a store can sit at the very end of a large file) and returns the raw JUMBF manifest store exactly as it appears in the file, and c2pa.WalkBoxes(ctx, jumbf, fn) walks its box tree. Together they reach assertions Read doesn't model — the pair a manifest viewer wants. A nil store means none was found, not an error. Box nesting is depth-capped so adversarial input can't exhaust the stack.

store, err := c2pa.ExtractStore(ctx, c2pa.JPEG, file)
c2pa.WalkBoxes(ctx, store, func(label, tbox string, content []byte) {
    fmt.Printf("%s %s %d bytes\n", label, tbox, len(content))
})

Requirements

Sponsor

If this saves you time, you can sponsor its maintenance. Sponsorship pays for the unglamorous half — triage, dependency bumps, release plumbing — and is never a condition of getting help here.

License

MIT — see LICENSE. The test fixture under testdata/ is from contentauth/c2pa-rs (see testdata/README.md). The embedded trust lists under trustlists/ are the official C2PA conformance lists (see trustlists/README.md).


Extracted from file-search-on, where it powers the is_c2pa / c2pa_* search attributes.

Documentation

Overview

Package c2pa reads, verifies and writes C2PA / Content Credentials (https://c2pa.org) provenance manifests embedded in media files — JPEG, PNG, BMFF (MP4/MOV/HEIC/AVIF), RIFF (WebP/WAV/AVI), TIFF/DNG, GIF, MP3, SVG and PDF — in pure Go, with no cgo and no c2pa-rs.

Three entry points, kept deliberately separate:

  • Read surfaces what a file CLAIMS — creating tool, title, declared media type, AI-generated flag, signer identity and signing time — by parsing the embedded JUMBF manifest store (ISO 19566-5), decoding the active claim and its c2pa.actions assertion, and reading the COSE_Sign1 envelope's headers. It verifies nothing.
  • Validate runs the C2PA validation algorithm: the COSE signature, the certificate chain and C2PA certificate profile against a trust list, the hard binding and every assertion hash, the RFC 3161 timestamp, optional revocation, and ingredients — reporting the specification's §15 status codes. ValidateFragmented does the same over a DASH/CMAF asset split across files.
  • NewSigner and Signer.Sign write a c2pa.claim.v2 manifest carrying the container's hard binding, signed once with COSE_Sign1 and optionally timestamped, at the container's canonical position. An asset that already carries a manifest keeps it, chained as the new manifest's parentOf ingredient. The output is validated before a byte is written, and c2pa-rs's c2patool checks every container's output in CI.

Read is UNVERIFIED

Treat every Info field like EXIF or an email From header: accurate-as-recorded, not authenticated. SignedBy is who the file CLAIMS signed it, not a verified identity. A file with no manifest yields Info{Present:false}; absence of a signal (e.g. AIGenerated) does not prove its negation. Trust decisions belong to Validate.

Read and Validate are best-effort and never panic: malformed or truncated input yields zero values or failure statuses rather than an error. Every input-scaled loop, every hash and every network request honours the supplied context.Context, so a cancelled call surrenders promptly and says so: Read and ReadAll return nothing (Info{} and nil), ExtractStore returns ctx.Err(), Validate and ValidateFragmented record general.error carrying ctx.Err() — a cancelled result is never Valid — and Sign and SignFragmented return an error for which errors.Is(err, ctx.Err()) holds, having written nothing. Sign is otherwise the exception that returns an error — and it writes nothing when it does.

Example

Example reads the Content Credentials a JPEG claims, and surfaces the (unverified) creating tool, AI-generated flag, and signer identity.

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/richardwooding/c2pa"
)

func main() {
	f, err := os.Open("testdata/c2pa_signed.jpg")
	if err != nil {
		panic(err)
	}
	defer func() { _ = f.Close() }()

	info := c2pa.Read(context.Background(), c2pa.JPEG, f)
	if !info.Present {
		fmt.Println("no Content Credentials")
		return
	}
	fmt.Println("title:", info.Title)
	fmt.Println("ai-generated:", info.AIGenerated)
	// SignedBy is the CLAIMED signer — not cryptographically verified.
	fmt.Println("signed by:", info.SignedBy)
}
Output:
title: CA.jpg
ai-generated: false
signed by: C2PA Signer

Index

Examples

Constants

View Source
const (
	// ActionCreated says the asset was created here. It cannot be used on an
	// asset that already carries a manifest — a prior manifest proves that
	// something preceded this one.
	ActionCreated = "c2pa.created"
	// ActionOpened says an existing asset was opened; Sign records what was
	// opened as a parentOf ingredient, chaining any prior manifest.
	ActionOpened = "c2pa.opened"
)

Actions a Manifest's first action may be (spec §10.2: a standard manifest's actions assertion opens with the action that brought the asset into being or into this workflow).

View Source
const (
	DigitalSourceTypeEmpty                   = "http://c2pa.org/digitalsourcetype/empty"
	DigitalSourceTypeDigitalCapture          = "http://cv.iptc.org/newscodes/digitalsourcetype/digitalCapture"
	DigitalSourceTypeTrainedAlgorithmicMedia = "http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia"
)

Digital source types for Action.DigitalSourceType (IPTC NewsCodes; the "empty" value is C2PA's own).

View Source
const (
	RoleCreator     = "cawg.creator"
	RoleContributor = "cawg.contributor"
	RoleEditor      = "cawg.editor"
	RoleProducer    = "cawg.producer"
	RolePublisher   = "cawg.publisher"
	RoleSponsor     = "cawg.sponsor"
	RoleTranslator  = "cawg.translator"
)

Named-actor roles defined by the CAWG Identity Assertion spec (§5.2.3), for IdentityInfo.Roles.

View Source
const MaxScan = 16 << 20

MaxScan caps how many leading bytes Read consumes looking for a manifest. C2PA manifests sit in the file header (before image data) and rarely exceed a few MB even with embedded thumbnails; past the cap Read gives up.

View Source
const SoftBindingListSnapshot = "2026-08-20"

SoftBindingListSnapshot is the date of the embedded C2PA soft binding algorithm list snapshot, in RFC 3339 date form.

It matters because the list grows: a caller acting on SoftBinding.AlgorithmRegistered == false needs to know whether the answer is "nobody registered this" or "we have not looked since this date". Validate names it in the explanation of softBinding.alg.unlisted for the same reason.

View Source
const ValidateMaxScan = 256 << 20

ValidateMaxScan caps how many leading bytes Validate consumes — and, for ValidateFragmented, how many of each input. Unlike Read's MaxScan (tuned for fast manifest discovery), validation must hash the whole asset for hard-binding checks, so the cap is larger. Assets beyond it cannot have their data hash verified — that is reported as an informational status, never a false mismatch.

Variables

View Source
var (
	// ErrNoInput is returned when the reader or writer is nil.
	ErrNoInput = errors.New("c2pa: nil reader or writer")
	// ErrUnsupportedContainer is returned for a container Sign cannot write
	// into, or an asset with a feature this release does not write into.
	ErrUnsupportedContainer = errors.New("c2pa: container cannot be signed")
	// ErrFragmentedBMFF is returned by Sign for a fragmented MP4 (a 'moof',
	// 'sidx' or 'styp' box, or merkle boxes) — a DASH/CMAF asset is signed with
	// SignFragmented, as an initialization segment plus its fragments — and by
	// SignFragmented for an initialization segment that is itself fragmented.
	ErrFragmentedBMFF = errors.New("c2pa: fragmented BMFF")
	// ErrMalformedAsset is returned when the input does not parse as the named
	// container, or carries a manifest store that cannot be chained.
	ErrMalformedAsset = errors.New("c2pa: asset could not be parsed for embedding")
	// ErrAssetTooLarge is returned when the input reaches ValidateMaxScan.
	ErrAssetTooLarge = errors.New("c2pa: asset exceeds the signing size cap")
	// ErrStoreTooLarge is returned when the manifest store would exceed 64 MiB.
	ErrStoreTooLarge = errors.New("c2pa: manifest store exceeds the size cap")
	// ErrManifestInvalid is returned for a Manifest Sign will not write: no
	// leading c2pa.created/c2pa.opened action, a reserved or duplicate
	// assertion label, an unencodable value, or c2pa.created on an asset that
	// already carries a manifest.
	ErrManifestInvalid = errors.New("c2pa: manifest is invalid")
	// ErrSignerKey is returned for a key whose type or size no COSE algorithm
	// the C2PA profile allows can use.
	ErrSignerKey = errors.New("c2pa: signing key unusable")
	// ErrSignerChain is returned for a certificate chain that does not match
	// the key, does not link, is not currently valid, or fails the C2PA
	// certificate profile Validate enforces.
	ErrSignerChain = errors.New("c2pa: certificate chain rejected")
	// ErrSignerOption is returned for an option value that cannot be used.
	ErrSignerOption = errors.New("c2pa: signer option invalid")
	// ErrTimestamp is returned when the timestamp authority named by
	// WithTimestampAuthority could not be reached, rejected the request, or
	// returned a token that does not verify over this signature or does not
	// echo the request's nonce. Nothing is written.
	ErrTimestamp = errors.New("c2pa: timestamp authority")
	// ErrSelfCheckFailed is returned when the signed output fails this
	// package's own Validate; nothing is written when it does.
	ErrSelfCheckFailed = errors.New("c2pa: signed output did not validate")
)

Errors Sign and NewSigner return. Every error is wrapped with detail; test with errors.Is.

View Source
var ErrFragmentSet = errors.New("c2pa: fragment set unusable")

ErrFragmentSet is returned by SignFragmented for a fragment set it cannot work with: none given, a writer count that differs from the reader count, more fragments than a Merkle tree may have leaves, a reader that cannot seek back to its start, or a fragment whose bytes changed between passes.

Functions

func ExtractStore added in v0.7.0

func ExtractStore(ctx context.Context, container Container, r io.Reader) ([]byte, error)

ExtractStore returns the raw JUMBF manifest store embedded in r, byte for byte as it appears in the file, or nil when the container carries none.

It is the byte-level counterpart to Read: WalkBoxes over the result reaches boxes and assertions Info does not model, which is what a manifest viewer needs. Reading is capped at ValidateMaxScan — Validate's cap, not Read's: a store can sit at the very end of a large asset (a PDF's incremental update, a BMFF box after mdat), and a viewer should find whatever Validate validates. Read keeps its 16 MiB triage cap by design. A nil store is "none found", not a failure — err is non-nil only when r itself errors or ctx ends, in which case the store is nil too: a truncated box tree is not the store.

func WalkBoxes

func WalkBoxes(ctx context.Context, jumbf []byte, fn func(label, tbox string, content []byte))

WalkBoxes recursively walks a JUMBF box tree, invoking fn(label, tbox, content) for every leaf box. label is the nearest enclosing superbox's jumd label, tbox is the 4-character box type, and content is the box payload. Nesting is capped at an internal depth limit so adversarial input cannot exhaust the stack; ctx is honoured at the top of every iteration, and the walk simply stops when it ends — check ctx.Err() afterwards to tell a cancelled walk from a short store.

This is a lower-level primitive — most callers want Read. It is exported for advanced use (e.g. surfacing assertions Read does not model).

Types

type Action added in v0.15.0

type Action struct {
	Action            string
	DigitalSourceType string
	SoftwareAgent     GeneratorInfo
	Parameters        map[string]any
}

Action is one entry of the c2pa.actions.v2 assertion. DigitalSourceType is recommended for ActionCreated. Parameters are copied as given; for the first action of an ActionOpened manifest Sign adds parameters.ingredients itself, pointing at the parentOf ingredient.

type Assertion added in v0.15.0

type Assertion struct {
	Label string
	Value any
	JSON  []byte
}

Assertion is a caller-supplied assertion. Exactly one of Value (encoded as deterministic CBOR — a cbor.RawMessage passes through verbatim) or JSON (written as a JSON content box) must be set.

type Attribution added in v0.6.0

type Attribution string

Attribution says what a manifest is a claim about. A container can carry a manifest describing a file inside the asset rather than the asset itself, and the C2PA markers on the two are identical, so only a reference from the document's own structure separates them.

const (
	// AttributionNone is the zero value: no manifest, nothing to attribute.
	AttributionNone Attribution = ""
	// AttributionAsset means the asset's own structure associates the manifest,
	// so it is a claim about the asset.
	AttributionAsset Attribution = "asset"
	// AttributionEmbedded means the asset's structure associates the manifest
	// with something the asset CARRIES rather than with the asset itself — a
	// PDF object-level manifest (spec §A.4.3), attached to the image, font or
	// other stream whose provenance it records. The attribution is resolved,
	// not guessed; what it says is that this is a claim about an embedded
	// resource. Do not report its signer or generator as the asset's.
	AttributionEmbedded Attribution = "embedded"
	// AttributionUnknown means the manifest was identified by its markers alone,
	// with nothing associating it with the asset. It may be an embedded
	// resource's manifest whose referring object could not be resolved, or the
	// reference may simply be unreadable. Do not report its signer or generator
	// as the asset's.
	AttributionUnknown Attribution = "unknown"
)

type BindingState added in v0.19.0

type BindingState int

BindingState says what the active manifest's hard binding proved about the bytes this call evaluated — the question "were these the signed bytes?", answered without reading status codes. It is recorded at the decision point rather than derived from Statuses afterwards: an update manifest's binding statuses carry the PARENT manifest's label, and general.unsupported is used for several unrelated things, so no reading of Statuses reconstructs it.

Valid is a different question. A manifest whose claim signature fails can still have BindingVerified (the bytes are the ones that manifest signed), and a manifest with a rejected timestamp is not Valid though its binding held.

const (
	// BindingNone: nothing bound the asset — no manifest, no usable hard
	// binding (a v1 c2pa.hash.bmff only, a BMFF binding on a non-BMFF asset, a
	// manifest without one), or an update manifest rejected before the parent
	// manifest that binds the content was reached (hardBinding.missing).
	BindingNone BindingState = iota
	// BindingVerified: a hard binding covered these bytes and held —
	// assertion.dataHash.match, assertion.boxesHash.match or, over a whole
	// file or a complete fragment set, assertion.bmffHash.match.
	BindingVerified
	// BindingFailed: a hard binding covered these bytes and did not hold — a
	// mismatch, or a binding too malformed or too weakly hashed to check
	// (*.mismatch, *.malformed, *.unknownBox, algorithm.unsupported).
	BindingFailed
	// BindingUnevaluated: a hard binding exists but this call did not evaluate
	// it against these bytes — an object-level PDF manifest whose subject is an
	// embedded object (§A.4.3), an asset past the scan cap, a fragmented asset
	// with fragments missing or unreadable, an initialization segment read on
	// its own, a container with no box map for c2pa.hash.boxes, merkle maps
	// that do not fit the file, or a cancelled call. Neither failed nor passed:
	// ask a different question, or supply the fragments.
	BindingUnevaluated
)

func (BindingState) String added in v0.19.0

func (s BindingState) String() string

String returns "none", "verified", "failed" or "unevaluated".

type Container

type Container string

Container identifies the carrier file format whose C2PA manifest to read.

const (
	// JPEG reads the manifest from APP11 (0xFFEB) marker segments.
	JPEG Container = "jpeg"
	// PNG reads the manifest from caBX chunks.
	PNG Container = "png"
	// BMFF reads the manifest from a top-level C2PA `uuid` box in any ISO Base
	// Media File Format file: MP4, MOV, M4A, HEIC, HEIF, AVIF. One constant
	// covers every brand — the carrier mechanics are identical; sniff the ftyp
	// brand yourself if you need to distinguish them. Note that Read's MaxScan
	// (16 MiB) can miss a manifest box placed after a large mdat; Validate's
	// larger cap usually will not.
	BMFF Container = "bmff"
	// PDF reads the manifest from the embedded file the document catalog
	// associates with the relationship /C2PA_Manifest (spec §A.4). An
	// incremental update appends a new store and the newest is the active one.
	// Note that Read's MaxScan (16 MiB) can miss the store in a large document,
	// since the embedded file sits wherever the producer appended it; Validate's
	// larger cap usually will not.
	PDF Container = "pdf"
	// RIFF reads the manifest from a top-level `C2PA` chunk in any RIFF asset:
	// WebP, WAV, AVI. One constant covers all three — like BMFF, the carrier
	// mechanics are identical and only the form type differs. An AVI over 1 GB
	// spills into further RIFF/AVIX containers, but the store lives in the
	// first.
	RIFF Container = "riff"
	// TIFF reads the manifest from IFD tag 0xCD41 in a TIFF, BigTIFF or DNG
	// file — classic and BigTIFF are the same walk at different field widths.
	TIFF Container = "tiff"
	// GIF reads the manifest from the application extension whose identifier is
	// "C2PA_GIF", its payload reassembled from the extension's data sub-blocks.
	GIF Container = "gif"
	// MP3 reads the manifest from an ID3v2 GEOB frame whose MIME type is
	// application/c2pa. An unsynchronised tag (v2.3 tag-level, v2.4 per-frame)
	// is restored before it is read.
	MP3 Container = "mp3"
	// SVG reads the manifest from a base64 <c2pa:manifest> element bound to
	// http://c2pa.org/manifest. The document is parsed as XML, not scanned.
	SVG Container = "svg"
)

type GeneratorInfo added in v0.15.0

type GeneratorInfo struct {
	Name    string
	Version string
}

GeneratorInfo names a piece of software: claim_generator_info and an action's softwareAgent. Version is optional.

type Identity added in v0.18.0

type Identity struct {
	// Label is the assertion label: "cawg.identity", or "cawg.identity__1", …
	// when a manifest carries several.
	Label string
	// URI is the URI this identity's statuses are recorded under:
	// "<manifest label>/<Label>".
	URI string
	// SigType is signer_payload.sig_type: "cawg.x509.cose" for an X.509
	// credential, "cawg.identity_claims_aggregation" for an aggregator's
	// verifiable credential.
	SigType string
	// Roles are the named actor's declared roles (e.g. "cawg.creator"), as
	// PRESENTED.
	Roles []string
	// Referenced lists the labels of the assertions the actor signed over, in
	// payload order.
	Referenced []string
	// Chain is the actor's certificate chain as PRESENTED (X.509 only), leaf
	// first, populated whether or not it verified — like SignerChain.
	Chain []*x509.Certificate
	// Issuer is the aggregator's DID (identity claims aggregation only), as
	// PRESENTED — e.g. "did:jwk:…". Only did:jwk is resolved and verified.
	Issuer string
	// VerifiedIdentities are the identity signals an aggregator vouched for
	// (identity claims aggregation only), as PRESENTED by the aggregator.
	VerifiedIdentities []VerifiedIdentity
	// SignedAt is the signing time from a TRUSTED timestamp on the identity
	// signature, or zero — like ValidationResult.SignedAt.
	SignedAt time.Time
	// Valid: the assertion is well-formed and its signature verifies —
	// cawg.identity.well-formed or cawg.identity.trusted was recorded. For an
	// aggregation credential that means cawg.ica.credential_valid AND an issuer
	// that is either trusted or not evaluated: an issuer ruled out by
	// WithIdentityIssuers is cawg.ica.untrusted_issuer, a failure, and leaves
	// this false even though the credential itself verified.
	Valid bool
	// Trusted: Valid, and the credential reaches a root of trust — an X.509
	// chain anchored by WithIdentityTrust, or an aggregator DID named by
	// WithIdentityIssuers. Neither has a default, so an identity is never
	// Trusted unless the caller said whom to believe. Only then is the actor
	// proven, and only then does Name() answer.
	Trusted bool
}

Identity is one CAWG identity assertion (cawg.identity) of the active manifest: a named actor's signature, made with the actor's own credential, over some of the manifest's assertions — always including the hard binding, so the actor vouches for the content bytes as well. See ValidationResult.Identities.

Valid is about the identity assertion alone: its CBOR, padding and references check and its signature verifies. A manifest whose own claim signature fails can still carry a Valid identity, and an asset with an invalid identity is itself invalid; ValidationResult.Valid is the verdict.

func (Identity) Name added in v0.18.0

func (id Identity) Name() string

Name returns the actor's name, ONLY when Trusted — exactly as ValidationResult.VerifiedSigner does for the claim signer. Otherwise "".

For an X.509 identity that is the leaf certificate's Subject Common Name, falling back to its first Organization; the name as presented, proven or not, is Chain[0].Subject. For an identity claims aggregation credential it is the first VerifiedIdentities entry to carry a Name or a Username — and it is the AGGREGATOR'S word, proven only as far as that aggregator is trusted, which is what putting its DID in WithIdentityIssuers asserts.

type IdentityInfo added in v0.18.0

type IdentityInfo struct {
	// Roles are the actor's roles in producing the asset — the Role* constants
	// (CAWG spec §5.2.3) or an entity-namespaced label such as
	// "com.example.reviewer". Optional.
	Roles []string
	// References names further assertions of this manifest the actor signs
	// over, by label: "c2pa.actions.v2", a caller assertion's label, … The hard
	// binding is always referenced and must not be listed. Each label at most
	// once, and each must exist in the manifest being written.
	References []string
}

IdentityInfo describes the named actor's relationship to an asset for the CAWG identity assertion (cawg.identity) a Signer with WithIdentitySigner writes. See ValidationResult.Identities for how it reads back.

type IdentityProvider added in v0.19.0

type IdentityProvider struct {
	ID   string
	Name string
}

IdentityProvider names the service that issued an identity signal.

type Info

type Info struct {
	// Present is true when a C2PA manifest was found and parsed.
	Present bool
	// Attribution says whether the manifest is a claim about this asset. Only
	// PDF can currently return AttributionUnknown; the other containers give a
	// manifest no place to hide that the carrier does not point at.
	Attribution Attribution
	// ClaimGenerator is the tool that created/edited the asset (e.g.
	// "Adobe Firefly", "make_test_images/0.33.1 c2pa-rs/0.33.1").
	ClaimGenerator string
	// Title is the claim's dc:title.
	Title string
	// Format is the claim's dc:format (declared media type).
	Format string
	// AIGenerated is true when a c2pa.actions assertion declares a
	// digitalSourceType of trainedAlgorithmicMedia or
	// compositeWithTrainedAlgorithmicMedia.
	AIGenerated bool
	// SoftwareAgent is the tool the first c2pa.actions action that names one
	// says performed it, as "name/version" (e.g. "gpt-image/2.0"). It is the
	// model or application, where ClaimGenerator is the signing service.
	// Empty when no action names one. UNVERIFIED, like every Read field.
	SoftwareAgent string
	// SignedBy is the COSE_Sign1 signer's leaf x509 certificate common name
	// (Subject CN, falling back to the first Organization). UNVERIFIED — the
	// certificate chain is not validated against the C2PA trust list.
	SignedBy string
	// SignedAt is the signing time from the RFC 3161 timestamp embedded in the
	// signature (sigTst). Zero when absent. UNVERIFIED.
	SignedAt time.Time
}

Info is the surfaced, CLAIMED, UNVERIFIED subset of a C2PA manifest. See the package doc: these are the file's assertions, not authenticated facts.

func Read

func Read(ctx context.Context, container Container, r io.Reader) Info

Read reads up to MaxScan bytes from r and, for the given container, locates and parses the embedded JUMBF manifest. It returns a zero Info (Present=false) when there's no manifest. It never returns an error — provenance is best-effort metadata, surfaced like EXIF.

ctx is honoured throughout — the read, the input-scaled scan loops and the manifest parse — and a cancelled call returns Info{} rather than whatever had been parsed by then: a partial Info presented as complete would be the read path's version of a false verdict.

Example (Pdf)

ExampleRead_pdf reads the Content Credentials a PDF claims. The fixture is a real document from ChatGPT's image pipeline, so unlike the JPEG above its signer chains to a production trust anchor.

Attribution is checked BEFORE the signer is reported. A PDF can carry a manifest describing an image or font inside it rather than the document (spec §A.4.3), and that manifest's signer is not the document's — reading SignedBy without this check is how a file gets credited to whoever signed a picture inside it.

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/richardwooding/c2pa"
)

func main() {
	f, err := os.Open("testdata/c2pa_chatgpt.pdf")
	if err != nil {
		panic(err)
	}
	defer func() { _ = f.Close() }()

	info := c2pa.Read(context.Background(), c2pa.PDF, f)
	if !info.Present {
		fmt.Println("no Content Credentials")
		return
	}
	fmt.Println("generator:", info.ClaimGenerator)
	fmt.Println("title:", info.Title)
	fmt.Println("ai-generated:", info.AIGenerated)

	switch info.Attribution {
	case c2pa.AttributionAsset:
		// The document's own structure associates this manifest.
		fmt.Println("signed by (claimed):", info.SignedBy)
	default:
		// A claim about something the document carries, or one nothing places.
		fmt.Println("manifest describes:", info.Attribution)
	}
}
Output:
generator: ChatGPT
title: image.pdf
ai-generated: true
signed by (claimed): OpenAI Media Service

func ReadAll added in v0.9.0

func ReadAll(ctx context.Context, container Container, r io.Reader) []Info

ReadAll returns one Info per manifest store the asset carries: the store the asset's own structure associates first, with AttributionAsset; then the object-level manifests an object associates with itself, with AttributionEmbedded; then whatever the C2PA markers alone identify, with AttributionUnknown. Nil when there is none.

Only PDF can return more than one entry today — §A.4.1 embeds a store as an associated file, and §A.4.3 lets an object carry a manifest of its own, so a document and the image inside it can both bear provenance. Read is exactly the first entry's view; a triage caller that wants to see a signed attachment inside an unsigned document is who this is for. It grew out of the review discussion on the PDF containers (#14).

Like Read: unverified, non-failing, capped at MaxScan.

Example (Pdf)

ExampleReadAll_pdf enumerates every manifest store a PDF carries. Only PDF returns more than one today: §A.4.1 embeds the document's own store as an associated file, and §A.4.3 lets an object carry a manifest of its own, so a document and the image inside it can both bear provenance. The first entry is exactly what Read returns.

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/richardwooding/c2pa"
)

func main() {
	f, err := os.Open("testdata/c2pa_chatgpt.pdf")
	if err != nil {
		panic(err)
	}
	defer func() { _ = f.Close() }()

	for i, info := range c2pa.ReadAll(context.Background(), c2pa.PDF, f) {
		fmt.Printf("%d: %s signed by %q (%s)\n",
			i, info.Attribution, info.SignedBy, info.ClaimGenerator)
	}
}
Output:
0: asset signed by "OpenAI Media Service" (ChatGPT)

type Manifest added in v0.15.0

type Manifest struct {
	Title      string
	Actions    []Action
	Assertions []Assertion
	// SoftBindings are written as c2pa.soft-binding assertions (§18.10):
	// perceptual identifiers that let a re-encoded copy be matched back to this
	// manifest. The VALUE is the caller's to compute — this library implements
	// no soft binding algorithm — and the algorithm must be one the embedded
	// C2PA list names. §9.1 allows any number of them alongside the hard
	// binding Sign always writes.
	SoftBindings []SoftBindingInfo
	// Identity is what the CAWG identity assertion Sign writes says about the
	// named actor's relationship to this asset. It is used only when the
	// Signer has WithIdentitySigner; setting it without one is
	// ErrManifestInvalid. The zero value is fine: the identity then vouches for
	// the hard binding alone, with no roles.
	Identity IdentityInfo
}

Manifest is what a Sign call says about one asset. Actions is required and its first entry must be ActionCreated or ActionOpened; Sign refuses a manifest without one rather than defaulting to "created", which would be a provenance claim the caller did not make. Assertions are written after the ones Sign generates (the hard binding, the ingredient, the actions); their labels may not be ones Sign writes itself.

type Severity added in v0.2.0

type Severity int

Severity classifies a StatusCode as success, informational, or failure. Only failures flip ValidationResult.Valid to false.

const (
	// SeverityInformational is advisory: the step ran but its outcome neither
	// proves nor disproves validity (e.g. revocation status unknown, an
	// unsupported-but-not-fatal feature, an absent optional timestamp).
	SeverityInformational Severity = iota
	// SeveritySuccess records a validation step that passed.
	SeveritySuccess
	// SeverityFailure records a validation step that failed. Any failure makes
	// the manifest invalid.
	SeverityFailure
)

type Signer added in v0.15.0

type Signer struct {
	// contains filtered or unexported fields
}

Signer signs assets with Content Credentials. It is configured once with what is per-signer — the key, its certificate chain, the claim generator — and Sign takes what is per-asset. A Signer keeps no per-call state, so it is safe for concurrent use to the extent its key is.

The COSE algorithm is inferred from the key's public half (§14.5.1): P-256 → ES256, P-384 → ES384, P-521 → ES512, RSA of at least 2048 bits → PS256, Ed25519 → EdDSA. Any crypto.Signer works — an in-memory key, an HSM or KMS wrapper, or a WebCrypto-backed key in a browser. Counterpart: c2pa-rs's Signer trait.

func NewSigner added in v0.15.0

func NewSigner(key crypto.Signer, chain []*x509.Certificate, opts ...SignerOption) (*Signer, error)

NewSigner validates the key and chain up front so that Sign can only fail on the asset. chain is leaf first, then intermediates; the trust anchor may be omitted — validators build the path to their own anchors, so a root in the file is dead weight — and a single self-signed certificate is accepted. The leaf must match the key, each certificate must be issued by the next, the leaf must be valid now, and the chain must satisfy the C2PA certificate profile (§14.5.2) exactly as Validate enforces it: digitalSignature key usage, a constrained signing EKU, a non-CA leaf, no SHA-1/MD5, RSA of at least 2048 bits. Never panics.

A key that can only sign whole messages — WebCrypto's SubtleCrypto.sign, some HSM and KMS APIs — implements the standard crypto.MessageSigner as well. Sign then hands it the COSE Sig_structure instead of a digest, with the opts and signature encoding x509.CreateCertificate uses (the hash for ECDSA, PSS options for RSA, crypto.Hash(0) for Ed25519; DER for ECDSA, raw for the others), and never calls its Sign method.

func (*Signer) Sign added in v0.15.0

func (s *Signer) Sign(ctx context.Context, container Container, in io.Reader, out io.Writer, m Manifest) error

Sign reads the whole asset from in (up to ValidateMaxScan), builds a c2pa.claim.v2 manifest carrying the container's hard binding, signs it once with COSE_Sign1 into an envelope of reserved size, embeds the manifest store where the C2PA specification puts it for that container (Annex A), validates the result with this package's own Validate, and only then writes it to out. On any error nothing is written.

An asset that already carries a manifest store keeps every prior manifest: they are carried into the new store verbatim and the new manifest names the previous active one as its parentOf ingredient, so provenance chains rather than being replaced. The manifest's first action must then be ActionOpened.

BMFF assets (MP4, MOV, HEIC, AVIF) are bound with c2pa.hash.bmff.v3 and the C2PA box is inserted after 'ftyp', with every 'stco', 'co64', 'saio' and 'iloc' offset rewritten to follow. A fragmented file is refused with ErrFragmentedBMFF: a DASH/CMAF asset — an initialization segment and its fragments — is signed with SignFragmented.

Like Validate, Sign never panics; malformed or oversized input, a manifest it will not write, or a failed self-check is an error. Counterpart: c2pa-rs's Builder::sign.

Example

ExampleSigner_Sign signs an MP4 that carries no Content Credentials with a c2pa.created manifest, then verifies the result with the signer's own root as the trust anchor. Nothing is written unless the output already validates, so the verdict here is the same one Sign checked before returning.

package main

import (
	"bytes"
	"context"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/x509"
	"crypto/x509/pkix"
	"fmt"
	"math/big"
	"os"
	"time"

	"github.com/richardwooding/c2pa"
)

// exampleSigner mints a self-signed P-256 certificate that satisfies the C2PA
// certificate profile (digitalSignature key usage, an emailProtection EKU, not
// a CA) and returns a Signer for it plus a pool that trusts it. A deployment
// loads a key and a CA-issued chain from PEM instead; the README shows how.
func exampleSigner() (*c2pa.Signer, *x509.CertPool) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		panic(err)
	}
	tmpl := &x509.Certificate{
		SerialNumber:          big.NewInt(1),
		Subject:               pkix.Name{CommonName: "Example Signer", Organization: []string{"Example Org"}},
		NotBefore:             time.Now().Add(-time.Hour),
		NotAfter:              time.Now().Add(24 * time.Hour),
		KeyUsage:              x509.KeyUsageDigitalSignature,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageEmailProtection},
		BasicConstraintsValid: true,
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
	if err != nil {
		panic(err)
	}
	cert, err := x509.ParseCertificate(der)
	if err != nil {
		panic(err)
	}
	signer, err := c2pa.NewSigner(key, []*x509.Certificate{cert}, c2pa.WithClaimGenerator("example", "1.0"))
	if err != nil {
		panic(err)
	}
	pool := x509.NewCertPool()
	pool.AddCert(cert)
	return signer, pool
}

func main() {
	signer, pool := exampleSigner()
	ctx := context.Background()

	in, err := os.Open("testdata/video_no_manifest.mp4")
	if err != nil {
		panic(err)
	}
	defer func() { _ = in.Close() }()

	var signed bytes.Buffer
	m := c2pa.Manifest{
		Title: "clip.mp4",
		Actions: []c2pa.Action{{
			Action:            c2pa.ActionCreated,
			DigitalSourceType: c2pa.DigitalSourceTypeDigitalCapture,
		}},
	}
	if err := signer.Sign(ctx, c2pa.BMFF, in, &signed, m); err != nil {
		panic(err)
	}

	r := c2pa.Validate(ctx, c2pa.BMFF, bytes.NewReader(signed.Bytes()), c2pa.WithSigningTrust(pool))
	fmt.Println("valid:", r.Valid)
	fmt.Println("content bound:", r.Has(c2pa.StatusAssertionBMFFHashMatch))
	fmt.Println("verified signer:", r.VerifiedSigner())
	fmt.Println("title:", r.Info.Title)
}
Output:
valid: true
content bound: true
verified signer: Example Signer
title: clip.mp4
Example (Resign)

ExampleSigner_Sign_resign signs an asset that already carries Content Credentials — the ChatGPT PDF, signed by OpenAI. The existing manifest is kept and becomes the new manifest's parentOf ingredient — provenance is chained, never replaced — which is why the manifest must open with c2pa.opened rather than c2pa.created. For PDF the new store arrives as an incremental update; nothing before the previous %%EOF changes.

WithSigningTrust REPLACES the embedded trust list, so the prior signer's chain (as the file presents it) is added to the pool to let the ingredient validate too. With only the new signer trusted the new manifest still verifies, and the ingredient's untrusted signer is reported, not hidden.

package main

import (
	"bytes"
	"context"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/x509"
	"crypto/x509/pkix"
	"fmt"
	"math/big"
	"os"
	"time"

	"github.com/richardwooding/c2pa"
)

// exampleSigner mints a self-signed P-256 certificate that satisfies the C2PA
// certificate profile (digitalSignature key usage, an emailProtection EKU, not
// a CA) and returns a Signer for it plus a pool that trusts it. A deployment
// loads a key and a CA-issued chain from PEM instead; the README shows how.
func exampleSigner() (*c2pa.Signer, *x509.CertPool) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		panic(err)
	}
	tmpl := &x509.Certificate{
		SerialNumber:          big.NewInt(1),
		Subject:               pkix.Name{CommonName: "Example Signer", Organization: []string{"Example Org"}},
		NotBefore:             time.Now().Add(-time.Hour),
		NotAfter:              time.Now().Add(24 * time.Hour),
		KeyUsage:              x509.KeyUsageDigitalSignature,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageEmailProtection},
		BasicConstraintsValid: true,
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
	if err != nil {
		panic(err)
	}
	cert, err := x509.ParseCertificate(der)
	if err != nil {
		panic(err)
	}
	signer, err := c2pa.NewSigner(key, []*x509.Certificate{cert}, c2pa.WithClaimGenerator("example", "1.0"))
	if err != nil {
		panic(err)
	}
	pool := x509.NewCertPool()
	pool.AddCert(cert)
	return signer, pool
}

func main() {
	signer, pool := exampleSigner()
	ctx := context.Background()

	fixture, err := os.ReadFile("testdata/c2pa_chatgpt.pdf")
	if err != nil {
		panic(err)
	}
	prior := c2pa.Validate(ctx, c2pa.PDF, bytes.NewReader(fixture))
	pool.AddCert(prior.SignerChain[len(prior.SignerChain)-1])

	var signed bytes.Buffer
	m := c2pa.Manifest{
		Title:   "image-edited.pdf",
		Actions: []c2pa.Action{{Action: c2pa.ActionOpened}},
	}
	if err := signer.Sign(ctx, c2pa.PDF, bytes.NewReader(fixture), &signed, m); err != nil {
		panic(err)
	}

	r := c2pa.Validate(ctx, c2pa.PDF, bytes.NewReader(signed.Bytes()), c2pa.WithSigningTrust(pool))
	fmt.Println("valid:", r.Valid)
	fmt.Println("title:", r.Info.Title)
	fmt.Println("verified signer:", r.VerifiedSigner())
	fmt.Println("ingredient validated:", r.Has(c2pa.StatusIngredientManifestValidated))
	fmt.Println("prior signer:", prior.VerifiedSigner())
}
Output:
valid: true
title: image-edited.pdf
verified signer: Example Signer
ingredient validated: true
prior signer: OpenAI Media Service

func (*Signer) SignFragmented added in v0.17.0

func (s *Signer) SignFragmented(ctx context.Context, init io.Reader, fragments []io.ReadSeeker, outInit io.Writer, outFragments []io.Writer, m Manifest) error

SignFragmented signs a fragmented BMFF asset — a DASH/CMAF initialization segment ('ftyp' and 'moov') and its media fragments ('styp', 'sidx', 'moof', 'mdat') as separate files — binding every fragment through a Merkle tree (§A.5.4): each fragment gains a C2PA merkle box before its 'moof' with its leaf's proof, and the initialization segment gains the manifest, whose c2pa.hash.bmff.v3 carries the tree's row and the segment's own hash. The counterpart of c2pa-rs's Builder::sign_fragmented_files, and what ValidateFragmented verifies.

fragments are ReadSeekers because each is visited more than once — hashed, verified in the self-check, written — one at a time, so memory is the initialization segment plus one fragment however long the stream is. outFragments receive the signed fragments in the same order as fragments and must be as many; outInit receives the signed initialization segment. Nothing is written until the whole set has passed ValidateFragmented; the fragments are then written first and the initialization segment last, so a write that fails midway leaves an unsigned segment beside playable fragments rather than a signed segment over unsigned ones.

One tree per call (uniqueId and localId 1): sign each rendition separately. The 'sidx' first_offset before the insertion, and a 'tfhd' base_data_offset, are re-anchored to the moved 'moof' — including the stale ones c2pa-rs leaves behind, so its output can be re-signed here. An asset already signed keeps its manifest as the new one's parentOf ingredient, exactly as Sign does, and its old merkle boxes are replaced. An initialization segment that is itself a fragmented file, or a fragment, is refused with ErrFragmentedBMFF; a fragment with more than one 'moof' or 'mdat' with ErrUnsupportedContainer.

type SignerOption added in v0.15.0

type SignerOption func(*signerConfig)

SignerOption configures a Signer. See the With* constructors.

func WithClaimGenerator added in v0.15.0

func WithClaimGenerator(name, version string) SignerOption

WithClaimGenerator sets claim_generator_info, the software that produced the manifest (default: this module's path and version).

func WithHashAlgorithm added in v0.15.0

func WithHashAlgorithm(alg string) SignerOption

WithHashAlgorithm sets the hash used for the claim's hashed URIs and the hard binding: "sha256" (default), "sha384" or "sha512".

func WithIdentitySigner added in v0.18.0

func WithIdentitySigner(key crypto.Signer, chain []*x509.Certificate) SignerOption

WithIdentitySigner adds a CAWG identity assertion (cawg.identity, sig_type cawg.x509.cose) to every manifest the Signer writes: the named actor's own COSE signature, with this key and chain, over the hard binding and whatever Manifest.Identity adds — a second signature inside the manifest, independent of the claim's, that says WHO vouches for the content where the claim says which tool wrote it. The key and chain are validated exactly as NewSigner validates the claim key (same errors, with an "identity" prefix); they may be the claim's own. The assertion's payload is encoded in the field order c2pa-rs re-serialises before verifying, so c2patool accepts it; a validator reports it cawg.identity.well-formed, and cawg.identity.trusted once the chain is anchored with WithIdentityTrust. When a timestamp authority is configured the identity signature is timestamped too.

func WithTimestampAuthority added in v0.15.0

func WithTimestampAuthority(url string) SignerOption

WithTimestampAuthority enables RFC 3161 timestamping (§13.2): every Sign POSTs a TimeStampReq to url and stores the verified TimeStampToken in the signature's sigTst2 header, so validators can pin the signing time without trusting the clock. The reply is checked with the validator's own code before it is embedded; a reply that fails the check, or an authority that cannot be reached, fails the sign with ErrTimestamp. Without this option Sign makes no network requests.

func WithTimestampHTTPClient added in v0.15.0

func WithTimestampHTTPClient(client *http.Client) SignerOption

WithTimestampHTTPClient sets the client used to reach the timestamp authority (default: a client with a 30-second timeout). WithHTTPClient is Validate's option for revocation fetches, hence the distinct name.

func WithVendor added in v0.15.0

func WithVendor(vendor string) SignerOption

WithVendor appends ":<vendor>" (lowercased; 1–32 visible characters, no space or colon) to every manifest label: urn:c2pa:<uuid>:<vendor>.

type SoftBinding added in v0.20.0

type SoftBinding struct {
	// Label is the assertion label, "c2pa.soft-binding" or an instance form.
	Label string
	// URI is "<manifest label>/<Label>", where this assertion's statuses are
	// recorded.
	URI string

	// Algorithm is the resolved identifier: the assertion's own "alg", else the
	// enclosing claim's "alg_soft" (§10.2.1). PRESENTED — a name, not a
	// verified property of the value bytes. Empty only when neither is present,
	// which the spec calls invalid (softBinding.alg.missing).
	Algorithm string
	// AlgorithmFromClaim reports that Algorithm came from the claim's alg_soft,
	// this assertion carrying none of its own.
	AlgorithmFromClaim bool
	// AlgorithmRegistered reports that Algorithm appears in this build's
	// EMBEDDED SNAPSHOT of the C2PA soft binding algorithm list. It is derived
	// from our data rather than presented by the manifest, and false means "not
	// in this snapshot" — which may mean "registered upstream since", since the
	// list grows. See SoftBindingListSnapshot and softbindings/README.md, and
	// note that §9.3.2 requires a listed algorithm while this library reports
	// an unlisted one informationally rather than failing it.
	AlgorithmRegistered bool
	// AlgorithmType is "watermark" or "fingerprint" from that same list, or ""
	// when the algorithm is not in this snapshot. Also from our data.
	AlgorithmType string

	// Name is the optional human-readable "name". PRESENTED free text with no
	// meaning to this library.
	Name string
	// Params is the optional "alg-params", verbatim and uninterpreted. The CDDL
	// says a byte string; c2pa-rs models a text string, so what a producer
	// wrote may be either (see CLAUDE.md).
	Params []byte
	// URL is the optional "url", which the spec marks UNUSED AND DEPRECATED. It
	// is presented verbatim and NEVER dereferenced: a manifest-controlled
	// outbound request would be an SSRF.
	URL string

	// Blocks are the algorithm's outputs, in stored order; at least one when
	// WellFormed.
	Blocks []SoftBindingBlock

	// WellFormed reports that the assertion decoded and satisfied the
	// structural rules of the spec's CDDL — that no softBinding.* failure was
	// recorded for it. It says NOTHING about whether any content matches.
	//
	// Named WellFormed rather than Valid deliberately: Identity.Valid means a
	// signature verified, and nothing is verified here.
	WellFormed bool
}

SoftBinding is one c2pa.soft-binding assertion of a manifest, AS PRESENTED.

It says "content matching this value under this algorithm is the content this manifest describes". Nothing here is proven: this library implements no soft binding algorithm, so it neither confirms nor refutes a match. Hand Algorithm and Blocks[i].Value to a matcher of your own, or to a C2PA Soft Binding Resolution API.

What IS proven, and by a different step, is that these assertion bytes are the ones the claim signed — assertion.hashedURI.match at this URI.

type SoftBindingAlgorithm added in v0.20.0

type SoftBindingAlgorithm struct {
	// Identifier is the registry's own numeric id, unique across the list.
	Identifier int
	// Alg is the identifier that appears on the wire, in a soft binding
	// assertion's "alg" or a claim's "alg_soft" — e.g. "io.iscc.v0".
	Alg string
	// Type is "watermark" (embedded in the content) or "fingerprint"
	// (computed from it).
	Type string
	// Description and DateEntered are the registry's own metadata.
	Description string
	DateEntered string
	// DecodedMediaTypes names the media FAMILIES the algorithm applies to
	// ("image", "audio", "video", "text", "application"), while
	// EncodedMediaTypes names full media types ("audio/mpeg", …). The registry
	// uses two keys with two vocabularies and an entry may carry either or
	// both, so both are surfaced as stored rather than merged.
	DecodedMediaTypes []string
	EncodedMediaTypes []string
	// ResolutionAPIs are the C2PA Soft Binding Resolution API endpoints the
	// registrant published, if any: where a caller could ask "which manifests
	// match this value". This library does not call them.
	ResolutionAPIs []string
}

SoftBindingAlgorithm is one entry of the C2PA soft binding algorithm list. It describes an algorithm this library can NAME but not compute: c2pa implements no soft binding algorithm (see SoftBinding).

func LookupSoftBindingAlgorithm added in v0.20.0

func LookupSoftBindingAlgorithm(alg string) (SoftBindingAlgorithm, bool)

LookupSoftBindingAlgorithm returns the registry entry for an algorithm identifier as it appears on the wire. ok is false when this snapshot does not name it — which means "not in this snapshot", not "not registered": see softbindings/README.md.

func SoftBindingAlgorithms added in v0.20.0

func SoftBindingAlgorithms() []SoftBindingAlgorithm

SoftBindingAlgorithms returns the embedded C2PA soft binding algorithm list, in the registry's own order. The result is a copy: the list is package data, and a caller mutating it must not change what Validate reports.

This is a point-in-time snapshot (softbindings/README.md records which), so an algorithm's absence is not proof it was never registered.

type SoftBindingBlock added in v0.20.0

type SoftBindingBlock struct {
	// Value is the block's "value" byte string, verbatim — the algorithm's
	// output as PRESENTED, opaque to this library.
	Value []byte
	// Scope is what part of the content the value covers.
	Scope SoftBindingScope
}

SoftBindingBlock is one block of a soft binding: a value, and the part of the content it covers.

type SoftBindingBlockInfo added in v0.21.0

type SoftBindingBlockInfo struct {
	// Value is the algorithm's output over this block of content, written as a
	// CBOR byte string. Required and non-empty.
	Value []byte
	// Timespan optionally scopes the block to a millisecond range of a
	// temporal asset.
	Timespan *SoftBindingTimespan
	// Region optionally scopes the block to a region of interest, written
	// verbatim as raw CBOR. This package models no region, so a caller who
	// needs one supplies its encoding.
	Region []byte
}

SoftBindingBlockInfo is one block of a soft binding Sign writes.

The deprecated "extent" and "url" fields have no counterpart here: Validate reports them where a producer wrote them, and this writer does not.

type SoftBindingInfo added in v0.21.0

type SoftBindingInfo struct {
	// Algorithm is written as "alg": an identifier from the C2PA soft binding
	// algorithm list (§9.3.2). Required. Sign refuses one this build's embedded
	// snapshot does not name — strict in what it emits, where Validate is
	// liberal in what it accepts; see softbindings/README.md.
	Algorithm string
	// Name is an optional human-readable description of what the binding
	// covers, written as "name".
	Name string
	// Params is an optional "alg-params", written verbatim as a CBOR byte
	// string, which is what the CDDL asks for.
	Params []byte
	// Blocks are the algorithm's outputs: at least one, each with a non-empty
	// Value.
	Blocks []SoftBindingBlockInfo
}

SoftBindingInfo is a c2pa.soft-binding assertion Sign writes.

The VALUE is yours to compute. This library implements no soft binding algorithm — see SoftBinding for why that is a decision rather than a gap — so it takes the algorithm's output from the caller, as WithIdentitySigner takes a key rather than minting one. That also means every algorithm in the C2PA list works here, including the proprietary watermarks this package could never implement.

type SoftBindingScope added in v0.20.0

type SoftBindingScope struct {
	// Extent is the "extent" byte string, verbatim — DEPRECATED by the spec in
	// favour of Region.
	Extent []byte
	// Timespan is the "timespan" range in milliseconds from the start of a
	// temporal asset, nil when absent. Start and End are as PRESENTED: the
	// spec gives no ordering rule, so End < Start is reported, not rejected.
	Timespan *SoftBindingTimespan
	// Region is the "region" region-of-interest as RAW CBOR, exactly as stored,
	// nil when absent. Deliberately not decoded: this library evaluates no
	// region, and modelling the structure would imply that it did.
	Region []byte
}

SoftBindingScope is the part of the content a block covers, AS PRESENTED. Every field is optional in the spec's CDDL and the spec does not say what an empty scope means, so an all-zero SoftBindingScope is reported as found rather than interpreted as "the whole asset".

type SoftBindingTimespan added in v0.20.0

type SoftBindingTimespan struct {
	Start uint64
	End   uint64
}

SoftBindingTimespan is a millisecond range of a temporal asset.

type StatusCode added in v0.2.0

type StatusCode string

StatusCode is a C2PA validation status code. The string values mirror the codes defined in the C2PA Technical Specification §15 (e.g. "claimSignature.validated", "signingCredential.untrusted") so a caller can match against them directly.

const (
	StatusClaimSignatureValidated  StatusCode = "claimSignature.validated"
	StatusSigningCredentialTrusted StatusCode = "signingCredential.trusted"
	StatusTimeStampValidated       StatusCode = "timeStamp.validated"
	// StatusTimeStampTrusted is recorded beside timeStamp.validated when the
	// time-stamp authority's chain reached a trusted anchor.
	StatusTimeStampTrusted StatusCode = "timeStamp.trusted"
	// StatusClaimSignatureInsideValidity: the signing credential chain was valid at
	// the time the claim was signed (the trusted time-stamp, else the clock).
	StatusClaimSignatureInsideValidity StatusCode = "claimSignature.insideValidity"
	StatusAssertionHashedURIMatch      StatusCode = "assertion.hashedURI.match"
	StatusAssertionDataHashMatch       StatusCode = "assertion.dataHash.match"
	StatusAssertionBoxesHashMatch      StatusCode = "assertion.boxesHash.match"
	StatusAssertionBMFFHashMatch       StatusCode = "assertion.bmffHash.match"
	StatusIngredientManifestValidated  StatusCode = "ingredient.manifest.validated"
	// StatusOCSPNotRevoked: a stapled OCSP response (COSE rVals.ocspVals) for the
	// signing certificate said "good" as of the time it is judged (stapledocsp.go).
	StatusOCSPNotRevoked StatusCode = "signingCredential.ocsp.notRevoked"
	// StatusMultiAssetHashMatch: the whole-asset data hash did not hold, but the
	// parts a c2pa.hash.multi-asset assertion (§18.9) describes all did, with
	// every required part present (multiasset.go).
	StatusMultiAssetHashMatch StatusCode = "assertion.multiAssetHash.match"
	// StatusIdentityTrusted reports a CAWG identity assertion (cawg.identity)
	// whose signature, references and padding all check and whose signing
	// credential reaches an identity trust anchor (WithIdentityTrust). The named
	// actor is proven. Recorded at "<manifest label>/<assertion label>".
	StatusIdentityTrusted StatusCode = "cawg.identity.trusted"
	// StatusICACredentialValid reports an identity claims aggregation
	// credential (CAWG §8.1) that passed every check this validator makes;
	// StatusICATimeStampValidated its verified sigTst2 time-stamp.
	StatusICACredentialValid    StatusCode = "cawg.ica.credential_valid"
	StatusICATimeStampValidated StatusCode = "cawg.ica.time_stamp.validated"
	// StatusIdentityWellFormed reports a CAWG identity assertion that checks in
	// every way except that no identity trust anchor vouches for its credential
	// (CAWG spec §7.2.1): the signature is genuine, the actor is unproven.
	StatusIdentityWellFormed StatusCode = "cawg.identity.well-formed"
)

Success status codes.

const (
	StatusClaimMissing         StatusCode = "claim.missing"
	StatusClaimRequiredMissing StatusCode = "claim.required.missing"
	StatusClaimMultiple        StatusCode = "claim.multiple"
	// StatusManifestUpdateInvalid reports an Update Manifest carrying something
	// §11.2.3 forbids it: a hard binding, a thumbnail, or an action outside the
	// four that do not change the content. Rejecting an update manifest also
	// leaves the asset unbound, so StatusHardBindingMissing is recorded with it.
	StatusManifestUpdateInvalid StatusCode = "manifest.update.invalid"
	// StatusManifestUpdateWrongParents reports an Update Manifest with zero or
	// more than one parentOf ingredient. Exactly one is required: it names the
	// manifest being updated, and so the hard binding that covers the content.
	// Recorded with StatusHardBindingMissing, since without that one parent
	// nothing hashed the asset.
	StatusManifestUpdateWrongParents StatusCode = "manifest.update.wrongParents"
	// StatusManifestMultipleParents reports a manifest with more than one
	// parentOf ingredient, which leaves the asset's lineage ambiguous.
	StatusManifestMultipleParents    StatusCode = "manifest.multipleParents"
	StatusClaimSignatureMissing      StatusCode = "claimSignature.missing"
	StatusClaimSignatureMismatch     StatusCode = "claimSignature.mismatch"
	StatusSigningCredentialUntrusted StatusCode = "signingCredential.untrusted"
	StatusSigningCredentialInvalid   StatusCode = "signingCredential.invalid"
	StatusSigningCredentialRevoked   StatusCode = "signingCredential.revoked"
	StatusSigningCredentialExpired   StatusCode = "signingCredential.expired"
	// StatusClaimSignatureOutsideValidity: a certificate in the signing chain was
	// outside its validity period at signing time. Recorded beside
	// signingCredential.expired.
	StatusClaimSignatureOutsideValidity StatusCode = "claimSignature.outsideValidity"
	StatusTimeStampMismatch             StatusCode = "timeStamp.mismatch"
	StatusTimeStampUntrusted            StatusCode = "timeStamp.untrusted"
	StatusTimeStampOutsideValidity      StatusCode = "timeStamp.outsideValidity"
	StatusAssertionHashedURIMismatch    StatusCode = "assertion.hashedURI.mismatch"
	StatusAssertionDataHashMismatch     StatusCode = "assertion.dataHash.mismatch"
	StatusAssertionBoxesHashMismatch    StatusCode = "assertion.boxesHash.mismatch"
	// StatusAssertionBoxesHashUnknownBox reports that the asset's box structure
	// does not line up with the boxes[] the assertion describes — a name that
	// does not match the next box in file order, or a box the assertion leaves
	// uncovered. Either way the assertion does not bind the asset as it stands.
	StatusAssertionBoxesHashUnknownBox StatusCode = "assertion.boxesHash.unknownBox"
	StatusAssertionBoxesHashMalformed  StatusCode = "assertion.boxesHash.malformed"
	StatusAssertionBMFFHashMismatch    StatusCode = "assertion.bmffHash.mismatch"
	StatusAssertionBMFFHashMalformed   StatusCode = "assertion.bmffHash.malformed"
	StatusAssertionMissing             StatusCode = "assertion.missing"
	// StatusHardBindingMissing reports that no usable hard binding covered the
	// asset's bytes, so nothing hashed them. Either the manifest carries no
	// binding this container can use, or an update manifest was rejected before
	// the parent manifest that would have bound the content was reached.
	StatusHardBindingMissing         StatusCode = "hardBinding.missing"
	StatusAlgorithmUnsupported       StatusCode = "algorithm.unsupported"
	StatusIngredientManifestMismatch StatusCode = "ingredient.manifest.mismatch"
	// StatusIngredientManifestMissing: an ingredient names a manifest the store
	// does not contain.
	StatusIngredientManifestMissing StatusCode = "ingredient.manifest.missing"
	StatusGeneralError              StatusCode = "general.error"

	// Claim and assertion structure (§15.2, claimcheck.go).
	StatusClaimCBORInvalid StatusCode = "claim.cbor.invalid"
	StatusClaimMalformed   StatusCode = "claim.malformed"
	// StatusClaimHardBindingsMissing: the store holds a hard-binding assertion
	// the claim does not reference, so nothing the signature covers binds the
	// asset; a manifest with no hard-binding assertion at all is
	// hardBinding.missing instead.
	StatusClaimHardBindingsMissing   StatusCode = "claim.hardBindings.missing"
	StatusAssertionCBORInvalid       StatusCode = "assertion.cbor.invalid"
	StatusAssertionIngredientMalform StatusCode = "assertion.ingredient.malformed"
	// StatusOCSPRevoked: a stapled OCSP response said the signing certificate
	// was revoked before the claim was signed (stapledocsp.go); recorded beside
	// signingCredential.revoked.
	StatusOCSPRevoked StatusCode = "signingCredential.ocsp.revoked"
	// Multi-asset hash (§18.9, multiasset.go): a part's bytes or its hash
	// assertion did not match, or data lies beyond the last present part
	// (mismatch); the parts do not tile the asset or name an absent assertion
	// (malformed); a required part is absent (missingPart).
	StatusMultiAssetHashMismatch    StatusCode = "assertion.multiAssetHash.mismatch"
	StatusMultiAssetHashMalformed   StatusCode = "assertion.multiAssetHash.malformed"
	StatusMultiAssetHashMissingPart StatusCode = "assertion.multiAssetHash.missingPart"

	// CAWG identity assertion failures (CAWG Identity Assertion spec §7.2.2),
	// recorded at "<manifest label>/<assertion label>". Codes the C2PA core
	// defines for the signature itself — claimSignature.*, signingCredential.*,
	// timeStamp.*, algorithm.unsupported — are reused at that same URI, as
	// §8.2.2 directs.
	StatusIdentityCBORInvalid        StatusCode = "cawg.identity.cbor.invalid"
	StatusIdentityAssertionMismatch  StatusCode = "cawg.identity.assertion.mismatch"
	StatusIdentityAssertionDuplicate StatusCode = "cawg.identity.assertion.duplicate"
	StatusIdentityHardBindingMissing StatusCode = "cawg.identity.hard_binding_missing"
	StatusIdentitySigTypeUnknown     StatusCode = "cawg.identity.sig_type.unknown"
	StatusIdentityPadInvalid         StatusCode = "cawg.identity.pad.invalid"
	StatusIdentityCredentialRevoked  StatusCode = "cawg.identity.credential_revoked"

	// Soft binding failures (spec §18.10), recorded at
	// "<manifest label>/<assertion label>". Structural only: whether the bytes
	// are a well-formed soft binding is checkable with certainty, whether the
	// content matches is not — that is softBinding.unevaluated, informational.
	// The C2PA specification defines no status codes for soft bindings.
	StatusSoftBindingMalformed  StatusCode = "softBinding.malformed"
	StatusSoftBindingAlgMissing StatusCode = "softBinding.alg.missing"
	StatusSoftBindingPadInvalid StatusCode = "softBinding.pad.invalid"

	// Identity claims aggregation failures (CAWG §8.1.5.6), at the identity
	// assertion's URI. Not declared, having no emission site: did_unavailable
	// (no DID is resolved over the network), untrusted_issuer (no issuer trust
	// list yet), and the revocation codes.
	StatusICAInvalidCOSESign1            StatusCode = "cawg.ica.invalid_cose_sign1"
	StatusICAInvalidAlg                  StatusCode = "cawg.ica.invalid_alg"
	StatusICAInvalidContentType          StatusCode = "cawg.ica.invalid_content_type"
	StatusICAInvalidVerifiableCredential StatusCode = "cawg.ica.invalid_verifiable_credential"
	StatusICAInvalidIssuer               StatusCode = "cawg.ica.invalid_issuer"
	// StatusICAUntrustedIssuer is CAWG §8.1.5.2.3's "a DID issued from an
	// untrusted source": the aggregation credential verified, but its issuer
	// is not on the list the caller passed to WithIdentityIssuers. Recorded
	// only when that option is given — with no list there is nothing to be
	// untrusted against, and the identity is reported well-formed instead.
	StatusICAUntrustedIssuer           StatusCode = "cawg.ica.untrusted_issuer"
	StatusICADIDUnsupportedMethod      StatusCode = "cawg.ica.did_unsupported_method"
	StatusICAInvalidDIDDocument        StatusCode = "cawg.ica.invalid_did_document"
	StatusICASignatureMismatch         StatusCode = "cawg.ica.signature_mismatch"
	StatusICATimeStampInvalid          StatusCode = "cawg.ica.time_stamp.invalid"
	StatusICAValidFromMissing          StatusCode = "cawg.ica.valid_from.missing"
	StatusICAValidFromInvalid          StatusCode = "cawg.ica.valid_from.invalid"
	StatusICAValidUntilInvalid         StatusCode = "cawg.ica.valid_until.invalid"
	StatusICASignerPayloadMismatch     StatusCode = "cawg.ica.signer_payload.mismatch"
	StatusICAVerifiedIdentitiesMissing StatusCode = "cawg.ica.verified_identities.missing"
	StatusICAVerifiedIdentitiesInvalid StatusCode = "cawg.ica.verified_identities.invalid"
)

Failure status codes.

const (
	StatusRevocationUnknown StatusCode = "signingCredential.revocation.unknown"
	StatusTimeStampMissing  StatusCode = "timeStamp.missing"
	StatusUnsupported       StatusCode = "general.unsupported"
	// StatusOCSPSkipped: stapled OCSP responses were present but none was
	// usable for the signing certificate (another serial, a bad signature, an
	// unauthorised responder, not yet valid, or past nextUpdate); the online
	// check, if enabled, runs as before.
	StatusOCSPSkipped StatusCode = "signingCredential.ocsp.skipped"

	// Soft binding informationals (spec §18.10), at the assertion's URI.
	// softBinding.unevaluated is the verdict on every well-formed soft binding:
	// this library computes no soft binding algorithm, so a match is neither
	// proved nor disproved. It is a code of its own rather than
	// general.unsupported because that code is used for several unrelated
	// things and a caller must be able to find THIS one.
	// softBinding.alg.unlisted is an algorithm absent from the embedded
	// snapshot of the C2PA algorithm list. §9.3.2 requires a listed algorithm,
	// but the list grows by third-party pull request and the specification's own
	// example uses an unregistered identifier, so failing on it would fail
	// correct files — a deliberate divergence, see softbindings/README.md.
	StatusSoftBindingUnevaluated StatusCode = "softBinding.unevaluated"
	StatusSoftBindingAlgUnlisted StatusCode = "softBinding.alg.unlisted"
	// StatusAssertionBoxesHashAdditionalExclusions reports that a box-hash
	// assertion excluded something beyond the C2PA store itself — asset
	// metadata, or a whole non-C2PA box skipped with "excluded": true. Those
	// exclusions are permitted, so this is advisory rather than a failure, but
	// it says the hard binding covers less of the asset than the baseline.
	StatusAssertionBoxesHashAdditionalExclusions StatusCode = "assertion.boxesHash.additionalExclusionsPresent"
)

Informational status codes.

func (StatusCode) Severity added in v0.2.0

func (c StatusCode) Severity() Severity

Severity returns the StatusCode's severity. Unknown codes are informational.

type StatusEntry added in v0.2.0

type StatusEntry struct {
	Code        StatusCode
	Severity    Severity
	URI         string
	Explanation string
	Err         error
}

StatusEntry is one outcome from the validation pipeline: a C2PA status code, its severity, the JUMBF URI of the subject it concerns (best-effort), a human-readable explanation, and the underlying error for failures.

type ValidateOption added in v0.2.0

type ValidateOption func(*validateConfig)

ValidateOption configures a Validate call. See the With* constructors.

func WithClock added in v0.2.0

func WithClock(now func() time.Time) ValidateOption

WithClock overrides the time source used when no trusted timestamp pins the signing time (defaults to time.Now). Useful for deterministic tests.

func WithHTTPClient added in v0.2.0

func WithHTTPClient(client *http.Client) ValidateOption

WithHTTPClient sets the HTTP client used for OCSP/CRL fetches when online revocation is enabled (defaults to a client with a short timeout).

func WithIdentityIssuers added in v0.22.0

func WithIdentityIssuers(dids ...string) ValidateOption

WithIdentityIssuers sets the identity claims aggregators a consumer trusts, by DID — the aggregation-credential counterpart of WithIdentityTrust, which anchors X.509 identities. CAWG §9.3 says a consumer SHOULD keep such a list per credential type and publishes none itself, having "not provided guidance about which identity claims aggregators to consider trusted".

With this option, an aggregation credential whose issuer is on the list makes the identity cawg.identity.trusted and Identity.Trusted true; one whose issuer is absent is cawg.ica.untrusted_issuer, a FAILURE per §8.1.5.2.3, and is neither well-formed nor Valid. Without it — the default — a valid credential stays cawg.identity.well-formed: a genuine credential from an aggregator this caller has expressed no opinion about.

Entries and issuers are compared after dropping any DID URL fragment, so "did:jwk:eyJ…" and "did:jwk:eyJ…#0" name the same aggregator, and after trimming surrounding space. Nothing else is normalised: a did:jwk's method-specific id is base64url and case-sensitive.

Calling it with no DIDs is meaningful and means "trust no aggregator": every aggregation credential then fails with cawg.ica.untrusted_issuer. Only not calling it leaves issuer trust unevaluated.

func WithIdentityTrust added in v0.18.0

func WithIdentityTrust(pool *x509.CertPool) ValidateOption

WithIdentityTrust sets the trust anchors for CAWG identity assertions — the certificate authorities whose credentials prove a named actor. There is no default: CAWG publishes no trust list and the spec keeps identity anchors separate from the claim signer's, so without this option a valid identity is reported cawg.identity.well-formed (genuine signature, unproven actor) and never cawg.identity.trusted.

func WithMaxIngredientDepth added in v0.2.0

func WithMaxIngredientDepth(n int) ValidateOption

WithMaxIngredientDepth caps recursive ingredient/nested-manifest validation depth (default 16).

func WithMaxScan added in v0.2.0

func WithMaxScan(n int) ValidateOption

WithMaxScan overrides how many leading bytes Validate reads — per input, for ValidateFragmented (default ValidateMaxScan).

func WithOnlineRevocation added in v0.2.0

func WithOnlineRevocation(enabled bool) ValidateOption

WithOnlineRevocation enables OCSP/CRL revocation checking, which makes network calls. It is off by default; when off, revocation is reported as an informational "unknown" status. Revocation is always soft-fail: a network or parse error is informational, never a validation failure.

func WithRequireClaimSigningEKU added in v0.23.0

func WithRequireClaimSigningEKU() ValidateOption

WithRequireClaimSigningEKU makes the claim signer's leaf certificate carry the c2pa-kp-claimSigning EKU (1.3.6.1.4.1.62558.2.1), as the current C2PA certificate profile requires. By default a leaf with only one of the earlier emailProtection, codeSigning or documentSigning purposes is still accepted, so credentials issued under the earlier profile keep validating. CAWG identity credentials are not affected.

func WithSigningTrust added in v0.2.0

func WithSigningTrust(pool *x509.CertPool) ValidateOption

WithSigningTrust overrides the embedded C2PA signing-anchor trust pool used to validate the claim signer's certificate chain.

func WithTimestampTrust added in v0.2.0

func WithTimestampTrust(pool *x509.CertPool) ValidateOption

WithTimestampTrust overrides the embedded C2PA timestamp-authority trust pool used to validate RFC 3161 timestamp tokens.

type ValidationResult added in v0.2.0

type ValidationResult struct {
	// Valid is true iff Statuses contains no SeverityFailure entry.
	Valid bool
	// Info mirrors the surfaced fields Read would return for the same input.
	Info Info
	// Statuses is the ordered list of every validation outcome.
	Statuses []StatusEntry
	// ActiveManifestLabel is the active (last) manifest's JUMBF label.
	ActiveManifestLabel string
	// SignerChain is the COSE signer's certificate chain (leaf first) as
	// presented in the manifest, populated once the chain is parsed.
	SignerChain []*x509.Certificate
	// SignedAt is the signing time from a verified RFC 3161 timestamp, or zero
	// when no trusted timestamp was found.
	SignedAt time.Time
	// Identities are the active manifest's CAWG identity assertions
	// (cawg.identity): named actors who signed over the content with their own
	// credentials, in assertion-store order. Each says whether it is Valid and
	// whether the actor is Trusted; identities in ingredient manifests are
	// validated (their statuses carry their URIs) but not listed.
	Identities []Identity

	// SoftBindings are the ACTIVE manifest's soft binding assertions
	// (c2pa.soft-binding), in assertion-store order: perceptual identifiers
	// that let a re-encoded copy be matched to this manifest, or a stripped
	// manifest be recovered from a provenance store elsewhere.
	//
	// Each is AS PRESENTED and none is proven — this library computes no soft
	// binding algorithm, so it neither confirms nor refutes a match; see
	// SoftBinding. Soft bindings in ingredient manifests are decoded and
	// checked (their statuses carry their own URIs) but NOT listed here: one
	// identifies the content of the manifest that carries it, so an
	// ingredient's identifies an earlier work rather than these bytes.
	SoftBindings []SoftBinding
	// Binding says what the ACTIVE manifest's hard binding proved about THESE
	// bytes: verified, failed, unevaluated, or none. It is the question "were
	// these the signed bytes?" answered directly; see BindingState.
	Binding BindingState
}

ValidationResult is the outcome of Validate. Valid is true exactly when no SeverityFailure status was recorded (see the package docs on the roll-up rule). Statuses is the ordered accumulation of every success, informational, and failure status produced along the way.

func Validate added in v0.2.0

func Validate(ctx context.Context, container Container, r io.Reader, opts ...ValidateOption) ValidationResult

Validate reads up to ValidateMaxScan bytes from r and performs full C2PA validation of the embedded manifest: COSE signature verification, certificate chain + C2PA cert-profile validation against the (embedded or overridden) trust list, assertion and hard-binding hash verification, RFC 3161 timestamp verification, optional revocation checking, and recursive ingredient validation. It reports every outcome as a StatusEntry; ValidationResult.Valid is true exactly when no failure status was recorded.

Like Read, Validate never returns an error and never panics: malformed, truncated, or cancelled input is reported via failure statuses with Valid=false. It is the verified counterpart to Read's fast, unverified scan.

Example

ExampleValidate verifies a JPEG's Content Credentials against the embedded C2PA trust list. The test fixture is signed by the c2pa-rs *test* PKI, so its signature verifies cryptographically but its signer does not chain to a production trust anchor — an honest "valid signature, untrusted signer" verdict. Pass WithSigningTrust / WithTimestampTrust to supply your own anchors.

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/richardwooding/c2pa"
)

func main() {
	f, err := os.Open("testdata/c2pa_signed.jpg")
	if err != nil {
		panic(err)
	}
	defer func() { _ = f.Close() }()

	r := c2pa.Validate(context.Background(), c2pa.JPEG, f)
	fmt.Println("valid:", r.Valid)
	fmt.Println("signature verified:", r.Has(c2pa.StatusClaimSignatureValidated))
	fmt.Println("signer trusted:", r.Has(c2pa.StatusSigningCredentialTrusted))
}
Output:
valid: false
signature verified: true
signer trusted: false
Example (Pdf)

ExampleValidate_pdf verifies a PDF against the embedded C2PA trust list. VerifiedSigner is the proven identity — empty unless the claim signature verified AND the chain reached a trust anchor — where Info.SignedBy is only what the file claims.

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/richardwooding/c2pa"
)

func main() {
	f, err := os.Open("testdata/c2pa_chatgpt.pdf")
	if err != nil {
		panic(err)
	}
	defer func() { _ = f.Close() }()

	r := c2pa.Validate(context.Background(), c2pa.PDF, f)
	fmt.Println("valid:", r.Valid)
	fmt.Println("verified signer:", r.VerifiedSigner())
	// Binding answers "were these the signed bytes?" directly: verified,
	// failed, unevaluated (a binding over other bytes, or a check that could
	// not run) or none.
	fmt.Println("binding:", r.Binding)
	// This document carries no RFC 3161 timestamp, so the signing time is
	// unproven and SignedAt stays zero.
	fmt.Println("trusted timestamp:", !r.Has(c2pa.StatusTimeStampMissing))
}
Output:
valid: true
verified signer: OpenAI Media Service
binding: verified
trusted timestamp: false

func ValidateFragmented added in v0.14.0

func ValidateFragmented(ctx context.Context, init io.Reader, fragments []io.Reader, opts ...ValidateOption) ValidationResult

ValidateFragmented validates a fragmented BMFF asset — DASH / CMAF / HLS fMP4 — whose initialization segment and media fragments are separate files. init is the initialization segment ('ftyp' + 'moov', carrying the C2PA manifest store in its uuid box, spec §A.5); fragments are the media segments ('styp'/'moof'/'mdat', each carrying a C2PA merkle uuid box), in any order. It reads up to ValidateMaxScan bytes from init and then from each fragment in turn, holding one fragment at a time, so memory is bounded by the initialization segment plus the largest fragment.

The initialization segment receives exactly the validation Validate gives a single BMFF file — COSE signature, certificate chain and profile, RFC 3161 timestamp, assertion hashes, revocation, ingredients — and only the hard binding differs. A c2pa.hash.bmff.v2/.v3 assertion's merkle array (spec §18.6.3) binds the initialization segment through each merkle-map's initHash, and binds every fragment through the merkle box the fragment carries, paired to its map by uniqueId/localId and placed in the tree by location. Each supplied fragment is verified against that proof; one that fails is a failure status whose URI ends in "#fragment=<i>", i being its index in fragments. The roll-up is assertion.bmffHash.match only when the initialization segment AND every location the trees bind — 0 through count-1 of each merkle-map THAT BINDS THIS INITIALIZATION SEGMENT, §15.12.2 — were verified; a map whose initHash belongs to another rendition (c2pa-rs signs several renditions into one manifest) is named as not evaluated here, and a fragment claiming such a map is a mismatch. Supplying a subset is a legitimate partial check: what was not covered is named in an informational general.unsupported status, and Valid stays true unless something supplied was disproved. No match is ever reported for a partial set, so Has(StatusAssertionBMFFHashMatch) keeps meaning "fully bound".

Like Validate, ValidateFragmented never returns an error and never panics: malformed, truncated, unreadable or cancelled input is reported through statuses. It is the counterpart of c2pa-rs's verify_stream_segments.

Example

ExampleValidateFragmented verifies a DASH/CMAF asset whose initialization segment and media fragments are separate files. The initialization segment carries the manifest; each fragment carries the Merkle proof that binds it. The binding is a match only when every fragment the manifest binds was supplied and verified; a partial set — here one fragment of eleven — is an informational status naming what was not covered, never a false match.

The fixture is a third-party signed set from c2pa-rs's test assets; its signer is not on the embedded trust list, so the chain it presents is anchored explicitly (a claim about identity, not proof of it).

package main

import (
	"context"
	"crypto/x509"
	"fmt"
	"io"
	"os"

	"github.com/richardwooding/c2pa"
)

func main() {
	init, err := os.Open("testdata/dash/dashinit.mp4")
	if err != nil {
		panic(err)
	}
	defer func() { _ = init.Close() }()
	frag, err := os.Open("testdata/dash/dash1.m4s")
	if err != nil {
		panic(err)
	}
	defer func() { _ = frag.Close() }()

	ctx := context.Background()
	presented := c2pa.Validate(ctx, c2pa.BMFF, init)
	pool := x509.NewCertPool()
	pool.AddCert(presented.SignerChain[len(presented.SignerChain)-1])
	if _, err := init.Seek(0, io.SeekStart); err != nil {
		panic(err)
	}

	r := c2pa.ValidateFragmented(ctx, init, []io.Reader{frag}, c2pa.WithSigningTrust(pool))
	fmt.Println("valid:", r.Valid)
	// Bound only if every fragment was supplied and verified.
	fmt.Println("bound:", r.Has(c2pa.StatusAssertionBMFFHashMatch))
	fmt.Println("signer:", r.VerifiedSigner())
	for _, s := range r.Statuses {
		if s.Code == c2pa.StatusUnsupported {
			fmt.Println(s.Explanation)
		}
	}
}
Output:
valid: true
bound: false
signer: Alice
fragmented BMFF hash only partly verified: initialization segment and 1 of 11 fragments verified; not verified: locations 1..10

func (ValidationResult) FirstFailure added in v0.2.0

func (r ValidationResult) FirstFailure() *StatusEntry

FirstFailure returns the first SeverityFailure status, or nil if none.

func (ValidationResult) Has added in v0.2.0

func (r ValidationResult) Has(code StatusCode) bool

Has reports whether any recorded status has the given code.

func (ValidationResult) VerifiedSigner added in v0.8.0

func (r ValidationResult) VerifiedSigner() string

VerifiedSigner returns the signer's identity — the leaf certificate's Subject Common Name, falling back to its first Organization — but ONLY when that identity was actually proven: the active manifest's claim signature verified, and its certificate chain reached a trust anchor. Otherwise it returns "".

Use this rather than reading SignerChain directly. SignerChain is the chain as PRESENTED, populated whether or not it verified, so a name taken straight from it is a claim rather than a fact — the same trap Info.SignedBy carries.

A hard-binding failure does not clear it: if the content was edited after signing, who signed the original is still proven, and Valid reports the edit.

type VerifiedIdentity added in v0.19.0

type VerifiedIdentity struct {
	// Type is the kind of signal: "cawg.document_verification",
	// "cawg.affiliation", "cawg.social_media", "cawg.crypto_wallet", ….
	Type string
	// Name is the actor's display name for this signal, when given.
	Name string
	// Username and URI locate the account for a social-media or wallet signal.
	Username string
	URI      string
	// VerifiedAt is when the aggregator verified the signal.
	VerifiedAt time.Time
	// Provider is who the aggregator verified the signal with.
	Provider IdentityProvider
}

VerifiedIdentity is one identity signal an aggregator vouched for in an identity claims aggregation credential, as PRESENTED by the aggregator.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址