Skip to content
Closed
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
2 changes: 1 addition & 1 deletion apps/auth-service/src/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ mod tests {
async fn profile_update_and_event_commit_together() {
let url = env::var("TEST_DATABASE_URL")
.expect("TEST_DATABASE_URL must name an isolated PostgreSQL database");
let config = DatabaseConfig::new_development(url, 5, Duration::from_secs(5))
let config = DatabaseConfig::new_development(&url, 5, Duration::from_secs(5))
.expect("test database configuration");
let database = Database::connect(config).await.expect("connect database");
database.run_migrations().await.expect("run migrations");
Expand Down
4 changes: 2 additions & 2 deletions apps/auth-service/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,9 @@ impl AuthConfig {
PublicUrl::parse(&required("AUTH_PUBLIC_BASE_URL")?)?
};
let database = if development {
DatabaseConfig::new_development(database_url, 10, Duration::from_secs(5))
DatabaseConfig::new_development(&database_url, 10, Duration::from_secs(5))
} else {
DatabaseConfig::new(database_url, 10, Duration::from_secs(5))
DatabaseConfig::new(&database_url, 10, Duration::from_secs(5))
}
.map_err(|_| ConfigurationError::Invalid {
name: "AUTH_DATABASE_URL",
Expand Down
2 changes: 1 addition & 1 deletion apps/auth-service/src/passkey.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1131,7 +1131,7 @@ mod tests {
let database_url = env::var("TEST_DATABASE_URL")
.expect("TEST_DATABASE_URL must name an isolated PostgreSQL database");
let database = Database::connect(
DatabaseConfig::new_development(database_url, 5, StdDuration::from_secs(5))
DatabaseConfig::new_development(&database_url, 5, StdDuration::from_secs(5))
.expect("database configuration"),
)
.await
Expand Down
2 changes: 1 addition & 1 deletion apps/auth-service/tests/http_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ async fn database() -> Database {
let url = env::var("TEST_DATABASE_URL")
.expect("TEST_DATABASE_URL must name an isolated PostgreSQL database");
Database::connect(
DatabaseConfig::new_development(url, 5, Duration::from_secs(5))
DatabaseConfig::new_development(&url, 5, Duration::from_secs(5))
.expect("test database configuration"),
)
.await
Expand Down
2 changes: 1 addition & 1 deletion apps/auth-service/tests/rpc_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ async fn database() -> Database {
let url = env::var("TEST_DATABASE_URL")
.expect("TEST_DATABASE_URL must name an isolated PostgreSQL database");
Database::connect(
DatabaseConfig::new_development(url, 8, Duration::from_secs(5))
DatabaseConfig::new_development(&url, 8, Duration::from_secs(5))
.expect("test database configuration"),
)
.await
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
ALTER TABLE webauthn_ceremonies
DROP CONSTRAINT webauthn_ceremonies_ceremony_kind_check;

ALTER TABLE webauthn_ceremonies
ADD CONSTRAINT webauthn_ceremonies_ceremony_kind_check
CHECK (ceremony_kind IN ('registration', 'authentication', 'enrollment', 'purpose_authentication'));
3 changes: 2 additions & 1 deletion crates/database/src/bin/migrate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ use std::{env, time::Duration};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let url = env::var("DATABASE_URL")?;
let database = Database::connect(DatabaseConfig::new(url, 1, Duration::from_secs(10))?).await?;
let database =
Database::connect(DatabaseConfig::new(&url, 1, Duration::from_secs(10))?).await?;
database.run_migrations().await?;
Ok(())
}
93 changes: 71 additions & 22 deletions crates/database/src/connection.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
use crate::{
DatabaseConnectionError, DatabaseError, repositories::*, transaction::DatabaseTransaction,
};
use sqlx::{PgPool, postgres::PgPoolOptions};
use std::{net::IpAddr, time::Duration};
use sqlx::{
PgPool,
postgres::{PgConnectOptions, PgPoolOptions, PgSslMode},
};
use std::{net::IpAddr, str::FromStr, time::Duration};
use url::Url;

/// Validated database connection configuration.
#[derive(Clone)]
pub struct DatabaseConfig {
url: String,
options: PgConnectOptions,
max_connections: u32,
connect_timeout: Duration,
}
impl std::fmt::Debug for DatabaseConfig {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("DatabaseConfig")
.field("url", &"[REDACTED]")
.field("options", &"[REDACTED]")
.field("max_connections", &self.max_connections)
.field("connect_timeout", &self.connect_timeout)
.finish()
Expand All @@ -25,27 +28,27 @@ impl std::fmt::Debug for DatabaseConfig {
impl DatabaseConfig {
/// Creates production configuration requiring verified `PostgreSQL` TLS.
pub fn new(
url: String,
url: &str,
max_connections: u32,
connect_timeout: Duration,
) -> Result<Self, DatabaseConnectionError> {
Self::validate(&url, max_connections, connect_timeout, false)?;
let options = Self::validate(url, max_connections, connect_timeout, false)?;
Ok(Self {
url,
options,
max_connections,
connect_timeout,
})
}

/// Creates explicit local-development configuration for a loopback database.
pub fn new_development(
url: String,
url: &str,
max_connections: u32,
connect_timeout: Duration,
) -> Result<Self, DatabaseConnectionError> {
Self::validate(&url, max_connections, connect_timeout, true)?;
let options = Self::validate(url, max_connections, connect_timeout, true)?;
Ok(Self {
url,
options,
max_connections,
connect_timeout,
})
Expand All @@ -56,7 +59,7 @@ impl DatabaseConfig {
max_connections: u32,
connect_timeout: Duration,
development: bool,
) -> Result<(), DatabaseConnectionError> {
) -> Result<PgConnectOptions, DatabaseConnectionError> {
let parsed = Url::parse(url).map_err(|_| DatabaseConnectionError::InvalidConfiguration)?;
if !matches!(parsed.scheme(), "postgres" | "postgresql")
|| max_connections == 0
Expand All @@ -67,6 +70,18 @@ impl DatabaseConfig {
let host = parsed
.host_str()
.ok_or(DatabaseConnectionError::InvalidConfiguration)?;

let mut ssl_modes = parsed.query_pairs().filter_map(|(name, value)| {
matches!(name.as_ref(), "sslmode" | "ssl-mode").then_some(value)
});
let ssl_mode = ssl_modes.next();
if ssl_modes.next().is_some()
|| parsed
.query_pairs()
.any(|(name, _)| matches!(name.as_ref(), "host" | "hostaddr"))
{
return Err(DatabaseConnectionError::InvalidConfiguration);
}
if development {
let loopback = host.eq_ignore_ascii_case("localhost")
|| host
Expand All @@ -75,13 +90,19 @@ impl DatabaseConfig {
if !loopback {
return Err(DatabaseConnectionError::InvalidConfiguration);
}
} else if !parsed
.query_pairs()
.any(|(name, value)| name == "sslmode" && value == "verify-full")
{
} else if ssl_mode.as_deref() != Some("verify-full") {
return Err(DatabaseConnectionError::InvalidConfiguration);
}
Ok(())

let options = PgConnectOptions::from_str(url)
.map_err(|_| DatabaseConnectionError::InvalidConfiguration)?;
Ok(if development {
options
} else {
// Keep the effective mode explicit even after validating the URL so
// future parser changes cannot silently weaken production TLS.
options.ssl_mode(PgSslMode::VerifyFull)
})
}
}

Expand All @@ -96,7 +117,7 @@ impl Database {
let pool = PgPoolOptions::new()
.max_connections(config.max_connections)
.acquire_timeout(config.connect_timeout)
.connect(&config.url)
.connect_with(config.options)
.await
.map_err(|_| DatabaseConnectionError::Unavailable)?;
Ok(Self { pool })
Expand Down Expand Up @@ -190,37 +211,65 @@ mod tests {

#[test]
fn production_requires_verified_tls() {
assert!(
DatabaseConfig::new("postgres://db.example/piquel", 1, Duration::from_secs(1)).is_err()
);
assert!(
DatabaseConfig::new(
"postgres://db.example/piquel".into(),
"postgres://db.example/piquel?sslmode=verify-full",
1,
Duration::from_secs(1)
)
.is_err()
.is_ok()
);
assert!(
DatabaseConfig::new(
"postgres://db.example/piquel?sslmode=verify-full".into(),
"postgres://db.example/piquel?ssl-mode=verify-full",
1,
Duration::from_secs(1)
)
.is_ok()
);
}

#[test]
fn production_rejects_ambiguous_tls_modes_and_host_overrides() {
for url in [
"postgres://db.example/piquel?sslmode=verify-full&sslmode=disable",
"postgres://db.example/piquel?sslmode=disable&sslmode=verify-full",
"postgres://db.example/piquel?sslmode=verify-full&ssl-mode=disable",
"postgres://db.example/piquel?sslmode=verify-full&ssl-mode=verify-full",
"postgres://db.example/piquel?sslmode=verify-full&host=elsewhere.example",
"postgres://db.example/piquel?sslmode=verify-full&hostaddr=127.0.0.1",
] {
assert!(
DatabaseConfig::new(url, 1, Duration::from_secs(1)).is_err(),
"accepted ambiguous database URL: {url}"
);
}
}

#[test]
fn development_is_loopback_only() {
assert!(
DatabaseConfig::new_development(
"postgres://localhost/piquel".into(),
"postgres://localhost/piquel",
1,
Duration::from_secs(1)
)
.is_ok()
);
assert!(
DatabaseConfig::new_development(
"postgres://db.example/piquel".into(),
"postgres://db.example/piquel",
1,
Duration::from_secs(1)
)
.is_err()
);
assert!(
DatabaseConfig::new_development(
"postgres://localhost/piquel?host=db.example",
1,
Duration::from_secs(1)
)
Expand Down
22 changes: 21 additions & 1 deletion crates/database/tests/identity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use std::{env, time::Duration};
async fn database() -> Database {
let url = env::var("TEST_DATABASE_URL")
.expect("TEST_DATABASE_URL must name an isolated PostgreSQL database");
let config = DatabaseConfig::new_development(url, 10, Duration::from_secs(5))
let config = DatabaseConfig::new_development(&url, 10, Duration::from_secs(5))
.expect("test database configuration");
let database = Database::connect(config)
.await
Expand Down Expand Up @@ -183,6 +183,26 @@ async fn identity_transactions_and_concurrency_hold() {
);
assert_eq!(usize::from(left.is_ok()) + usize::from(right.is_ok()), 1);

let enrollment_id = TokenId::new();
database
.passkeys()
.insert_ceremony(&InsertCeremony {
id: enrollment_id,
user_id: Some(first),
session_id: None,
kind: "enrollment".into(),
challenge_digest: vec![2; 32],
state: serde_json::json!({"enrollment":true}),
expires_at: Utc::now() + ChronoDuration::minutes(5),
})
.await
.expect("enrollment ceremony");
database
.passkeys()
.consume_ceremony(enrollment_id, "enrollment")
.await
.expect("consume enrollment ceremony");

let refresh_session = SessionId::new();
database
.sessions()
Expand Down
Loading
Loading