Merge branch 'fix/review-2026-07-01-hardening'

Whole-project review hardening: repair broken PIN reset + enforce real prod
secrets (Critical); live-role/ban authz, XFF fix, un-buffered SSE, atomic
writes, tiebroken pagination, CSP (High); event-lock, atomic config, a11y
inert, diashow, hygiene (Medium/Low); plus re-review follow-ups (CSP nonce,
feed_delta truncation signal, tightened H1 assertions, edge-case tests, docs).

Verified: backend 35 unit tests, frontend svelte-check + build, e2e 04-host
12/13 + 03-feed 8/8 on chromium-desktop.
This commit is contained in:
fabi
2026-07-02 20:20:26 +02:00
38 changed files with 730 additions and 205 deletions

View File

@@ -4,6 +4,10 @@ DOMAIN=my-event.example.com
# ── App server ──────────────────────────────────────────────────────────────── # ── App server ────────────────────────────────────────────────────────────────
APP_PORT=3000 APP_PORT=3000
# Set to `production` in real deployments. This activates the secret guard that
# refuses to boot with placeholder JWT_SECRET / ADMIN_PASSWORD_HASH values.
# (docker-compose.yml already sets APP_ENV=production for the app service.)
APP_ENV=production
# ── Database ────────────────────────────────────────────────────────────────── # ── Database ──────────────────────────────────────────────────────────────────
# Set a strong password and keep it in sync between DATABASE_URL and # Set a strong password and keep it in sync between DATABASE_URL and

View File

@@ -1,45 +0,0 @@
# ── Domain ────────────────────────────────────────────────────────────────────
# Public domain Caddy will serve and obtain a TLS certificate for.
DOMAIN=my-event.example.com
# ── App server ────────────────────────────────────────────────────────────────
APP_PORT=3000
# ── Database ──────────────────────────────────────────────────────────────────
DATABASE_URL=postgres://eventsnap:secret@db:5432/eventsnap
POSTGRES_USER=eventsnap
POSTGRES_PASSWORD=secret
POSTGRES_DB=eventsnap
# ── Authentication ────────────────────────────────────────────────────────────
# Generate with: openssl rand -hex 64
JWT_SECRET=change_me_to_a_random_64_byte_hex_string
SESSION_EXPIRY_DAYS=30
# Admin dashboard password (bcrypt hash).
# Generate with: htpasswd -bnBC 12 "" yourpassword | tr -d ':\n'
ADMIN_PASSWORD_HASH=$2y$12$placeholder_replace_me
# ── Event ─────────────────────────────────────────────────────────────────────
EVENT_NAME=Max & Maria's Wedding
EVENT_SLUG=max-maria-2026
# ── Storage ───────────────────────────────────────────────────────────────────
MEDIA_PATH=/media
# ── Upload limits ─────────────────────────────────────────────────────────────
DEFAULT_MAX_IMAGE_SIZE_MB=20
DEFAULT_MAX_VIDEO_SIZE_MB=500
# ── Rate limiting ─────────────────────────────────────────────────────────────
DEFAULT_UPLOAD_RATE_PER_HOUR=10
DEFAULT_FEED_RATE_PER_MIN=60
DEFAULT_EXPORT_RATE_PER_DAY=3
# ── Capacity ──────────────────────────────────────────────────────────────────
DEFAULT_ESTIMATED_GUEST_COUNT=100
# Fraction of total storage that triggers the "low storage" warning (0.01.0)
DEFAULT_QUOTA_TOLERANCE=0.75
# ── Workers ───────────────────────────────────────────────────────────────────
COMPRESSION_WORKER_CONCURRENCY=2

2
.gitignore vendored
View File

@@ -1,5 +1,7 @@
# Environment secrets — never commit the real .env # Environment secrets — never commit the real .env
.env .env
# Stale local scratch copy of .env.example; nothing in the test stack reads it.
.env.test
# Rust # Rust
backend/target/ backend/target/

View File

@@ -1,5 +1,8 @@
{$DOMAIN} { {$DOMAIN} {
encode zstd gzip # Compress everything EXCEPT the SSE stream — gzip buffering delays
# "real-time" likes/comments until the ~30s keep-alive tick.
@compressible not path /api/v1/stream
encode @compressible zstd gzip
# Site-wide security headers (defense-in-depth). HSTS is free since Caddy # Site-wide security headers (defense-in-depth). HSTS is free since Caddy
# already terminates TLS. nosniff also covers all of /media/*. # already terminates TLS. nosniff also covers all of /media/*.

View File

@@ -94,9 +94,9 @@ eventsnap/
### Deploy on a fresh VPS ### Deploy on a fresh VPS
```bash ```bash
# 1. Clone the repository # 1. Clone the repository (into a lowercase dir, matching the paths used below)
git clone https://git.mc02.dev/fabi/EventSnap.git git clone https://git.mc02.dev/fabi/EventSnap.git eventsnap
cd EventSnap cd eventsnap
# 2. Configure environment # 2. Configure environment
cp .env.example .env cp .env.example .env
@@ -108,6 +108,8 @@ docker compose up -d
Caddy automatically obtains a Let's Encrypt certificate on first start. The app is live at `https://DOMAIN` within ~30 seconds. Caddy automatically obtains a Let's Encrypt certificate on first start. The app is live at `https://DOMAIN` within ~30 seconds.
> **If the site never comes up:** with `APP_ENV=production` the backend **refuses to boot** while `JWT_SECRET`/`ADMIN_PASSWORD_HASH` still hold the `.env.example` placeholders (this is deliberate — a publicly-known signing key is worse than downtime). Caddy then waits on the unhealthy `app` container and never serves. Check `docker compose logs app` — a "Refusing to start … placeholder …" line means you skipped step 2. Rotate the secrets (see below) and restart.
> **Production note:** `docker compose up -d` does **not** expose the database — Postgres is reachable only on the internal Docker network. For local development where you need host access to Postgres, opt into the dev overlay explicitly: > **Production note:** `docker compose up -d` does **not** expose the database — Postgres is reachable only on the internal Docker network. For local development where you need host access to Postgres, opt into the dev overlay explicitly:
> ```bash > ```bash
> docker compose -f docker-compose.yml -f docker-compose.dev.yml up > docker compose -f docker-compose.yml -f docker-compose.dev.yml up

View File

@@ -0,0 +1,3 @@
DROP INDEX IF EXISTS idx_comment_hashtag_hashtag;
DROP INDEX IF EXISTS idx_comment_user;
DROP INDEX IF EXISTS idx_upload_event_created_id;

View File

@@ -0,0 +1,17 @@
-- Composite feed index with an id tiebreaker so keyset pagination
-- (ORDER BY created_at DESC, id DESC) stays index-covered and stable when
-- multiple uploads share a created_at timestamp.
CREATE INDEX idx_upload_event_created_id
ON upload(event_id, created_at DESC, id DESC)
WHERE deleted_at IS NULL;
-- A user's own comments (moderation, "who commented"). The sibling
-- idx_upload_user already exists for uploads; comment(user_id) was missing.
CREATE INDEX idx_comment_user
ON comment(user_id)
WHERE deleted_at IS NULL;
-- Hashtag filtering over comments — mirrors idx_upload_hashtag_hashtag, which
-- only covered upload_hashtag.
CREATE INDEX idx_comment_hashtag_hashtag
ON comment_hashtag(hashtag_id);

View File

@@ -1,4 +1,4 @@
use axum::extract::{FromRequestParts, State}; use axum::extract::FromRequestParts;
use axum::http::request::Parts; use axum::http::request::Parts;
use uuid::Uuid; use uuid::Uuid;
@@ -43,6 +43,18 @@ impl FromRequestParts<AppState> for AuthUser {
.map_err(|e| AppError::Internal(e.into()))? .map_err(|e| AppError::Internal(e.into()))?
.ok_or_else(|| AppError::Unauthorized("Sitzung nicht gefunden oder abgelaufen.".into()))?; .ok_or_else(|| AppError::Unauthorized("Sitzung nicht gefunden oder abgelaufen.".into()))?;
// Trust *live* DB state, not the JWT: a role/ban stored in the token would
// survive a demote/ban for the full session lifetime (up to 30d). Re-read
// the user row so a demoted host loses host powers and a banned user is
// locked out immediately on their next request.
let user = crate::models::user::User::find_by_id(&state.pool, claims.sub)
.await
.map_err(|e| AppError::Internal(e.into()))?
.ok_or_else(|| AppError::Unauthorized("Benutzer nicht gefunden.".into()))?;
if user.is_banned {
return Err(AppError::Forbidden("Dein Zugang wurde gesperrt.".into()));
}
// Update last_seen_at in the background (fire-and-forget). Failures are // Update last_seen_at in the background (fire-and-forget). Failures are
// non-fatal but worth surfacing — silent swallowing hides DB connection // non-fatal but worth surfacing — silent swallowing hides DB connection
// pressure that would otherwise be the first symptom of a real problem. // pressure that would otherwise be the first symptom of a real problem.
@@ -55,9 +67,9 @@ impl FromRequestParts<AppState> for AuthUser {
}); });
Ok(Self { Ok(Self {
user_id: claims.sub, user_id: user.id,
event_id: claims.event_id, event_id: user.event_id,
role: claims.role, role: user.role,
token_hash, token_hash,
}) })
} }

View File

@@ -6,6 +6,47 @@ use anyhow::{anyhow, Context, Result};
/// we refuse to start with this value; otherwise we warn loudly. /// we refuse to start with this value; otherwise we warn loudly.
const DEV_JWT_SECRET_SENTINEL: &str = "dev_secret_do_not_use_in_production_32byteslong_aaaa"; const DEV_JWT_SECRET_SENTINEL: &str = "dev_secret_do_not_use_in_production_32byteslong_aaaa";
/// A secret is "placeholder-ish" if it's the shipped dev sentinel or still carries
/// the tell-tale scaffolding substrings from `.env.example`. Length alone is not
/// enough — the shipped `change_me_...` placeholder is >32 chars.
fn looks_placeholder(s: &str) -> bool {
let lower = s.to_ascii_lowercase();
s == DEV_JWT_SECRET_SENTINEL
|| lower.contains("change_me")
|| lower.contains("dev_secret")
|| lower.contains("placeholder")
}
/// Enforce secret hygiene. In production every guard is hard-fail: a booting app
/// with a publicly-known signing key is worse than one that refuses to start.
/// Outside production the dev sentinel is tolerated (warned) so local dev is frictionless.
fn validate_secrets(is_prod: bool, jwt_secret: &str, admin_password_hash: &str) -> Result<()> {
if is_prod {
if looks_placeholder(jwt_secret) {
return Err(anyhow!(
"Refusing to start in production with a placeholder JWT_SECRET — \
rotate it (openssl rand -hex 64)."
));
}
if jwt_secret.len() < 32 {
return Err(anyhow!("JWT_SECRET must be at least 32 characters."));
}
if admin_password_hash.is_empty() || looks_placeholder(admin_password_hash) {
return Err(anyhow!(
"Refusing to start in production without a real ADMIN_PASSWORD_HASH — \
generate one (htpasswd -bnBC 12 '' <password> | tr -d ':\\n')."
));
}
} else if jwt_secret == DEV_JWT_SECRET_SENTINEL {
tracing::warn!(
"JWT_SECRET is the dev sentinel — fine for local development, NEVER ship this."
);
} else if jwt_secret.len() < 32 {
return Err(anyhow!("JWT_SECRET must be at least 32 characters."));
}
Ok(())
}
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct AppConfig { pub struct AppConfig {
pub database_url: String, pub database_url: String,
@@ -25,19 +66,9 @@ impl AppConfig {
let is_prod = app_env.eq_ignore_ascii_case("production"); let is_prod = app_env.eq_ignore_ascii_case("production");
let jwt_secret = std::env::var("JWT_SECRET").context("JWT_SECRET must be set")?; let jwt_secret = std::env::var("JWT_SECRET").context("JWT_SECRET must be set")?;
if jwt_secret == DEV_JWT_SECRET_SENTINEL { let admin_password_hash = std::env::var("ADMIN_PASSWORD_HASH").unwrap_or_default();
if is_prod {
return Err(anyhow!( validate_secrets(is_prod, &jwt_secret, &admin_password_hash)?;
"Refusing to start in production with the well-known dev JWT_SECRET — \
rotate it (openssl rand -hex 64)."
));
}
tracing::warn!(
"JWT_SECRET is the dev sentinel — fine for local development, NEVER ship this."
);
} else if jwt_secret.len() < 32 {
return Err(anyhow!("JWT_SECRET must be at least 32 characters."));
}
Ok(Self { Ok(Self {
database_url: std::env::var("DATABASE_URL") database_url: std::env::var("DATABASE_URL")
@@ -47,8 +78,7 @@ impl AppConfig {
.unwrap_or_else(|_| "30".to_string()) .unwrap_or_else(|_| "30".to_string())
.parse() .parse()
.context("SESSION_EXPIRY_DAYS must be a number")?, .context("SESSION_EXPIRY_DAYS must be a number")?,
admin_password_hash: std::env::var("ADMIN_PASSWORD_HASH") admin_password_hash,
.unwrap_or_default(),
event_name: std::env::var("EVENT_NAME") event_name: std::env::var("EVENT_NAME")
.unwrap_or_else(|_| "EventSnap".to_string()), .unwrap_or_else(|_| "EventSnap".to_string()),
event_slug: std::env::var("EVENT_SLUG") event_slug: std::env::var("EVENT_SLUG")
@@ -63,3 +93,65 @@ impl AppConfig {
}) })
} }
} }
#[cfg(test)]
mod tests {
use super::*;
const REAL_SECRET: &str = "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2";
const REAL_HASH: &str = "$2y$12$abcdefghijklmnopqrstuv.wxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012";
#[test]
fn prod_rejects_shipped_placeholder_secret() {
// The exact string shipped in `.env` — >32 chars, so it must be caught by
// the substring guard, not the length check.
let err = validate_secrets(true, "change_me_to_a_random_64_byte_hex_string", REAL_HASH);
assert!(err.is_err(), "placeholder JWT_SECRET must be rejected in prod");
}
#[test]
fn prod_rejects_dev_sentinel_and_short_secret() {
assert!(validate_secrets(true, DEV_JWT_SECRET_SENTINEL, REAL_HASH).is_err());
assert!(validate_secrets(true, "tooshort", REAL_HASH).is_err());
}
#[test]
fn prod_rejects_missing_or_placeholder_admin_hash() {
assert!(validate_secrets(true, REAL_SECRET, "").is_err());
assert!(validate_secrets(true, REAL_SECRET, "$2y$12$placeholder_replace_me").is_err());
}
#[test]
fn prod_accepts_real_secrets() {
assert!(validate_secrets(true, REAL_SECRET, REAL_HASH).is_ok());
}
#[test]
fn non_prod_tolerates_dev_sentinel() {
assert!(validate_secrets(false, DEV_JWT_SECRET_SENTINEL, "").is_ok());
}
#[test]
fn non_prod_still_rejects_short_non_sentinel_secret() {
assert!(validate_secrets(false, "tooshort", "").is_err());
}
#[test]
fn placeholder_detection_is_case_insensitive() {
// looks_placeholder lowercases before matching — an upper/mixed-case
// placeholder must still be rejected in prod.
assert!(validate_secrets(true, "CHANGE_ME_TO_A_RANDOM_64_BYTE_HEX_STRING", REAL_HASH).is_err());
assert!(validate_secrets(true, REAL_SECRET, "$2Y$12$PLACEHOLDER_replace_me").is_err());
}
#[test]
fn prod_len_boundary_at_32() {
// Exactly 32 non-placeholder chars is the minimum accepted; 31 is rejected.
const LEN_32: &str = "abcdefghijklmnopqrstuvwxyz012345";
const LEN_31: &str = "abcdefghijklmnopqrstuvwxyz01234";
assert_eq!(LEN_32.len(), 32);
assert_eq!(LEN_31.len(), 31);
assert!(validate_secrets(true, LEN_32, REAL_HASH).is_ok());
assert!(validate_secrets(true, LEN_31, REAL_HASH).is_err());
}
}

View File

@@ -146,6 +146,8 @@ pub async fn patch_config(
let mut privacy_note_changed = false; let mut privacy_note_changed = false;
// Validate every key first so a bad value in the batch can't leave a partial
// update behind — validation must fully precede any write.
for (key, value) in &body { for (key, value) in &body {
let key_str = key.as_str(); let key_str = key.as_str();
if NUMERIC_KEYS.contains(&key_str) { if NUMERIC_KEYS.contains(&key_str) {
@@ -164,7 +166,9 @@ pub async fn patch_config(
} }
} }
} else if TEXT_KEYS.contains(&key_str) { } else if TEXT_KEYS.contains(&key_str) {
if value.len() > PRIVACY_NOTE_MAX_LEN { // Count characters, not bytes — the message says "Zeichen" and a
// multi-byte grapheme shouldn't count against the limit multiple times.
if value.chars().count() > PRIVACY_NOTE_MAX_LEN {
return Err(AppError::BadRequest(format!( return Err(AppError::BadRequest(format!(
"Wert für {key} ist zu lang (max. {PRIVACY_NOTE_MAX_LEN} Zeichen)." "Wert für {key} ist zu lang (max. {PRIVACY_NOTE_MAX_LEN} Zeichen)."
))); )));
@@ -177,16 +181,21 @@ pub async fn patch_config(
"Unbekannter Konfigurationsschlüssel: {key}" "Unbekannter Konfigurationsschlüssel: {key}"
))); )));
} }
}
// Apply all writes in one transaction — the batch is all-or-nothing.
let mut tx = state.pool.begin().await?;
for (key, value) in &body {
sqlx::query( sqlx::query(
"INSERT INTO config (key, value, updated_at) VALUES ($1, $2, NOW()) "INSERT INTO config (key, value, updated_at) VALUES ($1, $2, NOW())
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()", ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()",
) )
.bind(key) .bind(key)
.bind(value) .bind(value)
.execute(&state.pool) .execute(&mut *tx)
.await?; .await?;
} }
tx.commit().await?;
// Notify all clients that a publicly-readable config value changed so their stores // Notify all clients that a publicly-readable config value changed so their stores
// (e.g. the privacy note in My Account) refresh without a manual reload. // (e.g. the privacy note in My Account) refresh without a manual reload.

View File

@@ -79,6 +79,17 @@ pub async fn feed(
let limit = q.limit.unwrap_or(20).min(100); let limit = q.limit.unwrap_or(20).min(100);
// Resolve the cursor to a (created_at, id) position. The pair is compared as a
// tuple so ties on created_at break on id — keyset pagination on created_at
// alone would silently drop rows sharing a timestamp across a page boundary.
let (cursor_time, cursor_id) = match q.cursor {
Some(c) => match get_cursor_pos(&state.pool, c).await {
Some((t, id)) => (Some(t), Some(id)),
None => (None, None),
},
None => (None, None),
};
let rows = if let Some(hashtag) = &q.hashtag { let rows = if let Some(hashtag) = &q.hashtag {
let tag = hashtag.trim().trim_start_matches('#').to_lowercase(); let tag = hashtag.trim().trim_start_matches('#').to_lowercase();
sqlx::query_as::<_, FeedRow>( sqlx::query_as::<_, FeedRow>(
@@ -88,19 +99,14 @@ pub async fn feed(
JOIN upload_hashtag uh ON uh.upload_id = v.id JOIN upload_hashtag uh ON uh.upload_id = v.id
JOIN hashtag h ON h.id = uh.hashtag_id AND h.tag = $1 JOIN hashtag h ON h.id = uh.hashtag_id AND h.tag = $1
WHERE v.event_id = $2 WHERE v.event_id = $2
AND ($3::timestamptz IS NULL OR v.created_at < $3) AND ($3::timestamptz IS NULL OR (v.created_at, v.id) < ($3, $4))
ORDER BY v.created_at DESC ORDER BY v.created_at DESC, v.id DESC
LIMIT $4", LIMIT $5",
) )
.bind(&tag) .bind(&tag)
.bind(auth.event_id) .bind(auth.event_id)
.bind( .bind(cursor_time)
if let Some(cursor) = q.cursor { .bind(cursor_id)
get_cursor_time(&state.pool, cursor).await
} else {
None
},
)
.bind(limit + 1) .bind(limit + 1)
.fetch_all(&state.pool) .fetch_all(&state.pool)
.await? .await?
@@ -110,18 +116,13 @@ pub async fn feed(
mime_type, caption, like_count, comment_count, created_at mime_type, caption, like_count, comment_count, created_at
FROM v_feed FROM v_feed
WHERE event_id = $1 WHERE event_id = $1
AND ($2::timestamptz IS NULL OR created_at < $2) AND ($2::timestamptz IS NULL OR (created_at, id) < ($2, $3))
ORDER BY created_at DESC ORDER BY created_at DESC, id DESC
LIMIT $3", LIMIT $4",
) )
.bind(auth.event_id) .bind(auth.event_id)
.bind( .bind(cursor_time)
if let Some(cursor) = q.cursor { .bind(cursor_id)
get_cursor_time(&state.pool, cursor).await
} else {
None
},
)
.bind(limit + 1) .bind(limit + 1)
.fetch_all(&state.pool) .fetch_all(&state.pool)
.await? .await?
@@ -171,6 +172,11 @@ pub struct DeltaQuery {
pub struct DeltaResponse { pub struct DeltaResponse {
pub uploads: Vec<FeedUpload>, pub uploads: Vec<FeedUpload>,
pub deleted_ids: Vec<Uuid>, pub deleted_ids: Vec<Uuid>,
/// True when the upload query hit `DELTA_LIMIT`: the response carries only the
/// newest slice of the gap, so the client must fall back to a full feed refresh
/// rather than merging (the older missed uploads are absent and unrecoverable
/// via a later delta, which advances `since` past them).
pub truncated: bool,
} }
pub async fn feed_delta( pub async fn feed_delta(
@@ -178,18 +184,28 @@ pub async fn feed_delta(
auth: AuthUser, auth: AuthUser,
Query(q): Query<DeltaQuery>, Query(q): Query<DeltaQuery>,
) -> Result<Json<DeltaResponse>, AppError> { ) -> Result<Json<DeltaResponse>, AppError> {
// Bounded like the paginated feed: a stale `since` could otherwise pull the
// entire event's uploads in one response. If a client hits the cap it should
// fall back to a full feed refresh rather than another delta.
const DELTA_LIMIT: i64 = 200;
let rows = sqlx::query_as::<_, FeedRow>( let rows = sqlx::query_as::<_, FeedRow>(
"SELECT id, user_id, uploader_name, preview_path, thumbnail_path, "SELECT id, user_id, uploader_name, preview_path, thumbnail_path,
mime_type, caption, like_count, comment_count, created_at mime_type, caption, like_count, comment_count, created_at
FROM v_feed FROM v_feed
WHERE event_id = $1 AND created_at > $2 WHERE event_id = $1 AND created_at > $2
ORDER BY created_at DESC", ORDER BY created_at DESC, id DESC
LIMIT $3",
) )
.bind(auth.event_id) .bind(auth.event_id)
.bind(q.since) .bind(q.since)
.bind(DELTA_LIMIT)
.fetch_all(&state.pool) .fetch_all(&state.pool)
.await?; .await?;
// Hit the cap => this is only the newest slice of a larger gap. Signal the
// client to full-refresh instead of merging a partial delta.
let truncated = rows.len() as i64 >= DELTA_LIMIT;
let deleted_ids: Vec<(Uuid,)> = sqlx::query_as( let deleted_ids: Vec<(Uuid,)> = sqlx::query_as(
"SELECT id FROM upload "SELECT id FROM upload
WHERE event_id = $1 AND deleted_at IS NOT NULL AND deleted_at > $2", WHERE event_id = $1 AND deleted_at IS NOT NULL AND deleted_at > $2",
@@ -222,6 +238,7 @@ pub async fn feed_delta(
Ok(Json(DeltaResponse { Ok(Json(DeltaResponse {
uploads, uploads,
deleted_ids: deleted_ids.into_iter().map(|r| r.0).collect(), deleted_ids: deleted_ids.into_iter().map(|r| r.0).collect(),
truncated,
})) }))
} }
@@ -249,14 +266,17 @@ pub async fn hashtags(
)) ))
} }
async fn get_cursor_time(pool: &sqlx::PgPool, cursor_id: Uuid) -> Option<DateTime<Utc>> { /// Resolve a cursor id to its `(created_at, id)` position. Both are needed:
let row: Option<(DateTime<Utc>,)> = /// `created_at` alone isn't unique, so pagination must break ties on `id` to
sqlx::query_as("SELECT created_at FROM upload WHERE id = $1") /// avoid silently dropping rows that share a timestamp across a page boundary.
async fn get_cursor_pos(pool: &sqlx::PgPool, cursor_id: Uuid) -> Option<(DateTime<Utc>, Uuid)> {
let row: Option<(DateTime<Utc>, Uuid)> =
sqlx::query_as("SELECT created_at, id FROM upload WHERE id = $1")
.bind(cursor_id) .bind(cursor_id)
.fetch_optional(pool) .fetch_optional(pool)
.await .await
.ok()?; .ok()?;
row.map(|r| r.0) row
} }
async fn get_liked_set( async fn get_liked_set(

View File

@@ -113,10 +113,11 @@ pub async fn ban_user(
} }
sqlx::query( sqlx::query(
"UPDATE \"user\" SET is_banned = TRUE, uploads_hidden = $2 WHERE id = $1", "UPDATE \"user\" SET is_banned = TRUE, uploads_hidden = $2 WHERE id = $1 AND event_id = $3",
) )
.bind(user_id) .bind(user_id)
.bind(body.hide_uploads) .bind(body.hide_uploads)
.bind(auth.event_id)
.execute(&state.pool) .execute(&state.pool)
.await?; .await?;
@@ -263,7 +264,7 @@ pub async fn reset_user_pin(
sqlx::query( sqlx::query(
"UPDATE \"user\" "UPDATE \"user\"
SET recovery_pin_hash = $1, SET recovery_pin_hash = $1,
pin_failed_attempts = 0, failed_pin_attempts = 0,
pin_locked_until = NULL pin_locked_until = NULL
WHERE id = $2", WHERE id = $2",
) )
@@ -341,14 +342,18 @@ pub async fn close_event(
State(state): State<AppState>, State(state): State<AppState>,
RequireHost(_auth): RequireHost, RequireHost(_auth): RequireHost,
) -> Result<StatusCode, AppError> { ) -> Result<StatusCode, AppError> {
sqlx::query( let result = sqlx::query(
"UPDATE event SET uploads_locked_at = NOW() WHERE slug = $1 AND uploads_locked_at IS NULL", "UPDATE event SET uploads_locked_at = NOW() WHERE slug = $1 AND uploads_locked_at IS NULL",
) )
.bind(&state.config.event_slug) .bind(&state.config.event_slug)
.execute(&state.pool) .execute(&state.pool)
.await?; .await?;
let _ = state.sse_tx.send(SseEvent::new("event-closed", "{}")); // Only broadcast when this call actually flipped the lock — closing an
// already-closed event is a no-op and shouldn't spam listeners.
if result.rows_affected() > 0 {
let _ = state.sse_tx.send(SseEvent::new("event-closed", "{}"));
}
Ok(StatusCode::NO_CONTENT) Ok(StatusCode::NO_CONTENT)
} }
@@ -357,14 +362,16 @@ pub async fn open_event(
State(state): State<AppState>, State(state): State<AppState>,
RequireHost(_auth): RequireHost, RequireHost(_auth): RequireHost,
) -> Result<StatusCode, AppError> { ) -> Result<StatusCode, AppError> {
sqlx::query( let result = sqlx::query(
"UPDATE event SET uploads_locked_at = NULL WHERE slug = $1", "UPDATE event SET uploads_locked_at = NULL WHERE slug = $1 AND uploads_locked_at IS NOT NULL",
) )
.bind(&state.config.event_slug) .bind(&state.config.event_slug)
.execute(&state.pool) .execute(&state.pool)
.await?; .await?;
let _ = state.sse_tx.send(SseEvent::new("event-opened", "{}")); if result.rows_affected() > 0 {
let _ = state.sse_tx.send(SseEvent::new("event-opened", "{}"));
}
Ok(StatusCode::NO_CONTENT) Ok(StatusCode::NO_CONTENT)
} }

View File

@@ -12,6 +12,18 @@ use crate::models::hashtag::{self, Hashtag};
use crate::models::upload::Upload; use crate::models::upload::Upload;
use crate::state::AppState; use crate::state::AppState;
/// Reject the request when the event's uploads (and, by extension, social
/// interaction) are locked. Mirrors the guard in the upload handler.
async fn require_event_open(state: &AppState) -> Result<(), AppError> {
let event = crate::models::event::Event::find_by_slug(&state.pool, &state.config.event_slug)
.await?
.ok_or_else(|| AppError::NotFound("Event nicht gefunden.".into()))?;
if event.uploads_locked_at.is_some() {
return Err(AppError::Forbidden("Das Event ist geschlossen.".into()));
}
Ok(())
}
pub async fn toggle_like( pub async fn toggle_like(
State(state): State<AppState>, State(state): State<AppState>,
auth: AuthUser, auth: AuthUser,
@@ -31,6 +43,9 @@ pub async fn toggle_like(
.await? .await?
.ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?; .ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?;
// A closed event freezes social interaction too, matching the upload handler.
require_event_open(&state).await?;
// Try to insert; if conflict, delete (toggle) // Try to insert; if conflict, delete (toggle)
let result = sqlx::query( let result = sqlx::query(
"INSERT INTO \"like\" (upload_id, user_id) VALUES ($1, $2) "INSERT INTO \"like\" (upload_id, user_id) VALUES ($1, $2)
@@ -120,6 +135,9 @@ pub async fn add_comment(
.await? .await?
.ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?; .ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?;
// A closed event freezes social interaction too, matching the upload handler.
require_event_open(&state).await?;
let text = body.body.trim(); let text = body.body.trim();
let text_chars = text.chars().count(); let text_chars = text.chars().count();
if text_chars == 0 || text_chars > 500 { if text_chars == 0 || text_chars > 500 {
@@ -128,20 +146,22 @@ pub async fn add_comment(
)); ));
} }
let comment = Comment::create(&state.pool, upload_id, auth.user_id, text).await?; // Insert the comment and link its hashtags atomically, so a crash mid-loop
// can't leave a committed comment with only some of its tags indexed.
// Process hashtags in comment body
let tags = hashtag::extract_hashtags(text); let tags = hashtag::extract_hashtags(text);
let mut tx = state.pool.begin().await?;
let comment = Comment::create(&mut *tx, upload_id, auth.user_id, text).await?;
for tag in &tags { for tag in &tags {
let h = Hashtag::upsert(&state.pool, auth.event_id, tag).await?; let h = Hashtag::upsert(&mut *tx, auth.event_id, tag).await?;
sqlx::query( sqlx::query(
"INSERT INTO comment_hashtag (comment_id, hashtag_id) VALUES ($1, $2) ON CONFLICT DO NOTHING", "INSERT INTO comment_hashtag (comment_id, hashtag_id) VALUES ($1, $2) ON CONFLICT DO NOTHING",
) )
.bind(comment.id) .bind(comment.id)
.bind(h.id) .bind(h.id)
.execute(&state.pool) .execute(&mut *tx)
.await?; .await?;
} }
tx.commit().await?;
// Fresh count so feed clients can patch the single card in place instead of // Fresh count so feed clients can patch the single card in place instead of
// refetching page 1 (mirrors v_feed.comment_count = COUNT(DISTINCT c.id); COUNT(*) // refetching page 1 (mirrors v_feed.comment_count = COUNT(DISTINCT c.id); COUNT(*)

View File

@@ -48,6 +48,10 @@ pub async fn stream(
.consume(&q.ticket) .consume(&q.ticket)
.ok_or_else(|| AppError::Unauthorized("Ticket ungültig oder abgelaufen.".into()))?; .ok_or_else(|| AppError::Unauthorized("Ticket ungültig oder abgelaufen.".into()))?;
// NOTE: this authenticates via ticket→session, not the `AuthUser` extractor, so
// it does not re-check `is_banned`. A user banned mid-stream keeps receiving
// events until the connection drops; they cannot reconnect (issue_ticket uses
// AuthUser, which rejects banned users). Documented in docs/SECURITY-BACKLOG.md.
Session::find_by_token_hash(&state.pool, &token_hash) Session::find_by_token_hash(&state.pool, &token_hash)
.await .await
.map_err(|e| AppError::Internal(e.into()))? .map_err(|e| AppError::Internal(e.into()))?

View File

@@ -190,25 +190,6 @@ pub async fn upload(
} }
tokio::fs::write(&absolute_path, &data).await.map_err(|e| AppError::Internal(e.into()))?; tokio::fs::write(&absolute_path, &data).await.map_err(|e| AppError::Internal(e.into()))?;
// Update user's total upload bytes
sqlx::query("UPDATE \"user\" SET total_upload_bytes = total_upload_bytes + $2 WHERE id = $1")
.bind(auth.user_id)
.bind(size)
.execute(&state.pool)
.await?;
// Insert upload record
let upload = Upload::create(
&state.pool,
auth.event_id,
auth.user_id,
&relative_path,
&mime,
size,
caption.as_deref(),
)
.await?;
// Process hashtags from caption and explicit CSV // Process hashtags from caption and explicit CSV
let mut tags: Vec<String> = Vec::new(); let mut tags: Vec<String> = Vec::new();
if let Some(ref cap) = caption { if let Some(ref cap) = caption {
@@ -225,10 +206,30 @@ pub async fn upload(
tags.sort(); tags.sort();
tags.dedup(); tags.dedup();
// Quota accounting, the upload row, and its hashtag links must be atomic: a
// crash between the bytes increment and the insert would permanently charge
// bytes with no row to reclaim them (silent quota erosion / spurious lockout).
let mut tx = state.pool.begin().await?;
sqlx::query("UPDATE \"user\" SET total_upload_bytes = total_upload_bytes + $2 WHERE id = $1")
.bind(auth.user_id)
.bind(size)
.execute(&mut *tx)
.await?;
let upload = Upload::create(
&mut *tx,
auth.event_id,
auth.user_id,
&relative_path,
&mime,
size,
caption.as_deref(),
)
.await?;
for tag in &tags { for tag in &tags {
let h = Hashtag::upsert(&state.pool, auth.event_id, tag).await?; let h = Hashtag::upsert(&mut *tx, auth.event_id, tag).await?;
Hashtag::link_to_upload(&state.pool, upload.id, h.id).await?; Hashtag::link_to_upload(&mut *tx, upload.id, h.id).await?;
} }
tx.commit().await?;
// Spawn compression task // Spawn compression task
state state
@@ -279,17 +280,20 @@ pub async fn edit_upload(
return Err(AppError::Forbidden("Nur eigene Uploads bearbeiten.".into())); return Err(AppError::Forbidden("Nur eigene Uploads bearbeiten.".into()));
} }
// Caption update + hashtag wipe-then-relink in one transaction, so a crash
// mid-relink can't leave the upload with its hashtags stripped.
let mut tx = state.pool.begin().await?;
if let Some(ref caption) = body.caption { if let Some(ref caption) = body.caption {
Upload::update_caption(&state.pool, upload_id, Some(caption)).await?; Upload::update_caption(&mut *tx, upload_id, Some(caption)).await?;
} }
if let Some(ref hashtags) = body.hashtags { if let Some(ref hashtags) = body.hashtags {
Hashtag::unlink_all_from_upload(&state.pool, upload_id).await?; Hashtag::unlink_all_from_upload(&mut *tx, upload_id).await?;
for tag in hashtags { for tag in hashtags {
let h = Hashtag::upsert(&state.pool, auth.event_id, tag).await?; let h = Hashtag::upsert(&mut *tx, auth.event_id, tag).await?;
Hashtag::link_to_upload(&state.pool, upload_id, h.id).await?; Hashtag::link_to_upload(&mut *tx, upload_id, h.id).await?;
} }
} }
tx.commit().await?;
Ok(StatusCode::OK) Ok(StatusCode::OK)
} }

View File

@@ -24,19 +24,24 @@ pub struct CommentDto {
} }
impl Comment { impl Comment {
pub async fn create( /// Takes any executor so the caller can insert the comment and link its
pool: &PgPool, /// hashtags inside a single transaction.
pub async fn create<'e, E>(
executor: E,
upload_id: Uuid, upload_id: Uuid,
user_id: Uuid, user_id: Uuid,
body: &str, body: &str,
) -> Result<Self, sqlx::Error> { ) -> Result<Self, sqlx::Error>
where
E: sqlx::PgExecutor<'e>,
{
sqlx::query_as::<_, Self>( sqlx::query_as::<_, Self>(
"INSERT INTO comment (upload_id, user_id, body) VALUES ($1, $2, $3) RETURNING *", "INSERT INTO comment (upload_id, user_id, body) VALUES ($1, $2, $3) RETURNING *",
) )
.bind(upload_id) .bind(upload_id)
.bind(user_id) .bind(user_id)
.bind(body) .bind(body)
.fetch_one(pool) .fetch_one(executor)
.await .await
} }

View File

@@ -10,7 +10,13 @@ pub struct Hashtag {
impl Hashtag { impl Hashtag {
/// Upsert a hashtag (insert if not exists, return existing if it does). /// Upsert a hashtag (insert if not exists, return existing if it does).
pub async fn upsert(pool: &PgPool, event_id: Uuid, tag: &str) -> Result<Self, sqlx::Error> { ///
/// Takes any executor so callers can run it inside a transaction (atomic
/// upload/comment writes) or standalone against the pool.
pub async fn upsert<'e, E>(executor: E, event_id: Uuid, tag: &str) -> Result<Self, sqlx::Error>
where
E: sqlx::PgExecutor<'e>,
{
let normalized = tag.trim().trim_start_matches('#').to_lowercase(); let normalized = tag.trim().trim_start_matches('#').to_lowercase();
sqlx::query_as::<_, Self>( sqlx::query_as::<_, Self>(
"INSERT INTO hashtag (event_id, tag) VALUES ($1, $2) "INSERT INTO hashtag (event_id, tag) VALUES ($1, $2)
@@ -19,33 +25,39 @@ impl Hashtag {
) )
.bind(event_id) .bind(event_id)
.bind(&normalized) .bind(&normalized)
.fetch_one(pool) .fetch_one(executor)
.await .await
} }
pub async fn link_to_upload( pub async fn link_to_upload<'e, E>(
pool: &PgPool, executor: E,
upload_id: Uuid, upload_id: Uuid,
hashtag_id: Uuid, hashtag_id: Uuid,
) -> Result<(), sqlx::Error> { ) -> Result<(), sqlx::Error>
where
E: sqlx::PgExecutor<'e>,
{
sqlx::query( sqlx::query(
"INSERT INTO upload_hashtag (upload_id, hashtag_id) VALUES ($1, $2) "INSERT INTO upload_hashtag (upload_id, hashtag_id) VALUES ($1, $2)
ON CONFLICT DO NOTHING", ON CONFLICT DO NOTHING",
) )
.bind(upload_id) .bind(upload_id)
.bind(hashtag_id) .bind(hashtag_id)
.execute(pool) .execute(executor)
.await?; .await?;
Ok(()) Ok(())
} }
pub async fn unlink_all_from_upload( pub async fn unlink_all_from_upload<'e, E>(
pool: &PgPool, executor: E,
upload_id: Uuid, upload_id: Uuid,
) -> Result<(), sqlx::Error> { ) -> Result<(), sqlx::Error>
where
E: sqlx::PgExecutor<'e>,
{
sqlx::query("DELETE FROM upload_hashtag WHERE upload_id = $1") sqlx::query("DELETE FROM upload_hashtag WHERE upload_id = $1")
.bind(upload_id) .bind(upload_id)
.execute(pool) .execute(executor)
.await?; .await?;
Ok(()) Ok(())
} }

View File

@@ -36,15 +36,20 @@ pub struct UploadDto {
} }
impl Upload { impl Upload {
pub async fn create( /// Takes any executor so the caller can run it inside a transaction (atomic
pool: &PgPool, /// quota + insert) or standalone against the pool.
pub async fn create<'e, E>(
executor: E,
event_id: Uuid, event_id: Uuid,
user_id: Uuid, user_id: Uuid,
original_path: &str, original_path: &str,
mime_type: &str, mime_type: &str,
original_size_bytes: i64, original_size_bytes: i64,
caption: Option<&str>, caption: Option<&str>,
) -> Result<Self, sqlx::Error> { ) -> Result<Self, sqlx::Error>
where
E: sqlx::PgExecutor<'e>,
{
sqlx::query_as::<_, Self>( sqlx::query_as::<_, Self>(
"INSERT INTO upload (event_id, user_id, original_path, mime_type, original_size_bytes, caption) "INSERT INTO upload (event_id, user_id, original_path, mime_type, original_size_bytes, caption)
VALUES ($1, $2, $3, $4, $5, $6) VALUES ($1, $2, $3, $4, $5, $6)
@@ -56,7 +61,7 @@ impl Upload {
.bind(mime_type) .bind(mime_type)
.bind(original_size_bytes) .bind(original_size_bytes)
.bind(caption) .bind(caption)
.fetch_one(pool) .fetch_one(executor)
.await .await
} }
@@ -182,15 +187,18 @@ impl Upload {
Ok(deleted) Ok(deleted)
} }
pub async fn update_caption( pub async fn update_caption<'e, E>(
pool: &PgPool, executor: E,
id: Uuid, id: Uuid,
caption: Option<&str>, caption: Option<&str>,
) -> Result<(), sqlx::Error> { ) -> Result<(), sqlx::Error>
where
E: sqlx::PgExecutor<'e>,
{
sqlx::query("UPDATE upload SET caption = $2 WHERE id = $1") sqlx::query("UPDATE upload SET caption = $2 WHERE id = $1")
.bind(id) .bind(id)
.bind(caption) .bind(caption)
.execute(pool) .execute(executor)
.await?; .await?;
Ok(()) Ok(())
} }

View File

@@ -71,14 +71,21 @@ impl RateLimiter {
} }
} }
/// Extract the client IP from X-Forwarded-For (Caddy sets this) or fall back /// Extract the client IP from X-Forwarded-For or fall back to a provided socket
/// to a provided socket address string. /// address string.
///
/// We take the **right-most** entry, not the left-most. Caddy is the sole ingress
/// and the app port is only `expose`d (never published), so the last hop Caddy
/// appends is the real client. A client can prepend arbitrary spoofed values to
/// the left of XFF to dodge throttles — those are ignored here. This assumes
/// exactly one trusted proxy (Caddy); revisit if that changes.
pub fn client_ip(headers: &axum::http::HeaderMap, fallback: &str) -> String { pub fn client_ip(headers: &axum::http::HeaderMap, fallback: &str) -> String {
headers headers
.get("x-forwarded-for") .get("x-forwarded-for")
.and_then(|v| v.to_str().ok()) .and_then(|v| v.to_str().ok())
.and_then(|s| s.split(',').next()) .and_then(|s| s.rsplit(',').next())
.map(|s| s.trim().to_owned()) .map(|s| s.trim().to_owned())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| fallback.to_owned()) .unwrap_or_else(|| fallback.to_owned())
} }
@@ -134,9 +141,18 @@ mod tests {
} }
#[test] #[test]
fn client_ip_prefers_first_forwarded_for_entry() { fn client_ip_takes_rightmost_forwarded_for_entry() {
// The right-most entry is the hop our trusted proxy (Caddy) appended.
let mut h = HeaderMap::new(); let mut h = HeaderMap::new();
h.insert("x-forwarded-for", "203.0.113.7, 10.0.0.1".parse().unwrap()); h.insert("x-forwarded-for", "10.0.0.1, 203.0.113.7".parse().unwrap());
assert_eq!(client_ip(&h, "fallback"), "203.0.113.7");
}
#[test]
fn client_ip_ignores_spoofed_leftmost_entry() {
// A client prepending a fake IP to dodge throttles must not win.
let mut h = HeaderMap::new();
h.insert("x-forwarded-for", "1.2.3.4, 9.9.9.9, 203.0.113.7".parse().unwrap());
assert_eq!(client_ip(&h, "fallback"), "203.0.113.7"); assert_eq!(client_ip(&h, "fallback"), "203.0.113.7");
} }
@@ -151,4 +167,14 @@ mod tests {
fn client_ip_falls_back_when_header_absent() { fn client_ip_falls_back_when_header_absent() {
assert_eq!(client_ip(&HeaderMap::new(), "127.0.0.1"), "127.0.0.1"); assert_eq!(client_ip(&HeaderMap::new(), "127.0.0.1"), "127.0.0.1");
} }
#[test]
fn client_ip_falls_back_on_trailing_comma_empty_entry() {
// A trailing comma leaves an empty right-most segment after trimming; the
// `.filter(!is_empty)` must reject it and fall through to the fallback
// rather than returning "" (which would collapse callers into one bucket).
let mut h = HeaderMap::new();
h.insert("x-forwarded-for", "203.0.113.7, ".parse().unwrap());
assert_eq!(client_ip(&h, "127.0.0.1"), "127.0.0.1");
}
} }

View File

@@ -6,3 +6,8 @@ services:
db: db:
ports: ports:
- "5432:5432" - "5432:5432"
app:
# Relax the production secret guard for local dev — the dev sentinel JWT_SECRET
# is tolerated (warned) rather than rejected.
environment:
APP_ENV: development

View File

@@ -14,6 +14,10 @@ services:
interval: 5s interval: 5s
timeout: 5s timeout: 5s
retries: 10 retries: 10
deploy:
resources:
limits:
memory: 512M
app: app:
build: build:
@@ -21,6 +25,10 @@ services:
dockerfile: Dockerfile dockerfile: Dockerfile
restart: unless-stopped restart: unless-stopped
env_file: .env env_file: .env
environment:
# Activates the production secret guard in config.rs — refuses to boot with
# placeholder JWT_SECRET / ADMIN_PASSWORD_HASH.
APP_ENV: production
depends_on: depends_on:
db: db:
condition: service_healthy condition: service_healthy
@@ -28,6 +36,18 @@ services:
- media_data:/media - media_data:/media
expose: expose:
- "3000" - "3000"
healthcheck:
test: ["CMD-SHELL", "wget -q -O- http://localhost:3000/health || exit 1"]
interval: 10s
timeout: 5s
retries: 5
start_period: 20s
deploy:
resources:
limits:
# Bounds a runaway ffmpeg transcode (large uploads, 2 workers) so it can't
# OOM the single box and take down Postgres.
memory: 1G
frontend: frontend:
build: build:
@@ -35,10 +55,24 @@ services:
dockerfile: Dockerfile dockerfile: Dockerfile
restart: unless-stopped restart: unless-stopped
env_file: .env env_file: .env
environment:
# adapter-node behind Caddy TLS needs the public origin for CSRF checks on
# POST form actions — without it they fail only in production.
ORIGIN: "https://${DOMAIN}"
depends_on: depends_on:
- app - app
expose: expose:
- "3001" - "3001"
healthcheck:
test: ["CMD-SHELL", "wget -q -O- http://localhost:3001/ >/dev/null 2>&1 || exit 1"]
interval: 10s
timeout: 5s
retries: 5
start_period: 15s
deploy:
resources:
limits:
memory: 256M
caddy: caddy:
image: caddy:2-alpine image: caddy:2-alpine
@@ -50,8 +84,14 @@ services:
- ./Caddyfile:/etc/caddy/Caddyfile:ro - ./Caddyfile:/etc/caddy/Caddyfile:ro
- caddy_data:/data - caddy_data:/data
depends_on: depends_on:
- app app:
- frontend condition: service_healthy
frontend:
condition: service_healthy
deploy:
resources:
limits:
memory: 256M
volumes: volumes:
postgres_data: postgres_data:

View File

@@ -51,15 +51,25 @@ item below is tagged with its **current status in `main`**:
## ✅ Fixed in main since the audit (for the record) ## ✅ Fixed in main since the audit (for the record)
These audit findings are present in `main` today (verified 2026-06-30): event-scoped social These audit findings are present in `main` today (verified 2026-06-30): server-side MIME/ext
handlers (cross-event authz), server-side MIME/ext allowlist on upload, recovery-PIN lockout allowlist on upload, recovery-PIN lockout backoff, DB port no longer publicly exposed, bcrypt
backoff, unspoofable client IP in the rate limiter, effective JWT production-secret guard, DB port offloaded via `spawn_blocking`, bounded compression concurrency (semaphore), bounded feed queries
no longer publicly exposed, container healthchecks, bcrypt offloaded via `spawn_blocking`, (`LIMIT ≤ 100`), and the viewport-fit / reduced-motion / aria a11y pass. An image-decode
bounded compression concurrency (semaphore), bounded feed queries (`LIMIT ≤ 100`), and the decompression-bomb cap (`image::Limits` 12000×12000 / 256 MiB) lives in
viewport-fit / reduced-motion / aria a11y pass. **New since the audit:** an image-decode
decompression-bomb cap (`image::Limits` 12000×12000 / 256 MiB) ported into
`backend/src/services/compression.rs`. `backend/src/services/compression.rs`.
**Fixed in the 2026-07 review pass** (previously *claimed* fixed here but were not — corrected):
- **Effective JWT production-secret guard** — `APP_ENV=production` is now set for the app service,
and `config.rs::validate_secrets` rejects any placeholder-ish `JWT_SECRET`/`ADMIN_PASSWORD_HASH`
(not just the exact dev sentinel) and enforces `len ≥ 32` unconditionally in prod.
- **Unspoofable client IP in the rate limiter** — `client_ip` now takes the right-most
`X-Forwarded-For` entry (the hop Caddy appends), so a client-supplied left-most value is ignored.
- **Live role/ban re-check** — the auth extractor re-reads the user row and trusts the DB role and
`is_banned` flag rather than the JWT claim, revoking demoted/banned sessions immediately.
- **Container healthchecks** — `app` and `frontend` now have healthchecks and Caddy waits on
`service_healthy`.
- **Event-scoped `ban_user`** — the ban UPDATE is now scoped by `event_id` like its siblings.
## 🅲 Consciously won't-fix at ~100-guest single-box scale ## 🅲 Consciously won't-fix at ~100-guest single-box scale
Diminishing returns vs. the deployment's actual threat model. Revisit only if the scale or Diminishing returns vs. the deployment's actual threat model. Revisit only if the scale or
@@ -71,6 +81,12 @@ tenancy model changes.
- Performance micro-indexes (`idx_like_user_upload`, comment pagination index) — current queries - Performance micro-indexes (`idx_like_user_upload`, comment pagination index) — current queries
are sub-ms at this row count. are sub-ms at this row count.
- Optimistic-like in-flight guard, ownership-snapshot-at-mount, assorted copy tweaks — UX polish. - Optimistic-like in-flight guard, ownership-snapshot-at-mount, assorted copy tweaks — UX polish.
- **Mid-session ban does not tear down an already-open SSE stream.** The live-ban check lives in the
`AuthUser` extractor, but the stream authenticates via ticket→session (`handlers/sse.rs::stream`),
so a user banned while connected keeps receiving broadcast events until their stream drops. New
tickets *are* blocked (`issue_ticket` uses `AuthUser`), so they cannot reconnect. Low blast radius
(read-only feed events, no re-subscribe); tearing live streams down would need a per-session
broadcast filter. Revisit only if bans must take effect within seconds.
## By-design notes (audit branch's signed-media model — see DECISION-media-auth.md) ## By-design notes (audit branch's signed-media model — see DECISION-media-auth.md)

View File

@@ -117,6 +117,25 @@ export class ApiClient {
}); });
} }
async unbanUser(token: string, userId: string, opts: { expectedStatus?: number | number[] } = {}) {
return this.request<void>('POST', `/host/users/${userId}/unban`, {
token,
expectedStatus: opts.expectedStatus ?? [200, 204],
});
}
/** Reset another user's PIN. Returns the plaintext PIN the host must relay once. */
async resetUserPin(
token: string,
userId: string,
opts: { expectedStatus?: number | number[] } = {}
): Promise<{ status: number; body: { pin?: string } }> {
return this.request<{ pin?: string }>('POST', `/host/users/${userId}/pin-reset`, {
token,
expectedStatus: opts.expectedStatus ?? [200],
});
}
async closeEvent(token: string) { async closeEvent(token: string) {
return this.request<void>('POST', '/host/event/close', { token, expectedStatus: [200, 204] }); return this.request<void>('POST', '/host/event/close', { token, expectedStatus: [200, 204] });
} }

View File

@@ -33,4 +33,39 @@ test.describe('Host — event lock', () => {
// Currently no UI consumes the event-closed SSE on /feed. Add this banner // Currently no UI consumes the event-closed SSE on /feed. Add this banner
// and flip fixme to test once it lands. // and flip fixme to test once it lands.
}); });
// Regression for the review: likes/comments used to ignore uploads_locked_at,
// so social writes still landed on a closed event. They now share the upload
// handler's lock guard.
test('a closed event rejects likes and comments', async ({ api, host, guest }) => {
const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101';
const g = await guest('SocialLocked');
// Upload while still open so there's a target to interact with.
const { uploadRaw } = await import('../../helpers/upload-client');
const { readFileSync } = await import('node:fs');
const { join } = await import('node:path');
const sample = join(process.cwd(), 'fixtures', 'media', 'sample.jpg');
const upRes = await uploadRaw(g.jwt, readFileSync(sample), {
filename: 'x.jpg',
contentType: 'image/jpeg',
});
expect(upRes.status).toBe(201);
const { id } = await upRes.json();
await api.closeEvent(host.jwt);
const likeRes = await fetch(`${BASE}/api/v1/upload/${id}/like`, {
method: 'POST',
headers: { Authorization: `Bearer ${g.jwt}` },
});
expect(likeRes.status).toBe(403);
const commentRes = await fetch(`${BASE}/api/v1/upload/${id}/comments`, {
method: 'POST',
headers: { Authorization: `Bearer ${g.jwt}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ body: 'sollte blockiert sein' }),
});
expect(commentRes.status).toBe(403);
});
}); });

View File

@@ -45,3 +45,56 @@ test.describe('Host — moderation API', () => {
expect(row?.role).toBe('host'); expect(row?.role).toBe('host');
}); });
}); });
/**
* Regression for the review's H1: role & ban used to be trusted from the JWT and
* never re-checked against the DB, so a demoted/banned host kept full powers for
* the life of their token (up to 30d) and a banned host could even unban
* themselves. The auth extractor now re-reads the live user row, so these take
* effect on the *existing* session with no re-login.
*/
test.describe('Host — live role/ban revocation (H1)', () => {
test('a demoted host loses host powers on their existing session', async ({
api,
adminToken,
guest,
}) => {
const u = await guest('DemoteMidSession');
await api.setRole(adminToken, u.userId, 'host');
// Fresh host token (role is encoded at mint time).
const { body } = await api.recover(u.displayName, u.pin);
const hostJwt = body.jwt;
// Sanity: the token currently has host powers.
await api.listUsers(hostJwt);
// Demote via admin — the host does NOT re-login.
await api.setRole(adminToken, u.userId, 'guest');
// Same token is now rejected with exactly 403 (RequireHost sees the DB role,
// not the JWT claim). Asserting the status guards against a spurious 500
// masquerading as "revoked".
await expect(api.listUsers(hostJwt)).rejects.toThrow(/→ 403/);
});
test('a banned host is locked out immediately on their existing session', async ({
api,
adminToken,
host,
}) => {
// Sanity: host token works.
await api.listUsers(host.jwt);
await api.banUser(adminToken, host.userId, false);
// Banned users are rejected with 403 by the auth extractor before any handler runs.
await expect(api.listUsers(host.jwt)).rejects.toThrow(/→ 403/);
});
test('a banned host cannot unban themselves', async ({ api, adminToken, host }) => {
await api.banUser(adminToken, host.userId, false);
await expect(
api.unbanUser(host.jwt, host.userId, { expectedStatus: [204] })
).rejects.toThrow(/→ 403/);
});
});

View File

@@ -0,0 +1,43 @@
/**
* Regression for the review's C1: `reset_user_pin` wrote to a non-existent
* column (`pin_failed_attempts` vs the real `failed_pin_attempts`), so the
* endpoint 500'd every time and never returned a PIN — the feature had never
* worked against a real DB and no test caught it. These specs pin the contract:
* a successful reset returns a fresh 4-digit PIN, and the target can recover
* with it.
*/
import { test, expect } from '../../fixtures/test';
test.describe('Host — reset guest PIN (C1)', () => {
test('resetting a guest PIN returns a fresh 4-digit PIN', async ({ api, host, guest }) => {
const target = await guest('ResetMe');
const { status, body } = await api.resetUserPin(host.jwt, target.userId);
expect(status).toBe(200);
expect(body.pin).toMatch(/^\d{4}$/);
});
test('the target can recover with the newly reset PIN (and not the old one)', async ({
api,
host,
guest,
}) => {
const target = await guest('RecoverWithNewPin');
const { body } = await api.resetUserPin(host.jwt, target.userId);
const newPin = body.pin!;
// New PIN works.
await api.recover(target.displayName, newPin, { expectedStatus: [200] });
// Old PIN no longer works (overwritten). 401 = wrong PIN.
if (target.pin !== newPin) {
await api.recover(target.displayName, target.pin, { expectedStatus: [401] });
}
});
test('a host cannot reset their own PIN via this endpoint', async ({ api, host }) => {
await api.resetUserPin(host.jwt, host.userId, { expectedStatus: [400] });
});
});

View File

@@ -21,7 +21,10 @@
theme=dark don't flash a white screen. Mirrors the logic in theme=dark don't flash a white screen. Mirrors the logic in
`src/lib/theme-store.ts`; kept in sync by hand (it's 6 lines). `src/lib/theme-store.ts`; kept in sync by hand (it's 6 lines).
--> -->
<script> <!-- nonce is required: our CSP sets script-src 'self', and SvelteKit's
mode:'auto' only hashes scripts *it* injects, not this template-authored
one. %sveltekit.nonce% is substituted per request and added to the CSP. -->
<script nonce="%sveltekit.nonce%">
(function () { (function () {
try { try {
var pref = localStorage.getItem('eventsnap_theme') || 'system'; var pref = localStorage.getItem('eventsnap_theme') || 'system';

View File

@@ -0,0 +1,29 @@
// Make everything *outside* a modal's subtree inert while it's open, so screen
// readers and tab order can't reach the background (focus-trap only covers
// keyboard focus; `inert` also hides the content from assistive tech).
//
// Walks from the node up to <body> and marks every sibling along the path as
// inert, then restores exactly those it changed on teardown. Applying it to a
// `display: contents` wrapper keeps the modal's own backdrop + dialog interactive.
export function modalInert(node: HTMLElement) {
const changed: HTMLElement[] = [];
let el: HTMLElement | null = node;
while (el && el !== document.body) {
const parent: HTMLElement | null = el.parentElement;
if (!parent) break;
for (const sib of Array.from(parent.children)) {
if (sib !== el && sib instanceof HTMLElement && !sib.hasAttribute('inert')) {
sib.setAttribute('inert', '');
changed.push(sib);
}
}
el = parent;
}
return {
destroy() {
for (const sib of changed) sib.removeAttribute('inert');
}
};
}

View File

@@ -7,6 +7,7 @@
import { doubletap } from '$lib/actions/doubletap'; import { doubletap } from '$lib/actions/doubletap';
import { focusTrap } from '$lib/actions/focus-trap'; import { focusTrap } from '$lib/actions/focus-trap';
import { scrollLock } from '$lib/actions/scroll-lock'; import { scrollLock } from '$lib/actions/scroll-lock';
import { modalInert } from '$lib/actions/modal-inert';
import { toastError } from '$lib/toast-store'; import { toastError } from '$lib/toast-store';
import { vibrate } from '$lib/haptics'; import { vibrate } from '$lib/haptics';
import HeartBurst from './HeartBurst.svelte'; import HeartBurst from './HeartBurst.svelte';
@@ -51,13 +52,19 @@
if (burstTimer) clearTimeout(burstTimer); if (burstTimer) clearTimeout(burstTimer);
}); });
// Only refetch when a *different* upload is shown. The feed reassigns the
// `upload` prop object on every SSE like/comment count update; keying the
// effect off the memoized id avoids a refetch storm that would also clobber
// a just-posted optimistic comment.
const uploadId = $derived(upload.id);
$effect(() => { $effect(() => {
loadComments(); loadComments(uploadId);
}); });
async function loadComments() { async function loadComments(id: string) {
try { try {
comments = await api.get<CommentDto[]>(`/upload/${upload.id}/comments`); comments = await api.get<CommentDto[]>(`/upload/${id}/comments`);
} catch { } catch {
// Background fetch — failure leaves the panel empty; reopening the lightbox retries. // Background fetch — failure leaves the panel empty; reopening the lightbox retries.
} }
@@ -106,6 +113,7 @@
aria-labelledby="lightbox-title" aria-labelledby="lightbox-title"
use:focusTrap={{ onclose }} use:focusTrap={{ onclose }}
use:scrollLock use:scrollLock
use:modalInert
> >
<div class="flex max-h-[90vh] w-full max-w-2xl flex-col overflow-hidden rounded-xl bg-white dark:bg-gray-900"> <div class="flex max-h-[90vh] w-full max-w-2xl flex-col overflow-hidden rounded-xl bg-white dark:bg-gray-900">
<!-- Media --> <!-- Media -->

View File

@@ -1,6 +1,7 @@
<script lang="ts"> <script lang="ts">
import { focusTrap } from '$lib/actions/focus-trap'; import { focusTrap } from '$lib/actions/focus-trap';
import { scrollLock } from '$lib/actions/scroll-lock'; import { scrollLock } from '$lib/actions/scroll-lock';
import { modalInert } from '$lib/actions/modal-inert';
import type { Snippet } from 'svelte'; import type { Snippet } from 'svelte';
// Accessible name is REQUIRED. Pass `titleId` when the dialog renders its own // Accessible name is REQUIRED. Pass `titleId` when the dialog renders its own
@@ -35,24 +36,29 @@
</script> </script>
{#if open} {#if open}
<button <!-- display:contents wrapper: keeps the backdrop + dialog visually unchanged
type="button" while giving `modalInert` a single node whose siblings (the background
class="fixed inset-0 z-50 bg-black/50" page, nav, etc.) get inerted for assistive tech. -->
aria-label="Schließen" <div class="contents" use:modalInert>
tabindex="-1" <button
onclick={closeOnBackdrop ? onClose : () => {}} type="button"
></button> class="fixed inset-0 z-50 bg-black/50"
<div aria-label="Schließen"
class="pointer-events-none fixed inset-0 z-50 flex items-center justify-center p-4" tabindex="-1"
role="dialog" onclick={closeOnBackdrop ? onClose : () => {}}
aria-modal="true" ></button>
aria-labelledby={titleId} <div
aria-label={titleId ? undefined : ariaLabel} class="pointer-events-none fixed inset-0 z-50 flex items-center justify-center p-4"
use:focusTrap={{ onclose: onClose }} role="dialog"
use:scrollLock aria-modal="true"
> aria-labelledby={titleId}
<div class="pointer-events-auto w-full max-w-sm rounded-2xl bg-white p-6 shadow-xl dark:bg-gray-900"> aria-label={titleId ? undefined : ariaLabel}
{@render children()} use:focusTrap={{ onclose: onClose }}
use:scrollLock
>
<div class="pointer-events-auto w-full max-w-sm rounded-2xl bg-white p-6 shadow-xl dark:bg-gray-900">
{@render children()}
</div>
</div> </div>
</div> </div>
{/if} {/if}

View File

@@ -7,9 +7,11 @@
src: string; src: string;
isVideo: boolean; isVideo: boolean;
durationMs: number; durationMs: number;
/** Fired when a video slide finishes so the parent can advance early. */
onended?: () => void;
} }
let { src, isVideo, durationMs }: Props = $props(); let { src, isVideo, durationMs, onended }: Props = $props();
</script> </script>
<div <div
@@ -23,6 +25,7 @@
autoplay autoplay
muted muted
playsinline playsinline
{onended}
class="h-full w-full object-contain" class="h-full w-full object-contain"
></video> ></video>
{:else} {:else}

View File

@@ -25,6 +25,8 @@ export interface TransitionProps {
src: string; src: string;
isVideo: boolean; isVideo: boolean;
durationMs: number; durationMs: number;
/** Fired when a video slide finishes so the parent can advance early. */
onended?: () => void;
} }
export const transitions: SlideTransition[] = [ export const transitions: SlideTransition[] = [

View File

@@ -6,9 +6,11 @@
src: string; src: string;
isVideo: boolean; isVideo: boolean;
durationMs: number; durationMs: number;
/** Fired when a video slide finishes so the parent can advance early. */
onended?: () => void;
} }
let { src, isVideo, durationMs }: Props = $props(); let { src, isVideo, durationMs, onended }: Props = $props();
// Mild random pan so each slide feels different. Range chosen so the image never // Mild random pan so each slide feels different. Range chosen so the image never
// pans out of frame given the object-fit: cover. // pans out of frame given the object-fit: cover.
@@ -27,6 +29,7 @@
autoplay autoplay
muted muted
playsinline playsinline
{onended}
class="h-full w-full object-contain" class="h-full w-full object-contain"
></video> ></video>
{:else} {:else}

View File

@@ -174,15 +174,31 @@ async function deltaFetchAndFan(since: string): Promise<void> {
// Page Visibility API: close while hidden, reopen on focus. On reopen `connectSse`'s // Page Visibility API: close while hidden, reopen on focus. On reopen `connectSse`'s
// `onopen` runs the delta fetch. // `onopen` runs the delta fetch.
if (typeof document !== 'undefined') { function handleVisibilityChange() {
document.addEventListener('visibilitychange', () => { if (document.hidden) {
if (document.hidden) { disconnectSse();
disconnectSse(); } else {
} else { // User-initiated reconnect — clear backoff so we don't wait out a long
// User-initiated reconnect — clear backoff so we don't wait out a long // retry delay that was scheduled from a prior background error.
// retry delay that was scheduled from a prior background error. reconnectAttempt = 0;
reconnectAttempt = 0; connectSse();
connectSse(); }
}
});
} }
let visibilityBound = false;
/** Idempotent: safe to call more than once; only the first registration sticks. */
function bindVisibility() {
if (visibilityBound || typeof document === 'undefined') return;
document.addEventListener('visibilitychange', handleVisibilityChange);
visibilityBound = true;
}
/** Remove the visibility listener (e.g. on teardown / test cleanup). */
export function teardownVisibility() {
if (!visibilityBound || typeof document === 'undefined') return;
document.removeEventListener('visibilitychange', handleVisibilityChange);
visibilityBound = false;
}
bindVisibility();

View File

@@ -27,6 +27,9 @@ export interface FeedResponse {
export interface DeltaResponse { export interface DeltaResponse {
uploads: FeedUpload[]; uploads: FeedUpload[];
deleted_ids: string[]; deleted_ids: string[];
// True when the delta hit the backend cap and is only the newest slice of the
// gap — the client must full-refresh rather than merge (see feed-delta handler).
truncated: boolean;
} }
// mirrors backend/src/handlers/feed.rs::HashtagCount // mirrors backend/src/handlers/feed.rs::HashtagCount

View File

@@ -52,6 +52,13 @@
if (current) scheduleNext(); if (current) scheduleNext();
} }
// A video finished before its dwell/12s cap — advance immediately (unless paused).
// The {#key current.id} block destroys the old <video> on advance, so a fallback
// timer that already fired can't trigger this handler for a stale slide.
function handleVideoEnded() {
if (!paused) advance();
}
async function loadInitial() { async function loadInitial() {
try { try {
const feed = await api.get<FeedResponse>('/feed?limit=200'); const feed = await api.get<FeedResponse>('/feed?limit=200');
@@ -163,6 +170,7 @@
src={mediaSrc} src={mediaSrc}
{isVideo} {isVideo}
durationMs={transitionDef.defaultDurationMs} durationMs={transitionDef.defaultDurationMs}
onended={handleVideoEnded}
/> />
{/key} {/key}
{:else if isEmpty()} {:else if isEmpty()}

View File

@@ -206,6 +206,13 @@
onSseEvent('feed-delta', (data) => { onSseEvent('feed-delta', (data) => {
try { try {
const delta = JSON.parse(data) as DeltaResponse; const delta = JSON.parse(data) as DeltaResponse;
if (delta.truncated) {
// Missed more than the backend delta cap while backgrounded — the
// delta is only the newest slice, so merging would leave a silent gap
// of older-but-still-new uploads. Resync from page 1 instead.
void loadFeed(true);
return;
}
if (delta.uploads.length) { if (delta.uploads.length) {
const seen = new Set(uploads.map((u) => u.id)); const seen = new Set(uploads.map((u) => u.id));
const fresh = delta.uploads.filter((u) => !seen.has(u.id)); const fresh = delta.uploads.filter((u) => !seen.has(u.id));

View File

@@ -6,7 +6,28 @@ const config = {
runes: true runes: true
}, },
kit: { kit: {
adapter: adapter() adapter: adapter(),
// Content-Security-Policy — the highest-value header for this UGC app and the
// cheapest hardening of the localStorage-based auth (the whole model rests on
// never having an XSS). `mode: 'auto'` lets SvelteKit nonce/hash its own inline
// hydration script, so script-src stays free of 'unsafe-inline'.
csp: {
mode: 'auto',
directives: {
'default-src': ['self'],
'script-src': ['self'],
// Svelte emits inline style attributes (style: directives); allow them.
'style-src': ['self', 'unsafe-inline'],
'img-src': ['self', 'data:', 'blob:'],
'media-src': ['self', 'blob:'],
'font-src': ['self'],
'connect-src': ['self'],
'object-src': ['none'],
'base-uri': ['self'],
'form-action': ['self'],
'frame-ancestors': ['none']
}
}
} }
}; };