Skip to main content

demesne_cli/
lib.rs

1#![doc = "The demesne command line's pure commands (validate, emit, help, version) over a `Files` source, shared by the native binary and the WASM build. Its errors are messages to print; the library crates (`demesne-model`, `demesne-emit-sql`, `demesne-postgres` and the emitters) return typed errors."]
2
3use demesne_emit_sql::{Manifest, Sql, definers_sql};
4use demesne_gocompat::quote;
5use demesne_model::{SpecExt, pdp::emit_pdp};
6use demesne_syntax::{Spec, SpecFiles};
7use std::io;
8
9pub const USAGE: &str = "demesne — RLS-compiled ReBAC authorization, point it at your database.
10
11USAGE:
12  demesne validate <spec.demesne>...           parse + validate a spec
13  demesne emit     <spec.demesne>... [kind]    print generated SQL
14                                               kind: rls|definers|enablement|triggers|pdp|all (default all)
15                                               manifest: JSON record of every object the SQL creates
16                                               migrate <manifest.json>: all, then exact drops of what that
17                                                            manifest's surface had and this spec no longer emits
18                                               --file <spec.demesne>: one file's share of a spec in several
19                                                            files (kind all, manifest or migrate)
20                                               --target ts: emit TypeScript (@foir/demesne)
21                                                            kind: claims|pdp|projections|framework|all
22                                               --profile supabase: emit the Supabase
23                                                            deployment profile (access-token hook)
24                                               v1 generates no Go; use demesne v0.93.1 for Go
25  demesne introspect <dsn>                     summarise the live schema (tables/columns/FKs)
26  demesne scaffold   [-i] <dsn>                generate a STARTER spec from the schema (-i: interactive)
27  demesne check    <spec.demesne> <dsn>        validate the spec, bind it to the live schema, check the RLS role,
28                                               and look for schema traps (owner-rights views, NULL-blind unique
29                                               scope indexes, policy comparisons that can't use an index)
30  demesne diff     <spec.demesne> <dsn> [--exit-code] [--allow <file>]
31                                               generated-vs-live drift, both ways: policies, definers, triggers
32                                               and orphans; --exit-code fails (exit 1) on any drift (CI guard);
33                                               --allow lists orphans to leave unreported, one per line
34  demesne coverage <spec.demesne> <dsn> [--exit-code]   ungoverned tables (no object → no RLS); --exit-code fails (exit 1) if any (CI guard)
35  demesne version                              print the build version
36
37<spec.demesne>... is a spec in one file, or in several, given in order: each file may refer to what the
38files before it declare, and may `replace` a declaration of theirs.
39<dsn> may be omitted to use $DATABASE_URL. A Postgres connection string, e.g.
40  postgres://user:pass@host:5432/db
41";
42
43pub type R = Result<(), String>;
44
45const NO_GO: &str = "v1 generates no Go: use --target ts for TypeScript, or demesne v0.93.1 for Go";
46
47#[derive(Debug, Default)]
48pub struct Out {
49    pub buf: Vec<u8>,
50    pub err: Vec<u8>,
51}
52
53impl Out {
54    pub fn print(&mut self, s: &str) {
55        self.buf.extend_from_slice(s.as_bytes());
56    }
57
58    pub fn warn_spec(&mut self, path: &str, s: &Spec) {
59        for w in demesne_emit_sql::validate_warnings(s) {
60            self.err.extend_from_slice(format!("warning: {path}: {w}\n").as_bytes());
61        }
62    }
63
64    /// Prints the warnings a loaded spec earns, each naming its file.
65    pub fn warn_loaded(&mut self, paths: &[String], loaded: &Loaded) {
66        match loaded {
67            Loaded::One(s) => self.warn_spec(&paths[0], s),
68            Loaded::Many(files) => {
69                for w in demesne_emit_sql::validate_files_warnings(files) {
70                    self.err.extend_from_slice(format!("warning: {w}\n").as_bytes());
71                }
72            }
73        }
74    }
75}
76
77/// A spec a command has loaded: written in one file, or in several compiled as one model.
78#[derive(Debug, Clone)]
79pub enum Loaded {
80    One(Box<Spec>),
81    Many(SpecFiles),
82}
83
84impl Loaded {
85    /// Returns the spec, of every file when it has several.
86    #[must_use]
87    pub fn spec(&self) -> &Spec {
88        match self {
89            Loaded::One(s) => s,
90            Loaded::Many(files) => files.spec(),
91        }
92    }
93}
94
95/// Splits a command's arguments into its spec files and the arguments after them.
96///
97/// The spec files are the first argument and every argument straight after it that ends in `.demesne`.
98#[must_use]
99pub fn spec_args(args: &[String]) -> (Vec<String>, Vec<String>) {
100    let n = args.iter().skip(1).take_while(|a| a.ends_with(".demesne")).count() + usize::from(!args.is_empty());
101    (args[..n].to_vec(), args[n..].to_vec())
102}
103
104/// Reads, parses and validates a spec in one file or in several.
105///
106/// # Errors
107///
108/// A file cannot be read, or the spec does not parse or validate. A spec in several files validates one prefix at a
109/// time, and each finding names its file.
110pub fn load_specs(files: &dyn Files, paths: &[String]) -> Result<Loaded, String> {
111    if let [path] = paths {
112        return load_spec(files, path).map(|s| Loaded::One(Box::new(s)));
113    }
114    let texts = paths.iter().map(|p| files.read(p)).collect::<Result<Vec<_>, _>>()?;
115    let spec = demesne_syntax::parse_files(paths.iter().map(String::as_str).zip(texts.iter().map(Vec::as_slice))).map_err(|e| format!("parse: {e}"))?;
116    demesne_emit_sql::validate_files(&spec).map_err(|e| format!("validate: {e}"))?;
117    Ok(Loaded::Many(spec))
118}
119
120#[must_use]
121pub fn build_version() -> &'static str {
122    match option_env!("DEMESNE_VERSION") {
123        Some(v) => v,
124        None => env!("CARGO_PKG_VERSION"),
125    }
126}
127
128pub trait Files {
129    /// Reads the whole file at `path`.
130    ///
131    /// # Errors
132    ///
133    /// The file cannot be read. The message matches the Go CLI's.
134    fn read(&self, path: &str) -> Result<Vec<u8>, String>;
135}
136
137#[derive(Debug)]
138pub struct OsFiles;
139
140impl Files for OsFiles {
141    fn read(&self, path: &str) -> Result<Vec<u8>, String> {
142        std::fs::read(path).map_err(|e| go_read_error(path, &e))
143    }
144}
145
146#[derive(Debug, Clone, PartialEq, Eq)]
147pub struct Output {
148    pub code: u8,
149    pub stdout: Vec<u8>,
150    pub stderr: Vec<u8>,
151}
152
153#[must_use]
154pub fn finish(out: Out, res: R) -> Output {
155    match res {
156        Ok(()) => Output { code: 0, stdout: out.buf, stderr: out.err },
157        Err(e) => {
158            let mut stderr = out.err;
159            stderr.extend_from_slice(format!("demesne: {e}\n").as_bytes());
160            Output { code: 1, stdout: out.buf, stderr }
161        }
162    }
163}
164
165pub const LIVE_COMMANDS: &[&str] = &["introspect", "scaffold", "check", "diff", "coverage"];
166
167pub fn run_pure(args: &[String], files: &dyn Files) -> Option<Output> {
168    let Some(cmd) = args.first() else {
169        return Some(Output { code: 2, stdout: Vec::new(), stderr: USAGE.as_bytes().to_vec() });
170    };
171    let rest = &args[1..];
172    let mut out = Out::default();
173    let res = match cmd.as_str() {
174        "validate" => cmd_validate(&mut out, files, rest),
175        "emit" => cmd_emit(&mut out, files, rest),
176        "version" | "--version" | "-v" => return Some(Output { code: 0, stdout: format!("{}\n", build_version()).into_bytes(), stderr: Vec::new() }),
177        "help" | "-h" | "--help" => return Some(Output { code: 0, stdout: USAGE.as_bytes().to_vec(), stderr: Vec::new() }),
178        c if LIVE_COMMANDS.contains(&c) => return None,
179        other => {
180            return Some(Output { code: 2, stdout: Vec::new(), stderr: format!("demesne: unknown command {}\n\n{USAGE}", quote(other)).into_bytes() });
181        }
182    };
183    Some(finish(out, res))
184}
185
186#[must_use]
187pub fn go_read_error(path: &str, e: &io::Error) -> String {
188    match e.kind() {
189        io::ErrorKind::NotFound => format!("open {path}: no such file or directory"),
190        io::ErrorKind::PermissionDenied => format!("open {path}: permission denied"),
191        io::ErrorKind::IsADirectory => format!("read {path}: is a directory"),
192        _ => format!("open {path}: {e}"),
193    }
194}
195
196/// Reads, parses and validates the spec at `path`.
197///
198/// # Errors
199///
200/// The file cannot be read, or the spec does not parse or validate.
201pub fn load_spec(files: &dyn Files, path: &str) -> Result<Spec, String> {
202    let src = files.read(path)?;
203    let s = demesne_syntax::parse_bytes(&src).map_err(|e| format!("parse {path}: {e}"))?;
204    demesne_emit_sql::validate(&s).map_err(|e| format!("validate {path}: {e}"))?;
205    Ok(s)
206}
207
208/// Checks a command received at least `n` arguments.
209///
210/// # Errors
211///
212/// Fewer than `n` arguments; the message names the missing `what`.
213pub fn need(args: &[String], n: usize, what: &str) -> R {
214    if args.len() < n {
215        return Err(format!("missing argument: {what}"));
216    }
217    Ok(())
218}
219
220fn cmd_validate(out: &mut Out, files: &dyn Files, args: &[String]) -> R {
221    need(args, 1, "<spec.demesne>")?;
222    let (paths, _) = spec_args(args);
223    let loaded = load_specs(files, &paths)?;
224    out.warn_loaded(&paths, &loaded);
225    let s = loaded.spec();
226    let rls = Sql::new(s).emit_rls().map_err(|e| e.to_string())?;
227    out.print(&format!(
228        "ok: {} objects, {} levels, {} policies, {} reachability grants\n",
229        s.objects.len(),
230        s.levels().len(),
231        rls.policies.len(),
232        s.reach_grants().len()
233    ));
234    Ok(())
235}
236
237#[must_use]
238pub fn strip_flag(args: &[String], name: &str, def: &str) -> (String, Vec<String>) {
239    let mut val = def.to_string();
240    let pfx = format!("--{name}=");
241    let flag = format!("--{name}");
242    let mut out = Vec::new();
243    let mut i = 0;
244    while i < args.len() {
245        let a = &args[i];
246        if *a == flag {
247            if i + 1 < args.len() {
248                val.clone_from(&args[i + 1]);
249                i += 1;
250            }
251        } else if let Some(v) = a.strip_prefix(&pfx) {
252            val = v.to_string();
253        } else {
254            out.push(a.clone());
255        }
256        i += 1;
257    }
258    (val, out)
259}
260
261fn cmd_emit(out: &mut Out, files: &dyn Files, args: &[String]) -> R {
262    let (target, args) = strip_flag(args, "target", "");
263    let (profile, args) = strip_flag(&args, "profile", "");
264    let (file, args) = strip_flag(&args, "file", "");
265    need(&args, 1, "<spec.demesne>")?;
266    let (paths, rest) = spec_args(&args);
267    let loaded = load_specs(files, &paths)?;
268    out.warn_loaded(&paths, &loaded);
269    let kind = rest.first().map_or("all", String::as_str);
270    if !file.is_empty() {
271        if !target.is_empty() || !profile.is_empty() {
272            return Err("--file picks one file's share of the SQL; --target and --profile emit the whole spec, so give them the files it is made of".into());
273        }
274        return emit_file(out, files, &paths, &loaded, &file, kind, &rest);
275    }
276    let s = loaded.spec();
277    if !profile.is_empty() {
278        return emit_profile(out, s, &profile);
279    }
280    match target.as_str() {
281        "" => {}
282        "ts" => return emit_ts(out, s, kind),
283        "go" => return Err(NO_GO.to_string()),
284        other => return Err(format!("unknown --target {} (ts)", quote(other))),
285    }
286    let sql = Sql::new(s);
287    match kind {
288        "definers" => emit_definers_sql(out, &sql),
289        "rls" | "policies" => emit_rls_sql(out, &sql),
290        "enablement" => emit_enablement_sql(out, &sql),
291        "triggers" => {
292            out.print(&sql.triggers_sql());
293            Ok(())
294        }
295        "claims" | "framework" => Err(format!("emit kind {} generated Go. {NO_GO}", quote(kind))),
296        "pdp" => emit_pdp_report(out, s),
297        "all" => emit_all_sql(out, &sql),
298        "manifest" => {
299            out.print(&sql.manifest().map_err(|e| e.to_string())?.to_json());
300            Ok(())
301        }
302        "migrate" => {
303            out.print(&sql.migration(&previous_manifest(files, &rest)?).map_err(|e| e.to_string())?);
304            Ok(())
305        }
306        other => Err(format!("unknown emit kind {} (rls|definers|enablement|triggers|pdp|all|manifest|migrate)", quote(other))),
307    }
308}
309
310fn previous_manifest(files: &dyn Files, rest: &[String]) -> Result<Manifest, String> {
311    let path = rest.get(1).ok_or("missing argument: <spec.demesne> migrate <previous manifest.json>")?;
312    let src = files.read(path)?;
313    Manifest::from_json(&String::from_utf8_lossy(&src)).map_err(|e| format!("{path}: {e}"))
314}
315
316fn emit_file(out: &mut Out, files: &dyn Files, paths: &[String], loaded: &Loaded, file: &str, kind: &str, rest: &[String]) -> R {
317    let k = paths.iter().position(|p| p == file).ok_or_else(|| format!("--file {} names none of the spec's files ({})", quote(file), paths.join(", ")))?;
318    let spec = match loaded {
319        Loaded::Many(spec) => spec.clone(),
320        Loaded::One(_) => {
321            let texts = paths.iter().map(|p| files.read(p)).collect::<Result<Vec<_>, _>>()?;
322            demesne_syntax::parse_files(paths.iter().map(String::as_str).zip(texts.iter().map(Vec::as_slice))).map_err(|e| format!("parse: {e}"))?
323        }
324    };
325    let text = match kind {
326        "all" => demesne_emit_sql::file_sql(&spec, k).map_err(|e| e.to_string())?,
327        "manifest" => Sql::new(spec.prefix(k)).manifest().map_err(|e| e.to_string())?.to_json(),
328        "migrate" => demesne_emit_sql::file_migration(&spec, k, &previous_manifest(files, rest)?).map_err(|e| e.to_string())?,
329        other => {
330            return Err(format!("--file takes the emit kinds all, manifest and migrate, and {} covers the whole spec: emit it without --file", quote(other)));
331        }
332    };
333    out.print(&text);
334    Ok(())
335}
336
337fn emit_profile(out: &mut Out, s: &Spec, profile: &str) -> R {
338    match profile {
339        "supabase" => {
340            let p = Sql::new(s).emit_supabase_profile().map_err(|e| e.to_string())?;
341            out.print(&p);
342            out.print("\n");
343            Ok(())
344        }
345        other => Err(format!("unknown --profile {} (supabase)", quote(other))),
346    }
347}
348
349fn emit_definers_sql(out: &mut Out, sql: &Sql) -> R {
350    let defs = sql.emit_definers().map_err(|e| e.to_string())?;
351    out.print(&definers_sql(&defs));
352    Ok(())
353}
354
355fn emit_rls_sql(out: &mut Out, sql: &Sql) -> R {
356    let res = sql.emit_rls().map_err(|e| e.to_string())?;
357    if !res.unsupported.is_empty() {
358        return Err(format!("spec has uncompilable @rls permissions: {}", res.unsupported.join("; ")));
359    }
360    out.print(&res.policy_sql("authenticated"));
361    Ok(())
362}
363
364fn emit_enablement_sql(out: &mut Out, sql: &Sql) -> R {
365    let res = sql.emit_rls().map_err(|e| e.to_string())?;
366    out.print(&res.enablement_sql());
367    Ok(())
368}
369
370fn emit_pdp_report(out: &mut Out, s: &Spec) -> R {
371    let pdps = emit_pdp(s).map_err(|e| e.to_string())?;
372    for (site, p) in &pdps {
373        out.print(&format!("# PDP {}: {} governed, {} ungoverned\n", quote(site), p.policy.len(), p.ungoverned.len()));
374        for (pr, perm) in p.policy.iter() {
375            out.print(&format!("{pr} -> {perm}\n"));
376        }
377    }
378    Ok(())
379}
380
381fn emit_all_sql(out: &mut Out, sql: &Sql) -> R {
382    let mut b = String::new();
383    let res = sql.write_all_sql(&mut b);
384    out.print(&b);
385    res.map_err(|e| e.to_string())
386}
387
388fn emit_ts(out: &mut Out, s: &Spec, kind: &str) -> R {
389    match kind {
390        "all" | "projections" => {
391            out.print(&demesne_emit_ts::emit_ts(s).map_err(|e| e.to_string())?);
392            Ok(())
393        }
394        "claims" => {
395            out.print(&demesne_emit_ts::render_claims_contract_ts(s, "ClaimsContract").map_err(|e| e.to_string())?);
396            Ok(())
397        }
398        "pdp" => {
399            let pdps = emit_pdp(s).map_err(|e| e.to_string())?;
400            for (i, (site, p)) in pdps.iter().enumerate() {
401                if i > 0 {
402                    out.print("\n");
403                }
404                out.print(&demesne_emit_ts::render_pdp_ts(p, &format!("{site}Policy")));
405            }
406            Ok(())
407        }
408        "framework" => {
409            out.print(&demesne_emit_ts::emit_framework_ts(s).map_err(|e| e.to_string())?);
410            Ok(())
411        }
412        "rls" | "policies" | "definers" | "enablement" | "triggers" => {
413            Err(format!("emit kind {} is language-neutral SQL/DDL — it has no TypeScript target; emit it without --target ts", quote(kind)))
414        }
415        other => Err(format!("unknown emit kind {} for --target ts (claims|pdp|projections|framework|all)", quote(other))),
416    }
417}