encypher-c2pa-cli 1.0.4

Offline C2PA verification command-line tool
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
use std::collections::HashMap;
use std::fs::{self, OpenOptions};
use std::io::{self, Read};
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use clap::{Parser, Subcommand, ValueEnum};
use encypher_c2pa::{
    detached_manifest_evidence, mime_from_path, set_telemetry_enabled, supported_mime_types,
    telemetry_preference, verify_file, verify_fragmented_with_options, verify_with_options, Error,
    TelemetryOptions, VerifyOptions,
};

mod encypher_api;

const MAX_PATH_ASSET_BYTES: u64 = 128 * 1024 * 1024;

#[derive(Debug, Parser)]
#[command(name = "encypher-c2pa", version, about = "Local C2PA verification")]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum TelemetrySetting {
    On,
    Off,
    Status,
}

// `Verify` carries every CLI flag inline, which clap's derive requires: a
// boxed or flattened args struct cannot be parsed into a subcommand variant.
// The enum is built once, from argv, and dropped at the end of main, so the
// variant size difference has no runtime cost worth restructuring for.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Subcommand)]
enum Command {
    /// Verify one local asset. First interactive use asks about failure telemetry.
    Verify {
        asset: PathBuf,
        #[arg(long)]
        mime: Option<String>,
        /// Fragmented BMFF media segment (`.m4s`). Repeat for each available segment.
        #[arg(long, value_name = "FILE", conflicts_with = "encypher_api")]
        fragment: Vec<PathBuf>,
        /// Claim-signer trust anchors (PEM bundle). Repeatable; bundles merge.
        #[arg(long, value_name = "PEM")]
        trust: Vec<PathBuf>,
        /// Timestamp-authority trust anchors (PEM bundle). Repeatable.
        #[arg(long, value_name = "PEM")]
        tsa_trust: Vec<PathBuf>,
        /// Directly allowed end-entity certificates (PEM bundle). Repeatable.
        #[arg(long, visible_alias = "allowed-certs", value_name = "PEM")]
        allowed: Vec<PathBuf>,
        /// CAWG named-actor (identity) trust anchors (PEM bundle). Repeatable.
        #[arg(long, value_name = "PEM")]
        cawg_trust: Vec<PathBuf>,
        /// Directly allowed CAWG end-entity certificates (PEM). Repeatable.
        #[arg(long, value_name = "PEM")]
        cawg_allowed: Vec<PathBuf>,
        /// Verify with caller-supplied trust only; ignore bundled snapshots.
        #[arg(long)]
        no_default_trust: bool,
        /// Pinned offline did:web DID documents for CAWG ICA issuers.
        /// Repeatable; each file is a DID document, an array of documents, or
        /// a DID -> document map. Without it did:web resolution fails closed.
        #[arg(long, value_name = "JSON")]
        cawg_did_documents: Vec<PathBuf>,
        /// Refuse CAWG 1.1-era legacy encodings; accept only CAWG 1.2
        /// canonical shapes.
        #[arg(long)]
        cawg_strict_encoding: bool,
        /// RFC 3339 validation instant (default: current UTC time).
        #[arg(long, visible_alias = "validation-time", value_name = "RFC3339")]
        time: Option<String>,
        /// Send anonymous, bounded validation failure codes to Encypher.
        #[arg(long)]
        telemetry: bool,
        /// Disable failure telemetry and save that preference.
        #[arg(long, conflicts_with = "telemetry")]
        no_telemetry: bool,
        /// Override the failure telemetry endpoint.
        #[arg(long, value_name = "URL")]
        telemetry_endpoint: Option<String>,
        #[arg(long)]
        json: bool,
        /// Ask Encypher to validate the raw C2PA manifest and match its signed
        /// registry. Requires `ENCYPHER_API_KEY` or `ENCYPHER_API_TOKEN`.
        /// Sends the file SHA-256 plus the embedded manifest carrier, not the
        /// media bytes. The response never changes the local verdict or exit code.
        #[arg(long)]
        encypher_api: bool,
        /// Override the Encypher verification endpoint (self-hosting, tests).
        #[arg(long, value_name = "URL", hide = true)]
        encypher_api_endpoint: Option<String>,
    },
    /// Read or change the saved failure telemetry preference.
    Telemetry {
        #[arg(value_enum)]
        setting: TelemetrySetting,
    },
    /// List canonical MIME types covered by the C2PA 2.4 profile.
    Formats {
        #[arg(long)]
        json: bool,
    },
    /// Explain a stable validation status code.
    Explain { code: String },
}

fn main() -> ExitCode {
    match run(Cli::parse()) {
        Ok(code) => code,
        Err(error) => {
            eprintln!("{}: {error}", error.code());
            if matches!(error, Error::UnsupportedMime(_)) {
                ExitCode::from(3)
            } else {
                ExitCode::FAILURE
            }
        }
    }
}

fn run(cli: Cli) -> Result<ExitCode, Error> {
    match cli.command {
        Command::Verify {
            asset,
            mime,
            fragment,
            trust,
            tsa_trust,
            allowed,
            cawg_trust,
            cawg_allowed,
            no_default_trust,
            cawg_did_documents,
            cawg_strict_encoding,
            time,
            telemetry,
            no_telemetry,
            telemetry_endpoint,
            json,
            encypher_api,
            encypher_api_endpoint,
        } => {
            // Telemetry preference persistence is best-effort: verification
            // MUST run even when no user configuration directory can be
            // resolved (containers, service accounts, HOME-less shells). The
            // explicit flag still governs this run via TelemetryOptions.
            let explicit_telemetry = if telemetry {
                Some(true)
            } else if no_telemetry {
                Some(false)
            } else {
                None
            };
            if let Some(enabled) = explicit_telemetry {
                if let Err(error) = set_telemetry_enabled(enabled) {
                    eprintln!(
                        "warning: could not save telemetry preference ({error}); \
                         telemetry stays {} for this run",
                        if enabled { "enabled" } else { "disabled" }
                    );
                }
            }
            let options = VerifyOptions {
                trust_pem: read_merged_pem(&trust)?,
                tsa_trust_pem: read_merged_pem(&tsa_trust)?,
                allowed_list_pem: read_merged_pem(&allowed)?,
                cawg_trust_pem: read_merged_pem(&cawg_trust)?,
                cawg_allowed_certs_pem: read_merged_pem(&cawg_allowed)?,
                no_default_trust,
                cawg_did_documents: read_did_documents(&cawg_did_documents)?,
                cawg_strict_encoding,
                strict_conformance: false,
                validation_time: time,
                telemetry: TelemetryOptions {
                    enabled: explicit_telemetry,
                    endpoint: telemetry_endpoint,
                    sdk_name: Some("cli".to_string()),
                },
            };
            let (report, encypher_api_result) = if encypher_api {
                let mime = match mime {
                    Some(value) => value,
                    None => mime_from_path(&asset)
                        .ok_or_else(|| Error::UnsupportedMime(asset.display().to_string()))?
                        .to_string(),
                };
                let bytes = read_path_asset(&asset)?;
                let report = verify_with_options(&bytes, &mime, &options)?;
                let evidence = detached_manifest_evidence(&bytes, &mime)?;
                let endpoint = encypher_api_endpoint
                    .unwrap_or_else(|| encypher_api::DEFAULT_ENDPOINT.to_string());
                let api_key = std::env::var("ENCYPHER_API_KEY")
                    .or_else(|_| std::env::var("ENCYPHER_API_TOKEN"))
                    .ok();
                let result = encypher_api::verify(
                    &endpoint,
                    api_key.as_deref(),
                    &bytes,
                    &mime,
                    &report,
                    evidence.as_ref(),
                );
                (report, Some(result))
            } else if fragment.is_empty() {
                (verify_file(&asset, mime.as_deref(), &options)?, None)
            } else {
                let mime = match mime {
                    Some(value) => value,
                    None => mime_from_path(&asset)
                        .ok_or_else(|| Error::UnsupportedMime(asset.display().to_string()))?
                        .to_string(),
                };
                let init_segment = read_path_asset(&asset)?;
                let fragment_bytes: Vec<Vec<u8>> = fragment
                    .iter()
                    .map(|path| read_path_asset(path))
                    .collect::<Result<_, _>>()?;
                let fragment_refs: Vec<&[u8]> = fragment_bytes.iter().map(Vec::as_slice).collect();
                (
                    verify_fragmented_with_options(&init_segment, &fragment_refs, &mime, &options)?,
                    None,
                )
            };
            if json {
                if let Some(lookup) = &encypher_api_result {
                    let mut value: serde_json::Value =
                        serde_json::from_str(&report.to_pretty_json()?)
                            .map_err(Error::Serialize)?;
                    if let Some(object) = value.as_object_mut() {
                        object.insert("encypher_api".to_string(), lookup.clone());
                    }
                    println!(
                        "{}",
                        serde_json::to_string_pretty(&value).map_err(Error::Serialize)?
                    );
                } else {
                    println!("{}", report.to_pretty_json()?);
                }
            } else {
                println!("asset: {}", asset.display());
                println!("profile: {}", report.profile);
                println!(
                    "provenance: {}",
                    if report.present { "present" } else { "absent" }
                );
                println!("integrity: {}", report.integrity);
                println!("signature: {}", report.signature);
                println!("hard binding: {}", report.hard_binding);
                println!("trust: {} ({})", report.trust.status, report.trust.basis);
                if !report.validation_results.failure.is_empty() {
                    println!("failures:");
                    for status in &report.validation_results.failure {
                        println!("  {}: {}", status.code, status.explanation);
                    }
                }
                println!("docs: https://encypher.com/c2pa/codes");
                if let Some(lookup) = &encypher_api_result {
                    encypher_api::render_human(lookup);
                }
            }
            Ok(if report.integrity == "valid" {
                ExitCode::SUCCESS
            } else {
                ExitCode::from(2)
            })
        }
        Command::Telemetry { setting } => {
            match setting {
                TelemetrySetting::On => {
                    set_telemetry_enabled(true)?;
                    println!("Failure telemetry enabled.");
                }
                TelemetrySetting::Off => {
                    set_telemetry_enabled(false)?;
                    println!("Failure telemetry disabled.");
                }
                TelemetrySetting::Status => match telemetry_preference()? {
                    Some(true) => println!("Failure telemetry is enabled."),
                    Some(false) => println!("Failure telemetry is disabled."),
                    None => println!("Failure telemetry preference is not set."),
                },
            }
            Ok(ExitCode::SUCCESS)
        }
        Command::Formats { json } => {
            let formats = supported_mime_types();
            if json {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&formats).map_err(Error::Serialize)?
                );
            } else {
                for mime in formats {
                    println!("{mime}");
                }
            }
            Ok(ExitCode::SUCCESS)
        }
        Command::Explain { code } => {
            let explanation = explain(&code).ok_or_else(|| {
                Error::Verification(format!("unknown validation status code: {code}"))
            })?;
            println!("{code}: {explanation}");
            println!("details: https://encypher.com/c2pa/codes/{code}");
            Ok(ExitCode::SUCCESS)
        }
    }
}

/// Read repeatable PEM-bundle options and merge them into one bundle (PEM
/// concatenates trivially), so separate anchor lists — your own CA, the C2PA
/// official list, a partner list — can be passed without cat-ing files.
fn read_merged_pem(paths: &[PathBuf]) -> Result<Option<String>, Error> {
    if paths.is_empty() {
        return Ok(None);
    }
    let mut pem = String::new();
    for path in paths {
        pem.push_str(&fs::read_to_string(path)?);
        if !pem.ends_with('\n') {
            pem.push('\n');
        }
    }
    Ok(Some(pem))
}

fn read_path_asset(path: &Path) -> io::Result<Vec<u8>> {
    let mut options = OpenOptions::new();
    options.read(true);
    #[cfg(unix)]
    options.custom_flags(libc::O_NONBLOCK | libc::O_CLOEXEC);

    let mut file = options.open(path)?;
    let metadata = file.metadata()?;
    if !metadata.is_file() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("asset path is not a regular file: {}", path.display()),
        ));
    }
    if metadata.len() > MAX_PATH_ASSET_BYTES {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!("asset exceeds the 128 MiB path limit: {}", path.display()),
        ));
    }

    let expected_len = usize::try_from(metadata.len())
        .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "asset size is not addressable"))?;
    let mut data = vec![0_u8; expected_len + 1];
    let mut used = 0;
    while used < expected_len {
        let count = file.read(&mut data[used..expected_len])?;
        if count == 0 {
            break;
        }
        used += count;
    }
    if used == expected_len && file.read(&mut data[expected_len..expected_len + 1])? != 0 {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "asset grew while being read",
        ));
    }
    data.truncate(used);
    Ok(data)
}

/// Build the pinned offline `did:web` DID-document store from repeatable
/// `--cawg-did-documents PATH` options. Each file holds either a single DID
/// document (keyed by its `id`), an array of DID documents, or an object
/// mapping DID -> document. Later files override earlier entries.
fn read_did_documents(
    paths: &[PathBuf],
) -> Result<Option<HashMap<String, serde_json::Value>>, Error> {
    if paths.is_empty() {
        return Ok(None);
    }
    let mut store = HashMap::new();
    fn insert_doc(
        doc: serde_json::Value,
        path: &std::path::Path,
        store: &mut HashMap<String, serde_json::Value>,
    ) -> Result<(), Error> {
        let id = doc
            .get("id")
            .and_then(|value| value.as_str())
            .filter(|id| id.starts_with("did:"))
            .ok_or_else(|| {
                Error::Verification(format!(
                    "cawg did documents: {}: document lacks a DID `id`",
                    path.display()
                ))
            })?
            .to_string();
        store.insert(id.split('#').next().unwrap_or(&id).to_string(), doc);
        Ok(())
    }
    for path in paths {
        let contents = fs::read_to_string(path)?;
        let parsed: serde_json::Value = serde_json::from_str(&contents).map_err(|error| {
            Error::Verification(format!("cawg did documents: {}: {error}", path.display()))
        })?;
        match parsed {
            serde_json::Value::Array(docs) => {
                for doc in docs {
                    insert_doc(doc, path, &mut store)?;
                }
            }
            doc @ serde_json::Value::Object(_) if doc.get("id").is_some() => {
                insert_doc(doc, path, &mut store)?;
            }
            serde_json::Value::Object(map) => {
                for (did, doc) in map {
                    if !did.starts_with("did:") {
                        return Err(Error::Verification(format!(
                            "cawg did documents: {}: key {did:?} is not a DID",
                            path.display()
                        )));
                    }
                    store.insert(did.split('#').next().unwrap_or(&did).to_string(), doc);
                }
            }
            _ => {
                return Err(Error::Verification(format!(
                    "cawg did documents: {}: expected a DID document, array, or DID->document map",
                    path.display()
                )))
            }
        }
    }
    Ok(Some(store))
}

fn explain(code: &str) -> Option<&'static str> {
    Some(match code {
        "claimSignature.validated" => "The active claim signature is cryptographically valid.",
        "claimSignature.mismatch" => "The active claim signature does not verify.",
        "assertion.hashedURI.match" => "A claim reference matches the exact assertion bytes.",
        "assertion.hashedURI.mismatch" => {
            "A referenced assertion changed or is not the referenced bytes."
        }
        "assertion.dataHash.match" => "The asset bytes match the signed data-hash assertion.",
        "assertion.dataHash.mismatch" => {
            "The asset bytes do not match the signed data-hash assertion."
        }
        "assertion.bmffHash.match" => "The BMFF boxes match the signed box-hash assertion.",
        "assertion.bmffHash.mismatch" => {
            "The BMFF boxes do not match the signed box-hash assertion."
        }
        "signingCredential.trusted" => "The signer chains to configured trust material.",
        "signingCredential.untrusted" => "The signer does not chain to configured trust material.",
        "signingCredential.ocsp.revoked" => {
            "Supplied revocation evidence marks the signer as revoked."
        }
        "claim.missing" => "No readable active C2PA claim is present.",
        "ingredient.manifest.missing" => {
            "An ingredient points to a manifest absent from the store."
        }
        _ => return None,
    })
}