auths-cli 0.1.16

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
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
//! Configuration gathering functions for the init command.

use anyhow::{Context, Result, anyhow};
use std::path::Path;
use std::sync::Arc;

use auths_infra_http::HttpRegistryClient;
use auths_sdk::keychain::{KeyAlias, KeyStorage, get_platform_keychain};
use auths_sdk::ports::AttestationSource;
use auths_sdk::ports::IdentityStorage;
use auths_sdk::storage::{
    GitRegistryBackend, RegistryAttestationStorage, RegistryConfig, RegistryIdentityStorage,
};
use auths_sdk::types::{CiEnvironment, CiIdentityConfig, CreateDeveloperIdentityConfig};

use super::InitCommand;
use super::helpers::{
    check_git_version, detect_ci_environment, get_auths_repo_path, select_agent_capabilities,
};
use super::prompts::{prompt_for_alias, prompt_for_conflict_policy, prompt_for_git_scope};
use crate::ux::format::Output;

pub(crate) fn gather_developer_config(
    interactive: bool,
    out: &Output,
    cmd: &InitCommand,
    registry_path: &Path,
) -> Result<(
    Box<dyn KeyStorage + Send + Sync>,
    CreateDeveloperIdentityConfig,
)> {
    out.print_info("Checking prerequisites...");
    let keychain = check_keychain_access(interactive, out)?;
    check_git_version(out)?;
    out.print_success("Prerequisites OK");
    out.newline();

    // State the passphrase policy up front so an interactive user learns the rule
    // before the prompt, not by failing it. Sourced from the same constant the
    // validator and the failure message use, so the three can never drift.
    if interactive {
        out.print_info(&format!(
            "Passphrase requirements: {}",
            auths_sdk::keychain::PASSPHRASE_POLICY_HINT
        ));
    }

    let alias = prompt_for_alias(interactive, cmd)?;
    let conflict_policy = prompt_for_conflict_policy(interactive, cmd, registry_path, out)?;
    let git_scope = prompt_for_git_scope(interactive, cmd.git_scope)?;

    let mut builder = CreateDeveloperIdentityConfig::builder(KeyAlias::new_unchecked(&alias))
        .with_conflict_policy(conflict_policy)
        .with_git_signing_scope(git_scope);

    if cmd.register {
        // --register is opt-in and there is no default registry, so it must name one.
        let registry = crate::commands::verify_helpers::require_registry(cmd.registry.clone())?;
        builder = builder.with_registration(&registry);
    }

    Ok((keychain, builder.build()))
}

#[allow(clippy::type_complexity)]
pub(crate) fn gather_ci_config(
    out: &Output,
    repo_opt: Option<&Path>,
) -> Result<(
    Option<String>,
    CiIdentityConfig,
    Box<dyn KeyStorage + Send + Sync>,
    String,
)> {
    out.print_info("Detecting CI environment...");
    let ci_env = detect_ci_environment();
    if let Some(ref vendor) = ci_env {
        out.print_success(&format!("Detected: {}", vendor));
    } else {
        out.print_warn("No CI environment detected, proceeding anyway");
    }
    out.newline();

    let registry_path = match repo_opt {
        Some(p) => p.to_path_buf(),
        None => std::env::current_dir()
            .context("Failed to determine current working directory")?
            .join(".auths-ci"),
    };
    let keychain_file = registry_path.join("keys.enc");
    #[allow(clippy::disallowed_methods)] // CLI boundary: CI passphrase from env
    let (passphrase, passphrase_source) = match std::env::var("AUTHS_PASSPHRASE") {
        Ok(p) => (p, "the AUTHS_PASSPHRASE environment variable"),
        Err(_) => (
            auths_sdk::types::generate_ci_passphrase(),
            "a generated per-identity ephemeral passphrase",
        ),
    };
    preflight_passphrase(&passphrase, passphrase_source)?;

    // Persist the CI key to an encrypted file co-located with the registry so a
    // separate `auths sign` process can load it — the in-memory backend would lose
    // the key the moment `init` exits. Setting these here also makes the vars present
    // for the rest of this process and matches the copy-pasteable env block we print.
    // SAFETY: single-threaded CLI context; vars read immediately below and by the SDK context.
    unsafe {
        std::env::set_var("AUTHS_KEYCHAIN_BACKEND", "file");
        std::env::set_var("AUTHS_KEYCHAIN_FILE", &keychain_file);
        std::env::set_var("AUTHS_PASSPHRASE", &passphrase);
    }
    let keychain = get_platform_keychain()
        .map_err(|e| anyhow!("Failed to get file-backed keychain: {}", e))?;

    out.print_info(&format!("Using keychain: {}", keychain.backend_name()));

    let config = CiIdentityConfig {
        ci_environment: map_ci_environment(&ci_env),
        registry_path,
        keychain_file,
        passphrase: passphrase.clone(),
    };

    Ok((ci_env, config, keychain, passphrase))
}

pub(crate) fn gather_agent_config(
    interactive: bool,
    out: &Output,
    cmd: &InitCommand,
) -> Result<(
    Box<dyn KeyStorage + Send + Sync>,
    auths_sdk::types::CreateAgentIdentityConfig,
)> {
    out.print_info("Setting capability scope...");
    let capabilities = select_agent_capabilities(interactive, out)?;
    let cap_names: Vec<String> = capabilities.iter().map(|c| c.name.clone()).collect();
    out.print_success(&format!("Capabilities: {}", cap_names.join(", ")));
    out.newline();

    let parsed_caps: Vec<auths_verifier::Capability> = cap_names
        .into_iter()
        .filter_map(|s| auths_verifier::Capability::parse(&s).ok())
        .collect();

    out.print_info("Checking prerequisites...");
    let keychain = check_keychain_access(interactive, out)?;
    out.print_success("Prerequisites OK");
    out.newline();

    let registry_path = get_auths_repo_path()?;

    let config = auths_sdk::types::CreateAgentIdentityConfig::builder(
        KeyAlias::new_unchecked("agent"),
        &registry_path,
    )
    .with_capabilities(parsed_caps)
    .with_expiry(365 * 24 * 3600)
    .dry_run(cmd.dry_run)
    .build();

    Ok((keychain, config))
}

pub(crate) fn submit_registration(
    repo_path: &Path,
    registry_url: Option<&str>,
    proof_url: Option<String>,
    skip: bool,
    out: &Output,
) -> Option<String> {
    if skip {
        out.print_info("Registration skipped (pass --register to publish to the registry)");
        return None;
    }
    // There is no default registry, and `gather` already refuses --register
    // without one — so reaching here without a URL is unreachable, not fatal.
    let Some(registry_url) = registry_url else {
        out.print_warn("Registration skipped: no registry configured (--registry <url>)");
        return None;
    };

    out.print_info("Publishing identity to Auths Registry...");
    let rt = match tokio::runtime::Runtime::new() {
        Ok(rt) => rt,
        Err(e) => {
            out.print_warn(&format!("Could not create async runtime: {e}"));
            return None;
        }
    };

    let backend = Arc::new(GitRegistryBackend::from_config_unchecked(
        RegistryConfig::single_tenant(repo_path),
    ));
    let identity_storage: Arc<dyn IdentityStorage + Send + Sync> =
        Arc::new(RegistryIdentityStorage::new(repo_path.to_path_buf()));
    let attestation_store = Arc::new(RegistryAttestationStorage::new(repo_path));
    let attestation_source: Arc<dyn AttestationSource + Send + Sync> = attestation_store;

    let registry_client = HttpRegistryClient::new();

    match rt.block_on(
        auths_sdk::domains::identity::registration::register_identity(
            identity_storage,
            backend,
            attestation_source,
            registry_url,
            proof_url,
            &registry_client,
        ),
    ) {
        Ok(outcome) => {
            out.print_success(&format!("Identity registered at {}", outcome.registry));
            Some(outcome.registry)
        }
        Err(auths_sdk::error::RegistrationError::AlreadyRegistered) => {
            out.print_success("Already registered on this registry");
            Some(registry_url.to_string())
        }
        Err(auths_sdk::error::RegistrationError::QuotaExceeded) => {
            out.print_warn("Registration quota exceeded. Run `auths id register` to retry later.");
            None
        }
        Err(auths_sdk::error::RegistrationError::NetworkError(_)) => {
            out.print_warn(
                "Could not reach the registry (offline?). Your local setup is complete.",
            );
            out.println("  Run `auths id register` when you're back online.");
            None
        }
        Err(
            e @ (auths_sdk::error::RegistrationError::InvalidDidFormat { .. }
            | auths_sdk::error::RegistrationError::IdentityLoadError(_)
            | auths_sdk::error::RegistrationError::RegistryReadError(_)
            | auths_sdk::error::RegistrationError::SerializationError(_)),
        ) => {
            out.print_warn(&format!("Could not prepare registration payload: {e}"));
            out.println("  Run `auths id register` to retry.");
            None
        }
        Err(e) => {
            out.print_warn(&format!("Registration failed: {e}"));
            None
        }
    }
}

pub(crate) fn ensure_registry_dir(registry_path: &Path) -> Result<()> {
    if !registry_path.exists() {
        std::fs::create_dir_all(registry_path).with_context(|| {
            format!(
                "Failed to create registry directory: {}",
                registry_path.display()
            )
        })?;
    }
    if git2::Repository::open(registry_path).is_err() {
        git2::Repository::init(registry_path).with_context(|| {
            format!(
                "Failed to initialize git repository: {}",
                registry_path.display()
            )
        })?;
    }
    auths_sdk::domains::identity::service::install_registry_hook(registry_path);
    Ok(())
}

/// What to do with a platform-selected keychain for a given run posture.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum KeychainSelection {
    /// The selected backend is usable as-is.
    UseSelected,
    /// A headless run selected a hardware backend, but the file backend is
    /// configured — switch to it instead of blocking on a Touch ID prompt.
    SwitchToFile,
    /// A headless run selected a hardware backend with no file backend
    /// configured — fail fast with a coded error rather than hang.
    FailFastHardware,
}

/// Decide how to treat a platform-default keychain given the run posture.
///
/// A hardware backend (Secure Enclave) needs an interactive Touch ID prompt; a
/// headless run that selects one blocks forever on a prompt that never arrives.
/// This pure decision keeps that policy testable without touching real key
/// storage.
///
/// Args:
/// * `interactive`: whether there is a TTY to prompt at.
/// * `has_backend_override`: whether `AUTHS_KEYCHAIN_BACKEND` was set.
/// * `is_hardware_backend`: whether the selected backend signs in hardware.
/// * `file_backend_ready`: whether the encrypted-file backend is fully configured.
///
/// Usage:
/// ```ignore
/// let choice = select_headless_keychain(false, false, true, false);
/// ```
pub(crate) fn select_headless_keychain(
    interactive: bool,
    has_backend_override: bool,
    is_hardware_backend: bool,
    file_backend_ready: bool,
) -> KeychainSelection {
    if interactive || has_backend_override || !is_hardware_backend {
        return KeychainSelection::UseSelected;
    }
    if file_backend_ready {
        KeychainSelection::SwitchToFile
    } else {
        KeychainSelection::FailFastHardware
    }
}

/// The typed error a headless run raises when the only usable backend needs an
/// interactive prompt. Renders as `[AUTHS-E4203]` with the file-backend remedy.
fn headless_hardware_error() -> anyhow::Error {
    anyhow::Error::new(auths_sdk::error::InitError::Key(
        auths_sdk::error::AgentError::BackendUnavailable {
            backend: "secure-enclave",
            reason: "Secure Enclave needs an interactive Touch ID prompt, \
                     unavailable in this headless session"
                .into(),
        },
    ))
}

pub(crate) fn check_keychain_access(
    interactive: bool,
    out: &Output,
) -> Result<Box<dyn KeyStorage + Send + Sync>> {
    #[allow(clippy::disallowed_methods)] // CLI boundary: backend override + file env
    let has_backend_override = std::env::var_os("AUTHS_KEYCHAIN_BACKEND").is_some();
    let keychain = get_platform_keychain().map_err(|e| anyhow!("Keychain not accessible: {e}"))?;

    #[allow(clippy::disallowed_methods)] // CLI boundary: file-backend env presence
    let file_backend_ready = std::env::var_os("AUTHS_KEYCHAIN_FILE").is_some()
        && std::env::var_os("AUTHS_PASSPHRASE").is_some();

    match select_headless_keychain(
        interactive,
        has_backend_override,
        keychain.is_hardware_backend(),
        file_backend_ready,
    ) {
        KeychainSelection::SwitchToFile => {
            // SAFETY: single-threaded CLI context; the var is read immediately below.
            unsafe { std::env::set_var("AUTHS_KEYCHAIN_BACKEND", "file") }
            let keychain =
                get_platform_keychain().map_err(|e| anyhow!("Keychain not accessible: {e}"))?;
            out.println(&format!(
                "  Keychain: {} (headless, file backend)",
                keychain.backend_name()
            ));
            preflight_env_passphrase(&*keychain)?;
            Ok(keychain)
        }
        KeychainSelection::FailFastHardware => Err(headless_hardware_error()),
        KeychainSelection::UseSelected => {
            out.println(&format!(
                "  Keychain: {} (accessible)",
                out.success(keychain.backend_name())
            ));
            preflight_env_passphrase(&*keychain)?;
            Ok(keychain)
        }
    }
}

/// Preflight a passphrase against the strength policy before any setup side
/// effect, so the failure lands at the prerequisites step with the input named —
/// not mid-flow behind a generic storage error.
pub(crate) fn preflight_passphrase(passphrase: &str, source_name: &str) -> Result<()> {
    auths_sdk::keychain::validate_passphrase(passphrase).map_err(|e| {
        // Route as the typed SetupError so the renderer prints [AUTHS-E5008] with its
        // fix line — an untyped anyhow string loses the code and the lookup.
        anyhow::Error::new(auths_sdk::error::SetupError::WeakPassphrase {
            source_name: source_name.to_string(),
            reason: e.to_string(),
        })
    })
}

/// Validate an env-supplied passphrase up front for software keychain backends.
/// Hardware backends (Secure Enclave) never use a passphrase, so nothing is
/// checked — and an interactive prompt is validated at point of use instead.
fn preflight_env_passphrase(keychain: &(dyn KeyStorage + Send + Sync)) -> Result<()> {
    if keychain.is_hardware_backend() {
        return Ok(());
    }
    #[allow(clippy::disallowed_methods)] // CLI boundary: env read for preflight
    match std::env::var("AUTHS_PASSPHRASE") {
        Ok(passphrase) => {
            preflight_passphrase(&passphrase, "the AUTHS_PASSPHRASE environment variable")
        }
        Err(_) => Ok(()),
    }
}

pub(crate) fn map_ci_environment(detected: &Option<String>) -> CiEnvironment {
    auths_sdk::domains::ci::map_ci_environment(detected)
}

#[cfg(test)]
mod tests {
    use super::*;
    use auths_sdk::error::AuthsErrorInfo;

    #[test]
    fn headless_hardware_without_file_backend_fails_fast() {
        // A non-interactive run that lands on a hardware backend with no file
        // backend configured must fail fast, not select the enclave and hang on a
        // Touch ID prompt that never arrives.
        assert_eq!(
            select_headless_keychain(false, false, true, false),
            KeychainSelection::FailFastHardware
        );
    }

    #[test]
    fn headless_hardware_with_file_backend_switches_to_file() {
        assert_eq!(
            select_headless_keychain(false, false, true, true),
            KeychainSelection::SwitchToFile
        );
    }

    #[test]
    fn interactive_or_override_or_software_uses_selected_backend() {
        // Interactive runs may prompt; an explicit override is the user's choice;
        // a software backend never blocks. All three keep the selected backend.
        assert_eq!(
            select_headless_keychain(true, false, true, false),
            KeychainSelection::UseSelected
        );
        assert_eq!(
            select_headless_keychain(false, true, true, false),
            KeychainSelection::UseSelected
        );
        assert_eq!(
            select_headless_keychain(false, false, false, false),
            KeychainSelection::UseSelected
        );
    }

    #[test]
    fn headless_hardware_error_carries_the_key_code_and_file_remedy() {
        // The fail-fast path must surface AUTHS-E4203 with the AUTHS_KEYCHAIN_BACKEND=file
        // escape hatch — the code and remedy the headless user needs.
        let err = headless_hardware_error();
        let init = err
            .chain()
            .find_map(|c| c.downcast_ref::<auths_sdk::error::InitError>())
            .expect("headless hardware failure must be a typed InitError");
        assert_eq!(init.error_code(), "AUTHS-E4203");
        let suggestion = init.suggestion().unwrap_or_default();
        assert!(
            suggestion.contains("AUTHS_KEYCHAIN_BACKEND=file"),
            "E4203 must name the file-backend escape hatch, got: {suggestion}"
        );
    }
}