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.
This commit is contained in:
parent
f1883e5001
commit
cca084b0ae
20 changed files with 1756 additions and 59 deletions
1
Cargo.lock
generated
1
Cargo.lock
generated
|
|
@ -2984,6 +2984,7 @@ dependencies = [
|
|||
"cookie",
|
||||
"ed25519-dalek",
|
||||
"hex",
|
||||
"hmac",
|
||||
"lettre",
|
||||
"oauth2",
|
||||
"rand 0.10.3",
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ Last updated: 2026-10-24.
|
|||
- Authenticated, encrypted UDP voice relay in voice-node.
|
||||
- Voice access is revoked when a channel is deleted, a member is kicked or permissions change.
|
||||
- Senders get acknowledgements for their own chat messages.
|
||||
- Hub email sign-in by one-time code (HMAC-protected, rate-limited; enabled only when SMTP is configured; code-ready, not yet enabled in production). Handle/avatar selection after first sign-in is not implemented.
|
||||
- Channel webhooks, GitHub sign-in, hub service, screen sharing and media broadcast.
|
||||
- `cargo audit`: no known vulnerabilities in both workspaces (2026-10-24).
|
||||
|
||||
|
|
|
|||
|
|
@ -10,6 +10,8 @@
|
|||
|
||||
Связать второй способ входа можно из аутентифицированного аккаунта после повторного подтверждения; требуется доказать владение добавляемым способом. Отвязка последнего способа входа запрещена без настроенного восстановления. Добавление/отзыв устройств, email и способов входа сопровождаются уведомлениями.
|
||||
|
||||
**Статус реализации (Hub, этап 1):** вход по почте с одноразовым кодом работает (`hub/AUTH.md`). Новый аккаунт получает сгенерированный handle `u_...` и нейтральное имя; выбор handle, отображаемого имени и аватара после первого подтверждения ещё не реализован. Связывание второго способа входа, passkey/MFA и уведомления о новых способах входа тоже впереди.
|
||||
|
||||
## GitHub OAuth
|
||||
|
||||
Клиент открывает системный браузер. Hub хранит OAuth client_secret, принимает provider callback, проверяет state/PKCE и получает подтверждённую identity через GitHub API. Клиенту возвращается одноразовый код Vnox для конкретного login attempt с PKCE, а не GitHub bearer token в URL.
|
||||
|
|
|
|||
44
hub/AUTH.md
44
hub/AUTH.md
|
|
@ -1,4 +1,6 @@
|
|||
# GitHub sign-in
|
||||
# Hub sign-in: GitHub and email code
|
||||
|
||||
## GitHub
|
||||
|
||||
Configure `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET` together in the protected service environment. GitHub Apps and OAuth Apps both support this user authorization flow; the GitHub App private signing key is unnecessary at runtime. Register this exact callback:
|
||||
|
||||
|
|
@ -26,3 +28,43 @@ Back up SQLite with the issuer identity, protect backups as credentials, and app
|
|||
`cargo test -p vnox-hub` exercises the complete local browser flow against an injected provider, wrong-browser/replay/expiry rejection and logout CSRF. A real GitHub login requires the account owner to authorize in their browser; automated tests never impersonate consent.
|
||||
|
||||
Provider reference: [GitHub App user authorization and PKCE](https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-a-user-access-token-for-a-github-app). GitHub App resource permissions are configured by its owner; this flow adds no OAuth scopes and only calls the public user endpoint.
|
||||
|
||||
## Email sign-in (one-time code)
|
||||
|
||||
Available only when SMTP is configured (`SMTP_HOST` etc., see `deploy/central/hub.env.example`); `GET /v1/info` reports `capabilities.email_auth` as `"enabled"` exactly then, otherwise `"not_enabled"` and both endpoints answer `503 email_not_configured`. No other setting is needed: the code MAC key is generated on first start as `email-auth.key` (hex, 0600) in the private data directory.
|
||||
|
||||
### Browser contract
|
||||
|
||||
- `POST /v1/auth/email/start` with JSON `{"email": "...", "lang": "ru"|"en"}` (`lang` optional, default `ru`, unknown values fall back to `ru`). Answers `202 {"status":"code_requested","expires_in":600,"resend_after":60}` and sets the browser-binding cookie `__Host-vnox_email` (HttpOnly, Secure, SameSite=Lax, 10 minutes). The answer is identical for addresses with and without an account: start never looks up accounts, and the code is never in the response.
|
||||
- `POST /v1/auth/email/verify` with JSON `{"email": "...", "code": "12345678"}` and that cookie. On success: `200` with the same body as `GET /v1/auth/session` (`{authenticated:true,user,csrf_token}`) and the same `__Host-vnox_session` cookie (7 days, CSRF token) as GitHub. Any failure (no attempt, expired, exhausted, wrong address, wrong code, wrong browser) is the same `400 {"error":"invalid_code"}`.
|
||||
- Other errors: `400 invalid_email` / `invalid_request`, `403 invalid_origin`, `429 try_later`, `503 try_later`.
|
||||
|
||||
### CSRF and browser binding
|
||||
|
||||
These are unauthenticated POSTs, so there is no session CSRF token to compare. They are protected by three layers: the exact `Origin` must equal `PUBLIC_BASE_URL`'s origin (as for logout); the body must be JSON with no unknown fields and at most 1 KiB (not a form a foreign page can submit without a CORS preflight); and the code is bound to a random 256-bit `__Host-` cookie created by `start`, stored only as a SHA-256 hash with the attempt. A code can be redeemed only in the browser that requested it, so a cross-site request can neither plant an attacker's login in a victim's browser nor redeem a victim's code. A new `start` from the same browser replaces its previous attempt.
|
||||
|
||||
### Codes
|
||||
|
||||
Eight digits from the OS CSPRNG with rejection sampling, valid for ten minutes, five verification tries. The stored value is `HMAC-SHA256(server_key, attempt_id, address_mac, code)` (length-prefixed fields), not a bare hash; a database leak alone does not allow guessing the 10^8 code space offline. Comparison is constant-time. The try counter is incremented by the same atomic `UPDATE ... RETURNING` that selects the attempt, so parallel guesses cannot exceed the limit; a correct code is consumed by an atomic `DELETE ... RETURNING`, so exactly one request wins. Pending attempts hold only the address MAC, never the address.
|
||||
|
||||
### Rate limits (SQLite ledger of MACs, atomic check-and-record)
|
||||
|
||||
Per address 1 per 60 s and 5 per hour; per source (`X-Forwarded-For`, as GitHub login) 10 per hour; globally 300 per hour. Budget is spent when a request passes validation, even if delivery later fails. The in-memory per-IP limiter used by GitHub (20 per minute, 300 global) also applies to both endpoints. At most 4096 attempts are pending.
|
||||
|
||||
### Address handling and accounts
|
||||
|
||||
Addresses are trimmed and lowercased; only ASCII, a local part of `[a-z0-9._%+-]` without leading/trailing/double dots, at most 64 characters, a multi-label hostname whose last label is alphabetic, at most 254 characters in total. `+tag` is not stripped and Gmail dots are not folded. Unusual legal addresses are rejected on purpose.
|
||||
|
||||
The identity is `external_identities(provider='email', subject=<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, display name and avatar after registration is not implemented yet (see `design/accounts-and-avatars.md`). The address is kept in plain normalized form in `external_identities` because later features (security notices, adding a second sign-in method) need it; it is used for nothing except sending codes today.
|
||||
|
||||
### Mail and logging
|
||||
|
||||
The message is rendered by `mail::templates::render_email_code` (Russian or English) and contains the code but no button and no link. Delivery uses the existing TLS-only `Mailer` through the internal `CodeSender` trait; there is no endpoint to send arbitrary mail. Codes, addresses, cookies and request bodies are never logged by the application, and the Nginx `/v1/auth/` location writes no access or error logs. A delivery failure returns `503 try_later` and removes the attempt.
|
||||
|
||||
### Known limits
|
||||
|
||||
- A third party can use up an address's hourly budget and delay that person's email sign-in (GitHub still works). Accepted trade-off of per-address limits.
|
||||
- Email proves control of a mailbox only; it is not strong authentication (see design notes on later MFA/passkeys).
|
||||
- Rate-limit counters for the in-memory limiter reset on restart; the email ledger persists.
|
||||
- Access to the mailbox, or to the SQLite file together with `email-auth.key` during the ten-minute window, defeats the code.
|
||||
- Tests use an injected sender; real SMTP delivery has not been exercised from tests.
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ sha2.workspace = true
|
|||
oauth2 = { version = "5", default-features = false, features = ["timing-resistant-secret-traits"] }
|
||||
cookie = "0.18"
|
||||
subtle = "2.6"
|
||||
hmac.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
|
|
|||
|
|
@ -14,10 +14,12 @@ Community messages and voice never pass through this process.
|
|||
- Durable SQLite schema and issuer identity with a private `0600` key file.
|
||||
- TLS-only SMTP transport and HTML/plain-text transactional email templates.
|
||||
|
||||
Email authentication, GitHub OAuth, server registration/discovery, friends, DM
|
||||
storage and marketplace API are **not enabled**. There is no public endpoint for
|
||||
sending mail. Existing schema tables are foundations, not working authentication.
|
||||
Template links are previews of future routes; they do not create working tokens.
|
||||
GitHub OAuth and email one-time-code sign-in are implemented (`AUTH.md`); email sign-in
|
||||
is reported as enabled in `/v1/info` only when SMTP is configured. Server
|
||||
registration/discovery, friends, DM storage and marketplace API are **not enabled**.
|
||||
There is no public endpoint for sending mail. Other schema tables are foundations.
|
||||
Links in the older verify/new-device templates are previews of future routes; they do
|
||||
not create working tokens.
|
||||
|
||||
## Configuration
|
||||
|
||||
|
|
|
|||
26
hub/migrations/0003_email_auth.sql
Normal file
26
hub/migrations/0003_email_auth.sql
Normal 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);
|
||||
379
hub/src/auth/email.rs
Normal file
379
hub/src/auth/email.rs
Normal file
|
|
@ -0,0 +1,379 @@
|
|||
//! Passwordless email sign-in: address normalization, keyed MACs, one-time codes and
|
||||
//! rate limits. Nothing in this module logs addresses, codes or network sources.
|
||||
|
||||
use std::{future::Future, pin::Pin, sync::Arc};
|
||||
|
||||
use hmac::{Hmac, Mac};
|
||||
use sha2::Sha256;
|
||||
use sqlx::SqlitePool;
|
||||
use subtle::ConstantTimeEq;
|
||||
|
||||
use super::store::{hash, now};
|
||||
use crate::mail::templates::Email;
|
||||
|
||||
/// Lifetime of a pending code. Also the cookie lifetime of the attempt binding.
|
||||
pub const CODE_TTL: i64 = 600;
|
||||
/// Verification tries per issued code, counted before the comparison.
|
||||
pub const MAX_FAILURES: i64 = 5;
|
||||
/// Pending attempts kept at once; protects the table from being filled by anonymous traffic.
|
||||
const MAX_PENDING: i64 = 4096;
|
||||
const CODE_DIGITS: usize = 8;
|
||||
|
||||
/// Delivery boundary. The production implementation is [`crate::mail::Mailer`]; tests
|
||||
/// inject a recorder so no network traffic or real mail is ever produced.
|
||||
pub trait CodeSender: Send + Sync {
|
||||
fn send<'a>(
|
||||
&'a self,
|
||||
recipient: &'a str,
|
||||
email: Email,
|
||||
) -> Pin<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,
|
||||
}
|
||||
|
||||
impl Default for EmailLimits {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
address_cooldown: 60,
|
||||
per_address_hour: 5,
|
||||
per_source_hour: 10,
|
||||
global_hour: 300,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Enabled email sign-in. Holds the server MAC key; deliberately not Debug.
|
||||
pub struct EmailAuth {
|
||||
key: [u8; 32],
|
||||
pub sender: Arc<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])
|
||||
}
|
||||
|
||||
/// Atomically checks every send budget and records the send in one statement, so
|
||||
/// concurrent requests cannot overshoot a limit.
|
||||
pub async fn reserve_send(
|
||||
&self,
|
||||
pool: &SqlitePool,
|
||||
email_mac: &str,
|
||||
source_mac: &str,
|
||||
) -> anyhow::Result<bool> {
|
||||
let t = now();
|
||||
let limits = self.limits;
|
||||
let result = sqlx::query(
|
||||
"INSERT INTO email_send_log(email_mac,source_mac,sent_at) SELECT ?,?,? WHERE \
|
||||
(SELECT COUNT(*) FROM email_send_log WHERE email_mac=? AND sent_at>?)=0 AND \
|
||||
(SELECT COUNT(*) FROM email_send_log WHERE email_mac=? AND sent_at>?)<? 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(limits.global_hour)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(result.rows_affected() == 1)
|
||||
}
|
||||
|
||||
/// 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>,
|
||||
) -> anyhow::Result<(String, String)> {
|
||||
let mut transaction = pool.begin().await?;
|
||||
if let Some(previous) = previous_browser {
|
||||
sqlx::query("DELETE FROM email_attempts WHERE browser_hash=?")
|
||||
.bind(hash(previous))
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
}
|
||||
let pending: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM email_attempts")
|
||||
.fetch_one(&mut *transaction)
|
||||
.await?;
|
||||
anyhow::ensure!(pending < MAX_PENDING, "email login capacity reached");
|
||||
let attempt_id = super::store::token();
|
||||
let code = generate_code();
|
||||
let email_mac = self.email_mac(email);
|
||||
sqlx::query(
|
||||
"INSERT INTO email_attempts(attempt_id,browser_hash,email_mac,code_mac,expires_at) VALUES(?,?,?,?,?)",
|
||||
)
|
||||
.bind(&attempt_id)
|
||||
.bind(hash(browser))
|
||||
.bind(&email_mac)
|
||||
.bind(self.code_mac(&attempt_id, &email_mac, &code))
|
||||
.bind(now() + CODE_TTL)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
transaction.commit().await?;
|
||||
Ok((attempt_id, code))
|
||||
}
|
||||
|
||||
pub async fn discard_attempt(&self, pool: &SqlitePool, attempt_id: &str) {
|
||||
let _ = sqlx::query("DELETE FROM email_attempts WHERE attempt_id=?")
|
||||
.bind(attempt_id)
|
||||
.execute(pool)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Checks a submitted code for the attempt bound to this browser.
|
||||
///
|
||||
/// The try counter is incremented by the same atomic statement that selects the row, so
|
||||
/// parallel guesses cannot exceed [`MAX_FAILURES`]. A correct code is consumed by a
|
||||
/// `DELETE ... RETURNING`: exactly one caller can win it. Every failure mode (missing,
|
||||
/// expired, exhausted, wrong address, wrong code) is reported identically.
|
||||
pub async fn verify(
|
||||
&self,
|
||||
pool: &SqlitePool,
|
||||
email: &str,
|
||||
code: &str,
|
||||
browser: &str,
|
||||
) -> anyhow::Result<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());
|
||||
}
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
pub mod email;
|
||||
pub mod provider;
|
||||
mod routes;
|
||||
pub mod store;
|
||||
|
|
@ -22,6 +23,8 @@ 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)>>,
|
||||
}
|
||||
|
||||
|
|
@ -48,9 +51,18 @@ impl AuthService {
|
|||
pool,
|
||||
origin,
|
||||
provider,
|
||||
email: None,
|
||||
limits: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
/// 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()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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},
|
||||
|
|
@ -14,11 +17,20 @@ use serde_json::json;
|
|||
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))
|
||||
}
|
||||
|
|
@ -61,15 +73,21 @@ 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
|
||||
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)
|
||||
.unwrap_or_else(|| "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 +147,160 @@ 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 reserved = mail
|
||||
.reserve_send(&auth.pool, &mail.email_mac(&address), &source)
|
||||
.await;
|
||||
match reserved {
|
||||
Ok(true) => {}
|
||||
Ok(false) => 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 previous = cookie(&headers, EMAIL_BROWSER);
|
||||
let Ok((attempt_id, code)) = mail
|
||||
.create_attempt(&auth.pool, &address, &browser, previous.as_deref())
|
||||
.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 {
|
||||
|
|
@ -155,8 +317,7 @@ 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()) {
|
||||
if !same_origin(&state.auth, &headers) {
|
||||
return failure(StatusCode::FORBIDDEN, "invalid_origin");
|
||||
}
|
||||
let Some(token) = cookie(&headers, SESSION) else {
|
||||
|
|
|
|||
|
|
@ -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,25 @@ 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>> {
|
||||
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=? 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)> {
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -8,14 +8,44 @@ pub fn escape(value: &str) -> String {
|
|||
.replace('\'', "'")
|
||||
}
|
||||
|
||||
/// 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),
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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: ¶graph_refs,
|
||||
code,
|
||||
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: ¶graphs,
|
||||
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 [
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
if let Some(smtp) = &config.smtp {
|
||||
mail::Mailer::new(smtp)?;
|
||||
}
|
||||
let state = Arc::new(web::HubState {
|
||||
auth: Arc::new(vnox_hub::auth::AuthService::new(
|
||||
// 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 {
|
||||
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(auth),
|
||||
database,
|
||||
issuer,
|
||||
smtp_configured: config.smtp.is_some(),
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
821
hub/tests/email_auth.rs
Normal file
821
hub/tests/email_auth.rs
Normal file
|
|
@ -0,0 +1,821 @@
|
|||
//! Email one-time-code sign-in. Delivery is replaced by an in-memory recorder: no SMTP
|
||||
//! connection is opened and no message ever leaves the process.
|
||||
|
||||
use axum::{
|
||||
Router,
|
||||
body::{Body, to_bytes},
|
||||
http::{Request, Response, StatusCode},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
future::Future,
|
||||
pin::Pin,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
use tower::ServiceExt;
|
||||
use vnox_hub::{
|
||||
auth::{
|
||||
self,
|
||||
email::{CodeSender, EmailAuth, EmailLimits},
|
||||
provider::GitHubProfile,
|
||||
store,
|
||||
},
|
||||
database,
|
||||
identity::Issuer,
|
||||
mail::templates::Email,
|
||||
web::{self, HubState},
|
||||
};
|
||||
|
||||
const ORIGIN: &str = "https://central.loki-code.dev";
|
||||
|
||||
#[derive(Default)]
|
||||
struct Recorder {
|
||||
sent: Mutex<Vec<(String, Email)>>,
|
||||
fail: bool,
|
||||
}
|
||||
impl CodeSender for Recorder {
|
||||
fn send<'a>(
|
||||
&'a self,
|
||||
recipient: &'a str,
|
||||
email: Email,
|
||||
) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
if self.fail {
|
||||
anyhow::bail!("simulated outage");
|
||||
}
|
||||
self.sent
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push((recipient.to_owned(), email));
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
impl Recorder {
|
||||
fn last_code(&self) -> String {
|
||||
let sent = self.sent.lock().unwrap();
|
||||
let text = &sent.last().expect("a message was recorded").1.text;
|
||||
let digits: Vec<&str> = text
|
||||
.split(|c: char| !c.is_ascii_digit())
|
||||
.filter(|part| part.len() == 8)
|
||||
.collect();
|
||||
assert_eq!(digits.len(), 1, "exactly one code in the message");
|
||||
digits[0].to_owned()
|
||||
}
|
||||
fn count(&self) -> usize {
|
||||
self.sent.lock().unwrap().len()
|
||||
}
|
||||
}
|
||||
|
||||
struct Harness {
|
||||
_dir: tempfile::TempDir,
|
||||
state: Arc<HubState>,
|
||||
app: Router,
|
||||
mail: Arc<Recorder>,
|
||||
}
|
||||
|
||||
async fn harness_with(limits: EmailLimits, fail: bool, enabled: bool) -> Harness {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
}
|
||||
let issuer = Issuer::load_or_create(dir.path()).unwrap();
|
||||
let pool = database::open(dir.path(), &issuer).await.unwrap();
|
||||
let mail = Arc::new(Recorder {
|
||||
fail,
|
||||
..Default::default()
|
||||
});
|
||||
let mut auth =
|
||||
auth::AuthService::with_provider(pool.clone(), url::Url::parse(ORIGIN).unwrap(), None);
|
||||
if enabled {
|
||||
let mut email = EmailAuth::new([42; 32], mail.clone());
|
||||
email.limits = limits;
|
||||
auth = auth.with_email(email);
|
||||
}
|
||||
let state = Arc::new(HubState {
|
||||
database: pool,
|
||||
auth: Arc::new(auth),
|
||||
issuer,
|
||||
smtp_configured: enabled,
|
||||
started: std::time::Instant::now(),
|
||||
});
|
||||
Harness {
|
||||
_dir: dir,
|
||||
app: web::router(state.clone()),
|
||||
state,
|
||||
mail,
|
||||
}
|
||||
}
|
||||
|
||||
fn relaxed() -> EmailLimits {
|
||||
EmailLimits {
|
||||
address_cooldown: 0,
|
||||
per_address_hour: 1000,
|
||||
per_source_hour: 1000,
|
||||
global_hour: 1000,
|
||||
}
|
||||
}
|
||||
|
||||
async fn harness() -> Harness {
|
||||
harness_with(relaxed(), false, true).await
|
||||
}
|
||||
|
||||
struct Post<'a> {
|
||||
path: &'a str,
|
||||
body: Value,
|
||||
cookie: Option<&'a str>,
|
||||
origin: Option<&'a str>,
|
||||
ip: &'a str,
|
||||
}
|
||||
fn post<'a>(path: &'a str, body: Value) -> Post<'a> {
|
||||
Post {
|
||||
path,
|
||||
body,
|
||||
cookie: None,
|
||||
origin: Some(ORIGIN),
|
||||
ip: "198.51.100.7",
|
||||
}
|
||||
}
|
||||
impl Post<'_> {
|
||||
fn request(&self) -> Request<Body> {
|
||||
let mut builder = Request::builder()
|
||||
.method("POST")
|
||||
.uri(self.path)
|
||||
.header("content-type", "application/json")
|
||||
.header("x-forwarded-for", self.ip);
|
||||
if let Some(origin) = self.origin {
|
||||
builder = builder.header("origin", origin);
|
||||
}
|
||||
if let Some(cookie) = self.cookie {
|
||||
builder = builder.header("cookie", cookie);
|
||||
}
|
||||
builder.body(Body::from(self.body.to_string())).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
async fn send(app: &Router, request: Request<Body>) -> (StatusCode, Vec<String>, String) {
|
||||
let response: Response<Body> = app.clone().oneshot(request).await.unwrap();
|
||||
let status = response.status();
|
||||
let cookies = response
|
||||
.headers()
|
||||
.get_all("set-cookie")
|
||||
.iter()
|
||||
.map(|v| v.to_str().unwrap().to_owned())
|
||||
.collect();
|
||||
let body = String::from_utf8(
|
||||
to_bytes(response.into_body(), 65536)
|
||||
.await
|
||||
.unwrap()
|
||||
.to_vec(),
|
||||
)
|
||||
.unwrap();
|
||||
(status, cookies, body)
|
||||
}
|
||||
|
||||
fn pair(cookies: &[String], name: &str) -> String {
|
||||
cookies
|
||||
.iter()
|
||||
.find(|c| c.starts_with(&format!("{name}=")))
|
||||
.unwrap_or_else(|| panic!("{name} cookie missing"))
|
||||
.split(';')
|
||||
.next()
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
/// Requests a code; returns the browser-binding cookie pair.
|
||||
async fn start(h: &Harness, email: &str) -> String {
|
||||
let (status, cookies, _) = send(
|
||||
&h.app,
|
||||
post("/v1/auth/email/start", json!({"email": email})).request(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::ACCEPTED);
|
||||
pair(&cookies, "__Host-vnox_email")
|
||||
}
|
||||
|
||||
async fn verify(
|
||||
h: &Harness,
|
||||
cookie: Option<&str>,
|
||||
email: &str,
|
||||
code: &str,
|
||||
) -> (StatusCode, Vec<String>, String) {
|
||||
let mut request = post(
|
||||
"/v1/auth/email/verify",
|
||||
json!({"email": email, "code": code}),
|
||||
);
|
||||
request.cookie = cookie;
|
||||
send(&h.app, request.request()).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn full_flow_creates_neutral_account_and_session() {
|
||||
let h = harness().await;
|
||||
let (status, cookies, body) = send(
|
||||
&h.app,
|
||||
post(
|
||||
"/v1/auth/email/start",
|
||||
json!({"email": " Alice.Secret@Example.COM "}),
|
||||
)
|
||||
.request(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::ACCEPTED);
|
||||
let browser_cookie = cookies
|
||||
.iter()
|
||||
.find(|c| c.starts_with("__Host-vnox_email="))
|
||||
.unwrap();
|
||||
for attribute in [
|
||||
"Secure",
|
||||
"HttpOnly",
|
||||
"SameSite=Lax",
|
||||
"Path=/",
|
||||
"Max-Age=600",
|
||||
] {
|
||||
assert!(browser_cookie.contains(attribute), "{attribute}");
|
||||
}
|
||||
assert!(!browser_cookie.contains("Domain"));
|
||||
let browser = pair(&cookies, "__Host-vnox_email");
|
||||
let code = h.mail.last_code();
|
||||
// The code reaches the user only by mail, never in any part of the HTTP response.
|
||||
assert!(!body.contains(&code));
|
||||
assert!(!cookies.iter().any(|c| c.contains(&code)));
|
||||
{
|
||||
let sent = h.mail.sent.lock().unwrap();
|
||||
assert_eq!(sent[0].0, "alice.secret@example.com");
|
||||
// Only the bare site origin appears (footer); no link carries a path, query or code.
|
||||
let html = &sent[0].1.html;
|
||||
assert_eq!(html.matches("href=\"").count(), 1);
|
||||
assert!(html.contains(&format!("href=\"{ORIGIN}\"")));
|
||||
for url in sent[0]
|
||||
.1
|
||||
.text
|
||||
.split_whitespace()
|
||||
.filter(|w| w.starts_with("http"))
|
||||
{
|
||||
assert_eq!(url, ORIGIN);
|
||||
}
|
||||
assert!(!html.contains(&format!("{ORIGIN}/")) || html.contains("/assets/vnox-mark.png"));
|
||||
}
|
||||
// Only keyed MACs are stored.
|
||||
let row: (String, String) = sqlx::query_as("SELECT email_mac,code_mac FROM email_attempts")
|
||||
.fetch_one(&h.state.database)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_ne!(row.1, store::hash(&code));
|
||||
assert_ne!(row.1, code);
|
||||
assert!(!row.0.contains("alice"));
|
||||
let (status, cookies, body) =
|
||||
verify(&h, Some(&browser), "alice.secret@example.com ", &code).await;
|
||||
assert_eq!(status, StatusCode::OK, "{body}");
|
||||
let session_cookie = cookies
|
||||
.iter()
|
||||
.find(|c| c.starts_with("__Host-vnox_session="))
|
||||
.unwrap();
|
||||
for attribute in [
|
||||
"Secure",
|
||||
"HttpOnly",
|
||||
"SameSite=Lax",
|
||||
"Path=/",
|
||||
"Max-Age=604800",
|
||||
] {
|
||||
assert!(session_cookie.contains(attribute), "{attribute}");
|
||||
}
|
||||
let json: Value = serde_json::from_str(&body).unwrap();
|
||||
assert_eq!(json["authenticated"], true);
|
||||
assert_eq!(json["user"]["display_name"], "Vnox user");
|
||||
let handle = json["user"]["handle"].as_str().unwrap();
|
||||
assert!(handle.starts_with("u_") && !handle.contains("alice"));
|
||||
assert!(!body.to_lowercase().contains("alice"));
|
||||
assert!(!json["csrf_token"].as_str().unwrap().is_empty());
|
||||
// The same session endpoint now reports the user, with the same format.
|
||||
let (status, _, session_body) = send(
|
||||
&h.app,
|
||||
Request::builder()
|
||||
.uri("/v1/auth/session")
|
||||
.header("cookie", pair(&cookies, "__Host-vnox_session"))
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
let session: Value = serde_json::from_str(&session_body).unwrap();
|
||||
assert_eq!(session, json);
|
||||
let identity: (String, String) =
|
||||
sqlx::query_as("SELECT provider,subject FROM external_identities")
|
||||
.fetch_one(&h.state.database)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
identity,
|
||||
("email".into(), "alice.secret@example.com".into())
|
||||
);
|
||||
let ttl: i64 = sqlx::query_scalar("SELECT expires_at-created_at FROM web_sessions")
|
||||
.fetch_one(&h.state.database)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(ttl, 7 * 24 * 60 * 60);
|
||||
// Same address signs in again to the same account.
|
||||
let again = start(&h, "ALICE.secret@example.com").await;
|
||||
let code = h.mail.last_code();
|
||||
let (_, _, body) = verify(&h, Some(&again), "alice.secret@example.com", &code).await;
|
||||
let second: Value = serde_json::from_str(&body).unwrap();
|
||||
assert_eq!(second["user"]["user_id"], json["user"]["user_id"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wrong_code_is_rejected_and_attempts_are_exhausted() {
|
||||
let h = harness().await;
|
||||
let browser = start(&h, "a@example.com").await;
|
||||
let code = h.mail.last_code();
|
||||
let wrong = if code == "00000000" {
|
||||
"11111111"
|
||||
} else {
|
||||
"00000000"
|
||||
};
|
||||
for _ in 0..4 {
|
||||
let (status, cookies, body) = verify(&h, Some(&browser), "a@example.com", wrong).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
assert!(body.contains("invalid_code"));
|
||||
assert!(!cookies.iter().any(|c| c.starts_with("__Host-vnox_session")));
|
||||
}
|
||||
// The fifth try uses the last allowed attempt; a wrong guess burns it ...
|
||||
let (status, ..) = verify(&h, Some(&browser), "a@example.com", wrong).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
// ... so even the correct code is now refused, with the same answer.
|
||||
let (status, _, body) = verify(&h, Some(&browser), "a@example.com", &code).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
assert!(body.contains("invalid_code"));
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM accounts")
|
||||
.fetch_one(&h.state.database)
|
||||
.await
|
||||
.unwrap(),
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn correct_code_still_works_after_some_failures() {
|
||||
let h = harness().await;
|
||||
let browser = start(&h, "a@example.com").await;
|
||||
let code = h.mail.last_code();
|
||||
let wrong = if code == "00000000" {
|
||||
"11111111"
|
||||
} else {
|
||||
"00000000"
|
||||
};
|
||||
for _ in 0..4 {
|
||||
verify(&h, Some(&browser), "a@example.com", wrong).await;
|
||||
}
|
||||
let (status, ..) = verify(&h, Some(&browser), "a@example.com", &code).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn code_is_single_use_and_wrong_address_does_not_pass() {
|
||||
let h = harness().await;
|
||||
let browser = start(&h, "a@example.com").await;
|
||||
let code = h.mail.last_code();
|
||||
let (status, ..) = verify(&h, Some(&browser), "other@example.com", &code).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
let (status, ..) = verify(&h, Some(&browser), "a@example.com", &code).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
let (status, ..) = verify(&h, Some(&browser), "a@example.com", &code).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST, "replay");
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM email_attempts")
|
||||
.fetch_one(&h.state.database)
|
||||
.await
|
||||
.unwrap(),
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn parallel_redemption_of_one_code_has_exactly_one_winner() {
|
||||
let h = harness().await;
|
||||
let browser = start(&h, "a@example.com").await;
|
||||
let code = h.mail.last_code();
|
||||
let results = futures_join(
|
||||
(0..4)
|
||||
.map(|_| {
|
||||
let app = h.app.clone();
|
||||
let browser = browser.clone();
|
||||
let code = code.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut request = post(
|
||||
"/v1/auth/email/verify",
|
||||
json!({"email": "a@example.com", "code": code}),
|
||||
);
|
||||
request.cookie = Some(&browser);
|
||||
send(&app, request.request()).await.0
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(results.iter().filter(|s| **s == StatusCode::OK).count(), 1);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM accounts")
|
||||
.fetch_one(&h.state.database)
|
||||
.await
|
||||
.unwrap(),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
async fn futures_join(handles: Vec<tokio::task::JoinHandle<StatusCode>>) -> Vec<StatusCode> {
|
||||
let mut out = Vec::new();
|
||||
for handle in handles {
|
||||
out.push(handle.await.unwrap());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn expired_code_is_rejected() {
|
||||
let h = harness().await;
|
||||
let browser = start(&h, "a@example.com").await;
|
||||
let code = h.mail.last_code();
|
||||
sqlx::query("UPDATE email_attempts SET expires_at=0")
|
||||
.execute(&h.state.database)
|
||||
.await
|
||||
.unwrap();
|
||||
let (status, ..) = verify(&h, Some(&browser), "a@example.com", &code).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn code_is_bound_to_the_requesting_browser() {
|
||||
let h = harness().await;
|
||||
let browser = start(&h, "a@example.com").await;
|
||||
let code = h.mail.last_code();
|
||||
let stranger = format!("__Host-vnox_email={}", "ab".repeat(32));
|
||||
assert_eq!(
|
||||
verify(&h, None, "a@example.com", &code).await.0,
|
||||
StatusCode::BAD_REQUEST
|
||||
);
|
||||
assert_eq!(
|
||||
verify(&h, Some(&stranger), "a@example.com", &code).await.0,
|
||||
StatusCode::BAD_REQUEST
|
||||
);
|
||||
// Strangers neither consumed the code nor spent its tries.
|
||||
assert_eq!(
|
||||
verify(&h, Some(&browser), "a@example.com", &code).await.0,
|
||||
StatusCode::OK
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resend_replaces_the_previous_code_of_that_browser() {
|
||||
let h = harness().await;
|
||||
let first_browser = start(&h, "a@example.com").await;
|
||||
let first = h.mail.last_code();
|
||||
let mut request = post("/v1/auth/email/start", json!({"email": "a@example.com"}));
|
||||
request.cookie = Some(&first_browser);
|
||||
let (status, cookies, _) = send(&h.app, request.request()).await;
|
||||
assert_eq!(status, StatusCode::ACCEPTED);
|
||||
let second_browser = pair(&cookies, "__Host-vnox_email");
|
||||
let second = h.mail.last_code();
|
||||
assert_eq!(h.mail.count(), 2);
|
||||
if first != second {
|
||||
assert_eq!(
|
||||
verify(&h, Some(&first_browser), "a@example.com", &first)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::BAD_REQUEST
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
verify(&h, Some(&second_browser), "a@example.com", &second)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::OK
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn start_responds_identically_for_existing_and_new_addresses() {
|
||||
let h = harness().await;
|
||||
let browser = start(&h, "known@example.com").await;
|
||||
let code = h.mail.last_code();
|
||||
assert_eq!(
|
||||
verify(&h, Some(&browser), "known@example.com", &code)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::OK
|
||||
);
|
||||
let mut shapes = Vec::new();
|
||||
for address in ["known@example.com", "stranger@example.com"] {
|
||||
let (status, cookies, body) = send(
|
||||
&h.app,
|
||||
post("/v1/auth/email/start", json!({"email": address})).request(),
|
||||
)
|
||||
.await;
|
||||
let attributes: Vec<String> = cookies
|
||||
.iter()
|
||||
.map(|c| c.split_once('=').unwrap().0.to_owned() + &c[c.find(';').unwrap()..])
|
||||
.collect();
|
||||
shapes.push((status, body, attributes));
|
||||
}
|
||||
assert_eq!(shapes[0], shapes[1]);
|
||||
assert_eq!(shapes[0].0, StatusCode::ACCEPTED);
|
||||
// Both addresses really did receive a code message.
|
||||
assert_eq!(h.mail.count(), 3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn start_rejects_bad_addresses_and_cross_site_or_malformed_requests() {
|
||||
let h = harness().await;
|
||||
for bad in [
|
||||
"",
|
||||
"no-at",
|
||||
"a@b",
|
||||
"a b@example.com",
|
||||
"x@y.com\r\nBcc: z@y.com",
|
||||
] {
|
||||
let (status, cookies, body) = send(
|
||||
&h.app,
|
||||
post("/v1/auth/email/start", json!({"email": bad})).request(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
assert!(body.contains("invalid_email"));
|
||||
assert!(cookies.is_empty());
|
||||
}
|
||||
let mut request = post("/v1/auth/email/start", json!({"email": "a@example.com"}));
|
||||
request.origin = None;
|
||||
assert_eq!(
|
||||
send(&h.app, request.request()).await.0,
|
||||
StatusCode::FORBIDDEN
|
||||
);
|
||||
let mut request = post("/v1/auth/email/start", json!({"email": "a@example.com"}));
|
||||
request.origin = Some("https://evil.example");
|
||||
assert_eq!(
|
||||
send(&h.app, request.request()).await.0,
|
||||
StatusCode::FORBIDDEN
|
||||
);
|
||||
let mut request = post(
|
||||
"/v1/auth/email/verify",
|
||||
json!({"email": "a@example.com", "code": "12345678"}),
|
||||
);
|
||||
request.origin = Some("https://evil.example");
|
||||
assert_eq!(
|
||||
send(&h.app, request.request()).await.0,
|
||||
StatusCode::FORBIDDEN
|
||||
);
|
||||
// Form posts, unknown fields and oversized bodies never reach the handler logic.
|
||||
let form = Request::builder()
|
||||
.method("POST")
|
||||
.uri("/v1/auth/email/start")
|
||||
.header("origin", ORIGIN)
|
||||
.header("content-type", "application/x-www-form-urlencoded")
|
||||
.body(Body::from("email=a@example.com"))
|
||||
.unwrap();
|
||||
assert_eq!(send(&h.app, form).await.0, StatusCode::BAD_REQUEST);
|
||||
let extra = post(
|
||||
"/v1/auth/email/start",
|
||||
json!({"email": "a@example.com", "x": 1}),
|
||||
);
|
||||
assert_eq!(
|
||||
send(&h.app, extra.request()).await.0,
|
||||
StatusCode::BAD_REQUEST
|
||||
);
|
||||
let big = post("/v1/auth/email/start", json!({"email": "a".repeat(5000)}));
|
||||
assert_eq!(send(&h.app, big.request()).await.0, StatusCode::BAD_REQUEST);
|
||||
assert_eq!(h.mail.count(), 0);
|
||||
// Malformed code shape is refused before touching any attempt.
|
||||
let browser = start(&h, "a@example.com").await;
|
||||
for bad in ["1234567", "123456789", "1234abcd", "12345678"] {
|
||||
assert_eq!(
|
||||
verify(&h, Some(&browser), "a@example.com", bad).await.0,
|
||||
StatusCode::BAD_REQUEST
|
||||
);
|
||||
}
|
||||
let failures: i64 = sqlx::query_scalar("SELECT failures FROM email_attempts")
|
||||
.fetch_one(&h.state.database)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(failures, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn address_cooldown_and_hourly_limits() {
|
||||
let h = harness_with(EmailLimits::default(), false, true).await;
|
||||
start(&h, "a@example.com").await;
|
||||
let (status, ..) = send(
|
||||
&h.app,
|
||||
post("/v1/auth/email/start", json!({"email": "A@Example.com"})).request(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
status,
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"cooldown applies to the normalized address"
|
||||
);
|
||||
assert_eq!(h.mail.count(), 1);
|
||||
// Hourly cap: pretend the earlier sends happened a few minutes ago.
|
||||
sqlx::query("UPDATE email_send_log SET sent_at=sent_at-120")
|
||||
.execute(&h.state.database)
|
||||
.await
|
||||
.unwrap();
|
||||
for i in 0..4 {
|
||||
let (status, ..) = send(
|
||||
&h.app,
|
||||
post("/v1/auth/email/start", json!({"email": "a@example.com"})).request(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::ACCEPTED, "send {i}");
|
||||
sqlx::query("UPDATE email_send_log SET sent_at=sent_at-120")
|
||||
.execute(&h.state.database)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let (status, ..) = send(
|
||||
&h.app,
|
||||
post("/v1/auth/email/start", json!({"email": "a@example.com"})).request(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::TOO_MANY_REQUESTS);
|
||||
assert_eq!(h.mail.count(), 5);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn source_and_global_limits() {
|
||||
let h = harness_with(
|
||||
EmailLimits {
|
||||
address_cooldown: 0,
|
||||
per_address_hour: 100,
|
||||
per_source_hour: 3,
|
||||
global_hour: 5,
|
||||
},
|
||||
false,
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
let attempt = |i: usize, ip: &'static str| {
|
||||
let app = h.app.clone();
|
||||
async move {
|
||||
let mut request = post(
|
||||
"/v1/auth/email/start",
|
||||
json!({"email": format!("user{i}@example.com")}),
|
||||
);
|
||||
request.ip = ip;
|
||||
send(&app, request.request()).await.0
|
||||
}
|
||||
};
|
||||
for i in 0..3 {
|
||||
assert_eq!(attempt(i, "203.0.113.1").await, StatusCode::ACCEPTED);
|
||||
}
|
||||
assert_eq!(
|
||||
attempt(3, "203.0.113.1").await,
|
||||
StatusCode::TOO_MANY_REQUESTS
|
||||
);
|
||||
assert_eq!(attempt(4, "203.0.113.2").await, StatusCode::ACCEPTED);
|
||||
assert_eq!(attempt(5, "203.0.113.2").await, StatusCode::ACCEPTED);
|
||||
assert_eq!(
|
||||
attempt(6, "203.0.113.3").await,
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"global budget"
|
||||
);
|
||||
assert_eq!(h.mail.count(), 5);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn source_hashes_not_addresses_are_ledgered() {
|
||||
let h = harness().await;
|
||||
start(&h, "private.person@example.com").await;
|
||||
let row: (String, String) = sqlx::query_as("SELECT email_mac,source_mac FROM email_send_log")
|
||||
.fetch_one(&h.state.database)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!row.0.contains("private") && !row.1.contains("198.51"));
|
||||
assert_eq!(row.0.len(), 64);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delivery_failure_reports_unavailable_and_leaves_no_attempt() {
|
||||
let h = harness_with(relaxed(), true, true).await;
|
||||
let (status, cookies, _) = send(
|
||||
&h.app,
|
||||
post("/v1/auth/email/start", json!({"email": "a@example.com"})).request(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
|
||||
assert!(cookies.is_empty());
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM email_attempts")
|
||||
.fetch_one(&h.state.database)
|
||||
.await
|
||||
.unwrap(),
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn capability_follows_configuration_and_disabled_endpoints_refuse() {
|
||||
let enabled = harness().await;
|
||||
let disabled = harness_with(relaxed(), false, false).await;
|
||||
for (h, expected) in [(&enabled, "enabled"), (&disabled, "not_enabled")] {
|
||||
let (_, _, body) = send(
|
||||
&h.app,
|
||||
Request::builder()
|
||||
.uri("/v1/info")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
let info: Value = serde_json::from_str(&body).unwrap();
|
||||
assert_eq!(info["capabilities"]["email_auth"], expected);
|
||||
assert_eq!(info["smtp"]["public_send_endpoint"], false);
|
||||
}
|
||||
let (status, ..) = send(
|
||||
&disabled.app,
|
||||
post("/v1/auth/email/start", json!({"email": "a@example.com"})).request(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
|
||||
assert_eq!(disabled.mail.count(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn email_never_merges_with_a_github_account() {
|
||||
let h = harness().await;
|
||||
let github = store::upsert_identity(
|
||||
&h.state.database,
|
||||
&GitHubProfile {
|
||||
id: 77,
|
||||
login: "same-person".into(),
|
||||
name: Some("Same Person".into()),
|
||||
avatar_url: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let browser = start(&h, "same-person@example.com").await;
|
||||
let code = h.mail.last_code();
|
||||
let (_, _, body) = verify(&h, Some(&browser), "same-person@example.com", &code).await;
|
||||
let json: Value = serde_json::from_str(&body).unwrap();
|
||||
assert_ne!(json["user"]["user_id"].as_str().unwrap(), github.user_id);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM accounts")
|
||||
.fetch_one(&h.state.database)
|
||||
.await
|
||||
.unwrap(),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn new_login_replaces_an_existing_session() {
|
||||
let h = harness().await;
|
||||
let user = store::upsert_email_identity(&h.state.database, "old@example.com")
|
||||
.await
|
||||
.unwrap();
|
||||
let (old, _) = store::create_session(&h.state.database, &user.user_id)
|
||||
.await
|
||||
.unwrap();
|
||||
let browser = start(&h, "new@example.com").await;
|
||||
let code = h.mail.last_code();
|
||||
let mut request = post(
|
||||
"/v1/auth/email/verify",
|
||||
json!({"email": "new@example.com", "code": code}),
|
||||
);
|
||||
let cookie = format!("{browser}; __Host-vnox_session={old}");
|
||||
request.cookie = Some(&cookie);
|
||||
assert_eq!(send(&h.app, request.request()).await.0, StatusCode::OK);
|
||||
assert!(
|
||||
store::get_session(&h.state.database, &old)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn expired_attempts_and_old_ledger_rows_are_pruned() {
|
||||
let h = harness().await;
|
||||
start(&h, "a@example.com").await;
|
||||
sqlx::query("UPDATE email_attempts SET expires_at=0")
|
||||
.execute(&h.state.database)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("UPDATE email_send_log SET sent_at=0")
|
||||
.execute(&h.state.database)
|
||||
.await
|
||||
.unwrap();
|
||||
store::cleanup(&h.state.database).await.unwrap();
|
||||
for sql in [
|
||||
"SELECT COUNT(*) FROM email_attempts",
|
||||
"SELECT COUNT(*) FROM email_send_log",
|
||||
] {
|
||||
let n: i64 = sqlx::query_scalar(sql)
|
||||
.fetch_one(&h.state.database)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(n, 0, "{sql}");
|
||||
}
|
||||
}
|
||||
|
|
@ -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(
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue