Skip to main content

tryaudex_core/
audit.rs

1use std::path::PathBuf;
2
3use chrono::{DateTime, Utc};
4use serde::{Deserialize, Serialize};
5
6use crate::error::Result;
7use crate::session::{CloudProvider, Session};
8
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct AuditEntry {
11    pub timestamp: DateTime<Utc>,
12    pub session_id: String,
13    /// Cloud provider for this entry (defaults to "aws" for backwards compat).
14    #[serde(default = "default_provider")]
15    pub provider: String,
16    pub event: AuditEvent,
17}
18
19fn default_provider() -> String {
20    "aws".to_string()
21}
22
23#[derive(Debug, Clone, Serialize, Deserialize)]
24#[serde(tag = "type", rename_all = "snake_case")]
25pub enum AuditEvent {
26    SessionCreated {
27        /// "Role ARN" for AWS, "Service Account" for GCP, "Subscription" for Azure
28        role_arn: String,
29        ttl_seconds: u64,
30        budget: Option<f64>,
31        allowed_actions: Vec<String>,
32        command: Vec<String>,
33        /// AI agent/model identity (from AUDEX_AGENT_ID env var).
34        #[serde(default, skip_serializing_if = "Option::is_none")]
35        agent_id: Option<String>,
36    },
37    CredentialsIssued {
38        access_key_id: String,
39        expires_at: DateTime<Utc>,
40    },
41    SessionEnded {
42        status: String,
43        duration_seconds: i64,
44        exit_code: Option<i32>,
45    },
46    BudgetWarning {
47        current_spend: f64,
48        limit: f64,
49    },
50    BudgetExceeded {
51        final_spend: f64,
52        limit: f64,
53    },
54}
55
56/// Append-only audit logger that writes to a local JSONL file.
57pub struct AuditLog {
58    path: PathBuf,
59}
60
61impl AuditLog {
62    pub fn new() -> Result<Self> {
63        let dir = dirs::data_local_dir()
64            .unwrap_or_else(|| PathBuf::from("."))
65            .join("audex")
66            .join("audit");
67        std::fs::create_dir_all(&dir)?;
68        let path = dir.join("audit.jsonl");
69        Ok(Self { path })
70    }
71
72    /// Construct an AuditLog at a caller-provided path. Used by tests so they
73    /// don't pollute the real audit log at `~/.local/share/audex/audit/audit.jsonl`.
74    pub fn with_path(path: PathBuf) -> Result<Self> {
75        if let Some(parent) = path.parent() {
76            std::fs::create_dir_all(parent)?;
77        }
78        Ok(Self { path })
79    }
80
81    pub fn log(&self, session_id: &str, event: AuditEvent) -> Result<()> {
82        self.log_with_provider(session_id, "aws", event)
83    }
84
85    pub fn log_with_provider(
86        &self,
87        session_id: &str,
88        provider: &str,
89        event: AuditEvent,
90    ) -> Result<()> {
91        let entry = AuditEntry {
92            timestamp: Utc::now(),
93            session_id: session_id.to_string(),
94            provider: provider.to_string(),
95            event,
96        };
97        let json_line = serde_json::to_string(&entry)?;
98
99        // Redact any credential material before persisting
100        let json_line = crate::leakdetect::redact_secrets(&json_line);
101
102        // Take an exclusive OS-level lock on the audit log for the entire
103        // read-hash-then-append sequence. Without this, concurrent writers
104        // (threads OR separate tryaudex processes) would each read the same
105        // `previous_hash`, compute HMACs against it, and append — breaking
106        // the chain for every line after the first one to hit disk.
107        use fs4::fs_std::FileExt;
108        use std::io::Write;
109        let mut file = std::fs::OpenOptions::new()
110            .create(true)
111            .append(true)
112            .read(true)
113            .open(&self.path)?;
114        file.lock_exclusive()?;
115
116        // Sign with chain HMAC for tamper detection — now inside the lock.
117        let previous_hash = crate::integrity::last_chain_hash(&self.path);
118        let signed_line = crate::integrity::sign_line(&json_line, &previous_hash);
119
120        let mut output = signed_line;
121        output.push('\n');
122
123        let write_result = file.write_all(output.as_bytes());
124        // Always release the lock, even if the write failed.
125        let _ = FileExt::unlock(&file);
126        write_result?;
127
128        Ok(())
129    }
130
131    pub fn log_session_created(&self, session: &Session) -> Result<()> {
132        let allowed_actions: Vec<String> = match session.provider {
133            CloudProvider::Gcp => session
134                .policy
135                .actions
136                .iter()
137                .map(|a| a.to_gcp_permission())
138                .collect(),
139            CloudProvider::Azure => session
140                .policy
141                .actions
142                .iter()
143                .map(|a| a.to_azure_permission())
144                .collect(),
145            CloudProvider::Aws => session
146                .policy
147                .actions
148                .iter()
149                .map(|a| a.to_iam_action())
150                .collect(),
151        };
152
153        self.log_with_provider(
154            &session.id,
155            &session.provider.to_string(),
156            AuditEvent::SessionCreated {
157                role_arn: session.role_arn.clone(),
158                ttl_seconds: session.ttl_seconds,
159                budget: session.budget,
160                allowed_actions,
161                command: session.command.clone(),
162                agent_id: session.agent_id.clone(),
163            },
164        )
165    }
166
167    pub fn log_session_ended(&self, session: &Session, exit_code: Option<i32>) -> Result<()> {
168        let duration = (Utc::now() - session.created_at).num_seconds();
169        self.log_with_provider(
170            &session.id,
171            &session.provider.to_string(),
172            AuditEvent::SessionEnded {
173                status: session.status.to_string(),
174                duration_seconds: duration,
175                exit_code,
176            },
177        )
178    }
179
180    /// Read all audit entries, optionally filtered by session ID.
181    pub fn read(&self, session_id: Option<&str>) -> Result<Vec<AuditEntry>> {
182        self.read_filtered(session_id, None)
183    }
184
185    /// Read audit entries with optional session ID and provider filters.
186    pub fn read_filtered(
187        &self,
188        session_id: Option<&str>,
189        provider: Option<&str>,
190    ) -> Result<Vec<AuditEntry>> {
191        if !self.path.exists() {
192            return Ok(Vec::new());
193        }
194        let content = std::fs::read_to_string(&self.path)?;
195        let entries: Vec<AuditEntry> = content
196            .lines()
197            .filter(|l| !l.trim().is_empty())
198            .filter_map(|l| {
199                // Strip HMAC signature if present before parsing JSON
200                let (json_content, _) = crate::integrity::parse_line(l);
201                serde_json::from_str(json_content).ok()
202            })
203            .filter(|e: &AuditEntry| session_id.is_none_or(|id| e.session_id == id))
204            .filter(|e: &AuditEntry| provider.is_none_or(|p| e.provider == p))
205            .collect();
206        Ok(entries)
207    }
208
209    /// Verify the integrity of the audit log using chain HMACs.
210    pub fn verify(&self) -> Result<crate::integrity::VerificationResult> {
211        crate::integrity::verify_audit_log(&self.path)
212    }
213
214    pub fn path(&self) -> &PathBuf {
215        &self.path
216    }
217}