turul-ai-catalog-cli 0.0.29

Command line for AI Catalog: validate, list, view, init, add, remove and store
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! The `key`, `sign` and `verify` commands: arguments, key-store connection and printing. The
//! key, the DID document, the artifact digest, the endorsement and the verification are the
//! trust crate's `SigningKey`, `ParameterKeyStore`, `did_document`, `endorse_catalog`,
//! `sign_catalog` and `verify`. Also the artifact opener `view` hands the terminal browser,
//! over the trust crate's `fetch_artifact` and `check_artifact`.

use std::io::{self, Write};
use std::time::SystemTime;

use clap::Args;
#[cfg(feature = "ssm")]
use clap::Subcommand;
use turul_ai_catalog::identity::ArtifactType;
use turul_ai_catalog::model::ArtifactSource;
use turul_ai_catalog_client::{Child, DisplayText, EntryRow, FetchPolicy, ResolvedCatalog, load};
use turul_ai_catalog_trust::{
    Coverage, CoverageGap, Endorsement, EntryReport, IntegrityError, SignatureOutcome, TrustPolicy,
    TrustReport, check_artifact, fetch_artifact, verify, verify_entry,
};
#[cfg(feature = "ssm")]
use turul_ai_catalog_trust::{
    DidWebRoot, ParameterKeyStore, SignerParams, SigningKey, did_document, endorse_catalog,
    sign_catalog,
};
use turul_ai_catalog_tui::{Integrity, Opened, Signature};

#[cfg(feature = "ssm")]
use crate::diagnostic_line;
use crate::{ERRORS, FAILED, OK, SourceArgs, fail, load_failed, skip_reason};

/// `key generate` and `key did-document`.
#[cfg(feature = "ssm")]
#[derive(Subcommand)]
pub enum KeyCommand {
    /// Generate a P-256 key into a new Parameter Store parameter and print its DID document.
    Generate {
        #[command(flatten)]
        key: KeyArgs,
    },
    /// Print the DID document of the key held in a Parameter Store parameter.
    DidDocument {
        #[command(flatten)]
        key: KeyArgs,
    },
}

/// Where the key is held and which DID and key fragment it signs as.
#[cfg(feature = "ssm")]
#[derive(Args)]
pub struct KeyArgs {
    /// The Parameter Store parameter holding the PKCS#8 PEM key.
    #[arg(long)]
    ssm_parameter: String,
    /// The root did:web DID of the signer.
    #[arg(long)]
    did: String,
    /// The fragment of the key id: the DID, `#`, then this.
    #[arg(long)]
    fragment: String,
}

/// `sign`.
#[cfg(feature = "ssm")]
#[derive(Args)]
pub struct SignArgs {
    #[command(flatten)]
    source: SourceArgs,
    #[command(flatten)]
    key: KeyArgs,
    /// The signature's issuedAt, RFC 3339.
    #[arg(long)]
    issued_at: String,
    /// The signature's expiresAt, RFC 3339.
    #[arg(long)]
    expires_at: Option<String>,
    /// Sign the whole catalog as it is instead of endorsing its entries.
    #[arg(long)]
    catalog: bool,
}

/// `verify`.
#[derive(Args)]
pub struct VerifyArgs {
    #[command(flatten)]
    source: SourceArgs,
    /// Exit 1 when any entry has no endorsement by its publisher.
    #[arg(long)]
    require_publisher: bool,
}

#[cfg(feature = "ssm")]
fn signer(did: &str) -> Result<DidWebRoot, String> {
    DidWebRoot::parse(did).ok_or_else(|| format!("{did} is not a root did:web DID"))
}

#[cfg(feature = "ssm")]
fn runtime() -> Result<tokio::runtime::Runtime, String> {
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|e| e.to_string())
}

#[cfg(feature = "ssm")]
async fn parameter(name: &str) -> ParameterKeyStore {
    let config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
    ParameterKeyStore::new(aws_sdk_ssm::Client::new(&config), name.to_string())
}

#[cfg(feature = "ssm")]
fn write_stdout(bytes: &[u8]) -> u8 {
    let mut out = io::stdout().lock();
    if out.write_all(bytes).and_then(|()| out.flush()).is_ok() {
        OK
    } else {
        FAILED
    }
}

/// Runs a `key` command and returns its exit code.
#[cfg(feature = "ssm")]
pub fn key(command: KeyCommand) -> u8 {
    let (args, generate) = match command {
        KeyCommand::Generate { key } => (key, true),
        KeyCommand::DidDocument { key } => (key, false),
    };
    let signer = match signer(&args.did) {
        Ok(signer) => signer,
        Err(message) => return fail(&message),
    };
    let runtime = match runtime() {
        Ok(runtime) => runtime,
        Err(message) => return fail(&message),
    };
    let key = if generate {
        SigningKey::generate()
    } else {
        match runtime.block_on(async { parameter(&args.ssm_parameter).await.load().await }) {
            Ok(key) => key,
            Err(e) => return fail(&e.to_string()),
        }
    };
    // The document is built before the key is stored, so a bad fragment writes nothing.
    let document = match key
        .public_jwk()
        .and_then(|jwk| did_document(&signer, &args.fragment, &jwk))
    {
        Ok(document) => document,
        Err(e) => return fail(&e.to_string()),
    };
    if generate
        && let Err(e) =
            runtime.block_on(async { parameter(&args.ssm_parameter).await.create(&key).await })
    {
        return fail(&e.to_string());
    }
    match document.to_canonical_vec() {
        Ok(bytes) => write_stdout(&bytes),
        Err(e) => fail(&turul_ai_catalog::error::chain(&e)),
    }
}

/// Runs `sign` and returns its exit code.
#[cfg(feature = "ssm")]
pub fn sign(args: SignArgs) -> u8 {
    let signer = match signer(&args.key.did) {
        Ok(signer) => signer,
        Err(message) => return fail(&message),
    };
    let (source, _) = match args.source.source() {
        Ok(s) => s,
        Err(message) => return fail(&message),
    };
    // Only the root is wanted: a file sends no request, a URL needs exactly its own.
    let mut policy = FetchPolicy::default();
    policy.max_requests = u32::from(!matches!(source, turul_ai_catalog_client::Source::File(_)));
    let tree = match load(&source, &policy) {
        Ok(tree) => tree,
        Err(e) => return load_failed(&e),
    };
    if tree.has_errors() {
        for d in tree.report.diagnostics() {
            eprintln!("{}", diagnostic_line(d));
        }
        return ERRORS;
    }
    let runtime = match runtime() {
        Ok(runtime) => runtime,
        Err(message) => return fail(&message),
    };
    let key =
        match runtime.block_on(async { parameter(&args.key.ssm_parameter).await.load().await }) {
            Ok(key) => key,
            Err(e) => return fail(&e.to_string()),
        };
    // Digest retrieval is blocking, so it runs outside the runtime.
    drop(runtime);
    let params = SignerParams {
        signer,
        key_fragment: args.key.fragment,
        issued_at: args.issued_at,
        expires_at: args.expires_at,
    };
    let base = tree.base.clone();
    let document = tree.document;
    let result = if args.catalog {
        sign_catalog(document, &params, &key).map_err(|e| turul_ai_catalog::error::chain(&e))
    } else {
        endorse_catalog(
            document,
            base.as_deref(),
            &params,
            &key,
            &FetchPolicy::default(),
        )
        .map_err(|e| turul_ai_catalog::error::chain(&e))
    };
    match result {
        Ok(catalog) => match catalog.to_json().to_canonical_vec() {
            Ok(bytes) => write_stdout(&bytes),
            Err(e) => fail(&turul_ai_catalog::error::chain(&e)),
        },
        Err(message) => fail(&message),
    }
}

/// Runs `verify` and returns its exit code.
pub fn verify_command(args: VerifyArgs) -> u8 {
    let (source, label) = match args.source.source() {
        Ok(s) => s,
        Err(message) => return fail(&message),
    };
    let tree = match load(&source, &FetchPolicy::default()) {
        Ok(tree) => tree,
        Err(e) => return load_failed(&e),
    };
    let report = verify(&tree, &TrustPolicy::default(), SystemTime::now());
    let mut stdout = io::stdout().lock();
    let rejected = match write_report(&report, &label, &mut stdout) {
        Ok(failed) => failed,
        Err(_) => return FAILED,
    };
    // A catalog that was not loaded, or that is invalid, was not verified.
    let unverified = match write_skipped(&tree, &mut stdout) {
        Ok(skipped) => skipped || tree.has_errors(),
        Err(_) => return FAILED,
    };
    if stdout.flush().is_err() {
        return FAILED;
    }
    if unverified
        || rejected.signature
        || rejected.integrity
        || (args.require_publisher && rejected.unendorsed)
    {
        ERRORS
    } else {
        OK
    }
}

/// Writes `skipped <reason> <url>` for every nested catalog of `tree` that was not loaded, and
/// `skipped embedded <identifier>` for every one embedded as `data`, and returns whether there
/// was one.
fn write_skipped(tree: &ResolvedCatalog, out: &mut dyn Write) -> io::Result<bool> {
    let mut any = false;
    // A catalog embedded as `data` is not loaded as a node, so its entries are never verified.
    for entry in &tree.document.entries {
        if entry.artifact_type == ArtifactType::AI_CATALOG
            && matches!(entry.source, ArtifactSource::Data(_))
        {
            writeln!(
                out,
                "skipped embedded {}",
                DisplayText::new(entry.identifier.as_str())
            )?;
            any = true;
        }
    }
    for n in &tree.children {
        match &n.child {
            Child::Catalog(c) => any |= write_skipped(c, out)?,
            Child::Skipped { url, reason } => {
                writeln!(
                    out,
                    "skipped {} {}",
                    DisplayText::new(&skip_reason(reason)),
                    DisplayText::new(url)
                )?;
                any = true;
            }
        }
    }
    Ok(any)
}

/// What the report holds that fails a verification.
#[derive(Default)]
struct Failures {
    signature: bool,
    integrity: bool,
    unendorsed: bool,
}

fn outcome_text(outcome: &SignatureOutcome<'_>) -> String {
    match outcome {
        SignatureOutcome::Unsigned => "unsigned".to_string(),
        SignatureOutcome::Accepted(_) => "accepted".to_string(),
        SignatureOutcome::Rejected(reason) => format!("rejected: {reason}"),
        _ => "unknown".to_string(),
    }
}

/// One line per catalog node (`catalog <source> signature <outcome>`) and per entry
/// (`entry <identifier> endorsement <publisher|contributor|none> integrity <ok|-|failure>`).
fn write_report(
    report: &TrustReport<'_>,
    root_label: &str,
    out: &mut dyn Write,
) -> io::Result<Failures> {
    let mut failures = Failures::default();
    for (index, node) in report.catalogs.iter().enumerate() {
        let label = if index == 0 {
            root_label
        } else {
            node.base.unwrap_or("(nested catalog)")
        };
        writeln!(
            out,
            "catalog {} signature {}",
            DisplayText::new(label),
            DisplayText::new(&outcome_text(&node.signature))
        )?;
        failures.signature |= matches!(node.signature, SignatureOutcome::Rejected(_));
        for entry in &node.entries {
            let level = entry.endorsement();
            let integrity = match &entry.integrity {
                None => "-".to_string(),
                Some(Ok(())) => "ok".to_string(),
                Some(Err(e)) => {
                    failures.integrity = true;
                    e.to_string()
                }
            };
            failures.signature |= entry
                .manifests
                .iter()
                .any(|m| matches!(m.signature, SignatureOutcome::Rejected(_)));
            failures.unendorsed |= level != Endorsement::Publisher;
            let level = match level {
                Endorsement::Publisher => "publisher",
                Endorsement::Contributor => "contributor",
                _ => "none",
            };
            writeln!(
                out,
                "entry {} endorsement {level} integrity {}",
                DisplayText::new(entry.entry.identifier.as_str()),
                DisplayText::new(&integrity)
            )?;
        }
    }
    Ok(failures)
}

/// Retrieves the entry's artifact once, under the default fetch policy, compares those bytes
/// with the entry's digest, and verifies the entry's trust manifests as `verify` does.
pub(crate) fn open_artifact(node: &ResolvedCatalog, row: &EntryRow) -> Opened {
    let entry = &node.document.entries[row.index];
    match fetch_artifact(entry, node.base.as_deref(), &FetchPolicy::default()) {
        Err(e) => Opened::Failed(turul_ai_catalog::error::chain(&e)),
        Ok(body) => {
            let integrity = match check_artifact(entry, &body) {
                Ok(()) => Integrity::Matches,
                Err(IntegrityError::DigestMissing) => {
                    Integrity::Unchecked(IntegrityError::DigestMissing.to_string())
                }
                Err(e) => Integrity::Failed(e.to_string()),
            };
            let report = verify_entry(
                entry,
                node.base.as_deref(),
                &TrustPolicy::default(),
                SystemTime::now(),
            );
            Opened::Artifact {
                body,
                integrity,
                signature: signature_status(&report),
            }
        }
    }
}

/// The strongest endorsement of the entry and its signer, or why none can be relied on.
fn signature_status(report: &EntryReport<'_>) -> Signature {
    if report.manifests.is_empty() {
        return Signature::Unsigned;
    }
    if let Some((signer, endorsement)) = report.endorsing_signer() {
        return Signature::Endorsed {
            signer: signer.as_str().to_string(),
            publisher: endorsement == Endorsement::Publisher,
        };
    }
    let why = report
        .manifests
        .iter()
        .find_map(|m| match (&m.signature, &m.coverage) {
            (SignatureOutcome::Rejected(reason), _) => {
                Some(format!("signature rejected: {reason}"))
            }
            (_, Some(Coverage::Uncovered(gap))) => Some(match gap {
                CoverageGap::SubjectMismatch => "its subject is not this entry".to_string(),
                CoverageGap::Integrity(e) => format!("the artifact it covers: {e}"),
                _ => "it does not cover this entry".to_string(),
            }),
            _ => None,
        })
        .unwrap_or_else(|| "no accepted signature".to_string());
    Signature::NotRelied(why)
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use std::time::SystemTime;

    use turul_ai_catalog_client::{FetchPolicy, Fetched, Source, load};
    use turul_ai_catalog_trust::{
        DidDocuments, DidWebRoot, SignerParams, SigningKey, TrustPolicy, accept_document,
        did_document, endorse_entry, verify_entry_resolved,
    };
    use turul_ai_catalog_tui::{Integrity, Opened, Signature};

    use super::{open_artifact, signature_status};

    // #verification-result: "Failure MUST NOT be treated as a verified endorsement." Only bytes
    // that hash to the entry's digest are reported as matching.
    #[test]
    fn opening_maps_each_digest_outcome_to_its_own_status() {
        let path: PathBuf = [
            env!("CARGO_MANIFEST_DIR"),
            "tests",
            "fixtures",
            "open-artifact.json",
        ]
        .iter()
        .collect();
        let tree = load(&Source::File(path), &FetchPolicy::default()).expect("fixture loads");
        let opened: Vec<Opened> = tree.rows.iter().map(|r| open_artifact(&tree, r)).collect();
        let body = br#"{"name":"a"}"#.to_vec();
        assert_eq!(
            opened[0],
            Opened::Artifact {
                body: body.clone(),
                integrity: Integrity::Matches,
                signature: Signature::Unsigned,
            }
        );
        assert_eq!(
            opened[1],
            Opened::Artifact {
                body,
                integrity: Integrity::Unchecked("entry has no digest".into()),
                signature: Signature::Unsigned,
            }
        );
        assert!(matches!(
            &opened[2],
            Opened::Artifact { integrity: Integrity::Failed(why), .. } if why.starts_with("digest mismatch")
        ));
        assert!(
            matches!(&opened[3], Opened::Failed(_)),
            "a relative url from a file root"
        );
        // A manifest whose JWS header is not JSON is rejected before any DID document is fetched.
        assert!(matches!(
            &opened[4],
            Opened::Artifact { integrity: Integrity::Matches, signature: Signature::NotRelied(why), .. }
                if why == "signature rejected: protected header refused"
        ));
    }

    // #level-3-trusted-catalog, #entry-release-coverage: the publisher's covering signature is
    // Endorsed with `publisher`, another contributor's without it, and a manifest whose subject no
    // longer binds the entry is not relied on.
    #[test]
    fn signature_status_names_the_endorsing_signer_or_why_none() {
        let path: PathBuf = [
            env!("CARGO_MANIFEST_DIR"),
            "tests",
            "fixtures",
            "open-artifact.json",
        ]
        .iter()
        .collect();
        let tree = load(&Source::File(path), &FetchPolicy::default()).expect("fixture loads");
        let key = SigningKey::generate();
        let jwk = key.public_jwk().expect("public key");
        let mut docs = DidDocuments::new();
        let signed = |did: &str| {
            let signer = DidWebRoot::parse(did).expect("root did:web");
            let params = SignerParams {
                signer: signer.clone(),
                key_fragment: "key-1".into(),
                issued_at: "2026-09-12T10:00:00Z".into(),
                expires_at: None,
            };
            // Entry 0 is inline `data` whose digest matches.
            let entry =
                endorse_entry(tree.document.entries[0].clone(), &params, &key).expect("endorsed");
            (signer, entry)
        };
        let status = |entry: &turul_ai_catalog::model::CatalogEntry, docs: &DidDocuments| {
            let report = verify_entry_resolved(
                entry,
                None,
                docs,
                &TrustPolicy::default(),
                SystemTime::now(),
            );
            signature_status(&report)
        };
        for did in ["did:web:example.com", "did:web:other.example"] {
            let signer = DidWebRoot::parse(did).expect("root did:web");
            let document = did_document(&signer, "key-1", &jwk).expect("document");
            let fetched = Fetched::new(
                200,
                Some("application/did+json".into()),
                document.to_canonical_vec().expect("bytes"),
            );
            docs.insert(signer.clone(), accept_document(&fetched, &signer));
        }

        let (_, publisher) = signed("did:web:example.com");
        assert_eq!(
            status(&publisher, &docs),
            Signature::Endorsed {
                signer: "did:web:example.com".into(),
                publisher: true
            }
        );
        let (_, contributor) = signed("did:web:other.example");
        assert_eq!(
            status(&contributor, &docs),
            Signature::Endorsed {
                signer: "did:web:other.example".into(),
                publisher: false
            }
        );
        let (_, mut moved) = signed("did:web:example.com");
        moved.version = Some("2.0.0".into());
        assert_eq!(
            status(&moved, &docs),
            Signature::NotRelied("its subject is not this entry".into())
        );
    }
}