Architecture and design

This page describes how Ipseity is structured so that an operator can reason about behaviour, failure modes and where to look for problems. The implementations live in app/:

Module Responsibility
app/http_server.py The HTTP server (BaseHTTPRequestHandler), all routes, OAuth flow orchestration, RBAC enforcement, account self-service, audit.
app/oauth.py JWT encode/decode, key management, JWKS, introspection helpers, TOTP, PKCE.
app/k8s_store.py Storage backends: KubernetesStore (ConfigMap entities), KV/refresh-token/auth-code stores, audit; entity validation and password hashing.
app/encryption.py AES-256-GCM encryption at rest (FieldCipher + EncryptingStore).
app/providers.py External auth provider client plumbing (discovery, token exchange, userinfo).
app/config.py All runtime configuration (see configuration.md).
app/mailer.py Pluggable mail channel (SMTP / console / noop).
app/static/ The web console (the only UI; served by the same process).
app/storage.py The abstract storage interfaces (Store, KVStore, AuditStore) plus the short-TTL CachingStore wrapper.

Runtime model

Ipseity is a single stateless-ish HTTP process: the web console, the OAuth endpoints, the REST API and static assets are all served from one port (default 8080). Long-lived state lives only in the storage backend, so many replicas can run behind a load balancer and share state (HA). The per-realm RS256 signing keys and the AES encryption key are persisted to Kubernetes Secrets so replicas converge (see security.md).

The server is deliberately served with the Python standard library (http.server) and minimal dependencies — cryptography is the only runtime third-party package (see the Dockerfile).

Storage abstraction

All data flows through three small interfaces in app/storage.py:

  • Store — entities (principals, groups, roles, clients, providers, memberships), keyed by name.
  • KVStore — time-to-live key/value data: token revocation entries, login-attempt counters, principal lockouts, emailverify: links, pending consent, pending external-login state.
  • AuditStore — LoggingAuditStore emits AUDIT JSON lines on stdout and keeps a capped recent-event cache per realm and process for /api/audit. This backend is used in both Kubernetes and local development.

Entity and KV data use these implementations:

Backend Used when Characteristics
Kubernetes (KubernetesStore + companions) KUBERNETES_SERVICE_HOST is set and a service account token is available Persistent, shared across replicas, HA; entities → ConfigMaps.
In-memory (InMemoryStore + companions) local development / no cluster Thread-safe, per-process, ephemeral.

For entity data the Kubernetes backend stores each entity as one ConfigMap (ipseity-<entity-singular>-<name>) whose data.payload holds the JSON document. KV, auth-code and refresh-token records are ConfigMaps too, labelled by component (see kubernetes-resources.md). Entities are looked up case-insensitively (matching ConfigMap name rules); a Secret value is never overwritten unless explicitly upserted.

Caching (performance)

Entity reads are served through a short-lived, thread-safe CachingStore wrapped around the (encrypting) store. It caches each document (get) and each whole entity listing (list) for IPSEITY_ENTITY_CACHE_TTL_SECONDS (default 5, 0 disables caching). This is what makes request latency independent of the number of lookups: on a slow cluster a document is loaded from the Kubernetes API at most once per TTL window.

  • Write-through invalidation — upsert/delete invalidate the affected document and that entity's listing immediately, so a process never observes its own stale writes. Cross-replica propagation is bounded by the TTL (the same tradeoff as the revocation cache).
  • Bulk, not N+1 — RBAC permission resolution reads whole (cached) groups/roles listings once and builds an in-memory index keyed by lowercased name, instead of issuing one GET per referenced group/role. A single API call that previously needed 1 + N + M Kubernetes round trips now needs at most 1 object read + 2 listing reads, and repeats within the TTL are free. The same bulk-listing path serves _resolve_group_roles, _principal_grants_super, /api/meta permission discovery and email lookup.
  • Values are returned as deep copies so callers can never corrupt cached state, and the caches are LRU-bounded (objects and listings separately).
  • Not-found is not cached, so a document created right after a miss is visible immediately.

The per-request hot path is therefore: decode + validate the JWT (CPU), one revocation check (already bounded by the revocation cache), one principal read, and two cached listing reads for RBAC — typically zero or one Kubernetes call per request once warm.

Refresh-token cleanup

Kubernetes refresh-token records are deleted immediately on consumption or revocation. A daemon worker sweeps every known realm on startup and every 300 seconds, independently of login traffic. The same sweep runs opportunistically on token issuance, throttled with a per-store lock so concurrent requests and the worker do not duplicate scans. Successful scans use paginated component-filtered listings and remove expired, revoked and malformed records. Failed scans may be retried immediately; a realm failure does not stop cleanup in other realms, and discovery failures are retried on the next worker pass. Valid sessions remain until their configured expiry or explicit revocation.

Request model

OAuth flow (authorization-code + PKCE)

Consoles at /realms/<realm> receive a server-rendered JSON context containing only the selected realm, its managed client ID and the scoped API base. Root and the explicit main realm share that context. Each realm's client is reconciled with its store and resolved before external client lookup; managed IDs are reserved even for unknown realms. Ordinary users are allowed to complete the same login flow for Account self-service. See console.md.

  1. GET /oauth/authorize renders the login form (or starts an external provider login via external_provider).
  2. POST /oauth/authorize validates the client, redirect URI, requested scope, and the principal credentials (password + optional TOTP, login permission). Rate limiting and per-principal lockout are enforced here. When the request asks for JSON (Accept: application/json), the authorization code is returned as JSON instead of a 302 redirect — this is how the identity console signs in entirely in-page (fetch, no holding pages); browser form posts keep the classic redirect.
  3. If the client requires consent (require_consent), the principal approves or denies the requested scopes on a consent screen (POST /oauth/authorize/consent).
  4. An authorization code is issued (one-time, TTL IPSEITY_AUTH_CODE_TTL_SECONDS, single-realm, PKCE-bound).
  5. The client exchanges the code at POST /oauth/token with PKCE proof. Ipseity issues an access token (JWT), an OIDC id_token, and a rotating refresh token.

Token contents

For membership login, realm/username selects an explicit tenant membership. Password/MFA and lockout run in the main realm; a synthetic membership:<name> principal combines its home profile with only the tenant's role/group assignments. Codes, consent, access/ID tokens and refresh tokens carry the identity binding, so changing a membership cannot transfer an existing session. Each authenticated use through Ipseity rechecks home account state and the tenant membership. These principals are projections, never persisted as duplicate principal records or credentials.

  • Access token — a JWT signed with the realm's key carrying iss/sub/aud/scope/realm/iat/exp/jti/token_use, plus the principal's RBAC claims (username, groups, roles, permissions) and sid.
  • id_token — OIDC claims filtered by the granted scopes (profile, groups, roles, email).
  • Refresh token — opaque, random, single-use; rotated on every use and renewable up to IPSEITY_REFRESH_TOKEN_TTL_SECONDS.
  • Revocation is checked against the shared KVStore; a short in-memory negative cache (IPSEITY_REVOCATION_CACHE_TTL_SECONDS) bounds load.

API model

Every /api/* request requires a Bearer access token. Effective permissions are resolved from the principal (direct permissions + roles + groups) and enforced per endpoint (see identity.md). ipseity.super principals may add an X-Ipseity-Realm header to operate in another realm. The console uses /realms/<realm>/api/* aliases, parsed by _request_path before dispatch. The URL realm is checked against the token before principal lookup; header overrides remain available only to main-realm super admins through their own console. Bootstrap bypasses apply only to unauthenticated main-realm routes. Metadata filters the realm directory by the caller's privileges.

Realms and keys

  • Realms are Kubernetes namespaces; multi-realm behaviour and per-realm routing are described in realms.md.
  • Each realm has its own RS256 signing key; the single /oidc/jwks aggregates all realms' active + retired public keys so verifiers don't have to switch documents. Rotation keeps old keys until IPSEITY_OIDC_JWKS_RETIRED_KEYS.
  • The ipseity realm can use an env-configured key (IPSEITY_OIDC_SIGNING_PRIVATE_KEY_PEM/_FILE); other realms always use Secrets.

Security controls (summary)

  • Passwords: PBKDF2-SHA256 (IPSEITY_PBKDF2_ITERATIONS, default 600k); plaintext legacy values migrate on successful login.
  • MFA: optional per-principal TOTP (mfa_enabled + base32 mfa_secret), used by password and authorize flows; self-service supports enrollment/reset.
  • Lockout: IPSEITY_AUTH_MAX_ATTEMPTS failures within IPSEITY_AUTH_FAIL_WINDOW_SECONDS lock the principal for IPSEITY_AUTH_LOCKOUT_SECONDS (KV-backed, shared across replicas).
  • Rate limiting: configurable per-IP / per-client sliding window on /oauth/authorize and /oauth/token (429 on exceed).
  • Encryption at rest: AES-256-GCM on the secret fields only (principals.password, principals.mfa_secret, clients.client_secret), plus KV payloads with the same cipher.
  • CORS: per-client allowed_origins enforced on /oauth/* POSTs; preflight OPTIONS answered for known origins.
  • Audit: every security-relevant action emits an AUDIT JSON line with its realm. /api/audit (requires admin.audit.read) reads only the serving process's recent-event cache; aggregate container logs in Loki for durable history.

See security.md for the full treatment.

Observability

  • GET /healthz — reports datastore/backend identity, K8s init status, signing and encryption key ephemerality, mailer backend.
  • GET /oidc/.well-known/openid-configuration — discovery.
  • GET /oidc/jwks — signing keys (public).
  • GET /api/audit — recent local audit events (requires admin.audit.read).

Failure behaviour worth knowing

  • If IPSEITY_ENCRYPTION_KEY(FILE) is set but the key can't be loaded, startup fails closed (no silent ephemeral fallback).
  • If an RS256 key is required and neither configured nor persisted, startup fails once bootstrap is closed.
  • Audit write failures never fail the request (they're logged to stderr).
  • Rate limiting uses per-process counters; KV is shared across replicas.