forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiB243c4e4Tahinli1 month ago15 commits

architecture.md16.9 KiBHistoryRawDownload

im architecture

im is the family's account service: an OpenID Connect provider, the people directory, and the service registry. It is the root of the family: in and iz depend on it, it depends on nothing. Read docs/contracts.md (the cross-app API) and docs/conventions.md (how code is written) first.

Status: design for the rebuild. The previous implementation (~/Documents/Code/Rust/old_im) is a feature reference only; its known defects are listed in section 11 so they are not carried over.


1. Goals

  • Boring and safe. im guards every other app. It changes rarely and carefully.
  • Feature parity with old im: password + TOTP sign-in, invites, password reset, two-sided email change, profile photo, preferences, sessions, connected apps, admin panel (users, services/clients, SMTP, policy, message, audit log, health), backups, CLI.
  • Better than old im: CSRF on every form, recovery codes, admin 2FA reset, key rotation, refresh-token reuse detection, back-channel logout, client-credentials machine tokens, no per-request introspection by apps, security headers and a strict CSP, every page translated.

Not goals now (listed in docs/backlog.md): passkeys, social sign-in, SCIM, multiple organisations, consent screens (every family client is first-party and trusted).


2. Crates and modules

im/
  Cargo.toml  config/im.example.toml  deploy/im.service  style/*.scss  docs/
  crates/
    im-core/   domain, store, migrations, config, secret, password, token, time, totp, jwt, authz, audit types, i18n-free
    im-web/    binary `im`: pages, OIDC endpoints, machine APIs, live, mail worker, back-channel worker, CLI

im-core

  • error.rs, time.rs, config.rs (+ settings.rs for UI overrides), secret.rs (instance key, seal/open)
  • password.rs (argon2id, policy check), token.rs (random tokens, hashing, constant-time compare, readable codes)
  • totp.rs (RFC 6238, SHA-1, 6 digits, 30 s, ±1 step, replay guard by last step)
  • jwt.rs (EdDSA sign/verify, header/claims structs; ed25519-dalek; no generic JWT library needed)
  • names.rs (email normalisation: trim, lowercase domain and local part, basic shape check)
  • authz.rs (actor kinds and actions, section 6)
  • model.rs (User, Session, Client, Service, Invite, ...)
  • store/ (mod.rs + one file per area: users.rs, sessions.rs, oidc.rs, clients.rs, invites.rs, links.rs (reset/email-change), mail.rs (outbox), backchannel.rs, directory.rs (change feed), audit.rs, settings.rs, snapshot.rs, migrate.rs)

im-web

  • main.rs, boot.rs, state.rs, admin_cli.rs
  • auth.rs (session cookie, current_user, require_user, require_admin, require_csrf, pre-CSRF, safe_next, pending-2FA sealed cookie), throttle.rs, client_ip.rs
  • oidc/ (discovery.rs, authorize.rs, token.rs, userinfo.rs, logout.rs, revoke.rs, introspect.rs, jwks.rs, keys.rs (rotation worker))
  • api/ machine routes (directory.rs, family.rs, photo.rs, machine_auth.rs = verify our own client-credentials JWTs)
  • pages/ (one file per page or area)
  • views/ (shell, components), i18n/ (key enums per area)
  • live.rs, mail/ (SMTP transport via lettre, outbox worker, templates), backchannel.rs (outbox worker), health.rs (service probe worker), audit.rs (writer), assets.rs
  • assets/nav.js, assets/pages.js (small page behaviours: dropdown search, copy button, QR toggle, photo upload progress), assets/offline.html, assets/sw.js

3. Data model

Conventions from docs/conventions.md section 4. Every table below is in 0001_init.sql unless noted.

users

  • id TEXT PK (ULID; this is the OIDC sub, never reused)
  • email TEXT NOT NULL, email_folded TEXT NOT NULL UNIQUE (normalised)
  • name TEXT NOT NULL (1–100 chars)
  • password_hash TEXT NOT NULL (argon2id PHC)
  • is_admin INTEGER NOT NULL DEFAULT 0, disabled_at TEXT NULL
  • totp_secret_sealed TEXT NULL, totp_enabled_at TEXT NULL, totp_last_step INTEGER NULL
  • locale TEXT NOT NULL DEFAULT 'en' CHECK (locale IN ('en','tr'))
  • zoneinfo TEXT NOT NULL DEFAULT 'Europe/Istanbul' (IANA name, validated against the jiff tz database)
  • theme TEXT NOT NULL DEFAULT 'system' CHECK IN ('system','light','dark')
  • photo_mime TEXT NULL, picture_version INTEGER NOT NULL DEFAULT 0
  • created_at, updated_at TEXT NOT NULL

recovery_codes: user_id FK CASCADE, code_hash TEXT, used_at TEXT NULL; PK (user_id, code_hash). Ten codes, xxxx-xxxx from the readable alphabet, shown once, regenerated as a set.

sessions (browser sessions at im)

  • id TEXT PK (ULID; this is the OIDC sid), user_id FK CASCADE, token_hash TEXT UNIQUE, csrf_token TEXT
  • created_at, expires_at, last_seen_at TEXT; ip TEXT, user_agent TEXT
  • auth_time TEXT, amr TEXT ('pwd' or 'pwd otp' or 'pwd rc')
  • Ended sessions are deleted (their back-channel jobs are queued first).

clients (OIDC clients; one per family app, plus any extra)

  • id TEXT PK (the client_id, ULID), name TEXT, secret_hash TEXT, secret_rotated_at TEXT
  • redirect_uris TEXT (JSON array), post_logout_redirect_uris TEXT (JSON array), backchannel_logout_uri TEXT NULL
  • allowed_scopes TEXT (space-separated; openid profile email plus machine scopes)
  • service_key TEXT NULL UNIQUE (family key such as in; NULL for a client that is not a family service)
  • created_at, disabled_at NULL

services (the switcher list)

  • key TEXT PK (^[a-z][a-z0-9-]{0,31}$), name TEXT, url TEXT (origin), position INTEGER, client_id TEXT NULL REFERENCES clients ON DELETE SET NULL
  • healthy INTEGER NULL, checked_at TEXT NULL, check_ms INTEGER NULL, check_error TEXT NULL
  • im's own row (key = 'im') is maintained at boot from base_url and cannot be removed.

auth_codes: code_hash PK, client_id, user_id, session_id, redirect_uri, scope, nonce, code_challenge, expires_at, used_at NULL. A second use of a used code revokes the refresh tokens issued from it (refresh_tokens.code_hash).

refresh_tokens: id PK, token_hash UNIQUE, family_id (first token of the chain), client_id, user_id, session_id FK sessions CASCADE, code_hash, scope, created_at, expires_at (30 days), used_at NULL, revoked_at NULL. Rotation on every use; presenting a used token revokes the whole family.

client_sessions: (session_id, client_id) PK, first_at, last_at. Which apps a browser session has signed in to: drives back-channel logout and the "connected apps" list.

signing_keys: kid PK (first 16 hex of SHA-256 of the public key), private_sealed, public_raw BLOB, created_at, activates_at, retires_at NULL. Exactly one key is "current": the newest with activates_at <= now and no retires_at.

invites: token_hash PK, email_folded, is_admin, invited_by NULL FK SET NULL, created_at, expires_at, accepted_at NULL. Creating a new invite for an address deletes its older pending invites.

account_links (password reset and email change)

  • token_hash PK, kind CHECK IN ('reset','email_old','email_new'), user_id FK CASCADE, pair_id NULL (both email-change halves share it), new_email NULL, created_at, expires_at, used_at NULL.

mail_outbox: id PK, kind (invite|reset|email_old|email_new|email_done|notice|test|security), to_addr, subject, body_text, state CHECK IN ('pending','sent','failed','abandoned'), attempts, next_attempt_at, last_error, created_at, sent_at. Links in bodies are never logged.

backchannel_outbox: id PK, client_id, sid NULL, sub, reason, state, attempts, next_attempt_at, last_error, created_at, done_at.

directory_changes: seq INTEGER PK AUTOINCREMENT, sub, kind CHECK IN ('member','deleted'), at. The cursor of the directory stream is seq. Rows older than 30 days are pruned; a cursor older than the oldest row gets resync.

audit_log: per conventions section 10.

settings: key PK, value, updated_at (UI overrides and sealed SMTP password).

Files beside the DB in data_dir: im.key, photos/<user_id> (0600, written by temp file + fsync + rename).


4. Routes

4.1 Browser pages

Path Who What
GET/POST /setup only while no user exists create the first admin
GET/POST /login anonymous email + password; then /login/2fa when TOTP is on
GET/POST /login/2fa pending cookie TOTP code or recovery code
POST /logout user end this session (back-channel to its apps)
GET/POST /logout (OIDC end-session) any section 4.2
GET/POST /forgot, GET/POST /reset/{token} anonymous password reset by mail
GET/POST /invite/{token} anonymous accept an invite: name + password
GET/POST /email/{token} anonymous confirm one side of an email change; GET never mutates
GET / user account home: profile card, connected apps, switcher
GET /account/profile + POSTs user name, photo upload/remove, email change request
GET /account/security + POSTs user password change, TOTP enroll/disable, recovery codes
GET /account/sessions + POST revoke user own browser sessions; revoke one or all others
GET /account/apps + POST revoke user apps signed in to; sign out of one app
GET /account/preferences + POST user language, time zone, theme
GET /people/{id} user public profile card
GET /admin/users (+ /{id}) and POSTs admin list, invite, disable/enable, delete, revoke sessions, rescue email, reset 2FA, promote/demote (not self, not the last admin)
GET /admin/services and POSTs admin services + their clients: add (key, name, origin → client with derived URIs, secret shown once), rename, reorder, rotate secret, edit scopes, remove
GET /admin/clients and POSTs admin non-family OIDC clients
GET /admin/mail and POSTs admin SMTP sender (password write-only, sealed), check connection, send test, outbox with retry
GET /admin/message + POST admin notice mail to everyone or one person (queued)
GET /admin/settings + POST admin policy (section 7), base URL, trusted proxies; UI > file > default
GET /admin/keys + POST rotate admin signing keys and their state
GET /admin/audit admin filters (action, actor, target, date range), keyset paging
GET /admin/health admin services health, outboxes, disk, DB size, last backup
GET /photo/{id} user photo bytes or initials SVG
GET /-/alive, GET /.../events per page live streams
GET /healthz, GET /assets/* anyone

4.2 OIDC and machine endpoints

As in docs/contracts.md sections 2–4: /.well-known/openid-configuration, /jwks.json, /authorize, /token (authorization_code, refresh_token, client_credentials), /userinfo, /logout (RP-initiated), /revoke (RFC 7009), /introspect (RFC 7662; for debugging and third-party clients; family apps do not use it), /api/v1/directory, /api/v1/directory/stream, /api/v1/people/{sub}/photo, /api/v1/family.

/authorize without a session redirects to /login?next=<the authorize URL>. After sign-in the user returns there and is redirected to the client. Invalid client_id or redirect_uri renders an error page (never redirects). Other errors redirect to the client with error= and state.


5. Sign-in, sessions, 2FA

  • Login order (forge): pre-CSRF → throttle (account key and IP key) → lookup (unknown → dummy verify) → password → disabled check (revealed only after a correct password) → 2FA step or session.
  • Pending 2FA: sealed cookie __Host-im_pending (user_id|expires|next|amr), SameSite=Strict, 5 minutes.
  • Second factor: 6 digits → TOTP with replay guard; xxxx-xxxx → recovery code (consumed). Throttled per user.
  • Session: 30 days idle-extended up to session_max_days (policy), cookie __Host-im_session. At most max_sessions per user: the oldest is ended (with back-channel) when exceeded.
  • Password change ends every other session; reset ends all. Disable and delete end all and queue back-channel logout by sub.
  • TOTP enroll: secret generated and held sealed in a pending state until a valid code confirms it; enrolling again while enabled requires the current code (old defect: re-visiting enroll reset it). Disabling TOTP requires the password and a code. Admin "reset 2FA" clears TOTP and recovery codes and is audited and mailed to the user.
  • Password policy: 10–256 chars, not containing the email local part or name words of ≥4 chars, not equal to the current one.

6. Authorization

authz::authorize(actor, action) -> Result<(), Denied> where actor is Anonymous, User { id, is_admin } or Client { id, scopes, service_key }, and action is an enum (ViewOwnAccount, EditOwnAccount, ViewPerson, Administer, ReadDirectory, ReadFamily, ...). Admin pages answer 404 to non-admins. Rules that are not role checks (last admin cannot be demoted or disabled, an admin cannot disable themself) live in the store as single conditional statements so they cannot race.


7. Policy settings (admin, UI > file > default)

Key Default Kind
registration invite (invite only; open sign-up is in the backlog) ReadOnly
invite_days 7 Live
reset_minutes 60 Live
email_change_hours 24 Live
session_max_days 30 Live
max_sessions 10 Live
require_2fa_for_admins true Live (an admin without TOTP is sent to enroll after sign-in)
base_url, trusted_proxies from file Restart
listen, database, data_dir from file ReadOnly

8. Workers (spawned at boot, stop with the stop flag)

  • mail: sends mail_outbox rows (5 attempts, backoff 1/5/15/60 min, then abandoned); SMTP via lettre, 465 implicit TLS, otherwise STARTTLS required. With no sender configured, rows wait without spending an attempt. Dev mode ([mail] log_only = true) writes mails to data_dir/mail-log/ instead.
  • backchannel: delivers backchannel_outbox rows per contracts.md 2.5.
  • keys: daily; creates the next key 24 h before rotation, retires old keys after 7 days.
  • health: probes services every 60 s (2 s timeout), updates services, bumps the admin health topic.
  • sweeper: hourly; deletes expired codes, links, sessions (queuing back-channel), old directory changes, sent mail older than 30 days.
  • backup (optional, [backup] dir): VACUUM INTO snapshot + photos + manifest on an interval, keeps N, pings a dead-man URL (/start, success, /fail).

9. Live

Topics: Account(user_id) (sessions, apps, profile, security changes; drives /-/alive account events, so a revoked session leaves at once), AdminUsers, AdminServices, AdminMail, AdminAudit, AdminHealth, Person(user_id). The directory stream for machines is separate (contracts.md 3.2) and reads directory_changes.


10. CLI

im admin create-admin <email> (prompts for name and password; IM_PASSWORD for scripts), im admin reset-2fa <email>, im admin disable <email>, im admin create-client <key> <name> <origin> (prints the secret once), im admin rotate-key, im admin backup --out DIR, im admin backup-verify SET, im admin restore --from SET --data-dir NEW, im admin audit-purge --older-than-days N. The CLI opens the database directly; it refuses to run while the server holds it unless --online is given, in which case it talks to the running server over a unix socket in data_dir/run/ with a per-boot token (forge admin_client.rs pattern).


11. Old defects not to repeat

From the inventory of old im: no CSRF tokens; signing key never rotated; refresh reuse not detected; access token scope hard-coded; email-change links leaked in a redirect query when mail failed; any client could claim unowned service rows; /directory, /photo and /family open to any client; live profile frames broadcast to everyone; revisiting enroll reset a confirmed TOTP; no way to disable TOTP or reset it for a locked-out user; login pages English-only; deleted users left reset links, email changes and photos behind; SMTP password left behind when the sender was cleared; cookie lifetime and DB lifetime disagreed; pack archives held the plaintext key; Google Fonts loaded from a third party; generated CSS committed.


12. Build order

  1. Scaffold: workspace, core basics (error, time, secret, token, password, config, store + migrate + 0001), boot, /healthz, assets pipeline, shell, nav.js, i18n skeleton, security headers, 404 page.
  2. Accounts: setup, login, 2FA, sessions, logout, throttle, account pages, preferences, photo.
  3. Mail outbox + SMTP; invites, password reset, email change.
  4. OIDC: keys, discovery, JWKS, authorize, token (all grants), userinfo, logout, revoke, introspect, back-channel.
  5. Machine APIs: directory + stream, photo, family.
  6. Admin: users, services/clients, mail, message, settings, keys, audit, health.
  7. Live topics, backups, CLI, deploy unit, README.