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).await
71    }
72
73    /// Assume a role with inline policy, optional boundary, and optional network conditions.
74    pub async fn issue_full(
75        &self,
76        session: &Session,
77        policy: &ScopedPolicy,
78        ttl: Duration,
79        permissions_boundary: Option<&str>,
80        network: Option<&crate::policy::NetworkPolicy>,
81    ) -> Result<TempCredentials> {
82        let policy_json = policy.to_iam_policy_json_with_network(network)?;
83        let ttl_secs = ttl.as_secs().min(43200) as i32; // STS max is 12 hours
84
85        tracing::info!(
86            session_id = %session.id,
87            role_arn = %session.role_arn,
88            ttl_secs = ttl_secs,
89            permissions_boundary = ?permissions_boundary,
90            "Assuming role with scoped policy"
91        );
92
93        let mut request = self
94            .sts_client
95            .assume_role()
96            .role_arn(&session.role_arn)
97            .role_session_name(format!("av-{}", &session.id[..8]))
98            .policy(&policy_json)
99            .duration_seconds(ttl_secs);
100
101        // Attach permissions boundary as a managed policy ARN ceiling
102        if let Some(boundary_arn) = permissions_boundary {
103            request = request.policy_arns(
104                aws_sdk_sts::types::PolicyDescriptorType::builder()
105                    .arn(boundary_arn)
106                    .build(),
107            );
108        }
109
110        let result = request
111            .send()
112            .await
113            .map_err(|e| AvError::Sts(e.to_string()))?;
114
115        let creds = result
116            .credentials()
117            .ok_or_else(|| AvError::Sts("No credentials returned by STS".to_string()))?;
118
119        let exp = creds.expiration();
120        let expires_at =
121            chrono::DateTime::from_timestamp(exp.secs(), exp.subsec_nanos())
122                .unwrap_or_else(chrono::Utc::now);
123
124        Ok(TempCredentials {
125            access_key_id: creds.access_key_id().to_string(),
126            secret_access_key: creds.secret_access_key().to_string(),
127            session_token: creds.session_token().to_string(),
128            expires_at,
129        })
130    }
131}
132
133/// Caches credentials on disk, keyed by session ID.
134pub struct CredentialCache {
135    dir: PathBuf,
136}
137
138impl CredentialCache {
139    pub fn new() -> Result<Self> {
140        let dir = dirs::data_local_dir()
141            .unwrap_or_else(|| PathBuf::from("."))
142            .join("audex")
143            .join("cred_cache");
144        std::fs::create_dir_all(&dir)?;
145        Ok(Self { dir })
146    }
147
148    /// Save credentials for a session (encrypted at rest).
149    pub fn save(&self, session_id: &str, creds: &TempCredentials) -> Result<()> {
150        let path = self.dir.join(format!("{}.json", session_id));
151        crate::keystore::encrypt_to_file(&path, creds)
152    }
153
154    /// Load cached credentials for a session. Returns None if expired or missing.
155    /// Handles both encrypted and legacy plaintext files for migration.
156    pub fn load(&self, session_id: &str) -> Result<Option<TempCredentials>> {
157        let path = self.dir.join(format!("{}.json", session_id));
158        let creds: Option<TempCredentials> = crate::keystore::decrypt_from_file(&path)?;
159        match creds {
160            Some(c) if c.expires_at <= chrono::Utc::now() => {
161                let _ = std::fs::remove_file(&path);
162                Ok(None)
163            }
164            other => Ok(other),
165        }
166    }
167
168    /// Remove cached credentials for a session.
169    pub fn remove(&self, session_id: &str) {
170        let path = self.dir.join(format!("{}.json", session_id));
171        let _ = std::fs::remove_file(path);
172    }
173}