Skip to main content

tryaudex_core/
credentials.rs

1use std::path::PathBuf;
2use std::time::Duration;
3
4use serde::{Deserialize, Serialize};
5
6use crate::error::{AvError, Result};
7use crate::policy::ScopedPolicy;
8use crate::session::Session;
9
10/// Temporary AWS credentials returned by STS.
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct TempCredentials {
13    pub access_key_id: String,
14    pub secret_access_key: String,
15    pub session_token: String,
16    pub expires_at: chrono::DateTime<chrono::Utc>,
17}
18
19impl TempCredentials {
20    /// Returns env vars to inject into the subprocess.
21    pub fn as_env_vars(&self) -> Vec<(&str, &str)> {
22        vec![
23            ("AWS_ACCESS_KEY_ID", &self.access_key_id),
24            ("AWS_SECRET_ACCESS_KEY", &self.secret_access_key),
25            ("AWS_SESSION_TOKEN", &self.session_token),
26        ]
27    }
28}
29
30/// Issues scoped, short-lived AWS credentials via STS AssumeRole.
31pub struct CredentialIssuer {
32    sts_client: aws_sdk_sts::Client,
33}
34
35impl CredentialIssuer {
36    pub async fn new() -> Result<Self> {
37        Self::with_region(None).await
38    }
39
40    pub async fn with_region(region: Option<&str>) -> Result<Self> {
41        let mut loader = aws_config::defaults(aws_config::BehaviorVersion::latest());
42        if let Some(region) = region {
43            loader = loader.region(aws_config::Region::new(region.to_string()));
44        }
45        let config = loader.load().await;
46        Ok(Self {
47            sts_client: aws_sdk_sts::Client::new(&config),
48        })
49    }
50
51    /// Assume a role with an inline policy that restricts permissions to the scoped policy.
52    /// Optionally attaches a permissions boundary ARN as an additional ceiling.
53    pub async fn issue(
54        &self,
55        session: &Session,
56        policy: &ScopedPolicy,
57        ttl: Duration,
58    ) -> Result<TempCredentials> {
59        self.issue_with_boundary(session, policy, ttl, None).await
60    }
61
62    /// Assume a role with an inline policy and optional permissions boundary.
63    pub async fn issue_with_boundary(
64        &self,
65        session: &Session,
66        policy: &ScopedPolicy,
67        ttl: Duration,
68        permissions_boundary: Option<&str>,
69    ) -> Result<TempCredentials> {
70        self.issue_full(session, policy, ttl, permissions_boundary, None)
71            .await
72    }
73
74    /// Assume a role with inline policy, optional boundary, and optional network conditions.
75    pub async fn issue_full(
76        &self,
77        session: &Session,
78        policy: &ScopedPolicy,
79        ttl: Duration,
80        permissions_boundary: Option<&str>,
81        network: Option<&crate::policy::NetworkPolicy>,
82    ) -> Result<TempCredentials> {
83        let policy_json = policy.to_iam_policy_json_with_network(network)?;
84        // AWS STS AssumeRole requires 900s <= DurationSeconds <= 43200s (15 minutes to 12 hours).
85        // Clamp at both ends rather than letting STS reject the call with a cryptic message.
86        let requested = ttl.as_secs();
87        let ttl_secs = requested.clamp(900, 43200) as i32;
88        if requested < 900 {
89            tracing::warn!(
90                requested_secs = requested,
91                clamped_to_secs = ttl_secs,
92                "TTL below AWS STS minimum (900s / 15m); clamping up"
93            );
94        } else if requested > 43200 {
95            tracing::warn!(
96                requested_secs = requested,
97                clamped_to_secs = ttl_secs,
98                "TTL above AWS STS maximum (43200s / 12h); clamping down"
99            );
100        }
101
102        tracing::info!(
103            session_id = %session.id,
104            role_arn = %session.role_arn,
105            ttl_secs = ttl_secs,
106            permissions_boundary = ?permissions_boundary,
107            "Assuming role with scoped policy"
108        );
109
110        let mut request = self
111            .sts_client
112            .assume_role()
113            .role_arn(&session.role_arn)
114            .role_session_name(format!("av-{}", &session.id[..8]))
115            .policy(&policy_json)
116            .duration_seconds(ttl_secs);
117
118        // Attach permissions boundary as a managed policy ARN ceiling
119        if let Some(boundary_arn) = permissions_boundary {
120            request = request.policy_arns(
121                aws_sdk_sts::types::PolicyDescriptorType::builder()
122                    .arn(boundary_arn)
123                    .build(),
124            );
125        }
126
127        let result = request.send().await.map_err(|e| {
128            // AWS SDK's Display impl collapses ServiceError variants to "service error".
129            // Extract the actual error code + message so the user can act on it.
130            let detail = match e.as_service_error() {
131                Some(svc) => {
132                    let code = svc.meta().code().unwrap_or("Unknown");
133                    let message = svc.meta().message().unwrap_or("(no message)");
134                    format!("{code}: {message}")
135                }
136                None => e.to_string(),
137            };
138            AvError::Sts(detail)
139        })?;
140
141        let creds = result
142            .credentials()
143            .ok_or_else(|| AvError::Sts("No credentials returned by STS".to_string()))?;
144
145        let exp = creds.expiration();
146        let expires_at = chrono::DateTime::from_timestamp(exp.secs(), exp.subsec_nanos())
147            .unwrap_or_else(chrono::Utc::now);
148
149        Ok(TempCredentials {
150            access_key_id: creds.access_key_id().to_string(),
151            secret_access_key: creds.secret_access_key().to_string(),
152            session_token: creds.session_token().to_string(),
153            expires_at,
154        })
155    }
156}
157
158/// Caches credentials on disk, keyed by session ID.
159pub struct CredentialCache {
160    dir: PathBuf,
161}
162
163impl CredentialCache {
164    pub fn new() -> Result<Self> {
165        let dir = dirs::data_local_dir()
166            .unwrap_or_else(|| PathBuf::from("."))
167            .join("audex")
168            .join("cred_cache");
169        std::fs::create_dir_all(&dir)?;
170        Ok(Self { dir })
171    }
172
173    /// Save credentials for a session (encrypted at rest).
174    pub fn save(&self, session_id: &str, creds: &TempCredentials) -> Result<()> {
175        let path = self.dir.join(format!("{}.json", session_id));
176        crate::keystore::encrypt_to_file(&path, creds)
177    }
178
179    /// Load cached credentials for a session. Returns None if expired or missing.
180    /// Handles both encrypted and legacy plaintext files for migration.
181    pub fn load(&self, session_id: &str) -> Result<Option<TempCredentials>> {
182        let path = self.dir.join(format!("{}.json", session_id));
183        let creds: Option<TempCredentials> = crate::keystore::decrypt_from_file(&path)?;
184        match creds {
185            Some(c) if c.expires_at <= chrono::Utc::now() => {
186                let _ = std::fs::remove_file(&path);
187                Ok(None)
188            }
189            other => Ok(other),
190        }
191    }
192
193    /// Remove cached credentials for a session.
194    pub fn remove(&self, session_id: &str) {
195        let path = self.dir.join(format!("{}.json", session_id));
196        let _ = std::fs::remove_file(path);
197    }
198}