diff --git a/Cargo.lock b/Cargo.lock index fd2b361..2d60dcf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "aead" version = "0.6.1" @@ -242,12 +248,24 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + [[package]] name = "byteorder" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + [[package]] name = "bytes" version = "1.12.1" @@ -417,6 +435,15 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" +[[package]] +name = "crc32fast" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +dependencies = [ + "cfg-if", +] + [[package]] name = "crossbeam-queue" version = "0.3.14" @@ -652,6 +679,15 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + [[package]] name = "fiat-crypto" version = "0.3.0" @@ -670,6 +706,17 @@ version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + [[package]] name = "flume" version = "0.12.0" @@ -1134,6 +1181,32 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "image-webp", + "moxcms", + "num-traits", + "png", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -1370,6 +1443,26 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "mio" version = "1.2.4" @@ -1381,6 +1474,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + [[package]] name = "multimap" version = "0.10.1" @@ -1557,6 +1660,19 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + [[package]] name = "poly1305" version = "0.9.1" @@ -1661,6 +1777,18 @@ dependencies = [ "prost", ] +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + [[package]] name = "quinn" version = "0.11.12" @@ -2223,6 +2351,12 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "simd_cesu8" version = "1.2.0" @@ -2983,7 +3117,9 @@ dependencies = [ "axum", "cookie", "ed25519-dalek", + "image", "hex", + "hmac", "lettre", "oauth2", "rand 0.10.3", @@ -3461,11 +3597,32 @@ dependencies = [ "yoke", "zerofrom", "zerovec-derive", +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + ] [[package]] name = "zerovec-derive" version = "0.11.7" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ diff --git a/deploy/central/README.md b/deploy/central/README.md index 499be11..4a1dd41 100644 --- a/deploy/central/README.md +++ b/deploy/central/README.md @@ -2,7 +2,8 @@ Current target: `central.loki-code.dev`, Ubuntu22.04, Nginx443 terminating HTTPS; Hub listener `127.0.0.1:37623` (randomly selected free port). The foundation has no -public email-send/auth/registry/friends/DM endpoints. See `hub/README.md` for exact +public email-send/registry/friends/DM endpoints. Sign-in endpoints are GitHub and, when SMTP +is configured, email one-time codes (`hub/AUTH.md`). See `hub/README.md` for exact capability status. SMTP sender display name is Vnox, address `noreply@loki-code.dev`. ## Layout diff --git a/docs/00-status.md b/docs/00-status.md index 67eb2fb..b305310 100644 --- a/docs/00-status.md +++ b/docs/00-status.md @@ -13,6 +13,8 @@ Last updated: 2026-10-24. - Authenticated, encrypted UDP voice relay in voice-node. - Voice access is revoked when a channel is deleted, a member is kicked or permissions change. - Senders get acknowledgements for their own chat messages. +- Hub email sign-in by one-time code (HMAC-protected, rate-limited; enabled only when SMTP is configured; code-ready, not yet enabled in production). Handle selection after first sign-in is not implemented. +- Hub own avatar (web): upload, remove and public serving of a re-encoded 256x256 PNG; code-ready, not deployed. Backup rotation to 30 days for deleted data is decided but not implemented. - Channel webhooks, GitHub sign-in, hub service, screen sharing and media broadcast. - `cargo audit`: no known vulnerabilities in both workspaces (2026-10-24). diff --git a/docs/design/accounts-and-avatars.md b/docs/design/accounts-and-avatars.md index 6c40d74..dea760b 100644 --- a/docs/design/accounts-and-avatars.md +++ b/docs/design/accounts-and-avatars.md @@ -10,6 +10,8 @@ Связать второй способ входа можно из аутентифицированного аккаунта после повторного подтверждения; требуется доказать владение добавляемым способом. Отвязка последнего способа входа запрещена без настроенного восстановления. Добавление/отзыв устройств, email и способов входа сопровождаются уведомлениями. +**Статус реализации (Hub, этап 1):** вход по почте с одноразовым кодом работает (`hub/AUTH.md`). Новый аккаунт получает сгенерированный handle `u_...` и нейтральное имя; выбор handle и отображаемого имени после первого подтверждения ещё не реализован. Собственный аватар можно загрузить и убрать на странице аккаунта сайта (реализовано в Hub, см. ниже). Связывание второго способа входа, passkey/MFA и уведомления о новых способах входа тоже впереди. + ## GitHub OAuth Клиент открывает системный браузер. Hub хранит OAuth client_secret, принимает provider callback, проверяет state/PKCE и получает подтверждённую identity через GitHub API. Клиенту возвращается одноразовый код Vnox для конкретного login attempt с PKCE, а не GitHub bearer token в URL. @@ -40,6 +42,8 @@ Email подтверждает контроль почтового ящика, Первоначальные ограничения клиента: исходный файл до10MiB, сторона до4096px, лимит памяти декодера64MiB. Ограничения проверяются при чтении/декодировании, ошибки показываются в диалоге. SVG, внешние URL и анимации не поддерживаются в первой версии. Оригинал не сохраняется после нормализации; выходной PNG не переносит исходные EXIF/геометки. Отмена и ошибка не заменяют прежний аватар; запись атомарная. +**Реализация в Hub (веб):** `POST/DELETE /v1/account/avatar`, `GET /v1/avatars/` (`hub/AUTH.md`). Hub принимает PNG/JPEG/WebP до 2 МиБ и 4096 px, проверяет тип по сигнатуре, полностью декодирует и заново кодирует в PNG 256×256 без метаданных, хранит один аватар на аккаунт в SQLite BLOB; адрес содержит хеш содержимого и кэшируется как immutable. Для сайта кадрирование делается на canvas до отправки, Hub дополнительно обрезает по центру. Для аккаунта GitHub «Убрать фото» возвращает аватар GitHub. Клиент Vnox пока не использует этот API. Резервные копии базы могут хранить удалённые данные до 30 дней (решение владельца; ротацию копий ещё нужно реализовать). + До Hub API аватар собственный/локальный и не выдаётся за синхронизированный с друзьями. Впоследствии Hub принимает нормализованное изображение, повторно проверяет/перекодирует его, обновляет avatar_id/revision и доступ по политике профиля. Изображение хранится до замены/удаления профиля; правило DM-вложения «4 дня» не применяется. Старые версии и кэши очищаются по отдельной политике. ## Ещё решения до публичного запуска diff --git a/gateway/src/proto/crypto/cipher.rs b/gateway/src/proto/crypto/cipher.rs deleted file mode 100644 index 2fd0206..0000000 --- a/gateway/src/proto/crypto/cipher.rs +++ /dev/null @@ -1,104 +0,0 @@ -use chacha20poly1305::{ - ChaCha20Poly1305, Key, KeyInit, Nonce, - aead::{Aead, Payload}, -}; - -pub(super) fn make_nonce(cid: &[u8; 8], seq: u64) -> [u8; 12] { - let mut nonce = [0u8; 12]; - nonce[..8].copy_from_slice(cid); - nonce[8..12].copy_from_slice(&(seq as u32).to_le_bytes()); - nonce -} - -pub(super) fn encrypt_with_key( - key: &[u8; 32], - cid: &[u8; 8], - seq: u64, - plaintext: &[u8], -) -> Vec { - encrypt_with_aad(key, cid, seq, plaintext, &[]) -} - -pub(super) fn encrypt_with_aad( - key: &[u8; 32], - cid: &[u8; 8], - seq: u64, - plaintext: &[u8], - aad: &[u8], -) -> Vec { - let cipher = ChaCha20Poly1305::new(&Key::from(*key)); - let nonce_bytes = make_nonce(cid, seq); - let nonce = Nonce::from(nonce_bytes); - cipher - .encrypt( - &nonce, - Payload { - msg: plaintext, - aad, - }, - ) - .expect("ChaCha20-Poly1305 encryption is infallible") -} - -pub(super) fn decrypt_with_key( - key: &[u8; 32], - cid: &[u8; 8], - seq: u64, - ciphertext: &[u8], -) -> anyhow::Result> { - decrypt_with_aad(key, cid, seq, ciphertext, &[]) -} - -pub(super) fn decrypt_with_aad( - key: &[u8; 32], - cid: &[u8; 8], - seq: u64, - ciphertext: &[u8], - aad: &[u8], -) -> anyhow::Result> { - let cipher = ChaCha20Poly1305::new(&Key::from(*key)); - let nonce_bytes = make_nonce(cid, seq); - let nonce = Nonce::from(nonce_bytes); - cipher - .decrypt( - &nonce, - Payload { - msg: ciphertext, - aad, - }, - ) - .map_err(|e| anyhow::anyhow!("decryption failed: {e:?}")) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn wire_ciphertext_matches_independent_chacha20_poly1305_vector() { - let key = std::array::from_fn(|index| index as u8); - let cid = [0x07, 0x00, 0x00, 0x00, 0x40, 0x41, 0x42, 0x43]; - let seq = 0x4746_4544; - let plaintext = b"VNOX dependency migration"; - // Cross-checked with Python cryptography's ChaCha20Poly1305 implementation, - // IETF nonce 070000004041424344454647, and empty associated data. - let expected = hex::decode( - "1fa23e7a312509b0fc8729521811348ff880daa5598c43a57635975f81278abdf4461b25af86aee1c3", - ) - .unwrap(); - assert_eq!(encrypt_with_key(&key, &cid, seq, plaintext), expected); - assert_eq!( - decrypt_with_key(&key, &cid, seq, &expected).unwrap(), - plaintext - ); - } - - #[test] - fn tampered_ciphertext_is_rejected() { - let key = [7; 32]; - let cid = [9; 8]; - let mut ciphertext = encrypt_with_key(&key, &cid, 42, b"authenticated"); - ciphertext[0] ^= 1; - assert!(decrypt_with_key(&key, &cid, 42, &ciphertext).is_err()); - } -} diff --git a/gateway/src/proto/crypto/mod.rs b/gateway/src/proto/crypto/mod.rs deleted file mode 100644 index 39b4ed2..0000000 --- a/gateway/src/proto/crypto/mod.rs +++ /dev/null @@ -1,128 +0,0 @@ -mod cipher; - -use hkdf::Hkdf; -use sha2::Sha256; -use x25519_dalek::{EphemeralSecret, PublicKey, SharedSecret}; - -#[derive(Clone)] -pub struct SessionCrypto { - c2s_key: [u8; 32], - s2c_key: [u8; 32], - cid: [u8; 8], -} - -impl SessionCrypto { - pub fn derive(shared_secret: &[u8; 32], session_id: &str) -> Self { - let salt = b"VNOX-LNEx-KDF-v2"; - let hk = Hkdf::::new(Some(salt), shared_secret); - - let mut keys = [0u8; 64]; - hk.expand(b"session-keys", &mut keys) - .expect("64 bytes is within HKDF max"); - - let c2s_key: [u8; 32] = keys[..32].try_into().unwrap(); - let s2c_key: [u8; 32] = keys[32..64].try_into().unwrap(); - - use sha2::Digest; - let hash = Sha256::digest(session_id.as_bytes()); - let cid: [u8; 8] = hash[..8].try_into().unwrap(); - - Self { - c2s_key, - s2c_key, - cid, - } - } - - pub fn encrypt_s2c(&self, seq: u64, plaintext: &[u8]) -> Vec { - cipher::encrypt_with_key(&self.s2c_key, &self.cid, seq, plaintext) - } - - pub fn decrypt_c2s(&self, seq: u64, ciphertext: &[u8]) -> anyhow::Result> { - cipher::decrypt_with_key(&self.c2s_key, &self.cid, seq, ciphertext) - } - - #[cfg(test)] - pub(crate) fn encrypt_c2s_frame(&self, seq: u64, plaintext: &[u8], header: &[u8]) -> Vec { - cipher::encrypt_with_aad(&self.c2s_key, &self.cid, seq, plaintext, header) - } - pub fn encrypt_s2c_frame(&self, seq: u64, plaintext: &[u8], header: &[u8]) -> Vec { - cipher::encrypt_with_aad(&self.s2c_key, &self.cid, seq, plaintext, header) - } - pub fn decrypt_c2s_frame( - &self, - seq: u64, - ciphertext: &[u8], - header: &[u8], - ) -> anyhow::Result> { - cipher::decrypt_with_aad(&self.c2s_key, &self.cid, seq, ciphertext, header) - } - - pub fn new_ephemeral() -> (EphemeralSecret, PublicKey) { - let mut rng = rand::rng(); - let sk = EphemeralSecret::random_from_rng(&mut rng); - let pk = PublicKey::from(&sk); - (sk, pk) - } - - pub fn ecdh(secret: EphemeralSecret, peer_public: &PublicKey) -> SharedSecret { - secret.diffie_hellman(peer_public) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn encrypt_then_decrypt_roundtrip() { - let shared_secret = [0xABu8; 32]; - let crypto = SessionCrypto::derive(&shared_secret, "test-session-id"); - - let plaintext = b"hello encrypted world"; - let seq = 42; - - let ciphertext = crypto.encrypt_s2c(seq, plaintext); - assert_ne!(ciphertext, plaintext); - assert!(ciphertext.len() > plaintext.len()); - } - - #[test] - fn different_keys_cannot_decrypt_each_other() { - let shared_secret = [0xABu8; 32]; - let crypto = SessionCrypto::derive(&shared_secret, "test-session-id"); - - let s2c_ct = crypto.encrypt_s2c(0, b"server to client"); - let result = crypto.decrypt_c2s(0, &s2c_ct); - assert!(result.is_err()); - } - - #[test] - fn different_keys_produce_different_ciphertexts() { - let secret_a = [0xAAu8; 32]; - let secret_b = [0xBBu8; 32]; - let crypto_a = SessionCrypto::derive(&secret_a, "session-a"); - let crypto_b = SessionCrypto::derive(&secret_b, "session-b"); - - let plaintext = b"same plaintext"; - let ct_a = crypto_a.encrypt_s2c(0, plaintext); - let ct_b = crypto_b.encrypt_s2c(0, plaintext); - assert_ne!(ct_a, ct_b); - } - - #[test] - fn ecdh_derives_same_secret_on_both_sides() { - let mut rng = rand::rng(); - - let alice_sk = EphemeralSecret::random_from_rng(&mut rng); - let alice_pk = PublicKey::from(&alice_sk); - - let bob_sk = EphemeralSecret::random_from_rng(&mut rng); - let bob_pk = PublicKey::from(&bob_sk); - - let alice_shared = alice_sk.diffie_hellman(&bob_pk); - let bob_shared = bob_sk.diffie_hellman(&alice_pk); - - assert_eq!(alice_shared.as_bytes(), bob_shared.as_bytes()); - } -} diff --git a/hub/AUTH.md b/hub/AUTH.md index 9f13305..ad76911 100644 --- a/hub/AUTH.md +++ b/hub/AUTH.md @@ -1,4 +1,6 @@ -# GitHub sign-in +# Hub sign-in: GitHub and email code + +## GitHub Configure `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET` together in the protected service environment. GitHub Apps and OAuth Apps both support this user authorization flow; the GitHub App private signing key is unnecessary at runtime. Register this exact callback: @@ -26,3 +28,79 @@ Back up SQLite with the issuer identity, protect backups as credentials, and app `cargo test -p vnox-hub` exercises the complete local browser flow against an injected provider, wrong-browser/replay/expiry rejection and logout CSRF. A real GitHub login requires the account owner to authorize in their browser; automated tests never impersonate consent. Provider reference: [GitHub App user authorization and PKCE](https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-a-user-access-token-for-a-github-app). GitHub App resource permissions are configured by its owner; this flow adds no OAuth scopes and only calls the public user endpoint. + +## Email sign-in (one-time code) + +Available only when SMTP is configured (`SMTP_HOST` etc., see `deploy/central/hub.env.example`); `GET /v1/info` reports `capabilities.email_auth` as `"enabled"` exactly then, otherwise `"not_enabled"` and both endpoints answer `503 email_not_configured`. No other setting is needed: the code MAC key is generated on first start as `email-auth.key` (hex, 0600) in the private data directory. + +### Browser contract + +- `POST /v1/auth/email/start` with JSON `{"email": "...", "lang": "ru"|"en"}` (`lang` optional, default `ru`, unknown values fall back to `ru`). Answers `202 {"status":"code_requested","expires_in":600,"resend_after":60}` and sets the browser-binding cookie `__Host-vnox_email` (HttpOnly, Secure, SameSite=Lax, 10 minutes). The answer is identical for addresses with and without an account: start never looks up accounts, and the code is never in the response. +- `POST /v1/auth/email/verify` with JSON `{"email": "...", "code": "12345678"}` and that cookie. On success: `200` with the same body as `GET /v1/auth/session` (`{authenticated:true,user,csrf_token}`) and the same `__Host-vnox_session` cookie (7 days, CSRF token) as GitHub. Any failure (no attempt, expired, exhausted, wrong address, wrong code, wrong browser) is the same `400 {"error":"invalid_code"}`. +- Other errors: `400 invalid_email` / `invalid_request`, `403 invalid_origin`, `429 try_later`, `503 try_later`. + +### CSRF and browser binding + +These are unauthenticated POSTs, so there is no session CSRF token to compare. They are protected by three layers: the exact `Origin` must equal `PUBLIC_BASE_URL`'s origin (as for logout); the body must be JSON with no unknown fields and at most 1 KiB (not a form a foreign page can submit without a CORS preflight); and the code is bound to a random 256-bit `__Host-` cookie created by `start`, stored only as a SHA-256 hash with the attempt. A code can be redeemed only in the browser that requested it, so a cross-site request can neither plant an attacker's login in a victim's browser nor redeem a victim's code. A new `start` from the same browser replaces its previous attempt. + +### Codes + +Eight digits from the OS CSPRNG with rejection sampling, valid for ten minutes, five verification tries. The stored value is `HMAC-SHA256(server_key, attempt_id, address_mac, code)` (length-prefixed fields), not a bare hash; a database leak alone does not allow guessing the 10^8 code space offline. Comparison is constant-time. The try counter is incremented by the same atomic `UPDATE ... RETURNING` that selects the attempt, so parallel guesses cannot exceed the limit; a correct code is consumed by an atomic `DELETE ... RETURNING`, so exactly one request wins. Pending attempts hold only the address MAC, never the address. + +### Rate limits (SQLite ledger of MACs, atomic check-and-record) + +Per address 1 per 60 s and 5 per hour; per source (`X-Forwarded-For`, as GitHub login) 10 per hour, where IPv6 sources are grouped by /64 and IPv4-mapped IPv6 counts as IPv4 (so rotating host bits does not dodge the limit; an attacker with a larger prefix or many networks still can); globally 300 per hour for new sign-ins plus a separate reserve of 100 per hour that only qualifying resends can spend. A resend qualifies when its `__Host-vnox_email` cookie belongs to a live attempt for the same normalized address with fewer than 5 failed tries, fewer than 3 earlier resends in its chain, and a chain younger than 30 minutes. The attempt is claimed by deleting it inside the same SQLite transaction that checks and records the send budgets, so the check and the reservation are atomic: parallel resends cannot both claim one attempt, chains cannot branch, and a refused request rolls the claim back. The chain counter and start time are carried to the replacement attempt. Flooding the general budget therefore cannot cut off people who are already mid sign-in, and one live attempt cannot be turned into a stream of reserve-funded mail to other addresses. It does not help people who start after the budget is exhausted; a resend that no longer qualifies, once it passes the normal budget, starts a fresh chain (each such reset costs a normal-budget send). Budget is spent when a request passes validation, even if delivery later fails. The in-memory per-IP limiter used by GitHub (20 per minute, 300 global) also applies to both endpoints. At most 4096 attempts are pending. + +### Address handling and accounts + +Addresses are trimmed and lowercased; only ASCII, a local part of `[a-z0-9._%+-]` without leading/trailing/double dots, at most 64 characters, a multi-label hostname whose last label is alphabetic, at most 254 characters in total. `+tag` is not stripped and Gmail dots are not folded. Unusual legal addresses are rejected on purpose. + +The identity is `external_identities(provider='email', subject=)`, reusing the existing table so one address maps to one account, and it can never collide with `github.com` subjects. A matching GitHub account or email is never merged automatically. A first successful verification creates an account with a generated `u_` handle and the neutral display name `Vnox user`; the local part of the address is never used. Choosing a handle and display name after registration is not implemented yet (an own avatar can be uploaded, see below) (see `design/accounts-and-avatars.md`). The address is kept in plain normalized form in `external_identities` because later features (security notices, adding a second sign-in method) need it; it is used for nothing except sending codes today. + +### Mail and logging + +The message is rendered by `mail::templates::render_email_code` (Russian or English) and contains the code but no button and no link. Delivery uses the existing TLS-only `Mailer` through the internal `CodeSender` trait; there is no endpoint to send arbitrary mail. Codes, addresses, cookies and request bodies are never logged by the application, and the Nginx `/v1/auth/` location writes no access or error logs. A delivery failure returns `503 try_later` and removes the attempt. + +### Known limits + +- A third party can use up an address's hourly budget and delay that person's email sign-in (GitHub still works). Accepted trade-off of per-address limits. +- Email proves control of a mailbox only; it is not strong authentication (see design notes on later MFA/passkeys). +- Rate-limit counters for the in-memory limiter reset on restart; the email ledger persists. +- Access to the mailbox, or to the SQLite file together with `email-auth.key` during the ten-minute window, defeats the code. +- Tests use an injected sender; real SMTP delivery has not been exercised from tests. + +## Own avatar + +A signed-in web session can set its own photo. Without one, `avatar_url` in `GET /v1/auth/session` (and in the email verify answer) is the provider's avatar (GitHub) or `null`; with one it is the same-origin path `/v1/avatars/`. + +### Contract + +- `POST /v1/account/avatar`: the body is the raw image, `Content-Type` is `image/png`, `image/jpeg` or `image/webp`. Answers `200 {"avatar_url":"/v1/avatars/"}`. +- `DELETE /v1/account/avatar`: removes the own photo. Answers `200 {"avatar_url": }`; repeating it is harmless. +- `GET /v1/avatars/`: public. `` is 64 lowercase hex characters, the SHA-256 of the stored bytes. `Cache-Control: public, max-age=31536000, immutable`, `Content-Type: image/png`, `X-Content-Type-Options: nosniff`, `Content-Security-Policy: default-src 'none'; sandbox; frame-ancestors 'none'`, `ETag`. Unknown or malformed ids give a `404` JSON error. After a replacement or removal the old URL gives `404` (browser caches may still hold it until they evict it). +- The two changing endpoints require the exact `Origin`, the session cookie and `X-CSRF-Token`, checked in that order, exactly as logout (shared `authorized` gate). All their responses, errors included, are `no-store`. +- Errors: `401 not_authenticated`, `403 invalid_origin` / `invalid_csrf`, `413 too_large`, `415 unsupported_type` / `type_mismatch`, `422 bad_dimensions` / `invalid_image`, `429 try_later`, `503 try_later`. + +### Upload pipeline + +1. Authentication, Origin and CSRF are checked before the body is read. +2. The declared `Content-Type` must be one of the three types. A cheap refusal here does not spend rate-limit budget. +3. Rate limit, in memory: 10 changes per hour per account and 30 per hour per source (`X-Forwarded-For`, /64 grouping for IPv6, as above). Uploads and removals both count; a refused request is not recorded. At most two decodes run at the same time, the rest get `429`. +4. Body limit 2 MiB: refused from `Content-Length` when announced, and the read itself stops at the limit for chunked bodies. +5. Magic bytes decide the real format (PNG, JPEG, WebP; SVG, GIF and everything else are `unsupported_type`). A different declared type is `type_mismatch`, so a renamed file does not pass. +6. The header is read first: more than 4096 or fewer than 32 pixels on a side is `bad_dimensions` before any pixel buffer exists (decoder limits: 4096 per side, 128 MiB allocation). A small file that claims 60000x60000 never allocates. +7. The image is fully decoded (corrupt or truncated data is `invalid_image`), rotated by its EXIF orientation, center-cropped to a square, resized to 256x256 (Lanczos3) and written as a new PNG (RGB, or RGBA when the source has transparency). Nothing from the source file is copied, so EXIF, GPS, ICC profiles, text chunks and trailing data are gone. The decode runs on a blocking thread. Animated sources yield a single still frame or are refused. +8. The row is written with `INSERT ... ON CONFLICT(user_id) DO UPDATE`, so there is one avatar per account and the old bytes are overwritten in the same statement. The original upload is never stored. + +### Storage + +SQLite BLOB in table `avatars` (migration `0005_avatars.sql`), keyed by `user_id` with `ON DELETE CASCADE`. Reasons: a normalized avatar is small (typically 20 to 150 KB), so the database stays small; replacement and account deletion are transactional with the account row; there is no second directory whose permissions, orphan files or backup consistency need care; the existing data-directory rules and the existing backup (database plus issuer together) cover it with no new moving parts. Files stay `0600` because they are inside the private data directory like the database itself. If avatars ever grow in number or size, serving can move to files or object storage behind the same URLs. + +The provider avatar URL stays on `accounts.avatar_url` and is the fallback after removal. + +### Known limits + +- Rate-limit counters are in memory and reset on restart. +- Avatars are public to anyone who knows the id; ids are not secret but are not listed anywhere. Identical images from two accounts share an id. +- Deleted photos can remain in database backups. The project owner decided that backups keep deleted data for up to 30 days; this needs backup rotation to be implemented and is not enforced by the Hub. +- Decoding uses the `image` crate with only the `png`, `jpeg` and `webp` features. `cargo audit` reported no advisories when this was added. Decoder bugs in these crates are the main residual risk; decoding is bounded in size, memory and concurrency. diff --git a/hub/Cargo.toml b/hub/Cargo.toml index c19956f..a1801ef 100644 --- a/hub/Cargo.toml +++ b/hub/Cargo.toml @@ -23,12 +23,15 @@ uuid = { workspace = true, features = ["serde"] } sqlx = { version = "0.9", default-features = false, features = ["sqlite", "runtime-tokio", "migrate", "macros"] } lettre = { version = "0.11.23", default-features = false, features = ["builder", "smtp-transport", "tokio1-rustls", "aws-lc-rs", "webpki-roots"] } url = "2" +# Avatar re-encoding: only PNG, JPEG and WebP decoders and the PNG encoder; no GIF, SVG or other formats. +image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "webp"] } reqwest.workspace = true sha2.workspace = true oauth2 = { version = "5", default-features = false, features = ["timing-resistant-secret-traits"] } cookie = "0.18" subtle = "2.6" +hmac.workspace = true [dev-dependencies] tempfile = "3" diff --git a/hub/README.md b/hub/README.md index 17a05f6..1c88a1a 100644 --- a/hub/README.md +++ b/hub/README.md @@ -12,12 +12,15 @@ Community messages and voice never pass through this process. - `/v1/info`: public issuer ID/key and honest feature availability. - `/`: deployment status page; `/assets/vnox-mark.svg`: approved V connection mark. - Durable SQLite schema and issuer identity with a private `0600` key file. +- Own avatar for signed-in web sessions: `POST`/`DELETE /v1/account/avatar`, public `GET /v1/avatars/` (re-encoded 256x256 PNG in SQLite, see `AUTH.md`). - TLS-only SMTP transport and HTML/plain-text transactional email templates. -Email authentication, GitHub OAuth, server registration/discovery, friends, DM -storage and marketplace API are **not enabled**. There is no public endpoint for -sending mail. Existing schema tables are foundations, not working authentication. -Template links are previews of future routes; they do not create working tokens. +GitHub OAuth and email one-time-code sign-in are implemented (`AUTH.md`); email sign-in +is reported as enabled in `/v1/info` only when SMTP is configured. Server +registration/discovery, friends, DM storage and marketplace API are **not enabled**. +There is no public endpoint for sending mail. Other schema tables are foundations. +Links in the older verify/new-device templates are previews of future routes; they do +not create working tokens. ## Configuration diff --git a/hub/migrations/0003_email_auth.sql b/hub/migrations/0003_email_auth.sql new file mode 100644 index 0000000..68dcedc --- /dev/null +++ b/hub/migrations/0003_email_auth.sql @@ -0,0 +1,26 @@ +-- Passwordless email sign-in. Email identities reuse external_identities +-- (provider='email', subject=normalized address): the (provider, subject) key already +-- guarantees one account per address and never collides with 'github.com' subjects, +-- so the two methods can never be merged implicitly. +-- +-- One pending code per browser. Only keyed MACs are stored: neither the code, nor the +-- address of a pending attempt, nor the requester's network address. +CREATE TABLE email_attempts ( + attempt_id TEXT PRIMARY KEY, + browser_hash TEXT NOT NULL UNIQUE, + email_mac TEXT NOT NULL, + code_mac TEXT NOT NULL, + failures INTEGER NOT NULL DEFAULT 0, + expires_at INTEGER NOT NULL +); +CREATE INDEX email_attempt_expiry ON email_attempts(expires_at); + +-- Sliding-window ledger for send rate limits, keyed by MAC of address / source. +CREATE TABLE email_send_log ( + email_mac TEXT NOT NULL, + source_mac TEXT NOT NULL, + sent_at INTEGER NOT NULL +); +CREATE INDEX email_send_by_address ON email_send_log(email_mac, sent_at); +CREATE INDEX email_send_by_source ON email_send_log(source_mac, sent_at); +CREATE INDEX email_send_by_time ON email_send_log(sent_at); diff --git a/hub/migrations/0004_email_resend_chain.sql b/hub/migrations/0004_email_resend_chain.sql new file mode 100644 index 0000000..0c6e0de --- /dev/null +++ b/hub/migrations/0004_email_resend_chain.sql @@ -0,0 +1,5 @@ +-- Resends from a browser with a live attempt may draw on a reserved global budget, but +-- only along a bounded chain: each attempt records how many resends led to it and when +-- the chain began. +ALTER TABLE email_attempts ADD COLUMN resends INTEGER NOT NULL DEFAULT 0; +ALTER TABLE email_attempts ADD COLUMN chain_started INTEGER NOT NULL DEFAULT 0; diff --git a/hub/migrations/0005_avatars.sql b/hub/migrations/0005_avatars.sql new file mode 100644 index 0000000..9581e4c --- /dev/null +++ b/hub/migrations/0005_avatars.sql @@ -0,0 +1,12 @@ +-- One own avatar per account, stored as a re-encoded PNG (no source metadata). The row is +-- replaced on upload and removed on "remove photo" or when the account is deleted. `id` is the +-- hex SHA-256 of the stored bytes; it names the immutable public URL /v1/avatars/. +-- accounts.avatar_url keeps the provider (GitHub) avatar as the fallback. +CREATE TABLE avatars ( + user_id TEXT PRIMARY KEY REFERENCES accounts(user_id) ON DELETE CASCADE, + id TEXT NOT NULL, + content_type TEXT NOT NULL, + bytes BLOB NOT NULL, + created_at INTEGER NOT NULL +); +CREATE INDEX avatars_by_id ON avatars(id); diff --git a/hub/src/auth/email.rs b/hub/src/auth/email.rs new file mode 100644 index 0000000..5c0e8b3 --- /dev/null +++ b/hub/src/auth/email.rs @@ -0,0 +1,448 @@ +//! Passwordless email sign-in: address normalization, keyed MACs, one-time codes and +//! rate limits. Nothing in this module logs addresses, codes or network sources. + +use std::{future::Future, pin::Pin, sync::Arc}; + +use hmac::{Hmac, Mac}; +use sha2::Sha256; +use sqlx::SqlitePool; +use subtle::ConstantTimeEq; + +use super::store::{hash, now}; +use crate::mail::templates::Email; + +/// Lifetime of a pending code. Also the cookie lifetime of the attempt binding. +pub const CODE_TTL: i64 = 600; +/// Verification tries per issued code, counted before the comparison. +pub const MAX_FAILURES: i64 = 5; +/// Pending attempts kept at once; protects the table from being filled by anonymous traffic. +const MAX_PENDING: i64 = 4096; +const CODE_DIGITS: usize = 8; +/// Resends per chain that may use the reserved global budget. +pub const MAX_RESENDS: i64 = 3; +/// Seconds after which a chain of resends stops qualifying for the reserve. +const CHAIN_LIFETIME: i64 = 1800; + +/// Position in a resend chain carried from a claimed attempt to its replacement. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Chain { + resends: i64, + started: i64, +} + +/// Result of [`EmailAuth::reserve_send`]. +pub enum Reservation { + Denied, + /// `chain` is set when the request replaced a live attempt for the same address. + Allowed { + chain: Option, + }, +} + +/// Delivery boundary. The production implementation is [`crate::mail::Mailer`]; tests +/// inject a recorder so no network traffic or real mail is ever produced. +pub trait CodeSender: Send + Sync { + fn send<'a>( + &'a self, + recipient: &'a str, + email: Email, + ) -> Pin> + Send + 'a>>; +} + +impl CodeSender for crate::mail::Mailer { + fn send<'a>( + &'a self, + recipient: &'a str, + email: Email, + ) -> Pin> + Send + 'a>> { + Box::pin(self.deliver(recipient, email)) + } +} + +/// Send budgets. Every request that passes validation consumes budget, whether or not +/// delivery later succeeds, so the limits bound SMTP use and address harassment. +#[derive(Clone, Copy)] +pub struct EmailLimits { + /// Minimum seconds between two codes for the same address. + pub address_cooldown: i64, + pub per_address_hour: i64, + pub per_source_hour: i64, + pub global_hour: i64, + /// Extra global budget usable only by resends from a browser that already holds a + /// live attempt, so exhausting `global_hour` with fresh starts cannot lock out people + /// who are mid sign-in. + pub global_resend_reserve: i64, +} + +impl Default for EmailLimits { + fn default() -> Self { + Self { + address_cooldown: 60, + per_address_hour: 5, + per_source_hour: 10, + global_hour: 300, + global_resend_reserve: 100, + } + } +} + +/// Enabled email sign-in. Holds the server MAC key; deliberately not Debug. +pub struct EmailAuth { + key: [u8; 32], + pub sender: Arc, + pub limits: EmailLimits, +} + +impl EmailAuth { + pub fn new(key: [u8; 32], sender: Arc) -> Self { + Self { + key, + sender, + limits: EmailLimits::default(), + } + } + + /// HMAC-SHA256 under the server secret, domain separated and length prefixed so + /// different field combinations can never produce the same input. + pub fn mac(&self, domain: &str, parts: &[&str]) -> String { + let mut mac = as hmac::digest::KeyInit>::new_from_slice(&self.key) + .expect("HMAC accepts any key length"); + for part in std::iter::once(domain).chain(parts.iter().copied()) { + mac.update(&(part.len() as u64).to_be_bytes()); + mac.update(part.as_bytes()); + } + hex::encode(mac.finalize().into_bytes()) + } + + fn code_mac(&self, attempt_id: &str, email_mac: &str, code: &str) -> String { + self.mac("vnox-email-code-v1", &[attempt_id, email_mac, code]) + } + + pub fn email_mac(&self, email: &str) -> String { + self.mac("vnox-email-address-v1", &[email]) + } + + pub fn source_mac(&self, source: &str) -> String { + self.mac("vnox-email-source-v1", &[source]) + } + + /// Checks every send budget and records the send, in one transaction. + /// + /// A request carrying the cookie of a live attempt for the *same address* (fewer than + /// [`MAX_FAILURES`] failures, fewer than [`MAX_RESENDS`] earlier resends, chain younger + /// than 30 minutes) claims that attempt by deleting it inside the transaction, which + /// makes the claim exclusive (parallel resends cannot both win it, chains cannot + /// branch) and rolls back with the rest if any budget refuses. Only a claimed request + /// may spend the global reserve. + pub async fn reserve_send( + &self, + pool: &SqlitePool, + email_mac: &str, + source_mac: &str, + browser: Option<&str>, + ) -> anyhow::Result { + let t = now(); + let limits = self.limits; + let mut transaction = pool.begin().await?; + let claimed: Option<(i64, i64)> = match browser { + Some(browser) => { + sqlx::query_as( + "DELETE FROM email_attempts WHERE browser_hash=? AND email_mac=? AND expires_at>? \ + AND failures? RETURNING resends,chain_started", + ) + .bind(hash(browser)) + .bind(email_mac) + .bind(t) + .bind(MAX_FAILURES) + .bind(MAX_RESENDS) + .bind(t - CHAIN_LIFETIME) + .fetch_optional(&mut *transaction) + .await? + } + None => None, + }; + let global_limit = limits.global_hour + + if claimed.is_some() { + limits.global_resend_reserve + } else { + 0 + }; + let result = sqlx::query( + "INSERT INTO email_send_log(email_mac,source_mac,sent_at) SELECT ?,?,? WHERE \ + (SELECT COUNT(*) FROM email_send_log WHERE email_mac=? AND sent_at>?)=0 AND \ + (SELECT COUNT(*) FROM email_send_log WHERE email_mac=? AND sent_at>?)?)?), + chain: Option, + ) -> anyhow::Result<(String, String)> { + let mut transaction = pool.begin().await?; + if let Some(previous) = previous_browser { + sqlx::query("DELETE FROM email_attempts WHERE browser_hash=?") + .bind(hash(previous)) + .execute(&mut *transaction) + .await?; + } + let pending: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM email_attempts") + .fetch_one(&mut *transaction) + .await?; + anyhow::ensure!(pending < MAX_PENDING, "email login capacity reached"); + let attempt_id = super::store::token(); + let code = generate_code(); + let email_mac = self.email_mac(email); + sqlx::query( + "INSERT INTO email_attempts(attempt_id,browser_hash,email_mac,code_mac,expires_at,resends,chain_started) VALUES(?,?,?,?,?,?,?)", + ) + .bind(&attempt_id) + .bind(hash(browser)) + .bind(&email_mac) + .bind(self.code_mac(&attempt_id, &email_mac, &code)) + .bind(now() + CODE_TTL) + .bind(chain.map_or(0, |c| c.resends)) + .bind(chain.map_or_else(now, |c| c.started)) + .execute(&mut *transaction) + .await?; + transaction.commit().await?; + Ok((attempt_id, code)) + } + + pub async fn discard_attempt(&self, pool: &SqlitePool, attempt_id: &str) { + let _ = sqlx::query("DELETE FROM email_attempts WHERE attempt_id=?") + .bind(attempt_id) + .execute(pool) + .await; + } + + /// Checks a submitted code for the attempt bound to this browser. + /// + /// The try counter is incremented by the same atomic statement that selects the row, so + /// parallel guesses cannot exceed [`MAX_FAILURES`]. A correct code is consumed by a + /// `DELETE ... RETURNING`: exactly one caller can win it. Every failure mode (missing, + /// expired, exhausted, wrong address, wrong code) is reported identically. + pub async fn verify( + &self, + pool: &SqlitePool, + email: &str, + code: &str, + browser: &str, + ) -> anyhow::Result { + let row: Option<(String, String, String, i64)> = sqlx::query_as( + "UPDATE email_attempts SET failures=failures+1 WHERE browser_hash=? AND expires_at>? AND failures= MAX_FAILURES { + self.discard_attempt(pool, &attempt_id).await; + } + return Ok(false); + } + let consumed: Option = sqlx::query_scalar( + "DELETE FROM email_attempts WHERE attempt_id=? AND expires_at>? RETURNING attempt_id", + ) + .bind(&attempt_id) + .bind(now()) + .fetch_optional(pool) + .await?; + Ok(consumed.is_some()) + } +} + +/// Uniform eight-digit code from the OS-seeded CSPRNG, using rejection sampling to avoid +/// modulo bias. +pub fn generate_code() -> String { + use rand::Rng; + const SPAN: u64 = 10u64.pow(CODE_DIGITS as u32); + const LIMIT: u64 = u64::MAX - u64::MAX % SPAN; + loop { + let mut bytes = [0u8; 8]; + rand::rng().fill_bytes(&mut bytes); + let value = u64::from_le_bytes(bytes); + if value < LIMIT { + return format!("{:0width$}", value % SPAN, width = CODE_DIGITS); + } + } +} + +/// True for exactly eight ASCII digits. +pub fn valid_code_shape(code: &str) -> bool { + code.len() == CODE_DIGITS && code.bytes().all(|byte| byte.is_ascii_digit()) +} + +/// Trims and lowercases an address and accepts a deliberately conservative subset of RFC +/// 5321: ASCII only, a dot-atom local part limited to `[a-z0-9._%+-]`, and a multi-label +/// hostname whose last label is alphabetic (no IP literals). `+tags` are kept, so different +/// tags are different identities. Unusual but legal addresses are rejected rather than +/// risk look-alike or parser-differential identities. +pub fn normalize_email(raw: &str) -> Option { + let value = raw.trim().to_ascii_lowercase(); + if value.len() > 254 || !value.is_ascii() { + return None; + } + let (local, domain) = value.split_once('@')?; + if domain.contains('@') || local.is_empty() || local.len() > 64 { + return None; + } + if local.starts_with('.') + || local.ends_with('.') + || local.contains("..") + || !local + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"._%+-".contains(&b)) + { + return None; + } + if domain.len() > 253 { + return None; + } + let labels: Vec<&str> = domain.split('.').collect(); + if labels.len() < 2 { + return None; + } + for label in &labels { + if label.is_empty() + || label.len() > 63 + || label.starts_with('-') + || label.ends_with('-') + || !label + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-') + { + return None; + } + } + let tld = labels[labels.len() - 1]; + if tld.len() < 2 || !tld.bytes().all(|b| b.is_ascii_alphabetic()) { + return None; + } + Some(value) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hmac_sha256_matches_rfc_4231_case_2_construction() { + // Sanity check of the primitive itself with the RFC 4231 test case 2 vector. + let mut mac = as hmac::digest::KeyInit>::new_from_slice(b"Jefe").unwrap(); + mac.update(b"what do ya want for nothing?"); + assert_eq!( + hex::encode(mac.finalize().into_bytes()), + "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843" + ); + } + + #[test] + fn mac_fields_are_domain_separated_and_unambiguous() { + struct Nop; + impl CodeSender for Nop { + fn send<'a>( + &'a self, + _: &'a str, + _: Email, + ) -> Pin> + Send + 'a>> { + Box::pin(async { Ok(()) }) + } + } + let auth = EmailAuth::new([7; 32], Arc::new(Nop)); + assert_ne!(auth.mac("a", &["bc"]), auth.mac("ab", &["c"])); + assert_ne!(auth.mac("d", &["a", "bc"]), auth.mac("d", &["ab", "c"])); + assert_ne!(auth.email_mac("x@y.zz"), auth.source_mac("x@y.zz")); + let other = EmailAuth::new([8; 32], Arc::new(Nop)); + assert_ne!(auth.email_mac("x@y.zz"), other.email_mac("x@y.zz")); + } + + #[test] + fn codes_are_eight_digits_and_vary() { + let codes: std::collections::HashSet = (0..64).map(|_| generate_code()).collect(); + assert!(codes.len() > 60); + assert!(codes.iter().all(|code| valid_code_shape(code))); + } + + #[test] + fn normalization_accepts_and_rejects_expected_shapes() { + assert_eq!( + normalize_email(" Person.Name+Tag@Example.COM \n").as_deref(), + Some("person.name+tag@example.com") + ); + for bad in [ + "", + "plain", + "a@b", + "a@@b.cc", + "a@b@c.cc", + "@b.cc", + "a b@c.cc", + ".a@b.cc", + "a.@b.cc", + "a..b@c.cc", + "\"a\"@b.cc", + "a@b.c", + "a@b.123", + "a@[127.0.0.1]", + "a@-b.cc", + "a@b-.cc", + "a@b..cc", + "а@b.cc", + "a@b.cc\r\nBcc: x@y.cc", + "a"#.to_vec(); + + for (declared, body, code) in [ + ("image/gif", gif.clone(), "unsupported_type"), + ("image/png", gif, "unsupported_type"), + ("image/svg+xml", svg.clone(), "unsupported_type"), + ("image/png", svg, "unsupported_type"), + ("text/plain", b"hello".to_vec(), "unsupported_type"), + ("application/json", b"{}".to_vec(), "unsupported_type"), + ( + "image/png", + b"not an image at all".to_vec(), + "unsupported_type", + ), + // A JPEG sent as a PNG, a PNG sent as a JPEG, WebP sent as PNG: the name does not matter. + ("image/png", jpeg(64, 64), "type_mismatch"), + ("image/jpeg", png(64, 64), "type_mismatch"), + ("image/png", webp(64, 64), "type_mismatch"), + ] { + assert_error( + fx.upload(&alice, declared, body).await, + StatusCode::UNSUPPORTED_MEDIA_TYPE, + code, + ) + .await; + } + // No content type at all. + let response = fx + .send( + Request::builder() + .method(Method::POST) + .uri("/v1/account/avatar") + .header("cookie", format!("__Host-vnox_session={}", alice.token)) + .header("x-csrf-token", &alice.csrf) + .header("origin", ORIGIN) + .body(Body::from(png(64, 64))) + .unwrap(), + ) + .await; + assert_eq!(response.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE); + assert_eq!(fx.avatar_rows().await, 0); +} + +#[tokio::test] +async fn oversized_bodies_are_refused() { + let fx = fixture().await; + let alice = fx.email_user("alice@example.com").await; + let mut big = png(64, 64); + big.resize(2 * 1024 * 1024 + 1, 0); + // Without a Content-Length (chunked), the read itself stops at the limit. + assert_error( + fx.upload(&alice, "image/png", big.clone()).await, + StatusCode::PAYLOAD_TOO_LARGE, + "too_large", + ) + .await; + // With an announced length, it is refused before reading. + let response = fx + .send( + Request::builder() + .method(Method::POST) + .uri("/v1/account/avatar") + .header("cookie", format!("__Host-vnox_session={}", alice.token)) + .header("x-csrf-token", &alice.csrf) + .header("origin", ORIGIN) + .header("content-type", "image/png") + .header("content-length", big.len()) + .body(Body::from(big)) + .unwrap(), + ) + .await; + assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE); + // Unauthenticated callers never get their body read or decoded. + let response = fx + .change( + Method::POST, + None, + None, + Some(ORIGIN), + "image/png", + vec![0; 3 << 20], + ) + .await; + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + assert_eq!(fx.avatar_rows().await, 0); +} + +#[tokio::test] +async fn decompression_bomb_and_odd_dimensions_are_refused_before_decoding() { + let fx = fixture().await; + let alice = fx.email_user("alice@example.com").await; + + // Tiny files whose headers claim huge or oversized pictures. + for (w, h) in [(60_000, 60_000), (4097, 64), (64, 4097), (u32::MAX >> 1, 1)] { + let lie = claim_size(&png(64, 64), w, h); + assert!(lie.len() < 100_000); + assert_error( + fx.upload(&alice, "image/png", lie).await, + StatusCode::UNPROCESSABLE_ENTITY, + "bad_dimensions", + ) + .await; + } + // Real, merely oversized or undersized pictures. + assert_error( + fx.upload(&alice, "image/png", png(4097, 40)).await, + StatusCode::UNPROCESSABLE_ENTITY, + "bad_dimensions", + ) + .await; + assert_error( + fx.upload(&alice, "image/jpeg", jpeg(16, 16)).await, + StatusCode::UNPROCESSABLE_ENTITY, + "bad_dimensions", + ) + .await; + // Truncated and corrupted data. + let mut cut = png(300, 300); + cut.truncate(cut.len() / 2); + assert_error( + fx.upload(&alice, "image/png", cut).await, + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_image", + ) + .await; + let mut cut = jpeg(300, 300); + cut.truncate(60); + let response = fx.upload(&alice, "image/jpeg", cut).await; + assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY); + assert_eq!(fx.avatar_rows().await, 0); +} + +#[tokio::test] +async fn a_new_upload_replaces_the_old_one() { + let fx = fixture().await; + let alice = fx.email_user("alice@example.com").await; + let first = json(fx.upload(&alice, "image/png", png(100, 100)).await).await["avatar_url"] + .as_str() + .unwrap() + .to_owned(); + let second = json(fx.upload(&alice, "image/jpeg", jpeg(150, 150)).await).await["avatar_url"] + .as_str() + .unwrap() + .to_owned(); + assert_ne!(first, second); + assert_eq!(fx.avatar_rows().await, 1); + assert_eq!(fx.get(&first).await.status(), StatusCode::NOT_FOUND); + assert_eq!(fx.get(&second).await.status(), StatusCode::OK); + assert_eq!(fx.session_avatar(&alice).await, second); +} + +#[tokio::test] +async fn delete_returns_the_provider_avatar_or_the_default() { + let fx = fixture().await; + let github = fx.github_user().await; + assert_eq!(fx.session_avatar(&github).await, GITHUB_AVATAR); + + let url = json(fx.upload(&github, "image/png", png(64, 64)).await).await["avatar_url"] + .as_str() + .unwrap() + .to_owned(); + assert_ne!(fx.session_avatar(&github).await, GITHUB_AVATAR); + + let response = fx.remove(&github).await; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.headers()["cache-control"], "no-store"); + assert_eq!(json(response).await["avatar_url"], GITHUB_AVATAR); + assert_eq!(fx.session_avatar(&github).await, GITHUB_AVATAR); + assert_eq!(fx.get(&url).await.status(), StatusCode::NOT_FOUND); + assert_eq!(fx.avatar_rows().await, 0); + + // Removing again is harmless, and an email account falls back to the default (null). + assert_eq!(fx.remove(&github).await.status(), StatusCode::OK); + let alice = fx.email_user("alice@example.com").await; + fx.upload(&alice, "image/png", png(64, 64)).await; + let response = fx.remove(&alice).await; + assert_eq!(json(response).await["avatar_url"], serde_json::Value::Null); + assert_eq!(fx.session_avatar(&alice).await, serde_json::Value::Null); +} + +#[tokio::test] +async fn avatar_urls_are_validated_and_unknown_ids_are_not_found() { + let fx = fixture().await; + for path in [ + "/v1/avatars/".to_owned(), + "/v1/avatars/abc".to_owned(), + format!("/v1/avatars/{}", "0".repeat(64)), + format!("/v1/avatars/{}", "G".repeat(64)), + format!("/v1/avatars/{}", "A".repeat(64)), + "/v1/avatars/..%2F..%2Fhub.sqlite3".to_owned(), + ] { + let response = fx.get(&path).await; + assert_eq!(response.status(), StatusCode::NOT_FOUND, "{path}"); + assert_eq!(response.headers()["cache-control"], "no-store"); + } +} + +#[tokio::test] +async fn upload_rate_limit_applies_per_account() { + let fx = fixture().await; + let alice = fx.email_user("alice@example.com").await; + let bob = fx.email_user("bob@example.com").await; + let image = png(64, 64); + for _ in 0..10 { + assert_eq!( + fx.upload(&alice, "image/png", image.clone()).await.status(), + StatusCode::OK + ); + } + assert_error( + fx.upload(&alice, "image/png", image.clone()).await, + StatusCode::TOO_MANY_REQUESTS, + "try_later", + ) + .await; + assert_error( + fx.remove(&alice).await, + StatusCode::TOO_MANY_REQUESTS, + "try_later", + ) + .await; + // Another account from the same source still has its own budget. + assert_eq!( + fx.upload(&bob, "image/png", image).await.status(), + StatusCode::OK + ); +} + +#[tokio::test] +async fn upload_rate_limit_applies_per_source() { + let fx = fixture().await; + let image = png(64, 64); + let mut accepted = 0; + for n in 0..40 { + let user = fx.email_user(&format!("user{n}@example.com")).await; + let response = fx + .send( + Request::builder() + .method(Method::POST) + .uri("/v1/account/avatar") + .header("cookie", format!("__Host-vnox_session={}", user.token)) + .header("x-csrf-token", &user.csrf) + .header("origin", ORIGIN) + .header("x-forwarded-for", "203.0.113.9") + .header("content-type", "image/png") + .body(Body::from(image.clone())) + .unwrap(), + ) + .await; + match response.status() { + StatusCode::OK => accepted += 1, + StatusCode::TOO_MANY_REQUESTS => break, + other => panic!("unexpected {other}"), + } + } + assert_eq!(accepted, 30); +} + +#[tokio::test] +async fn deleting_an_account_removes_its_avatar() { + let fx = fixture().await; + let alice = fx.email_user("alice@example.com").await; + fx.upload(&alice, "image/png", png(64, 64)).await; + sqlx::query("DELETE FROM accounts WHERE user_id=?") + .bind(&alice.user.user_id) + .execute(&fx.state.database) + .await + .unwrap(); + assert_eq!(fx.avatar_rows().await, 0); +} diff --git a/hub/tests/email_auth.rs b/hub/tests/email_auth.rs new file mode 100644 index 0000000..065ef23 --- /dev/null +++ b/hub/tests/email_auth.rs @@ -0,0 +1,1022 @@ +//! Email one-time-code sign-in. Delivery is replaced by an in-memory recorder: no SMTP +//! connection is opened and no message ever leaves the process. + +use axum::{ + Router, + body::{Body, to_bytes}, + http::{Request, Response, StatusCode}, +}; +use serde_json::{Value, json}; +use std::{ + future::Future, + pin::Pin, + sync::{Arc, Mutex}, +}; +use tower::ServiceExt; +use vnox_hub::{ + auth::{ + self, + email::{CodeSender, EmailAuth, EmailLimits}, + provider::GitHubProfile, + store, + }, + database, + identity::Issuer, + mail::templates::Email, + web::{self, HubState}, +}; + +const ORIGIN: &str = "https://central.loki-code.dev"; + +#[derive(Default)] +struct Recorder { + sent: Mutex>, + fail: bool, +} +impl CodeSender for Recorder { + fn send<'a>( + &'a self, + recipient: &'a str, + email: Email, + ) -> Pin> + Send + 'a>> { + Box::pin(async move { + if self.fail { + anyhow::bail!("simulated outage"); + } + self.sent + .lock() + .unwrap() + .push((recipient.to_owned(), email)); + Ok(()) + }) + } +} +impl Recorder { + fn last_code(&self) -> String { + let sent = self.sent.lock().unwrap(); + let text = &sent.last().expect("a message was recorded").1.text; + let digits: Vec<&str> = text + .split(|c: char| !c.is_ascii_digit()) + .filter(|part| part.len() == 8) + .collect(); + assert_eq!(digits.len(), 1, "exactly one code in the message"); + digits[0].to_owned() + } + fn count(&self) -> usize { + self.sent.lock().unwrap().len() + } +} + +struct Harness { + _dir: tempfile::TempDir, + state: Arc, + app: Router, + mail: Arc, +} + +async fn harness_with(limits: EmailLimits, fail: bool, enabled: bool) -> Harness { + let dir = tempfile::tempdir().unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + } + let issuer = Issuer::load_or_create(dir.path()).unwrap(); + let pool = database::open(dir.path(), &issuer).await.unwrap(); + let mail = Arc::new(Recorder { + fail, + ..Default::default() + }); + let mut auth = + auth::AuthService::with_provider(pool.clone(), url::Url::parse(ORIGIN).unwrap(), None); + if enabled { + let mut email = EmailAuth::new([42; 32], mail.clone()); + email.limits = limits; + auth = auth.with_email(email); + } + let state = Arc::new(HubState { + database: pool, + auth: Arc::new(auth), + issuer, + smtp_configured: enabled, + started: std::time::Instant::now(), + }); + Harness { + _dir: dir, + app: web::router(state.clone()), + state, + mail, + } +} + +fn relaxed() -> EmailLimits { + EmailLimits { + address_cooldown: 0, + per_address_hour: 1000, + per_source_hour: 1000, + global_hour: 1000, + global_resend_reserve: 0, + } +} + +async fn harness() -> Harness { + harness_with(relaxed(), false, true).await +} + +struct Post<'a> { + path: &'a str, + body: Value, + cookie: Option<&'a str>, + origin: Option<&'a str>, + ip: &'a str, +} +fn post<'a>(path: &'a str, body: Value) -> Post<'a> { + Post { + path, + body, + cookie: None, + origin: Some(ORIGIN), + ip: "198.51.100.7", + } +} +impl Post<'_> { + fn request(&self) -> Request { + let mut builder = Request::builder() + .method("POST") + .uri(self.path) + .header("content-type", "application/json") + .header("x-forwarded-for", self.ip); + if let Some(origin) = self.origin { + builder = builder.header("origin", origin); + } + if let Some(cookie) = self.cookie { + builder = builder.header("cookie", cookie); + } + builder.body(Body::from(self.body.to_string())).unwrap() + } +} + +async fn send(app: &Router, request: Request) -> (StatusCode, Vec, String) { + let response: Response = app.clone().oneshot(request).await.unwrap(); + let status = response.status(); + let cookies = response + .headers() + .get_all("set-cookie") + .iter() + .map(|v| v.to_str().unwrap().to_owned()) + .collect(); + let body = String::from_utf8( + to_bytes(response.into_body(), 65536) + .await + .unwrap() + .to_vec(), + ) + .unwrap(); + (status, cookies, body) +} + +fn pair(cookies: &[String], name: &str) -> String { + cookies + .iter() + .find(|c| c.starts_with(&format!("{name}="))) + .unwrap_or_else(|| panic!("{name} cookie missing")) + .split(';') + .next() + .unwrap() + .to_owned() +} + +/// Requests a code; returns the browser-binding cookie pair. +async fn start(h: &Harness, email: &str) -> String { + let (status, cookies, _) = send( + &h.app, + post("/v1/auth/email/start", json!({"email": email})).request(), + ) + .await; + assert_eq!(status, StatusCode::ACCEPTED); + pair(&cookies, "__Host-vnox_email") +} + +async fn verify( + h: &Harness, + cookie: Option<&str>, + email: &str, + code: &str, +) -> (StatusCode, Vec, String) { + let mut request = post( + "/v1/auth/email/verify", + json!({"email": email, "code": code}), + ); + request.cookie = cookie; + send(&h.app, request.request()).await +} + +#[tokio::test] +async fn full_flow_creates_neutral_account_and_session() { + let h = harness().await; + let (status, cookies, body) = send( + &h.app, + post( + "/v1/auth/email/start", + json!({"email": " Alice.Secret@Example.COM "}), + ) + .request(), + ) + .await; + assert_eq!(status, StatusCode::ACCEPTED); + let browser_cookie = cookies + .iter() + .find(|c| c.starts_with("__Host-vnox_email=")) + .unwrap(); + for attribute in [ + "Secure", + "HttpOnly", + "SameSite=Lax", + "Path=/", + "Max-Age=600", + ] { + assert!(browser_cookie.contains(attribute), "{attribute}"); + } + assert!(!browser_cookie.contains("Domain")); + let browser = pair(&cookies, "__Host-vnox_email"); + let code = h.mail.last_code(); + // The code reaches the user only by mail, never in any part of the HTTP response. + assert!(!body.contains(&code)); + assert!(!cookies.iter().any(|c| c.contains(&code))); + { + let sent = h.mail.sent.lock().unwrap(); + assert_eq!(sent[0].0, "alice.secret@example.com"); + // Only the bare site origin appears (footer); no link carries a path, query or code. + let html = &sent[0].1.html; + assert_eq!(html.matches("href=\"").count(), 1); + assert!(html.contains(&format!("href=\"{ORIGIN}\""))); + for url in sent[0] + .1 + .text + .split_whitespace() + .filter(|w| w.starts_with("http")) + { + assert_eq!(url, ORIGIN); + } + assert!(!html.contains(&format!("{ORIGIN}/")) || html.contains("/assets/vnox-mark.png")); + } + // Only keyed MACs are stored. + let row: (String, String) = sqlx::query_as("SELECT email_mac,code_mac FROM email_attempts") + .fetch_one(&h.state.database) + .await + .unwrap(); + assert_ne!(row.1, store::hash(&code)); + assert_ne!(row.1, code); + assert!(!row.0.contains("alice")); + let (status, cookies, body) = + verify(&h, Some(&browser), "alice.secret@example.com ", &code).await; + assert_eq!(status, StatusCode::OK, "{body}"); + let session_cookie = cookies + .iter() + .find(|c| c.starts_with("__Host-vnox_session=")) + .unwrap(); + for attribute in [ + "Secure", + "HttpOnly", + "SameSite=Lax", + "Path=/", + "Max-Age=604800", + ] { + assert!(session_cookie.contains(attribute), "{attribute}"); + } + let json: Value = serde_json::from_str(&body).unwrap(); + assert_eq!(json["authenticated"], true); + assert_eq!(json["user"]["display_name"], "Vnox user"); + let handle = json["user"]["handle"].as_str().unwrap(); + assert!(handle.starts_with("u_") && !handle.contains("alice")); + assert!(!body.to_lowercase().contains("alice")); + assert!(!json["csrf_token"].as_str().unwrap().is_empty()); + // The same session endpoint now reports the user, with the same format. + let (status, _, session_body) = send( + &h.app, + Request::builder() + .uri("/v1/auth/session") + .header("cookie", pair(&cookies, "__Host-vnox_session")) + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(status, StatusCode::OK); + let session: Value = serde_json::from_str(&session_body).unwrap(); + assert_eq!(session, json); + let identity: (String, String) = + sqlx::query_as("SELECT provider,subject FROM external_identities") + .fetch_one(&h.state.database) + .await + .unwrap(); + assert_eq!( + identity, + ("email".into(), "alice.secret@example.com".into()) + ); + let ttl: i64 = sqlx::query_scalar("SELECT expires_at-created_at FROM web_sessions") + .fetch_one(&h.state.database) + .await + .unwrap(); + assert_eq!(ttl, 7 * 24 * 60 * 60); + // Same address signs in again to the same account. + let again = start(&h, "ALICE.secret@example.com").await; + let code = h.mail.last_code(); + let (_, _, body) = verify(&h, Some(&again), "alice.secret@example.com", &code).await; + let second: Value = serde_json::from_str(&body).unwrap(); + assert_eq!(second["user"]["user_id"], json["user"]["user_id"]); +} + +#[tokio::test] +async fn wrong_code_is_rejected_and_attempts_are_exhausted() { + let h = harness().await; + let browser = start(&h, "a@example.com").await; + let code = h.mail.last_code(); + let wrong = if code == "00000000" { + "11111111" + } else { + "00000000" + }; + for _ in 0..4 { + let (status, cookies, body) = verify(&h, Some(&browser), "a@example.com", wrong).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + assert!(body.contains("invalid_code")); + assert!(!cookies.iter().any(|c| c.starts_with("__Host-vnox_session"))); + } + // The fifth try uses the last allowed attempt; a wrong guess burns it ... + let (status, ..) = verify(&h, Some(&browser), "a@example.com", wrong).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + // ... so even the correct code is now refused, with the same answer. + let (status, _, body) = verify(&h, Some(&browser), "a@example.com", &code).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + assert!(body.contains("invalid_code")); + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM accounts") + .fetch_one(&h.state.database) + .await + .unwrap(), + 0 + ); +} + +#[tokio::test] +async fn correct_code_still_works_after_some_failures() { + let h = harness().await; + let browser = start(&h, "a@example.com").await; + let code = h.mail.last_code(); + let wrong = if code == "00000000" { + "11111111" + } else { + "00000000" + }; + for _ in 0..4 { + verify(&h, Some(&browser), "a@example.com", wrong).await; + } + let (status, ..) = verify(&h, Some(&browser), "a@example.com", &code).await; + assert_eq!(status, StatusCode::OK); +} + +#[tokio::test] +async fn code_is_single_use_and_wrong_address_does_not_pass() { + let h = harness().await; + let browser = start(&h, "a@example.com").await; + let code = h.mail.last_code(); + let (status, ..) = verify(&h, Some(&browser), "other@example.com", &code).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + let (status, ..) = verify(&h, Some(&browser), "a@example.com", &code).await; + assert_eq!(status, StatusCode::OK); + let (status, ..) = verify(&h, Some(&browser), "a@example.com", &code).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "replay"); + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM email_attempts") + .fetch_one(&h.state.database) + .await + .unwrap(), + 0 + ); +} + +#[tokio::test] +async fn parallel_redemption_of_one_code_has_exactly_one_winner() { + let h = harness().await; + let browser = start(&h, "a@example.com").await; + let code = h.mail.last_code(); + let results = futures_join( + (0..4) + .map(|_| { + let app = h.app.clone(); + let browser = browser.clone(); + let code = code.clone(); + tokio::spawn(async move { + let mut request = post( + "/v1/auth/email/verify", + json!({"email": "a@example.com", "code": code}), + ); + request.cookie = Some(&browser); + send(&app, request.request()).await.0 + }) + }) + .collect(), + ) + .await; + assert_eq!(results.iter().filter(|s| **s == StatusCode::OK).count(), 1); + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM accounts") + .fetch_one(&h.state.database) + .await + .unwrap(), + 1 + ); +} + +async fn futures_join(handles: Vec>) -> Vec { + let mut out = Vec::new(); + for handle in handles { + out.push(handle.await.unwrap()); + } + out +} + +#[tokio::test] +async fn expired_code_is_rejected() { + let h = harness().await; + let browser = start(&h, "a@example.com").await; + let code = h.mail.last_code(); + sqlx::query("UPDATE email_attempts SET expires_at=0") + .execute(&h.state.database) + .await + .unwrap(); + let (status, ..) = verify(&h, Some(&browser), "a@example.com", &code).await; + assert_eq!(status, StatusCode::BAD_REQUEST); +} + +#[tokio::test] +async fn code_is_bound_to_the_requesting_browser() { + let h = harness().await; + let browser = start(&h, "a@example.com").await; + let code = h.mail.last_code(); + let stranger = format!("__Host-vnox_email={}", "ab".repeat(32)); + assert_eq!( + verify(&h, None, "a@example.com", &code).await.0, + StatusCode::BAD_REQUEST + ); + assert_eq!( + verify(&h, Some(&stranger), "a@example.com", &code).await.0, + StatusCode::BAD_REQUEST + ); + // Strangers neither consumed the code nor spent its tries. + assert_eq!( + verify(&h, Some(&browser), "a@example.com", &code).await.0, + StatusCode::OK + ); +} + +#[tokio::test] +async fn resend_replaces_the_previous_code_of_that_browser() { + let h = harness().await; + let first_browser = start(&h, "a@example.com").await; + let first = h.mail.last_code(); + let mut request = post("/v1/auth/email/start", json!({"email": "a@example.com"})); + request.cookie = Some(&first_browser); + let (status, cookies, _) = send(&h.app, request.request()).await; + assert_eq!(status, StatusCode::ACCEPTED); + let second_browser = pair(&cookies, "__Host-vnox_email"); + let second = h.mail.last_code(); + assert_eq!(h.mail.count(), 2); + if first != second { + assert_eq!( + verify(&h, Some(&first_browser), "a@example.com", &first) + .await + .0, + StatusCode::BAD_REQUEST + ); + } + assert_eq!( + verify(&h, Some(&second_browser), "a@example.com", &second) + .await + .0, + StatusCode::OK + ); +} + +#[tokio::test] +async fn start_responds_identically_for_existing_and_new_addresses() { + let h = harness().await; + let browser = start(&h, "known@example.com").await; + let code = h.mail.last_code(); + assert_eq!( + verify(&h, Some(&browser), "known@example.com", &code) + .await + .0, + StatusCode::OK + ); + let mut shapes = Vec::new(); + for address in ["known@example.com", "stranger@example.com"] { + let (status, cookies, body) = send( + &h.app, + post("/v1/auth/email/start", json!({"email": address})).request(), + ) + .await; + let attributes: Vec = cookies + .iter() + .map(|c| c.split_once('=').unwrap().0.to_owned() + &c[c.find(';').unwrap()..]) + .collect(); + shapes.push((status, body, attributes)); + } + assert_eq!(shapes[0], shapes[1]); + assert_eq!(shapes[0].0, StatusCode::ACCEPTED); + // Both addresses really did receive a code message. + assert_eq!(h.mail.count(), 3); +} + +#[tokio::test] +async fn start_rejects_bad_addresses_and_cross_site_or_malformed_requests() { + let h = harness().await; + for bad in [ + "", + "no-at", + "a@b", + "a b@example.com", + "x@y.com\r\nBcc: z@y.com", + ] { + let (status, cookies, body) = send( + &h.app, + post("/v1/auth/email/start", json!({"email": bad})).request(), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + assert!(body.contains("invalid_email")); + assert!(cookies.is_empty()); + } + let mut request = post("/v1/auth/email/start", json!({"email": "a@example.com"})); + request.origin = None; + assert_eq!( + send(&h.app, request.request()).await.0, + StatusCode::FORBIDDEN + ); + let mut request = post("/v1/auth/email/start", json!({"email": "a@example.com"})); + request.origin = Some("https://evil.example"); + assert_eq!( + send(&h.app, request.request()).await.0, + StatusCode::FORBIDDEN + ); + let mut request = post( + "/v1/auth/email/verify", + json!({"email": "a@example.com", "code": "12345678"}), + ); + request.origin = Some("https://evil.example"); + assert_eq!( + send(&h.app, request.request()).await.0, + StatusCode::FORBIDDEN + ); + // Form posts, unknown fields and oversized bodies never reach the handler logic. + let form = Request::builder() + .method("POST") + .uri("/v1/auth/email/start") + .header("origin", ORIGIN) + .header("content-type", "application/x-www-form-urlencoded") + .body(Body::from("email=a@example.com")) + .unwrap(); + assert_eq!(send(&h.app, form).await.0, StatusCode::BAD_REQUEST); + let extra = post( + "/v1/auth/email/start", + json!({"email": "a@example.com", "x": 1}), + ); + assert_eq!( + send(&h.app, extra.request()).await.0, + StatusCode::BAD_REQUEST + ); + let big = post("/v1/auth/email/start", json!({"email": "a".repeat(5000)})); + assert_eq!(send(&h.app, big.request()).await.0, StatusCode::BAD_REQUEST); + assert_eq!(h.mail.count(), 0); + // Malformed code shape is refused before touching any attempt. + let browser = start(&h, "a@example.com").await; + for bad in ["1234567", "123456789", "1234abcd", "12345678"] { + assert_eq!( + verify(&h, Some(&browser), "a@example.com", bad).await.0, + StatusCode::BAD_REQUEST + ); + } + let failures: i64 = sqlx::query_scalar("SELECT failures FROM email_attempts") + .fetch_one(&h.state.database) + .await + .unwrap(); + assert_eq!(failures, 0); +} + +#[tokio::test] +async fn address_cooldown_and_hourly_limits() { + let h = harness_with(EmailLimits::default(), false, true).await; + start(&h, "a@example.com").await; + let (status, ..) = send( + &h.app, + post("/v1/auth/email/start", json!({"email": "A@Example.com"})).request(), + ) + .await; + assert_eq!( + status, + StatusCode::TOO_MANY_REQUESTS, + "cooldown applies to the normalized address" + ); + assert_eq!(h.mail.count(), 1); + // Hourly cap: pretend the earlier sends happened a few minutes ago. + sqlx::query("UPDATE email_send_log SET sent_at=sent_at-120") + .execute(&h.state.database) + .await + .unwrap(); + for i in 0..4 { + let (status, ..) = send( + &h.app, + post("/v1/auth/email/start", json!({"email": "a@example.com"})).request(), + ) + .await; + assert_eq!(status, StatusCode::ACCEPTED, "send {i}"); + sqlx::query("UPDATE email_send_log SET sent_at=sent_at-120") + .execute(&h.state.database) + .await + .unwrap(); + } + let (status, ..) = send( + &h.app, + post("/v1/auth/email/start", json!({"email": "a@example.com"})).request(), + ) + .await; + assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); + assert_eq!(h.mail.count(), 5); +} + +#[tokio::test] +async fn source_and_global_limits() { + let h = harness_with( + EmailLimits { + address_cooldown: 0, + per_address_hour: 100, + per_source_hour: 3, + global_hour: 5, + global_resend_reserve: 0, + }, + false, + true, + ) + .await; + let attempt = |i: usize, ip: &'static str| { + let app = h.app.clone(); + async move { + let mut request = post( + "/v1/auth/email/start", + json!({"email": format!("user{i}@example.com")}), + ); + request.ip = ip; + send(&app, request.request()).await.0 + } + }; + for i in 0..3 { + assert_eq!(attempt(i, "203.0.113.1").await, StatusCode::ACCEPTED); + } + assert_eq!( + attempt(3, "203.0.113.1").await, + StatusCode::TOO_MANY_REQUESTS + ); + assert_eq!(attempt(4, "203.0.113.2").await, StatusCode::ACCEPTED); + assert_eq!(attempt(5, "203.0.113.2").await, StatusCode::ACCEPTED); + assert_eq!( + attempt(6, "203.0.113.3").await, + StatusCode::TOO_MANY_REQUESTS, + "global budget" + ); + assert_eq!(h.mail.count(), 5); +} + +#[tokio::test] +async fn source_hashes_not_addresses_are_ledgered() { + let h = harness().await; + start(&h, "private.person@example.com").await; + let row: (String, String) = sqlx::query_as("SELECT email_mac,source_mac FROM email_send_log") + .fetch_one(&h.state.database) + .await + .unwrap(); + assert!(!row.0.contains("private") && !row.1.contains("198.51")); + assert_eq!(row.0.len(), 64); +} + +#[tokio::test] +async fn delivery_failure_reports_unavailable_and_leaves_no_attempt() { + let h = harness_with(relaxed(), true, true).await; + let (status, cookies, _) = send( + &h.app, + post("/v1/auth/email/start", json!({"email": "a@example.com"})).request(), + ) + .await; + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); + assert!(cookies.is_empty()); + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM email_attempts") + .fetch_one(&h.state.database) + .await + .unwrap(), + 0 + ); +} + +#[tokio::test] +async fn capability_follows_configuration_and_disabled_endpoints_refuse() { + let enabled = harness().await; + let disabled = harness_with(relaxed(), false, false).await; + for (h, expected) in [(&enabled, "enabled"), (&disabled, "not_enabled")] { + let (_, _, body) = send( + &h.app, + Request::builder() + .uri("/v1/info") + .body(Body::empty()) + .unwrap(), + ) + .await; + let info: Value = serde_json::from_str(&body).unwrap(); + assert_eq!(info["capabilities"]["email_auth"], expected); + assert_eq!(info["smtp"]["public_send_endpoint"], false); + } + let (status, ..) = send( + &disabled.app, + post("/v1/auth/email/start", json!({"email": "a@example.com"})).request(), + ) + .await; + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(disabled.mail.count(), 0); +} + +#[tokio::test] +async fn email_never_merges_with_a_github_account() { + let h = harness().await; + let github = store::upsert_identity( + &h.state.database, + &GitHubProfile { + id: 77, + login: "same-person".into(), + name: Some("Same Person".into()), + avatar_url: None, + }, + ) + .await + .unwrap(); + let browser = start(&h, "same-person@example.com").await; + let code = h.mail.last_code(); + let (_, _, body) = verify(&h, Some(&browser), "same-person@example.com", &code).await; + let json: Value = serde_json::from_str(&body).unwrap(); + assert_ne!(json["user"]["user_id"].as_str().unwrap(), github.user_id); + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM accounts") + .fetch_one(&h.state.database) + .await + .unwrap(), + 2 + ); +} + +#[tokio::test] +async fn new_login_replaces_an_existing_session() { + let h = harness().await; + let user = store::upsert_email_identity(&h.state.database, "old@example.com") + .await + .unwrap(); + let (old, _) = store::create_session(&h.state.database, &user.user_id) + .await + .unwrap(); + let browser = start(&h, "new@example.com").await; + let code = h.mail.last_code(); + let mut request = post( + "/v1/auth/email/verify", + json!({"email": "new@example.com", "code": code}), + ); + let cookie = format!("{browser}; __Host-vnox_session={old}"); + request.cookie = Some(&cookie); + assert_eq!(send(&h.app, request.request()).await.0, StatusCode::OK); + assert!( + store::get_session(&h.state.database, &old) + .await + .unwrap() + .is_none() + ); +} + +#[tokio::test] +async fn expired_attempts_and_old_ledger_rows_are_pruned() { + let h = harness().await; + start(&h, "a@example.com").await; + sqlx::query("UPDATE email_attempts SET expires_at=0") + .execute(&h.state.database) + .await + .unwrap(); + sqlx::query("UPDATE email_send_log SET sent_at=0") + .execute(&h.state.database) + .await + .unwrap(); + store::cleanup(&h.state.database).await.unwrap(); + for sql in [ + "SELECT COUNT(*) FROM email_attempts", + "SELECT COUNT(*) FROM email_send_log", + ] { + let n: i64 = sqlx::query_scalar(sql) + .fetch_one(&h.state.database) + .await + .unwrap(); + assert_eq!(n, 0, "{sql}"); + } +} + +#[tokio::test] +async fn ipv6_sources_are_limited_per_slash_64() { + let h = harness_with( + EmailLimits { + address_cooldown: 0, + per_address_hour: 100, + per_source_hour: 2, + global_hour: 100, + global_resend_reserve: 0, + }, + false, + true, + ) + .await; + let go = |i: usize, ip: &'static str| { + let app = h.app.clone(); + async move { + let mut request = post( + "/v1/auth/email/start", + json!({"email": format!("v6user{i}@example.com")}), + ); + request.ip = ip; + send(&app, request.request()).await.0 + } + }; + assert_eq!(go(0, "2001:db8:1:2::1").await, StatusCode::ACCEPTED); + assert_eq!( + go(1, "2001:db8:1:2:ffff:aaaa:bbbb:cccc").await, + StatusCode::ACCEPTED + ); + assert_eq!( + go(2, "2001:db8:1:2:1234::9").await, + StatusCode::TOO_MANY_REQUESTS + ); + // A different /64 has its own budget; mapped IPv4 shares the IPv4 bucket. + assert_eq!(go(3, "2001:db8:1:3::1").await, StatusCode::ACCEPTED); + assert_eq!(go(4, "::ffff:192.0.2.9").await, StatusCode::ACCEPTED); + assert_eq!(go(5, "192.0.2.9").await, StatusCode::ACCEPTED); + assert_eq!( + go(6, "::ffff:192.0.2.9").await, + StatusCode::TOO_MANY_REQUESTS + ); +} + +#[tokio::test] +async fn global_reserve_serves_only_resends_from_a_live_attempt() { + let h = harness_with( + EmailLimits { + address_cooldown: 0, + per_address_hour: 100, + per_source_hour: 100, + global_hour: 2, + global_resend_reserve: 2, + }, + false, + true, + ) + .await; + let browser = start(&h, "a@example.com").await; + start(&h, "b@example.com").await; + // Fresh starts are now refused, including with a bogus or missing browser cookie. + let fresh = post("/v1/auth/email/start", json!({"email": "c@example.com"})); + assert_eq!( + send(&h.app, fresh.request()).await.0, + StatusCode::TOO_MANY_REQUESTS + ); + let mut bogus = post("/v1/auth/email/start", json!({"email": "c@example.com"})); + let stranger = format!("__Host-vnox_email={}", "cd".repeat(32)); + bogus.cookie = Some(&stranger); + assert_eq!( + send(&h.app, bogus.request()).await.0, + StatusCode::TOO_MANY_REQUESTS + ); + // A browser mid sign-in can still resend from the reserve, until it is used up. + let mut resend = post("/v1/auth/email/start", json!({"email": "a@example.com"})); + resend.cookie = Some(&browser); + let (status, cookies, _) = send(&h.app, resend.request()).await; + assert_eq!(status, StatusCode::ACCEPTED); + let browser = pair(&cookies, "__Host-vnox_email"); + let mut resend = post("/v1/auth/email/start", json!({"email": "a@example.com"})); + resend.cookie = Some(&browser); + assert_eq!(send(&h.app, resend.request()).await.0, StatusCode::ACCEPTED); + let mut resend = post("/v1/auth/email/start", json!({"email": "a@example.com"})); + resend.cookie = Some(&browser); + let (status, cookies, _) = send(&h.app, resend.request()).await; + assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); + assert!(cookies.is_empty()); +} + +fn reserve_limits() -> EmailLimits { + EmailLimits { + address_cooldown: 0, + per_address_hour: 1000, + per_source_hour: 1000, + global_hour: 1, + global_resend_reserve: 100, + } +} + +async fn resend(h: &Harness, cookie: &str, email: &str) -> (StatusCode, Vec) { + let mut request = post("/v1/auth/email/start", json!({"email": email})); + request.cookie = Some(cookie); + let (status, cookies, _) = send(&h.app, request.request()).await; + (status, cookies) +} + +#[tokio::test] +async fn reserve_is_not_available_for_a_different_address() { + let h = harness_with(reserve_limits(), false, true).await; + let browser = start(&h, "a@example.com").await; + // The normal budget (1) is spent. A live attempt for a@ must not open the reserve + // for sending to anyone else. + assert_eq!( + resend(&h, &browser, "victim@example.com").await.0, + StatusCode::TOO_MANY_REQUESTS + ); + assert_eq!( + resend(&h, &browser, "a@example.com").await.0, + StatusCode::ACCEPTED + ); + assert_eq!(h.mail.count(), 2); +} + +#[tokio::test] +async fn resend_chain_is_bounded() { + let h = harness_with(reserve_limits(), false, true).await; + let mut browser = start(&h, "a@example.com").await; + for i in 0..3 { + let (status, cookies) = resend(&h, &browser, "a@example.com").await; + assert_eq!(status, StatusCode::ACCEPTED, "resend {i}"); + browser = pair(&cookies, "__Host-vnox_email"); + } + // Reserve is still plentiful, but the chain has used its three resends. + assert_eq!( + resend(&h, &browser, "a@example.com").await.0, + StatusCode::TOO_MANY_REQUESTS + ); + assert_eq!(h.mail.count(), 4); + // The refused request rolled back: the live attempt still verifies. + let code = h.mail.last_code(); + assert_eq!( + verify(&h, Some(&browser), "a@example.com", &code).await.0, + StatusCode::OK + ); +} + +#[tokio::test] +async fn old_chains_and_attempts_with_spent_tries_lose_the_reserve() { + let h = harness_with(reserve_limits(), false, true).await; + let browser = start(&h, "a@example.com").await; + sqlx::query("UPDATE email_attempts SET failures=5") + .execute(&h.state.database) + .await + .unwrap(); + assert_eq!( + resend(&h, &browser, "a@example.com").await.0, + StatusCode::TOO_MANY_REQUESTS + ); + sqlx::query("UPDATE email_attempts SET failures=0, chain_started=chain_started-3600") + .execute(&h.state.database) + .await + .unwrap(); + assert_eq!( + resend(&h, &browser, "a@example.com").await.0, + StatusCode::TOO_MANY_REQUESTS + ); +} + +#[tokio::test] +async fn parallel_resends_claim_a_live_attempt_only_once() { + let h = harness_with(reserve_limits(), false, true).await; + let browser = start(&h, "a@example.com").await; + let mut tasks = Vec::new(); + for _ in 0..6 { + let app = h.app.clone(); + let browser = browser.clone(); + tasks.push(tokio::spawn(async move { + let mut request = post("/v1/auth/email/start", json!({"email": "a@example.com"})); + request.cookie = Some(&browser); + send(&app, request.request()).await.0 + })); + } + let mut accepted = 0; + for task in tasks { + if task.await.unwrap() == StatusCode::ACCEPTED { + accepted += 1; + } + } + assert_eq!(accepted, 1); + assert_eq!(h.mail.count(), 2); + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM email_attempts") + .fetch_one(&h.state.database) + .await + .unwrap(), + 1 + ); +} diff --git a/hub/tests/foundation.rs b/hub/tests/foundation.rs index 44f0556..c9bace7 100644 --- a/hub/tests/foundation.rs +++ b/hub/tests/foundation.rs @@ -187,11 +187,23 @@ async fn capabilities_and_routes_do_not_pretend_authentication_is_ready() { } assert_eq!(value["smtp"]["public_send_endpoint"], false); assert!(value.get("secret_key").is_none()); - for path in [ - "/v1/auth/email/start", - "/v1/servers/register", - "/v1/mail/send", - ] { + // Email sign-in exists but stays closed until SMTP is configured; there is still no + // route that sends arbitrary mail. + for path in ["/v1/auth/email/start", "/v1/auth/email/verify"] { + let response = app + .clone() + .oneshot( + Request::builder() + .method("POST") + .uri(path) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + } + for path in ["/v1/servers/register", "/v1/mail/send"] { let response = app .clone() .oneshot( diff --git a/hub/tests/mail.rs b/hub/tests/mail.rs index 6cba93e..e10bc0e 100644 --- a/hub/tests/mail.rs +++ b/hub/tests/mail.rs @@ -107,3 +107,28 @@ async fn smtp_probe_requires_tls_and_never_falls_back_to_cleartext_authenticatio assert!(!commands.contains("AUTH")); assert!(!commands.contains("MAIL FROM")); } + +#[test] +fn email_code_messages_are_bilingual_and_carry_no_links() { + use vnox_hub::mail::layout::Lang; + let origin = parse_origin("https://central.loki-code.dev").unwrap(); + for (lang, tag, phrase) in [ + (Lang::Ru, "lang=\"ru\"", "10 минут"), + (Lang::En, "lang=\"en\"", "10 minutes"), + ] { + let email = templates::render_email_code(&origin, "12345678", lang).unwrap(); + assert!(email.html.contains(tag) && email.html.contains(phrase)); + assert!(email.text.contains("12345678") && email.html.contains("12345678")); + assert!(email.text.contains(phrase)); + // No button and no copy-the-link block; only the bare origin in the footer. + assert_eq!(email.html.matches("href=\"").count(), 1); + assert!(!email.html.contains("?token=") && !email.html.contains("/login")); + assert!(!email.text.contains("http://") && !email.text.contains("?token")); + assert!(!email.subject.contains('\u{2014}')); + } + assert!(templates::render_email_code(&origin, "1234567", Lang::En).is_err()); + assert!(templates::render_email_code(&origin, "1234567a", Lang::Ru).is_err()); + assert_eq!(Lang::from_tag(Some("en")), Lang::En); + assert_eq!(Lang::from_tag(Some("de")), Lang::Ru); + assert_eq!(Lang::from_tag(None), Lang::Ru); +}