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