auths-cli 0.1.3

Command-line interface for Auths decentralized identity system
Documentation
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
//! `auths credential …` — issue / revoke / list / verify capability credentials.
//!
//! A credential is an ACDC anchored to the issuer's KEL via a backerless TEL. This is
//! the thin presentation layer; all orchestration (issuee guard, registry, issuer-sign,
//! `iss`/`rev` anchor, the verify resolution + freshness layer) lives in
//! `auths_sdk::domains::credentials`. The clock (`Utc::now()`) is read only here.

use std::path::PathBuf;
use std::sync::Arc;

use anyhow::Result;
use clap::{Parser, Subcommand};
use serde::Serialize;

use auths_rp::{Nonce, WirePresentation};
use auths_sdk::core_config::EnvironmentConfig;
use auths_sdk::domains::credentials::{
    CredentialVerdict, PresentationChallenge, VerifierWitnessPolicy, issue, list,
    present_credential, revoke, verify_by_said,
};
use auths_sdk::keychain::KeyAlias;
use auths_sdk::signing::PassphraseProvider;
use auths_sdk::storage_layout::layout;

use crate::commands::executable::ExecutableCommand;
use crate::config::CliConfig;
use crate::factories::storage::build_auths_context;
use crate::ux::format::{JsonResponse, is_json_mode};

/// Issue, revoke, list, and verify capability credentials (ACDCs).
#[derive(Parser, Debug, Clone)]
#[command(
    about = "Issue, revoke, list, and verify capability credentials (ACDCs).",
    after_help = "Examples:
  auths credential issue --issuer my-key --to did:keri:E… --cap sign --role deployer
  auths credential revoke ECred… --issuer my-key
  auths credential list --issuer my-key
  auths credential verify ECred… --issuer my-key --require-witnesses"
)]
pub struct CredentialCommand {
    #[clap(subcommand)]
    pub subcommand: CredentialSubcommand,
}

/// Credential subcommands.
#[derive(Subcommand, Debug, Clone)]
pub enum CredentialSubcommand {
    /// Issue a capability credential to an issuee (its KEL must already exist).
    Issue {
        /// The issuer's signing key name (your identity's key).
        #[arg(long, help = "The issuer's signing key name (your identity's key).")]
        issuer: String,

        /// The issuee/subject `did:keri:` to credential.
        #[arg(long = "to", help = "The issuee/subject did:keri to credential.")]
        to: String,

        /// Capability to grant (repeatable).
        #[arg(long = "cap", help = "Capability to grant (repeatable).")]
        cap: Vec<auths_keri::Capability>,

        /// Informational role claim.
        #[arg(long, help = "Informational role claim (e.g. deployer).")]
        role: Option<String>,

        /// Expire the credential this many seconds from now.
        #[arg(long = "expires-in", help = "Expire the credential after N seconds.")]
        expires_in: Option<i64>,
    },

    /// Revoke a credential (anchors a `rev` in the issuer's KEL). Idempotent.
    Revoke {
        /// The credential SAID to revoke.
        #[arg(help = "The credential SAID to revoke.")]
        credential_said: String,

        /// The issuer's signing key name.
        #[arg(long, help = "The issuer's signing key name.")]
        issuer: String,
    },

    /// List the issuer's live credentials (issued − revoked).
    List {
        /// The issuer's signing key name.
        #[arg(long, help = "The issuer's signing key name.")]
        issuer: Option<String>,

        /// Include revoked credentials in the listing.
        #[arg(long, help = "Include revoked credentials.")]
        include_revoked: bool,
    },

    /// Verify a credential, resolving the issuer KEL/TEL + witness receipts.
    Verify {
        /// The credential SAID to verify.
        #[arg(help = "The credential SAID to verify.")]
        credential_said: String,

        /// The issuer's signing key name (whose namespace holds the credential).
        #[arg(long, help = "The issuer's signing key name.")]
        issuer: String,

        /// Fail closed unless every lifecycle anchor reaches witness quorum.
        #[arg(
            long = "require-witnesses",
            help = "Fail closed unless every lifecycle anchor reaches witness quorum."
        )]
        require_witnesses: bool,
    },

    /// Present a credential: prove control of the subject AID and emit an `Auths-Presentation` header.
    Present {
        /// The subject (holder/agent) keychain alias whose current key signs the presentation.
        #[arg(long, help = "The subject (holder) keychain alias to sign with.")]
        subject: String,

        /// The credential SAID to present.
        #[arg(long = "said", help = "The credential SAID to present.")]
        said: String,

        /// The relying-party audience the presentation binds to.
        #[arg(long, help = "The relying-party audience to bind to.")]
        audience: String,

        /// The base64url challenge nonce issued by the relying party.
        #[arg(long, help = "The base64url challenge nonce from /v1/auth/challenge.")]
        nonce: String,
    },
}

/// JSON response for `credential issue`.
#[derive(Debug, Serialize)]
struct IssueResponse {
    credential_said: String,
    registry_said: String,
    issuer_did: String,
    issuee_did: String,
}

impl ExecutableCommand for CredentialCommand {
    fn execute(&self, ctx: &CliConfig) -> Result<()> {
        let repo_path = layout::resolve_repo_path(ctx.repo_path.clone())?;
        handle_credential(
            self.clone(),
            repo_path,
            &ctx.env_config,
            ctx.passphrase_provider.clone(),
        )
    }
}

/// Dispatch an `auths credential …` subcommand.
///
/// Args:
/// * `cmd`: The parsed credential command.
/// * `repo_path`: Resolved registry repository path.
/// * `env_config`: Environment configuration for context building.
/// * `passphrase_provider`: Passphrase source for issuer key access.
///
/// Usage:
/// ```ignore
/// handle_credential(cmd, repo_path, &env_config, passphrase_provider)?;
/// ```
pub fn handle_credential(
    cmd: CredentialCommand,
    repo_path: PathBuf,
    env_config: &EnvironmentConfig,
    passphrase_provider: Arc<dyn PassphraseProvider + Send + Sync>,
) -> Result<()> {
    match cmd.subcommand {
        CredentialSubcommand::Issue {
            issuer,
            to,
            cap,
            role,
            expires_in,
        } => {
            let ctx = build_auths_context(&repo_path, env_config, Some(passphrase_provider))?;
            let issuer_alias = KeyAlias::new_unchecked(issuer);
            // Clock at the presentation boundary (the SDK/core never call Utc::now()).
            #[allow(clippy::disallowed_methods)]
            let expires_at =
                expires_in.map(|secs| chrono::Utc::now() + chrono::Duration::seconds(secs));
            let issued = issue(&ctx, &issuer_alias, &to, &cap, role.as_deref(), expires_at)
                .map_err(anyhow::Error::new)?;

            if is_json_mode() {
                JsonResponse::success(
                    "credential issue",
                    IssueResponse {
                        credential_said: issued.credential_said.clone(),
                        registry_said: issued.registry_said.clone(),
                        issuer_did: issued.issuer_did.clone(),
                        issuee_did: issued.issuee_did.clone(),
                    },
                )
                .print()?;
            } else {
                println!("✓ Credential issued and anchored to the issuer KEL:");
                println!("  credential: {}", issued.credential_said);
                println!("  issuee:     {}", issued.issuee_did);
            }
            Ok(())
        }

        CredentialSubcommand::Present {
            subject,
            said,
            audience,
            nonce,
        } => {
            let ctx = build_auths_context(&repo_path, env_config, Some(passphrase_provider))?;
            let subject_alias = KeyAlias::new_unchecked(subject);
            let challenge_nonce = Nonce::parse_b64url(&nonce).map_err(anyhow::Error::new)?;
            let envelope = present_credential(
                &ctx,
                &subject_alias,
                &said,
                &audience,
                PresentationChallenge::Challenge {
                    nonce: challenge_nonce.as_bytes().to_vec(),
                },
            )
            .map_err(anyhow::Error::new)?;
            let token = WirePresentation::from_envelope(&envelope)
                .to_token()
                .map_err(anyhow::Error::new)?;
            let header = format!("Auths-Presentation {token}");

            if is_json_mode() {
                JsonResponse::success(
                    "credential present",
                    serde_json::json!({ "authorization": header }),
                )
                .print()?;
            } else {
                println!("{header}");
            }
            Ok(())
        }

        CredentialSubcommand::Revoke {
            credential_said,
            issuer,
        } => {
            let ctx = build_auths_context(&repo_path, env_config, Some(passphrase_provider))?;
            let issuer_alias = KeyAlias::new_unchecked(issuer);
            revoke(&ctx, &issuer_alias, &credential_said).map_err(anyhow::Error::new)?;

            if is_json_mode() {
                JsonResponse::success(
                    "credential revoke",
                    serde_json::json!({ "credential_said": credential_said, "revoked": true }),
                )
                .print()?;
            } else {
                println!(
                    "✓ Credential revoked (rev anchored in the issuer KEL): {credential_said}"
                );
            }
            Ok(())
        }

        CredentialSubcommand::List {
            issuer,
            include_revoked,
        } => {
            let ctx = build_auths_context(&repo_path, env_config, Some(passphrase_provider))?;
            let issuer_alias = KeyAlias::new_unchecked(issuer.unwrap_or_default());
            let credentials = list(&ctx, &issuer_alias).map_err(anyhow::Error::new)?;
            let shown: Vec<_> = credentials
                .into_iter()
                .filter(|c| include_revoked || !c.revoked)
                .collect();

            if is_json_mode() {
                let data: Vec<_> = shown
                    .iter()
                    .map(|c| {
                        serde_json::json!({
                            "credential_said": c.credential_said,
                            "subject_did": c.subject_did,
                            "capabilities": c.capabilities,
                            "revoked": c.revoked,
                        })
                    })
                    .collect();
                JsonResponse::success(
                    "credential list",
                    serde_json::json!({ "credentials": data }),
                )
                .print()?;
            } else if shown.is_empty() {
                println!("No credentials issued by this identity.");
            } else {
                println!("Issued credentials:");
                for c in &shown {
                    let status = if c.revoked { " (revoked)" } else { "" };
                    println!(
                        "  {}{} [{}]{}",
                        c.credential_said,
                        c.subject_did,
                        c.capabilities
                            .iter()
                            .map(|cap| cap.as_str())
                            .collect::<Vec<_>>()
                            .join(","),
                        status
                    );
                }
            }
            Ok(())
        }

        CredentialSubcommand::Verify {
            credential_said,
            issuer,
            require_witnesses,
        } => {
            let ctx = build_auths_context(&repo_path, env_config, Some(passphrase_provider))?;
            let issuer_alias = KeyAlias::new_unchecked(issuer);
            let policy = if require_witnesses {
                VerifierWitnessPolicy::RequireWitnesses
            } else {
                VerifierWitnessPolicy::Warn
            };
            // Clock at the presentation boundary.
            #[allow(clippy::disallowed_methods)]
            let now = chrono::Utc::now();
            let rt = tokio::runtime::Runtime::new()?;
            let verdict = rt
                .block_on(verify_by_said(
                    &ctx,
                    &issuer_alias,
                    &credential_said,
                    policy,
                    now,
                ))
                .map_err(anyhow::Error::new)?;
            print_verdict(&credential_said, &verdict)
        }
    }
}

/// Render a verification verdict to stdout (JSON or human-readable).
fn print_verdict(credential_said: &str, verdict: &CredentialVerdict) -> Result<()> {
    let valid = verdict.is_valid();
    let (status, detail, as_of) = describe(verdict);

    if is_json_mode() {
        JsonResponse::success(
            "credential verify",
            serde_json::json!({
                "credential_said": credential_said,
                "valid": valid,
                "status": status,
                "detail": detail,
                "as_of": as_of,
            }),
        )
        .print()?;
    } else if valid {
        println!("✓ Credential is valid: {credential_said}");
        if let Some(seq) = as_of {
            println!("  as-of issuer KEL seq {seq}");
        }
    } else {
        println!("✗ Credential did not verify: {credential_said}");
        println!("  status: {status}");
        if let Some(d) = detail {
            println!("  detail: {d}");
        }
    }
    Ok(())
}

/// A `(status, detail, as_of_seq)` summary of a verdict for presentation.
fn describe(verdict: &CredentialVerdict) -> (&'static str, Option<String>, Option<u128>) {
    use auths_verifier::CredentialVerdict as Inner;
    match verdict {
        CredentialVerdict::StaleOrUnresolvable { as_of, reason } => (
            "stale_or_unresolvable",
            Some(reason.clone()),
            Some(as_of.seq),
        ),
        CredentialVerdict::Resolved { verdict, as_of } => {
            let seq = Some(as_of.seq);
            match verdict {
                Inner::Valid { .. } => ("valid", None, seq),
                Inner::SaidMismatch => ("said_mismatch", None, seq),
                Inner::SchemaInvalid => ("schema_invalid", None, seq),
                Inner::IssuerSignatureInvalid => ("issuer_signature_invalid", None, seq),
                Inner::RegistryNotEstablished => ("registry_not_established", None, seq),
                Inner::CredentialRevoked { revoked_at } => (
                    "revoked",
                    Some(format!("revoked at issuer KEL seq {revoked_at}")),
                    seq,
                ),
                Inner::Expired { expired_at, .. } => {
                    ("expired", Some(format!("expired at {expired_at}")), seq)
                }
                Inner::WitnessQuorumNotMet {
                    event,
                    collected,
                    required,
                } => (
                    "witness_quorum_not_met",
                    Some(format!(
                        "{event} anchor: {collected}/{required} witness receipts"
                    )),
                    seq,
                ),
                Inner::IssuerKelDuplicitous => ("issuer_kel_duplicitous", None, seq),
            }
        }
    }
}