Fundamentum client v0.5.0

This commit is contained in:
2026-11-05 09:05:13 +01:00
commit 353f08e0bb
36 changed files with 8844 additions and 0 deletions
+319
View File
@@ -0,0 +1,319 @@
//! The app side of Custos' local API (docs/TESSERA.md §10): a Domi app on the same Windows machine keeps its
//! subkey seed in Custos and asks Custos to certify the subkey with the person's root.
//!
//! ```no_run
//! # use tessera::Id;
//! let mut custos = custos_local::Custos::connect().unwrap();
//! let app_id = Id::new("fiscus").unwrap();
//! let subkey = custos.subkey("Fiscus Domi", &app_id).unwrap();
//! println!("Custos will show {}", tessera::match_code(&subkey.public()));
//! let cert = custos.request_cert("Fiscus Domi", &app_id, &Id::new("sync").unwrap(), &subkey).unwrap();
//! ```
//!
//! The seed lives in Custos under `domi://<app_id>/tessera-subkey`; the root never leaves Custos, and no
//! answer contains private key material other than the app's own secrets, in its own namespace: the subkey
//! seed, the state keys and the backup secret.
//!
//! v1.1 (docs/TESSERA.md §12): on every sync an app applies the revocations the person started in Custos and
//! backs up its self group:
//!
//! ```ignore
//! for statements in custos.revocations_to_apply("Fiscus Domi", &app_id, |k| client.events_by_all(k))? {
//! client.apply_revocation(&statements)?;
//! }
//! client.backup(&custos.backup_secret("Fiscus Domi", &app_id)?)?;
//! ```
use data_encoding::BASE64URL_NOPAD;
use serde_json::{Value, json};
use sha2::Digest;
use std::io::{Read, Write};
use tessera::{BackupSecret, Id, PublicKey, Revocation, Subkey, SubkeyCert};
use zeroize::Zeroizing;
/// The pipe Custos listens on; `CUSTOS_PIPE` overrides it (tests, a second Custos).
pub const PIPE: &str = r"\\.\pipe\custos-domi";
const SEED_NAME: &str = "tessera-subkey";
#[derive(Debug, thiserror::Error)]
pub enum LocalError {
#[error("Custos is not running (or this is not Windows): {0}")]
NotRunning(std::io::Error),
#[error("talking to Custos failed: {0}")]
Io(std::io::Error),
#[error("Custos refused: {error} ({message})")]
Refused { error: String, message: String },
#[error("Custos sent an answer this app does not understand")]
BadAnswer,
#[error("the certificate Custos sent does not match the request: {0}")]
WrongCert(&'static str),
#[error("no random numbers from the OS")]
Random,
#[error("the revocation Custos sent does not match the request")]
WrongRevocation,
}
/// A revocation the person started in Custos (Domi identity → a key → Revoke).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PendingRevocation {
pub subkey: PublicKey,
/// Unix seconds, as Custos chose it.
pub revoked_at: u64,
/// `None` until a device of this app sent the list of events to keep.
pub statements: Option<Vec<Revocation>>,
}
/// A connection to Custos.
pub struct Custos {
pipe: std::fs::File,
}
impl Custos {
pub fn connect() -> Result<Custos, LocalError> {
let name = std::env::var("CUSTOS_PIPE").unwrap_or_else(|_| PIPE.to_owned());
let pipe = std::fs::OpenOptions::new().read(true).write(true).open(name).map_err(LocalError::NotRunning)?;
Ok(Custos { pipe })
}
/// One request, one answer. Answers with `"ok": false` become [`LocalError::Refused`].
fn call(&mut self, req: &Value) -> Result<Value, LocalError> {
let out = Zeroizing::new(serde_json::to_vec(req).map_err(|_| LocalError::BadAnswer)?);
self.pipe.write_all(&out).map_err(LocalError::Io)?;
let mut buf = Zeroizing::new(Vec::new());
let mut chunk = Zeroizing::new(vec![0u8; 64 * 1024]);
let v: Value = loop {
let n = self.pipe.read(&mut chunk).map_err(LocalError::Io)?;
if n == 0 {
return Err(LocalError::BadAnswer);
}
buf.extend_from_slice(&chunk[..n]);
match serde_json::from_slice(&buf) {
Ok(v) => break v,
Err(e) if e.is_eof() => continue,
Err(_) => return Err(LocalError::BadAnswer),
}
};
if v["ok"] == true {
return Ok(v);
}
Err(LocalError::Refused {
error: v["error"].as_str().unwrap_or("unknown").to_owned(),
message: v["message"].as_str().unwrap_or("").to_owned(),
})
}
/// This app's subkey: the seed kept in Custos, or a new one from the OS CSPRNG stored there first.
/// Custos asks the person once whether `app` may use the namespace `app_id`.
pub fn subkey(&mut self, app: &str, app_id: &Id) -> Result<Subkey, LocalError> {
let seed = self.random_secret(app, &format!("domi://{app_id}/{SEED_NAME}"), "Domi subkey")?;
Ok(Subkey::from_seed(&seed))
}
/// The key that encrypts this app's Tabellarius state file at `state_path` (one per file), kept in Custos.
pub fn state_key(&mut self, app: &str, app_id: &Id, state_path: &str) -> Result<Zeroizing<[u8; 32]>, LocalError> {
let id: String =
sha2::Sha256::digest(state_path.as_bytes()).iter().take(6).map(|b| format!("{b:02x}")).collect();
self.random_secret(app, &format!("domi://{app_id}/tabellarius-state-{id}"), "Tabellarius state key")
}
/// 32 bytes kept in Custos under `r`: read, or made from the OS CSPRNG and stored first.
fn random_secret(&mut self, app: &str, r: &str, what: &str) -> Result<Zeroizing<[u8; 32]>, LocalError> {
match self.call(&json!({ "op": "get", "ref": r, "app": app })) {
Ok(v) => {
let text = Zeroizing::new(v["value"].as_str().ok_or(LocalError::BadAnswer)?.to_owned());
let seed = Zeroizing::new(BASE64URL_NOPAD.decode(text.as_bytes()).map_err(|_| LocalError::BadAnswer)?);
Ok(Zeroizing::new(seed.as_slice().try_into().map_err(|_| LocalError::BadAnswer)?))
}
Err(LocalError::Refused { error, .. }) if error == "not_found" => {
let mut seed = Zeroizing::new([0u8; 32]);
getrandom::fill(seed.as_mut()).map_err(|_| LocalError::Random)?;
let text = Zeroizing::new(BASE64URL_NOPAD.encode(seed.as_ref()));
let label = format!("{app}: {what}");
self.call(&json!({ "op": "set", "ref": r, "value": text.as_str(), "label": label, "app": app }))?;
Ok(seed)
}
Err(e) => Err(e),
}
}
/// Asks Custos to certify `subkey` for `app_id` and `purpose`. Custos shows the subkey's match code
/// (`tessera::match_code`); show the same code in the app while this waits. Blocks until the person
/// answers. The cert is checked before it is returned.
pub fn request_cert(
&mut self,
app: &str,
app_id: &Id,
purpose: &Id,
subkey: &Subkey,
) -> Result<SubkeyCert, LocalError> {
self.request_cert_for(app, app_id, purpose, &subkey.public())
}
/// [`Custos::request_cert`] for a key this app does not hold: another device of the same person (an app's
/// server-side device, paired through this desktop). Custos shows the key's match code; the other device
/// shows the same code, so the person approves only the key they see there.
pub fn request_cert_for(
&mut self,
app: &str,
app_id: &Id,
purpose: &Id,
key: &PublicKey,
) -> Result<SubkeyCert, LocalError> {
let v = self.call(&json!({
"op": "subkey",
"app": app,
"app_id": app_id.as_str(),
"purpose": purpose.as_str(),
"subkey": key.to_string(),
}))?;
let cert = SubkeyCert::from_text(v["cert"].as_str().ok_or(LocalError::BadAnswer)?)
.map_err(|_| LocalError::BadAnswer)?;
check(&cert, app_id, purpose, key, now())?;
Ok(cert)
}
}
impl Custos {
/// The revocations the person started for this app's subkeys and for device keys.
pub fn revocations(&mut self, app: &str, app_id: &Id) -> Result<Vec<PendingRevocation>, LocalError> {
let v = self.call(&json!({ "op": "revocations", "app": app, "app_id": app_id.as_str() }))?;
let list = v["revocations"].as_array().ok_or(LocalError::BadAnswer)?;
list.iter()
.map(|r| {
let subkey = r["subkey"].as_str().and_then(PublicKey::from_text).ok_or(LocalError::BadAnswer)?;
let revoked_at = r["revoked_at"].as_u64().ok_or(LocalError::BadAnswer)?;
let statements = match &r["statements"] {
Value::Null => None,
s => Some(statements(s, &subkey, revoked_at)?),
};
Ok(PendingRevocation { subkey, revoked_at, statements })
})
.collect()
}
/// Sends the hashes of the events `pending`'s key wrote that stay valid (`Client::events_by_all`); Custos
/// signs the revocation with the root. If another device of this app answered first, Custos returns
/// what it signed then.
pub fn revoke(
&mut self,
app: &str,
app_id: &Id,
pending: &PendingRevocation,
accepted: &[[u8; 32]],
) -> Result<Vec<Revocation>, LocalError> {
let v = self.call(&json!({
"op": "revoke",
"app": app,
"app_id": app_id.as_str(),
"subkey": pending.subkey.to_string(),
"revoked_at": pending.revoked_at,
"accepted": BASE64URL_NOPAD.encode(&accepted.concat()),
}))?;
statements(&v["statements"], &pending.subkey, pending.revoked_at)
}
/// Every revocation this app has to apply, signed: answers the ones still waiting with `accepted_of`
/// (`|k| client.events_by_all(k)`). Hand each to `Client::apply_revocation`.
pub fn revocations_to_apply(
&mut self,
app: &str,
app_id: &Id,
accepted_of: impl Fn(&PublicKey) -> Vec<[u8; 32]>,
) -> Result<Vec<Vec<Revocation>>, LocalError> {
let mut out = Vec::new();
for p in self.revocations(app, app_id)? {
out.push(match &p.statements {
Some(s) => s.clone(),
None => self.revoke(app, app_id, &p, &accepted_of(&p.subkey))?,
});
}
Ok(out)
}
/// This app's backup secret (docs/TESSERA.md §12), derived by Custos from the root. Nothing reads it back
/// out of [`BackupSecret`].
pub fn backup_secret(&mut self, app: &str, app_id: &Id) -> Result<BackupSecret, LocalError> {
let v = self.call(&json!({ "op": "backup_key", "app": app, "app_id": app_id.as_str() }))?;
let text = Zeroizing::new(v["secret"].as_str().ok_or(LocalError::BadAnswer)?.to_owned());
let bytes = Zeroizing::new(BASE64URL_NOPAD.decode(text.as_bytes()).map_err(|_| LocalError::BadAnswer)?);
let secret: [u8; 32] = bytes.as_slice().try_into().map_err(|_| LocalError::BadAnswer)?;
Ok(BackupSecret::from_bytes(secret))
}
}
/// Signed statements from an answer: one root, the asked-for key and time, each signature valid.
fn statements(v: &Value, subkey: &PublicKey, revoked_at: u64) -> Result<Vec<Revocation>, LocalError> {
let list: Vec<Revocation> = v
.as_array()
.ok_or(LocalError::BadAnswer)?
.iter()
.map(|t| t.as_str().and_then(|t| Revocation::from_text(t).ok()).ok_or(LocalError::BadAnswer))
.collect::<Result<_, _>>()?;
let root = list.first().ok_or(LocalError::WrongRevocation)?.root();
let ok = list
.iter()
.all(|r| r.root() == root && r.subkey() == *subkey && r.revoked_at() == revoked_at && r.verify(&root).is_ok());
if !ok {
return Err(LocalError::WrongRevocation);
}
Ok(list)
}
fn now() -> u64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}
/// Whether `cert` is what was asked for, and valid now under the root it names.
fn check(cert: &SubkeyCert, app_id: &Id, purpose: &Id, key: &PublicKey, now: u64) -> Result<(), LocalError> {
if cert.subkey() != *key {
return Err(LocalError::WrongCert("another subkey"));
}
if cert.app_id() != app_id || cert.purpose() != purpose {
return Err(LocalError::WrongCert("another app id or purpose"));
}
cert.verify(&cert.root(), now).map_err(|_| LocalError::WrongCert("not valid now"))
}
#[cfg(test)]
mod tests {
use super::*;
use tessera::{CertRequest, RootKey, certify};
#[test]
fn a_cert_is_checked_against_the_request() {
let root = RootKey::from_mnemonic(
"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon \
abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art",
)
.unwrap();
let sub = Subkey::from_seed(&[1; 32]);
let (fiscus, sync) = (Id::new("fiscus").unwrap(), Id::new("sync").unwrap());
let cert = certify(&root, &CertRequest::standard(sub.public(), fiscus.clone(), sync.clone(), 1000)).unwrap();
let key = sub.public();
assert!(check(&cert, &fiscus, &sync, &key, 1000).is_ok());
assert!(check(&cert, &Id::new("calenda").unwrap(), &sync, &key, 1000).is_err());
assert!(check(&cert, &fiscus, &sync, &Subkey::from_seed(&[2; 32]).public(), 1000).is_err());
assert!(check(&cert, &fiscus, &sync, &key, 1000 + 366 * 86_400).is_err());
}
#[test]
fn statements_are_checked_against_the_request() {
let root = RootKey::from_mnemonic(
"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art",
)
.unwrap();
let lost = Subkey::from_seed(&[1; 32]).public();
let signed = tessera::revoke(&root, lost, 1000, vec![[7; 32]]).unwrap();
let answer = json!(signed.iter().map(|r| r.to_text()).collect::<Vec<_>>());
assert_eq!(statements(&answer, &lost, 1000).unwrap(), signed);
assert!(matches!(statements(&answer, &lost, 999), Err(LocalError::WrongRevocation)));
let other = Subkey::from_seed(&[2; 32]).public();
assert!(matches!(statements(&answer, &other, 1000), Err(LocalError::WrongRevocation)));
assert!(matches!(statements(&json!([]), &lost, 1000), Err(LocalError::WrongRevocation)));
let mut forged = signed[0].to_bytes();
let n = forged.len();
forged[n - 1] ^= 1;
let forged = json!([data_encoding::BASE64URL_NOPAD.encode(&forged)]);
assert!(matches!(statements(&forged, &lost, 1000), Err(LocalError::WrongRevocation)));
}
}