From cca084b0aea7fd72b1560984e63a69023568b6e3 Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Sat, 24 Oct 2026 17:42:49 +0200 Subject: [PATCH 1/4] feat(hub): email one-time-code sign-in POST /v1/auth/email/start and /verify with HMAC-protected 8-digit codes (10 min, 5 tries, atomic single use), browser-bound via a __Host- cookie, same-origin checks, per-address/source/global rate limits and an injectable sender. Enabled in /v1/info only when SMTP is configured. Email identities use external_identities(provider='email') and never merge with GitHub. --- Cargo.lock | 1 + deploy/central/README.md | 3 +- docs/00-status.md | 1 + docs/design/accounts-and-avatars.md | 2 + hub/AUTH.md | 44 +- hub/Cargo.toml | 1 + hub/README.md | 10 +- hub/migrations/0003_email_auth.sql | 26 + hub/src/auth/email.rs | 379 +++++++++++++ hub/src/auth/mod.rs | 12 + hub/src/auth/routes.rs | 185 ++++++- hub/src/auth/store.rs | 54 +- hub/src/identity.rs | 74 ++- hub/src/mail/layout.rs | 78 ++- hub/src/mail/templates.rs | 58 +- hub/src/main.rs | 17 +- hub/src/web.rs | 2 +- hub/tests/email_auth.rs | 821 ++++++++++++++++++++++++++++ hub/tests/foundation.rs | 22 +- hub/tests/mail.rs | 25 + 20 files changed, 1756 insertions(+), 59 deletions(-) create mode 100644 hub/migrations/0003_email_auth.sql create mode 100644 hub/src/auth/email.rs create mode 100644 hub/tests/email_auth.rs diff --git a/Cargo.lock b/Cargo.lock index fd2b361..c48f048 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2984,6 +2984,7 @@ dependencies = [ "cookie", "ed25519-dalek", "hex", + "hmac", "lettre", "oauth2", "rand 0.10.3", 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..daf8cb7 100644 --- a/docs/00-status.md +++ b/docs/00-status.md @@ -13,6 +13,7 @@ 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/avatar selection after first sign-in is 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..ee4b8dd 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, отображаемого имени и аватара после первого подтверждения ещё не реализован. Связывание второго способа входа, passkey/MFA и уведомления о новых способах входа тоже впереди. + ## GitHub OAuth Клиент открывает системный браузер. Hub хранит OAuth client_secret, принимает provider callback, проверяет state/PKCE и получает подтверждённую identity через GitHub API. Клиенту возвращается одноразовый код Vnox для конкретного login attempt с PKCE, а не GitHub bearer token в URL. diff --git a/hub/AUTH.md b/hub/AUTH.md index 9f13305..dbe799b 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,43 @@ 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; globally 300 per hour. 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, display name and avatar after registration is not implemented yet (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. diff --git a/hub/Cargo.toml b/hub/Cargo.toml index c19956f..248a13f 100644 --- a/hub/Cargo.toml +++ b/hub/Cargo.toml @@ -29,6 +29,7 @@ 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..7b03769 100644 --- a/hub/README.md +++ b/hub/README.md @@ -14,10 +14,12 @@ Community messages and voice never pass through this process. - Durable SQLite schema and issuer identity with a private `0600` key file. - 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/src/auth/email.rs b/hub/src/auth/email.rs new file mode 100644 index 0000000..c261177 --- /dev/null +++ b/hub/src/auth/email.rs @@ -0,0 +1,379 @@ +//! 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; + +/// 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, +} + +impl Default for EmailLimits { + fn default() -> Self { + Self { + address_cooldown: 60, + per_address_hour: 5, + per_source_hour: 10, + global_hour: 300, + } + } +} + +/// 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]) + } + + /// Atomically checks every send budget and records the send in one statement, so + /// concurrent requests cannot overshoot a limit. + pub async fn reserve_send( + &self, + pool: &SqlitePool, + email_mac: &str, + source_mac: &str, + ) -> anyhow::Result { + let t = now(); + let limits = self.limits; + 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>?)?)?), + ) -> 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) VALUES(?,?,?,?,?)", + ) + .bind(&attempt_id) + .bind(hash(browser)) + .bind(&email_mac) + .bind(self.code_mac(&attempt_id, &email_mac, &code)) + .bind(now() + CODE_TTL) + .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); +}