1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
//! Configuration for Postrust.
//!
//! Mirrors PostgREST's configuration options.
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
const EXPECTED_BOOLEAN: &str = "one of: true, false, 1, 0, yes, no, on, off";
/// An environment variable contains a value that cannot be used safely.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[error("invalid value for {variable}: {value:?}; expected {expected}")]
pub struct ConfigError {
variable: &'static str,
value: String,
expected: &'static str,
}
/// Main application configuration.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AppConfig {
// ========================================================================
// Database Settings
// ========================================================================
/// PostgreSQL connection URI
#[serde(default = "default_db_uri")]
pub db_uri: String,
/// Schemas to expose via the API
#[serde(default = "default_db_schemas")]
pub db_schemas: Vec<String>,
/// Role for unauthenticated requests
pub db_anon_role: Option<String>,
/// Connection pool size
#[serde(default = "default_pool_size")]
pub db_pool_size: u32,
/// Pool acquisition timeout in seconds
#[serde(default = "default_pool_timeout")]
pub db_pool_timeout: u64,
/// Isolation level for the transaction every request runs in.
///
/// `READ COMMITTED` unless set, which is PostgreSQL's own default; a
/// stricter level is issued as `SET TRANSACTION ISOLATION LEVEL` on the
/// request's transaction.
#[serde(default = "default_tx_isolation")]
pub db_tx_isolation: IsolationLevel,
/// Use prepared statements
#[serde(default = "default_true")]
pub db_prepared_statements: bool,
/// Schemas added to the `search_path` of every request, after the
/// request's own schema.
///
/// These are not exposed as API endpoints; they are where a function an
/// exposed one calls, or a type it references, is allowed to live. An
/// aggregate returning a domain declared elsewhere cannot resolve that
/// domain without this. `public` by default, as in PostgREST.
#[serde(default = "default_extra_search_path")]
pub db_extra_search_path: Vec<String>,
/// LISTEN/NOTIFY channel for schema reload
#[serde(default = "default_db_channel")]
pub db_channel: String,
/// Enable NOTIFY-based schema cache reload
#[serde(default)]
pub db_channel_enabled: bool,
/// Function called on the request's transaction before its own query,
/// after every setting is applied. Anything it raises aborts the request.
pub db_pre_request: Option<String>,
/// Maximum rows allowed in a response
pub db_max_rows: Option<i64>,
/// Enable aggregate functions in `select`.
///
/// Off by default, as in PostgREST: an aggregate over a large table costs
/// far more than the request looks like it asks for.
#[serde(default)]
pub db_aggregates_enabled: bool,
// ========================================================================
// Server Settings
// ========================================================================
/// Server host to bind
#[serde(default = "default_host")]
pub server_host: String,
/// Server port
#[serde(default = "default_port")]
pub server_port: u16,
/// Origins allowed by CORS.
///
/// Empty means every origin is allowed, which is the default and what
/// `PGRST_SERVER_CORS_ORIGINS="*"` selects explicitly. A non-empty list
/// restricts the `Access-Control-Allow-Origin` response to exactly those
/// origins; anything else gets no CORS headers and is refused by the
/// browser.
#[serde(default)]
pub server_cors_origins: Vec<String>,
/// Maximum accepted request body, in bytes.
///
/// The REST handler applies this when it reads the body; the routes that
/// take a body extractor get it through axum's `DefaultBodyLimit`. Before
/// this was read, the limit in force was a 10 MiB constant in the request
/// handler, whatever the variable said.
#[serde(default = "default_max_body_size")]
pub max_body_size: usize,
/// Listen on a Unix domain socket instead of host and port.
pub server_unix_socket: Option<String>,
/// Serve liveness and readiness on a second port of their own.
pub admin_server_port: Option<u16>,
// ========================================================================
// JWT Settings
// ========================================================================
/// JWT secret key (or JWKS URL)
pub jwt_secret: Option<String>,
/// JWT secret as base64
#[serde(default)]
pub jwt_secret_is_base64: bool,
/// JWT audience claim to validate
pub jwt_aud: Option<String>,
/// JWT claim that contains the role
#[serde(default = "default_jwt_role_claim")]
pub jwt_role_claim_key: String,
/// Cache validated tokens, so a repeated token is not verified again.
#[serde(default = "default_true")]
pub jwt_cache_enabled: bool,
/// How long a cached validation may be reused, in seconds.
///
/// A token's own `exp` bounds this; the cache never answers with a token
/// past its expiry. `0` turns the cache off, as in PostgREST.
#[serde(default = "default_jwt_cache_max")]
pub jwt_cache_max_lifetime: u64,
// ========================================================================
// Hasura Authentication
// ========================================================================
/// The shared secret that authenticates an administrator, and the switch
/// that makes `x-hasura-*` headers mean anything at all.
///
/// Unset, this server ignores those headers and reads session variables
/// only from a verified token -- because honouring a header nothing
/// authenticated would let any caller name its own identity, and a policy
/// reading a value the caller chose is not a policy. Hasura instead treats
/// an unsecured deployment as wholly administrative; the divergence is
/// deliberate and is recorded in `postrust_auth::hasura`.
pub hasura_admin_secret: Option<String>,
/// The role a request falls to when nothing authenticated it. Hasura's
/// `HASURA_GRAPHQL_UNAUTHORIZED_ROLE`; unset means such a request is
/// refused rather than answered as a stranger.
pub hasura_unauthorized_role: Option<String>,
// ========================================================================
// OpenAPI Settings
// ========================================================================
/// Address to advertise in the specification's `servers`, for when the
/// server sits behind a reverse proxy and its own address is not the one
/// clients use.
pub openapi_server_proxy_uri: Option<String>,
/// OpenAPI mode: disabled, follow-privileges, ignore-privileges
#[serde(default = "default_openapi_mode")]
pub openapi_mode: OpenApiMode,
// ========================================================================
// Logging Settings
// ========================================================================
/// Log level: crit, error, warn, info, debug
#[serde(default = "default_log_level")]
pub log_level: LogLevel,
// ========================================================================
// Role Settings
// ========================================================================
/// Per-role settings (isolation level, timeout)
#[serde(default)]
pub role_settings: HashMap<String, RoleSettings>,
/// App-level settings to expose via GUC
#[serde(default)]
pub app_settings: HashMap<String, String>,
// ========================================================================
// GraphQL Settings
// ========================================================================
/// Expose the GraphQL API as an Apollo Federation subgraph.
#[serde(default)]
pub graphql_federation: bool,
/// Namespace applied to generated GraphQL table types and root fields.
#[serde(default)]
pub graphql_type_prefix: Option<String>,
// ========================================================================
// Compatibility Settings
// ========================================================================
/// PostgREST compatibility mode.
///
/// When enabled, the REST surface is also served at the root (so canonical
/// PostgREST paths like `/rpc/<name>` and `/<table>` work in addition to
/// the `/api`-prefixed paths), and RPC responses are un-wrapped to match
/// PostgREST's shape (bare object/scalar for non-set-returning functions,
/// a top-level array for set-returning ones) instead of the array-wrapped,
/// function-name-keyed default.
#[serde(default)]
pub compat_mode: bool,
}
impl Default for AppConfig {
fn default() -> Self {
Self {
db_uri: default_db_uri(),
db_schemas: default_db_schemas(),
db_anon_role: None,
db_pool_size: default_pool_size(),
db_pool_timeout: default_pool_timeout(),
db_tx_isolation: default_tx_isolation(),
db_prepared_statements: true,
db_extra_search_path: default_extra_search_path(),
db_channel: default_db_channel(),
db_channel_enabled: false,
db_pre_request: None,
db_max_rows: None,
db_aggregates_enabled: false,
server_host: default_host(),
server_port: default_port(),
server_cors_origins: Vec::new(),
max_body_size: default_max_body_size(),
server_unix_socket: None,
admin_server_port: None,
jwt_secret: None,
jwt_secret_is_base64: false,
jwt_aud: None,
jwt_role_claim_key: default_jwt_role_claim(),
jwt_cache_enabled: true,
jwt_cache_max_lifetime: default_jwt_cache_max(),
hasura_admin_secret: None,
hasura_unauthorized_role: None,
openapi_server_proxy_uri: None,
openapi_mode: OpenApiMode::FollowPrivileges,
log_level: default_log_level(),
role_settings: HashMap::new(),
app_settings: HashMap::new(),
graphql_federation: false,
graphql_type_prefix: None,
compat_mode: false,
}
}
}
/// Say that a variable was set to something unusable, rather than silently
/// applying the default. A rejected value and an unset one are different
/// mistakes and the operator can only fix the one they are told about.
fn warn_ignored(var: &str, value: &str, expected: &str) {
tracing::warn!("Ignoring {}={:?}: expected {}", var, value, expected);
}
/// Parse the explicit spellings accepted for boolean environment variables.
fn parse_bool(value: &str) -> Option<bool> {
match value.trim().to_ascii_lowercase().as_str() {
"true" | "1" | "yes" | "on" => Some(true),
"false" | "0" | "no" | "off" => Some(false),
_ => None,
}
}
fn env_bool(variable: &'static str, value: &str) -> Result<bool, ConfigError> {
parse_bool(value).ok_or_else(|| {
let error = ConfigError {
variable,
value: value.to_string(),
expected: EXPECTED_BOOLEAN,
};
tracing::warn!("{error}");
error
})
}
/// Validate a namespace before it becomes part of generated GraphQL names.
fn parse_graphql_type_prefix(value: &str) -> Result<Option<String>, &'static str> {
let value = value.trim();
if value.is_empty() {
return Ok(None);
}
let mut chars = value.chars();
let valid_first = chars
.next()
.is_some_and(|c| c == '_' || c.is_ascii_alphabetic());
if !valid_first || !chars.all(|c| c == '_' || c.is_ascii_alphanumeric()) {
return Err("a GraphQL identifier beginning with a letter or underscore");
}
Ok(Some(value.to_string()))
}
/// The name an environment variable is looked up by. Windows environment
/// names are case-insensitive, and `std::env::var("PGRST_DB_URI")` finds
/// `pgrst_db_uri` there; the names collected for [`AppConfig::try_from_vars`]
/// are matched exactly, so on Windows they are upper-cased to keep that.
/// App settings lose nothing by it: their names are lower-cased anyway.
fn env_name(name: String) -> String {
if cfg!(windows) {
upper_env_name(name)
} else {
name
}
}
fn upper_env_name(mut name: String) -> String {
name.make_ascii_uppercase();
name
}
impl AppConfig {
/// Load configuration from environment variables.
///
/// # Panics
///
/// Panics if a boolean environment variable has an unsupported value. Use
/// [`Self::try_from_env`] when the caller can propagate a startup error.
pub fn from_env() -> Self {
Self::try_from_env().unwrap_or_else(|error| panic!("{error}"))
}
/// Load configuration from environment variables, rejecting invalid
/// boolean values.
pub fn try_from_env() -> Result<Self, ConfigError> {
// A variable whose name or value is not UTF-8 is skipped, as
// `std::env::var` would have refused it.
Self::try_from_vars(
std::env::vars_os().filter_map(|(k, v)| {
Some((env_name(k.into_string().ok()?), v.into_string().ok()?))
}),
)
}
/// Load configuration from name/value pairs spelled as the environment
/// variables are, for a host with no process environment -- a Cloudflare
/// Worker reads its bindings instead. Where a name appears twice, the last
/// one wins. Names are matched exactly, case included.
pub fn try_from_vars<I, K, V>(vars: I) -> Result<Self, ConfigError>
where
I: IntoIterator<Item = (K, V)>,
K: Into<String>,
V: Into<String>,
{
// Kept in the order given as well as looked up by name: the app
// settings are found by walking the pairs, and two of them that differ
// only in case name the same setting, so which one wins has to depend
// on that order and not on a hash.
let pairs: Vec<(String, String)> = vars
.into_iter()
.map(|(k, v)| (k.into(), v.into()))
.collect();
let vars: HashMap<&str, &str> = pairs
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
let get = |key: &str| vars.get(key).map(|v| v.to_string()).ok_or(());
let mut config = Self::default();
if let Ok(uri) = get("PGRST_DB_URI") {
config.db_uri = uri;
}
if let Ok(uri) = get("DATABASE_URL") {
config.db_uri = uri;
}
if let Ok(schemas) = get("PGRST_DB_SCHEMAS") {
config.db_schemas = schemas.split(',').map(|s| s.trim().to_string()).collect();
}
if let Ok(role) = get("PGRST_DB_ANON_ROLE") {
config.db_anon_role = Some(role);
}
// `PGRST_DB_POOL` is PostgREST's own name; `PGRST_DB_POOL_SIZE` is the
// one this project's documentation has always given, including the
// production checklist in docs/deployment.md. Only the former was read,
// so anybody who followed our own instructions silently kept the
// default pool.
for var in ["PGRST_DB_POOL", "PGRST_DB_POOL_SIZE"] {
if let Ok(size) = get(var) {
match size.parse::<u32>() {
Ok(n) if n > 0 => config.db_pool_size = n,
_ => warn_ignored(var, &size, "a positive integer"),
}
}
}
if let Ok(secs) = get("PGRST_DB_POOL_TIMEOUT") {
match secs.parse::<u64>() {
Ok(n) if n > 0 => config.db_pool_timeout = n,
_ => warn_ignored("PGRST_DB_POOL_TIMEOUT", &secs, "a positive integer"),
}
}
if let Ok(level) = get("PGRST_DB_TX_ISOLATION") {
match IsolationLevel::parse_config(&level) {
Some(l) => config.db_tx_isolation = l,
None => warn_ignored(
"PGRST_DB_TX_ISOLATION",
&level,
"one of: read committed, repeatable read, serializable",
),
}
}
if let Ok(v) = get("PGRST_DB_EXTRA_SEARCH_PATH") {
config.db_extra_search_path = v
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
}
if let Ok(v) = get("PGRST_DB_AGGREGATES_ENABLED") {
config.db_aggregates_enabled = env_bool("PGRST_DB_AGGREGATES_ENABLED", &v)?;
}
if let Ok(v) = get("PGRST_DB_PREPARED_STATEMENTS") {
config.db_prepared_statements = env_bool("PGRST_DB_PREPARED_STATEMENTS", &v)?;
}
if let Ok(v) = get("PGRST_DB_PRE_REQUEST") {
if !v.trim().is_empty() {
config.db_pre_request = Some(v.trim().to_string());
}
}
if let Ok(v) = get("PGRST_DB_CHANNEL") {
if !v.trim().is_empty() {
config.db_channel = v.trim().to_string();
}
}
if let Ok(v) = get("PGRST_DB_CHANNEL_ENABLED") {
config.db_channel_enabled = env_bool("PGRST_DB_CHANNEL_ENABLED", &v)?;
}
// `PGRST_DB_MAX_ROWS` mirrors PostgREST's `db-max-rows`. Accept both.
for var in ["PGRST_DB_MAX_ROWS", "PGRST_MAX_ROWS"] {
if let Ok(max_rows) = get(var) {
match max_rows.parse::<i64>() {
Ok(n) if n >= 0 => config.db_max_rows = Some(n),
_ => warn_ignored(var, &max_rows, "a non-negative integer"),
}
}
}
if let Ok(secret) = get("PGRST_JWT_SECRET") {
config.jwt_secret = Some(secret);
}
if let Ok(aud) = get("PGRST_JWT_AUD") {
config.jwt_aud = Some(aud);
}
// Both of these reach the JWT layer already -- `JwtConfig` is built
// from them in every binary. Only the environment read was missing, so
// a base64 secret was verified against its own text and a role claim
// outside `role` was never found.
if let Ok(v) = get("PGRST_JWT_SECRET_IS_BASE64") {
config.jwt_secret_is_base64 = env_bool("PGRST_JWT_SECRET_IS_BASE64", &v)?;
}
if let Ok(key) = get("PGRST_JWT_ROLE_CLAIM_KEY") {
if !key.trim().is_empty() {
config.jwt_role_claim_key = key;
}
}
if let Ok(v) = get("PGRST_JWT_CACHE_ENABLED") {
config.jwt_cache_enabled = env_bool("PGRST_JWT_CACHE_ENABLED", &v)?;
}
// Zero is meaningful here -- it turns the cache off, as in PostgREST --
// so unlike the other durations it is not rejected.
if let Ok(v) = get("PGRST_JWT_CACHE_MAX_LIFETIME") {
match v.parse::<u64>() {
Ok(n) => config.jwt_cache_max_lifetime = n,
Err(_) => warn_ignored(
"PGRST_JWT_CACHE_MAX_LIFETIME",
&v,
"a non-negative integer number of seconds",
),
}
}
// Hasura's own spelling is accepted beside ours, because a deployment
// migrating from it has these in a compose file already and the point
// of the mode is that the client does not have to be rewritten. The
// `PGRST_` name wins where both are set, on the grounds that it is the
// more specific instruction to this server.
for var in ["HASURA_GRAPHQL_ADMIN_SECRET", "PGRST_HASURA_ADMIN_SECRET"] {
if let Ok(secret) = get(var) {
if !secret.is_empty() {
config.hasura_admin_secret = Some(secret);
}
}
}
for var in [
"HASURA_GRAPHQL_UNAUTHORIZED_ROLE",
"PGRST_HASURA_UNAUTHORIZED_ROLE",
] {
if let Ok(role) = get(var) {
if !role.is_empty() {
config.hasura_unauthorized_role = Some(role);
}
}
}
if let Ok(host) = get("PGRST_SERVER_HOST") {
config.server_host = host;
}
if let Ok(port) = get("PGRST_SERVER_PORT") {
if let Ok(p) = port.parse() {
config.server_port = p;
}
}
if let Ok(port) = get("PORT") {
if let Ok(p) = port.parse() {
config.server_port = p;
}
}
// A bare `*` is the documented way to spell "any origin", and is the
// default. An empty list means the same thing, so a value of only
// separators does not accidentally lock everybody out.
if let Ok(origins) = get("PGRST_SERVER_CORS_ORIGINS") {
config.server_cors_origins = if origins.trim() == "*" {
Vec::new()
} else {
origins
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect()
};
}
if let Ok(bytes) = get("PGRST_MAX_BODY_SIZE") {
match bytes.parse::<usize>() {
Ok(n) if n > 0 => config.max_body_size = n,
_ => warn_ignored("PGRST_MAX_BODY_SIZE", &bytes, "a positive integer"),
}
}
if let Ok(level) = get("PGRST_LOG_LEVEL") {
match LogLevel::parse_config(&level) {
Some(l) => config.log_level = l,
None => warn_ignored(
"PGRST_LOG_LEVEL",
&level,
"one of: crit, error, warn, info, debug",
),
}
}
if let Ok(path) = get("PGRST_SERVER_UNIX_SOCKET") {
if !path.trim().is_empty() {
config.server_unix_socket = Some(path.trim().to_string());
}
}
if let Ok(port) = get("PGRST_ADMIN_SERVER_PORT") {
match port.parse::<u16>() {
Ok(p) if p > 0 => config.admin_server_port = Some(p),
_ => warn_ignored("PGRST_ADMIN_SERVER_PORT", &port, "a port number"),
}
}
if let Ok(uri) = get("PGRST_OPENAPI_SERVER_PROXY_URI") {
if !uri.trim().is_empty() {
config.openapi_server_proxy_uri = Some(uri.trim().to_string());
}
}
if let Ok(mode) = get("PGRST_OPENAPI_MODE") {
match OpenApiMode::parse_config(&mode) {
Some(m) => config.openapi_mode = m,
None => warn_ignored(
"PGRST_OPENAPI_MODE",
&mode,
"one of: disabled, follow-privileges, ignore-privileges",
),
}
}
// `PGRST_ROLE_SETTINGS` is JSON rather than a per-role variable,
// because a PostgreSQL role name may hold characters an environment
// variable name cannot.
if let Ok(raw) = get("PGRST_ROLE_SETTINGS") {
match serde_json::from_str::<HashMap<String, RoleSettings>>(&raw) {
Ok(settings) => config.role_settings = settings,
Err(e) => warn_ignored(
"PGRST_ROLE_SETTINGS",
&raw,
&format!("a JSON object of role to settings ({e})"),
),
}
}
if let Ok(value) = get("PGRST_GRAPHQL_FEDERATION") {
config.graphql_federation = env_bool("PGRST_GRAPHQL_FEDERATION", &value)?;
}
if let Ok(value) = get("PGRST_GRAPHQL_TYPE_PREFIX") {
match parse_graphql_type_prefix(&value) {
Ok(prefix) => config.graphql_type_prefix = prefix,
Err(expected) => warn_ignored("PGRST_GRAPHQL_TYPE_PREFIX", &value, expected),
}
}
// `PGRST_APP_SETTINGS_<NAME>` becomes `app.settings.<name>`, which is
// where PostgREST puts it and where a policy expects to read it back.
// Names that differ only in case (`..._Tenant`, `..._TENANT`) are the
// same setting; the one that comes later in the pairs wins, as the
// later of two equal names does.
for (key, value) in &pairs {
if let Some(name) = key.strip_prefix("PGRST_APP_SETTINGS_") {
if !name.is_empty() {
config
.app_settings
.insert(name.to_ascii_lowercase(), value.clone());
}
}
}
// Accept either the PGRST_-prefixed name (for parity with other options)
// or a POSTRUST_-prefixed alias.
for var in ["PGRST_COMPAT_MODE", "POSTRUST_COMPAT_MODE"] {
if let Ok(v) = get(var) {
config.compat_mode = env_bool(var, &v)?;
}
}
Ok(config)
}
/// Get the default schema (first in the list).
pub fn default_schema(&self) -> &str {
self.db_schemas
.first()
.map(|s| s.as_str())
.unwrap_or("public")
}
}
// Serialized as the spelling configuration uses, not as the Rust variant name,
// so that what this writes is what `parse_config` reads back. Deriving
// `Serialize` here instead emits `"ReadCommitted"`, which then fails to
// deserialize -- and `Serializable` happens to survive the round trip, which
// makes the breakage look intermittent rather than total.
impl Serialize for IsolationLevel {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_config_str())
}
}
impl<'de> Deserialize<'de> for IsolationLevel {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let raw = String::deserialize(deserializer)?;
Self::parse_config(&raw).ok_or_else(|| {
serde::de::Error::custom(format!(
"unknown isolation level {raw:?}: expected one of \
read committed, repeatable read, serializable"
))
})
}
}
impl Serialize for OpenApiMode {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_config_str())
}
}
impl<'de> Deserialize<'de> for OpenApiMode {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let raw = String::deserialize(deserializer)?;
Self::parse_config(&raw).ok_or_else(|| {
serde::de::Error::custom(format!(
"unknown OpenAPI mode {raw:?}: expected one of \
disabled, follow-privileges, ignore-privileges"
))
})
}
}
impl Serialize for LogLevel {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_config_str())
}
}
impl<'de> Deserialize<'de> for LogLevel {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let raw = String::deserialize(deserializer)?;
Self::parse_config(&raw).ok_or_else(|| {
serde::de::Error::custom(format!(
"unknown log level {raw:?}: expected one of \
crit, error, warn, info, debug"
))
})
}
}
/// Per-role settings.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct RoleSettings {
/// Isolation level for this role
pub isolation_level: Option<IsolationLevel>,
/// Statement timeout in milliseconds
pub statement_timeout: Option<u64>,
}
/// Transaction isolation levels.
///
/// Deserialized from the spelling the documentation uses (`"serializable"`,
/// `"read committed"`), not from the Rust variant name, so a `role_settings`
/// entry reads the same as the environment variable.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum IsolationLevel {
/// PostgreSQL's default. A statement sees rows committed before it began.
ReadCommitted,
/// Every statement in the transaction sees the same snapshot.
RepeatableRead,
/// As `RepeatableRead`, and concurrent transactions are additionally
/// guaranteed to be equivalent to some serial order. May abort with a
/// serialization failure, which the client is expected to retry.
Serializable,
}
impl IsolationLevel {
/// The spelling PostgreSQL's `SET TRANSACTION ISOLATION LEVEL` expects.
pub fn to_sql(&self) -> &'static str {
match self {
Self::ReadCommitted => "READ COMMITTED",
Self::RepeatableRead => "REPEATABLE READ",
Self::Serializable => "SERIALIZABLE",
}
}
/// Parse the spelling used in configuration.
///
/// Case-insensitive, and a hyphen, underscore or space separates the words
/// equally -- the documentation writes `read committed` and an environment
/// file is as likely to carry `read-committed`.
pub fn parse_config(s: &str) -> Option<Self> {
match s
.trim()
.to_ascii_lowercase()
.replace(['-', '_'], " ")
.as_str()
{
"read committed" => Some(Self::ReadCommitted),
"repeatable read" => Some(Self::RepeatableRead),
"serializable" => Some(Self::Serializable),
_ => None,
}
}
/// The inverse of [`parse_config`](Self::parse_config).
pub fn as_config_str(&self) -> &'static str {
match self {
Self::ReadCommitted => "read committed",
Self::RepeatableRead => "repeatable read",
Self::Serializable => "serializable",
}
}
}
/// OpenAPI generation mode.
///
/// PostgREST also has a `security-definer` mode, where the specification comes
/// from a user-supplied `SECURITY DEFINER` function. There is no configuration
/// here for naming that function, so the variant is absent rather than present
/// and behaving as one of the others.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum OpenApiMode {
/// No OpenAPI document is served.
Disabled,
/// The document describes only what the requesting role may reach, so two
/// roles asking are answered differently.
FollowPrivileges,
/// The document describes the whole exposed schema, whoever is asking.
IgnorePrivileges,
}
impl OpenApiMode {
/// Parse the spelling used in configuration. Case-insensitive, and a
/// hyphen or an underscore separates the words equally.
pub fn parse_config(s: &str) -> Option<Self> {
match s
.trim()
.to_ascii_lowercase()
.replace(['-', '_'], " ")
.as_str()
{
"disabled" => Some(Self::Disabled),
"follow privileges" => Some(Self::FollowPrivileges),
"ignore privileges" => Some(Self::IgnorePrivileges),
_ => None,
}
}
/// The inverse of [`parse_config`](Self::parse_config).
pub fn as_config_str(&self) -> &'static str {
match self {
Self::Disabled => "disabled",
Self::FollowPrivileges => "follow-privileges",
Self::IgnorePrivileges => "ignore-privileges",
}
}
}
/// Log levels.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LogLevel {
/// Only failures that stop the server. Mapped onto `ERROR`, which is the
/// least severe level `tracing` offers.
Crit,
/// Requests that failed, and faults that did not stop the server.
Error,
/// Configuration that was ignored, and conditions worth noticing.
Warn,
/// Start-up, schema reloads, and one line per request.
Info,
/// The generated SQL and the decisions behind it.
Debug,
}
impl LogLevel {
/// The `tracing` level this maps onto.
///
/// `Crit` and `Error` both become `ERROR`: PostgREST distinguishes them
/// and `tracing` has nothing more severe to map `Crit` onto.
pub fn to_tracing(&self) -> tracing::Level {
match self {
Self::Crit | Self::Error => tracing::Level::ERROR,
Self::Warn => tracing::Level::WARN,
Self::Info => tracing::Level::INFO,
Self::Debug => tracing::Level::DEBUG,
}
}
/// Parse the spelling used in configuration. Case-insensitive.
pub fn parse_config(s: &str) -> Option<Self> {
match s.trim().to_ascii_lowercase().as_str() {
"crit" | "critical" => Some(Self::Crit),
"error" => Some(Self::Error),
"warn" | "warning" => Some(Self::Warn),
"info" => Some(Self::Info),
"debug" => Some(Self::Debug),
_ => None,
}
}
/// The inverse of [`parse_config`](Self::parse_config).
pub fn as_config_str(&self) -> &'static str {
match self {
Self::Crit => "crit",
Self::Error => "error",
Self::Warn => "warn",
Self::Info => "info",
Self::Debug => "debug",
}
}
}
// Default value functions
fn default_db_uri() -> String {
"postgresql://localhost/postgres".to_string()
}
fn default_db_schemas() -> Vec<String> {
vec!["public".to_string()]
}
fn default_pool_size() -> u32 {
10
}
fn default_pool_timeout() -> u64 {
10
}
fn default_tx_isolation() -> IsolationLevel {
IsolationLevel::ReadCommitted
}
fn default_max_body_size() -> usize {
10 * 1024 * 1024
}
fn default_extra_search_path() -> Vec<String> {
vec!["public".to_string()]
}
fn default_db_channel() -> String {
"pgrst".to_string()
}
fn default_host() -> String {
"127.0.0.1".to_string()
}
fn default_port() -> u16 {
3000
}
fn default_jwt_role_claim() -> String {
"role".to_string()
}
fn default_jwt_cache_max() -> u64 {
3600
}
fn default_openapi_mode() -> OpenApiMode {
OpenApiMode::FollowPrivileges
}
// `info`, not `error`. The documentation has always said `info`, and the
// server's own fallback filter is `postrust=info`, so `error` was a third
// answer that agreed with neither -- harmless only for as long as nothing
// read the field.
fn default_log_level() -> LogLevel {
LogLevel::Info
}
fn default_true() -> bool {
true
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_config() {
let config = AppConfig::default();
assert_eq!(config.server_port, 3000);
assert_eq!(config.db_pool_size, 10);
assert!(config.db_prepared_statements);
assert!(!config.graphql_federation);
assert_eq!(config.graphql_type_prefix, None);
}
#[test]
fn test_default_schema() {
let mut config = AppConfig::default();
assert_eq!(config.default_schema(), "public");
config.db_schemas = vec!["api".to_string(), "public".to_string()];
assert_eq!(config.default_schema(), "api");
}
#[test]
fn test_isolation_level_sql() {
assert_eq!(IsolationLevel::ReadCommitted.to_sql(), "READ COMMITTED");
assert_eq!(IsolationLevel::Serializable.to_sql(), "SERIALIZABLE");
}
#[test]
fn isolation_level_accepts_the_documented_spellings() {
// The documentation writes `read committed`; an environment file is as
// likely to carry either separator, or capitals.
for s in [
"read committed",
"READ COMMITTED",
"read-committed",
" Read_Committed ",
] {
assert_eq!(
IsolationLevel::parse_config(s),
Some(IsolationLevel::ReadCommitted),
"{s:?}"
);
}
assert_eq!(
IsolationLevel::parse_config("serializable"),
Some(IsolationLevel::Serializable)
);
assert_eq!(
IsolationLevel::parse_config("repeatable read"),
Some(IsolationLevel::RepeatableRead)
);
// Not a level. Rejected rather than resolved to a default, so the
// caller can say so.
assert_eq!(IsolationLevel::parse_config("dirty read"), None);
assert_eq!(IsolationLevel::parse_config(""), None);
}
#[test]
fn log_level_accepts_the_documented_spellings() {
assert_eq!(LogLevel::parse_config("INFO"), Some(LogLevel::Info));
assert_eq!(LogLevel::parse_config("warning"), Some(LogLevel::Warn));
assert_eq!(LogLevel::parse_config("crit"), Some(LogLevel::Crit));
// `trace` was listed in the documentation and is not a level this
// server has. It is rejected rather than silently read as `debug`.
assert_eq!(LogLevel::parse_config("trace"), None);
}
#[test]
fn default_log_level_matches_the_documented_one() {
// The struct default disagreed with both the documentation and the
// server's own fallback filter for as long as nothing read it.
assert_eq!(AppConfig::default().log_level, LogLevel::Info);
}
#[test]
fn parse_bool_accepts_only_the_supported_spellings() {
for s in ["true", "TRUE", "1", "yes", "on", " On "] {
assert_eq!(parse_bool(s), Some(true), "{s:?}");
}
for s in ["false", "FALSE", "0", "no", "off", " Off "] {
assert_eq!(parse_bool(s), Some(false), "{s:?}");
}
for s in ["", "maybe", "enabled", "2"] {
assert_eq!(parse_bool(s), None, "{s:?}");
}
}
#[test]
fn graphql_federation_configuration_is_read() {
let config = with_env(&[
("PGRST_GRAPHQL_FEDERATION", "true"),
("PGRST_GRAPHQL_TYPE_PREFIX", " test "),
]);
assert!(config.graphql_federation);
assert_eq!(config.graphql_type_prefix.as_deref(), Some("test"));
}
#[test]
fn graphql_federation_accepts_an_explicit_false() {
assert!(!with_env(&[("PGRST_GRAPHQL_FEDERATION", "false")]).graphql_federation);
}
#[test]
fn malformed_graphql_federation_configuration_is_rejected() {
let error = with_env_result(&[("PGRST_GRAPHQL_FEDERATION", "sometimes")])
.expect_err("an invalid boolean must reject the configuration");
assert_eq!(
error.to_string(),
"invalid value for PGRST_GRAPHQL_FEDERATION: \"sometimes\"; expected one of: true, false, 1, 0, yes, no, on, off"
);
}
#[test]
fn an_empty_graphql_prefix_means_unset() {
let config = with_env(&[("PGRST_GRAPHQL_TYPE_PREFIX", " ")]);
assert_eq!(config.graphql_type_prefix, None);
}
// `from_env` reads process-global state, so these run one at a time.
static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// Set the given variables, load, then remove them again.
fn with_env(vars: &[(&str, &str)]) -> AppConfig {
with_env_result(vars).expect("test configuration should be valid")
}
fn with_env_result(vars: &[(&str, &str)]) -> Result<AppConfig, ConfigError> {
let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
for (k, v) in vars {
std::env::set_var(k, v);
}
let config = AppConfig::try_from_env();
for (k, _) in vars {
std::env::remove_var(k);
}
config
}
#[test]
fn documented_variables_are_read() {
// Every one of these was documented and read by nothing. The features
// behind them already worked -- only the environment read was missing.
let config = with_env(&[
("PGRST_DB_POOL_SIZE", "42"),
("PGRST_DB_POOL_TIMEOUT", "7"),
("PGRST_DB_TX_ISOLATION", "serializable"),
("PGRST_JWT_SECRET_IS_BASE64", "true"),
("PGRST_JWT_ROLE_CLAIM_KEY", "user.role"),
("PGRST_LOG_LEVEL", "warn"),
("PGRST_MAX_BODY_SIZE", "1024"),
(
"PGRST_SERVER_CORS_ORIGINS",
"https://a.example, https://b.example",
),
]);
assert_eq!(config.db_pool_size, 42);
assert_eq!(config.db_pool_timeout, 7);
assert_eq!(config.db_tx_isolation, IsolationLevel::Serializable);
assert!(config.jwt_secret_is_base64);
assert_eq!(config.jwt_role_claim_key, "user.role");
assert_eq!(config.log_level, LogLevel::Warn);
assert_eq!(config.max_body_size, 1024);
assert_eq!(
config.server_cors_origins,
vec![
"https://a.example".to_string(),
"https://b.example".to_string()
]
);
}
#[test]
fn variables_can_come_from_somewhere_other_than_the_environment() {
// What a Cloudflare Worker does with its bindings: nothing here is in
// the process environment, and the app settings, which are found by
// prefix rather than by name, arrive all the same.
let config = AppConfig::try_from_vars([
("PGRST_DB_SCHEMAS", "api, extra"),
("PGRST_DB_ANON_ROLE", "web_anon"),
("PGRST_JWT_SECRET", "a-secret"),
("PGRST_DB_MAX_ROWS", "100"),
("PGRST_APP_SETTINGS_Tenant", "acme"),
])
.unwrap();
assert_eq!(config.db_schemas, ["api", "extra"]);
assert_eq!(config.db_anon_role.as_deref(), Some("web_anon"));
assert_eq!(config.jwt_secret.as_deref(), Some("a-secret"));
assert_eq!(config.db_max_rows, Some(100));
assert_eq!(
config.app_settings.get("tenant").map(String::as_str),
Some("acme")
);
let refused = AppConfig::try_from_vars([("PGRST_DB_AGGREGATES_ENABLED", "maybe")]);
assert!(refused.is_err());
}
#[test]
fn app_settings_differing_only_in_case_take_the_later_value() {
// Both name `app.settings.tenant`. Run it a few times: with the pairs
// in a hash map the winner changed from one run to the next.
for _ in 0..16 {
let config = AppConfig::try_from_vars([
("PGRST_APP_SETTINGS_Tenant", "first"),
("PGRST_APP_SETTINGS_TENANT", "second"),
("PGRST_APP_SETTINGS_tenant", "third"),
])
.unwrap();
assert_eq!(
config.app_settings.get("tenant").map(String::as_str),
Some("third")
);
let config = AppConfig::try_from_vars([
("PGRST_APP_SETTINGS_tenant", "third"),
("PGRST_APP_SETTINGS_TENANT", "second"),
])
.unwrap();
assert_eq!(
config.app_settings.get("tenant").map(String::as_str),
Some("second")
);
}
}
#[test]
fn windows_environment_names_are_matched_whatever_their_case() {
// What `env_name` does on Windows, where `std::env::var` ignored case.
let config = AppConfig::try_from_vars([
(upper_env_name("pgrst_db_schemas".into()), "api"),
(upper_env_name("Pgrst_App_Settings_Tenant".into()), "acme"),
])
.unwrap();
assert_eq!(config.db_schemas, ["api"]);
assert_eq!(
config.app_settings.get("tenant").map(String::as_str),
Some("acme")
);
assert_eq!(env_name("PGRST_DB_URI".into()), "PGRST_DB_URI");
assert_eq!(
env_name("pgrst_db_uri".into()) == "PGRST_DB_URI",
cfg!(windows)
);
}
#[test]
fn pool_size_accepts_postgrests_own_name() {
assert_eq!(with_env(&[("PGRST_DB_POOL", "5")]).db_pool_size, 5);
}
#[test]
fn a_star_origin_means_any_origin() {
// Empty is how "any" is carried, so `*` must not become a literal
// origin that matches nothing.
assert!(with_env(&[("PGRST_SERVER_CORS_ORIGINS", "*")])
.server_cors_origins
.is_empty());
assert!(with_env(&[("PGRST_SERVER_CORS_ORIGINS", " , ")])
.server_cors_origins
.is_empty());
}
#[test]
fn an_unusable_value_leaves_the_default() {
let config = with_env(&[
("PGRST_DB_POOL_SIZE", "lots"),
("PGRST_DB_POOL_TIMEOUT", "0"),
("PGRST_MAX_BODY_SIZE", "-1"),
("PGRST_DB_TX_ISOLATION", "dirty read"),
("PGRST_LOG_LEVEL", "shout"),
]);
let d = AppConfig::default();
assert_eq!(config.db_pool_size, d.db_pool_size);
assert_eq!(config.db_pool_timeout, d.db_pool_timeout);
assert_eq!(config.max_body_size, d.max_body_size);
assert_eq!(config.db_tx_isolation, d.db_tx_isolation);
assert_eq!(config.log_level, d.log_level);
}
#[test]
fn the_formerly_dead_fields_are_read() {
// Every one of these was a public field that nothing set and nothing
// consumed.
let config = with_env(&[
("PGRST_DB_PREPARED_STATEMENTS", "false"),
("PGRST_DB_PRE_REQUEST", "auth.check"),
("PGRST_DB_CHANNEL", "my_channel"),
("PGRST_DB_CHANNEL_ENABLED", "yes"),
("PGRST_JWT_CACHE_ENABLED", "false"),
("PGRST_JWT_CACHE_MAX_LIFETIME", "60"),
("PGRST_SERVER_UNIX_SOCKET", "/tmp/postrust.sock"),
("PGRST_ADMIN_SERVER_PORT", "3001"),
("PGRST_OPENAPI_SERVER_PROXY_URI", "https://api.example.com"),
("PGRST_OPENAPI_MODE", "ignore-privileges"),
]);
assert!(!config.db_prepared_statements);
assert_eq!(config.db_pre_request.as_deref(), Some("auth.check"));
assert_eq!(config.db_channel, "my_channel");
assert!(config.db_channel_enabled);
assert!(!config.jwt_cache_enabled);
assert_eq!(config.jwt_cache_max_lifetime, 60);
assert_eq!(
config.server_unix_socket.as_deref(),
Some("/tmp/postrust.sock")
);
assert_eq!(config.admin_server_port, Some(3001));
assert_eq!(
config.openapi_server_proxy_uri.as_deref(),
Some("https://api.example.com")
);
assert_eq!(config.openapi_mode, OpenApiMode::IgnorePrivileges);
}
#[test]
fn a_zero_jwt_cache_lifetime_is_kept_because_it_turns_the_cache_off() {
// Unlike the other durations, 0 is a meaningful value here and must
// not be rejected as unusable.
assert_eq!(
with_env(&[("PGRST_JWT_CACHE_MAX_LIFETIME", "0")]).jwt_cache_max_lifetime,
0
);
}
#[test]
fn app_settings_come_from_a_prefix() {
let config = with_env(&[
("PGRST_APP_SETTINGS_JWT_LIFETIME", "3600"),
("PGRST_APP_SETTINGS_TenantName", "acme"),
]);
// Lower-cased, because that is the name a policy reads back with
// `current_setting('app.settings.<name>')`.
assert_eq!(
config.app_settings.get("jwt_lifetime").map(String::as_str),
Some("3600")
);
assert_eq!(
config.app_settings.get("tenantname").map(String::as_str),
Some("acme")
);
}
#[test]
fn role_settings_parse_from_json_using_the_documented_spellings() {
let config = with_env(&[(
"PGRST_ROLE_SETTINGS",
r#"{"web_user":{"isolation_level":"serializable","statement_timeout":5000}}"#,
)]);
let web_user = config.role_settings.get("web_user").expect("role present");
assert_eq!(web_user.isolation_level, Some(IsolationLevel::Serializable));
assert_eq!(web_user.statement_timeout, Some(5000));
}
#[test]
fn unparseable_role_settings_leave_the_map_empty() {
assert!(with_env(&[("PGRST_ROLE_SETTINGS", "{not json")])
.role_settings
.is_empty());
// A valid JSON object naming a level that does not exist is refused
// as a whole rather than half-applied.
assert!(with_env(&[(
"PGRST_ROLE_SETTINGS",
r#"{"r":{"isolation_level":"dirty"}}"#
)])
.role_settings
.is_empty());
}
#[test]
fn openapi_mode_accepts_the_documented_spellings() {
assert_eq!(
OpenApiMode::parse_config("follow-privileges"),
Some(OpenApiMode::FollowPrivileges)
);
assert_eq!(
OpenApiMode::parse_config("IGNORE_PRIVILEGES"),
Some(OpenApiMode::IgnorePrivileges)
);
assert_eq!(
OpenApiMode::parse_config("disabled"),
Some(OpenApiMode::Disabled)
);
// PostgREST's fourth mode needs a function this server has no
// configuration for, so it is not accepted rather than aliased.
assert_eq!(OpenApiMode::parse_config("security-definer"), None);
}
#[test]
fn the_config_enums_round_trip_through_json() {
// Deriving `Serialize` emits the Rust variant name while the
// hand-written `Deserialize` reads the configuration spelling, so a
// value this type writes could not be read back. `Serializable`
// survived by coincidence -- its variant name lowercases to the
// accepted spelling -- which made the breakage look intermittent.
for level in [
IsolationLevel::ReadCommitted,
IsolationLevel::RepeatableRead,
IsolationLevel::Serializable,
] {
let json = serde_json::to_string(&level).unwrap();
let back: IsolationLevel = serde_json::from_str(&json).unwrap();
assert_eq!(back, level, "{json}");
}
for mode in [
OpenApiMode::Disabled,
OpenApiMode::FollowPrivileges,
OpenApiMode::IgnorePrivileges,
] {
let json = serde_json::to_string(&mode).unwrap();
assert_eq!(serde_json::from_str::<OpenApiMode>(&json).unwrap(), mode);
}
for level in [
LogLevel::Crit,
LogLevel::Error,
LogLevel::Warn,
LogLevel::Info,
LogLevel::Debug,
] {
let json = serde_json::to_string(&level).unwrap();
assert_eq!(serde_json::from_str::<LogLevel>(&json).unwrap(), level);
}
}
#[test]
fn a_whole_config_round_trips_through_json() {
// The struct derives both, which invites persisting it.
let mut config = AppConfig::default();
config.role_settings.insert(
"web_user".to_string(),
RoleSettings {
isolation_level: Some(IsolationLevel::RepeatableRead),
statement_timeout: Some(5000),
},
);
let json = serde_json::to_string(&config).unwrap();
let back: AppConfig = serde_json::from_str(&json).expect("config should round trip");
assert_eq!(back.db_tx_isolation, config.db_tx_isolation);
assert_eq!(back.log_level, config.log_level);
assert_eq!(back.openapi_mode, config.openapi_mode);
assert_eq!(
back.role_settings["web_user"].isolation_level,
Some(IsolationLevel::RepeatableRead)
);
}
#[test]
fn the_serialized_spelling_is_the_configuration_spelling() {
// Not the Rust variant name: what is written should be what an
// operator could paste into the environment.
assert_eq!(
serde_json::to_string(&IsolationLevel::ReadCommitted).unwrap(),
"\"read committed\""
);
assert_eq!(
serde_json::to_string(&OpenApiMode::FollowPrivileges).unwrap(),
"\"follow-privileges\""
);
assert_eq!(serde_json::to_string(&LogLevel::Warn).unwrap(), "\"warn\"");
}
#[test]
fn an_empty_role_claim_key_is_not_accepted() {
// An empty key would look up nothing and every request would fall to
// the anonymous role.
assert_eq!(
with_env(&[("PGRST_JWT_ROLE_CLAIM_KEY", " ")]).jwt_role_claim_key,
AppConfig::default().jwt_role_claim_key
);
}
}