From 836aa7300f2b6561d4a6a1a422e7b0535f52bad6 Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 3 Nov 2026 15:13:52 +0100 Subject: [PATCH 1/9] refactor(core): split KeyMaterial out of SymmetricKey Wrapping a key only needs its bytes, so `Wraps` now asks for `KeyMaterial`. `SymmetricKey` keeps what only a key that can seal needs. This makes room for wrapped keys that cannot wrap anything themselves, like a signing key. Also rename `RootKEK` to `RootKek`, the spelling the docs already use. No change to what is stored: the golden tests still pass unchanged. Co-Authored-By: Claude Opus 5.5 --- rust/crates/keygo-core/src/ark_session.rs | 8 +++---- .../keygo-core/src/backup/encryption.rs | 2 +- .../keygo-core/src/backup/format/json.rs | 2 +- rust/crates/keygo-core/src/backup/key.rs | 2 +- .../keygo-core/src/crypto/golden_tests.rs | 6 +++--- rust/crates/keygo-core/src/crypto/key.rs | 21 ++++++++++++------- rust/crates/keygo-core/src/crypto/keys.rs | 20 +++++++++--------- rust/crates/keygo-core/src/crypto/mod.rs | 4 ++-- rust/crates/keygo-uniffi/src/backup/mod.rs | 2 +- rust/crates/keygo-uniffi/src/types.rs | 2 +- 10 files changed, 38 insertions(+), 31 deletions(-) diff --git a/rust/crates/keygo-core/src/ark_session.rs b/rust/crates/keygo-core/src/ark_session.rs index d8d2da617..348062718 100644 --- a/rust/crates/keygo-core/src/ark_session.rs +++ b/rust/crates/keygo-core/src/ark_session.rs @@ -1,7 +1,7 @@ use crate::crypto::kdf::new_salt; use crate::crypto::{ - AccountRootKey, CryptoError, Encrypts, NamespaceDataAad, NamespaceId, NamespaceKey, - NamespaceKeyAad, RootKEK, Sealed, SecretKind, SymmetricKey, UserId, VaultId, VaultKey, Wraps, + AccountRootKey, CryptoError, Encrypts, KeyMaterial, NamespaceDataAad, NamespaceId, + NamespaceKey, NamespaceKeyAad, RootKek, Sealed, SecretKind, UserId, VaultId, VaultKey, Wraps, }; use std::sync::{Mutex, MutexGuard}; use subtle::ConstantTimeEq; @@ -208,8 +208,8 @@ impl ArkSession { } } -fn derive_kek(password: &str, salt: &[u8]) -> ArkSessionResult { - RootKEK::from_password(password.as_bytes(), salt).map_err(ArkSessionError::Derivation) +fn derive_kek(password: &str, salt: &[u8]) -> ArkSessionResult { + RootKek::from_password(password.as_bytes(), salt).map_err(ArkSessionError::Derivation) } #[cfg(test)] diff --git a/rust/crates/keygo-core/src/backup/encryption.rs b/rust/crates/keygo-core/src/backup/encryption.rs index 50953b0b1..1991fc146 100644 --- a/rust/crates/keygo-core/src/backup/encryption.rs +++ b/rust/crates/keygo-core/src/backup/encryption.rs @@ -161,7 +161,7 @@ mod tests { use super::*; use crate::backup::CURRENT_VERSION; use crate::crypto::kdf::argon2::MAX_ARGON2_MEM_KIB; - use crate::crypto::{CryptoError, SymmetricKey}; + use crate::crypto::{CryptoError, KeyMaterial}; #[test] fn key_source_serialization() { diff --git a/rust/crates/keygo-core/src/backup/format/json.rs b/rust/crates/keygo-core/src/backup/format/json.rs index 5d5e4de3f..00a1b3d27 100644 --- a/rust/crates/keygo-core/src/backup/format/json.rs +++ b/rust/crates/keygo-core/src/backup/format/json.rs @@ -45,7 +45,7 @@ mod tests { use super::*; use crate::backup::encryption::{Kdf, KeySource}; use crate::backup::{Card, Login, Passkey, Vault}; - use crate::crypto::{AccountRootKey, CryptoError, SymmetricKey}; + use crate::crypto::{AccountRootKey, CryptoError, KeyMaterial}; fn sample_backup() -> Backup { Backup { diff --git a/rust/crates/keygo-core/src/backup/key.rs b/rust/crates/keygo-core/src/backup/key.rs index 28eeb4b41..4725bdf35 100644 --- a/rust/crates/keygo-core/src/backup/key.rs +++ b/rust/crates/keygo-core/src/backup/key.rs @@ -1,6 +1,6 @@ use crate::crypto::kdf::argon2::{Argon2Params, derive_argon2id}; use crate::crypto::kdf::hkdf::derive_hkdf_sha256; -use crate::crypto::{AccountRootKey, CryptoResult, SymmetricKey, symmetric_key}; +use crate::crypto::{AccountRootKey, CryptoResult, KeyMaterial, symmetric_key}; const DOMAIN_PASSPHRASE: &[u8] = b"v1:backup/passphrase"; const DOMAIN_ARK: &[u8] = b"v1:backup/ark"; diff --git a/rust/crates/keygo-core/src/crypto/golden_tests.rs b/rust/crates/keygo-core/src/crypto/golden_tests.rs index 8a5059fc4..fbc0edd0c 100644 --- a/rust/crates/keygo-core/src/crypto/golden_tests.rs +++ b/rust/crates/keygo-core/src/crypto/golden_tests.rs @@ -1,8 +1,8 @@ //! Shipped ciphertexts under fixed keys. They must keep opening; regenerate only with a migration. use crate::crypto::{ - AccountRootKey, Encrypts, ItemAad, ItemDataAad, ItemId, ItemKey, NamespaceDataAad, NamespaceId, - NamespaceKey, NamespaceKeyAad, RootKEK, Sealed, SecretKind, SymmetricKey, UserId, VaultId, + AccountRootKey, Encrypts, ItemAad, ItemDataAad, ItemId, ItemKey, KeyMaterial, NamespaceDataAad, + NamespaceId, NamespaceKey, NamespaceKeyAad, RootKek, Sealed, SecretKind, UserId, VaultId, VaultKey, Wraps, }; use uuid::Uuid; @@ -58,7 +58,7 @@ fn sealed((nonce, ciphertext): (&str, &str)) -> Sealed { #[test] fn password_wrapped_ark_still_unwraps() { - let kek = RootKEK::from_bytes(&KEK).unwrap(); + let kek = RootKek::from_bytes(&KEK).unwrap(); let ark = kek.unwrap_key(&sealed(WRAPPED_ARK), &USER_ID).unwrap(); assert_eq!(ark.as_bytes(), ARK); } diff --git a/rust/crates/keygo-core/src/crypto/key.rs b/rust/crates/keygo-core/src/crypto/key.rs index 617e6df8f..1cc5fda50 100644 --- a/rust/crates/keygo-core/src/crypto/key.rs +++ b/rust/crates/keygo-core/src/crypto/key.rs @@ -2,18 +2,19 @@ use crate::crypto::aad::encode_aad; use crate::crypto::{Aad, CipherKey, CryptoError, CryptoResult, Sealed}; use zeroize::{ZeroizeOnDrop, Zeroizing}; -pub trait SymmetricKey: Sized + ZeroizeOnDrop { +/// Anything that can be sealed under a wrapping key. +pub trait KeyMaterial: Sized + ZeroizeOnDrop { fn from_bytes(bytes: &[u8]) -> CryptoResult; + fn as_bytes(&self) -> &[u8]; +} - fn as_bytes(&self) -> &[u8] { - self.cipher_key().as_slice() - } - +/// A key that can seal things itself. +pub trait SymmetricKey: KeyMaterial { #[doc(hidden)] fn cipher_key(&self) -> &CipherKey; } -pub trait Wraps: SymmetricKey { +pub trait Wraps: SymmetricKey { type Aad: Aad; fn wrap_key(&self, key: &K, aad: &Self::Aad) -> CryptoResult> { @@ -51,7 +52,7 @@ macro_rules! symmetric_key { #[derive(::zeroize::Zeroize, ::zeroize::ZeroizeOnDrop)] $vis struct $name($crate::crypto::CipherKey); - impl $crate::crypto::SymmetricKey for $name { + impl $crate::crypto::KeyMaterial for $name { fn from_bytes(bytes: &[u8]) -> $crate::crypto::CryptoResult { $crate::crypto::CipherKey::try_from(bytes).map(Self).map_err(|_| { $crate::crypto::CryptoError::InvalidKeyLength { @@ -61,6 +62,12 @@ macro_rules! symmetric_key { }) } + fn as_bytes(&self) -> &[u8] { + self.0.as_slice() + } + } + + impl $crate::crypto::SymmetricKey for $name { fn cipher_key(&self) -> &$crate::crypto::CipherKey { &self.0 } diff --git a/rust/crates/keygo-core/src/crypto/keys.rs b/rust/crates/keygo-core/src/crypto/keys.rs index b3a84bf1a..2c0a2d8d2 100644 --- a/rust/crates/keygo-core/src/crypto/keys.rs +++ b/rust/crates/keygo-core/src/crypto/keys.rs @@ -1,14 +1,14 @@ //! Key hierarchy and the AAD of each wrap: //! //! ```text -//! RootKEK --UserId--> AccountRootKey --VaultId--> VaultKey --ItemAad--> ItemKey --ItemDataAad--> item data +//! RootKek --UserId--> AccountRootKey --VaultId--> VaultKey --ItemAad--> ItemKey --ItemDataAad--> item data //! \ //! --NamespaceKeyAad--> NamespaceKey --NamespaceDataAad--> account record //! ``` use crate::crypto::kdf::argon2::{Argon2Params, derive_argon2id}; use crate::crypto::{ - Aad, CipherKey, CryptoResult, Encrypts, ItemId, NamespaceId, SymmetricKey, UserId, VaultId, + Aad, CipherKey, CryptoResult, Encrypts, ItemId, KeyMaterial, NamespaceId, UserId, VaultId, Wraps, aad, symmetric_key, }; use aead::Generate; @@ -24,7 +24,7 @@ const NAMESPACE_KEY_DOMAIN: &str = "v1:ns/key"; const NAMESPACE_DATA_DOMAIN: &str = "v1:ns/data"; symmetric_key! { - pub struct RootKEK; + pub struct RootKek; } symmetric_key! { @@ -118,7 +118,7 @@ impl SecretKind { } } -impl Wraps for RootKEK { +impl Wraps for RootKek { type Aad = UserId; // TODO: bind the credential epoch } @@ -142,7 +142,7 @@ impl Encrypts for NamespaceKey { type Aad = NamespaceDataAad; } -impl RootKEK { +impl RootKek { pub fn from_password(password: &[u8], salt: &[u8]) -> CryptoResult { let derived = derive_argon2id(password, salt, PASSWORD_DOMAIN, Argon2Params::default())?; Self::from_bytes(derived.as_slice()) @@ -170,15 +170,15 @@ mod tests { #[test] fn same_password_and_salt_give_the_same_kek() { - let a = RootKEK::from_password(b"hunter2", SALT).unwrap(); - let b = RootKEK::from_password(b"hunter2", SALT).unwrap(); + let a = RootKek::from_password(b"hunter2", SALT).unwrap(); + let b = RootKek::from_password(b"hunter2", SALT).unwrap(); assert_eq!(a.as_bytes(), b.as_bytes()); } #[test] fn different_salts_give_different_keks() { - let a = RootKEK::from_password(b"hunter2", &[7; 16]).unwrap(); - let b = RootKEK::from_password(b"hunter2", SALT).unwrap(); + let a = RootKek::from_password(b"hunter2", &[7; 16]).unwrap(); + let b = RootKek::from_password(b"hunter2", SALT).unwrap(); assert_ne!(a.as_bytes(), b.as_bytes()); } @@ -187,7 +187,7 @@ mod tests { fn password_domain_is_pinned() { assert_eq!(PASSWORD_DOMAIN, b"v1:kek/pwd"); - let kek = RootKEK::from_password(b"hunter2", &[7; 16]).unwrap(); + let kek = RootKek::from_password(b"hunter2", &[7; 16]).unwrap(); assert_eq!( kek.as_bytes(), diff --git a/rust/crates/keygo-core/src/crypto/mod.rs b/rust/crates/keygo-core/src/crypto/mod.rs index a026d9d93..8b7040727 100644 --- a/rust/crates/keygo-core/src/crypto/mod.rs +++ b/rust/crates/keygo-core/src/crypto/mod.rs @@ -12,10 +12,10 @@ pub use cipher::{Cipher, CipherKey, KEY_LEN, NONCE_LEN, Sealed}; pub use error::{CryptoError, CryptoResult}; pub use ids::{ItemId, NamespaceId, UserId, VaultId}; pub(crate) use key::symmetric_key; -pub use key::{Encrypts, SymmetricKey, Wraps}; +pub use key::{Encrypts, KeyMaterial, SymmetricKey, Wraps}; pub use keys::{ AccountRootKey, ItemAad, ItemDataAad, ItemKey, NamespaceDataAad, NamespaceKey, NamespaceKeyAad, - RootKEK, SecretKind, VaultKey, + RootKek, SecretKind, VaultKey, }; #[cfg(test)] diff --git a/rust/crates/keygo-uniffi/src/backup/mod.rs b/rust/crates/keygo-uniffi/src/backup/mod.rs index e4d4af495..eb9a4614e 100644 --- a/rust/crates/keygo-uniffi/src/backup/mod.rs +++ b/rust/crates/keygo-uniffi/src/backup/mod.rs @@ -145,7 +145,7 @@ impl CsvBackupManager { #[cfg(test)] mod tests { - use keygo_core::crypto::SymmetricKey; + use keygo_core::crypto::KeyMaterial; use super::*; use crate::ark_session::ArkSession; diff --git a/rust/crates/keygo-uniffi/src/types.rs b/rust/crates/keygo-uniffi/src/types.rs index 1eb26e63f..bc4c6a7ae 100644 --- a/rust/crates/keygo-uniffi/src/types.rs +++ b/rust/crates/keygo-uniffi/src/types.rs @@ -1,4 +1,4 @@ -use keygo_core::crypto::{ItemId, ItemKey, NamespaceId, SymmetricKey, UserId, VaultId, VaultKey}; +use keygo_core::crypto::{ItemId, ItemKey, KeyMaterial, NamespaceId, UserId, VaultId, VaultKey}; use uuid::Uuid; uniffi::custom_type!(Uuid, String, { From 9d500ba20da2f0f97e974951300c00804447b4c6 Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 3 Nov 2026 15:13:52 +0100 Subject: [PATCH 2/9] refactor(rust): extract keygo-keys from keygo-core The server has to store wrapped keys, but keygo-core also carries app-only code like TOTP, passkeys and the backup format. Move the key hierarchy, ids, AADs, KDFs and `Sealed` into a crate both can depend on. Everything that can touch key material sits behind the `crypto` feature. Without it `Sealed` can still be parsed and stored, but a key cannot be created, which is the view the server gets. The nonce is now plain bytes so `Sealed` compiles without the cipher, and const assertions keep the hard-coded lengths in line with it. `BackupKey`, `BackupAad` and `KeySource` move too, so `symmetric_key!` and the derive functions can stay private and no other crate can declare a key type. That makes `BackupKey`'s constructors, `Argon2Params` and `new_salt` public. keygo-core re-exports the crate as `crypto`, so its callers barely change. The stored format and the generated Kotlin bindings are unchanged. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 3 +- rust/Cargo.lock | 24 +++-- rust/crates/keygo-core/Cargo.toml | 8 +- .../keygo-core/src/backup/encryption.rs | 23 +---- rust/crates/keygo-core/src/backup/mod.rs | 2 - rust/crates/keygo-core/src/crypto/cipher.rs | 93 ------------------- rust/crates/keygo-core/src/crypto/kdf/mod.rs | 10 -- rust/crates/keygo-core/src/crypto/mod.rs | 22 ----- rust/crates/keygo-core/src/lib.rs | 2 +- rust/crates/keygo-keys/Cargo.toml | 33 +++++++ .../src/crypto/aad.rs | 3 +- .../src/crypto/backup.rs} | 29 +++++- rust/crates/keygo-keys/src/crypto/cipher.rs | 40 ++++++++ .../src/crypto/golden_tests.rs | 8 +- .../src/crypto/hierarchy.rs} | 58 ++++-------- .../src/crypto/kdf/argon2.rs | 8 +- .../src/crypto/kdf/hkdf.rs | 2 +- rust/crates/keygo-keys/src/crypto/kdf/mod.rs | 10 ++ rust/crates/keygo-keys/src/crypto/mod.rs | 15 +++ .../src/crypto/traits.rs} | 45 ++------- .../src/crypto => keygo-keys/src}/error.rs | 8 +- .../src/crypto => keygo-keys/src}/ids.rs | 0 rust/crates/keygo-keys/src/keys.rs | 55 +++++++++++ rust/crates/keygo-keys/src/lib.rs | 20 ++++ rust/crates/keygo-keys/src/sealed.rs | 71 ++++++++++++++ 25 files changed, 338 insertions(+), 254 deletions(-) delete mode 100644 rust/crates/keygo-core/src/crypto/cipher.rs delete mode 100644 rust/crates/keygo-core/src/crypto/kdf/mod.rs delete mode 100644 rust/crates/keygo-core/src/crypto/mod.rs create mode 100644 rust/crates/keygo-keys/Cargo.toml rename rust/crates/{keygo-core => keygo-keys}/src/crypto/aad.rs (89%) rename rust/crates/{keygo-core/src/backup/key.rs => keygo-keys/src/crypto/backup.rs} (78%) create mode 100644 rust/crates/keygo-keys/src/crypto/cipher.rs rename rust/crates/{keygo-core => keygo-keys}/src/crypto/golden_tests.rs (95%) rename rust/crates/{keygo-core/src/crypto/keys.rs => keygo-keys/src/crypto/hierarchy.rs} (89%) rename rust/crates/{keygo-core => keygo-keys}/src/crypto/kdf/argon2.rs (96%) rename rust/crates/{keygo-core => keygo-keys}/src/crypto/kdf/hkdf.rs (97%) create mode 100644 rust/crates/keygo-keys/src/crypto/kdf/mod.rs create mode 100644 rust/crates/keygo-keys/src/crypto/mod.rs rename rust/crates/{keygo-core/src/crypto/key.rs => keygo-keys/src/crypto/traits.rs} (78%) rename rust/crates/{keygo-core/src/crypto => keygo-keys/src}/error.rs (95%) rename rust/crates/{keygo-core/src/crypto => keygo-keys/src}/ids.rs (100%) create mode 100644 rust/crates/keygo-keys/src/keys.rs create mode 100644 rust/crates/keygo-keys/src/lib.rs create mode 100644 rust/crates/keygo-keys/src/sealed.rs diff --git a/CLAUDE.md b/CLAUDE.md index b2d1b482b..34af39635 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -64,7 +64,8 @@ Rust workspace (`rust/`, toolchain pinned in `rust-toolchain.toml`, edition 2024 | Crate | Purpose | |-----------------|-------------------------------------------------------------------------------| -| `keygo-core` | Crypto, ARK session, passkeys, TOTP, backup, card formatting used by the app | +| `keygo-keys` | Key hierarchy, ids, `Sealed`, shared by app and server. Crypto sits behind the `crypto` feature; the server must leave it off, so it can store wrapped keys but never hold one | +| `keygo-core` | App-only: ARK session, passkeys, TOTP, backup format, card formatting. The server must not depend on it. `keygo_core::crypto` re-exports `keygo-keys` | | `keygo-uniffi` | UniFFI bindings exposing `keygo-core` to Kotlin (`libkeygo_bindings.so`) | | `keygo-opaque` | OPAQUE (opaque-ke, ristretto255 + Argon2) client/server wrapper, `forbid(unsafe_code)` | | `keygo-server` | Self-hostable sync server (axum + sqlx/Postgres + clap CLI), see Sync Server | diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 369bc094e..6bd9a6b18 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1597,23 +1597,18 @@ dependencies = [ name = "keygo-core" version = "0.1.0" dependencies = [ - "aead", - "aes-gcm-siv", - "argon2 0.6.0", "async-trait", "base64 0.23.1", - "bcs", "ciborium", "coset", "csv", "email_address", - "hkdf 0.13.0", + "keygo-keys", "passkey", "passkey-authenticator", "passkey-types", "serde", "serde_json", - "sha2 0.11.1", "subtle", "thiserror", "tokio", @@ -1639,6 +1634,23 @@ dependencies = [ "zeroize", ] +[[package]] +name = "keygo-keys" +version = "0.1.0" +dependencies = [ + "aead", + "aes-gcm-siv", + "argon2 0.6.0", + "base64 0.23.1", + "bcs", + "hkdf 0.13.0", + "serde", + "sha2 0.11.1", + "thiserror", + "uuid", + "zeroize", +] + [[package]] name = "keygo-opaque" version = "0.1.0" diff --git a/rust/crates/keygo-core/Cargo.toml b/rust/crates/keygo-core/Cargo.toml index 5fa140e48..37ad235fe 100644 --- a/rust/crates/keygo-core/Cargo.toml +++ b/rust/crates/keygo-core/Cargo.toml @@ -4,16 +4,15 @@ version.workspace = true edition.workspace = true [dependencies] +keygo-keys = { path = "../keygo-keys", features = ["crypto"] } + thiserror.workspace = true uuid.workspace = true zeroize.workspace = true base64.workspace = true serde = { workspace = true, features = ["derive"] } serde_json.workspace = true -sha2.workspace = true -aead = "0.6.0" -aes-gcm-siv = "0.12.1" async-trait = "0.1.89" ciborium = "0.2.2" coset = "0.4.2" @@ -22,11 +21,8 @@ passkey-authenticator = { version = "0.6.0", features = ["tokio"] } # Needed so passkey JSON responses are serialized into base64 strings passkey-types = { version = "0.6.0", features = ["serialize_bytes_as_base64_string"] } -argon2 = "0.6.0" -bcs = "0.2.0" csv = "1.4.0" email_address = "0.2.9" -hkdf = "0.13.0" subtle = "2.6" totp-rs = { version = "6.0.0", features = ["otpauth", "zeroize"] } url = "2.5.8" diff --git a/rust/crates/keygo-core/src/backup/encryption.rs b/rust/crates/keygo-core/src/backup/encryption.rs index 1991fc146..2dc17a636 100644 --- a/rust/crates/keygo-core/src/backup/encryption.rs +++ b/rust/crates/keygo-core/src/backup/encryption.rs @@ -1,9 +1,9 @@ use crate::b64; use crate::backup::BackupError; -use crate::backup::BackupKey; +pub use crate::crypto::KeySource; use crate::crypto::kdf::argon2::Argon2Params; use crate::crypto::kdf::new_salt; -use crate::crypto::{AccountRootKey, Encrypts, Sealed, aad}; +use crate::crypto::{AccountRootKey, BackupAad, BackupKey, Encrypts, Sealed}; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize)] @@ -14,13 +14,6 @@ pub struct EncryptionHeader { pub nonce: Vec, } -#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)] -#[serde(rename_all = "snake_case")] -pub enum KeySource { - Passphrase, - Ark, -} - #[derive(Serialize, Deserialize, Clone)] #[serde(tag = "type", rename_all = "snake_case")] pub enum Kdf { @@ -52,18 +45,6 @@ impl Kdf { } } -aad! { - /// Wire format: change only with a version bump. - pub struct BackupAad { - pub version: u32, - pub source: KeySource, - } -} - -impl Encrypts for BackupKey { - type Aad = BackupAad; -} - #[derive(Clone, Copy)] pub enum BackupCredential<'a> { Passphrase(&'a [u8]), diff --git a/rust/crates/keygo-core/src/backup/mod.rs b/rust/crates/keygo-core/src/backup/mod.rs index 2bd02fc64..832c07cd5 100644 --- a/rust/crates/keygo-core/src/backup/mod.rs +++ b/rust/crates/keygo-core/src/backup/mod.rs @@ -1,7 +1,6 @@ mod encryption; mod error; mod format; -mod key; mod model; pub use encryption::{BackupCredential, KeySource}; @@ -10,7 +9,6 @@ pub use format::csv::{ ColumnMapping, Confidence, CsvAnalysis, CsvColumn, ExportPreset, FieldConfidence, ImportReport, }; pub use format::{csv, json}; -pub use key::BackupKey; pub use model::{Backup, Card, Login, Passkey, Vault}; pub const CURRENT_VERSION: u32 = 1; diff --git a/rust/crates/keygo-core/src/crypto/cipher.rs b/rust/crates/keygo-core/src/crypto/cipher.rs deleted file mode 100644 index 7466abfbe..000000000 --- a/rust/crates/keygo-core/src/crypto/cipher.rs +++ /dev/null @@ -1,93 +0,0 @@ -use crate::crypto::{CryptoError, CryptoResult}; -use aead::array::typenum::Unsigned; -use aead::{Aead, AeadCore, Generate, KeyInit, KeySizeUser, Nonce, Payload}; -use aes_gcm_siv::Aes256GcmSiv; -use std::marker::PhantomData; - -pub type Cipher = Aes256GcmSiv; -pub type CipherKey = aead::Key; - -pub const KEY_LEN: usize = <::KeySize as Unsigned>::USIZE; -pub const NONCE_LEN: usize = <::NonceSize as Unsigned>::USIZE; - -pub struct Sealed { - nonce: Nonce, - ciphertext: Vec, - content: PhantomData Box>, -} - -impl Sealed { - pub fn from_parts(nonce: &[u8], ciphertext: Vec) -> CryptoResult { - let nonce = - Nonce::::try_from(nonce).map_err(|_| CryptoError::InvalidNonceLength { - expected: NONCE_LEN, - got: nonce.len(), - })?; - Ok(Self { - nonce, - ciphertext, - content: PhantomData, - }) - } - - pub fn nonce(&self) -> &[u8] { - self.nonce.as_slice() - } - - pub fn ciphertext(&self) -> &[u8] { - &self.ciphertext - } - - /// `(nonce, ciphertext)` - pub fn into_parts(self) -> (Vec, Vec) { - (self.nonce.to_vec(), self.ciphertext) - } - - pub(crate) fn seal(key: &CipherKey, plaintext: &[u8], aad: &[u8]) -> Result { - let nonce = Nonce::::generate(); - let ciphertext = Cipher::new(key).encrypt( - &nonce, - Payload { - msg: plaintext, - aad, - }, - )?; - Ok(Self { - nonce, - ciphertext, - content: PhantomData, - }) - } - - pub(crate) fn open(&self, key: &CipherKey, aad: &[u8]) -> Result, aead::Error> { - Cipher::new(key).decrypt( - &self.nonce, - Payload { - msg: &self.ciphertext, - aad, - }, - ) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn from_parts_rejects_a_wrong_length_nonce() { - assert!(matches!( - Sealed::<[u8]>::from_parts(&[0; 8], vec![]), - Err(CryptoError::InvalidNonceLength { - expected: NONCE_LEN, - got: 8, - }) - )); - } - - #[test] - fn parts_round_trip() { - let sealed = Sealed::<[u8]>::from_parts(&[7; NONCE_LEN], vec![1, 2, 3]).unwrap(); - assert_eq!(sealed.into_parts(), (vec![7; NONCE_LEN], vec![1, 2, 3])); - } -} diff --git a/rust/crates/keygo-core/src/crypto/kdf/mod.rs b/rust/crates/keygo-core/src/crypto/kdf/mod.rs deleted file mode 100644 index 14b02cc1b..000000000 --- a/rust/crates/keygo-core/src/crypto/kdf/mod.rs +++ /dev/null @@ -1,10 +0,0 @@ -pub(crate) mod argon2; -pub(crate) mod hkdf; - -use aead::Generate; - -pub(crate) const SALT_LEN: usize = 16; - -pub(crate) fn new_salt() -> [u8; SALT_LEN] { - <[u8; SALT_LEN]>::generate() -} diff --git a/rust/crates/keygo-core/src/crypto/mod.rs b/rust/crates/keygo-core/src/crypto/mod.rs deleted file mode 100644 index 8b7040727..000000000 --- a/rust/crates/keygo-core/src/crypto/mod.rs +++ /dev/null @@ -1,22 +0,0 @@ -pub(crate) mod aad; -mod cipher; -mod error; -mod ids; -pub(crate) mod kdf; -mod key; -mod keys; - -pub use aad::Aad; -pub(crate) use aad::aad; -pub use cipher::{Cipher, CipherKey, KEY_LEN, NONCE_LEN, Sealed}; -pub use error::{CryptoError, CryptoResult}; -pub use ids::{ItemId, NamespaceId, UserId, VaultId}; -pub(crate) use key::symmetric_key; -pub use key::{Encrypts, KeyMaterial, SymmetricKey, Wraps}; -pub use keys::{ - AccountRootKey, ItemAad, ItemDataAad, ItemKey, NamespaceDataAad, NamespaceKey, NamespaceKeyAad, - RootKek, SecretKind, VaultKey, -}; - -#[cfg(test)] -mod golden_tests; diff --git a/rust/crates/keygo-core/src/lib.rs b/rust/crates/keygo-core/src/lib.rs index f6915a921..6efaa236c 100644 --- a/rust/crates/keygo-core/src/lib.rs +++ b/rust/crates/keygo-core/src/lib.rs @@ -4,7 +4,7 @@ pub mod ark_session; mod b64; pub mod backup; pub mod card; -pub mod crypto; +pub use keygo_keys as crypto; pub mod passkey; pub mod totp; mod url; diff --git a/rust/crates/keygo-keys/Cargo.toml b/rust/crates/keygo-keys/Cargo.toml new file mode 100644 index 000000000..8699de60e --- /dev/null +++ b/rust/crates/keygo-keys/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "keygo-keys" +description = "KeyGo key types, ids and sealed blobs, shared by the app and the server." +version.workspace = true +edition.workspace = true + +[features] +# Everything that can touch key material. The server stores sealed blobs and leaves this off. +crypto = [ + "dep:aead", + "dep:aes-gcm-siv", + "dep:argon2", + "dep:bcs", + "dep:hkdf", + "dep:sha2", + "dep:zeroize", +] + +[dependencies] +serde = { workspace = true, features = ["derive"] } +thiserror.workspace = true +uuid.workspace = true + +aead = { version = "0.6.0", optional = true } +aes-gcm-siv = { version = "0.12.1", optional = true } +argon2 = { version = "0.6.0", optional = true } +bcs = { version = "0.2.0", optional = true } +hkdf = { version = "0.13.0", optional = true } +sha2 = { workspace = true, optional = true } +zeroize = { workspace = true, features = ["derive"], optional = true } + +[dev-dependencies] +base64.workspace = true diff --git a/rust/crates/keygo-core/src/crypto/aad.rs b/rust/crates/keygo-keys/src/crypto/aad.rs similarity index 89% rename from rust/crates/keygo-core/src/crypto/aad.rs rename to rust/crates/keygo-keys/src/crypto/aad.rs index c5558f024..0bbb16501 100644 --- a/rust/crates/keygo-core/src/crypto/aad.rs +++ b/rust/crates/keygo-keys/src/crypto/aad.rs @@ -1,4 +1,5 @@ -use crate::crypto::{CryptoResult, UserId, VaultId}; +use crate::error::CryptoResult; +use crate::{UserId, VaultId}; use serde::Serialize; /// AADs are BCS-encoded; the encoding is part of the stored format. diff --git a/rust/crates/keygo-core/src/backup/key.rs b/rust/crates/keygo-keys/src/crypto/backup.rs similarity index 78% rename from rust/crates/keygo-core/src/backup/key.rs rename to rust/crates/keygo-keys/src/crypto/backup.rs index 4725bdf35..49425b468 100644 --- a/rust/crates/keygo-core/src/backup/key.rs +++ b/rust/crates/keygo-keys/src/crypto/backup.rs @@ -1,16 +1,35 @@ +use crate::crypto::Encrypts; +use crate::crypto::KeyMaterial; +use crate::crypto::aad::aad; use crate::crypto::kdf::argon2::{Argon2Params, derive_argon2id}; use crate::crypto::kdf::hkdf::derive_hkdf_sha256; -use crate::crypto::{AccountRootKey, CryptoResult, KeyMaterial, symmetric_key}; +use crate::{AccountRootKey, BackupKey, CryptoResult}; +use serde::{Deserialize, Serialize}; const DOMAIN_PASSPHRASE: &[u8] = b"v1:backup/passphrase"; const DOMAIN_ARK: &[u8] = b"v1:backup/ark"; -symmetric_key! { - pub struct BackupKey; +#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)] +#[serde(rename_all = "snake_case")] +pub enum KeySource { + Passphrase, + Ark, +} + +aad! { + /// Wire format: change only with a version bump. + pub struct BackupAad { + pub version: u32, + pub source: KeySource, + } +} + +impl Encrypts for BackupKey { + type Aad = BackupAad; } impl BackupKey { - pub(crate) fn from_passphrase( + pub fn from_passphrase( passphrase: &[u8], salt: &[u8], params: Argon2Params, @@ -19,7 +38,7 @@ impl BackupKey { Self::from_bytes(derived.as_slice()) } - pub(crate) fn from_ark(ark: &AccountRootKey, salt: &[u8]) -> CryptoResult { + pub fn from_ark(ark: &AccountRootKey, salt: &[u8]) -> CryptoResult { Self::from_bytes(derive_hkdf_sha256(ark.as_bytes(), salt, DOMAIN_ARK).as_slice()) } } diff --git a/rust/crates/keygo-keys/src/crypto/cipher.rs b/rust/crates/keygo-keys/src/crypto/cipher.rs new file mode 100644 index 000000000..aef365b5c --- /dev/null +++ b/rust/crates/keygo-keys/src/crypto/cipher.rs @@ -0,0 +1,40 @@ +use crate::{KEY_LEN, NONCE_LEN, Sealed}; +use aead::array::typenum::Unsigned; +use aead::{Aead, AeadCore, Generate, KeyInit, KeySizeUser, Nonce, Payload}; +use aes_gcm_siv::Aes256GcmSiv; +use std::marker::PhantomData; + +pub type Cipher = Aes256GcmSiv; +pub type CipherKey = aead::Key; + +// `sealed.rs` is compiled without the cipher, so it cannot ask it for these. +const _: () = assert!(KEY_LEN == <::KeySize as Unsigned>::USIZE); +const _: () = assert!(NONCE_LEN == <::NonceSize as Unsigned>::USIZE); + +impl Sealed { + pub(crate) fn seal(key: &CipherKey, plaintext: &[u8], aad: &[u8]) -> Result { + let nonce = Nonce::::generate(); + let ciphertext = Cipher::new(key).encrypt( + &nonce, + Payload { + msg: plaintext, + aad, + }, + )?; + Ok(Self { + nonce: nonce.into(), + ciphertext, + content: PhantomData, + }) + } + + pub(crate) fn open(&self, key: &CipherKey, aad: &[u8]) -> Result, aead::Error> { + Cipher::new(key).decrypt( + &Nonce::::from(self.nonce), + Payload { + msg: &self.ciphertext, + aad, + }, + ) + } +} diff --git a/rust/crates/keygo-core/src/crypto/golden_tests.rs b/rust/crates/keygo-keys/src/crypto/golden_tests.rs similarity index 95% rename from rust/crates/keygo-core/src/crypto/golden_tests.rs rename to rust/crates/keygo-keys/src/crypto/golden_tests.rs index fbc0edd0c..c97d79d61 100644 --- a/rust/crates/keygo-core/src/crypto/golden_tests.rs +++ b/rust/crates/keygo-keys/src/crypto/golden_tests.rs @@ -1,10 +1,12 @@ //! Shipped ciphertexts under fixed keys. They must keep opening; regenerate only with a migration. -use crate::crypto::{ +use crate::{ AccountRootKey, Encrypts, ItemAad, ItemDataAad, ItemId, ItemKey, KeyMaterial, NamespaceDataAad, NamespaceId, NamespaceKey, NamespaceKeyAad, RootKek, Sealed, SecretKind, UserId, VaultId, VaultKey, Wraps, }; +use base64::Engine; +use base64::engine::general_purpose::STANDARD; use uuid::Uuid; const USER_ID: UserId = UserId(Uuid::from_u128(0x1111_1111_1111_4111_8111_1111_1111_1111)); @@ -50,8 +52,8 @@ const ACCOUNT_RECORD_PLAINTEXT: &[u8] = b"secret account record"; fn sealed((nonce, ciphertext): (&str, &str)) -> Sealed { Sealed::from_parts( - &crate::b64::decode(nonce).unwrap(), - crate::b64::decode(ciphertext).unwrap(), + &STANDARD.decode(nonce).unwrap(), + STANDARD.decode(ciphertext).unwrap(), ) .unwrap() } diff --git a/rust/crates/keygo-core/src/crypto/keys.rs b/rust/crates/keygo-keys/src/crypto/hierarchy.rs similarity index 89% rename from rust/crates/keygo-core/src/crypto/keys.rs rename to rust/crates/keygo-keys/src/crypto/hierarchy.rs index 2c0a2d8d2..21a49a136 100644 --- a/rust/crates/keygo-core/src/crypto/keys.rs +++ b/rust/crates/keygo-keys/src/crypto/hierarchy.rs @@ -6,10 +6,12 @@ //! --NamespaceKeyAad--> NamespaceKey --NamespaceDataAad--> account record //! ``` +use crate::crypto::aad::{Aad, aad}; use crate::crypto::kdf::argon2::{Argon2Params, derive_argon2id}; -use crate::crypto::{ - Aad, CipherKey, CryptoResult, Encrypts, ItemId, KeyMaterial, NamespaceId, UserId, VaultId, - Wraps, aad, symmetric_key, +use crate::crypto::{CipherKey, Encrypts, KeyMaterial, Wraps}; +use crate::{ + AccountRootKey, CryptoResult, ItemId, ItemKey, NamespaceId, NamespaceKey, RootKek, UserId, + VaultId, VaultKey, }; use aead::Generate; use serde::{Serialize, Serializer}; @@ -23,27 +25,6 @@ const NAMESPACE_KEY_DOMAIN: &str = "v1:ns/key"; /// Part of every account-record AAD; must never change. const NAMESPACE_DATA_DOMAIN: &str = "v1:ns/data"; -symmetric_key! { - pub struct RootKek; -} - -symmetric_key! { - pub struct AccountRootKey; -} - -symmetric_key! { - pub struct VaultKey; -} - -symmetric_key! { - pub struct ItemKey; -} - -symmetric_key! { - /// Seals one account-wide record that belongs to no vault. - pub struct NamespaceKey; -} - aad! { pub struct ItemAad { pub item_id: ItemId, @@ -118,26 +99,27 @@ impl SecretKind { } } -impl Wraps for RootKek { - type Aad = UserId; // TODO: bind the credential epoch -} - -impl Wraps for AccountRootKey { - type Aad = VaultId; // TODO: bind vault_key_epoch +macro_rules! wraps { + ($($parent:ident -> $child:ident with $aad:ident),+ $(,)?) => { + $( + impl Wraps<$child> for $parent { + type Aad = $aad; + } + )+ + }; } -impl Wraps for VaultKey { - type Aad = ItemAad; +wraps! { + RootKek -> AccountRootKey with UserId, // TODO: bind the credential epoch + AccountRootKey -> VaultKey with VaultId, // TODO: bind vault_key_epoch + AccountRootKey -> NamespaceKey with NamespaceKeyAad, + VaultKey -> ItemKey with ItemAad, } impl Encrypts for ItemKey { type Aad = ItemDataAad; } -impl Wraps for AccountRootKey { - type Aad = NamespaceKeyAad; -} - impl Encrypts for NamespaceKey { type Aad = NamespaceDataAad; } @@ -153,7 +135,7 @@ macro_rules! impl_generate { ($($key:ident),+) => { $(impl $key { pub fn generate() -> Self { - Self(CipherKey::generate()) + Self { key: CipherKey::generate() } } })+ }; @@ -164,7 +146,7 @@ impl_generate!(AccountRootKey, VaultKey, ItemKey, NamespaceKey); #[cfg(test)] mod tests { use super::*; - use crate::crypto::Sealed; + use crate::Sealed; const SALT: &[u8] = &[6; 16]; diff --git a/rust/crates/keygo-core/src/crypto/kdf/argon2.rs b/rust/crates/keygo-keys/src/crypto/kdf/argon2.rs similarity index 96% rename from rust/crates/keygo-core/src/crypto/kdf/argon2.rs rename to rust/crates/keygo-keys/src/crypto/kdf/argon2.rs index 1045de374..1ead2f651 100644 --- a/rust/crates/keygo-core/src/crypto/kdf/argon2.rs +++ b/rust/crates/keygo-keys/src/crypto/kdf/argon2.rs @@ -1,13 +1,13 @@ -use crate::crypto::{CryptoError, CryptoResult, KEY_LEN}; +use crate::{CryptoError, CryptoResult, KEY_LEN}; use argon2::{Algorithm, Argon2, Params, Version}; use zeroize::Zeroizing; pub(crate) const MIN_SALT_LEN: usize = 16; -pub(crate) const MAX_ARGON2_MEM_KIB: u32 = 256 * 1024; -pub(crate) const MAX_ARGON2_ITERS: u32 = 16; +pub const MAX_ARGON2_MEM_KIB: u32 = 256 * 1024; +pub const MAX_ARGON2_ITERS: u32 = 16; #[derive(Clone, Copy)] -pub(crate) struct Argon2Params { +pub struct Argon2Params { /// Memory cost in KiB pub mem_kib: u32, pub iters: u32, diff --git a/rust/crates/keygo-core/src/crypto/kdf/hkdf.rs b/rust/crates/keygo-keys/src/crypto/kdf/hkdf.rs similarity index 97% rename from rust/crates/keygo-core/src/crypto/kdf/hkdf.rs rename to rust/crates/keygo-keys/src/crypto/kdf/hkdf.rs index 968ba2851..b633966f6 100644 --- a/rust/crates/keygo-core/src/crypto/kdf/hkdf.rs +++ b/rust/crates/keygo-keys/src/crypto/kdf/hkdf.rs @@ -1,4 +1,4 @@ -use crate::crypto::KEY_LEN; +use crate::KEY_LEN; use hkdf::Hkdf; use sha2::Sha256; use zeroize::Zeroizing; diff --git a/rust/crates/keygo-keys/src/crypto/kdf/mod.rs b/rust/crates/keygo-keys/src/crypto/kdf/mod.rs new file mode 100644 index 000000000..e23167af8 --- /dev/null +++ b/rust/crates/keygo-keys/src/crypto/kdf/mod.rs @@ -0,0 +1,10 @@ +pub mod argon2; +pub(crate) mod hkdf; + +use aead::Generate; + +pub const SALT_LEN: usize = 16; + +pub fn new_salt() -> [u8; SALT_LEN] { + <[u8; SALT_LEN]>::generate() +} diff --git a/rust/crates/keygo-keys/src/crypto/mod.rs b/rust/crates/keygo-keys/src/crypto/mod.rs new file mode 100644 index 000000000..83d48ad86 --- /dev/null +++ b/rust/crates/keygo-keys/src/crypto/mod.rs @@ -0,0 +1,15 @@ +mod aad; +mod backup; +mod cipher; +mod hierarchy; +pub mod kdf; +mod traits; + +pub use aad::Aad; +pub use backup::{BackupAad, KeySource}; +pub use cipher::{Cipher, CipherKey}; +pub use hierarchy::{ItemAad, ItemDataAad, NamespaceDataAad, NamespaceKeyAad, SecretKind}; +pub use traits::{Encrypts, KeyMaterial, SymmetricKey, Wraps}; + +#[cfg(test)] +mod golden_tests; diff --git a/rust/crates/keygo-core/src/crypto/key.rs b/rust/crates/keygo-keys/src/crypto/traits.rs similarity index 78% rename from rust/crates/keygo-core/src/crypto/key.rs rename to rust/crates/keygo-keys/src/crypto/traits.rs index 1cc5fda50..2993d60ac 100644 --- a/rust/crates/keygo-core/src/crypto/key.rs +++ b/rust/crates/keygo-keys/src/crypto/traits.rs @@ -1,5 +1,7 @@ -use crate::crypto::aad::encode_aad; -use crate::crypto::{Aad, CipherKey, CryptoError, CryptoResult, Sealed}; +use crate::Sealed; +use crate::crypto::CipherKey; +use crate::crypto::aad::{Aad, encode_aad}; +use crate::error::{CryptoError, CryptoResult}; use zeroize::{ZeroizeOnDrop, Zeroizing}; /// Anything that can be sealed under a wrapping key. @@ -46,46 +48,15 @@ pub trait Encrypts: SymmetricKey { } } -macro_rules! symmetric_key { - ($(#[$meta:meta])* $vis:vis struct $name:ident;) => { - $(#[$meta])* - #[derive(::zeroize::Zeroize, ::zeroize::ZeroizeOnDrop)] - $vis struct $name($crate::crypto::CipherKey); - - impl $crate::crypto::KeyMaterial for $name { - fn from_bytes(bytes: &[u8]) -> $crate::crypto::CryptoResult { - $crate::crypto::CipherKey::try_from(bytes).map(Self).map_err(|_| { - $crate::crypto::CryptoError::InvalidKeyLength { - expected: $crate::crypto::KEY_LEN, - got: bytes.len(), - } - }) - } - - fn as_bytes(&self) -> &[u8] { - self.0.as_slice() - } - } - - impl $crate::crypto::SymmetricKey for $name { - fn cipher_key(&self) -> &$crate::crypto::CipherKey { - &self.0 - } - } - }; -} -pub(crate) use symmetric_key; - #[cfg(test)] mod tests { use super::*; - use crate::crypto::aad; + use crate::crypto::aad::aad; + use crate::keys::symmetric_key; symmetric_key! { - struct TestWrappingKey; - } - symmetric_key! { - struct TestKey; + struct TestWrappingKey, + struct TestKey, } aad! { diff --git a/rust/crates/keygo-core/src/crypto/error.rs b/rust/crates/keygo-keys/src/error.rs similarity index 95% rename from rust/crates/keygo-core/src/crypto/error.rs rename to rust/crates/keygo-keys/src/error.rs index 5a0351ebf..494f4e1af 100644 --- a/rust/crates/keygo-core/src/crypto/error.rs +++ b/rust/crates/keygo-keys/src/error.rs @@ -17,9 +17,6 @@ pub enum CryptoError { #[error("Invalid nonce length: expected {expected} bytes, got {got} bytes")] InvalidNonceLength { expected: usize, got: usize }, - #[error("AAD encoding failed: {0}")] - AadEncoding(#[from] bcs::Error), - #[error("Password must not be empty")] EmptyPassword, #[error("Salt too short: expected at least {min} bytes, got {got} bytes")] @@ -28,6 +25,11 @@ pub enum CryptoError { Argon2MemoryTooHigh { max: u32, got: u32 }, #[error("Argon2 iteration count too high: {got} exceeds the {max} limit")] Argon2ItersTooHigh { max: u32, got: u32 }, + + #[cfg(feature = "crypto")] + #[error("AAD encoding failed: {0}")] + AadEncoding(#[from] bcs::Error), + #[cfg(feature = "crypto")] #[error("Argon2 failed: {0}")] Argon2(argon2::Error), } diff --git a/rust/crates/keygo-core/src/crypto/ids.rs b/rust/crates/keygo-keys/src/ids.rs similarity index 100% rename from rust/crates/keygo-core/src/crypto/ids.rs rename to rust/crates/keygo-keys/src/ids.rs diff --git a/rust/crates/keygo-keys/src/keys.rs b/rust/crates/keygo-keys/src/keys.rs new file mode 100644 index 000000000..348f2a750 --- /dev/null +++ b/rust/crates/keygo-keys/src/keys.rs @@ -0,0 +1,55 @@ +//! The key types. They are always nameable, but only hold key material with the `crypto` feature; +//! without it they have no public constructor, so a build without it can never hold a key. + +macro_rules! symmetric_key { + ($($(#[$meta:meta])* $vis:vis struct $name:ident),+ $(,)?) => { + $( + $(#[$meta])* + #[cfg_attr(feature = "crypto", derive(::zeroize::Zeroize, ::zeroize::ZeroizeOnDrop))] + $vis struct $name { + #[cfg(feature = "crypto")] + pub(crate) key: $crate::crypto::CipherKey, + #[cfg(not(feature = "crypto"))] + _no_constructor: (), + } + + #[cfg(feature = "crypto")] + impl $crate::crypto::KeyMaterial for $name { + fn from_bytes(bytes: &[u8]) -> $crate::CryptoResult { + $crate::crypto::CipherKey::try_from(bytes) + .map(|key| Self { key }) + .map_err(|_| $crate::CryptoError::InvalidKeyLength { + expected: $crate::KEY_LEN, + got: bytes.len(), + }) + } + + fn as_bytes(&self) -> &[u8] { + self.key.as_slice() + } + } + + #[cfg(feature = "crypto")] + impl $crate::crypto::SymmetricKey for $name { + fn cipher_key(&self) -> &$crate::crypto::CipherKey { + &self.key + } + } + )+ + }; +} +#[cfg_attr(not(all(test, feature = "crypto")), allow(unused_imports))] +pub(crate) use symmetric_key; + +symmetric_key! { + pub struct RootKek, + + pub struct AccountRootKey, + pub struct VaultKey, + pub struct ItemKey, + + /// Seals one account-wide record that belongs to no vault. + pub struct NamespaceKey, + + pub struct BackupKey, +} diff --git a/rust/crates/keygo-keys/src/lib.rs b/rust/crates/keygo-keys/src/lib.rs new file mode 100644 index 000000000..9317035de --- /dev/null +++ b/rust/crates/keygo-keys/src/lib.rs @@ -0,0 +1,20 @@ +#![forbid(unsafe_code)] + +//! The key hierarchy, the ids it binds to and the sealed blobs it produces. +//! +//! Without the `crypto` feature this is only names and storage: `Sealed` can be parsed, +//! stored and passed on, but no key can ever be created or read. That is the server's view. + +#[cfg(feature = "crypto")] +mod crypto; +mod error; +mod ids; +mod keys; +mod sealed; + +#[cfg(feature = "crypto")] +pub use crypto::*; +pub use error::{CryptoError, CryptoResult}; +pub use ids::{ItemId, NamespaceId, UserId, VaultId}; +pub use keys::{AccountRootKey, BackupKey, ItemKey, NamespaceKey, RootKek, VaultKey}; +pub use sealed::{KEY_LEN, NONCE_LEN, Sealed}; diff --git a/rust/crates/keygo-keys/src/sealed.rs b/rust/crates/keygo-keys/src/sealed.rs new file mode 100644 index 000000000..3aae70315 --- /dev/null +++ b/rust/crates/keygo-keys/src/sealed.rs @@ -0,0 +1,71 @@ +use crate::error::{CryptoError, CryptoResult}; +use std::marker::PhantomData; + +pub const KEY_LEN: usize = 32; +pub const NONCE_LEN: usize = 12; + +pub struct Sealed { + pub(crate) nonce: [u8; NONCE_LEN], + pub(crate) ciphertext: Vec, + pub(crate) content: PhantomData Box>, +} + +impl Sealed { + pub fn from_parts(nonce: &[u8], ciphertext: Vec) -> CryptoResult { + let nonce = nonce + .try_into() + .map_err(|_| CryptoError::InvalidNonceLength { + expected: NONCE_LEN, + got: nonce.len(), + })?; + + Ok(Self { + nonce, + ciphertext, + content: PhantomData, + }) + } + + pub fn nonce(&self) -> &[u8] { + self.nonce.as_slice() + } + + pub fn ciphertext(&self) -> &[u8] { + &self.ciphertext + } + + /// `(nonce, ciphertext)` + pub fn into_parts(self) -> (Vec, Vec) { + (self.nonce.to_vec(), self.ciphertext) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::VaultKey; + + #[test] + fn from_parts_rejects_a_wrong_length_nonce() { + assert!(matches!( + Sealed::<[u8]>::from_parts(&[0; 8], vec![]), + Err(CryptoError::InvalidNonceLength { + expected: NONCE_LEN, + got: 8, + }) + )); + } + + #[test] + fn parts_round_trip() { + let sealed = Sealed::<[u8]>::from_parts(&[7; NONCE_LEN], vec![1, 2, 3]).unwrap(); + assert_eq!(sealed.into_parts(), (vec![7; NONCE_LEN], vec![1, 2, 3])); + } + + #[test] + fn a_wrapped_key_is_nameable_in_every_build() { + let wrapped = Sealed::::from_parts(&[7; NONCE_LEN], vec![1, 2, 3]).unwrap(); + assert_eq!(wrapped.nonce(), [7; NONCE_LEN]); + assert_eq!(wrapped.ciphertext(), [1, 2, 3]); + } +} From f6ba9f91bb76b6f6d3d828fc5754c4547f2be588 Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 3 Nov 2026 15:13:52 +0100 Subject: [PATCH 3/9] ci(rust): check keygo-keys without the crypto feature A workspace build unifies features, so keygo-core turns `crypto` on and hides any dependency that leaks out from behind it. Build the crate on its own and fail if a cipher or KDF crate shows up in its tree. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yaml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index cb148783c..b05249029 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -59,6 +59,11 @@ jobs: run: cargo fmt --check --all - name: Clippy run: cargo clippy --workspace --all-targets -- -D warnings + # A workspace build unifies features, so only a build of its own shows this crate without them. + - name: keygo-keys holds no crypto without its feature + run: | + cargo clippy -p keygo-keys --all-targets -- -D warnings + ! cargo tree -p keygo-keys -e normal --prefix none | grep -E '^(aead|aes-gcm-siv|argon2|bcs|hkdf|zeroize) ' # Rust-native tests (no NDK). Runs in parallel with android-test once lint passes. rust-test: From 98453acc8b01274c2c9f7ab9a856547f576c17c3 Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 3 Nov 2026 15:44:12 +0100 Subject: [PATCH 4/9] refactor(rust): rename keygo-keys to keygo-core and keygo-core to keygo-client The shared crate now holds more than keys, and the old keygo-core was only ever the app's: TOTP, passkeys, the backup format and the ARK session. The new names say which crate the server may depend on. Only names change. The generated Kotlin bindings are identical. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yaml | 6 +-- CLAUDE.md | 6 +-- rust/Cargo.lock | 32 +++++++------- rust/crates/keygo-client/Cargo.toml | 31 ++++++++++++++ .../src/ark_session.rs | 0 .../{keygo-core => keygo-client}/src/b64.rs | 0 .../src/backup/encryption.rs | 0 .../src/backup/error.rs | 0 .../src/backup/format/csv/detect.rs | 0 .../src/backup/format/csv/mod.rs | 0 .../src/backup/format/json.rs | 0 .../src/backup/format/mod.rs | 0 .../src/backup/mod.rs | 0 .../src/backup/model.rs | 0 .../src/card/expiration.rs | 0 .../src/card/mod.rs | 0 .../src/card/network.rs | 0 .../src/card/number.rs | 0 rust/crates/keygo-client/src/lib.rs | 10 +++++ .../src/passkey/authentication.rs | 0 .../src/passkey/authenticator.rs | 0 .../src/passkey/codec.rs | 0 .../src/passkey/mod.rs | 0 .../src/passkey/registration.rs | 0 .../{keygo-core => keygo-client}/src/totp.rs | 0 .../{keygo-core => keygo-client}/src/url.rs | 0 rust/crates/keygo-core/Cargo.toml | 42 ++++++++++--------- .../src/crypto/aad.rs | 0 .../src/crypto/backup.rs | 0 .../src/crypto/cipher.rs | 0 .../src/crypto/golden_tests.rs | 0 .../src/crypto/hierarchy.rs | 0 .../src/crypto/kdf/argon2.rs | 0 .../src/crypto/kdf/hkdf.rs | 0 .../src/crypto/kdf/mod.rs | 0 .../src/crypto/mod.rs | 0 .../src/crypto/traits.rs | 0 .../{keygo-keys => keygo-core}/src/error.rs | 0 .../{keygo-keys => keygo-core}/src/ids.rs | 0 .../{keygo-keys => keygo-core}/src/keys.rs | 0 rust/crates/keygo-core/src/lib.rs | 26 ++++++++---- .../{keygo-keys => keygo-core}/src/sealed.rs | 0 rust/crates/keygo-keys/Cargo.toml | 33 --------------- rust/crates/keygo-keys/src/lib.rs | 20 --------- rust/crates/keygo-uniffi/Cargo.toml | 2 +- rust/crates/keygo-uniffi/src/ark_session.rs | 4 +- rust/crates/keygo-uniffi/src/backup/csv.rs | 2 +- rust/crates/keygo-uniffi/src/backup/mod.rs | 6 +-- rust/crates/keygo-uniffi/src/backup/model.rs | 2 +- rust/crates/keygo-uniffi/src/card.rs | 2 +- rust/crates/keygo-uniffi/src/item.rs | 2 +- rust/crates/keygo-uniffi/src/key_wrap.rs | 2 +- rust/crates/keygo-uniffi/src/passkey.rs | 2 +- rust/crates/keygo-uniffi/src/totp.rs | 24 +++++------ rust/crates/keygo-uniffi/src/types.rs | 2 +- rust/crates/keygo-uniffi/src/vault.rs | 2 +- 56 files changed, 129 insertions(+), 129 deletions(-) create mode 100644 rust/crates/keygo-client/Cargo.toml rename rust/crates/{keygo-core => keygo-client}/src/ark_session.rs (100%) rename rust/crates/{keygo-core => keygo-client}/src/b64.rs (100%) rename rust/crates/{keygo-core => keygo-client}/src/backup/encryption.rs (100%) rename rust/crates/{keygo-core => keygo-client}/src/backup/error.rs (100%) rename rust/crates/{keygo-core => keygo-client}/src/backup/format/csv/detect.rs (100%) rename rust/crates/{keygo-core => keygo-client}/src/backup/format/csv/mod.rs (100%) rename rust/crates/{keygo-core => keygo-client}/src/backup/format/json.rs (100%) rename rust/crates/{keygo-core => keygo-client}/src/backup/format/mod.rs (100%) rename rust/crates/{keygo-core => keygo-client}/src/backup/mod.rs (100%) rename rust/crates/{keygo-core => keygo-client}/src/backup/model.rs (100%) rename rust/crates/{keygo-core => keygo-client}/src/card/expiration.rs (100%) rename rust/crates/{keygo-core => keygo-client}/src/card/mod.rs (100%) rename rust/crates/{keygo-core => keygo-client}/src/card/network.rs (100%) rename rust/crates/{keygo-core => keygo-client}/src/card/number.rs (100%) create mode 100644 rust/crates/keygo-client/src/lib.rs rename rust/crates/{keygo-core => keygo-client}/src/passkey/authentication.rs (100%) rename rust/crates/{keygo-core => keygo-client}/src/passkey/authenticator.rs (100%) rename rust/crates/{keygo-core => keygo-client}/src/passkey/codec.rs (100%) rename rust/crates/{keygo-core => keygo-client}/src/passkey/mod.rs (100%) rename rust/crates/{keygo-core => keygo-client}/src/passkey/registration.rs (100%) rename rust/crates/{keygo-core => keygo-client}/src/totp.rs (100%) rename rust/crates/{keygo-core => keygo-client}/src/url.rs (100%) rename rust/crates/{keygo-keys => keygo-core}/src/crypto/aad.rs (100%) rename rust/crates/{keygo-keys => keygo-core}/src/crypto/backup.rs (100%) rename rust/crates/{keygo-keys => keygo-core}/src/crypto/cipher.rs (100%) rename rust/crates/{keygo-keys => keygo-core}/src/crypto/golden_tests.rs (100%) rename rust/crates/{keygo-keys => keygo-core}/src/crypto/hierarchy.rs (100%) rename rust/crates/{keygo-keys => keygo-core}/src/crypto/kdf/argon2.rs (100%) rename rust/crates/{keygo-keys => keygo-core}/src/crypto/kdf/hkdf.rs (100%) rename rust/crates/{keygo-keys => keygo-core}/src/crypto/kdf/mod.rs (100%) rename rust/crates/{keygo-keys => keygo-core}/src/crypto/mod.rs (100%) rename rust/crates/{keygo-keys => keygo-core}/src/crypto/traits.rs (100%) rename rust/crates/{keygo-keys => keygo-core}/src/error.rs (100%) rename rust/crates/{keygo-keys => keygo-core}/src/ids.rs (100%) rename rust/crates/{keygo-keys => keygo-core}/src/keys.rs (100%) rename rust/crates/{keygo-keys => keygo-core}/src/sealed.rs (100%) delete mode 100644 rust/crates/keygo-keys/Cargo.toml delete mode 100644 rust/crates/keygo-keys/src/lib.rs diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index b05249029..06f45c127 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -60,10 +60,10 @@ jobs: - name: Clippy run: cargo clippy --workspace --all-targets -- -D warnings # A workspace build unifies features, so only a build of its own shows this crate without them. - - name: keygo-keys holds no crypto without its feature + - name: keygo-core holds no crypto without its feature run: | - cargo clippy -p keygo-keys --all-targets -- -D warnings - ! cargo tree -p keygo-keys -e normal --prefix none | grep -E '^(aead|aes-gcm-siv|argon2|bcs|hkdf|zeroize) ' + cargo clippy -p keygo-core --all-targets -- -D warnings + ! cargo tree -p keygo-core -e normal --prefix none | grep -E '^(aead|aes-gcm-siv|argon2|bcs|hkdf|zeroize) ' # Rust-native tests (no NDK). Runs in parallel with android-test once lint passes. rust-test: diff --git a/CLAUDE.md b/CLAUDE.md index 34af39635..b3779979d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -64,9 +64,9 @@ Rust workspace (`rust/`, toolchain pinned in `rust-toolchain.toml`, edition 2024 | Crate | Purpose | |-----------------|-------------------------------------------------------------------------------| -| `keygo-keys` | Key hierarchy, ids, `Sealed`, shared by app and server. Crypto sits behind the `crypto` feature; the server must leave it off, so it can store wrapped keys but never hold one | -| `keygo-core` | App-only: ARK session, passkeys, TOTP, backup format, card formatting. The server must not depend on it. `keygo_core::crypto` re-exports `keygo-keys` | -| `keygo-uniffi` | UniFFI bindings exposing `keygo-core` to Kotlin (`libkeygo_bindings.so`) | +| `keygo-core` | Key hierarchy, ids, `Sealed`, shared by client and server. Crypto sits behind the `crypto` feature; the server must leave it off, so it can store wrapped keys but never hold one | +| `keygo-client` | App-only: ARK session, passkeys, TOTP, backup format, card formatting. The server must not depend on it. `keygo_client::crypto` re-exports `keygo-core` | +| `keygo-uniffi` | UniFFI bindings exposing `keygo-client` to Kotlin (`libkeygo_bindings.so`) | | `keygo-opaque` | OPAQUE (opaque-ke, ristretto255 + Argon2) client/server wrapper, `forbid(unsafe_code)` | | `keygo-server` | Self-hostable sync server (axum + sqlx/Postgres + clap CLI), see Sync Server | | `tools/uniffi-bindgen` | Bindgen runner used by `make bindgen` | diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 6bd9a6b18..ec1f70173 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1594,7 +1594,7 @@ dependencies = [ ] [[package]] -name = "keygo-core" +name = "keygo-client" version = "0.1.0" dependencies = [ "async-trait", @@ -1603,7 +1603,7 @@ dependencies = [ "coset", "csv", "email_address", - "keygo-keys", + "keygo-core", "passkey", "passkey-authenticator", "passkey-types", @@ -1619,35 +1619,35 @@ dependencies = [ ] [[package]] -name = "keygo-dpop" +name = "keygo-core" version = "0.1.0" dependencies = [ + "aead", + "aes-gcm-siv", + "argon2 0.6.0", "base64 0.23.1", - "fluent-uri", - "getrandom 0.4.3", - "hmac 0.13.0", - "p256", + "bcs", + "hkdf 0.13.0", "serde", - "serde_json", "sha2 0.11.1", "thiserror", + "uuid", "zeroize", ] [[package]] -name = "keygo-keys" +name = "keygo-dpop" version = "0.1.0" dependencies = [ - "aead", - "aes-gcm-siv", - "argon2 0.6.0", "base64 0.23.1", - "bcs", - "hkdf 0.13.0", + "fluent-uri", + "getrandom 0.4.3", + "hmac 0.13.0", + "p256", "serde", + "serde_json", "sha2 0.11.1", "thiserror", - "uuid", "zeroize", ] @@ -1710,7 +1710,7 @@ dependencies = [ name = "keygo-uniffi" version = "0.1.0" dependencies = [ - "keygo-core", + "keygo-client", "thiserror", "tokio", "uniffi", diff --git a/rust/crates/keygo-client/Cargo.toml b/rust/crates/keygo-client/Cargo.toml new file mode 100644 index 000000000..0e20912d1 --- /dev/null +++ b/rust/crates/keygo-client/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "keygo-client" +version.workspace = true +edition.workspace = true + +[dependencies] +keygo-core = { path = "../keygo-core", features = ["crypto"] } + +thiserror.workspace = true +uuid.workspace = true +zeroize.workspace = true +base64.workspace = true +serde = { workspace = true, features = ["derive"] } +serde_json.workspace = true + +async-trait = "0.1.89" +ciborium = "0.2.2" +coset = "0.4.2" +passkey = "0.6.0" +passkey-authenticator = { version = "0.6.0", features = ["tokio"] } +# Needed so passkey JSON responses are serialized into base64 strings +passkey-types = { version = "0.6.0", features = ["serialize_bytes_as_base64_string"] } + +csv = "1.4.0" +email_address = "0.2.9" +subtle = "2.6" +totp-rs = { version = "6.0.0", features = ["otpauth", "zeroize"] } +url = "2.5.8" + +[dev-dependencies] +tokio = { workspace = true, features = ["rt", "macros"] } diff --git a/rust/crates/keygo-core/src/ark_session.rs b/rust/crates/keygo-client/src/ark_session.rs similarity index 100% rename from rust/crates/keygo-core/src/ark_session.rs rename to rust/crates/keygo-client/src/ark_session.rs diff --git a/rust/crates/keygo-core/src/b64.rs b/rust/crates/keygo-client/src/b64.rs similarity index 100% rename from rust/crates/keygo-core/src/b64.rs rename to rust/crates/keygo-client/src/b64.rs diff --git a/rust/crates/keygo-core/src/backup/encryption.rs b/rust/crates/keygo-client/src/backup/encryption.rs similarity index 100% rename from rust/crates/keygo-core/src/backup/encryption.rs rename to rust/crates/keygo-client/src/backup/encryption.rs diff --git a/rust/crates/keygo-core/src/backup/error.rs b/rust/crates/keygo-client/src/backup/error.rs similarity index 100% rename from rust/crates/keygo-core/src/backup/error.rs rename to rust/crates/keygo-client/src/backup/error.rs diff --git a/rust/crates/keygo-core/src/backup/format/csv/detect.rs b/rust/crates/keygo-client/src/backup/format/csv/detect.rs similarity index 100% rename from rust/crates/keygo-core/src/backup/format/csv/detect.rs rename to rust/crates/keygo-client/src/backup/format/csv/detect.rs diff --git a/rust/crates/keygo-core/src/backup/format/csv/mod.rs b/rust/crates/keygo-client/src/backup/format/csv/mod.rs similarity index 100% rename from rust/crates/keygo-core/src/backup/format/csv/mod.rs rename to rust/crates/keygo-client/src/backup/format/csv/mod.rs diff --git a/rust/crates/keygo-core/src/backup/format/json.rs b/rust/crates/keygo-client/src/backup/format/json.rs similarity index 100% rename from rust/crates/keygo-core/src/backup/format/json.rs rename to rust/crates/keygo-client/src/backup/format/json.rs diff --git a/rust/crates/keygo-core/src/backup/format/mod.rs b/rust/crates/keygo-client/src/backup/format/mod.rs similarity index 100% rename from rust/crates/keygo-core/src/backup/format/mod.rs rename to rust/crates/keygo-client/src/backup/format/mod.rs diff --git a/rust/crates/keygo-core/src/backup/mod.rs b/rust/crates/keygo-client/src/backup/mod.rs similarity index 100% rename from rust/crates/keygo-core/src/backup/mod.rs rename to rust/crates/keygo-client/src/backup/mod.rs diff --git a/rust/crates/keygo-core/src/backup/model.rs b/rust/crates/keygo-client/src/backup/model.rs similarity index 100% rename from rust/crates/keygo-core/src/backup/model.rs rename to rust/crates/keygo-client/src/backup/model.rs diff --git a/rust/crates/keygo-core/src/card/expiration.rs b/rust/crates/keygo-client/src/card/expiration.rs similarity index 100% rename from rust/crates/keygo-core/src/card/expiration.rs rename to rust/crates/keygo-client/src/card/expiration.rs diff --git a/rust/crates/keygo-core/src/card/mod.rs b/rust/crates/keygo-client/src/card/mod.rs similarity index 100% rename from rust/crates/keygo-core/src/card/mod.rs rename to rust/crates/keygo-client/src/card/mod.rs diff --git a/rust/crates/keygo-core/src/card/network.rs b/rust/crates/keygo-client/src/card/network.rs similarity index 100% rename from rust/crates/keygo-core/src/card/network.rs rename to rust/crates/keygo-client/src/card/network.rs diff --git a/rust/crates/keygo-core/src/card/number.rs b/rust/crates/keygo-client/src/card/number.rs similarity index 100% rename from rust/crates/keygo-core/src/card/number.rs rename to rust/crates/keygo-client/src/card/number.rs diff --git a/rust/crates/keygo-client/src/lib.rs b/rust/crates/keygo-client/src/lib.rs new file mode 100644 index 000000000..a8fcb9c61 --- /dev/null +++ b/rust/crates/keygo-client/src/lib.rs @@ -0,0 +1,10 @@ +#![forbid(unsafe_code)] + +pub mod ark_session; +mod b64; +pub mod backup; +pub mod card; +pub use keygo_core as crypto; +pub mod passkey; +pub mod totp; +mod url; diff --git a/rust/crates/keygo-core/src/passkey/authentication.rs b/rust/crates/keygo-client/src/passkey/authentication.rs similarity index 100% rename from rust/crates/keygo-core/src/passkey/authentication.rs rename to rust/crates/keygo-client/src/passkey/authentication.rs diff --git a/rust/crates/keygo-core/src/passkey/authenticator.rs b/rust/crates/keygo-client/src/passkey/authenticator.rs similarity index 100% rename from rust/crates/keygo-core/src/passkey/authenticator.rs rename to rust/crates/keygo-client/src/passkey/authenticator.rs diff --git a/rust/crates/keygo-core/src/passkey/codec.rs b/rust/crates/keygo-client/src/passkey/codec.rs similarity index 100% rename from rust/crates/keygo-core/src/passkey/codec.rs rename to rust/crates/keygo-client/src/passkey/codec.rs diff --git a/rust/crates/keygo-core/src/passkey/mod.rs b/rust/crates/keygo-client/src/passkey/mod.rs similarity index 100% rename from rust/crates/keygo-core/src/passkey/mod.rs rename to rust/crates/keygo-client/src/passkey/mod.rs diff --git a/rust/crates/keygo-core/src/passkey/registration.rs b/rust/crates/keygo-client/src/passkey/registration.rs similarity index 100% rename from rust/crates/keygo-core/src/passkey/registration.rs rename to rust/crates/keygo-client/src/passkey/registration.rs diff --git a/rust/crates/keygo-core/src/totp.rs b/rust/crates/keygo-client/src/totp.rs similarity index 100% rename from rust/crates/keygo-core/src/totp.rs rename to rust/crates/keygo-client/src/totp.rs diff --git a/rust/crates/keygo-core/src/url.rs b/rust/crates/keygo-client/src/url.rs similarity index 100% rename from rust/crates/keygo-core/src/url.rs rename to rust/crates/keygo-client/src/url.rs diff --git a/rust/crates/keygo-core/Cargo.toml b/rust/crates/keygo-core/Cargo.toml index 37ad235fe..97609a516 100644 --- a/rust/crates/keygo-core/Cargo.toml +++ b/rust/crates/keygo-core/Cargo.toml @@ -1,31 +1,33 @@ [package] name = "keygo-core" +description = "KeyGo ids, key types and sealed blobs, shared by the client and the server." version.workspace = true edition.workspace = true -[dependencies] -keygo-keys = { path = "../keygo-keys", features = ["crypto"] } +[features] +# Everything that can touch key material. The server stores sealed blobs and leaves this off. +crypto = [ + "dep:aead", + "dep:aes-gcm-siv", + "dep:argon2", + "dep:bcs", + "dep:hkdf", + "dep:sha2", + "dep:zeroize", +] +[dependencies] +serde = { workspace = true, features = ["derive"] } thiserror.workspace = true uuid.workspace = true -zeroize.workspace = true -base64.workspace = true -serde = { workspace = true, features = ["derive"] } -serde_json.workspace = true - -async-trait = "0.1.89" -ciborium = "0.2.2" -coset = "0.4.2" -passkey = "0.6.0" -passkey-authenticator = { version = "0.6.0", features = ["tokio"] } -# Needed so passkey JSON responses are serialized into base64 strings -passkey-types = { version = "0.6.0", features = ["serialize_bytes_as_base64_string"] } -csv = "1.4.0" -email_address = "0.2.9" -subtle = "2.6" -totp-rs = { version = "6.0.0", features = ["otpauth", "zeroize"] } -url = "2.5.8" +aead = { version = "0.6.0", optional = true } +aes-gcm-siv = { version = "0.12.1", optional = true } +argon2 = { version = "0.6.0", optional = true } +bcs = { version = "0.2.0", optional = true } +hkdf = { version = "0.13.0", optional = true } +sha2 = { workspace = true, optional = true } +zeroize = { workspace = true, features = ["derive"], optional = true } [dev-dependencies] -tokio = { workspace = true, features = ["rt", "macros"] } +base64.workspace = true diff --git a/rust/crates/keygo-keys/src/crypto/aad.rs b/rust/crates/keygo-core/src/crypto/aad.rs similarity index 100% rename from rust/crates/keygo-keys/src/crypto/aad.rs rename to rust/crates/keygo-core/src/crypto/aad.rs diff --git a/rust/crates/keygo-keys/src/crypto/backup.rs b/rust/crates/keygo-core/src/crypto/backup.rs similarity index 100% rename from rust/crates/keygo-keys/src/crypto/backup.rs rename to rust/crates/keygo-core/src/crypto/backup.rs diff --git a/rust/crates/keygo-keys/src/crypto/cipher.rs b/rust/crates/keygo-core/src/crypto/cipher.rs similarity index 100% rename from rust/crates/keygo-keys/src/crypto/cipher.rs rename to rust/crates/keygo-core/src/crypto/cipher.rs diff --git a/rust/crates/keygo-keys/src/crypto/golden_tests.rs b/rust/crates/keygo-core/src/crypto/golden_tests.rs similarity index 100% rename from rust/crates/keygo-keys/src/crypto/golden_tests.rs rename to rust/crates/keygo-core/src/crypto/golden_tests.rs diff --git a/rust/crates/keygo-keys/src/crypto/hierarchy.rs b/rust/crates/keygo-core/src/crypto/hierarchy.rs similarity index 100% rename from rust/crates/keygo-keys/src/crypto/hierarchy.rs rename to rust/crates/keygo-core/src/crypto/hierarchy.rs diff --git a/rust/crates/keygo-keys/src/crypto/kdf/argon2.rs b/rust/crates/keygo-core/src/crypto/kdf/argon2.rs similarity index 100% rename from rust/crates/keygo-keys/src/crypto/kdf/argon2.rs rename to rust/crates/keygo-core/src/crypto/kdf/argon2.rs diff --git a/rust/crates/keygo-keys/src/crypto/kdf/hkdf.rs b/rust/crates/keygo-core/src/crypto/kdf/hkdf.rs similarity index 100% rename from rust/crates/keygo-keys/src/crypto/kdf/hkdf.rs rename to rust/crates/keygo-core/src/crypto/kdf/hkdf.rs diff --git a/rust/crates/keygo-keys/src/crypto/kdf/mod.rs b/rust/crates/keygo-core/src/crypto/kdf/mod.rs similarity index 100% rename from rust/crates/keygo-keys/src/crypto/kdf/mod.rs rename to rust/crates/keygo-core/src/crypto/kdf/mod.rs diff --git a/rust/crates/keygo-keys/src/crypto/mod.rs b/rust/crates/keygo-core/src/crypto/mod.rs similarity index 100% rename from rust/crates/keygo-keys/src/crypto/mod.rs rename to rust/crates/keygo-core/src/crypto/mod.rs diff --git a/rust/crates/keygo-keys/src/crypto/traits.rs b/rust/crates/keygo-core/src/crypto/traits.rs similarity index 100% rename from rust/crates/keygo-keys/src/crypto/traits.rs rename to rust/crates/keygo-core/src/crypto/traits.rs diff --git a/rust/crates/keygo-keys/src/error.rs b/rust/crates/keygo-core/src/error.rs similarity index 100% rename from rust/crates/keygo-keys/src/error.rs rename to rust/crates/keygo-core/src/error.rs diff --git a/rust/crates/keygo-keys/src/ids.rs b/rust/crates/keygo-core/src/ids.rs similarity index 100% rename from rust/crates/keygo-keys/src/ids.rs rename to rust/crates/keygo-core/src/ids.rs diff --git a/rust/crates/keygo-keys/src/keys.rs b/rust/crates/keygo-core/src/keys.rs similarity index 100% rename from rust/crates/keygo-keys/src/keys.rs rename to rust/crates/keygo-core/src/keys.rs diff --git a/rust/crates/keygo-core/src/lib.rs b/rust/crates/keygo-core/src/lib.rs index 6efaa236c..9317035de 100644 --- a/rust/crates/keygo-core/src/lib.rs +++ b/rust/crates/keygo-core/src/lib.rs @@ -1,10 +1,20 @@ #![forbid(unsafe_code)] -pub mod ark_session; -mod b64; -pub mod backup; -pub mod card; -pub use keygo_keys as crypto; -pub mod passkey; -pub mod totp; -mod url; +//! The key hierarchy, the ids it binds to and the sealed blobs it produces. +//! +//! Without the `crypto` feature this is only names and storage: `Sealed` can be parsed, +//! stored and passed on, but no key can ever be created or read. That is the server's view. + +#[cfg(feature = "crypto")] +mod crypto; +mod error; +mod ids; +mod keys; +mod sealed; + +#[cfg(feature = "crypto")] +pub use crypto::*; +pub use error::{CryptoError, CryptoResult}; +pub use ids::{ItemId, NamespaceId, UserId, VaultId}; +pub use keys::{AccountRootKey, BackupKey, ItemKey, NamespaceKey, RootKek, VaultKey}; +pub use sealed::{KEY_LEN, NONCE_LEN, Sealed}; diff --git a/rust/crates/keygo-keys/src/sealed.rs b/rust/crates/keygo-core/src/sealed.rs similarity index 100% rename from rust/crates/keygo-keys/src/sealed.rs rename to rust/crates/keygo-core/src/sealed.rs diff --git a/rust/crates/keygo-keys/Cargo.toml b/rust/crates/keygo-keys/Cargo.toml deleted file mode 100644 index 8699de60e..000000000 --- a/rust/crates/keygo-keys/Cargo.toml +++ /dev/null @@ -1,33 +0,0 @@ -[package] -name = "keygo-keys" -description = "KeyGo key types, ids and sealed blobs, shared by the app and the server." -version.workspace = true -edition.workspace = true - -[features] -# Everything that can touch key material. The server stores sealed blobs and leaves this off. -crypto = [ - "dep:aead", - "dep:aes-gcm-siv", - "dep:argon2", - "dep:bcs", - "dep:hkdf", - "dep:sha2", - "dep:zeroize", -] - -[dependencies] -serde = { workspace = true, features = ["derive"] } -thiserror.workspace = true -uuid.workspace = true - -aead = { version = "0.6.0", optional = true } -aes-gcm-siv = { version = "0.12.1", optional = true } -argon2 = { version = "0.6.0", optional = true } -bcs = { version = "0.2.0", optional = true } -hkdf = { version = "0.13.0", optional = true } -sha2 = { workspace = true, optional = true } -zeroize = { workspace = true, features = ["derive"], optional = true } - -[dev-dependencies] -base64.workspace = true diff --git a/rust/crates/keygo-keys/src/lib.rs b/rust/crates/keygo-keys/src/lib.rs deleted file mode 100644 index 9317035de..000000000 --- a/rust/crates/keygo-keys/src/lib.rs +++ /dev/null @@ -1,20 +0,0 @@ -#![forbid(unsafe_code)] - -//! The key hierarchy, the ids it binds to and the sealed blobs it produces. -//! -//! Without the `crypto` feature this is only names and storage: `Sealed` can be parsed, -//! stored and passed on, but no key can ever be created or read. That is the server's view. - -#[cfg(feature = "crypto")] -mod crypto; -mod error; -mod ids; -mod keys; -mod sealed; - -#[cfg(feature = "crypto")] -pub use crypto::*; -pub use error::{CryptoError, CryptoResult}; -pub use ids::{ItemId, NamespaceId, UserId, VaultId}; -pub use keys::{AccountRootKey, BackupKey, ItemKey, NamespaceKey, RootKek, VaultKey}; -pub use sealed::{KEY_LEN, NONCE_LEN, Sealed}; diff --git a/rust/crates/keygo-uniffi/Cargo.toml b/rust/crates/keygo-uniffi/Cargo.toml index 178c003ce..3c385a069 100644 --- a/rust/crates/keygo-uniffi/Cargo.toml +++ b/rust/crates/keygo-uniffi/Cargo.toml @@ -8,7 +8,7 @@ name = "keygo_bindings" crate-type = ["cdylib"] [dependencies] -keygo-core = { path = "../keygo-core" } +keygo-client = { path = "../keygo-client" } thiserror.workspace = true uuid.workspace = true diff --git a/rust/crates/keygo-uniffi/src/ark_session.rs b/rust/crates/keygo-uniffi/src/ark_session.rs index 7c2ed73c9..4a18d2aa7 100644 --- a/rust/crates/keygo-uniffi/src/ark_session.rs +++ b/rust/crates/keygo-uniffi/src/ark_session.rs @@ -1,10 +1,10 @@ use crate::item::EncryptedItemBlob; use crate::key_wrap::{KeyWrapError, WrappedKeyBlob}; -use keygo_core::ark_session::{ +use keygo_client::ark_session::{ AccountRecord as CoreAccountRecord, ArkSession as CoreArkSession, ArkSessionError as CoreArkSessionError, NewAccount as CoreNewAccount, PasswordWrappedArk, }; -use keygo_core::crypto::{CryptoError, NamespaceId, SecretKind, UserId, VaultId, VaultKey}; +use keygo_client::crypto::{CryptoError, NamespaceId, SecretKind, UserId, VaultId, VaultKey}; use std::sync::Arc; #[derive(Debug, thiserror::Error, uniffi::Error)] diff --git a/rust/crates/keygo-uniffi/src/backup/csv.rs b/rust/crates/keygo-uniffi/src/backup/csv.rs index 33d36282e..d2d6acd70 100644 --- a/rust/crates/keygo-uniffi/src/backup/csv.rs +++ b/rust/crates/keygo-uniffi/src/backup/csv.rs @@ -1,4 +1,4 @@ -use keygo_core::backup::{ +use keygo_client::backup::{ Backup, ColumnMapping, Confidence, CsvAnalysis, CsvColumn, ExportPreset, FieldConfidence, ImportReport, }; diff --git a/rust/crates/keygo-uniffi/src/backup/mod.rs b/rust/crates/keygo-uniffi/src/backup/mod.rs index eb9a4614e..aed37e64a 100644 --- a/rust/crates/keygo-uniffi/src/backup/mod.rs +++ b/rust/crates/keygo-uniffi/src/backup/mod.rs @@ -3,8 +3,8 @@ mod model; use std::sync::Arc; -use keygo_core::ark_session::ArkSessionError; -use keygo_core::backup::{ +use keygo_client::ark_session::ArkSessionError; +use keygo_client::backup::{ Backup, BackupCredential as CoreCredential, BackupError as CoreError, ColumnMapping, CsvAnalysis, ExportPreset, KeySource, csv as core_csv, json as core_json, }; @@ -145,7 +145,7 @@ impl CsvBackupManager { #[cfg(test)] mod tests { - use keygo_core::crypto::KeyMaterial; + use keygo_client::crypto::KeyMaterial; use super::*; use crate::ark_session::ArkSession; diff --git a/rust/crates/keygo-uniffi/src/backup/model.rs b/rust/crates/keygo-uniffi/src/backup/model.rs index e85827c4f..0107e02df 100644 --- a/rust/crates/keygo-uniffi/src/backup/model.rs +++ b/rust/crates/keygo-uniffi/src/backup/model.rs @@ -1,4 +1,4 @@ -use keygo_core::backup::{Backup, Card, Login, Passkey, Vault}; +use keygo_client::backup::{Backup, Card, Login, Passkey, Vault}; #[uniffi::remote(Record)] #[uniffi(name = "BackupPasskey")] diff --git a/rust/crates/keygo-uniffi/src/card.rs b/rust/crates/keygo-uniffi/src/card.rs index 1bfc14fd0..3bf9e78b3 100644 --- a/rust/crates/keygo-uniffi/src/card.rs +++ b/rust/crates/keygo-uniffi/src/card.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use keygo_core::card::{Card, format_expiration_after_edit as core_format_expiration_after_edit}; +use keygo_client::card::{Card, format_expiration_after_edit as core_format_expiration_after_edit}; #[derive(uniffi::Object)] pub struct CardFormatter; diff --git a/rust/crates/keygo-uniffi/src/item.rs b/rust/crates/keygo-uniffi/src/item.rs index 084c23621..da091e558 100644 --- a/rust/crates/keygo-uniffi/src/item.rs +++ b/rust/crates/keygo-uniffi/src/item.rs @@ -1,4 +1,4 @@ -use keygo_core::crypto::{ +use keygo_client::crypto::{ CryptoError, Encrypts, ItemAad, ItemDataAad, ItemId, ItemKey, Sealed, SecretKind, VaultId, }; use std::sync::Arc; diff --git a/rust/crates/keygo-uniffi/src/key_wrap.rs b/rust/crates/keygo-uniffi/src/key_wrap.rs index 336613032..52fa5cb10 100644 --- a/rust/crates/keygo-uniffi/src/key_wrap.rs +++ b/rust/crates/keygo-uniffi/src/key_wrap.rs @@ -1,4 +1,4 @@ -use keygo_core::crypto::{CryptoError, ItemAad, ItemKey, Sealed, VaultKey, Wraps}; +use keygo_client::crypto::{CryptoError, ItemAad, ItemKey, Sealed, VaultKey, Wraps}; use std::sync::Arc; #[derive(uniffi::Record)] diff --git a/rust/crates/keygo-uniffi/src/passkey.rs b/rust/crates/keygo-uniffi/src/passkey.rs index 8483c93c0..956b00cc7 100644 --- a/rust/crates/keygo-uniffi/src/passkey.rs +++ b/rust/crates/keygo-uniffi/src/passkey.rs @@ -1,4 +1,4 @@ -use keygo_core::passkey::{ +use keygo_client::passkey::{ self as core, CreationInfo, PasskeyError as CorePasskeyError, Registration, }; use std::sync::Arc; diff --git a/rust/crates/keygo-uniffi/src/totp.rs b/rust/crates/keygo-uniffi/src/totp.rs index 93b54d85e..058ecd42a 100644 --- a/rust/crates/keygo-uniffi/src/totp.rs +++ b/rust/crates/keygo-uniffi/src/totp.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use keygo_core::totp::{self as core, TotpInfo as CoreTotpInfo, TotpParams}; +use keygo_client::totp::{self as core, TotpInfo as CoreTotpInfo, TotpParams}; use thiserror::Error; #[derive(Debug, Clone, Copy, uniffi::Enum)] @@ -10,25 +10,25 @@ pub enum Algorithm { Sha512, } -impl From for keygo_core::totp::Algorithm { +impl From for keygo_client::totp::Algorithm { fn from(value: Algorithm) -> Self { match value { - Algorithm::Sha1 => keygo_core::totp::Algorithm::SHA1, - Algorithm::Sha256 => keygo_core::totp::Algorithm::SHA256, - Algorithm::Sha512 => keygo_core::totp::Algorithm::SHA512, + Algorithm::Sha1 => keygo_client::totp::Algorithm::SHA1, + Algorithm::Sha256 => keygo_client::totp::Algorithm::SHA256, + Algorithm::Sha512 => keygo_client::totp::Algorithm::SHA512, } } } -impl TryFrom for Algorithm { +impl TryFrom for Algorithm { type Error = TotpError; /// `Algorithm` is non-exhaustive; an unknown variant is an error, not a panic across FFI. - fn try_from(value: keygo_core::totp::Algorithm) -> Result { + fn try_from(value: keygo_client::totp::Algorithm) -> Result { match value { - keygo_core::totp::Algorithm::SHA1 => Ok(Algorithm::Sha1), - keygo_core::totp::Algorithm::SHA256 => Ok(Algorithm::Sha256), - keygo_core::totp::Algorithm::SHA512 => Ok(Algorithm::Sha512), + keygo_client::totp::Algorithm::SHA1 => Ok(Algorithm::Sha1), + keygo_client::totp::Algorithm::SHA256 => Ok(Algorithm::Sha256), + keygo_client::totp::Algorithm::SHA512 => Ok(Algorithm::Sha512), _ => Err(TotpError::InvalidInput), } } @@ -68,8 +68,8 @@ pub enum TotpError { InvalidInput, } -impl From for TotpError { - fn from(err: keygo_core::totp::TotpError) -> Self { +impl From for TotpError { + fn from(err: keygo_client::totp::TotpError) -> Self { Self::Generic(err.to_string()) } } diff --git a/rust/crates/keygo-uniffi/src/types.rs b/rust/crates/keygo-uniffi/src/types.rs index bc4c6a7ae..295acb49f 100644 --- a/rust/crates/keygo-uniffi/src/types.rs +++ b/rust/crates/keygo-uniffi/src/types.rs @@ -1,4 +1,4 @@ -use keygo_core::crypto::{ItemId, ItemKey, KeyMaterial, NamespaceId, UserId, VaultId, VaultKey}; +use keygo_client::crypto::{ItemId, ItemKey, KeyMaterial, NamespaceId, UserId, VaultId, VaultKey}; use uuid::Uuid; uniffi::custom_type!(Uuid, String, { diff --git a/rust/crates/keygo-uniffi/src/vault.rs b/rust/crates/keygo-uniffi/src/vault.rs index bd3c40ba4..1f9708e98 100644 --- a/rust/crates/keygo-uniffi/src/vault.rs +++ b/rust/crates/keygo-uniffi/src/vault.rs @@ -1,4 +1,4 @@ -use keygo_core::crypto::VaultKey; +use keygo_client::crypto::VaultKey; use std::sync::Arc; #[derive(uniffi::Object)] From 9814febf3a35a2d5035b4b6c6b4b33df69ba2b3c Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 3 Nov 2026 15:44:47 +0100 Subject: [PATCH 5/9] build(server): depend on keygo-core without crypto The server will store wrapped keys, so it needs their names and `Sealed`, but must never be able to create a key. A workspace build turns `crypto` on for it anyway, so it would hide a server that uses it. Check the server on its own in CI too, and have the `serve` alias use `-p`, so it runs what the Docker image ships rather than a build with `crypto` on. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yaml | 4 ++++ rust/.cargo/config.toml | 3 ++- rust/Cargo.lock | 1 + rust/crates/keygo-server/Cargo.toml | 1 + 4 files changed, 8 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 06f45c127..c8906e539 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -64,6 +64,10 @@ jobs: run: | cargo clippy -p keygo-core --all-targets -- -D warnings ! cargo tree -p keygo-core -e normal --prefix none | grep -E '^(aead|aes-gcm-siv|argon2|bcs|hkdf|zeroize) ' + - name: keygo-server builds without crypto or client code + run: | + cargo clippy -p keygo-server --all-targets -- -D warnings + ! cargo tree -p keygo-server -e features | grep -E 'keygo-client|keygo-core feature "crypto"' # Rust-native tests (no NDK). Runs in parallel with android-test once lint passes. rust-test: diff --git a/rust/.cargo/config.toml b/rust/.cargo/config.toml index 040e81bd1..79670ca50 100644 --- a/rust/.cargo/config.toml +++ b/rust/.cargo/config.toml @@ -1,2 +1,3 @@ [alias] -serve = "run --bin keygo-server -- serve" \ No newline at end of file +# `-p`, not `--bin`: `--bin` selects the whole workspace, which turns on keygo-core's crypto feature. +serve = "run -p keygo-server -- serve" \ No newline at end of file diff --git a/rust/Cargo.lock b/rust/Cargo.lock index ec1f70173..2fd11922e 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1683,6 +1683,7 @@ dependencies = [ "hmac 0.13.0", "http-body-util", "humantime", + "keygo-core", "keygo-dpop", "keygo-opaque", "moka", diff --git a/rust/crates/keygo-server/Cargo.toml b/rust/crates/keygo-server/Cargo.toml index 72a2c3a01..60fe71ef1 100644 --- a/rust/crates/keygo-server/Cargo.toml +++ b/rust/crates/keygo-server/Cargo.toml @@ -5,6 +5,7 @@ version.workspace = true edition.workspace = true [dependencies] +keygo-core = { path = "../keygo-core" } keygo-opaque = { path = "../keygo-opaque" } keygo-dpop = { path = "../keygo-dpop" } From 6bb932f647708ea9570e9be93a76a15d37d3094d Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 3 Nov 2026 15:45:40 +0100 Subject: [PATCH 6/9] test(server): pin the bytes and wire form of UserId The OPAQUE identifier test used one repeated byte, so it could not see a change in byte order. Use distinct bytes, and pin the JSON form as well, before `UserId` moves to the shared crate. Co-Authored-By: Claude Opus 5.5 --- rust/crates/keygo-server/src/domain/ids.rs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/rust/crates/keygo-server/src/domain/ids.rs b/rust/crates/keygo-server/src/domain/ids.rs index f6f56d40f..76e754527 100644 --- a/rust/crates/keygo-server/src/domain/ids.rs +++ b/rust/crates/keygo-server/src/domain/ids.rs @@ -149,9 +149,24 @@ mod tests { #[test] fn opaque_identifier_is_pinned() { - let user_id = UserId::from(Uuid::from_bytes([7; LEN])); + let bytes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; + let user_id = UserId::from(Uuid::from_bytes(bytes)); - assert_eq!(user_id.opaque_identifier(), [7; LEN]); + assert_eq!(user_id.opaque_identifier(), bytes); + } + + #[test] + fn user_id_travels_as_the_uuids_string_form() { + let text = "00010203-0405-0607-0809-0a0b0c0d0e0f"; + let user_id = UserId::from(Uuid::from_bytes([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + ])); + + assert_eq!(serde_json::to_value(user_id).unwrap(), text); + assert_eq!( + serde_json::from_value::(text.into()).unwrap(), + user_id + ); } #[test] From f899c359eda9114770c5f8c3d69204754df63668 Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 3 Nov 2026 15:48:45 +0100 Subject: [PATCH 7/9] refactor(server): share UserId with the client through keygo-core Both sides hold the same id: it is generated by the client and equals the local user id. The shared type gains what the server relied on, `Deserialize`, `From` and `as_uuid`, and `domain` re-exports it so most callers stay as they are. `opaque_identifier` is server-only, and a method on a foreign type is not allowed, so it becomes a function. Its bytes and the JSON form are pinned by the tests added in the previous commit, whose expected values did not change. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 3 ++- rust/crates/keygo-core/src/ids.rs | 14 ++++++++-- .../src/api/routes/auth/register.rs | 2 +- .../keygo-server/src/db/opaque_records.rs | 3 ++- .../keygo-server/src/domain/access_token.rs | 27 ++++++++++++++----- rust/crates/keygo-server/src/domain/ids.rs | 16 +++++------ rust/crates/keygo-server/src/domain/mod.rs | 2 +- .../keygo-server/src/service/login/start.rs | 4 +-- .../src/service/registration/start.rs | 9 ++++--- .../keygo-server/src/service/step_up/start.rs | 4 +-- 10 files changed, 56 insertions(+), 28 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index b3779979d..df071e2c2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -199,7 +199,8 @@ Caddy as TLS proxy; `.env.example` sets `DOMAIN` and signups). multiple statements. - **Trailing commas** on multi-line parameter lists and collection literals. - **Rust constructors** — ids are made with `random()`, secret material (keys, tokens, codes) with - `generate()`. Server ids come from the `random_id!`/`uuid_id!` macros in `domain/ids.rs`. + `generate()`. Ids the client and server share live in `keygo-core`; server-only ids come from the + `random_id!`/`uuid_id!` macros in `domain/ids.rs`. ## Testing diff --git a/rust/crates/keygo-core/src/ids.rs b/rust/crates/keygo-core/src/ids.rs index 58262d95a..8552710c9 100644 --- a/rust/crates/keygo-core/src/ids.rs +++ b/rust/crates/keygo-core/src/ids.rs @@ -1,9 +1,9 @@ -use serde::Serialize; +use serde::{Deserialize, Serialize}; use uuid::Uuid; macro_rules! id { ($($name:ident),+) => { - $(#[derive(Serialize, Clone, Copy, PartialEq, Eq, Hash, Debug)] + $(#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Hash, Debug)] #[serde(transparent)] pub struct $name(pub Uuid); @@ -11,6 +11,16 @@ macro_rules! id { pub fn random() -> Self { Self(Uuid::new_v4()) } + + pub const fn as_uuid(self) -> Uuid { + self.0 + } + } + + impl From for $name { + fn from(value: Uuid) -> Self { + Self(value) + } })+ }; } diff --git a/rust/crates/keygo-server/src/api/routes/auth/register.rs b/rust/crates/keygo-server/src/api/routes/auth/register.rs index d7f34f73c..803f13572 100644 --- a/rust/crates/keygo-server/src/api/routes/auth/register.rs +++ b/rust/crates/keygo-server/src/api/routes/auth/register.rs @@ -318,7 +318,7 @@ mod tests { #[sqlx::test] async fn start_rejects_a_structured_user_id(db: PgPool) { - let (_, body) = start_body("ada", UserId::nil()); + let (_, body) = start_body("ada", UserId::from(Uuid::nil())); let (status, body) = post(&db, &ServerSetup::generate(), START, body).await; diff --git a/rust/crates/keygo-server/src/db/opaque_records.rs b/rust/crates/keygo-server/src/db/opaque_records.rs index 358f1dbf7..ae37e1e9c 100644 --- a/rust/crates/keygo-server/src/db/opaque_records.rs +++ b/rust/crates/keygo-server/src/db/opaque_records.rs @@ -88,7 +88,8 @@ mod tests { let setup = ServerSetup::generate(); let (client, request) = ClientRegistration::start(PASSWORD).unwrap(); let response = - server::registration_start(&setup, request, user_id.opaque_identifier()).unwrap(); + server::registration_start(&setup, request, crate::domain::opaque_identifier(&user_id)) + .unwrap(); let finish = client.finish(PASSWORD, response).unwrap(); server::registration_finish(finish.upload) } diff --git a/rust/crates/keygo-server/src/domain/access_token.rs b/rust/crates/keygo-server/src/domain/access_token.rs index 879f29b10..a27517f5c 100644 --- a/rust/crates/keygo-server/src/domain/access_token.rs +++ b/rust/crates/keygo-server/src/domain/access_token.rs @@ -373,7 +373,7 @@ mod tests { fn expires_after_lifetime() { let claims = Claims::new_at( String::new(), - UserId::nil(), + UserId::from(uuid::Uuid::nil()), SessionId::nil(), 0, &JKT, @@ -386,7 +386,17 @@ mod tests { #[test] fn generated_jtis_differ() { - let new = || Claims::new_at(String::new(), UserId::nil(), SessionId::nil(), 0, &JKT, 0).jti; + let new = || { + Claims::new_at( + String::new(), + UserId::from(uuid::Uuid::nil()), + SessionId::nil(), + 0, + &JKT, + 0, + ) + .jti + }; assert_ne!(new(), new()); } @@ -543,7 +553,7 @@ mod tests { fn fresh_within_window_after_auth_time() { let claims = Claims::new_at( String::new(), - UserId::nil(), + UserId::from(uuid::Uuid::nil()), SessionId::nil(), 1_000, &JKT, @@ -560,7 +570,7 @@ mod tests { let key = AccessTokenKey::new(&SEED); let token = key.sign(&Claims::new_at( ISS.into(), - UserId::nil(), + UserId::from(uuid::Uuid::nil()), SessionId::nil(), unix_now(), &JKT, @@ -591,7 +601,7 @@ mod tests { fn issuer_rejects_tokens_for_another_issuer() { let key = || AccessTokenKey::new(&SEED); let token = TokenIssuer::new(key(), "https://other.example").issue( - UserId::nil(), + UserId::from(uuid::Uuid::nil()), SessionId::nil(), unix_now(), &JKT, @@ -608,7 +618,12 @@ mod tests { let issuer = TokenIssuer::new(AccessTokenKey::new(&SEED), ISS); let auth_time = unix_now() - FRESH_AUTH_WINDOW.as_secs() - 1; - let token = issuer.issue(UserId::nil(), SessionId::nil(), auth_time, &JKT); + let token = issuer.issue( + UserId::from(uuid::Uuid::nil()), + SessionId::nil(), + auth_time, + &JKT, + ); let claims = issuer.verify(token.expose()).unwrap(); assert!(!claims.is_fresh()); diff --git a/rust/crates/keygo-server/src/domain/ids.rs b/rust/crates/keygo-server/src/domain/ids.rs index 76e754527..ec739172e 100644 --- a/rust/crates/keygo-server/src/domain/ids.rs +++ b/rust/crates/keygo-server/src/domain/ids.rs @@ -4,6 +4,9 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer}; use thiserror::Error; use uuid::Uuid; +/// An account. Client-generated at registration and equal to the app's local user id. +pub use keygo_core::UserId; + const LEN: usize = 16; #[derive(Debug, Clone, Copy, PartialEq, Eq, Error)] @@ -98,9 +101,6 @@ uuid_id! { /// A device registered to an account. DeviceId; - - /// An account. Client-generated at registration and equal to the app's local user id. - UserId; } impl RegistrationId { @@ -109,11 +109,9 @@ impl RegistrationId { } } -impl UserId { - /// What OPAQUE binds the password file to: registration, login and step-up must all agree on it. - pub const fn opaque_identifier(&self) -> &[u8] { - self.0.as_bytes() - } +/// What OPAQUE binds the password file to: registration, login and step-up must all agree on it. +pub const fn opaque_identifier(user_id: &UserId) -> &[u8] { + user_id.0.as_bytes() } #[cfg(test)] @@ -152,7 +150,7 @@ mod tests { let bytes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; let user_id = UserId::from(Uuid::from_bytes(bytes)); - assert_eq!(user_id.opaque_identifier(), bytes); + assert_eq!(opaque_identifier(&user_id), bytes); } #[test] diff --git a/rust/crates/keygo-server/src/domain/mod.rs b/rust/crates/keygo-server/src/domain/mod.rs index 06a4b73bc..3290d9314 100644 --- a/rust/crates/keygo-server/src/domain/mod.rs +++ b/rust/crates/keygo-server/src/domain/mod.rs @@ -13,7 +13,7 @@ mod username; pub use access_token::FRESH_AUTH_WINDOW; pub use access_token::{ACCESS_TOKEN_LIFETIME, AccessToken, AccessTokenKey, Claims, TokenIssuer}; pub use device::{Device, DeviceClaim, DeviceInfo}; -pub use ids::{DeviceId, LoginId, RegistrationId, SessionId, UserId}; +pub use ids::{DeviceId, LoginId, RegistrationId, SessionId, UserId, opaque_identifier}; pub use invite_code::{InviteCode, InvitePepper}; pub use invite_hash::InviteHash; pub use invite_id::InviteId; diff --git a/rust/crates/keygo-server/src/service/login/start.rs b/rust/crates/keygo-server/src/service/login/start.rs index 0aff41abd..57d00e6cd 100644 --- a/rust/crates/keygo-server/src/service/login/start.rs +++ b/rust/crates/keygo-server/src/service/login/start.rs @@ -1,6 +1,6 @@ use crate::cache::LoginStates; use crate::db::opaque_records; -use crate::domain::Username; +use crate::domain::{Username, opaque_identifier}; use crate::service::handshake::{self, Error, Started}; use keygo_opaque::CredentialRequest; use keygo_opaque::server::ServerSetup; @@ -36,7 +36,7 @@ pub async fn start( Some(record) => ( Some(record.user_id), Some(record.file), - record.user_id.opaque_identifier().to_vec(), + opaque_identifier(&record.user_id).to_vec(), ), None => (None, None, fake_identifier(&username)), }; diff --git a/rust/crates/keygo-server/src/service/registration/start.rs b/rust/crates/keygo-server/src/service/registration/start.rs index 8d817df19..be9df8717 100644 --- a/rust/crates/keygo-server/src/service/registration/start.rs +++ b/rust/crates/keygo-server/src/service/registration/start.rs @@ -1,6 +1,6 @@ use crate::db::registrations::{self, ReserveError}; use crate::db::{invites, users}; -use crate::domain::{InviteCode, InviteHash, RegistrationId, UserId, Username}; +use crate::domain::{InviteCode, InviteHash, RegistrationId, UserId, Username, opaque_identifier}; use crate::service::registration::{Signup, TTL}; use keygo_opaque::server::ServerSetup; use keygo_opaque::{OpaqueError, RegistrationRequest, RegistrationResponse, server}; @@ -78,7 +78,7 @@ pub async fn start( // Pure computation, so it runs before the transaction to keep the reservation's lock short. let registration_response = - server::registration_start(setup, registration_request, user_id.opaque_identifier())?; + server::registration_start(setup, registration_request, opaque_identifier(&user_id))?; let mut tx = db.begin().await?; let registration_id = RegistrationId::random(); @@ -295,7 +295,10 @@ mod tests { #[sqlx::test] async fn start_rejects_structured_user_ids(db: PgPool) { - let err = start_as(&db, UserId::nil(), "ada").await.err().unwrap(); + let err = start_as(&db, UserId::from(Uuid::nil()), "ada") + .await + .err() + .unwrap(); assert!(matches!(err, StartError::InvalidUserId), "{err:?}"); assert_eq!(count(&db, "pending_registrations").await, 0); diff --git a/rust/crates/keygo-server/src/service/step_up/start.rs b/rust/crates/keygo-server/src/service/step_up/start.rs index a71637840..68b9ebb9d 100644 --- a/rust/crates/keygo-server/src/service/step_up/start.rs +++ b/rust/crates/keygo-server/src/service/step_up/start.rs @@ -1,6 +1,6 @@ use crate::cache::StepUpStates; use crate::db::opaque_records; -use crate::domain::UserId; +use crate::domain::{UserId, opaque_identifier}; use crate::service::handshake::{self, Error, Started}; use keygo_opaque::server::ServerSetup; use keygo_opaque::{CredentialRequest, OpaqueError}; @@ -33,7 +33,7 @@ pub async fn start( setup, user_id, Some(password_file), - user_id.opaque_identifier(), + opaque_identifier(&user_id), credential_request, ) } From e5054f8574442ec9559e6316800f7bc37612e5f7 Mon Sep 17 00:00:00 2001 From: Davis Date: Wed, 4 Nov 2026 10:55:05 +0100 Subject: [PATCH 8/9] ci(rust): test keygo-core and keygo-server without crypto A workspace run unifies features, so keygo-client's crypto reached every crate and the builds without it were linted but never tested. Test both crates alone and leave keygo-server out of the workspace run. make test runs the same commands. The dependency checks could pass without checking anything: a failing cargo tree counted as no match, and renaming the feature hid a leak. Allow only the expected keygo-core deps, which also catches sha2 and any new mandatory dep, and confirm the pattern still matches keygo-client. Drop clippy -p keygo-server, as the new test step and clippy -p keygo-core catch what it did. Make rust-test wait for rust-lint, as the comments already said. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yaml | 22 ++++++++++++++++------ rust/Makefile | 6 ++++-- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index c8906e539..bd6cad2e1 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -63,15 +63,19 @@ jobs: - name: keygo-core holds no crypto without its feature run: | cargo clippy -p keygo-core --all-targets -- -D warnings - ! cargo tree -p keygo-core -e normal --prefix none | grep -E '^(aead|aes-gcm-siv|argon2|bcs|hkdf|zeroize) ' - - name: keygo-server builds without crypto or client code + deps=$(cargo tree -p keygo-core -e normal --depth 1 --prefix none | tail -n +2 | cut -d' ' -f1 | sort | xargs) + [ "$deps" = "serde thiserror uuid" ] || { echo "unexpected keygo-core deps: $deps" >&2; exit 1; } + - name: keygo-server holds no crypto or client code run: | - cargo clippy -p keygo-server --all-targets -- -D warnings - ! cargo tree -p keygo-server -e features | grep -E 'keygo-client|keygo-core feature "crypto"' + # Proves the pattern below still matches, so renaming the feature can't silently disable it. + client=$(cargo tree -p keygo-client -e features) + grep -q 'keygo-core feature "crypto"' <<<"$client" + server=$(cargo tree -p keygo-server -e features) + if grep -E 'keygo-client|keygo-core feature "crypto"' <<<"$server"; then exit 1; fi # Rust-native tests (no NDK). Runs in parallel with android-test once lint passes. rust-test: - needs: [ detect-changes ] + needs: [ detect-changes, rust-lint ] if: needs.detect-changes.outputs.rust == 'true' runs-on: ubuntu-latest @@ -117,8 +121,14 @@ jobs: restore-keys: ${{ runner.os }}-cargo-test- - name: Build run: cargo build --workspace --all-targets --verbose + # A workspace build unifies features, so keygo-client's "crypto" reaches every crate in it. + # keygo-core and keygo-server are also tested alone, in the form the server ships them. - name: Run tests - run: cargo test --workspace --verbose + run: cargo test --workspace --exclude keygo-server --verbose + - name: Run keygo-core tests without crypto + run: cargo test -p keygo-core --verbose + - name: Run keygo-server tests + run: cargo test -p keygo-server --verbose # Offline builds never see the schema, so a migration that changes a queried column would # still compile against stale .sqlx data. Recompute it against the migrated database instead. - name: Install sqlx-cli diff --git a/rust/Makefile b/rust/Makefile index 33b93fecc..9bd369838 100644 --- a/rust/Makefile +++ b/rust/Makefile @@ -80,8 +80,10 @@ check: ## cargo check the workspace fmt: ## Format Rust code with cargo fmt cargo fmt --all -test: ## cargo test the workspace - cargo test --workspace +test: ## cargo test the workspace, with keygo-core and keygo-server also built without crypto + cargo test --workspace --exclude keygo-server + cargo test -p keygo-core + cargo test -p keygo-server clean: ## Remove build artifacts and generated jniLibs cargo clean From 750d233442aacc062f4e44bd6640a5d1940a5c88 Mon Sep 17 00:00:00 2001 From: Davis Date: Wed, 4 Nov 2026 10:55:53 +0100 Subject: [PATCH 9/9] doc(rust): change comment --- rust/crates/keygo-core/src/crypto/traits.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/crates/keygo-core/src/crypto/traits.rs b/rust/crates/keygo-core/src/crypto/traits.rs index 2993d60ac..1d78f28a4 100644 --- a/rust/crates/keygo-core/src/crypto/traits.rs +++ b/rust/crates/keygo-core/src/crypto/traits.rs @@ -4,7 +4,7 @@ use crate::crypto::aad::{Aad, encode_aad}; use crate::error::{CryptoError, CryptoResult}; use zeroize::{ZeroizeOnDrop, Zeroizing}; -/// Anything that can be sealed under a wrapping key. +/// Represents a raw key. pub trait KeyMaterial: Sized + ZeroizeOnDrop { fn from_bytes(bytes: &[u8]) -> CryptoResult; fn as_bytes(&self) -> &[u8];