footing 0.6.2

Feature-gated foundations for Rust backend services
Documentation
//! PostgreSQL identifiers and redacted URL helpers shared by configuration and runtime code.

use percent_encoding::percent_decode_str;
use sqlx::{ConnectOptions, postgres::PgConnectOptions};
use url::{Position, Url};

#[must_use]
/// Extracts an explicitly configured database name from a PostgreSQL URL.
///
/// Only `postgres` and `postgresql` URLs are accepted. A missing name is not
/// filled from `PGDATABASE` or another process-level default. This helper does
/// not load credentials, validate connection options, or emit driver logs.
pub fn database_name(database_url: &str) -> Option<String> {
    let url = parse_database_url(database_url).ok()?;
    let name = url
        .query_pairs()
        .filter(|(key, _)| key == "dbname")
        .map(|(_, value)| value.into_owned())
        .last()
        .or_else(|| {
            percent_decode_str(url.path().trim_start_matches('/'))
                .decode_utf8()
                .ok()
                .map(|name| name.into_owned())
        })?;
    (!name.trim().is_empty()).then_some(name)
}

pub(super) fn connect_options(database_url: &str) -> Result<PgConnectOptions, sqlx::Error> {
    let url = parse_database_url(database_url)?;
    // SQLx only warns about unknown parameters before ignoring them. Reject
    // them here so a misspelled TLS policy or server setting cannot disappear
    // when driver logs are suppressed. Keep this list aligned with SQLx's URL
    // parser. SQLx validates connection values; PostgreSQL validates GUCs.
    for (name, _) in url.query_pairs() {
        let supported = matches!(
            name.as_ref(),
            "sslmode"
                | "ssl-mode"
                | "sslrootcert"
                | "ssl-root-cert"
                | "ssl-ca"
                | "sslcert"
                | "ssl-cert"
                | "sslkey"
                | "ssl-key"
                | "statement-cache-capacity"
                | "host"
                | "hostaddr"
                | "port"
                | "dbname"
                | "user"
                | "password"
                | "application_name"
                | "options"
        ) || name
            .strip_prefix("options[")
            .and_then(|name| name.strip_suffix(']'))
            .is_some_and(|name| !name.is_empty());
        if !supported {
            return Err(sqlx::Error::Configuration(
                "PostgreSQL URL contains an unsupported connection parameter".into(),
            ));
        }
    }
    // SQLx can log malformed pgpass lines verbatim.
    // Isolate only its synchronous parsing step; the caller's subscriber is
    // restored before any connection future is created or polled.
    tracing::subscriber::with_default(tracing::subscriber::NoSubscriber::default(), || {
        PgConnectOptions::from_url(&url)
    })
}

fn parse_database_url(database_url: &str) -> Result<Url, sqlx::Error> {
    let url = Url::parse(database_url).map_err(sqlx::Error::config)?;
    // PostgreSQL startup fields are NUL-terminated. Reject their delimiter
    // before SQLx parses or serializes any user-controlled connection field;
    // otherwise a value can inject a different database or startup option.
    // Check both forms because URL normalization strips ASCII tabs/newlines.
    if [database_url, url.as_str()]
        .into_iter()
        .any(|value| percent_decode_str(value).any(|byte| byte == 0))
    {
        return Err(sqlx::Error::config(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "database URL must not contain NUL bytes",
        )));
    }
    if !matches!(url.scheme(), "postgres" | "postgresql") {
        return Err(sqlx::Error::config(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "database URL must use the postgres or postgresql scheme",
        )));
    }
    Ok(url)
}

#[must_use]
/// Redacts passwords, username-only credentials, query values and fragments.
///
/// Routing components and query names are retained. Invalid URLs, unsupported
/// schemes and opaque URLs return a fixed placeholder rather than input text.
pub fn redact_database_url(database_url: &str) -> String {
    const INVALID_URL: &str = "<invalid-postgres-url>";
    let Ok(mut url) = parse_database_url(database_url) else {
        return INVALID_URL.to_owned();
    };
    if !url.has_authority() {
        return INVALID_URL.to_owned();
    }
    let mut redacted = format!("{}://", url.scheme());
    if url.password().is_some() {
        redacted.push_str(url.username());
        redacted.push_str(":****@");
    } else if !url.username().is_empty() {
        redacted.push_str("****@");
    }
    if url.query().is_some() {
        let keys: Vec<_> = url.query_pairs().map(|(key, _)| key.into_owned()).collect();
        url.query_pairs_mut()
            .clear()
            .extend_pairs(keys.iter().map(|key| (key, "****")));
    }
    if url.fragment().is_some() {
        url.set_fragment(Some("****"));
    }
    redacted.push_str(&url[Position::BeforeHost..]);
    redacted
}

#[must_use]
/// Derives a stable advisory-lock key from a namespace and name.
pub fn advisory_lock_key(namespace: &str, name: &str) -> i64 {
    const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
    const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;

    let mut hash = FNV_OFFSET;
    for byte in namespace
        .trim()
        .bytes()
        .chain([0])
        .chain(name.trim().bytes())
    {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(FNV_PRIME);
    }

    i64::from_ne_bytes(hash.to_ne_bytes())
}

#[must_use]
/// Derives the database-scoped lock used by every schema maintenance operation.
///
/// Migrations and destructive resets deliberately share this key so they can
/// never mutate the same database schema concurrently.
pub fn schema_maintenance_advisory_lock_key(database_name: &str) -> i64 {
    advisory_lock_key("footing.postgres.schema-maintenance", database_name)
}