Skip to main content

postgres_mcp/
config.rs

1//! Environment-only configuration: server, API key, limits, toolsets, logging and database connections.
2
3use std::collections::HashMap;
4use std::fmt;
5use std::net::{IpAddr, Ipv4Addr};
6use std::path::PathBuf;
7use std::time::Duration;
8
9use serde_json::{Map, Value};
10use url::Url;
11
12use crate::http_guard::parse_origin;
13use std::sync::Arc;
14
15use rustls::ClientConfig;
16
17use crate::pg::tls::{self, PemSource, SslMode, TlsSources};
18use crate::pg::wire::{AuthPolicy, ConnectConfig};
19
20const DEFAULT_PORT: u16 = 8432;
21const MIN_API_KEY_CHARS: usize = 16;
22const DEFAULT_PG_HOST: &str = "127.0.0.1";
23const DEFAULT_PG_PORT: u16 = 5432;
24const DEFAULT_APP_NAME: &str = "postgres-mcp";
25const DEFAULT_CONNECT_TIMEOUT_SECS: u64 = 10;
26const MAX_CONNECT_TIMEOUT_SECS: u64 = 3_600;
27const DEFAULT_MAX_CONNECTIONS: usize = 4;
28const DEFAULT_STATEMENT_TIMEOUT_MS: u64 = 30_000;
29const DEFAULT_LOCK_TIMEOUT_MS: u64 = 5_000;
30const MAX_NAME_LEN: usize = 63;
31const NAME_RULE: &str = "1 to 63 characters of A-Z, a-z, 0-9, _ or -";
32
33const DATABASE_FIELDS: &[&str] = &[
34    "name",
35    "url",
36    "host",
37    "port",
38    "database",
39    "user",
40    "password",
41    "password_file",
42    "sslmode",
43    "sslrootcert",
44    "sslrootcert_pem",
45    "sslcert",
46    "sslcert_pem",
47    "sslkey",
48    "sslkey_pem",
49    "require_auth",
50    "max_connections",
51    "statement_timeout_ms",
52    "lock_timeout_ms",
53];
54/// Fields that describe the connection itself, so they cannot accompany `url`. Inline PEM fields may.
55const URL_EXCLUSIVE_FIELDS: &[&str] = &[
56    "host",
57    "port",
58    "database",
59    "user",
60    "password",
61    "sslmode",
62    "sslrootcert",
63    "sslcert",
64    "sslkey",
65    "require_auth",
66];
67
68/// Every variable this module reads; `from_env` copies them out of the process environment.
69const ENV_VARS: &[&str] = &[
70    "MCP_HOST",
71    "MCP_PORT",
72    "API_KEY",
73    "API_KEY_FILE",
74    "ALLOWED_ORIGINS",
75    "ALLOWED_HOSTS",
76    "PG_DATABASES",
77    "PG_DATABASES_FILE",
78    "DATABASE_URL",
79    "PG_NAME",
80    "PGHOST",
81    "PGPORT",
82    "PGDATABASE",
83    "PGUSER",
84    "PGPASSWORD",
85    "PGSSLMODE",
86    "PGSSLROOTCERT",
87    "PGSSLCERT",
88    "PGSSLKEY",
89    "PGSSLROOTCERT_PEM",
90    "PGSSLCERT_PEM",
91    "PGSSLKEY_PEM",
92    "PGREQUIREAUTH",
93    "PGAPPNAME",
94    "MAX_ROWS",
95    "MAX_VALUE_BYTES",
96    "MAX_BINARY_PREVIEW_BYTES",
97    "MAX_RESPONSE_BYTES",
98    "MAX_REQUEST_BYTES",
99    "MAX_SQL_BYTES",
100    "MAX_CONCURRENT_REQUESTS",
101    "STATEMENT_TIMEOUT_MS",
102    "LOCK_TIMEOUT_MS",
103    "TOOLSETS",
104    "AUDIT_LOG",
105    "LOG_FORMAT",
106];
107
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct Limits {
110    pub max_rows: usize,
111    pub max_value_bytes: usize,
112    pub max_binary_preview_bytes: usize,
113    pub max_response_bytes: usize,
114    pub max_request_bytes: usize,
115    pub max_sql_bytes: usize,
116    pub max_concurrent_requests: usize,
117}
118
119#[derive(Clone)]
120pub struct DatabaseConfig {
121    pub name: String,
122    pub connect: ConnectConfig,
123    /// Authentication methods the server may use, from `require_auth`.
124    pub auth: AuthPolicy,
125    pub max_connections: usize,
126    pub statement_timeout_ms: u64,
127    pub lock_timeout_ms: u64,
128    /// TLS configuration built by `Config::prepare_tls`; None until then or when sslmode is disable.
129    pub tls: Option<Arc<ClientConfig>>,
130    /// The root and client certificate settings that `prepare_tls` reads; inline PEM stays redacted in Debug.
131    pub tls_sources: TlsSources,
132}
133
134impl fmt::Debug for DatabaseConfig {
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        f.debug_struct("DatabaseConfig")
137            .field("name", &self.name)
138            .field("host", &self.connect.host)
139            .field("port", &self.connect.port)
140            .field("database", &self.connect.database)
141            .field("user", &self.connect.user)
142            .field("ssl_mode", &self.connect.ssl_mode)
143            .finish()
144    }
145}
146
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub struct Toolsets {
149    pub schema: bool,
150    pub monitor: bool,
151    pub logs: bool,
152    pub timescale: bool,
153}
154
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
156pub enum LogFormat {
157    Text,
158    Json,
159}
160
161#[derive(Clone)]
162pub struct Config {
163    pub host: IpAddr,
164    pub port: u16,
165    pub api_key: Option<String>,
166    pub allowed_origins: Vec<String>,
167    pub allowed_hosts: Vec<String>,
168    pub databases: Vec<DatabaseConfig>,
169    pub limits: Limits,
170    pub toolsets: Toolsets,
171    pub audit_log: bool,
172    pub log_format: LogFormat,
173}
174
175impl fmt::Debug for Config {
176    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177        let api_key = if self.api_key.is_some() {
178            "set"
179        } else {
180            "unset"
181        };
182        f.debug_struct("Config")
183            .field("host", &self.host)
184            .field("port", &self.port)
185            .field("api_key", &api_key)
186            .field("allowed_origins", &self.allowed_origins)
187            .field("allowed_hosts", &self.allowed_hosts)
188            .field("databases", &self.databases)
189            .field("limits", &self.limits)
190            .field("toolsets", &self.toolsets)
191            .field("audit_log", &self.audit_log)
192            .field("log_format", &self.log_format)
193            .finish()
194    }
195}
196
197#[derive(Debug, thiserror::Error, PartialEq, Eq)]
198#[error("{0}")]
199pub struct ConfigError(pub String);
200
201/// Defaults for the timeouts that a database entry may override.
202struct Defaults {
203    statement_timeout_ms: u64,
204    lock_timeout_ms: u64,
205}
206
207/// One database's connection settings before the startup parameters are added.
208struct Target {
209    host: String,
210    port: u16,
211    database: String,
212    user: String,
213    password: Option<String>,
214    ssl_mode: SslMode,
215    tls: TlsSources,
216    auth: AuthPolicy,
217    /// `application_name` from a URL query, used when PGAPPNAME is unset.
218    application_name: Option<String>,
219    connect_timeout: Option<Duration>,
220}
221
222impl Config {
223    /// Reads the process environment and validates it; see `from_lookup`.
224    pub fn from_env() -> Result<Config, ConfigError> {
225        let mut vars = HashMap::new();
226        for name in ENV_VARS {
227            match std::env::var(name) {
228                Ok(value) => {
229                    vars.insert(*name, value);
230                }
231                Err(std::env::VarError::NotPresent) => {}
232                Err(std::env::VarError::NotUnicode(_)) => {
233                    return Err(ConfigError(format!("{name}: value is not valid UTF-8")));
234                }
235            }
236        }
237        let mut config = Config::from_lookup(&|name| vars.get(name).cloned())?;
238        config.prepare_tls()?;
239        Ok(config)
240    }
241
242    /// Builds each database's TLS configuration once, so the root file is read at startup, not per connection.
243    /// A failure names the database and the cause, never the file contents.
244    pub fn prepare_tls(&mut self) -> Result<(), ConfigError> {
245        for db in &mut self.databases {
246            if db.connect.ssl_mode == SslMode::Disable {
247                continue;
248            }
249            let config = tls::startup_client_config(db.connect.ssl_mode, &db.tls_sources)
250                .map_err(|reason| ConfigError(format!("{}: {reason}", db.name)))?;
251            db.tls = Some(config);
252        }
253        Ok(())
254    }
255
256    /// Same logic with an injectable variable lookup, for tests. An empty value counts as unset.
257    pub fn from_lookup(get: &dyn Fn(&str) -> Option<String>) -> Result<Config, ConfigError> {
258        let host = match var(get, "MCP_HOST") {
259            Some(raw) => raw.parse::<IpAddr>().map_err(|_| {
260                ConfigError(format!(
261                    "MCP_HOST: \"{raw}\" is not an IP address; use 127.0.0.1 or ::1"
262                ))
263            })?,
264            None => IpAddr::V4(Ipv4Addr::LOCALHOST),
265        };
266        let port = match var(get, "MCP_PORT") {
267            Some(raw) => parse_port("MCP_PORT", &raw)?,
268            None => DEFAULT_PORT,
269        };
270        let defaults = Defaults {
271            statement_timeout_ms: bounded(
272                get,
273                "STATEMENT_TIMEOUT_MS",
274                100,
275                3_600_000,
276                DEFAULT_STATEMENT_TIMEOUT_MS,
277            )?,
278            lock_timeout_ms: bounded(get, "LOCK_TIMEOUT_MS", 10, 600_000, DEFAULT_LOCK_TIMEOUT_MS)?,
279        };
280        Ok(Config {
281            host,
282            port,
283            api_key: api_key(get)?,
284            allowed_origins: allowed_origins(var(get, "ALLOWED_ORIGINS"))?,
285            allowed_hosts: list(var(get, "ALLOWED_HOSTS")),
286            databases: databases(get, &defaults)?,
287            limits: limits(get)?,
288            toolsets: toolsets(var(get, "TOOLSETS"))?,
289            audit_log: audit_log(var(get, "AUDIT_LOG"))?,
290            log_format: log_format(var(get, "LOG_FORMAT"))?,
291        })
292    }
293
294    /// Returns the named database, or the only one when `name` is None.
295    pub fn database(&self, name: Option<&str>) -> Result<&DatabaseConfig, ConfigError> {
296        match name {
297            None => match self.databases.as_slice() {
298                [only] => Ok(only),
299                _ => Err(ConfigError(format!(
300                    "'database' is required: choose one of {}",
301                    self.database_names()
302                ))),
303            },
304            Some(wanted) => self
305                .databases
306                .iter()
307                .find(|d| d.name == wanted)
308                .ok_or_else(|| {
309                    ConfigError(format!(
310                        "unknown database \"{wanted}\": configured databases are {}",
311                        self.database_names()
312                    ))
313                }),
314        }
315    }
316
317    fn database_names(&self) -> String {
318        self.databases
319            .iter()
320            .map(|d| d.name.as_str())
321            .collect::<Vec<_>>()
322            .join(", ")
323    }
324}
325
326/// The variable's value, where an empty value counts as unset.
327fn var(get: &dyn Fn(&str) -> Option<String>, name: &str) -> Option<String> {
328    get(name).filter(|v| !v.is_empty())
329}
330
331/// Reads a numeric variable with bounds, or returns `default` when it is unset.
332fn bounded(
333    get: &dyn Fn(&str) -> Option<String>,
334    name: &str,
335    min: u64,
336    max: u64,
337    default: u64,
338) -> Result<u64, ConfigError> {
339    match var(get, name) {
340        Some(raw) => whole(name, &raw, min, max),
341        None => Ok(default),
342    }
343}
344
345fn whole(name: &str, raw: &str, min: u64, max: u64) -> Result<u64, ConfigError> {
346    match raw.parse::<u64>() {
347        Ok(value) => check_range(name, value, min, max),
348        Err(_) if !raw.is_empty() && raw.bytes().all(|b| b.is_ascii_digit()) => Err(ConfigError(
349            format!("{name}: {raw} is above the maximum {max}"),
350        )),
351        Err(_) => Err(ConfigError(format!(
352            "{name}: \"{raw}\" is not a whole number"
353        ))),
354    }
355}
356
357fn check_range(name: &str, value: u64, min: u64, max: u64) -> Result<u64, ConfigError> {
358    if value < min {
359        Err(ConfigError(format!(
360            "{name}: {value} is below the minimum {min}"
361        )))
362    } else if value > max {
363        Err(ConfigError(format!(
364            "{name}: {value} is above the maximum {max}"
365        )))
366    } else {
367        Ok(value)
368    }
369}
370
371fn parse_port(name: &str, raw: &str) -> Result<u16, ConfigError> {
372    match raw.parse::<u16>() {
373        Ok(port) if port > 0 => Ok(port),
374        _ => Err(ConfigError(format!(
375            "{name}: \"{raw}\" is not a port number"
376        ))),
377    }
378}
379
380/// The TLS settings of one database as written; a file and an inline value of one item stay apart.
381#[derive(Default)]
382struct TlsInputs {
383    root_file: Option<PathBuf>,
384    root_pem: Option<String>,
385    cert_file: Option<PathBuf>,
386    cert_pem: Option<String>,
387    key_file: Option<PathBuf>,
388    key_pem: Option<String>,
389}
390
391/// The setting names that TLS rule errors are reported under.
392struct TlsNames<'a> {
393    sslmode: &'a str,
394    root: &'a str,
395    cert: &'a str,
396    key: &'a str,
397}
398
399/// Applies the TLS rules of one database and returns its sources.
400fn resolve_tls(
401    names: &TlsNames,
402    mode: SslMode,
403    inputs: TlsInputs,
404) -> Result<TlsSources, ConfigError> {
405    let cert_set = inputs.cert_file.is_some() || inputs.cert_pem.is_some();
406    let key_set = inputs.key_file.is_some() || inputs.key_pem.is_some();
407    if cert_set != key_set {
408        let name = if cert_set { names.cert } else { names.key };
409        return Err(ConfigError(format!(
410            "{name}: sslcert and sslkey must be set together"
411        )));
412    }
413    if inputs.root_file.is_some() && inputs.root_pem.is_some() {
414        return Err(ConfigError(format!(
415            "{}: sslrootcert and sslrootcert_pem cannot both be set",
416            names.root
417        )));
418    }
419    if inputs.cert_file.is_some() && inputs.cert_pem.is_some() {
420        return Err(ConfigError(format!(
421            "{}: sslcert and sslcert_pem cannot both be set",
422            names.cert
423        )));
424    }
425    if inputs.key_file.is_some() && inputs.key_pem.is_some() {
426        return Err(ConfigError(format!(
427            "{}: sslkey and sslkey_pem cannot both be set",
428            names.key
429        )));
430    }
431    if cert_set && mode == SslMode::Disable {
432        return Err(ConfigError(format!(
433            "{}: sslcert needs TLS: sslmode must not be disable",
434            names.sslmode
435        )));
436    }
437    let has_root = inputs.root_file.is_some() || inputs.root_pem.is_some();
438    // A root that the mode never checks would look verified in the logs, so the combination is refused.
439    if has_root && matches!(mode, SslMode::Prefer | SslMode::Require) {
440        return Err(ConfigError(format!(
441            "{}: sslrootcert is set but sslmode={} does not verify the server; use sslmode=verify-ca or sslmode=verify-full",
442            names.sslmode,
443            mode.as_str()
444        )));
445    }
446    if has_root && mode == SslMode::Disable {
447        return Err(ConfigError(format!(
448            "{}: sslrootcert is set but sslmode=disable does not use TLS; use sslmode=verify-ca or sslmode=verify-full",
449            names.sslmode
450        )));
451    }
452    // verify-ca checks the chain only, so it needs a root certificate to check against.
453    if mode == SslMode::VerifyCa && !has_root {
454        return Err(ConfigError(format!(
455            "{}: sslmode=verify-ca needs sslrootcert",
456            names.sslmode
457        )));
458    }
459    Ok(TlsSources {
460        root: pick(inputs.root_file, inputs.root_pem),
461        client_cert: pick(inputs.cert_file, inputs.cert_pem),
462        client_key: pick(inputs.key_file, inputs.key_pem),
463    })
464}
465
466/// The one source of an item; both forms set is rejected earlier.
467fn pick(file: Option<PathBuf>, pem: Option<String>) -> Option<PemSource> {
468    match (file, pem) {
469        (Some(path), _) => Some(PemSource::File(path)),
470        (None, Some(text)) => Some(PemSource::Inline(text)),
471        (None, None) => None,
472    }
473}
474
475/// Inline PEM variables; a literal backslash-n becomes a newline, since env values cannot hold one.
476fn env_pem(get: &dyn Fn(&str) -> Option<String>) -> TlsInputs {
477    TlsInputs {
478        root_pem: var(get, "PGSSLROOTCERT_PEM").map(unescape_newlines),
479        cert_pem: var(get, "PGSSLCERT_PEM").map(unescape_newlines),
480        key_pem: var(get, "PGSSLKEY_PEM").map(unescape_newlines),
481        ..TlsInputs::default()
482    }
483}
484
485fn unescape_newlines(raw: String) -> String {
486    raw.replace("\\n", "\n")
487}
488
489/// Parses a `require_auth` comma list; each item names one method the server may use.
490fn parse_require_auth(name: &str, raw: &str) -> Result<AuthPolicy, ConfigError> {
491    let mut policy = AuthPolicy {
492        scram: false,
493        md5: false,
494        password: false,
495        trust: false,
496    };
497    let mut listed = false;
498    for item in raw.split(',').map(str::trim).filter(|s| !s.is_empty()) {
499        listed = true;
500        match item {
501            "scram-sha-256" => policy.scram = true,
502            "md5" => policy.md5 = true,
503            "password" => policy.password = true,
504            "none" => policy.trust = true,
505            other => {
506                return Err(ConfigError(format!(
507                    "{name}: unknown authentication method \"{other}\"; expected scram-sha-256, md5, password or none"
508                )));
509            }
510        }
511    }
512    if !listed {
513        return Err(ConfigError(format!(
514            "{name}: no authentication method is listed"
515        )));
516    }
517    Ok(policy)
518}
519
520fn parse_ssl_mode(name: &str, raw: &str) -> Result<SslMode, ConfigError> {
521    raw.parse::<SslMode>().map_err(|_| {
522        ConfigError(format!(
523            "{name}: invalid ssl mode \"{raw}\"; expected disable, prefer, require, verify-ca or verify-full"
524        ))
525    })
526}
527
528fn read_file(name: &str, path: &str) -> Result<String, ConfigError> {
529    std::fs::read_to_string(path)
530        .map_err(|e| ConfigError(format!("{name}: cannot read {path}: {e}")))
531}
532
533/// Reads a password file, dropping only the trailing line break; an empty file means no password.
534fn read_password_file(name: &str, path: &str) -> Result<Option<String>, ConfigError> {
535    let text = read_file(name, path)?;
536    let password = text.trim_end_matches(['\r', '\n']);
537    Ok((!password.is_empty()).then(|| password.to_owned()))
538}
539
540fn api_key(get: &dyn Fn(&str) -> Option<String>) -> Result<Option<String>, ConfigError> {
541    let (source, key) = match (var(get, "API_KEY"), var(get, "API_KEY_FILE")) {
542        (Some(_), Some(_)) => {
543            return Err(ConfigError(
544                "API_KEY and API_KEY_FILE are both set; set only one".into(),
545            ));
546        }
547        (Some(key), None) => ("API_KEY", key),
548        (None, Some(path)) => (
549            "API_KEY_FILE",
550            read_file("API_KEY_FILE", &path)?.trim().to_owned(),
551        ),
552        (None, None) => return Ok(None),
553    };
554    if key != key.trim() {
555        return Err(ConfigError(format!(
556            "{source}: must not start or end with whitespace"
557        )));
558    }
559    if key.chars().count() < MIN_API_KEY_CHARS {
560        return Err(ConfigError(format!(
561            "{source}: must be at least {MIN_API_KEY_CHARS} characters"
562        )));
563    }
564    Ok(Some(key))
565}
566
567/// Splits a comma list, trimming entries and dropping empty ones.
568fn list(raw: Option<String>) -> Vec<String> {
569    raw.map(|r| {
570        r.split(',')
571            .map(str::trim)
572            .filter(|s| !s.is_empty())
573            .map(str::to_owned)
574            .collect()
575    })
576    .unwrap_or_default()
577}
578
579fn allowed_origins(raw: Option<String>) -> Result<Vec<String>, ConfigError> {
580    let origins = list(raw);
581    if let Some(bad) = origins.iter().find(|o| parse_origin(o).is_none()) {
582        return Err(ConfigError(format!(
583            "ALLOWED_ORIGINS: \"{bad}\" is not an origin of the form scheme://host[:port]"
584        )));
585    }
586    Ok(origins)
587}
588
589fn toolsets(raw: Option<String>) -> Result<Toolsets, ConfigError> {
590    let Some(raw) = raw else {
591        return Ok(Toolsets {
592            schema: true,
593            monitor: true,
594            logs: true,
595            timescale: true,
596        });
597    };
598    let mut toolsets = Toolsets {
599        schema: false,
600        monitor: false,
601        logs: false,
602        timescale: false,
603    };
604    let mut listed = false;
605    for name in raw.split(',').map(str::trim).filter(|s| !s.is_empty()) {
606        listed = true;
607        match name {
608            "schema" => toolsets.schema = true,
609            "monitor" => toolsets.monitor = true,
610            "logs" => toolsets.logs = true,
611            "timescale" => toolsets.timescale = true,
612            "core" => {}
613            "all" => {
614                toolsets.schema = true;
615                toolsets.monitor = true;
616                toolsets.logs = true;
617                toolsets.timescale = true;
618            }
619            other => {
620                return Err(ConfigError(format!(
621                    "TOOLSETS: unknown toolset \"{other}\" (expected schema, monitor, logs, timescale, core or all)"
622                )));
623            }
624        }
625    }
626    if !listed {
627        return Err(ConfigError("TOOLSETS: no toolset is listed".into()));
628    }
629    Ok(toolsets)
630}
631
632fn audit_log(raw: Option<String>) -> Result<bool, ConfigError> {
633    match raw.as_deref() {
634        None | Some("on" | "true" | "1") => Ok(true),
635        Some("off" | "false" | "0") => Ok(false),
636        Some(other) => Err(ConfigError(format!(
637            "AUDIT_LOG: \"{other}\" is not on, off, true, false, 1 or 0"
638        ))),
639    }
640}
641
642fn log_format(raw: Option<String>) -> Result<LogFormat, ConfigError> {
643    match raw.as_deref() {
644        None | Some("text") => Ok(LogFormat::Text),
645        Some("json") => Ok(LogFormat::Json),
646        Some(other) => Err(ConfigError(format!(
647            "LOG_FORMAT: \"{other}\" is not text or json"
648        ))),
649    }
650}
651
652fn limits(get: &dyn Fn(&str) -> Option<String>) -> Result<Limits, ConfigError> {
653    Ok(Limits {
654        max_rows: bounded(get, "MAX_ROWS", 1, 100_000, 1_000)? as usize,
655        max_value_bytes: bounded(get, "MAX_VALUE_BYTES", 64, 1_048_576, 4_096)? as usize,
656        max_binary_preview_bytes: bounded(get, "MAX_BINARY_PREVIEW_BYTES", 16, 65_536, 256)?
657            as usize,
658        max_response_bytes: bounded(get, "MAX_RESPONSE_BYTES", 1_024, 16_777_216, 48_000)? as usize,
659        max_request_bytes: bounded(get, "MAX_REQUEST_BYTES", 1_024, 16_777_216, 1_048_576)?
660            as usize,
661        max_sql_bytes: bounded(get, "MAX_SQL_BYTES", 256, 1_048_576, 102_400)? as usize,
662        max_concurrent_requests: bounded(get, "MAX_CONCURRENT_REQUESTS", 1, 1_024, 16)? as usize,
663    })
664}
665
666fn databases(
667    get: &dyn Fn(&str) -> Option<String>,
668    defaults: &Defaults,
669) -> Result<Vec<DatabaseConfig>, ConfigError> {
670    let app_name = var(get, "PGAPPNAME");
671    let app_name = app_name.as_deref();
672    match (var(get, "PG_DATABASES_FILE"), var(get, "PG_DATABASES")) {
673        (Some(_), Some(_)) => Err(ConfigError(
674            "PG_DATABASES_FILE and PG_DATABASES are both set; set only one".into(),
675        )),
676        (Some(path), None) => {
677            let text = read_file("PG_DATABASES_FILE", &path)?;
678            json_databases("PG_DATABASES_FILE", &text, defaults, app_name)
679        }
680        (None, Some(json)) => json_databases("PG_DATABASES", &json, defaults, app_name),
681        (None, None) => {
682            if let Some(url) = var(get, "DATABASE_URL") {
683                let target = url_target("DATABASE_URL", &url, env_pem(get))?;
684                let name = resolve_name(get, &target.database, "DATABASE_URL")?;
685                Ok(vec![env_database(name, target, defaults, app_name)])
686            } else if let Some(database) = var(get, "PGDATABASE") {
687                Ok(vec![libpq_database(get, database, defaults, app_name)?])
688            } else {
689                Err(ConfigError(
690                    "no database configured: set PG_DATABASES, DATABASE_URL, or PGDATABASE with PGHOST and PGUSER".into(),
691                ))
692            }
693        }
694    }
695}
696
697fn libpq_database(
698    get: &dyn Fn(&str) -> Option<String>,
699    database: String,
700    defaults: &Defaults,
701    app_name: Option<&str>,
702) -> Result<DatabaseConfig, ConfigError> {
703    let name = resolve_name(get, &database, "PGDATABASE")?;
704    let user = var(get, "PGUSER")
705        .ok_or_else(|| ConfigError("PGUSER: required when PGDATABASE is set".into()))?;
706    let ssl_mode = match var(get, "PGSSLMODE") {
707        Some(raw) => parse_ssl_mode("PGSSLMODE", &raw)?,
708        None => SslMode::Prefer,
709    };
710    let inputs = TlsInputs {
711        root_file: var(get, "PGSSLROOTCERT").map(PathBuf::from),
712        cert_file: var(get, "PGSSLCERT").map(PathBuf::from),
713        key_file: var(get, "PGSSLKEY").map(PathBuf::from),
714        ..env_pem(get)
715    };
716    let names = TlsNames {
717        sslmode: "PGSSLMODE",
718        root: "PGSSLROOTCERT",
719        cert: "PGSSLCERT",
720        key: "PGSSLKEY",
721    };
722    let tls = resolve_tls(&names, ssl_mode, inputs)?;
723    let auth = match var(get, "PGREQUIREAUTH") {
724        Some(raw) => parse_require_auth("PGREQUIREAUTH", &raw)?,
725        None => AuthPolicy::default(),
726    };
727    let target = Target {
728        host: var(get, "PGHOST").unwrap_or_else(|| DEFAULT_PG_HOST.to_owned()),
729        port: match var(get, "PGPORT") {
730            Some(raw) => parse_port("PGPORT", &raw)?,
731            None => DEFAULT_PG_PORT,
732        },
733        database,
734        user,
735        password: var(get, "PGPASSWORD"),
736        ssl_mode,
737        tls,
738        auth,
739        application_name: None,
740        connect_timeout: None,
741    };
742    Ok(env_database(name, target, defaults, app_name))
743}
744
745/// The connection name: PG_NAME when set, else the database name, which must itself be a valid name.
746fn resolve_name(
747    get: &dyn Fn(&str) -> Option<String>,
748    database: &str,
749    database_source: &str,
750) -> Result<String, ConfigError> {
751    match var(get, "PG_NAME") {
752        Some(name) if valid_name(&name) => Ok(name),
753        Some(_) => Err(ConfigError(format!("PG_NAME: must be {NAME_RULE}"))),
754        None if valid_name(database) => Ok(database.to_owned()),
755        None => Err(ConfigError(format!(
756            "{database_source}: the database name cannot be used as a connection name; set PG_NAME"
757        ))),
758    }
759}
760
761fn valid_name(name: &str) -> bool {
762    (1..=MAX_NAME_LEN).contains(&name.len())
763        && name
764            .bytes()
765            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
766}
767
768/// A database from the environment forms, which take the default timeouts and pool size.
769fn env_database(
770    name: String,
771    target: Target,
772    defaults: &Defaults,
773    app_name: Option<&str>,
774) -> DatabaseConfig {
775    let auth = target.auth.clone();
776    let tls_sources = target.tls.clone();
777    DatabaseConfig {
778        name,
779        connect: connect_config(target, app_name),
780        auth,
781        max_connections: DEFAULT_MAX_CONNECTIONS,
782        statement_timeout_ms: defaults.statement_timeout_ms,
783        lock_timeout_ms: defaults.lock_timeout_ms,
784        tls: None,
785        tls_sources,
786    }
787}
788
789fn connect_config(target: Target, app_name: Option<&str>) -> ConnectConfig {
790    // A root file is also passed to the wire client, which reads it only without a prepared configuration.
791    let ssl_root_cert = match &target.tls.root {
792        Some(PemSource::File(path)) => Some(path.clone()),
793        _ => None,
794    };
795    let application_name = app_name
796        .map(str::to_owned)
797        .or(target.application_name)
798        .unwrap_or_else(|| DEFAULT_APP_NAME.to_owned());
799    let mut startup_params = vec![("application_name".to_owned(), application_name)];
800    let fixed = [
801        ("DateStyle", "ISO, MDY"),
802        ("IntervalStyle", "iso_8601"),
803        ("TimeZone", "UTC"),
804        ("bytea_output", "hex"),
805        ("extra_float_digits", "1"),
806        ("standard_conforming_strings", "on"),
807        ("default_transaction_read_only", "on"),
808    ];
809    startup_params.extend(
810        fixed
811            .iter()
812            .map(|(key, value)| (key.to_string(), value.to_string())),
813    );
814    ConnectConfig {
815        host: target.host,
816        port: target.port,
817        database: target.database,
818        user: target.user,
819        password: target.password,
820        ssl_mode: target.ssl_mode,
821        ssl_root_cert,
822        connect_timeout: target
823            .connect_timeout
824            .unwrap_or(Duration::from_secs(DEFAULT_CONNECT_TIMEOUT_SECS)),
825        startup_params,
826    }
827}
828
829/// Parses a `postgres://` or `postgresql://` URL, with the inline PEM settings the caller holds. Errors never echo the URL.
830fn url_target(label: &str, raw: &str, pem: TlsInputs) -> Result<Target, ConfigError> {
831    let invalid = || ConfigError(format!("{label}: not a valid postgres:// URL"));
832    let url = Url::parse(raw).map_err(|_| invalid())?;
833    if !matches!(url.scheme(), "postgres" | "postgresql") {
834        return Err(invalid());
835    }
836    if url.username().is_empty() {
837        return Err(ConfigError(format!("{label}: the URL has no user")));
838    }
839    let user = percent_decode(label, url.username())?;
840    let password = url
841        .password()
842        .map(|p| percent_decode(label, p))
843        .transpose()?
844        .filter(|p| !p.is_empty());
845    let database = percent_decode(label, url.path().strip_prefix('/').unwrap_or_default())?;
846    if database.is_empty() {
847        return Err(ConfigError(format!("{label}: the URL has no database")));
848    }
849    let host = match url.host_str() {
850        Some(host) if !host.is_empty() => host
851            .strip_prefix('[')
852            .and_then(|h| h.strip_suffix(']'))
853            .unwrap_or(host)
854            .to_owned(),
855        _ => DEFAULT_PG_HOST.to_owned(),
856    };
857
858    let mut sslmode = None;
859    let mut sslrootcert = None;
860    let mut sslcert = None;
861    let mut sslkey = None;
862    let mut require_auth = None;
863    let mut application_name = None;
864    let mut connect_timeout = None;
865    for (key, value) in url.query_pairs() {
866        match key.as_ref() {
867            "sslmode" => sslmode = Some(value.into_owned()),
868            "sslrootcert" => sslrootcert = Some(PathBuf::from(value.as_ref())),
869            "sslcert" => sslcert = Some(PathBuf::from(value.as_ref())),
870            "sslkey" => sslkey = Some(PathBuf::from(value.as_ref())),
871            "require_auth" => require_auth = Some(value.into_owned()),
872            "application_name" => application_name = Some(value.into_owned()),
873            "connect_timeout" => connect_timeout = Some(value.into_owned()),
874            other => {
875                return Err(ConfigError(format!(
876                    "{label}: unknown URL parameter \"{other}\""
877                )));
878            }
879        }
880    }
881    let ssl_mode = match sslmode {
882        Some(raw) => parse_ssl_mode(&format!("{label}: sslmode"), &raw)?,
883        None => SslMode::Prefer,
884    };
885    let inputs = TlsInputs {
886        root_file: sslrootcert,
887        cert_file: sslcert,
888        key_file: sslkey,
889        ..pem
890    };
891    let names = TlsNames {
892        sslmode: label,
893        root: label,
894        cert: label,
895        key: label,
896    };
897    let tls = resolve_tls(&names, ssl_mode, inputs)?;
898    let auth = match require_auth {
899        Some(raw) => parse_require_auth(&format!("{label}: require_auth"), &raw)?,
900        None => AuthPolicy::default(),
901    };
902    let connect_timeout = connect_timeout
903        .map(|raw| {
904            whole(
905                &format!("{label}: connect_timeout"),
906                &raw,
907                1,
908                MAX_CONNECT_TIMEOUT_SECS,
909            )
910            .map(Duration::from_secs)
911        })
912        .transpose()?;
913    Ok(Target {
914        host,
915        port: url.port().unwrap_or(DEFAULT_PG_PORT),
916        database,
917        user,
918        password,
919        ssl_mode,
920        tls,
921        auth,
922        application_name,
923        connect_timeout,
924    })
925}
926
927/// Decodes `%XX` escapes; a malformed escape is an error that does not echo the input.
928fn percent_decode(label: &str, raw: &str) -> Result<String, ConfigError> {
929    let mut out = Vec::with_capacity(raw.len());
930    let mut bytes = raw.bytes();
931    while let Some(byte) = bytes.next() {
932        if byte != b'%' {
933            out.push(byte);
934            continue;
935        }
936        match (
937            bytes.next().and_then(hex_value),
938            bytes.next().and_then(hex_value),
939        ) {
940            (Some(high), Some(low)) => out.push(high * 16 + low),
941            _ => {
942                return Err(ConfigError(format!(
943                    "{label}: invalid percent-encoding in the URL"
944                )));
945            }
946        }
947    }
948    String::from_utf8(out).map_err(|_| ConfigError(format!("{label}: URL is not valid UTF-8")))
949}
950
951fn hex_value(byte: u8) -> Option<u8> {
952    match byte {
953        b'0'..=b'9' => Some(byte - b'0'),
954        b'a'..=b'f' => Some(byte - b'a' + 10),
955        b'A'..=b'F' => Some(byte - b'A' + 10),
956        _ => None,
957    }
958}
959
960/// Parses the JSON array in PG_DATABASES or PG_DATABASES_FILE.
961fn json_databases(
962    source: &str,
963    text: &str,
964    defaults: &Defaults,
965    app_name: Option<&str>,
966) -> Result<Vec<DatabaseConfig>, ConfigError> {
967    let value: Value = serde_json::from_str(text)
968        .map_err(|e| ConfigError(format!("{source}: not valid JSON: {e}")))?;
969    let Value::Array(entries) = value else {
970        return Err(ConfigError(format!(
971            "{source}: expected a JSON array of database objects"
972        )));
973    };
974    if entries.is_empty() {
975        return Err(ConfigError(format!(
976            "{source}: at least one database is required"
977        )));
978    }
979    let mut databases: Vec<DatabaseConfig> = Vec::with_capacity(entries.len());
980    for (index, entry) in entries.iter().enumerate() {
981        let database = json_database(&format!("{source}[{index}]"), entry, defaults, app_name)?;
982        if databases.iter().any(|d| d.name == database.name) {
983            return Err(ConfigError(format!(
984                "{source}[{index}] (\"{}\"): duplicate database name \"{}\"",
985                database.name, database.name
986            )));
987        }
988        databases.push(database);
989    }
990    Ok(databases)
991}
992
993fn json_database(
994    base: &str,
995    entry: &Value,
996    defaults: &Defaults,
997    app_name: Option<&str>,
998) -> Result<DatabaseConfig, ConfigError> {
999    let Value::Object(map) = entry else {
1000        return Err(ConfigError(format!("{base}: expected an object")));
1001    };
1002    let name = json_string(map, "name", base)?
1003        .ok_or_else(|| ConfigError(format!("{base}: \"name\" is required")))?;
1004    if !valid_name(&name) {
1005        return Err(ConfigError(format!("{base}: \"name\" must be {NAME_RULE}")));
1006    }
1007    let label = format!("{base} (\"{name}\")");
1008    if let Some(key) = map
1009        .keys()
1010        .find(|key| !DATABASE_FIELDS.contains(&key.as_str()))
1011    {
1012        return Err(ConfigError(format!("{label}: unknown field \"{key}\"")));
1013    }
1014    let statement_timeout_ms = json_bounded(map, "statement_timeout_ms", &label, 100, 3_600_000)?
1015        .unwrap_or(defaults.statement_timeout_ms);
1016    let lock_timeout_ms = json_bounded(map, "lock_timeout_ms", &label, 10, 600_000)?
1017        .unwrap_or(defaults.lock_timeout_ms);
1018    let max_connections = json_bounded(map, "max_connections", &label, 1, 64)?
1019        .map_or(DEFAULT_MAX_CONNECTIONS, |n| n as usize);
1020    let target = match json_string(map, "url", &label)? {
1021        Some(url) => {
1022            if let Some(key) = URL_EXCLUSIVE_FIELDS
1023                .iter()
1024                .find(|key| map.contains_key(**key))
1025            {
1026                return Err(ConfigError(format!(
1027                    "{label}: \"{key}\" cannot be combined with \"url\""
1028                )));
1029            }
1030            let mut target = url_target(&label, &url, json_pem(map, &label)?)?;
1031            if let Some(path) = json_string(map, "password_file", &label)? {
1032                target.password = read_password_file(&format!("{label}: password_file"), &path)?;
1033            }
1034            target
1035        }
1036        None => json_discrete_target(map, &label)?,
1037    };
1038    let auth = target.auth.clone();
1039    let tls_sources = target.tls.clone();
1040    Ok(DatabaseConfig {
1041        name,
1042        connect: connect_config(target, app_name),
1043        auth,
1044        max_connections,
1045        statement_timeout_ms,
1046        lock_timeout_ms,
1047        tls: None,
1048        tls_sources,
1049    })
1050}
1051
1052/// The inline PEM fields of a JSON entry; they may accompany `url` as well as the discrete fields.
1053fn json_pem(map: &Map<String, Value>, label: &str) -> Result<TlsInputs, ConfigError> {
1054    Ok(TlsInputs {
1055        root_pem: json_string(map, "sslrootcert_pem", label)?,
1056        cert_pem: json_string(map, "sslcert_pem", label)?,
1057        key_pem: json_string(map, "sslkey_pem", label)?,
1058        ..TlsInputs::default()
1059    })
1060}
1061
1062/// The discrete-field form of a JSON entry; passwords are never echoed in errors.
1063fn json_discrete_target(map: &Map<String, Value>, label: &str) -> Result<Target, ConfigError> {
1064    let database = json_string(map, "database", label)?
1065        .ok_or_else(|| ConfigError(format!("{label}: \"database\" is required")))?;
1066    let user = json_string(map, "user", label)?
1067        .ok_or_else(|| ConfigError(format!("{label}: \"user\" is required")))?;
1068    let password = match (
1069        json_string(map, "password", label)?,
1070        json_string(map, "password_file", label)?,
1071    ) {
1072        (Some(_), Some(_)) => {
1073            return Err(ConfigError(format!(
1074                "{label}: \"password\" and \"password_file\" are both set"
1075            )));
1076        }
1077        (Some(password), None) => Some(password),
1078        (None, Some(path)) => read_password_file(&format!("{label}: password_file"), &path)?,
1079        (None, None) => None,
1080    };
1081    let port = match json_bounded(map, "port", label, 1, 65_535)? {
1082        Some(port) => port as u16,
1083        None => DEFAULT_PG_PORT,
1084    };
1085    let ssl_mode = match json_string(map, "sslmode", label)? {
1086        Some(raw) => parse_ssl_mode(&format!("{label}: sslmode"), &raw)?,
1087        None => SslMode::Prefer,
1088    };
1089    let inputs = TlsInputs {
1090        root_file: json_string(map, "sslrootcert", label)?.map(PathBuf::from),
1091        cert_file: json_string(map, "sslcert", label)?.map(PathBuf::from),
1092        key_file: json_string(map, "sslkey", label)?.map(PathBuf::from),
1093        ..json_pem(map, label)?
1094    };
1095    let names = TlsNames {
1096        sslmode: label,
1097        root: label,
1098        cert: label,
1099        key: label,
1100    };
1101    let tls = resolve_tls(&names, ssl_mode, inputs)?;
1102    let auth = match json_string(map, "require_auth", label)? {
1103        Some(raw) => parse_require_auth(&format!("{label}: require_auth"), &raw)?,
1104        None => AuthPolicy::default(),
1105    };
1106    Ok(Target {
1107        host: json_string(map, "host", label)?.unwrap_or_else(|| DEFAULT_PG_HOST.to_owned()),
1108        port,
1109        database,
1110        user,
1111        password,
1112        ssl_mode,
1113        tls,
1114        auth,
1115        application_name: None,
1116        connect_timeout: None,
1117    })
1118}
1119
1120/// A string field; an empty string counts as absent, and any non-string is an error.
1121fn json_string(
1122    map: &Map<String, Value>,
1123    key: &str,
1124    label: &str,
1125) -> Result<Option<String>, ConfigError> {
1126    match map.get(key) {
1127        None => Ok(None),
1128        Some(Value::String(text)) if !text.is_empty() => Ok(Some(text.clone())),
1129        Some(Value::String(_)) => Ok(None),
1130        Some(_) => Err(ConfigError(format!("{label}: \"{key}\" must be a string"))),
1131    }
1132}
1133
1134/// A whole-number field with bounds, named `label: key` in errors.
1135fn json_bounded(
1136    map: &Map<String, Value>,
1137    key: &str,
1138    label: &str,
1139    min: u64,
1140    max: u64,
1141) -> Result<Option<u64>, ConfigError> {
1142    let Some(value) = map.get(key) else {
1143        return Ok(None);
1144    };
1145    let name = format!("{label}: {key}");
1146    let number = value
1147        .as_u64()
1148        .ok_or_else(|| ConfigError(format!("{name} must be a whole number")))?;
1149    check_range(&name, number, min, max).map(Some)
1150}