Skip to main content

postrust_core/
config.rs

1//! Configuration for Postrust.
2//!
3//! Mirrors PostgREST's configuration options.
4
5use serde::{Deserialize, Serialize};
6use std::collections::{BTreeMap, HashMap};
7
8const EXPECTED_BOOLEAN: &str = "one of: true, false, 1, 0, yes, no, on, off";
9const EXPECTED_SQLSTATES: &str = "true, false, or a comma-separated list of SQLSTATEs \
10     (P0001) and prefixes ending in * (PT*)";
11const EXPECTED_DB_ERROR_STATUS: &str = "a comma-separated list of PATTERN:STATUS, where PATTERN \
12     is a SQLSTATE (P0002) or a prefix ending in * (23*) and STATUS is an HTTP status from \
13     400 to 599, such as P0002:404,23*:422";
14
15/// An environment variable contains a value that cannot be used safely.
16#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
17#[error("invalid value for {variable}: {value:?}; expected {expected}")]
18pub struct ConfigError {
19    variable: &'static str,
20    value: String,
21    expected: &'static str,
22}
23
24/// Main application configuration.
25#[derive(Clone, Debug, Serialize, Deserialize)]
26#[non_exhaustive]
27pub struct AppConfig {
28    // ========================================================================
29    // Database Settings
30    // ========================================================================
31    /// PostgreSQL connection URI
32    #[serde(default = "default_db_uri")]
33    pub db_uri: String,
34
35    /// Schemas to expose via the API
36    #[serde(default = "default_db_schemas")]
37    pub db_schemas: Vec<String>,
38
39    /// Role for unauthenticated requests
40    pub db_anon_role: Option<String>,
41
42    /// Connection pool size
43    #[serde(default = "default_pool_size")]
44    pub db_pool_size: u32,
45
46    /// Pool acquisition timeout in seconds
47    #[serde(default = "default_pool_timeout")]
48    pub db_pool_timeout: u64,
49
50    /// Isolation level for the transaction every request runs in.
51    ///
52    /// `READ COMMITTED` unless set, which is PostgreSQL's own default; a
53    /// stricter level is issued as `SET TRANSACTION ISOLATION LEVEL` on the
54    /// request's transaction.
55    #[serde(default = "default_tx_isolation")]
56    pub db_tx_isolation: IsolationLevel,
57
58    /// Use prepared statements
59    #[serde(default = "default_true")]
60    pub db_prepared_statements: bool,
61
62    /// Schemas added to the `search_path` of every request, after the
63    /// request's own schema.
64    ///
65    /// These are not exposed as API endpoints; they are where a function an
66    /// exposed one calls, or a type it references, is allowed to live. An
67    /// aggregate returning a domain declared elsewhere cannot resolve that
68    /// domain without this. `public` by default, as in PostgREST.
69    #[serde(default = "default_extra_search_path")]
70    pub db_extra_search_path: Vec<String>,
71
72    /// LISTEN/NOTIFY channel for schema reload
73    #[serde(default = "default_db_channel")]
74    pub db_channel: String,
75
76    /// Enable NOTIFY-based schema cache reload
77    #[serde(default)]
78    pub db_channel_enabled: bool,
79
80    /// Function called on the request's transaction before its own query,
81    /// after every setting is applied. Anything it raises aborts the request.
82    pub db_pre_request: Option<String>,
83
84    /// Maximum rows allowed in a response
85    pub db_max_rows: Option<i64>,
86
87    /// Enable aggregate functions in `select`.
88    ///
89    /// Off by default, as in PostgREST: an aggregate over a large table costs
90    /// far more than the request looks like it asks for.
91    #[serde(default)]
92    pub db_aggregates_enabled: bool,
93
94    // ========================================================================
95    // Server Settings
96    // ========================================================================
97    /// Server host to bind
98    #[serde(default = "default_host")]
99    pub server_host: String,
100
101    /// Server port
102    #[serde(default = "default_port")]
103    pub server_port: u16,
104
105    /// Origins allowed by CORS.
106    ///
107    /// Empty means every origin is allowed, which is the default and what
108    /// `PGRST_SERVER_CORS_ORIGINS="*"` selects explicitly. A non-empty list
109    /// restricts the `Access-Control-Allow-Origin` response to exactly those
110    /// origins; anything else gets no CORS headers and is refused by the
111    /// browser.
112    #[serde(default)]
113    pub server_cors_origins: Vec<String>,
114
115    /// Maximum accepted request body, in bytes.
116    ///
117    /// The REST handler applies this when it reads the body; the routes that
118    /// take a body extractor get it through axum's `DefaultBodyLimit`. Before
119    /// this was read, the limit in force was a 10 MiB constant in the request
120    /// handler, whatever the variable said.
121    #[serde(default = "default_max_body_size")]
122    pub max_body_size: usize,
123
124    /// Listen on a Unix domain socket instead of host and port.
125    pub server_unix_socket: Option<String>,
126
127    /// Serve liveness and readiness on a second port of their own.
128    pub admin_server_port: Option<u16>,
129
130    // ========================================================================
131    // JWT Settings
132    // ========================================================================
133    /// JWT secret: an HMAC secret, or a JSON Web Key or JWK Set.
134    pub jwt_secret: Option<String>,
135
136    /// JWT secret as base64
137    #[serde(default)]
138    pub jwt_secret_is_base64: bool,
139
140    /// JWT audience claim to validate
141    pub jwt_aud: Option<String>,
142
143    /// The issuer a token's `iss` claim must name (`PGRST_JWT_ISS`). Unset,
144    /// `iss` is not checked.
145    pub jwt_iss: Option<String>,
146
147    /// JWT claim that contains the role
148    #[serde(default = "default_jwt_role_claim")]
149    pub jwt_role_claim_key: String,
150
151    /// Cache validated tokens, so a repeated token is not verified again.
152    #[serde(default = "default_true")]
153    pub jwt_cache_enabled: bool,
154
155    /// How long a cached validation may be reused, in seconds.
156    ///
157    /// A token's own `exp` bounds this; the cache never answers with a token
158    /// past its expiry. `0` turns the cache off, as in PostgREST.
159    #[serde(default = "default_jwt_cache_max")]
160    pub jwt_cache_max_lifetime: u64,
161
162    /// Where to fetch a JSON Web Key Set from (`PGRST_JWT_JWKS_URL`), and
163    /// keep fetching it as the identity provider rotates its keys.
164    ///
165    /// `https`, or `http` to a loopback host; checked when the server is
166    /// built. With `jwt_secret` also set, a token either one verifies is
167    /// accepted. See docs/authentication.md.
168    pub jwt_jwks_url: Option<String>,
169
170    /// How often to fetch `jwt_jwks_url` again, in seconds, when its response
171    /// carries no `Cache-Control: max-age` (`PGRST_JWT_JWKS_REFRESH`).
172    #[serde(default = "default_jwt_jwks_refresh")]
173    pub jwt_jwks_refresh: u64,
174
175    // ========================================================================
176    // Hasura Authentication
177    // ========================================================================
178    /// The shared secret that authenticates an administrator, and the switch
179    /// that makes `x-hasura-*` headers mean anything at all.
180    ///
181    /// Unset, this server ignores those headers and reads session variables
182    /// only from a verified token -- because honouring a header nothing
183    /// authenticated would let any caller name its own identity, and a policy
184    /// reading a value the caller chose is not a policy. Hasura instead treats
185    /// an unsecured deployment as wholly administrative; the divergence is
186    /// deliberate and is recorded in `postrust_auth::hasura`.
187    pub hasura_admin_secret: Option<String>,
188
189    /// The role a request falls to when nothing authenticated it. Hasura's
190    /// `HASURA_GRAPHQL_UNAUTHORIZED_ROLE`; unset means such a request is
191    /// refused rather than answered as a stranger.
192    pub hasura_unauthorized_role: Option<String>,
193
194    // ========================================================================
195    // OpenAPI Settings
196    // ========================================================================
197    /// Address to advertise in the specification's `servers`, for when the
198    /// server sits behind a reverse proxy and its own address is not the one
199    /// clients use.
200    pub openapi_server_proxy_uri: Option<String>,
201
202    /// OpenAPI mode: disabled, follow-privileges, ignore-privileges
203    #[serde(default = "default_openapi_mode")]
204    pub openapi_mode: OpenApiMode,
205
206    // ========================================================================
207    // Logging Settings
208    // ========================================================================
209    /// Log level: crit, error, warn, info, debug
210    #[serde(default = "default_log_level")]
211    pub log_level: LogLevel,
212
213    /// How log lines are written: `text` for a person at a terminal, `json`
214    /// for a log shipper. JSON lines carry the fields of every span the event
215    /// happened in, so each one names its `request_id` and `trace_id`.
216    ///
217    /// Like `log_level`, the binaries read the variable themselves before the
218    /// configuration is loaded -- the subscriber has to exist first to report
219    /// what loading it rejects -- and this field is that same value, kept for
220    /// anything that reads the configuration afterwards.
221    #[serde(default)]
222    pub log_format: LogFormat,
223
224    /// Record the SQL of a request's main query on its `db.query` span, as
225    /// OpenTelemetry's `db.query.text`.
226    ///
227    /// Off by default. The statement is parameterized, so the values a client
228    /// sent are not in it -- but the table, column and function names are,
229    /// and whatever collects traces may be read by more people than the
230    /// schema is meant for. Formatting it costs nothing while it is off.
231    #[serde(default)]
232    pub otel_db_statement: bool,
233
234    // ========================================================================
235    // Role Settings
236    // ========================================================================
237    /// Per-role settings (isolation level, timeout)
238    #[serde(default)]
239    pub role_settings: HashMap<String, RoleSettings>,
240
241    /// App-level settings to expose via GUC
242    #[serde(default)]
243    pub app_settings: HashMap<String, String>,
244
245    // ========================================================================
246    // GraphQL Settings
247    // ========================================================================
248    /// Expose the GraphQL API as an Apollo Federation subgraph.
249    #[serde(default)]
250    pub graphql_federation: bool,
251
252    /// Namespace applied to generated GraphQL table types and root fields.
253    #[serde(default)]
254    pub graphql_type_prefix: Option<String>,
255
256    // ========================================================================
257    // Compatibility Settings
258    // ========================================================================
259    /// PostgREST compatibility mode.
260    ///
261    /// When enabled, the REST surface is also served at the root (so canonical
262    /// PostgREST paths like `/rpc/<name>` and `/<table>` work in addition to
263    /// the `/api`-prefixed paths), and RPC responses are un-wrapped to match
264    /// PostgREST's shape (bare object/scalar for non-set-returning functions,
265    /// a top-level array for set-returning ones) instead of the array-wrapped,
266    /// function-name-keyed default.
267    #[serde(default)]
268    pub compat_mode: bool,
269
270    /// The SQLSTATEs whose database errors are answered in the database's own
271    /// words -- its code, message, detail and hint -- rather than as
272    /// `"Database error"`.
273    ///
274    /// Each entry is a five-character SQLSTATE (`P0001`) or a prefix ending in
275    /// `*` (`PT*`); `*` alone is every one. Empty by default, because most of
276    /// what PostgreSQL says describes the schema rather than the request: a
277    /// constraint's name, a missing table. What a function raises on purpose
278    /// for the person using the app is the exception worth listing.
279    /// Compatibility mode passes every database error through regardless.
280    #[serde(default, deserialize_with = "deserialize_sqlstate_patterns")]
281    pub db_errors_verbatim: Vec<String>,
282
283    /// The HTTP status a database error is answered with, by SQLSTATE.
284    ///
285    /// Each key is a SQLSTATE (`P0002`) or a prefix ending in `*` (`23*`),
286    /// spelt as in [`db_errors_verbatim`](Self::db_errors_verbatim), and each
287    /// value a status from 400 to 599. The most specific key that matches
288    /// wins: a whole SQLSTATE over any prefix, a longer prefix over a shorter
289    /// one. Empty by default, which leaves the built-in table in charge --
290    /// PostgREST's, except that outside compatibility mode `P0002`
291    /// (`no_data_found`) is a 404 rather than a 500. An entry here wins over
292    /// that in both modes, so `P0002:500` puts PostgREST's answer back.
293    ///
294    /// What a function raises with `sqlstate 'PGRST'` or `PT<nnn>` is a
295    /// request for a status from the schema itself, and is never overridden.
296    #[serde(default, deserialize_with = "deserialize_db_error_status")]
297    pub db_error_status: BTreeMap<String, u16>,
298
299    /// Answer `POST /rpc/<fn>` the way PostgREST does -- a bare object or
300    /// scalar for a function that returns one row, a top-level array for a set
301    /// -- instead of the default `[{"<fn>": ...}]`, without the rest of
302    /// compatibility mode. Off by default. Compatibility mode implies it; ask
303    /// [`unwrap_rpc_results`](Self::unwrap_rpc_results) rather than this field.
304    #[serde(default)]
305    pub rpc_unwrap: bool,
306}
307
308impl Default for AppConfig {
309    fn default() -> Self {
310        Self {
311            db_uri: default_db_uri(),
312            db_schemas: default_db_schemas(),
313            db_anon_role: None,
314            db_pool_size: default_pool_size(),
315            db_pool_timeout: default_pool_timeout(),
316            db_tx_isolation: default_tx_isolation(),
317            db_prepared_statements: true,
318            db_extra_search_path: default_extra_search_path(),
319            db_channel: default_db_channel(),
320            db_channel_enabled: false,
321            db_pre_request: None,
322            db_max_rows: None,
323            db_aggregates_enabled: false,
324            server_host: default_host(),
325            server_port: default_port(),
326            server_cors_origins: Vec::new(),
327            max_body_size: default_max_body_size(),
328            server_unix_socket: None,
329            admin_server_port: None,
330            jwt_secret: None,
331            jwt_secret_is_base64: false,
332            jwt_aud: None,
333            jwt_iss: None,
334            jwt_role_claim_key: default_jwt_role_claim(),
335            jwt_cache_enabled: true,
336            jwt_cache_max_lifetime: default_jwt_cache_max(),
337            jwt_jwks_url: None,
338            jwt_jwks_refresh: default_jwt_jwks_refresh(),
339            hasura_admin_secret: None,
340            hasura_unauthorized_role: None,
341            openapi_server_proxy_uri: None,
342            openapi_mode: OpenApiMode::FollowPrivileges,
343            log_level: default_log_level(),
344            log_format: LogFormat::Text,
345            otel_db_statement: false,
346            role_settings: HashMap::new(),
347            app_settings: HashMap::new(),
348            graphql_federation: false,
349            graphql_type_prefix: None,
350            compat_mode: false,
351            db_errors_verbatim: Vec::new(),
352            db_error_status: BTreeMap::new(),
353            rpc_unwrap: false,
354        }
355    }
356}
357
358/// Say that a variable was set to something unusable, rather than silently
359/// applying the default. A rejected value and an unset one are different
360/// mistakes and the operator can only fix the one they are told about.
361fn warn_ignored(var: &str, value: &str, expected: &str) {
362    tracing::warn!("Ignoring {}={:?}: expected {}", var, value, expected);
363}
364
365/// Parse the explicit spellings accepted for boolean environment variables.
366fn parse_bool(value: &str) -> Option<bool> {
367    match value.trim().to_ascii_lowercase().as_str() {
368        "true" | "1" | "yes" | "on" => Some(true),
369        "false" | "0" | "no" | "off" => Some(false),
370        _ => None,
371    }
372}
373
374/// Report a variable set to a value that cannot be used, and return the
375/// error that stops start-up.
376fn invalid(variable: &'static str, value: &str, expected: &'static str) -> ConfigError {
377    let error = ConfigError {
378        variable,
379        value: value.to_string(),
380        expected,
381    };
382    tracing::warn!("{error}");
383    error
384}
385
386fn env_bool(variable: &'static str, value: &str) -> Result<bool, ConfigError> {
387    parse_bool(value).ok_or_else(|| invalid(variable, value, EXPECTED_BOOLEAN))
388}
389
390/// Parse `PGRST_DB_ERRORS_VERBATIM`: a boolean, where `true` is every
391/// SQLSTATE and `false` none, or a list of SQLSTATEs and `*`-ended prefixes.
392/// Upper-cased, since PostgreSQL reports SQLSTATEs in capitals and `p0001`
393/// is plainly meant as `P0001`. `None` for anything else -- a typo here would
394/// otherwise go on sanitising the very errors it was set to let through.
395fn parse_sqlstate_patterns(value: &str) -> Option<Vec<String>> {
396    match parse_bool(value) {
397        Some(true) => return Some(vec!["*".to_string()]),
398        Some(false) => return Some(Vec::new()),
399        None => {}
400    }
401    value
402        .split(',')
403        .filter(|s| !s.trim().is_empty())
404        .map(parse_sqlstate_pattern)
405        .collect()
406}
407
408/// One SQLSTATE or `*`-ended prefix, upper-cased, or `None` if it is neither.
409/// What `PGRST_DB_ERRORS_VERBATIM` and `PGRST_DB_ERROR_STATUS` both mean by
410/// a pattern, so that a SQLSTATE is spelt one way wherever it is configured.
411fn parse_sqlstate_pattern(pattern: &str) -> Option<String> {
412    let sqlstate_chars = |s: &str| s.chars().all(|c| c.is_ascii_alphanumeric());
413    let s = pattern.trim().to_ascii_uppercase();
414    let valid = match s.strip_suffix('*') {
415        Some(prefix) => prefix.len() < 5 && sqlstate_chars(prefix),
416        None => s.len() == 5 && sqlstate_chars(&s),
417    };
418    valid.then_some(s)
419}
420
421/// Parse `PGRST_DB_ERROR_STATUS`: `PATTERN:STATUS` pairs, comma-separated.
422/// `None` if any pair is malformed or its status is not a 4xx or 5xx, so that
423/// a typo cannot quietly leave an error on the status it was meant to change.
424/// A pattern given twice keeps the later status.
425fn parse_db_error_status(value: &str) -> Option<BTreeMap<String, u16>> {
426    value
427        .split(',')
428        .filter(|s| !s.trim().is_empty())
429        .map(|pair| {
430            let (pattern, status) = pair.split_once(':')?;
431            let status = status.trim().parse::<u16>().ok()?;
432            ((400..=599).contains(&status)).then_some(())?;
433            Some((parse_sqlstate_pattern(pattern)?, status))
434        })
435        .collect()
436}
437
438/// `db_error_status` as configuration spells it: an object from SQLSTATE or
439/// prefix to status, checked as `PGRST_DB_ERROR_STATUS` is.
440fn deserialize_db_error_status<'de, D: serde::Deserializer<'de>>(
441    deserializer: D,
442) -> Result<BTreeMap<String, u16>, D::Error> {
443    let raw = BTreeMap::<String, u16>::deserialize(deserializer)?;
444    let spelt = raw
445        .iter()
446        .map(|(pattern, status)| format!("{pattern}:{status}"))
447        .collect::<Vec<_>>()
448        .join(",");
449    parse_db_error_status(&spelt).ok_or_else(|| {
450        serde::de::Error::custom(format!(
451            "invalid db_error_status {spelt:?}: expected {EXPECTED_DB_ERROR_STATUS}"
452        ))
453    })
454}
455
456/// `db_errors_verbatim` as configuration spells it, checked and upper-cased
457/// as `PGRST_DB_ERRORS_VERBATIM` is: a file that says `["p0001"]` or
458/// `["true"]` means what the variable would.
459fn deserialize_sqlstate_patterns<'de, D: serde::Deserializer<'de>>(
460    deserializer: D,
461) -> Result<Vec<String>, D::Error> {
462    let raw = Vec::<String>::deserialize(deserializer)?.join(",");
463    parse_sqlstate_patterns(&raw).ok_or_else(|| {
464        serde::de::Error::custom(format!(
465            "invalid db_errors_verbatim {raw:?}: expected {EXPECTED_SQLSTATES}"
466        ))
467    })
468}
469
470/// Whether `code` is the SQLSTATE `pattern` names, or begins with the prefix
471/// a `*`-ended one does.
472fn sqlstate_matches(pattern: &str, code: &str) -> bool {
473    match pattern.strip_suffix('*') {
474        Some(prefix) => code.starts_with(prefix),
475        None => pattern == code,
476    }
477}
478
479/// Validate a namespace before it becomes part of generated GraphQL names.
480fn parse_graphql_type_prefix(value: &str) -> Result<Option<String>, &'static str> {
481    let value = value.trim();
482    if value.is_empty() {
483        return Ok(None);
484    }
485
486    let mut chars = value.chars();
487    let valid_first = chars
488        .next()
489        .is_some_and(|c| c == '_' || c.is_ascii_alphabetic());
490    if !valid_first || !chars.all(|c| c == '_' || c.is_ascii_alphanumeric()) {
491        return Err("a GraphQL identifier beginning with a letter or underscore");
492    }
493
494    Ok(Some(value.to_string()))
495}
496
497/// The name an environment variable is looked up by. Windows environment
498/// names are case-insensitive, and `std::env::var("PGRST_DB_URI")` finds
499/// `pgrst_db_uri` there; the names collected for [`AppConfig::try_from_vars`]
500/// are matched exactly, so on Windows they are upper-cased to keep that.
501/// App settings lose nothing by it: their names are lower-cased anyway.
502fn env_name(name: String) -> String {
503    if cfg!(windows) {
504        upper_env_name(name)
505    } else {
506        name
507    }
508}
509
510fn upper_env_name(mut name: String) -> String {
511    name.make_ascii_uppercase();
512    name
513}
514
515impl AppConfig {
516    /// Load configuration from environment variables.
517    ///
518    /// # Panics
519    ///
520    /// Panics if a boolean environment variable has an unsupported value. Use
521    /// [`Self::try_from_env`] when the caller can propagate a startup error.
522    pub fn from_env() -> Self {
523        Self::try_from_env().unwrap_or_else(|error| panic!("{error}"))
524    }
525
526    /// Load configuration from environment variables, rejecting invalid
527    /// boolean values.
528    pub fn try_from_env() -> Result<Self, ConfigError> {
529        // A variable whose name or value is not UTF-8 is skipped, as
530        // `std::env::var` would have refused it.
531        Self::try_from_vars(
532            std::env::vars_os().filter_map(|(k, v)| {
533                Some((env_name(k.into_string().ok()?), v.into_string().ok()?))
534            }),
535        )
536    }
537
538    /// Load configuration from name/value pairs spelled as the environment
539    /// variables are, for a host with no process environment -- a Cloudflare
540    /// Worker reads its bindings instead. Where a name appears twice, the last
541    /// one wins. Names are matched exactly, case included.
542    pub fn try_from_vars<I, K, V>(vars: I) -> Result<Self, ConfigError>
543    where
544        I: IntoIterator<Item = (K, V)>,
545        K: Into<String>,
546        V: Into<String>,
547    {
548        // Kept in the order given as well as looked up by name: the app
549        // settings are found by walking the pairs, and two of them that differ
550        // only in case name the same setting, so which one wins has to depend
551        // on that order and not on a hash.
552        let pairs: Vec<(String, String)> = vars
553            .into_iter()
554            .map(|(k, v)| (k.into(), v.into()))
555            .collect();
556        let vars: HashMap<&str, &str> = pairs
557            .iter()
558            .map(|(k, v)| (k.as_str(), v.as_str()))
559            .collect();
560        let get = |key: &str| vars.get(key).map(|v| v.to_string()).ok_or(());
561        let mut config = Self::default();
562
563        if let Ok(uri) = get("PGRST_DB_URI") {
564            config.db_uri = uri;
565        }
566        if let Ok(uri) = get("DATABASE_URL") {
567            config.db_uri = uri;
568        }
569        if let Ok(schemas) = get("PGRST_DB_SCHEMAS") {
570            config.db_schemas = schemas.split(',').map(|s| s.trim().to_string()).collect();
571        }
572        if let Ok(role) = get("PGRST_DB_ANON_ROLE") {
573            config.db_anon_role = Some(role);
574        }
575        // `PGRST_DB_POOL` is PostgREST's own name; `PGRST_DB_POOL_SIZE` is the
576        // one this project's documentation has always given, including the
577        // production checklist in docs/deployment.md. Only the former was read,
578        // so anybody who followed our own instructions silently kept the
579        // default pool.
580        for var in ["PGRST_DB_POOL", "PGRST_DB_POOL_SIZE"] {
581            if let Ok(size) = get(var) {
582                match size.parse::<u32>() {
583                    Ok(n) if n > 0 => config.db_pool_size = n,
584                    _ => warn_ignored(var, &size, "a positive integer"),
585                }
586            }
587        }
588        if let Ok(secs) = get("PGRST_DB_POOL_TIMEOUT") {
589            match secs.parse::<u64>() {
590                Ok(n) if n > 0 => config.db_pool_timeout = n,
591                _ => warn_ignored("PGRST_DB_POOL_TIMEOUT", &secs, "a positive integer"),
592            }
593        }
594        if let Ok(level) = get("PGRST_DB_TX_ISOLATION") {
595            match IsolationLevel::parse_config(&level) {
596                Some(l) => config.db_tx_isolation = l,
597                None => warn_ignored(
598                    "PGRST_DB_TX_ISOLATION",
599                    &level,
600                    "one of: read committed, repeatable read, serializable",
601                ),
602            }
603        }
604        if let Ok(v) = get("PGRST_DB_EXTRA_SEARCH_PATH") {
605            config.db_extra_search_path = v
606                .split(',')
607                .map(|s| s.trim().to_string())
608                .filter(|s| !s.is_empty())
609                .collect();
610        }
611
612        if let Ok(v) = get("PGRST_DB_AGGREGATES_ENABLED") {
613            config.db_aggregates_enabled = env_bool("PGRST_DB_AGGREGATES_ENABLED", &v)?;
614        }
615        if let Ok(v) = get("PGRST_DB_PREPARED_STATEMENTS") {
616            config.db_prepared_statements = env_bool("PGRST_DB_PREPARED_STATEMENTS", &v)?;
617        }
618        if let Ok(v) = get("PGRST_DB_PRE_REQUEST") {
619            if !v.trim().is_empty() {
620                config.db_pre_request = Some(v.trim().to_string());
621            }
622        }
623        if let Ok(v) = get("PGRST_DB_CHANNEL") {
624            if !v.trim().is_empty() {
625                config.db_channel = v.trim().to_string();
626            }
627        }
628        if let Ok(v) = get("PGRST_DB_CHANNEL_ENABLED") {
629            config.db_channel_enabled = env_bool("PGRST_DB_CHANNEL_ENABLED", &v)?;
630        }
631
632        // `PGRST_DB_MAX_ROWS` mirrors PostgREST's `db-max-rows`. Accept both.
633        for var in ["PGRST_DB_MAX_ROWS", "PGRST_MAX_ROWS"] {
634            if let Ok(max_rows) = get(var) {
635                match max_rows.parse::<i64>() {
636                    Ok(n) if n >= 0 => config.db_max_rows = Some(n),
637                    _ => warn_ignored(var, &max_rows, "a non-negative integer"),
638                }
639            }
640        }
641        if let Ok(secret) = get("PGRST_JWT_SECRET") {
642            config.jwt_secret = Some(secret);
643        }
644        if let Ok(aud) = get("PGRST_JWT_AUD") {
645            config.jwt_aud = Some(aud);
646        }
647        // Not a PostgREST setting. Empty is read as unset rather than as an
648        // issuer nobody can name, which would refuse every token.
649        if let Ok(iss) = get("PGRST_JWT_ISS") {
650            if !iss.trim().is_empty() {
651                config.jwt_iss = Some(iss);
652            }
653        }
654        // Both of these reach the JWT layer already -- `JwtConfig` is built
655        // from them in every binary. Only the environment read was missing, so
656        // a base64 secret was verified against its own text and a role claim
657        // outside `role` was never found.
658        if let Ok(v) = get("PGRST_JWT_SECRET_IS_BASE64") {
659            config.jwt_secret_is_base64 = env_bool("PGRST_JWT_SECRET_IS_BASE64", &v)?;
660        }
661        if let Ok(key) = get("PGRST_JWT_ROLE_CLAIM_KEY") {
662            if !key.trim().is_empty() {
663                config.jwt_role_claim_key = key;
664            }
665        }
666        if let Ok(v) = get("PGRST_JWT_CACHE_ENABLED") {
667            config.jwt_cache_enabled = env_bool("PGRST_JWT_CACHE_ENABLED", &v)?;
668        }
669        // Zero is meaningful here -- it turns the cache off, as in PostgREST --
670        // so unlike the other durations it is not rejected.
671        if let Ok(v) = get("PGRST_JWT_CACHE_MAX_LIFETIME") {
672            match v.parse::<u64>() {
673                Ok(n) => config.jwt_cache_max_lifetime = n,
674                Err(_) => warn_ignored(
675                    "PGRST_JWT_CACHE_MAX_LIFETIME",
676                    &v,
677                    "a non-negative integer number of seconds",
678                ),
679            }
680        }
681        // Not PostgREST settings. Empty is unset, as for the issuer.
682        if let Ok(url) = get("PGRST_JWT_JWKS_URL") {
683            if !url.trim().is_empty() {
684                config.jwt_jwks_url = Some(url.trim().to_string());
685            }
686        }
687        if let Ok(secs) = get("PGRST_JWT_JWKS_REFRESH") {
688            match secs.parse::<u64>() {
689                Ok(n) if n > 0 => config.jwt_jwks_refresh = n,
690                _ => warn_ignored(
691                    "PGRST_JWT_JWKS_REFRESH",
692                    &secs,
693                    "a positive integer number of seconds",
694                ),
695            }
696        }
697        // Hasura's own spelling is accepted beside ours, because a deployment
698        // migrating from it has these in a compose file already and the point
699        // of the mode is that the client does not have to be rewritten. The
700        // `PGRST_` name wins where both are set, on the grounds that it is the
701        // more specific instruction to this server.
702        for var in ["HASURA_GRAPHQL_ADMIN_SECRET", "PGRST_HASURA_ADMIN_SECRET"] {
703            if let Ok(secret) = get(var) {
704                if !secret.is_empty() {
705                    config.hasura_admin_secret = Some(secret);
706                }
707            }
708        }
709        for var in [
710            "HASURA_GRAPHQL_UNAUTHORIZED_ROLE",
711            "PGRST_HASURA_UNAUTHORIZED_ROLE",
712        ] {
713            if let Ok(role) = get(var) {
714                if !role.is_empty() {
715                    config.hasura_unauthorized_role = Some(role);
716                }
717            }
718        }
719        if let Ok(host) = get("PGRST_SERVER_HOST") {
720            config.server_host = host;
721        }
722        if let Ok(port) = get("PGRST_SERVER_PORT") {
723            if let Ok(p) = port.parse() {
724                config.server_port = p;
725            }
726        }
727        if let Ok(port) = get("PORT") {
728            if let Ok(p) = port.parse() {
729                config.server_port = p;
730            }
731        }
732        // A bare `*` is the documented way to spell "any origin", and is the
733        // default. An empty list means the same thing, so a value of only
734        // separators does not accidentally lock everybody out.
735        if let Ok(origins) = get("PGRST_SERVER_CORS_ORIGINS") {
736            config.server_cors_origins = if origins.trim() == "*" {
737                Vec::new()
738            } else {
739                origins
740                    .split(',')
741                    .map(|s| s.trim().to_string())
742                    .filter(|s| !s.is_empty())
743                    .collect()
744            };
745        }
746        if let Ok(bytes) = get("PGRST_MAX_BODY_SIZE") {
747            match bytes.parse::<usize>() {
748                Ok(n) if n > 0 => config.max_body_size = n,
749                _ => warn_ignored("PGRST_MAX_BODY_SIZE", &bytes, "a positive integer"),
750            }
751        }
752        if let Ok(level) = get("PGRST_LOG_LEVEL") {
753            match LogLevel::parse_config(&level) {
754                Some(l) => config.log_level = l,
755                None => warn_ignored(
756                    "PGRST_LOG_LEVEL",
757                    &level,
758                    "one of: crit, error, warn, info, debug",
759                ),
760            }
761        }
762        if let Ok(format) = get("PGRST_LOG_FORMAT") {
763            match LogFormat::parse_config(&format) {
764                Some(f) => config.log_format = f,
765                None => warn_ignored("PGRST_LOG_FORMAT", &format, "one of: text, json"),
766            }
767        }
768        if let Ok(v) = get("PGRST_OTEL_DB_STATEMENT") {
769            config.otel_db_statement = env_bool("PGRST_OTEL_DB_STATEMENT", &v)?;
770        }
771        if let Ok(path) = get("PGRST_SERVER_UNIX_SOCKET") {
772            if !path.trim().is_empty() {
773                config.server_unix_socket = Some(path.trim().to_string());
774            }
775        }
776        if let Ok(port) = get("PGRST_ADMIN_SERVER_PORT") {
777            match port.parse::<u16>() {
778                Ok(p) if p > 0 => config.admin_server_port = Some(p),
779                _ => warn_ignored("PGRST_ADMIN_SERVER_PORT", &port, "a port number"),
780            }
781        }
782        if let Ok(uri) = get("PGRST_OPENAPI_SERVER_PROXY_URI") {
783            if !uri.trim().is_empty() {
784                config.openapi_server_proxy_uri = Some(uri.trim().to_string());
785            }
786        }
787        if let Ok(mode) = get("PGRST_OPENAPI_MODE") {
788            match OpenApiMode::parse_config(&mode) {
789                Some(m) => config.openapi_mode = m,
790                None => warn_ignored(
791                    "PGRST_OPENAPI_MODE",
792                    &mode,
793                    "one of: disabled, follow-privileges, ignore-privileges",
794                ),
795            }
796        }
797
798        // `PGRST_ROLE_SETTINGS` is JSON rather than a per-role variable,
799        // because a PostgreSQL role name may hold characters an environment
800        // variable name cannot.
801        if let Ok(raw) = get("PGRST_ROLE_SETTINGS") {
802            match serde_json::from_str::<HashMap<String, RoleSettings>>(&raw) {
803                Ok(settings) => config.role_settings = settings,
804                Err(e) => warn_ignored(
805                    "PGRST_ROLE_SETTINGS",
806                    &raw,
807                    &format!("a JSON object of role to settings ({e})"),
808                ),
809            }
810        }
811
812        if let Ok(value) = get("PGRST_GRAPHQL_FEDERATION") {
813            config.graphql_federation = env_bool("PGRST_GRAPHQL_FEDERATION", &value)?;
814        }
815        if let Ok(value) = get("PGRST_GRAPHQL_TYPE_PREFIX") {
816            match parse_graphql_type_prefix(&value) {
817                Ok(prefix) => config.graphql_type_prefix = prefix,
818                Err(expected) => warn_ignored("PGRST_GRAPHQL_TYPE_PREFIX", &value, expected),
819            }
820        }
821
822        // `PGRST_APP_SETTINGS_<NAME>` becomes `app.settings.<name>`, which is
823        // where PostgREST puts it and where a policy expects to read it back.
824        // Names that differ only in case (`..._Tenant`, `..._TENANT`) are the
825        // same setting; the one that comes later in the pairs wins, as the
826        // later of two equal names does.
827        for (key, value) in &pairs {
828            if let Some(name) = key.strip_prefix("PGRST_APP_SETTINGS_") {
829                if !name.is_empty() {
830                    config
831                        .app_settings
832                        .insert(name.to_ascii_lowercase(), value.clone());
833                }
834            }
835        }
836        // Accept either the PGRST_-prefixed name (for parity with other options)
837        // or a POSTRUST_-prefixed alias.
838        for var in ["PGRST_COMPAT_MODE", "POSTRUST_COMPAT_MODE"] {
839            if let Ok(v) = get(var) {
840                config.compat_mode = env_bool(var, &v)?;
841            }
842        }
843
844        for var in ["PGRST_RPC_UNWRAP", "POSTRUST_RPC_UNWRAP"] {
845            if let Ok(v) = get(var) {
846                config.rpc_unwrap = env_bool(var, &v)?;
847            }
848        }
849
850        if let Ok(v) = get("PGRST_DB_ERRORS_VERBATIM") {
851            config.db_errors_verbatim = parse_sqlstate_patterns(&v)
852                .ok_or_else(|| invalid("PGRST_DB_ERRORS_VERBATIM", &v, EXPECTED_SQLSTATES))?;
853        }
854
855        // The alias is read second, so it wins where both are set, as it does
856        // for `PGRST_COMPAT_MODE`.
857        for var in ["PGRST_DB_ERROR_STATUS", "POSTRUST_DB_ERROR_STATUS"] {
858            if let Ok(v) = get(var) {
859                config.db_error_status = parse_db_error_status(&v)
860                    .ok_or_else(|| invalid(var, &v, EXPECTED_DB_ERROR_STATUS))?;
861            }
862        }
863
864        Ok(config)
865    }
866
867    /// Whether a request that runs as `role` counts as authenticated, which
868    /// decides whether a missing grant is answered 403 rather than 401.
869    ///
870    /// As PostgREST decides it: the role differs from the configured
871    /// anonymous role, so with no anonymous role configured every role does.
872    pub fn is_authenticated_role(&self, role: &str) -> bool {
873        Some(role) != self.db_anon_role.as_deref()
874    }
875
876    /// Whether `error` is answered in the database's own words: a database
877    /// error, in compatibility mode or with a SQLSTATE
878    /// [`db_errors_verbatim`](Self::db_errors_verbatim) lists.
879    pub fn verbatim_db_error(&self, error: &crate::Error) -> bool {
880        match error {
881            crate::Error::Database(db) => {
882                self.compat_mode
883                    || self
884                        .db_errors_verbatim
885                        .iter()
886                        .any(|pattern| sqlstate_matches(pattern, &db.code))
887            }
888            _ => false,
889        }
890    }
891
892    /// The status this configuration gives a database error, where it has an
893    /// opinion; `None` leaves the built-in table
894    /// ([`DatabaseError::status_code_as`](crate::error::DatabaseError::status_code_as))
895    /// to decide.
896    ///
897    /// An error the schema chose the status of -- `RAISE sqlstate 'PGRST'` or
898    /// `PT<nnn>` -- is never remapped: a function that asked for a 402 meant it.
899    /// Otherwise the most specific entry of
900    /// [`db_error_status`](Self::db_error_status) wins, a whole SQLSTATE over
901    /// any prefix and a longer prefix over a shorter. With none, `P0002`
902    /// (`no_data_found`) is a 404 outside compatibility mode, where a function
903    /// that found nothing is reporting a missing thing, and stays PostgREST's
904    /// 500 inside it.
905    pub fn db_error_status(&self, error: &crate::error::DatabaseError) -> Option<http::StatusCode> {
906        if error.status_is_raised() {
907            return None;
908        }
909        let configured = self
910            .db_error_status
911            .iter()
912            .filter(|(pattern, _)| sqlstate_matches(pattern, &error.code))
913            .max_by_key(|(pattern, _)| match pattern.ends_with('*') {
914                true => pattern.len(),
915                false => usize::MAX,
916            })
917            .and_then(|(_, status)| http::StatusCode::from_u16(*status).ok());
918        match configured {
919            Some(status) => Some(status),
920            None if !self.compat_mode && error.code == "P0002" => Some(http::StatusCode::NOT_FOUND),
921            None => None,
922        }
923    }
924
925    /// Whether any database error can be answered in its own words, which is
926    /// what decides if a custom route's errors need rendering again.
927    pub fn any_verbatim_db_errors(&self) -> bool {
928        self.compat_mode || !self.db_errors_verbatim.is_empty()
929    }
930
931    /// Whether RPC responses are un-nested PostgREST-style: in compatibility
932    /// mode, or with [`rpc_unwrap`](Self::rpc_unwrap) on its own.
933    pub fn unwrap_rpc_results(&self) -> bool {
934        self.compat_mode || self.rpc_unwrap
935    }
936
937    /// Get the default schema (first in the list).
938    pub fn default_schema(&self) -> &str {
939        self.db_schemas
940            .first()
941            .map(|s| s.as_str())
942            .unwrap_or("public")
943    }
944}
945
946// Serialized as the spelling configuration uses, not as the Rust variant name,
947// so that what this writes is what `parse_config` reads back. Deriving
948// `Serialize` here instead emits `"ReadCommitted"`, which then fails to
949// deserialize -- and `Serializable` happens to survive the round trip, which
950// makes the breakage look intermittent rather than total.
951impl Serialize for IsolationLevel {
952    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
953        serializer.serialize_str(self.as_config_str())
954    }
955}
956
957impl<'de> Deserialize<'de> for IsolationLevel {
958    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
959        let raw = String::deserialize(deserializer)?;
960        Self::parse_config(&raw).ok_or_else(|| {
961            serde::de::Error::custom(format!(
962                "unknown isolation level {raw:?}: expected one of \
963                 read committed, repeatable read, serializable"
964            ))
965        })
966    }
967}
968
969impl Serialize for OpenApiMode {
970    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
971        serializer.serialize_str(self.as_config_str())
972    }
973}
974
975impl<'de> Deserialize<'de> for OpenApiMode {
976    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
977        let raw = String::deserialize(deserializer)?;
978        Self::parse_config(&raw).ok_or_else(|| {
979            serde::de::Error::custom(format!(
980                "unknown OpenAPI mode {raw:?}: expected one of \
981                 disabled, follow-privileges, ignore-privileges"
982            ))
983        })
984    }
985}
986
987impl Serialize for LogLevel {
988    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
989        serializer.serialize_str(self.as_config_str())
990    }
991}
992
993impl<'de> Deserialize<'de> for LogLevel {
994    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
995        let raw = String::deserialize(deserializer)?;
996        Self::parse_config(&raw).ok_or_else(|| {
997            serde::de::Error::custom(format!(
998                "unknown log level {raw:?}: expected one of \
999                 crit, error, warn, info, debug"
1000            ))
1001        })
1002    }
1003}
1004
1005impl Serialize for LogFormat {
1006    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1007        serializer.serialize_str(self.as_config_str())
1008    }
1009}
1010
1011impl<'de> Deserialize<'de> for LogFormat {
1012    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1013        let raw = String::deserialize(deserializer)?;
1014        Self::parse_config(&raw).ok_or_else(|| {
1015            serde::de::Error::custom(format!(
1016                "unknown log format {raw:?}: expected one of text, json"
1017            ))
1018        })
1019    }
1020}
1021
1022/// Per-role settings.
1023#[derive(Clone, Debug, Default, Serialize, Deserialize)]
1024#[non_exhaustive]
1025pub struct RoleSettings {
1026    /// Isolation level for this role
1027    pub isolation_level: Option<IsolationLevel>,
1028    /// Statement timeout in milliseconds
1029    pub statement_timeout: Option<u64>,
1030}
1031
1032/// Transaction isolation levels.
1033///
1034/// Deserialized from the spelling the documentation uses (`"serializable"`,
1035/// `"read committed"`), not from the Rust variant name, so a `role_settings`
1036/// entry reads the same as the environment variable.
1037#[derive(Clone, Debug, PartialEq, Eq)]
1038pub enum IsolationLevel {
1039    /// PostgreSQL's default. A statement sees rows committed before it began.
1040    ReadCommitted,
1041    /// Every statement in the transaction sees the same snapshot.
1042    RepeatableRead,
1043    /// As `RepeatableRead`, and concurrent transactions are additionally
1044    /// guaranteed to be equivalent to some serial order. May abort with a
1045    /// serialization failure, which the client is expected to retry.
1046    Serializable,
1047}
1048
1049impl IsolationLevel {
1050    /// The spelling PostgreSQL's `SET TRANSACTION ISOLATION LEVEL` expects.
1051    pub fn to_sql(&self) -> &'static str {
1052        match self {
1053            Self::ReadCommitted => "READ COMMITTED",
1054            Self::RepeatableRead => "REPEATABLE READ",
1055            Self::Serializable => "SERIALIZABLE",
1056        }
1057    }
1058
1059    /// Parse the spelling used in configuration.
1060    ///
1061    /// Case-insensitive, and a hyphen, underscore or space separates the words
1062    /// equally -- the documentation writes `read committed` and an environment
1063    /// file is as likely to carry `read-committed`.
1064    pub fn parse_config(s: &str) -> Option<Self> {
1065        match s
1066            .trim()
1067            .to_ascii_lowercase()
1068            .replace(['-', '_'], " ")
1069            .as_str()
1070        {
1071            "read committed" => Some(Self::ReadCommitted),
1072            "repeatable read" => Some(Self::RepeatableRead),
1073            "serializable" => Some(Self::Serializable),
1074            _ => None,
1075        }
1076    }
1077
1078    /// The inverse of [`parse_config`](Self::parse_config).
1079    pub fn as_config_str(&self) -> &'static str {
1080        match self {
1081            Self::ReadCommitted => "read committed",
1082            Self::RepeatableRead => "repeatable read",
1083            Self::Serializable => "serializable",
1084        }
1085    }
1086}
1087
1088/// OpenAPI generation mode.
1089///
1090/// PostgREST also has a `security-definer` mode, where the specification comes
1091/// from a user-supplied `SECURITY DEFINER` function. There is no configuration
1092/// here for naming that function, so the variant is absent rather than present
1093/// and behaving as one of the others.
1094#[derive(Clone, Debug, PartialEq, Eq)]
1095pub enum OpenApiMode {
1096    /// No OpenAPI document is served.
1097    Disabled,
1098    /// The document describes only what the requesting role may reach, so two
1099    /// roles asking are answered differently.
1100    FollowPrivileges,
1101    /// The document describes the whole exposed schema, whoever is asking.
1102    IgnorePrivileges,
1103}
1104
1105impl OpenApiMode {
1106    /// Parse the spelling used in configuration. Case-insensitive, and a
1107    /// hyphen or an underscore separates the words equally.
1108    pub fn parse_config(s: &str) -> Option<Self> {
1109        match s
1110            .trim()
1111            .to_ascii_lowercase()
1112            .replace(['-', '_'], " ")
1113            .as_str()
1114        {
1115            "disabled" => Some(Self::Disabled),
1116            "follow privileges" => Some(Self::FollowPrivileges),
1117            "ignore privileges" => Some(Self::IgnorePrivileges),
1118            _ => None,
1119        }
1120    }
1121
1122    /// The inverse of [`parse_config`](Self::parse_config).
1123    pub fn as_config_str(&self) -> &'static str {
1124        match self {
1125            Self::Disabled => "disabled",
1126            Self::FollowPrivileges => "follow-privileges",
1127            Self::IgnorePrivileges => "ignore-privileges",
1128        }
1129    }
1130}
1131
1132/// Log levels.
1133#[derive(Clone, Debug, PartialEq, Eq)]
1134pub enum LogLevel {
1135    /// Only failures that stop the server. Mapped onto `ERROR`, which is the
1136    /// least severe level `tracing` offers.
1137    Crit,
1138    /// Requests that failed, and faults that did not stop the server.
1139    Error,
1140    /// Configuration that was ignored, and conditions worth noticing.
1141    Warn,
1142    /// Start-up and schema reloads. Every line logged while a request is
1143    /// being served names its `request_id` and `trace_id`.
1144    Info,
1145    /// One line per request with its status and latency, the generated SQL,
1146    /// and the decisions behind it.
1147    Debug,
1148}
1149
1150impl LogLevel {
1151    /// The `tracing` level this maps onto.
1152    ///
1153    /// `Crit` and `Error` both become `ERROR`: PostgREST distinguishes them
1154    /// and `tracing` has nothing more severe to map `Crit` onto.
1155    pub fn to_tracing(&self) -> tracing::Level {
1156        match self {
1157            Self::Crit | Self::Error => tracing::Level::ERROR,
1158            Self::Warn => tracing::Level::WARN,
1159            Self::Info => tracing::Level::INFO,
1160            Self::Debug => tracing::Level::DEBUG,
1161        }
1162    }
1163
1164    /// Parse the spelling used in configuration. Case-insensitive.
1165    pub fn parse_config(s: &str) -> Option<Self> {
1166        match s.trim().to_ascii_lowercase().as_str() {
1167            "crit" | "critical" => Some(Self::Crit),
1168            "error" => Some(Self::Error),
1169            "warn" | "warning" => Some(Self::Warn),
1170            "info" => Some(Self::Info),
1171            "debug" => Some(Self::Debug),
1172            _ => None,
1173        }
1174    }
1175
1176    /// The inverse of [`parse_config`](Self::parse_config).
1177    pub fn as_config_str(&self) -> &'static str {
1178        match self {
1179            Self::Crit => "crit",
1180            Self::Error => "error",
1181            Self::Warn => "warn",
1182            Self::Info => "info",
1183            Self::Debug => "debug",
1184        }
1185    }
1186}
1187
1188/// How log lines are written.
1189#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1190pub enum LogFormat {
1191    /// One human-readable line per event, with the fields of the spans it
1192    /// happened in. The default.
1193    #[default]
1194    Text,
1195    /// One JSON object per line, for a log shipper: the event's fields, and
1196    /// the current span and every span above it with their fields.
1197    Json,
1198}
1199
1200impl LogFormat {
1201    /// Parse the spelling used in configuration. Case-insensitive.
1202    pub fn parse_config(s: &str) -> Option<Self> {
1203        match s.trim().to_ascii_lowercase().as_str() {
1204            "text" => Some(Self::Text),
1205            "json" => Some(Self::Json),
1206            _ => None,
1207        }
1208    }
1209
1210    /// The inverse of [`parse_config`](Self::parse_config).
1211    pub fn as_config_str(&self) -> &'static str {
1212        match self {
1213            Self::Text => "text",
1214            Self::Json => "json",
1215        }
1216    }
1217}
1218
1219// Default value functions
1220fn default_db_uri() -> String {
1221    "postgresql://localhost/postgres".to_string()
1222}
1223
1224fn default_db_schemas() -> Vec<String> {
1225    vec!["public".to_string()]
1226}
1227
1228fn default_pool_size() -> u32 {
1229    10
1230}
1231
1232fn default_pool_timeout() -> u64 {
1233    10
1234}
1235
1236fn default_tx_isolation() -> IsolationLevel {
1237    IsolationLevel::ReadCommitted
1238}
1239
1240fn default_max_body_size() -> usize {
1241    10 * 1024 * 1024
1242}
1243
1244fn default_extra_search_path() -> Vec<String> {
1245    vec!["public".to_string()]
1246}
1247
1248fn default_db_channel() -> String {
1249    "pgrst".to_string()
1250}
1251
1252fn default_host() -> String {
1253    "127.0.0.1".to_string()
1254}
1255
1256fn default_port() -> u16 {
1257    3000
1258}
1259
1260fn default_jwt_role_claim() -> String {
1261    "role".to_string()
1262}
1263
1264fn default_jwt_cache_max() -> u64 {
1265    3600
1266}
1267
1268fn default_jwt_jwks_refresh() -> u64 {
1269    300
1270}
1271
1272fn default_openapi_mode() -> OpenApiMode {
1273    OpenApiMode::FollowPrivileges
1274}
1275
1276// `info`, not `error`. The documentation has always said `info`, and the
1277// server's own fallback filter is `postrust=info`, so `error` was a third
1278// answer that agreed with neither -- harmless only for as long as nothing
1279// read the field.
1280fn default_log_level() -> LogLevel {
1281    LogLevel::Info
1282}
1283
1284fn default_true() -> bool {
1285    true
1286}
1287
1288#[cfg(test)]
1289mod tests {
1290    use super::*;
1291
1292    #[test]
1293    fn test_default_config() {
1294        let config = AppConfig::default();
1295        assert_eq!(config.server_port, 3000);
1296        assert_eq!(config.db_pool_size, 10);
1297        assert!(config.db_prepared_statements);
1298        assert!(!config.graphql_federation);
1299        assert_eq!(config.graphql_type_prefix, None);
1300    }
1301
1302    #[test]
1303    fn db_errors_verbatim_takes_sqlstates_prefixes_and_booleans() {
1304        let parse = |v: &str| {
1305            AppConfig::try_from_vars([("PGRST_DB_ERRORS_VERBATIM", v)])
1306                .map(|c| c.db_errors_verbatim)
1307        };
1308        assert_eq!(parse("P0001, pt*").unwrap(), ["P0001", "PT*"]);
1309        assert_eq!(parse("true").unwrap(), ["*"]);
1310        assert_eq!(parse("off").unwrap(), Vec::<String>::new());
1311        assert_eq!(parse("").unwrap(), Vec::<String>::new());
1312        for bad in ["P001", "P00011", "P0*01", "P0001*", "4250!"] {
1313            assert!(parse(bad).is_err(), "{bad:?}");
1314        }
1315
1316        // A configuration file is held to the same spellings.
1317        let from_json = |v: &str| {
1318            serde_json::from_str::<AppConfig>(&format!(r#"{{"db_errors_verbatim": {v}}}"#))
1319                .map(|c| c.db_errors_verbatim)
1320        };
1321        assert_eq!(from_json(r#"["p0001", "PT*"]"#).unwrap(), ["P0001", "PT*"]);
1322        assert_eq!(from_json(r#"["true"]"#).unwrap(), ["*"]);
1323        assert!(from_json(r#"["P001"]"#).is_err());
1324    }
1325
1326    #[test]
1327    fn verbatim_db_error_matches_only_listed_database_errors() {
1328        let db = |code: &str| {
1329            crate::Error::Database(crate::error::DatabaseError {
1330                code: code.to_string(),
1331                message: String::new(),
1332                details: None,
1333                hint: None,
1334                constraint: None,
1335                table: None,
1336                column: None,
1337            })
1338        };
1339        let mut config = AppConfig::default();
1340        assert!(!config.verbatim_db_error(&db("P0001")));
1341        assert!(!config.any_verbatim_db_errors());
1342
1343        config.db_errors_verbatim = vec!["P0001".to_string(), "PT*".to_string()];
1344        assert!(config.any_verbatim_db_errors());
1345        assert!(config.verbatim_db_error(&db("P0001")));
1346        assert!(config.verbatim_db_error(&db("PT402")));
1347        assert!(!config.verbatim_db_error(&db("23505")));
1348        assert!(!config.verbatim_db_error(&crate::Error::NotFound("t".to_string())));
1349
1350        config.db_errors_verbatim = vec!["*".to_string()];
1351        assert!(config.verbatim_db_error(&db("42P01")));
1352
1353        config.db_errors_verbatim.clear();
1354        config.compat_mode = true;
1355        assert!(config.verbatim_db_error(&db("23505")));
1356    }
1357
1358    fn database_error(code: &str) -> crate::error::DatabaseError {
1359        crate::error::DatabaseError {
1360            code: code.to_string(),
1361            message: String::new(),
1362            details: None,
1363            hint: None,
1364            constraint: None,
1365            table: None,
1366            column: None,
1367        }
1368    }
1369
1370    #[test]
1371    fn db_error_status_takes_patterns_and_statuses() {
1372        let parse =
1373            |name: &str, v: &str| AppConfig::try_from_vars([(name, v)]).map(|c| c.db_error_status);
1374        let expected: BTreeMap<String, u16> = [("P0002", 404), ("23*", 422)]
1375            .into_iter()
1376            .map(|(p, s)| (p.to_string(), s))
1377            .collect();
1378        // Both names; the pattern spelt as `PGRST_DB_ERRORS_VERBATIM` allows,
1379        // so lower case is upper-cased and spaces are ignored.
1380        for name in ["PGRST_DB_ERROR_STATUS", "POSTRUST_DB_ERROR_STATUS"] {
1381            assert_eq!(
1382                parse(name, "P0002:404,23*:422").unwrap(),
1383                expected,
1384                "{name}"
1385            );
1386            assert_eq!(parse(name, " p0002 : 404 , 23*:422,").unwrap(), expected);
1387            assert!(parse(name, "").unwrap().is_empty());
1388        }
1389        // Where both are set, the alias is read last and wins.
1390        let both = AppConfig::try_from_vars([
1391            ("PGRST_DB_ERROR_STATUS", "P0002:404"),
1392            ("POSTRUST_DB_ERROR_STATUS", "P0002:410"),
1393        ])
1394        .unwrap();
1395        assert_eq!(both.db_error_status["P0002"], 410);
1396
1397        for bad in [
1398            "P0002",       // no status
1399            "P0002:",      // empty status
1400            "P0002:abc",   // not a number
1401            "P0002:399",   // below 400
1402            "P0002:600",   // above 599
1403            "P0002:-404",  // not a status
1404            "P001:404",    // not a SQLSTATE
1405            "P0*01:404",   // `*` only ends a prefix
1406            "P0002:404:5", // two statuses
1407            "true",        // `PGRST_DB_ERRORS_VERBATIM`'s booleans mean nothing here
1408            "P0002:404,xx",
1409        ] {
1410            let error = parse("PGRST_DB_ERROR_STATUS", bad).unwrap_err();
1411            assert!(
1412                error.to_string().contains("PGRST_DB_ERROR_STATUS"),
1413                "{bad:?}"
1414            );
1415            assert!(parse("POSTRUST_DB_ERROR_STATUS", bad).is_err(), "{bad:?}");
1416        }
1417
1418        // A configuration file is held to the same rules.
1419        let from_json = |v: &str| {
1420            serde_json::from_str::<AppConfig>(&format!(r#"{{"db_error_status": {v}}}"#))
1421                .map(|c| c.db_error_status)
1422        };
1423        assert_eq!(
1424            from_json(r#"{"p0002": 404, "23*": 422}"#).unwrap(),
1425            expected
1426        );
1427        assert!(from_json(r#"{"P0002": 200}"#).is_err());
1428        assert!(from_json(r#"{"P001": 404}"#).is_err());
1429        assert!(AppConfig::default().db_error_status.is_empty());
1430    }
1431
1432    #[test]
1433    fn the_most_specific_db_error_status_wins() {
1434        let status = |config: &AppConfig, code: &str| {
1435            config
1436                .db_error_status(&database_error(code))
1437                .map(|s| s.as_u16())
1438        };
1439        let mut config = AppConfig {
1440            db_error_status: [("*", 400), ("23*", 422), ("232*", 423), ("23505", 409)]
1441                .into_iter()
1442                .map(|(p, s)| (p.to_string(), s))
1443                .collect(),
1444            ..AppConfig::default()
1445        };
1446        assert_eq!(
1447            status(&config, "23505"),
1448            Some(409),
1449            "a code beats any prefix"
1450        );
1451        assert_eq!(status(&config, "23503"), Some(422));
1452        assert_eq!(status(&config, "23514"), Some(422));
1453        assert_eq!(status(&config, "23201"), Some(423), "a longer prefix wins");
1454        assert_eq!(status(&config, "42P01"), Some(400), "the catch-all");
1455        // A prefix matches from the start of the code, not anywhere in it.
1456        config.db_error_status = [("2*", 422)]
1457            .into_iter()
1458            .map(|(p, s)| (p.to_string(), s))
1459            .collect();
1460        assert_eq!(status(&config, "P0002"), Some(404));
1461    }
1462
1463    #[test]
1464    fn no_data_found_is_a_404_except_in_compat_mode_or_when_mapped() {
1465        let status = |config: &AppConfig, code: &str| {
1466            config
1467                .db_error_status(&database_error(code))
1468                .map(|s| s.as_u16())
1469        };
1470        let mut config = AppConfig::default();
1471        assert_eq!(status(&config, "P0002"), Some(404));
1472        // Nothing else has an opinion by default.
1473        assert_eq!(status(&config, "P0001"), None);
1474        assert_eq!(status(&config, "23505"), None);
1475
1476        config.compat_mode = true;
1477        assert_eq!(status(&config, "P0002"), None, "PostgREST's 500 stands");
1478
1479        // An explicit mapping wins in both modes, `P0002:500` included.
1480        config.db_error_status.insert("P0002".to_string(), 500);
1481        assert_eq!(status(&config, "P0002"), Some(500));
1482        config.compat_mode = false;
1483        assert_eq!(status(&config, "P0002"), Some(500));
1484        config.db_error_status.insert("P0002".to_string(), 409);
1485        assert_eq!(status(&config, "P0002"), Some(409));
1486    }
1487
1488    #[test]
1489    fn a_status_the_schema_raised_is_not_mapped() {
1490        let config = AppConfig {
1491            db_error_status: [("*", 418)]
1492                .into_iter()
1493                .map(|(p, s)| (p.to_string(), s))
1494                .collect(),
1495            ..AppConfig::default()
1496        };
1497        assert_eq!(config.db_error_status(&database_error("PGRST")), None);
1498        assert_eq!(config.db_error_status(&database_error("PT402")), None);
1499        assert_eq!(
1500            config
1501                .db_error_status(&database_error("42501"))
1502                .map(|s| s.as_u16()),
1503            Some(418)
1504        );
1505    }
1506
1507    #[test]
1508    fn rpc_unwrap_is_read_under_either_name_and_defaults_off() {
1509        let read = |vars: &[(&str, &str)]| {
1510            AppConfig::try_from_vars(vars.iter().map(|(k, v)| (k.to_string(), v.to_string())))
1511        };
1512        assert!(!read(&[]).unwrap().rpc_unwrap);
1513        assert!(read(&[("PGRST_RPC_UNWRAP", "true")]).unwrap().rpc_unwrap);
1514        assert!(read(&[("POSTRUST_RPC_UNWRAP", "1")]).unwrap().rpc_unwrap);
1515        assert!(!read(&[("PGRST_RPC_UNWRAP", "false")]).unwrap().rpc_unwrap);
1516        assert!(read(&[("PGRST_RPC_UNWRAP", "maybe")]).is_err());
1517        assert!(read(&[("POSTRUST_RPC_UNWRAP", "maybe")]).is_err());
1518        let config: AppConfig = serde_json::from_str(r#"{"rpc_unwrap": true}"#).unwrap();
1519        assert!(config.rpc_unwrap);
1520    }
1521
1522    #[test]
1523    fn unwrap_rpc_results_follows_either_setting() {
1524        let mut config = AppConfig::default();
1525        assert!(!config.unwrap_rpc_results());
1526        config.rpc_unwrap = true;
1527        assert!(config.unwrap_rpc_results());
1528        config.rpc_unwrap = false;
1529        config.compat_mode = true;
1530        assert!(config.unwrap_rpc_results());
1531    }
1532
1533    #[test]
1534    fn test_default_schema() {
1535        let mut config = AppConfig::default();
1536        assert_eq!(config.default_schema(), "public");
1537
1538        config.db_schemas = vec!["api".to_string(), "public".to_string()];
1539        assert_eq!(config.default_schema(), "api");
1540    }
1541
1542    #[test]
1543    fn test_isolation_level_sql() {
1544        assert_eq!(IsolationLevel::ReadCommitted.to_sql(), "READ COMMITTED");
1545        assert_eq!(IsolationLevel::Serializable.to_sql(), "SERIALIZABLE");
1546    }
1547
1548    #[test]
1549    fn isolation_level_accepts_the_documented_spellings() {
1550        // The documentation writes `read committed`; an environment file is as
1551        // likely to carry either separator, or capitals.
1552        for s in [
1553            "read committed",
1554            "READ COMMITTED",
1555            "read-committed",
1556            " Read_Committed ",
1557        ] {
1558            assert_eq!(
1559                IsolationLevel::parse_config(s),
1560                Some(IsolationLevel::ReadCommitted),
1561                "{s:?}"
1562            );
1563        }
1564        assert_eq!(
1565            IsolationLevel::parse_config("serializable"),
1566            Some(IsolationLevel::Serializable)
1567        );
1568        assert_eq!(
1569            IsolationLevel::parse_config("repeatable read"),
1570            Some(IsolationLevel::RepeatableRead)
1571        );
1572        // Not a level. Rejected rather than resolved to a default, so the
1573        // caller can say so.
1574        assert_eq!(IsolationLevel::parse_config("dirty read"), None);
1575        assert_eq!(IsolationLevel::parse_config(""), None);
1576    }
1577
1578    #[test]
1579    fn log_level_accepts_the_documented_spellings() {
1580        assert_eq!(LogLevel::parse_config("INFO"), Some(LogLevel::Info));
1581        assert_eq!(LogLevel::parse_config("warning"), Some(LogLevel::Warn));
1582        assert_eq!(LogLevel::parse_config("crit"), Some(LogLevel::Crit));
1583        // `trace` was listed in the documentation and is not a level this
1584        // server has. It is rejected rather than silently read as `debug`.
1585        assert_eq!(LogLevel::parse_config("trace"), None);
1586    }
1587
1588    #[test]
1589    fn default_log_level_matches_the_documented_one() {
1590        // The struct default disagreed with both the documentation and the
1591        // server's own fallback filter for as long as nothing read it.
1592        assert_eq!(AppConfig::default().log_level, LogLevel::Info);
1593    }
1594
1595    #[test]
1596    fn parse_bool_accepts_only_the_supported_spellings() {
1597        for s in ["true", "TRUE", "1", "yes", "on", " On "] {
1598            assert_eq!(parse_bool(s), Some(true), "{s:?}");
1599        }
1600        for s in ["false", "FALSE", "0", "no", "off", " Off "] {
1601            assert_eq!(parse_bool(s), Some(false), "{s:?}");
1602        }
1603        for s in ["", "maybe", "enabled", "2"] {
1604            assert_eq!(parse_bool(s), None, "{s:?}");
1605        }
1606    }
1607
1608    #[test]
1609    fn graphql_federation_configuration_is_read() {
1610        let config = with_env(&[
1611            ("PGRST_GRAPHQL_FEDERATION", "true"),
1612            ("PGRST_GRAPHQL_TYPE_PREFIX", " test "),
1613        ]);
1614
1615        assert!(config.graphql_federation);
1616        assert_eq!(config.graphql_type_prefix.as_deref(), Some("test"));
1617    }
1618
1619    #[test]
1620    fn graphql_federation_accepts_an_explicit_false() {
1621        assert!(!with_env(&[("PGRST_GRAPHQL_FEDERATION", "false")]).graphql_federation);
1622    }
1623
1624    #[test]
1625    fn malformed_graphql_federation_configuration_is_rejected() {
1626        let error = with_env_result(&[("PGRST_GRAPHQL_FEDERATION", "sometimes")])
1627            .expect_err("an invalid boolean must reject the configuration");
1628
1629        assert_eq!(
1630            error.to_string(),
1631            "invalid value for PGRST_GRAPHQL_FEDERATION: \"sometimes\"; expected one of: true, false, 1, 0, yes, no, on, off"
1632        );
1633    }
1634
1635    #[test]
1636    fn an_empty_graphql_prefix_means_unset() {
1637        let config = with_env(&[("PGRST_GRAPHQL_TYPE_PREFIX", "   ")]);
1638
1639        assert_eq!(config.graphql_type_prefix, None);
1640    }
1641
1642    // `from_env` reads process-global state, so these run one at a time.
1643    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
1644
1645    /// Set the given variables, load, then remove them again.
1646    fn with_env(vars: &[(&str, &str)]) -> AppConfig {
1647        with_env_result(vars).expect("test configuration should be valid")
1648    }
1649
1650    fn with_env_result(vars: &[(&str, &str)]) -> Result<AppConfig, ConfigError> {
1651        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
1652        for (k, v) in vars {
1653            std::env::set_var(k, v);
1654        }
1655        let config = AppConfig::try_from_env();
1656        for (k, _) in vars {
1657            std::env::remove_var(k);
1658        }
1659        config
1660    }
1661
1662    #[test]
1663    fn documented_variables_are_read() {
1664        // Every one of these was documented and read by nothing. The features
1665        // behind them already worked -- only the environment read was missing.
1666        let config = with_env(&[
1667            ("PGRST_DB_POOL_SIZE", "42"),
1668            ("PGRST_DB_POOL_TIMEOUT", "7"),
1669            ("PGRST_DB_TX_ISOLATION", "serializable"),
1670            ("PGRST_JWT_SECRET_IS_BASE64", "true"),
1671            ("PGRST_JWT_ROLE_CLAIM_KEY", "user.role"),
1672            ("PGRST_LOG_LEVEL", "warn"),
1673            ("PGRST_MAX_BODY_SIZE", "1024"),
1674            (
1675                "PGRST_SERVER_CORS_ORIGINS",
1676                "https://a.example, https://b.example",
1677            ),
1678        ]);
1679
1680        assert_eq!(config.db_pool_size, 42);
1681        assert_eq!(config.db_pool_timeout, 7);
1682        assert_eq!(config.db_tx_isolation, IsolationLevel::Serializable);
1683        assert!(config.jwt_secret_is_base64);
1684        assert_eq!(config.jwt_role_claim_key, "user.role");
1685        assert_eq!(config.log_level, LogLevel::Warn);
1686        assert_eq!(config.max_body_size, 1024);
1687        assert_eq!(
1688            config.server_cors_origins,
1689            vec![
1690                "https://a.example".to_string(),
1691                "https://b.example".to_string()
1692            ]
1693        );
1694    }
1695
1696    #[test]
1697    fn the_jwt_issuer_is_read_and_an_empty_one_is_unset() {
1698        let read = |value: &str| {
1699            AppConfig::try_from_vars([("PGRST_JWT_ISS", value)])
1700                .unwrap()
1701                .jwt_iss
1702        };
1703        assert_eq!(
1704            read("https://issuer.example").as_deref(),
1705            Some("https://issuer.example")
1706        );
1707        assert_eq!(read("  "), None);
1708        assert_eq!(
1709            AppConfig::try_from_vars(Vec::<(String, String)>::new())
1710                .unwrap()
1711                .jwt_iss,
1712            None
1713        );
1714    }
1715
1716    #[test]
1717    fn the_jwks_url_and_its_refresh_interval_are_read() {
1718        let read = |vars: &[(&str, &str)]| AppConfig::try_from_vars(vars.to_vec()).unwrap();
1719        let config = read(&[
1720            ("PGRST_JWT_JWKS_URL", " https://idp.example/jwks "),
1721            ("PGRST_JWT_JWKS_REFRESH", "60"),
1722        ]);
1723        assert_eq!(
1724            config.jwt_jwks_url.as_deref(),
1725            Some("https://idp.example/jwks")
1726        );
1727        assert_eq!(config.jwt_jwks_refresh, 60);
1728
1729        let defaults = read(&[("PGRST_JWT_JWKS_URL", ""), ("PGRST_JWT_JWKS_REFRESH", "0")]);
1730        assert_eq!(defaults.jwt_jwks_url, None);
1731        assert_eq!(defaults.jwt_jwks_refresh, 300);
1732        assert_eq!(
1733            read(&[("PGRST_JWT_JWKS_REFRESH", "soon")]).jwt_jwks_refresh,
1734            300
1735        );
1736    }
1737
1738    /// As PostgREST: authenticated is any role but the anonymous one, and
1739    /// with no anonymous role configured, every role.
1740    #[test]
1741    fn a_role_other_than_the_anonymous_one_is_authenticated() {
1742        let mut config = AppConfig::default();
1743        assert!(config.is_authenticated_role("web_anon"));
1744        config.db_anon_role = Some("web_anon".to_string());
1745        assert!(!config.is_authenticated_role("web_anon"));
1746        assert!(config.is_authenticated_role("web_user"));
1747    }
1748
1749    #[test]
1750    fn variables_can_come_from_somewhere_other_than_the_environment() {
1751        // What a Cloudflare Worker does with its bindings: nothing here is in
1752        // the process environment, and the app settings, which are found by
1753        // prefix rather than by name, arrive all the same.
1754        let config = AppConfig::try_from_vars([
1755            ("PGRST_DB_SCHEMAS", "api, extra"),
1756            ("PGRST_DB_ANON_ROLE", "web_anon"),
1757            ("PGRST_JWT_SECRET", "a-secret"),
1758            ("PGRST_DB_MAX_ROWS", "100"),
1759            ("PGRST_APP_SETTINGS_Tenant", "acme"),
1760        ])
1761        .unwrap();
1762
1763        assert_eq!(config.db_schemas, ["api", "extra"]);
1764        assert_eq!(config.db_anon_role.as_deref(), Some("web_anon"));
1765        assert_eq!(config.jwt_secret.as_deref(), Some("a-secret"));
1766        assert_eq!(config.db_max_rows, Some(100));
1767        assert_eq!(
1768            config.app_settings.get("tenant").map(String::as_str),
1769            Some("acme")
1770        );
1771
1772        let refused = AppConfig::try_from_vars([("PGRST_DB_AGGREGATES_ENABLED", "maybe")]);
1773        assert!(refused.is_err());
1774    }
1775
1776    #[test]
1777    fn app_settings_differing_only_in_case_take_the_later_value() {
1778        // Both name `app.settings.tenant`. Run it a few times: with the pairs
1779        // in a hash map the winner changed from one run to the next.
1780        for _ in 0..16 {
1781            let config = AppConfig::try_from_vars([
1782                ("PGRST_APP_SETTINGS_Tenant", "first"),
1783                ("PGRST_APP_SETTINGS_TENANT", "second"),
1784                ("PGRST_APP_SETTINGS_tenant", "third"),
1785            ])
1786            .unwrap();
1787            assert_eq!(
1788                config.app_settings.get("tenant").map(String::as_str),
1789                Some("third")
1790            );
1791
1792            let config = AppConfig::try_from_vars([
1793                ("PGRST_APP_SETTINGS_tenant", "third"),
1794                ("PGRST_APP_SETTINGS_TENANT", "second"),
1795            ])
1796            .unwrap();
1797            assert_eq!(
1798                config.app_settings.get("tenant").map(String::as_str),
1799                Some("second")
1800            );
1801        }
1802    }
1803
1804    #[test]
1805    fn windows_environment_names_are_matched_whatever_their_case() {
1806        // What `env_name` does on Windows, where `std::env::var` ignored case.
1807        let config = AppConfig::try_from_vars([
1808            (upper_env_name("pgrst_db_schemas".into()), "api"),
1809            (upper_env_name("Pgrst_App_Settings_Tenant".into()), "acme"),
1810        ])
1811        .unwrap();
1812        assert_eq!(config.db_schemas, ["api"]);
1813        assert_eq!(
1814            config.app_settings.get("tenant").map(String::as_str),
1815            Some("acme")
1816        );
1817        assert_eq!(env_name("PGRST_DB_URI".into()), "PGRST_DB_URI");
1818        assert_eq!(
1819            env_name("pgrst_db_uri".into()) == "PGRST_DB_URI",
1820            cfg!(windows)
1821        );
1822    }
1823
1824    #[test]
1825    fn pool_size_accepts_postgrests_own_name() {
1826        assert_eq!(with_env(&[("PGRST_DB_POOL", "5")]).db_pool_size, 5);
1827    }
1828
1829    #[test]
1830    fn a_star_origin_means_any_origin() {
1831        // Empty is how "any" is carried, so `*` must not become a literal
1832        // origin that matches nothing.
1833        assert!(with_env(&[("PGRST_SERVER_CORS_ORIGINS", "*")])
1834            .server_cors_origins
1835            .is_empty());
1836        assert!(with_env(&[("PGRST_SERVER_CORS_ORIGINS", " , ")])
1837            .server_cors_origins
1838            .is_empty());
1839    }
1840
1841    #[test]
1842    fn an_unusable_value_leaves_the_default() {
1843        let config = with_env(&[
1844            ("PGRST_DB_POOL_SIZE", "lots"),
1845            ("PGRST_DB_POOL_TIMEOUT", "0"),
1846            ("PGRST_MAX_BODY_SIZE", "-1"),
1847            ("PGRST_DB_TX_ISOLATION", "dirty read"),
1848            ("PGRST_LOG_LEVEL", "shout"),
1849        ]);
1850
1851        let d = AppConfig::default();
1852        assert_eq!(config.db_pool_size, d.db_pool_size);
1853        assert_eq!(config.db_pool_timeout, d.db_pool_timeout);
1854        assert_eq!(config.max_body_size, d.max_body_size);
1855        assert_eq!(config.db_tx_isolation, d.db_tx_isolation);
1856        assert_eq!(config.log_level, d.log_level);
1857    }
1858
1859    #[test]
1860    fn the_formerly_dead_fields_are_read() {
1861        // Every one of these was a public field that nothing set and nothing
1862        // consumed.
1863        let config = with_env(&[
1864            ("PGRST_DB_PREPARED_STATEMENTS", "false"),
1865            ("PGRST_DB_PRE_REQUEST", "auth.check"),
1866            ("PGRST_DB_CHANNEL", "my_channel"),
1867            ("PGRST_DB_CHANNEL_ENABLED", "yes"),
1868            ("PGRST_JWT_CACHE_ENABLED", "false"),
1869            ("PGRST_JWT_CACHE_MAX_LIFETIME", "60"),
1870            ("PGRST_SERVER_UNIX_SOCKET", "/tmp/postrust.sock"),
1871            ("PGRST_ADMIN_SERVER_PORT", "3001"),
1872            ("PGRST_OPENAPI_SERVER_PROXY_URI", "https://api.example.com"),
1873            ("PGRST_OPENAPI_MODE", "ignore-privileges"),
1874        ]);
1875
1876        assert!(!config.db_prepared_statements);
1877        assert_eq!(config.db_pre_request.as_deref(), Some("auth.check"));
1878        assert_eq!(config.db_channel, "my_channel");
1879        assert!(config.db_channel_enabled);
1880        assert!(!config.jwt_cache_enabled);
1881        assert_eq!(config.jwt_cache_max_lifetime, 60);
1882        assert_eq!(
1883            config.server_unix_socket.as_deref(),
1884            Some("/tmp/postrust.sock")
1885        );
1886        assert_eq!(config.admin_server_port, Some(3001));
1887        assert_eq!(
1888            config.openapi_server_proxy_uri.as_deref(),
1889            Some("https://api.example.com")
1890        );
1891        assert_eq!(config.openapi_mode, OpenApiMode::IgnorePrivileges);
1892    }
1893
1894    #[test]
1895    fn tracing_settings_are_read() {
1896        let d = AppConfig::default();
1897        assert_eq!(d.log_format, LogFormat::Text);
1898        assert!(!d.otel_db_statement);
1899
1900        let config = with_env(&[
1901            ("PGRST_LOG_FORMAT", "JSON"),
1902            ("PGRST_OTEL_DB_STATEMENT", "on"),
1903        ]);
1904        assert_eq!(config.log_format, LogFormat::Json);
1905        assert!(config.otel_db_statement);
1906
1907        // A format nobody can write is ignored with a warning; a boolean that
1908        // is not one fails, as every boolean setting does.
1909        assert_eq!(
1910            with_env(&[("PGRST_LOG_FORMAT", "yaml")]).log_format,
1911            LogFormat::Text
1912        );
1913        assert!(with_env_result(&[("PGRST_OTEL_DB_STATEMENT", "maybe")]).is_err());
1914    }
1915
1916    #[test]
1917    fn a_zero_jwt_cache_lifetime_is_kept_because_it_turns_the_cache_off() {
1918        // Unlike the other durations, 0 is a meaningful value here and must
1919        // not be rejected as unusable.
1920        assert_eq!(
1921            with_env(&[("PGRST_JWT_CACHE_MAX_LIFETIME", "0")]).jwt_cache_max_lifetime,
1922            0
1923        );
1924    }
1925
1926    #[test]
1927    fn app_settings_come_from_a_prefix() {
1928        let config = with_env(&[
1929            ("PGRST_APP_SETTINGS_JWT_LIFETIME", "3600"),
1930            ("PGRST_APP_SETTINGS_TenantName", "acme"),
1931        ]);
1932        // Lower-cased, because that is the name a policy reads back with
1933        // `current_setting('app.settings.<name>')`.
1934        assert_eq!(
1935            config.app_settings.get("jwt_lifetime").map(String::as_str),
1936            Some("3600")
1937        );
1938        assert_eq!(
1939            config.app_settings.get("tenantname").map(String::as_str),
1940            Some("acme")
1941        );
1942    }
1943
1944    #[test]
1945    fn role_settings_parse_from_json_using_the_documented_spellings() {
1946        let config = with_env(&[(
1947            "PGRST_ROLE_SETTINGS",
1948            r#"{"web_user":{"isolation_level":"serializable","statement_timeout":5000}}"#,
1949        )]);
1950        let web_user = config.role_settings.get("web_user").expect("role present");
1951        assert_eq!(web_user.isolation_level, Some(IsolationLevel::Serializable));
1952        assert_eq!(web_user.statement_timeout, Some(5000));
1953    }
1954
1955    #[test]
1956    fn unparseable_role_settings_leave_the_map_empty() {
1957        assert!(with_env(&[("PGRST_ROLE_SETTINGS", "{not json")])
1958            .role_settings
1959            .is_empty());
1960        // A valid JSON object naming a level that does not exist is refused
1961        // as a whole rather than half-applied.
1962        assert!(with_env(&[(
1963            "PGRST_ROLE_SETTINGS",
1964            r#"{"r":{"isolation_level":"dirty"}}"#
1965        )])
1966        .role_settings
1967        .is_empty());
1968    }
1969
1970    #[test]
1971    fn openapi_mode_accepts_the_documented_spellings() {
1972        assert_eq!(
1973            OpenApiMode::parse_config("follow-privileges"),
1974            Some(OpenApiMode::FollowPrivileges)
1975        );
1976        assert_eq!(
1977            OpenApiMode::parse_config("IGNORE_PRIVILEGES"),
1978            Some(OpenApiMode::IgnorePrivileges)
1979        );
1980        assert_eq!(
1981            OpenApiMode::parse_config("disabled"),
1982            Some(OpenApiMode::Disabled)
1983        );
1984        // PostgREST's fourth mode needs a function this server has no
1985        // configuration for, so it is not accepted rather than aliased.
1986        assert_eq!(OpenApiMode::parse_config("security-definer"), None);
1987    }
1988
1989    #[test]
1990    fn the_config_enums_round_trip_through_json() {
1991        // Deriving `Serialize` emits the Rust variant name while the
1992        // hand-written `Deserialize` reads the configuration spelling, so a
1993        // value this type writes could not be read back. `Serializable`
1994        // survived by coincidence -- its variant name lowercases to the
1995        // accepted spelling -- which made the breakage look intermittent.
1996        for level in [
1997            IsolationLevel::ReadCommitted,
1998            IsolationLevel::RepeatableRead,
1999            IsolationLevel::Serializable,
2000        ] {
2001            let json = serde_json::to_string(&level).unwrap();
2002            let back: IsolationLevel = serde_json::from_str(&json).unwrap();
2003            assert_eq!(back, level, "{json}");
2004        }
2005
2006        for mode in [
2007            OpenApiMode::Disabled,
2008            OpenApiMode::FollowPrivileges,
2009            OpenApiMode::IgnorePrivileges,
2010        ] {
2011            let json = serde_json::to_string(&mode).unwrap();
2012            assert_eq!(serde_json::from_str::<OpenApiMode>(&json).unwrap(), mode);
2013        }
2014
2015        for level in [
2016            LogLevel::Crit,
2017            LogLevel::Error,
2018            LogLevel::Warn,
2019            LogLevel::Info,
2020            LogLevel::Debug,
2021        ] {
2022            let json = serde_json::to_string(&level).unwrap();
2023            assert_eq!(serde_json::from_str::<LogLevel>(&json).unwrap(), level);
2024        }
2025    }
2026
2027    #[test]
2028    fn a_whole_config_round_trips_through_json() {
2029        // The struct derives both, which invites persisting it.
2030        let mut config = AppConfig::default();
2031        config.role_settings.insert(
2032            "web_user".to_string(),
2033            RoleSettings {
2034                isolation_level: Some(IsolationLevel::RepeatableRead),
2035                statement_timeout: Some(5000),
2036            },
2037        );
2038
2039        let json = serde_json::to_string(&config).unwrap();
2040        let back: AppConfig = serde_json::from_str(&json).expect("config should round trip");
2041
2042        assert_eq!(back.db_tx_isolation, config.db_tx_isolation);
2043        assert_eq!(back.log_level, config.log_level);
2044        assert_eq!(back.openapi_mode, config.openapi_mode);
2045        assert_eq!(
2046            back.role_settings["web_user"].isolation_level,
2047            Some(IsolationLevel::RepeatableRead)
2048        );
2049    }
2050
2051    #[test]
2052    fn the_serialized_spelling_is_the_configuration_spelling() {
2053        // Not the Rust variant name: what is written should be what an
2054        // operator could paste into the environment.
2055        assert_eq!(
2056            serde_json::to_string(&IsolationLevel::ReadCommitted).unwrap(),
2057            "\"read committed\""
2058        );
2059        assert_eq!(
2060            serde_json::to_string(&OpenApiMode::FollowPrivileges).unwrap(),
2061            "\"follow-privileges\""
2062        );
2063        assert_eq!(serde_json::to_string(&LogLevel::Warn).unwrap(), "\"warn\"");
2064    }
2065
2066    #[test]
2067    fn an_empty_role_claim_key_is_not_accepted() {
2068        // An empty key would look up nothing and every request would fall to
2069        // the anonymous role.
2070        assert_eq!(
2071            with_env(&[("PGRST_JWT_ROLE_CLAIM_KEY", "  ")]).jwt_role_claim_key,
2072            AppConfig::default().jwt_role_claim_key
2073        );
2074    }
2075}