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
//! Configuration for Postrust.
//!
//! Mirrors PostgREST's configuration options.
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// Main application configuration.
#[derive(Clone, Debug, Serialize, Deserialize)]
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,
/// Use prepared statements
#[serde(default = "default_true")]
pub db_prepared_statements: bool,
/// Extra search path schemas
#[serde(default)]
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,
/// Pre-request function to call
pub db_pre_request: Option<String>,
/// Maximum rows allowed in a response
pub db_max_rows: Option<i64>,
/// Enable aggregate functions
#[serde(default = "default_true")]
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,
/// Unix socket path (alternative to host/port)
pub server_unix_socket: Option<String>,
/// Admin server port (for health checks)
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 JWT validations
#[serde(default = "default_true")]
pub jwt_cache_enabled: bool,
/// JWT cache max entries
#[serde(default = "default_jwt_cache_max")]
pub jwt_cache_max_lifetime: u64,
// ========================================================================
// OpenAPI Settings
// ========================================================================
/// OpenAPI server URL
pub openapi_server_proxy_uri: Option<String>,
/// OpenAPI mode: disabled, follow-privileges, ignore-privileges, security-definer
#[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>,
// ========================================================================
// 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_prepared_statements: true,
db_extra_search_path: vec![],
db_channel: default_db_channel(),
db_channel_enabled: false,
db_pre_request: None,
db_max_rows: None,
db_aggregates_enabled: true,
server_host: default_host(),
server_port: default_port(),
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(),
openapi_server_proxy_uri: None,
openapi_mode: OpenApiMode::FollowPrivileges,
log_level: LogLevel::Error,
role_settings: HashMap::new(),
app_settings: HashMap::new(),
compat_mode: false,
}
}
}
impl AppConfig {
/// Load configuration from environment variables.
pub fn from_env() -> Self {
let mut config = Self::default();
if let Ok(uri) = std::env::var("PGRST_DB_URI") {
config.db_uri = uri;
}
if let Ok(uri) = std::env::var("DATABASE_URL") {
config.db_uri = uri;
}
if let Ok(schemas) = std::env::var("PGRST_DB_SCHEMAS") {
config.db_schemas = schemas.split(',').map(|s| s.trim().to_string()).collect();
}
if let Ok(role) = std::env::var("PGRST_DB_ANON_ROLE") {
config.db_anon_role = Some(role);
}
if let Ok(size) = std::env::var("PGRST_DB_POOL") {
if let Ok(n) = size.parse() {
config.db_pool_size = n;
}
}
// `PGRST_MAX_ROWS` is the name used in our own documentation;
// `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) = std::env::var(var) {
match max_rows.parse::<i64>() {
Ok(n) if n >= 0 => config.db_max_rows = Some(n),
_ => {
tracing::warn!(
"Ignoring {}={:?}: expected a non-negative integer",
var,
max_rows
);
}
}
}
}
if let Ok(secret) = std::env::var("PGRST_JWT_SECRET") {
config.jwt_secret = Some(secret);
}
if let Ok(aud) = std::env::var("PGRST_JWT_AUD") {
config.jwt_aud = Some(aud);
}
if let Ok(host) = std::env::var("PGRST_SERVER_HOST") {
config.server_host = host;
}
if let Ok(port) = std::env::var("PGRST_SERVER_PORT") {
if let Ok(p) = port.parse() {
config.server_port = p;
}
}
if let Ok(port) = std::env::var("PORT") {
if let Ok(p) = port.parse() {
config.server_port = p;
}
}
// 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) = std::env::var(var) {
config.compat_mode = matches!(
v.trim().to_ascii_lowercase().as_str(),
"true" | "1" | "yes" | "on"
);
}
}
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")
}
}
/// Per-role settings.
#[derive(Clone, Debug, Serialize, Deserialize)]
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.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum IsolationLevel {
ReadCommitted,
RepeatableRead,
Serializable,
}
impl IsolationLevel {
pub fn to_sql(&self) -> &'static str {
match self {
Self::ReadCommitted => "READ COMMITTED",
Self::RepeatableRead => "REPEATABLE READ",
Self::Serializable => "SERIALIZABLE",
}
}
}
/// OpenAPI generation mode.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum OpenApiMode {
Disabled,
FollowPrivileges,
IgnorePrivileges,
SecurityDefiner,
}
/// Log levels.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum LogLevel {
Crit,
Error,
Warn,
Info,
Debug,
}
impl LogLevel {
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,
}
}
}
// 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_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
}
fn default_log_level() -> LogLevel {
LogLevel::Error
}
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);
}
#[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");
}
}