1use pg_query::protobuf::{ScanToken, Token};
4use serde_json::{Map, Value};
5
6#[derive(Debug, Clone)]
8pub struct GateOptions {
9 pub allow_placeholders: bool,
10 pub max_sql_bytes: usize,
11}
12
13impl Default for GateOptions {
14 fn default() -> Self {
15 Self {
16 allow_placeholders: false,
17 max_sql_bytes: 100 * 1024,
18 }
19 }
20}
21
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum StatementKind {
24 Select,
25 Explain { analyze: bool },
26 Show { name: String },
27}
28
29#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct Accepted {
33 pub kind: StatementKind,
34 pub sql: String,
35 pub rewritten: bool,
37}
38
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct Rejection {
41 pub code: &'static str,
42 pub message: String,
43}
44
45const PARSE_STACK_BYTES: usize = 64 * 1024 * 1024;
47const MAX_DEPTH: usize = 5000;
49
50pub const SECRET_SETTINGS: &[&str] = &[
52 "primary_conninfo",
53 "ssl_passphrase_command",
54 "ssl_key_file",
55 "archive_command",
56 "restore_command",
57 "archive_cleanup_command",
58 "recovery_end_command",
59 "krb_server_keyfile",
60];
61
62const CREDENTIAL_RELATIONS: &[&str] = &[
65 "pg_shadow",
66 "pg_user_mappings",
67 "_pg_user_mappings",
68 "user_mapping_options",
69 "pg_settings",
70 "pg_file_settings",
71 "pg_hba_file_rules",
72 "pg_ident_file_mappings",
73 "pg_config",
74 "_pg_foreign_servers",
75 "_pg_foreign_data_wrappers",
76 "foreign_servers",
77 "foreign_server_options",
78 "foreign_data_wrappers",
79 "foreign_data_wrapper_options",
80];
81
82const PLAIN_CATALOG_TABLES: &[&str] = &[
85 "pg_authid",
86 "pg_user_mapping",
87 "pg_subscription",
88 "pg_db_role_setting",
89 "pg_statistic",
90 "pg_statistic_ext_data",
91 "pg_foreign_server",
92 "pg_foreign_data_wrapper",
93];
94
95pub fn credential_roots() -> Vec<&'static str> {
98 PLAIN_CATALOG_TABLES
99 .iter()
100 .copied()
101 .chain(std::iter::once("pg_largeobject"))
102 .collect()
103}
104
105fn is_credential_relation(name: &str) -> bool {
106 PLAIN_CATALOG_TABLES.contains(&name) || CREDENTIAL_RELATIONS.contains(&name)
107}
108
109const STATS_VIEWS: &[&str] = &["pg_stats", "pg_stats_ext", "pg_stats_ext_exprs"];
111
112const SETTINGS_RELATIONS: &[&str] = &["pg_settings", "pg_file_settings"];
114
115const INTERNAL_SCHEMAS: &[&str] = &[
117 "_timescaledb_functions",
118 "_timescaledb_internal",
119 "_timescaledb_catalog",
120];
121
122const EXPLAIN_OPTIONS: &[&str] = &[
123 "analyze",
124 "verbose",
125 "costs",
126 "settings",
127 "generic_plan",
128 "buffers",
129 "serialize",
130 "wal",
131 "timing",
132 "summary",
133 "memory",
134 "format",
135 "io",
136];
137
138const ALLOWED_NODES: &[&str] = &[
140 "SelectStmt",
141 "ExplainStmt",
142 "VariableShowStmt",
143 "DefElem",
144 "ResTarget",
145 "ColumnRef",
146 "AStar",
147 "AConst",
148 "AExpr",
149 "BoolExpr",
150 "NullTest",
151 "BooleanTest",
152 "SubLink",
153 "CaseExpr",
154 "CaseWhen",
155 "CoalesceExpr",
156 "MinMaxExpr",
157 "NullIfExpr",
158 "RowExpr",
159 "TypeCast",
160 "TypeName",
161 "CollateClause",
162 "FuncCall",
163 "NamedArgExpr",
164 "WindowDef",
165 "SortBy",
166 "RangeVar",
167 "RangeSubselect",
168 "RangeFunction",
169 "RangeTableFunc",
170 "RangeTableFuncCol",
171 "RangeTableSample",
172 "JoinExpr",
173 "Alias",
174 "WithClause",
175 "CommonTableExpr",
176 "CtesearchClause",
177 "CtecycleClause",
178 "AIndices",
179 "AIndirection",
180 "AArrayExpr",
181 "GroupingSet",
182 "GroupingFunc",
183 "ParamRef",
184 "SqlvalueFunction",
185 "XmlExpr",
186 "XmlSerialize",
187 "String",
188 "Integer",
189 "Float",
190 "Boolean",
191 "BitString",
192 "List",
193 "ColumnDef",
194 "JsonObjectConstructor",
195 "JsonArrayConstructor",
196 "JsonArrayQueryConstructor",
197 "JsonObjectAgg",
198 "JsonArrayAgg",
199 "JsonAggConstructor",
200 "JsonKeyValue",
201 "JsonValueExpr",
202 "JsonFormat",
203 "JsonOutput",
204 "JsonReturning",
205 "JsonIsPredicate",
206 "JsonFuncExpr",
207 "JsonParseExpr",
208 "JsonScalarExpr",
209 "JsonSerializeExpr",
210 "JsonTable",
211 "JsonTableColumn",
212 "JsonTablePathSpec",
213 "JsonArgument",
214 "JsonBehavior",
215];
216
217const CRON_JOB_FUNCTIONS: &[&str] = &[
218 "schedule",
219 "schedule_in_database",
220 "unschedule",
221 "alter_job",
222];
223
224const R_CONTROL: &str = "it controls the server or other sessions";
225const R_STATS: &str = "it changes statistics";
226const R_SESSION: &str = "it changes session state that pooled connections would leak";
227const R_SEQUENCE: &str = "it consumes a sequence value or transaction id";
228const R_LARGE_OBJECT: &str = "it writes or exports large objects";
229const R_OTHER_SQL: &str = "it executes SQL text the gate cannot inspect";
230const R_WAL: &str = "it writes WAL or changes replication state";
231const R_FILES: &str = "it reads or writes server files";
232const R_MAINTENANCE: &str = "it performs maintenance work";
233const R_SETTINGS: &str = "it can expose credentials; use the server_info tool";
234const R_TIMESCALE: &str = "it changes TimescaleDB objects";
235const R_CRON: &str = "it changes scheduled jobs";
236const R_RAW_PAGES: &str = "it changes or reads table pages directly";
237const R_WAL_DATA: &str = "it returns raw write-ahead log data";
238const R_STAT_VALUES: &str = "it returns sampled column values held in statistics";
239const R_EXTENSION: &str = "it is an extension routine the gate does not allow";
240const R_NETWORK: &str = "it makes network requests";
241const R_TIMESCALE_INTERNAL: &str = "it calls TimescaleDB internals the gate cannot classify";
242const R_LOG_HELPERS: &str =
243 "the server log helper functions are reserved for the read_server_log tool";
244
245const DENIED_FUNCTIONS: &[(&str, &str)] = &[
247 ("pg_terminate_backend", R_CONTROL),
248 ("pg_cancel_backend", R_CONTROL),
249 ("pg_reload_conf", R_CONTROL),
250 ("pg_rotate_logfile", R_CONTROL),
251 ("pg_rotate_logfile_old", R_CONTROL),
253 ("pg_switch_wal", R_CONTROL),
254 ("pg_create_restore_point", R_CONTROL),
255 ("pg_promote", R_CONTROL),
256 ("pg_wal_replay_*", R_CONTROL),
257 ("pg_backup_*", R_CONTROL),
258 ("pg_log_backend_memory_contexts", R_CONTROL),
259 ("pg_log_standby_snapshot", R_CONTROL),
260 ("pg_import_system_collations", R_CONTROL),
261 ("binary_upgrade_*", R_CONTROL),
262 ("pg_stat_reset*", R_STATS),
263 ("pg_stat_statements_reset", R_STATS),
264 ("pg_stat_force_next_flush", R_STATS),
265 ("pg_stat_clear_snapshot", R_STATS),
266 ("pg_restore_*", R_STATS),
267 ("pg_clear_*", R_STATS),
268 ("pg_advisory_*", R_SESSION),
269 ("pg_try_advisory_*", R_SESSION),
270 ("set_config", R_SESSION),
271 ("pg_notify", R_SESSION),
272 ("setseed", R_SESSION),
273 ("pg_export_snapshot", R_SESSION),
274 ("nextval", R_SEQUENCE),
275 ("setval", R_SEQUENCE),
276 ("txid_current", R_SEQUENCE),
277 ("pg_current_xact_id", R_SEQUENCE),
278 ("lo_import", R_LARGE_OBJECT),
279 ("lo_export", R_LARGE_OBJECT),
280 ("lo_unlink", R_LARGE_OBJECT),
281 ("lo_create", R_LARGE_OBJECT),
282 ("lo_creat", R_LARGE_OBJECT),
283 ("lo_put", R_LARGE_OBJECT),
284 ("lo_from_bytea", R_LARGE_OBJECT),
285 ("lowrite", R_LARGE_OBJECT),
286 ("lo_open", R_LARGE_OBJECT),
287 ("lo_truncate", R_LARGE_OBJECT),
288 ("lo_truncate64", R_LARGE_OBJECT),
289 ("dblink*", R_OTHER_SQL),
290 ("query_to_xml*", R_OTHER_SQL),
291 ("cursor_to_xml*", R_OTHER_SQL),
292 ("table_to_xml*", R_OTHER_SQL),
293 ("schema_to_xml*", R_OTHER_SQL),
294 ("database_to_xml*", R_OTHER_SQL),
295 ("ts_stat", R_OTHER_SQL),
296 ("ts_rewrite", R_OTHER_SQL),
297 ("crosstab*", R_OTHER_SQL),
298 ("connectby", R_OTHER_SQL),
299 ("xpath_table", R_OTHER_SQL),
300 ("pg_logical_emit_message", R_WAL),
301 ("pg_logical_slot_*", R_WAL),
302 ("pg_replication_slot_*", R_WAL),
303 ("pg_create_logical_replication_slot", R_WAL),
304 ("pg_create_physical_replication_slot", R_WAL),
305 ("pg_drop_replication_slot", R_WAL),
306 ("pg_copy_logical_replication_slot", R_WAL),
307 ("pg_copy_physical_replication_slot", R_WAL),
308 ("pg_replication_origin_*", R_WAL),
309 ("pg_sync_replication_slots", R_WAL),
310 ("pg_read_file", R_FILES),
311 ("pg_read_file_old", R_FILES),
313 ("pg_read_binary_file", R_FILES),
314 ("pg_ls_dir", R_FILES),
316 ("pg_stat_file", R_FILES),
317 ("pg_file_*", R_FILES),
318 ("pg_prewarm", R_MAINTENANCE),
319 ("brin_summarize_*", R_MAINTENANCE),
320 ("brin_desummarize_range", R_MAINTENANCE),
321 ("gin_clean_pending_list", R_MAINTENANCE),
322 ("pg_buffercache_evict*", R_MAINTENANCE),
323 ("pg_show_all_settings", R_SETTINGS),
324 ("pg_show_all_file_settings", R_SETTINGS),
325 ("pg_hba_file_rules", R_SETTINGS),
326 ("pg_ident_file_mappings", R_SETTINGS),
327 ("add_columnstore_policy", R_TIMESCALE),
328 ("add_compaction_policy", R_TIMESCALE),
329 ("add_compression_policy", R_TIMESCALE),
330 ("add_continuous_aggregate_policy", R_TIMESCALE),
331 ("add_dimension", R_TIMESCALE),
332 ("add_job", R_TIMESCALE),
333 ("add_policies", R_TIMESCALE),
334 ("add_reorder_policy", R_TIMESCALE),
335 ("add_retention_policy", R_TIMESCALE),
336 ("alter_job", R_TIMESCALE),
337 ("alter_policies", R_TIMESCALE),
338 ("attach_chunk", R_TIMESCALE),
339 ("attach_tablespace", R_TIMESCALE),
340 ("cagg_migrate", R_TIMESCALE),
341 ("compress_chunk", R_TIMESCALE),
342 ("convert_to_columnstore", R_TIMESCALE),
343 ("convert_to_rowstore", R_TIMESCALE),
344 ("copy_chunk", R_TIMESCALE),
345 ("create_chunk", R_TIMESCALE),
346 ("create_distributed_hypertable", R_TIMESCALE),
347 ("create_hypertable", R_TIMESCALE),
348 ("decompress_chunk", R_TIMESCALE),
349 ("delete_job", R_TIMESCALE),
350 ("detach_chunk", R_TIMESCALE),
351 ("detach_tablespace", R_TIMESCALE),
352 ("detach_tablespaces", R_TIMESCALE),
353 ("disable_chunk_skipping", R_TIMESCALE),
354 ("drop_chunks", R_TIMESCALE),
355 ("enable_chunk_skipping", R_TIMESCALE),
356 ("merge_chunks", R_TIMESCALE),
357 ("merge_chunks_concurrently", R_TIMESCALE),
358 ("move_chunk", R_TIMESCALE),
359 ("recompress_chunk", R_TIMESCALE),
360 ("refresh_continuous_aggregate", R_TIMESCALE),
361 ("remove_all_policies", R_TIMESCALE),
362 ("remove_columnstore_policy", R_TIMESCALE),
363 ("remove_compaction_policy", R_TIMESCALE),
364 ("remove_compression_policy", R_TIMESCALE),
365 ("remove_continuous_aggregate_policy", R_TIMESCALE),
366 ("remove_policies", R_TIMESCALE),
367 ("remove_reorder_policy", R_TIMESCALE),
368 ("remove_retention_policy", R_TIMESCALE),
369 ("reorder_chunk", R_TIMESCALE),
370 ("run_job", R_TIMESCALE),
371 ("set_adaptive_chunking", R_TIMESCALE),
372 ("set_chunk_time_interval", R_TIMESCALE),
373 ("set_integer_now_func", R_TIMESCALE),
374 ("set_number_partitions", R_TIMESCALE),
375 ("set_partitioning_interval", R_TIMESCALE),
376 ("set_replication_factor", R_TIMESCALE),
377 ("split_chunk", R_TIMESCALE),
378 ("timescaledb_post_restore", R_TIMESCALE),
379 ("timescaledb_pre_restore", R_TIMESCALE),
380 ("heap_force_kill", R_RAW_PAGES),
381 ("heap_force_freeze", R_RAW_PAGES),
382 ("pg_truncate_visibility_map", R_RAW_PAGES),
383 ("get_raw_page", R_RAW_PAGES),
384 ("heap_page_items", R_RAW_PAGES),
385 ("bt_page_items", R_RAW_PAGES),
386 ("brin_page_items", R_RAW_PAGES),
387 ("gin_page_items", R_RAW_PAGES),
388 ("gist_page_items", R_RAW_PAGES),
389 ("hash_page_items", R_RAW_PAGES),
390 ("spgist_page_items", R_RAW_PAGES),
391 ("brin_metapage_info", R_RAW_PAGES),
392 ("brin_page_type", R_RAW_PAGES),
393 ("bt_multi_page_stats", R_RAW_PAGES),
394 ("bt_page_stats", R_RAW_PAGES),
395 ("fsm_page_contents", R_RAW_PAGES),
396 ("gin_leafpage_items", R_RAW_PAGES),
397 ("gin_metapage_info", R_RAW_PAGES),
398 ("gin_page_opaque_info", R_RAW_PAGES),
399 ("gist_page_items_bytea", R_RAW_PAGES),
400 ("gist_page_opaque_info", R_RAW_PAGES),
401 ("hash_metapage_info", R_RAW_PAGES),
402 ("hash_page_stats", R_RAW_PAGES),
403 ("hash_page_type", R_RAW_PAGES),
404 ("heap_page_item_attrs", R_RAW_PAGES),
405 ("heap_tuple_infomask_flags", R_RAW_PAGES),
406 ("page_checksum", R_RAW_PAGES),
407 ("page_header", R_RAW_PAGES),
408 ("tuple_data_split", R_RAW_PAGES),
409 ("pg_get_wal_block_info", R_WAL_DATA),
410 ("pg_get_wal_record_info", R_WAL_DATA),
411 ("pg_get_wal_records_info", R_WAL_DATA),
412 ("pg_get_wal_records_info_till_end_of_wal", R_WAL_DATA),
413 ("pg_get_wal_stats", R_WAL_DATA),
414 ("pg_get_wal_stats_till_end_of_wal", R_WAL_DATA),
415 ("pg_available_wal_summaries", R_FILES),
416 ("pg_wal_summary_contents", R_FILES),
417 ("pg_mcv_list_items", R_STAT_VALUES),
418 ("_postgis_stats", R_STAT_VALUES),
419 ("autoprewarm_dump_now", R_MAINTENANCE),
420 ("autoprewarm_start_worker", R_MAINTENANCE),
421 ("pg_logdir_ls", R_FILES),
422 ("pg_background_launch", R_OTHER_SQL),
423 ("pg_background_result", R_OTHER_SQL),
424 ("pg_background_detach", R_OTHER_SQL),
425 ("http", R_NETWORK),
426 ("http_get", R_NETWORK),
427 ("http_post", R_NETWORK),
428 ("http_put", R_NETWORK),
429 ("http_patch", R_NETWORK),
430 ("http_delete", R_NETWORK),
431 ("http_head", R_NETWORK),
432 ("http_set_curlopt", R_NETWORK),
433 ("http_reset_curlopt", R_NETWORK),
434 ("postgres_fdw_disconnect", R_CONTROL),
435 ("postgres_fdw_disconnect_all", R_CONTROL),
436 ("hypopg_create_index", R_SESSION),
437 ("hypopg_drop_index", R_SESSION),
438 ("hypopg_reset", R_SESSION),
439 ("hypopg_reset_index", R_SESSION),
440 ("hypopg_hide_index", R_SESSION),
441 ("hypopg_unhide_index", R_SESSION),
442 ("hypopg_unhide_all_indexes", R_SESSION),
443 ("pg_stat_kcache_reset", R_STATS),
444 ("pg_qualstats_reset", R_STATS),
445 ("pg_wait_sampling_reset_profile", R_STATS),
446 ("pg_stat_monitor_reset", R_STATS),
447 ("pgr_*", R_EXTENSION),
448 ("read_log_file", R_LOG_HELPERS),
449 ("list_log_files", R_LOG_HELPERS),
450];
451
452const ALLOWED_FUNCTIONS: &[&str] = &["pg_current_xact_id_if_assigned", "pg_stat_get_*", "lo_get"];
454
455#[doc(hidden)]
457pub fn denied_functions() -> &'static [(&'static str, &'static str)] {
458 DENIED_FUNCTIONS
459}
460
461pub fn check(sql: &str, opts: &GateOptions) -> Result<Accepted, Rejection> {
463 if sql.trim().is_empty() {
464 return Err(reject("empty", "SQL text is empty."));
465 }
466 if sql.len() > opts.max_sql_bytes {
467 let message = format!(
468 "SQL text is {} bytes; the limit is {} bytes.",
469 sql.len(),
470 opts.max_sql_bytes
471 );
472 return Err(reject("too_long", message));
473 }
474 if sql.contains('\0') {
475 return Err(reject("nul_byte", "SQL text contains a NUL byte."));
476 }
477 std::thread::scope(|scope| {
478 let worker = std::thread::Builder::new()
479 .stack_size(PARSE_STACK_BYTES)
480 .spawn_scoped(scope, || analyse(sql, opts));
481 match worker {
482 Err(error) => Err(parse_failed(format!(
483 "could not start the parser thread: {error}"
484 ))),
485 Ok(handle) => handle
486 .join()
487 .unwrap_or_else(|_| Err(parse_failed("internal parser failure"))),
488 }
489 })
490}
491
492fn analyse(sql: &str, opts: &GateOptions) -> Result<Accepted, Rejection> {
494 let parsed = pg_query::parse(sql, pg_query::ParserOptions::DEFAULT).map_err(parse_error_of)?;
495 let statement = match parsed.protobuf.stmts.as_slice() {
496 [] => return Err(reject("empty", "SQL text is empty.")),
497 [single] => single,
498 many => {
499 let message = format!("Send exactly one statement per call; found {}.", many.len());
500 return Err(reject("multiple_statements", message));
501 }
502 };
503 let Some(node) = statement.stmt.as_deref() else {
504 return Err(malformed());
505 };
506 let tree = serde_json::to_value(node).map_err(|error| parse_failed(error.to_string()))?;
507 let kind = classify(&tree)?;
508 let mut found = Found::default();
509 walk(&tree, opts, &mut found)?;
510 if let Some(name) = found
511 .cte_names
512 .iter()
513 .find(|name| STATS_VIEWS.contains(&name.as_str()))
514 {
515 return Err(view_denied(name));
516 }
517 if found.views.is_empty() {
518 return Ok(Accepted {
519 kind,
520 sql: sql.to_owned(),
521 rewritten: false,
522 });
523 }
524 let rewritten = rewrite_views(sql, &found.views)?;
525 Ok(Accepted {
526 kind,
527 sql: rewritten,
528 rewritten: true,
529 })
530}
531
532#[derive(Default)]
534struct Found {
535 views: Vec<ViewRef>,
536 cte_names: Vec<String>,
537}
538
539struct ViewRef {
541 view: &'static str,
542 location: i64,
544 qualified: bool,
545 aliased: bool,
546 inherits: bool,
547}
548
549fn classify(tree: &Value) -> Result<StatementKind, Rejection> {
550 let Some((variant, body)) = node_of(tree) else {
551 return Err(malformed());
552 };
553 match variant {
554 "SelectStmt" => Ok(StatementKind::Select),
555 "ExplainStmt" => classify_explain(body),
556 "VariableShowStmt" => {
557 let name = str_field(body, "name")
558 .unwrap_or_default()
559 .to_ascii_lowercase();
560 Ok(StatementKind::Show { name })
561 }
562 other => Err(statement_not_allowed(other)),
563 }
564}
565
566fn classify_explain(body: &Value) -> Result<StatementKind, Rejection> {
567 let Some((inner, _)) = body.get("query").and_then(node_of) else {
568 return Err(malformed());
569 };
570 if inner != "SelectStmt" {
571 return Err(statement_not_allowed(inner));
572 }
573 let mut analyze = false;
574 for option in items(body, "options") {
575 let Some(("DefElem", def)) = node_of(option) else {
576 return Err(malformed());
577 };
578 let name = str_field(def, "defname")
579 .unwrap_or_default()
580 .to_ascii_lowercase();
581 if !EXPLAIN_OPTIONS.contains(&name.as_str()) {
582 return Err(reject(
583 "explain_option",
584 format!("EXPLAIN option {name} is not allowed."),
585 ));
586 }
587 if name == "analyze" && !is_false_value(def.get("arg")) {
588 analyze = true;
589 }
590 }
591 Ok(StatementKind::Explain { analyze })
592}
593
594fn is_false_value(arg: Option<&Value>) -> bool {
596 let Some((variant, body)) = arg.and_then(node_of) else {
597 return false;
598 };
599 match variant {
600 "Boolean" => body.get("boolval").and_then(Value::as_bool) == Some(false),
601 "Integer" => body.get("ival").and_then(Value::as_i64) == Some(0),
602 "String" => str_field(body, "sval")
603 .is_some_and(|s| matches!(s.to_ascii_lowercase().as_str(), "false" | "off" | "0")),
604 _ => false,
605 }
606}
607
608fn walk(root: &Value, opts: &GateOptions, found: &mut Found) -> Result<(), Rejection> {
610 let mut pending: Vec<(&Value, usize)> = vec![(root, 1)];
611 while let Some((value, depth)) = pending.pop() {
612 if depth > MAX_DEPTH {
613 return Err(reject(
614 "too_deep",
615 "The query is nested too deeply for the read-only gate.",
616 ));
617 }
618 match value {
619 Value::Object(map) => {
620 check_fields(map)?;
621 if let Some((variant, body)) = node_of(value) {
622 check_node(variant, body, opts, found)?;
623 }
624 pending.extend(map.values().map(|child| (child, depth + 1)));
625 }
626 Value::Array(list) => pending.extend(list.iter().map(|child| (child, depth + 1))),
627 _ => {}
628 }
629 }
630 Ok(())
631}
632
633fn check_fields(map: &Map<String, Value>) -> Result<(), Rejection> {
634 if map.get("into_clause").is_some_and(|value| !value.is_null()) {
635 let message = "SELECT ... INTO creates a table and is not allowed. Remove the INTO clause.";
636 return Err(reject("select_into", message));
637 }
638 if map
639 .get("locking_clause")
640 .and_then(Value::as_array)
641 .is_some_and(|list| !list.is_empty())
642 {
643 let message =
644 "FOR UPDATE / FOR SHARE takes row locks and is not allowed. Remove the locking clause.";
645 return Err(reject("row_locking", message));
646 }
647 Ok(())
648}
649
650fn check_node(
651 variant: &str,
652 body: &Value,
653 opts: &GateOptions,
654 found: &mut Found,
655) -> Result<(), Rejection> {
656 if !ALLOWED_NODES.contains(&variant) {
657 let message =
658 format!("This query uses a construct the read-only gate does not allow: {variant}.");
659 return Err(reject("node_not_allowed", message));
660 }
661 match variant {
662 "ParamRef" if !opts.allow_placeholders => Err(reject(
663 "placeholder",
664 "Parameter placeholders ($1) are not supported. Inline the value.",
665 )),
666 "CommonTableExpr" => {
667 if let Some(name) = str_field(body, "ctename") {
668 found.cte_names.push(name.to_owned());
669 }
670 check_cte(body)
671 }
672 "FuncCall" => check_function(body),
673 "AIndirection" => check_indirection(body),
674 "ColumnRef" => check_column_ref(body),
675 "RangeVar" => {
676 check_relation(body)?;
677 if let Some(view) = stats_view_of(body) {
678 if str_field(body, "catalogname").is_some_and(|name| !name.is_empty()) {
679 return Err(view_denied(view));
680 }
681 found.views.push(view_ref(body, view));
682 }
683 Ok(())
684 }
685 "VariableShowStmt" => check_setting(str_field(body, "name").unwrap_or_default()),
686 _ => Ok(()),
687 }
688}
689
690fn check_cte(body: &Value) -> Result<(), Rejection> {
692 match body.get("ctequery").and_then(node_of) {
693 Some(("SelectStmt", _)) => Ok(()),
694 Some(_) => {
695 let message = "Data-modifying statements inside WITH (INSERT, UPDATE, DELETE, MERGE) are not allowed.";
696 Err(reject("data_modifying_cte", message))
697 }
698 None => Err(malformed()),
699 }
700}
701
702fn check_function(body: &Value) -> Result<(), Rejection> {
703 let names: Vec<&str> = items(body, "funcname")
704 .iter()
705 .filter_map(node_of)
706 .filter_map(|(variant, part)| {
707 if variant == "String" {
708 str_field(part, "sval")
709 } else {
710 None
711 }
712 })
713 .collect();
714 let Some(&last) = names.last() else {
715 return Err(malformed());
716 };
717 let lowered = last.to_ascii_lowercase();
718 let qualifier = names.iter().rev().nth(1).map(|q| q.to_ascii_lowercase());
719 if qualifier.as_deref() == Some("cron") && CRON_JOB_FUNCTIONS.contains(&lowered.as_str()) {
720 return Err(function_denied(last, R_CRON));
721 }
722 if qualifier.as_deref() == Some("pgmcp") {
723 return Err(function_denied(last, R_LOG_HELPERS));
724 }
725 if let Some(qualifier) = qualifier.as_deref()
726 && INTERNAL_SCHEMAS.contains(&qualifier)
727 {
728 return Err(function_denied(last, R_TIMESCALE_INTERNAL));
729 }
730 if let Some(reason) = deny_reason(&lowered) {
731 return Err(function_denied(last, reason));
732 }
733 if lowered == "current_setting" {
734 check_current_setting(body)?;
735 }
736 Ok(())
737}
738
739fn check_indirection(body: &Value) -> Result<(), Rejection> {
741 items(body, "indirection")
742 .iter()
743 .try_for_each(check_dotted_name)
744}
745
746fn check_column_ref(body: &Value) -> Result<(), Rejection> {
748 let fields = items(body, "fields");
749 if let [catalog, view, _] = fields {
750 let view_name =
751 string_part(view).and_then(|name| STATS_VIEWS.iter().copied().find(|v| *v == name));
752 if let (Some("pg_catalog"), Some(view)) = (string_part(catalog), view_name) {
753 let message = format!(
754 "{} Refer to its columns as {view}.column or through an alias.",
755 view_message(view)
756 );
757 return Err(reject("relation_denied", message));
758 }
759 }
760 if fields.len() < 2 {
761 return Ok(());
762 }
763 fields.last().map_or(Ok(()), check_dotted_name)
764}
765
766fn check_dotted_name(part: &Value) -> Result<(), Rejection> {
768 let Some(("String", body)) = node_of(part) else {
769 return Ok(());
770 };
771 let Some(name) = str_field(body, "sval") else {
772 return Ok(());
773 };
774 let lowered = name.to_ascii_lowercase();
775 if let Some(reason) = deny_reason(&lowered) {
776 return Err(dotted_denied(name, reason));
777 }
778 if lowered == "current_setting" {
779 let message = "\"current_setting\" after a dot would call current_setting() with a computed name, which is not allowed. Use current_setting('name') with a literal name. If it is a column of yours, give it another name with AS in a subquery.";
780 return Err(reject("setting_denied", message));
781 }
782 Ok(())
783}
784
785fn check_current_setting(body: &Value) -> Result<(), Rejection> {
787 let args = items(body, "args");
788 let literal = args.first().and_then(string_constant);
789 let missing_ok_is_constant = args.get(1).is_none_or(is_constant);
790 match literal {
791 Some(name) if args.len() <= 2 && missing_ok_is_constant => check_setting(name),
792 _ => {
793 let message = "current_setting() takes a literal setting name here; computed names are not allowed.";
794 Err(reject("setting_denied", message))
795 }
796 }
797}
798
799const TOAST_MESSAGE: &str =
800 "TOAST tables are not readable through this server. Read the table they belong to.";
801
802fn is_toast_relation(schema: &str, relname: &str) -> bool {
805 if schema == "pg_toast" || schema.starts_with("pg_toast_temp_") {
806 return true;
807 }
808 let Some(rest) = relname.strip_prefix("pg_toast_") else {
809 return false;
810 };
811 let digits = rest.strip_suffix("_index").unwrap_or(rest);
812 !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())
813}
814
815fn check_relation(body: &Value) -> Result<(), Rejection> {
816 let relname = str_field(body, "relname")
817 .unwrap_or_default()
818 .to_ascii_lowercase();
819 let schema = str_field(body, "schemaname")
820 .unwrap_or_default()
821 .to_ascii_lowercase();
822 if is_toast_relation(&schema, &relname) {
823 return Err(reject("relation_denied", TOAST_MESSAGE));
824 }
825 if is_credential_relation(&relname)
826 && matches!(schema.as_str(), "" | "pg_catalog" | "information_schema")
827 {
828 let message = if SETTINGS_RELATIONS.contains(&relname.as_str()) {
829 format!(
830 "{relname} can expose credentials and is not readable through this server. Use the server_info tool for settings."
831 )
832 } else {
833 format!(
834 "Relation {relname} is not readable through this server. It can expose credentials."
835 )
836 };
837 return Err(reject("relation_denied", message));
838 }
839 Ok(())
840}
841
842fn stats_view_of(body: &Value) -> Option<&'static str> {
844 let relname = str_field(body, "relname")?;
845 let schema = str_field(body, "schemaname").unwrap_or_default();
846 if !matches!(schema, "" | "pg_catalog") {
847 return None;
848 }
849 STATS_VIEWS.iter().copied().find(|view| *view == relname)
850}
851
852fn view_ref(body: &Value, view: &'static str) -> ViewRef {
854 ViewRef {
855 view,
856 location: body.get("location").and_then(Value::as_i64).unwrap_or(-1),
857 qualified: str_field(body, "schemaname").is_some_and(|schema| !schema.is_empty()),
858 aliased: body.get("alias").is_some_and(|alias| !alias.is_null()),
859 inherits: body.get("inh").and_then(Value::as_bool).unwrap_or(false),
860 }
861}
862
863fn view_message(view: &str) -> String {
864 format!(
865 "{view} can only be read as a plain table reference in FROM or JOIN, for example: SELECT attname, n_distinct FROM pg_stats WHERE tablename = 'orders'"
866 )
867}
868
869fn view_denied(view: &str) -> Rejection {
870 reject("relation_denied", view_message(view))
871}
872
873fn string_part(value: &Value) -> Option<&str> {
875 match node_of(value) {
876 Some(("String", body)) => str_field(body, "sval"),
877 _ => None,
878 }
879}
880
881fn rewrite_views(sql: &str, views: &[ViewRef]) -> Result<String, Rejection> {
884 let fallback = views.first().map_or("pg_stats", |view| view.view);
885 let scanned = pg_query::scan(sql).map_err(|_| view_denied(fallback))?;
886 let mut edits = Vec::with_capacity(views.len());
887 for view in views {
888 edits.push(splice(&scanned.tokens, view)?);
889 }
890 edits.sort_by_key(|edit| edit.start);
891 let mut out = String::with_capacity(sql.len() + 256 * edits.len());
892 let mut cursor = 0;
893 for edit in edits {
894 if edit.start < cursor {
895 return Err(view_denied(edit.view));
896 }
897 let kept = sql
898 .get(cursor..edit.start)
899 .ok_or_else(|| view_denied(edit.view))?;
900 out.push_str(kept);
901 out.push_str(&edit.text);
902 cursor = edit.end;
903 }
904 out.push_str(sql.get(cursor..).ok_or_else(|| view_denied(fallback))?);
905 verify_rewrite(&out, views.len(), fallback)?;
906 Ok(out)
907}
908
909struct Edit {
911 view: &'static str,
912 start: usize,
913 end: usize,
914 text: String,
915}
916
917fn splice(tokens: &[ScanToken], view: &ViewRef) -> Result<Edit, Rejection> {
920 let denied = || view_denied(view.view);
921 let start = usize::try_from(view.location).map_err(|_| denied())?;
922 let index = tokens
923 .iter()
924 .position(|token| usize::try_from(token.start).ok() == Some(start))
925 .ok_or_else(denied)?;
926 let before = previous_token(tokens, index);
927 let follows_list = [Token::From, Token::Join, Token::Ascii44, Token::Ascii40]
928 .iter()
929 .any(|kind| Some(*kind as i32) == before);
930 if !follows_list || !view.inherits {
931 return Err(denied());
932 }
933 let ident = |at: usize| {
934 tokens
935 .get(at)
936 .filter(|token| token.token == Token::Ident as i32)
937 };
938 let last = if view.qualified {
939 if tokens.get(index + 1).map(|token| token.token) != Some(Token::Ascii46 as i32) {
940 return Err(denied());
941 }
942 index + 2
943 } else {
944 index
945 };
946 ident(index).ok_or_else(denied)?;
947 let last_token = ident(last).ok_or_else(denied)?;
948 let end = usize::try_from(last_token.end).map_err(|_| denied())?;
949 let after = tokens.get(last + 1).map(|token| token.token);
950 if after == Some(Token::Ascii42 as i32) || after == Some(Token::Tablesample as i32) {
951 return Err(denied());
952 }
953 let name = view.view;
954 let hidden = credential_roots().join(",");
955 let mut text = format!(
956 "(SELECT * FROM pg_catalog.{name} WHERE schemaname OPERATOR(pg_catalog.<>) 'pg_catalog'::pg_catalog.name OR tablename OPERATOR(pg_catalog.<>) ALL ('{{{hidden}}}'::pg_catalog.name[]) OFFSET 0)"
957 );
958 if !view.aliased {
959 text.push_str(" AS ");
960 text.push_str(name);
961 }
962 Ok(Edit {
963 view: name,
964 start,
965 end,
966 text,
967 })
968}
969
970fn previous_token(tokens: &[ScanToken], index: usize) -> Option<i32> {
972 tokens[..index]
973 .iter()
974 .rev()
975 .map(|token| token.token)
976 .find(|kind| *kind != Token::SqlComment as i32 && *kind != Token::CComment as i32)
977}
978
979fn verify_rewrite(out: &str, references: usize, fallback: &'static str) -> Result<(), Rejection> {
982 let parsed = pg_query::parse(out, pg_query::ParserOptions::DEFAULT)
983 .map_err(|_| view_denied(fallback))?;
984 let tree =
985 serde_json::to_value(&parsed.protobuf).map_err(|error| parse_failed(error.to_string()))?;
986 let (mut injected, mut bare) = (0_usize, 0_usize);
987 let mut pending = vec![&tree];
988 while let Some(value) = pending.pop() {
989 match value {
990 Value::Object(map) => {
991 if let Some(range_var) = map.get("RangeVar") {
992 let relname = str_field(range_var, "relname").unwrap_or_default();
993 if STATS_VIEWS.contains(&relname) {
994 if str_field(range_var, "schemaname") == Some("pg_catalog") {
995 injected += 1;
996 } else {
997 bare += 1;
998 }
999 }
1000 }
1001 pending.extend(map.values());
1002 }
1003 Value::Array(list) => pending.extend(list.iter()),
1004 _ => {}
1005 }
1006 }
1007 if bare != 0 || injected != references {
1008 return Err(view_denied(fallback));
1009 }
1010 Ok(())
1011}
1012
1013fn check_setting(name: &str) -> Result<(), Rejection> {
1014 let lowered = name.to_ascii_lowercase();
1015 if SECRET_SETTINGS.contains(&lowered.as_str()) {
1016 let message = format!(
1017 "The setting {lowered} can expose credentials or local paths and is not readable through this server. Use the server_info tool for settings."
1018 );
1019 return Err(reject("setting_denied", message));
1020 }
1021 Ok(())
1022}
1023
1024fn deny_reason(name: &str) -> Option<&'static str> {
1025 if ALLOWED_FUNCTIONS
1026 .iter()
1027 .any(|pattern| matches_pattern(pattern, name))
1028 {
1029 return None;
1030 }
1031 DENIED_FUNCTIONS
1032 .iter()
1033 .find(|entry| matches_pattern(entry.0, name))
1034 .map(|entry| entry.1)
1035}
1036
1037fn matches_pattern(pattern: &str, name: &str) -> bool {
1038 match pattern.strip_suffix('*') {
1039 Some(prefix) => name.starts_with(prefix),
1040 None => pattern == name,
1041 }
1042}
1043
1044fn dotted_denied(name: &str, reason: &str) -> Rejection {
1045 let message = format!(
1046 "\"{name}\" after a dot would call the function {name}(), which is not allowed: {reason}. If it is a column of yours, give it another name with AS in a subquery."
1047 );
1048 reject("function_denied", message)
1049}
1050
1051fn function_denied(name: &str, reason: &str) -> Rejection {
1052 reject(
1053 "function_denied",
1054 format!("Function {name}() is not allowed: {reason}."),
1055 )
1056}
1057
1058fn statement_kind_name(variant: &str) -> String {
1060 let known = match variant {
1061 "InsertStmt" => "INSERT",
1062 "UpdateStmt" => "UPDATE",
1063 "DeleteStmt" => "DELETE",
1064 "MergeStmt" => "MERGE",
1065 "VariableSetStmt" => "SET",
1066 "TransactionStmt" => "transaction control",
1067 "CopyStmt" => "COPY",
1068 "DoStmt" => "DO",
1069 "CallStmt" => "CALL",
1070 "CreateStmt" | "CreateTableAsStmt" => "CREATE",
1071 "DropStmt" => "DROP",
1072 "AlterTableStmt" => "ALTER",
1073 "TruncateStmt" => "TRUNCATE",
1074 "GrantStmt" | "GrantRoleStmt" => "GRANT/REVOKE",
1075 "ListenStmt" => "LISTEN",
1076 "NotifyStmt" => "NOTIFY",
1077 "PrepareStmt" => "PREPARE",
1078 "ExecuteStmt" => "EXECUTE",
1079 "DeclareCursorStmt" => "DECLARE",
1080 "FetchStmt" => "FETCH",
1081 "LockStmt" => "LOCK",
1082 "DiscardStmt" => "DISCARD",
1083 "VacuumStmt" => "VACUUM/ANALYZE",
1084 "RefreshMatViewStmt" => "REFRESH MATERIALIZED VIEW",
1085 "SecLabelStmt" => "SECURITY LABEL",
1086 other => {
1087 return other
1088 .strip_suffix("Stmt")
1089 .unwrap_or(other)
1090 .to_ascii_uppercase();
1091 }
1092 };
1093 known.to_string()
1094}
1095
1096fn statement_not_allowed(variant: &str) -> Rejection {
1097 let message = format!(
1098 "Only read-only statements are accepted (SELECT, WITH, VALUES, TABLE, EXPLAIN, SHOW). This is a {} statement.",
1099 statement_kind_name(variant)
1100 );
1101 reject("statement_not_allowed", message)
1102}
1103
1104fn parse_error_of(error: pg_query::Error) -> Rejection {
1105 match error {
1106 pg_query::Error::Parse(message) => {
1107 reject("parse_error", format!("SQL syntax error: {message}"))
1108 }
1109 other => parse_failed(other.to_string()),
1110 }
1111}
1112
1113fn parse_failed(detail: impl std::fmt::Display) -> Rejection {
1114 reject("parse_error", format!("SQL could not be parsed: {detail}"))
1115}
1116
1117fn malformed() -> Rejection {
1118 parse_failed("unexpected parse tree")
1119}
1120
1121fn reject(code: &'static str, message: impl Into<String>) -> Rejection {
1122 Rejection {
1123 code,
1124 message: message.into(),
1125 }
1126}
1127
1128fn node_of(wrapper: &Value) -> Option<(&str, &Value)> {
1130 let map = wrapper.as_object()?;
1131 if map.len() != 1 {
1132 return None;
1133 }
1134 let inner = map.get("node")?.as_object()?;
1135 if inner.len() != 1 {
1136 return None;
1137 }
1138 let (variant, body) = inner.iter().next()?;
1139 Some((variant.as_str(), body))
1140}
1141
1142fn items<'a>(value: &'a Value, key: &str) -> &'a [Value] {
1143 match value.get(key) {
1144 Some(Value::Array(list)) => list.as_slice(),
1145 _ => &[],
1146 }
1147}
1148
1149fn str_field<'a>(value: &'a Value, key: &str) -> Option<&'a str> {
1150 value.get(key).and_then(Value::as_str)
1151}
1152
1153fn is_constant(arg: &Value) -> bool {
1155 node_of(arg).is_some_and(|(variant, _)| variant == "AConst")
1156}
1157
1158fn string_constant(arg: &Value) -> Option<&str> {
1160 let (variant, body) = node_of(arg)?;
1161 if variant != "AConst" {
1162 return None;
1163 }
1164 str_field(body.get("val")?.get("Sval")?, "sval")
1165}