Skip to main content

qcs_api_client_common/configuration/
secrets.rs

1//! Models and utilities for managing QCS secret credentials.
2
3use std::collections::HashMap;
4use std::path::{Path, PathBuf};
5
6use figment::Figment;
7use figment::providers::{Format, Toml};
8use serde::{Deserialize, Serialize};
9use time::format_description::well_known::Rfc3339;
10use time::{OffsetDateTime, PrimitiveDateTime};
11use toml_edit::{DocumentMut, Item};
12
13use crate::configuration::LoadError;
14
15use super::error::{IoErrorWithPath, IoOperation, WriteError};
16use super::tokens::ClientCredentials;
17use super::{DEFAULT_PROFILE_NAME, expand_path_from_env_or_default};
18
19pub use super::external_command::{ExternalCommandError, ExternallyManagedCredential};
20pub use super::secret_string::{ClientSecret, SecretAccessToken, SecretRefreshToken};
21
22/// Setting the `QCS_SECRETS_FILE_PATH` environment variable will change which file is used for loading secrets
23pub const SECRETS_PATH_VAR: &str = "QCS_SECRETS_FILE_PATH";
24/// `QCS_SECRETS_READ_ONLY` indicates whether to treat the `secrets.toml` file as read-only. Disabled by default.
25/// * Access token updates will _not_ be persisted to the secrets file, regardless of file permissions, for any of the following values (case insensitive): "true", "yes", "1".  
26/// * Access token updates will be persisted to the secrets file if it is writeable for any other value or if unset.
27pub const SECRETS_READ_ONLY_VAR: &str = "QCS_SECRETS_READ_ONLY";
28/// The default path that [`Secrets`] will be loaded from
29pub const DEFAULT_SECRETS_PATH: &str = "~/.qcs/secrets.toml";
30
31/// The structure of QCS secrets, typically serialized as a TOML file at [`DEFAULT_SECRETS_PATH`].
32#[derive(Deserialize, Debug, PartialEq, Eq, Serialize)]
33pub struct Secrets {
34    /// All named [`Credential`]s defined in the secrets file.
35    #[serde(default = "default_credentials")]
36    pub credentials: HashMap<String, Credential>,
37    /// The path to the secrets file this [`Secrets`] was loaded from,
38    /// if it was loaded from a file. This is not stored in the secrets file itself.
39    #[serde(skip)]
40    pub file_path: Option<PathBuf>,
41}
42
43fn default_credentials() -> HashMap<String, Credential> {
44    HashMap::from([(DEFAULT_PROFILE_NAME.to_string(), Credential::default())])
45}
46
47impl Default for Secrets {
48    fn default() -> Self {
49        Self {
50            credentials: default_credentials(),
51            file_path: None,
52        }
53    }
54}
55
56impl Secrets {
57    /// Load [`Secrets`] from the path specified by the [`SECRETS_PATH_VAR`] environment variable if set,
58    /// or else the default path at [`DEFAULT_SECRETS_PATH`].
59    ///
60    /// # Errors
61    ///
62    /// [`LoadError`] if the secrets file cannot be loaded.
63    pub fn load() -> Result<Self, LoadError> {
64        let path = expand_path_from_env_or_default(SECRETS_PATH_VAR, DEFAULT_SECRETS_PATH)?;
65        #[cfg(feature = "tracing")]
66        tracing::debug!("loading QCS secrets from {path:?}");
67        Self::load_from_path(&path)
68    }
69
70    /// Load [`Secrets`] from the path specified by `path`.
71    ///
72    /// # Errors
73    ///
74    /// [`LoadError`] if the secrets file cannot be loaded.
75    pub fn load_from_path(path: &PathBuf) -> Result<Self, LoadError> {
76        let mut secrets: Self = Figment::from(Toml::file(path)).extract()?;
77        secrets.file_path = Some(path.into());
78        Ok(secrets)
79    }
80
81    /// Returns a bool indicating whether or not the QCS [`Secrets`] file is read-only.
82    ///
83    /// The file is considered read-only if the [`SECRETS_READ_ONLY_VAR`] environment variable is set,
84    /// or if the file permissions indicate that it is read-only.
85    ///
86    /// # Errors
87    ///
88    /// [`WriteError`] if the file permissions cannot be checked.
89    pub async fn is_read_only(
90        secrets_path: impl AsRef<Path> + Send + Sync,
91    ) -> Result<bool, WriteError> {
92        // Check if the QCS_SECRETS_READ_ONLY environment variable is set
93        let ro_env = std::env::var(SECRETS_READ_ONLY_VAR);
94        let ro_env_lowercase = ro_env.as_deref().map(str::to_lowercase);
95        if let Ok("true" | "yes" | "1") = ro_env_lowercase.as_deref() {
96            return Ok(true);
97        }
98
99        // Check file permissions - a non-existent file is treated as writable if its
100        // parent directory is writable
101        for (i, ancestor) in secrets_path.as_ref().ancestors().enumerate() {
102            match tokio::fs::metadata(ancestor).await {
103                Ok(metadata) => return Ok(metadata.permissions().readonly()),
104                Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
105                Err(error) if i == 0 => {
106                    return Err(IoErrorWithPath {
107                        error,
108                        path: secrets_path.as_ref().to_path_buf(),
109                        operation: IoOperation::GetMetadata,
110                    }
111                    .into());
112                }
113                Err(_) => return Ok(true), // Can't access ancestor = read-only
114            }
115        }
116        Ok(true) // No existing ancestor found = read-only
117    }
118
119    /// Attempts to write a refresh and access token to the QCS [`Secrets`] file at
120    /// the given path.
121    ///
122    /// The access token will only be updated if the access token currently stored in the file is
123    /// older than the provided `updated_at` timestamp.
124    ///
125    /// # Errors
126    ///
127    /// - [`TokenError`] for possible errors.
128    pub(crate) async fn write_tokens(
129        secrets_path: impl AsRef<Path> + Send + Sync + std::fmt::Debug,
130        credentials_name: &str,
131        refresh_token: Option<&SecretRefreshToken>,
132        access_token: &SecretAccessToken,
133        updated_at: OffsetDateTime,
134    ) -> Result<(), WriteError> {
135        // Read the current contents of the secrets file
136        let secrets_string = tokio::fs::read_to_string(&secrets_path)
137            .await
138            .map_err(|error| IoErrorWithPath {
139                error,
140                path: secrets_path.as_ref().to_path_buf(),
141                operation: IoOperation::Read,
142            })?;
143
144        // Parse the TOML content into a mutable document
145        let mut secrets_toml = secrets_string.parse::<DocumentMut>()?;
146
147        // Navigate to the `[credentials.<credentials_name>.token_payload]` table
148        let token_payload = Self::get_token_payload_table(&mut secrets_toml, credentials_name)?;
149
150        let current_updated_at = token_payload
151            .get("updated_at")
152            .and_then(|v| v.as_str())
153            .and_then(|s| PrimitiveDateTime::parse(s, &Rfc3339).ok())
154            .map(PrimitiveDateTime::assume_utc);
155
156        let did_update_access_token = if current_updated_at.is_none_or(|dt| dt < updated_at) {
157            token_payload["access_token"] = access_token.secret().into();
158            token_payload["updated_at"] = updated_at.format(&Rfc3339)?.into();
159            true
160        } else {
161            false
162        };
163
164        let did_update_refresh_token = refresh_token.is_some_and(|new_refresh_token| {
165            let current_refresh_token = token_payload.get("refresh_token").and_then(|v| v.as_str());
166            let new_refresh_token = new_refresh_token.secret();
167
168            let is_changed = current_refresh_token != Some(new_refresh_token);
169            if is_changed {
170                token_payload["refresh_token"] = new_refresh_token.into();
171            }
172            is_changed
173        });
174
175        if did_update_access_token || did_update_refresh_token {
176            // Atomically overwrite the secrets file. The temporary buffer is
177            // staged next to the destination so the rename stays atomic even when
178            // the secrets file lives on a different mount point from the system
179            // temporary directory (which previously caused `cross-device link` errors).
180            super::fs::atomic_write(&secrets_path, secrets_toml.to_string().as_bytes()).await?;
181        }
182
183        Ok(())
184    }
185
186    /// Get the `[credentials.<credentials_name>.token_payload]` table from the TOML document
187    fn get_token_payload_table<'a>(
188        secrets_toml: &'a mut DocumentMut,
189        credentials_name: &str,
190    ) -> Result<&'a mut Item, WriteError> {
191        secrets_toml
192            .get_mut("credentials")
193            .and_then(|credentials| {
194                credentials
195                    .get_mut(credentials_name)?
196                    .get_mut("token_payload")
197            })
198            .ok_or_else(|| {
199                WriteError::MissingTable(format!("credentials.{credentials_name}.token_payload"))
200            })
201    }
202}
203
204/// A QCS credential, containing or providing access to sensitive authentication secrets.
205#[derive(Deserialize, Debug, PartialEq, Eq, Serialize)]
206#[serde(rename_all = "snake_case")]
207pub enum Credential {
208    /// The [`TokenPayload`] for this credential.
209    TokenPayload(TokenPayload),
210    /// Defer to a subcommand to manage access tokens.
211    ExternallyManaged(ExternallyManagedCredential),
212    /// Exchange a client secret for access tokens.
213    ClientCredentials(ClientCredentials),
214}
215
216impl Default for Credential {
217    fn default() -> Self {
218        Self::TokenPayload(TokenPayload::default())
219    }
220}
221
222/// A QCS token payload, containing sensitive authentication secrets.
223#[derive(Deserialize, Debug, Default, PartialEq, Eq, Serialize)]
224pub struct TokenPayload {
225    /// The refresh token for this credential.
226    pub refresh_token: Option<SecretRefreshToken>,
227    /// The access token for this credential.
228    pub access_token: Option<SecretAccessToken>,
229    /// The time at which this token was last updated.
230    #[serde(
231        default,
232        deserialize_with = "time::serde::rfc3339::option::deserialize",
233        serialize_with = "time::serde::rfc3339::option::serialize"
234    )]
235    pub updated_at: Option<OffsetDateTime>,
236
237    // The below fields are retained for (de)serialization for compatibility with other
238    // libraries that use token payloads, but are not relevant here.
239    scope: Option<String>,
240    expires_in: Option<u32>,
241    id_token: Option<String>,
242    token_type: Option<String>,
243}
244
245#[cfg(test)]
246mod describe_load {
247    #![allow(clippy::result_large_err, reason = "happens in figment tests")]
248
249    #[cfg(unix)]
250    use std::os::unix::fs::PermissionsExt;
251    use std::path::PathBuf;
252
253    use time::{OffsetDateTime, macros::datetime};
254
255    use crate::configuration::secrets::{SECRETS_READ_ONLY_VAR, SecretAccessToken};
256
257    use super::{Credential, SECRETS_PATH_VAR, Secrets};
258
259    #[test]
260    fn returns_err_if_invalid_path_env() {
261        figment::Jail::expect_with(|jail| {
262            jail.set_env(SECRETS_PATH_VAR, "/blah/doesnt_exist.toml");
263            Secrets::load().expect_err("Should return error when a file cannot be found.");
264            Ok(())
265        });
266    }
267
268    #[test]
269    fn loads_from_env_var_path() {
270        figment::Jail::expect_with(|jail| {
271            let mut secrets = Secrets {
272                file_path: Some(PathBuf::from("env_secrets.toml")),
273                ..Secrets::default()
274            };
275            secrets
276                .credentials
277                .insert("test".to_string(), Credential::default());
278            let secrets_string =
279                toml::to_string(&secrets).expect("Should be able to serialize secrets");
280
281            _ = jail.create_file("env_secrets.toml", &secrets_string)?;
282            jail.set_env(SECRETS_PATH_VAR, "env_secrets.toml");
283
284            assert_eq!(secrets, Secrets::load().unwrap());
285
286            Ok(())
287        });
288    }
289
290    const fn max_rfc3339() -> OffsetDateTime {
291        // PrimitiveDateTime::MAX can be larger than what can fit in a RFC3339 timestamp if the `time` crate's `large-dates` feature is enabled.
292        // Instead of asserting that the `time` crate's `large-dates` feature is disabled, we use a hardcoded max value here.
293        datetime!(9999-12-31 23:59:59.999_999_999).assume_utc()
294    }
295
296    #[test]
297    fn test_write_access_token() {
298        figment::Jail::expect_with(|jail| {
299            let secrets_file_contents = r#"
300[credentials]
301[credentials.test]
302[credentials.test.token_payload]
303access_token = "old_access_token"
304expires_in = 3600
305id_token = "id_token"
306refresh_token = "refresh_token"
307scope = "offline_access openid profile email"
308token_type = "Bearer"
309"#;
310
311            jail.create_file("secrets.toml", secrets_file_contents)
312                .expect("should create test secrets.toml");
313            let mut original_permissions = std::fs::metadata("secrets.toml")
314                .expect("Should be able to get file metadata")
315                .permissions();
316            #[cfg(unix)]
317            {
318                assert_ne!(
319                    0o666,
320                    original_permissions.mode(),
321                    "Initial file mode should not be 666"
322                );
323                original_permissions.set_mode(0o100_666);
324                std::fs::set_permissions("secrets.toml", original_permissions.clone())
325                    .expect("Should be able to set file permissions");
326            }
327            jail.set_env("QCS_SECRETS_FILE_PATH", "secrets.toml");
328            jail.set_env("QCS_PROFILE_NAME", "test");
329
330            let rt = tokio::runtime::Runtime::new().unwrap();
331            rt.block_on(async {
332                // Create array of token updates with different timestamps
333                let token_updates = [
334                    ("new_access_token", max_rfc3339()),
335                    ("stale_access_token", OffsetDateTime::now_utc()),
336                ];
337
338                for (access_token, updated_at) in token_updates {
339                    Secrets::write_tokens(
340                        "secrets.toml",
341                        "test",
342                        None,
343                        &SecretAccessToken::from(access_token),
344                        updated_at,
345                    )
346                    .await
347                    .expect("Should be able to write access token");
348                }
349
350                // Verify the final state
351                let mut secrets = Secrets::load_from_path(&"secrets.toml".into()).unwrap();
352                let Credential::TokenPayload(payload) = secrets.credentials.remove("test").unwrap()
353                else {
354                    panic!("expected a token payload credential");
355                };
356
357                assert_eq!(
358                    payload.access_token.unwrap(),
359                    SecretAccessToken::from("new_access_token")
360                );
361                assert_eq!(payload.updated_at.unwrap(), max_rfc3339());
362                let new_permissions = std::fs::metadata("secrets.toml")
363                    .expect("Should be able to get file metadata")
364                    .permissions();
365                assert_eq!(
366                    original_permissions, new_permissions,
367                    "Final file permissions should not be changed"
368                );
369            });
370
371            Ok(())
372        });
373    }
374
375    /// Set file permissions on Unix systems for jail-created files and directories
376    fn set_mode(path: &PathBuf, mode: u32) {
377        #[cfg(unix)]
378        {
379            use std::os::unix::fs::PermissionsExt;
380            let perms = std::fs::Permissions::from_mode(mode);
381            std::fs::set_permissions(path, perms).expect("Should be able to set permissions");
382        }
383    }
384
385    #[test]
386    fn test_is_read_only_missing_file_checks_parent_dir() {
387        figment::Jail::expect_with(|jail| {
388            jail.set_env(SECRETS_READ_ONLY_VAR, "false");
389
390            let writable_dir = jail.create_dir("writable_dir")?;
391            let readonly_dir = jail.create_dir("readonly_dir")?;
392
393            set_mode(&writable_dir, 0o777);
394            set_mode(&readonly_dir, 0o555);
395
396            let rt = tokio::runtime::Runtime::new().unwrap();
397            rt.block_on(async {
398                // Missing file in writable directory should be writable (not read-only)
399                let writable_path = writable_dir.join("missing_secrets.toml");
400                let is_ro = Secrets::is_read_only(&writable_path)
401                    .await
402                    .expect("Should not error");
403                assert!(
404                    !is_ro,
405                    "Missing file in writable directory should not be read-only: {}",
406                    writable_path.display()
407                );
408
409                // Missing file in read-only directory should be read-only
410                let readonly_path = readonly_dir.join("missing_secrets.toml");
411                let is_ro = Secrets::is_read_only(&readonly_path)
412                    .await
413                    .expect("Should not error");
414                assert!(
415                    is_ro,
416                    "Missing file in read-only directory should be read-only: {}",
417                    readonly_path.display()
418                );
419            });
420
421            Ok(())
422        });
423    }
424
425    #[test]
426    fn test_is_read_only_existing_file() {
427        figment::Jail::expect_with(|jail| {
428            jail.set_env(SECRETS_READ_ONLY_VAR, "false");
429
430            jail.create_file("writable_secrets.toml", "")?;
431            jail.create_file("readonly_secrets.toml", "")?;
432
433            let writable_path = jail.directory().join("writable_secrets.toml");
434            let readonly_path = jail.directory().join("readonly_secrets.toml");
435
436            set_mode(&writable_path, 0o666);
437            set_mode(&readonly_path, 0o444);
438
439            let rt = tokio::runtime::Runtime::new().unwrap();
440            rt.block_on(async {
441                // Existing writable file should not be read-only
442                let is_ro = Secrets::is_read_only(&writable_path)
443                    .await
444                    .expect("Should not error");
445                assert!(
446                    !is_ro,
447                    "Writable file should not be read-only: {}",
448                    writable_path.display()
449                );
450
451                // Existing read-only file should be read-only
452                let is_ro = Secrets::is_read_only(&readonly_path)
453                    .await
454                    .expect("Should not error");
455                assert!(
456                    is_ro,
457                    "Read-only file should be read-only: {}",
458                    readonly_path.display()
459                );
460            });
461
462            Ok(())
463        });
464    }
465}