Skip to content

Threat Model: Authentication

Created 2026-08-09
Last reviewed 2026-10-19
Next review due 2027-04-19 (6-month cadence, or on any change to the auth surface)
Reviewers Platform owner
Version 2.4
Surface owner Platform / Auth

Scope: how people prove who they are to Tomoda. That covers app users signing in to the tomoda backend (password, Google, Apple, passkey, one-time codes), the sessions the backend issues, and operators reaching admin surfaces (oauth2-proxy, Argo CD Dex, Cloudflare Access, Tailscale). The synthetic probe account is in scope because it is a real prod login.

Out of scope: edge and origin lock (network & ingress), secret delivery and CI identities (secrets & supply chain, Release Integrity), and data-store access (data plane).

Code references are to the tomoda repo's backend/ unless they start with one of this repo's paths. How the pieces work: GCP → OAuth clients, oauth2-proxy, Access Control, Server Access, Synthetic monitoring.

Data flow diagrams

App users and operators authenticate on separate paths. Opening one does not open the other.

Path 1: app sign-in and session use

Every request crosses Cloudflare (proxied, WAF, origin-locked) and Traefik before the backend. Inside the backend, the IP blocker and per-IP limiters run before any auth handler.

flowchart LR
    E1([E1 · App user]) -->|F1 HTTPS| P0
    E3([E3 · Google / Apple<br/>identity provider]) -->|F2 ID token| E1
    subgraph edge[trust boundary: Cloudflare + Traefik]
        P0[P0 · edge<br/>WAF · origin pull · client IP]
    end
    P0 -->|F3 request + client IP| P1
    subgraph backend[trust boundary: tomoda backend]
        P1[P1 · IP blocker<br/>per-IP limiters]
        P1 --> P2[P2 · auth handlers<br/>password · social · passkey · OTP]
        P2 -->|F4 lookup / history| D1[(D1 · Postgres<br/>users · login_histories<br/>refresh_tokens · webauthn)]
        P2 -->|F5 counters · challenges| D3[(D3 · Redis<br/>limits · blocks · OTP budget)]
        P3[P3 · JWTAuth<br/>signature · token_version · status]
        P3 --> D1
    end
    P2 -->|F6 access JWT + refresh token| E1
    E1 -->|F7 Bearer JWT| P3

Path 2: operator access

flowchart LR
    E2([E2 · Operator]) -->|F8 HTTPS| P4
    E2 -->|F11 WireGuard| P7
    subgraph cf[trust boundary: Cloudflare Access]
        P6[P6 · Access<br/>GitHub org · service token]
    end
    E2 -->|F12 HTTPS| P6
    P6 --> X1[docs.tomoda.life<br/>loki-push]
    subgraph edge[trust boundary: cluster edge]
        P4[P4 · oauth2-proxy<br/>allow-list · or Argo Dex + RBAC]
        P4 -->|F9 X-Auth-Request-Email| P5[P5 · admin UIs<br/>Grafana · pgAdmin · redis-insight<br/>OTA dashboard · Argo CD]
    end
    P5 -->|F10 SQL / Redis| D2[(D2 · production data)]
    subgraph ts[trust boundary: tailnet]
        P7[P7 · Tailscale<br/>tcp 22 · 6443 to tag:server]
    end
    P7 --> X2[SSH · k3s API]

DFD elements

Ref Type Element Notes
E1 External entity App user Any Google or Apple account, or an email + password
E2 External entity Operator tomoda.life Google account, tailnet member, tomoda-labs GitHub member
E3 External entity Identity providers Google and Apple mint the ID tokens
P0 Process Cloudflare + Traefik Traefik trusts X-Forwarded-For only from Cloudflare ranges
P1 Process IP blocker + limiters middleware/ip_blocker.go, middleware/rate_limiter.go
P2 Process Auth handlers services/auth/
P3 Process JWT middleware middleware/auth.go
P4 Process oauth2-proxy / Dex k8s/envs/platform/oauth2-proxy/, k8s/envs/platform/argocd/values.yaml
P5 Process Admin UIs Behind P4
P6 Process Cloudflare Access infrastructure/cloudflare/access.tf
P7 Process Tailscale infrastructure/tailscale/policy.hujson
D1 Data store Auth tables in Postgres Link keys are provider subjects
D2 Data store Production data Reached only through P5 or P7
D3 Data store Redis Limiter counters, IP blocks, OTP budget, WebAuthn challenges

Assets and trust boundaries

Asset DFD Boundary crossed
App user identity E1/E3→P2 Internet → edge → backend
Access JWT and refresh token P2→E1, E1→P3 Backend → device storage → backend
Password hashes, provider links, passkey keys D1 Backend → Postgres
OTP codes and attempt budget D1, D3 Backend → email, Redis
JWT_SECRET, OAuth client secrets (out of band) Secret Manager → ESO → tomoda-prod
Operator sessions E2→P4, P6 Browser → cluster edge, Cloudflare Access
Server and cluster-admin access E2→P7 Tailnet → node

Controls in place

Control Value Where
Client IP Rightmost untrusted X-Forwarded-For hop past the pod CIDR and Cloudflare ranges api/context.go, config.prod.yaml trusted_proxies
Edge rate limit 20 requests per 10s per IP and colo on the credential endpoints, 10s block, at Cloudflare before the origin devops infrastructure/cloudflare/waf.tf
Global limit 600 req/min/IP on /api/v1, fails open RateLimiter.APILimit
Login limit 10 per 15 min per IP on password, Google, Apple and passkey routes, fails closed LoginLimit
Register / reset / OTP limits 5/h, 5/h, 10 per 15 min per IP, fail closed rate_limiter.go
Account lockout 5 failed passwords in 15 min. Failures before a later success don't count, and lockout refusals are audited but never counted, so the lockout ends 15 min after the last real failure SessionService.CheckLoginRateLimit, CountFailedLoginAttempts
OTP 6 digits, 10 min TTL, single use, 5 verifies per address per 15 min (fails closed), a new send retires the old code otp_service.go
IP blocker Global, before routing. Rejects probe-pattern requests and blocks repeat offenders; never blocks Cloudflare's published ranges or private and loopback addresses. Thresholds, signed Worker bypass and unblock path: app repo docs/backend/security/ip-blocker.md ip_blocker.go
Google idtoken.Validate, aud in the web/iOS/Android client set, email_verified required verifyGoogleIDToken
Apple RS256, issuer appleid.apple.com, exp required, aud = bundle or service ID, email_verified if email present verifyAppleIDToken
Social linking Google and Apple link only by subject; a shared email returns SOCIAL_LINK_REQUIRED emailAlreadyOwned
Login finalization Password, Google, Apple and passkey logins all end in finalizeLogin: inactive and suspended accounts are refused, then tokens are issued and a login_histories row is written. New social accounts pass the 3-per-device cap and, when the provider sends a birthdate, the 18+ check finalizeLogin
Passkeys RP ID tomoda.life, origin https://tomoda.life, 5 min challenge in Redis, sign counter persisted config.prod.yaml webauthn, FinishWebAuthnLogin
Token transport Authorization: Bearer only. ?token= is accepted only on /ws/* upgrades, where browsers cannot set headers requestToken in middleware/auth.go
Query strings in logs Traefik's access log keeps query strings; Alloy redacts the values of tokens, codes, passwords, signatures, identifier and X-Amz-* params before Loki. The backend request log redacts token keys k8s/envs/platform/traefik/values.yaml, k8s/envs/platform/loki/values-alloy.yaml
Access JWT HS256, 24h, secret at least 32 bytes and not the dev placeholder (boot fails otherwise) GenerateToken, config.go
Revocation Each request checks token_version and account status (60s cache); reset password, revoke-all and admin ban terminate sessions JWTAuth, TerminateUserSessions
Refresh token 32 random bytes, sliding 180 days (native) or 30 days (web), 365-day cap, Postgres is the authority session_service.go
Admin authorization access.Require(TomodaAdmin): account type tomoda and role admin access/policies.go
Operator gates oauth2-proxy allow-list of four named accounts; Argo Dex hostedDomains + RBAC default readonly; fail-closed CI policy on every *.tomoda.life Ingress policy/admin_ingress_auth.rego
Cloudflare Access docs.tomoda.life: tomoda-labs GitHub org members. loki-push: synthetic Worker service token only access.tf
Server access Tailscale only (22 and 6443 on tailscale0); personal SSH logins, no root, no password login Server Access
Synthetic canaries login (200), login-bad-password (401) and auth-middleware (401) every minute synthetic/worker.js

STRIDE

Spoofing

DFD Threat Control Residual
E3/P2 Forged or wrong-audience Google/Apple token Signature, issuer, expiry and audience checks above Low
E1/P2/D1 Email-collision takeover through a new social identity Google and Apple refuse to merge by email Low
E1/P2 Stolen access JWT used where proof of email control is required (password reset, deletion reauth) OTP tokens are typed, purpose-bound and signed with their own key, so an access token is refused where a verified code is required Low
E1/P2 Password guessing Per-IP login limit, per-account lockout, bcrypt cost 12 Low
E1/P2 Credential spray across rotating IPs Per-account lockout Low
E1/P2 OTP brute force 5 verifies per address, a new send retires the old code Low
E3/P2 Replay of a captured ID token The nonce is compared with a value the client sends in the same request; the server never issues or stores it Low, accepted. Gives no replay protection; ID tokens are short-lived
P4/P5 Injected X-Auth-Request-Email to impersonate an operator in Grafana Traefik forwardAuth overwrites authResponseHeaders from oauth2-proxy; CI policy requires the middleware Low

Tampering

DFD Threat Control Residual
P4/P5 Admin UI exposed without the gate Fail-closed policy/admin_ingress_auth.rego in k8s-validate.yml; OTA hosts may expose only three Exact paths Low
P4 Allow-list or RBAC edited in the cluster GitOps with self-heal Low
P6/P7 Access or tailnet policy edited in a console Both in Terraform; the next apply reverts drift Low

Repudiation

DFD Threat Control Residual
E1/P2 App login not attributable Audit log on every login; login_histories with IP, device and risk score for every login method (kept 180 days) Low
E2/P5 Operator action not attributable Grafana provisions from the proxy header; Argo RBAC uses the Dex identity Low-Medium. pgAdmin and redis-insight attribute only through the proxy access log

Information disclosure

DFD Threat Control Residual
E1/P3 Access JWT leaked through logs Query tokens only on /ws/*; Alloy redacts sensitive params from Traefik lines before Loki; the backend redacts token keys Low. The unredacted Traefik line sits in the pod log on the node until rotation and shows in kubectl logs; a new secret param is only redacted once it is added to the Alloy list
D1 Database or backup read yields live credentials Database and backup access (data plane page) Low-Medium. Refresh tokens are stored in Postgres as issued (refresh_tokens.token, sessions.refresh_token), so a read yields tokens that mint access JWTs. Only the Redis mirror key is a SHA-256 hash
E1/P2 Account enumeration Login returns invalid credentials for unknown users Low. A locked account returns 429 rather than 401, unknown users skip bcrypt (timing), and passkey login/begin answers differently for unknown identifiers
(secret) OAuth client secret or JWT secret leaked GCP Secret Manager through ESO Low
E2/P4 Operator session cookie theft Secure, HttpOnly, SameSite=Lax, TLS Low

Denial of service

DFD Threat Control Residual
E1/P1 Login flood Per-IP limits fail closed, so a Redis outage rejects logins rather than leaving them unthrottled Low
E1/P2 Attacker keeps a victim's password login locked Lockout refusals don't extend the lockout; passkey and social login still work Low. One failed guess each time the window slides keeps the account locked
E1/P1 IP blocker false positive Clear exploit traffic is blocked at the edge first; the app's block policy and exemptions are in the app repo's ip-blocker.md Low
E1 Probe account locked by a stranger None Low. Its email is public in this repo; 5 bad passwords page login DOWN for 15 min
P4 oauth2-proxy outage Single replica, cookie sessions Medium, accepted. Operational tooling only

Elevation of privilege

DFD Threat Control Residual
E1/P3 App user reaches admin routes Default RoleBase; admin routes need account type tomoda + role admin Low
P3 Demoted admin keeps privileges Role is read from the JWT claim Low. A DB-only role change lasts until the token expires (up to 24h) unless token_version is bumped
E1/P2 Suspended or inactive user signs in through a side path Every login method ends in finalizeLogin; JWTAuth also rejects unusable accounts on every request Low
E1/P3 Revocation bypassed during a DB/Redis blip Deleted users fail closed Low, accepted. token_version, account status and lockout checks fail open on infrastructure errors
E2/P4 Operator gains Argo write unexpectedly RBAC default readonly, four named admins Low
P4 App-side OAuth client incident disrupts admin login None. App, oauth2-proxy and Dex share client 287267207777-7d0c… Medium, open
E1 Probe account used beyond probing Account type synthetic; password in Secret Manager and the Worker Low. It is a full, age-verified standard account, and each boot forces is_active=true

Findings and recommendations

Ordered by priority.

  1. Shared OAuth client (Medium, open). Give oauth2-proxy and Dex their own web client (GCP → OAuth clients).
  2. Refresh tokens stored as issued (Low). Postgres keeps the token string in refresh_tokens.token and sessions.refresh_token; only the Redis key is hashed. A database or backup read yields tokens that stay valid until they expire, and each use slides the expiry up to the 365-day cap. Store a SHA-256 hash of the token in both tables and look it up by hash on refresh and revoke.
  3. Enumeration and victim lockout (Low). Return the same status for a locked account and bad credentials, and run a dummy bcrypt for unknown users.
  4. Probe account scope (Low). Restrict account type synthetic to the auth and health routes, and exclude it from the lockout or alert on login only after consecutive failures.
  5. Role changes and token_version (Low). Bump token_version on any role or account-type change.
  6. Operator attribution for pgAdmin and redis-insight (Low). The proxy access log is the only record.
  7. Nonce not server-issued (Low, accepted).