1use 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#[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#[derive(Clone, Debug, Serialize, Deserialize)]
26#[non_exhaustive]
27pub struct AppConfig {
28 #[serde(default = "default_db_uri")]
33 pub db_uri: String,
34
35 #[serde(default = "default_db_schemas")]
37 pub db_schemas: Vec<String>,
38
39 pub db_anon_role: Option<String>,
41
42 #[serde(default = "default_pool_size")]
44 pub db_pool_size: u32,
45
46 #[serde(default = "default_pool_timeout")]
48 pub db_pool_timeout: u64,
49
50 #[serde(default = "default_tx_isolation")]
56 pub db_tx_isolation: IsolationLevel,
57
58 #[serde(default = "default_true")]
60 pub db_prepared_statements: bool,
61
62 #[serde(default = "default_extra_search_path")]
70 pub db_extra_search_path: Vec<String>,
71
72 #[serde(default = "default_db_channel")]
74 pub db_channel: String,
75
76 #[serde(default)]
78 pub db_channel_enabled: bool,
79
80 pub db_pre_request: Option<String>,
83
84 pub db_max_rows: Option<i64>,
86
87 #[serde(default)]
92 pub db_aggregates_enabled: bool,
93
94 #[serde(default = "default_host")]
99 pub server_host: String,
100
101 #[serde(default = "default_port")]
103 pub server_port: u16,
104
105 #[serde(default)]
113 pub server_cors_origins: Vec<String>,
114
115 #[serde(default = "default_max_body_size")]
122 pub max_body_size: usize,
123
124 pub server_unix_socket: Option<String>,
126
127 pub admin_server_port: Option<u16>,
129
130 pub jwt_secret: Option<String>,
135
136 #[serde(default)]
138 pub jwt_secret_is_base64: bool,
139
140 pub jwt_aud: Option<String>,
142
143 pub jwt_iss: Option<String>,
146
147 #[serde(default = "default_jwt_role_claim")]
149 pub jwt_role_claim_key: String,
150
151 #[serde(default = "default_true")]
153 pub jwt_cache_enabled: bool,
154
155 #[serde(default = "default_jwt_cache_max")]
160 pub jwt_cache_max_lifetime: u64,
161
162 pub jwt_jwks_url: Option<String>,
169
170 #[serde(default = "default_jwt_jwks_refresh")]
173 pub jwt_jwks_refresh: u64,
174
175 pub hasura_admin_secret: Option<String>,
188
189 pub hasura_unauthorized_role: Option<String>,
193
194 pub openapi_server_proxy_uri: Option<String>,
201
202 #[serde(default = "default_openapi_mode")]
204 pub openapi_mode: OpenApiMode,
205
206 #[serde(default = "default_log_level")]
211 pub log_level: LogLevel,
212
213 #[serde(default)]
222 pub log_format: LogFormat,
223
224 #[serde(default)]
232 pub otel_db_statement: bool,
233
234 #[serde(default)]
239 pub role_settings: HashMap<String, RoleSettings>,
240
241 #[serde(default)]
243 pub app_settings: HashMap<String, String>,
244
245 #[serde(default)]
250 pub graphql_federation: bool,
251
252 #[serde(default)]
254 pub graphql_type_prefix: Option<String>,
255
256 #[serde(default)]
268 pub compat_mode: bool,
269
270 #[serde(default, deserialize_with = "deserialize_sqlstate_patterns")]
281 pub db_errors_verbatim: Vec<String>,
282
283 #[serde(default, deserialize_with = "deserialize_db_error_status")]
297 pub db_error_status: BTreeMap<String, u16>,
298
299 #[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
358fn warn_ignored(var: &str, value: &str, expected: &str) {
362 tracing::warn!("Ignoring {}={:?}: expected {}", var, value, expected);
363}
364
365fn 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
374fn 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
390fn 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
408fn 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
421fn 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
438fn 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
456fn 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
470fn 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
479fn 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
497fn 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 pub fn from_env() -> Self {
523 Self::try_from_env().unwrap_or_else(|error| panic!("{error}"))
524 }
525
526 pub fn try_from_env() -> Result<Self, ConfigError> {
529 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 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 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 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 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 if let Ok(iss) = get("PGRST_JWT_ISS") {
650 if !iss.trim().is_empty() {
651 config.jwt_iss = Some(iss);
652 }
653 }
654 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 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 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 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 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 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 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 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 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 pub fn is_authenticated_role(&self, role: &str) -> bool {
873 Some(role) != self.db_anon_role.as_deref()
874 }
875
876 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 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 pub fn any_verbatim_db_errors(&self) -> bool {
928 self.compat_mode || !self.db_errors_verbatim.is_empty()
929 }
930
931 pub fn unwrap_rpc_results(&self) -> bool {
934 self.compat_mode || self.rpc_unwrap
935 }
936
937 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
946impl 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#[derive(Clone, Debug, Default, Serialize, Deserialize)]
1024#[non_exhaustive]
1025pub struct RoleSettings {
1026 pub isolation_level: Option<IsolationLevel>,
1028 pub statement_timeout: Option<u64>,
1030}
1031
1032#[derive(Clone, Debug, PartialEq, Eq)]
1038pub enum IsolationLevel {
1039 ReadCommitted,
1041 RepeatableRead,
1043 Serializable,
1047}
1048
1049impl IsolationLevel {
1050 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 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 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#[derive(Clone, Debug, PartialEq, Eq)]
1095pub enum OpenApiMode {
1096 Disabled,
1098 FollowPrivileges,
1101 IgnorePrivileges,
1103}
1104
1105impl OpenApiMode {
1106 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 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#[derive(Clone, Debug, PartialEq, Eq)]
1134pub enum LogLevel {
1135 Crit,
1138 Error,
1140 Warn,
1142 Info,
1145 Debug,
1148}
1149
1150impl LogLevel {
1151 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 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 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1190pub enum LogFormat {
1191 #[default]
1194 Text,
1195 Json,
1198}
1199
1200impl LogFormat {
1201 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 pub fn as_config_str(&self) -> &'static str {
1212 match self {
1213 Self::Text => "text",
1214 Self::Json => "json",
1215 }
1216 }
1217}
1218
1219fn 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
1276fn 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 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 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 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", "P0002:", "P0002:abc", "P0002:399", "P0002:600", "P0002:-404", "P001:404", "P0*01:404", "P0002:404:5", "true", "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 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 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 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 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 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 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 assert_eq!(LogLevel::parse_config("trace"), None);
1586 }
1587
1588 #[test]
1589 fn default_log_level_matches_the_documented_one() {
1590 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 static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
1644
1645 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 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 #[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 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 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 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 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 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 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 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 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 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 assert_eq!(OpenApiMode::parse_config("security-definer"), None);
1987 }
1988
1989 #[test]
1990 fn the_config_enums_round_trip_through_json() {
1991 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 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 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 assert_eq!(
2071 with_env(&[("PGRST_JWT_ROLE_CLAIM_KEY", " ")]).jwt_role_claim_key,
2072 AppConfig::default().jwt_role_claim_key
2073 );
2074 }
2075}