diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index cb148783c..bd6cad2e1 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -59,10 +59,23 @@ 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-core holds no crypto without its feature + run: | + cargo clippy -p keygo-core --all-targets -- -D warnings + 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: | + # 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 @@ -108,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/CLAUDE.md b/CLAUDE.md index b2d1b482b..df071e2c2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -64,8 +64,9 @@ 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-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` | @@ -198,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/.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 369bc094e..2fd11922e 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1594,26 +1594,21 @@ dependencies = [ ] [[package]] -name = "keygo-core" +name = "keygo-client" 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-core", "passkey", "passkey-authenticator", "passkey-types", "serde", "serde_json", - "sha2 0.11.1", "subtle", "thiserror", "tokio", @@ -1623,6 +1618,23 @@ dependencies = [ "zeroize", ] +[[package]] +name = "keygo-core" +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-dpop" version = "0.1.0" @@ -1671,6 +1683,7 @@ dependencies = [ "hmac 0.13.0", "http-body-util", "humantime", + "keygo-core", "keygo-dpop", "keygo-opaque", "moka", @@ -1698,7 +1711,7 @@ dependencies = [ name = "keygo-uniffi" version = "0.1.0" dependencies = [ - "keygo-core", + "keygo-client", "thiserror", "tokio", "uniffi", 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 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 98% rename from rust/crates/keygo-core/src/ark_session.rs rename to rust/crates/keygo-client/src/ark_session.rs index d8d2da617..348062718 100644 --- a/rust/crates/keygo-core/src/ark_session.rs +++ b/rust/crates/keygo-client/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/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 94% rename from rust/crates/keygo-core/src/backup/encryption.rs rename to rust/crates/keygo-client/src/backup/encryption.rs index 50953b0b1..2dc17a636 100644 --- a/rust/crates/keygo-core/src/backup/encryption.rs +++ b/rust/crates/keygo-client/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]), @@ -161,7 +142,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/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 99% rename from rust/crates/keygo-core/src/backup/format/json.rs rename to rust/crates/keygo-client/src/backup/format/json.rs index 5d5e4de3f..00a1b3d27 100644 --- a/rust/crates/keygo-core/src/backup/format/json.rs +++ b/rust/crates/keygo-client/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/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 93% rename from rust/crates/keygo-core/src/backup/mod.rs rename to rust/crates/keygo-client/src/backup/mod.rs index 2bd02fc64..832c07cd5 100644 --- a/rust/crates/keygo-core/src/backup/mod.rs +++ b/rust/crates/keygo-client/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/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 5fa140e48..97609a516 100644 --- a/rust/crates/keygo-core/Cargo.toml +++ b/rust/crates/keygo-core/Cargo.toml @@ -1,35 +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 +[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 -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" -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"] } -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" +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-core/src/crypto/aad.rs b/rust/crates/keygo-core/src/crypto/aad.rs index c5558f024..0bbb16501 100644 --- a/rust/crates/keygo-core/src/crypto/aad.rs +++ b/rust/crates/keygo-core/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-core/src/crypto/backup.rs similarity index 78% rename from rust/crates/keygo-core/src/backup/key.rs rename to rust/crates/keygo-core/src/crypto/backup.rs index 28eeb4b41..49425b468 100644 --- a/rust/crates/keygo-core/src/backup/key.rs +++ b/rust/crates/keygo-core/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, SymmetricKey, 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-core/src/crypto/cipher.rs b/rust/crates/keygo-core/src/crypto/cipher.rs index 7466abfbe..aef365b5c 100644 --- a/rust/crates/keygo-core/src/crypto/cipher.rs +++ b/rust/crates/keygo-core/src/crypto/cipher.rs @@ -1,4 +1,4 @@ -use crate::crypto::{CryptoError, CryptoResult}; +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; @@ -7,42 +7,11 @@ 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>, -} +// `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 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( @@ -53,7 +22,7 @@ impl Sealed { }, )?; Ok(Self { - nonce, + nonce: nonce.into(), ciphertext, content: PhantomData, }) @@ -61,7 +30,7 @@ impl Sealed { pub(crate) fn open(&self, key: &CipherKey, aad: &[u8]) -> Result, aead::Error> { Cipher::new(key).decrypt( - &self.nonce, + &Nonce::::from(self.nonce), Payload { msg: &self.ciphertext, aad, @@ -69,25 +38,3 @@ impl Sealed { ) } } - -#[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/golden_tests.rs b/rust/crates/keygo-core/src/crypto/golden_tests.rs index 8a5059fc4..c97d79d61 100644 --- a/rust/crates/keygo-core/src/crypto/golden_tests.rs +++ b/rust/crates/keygo-core/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::{ - AccountRootKey, Encrypts, ItemAad, ItemDataAad, ItemId, ItemKey, NamespaceDataAad, NamespaceId, - NamespaceKey, NamespaceKeyAad, RootKEK, Sealed, SecretKind, SymmetricKey, UserId, VaultId, +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,15 +52,15 @@ 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() } #[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/keys.rs b/rust/crates/keygo-core/src/crypto/hierarchy.rs similarity index 85% rename from rust/crates/keygo-core/src/crypto/keys.rs rename to rust/crates/keygo-core/src/crypto/hierarchy.rs index b3a84bf1a..21a49a136 100644 --- a/rust/crates/keygo-core/src/crypto/keys.rs +++ b/rust/crates/keygo-core/src/crypto/hierarchy.rs @@ -1,15 +1,17 @@ //! 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::aad::{Aad, aad}; use crate::crypto::kdf::argon2::{Argon2Params, derive_argon2id}; -use crate::crypto::{ - Aad, CipherKey, CryptoResult, Encrypts, ItemId, NamespaceId, SymmetricKey, 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,31 +99,32 @@ 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; } -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()) @@ -153,7 +135,7 @@ macro_rules! impl_generate { ($($key:ident),+) => { $(impl $key { pub fn generate() -> Self { - Self(CipherKey::generate()) + Self { key: CipherKey::generate() } } })+ }; @@ -164,21 +146,21 @@ impl_generate!(AccountRootKey, VaultKey, ItemKey, NamespaceKey); #[cfg(test)] mod tests { use super::*; - use crate::crypto::Sealed; + use crate::Sealed; const SALT: &[u8] = &[6; 16]; #[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 +169,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/ids.rs b/rust/crates/keygo-core/src/crypto/ids.rs deleted file mode 100644 index 58262d95a..000000000 --- a/rust/crates/keygo-core/src/crypto/ids.rs +++ /dev/null @@ -1,18 +0,0 @@ -use serde::Serialize; -use uuid::Uuid; - -macro_rules! id { - ($($name:ident),+) => { - $(#[derive(Serialize, Clone, Copy, PartialEq, Eq, Hash, Debug)] - #[serde(transparent)] - pub struct $name(pub Uuid); - - impl $name { - pub fn random() -> Self { - Self(Uuid::new_v4()) - } - })+ - }; -} - -id!(UserId, VaultId, ItemId, NamespaceId); diff --git a/rust/crates/keygo-core/src/crypto/kdf/argon2.rs b/rust/crates/keygo-core/src/crypto/kdf/argon2.rs index 1045de374..1ead2f651 100644 --- a/rust/crates/keygo-core/src/crypto/kdf/argon2.rs +++ b/rust/crates/keygo-core/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-core/src/crypto/kdf/hkdf.rs index 968ba2851..b633966f6 100644 --- a/rust/crates/keygo-core/src/crypto/kdf/hkdf.rs +++ b/rust/crates/keygo-core/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-core/src/crypto/kdf/mod.rs b/rust/crates/keygo-core/src/crypto/kdf/mod.rs index 14b02cc1b..e23167af8 100644 --- a/rust/crates/keygo-core/src/crypto/kdf/mod.rs +++ b/rust/crates/keygo-core/src/crypto/kdf/mod.rs @@ -1,10 +1,10 @@ -pub(crate) mod argon2; +pub mod argon2; pub(crate) mod hkdf; use aead::Generate; -pub(crate) const SALT_LEN: usize = 16; +pub const SALT_LEN: usize = 16; -pub(crate) fn new_salt() -> [u8; SALT_LEN] { +pub 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 index a026d9d93..83d48ad86 100644 --- a/rust/crates/keygo-core/src/crypto/mod.rs +++ b/rust/crates/keygo-core/src/crypto/mod.rs @@ -1,22 +1,15 @@ -pub(crate) mod aad; +mod aad; +mod backup; mod cipher; -mod error; -mod ids; -pub(crate) mod kdf; -mod key; -mod keys; +mod hierarchy; +pub mod kdf; +mod traits; 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, SymmetricKey, Wraps}; -pub use keys::{ - AccountRootKey, ItemAad, ItemDataAad, ItemKey, NamespaceDataAad, NamespaceKey, NamespaceKeyAad, - RootKEK, SecretKind, VaultKey, -}; +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-core/src/crypto/traits.rs similarity index 77% rename from rust/crates/keygo-core/src/crypto/key.rs rename to rust/crates/keygo-core/src/crypto/traits.rs index 617e6df8f..1d78f28a4 100644 --- a/rust/crates/keygo-core/src/crypto/key.rs +++ b/rust/crates/keygo-core/src/crypto/traits.rs @@ -1,19 +1,22 @@ -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}; -pub trait SymmetricKey: Sized + ZeroizeOnDrop { +/// Represents a raw 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> { @@ -45,40 +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::SymmetricKey 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 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-core/src/error.rs similarity index 95% rename from rust/crates/keygo-core/src/crypto/error.rs rename to rust/crates/keygo-core/src/error.rs index 5a0351ebf..494f4e1af 100644 --- a/rust/crates/keygo-core/src/crypto/error.rs +++ b/rust/crates/keygo-core/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/ids.rs b/rust/crates/keygo-core/src/ids.rs new file mode 100644 index 000000000..8552710c9 --- /dev/null +++ b/rust/crates/keygo-core/src/ids.rs @@ -0,0 +1,28 @@ +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +macro_rules! id { + ($($name:ident),+) => { + $(#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Hash, Debug)] + #[serde(transparent)] + pub struct $name(pub Uuid); + + impl $name { + 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) + } + })+ + }; +} + +id!(UserId, VaultId, ItemId, NamespaceId); diff --git a/rust/crates/keygo-core/src/keys.rs b/rust/crates/keygo-core/src/keys.rs new file mode 100644 index 000000000..348f2a750 --- /dev/null +++ b/rust/crates/keygo-core/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-core/src/lib.rs b/rust/crates/keygo-core/src/lib.rs index f6915a921..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 mod 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-core/src/sealed.rs b/rust/crates/keygo-core/src/sealed.rs new file mode 100644 index 000000000..3aae70315 --- /dev/null +++ b/rust/crates/keygo-core/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]); + } +} 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" } 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 f6f56d40f..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)] @@ -149,9 +147,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!(opaque_identifier(&user_id), 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] 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, ) } 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 e4d4af495..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::SymmetricKey; + 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 1eb26e63f..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, NamespaceId, SymmetricKey, 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)]