//! A receipt, signed by the device that made it (keys slice KS1). //! //! The signed string is //! `lp("cotton-receipt-v1") ‖ lp(database id) ‖ lp(SHA-256(bytes))`, where //! `lp(x)` is a 4-byte big-endian length followed by x, and `bytes` are the //! receipt's canonical bytes exactly as `mint` made them ([`crate::canonical`]). //! The signature is Ed25519, 64 bytes: raw in the `sig` column beside the //! bytes, base64url unpadded in an op's `sig` on the wire. //! //! The database id is in the string so a receipt lifted out of one database //! verifies in no other. The op id is outside the bytes and outside the //! signature, so a re-keyed op id breaks nothing. //! //! THE KEY IS THE AUTHOR'S DEVICE. A receipt's stamp names its author, the //! author's fact (`cotton_authors`) names a device, and a device id is the //! public half of its Ed25519 key — so a verifier reads stamp → author fact → //! `device_id` → key ([`verify_op`]). A handle that signs coins its authors //! under the signer's key ([`crate::mint`]), which is what makes that walk end //! at a key. //! //! The private half never enters this crate: a handle is given a //! [`ReceiptSigner`] by the process that holds the device key //! ([`crate::driver::Driver::signed_by`]), and a handle with none mints //! unsigned receipts — a test's, or a server that is not a device. use sha2::{Digest, Sha256}; use crate::driver::Driver; use crate::error::{Result, StoreError}; use crate::protocol::types::CottonOp; /// The first field of every signed string: what is being signed, and under /// which version of this rule. pub const CONTEXT: &str = "cotton-receipt-v1"; /// An Ed25519 signature's length. pub const SIG_LENGTH: usize = 64; /// The device key a handle's receipts are signed with. pub trait ReceiptSigner: Send + Sync { /// The device id: the key's public half, 32 bytes, base64url unpadded. fn device_key(&self) -> String; /// Sign the string [`signed_string`] built. fn sign(&self, message: &[u8]) -> std::result::Result<[u8; SIG_LENGTH], String>; } /// Where a process's handles read their signer from. A process opens files /// before it has read its device key from the keychain, so every handle it /// opens shares one slot and the key is put in once, when it is known; a /// handle whose slot is still empty mints unsigned. #[derive(Clone, Default)] pub struct SignerSlot(std::sync::Arc>>); impl SignerSlot { pub fn filled(signer: std::sync::Arc) -> SignerSlot { let slot = SignerSlot::default(); slot.fill(signer); slot } /// Put the device key in. A slot is filled once: a second key is ignored, /// because a process has one device key for its whole life. pub fn fill(&self, signer: std::sync::Arc) { let _ = self.0.set(signer); } pub fn get(&self) -> Option<&std::sync::Arc> { self.0.get() } } /// Why a receipt does not verify — the two things the serving Mac says. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Unverified { /// It carries no signature, or its author names no device key. Unsigned, /// It carries one that is not the author's device's over these bytes in /// this database. Mismatch, /// It is signed, and its author has not announced itself here yet, so /// there is no key to check it against: not a refusal for good — the /// author's fact is on its way, and the write is offered again after it. UnknownAuthor, } /// A retryable rejection's reason word: the write's author has no fact on the /// serving Mac yet, so its signature cannot be checked until the fact lands. pub const REJECTION_AUTHOR_UNKNOWN: &str = "author_unknown"; /// A retryable rejection's reason word (slice 12): a relayed author fact — /// one naming a device other than the pusher — that the serving Mac holds /// until the device it names pushes it itself. pub const REJECTION_AUTHOR_WAITING: &str = "author_waiting"; impl Unverified { pub fn reason(self) -> &'static str { match self { Unverified::Unsigned => "this write is not signed by the device that made it", Unverified::Mismatch => "this write's signature does not match the device that made it", Unverified::UnknownAuthor => "this write's author has not announced itself to the serving Mac yet", } } } fn lp(out: &mut Vec, field: &[u8]) { // A field here is a constant, an id or a 32-byte digest: never near 4 GiB. out.extend_from_slice(&u32::try_from(field.len()).unwrap_or(u32::MAX).to_be_bytes()); out.extend_from_slice(field); } /// The string a device signs for one receipt in one database. pub fn signed_string(database_id: &str, bytes: &[u8]) -> Vec { let digest = Sha256::digest(bytes); let mut out = Vec::with_capacity(12 + CONTEXT.len() + database_id.len() + digest.len()); lp(&mut out, CONTEXT.as_bytes()); lp(&mut out, database_id.as_bytes()); lp(&mut out, &digest); out } /// An op's `sig` as the 64 raw bytes its column keeps, or `None` when it /// carries none or one that is not 64 bytes of base64url. pub fn sig_bytes(op: &CottonOp) -> Option> { let raw = base64url_decode(op.sig.as_deref()?)?; (raw.len() == SIG_LENGTH).then_some(raw) } /// The `sig` column's bytes as an op carries them. pub fn sig_text(raw: &[u8]) -> String { base64url_encode(raw) } /// Sign an op this handle just minted, when the handle has a signer. The one /// door a signature is made through, called where `mint` makes bytes. pub(crate) fn seal(db: &Driver, database_id: &str, mut op: CottonOp) -> Result { let Some(signer) = db.signer() else { return Ok(op); }; let sig = signer .sign(&signed_string(database_id, op.receipt.as_bytes())) .map_err(|e| StoreError::refused(format!("this device's key could not sign the write: {e}")))?; op.sig = Some(sig_text(&sig)); Ok(op) } /// Is this receipt stamped below the oldest file this build moves, or does a /// schema move between its stamp and this build drop its table or fold a /// field it writes (`crate::schema::move_intents`)? Below the floor no rise /// is declared, so nothing here can say what its fields mean now. fn moved_away(receipt: &crate::canonical::Receipt) -> bool { if receipt.schema < crate::shape_move::LEDGER_BASE { return true; } crate::schema::move_intents::losses_between(receipt.schema, crate::migrate::SCHEMA_VERSION).any(|loss| match loss { crate::schema::move_intents::Loss::DropTable { table } => *table == receipt.table, crate::schema::move_intents::Loss::FoldColumn { table, column, .. } => { *table == receipt.table && receipt.fields.contains_key(*column) } }) } /// Does moving the copy this unsent change was made in to this build's schema /// lose something it writes — its table dropped, or a field it writes folded? /// Such a change holds its copy where it is (`cotton_client::dev_heal`). A /// receipt that will not decode is answered `true`: what it writes cannot be /// told. pub fn touches_a_loss(op: &CottonOp) -> bool { match crate::canonical::decode(op.receipt.as_bytes()) { Ok(receipt) => receipt.schema < crate::migrate::SCHEMA_VERSION && moved_away(&receipt), Err(_) => true, } } /// Does `sig` verify as `device_key`'s over these bytes in this database? pub fn verify( device_key: &str, database_id: &str, bytes: &[u8], sig: Option<&[u8]>, ) -> std::result::Result<(), Unverified> { let sig = sig.ok_or(Unverified::Unsigned)?; // An author that names no key (`device:` of a handle that never // signed) made a write nobody can check: unsigned, whatever rides beside it. let key = public_key(device_key).ok_or(Unverified::Unsigned)?; let sig: [u8; SIG_LENGTH] = sig.try_into().map_err(|_| Unverified::Mismatch)?; key.verify_strict( &signed_string(database_id, bytes), &ed25519_dalek::Signature::from_bytes(&sig), ) .map_err(|_| Unverified::Mismatch) } /// The device an author fact names, when `op` is the fact that introduces /// its own author — the one receipt that answers for itself. pub fn introduced_device(op: &CottonOp) -> Option { if op.table != crate::fold::AUTHORS_TABLE || op.row_id != op.device_id { return None; } op.patch .as_ref() .and_then(|patch| patch.get("device_id")) .and_then(serde_json::Value::as_str) .map(str::to_string) } /// Verify an op against the device its author names. `device_of` answers an /// author's `cotton_authors.device_id`; an author fact answers for itself, by /// the device it names, because it is the receipt that introduces the author. pub fn verify_op( op: &CottonOp, database_id: &str, device_of: impl Fn(&str) -> Option, ) -> std::result::Result<(), Unverified> { if op.sig.is_none() { return Err(Unverified::Unsigned); } let named_by_fact = introduced_device(op); let device_key = device_of(&op.device_id).or(named_by_fact).ok_or(Unverified::UnknownAuthor)?; let sig = sig_bytes(op).ok_or(Unverified::Mismatch)?; verify(&device_key, database_id, op.receipt.as_bytes(), Some(&sig)) } fn public_key(device_key: &str) -> Option { let raw: [u8; 32] = base64url_decode(device_key)?.try_into().ok()?; ed25519_dalek::VerifyingKey::from_bytes(&raw).ok() } fn base64url_encode(raw: &[u8]) -> String { use base64::Engine as _; base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(raw) } fn base64url_decode(text: &str) -> Option> { use base64::Engine as _; base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(text).ok() } /// A signer over a key held in memory — for this crate's tests and every /// other crate's fixtures. A shipping process signs with the key its keychain /// holds, through its own [`ReceiptSigner`]. #[cfg(any(test, feature = "fixtures"))] pub struct KeySigner(pub ed25519_dalek::SigningKey); #[cfg(any(test, feature = "fixtures"))] impl KeySigner { /// The signer of the key whose 32 secret bytes are all `seed`. pub fn of_seed(seed: u8) -> KeySigner { KeySigner(ed25519_dalek::SigningKey::from_bytes(&[seed; 32])) } /// Sign an op built outside `mint` (a fixture's), as this key in /// `database_id`. pub fn sign_op(&self, database_id: &str, mut op: CottonOp) -> CottonOp { use ed25519_dalek::Signer as _; let sig = self.0.sign(&signed_string(database_id, op.receipt.as_bytes())); op.sig = Some(sig_text(&sig.to_bytes())); op } } #[cfg(any(test, feature = "fixtures"))] impl ReceiptSigner for KeySigner { fn device_key(&self) -> String { base64url_encode(self.0.verifying_key().as_bytes()) } fn sign(&self, message: &[u8]) -> std::result::Result<[u8; SIG_LENGTH], String> { use ed25519_dalek::Signer as _; Ok(self.0.sign(message).to_bytes()) } } #[cfg(test)] #[path = "signed_tests.rs"] mod tests; /// Whether `signature` (Ed25519, base64url) is `key`'s (base64url) over /// `bytes`, strictly. A malformed key or signature never verifies. pub fn verifies(key: &str, bytes: &[u8], signature: &str) -> bool { use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; use ed25519_dalek::{Signature, VerifyingKey}; let Some(key) = URL_SAFE_NO_PAD .decode(key) .ok() .and_then(|raw| raw.try_into().ok()) .and_then(|raw| VerifyingKey::from_bytes(&raw).ok()) else { return false; }; let Some(sig) = URL_SAFE_NO_PAD .decode(signature) .ok() .and_then(|raw| Signature::from_slice(&raw).ok()) else { return false; }; key.verify_strict(bytes, &sig).is_ok() }