Compare commits

...

4 commits

Author SHA1 Message Date
a2b0f26645
feat(hub): let users upload their own avatar
POST/DELETE /v1/account/avatar (session, exact Origin, CSRF) and public
GET /v1/avatars/<id>. Uploads are sniffed, size and dimension limited,
fully decoded, re-encoded to a 256x256 PNG without metadata and stored in
SQLite, one per account. avatar_url in the session points to it, with the
provider avatar as fallback.

Claude-Session: https://claude.ai/code/session_01GDjxLvBcnJqniFQGUGb1V4
2026-10-24 21:48:05 +02:00
fea876654b
fix(hub): bind email budget reserve to a bounded resend chain
The global reserve is claimed atomically with the budget check by deleting a live
attempt for the same address (under 5 failures, under 3 resends, chain under 30
minutes), so it cannot fund mail to other addresses, branch or race.
2026-10-24 17:48:20 +02:00
6ea14d0ec2
fix(hub): group IPv6 sources by /64 and reserve email budget for resends
Per-source limits no longer dodgeable by rotating IPv6 host bits, and a
separate global reserve lets browsers with a live attempt resend even when
fresh starts exhaust the hourly budget.
2026-10-24 17:45:36 +02:00
cca084b0ae
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.
2026-10-24 17:42:52 +02:00
28 changed files with 3380 additions and 301 deletions

157
Cargo.lock generated
View file

@ -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 = [

View file

@ -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

View file

@ -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).

View file

@ -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/<id>` (`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 дня» не применяется. Старые версии и кэши очищаются по отдельной политике.
## Ещё решения до публичного запуска

View file

@ -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<u8> {
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<u8> {
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<Vec<u8>> {
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<Vec<u8>> {
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());
}
}

View file

@ -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::<Sha256>::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<u8> {
cipher::encrypt_with_key(&self.s2c_key, &self.cid, seq, plaintext)
}
pub fn decrypt_c2s(&self, seq: u64, ciphertext: &[u8]) -> anyhow::Result<Vec<u8>> {
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<u8> {
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<u8> {
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<Vec<u8>> {
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());
}
}

View file

@ -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=<normalized address>)`, 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_<uuid>` 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/<id>`.
### 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/<id>"}`.
- `DELETE /v1/account/avatar`: removes the own photo. Answers `200 {"avatar_url": <provider URL or null>}`; repeating it is harmless.
- `GET /v1/avatars/<id>`: public. `<id>` 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.

View file

@ -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"

View file

@ -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/<id>` (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

View file

@ -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);

View file

@ -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;

View file

@ -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/<id>.
-- 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);

448
hub/src/auth/email.rs Normal file
View file

@ -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<Chain>,
},
}
/// 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<Box<dyn Future<Output = anyhow::Result<()>> + Send + 'a>>;
}
impl CodeSender for crate::mail::Mailer {
fn send<'a>(
&'a self,
recipient: &'a str,
email: Email,
) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + 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<dyn CodeSender>,
pub limits: EmailLimits,
}
impl EmailAuth {
pub fn new(key: [u8; 32], sender: Arc<dyn CodeSender>) -> 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 = <Hmac<Sha256> 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<Reservation> {
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<? AND resends<? AND chain_started>? 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>?)<? AND \
(SELECT COUNT(*) FROM email_send_log WHERE source_mac=? AND sent_at>?)<? AND \
(SELECT COUNT(*) FROM email_send_log WHERE sent_at>?)<?",
)
.bind(email_mac)
.bind(source_mac)
.bind(t)
.bind(email_mac)
.bind(t - limits.address_cooldown)
.bind(email_mac)
.bind(t - 3600)
.bind(limits.per_address_hour)
.bind(source_mac)
.bind(t - 3600)
.bind(limits.per_source_hour)
.bind(t - 3600)
.bind(global_limit)
.execute(&mut *transaction)
.await?;
if result.rows_affected() != 1 {
transaction.rollback().await?;
return Ok(Reservation::Denied);
}
transaction.commit().await?;
Ok(Reservation::Allowed {
chain: claimed.map(|(resends, started)| Chain {
resends: resends + 1,
started,
}),
})
}
/// Stores a new pending attempt, replacing the one bound to the browser's previous
/// cookie (a resend). Returns the generated code. Fails when capacity is reached.
pub async fn create_attempt(
&self,
pool: &SqlitePool,
email: &str,
browser: &str,
previous_browser: Option<&str>,
chain: Option<Chain>,
) -> 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<bool> {
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<? \
RETURNING attempt_id,email_mac,code_mac,failures",
)
.bind(hash(browser))
.bind(now())
.bind(MAX_FAILURES)
.fetch_optional(pool)
.await?;
let Some((attempt_id, stored_email, stored_code, failures)) = row else {
return Ok(false);
};
let email_ok = self
.email_mac(email)
.as_bytes()
.ct_eq(stored_email.as_bytes());
let code_ok = self
.code_mac(&attempt_id, &stored_email, code)
.as_bytes()
.ct_eq(stored_code.as_bytes());
if !bool::from(email_ok & code_ok) {
if failures >= MAX_FAILURES {
self.discard_attempt(pool, &attempt_id).await;
}
return Ok(false);
}
let consumed: Option<String> = 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<String> {
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 = <Hmac<Sha256> 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<Box<dyn Future<Output = anyhow::Result<()>> + 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<String> = (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<script>@b.cc",
] {
assert!(normalize_email(bad).is_none(), "{bad:?}");
}
assert!(normalize_email(&format!("{}@b.cc", "a".repeat(65))).is_none());
assert!(normalize_email(&format!("a@{}.cc", "b".repeat(64))).is_none());
assert!(normalize_email(&format!("a@{}.cc", "b.".repeat(130))).is_none());
}
}

View file

@ -1,3 +1,4 @@
pub mod email;
pub mod provider;
mod routes;
pub mod store;
@ -22,9 +23,20 @@ pub struct AuthService {
pub pool: SqlitePool,
pub origin: Url,
pub provider: Option<Arc<dyn IdentityProvider>>,
/// Present only when a mail transport is configured.
pub email: Option<email::EmailAuth>,
limits: Mutex<HashMap<String, (i64, u32)>>,
avatar_events: Mutex<HashMap<String, Vec<i64>>>,
/// Bounds concurrent image decodes, which are the most expensive thing a session can ask for.
pub avatar_decoding: tokio::sync::Semaphore,
}
/// Avatar changes (upload or removal) per account and per source within one hour.
const AVATAR_PER_USER_HOUR: usize = 10;
const AVATAR_PER_SOURCE_HOUR: usize = 30;
const AVATAR_WINDOW: i64 = 3600;
const AVATAR_TRACKED_KEYS: usize = 8192;
impl AuthService {
pub fn new(
pool: SqlitePool,
@ -48,9 +60,20 @@ impl AuthService {
pool,
origin,
provider,
email: None,
limits: Mutex::new(HashMap::new()),
avatar_events: Mutex::new(HashMap::new()),
avatar_decoding: tokio::sync::Semaphore::new(2),
}
}
/// Enables email sign-in. Callers do this only when SMTP is configured (or a test sender).
pub fn with_email(mut self, email: email::EmailAuth) -> Self {
self.email = Some(email);
self
}
pub fn email_enabled(&self) -> bool {
self.email.is_some()
}
pub fn configured(&self) -> bool {
self.provider.is_some()
}
@ -74,4 +97,29 @@ impl AuthService {
limits.entry(ip.to_owned()).or_insert((now, 0)).1 += 1;
true
}
/// Records one avatar change attempt for `user` and `source` and reports whether both
/// budgets still had room. A refused attempt is not recorded, so a blocked client does
/// not extend its own block.
pub fn allow_avatar(&self, user: &str, source: &str) -> bool {
let Ok(mut events) = self.avatar_events.lock() else {
return false;
};
let now = store::now();
events.retain(|_, times| {
times.retain(|at| now - *at < AVATAR_WINDOW);
!times.is_empty()
});
let user_key = format!("u:{user}");
let source_key = format!("s:{source}");
let count = |key: &str| events.get(key).map_or(0, Vec::len);
if count(&user_key) >= AVATAR_PER_USER_HOUR
|| count(&source_key) >= AVATAR_PER_SOURCE_HOUR
|| events.len() + 2 > AVATAR_TRACKED_KEYS
{
return false;
}
events.entry(user_key).or_default().push(now);
events.entry(source_key).or_default().push(now);
true
}
}

View file

@ -1,8 +1,11 @@
use super::{AuthService, store};
use crate::web::HubState;
use super::{AuthService, email, store};
use crate::{
mail::{layout::Lang, templates},
web::HubState,
};
use axum::{
Json, Router,
extract::{Query, State},
extract::{DefaultBodyLimit, Query, State, rejection::JsonRejection},
http::{HeaderMap, StatusCode, header},
response::{IntoResponse, Redirect, Response},
routing::{get, post},
@ -11,16 +14,31 @@ use cookie::{Cookie, SameSite};
use oauth2::{CsrfToken, PkceCodeChallenge};
use serde::Deserialize;
use serde_json::json;
mod avatar;
use std::sync::Arc;
use subtle::ConstantTimeEq;
const BROWSER: &str = "__Host-vnox_oauth";
const EMAIL_BROWSER: &str = "__Host-vnox_email";
const SESSION: &str = "__Host-vnox_session";
pub fn router() -> Router<Arc<HubState>> {
Router::new()
.route("/v1/auth/github/start", get(start))
.route("/v1/auth/github/callback", get(callback))
.route(
"/v1/auth/email/start",
post(email_start).layer(DefaultBodyLimit::max(1024)),
)
.route(
"/v1/auth/email/verify",
post(email_verify).layer(DefaultBodyLimit::max(1024)),
)
.route("/v1/auth/session", get(session))
.route("/v1/auth/logout", post(logout))
.route(
"/v1/account/avatar",
post(avatar::upload).delete(avatar::remove),
)
.route("/v1/avatars/{id}", get(avatar::serve))
}
fn failure(status: StatusCode, code: &'static str) -> Response {
(status, Json(json!({"error":code}))).into_response()
@ -61,15 +79,34 @@ fn set_cookie(response: &mut Response, name: &'static str, value: String, ttl: i
.headers_mut()
.append(header::SET_COOKIE, value.parse().expect("generated cookie"));
}
fn allowed(auth: &AuthService, headers: &HeaderMap) -> bool {
fn client_ip(headers: &HeaderMap) -> String {
// The loopback-only service trusts only the reverse proxy, which overwrites this header.
let ip = headers
// IPv6 sources are grouped by /64 (one subscriber's usual allocation or smaller), and
// IPv4-mapped addresses count as IPv4, so rotating host bits cannot dodge per-source limits.
use std::net::IpAddr;
match headers
.get("x-forwarded-for")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse::<std::net::IpAddr>().ok())
.map(|v| v.to_string())
.unwrap_or_else(|| "local".into());
auth.allow(&ip)
.and_then(|v| v.parse::<IpAddr>().ok())
{
Some(IpAddr::V6(v6)) => match v6.to_ipv4_mapped() {
Some(v4) => v4.to_string(),
None => {
let mut octets = v6.octets();
octets[8..].fill(0);
format!("{}/64", std::net::Ipv6Addr::from(octets))
}
},
Some(v4) => v4.to_string(),
None => "local".into(),
}
}
fn allowed(auth: &AuthService, headers: &HeaderMap) -> bool {
auth.allow(&client_ip(headers))
}
fn same_origin(auth: &AuthService, headers: &HeaderMap) -> bool {
let origin = auth.origin.origin().ascii_serialization();
headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) == Some(origin.as_str())
}
async fn start(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Response {
let auth = &state.auth;
@ -129,16 +166,167 @@ async fn callback(
let Ok((token, _)) = store::create_session(&auth.pool, &user.user_id).await else {
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
};
if let Some(old) = cookie(&headers, SESSION) {
drop_old_session(auth, &headers).await;
let mut response =
Redirect::to(auth.origin.join("account").expect("fixed path").as_str()).into_response();
set_cookie(&mut response, SESSION, token, store::SESSION_TTL);
set_cookie(&mut response, BROWSER, String::new(), 0);
response
}
/// A fresh login replaces any session the browser already holds (no session fixation).
async fn drop_old_session(auth: &AuthService, headers: &HeaderMap) {
if let Some(old) = cookie(headers, SESSION) {
let _ = sqlx::query("DELETE FROM web_sessions WHERE token_hash=?")
.bind(store::hash(&old))
.execute(&auth.pool)
.await;
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct EmailStart {
email: String,
lang: Option<String>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct EmailVerify {
email: String,
code: String,
}
/// Unauthenticated, state-changing POSTs have no session CSRF token to check. Instead:
/// the exact `Origin` is required (browsers always send it on cross-origin POSTs), the body
/// must be JSON (a non-simple request that cannot be forged by a plain form), and the code
/// is bound to a random `__Host-` cookie created by `start`, so a code can only be redeemed
/// by the browser that asked for it. A forged cross-site request can therefore neither
/// plant an attacker's login in a victim's browser nor redeem a victim's code.
async fn email_start(
State(state): State<Arc<HubState>>,
headers: HeaderMap,
body: Result<Json<EmailStart>, JsonRejection>,
) -> Response {
let auth = &state.auth;
let Some(mail) = &auth.email else {
return failure(StatusCode::SERVICE_UNAVAILABLE, "email_not_configured");
};
if !same_origin(auth, &headers) {
return failure(StatusCode::FORBIDDEN, "invalid_origin");
}
let Ok(Json(body)) = body else {
return failure(StatusCode::BAD_REQUEST, "invalid_request");
};
if !allowed(auth, &headers) {
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
}
let Some(address) = email::normalize_email(&body.email) else {
return failure(StatusCode::BAD_REQUEST, "invalid_email");
};
let lang = Lang::from_tag(body.lang.as_deref());
let source = mail.source_mac(&client_ip(&headers));
let previous = cookie(&headers, EMAIL_BROWSER);
let chain = match mail
.reserve_send(
&auth.pool,
&mail.email_mac(&address),
&source,
previous.as_deref(),
)
.await
{
Ok(email::Reservation::Allowed { chain }) => chain,
Ok(email::Reservation::Denied) => {
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
}
Err(_) => return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
};
// Housekeeping failures must not block sign-in; expiry is enforced on every read.
let _ = store::cleanup(&auth.pool).await;
let browser = store::token();
let Ok((attempt_id, code)) = mail
.create_attempt(&auth.pool, &address, &browser, previous.as_deref(), chain)
.await
else {
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
};
let message = match templates::render_email_code(&auth.origin, &code, lang) {
Ok(message) => message,
Err(_) => {
mail.discard_attempt(&auth.pool, &attempt_id).await;
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
}
};
// Whether the address already has an account is never consulted here, so the response,
// its timing and its cookie are identical for known and unknown addresses.
let delivery = tokio::time::timeout(
std::time::Duration::from_secs(25),
mail.sender.send(&address, message),
)
.await;
if !matches!(delivery, Ok(Ok(()))) {
mail.discard_attempt(&auth.pool, &attempt_id).await;
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
}
let mut response = (
StatusCode::ACCEPTED,
Json(json!({
"status": "code_requested",
"expires_in": email::CODE_TTL,
"resend_after": mail.limits.address_cooldown
})),
)
.into_response();
set_cookie(&mut response, EMAIL_BROWSER, browser, email::CODE_TTL);
response
}
async fn email_verify(
State(state): State<Arc<HubState>>,
headers: HeaderMap,
body: Result<Json<EmailVerify>, JsonRejection>,
) -> Response {
let auth = &state.auth;
let Some(mail) = &auth.email else {
return failure(StatusCode::SERVICE_UNAVAILABLE, "email_not_configured");
};
if !same_origin(auth, &headers) {
return failure(StatusCode::FORBIDDEN, "invalid_origin");
}
let Ok(Json(body)) = body else {
return failure(StatusCode::BAD_REQUEST, "invalid_request");
};
if !allowed(auth, &headers) {
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
}
let (Some(browser), Some(address)) = (
cookie(&headers, EMAIL_BROWSER),
email::normalize_email(&body.email),
) else {
return failure(StatusCode::BAD_REQUEST, "invalid_code");
};
if !email::valid_code_shape(&body.code) {
return failure(StatusCode::BAD_REQUEST, "invalid_code");
}
match mail
.verify(&auth.pool, &address, &body.code, &browser)
.await
{
Ok(true) => {}
Ok(false) => return failure(StatusCode::BAD_REQUEST, "invalid_code"),
Err(_) => return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
}
let Ok(user) = store::upsert_email_identity(&auth.pool, &address).await else {
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
};
let Ok((token, csrf)) = store::create_session(&auth.pool, &user.user_id).await else {
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
};
drop_old_session(auth, &headers).await;
let mut response =
Redirect::to(auth.origin.join("account").expect("fixed path").as_str()).into_response();
Json(json!({"authenticated":true,"user":user,"csrf_token":csrf})).into_response();
set_cookie(&mut response, SESSION, token, store::SESSION_TTL);
set_cookie(&mut response, BROWSER, String::new(), 0);
set_cookie(&mut response, EMAIL_BROWSER, String::new(), 0);
response
}
async fn session(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Response {
@ -154,24 +342,44 @@ async fn session(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Resp
}
Json(json!({"authenticated":false})).into_response()
}
async fn logout(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Response {
let origin = state.auth.origin.origin().ascii_serialization();
if headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) != Some(origin.as_str()) {
return failure(StatusCode::FORBIDDEN, "invalid_origin");
/// Session gate for state-changing requests by a signed-in user: exact `Origin`, a live
/// session, and the session's CSRF token in `X-CSRF-Token`. Returns the user and session token.
async fn authorized(
state: &HubState,
headers: &HeaderMap,
) -> Result<(store::User, String), Box<Response>> {
if !same_origin(&state.auth, headers) {
return Err(Box::new(failure(StatusCode::FORBIDDEN, "invalid_origin")));
}
let Some(token) = cookie(&headers, SESSION) else {
return failure(StatusCode::UNAUTHORIZED, "not_authenticated");
let Some(token) = cookie(headers, SESSION) else {
return Err(Box::new(failure(
StatusCode::UNAUTHORIZED,
"not_authenticated",
)));
};
let Ok(Some((_, csrf))) = store::get_session(&state.auth.pool, &token).await else {
return failure(StatusCode::UNAUTHORIZED, "not_authenticated");
let Ok(Some((user, csrf))) = store::get_session(&state.auth.pool, &token).await else {
return Err(Box::new(failure(
StatusCode::UNAUTHORIZED,
"not_authenticated",
)));
};
let supplied = headers
.get("x-csrf-token")
.map(|v| v.as_bytes())
.unwrap_or_default();
if !bool::from(csrf.as_bytes().ct_eq(supplied)) {
return failure(StatusCode::FORBIDDEN, "invalid_csrf");
return Err(Box::new(failure(StatusCode::FORBIDDEN, "invalid_csrf")));
}
Ok((user, token))
}
fn allowed_avatar(auth: &AuthService, user_id: &str, headers: &HeaderMap) -> bool {
auth.allow_avatar(user_id, &client_ip(headers))
}
async fn logout(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Response {
let token = match authorized(&state, &headers).await {
Ok((_, token)) => token,
Err(response) => return *response,
};
if sqlx::query("DELETE FROM web_sessions WHERE token_hash=?")
.bind(store::hash(&token))
.execute(&state.auth.pool)

View file

@ -0,0 +1,132 @@
//! Own-avatar endpoints. Changing requires an authenticated web session, the exact `Origin`
//! and the session's `X-CSRF-Token` (the same gate as logout). Serving is public.
use super::{HeaderMap, StatusCode, allowed_avatar, authorized, failure};
use crate::{avatar, web::HubState};
use axum::{
Json,
body::{Body, to_bytes},
extract::{Path, State},
http::{HeaderValue, header},
response::{IntoResponse, Response},
};
use serde_json::json;
use std::sync::Arc;
/// `POST /v1/account/avatar`: body is the raw image, `Content-Type` its type.
pub(super) async fn upload(
State(state): State<Arc<HubState>>,
headers: HeaderMap,
body: Body,
) -> Response {
let user = match authorized(&state, &headers).await {
Ok((user, _)) => user,
Err(response) => return *response,
};
let declared = headers
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.map(|v| {
v.split(';')
.next()
.unwrap_or("")
.trim()
.to_ascii_lowercase()
})
.unwrap_or_default();
if !matches!(declared.as_str(), "image/png" | "image/jpeg" | "image/webp") {
return failure(StatusCode::UNSUPPORTED_MEDIA_TYPE, "unsupported_type");
}
if !allowed_avatar(&state.auth, &user.user_id, &headers) {
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
}
// Reject by announced size first; the read below enforces the limit for chunked bodies.
let announced = headers
.get(header::CONTENT_LENGTH)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse::<usize>().ok());
if announced.is_some_and(|n| n > avatar::MAX_UPLOAD_BYTES) {
return failure(StatusCode::PAYLOAD_TOO_LARGE, "too_large");
}
let Ok(data) = to_bytes(body, avatar::MAX_UPLOAD_BYTES).await else {
return failure(StatusCode::PAYLOAD_TOO_LARGE, "too_large");
};
let Ok(permit) = state.auth.avatar_decoding.try_acquire() else {
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
};
let processed = tokio::task::spawn_blocking(move || avatar::normalize(&declared, &data)).await;
drop(permit);
let png = match processed {
Ok(Ok(png)) => png,
Ok(Err(avatar::AvatarError::UnsupportedType)) => {
return failure(StatusCode::UNSUPPORTED_MEDIA_TYPE, "unsupported_type");
}
Ok(Err(avatar::AvatarError::TypeMismatch)) => {
return failure(StatusCode::UNSUPPORTED_MEDIA_TYPE, "type_mismatch");
}
Ok(Err(avatar::AvatarError::BadDimensions)) => {
return failure(StatusCode::UNPROCESSABLE_ENTITY, "bad_dimensions");
}
Ok(Err(avatar::AvatarError::Invalid)) => {
return failure(StatusCode::UNPROCESSABLE_ENTITY, "invalid_image");
}
Err(_) => return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
};
match avatar::replace(&state.auth.pool, &user.user_id, &png).await {
Ok(url) => Json(json!({"avatar_url": url})).into_response(),
Err(_) => failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
}
}
/// `DELETE /v1/account/avatar`: drops the own photo; the answer carries the avatar now in
/// effect (the provider's, or null for the default).
pub(super) async fn remove(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Response {
let user = match authorized(&state, &headers).await {
Ok((user, _)) => user,
Err(response) => return *response,
};
if !allowed_avatar(&state.auth, &user.user_id, &headers) {
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
}
let pool = &state.auth.pool;
if avatar::remove(pool, &user.user_id).await.is_err() {
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
}
match avatar::provider_url(pool, &user.user_id).await {
Ok(url) => Json(json!({"avatar_url": url})).into_response(),
Err(_) => failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
}
}
/// `GET /v1/avatars/<id>`: public and immutable, because the id is the content hash.
pub(super) async fn serve(State(state): State<Arc<HubState>>, Path(id): Path<String>) -> Response {
if !avatar::valid_id(&id) {
return failure(StatusCode::NOT_FOUND, "not_found");
}
let (content_type, bytes) = match avatar::fetch(&state.auth.pool, &id).await {
Ok(Some(found)) => found,
Ok(None) => return failure(StatusCode::NOT_FOUND, "not_found"),
Err(_) => return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
};
let mut response = bytes.into_response();
let headers = response.headers_mut();
if let Ok(value) = HeaderValue::from_str(&content_type) {
headers.insert(header::CONTENT_TYPE, value);
}
headers.insert(
header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=31536000, immutable"),
);
headers.insert(
header::CONTENT_SECURITY_POLICY,
HeaderValue::from_static("default-src 'none'; sandbox; frame-ancestors 'none'"),
);
headers.insert(
header::CONTENT_DISPOSITION,
HeaderValue::from_static("inline; filename=\"avatar.png\""),
);
if let Ok(value) = HeaderValue::from_str(&format!("\"{id}\"")) {
headers.insert(header::ETAG, value);
}
response
}

View file

@ -41,6 +41,15 @@ pub async fn cleanup(pool: &SqlitePool) -> anyhow::Result<()> {
.bind(now())
.execute(pool)
.await?;
sqlx::query("DELETE FROM email_attempts WHERE expires_at<=?")
.bind(now())
.execute(pool)
.await?;
// The longest rate-limit window is one hour.
sqlx::query("DELETE FROM email_send_log WHERE sent_at<=?")
.bind(now() - 3600)
.execute(pool)
.await?;
Ok(())
}
@ -70,13 +79,6 @@ pub async fn consume_attempt(
}
pub async fn upsert_identity(pool: &SqlitePool, profile: &GitHubProfile) -> anyhow::Result<User> {
let subject = profile.id.to_string();
if let Some(user) = lookup_identity(pool, &subject).await? {
return Ok(user);
}
let id = Uuid::new_v4();
// Generated stable handle avoids claiming a privileged/reused handle from another provider.
let handle = format!("u_{}", id.simple());
let name = profile
.name
.as_deref()
@ -92,6 +94,28 @@ pub async fn upsert_identity(pool: &SqlitePool, profile: &GitHubProfile) -> anyh
&& url.password().is_none()
})
});
upsert_external(pool, "github.com", &profile.id.to_string(), &name, avatar).await
}
/// Account for a verified, normalized email address. The display name is deliberately
/// neutral: the local part of an address must never become a public profile string.
pub async fn upsert_email_identity(pool: &SqlitePool, email: &str) -> anyhow::Result<User> {
upsert_external(pool, "email", email, "Vnox user", None).await
}
async fn upsert_external(
pool: &SqlitePool,
provider: &str,
subject: &str,
name: &str,
avatar: Option<&str>,
) -> anyhow::Result<User> {
if let Some(user) = lookup_identity(pool, provider, subject).await? {
return Ok(user);
}
let id = Uuid::new_v4();
// Generated stable handle avoids claiming a privileged/reused handle from another provider.
let handle = format!("u_{}", id.simple());
let mut transaction = pool.begin().await?;
sqlx::query(
"INSERT INTO accounts(user_id,handle,created_at,display_name,avatar_url) VALUES(?,?,?,?,?)",
@ -103,21 +127,26 @@ pub async fn upsert_identity(pool: &SqlitePool, profile: &GitHubProfile) -> anyh
.bind(avatar)
.execute(&mut *transaction)
.await?;
let inserted = sqlx::query("INSERT INTO external_identities(provider,subject,user_id,linked_at) VALUES('github.com',?,?,?) ON CONFLICT(provider,subject) DO NOTHING")
.bind(&subject).bind(id.to_string()).bind(now()).execute(&mut *transaction).await?;
let inserted = sqlx::query("INSERT INTO external_identities(provider,subject,user_id,linked_at) VALUES(?,?,?,?) ON CONFLICT(provider,subject) DO NOTHING")
.bind(provider).bind(subject).bind(id.to_string()).bind(now()).execute(&mut *transaction).await?;
if inserted.rows_affected() == 0 {
transaction.rollback().await?;
} else {
transaction.commit().await?;
}
lookup_identity(pool, &subject)
lookup_identity(pool, provider, subject)
.await?
.ok_or_else(|| anyhow::anyhow!("identity transaction failed"))
}
async fn lookup_identity(pool: &SqlitePool, subject: &str) -> anyhow::Result<Option<User>> {
Ok(sqlx::query_as("SELECT a.user_id,a.handle,a.display_name,a.avatar_url FROM accounts a JOIN external_identities e ON e.user_id=a.user_id WHERE e.provider='github.com' AND e.subject=?")
.bind(subject).fetch_optional(pool).await?)
async fn lookup_identity(
pool: &SqlitePool,
provider: &str,
subject: &str,
) -> anyhow::Result<Option<User>> {
// The own avatar (same-origin path) wins over the provider URL kept on the account.
Ok(sqlx::query_as("SELECT a.user_id,a.handle,a.display_name,COALESCE('/v1/avatars/'||v.id,a.avatar_url) AS avatar_url FROM accounts a LEFT JOIN avatars v ON v.user_id=a.user_id JOIN external_identities e ON e.user_id=a.user_id WHERE e.provider=? AND e.subject=?")
.bind(provider).bind(subject).fetch_optional(pool).await?)
}
pub async fn create_session(pool: &SqlitePool, user_id: &str) -> anyhow::Result<(String, String)> {
@ -140,7 +169,7 @@ pub async fn get_session(
avatar_url: Option<String>,
csrf_token: String,
}
let row: Option<Row> = sqlx::query_as("SELECT a.user_id,a.handle,a.display_name,a.avatar_url,s.csrf_token FROM web_sessions s JOIN accounts a ON a.user_id=s.user_id WHERE s.token_hash=? AND s.expires_at>?")
let row: Option<Row> = sqlx::query_as("SELECT a.user_id,a.handle,a.display_name,COALESCE('/v1/avatars/'||v.id,a.avatar_url) AS avatar_url,s.csrf_token FROM web_sessions s JOIN accounts a ON a.user_id=s.user_id LEFT JOIN avatars v ON v.user_id=a.user_id WHERE s.token_hash=? AND s.expires_at>?")
.bind(hash(session)).bind(now()).fetch_optional(pool).await?;
Ok(row.map(|r| {
(

165
hub/src/avatar.rs Normal file
View file

@ -0,0 +1,165 @@
//! Own-avatar processing and storage.
//!
//! Uploads are never stored as received. The bytes are sniffed (PNG, JPEG or WebP only),
//! the header dimensions are checked before any pixel buffer exists, the image is fully
//! decoded under a memory limit, rotated by its EXIF orientation, cropped to a square,
//! resized and written again as a fresh PNG. A fresh PNG carries no EXIF, GPS, ICC, text or
//! other ancillary chunks from the source, so metadata cannot survive.
use std::io::Cursor;
use image::{
DynamicImage, ImageDecoder, ImageEncoder, ImageFormat, Limits, codecs::png::PngEncoder,
imageops::FilterType,
};
use sha2::{Digest, Sha256};
use sqlx::SqlitePool;
/// Request body limit (2 MiB).
pub const MAX_UPLOAD_BYTES: usize = 2 * 1024 * 1024;
/// Largest accepted source side, checked from the header before decoding.
pub const MAX_SOURCE_SIDE: u32 = 4096;
/// Smallest accepted source side.
pub const MIN_SOURCE_SIDE: u32 = 32;
/// Side of the stored square.
pub const OUTPUT_SIDE: u32 = 256;
/// Decoder allocation budget; a 4096x4096 RGBA frame is 64 MiB.
const MAX_DECODE_ALLOC: u64 = 128 * 1024 * 1024;
#[derive(Debug, PartialEq, Eq)]
pub enum AvatarError {
/// Not PNG, JPEG or WebP (SVG, GIF and everything else included).
UnsupportedType,
/// Declared and detected types differ.
TypeMismatch,
/// Larger than 4096 on a side, or smaller than 32.
BadDimensions,
/// Looks like a supported image but does not decode.
Invalid,
}
/// The MIME type of a supported format.
pub fn mime_for(format: ImageFormat) -> Option<&'static str> {
match format {
ImageFormat::Png => Some("image/png"),
ImageFormat::Jpeg => Some("image/jpeg"),
ImageFormat::WebP => Some("image/webp"),
_ => None,
}
}
/// Validates and re-encodes an upload. `declared` is the request `Content-Type` without
/// parameters. CPU and memory heavy: call from a blocking thread.
pub fn normalize(declared: &str, data: &[u8]) -> Result<Vec<u8>, AvatarError> {
let format = image::guess_format(data).map_err(|_| AvatarError::UnsupportedType)?;
let detected = mime_for(format).ok_or(AvatarError::UnsupportedType)?;
if detected != declared {
return Err(AvatarError::TypeMismatch);
}
let mut limits = Limits::default();
limits.max_image_width = Some(MAX_SOURCE_SIDE);
limits.max_image_height = Some(MAX_SOURCE_SIDE);
limits.max_alloc = Some(MAX_DECODE_ALLOC);
let mut reader = image::ImageReader::with_format(Cursor::new(data), format);
reader.limits(limits);
let mut decoder = reader.into_decoder().map_err(|error| match error {
image::ImageError::Limits(_) => AvatarError::BadDimensions,
_ => AvatarError::Invalid,
})?;
// Header-only: nothing has been allocated for pixels yet.
let (width, height) = decoder.dimensions();
if width > MAX_SOURCE_SIDE
|| height > MAX_SOURCE_SIDE
|| width < MIN_SOURCE_SIDE
|| height < MIN_SOURCE_SIDE
{
return Err(AvatarError::BadDimensions);
}
let orientation = decoder.orientation().map_err(|_| AvatarError::Invalid)?;
let mut picture = DynamicImage::from_decoder(decoder).map_err(|_| AvatarError::Invalid)?;
picture.apply_orientation(orientation);
let square = picture.resize_to_fill(OUTPUT_SIDE, OUTPUT_SIDE, FilterType::Lanczos3);
let mut out = Vec::new();
let encoder = PngEncoder::new(&mut out);
let written = if square.color().has_alpha() {
let pixels = square.to_rgba8();
encoder.write_image(
pixels.as_raw(),
OUTPUT_SIDE,
OUTPUT_SIDE,
image::ExtendedColorType::Rgba8,
)
} else {
let pixels = square.to_rgb8();
encoder.write_image(
pixels.as_raw(),
OUTPUT_SIDE,
OUTPUT_SIDE,
image::ExtendedColorType::Rgb8,
)
};
written.map_err(|_| AvatarError::Invalid)?;
Ok(out)
}
/// Public identifier: hex SHA-256 of the stored bytes.
pub fn content_id(bytes: &[u8]) -> String {
hex::encode(Sha256::digest(bytes))
}
/// True for a 64 character lowercase hex identifier.
pub fn valid_id(id: &str) -> bool {
id.len() == 64 && id.bytes().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f'))
}
/// Replaces the account's avatar atomically and returns its URL path.
pub async fn replace(pool: &SqlitePool, user_id: &str, png: &[u8]) -> anyhow::Result<String> {
let id = content_id(png);
sqlx::query(
"INSERT INTO avatars(user_id,id,content_type,bytes,created_at) VALUES(?,?,?,?,?) \
ON CONFLICT(user_id) DO UPDATE SET id=excluded.id,content_type=excluded.content_type,\
bytes=excluded.bytes,created_at=excluded.created_at",
)
.bind(user_id)
.bind(&id)
.bind("image/png")
.bind(png)
.bind(crate::auth::store::now())
.execute(pool)
.await?;
Ok(url_path(&id))
}
/// Deletes the account's own avatar; true if one existed.
pub async fn remove(pool: &SqlitePool, user_id: &str) -> anyhow::Result<bool> {
let done = sqlx::query("DELETE FROM avatars WHERE user_id=?")
.bind(user_id)
.execute(pool)
.await?;
Ok(done.rows_affected() > 0)
}
/// Content type and bytes for a public avatar id.
pub async fn fetch(pool: &SqlitePool, id: &str) -> anyhow::Result<Option<(String, Vec<u8>)>> {
Ok(
sqlx::query_as("SELECT content_type,bytes FROM avatars WHERE id=? LIMIT 1")
.bind(id)
.fetch_optional(pool)
.await?,
)
}
/// The provider avatar kept on the account, if any.
pub async fn provider_url(pool: &SqlitePool, user_id: &str) -> anyhow::Result<Option<String>> {
Ok(
sqlx::query_scalar("SELECT avatar_url FROM accounts WHERE user_id=?")
.bind(user_id)
.fetch_optional(pool)
.await?
.flatten(),
)
}
pub fn url_path(id: &str) -> String {
format!("/v1/avatars/{id}")
}

View file

@ -72,6 +72,37 @@ impl Issuer {
}
}
/// Loads a 32-byte server secret stored as hex in a 0600 file, creating it from the OS
/// CSPRNG on first use. The value is never logged and has no Debug/Serialize wrapper.
pub fn load_or_create_secret(directory: &Path, name: &str) -> Result<[u8; 32]> {
check_private_directory(directory)?;
let path = directory.join(name);
for _ in 0..2 {
match OpenOptions::new().read(true).open(&path) {
Ok(file) => {
check_private_permissions(&file)?;
if file.metadata()?.len() > 256 {
bail!("Hub secret file exceeds the expected size");
}
let text = std::io::read_to_string(file).context("reading Hub secret file")?;
return hex::decode(text.trim())
.ok()
.and_then(|bytes| <[u8; 32]>::try_from(bytes).ok())
.context("Hub secret file has invalid encoding or length");
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
use rand::Rng;
let mut bytes = [0u8; 32];
rand::rng().fill_bytes(&mut bytes);
// A concurrent creator winning the race is fine: the loop re-reads its file.
let _ = persist_new_file(&path, hex::encode(bytes).as_bytes());
}
Err(error) => return Err(error).context("opening Hub secret file"),
}
}
bail!("could not create Hub secret file")
}
fn check_private_permissions(file: &std::fs::File) -> Result<()> {
#[cfg(unix)]
{
@ -97,6 +128,10 @@ fn check_private_directory(directory: &Path) -> Result<()> {
// Publish a fully synced key file without replacing any concurrent issuer.
// A failed first write must never leave a truncated final identity behind.
fn persist_new_identity(path: &Path, identity: &StoredIdentity) -> Result<()> {
persist_new_file(path, &serde_json::to_vec_pretty(identity)?)
}
fn persist_new_file(path: &Path, contents: &[u8]) -> Result<()> {
let temporary = path.with_extension(format!("{}.tmp", Uuid::new_v4()));
let result = (|| -> Result<()> {
let mut options = OpenOptions::new();
@ -110,7 +145,7 @@ fn persist_new_identity(path: &Path, identity: &StoredIdentity) -> Result<()> {
let mut file = options
.open(&temporary)
.context("preparing Hub issuer identity")?;
file.write_all(&serde_json::to_vec_pretty(identity)?)
file.write_all(contents)
.context("writing Hub issuer identity")?;
file.sync_all().context("syncing Hub issuer identity")?;
}
@ -129,6 +164,43 @@ fn persist_new_identity(path: &Path, identity: &StoredIdentity) -> Result<()> {
mod tests {
use super::*;
#[test]
fn generated_secret_is_stable_private_and_validated() {
let directory = tempfile::tempdir().unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700))
.unwrap();
}
let first = load_or_create_secret(directory.path(), "s.key").unwrap();
assert_eq!(
first,
load_or_create_secret(directory.path(), "s.key").unwrap()
);
assert_ne!(first, [0; 32]);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(directory.path().join("s.key"))
.unwrap()
.permissions()
.mode();
assert_eq!(mode & 0o077, 0);
}
std::fs::write(directory.path().join("bad.key"), "zz").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(
directory.path().join("bad.key"),
std::fs::Permissions::from_mode(0o600),
)
.unwrap();
}
assert!(load_or_create_secret(directory.path(), "bad.key").is_err());
}
#[test]
fn publishing_never_overwrites_an_existing_identity_or_leaves_temp_files() {
let directory = tempfile::tempdir().unwrap();

View file

@ -1,4 +1,5 @@
pub mod auth;
pub mod avatar;
pub mod config;
pub mod database;
pub mod identity;

View file

@ -8,14 +8,44 @@ pub fn escape(value: &str) -> String {
.replace('\'', "&#39;")
}
/// Language of the fixed layout chrome (tagline, footer, hints).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Lang {
Ru,
En,
}
impl Lang {
/// Parses a client supplied language tag; anything unknown falls back to Russian.
pub fn from_tag(tag: Option<&str>) -> Self {
match tag {
Some("en") => Self::En,
_ => Self::Ru,
}
}
pub fn tag(self) -> &'static str {
match self {
Self::Ru => "ru",
Self::En => "en",
}
}
}
/// Optional call-to-action. Code messages deliberately carry none.
pub struct Link<'a> {
pub button: &'a str,
pub url: &'a str,
}
pub struct Content<'a> {
pub lang: Lang,
pub title: &'a str,
pub preheader: &'a str,
pub paragraphs: &'a [&'a str],
pub code: Option<&'a str>,
pub button: &'a str,
pub url: &'a str,
pub link: Option<Link<'a>>,
pub expiry: &'a str,
pub warning: &'a str,
pub origin: &'a str,
}
@ -33,27 +63,51 @@ pub fn render(content: &Content<'_>) -> String {
.collect::<String>();
let code = content.code.map(|value| format!("<p style=\"margin:22px 0;padding:18px;background:#111112;border:1px solid #494238;border-radius:10px;font-family:Consolas,monospace;font-size:30px;font-weight:700;letter-spacing:6px;text-align:center;color:#f0d7ae\">{}</p>", escape(value))).unwrap_or_default();
let title = escape(content.title);
let url = escape(content.url);
let (tagline, automatic) = match content.lang {
Lang::Ru => (
"Личное пространство для общения",
"Автоматическое письмо Vnox. Отвечать на него не нужно.",
),
Lang::En => (
"A personal space to talk",
"Automatic message from Vnox. No need to reply.",
),
};
let link = content
.link
.as_ref()
.map(|link| {
let url = escape(link.url);
let button = escape(link.button);
let hint = match content.lang {
Lang::Ru => "Если кнопка не открывается, скопируй ссылку:",
Lang::En => "If the button does not open, copy the link:",
};
format!(
r##"<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:23px 0 17px"><tr><td bgcolor="#d5b58a" style="border-radius:9px"><a href="{url}" style="display:inline-block;padding:14px 26px;color:#231d16;text-decoration:none;font-size:15px;font-weight:700;border-radius:9px">{button}</a></td></tr></table>
<p style="margin:0 0 9px;font-size:12px;color:#aca49a">{hint}</p>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td bgcolor="#171718" style="padding:13px;border:1px solid #3c3732;border-radius:9px;word-break:break-all;font-size:12px;line-height:20px"><a href="{url}" style="color:#d8bd98;text-decoration:none">{url}</a></td></tr></table>"##
)
})
.unwrap_or_default();
let origin = escape(content.origin);
format!(
r##"<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="dark light"><title>{title}</title></head>
r##"<!doctype html><html lang="{lang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="dark light"><title>{title}</title></head>
<body style="margin:0;padding:0;background:#101011" bgcolor="#101011">
<div style="display:none;max-height:0;overflow:hidden;opacity:0">{preheader}</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#101011"><tr><td align="center" style="padding:32px 12px">
<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" bgcolor="#1c1c1e" style="width:100%;max-width:600px;border:1px solid #383634;border-radius:18px;overflow:hidden;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Arial,sans-serif">
<tr><td bgcolor="#38312a" style="background:#38312a;background-image:linear-gradient(125deg,#514033 0%,#39312c 55%,#242426 100%);padding:30px 32px 32px">
<table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr><td width="42" height="42" align="center" bgcolor="#151516" style="border-radius:11px;color:#e8d5b8;font-size:19px;font-weight:800"><img src="{origin}/assets/vnox-mark.png" width="42" height="42" alt="V" style="display:block;border:0;border-radius:11px"></td><td style="padding-left:12px;color:#f6f0e7;font-size:23px;font-weight:700">Vnox</td></tr></table>
<p style="margin:25px 0 10px;color:#d1b998;font-size:12px">Личное пространство для общения</p>
<p style="margin:25px 0 10px;color:#d1b998;font-size:12px">{tagline}</p>
<h1 style="margin:0;color:#fff9ef;font-size:28px;line-height:35px;font-weight:700">{title}</h1>
</td></tr><tr><td style="padding:32px 32px 12px">{paragraphs}{code}
<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:23px 0 17px"><tr><td bgcolor="#d5b58a" style="border-radius:9px"><a href="{url}" style="display:inline-block;padding:14px 26px;color:#231d16;text-decoration:none;font-size:15px;font-weight:700;border-radius:9px">{button}</a></td></tr></table>
</td></tr><tr><td style="padding:32px 32px 12px">{paragraphs}{code}{link}
<p style="margin:0 0 24px;font-size:13px;line-height:21px;color:#aca49a">{expiry}</p>
<p style="margin:0 0 9px;font-size:12px;color:#aca49a">Если кнопка не открывается, скопируй ссылку:</p>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td bgcolor="#171718" style="padding:13px;border:1px solid #3c3732;border-radius:9px;word-break:break-all;font-size:12px;line-height:20px"><a href="{url}" style="color:#d8bd98;text-decoration:none">{url}</a></td></tr></table>
<p style="margin:26px 0 18px;font-size:13px;line-height:21px;color:#aca49a">Не запрашивал это действие? Не передавай код или ссылку другим людям. Если это письмо о новом устройстве, проверь активные сеансы.</p>
</td></tr><tr><td bgcolor="#171718" style="border-top:1px solid #383634;padding:21px 32px;color:#9e978d;font-size:12px;line-height:20px">Автоматическое письмо Vnox. Отвечать на него не нужно.<br><a href="{origin}" style="color:#d8bd98;text-decoration:none">{origin}</a></td></tr></table></td></tr></table></body></html>"##,
<p style="margin:26px 0 18px;font-size:13px;line-height:21px;color:#aca49a">{warning}</p>
</td></tr><tr><td bgcolor="#171718" style="border-top:1px solid #383634;padding:21px 32px;color:#9e978d;font-size:12px;line-height:20px">{automatic}<br><a href="{origin}" style="color:#d8bd98;text-decoration:none">{origin}</a></td></tr></table></td></tr></table></body></html>"##,
lang = content.lang.tag(),
preheader = escape(content.preheader),
button = escape(content.button),
expiry = escape(content.expiry),
warning = escape(content.warning),
)
}

View file

@ -1,7 +1,7 @@
use anyhow::{Result, bail};
use url::Url;
use super::layout::{self, Content};
use super::layout::{self, Content, Lang, Link};
use crate::config::parse_origin;
/// A rendered transactional message; no recipient or delivery happens here.
@ -70,13 +70,17 @@ pub fn render(origin: &Url, kind: Kind<'_>) -> Result<Email> {
let paragraph_refs = paragraphs.iter().map(String::as_str).collect::<Vec<_>>();
let origin_text = origin.as_str().trim_end_matches('/');
let content = Content {
lang: Lang::Ru,
title,
preheader: title,
paragraphs: &paragraph_refs,
code,
button,
url: url.as_str(),
link: Some(Link {
button,
url: url.as_str(),
}),
expiry,
warning: "Не запрашивал это действие? Не передавай код или ссылку другим людям. Если это письмо о новом устройстве, проверь активные сеансы.",
origin: origin_text,
};
let text = format!(
@ -93,6 +97,54 @@ pub fn render(origin: &Url, kind: Kind<'_>) -> Result<Email> {
})
}
/// Sign-in code message for the passwordless email flow. It carries no link and no
/// button: the code is typed into the page that requested it, never opened from a URL.
pub fn render_email_code(origin: &Url, code: &str, lang: Lang) -> Result<Email> {
parse_origin(origin.as_str())?;
if code.len() != 8 || !code.bytes().all(|byte| byte.is_ascii_digit()) {
bail!("email code must contain exactly eight ASCII digits");
}
let (title, paragraph, expiry, warning, subject, label) = match lang {
Lang::Ru => (
"Код для входа в Vnox",
"Введи этот код на странице входа. Он подойдёт только в том браузере, где ты запросил вход.",
"Код действует 10 минут и срабатывает один раз.",
"Не запрашивал вход? Просто проигнорируй письмо и никому не сообщай код.",
"Vnox: код для входа",
"Код",
),
Lang::En => (
"Your Vnox sign-in code",
"Enter this code on the sign-in page. It only works in the browser where you asked to sign in.",
"The code is valid for 10 minutes and works once.",
"Did not ask to sign in? Ignore this message and never share the code.",
"Vnox: sign-in code",
"Code",
),
};
let origin_text = origin.as_str().trim_end_matches('/');
let paragraphs = [paragraph];
let html = layout::render(&Content {
lang,
title,
preheader: title,
paragraphs: &paragraphs,
code: Some(code),
link: None,
expiry,
warning,
origin: origin_text,
});
let text = format!(
"Vnox\n\n{title}\n\n{paragraph}\n\n{label}: {code}\n\n{expiry}\n\n{warning}\n\n{origin_text}\n"
);
Ok(Email {
subject: subject.to_owned(),
text,
html,
})
}
pub fn write_previews(directory: &std::path::Path, origin: &Url) -> Result<()> {
std::fs::create_dir_all(directory)?;
for (name, kind) in [

View file

@ -43,15 +43,20 @@ async fn main() -> Result<()> {
let database = database::open(&config.data_dir, &issuer).await?;
// Validate configured SMTP eagerly without making startup depend on the
// availability of an external provider. There is no public mail endpoint.
// Email sign-in is enabled exactly when SMTP is configured. The code MAC key lives in
// the private data directory next to the issuer identity and is generated on first use.
let mut auth = vnox_hub::auth::AuthService::new(
database.clone(),
config.origin.clone(),
config.github.as_ref(),
)?;
if let Some(smtp) = &config.smtp {
mail::Mailer::new(smtp)?;
let mailer = Arc::new(mail::Mailer::new(smtp)?);
let key = vnox_hub::identity::load_or_create_secret(&config.data_dir, "email-auth.key")?;
auth = auth.with_email(vnox_hub::auth::email::EmailAuth::new(key, mailer));
}
let state = Arc::new(web::HubState {
auth: Arc::new(vnox_hub::auth::AuthService::new(
database.clone(),
config.origin.clone(),
config.github.as_ref(),
)?),
auth: Arc::new(auth),
database,
issuer,
smtp_configured: config.smtp.is_some(),

View file

@ -75,7 +75,7 @@ async fn info(State(state): State<Arc<HubState>>) -> Json<Value> {
"uptime_seconds": state.started.elapsed().as_secs(),
"smtp": {"configured": state.smtp_configured, "public_send_endpoint": false},
"capabilities": {
"email_auth": "not_enabled",
"email_auth": if state.auth.email_enabled() { "enabled" } else { "not_enabled" },
"github_auth": if state.auth.configured() { "enabled" } else { "not_enabled" },
"server_registry": "not_enabled",
"friends": "not_enabled",
@ -106,6 +106,7 @@ async fn index() -> Html<&'static str> {
async fn headers(request: Request<Body>, next: Next) -> Response {
let mut response = next.run(request).await;
// Handlers that set their own cache policy or CSP (avatar delivery) keep them.
for (name, value) in [
("cache-control", "no-store"),
("x-content-type-options", "nosniff"),
@ -115,6 +116,10 @@ async fn headers(request: Request<Body>, next: Next) -> Response {
"default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; frame-ancestors 'none'",
),
] {
let present = response.headers().contains_key(name);
if present && matches!(name, "cache-control" | "content-security-policy") {
continue;
}
response
.headers_mut()
.insert(name, HeaderValue::from_static(value));

742
hub/tests/avatar.rs Normal file
View file

@ -0,0 +1,742 @@
use axum::{
Router,
body::{Body, to_bytes},
http::{Method, Request, Response, StatusCode},
};
use image::{ExtendedColorType, ImageEncoder, RgbImage};
use std::sync::Arc;
use tower::ServiceExt;
use vnox_hub::{
auth::{
self,
provider::GitHubProfile,
store::{self, User},
},
database,
identity::Issuer,
web::{self, HubState},
};
const ORIGIN: &str = "https://central.loki-code.dev";
const GITHUB_AVATAR: &str = "https://avatars.githubusercontent.com/u/123?v=4";
struct Session {
user: User,
token: String,
csrf: String,
}
struct Fixture {
_dir: tempfile::TempDir,
state: Arc<HubState>,
app: Router,
}
async fn fixture() -> Fixture {
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 auth = auth::AuthService::with_provider(pool.clone(), ORIGIN.parse().unwrap(), None);
let state = Arc::new(HubState {
database: pool,
auth: Arc::new(auth),
issuer,
smtp_configured: false,
started: std::time::Instant::now(),
});
Fixture {
_dir: dir,
app: web::router(state.clone()),
state,
}
}
impl Fixture {
async fn email_user(&self, address: &str) -> Session {
let user = store::upsert_email_identity(&self.state.database, address)
.await
.unwrap();
self.session(user).await
}
async fn github_user(&self) -> Session {
let profile = GitHubProfile {
id: 123,
login: "person".into(),
name: Some("Person".into()),
avatar_url: Some(GITHUB_AVATAR.into()),
};
let user = store::upsert_identity(&self.state.database, &profile)
.await
.unwrap();
self.session(user).await
}
async fn session(&self, user: User) -> Session {
let (token, csrf) = store::create_session(&self.state.database, &user.user_id)
.await
.unwrap();
Session { user, token, csrf }
}
async fn send(&self, request: Request<Body>) -> Response<Body> {
self.app.clone().oneshot(request).await.unwrap()
}
/// A well-formed request; callers override pieces to break it.
fn change<'a>(
&'a self,
method: Method,
session: Option<&Session>,
csrf: Option<&str>,
origin: Option<&str>,
content_type: &str,
body: Vec<u8>,
) -> impl std::future::Future<Output = Response<Body>> + use<'a> {
let mut request = Request::builder()
.method(method)
.uri("/v1/account/avatar")
.header("content-type", content_type);
if let Some(session) = session {
request = request.header("cookie", format!("__Host-vnox_session={}", session.token));
}
if let Some(csrf) = csrf {
request = request.header("x-csrf-token", csrf);
}
if let Some(origin) = origin {
request = request.header("origin", origin);
}
self.send(request.body(Body::from(body)).unwrap())
}
async fn upload(&self, session: &Session, content_type: &str, body: Vec<u8>) -> Response<Body> {
self.change(
Method::POST,
Some(session),
Some(&session.csrf),
Some(ORIGIN),
content_type,
body,
)
.await
}
async fn remove(&self, session: &Session) -> Response<Body> {
self.change(
Method::DELETE,
Some(session),
Some(&session.csrf),
Some(ORIGIN),
"application/json",
Vec::new(),
)
.await
}
async fn get(&self, path: &str) -> Response<Body> {
self.send(Request::builder().uri(path).body(Body::empty()).unwrap())
.await
}
async fn session_avatar(&self, session: &Session) -> serde_json::Value {
let response = self
.send(
Request::builder()
.uri("/v1/auth/session")
.header("cookie", format!("__Host-vnox_session={}", session.token))
.body(Body::empty())
.unwrap(),
)
.await;
json(response).await["user"]["avatar_url"].clone()
}
async fn avatar_rows(&self) -> i64 {
sqlx::query_scalar("SELECT COUNT(*) FROM avatars")
.fetch_one(&self.state.database)
.await
.unwrap()
}
}
async fn json(response: Response<Body>) -> serde_json::Value {
serde_json::from_slice(&to_bytes(response.into_body(), 1 << 20).await.unwrap()).unwrap()
}
async fn bytes(response: Response<Body>) -> Vec<u8> {
to_bytes(response.into_body(), 1 << 22)
.await
.unwrap()
.to_vec()
}
fn picture(width: u32, height: u32) -> RgbImage {
RgbImage::from_fn(width, height, |x, y| {
image::Rgb([(x % 256) as u8, (y % 256) as u8, ((x + y) % 256) as u8])
})
}
fn png(width: u32, height: u32) -> Vec<u8> {
let mut out = Vec::new();
image::codecs::png::PngEncoder::new(&mut out)
.write_image(
picture(width, height).as_raw(),
width,
height,
ExtendedColorType::Rgb8,
)
.unwrap();
out
}
fn jpeg(width: u32, height: u32) -> Vec<u8> {
let mut out = Vec::new();
image::codecs::jpeg::JpegEncoder::new(&mut out)
.write_image(
picture(width, height).as_raw(),
width,
height,
ExtendedColorType::Rgb8,
)
.unwrap();
out
}
fn webp(width: u32, height: u32) -> Vec<u8> {
let mut out = Vec::new();
image::codecs::webp::WebPEncoder::new_lossless(&mut out)
.write_image(
picture(width, height).as_raw(),
width,
height,
ExtendedColorType::Rgb8,
)
.unwrap();
out
}
/// Inserts an EXIF APP1 segment carrying `marker` right after the JPEG start marker.
fn with_exif(jpeg: &[u8], marker: &str) -> Vec<u8> {
let mut payload = b"Exif\0\0".to_vec();
payload.extend_from_slice(marker.as_bytes());
let mut out = jpeg[..2].to_vec();
out.extend_from_slice(&[0xFF, 0xE1]);
out.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes());
out.extend_from_slice(&payload);
out.extend_from_slice(&jpeg[2..]);
out
}
fn crc32(data: &[u8]) -> u32 {
let mut crc = !0u32;
for byte in data {
crc ^= u32::from(*byte);
for _ in 0..8 {
crc = if crc & 1 == 1 {
(crc >> 1) ^ 0xEDB8_8320
} else {
crc >> 1
};
}
}
!crc
}
/// Inserts an ancillary chunk before IEND.
fn with_chunk(png: &[u8], kind: &[u8; 4], data: &[u8]) -> Vec<u8> {
let end = png.len() - 12;
let mut out = png[..end].to_vec();
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
let mut body = kind.to_vec();
body.extend_from_slice(data);
out.extend_from_slice(&body);
out.extend_from_slice(&crc32(&body).to_be_bytes());
out.extend_from_slice(&png[end..]);
out
}
/// Rewrites the IHDR size of a PNG and fixes its CRC: a tiny file that claims huge pixels.
fn claim_size(png: &[u8], width: u32, height: u32) -> Vec<u8> {
let mut out = png.to_vec();
out[16..20].copy_from_slice(&width.to_be_bytes());
out[20..24].copy_from_slice(&height.to_be_bytes());
let crc = crc32(&out[12..29]);
out[29..33].copy_from_slice(&crc.to_be_bytes());
out
}
fn chunk_names(png: &[u8]) -> Vec<String> {
let mut names = Vec::new();
let mut at = 8;
while at + 8 <= png.len() {
let length = u32::from_be_bytes(png[at..at + 4].try_into().unwrap()) as usize;
names.push(String::from_utf8_lossy(&png[at + 4..at + 8]).into_owned());
at += 12 + length;
}
names
}
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
haystack.windows(needle.len()).any(|w| w == needle)
}
async fn assert_error(response: Response<Body>, status: StatusCode, code: &str) {
assert_eq!(response.status(), status);
assert_eq!(response.headers()["cache-control"], "no-store");
assert_eq!(json(response).await["error"], code);
}
#[tokio::test]
async fn upload_reencodes_to_a_square_png_and_serves_it_with_safe_headers() {
let fx = fixture().await;
let alice = fx.email_user("alice@example.com").await;
assert_eq!(fx.session_avatar(&alice).await, serde_json::Value::Null);
let response = fx.upload(&alice, "image/png", png(600, 300)).await;
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()["cache-control"], "no-store");
let url = json(response).await["avatar_url"]
.as_str()
.unwrap()
.to_owned();
assert!(url.starts_with("/v1/avatars/"));
assert_eq!(url.len(), "/v1/avatars/".len() + 64);
assert_eq!(fx.session_avatar(&alice).await, url);
let served = fx.get(&url).await;
assert_eq!(served.status(), StatusCode::OK);
let h = served.headers();
assert_eq!(h["content-type"], "image/png");
assert_eq!(h["x-content-type-options"], "nosniff");
assert_eq!(h["cache-control"], "public, max-age=31536000, immutable");
assert!(
h["content-security-policy"]
.to_str()
.unwrap()
.contains("default-src 'none'")
);
assert!(h.get("set-cookie").is_none());
let body = bytes(served).await;
let decoded = image::load_from_memory(&body).unwrap();
assert_eq!((decoded.width(), decoded.height()), (256, 256));
// The id is the content hash.
assert_eq!(
url,
format!("/v1/avatars/{}", vnox_hub::avatar::content_id(&body))
);
}
#[tokio::test]
async fn jpeg_and_webp_are_accepted_and_exif_and_png_text_chunks_are_removed() {
let fx = fixture().await;
let alice = fx.email_user("alice@example.com").await;
let tagged = with_exif(&jpeg(200, 200), "SECRET-GPS-48.8566N");
assert!(contains(&tagged, b"SECRET-GPS"));
let response = fx.upload(&alice, "image/jpeg", tagged).await;
assert_eq!(response.status(), StatusCode::OK);
let url = json(response).await["avatar_url"]
.as_str()
.unwrap()
.to_owned();
let body = bytes(fx.get(&url).await).await;
assert!(!contains(&body, b"SECRET"));
assert!(!contains(&body, b"Exif"));
assert_eq!(chunk_names(&body), ["IHDR", "IDAT", "IEND"]);
let marked = with_chunk(&png(100, 100), b"tEXt", b"Comment\0SECRET-AUTHOR");
let marked = with_chunk(&marked, b"eXIf", b"SECRET-EXIF");
assert!(contains(&marked, b"SECRET-AUTHOR"));
let response = fx.upload(&alice, "image/png", marked).await;
assert_eq!(response.status(), StatusCode::OK);
let url = json(response).await["avatar_url"]
.as_str()
.unwrap()
.to_owned();
let body = bytes(fx.get(&url).await).await;
assert!(!contains(&body, b"SECRET"));
assert_eq!(chunk_names(&body), ["IHDR", "IDAT", "IEND"]);
let response = fx.upload(&alice, "image/webp", webp(120, 90)).await;
assert_eq!(response.status(), StatusCode::OK);
let url = json(response).await["avatar_url"]
.as_str()
.unwrap()
.to_owned();
let served = fx.get(&url).await;
assert_eq!(served.headers()["content-type"], "image/png");
let decoded = image::load_from_memory(&bytes(served).await).unwrap();
assert_eq!((decoded.width(), decoded.height()), (256, 256));
}
#[tokio::test]
async fn changes_need_session_csrf_and_exact_origin() {
let fx = fixture().await;
let alice = fx.email_user("alice@example.com").await;
let image = png(64, 64);
for method in [Method::POST, Method::DELETE] {
let go = |session, csrf: Option<&str>, origin: Option<&str>| {
fx.change(
method.clone(),
session,
csrf,
origin,
"image/png",
image.clone(),
)
};
assert_error(
go(None, Some(&alice.csrf), Some(ORIGIN)).await,
StatusCode::UNAUTHORIZED,
"not_authenticated",
)
.await;
assert_error(
go(Some(&alice), None, Some(ORIGIN)).await,
StatusCode::FORBIDDEN,
"invalid_csrf",
)
.await;
assert_error(
go(Some(&alice), Some("0".repeat(64).as_str()), Some(ORIGIN)).await,
StatusCode::FORBIDDEN,
"invalid_csrf",
)
.await;
for origin in [
None,
Some("https://evil.example"),
Some("http://central.loki-code.dev"),
Some("https://central.loki-code.dev:8443"),
Some("null"),
] {
assert_error(
go(Some(&alice), Some(&alice.csrf), origin).await,
StatusCode::FORBIDDEN,
"invalid_origin",
)
.await;
}
}
assert_eq!(fx.avatar_rows().await, 0);
}
#[tokio::test]
async fn another_account_cannot_change_or_remove_my_avatar() {
let fx = fixture().await;
let alice = fx.email_user("alice@example.com").await;
let bob = fx.email_user("bob@example.com").await;
let response = fx.upload(&alice, "image/png", png(64, 64)).await;
let alice_url = json(response).await["avatar_url"]
.as_str()
.unwrap()
.to_owned();
// Bob's session with Alice's CSRF token, and Alice's cookie with Bob's token.
let mixed = [
fx.change(
Method::DELETE,
Some(&bob),
Some(&alice.csrf),
Some(ORIGIN),
"x/y",
vec![],
)
.await,
fx.change(
Method::POST,
Some(&bob),
Some(&alice.csrf),
Some(ORIGIN),
"image/png",
png(64, 64),
)
.await,
fx.change(
Method::DELETE,
Some(&alice),
Some(&bob.csrf),
Some(ORIGIN),
"x/y",
vec![],
)
.await,
];
for response in mixed {
assert_eq!(response.status(), StatusCode::FORBIDDEN);
}
assert_eq!(fx.session_avatar(&alice).await, alice_url);
assert_eq!(fx.session_avatar(&bob).await, serde_json::Value::Null);
// Bob acting as himself only affects Bob.
assert_eq!(
fx.upload(&bob, "image/png", png(80, 80)).await.status(),
StatusCode::OK
);
assert_eq!(fx.remove(&bob).await.status(), StatusCode::OK);
assert_eq!(fx.session_avatar(&alice).await, alice_url);
assert_eq!(fx.get(&alice_url).await.status(), StatusCode::OK);
}
#[tokio::test]
async fn wrong_types_and_swapped_extensions_are_refused() {
let fx = fixture().await;
let alice = fx.email_user("alice@example.com").await;
let gif = b"GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;".to_vec();
let svg = br#"<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><script>alert(1)</script></svg>"#.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);
}

1022
hub/tests/email_auth.rs Normal file

File diff suppressed because it is too large Load diff

View file

@ -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(

View file

@ -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);
}