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