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; 20] = [
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::ApprovalEscalated,
60    EventKind::LogLine,
61    EventKind::UserSignedIn,
62    EventKind::UserSignedUp,
63    EventKind::UserSignedOut,
64    EventKind::ProviderAccountUpdated,
65    EventKind::SignalAwaited,
66    EventKind::SignalReceived,
67    EventKind::ScheduleOccurrencesMissed,
68    EventKind::WorkflowPaused,
69    EventKind::WorkflowResumed,
70];
71
72/// Parse a `--type` value, listing the accepted values on failure.
73///
74/// # Errors
75///
76/// Returns the list of accepted event kinds when `raw` is not one of them.
77fn parse_event_kind(raw: &str) -> Result<EventKind, String> {
78    parse_enum(raw, &ALL_EVENT_KINDS, "event type")
79}
80
81/// Execute an audit log subcommand.
82///
83/// # Errors
84///
85/// Returns an error on API failure, including 403 for non-admin callers.
86pub async fn execute(client: &IronflowClient, args: &AuditLogArgs, json_mode: bool) -> Result<()> {
87    match &args.command {
88        AuditLogCommands::List {
89            run,
90            event_type,
91            from,
92            to,
93            page,
94            per_page,
95        } => {
96            let event_type = event_type.as_ref().map(ToString::to_string);
97            let filter = ListAuditLogsFilter {
98                run_id: *run,
99                event_type: event_type.as_deref(),
100                from: *from,
101                to: *to,
102                page: *page,
103                per_page: *per_page,
104            };
105
106            let response = client.list_audit_logs_filtered(&filter).await?;
107            output::print_output(json_mode, &response, || {
108                output::audit_logs_table(&response.data)
109            })?;
110        }
111    }
112    Ok(())
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118
119    #[test]
120    fn parse_event_kind_accepts_every_declared_kind() {
121        for kind in ALL_EVENT_KINDS {
122            let raw = kind.to_string();
123            assert_eq!(parse_event_kind(&raw).unwrap(), kind);
124        }
125    }
126
127    #[test]
128    fn parse_event_kind_rejects_an_unknown_value_and_lists_the_valid_ones() {
129        let err = parse_event_kind("run_exploded").unwrap_err();
130        assert!(err.contains("unknown event type 'run_exploded'"), "{err}");
131        assert!(err.contains("run_created"), "{err}");
132    }
133}