Skip to content

Latest commit

 

History

History
548 lines (429 loc) · 24.8 KB

auth-security.md

File metadata and controls

548 lines (429 loc) · 24.8 KB

Authentication and security

0. Admin console

/admin uses the same cookie session as the app but requires users.is_admin = true. Admin login replaces a normal user session with an admin session. A non-admin session is redirected to /admin/login?error=notadmin; admin APIs return 401. TFA-enabled admins must complete the normal app login first. The first admin is created only when there are zero admins and BOOND_ADMIN_PASSWORD (12+ characters) is set, or with boond admin create. No generated password is written to logs.

Environment values saved from the admin panel are stored in settings (secret values are AES-GCM encrypted with the sealing key) and applied on the next startup. Only changed keys are accepted by the UI. Database URL, JWT secret, and admin password are deliberately not editable there.

This chapter expands SPEC §§5 and 14. It is normative. Security controls are not optional for a public deployment, even a single-user one.

1. Principles

  • One identity per request. Cookie or bearer, never both.
  • Least privilege: a token grants only the user's data; sharing narrows, never widens.
  • Fail closed: absent Origin, unknown client, expired code, unverified redirect → deny.
  • No custom protocol requirements that official clients do not send (no CSRF tokens, no mandatory PKCE, no custom headers beyond Authorization and Content-Type).
  • Secrets are hashed or encrypted at rest; never logged.
  • Every state-changing request is auditable.

2. Credentials and storage

2.1 Signing and sealing keys

BOOND_JWT_SECRET is optional. When empty, 32 random bytes are generated once and stored at $BOOND_STORAGE_PATH/secrets/jwt.key (or BOOND_SECRET_PATH), mode 0600. Secrets shorter than 32 bytes are refused. The retired public sample value is replaced once with a new persisted key and a startup warning (sessions invalidated, TOTP re-enrolment required). The TOTP sealing key is derived with HKDF-SHA256 using a different info string, so a database dump cannot decrypt TOTP seeds with the JWT signing key alone. Rotating the JWT secret invalidates sessions and makes old TOTP secrets unreadable; affected users must re-enrol 2FA or use a recovery code.

Secret Storage Notes
Account password Argon2id hash 64 MiB, t=3, p=2, 16-byte salt, 32-byte key
Session token SHA-256 hash 32 random bytes; cookie holds plaintext
API access token SHA-256 hash Prefix rdt_; 32 random bytes
Refresh token SHA-256 hash Prefix rdr_; rotated on use
Test token SHA-256 hash 24 h TTL; shown once; never stored plaintext
OAuth client secret SHA-256 hash 32 random bytes; shown once at creation/rotation
OAuth authorization code SHA-256 hash 60 s TTL; single-use
JWT handoff HMAC/EdDSA signature 60 s TTL; jti replay cache
TOTP secret AES-GCM encrypted Derived sealing key, not the JWT signing key
Recovery code SHA-256 hash Normalize punctuation/case before hashing
FCM device token SHA-256 hash + encrypted copy Needed to send push
Invite token SHA-256 hash 32 random bytes, base64url
Email token SHA-256 hash Verify/reset; single-use

Encryption key: BOOND_ENCRYPTION_KEY (32 bytes, base64). Key rotation is out of scope for v1; document how to re-encrypt with a maintenance command.

Hashing: use Go's crypto/subtle.ConstantTimeCompare for token comparisons. Never compare secrets with ==.

3. Sessions

3.1 Creation

On login/TFA/social/JWT:

  1. Generate 32 random bytes (base64url, no padding).
  2. Store sha256(token) in sessions, with user, expiry, IP, UA.
  3. Set cookie boond_session=<token>; Path=/; HttpOnly; Secure; SameSite=Lax. Add Domain=<BOOND_COOKIE_DOMAIN> if configured. Local HTTP development (Android cleartext, localhost) may set BOOND_INSECURE_COOKIES=true to omit Secure; refuse that setting when BOOND_MODE=prod. Prefer a local TLS proxy for realistic testing.
  4. Rotate any pre-login session ID (session fixation defense): delete the old session row, set the new cookie.

3.2 Validation

  • Parse cookie, hash, look up non-revoked, non-expired session.
  • Check idle timeout (30 days) and absolute timeout (180 days). If idle-expired, revoke and treat as anonymous.
  • Update last_seen_at at most once per hour (write amplification control).
  • Load the user; if deleted_at is set, revoke and 401.
  • If the session is valid but the user has TFA newly enabled, do not invalidate; TFA applies at next login.
  • On password change, revoke all other sessions (keep current) and all refresh tokens.
  • On email change, revoke all other sessions and require re-verification.

3.3 Logout

  • GET /auth/logout revokes current session; all revokes all.
  • Clear cookie with Max-Age=0 and the same Path/Domain/Secure/SameSite.
  • Return JSON when no_redirect, else 303.
  • Logout is idempotent: an already-invalid session returns success.

3.4 Cookie scope and subdomains

For app.example.com + api.example.com, set BOOND_COOKIE_DOMAIN=.example.com so the cookie is sent to both. The app and API MUST share a registrable domain when a parent cookie is used; validate this at startup and refuse a Domain that does not cover both. For path-only deployments (https://example.com/api and https://example.com/app), a host-only cookie works. For a single origin, host-only is safest. Never set SameSite=None unless an embedding use case requires it; document the CSRF and third-party-cookie consequences (Safari/ITP will block it).

Safari/ITP: third-party cookies are blocked. Deploy API and app on the same site (subdomains count as same site if the registrable domain matches). The extension's Safari profile-cookie workaround is a client-side patch; Boond should not depend on it.

4. Password login

4.1 Request

POST /auth/email/login accepts:

{"email":"alice","password":"…"}

or form:

email=alice&password=…&redirect=%2Fmy%2F0

email may be a username. Normalize email to lowercase; usernames are case-insensitive.

4.2 Response

  • JSON: 200 {"result":true} + Set-Cookie, or {"result":true,"tfa":"…"}.
  • Form: 303 to redirect if it is a safe app-relative path or allowlisted absolute URL; otherwise to BOOND_APP_URL. On failure, 303 to BOOND_APP_URL/account/login?error=<generic message>.
  • The login page reads ?error and displays it (app:src/routes/account/login/index.js#L19-L35).

4.3 Defenses

  • Per-IP: 20 attempts / 5 minutes.
  • Per-account: 10 failures / 15 minutes, then exponential lockout (max 1 hour).
  • Constant-time password check; if the user does not exist, compare against a dummy hash to equalize timing.
  • Generic message: Invalid email or password.
  • Do not log the submitted password or the full email.
  • Optional CAPTCHA: only if configured; the client sends recaptcha on signup, not login. Do not require it for login by default.

5. Signup and email verification

POST /auth/email/signup creates the account but does not log in (the client calls login next). Steps:

  1. Validate username/email/password; normalize.
  2. Check uniqueness; 409 with field-specific message.
  3. Enforce BOOND_SIGNUP (open, closed, or invite) and rate-limit signup.
  4. Argon2id hash.
  5. Transaction: insert user, default group g1, user_stats row, config defaults.
  6. Generate a 32-byte verification token, store hash, send email with BOOND_APP_URL/account/confirm/<token>.
  7. Return the user (private fields appropriate to the creator) or {result:true}.

Verification:

  • POST /auth/email/confirm {token} marks verified; token single-use, 24 h TTL.
  • Unverified accounts cannot log in when SMTP is configured (BOOND_ALLOW_UNCONFIRMED_LOGIN=false by default). The first administrator is confirmed automatically.
  • POST /user/send_email_confirm resends, rate-limited.

Password reset:

  • POST /auth/email/lost {email} always succeeds. If the account exists, send a reset link (BOOND_APP_URL/account/recover/<token>) valid 1 hour.
  • POST /auth/email/recover {token,password} verifies, updates, revokes sessions/tokens, returns {result:true,email}.
  • Use the same response for unknown emails to avoid enumeration.

6. TOTP

6.1 Setup

  • GET /user/tfa: if no pending secret, generate 20 bytes, encrypt, store enabled=false; return base32 secret and a QR data URI for otpauth://totp/Boond:<email>?secret=…&issuer=Boond&algorithm=SHA1&digits=6&period=30.
  • POST /user/tfa {code}: verify ±1 step; set enabled; generate 10 recovery codes, return plaintext once; store hashes.
  • DELETE /user/tfa {code}: verify TOTP or recovery code; disable and delete secret.

6.2 Login

  • If enabled, password success creates a tfa_challenges row: id, user_id, token_hash, expires_at (5 min), attempts, used_at.
  • Return {"result":true,"tfa":"<challenge>"}. No session cookie.
  • POST /auth/tfa/{challenge} {code} verifies TOTP ±1 or unused recovery code; marks used; creates session; returns success.
  • Form variant redirects to the app.
  • DELETE /auth/tfa/{challenge} {code} verifies the code, disables TFA for the challenge's user, revokes the challenge, and does not create a session (the client's "disable while logging in" flow).
  • Rate limit: 5 attempts per challenge, 10 per account per 15 minutes, then 429. The account counter is shared by login and disable-at-login; recovery codes are consumed atomically and TOTP steps are single-use.
  • Recovery code use marks it used; users can regenerate at setup.

TOTP clock skew: accept ±1 step (30 s). Do not accept codes older than 90 s. Reject reuse of the same time step for a user (store last step).

7. Social and native login

7.1 Web Google/Apple

GET /auth/google?redirect=/my/0
  → 307 accounts.google.com/o/oauth2/v2/auth?client_id=…&redirect_uri=…&state=…
  → callback /auth/google/callback?code=…&state=…
  → verify state, exchange code, verify id_token, find/create user
  → set session cookie, 303 to redirect
  • State is HMAC-signed and contains the validated redirect and a nonce; 10 min TTL.
  • Verify id_token signature via JWKS, aud, iss, exp, email_verified.
  • Match by provider sub first, then verified email; link to an existing account only if the email is verified. Otherwise create a new user with a generated unique username.
  • Apple: same, with name from the first authorization only; handle private relay emails. Use identity_token JWKS verification.

7.2 Native mobile

GET /auth/google/native?access_token=…:

  • Verify the access token by calling Google's userinfo endpoint (not by trusting the client).
  • Require verified_email.
  • Find/create user; set session cookie; return {"result":true,"auth":true}.
  • If TFA enabled, return {"result":true,"auth":false,"tfa":"…"} and no session.

GET /auth/apple/native?code=…&identity_token=…&display_name=…:

  • Verify identity_token with Apple's JWKS; validate aud (bundle ID), iss, exp.
  • Optionally exchange code at Apple's token endpoint for server-side validation.
  • display_name is user-provided on first login only; sanitize and store as full name.
  • Same response shape.

The mobile app calls auth/{provider}/native + a query string (android:src/screens/auth/native/google.js#L20-L23; apple.ios.js#L17-L20), so the handler MUST accept query parameters, not a JSON body.

7.3 Provider failures

  • Invalid/expired token: 401 {"result":false,"auth":false,"error":"invalid_provider_token"}.
  • Provider not configured: 501 not_configured.
  • Email already exists with a different provider: link only if verified; otherwise 409 email_exists and instruct the user to sign in with the original method. Do not create duplicate accounts.

8. OAuth2 authorization server

8.1 Client registration

POST /oauth/client by a logged-in user. Validate:

  • name 1–200.
  • site absolute http(s), optional.
  • redirects array 1–20 of absolute URIs; allow http://localhost / 127.0.0.1 for development, otherwise require https. No fragments. No wildcards.
  • Generate 24-hex ID and 32-byte secret.

The client secret is displayed to the owner. Treat it as a password; encrypt at rest.

8.2 Authorization request

GET /oauth/authorize:

  1. Parse client_id, redirect_uri, response_type (default code), state, scope, code_challenge, code_challenge_method.
  2. If client_id invalid → 400 HTML, do not redirect.
  3. If redirect_uri missing or not an exact registered URI → 400 HTML, do not redirect.
  4. If response_type is present and not code → redirect with error=unsupported_response_type (only after validating redirect).
  5. If not logged in → 303 to app login with redirect = full authorize URL. After login, the app returns to the authorize URL.
  6. Render consent page: client name/icon/site, requesting user, account email, scopes (display only), Approve/Deny buttons, CSRF token in the form.
  7. Approve: create oauth_codes row with hashed code, client, user, redirect URI, PKCE challenge/method, 60 s TTL. Redirect to redirect_uri?code=…&state=….
  8. Deny: redirect with error=access_denied&state=….

The consent form POSTs to /oauth/authorize with decision=approve|deny, client_id, redirect_uri, state, code_challenge, and a CSRF token. Validate the CSRF token and that the client/redirect match the code request. Never accept an arbitrary redirect from the form.

PKCE: if code_challenge is present, require S256; store it; require a matching code_verifier at exchange. If absent, allow (public clients without PKCE still work). state is echoed but not required.

8.3 Token exchange

POST /oauth/access_token:

  • Parse form or JSON. grant_type required.
  • Client auth: client_id + client_secret in body or HTTP Basic. Compare with constant-time hash check.
  • authorization_code:
    • Validate code hash, unused, unexpired, client, redirect URI exact, PKCE.
    • Mark code used in the same transaction that creates tokens (prevent replay).
    • Issue access (14 days) + refresh (30 days) tokens; store hashes.
    • Return {access_token,refresh_token,expires,expires_in,token_type}.
  • refresh_token:
    • Validate hash, active, client.
    • Rotate: revoke old refresh, issue new access + refresh in one transaction.
    • Return the same shape.
  • Errors: HTTP 400 {"error":"invalid_request"|"invalid_client"|"invalid_grant"|"unsupported_grant_type"}. Do not use the standard JSON envelope for OAuth errors.

8.4 Consent page security

  • CSRF token bound to the session and the pending authorize request.
  • Escape client name/site/description (HTML).
  • Frame-ancestors 'none'; no third-party scripts.
  • Never auto-approve; the user must click.
  • If the client is owned by the same user, still show consent (or allow a trusted flag after the first approval; default show).

8.5 Token validation

  • Bearer tokens are looked up by hash, checked for revocation and expiry.
  • A token's user must be active.
  • On password change/account deletion, revoke all tokens.
  • last_used_at update at most once per 5 minutes.
  • Token scopes are not enforced in v1; store scope if provided and expose it in connections, but do not restrict. Document this as legacy-compatible.

9. Desktop JWT handoff

Flow:

  1. Desktop opens https://api.example.com/v1/auth/jwt?done_uri=rnio://account/jwt in the system browser.
  2. If not logged in, the API redirects to the app login with a redirect back to the JWT URL.
  3. With a session, the API mints a JWT and 302s to rnio://account/jwt?token=<jwt>.
  4. The OS opens the desktop app; it navigates the web app to #/account/jwt?token=….
  5. The web app calls POST /auth/jwt {token}; the API validates and sets a cookie.

JWT:

  • Header alg=EdDSA (or HS256 with a server secret), typ=JWT.
  • Claims: iss=BOOND_PUBLIC_URL, sub=<user id>, aud=boond-login, iat, exp=+60s, jti=<random>, purpose=desktop.
  • Verify signature, issuer, audience, expiry, and jti unused. Store used jti in a table/Redis until expiry; reject replay.
  • The token is single-use; do not allow it to create multiple sessions.
  • done_uri allowlist: exact schemes rnio, raindrop, rniomacsafari, plus configured HTTPS app origins. Reject javascript:, data:, file:, credentials in URL, and non-allowlisted hosts.

10. CSRF

Cookie-auth unsafe methods require:

  • a valid Origin or Referer in the allowlist; or
  • Sec-Fetch-Site: same-origin and an allowlisted Host when Origin is absent.

If neither is present → 403 csrf.

Native clients (the Android/iOS apps, CLI tools) send neither Origin nor Sec-Fetch-Site. They are not browsers and cannot be CSRF'd, but they must now identify themselves with X-Boond-Client: android or X-Boond-Client: ios. A cookie-authenticated write with neither browser metadata nor this marker is rejected with 403 csrf. Set BOOND_CSRF_REQUIRE_CLIENT=false only as a temporary compatibility escape hatch for pre-marker native builds; it is insecure and not recommended.

Allow:

  • app origin(s), API origin, public site origin;
  • extension origins from config (chrome-extension://<id>, moz-extension://<uuid>, safari-web-extension://<id>).

Do not require a CSRF token for API JSON requests; the official clients do not send one. For HTML forms (login, consent, account deletion), include a CSRF token in the form and validate it, because those are top-level browser navigations.

GET requests must be safe. The legacy GET /user/remove and GET /backup violate this; Boond keeps them for compatibility but adds confirmation/one-shot guards as described in the API reference. GET /auth/logout is a state change but is safe enough (logout CSRF only causes annoyance) and is required by clients; keep it.

11. SSRF and outbound fetch policy

Every outbound fetch (URL parse, archive, screenshot, iframeable, favicon, broken-link check, OAuth provider metadata) goes through one SafeFetcher:

  1. Parse URL; allow only http/https.
  2. Resolve DNS; reject if any resolved IP is loopback, private, link-local, multicast, unspecified, or cloud metadata (169.254.169.254, fd00:ec2::254).
  3. Pin the resolved IP for the request (prevent DNS rebinding) by dialing the IP with the original Host/SNI.
  4. Follow at most 5 redirects, re-running the IP check on each.
  5. Enforce connect timeout 5 s, total 20 s, response body limit 5 MiB for metadata, 70 MB for archives, 1 MB for favicons.
  6. Send a descriptive User-Agent with the instance URL and a contact.
  7. Respect robots.txt? For user-initiated parse, no (single fetch); for bulk scanners, rate-limit per host. Do not crawl.
  8. Do not forward cookies, Authorization headers, or the user's IP.
  9. Allow an operator to permit private ranges (intranet use) via BOOND_FETCH_ALLOW_PRIVATE=true; default false.

12. Upload security

  • Enforce MaxBytesReader before parsing multipart.
  • Stream to a temp file, compute SHA-256, sniff magic bytes with http.DetectContentType plus format-specific checks (image decode config, PDF header, EPUB zip).
  • Reject polyglots where feasible; never trust the filename extension.
  • Images: decode with a pixel limit (e.g. 50 MP) to prevent decompression bombs; re-encode to strip metadata/EXIF (or preserve orientation).
  • PDFs: do not render server-side without sandboxing; serve as attachment.
  • ZIP: reject .., absolute paths, symlinks, >100k entries, >2 GiB expanded, and nested compression bombs.
  • Store with random/opaque object keys; never use user filenames as paths.
  • Serve with X-Content-Type-Options: nosniff, Content-Security-Policy: sandbox, and Content-Disposition as appropriate.
  • Virus scanning: optional hook (BOOND_UPLOAD_SCAN_CMD); document that it is the operator's responsibility.

13. XSS and HTML sanitization

  • User-controlled HTML appears in: public pages, reader preview, article html, collection descriptions, notes, highlights, titles, OAuth client metadata.
  • Use html/template with autoescape for server-rendered pages.
  • Sanitize stored article HTML with an allowlist (bluemonday):
    • allow structural tags, links (http/https/mailto), images (http/https/data:image), tables, code, blockquotes;
    • strip <script>, <style> (or sanitize), <iframe> (except explicit embeds), forms, inputs, event handlers, javascript: URLs, data:text/html.
  • If ?html=1 returns article HTML, sanitize before storing and again before serving (defense in depth).
  • Public page CSP: default-src 'self'; img-src * data:; style-src 'self' 'unsafe-inline'; script-src 'self'; frame-ancestors 'none'.
  • Reader iframe CSP: default-src 'none'; img-src * data:; style-src 'unsafe-inline'; script-src 'sha256-<theme-script-hash>'; frame-ancestors <app origins>. The only allowed script is the tiny theme/font fragment handler, pinned by hash; never 'unsafe-inline' for scripts.
  • Embed pages need frame-ancestors *, but never combine with user HTML; only the trusted public-page template.

14. SQL injection and query safety

  • All SQL through pgx with parameters. Never concatenate user input.
  • Search parser produces an AST; the SQL builder emits placeholders and safe tsquery strings. Tag/collection IDs are numeric and validated.
  • ORDER BY uses an allowlist enum, not raw input.
  • LIMIT/OFFSET are integers with bounds.
  • Dynamic IN lists use = ANY($1::bigint[]), not string joining.

15. Authorization tests

For every endpoint, test the matrix:

Actor Owned Shared viewer Shared member Public Unrelated
Anonymous 401/404 401/404 401/404 read 404
Owner full full full full 404
Viewer — read read read 404
Member — read read/write read/write 404
Other user 404 404 404 read if public 404

Also test nested inheritance (share parent, access child), share removal, leaving, public→private transitions, and Trash access. A 404 (not 403) for unrelated resources is required to avoid enumeration.

16. Threat model (abbreviated)

Threat Mitigation
Credential stuffing rate limits, generic errors, optional CAPTCHA, TOTP
Session theft HttpOnly/Secure, short idle/absolute expiry, revoke on password change
CSRF Origin/Referer checks, SameSite=Lax, form CSRF tokens
XSS via notes/titles autoescape, sanitize HTML, CSP
SSRF via URL parse/archive SafeFetcher with IP pinning, private ranges blocked
Path traversal uploads random keys, no user filenames, zip guards
IDOR centralized policy, 404 for unrelated, tests
Token leakage hashes at rest, no logs, prefixes, revocation
OAuth redirect hijack exact redirect match, state, PKCE support
Replay of JWT/code single-use jti/code, short TTL
Enumeration generic login/reset responses, 404 policy
Abuse/DoS body limits, rate limits, job concurrency, timeouts
Malicious archive sandboxed renderer, sanitize, size limits, never execute scripts
Privilege escalation via sharing max(inherited, explicit), owner-only manage, tests
Deleted account data leak purge job, revoke tokens, audit
Backup leakage owner-only download, signed short-lived URLs, encryption at rest

17. Security headers

For HTML responses:

Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
X-Frame-Options: DENY            (except /share embeds)
Content-Security-Policy: …       (per route)
Permissions-Policy: camera=(), microphone=(), geolocation=()

Invite/join pages, login, password reset, and backup download pages MUST use Referrer-Policy: no-referrer so tokens never leak via Referer. Access logs MUST redact values of query keys token, code, state, access_token, refresh_token, code_challenge, and email; log only the key presence.

For JSON: Cache-Control: private, no-store, X-Content-Type-Options: nosniff.

For media: X-Content-Type-Options: nosniff, Content-Security-Policy: sandbox, Accept-Ranges: bytes, long cache for immutable objects.

18. Secrets and configuration

Required:

  • BOOND_ENCRYPTION_KEY (32 bytes base64)
  • BOOND_SESSION_SECRET (for signed CSRF/state; 32 bytes)
  • BOOND_JWT_KEY (Ed25519 private key or 32-byte HMAC; separate from session)
  • BOOND_DATABASE_URL
  • BOOND_PUBLIC_URL, BOOND_API_URL, BOOND_APP_URL, BOOND_MEDIA_URL
  • BOOND_ALLOWED_ORIGINS
  • SMTP settings (optional; if absent, emails are logged in dev)
  • BOOND_STORAGE_BACKEND=local|s3, plus local path or S3 endpoint/bucket/keys

Optional:

  • Google/Apple OAuth client IDs/secrets
  • FCM service account
  • S3 CDN base URL
  • BOOND_SCREENSHOTS=off|chromedp|external
  • BOOND_SEARCH=postgres|meilisearch
  • BOOND_REDIS_URL
  • BOOND_RECAPTCHA_SECRET

Never commit real secrets. .env.example documents names with placeholders. Production should use a secret manager or Docker secrets; environment variables are acceptable for a single-user self-host.