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