Fundamentum client v0.5.0
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
[package]
|
||||
name = "tabellarius-client"
|
||||
description = "Tabellarius client: MLS groups (OpenMLS) of Domi devices, signed event logs, offline-first sync (docs/TABELLARIUS.md)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
tessera = { path = "../tessera" }
|
||||
envelope = { path = "../envelope" }
|
||||
tabellarius-proto = { path = "../proto" }
|
||||
openmls = "0.9"
|
||||
openmls_rust_crypto = "0.6"
|
||||
openmls_basic_credential = "0.6"
|
||||
openmls_memory_storage = "0.6"
|
||||
openmls_traits = "0.6"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
chacha20poly1305 = "0.10"
|
||||
sha2.workspace = true
|
||||
zeroize.workspace = true
|
||||
thiserror.workspace = true
|
||||
data-encoding.workspace = true
|
||||
|
||||
# The native driver only (docs/V1_1B.md §1); the browser talks through fetch.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
ureq = "3"
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,161 @@
|
||||
//! The native driver (docs/V1_1B.md §1): [`Client`] is the [`Core`] over `ureq` and the app's [`Subkey`],
|
||||
//! with the blocking API apps have used since v0.2. Neither the transport nor the signer ever waits, so each
|
||||
//! operation completes the first time its future is polled: no executor, no thread.
|
||||
|
||||
use crate::{
|
||||
AppEvent, Core, Device, GroupId, HttpRequest, HttpResponse, Result, StateStore, SyncReport, Transport,
|
||||
VerifiedEvent,
|
||||
};
|
||||
use std::future::Future;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::sync::Arc;
|
||||
use std::task::{Context, Poll, Waker};
|
||||
use std::time::Duration;
|
||||
use tessera::{BackupSecret, Revocation, Subkey, SubkeyCert};
|
||||
|
||||
/// The blocking HTTP transport: no redirects, 15 s for a whole request.
|
||||
pub struct Ureq(ureq::Agent);
|
||||
|
||||
impl Default for Ureq {
|
||||
fn default() -> Self {
|
||||
Ureq(
|
||||
ureq::Agent::config_builder()
|
||||
.max_redirects(0)
|
||||
.http_status_as_error(false)
|
||||
.timeout_global(Some(Duration::from_secs(15)))
|
||||
.build()
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Transport for Ureq {
|
||||
async fn send(&self, req: HttpRequest) -> std::result::Result<HttpResponse, String> {
|
||||
fn with<B>(mut r: ureq::RequestBuilder<B>, headers: &[(&'static str, String)]) -> ureq::RequestBuilder<B> {
|
||||
for (n, v) in headers {
|
||||
r = r.header(*n, v);
|
||||
}
|
||||
r
|
||||
}
|
||||
let resp = match req.method.as_str() {
|
||||
"GET" => with(self.0.get(&req.url), &req.headers).call(),
|
||||
"DELETE" => with(self.0.delete(&req.url), &req.headers).call(),
|
||||
"PUT" => with(self.0.put(&req.url), &req.headers).send(&req.body[..]),
|
||||
_ => with(self.0.post(&req.url), &req.headers).send(&req.body[..]),
|
||||
};
|
||||
let mut resp = resp.map_err(|e| e.to_string())?;
|
||||
let status = resp.status().as_u16();
|
||||
let body = resp.body_mut().read_to_vec().unwrap_or_default();
|
||||
Ok(HttpResponse { status, body })
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a core operation over the native transport and signer: it is ready on the first poll.
|
||||
fn now<F: Future>(f: F) -> F::Output {
|
||||
let mut f = std::pin::pin!(f);
|
||||
match f.as_mut().poll(&mut Context::from_waker(Waker::noop())) {
|
||||
Poll::Ready(v) => v,
|
||||
// Unreachable: `Ureq` and `Subkey` never return Pending, and the core awaits nothing else.
|
||||
Poll::Pending => unreachable!("a native operation waited"),
|
||||
}
|
||||
}
|
||||
|
||||
fn system_ms() -> u64 {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The native client. Every operation that does not talk to the relay or sign (`groups`, `log`, `members`,
|
||||
/// `import`, …) is the [`Core`]'s, reached through `Deref`.
|
||||
pub struct Client(Core<Ureq, Subkey>);
|
||||
|
||||
impl Deref for Client {
|
||||
type Target = Core<Ureq, Subkey>;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl DerefMut for Client {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Client {
|
||||
/// Opens the client for `device`'s app, with its state from `store` (or empty).
|
||||
pub fn open(relay: &str, device: Device, store: Box<dyn StateStore>) -> Result<Client> {
|
||||
Core::open(relay, device.cert, device.subkey, Ureq::default(), store, Arc::new(system_ms)).map(Client)
|
||||
}
|
||||
|
||||
/// The group of this person's own devices for this app; created on first use.
|
||||
pub fn self_group(&mut self) -> Result<GroupId> {
|
||||
now(self.0.self_group())
|
||||
}
|
||||
|
||||
/// A new group shared with people you will invite.
|
||||
pub fn open_group(&mut self, name: &str) -> Result<GroupId> {
|
||||
now(self.0.open_group(name))
|
||||
}
|
||||
|
||||
/// Signs `events`, applies them to the local log at once, and queues them for the group. Never needs the
|
||||
/// relay.
|
||||
pub fn send(&mut self, g: &GroupId, events: Vec<AppEvent>) -> Result<()> {
|
||||
now(self.0.send(g, events))
|
||||
}
|
||||
|
||||
/// An invite token (`tab1:…`). Needs the relay. See [`Core::invite`].
|
||||
pub fn invite(&mut self, g: &GroupId) -> Result<String> {
|
||||
now(self.0.invite(g))
|
||||
}
|
||||
|
||||
/// Asks to join with an invite token. Needs the relay. See [`Core::join`].
|
||||
pub fn join(&mut self, token: &str) -> Result<()> {
|
||||
now(self.0.join(token))
|
||||
}
|
||||
|
||||
/// Removes a member. Needs the relay.
|
||||
pub fn remove(&mut self, g: &GroupId, member: u32) -> Result<()> {
|
||||
now(self.0.remove(g, member))
|
||||
}
|
||||
|
||||
/// See [`Core::apply_revocation`].
|
||||
pub fn apply_revocation(&mut self, statements: &[Revocation]) -> Result<usize> {
|
||||
now(self.0.apply_revocation(statements))
|
||||
}
|
||||
|
||||
/// See [`Core::announce_revocation`].
|
||||
pub fn announce_revocation(&mut self, g: &GroupId, statements: Vec<Revocation>) -> Result<()> {
|
||||
now(self.0.announce_revocation(g, statements))
|
||||
}
|
||||
|
||||
/// See [`Core::revoke`].
|
||||
pub fn revoke(&mut self, g: &GroupId, statements: Vec<Revocation>) -> Result<usize> {
|
||||
now(self.0.revoke(g, statements))
|
||||
}
|
||||
|
||||
/// See [`Core::renew`].
|
||||
pub fn renew(&mut self, cert: SubkeyCert) -> Result<()> {
|
||||
now(self.0.renew(cert))
|
||||
}
|
||||
|
||||
/// See [`Core::backup`].
|
||||
pub fn backup(&mut self, secret: &BackupSecret) -> Result<bool> {
|
||||
now(self.0.backup(secret))
|
||||
}
|
||||
|
||||
/// See [`Core::restore`].
|
||||
pub fn restore(&self, secret: &BackupSecret) -> Result<Vec<Vec<u8>>> {
|
||||
now(self.0.restore(secret))
|
||||
}
|
||||
|
||||
/// Uploads what is queued, downloads and verifies what is new, admits invited devices, picks up groups this
|
||||
/// device was admitted to. An unreachable relay is `relay_ok: false`, not an error.
|
||||
pub fn sync(&mut self) -> Result<SyncReport> {
|
||||
now(self.0.sync())
|
||||
}
|
||||
|
||||
/// `sync`, then the group's log.
|
||||
pub fn pull(&mut self, g: &GroupId) -> Result<Vec<VerifiedEvent>> {
|
||||
now(self.0.pull(g))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
//! Where the client keeps its state (docs/TABELLARIUS.md §5). The state holds MLS secrets, so on disk it is
|
||||
//! always encrypted, with a key the app keeps in Custos.
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
|
||||
use std::io;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Mutex;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
/// `Send`, so a [`crate::Client`] can live in a server task or a Tauri app's state.
|
||||
pub trait StateStore: Send {
|
||||
fn load(&self) -> io::Result<Option<Vec<u8>>>;
|
||||
fn save(&self, state: &[u8]) -> io::Result<()>;
|
||||
}
|
||||
|
||||
/// State in memory only: tests, and apps that persist it themselves.
|
||||
#[derive(Default)]
|
||||
pub struct MemoryStore(Mutex<Option<Zeroizing<Vec<u8>>>>);
|
||||
|
||||
impl MemoryStore {
|
||||
pub fn with(state: Vec<u8>) -> MemoryStore {
|
||||
MemoryStore(Mutex::new(Some(Zeroizing::new(state))))
|
||||
}
|
||||
}
|
||||
|
||||
impl StateStore for MemoryStore {
|
||||
fn load(&self) -> io::Result<Option<Vec<u8>>> {
|
||||
Ok(self.0.lock().map_err(|_| io::Error::other("lock"))?.as_ref().map(|s| s.to_vec()))
|
||||
}
|
||||
|
||||
fn save(&self, state: &[u8]) -> io::Result<()> {
|
||||
*self.0.lock().map_err(|_| io::Error::other("lock"))? = Some(Zeroizing::new(state.to_vec()));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAGIC: &[u8; 4] = b"TSF1";
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// State in a file: `TSF1 ‖ nonce (24) ‖ XChaCha20-Poly1305(key, nonce, state, aad = TSF1)`, written to a temporary
|
||||
/// file and renamed. The key comes from Custos (`domi://<app>/tabellarius-state`), never from a file.
|
||||
pub struct EncryptedFileStore {
|
||||
path: PathBuf,
|
||||
key: Zeroizing<[u8; 32]>,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl EncryptedFileStore {
|
||||
pub fn new(path: impl Into<PathBuf>, key: [u8; 32]) -> EncryptedFileStore {
|
||||
EncryptedFileStore { path: path.into(), key: Zeroizing::new(key) }
|
||||
}
|
||||
|
||||
fn cipher(&self) -> XChaCha20Poly1305 {
|
||||
XChaCha20Poly1305::new_from_slice(self.key.as_ref()).expect("32-byte key")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl StateStore for EncryptedFileStore {
|
||||
fn load(&self) -> io::Result<Option<Vec<u8>>> {
|
||||
let bytes = match std::fs::read(&self.path) {
|
||||
Ok(b) => b,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
if bytes.len() < 4 + 24 || &bytes[..4] != MAGIC {
|
||||
return Err(io::Error::other("not a Tabellarius state file"));
|
||||
}
|
||||
let nonce = XNonce::from_slice(&bytes[4..28]);
|
||||
let plain = self
|
||||
.cipher()
|
||||
.decrypt(nonce, Payload { msg: &bytes[28..], aad: MAGIC })
|
||||
.map_err(|_| io::Error::other("the state file does not open with this key (wrong key or damaged)"))?;
|
||||
Ok(Some(plain))
|
||||
}
|
||||
|
||||
fn save(&self, state: &[u8]) -> io::Result<()> {
|
||||
let nonce_bytes = tabellarius_proto::random32();
|
||||
let nonce = XNonce::from_slice(&nonce_bytes[..24]);
|
||||
let ct = self
|
||||
.cipher()
|
||||
.encrypt(nonce, Payload { msg: state, aad: MAGIC })
|
||||
.map_err(|_| io::Error::other("encryption"))?;
|
||||
let mut out = MAGIC.to_vec();
|
||||
out.extend_from_slice(&nonce_bytes[..24]);
|
||||
out.extend_from_slice(&ct);
|
||||
let tmp = self.path.with_extension("tmp");
|
||||
std::fs::write(&tmp, &out)?;
|
||||
std::fs::rename(&tmp, &self.path)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_file_is_ciphertext_and_opens_only_with_its_key() {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("tsf-{}", tabellarius_proto::b64(&tabellarius_proto::random32()[..6])));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("state.tsf");
|
||||
let s = EncryptedFileStore::new(&path, [7; 32]);
|
||||
assert_eq!(s.load().unwrap(), None);
|
||||
s.save(b"MARKER-SECRET-STATE").unwrap();
|
||||
let raw = std::fs::read(&path).unwrap();
|
||||
assert!(!raw.windows(6).any(|w| w == b"MARKER"));
|
||||
assert_eq!(s.load().unwrap().unwrap(), b"MARKER-SECRET-STATE");
|
||||
assert!(EncryptedFileStore::new(&path, [8; 32]).load().is_err());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//! What the core needs from its surroundings (docs/V1_1B.md §1, §2): a way to reach the relay and the device
|
||||
//! key. The native driver implements both without ever waiting; the browser's wait on `fetch` and WebCrypto.
|
||||
|
||||
use std::future::Future;
|
||||
use tessera::{PublicKey, Signature, Subkey};
|
||||
|
||||
/// One HTTP request to the relay, already signed with a mailbox key.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct HttpRequest {
|
||||
pub method: String,
|
||||
pub url: String,
|
||||
pub headers: Vec<(&'static str, String)>,
|
||||
pub body: Vec<u8>,
|
||||
}
|
||||
|
||||
/// The relay's answer: any status, and the body.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct HttpResponse {
|
||||
pub status: u16,
|
||||
pub body: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Reaches the relay. `Err` only when it could not be reached (offline); every HTTP status is an `Ok` answer.
|
||||
/// No redirects are followed.
|
||||
pub trait Transport {
|
||||
fn send(&self, req: HttpRequest) -> impl Future<Output = Result<HttpResponse, String>>;
|
||||
}
|
||||
|
||||
/// The device key: the app subkey its cert certifies. The domains are prepended here, never by the caller,
|
||||
/// so a signer cannot be asked to sign one kind of statement as another.
|
||||
pub trait DeviceSigner {
|
||||
fn public(&self) -> PublicKey;
|
||||
/// A signature over `tessera::EVENT_DOMAIN ‖ tbs`.
|
||||
fn sign_event_tbs(&self, tbs: &[u8]) -> impl Future<Output = Result<Signature, String>>;
|
||||
/// A signature over `tessera::CREDENTIAL_DOMAIN ‖ tbs`.
|
||||
fn sign_credential_tbs(&self, tbs: &[u8]) -> impl Future<Output = Result<Signature, String>>;
|
||||
}
|
||||
|
||||
impl DeviceSigner for Subkey {
|
||||
fn public(&self) -> PublicKey {
|
||||
Subkey::public(self)
|
||||
}
|
||||
|
||||
async fn sign_event_tbs(&self, tbs: &[u8]) -> Result<Signature, String> {
|
||||
Ok(Subkey::sign_event_tbs(self, tbs))
|
||||
}
|
||||
|
||||
async fn sign_credential_tbs(&self, tbs: &[u8]) -> Result<Signature, String> {
|
||||
Ok(Subkey::sign_credential_tbs(self, tbs))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user