//! Values signed by their user: under a strict policy (`access::policy`), at what //! decides who may do what and at the paths the swarm lists as user-signed //! (`_continuum/access/userSigned`, `listed`; `signed_paths`), the value is a signed envelope, one //! string, `cv2...` (each base64url, unpadded). The value is //! JSON, as its user wrote it (`null`: deleted). What continuum adds is apart, in the //! meta, JSON too: the `swarm` and the `path` it is for (segments), the `user` who //! signed it, when (`at`, Unix ms, by the signer's clock), `seq`, and `prev`: the //! SHA-256 (hex) of the envelope it replaces, empty if none. The signature is the //! user's, with one of its keys (`registry::User::keys`), over the value's bytes, a //! newline, and the meta's bytes (neither holds a newline), as //! `ssh-keygen -Y sign -n continuum-value` makes it (`access::sshsig`), its SSHSIG blob. //! //! It travels with the value, through replays and snapshots alike, and anyone can check //! it (`check`): a node before it writes or applies one, a client reading it. An //! envelope only replaces the one it names (`prev`), and its `seq` is one more than //! that one's (0 where it replaces none). Of the envelopes a place holds, written at //! once, the one with the highest `seq` is the place's value (`document::store`): so a //! member that puts an older signed value back beside a newer one changes nothing. A //! node never writes there but as its user signed it. use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD as B64URL}; use serde::{Deserialize, Serialize}; use serde_json::Value as JsonValue; use sha2::{Digest, Sha256}; use super::{Right, agree, registry, sshsig}; use crate::document::{ReadDoc, meta, store}; /// What a signature over a payload is for (`sshsig`). pub(crate) const NAMESPACE: &str = "continuum-value"; /// What every envelope starts with. const PREFIX: &str = "cv2"; /// Where the swarm lists the user-signed paths: a list of paths, each a list of /// segments. pub(crate) fn listed_at() -> Vec { meta::path(&[meta::ACCESS, "userSigned"]) } /// The paths `doc` lists as user-signed; an entry that isn't a list of strings is left /// out. pub(crate) fn listed(doc: &impl ReadDoc) -> Vec> { let Ok(Some(JsonValue::Array(entries))) = store::read_plain(doc, &listed_at()) else { return Vec::new(); }; entries .iter() .filter_map(|entry| { entry .as_array()? .iter() .map(|segment| segment.as_str().map(str::to_owned)) .collect() }) .collect() } /// What decides who may do what, whose values are always user-signed under a strict /// policy (`access::policy`): every user's entry, every entry of `_continuum/access`, /// every ban. A `*` segment stands for any one key. fn deciding() -> Vec> { [meta::USERS, meta::ACCESS, meta::BANNED] .iter() .map(|part| meta::path(&[part, "*"])) .collect() } /// The paths whose values their users sign under a strict policy: what decides who may /// do what (`deciding`), and those `doc` lists (`listed`). pub(crate) fn signed_paths(doc: &impl ReadDoc) -> Vec> { let mut paths = deciding(); paths.extend(listed(doc)); paths } /// The user-signed path `path` is at or within, if any, of `signed` (`signed_paths`): /// its `*` segments as `path` has them. pub(crate) fn signed_path(signed: &[Vec], path: &[String]) -> Option> { signed.iter().find_map(|pattern| { (path.len() >= pattern.len() && agree(pattern, path)) .then(|| path[..pattern.len()].to_vec()) }) } /// Whether `path` is where a user-signed value goes, of `signed` (`signed_paths`). pub(crate) fn is_signed(signed: &[Vec], path: &[String]) -> bool { signed .iter() .any(|pattern| pattern.len() == path.len() && agree(pattern, path)) } /// Whether a user-signed value of `signed` may be below `path` (`signed_paths`). pub(crate) fn above_signed(signed: &[Vec], path: &[String]) -> bool { signed .iter() .any(|pattern| pattern.len() > path.len() && agree(pattern, path)) } /// Whether a write at `path` reaches a user-signed value of `signed` (`signed_paths`): /// at one, within one, or above one. pub(crate) fn reaches_signed(signed: &[Vec], path: &[String]) -> bool { signed.iter().any(|pattern| agree(pattern, path)) } /// What a signed value says: its value, and its meta. #[derive(Debug, Clone, PartialEq)] pub(crate) struct Payload { pub(crate) value: JsonValue, /// The swarm it is for: one user, with the same name and key in two swarms, signs /// for one only. pub(crate) swarm: String, pub(crate) path: Vec, pub(crate) user: String, pub(crate) at: u64, /// One more than that of the envelope it replaces; 0 where it replaces none. pub(crate) seq: u64, pub(crate) prev: String, } /// An envelope's meta, as it is written. #[derive(Serialize, Deserialize)] struct Meta { swarm: String, path: Vec, user: String, at: u64, seq: u64, prev: String, } impl Payload { /// The bytes its user signs (`seal`): the value, a newline, the meta. #[cfg(test)] pub(crate) fn signed(&self) -> Vec { let meta = Meta { swarm: self.swarm.clone(), path: self.path.clone(), user: self.user.clone(), at: self.at, seq: self.seq, prev: self.prev.clone(), }; let mut bytes = serde_json::to_vec(&self.value).expect("a value is JSON"); bytes.push(b'\n'); bytes.extend(serde_json::to_vec(&meta).expect("a meta is JSON")); bytes } } /// The `seq` of `envelope`, unchecked; None if it isn't one. pub(crate) fn seq(envelope: &str) -> Option { read(envelope).ok().map(|payload| payload.seq) } /// An envelope checked (`check`): what it says, and the key that signed it. #[derive(Debug, Clone, PartialEq)] pub(crate) struct Signed { pub(crate) payload: Payload, pub(crate) key: sshsig::PublicKey, } /// What `prev` names for `envelope`, the one replaced (none: empty). pub(crate) fn digest(envelope: Option<&str>) -> String { envelope.map_or_else(String::new, |envelope| { Sha256::digest(envelope.as_bytes()) .iter() .map(|byte| format!("{byte:02x}")) .collect() }) } /// The envelope of `signed` (the exact bytes signed: the value's JSON, a newline, the /// meta's JSON) signed by `signature` (armored, as `ssh-keygen -Y sign` writes it). pub(crate) fn seal(signed: &[u8], armored: &str) -> Result { let blob = sshsig::dearmor(armored)?; let mut lines = signed.split(|byte| *byte == b'\n'); let (Some(value), Some(meta), None) = (lines.next(), lines.next(), lines.next()) else { return Err("its value's line, then its meta's".to_owned()); }; Ok(format!( "{PREFIX}.{}.{}.{}", B64URL.encode(value), B64URL.encode(meta), B64URL.encode(blob) )) } /// What `envelope` holds, unchecked: the bytes signed, what it says, the signature's /// blob. fn open(envelope: &str) -> Result<(Vec, Payload, Vec), String> { let mut parts = envelope.split('.'); let (Some(PREFIX), Some(value), Some(meta), Some(signature), None) = ( parts.next(), parts.next(), parts.next(), parts.next(), parts.next(), ) else { return Err("not a signed value (cv2...)".to_owned()); }; let decoded = |part: &str, what: &str| { let bytes = B64URL .decode(part) .map_err(|error| format!("its {what} doesn't decode: {error}"))?; // One line each: the bytes signed part at the one newline between them. if bytes.contains(&b'\n') { return Err(format!("its {what} holds a newline")); } Ok(bytes) }; let mut signed = decoded(value, "value")?; let value: JsonValue = serde_json::from_slice(&signed) .map_err(|error| format!("its value isn't JSON: {error}"))?; let meta = decoded(meta, "meta")?; let Meta { swarm, path, user, at, seq, prev, } = serde_json::from_slice(&meta).map_err(|error| format!("its meta isn't one: {error}"))?; signed.push(b'\n'); signed.extend(meta); let signature = B64URL .decode(signature) .map_err(|error| format!("its signature doesn't decode: {error}"))?; let payload = Payload { value, swarm, path, user, at, seq, prev, }; Ok((signed, payload, signature)) } /// What `envelope` says, unchecked: for showing a value (`check` before taking it). pub(crate) fn read(envelope: &str) -> Result { open(envelope).map(|(_, payload, _)| payload) } /// Checks `envelope` as the value at `path`, replacing `previous` (the envelope there /// before, if any), against the user registry `doc` holds (as the writer saw it): for /// its swarm, that path, naming what it replaces and numbered after it, signed by one of /// its user's keys, a user who may write there. pub(crate) fn check( doc: &impl ReadDoc, envelope: &str, path: &[String], previous: Option<&str>, ) -> Result { let (bytes, payload, signature) = open(envelope)?; let swarm = store::read_path( doc, &crate::document::meta::path(&[crate::document::meta::SWARM]), ) .ok() .flatten(); if swarm.as_ref().and_then(JsonValue::as_str) != Some(payload.swarm.as_str()) { return Err(format!("signed for swarm {}, not this one", payload.swarm)); } if payload.path != path { return Err(format!( "signed for /{}, not /{}", payload.path.join("/"), path.join("/") )); } if payload.prev != digest(previous) { return Err("it doesn't replace the value there (prev)".to_owned()); } let next = match previous.map(seq) { None => Some(0), Some(before) => before.and_then(|before| before.checked_add(1)), }; if Some(payload.seq) != next { return Err("it isn't numbered after the value there (seq)".to_owned()); } let key = sshsig::verify_blob(&signature, NAMESPACE, &bytes)?; let user = registry::user(doc, &payload.user).ok_or_else(|| format!("no user {}", payload.user))?; if !user.keys.values().any(|known| *known == key) { return Err(format!("{} has no key {}", payload.user, key.fingerprint())); } if !user.caps().allows(Right::Write, path) && !own_keys_only(doc, &payload, &user, path) { return Err(format!( "{} may not write /{}", payload.user, path.join("/") )); } Ok(Signed { payload, key }) } /// Whether `payload`, signed by its user (`user`, enabled), is that user's own entry /// with only its keys changed from the one at `path` in `doc`, one left at least: a user /// manages its own keys, whatever else it may do. fn own_keys_only( doc: &impl ReadDoc, payload: &Payload, user: ®istry::User, path: &[String], ) -> bool { if user.disabled || path != registry::user_path(&payload.user) { return false; } let Ok(Some(mut before)) = store::read_plain(doc, path) else { return false; }; // One key left at least: a user can't sign, nor log in by key, without one. if payload .value .get("keys") .and_then(JsonValue::as_object) .is_none_or(serde_json::Map::is_empty) { return false; } let mut after = payload.value.clone(); for entry in [&mut before, &mut after] { match entry.as_object_mut() { Some(entry) => { entry.remove("keys"); } None => return false, } } before == after } #[cfg(test)] mod tests { use super::*; use crate::document::Document; use crate::document::testing::change; use ed25519_dalek::SigningKey; use serde_json::json; fn path(text: &str) -> Vec { text.split('/').map(str::to_owned).collect() } /// A registry with alice, who may write `config` and holds `key`'s public key, and /// bob, who holds it too but may write nothing. fn registry_with(key: &SigningKey) -> Document { let line = sshsig::PublicKey(key.verifying_key().to_bytes()).line(); let mut doc = Document::new(); change(&mut doc, |doc| { store::write_path(doc, &path("_continuum/swarm"), &json!("s")).unwrap(); let mut alice = registry::entry("root", 1, &[(path("config"), &[Right::Write][..])]); alice["keys"] = json!({ "laptop": line }); store::write_path(doc, ®istry::user_path("alice"), &alice).unwrap(); let mut bob = registry::entry("root", 1, &[]); bob["keys"] = json!({ "laptop": line }); store::write_path(doc, ®istry::user_path("bob"), &bob).unwrap(); }); doc } fn signed(key: &SigningKey, payload: &Payload) -> String { let bytes = payload.signed(); seal(&bytes, &sshsig::sign(key, NAMESPACE, &bytes)).unwrap() } /// The first at its place (`prev` empty), or the one after it. fn payload(user: &str, at: &str, value: JsonValue, prev: &str) -> Payload { Payload { value, swarm: "s".to_owned(), path: path(at), user: user.to_owned(), at: 1, seq: u64::from(!prev.is_empty()), prev: prev.to_owned(), } } /// Signed for its path, replacing what is there, by one of its user's keys, a user /// who may write there: taken; anything else refused. #[test] fn what_an_envelope_must_be() { let key = SigningKey::from_bytes(&[5; 32]); let other = SigningKey::from_bytes(&[6; 32]); let doc = registry_with(&key); let first = signed( &key, &payload("alice", "config", json!({"mode": "fast"}), ""), ); let checked = check(&doc, &first, &path("config"), None).unwrap(); assert_eq!(checked.payload.value, json!({"mode": "fast"})); assert_eq!(read(&first).unwrap().user, "alice"); // Another path, another key, a user who may not, an unknown one. assert!(check(&doc, &first, &path("other"), None).is_err()); let foreign = signed(&other, &payload("alice", "config", json!(1), "")); assert!(check(&doc, &foreign, &path("config"), None).is_err()); let bobs = signed(&key, &payload("bob", "config", json!(1), "")); assert!(check(&doc, &bobs, &path("config"), None).is_err()); let nobodys = signed(&key, &payload("carol", "config", json!(1), "")); assert!(check(&doc, &nobodys, &path("config"), None).is_err()); // Replacing: only what it names. let second = signed( &key, &payload("alice", "config", json!(null), &digest(Some(&first))), ); assert!(check(&doc, &second, &path("config"), Some(&first)).is_ok()); assert!(check(&doc, &second, &path("config"), None).is_err()); assert!(check(&doc, &first, &path("config"), Some(&second)).is_err()); // Numbered after it, and nothing else: not as the first, nor two on. for seq in [0, 2] { let misnumbered = signed( &key, &Payload { seq, ..payload("alice", "config", json!(null), &digest(Some(&first))) }, ); assert!(check(&doc, &misnumbered, &path("config"), Some(&first)).is_err()); } let late = signed( &key, &Payload { seq: 1, ..payload("alice", "config", json!(1), "") }, ); assert!(check(&doc, &late, &path("config"), None).is_err()); // Tampered with: its value, its meta. let tampered = first.replacen("cv2.", "cv2.e30", 1); assert!(check(&doc, &tampered, &path("config"), None).is_err()); let mut parts: Vec<&str> = first.split('.').collect(); let renumbered = B64URL.encode( String::from_utf8(B64URL.decode(parts[2]).unwrap()) .unwrap() .replace("\"seq\":0", "\"seq\":7"), ); parts[2] = &renumbered; assert!(check(&doc, &parts.join("."), &path("config"), None).is_err()); assert!(check(&doc, "plain", &path("config"), None).is_err()); // For another swarm. let elsewhere = signed( &key, &Payload { swarm: "t".to_owned(), ..payload("alice", "config", json!({"mode": "fast"}), "") }, ); assert!(check(&doc, &elsewhere, &path("config"), None).is_err()); } /// A user signs its own entry with its keys changed, though it may not write the /// registry; not with anything else changed, nor another's. #[test] fn users_sign_their_own_keys() { let key = SigningKey::from_bytes(&[5; 32]); let doc = registry_with(&key); let entry = store::read_plain(&doc, ®istry::user_path("alice")) .unwrap() .unwrap(); let line = sshsig::PublicKey(SigningKey::from_bytes(&[8; 32]).verifying_key().to_bytes()).line(); let mut rekeyed = entry.clone(); rekeyed["keys"]["phone"] = json!(line); let at = "_continuum/users/alice"; let signed_as = |user: &str, value: JsonValue| signed(&key, &payload(user, at, value, "")); assert!(check(&doc, &signed_as("alice", rekeyed.clone()), &path(at), None).is_ok()); let mut more = rekeyed.clone(); more["caps"] = json!({"x": {"path": [], "rights": ["write"]}}); assert!(check(&doc, &signed_as("alice", more), &path(at), None).is_err()); // bob, holding the same key, for alice: not his entry. assert!(check(&doc, &signed_as("bob", rekeyed), &path(at), None).is_err()); // Her keys all gone: no. let mut keyless = entry.clone(); keyless["keys"] = json!({}); assert!(check(&doc, &signed_as("alice", keyless), &path(at), None).is_err()); } #[test] fn listed_paths() { let mut doc = Document::new(); change(&mut doc, |doc| { store::write_path(doc, &listed_at(), &json!([["config"], ["a", "b"], "junk"])).unwrap(); }); assert_eq!(listed(&doc), vec![path("config"), path("a/b")]); let signed = signed_paths(&doc); assert_eq!(signed_path(&signed, &path("config")), Some(path("config"))); assert_eq!(signed_path(&signed, &path("a/b/c")), Some(path("a/b"))); assert_eq!(signed_path(&signed, &path("a")), None); assert_eq!( signed_path(&signed, &path("_continuum/users/alice/caps")), Some(path("_continuum/users/alice")) ); assert_eq!(signed_path(&signed, &path("_continuum/users")), None); assert_eq!( signed_path(&signed, &path("_continuum/access/policy")), Some(path("_continuum/access/policy")) ); assert!(is_signed(&signed, &path("_continuum/users/alice"))); assert!(!is_signed(&signed, &path("_continuum/users/alice/caps"))); assert!(above_signed(&signed, &path("_continuum/users"))); assert!(above_signed(&signed, &path("a"))); assert!(!above_signed(&signed, &path("a/b"))); assert!(reaches_signed(&signed, &path("a"))); assert!(reaches_signed(&signed, &path("a/b/c"))); assert!(!reaches_signed(&signed, &path("a/c"))); assert!(!reaches_signed(&signed, &path("_continuum/members/x"))); } }