Skip to main content

vantage_aws/
account.rs

1//! `AwsAccount` — account-wide credentials handle.
2//!
3//! Holds the access key, secret key, and region. Cheap to clone (everything
4//! lives behind an `Arc`). Used directly as the `TableSource` for JSON-1.1
5//! tables — see `crate::json1` for the protocol impl. The per-operation
6//! configuration (service, operation target, response array key) lives in
7//! the table name, formatted as `array_key:service/target`.
8
9use std::collections::HashMap;
10use std::path::PathBuf;
11use std::sync::Arc;
12
13use vantage_core::Result;
14use vantage_core::error;
15
16#[derive(Clone)]
17pub struct AwsAccount {
18    inner: Arc<Inner>,
19}
20
21struct Inner {
22    access_key: String,
23    secret_key: String,
24    session_token: Option<String>,
25    region: String,
26    http: reqwest::Client,
27}
28
29impl AwsAccount {
30    /// Construct from explicit static credentials.
31    pub fn new(
32        access_key: impl Into<String>,
33        secret_key: impl Into<String>,
34        region: impl Into<String>,
35    ) -> Self {
36        Self {
37            inner: Arc::new(Inner {
38                access_key: access_key.into(),
39                secret_key: secret_key.into(),
40                session_token: None,
41                region: region.into(),
42                http: reqwest::Client::new(),
43            }),
44        }
45    }
46
47    /// Read `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and
48    /// `AWS_REGION` from the environment. Picks up `AWS_SESSION_TOKEN`
49    /// for temporary credentials if present.
50    pub fn from_env() -> Result<Self> {
51        let access_key =
52            std::env::var("AWS_ACCESS_KEY_ID").map_err(|_| error!("AWS_ACCESS_KEY_ID not set"))?;
53        let secret_key = std::env::var("AWS_SECRET_ACCESS_KEY")
54            .map_err(|_| error!("AWS_SECRET_ACCESS_KEY not set"))?;
55        let region = std::env::var("AWS_REGION").map_err(|_| error!("AWS_REGION not set"))?;
56        let session_token = std::env::var("AWS_SESSION_TOKEN").ok();
57
58        Ok(Self {
59            inner: Arc::new(Inner {
60                access_key,
61                secret_key,
62                session_token,
63                region,
64                http: reqwest::Client::new(),
65            }),
66        })
67    }
68
69    /// Read the `[default]` profile from `~/.aws/credentials`. Other
70    /// profiles, `AWS_PROFILE`, SSO, and assume-role aren't supported
71    /// in v0.
72    ///
73    /// Region resolution falls through `AWS_REGION` →
74    /// `AWS_DEFAULT_REGION` → `~/.aws/config` `[default]` `region`.
75    pub fn from_credentials_file() -> Result<Self> {
76        let home_dir = home_dir().ok_or_else(|| error!("HOME not set"))?;
77        let creds_path = home_dir.join(".aws/credentials");
78        let creds_text = std::fs::read_to_string(&creds_path)
79            .map_err(|e| error!(format!("failed to read {}: {}", creds_path.display(), e)))?;
80        let creds = parse_default_profile(&creds_text)
81            .ok_or_else(|| error!(format!("no [default] profile in {}", creds_path.display())))?;
82
83        let access_key = creds
84            .get("aws_access_key_id")
85            .ok_or_else(|| {
86                error!(format!(
87                    "aws_access_key_id missing in {} [default]",
88                    creds_path.display()
89                ))
90            })?
91            .clone();
92        let secret_key = creds
93            .get("aws_secret_access_key")
94            .ok_or_else(|| {
95                error!(format!(
96                    "aws_secret_access_key missing in {} [default]",
97                    creds_path.display()
98                ))
99            })?
100            .clone();
101        let session_token = creds.get("aws_session_token").cloned();
102
103        let region = std::env::var("AWS_REGION")
104            .ok()
105            .or_else(|| std::env::var("AWS_DEFAULT_REGION").ok())
106            .or_else(|| {
107                let config_path = home_dir.join(".aws/config");
108                let text = std::fs::read_to_string(&config_path).ok()?;
109                parse_default_profile(&text)?.get("region").cloned()
110            })
111            .ok_or_else(|| {
112                error!(
113                    "AWS region not found (set AWS_REGION or add region to ~/.aws/config [default])"
114                )
115            })?;
116
117        Ok(Self {
118            inner: Arc::new(Inner {
119                access_key,
120                secret_key,
121                session_token,
122                region,
123                http: reqwest::Client::new(),
124            }),
125        })
126    }
127
128    /// Try [`from_env`](Self::from_env), fall back to
129    /// [`from_credentials_file`](Self::from_credentials_file). Use
130    /// this when you don't care which one — typical CLI / dev setup.
131    pub fn from_default() -> Result<Self> {
132        match Self::from_env() {
133            Ok(acc) => Ok(acc),
134            Err(_) => Self::from_credentials_file(),
135        }
136    }
137
138    pub(crate) fn region(&self) -> &str {
139        &self.inner.region
140    }
141
142    pub(crate) fn access_key(&self) -> &str {
143        &self.inner.access_key
144    }
145
146    pub(crate) fn secret_key(&self) -> &str {
147        &self.inner.secret_key
148    }
149
150    pub(crate) fn session_token(&self) -> Option<&str> {
151        self.inner.session_token.as_deref()
152    }
153
154    pub(crate) fn http(&self) -> &reqwest::Client {
155        &self.inner.http
156    }
157}
158
159impl std::fmt::Debug for AwsAccount {
160    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161        f.debug_struct("AwsAccount")
162            .field("region", &self.inner.region)
163            .field("access_key", &"<redacted>")
164            .field("secret_key", &"<redacted>")
165            .field(
166                "session_token",
167                &self.inner.session_token.as_ref().map(|_| "<redacted>"),
168            )
169            .finish()
170    }
171}
172
173fn home_dir() -> Option<PathBuf> {
174    std::env::var_os("HOME").map(PathBuf::from)
175}
176
177/// Pull the `[default]` section from an AWS-style INI file. Returns
178/// `None` if no `[default]` section was seen. `~/.aws/config` happens
179/// to use `[default]` (not `[profile default]`) for the default
180/// profile, so the same parser handles both files.
181fn parse_default_profile(content: &str) -> Option<HashMap<String, String>> {
182    let mut in_default = false;
183    let mut found_default = false;
184    let mut map = HashMap::new();
185
186    for raw in content.lines() {
187        let line = raw.trim();
188        if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
189            continue;
190        }
191        if let Some(section) = line.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
192            in_default = section.trim() == "default";
193            if in_default {
194                found_default = true;
195            }
196            continue;
197        }
198        if in_default && let Some((k, v)) = line.split_once('=') {
199            map.insert(k.trim().to_string(), v.trim().to_string());
200        }
201    }
202
203    found_default.then_some(map)
204}
205
206#[cfg(test)]
207mod tests {
208    use super::parse_default_profile;
209
210    #[test]
211    fn picks_default_section_only() {
212        let ini = "\
213[other]
214aws_access_key_id = NOPE
215aws_secret_access_key = NOPE
216
217[default]
218aws_access_key_id = AKIA_DEFAULT
219aws_secret_access_key = secret_default
220aws_session_token = token_default
221
222[another]
223aws_access_key_id = ALSO_NOPE
224";
225        let p = parse_default_profile(ini).expect("default section");
226        assert_eq!(p.get("aws_access_key_id").unwrap(), "AKIA_DEFAULT");
227        assert_eq!(p.get("aws_secret_access_key").unwrap(), "secret_default");
228        assert_eq!(p.get("aws_session_token").unwrap(), "token_default");
229    }
230
231    #[test]
232    fn no_default_returns_none() {
233        let ini = "[work]\naws_access_key_id = X\n";
234        assert!(parse_default_profile(ini).is_none());
235    }
236
237    #[test]
238    fn ignores_comments_and_blank_lines() {
239        let ini = "\
240# top comment
241; also a comment
242
243[default]
244# inline comment line
245aws_access_key_id = AK
246  aws_secret_access_key  =  SK
247";
248        let p = parse_default_profile(ini).unwrap();
249        assert_eq!(p.get("aws_access_key_id").unwrap(), "AK");
250        assert_eq!(p.get("aws_secret_access_key").unwrap(), "SK");
251    }
252}