Cotton code
430 lines · 16.7 KB · RustRaw
//! The device key's USE. Its storage is the Keychain's, and the Keychain is//! Swift's (design M8).//!//! A server admits a DEVICE, not a session: every owner route is signed by an//! Ed25519 key the server has approved, and the public half IS the device id (32//! raw bytes, base64url). This type holds the key the app handed down at open//! and answers the two questions the client half asks of it — "who am I" and//! "sign this".//!//! WHAT IS DELIBERATELY NOT HERE: the string a request signs. Its seven fields//! are declared once, in `cotton-server`'s `devices::device_auth`//! (`cotton-device-v1`), because the side that VERIFIES owns the format; a//! second copy in the client is a format that drifts and a device that is//! refused without being told why. The signer that composes it is wired in the//! connection port (3e).use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine;use ed25519_dalek::{Signer, SigningKey};/// The 32-byte Ed25519 seed a device's key is.pub const SECRET_LENGTH: usize = 32;#[derive(Debug, thiserror::Error)]pub enum IdentityError {    #[error("a device key is {SECRET_LENGTH} bytes; this one is {got}")]    WrongLength { got: usize },}pub struct DeviceIdentity {    signing: SigningKey,}impl std::fmt::Debug for DeviceIdentity {    /// The device id, never the secret: a `{:?}` of a key is how key material    /// reaches a log file.    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.debug_struct("DeviceIdentity")            .field("device_id", &self.device_id())            .finish_non_exhaustive()    }}/// The device key signs the receipts this device mints (keys slice KS1): the/// store asks for a signature and never holds the secret.impl cotton_store::signed::ReceiptSigner for DeviceIdentity {    fn device_key(&self) -> String {        self.device_id()    }    fn sign(&self, message: &[u8]) -> Result<[u8; cotton_store::signed::SIG_LENGTH], String> {        Ok(DeviceIdentity::sign(self, message))    }}impl DeviceIdentity {    /// From the 32 raw bytes the Keychain held.    pub fn from_secret(secret: &[u8]) -> Result<Self, IdentityError> {        let bytes: [u8; SECRET_LENGTH] = secret            .try_into()            .map_err(|_| IdentityError::WrongLength { got: secret.len() })?;        Ok(Self {            signing: SigningKey::from_bytes(&bytes),        })    }    /// The device id: the public key, 32 raw bytes, base64url unpadded — the    /// same 43 characters the `x-cotton-device` header carries.    pub fn device_id(&self) -> String {        URL_SAFE_NO_PAD.encode(self.signing.verifying_key().to_bytes())    }    /// Sign the bytes a caller composed, base64url unpadded — the shape of    /// `x-cotton-device-sig`.    pub fn sign_base64url(&self, payload: &[u8]) -> String {        URL_SAFE_NO_PAD.encode(self.sign(payload))    }    /// The raw 64 bytes, for a caller that formats the header itself.    ///    /// `cotton_core::device::signature::format_device_sig_header` takes bytes    /// and does the encoding, so the request signer asks for these rather than    /// decoding what [`Self::sign_base64url`] just encoded.    pub fn sign(&self, payload: &[u8]) -> [u8; 64] {        self.signing.sign(payload).to_bytes()    }}/// The id the server admits THIS device by — its device key id — in ONE slot/// per process.////// The shell fills it at open, from the same identity the transport signs/// with; every pass that names this device in the media ledger reads it when/// it runs, so a slot filled after a pass was built is still the answer. The/// replica's AUTHOR id (`Replica::device_id`, `device:<ulid>`) answers a/// different question and is never this one. `None` is a device that has not/// paired — a named state, never a guess.#[derive(Debug, Clone, Default)]pub struct DeviceKey(std::sync::Arc<std::sync::Mutex<Option<String>>>);impl DeviceKey {    /// A slot already holding `key` — for a caller that knows it up front.    pub fn fixed(key: Option<String>) -> DeviceKey {        let slot = DeviceKey::default();        slot.set(key);        slot    }    pub fn set(&self, key: Option<String>) {        *self.0.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = key;    }    pub fn get(&self) -> Option<String> {        self.0            .lock()            .unwrap_or_else(|poisoned| poisoned.into_inner())            .clone()            .filter(|key| !key.is_empty())    }}// ─────────────────────────────────────────────────────────────────────────────// Where the seed LIVES — the one decision the Keychain does not make for us.// ─────────────────────────────────────────────────────────────────────────────/// Where this install's device seed is kept.////// Design M8: Swift owns the Security framework, so a PACKAGED app keeps the/// 32-byte seed in the Keychain (`kSecClassGenericPassword`) and hands it down/// at open — there is no file, because a Keychain item IS the store. Electron/// needed `identity/device.key` only because `safeStorage` encrypts and the/// ciphertext had to live somewhere.////// The one exception is a REHEARSAL: an unpackaged build pointed at an/// overridden data directory keeps its seed in plain text beside the synthetic/// database, exactly as `rehearsalEncryptor` did, so a walk over a scratch/// folder never touches the Keychain the real install uses.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum IdentityStorage {    Keychain,    RehearsalFile,}/// The rehearsal decision, as a pure function of the two facts that decide it.////// BOTH have to be true. A packaged app never takes this path whatever its data/// directory — the installed app's key belongs in the Keychain even when it is/// pointed somewhere else for an afternoon — and a dev build on the REAL data/// directory is the everyday loop, whose device row is the one the phone is/// paired with.pub fn identity_storage_for(packaged: bool, data_dir_override: Option<&str>) -> IdentityStorage {    if !packaged && data_dir_override.is_some() {        IdentityStorage::RehearsalFile    } else {        IdentityStorage::Keychain    }}/// The first bytes of a rehearsal's key file. It is there so the file SAYS what/// it is: a seed nothing encrypted, written by a build that was told to use a/// scratch folder.pub const REHEARSAL_MARK: &str = "cottondb-rehearsal-v1:";#[derive(Debug, thiserror::Error)]pub enum SeedFileError {    #[error("{path}: {source}")]    Io {        path: String,        #[source]        source: std::io::Error,    },    /// A file that is not a rehearsal's. Never overwritten: re-minting over a    /// key would change this Mac's device id, and a device id that changes is a    /// Mac the server no longer admits.    #[error("{path} was not written by a rehearsal — leave it alone rather than minting over it")]    NotARehearsalFile { path: String },    #[error("{path} holds no usable device key")]    Unreadable { path: String },}/// What a load-or-mint answered.#[derive(Debug, Clone)]pub struct SeedRead {    /// The 32-byte seed.    pub secret: [u8; SECRET_LENGTH],    /// True the first time, false every time after.    pub minted: bool,}/// Read `<dataDir>/identity/device.key`, minting one the first time.////// `0600`, and the directory `0700`. Two rules that are the whole point:/// **an existing file is never minted over** — not one this build cannot read,/// and not one another writer left — because the seed IS the device id, and a/// new device id is a Mac the server stops admitting mid-rehearsal; and the/// mint is EXCLUSIVE (`create_new`), so two starts racing on one folder end/// with one key and the loser reading the winner's.pub fn load_or_mint_rehearsal_seed(path: &std::path::Path) -> Result<SeedRead, SeedFileError> {    let io = |source: std::io::Error| SeedFileError::Io {        path: path.display().to_string(),        source,    };    match std::fs::read_to_string(path) {        Ok(text) => read_rehearsal_seed(path, &text).map(|secret| SeedRead {            secret,            minted: false,        }),        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {            let secret = mint_seed();            if let Some(parent) = path.parent() {                std::fs::create_dir_all(parent).map_err(io)?;                set_mode(parent, 0o700);            }            let body = format!("{REHEARSAL_MARK}{}\n", URL_SAFE_NO_PAD.encode(secret));            match std::fs::OpenOptions::new()                .write(true)                .create_new(true)                .open(path)            {                Ok(mut file) => {                    use std::io::Write;                    file.write_all(body.as_bytes()).map_err(io)?;                    drop(file);                    set_mode(path, 0o600);                    Ok(SeedRead {                        secret,                        minted: true,                    })                }                // Somebody else won the race between the read and the create.                // Their key is the one this install has, so read it.                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {                    let text = std::fs::read_to_string(path).map_err(io)?;                    read_rehearsal_seed(path, &text).map(|secret| SeedRead {                        secret,                        minted: false,                    })                }                Err(error) => Err(io(error)),            }        }        Err(error) => Err(io(error)),    }}fn read_rehearsal_seed(    path: &std::path::Path,    text: &str,) -> Result<[u8; SECRET_LENGTH], SeedFileError> {    let Some(encoded) = text.trim().strip_prefix(REHEARSAL_MARK) else {        return Err(SeedFileError::NotARehearsalFile {            path: path.display().to_string(),        });    };    let bytes = URL_SAFE_NO_PAD        .decode(encoded)        .map_err(|_| SeedFileError::Unreadable {            path: path.display().to_string(),        })?;    bytes.try_into().map_err(|_| SeedFileError::Unreadable {        path: path.display().to_string(),    })}/// 32 bytes from the OS. Not a seam: a device key drawn from an injected/// "random" would be a device key a test could predict, and this one is only/// ever a rehearsal's.fn mint_seed() -> [u8; SECRET_LENGTH] {    use rand::RngCore;    let mut secret = [0u8; SECRET_LENGTH];    rand::rngs::OsRng.fill_bytes(&mut secret);    secret}fn set_mode(path: &std::path::Path, mode: u32) {    #[cfg(unix)]    {        use std::os::unix::fs::PermissionsExt;        let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));    }    #[cfg(not(unix))]    let _ = (path, mode);}#[cfg(test)]mod tests {    use super::*;    use ed25519_dalek::{Signature, Verifier, VerifyingKey};    /// Synthetic, fixed, and not a key any device has ever held.    const SEED: [u8; SECRET_LENGTH] = [7u8; SECRET_LENGTH];    #[test]    fn the_device_id_is_the_public_key_in_the_43_characters_the_header_carries() {        let identity = DeviceIdentity::from_secret(&SEED).expect("the key");        let id = identity.device_id();        assert_eq!(id.len(), 43);        assert!(id            .bytes()            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'));    }    #[test]    fn the_same_secret_is_always_the_same_device() {        let a = DeviceIdentity::from_secret(&SEED).expect("the key");        let b = DeviceIdentity::from_secret(&SEED).expect("the key");        assert_eq!(a.device_id(), b.device_id());    }    #[test]    fn a_signature_verifies_against_the_device_id_the_server_reads_off_the_header() {        let identity = DeviceIdentity::from_secret(&SEED).expect("the key");        let payload = b"cotton-device-v1\nhttps://example.invalid\nGET\n/v1/me\n0\n\n";        let signature = identity.sign_base64url(payload);        let key_bytes: [u8; 32] = URL_SAFE_NO_PAD            .decode(identity.device_id())            .expect("the id decodes")            .try_into()            .expect("32 bytes");        let signature_bytes: [u8; 64] = URL_SAFE_NO_PAD            .decode(signature)            .expect("the signature decodes")            .try_into()            .expect("64 bytes");        VerifyingKey::from_bytes(&key_bytes)            .expect("the key")            .verify(payload, &Signature::from_bytes(&signature_bytes))            .expect("the signature verifies");    }    // ── Where the seed lives ───────────────────────────────────────────────    #[test]    fn the_rehearsal_file_is_chosen_only_by_an_unpackaged_build_told_to_use_another_folder() {        assert_eq!(            identity_storage_for(false, Some("/tmp/walk")),            IdentityStorage::RehearsalFile        );        // The installed app keeps the Keychain even when pointed elsewhere.        assert_eq!(            identity_storage_for(true, Some("/tmp/walk")),            IdentityStorage::Keychain        );        // And a dev build on the real data directory is the everyday loop,        // whose device row is the one the phone is paired with.        assert_eq!(identity_storage_for(false, None), IdentityStorage::Keychain);        assert_eq!(identity_storage_for(true, None), IdentityStorage::Keychain);    }    #[test]    fn a_rehearsal_seed_is_minted_once_at_0600_and_read_back_as_the_same_device() {        let root = tempfile::tempdir().expect("a temp dir");        let path = root.path().join("identity").join("device.key");        let first = load_or_mint_rehearsal_seed(&path).expect("a seed");        assert!(first.minted);        let second = load_or_mint_rehearsal_seed(&path).expect("a seed");        assert!(!second.minted);        assert_eq!(first.secret, second.secret);        let id = DeviceIdentity::from_secret(&first.secret)            .expect("the key")            .device_id();        assert_eq!(id.len(), 43);        // The file SAYS it is a rehearsal's, and nothing else can read it.        let text = std::fs::read_to_string(&path).expect("the file");        assert!(text.starts_with(REHEARSAL_MARK));        #[cfg(unix)]        {            use std::os::unix::fs::PermissionsExt;            assert_eq!(                std::fs::metadata(&path)                    .expect("the file")                    .permissions()                    .mode()                    & 0o777,                0o600            );            assert_eq!(                std::fs::metadata(path.parent().expect("the folder"))                    .expect("the folder")                    .permissions()                    .mode()                    & 0o777,                0o700            );        }    }    #[test]    fn a_file_no_rehearsal_wrote_is_refused_rather_than_minted_over() {        let root = tempfile::tempdir().expect("a temp dir");        let path = root.path().join("device.key");        // What the Electron app's Keychain-wrapped file looked like: opaque        // bytes with no mark. Re-minting over it would change this Mac's device        // id, and a device id that changes is a Mac the server stops admitting.        std::fs::write(&path, b"v10\x00\x01\x02").expect("the file");        let error = load_or_mint_rehearsal_seed(&path).expect_err("a refusal");        assert!(matches!(error, SeedFileError::NotARehearsalFile { .. }));        assert_eq!(std::fs::read(&path).expect("the file"), b"v10\x00\x01\x02");    }    #[test]    fn a_rehearsal_file_holding_nonsense_is_unreadable_and_still_never_overwritten() {        let root = tempfile::tempdir().expect("a temp dir");        let path = root.path().join("device.key");        std::fs::write(&path, format!("{REHEARSAL_MARK}not-a-key")).expect("the file");        let error = load_or_mint_rehearsal_seed(&path).expect_err("a refusal");        assert!(matches!(error, SeedFileError::Unreadable { .. }));        assert!(path.exists());    }    #[test]    fn a_key_of_the_wrong_length_is_refused_rather_than_padded() {        let error = DeviceIdentity::from_secret(&[1u8; 16]).expect_err("a refusal");        assert!(error.to_string().contains("16"));    }    #[test]    fn the_debug_rendering_carries_the_device_id_and_no_key_material() {        let identity = DeviceIdentity::from_secret(&SEED).expect("the key");        let rendered = format!("{identity:?}");        assert!(rendered.contains(&identity.device_id()));        assert!(!rendered.contains("signing"));    }}