π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
docs: add crypto docs to rust-crypto
Prateek Sunal80f5146256b2
diff --git a/rust/README.md b/rust/README.mdindex df6e28ab72..d669d026f9 100644--- a/rust/README.md+++ b/rust/README.md@@ -1,213 +1,40 @@# Rust in Ente-```- βββββββββββββββββββββββββββββββββββββββββ- β rust/core/ β- β (ente-core crate) β- β β- β Pure Rust - NO FFI annotations β- β Stateless business logic β- β Fully testable with cargo test β- βββββββββββββββββββββββββββββββββββββββββ- β- ββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββ- β β β- βΌ βΌ βΌ-βββββββββββββββββββββββββββββ βββββββββββββββββββββββββββββ ββββββββββββββββββββββββββ-β mobile/packages/rust/ β β web/packages/wasm/ β β rust/cli/ β-β (ente_rust crate) β β (ente-wasm crate) β β β-β β β β β CLI binary, depends β-β Shared #[frb] wrappers β β #[wasm_bindgen] wrappers β β on ente-core β-β for all mobile apps β β for all web apps β β β-βββββββββββββββββββββββββββββ βββββββββββββββββββββββββββββ ββββββββββββββββββββββββββ- β β β- β ββββββββββββββββ β- βΌ βΌ βΌ-βββββββββββββββββββ ββββββββββββββ βββββββββββββββββββββββββββββ-β Photos App β β Other apps β β Web Apps β-β β β (Auth ...) β β (Photos, Auth, etc.) β-βββββββββββββββββββ ββββββββββββββ βββββββββββββββββββββββββββββ- β²- β-βββββββββββββββββββββββββββββ-β mobile/apps/photos/rust/ β-β (ente_photos_rust crate) β-β β-β App-specific #[frb]: β-β usearch, ML, etc. β-βββββββββββββββββββββββββββββ-```--## Directory Structure--```-rust/-βββ cli/ # CLI package-β βββ src/-β β βββ main.rs-β βββ Cargo.toml-β βββ Cargo.lock-β-βββ core/ # Pure Rust business logic- βββ src/- β βββ lib.rs- β βββ urls.rs- βββ Cargo.toml # crate name: ente-core--web/packages/wasm/ # WASM bindings (lives in web workspace)-βββ src/-β βββ lib.rs # #[wasm_bindgen] wrappers around ente-core-βββ Cargo.toml # crate name: ente-wasm-βββ package.json # includes wasm-pack as devDependency-βββ pkg/ # generated output (gitignored)--mobile/packages/rust/ # Shared FRB bindings for all mobile apps-βββ rust/-β βββ src/-β β βββ api/ # #[frb] wrappers around ente-core-β βββ Cargo.toml # crate name: ente_rust-βββ lib/ # Generated Dart bindings-βββ pubspec.yaml # Flutter plugin package--mobile/apps/photos/rust/ # Photos app-specific FRB bindings-βββ src/-β βββ lib.rs-β βββ api/ # #[frb] app-specific code (usearch, ML)-β βββ *.rs-βββ Cargo.toml # crate name: ente_photos_rust-```--**Crates:**--- `ente-core` - shared business logic (pure Rust, no FFI)-- `ente-wasm` - wasm-bindgen wrappers for web-- `ente_rust` - shared FRB wrappers for mobile (Dart class: `EnteRust`)-- `ente_photos_rust` - Photos app-specific FRB (Dart class: `EntePhotosRust`)--## Tooling+This directory hosts Rust crates used across Ente clients.-### [wasm-bindgen](https://github.com/wasm-bindgen/wasm-bindgen)+## Crates-A Rust library that provides the `#[wasm_bindgen]` attribute macro. When you annotate a function with `#[wasm_bindgen]`, it:+### `rust/core/` (ente-core)-1. Marks the function for export to JavaScript-2. Handles type conversions between Rust and JS (e.g., `String` β JS string, `i64` β `BigInt`)-3. Generates metadata that the wasm-bindgen CLI uses to create JS/TS glue code+Pure Rust shared logic (primarily cryptography) that is wire-compatible with the existing+JS/Dart implementations.-The library itself is lightweight - just macros and runtime types.--### [wasm-pack](https://github.com/drager/wasm-pack)--A CLI tool that orchestrates the WASM build process:--1. Runs `cargo build --target wasm32-unknown-unknown`-2. Invokes `wasm-bindgen` CLI to generate JS/TS bindings from the compiled WASM-3. Outputs everything to a `pkg/` directory ready for npm/bundlers--wasm-pack is installed via npm as a devDependency, so `yarn install` handles it.--### [Flutter Rust Bridge (FRB)](https://github.com/fzyzcjy/flutter_rust_bridge)--Used for Flutter integration. FRB is used on two crates:--- **`ente_rust`** (`mobile/packages/rust/`) - Shared wrappers around `ente-core`, used by multiple mobile apps (Photos, Auth, etc.)-- **`ente_photos_rust`** (`mobile/apps/photos/rust/`) - Photos app-specific functionality (usearch, ML)--Both depend on `ente-core` and use `#[frb]` annotations to generate Dart bindings.+- Source: `rust/core/src/`+- Docs:+ - `rust/core/docs/crypto.md`## Development-### Commands-**ente-core (rust/core/):**```sh-cargo fmt # format-cargo clippy # lint-cargo build # build-cargo test # test-```--**ente-wasm (web/packages/wasm/):**--```sh-yarn install # installs wasm-pack-yarn build # runs wasm-pack build --target bundler-```--Or from web/ root:--```sh-yarn build:wasm # builds the WASM package-```--> [!TIP]->-> For active Rust development, use watch mode in a separate terminal:->-> ```sh-> cargo install cargo-watch-> cd web/-> cargo watch -w ../rust/core -w packages/wasm/src -s "yarn build:wasm"-> ```--**ente_rust (mobile/packages/rust/):**--```sh-cargo install flutter_rust_bridge_codegen-flutter_rust_bridge_codegen generate-```--`flutter_rust_bridge_codegen generate` needs to be run either manually (or in watch mode, `flutter_rust_bridge_codegen generate --watch`) whenever the Rust source changes to get the bindings to update.--**ente_photos_rust (mobile/apps/photos/rust/):**--```sh-flutter_rust_bridge_codegen generate-flutter test+cargo fmt+cargo clippy+cargo build+cargo test```-## Future--### CLI Migration--A WIP CLI lives in `rust/cli/` and depends on ente-core via path dependency.--Next steps:+## Integrations-1. Move code from CLI to ente-core, adding tests as we migrate.-2. Update CLI to use ente-core implementations-3. Prune CLI dependencies as code moves to core--### WASM Compatibility--Core crate must handle deps that don't compile to WASM:--| Dependency | Issue | Solution |-| ---------------------- | ---------------- | --------------------------------------------------------------------------------------- |-| `libsodium-sys-stable` | Native C library | Feature-gate; use pure Rust crypto (e.g., `chacha20poly1305` crate) or WebCrypto via JS |-| `rusqlite` | Native SQLite | Feature-gate; WASM uses IndexedDB via JS interop |-| `tokio` (full) | Threading | Use WASM-compatible features only |-| Filesystem ops | No FS in browser | Abstract behind traits |--**Approach:** Cargo feature flags in ente-core?--```toml-[features]-default = ["native"]-native = ["libsodium-sys-stable", "rusqlite/bundled"]-wasm = ["getrandom/js"]-```+- Web (wasm-bindgen): `web/packages/wasm/` wraps `ente-core` for web apps.+- Mobile (FRB): `mobile/packages/rust/` wraps `ente-core` for Flutter apps.-### Other notes+## CLI (added in a follow-up PR)-- Never panic across FFI boundary - always return Result or map errors-- Keep binding functions thin - logic belongs in ente-core-- Mobile binary size: LTO + symbol stripping+A Rust CLI lives in `rust/cli/` and will depend on `ente-core`.-## Tests+## Validation + Fuzzing (added in a follow-up PR)-- **ente-core:** Standard `cargo test` - comprehensive unit tests-- **ente_photos_rust:** Minimal FRB smoke test in Dart to catch binding drift-- **ente-wasm:** Vitest tests in web package-- **Golden fixtures:** Share test vectors across native/FRB/WASM for crypto parity+Validation suite + benchmarks (vs libsodium) and fuzz targets will live under:+- `rust/validation/`+- `rust/core/fuzz/`diff --git a/rust/core/README.md b/rust/core/README.mdindex e0e3115a4d..6f5a62f336 100644--- a/rust/core/README.md+++ b/rust/core/README.md@@ -1,10 +1,49 @@+# ente-core+Common Rust code for Ente apps.+## Modules++| Module | Description |+|--------|-------------|+| `crypto` | Cryptographic utilities (pure Rust, libsodium-wire-compatible) |+| `http` | HTTP client for Ente API |+| `urls` | URL construction utilities |++## Crypto++Pure Rust cryptography, byte-compatible with JS/Dart clients.++| Submodule | Algorithm | Use Case |+|-----------|-----------|----------|+| `secretbox` | XSalsa20-Poly1305 | Encrypt keys, small data |+| `blob` | XChaCha20-Poly1305 | Encrypt metadata |+| `stream` | XChaCha20-Poly1305 | Encrypt large files (4MB chunks) |+| `sealed` | X25519 + XSalsa20-Poly1305 | Anonymous public-key encryption |+| `argon` | Argon2id | Password-based key derivation |+| `kdf` | BLAKE2b | Subkey derivation |+| `hash` | BLAKE2b | Cryptographic hashing |+| `keys` | - | Key generation |++### Quick Start++```rust+use ente_core::crypto;++crypto::init().unwrap();++let key = crypto::keys::generate_key();+let encrypted = crypto::secretbox::encrypt(b"Hello", &key).unwrap();+let decrypted = crypto::secretbox::decrypt_box(&encrypted, &key).unwrap();+```++π **[Full Crypto Docs](docs/crypto.md)**+## Development```bash-cargo fmt # format-cargo clippy # lint-cargo build # build-cargo test # test+cargo fmt # format+cargo clippy # lint+cargo build # build+cargo test # test```diff --git a/rust/core/docs/crypto.md b/rust/core/docs/crypto.mdnew file mode 100644index 0000000000..fc2e99738b--- /dev/null+++ b/rust/core/docs/crypto.md@@ -0,0 +1,101 @@+# Crypto Module++Pure Rust cryptographic utilities, wire-compatible with JS/Dart clients.++## Quick Reference++```rust+use ente_core::crypto;++crypto::init().unwrap(); // Optional (no-op for pure Rust)+```++| Task | Module | Example |+|------|--------|---------|+| Encrypt keys/tokens | `secretbox` | `secretbox::encrypt(data, &key)` |+| Encrypt metadata | `blob` | `blob::encrypt(data, &key)` |+| Encrypt files | `stream` | `stream::encrypt_file(&mut src, &mut dst, None)` |+| Anonymous encrypt | `sealed` | `sealed::seal(data, &public_key)` |+| Password β Key | `argon` | `argon::derive_sensitive_key("password")` |+| Master β Subkey | `kdf` | `kdf::derive_login_key(&master_key)` |+| Hash data/files | `hash` | `hash::hash_reader(&mut file, None)` |+| Generate keys | `keys` | `keys::generate_key()` |++## Common Patterns++### Encrypt user data with password+```rust+let derived = argon::derive_sensitive_key("password")?;+let encrypted = secretbox::encrypt(&user_data, &derived.key)?;+// Store: encrypted.encrypted_data, encrypted.nonce, derived.salt+```++### Encrypt a file+```rust+let mut src = File::open("photo.jpg")?;+let mut dst = File::create("photo.enc")?;+let (key, header) = stream::encrypt_file(&mut src, &mut dst, None)?;+// Store key and header for decryption+```++### Encrypt a file with MD5+MD5 is computed over the encrypted output (header excluded).+```rust+let mut src = File::open("photo.jpg")?;+let mut dst = File::create("photo.enc")?;+let (key, header, md5) = stream::encrypt_file_with_md5(&mut src, &mut dst, None)?;+let md5_b64 = crypto::encode_b64(&md5);+```++### Share data with public key+```rust+let sealed = sealed::seal(&secret_data, &recipient_public_key)?;+// Only recipient can open with their secret key+let opened = sealed::open(&sealed, &recipient_pk, &recipient_sk)?;+```++### Derive login key for SRP+```rust+let kek = argon::derive_key("password", &salt, mem_limit, ops_limit)?;+let login_key = kdf::derive_login_key(&kek)?;+```++## Dart β Rust Mapping++| Dart | Rust |+|------|------|+| `encryptSync()` / `decryptSync()` | `secretbox::encrypt()` / `decrypt_box()` |+| `encryptChaCha()` / `decryptChaCha()` | `blob::encrypt()` / `decrypt()` |+| `encryptFile()` / `decryptFile()` | `stream::encrypt_file()` / `decrypt_file()` |+| `encryptFileWithMD5()` | `stream::encrypt_file_with_md5()` |+| `sealSync()` / `openSealSync()` | `sealed::seal()` / `open()` |+| `deriveSensitiveKey()` | `argon::derive_sensitive_key_with_salt_adaptive(password.as_bytes(), &salt)` |+| `deriveInteractiveKey()` | `argon::derive_interactive_key_with_salt(password, &salt)` (`derive_interactive_key` generates salt) |+| `cryptoPwHash()` | `argon::derive_key(password, &salt, mem_limit, ops_limit)` |+| `pwhashMemLimitInteractive` / `pwhashMemLimitSensitive` / `pwhashOpsLimitInteractive` / `pwhashOpsLimitSensitive` | `argon::MEMLIMIT_INTERACTIVE`, `argon::MEMLIMIT_SENSITIVE`, `argon::OPSLIMIT_INTERACTIVE`, `argon::OPSLIMIT_SENSITIVE` |+| `deriveLoginKey()` | `kdf::derive_login_key()` |+| `getHash()` | `hash::hash_reader()` |+| `generateKey()` | `keys::generate_key()` |+| `strToBin()` | `str_to_bin(input)` |+| `base642bin()` / `bin2base64()` | `base642bin(input)` / `bin2base64(input, url_safe)` (`url_safe=false` for standard, `true` for URL-safe) |++## Key Constants++| Constant | Value | Where |+|----------|-------|-------|+| `ENCRYPTION_CHUNK_SIZE` | 4 MB | stream |+| `KEY_BYTES` | 32 | all modules |+| `NONCE_BYTES` | 24 | secretbox |+| `HEADER_BYTES` | 24 | stream/blob |+| `SALT_BYTES` | 16 | argon/keys |+| `MEMLIMIT_INTERACTIVE` | 64 MB | argon |+| `MEMLIMIT_SENSITIVE` | 1 GB | argon |+| `OPSLIMIT_INTERACTIVE` | 2 | argon |+| `OPSLIMIT_SENSITIVE` | 4 | argon |+| `SEAL_OVERHEAD` | 48 | sealed |++## Wire Formats++- **SecretBox**: `MAC (16) || ciphertext`+- **Stream chunk**: `ciphertext (plaintext + 17 bytes with tag embedded)`+- **Sealed**: `ephemeral_pk (32) || MAC (16) || ciphertext`