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:
parent
72bc4c7148
commit
7f4b532f99
257 changed files with 13085 additions and 6582 deletions
88
backend/accounts-service/src/accounts/handlers.rs
Normal file
88
backend/accounts-service/src/accounts/handlers.rs
Normal 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,
|
||||
}))
|
||||
}
|
||||
|
|
@ -1,2 +1,3 @@
|
|||
pub mod handlers;
|
||||
pub mod model;
|
||||
pub mod repo;
|
||||
|
|
|
|||
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
|
|
|
|||
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,3 @@
|
|||
pub mod handlers;
|
||||
pub mod password;
|
||||
pub mod tokens;
|
||||
pub mod handlers;
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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::*;
|
||||
|
|
|
|||
|
|
@ -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),
|
||||
}))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<()> {
|
||||
|
|
|
|||
|
|
@ -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(),
|
||||
|
|
|
|||
|
|
@ -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()))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
54
backend/accounts-service/src/device/links.rs
Normal file
54
backend/accounts-service/src/device/links.rs
Normal 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)
|
||||
}
|
||||
|
|
@ -1,2 +1,3 @@
|
|||
pub mod handlers;
|
||||
pub mod links;
|
||||
pub mod store;
|
||||
|
|
|
|||
|
|
@ -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() {
|
||||
|
|
|
|||
|
|
@ -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())
|
||||
|
|
|
|||
215
backend/accounts-service/src/grpc/mod.rs
Normal file
215
backend/accounts-service/src/grpc/mod.rs
Normal 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();
|
||||
}
|
||||
}
|
||||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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(())
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue