chore(history): squash 67 commit(s) from 2026-09-25

- feat(accounts): persist device links with opaque hashed tokens, list and revoke endpoints
- feat(frontend): app shell, routing and landing page with the chat-command hero
- feat(frontend): Cyrillic-first fonts (Unbounded, Onest, JetBrains Mono); add i18next and motion
- docs: free mod, bilingual site, one-click download, theme editor, public profiles, rich landing in plans
- feat(accounts): internal gRPC AuthenticateDevice guarded by internal key
- feat(frontend): ru/en i18n with typed per-feature dictionaries and language switch
- feat(accounts): GET /me profile endpoint
- feat(gateway): scaffold crate with config validation and health check
- feat(gateway): reverse proxy to accounts and configs services
- feat(gateway): resolve identity once from access JWT or device token via gRPC
- feat(gateway): per-route and global rate limits with Retry-After
- feat(gateway): CORS for the site origin; docs for gateway and internal contract
- feat(configs): scaffold service with schema, config validation and health check
- feat(configs): four config slots per account with list, get and save
- feat(configs): permanent share codes with regenerate and public load-by-code
- feat(accounts): GetPublicProfiles gRPC for showcase author info
- style(accounts,common): apply rustfmt to existing sources
- feat(configs): public showcase with publish, browse, detail and copy-to-slot
- feat(backend): public profile endpoint and showcase author filter
- fix(gateway): silence clippy collapsible-if and needless-ref warnings
- docs(backend): configs-service implemented; Подсистема 1 backend complete
- feat(mod): add Optimize module skeleton with OptimizeState holder
- feat(mod): gate glass blur behind Optimize no_glass knob
- feat(mod): cut MotionBlur and DoF sample counts behind lite_post knob
- feat(mod): trim procedural sky noise behind lite_sky knob
- feat(mod): drop fade gradients and digit rolls behind lean_hud knob
- docs(todo): mark Optimize module phase 9.2 complete
- refactor(mod): drop dead Renderer2D compatibility shims
- refactor(mod): prune unreachable Renderer2D overload towers
- refactor(mod): remove unused Renderer2D overloads and imports
- docs(todo): mark Renderer2D giant-splitting done (2179 to 1597)
- refactor(mod): extract shader id constants from LoVisualRenderPipelines
- docs(todo): record registry wave 2026-09-25 (Renderer2D, pipelines)
- refactor(mod): move Renderer2D instance state into base class
- refactor(mod): extract Renderer2DRounded drawing family
- refactor(mod): extract Renderer2DPath connector and chamfer family
- refactor(mod): extract Renderer2DShapes circle line and texture primitives
- refactor(mod): extract Renderer2DGlass and Renderer2DItem families
- refactor(mod): prune Renderer2D imports after facade split
- docs(todo): record Renderer2D facade inheritance split (1597 to 475)
- docs: easter eggs — .env honeypot, konami troll mode, devtools banner, IDDQD config, breakable 404 block, 418 teapot
- feat(mod): introduce surface style system core (SurfaceStyle, StyleSpec, StyleConfig, SurfaceRenderer)
- refactor(mod): delegate HudRenderUtil liquid glass draws to SurfaceRenderer (dedupe glass constants)
- refactor(mod): route bespoke glass call sites through SurfaceRenderer.plateSpec
- feat(mod): add Auto option to HUD bg effects via shared HudBgStyles resolution
- feat(mod): flat fallback for no-glass optimize mode and persist global HUD config
- feat(mod): default HUD bg effects to Auto so the global surface style drives widgets
- feat(mod): add global cycle-style hotkey with surface style notification
- feat(mod): add surface style swatch strip under the global style picker
- feat(gateway): reject ambiguous paths and answer .env probes with a honeypot
- fix(gateway): charge failed credentials against the rate limit, allow stale ones on /auth
- feat(frontend): ClickGui theme pipeline generated from the mod, live site theming
- feat(frontend): landing v2 hero — voxel/particle backdrop, live ClickGui, theme strip
- docs(todo): drop the FPS A/B measurement from phase 9.3, close phase 9
- feat(gateway): answer /coffee with a 418 teapot
- feat(frontend): land the rest of landing v2 — HUD, module wall, showcase, FAQ, footer
- feat(frontend): one-click download from GitHub releases, changelog page, release CI
- feat(frontend): theme editor with live ClickGui preview, mod-compatible export and share links
- fix(frontend): landing HUD playground now shows real mod widgets (fps, coordinates, module list, keybinds, ping)
- style(frontend): apply ClickGui glass effect to landing HUD playground widgets
- fix(frontend): prevent color field row overflow in theme editor grid
- fix(frontend): never attach stale bearer token to /auth/* requests
- fix(configs): unpublish/publish can no longer bypass moderation
- refactor(accounts): shrink auth/handlers.rs under the 250-line cap
- fix(accounts): tolerate concurrent refresh without killing every session
- fix(gateway): minor hardening from the backend review
- feat(configs): IDDQD easter egg config
This commit is contained in:
loki5512344 2026-09-25 20:22:13 +02:00
parent 72bc4c7148
commit 7f4b532f99
257 changed files with 13085 additions and 6582 deletions

File diff suppressed because it is too large Load diff

View file

@ -32,6 +32,8 @@ aws-config = "1"
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] }
anyhow = "1"
dotenvy = "0.15"
tonic = "0.14"
[dev-dependencies]
axum-test = "21"
tokio-stream = { version = "0.1", features = ["net"] }

View file

@ -0,0 +1,2 @@
-- Device tokens are looked up by hash on every mod request (via gateway gRPC).
CREATE UNIQUE INDEX device_links_token_hash_idx ON device_links (device_token_hash);

View file

@ -0,0 +1,14 @@
-- Tracks when a refresh token was revoked specifically *by rotation* (as
-- opposed to logout or reuse-detection), so a short grace window can
-- tolerate two concurrent refreshes of the same token (e.g. two tabs)
-- without treating the second one as token theft.
ALTER TABLE refresh_tokens ADD COLUMN rotated_at TIMESTAMPTZ;
-- Used by rotate_refresh to decide whether a just-rotated token is still
-- within the grace window.
CREATE INDEX idx_refresh_tokens_rotated_at ON refresh_tokens(rotated_at)
WHERE rotated_at IS NOT NULL;
-- Used by the accounts::repo "early" badge (count of accounts created
-- before a given account's created_at).
CREATE INDEX IF NOT EXISTS idx_accounts_created_at ON accounts(created_at);

View file

@ -0,0 +1,88 @@
use super::repo;
use crate::error::AppError;
use axum::{
Json,
extract::{Path, State},
};
use chrono::{DateTime, Utc};
use common::internal::GatewayIdentity;
use serde::Serialize;
use uuid::Uuid;
#[derive(Clone)]
pub struct AccountsState {
pub pool: sqlx::PgPool,
pub avatar_base_url: String,
}
#[derive(Serialize)]
pub struct MeResponse {
pub id: Uuid,
pub email: String,
pub display_nick: String,
pub role: String,
pub avatar_url: Option<String>,
pub created_at: DateTime<Utc>,
}
pub async fn me(
State(state): State<AccountsState>,
identity: GatewayIdentity,
) -> Result<Json<MeResponse>, AppError> {
let account = repo::find_by_id(&state.pool, identity.account_id)
.await?
.ok_or(AppError::Unauthorized)?;
let avatar_url = repo::avatar_key(&state.pool, account.id)
.await?
.map(|key| format!("{}/{key}", state.avatar_base_url));
Ok(Json(MeResponse {
id: account.id,
email: account.email,
display_nick: account.display_nick,
role: account.role,
avatar_url,
created_at: account.created_at,
}))
}
/// Public profile for the site's `/u/:id` page: no identity required, and no
/// private fields (email, role) — only what showcase viewers may see.
#[derive(Serialize)]
pub struct PublicProfileResponse {
pub id: Uuid,
pub display_nick: String,
pub avatar_url: Option<String>,
pub created_at: DateTime<Utc>,
pub badges: Vec<String>,
}
/// Accounts are handed out in `created_at` order, so the first 1000 to sign
/// up get the `early` badge.
const EARLY_ADOPTER_LIMIT: i64 = 1000;
pub async fn public_profile(
State(state): State<AccountsState>,
Path(raw): Path<String>,
) -> Result<Json<PublicProfileResponse>, AppError> {
let not_found = || AppError::NotFound("no such account".into());
let id = Uuid::parse_str(&raw).map_err(|_| not_found())?;
let account = repo::find_by_id(&state.pool, id)
.await?
.ok_or_else(not_found)?;
let avatar_url = repo::avatar_key(&state.pool, account.id)
.await?
.map(|key| format!("{}/{key}", state.avatar_base_url));
let rank = repo::account_rank(&state.pool, account.created_at).await?;
let badges = if rank < EARLY_ADOPTER_LIMIT {
vec!["early".to_owned()]
} else {
Vec::new()
};
Ok(Json(PublicProfileResponse {
id: account.id,
display_nick: account.display_nick,
avatar_url,
created_at: account.created_at,
badges,
}))
}

View file

@ -1,2 +1,3 @@
pub mod handlers;
pub mod model;
pub mod repo;

View file

@ -1,3 +1,5 @@
use crate::auth::password::MAX_PASSWORD_BYTES;
use crate::error::AppError;
use chrono::{DateTime, Utc};
use serde::Serialize;
use uuid::Uuid;
@ -13,3 +15,106 @@ pub struct Account {
pub can_publish_addons: bool,
pub created_at: DateTime<Utc>,
}
/// Validates and normalizes a registration request. Returns the trimmed
/// `(email, nick)` on success. Lives here (rather than `auth::handlers`) so
/// that handler file stays small and this stays testable independent of axum.
pub fn validate_register(
email: &str,
password: &str,
nick: &str,
) -> Result<(String, String), AppError> {
let email = email.trim();
if email.is_empty() {
return Err(AppError::Validation("email must not be empty".into()));
}
if email.len() > 254 {
return Err(AppError::Validation(
"email must be at most 254 characters".into(),
));
}
let mut parts = email.split('@');
let (Some(local), Some(domain)) = (parts.next(), parts.next()) else {
return Err(AppError::Validation("email must contain '@'".into()));
};
if parts.next().is_some() || local.is_empty() || domain.is_empty() {
return Err(AppError::Validation(
"email must have exactly one '@' with non-empty parts".into(),
));
}
let nick = nick.trim();
let nick_len = nick.chars().count();
if nick_len == 0 || nick_len > 32 {
return Err(AppError::Validation(
"nick must be 1 to 32 characters".into(),
));
}
if nick.chars().any(|c| c.is_control()) {
return Err(AppError::Validation(
"nick must not contain control characters".into(),
));
}
if password.chars().count() < 8 {
return Err(AppError::Validation(
"password must be at least 8 characters".into(),
));
}
if password.len() > MAX_PASSWORD_BYTES {
return Err(AppError::Validation(format!(
"password must be at most {MAX_PASSWORD_BYTES} bytes"
)));
}
Ok((email.to_string(), nick.to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
fn valid() -> (String, String, String) {
(
"user@example.com".into(),
"password123".into(),
"Rider".into(),
)
}
#[test]
fn valid_request_passes() {
let (email, password, nick) = valid();
assert!(validate_register(&email, &password, &nick).is_ok());
}
#[test]
fn short_password_is_rejected() {
let (email, _, nick) = valid();
assert!(validate_register(&email, "short12", &nick).is_err());
}
#[test]
fn empty_email_is_rejected() {
let (_, password, nick) = valid();
assert!(validate_register(" ", &password, &nick).is_err());
}
#[test]
fn email_without_at_is_rejected() {
let (_, password, nick) = valid();
assert!(validate_register("not-an-email", &password, &nick).is_err());
}
#[test]
fn empty_nick_is_rejected() {
let (email, password, _) = valid();
assert!(validate_register(&email, &password, " ").is_err());
}
#[test]
fn thirty_three_char_nick_is_rejected() {
let (email, password, _) = valid();
assert!(validate_register(&email, &password, &"a".repeat(33)).is_err());
}
}

View file

@ -58,6 +58,40 @@ pub async fn set_avatar(pool: &PgPool, account_id: Uuid, s3_key: &str) -> Result
Ok(())
}
pub async fn avatar_key(pool: &PgPool, account_id: Uuid) -> Result<Option<String>, sqlx::Error> {
sqlx::query_scalar("SELECT s3_key FROM avatars WHERE account_id = $1")
.bind(account_id)
.fetch_optional(pool)
.await
}
/// Nick + avatar key for the given accounts (showcase authors etc.).
/// Missing ids are simply absent from the result.
pub async fn public_profiles(
pool: &PgPool,
ids: &[Uuid],
) -> Result<Vec<(Uuid, String, Option<String>)>, sqlx::Error> {
sqlx::query_as(
"SELECT a.id, a.display_nick, av.s3_key FROM accounts a
LEFT JOIN avatars av ON av.account_id = a.id
WHERE a.id = ANY($1)",
)
.bind(ids)
.fetch_all(pool)
.await
}
/// How many accounts existed before `created_at`; 0 means the very first one.
pub async fn account_rank(
pool: &PgPool,
created_at: chrono::DateTime<chrono::Utc>,
) -> Result<i64, sqlx::Error> {
sqlx::query_scalar("SELECT count(*) FROM accounts WHERE created_at < $1")
.bind(created_at)
.fetch_one(pool)
.await
}
#[cfg(test)]
mod tests {
use super::*;
@ -66,7 +100,10 @@ mod tests {
let url = std::env::var("DATABASE_URL")
.unwrap_or_else(|_| "postgres://lovisual:lovisual@localhost:5432/accounts_db".into());
let pool = PgPool::connect(&url).await.expect("connect");
sqlx::migrate!("./migrations").run(&pool).await.expect("migrate");
sqlx::migrate!("./migrations")
.run(&pool)
.await
.expect("migrate");
pool
}
@ -80,7 +117,10 @@ mod tests {
assert_eq!(created.role, "user");
assert!(created.can_publish_addons);
let found = find_by_email(&pool, &email).await.unwrap().expect("must exist");
let found = find_by_email(&pool, &email)
.await
.unwrap()
.expect("must exist");
assert_eq!(found.id, created.id);
sqlx::query("DELETE FROM accounts WHERE id = $1")
@ -93,7 +133,9 @@ mod tests {
#[tokio::test]
async fn find_by_email_returns_none_for_missing() {
let pool = test_pool().await;
let result = find_by_email(&pool, "does-not-exist@example.com").await.unwrap();
let result = find_by_email(&pool, "does-not-exist@example.com")
.await
.unwrap();
assert!(result.is_none());
}
@ -123,7 +165,9 @@ mod tests {
async fn duplicate_email_differing_only_by_case_is_rejected() {
let pool = test_pool().await;
let tag = Uuid::new_v4();
let first = create(&pool, &format!("dup-{tag}@example.com"), "h", "A").await.unwrap();
let first = create(&pool, &format!("dup-{tag}@example.com"), "h", "A")
.await
.unwrap();
let second = create(&pool, &format!("DUP-{tag}@EXAMPLE.com"), "h", "B").await;
let err = second.expect_err("case-variant duplicate must violate the unique index");
@ -144,12 +188,21 @@ mod tests {
#[tokio::test]
async fn set_avatar_inserts_then_updates_in_place() {
let pool = test_pool().await;
let created = create(&pool, &format!("av-{}@example.com", Uuid::new_v4()), "h", "N")
let created = create(
&pool,
&format!("av-{}@example.com", Uuid::new_v4()),
"h",
"N",
)
.await
.unwrap();
set_avatar(&pool, created.id, "avatars/one.png")
.await
.unwrap();
set_avatar(&pool, created.id, "avatars/two.png")
.await
.unwrap();
set_avatar(&pool, created.id, "avatars/one.png").await.unwrap();
set_avatar(&pool, created.id, "avatars/two.png").await.unwrap();
let rows: Vec<(String,)> =
sqlx::query_as("SELECT s3_key FROM avatars WHERE account_id = $1")

View file

@ -1,7 +1,8 @@
use crate::accounts::model::validate_register;
use crate::accounts::repo;
use crate::auth::{password, tokens};
use crate::error::{AppError, AppJson};
use axum::{extract::State, http::StatusCode, Json};
use axum::{Json, extract::State, http::StatusCode};
use axum_extra::extract::cookie::CookieJar;
use common::jwt;
use serde::{Deserialize, Serialize};
@ -49,52 +50,16 @@ pub struct RegisterResponse {
pub display_nick: String,
}
/// Validates and normalizes a register request. Returns the trimmed
/// `(email, nick)` on success.
fn validate_register(req: &RegisterRequest) -> Result<(String, String), AppError> {
let email = req.email.trim();
if email.is_empty() {
return Err(AppError::Validation("email must not be empty".into()));
}
if email.len() > 254 {
return Err(AppError::Validation("email must be at most 254 characters".into()));
}
let mut parts = email.split('@');
let (Some(local), Some(domain)) = (parts.next(), parts.next()) else {
return Err(AppError::Validation("email must contain '@'".into()));
};
if parts.next().is_some() || local.is_empty() || domain.is_empty() {
return Err(AppError::Validation("email must have exactly one '@' with non-empty parts".into()));
}
let nick = req.nick.trim();
let nick_len = nick.chars().count();
if nick_len == 0 || nick_len > 32 {
return Err(AppError::Validation("nick must be 1 to 32 characters".into()));
}
if nick.chars().any(|c| c.is_control()) {
return Err(AppError::Validation("nick must not contain control characters".into()));
}
if req.password.chars().count() < 8 {
return Err(AppError::Validation("password must be at least 8 characters".into()));
}
if req.password.len() > password::MAX_PASSWORD_BYTES {
return Err(AppError::Validation(format!(
"password must be at most {} bytes",
password::MAX_PASSWORD_BYTES
)));
}
Ok((email.to_string(), nick.to_string()))
}
pub async fn register(
State(state): State<AuthState>,
AppJson(req): AppJson<RegisterRequest>,
) -> Result<(StatusCode, Json<RegisterResponse>), AppError> {
let (email, nick) = validate_register(&req)?;
let hash = state.hasher.hash(req.password.clone()).await.map_err(AppError::Internal)?;
let (email, nick) = validate_register(&req.email, &req.password, &req.nick)?;
let hash = state
.hasher
.hash(req.password.clone())
.await
.map_err(AppError::Internal)?;
let account = repo::create(&state.pool, &email, &hash, &nick).await?;
Ok((
StatusCode::CREATED,
@ -142,7 +107,9 @@ pub async fn login(
let refresh = tokens::store_refresh(&state.pool, account.id).await?;
Ok((
jar.add(tokens::refresh_cookie(refresh, state.cookie_secure)),
Json(LoginResponse { access_token: jwt::issue_access_token(account.id, &state.jwt_secret) }),
Json(LoginResponse {
access_token: jwt::issue_access_token(account.id, &state.jwt_secret),
}),
))
}
@ -150,11 +117,19 @@ pub async fn refresh(
State(state): State<AuthState>,
jar: CookieJar,
) -> Result<(CookieJar, Json<LoginResponse>), AppError> {
let token = jar.get(tokens::REFRESH_COOKIE).map(|c| c.value().to_owned()).ok_or(AppError::Unauthorized)?;
let token = jar
.get(tokens::REFRESH_COOKIE)
.map(|c| c.value().to_owned())
.ok_or(AppError::Unauthorized)?;
match tokens::rotate_refresh(&state.pool, &token).await? {
tokens::RotateOutcome::Rotated { account_id, new_token } => Ok((
tokens::RotateOutcome::Rotated {
account_id,
new_token,
} => Ok((
jar.add(tokens::refresh_cookie(new_token, state.cookie_secure)),
Json(LoginResponse { access_token: jwt::issue_access_token(account_id, &state.jwt_secret) }),
Json(LoginResponse {
access_token: jwt::issue_access_token(account_id, &state.jwt_secret),
}),
)),
tokens::RotateOutcome::Invalid => Err(AppError::Unauthorized),
}
@ -168,60 +143,7 @@ pub async fn logout(
tokens::revoke_refresh(&state.pool, cookie.value()).await?;
}
Ok((
jar.remove(axum_extra::extract::cookie::Cookie::build(tokens::REFRESH_COOKIE).path("/auth")),
jar.add(tokens::removal_cookie(state.cookie_secure)),
StatusCode::NO_CONTENT,
))
}
#[cfg(test)]
mod tests {
use super::*;
fn valid_request() -> RegisterRequest {
RegisterRequest {
email: "user@example.com".into(),
password: "password123".into(),
nick: "Rider".into(),
}
}
#[test]
fn valid_request_passes() {
assert!(validate_register(&valid_request()).is_ok());
}
#[test]
fn short_password_is_rejected() {
let mut req = valid_request();
req.password = "short12".into();
assert!(validate_register(&req).is_err());
}
#[test]
fn empty_email_is_rejected() {
let mut req = valid_request();
req.email = " ".into();
assert!(validate_register(&req).is_err());
}
#[test]
fn email_without_at_is_rejected() {
let mut req = valid_request();
req.email = "not-an-email".into();
assert!(validate_register(&req).is_err());
}
#[test]
fn empty_nick_is_rejected() {
let mut req = valid_request();
req.nick = " ".into();
assert!(validate_register(&req).is_err());
}
#[test]
fn thirty_three_char_nick_is_rejected() {
let mut req = valid_request();
req.nick = "a".repeat(33);
assert!(validate_register(&req).is_err());
}
}

View file

@ -1,3 +1,3 @@
pub mod handlers;
pub mod password;
pub mod tokens;
pub mod handlers;

View file

@ -64,7 +64,9 @@ impl PasswordHasher {
let permits = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(2);
PasswordHasher { permits: Arc::new(Semaphore::new(permits)) }
PasswordHasher {
permits: Arc::new(Semaphore::new(permits)),
}
}
/// Runs Argon2 hashing off the async workers, bounded by the permit count.

View file

@ -1,10 +1,17 @@
use axum_extra::extract::cookie::{Cookie, SameSite};
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use chrono::{DateTime, Utc};
use rand::RngExt;
use sha2::{Digest, Sha256};
use sqlx::PgPool;
use uuid::Uuid;
/// A refresh token revoked by rotation less than this long ago is treated as
/// a benign race between two concurrent refreshes of the same token (e.g.
/// two open tabs), not token theft: the second caller gets a plain 401
/// without the reuse-detection cascade that would kill every session.
const ROTATION_GRACE: chrono::Duration = chrono::Duration::seconds(10);
pub const REFRESH_COOKIE: &str = "lv_refresh";
/// 256-bit random token: nothing to brute-force, so a slow hash would only
@ -39,8 +46,8 @@ pub enum RotateOutcome {
pub async fn rotate_refresh(pool: &PgPool, token: &str) -> Result<RotateOutcome, sqlx::Error> {
let mut tx = pool.begin().await?;
let row: Option<(Uuid, bool, bool)> = sqlx::query_as(
"SELECT account_id, revoked_at IS NOT NULL, expires_at <= now()
let row: Option<(Uuid, bool, bool, Option<DateTime<Utc>>)> = sqlx::query_as(
"SELECT account_id, revoked_at IS NOT NULL, expires_at <= now(), rotated_at
FROM refresh_tokens WHERE token_hash = $1 FOR UPDATE",
)
.bind(hash_token(token))
@ -49,8 +56,16 @@ pub async fn rotate_refresh(pool: &PgPool, token: &str) -> Result<RotateOutcome,
let outcome = match row {
None => RotateOutcome::Invalid,
Some((account_id, true, _)) => {
// Reuse of a rotated token: someone else holds a copy. Kill all sessions.
Some((_, true, _, Some(rotated_at))) if Utc::now() - rotated_at < ROTATION_GRACE => {
// Two concurrent refreshes of the same token (e.g. two tabs): the
// first already rotated it moments ago. Reject this one without
// the reuse-detection cascade, so the first caller's new token
// (and every other session) stays valid.
RotateOutcome::Invalid
}
Some((account_id, true, _, _)) => {
// Reuse of a rotated token outside the grace window: someone else
// holds a copy. Kill all sessions.
sqlx::query(
"UPDATE refresh_tokens SET revoked_at = now()
WHERE account_id = $1 AND revoked_at IS NULL",
@ -60,12 +75,15 @@ pub async fn rotate_refresh(pool: &PgPool, token: &str) -> Result<RotateOutcome,
.await?;
RotateOutcome::Invalid
}
Some((_, false, true)) => RotateOutcome::Invalid,
Some((account_id, false, false)) => {
sqlx::query("UPDATE refresh_tokens SET revoked_at = now() WHERE token_hash = $1")
.bind(hash_token(token))
.execute(&mut *tx)
.await?;
Some((_, false, true, _)) => RotateOutcome::Invalid,
Some((account_id, false, false, _)) => {
sqlx::query(
"UPDATE refresh_tokens SET revoked_at = now(), rotated_at = now()
WHERE token_hash = $1",
)
.bind(hash_token(token))
.execute(&mut *tx)
.await?;
let new_token = new_opaque_token("lvr_");
sqlx::query(
"INSERT INTO refresh_tokens (account_id, token_hash, expires_at)
@ -75,7 +93,10 @@ pub async fn rotate_refresh(pool: &PgPool, token: &str) -> Result<RotateOutcome,
.bind(hash_token(&new_token))
.execute(&mut *tx)
.await?;
RotateOutcome::Rotated { account_id, new_token }
RotateOutcome::Rotated {
account_id,
new_token,
}
}
};
tx.commit().await?;
@ -104,6 +125,19 @@ pub fn refresh_cookie(token: String, secure: bool) -> Cookie<'static> {
.build()
}
/// Removal cookie for logout: same attributes as `refresh_cookie` (minus the
/// value/max-age) so the browser actually matches and clears it — a cookie
/// removal with mismatched attributes is silently ignored.
pub fn removal_cookie(secure: bool) -> Cookie<'static> {
Cookie::build((REFRESH_COOKIE, ""))
.http_only(true)
.secure(secure)
.same_site(SameSite::Strict)
.path("/auth")
.max_age(time::Duration::ZERO)
.build()
}
#[cfg(test)]
mod tests {
use super::*;

View file

@ -1,10 +1,10 @@
use crate::accounts::repo;
use crate::avatars::processing::{process_avatar, AvatarImageError};
use crate::avatars::processing::{AvatarImageError, process_avatar};
use crate::avatars::storage::S3Storage;
use crate::error::AppError;
use axum::{
extract::{Multipart, State},
Json,
extract::{Multipart, State},
};
use common::internal::GatewayIdentity;
use serde::Serialize;
@ -56,8 +56,14 @@ pub async fn upload(
})?;
let key = format!("avatars/{account_id}.png");
state.storage.put(&key, png, "image/png").await.map_err(AppError::Internal)?;
state
.storage
.put(&key, png, "image/png")
.await
.map_err(AppError::Internal)?;
repo::set_avatar(&state.pool, account_id, &key).await?;
Ok(Json(AvatarResponse { avatar_url: format!("{}/{key}", state.base_url) }))
Ok(Json(AvatarResponse {
avatar_url: format!("{}/{key}", state.base_url),
}))
}

View file

@ -1,4 +1,4 @@
use image::{imageops::FilterType, ImageFormat, ImageReader, Limits};
use image::{ImageFormat, ImageReader, Limits, imageops::FilterType};
use std::io::Cursor;
pub const AVATAR_SIZE: u32 = 256;
@ -60,12 +60,18 @@ mod tests {
let out = process_avatar(&png_of(300, 100)).unwrap();
assert!(out.starts_with(&[0x89, b'P', b'N', b'G']));
let decoded = image::load_from_memory(&out).unwrap();
assert_eq!((decoded.width(), decoded.height()), (AVATAR_SIZE, AVATAR_SIZE));
assert_eq!(
(decoded.width(), decoded.height()),
(AVATAR_SIZE, AVATAR_SIZE)
);
}
#[test]
fn non_image_bytes_are_unsupported() {
assert_eq!(process_avatar(b"not an image"), Err(AvatarImageError::Unsupported));
assert_eq!(
process_avatar(b"not an image"),
Err(AvatarImageError::Unsupported)
);
}
#[test]
@ -85,6 +91,9 @@ mod tests {
#[test]
fn image_wider_than_the_limit_is_rejected() {
assert_eq!(process_avatar(&png_of(MAX_DIMENSION + 1, 1)), Err(AvatarImageError::Invalid));
assert_eq!(
process_avatar(&png_of(MAX_DIMENSION + 1, 1)),
Err(AvatarImageError::Invalid)
);
}
}

View file

@ -1,5 +1,5 @@
use aws_sdk_s3::primitives::ByteStream;
use aws_sdk_s3::Client;
use aws_sdk_s3::primitives::ByteStream;
#[derive(Clone)]
pub struct S3Storage {
@ -11,7 +11,8 @@ impl S3Storage {
/// Builds the S3 client synchronously (no I/O happens here — connections
/// are made lazily on first request).
pub fn from_config(endpoint: &str, access_key: &str, secret_key: &str, bucket: String) -> Self {
let creds = aws_sdk_s3::config::Credentials::new(access_key, secret_key, None, None, "static");
let creds =
aws_sdk_s3::config::Credentials::new(access_key, secret_key, None, None, "static");
let config = aws_sdk_s3::config::Builder::new()
.endpoint_url(endpoint)
.credentials_provider(creds)
@ -19,7 +20,10 @@ impl S3Storage {
.force_path_style(true)
.behavior_version(aws_sdk_s3::config::BehaviorVersion::latest())
.build();
S3Storage { client: Client::from_conf(config), bucket }
S3Storage {
client: Client::from_conf(config),
bucket,
}
}
pub async fn put(&self, key: &str, bytes: Vec<u8>, content_type: &str) -> anyhow::Result<()> {

View file

@ -6,6 +6,7 @@ pub struct Config {
pub jwt_secret: String,
pub internal_key: String,
pub port: u16,
pub grpc_port: u16,
pub s3_endpoint: String,
pub s3_bucket: String,
pub s3_access_key: String,
@ -16,25 +17,24 @@ pub struct Config {
impl Config {
pub fn from_env() -> Result<Config> {
Ok(Config {
database_url: std::env::var("DATABASE_URL")
.context("DATABASE_URL not set")?,
jwt_secret: std::env::var("JWT_SECRET")
.context("JWT_SECRET not set")?,
internal_key: std::env::var("INTERNAL_KEY")
.context("INTERNAL_KEY not set")?,
database_url: std::env::var("DATABASE_URL").context("DATABASE_URL not set")?,
jwt_secret: std::env::var("JWT_SECRET").context("JWT_SECRET not set")?,
internal_key: std::env::var("INTERNAL_KEY").context("INTERNAL_KEY not set")?,
port: std::env::var("PORT")
.unwrap_or_else(|_| "8081".into())
.parse()
.context("PORT must be a number")?,
s3_endpoint: std::env::var("S3_ENDPOINT")
.context("S3_ENDPOINT not set")?,
s3_bucket: std::env::var("S3_BUCKET")
.context("S3_BUCKET not set")?,
s3_access_key: std::env::var("S3_ACCESS_KEY")
.context("S3_ACCESS_KEY not set")?,
s3_secret_key: std::env::var("S3_SECRET_KEY")
.context("S3_SECRET_KEY not set")?,
cookie_secure: std::env::var("COOKIE_SECURE").map(|v| v != "false").unwrap_or(true),
grpc_port: std::env::var("GRPC_PORT")
.unwrap_or_else(|_| "50051".into())
.parse()
.context("GRPC_PORT must be a number")?,
s3_endpoint: std::env::var("S3_ENDPOINT").context("S3_ENDPOINT not set")?,
s3_bucket: std::env::var("S3_BUCKET").context("S3_BUCKET not set")?,
s3_access_key: std::env::var("S3_ACCESS_KEY").context("S3_ACCESS_KEY not set")?,
s3_secret_key: std::env::var("S3_SECRET_KEY").context("S3_SECRET_KEY not set")?,
cookie_secure: std::env::var("COOKIE_SECURE")
.map(|v| v != "false")
.unwrap_or(true),
})
}
}
@ -56,7 +56,11 @@ impl Config {
/// Public prefix of stored avatars: `<endpoint>/<bucket>`.
pub fn avatar_base_url(&self) -> String {
format!("{}/{}", self.s3_endpoint.trim_end_matches('/'), self.s3_bucket)
format!(
"{}/{}",
self.s3_endpoint.trim_end_matches('/'),
self.s3_bucket
)
}
}
@ -70,6 +74,7 @@ mod tests {
jwt_secret: secret.into(),
internal_key: "k".repeat(32),
port: 0,
grpc_port: 0,
s3_endpoint: String::new(),
s3_bucket: String::new(),
s3_access_key: String::new(),

View file

@ -1,14 +1,20 @@
use crate::device::store::{self, DeviceStore, PollResult};
use crate::device::{
links,
store::{self, DeviceStore, PollResult},
};
use crate::error::{AppError, AppJson};
use axum::{extract::State, http::StatusCode, Json};
use axum::{
Json,
extract::{Path, State},
http::StatusCode,
};
use common::internal::GatewayIdentity;
use common::jwt;
use serde::{Deserialize, Serialize};
#[derive(Clone)]
pub struct DeviceState {
pub store: DeviceStore,
pub jwt_secret: String,
pub pool: sqlx::PgPool,
}
#[derive(Serialize)]
@ -24,7 +30,11 @@ pub async fn create_code(
let (device_code, user_code) = state.store.create().ok_or(AppError::TooManyRequests)?;
Ok((
StatusCode::CREATED,
Json(DeviceCodeResponse { device_code, user_code, expires_in: store::TTL.as_secs() }),
Json(DeviceCodeResponse {
device_code,
user_code,
expires_in: store::TTL.as_secs(),
}),
))
}
@ -63,11 +73,29 @@ pub async fn token(
PollResult::Unknown => Err(AppError::NotFound("unknown or expired device_code".into())),
PollResult::Pending => Ok((StatusCode::ACCEPTED, Json(None))),
PollResult::Confirmed(account_id) => {
// The long-lived device_token is just a refresh-style JWT for now;
// the gateway plan is where per-device revocation via
// device_links.device_token_hash gets enforced on every request.
let device_token = jwt::issue_refresh_token(account_id, &state.jwt_secret);
// The long-lived device token is an opaque random secret, stored
// hashed in device_links so the gateway can revoke it per device.
let device_token = links::create(&state.pool, account_id).await?;
Ok((StatusCode::OK, Json(Some(TokenResponse { device_token }))))
}
}
}
pub async fn list_links(
State(state): State<DeviceState>,
identity: GatewayIdentity,
) -> Result<Json<Vec<links::DeviceLink>>, AppError> {
Ok(Json(links::list(&state.pool, identity.account_id).await?))
}
pub async fn revoke_link(
State(state): State<DeviceState>,
identity: GatewayIdentity,
Path(link_id): Path<uuid::Uuid>,
) -> Result<StatusCode, AppError> {
if links::revoke(&state.pool, identity.account_id, link_id).await? {
Ok(StatusCode::NO_CONTENT)
} else {
Err(AppError::NotFound("no such device link".into()))
}
}

View file

@ -0,0 +1,54 @@
use crate::auth::tokens::{hash_token, new_opaque_token};
use chrono::{DateTime, Utc};
use common::internal::DEVICE_TOKEN_PREFIX;
use serde::Serialize;
use sqlx::PgPool;
use uuid::Uuid;
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct DeviceLink {
pub id: Uuid,
pub linked_at: DateTime<Utc>,
pub last_seen: Option<DateTime<Utc>>,
}
pub async fn create(pool: &PgPool, account_id: Uuid) -> Result<String, sqlx::Error> {
let token = new_opaque_token(DEVICE_TOKEN_PREFIX);
sqlx::query("INSERT INTO device_links (account_id, device_token_hash) VALUES ($1, $2)")
.bind(account_id)
.bind(hash_token(&token))
.execute(pool)
.await?;
Ok(token)
}
/// Resolves a device token to its account and bumps `last_seen`. Returns
/// `None` for unknown tokens (and for nothing else — revocation deletes the
/// row, so revoked tokens are just unknown).
pub async fn authenticate(pool: &PgPool, token: &str) -> Result<Option<Uuid>, sqlx::Error> {
sqlx::query_scalar(
"UPDATE device_links SET last_seen = now() WHERE device_token_hash = $1 RETURNING account_id",
)
.bind(hash_token(token))
.fetch_optional(pool)
.await
}
pub async fn list(pool: &PgPool, account_id: Uuid) -> Result<Vec<DeviceLink>, sqlx::Error> {
sqlx::query_as(
"SELECT id, linked_at, last_seen FROM device_links WHERE account_id = $1 ORDER BY linked_at DESC",
)
.bind(account_id)
.fetch_all(pool)
.await
}
/// Deletes the link only if it belongs to `account_id`; `false` otherwise.
pub async fn revoke(pool: &PgPool, account_id: Uuid, link_id: Uuid) -> Result<bool, sqlx::Error> {
let result = sqlx::query("DELETE FROM device_links WHERE id = $1 AND account_id = $2")
.bind(link_id)
.bind(account_id)
.execute(pool)
.await?;
Ok(result.rows_affected() == 1)
}

View file

@ -1,2 +1,3 @@
pub mod handlers;
pub mod links;
pub mod store;

View file

@ -33,7 +33,9 @@ fn random_user_code() -> String {
const ALPHABET: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // no O/0/I/1 confusion
let mut rng = rand::rng();
let mut part = |n: usize| -> String {
(0..n).map(|_| ALPHABET[rng.random_range(0..ALPHABET.len())] as char).collect()
(0..n)
.map(|_| ALPHABET[rng.random_range(0..ALPHABET.len())] as char)
.collect()
};
format!("{}-{}", part(4), part(4))
}
@ -42,7 +44,8 @@ impl DeviceStore {
/// Returns `(device_code, user_code)`, or `None` when the store is full.
pub fn create(&self) -> Option<(String, String)> {
let now = Instant::now();
self.by_device_code.retain(|_, entry| entry.expires_at > now);
self.by_device_code
.retain(|_, entry| entry.expires_at > now);
if self.by_device_code.len() >= MAX_PENDING {
return None;
}
@ -130,7 +133,11 @@ mod tests {
assert!(store.confirm(&user_code, Uuid::new_v4()));
assert!(matches!(store.poll(&device_code), PollResult::Confirmed(_)));
assert_eq!(store.poll(&device_code), PollResult::Unknown, "replay must fail");
assert_eq!(
store.poll(&device_code),
PollResult::Unknown,
"replay must fail"
);
}
#[test]
@ -161,7 +168,10 @@ mod tests {
let attacker = Uuid::new_v4();
assert!(store.confirm(&user_code, first));
assert!(!store.confirm(&user_code, attacker), "re-confirm must be refused");
assert!(
!store.confirm(&user_code, attacker),
"re-confirm must be refused"
);
assert_eq!(store.poll(&device_code), PollResult::Confirmed(first));
}
@ -180,7 +190,10 @@ mod tests {
for _ in 0..MAX_PENDING {
assert!(store.create().is_some());
}
assert!(store.create().is_none(), "store must refuse beyond MAX_PENDING");
assert!(
store.create().is_none(),
"store must refuse beyond MAX_PENDING"
);
// Force everything to be expired; the next create purges and succeeds.
for mut entry in store.by_device_code.iter_mut() {

View file

@ -1,8 +1,8 @@
use axum::{
extract::{rejection::JsonRejection, FromRequest},
Json,
extract::{FromRequest, rejection::JsonRejection},
http::StatusCode,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
@ -23,7 +23,10 @@ impl IntoResponse for AppError {
AppError::Conflict(msg) => (StatusCode::CONFLICT, msg),
AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".into()),
AppError::NotFound(msg) => (StatusCode::NOT_FOUND, msg),
AppError::TooManyRequests => (StatusCode::TOO_MANY_REQUESTS, "too many pending device codes".into()),
AppError::TooManyRequests => (
StatusCode::TOO_MANY_REQUESTS,
"too many pending device codes".into(),
),
AppError::Internal(err) => {
tracing::error!("internal error: {err:?}");
(StatusCode::INTERNAL_SERVER_ERROR, "internal error".into())

View file

@ -0,0 +1,215 @@
use common::internal::GrpcKeyCheck;
use common::pb::accounts::accounts_internal_server::{AccountsInternal, AccountsInternalServer};
use common::pb::accounts::{
AuthenticateDeviceReply, AuthenticateDeviceRequest, GetPublicProfilesReply,
GetPublicProfilesRequest, PublicProfile,
};
use sqlx::PgPool;
use tonic::{Request, Response, Status, service::interceptor::InterceptedService};
use uuid::Uuid;
const MAX_PROFILE_IDS: usize = 100;
pub struct AccountsGrpc {
pool: PgPool,
avatar_base_url: String,
}
impl AccountsGrpc {
pub fn new(pool: PgPool, avatar_base_url: String) -> Self {
AccountsGrpc {
pool,
avatar_base_url,
}
}
}
/// Builds the internal `AccountsInternal` gRPC service, guarded by
/// `GrpcKeyCheck` so only callers holding the shared internal key (i.e. the
/// gateway) can reach it.
pub fn server(
pool: PgPool,
avatar_base_url: String,
internal_key: &str,
) -> InterceptedService<AccountsInternalServer<AccountsGrpc>, GrpcKeyCheck> {
AccountsInternalServer::with_interceptor(
AccountsGrpc::new(pool, avatar_base_url),
GrpcKeyCheck::new(internal_key),
)
}
#[tonic::async_trait]
impl AccountsInternal for AccountsGrpc {
async fn authenticate_device(
&self,
request: Request<AuthenticateDeviceRequest>,
) -> Result<Response<AuthenticateDeviceReply>, Status> {
let token = request.into_inner().device_token;
match crate::device::links::authenticate(&self.pool, &token).await {
Ok(Some(account_id)) => Ok(Response::new(AuthenticateDeviceReply {
account_id: account_id.to_string(),
})),
Ok(None) => Err(Status::unauthenticated("unknown or revoked device token")),
Err(err) => {
tracing::error!("authenticate_device: {err:?}");
Err(Status::internal("internal error"))
}
}
}
async fn get_public_profiles(
&self,
request: Request<GetPublicProfilesRequest>,
) -> Result<Response<GetPublicProfilesReply>, Status> {
let raw = request.into_inner().account_ids;
if raw.len() > MAX_PROFILE_IDS {
return Err(Status::invalid_argument("at most 100 account ids per call"));
}
let ids: Vec<Uuid> = raw.iter().filter_map(|s| Uuid::parse_str(s).ok()).collect();
let rows = crate::accounts::repo::public_profiles(&self.pool, &ids)
.await
.map_err(|err| {
tracing::error!("get_public_profiles: {err:?}");
Status::internal("internal error")
})?;
let profiles = rows
.into_iter()
.map(|(id, nick, key)| PublicProfile {
account_id: id.to_string(),
display_nick: nick,
avatar_url: key
.map(|k| format!("{}/{k}", self.avatar_base_url))
.unwrap_or_default(),
})
.collect();
Ok(Response::new(GetPublicProfilesReply { profiles }))
}
}
#[cfg(test)]
mod tests {
use super::*;
use common::internal::GrpcKeyAttach;
use common::pb::accounts::accounts_internal_client::AccountsInternalClient;
const KEY: &str = "internal-key-internal-key-internal!!";
const CDN: &str = "http://cdn/avatars";
async fn pool() -> PgPool {
let url = std::env::var("DATABASE_URL")
.unwrap_or_else(|_| "postgres://lovisual:lovisual@localhost:5432/accounts_db".into());
let pool = PgPool::connect(&url).await.expect("connect");
sqlx::migrate!("./migrations")
.run(&pool)
.await
.expect("migrate");
pool
}
#[tokio::test]
async fn authenticate_device_over_grpc() {
let pool = pool().await;
let account = crate::accounts::repo::create(
&pool,
&format!("g-{}@example.com", Uuid::new_v4()),
"x",
"Grpc",
)
.await
.unwrap();
let token = crate::device::links::create(&pool, account.id)
.await
.unwrap();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(
tonic::transport::Server::builder()
.add_service(server(pool.clone(), CDN.into(), KEY))
.serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener)),
);
let channel = tonic::transport::Endpoint::from_shared(format!("http://{addr}"))
.unwrap()
.connect_lazy();
let mut client = AccountsInternalClient::with_interceptor(
channel.clone(),
GrpcKeyAttach::new(KEY).unwrap(),
);
let reply = client
.authenticate_device(AuthenticateDeviceRequest {
device_token: token,
})
.await
.unwrap()
.into_inner();
assert_eq!(reply.account_id, account.id.to_string());
let err = client
.authenticate_device(AuthenticateDeviceRequest {
device_token: "lvd_unknown".into(),
})
.await
.unwrap_err();
assert_eq!(err.code(), tonic::Code::Unauthenticated);
let mut no_key = AccountsInternalClient::new(channel);
let err = no_key
.authenticate_device(AuthenticateDeviceRequest {
device_token: "x".into(),
})
.await
.unwrap_err();
assert_eq!(err.code(), tonic::Code::PermissionDenied);
sqlx::query("DELETE FROM accounts WHERE id = $1")
.bind(account.id)
.execute(&pool)
.await
.unwrap();
}
#[tokio::test]
async fn public_profiles_over_grpc() {
let pool = pool().await;
let a = crate::accounts::repo::create(
&pool,
&format!("p-{}@example.com", Uuid::new_v4()),
"x",
"Alice",
)
.await
.unwrap();
let svc = AccountsGrpc::new(pool.clone(), CDN.into());
let reply = svc
.get_public_profiles(tonic::Request::new(GetPublicProfilesRequest {
account_ids: vec![
a.id.to_string(),
Uuid::new_v4().to_string(),
"garbage".into(),
],
}))
.await
.unwrap()
.into_inner();
assert_eq!(reply.profiles.len(), 1);
assert_eq!(reply.profiles[0].display_nick, "Alice");
assert_eq!(reply.profiles[0].avatar_url, "");
let too_many: Vec<String> = (0..101).map(|_| Uuid::new_v4().to_string()).collect();
let err = svc
.get_public_profiles(tonic::Request::new(GetPublicProfilesRequest {
account_ids: too_many,
}))
.await
.unwrap_err();
assert_eq!(err.code(), tonic::Code::InvalidArgument);
sqlx::query("DELETE FROM accounts WHERE id = $1")
.bind(a.id)
.execute(&pool)
.await
.unwrap();
}
}

View file

@ -4,22 +4,25 @@ pub mod avatars;
pub mod config;
pub mod device;
pub mod error;
pub mod grpc;
use accounts::handlers::AccountsState;
use auth::handlers::AuthState;
use avatars::{handlers::AvatarState, storage::S3Storage};
use axum::{
extract::DefaultBodyLimit,
Router,
extract::DefaultBodyLimit,
routing::{get, post},
};
use config::Config;
use device::{handlers::DeviceState, store::DeviceStore};
pub fn build_app(pool: sqlx::PgPool, cfg: &Config) -> Router {
let auth_state =
AuthState::new(pool.clone(), cfg.jwt_secret.clone(), cfg.cookie_secure);
let device_state =
DeviceState { store: DeviceStore::default(), jwt_secret: cfg.jwt_secret.clone() };
let auth_state = AuthState::new(pool.clone(), cfg.jwt_secret.clone(), cfg.cookie_secure);
let device_state = DeviceState {
store: DeviceStore::default(),
pool: pool.clone(),
};
let avatar_state = AvatarState {
pool: pool.clone(),
storage: S3Storage::from_config(
@ -30,6 +33,10 @@ pub fn build_app(pool: sqlx::PgPool, cfg: &Config) -> Router {
),
base_url: cfg.avatar_base_url(),
};
let accounts_state = AccountsState {
pool: pool.clone(),
avatar_base_url: cfg.avatar_base_url(),
};
let auth_routes = Router::new()
.route("/auth/register", post(auth::handlers::register))
@ -42,6 +49,11 @@ pub fn build_app(pool: sqlx::PgPool, cfg: &Config) -> Router {
.route("/device/code", post(device::handlers::create_code))
.route("/device/confirm", post(device::handlers::confirm))
.route("/device/token", post(device::handlers::token))
.route("/device/links", get(device::handlers::list_links))
.route(
"/device/links/{id}",
axum::routing::delete(device::handlers::revoke_link),
)
.with_state(device_state);
let avatar_routes = Router::new()
@ -50,6 +62,11 @@ pub fn build_app(pool: sqlx::PgPool, cfg: &Config) -> Router {
.layer(DefaultBodyLimit::max(6 * 1024 * 1024))
.with_state(avatar_state);
let accounts_routes = Router::new()
.route("/me", get(accounts::handlers::me))
.route("/users/{id}", get(accounts::handlers::public_profile))
.with_state(accounts_state);
// Everything except /health is internal-only: reachable solely through
// the gateway, which authenticates the caller and forwards the identity
// header. Direct traffic (or spoofed headers) is rejected here.
@ -57,6 +74,7 @@ pub fn build_app(pool: sqlx::PgPool, cfg: &Config) -> Router {
.merge(auth_routes)
.merge(device_routes)
.merge(avatar_routes)
.merge(accounts_routes)
.layer(axum::middleware::from_fn_with_state(
common::internal::InternalKey::new(cfg.internal_key.clone()),
common::internal::require_internal_key,

View file

@ -14,9 +14,26 @@ async fn main() -> anyhow::Result<()> {
sqlx::migrate!("./migrations").run(&pool).await?;
let http = tokio::net::TcpListener::bind(("0.0.0.0", cfg.port)).await?;
let grpc_addr = std::net::SocketAddr::from(([0, 0, 0, 0], cfg.grpc_port));
tracing::info!(
"accounts-service listening on {} (http) and {} (grpc)",
cfg.port,
grpc_addr
);
let grpc = tonic::transport::Server::builder()
.add_service(accounts_service::grpc::server(
pool.clone(),
cfg.avatar_base_url(),
&cfg.internal_key,
))
.serve(grpc_addr);
let app = build_app(pool, &cfg);
let listener = tokio::net::TcpListener::bind(("0.0.0.0", cfg.port)).await?;
tracing::info!("accounts-service listening on {}", cfg.port);
axum::serve(listener, app).await?;
tokio::try_join!(
async { axum::serve(http, app).await.map_err(anyhow::Error::from) },
async { grpc.await.map_err(anyhow::Error::from) },
)?;
Ok(())
}

View file

@ -16,7 +16,9 @@ async fn register_then_login_succeeds() {
let register_response = server
.post("/auth/register")
.json(&json!({ "email": email, "password": "correct-horse-battery-staple", "nick": "Rider" }))
.json(
&json!({ "email": email, "password": "correct-horse-battery-staple", "nick": "Rider" }),
)
.await;
register_response.assert_status(axum::http::StatusCode::CREATED);
@ -27,7 +29,10 @@ async fn register_then_login_succeeds() {
login_response.assert_status_ok();
let body: serde_json::Value = login_response.json();
assert!(body["access_token"].is_string());
assert!(body["refresh_token"].is_null(), "refresh token must be in the httpOnly cookie, not the body");
assert!(
body["refresh_token"].is_null(),
"refresh token must be in the httpOnly cookie, not the body"
);
sqlx::query("DELETE FROM accounts WHERE email = $1")
.bind(&email)
@ -141,7 +146,10 @@ async fn malformed_json_body_returns_400_with_json_error_shape() {
.await;
response.assert_status(axum::http::StatusCode::BAD_REQUEST);
let body: serde_json::Value = response.json();
assert!(body["error"].is_string(), "expected {{\"error\": ...}}, got {body}");
assert!(
body["error"].is_string(),
"expected {{\"error\": ...}}, got {body}"
);
}
#[tokio::test]
@ -160,3 +168,24 @@ async fn register_rejects_oversized_password_with_400() {
.await;
response.assert_status(axum::http::StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn me_returns_profile_without_password_hash() {
let pool = common::test_pool().await;
let server = common::test_server(accounts_service::build_app(pool, &common::test_config()));
let (id, email) = common::register_account(&server).await;
let res = server
.get("/me")
.add_header(common::ACCOUNT_ID_HEADER, id.to_string())
.await;
res.assert_status_ok();
let body: serde_json::Value = res.json();
assert_eq!(body["email"], email);
assert_eq!(body["display_nick"], "Tester");
assert_eq!(body["role"], "user");
assert!(body["avatar_url"].is_null());
assert!(body.get("password_hash").is_none());
server.get("/me").await.assert_status_unauthorized();
}

View file

@ -13,8 +13,14 @@ async fn login(server: &axum_test::TestServer, email: &str) -> (String, String)
assert!(cookie.http_only().unwrap_or(false));
assert_eq!(cookie.path(), Some("/auth"));
let body: serde_json::Value = res.json();
assert!(body.get("refresh_token").is_none(), "refresh token must not be in the JSON body");
(body["access_token"].as_str().unwrap().to_owned(), cookie.value().to_owned())
assert!(
body.get("refresh_token").is_none(),
"refresh token must not be in the JSON body"
);
(
body["access_token"].as_str().unwrap().to_owned(),
cookie.value().to_owned(),
)
}
#[tokio::test]
@ -47,6 +53,9 @@ async fn reusing_a_rotated_refresh_token_revokes_all_sessions() {
.cookie("lv_refresh")
.value()
.to_owned();
// Wait out the rotation grace window: a replay this long after rotation
// is genuine reuse, not a benign concurrent-refresh race.
tokio::time::sleep(std::time::Duration::from_secs(11)).await;
// Attacker replays the old token -> rejected, and the legit new one dies too.
server
.post("/auth/refresh")
@ -60,6 +69,36 @@ async fn reusing_a_rotated_refresh_token_revokes_all_sessions() {
.assert_status(StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn concurrent_refresh_within_the_grace_window_does_not_kill_the_session() {
let pool = common::test_pool().await;
let server = common::test_server(accounts_service::build_app(pool, &common::test_config()));
let (_, email) = common::register_account(&server).await;
let (_, first) = login(&server, &email).await;
// Two tabs racing to refresh the same cookie: the first wins and rotates.
let second = server
.post("/auth/refresh")
.add_cookie(Cookie::new("lv_refresh", first.clone()))
.await
.cookie("lv_refresh")
.value()
.to_owned();
// The second tab's request lands moments later with the now-stale cookie:
// it must be rejected...
server
.post("/auth/refresh")
.add_cookie(Cookie::new("lv_refresh", first))
.await
.assert_status(StatusCode::UNAUTHORIZED);
// ...but the first tab's freshly-rotated token must keep working.
server
.post("/auth/refresh")
.add_cookie(Cookie::new("lv_refresh", second))
.await
.assert_status_ok();
}
#[tokio::test]
async fn logout_revokes_the_refresh_token() {
let pool = common::test_pool().await;
@ -67,11 +106,14 @@ async fn logout_revokes_the_refresh_token() {
let (_, email) = common::register_account(&server).await;
let (_, refresh) = login(&server, &email).await;
server
let res = server
.post("/auth/logout")
.add_cookie(Cookie::new("lv_refresh", refresh.clone()))
.await
.assert_status(StatusCode::NO_CONTENT);
.await;
res.assert_status(StatusCode::NO_CONTENT);
let removal = res.cookie("lv_refresh");
assert_eq!(removal.value(), "");
assert_eq!(removal.max_age(), Some(time::Duration::ZERO));
server
.post("/auth/refresh")
.add_cookie(Cookie::new("lv_refresh", refresh))
@ -83,7 +125,10 @@ async fn logout_revokes_the_refresh_token() {
async fn refresh_without_cookie_or_with_garbage_is_401() {
let pool = common::test_pool().await;
let server = common::test_server(accounts_service::build_app(pool, &common::test_config()));
server.post("/auth/refresh").await.assert_status(StatusCode::UNAUTHORIZED);
server
.post("/auth/refresh")
.await
.assert_status(StatusCode::UNAUTHORIZED);
server
.post("/auth/refresh")
.add_cookie(Cookie::new("lv_refresh", "lvr_garbage"))

View file

@ -12,13 +12,19 @@ fn png_bytes() -> Vec<u8> {
}
fn form(bytes: Vec<u8>) -> MultipartForm {
MultipartForm::new().add_part("file", Part::bytes(bytes).file_name("a.png").mime_type("image/png"))
MultipartForm::new().add_part(
"file",
Part::bytes(bytes).file_name("a.png").mime_type("image/png"),
)
}
#[tokio::test]
async fn valid_upload_stores_avatar_and_returns_url() {
let pool = common::test_pool().await;
let server = common::test_server(accounts_service::build_app(pool.clone(), &common::test_config()));
let server = common::test_server(accounts_service::build_app(
pool.clone(),
&common::test_config(),
));
let (account_id, email) = common::register_account(&server).await;
let response = server
@ -27,8 +33,14 @@ async fn valid_upload_stores_avatar_and_returns_url() {
.multipart(form(png_bytes()))
.await;
response.assert_status_ok();
let url = response.json::<serde_json::Value>()["avatar_url"].as_str().unwrap().to_string();
assert!(url.starts_with("http://localhost:9000/lovisual-avatars-test/avatars/"), "{url}");
let url = response.json::<serde_json::Value>()["avatar_url"]
.as_str()
.unwrap()
.to_string();
assert!(
url.starts_with("http://localhost:9000/lovisual-avatars-test/avatars/"),
"{url}"
);
assert!(url.ends_with(".png"), "{url}");
let stored: (String,) = sqlx::query_as(
@ -50,7 +62,10 @@ async fn valid_upload_stores_avatar_and_returns_url() {
#[tokio::test]
async fn non_image_upload_is_rejected_with_400() {
let pool = common::test_pool().await;
let server = common::test_server(accounts_service::build_app(pool.clone(), &common::test_config()));
let server = common::test_server(accounts_service::build_app(
pool.clone(),
&common::test_config(),
));
let (account_id, email) = common::register_account(&server).await;
server
@ -70,7 +85,10 @@ async fn non_image_upload_is_rejected_with_400() {
#[tokio::test]
async fn oversized_upload_is_rejected_with_400() {
let pool = common::test_pool().await;
let server = common::test_server(accounts_service::build_app(pool.clone(), &common::test_config()));
let server = common::test_server(accounts_service::build_app(
pool.clone(),
&common::test_config(),
));
let (account_id, email) = common::register_account(&server).await;
server
@ -90,7 +108,10 @@ async fn oversized_upload_is_rejected_with_400() {
#[tokio::test]
async fn upload_without_identity_is_401() {
let pool = common::test_pool().await;
let server = common::test_server(accounts_service::build_app(pool.clone(), &common::test_config()));
let server = common::test_server(accounts_service::build_app(
pool.clone(),
&common::test_config(),
));
server
.post("/avatars")

View file

@ -11,8 +11,13 @@ pub use ::common::internal::{ACCOUNT_ID_HEADER, INTERNAL_KEY_HEADER};
pub async fn test_pool() -> sqlx::PgPool {
let url = std::env::var("DATABASE_URL")
.unwrap_or_else(|_| "postgres://lovisual:lovisual@localhost:5432/accounts_db".into());
let pool = sqlx::PgPool::connect(&url).await.expect("connect to test database");
sqlx::migrate!("./migrations").run(&pool).await.expect("run migrations");
let pool = sqlx::PgPool::connect(&url)
.await
.expect("connect to test database");
sqlx::migrate!("./migrations")
.run(&pool)
.await
.expect("run migrations");
pool
}
@ -22,6 +27,7 @@ pub fn test_config() -> Config {
jwt_secret: "test-secret-test-secret-test-secret!".into(),
internal_key: TEST_INTERNAL_KEY.into(),
port: 0,
grpc_port: 0,
s3_endpoint: "http://localhost:9000".into(),
s3_bucket: "lovisual-avatars-test".into(),
s3_access_key: "minioadmin".into(),
@ -48,5 +54,8 @@ pub async fn register_account(server: &TestServer) -> (Uuid, String) {
.await;
res.assert_status(axum::http::StatusCode::CREATED);
let body: serde_json::Value = res.json();
(Uuid::parse_str(body["id"].as_str().unwrap()).unwrap(), email)
(
Uuid::parse_str(body["id"].as_str().unwrap()).unwrap(),
email,
)
}

View file

@ -1,4 +1,8 @@
mod common;
// A test root's submodules resolve against `tests/`, not the file's own
// directory — pin the path so `tests/` itself stays at 4 files.
#[path = "device_flow/links.rs"]
mod links;
use axum::http::StatusCode;
use serde_json::json;
@ -6,7 +10,10 @@ use serde_json::json;
#[tokio::test]
async fn full_device_link_flow() {
let pool = common::test_pool().await;
let server = common::test_server(accounts_service::build_app(pool.clone(), &common::test_config()));
let server = common::test_server(accounts_service::build_app(
pool.clone(),
&common::test_config(),
));
let (account_id, email) = common::register_account(&server).await;
let code_response: serde_json::Value = server.post("/device/code").await.json();
@ -32,7 +39,11 @@ async fn full_device_link_flow() {
.await;
poll_after.assert_status_ok();
let token_body: serde_json::Value = poll_after.json();
assert!(token_body["device_token"].is_string());
let device_token = token_body["device_token"].as_str().unwrap();
assert!(
device_token.starts_with("lvd_"),
"opaque device token, got {device_token}"
);
// Single use: the same device_code cannot be redeemed twice.
server
@ -51,7 +62,10 @@ async fn full_device_link_flow() {
#[tokio::test]
async fn confirm_without_identity_is_401() {
let pool = common::test_pool().await;
let server = common::test_server(accounts_service::build_app(pool.clone(), &common::test_config()));
let server = common::test_server(accounts_service::build_app(
pool.clone(),
&common::test_config(),
));
let code: serde_json::Value = server.post("/device/code").await.json();
server
.post("/device/confirm")
@ -63,7 +77,10 @@ async fn confirm_without_identity_is_401() {
#[tokio::test]
async fn unknown_device_code_and_user_code_return_404() {
let pool = common::test_pool().await;
let server = common::test_server(accounts_service::build_app(pool.clone(), &common::test_config()));
let server = common::test_server(accounts_service::build_app(
pool.clone(),
&common::test_config(),
));
let (account_id, email) = common::register_account(&server).await;
server

View file

@ -0,0 +1,116 @@
use super::common;
use super::common::ACCOUNT_ID_HEADER;
use axum::http::StatusCode;
async fn link_device(server: &axum_test::TestServer, account: uuid::Uuid) -> String {
let code: serde_json::Value = server.post("/device/code").await.json();
server
.post("/device/confirm")
.add_header(ACCOUNT_ID_HEADER, account.to_string())
.json(&serde_json::json!({ "user_code": code["user_code"] }))
.await
.assert_status_ok();
let res = server
.post("/device/token")
.json(&serde_json::json!({ "device_code": code["device_code"] }))
.await;
res.assert_status_ok();
res.json::<serde_json::Value>()["device_token"]
.as_str()
.unwrap()
.to_owned()
}
#[tokio::test]
async fn confirmed_device_gets_an_opaque_token_backed_by_a_link_row() {
let pool = common::test_pool().await;
let server = common::test_server(accounts_service::build_app(
pool.clone(),
&common::test_config(),
));
let (account, _) = common::register_account(&server).await;
let token = link_device(&server, account).await;
assert!(token.starts_with("lvd_"));
let resolved = accounts_service::device::links::authenticate(&pool, &token)
.await
.unwrap();
assert_eq!(resolved, Some(account));
let links: Vec<serde_json::Value> = server
.get("/device/links")
.add_header(ACCOUNT_ID_HEADER, account.to_string())
.await
.json();
assert_eq!(links.len(), 1);
assert!(
links[0]["last_seen"].is_string(),
"authenticate must bump last_seen"
);
}
#[tokio::test]
async fn revoking_a_link_kills_its_token_only() {
let pool = common::test_pool().await;
let server = common::test_server(accounts_service::build_app(
pool.clone(),
&common::test_config(),
));
let (account, _) = common::register_account(&server).await;
let t1 = link_device(&server, account).await;
let t2 = link_device(&server, account).await;
let links: Vec<serde_json::Value> = server
.get("/device/links")
.add_header(ACCOUNT_ID_HEADER, account.to_string())
.await
.json();
let first_id = links.iter().find(|l| l["id"].is_string()).unwrap()["id"]
.as_str()
.unwrap()
.to_owned();
server
.delete(&format!("/device/links/{first_id}"))
.add_header(ACCOUNT_ID_HEADER, account.to_string())
.await
.assert_status(StatusCode::NO_CONTENT);
let alive = [
accounts_service::device::links::authenticate(&pool, &t1)
.await
.unwrap(),
accounts_service::device::links::authenticate(&pool, &t2)
.await
.unwrap(),
];
assert_eq!(alive.iter().filter(|a| a.is_some()).count(), 1);
}
#[tokio::test]
async fn cannot_revoke_someone_elses_link() {
let pool = common::test_pool().await;
let server = common::test_server(accounts_service::build_app(pool, &common::test_config()));
let (owner, _) = common::register_account(&server).await;
let (stranger, _) = common::register_account(&server).await;
link_device(&server, owner).await;
let links: Vec<serde_json::Value> = server
.get("/device/links")
.add_header(ACCOUNT_ID_HEADER, owner.to_string())
.await
.json();
let id = links[0]["id"].as_str().unwrap();
server
.delete(&format!("/device/links/{id}"))
.add_header(ACCOUNT_ID_HEADER, stranger.to_string())
.await
.assert_status(StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn unknown_device_token_does_not_authenticate() {
let pool = common::test_pool().await;
let r = accounts_service::device::links::authenticate(&pool, "lvd_nope")
.await
.unwrap();
assert_eq!(r, None);
}

View file

@ -7,8 +7,7 @@ async fn health_returns_ok() {
// NOTE: this test does not touch the DB — pass a pool that is never
// queried. sqlx::PgPool::connect_lazy never opens a connection until
// a query runs, so this is safe without a running Postgres.
let pool = sqlx::PgPool::connect_lazy("postgres://user:pass@localhost/db")
.expect("lazy pool");
let pool = sqlx::PgPool::connect_lazy("postgres://user:pass@localhost/db").expect("lazy pool");
let app = accounts_service::build_app(pool, &common::test_config());
let server = TestServer::new(app);
@ -25,7 +24,10 @@ async fn migrations_create_accounts_table() {
.fetch_one(&pool)
.await
.expect("query must succeed");
assert!(row.0.is_some(), "accounts table must exist after migrations run");
assert!(
row.0.is_some(),
"accounts table must exist after migrations run"
);
}
#[tokio::test]
@ -33,10 +35,50 @@ async fn api_routes_require_internal_key_but_health_does_not() {
let pool = common::test_pool().await;
// A raw server: no internal key header on any request, as if the
// service were reached directly, bypassing the gateway.
let server = axum_test::TestServer::new(accounts_service::build_app(pool, &common::test_config()));
let server =
axum_test::TestServer::new(accounts_service::build_app(pool, &common::test_config()));
server.get("/health").await.assert_status_ok();
server
.post("/device/code")
.await
.assert_status(axum::http::StatusCode::FORBIDDEN);
}
#[tokio::test]
async fn public_profile_is_reachable_without_identity_but_never_leaks_private_fields() {
let pool = common::test_pool().await;
let server = common::test_server(accounts_service::build_app(pool, &common::test_config()));
let (id, _email) = common::register_account(&server).await;
// No identity header: public data must not need a logged-in caller.
let res = server.get(&format!("/users/{id}")).await;
res.assert_status_ok();
let body: serde_json::Value = res.json();
assert_eq!(body["id"], id.to_string());
assert_eq!(body["display_nick"], "Tester");
assert!(body["avatar_url"].is_null());
assert!(body.get("email").is_none(), "email must never be public");
assert!(body.get("role").is_none(), "role must never be public");
assert!(
body["badges"]
.as_array()
.expect("badges array")
.iter()
.any(|b| b == "early")
);
server
.get(&format!("/users/{}", uuid::Uuid::new_v4()))
.await
.assert_status(axum::http::StatusCode::NOT_FOUND);
server
.get("/users/not-a-uuid")
.await
.assert_status(axum::http::StatusCode::NOT_FOUND);
sqlx::query("DELETE FROM accounts WHERE id = $1")
.bind(id)
.execute(&common::test_pool().await)
.await
.expect("cleanup");
}