Threat Model¶
What we're defending against, what we do about it, and where in the code the defense lives. This is the high-level catalogue — operational tuning of each control lives in the linked sub-pages.
Credential stuffing and brute force¶
Threat. Attackers replay credential lists against /auth/login, /auth/webauthn/login/begin, /auth/otp/verify, etc., or hammer registration to enumerate emails.
Mitigation.
- Per-IP rate limits — 10 logins / 15 min, 5 registrations / hour, 5 password resets / hour.
- Bcrypt password hashing with a default cost factor — slow by design, takes years to brute force a single hash.
- Failed logins logged in the audit trail (
AuditService) so anomalies surface in analytics. - Per-account lockout after 5 wrong passwords in 15 minutes (Auth → Account lockout).
Where. backend/internal/middleware/rate_limiter.go, backend/internal/middleware/ip_blocker.go. See Security → Rate Limiting.
Account farming / sybil attacks¶
Threat. Mass account creation to game social proof, spam events, or harvest invitations.
Mitigation. Layered, independent gates:
- IP rate limit (5 registrations / hour).
- Email OTP at signup — must own the address.
- Device fingerprint cap — 3 accounts per device per 30 days.
Where. backend/internal/services/auth/auth_service.go (checkDeviceFingerprint). See Security → Device Fingerprint.
SQL injection¶
Threat. Malicious input crafted to alter or read SQL beyond the intended query.
Mitigation.
- sqlc-generated query construction. Each domain's
store.goruns generated queries whose values are always bound as positional parameters ($1, $2, ...), never string-concatenated. Raw SQL is restricted to a small set of PostGIS queries that also bind their arguments, verifiable by grepping the store files for inline SQL (grep -rn 'pool.Query\|pool.Exec\|\.Query(\|\.Exec(' backend/internal/services/*/*store*.go). - Heuristic block at the edge:
IPBlocker.SuspiciousActivityMiddlewaredetects classic injection signatures (' OR '1'='1,UNION SELECT, etc.) in query params and 403s the request with a 48-hour IP block.
Where. backend/internal/middleware/ip_blocker.go, the store.go files across backend/internal/services/.
SSRF (server-side request forgery)¶
Threat. The /api/v1/link-preview endpoint fetches arbitrary URLs to extract OG metadata. Without protection, it could reach internal services (metadata endpoints, internal HTTP APIs).
Mitigation.
- Scheme allowlist —
httpsonly. - Hostname resolution + private-IP rejection —
net.LookupHost, then for each resolved IP, reject if it falls in any RFC1918 / loopback / link-local / multicast range.
// backend/internal/services/media/link_preview_handler.go
if u.Scheme != "https" { return fmt.Errorf("only https URLs are allowed") }
hostname := u.Hostname()
addrs, _ := net.LookupHost(hostname)
for _, addr := range addrs {
ip := net.ParseIP(addr)
if ip == nil || isPrivateIP(ip) {
return fmt.Errorf("target resolves to a private IP address")
}
}
Beyond this endpoint-level check, all outbound calls route through httpx.SafeClient, which re-checks the resolved IP at dial time (defeating DNS rebinding). See Security → Outbound HTTP.
Where. backend/internal/services/media/link_preview_handler.go::validateURL.
CSRF¶
Threat. A malicious site causes an authenticated user's browser to make state-changing requests.
Mitigation. Largely not applicable for our API:
- Auth is bearer-token, not cookie. Browsers don't auto-attach
Authorizationheaders across origins. - CORS allows
*in dev (locked down in prod), but credentials in headers must be explicitly set by the calling code — there's no implicit auth. - The only cookie-style risks would be on the webhook endpoints, which use their own signing/verification (Stripe webhook signature, Apple notification JWT signature).
We do not issue or accept CSRF tokens.
XSS¶
Threat. User-supplied content rendered into HTML executes attacker JavaScript.
Mitigation.
- API returns JSON, never HTML. The only HTML the backend emits is the public event share page (
/api/v1/share/events/:id), which renders through Go'shtml/template(auto-escaping) and only includes fields validated server-side. X-Content-Type-Options: nosniffandX-Frame-Options: DENYon every response viaSecurityHeadersmiddleware.- HSTS (
Strict-Transport-Security: max-age=31536000; includeSubDomains) on production responses. - Frontend uses React (auto-escapes JSX) and adds a CSP at the document level — see frontend docs.
Where. backend/internal/middleware/security.go, backend/internal/services/event/event_handler.go (GetEventSharePage), backend/templates/og.html.
Bot / spam¶
Threat. Automated event spam, fake messages, drive-by signups.
Mitigation.
- Email OTP required for signup, password reset, and email change — eliminates throwaway-without-email-access flows.
- Rate limits on the public auth surface (above).
- Suspicious-activity middleware catches obvious automated scanning.
- Audit log of all activity (
AuditService) gives ops a paper trail for after-the-fact takedowns. - Inbound support email carries the edge worker's SPF, DKIM and DMARC verdict; DMARC failures are refused, and Tomoda replies are emailed only to an address proven by an account or a DMARC pass, so a spoofed sender can't receive a thread.
- The public contact form has a feature switch (
support.public_form) an admin can turn off from Backstage during a spam wave, without a release.
Data exposure at rest¶
Threat. A DB dump exposes passwords, credentials, or PII directly.
Mitigation.
- Passwords: bcrypt-hashed, never stored plaintext.
- OAuth provider tokens are never persisted. Only the provider subject id (
google_id,apple_id) is stored. - JWTs are never stored — they're verified statelessly and forgotten.
- Refresh tokens are stored only as hex SHA-256 (
refresh_tokens.token_hash,sessions.refresh_token_hash, and the Redis mirror key) and looked up by hash. Tokens are 256 random bits, so an unsalted hash is not reversible. - PII minimisation — we keep email, optional phone, optional display name, and an avatar URL. No address, no DOB, no payment card data (Stripe holds card details).
Where. backend/internal/services/auth/auth_service.go, backend/internal/services/auth/session_service.go (hashRefreshToken), backend/internal/services/auth/session_store.go.
Privilege escalation¶
Threat. A non-admin user calls an admin endpoint.
Mitigation. Two-layer auth:
JWTAuth(middleware/auth.go) validates the bearer token and setsuser_id,account_type, androleon the request context. It also compares the token's version againstCurrentTokenVersion, so bumping a user's token version invalidates every issued token (the revocation lever).- Every Backstage route (
/backstage/*, ranking weights) goes throughaccess.Authorizer.Require, which re-reads the caller's account type, role and standing from Postgres on each request and checks one capability, failing closed when the read errors. A demotion or suspension applies on the next request. Partner-scoped routes check a partner capability against the caller's membership through the same authorizer, which also reads the database (and refuses a suspended workspace). Capabilities flagged step-up or private are enforced by that middleware, not by handlers. Capability names carry their surface (backstage.,partner.), so one account type's role can't hold another surface's capability. - How each account type signs in, how long its sessions last and whether switching into it needs a step-up come from one registry (
access.AccountPolicy), enforced in every sign-in path; a method the policy doesn't allow answers like a wrong credential. Switching into Backstage and every linked-access change (including a Tomoda account linking or unlinking its personal account, which also proves the personal account's own password under its login lockout) need a server-verified step-up of the Tomoda credential (passkey or password): a single-use, five-minute token bound to caller, target account and purpose, rate-limited per account and spending the login lockout on failure. Tomoda accounts sign in directly with a passkey, or with a password plus a one-time code emailed to the account's address (never Google, Apple or password reset); the code step shares the login failure budget, and a wrong code reveals nothing about the password. Tomoda addresses must be at the Tomoda domain. The master admin is created by an operator task that reads its password secret with the operator's own credentials; the secret is not in any pod, and a rotation never re-activates or re-roles the account. Backstage sessions last 15 minutes per access token and at most 12 hours per refresh chain. Admins can't change their own access or remove the last admin.
Where. backend/internal/access/ (accounttypes.go, capabilities.go, authorizer.go, require.go), backend/internal/services/auth/link_service.go, login_code.go.
Transport security¶
Threat. Plain-HTTP requests, downgrade attacks, missing certificate pinning.
Mitigation. TLS is terminated by Traefik in the cluster (cert-manager / Let's Encrypt); prod hostnames are additionally proxied through Cloudflare with authenticated origin pulls. HSTS is enabled in production. Mobile clients pin to LetsEncrypt issuers transitively (no static cert pinning today).
Out of scope / known gaps¶
| Gap | Impact | Mitigation status |
|---|---|---|
| Per-user rate limits on authenticated routes | Compromised account can spam | Rely on IP + audit log |
| Captcha on registration | Determined attacker can defeat the email OTP loop | Considered for next milestone |
| Production WAF | No L7 inspection beyond our middleware | LB-level WAF on the roadmap |
Use the audit log + alerting rules to spot abuse that slips through these gates. For incident response, see Getting Started (app-side procedures) and the DevOps Runbook (cluster-side).