Skip to main content

auths_cli/commands/device/
authorization.rs

1use anyhow::{Context, Result, anyhow};
2use clap::{Args, Subcommand};
3use log::warn;
4use serde::Serialize;
5use serde_json::Value;
6use std::fs;
7use std::path::{Path, PathBuf};
8use std::sync::Arc;
9
10use auths_sdk::core_config::EnvironmentConfig;
11use auths_sdk::identity::ManagedIdentity;
12use auths_sdk::keychain::KeyAlias;
13use auths_sdk::ports::{AttestationSource, IdentityStorage};
14use auths_sdk::signing::{PassphraseProvider, UnifiedPassphraseProvider};
15use auths_sdk::storage::{RegistryAttestationStorage, RegistryIdentityStorage};
16use auths_sdk::storage_layout::{StorageLayoutConfig, layout};
17
18use crate::commands::registry_overrides::RegistryOverrides;
19use crate::factories::storage::build_auths_context;
20use crate::ux::format::{JsonResponse, is_json_mode};
21
22#[derive(Serialize)]
23struct DeviceEntry {
24    id: String,
25    /// `active` or `revoked` — a delegated device carries no expiry (KERI
26    /// delegation has no timestamps).
27    status: String,
28    /// Always true for a delegated device: its `dip` is anchored by the root.
29    anchored: bool,
30}
31
32#[derive(Args, Debug, Clone)]
33#[command(
34    about = "Manage which devices can sign with your identity.",
35    after_help = "Examples:
36  auths device list         # List authorized devices
37  auths device link --key identity-key --device-key device-key --device did:key:...
38                            # Authorize a new device
39  auths device revoke       # Revoke a device
40  auths device extend       # Extend device expiry
41
42Related:
43  auths status  — Show device status and expiry
44  auths init    — Set up identity and signing"
45)]
46pub struct DeviceCommand {
47    #[command(subcommand)]
48    pub command: DeviceSubcommand,
49
50    #[command(flatten)]
51    pub overrides: RegistryOverrides,
52}
53
54#[derive(Subcommand, Debug, Clone)]
55pub enum DeviceSubcommand {
56    /// List all authorized devices for the current identity.
57    List {
58        /// Include devices with revoked or expired authorizations in the output.
59        #[arg(
60            long,
61            help = "Include devices with revoked or expired authorizations in the output."
62        )]
63        include_revoked: bool,
64    },
65
66    /// Add a device as a delegated identifier of the identity.
67    ///
68    /// The new device gets its own KERI KEL (a delegated inception) that the
69    /// root identity anchors — the keripy-native, device-bound way to grant a
70    /// device signing authority. (Use `link` for the legacy attestation flow.)
71    Add {
72        #[arg(long, help = "Your identity's signing key name.")]
73        key: String,
74
75        #[arg(long, help = "Keychain alias to store the new device's key under.")]
76        device_key: String,
77
78        #[arg(
79            long,
80            default_value = "p256",
81            help = "Curve for the new device key (p256 or ed25519)."
82        )]
83        curve: String,
84    },
85
86    /// Authorize a new device to act on behalf of the identity (legacy attestation).
87    Link {
88        #[arg(long, help = "Your identity's key name.")]
89        key: String,
90
91        #[arg(
92            long,
93            help = "The new device's key name (import first with: auths key import)."
94        )]
95        device_key: String,
96
97        #[arg(
98            long,
99            visible_alias = "device",
100            help = "The device's ID (must match --device-key)."
101        )]
102        device_did: String,
103
104        #[arg(
105            long,
106            value_name = "PAYLOAD_PATH",
107            help = "Optional path to a JSON file containing arbitrary payload data for the authorization."
108        )]
109        payload: Option<PathBuf>,
110
111        #[arg(
112            long,
113            value_name = "SCHEMA_PATH",
114            help = "Optional path to a JSON schema for validating the payload (experimental)."
115        )]
116        schema: Option<PathBuf>,
117
118        /// Duration in seconds until expiration (per RFC 6749).
119        #[arg(
120            long = "expires-in",
121            value_name = "SECS",
122            help = "Optional number of seconds until this device authorization expires."
123        )]
124        expires_in: Option<u64>,
125
126        #[arg(
127            long,
128            help = "Optional description/note for this device authorization."
129        )]
130        note: Option<String>,
131    },
132
133    /// Remove a device from the shared identity's controller set by
134    /// signing a rotation on the shared KEL.
135    ///
136    /// Semantically distinct from `revoke`: `remove` changes *who can
137    /// sign for the identity* by producing a new `rot` event; `revoke`
138    /// produces an attestation revocation that marks a specific
139    /// attestation inactive without touching the controller set.
140    ///
141    /// Self-removal is rejected at the CLI with a pointer to
142    /// `auths reset`. The authoritative guard lives in the
143    /// SDK — even callers that bypass the CLI check hit
144    /// `SharedKelError::WouldOrphanIdentity`.
145    Remove {
146        /// The controller DID (`did:keri:E…`) to drop.
147        #[arg(long, visible_alias = "device", help = "The controller DID to remove.")]
148        device_did: String,
149
150        #[arg(long, help = "Your identity's signing key name.")]
151        key: String,
152    },
153
154    /// Revoke an existing device authorization using the identity key.
155    Revoke {
156        #[arg(long, visible_alias = "device", help = "The device's ID to revoke.")]
157        device_did: String,
158
159        #[arg(long, help = "Your identity's key name.")]
160        key: String,
161
162        #[arg(long, help = "Optional note explaining the revocation.")]
163        note: Option<String>,
164
165        #[arg(long, help = "Preview actions without making changes.")]
166        dry_run: bool,
167    },
168
169    /// Resolve a device to its owner identity.
170    Resolve {
171        #[arg(
172            long,
173            visible_alias = "device",
174            help = "The device ID to resolve (e.g. did:key:z6Mk...)."
175        )]
176        device_did: String,
177    },
178
179    /// Link devices to your identity via QR code or short code.
180    Pair(super::pair::PairCommand),
181
182    /// Verify device authorization signatures (attestation).
183    #[command(name = "verify")]
184    VerifyAttestation(super::verify_attestation::VerifyCommand),
185
186    /// Extend the expiration date of an existing device authorization.
187    Extend {
188        #[arg(long, visible_alias = "device", help = "The device's ID to extend.")]
189        device_did: String,
190
191        /// Duration in seconds until expiration (per RFC 6749).
192        #[arg(
193            long = "expires-in",
194            value_name = "SECS",
195            help = "Number of seconds to extend the expiration by (from now)."
196        )]
197        expires_in: u64,
198
199        #[arg(long, help = "Your identity's key name.")]
200        key: String,
201
202        #[arg(long, help = "The device's key name.")]
203        device_key: String,
204    },
205}
206
207#[allow(clippy::too_many_arguments)]
208pub fn handle_device(
209    cmd: DeviceCommand,
210    repo_opt: Option<PathBuf>,
211    identity_ref_override: Option<String>,
212    identity_blob_name_override: Option<String>,
213    attestation_prefix_override: Option<String>,
214    attestation_blob_name_override: Option<String>,
215    passphrase_provider: Arc<dyn PassphraseProvider + Send + Sync>,
216    env_config: &EnvironmentConfig,
217) -> Result<()> {
218    let repo_path = layout::resolve_repo_path(repo_opt)?;
219
220    let mut config = StorageLayoutConfig::default();
221    if let Some(identity_ref) = identity_ref_override {
222        config.identity_ref = identity_ref.into();
223    }
224    if let Some(blob_name) = identity_blob_name_override {
225        config.identity_blob_name = blob_name.into();
226    }
227    if let Some(prefix) = attestation_prefix_override {
228        config.device_attestation_prefix = prefix.into();
229    }
230    if let Some(blob_name) = attestation_blob_name_override {
231        config.attestation_blob_name = blob_name.into();
232    }
233
234    match cmd.command {
235        DeviceSubcommand::List { include_revoked } => {
236            list_devices(&repo_path, env_config, include_revoked)
237        }
238        DeviceSubcommand::Resolve { device_did } => resolve_device(&repo_path, &device_did),
239        DeviceSubcommand::Pair(pair_cmd) => {
240            super::pair::handle_pair(pair_cmd, passphrase_provider.clone(), env_config)
241        }
242        DeviceSubcommand::VerifyAttestation(verify_cmd) => {
243            let rt = tokio::runtime::Runtime::new()?;
244            rt.block_on(super::verify_attestation::handle_verify(verify_cmd))
245        }
246        DeviceSubcommand::Link {
247            key,
248            device_key,
249            device_did,
250            payload: payload_path_opt,
251            schema: schema_path_opt,
252            expires_in,
253            note,
254        } => {
255            let payload = read_payload_file(payload_path_opt.as_deref())?;
256            validate_payload_schema(schema_path_opt.as_deref(), &payload)?;
257
258            let link_config = auths_sdk::types::DeviceLinkConfig {
259                identity_key_alias: KeyAlias::new_unchecked(key),
260                device_key_alias: Some(KeyAlias::new_unchecked(device_key)),
261                device_did: Some(device_did.clone()),
262                expires_in,
263                note,
264                payload,
265            };
266
267            let passphrase_provider: Arc<dyn PassphraseProvider + Send + Sync> =
268                Arc::new(UnifiedPassphraseProvider::new(passphrase_provider));
269            let ctx = build_auths_context(
270                &repo_path,
271                env_config,
272                Some(Arc::clone(&passphrase_provider)),
273            )?;
274
275            let result = auths_sdk::domains::device::service::link_device(
276                link_config,
277                &ctx,
278                &auths_sdk::ports::SystemClock,
279            )
280            .map_err(anyhow::Error::new)?;
281
282            display_link_result(&result, &device_did)
283        }
284
285        DeviceSubcommand::Add {
286            key,
287            device_key,
288            curve,
289        } => {
290            let curve = parse_curve(&curve)?;
291            let ctx = build_auths_context(
292                &repo_path,
293                env_config,
294                Some(Arc::clone(&passphrase_provider)),
295            )?;
296            let root_alias = KeyAlias::new_unchecked(key);
297            let device_alias = KeyAlias::new_unchecked(device_key);
298            let result =
299                auths_sdk::domains::device::add_device(&ctx, &root_alias, &device_alias, curve)
300                    .map_err(anyhow::Error::new)?;
301            display_add_result(&result.device_did, &repo_path)
302        }
303
304        DeviceSubcommand::Remove { device_did, key } => {
305            // Remove = revoke the device's KERI delegation: the root anchors a
306            // revocation marker so verifiers stop honouring the device. Single-
307            // author (the root's key signs); the device's key is not needed.
308            //
309            // Self-removal pre-flight (UX only — the SDK is the authoritative
310            // guard): reject removing the root identity itself; point the caller
311            // at `auths reset` to wipe their own state.
312            let ctx = build_auths_context(
313                &repo_path,
314                env_config,
315                Some(Arc::clone(&passphrase_provider)),
316            )?;
317            let identity = ctx.identity_storage.load_identity().map_err(|e| {
318                anyhow::anyhow!("failed to load identity for self-removal check: {e}")
319            })?;
320            if device_did == identity.controller_did.as_str() {
321                return Err(anyhow::anyhow!(
322                    "Cannot remove the root identity itself. \
323                     Use `auths reset` to delete this device's copy of the identity."
324                ));
325            }
326            let root_alias = KeyAlias::new_unchecked(key);
327            auths_sdk::domains::device::remove_device(&ctx, &root_alias, &device_did)
328                .map_err(anyhow::Error::new)?;
329            display_revoke_result(&device_did, &repo_path)
330        }
331
332        DeviceSubcommand::Revoke {
333            device_did,
334            key,
335            note,
336            dry_run,
337        } => {
338            if dry_run {
339                return display_dry_run_revoke(&device_did, &key);
340            }
341
342            let ctx = build_auths_context(
343                &repo_path,
344                env_config,
345                Some(Arc::clone(&passphrase_provider)),
346            )?;
347
348            let identity_key_alias = KeyAlias::new_unchecked(key);
349            auths_sdk::domains::device::service::revoke_device(
350                &device_did,
351                &identity_key_alias,
352                &ctx,
353                note,
354                &auths_sdk::ports::SystemClock,
355            )
356            .map_err(anyhow::Error::new)?;
357
358            display_revoke_result(&device_did, &repo_path)
359        }
360
361        DeviceSubcommand::Extend {
362            device_did,
363            expires_in,
364            key,
365            device_key,
366        } => handle_extend(
367            &repo_path,
368            &config,
369            &device_did,
370            expires_in,
371            &key,
372            &device_key,
373            passphrase_provider,
374            env_config,
375        ),
376    }
377}
378
379fn display_link_result(
380    result: &auths_sdk::result::DeviceLinkResult,
381    _device_did: &str,
382) -> Result<()> {
383    println!(
384        "\n✅ Device authorized. (Attestation: {})",
385        result.attestation_id
386    );
387    Ok(())
388}
389
390fn display_dry_run_revoke(device_did: &str, identity_key_alias: &str) -> Result<()> {
391    if is_json_mode() {
392        JsonResponse::success(
393            "device revoke",
394            &serde_json::json!({
395                "dry_run": true,
396                "device_did": device_did,
397                "identity_key_alias": identity_key_alias,
398                "actions": [
399                    "Revoke device authorization",
400                    "Create signed revocation attestation",
401                    "Store revocation in Git repository"
402                ]
403            }),
404        )
405        .print()
406        .map_err(anyhow::Error::from)
407    } else {
408        let out = crate::ux::format::Output::new();
409        out.print_info("Dry run mode — no changes will be made");
410        out.newline();
411        out.println("Would perform the following actions:");
412        out.println(&format!(
413            "  1. Revoke device authorization for {}",
414            device_did
415        ));
416        out.println("  2. Create signed revocation attestation");
417        out.println("  3. Store revocation in Git repository");
418        Ok(())
419    }
420}
421
422fn parse_curve(s: &str) -> Result<auths_crypto::CurveType> {
423    match s.to_ascii_lowercase().as_str() {
424        "p256" | "p-256" => Ok(auths_crypto::CurveType::P256),
425        "ed25519" => Ok(auths_crypto::CurveType::Ed25519),
426        other => Err(anyhow::anyhow!(
427            "unknown curve {:?}: expected p256 or ed25519",
428            other
429        )),
430    }
431}
432
433fn display_add_result(device_did: &str, repo_path: &Path) -> Result<()> {
434    let identity_storage = RegistryIdentityStorage::new(repo_path.to_path_buf());
435    let identity: ManagedIdentity = identity_storage
436        .load_identity()
437        .context("Failed to load identity")?;
438    println!(
439        "\n✅ Delegated device {} added to identity {}",
440        device_did, identity.controller_did
441    );
442    Ok(())
443}
444
445fn display_revoke_result(device_did: &str, repo_path: &Path) -> Result<()> {
446    let identity_storage = RegistryIdentityStorage::new(repo_path.to_path_buf());
447    let identity: ManagedIdentity = identity_storage
448        .load_identity()
449        .context("Failed to load identity")?;
450
451    println!(
452        "\n✅ Successfully revoked device {} for identity {}",
453        device_did, identity.controller_did
454    );
455    Ok(())
456}
457
458fn read_payload_file(path: Option<&Path>) -> Result<Option<Value>> {
459    match path {
460        Some(p) => {
461            let content = fs::read_to_string(p)
462                .with_context(|| format!("Failed to read payload file {:?}", p))?;
463            let value: Value = serde_json::from_str(&content)
464                .with_context(|| format!("Failed to parse JSON from payload file {:?}", p))?;
465            Ok(Some(value))
466        }
467        None => Ok(None),
468    }
469}
470
471fn validate_payload_schema(schema_path: Option<&Path>, payload: &Option<Value>) -> Result<()> {
472    match (schema_path, payload) {
473        (Some(schema_path), Some(payload_val)) => {
474            let schema_content = fs::read_to_string(schema_path)
475                .with_context(|| format!("Failed to read schema file {:?}", schema_path))?;
476            let schema_json: serde_json::Value = serde_json::from_str(&schema_content)
477                .with_context(|| format!("Failed to parse JSON schema from {:?}", schema_path))?;
478            let validator = jsonschema::validator_for(&schema_json)
479                .map_err(|e| anyhow!("Invalid JSON schema in {:?}: {}", schema_path, e))?;
480            let errors: Vec<String> = validator
481                .iter_errors(payload_val)
482                .map(|e| format!("  - {}", e))
483                .collect();
484            if !errors.is_empty() {
485                return Err(anyhow!(
486                    "Payload does not conform to schema:\n{}",
487                    errors.join("\n")
488                ));
489            }
490            Ok(())
491        }
492        (Some(_), None) => {
493            warn!("--schema specified but no --payload provided; skipping validation.");
494            Ok(())
495        }
496        _ => Ok(()),
497    }
498}
499
500#[allow(clippy::too_many_arguments)]
501fn handle_extend(
502    repo_path: &Path,
503    _config: &StorageLayoutConfig,
504    device_did: &str,
505    expires_in: u64,
506    key: &str,
507    device_key: &str,
508    passphrase_provider: Arc<dyn PassphraseProvider + Send + Sync>,
509    env_config: &EnvironmentConfig,
510) -> Result<()> {
511    let config = auths_sdk::types::DeviceExtensionConfig {
512        repo_path: repo_path.to_path_buf(),
513        #[allow(clippy::disallowed_methods)] // INVARIANT: device_did from CLI arg validated upstream
514        device_did: auths_verifier::types::CanonicalDid::new_unchecked(device_did),
515        expires_in,
516        identity_key_alias: KeyAlias::new_unchecked(key),
517        device_key_alias: Some(KeyAlias::new_unchecked(device_key)),
518    };
519    let ctx = build_auths_context(repo_path, env_config, Some(passphrase_provider))?;
520
521    let result = auths_sdk::domains::device::service::extend_device(
522        config,
523        &ctx,
524        &auths_sdk::ports::SystemClock,
525    )
526    .with_context(|| format!("Failed to extend device authorization for '{}'", device_did))?;
527
528    println!(
529        "Successfully extended expiration for {} to {}",
530        result.device_did,
531        result.new_expires_at.date_naive()
532    );
533    Ok(())
534}
535
536fn resolve_device(repo_path: &Path, device_did_str: &str) -> Result<()> {
537    let attestation_storage = RegistryAttestationStorage::new(repo_path.to_path_buf());
538    #[allow(clippy::disallowed_methods)] // INVARIANT: device_did_str from attestation storage
539    let device_did = auths_verifier::types::CanonicalDid::new_unchecked(device_did_str);
540    let attestations = attestation_storage
541        .load_attestations_for_device(&device_did)
542        .with_context(|| format!("Failed to load attestations for device {device_did_str}"))?;
543
544    let latest = attestations
545        .last()
546        .ok_or_else(|| anyhow!("No attestation found for device {device_did_str}"))?;
547
548    println!("{}", latest.issuer);
549    Ok(())
550}
551
552fn list_devices(
553    repo_path: &Path,
554    env_config: &EnvironmentConfig,
555    include_revoked: bool,
556) -> Result<()> {
557    let ctx = build_auths_context(repo_path, env_config, None)
558        .context("Failed to build auths context")?;
559
560    let identity = ctx
561        .identity_storage
562        .load_identity()
563        .with_context(|| format!("Failed to load identity from {:?}", repo_path))?;
564
565    // The delegation set is the source of truth: live = delegated − revoked. A
566    // delegated device is inherently anchored and carries no expiry.
567    let devices = auths_sdk::domains::device::list_delegated_devices(&ctx)
568        .map_err(anyhow::Error::from)
569        .context("Could not list delegated devices")?;
570
571    let mut entries: Vec<DeviceEntry> = Vec::new();
572    for device in devices {
573        if !include_revoked && device.revoked {
574            continue;
575        }
576        entries.push(DeviceEntry {
577            id: device.device_did,
578            status: if device.revoked {
579                "revoked".to_string()
580            } else {
581                "active".to_string()
582            },
583            anchored: true,
584        });
585    }
586
587    let duplicity_warning = root_duplicity_warning(&ctx, identity.controller_did.as_str());
588
589    if is_json_mode() {
590        return JsonResponse::success(
591            "device list",
592            &serde_json::json!({
593                "identity": identity.controller_did.to_string(),
594                "devices": entries,
595            }),
596        )
597        .print()
598        .map_err(anyhow::Error::from);
599    }
600
601    if let Some(warning) = &duplicity_warning {
602        println!("{warning}");
603        println!();
604    }
605
606    println!("Authorized devices for: {}", identity.controller_did);
607    if entries.is_empty() {
608        if include_revoked {
609            println!("  No delegated devices found.");
610        } else {
611            println!("  (No active devices. Use --include-revoked to see all.)");
612        }
613        return Ok(());
614    }
615    for (i, entry) in entries.iter().enumerate() {
616        println!("{:>2}. {}   {}", i + 1, entry.id, entry.status);
617    }
618    Ok(())
619}
620
621/// Run duplicity detection over the root KEL and return a non-fatal warning if the
622/// local registry has recorded a fork (concurrent rotations on different
623/// controllers). A linear KEL reports `Clean` and yields `None`.
624///
625/// Args:
626/// * `ctx`: Auths context (its registry holds the root KEL).
627/// * `controller_did`: The root identity's `did:keri:`.
628///
629/// Usage:
630/// ```ignore
631/// if let Some(w) = root_duplicity_warning(&ctx, &controller_did) { println!("{w}"); }
632/// ```
633fn root_duplicity_warning(
634    ctx: &auths_sdk::context::AuthsContext,
635    controller_did: &str,
636) -> Option<String> {
637    use auths_sdk::verify::{DuplicityReport, KelEventRef, detect_duplicity};
638
639    let prefix_str = controller_did.strip_prefix("did:keri:")?;
640    let prefix = auths_keri::Prefix::new_unchecked(prefix_str.to_string());
641    let tip = ctx.registry.get_tip(&prefix).ok()?;
642
643    let mut events = Vec::new();
644    for seq in 0..=tip.sequence {
645        events.push(ctx.registry.get_event(&prefix, seq).ok()?);
646    }
647    let refs: Vec<KelEventRef> = events
648        .iter()
649        .enumerate()
650        .map(|(seq, event)| KelEventRef {
651            prefix: controller_did,
652            seq: seq as u64,
653            said: event.said().as_str(),
654        })
655        .collect();
656
657    match detect_duplicity(&refs) {
658        DuplicityReport::Diverging { seq, .. } => {
659            Some(auths_sdk::keri::copy::format_duplicity_warning(seq))
660        }
661        _ => None,
662    }
663}