ikigai_script/authority.rs
1//! The three authorities, never merged — and the one computation that decides what a run
2//! may touch.
3//!
4//! 1. **Publish or change**: `urn:cap:script:write:{name}`, and `urn:cap:script:delete:{name}`
5//! to retire.
6//! 2. **Run**: `urn:cap:script:run:{name}`. A **public** script is also runnable by any
7//! holder of [`CAP_RUN_PUBLIC`], which is the grant a host gives its anonymous
8//! principal.
9//! 3. **Runs as**: what [`effective`] computes, applied to the runner's own capability by
10//! attenuation. Never minted.
11//!
12//! Reading a script without running it is a fourth scope, `urn:cap:script:read:{name}`
13//! (or [`CAP_READ_PUBLIC`] for a public, published script): source code is not the same
14//! sensitivity as running it, the same split `ikigai-ledger` draws between read and write.
15//!
16//! # Runs as: the least of four
17//!
18//! A run executes under
19//!
20//! ```text
21//! runner.attenuate( { s in declared : s in granted-at-publish and ceiling.allows(s) }
22//! + the publisher's exclusions + the ceiling's exclusions )
23//! ```
24//!
25//! - **declared**: what the script says it needs (`requires=` at publish), plus the
26//! capability its LANGUAGE needs (`urn:cap:lisp` for Lisp), because evaluating code is
27//! itself authority.
28//! - **granted at publish**: the part of `declared` the publisher held when they published.
29//! **A publish that declares a scope the publisher does not hold is REFUSED** with a typed
30//! `Denied` naming the scopes. Narrowing silently instead would store a script whose
31//! `requires` says one thing and whose runs get another, and the manifold would lie.
32//! The snapshot is still stored and still intersected, so a hand edit of ONE record (a
33//! version's `requires`, say, in a [`crate::DirBackend`] file) cannot widen a run past
34//! the other. Editing both is the host operator's act — the same trust as the ceiling
35//! files — and the ceiling bounds every run whatever the records say.
36//! - **the host's ceiling** for this script ([`Ceiling`], from the host's
37//! `<config home>/script-authority/{name}`): the host decides, never the script.
38//! - **the runner's own capability**: [`Capability::attenuate`] keeps a grant only when the
39//! runner holds it, so a run never exceeds the intersection of runner and script.
40//!
41//! **Exclusions travel.** A publisher who holds `urn:cap:fs:read:/root` together with the
42//! exclusion `urn:cap:fs:read:-/root/secret` could not read the secret, so neither can the
43//! script, whoever runs it: every exclusion the publisher held is stored with the version's
44//! grant and handed to `attenuate`, which keeps a requested exclusion (it only narrows).
45//! The ceiling's exclusions travel the same way.
46//!
47//! ```
48//! use ikigai_core::Capability;
49//! use ikigai_script::authority::{effective, Ceiling};
50//! use std::collections::BTreeSet;
51//!
52//! let set = |xs: &[&str]| xs.iter().map(|s| s.to_string()).collect::<BTreeSet<_>>();
53//! let declared = set(&["urn:cap:lisp", "urn:cap:net:example.com", "urn:cap:mail:send"]);
54//! let granted = declared.clone(); // the publisher held all three
55//! let exclusions = set(&["urn:cap:net:-example.com/admin"]);
56//! // The host lets this script run Lisp and reach the network, but not send mail.
57//! let ceiling = Ceiling::scoped(["urn:cap:lisp", "urn:cap:net:*"]);
58//!
59//! let request = effective(&declared, &granted, &exclusions, &ceiling);
60//! assert_eq!(
61//! request,
62//! set(&["urn:cap:lisp", "urn:cap:net:-example.com/admin", "urn:cap:net:example.com"])
63//! );
64//!
65//! // A runner who holds Lisp and mail, but not the network: the run gets Lisp, and the
66//! // exclusion still rides along (it only narrows).
67//! let runner = Capability::scoped(["urn:cap:lisp", "urn:cap:mail:send", "urn:cap:script:run:x"]);
68//! let runs_as = runner.attenuate(request);
69//! assert!(runs_as.allows("urn:cap:lisp"));
70//! assert!(!runs_as.allows("urn:cap:mail:send")); // the ceiling withheld it
71//! assert!(!runs_as.allows("urn:cap:net:example.com")); // the runner never held it
72//! assert!(!runs_as.allows("urn:cap:script:run:x")); // nothing undeclared survives
73//! ```
74
75use std::collections::BTreeSet;
76use std::sync::Arc;
77
78use ikigai_core::{is_deny_scope, Capability, Error, Invocation, Result};
79
80/// Reading a script, as declared: "holds some script read grant". A held grant names one
81/// script — [`cap_read`] — and the exact one is checked inside.
82pub const CAP_READ: &str = "urn:cap:script:read:*";
83/// Publishing or replacing a script, as declared. Exact form: [`cap_write`].
84pub const CAP_WRITE: &str = "urn:cap:script:write:*";
85/// Retiring a script, as declared. Exact form: [`cap_delete`].
86pub const CAP_DELETE: &str = "urn:cap:script:delete:*";
87/// Running a script, as declared. Exact form: [`cap_run`], or [`CAP_RUN_PUBLIC`] for a
88/// public script.
89pub const CAP_RUN: &str = "urn:cap:script:run:*";
90/// Any script grant at all: the compiled form is readable by a reader OR a runner, and a
91/// `requires` is a conjunction, so it declares the family and checks the exact pair inside.
92pub const CAP_ANY: &str = "urn:cap:script:*";
93
94/// Run any script marked **public** (and published). The grant a host gives its anonymous
95/// principal: it is how "a public script grants the run capability to the anonymous
96/// principal" is spelled, since a host's anonymous grant cannot enumerate scripts that do
97/// not exist yet. Withhold it and nothing runs anonymously.
98pub const CAP_RUN_PUBLIC: &str = "urn:cap:script:run:public";
99/// Read the source of any script marked public (and published).
100pub const CAP_READ_PUBLIC: &str = "urn:cap:script:read:public";
101
102/// The capability `urn:lisp:eval` requires, and so every Lisp script declares implicitly
103/// (see [`crate::model::Language::capability`]). Spelled here rather than imported:
104/// the library does not link `ikigai-lisp`.
105pub const CAP_LISP: &str = "urn:cap:lisp";
106
107/// The exact grant to read `{name}`.
108pub fn cap_read(name: &str) -> String {
109 format!("urn:cap:script:read:{name}")
110}
111
112/// The exact grant to publish or replace `{name}`.
113pub fn cap_write(name: &str) -> String {
114 format!("urn:cap:script:write:{name}")
115}
116
117/// The exact grant to retire `{name}`.
118pub fn cap_delete(name: &str) -> String {
119 format!("urn:cap:script:delete:{name}")
120}
121
122/// The exact grant to run `{name}`.
123pub fn cap_run(name: &str) -> String {
124 format!("urn:cap:script:run:{name}")
125}
126
127/// Who a request comes from, as the HOST says — never an argument the caller sends.
128///
129/// The library records it on every publish and every run. It has no way to know who is
130/// on the other end of a door, so the host hands [`crate::SpaceConfig::principal`] a
131/// function of the invocation, which can read what the host's own door stamped (an
132/// authenticated identity, the capability) and nothing the caller chose. The ledger's
133/// `ClaimKindStamper` is the same shape for the same reason.
134///
135/// ```
136/// use ikigai_script::authority::{PrincipalStamper, ANONYMOUS};
137/// use std::sync::Arc;
138/// // A host whose door holds back anonymous callers to `urn:cap:script:run:public`:
139/// let stamper: PrincipalStamper = Arc::new(|inv| {
140/// if inv.capability.allows("urn:cap:host:signed-in") {
141/// "urn:example:person:brian".to_string()
142/// } else {
143/// ANONYMOUS.to_string()
144/// }
145/// });
146/// # let _ = stamper;
147/// ```
148pub type PrincipalStamper = Arc<dyn Fn(&Invocation<'_>) -> String + Send + Sync>;
149
150/// What the default stamper records: the host did not say who.
151pub const UNSTAMPED: &str = "urn:script:principal:unstamped";
152
153/// What a host's stamper conventionally records for an unauthenticated caller.
154pub const ANONYMOUS: &str = "urn:script:principal:anonymous";
155
156/// The default stamper: every request is [`UNSTAMPED`]. Honest rather than useful, so a
157/// host that never decides cannot have its run records claim an identity nobody checked.
158pub fn unstamped() -> PrincipalStamper {
159 Arc::new(|_| UNSTAMPED.to_string())
160}
161
162/// Whether a stamped principal names SOMEONE: anything but [`UNSTAMPED`] and
163/// [`ANONYMOUS`], which a stamper answers for many different callers at once.
164///
165/// It decides who may see a draft. A draft is visible only to its author until it is
166/// published, and the author is the principal the stamper recorded when the draft was
167/// written; two callers stamped [`ANONYMOUS`] are not one person, and a host that stamps
168/// nothing cannot tell any two callers apart. So a draft written under either is nobody's:
169/// only root sees it until it is published. A host whose door cannot identify a caller
170/// stamps [`ANONYMOUS`] rather than inventing a shared name.
171///
172/// ```
173/// use ikigai_script::authority::{is_identity, ANONYMOUS, UNSTAMPED};
174/// assert!(is_identity("urn:example:person:brian"));
175/// assert!(!is_identity(ANONYMOUS));
176/// assert!(!is_identity(UNSTAMPED));
177/// assert!(!is_identity(""));
178/// ```
179pub fn is_identity(principal: &str) -> bool {
180 !principal.trim().is_empty() && principal != UNSTAMPED && principal != ANONYMOUS
181}
182
183/// The host's ceiling for one script: the most it will let that script's runs touch.
184#[derive(Clone, Debug, PartialEq, Eq)]
185pub enum Ceiling {
186 /// The host imposes nothing beyond what the script declared and its publisher held.
187 Unbounded,
188 /// Exactly these scopes. A grant ending in `*` admits every scope under that prefix
189 /// (`urn:cap:net:*`); a deny-shaped scope ([`is_deny_scope`]) is an exclusion every run
190 /// of the script carries.
191 Scopes(BTreeSet<String>),
192}
193
194impl Ceiling {
195 /// No ceiling: [`Ceiling::Unbounded`].
196 pub fn unbounded() -> Ceiling {
197 Ceiling::Unbounded
198 }
199
200 /// The empty ceiling: the script may touch nothing, not even its language, so it cannot
201 /// run. The answer for a script the host has no file for, when the host fails closed.
202 pub fn nothing() -> Ceiling {
203 Ceiling::Scopes(BTreeSet::new())
204 }
205
206 /// Exactly these scopes.
207 pub fn scoped<I, S>(scopes: I) -> Ceiling
208 where
209 I: IntoIterator<Item = S>,
210 S: Into<String>,
211 {
212 Ceiling::Scopes(scopes.into_iter().map(Into::into).collect())
213 }
214
215 /// Parse the text of a ceiling file (`<config home>/script-authority/{name}`): one
216 /// `urn:cap:` scope per line, `#` to the end of a line is a comment, blank lines are
217 /// ignored. A lone `*` line means [`Ceiling::Unbounded`].
218 ///
219 /// ```
220 /// use ikigai_script::authority::Ceiling;
221 /// let ceiling = Ceiling::parse(
222 /// "# the nightly report\nurn:cap:lisp\nurn:cap:net:* # any host\n\
223 /// urn:cap:net:-internal.example\n",
224 /// )
225 /// .unwrap();
226 /// assert!(ceiling.allows("urn:cap:lisp"));
227 /// assert!(ceiling.allows("urn:cap:net:example.com"));
228 /// assert!(!ceiling.allows("urn:cap:mail:send"));
229 /// assert_eq!(ceiling.exclusions(), vec!["urn:cap:net:-internal.example".to_string()]);
230 /// assert_eq!(Ceiling::parse("*\n").unwrap(), Ceiling::Unbounded);
231 /// assert!(Ceiling::parse("lisp\n").is_err()); // not a capability scope
232 /// ```
233 pub fn parse(text: &str) -> Result<Ceiling> {
234 let mut scopes = BTreeSet::new();
235 for (number, line) in text.lines().enumerate() {
236 let line = line.split('#').next().unwrap_or("").trim();
237 if line.is_empty() {
238 continue;
239 }
240 if line == "*" {
241 return Ok(Ceiling::Unbounded);
242 }
243 if !line.starts_with("urn:cap:") || line.split_whitespace().count() != 1 {
244 return Err(Error::InvalidArgument {
245 name: "ceiling".to_string(),
246 detail: format!(
247 "line {}: `{line}` is not one `urn:cap:` scope (or `*` for no ceiling)",
248 number + 1
249 ),
250 });
251 }
252 scopes.insert(line.to_string());
253 }
254 Ok(Ceiling::Scopes(scopes))
255 }
256
257 /// Whether the ceiling admits the grant `scope`: held exactly, or under a held
258 /// `prefix*` family. An exclusion is never admitted as a grant.
259 pub fn allows(&self, scope: &str) -> bool {
260 match self {
261 Ceiling::Unbounded => !is_deny_scope(scope),
262 Ceiling::Scopes(held) => {
263 !is_deny_scope(scope)
264 && held.iter().any(|h| match h.strip_suffix('*') {
265 Some(prefix) => scope.starts_with(prefix),
266 None => h == scope,
267 })
268 }
269 }
270 }
271
272 /// The exclusions the ceiling carries, which every run of the script carries too.
273 pub fn exclusions(&self) -> Vec<String> {
274 match self {
275 Ceiling::Unbounded => Vec::new(),
276 Ceiling::Scopes(held) => held.iter().filter(|s| is_deny_scope(s)).cloned().collect(),
277 }
278 }
279}
280
281/// How the host answers "what is the ceiling for this script?" — called on every run, so a
282/// changed ceiling takes effect at the next one (and a cached result is cut by
283/// [`crate::name::authority_thread`]).
284///
285/// ```
286/// use ikigai_script::authority::{Ceiling, CeilingPolicy};
287/// use std::sync::Arc;
288/// // A host reading `<config home>/script-authority/{name}`, failing closed when the file
289/// // is missing or unreadable:
290/// let dir = std::path::PathBuf::from("/etc/my-host/script-authority");
291/// let policy: CeilingPolicy = Arc::new(move |name| {
292/// std::fs::read_to_string(dir.join(name))
293/// .ok()
294/// .and_then(|text| Ceiling::parse(&text).ok())
295/// .unwrap_or_else(Ceiling::nothing)
296/// });
297/// # let _ = policy;
298/// ```
299pub type CeilingPolicy = Arc<dyn Fn(&str) -> Ceiling + Send + Sync>;
300
301/// A ceiling policy that answers the same ceiling for every script.
302pub fn same_for_all(ceiling: Ceiling) -> CeilingPolicy {
303 Arc::new(move |_| ceiling.clone())
304}
305
306/// Parse `requires=`: whitespace-separated `urn:cap:` grants.
307///
308/// Refused: anything not under `urn:cap:`, a family wildcard (`*`: a script states the
309/// grants it needs, and attenuation keeps grants by exact name, so a wildcard would keep
310/// nothing), and an exclusion (it is not something a script can need; exclusions come
311/// from the publisher and the host).
312pub fn parse_requires(text: &str) -> Result<BTreeSet<String>> {
313 let mut scopes = BTreeSet::new();
314 for scope in text.split_whitespace() {
315 let detail = if !scope.starts_with("urn:cap:") {
316 Some("is not a `urn:cap:` scope")
317 } else if scope.ends_with('*') {
318 Some(
319 "is a family wildcard; a script declares the exact grants it needs, \
320 because a run keeps grants by exact name",
321 )
322 } else if is_deny_scope(scope) {
323 Some("is an exclusion; a script declares what it needs, not what it may not touch")
324 } else {
325 None
326 };
327 if let Some(detail) = detail {
328 return Err(Error::InvalidArgument {
329 name: "requires".to_string(),
330 detail: format!("`{scope}` {detail}"),
331 });
332 }
333 scopes.insert(scope.to_string());
334 }
335 Ok(scopes)
336}
337
338/// What the publisher held of a script's declared scopes, taken at publish time.
339#[derive(Clone, Debug, PartialEq, Eq)]
340pub struct Grant {
341 /// The declared scopes the publisher held: all of them, since a publish declaring more
342 /// is refused. For a declared FAMILY (`prefix*`, which only a SPARQL script's derived
343 /// authority carries: [`crate::sparql::CAP_READ_GRAPH`]), the publisher's own grants
344 /// under it, each one, or the family itself when the publisher was root.
345 pub granted: BTreeSet<String>,
346 /// Every exclusion the publisher's capability carried, which every run carries too.
347 pub exclusions: BTreeSet<String>,
348}
349
350/// A declared family (`prefix*`): its prefix.
351fn family(scope: &str) -> Option<&str> {
352 scope.strip_suffix('*')
353}
354
355/// Take the publisher's grant for `declared`, or refuse with a typed `Denied` naming what
356/// they do not hold. **No elevation**: a script never runs with more than its publisher
357/// held.
358///
359/// A declared family (`prefix*`) is held when the publisher holds some grant under it,
360/// the kernel's own reading of a family in a `requires`; what is taken is every such
361/// grant, so a run's union is never wider than its publisher's.
362pub fn grant_at_publish(publisher: &Capability, declared: &BTreeSet<String>) -> Result<Grant> {
363 let held_under = |prefix: &str| -> Vec<String> {
364 publisher
365 .scopes()
366 .map(|held| {
367 held.iter()
368 .filter(|s| s.starts_with(prefix) && !is_deny_scope(s))
369 .cloned()
370 .collect()
371 })
372 .unwrap_or_default()
373 };
374 let mut granted = BTreeSet::new();
375 let mut missing: Vec<&str> = Vec::new();
376 for scope in declared {
377 match family(scope) {
378 Some(_) if publisher.is_root() => {
379 granted.insert(scope.clone());
380 }
381 Some(prefix) => {
382 let held = held_under(prefix);
383 if held.is_empty() {
384 missing.push(scope);
385 }
386 granted.extend(held);
387 }
388 None if publisher.allows(scope) => {
389 granted.insert(scope.clone());
390 }
391 None => missing.push(scope),
392 }
393 }
394 if !missing.is_empty() {
395 return Err(Error::Denied(format!(
396 "a script cannot be given more than its publisher holds, and this capability \
397 does not hold {} — declare less, or publish under a capability that holds it",
398 missing.join(", ")
399 )));
400 }
401 let exclusions = publisher
402 .scopes()
403 .map(|held| held.iter().filter(|s| is_deny_scope(s)).cloned().collect())
404 .unwrap_or_default();
405 Ok(Grant {
406 granted,
407 exclusions,
408 })
409}
410
411/// The scopes a run asks to keep: `{ s in declared : s in granted and ceiling.allows(s) }`
412/// plus the publisher's and the ceiling's exclusions. The run's capability is the runner's
413/// own [`Capability::attenuate`]d to this set — see the module documentation.
414///
415/// A declared family keeps the publisher's grants under it that the ceiling allows; when
416/// the publisher was root it keeps the family itself, a marker the SPARQL run expands
417/// into exact grants (each checked against the ceiling and the runner) before anything
418/// is attenuated, because attenuation keeps grants by exact name.
419pub fn effective(
420 declared: &BTreeSet<String>,
421 granted: &BTreeSet<String>,
422 exclusions: &BTreeSet<String>,
423 ceiling: &Ceiling,
424) -> BTreeSet<String> {
425 let mut keep: BTreeSet<String> = BTreeSet::new();
426 for scope in declared {
427 match family(scope) {
428 Some(_) if granted.contains(scope) => {
429 keep.insert(scope.clone());
430 }
431 Some(prefix) => keep.extend(
432 granted
433 .iter()
434 .filter(|g| g.starts_with(prefix) && ceiling.allows(g))
435 .cloned(),
436 ),
437 None if granted.contains(scope) && ceiling.allows(scope) => {
438 keep.insert(scope.clone());
439 }
440 None => {}
441 }
442 }
443 keep.extend(exclusions.iter().filter(|s| is_deny_scope(s)).cloned());
444 keep.extend(ceiling.exclusions());
445 keep
446}
447
448#[cfg(test)]
449mod tests {
450 use super::*;
451
452 fn set(xs: &[&str]) -> BTreeSet<String> {
453 xs.iter().map(|s| s.to_string()).collect()
454 }
455
456 #[test]
457 fn a_publisher_cannot_declare_what_they_do_not_hold() {
458 let publisher = Capability::scoped(["urn:cap:lisp", "urn:cap:script:write:x"]);
459 let err =
460 grant_at_publish(&publisher, &set(&["urn:cap:lisp", "urn:cap:mail:send"])).unwrap_err();
461 assert!(
462 matches!(&err, Error::Denied(m) if m.contains("urn:cap:mail:send") && !m.contains("urn:cap:lisp,")),
463 "{err:?}"
464 );
465 }
466
467 #[test]
468 fn the_publishers_exclusions_are_taken_with_the_grant() {
469 let publisher = Capability::scoped([
470 "urn:cap:lisp",
471 "urn:cap:fs:read:/root",
472 "urn:cap:fs:read:-/root/secret",
473 ]);
474 let grant =
475 grant_at_publish(&publisher, &set(&["urn:cap:lisp", "urn:cap:fs:read:/root"])).unwrap();
476 assert_eq!(grant.exclusions, set(&["urn:cap:fs:read:-/root/secret"]));
477 // Root holds no exclusions and every grant.
478 let grant = grant_at_publish(&Capability::root(), &set(&["urn:cap:anything"])).unwrap();
479 assert!(grant.exclusions.is_empty());
480 }
481
482 #[test]
483 fn a_hand_widened_grant_still_cannot_exceed_the_stored_snapshot() {
484 // declared names mail, but the snapshot (what the publisher held) does not.
485 let request = effective(
486 &set(&["urn:cap:lisp", "urn:cap:mail:send"]),
487 &set(&["urn:cap:lisp"]),
488 &BTreeSet::new(),
489 &Ceiling::Unbounded,
490 );
491 assert_eq!(request, set(&["urn:cap:lisp"]));
492 }
493
494 #[test]
495 fn a_family_takes_the_publishers_grants_under_it() {
496 let family = "urn:cap:store:read:graph:*";
497 let publisher = Capability::scoped([
498 "urn:cap:store:read:graph:urn:a",
499 "urn:cap:store:read:graph:urn:b",
500 "urn:cap:other",
501 ]);
502 let grant = grant_at_publish(&publisher, &set(&[family])).unwrap();
503 assert_eq!(
504 grant.granted,
505 set(&[
506 "urn:cap:store:read:graph:urn:a",
507 "urn:cap:store:read:graph:urn:b"
508 ])
509 );
510 // Holding nothing under it is holding nothing it declares.
511 assert!(grant_at_publish(&Capability::scoped(["urn:cap:other"]), &set(&[family])).is_err());
512 // Root keeps the family, as a marker for the run to expand.
513 let root = grant_at_publish(&Capability::root(), &set(&[family])).unwrap();
514 assert_eq!(root.granted, set(&[family]));
515 // The ceiling narrows the members.
516 let keep = effective(
517 &set(&[family]),
518 &grant.granted,
519 &BTreeSet::new(),
520 &Ceiling::scoped(["urn:cap:store:read:graph:urn:a"]),
521 );
522 assert_eq!(keep, set(&["urn:cap:store:read:graph:urn:a"]));
523 }
524
525 #[test]
526 fn requires_refuses_wildcards_exclusions_and_strangers() {
527 assert!(parse_requires("urn:cap:net:*").is_err());
528 assert!(parse_requires("urn:cap:fs:read:-/x").is_err());
529 assert!(parse_requires("lisp").is_err());
530 assert_eq!(
531 parse_requires(" urn:cap:a\n urn:cap:b urn:cap:a ").unwrap(),
532 set(&["urn:cap:a", "urn:cap:b"])
533 );
534 }
535
536 #[test]
537 fn a_ceiling_never_admits_an_exclusion_as_a_grant() {
538 assert!(!Ceiling::Unbounded.allows("urn:cap:net:-x"));
539 assert!(!Ceiling::scoped(["urn:cap:net:*"]).allows("urn:cap:net:-x"));
540 assert!(!Ceiling::nothing().allows("urn:cap:lisp"));
541 }
542}