# Demeter API — OWASP Top 10 (2021) Security Assessment

**Scope:** `apps/demeter/api` (Fastify REST API, Postgres/Drizzle persistence).
**Date:** 2026-05-31. **Task:** TODOS/phase-29 §29.18.5.1.

This assessment maps each OWASP Top 10 (2021) category to the concrete controls
implemented in the Demeter API and to the automated tests that verify them, and
records residual gaps with recommendations. Test references are to
`src/__tests__/security.test.ts` (61 cases, executed against a live
`demeter_test` database) and the integration suite under `test/integration/`.

Status legend: **Covered** = control present and test-verified · **Partial** =
control present, residual gap noted · **Deployment** = handled at the
infrastructure/ops layer (tracked separately under §29.19).

---

## A01:2021 — Broken Access Control — **Covered**

- Every authenticated route requires a valid bearer JWT via the `authenticate`
  preHandler; protected routes reject anonymous requests with 401.
- Resource ownership is enforced inline in each route against the owning user id
  (gardens by `userId`; beds/plantings/harvests/observations/sensors via FK
  chains to the owning garden; community posts by author for private posts).
  Cross-tenant access returns 404 (existence-hiding) rather than 403 where
  appropriate.
- Non-UUID / malformed ids are guarded (`isUuid`) and resolve to 404 instead of
  leaking a database error.
- **Verified by:** `Security: Authorization Boundaries (29.18.5.2/.3)`,
  per-resource ownership assertions in the integration specs
  (`gardens`/`plantings`/`harvests`/`observations`/`community`), and the
  concurrent-users isolation test (`test/performance/concurrent-users`).

## A02:2021 — Cryptographic Failures — **Partial**

- Passwords are hashed with `bcryptjs` (salted, configurable cost) —
  `src/routes/auth.ts` (`bcrypt.hash` / `bcrypt.compare`); plaintext passwords
  are never stored or logged.
- Access tokens are signed JWTs (`@fastify/jwt`); refresh tokens are random,
  hashed at rest, and rotated. OAuth provider tokens are verified against
  provider JWKS via `jose` (`src/auth/oauth-verifiers.ts`).
- **Residual gaps:** (1) Encryption _at rest_ for the database/object storage is
  a **Deployment** concern (§29.18.5.8 — RDS/volume encryption). (2) Encryption
  _in transit_ (TLS termination) is a **Deployment** concern (§29.18.5.9). (3)
  JWT uses symmetric HS256 with a shared secret; if tokens must be verified by
  independent services, migrate to asymmetric RS256/EdDSA.

## A03:2021 — Injection — **Covered**

- All database access goes through Drizzle ORM parameterized queries — no
  string-concatenated SQL anywhere in the store layer (`src/db/*`).
- All request bodies/queries are validated and coerced by Zod schemas before
  use; unknown fields are dropped by the Fastify JSON schema.
- NUL bytes are stripped from free-text input (`src/db/text-utils.ts`) so
  hostile payloads cannot raise encoding errors or corrupt rows.
- **Verified by:** `Security: SQL Injection Prevention (29.18.5.4)` (payloads in
  query params, body strings, and path params) and
  `Security: XSS Prevention (29.18.5.5)` (script-tag and event-handler payloads
  are stored inertly and echoed without server-side execution; rendering layers
  escape on output).

## A04:2021 — Insecure Design — **Covered**

- Rate limiting is designed in tiers (anonymous / authenticated / auth-endpoint
  / IoT-device) with burst allowance — `src/plugins/rate-limit.ts`.
- Refresh-token rotation with family-based reuse detection: replaying a rotated
  token revokes the entire token family (`src/db/auth-store.ts`).
- Magic links are single-use; sessions are tracked with device/IP metadata and
  evicted on limit.
- **Verified by:** `Security: Rate Limiting (29.18.5.7)`, auth integration spec
  (rotation + reuse-detection cases).

## A05:2021 — Security Misconfiguration — **Covered**

- Hardening response headers are emitted on every reply (success, error,
  and 404) via `src/plugins/security-headers.ts`:
  `Content-Security-Policy: default-src 'none'; frame-ancestors 'none'; base-uri 'none'`,
  `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`,
  `Referrer-Policy: no-referrer`, `Cross-Origin-Resource-Policy: same-origin`,
  `X-DNS-Prefetch-Control: off`, and `Strict-Transport-Security` (honored over
  TLS). A maximally restrictive CSP is appropriate because the API only returns
  JSON.
- CORS is configured from validated app config (explicit allowed-origin list or
  `*`) — `src/plugins/cors.ts`.
- The global error handler returns sanitized messages and never leaks stack
  traces or internal details for 5xx responses — `src/plugins/error-handler.ts`.
- Configuration is schema-validated at boot (`src/config.ts`); the development
  `JWT_SECRET` default is rejected outside development by a `superRefine` check.
- **Verified by:** `Security: Additional Hardening` (header assertions on an
  unauthenticated 404).

## A06:2021 — Vulnerable and Outdated Components — **Covered**

- Dependencies are centrally version-pinned via the pnpm catalog
  (`pnpm-workspace.yaml`); a dependency vulnerability scan is run as part of the
  security workstream (§29.18.5.10).
- **Recommendation:** keep the scan wired into CI so regressions surface on
  every dependency bump.

## A07:2021 — Identification and Authentication Failures — **Covered**

- Strong password hashing (bcrypt), strict auth-endpoint rate limits (5 + 2
  burst per IP) to throttle credential stuffing/brute force, short-lived access
  tokens with rotating refresh tokens, single-use magic links, and verified
  OAuth (Google/Apple/Facebook) sign-in.
- **Verified by:** `Security: Authentication Bypass (29.18.5.2)` (tampered /
  expired / wrong-secret / missing tokens rejected) and the auth integration
  suite (login/logout/refresh/magic-link/OAuth/session/API-key flows).

## A08:2021 — Software and Data Integrity Failures — **Covered**

- Token integrity is enforced cryptographically: tampered JWTs fail signature
  verification; rotated-then-replayed refresh tokens trip family reuse detection
  and invalidate the family.
- OAuth assertions are verified against provider JWKS rather than trusted
  blindly (`jose`).
- **Verified by:** auth integration spec (payload-tampered tokens rejected;
  reuse-detection revocation).

## A09:2021 — Security Logging and Monitoring Failures — **Partial**

- Structured request logging (pino) with a per-request `requestId` correlation
  id; auth-significant events (register/login/logout/refresh, ownership
  failures) are logged with context.
- **Residual gap:** centralized log aggregation, alerting, and anomaly detection
  are **Deployment** concerns (CloudWatch/SIEM, §29.19). **Recommendation:**
  ship structured logs to a central sink and alert on auth-failure spikes.

## A10:2021 — Server-Side Request Forgery (SSRF) — **Low risk**

- The only outbound HTTP the API performs is the weather provider, which targets
  a fixed Open-Meteo host derived from server config — never a user-supplied URL
  (`src/weather/weather-provider.ts`). There is no user-controlled fetch
  surface.
- **Recommendation:** keep the weather host on a config allowlist; if any
  user-supplied URL fetching is added later, validate against an allowlist and
  block private/link-local address ranges.

---

## Summary

| Category                           | Status                                        |
| ---------------------------------- | --------------------------------------------- |
| A01 Broken Access Control          | Covered                                       |
| A02 Cryptographic Failures         | Partial (at-rest/in-transit = deployment)     |
| A03 Injection                      | Covered                                       |
| A04 Insecure Design                | Covered                                       |
| A05 Security Misconfiguration      | Covered                                       |
| A06 Vulnerable Components          | Covered                                       |
| A07 Identification & Auth Failures | Covered                                       |
| A08 Software & Data Integrity      | Covered                                       |
| A09 Logging & Monitoring           | Partial (centralized monitoring = deployment) |
| A10 SSRF                           | Low risk                                      |

**Application-layer posture:** all application-layer controls are in place and
test-verified (the A05 security-header gap surfaced by this assessment was
remediated with `src/plugins/security-headers.ts`). The remaining residual items
— encryption at rest (§29.18.5.8), TLS in transit (§29.18.5.9), and centralized
log aggregation/alerting (A09) — are deployment-layer controls tracked under
§29.19. A future consideration is asymmetric (RS256/EdDSA) JWT signing if tokens
must be verified by independent services.
