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 ¶
- Constants
- Variables
- func ExtractStore(ctx context.Context, container Container, r io.Reader) ([]byte, error)
- func WalkBoxes(ctx context.Context, jumbf []byte, fn func(label, tbox string, content []byte))
- type Action
- type Assertion
- type Attribution
- type BindingState
- type Container
- type GeneratorInfo
- type Identity
- type IdentityInfo
- type IdentityProvider
- type Info
- type Manifest
- type Severity
- type Signer
- type SignerOption
- func WithClaimGenerator(name, version string) SignerOption
- func WithHashAlgorithm(alg string) SignerOption
- func WithIdentitySigner(key crypto.Signer, chain []*x509.Certificate) SignerOption
- func WithTimestampAuthority(url string) SignerOption
- func WithTimestampHTTPClient(client *http.Client) SignerOption
- func WithVendor(vendor string) SignerOption
- type SoftBinding
- type SoftBindingAlgorithm
- type SoftBindingBlock
- type SoftBindingBlockInfo
- type SoftBindingInfo
- type SoftBindingScope
- type SoftBindingTimespan
- type StatusCode
- type StatusEntry
- type ValidateOption
- func WithClock(now func() time.Time) ValidateOption
- func WithHTTPClient(client *http.Client) ValidateOption
- func WithIdentityIssuers(dids ...string) ValidateOption
- func WithIdentityTrust(pool *x509.CertPool) ValidateOption
- func WithMaxIngredientDepth(n int) ValidateOption
- func WithMaxScan(n int) ValidateOption
- func WithOnlineRevocation(enabled bool) ValidateOption
- func WithRequireClaimSigningEKU() ValidateOption
- func WithSigningTrust(pool *x509.CertPool) ValidateOption
- func WithTimestampTrust(pool *x509.CertPool) ValidateOption
- type ValidationResult
- type VerifiedIdentity
Examples ¶
Constants ¶
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).
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).
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.
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.
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.
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 ¶
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.
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
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 ¶
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
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
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
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
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 ¶
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
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
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.
Source Files
¶
- binding.go
- bmff.go
- bmffembed.go
- bmffhash.go
- bmffmerklewrite.go
- boxes.go
- boxeshash.go
- boxmap.go
- c2pa.go
- cawg.go
- cawgica.go
- cawgsign.go
- cawgverify.go
- chain.go
- claimcheck.go
- claimwrite.go
- cose_verify.go
- cosesign.go
- ctx.go
- embed.go
- fragmented.go
- gif.go
- hashbinding.go
- ingredient.go
- jumbfwrite.go
- mp3.go
- multiasset.go
- pdf.go
- pdfwrite.go
- revocation.go
- riff.go
- sign.go
- signflat.go
- signfragmented.go
- softbinding.go
- softbindingalgs.go
- stapledocsp.go
- statuscodes.go
- svg.go
- tiff.go
- timestamp.go
- trust.go
- tsaclient.go
- validate.go