Skip to content

armgit / ente

Public Imported from GitHub
0

💚 End-to-end encrypted cloud for everything.

Prune ente-core comments

Manav Rathi8c10c3663418
diff --git a/rust/crates/core/Cargo.toml b/rust/crates/core/Cargo.toml
index 5676f88b5f..bafdefe103 100644
--- a/rust/crates/core/Cargo.toml
+++ b/rust/crates/core/Cargo.toml
@@ -38,6 +38,3 @@ gloo-timers = { version = "0.3.0", features = ["futures"] }
[dev-dependencies]
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
mockito.workspace = true
-
-[lints.rust]
-missing_docs = "warn"
diff --git a/rust/crates/core/examples/ping.rs b/rust/crates/core/examples/ping.rs
index 4664e6db15..d9635a4c7f 100644
--- a/rust/crates/core/examples/ping.rs
+++ b/rust/crates/core/examples/ping.rs
@@ -1,9 +1,3 @@
-//! Example: ping the Ente API.
-//!
-//! ```sh
-//! cargo run --example ping -- https://api.ente.com
-//! ```
-
use ente_core::http::{Api, ApiConfig, Http};
#[tokio::main]
diff --git a/rust/crates/core/src/b64.rs b/rust/crates/core/src/b64.rs
index a104d04810..34a51889c1 100644
--- a/rust/crates/core/src/b64.rs
+++ b/rust/crates/core/src/b64.rs
@@ -1,5 +1,3 @@
-//! Base64 encoding and decoding.
-
use base64::{
Engine,
engine::general_purpose::{STANDARD, URL_SAFE, URL_SAFE_NO_PAD},
@@ -7,43 +5,30 @@ use base64::{
pub use base64::DecodeError;
-/// Decode a standard base64 string to bytes, the inverse of [`encode`].
pub fn decode(input: &str) -> Result<Vec<u8>, DecodeError> {
STANDARD.decode(input)
}
-/// Encode bytes to a standard base64 string, the inverse of [`decode`].
-///
-/// Standard base64 (RFC 4648 §4), matching libsodium's
-/// `sodium_base64_VARIANT_ORIGINAL`.
+// Standard base64 (RFC 4648), matching libsodium's
+// `sodium_base64_VARIANT_ORIGINAL`.
pub fn encode(input: &[u8]) -> String {
STANDARD.encode(input)
}
-/// Encode bytes to a URL-safe base64 string.
-///
-/// This uses the URL-safe alphabet (RFC 4648 §5) with padding, matching
-/// libsodium's `sodium_base64_VARIANT_URLSAFE` and Go's `base64.URLEncoding`.
+// The URL-safe alphabet with padding matches libsodium's
+// `sodium_base64_VARIANT_URLSAFE` and Go's `base64.URLEncoding`.
pub fn encode_url_safe(input: &[u8]) -> String {
URL_SAFE.encode(input)
}
-/// Decode a URL-safe base64 string to bytes, the inverse of
-/// [`encode_url_safe`].
pub fn decode_url_safe(input: &str) -> Result<Vec<u8>, DecodeError> {
URL_SAFE.decode(input)
}
-/// Encode bytes to an unpadded URL-safe base64 string.
-///
-/// Like [`encode_url_safe`] but without trailing "=" padding, as required
-/// e.g. when serializing WebAuthn binary values.
pub fn encode_url_safe_no_padding(input: &[u8]) -> String {
URL_SAFE_NO_PAD.encode(input)
}
-/// Decode an unpadded URL-safe base64 string to bytes, the inverse of
-/// [`encode_url_safe_no_padding`].
pub fn decode_url_safe_no_padding(input: &str) -> Result<Vec<u8>, DecodeError> {
URL_SAFE_NO_PAD.decode(input)
}
@@ -68,7 +53,6 @@ mod tests {
#[test]
fn test_url_safe_variants() {
- // 0xfb 0xef exercises the -_ alphabet; 2 bytes forces padding
let bytes = [0xfbu8, 0xef];
assert_eq!(encode_url_safe(&bytes), "--8=");
assert_eq!(encode_url_safe_no_padding(&bytes), "--8");
diff --git a/rust/crates/core/src/crypto/argon.rs b/rust/crates/core/src/crypto/argon.rs
index 97743d5d8f..7d30842bb1 100644
--- a/rust/crates/core/src/crypto/argon.rs
+++ b/rust/crates/core/src/crypto/argon.rs
@@ -1,84 +1,43 @@
-//! Deriving keys from passwords with Argon2id.
-//!
-//! Argon2id stretches a low-entropy, human-chosen password into a key, spending
-//! tunable memory and time to make brute-force guessing expensive. Use it to
-//! turn a passphrase into a key; to derive subkeys from a key that is already
-//! high-entropy, use [`kdf`](super::kdf) instead.
-//!
-//! The same password, salt, and [`Params`] always produce the same key, so the
-//! salt and parameters must be stored alongside the data for other clients to
-//! reproduce it (see [`DerivedKey`]).
-
use std::fmt;
use argon2::{Algorithm, Argon2, Params as Argon2Params, Version};
use crate::crypto::{Error, Key, Result, Salt};
-/// Argon2id cost parameters: how much memory to use and how many passes to make.
-///
-/// Higher values cost an attacker more but also slow legitimate derivation. Use
-/// the presets ([`INTERACTIVE`](Self::INTERACTIVE), [`MODERATE`](Self::MODERATE),
-/// [`SENSITIVE`](Self::SENSITIVE)) unless re-deriving a key with parameters that
-/// were stored alongside it, such as the server's key attributes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Params {
- /// Memory limit in bytes.
pub mem_limit: u32,
- /// Operations (iterations) limit.
pub ops_limit: u32,
}
impl Params {
- /// Parameters for interactive use (64 MiB, 2 ops): fast, for UI
- /// responsiveness.
pub const INTERACTIVE: Self = Self {
mem_limit: 67_108_864,
ops_limit: 2,
};
- /// Parameters for moderate-cost password gates (256 MiB, 3 ops).
pub const MODERATE: Self = Self {
mem_limit: 268_435_456,
ops_limit: 3,
};
- /// Parameters for sensitive keys (1 GiB, 4 ops).
- ///
- /// New sensitive derivations should normally go through
- /// [`derive_sensitive_key`], which adaptively trades memory for ops while
- /// preserving this strength.
pub const SENSITIVE: Self = Self {
mem_limit: 1_073_741_824,
ops_limit: 4,
};
- /// The cheapest parameters Argon2 accepts (8 KiB, 1 op).
- ///
- /// These provide essentially no brute-force protection, and are only for
- /// inputs that are already high-entropy keys (where the KDF is a
- /// formality), never for human-chosen passwords.
+ // Only for inputs that are already high-entropy, never passwords.
pub const MIN: Self = Self {
mem_limit: 8_192,
ops_limit: 1,
};
}
-/// Minimum memory limit for adaptive sensitive derivation (128 MiB).
-///
-/// This matches the server-side floor for accepted account key attributes.
const MEMLIMIT_SENSITIVE_MIN: u32 = 134_217_728;
-/// A key derived from a passphrase, along with the salt and parameters used.
-///
-/// The salt and parameters must be stored alongside the encrypted data: other
-/// clients need them to re-derive the same key.
pub struct DerivedKey {
- /// The derived key.
pub key: Key,
- /// The salt used for derivation.
pub salt: Salt,
- /// The Argon2 parameters used for derivation.
pub params: Params,
}
@@ -92,21 +51,8 @@ impl fmt::Debug for DerivedKey {
}
}
-/// Derive a key from `password` and `salt` with the given Argon2id `params`.
-///
-/// Deterministic: the same inputs always yield the same key, which is how other
-/// clients reproduce it. The result is a [`Key`], zeroized on drop. To make a
-/// new key, the `derive_*_key` helpers choose parameters and a salt for you.
-///
-/// # Errors
-///
-/// Returns
-/// [`InvalidKeyDerivationParams`](Error::InvalidKeyDerivationParams) if
-/// `params` fall below the accepted minimum or memory is not a multiple of 1024
-/// bytes.
-///
-/// Produces the same key as libsodium's `crypto_pwhash` with
-/// `crypto_pwhash_ALG_ARGON2ID13`.
+// Produces the same key as libsodium's `crypto_pwhash` with
+// `crypto_pwhash_ALG_ARGON2ID13`.
pub fn derive_key(password: &str, salt: &Salt, params: Params) -> Result<Key> {
derive_key_impl(password.as_bytes(), salt, params)
}
@@ -135,10 +81,9 @@ fn derive_key_impl(password: &[u8], salt: &Salt, params: Params) -> Result<Key>
)));
}
- // Convert bytes to KiB (Argon2 uses KiB internally)
let m_cost = params.mem_limit / 1024;
let t_cost = params.ops_limit;
- let p_cost = 1; // Parallelism degree
+ let p_cost = 1;
let argon2_params = Argon2Params::new(m_cost, t_cost, p_cost, Some(Key::BYTES))
.map_err(|e| Error::InvalidKeyDerivationParams(e.to_string()))?;
@@ -153,11 +98,6 @@ fn derive_key_impl(password: &[u8], salt: &Salt, params: Params) -> Result<Key>
Ok(Key::from_bytes(key))
}
-/// Derive a key from `password` with [`Params::INTERACTIVE`] and a freshly
-/// generated salt.
-///
-/// Returns the key together with the salt and parameters used, which must be
-/// stored to reproduce it.
pub fn derive_interactive_key(password: &str) -> Result<DerivedKey> {
let salt = Salt::generate();
let key = derive_key(password, &salt, Params::INTERACTIVE)?;
@@ -168,11 +108,6 @@ pub fn derive_interactive_key(password: &str) -> Result<DerivedKey> {
})
}
-/// Derive a key from `password` with [`Params::MODERATE`] and a freshly
-/// generated salt.
-///
-/// Returns the key together with the salt and parameters used, which must be
-/// stored to reproduce it.
pub fn derive_moderate_key(password: &str) -> Result<DerivedKey> {
let salt = Salt::generate();
let key = derive_key(password, &salt, Params::MODERATE)?;
@@ -183,18 +118,6 @@ pub fn derive_moderate_key(password: &str) -> Result<DerivedKey> {
})
}
-/// Derive a high-security key from `password`, adapting the cost to the device.
-///
-/// Aims for [`Params::SENSITIVE`] strength but starts at moderate memory
-/// (256 MiB) with the ops limit scaled up to compensate, then halves memory and
-/// doubles ops whenever allocation fails, down to a 128 MiB floor (the
-/// server-side minimum for accepted account key attributes). Holding the
-/// product of memory and ops constant preserves the work factor while fitting
-/// low-memory devices, and matches the policy used by the web and Flutter
-/// clients so the same account derives consistently everywhere.
-///
-/// Returns the key together with the salt and parameters actually used, which
-/// must be stored to reproduce it.
pub fn derive_sensitive_key(password: &str) -> Result<DerivedKey> {
let salt = Salt::generate();
derive_sensitive_adaptive(password.as_bytes(), &salt)
@@ -230,6 +153,8 @@ fn derive_sensitive_adaptive(password: &[u8], salt: &Salt) -> Result<DerivedKey>
)));
}
+ // The server rejects account key attributes below 128 MiB. Halving memory
+ // and doubling ops matches the web and Flutter fallback policy.
let mut last_error = None;
while mem_limit >= MEMLIMIT_SENSITIVE_MIN {
let params = Params {
@@ -272,8 +197,6 @@ mod tests {
let password = "correct horse battery staple";
let salt = Salt::generate();
- // Just checks the derivation succeeds; determinism and length are
- // covered below (length is in the type).
derive_key(password, &salt, Params::INTERACTIVE).unwrap();
}
diff --git a/rust/crates/core/src/crypto/blob.rs b/rust/crates/core/src/crypto/blob.rs
index f6927d4f2c..fd9e5681c0 100644
--- a/rust/crates/core/src/crypto/blob.rs
+++ b/rust/crates/core/src/crypto/blob.rs
@@ -1,73 +1,26 @@
-//! Authenticated encryption of a single value with XChaCha20-Poly1305.
-//!
-//! A blob is one secretstream message: the data is encrypted and authenticated
-//! in a single shot, without the chunking that [`stream`](super::stream) applies
-//! to large file contents. Ente uses it for the small, bounded values attached
-//! to an object, such as file or collection metadata.
-//! ([`secretbox`](super::secretbox) fills the same single-value role for data
-//! not tied to an object.)
-//!
-//! The construction is libsodium's secretstream
-//! (`crypto_secretstream_xchacha20poly1305`), driven here for a single message
-//! tagged final; the implementation is pure Rust but wire-compatible (recorded
-//! per function below). Unlike a secretbox nonce, the per-message randomness
-//! lives in a `header` that secretstream generates during encryption.
-//!
-//! Two payload shapes are offered, differing only in how the header travels:
-//!
-//! - Split ([`encrypt`] / [`decrypt`]): the ciphertext and the decryption
-//! header are returned separately.
-//!
-//! - Combined ([`encrypt_combined`] / [`decrypt_combined`]): the header is
-//! prepended to the ciphertext to form one self-contained buffer
-//! (`header ‖ ciphertext`).
-
use super::stream::{Decryptor, Encryptor};
use crate::crypto::{Error, Header, Key, Result};
-/// Size of the encryption key in bytes.
pub const KEY_BYTES: usize = Key::BYTES;
-/// Size of the decryption header in bytes.
pub const HEADER_BYTES: usize = Header::BYTES;
-/// Overhead (tag + MAC) added to the plaintext by encryption.
pub use super::stream::ABYTES;
-/// A blob ciphertext together with the header needed to open it, as returned by
-/// [`encrypt`].
-///
-/// This is the split shape, with the header held separately from the
-/// ciphertext; see the module docs for the combined alternative.
#[derive(Debug, Clone)]
pub struct EncryptedBlob {
- /// The encrypted data: one secretstream message, [`ABYTES`] bytes longer
- /// than the plaintext.
pub encrypted_data: Vec<u8>,
- /// The header that secretstream produced while encrypting. Needed to
- /// decrypt, and not secret.
pub decryption_header: Header,
}
impl EncryptedBlob {
- /// Decrypt this blob with `key`, returning the plaintext.
- ///
- /// A convenience wrapper over [`decrypt`] using the stored ciphertext and
- /// header; see it for the error cases.
pub fn decrypt(&self, key: &Key) -> Result<Vec<u8>> {
decrypt(&self.encrypted_data, &self.decryption_header, key)
}
}
-/// Encrypt `data` with `key` as a single secretstream message.
-///
-/// A fresh header is generated for every call. The message is tagged final, so
-/// [`decrypt`] can later confirm the ciphertext is complete. Returns the
-/// ciphertext and that header; decrypt with [`decrypt`] or
-/// [`EncryptedBlob::decrypt`].
-///
-/// Wire-compatible with libsodium's secretstream, as one message tagged
-/// `TAG_FINAL` (`crypto_secretstream_xchacha20poly1305`).
+// Wire-compatible with libsodium's secretstream as one message tagged
+// `TAG_FINAL`.
pub fn encrypt(data: &[u8], key: &Key) -> Result<EncryptedBlob> {
let mut encryptor = Encryptor::new(key);
let decryption_header = *encryptor.header();
@@ -79,23 +32,7 @@ pub fn encrypt(data: &[u8], key: &Key) -> Result<EncryptedBlob> {
})
}
-/// Decrypt a blob produced by [`encrypt`], using its `header` and `key`.
-///
-/// The message must carry the secretstream final tag, which proves it was not
-/// truncated; its Poly1305 MAC proves it was not otherwise altered. Data
-/// written by older clients without the final tag is rejected here; use
-/// [`decrypt_legacy`] for it.
-///
-/// # Errors
-///
-/// Returns [`CiphertextTooShort`](Error::CiphertextTooShort) if `data` is
-/// smaller than the per-message overhead,
-/// [`StreamTruncated`](Error::StreamTruncated) if the final tag is absent,
-/// or [`StreamPullFailed`](Error::StreamPullFailed) if the MAC does not
-/// verify, which happens when the key or header is wrong or the data was
-/// tampered with.
-///
-/// Wire-compatible with libsodium's `crypto_secretstream_xchacha20poly1305`.
+// Wire-compatible with libsodium's `crypto_secretstream_xchacha20poly1305`.
pub fn decrypt(data: &[u8], header: &Header, key: &Key) -> Result<Vec<u8>> {
let (plaintext, is_final) = decrypt_impl(data, header, key)?;
if !is_final {
@@ -104,21 +41,7 @@ pub fn decrypt(data: &[u8], header: &Header, key: &Key) -> Result<Vec<u8>> {
Ok(plaintext)
}
-/// Decrypt a blob that might be missing the secretstream final tag.
-///
-/// Same as [`decrypt`], but it doesn't require the final tag, so it can't tell
-/// whether the blob was cut short. The MAC still guarantees that whatever it
-/// returns wasn't tampered with. Use this only to read old data written without
-/// the tag; use [`decrypt`] everywhere else.
-///
-/// Affected blobs: Auth's authenticator entities, pre Nov-2025. Locker also
-/// briefly did this, but only in internal builds pre-launch; no public Locker
-/// release was affected.
-///
-/// # Errors
-///
-/// Same as [`decrypt`], except it never returns
-/// [`StreamTruncated`](Error::StreamTruncated).
+// Pre-November 2025 Auth authenticator entities may omit the final tag.
pub fn decrypt_legacy(data: &[u8], header: &Header, key: &Key) -> Result<Vec<u8>> {
Ok(decrypt_impl(data, header, key)?.0)
}
@@ -135,15 +58,8 @@ fn decrypt_impl(data: &[u8], header: &Header, key: &Key) -> Result<(Vec<u8>, boo
decryptor.pull(data)
}
-/// Encrypt `data` with `key` into one self-contained buffer.
-///
-/// Like [`encrypt`], but prepends the decryption header to the ciphertext,
-/// returning `header ‖ ciphertext`: everything needed to decrypt except the
-/// key. Prefer this when a single opaque blob is easier to store or pass around
-/// than a separate ciphertext and header. Decrypt with [`decrypt_combined`].
-///
-/// Wire-compatible with libsodium's secretstream, storing the header ahead of
-/// the single message.
+// Wire-compatible with libsodium's secretstream, with the header stored before
+// the single message.
pub fn encrypt_combined(data: &[u8], key: &Key) -> Result<Vec<u8>> {
let encrypted = encrypt(data, key)?;
let mut combined = Vec::with_capacity(Header::BYTES + encrypted.encrypted_data.len());
@@ -152,16 +68,6 @@ pub fn encrypt_combined(data: &[u8], key: &Key) -> Result<Vec<u8>> {
Ok(combined)
}
-/// Decrypt a combined buffer produced by [`encrypt_combined`].
-///
-/// Splits the leading header from the ciphertext, then decrypts as [`decrypt`]
-/// does.
-///
-/// # Errors
-///
-/// Returns [`CiphertextTooShort`](Error::CiphertextTooShort) if `data` is
-/// too short to hold a header and one message, otherwise the same errors as
-/// [`decrypt`].
pub fn decrypt_combined(data: &[u8], key: &Key) -> Result<Vec<u8>> {
if data.len() < Header::BYTES + ABYTES {
return Err(Error::CiphertextTooShort {
@@ -174,37 +80,24 @@ pub fn decrypt_combined(data: &[u8], key: &Key) -> Result<Vec<u8>> {
decrypt(ciphertext, &Header::try_from_slice(header)?, key)
}
-/// Serialize `value` to JSON and encrypt it as a blob.
-///
-/// The inverse is [`decrypt_json`].
pub fn encrypt_json<T: serde::Serialize>(value: &T, key: &Key) -> Result<EncryptedBlob> {
let json = serde_json::to_vec(value)
.map_err(|e| Error::Json(format!("JSON serialization failed: {}", e)))?;
encrypt(&json, key)
}
-/// Serialize `value` to JSON and encrypt it into one combined buffer.
-///
-/// Like [`encrypt_json`] but using [`encrypt_combined`]; the inverse is
-/// [`decrypt_json_combined`].
pub fn encrypt_json_combined<T: serde::Serialize>(value: &T, key: &Key) -> Result<Vec<u8>> {
let json = serde_json::to_vec(value)
.map_err(|e| Error::Json(format!("JSON serialization failed: {}", e)))?;
encrypt_combined(&json, key)
}
-/// Decrypt a blob and deserialize its plaintext from JSON into `T`.
-///
-/// The inverse of [`encrypt_json`].
pub fn decrypt_json<T: serde::de::DeserializeOwned>(blob: &EncryptedBlob, key: &Key) -> Result<T> {
let plaintext = blob.decrypt(key)?;
serde_json::from_slice(&plaintext)
.map_err(|e| Error::Json(format!("JSON deserialization failed: {}", e)))
}
-/// Decrypt a combined buffer and deserialize its plaintext from JSON into `T`.
-///
-/// The inverse of [`encrypt_json_combined`].
pub fn decrypt_json_combined<T: serde::de::DeserializeOwned>(
combined: &[u8],
key: &Key,
@@ -257,7 +150,7 @@ mod tests {
#[test]
fn test_encrypt_decrypt_large() {
let key = Key::generate();
- let plaintext = vec![0x42u8; 1024 * 1024]; // 1 MB
+ let plaintext = vec![0x42u8; 1024 * 1024];
let encrypted = encrypt(&plaintext, &key).unwrap();
assert_eq!(encrypted.decrypt(&key).unwrap(), plaintext);
@@ -349,7 +242,6 @@ mod tests {
)
.unwrap();
- // Decrypt into a mismatched type; should be Error::Json
let result: std::result::Result<Different, _> = decrypt_json(&encrypted, &key);
assert!(
matches!(result, Err(Error::Json(_))),
@@ -405,7 +297,6 @@ mod tests {
let encrypted1 = encrypt(plaintext, &key).unwrap();
let encrypted2 = encrypt(plaintext, &key).unwrap();
- // Different headers (random) -> different ciphertexts
assert_ne!(encrypted1.decryption_header, encrypted2.decryption_header);
assert_ne!(encrypted1.encrypted_data, encrypted2.encrypted_data);
diff --git a/rust/crates/core/src/crypto/error.rs b/rust/crates/core/src/crypto/error.rs
index cc490c5f82..c6c2d15174 100644
--- a/rust/crates/core/src/crypto/error.rs
+++ b/rust/crates/core/src/crypto/error.rs
@@ -1,127 +1,73 @@
-//! The error type shared by the crypto module.
-
use thiserror::Error;
-/// An error from a cryptographic operation.
-///
-/// Each variant is returned by the operations documented to produce it.
-/// [`code`](Self::code) maps a variant to a stable string identifier that
-/// bindings forward to non-Rust callers.
#[derive(Error, Debug)]
pub enum Error {
- /// Invalid key length.
#[error("Invalid key length: expected {expected}, got {actual}")]
- InvalidKeyLength {
- /// Expected length.
- expected: usize,
- /// Actual length.
- actual: usize,
- },
-
- /// Invalid nonce length.
+ InvalidKeyLength { expected: usize, actual: usize },
+
#[error("Invalid nonce length: expected {expected}, got {actual}")]
- InvalidNonceLength {
- /// Expected length.
- expected: usize,
- /// Actual length.
- actual: usize,
- },
-
- /// Invalid salt length.
+ InvalidNonceLength { expected: usize, actual: usize },
+
#[error("Invalid salt length: expected {expected}, got {actual}")]
- InvalidSaltLength {
- /// Expected length.
- expected: usize,
- /// Actual length.
- actual: usize,
- },
-
- /// Invalid header length.
+ InvalidSaltLength { expected: usize, actual: usize },
+
#[error("Invalid header length: expected {expected}, got {actual}")]
- InvalidHeaderLength {
- /// Expected length.
- expected: usize,
- /// Actual length.
- actual: usize,
- },
-
- /// Ciphertext too short.
+ InvalidHeaderLength { expected: usize, actual: usize },
+
#[error("Ciphertext too short: minimum {minimum}, got {actual}")]
- CiphertextTooShort {
- /// Minimum required length.
- minimum: usize,
- /// Actual length.
- actual: usize,
- },
-
- /// Invalid memory or operation limits for key derivation.
+ CiphertextTooShort { minimum: usize, actual: usize },
+
#[error("Invalid key derivation parameters: {0}")]
InvalidKeyDerivationParams(String),
- /// Key derivation failed.
#[error("Key derivation failed")]
KeyDerivationFailed,
- /// Encryption failed.
#[error("Encryption failed")]
EncryptionFailed,
- /// Decryption failed.
#[error("Decryption failed")]
DecryptionFailed,
- /// Stream initialization failed.
#[error("Stream initialization failed")]
StreamInitFailed,
- /// Stream push (encrypt) failed.
#[error("Stream push failed")]
StreamPushFailed,
- /// Stream pull (decrypt) failed.
#[error("Stream pull failed")]
StreamPullFailed,
- /// Stream was truncated (EOF before final tag).
#[error("Stream truncated: EOF before final tag")]
StreamTruncated,
- /// Stream had trailing ciphertext after the final tag.
#[error("Stream has trailing data after final tag")]
StreamTrailingData,
- /// Sealed box open failed.
#[error("Sealed box open failed")]
SealedBoxOpenFailed,
- /// Invalid public key (e.g., small-order point).
#[error("Invalid public key")]
InvalidPublicKey,
- /// JSON serialization or deserialization failed.
#[error("JSON error: {0}")]
Json(String),
- /// Argon2 error.
#[error("Argon2 error: {0:?}")]
Argon2(argon2::Error),
- /// AEAD error.
#[error("AEAD error")]
Aead,
- /// Array conversion error.
#[error("Array conversion error")]
ArrayConversion,
- /// IO error.
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
}
impl Error {
- /// A stable, machine-readable identifier for this error, suitable for
- /// programmatic matching (e.g. `"invalid_key_length"`).
+ // Bindings expose these strings to non-Rust callers.
pub fn code(&self) -> &'static str {
match self {
Error::InvalidKeyLength { .. } => "invalid_key_length",
@@ -149,7 +95,6 @@ impl Error {
}
}
-/// Result type for crypto operations.
pub type Result<T> = std::result::Result<T, Error>;
impl From<std::array::TryFromSliceError> for Error {
diff --git a/rust/crates/core/src/crypto/hash.rs b/rust/crates/core/src/crypto/hash.rs
index e441bf72de..bf3b816367 100644
--- a/rust/crates/core/src/crypto/hash.rs
+++ b/rust/crates/core/src/crypto/hash.rs
@@ -1,48 +1,24 @@
-//! Cryptographic hashing with BLAKE2b.
-//!
-//! BLAKE2b maps data of any length to a fixed-size digest (16 to 64 bytes, 32
-//! by default). Supplying a key turns it into a MAC. Hashing is available
-//! one-shot ([`hash`]), incrementally for data that arrives in pieces
-//! ([`HashState`]), or straight from a reader ([`hash_reader`]).
-//!
-//! The construction is libsodium's `crypto_generichash`; the implementation
-//! here wraps the pure-Rust `blake2b_simd` crate and produces the same digests.
+// This BLAKE2b implementation produces the same digests as libsodium's
+// `crypto_generichash`.
use blake2b_simd::{Params as Blake2bParams, State as Blake2bState};
use std::io::Read;
use crate::crypto::{Error, Result};
-/// Minimum hash output length in bytes.
pub const HASH_BYTES_MIN: usize = 16;
-/// Maximum hash output length in bytes.
pub const HASH_BYTES_MAX: usize = 64;
-/// Default hash output length (libsodium default is 32 bytes).
+// Libsodium's default hash output length is 32 bytes.
pub const HASH_BYTES: usize = 32;
-/// Hash chunk size for streaming (4 MB).
pub const HASH_CHUNK_SIZE: usize = 4 * 1024 * 1024;
-/// Minimum key length in bytes for keyed hashing.
pub const KEY_BYTES_MIN: usize = 16;
-/// Maximum key length in bytes for keyed hashing.
pub const KEY_BYTES_MAX: usize = 64;
-/// Hash `data` with BLAKE2b.
-///
-/// `out_len` chooses the digest length (16 to 64 bytes), defaulting to 32.
-/// Passing a `key` of 16 to 64 bytes computes a keyed hash (a MAC); `None` or
-/// an empty key hashes without one.
-///
-/// # Errors
-///
-/// Returns [`InvalidKeyLength`](Error::InvalidKeyLength) if `out_len` is
-/// outside 16 to 64 bytes, or if a non-empty `key` is outside that range.
-///
-/// Produces the same digest as libsodium's `crypto_generichash`.
pub fn hash(data: &[u8], out_len: Option<usize>, key: Option<&[u8]>) -> Result<Vec<u8>> {
let out_len = out_len.unwrap_or(HASH_BYTES);
@@ -57,7 +33,7 @@ pub fn hash(data: &[u8], out_len: Option<usize>, key: Option<&[u8]>) -> Result<V
params.hash_length(out_len);
if let Some(k) = key {
- // libsodium: key must be 0 OR 16-64 bytes
+ // Libsodium accepts an empty key or 16-64 bytes.
if !k.is_empty() && (k.len() < KEY_BYTES_MIN || k.len() > KEY_BYTES_MAX) {
return Err(Error::InvalidKeyLength {
expected: KEY_BYTES_MAX,
@@ -73,33 +49,16 @@ pub fn hash(data: &[u8], out_len: Option<usize>, key: Option<&[u8]>) -> Result<V
Ok(hash.as_bytes()[..out_len].to_vec())
}
-/// Hash `data` with BLAKE2b using the defaults: a 32-byte digest and no key.
-///
-/// Shorthand for [`hash`] with `out_len` 32 and no key.
pub fn hash_default(data: &[u8]) -> Result<Vec<u8>> {
hash(data, Some(HASH_BYTES), None)
}
-/// Incremental BLAKE2b hasher, for data that arrives in pieces.
-///
-/// Build it with [`new`](Self::new), feed chunks with [`update`](Self::update),
-/// and produce the digest with [`finalize`](Self::finalize). The result is
-/// identical to passing the concatenation of the chunks to [`hash`], so a large
-/// input can be hashed without holding it all in memory.
pub struct HashState {
state: Blake2bState,
out_len: usize,
}
impl HashState {
- /// Create a hasher with the given digest length and optional key.
- ///
- /// `out_len` and `key` follow the same rules and defaults as [`hash`].
- ///
- /// # Errors
- ///
- /// Returns [`InvalidKeyLength`](Error::InvalidKeyLength) if `out_len`
- /// or a non-empty `key` is outside 16 to 64 bytes.
pub fn new(out_len: Option<usize>, key: Option<&[u8]>) -> Result<Self> {
let out_len = out_len.unwrap_or(HASH_BYTES);
@@ -114,7 +73,7 @@ impl HashState {
params.hash_length(out_len);
if let Some(k) = key {
- // libsodium: key must be 0 OR 16-64 bytes
+ // Libsodium accepts an empty key or 16-64 bytes.
if !k.is_empty() && (k.len() < KEY_BYTES_MIN || k.len() > KEY_BYTES_MAX) {
return Err(Error::InvalidKeyLength {
expected: KEY_BYTES_MAX,
@@ -131,34 +90,21 @@ impl HashState {
Ok(HashState { state, out_len })
}
- /// Feed more data into the hash.
pub fn update(&mut self, data: &[u8]) -> Result<()> {
self.state.update(data);
Ok(())
}
- /// Consume the hasher and return the digest, of the configured length.
pub fn finalize(self) -> Result<Vec<u8>> {
let hash = self.state.finalize();
Ok(hash.as_bytes()[..self.out_len].to_vec())
}
}
-/// Create an incremental [`HashState`] with the defaults: a 32-byte digest and
-/// no key.
pub fn hash_state_new() -> Result<HashState> {
HashState::new(Some(HASH_BYTES), None)
}
-/// Hash everything from `reader` with BLAKE2b.
-///
-/// Reads to EOF, hashing as it goes, so the source is never fully held in
-/// memory. `out_len` is the digest length (16 to 64 bytes, default 32).
-///
-/// # Errors
-///
-/// Returns [`InvalidKeyLength`](Error::InvalidKeyLength) if `out_len` is
-/// out of range, or an [`Io`](Error::Io) error if the reader fails.
pub fn hash_reader<R: Read>(reader: &mut R, out_len: Option<usize>) -> Result<Vec<u8>> {
let mut state = HashState::new(out_len, None)?;
let mut buffer = vec![0u8; 4096];
@@ -189,7 +135,6 @@ mod tests {
fn test_hash_with_length() {
let data = b"Test data";
- // Test various output lengths
for &len in &[16, 32, 48, 64] {
let hash = hash(data, Some(len), None).unwrap();
assert_eq!(hash.len(), len);
@@ -223,7 +168,6 @@ mod tests {
let hash1 = hash(data, Some(64), Some(&key)).unwrap();
let hash2 = hash(data, Some(64), None).unwrap();
- // Keyed and unkeyed hashes should be different
assert_ne!(hash1, hash2);
}
@@ -252,7 +196,7 @@ mod tests {
#[test]
fn test_invalid_key_length() {
let data = b"Test";
- let bad_key = vec![0u8; 8]; // Too short
+ let bad_key = vec![0u8; 8];
let result = hash(data, Some(64), Some(&bad_key));
assert!(result.is_err());
@@ -262,12 +206,10 @@ mod tests {
fn test_key_min_max_length() {
let data = b"Test";
- // Min length should work
let key_min = vec![0u8; KEY_BYTES_MIN];
let hash1 = hash(data, Some(64), Some(&key_min)).unwrap();
assert_eq!(hash1.len(), 64);
- // Max length should work
let key_max = vec![0u8; KEY_BYTES_MAX];
let hash2 = hash(data, Some(64), Some(&key_max)).unwrap();
assert_eq!(hash2.len(), 64);
@@ -282,7 +224,7 @@ mod tests {
#[test]
fn test_large_data() {
- let data = vec![0x42u8; 1024 * 1024]; // 1 MB
+ let data = vec![0x42u8; 1024 * 1024];
let hash = hash_default(&data).unwrap();
assert_eq!(hash.len(), HASH_BYTES);
}
@@ -290,19 +232,17 @@ mod tests {
#[test]
fn test_avalanche_effect() {
let data1 = b"Test";
- let data2 = b"Test "; // One extra space
+ let data2 = b"Test ";
let hash1 = hash_default(data1).unwrap();
let hash2 = hash_default(data2).unwrap();
- // Count differing bytes
let diff_count = hash1
.iter()
.zip(hash2.iter())
.filter(|(a, b)| a != b)
.count();
- // Should have significant differences (avalanche effect)
- assert!(diff_count > 15); // Expect ~50% different
+ assert!(diff_count > 15);
}
}
diff --git a/rust/crates/core/src/crypto/kdf.rs b/rust/crates/core/src/crypto/kdf.rs
index c26277560d..f04dd54d04 100644
--- a/rust/crates/core/src/crypto/kdf.rs
+++ b/rust/crates/core/src/crypto/kdf.rs
@@ -1,62 +1,22 @@
-//! Deriving independent subkeys from a high-entropy key, with BLAKE2b.
-//!
-//! Given one high-entropy key, this produces subkeys such that knowing a
-//! derived subkey reveals nothing about the parent key or its sibling subkeys.
-//! Each subkey is selected by a numeric id and an 8-byte context, so a single
-//! parent key can safely key many separate purposes.
-//!
-//! Unlike [`argon`](super::argon), the input must already be high-entropy (a
-//! key, not a password): this is fast keyed hashing, not password stretching.
-//!
-//! The construction is libsodium's `crypto_kdf_derive_from_key`; this pure-Rust
-//! implementation derives the same subkeys.
-
use blake2b_simd::Params as Blake2bParams;
use crate::crypto::{Key, Result, SecretVec};
-/// Size of KDF context in bytes.
pub const CONTEXT_BYTES: usize = 8;
-/// Size of master key in bytes.
pub const KEY_BYTES: usize = Key::BYTES;
-/// Minimum subkey length in bytes.
pub const SUBKEY_BYTES_MIN: usize = 16;
-/// Maximum subkey length in bytes.
pub const SUBKEY_BYTES_MAX: usize = 64;
-/// Login subkey length in bytes (used by derive_login_key).
pub const LOGIN_SUBKEY_LEN: usize = 32;
-/// Login subkey ID (used by derive_login_key).
pub const LOGIN_SUBKEY_ID: u64 = 1;
-/// Login subkey context (used by derive_login_key).
pub const LOGIN_SUBKEY_CONTEXT: &[u8; CONTEXT_BYTES] = b"loginctx";
-/// Derive a `subkey_len`-byte subkey of `key`, selected by `subkey_id` and
-/// `context`.
-///
-/// `subkey_id` and `context` together name the subkey: the same `key` yields
-/// independent subkeys for different ids or contexts, so `context` acts as a
-/// domain separator (conventionally a short, fixed application label).
-/// `subkey_len` must be between 16 and 64 bytes. The result is a [`SecretVec`],
-/// zeroized on drop.
-///
-/// # Wire format
-///
-/// BLAKE2b keyed with `key`, salt `subkey_id` (8 bytes little-endian followed
-/// by 8 zero bytes), personalization `context` (8 bytes followed by 8 zero
-/// bytes).
-///
-/// # Errors
-///
-/// Returns [`InvalidKeyLength`](crate::crypto::Error::InvalidKeyLength) if
-/// `subkey_len` is outside 16 to 64 bytes.
-///
-/// Produces the same subkey as libsodium's `crypto_kdf_derive_from_key`.
+// Produces the same subkey as libsodium's `crypto_kdf_derive_from_key`.
pub fn derive_subkey(
key: &Key,
subkey_len: usize,
@@ -70,11 +30,12 @@ pub fn derive_subkey(
});
}
- // Build salt: subkey_id (8 bytes LE) || zeros (8 bytes)
+ // Match libsodium's salt and personalization layout exactly.
+ // Salt: subkey_id (8 bytes LE) || zeros (8 bytes).
let mut salt = [0u8; 16];
salt[0..8].copy_from_slice(&subkey_id.to_le_bytes());
- // Build personal: context (8 bytes) || zeros (8 bytes)
+ // Personalization: context (8 bytes) || zeros (8 bytes).
let mut personal = [0u8; 16];
personal[0..CONTEXT_BYTES].copy_from_slice(context);
@@ -89,12 +50,6 @@ pub fn derive_subkey(
Ok(SecretVec::new(hash.as_bytes()[..subkey_len].to_vec()))
}
-/// Derive the SRP login key from the user's master key.
-///
-/// A fixed specialization of [`derive_subkey`]: the first 16 bytes of the
-/// 32-byte subkey with id 1 and context `loginctx`. The login key is what the
-/// client proves knowledge of during SRP authentication, which keeps the master
-/// key itself off the wire. The result is a [`SecretVec`], zeroized on drop.
pub fn derive_login_key(master_key: &Key) -> SecretVec {
let subkey = derive_subkey(
master_key,
@@ -169,7 +124,6 @@ mod tests {
let login_key = derive_login_key(&test_key());
let subkey = derive_subkey(&test_key(), 32, 1, b"loginctx").unwrap();
- // Login key should be first 16 bytes of subkey
assert_eq!(login_key.as_ref(), &subkey[..16]);
}
diff --git a/rust/crates/core/src/crypto/mod.rs b/rust/crates/core/src/crypto/mod.rs
index ae9af40825..bfd9698944 100644
--- a/rust/crates/core/src/crypto/mod.rs
+++ b/rust/crates/core/src/crypto/mod.rs
@@ -1,46 +1,3 @@
-//! Cryptographic primitives for Ente.
-//!
-//! This module provides all the cryptographic primitives used by Ente clients.
-//!
-//! # Implementation
-//!
-//! Every primitive is implemented in pure Rust, with no libsodium or other C
-//! dependency, drawing on established crates such as those from the RustCrypto
-//! project, `blake2b_simd`, and `crypto_secretstream`. All of them keep
-//! byte-for-byte wire compatibility with libsodium, so keys and ciphertext
-//! interoperate with the existing mobile and web clients.
-//!
-//! # Overview
-//!
-//! Authenticated encryption:
-//! - [`secretbox`] - a single small, independent value
-//! - [`blob`] - a single value attached to an Ente object, such as metadata
-//! - [`stream`] - file contents of any size, encrypted in chunks
-//!
-//! Public-key:
-//! - [`sealed`] - anonymous encryption to a recipient's public key
-//!
-//! Key derivation and hashing:
-//! - [`argon`] - derive a key from a password (Argon2id)
-//! - [`kdf`] - derive subkeys from a high-entropy key (BLAKE2b)
-//! - [`hash`] - BLAKE2b hashing
-//!
-//! Key material is typed ([`Key`], [`Nonce`], [`Salt`], [`Header`],
-//! [`PublicKey`], [`SecretKey`]), with lengths validated at construction, and
-//! secrets are held in zeroizing [`SecretVec`] / [`SecretString`].
-//!
-//! # Example
-//!
-//! ```rust
-//! use ente_core::crypto::{Key, secretbox};
-//!
-//! let key = Key::generate();
-//! let encrypted = secretbox::encrypt(b"a secret", &key);
-//!
-//! let decrypted = encrypted.decrypt(&key).unwrap();
-//! assert_eq!(decrypted, b"a secret");
-//! ```
-
mod error;
mod secret;
mod types;
diff --git a/rust/crates/core/src/crypto/sealed.rs b/rust/crates/core/src/crypto/sealed.rs
index 5fc6e5eac5..491457aa71 100644
--- a/rust/crates/core/src/crypto/sealed.rs
+++ b/rust/crates/core/src/crypto/sealed.rs
@@ -1,23 +1,3 @@
-//! Anonymous public-key encryption (sealed boxes).
-//!
-//! A sealed box lets anyone encrypt a message to a recipient's public key so
-//! that only the holder of the matching secret key can read it, while the
-//! recipient learns nothing about who sent it. Each message uses a fresh
-//! ephemeral key pair whose public half is included in the output; the
-//! ephemeral secret is discarded, so even the sender cannot decrypt afterwards.
-//!
-//! The construction is libsodium's `crypto_box_seal`; the implementation here
-//! is pure Rust but wire-compatible (recorded per function below).
-//!
-//! # Wire format
-//!
-//! `ephemeral_pk (32 bytes) ‖ MAC (16 bytes) ‖ ciphertext`, where:
-//!
-//! - the nonce is `BLAKE2b-24(ephemeral_pk ‖ recipient_pk)`,
-//! - the shared secret is `X25519(ephemeral_sk, recipient_pk)`,
-//! - the symmetric key is `HSalsa20(shared_secret, zero_nonce)`, and
-//! - the body is the `MAC ‖ ciphertext` of XSalsa20-Poly1305.
-
use blake2b_simd::Params as Blake2bParams;
use rand_core::{OsRng, RngCore};
use salsa20::hsalsa;
@@ -30,18 +10,12 @@ use zeroize::Zeroize;
use crate::crypto::{Error, PublicKey, Result, SecretKey};
-/// Size of a public key in bytes.
pub const PUBLIC_KEY_BYTES: usize = PublicKey::BYTES;
-/// Size of a secret key in bytes.
pub const SECRET_KEY_BYTES: usize = SecretKey::BYTES;
-/// Overhead added by sealing (ephemeral_pk + MAC).
pub const SEAL_OVERHEAD: usize = 32 + 16;
-/// Derive nonce from ephemeral and recipient public keys.
-///
-/// Nonce = BLAKE2b-24(ephemeral_pk || recipient_pk)
fn seal_nonce(ephemeral_pk: &[u8; 32], recipient_pk: &[u8; 32]) -> [u8; 24] {
let hash = Blake2bParams::new()
.hash_length(24)
@@ -55,71 +29,45 @@ fn seal_nonce(ephemeral_pk: &[u8; 32], recipient_pk: &[u8; 32]) -> [u8; 24] {
nonce
}
-/// Derive crypto_box key from X25519 shared secret.
-///
-/// Key = HSalsa20(shared_secret, zero_nonce)
fn derive_box_key(shared_secret: &[u8; 32]) -> [u8; 32] {
use salsa20::cipher::consts::U10;
let zero_nonce = [0u8; 16];
- // HSalsa20 core function with 20 rounds (U10 * 2)
+ // U10 runs the 20 rounds required by libsodium's crypto_box construction.
let result = hsalsa::<U10>(shared_secret.into(), (&zero_nonce).into());
result.into()
}
-/// Check if shared secret is contributory (not all zeros).
-///
-/// This prevents attacks using small-order points.
-/// Uses constant-time comparison to avoid leaking information about the
-/// shared secret through timing.
fn is_contributory(shared_secret: &[u8; 32]) -> bool {
shared_secret.ct_ne(&[0u8; 32]).into()
}
-/// Encrypt `plaintext` so that only the holder of `recipient_pk`'s secret key
-/// can read it.
-///
-/// A fresh ephemeral key pair is generated per call and its secret discarded,
-/// so the output carries no sender identity and the sender cannot decrypt it
-/// afterwards. Open it with [`open`].
-///
-/// # Errors
-///
-/// Returns [`InvalidPublicKey`](Error::InvalidPublicKey) if `recipient_pk`
-/// is a low-order point, which would make the X25519 exchange yield an all-zero
-/// shared secret and provide no security.
-///
-/// Returns `ephemeral_pk ‖ MAC ‖ ciphertext`, wire-compatible with libsodium's
-/// `crypto_box_seal`.
+// Returns `ephemeral_pk || MAC || ciphertext`, wire-compatible with libsodium's
+// `crypto_box_seal`.
pub fn seal(plaintext: &[u8], recipient_pk: &PublicKey) -> Result<Vec<u8>> {
let recipient_pk_arr: [u8; 32] = *recipient_pk.as_bytes();
let recipient_pk_point = x25519_dalek::PublicKey::from(recipient_pk_arr);
- // Generate ephemeral keypair
let mut ephemeral_secret_bytes = [0u8; 32];
OsRng.fill_bytes(&mut ephemeral_secret_bytes);
let ephemeral_secret = StaticSecret::from(ephemeral_secret_bytes);
let ephemeral_public = x25519_dalek::PublicKey::from(&ephemeral_secret);
- // Compute shared secret
let shared_secret = ephemeral_secret.diffie_hellman(&recipient_pk_point);
- // SECURITY: Reject non-contributory (small-order point)
+ // Reject small-order points that produce an all-zero shared secret.
if !is_contributory(shared_secret.as_bytes()) {
ephemeral_secret_bytes.zeroize();
return Err(Error::InvalidPublicKey);
}
- // Derive encryption key
let mut box_key = derive_box_key(shared_secret.as_bytes());
- // Compute nonce
let nonce = seal_nonce(ephemeral_public.as_bytes(), &recipient_pk_arr);
- // Encrypt with XSalsa20-Poly1305
- // RustCrypto outputs: MAC || ciphertext (same as libsodium)
+ // RustCrypto and libsodium both encode this as MAC || ciphertext.
let cipher = XSalsa20Poly1305::new(GenericArray::from_slice(&box_key));
let encrypted = cipher
.encrypt(GenericArray::from_slice(&nonce), plaintext)
@@ -128,33 +76,17 @@ pub fn seal(plaintext: &[u8], recipient_pk: &PublicKey) -> Result<Vec<u8>> {
Error::EncryptionFailed
})?;
- // Build output: ephemeral_pk || MAC || ciphertext
let mut result = Vec::with_capacity(32 + encrypted.len());
result.extend_from_slice(ephemeral_public.as_bytes());
result.extend_from_slice(&encrypted);
- // Clean up sensitive data
ephemeral_secret_bytes.zeroize();
box_key.zeroize();
Ok(result)
}
-/// Decrypt a sealed box addressed to `recipient_pk` / `recipient_sk`.
-///
-/// `ciphertext` is the `ephemeral_pk ‖ MAC ‖ ciphertext` produced by [`seal`].
-/// Both halves of the recipient key pair are needed: the secret key performs
-/// the X25519 exchange, and the public key reconstructs the nonce.
-///
-/// # Errors
-///
-/// Returns [`CiphertextTooShort`](Error::CiphertextTooShort) if
-/// `ciphertext` is smaller than [`SEAL_OVERHEAD`],
-/// [`InvalidPublicKey`](Error::InvalidPublicKey) if the embedded ephemeral
-/// key is low-order, or [`DecryptionFailed`](Error::DecryptionFailed) if
-/// the MAC does not verify, which happens with the wrong key pair or tampering.
-///
-/// Wire-compatible with libsodium's `crypto_box_seal_open`.
+// Wire-compatible with libsodium's `crypto_box_seal_open`.
pub fn open(
ciphertext: &[u8],
recipient_pk: &PublicKey,
@@ -167,31 +99,26 @@ pub fn open(
});
}
- // Parse: ephemeral_pk (32) || MAC (16) || ciphertext
let ephemeral_pk_bytes: [u8; 32] = ciphertext[..32]
.try_into()
.map_err(|_| Error::ArrayConversion)?;
- let encrypted = &ciphertext[32..]; // MAC || ciphertext
+ let encrypted = &ciphertext[32..];
let ephemeral_pk = x25519_dalek::PublicKey::from(ephemeral_pk_bytes);
let recipient_sk_key = StaticSecret::from(*recipient_sk.as_bytes());
let recipient_pk_arr: [u8; 32] = *recipient_pk.as_bytes();
- // Compute shared secret
let shared_secret = recipient_sk_key.diffie_hellman(&ephemeral_pk);
- // SECURITY: Reject non-contributory (small-order point)
+ // Reject small-order points that produce an all-zero shared secret.
if !is_contributory(shared_secret.as_bytes()) {
return Err(Error::InvalidPublicKey);
}
- // Derive encryption key
let mut box_key = derive_box_key(shared_secret.as_bytes());
- // Compute nonce
let nonce = seal_nonce(&ephemeral_pk_bytes, &recipient_pk_arr);
- // Decrypt (RustCrypto expects same format: MAC || ciphertext)
let cipher = XSalsa20Poly1305::new(GenericArray::from_slice(&box_key));
let plaintext = cipher
.decrypt(GenericArray::from_slice(&nonce), encrypted)
@@ -239,7 +166,6 @@ mod tests {
let sealed1 = seal(plaintext, &pk).unwrap();
let sealed2 = seal(plaintext, &pk).unwrap();
- // Different ephemeral keys -> different ciphertexts
assert_ne!(sealed1, sealed2);
}
@@ -274,7 +200,6 @@ mod tests {
let mut sealed = seal(plaintext, &pk).unwrap();
- // Corrupt a byte in the middle
let mid = sealed.len() / 2;
sealed[mid] ^= 1;
@@ -289,7 +214,6 @@ mod tests {
let mut sealed = seal(plaintext, &pk).unwrap();
- // Corrupt ephemeral public key
sealed[0] ^= 1;
let result = open(&sealed, &pk, &sk);
@@ -303,7 +227,6 @@ mod tests {
let mut sealed = seal(plaintext, &pk).unwrap();
- // Corrupt MAC (at position 32-47)
sealed[40] ^= 1;
let result = open(&sealed, &pk, &sk);
@@ -313,7 +236,7 @@ mod tests {
#[test]
fn test_ciphertext_too_short() {
let (pk, sk) = generate_keypair();
- let bad_ciphertext = vec![0u8; 40]; // Less than SEAL_OVERHEAD
+ let bad_ciphertext = vec![0u8; 40];
let result = open(&bad_ciphertext, &pk, &sk);
assert!(matches!(result, Err(Error::CiphertextTooShort { .. })));
@@ -334,7 +257,7 @@ mod tests {
#[test]
fn test_large_plaintext() {
let (pk, sk) = generate_keypair();
- let plaintext = vec![0x42u8; 1024 * 1024]; // 1 MB
+ let plaintext = vec![0x42u8; 1024 * 1024];
let sealed = seal(&plaintext, &pk).unwrap();
let opened = open(&sealed, &pk, &sk).unwrap();
@@ -344,8 +267,6 @@ mod tests {
#[test]
fn test_seal_rejects_small_order_point() {
- // The all-zero public key is a small-order point. X25519 DH with it
- // produces an all-zero shared secret, which is_contributory must reject.
let zero_pk = PublicKey::from_bytes([0u8; 32]);
let result = seal(b"test", &zero_pk);
assert!(
@@ -359,11 +280,7 @@ mod tests {
fn test_open_rejects_small_order_ephemeral_key() {
let (pk, sk) = generate_keypair();
- // Craft a ciphertext with an all-zero ephemeral public key (32 zero
- // bytes) followed by enough garbage to pass the length check.
let mut fake_ciphertext = vec![0u8; SEAL_OVERHEAD + 16];
- // Fill the MAC + ciphertext portion with non-zero data so we know
- // the rejection is from is_contributory, not from decryption.
for b in &mut fake_ciphertext[32..] {
*b = 0xFF;
}
@@ -382,18 +299,15 @@ mod tests {
let (pk2, sk2) = generate_keypair();
let plaintext = b"Broadcast message";
- // Seal for different recipients
let sealed1 = seal(plaintext, &pk1).unwrap();
let sealed2 = seal(plaintext, &pk2).unwrap();
- // Each recipient can decrypt their own
let opened1 = open(&sealed1, &pk1, &sk1).unwrap();
let opened2 = open(&sealed2, &pk2, &sk2).unwrap();
assert_eq!(opened1, plaintext);
assert_eq!(opened2, plaintext);
- // But not each other's
assert!(open(&sealed1, &pk2, &sk2).is_err());
assert!(open(&sealed2, &pk1, &sk1).is_err());
}
diff --git a/rust/crates/core/src/crypto/secret.rs b/rust/crates/core/src/crypto/secret.rs
index 3b9aec4115..12393b8a41 100644
--- a/rust/crates/core/src/crypto/secret.rs
+++ b/rust/crates/core/src/crypto/secret.rs
@@ -1,21 +1,14 @@
-//! Zeroizing wrappers for sensitive material.
-
use std::fmt;
use std::ops::{Deref, DerefMut};
use subtle::ConstantTimeEq;
use zeroize::{Zeroize, ZeroizeOnDrop};
-/// A heap-allocated byte buffer for sensitive material.
-///
-/// `SecretVec` zeroizes its contents on drop and requires an explicit
-/// [`SecretVec::into_vec`] when crossing out of the trusted Rust layer.
#[repr(transparent)]
#[derive(Default, Zeroize, ZeroizeOnDrop)]
pub struct SecretVec(Vec<u8>);
impl PartialEq for SecretVec {
- /// Constant-time comparison (the length itself is not hidden).
fn eq(&self, other: &Self) -> bool {
self.0.ct_eq(&other.0).into()
}
@@ -30,12 +23,10 @@ impl std::hash::Hash for SecretVec {
}
impl SecretVec {
- /// Wrap a byte vector so it is zeroized on drop.
pub fn new(value: Vec<u8>) -> Self {
Self(value)
}
- /// Explicitly unwrap the secret bytes when crossing a trust boundary.
pub fn into_vec(mut self) -> Vec<u8> {
std::mem::take(&mut self.0)
}
@@ -79,16 +70,11 @@ impl From<Vec<u8>> for SecretVec {
}
}
-/// A heap-allocated string for sensitive material.
-///
-/// `SecretString` zeroizes its contents on drop and requires an explicit
-/// [`SecretString::into_string`] when crossing out of the trusted Rust layer.
#[repr(transparent)]
#[derive(Default, Zeroize, ZeroizeOnDrop)]
pub struct SecretString(String);
impl PartialEq for SecretString {
- /// Constant-time comparison (the length itself is not hidden).
fn eq(&self, other: &Self) -> bool {
self.0.as_bytes().ct_eq(other.0.as_bytes()).into()
}
@@ -103,12 +89,10 @@ impl std::hash::Hash for SecretString {
}
impl SecretString {
- /// Wrap a string so it is zeroized on drop.
pub fn new(value: String) -> Self {
Self(value)
}
- /// Explicitly unwrap the secret string when crossing a trust boundary.
pub fn into_string(mut self) -> String {
std::mem::take(&mut self.0)
}
@@ -152,9 +136,6 @@ mod tests {
#[test]
fn test_secret_vec_zeroize_clears_buffer() {
- // Verify that calling zeroize() (which Drop invokes) zeroes the
- // buffer while we still own the memory; no UB from reading freed
- // allocations.
let mut secret = SecretVec::new(vec![0xABu8; 64]);
assert!(secret.iter().any(|&b| b != 0), "precondition: non-zero");
secret.zeroize();
@@ -168,19 +149,14 @@ mod tests {
fn test_secret_vec_into_vec_preserves_contents() {
let secret = SecretVec::new(vec![0xCDu8; 32]);
let vec = secret.into_vec();
- // The extracted vec should still have the original contents
assert!(vec.iter().all(|&b| b == 0xCD));
}
#[test]
fn test_secret_vec_into_vec_leaves_empty_inner() {
- // After into_vec(), the SecretVec's inner buffer is empty, so
- // Drop won't zeroize the extracted data; that's the caller's
- // responsibility now.
let secret = SecretVec::new(vec![0xEFu8; 16]);
let vec = secret.into_vec();
assert_eq!(vec.len(), 16);
- // No panic on implicit drop of the now-empty SecretVec
}
#[test]
diff --git a/rust/crates/core/src/crypto/secretbox.rs b/rust/crates/core/src/crypto/secretbox.rs
index dd10d99acb..28fb04158e 100644
--- a/rust/crates/core/src/crypto/secretbox.rs
+++ b/rust/crates/core/src/crypto/secretbox.rs
@@ -1,70 +1,25 @@
-//! Authenticated encryption with XSalsa20-Poly1305.
-//!
-//! SecretBox encrypts and authenticates a single, self-contained value with a
-//! 256-bit key. It suits small, independent pieces of data such as a wrapped
-//! key or a short field. Ente uses [`blob`](super::blob) for data attached to
-//! an object (file or collection metadata and the like), and
-//! [`stream`](super::stream) for file contents, which are encrypted in chunks.
-//!
-//! The name comes from libsodium, which exposes this same construction as
-//! `crypto_secretbox`; the implementation here is pure Rust but wire-compatible
-//! (recorded per function below).
-//!
-//! Every message uses a 192-bit nonce, generated fresh on each call. It is not
-//! secret, but it is needed to decrypt.
-//!
-//! Two payload shapes are offered, differing only in how the nonce travels:
-//!
-//! - Split ([`encrypt`] / [`decrypt`]): the ciphertext (`MAC ‖ ct`) and the
-//! nonce are returned separately.
-//!
-//! - Combined ([`encrypt_combined`] / [`decrypt_combined`]): the nonce is
-//! prepended to the ciphertext to form one self-contained buffer
-//! (`nonce ‖ MAC ‖ ct`).
-
use xsalsa20poly1305::XSalsa20Poly1305;
use xsalsa20poly1305::aead::generic_array::GenericArray;
use xsalsa20poly1305::aead::{Aead, KeyInit};
use crate::crypto::{Error, Key, Nonce, Result};
-/// Size in bytes of the Poly1305 authentication tag that prefixes every
-/// ciphertext.
-///
-/// Same as libsodium's `crypto_secretbox_MACBYTES`.
+// Same as libsodium's `crypto_secretbox_MACBYTES`.
pub const MAC_BYTES: usize = 16;
-/// A secretbox ciphertext together with the nonce needed to open it, as
-/// returned by [`encrypt`].
-///
-/// This is the split shape, with the nonce held separately from the ciphertext;
-/// see the module docs for the combined alternative.
#[derive(Debug, Clone, PartialEq)]
pub struct EncryptedBox {
- /// The Poly1305 tag followed by the ciphertext: `MAC (16 bytes) ‖ ciphertext`.
pub encrypted_data: Vec<u8>,
- /// The nonce that encrypted [`encrypted_data`](Self::encrypted_data). Needed
- /// to decrypt, and not secret, but never reused with the same key.
pub nonce: Nonce,
}
impl EncryptedBox {
- /// Decrypt this box with `key`, returning the plaintext.
- ///
- /// A convenience wrapper over [`decrypt`] using the stored ciphertext and
- /// nonce; see it for the error cases.
pub fn decrypt(&self, key: &Key) -> Result<Vec<u8>> {
decrypt(&self.encrypted_data, &self.nonce, key)
}
}
-/// Encrypt `data` with `key` and a freshly generated random nonce.
-///
-/// Returns the ciphertext and the nonce; decrypt with [`decrypt`] or
-/// [`EncryptedBox::decrypt`]. The plaintext is not padded, so the ciphertext
-/// length reveals the exact plaintext length.
-///
-/// Wire-compatible with libsodium's `crypto_secretbox_easy`.
+// Wire-compatible with libsodium's `crypto_secretbox_easy`.
pub fn encrypt(data: &[u8], key: &Key) -> EncryptedBox {
let nonce = Nonce::generate();
let encrypted_data = encrypt_with_nonce(data, &nonce, key);
@@ -74,9 +29,6 @@ pub fn encrypt(data: &[u8], key: &Key) -> EncryptedBox {
}
}
-/// Shared back end for [`encrypt`] and [`encrypt_combined`]: encrypts `data`
-/// with `key` and the given `nonce`, returning `MAC ‖ ciphertext`. Both
-/// callers generate a fresh nonce, so a (key, nonce) pair is never reused.
fn encrypt_with_nonce(data: &[u8], nonce: &Nonce, key: &Key) -> Vec<u8> {
let cipher = XSalsa20Poly1305::new(GenericArray::from_slice(key.as_bytes()));
let nonce_ga = GenericArray::from_slice(nonce.as_bytes());
@@ -88,21 +40,7 @@ fn encrypt_with_nonce(data: &[u8], nonce: &Nonce, key: &Key) -> Vec<u8> {
.expect("XSalsa20-Poly1305 encryption cannot fail for in-memory plaintexts")
}
-/// Decrypt a ciphertext produced by [`encrypt`].
-///
-/// Pass the same `nonce` and `key` that encrypted it. `data` is
-/// `MAC (16 bytes) ‖ ciphertext`. The Poly1305 tag is verified before any
-/// plaintext is returned, so a successful result is also proof that the
-/// ciphertext was not altered.
-///
-/// # Errors
-///
-/// Returns [`CiphertextTooShort`](Error::CiphertextTooShort) if `data` is
-/// smaller than the tag, or [`DecryptionFailed`](Error::DecryptionFailed)
-/// if the tag does not verify, which is the case whenever the key, nonce, or
-/// ciphertext is wrong or the data was tampered with.
-///
-/// Wire-compatible with libsodium's `crypto_secretbox_open_easy`.
+// Wire-compatible with libsodium's `crypto_secretbox_open_easy`.
pub fn decrypt(data: &[u8], nonce: &Nonce, key: &Key) -> Result<Vec<u8>> {
if data.len() < MAC_BYTES {
return Err(Error::CiphertextTooShort {
@@ -119,17 +57,8 @@ pub fn decrypt(data: &[u8], nonce: &Nonce, key: &Key) -> Result<Vec<u8>> {
.map_err(|_| Error::DecryptionFailed)
}
-/// Encrypt `data` with `key` into one self-contained buffer.
-///
-/// Like [`encrypt`], but prepends a random nonce to the ciphertext,
-/// returning `nonce (24 bytes) ‖ MAC (16 bytes) ‖ ciphertext`: everything
-/// needed to decrypt except the key. Prefer this when a single opaque blob is
-/// easier to store or pass around than a separate ciphertext and nonce. Decrypt
-/// with [`decrypt_combined`].
-///
-/// The `MAC ‖ ciphertext` body is wire-compatible with libsodium's
-/// `crypto_secretbox_easy`; prepending the nonce is an Ente convention, not part
-/// of libsodium itself.
+// The MAC || ciphertext body is wire-compatible with libsodium's
+// `crypto_secretbox_easy`; prepending the nonce is an Ente convention.
pub fn encrypt_combined(data: &[u8], key: &Key) -> Vec<u8> {
let nonce = Nonce::generate();
let encrypted = encrypt_with_nonce(data, &nonce, key);
@@ -140,18 +69,8 @@ pub fn encrypt_combined(data: &[u8], key: &Key) -> Vec<u8> {
combined
}
-/// Decrypt a combined buffer produced by [`encrypt_combined`].
-///
-/// Splits the leading nonce from the `MAC ‖ ciphertext` body, then verifies the
-/// tag and decrypts as [`decrypt`] does.
-///
-/// # Errors
-///
-/// Returns [`CiphertextTooShort`](Error::CiphertextTooShort) if `data` is
-/// too short to hold a nonce and tag, otherwise the same errors as [`decrypt`].
-///
-/// The body is wire-compatible with libsodium's `crypto_secretbox_open_easy`;
-/// the leading nonce is an Ente convention.
+// The body is wire-compatible with libsodium's `crypto_secretbox_open_easy`;
+// the leading nonce is an Ente convention.
pub fn decrypt_combined(data: &[u8], key: &Key) -> Result<Vec<u8>> {
if data.len() < Nonce::BYTES + MAC_BYTES {
return Err(Error::CiphertextTooShort {
@@ -221,8 +140,6 @@ mod tests {
#[test]
fn test_combined_is_split_with_nonce_prefix() {
- // The combined format must be exactly nonce ‖ (split ciphertext), so
- // the two shapes stay interconvertible.
let key = Key::generate();
let plaintext = b"Interop test";
@@ -286,7 +203,7 @@ mod tests {
#[test]
fn test_large_plaintext() {
let key = Key::generate();
- let plaintext = vec![0x42u8; 1024 * 1024]; // 1 MB
+ let plaintext = vec![0x42u8; 1024 * 1024];
let encrypted = encrypt(&plaintext, &key);
assert_eq!(encrypted.decrypt(&key).unwrap(), plaintext);
diff --git a/rust/crates/core/src/crypto/stream.rs b/rust/crates/core/src/crypto/stream.rs
index 826a01dc9b..a57863f1ac 100644
--- a/rust/crates/core/src/crypto/stream.rs
+++ b/rust/crates/core/src/crypto/stream.rs
@@ -1,26 +1,6 @@
-//! Chunked authenticated encryption with XChaCha20-Poly1305.
-//!
-//! This is the encryption used for file contents: the plaintext is split into
-//! fixed-size chunks ([`ENCRYPTION_CHUNK_SIZE`]) and each chunk is encrypted as
-//! one secretstream message, so an arbitrarily large file can be processed
-//! without holding it all in memory. For a single bounded value that fits in
-//! memory, use [`blob`](super::blob) instead.
-//!
-//! The chunks are chained, so a decryptor detects any truncation, reordering,
-//! or modification. The last chunk is tagged final, and reaching that tag is
-//! what proves the stream is complete rather than cut short (see
-//! [`Decryptor::finish`]).
-//!
-//! The construction is libsodium's secretstream
-//! (`crypto_secretstream_xchacha20poly1305`); the implementation here wraps the
-//! pure-Rust `crypto_secretstream` crate and is wire-compatible.
-//!
-//! # Wire format
-//!
-//! A 24-byte header (produced when encryption starts, stored or sent
-//! separately), followed by one secretstream message per chunk. Each message is
-//! [`ABYTES`] bytes longer than its plaintext: a one-byte encrypted tag, the
-//! ciphertext, and a 16-byte Poly1305 MAC.
+// Wire-compatible with libsodium's `crypto_secretstream_xchacha20poly1305`.
+// A separate 24-byte header precedes the encrypted messages.
+// The final tag is required to distinguish a complete stream from truncation.
use crypto_secretstream::{
Header as UpstreamHeader, Key as UpstreamKey, PullStream, PushStream, Stream, Tag,
@@ -35,39 +15,26 @@ use crate::crypto::{Error, Header, Key, Result};
const _: () = assert!(Key::BYTES == UpstreamKey::BYTES);
const _: () = assert!(Header::BYTES == UpstreamHeader::BYTES);
-/// Size of the stream header in bytes.
pub const HEADER_BYTES: usize = Header::BYTES;
-/// Size of the encryption key in bytes.
pub const KEY_BYTES: usize = Key::BYTES;
-/// Per-message overhead secretstream adds to the plaintext: a one-byte
-/// encrypted tag and a 16-byte Poly1305 MAC.
pub const ABYTES: usize = Stream::ABYTES;
-/// Plaintext chunk size for streaming file encryption (4 MB).
pub const ENCRYPTION_CHUNK_SIZE: usize = 4 * 1024 * 1024;
-/// Ciphertext chunk size for streaming file decryption (4 MB + overhead).
pub const DECRYPTION_CHUNK_SIZE: usize = ENCRYPTION_CHUNK_SIZE + ABYTES;
fn upstream_key(key: &Key) -> UpstreamKey {
UpstreamKey::from(*key.as_bytes())
}
-/// Stateful chunk-by-chunk stream encryptor.
-///
-/// Feed the plaintext one chunk at a time to [`push`](Self::push), marking the
-/// last chunk with `is_final`. The [`header`](Self::header) must be kept and
-/// handed to the [`Decryptor`]. This is the low-level building block; for
-/// reader/writer plumbing see [`encrypt_file`] and [`StreamingEncryptor`].
pub struct Encryptor {
stream: PushStream,
header: Header,
}
impl Encryptor {
- /// Create an encryptor with `key`, generating a fresh random header.
pub fn new(key: &Key) -> Self {
let (header, stream) = PushStream::init(OsRng, &upstream_key(key));
Self {
@@ -76,12 +43,10 @@ impl Encryptor {
}
}
- /// The decryption header. Required for decryption; not secret.
pub fn header(&self) -> &Header {
&self.header
}
- /// Encrypt a chunk, marking it final if it is the last one.
pub fn push(&mut self, data: &[u8], is_final: bool) -> Result<Vec<u8>> {
let mut buffer = Vec::with_capacity(data.len() + ABYTES);
buffer.extend_from_slice(data);
@@ -89,8 +54,6 @@ impl Encryptor {
Ok(buffer)
}
- /// Encrypt a chunk in-place: the buffer's plaintext is replaced by
- /// ciphertext (growing by [`ABYTES`]).
fn push_in_place(&mut self, buffer: &mut Vec<u8>, is_final: bool) -> Result<()> {
let tag = if is_final { Tag::Final } else { Tag::Message };
self.stream
@@ -99,21 +62,12 @@ impl Encryptor {
}
}
-/// Stateful chunk-by-chunk stream decryptor.
-///
-/// Decrypt each chunk with [`pull`](Self::pull), in the order they were
-/// produced. After the last chunk, call [`finish`](Self::finish): it fails if
-/// the final tag was never seen, which is how truncation at a chunk boundary is
-/// caught. This is the low-level building block; for reader/writer plumbing see
-/// [`decrypt_file`] and [`StreamingDecryptor`].
pub struct Decryptor {
stream: PullStream,
seen_final: bool,
}
impl Decryptor {
- /// Create a decryptor from the `header` produced during encryption and the
- /// same `key`.
pub fn new(header: &Header, key: &Key) -> Self {
let header = UpstreamHeader::from(*header.as_bytes());
let stream = PullStream::init(header, &upstream_key(key));
@@ -123,25 +77,12 @@ impl Decryptor {
}
}
- /// Decrypt the next chunk, returning its plaintext and whether it was the
- /// final chunk.
- ///
- /// Chunks must be pulled in the order they were pushed; a wrong key or
- /// header, or out-of-order, modified, or reordered chunks, all fail the MAC.
- ///
- /// # Errors
- ///
- /// Returns [`StreamPullFailed`](Error::StreamPullFailed) if the chunk
- /// is shorter than the per-message overhead or its MAC does not verify.
pub fn pull(&mut self, data: &[u8]) -> Result<(Vec<u8>, bool)> {
let mut buffer = data.to_vec();
let is_final = self.pull_in_place(&mut buffer)?;
Ok((buffer, is_final))
}
- /// Decrypt a chunk in-place: the buffer's ciphertext is replaced by
- /// plaintext (shrinking by [`ABYTES`]). Returns whether this was the
- /// final chunk.
fn pull_in_place(&mut self, buffer: &mut Vec<u8>) -> Result<bool> {
if buffer.len() < ABYTES {
return Err(Error::StreamPullFailed);
@@ -159,16 +100,7 @@ impl Decryptor {
Ok(is_final)
}
- /// Confirm the stream was complete, consuming the decryptor.
- ///
- /// Call this after the last [`pull`](Self::pull). Without it, a stream cut
- /// short exactly at a chunk boundary is indistinguishable from a complete
- /// one, since each chunk on its own is valid.
- ///
- /// # Errors
- ///
- /// Returns [`StreamTruncated`](Error::StreamTruncated) if no
- /// final-tagged chunk was ever pulled.
+ // A valid non-final chunk can end at EOF, so callers must finish the stream.
pub fn finish(self) -> Result<()> {
if self.seen_final {
Ok(())
@@ -178,12 +110,6 @@ impl Decryptor {
}
}
-/// Predict the ciphertext size, excluding the header, for encrypting
-/// `plaintext_len` bytes.
-///
-/// The plaintext is split into [`ENCRYPTION_CHUNK_SIZE`] chunks, each gaining
-/// [`ABYTES`] of overhead; an empty plaintext still emits one empty final
-/// chunk. Saturates to `usize::MAX` rather than overflowing.
#[inline]
pub fn estimate_encrypted_size(plaintext_len: usize) -> usize {
if plaintext_len == 0 {
@@ -212,12 +138,6 @@ pub fn estimate_encrypted_size(plaintext_len: usize) -> usize {
}
}
-/// Check that `ciphertext_len` is what encrypting `plaintext_len` bytes would
-/// produce.
-///
-/// Returns `true` when `ciphertext_len` equals [`estimate_encrypted_size`] for
-/// the given plaintext. This compares sizes only and excludes the header; it is
-/// a cheap sanity check, not an integrity check (decryption provides that).
#[inline]
pub fn validate_sizes(plaintext_len: usize, ciphertext_len: usize) -> bool {
let estimated = estimate_encrypted_size(plaintext_len);
@@ -227,29 +147,15 @@ pub fn validate_sizes(plaintext_len: usize, ciphertext_len: usize) -> bool {
estimated == ciphertext_len
}
-/// Encrypt a stream of writes to an underlying writer, chunk by chunk.
-///
-/// Feed plaintext with [`write`](Self::write) and end with
-/// [`finish`](Self::finish); the header is written to the writer up front. Use
-/// this when plaintext arrives incrementally. When you already have a reader,
-/// [`encrypt_file`] is simpler.
-///
-/// It holds back the last full chunk so that chunk can be tagged final, which
-/// avoids emitting an extra empty final chunk when the plaintext is an exact
-/// multiple of [`ENCRYPTION_CHUNK_SIZE`].
pub struct StreamingEncryptor<W: Write> {
encryptor: Encryptor,
writer: W,
- /// Remainder bytes (< chunk size).
buffer: Vec<u8>,
- /// Pending full chunk (exactly `ENCRYPTION_CHUNK_SIZE` bytes) that is not
- /// written until we know whether it's the final chunk.
+ // Hold one full chunk until we know whether it needs the final tag.
pending: Vec<u8>,
}
impl<W: Write> StreamingEncryptor<W> {
- /// Create a streaming encryptor with `key`, writing the decryption header
- /// to `writer` before any ciphertext.
pub fn new(key: &Key, mut writer: W) -> Result<Self> {
let encryptor = Encryptor::new(key);
writer.write_all(encryptor.header().as_bytes())?;
@@ -282,10 +188,6 @@ impl<W: Write> StreamingEncryptor<W> {
Ok(())
}
- /// Buffer and encrypt plaintext, writing completed chunks to the writer.
- ///
- /// Bytes accumulate until a full chunk is available; call
- /// [`finish`](Self::finish) to flush the remainder as the final chunk.
pub fn write(&mut self, data: &[u8]) -> Result<()> {
let mut input_pos = 0;
@@ -317,7 +219,6 @@ impl<W: Write> StreamingEncryptor<W> {
Ok(())
}
- /// Flush the buffered remainder as the final chunk and return the writer.
pub fn finish(mut self) -> Result<W> {
if !self.pending.is_empty() {
if !self.buffer.is_empty() {
@@ -334,24 +235,10 @@ impl<W: Write> StreamingEncryptor<W> {
}
}
-/// Decrypt a stream from an underlying reader, chunk by chunk.
-///
-/// Read plaintext with [`read`](Self::read) or
-/// [`read_to_end`](Self::read_to_end); the header is read from the reader
-/// first. Like [`decrypt_file`] it detects truncation: reaching EOF without the
-/// final tag is an error, as is trailing data after it. Use this when you want
-/// to consume plaintext incrementally.
-///
-/// Decryption happens in place in a single reused buffer, avoiding the copies
-/// that separate read, decrypt, and output buffers would incur.
pub struct StreamingDecryptor<R: Read> {
decryptor: Decryptor,
reader: R,
- /// Single buffer: holds ciphertext during read, then plaintext after
- /// decryption. Unconsumed plaintext is at indices
- /// `data_start..buffer.len()`.
buffer: Vec<u8>,
- /// Start index of unconsumed plaintext in buffer.
data_start: usize,
finished: bool,
seen_final: bool,
@@ -371,8 +258,6 @@ fn ensure_reader_exhausted<R: Read>(reader: &mut R) -> Result<()> {
}
impl<R: Read> StreamingDecryptor<R> {
- /// Create a streaming decryptor with `key`, reading the decryption header
- /// from `reader` before any ciphertext.
pub fn new(key: &Key, mut reader: R) -> Result<Self> {
let mut header = [0u8; Header::BYTES];
reader.read_exact(&mut header)?;
@@ -387,20 +272,9 @@ impl<R: Read> StreamingDecryptor<R> {
})
}
- /// Decrypt into `buf`, returning the number of bytes written, or 0 at the
- /// end of the stream.
- ///
- /// # Errors
- ///
- /// Returns [`StreamTruncated`](Error::StreamTruncated) if the stream
- /// ends before the final tag,
- /// [`StreamTrailingData`](Error::StreamTrailingData) if bytes follow
- /// the final chunk, or [`StreamPullFailed`](Error::StreamPullFailed)
- /// if a chunk fails to decrypt.
pub fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
- // If we have buffered plaintext, return it first (O(1) via index)
- // This must be checked BEFORE the finished flag, since we may have
- // buffered data remaining after seeing the final tag.
+ // A final chunk may still have unread plaintext, so drain it before
+ // honoring `finished`.
let buffered_remaining = self.buffer.len() - self.data_start;
if buffered_remaining > 0 {
let to_copy = std::cmp::min(buf.len(), buffered_remaining);
@@ -408,7 +282,6 @@ impl<R: Read> StreamingDecryptor<R> {
.copy_from_slice(&self.buffer[self.data_start..self.data_start + to_copy]);
self.data_start += to_copy;
- // Reset buffer when fully consumed to reclaim memory
if self.data_start == self.buffer.len() {
self.buffer.clear();
self.data_start = 0;
@@ -416,12 +289,10 @@ impl<R: Read> StreamingDecryptor<R> {
return Ok(to_copy);
}
- // No more buffered data - check if we're done
if self.finished {
return Ok(0);
}
- // Read next encrypted chunk directly into buffer (single-buffer strategy)
self.buffer.clear();
self.buffer.resize(DECRYPTION_CHUNK_SIZE, 0);
let mut total_read = 0;
@@ -441,7 +312,6 @@ impl<R: Read> StreamingDecryptor<R> {
}
if total_read == 0 {
- // EOF reached - verify we saw the final tag (truncation detection)
self.buffer.clear();
if !self.seen_final {
return Err(Error::StreamTruncated);
@@ -450,7 +320,6 @@ impl<R: Read> StreamingDecryptor<R> {
return Ok(0);
}
- // Truncate buffer to actual bytes read, then decrypt in-place
self.buffer.truncate(total_read);
let is_final = self.decryptor.pull_in_place(&mut self.buffer)?;
@@ -460,14 +329,12 @@ impl<R: Read> StreamingDecryptor<R> {
self.finished = true;
}
- // Serve plaintext via indices (buffer now contains plaintext)
self.data_start = 0;
let plaintext_len = self.buffer.len();
let to_copy = std::cmp::min(buf.len(), plaintext_len);
buf[..to_copy].copy_from_slice(&self.buffer[..to_copy]);
self.data_start = to_copy;
- // Reset buffer if fully consumed
if self.data_start == self.buffer.len() {
self.buffer.clear();
self.data_start = 0;
@@ -476,9 +343,6 @@ impl<R: Read> StreamingDecryptor<R> {
Ok(to_copy)
}
- /// Decrypt the entire remaining stream into a new `Vec`.
- ///
- /// Convenience over repeated [`read`](Self::read); the same errors apply.
pub fn read_to_end(&mut self) -> Result<Vec<u8>> {
let mut result = Vec::new();
let mut buf = [0u8; 8192];
@@ -494,16 +358,6 @@ impl<R: Read> StreamingDecryptor<R> {
}
}
-/// Encrypt everything from `reader` to `writer`, returning the decryption
-/// header.
-///
-/// The header is not written to the `writer` but is returned; store or send
-/// it separately (for instance, in the file's server-side metadata). Only the
-/// encrypted chunks are written, and you can predict their total length with
-/// [`estimate_encrypted_size`].
-///
-/// Reuses buffers and encrypts in place, so memory stays bounded to about twice
-/// the chunk size regardless of file size.
pub fn encrypt_file<R: Read, W: Write>(
reader: &mut R,
writer: &mut W,
@@ -525,17 +379,14 @@ pub fn encrypt_file<R: Read, W: Write>(
Ok(total_read)
};
- // Reusable buffers for plaintext chunks
let mut curr = vec![0u8; ENCRYPTION_CHUNK_SIZE];
let mut next = vec![0u8; ENCRYPTION_CHUNK_SIZE];
- // Reusable buffer for in-place encryption (avoids per-chunk allocation)
let mut encrypt_buffer = Vec::with_capacity(ENCRYPTION_CHUNK_SIZE + ABYTES);
let mut curr_len = read_chunk(&mut curr)?;
if curr_len == 0 {
- // Empty file: single empty FINAL chunk
encrypt_buffer.clear();
encryptor.push_in_place(&mut encrypt_buffer, true)?;
writer.write_all(&encrypt_buffer)?;
@@ -544,7 +395,6 @@ pub fn encrypt_file<R: Read, W: Write>(
loop {
if curr_len < ENCRYPTION_CHUNK_SIZE {
- // Last chunk is partial
encrypt_buffer.clear();
encrypt_buffer.extend_from_slice(&curr[..curr_len]);
encryptor.push_in_place(&mut encrypt_buffer, true)?;
@@ -571,19 +421,6 @@ pub fn encrypt_file<R: Read, W: Write>(
Ok(header)
}
-/// Decrypt the chunk stream in `reader` to `writer`, using `header` and `key`.
-///
-/// `reader` holds the ciphertext only; the header travels separately. Like
-/// [`encrypt_file`] it reuses buffers and decrypts in place, so memory stays
-/// bounded to about twice the chunk size.
-///
-/// # Errors
-///
-/// Returns [`StreamTruncated`](Error::StreamTruncated) if EOF is reached
-/// without the final tag (the truncation check), or
-/// [`StreamTrailingData`](Error::StreamTrailingData) if bytes remain after
-/// the final chunk. A chunk that fails to decrypt yields
-/// [`StreamPullFailed`](Error::StreamPullFailed).
pub fn decrypt_file<R: Read, W: Write>(
reader: &mut R,
writer: &mut W,
@@ -591,17 +428,14 @@ pub fn decrypt_file<R: Read, W: Write>(
key: &Key,
) -> Result<()> {
let mut decryptor = Decryptor::new(header, key);
- // Reusable read buffer - sized for ciphertext chunks
let mut read_buffer = vec![0u8; DECRYPTION_CHUNK_SIZE];
- // Reusable decrypt buffer for in-place decryption (avoids per-chunk allocation)
let mut decrypt_buffer = Vec::with_capacity(DECRYPTION_CHUNK_SIZE);
loop {
let mut total_read = 0;
- // Read up to DECRYPTION_CHUNK_SIZE bytes
while total_read < DECRYPTION_CHUNK_SIZE {
match reader.read(&mut read_buffer[total_read..]) {
- Ok(0) => break, // EOF
+ Ok(0) => break,
Ok(n) => total_read += n,
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
Err(e) => return Err(e.into()),
@@ -609,28 +443,21 @@ pub fn decrypt_file<R: Read, W: Write>(
}
if total_read == 0 {
- // EOF reached without seeing the final tag - stream was truncated
return decryptor.finish();
}
- // Copy to decrypt buffer and decrypt in-place (reuses buffer each iteration)
decrypt_buffer.clear();
decrypt_buffer.extend_from_slice(&read_buffer[..total_read]);
let is_final = decryptor.pull_in_place(&mut decrypt_buffer)?;
writer.write_all(&decrypt_buffer)?;
if is_final {
- // Successfully decrypted the final chunk - stream is complete
ensure_reader_exhausted(reader)?;
return Ok(());
}
}
}
-/// Decrypt an in-memory chunk stream, using `header` and `key`.
-///
-/// Convenience over [`decrypt_file`] for when the whole ciphertext is already
-/// in a buffer; the same truncation and trailing-data checks apply.
pub fn decrypt_file_data(encrypted_data: &[u8], header: &Header, key: &Key) -> Result<Vec<u8>> {
use std::io::Cursor;
@@ -654,7 +481,6 @@ mod tests {
let key = test_key();
let plaintext = b"Hello, world! This is a test message.";
- // Encrypt
let mut encrypted = Vec::new();
{
let mut encryptor =
@@ -663,7 +489,6 @@ mod tests {
encryptor.finish().expect("finish failed");
}
- // Decrypt
let reader = Cursor::new(&encrypted);
let mut decryptor =
StreamingDecryptor::new(&key, reader).expect("decryptor creation failed");
@@ -676,7 +501,6 @@ mod tests {
fn test_truncation_detection_empty_stream() {
let key = test_key();
- // Create a stream with just the header, no encrypted data
let encryptor = Encryptor::new(&key);
let truncated_data = encryptor.header().as_bytes().to_vec();
@@ -697,7 +521,6 @@ mod tests {
let key = test_key();
let plaintext = b"Hello, world!";
- // Encrypt with non-final tag only
let mut encryptor = Encryptor::new(&key);
let mut truncated_data = encryptor.header().as_bytes().to_vec();
let encrypted_chunk = encryptor.push(plaintext, false).expect("push failed");
@@ -735,8 +558,6 @@ mod tests {
#[test]
fn test_decryptor_finish_detects_missing_final_tag() {
- // Manual chunk-by-chunk decryption succeeds per-chunk, but finish()
- // must catch a stream that never carried the final tag.
let key = test_key();
let mut encryptor = Encryptor::new(&key);
@@ -770,13 +591,9 @@ mod tests {
#[test]
fn test_small_buffer_reads_no_quadratic() {
- // Regression test: ensure small-buffer reads don't cause O(n²) behavior.
- // Uses index-based buffering instead of Vec::drain() to achieve O(n) total.
let key = test_key();
- // Use a larger plaintext to make the test meaningful
let plaintext: Vec<u8> = (0..10000).map(|i| (i % 256) as u8).collect();
- // Encrypt
let mut encrypted = Vec::new();
{
let mut encryptor =
@@ -785,7 +602,6 @@ mod tests {
encryptor.finish().expect("finish failed");
}
- // Decrypt using very small buffer (1 byte at a time - worst case for old impl)
let reader = Cursor::new(&encrypted);
let mut decryptor =
StreamingDecryptor::new(&key, reader).expect("decryptor creation failed");
@@ -804,11 +620,9 @@ mod tests {
#[test]
fn test_varied_buffer_sizes() {
- // Test with various buffer sizes to ensure correctness
let key = test_key();
let plaintext: Vec<u8> = (0..5000).map(|i| (i % 256) as u8).collect();
- // Encrypt
let mut encrypted = Vec::new();
{
let mut encryptor =
@@ -817,7 +631,6 @@ mod tests {
encryptor.finish().expect("finish failed");
}
- // Test with various buffer sizes
for buf_size in [1, 7, 13, 64, 100, 1000, 8192] {
let reader = Cursor::new(&encrypted);
let mut decryptor =
@@ -842,28 +655,19 @@ mod tests {
#[test]
fn test_large_slice_write_no_quadratic() {
- // Regression test: verify StreamingEncryptor::write() is O(n) for large slices.
- // The optimization processes full chunks directly from input slice without
- // buffering them first, and buffers only the remainder (< chunk size).
- // This avoids O(n²) behavior that would occur with copy_within compaction.
let key = test_key();
- // Create data spanning multiple chunks to exercise the optimization
- // 3 full chunks + partial = tests the direct slice processing path
let size = ENCRYPTION_CHUNK_SIZE * 3 + 1234;
let plaintext: Vec<u8> = (0..size).map(|i| (i % 256) as u8).collect();
- // Write in a single large call (worst case for old O(n²) implementation)
let mut encrypted = Vec::new();
{
let mut encryptor =
StreamingEncryptor::new(&key, &mut encrypted).expect("encryptor creation failed");
- // Single large write should be O(n) not O(n²)
encryptor.write(&plaintext).expect("write failed");
encryptor.finish().expect("finish failed");
}
- // Verify correctness
let reader = Cursor::new(&encrypted);
let mut decryptor =
StreamingDecryptor::new(&key, reader).expect("decryptor creation failed");
@@ -872,15 +676,12 @@ mod tests {
assert_eq!(plaintext.len(), decrypted.len());
assert_eq!(plaintext, decrypted);
- // Verify size matches estimate (confirms proper chunk structure)
let ciphertext_len = encrypted.len() - HEADER_BYTES;
assert_eq!(ciphertext_len, estimate_encrypted_size(plaintext.len()));
}
#[test]
fn test_write_with_partial_buffer_then_large_slice() {
- // Regression test: verify optimization handles partial buffer correctly.
- // Write small data (partial buffer), then large data that spans chunks.
let key = test_key();
let mut encrypted = Vec::new();
@@ -888,11 +689,9 @@ mod tests {
let mut encryptor =
StreamingEncryptor::new(&key, &mut encrypted).expect("encryptor creation failed");
- // Write small data first (creates partial buffer)
let small_data: Vec<u8> = (0..1000).map(|i| (i % 256) as u8).collect();
encryptor.write(&small_data).expect("write small failed");
- // Write large data that will complete the partial buffer then process full chunks
let large_size = ENCRYPTION_CHUNK_SIZE * 2 + 500;
let large_data: Vec<u8> = (0..large_size).map(|i| ((i + 1000) % 256) as u8).collect();
encryptor.write(&large_data).expect("write large failed");
@@ -900,7 +699,6 @@ mod tests {
encryptor.finish().expect("finish failed");
}
- // Decrypt and verify
let total_plaintext_size = 1000 + ENCRYPTION_CHUNK_SIZE * 2 + 500;
let reader = Cursor::new(&encrypted);
let mut decryptor =
@@ -909,7 +707,6 @@ mod tests {
assert_eq!(decrypted.len(), total_plaintext_size);
- // Verify content: first 1000 bytes, then large_data
for (i, byte) in decrypted.iter().take(1000).enumerate() {
assert_eq!(*byte, (i % 256) as u8, "Mismatch at small_data[{}]", i);
}
@@ -929,22 +726,17 @@ mod tests {
#[test]
fn test_empty_streaming() {
- // Test streaming encryption/decryption of empty data
let key = test_key();
- // Encrypt empty data
let mut encrypted = Vec::new();
{
let encryptor =
StreamingEncryptor::new(&key, &mut encrypted).expect("encryptor creation failed");
- // Don't write anything - just finish with empty final chunk
encryptor.finish().expect("finish failed");
}
- // Should have header + empty final chunk
assert_eq!(encrypted.len(), HEADER_BYTES + ABYTES);
- // Decrypt
let reader = Cursor::new(&encrypted);
let mut decryptor =
StreamingDecryptor::new(&key, reader).expect("decryptor creation failed");
@@ -955,9 +747,8 @@ mod tests {
#[test]
fn test_multi_chunk_roundtrip() {
- // Test with data larger than a (test-sized) chunk
let key = test_key();
- let chunk_size = 1024; // Smaller for test speed
+ let chunk_size = 1024;
let num_chunks = 3;
let plaintext: Vec<u8> = (0..(chunk_size * num_chunks + 500))
.map(|i| (i % 256) as u8)
@@ -978,7 +769,6 @@ mod tests {
offset = end;
}
- // Decrypt chunk by chunk
let mut decryptor = Decryptor::new(&header, &key);
let mut decrypted = Vec::new();
let mut ct_offset = 0;
@@ -1009,11 +799,9 @@ mod tests {
let header = *encryptor.header();
let mut ciphertext = encryptor.push(plaintext, true).expect("push failed");
- // Tamper with the ciphertext (flip a bit in the middle)
let mid = ciphertext.len() / 2;
ciphertext[mid] ^= 0x01;
- // Decryption should fail
let mut decryptor = Decryptor::new(&header, &key);
let result = decryptor.pull(&ciphertext);
@@ -1033,10 +821,8 @@ mod tests {
let mut header_bytes = *encryptor.header().as_bytes();
let ciphertext = encryptor.push(plaintext, true).expect("push failed");
- // Tamper with header
header_bytes[0] ^= 0x01;
- // Decryption should fail
let mut decryptor = Decryptor::new(&Header::from_bytes(header_bytes), &key);
let result = decryptor.pull(&ciphertext);
@@ -1056,7 +842,6 @@ mod tests {
let header = *encryptor.header();
let mut ciphertext = encryptor.push(plaintext, true).expect("push failed");
- // Tamper with MAC (last byte)
let last = ciphertext.len() - 1;
ciphertext[last] ^= 0x01;
@@ -1092,7 +877,6 @@ mod tests {
#[test]
fn test_constants_match_upstream() {
- // Verify our constants match the upstream crate
assert_eq!(HEADER_BYTES, 24);
assert_eq!(KEY_BYTES, 32);
assert_eq!(ABYTES, 17);
@@ -1100,19 +884,15 @@ mod tests {
#[test]
fn test_estimate_encrypted_size() {
- // Empty: just ABYTES for the FINAL tag
assert_eq!(estimate_encrypted_size(0), ABYTES);
- // Small data: data + ABYTES
assert_eq!(estimate_encrypted_size(100), 100 + ABYTES);
- // Exact chunk size: one FINAL chunk
assert_eq!(
estimate_encrypted_size(ENCRYPTION_CHUNK_SIZE),
DECRYPTION_CHUNK_SIZE
);
- // Multiple chunks
let two_chunks_plus = ENCRYPTION_CHUNK_SIZE * 2 + 500;
let expected = 2 * DECRYPTION_CHUNK_SIZE + 500 + ABYTES;
assert_eq!(estimate_encrypted_size(two_chunks_plus), expected);
@@ -1123,8 +903,8 @@ mod tests {
assert!(validate_sizes(0, ABYTES));
assert!(validate_sizes(100, 100 + ABYTES));
assert!(validate_sizes(ENCRYPTION_CHUNK_SIZE, DECRYPTION_CHUNK_SIZE));
- assert!(!validate_sizes(100, 100)); // Missing ABYTES
- assert!(!validate_sizes(100, 200)); // Wrong size
+ assert!(!validate_sizes(100, 100));
+ assert!(!validate_sizes(100, 200));
}
#[test]
@@ -1160,13 +940,8 @@ mod tests {
#[test]
fn test_file_encrypt_decrypt_multi_chunk() {
- // Regression test: exercises multiple chunks
- // - Multiple full chunks with MESSAGE tag
- // - Final partial chunk with FINAL tag
- // - Lookahead logic for determining is_final flag
let key = test_key();
- // 2 full chunks + 1000 bytes (total: ~8MB + 1000)
let size = ENCRYPTION_CHUNK_SIZE * 2 + 1000;
let plaintext: Vec<u8> = (0..size).map(|i| (i % 256) as u8).collect();
@@ -1174,8 +949,6 @@ mod tests {
let mut reader = Cursor::new(&plaintext);
let header = encrypt_file(&mut reader, &mut encrypted, &key).expect("encrypt_file failed");
- // Verify ciphertext size: 2 full chunks + 1 partial chunk
- // Each chunk adds ABYTES overhead
let expected_ct_size = 2 * DECRYPTION_CHUNK_SIZE + (1000 + ABYTES);
assert_eq!(
encrypted.len(),
@@ -1193,8 +966,6 @@ mod tests {
#[test]
fn test_file_encrypt_decrypt_exact_chunk_boundary() {
- // Edge case: plaintext exactly at chunk boundary.
- // The last full chunk must be tagged FINAL (no extra empty FINAL chunk).
let key = test_key();
let plaintext: Vec<u8> = (0..ENCRYPTION_CHUNK_SIZE)
@@ -1206,7 +977,6 @@ mod tests {
let header = encrypt_file(&mut reader, &mut encrypted, &key).expect("encrypt_file failed");
assert_eq!(encrypted.len(), DECRYPTION_CHUNK_SIZE);
- // Should match estimate
assert_eq!(encrypted.len(), estimate_encrypted_size(plaintext.len()));
let mut decrypted = Vec::new();
@@ -1218,7 +988,6 @@ mod tests {
#[test]
fn test_file_encrypt_decrypt_empty() {
- // Edge case: empty file
let key = test_key();
let plaintext: Vec<u8> = Vec::new();
@@ -1226,7 +995,6 @@ mod tests {
let mut reader = Cursor::new(&plaintext);
let header = encrypt_file(&mut reader, &mut encrypted, &key).expect("encrypt_file failed");
- // Should be exactly one empty FINAL chunk
assert_eq!(encrypted.len(), ABYTES);
let mut decrypted = Vec::new();
@@ -1250,11 +1018,8 @@ mod tests {
assert_eq!(decrypted, plaintext);
}
- // Truncation detection tests for decrypt_file
-
#[test]
fn test_decrypt_file_truncation_empty_ciphertext() {
- // Test that decrypt_file detects truncation when there's no ciphertext at all
let key = test_key();
let header = Header::from_bytes([0u8; Header::BYTES]);
let empty_ciphertext: &[u8] = &[];
@@ -1272,17 +1037,13 @@ mod tests {
#[test]
fn test_decrypt_file_truncation_at_chunk_boundary() {
- // SECURITY TEST: Verify decrypt_file detects truncation at chunk boundary
- // This tests the case where we have a valid MESSAGE chunk but no FINAL chunk
let key = test_key();
let plaintext = b"Test message for truncation detection";
- // Create a valid encrypted chunk with MESSAGE tag (not FINAL)
let mut encryptor = Encryptor::new(&key);
let header = *encryptor.header();
let encrypted_chunk = encryptor.push(plaintext, false).expect("push failed");
- // Decrypt should fail because there's no FINAL tag
let mut reader = Cursor::new(&encrypted_chunk);
let mut output = Vec::new();
let result = decrypt_file(&mut reader, &mut output, &header, &key);
@@ -1296,25 +1057,20 @@ mod tests {
#[test]
fn test_decrypt_file_truncation_via_encrypt_file() {
- // Test truncation detection when truncating output from encrypt_file
let key = test_key();
let plaintext = b"Test data that will be truncated";
- // Encrypt using encrypt_file to get proper format
let mut encrypted = Vec::new();
let mut reader = Cursor::new(plaintext.as_slice());
let header = encrypt_file(&mut reader, &mut encrypted, &key).expect("encrypt_file failed");
- // Truncate the ciphertext (remove the last few bytes which contain MAC/tag info)
let truncated_len = encrypted.len() - 5;
let truncated = &encrypted[..truncated_len];
- // Decrypt should fail with authentication error (truncated ciphertext)
let mut reader = Cursor::new(truncated);
let mut output = Vec::new();
let result = decrypt_file(&mut reader, &mut output, &header, &key);
- // The truncated ciphertext will fail MAC verification
assert!(
result.is_err(),
"Expected error from truncated ciphertext, got {:?}",
@@ -1324,7 +1080,6 @@ mod tests {
#[test]
fn test_decrypt_file_valid_single_chunk() {
- // Verify that a valid single FINAL chunk works
let key = test_key();
let plaintext = b"Valid single chunk";
@@ -1365,12 +1120,10 @@ mod tests {
let key = test_key();
let plaintext: Vec<u8> = (0..5000).map(|i| (i % 256) as u8).collect();
- // Encrypt using encrypt_file
let mut encrypted = Vec::new();
let mut reader = Cursor::new(&plaintext);
let header = encrypt_file(&mut reader, &mut encrypted, &key).expect("encrypt_file failed");
- // Decrypt using decrypt_file
let mut reader = Cursor::new(&encrypted);
let mut output = Vec::new();
decrypt_file(&mut reader, &mut output, &header, &key).expect("decrypt_file failed");
@@ -1380,7 +1133,6 @@ mod tests {
#[test]
fn test_decrypt_file_data_truncation() {
- // Test that decrypt_file_data also detects truncation (it calls decrypt_file)
let key = test_key();
let plaintext = b"Test decrypt_file_data truncation";
@@ -1439,8 +1191,6 @@ mod tests {
);
}
- // Size estimation consistency tests
-
#[test]
fn test_encrypt_file_size_matches_estimate() {
let key = test_key();
@@ -1471,8 +1221,6 @@ mod tests {
#[test]
fn test_encrypt_file_and_streaming_encryptor_same_size() {
- // Verify encrypt_file and StreamingEncryptor produce same ciphertext sizes
- // for the edge case of exact chunk multiple
let key = test_key();
for multiplier in [0, 1, 2, 3] {
@@ -1480,16 +1228,14 @@ mod tests {
for &e in &extra {
let size = ENCRYPTION_CHUNK_SIZE * multiplier + e;
if size > ENCRYPTION_CHUNK_SIZE * 3 {
- continue; // Skip very large sizes for test speed
+ continue;
}
let plaintext: Vec<u8> = (0..size).map(|i| (i % 256) as u8).collect();
- // encrypt_file
let mut enc_file = Vec::new();
let mut reader = Cursor::new(&plaintext);
encrypt_file(&mut reader, &mut enc_file, &key).expect("encrypt_file failed");
- // StreamingEncryptor
let mut enc_stream = Vec::new();
{
let mut encryptor =
@@ -1521,7 +1267,6 @@ mod tests {
#[test]
fn test_validate_sizes_with_encrypt_file() {
- // Verify validate_sizes works correctly with encrypt_file output
let key = test_key();
for size in [0, 100, ENCRYPTION_CHUNK_SIZE, ENCRYPTION_CHUNK_SIZE + 500] {
diff --git a/rust/crates/core/src/crypto/types.rs b/rust/crates/core/src/crypto/types.rs
index 0aa6ab5e7d..54f11a32c1 100644
--- a/rust/crates/core/src/crypto/types.rs
+++ b/rust/crates/core/src/crypto/types.rs
@@ -1,46 +1,25 @@
-//! Typed key material and related fixed-size values.
-//!
-//! These newtypes carry their size in the type, so length validation happens
-//! once, at the boundary where raw bytes enter ([`Key::try_from_slice`] and
-//! friends), rather than inside every operation. Secret types zeroize on drop
-//! and redact their `Debug` output; non-secret types (`Nonce`, `Salt`,
-//! [`Header`]) are plain `Copy` values.
-
use rand_core::{OsRng, RngCore};
use subtle::ConstantTimeEq;
use zeroize::{Zeroize, ZeroizeOnDrop};
use crate::crypto::{Error, Result, SecretVec};
-/// A 256-bit symmetric encryption key.
-///
-/// One key type serves the secretbox, blob and stream operations: both
-/// algorithm families take 256-bit keys, and Ente's data model shares key
-/// material across them (e.g. a collection key wraps file keys via secretbox
-/// and encrypts collection metadata via blob).
-///
-/// `Clone` is provided because real pipelines cache and share keys; `Copy` is
-/// deliberately not, so every duplication of secret material is explicit.
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
pub struct Key([u8; Self::BYTES]);
impl Key {
- /// Size of a key in bytes.
pub const BYTES: usize = 32;
- /// Generate a new random key.
pub fn generate() -> Self {
let mut bytes = [0u8; Self::BYTES];
OsRng.fill_bytes(&mut bytes);
Self(bytes)
}
- /// Wrap an existing 32-byte array as a key.
pub fn from_bytes(bytes: [u8; Self::BYTES]) -> Self {
Self(bytes)
}
- /// Construct a key from a byte slice, validating its length.
pub fn try_from_slice(bytes: &[u8]) -> Result<Self> {
Ok(Self(bytes.try_into().map_err(|_| {
Error::InvalidKeyLength {
@@ -50,13 +29,11 @@ impl Key {
})?))
}
- /// The raw key bytes.
pub fn as_bytes(&self) -> &[u8; Self::BYTES] {
&self.0
}
}
-/// Consumes the source, so it zeroizes on drop.
impl TryFrom<SecretVec> for Key {
type Error = Error;
@@ -72,7 +49,6 @@ impl std::fmt::Debug for Key {
}
impl PartialEq for Key {
- /// Constant-time comparison.
fn eq(&self, other: &Self) -> bool {
self.0.ct_eq(&other.0).into()
}
@@ -80,27 +56,22 @@ impl PartialEq for Key {
impl Eq for Key {}
-/// A 192-bit SecretBox nonce. Not secret.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Nonce([u8; Self::BYTES]);
impl Nonce {
- /// Size of a nonce in bytes.
pub const BYTES: usize = 24;
- /// Generate a new random nonce.
pub fn generate() -> Self {
let mut bytes = [0u8; Self::BYTES];
OsRng.fill_bytes(&mut bytes);
Self(bytes)
}
- /// Wrap an existing 24-byte array as a nonce.
pub fn from_bytes(bytes: [u8; Self::BYTES]) -> Self {
Self(bytes)
}
- /// Construct a nonce from a byte slice, validating its length.
pub fn try_from_slice(bytes: &[u8]) -> Result<Self> {
Ok(Self(bytes.try_into().map_err(|_| {
Error::InvalidNonceLength {
@@ -110,33 +81,27 @@ impl Nonce {
})?))
}
- /// The raw nonce bytes.
pub fn as_bytes(&self) -> &[u8; Self::BYTES] {
&self.0
}
}
-/// A 128-bit key derivation salt. Not secret.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Salt([u8; Self::BYTES]);
impl Salt {
- /// Size of a salt in bytes.
pub const BYTES: usize = 16;
- /// Generate a new random salt.
pub fn generate() -> Self {
let mut bytes = [0u8; Self::BYTES];
OsRng.fill_bytes(&mut bytes);
Self(bytes)
}
- /// Wrap an existing 16-byte array as a salt.
pub fn from_bytes(bytes: [u8; Self::BYTES]) -> Self {
Self(bytes)
}
- /// Construct a salt from a byte slice, validating its length.
pub fn try_from_slice(bytes: &[u8]) -> Result<Self> {
Ok(Self(bytes.try_into().map_err(|_| {
Error::InvalidSaltLength {
@@ -146,25 +111,17 @@ impl Salt {
})?))
}
- /// The raw salt bytes.
pub fn as_bytes(&self) -> &[u8; Self::BYTES] {
&self.0
}
}
-/// A 192-bit SecretStream decryption header. Not secret.
-///
-/// While the exact contents are an implementation detail of the secretstream
-/// construction, it effectively contains the random nonce generated during
-/// encryption, and is required for decryption.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Header([u8; Self::BYTES]);
impl Header {
- /// Size of a header in bytes.
pub const BYTES: usize = 24;
- /// Construct a header from a byte slice, validating its length.
pub fn try_from_slice(bytes: &[u8]) -> Result<Self> {
Ok(Self(bytes.try_into().map_err(|_| {
Error::InvalidHeaderLength {
@@ -174,26 +131,21 @@ impl Header {
})?))
}
- /// Wrap an existing 24-byte array as a header.
pub fn from_bytes(bytes: [u8; Self::BYTES]) -> Self {
Self(bytes)
}
- /// The raw header bytes.
pub fn as_bytes(&self) -> &[u8; Self::BYTES] {
&self.0
}
}
-/// An X25519 public key. Not secret.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PublicKey([u8; Self::BYTES]);
impl PublicKey {
- /// Size of a public key in bytes.
pub const BYTES: usize = 32;
- /// Construct a public key from a byte slice, validating its length.
pub fn try_from_slice(bytes: &[u8]) -> Result<Self> {
Ok(Self(bytes.try_into().map_err(|_| {
Error::InvalidKeyLength {
@@ -203,38 +155,28 @@ impl PublicKey {
})?))
}
- /// Wrap an existing 32-byte array as a public key.
pub fn from_bytes(bytes: [u8; Self::BYTES]) -> Self {
Self(bytes)
}
- /// The raw public key bytes.
pub fn as_bytes(&self) -> &[u8; Self::BYTES] {
&self.0
}
}
-/// An X25519 secret key. Zeroized on drop.
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
pub struct SecretKey([u8; Self::BYTES]);
impl SecretKey {
- /// Size of a secret key in bytes.
pub const BYTES: usize = 32;
- /// Generate a new random secret key.
pub fn generate() -> Self {
let mut bytes = [0u8; Self::BYTES];
OsRng.fill_bytes(&mut bytes);
Self(bytes)
}
- /// Deterministically derive a secret key from a 32-byte seed.
- ///
- /// The seed bytes are stored as-is and used as the X25519 secret scalar
- /// (clamping happens during scalar multiplication, per the X25519
- /// construction). Suitable for deriving stable box keys from a
- /// higher-entropy master secret.
+ // Store the seed unchanged; X25519 clamps it during scalar multiplication.
pub fn from_seed(seed: &[u8]) -> Result<Self> {
Ok(Self(seed.try_into().map_err(|_| {
Error::InvalidKeyLength {
@@ -244,18 +186,15 @@ impl SecretKey {
})?))
}
- /// Construct a secret key from a byte slice, validating its length.
pub fn try_from_slice(bytes: &[u8]) -> Result<Self> {
Self::from_seed(bytes)
}
- /// The public key corresponding to this secret key.
pub fn public_key(&self) -> PublicKey {
let secret = x25519_dalek::StaticSecret::from(self.0);
PublicKey(*x25519_dalek::PublicKey::from(&secret).as_bytes())
}
- /// The raw secret key bytes.
pub fn as_bytes(&self) -> &[u8; Self::BYTES] {
&self.0
}
@@ -268,7 +207,6 @@ impl std::fmt::Debug for SecretKey {
}
impl PartialEq for SecretKey {
- /// Constant-time comparison.
fn eq(&self, other: &Self) -> bool {
self.0.ct_eq(&other.0).into()
}
@@ -276,7 +214,6 @@ impl PartialEq for SecretKey {
impl Eq for SecretKey {}
-/// Generate random bytes of specified length.
pub fn random_bytes(len: usize) -> Vec<u8> {
let mut buf = vec![0u8; len];
OsRng.fill_bytes(&mut buf);
diff --git a/rust/crates/core/src/error.rs b/rust/crates/core/src/error.rs
index 28c940bc12..d659ec44c8 100644
--- a/rust/crates/core/src/error.rs
+++ b/rust/crates/core/src/error.rs
@@ -1,10 +1,5 @@
-//! Helpers for working with errors.
-
use std::fmt::Write;
-/// Render an error and its chain of causes as one string.
-///
-/// The causes are appended, colon separated, to the error's own message.
pub fn chain(error: &dyn std::error::Error) -> String {
let mut message = error.to_string();
let mut source = error.source();
diff --git a/rust/crates/core/src/http.rs b/rust/crates/core/src/http.rs
index 3910daffed..de7268ccbd 100644
--- a/rust/crates/core/src/http.rs
+++ b/rust/crates/core/src/http.rs
@@ -1,14 +1,3 @@
-//! HTTP client for the Ente API.
-//!
-//! These are thin wrappers over [`reqwest`] with Ente-specific ergonomics.
-//! [`Http`] is a transparent wrapper that adds nothing of its own to a request;
-//! beyond its convenience methods it exists so that a single connection pool can
-//! be shared across clients (an `Http` is cheap to clone, and clones share the
-//! pool). [`Api`] is tailored to one Ente API origin, with pluggable
-//! authentication and built-in Ente headers.
-//!
-//! The interface mirrors reqwest, so if you know reqwest you will feel at home.
-
use std::future::Future;
use std::sync::{PoisonError, RwLock};
use std::time::Duration;
@@ -36,51 +25,34 @@ const LINK_DEVICE_TOKEN: HeaderName = HeaderName::from_static("x-auth-link-devic
const CAST_ACCESS_TOKEN: HeaderName = HeaderName::from_static("x-cast-access-token");
const SPACE_SESSION_TOKEN: HeaderName = HeaderName::from_static("x-space-session-token");
-/// An error from an HTTP request.
#[derive(Error, Debug)]
pub enum Error {
- /// The request could not be sent, or the response could not be read.
#[error(transparent)]
Network(NetworkError),
- /// The server responded with a non-2xx status.
#[error("HTTP {status} at {path}")]
- Http {
- /// The HTTP status code.
- status: u16,
- /// The request path that failed, with its query stripped.
- path: String,
- },
+ Http { status: u16, path: String },
- /// The server responded with a non-2xx status, and its body carried an
- /// Ente API error code.
#[error("HTTP {status} {code} at {path}")]
Api {
- /// The HTTP status code.
status: u16,
- /// The request path that failed, with its query stripped.
path: String,
- /// The server's error code, e.g. `USER_NOT_REGISTERED`.
code: String,
},
- /// The response arrived, but its body was not the expected JSON.
#[error(transparent)]
Parse(ParseError),
}
-/// The underlying failure of a [`Network`](Error::Network) error.
#[derive(Error, Debug)]
#[error(transparent)]
pub struct NetworkError(reqwest::Error);
-/// The underlying failure of a [`Parse`](Error::Parse) error.
#[derive(Error, Debug)]
#[error(transparent)]
pub struct ParseError(serde_json::Error);
impl Error {
- /// A connection could not be established.
pub fn is_connect(&self) -> bool {
#[cfg(not(target_arch = "wasm32"))]
{
@@ -92,12 +64,10 @@ impl Error {
}
}
- /// The request timed out.
pub fn is_timeout(&self) -> bool {
matches!(self, Error::Network(e) if e.0.is_timeout())
}
- /// The HTTP status code, if the server responded with a non-2xx status.
pub fn status_code(&self) -> Option<u16> {
match self {
Error::Http { status, .. } | Error::Api { status, .. } => Some(*status),
@@ -105,8 +75,6 @@ impl Error {
}
}
- /// Returns `true` if the request failed in transit, or if the server
- /// answered with a 429 or a 5xx status.
pub fn is_retryable(&self) -> bool {
match self {
Error::Network(e) => e.0.is_request() || e.0.is_body(),
@@ -127,16 +95,12 @@ impl From<reqwest::Error> for Error {
}
}
-/// A bare HTTP client for requests to arbitrary URLs.
-///
-/// Cloning is cheap and shares one connection pool.
#[derive(Clone)]
pub struct Http {
client: reqwest::Client,
}
impl Http {
- /// Create a transport with default connect and read timeouts.
pub fn new() -> Result<Self, Error> {
let builder = reqwest::Client::builder();
#[cfg(not(target_arch = "wasm32"))]
@@ -148,27 +112,22 @@ impl Http {
})
}
- /// Start a GET request to `url`.
pub fn get(&self, url: &str) -> RequestBuilder {
self.request(Method::GET, url)
}
- /// Start a POST request to `url`.
pub fn post(&self, url: &str) -> RequestBuilder {
self.request(Method::POST, url)
}
- /// Start a PUT request to `url`.
pub fn put(&self, url: &str) -> RequestBuilder {
self.request(Method::PUT, url)
}
- /// Start a DELETE request to `url`.
pub fn delete(&self, url: &str) -> RequestBuilder {
self.request(Method::DELETE, url)
}
- /// Start a HEAD request to `url`.
pub fn head(&self, url: &str) -> RequestBuilder {
self.request(Method::HEAD, url)
}
@@ -178,27 +137,15 @@ impl Http {
}
}
-/// How an [`Api`] authenticates its requests.
-///
-/// An `Api` uses a single scheme for its lifetime. To act as more than one
-/// identity at once, hold several `Api`s over the same [`Http`].
#[derive(ZeroizeOnDrop)]
pub enum Auth {
- /// A logged-in user, sent as the `X-Auth-Token` header.
User(String),
- /// A viewer of a public album, sent as `X-Auth-Access-Token` with an optional
- /// password JWT and link-device token.
PublicAlbum {
- /// The album access token.
access_token: String,
- /// The password-protected album's JWT, if the album has a password.
jwt: Option<String>,
- /// The link-device token, if one has been issued.
link_device: Option<String>,
},
- /// A cast session, sent as the `X-Cast-Access-Token` header.
Cast(String),
- /// A Space browser session, sent as the `X-Space-Session-Token` header.
SpaceSession(String),
}
@@ -241,22 +188,15 @@ fn sensitive_header(
}
}
-/// Settings for building an [`Api`].
pub struct ApiConfig {
- /// The Ente API origin: scheme, host, and port, e.g. `https://api.ente.com`.
pub origin: String,
- /// The client package, sent as `X-Client-Package` (e.g. `io.ente.photos`).
pub client_package: Option<String>,
- /// The client version, sent as `X-Client-Version`.
pub client_version: Option<String>,
- /// The user agent to send. Ignored on wasm.
pub user_agent: Option<String>,
- /// The authentication to start with, or `None` to start unauthenticated.
pub auth: Option<Auth>,
}
impl ApiConfig {
- /// Config with only the origin set.
pub fn new(origin: String) -> Self {
Self {
origin,
@@ -268,10 +208,6 @@ impl ApiConfig {
}
}
-/// An Ente API client, bound to a single origin.
-///
-/// Requests take a path relative to that origin and automatically carry the Ente
-/// client headers and the credentials of the [`Auth`] scheme.
pub struct Api {
http: Http,
origin: String,
@@ -283,7 +219,6 @@ pub struct Api {
}
impl Api {
- /// Build a client over `http`, sharing its connection pool.
pub fn new(http: Http, config: ApiConfig) -> Self {
Self {
http,
@@ -296,42 +231,34 @@ impl Api {
}
}
- /// The bare transport underneath, for requests to other hosts.
pub fn http(&self) -> &Http {
&self.http
}
- /// Change the authentication used for subsequent requests, e.g. after login.
pub fn set_auth(&self, auth: Option<Auth>) {
*self.auth.write().unwrap_or_else(PoisonError::into_inner) = auth;
}
- /// Start a GET request to `path`, relative to the origin.
pub fn get(&self, path: &str) -> RequestBuilder {
self.request(Method::GET, path)
}
- /// Start a POST request to `path`, relative to the origin.
pub fn post(&self, path: &str) -> RequestBuilder {
self.request(Method::POST, path)
}
- /// Start a PUT request to `path`, relative to the origin.
pub fn put(&self, path: &str) -> RequestBuilder {
self.request(Method::PUT, path)
}
- /// Start a DELETE request to `path`, relative to the origin.
pub fn delete(&self, path: &str) -> RequestBuilder {
self.request(Method::DELETE, path)
}
- /// Start a HEAD request to `path`, relative to the origin.
pub fn head(&self, path: &str) -> RequestBuilder {
self.request(Method::HEAD, path)
}
- /// Check that the server is reachable.
pub async fn ping(&self) -> Result<PingResponse, Error> {
self.get("/ping")
.send()
@@ -363,69 +290,47 @@ impl Api {
}
}
-/// A request under construction.
-///
-/// Configure it by chaining methods, then [`send`](Self::send) it.
#[must_use = "a request is only sent when you call send()"]
pub struct RequestBuilder(reqwest::RequestBuilder);
impl RequestBuilder {
- /// Add URL query parameters, serialized from any [`Serialize`] value with
- /// `serde_urlencoded`.
pub fn query<Q: Serialize + ?Sized>(self, query: &Q) -> Self {
Self(self.0.query(query))
}
- /// Add a header.
pub fn header(self, name: &str, value: &str) -> Self {
Self(self.0.header(name, value))
}
- /// Set the body to `body` serialized as JSON, with a JSON `Content-Type`.
pub fn json<B: Serialize + ?Sized>(self, body: &B) -> Self {
Self(self.0.json(body))
}
- /// Set the body to raw bytes.
pub fn body(self, body: Vec<u8>) -> Self {
Self(self.0.body(body))
}
- /// Send the request, returning the [`Response`] for any status.
pub async fn send(self) -> Result<Response, Error> {
Ok(Response(self.0.send().await?))
}
}
-/// The response to a sent request.
-///
-/// The usual flow is to call [`error_for_status`](Self::error_for_status) to
-/// turn a non-2xx status into an error, then read the body with
-/// [`json`](Self::json), [`text`](Self::text), [`bytes`](Self::bytes), or
-/// [`bytes_stream`](Self::bytes_stream).
-///
-/// The [`status`](Self::status) and [`header`](Self::header)s are also available
-/// directly.
#[derive(Debug)]
pub struct Response(reqwest::Response);
impl Response {
- /// The HTTP status code.
pub fn status(&self) -> u16 {
self.0.status().as_u16()
}
- /// The value of a response header, if present and valid UTF-8.
pub fn header(&self, name: &str) -> Option<&str> {
self.0.headers().get(name).and_then(|v| v.to_str().ok())
}
- /// All the response headers.
pub fn headers(&self) -> &reqwest::header::HeaderMap {
self.0.headers()
}
- /// Return an [`Error::Http`] if the status is not 2xx, otherwise the response.
pub fn error_for_status(self) -> Result<Self, Error> {
if self.0.status().is_success() {
Ok(self)
@@ -437,13 +342,6 @@ impl Response {
}
}
- /// Return an [`Error::Api`] carrying the server's error code if the
- /// status is not 2xx, otherwise the response.
- ///
- /// A variant of [`error_for_status`](Self::error_for_status) for call
- /// sites that need to act on the error code that the Ente API includes
- /// in its error responses. When the body does not carry a code, this
- /// returns the same [`Error::Http`] that `error_for_status` would.
pub async fn error_for_code(self) -> Result<Self, Error> {
if self.0.status().is_success() {
return Ok(self);
@@ -460,17 +358,14 @@ impl Response {
}
}
- /// Read the whole body and deserialize it as JSON.
pub async fn json<T: DeserializeOwned>(self) -> Result<T, Error> {
serde_json::from_slice(&self.0.bytes().await?).map_err(|e| Error::Parse(ParseError(e)))
}
- /// Read the whole body as text.
pub async fn text(self) -> Result<String, Error> {
Ok(self.0.text().await?)
}
- /// Read the whole body as bytes.
pub async fn bytes(self) -> Result<Vec<u8>, Error> {
Ok(self.0.bytes().await?.into())
}
@@ -487,7 +382,6 @@ mod body_stream {
use super::{Error, Response};
impl Response {
- /// Stream the body in chunks instead of buffering it, for large downloads.
pub fn bytes_stream(self) -> impl Stream<Item = Result<Bytes, Error>> + Send {
BytesStream(Box::pin(self.0.bytes_stream()))
}
@@ -507,31 +401,20 @@ mod body_stream {
}
}
-/// The Ente API's error body, e.g. `{"code": "USER_NOT_REGISTERED", ...}`.
#[derive(Deserialize)]
struct ApiErrorEnvelope {
code: String,
}
-/// The reply from the `/ping` endpoint.
#[derive(Deserialize, Debug)]
pub struct PingResponse {
- /// Always `"pong"`.
pub message: String,
- /// The server's git commit hash.
pub id: String,
}
-/// How persistently to retry a failed request.
-///
-/// Both profiles make one original attempt and up to three retries. The
-/// delays match the web client's retry schedules.
#[derive(Clone, Copy, Debug)]
pub enum RetryProfile {
- /// For requests a user is waiting on. Retries after 2, 5, and 10 seconds.
Interactive,
- /// For unattended work, where waiting longer handles remote hiccups
- /// better. Retries after 10, 30, and 120 seconds.
Background,
}
@@ -544,14 +427,6 @@ impl RetryProfile {
}
}
-/// Run `operation`, retrying failures per [`RetryProfile::Interactive`].
-///
-/// A failure is retried when [`Error::is_retryable`] says so: the request
-/// failed in transit, or the server answered with a 429 or a 5xx status.
-/// Any other error returns immediately.
-///
-/// Each retry runs the whole closure again, so wrap only operations that
-/// are safe to repeat.
pub async fn retry<T, F, Fut>(operation: F) -> Result<T, Error>
where
F: FnMut() -> Fut,
@@ -560,7 +435,7 @@ where
retry_with_profile(RetryProfile::Interactive, operation).await
}
-/// Like [`retry`](retry()), but with an explicitly chosen profile.
+// The closure can run four times; callers must only retry operations safe to repeat.
pub async fn retry_with_profile<T, F, Fut>(profile: RetryProfile, operation: F) -> Result<T, Error>
where
F: FnMut() -> Fut,
diff --git a/rust/crates/core/src/io.rs b/rust/crates/core/src/io.rs
index 4dddb14853..49c322dc2d 100644
--- a/rust/crates/core/src/io.rs
+++ b/rust/crates/core/src/io.rs
@@ -1,33 +1,13 @@
-//! I/O adapters used alongside the crypto routines.
-
use std::io::{self, Write};
use md5::{Digest, Md5};
-/// A write-through adapter that computes the MD5 digest of everything written.
-///
-/// Wrap the destination writer in this to obtain, in a single pass, the MD5 of
-/// a produced byte stream — e.g. the `Content-MD5` of encrypted file content
-/// required by object-store uploads:
-///
-/// ```rust
-/// use std::io::Cursor;
-/// use ente_core::crypto::{Key, stream};
-/// use ente_core::io::Md5Writer;
-///
-/// let key = Key::generate();
-/// let mut writer = Md5Writer::new(Vec::new());
-/// let header = stream::encrypt_file(&mut Cursor::new(b"data"), &mut writer, &key).unwrap();
-/// let (encrypted, md5) = writer.finalize();
-/// # let _ = (header, encrypted, md5);
-/// ```
pub struct Md5Writer<W: Write> {
inner: W,
digest: Md5,
}
impl<W: Write> Md5Writer<W> {
- /// Wrap a writer, computing the MD5 of all bytes written through it.
pub fn new(inner: W) -> Self {
Self {
inner,
@@ -35,7 +15,6 @@ impl<W: Write> Md5Writer<W> {
}
}
- /// Unwrap the inner writer and return it along with the 16-byte digest.
pub fn finalize(self) -> (W, [u8; 16]) {
(self.inner, self.digest.finalize().into())
}
diff --git a/rust/crates/core/src/lib.rs b/rust/crates/core/src/lib.rs
index 57b4abfd38..8897b59782 100644
--- a/rust/crates/core/src/lib.rs
+++ b/rust/crates/core/src/lib.rs
@@ -1,8 +1,3 @@
-//! Core library for Ente clients.
-//!
-//! This crate provides shared functionality for all Ente client implementations,
-//! including cryptography, HTTP utilities, and common data structures.
-
pub mod b64;
pub mod crypto;
pub mod error;
diff --git a/rust/crates/core/src/urls.rs b/rust/crates/core/src/urls.rs
index b2bfbe02c6..5657c90577 100644
--- a/rust/crates/core/src/urls.rs
+++ b/rust/crates/core/src/urls.rs
@@ -1,13 +1,7 @@
-//! URL construction utilities.
-
-/// Production API origin.
pub const PRODUCTION_API_ORIGIN: &str = "https://api.ente.com";
-/// Append a trusted endpoint path to the configured API origin.
-///
-/// The configured value is expected to be an origin and endpoint paths are
-/// trusted. Any path prefix is retained as a best-effort convenience for
-/// self-hosted deployments.
+// `origin` must be an origin. Preserving path prefixes is a best-effort
+// convenience for self-hosters.
pub(crate) fn api_url(origin: &str, path: &str) -> String {
format!(
"{}/{}",
@@ -16,7 +10,6 @@ pub(crate) fn api_url(origin: &str, path: &str) -> String {
)
}
-/// Generate the download URL for a file.
pub fn file_download_url(api_origin: &str, file_id: i64) -> String {
if api_origin == PRODUCTION_API_ORIGIN {
format!("https://files.ente.com/?fileID={}", file_id)