feat(hub): let users upload their own avatar

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

Claude-Session: https://claude.ai/code/session_01GDjxLvBcnJqniFQGUGb1V4
This commit is contained in:
Loki 2026-10-24 21:43:44 +02:00
parent fea876654b
commit a2b0f26645
Signed by: boba
GPG key ID: 253067914055423B
15 changed files with 1332 additions and 13 deletions

View file

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

View file

@ -14,6 +14,7 @@ use cookie::{Cookie, SameSite};
use oauth2::{CsrfToken, PkceCodeChallenge};
use serde::Deserialize;
use serde_json::json;
mod avatar;
use std::sync::Arc;
use subtle::ConstantTimeEq;
const BROWSER: &str = "__Host-vnox_oauth";
@ -33,6 +34,11 @@ pub fn router() -> Router<Arc<HubState>> {
)
.route("/v1/auth/session", get(session))
.route("/v1/auth/logout", post(logout))
.route(
"/v1/account/avatar",
post(avatar::upload).delete(avatar::remove),
)
.route("/v1/avatars/{id}", get(avatar::serve))
}
fn failure(status: StatusCode, code: &'static str) -> Response {
(status, Json(json!({"error":code}))).into_response()
@ -336,23 +342,44 @@ async fn session(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Resp
}
Json(json!({"authenticated":false})).into_response()
}
async fn logout(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Response {
if !same_origin(&state.auth, &headers) {
return failure(StatusCode::FORBIDDEN, "invalid_origin");
/// Session gate for state-changing requests by a signed-in user: exact `Origin`, a live
/// session, and the session's CSRF token in `X-CSRF-Token`. Returns the user and session token.
async fn authorized(
state: &HubState,
headers: &HeaderMap,
) -> Result<(store::User, String), Box<Response>> {
if !same_origin(&state.auth, headers) {
return Err(Box::new(failure(StatusCode::FORBIDDEN, "invalid_origin")));
}
let Some(token) = cookie(&headers, SESSION) else {
return failure(StatusCode::UNAUTHORIZED, "not_authenticated");
let Some(token) = cookie(headers, SESSION) else {
return Err(Box::new(failure(
StatusCode::UNAUTHORIZED,
"not_authenticated",
)));
};
let Ok(Some((_, csrf))) = store::get_session(&state.auth.pool, &token).await else {
return failure(StatusCode::UNAUTHORIZED, "not_authenticated");
let Ok(Some((user, csrf))) = store::get_session(&state.auth.pool, &token).await else {
return Err(Box::new(failure(
StatusCode::UNAUTHORIZED,
"not_authenticated",
)));
};
let supplied = headers
.get("x-csrf-token")
.map(|v| v.as_bytes())
.unwrap_or_default();
if !bool::from(csrf.as_bytes().ct_eq(supplied)) {
return failure(StatusCode::FORBIDDEN, "invalid_csrf");
return Err(Box::new(failure(StatusCode::FORBIDDEN, "invalid_csrf")));
}
Ok((user, token))
}
fn allowed_avatar(auth: &AuthService, user_id: &str, headers: &HeaderMap) -> bool {
auth.allow_avatar(user_id, &client_ip(headers))
}
async fn logout(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Response {
let token = match authorized(&state, &headers).await {
Ok((_, token)) => token,
Err(response) => return *response,
};
if sqlx::query("DELETE FROM web_sessions WHERE token_hash=?")
.bind(store::hash(&token))
.execute(&state.auth.pool)

View file

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

View file

@ -144,7 +144,8 @@ async fn lookup_identity(
provider: &str,
subject: &str,
) -> anyhow::Result<Option<User>> {
Ok(sqlx::query_as("SELECT a.user_id,a.handle,a.display_name,a.avatar_url FROM accounts a JOIN external_identities e ON e.user_id=a.user_id WHERE e.provider=? AND e.subject=?")
// The own avatar (same-origin path) wins over the provider URL kept on the account.
Ok(sqlx::query_as("SELECT a.user_id,a.handle,a.display_name,COALESCE('/v1/avatars/'||v.id,a.avatar_url) AS avatar_url FROM accounts a LEFT JOIN avatars v ON v.user_id=a.user_id JOIN external_identities e ON e.user_id=a.user_id WHERE e.provider=? AND e.subject=?")
.bind(provider).bind(subject).fetch_optional(pool).await?)
}
@ -168,7 +169,7 @@ pub async fn get_session(
avatar_url: Option<String>,
csrf_token: String,
}
let row: Option<Row> = sqlx::query_as("SELECT a.user_id,a.handle,a.display_name,a.avatar_url,s.csrf_token FROM web_sessions s JOIN accounts a ON a.user_id=s.user_id WHERE s.token_hash=? AND s.expires_at>?")
let row: Option<Row> = sqlx::query_as("SELECT a.user_id,a.handle,a.display_name,COALESCE('/v1/avatars/'||v.id,a.avatar_url) AS avatar_url,s.csrf_token FROM web_sessions s JOIN accounts a ON a.user_id=s.user_id LEFT JOIN avatars v ON v.user_id=a.user_id WHERE s.token_hash=? AND s.expires_at>?")
.bind(hash(session)).bind(now()).fetch_optional(pool).await?;
Ok(row.map(|r| {
(

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

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

View file

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

View file

@ -106,6 +106,7 @@ async fn index() -> Html<&'static str> {
async fn headers(request: Request<Body>, next: Next) -> Response {
let mut response = next.run(request).await;
// Handlers that set their own cache policy or CSP (avatar delivery) keep them.
for (name, value) in [
("cache-control", "no-store"),
("x-content-type-options", "nosniff"),
@ -115,6 +116,10 @@ async fn headers(request: Request<Body>, next: Next) -> Response {
"default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; frame-ancestors 'none'",
),
] {
let present = response.headers().contains_key(name);
if present && matches!(name, "cache-control" | "content-security-policy") {
continue;
}
response
.headers_mut()
.insert(name, HeaderValue::from_static(value));