tryaudex_core/
credentials.rs1use 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#[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 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
30pub 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 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 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 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 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 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 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
158pub 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 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 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 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}