Skip to main content

ironflow_cli/commands/
audit_log.rs

1//! Audit log subcommands: list.
2
3use anyhow::Result;
4use chrono::{DateTime, Utc};
5use clap::{Args, Subcommand};
6use ironflow_sdk::IronflowClient;
7use ironflow_sdk::client::ListAuditLogsFilter;
8use ironflow_sdk::types::EventKind;
9use uuid::Uuid;
10
11use crate::commands::parse_enum;
12use crate::output;
13
14/// Arguments for the `audit-log` command group.
15#[derive(Debug, Args)]
16pub struct AuditLogArgs {
17    /// Audit log subcommand.
18    #[command(subcommand)]
19    pub command: AuditLogCommands,
20}
21
22/// Available audit log subcommands.
23#[derive(Debug, Subcommand)]
24pub enum AuditLogCommands {
25    /// List audit log entries with optional filters.
26    List {
27        /// Only entries attached to this run.
28        #[arg(long = "run", value_name = "UUID")]
29        run: Option<Uuid>,
30        /// Only entries of this event type (e.g. `run_created`).
31        #[arg(long = "type", value_name = "KIND", value_parser = parse_event_kind)]
32        event_type: Option<EventKind>,
33        /// Only entries recorded at or after this instant (RFC 3339).
34        #[arg(long)]
35        from: Option<DateTime<Utc>>,
36        /// Only entries recorded at or before this instant (RFC 3339).
37        #[arg(long)]
38        to: Option<DateTime<Utc>>,
39        /// Page number (1-based).
40        #[arg(long)]
41        page: Option<u32>,
42        /// Items per page.
43        #[arg(long)]
44        per_page: Option<u32>,
45    },
46}
47
48/// Every event kind the API records, in the order the enum declares them.
49const ALL_EVENT_KINDS: [EventKind; 13] = [
50    EventKind::RunCreated,
51    EventKind::RunStatusChanged,
52    EventKind::RunFailed,
53    EventKind::RunBudgetExceeded,
54    EventKind::StepCompleted,
55    EventKind::StepFailed,
56    EventKind::ApprovalRequested,
57    EventKind::ApprovalGranted,
58    EventKind::ApprovalRejected,
59    EventKind::LogLine,
60    EventKind::UserSignedIn,
61    EventKind::UserSignedUp,
62    EventKind::UserSignedOut,
63];
64
65/// Parse a `--type` value, listing the accepted values on failure.
66///
67/// # Errors
68///
69/// Returns the list of accepted event kinds when `raw` is not one of them.
70fn parse_event_kind(raw: &str) -> Result<EventKind, String> {
71    parse_enum(raw, &ALL_EVENT_KINDS, "event type")
72}
73
74/// Execute an audit log subcommand.
75///
76/// # Errors
77///
78/// Returns an error on API failure, including 403 for non-admin callers.
79pub async fn execute(client: &IronflowClient, args: &AuditLogArgs, json_mode: bool) -> Result<()> {
80    match &args.command {
81        AuditLogCommands::List {
82            run,
83            event_type,
84            from,
85            to,
86            page,
87            per_page,
88        } => {
89            let event_type = event_type.as_ref().map(ToString::to_string);
90            let filter = ListAuditLogsFilter {
91                run_id: *run,
92                event_type: event_type.as_deref(),
93                from: *from,
94                to: *to,
95                page: *page,
96                per_page: *per_page,
97            };
98
99            let response = client.list_audit_logs_filtered(&filter).await?;
100            output::print_output(json_mode, &response, || {
101                output::audit_logs_table(&response.data)
102            })?;
103        }
104    }
105    Ok(())
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111
112    #[test]
113    fn parse_event_kind_accepts_every_declared_kind() {
114        for kind in ALL_EVENT_KINDS {
115            let raw = kind.to_string();
116            assert_eq!(parse_event_kind(&raw).unwrap(), kind);
117        }
118    }
119
120    #[test]
121    fn parse_event_kind_rejects_an_unknown_value_and_lists_the_valid_ones() {
122        let err = parse_event_kind("run_exploded").unwrap_err();
123        assert!(err.contains("unknown event type 'run_exploded'"), "{err}");
124        assert!(err.contains("run_created"), "{err}");
125    }
126}