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—LoggingAuditStoreemitsAUDITJSON 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/deleteinvalidate 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/roleslistings once and builds an in-memory index keyed by lowercased name, instead of issuing oneGETper referenced group/role. A single API call that previously needed1 + N + MKubernetes round trips now needs at most1object read +2listing reads, and repeats within the TTL are free. The same bulk-listing path serves_resolve_group_roles,_principal_grants_super,/api/metapermission 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.
GET /oauth/authorizerenders the login form (or starts an external provider login viaexternal_provider).POST /oauth/authorizevalidates the client, redirect URI, requested scope, and the principal credentials (password + optional TOTP,loginpermission). 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 a302redirect — this is how the identity console signs in entirely in-page (fetch, no holding pages); browser form posts keep the classic redirect.- If the client requires consent (
require_consent), the principal approves or denies the requested scopes on a consent screen (POST /oauth/authorize/consent). - An authorization code is issued (one-time, TTL
IPSEITY_AUTH_CODE_TTL_SECONDS, single-realm, PKCE-bound). - The client exchanges the code at
POST /oauth/tokenwith PKCE proof. Ipseity issues an access token (JWT), an OIDCid_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) andsid. - 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/jwksaggregates all realms' active + retired public keys so verifiers don't have to switch documents. Rotation keeps old keys untilIPSEITY_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+ base32mfa_secret), used by password and authorize flows; self-service supports enrollment/reset. - Lockout:
IPSEITY_AUTH_MAX_ATTEMPTSfailures withinIPSEITY_AUTH_FAIL_WINDOW_SECONDSlock the principal forIPSEITY_AUTH_LOCKOUT_SECONDS(KV-backed, shared across replicas). - Rate limiting: configurable per-IP / per-client sliding window on
/oauth/authorizeand/oauth/token(429on 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_originsenforced on/oauth/*POSTs; preflightOPTIONSanswered for known origins. - Audit: every security-relevant action emits an
AUDITJSON line with its realm./api/audit(requiresadmin.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 (requiresadmin.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.
