Skip to main content

auths_cli/commands/
status.rs

1//! Status overview command for Auths.
2
3use crate::ux::format::{JsonResponse, Output, is_json_mode};
4use anyhow::{Result, anyhow};
5use auths_id::storage::attestation::AttestationSource;
6use auths_id::storage::identity::IdentityStorage;
7use auths_id::storage::layout;
8use auths_storage::git::{RegistryAttestationStorage, RegistryIdentityStorage};
9use chrono::{DateTime, Duration, Utc};
10use clap::Parser;
11use serde::Serialize;
12use std::fs;
13use std::path::PathBuf;
14
15#[cfg(unix)]
16use nix::sys::signal;
17#[cfg(unix)]
18use nix::unistd::Pid;
19
20/// Show identity and agent status overview.
21#[derive(Parser, Debug, Clone)]
22#[command(name = "status", about = "Show identity and agent status overview")]
23pub struct StatusCommand {}
24
25/// Full status report.
26#[derive(Debug, Serialize)]
27pub struct StatusReport {
28    pub identity: Option<IdentityStatus>,
29    pub agent: AgentStatusInfo,
30    pub devices: DevicesSummary,
31}
32
33/// Identity status information.
34#[derive(Debug, Serialize)]
35pub struct IdentityStatus {
36    pub controller_did: String,
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub alias: Option<String>,
39}
40
41/// Agent status information.
42#[derive(Debug, Serialize)]
43pub struct AgentStatusInfo {
44    pub running: bool,
45    #[serde(skip_serializing_if = "Option::is_none")]
46    pub pid: Option<u32>,
47    #[serde(skip_serializing_if = "Option::is_none")]
48    pub socket_path: Option<String>,
49}
50
51/// Devices summary.
52#[derive(Debug, Serialize)]
53pub struct DevicesSummary {
54    pub linked: usize,
55    pub revoked: usize,
56    pub expiring_soon: Vec<ExpiringDevice>,
57    pub devices_detail: Vec<DeviceStatus>,
58}
59
60/// Per-device status for expiry display.
61#[derive(Debug, Serialize)]
62pub struct DeviceStatus {
63    pub device_did: String,
64    pub revoked_at: Option<chrono::DateTime<chrono::Utc>>,
65    pub expires_at: Option<DateTime<Utc>>,
66}
67
68/// Device that is expiring soon.
69#[derive(Debug, Serialize)]
70pub struct ExpiringDevice {
71    pub device_did: String,
72    pub expires_in_days: i64,
73}
74
75/// Handle the status command.
76pub fn handle_status(_cmd: StatusCommand, repo: Option<PathBuf>) -> Result<()> {
77    // Determine repository path
78    let repo_path = resolve_repo_path(repo)?;
79
80    // Load identity
81    let identity = load_identity_status(&repo_path);
82
83    // Get agent status
84    let agent = get_agent_status();
85
86    // Load device attestations summary
87    let devices = load_devices_summary(&repo_path);
88
89    let report = StatusReport {
90        identity,
91        agent,
92        devices,
93    };
94
95    if is_json_mode() {
96        JsonResponse::success("status", report).print()?;
97    } else {
98        print_status(&report);
99    }
100
101    Ok(())
102}
103
104/// Print status in human-readable format.
105fn print_status(report: &StatusReport) {
106    let out = Output::new();
107
108    // Identity
109    if let Some(ref id) = report.identity {
110        out.println(&format!("Identity:   {}", out.info(&id.controller_did)));
111        if let Some(ref alias) = id.alias {
112            out.println(&format!("Alias:      {}", alias));
113        }
114    } else {
115        out.println(&format!("Identity:   {}", out.dim("not initialized")));
116    }
117
118    // Agent
119    if report.agent.running {
120        let pid_str = report
121            .agent
122            .pid
123            .map(|p| format!("pid {}", p))
124            .unwrap_or_default();
125        let socket_str = report
126            .agent
127            .socket_path
128            .as_ref()
129            .map(|s| format!(", socket {}", s))
130            .unwrap_or_default();
131        out.println(&format!(
132            "Agent:      {} ({}{})",
133            out.success("running"),
134            pid_str,
135            socket_str
136        ));
137    } else {
138        out.println(&format!("Agent:      {}", out.warn("stopped")));
139    }
140
141    // Devices
142    let mut parts = Vec::new();
143    if report.devices.linked > 0 {
144        parts.push(format!("{} linked", report.devices.linked));
145    }
146    if report.devices.revoked > 0 {
147        parts.push(format!("{} revoked", report.devices.revoked));
148    }
149    if !report.devices.expiring_soon.is_empty() {
150        let expiring_count = report.devices.expiring_soon.len();
151        let min_days = report
152            .devices
153            .expiring_soon
154            .iter()
155            .map(|e| e.expires_in_days)
156            .min()
157            .unwrap_or(0);
158        if min_days == 0 {
159            parts.push(format!("{} expiring today", expiring_count));
160        } else if min_days == 1 {
161            parts.push(format!("{} expiring in 1 day", expiring_count));
162        } else {
163            parts.push(format!("{} expiring in {} days", expiring_count, min_days));
164        }
165    }
166
167    if parts.is_empty() {
168        out.println(&format!("Devices:    {}", out.dim("none")));
169    } else {
170        out.println(&format!("Devices:    {}", parts.join(", ")));
171    }
172
173    // Per-device expiry detail
174    if !report.devices.devices_detail.is_empty() {
175        out.newline();
176        let now = Utc::now();
177        for device in &report.devices.devices_detail {
178            if device.revoked_at.is_some() {
179                continue;
180            }
181            out.println(&format!("  {}", out.dim(&device.device_did)));
182            display_device_expiry(device.expires_at, &out, now);
183        }
184    }
185}
186
187/// Display color-coded device expiry information.
188fn display_device_expiry(expires_at: Option<DateTime<Utc>>, out: &Output, now: DateTime<Utc>) {
189    let Some(expires_at) = expires_at else {
190        out.println(&format!("  Expires: {}", out.info("never")));
191        return;
192    };
193
194    let remaining = expires_at - now;
195    let days = remaining.num_days();
196
197    let (label, color_fn): (&str, fn(&Output, &str) -> String) = match days {
198        d if d < 0 => ("EXPIRED", Output::error),
199        0..=6 => ("expiring soon", Output::warn),
200        7..=29 => ("expiring", Output::warn),
201        _ => ("active", Output::success),
202    };
203
204    let display = format!(
205        "{} ({}, {}d remaining)",
206        expires_at.format("%Y-%m-%d"),
207        label,
208        days
209    );
210    out.println(&format!("  Expires: {}", color_fn(out, &display)));
211
212    if (0..=7).contains(&days) {
213        out.print_warn("  Run `auths device extend` to renew.");
214    }
215}
216
217/// Load identity status from the repository.
218fn load_identity_status(repo_path: &PathBuf) -> Option<IdentityStatus> {
219    if crate::factories::storage::open_git_repo(repo_path).is_err() {
220        return None;
221    }
222
223    let storage = RegistryIdentityStorage::new(repo_path);
224    match storage.load_identity() {
225        Ok(identity) => Some(IdentityStatus {
226            controller_did: identity.controller_did.to_string(),
227            alias: None, // Would need to look up from keychain
228        }),
229        Err(_) => None,
230    }
231}
232
233/// Get agent status by checking PID file and socket.
234fn get_agent_status() -> AgentStatusInfo {
235    let auths_dir = match get_auths_dir() {
236        Ok(dir) => dir,
237        Err(_) => {
238            return AgentStatusInfo {
239                running: false,
240                pid: None,
241                socket_path: None,
242            };
243        }
244    };
245
246    let pid_path = auths_dir.join("agent.pid");
247    let socket_path = auths_dir.join("agent.sock");
248
249    // Read PID file
250    let pid = fs::read_to_string(&pid_path)
251        .ok()
252        .and_then(|content| content.trim().parse::<u32>().ok());
253
254    // Check if process is running
255    let running = pid.map(is_process_running).unwrap_or(false);
256    let socket_exists = socket_path.exists();
257
258    AgentStatusInfo {
259        running: running && socket_exists,
260        pid: if running { pid } else { None },
261        socket_path: if socket_exists && running {
262            Some(socket_path.to_string_lossy().to_string())
263        } else {
264            None
265        },
266    }
267}
268
269/// Load devices summary from attestations.
270fn load_devices_summary(repo_path: &PathBuf) -> DevicesSummary {
271    if crate::factories::storage::open_git_repo(repo_path).is_err() {
272        return DevicesSummary {
273            linked: 0,
274            revoked: 0,
275            expiring_soon: Vec::new(),
276            devices_detail: Vec::new(),
277        };
278    }
279
280    let storage = RegistryAttestationStorage::new(repo_path);
281    let attestations = match storage.load_all_attestations() {
282        Ok(a) => a,
283        Err(_) => {
284            return DevicesSummary {
285                linked: 0,
286                revoked: 0,
287                expiring_soon: Vec::new(),
288                devices_detail: Vec::new(),
289            };
290        }
291    };
292
293    // Group by device and get latest attestation per device
294    let mut latest_by_device: std::collections::HashMap<
295        String,
296        &auths_verifier::core::Attestation,
297    > = std::collections::HashMap::new();
298
299    for att in &attestations {
300        let key = att.subject.as_str().to_string();
301        latest_by_device
302            .entry(key)
303            .and_modify(|existing| {
304                // Keep the one with later timestamp
305                if att.timestamp > existing.timestamp {
306                    *existing = att;
307                }
308            })
309            .or_insert(att);
310    }
311
312    let now = Utc::now();
313    let threshold = now + Duration::days(7);
314    let mut linked = 0;
315    let mut revoked = 0;
316    let mut expiring_soon = Vec::new();
317    let mut devices_detail = Vec::new();
318
319    for (device_did, att) in &latest_by_device {
320        devices_detail.push(DeviceStatus {
321            device_did: device_did.clone(),
322            revoked_at: att.revoked_at,
323            expires_at: att.expires_at,
324        });
325
326        if att.is_revoked() {
327            revoked += 1;
328        } else {
329            linked += 1;
330            // Check if expiring soon
331            if let Some(expires_at) = att.expires_at
332                && expires_at <= threshold
333                && expires_at > now
334            {
335                let days_left = (expires_at - now).num_days();
336                expiring_soon.push(ExpiringDevice {
337                    device_did: device_did.clone(),
338                    expires_in_days: days_left,
339                });
340            }
341        }
342    }
343
344    // Sort expiring devices by days remaining
345    expiring_soon.sort_by_key(|e| e.expires_in_days);
346
347    DevicesSummary {
348        linked,
349        revoked,
350        expiring_soon,
351        devices_detail,
352    }
353}
354
355/// Get the auths directory path (~/.auths), respecting AUTHS_HOME.
356fn get_auths_dir() -> Result<PathBuf> {
357    auths_core::paths::auths_home().map_err(|e| anyhow!(e))
358}
359
360/// Resolve the repository path from optional argument or default (~/.auths).
361fn resolve_repo_path(repo_arg: Option<PathBuf>) -> Result<PathBuf> {
362    layout::resolve_repo_path(repo_arg).map_err(|e| anyhow!(e))
363}
364
365/// Check if a process with the given PID is running.
366#[cfg(unix)]
367fn is_process_running(pid: u32) -> bool {
368    signal::kill(Pid::from_raw(pid as i32), None).is_ok()
369}
370
371#[cfg(not(unix))]
372fn is_process_running(_pid: u32) -> bool {
373    false
374}
375
376impl crate::commands::executable::ExecutableCommand for StatusCommand {
377    fn execute(&self, ctx: &crate::config::CliConfig) -> anyhow::Result<()> {
378        handle_status(self.clone(), ctx.repo_path.clone())
379    }
380}
381
382#[cfg(test)]
383mod tests {
384    use super::*;
385
386    #[test]
387    fn test_get_auths_dir() {
388        let dir = get_auths_dir().unwrap();
389        assert!(dir.ends_with(".auths"));
390    }
391}