Skip to main content

demesne_postgres/
drift.rs

1use crate::{Error, query_error};
2use demesne_emit_sql::{Object, objects, revoked_from_public};
3use demesne_runtime::quote_literal;
4use postgres::{Client, Transaction};
5use std::collections::{BTreeMap, BTreeSet};
6
7/// How a live object differs from the spec's.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
9#[non_exhaustive]
10pub enum DriftKind {
11    /// The spec creates it and the database has no such object.
12    Missing,
13    /// Both have it, with different definitions.
14    Changed,
15    /// The spec's statement for it does not compile against the live database.
16    Invalid,
17    /// The database has it where the spec governs, and the spec does not create it.
18    Orphan,
19    /// An allow-list entry that no live orphan matches.
20    Stale,
21}
22
23impl DriftKind {
24    /// The label `demesne diff` prints for it.
25    #[must_use]
26    pub fn label(self) -> &'static str {
27        match self {
28            Self::Missing => "MISSING",
29            Self::Changed => "CHANGED",
30            Self::Invalid => "INVALID",
31            Self::Orphan => "ORPHAN",
32            Self::Stale => "STALE",
33        }
34    }
35}
36
37/// One difference between the live database and the spec's SQL.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct Finding {
40    /// What kind of difference it is.
41    pub kind: DriftKind,
42    /// The object, such as `policy notes_select on public.notes` or `function auth.f(text)`.
43    pub object: String,
44    /// What differs, or what to do about it.
45    pub detail: String,
46}
47
48/// Every difference between the live database and the spec's SQL, and how many objects match.
49#[derive(Debug, Clone, Default, PartialEq, Eq)]
50pub struct Drift {
51    /// The differences: tables, policies, functions, then triggers, each in the order the SQL creates them, then orphans and stale allow entries.
52    pub findings: Vec<Finding>,
53    /// Policies whose live definition is the generated one.
54    pub policies: usize,
55    /// Functions whose live definition is the generated one.
56    pub functions: usize,
57    /// Triggers whose live definition is the generated one.
58    pub triggers: usize,
59}
60
61/// Compares the live database with `sql`, the spec's whole SQL, in both directions.
62///
63/// Policies are compared by command, roles, permissive, `USING` and `WITH CHECK`, and functions and triggers by their whole definition. A function the SQL revokes `EXECUTE` on from PUBLIC is also changed when PUBLIC may execute it live. Orphans are the policies on a governed table, and the functions in a definer schema or triggers calling them, that the SQL does not create.
64///
65/// Each generated object is created as a temporary copy and read back, so both sides are compared as Postgres deparses them. Nothing outside the session's temporary schema is created, and the transaction is rolled back. An `allow` entry is an orphan's object text, such as `function auth.f(text)`, to leave unreported; an entry that matches no orphan is reported as stale.
66///
67/// # Errors
68///
69/// The SQL creates an object the manifest does not record, or a catalog query fails.
70pub fn drift(client: &mut Client, sql: &str, allow: &[String]) -> Result<Drift, Error> {
71    let objs = objects(sql).map_err(|e| Error::sql(e.to_string()))?;
72    let revoked = revoked_from_public(sql).into_iter().collect();
73    compare(client, &objs, &revoked, allow).map_err(Error::query)
74}
75
76fn compare(client: &mut Client, objs: &[(Object, String)], revoked: &BTreeSet<String>, allow: &[String]) -> Result<Drift, String> {
77    let mut tx = client.transaction().map_err(|e| query_error(&e))?;
78    tx.batch_execute("SET LOCAL check_function_bodies = off; SELECT set_config('search_path', current_setting('search_path') || ', pg_temp', true)")
79        .map_err(|e| query_error(&e))?;
80    let mut c = Comparison {
81        objs,
82        revoked,
83        live: BTreeMap::new(),
84        shadow: BTreeMap::new(),
85        governed: BTreeSet::new(),
86        scratch: BTreeMap::new(),
87        invalid: BTreeMap::new(),
88        schemas: Vec::new(),
89        out: Drift::default(),
90        orphans: Vec::new(),
91    };
92    c.shadow_tables(&mut tx)?;
93    c.create_generated(&mut tx);
94    tx.batch_execute("SET LOCAL search_path = ''").map_err(|e| query_error(&e))?;
95    c.policies(&mut tx)?;
96    c.functions(&mut tx)?;
97    c.triggers(&mut tx)?;
98    tx.rollback().map_err(|e| query_error(&e))?;
99    Ok(c.finish(allow))
100}
101
102#[derive(Debug, Clone, PartialEq, Eq)]
103struct PolicyDef {
104    cmd: String,
105    permissive: bool,
106    roles: Vec<String>,
107    using: String,
108    check: String,
109}
110
111struct Comparison<'a> {
112    objs: &'a [(Object, String)],
113    revoked: &'a BTreeSet<String>,
114    live: BTreeMap<String, u32>,
115    shadow: BTreeMap<String, (String, u32)>,
116    governed: BTreeSet<String>,
117    scratch: BTreeMap<Object, String>,
118    invalid: BTreeMap<Object, String>,
119    schemas: Vec<u32>,
120    out: Drift,
121    orphans: Vec<Finding>,
122}
123
124impl Comparison<'_> {
125    fn found(&mut self, kind: DriftKind, object: String, detail: String) {
126        self.out.findings.push(Finding { kind, object, detail });
127    }
128
129    fn shadow_tables(&mut self, tx: &mut Transaction<'_>) -> Result<(), String> {
130        let mut tables = BTreeSet::new();
131        for (o, _) in self.objs {
132            match o {
133                Object::Policy { table, .. } | Object::Rls(table) => {
134                    tables.insert(table.clone());
135                    self.governed.insert(table.clone());
136                }
137                Object::Trigger { table, .. } => {
138                    tables.insert(table.clone());
139                }
140                _ => {}
141            }
142        }
143        let mut used = BTreeSet::new();
144        for (i, t) in tables.into_iter().enumerate() {
145            let row = tx
146                .query_one(
147                    "SELECT to_regclass($1)::oid, (SELECT string_agg(format('%I %s', attname, format_type(atttypid, atttypmod)), ', ' ORDER BY attnum)
148                       FROM pg_attribute WHERE attrelid = to_regclass($1) AND attnum > 0 AND NOT attisdropped)",
149                    &[&t],
150                )
151                .map_err(|e| query_error(&e))?;
152            let Some(oid) = row.get::<_, Option<u32>>(0) else {
153                self.found(DriftKind::Missing, format!("table {t}"), "the spec governs it, but the database has no such table".into());
154                continue;
155            };
156            let bare = t.rsplit_once('.').map_or(t.as_str(), |(_, b)| b).to_string();
157            let name = if used.insert(bare.clone()) { bare } else { format!("demesne_shadow_{i}") };
158            let cols: Option<String> = row.get(1);
159            tx.batch_execute(&format!("CREATE TEMP TABLE {name} ({})", cols.unwrap_or_default())).map_err(|e| query_error(&e))?;
160            let shadow_oid: u32 =
161                tx.query_one(&format!("SELECT {}::regclass::oid", quote_literal(&format!("pg_temp.{name}"))), &[]).map_err(|e| query_error(&e))?.get(0);
162            self.live.insert(t.clone(), oid);
163            self.shadow.insert(t, (name, shadow_oid));
164        }
165        Ok(())
166    }
167
168    fn create_generated(&mut self, tx: &mut Transaction<'_>) {
169        for (i, (o, stmt)) in self.objs.iter().enumerate() {
170            let scratch = match o {
171                Object::Function(sig) => {
172                    let name = format!("pg_temp.demesne_fn_{i}");
173                    self.scratch.insert(o.clone(), format!("{name}{}", arguments(sig)));
174                    renamed(stmt, &name)
175                }
176                Object::Policy { table, .. } | Object::Trigger { table, .. } => {
177                    self.shadow.get(table).and_then(|(name, _)| retarget(stmt, table, &format!("pg_temp.{name}")))
178                }
179                _ => None,
180            };
181            let Some(scratch) = scratch else { continue };
182            if let Err(e) = attempt(tx, &scratch) {
183                self.invalid.insert(o.clone(), e);
184            }
185        }
186    }
187
188    fn policies(&mut self, tx: &mut Transaction<'_>) -> Result<(), String> {
189        let mut by_oid: BTreeMap<u32, (String, bool)> = self.live.iter().map(|(t, oid)| (*oid, (t.clone(), false))).collect();
190        by_oid.extend(self.shadow.iter().map(|(t, (_, oid))| (*oid, (t.clone(), true))));
191        let oids: Vec<u32> = by_oid.keys().copied().collect();
192        let rows = tx
193            .query(
194                "SELECT pol.polrelid, pol.polname::text, pol.polcmd::text, pol.polpermissive,
195                        ARRAY(SELECT CASE WHEN r = 0 THEN 'public' ELSE pg_get_userbyid(r)::text END FROM unnest(pol.polroles) r ORDER BY 1),
196                        coalesce(pg_get_expr(pol.polqual, pol.polrelid), ''), coalesce(pg_get_expr(pol.polwithcheck, pol.polrelid), '')
197                   FROM pg_policy pol WHERE pol.polrelid = ANY($1)",
198                &[&oids],
199            )
200            .map_err(|e| query_error(&e))?;
201        let mut live = BTreeMap::new();
202        let mut generated = BTreeMap::new();
203        for row in rows {
204            let Some((table, is_shadow)) = by_oid.get(&row.get::<_, u32>(0)) else { continue };
205            let def =
206                PolicyDef { cmd: command(&row.get::<_, String>(2)).into(), permissive: row.get(3), roles: row.get(4), using: row.get(5), check: row.get(6) };
207            let side = if *is_shadow { &mut generated } else { &mut live };
208            side.insert((table.clone(), row.get::<_, String>(1)), def);
209        }
210        let mut wanted = BTreeSet::new();
211        for (o, _) in self.objs {
212            let Object::Policy { table, name } = o else { continue };
213            let key = (table.clone(), name.clone());
214            wanted.insert(key.clone());
215            let object = format!("policy {name} on {table}");
216            if !self.live.contains_key(table) {
217                continue;
218            }
219            if let Some(e) = self.invalid.get(o).cloned() {
220                self.found(DriftKind::Invalid, object, format!("the generated policy does not compile against the live database: {e}"));
221                continue;
222            }
223            match (live.get(&key), generated.get(&key)) {
224                (None, _) => self.found(DriftKind::Missing, object, "generated but not live (apply it)".into()),
225                (Some(l), Some(g)) if l != g => self.found(DriftKind::Changed, object, policy_change(l, g)),
226                _ => self.out.policies += 1,
227            }
228        }
229        for (table, name) in live.keys() {
230            if self.governed.contains(table) && !wanted.contains(&(table.clone(), name.clone())) {
231                self.orphans.push(Finding {
232                    kind: DriftKind::Orphan,
233                    object: format!("policy {name} on {table}"),
234                    detail: "live on a governed table but not generated (remove it, or model it)".into(),
235                });
236            }
237        }
238        Ok(())
239    }
240
241    fn functions(&mut self, tx: &mut Transaction<'_>) -> Result<(), String> {
242        let mut schemas = BTreeSet::new();
243        let mut generated_oids: Vec<u32> = Vec::new();
244        for (o, _) in self.objs {
245            let Object::Function(sig) = o else { continue };
246            let object = format!("function {sig}");
247            let row = tx.query_one("SELECT to_regnamespace($1)::oid, to_regprocedure($2)::oid", &[&schema_of(sig), sig]).map_err(|e| query_error(&e))?;
248            schemas.extend(row.get::<_, Option<u32>>(0));
249            let live_oid = row.get::<_, Option<u32>>(1);
250            generated_oids.extend(live_oid);
251            if let Some(e) = self.invalid.get(o).cloned() {
252                self.found(DriftKind::Invalid, object, format!("the generated function does not compile against the live database: {e}"));
253                continue;
254            }
255            let Some(live_oid) = live_oid else {
256                self.found(DriftKind::Missing, object, "generated but not live (apply it)".into());
257                continue;
258            };
259            let open = self.revoked.contains(sig)
260                && tx.query_one("SELECT has_function_privilege('public', $1::oid, 'EXECUTE')", &[&live_oid]).map_err(|e| query_error(&e))?.get::<_, bool>(0);
261            if open {
262                self.found(DriftKind::Changed, object.clone(), "PUBLIC may execute it, and the generated SQL revokes that (re-apply it)".into());
263            }
264            let scratch = self.scratch.get(o).cloned().unwrap_or_default();
265            let defs = tx
266                .query_one("SELECT pg_get_functiondef($1), pg_get_functiondef(to_regprocedure($2)::oid)", &[&live_oid, &scratch])
267                .map_err(|e| query_error(&e))?;
268            let (live, generated): (String, String) = (defs.get(0), defs.get(1));
269            match first_difference(after_name(&live), after_name(&generated)) {
270                Some((l, g)) => {
271                    self.found(DriftKind::Changed, object, format!("its live definition is not the generated one (re-apply it): live `{l}`, generated `{g}`"));
272                }
273                None if !open => self.out.functions += 1,
274                None => {}
275            }
276        }
277        self.schemas = schemas.into_iter().collect();
278        let rows = tx
279            .query(
280                "SELECT p.oid::regprocedure::text FROM pg_proc p WHERE p.pronamespace = ANY($1) AND NOT (p.oid = ANY($2)) ORDER BY 1",
281                &[&self.schemas, &generated_oids],
282            )
283            .map_err(|e| query_error(&e))?;
284        for row in rows {
285            self.orphans.push(Finding {
286                kind: DriftKind::Orphan,
287                object: format!("function {}", row.get::<_, String>(0)),
288                detail: "live in a definer schema but not generated (drop it, or allow it)".into(),
289            });
290        }
291        Ok(())
292    }
293
294    fn triggers(&mut self, tx: &mut Transaction<'_>) -> Result<(), String> {
295        let mut wanted = BTreeSet::new();
296        for (o, _) in self.objs {
297            let Object::Trigger { table, name } = o else { continue };
298            wanted.insert((table.clone(), name.clone()));
299            let object = format!("trigger {name} on {table}");
300            let (Some(live_oid), Some((shadow, shadow_oid))) = (self.live.get(table).copied(), self.shadow.get(table).cloned()) else { continue };
301            if let Some(e) = self.invalid.get(o).cloned() {
302                self.found(DriftKind::Invalid, object, format!("the generated trigger does not compile against the live database: {e}"));
303                continue;
304            }
305            let row = tx
306                .query_one(
307                    "SELECT (SELECT pg_get_triggerdef(oid) FROM pg_trigger WHERE tgrelid = $1 AND tgname = $3 AND NOT tgisinternal),
308                            (SELECT pg_get_triggerdef(oid) FROM pg_trigger WHERE tgrelid = $2 AND tgname = $3),
309                            $1::regclass::text",
310                    &[&live_oid, &shadow_oid, name],
311                )
312                .map_err(|e| query_error(&e))?;
313            let (live, generated, live_table): (Option<String>, Option<String>, String) = (row.get(0), row.get(1), row.get(2));
314            let Some(live) = live else {
315                self.found(DriftKind::Missing, object, "generated but not live (apply it)".into());
316                continue;
317            };
318            let generated = generated.unwrap_or_default().replacen(&format!("pg_temp.{shadow}"), &live_table, 1);
319            if live == generated {
320                self.out.triggers += 1;
321            } else {
322                self.found(DriftKind::Changed, object, format!("live `{live}`, generated `{generated}`"));
323            }
324        }
325        let by_oid: BTreeMap<u32, String> = self.live.iter().map(|(t, oid)| (*oid, t.clone())).collect();
326        let oids: Vec<u32> = by_oid.keys().copied().collect();
327        let rows = tx
328            .query(
329                "SELECT t.tgrelid, t.tgname::text FROM pg_trigger t JOIN pg_proc p ON p.oid = t.tgfoid
330                  WHERE NOT t.tgisinternal AND t.tgrelid = ANY($1) AND p.pronamespace = ANY($2) ORDER BY 1, 2",
331                &[&oids, &self.schemas],
332            )
333            .map_err(|e| query_error(&e))?;
334        for row in rows {
335            let (Some(table), name) = (by_oid.get(&row.get::<_, u32>(0)), row.get::<_, String>(1)) else { continue };
336            if !wanted.contains(&(table.clone(), name.clone())) {
337                self.orphans.push(Finding {
338                    kind: DriftKind::Orphan,
339                    object: format!("trigger {name} on {table}"),
340                    detail: "live, calling a definer-schema function, but not generated (drop it, or allow it)".into(),
341                });
342            }
343        }
344        Ok(())
345    }
346
347    fn finish(mut self, allow: &[String]) -> Drift {
348        let allowed: BTreeSet<&str> = allow.iter().map(String::as_str).collect();
349        let orphaned: BTreeSet<String> = self.orphans.iter().map(|f| f.object.clone()).collect();
350        self.out.findings.extend(self.orphans.into_iter().filter(|f| !allowed.contains(f.object.as_str())));
351        self.out.findings.extend(allowed.into_iter().filter(|a| !orphaned.contains(*a)).map(|a| Finding {
352            kind: DriftKind::Stale,
353            object: a.to_string(),
354            detail: "allowed as an orphan, but nothing live matches it (remove the entry)".into(),
355        }));
356        self.out
357    }
358}
359
360fn attempt(tx: &mut Transaction<'_>, stmt: &str) -> Result<(), String> {
361    let mut sp = tx.savepoint("demesne_diff").map_err(|e| query_error(&e))?;
362    match sp.batch_execute(stmt) {
363        Ok(()) => sp.commit().map_err(|e| query_error(&e)),
364        Err(e) => Err(e.as_db_error().map_or_else(|| query_error(&e), |d| d.message().to_string())),
365    }
366}
367
368fn command(polcmd: &str) -> &'static str {
369    match polcmd {
370        "r" => "SELECT",
371        "a" => "INSERT",
372        "w" => "UPDATE",
373        "d" => "DELETE",
374        _ => "ALL",
375    }
376}
377
378fn policy_change(live: &PolicyDef, generated: &PolicyDef) -> String {
379    let mut parts = Vec::new();
380    if live.cmd != generated.cmd {
381        parts.push(format!("command: live {}, generated {}", live.cmd, generated.cmd));
382    }
383    if live.permissive != generated.permissive {
384        let kind = |p: bool| if p { "permissive" } else { "restrictive" };
385        parts.push(format!("live {}, generated {}", kind(live.permissive), kind(generated.permissive)));
386    }
387    if live.roles != generated.roles {
388        parts.push(format!("roles: live {}, generated {}", live.roles.join(", "), generated.roles.join(", ")));
389    }
390    if live.using != generated.using {
391        parts.push(format!("USING: live `{}`, generated `{}`", live.using, generated.using));
392    }
393    if live.check != generated.check {
394        parts.push(format!("WITH CHECK: live `{}`, generated `{}`", live.check, generated.check));
395    }
396    parts.join("; ")
397}
398
399fn schema_of(sig: &str) -> String {
400    let name = sig.split('(').next().unwrap_or_default();
401    name.rsplit_once('.').map(|(schema, _)| schema.to_string()).unwrap_or_default()
402}
403
404fn arguments(sig: &str) -> &str {
405    sig.find('(').map_or("()", |k| &sig[k..])
406}
407
408fn renamed(stmt: &str, name: &str) -> Option<String> {
409    let start = stmt.find("FUNCTION")? + "FUNCTION".len();
410    let open = start + stmt[start..].find('(')?;
411    Some(format!("{} {name}{}", &stmt[..start], &stmt[open..]))
412}
413
414fn retarget(stmt: &str, table: &str, to: &str) -> Option<String> {
415    let needle = format!(" ON {table}");
416    let mut from = 0;
417    while let Some(k) = stmt[from..].find(&needle).map(|k| from + k) {
418        let end = k + needle.len();
419        if stmt[end..].chars().next().is_none_or(char::is_whitespace) {
420            return Some(format!("{} ON {to}{}", &stmt[..k], &stmt[end..]));
421        }
422        from = end;
423    }
424    None
425}
426
427fn after_name(def: &str) -> &str {
428    def.split_once('(').map_or(def, |(_, rest)| rest)
429}
430
431fn first_difference<'a>(live: &'a str, generated: &'a str) -> Option<(&'a str, &'a str)> {
432    if live == generated {
433        return None;
434    }
435    let mut l = live.lines();
436    let mut g = generated.lines();
437    loop {
438        match (l.next(), g.next()) {
439            (Some(a), Some(b)) if a == b => {}
440            (a, b) => return Some((a.unwrap_or("<end>").trim(), b.unwrap_or("<end>").trim())),
441        }
442    }
443}