Skip to main content

Crate c2pa

Crate c2pa 

Source
Expand description

This library supports reading, creating, and embedding C2PA data for a variety of asset types.

Some functionality requires you to enable specific crate features, as noted in the documentation.

The library has a Builder/Reader API that focuses on simplicity and stream support.

For more information, see CAI open source SDK - Rust library

§Examples

§Reading a manifest

use c2pa::{assertions::Actions, Reader};

let stream = std::fs::File::open("tests/fixtures/C.jpg")?;
let reader = Reader::from_stream("image/jpeg", stream)?;
println!("{}", reader.json());

if let Some(manifest) = reader.active_manifest() {
    let actions: Actions = manifest.find_assertion(Actions::LABEL)?;
    for action in actions.actions {
        println!("{}\n", action.action());
    }
}

§Reading a manifest using Context, Settings, and trust list

Download the official C2PA trust list PEM and point trust.trust_anchors to its contents.

use c2pa::{settings::Settings, Context, Reader, Result};

#[cfg(feature = "file_io")]
{
    // Load the official C2PA trust list (PEM bundle) from a local file you downloaded.
    let trust_pem = std::fs::read_to_string("path/to/C2PA-TRUST-LIST.pem")?;

    // Build Settings enabling certificate trust verification against the C2PA trust anchors.
    let settings = Settings::new().with_value("trust.trust_anchors", trust_pem)?;

    // Create a Context with these settings and read an asset.
    let context = Context::new().with_settings(settings)?;
    let reader = Reader::from_context(context).with_file("path/to/asset.jpg")?;

    println!("{}", reader.json());
}

§Adding a signed manifest to a file

use std::io::Cursor;

use c2pa::{Builder, BuilderIntent, Context};
use serde::Serialize;
use serde_json::json;

#[derive(Serialize)]
struct Test {
    my_tag: usize,
}

// Create context with signer configuration.
let context =
    Context::new().with_settings(include_str!("../tests/fixtures/test_settings.toml"))?;

// Build manifest.
let mut builder = Builder::from_context(context)
    .with_definition(json!({"title": "Test"}))?;
// Use Edit intent so the parent ingredient is captured from the source stream.
builder.set_intent(BuilderIntent::Edit);
builder.add_assertion("org.contentauth.test", &Test { my_tag: 42 })?;

// Save with automatic signer from context (created from settings).
let mut source = std::fs::File::open("tests/fixtures/C.jpg")?;
let mut dest = Cursor::new(Vec::new());
let _c2pa_data = builder.save_to_stream("image/jpeg", &mut source, &mut dest)?;

§Adding an ingredient and signing

use std::io::Cursor;

use c2pa::{Builder, BuilderIntent, Context, DigitalSourceType};
use serde_json::json;

// Create context with signer configuration.
let context =
    Context::new().with_settings(include_str!("../tests/fixtures/test_settings.toml"))?;

// Build manifest.
let mut builder = Builder::from_context(context)
    .with_definition(json!({"title": "Created Asset"}))?;
// Use Create intent with a source type and add a component ingredient.
builder.set_intent(BuilderIntent::Create(DigitalSourceType::DigitalCapture));

// Add an ingredient using Builder helper (no direct Ingredient struct).
let ingredient_json = json!({
    "title": "My ingredient",
    "relationship": "componentOf"
}).to_string();
let mut ingredient = std::fs::File::open("tests/fixtures/sample1.png")?;
builder.add_ingredient_from_stream(ingredient_json, "image/png", &mut ingredient)?;

// Sign and embed using the context's signer.
let mut source = std::fs::File::open("tests/fixtures/C.jpg")?;
let mut dest = Cursor::new(Vec::new());
let _c2pa_data = builder.save_to_stream("image/jpeg", &mut source, &mut dest)?;

§Features

The crate provides the following features:

These features are enabled by default:

  • default_http: Enables default HTTP features for sync and async HTTP resolvers (http_req, http_reqwest, http_wasi, and http_std).
  • openssl: Use the vendored openssl implementation for cryptography.

One of openssl or rust_native_crypto must be enabled. If both are enabled, rust_native_crypto is used.

Other features:

  • add_thumbnails: Adds the image crate to enable auto-generated thumbnails, if possible and enabled in settings.
  • fetch_remote_manifests: Fetches remote manifests over the network when no embedded manifest is present and that option is enabled in settings.
  • file_io: Enables APIs that use filesystem I/O.
  • json_schema: Adds the schemars crate to derive JSON schemas for JSON-compatible structs.
  • pdf: Enables basic PDF read support.
  • rust_native_crypto: Use Rust native cryptography.

§HTTP features

WARNING: These features are for advanced users. Most people can ignore them. These features toggle compilation with different HTTP libraries, depending on the one you use. Some are async-only and others are sync-only. Disabling all of them will disable HTTP, speed up compilation, and decrease build size.

  • http_ureq: Enables ureq for sync HTTP requests.
  • http_reqwest: Enables reqwest for async HTTP requests.
  • http_reqwest_blocking: Enables the blocking feature of reqwest for sync HTTP requests.
  • http_wasi: Enables wasi for sync HTTP requests on WASI.
  • http_wstd: Enables wstd for async HTTP requests on WASI.

§WASM and WASI

For WASM the only supported HTTP feature is http_reqwest. This means WASM only supports the async API for network requests.

For WASI the only supported HTTP features are http_wasi, which enables sync network requests, and http_wstd which enables async network requests.

Modules§

assertions
The assertions module contains the definitions for the assertions that are part of the C2PA specification. Assertion helpers to build, validate, and parse assertions.
cose_sign
The cose_sign module contains the definitions for the COSE signing algorithms. Provides access to COSE signature generation.
create_signer
The create_signer module contains the definitions for the signers that are part of the C2PA specification. The create_signer module provides a way to obtain a Signer instance for each signing format supported by this crate.
jumbf_io
The jumbf_io module contains the definitions for the JUMBF data in assets.
settings
The settings module provides a way to configure the C2PA SDK.
validation_results
The validation_results module contains the definitions for the validation results that are part of the C2PA specification.

Structs§

Builder
Use a Builder to add a signed manifest to an asset.
CallbackSigner
Defines a signer that uses a callback to sign data.
ClaimGeneratorInfo
Description of the claim generator, or the software used in generating the claim.
Context
Context holds the configuration and dependencies for C2PA operations.
HashRange
Defines a hash range to be used with hash_stream_by_alg
HashedUri
A HashedUri provides a reference to content available within the same manifest store.
Ingredient
An Ingredient is any external asset that has been used in the creation of an asset.
Manifest
A Manifest represents all the information in a c2pa manifest
ManifestAssertion
A labeled container for an Assertion value in a Manifest
ManifestDefinition
Use a ManifestDefinition to define a manifest and to build a ManifestStore. A manifest is a collection of ingredients and assertions used to define a claim that can be signed and embedded into a file.
Reader
Use a Reader to read and validate a manifest store.
ResourceRef
A reference to a resource to be used in JSON serialization.
ResourceStore
Resource store to contain binary objects referenced from JSON serializable structures
Settings
Settings for configuring all aspects of c2pa-rs.
SignatureInfo
Holds information about a signature
ValidationResults
A map of validation results for a manifest store.

Enums§

BuilderIntent
Represents the type of builder flow being used.
DigitalSourceType
Description of the source of an asset.
Error
Error enumerates errors returned by most C2PA toolkit operations.
ManifestAssertionKind
Assertions in C2PA can be stored in several formats
Relationship
The relationship of the ingredient to the current asset.
SigningAlg
Describes the digital signature algorithms allowed by the C2PA spec.
ValidationState
Represents the levels of assurance a manifest store achives when evaluated against the C2PA specifications structural, cryptographic, and trust requirements.

Constants§

NAME
The internal name of the C2PA SDK.
VERSION
The version of this C2PA SDK.

Traits§

AsyncSigner
The AsyncSigner trait generates a cryptographic signature over a byte array.
Signer
The Signer trait generates a cryptographic signature over a byte array.

Functions§

format_from_path
Return a MIME type given a file path.
hash_stream_by_alg
May be used to generate hashes in combination with embeddable APIs.

Type Aliases§

BoxedAsyncSigner
Type alias for a boxed AsyncSigner with conditional Send + Sync bounds. On non-WASM targets, the signer is Send + Sync for thread-safe usage.
BoxedSigner
Type alias for a boxed Signer with conditional Send + Sync bounds. On non-WASM targets, the signer is Send + Sync for thread-safe usage.
CallbackFunc
Defines a callback function interface for a CallbackSigner.
Result
A specialized Result type for C2PA toolkit operations.