From 68754cc81749173449636a802f268d2522bd6b60 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 20:56:33 +0100 Subject: [PATCH] chore(lint): the environment is read only through Variable --- apps/auth-service/src/cli/output/mod.rs | 9 +++-- clippy.toml | 8 +++++ crates/auth-sdk/examples/notes.rs | 4 +++ crates/common/src/config/mod.rs | 35 +++++++++++++++---- crates/common/src/config/reference.rs | 2 +- crates/common/src/protocol/typescript.rs | 4 +++ crates/crypto/Cargo.toml | 4 +++ crates/crypto/tests/sdk_vectors.rs | 3 +- crates/database/Cargo.toml | 2 +- crates/database/src/connection/mod.rs | 2 +- crates/database/src/connection/tests.rs | 5 ++- crates/database/src/fixtures.rs | 19 +++++++++- .../database/src/repositories/audit/tests.rs | 4 +-- crates/database/tests/recoveries.rs | 5 ++- docs/dev/rust-conventions.md | 3 ++ 15 files changed, 87 insertions(+), 22 deletions(-) diff --git a/apps/auth-service/src/cli/output/mod.rs b/apps/auth-service/src/cli/output/mod.rs index 65ce04278..bb759fcff 100644 --- a/apps/auth-service/src/cli/output/mod.rs +++ b/apps/auth-service/src/cli/output/mod.rs @@ -19,6 +19,7 @@ use sourceorigin_common::{ AccountStatus, admin::{DeliveryStatus, Paging, SigningKeyState}, alerts::AlertState, + config::Variable, }; use std::{ error::Error, @@ -113,8 +114,12 @@ impl Stream { /// `TERM` is not `dumb`. fn terminal(writer: impl Write + IsTerminal + Send + 'static) -> Self { let color = writer.is_terminal() - && std::env::var_os("NO_COLOR").is_none_or(|value| value.is_empty()) - && std::env::var_os("TERM").is_none_or(|term| term != "dumb"); + && Variable::new("NO_COLOR") + .raw() + .is_none_or(|value| value.is_empty()) + && Variable::new("TERM") + .raw() + .is_none_or(|term| term != "dumb"); Self { writer: Box::new(writer), color, diff --git a/clippy.toml b/clippy.toml index fe289d379..71f0aa8e6 100644 --- a/clippy.toml +++ b/clippy.toml @@ -6,3 +6,11 @@ allow-dbg-in-tests = true # The project's name is a word in prose, not code. `..` keeps Clippy's defaults. doc-valid-idents = ["SourceOrigin", ".."] + +# Environment reads go through `Variable` (`sourceorigin_common::config`), which +# names the variable, parses it and keeps secrets out of errors. +disallowed-methods = [ + { path = "std::env::var", reason = "read the environment through `Variable`" }, + { path = "std::env::var_os", reason = "read the environment through `Variable`" }, + { path = "std::env::vars", reason = "read the environment through `Variable`" }, +] diff --git a/crates/auth-sdk/examples/notes.rs b/crates/auth-sdk/examples/notes.rs index 77cfdcb66..48265c526 100644 --- a/crates/auth-sdk/examples/notes.rs +++ b/crates/auth-sdk/examples/notes.rs @@ -13,6 +13,10 @@ //! //! The `ANCHOR` comments mark the parts `docs/user/apps/sign-in-rust.md` and //! `docs/user/apps/protect-an-api.md` show. +#![expect( + clippy::disallowed_methods, + reason = "An example for applications that read their settings with `std::env`, not SourceOrigin's `Variable`" +)] use axum::{Json, Router, extract::State, http::StatusCode, routing::get}; use sourceorigin_auth::{ diff --git a/crates/common/src/config/mod.rs b/crates/common/src/config/mod.rs index 1368360d0..8756bac1a 100644 --- a/crates/common/src/config/mod.rs +++ b/crates/common/src/config/mod.rs @@ -5,7 +5,7 @@ mod reference; pub use reference::{Documented, GeneratedFile, Section, Stale}; use secrecy::zeroize::Zeroizing; -use std::{env, error::Error as StdError, fmt, fs, path::PathBuf, str::FromStr}; +use std::{env, error::Error as StdError, ffi::OsString, fmt, fs, path::PathBuf, str::FromStr}; use thiserror::Error; use url::Url; @@ -69,16 +69,37 @@ impl Variable { source: Some(Box::new(source)), } } + /// The environment variable `name` as the operating system holds it, if set. + /// The only read of the process environment: `env::var` would put a + /// non-Unicode value into its error, so every read takes the raw value. + #[expect( + clippy::disallowed_methods, + reason = "`Variable` is where the environment is read" + )] + pub(crate) fn os(name: &str) -> Option { + env::var_os(name) + } + /// The value as the operating system holds it, if set. For a setting that is + /// not text, such as a flag whose presence is its value. + #[must_use] + pub fn raw(self) -> Option { + Self::os(self.0) + } + /// Whether the variable is set, even to nothing. + #[must_use] + pub fn is_set(self) -> bool { + self.raw().is_some() + } /// Reads an optional UTF-8 setting. /// /// # Errors /// Returns an error for non-Unicode environment values, without exposing them. pub fn optional(self) -> Result, ConfigurationError> { - match env::var(self.0) { - Ok(value) => Ok(Some(value)), - Err(env::VarError::NotPresent) => Ok(None), - // VarError::NotUnicode contains the value, so it must not enter diagnostics. - Err(env::VarError::NotUnicode(_)) => Err(self.invalid("must contain UTF-8 text")), + match self.raw().map(OsString::into_string) { + None => Ok(None), + Some(Ok(value)) => Ok(Some(value)), + // The error is the value itself, which must not enter diagnostics. + Some(Err(_)) => Err(self.invalid("must contain UTF-8 text")), } } /// Reads a required setting. @@ -281,7 +302,7 @@ impl SecretReference { pub fn resolve(&self) -> Result { let bytes = match &self.0 { // var_os keeps the value out of the error, unlike env::var. - SecretLocation::Environment(name) => env::var_os(name) + SecretLocation::Environment(name) => Variable::os(name) .ok_or(SecretError::MissingVariable)? .into_string() .map_err(|_| SecretError::NotUnicode)? diff --git a/crates/common/src/config/reference.rs b/crates/common/src/config/reference.rs index d53f38cc1..cd28d3c0e 100644 --- a/crates/common/src/config/reference.rs +++ b/crates/common/src/config/reference.rs @@ -144,7 +144,7 @@ impl GeneratedFile { /// # Errors /// Returns [`Stale`] when the committed file differs, or the write's error. pub fn write_or_compare(&self) -> Result<(), Stale> { - if std::env::var_os(UPDATE).is_some() { + if Variable::new(UPDATE).is_set() { return fs::write(&self.path, &self.text).map_err(|source| Stale::Write { path: self.path.clone(), source, diff --git a/crates/common/src/protocol/typescript.rs b/crates/common/src/protocol/typescript.rs index 62c113ec2..55dac4ab2 100644 --- a/crates/common/src/protocol/typescript.rs +++ b/crates/common/src/protocol/typescript.rs @@ -393,6 +393,10 @@ fn generate() -> String { /// The committed declarations match the Rust types. #[test] +#[expect( + clippy::disallowed_methods, + reason = "`Variable` needs the `config` feature, which this crate's own tests do not enable" +)] fn typescript_declarations_are_current() { let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../packages/auth/src/protocol.ts"); diff --git a/crates/crypto/Cargo.toml b/crates/crypto/Cargo.toml index c35d19d0d..a88f19b32 100644 --- a/crates/crypto/Cargo.toml +++ b/crates/crypto/Cargo.toml @@ -21,6 +21,10 @@ serde.workspace = true serde_json.workspace = true thiserror.workspace = true +[dev-dependencies] +# The vector test reads its `UPDATE_SDK_VECTORS` flag through `Variable`. +sourceorigin-common = { workspace = true, features = ["config"] } + [package.metadata.docs.rs] all-features = true # Labels feature-gated items with the features they need. diff --git a/crates/crypto/tests/sdk_vectors.rs b/crates/crypto/tests/sdk_vectors.rs index 59140cdba..1333bbfa8 100644 --- a/crates/crypto/tests/sdk_vectors.rs +++ b/crates/crypto/tests/sdk_vectors.rs @@ -19,6 +19,7 @@ use serde::Serialize; use serde_json::{Value, json}; use sourceorigin_common::{ AuthenticationMethod, ClientId, DeliveryId, SessionId, TokenId, + config::Variable, protocol::{ challenge::{BearerChallenge, BearerError}, claims::{ @@ -181,7 +182,7 @@ impl Vectors { .is_some_and(|extension| extension == "json") }) .collect(); - if std::env::var_os("UPDATE_SDK_VECTORS").is_some() { + if Variable::new("UPDATE_SDK_VECTORS").is_set() { for path in committed { fs::remove_file(path).expect("remove old vector"); } diff --git a/crates/database/Cargo.toml b/crates/database/Cargo.toml index 2d873d135..011cc3ff9 100644 --- a/crates/database/Cargo.toml +++ b/crates/database/Cargo.toml @@ -9,7 +9,7 @@ publish = false [dependencies] chrono.workspace = true -sourceorigin-common = { workspace = true, features = ["admin", "events", "sqlx"] } +sourceorigin-common = { workspace = true, features = ["admin", "config", "events", "sqlx"] } sourceorigin-crypto.workspace = true sourceorigin-telemetry.workspace = true secrecy.workspace = true diff --git a/crates/database/src/connection/mod.rs b/crates/database/src/connection/mod.rs index 12df5aace..175a5cf15 100644 --- a/crates/database/src/connection/mod.rs +++ b/crates/database/src/connection/mod.rs @@ -393,7 +393,7 @@ impl Database { /// Connects to `TEST_DATABASE_URL` and applies the schema. In-crate database /// tests get the raw pool so they can insert fixtures with plain SQL. pub(crate) async fn test_pool() -> PgPool { - let url = std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL"); + let url = Self::test_url(); let pool = PgPool::connect(&url).await.expect("connect"); Self { pool: pool.clone() } .run_migrations() diff --git a/crates/database/src/connection/tests.rs b/crates/database/src/connection/tests.rs index 4a6ef9c00..aff96d951 100644 --- a/crates/database/src/connection/tests.rs +++ b/crates/database/src/connection/tests.rs @@ -388,8 +388,7 @@ async fn under_provisioning_lock(owner: &Database, sql: &str) { /// Connection settings for `user` on `TEST_DATABASE_URL`, without a password. fn config_for(user: &str) -> DatabaseConfig { - let mut url = url::Url::parse(&std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL")) - .expect("test URL"); + let mut url = url::Url::parse(&Database::test_url()).expect("test URL"); url.set_username(user).expect("user"); url.set_password(None).expect("password"); DatabaseConfig::new(url.as_str(), 1, Duration::from_secs(5)).expect("config") @@ -533,7 +532,7 @@ async fn functions_running_as_their_owner_are_not_executable_by_others() { #[ignore = "requires a disposable TEST_DATABASE_URL"] async fn statements_and_lock_waits_past_their_limits_fail() { Database::test_pool().await; - let url = std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL"); + let url = Database::test_url(); let config = DatabaseConfig::new(&url, 2, Duration::from_secs(5)).expect("configuration"); let database = Database::connect(config).await.expect("connect"); let settings: Vec = sqlx::query_scalar( diff --git a/crates/database/src/fixtures.rs b/crates/database/src/fixtures.rs index 233237e39..33c90ef52 100644 --- a/crates/database/src/fixtures.rs +++ b/crates/database/src/fixtures.rs @@ -6,11 +6,28 @@ use crate::{Database, DatabaseConfig, EventRepository, InsertSession, InsertUser use chrono::{TimeDelta, Utc}; use sourceorigin_common::{ Handle, SessionId, UserId, + config::Variable, events::{Browser, DomainEvent, Platform, UserAgentFamily}, }; use std::net::IpAddr; impl Database { + /// The URL of the disposable cluster that database tests run against. + /// + /// # Panics + /// + /// Panics if `TEST_DATABASE_URL` is unset. + #[expect( + clippy::expect_used, + reason = "test-only fixture; documented under `# Panics`" + )] + #[must_use] + pub fn test_url() -> String { + Variable::new("TEST_DATABASE_URL") + .required() + .expect("TEST_DATABASE_URL") + } + /// Opens a pool of up to five connections to `TEST_DATABASE_URL`, with the /// time limits every connection of the service has, and applies the schema. /// @@ -23,7 +40,7 @@ impl Database { reason = "test-only fixture; documented under `# Panics`" )] pub async fn test() -> Self { - let url = std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL"); + let url = Self::test_url(); let config = DatabaseConfig::new(&url, 5, std::time::Duration::from_secs(5)) .expect("database configuration"); let database = Self::connect(config).await.expect("connect"); diff --git a/crates/database/src/repositories/audit/tests.rs b/crates/database/src/repositories/audit/tests.rs index 2cc775724..4feda1528 100644 --- a/crates/database/src/repositories/audit/tests.rs +++ b/crates/database/src/repositories/audit/tests.rs @@ -58,7 +58,7 @@ async fn sealing_needs_committed_data() { #[tokio::test] #[ignore = "requires a disposable TEST_DATABASE_URL"] async fn sealed_history_is_guarded() { - let url = std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL"); + let url = Database::test_url(); let database = Database::isolated( DatabaseConfig::new(&url, 1, Duration::from_secs(5)).expect("configuration"), ) @@ -146,7 +146,7 @@ async fn sealed_history_is_guarded() { #[tokio::test] #[ignore = "requires a disposable TEST_DATABASE_URL"] async fn personal_data_is_recorded_only_with_its_event() { - let url = std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL"); + let url = Database::test_url(); let database = Database::isolated( DatabaseConfig::new(&url, 1, Duration::from_secs(5)).expect("configuration"), ) diff --git a/crates/database/tests/recoveries.rs b/crates/database/tests/recoveries.rs index df9ab0cc7..3955affce 100644 --- a/crates/database/tests/recoveries.rs +++ b/crates/database/tests/recoveries.rs @@ -32,7 +32,7 @@ impl Owner { let db = Database::test().await; // A repository never hands out its pool, so the raw statements get one // of their own. - let url = std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL"); + let url = Database::test_url(); let pool = sqlx::PgPool::connect(&url).await.expect("pool"); Self { db, pool } } @@ -96,8 +96,7 @@ impl Limited { REVOKE ALL ON account_recoveries FROM {name};" )) .await; - let mut url = - url::Url::parse(&std::env::var("TEST_DATABASE_URL").expect("URL")).expect("test URL"); + let mut url = url::Url::parse(&Database::test_url()).expect("test URL"); url.set_username(&name).expect("user"); url.set_password(None).expect("password"); let config = DatabaseConfig::new(url.as_str(), 1, std::time::Duration::from_secs(5)) diff --git a/docs/dev/rust-conventions.md b/docs/dev/rust-conventions.md index 0bd456d47..1c0332e19 100644 --- a/docs/dev/rust-conventions.md +++ b/docs/dev/rust-conventions.md @@ -91,6 +91,9 @@ Declare each environment variable as a `Variable` constant beside its configurat section. `ConfigurationError` names the variable, explains how to fix it and retains safe underlying sources. Parse configuration into validated types such as `Origin` at startup; downstream code uses those values without revalidation. +Nothing else reads the environment: Clippy bans `std::env::var`, `var_os` and `vars` +(`clippy.toml`), and `Variable::os` is the one read. A flag or a setting that is not +text uses `Variable::raw` or `Variable::is_set`. OIDC clients are not configuration: they live in the database (see below). `AuthConfig` combines one section per application, such as `PasskeyConfig`,