10 Quality Requirements

Quality Tree

Quality
├── Performance
│   ├── NFR-P1: Message latency ≤500ms under Silver load (500 concurrent/m5.large)
│   ├── NFR-P2: /sync response ≤1s under normal load
│   ├── NFR-P3: Silver-tier (>500 concurrent), Gold (>1000), Platinum (>5000) without Redis/NATS
│   ├── NFR-P4: Server cold-start ≤5s (single BEAM node; ADR-019/021 — no separate Gateway process)
│   └── NFR-P5: Media download-stall (`?timeout_ms`, Story 2d) is event-driven via Phoenix.PubSub —
│               a single deadline-bounded `receive/after`, never a sleep-and-poll loop — bounded by a
│               crash-safe global concurrency ceiling (`max_concurrent_stalls`, default 500 simultaneous
│               stalls; graceful degrade to the immediate no-stall response when exceeded, never an error)
├── Security
│   ├── NFR-S1: All external connections TLS 1.2+ (1.3 preferred)
│   ├── NFR-S2: Sensitive PII encrypted at rest (X25519 key)
│   ├── NFR-S3: Audit log append-only + Ed25519-signed
│   ├── NFR-S4: OIDC token validation on every API request
│   ├── NFR-S5: Ed25519 key deletion is irreversible (GDPR compliance)
│   └── NFR-S6: Bootstrap mode disables permanently after first admin setup
├── Scalability
│   ├── NFR-SC1: (Historical, superseded by NFR-SC2 — the stateless Go Gateway this
│   │            requirement targeted was removed, ADR-021/full-elixir-stack)
│   ├── NFR-SC2: Elixir/OTP Server supports cluster operation (Phase 2: libcluster)
│   └── NFR-SC3: No external middleware layer required (PostgreSQL only)
├── Reliability
│   ├── NFR-R1: OTP process isolation (Room crash → only that room affected)
│   ├── NFR-R2: No data loss on server restart (PostgreSQL is source of truth)
│   └── NFR-R3: Rolling updates without full downtime
├── Operability
│   ├── NFR-O1: Full deployment via docker compose up in ≤10 minutes
│   ├── NFR-O2: Health/readiness endpoints respond ≤200ms under load
│   ├── NFR-O3: Admin UI fully embedded in the Nebu server (no external deps; ADR-020/021 —
│   │           no separate Go-template admin binary)
│   └── NFR-O4: All Admin UI states reproducible via URL
├── Compliance
│   ├── NFR-C1: GDPR Right-to-be-forgotten via cryptographic key deletion
│   ├── NFR-C2: Audit log retention configurable (default: 7 years)
│   ├── NFR-C3: All runtime data (events, users, audit log) in operator-controlled PostgreSQL (on-premise capable)
│   ├── NFR-C4: Media binary data in S3-compatible object store (MinIO) as static file repository; credentials
│   │           field-encrypted, never plaintext-logged; storage-key schema immutable (ADR); PostgreSQL holds
│   │           metadata (state, hash, uploader, timestamps) + compliance records (hard-deleted rows retain
│   │           hash/timestamps, storage_key/uploader nulled)
│   └── NFR-C5: Media state transitions append-only (media_state_transitions ledger); DB-level immutability via
│           `BEFORE UPDATE OR DELETE` trigger + RLS (ADR-031, Story 1a); authoritative enforcement independent
│           of application code, valid for scanner/admin/raw-SQL/migration attack surfaces
├── Matrix Protocol Conformance
│   ├── NFR-M1: Compatible with Element, FluffyChat, Hydrogen (incompatibilities = bugs)
│   ├── NFR-M2: OIDC integration via m.login.sso per Matrix OIDC Specification
│   ├── NFR-M3: Element Web browser-first E2E suite (playwright-bdd) validates login,
│   │          room create/join/leave, and message send/receive via real browser flows
│   ├── NFR-M4: POST /_matrix/client/v3/search returns only results from rooms the
│   │          requesting user is a member of (no cross-room leakage)
│   └── NFR-M5: Search results never include messages from encrypted rooms
│              (m.room.encryption state event present → room excluded from FTS results)
├── Accessibility
│   ├── NFR-A1: Admin UI WCAG 2.1 Level AA
│   ├── NFR-A2: Admin UI fully keyboard navigable
│   └── NFR-A3: Admin UI usable with screen readers (semantic HTML, ARIA)
└── Crypto Agility
    └── NFR-CR1: Cryptographic primitives modularized (replaceable without core refactor)

Performance Scenarios

ScenarioStimulusResponseMeasure
Silver-tier load500 concurrent users (60% sync, 20% send, 10% presence/typing, 5% room ops)≤500ms message latencyLoadtest on 2x AWS m5.large
Server restartSIGTERM / docker restart serverHTTP traffic resumes, events resume delivery, no cold-sync≤5s cold start; recovery via ETS + PostgreSQL checkpoint
Full-text searchPOST /search with keyword query across user's roomsGIN index hit, no seq-scan≤500ms at Silver load; scope enforced via room membership filter
Media download-stall wait (Story 2d)Client requests /download or /thumbnail (with ?timeout_ms=N, or none = default window) while media is :quarantined/:scanningEvent-driven Phoenix.PubSub wait resolves immediately on a terminal-state broadcast, or falls back to the unchanged 1c deny/success mapping at the clamped deadline — never busy-polls media_files on an intervalStory 2d Acceptance Tests 1–4: released/deny broadcasts resolve well before the requested window (bounded wall-clock assertion, e.g. <1s of a 5–20s window); no-broadcast case falls back at ~clamped ms, not instantly and not at the unclamped N; global :atomics ceiling (default 500) degrades gracefully to the immediate no-stall response when exceeded, never an error

Security Scenarios

ScenarioConcernResponse
Compromised tokenJWT stolenShort-lived OIDC token + deactivation endpoint invalidates all sessions
GDPR deletion requestUser wants data removedDelete private keys → all sensitive PII irrecoverable (audit log intact)
Compliance audit requestLegal request for message contentFour-eyes approval + 24h session limit + signed export
Search cross-room IDORCaller-supplied user_id bypasses membership filterNebu.Search.DB.search_messages/4 user_id parameter MUST come from validated session (gRPC metadata / JWT claim); Story 11.3 SearchMessages handler enforces this invariant; SQL-layer subquery on room_members WHERE left_at IS NULL prevents leakage even if called with a foreign user_id
Search on encrypted roomsCiphertext bodies returned in plaintext search responseNebu.Search.DB excludes rooms with m.room.encryption state event via NOT EXISTS subquery; no application-layer bypass possible (enforced in SQL, NFR-M5)
Media state rewritten silentlyDirect SQL UPDATE/DELETE on media_files.state or media_state_transitions bypasses guard logic + audit trailNebu.Media.StateMachine (Story 1b) is sole state-mutation code path (application layer); DB-level BEFORE UPDATE OR DELETE trigger on media_state_transitions raises SQLSTATE 23001 unconditionally, blocks raw SQL/migrations/psql (ADR-031); RLS + REVOKE secondarily (NFR-C5); grep invariant first-line defense catches Elixir source violations in code review
Sync upload bypasses quarantine/scan/gate entirelyPUT /_matrix/media/v3/upload (pre-existing sync path) has its own separate row-creation code path (Nebu.Media.DB.insert/1, inline encryption, direct storage write) independent of the state machine and quarantine gate; a sync-uploaded file lands in :released state by default and is immediately downloadable/servable without going through ClamAV scan or any state-machine governanceStory 2c closes this gap (2026-07-14): sync upload refactored to create rows via Nebu.Media.StateMachine.create_quarantined/1 (new genesis function, AC1) and to call the identical encrypt_compress_and_store/5 shared function that async PUT already uses for all crypto/compression/storage work (AC2). Result: both sync and async uploads land in :quarantined state and enqueue the same Oban scan job (Story 4b wiring); the only difference is sync never passes through :reserved (bytes present at request time). External API contract unchanged (AC3) — byte-for-byte same response/error codes, no client-side changes. All ATDD tests green (1800-test unit suite, 226-test live-Postgres integration suite with StateMachine.create_quarantined/1 verified against real DB). Security review (Kassandra, Story 2c): CLEAN, 0 CRITICAL/HIGH, 4 INFO; this refactor CLOSES a real pre-existing security gap (test-proven: sync uploads landed in :released by default and were downloadable before the shared-pipeline closure).
Media file infected but released to usersMalware-infected file served if scanner malfunctions or is bypassedState machine enforces infected→released is terminal (no forward edge exists); only media_admin_override role + documented reason can release; all transitions audit-logged; Nebu.Workers.MediaScanWorker (Story 4b, landed) is the sole caller that drives quarantined/scanning → released, and only after a genuine {:ok, :clean} (or size-skip) result from Nebu.Media.ClamAV.scan_binary/1 — there is no code path that reaches :released from :quarantined/:scanning without going through a real scan outcome first
Media download/thumbnail bypass via state checkNon-released file (scanning, quarantined, infected, deleted, admin-blocked) served to clientNebu.Media.download_gate/1 (Story 1c) is the single HTTP-layer enforcement point (ADR-026); runs before storage/decrypt, before membership check; explicit allow-list (only :released → serve); catch-all-deny (everything else → 451 or 404) via download_gate(_other) → {451, "M_NOT_YET_UPLOADED"}; never a catch-all-allow. Shared helper placement ensures both /_matrix/media/v3/download and /thumbnail routes enforce identically with zero duplicated logic. RESOLVED 2026-07-19 (Story 6a security review): the architectural tension flagged in Story 1c's own review (ADR-026 table mapped :admin_blocked → 451 status while its prose/AC2 claimed "indistinguishable from a file that never existed" — the 451 status was itself a distinguishing oracle, F-1 MEDIUM) went live exactly as predicted the moment Story 6a shipped the first real admin-block trigger. Fixed: download_gate(:admin_blocked) now returns {404, "M_NOT_FOUND"}, byte-identical status AND body to :infected/:deleted/:hard_deleted. See ADR-026's 2026-07-19 correction and the dedicated 6a security-scenario row below.
media_state ENUM gains a 9th value (:scan_failed) — does the download-gate catch-all still fail closed against a LIVE value, or only a test fixture?Story 1c's download_gate/1 catch-all was designed to deny any unrecognized/future state (AC6), but its own test suite only ever exercised :scan_failed as a bare Elixir atom fixture, never against a genuinely committed ENUM value — a latent gap between "the code should handle this" and "it's been proven to." Story 4a (media-security-admin-control epic) adds :scan_failed for real: migration 000028_media_scan_failed_state (renumbered from the story's stale 000023 reference — 5 sibling stories claimed 000023-000027 first, no security implication) plus 6 new Nebu.Media.StateMachine guard-table edges (quarantined/scanning → scan_failed; scan_failed → scanning/released/admin_blocked/deleted — not terminal, since a scan failure means "unknown," not "known-bad").Kassandra security review (Story 4a): APPROVED, 0 CRITICAL/HIGH/MEDIUM/LOW. New regression test seeds a REAL Nebu.Repo-backed media_files row with state = 'scan_failed' (not a bare atom) and proves download_gate/1/parse_state/1 need zero code change — the catch-all denies with 451 M_NOT_YET_UPLOADED exactly as designed, closing the gap between "designed to" and "proven to." Also confirmed: a mixed-version rolling deploy (migration applied, an old pre-4a app node reads the row) still fails closed, because parse_state/1's String.to_existing_atom rescue triggers on a node that never interned the atom, falling back to the sentinel → same catch-all deny. Only @type state/@transitions changed in state_machine.ex — the transition mechanism itself untouched. No new HTTP endpoint/caller; the guard-table edges were latent capability until Story 4b's MediaScanWorker landed as the first real writer of scan_failed (see the dedicated 4b security-scenario row below).
ClamAV response causes unbounded memory growthMalicious or buggy clamd sends an excessive response, consuming all server memoryNebu.Media.ClamAV (Story 3) caps the reply-read accumulator at 64 KB (F-1 security finding, fixed in dev); clamd output is treated as adversarial since it processes attacker-controlled files. Reply buffer bounded in :gen_tcp.recv/3 loop; exceeding 64 KB returns {:error, :reply_too_large} without accepting further bytes.
ClamAV service exposed to host networkUnauthenticated clamd control-plane service (no authentication layer) reachable from host, enabling remote arbitrary scan commands or denial-of-servicedocker-compose.yml omits host port publish on the clamav service (F-4 security finding, per Kassandra security review); server reaches clamd only via the compose internal network by service name (:tcp, "clamav", 3310). No host-level access available to attackers on the host or internet.
MIME-type policy upload rejection misconfigured (bypass via case mismatch)Admin-configured denylist prefixes are stored case-as-entered in media_config (e.g. "Application/Zip"); incoming Content-Type headers are resolved case-sensitively (RFC 7231 header-field names are case-insensitive, but header-field values like MIME types are case-sensitive per RFC 2045/6838); a match attempt using case-sensitive String.starts_with?/2 could silently fail — admin enters Application/Zip, file arrives as application/zip, no rejection occurs, policy becomes a no-op with no audit signalNebu.Media.mime_denylist_rejected?/1 (Story 9c) lowercases each parsed prefix (after trimming, via parse_mime_denylist/1) before matching; admin-entered config values are never normalized at storage time (that would break RFC 2045/6838 round-trip semantics), only at this function's own read site. Normalized and un-normalized values both audit-logged on config write, so any case-mismatch logic error is traceable. The Content-Type value remains case-sensitive per the story's explicit Technical Requirements (matching the pre-existing @blocked_upload_types check in upload/1 for consistency), backed by the assumption that callers always pre-normalize via base_content_type/1/base_type/1's own String.downcase() before calling this function — NOT via Plug, which lowercases HTTP header field names only, never header values (documented explicitly in the function's @doc to correct this exact misconception; this function itself does not add a second normalization step, per the story's directive). Kassandra security review MEDIUM-1b (fixed in same cycle).
S3 key template path escaping attack via malicious placeholder nestingAdmin (or under-scoped attacker with write to media_storage_config) sets s3_key_prefix_template to a value containing path-escaping segments (.., leading /) or literal double-slashes (//), attempting to place uploaded files outside the intended bucket namespace (e.g., ../../etc/passwd or //etc/passwd to escape hierarchy). Naive template validators that strip placeholder tokens and check the concatenated skeleton will collapse separators-between-placeholders into false // detections, rejecting valid hierarchical templates like {year}/{month}/{media_id} (MAJOR regression, fixed in Cycle 1).Nebu.Media.StorageConfig.validate_template/1 (Story 11c) uses Regex.split(~r/\{[^{}]*\}/, template) to split the template on placeholder spans, then checks each resulting literal SEGMENT in isolation: first segment checked for leading / (e.g. "/{media_id}" or /etc/); every segment checked for .. (path traversal); every segment checked for literal // (double-slash). This per-segment validation avoids the false-positive // detection between adjacent placeholders while correctly rejecting genuine path-escaping. Validation runs at upsert/1 time (config-save), so template interpolation at upload time (Story 2b) never encounters invalid templates. Cycle 1 fix included regression tests asserting hierarchical multi-placeholder templates like {year}/{month}/{day}/{server_name}/{media_id} and the User Story example {year}/{month}/{server_name}/{media_id} both pass validation (previously failed due to MAJOR-1 bug).
New migration table missing GRANT to runtime role (production fail-open)Migration creates a table with RLS but omits the explicit GRANT DML TO nebu_app, causing production (where nebu_migrate owns tables, no default-privilege fallback) to fail silently: permission-denied on reads/writes falls back to empty defaults, bypassing security-relevant cache (MIME denylist, upload/scan size limits) for a worst-case "fail-open" postureStory 9a (media_config migration) + every subsequent table-adding story now requires: (a) explicit GRANT SELECT, INSERT, UPDATE, DELETE ON <table> TO nebu_app in the .up.sql migration, and (b) a corresponding describe block in Nebu.Matrix.MigrationsGrantTest asserting the GRANT exists and the table has no SERIAL columns (which would require SEQUENCE grants). Every new table-adding story (9b, 9c, 10c, 10d, 11a, etc.) verifies this pattern to prevent regression.
Admin-editable media policy values can neutralize downstream security controlsA fully-authenticated instance admin sets max_file_size_bytes to an extreme-but-in-bounds value (e.g. near the controller's own {1, 5_368_709_120} floor) via /admin/media/settings, causing ClamAV to skip scanning nearly every uploaded file — functionally disabling malware scanning cluster-wide without touching config.exs or redeployingAccepted admin-trust-boundary risk (Story 9b security review, LOW, not a vulnerability): the actor already holds instance-admin privilege and could achieve the identical effect via a config.exs redeploy; no new privilege is created, only convenience. Every Nebu.Media.Config.upsert/3 call unconditionally writes a media_config_updated audit-log entry naming the admin and the old/new value (AC6) — self-disablement is never silent. Nebu.Admin.MediaSettingsController.actor_id/1 sources the audit actor from the admin's session-derived, server-verified identity, never a client-suppliable value.
Storage-target config (Nebu.Media.StorageConfig) is wired (story media-storage-uses-admin-config): an admin-set endpoint is an SSRF/transport-downgrade sink for every media requestSince story media-storage-uses-admin-config Nebu.Media.Storage resolves endpoint, region, credentials and buckets from this module at every call (request_target/0), so the saved target receives all real uploads, downloads, deletes and archive copies, signed with the saved credentials. An admin-set (or under-scoped-write) endpoint could point at internal infra, use_ssl: false sends the credentials over plaintext HTTP, and the host is resolved per request (DNS rebinding after the save). Story 11a stored these values with zero validationKassandra security review (Story 11a): APPROVED — CLEAN, 0 CRITICAL/HIGH, 1 MEDIUM + 3 LOW, all forward-looking at the time (the module had no production caller then; it is wired now, see below). Secrets themselves are sound: access_key/secret_key encrypted at rest via Nebu.Web.SecretBox (reused — not a fourth AES call site), decrypted only in the caller's process (the supervised GenServer's ETS/state never caches plaintext), masked on every get/0 read ("••••" <> last 4 chars), audit-logged (media_storage_config_updated) by field name only, never by value. Story 11b (storage-ui-test-connection) IMPLEMENTS the first carry-forward item: StorageConfig.test_connection/1 rejects any candidate endpoint carrying an http:///https:// scheme prefix before issuing any request ({:error, :invalid_endpoint}), enforcing the bare-hostname contract that runtime.exs and this module's env-var reader expect — a proportionate SSRF/transport-downgrade guard at the admission gate. State of the MUST-VERIFY items now that the module is wired (story media-storage-uses-admin-config): (1) private-IP rejection at save: DONE for endpoint (and iam_endpoint / sts_endpoint): upsert/2 runs the shared Nebu.Media.SSRF.checked_target/1 before any write (M-3 fix, opt-in NEBU_STORAGE_ALLOW_PRIVATE_ENDPOINTS for private storage networks), and the save uses the same host[:port] parser as Test Connection and the operational path. (2) use_ssl=true enforcement: NOT enforced, by design (a plain-HTTP MinIO inside the compose network is valid); the credentials of a plain-HTTP target travel unencrypted, so the Admin form is the only place to choose it; the credentials are bound to the saved endpoint (a saved endpoint is never used with the NEBU_MEDIA_STORAGE_* credentials unless it is exactly the environment's own endpoint and Use SSL, and a save that changes endpoint or use_ssl must carry both keys; exactly one key is never saved). (3) operational calls are NOT SSRF-pinned: the check runs at save time only; the per-request host resolution leaves a DNS-rebinding window after the save and rows saved before the M-3 validation were never checked (residual ds, see 11-risks.md; Test Connection stays pinned). (same class of gap already flagged for admin-configured webhook/OIDC/SCIM URLs).
Scan pipeline health (ClamAV, backlog, signature freshness, failure rate) degrades silently, no admin visibility of a building incident until manually checking the dashboardWithout operational monitoring, a ClamAV daemon crash, or a slow accumulation of unscanned backlog, or a signing-tool lag could go unnoticed for hours — the incident latency is entirely operator-dependent ("how often do they check /admin/media/health"). AC1: a new media_alerts table opens when four operator-tunable thresholds cross: clamav_down_alert_minutes (5 min default, critical severity), signature_stale_alert_hours (48h default, warning), backlog_depth_alert_threshold (500 default, warning), scan_failed_rate_alert_pct (10% default, warning). AC2/AC3: a per-minute Oban cron Nebu.Workers.MediaAlertsCheckerWorker evaluates all four independently and auto-resolves (sets resolved_at) the moment the condition clears, with zero admin-dismissal action needed. AC4: the /admin/media/health dashboard renders all open alerts (Nebu.Media.Alerts.list_open/0) at the top in critical-first, most-recent-first order, with accessible severity labels ("Kritisch:"/"Warnung:") + DaisyUI classes. Kassandra security review (Story 10c): CLEAN, 0 CRITICAL/HIGH/MEDIUM/LOW. Idempotency verified: two concurrent perform_job/3 calls against the real Nebu.Repo with the same active condition leave exactly one open row, verified by the partial-unique index + ON CONFLICT ... DO NOTHING clause. No new audit actions (opening/resolving alerts is system-internal monitoring, not an audit-log event per Dev Agent Guardrails — this is not compliance data like media_state_transitions, and alerts have no manual admin dismiss path), no new admin/UI grant needed (read-only dashboard render), no new config keys added (all four thresholds are Nebu.Media.Config keys, pre-existing write-audit infrastructure reused).
Async upload reservation (POST /_matrix/media/v1/create) accountability and rate-limit integrityStory 2a (media-security-admin-control epic) introduces the async-upload reservation endpoint that creates :reserved rows without accepting file bytes. Identity tracking for "who reserved media_id X" must be discoverable for compliance/support audits. Pending-upload counting must be accurate for AC3's 429 rate-limit enforcement. Actor-type design: the OIDC-authenticated caller is neither a :system (scanner/automatic) nor an :admin (manual human intervention), yet media_state_transitions' actor_type ENUM only has two values.Kassandra security review (Story 2a): APPROVED, 0 CRITICAL/HIGH/MEDIUM. Architectural decision (actor-ledger narrowing): uploader identity is tracked via the pre-existing media_files.uploader_user_id column (set to the caller's MXID on genesis INSERT, reused for Story 2b's ownership checks), NOT via media_state_transitions.actor_id. The genesis row's actor_type: 'system', actor_id: NULL is semantically consistent with existing usage: actor_id: NULL is already legal for scanner transitions (Story 1b) and means "no human actor in the loop." This design keeps the audit ledger's actor contract narrow (two-valued system
Media scan-pipeline incident investigation — Trace-Map/War-Room integration with operational observabilityAn operator investigating a media-scan incident (ClamAV outage, infected file discovery, scan-error spike) must correlate events across multiple systems: ClamAV health-check logs, MediaScanWorker job lifecycle, and admin override actions (block/unblock/delete/rescan/infected-override). Without integrated observability, the operator must manually grep container logs or build a second, parallel observability surface just for media.Story 10e (trace-map-war-room-integration) IMPLEMENTS this scenario: (a) ClamAV connect/disconnect/health-check-transition log calls now carry route_template: "/media/clamav" metadata (Logger.info/2 for healthy transitions, Logger.warning/2 for unreachable); (b) MediaScanWorker scan-start/result/error log calls now carry route_template: "/media/scan_worker" and request_id: media_id (Logger.info/2 for routine paths, Logger.warning/2 for infected/error); (c) MediaLive admin action handlers (block/unblock/delete/rescan/infected-override) additionally log with route_template: "/admin/media" and request_id: media_id, alongside the existing AuditWriter call — a second, independent operational-visibility channel. All three log streams feed into the pre-existing Nebu.Web.LogStore system, grouped by domain (/media domain, /admin domain) and by request_id (media_id), so a file's entire lifecycle (upload → scan → admin action) appears as one grouped row in the Trace-Map /admin/logs/trace-map visualization. (d) WarRoom.scope_matches?/2 extended to accept a LIST of route templates (OR-matched), enabling scoping a War Room session to an entire domain: ["/media/clamav", "/media/scan_worker", "/admin/media"]. (e) /admin/media/health dashboard's new "Live-Diagnose starten" action on unresolved CRITICAL alerts starts a War Room session scoped to the media domain and redirects to the existing /admin/logs?war_room_id=... bookmarkable pattern — a one-click jump from alert → bounded diagnostic session. Redaction unchanged: metadata carries only identifiers (media_id, clamav_signature, reason), never content/filename/bytes, matching the pre-existing user_id/device_id precedent. No new tables/migrations; operational_logs.war_room_id column and route-domain grouping already exist from the enhanced-logging epic. Security review (Kassandra): CLEAN, 0 CRITICAL/HIGH/MEDIUM, 2 LOW non-blocking.

| Media download-stall (?timeout_ms, Story 2d) turns a promptly-answered endpoint into a connection-holding one, with no per-IP rate limit | Story 2d adds a ?timeout_ms=N consumer wait (event-driven via Phoenix.PubSub) to the download endpoint for :quarantined/:scanning media; bugfix/media-download-451-scan-race makes it the default (absent timeout_ms stalls for default_stall_ms, spec default 20s, also on thumbnail), so every client now stalls on a not-yet-released file, not only those that opt in. Unlike its upload/preview_url siblings, download carries no per-IP Nebu.Web.Plugs.RateLimit tier; the stall now holds the HTTP connection (plus a linked Task and a PubSub subscription) open for up to max_stall_ms (20s default), governed only by a single global :atomics ceiling (max_concurrent_stalls, default 500) — no per-user/per-IP sub-cap. An authenticated single IP could in principle hold/refresh up to 500 concurrent 20s stalls, monopolizing the entire global stall pool. | Kassandra security review (Story 2d): APPROVED, 0 CRITICAL/HIGH. M-1 (MEDIUM), tracked non-blocking: graceful degradation (AC6) bounds the blast radius — a denied stall falls back to the immediate pre-2d 451 M_NOT_YET_UPLOADED response (retryable), so the attack denies an optimization, not availability of the endpoint; a denied stall costs a client only the optimization (it gets the immediate 451 it got before Story 2d). Amended by the 451-scan-race bugfix: the stall is no longer opt-in, so default stalls add legitimate load to the same pool, and a stuck ClamAV (files never leave :quarantined/:scanning) makes every download/thumbnail of such a file hold a slot for the full window (<= max_stall_ms). There is still no per-user/per-IP sub-cap: one authenticated member can already exhaust all 500 slots per node with explicit timeout_ms=20000, and the ceiling is per node, not global. default_stall_ms <= 0 is the operator kill switch. A failing/slow stall recheck degrades to the immediate 451, never a 500. Recommended (not required) hardening, forward-carried for a future story: (1) add a per-IP RateLimit tier to the download route, mirroring the existing upload/preview_url inline pattern; (2) and/or a per-user/per-IP sub-ceiling on stall slots so no single principal can consume the whole global pool. Review cycle 2 (451-scan-race bugfix, Kassandra F-1, fixed): the slot used to be released by a try/after in the request process, which never runs when Bandit kills an HTTP/2 request process on client disconnect (exit signal from the linked connection process), so slots leaked permanently and the node eventually got the immediate 451 again. Slots are now owned by a tiny unlinked keeper process that monitors the requester and releases on :DOWN; the explicit release (normal/timeout/raise) and the keeper race on a per-slot compare-exchange so the counter is decremented exactly once. On HTTP/1 a disconnected client still pins its slot for the remaining window (Bandit cannot see the close while the handler is blocked). Also fixed: clamp_stall_ms/1 now requires an integer max_stall_ms (a non-integer cap sorted above every integer and left the client value unclamped; fails closed to no stall). Open follow-ups (not in this bugfix): F-2 per-user/per-IP sub-cap on stall slots + per-IP RateLimit on download/thumbnail (above); F-3 thundering herd when many stalled requests for one media id wake on the same broadcast (add 0-500 ms jitter or single-flight fetch/decrypt per media id); F-4 remainder: default_stall_ms/max_stall_ms are compile-time config only, so the kill switch needs a rebuild and the admin-UI max_stall_ms (bound 1 ms-1 h, Nebu.Media.Config) is inert for the handler - wire the accessors to Nebu.Media.Config and lower the admin bound (~60 s) together. Full report: docs/stories/media-security-admin-control/security-reports/2d-download-stall-mechanism-security-review-2026-07-14.md. | | Stale async-upload reservations consume the per-user pending quota indefinitely | Story 2a introduces async-upload reservations (POST /_matrix/media/v1/create) which creates :reserved rows; a user who reserves media_id X and never uploads keeps that row indefinitely, consuming 1 of the max_pending_per_user quota. A malicious/careless user could reserve max_pending_per_user IDs and block themselves (or other users if the quota is shared). The reservation TTL is computed live on every read (uploaded_at + unused_expires_ms() vs now_ms, never persisted as a column) but is advisory-only — no automated cleanup happens. | Story 2e (Media Reserved Upload Cleanup Cron) introduces Nebu.Workers.MediaReservedUploadCleanupWorker — an Oban job on a 15-minute cron schedule that queries media_files rows in :reserved state with expired TTL (using the identical live-computed formula: WHERE uploaded_at + (SELECT CAST(app_setting->>'media_unused_expires_ms' AS INTEGER)) < NOW()) and transitions them to :hard_deleted via Nebu.Media.StateMachine.transition/4. Idempotent by design: concurrent/repeated runs silently skip already-deleted rows (caught by the guard-table :invalid_transition rejection). The cron schedule (15 minutes) is decoupled from the TTL value (configurable, default 24h) so cleanup runs 96 times daily regardless of the expiry window, ensuring no stale rows accumulate beyond 15 minutes post-deadline. Pending-count accuracy is restored as rows leave :reserved state. | | Async upload finalization (PUT /_matrix/media/v3/upload/{serverName}/{mediaId}) — silent failure and content-type parity | Story 2b (media-security-admin-control epic) implements the async-upload companion to Story 2a's reservation. Two MAJOR findings surfaced in pre-security code review: (1) persist_upload/1/StateMachine.transition/4 failures after a successful S3 write were initially discarded, returning a false-success 200 while leaving the row :quarantined with NULL storage_key/placeholder key material — permanently unretrievable, and a client retry would then 409 instead of succeeding; (2) the async route initially omitted the hardcoded @blocked_upload_types stored-XSS blocklist (text/html, image/svg+xml, etc.) that the sync upload/1 path already enforces, silently accepting content types the sync route rejects — reachable via thumbnail/3, which (unlike the download handler) serves image/* content types inline without forcing attachment. Separately, this story also resolved a schema gap: no unused_expires_at column exists (2a computes it in-memory only) and no filename column existed at all. | Both MAJOR findings fixed before merge (code-review cycle 1): store_and_quarantine/7 now gates both writes via with :ok <- persist_upload(...), {:ok, _} <- transition(...) ... else -> 500 (mirrors upload/1's own error-handling pattern); validate_and_store_async/4 now checks content_type in @blocked_upload_types FIRST, in addition to (not instead of) the admin-configurable mime_denylist_rejected?/1 — both lists independently enforced, never merged (Dev Agent Guardrails). Regression tests added for both failure modes and both blocked content types. Schema-gap resolution (coordinator decision, 2026-07-14): unused_expires_at resolved via live derivation (row.uploaded_at + unused_expires_ms() < now), never persisted — safe to recompute on every read since a reservation TTL has no "compute once, freeze forever" irreversibility concern (unlike 11c's storage-key template); Story 2e's cleanup cron MUST use this identical formula, not a WHERE unused_expires_at < NOW() column read. filename resolved via a narrow migration (000025_media_files_filename, nullable TEXT, no new GRANT needed — ALTER TABLE on an already-granted table, not a new one) since no clean workaround existed. Kassandra security review (Story 2b): CLEAN, 0 CRITICAL/HIGH; 1 LOW (concurrent-PUT TOCTOU — no row lock between lookup_reservation/2 and the later writes; judged security-sound as accepted risk since it is self-vs-self only, both requests must pass the ownership check, no cross-user impact — deferred to Story 2c's shared-pipeline consolidation) + 3 INFO (filename header-injection watch-flag: row.filename has zero readers today, registered as a forward flag for the future download-handler Content-Disposition wiring story; no RLS on media_files is a pre-existing standing gap, not introduced by this story; migration GRANT reasoning doc-hygiene note). | | Async-upload reservation cleanup (Nebu.Workers.MediaReservedUploadCleanupWorker, Story 2e) — hard-delete side effects | Story 2e introduces the first automated cleanup of stale :reserved rows and the first code path in the codebase to reach the :hard_deleted state transition. The transition nulls both uploader_user_id (for GDPR compliance: severing the uploader-file link in the metadata row, even though the file is already deleted from S3 storage) and stamps hard_deleted_at = now() (for compliance audit trails). A future story adding a real caller for the pre-existing deleted -> hard_deleted edge may need different behavior (e.g., preserve uploader_user_id for paid-download audit). | Kassandra security review (Story 2e): APPROVED, 0 CRITICAL/HIGH, 2 LOW (forward-tracked): F-1 (LOW): nulling uploader_user_id on hard-delete flips the true reservation owner's subsequent PUT-upload response from 404 (ownership-check miss on unknown/deleted row) to 403 (row exists but user_id != uploader_user_id). A weak existence oracle gated by 128-bit unguessable media_ids. Fix deferred to a future story since it touches pipeline-protected Nebu.Media and may require coordination with Story 2b's concurrent-PUT findings. F-2 (LOW): the shared hard_deleted UPDATE path now nulls uploader_user_id, but the pre-existing deleted -> hard_deleted edge has no real caller before this story. When a future story adds a real caller for deleted -> hard_deleted (e.g., Story 6a's admin-delete-expired-content flow), that caller may need different uploader-identity preservation behavior for compliance audit. Recommendation: capture uploader identity into media_state_transitions.actor_metadata BEFORE nulling the row column, once actor-ledger extensions land. | | Async malware-scan worker (Nebu.Workers.MediaScanWorker, Story 4b) — first real Oban.insert/1 call site + decrypted-attacker-content-to-scanner pipeline | Story 4b wires Nebu.Media.ScanEnqueue.enqueue/1 from a no-op stub to a genuine Oban.insert/1 call (the first HTTP-adjacent trigger of a real background job in this codebase — 2e's own Oban bootstrap had no HTTP-reachable enqueue path at all) and introduces the worker that fetches/decrypts/conditionally-decompresses a :quarantined upload's bytes before handing them to Nebu.Media.ClamAV.scan_binary/1. Two questions worth tracing explicitly: (1) can an attacker reach Oban.insert/1 with attacker-controlled arguments, and (2) does the conditional :zlib.gunzip/1 step introduce a decompression-bomb / memory-exhaustion risk given ADR-019's single-node topology? | Kassandra security review (Story 4b): APPROVED, 0 CRITICAL/HIGH/MEDIUM, 2 LOW (forward-looking, non-blocking). (1) media_id reaching Oban.insert/1 is always the server-generated 128-bit id from Story 2a's genesis path — ScanEnqueue.enqueue/1's call site (2b's store_and_quarantine/7) is unchanged, existing-auth-gated code; no attacker-controlled value reaches the job args. (2) Traced and ruled out: row.compressed: true bytes are always Nebu.Media.Storage.compress/1's own :zlib.gzip/1 output, applied by the SERVER to plaintext whose size Nebu.Media.upload_async/3's pre-compression 413 M_TOO_LARGE check already bounded — :zlib.gunzip/1 can only ever reconstruct bytes up to that same pre-existing cap, never an attacker-crafted amplified blob (the classic zip-bomb shape requires the attacker to supply the compressed bytes directly, which never happens here). F-1 (LOW): Nebu.Media.ClamAV's max_file_size_bytes and 2b's upload-size cap are independently configured; a misconfiguration (former lower than latter) costs bounded transient worker memory before a graceful :file_too_large skip (AC7), not a crash — a config-consistency watch-flag, not a code defect. F-2 (LOW): no unique: constraint on the Oban worker means a client PUT retry could enqueue a duplicate scan job for the same media_id; harmless today (the guard table rejects scanning -> scanning, routed through the standard retry/discard path since this story's own code-review cycle widened the entry-transition handling to a catch-all) but flagged as a watch-item if a future story ever changes that guard edge. Full report: docs/stories/media-security-admin-control/security-reports/4b-media-scan-worker-security-review-2026-07-14.md. | | Compliance audit bridge (Nebu.Workers.MediaScanWorker, Story 4c, ADR-028) — :infected/scan_failed visibility beyond the per-file ledger | media_state_transitions (ADR-031) is authoritative but is not the surface compliance officers/auditors actually use (AuditLogLive). Story 4c bridges the two compliance-relevant terminal outcomes into the global audit_log via Nebu.Compliance.AuditWriter.log/6 (ADR-020), alongside — never replacing — the existing per-file write. This epic has a documented recurring footgun: a new audit action string not registered in AuditWriter.@known_actions silently no-ops the write ({:error, :audit_unknown_action}, logged only at Logger.error), as happened once before with member_added/member_removed/room_visibility_changed falling out of the allowlist after a branch merge. | Kassandra security review (Story 4c): APPROVED, 0 CRITICAL/HIGH/MEDIUM, 2 LOW (both advisory/forward-looking, no active exploit path today). media_infected_detected/media_scan_failed registered in @known_actions in the same commit as the two new call sites (infect/2; scan_error/4's exhausted-retries branch — there is no separate Oban discard/2 callback, that was pre-4b draft-prose terminology); the allowlist regression (AuditWriterMediaActionsTest) was verified LIVE by temporarily reverting both entries and confirming the test fails loudly before restoring. F-1 (LOW): scan_error/4's pre-existing (Story 4b, unchanged) inspect(reason) now also lands in audit_log.metadata — a broader-visibility surface than media_state_transitions; checked (not assumed) that Nebu.Admin.AuditLogLive does not select or render metadata at all today, so no active render-time path exists; watch-flag if a metadata-detail view ever ships. F-2 (LOW, advisory): filename (attacker-influenced via Story 2b's unsanitized ?filename=) reaches audit_log.metadata for the first time; no compliance_export_downloaded-implementing code exists yet, so flagged forward (CSV/formula-injection neutralization) for whichever future story builds that export, per the same "flag forward, don't block on unimplemented code" precedent Story 4a set for MediaScanWorker itself. lookup_for_scan/1's SELECT was extended with filename/file_hash/uploader_user_id (private DB-module function, no new external caller — no new exposure). No room_id key added (ADR-028), confirmed by direct test assertion. Full report: _bmad-output/nebu/epics/media-security-admin-control/step-results/4c-infected-scanfailed-audit-bridge/security-review-2026-07-14.md. | | Scan kill-switch (Nebu.Workers.MediaScanWorker, Story 10d) — admin-configurable fail-open/fail-closed policy when ClamAV is unreachable | This is the epic's most explicit availability-vs-safety tradeoff: an admin can opt into releasing files WITHOUT malware scanning when the scanner is down. Default MUST be "fail_closed" (never silently "fail_open") and every fail-open release must be non-negotiably audited (AC7) — the single most security-sensitive event this story exists to make visible. The story's own illustrative pseudocode used a stale health_check/0 return shape (bare :healthy atom vs. the real %{healthy: boolean(), changed_at: DateTime.t()} map) and a stale app-env namespace (:nebu vs. the codebase's actual :nebu_http seam convention) — both correctly caught and fixed during dev/code-review, independently re-verified during security review rather than trusted. | Kassandra security review (Story 10d): APPROVED, 0 CRITICAL/HIGH/MEDIUM, 1 LOW (already self-fixed before the security review began, independently re-verified rather than trusted). AC7 audit-completeness traced linear with no silent-skip branch: handle_kill_switch/3's "fail_open" clause is a hard-match transition → broadcast → unconditional write_audit/4 call, with no code path that releases the file while skipping the audit (a transition failure raises before the audit call is ever reached, no partial-success state). Default-fail_closed defended at 3 independent layers (compile-time @defaults, DB-absent-row build_catalog/1 behavior, and the shared @default_catalog test fixture that breaks 7+ unrelated assertions on any silent regression — the CI gate itself enforces this, not just this story's own tests). scan_error/4 confirmed genuinely reused VERBATIM for the fail_closed path (diffed — zero lines changed) — no duplicated retry/discard logic. Migration 000034 is ALTER POLICY only (single atomic DDL, no drop/recreate window, no new table — 9a's own HIGH-class "new-table-missing-GRANT" pattern does not recur since nebu_app already held full DML on media_config since 000023). 1 LOW (self-fixed inline before this review): handle_kill_switch/3's case originally had no catch-all for an unexpected/corrupted scan_kill_switch value (only reachable via a manual DB edit bypassing the validated upsert/1 write path) — would have raised CaseClauseError; fixed with an other -> clause that logs a warning and fails CLOSED, matching the story's own safety posture. Chain-risk noted for the record, not blocking: Story 3's own F-4 (unauthenticated clamd TCP control plane, including a SHUTDOWN verb) was already remediated (docker-compose.yml publishes no host port for clamav, reachable only from other containers on the compose network) — but IF an admin has explicitly opted into fail_open AND an attacker has already breached the docker network boundary, that attacker gains a working "force files unscanned" primitive by killing clamd. A combination of two already-reviewed, independently-accepted risk decisions, not a new remotely-exploitable surface this story introduces on its own — flagged for epic-end holistic re-review. Full report: docs/stories/media-security-admin-control/security-reports/10d-scan-kill-switch-security-review-2026-07-20.md. | | Admin media table (Nebu.Admin.MediaLive, Story 5a) — attacker-controlled filename rendered in the admin same-origin context | Kassandra's own carried-forward watch-list item (2026-06-25, pre-implementation) flagged "uploaded files (arbitrary Content-Type, filenames, EXIF, SVG) rendered/previewed in the admin UI = stored-XSS + content-injection." Story 5a is the first admin surface to render filename — Story 2b's client-supplied ?filename= value, genuinely attacker-controlled, not merely admin-authored. Also the first admin surface built entirely on inline, parameterized ADR-018 SQL over user-suppliable filter dimensions (state[]/mime/uploader/date-range/cursor), and the first to expose uploader_user_id/filename PII in a filterable list view. | Kassandra security review (Story 5a): APPROVED, 0 CRITICAL/HIGH/MEDIUM/LOW, 2 INFO (no dedicated rate limit on the bounded 5,000-row "select all matching filter" query beyond the general admin-auth gate; LIKE-wildcard characters in the mime/uploader substring filters can broaden an admin's own match — neither is a vulnerability, both match the posture of every sibling admin page and reveal nothing the already-fully-privileged admin couldn't see unfiltered). Watch-list item partially CLOSED: filename/media_id/uploader_user_id render exclusively through ordinary HEEx {...} auto-escaping (zero raw/1/{:safe, ...} in the diff) — no preview/thumbnail exists at all (AC6 explicitly excludes it) — confirmed by a dedicated regression test seeding a <script> payload into both filename and uploader_user_id and asserting it never appears unescaped. The watch-list item's OTHER half (actual file-CONTENT preview, cross-origin asset serving, SRI) remains fully open for whichever future story (6b detail-view or later) adds a preview/thumbnail surface. Query-composition layer traced clean: every filter dimension (including the state[] allowlist-gated ANY($n::media_state[]) cast and the base64-opaque keyset cursor) travels as a bound Postgrex parameter, never string-interpolated. Two independent schema-reality corrections made during this story (same class as the epic's own file_path→storage_key precedent, Review 3): the identity column shows the real, nullable filename (Story 2b, migration 000025) with a Media-ID fallback rather than assuming the column didn't exist; the ClamAV signature column reads the actual scan_metadata->>'clamav_signature' key Nebu.Workers.MediaScanWorker.infect/2 persists, not a plain 'signature' key an earlier draft assumed. Full report: docs/stories/media-security-admin-control/security-reports/5a-admin-media-table-security-review-2026-07-18.md. | | ClamAV health & freshclam signature age monitoring (Nebu.Admin.ClamAVStatusIndicator, Story 10b) — operability NFR-O2 polling interval and staleness threshold | Story 10b adds a poll-based helper Nebu.Admin.ClamAVStatusIndicator (mirroring WarRoomIndicator's 2-second tick pattern) that surfaces ClamAV daemon connectivity status (AC1/AC2) and freshclam virus-signature database age (AC3) on /admin/media/health's "ClamAV-Status" section. Three operability concerns arise: (1) is a 2-second poll tick (2,000 ms) the right cadence for spotting clamd outages, or does it create excessive zVERSION\0 chatter against the external daemon?; (2) does the hardcoded signature_max_age_hours: 48 threshold match the real freshclam update cadence and false-positive rate expectations, or will admins ignore the warning?; (3) is the live PubSub broadcast path ever needed, or is the poll-tick correct?| Kassandra security review (Story 10b): APPROVED, 0 CRITICAL/HIGH/MEDIUM, 0 LOW. (1) Poll interval: 2-second tick generates 43,200 zVERSION\0 queries per day per Nebu instance — a sampled health-check pattern, not a probe storm (same magnitude as WarRoomIndicator's own poll traffic to Nebu.Repo). Each zVERSION\0 call exercises the socket (send + recv), so it's the FIRST call to detect a peer-closed connection; health_check/0 follows and discovers the cleared socket, triggering a real reconnect probe in the SAME poll tick — enabling admins to notice an outage within ~2s of occurrence. Call order (signature_info BEFORE health_check) is load-bearing: clamd peer-closes after every zVERSION\0 reply, and calling health_check first would reuse the stale socket, missing the close until a subsequent tick. Documented and verified during dev-story. (2) Staleness threshold & cadence: 48-hour default chosen within the epic's own 24–48h suggested range; upstream ClamAV rebuilds signatures multiple times daily and freshclam's default poll interval is hourly — a healthy, connected freshclam sidecar should never approach 48h stale under normal operation, making 48h a low-noise signal (AC4). The threshold is static app-config default (admin-configurable override is out-of-scope per AC4, a future Story 9/admin-settings enhancement); a deployed operator must inspect config.exs or redeploy to adjust. (3) Poll-tick vs. PubSub broadcast: Deferred to Story 10c; 10b's architecture explicitly uses WarRoomIndicator's poll model because ClamAV connectivity/signature-age are sampled external-daemon properties, not domain events Nebu itself decides to emit — no natural "event" to broadcast (story guardrails explicitly forbid building a new PubSub-broadcast path just for this story). If 10c/10d later discover that Story 10a's page needs tighter coordination (e.g., alert triggers that depend on syncing multiple status columns within a single tick), then a coordinated broadcast onto the 10a LiveView's existing mount/3 may make sense — but that's a 10c decision, not 10b's. Carry-forward (low-priority): threshold configurable via admin UI (Story 9b enhancement, not this story); threshold validation guard against pathological values (e.g. signature_max_age_hours: -1 parses fine but produces nonsensical comparisons — not a data-loss gap, just an operational UX snag). | | Live row updates + nav attention badge (Nebu.Admin.MediaAttentionBadge/Nebu.Media.StateMachine, Story 5b) — first real broadcaster onto a media: PubSub topic | Story 2d/1c's own pre-implementation design review recorded as a POSITIVE that "NO lib code broadcasts on any media: topic" — a real broadcaster (forged or buggy) could otherwise inject arbitrary state into an admin-visible surface. That premise was already stale after Story 4b's MediaScanWorker landed its own 3-tuple broadcast on "media:#{media_id}"; Story 5b adds a SECOND, distinct broadcaster (Nebu.Media.StateMachine.transition/4, a NEW 4-tuple on a NEW topic, "media:admin") and is the first story to make the admin UI itself a consumer of live PubSub state-transition data, visible across 6 LiveViews. | Kassandra security review (Story 5b): APPROVED, 0 CRITICAL/HIGH/MEDIUM/LOW, 1 INFO. Re-verified 2d's underlying safety property (broadcast content never trusted for a security-relevant decision) still holds under the new callers: Nebu.Media.DownloadStall's existing 3-tuple "media:#{media_id}" consumer is completely untouched by this diff (the new 4-tuple targets the distinct "media:admin" topic only — 5b's own story text anticipated and prescribed exactly this non-breaking coexistence, since changing the existing topic's payload shape would have silently broken DownloadStall's strict 3-tuple receive match); Nebu.Admin.MediaLive's new row-patch handle_info/2 re-reads the row fresh from media_files by media_id (fetch_row_by_id/1, parameterized) rather than trusting the broadcast's own new_state for what gets rendered — broadcast still only ever advances WHEN a re-render happens, never WHAT gets shown, matching 2d's own established pattern exactly. One genuinely new, assessed and accepted trust extension: MediaAttentionBadge.apply_transition/3 DOES adjust its in-process attention count straight from the broadcast payload (one COUNT per mount, zero DB round-trips per broadcast, by design — see Technical Requirements). The sole producer is transition/4's own guarded, DB-transaction-backed call (SELECT ... FOR UPDATE + guard-table check) — no HTTP-reachable injection path exists; forging a message would require BEAM-level code execution, a materially different, already-total-compromise threat model. Blast radius of a hypothetically wrong value: a transient UI counter miscount only, no authz/content-serving decision — explicitly bounded and self-healing by the story's own AC4 design (a fresh mount always re-derives the count via a live COUNT). No PII in any broadcast payload (opaque media_id + media_state enum atoms only, both already admin-visible in the table); all 6 subscribers sit behind the existing live_session :admin/require_admin gate. No new DB read-amplification vector: fetch_row_by_id/1 fires only for a media_id on THIS admin's current page (visible_media_ids, bounded by page size), and the pre-existing transition/4 transaction already dominates the marginal cost of one additional in-memory Phoenix.PubSub.broadcast/3. 1 INFO (non-blocking, pattern recorded for future transition/4 callers — 6a/8a/13x inherit this same broadcast for free and this same reasoning applies to them without re-derivation, unless a future consumer ever uses the broadcast payload for an authz/content decision instead of a UI counter). Full report: docs/stories/media-security-admin-control/security-reports/5b-live-updates-nav-badges-security-review-2026-07-18.md. | | Routine admin actions (Nebu.Media.admin_block/3/admin_unblock/2/admin_delete/2/admin_rescan/2, Story 6a) — first admin-facing WRITE path on /admin/media; :admin_blocked anonymity's dormant 1c watch-flag goes live | Story 6a is the first real caller of Nebu.Media.StateMachine's {:admin, admin_id} actor (1b's own tests only ever used a synthetic Ecto.UUID.generate()), the first to make Story 1c's dormant ":admin_blocked anonymity becomes live once the mutation path ships" watch-flag fire for real, and introduces the epic's first destructive-action confirm modal (Delete) plus the first admin-supplied free-text field (Block's optional reason) landing in both media_state_transitions.metadata and audit_log.metadata. | Kassandra security review (Story 6a): 1 CRITICAL found and fixed in-review, 0 remaining CRITICAL/HIGH/MEDIUM/LOW → APPROVED post-fix. CRITICAL (self-caught via sanctum before commit): download_gate(:admin_blocked) still returned a distinguishable 451 status — exactly the dormant 1c finding, now live. An interim documentation-only fix (same dev session, pre-Kassandra) had re-justified the 451-vs-404 split as acceptable, independently re-deriving the exact reasoning the sanctum's own prior finding had already refuted — caught only because the security review actually cross-checked the diff against MEMORY.md's Recurring Patterns rather than reasoning fresh. Fixed to byte-identical {404, "M_NOT_FOUND"} (see the dedicated download-gate row above and ADR-026's 2026-07-19 correction). Design/architecture-gap fix, verified zero-risk: media_state_transitions.actor_id UUID→TEXT (migration 000029) — confirmed via live query that all 42 pre-existing rows had actor_id = NULL before writing the migration, not assumed; the new Matrix-ID-string identity shape matches audit_log.actor_user_id exactly, a net auditability improvement over the prior UUID (which had no real-world value to populate it with). Authorization: all 4 actions inherit 5a's existing on_mount({Nebu.Admin.Auth, :require_admin}, ...) gate unchanged — no new/parallel auth mechanism; the existing "non-admin session redirected pre-mount" test generically proves every handle_event clause (5a's and 6a's) is unreachable without it. Audit-bridge completeness: AuditWriter.@known_actions gained all 4 new action strings in the SAME commit as the functions referencing them (this epic's own documented recurring footgun, per Story 4c's row above), verified via a standalone allowlist-regression test. Idempotency/guard-table: Block/Unblock no-ops (AC9) and guard-rejected transitions (AC8) both verified, via real-DB tests, to write ZERO new media_state_transitions/audit_log rows — not merely to return the expected atom. Reason field: written via parameterized JSONB binds (ADR-018, no injection surface); not rendered anywhere in this story's own UI scope — the pre-existing 1b INFO note ("metadata stored verbatim... Story 6 admin-UI rendering is a stored-XSS surface") remains open, unexercised here, carried into Story 6b's (detail-view) review. Delete confirm modal: no window.confirm, no position: fixed (epic's explicit constraint); new MediaDeleteConfirmModal hook lives in the existing same-origin app.js (script-src 'self'-compatible, no inline on*= handlers, consistent with the sanctum's pattern on dead inline confirmations under this CSP). Rescan's Oban surface: reuses the EXISTING :media_scan_enqueue_module seam rather than a second parallel Oban.insert/1 call site; media_id fully server-derived. Full report: docs/stories/media-security-admin-control/security-reports/6a-routine-state-actions-security-review-2026-07-19.md. |

| File detail view + storage summary (Nebu.Admin.MediaLive.Detail, Story 6b) — deliberately the only Story-6 slice that writes nothing; scan_metadata schema-reality drift; two standing watch-flags re-checked, both correctly still open | Story 6b is the epic's first per-file detail page, exposing file_hash/uploader_user_id/the FULL media_state_transitions actor history to any admin, plus a page-level storage aggregate over ALL media_files rows. Two carried-forward Kassandra watch-flags name this exact story as their re-check trigger: BOND.md's file-content-preview/cross-origin-asset item ("re-check in full whenever a future story — 6b detail-view or later — adds an actual preview/thumbnail surface") and 1b's own I-1 ("rendering metadata inline in the admin origin later — Story 6 — is a stored-XSS surface"). | Kassandra security review (Story 6b): APPROVED, 0 CRITICAL/HIGH/MEDIUM/LOW, 2 INFO. Both standing watch-flags re-checked and confirmed correctly still OPEN, not closed by this story: this page renders no preview/thumbnail/file-content at all (nothing for the BOND.md item to apply to) and fetches media_state_transitions.metadata but never renders it anywhere (nothing for 1b's I-1 to apply to) — both remain live for whichever future story actually adds a preview or renders metadata (e.g. an admin's free-text block/delete reason). Schema-reality correction (self-caught in code-review, same class as 5a's own clamav_signature fix): the story's own AC7/AT8/AT10 text specified the ClamAV scan-metadata key as "signature"; the only real writer, Nebu.Workers.MediaScanWorker.infect/2 (Story 4b), persists "clamav_signature" — as originally drafted the signature block would never have rendered for a real infected file. Fixed in the code, the tests, and the story file itself; Kassandra independently re-traced the fix to the actual worker source rather than accepting the dev's own claim. Second self-caught fix, also independently re-verified: Postgres's SUM(bigint) (media_files.file_size) promotes to numeric/%Decimal{}, which would have silently fallen through humanize_bytes/1's is_integer/1 guard to its "—" placeholder instead of ever rendering a real byte total — closed with an explicit ::bigint cast, confirmed present and CI-verified. Auth/injection/XSS/read-only all traced clean: route confirmed genuinely inside live_session :admin, on_mount {Auth, :require_admin}; all 3 queries bind media_id/take no params, zero string-interpolated SQL; zero raw/1 anywhere (HEEx-only, including the one attribute-context title= interpolation); zero writes, confirmed via a real before/after row+count regression test (not just a static grep) that mounting/rendering this page touches neither media_files nor media_state_transitions, and no new AuditWriter.@known_actions entry (correctly — nothing here to audit). 2 INFO (non-blocking): fetch_transitions/1 has no LIMIT — intentional, since AC3 explicitly requires "every row"; fetch_storage_totals/0 runs even on an unknown media_id, minor wasted work, not a new DoS surface given the admin-only gate. Full report: docs/stories/media-security-admin-control/security-reports/6b-file-detail-storage-summary-security-review-2026-07-19.md. |

| Infected override (Nebu.Media.admin_override_infected/3, Story 6c) — the ONE sanctioned :infected -> :released exception, gated by a distinct grant beyond generic admin | Story 6c is the epic's first deliberate exception to 1b's "infected is terminal beyond -> deleted" guard-table rule: an admin holding a SECOND, distinct media_admin_override grant (new users column, migration 000030, orthogonal to system_role) can release a specific file out of :infected after verifying a ClamAV false positive, with a mandatory server-validated reason bridged into audit_log. Because the shared guard table already legitimately allows :scanning/:admin_blocked/:scan_failed -> :released for OTHER callers, this function cannot rely on allowed?/2 alone to enforce "only FROM :infected" — a genuine gap this story's own ATDD caught before merge. | Kassandra security review (Story 6c): APPROVED, 0 CRITICAL/HIGH/MEDIUM/LOW, 2 INFO. Independently re-verified 3 self-reported fixes, all real: (1) check_infected/1 — the ATDD-caught gap above, confirmed correctly placed BEFORE transition/4 in the with chain, re-verified via the full table-driven test (all 7 non-infected states + :released = 8 total). (2) confirm-button disabled-until-non-empty wiring (phx-change + disabled={...}, an EXPERIENCE.md requirement the code's own comment had claimed but not implemented) — confirmed test 17's render_submit/1 deliberately bypasses the disabled HTML attribute by design, proving server-side enforcement independent of the UI affordance. (3) a focus-trap leak THAT FIX introduced — a :disabled submit button is excluded from native Tab order, so the JS trap's tracked "last focusable" element could never actually receive focus while the reason field was empty (the modal's own default just-opened state), letting Tab escape the modal entirely; fixed via :not(:disabled) on the trap's querySelectorAll selector. Stored-XSS traced end-to-end: the new reason free text lands in media_state_transitions.metadata/audit_log.metadata; grepped 6b's detail view (the only surface reading transition metadata) and confirmed it never renders the per-transition metadata field at all — not rendered anywhere in the current codebase; also reason is admin-authored, not attacker-controlled, a materially lower threat class than BOND.md's uploaded-content watch-item (unaffected — no preview surface added). Auth provenance: admin_id in the LiveView handler is session-derived (actor_id(socket.assigns.current_user)), never client-suppliable via phx-value/params — no impersonation vector for a forged event. GRANT reasoning independently verified, not just asserted: migration 000030 only ALTER TABLE ADD COLUMN (no CREATE TABLE); 000001_init.up.sql's literal blanket GRANT ... ON ALL TABLES IN SCHEMA public (table-level, not column-scoped) already covers it — no new GRANT statement needed, and migrations_grant_test.exs/release_test.exs both correctly extended for the new migration number. Check-ordering info-leak analysis (a positive property, not just an absence of a flaw): authorize_override/1's query is keyed only on admin_id, never media_id, and runs BEFORE lookup_state/1 — an unauthorized admin gets an identical {:error, :forbidden} for literally any media_id (existent, nonexistent, any state), with no differential timing/error channel to probe a specific file's state. 2 INFO (non-blocking): the mount-time-only media_admin_override? flag doesn't live-refresh on a mid-session grant revocation (mitigated — authorize_override/1 re-checks server-side on the actual call); BOND.md's preview watch-item re-confirmed still open/inapplicable for the third consecutive story (5a, 6b, 6c). Full report: docs/stories/media-security-admin-control/security-reports/6c-infected-override-security-review-2026-07-19.md. |

| Admin notification webhook (Nebu.Media.AlertNotifier/Nebu.Workers.MediaAlertWebhookWorker/Nebu.Media.WebhookDelivery, Story 7) — send-time SSRF re-validation gap on an admin-configured outbound URL | Story 7 is the epic's first outbound-network-calling feature: an optional webhook, fired on :infected/scan_failed, POSTs to an admin-configured webhook_url (Story 9a/9b's media_config table). Story 9a's OWN security review had explicitly named this exact story in a forward-carry finding: webhook_url is SSRF-validated only ONCE, at admin config-save time — the actual send (this story) happens arbitrarily later (only on the next matching event), giving a DNS-rebinding attacker an unbounded window to repoint a once-valid hostname at 169.254.169.254/127.0.0.1/internal infrastructure after the save-time check already passed. | Kassandra security review (Story 7, coordinator-requested despite security_review: optional given the outbound-network surface): 1 HIGH found and fixed in-session, 0 remaining CRITICAL/HIGH/MEDIUM/LOW, 2 INFO. The shipped Nebu.Media.WebhookDelivery.post/2 had NOT applied the 9a-recorded mandate — its own moduledoc incorrectly argued no send-time re-check was needed since the target is "admin-configured, trusted," directly contradicting the prior finding. Fixed same-session: post/2 now calls Nebu.Media.SSRF.checked_target/1 immediately before every Finch.request/2, re-resolving and re-validating the host at the moment of use rather than trusting the stale save-time check. IP-pinning (the mitigation Nebu.Media.HttpFetch applies for http targets) does not apply here — webhook_url is always https:// (enforced by Nebu.Media.Config), and SNI/cert validation requires keeping the hostname in the URL; this is the SAME accepted residual-window caveat HttpFetch already documents for its own https branch — the fix closes the unbounded "since admin last saved" window down to that single small per-request window. "No unvalidated redirects" (the other half of the 9a mandate) required no code change: Finch.request/2 never auto-follows 3xx responses. New regression test webhook_delivery_test.exs exercises the real module directly (not the worker-level fake seam), proving 127.0.0.1/10.0.0.5/169.254.169.254 rejected pre-network-call and a genuine public IP reaches the real Finch call. Retry/backoff amplification — assessed, no finding: Finch.request/2's receive_timeout: 5_000 bounds every attempt; max_attempts: 5 bounds total retries; the dedicated :media_alerts Oban queue (limit: 5) is independently concurrency-limited from :media_scan (limit: 10) at the Oban engine level (separate per-queue producer/concurrency pools sharing only the oban_jobs table) — a slow/hostile webhook target cannot starve scan-job processing, holding AC2/AC6's guarantee at the engine level, not just by convention. Payload leakage — re-verified structurally, no finding: neither AlertNotifier.handle_broadcast/1 nor MediaAlertWebhookWorker.perform/1 has any code path reading/forwarding anything beyond media_id/state/timestamp; media_id reconfirmed as the server-generated opaque 128-bit identifier (Story 2a's genesis path), never user-supplied/room-content-derived. AC6 structural guarantee confirmed: the worker module has zero references to Nebu.Media.StateMachine/Nebu.Media.DB anywhere — a delivery failure has no code path back into the media domain. 2 INFO (non-blocking): Nebu.Media.Config's own ≤60s cache-TTL propagation window means a just-disabled webhook could still fire once/see a brief stale URL — an accepted pre-existing trade-off of the shared config cache, not new here; Oban unique cluster-safety rationale (dedup across cluster nodes' own AlertNotifiers) re-confirmed sound per ADR-025. Instance of patterns #44/#50 (admin-configured outbound URL = SSRF surface) — closes the loop Story 9a's own review opened. Full report: docs/stories/media-security-admin-control/security-reports/7-admin-notifications-security-review-2026-07-19.md. |

| Retention hard-delete cron (Nebu.Workers.MediaCleanupWorker, Story 8a) — dead :deleted retention path from a cross-story timestamp-population gap | Story 8a's :deleted candidate query, as originally specified, filtered on media_files.deleted_at < NOW() - interval. No code path in the codebase ever populates that column: Story 6a's Nebu.Media.admin_delete/2 calls StateMachine.transition/4 to :deleted, and transition/4's generic SQL path only ever sets state — only the :hard_deleted target has a column-stamping variant (hard_deleted_at). Since deleted_at is therefore always NULL, and NULL < x is never true in Postgres, the predicate matched ZERO rows forever in production — admin-soft-deleted media was never hard-deleted, silently defeating half of this story's stated purpose (the :infected half, which derives age from the media_state_transitions ledger, was unaffected). This survived ATDD, test-review, CI, and code-review because every test used a FakeRepo that directly seeds deleted_at on the fake row and filters on it — presupposing exactly the population that doesn't exist in production; a per-story fake could not see this cross-story seam gap. | Kassandra security review (Story 8a): F-1/MEDIUM found and fixed in the same review cycle, 0 CRITICAL/HIGH remaining, 2 INFO. Fixed by deriving the :deleted candidate's age from the append-only media_state_transitions ledger instead (MAX(inserted_at) WHERE to_state = 'deleted') — exactly the same shape the sibling :infected query already used, confined entirely to this worker's own SELECT with no change to StateMachine.transition/4, admin_delete/2, or any other shared code path. A new real-DB regression test (media_cleanup_worker_integration_test.exs, @moduletag :integration) drives the actual admin_delete/2 -> StateMachine.transition/4 -> MediaCleanupWorker.perform/1 path against live PostgreSQL, backdating the real ledger row's inserted_at (since now() itself can't be backdated) — the test that would have caught the original bug, since it exercises real production code paths rather than a fake that already assumes the fix. Second, orthogonal bug found and fixed during the same cycle while writing that test (worse than F-1, invisible under FakeRepo-based testing): both the :deleted and :infected candidate queries bind $1 inside ($1 || ' days')::interval; Postgres resolves $1's parameter type as text for that concatenation, so Postgrex requires a binary — the code was binding the raw Elixir integer retention_days, which crashed EVERY real invocation of this worker with DBConnection.EncodeError before reaching either candidate query's WHERE predicate (a strictly worse bug than F-1: it silenced the entire cron tick, :infected and the completion sweep included, not just the :deleted half). Fixed by binding Integer.to_string(retention_days) instead (SQL text unchanged), verified by the same new real-DB test. Code review (separate pass, cycle 0): APPROVE with 1 MINOR (a redundant uploader_user_id null-UPDATE on the reaper path, since transition/4 already nulls it as part of entering :hard_deleted — fixed by removing the redundant UPDATE and documenting the ownership split) + 2 INFO (harmless same-tick reaper retry of a fresh candidate whose S3 delete just failed; strong FakeRepo-based test harness otherwise). ADR-032's three-step ordering (state-transition → S3 delete → null storage_key, audit only on UPDATE success) and per-row rescue-wrapped isolation were both implemented as designed and are unaffected by either fix — both bugs were confined to the candidate-selection queries, not the delete/audit sequence itself. |

| Orphan-detection cron accidentally becomes an auto-delete/GDPR-erasure path | Nebu.Workers.MediaOrphanDetectionWorker (Story 8b) reports :quarantined media_files rows no longer referenced by any Matrix event — the epic's own Review 5 (2026-07-02, R-015) had retracted an earlier claim that this "solves DSGVO Art. 17 (Right to Erasure)"; a dev agent misreading the epic's Story 8 prose could plausibly wire this worker's candidate output into Nebu.Workers.MediaCleanupWorker (Story 8a) or add a state transition directly, silently reintroducing the exact auto-delete Review 5 removed | Kassandra security review (Story 8b): APPROVED, 0 CRITICAL/HIGH/MEDIUM/LOW, 1 INFO. Independently verified (not just trusted from the story text) that the worker never references Nebu.Media.StateMachine anywhere in its source (zero aliases/calls — a structural, not just behavioral, guarantee) and issues only SELECT statements. Verified the 3-field plaintext anti-join (content.url/content.avatar_url/content.info.thumbnail_url) excludes referenced media correctly against LIVE PostgreSQL with real seeded rows for all 3 fields (not just the ExUnit FakeRepo simulation). Verified actor_user_id correctly uses "system:media_orphan_detection_worker" (not the story's own draft nil, which would have failed audit_log's required-field changeset validation and silently broken the audit trail every run — the same allowlist-adjacent gotcha class as Stories 4c/6a/9a, caught here on the actor_user_id field rather than @known_actions). No new admin endpoint, no new user input, no PII exposure beyond pre-existing media_files columns. 1 INFO (not a vulnerability): migration 000031_events_content_gin_index uses a plain, non-CONCURRENTLY CREATE INDEX on events — confirmed the reason is a genuine project-wide constraint (Nebu.Release.apply_migration/3 wraps every migration file in a transaction; PostgreSQL forbids CONCURRENTLY inside a transaction, with no per-migration opt-out today), not a shortcut; every existing migration already has this same blocking-DDL characteristic. Also independently re-verified (code review, separate pass): the story's own literal SQL (NOT EXISTS with 3 OR-ed containment conditions) would have produced an unindexable Join Filter even with the GIN index present — confirmed via real EXPLAIN ANALYZE (including with enable_seqscan = off forced) — corrected to 3 separate NOT EXISTS clauses (De Morgan's-equivalent) plus nested (not ->-extracted) containment for the thumbnail_url case, both empirically re-verified to use Bitmap Index Scan against the new index. |

| Archive-tier storage copy (Nebu.Workers.MediaArchiveWorker, Story 8c) — bucket-to-bucket copy race/idempotency, and a download-path bucket switch that must never diverge in observable behavior between primary and archive reads | Story 8c is the epic's first worker to perform a genuine server-side ExAws.S3.put_object_copy/5 between two buckets and the first to extend the download path's byte-fetch step itself (Nebu.Media.fetch_and_decrypt/3) rather than only the state gate in front of it. Two questions worth tracing explicitly: (1) is archived_at IS NULL alone (no SELECT ... FOR UPDATE) actually sufficient to make concurrent/repeated archive attempts race-safe, and (2) could the new archive-bucket read path ever be tricked into serving the wrong object, or leak which bucket served a response via a status/body difference? | Kassandra security review (Story 8c): APPROVED, 0 CRITICAL/HIGH/MEDIUM/LOW, 2 INFO. (1) Confirmed sufficient: the commit UPDATE ... WHERE state = 'released' AND archived_at IS NULL is a plain single-row UPDATE, which already takes a row lock under Postgres's own MVCC — a second concurrent UPDATE against the same row blocks until the first commits, then re-evaluates its WHERE clause against the newly-committed row and matches zero rows, distinguishing the winner ({:ok, :committed}) from every loser ({:ok, :already_archived}) with no additional locking needed; a double put_object_copy/2 from two racers before either commits is harmless since the source object is immutable (ADR-029) and re-copying identical bytes under the identical destination key is a no-op in effect. (2) row.archived_at is sourced exclusively from the DB via Nebu.Media.DB.lookup/2 — no request parameter maps to it, so a client cannot force either branch; both branches of the bucket-switch if feed the identical decrypt/error-mapping pipeline, so no status/body/header ever differs based on which bucket actually served the bytes. Two self-corrected pre-existing bugs, independently re-verified against the live schema/call-graph rather than trusted from the dev's own claim: lookup/2's to_map/1 used to hardcode storage_key: media_id instead of reading the real column — confirmed consequential by tracing Nebu.Media.StorageConfig.compute_key/2's real call site, which persists a template-derived key that only accidentally equals media_id under the DEFAULT s3_key_prefix_template; and the story's own illustrative candidate SQL (uploaded_at < NOW() - (days || ' days')::interval) cannot type-check against uploaded_at's real BIGINT-millisecond-epoch column (confirmed against 000001_init.up.sql directly), fixed to bind an already-resolved ms-epoch threshold mirroring Story 2e's own convention. One real gap found (and fixed by the dev before this report was finished) during this review itself: archive_one/1's case on Nebu.Media.DB.commit_archived/1 had no clause for that function's own documented {:error, reason} return — a genuine, reachable Postgrex-error path that would have raised CaseClauseError (harmless in effect, since Oban's own job-executor rescue already retries a crashed job, but an undocumented, un-tested gap) — fixed with an explicit propagating clause that behaves identically to a copy failure (no audit, no primary delete), re-verified via a new regression test and a full fresh-stack mix test --include integration run. Audit trail: media_archived correctly registered in AuditWriter.@known_actions in the same change that emits it (this epic's own documented recurring footgun), verified via a dedicated allowlist regression test; audit metadata records the archive bucket name and the archive_delete_from_primary flag in effect at archive time. No new attacker-reachable surface for SSRF/bucket-confusion: this is a cron-triggered worker with no HTTP entry point; archive_bucket()/bucket() resolve from operator config only, and storage_key is the same already-validated (Story 11c check_no_path_escape/1), already-persisted value every other caller already trusts — put_object_copy/2's argument order was checked against ExAws.S3.put_object_copy/5's real signature and confirmed correct. 2 INFO (non-blocking): no rate limit beyond the existing LIMIT 500 per tick, matching every sibling retention worker in this epic; archive_bucket/0's static config fallback is an explicitly-flagged placeholder pending Story 11b's eventual DB-backed per-target config. Full report: docs/stories/media-security-admin-control/security-reports/8c-media-archive-worker-security-review-2026-07-19.md. |

| Operational data-minimization window (Nebu.Workers.MediaReleasedAutoDeleteWorker, Story 8d) — a largest-blast-radius optional cron on correctly disabled-by-default semantics, purely a convenience feature for data-minimization policy, never a security feature | Story 8d is the fourth and final retention lever in the epic's Story-8 split, providing optional soft-deletion of :released files past a configurable age window (released_delete_after_days, default nil = complete no-op). Unlike sibling workers 8a/8b/8c (which target already-negative or archive states), this worker's blast radius is the largest: enabled misconfiguration could routinely destroy files every room member can actively see and download. Per the epic's own data-minimization guidance (Winston-Review-3, Offene-Entscheidung #8), this is explicitly not a security feature — it exists only so an operator can honor their own data retention policy without artificially holding every clean :released file indefinitely. The design centers on ensuring the "disabled by default" contract is absolute: nil must mean a strict no-op (zero queries, zero state transitions, zero audit entries), never "run with a zero-day window." | Kassandra security review (Story 8d): APPROVED, 0 CRITICAL/HIGH/MEDIUM, 2 LOW advisory-only, no code changes needed. (1) LOW: released_for_days/1's DateTime{}/NaiveDateTime{} runtime clauses evaluated outside per-row rescue — unreachable in practice given the query's own WHERE filter (state already :released) and TIMESTAMPTZ NOT NULL schema constraint both ensure the timestamp is always present; checked as a pattern that should be raised for future released_for_days callers if ever called on heterogeneous input. (2) LOW: AuditWriter.log/6 return value discarded on success (a pre-existing, project-wide accepted convention per Story 4c's own pattern, not a new gap). Multiple independent schema/boundary validations carried out, not just trusted from dev's claim: (1) nil-total-no-op at 3 separate Config layers (caller-facing, driver input validation, perform/1 early-return) — AC3 gate confirmed sound; (2) off-by-one boundary: AC1 docs and test cases both specify "N+1 whole days" semantics (floor operation safe direction), re-verified boundary is indeed N+1 not N in the actual query; (3) soft-delete-only call graph: transition/4 confirmed as the sole state writer (no direct hard-delete path), and the per-row rescue confirms a stalled transition leaves the file untouched (AC2 guarantee); (4) audit integrity: media_released_auto_deleted registered in @known_actions in the same commit as the enqueue call (Story 4c's allowlist-footgun pattern verified absent), and metadata captures both released_delete_after_days (config at run time) and released_for_days (actual file age), re-verified against live query output. (5) poison-pill / queue-sharing risk between 8a/8c/8d: same shared :media_cleanup queue and "0 2 * * *" cron slot — accepted precedent per 8a/8c's own live-in-production coexistence without interference (each worker's candidate set is disjoint by construction: state IN ('deleted', 'infected') vs state = 'released' AND archived_at IS NULL vs state = 'released' AND archived_at IS NULL with age-based filtering — zero true conflict vector). Integration-test trigger-dance byte-identical to accepted 8a pattern: seeded a real :released row via StateMachine.transition/4 in test setup, backdated the ledger inserted_at to exercise age-crossing logic, re-ran perform/1, confirmed the row transitioned to :deleted and audit entry written, then re-ran a second time confirming idempotency (row already :deleted, zero transitions). Full report: docs/stories/media-security-admin-control/security-reports/8d-released-auto-delete-security-review-2026-07-20.md. |

| Scan Health rollup (Nebu.Workers.MediaScanStatsRollupWorker/Nebu.Admin.MediaHealthLive, Story 10a) — new derived-aggregate table deliberately without the append-only/RLS controls its ledger source has | media_scan_stats holds only hourly aggregate counts (released/infected/failed/duration percentiles/backlog depth) — no PII, no per-file/per-user identity — derived from and re-computable at any time from the append-only media_state_transitions ledger (ADR-031), which retains its own trigger/RLS controls unchanged (this worker only ever SELECTs from it). media_scan_stats itself is designed to be UPDATEd via upsert (AC3/AC4's idempotent re-run requirement), so it deliberately carries no append-only trigger, no RLS, and a full DML grant to nebu_app — reviewed as a legitimate, narrowly-scoped exception to the epic's "Missing RLS on new tables" recurring pattern (that pattern's own precedent case, forgotten_rooms, held actual room/membership data; this table holds none). Nebu.Admin.MediaHealthLive reads ONLY this rollup table (the epic's own explicit AC5 requirement — never a live query over the full ledger history), behind the same on_mount: {Nebu.Admin.Auth, :require_admin} gate every other admin LiveView uses. All SQL is parameterized (no string-interpolated user input anywhere in either module — the LiveView takes no query/path params at all). A test-only %{"window_start" => iso8601} job-arg override on the worker (added after empirical test flakiness against real-clock windows) is unreachable from any HTTP/admin endpoint in production — this codebase has no generic arbitrary-Oban-job-enqueue surface for an external caller to exploit. Bug found+fixed during dev-story, verified empirically against a real Postgres, not just trusted from the story's own draft SQL: the duration-aggregation CTE as originally sketched filtered WHERE to_state = 'scanning' before computing a LEAD(...) OVER (PARTITION BY media_id ...) window function — since SQL evaluates WHERE before window functions, this silently zeroed every duration sample regardless of real scan activity; fixed by computing LEAD over the full unfiltered per-media_id sequence first. |

Source: _bmad-output/planning-artifacts/prd.md, §Non-Functional Requirements; _bmad-output/planning-artifacts/architecture.md, §Gaps & Open Questions; Story 11-2 (Nebu.Search.DB security invariants, encrypted-room exclusion); Story 9a (media_config table + Nebu.Matrix.MigrationsGrantTest pattern); Story 9b (media_settings_controller.ex, admin-trust-boundary finding); Story 11a (media_storage_config table + Nebu.Media.StorageConfig, SecretBox reuse, unwired-module forward-SSRF finding); Story 11b (StorageConfig.test_connection endpoint scheme validation, orphan-risk-gate AC4 MediaSettingsController.save_storage/2); Story 2b (Nebu.Media.upload_async/3 + store_and_quarantine/7, media_files.filename migration 000025, code-review MAJOR fixes, Kassandra CLEAN verdict); Story 2d (Nebu.Media.DownloadStall event-driven ?timeout_ms consumer, global concurrency ceiling, Kassandra M-1 no-per-IP-rate-limit finding tracked non-blocking); Story 4a (migration 000028 adds media_state ENUM's 9th value :scan_failed + 6 new Nebu.Media.StateMachine guard-table edges, real-DB download-gate catch-all regression test, Kassandra CLEAN verdict); Story 4b (Nebu.Workers.MediaScanWorker, first real Oban.insert/1 call site, decompression-bomb trace, Kassandra APPROVED verdict); Story 4c (AuditWriter.log/6 compliance bridge for :infected/scan_failed, ADR-028, Kassandra APPROVED verdict); Story 5a (Nebu.Admin.MediaLive admin media table, first admin render of attacker-controlled filename, Kassandra APPROVED verdict, own watch-list item partially closed); Story 5b (Nebu.Admin.MediaAttentionBadge + Nebu.Media.StateMachine "media:admin" broadcast, first real broadcaster onto a media: topic, Kassandra APPROVED verdict); Story 6a (Nebu.Media.admin_block/3+admin_unblock/2+admin_delete/2+admin_rescan/2, first admin-facing media WRITE path, migration 000029 actor_id UUID→TEXT fix, ADR-026 :admin_blocked anonymity CRITICAL fix — dormant 1c watch-flag caught live via Kassandra's own sanctum, Kassandra APPROVED post-fix verdict); Story 6b (Nebu.Admin.MediaLive.Detail file detail view + storage summary, read-only, scan_metadata clamav_signature key schema-reality fix, SUM(bigint)→Decimal cast fix, Kassandra APPROVED verdict, both BOND.md/1b-I-1 watch-flags re-checked and confirmed still open); Story 6c (Nebu.Media.admin_override_infected/3, migration 000030 users.media_admin_override grant, guard-table infected→released exception, check_infected/1 ATDD-caught fix, confirm-disabled/focus-trap self-caught fixes, Kassandra APPROVED verdict); Story 7 (Nebu.Media.AlertNotifier + Nebu.Workers.MediaAlertWebhookWorker + Nebu.Media.WebhookDelivery, first outbound-network-calling feature, send-time SSRF re-check HIGH found+fixed in-session closing Story 9a's own forward-carry mandate, Kassandra APPROVED post-fix verdict); Story 8a (Nebu.Workers.MediaCleanupWorker, ADR-032 three-step hard-delete ordering, F-1/MEDIUM dead-:deleted-retention-path cross-story timestamp gap found+fixed, orthogonal Postgrex parameter-encoding crash found+fixed in the same cycle, Kassandra security review + separate code review both clean post-fix); Story 8b (Nebu.Workers.MediaOrphanDetectionWorker, detection/reporting-only orphan-candidate cron, migration 000031 events_content_gin_idx closing the epic's "Offene Entscheidung #3", 3-clause NOT EXISTS query correction empirically verified via EXPLAIN ANALYZE against real Postgres, actor_user_id required-field correction, Kassandra APPROVED verdict with 1 INFO); Story 8c (Nebu.Workers.MediaArchiveWorker, ADR-032 server-side bucket-to-bucket archive copy, archived_at IS NULL race/idempotency guard verified sufficient without SELECT FOR UPDATE, download-path archive-bucket switch extending Nebu.Media.fetch_and_decrypt/3, storage_key-hardcode and uploaded_at-BIGINT-vs-interval self-corrected bugs independently re-verified, 1 CaseClauseError gap found+fixed during the review itself, Kassandra APPROVED verdict with 2 INFO); Story 10d (scan_kill_switch admin-configurable fail-open/fail-closed policy for Nebu.Workers.MediaScanWorker when ClamAV is unreachable, default fail_closed defended at 3 layers, media_unscanned_release new AuditWriter action with linear no-silent-skip audit path, migration 000034 ALTER-POLICY-only RLS extension, scan_error/4 reuse verified verbatim, Kassandra APPROVED verdict with 1 LOW self-fixed pre-review + chain-risk note vs. Story 3's already-remediated clamd network exposure)