1use crate::{Error, query_error};
2use postgres::{Client, Transaction};
3use std::collections::{BTreeMap, BTreeSet};
4use std::fmt;
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
8#[non_exhaustive]
9pub enum Severity {
10 Danger,
12 Warning,
14}
15
16impl fmt::Display for Severity {
17 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18 f.write_str(match self {
19 Severity::Danger => "DANGER",
20 Severity::Warning => "warning",
21 })
22 }
23}
24
25#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct Trap {
28 pub severity: Severity,
30 pub message: String,
32}
33
34pub fn schema_traps(client: &mut Client, governed: &[String], scope_columns: &[(String, String)]) -> Result<Vec<Trap>, Error> {
42 read_traps(client, governed, scope_columns).map_err(Error::query)
43}
44
45fn read_traps(client: &mut Client, governed: &[String], scope_columns: &[(String, String)]) -> Result<Vec<Trap>, String> {
46 let mut tx = client.transaction().map_err(|e| query_error(&e))?;
47 tx.batch_execute("SET LOCAL search_path = ''").map_err(|e| query_error(&e))?;
48 let mut oids = Vec::new();
49 for t in governed {
50 let oid: Option<u32> = tx.query_one("SELECT to_regclass($1)::oid", &[t]).map_err(|e| query_error(&e))?.get(0);
51 oids.extend(oid);
52 }
53 let mut traps = owner_views(&mut tx, &oids)?;
54 traps.extend(nullable_unique(&mut tx, scope_columns)?);
55 traps.extend(wrapped_columns(&mut tx, &oids)?);
56 tx.rollback().map_err(|e| query_error(&e))?;
57 Ok(traps)
58}
59
60fn owner_views(tx: &mut Transaction<'_>, governed: &[u32]) -> Result<Vec<Trap>, String> {
61 let rows = tx
62 .query(
63 "WITH RECURSIVE deps AS (
64 SELECT DISTINCT r.ev_class AS view, d.refobjid AS rel
65 FROM pg_rewrite r JOIN pg_depend d ON d.classid = 'pg_rewrite'::regclass AND d.objid = r.oid AND d.refclassid = 'pg_class'::regclass
66 WHERE d.refobjid <> r.ev_class
67 ), over AS (
68 SELECT view, rel AS base FROM deps WHERE rel = ANY($1)
69 UNION
70 SELECT d.view, o.base FROM deps d JOIN over o ON d.rel = o.view
71 )
72 SELECT c.oid::regclass::text, c.relkind = 'm', pg_get_userbyid(c.relowner)::text, ro.rolsuper OR ro.rolbypassrls,
73 string_agg(DISTINCT o.base::regclass::text, ', ' ORDER BY o.base::regclass::text)
74 FROM over o JOIN pg_class c ON c.oid = o.view JOIN pg_roles ro ON ro.oid = c.relowner
75 WHERE NOT coalesce((SELECT option_value::boolean FROM pg_options_to_table(c.reloptions) WHERE option_name = 'security_invoker'), false)
76 GROUP BY c.oid, c.relkind, c.relowner, ro.rolsuper, ro.rolbypassrls
77 ORDER BY 1",
78 &[&governed],
79 )
80 .map_err(|e| query_error(&e))?;
81 Ok(rows
82 .iter()
83 .map(|r| {
84 let (view, materialized, owner, bypasses, bases): (String, bool, String, bool, String) = (r.get(0), r.get(1), r.get(2), r.get(3), r.get(4));
85 let severity = if bypasses { Severity::Danger } else { Severity::Warning };
86 let who = if bypasses { format!("its owner {owner}, who bypasses row level security, so every reader sees every row") } else { format!("its owner {owner}, so the policies judge {owner}, not the reader") };
87 let message = if materialized {
88 format!("materialized view {view} over governed {bases} holds the rows read at refresh by {who}: revoke access to it, or replace it with a view WITH (security_invoker = true)")
89 } else {
90 format!("view {view} over governed {bases} reads as {who}: ALTER VIEW {view} SET (security_invoker = true)")
91 };
92 Trap { severity, message }
93 })
94 .collect())
95}
96
97struct UniqueIndex {
98 name: String,
99 keys: Vec<i16>,
100 exprs: String,
101 pred: String,
102 nulls_not_distinct: bool,
103}
104
105fn nullable_unique(tx: &mut Transaction<'_>, scope_columns: &[(String, String)]) -> Result<Vec<Trap>, String> {
106 let mut by_table: BTreeMap<&str, Vec<String>> = BTreeMap::new();
107 for (t, c) in scope_columns {
108 by_table.entry(t.as_str()).or_default().push(c.clone());
109 }
110 let version: i32 = tx.query_one("SELECT current_setting('server_version_num')::int", &[]).map_err(|e| query_error(&e))?.get(0);
111 let nulls_not_distinct = if version >= 150_000 { "i.indnullsnotdistinct" } else { "false" };
112 let mut traps = Vec::new();
113 for (table, cols) in by_table {
114 let indexes: Vec<UniqueIndex> = tx
115 .query(
116 &format!(
117 "SELECT i.indexrelid::regclass::text, i.indkey::int2[], coalesce(pg_get_expr(i.indexprs, i.indrelid), ''), coalesce(pg_get_expr(i.indpred, i.indrelid), ''), {nulls_not_distinct}
118 FROM pg_index i WHERE i.indisunique AND i.indrelid = to_regclass($1) ORDER BY 1"
119 ),
120 &[&table],
121 )
122 .map_err(|e| query_error(&e))?
123 .iter()
124 .map(|r| UniqueIndex { name: r.get(0), keys: r.get(1), exprs: r.get(2), pred: r.get(3), nulls_not_distinct: r.get(4) })
125 .collect();
126 let nullable: Vec<(i16, String)> = tx
127 .query("SELECT attnum, attname::text FROM pg_attribute WHERE attrelid = to_regclass($1) AND attname = ANY($2) AND attnum > 0 AND NOT attnotnull ORDER BY attnum", &[&table, &cols])
128 .map_err(|e| query_error(&e))?
129 .iter()
130 .map(|r| (r.get(0), r.get(1)))
131 .collect();
132 for u in indexes.iter().filter(|u| !u.nulls_not_distinct) {
133 let open = nullable.iter().filter(|(n, c)| u.keys.contains(n) && !covers_null_tier(&indexes, u, *n, c));
134 traps.extend(open.map(|(_, col)| Trap {
135 severity: Severity::Warning,
136 message: format!(
137 "unique index {} on {table} includes the nullable scope column {col} without NULLS NOT DISTINCT, so rows where {col} is NULL, the shared tier, never conflict: recreate it with NULLS NOT DISTINCT, or add a partial unique index on its other columns WHERE {col} IS NULL",
138 u.name
139 ),
140 }));
141 }
142 }
143 Ok(traps)
144}
145
146fn covers_null_tier(indexes: &[UniqueIndex], u: &UniqueIndex, attnum: i16, col: &str) -> bool {
147 let mut rest: Vec<i16> = u.keys.iter().copied().filter(|k| *k != attnum).collect();
148 rest.sort_unstable();
149 indexes.iter().any(|p| {
150 let mut keys = p.keys.clone();
151 keys.sort_unstable();
152 let mirrors = keys == rest && p.exprs == u.exprs && p.pred.contains(&format!("({col} IS NULL)"));
153 let narrower = p.exprs.is_empty() && p.pred.is_empty() && p.keys.iter().all(|k| rest.contains(k));
154 mirrors || narrower
155 })
156}
157
158fn wrapped_columns(tx: &mut Transaction<'_>, governed: &[u32]) -> Result<Vec<Trap>, String> {
159 let rows = tx
160 .query(
161 "SELECT pol.polname::text, pol.polrelid, pol.polrelid::regclass::text, coalesce(pol.polqual::text, ''), coalesce(pol.polwithcheck::text, '')
162 FROM pg_policy pol WHERE pol.polrelid = ANY($1) ORDER BY 3, 1",
163 &[&governed],
164 )
165 .map_err(|e| query_error(&e))?;
166 let mut traps = Vec::new();
167 for r in rows {
168 let (policy, relid, table): (String, u32, String) = (r.get(0), r.get(1), r.get(2));
169 let mut found = BTreeSet::new();
170 for tree in [r.get::<_, String>(3), r.get::<_, String>(4)] {
171 if let Some(node) = parse(&tree) {
172 comparisons(&node, &mut found);
173 }
174 }
175 for (attno, wrapper) in found {
176 let (function, operator) = wrapper.oids();
177 let row = tx
178 .query_one(
179 "SELECT (SELECT attname::text FROM pg_attribute WHERE attrelid = $1 AND attnum = $2),
180 coalesce((SELECT proname::text FROM pg_proc WHERE oid = $3), (SELECT oprname::text FROM pg_operator WHERE oid = $4))",
181 &[&relid, &attno, &function, &operator],
182 )
183 .map_err(|e| query_error(&e))?;
184 let (col, function): (Option<String>, Option<String>) = (row.get(0), row.get(1));
185 let col = col.unwrap_or_else(|| format!("column {attno}"));
186 traps.push(Trap {
187 severity: Severity::Warning,
188 message: format!(
189 "policy {policy} on {table} compares {col} through {}, so the comparison cannot use an index on {col} and is checked row by row: compare the bare column, or index the expression",
190 wrapper.describe(function.as_deref())
191 ),
192 });
193 }
194 }
195 Ok(traps)
196}
197
198#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
199enum Wrapper {
200 Coalesce,
201 NullIf,
202 Case,
203 Cast,
204 Function(u32),
205 Operator(u32),
206}
207
208impl Wrapper {
209 fn oids(&self) -> (u32, u32) {
210 match self {
211 Self::Function(oid) => (*oid, 0),
212 Self::Operator(oid) => (0, *oid),
213 _ => (0, 0),
214 }
215 }
216
217 fn describe(&self, name: Option<&str>) -> String {
218 let name = |oid: u32| name.map_or_else(|| oid.to_string(), String::from);
219 match self {
220 Self::Coalesce => "COALESCE".into(),
221 Self::NullIf => "NULLIF".into(),
222 Self::Case => "CASE".into(),
223 Self::Cast => "a cast through text".into(),
224 Self::Function(oid) => format!("{}()", name(*oid)),
225 Self::Operator(oid) => format!("the operator {}", name(*oid)),
226 }
227 }
228}
229
230#[derive(Debug, Clone, PartialEq, Eq)]
231enum Node {
232 Struct(String, Vec<(String, Node)>),
233 List(Vec<Node>),
234 Atom(String),
235}
236
237impl Node {
238 fn kind(&self) -> &str {
239 match self {
240 Self::Struct(k, _) => k,
241 _ => "",
242 }
243 }
244
245 fn field(&self, name: &str) -> Option<&Node> {
246 match self {
247 Self::Struct(_, fields) => fields.iter().find(|(f, _)| f == name).map(|(_, v)| v),
248 _ => None,
249 }
250 }
251
252 fn atom(&self, name: &str) -> Option<&str> {
253 match self.field(name) {
254 Some(Self::Atom(a)) => Some(a),
255 _ => None,
256 }
257 }
258
259 fn args(&self) -> &[Node] {
260 match self.field("args") {
261 Some(Self::List(items)) => items,
262 _ => &[],
263 }
264 }
265
266 fn row_column(&self) -> Option<i16> {
267 if self.kind() == "VAR" { self.atom("varattno")?.parse().ok() } else { None }
268 }
269
270 fn wrapped_column(&self) -> Option<i16> {
271 if let Some(col) = self.row_column() {
272 return Some(col);
273 }
274 match self {
275 Self::Struct(kind, fields) if kind != "SUBLINK" => fields.iter().find_map(|(_, v)| v.wrapped_column()),
276 Self::List(items) => items.iter().find_map(Node::wrapped_column),
277 _ => None,
278 }
279 }
280
281 fn wrapper(&self) -> Option<Wrapper> {
282 match self.kind() {
283 "COALESCEEXPR" => Some(Wrapper::Coalesce),
284 "NULLIFEXPR" => Some(Wrapper::NullIf),
285 "CASEEXPR" => Some(Wrapper::Case),
286 "COERCEVIAIO" => Some(Wrapper::Cast),
287 "FUNCEXPR" => self.atom("funcid")?.parse().ok().map(Wrapper::Function),
288 "OPEXPR" => self.atom("opno")?.parse().ok().map(Wrapper::Operator),
289 _ => None,
290 }
291 }
292}
293
294fn comparisons(node: &Node, found: &mut BTreeSet<(i16, Wrapper)>) {
295 match node.kind() {
296 "BOOLEXPR" => node.args().iter().for_each(|a| comparisons(a, found)),
297 "OPEXPR" | "SCALARARRAYOPEXPR" | "DISTINCTEXPR" => {
298 for arg in node.args() {
299 if let (Some(w), Some(col)) = (arg.wrapper(), arg.wrapped_column()) {
300 found.insert((col, w));
301 }
302 }
303 }
304 _ => {}
305 }
306}
307
308fn parse(src: &str) -> Option<Node> {
309 let tokens = tokens(src);
310 let mut i = 0;
311 value(&tokens, &mut i)
312}
313
314fn tokens(src: &str) -> Vec<String> {
315 let mut out = Vec::new();
316 let mut chars = src.chars().peekable();
317 while let Some(c) = chars.next() {
318 match c {
319 c if c.is_whitespace() => {}
320 '{' | '}' | '(' | ')' => out.push(c.to_string()),
321 '[' => {
322 let _ = chars.by_ref().find(|d| *d == ']');
323 out.push("[]".into());
324 }
325 _ => out.push(atom(c, &mut chars)),
326 }
327 }
328 out
329}
330
331fn atom(first: char, chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> String {
332 let mut s = String::new();
333 let mut next = Some(first);
334 while let Some(d) = next {
335 if d == '\\' {
336 s.extend(chars.next());
337 } else {
338 s.push(d);
339 }
340 next = chars.next_if(|d| !d.is_whitespace() && !"{}()".contains(*d));
341 }
342 s
343}
344
345fn value(tokens: &[String], i: &mut usize) -> Option<Node> {
346 let t = tokens.get(*i)?.clone();
347 *i += 1;
348 match t.as_str() {
349 "{" => {
350 let kind = tokens.get(*i)?.clone();
351 *i += 1;
352 let mut fields = Vec::new();
353 while let Some(t) = tokens.get(*i) {
354 if t == "}" {
355 *i += 1;
356 break;
357 }
358 let name = t.strip_prefix(':').map(String::from);
359 *i += 1;
360 let Some(name) = name else { continue };
361 if tokens.get(*i).is_some_and(|n| n == "}" || n.starts_with(':')) {
362 fields.push((name, Node::Atom(String::new())));
363 continue;
364 }
365 let v = value(tokens, i)?;
366 fields.push((name, v));
367 }
368 Some(Node::Struct(kind, fields))
369 }
370 "(" => {
371 let mut items = Vec::new();
372 while tokens.get(*i).is_some_and(|t| t != ")") {
373 items.push(value(tokens, i)?);
374 }
375 *i += 1;
376 Some(Node::List(items))
377 }
378 _ => Some(Node::Atom(t)),
379 }
380}