Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions apps/auth-service/src/cli/output/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use sourceorigin_common::{
AccountStatus,
admin::{DeliveryStatus, Paging, SigningKeyState},
alerts::AlertState,
config::Variable,
};
use std::{
error::Error,
Expand Down Expand Up @@ -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,
Expand Down
8 changes: 8 additions & 0 deletions clippy.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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`" },
]
4 changes: 4 additions & 0 deletions crates/auth-sdk/examples/notes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down
35 changes: 28 additions & 7 deletions crates/common/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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<OsString> {
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<OsString> {
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<Option<String>, 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.
Expand Down Expand Up @@ -281,7 +302,7 @@ impl SecretReference {
pub fn resolve(&self) -> Result<SecretBytes, SecretError> {
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)?
Expand Down
2 changes: 1 addition & 1 deletion crates/common/src/config/reference.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 4 additions & 0 deletions crates/common/src/protocol/typescript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
4 changes: 4 additions & 0 deletions crates/crypto/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion crates/crypto/tests/sdk_vectors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -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");
}
Expand Down
2 changes: 1 addition & 1 deletion crates/database/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion crates/database/src/connection/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
5 changes: 2 additions & 3 deletions crates/database/src/connection/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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<String> = sqlx::query_scalar(
Expand Down
19 changes: 18 additions & 1 deletion crates/database/src/fixtures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand All @@ -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");
Expand Down
4 changes: 2 additions & 2 deletions crates/database/src/repositories/audit/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
)
Expand Down Expand Up @@ -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"),
)
Expand Down
5 changes: 2 additions & 3 deletions crates/database/tests/recoveries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
}
Expand Down Expand Up @@ -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))
Expand Down
3 changes: 3 additions & 0 deletions docs/dev/rust-conventions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand Down
Loading