Skip to main content

ostrya_remote/s3/
credentials.rs

1//! The key pair that signs an S3 request.
2
3use crate::{Error, Result};
4
5/// An AWS access key pair, with an optional session token.
6///
7/// [`SigV4`](super::SigV4) signs each request with it.
8/// [`resolve`](super::resolve) gives one from the environment or from the
9/// shared AWS files, and a caller can make one with
10/// [`Credentials::new`].
11///
12/// The [`Debug`] output shows the access key id alone. It shows the secret
13/// access key and the session token as `<redacted>`. No method gives the
14/// secret access key or the session token back.
15#[derive(Clone)]
16pub struct Credentials {
17    access_key_id: String,
18    secret_access_key: String,
19    session_token: Option<String>,
20}
21
22impl Credentials {
23    /// Returns the key pair of `access_key_id` and `secret_access_key`, with
24    /// the session token `session_token`.
25    ///
26    /// # Errors
27    ///
28    /// [`Error::InvalidInput`] if a value cannot go into a signature. The
29    /// message holds no part of the secret access key or of the session
30    /// token. These values are refused:
31    ///
32    /// - an empty access key id, or an access key id with a character that is
33    ///   not printable ASCII, a space, `/`, or `,`
34    /// - an empty secret access key, or a secret access key with a control
35    ///   character
36    /// - an empty session token, or a session token with a character that is
37    ///   not printable ASCII, or a space
38    ///
39    /// # Examples
40    ///
41    /// ```
42    /// use ostrya_remote::s3::Credentials;
43    /// # fn run() -> ostrya_remote::Result<()> {
44    /// let credentials = Credentials::new(
45    ///     "AKIAIOSFODNN7EXAMPLE".into(),
46    ///     "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".into(),
47    ///     None,
48    /// )?;
49    /// assert_eq!(credentials.access_key_id(), "AKIAIOSFODNN7EXAMPLE");
50    /// assert!(!format!("{credentials:?}").contains("EXAMPLEKEY"));
51    /// # Ok(()) }
52    /// # run().unwrap();
53    /// ```
54    pub fn new(
55        access_key_id: String,
56        secret_access_key: String,
57        session_token: Option<String>,
58    ) -> Result<Credentials> {
59        Credentials::checked(access_key_id, secret_access_key, session_token)
60            .map_err(|why| Error::InvalidInput(why.into()))
61    }
62
63    /// Returns the key pair as [`Credentials::new`] does, or the reason of its
64    /// refusal. The reason holds no value.
65    pub(super) fn checked(
66        access_key_id: String,
67        secret_access_key: String,
68        session_token: Option<String>,
69    ) -> std::result::Result<Credentials, &'static str> {
70        if access_key_id.is_empty() {
71            return Err("the access key id is empty");
72        }
73        if !access_key_id
74            .bytes()
75            .all(|b| b.is_ascii_graphic() && b != b'/' && b != b',')
76        {
77            return Err(
78                "the access key id holds a character that is not printable ASCII, a space, '/', or ','",
79            );
80        }
81        if secret_access_key.is_empty() {
82            return Err("the secret access key is empty");
83        }
84        if secret_access_key.chars().any(char::is_control) {
85            return Err("the secret access key holds a control character");
86        }
87        if let Some(token) = &session_token {
88            if token.is_empty() {
89                return Err("the session token is empty");
90            }
91            if !token.bytes().all(|b| b.is_ascii_graphic()) {
92                return Err(
93                    "the session token holds a character that is not printable ASCII, or a space",
94                );
95            }
96        }
97        Ok(Credentials {
98            access_key_id,
99            secret_access_key,
100            session_token,
101        })
102    }
103
104    /// Returns the access key id.
105    pub fn access_key_id(&self) -> &str {
106        &self.access_key_id
107    }
108
109    /// Returns `true` if the key pair has a session token.
110    pub fn has_session_token(&self) -> bool {
111        self.session_token.is_some()
112    }
113
114    /// Returns the secret access key, for the signing key.
115    pub(super) fn secret_access_key(&self) -> &str {
116        &self.secret_access_key
117    }
118
119    /// Returns the session token, for the `x-amz-security-token` header.
120    pub(super) fn session_token(&self) -> Option<&str> {
121        self.session_token.as_deref()
122    }
123}
124
125impl std::fmt::Debug for Credentials {
126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        f.debug_struct("Credentials")
128            .field("access_key_id", &self.access_key_id)
129            .field("secret_access_key", &"<redacted>")
130            .field(
131                "session_token",
132                &self.session_token.as_ref().map(|_| "<redacted>"),
133            )
134            .finish()
135    }
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    fn refused(id: &str, secret: &str, token: Option<&str>) -> String {
143        match Credentials::new(id.into(), secret.into(), token.map(Into::into)) {
144            Err(Error::InvalidInput(msg)) => msg,
145            other => panic!("expected a refusal, got {other:?}"),
146        }
147    }
148
149    #[test]
150    fn a_valid_pair_is_accepted() {
151        let credentials = Credentials::new(
152            "AKIAIOSFODNN7EXAMPLE".into(),
153            "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".into(),
154            Some("FwoGZXIvYXdz+/=".into()),
155        )
156        .unwrap();
157        assert_eq!(credentials.access_key_id(), "AKIAIOSFODNN7EXAMPLE");
158        assert!(credentials.has_session_token());
159        assert_eq!(credentials.session_token(), Some("FwoGZXIvYXdz+/="));
160    }
161
162    #[test]
163    fn each_invalid_value_is_refused_without_the_secret() {
164        // Each secret holds `QQ` and each token holds `ZZ`, which no message
165        // may hold.
166        let cases: &[(&str, &str, Option<&str>, &str)] = &[
167            ("", "QQ", None, "access key id is empty"),
168            ("AKIA EXAMPLE", "QQ", None, "access key id holds"),
169            ("AKIA/EXAMPLE", "QQ", None, "access key id holds"),
170            ("AKIA,EXAMPLE", "QQ", None, "access key id holds"),
171            ("AKIAÉXAMPLE", "QQ", None, "access key id holds"),
172            ("AKIA", "", None, "secret access key is empty"),
173            ("AKIA", "Q\nQ", None, "secret access key holds"),
174            ("AKIA", "QQ", Some(""), "session token is empty"),
175            ("AKIA", "QQ", Some("ZZ ZZ"), "session token holds"),
176            ("AKIA", "QQ", Some("ZZ\u{7f}"), "session token holds"),
177        ];
178        for (id, secret, token, want) in cases {
179            let msg = refused(id, secret, *token);
180            assert!(msg.contains(want), "{id:?}: {msg}");
181            assert!(!msg.contains('Q'), "{msg}");
182            assert!(!msg.contains('Z'), "{msg}");
183        }
184    }
185
186    #[test]
187    fn a_secret_with_unicode_and_spaces_is_accepted() {
188        Credentials::new("AKIA".into(), "s é cret".into(), None).unwrap();
189    }
190
191    #[test]
192    fn debug_hides_the_secret_and_the_token() {
193        let credentials = Credentials::new(
194            "AKIAIOSFODNN7EXAMPLE".into(),
195            "wJalrXUtnFEMI".into(),
196            Some("FwoGZXIvYXdz".into()),
197        )
198        .unwrap();
199        let debug = format!("{credentials:?}");
200        assert!(debug.contains("AKIAIOSFODNN7EXAMPLE"), "{debug}");
201        assert!(!debug.contains("wJalrXUtnFEMI"), "{debug}");
202        assert!(!debug.contains("FwoGZXIvYXdz"), "{debug}");
203        assert!(debug.contains("Some(\"<redacted>\")"), "{debug}");
204        let none = Credentials::new("AKIA".into(), "x".into(), None).unwrap();
205        assert!(format!("{none:?}").contains("session_token: None"));
206    }
207}