TIM
Rust re-implementation of the Token Identity Manager. TIM issues, tracks, and validates JSON Web Tokens; brokers OAuth2 / OIDC authentication against upstream identity providers; and answers RFC 7662 introspection requests. Backed by PostgreSQL.
Version: 0.2.0-alpha.2 · License: Apache-2.0
One-command demo
Bring up TIM and Postgres:
docker compose up -d
Health check:
curl http://localhost:8085/health
# {"status":"ok"}
Generate a custom JWT (privileged endpoints require an admin token — see Security hardening):
curl -sX POST http://localhost:8085/jwt/custom/generate \
-H 'content-type: application/json' \
-H "X-TIM-Admin-Token: $TIM_ADMIN_TOKEN" \
-d '{"JWTName":"demo","content":{"sub":"user-123"},"expirationInMinutes":60}'
Response:
{
"status": "created",
"jwt_name": "demo",
"token": "eyJhbGciOi...",
"expires_at": "2026-07-30T09:12:34Z"
}
Validate it (validate is public — no admin token needed):
curl -sX POST http://localhost:8085/jwt/custom/validate \
-H 'content-type: application/json' \
-d '{"token":"eyJhbGciOi..."}'
What TIM does
- Custom JWT lifecycle — generate, validate, extend (issue a fresh token preserving the old claims), revoke (single or bulk), and list a caller's tokens. Every issue is logged to an immutable audit table.
- OAuth2 / OIDC — proxy the authorization code flow to any
standard OIDC provider (Google, TARA, Azure AD, Okta, Auth0, or
any provider that publishes a discovery document). Full ID-token
validation: JWKS-fetched signature,
iss,aud,exp,nbf,iat(with configurable clock skew), and mandatory nonce match. - RFC 7662 introspection — a single endpoint that answers "is this token active?" for any TIM-issued custom JWT.
- Session persistence — sessions stored either in-process
(
session_store: "memory", default) or in Postgres with AEAD-encrypted profile data (session_store: "postgres"). Multi-replica-safe when Postgres is selected. - Legacy Buerokratt-TIM compatibility —
GET /jwt/userinfo,POST /jwt/blacklist,POST /jwt/custom-jwt-blackliststill present for the Ruuter DSL corpus. See Legacy compatibility.
What TIM does NOT do
- Password authentication (no local user database).
- Authorization ("can Alice call X?" — that's the calling service).
- Rate limiting (deploy behind an ingress that provides it).
- Admin HTTP endpoints for TIM itself (an admin token gates the privileged endpoints, but there is no admin surface for managing users, keys, or config at runtime).
- Secret management (mount the private key, database URL, admin token, and session encryption key from your secret store).
Where to next
- Getting started — install + first token in five minutes.
- Configuration — every field of
tim.yamland every env var TIM understands. - OAuth2 / OIDC — provider setup, discovery cache, session model, ID-token verification.
- Security hardening — admin gate, HTTP security headers, CORS, schema-role isolation, key rotation.
- Legacy compatibility — the three cookie-borne endpoints kept alive for the Ruuter DSL corpus.
- Migrating from JVM TIM — behavioural and shape changes vs. Buerokratt / JVM 2.0.
- Failure modes — every HTTP status TIM can return and its cause.
Getting started
Ten-minute install from an empty machine to first JWT.
1. Prerequisites
- Docker 20+ with Docker Compose v2 (
docker compose ...). curlandjq.openssl(only for generating a demo signing key + admin token — you already have this on every modern *nix).
Nothing else. TIM's runtime is a self-contained container image.
2. Get the source (only for local build)
If you just want the published image, skip to step 3.
git clone https://github.com/turnerrainer/TIM.git
cd TIM
3. Generate a demo RSA signing key
TIM signs JWTs with RS256. Generate a PKCS#8 PEM keypair — the
private half is what TIM loads; the public half is derived and
published automatically at /jwt/keys/public.
mkdir -p keys
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 \
-out keys/jwt-private.pem
chmod 644 keys/jwt-private.pem
Never commit this file. It is a secret. .gitignore already
excludes *.pem outside tests/fixtures/.
4. Set the required secrets
TIM refuses to start unless the DB URL and admin token are set.
export TIM_DATABASE_PASSWORD=demo-only-do-not-use-in-prod
export TIM_ADMIN_TOKEN=$(openssl rand -hex 32)
echo "Save this admin token; you need it for privileged endpoints:"
echo "$TIM_ADMIN_TOKEN"
The admin token gates the four privileged endpoints
(/jwt/custom/generate, /revoke, /revoke/bulk, /extend, plus
the legacy /jwt/blacklist and /jwt/custom-jwt-blacklist). See
Security hardening for how to
provision it in production.
Optional — if you also want persistent OAuth2 sessions across restarts:
export TIM_SESSION_ENCRYPTION_KEY=$(openssl rand -hex 32)
And in tim.yaml:
oauth2:
session_store: "postgres"
5. Bring TIM + Postgres up
docker compose up -d
Docker Compose starts:
tim-postgres— PostgreSQL 16, port 5432 on host.tim— TIM API server, port 8085 on host.
TIM waits for Postgres to be healthy, runs SQL migrations on first boot, and starts serving.
6. Verify the install
Health check:
curl -sf http://localhost:8085/health
# {"status":"ok"}
Check that security response headers are set:
curl -sI http://localhost:8085/health | grep -Ei 'content-security|strict-transport|x-frame|x-content-type|referrer'
# content-security-policy: default-src 'none'; frame-ancestors 'none'
# strict-transport-security: max-age=63072000; includeSubDomains
# referrer-policy: no-referrer
# x-frame-options: DENY
# x-content-type-options: nosniff
Public JWKS (proves the key loaded and TIM is signing-ready):
curl -s http://localhost:8085/jwt/keys/public | jq
# {
# "keys": [
# {"kty":"RSA","alg":"RS256","use":"sig","kid":"tim-rs-1","n":"...","e":"AQAB"}
# ]
# }
7. Generate your first JWT
TOKEN=$(curl -sX POST http://localhost:8085/jwt/custom/generate \
-H 'content-type: application/json' \
-H "X-TIM-Admin-Token: $TIM_ADMIN_TOKEN" \
-d '{"JWTName":"welcome","content":{"sub":"you"},"expirationInMinutes":15}' \
| jq -r .token)
echo "$TOKEN"
Try the same request without the admin header — you get 401:
curl -sX POST http://localhost:8085/jwt/custom/generate \
-H 'content-type: application/json' \
-d '{"JWTName":"nope","content":{"sub":"you"},"expirationInMinutes":15}' \
-o /dev/null -w 'HTTP=%{http_code}\n'
# HTTP=401
Decode the payload (no admin token needed to read a JWT — anyone holding it can decode):
echo "$TOKEN" | cut -d. -f2 | base64 -d 2>/dev/null | jq
Validate (public):
curl -sX POST http://localhost:8085/jwt/custom/validate \
-H 'content-type: application/json' \
-d "{\"token\":\"$TOKEN\"}" | jq
Response includes valid: true, active: true, the subject, and
the full claim map. HTTP status is 200 when active, 401 when not.
8. Introspect (RFC 7662)
curl -sX POST http://localhost:8085/introspect \
-d "token=$TOKEN" | jq
9. Revoke (admin-gated)
curl -sX POST http://localhost:8085/jwt/custom/revoke \
-H 'content-type: application/json' \
-H "X-TIM-Admin-Token: $TIM_ADMIN_TOKEN" \
-d "{\"token\":\"$TOKEN\",\"reason\":\"demo cleanup\"}" | jq
# {"status":"revoked","message":"Token has been successfully revoked"}
Second call returns 409 (idempotent):
curl -sX POST http://localhost:8085/jwt/custom/revoke \
-H 'content-type: application/json' \
-H "X-TIM-Admin-Token: $TIM_ADMIN_TOKEN" \
-d "{\"token\":\"$TOKEN\"}" \
-o /dev/null -w 'HTTP=%{http_code}\n'
# HTTP=409
Re-validate — HTTP 401, body reason: "revoked".
10. Legacy cookie-borne endpoints
If you are migrating existing Ruuter DSL flows that expect
GET /jwt/userinfo, POST /jwt/blacklist, or
POST /jwt/custom-jwt-blacklist, those endpoints are still present.
See Legacy compatibility for the mapping and
usage.
11. Verify the image cosign signature (optional, recommended)
Every published tag is signed keyless via cosign. From a machine
with cosign installed:
cosign verify docker.io/turnerrainer/tim:0.1.0-alpha.1 \
--certificate-identity-regexp '(?i)https://github\.com/turnerrainer/tim/' \
--certificate-oidc-issuer 'https://token.actions.githubusercontent.com'
Next
- Configure OAuth2 providers.
- Read the full config reference.
- Understand every HTTP status TIM returns.
- Harden for production.
Configuration
TIM loads its config from a YAML file. Search order at startup:
--config <path>CLI flag.TIM_CONFIG=<path>env var../tim.yamlor./tim.ymlin the working directory.- Built-in defaults (equivalent to the shipped
tim.yaml).
Every field has a safe default; override only what you need. Passwords and secrets are never in the config file itself — the config points at an env-var name, and startup refuses if that env var is missing when the referring section is configured.
This page is a walk-through. For a flat, alphabetised reference, see Configuration reference.
Sections
TIM's config has five top-level sections:
server— HTTP listener, request limits, public base URL.database— Postgres URL env var + pool tuning.jwt— signing key, issuer, audience validation, legacy cookie name.oauth2— provider registry, session store, discovery cache, sweeper.security— admin token, CORS, response headers.
server
server:
bind: "0.0.0.0"
port: 8085
max_request_bytes: 1048576
request_timeout_seconds: 30
public_base_url: "https://tim.example.com"
The default bind: "0.0.0.0" is container-friendly; for local dev
outside a container use 127.0.0.1.
public_base_url is used to synthesise the default OAuth2 callback
URL. Startup logs a WARN if empty AND bind != "127.0.0.1" because
that combination usually means "TIM is reachable from outside
localhost but doesn't know its own address."
database
database:
url_env: "TIM_DATABASE_URL"
min_connections: 2
max_connections: 10
auto_migrate: true
acquire_timeout_seconds: 30
idle_timeout_seconds: 600
max_lifetime_seconds: 1800
url_env is the name of the env var that holds the actual
postgres:// URL. Startup refuses if that env var is unset.
Pool knobs correspond one-to-one with sqlx's PgPoolOptions
methods. Setting a value to 0 skips calling the corresponding
.acquire_timeout() / .idle_timeout() / .max_lifetime() (i.e.,
uses sqlx's own default).
auto_migrate: true runs the SQL in migrations/ on every boot.
Set false when your CI already applied them.
jwt
jwt:
private_key_path: "/opt/tim/keys/jwt-private.pem"
key_id: "tim-rs-1"
issuer: "TIM"
audience:
validation_enabled: false
allowed: []
default: "tim-service"
max_claims_bytes: 32768
bulk_revoke_max: 100
cookie_name: "jwt"
private_key_path points at a PKCS#8 PEM file; the public half is
derived and served at /jwt/keys/public. Rotation is redeploy-only
— see Security hardening.
audience.validation_enabled: true makes TIM reject
POST /jwt/custom/generate requests whose audience is not in
audience.allowed. Off by default.
cookie_name is used only by the legacy compatibility
endpoints; it must match the name your DSL /
browser client uses.
oauth2
oauth2:
session_store: "memory" # or "postgres"
discovery_cache_ttl_seconds: 3600
session_ttl_seconds: 86400
session_sweep_interval_seconds: 60
state_max_age_seconds: 300
session_encryption_key_env: "TIM_SESSION_ENCRYPTION_KEY"
providers: {}
session_store — "memory" for single-replica dev,
"postgres" for production. Anything else fails at startup.
session_ttl_seconds — hard cap on session lifetime; the
effective expiry is min(this, expires_in-from-IdP). See
OAuth2 / OIDC.
state_max_age_seconds — how long an auth.oauth_state row
remains eligible for callback consumption. 5 min is standard.
session_sweep_interval_seconds — background task that deletes
expired sessions + stale state rows. 0 disables (tests only).
session_encryption_key_env — required when
session_store: "postgres". Name of the env var holding a 32-byte
key hex-encoded (64 chars). Startup refuses if unset in postgres
mode.
oauth2.providers.<id>
oauth2:
providers:
google:
name: "Google"
discovery_url: "https://accounts.google.com/.well-known/openid-configuration"
client_id_env: "TIM_GOOGLE_CLIENT_ID"
client_secret_env: "TIM_GOOGLE_CLIENT_SECRET"
scopes: ["openid", "profile", "email"]
claim_mappings:
first_name: "given_name"
last_name: "family_name"
email: "email"
token_validation:
clock_skew_seconds: 60
cache_ttl_seconds: 3600
allowed_redirect_uris:
- "https://tim.example.com/auth/callback/google"
claim_mappings are <canonical name> → <IdP claim name> —
what gets extracted into the session's profile map. If the ID token
has given_name: "Alice", first_name: "given_name" in the map
puts first_name: "Alice" on the session.
token_validation.clock_skew_seconds is real leeway applied to
exp, nbf, and iat during ID-token verification.
allowed_redirect_uris — see redirect_uri resolution in the
OAuth2 chapter. Empty list =
only the synthesised {public_base_url}/auth/callback/{id} is
accepted; explicit list = caller-supplied URI must be an exact
match; missing caller URI = first entry used as default.
security
security:
admin_token_env: "TIM_ADMIN_TOKEN"
require_admin_token: true
cors_allowed_origins: []
content_security_policy: "default-src 'none'; frame-ancestors 'none'"
strict_transport_security: "max-age=63072000; includeSubDomains"
referrer_policy: "no-referrer"
x_frame_options: "DENY"
x_content_type_options: "nosniff"
See Security hardening for every field.
require_admin_token: true is the default and enforced at startup;
setting to false and leaving admin_token_env: "" is a valid but
noisy combination (WARN in the log; do not deploy to production
this way).
introspection
RFC 7662 §2.1 recommends that POST /introspect require client
authentication. As of 0.4.0-alpha the gate is on by default
(audit FN1) — a config that does not set introspection.clients
refuses to start. Register every legitimate downstream caller:
introspection:
required_client_auth: true # default in 0.4.0-alpha
clients:
- client_id: "ruuter-classifier"
client_secret_env: "TIM_INTROSPECT_RUUTER_SECRET"
- client_id: "analytics-worker"
client_secret_env: "TIM_INTROSPECT_ANALYTICS_SECRET"
Callers present Authorization: Basic <base64(id:secret)> on every
request. Scheme name is case-insensitive per RFC 7235 §2.1 —
Basic, basic, BASIC all take the same path. Missing header,
unknown id, wrong secret → 401. Secret comparison is constant-time
(subtle::ConstantTimeEq). Startup fails if any referenced
client_secret_env is unset while the gate is on.
To opt out (dev, one-off scripts, running behind a proxy that authenticates the caller already):
introspection:
required_client_auth: false
Boot then emits a WARN naming the risk. Any deployment that reaches the public internet SHOULD keep the gate on.
Extending the gate to /jwt/custom/validate* (audit F-TIM-2)
/jwt/custom/validate and /jwt/custom/validate/boolean have the
same DoS shape as /introspect (crypto verify → denylist SELECT)
but ship without an auth gate by default — every internal service
that TIM issued a token for calls them constantly, so requiring
Basic auth is BC-breaking for existing callers.
For deployments where TIM is exposed to untrusted networks OR where the reverse proxy in front can forward a Basic header from its guards, opt in:
introspection:
gate_validation_endpoints: true
# Same clients: list as above — one gate, one secret rotation.
With the gate on, an unauthenticated POST /jwt/custom/validate
returns 401 BEFORE the DB SELECT + crypto verify run — so an
attacker cannot drive the DB pool to exhaustion.
Extending the gate to JVM 1.x compat validation endpoints (audit F-TIM-6)
Same shape for /jwt/userinfo, /jwt/custom-jwt-verify,
/jwt/custom-jwt-userinfo. These require a cookie present, but
the cookie value is not authenticated — any value drives a
crypto-verify + DB SELECT.
Enabling the gate breaks browser-direct DSL flows unless the reverse proxy forwards a Basic header on behalf of the browser:
introspection:
gate_jvm_compat_endpoints: true
The three gates (required_client_auth, gate_validation_endpoints,
gate_jvm_compat_endpoints) are independent — enable exactly the
subset your topology permits.
Environment variables
Every value TIM reads at runtime is one of:
- A field in
tim.yaml. - An env var named by an
_env-suffixed field intim.yaml. RUST_LOG— standardtracing_subscriber::EnvFiltersyntax (info,debug,tim=debug,sqlx=warn).TIM_CONFIG— path to the config file (alternative to--config).TIM_OFFLINE— see below.
There are no undocumented env vars.
Required env vars in a typical production deployment:
| Env var name | Purpose |
|---|---|
TIM_DATABASE_URL | Postgres connection URL. |
TIM_ADMIN_TOKEN | Admin token for privileged endpoints. |
TIM_SESSION_ENCRYPTION_KEY | Only when session_store: "postgres". |
TIM_<PROVIDER>_CLIENT_ID, _CLIENT_SECRET | One pair per OAuth2 provider. |
TIM_INTROSPECT_<CALLER>_SECRET | One per introspection client (see above). |
TIM_OFFLINE — pentest / break-test gate
Set TIM_OFFLINE=1 (or true, yes) to make every outbound HTTP
call refuse with 502 instead of hitting the network. Intended for
pentest engagements, adversarial CI, and any environment where TIM
must NOT accidentally reach a real upstream IdP:
- OIDC discovery (
GET .well-known/openid-configuration) - JWKS fetch (
GET jwks_uri) - Token exchange (
POST token_endpoint)
Boot emits a WARN naming the flag so operators see the posture in
the log stream. Value is snapshotted at first read; changing it
mid-run has no effect. Not a config field — env-only so a CI job
doesn't have to touch operator tim.yaml.
Sample production overrides
server:
public_base_url: "https://tim.example.com"
database:
url_env: "TIM_DATABASE_URL"
min_connections: 5
max_connections: 25
auto_migrate: false # run migrations from CI instead
jwt:
private_key_path: "/etc/secrets/tim/jwt-private.pem"
key_id: "prod-2026-01"
cookie_name: "jwt"
oauth2:
session_store: "postgres"
session_ttl_seconds: 3600 # tighter than default 24h
providers:
google:
name: "Google"
discovery_url: "https://accounts.google.com/.well-known/openid-configuration"
client_id_env: "TIM_GOOGLE_CLIENT_ID"
client_secret_env: "TIM_GOOGLE_CLIENT_SECRET"
scopes: ["openid", "profile", "email"]
allowed_redirect_uris:
- "https://tim.example.com/auth/callback/google"
security:
admin_token_env: "TIM_ADMIN_TOKEN"
require_admin_token: true
cors_allowed_origins:
- "https://app.example.com"
Env at deploy:
TIM_DATABASE_URL=postgres://tim:$(vault kv get -field=password secret/tim/db)@db:5432/tim
TIM_ADMIN_TOKEN=$(vault kv get -field=token secret/tim/admin)
TIM_SESSION_ENCRYPTION_KEY=$(vault kv get -field=key secret/tim/session)
TIM_GOOGLE_CLIENT_ID=<from Google Cloud Console>
TIM_GOOGLE_CLIENT_SECRET=<from Google Cloud Console>
OAuth2 / OIDC
TIM proxies the standard OAuth2 authorization code flow to any
OIDC-compliant identity provider. Providers are configured in
tim.yaml; no code changes are needed to add a new one.
Configuring a provider
Every provider is a block under oauth2.providers.<id>. See the
configuration reference for the full field
list.
Example — Google:
server:
# REQUIRED for the default callback URL to resolve outside
# localhost. If empty, callers MUST pass ?redirect_uri= explicitly
# AND it must be on the provider's allow-list.
public_base_url: "https://tim.example.com"
oauth2:
providers:
google:
name: "Google"
discovery_url: "https://accounts.google.com/.well-known/openid-configuration"
client_id_env: "TIM_GOOGLE_CLIENT_ID"
client_secret_env: "TIM_GOOGLE_CLIENT_SECRET"
scopes: ["openid", "profile", "email"]
claim_mappings:
first_name: "given_name"
last_name: "family_name"
email: "email"
token_validation:
clock_skew_seconds: 60
cache_ttl_seconds: 3600
# Redirect-URI allow-list. First entry is the default when the
# caller omits ?redirect_uri=; any caller-supplied value must
# match one of the entries exactly.
allowed_redirect_uris:
- "https://tim.example.com/auth/callback/google"
- "https://tim.example.com/auth/callback/google/staging"
At startup, TIM:
- Reads the provider's discovery document from
discovery_url(with retry-with-backoff on 5xx / network errors — three attempts). - Validates required fields (
issuer,authorization_endpoint,token_endpoint,jwks_uri) plus, when advertised,grant_types_supportedincludingauthorization_codeandresponse_types_supportedincludingcode. - Caches the discovery response for
oauth2.discovery_cache_ttl_seconds. - Prepares an on-demand JWKS cache — JWKS is fetched at first
ID-token verification and reused until
token_validation.cache_ttl_secondsexpires. - Resolves
client_id_envandclient_secret_env— refuses to start if either env var is unset.
Authorization code flow
-
GET /auth/login/{provider_id}?redirect_uri=<...>TIM generates a random
state+nonce(256 bits each), persists them toauth.oauth_state, and returns:{ "authorization_url": "https://accounts.google.com/o/oauth2/...&state=abc&nonce=def", "provider": "google", "state": "abc" }Consumer redirects the end-user to
authorization_url.redirect_uriresolution order:- Caller-supplied query param — accepted only if on the
provider's
allowed_redirect_uris. - First entry of
allowed_redirect_urisif that list is populated. - Synthesised from
server.public_base_urlas{public_base_url}/auth/callback/{provider_id}. - Error 400 if none of the above resolve.
- Caller-supplied query param — accepted only if on the
provider's
-
GET /auth/callback/{provider_id}?code=<...>&state=<...>TIM:
- Validates
state(single-use — atomicallyDELETE ... RETURNING); rejects rows older thanoauth2.state_max_age_seconds(default 300 s). - Exchanges
codefor tokens at the provider'stoken_endpoint. - Verifies the ID token — see next section.
- Creates a session; expiry capped at
min(oauth2.session_ttl_seconds, expires_in-from-token-response).
Response:
{ "status": "ok", "provider": "google", "session_id": "abc123...", "expires_at": "2026-07-30T13:45:00Z", "user_profile": { "user_id": "user-google-000", "first_name": "Alice", "last_name": "Example", "email": "alice@example.com" } }If the IdP returned an
error=(user cancelled, provider bounce), TIM bubbles the error as a structured 400 instead of a validation error:{ "status": "error", "provider": "google", "error": "access_denied", "error_description": "user cancelled" } - Validates
-
GET /auth/session/validate— session lookup + touch. -
GET /auth/profile— canonical profile from the session. -
POST /auth/logout— session invalidation.
Session-carrying endpoints accept three transports for the ID:
Authorization: Bearer sess_<id>(recommended for new callers)X-TIM-Session: <id>?session_id=<id>— legacy, logged at debug level
See Session storage below.
ID token verification
Every ID token returned by the token endpoint is validated per
OIDC Core §3.1.3.7 before the session is created. The verifier lives
in src/oauth2/idtoken.rs. It rejects the token if any of the
following fails:
- Header parses;
algis a supported asymmetric algorithm (RS/PS/ES 256/384/512).alg=noneand symmetric algorithms are refused outright. kid(if present in the header) resolves to a key in the provider's JWKS. When absent, TIM falls back to the first JWKS key whose algorithm family matches the header.- Signature verifies against the resolved key.
issclaim matchesdiscovery.issuerexactly.audclaim contains the configuredclient_id.exp> now (withtoken_validation.clock_skew_secondsleeway).nbf, if present, ≤ now (with leeway).iat≤ now + leeway (future-date guard).nonceMUST be present and MUST match the value TIM stored inauth.oauth_stateat login time. Comparison is constant-time.
Failure → 422 Unprocessable Entity, no session created.
Session storage
The session store is selected by oauth2.session_store. Two backends
are supported; anything else fails at startup.
session_store: "memory" (default)
- In-process
DashMap. - Zero config.
- Sessions do NOT survive process restart.
- Sessions do NOT span replicas.
- Fine for single-replica dev and small deployments behind a session-affinity load balancer.
session_store: "postgres"
- Persisted to
auth.session(migration0002_session_store.sql). - Profile data (which may contain PII from the IdP) is AEAD-encrypted at rest with chacha20poly1305.
- Required env var: name given by
oauth2.session_encryption_key_env(defaultTIM_SESSION_ENCRYPTION_KEY), 64-hex-character value = 32 bytes. - Survives restart; safe for multi-replica.
- Startup refuses if the encryption key env var is unset or malformed.
Both backends respect oauth2.session_ttl_seconds as an upper cap on
session lifetime — an oversized expires_in from the IdP does not
extend the session past this bound.
A background sweeper task, running every
oauth2.session_sweep_interval_seconds (default 60 s), deletes
expired sessions and orphaned auth.oauth_state rows. Set to 0 to
disable (test-only).
TARA (Estonian eID)
TARA is a standard OIDC provider — the Rust integration is
config-only, same shape as Google or Azure. Test-environment and
production endpoints differ only in the discovery URL. Regression
coverage: tests/it_oauth2_tara.rs (7 cases).
Config:
oauth2:
providers:
tara:
name: "TARA"
# Production. Test env: https://tara-test.ria.ee/oidc/.well-known/openid-configuration
discovery_url: "https://tara.ria.ee/oidc/.well-known/openid-configuration"
client_id_env: "TIM_TARA_CLIENT_ID"
client_secret_env: "TIM_TARA_CLIENT_SECRET"
scopes: ["openid"] # add "phone", "idcard", "mid" to restrict method
claim_mappings:
# TARA emits the 11-digit personal code as the JWT `sub`
# claim. Map into the profile as `personal_code` so
# downstream services find it under a canonical name.
personal_code: "sub"
first_name: "given_name"
last_name: "family_name"
date_of_birth: "date_of_birth"
acr: "acr" # low / substantial / high
amr: "amr" # ["mID"] / ["smart-id"] / ["idcard"] / ["eIDAS"]
token_validation:
clock_skew_seconds: 60
cache_ttl_seconds: 3600
allowed_redirect_uris:
- "https://tim.example.com/auth/callback/tara"
Claim shape received from TARA
| Claim | Type | Purpose |
|---|---|---|
sub | string (11 digits, e.g. "60001019906") | Estonian personal code — legally-attested identity |
given_name | string, UTF-8 | First name; Estonian characters (Kärt, Ööbik) preserved |
family_name | string, UTF-8 | Family name |
date_of_birth | string ("YYYY-MM-DD") | Optional |
acr | string | "low" / "substantial" / "high" — Level of Assurance |
amr | array of strings | Authentication method used (["mID"], ["smart-id"], ["idcard"], ["eIDAS"]) |
profile_attributes | object | Nested duplicate of some claims — NOT flattened by TIM; mapping is exact-key at the top level. |
Scope semantics
TARA-specific scopes restrict which authentication methods the user sees:
openidalone — any method available on TARA (default).openid phone— Mobile-ID only.openid idcard— ID-card only.openid mid— synonym for Mobile-ID.
Test vs prod
Swap discovery_url — nothing else changes:
- Test:
https://tara-test.ria.ee/oidc/.well-known/openid-configuration. - Prod:
https://tara.ria.ee/oidc/.well-known/openid-configuration.
Client registration is separate per environment; test uses
tara-test.ria.ee client credentials, prod uses tara.ria.ee
ones.
Level-of-Assurance policy enforcement
TIM extracts acr into the session profile but does not
enforce a minimum LoA. Downstream services that require a
"high"-LoA login (legal signature, sensitive personal data
retrieval) should check user_profile.acr themselves.
PKCE
The current flow does NOT emit PKCE parameters. auth.oauth_state
has a pkce_verifier column reserved for a future PKCE
implementation. The state parameter alone provides CSRF
protection today; PKCE adds interception protection for public
clients, which TIM does not currently target. Some TARA / Google
client registrations may mandate PKCE — until PKCE is wired end
to end, such client registrations will reject TIM's login attempts
with invalid_request.
Provider onboarding checklist
Adding a new provider:
- Create OAuth2 credentials at the provider (client ID + secret).
- Register your callback URLs — either
{server.public_base_url}/auth/callback/{provider_id}or whatever you put inallowed_redirect_uris. - Add a block to
tim.yamlunderoauth2.providers.<provider_id>. - Set
<CLIENT_ID_ENV>and<CLIENT_SECRET_ENV>in the environment. - Restart TIM. First
GET /auth/login/<provider_id>triggers discovery + validation; watch fordiscovery: provider does not advertise ...errors in the log if the provider's advertisements are non-standard. - Test with
curl http://localhost:8085/auth/providers.
Security hardening
TIM ships secure defaults, but its threat model changes with the deployment topology. This chapter walks through every knob that affects the security posture: what the default is, what the safer production setting looks like, and what breaks if you get it wrong.
Admin token
Config: security.admin_token_env (default
"TIM_ADMIN_TOKEN"), security.require_admin_token (default
true).
Gated endpoints:
POST /jwt/custom/generatePOST /jwt/custom/revokePOST /jwt/custom/revoke/bulkPOST /jwt/custom/extendPOST /jwt/custom-jwt-blacklist(legacy)POST /jwt/blacklist(legacy)
Transport: callers present the token via one of:
X-TIM-Admin-Token: <secret>(preferred)Authorization: Bearer <secret>(accepted for symmetry with modern APIs; use only when the caller is not simultaneously carrying a user JWT)
Comparison is constant-time (subtle::ConstantTimeEq).
Provisioning:
# 32 random bytes, hex-encoded — 64 chars. Store in your secrets
# manager alongside the DB password.
openssl rand -hex 32
Mount into the container's environment via docker-compose / k8s
secret / whatever your platform does. TIM refuses to boot if
require_admin_token: true (the default) and the referenced env
var is unset or empty.
Ungated mode (require_admin_token: false + empty
admin_token_env): available only for tests and single-machine dev.
Startup logs a WARN. Never deploy this way to a network reachable by
untrusted callers.
Endpoint auth invariants
Full audit performed 2026-09-18 (h2ck.me v1 NEXT-TASKS T-19). Every
route in src/router/mod.rs::build_router was classified. Regression
pin: tests/security_admin_surface_audit.rs.
Public-by-design (no credentials, cannot be gated without breaking the protocol or the operator's health-check story):
| Route | Why public |
|---|---|
GET /health, GET /healthz | LB / K8s liveness probe. |
GET /auth/health | OAuth registry status probe. |
GET /jwt/keys/public | RFC 7517 JWKS — verifiers pull unauth. |
GET /jwt/verification-key | Legacy JVM 1.x PEM mirror of JWKS. |
GET /introspect/types | RFC 7662-shaped discovery of supported token types. |
GET /auth/providers, GET /auth/providers/:id | Public provider catalogue (client picks a provider before it has a session). |
GET /auth/login/:id | Starts OAuth flow — must be reachable pre-session. |
GET /auth/callback/:id | Called by the IdP after user consent — must be reachable pre-session. |
Optionally gated (config flag decides): POST /introspect +
/jwt/custom/validate* + the three JVM cookie validation compat
endpoints — see Validation-endpoint DoS gate
below.
Always gated (admin, bearer, session, or cookie extractor):
every write path (generate, revoke*, extend*, blacklist*) and
every session-scoped read (/auth/session/validate, /auth/profile,
/auth/logout, /jwt/custom/list/me, all JVM cookie compat handlers).
The full auth matrix lives in API reference → Auth legend; this section only summarises the security invariant.
Verdict on Ruuter-style /_/* admin surface: not adopted. Ruuter's
/_/* env-gated prefix solves a different problem (per-environment
feature-flag surfaces for its runtime config UI). TIM's admin surface
is already comprehensive: every mutating endpoint runs behind
AdminAuth, every session read behind SessionAuth, no admin-shaped
functionality lives on a public route. Adding /_/* would give
attackers a distinct env-shape to probe without security benefit.
HTTP response headers
Config: security.content_security_policy,
security.strict_transport_security, security.referrer_policy,
security.x_frame_options, security.x_content_type_options.
Each is a string that becomes a response header on every route (including 404s). Empty string skips a given header.
Defaults are conservative — the shipped tim.yaml sets:
content_security_policy: "default-src 'none'; frame-ancestors 'none'"
strict_transport_security: "max-age=63072000; includeSubDomains"
referrer_policy: "no-referrer"
x_frame_options: "DENY"
x_content_type_options: "nosniff"
These are TIM's own responses. If your reverse proxy already sets
these headers, either leave TIM's alone (harmless — the proxy
usually preserves) or set the fields to "" to opt out.
CORS
Config: security.cors_allowed_origins (default []).
Behaviour:
[](default) — no CORS layer, noAccess-Control-*headers emitted. Same-origin callers work; cross-origin browser callers get blocked at the browser.["*"]— wildcardAccess-Control-Allow-Origin: *; browser callers from anywhere accepted; credentials NOT allowed (browser-side spec restriction with wildcard).- Explicit list — reflected origin match plus
Access-Control-Allow-Credentials: truefor cookie-carrying browsers. Recommended in production.
Example:
security:
cors_allowed_origins:
- "https://app.example.com"
- "https://admin.example.com"
Session encryption at rest
Config: oauth2.session_store: "postgres" +
oauth2.session_encryption_key_env (default
"TIM_SESSION_ENCRYPTION_KEY").
When postgres is selected, the profile map in auth.session is
sealed with chacha20poly1305 (12-byte random nonce prepended to the
ciphertext + tag). A 32-byte (64 hex chars) key is required; startup
refuses if the env var is unset or malformed.
Generate and mount:
openssl rand -hex 32
Key rotation: out-of-scope for the current release — rotating the key invalidates all existing sessions. Plan a rollout that drains sessions before rotating, or accept the forced re-login.
Database schema isolation (optional)
File: db/schema-security.sql (NOT auto-applied).
By default, TIM runs against a single Postgres role with full access
to both custom_jwt.* and auth.*. For defense-in-depth against a
bug that accidentally crosses schema boundaries, apply
db/schema-security.sql as a superuser once per deployment:
psql "$TIM_ADMIN_URL" \
-v tim.cjwt_password="$TIM_CJWT_PASSWORD" \
-v tim.auth_password="$TIM_AUTH_PASSWORD" \
-v tim.introspect_password="$TIM_INTROSPECT_PASSWORD" \
-f db/schema-security.sql
Then run three TIM instances (or one TIM behind a routing layer / PgBouncer) each connecting as the narrowest role:
tim_custom_jwt— RW oncustom_jwt.*, noauthaccess.tim_auth— RW onauth.*, nocustom_jwtaccess.tim_introspect— RO on both.
A bug that queries the wrong schema now raises permission denied
at the DB rather than silently succeeding. Not required for
correctness — offered for operators who want the extra layer.
Key rotation
The JWT signing key is loaded once at startup from a PKCS#8 PEM file
(jwt.private_key_path). Two rotation modes are supported:
Grace-period rotation (recommended)
For a rotation that does not require every downstream verifier to
refresh JWKS on the same second, configure jwt.previous_key alongside
the new active key:
jwt:
private_key_path: /opt/tim/keys/jwt-private-2027.pem
key_id: tim-rs-2
previous_key:
private_key_path: /opt/tim/keys/jwt-private-2026.pem
key_id: tim-rs-1
retires_at: "2027-01-15T00:00:00Z"
rotation_warn_days: 7 # boot WARN threshold, default 7
While retires_at is in the future:
GET /jwt/keys/publicreturns BOTH keys.- Newly signed tokens use
tim-rs-2(the current key). POST /introspectaccepts tokens signed by either key.
At or after retires_at, the previous key is refused on verification
and dropped from JWKS. Remove the jwt.previous_key block on the next
deploy to clean up.
tim doctor reports the rotation state as a jwt.previous_key check
row; boot emits WARN when the retirement cliff is within
jwt.rotation_warn_days days. Fleet-strongholds row U22/U23: this
grace-period mechanism is the runtime handshake that lets an operator
adopt an HSM/KMS-backed key without a coordinated fleet cut-over.
The legacy JVM 1.x /jwt/verification-key PEM endpoint always returns
the CURRENT key only — its callers cannot pick between candidates. Any
JVM consumer that needs multi-key support must migrate to
/jwt/keys/public (JWKS).
Cold-swap rotation (legacy)
If your downstream verifiers all refresh JWKS quickly and you can tolerate a brief window of "old-kid tokens" being refused:
- Generate a new PKCS#8 PEM keypair.
- Update
jwt.key_idto a new value. - Deploy a new TIM instance with the new key + new kid (no
jwt.previous_key). - Verify
/jwt/keys/publicon the new instance advertises the new kid. - Drain traffic from the old instance.
The old kid disappears from JWKS immediately on cutover. Downstream services that cache JWKS with a TTL keep validating old-kid tokens until their cache expires. Size the overlap window accordingly.
There is no runtime rotation endpoint. This is deliberate — see the "What TIM does NOT do" note in the Introduction.
Container posture
The shipped Dockerfile + docker-compose.yml enforce:
- Distroless runtime (
gcr.io/distroless/cc-debian12:nonroot) — no shell, no package manager, nocurl/wget, no useradd. Trivy--severity HIGH,CRITICALbaseline: 0. (Olddebian:13.6-slimruntime: 3 CRITICAL + 62 HIGH.) - Runs as
USER nonroot:nonroot(UID 65532) — no root at any point. - Read-only root filesystem (
read_only: true), tmpfs for/tmp. - All Linux capabilities dropped (
cap_drop: [ALL]). no-new-privilegesset.- Resource limits (CPU / memory) applied.
- Healthcheck via
tim healthcheck(probes/healthvia reqwest; no shell needed) every 30 s.
No tini. TIM is a single-process axum server — the child-reaping
role tini plays for multi-process containers is a no-op here. K8s or
docker run --init cover PID-1 signal forwarding if needed.
If you build your own image, keep these guarantees. If you run TIM outside Docker (systemd, Nomad), replicate the equivalent primitives.
Rate limiting
TIM does not rate-limit. Put a rate-limiting reverse proxy in
front: nginx limit_req, envoy local_ratelimit, cloud WAF, etc.
The admin-gated endpoints are the primary abuse targets; validate
and userinfo are relatively cheap but still worth capping.
Validation-endpoint DoS gate (audit F-TIM-2, F-TIM-6)
/introspect is not the only endpoint with the "crypto verify +
DB SELECT" shape. /jwt/custom/validate and the JVM 1.x compat
validation endpoints (/jwt/userinfo, /jwt/custom-jwt-verify,
/jwt/custom-jwt-userinfo) share the same DoS profile: an attacker
sending arbitrary tokens can drive the DB pool to exhaustion at low
cost. TIM ships an opt-in Basic-auth gate that reuses the same
introspection.clients list to protect these endpoints without
adding a second secret-rotation policy.
Turn on when TIM is exposed to untrusted networks OR when the reverse proxy in front can forward a Basic header on behalf of the DSL callers. See Configuration → introspection for the three independent axes:
introspection.required_client_auth— protects/introspect(defaulttruesince 0.4.0-alpha).introspection.gate_validation_endpoints— protects/jwt/custom/validate+/validate/boolean(defaultfalse).introspection.gate_jvm_compat_endpoints— protects the three JVM 1.x cookie-borne validation compat endpoints (defaultfalse— enabling breaks browser-direct DSL flows).
Pre-boot validation — tim doctor
Every deploy should run tim doctor before restarting the service.
The subcommand parses tim.yaml, resolves every referenced env var
(admin token, database URL, session encryption key, provider
credentials, introspection client secrets), verifies the JWT key
file exists and parses as PKCS#8 PEM, and prints a structured
PASS / WARN / FAIL table. It never binds a port, never opens a
Postgres connection, never touches the network — safe to run in
locked-down CI.
$ tim doctor
[ OK ] config: loaded from /etc/tim/tim.yaml
[ OK ] config: validate: all cross-field checks pass
[ OK ] jwt.private_key: parsed OK from /etc/secrets/tim/jwt-private.pem (kid=prod-2026-01)
[ OK ] database.url_env: `TIM_DATABASE_URL` resolved to a non-empty value
[ OK ] security.admin_token_env: `TIM_ADMIN_TOKEN` resolved (require_admin_token = true)
[ OK ] introspection.clients: client[ruuter].client_secret_env `TIM_INTROSPECT_RUUTER_SECRET` resolved
[ WARN ] jwt.audience: validation_enabled = false — every caller can request any audience.
---
Summary: 6 pass, 1 warn, 0 fail (total 7)
Exit codes: 0 on all-pass (WARN advisory), 1 on any FAIL or
(under --strict) any WARN, 2 on doctor itself failing. Wire
into deploy pipelines as a pre-flight gate:
tim doctor --strict || { echo "config unsafe, refusing deploy"; exit 1; }
Offline mode — TIM_OFFLINE=1
For pentest engagements, adversarial CI, or any environment where
TIM must NOT accidentally reach a real upstream IdP: set
TIM_OFFLINE=1 and every outbound HTTP call (discovery, JWKS,
token exchange) refuses with 502 instead of hitting the network.
Boot emits a WARN so operators see the flag in the log. Env-only
knob, snapshotted at first read; changing it mid-run has no
effect.
W3C Trace Context — every response carries traceparent
TIM emits traceparent: 00-<32-hex trace-id>-<16-hex span-id>-<2-hex flags>
and x-trace-id: <32-hex trace-id> on every response, including
4xx and 5xx. When a request arrives with a well-formed incoming
traceparent (typically from Ruuter, the fleet reverse proxy),
TIM echoes the caller's trace-id and preserves their sampling
decision (flags). Span-id is always fresh — TIM is a new span
within the (possibly-inherited) trace.
Downstream tooling can correlate a specific TIM response with TIM's log line by grepping the trace-id; the access-log line that names the request carries the same value:
INFO http_request_completed method=POST route=/introspect
status=200 duration_us=1234 trace_id=<same 32-hex value>
Strict request schemas — #[serde(deny_unknown_fields)]
Every modern JSON body / form / query DTO carries
#[serde(deny_unknown_fields)]. A caller sending
{"token":"x","admin_override":true} gets 4xx with the offending
field named, instead of the extra field being silently dropped.
Applies to:
POST /jwt/custom/{generate,validate,extend,revoke,revoke/bulk,list/me}POST /introspect(both JSON and form-encoded)POST /auth/logout(body),GET /auth/login/:id(query)
Deliberately exempt (compat / IdP-driven surfaces): JVM 1.x compat
endpoints, GET /auth/callback/:id (IdPs add per-request params
per RFC 6749), and IdP response DTOs (discovery, JWKS, token
response).
Threat model summary
| Attacker capability | Protection |
|---|---|
| Reach the network | Admin gate on state-changing endpoints (26); reverse-proxy rate limits; CORS if browser-borne |
| Steal a session ID | Session IDs travel via header (27); still short-lived (session_ttl_seconds cap, 9) |
| Steal an admin token | Constant-time compare (26); short-token lifetime by rotation; monitor for unusual X-TIM-Admin-Token traffic |
| Compromise the IdP token endpoint | ID-token JWKS signature verification (01); iss / aud / nonce (02) blocks forged tokens |
| Compromise the DB | Session profile encrypted at rest; JWT tokens hashed to jti in denylist (no plaintext in DB) |
| Bug in JWT service that touches auth schema | Optional per-schema role isolation (23) |
Downgrade to alg=none | Refused at token-header parse (see oauth2::idtoken::verify) |
Legacy compatibility
TIM-on-Rust keeps the eight cookie-borne and PEM-shaped endpoints
from the original Buerokratt TIM alive so the ~93 Ruuter DSL files
that reference check-user-authority.yml and logout.yml continue
to work unchanged. These endpoints coexist with the modern
header/body shapes — nothing was replaced; both surfaces hit the
same backing services.
The eight legacy endpoints and their roles:
| Path | Method | Purpose | Auth |
|---|---|---|---|
/healthz | GET | Alias for /health (same body) | public |
/jwt/verification-key | GET | Returns the JWT signing public key as PEM | public |
/jwt/userinfo | GET | Read JWT from <jwt.cookie_name> cookie → subject + claims | public |
/jwt/custom-jwt-verify | POST | Verify JWT from cookie named in body | public |
/jwt/custom-jwt-userinfo | POST | Read JWT from cookie named in body → subject + claims | public |
/jwt/custom-jwt-extend | POST | Extend JWT from cookie named in body; refresh cookie | admin |
/jwt/extend-jwt-session | GET | Extend JWT from <jwt.cookie_name> cookie; refresh cookie | admin |
/jwt/custom-jwt-blacklist | POST | Revoke JWT from cookie named in body | admin |
/jwt/blacklist | POST | Revoke by cookie / ?jwt=<uuid> / ?sessionId=<id> | admin |
Config
One knob:
jwt:
cookie_name: "jwt" # matches the JVM JwtSignatureConfig.cookieName
Set this to whatever name your browser client / DSL uses for the JWT cookie.
GET /jwt/userinfo — public
Reads the JWT from a cookie named <jwt.cookie_name>, runs it
through the same authenticated-bearer path as
POST /jwt/custom/list/me (signature + exp + denylist check), and
returns a UserInfo-shaped response.
Request:
GET /jwt/userinfo HTTP/1.1
Cookie: jwt=eyJhbGciOi...
Success — 200:
{
"userinfo": {
"subject": "user-42",
"issuer": "TIM",
"audience": ["tim-service"],
"expires_at": "2026-08-04T12:34:56Z",
"issued_at": "2026-08-04T11:34:56Z",
"jwt_id": "0e2b...-uuid",
"claims": {
"role": "admin",
"token_type": "custom_jwt",
"any": "other custom claims here"
}
}
}
Failure paths:
- 400 —
Cookieheader absent, or the named cookie is not among the set of cookies sent. - 401 — cookie present but the JWT is revoked, expired, or has an invalid signature.
Public: no admin token required.
POST /jwt/custom-jwt-blacklist — admin-gated
Matches the JVM shape: the request body is the name of the
cookie whose value to revoke. The cookie itself must be present on
the request (Cookie: <name>=<jwt>).
Request:
POST /jwt/custom-jwt-blacklist HTTP/1.1
Cookie: jwt=eyJhbGciOi...
X-TIM-Admin-Token: <secret>
Content-Type: text/plain
jwt
Body may be the bare cookie name (jwt) or a JSON-quoted string
("jwt") — TIM trims quotes and whitespace defensively.
Responses:
- 200
{"status": "blacklisted"}— newly revoked. - 409
{"status": "already_blacklisted"}— idempotent repeat. - 404
{"status": "not_found", "message": "..."}— named cookie wasn't on the request. - 400 — body was empty or the token couldn't be parsed.
POST /jwt/blacklist — admin-gated
Three parameter modes, matching the JVM. Priority order:
- Cookie mode —
Cookie: <jwt.cookie_name>=<jwt>on the request. Revokes that custom JWT. - Jti mode —
?jwt=<uuid>query param. Looks up the token's metadata (for its expiry timestamp) and adds to the denylist. - Session mode —
?sessionId=<id>query param. Revokes the OAuth2 session.
Request examples:
# Cookie mode
curl -X POST http://localhost:8085/jwt/blacklist \
-H "X-TIM-Admin-Token: $TIM_ADMIN_TOKEN" \
-H "Cookie: jwt=eyJhbGciOi..."
# Jti mode
curl -X POST "http://localhost:8085/jwt/blacklist?jwt=0e2b1234-5678-90ab-cdef-1234567890ab" \
-H "X-TIM-Admin-Token: $TIM_ADMIN_TOKEN"
# Session mode
curl -X POST "http://localhost:8085/jwt/blacklist?sessionId=abc123..." \
-H "X-TIM-Admin-Token: $TIM_ADMIN_TOKEN"
Responses:
| Status | Meaning |
|---|---|
200 {"status":"blacklisted"} | Custom JWT (cookie or jti mode) newly revoked. |
200 {"status":"logged_out"} | Session mode: session existed and was revoked. |
409 {"status":"already_blacklisted"} | Idempotent repeat (cookie / jti mode). |
404 {"status":"not_found"} | Jti mode: no TIM-issued JWT with this jti. Session mode: no such session. |
| 400 | None of the three parameter modes supplied. |
| 400 | ?jwt=<uuid> value is not a valid UUID string. |
| 400 | Cookie present but the JWT couldn't be parsed / signature fails. |
Behavioural difference vs. the JVM
The original JVM /blacklist returned 200 for every case — even
when nothing was actually blacklisted. TIM-on-Rust returns meaningful
status codes. DSLs that unconditionally treated 200 as success are
unaffected; DSLs that treated non-200 as error should learn to
accept 409 as "already done."
GET /healthz — public
Alias for GET /health. Same body ({"status":"ok"}), same
status code (200). Exists purely so JVM 1.x container healthchecks
and load-balancer probes that hit /healthz continue to work.
curl -sf http://localhost:8085/healthz
# {"status":"ok"}
GET /jwt/verification-key — public
Returns the JWT signing public key as a PKCS#1 PEM string. Legacy
Java consumers that verify TIM-signed JWTs with a PEM-based parser
use this shape. The modern equivalent (GET /jwt/keys/public)
returns a bare RFC 7517 JWKS instead.
curl -sf http://localhost:8085/jwt/verification-key
# -----BEGIN RSA PUBLIC KEY-----
# MIIBCgKCAQEA0vx7...
# -----END RSA PUBLIC KEY-----
Content-Type: text/plain.
POST /jwt/custom-jwt-verify — public
Body is the cookie name whose value TIM should verify. The cookie
itself must be on the request. Returns the same
ValidateResponse shape as POST /jwt/custom/validate.
curl -sX POST http://localhost:8085/jwt/custom-jwt-verify \
-H 'Cookie: my-app-jwt=eyJhbGciOi...' \
-d 'my-app-jwt'
# {"valid":true,"active":true,"subject":"user-42", ...}
Failure modes:
- Cookie present but token invalid / expired / revoked → 401 with
ValidateResponsebody. - Cookie missing from request → 401 with
{"valid": false, "reason": "cookie_not_present"}. - Empty body → 400.
POST /jwt/custom-jwt-userinfo — public
Body is the cookie name whose value to read. Response is a
UserInfo-shaped object with the JWT's claims. Differs from
GET /jwt/userinfo in that the caller specifies WHICH cookie —
GET /jwt/userinfo uses the configured jwt.cookie_name default.
curl -sX POST http://localhost:8085/jwt/custom-jwt-userinfo \
-H 'Cookie: SESSION_JWT=eyJhbGciOi...' \
-d 'SESSION_JWT'
# {
# "userinfo": {
# "subject": "user-42",
# "issuer": "TIM",
# "audience": ["tim-service"],
# "expires_at": "...",
# "issued_at": "...",
# "jwt_id": "0e2b...",
# "claims": {...}
# },
# "cookie_name": "SESSION_JWT"
# }
POST /jwt/custom-jwt-extend — admin-gated
Body is the cookie name; server reads that cookie, extends the JWT,
and returns Set-Cookie with the fresh token under the same name.
curl -sX POST http://localhost:8085/jwt/custom-jwt-extend \
-H "X-TIM-Admin-Token: $TIM_ADMIN_TOKEN" \
-H 'Cookie: jwt=eyJhbGciOi...' \
-d 'jwt' -i
# HTTP/1.1 200 OK
# set-cookie: jwt=eyJhbGciOi...NEW...; Path=/; HttpOnly; Secure; SameSite=Lax
# content-type: application/json
#
# {"status":"extended","jwt_name":"...","token":"eyJhbGciOi...NEW...","expires_at":"..."}
GET /jwt/extend-jwt-session — admin-gated
GET-based extend for browser-flow callers. Reads the JWT from the
configured jwt.cookie_name cookie (default "jwt") — no body,
no query param needed. Returns Set-Cookie with the refreshed token.
curl -sX GET http://localhost:8085/jwt/extend-jwt-session \
-H "X-TIM-Admin-Token: $TIM_ADMIN_TOKEN" \
-H 'Cookie: jwt=eyJhbGciOi...' -i
# HTTP/1.1 200 OK
# set-cookie: jwt=eyJhbGciOi...NEW...; Path=/; HttpOnly; Secure; SameSite=Lax
Priority when a request satisfies multiple modes
Cookie takes precedence over query params. If a caller sends both
Cookie: jwt=... and ?jwt=<uuid>, the cookie is used. This
matches the JVM.
Configuration example
Minimal legacy-friendly deployment:
jwt:
cookie_name: "jwt" # or whatever your DSL sets
security:
admin_token_env: "TIM_ADMIN_TOKEN"
require_admin_token: true
# If browser clients hit these endpoints from another origin:
cors_allowed_origins:
- "https://frontpage.example.com"
DSL callers add the admin token once, at their outbound HTTP config layer — no per-endpoint changes required.
Migrating from JVM TIM
This chapter documents every observable difference between TIM-on-Rust and the two upstream Java implementations:
- Original Buerokratt TIM (Java / Spring Boot, JVM 1.x).
- Buerostack JVM 2.0 (Java / Spring Boot 3.3.3 rewrite).
If you are migrating an existing deployment, use this as a
per-endpoint checklist. Every deviation was surfaced during the
post-alpha audit; see the CHANGELOG entry for [0.2.0-alpha.1]
for the full change list.
Endpoint availability matrix
| Endpoint | Buerokratt JVM 1.x | Buerostack JVM 2.0 | TIM-on-Rust |
|---|---|---|---|
GET /health | yes | yes | yes |
GET /jwt/keys/public | yes (wrapped) | yes (wrapped) | yes (bare JWKS, RFC 7517) |
POST /jwt/custom/generate | (was /jwt/custom-jwt-generate) | yes | yes, admin-gated |
POST /jwt/custom/validate | via /custom-jwt-verify | yes | yes |
POST /jwt/custom/validate/boolean | — | yes | yes |
POST /jwt/custom/revoke | via /custom-jwt-blacklist | yes | yes, admin-gated |
POST /jwt/custom/revoke/bulk | — | yes | yes, admin-gated |
POST /jwt/custom/extend | via /custom-jwt-extend | yes | yes, admin-gated |
POST /jwt/custom/list/me | — | yes | yes |
POST /introspect | — | yes | yes |
GET /introspect/types | — | yes | yes |
GET /auth/providers | (implicit) | yes | yes |
GET /auth/login/{id} | via Spring Security OAuth2 | yes | yes |
GET /auth/callback/{id} | via /authenticate | yes | yes (+ real ID-token verification) |
GET /auth/session/validate | — | yes | yes |
GET /auth/profile | via /userinfo (cookie) | yes | yes |
POST /auth/logout | via /logout | yes | yes |
GET /jwt/userinfo | yes (cookie) | dropped | restored (legacy, public) |
POST /jwt/blacklist | yes | dropped | restored (legacy, admin-gated) |
POST /jwt/custom-jwt-blacklist | yes | dropped | restored (legacy, admin-gated) |
The three restored legacy endpoints are documented in Legacy compatibility. They coexist with the modern shapes; nothing was replaced.
Response-shape changes
POST /jwt/custom/generate
| Field | JVM 2.0 | TIM-on-Rust |
|---|---|---|
status | "created" | "created" ← parity restored |
TIM-on-Rust 0.1.0-alpha.1 briefly returned "ok"; the current build
returns "created" to match JVM 2.0.
POST /jwt/custom/extend
| Field | JVM 2.0 | TIM-on-Rust |
|---|---|---|
status | "extended" | "extended" ← parity restored |
jwt_name on missing | "EXTENDED_TOKEN" | "EXTENDED_TOKEN" ← parity restored |
Default expirationInMinutes | 60 | 60 ← parity restored |
| HTTP on expired/revoked | 401 | 422 (Rust chose 422 as more precise; JVM callers switching on 401 need to add 422 to their branch) |
POST /jwt/custom/revoke
| Situation | JVM 2.0 | TIM-on-Rust |
|---|---|---|
| Newly revoked | 200 {"status": "revoked"} | 200 {"status": "revoked", "message": "..."} |
| Idempotent repeat | 409 {"status": "already_revoked"} | 409 {"status": "already_revoked", "message": "..."} |
Parity restored.
POST /jwt/custom/validate
| Situation | JVM 2.0 | TIM-on-Rust |
|---|---|---|
| Valid + active | 200 | 200 |
| Invalid or revoked | 401 with response body | 401 ← parity restored |
Callers that assumed 200 for every response now need to check HTTP
status. The response body's valid/active fields still tell the
full story.
POST /jwt/custom/list/me
| Field | JVM 2.0 | TIM-on-Rust |
|---|---|---|
Request offset | page number | page number (opt into row-offset with by_row: true) |
Request limit | page size (default 20) | page size (default 20) |
Request jwtName | accepted (JVM bug: silently ignored) | accepted and honoured |
Response page | present | present |
Response size | present | present |
Response total_pages | present | present |
Response offset | absent | additionally present (row offset) |
Response limit | absent | additionally present (page size) |
| Denylist check | yes | yes ← now checked (was missing in initial Rust cut) |
GET /jwt/keys/public
| Shape | JVM 2.0 | TIM-on-Rust |
|---|---|---|
| Response | {"jwk": "<stringified JWKS>"} | {"keys": [...]} (bare RFC 7517 JWKS) |
Breaking difference kept for RFC-correctness. Clients that
unwrapped .jwk and parsed the inner string must switch to parsing
the top-level keys directly.
OAuth2 flow changes
ID-token verification
JVM 2.0 — JwtValidationService.validateIdToken verifies
signature, iss, aud, exp, nbf, iat, and nonce.
TIM-on-Rust 0.1.0-alpha.1 — did not verify signature at all (critical bug fixed post-alpha.1).
Current — matches JVM 2.0 behaviour and adds: constant-time
nonce comparison, mandatory nonce presence, refusal of alg=none
and symmetric algorithms.
Session storage
JVM 2.0 — in-process ConcurrentHashMap; no persistence.
TIM-on-Rust 0.1.0-alpha.1 — same, but the config knob was silently ignored.
Current — oauth2.session_store: "memory" | "postgres". Postgres
mode persists across restart, spans replicas, encrypts profile
data at rest with chacha20poly1305.
Session TTL
JVM 2.0 — min(24h, expires_in).
TIM-on-Rust 0.1.0-alpha.1 — expires_in unbounded.
Current — min(oauth2.session_ttl_seconds, expires_in). Matches
JVM's cap semantics.
redirect_uri handling
Buerokratt / JVM 2.0 — hard-coded http://localhost:8085/...
(TODO comment in both).
TIM-on-Rust 0.1.0-alpha.1 — accepted any caller-supplied value without validation.
Current — per-provider allowed_redirect_uris allow-list;
falls back to {server.public_base_url}/auth/callback/{id}. Invalid
input rejected 400.
Callback error handling
JVM 2.0 — accepts error= param, bubbles to caller.
TIM-on-Rust 0.1.0-alpha.1 — required code=, so IdP-returned
errors surfaced as "missing field code" 400s.
Current — matches JVM.
auth.oauth_state hygiene
JVM 2.0 — in-memory state, 5-minute expiry checked in
validateCallback.
TIM-on-Rust 0.1.0-alpha.1 — DB-backed state, no age check, no sweep — rows accumulated indefinitely.
Current — DB-backed state with 5-minute default age cap
(oauth2.state_max_age_seconds) enforced in the DELETE ... RETURNING clause, plus a background sweeper every
oauth2.session_sweep_interval_seconds.
Config surface — new fields
| Field | Purpose | Default |
|---|---|---|
server.public_base_url | External TIM URL; used for default callback synthesis | "" |
database.acquire_timeout_seconds | Pool timeout knob | 30 |
database.idle_timeout_seconds | Pool timeout knob | 600 |
database.max_lifetime_seconds | Pool timeout knob | 1800 |
jwt.cookie_name | Cookie name for legacy endpoints | "jwt" |
oauth2.state_max_age_seconds | oauth_state row max age | 300 |
oauth2.session_sweep_interval_seconds | Sweeper interval | 60 |
oauth2.session_encryption_key_env | Env var for AEAD key | "TIM_SESSION_ENCRYPTION_KEY" |
oauth2.providers.<id>.allowed_redirect_uris | Per-provider allow-list | [] |
security.admin_token_env | Env var for admin token | "TIM_ADMIN_TOKEN" (empty in defaults) |
security.require_admin_token | Refuse boot if unresolved | true |
security.cors_allowed_origins | CORS origin list | [] |
security.content_security_policy | CSP header | (see Security hardening) |
security.strict_transport_security | HSTS header | (see Security hardening) |
security.referrer_policy | Referrer-Policy header | "no-referrer" |
security.x_frame_options | X-Frame-Options header | "DENY" |
security.x_content_type_options | X-Content-Type-Options header | "nosniff" |
Migration checklist
For each existing JVM 2.0 deployment:
- Generate an admin token and set
TIM_ADMIN_TOKENin the environment. - Set
server.public_base_urlintim.yaml. - For every provider block, add
allowed_redirect_uris: [<canonical URL>]. - Decide session store: keep
memory(single replica) or switch topostgres(multi replica). If Postgres, generate a 32-byte hex key and setTIM_SESSION_ENCRYPTION_KEY. - Update client-side callers that switched on
body.status == "ok"— the value is now"created"for generate and"extended"for extend. - Update client-side callers that expected 200 for every validate response — invalid tokens now return 401.
- Update client-side callers that expected 200 for idempotent revokes — repeat revocations now return 409.
- If you consume
/jwt/keys/public, unwrap the JVM's{"jwk": "..."}wrapper — TIM-on-Rust returns the bare JWKS. - If any Ruuter DSL calls
/jwt/userinfo,/jwt/blacklist, or/jwt/custom-jwt-blacklist, no changes are required — those endpoints are still present. See Legacy compatibility.
For deployments coming from Buerokratt JVM 1.x (not 2.0), additionally:
- Rename all endpoint calls per the table at the top of this page.
- The
UserInfoshape from the original/jwt/userinfohas been simplified — Estonian-specific fields (channel type, personal ID) are gone; extract them from theclaimsmap instead. - IP allow-listing (
security.allowlist.jwt) is not implemented; gate at the reverse proxy or rely on the admin token.
Failure modes
Every HTTP status TIM can return, and what caused it.
Framework-level
| Status | Cause | Response body |
|---|---|---|
| 200 | Success. | Endpoint-specific JSON. |
| 400 | Invalid JSON, missing required field, or field out of range. | {"error":"bad_request","detail":"..."} |
| 401 | Bearer / admin token required and missing / malformed. | {"error":"unauthorized"} |
| 403 | Bearer token valid but caller not permitted. | {"error":"forbidden"} |
| 404 | No such route, or entity not found. | {"error":"not_found","detail":"..."} |
| 405 | Method not allowed on that route. | {"error":"method_not_allowed"} |
| 408 | Request exceeded server.request_timeout_seconds. | {"error":"request_timeout"} |
| 409 | Idempotent-conflict (already-revoked / already-blacklisted). | {"status":"already_revoked","message":"..."} |
| 413 | Request body exceeded server.max_request_bytes or jwt.max_claims_bytes. | {"error":"payload_too_large","max":<n>} |
| 415 | Unsupported Content-Type (only introspect enforces this, and only when body parses in neither JSON nor form). | {"error":"unsupported_media_type"} |
| 422 | Semantic validation failure (invalid audience, ID token failed OIDC checks, extend of expired/revoked token). | {"error":"unprocessable_entity","detail":"..."} |
| 500 | Unhandled internal error. Every occurrence logs with the request ID. | {"error":"internal_error"} — no internals leaked. |
| 502 | Upstream (OAuth2 provider or JWKS endpoint) returned a malformed or unexpected response. | {"error":"bad_gateway","detail":"..."} |
| 504 | Upstream OAuth2 provider exceeded the timeout. | {"error":"upstream_timeout","detail":"..."} |
Custom JWT endpoints
POST /jwt/custom/generate — admin-gated
| Status | Cause |
|---|---|
| 200 | Token issued and persisted. status: "created". |
| 400 | Missing JWTName, missing / invalid expirationInMinutes, malformed content. |
| 401 | Admin token missing or wrong. |
| 413 | content payload larger than jwt.max_claims_bytes. |
| 422 | audience present but validation is enabled and none of the values are in jwt.audience.allowed. |
POST /jwt/custom/validate and /validate/boolean
| Status | Cause |
|---|---|
| 200 | Token verified and active. |
| 401 | Token invalid, expired, or revoked — the response body's reason field explains why. |
| 400 | Missing token field. |
Response body carries valid + active:
valid: true, active: true— signature OK, not expired, not revoked → HTTP 200.valid: true, active: false, reason: "expired"→ HTTP 401.valid: true, active: false, reason: "revoked"→ HTTP 401.valid: false, reason: "signature_mismatch"→ HTTP 401.valid: true, active: false, reason: "audience_mismatch"→ HTTP 401.valid: true, active: false, reason: "issuer_mismatch"→ HTTP 401.
The /validate/boolean variant returns plain true/false in the
body with the same status semantics.
POST /jwt/custom/revoke — admin-gated
| Status | Cause |
|---|---|
| 200 | Token added to denylist. {"status":"revoked","message":"..."} |
| 409 | Already denylisted. {"status":"already_revoked","message":"..."} |
| 400 | Missing token field, or token signature invalid. |
| 401 | Admin token missing or wrong. |
POST /jwt/custom/revoke/bulk — admin-gated
| Status | Cause |
|---|---|
| 200 | Every token in the batch newly revoked. |
| 207 | Multi-status: mix of newly / already / failed. |
| 409 | All tokens were already revoked (nothing changed). |
| 400 | tokens empty, larger than jwt.bulk_revoke_max, or every token failed. |
| 401 | Admin token missing or wrong. |
Response body:
{
"newly_revoked": 3,
"already_revoked": 1,
"failed": 2,
"results": [
{"token": "eyJhbGciOi...", "status": "revoked"},
{"token": "eyJhbGciOi...", "status": "already"},
{"token": "eyJhbGciOi...", "status": "failed", "reason": "malformed"}
]
}
POST /jwt/custom/extend — admin-gated
| Status | Cause |
|---|---|
| 200 | New token issued, old token added to denylist. status: "extended". |
| 400 | Missing token field. |
| 401 | Admin token missing or wrong. |
| 422 | Old token is already expired or revoked. |
POST /jwt/custom/list/me
| Status | Cause |
|---|---|
| 200 | Paginated result. |
| 401 | Missing / malformed Authorization: Bearer <jwt> header, or the bearer JWT is revoked / expired / has an invalid signature. |
| 400 | limit > 200 or offset negative. |
Legacy compat endpoints
GET /jwt/userinfo — public
| Status | Cause |
|---|---|
| 200 | Cookie present and JWT valid. Response body carries userinfo object. |
| 400 | Cookie header absent, or the named cookie missing. |
| 401 | Cookie present but JWT revoked / expired / bad signature. |
POST /jwt/custom-jwt-blacklist — admin-gated
| Status | Cause |
|---|---|
| 200 | {"status":"blacklisted"}. |
| 409 | {"status":"already_blacklisted"}. |
| 404 | Named cookie not present on the request. |
| 400 | Body empty, or JWT signature invalid. |
| 401 | Admin token missing or wrong. |
POST /jwt/blacklist — admin-gated
| Status | Cause |
|---|---|
| 200 | Custom JWT (cookie / jti) newly revoked OR session (sessionId) logged out. |
| 409 | Custom JWT already revoked. |
| 404 | Jti mode: no TIM-issued JWT with that jti. Session mode: no such session. |
| 400 | None of the three parameter modes supplied; or ?jwt=<uuid> value not a valid UUID; or cookie JWT unparseable. |
| 401 | Admin token missing or wrong. |
OAuth2 endpoints
GET /auth/login/{provider_id}
| Status | Cause |
|---|---|
| 200 | Authorization URL returned. |
| 400 | Caller-supplied redirect_uri not on the provider's allow-list. |
| 400 | No redirect_uri supplied and neither the allow-list nor server.public_base_url yield a default. |
| 404 | Unknown provider ID. |
| 502 | Upstream discovery fetch failed (after retries). |
| 504 | Discovery fetch timed out. |
GET /auth/callback/{provider_id}
| Status | Cause |
|---|---|
| 200 | Session created. |
| 400 | Missing code or state query param. |
| 400 | IdP returned error= — body includes error and error_description from the provider. |
| 404 | Unknown provider ID. |
| 422 | State does not match a persisted state row (CSRF / replay / expired past state_max_age_seconds). |
| 422 | Token response has no id_token. |
| 422 | ID-token verification failed (bad iss, aud, nonce, signature, exp, nbf, iat; symmetric or alg=none refused; kid not in JWKS). |
| 502 | Token exchange with provider failed / JWKS fetch failed. |
| 504 | Token exchange timed out. |
GET /auth/session/validate and /profile
| Status | Cause |
|---|---|
| 200 | Session found; body indicates valid + expiry. |
| 401 | No session ID supplied via any of the three transports. |
| 404 | Session not found or expired. |
POST /auth/logout
| Status | Cause |
|---|---|
| 200 | Session existed and was revoked, OR unknown session (idempotent). Body's status distinguishes. |
| 401 | No session ID supplied. |
Note: unlike blacklist, logout intentionally does not 404 for unknown sessions — a browser retry after network flakiness shouldn't produce a spurious error surface.
Introspection
POST /introspect
| Status | Cause |
|---|---|
| 200 | Standard RFC 7662 response (may report active: false). |
| 400 | Missing token in body, or body parses in neither JSON nor form. |
The response never distinguishes "unknown token" from "revoked
token" — both are bare {"active": false} per RFC 7662 §2.2, on
every failure path.
Framework
GET /health
Always 200 {"status":"ok"} — a 200 here proves the process is
alive and can bind. It does NOT prove database connectivity;
database problems surface as 500 on the actual endpoints. This is
deliberate — a "deep" healthcheck that hits the DB would take TIM
down as a side effect of DB blips.
GET /auth/health
Reports the OAuth2 registry status: available providers, provider IDs, timestamp. Always 200 unless TIM itself is unhealthy.
Response headers on every response
Every response (including error paths and 404s) carries the security
headers configured in security.*. Default set:
content-security-policy: default-src 'none'; frame-ancestors 'none'
strict-transport-security: max-age=63072000; includeSubDomains
referrer-policy: no-referrer
x-frame-options: DENY
x-content-type-options: nosniff
Empty strings in the config skip a given header. See Security hardening.
API reference
Compact, endpoint-by-endpoint reference. Every route TIM exposes, its method, the auth it requires, and the input/output shape.
For failure paths and status-code semantics, see Failure modes.
Auth legend
| Symbol | Meaning |
|---|---|
| — | Public (no credentials required). |
| admin | Requires X-TIM-Admin-Token: <secret> or Authorization: Bearer <secret>. |
| bearer | Requires Authorization: Bearer <TIM-issued JWT> — signature, exp, and denylist checked. |
| session | Requires Authorization: Bearer sess_<id>, X-TIM-Session: <id>, or legacy ?session_id=<id>. |
| cookie | Requires Cookie: <jwt.cookie_name>=<TIM-issued JWT>. |
Framework
| Route | Auth | Purpose |
|---|---|---|
GET /health | — | Liveness check. Always {"status":"ok"}. |
Custom JWT
| Route | Auth | Purpose |
|---|---|---|
POST /jwt/custom/generate | admin | Issue a new JWT. |
POST /jwt/custom/validate | — | Structured validation (returns 401 when inactive). |
POST /jwt/custom/validate/boolean | — | Plain-text true/false, same auth semantics. |
POST /jwt/custom/revoke | admin | Single-token denylist. 200 new, 409 already. |
POST /jwt/custom/revoke/bulk | admin | Up to jwt.bulk_revoke_max per call. |
POST /jwt/custom/extend | admin | Reissue with preserved claims; old goes to denylist. |
POST /jwt/custom/list/me | bearer | Paginated own-token list. |
GET /jwt/keys/public | — | RFC 7517 JWKS with the signing public key. |
POST /jwt/custom/generate
Request:
{
"JWTName": "session-token",
"content": {
"sub": "user-42",
"role": "admin"
},
"expirationInMinutes": 60,
"audience": "downstream-api",
"setCookie": false
}
JWTName(required) — free-form label; stored in metadata.content(required) — map of claim-name → JSON value.subis extracted into the signedsubclaim; all other keys land in the flatten-extras. Reserved names (iss,aud,exp,iat,jti,nbf) are stripped.token_type: "custom_jwt"is injected automatically.expirationInMinutes(required, > 0).audience(optional) — string or list of strings.setCookie(optional bool) — if true, the response carriesSet-Cookie: <JWTName>=<token>; Path=/; HttpOnly; Secure; SameSite=Lax.
Also accepts snake-case aliases: jwt_name, expiration_in_minutes,
set_cookie.
Response (200):
{
"status": "created",
"jwt_name": "session-token",
"token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6...",
"expires_at": "2026-08-04T13:34:56Z"
}
POST /jwt/custom/validate
Request:
{
"token": "eyJhbGciOi...",
"audience": "expected-aud",
"issuer": "TIM",
"reason": null
}
audience and issuer are optional expectations; when set, TIM
enforces them and returns audience_mismatch / issuer_mismatch
on failure.
Response (200 when active, 401 when not):
{
"valid": true,
"active": true,
"reason": null,
"subject": "user-42",
"issuer": "TIM",
"audience": ["tim-service"],
"expires_at": "2026-08-04T13:34:56Z",
"issued_at": "2026-08-04T12:34:56Z",
"jwt_id": "0e2b...-uuid",
"claims": { "role": "admin", "token_type": "custom_jwt" }
}
reason is one of: "expired", "revoked", "signature_mismatch",
"audience_mismatch", "issuer_mismatch".
POST /jwt/custom/validate/boolean
Same request. Response body is plain true or false with
Content-Type: text/plain. HTTP status is 200 when true, 401 when
false.
POST /jwt/custom/revoke
Request:
{ "token": "eyJhbGciOi...", "reason": "user logout" }
Response 200:
{ "status": "revoked", "message": "Token has been successfully revoked" }
Response 409 (idempotent repeat):
{ "status": "already_revoked", "message": "Token was already revoked" }
POST /jwt/custom/revoke/bulk
Request:
{ "tokens": ["eyJhbGciOi...", "eyJhbGciOi...", "..."], "reason": "batch" }
Response 200 / 207 / 409 / 400 depending on outcome. See Failure modes.
POST /jwt/custom/extend
Request:
{ "token": "eyJhbGciOi...", "expirationInMinutes": 30, "setCookie": true }
expirationInMinutes defaults to 60. setCookie: true adds
Set-Cookie: EXTENDED_TOKEN=<new>; Path=/; HttpOnly; Secure; SameSite=Lax.
Response 200:
{
"status": "extended",
"jwt_name": "session-token",
"token": "eyJhbGciOi...",
"expires_at": "2026-08-04T14:04:56Z"
}
POST /jwt/custom/list/me
Bearer authentication required. Request body optional:
{
"offset": 0,
"limit": 20,
"byRow": false,
"issuedAfter": "2026-07-01T00:00:00Z",
"issuedBefore": null,
"expiresAfter": null,
"expiresBefore": null,
"jwtName": null
}
Semantics — offset is a page number by default (JVM parity).
Set byRow: true to interpret offset as a row offset instead.
limit is page size (cap 200).
Response:
{
"tokens": [
{
"jti": "0e2b...-uuid",
"subject": "user-42",
"jwt_name": "session-token",
"issued_at": "2026-08-04T12:34:56Z",
"expires_at": "2026-08-04T13:34:56Z",
"issuer": "TIM",
"audience": "tim-service",
"status": "active"
}
],
"pagination": {
"total": 42,
"offset": 0,
"limit": 20,
"page": 0,
"size": 20,
"total_pages": 3
}
}
Both pagination shapes are populated concurrently for parity with either JVM or row-based clients.
GET /jwt/keys/public
No request body. Response is a bare RFC 7517 JWKS:
{
"keys": [
{
"kty": "RSA",
"alg": "RS256",
"use": "sig",
"kid": "tim-rs-1",
"n": "0vx7ag...",
"e": "AQAB"
}
]
}
Note: differs from the JVM 2.0 shape which wrapped this in
{"jwk": "<stringified>"}. See
Migrating from JVM TIM.
Introspection
| Route | Auth | Purpose |
|---|---|---|
POST /introspect | — | RFC 7662 introspection. Accepts JSON or form. |
GET /introspect/types | — | Supported token types. |
POST /introspect
Accepts one of:
Content-Type: application/x-www-form-urlencoded— bodytoken=<jwt>&token_type_hint=<optional>.Content-Type: application/json— body{"token": "...", "token_type_hint": "..."}.- No or unknown Content-Type — TIM tries JSON, then form (best-effort parse).
Response 200 for active tokens:
{
"active": true,
"iss": "TIM",
"sub": "user-42",
"aud": ["tim-service"],
"exp": 1723456789,
"iat": 1723453189,
"jti": "0e2b...-uuid",
"token_type": "custom_jwt",
"extra_claims": { "role": "admin" }
}
Every inactive path (unknown, revoked, expired, wrong issuer, bad
signature) returns bare {"active": false} per RFC 7662 §2.2.
OAuth2 / OIDC
| Route | Auth | Purpose |
|---|---|---|
GET /auth/providers | — | List configured providers. |
GET /auth/providers/{id} | — | One provider's public config. |
GET /auth/login/{id} | — | Start authorization code flow. |
GET /auth/callback/{id} | — | Complete flow (called by IdP redirect). |
GET /auth/session/validate | session | Verify + touch. |
GET /auth/profile | session | Return canonical profile map. |
POST /auth/logout | session | Revoke session. Body may include {"reason":"..."}. |
GET /auth/health | — | Registry / provider status. |
Session transports (accepted on any session-marked endpoint):
Authorization: Bearer sess_<id>X-TIM-Session: <id>?session_id=<id>(legacy)
Legacy compat (Buerokratt shape)
| Route | Auth | Purpose |
|---|---|---|
GET /healthz | — | Alias for GET /health. |
GET /jwt/verification-key | — | PEM-formatted JWT signing public key. |
GET /jwt/userinfo | cookie | Decode cookie JWT → subject + claims. |
POST /jwt/custom-jwt-verify | cookie | Verify JWT from cookie named in body. |
POST /jwt/custom-jwt-userinfo | cookie | Read JWT from cookie named in body → subject + claims. |
POST /jwt/custom-jwt-extend | admin + cookie | Extend JWT from cookie named in body; refresh cookie. |
GET /jwt/extend-jwt-session | admin + cookie | Extend JWT from jwt.cookie_name cookie; refresh cookie. |
POST /jwt/custom-jwt-blacklist | admin + cookie | Revoke JWT from named cookie (body = cookie name). |
POST /jwt/blacklist | admin | Three modes: cookie, ?jwt=<uuid>, ?sessionId=<id>. |
See Legacy compatibility for full request / response examples.
Configuration reference
Flat, alphabetised reference. Every field TIM accepts in tim.yaml,
its type, its default, and one line about what it does. For a
walk-through with examples, see Configuration.
server
| Field | Type | Default | Description |
|---|---|---|---|
server.bind | string | "0.0.0.0" | Bind address. |
server.port | u16 | 8085 | TCP listener port. |
server.max_request_bytes | usize | 1048576 | Global request body cap. |
server.request_timeout_seconds | u64 | 30 | Per-request deadline. |
server.public_base_url | string | "" | Externally-reachable base URL; used to synthesise the default OAuth2 callback. |
database
| Field | Type | Default | Description |
|---|---|---|---|
database.url_env | string | "TIM_DATABASE_URL" | Env var name holding the postgres:// URL. |
database.min_connections | u32 | 2 | Pool floor. |
database.max_connections | u32 | 10 | Pool ceiling. |
database.auto_migrate | bool | true | Run sqlx::migrate! at startup. |
database.acquire_timeout_seconds | u64 | 30 | Pool acquire timeout (0 = sqlx default). |
database.idle_timeout_seconds | u64 | 600 | Idle-connection reaper (0 = sqlx default). |
database.max_lifetime_seconds | u64 | 1800 | Connection max lifetime (0 = sqlx default). |
Connections are .test_before_acquire(true) — a stale connection
after a PgBouncer bounce is refreshed transparently.
jwt
| Field | Type | Default | Description |
|---|---|---|---|
jwt.private_key_path | path | "/opt/tim/keys/jwt-private.pem" | PKCS#8 PEM RSA private key. |
jwt.key_id | string | "tim-rs-1" | kid advertised in JWS headers + JWKS. |
jwt.issuer | string | "TIM" | iss claim on every issued token. |
jwt.audience.validation_enabled | bool | false | If true, POST /jwt/custom/generate rejects unlisted audiences. |
jwt.audience.allowed | list | [] | Allow-list when validation is enabled. |
jwt.audience.default | string | "tim-service" | Fallback aud when the caller omits one. |
jwt.max_claims_bytes | usize | 32768 | Cap on custom claim payload size at generate time. |
jwt.bulk_revoke_max | usize | 100 | Max tokens per /jwt/custom/revoke/bulk call. |
jwt.cookie_name | string | "jwt" | Cookie name used by the legacy compat endpoints. |
jwt.rotation_warn_days | u32 | 7 | Days-before-retirement window at which boot emits a WARN that the previous key is approaching its cliff. |
jwt.previous_key | object | (unset) | Optional predecessor key retained during a rotation grace period. Signing always uses the current key; verifiers accept either while retires_at > now. See "Rotating the JWT signing key" below. |
jwt.previous_key
Set together with jwt.private_key_path when rotating the JWT signing
key. All three fields are required when the block is present.
| Field | Type | Description |
|---|---|---|
.private_key_path | path | PKCS#8 PEM path of the retiring key. |
.key_id | string | kid under which the retiring key was advertised. MUST differ from jwt.key_id. |
.retires_at | RFC 3339 | Instant past which the previous key is refused on verification and dropped from JWKS. |
Rotation flow:
- Generate a new PKCS#8 PEM. Add
jwt.previous_keypointing at the OLD path + kid, setretires_atsome days in the future (long enough for every downstream verifier to refresh its JWKS cache). Repointjwt.private_key_path+jwt.key_idat the NEW key. - Deploy TIM.
GET /jwt/keys/publicnow returns both keys; all in-flight tokens continue to verify. New signatures use the new key. - On or after
retires_at, the previous key is no longer accepted and is dropped from JWKS. Delete thejwt.previous_keyblock on the next deploy to clean up.
Boot emits WARN when retires_at is within jwt.rotation_warn_days
days. tim doctor reports the same via a jwt.previous_key check
row.
oauth2
| Field | Type | Default | Description |
|---|---|---|---|
oauth2.session_store | string | "memory" | "memory" or "postgres"; anything else fails at startup. |
oauth2.discovery_cache_ttl_seconds | u64 | 3600 | OIDC discovery cache TTL per provider. |
oauth2.session_ttl_seconds | u64 | 86400 | Hard cap on session lifetime. |
oauth2.session_sweep_interval_seconds | u64 | 60 | Background sweeper interval; 0 disables. |
oauth2.state_max_age_seconds | u64 | 300 | Max age of an auth.oauth_state row at callback time. |
oauth2.session_encryption_key_env | string | "TIM_SESSION_ENCRYPTION_KEY" | Env var holding the 32-byte hex AEAD key; required when session_store: "postgres". |
oauth2.providers | map | {} | Provider ID → provider config. |
oauth2.providers.<id>
| Field | Type | Default | Description |
|---|---|---|---|
.name | string | (required) | Human label. |
.discovery_url | string | (required) | .well-known/openid-configuration URL. |
.client_id_env | string | (required) | Env var name holding the client ID. |
.client_secret_env | string | (required) | Env var name holding the client secret. |
.scopes | list | ["openid","profile","email"] | Scopes to request. |
.claim_mappings | map<string,string> | {} | <canonical> → <IdP claim>. |
.token_validation.clock_skew_seconds | u64 | 60 | Leeway for exp, nbf, iat. |
.token_validation.cache_ttl_seconds | u64 | 3600 | JWKS cache TTL. |
.allowed_redirect_uris | list | [] | Allow-list of redirect_uri values. Empty = only the synthesised default. |
security
| Field | Type | Default | Description |
|---|---|---|---|
security.admin_token_env | string | "" | Env var name holding the admin token. |
security.require_admin_token | bool | true | Refuse boot when admin_token_env is set but empty. |
security.cors_allowed_origins | list | [] | CORS origins. ["*"] for wildcard; empty = no CORS layer. |
security.content_security_policy | string | "default-src 'none'; frame-ancestors 'none'" | CSP header. Empty = skip. |
security.strict_transport_security | string | "max-age=63072000; includeSubDomains" | HSTS header. Empty = skip. |
security.referrer_policy | string | "no-referrer" | Referrer-Policy header. |
security.x_frame_options | string | "DENY" | X-Frame-Options header. |
security.x_content_type_options | string | "nosniff" | X-Content-Type-Options header. |
Command-line + env
| Source | Purpose |
|---|---|
--config <path> | Explicit config path. |
TIM_CONFIG | Same, via env. |
RUST_LOG | tracing_subscriber EnvFilter (info, debug, tim=debug,sqlx=warn). |
Startup-refusal matrix
Startup fails hard when:
database.url_envenv var is unset.security.require_admin_token: trueandadmin_token_envis unset or its target env var is empty.oauth2.session_store: "postgres"andsession_encryption_key_envis empty or the target env var is malformed hex / not 32 bytes.oauth2.session_storeis anything other than"memory"or"postgres".- Any provider's
client_id_envorclient_secret_envtarget is unset. - The JWT private key PEM is unreadable or not PKCS#8.
- Migrations fail (with
auto_migrate: true).
Changelog
All notable changes to TIM will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
Unreleased
Fixed
- Allow
clippy::double_must_useinCargo.toml [lints.clippy]. Rust 1.99.0's new lint flagsasync fninside#[async_trait]blocks (the macro layers its own#[must_use]on top of an already-#[must_use]boxed future), breakingcargo clippy --all-targets -- -D warningson every PR againstdev. The offending attribute is in theasync-traitcrate's macro expansion, not TIM source. Unblocks thetestsCI workflow.
Security
- Suppress
RUSTSEC-2024-0449(unmaintainedunsafe-libyaml) in.cargo/audit.tomlanddeny.tomlwith rationale + review date. Pulled in only as a transitive dep ofserde_yaml_ng, which parses the operator-supplied YAML config file at startup — not reachable from the network. Unblocks the scheduledsecurityCI workflow. Migration away fromserde_yaml_ngis tracked as a follow-up. - Update
tokio1.53.1 → 1.54.1 (RUSTSEC-2026-0386,AsyncFd::newI/O-safety unsoundness) and the dev-onlyrustix1.1.4 → 1.1.6 (RUSTSEC-2026-0486, xattr zero-length buffer unsoundness) viaCargo.lock. Lockfile-only; noCargo.tomlchange. - Suppress
RUSTSEC-2026-0459(libsqlite3-sysbundled-SQLite uninitialised-memory disclosure) in.cargo/audit.tomlanddeny.tomlwith rationale + review date. The crate is present inCargo.lockonly as an unresolved optional dependency ofsqlx-macros-core; TIM enables just the sqlxpostgresdriver, so no SQLite code is compiled or linked. No sqlx release can pick up the patchedlibsqlite3-sys >= 0.39(sqlx-sqlite 0.8.6 pins^0.30.1, 0.9.0 caps< 0.38). Together with the two lockfile bumps above, this turns the dailysecurityworkflow green again (red since 2026-11-05).
0.4.1-alpha - 2026-09-18
Eight PRs (#28–#32, #52–#54) rolled into a coordinated release closing the remaining h2ck.me v1 NEXT-TASKS backlog: T-4, T-7, T-8, T-12, T-13, T-15, T-18, T-19. Every open finding from the h2ck.me v1 audit is now landed.
No breaking wire-behaviour changes. The only operator-visible shift is the container runtime — see "Upgrading from 0.4.0-alpha" below.
Upgrading from 0.4.0-alpha
Container runtime switched to distroless (T-12 / G1). If your
deployment pulls docker.io/turnerrainer/tim:0.4.1-alpha (or
ghcr.io/...) unchanged, no action needed — the smaller, zero-CVE
image runs as nonroot:nonroot (UID 65532) and starts on the same
port with the same env vars.
If your deployment customises the container in any of these ways, adjust before upgrading:
- Custom
Dockerfile FROM tim:0.4.0-alpha— the base is nowgcr.io/distroless/cc-debian12:nonroot. No shell, noapt, nocurl. Move anyRUNsteps into an earlier builder stage. - Custom HEALTHCHECK invoking
curl— swap to["CMD", "/app/tim", "healthcheck"]. Thetim healthchecksubcommand probes/healthvia reqwest and exits 0/1; no shell needed. docker exec <container> sh— no shell exists. Usekubectl debug --image=busyboxon K8s, or attach a debug sidecar in compose.- Bind-mounted paths under
/opt/tim/keys— the container user is UID 65532 (was 1000). Ensure the file mode allows reads by that UID. tinias PID 1 — removed. TIM is a single-process axum server; child-reaping is a no-op. K8s ordocker run --initcover PID-1 signal forwarding externally if needed.
No schema migration required.
Added
jwt.previous_keyconfig block (T-7 / F-PR-3) — signing-key rotation with a grace period. JWKS emits both keys and/introspectaccepts tokens signed by either whileretires_at > now; afterretires_atthe previous key is dropped from JWKS and refused on verification. Boot +tim doctoremit WARN when the retirement cliff is withinjwt.rotation_warn_daysdays (default 7). Seebook/src/security-hardening.md§Grace-period rotation.tim healthchecksubcommand (T-12) — probes/healthviareqwestand exits 0 on 200 / 1 otherwise. Wired as the docker-compose HEALTHCHECK on the distroless image (which has nocurl/ shell forCMD-SHELL).--urloverrides the defaulthttp://127.0.0.1:<server.port>/health;--timeout-secondsbounds the probe (default 5s).
Changed
- Docker runtime image switched to distroless (T-12 / G1). Was
debian:13.6-slim; nowgcr.io/distroless/cc-debian12:nonroot. Trivy--severity HIGH,CRITICALcount drops from 65 (3 CRITICAL + 62 HIGH) to 0. Image size shrinks from 119 MB to 32 MB. No shell, no package manager, nocurl, nouseradd. See "Upgrading from 0.4.0-alpha" above. .cargo/audit.toml(T-13) — reviewedRUSTSEC-2023-0071(rsa Marvin timing) rationale. Confirmed session-at-rest encryption uses ChaCha20-Poly1305 (not RSA), noRsaPrivateKey::decryptcall path exists. Next review 2027-03-18.
Fixed
- JWKS thundering herd (T-4 / concurrency mini-audit R-3).
src/oauth2/jwks.rsreplaces theget()+insert()cache-miss path with Moka'stry_get_with, coalescing N concurrent misses on the samejwks_uriinto a single upstream fetch. Regression pin:oauth2::jwks::tests::concurrent_misses_coalesce_to_single_upstream_fetch— 100 concurrent misses → 1 upstream hit. - Attacker-controlled fields clipped in error responses (T-18 /
AP-6). Provider IDs, OIDC callback
error+error_description, id_token parse errors, JWK decode errors, and?jwt=echoes are all clipped to 256 characters viaerror::clip_untrusted. Bounds response payload from a malformed input and caps downstream log-echo blast radius. Regression pin:tests/security_error_echo_clipped.rs.
Security
- JWT algorithm-confusion regression pins (T-8 / G4).
tests/security_jwt_alg_confusion_v1.rsproves TIM refusesalg=nonewith a valid kid, HS256-signed-with-public-key, and every symmetric algorithm +noneforging the signer's kid — all resolve to{"active": false}. Pins the positive control against a future regression that swaps in a permissiveValidation. - Slow-body Slowloris probe (T-15). Verified that
tower_http::timeout::TimeoutLayerbounds body-read too, not just handler execution: a request that trickles bytes pastserver.request_timeout_secondsis aborted at the configured deadline. Not vulnerable, but pinned bytests/security_slow_body_timeout.rs— 8s trickle against a 2s timeout completes in ~2s. - Admin-surface audit (T-19). Enumerated every route in
src/router/mod.rs::build_router; confirmed no accidental public exposure — every mutating endpoint runs behindAdminAuth, every session-scoped read behindSessionAuth, the eight public-by-design endpoints are all protocol-required (health probes, JWKS, OAuth flow endpoints, RFC 7662 discovery). Regression pin:tests/security_admin_surface_audit.rs— 5 cases covering admin/bearer/session/cookie 401s AND that documented-public routes do NOT 401. Book updated with the full inventory (§Endpoint auth invariants). Explicit verdict: TIM does NOT adopt a Ruuter-style/_/*env-gated admin surface — the current gating is comprehensive and adding/_/*would offer attackers a distinct env-shape to probe without security benefit.
0.4.0-alpha - 2026-09-12
Twelve PRs landed on dev between 2026-09-11 and 2026-09-12 as
one coordinated batch closing every open h2ck.me v1 finding (LOG
FN-LOG-1..3, RUNTIME FN1..FN5, PUBLIC-EXPOSURE F-TIM-1..6)
plus eight fleet-strongholds patterns (§1.1, §1.2, §1.6, §2.2,
§2.3, §6.1, §8.2, §9.1) and the CLAUDE.md breaking-change
playbook for LLM agents.
One breaking change — see the "Upgrading from 0.3.0-alpha" section below.
Upgrading from 0.3.0-alpha
One breaking change (audit FN1). introspection.required_client_auth
now defaults to true. POST /introspect refuses unauthenticated
requests, and startup refuses if the flag is on and no
introspection.clients are configured.
To keep the previous permissive behaviour, add to tim.yaml
before upgrading:
introspection:
required_client_auth: false
To take the recommended posture, register each caller:
introspection:
required_client_auth: true
clients:
- client_id: "ruuter"
client_secret_env: "TIM_INTROSPECT_RUUTER_SECRET"
# ... one entry per downstream caller
Then export TIM_INTROSPECT_<name>_SECRET for every referenced env
var before starting TIM. Callers present the secret as HTTP Basic
(scheme case-insensitive per RFC 7235 §2.1):
Authorization: Basic <base64(client_id:secret)>
Two optional new gates (audit F-TIM-2, F-TIM-6) reuse the same
client list and both default false:
introspection.gate_validation_endpoints: true— extends the gate to/jwt/custom/validate+/jwt/custom/validate/boolean.introspection.gate_jvm_compat_endpoints: true— extends the gate to/jwt/userinfo,/jwt/custom-jwt-verify,/jwt/custom-jwt-userinfo. Enabling breaks browser-direct DSL flows unless the reverse proxy forwards a Basic header.
Two operational notes (non-breaking):
- Log stream ANSI escapes now off in non-TTY environments. If your log-shipper regex depends on ESC bytes for delimiter detection, update it — the fleet reference (Ruuter, Resql) has always been 0 ESC bytes.
- Every response now carries
traceparent+x-trace-idheaders. Downstream tooling can correlate a response with TIM's access log by grepping the trace-id.
No schema migration required.
Added
- New subcommand
tim doctor(--strictflag) (fleet §8.2). Pre-boot validator: parsestim.yaml, resolves every referenced env var, verifies the JWT key file exists and parses as PKCS#8 PEM, prints a structured[ OK ] / [ WARN ] / [ FAIL ]table. Exits0on all-pass (WARN advisory),1on any FAIL or--strict+ any WARN. No side effects: never binds a port, never opens a Postgres connection, never touches the network. Wire into deploy pipelines as a pre-flight gate. TIM_OFFLINE=1env var (fleet §9.1). When set (1/true/yes), every outbound HTTP call (OIDC discovery, JWKS, token exchange) short-circuits with 502. Intended for pentest / adversarial CI runs; boot WARN emitted so operators see the posture in the log. Snapshotted at first read.- W3C Trace Context on every response (fleet §1.6):
traceparent: 00-<32-hex>-<16-hex>-<flags>+x-trace-id: <32-hex>. Inherits trace-id and flags from a well-formed incomingtraceparent; generates a fresh trace-id otherwise. Span-id is always fresh — TIM is a new span within the (possibly-inherited) trace. Emitted on 4xx and 5xx paths too. - Per-request access log (audit LOG-v1 FN-LOG-2, fleet §1.2).
One INFO line per completed request:
INFO http_request_completed method=POST route=/introspect status=200 duration_us=1234 trace_id=<32-hex>. Deliberately omits headers, request/response body, and client IP — Ruuter's access log is authoritative for those. - Two opt-in Basic-auth gates on validation surfaces (audit
F-TIM-2, F-TIM-6).
introspection.gate_validation_endpointsprotects/jwt/custom/validate*;introspection.gate_jvm_compat_endpointsprotects the three JVM 1.x cookie-borne validation compat endpoints. Both share the sameintrospection.clientslist — one gate, one secret rotation policy. Both defaultfalsefor BC with existing DSL callers. - Structured JSON on 413 responses (audit RUNTIME-v1 FN3,
fleet §2.3 / §6.1). Wrapped
DefaultBodyLimitwith a middleware that returns{"error":"payload_too_large","max":N}withContent-Type: application/json— instead of Axum's default bare-text. Added aContent-Lengthpreflight so an oversize- declared body is rejected before any bytes are read.
Changed
- BREAKING —
introspection.required_client_authnow defaults totrue(audit FN1). See "Upgrading from 0.3.0-alpha" above. - Log stream ANSI escapes disabled under Docker / systemd / any
pipe (audit LOG-v1 FN-LOG-1).
tracing_subscriber::fmt::Layergates ANSI onstd::io::stderr().is_terminal(). Colours retained when a developer runscargo runat a TTY. - Every modern JSON body / form / query DTO now carries
#[serde(deny_unknown_fields)](fleet §2.2). A request with an unknown field returns 4xx naming the field, instead of silently dropping it. Applies to:POST /jwt/custom/{generate, validate, extend, revoke, revoke/bulk, list/me},POST /introspect(JSON- form),
GET /auth/login/:id(query),POST /auth/logout(body). Deliberately exempt (compat / IdP-driven surfaces): JVM 1.x compat endpoints,GET /auth/callback/:id, IdP response DTOs.
- form),
bind_is_loopbackhelper widened (audit PR #9 nit). Previously matched only127.0.0.1+::1; now accepts127.0.0.0/8,localhost(case-insensitive),[::1],::ffff:127.0.0.1. Applied uniformly in bothAppConfig::validate()anddiagnose()— one helper, two callers.- Basic auth scheme comparison now case-insensitive (audit PR #4
nit, RFC 7235 §2.1).
Basic,basic,BASIC,BaSiCall take the same path. Non-basicschemes (bearer,digest, …) still refused in any casing.
Fixed
- Empty-string
oauth2.providers.<id>.jwks_uripin now rejected at config load (audit PR #10 nit). Previously silently permissive at runtime — indistinguishable from "no pin set" despite the operator's clear intent to pin. Omit the field entirely to disable pinning.
Testing
- New regression pins:
tests/security_log_ansi_off.rs— 2 cases (FN-LOG-1).tests/security_log_access_present.rs— 3 cases (FN-LOG-2).tests/security_introspect_no_token_leak.rs— 3 cases (FN-LOG-3).tests/security_traceparent_response.rs— 6 cases (fleet §1.6).tests/security_413_structured_body.rs— 3 cases (FN3).tests/security_deny_unknown_fields.rs— 8 cases (fleet §2.2).tests/security_offline_mode.rs— 1 case (fleet §9.1).tests/security_validation_gate.rs— 11 cases (F-TIM-2, F-TIM-6).
- Plus 20+ new unit tests across
src/config,src/doctor,src/access_log,src/http,src/security/introspect_auth.
Documentation
- CLAUDE.md — "Shipping a breaking change" playbook. Self- contained rules for LLM agents proposing new breaking changes: what counts, version-bump mechanics, CHANGELOG discipline, migration immutability, PR shape, explicit "must NOT" list.
- CLAUDE.md — verification loop grows a "smoke-test necessary" paragraph. Automated tests are necessary but not sufficient; the exact live-boot smoke recipe is documented, with the concrete reason (cross-branch bugs no unit test catches — one was found in this batch by exactly this smoke pass).
- CLAUDE.md — new
timsubcommands + environment variables sections. Code-layout expanded with new modules (src/access_log,src/doctor,src/http). - Book —
configuration.md. Introspection section rewritten for the new default + three-axis gate model.TIM_OFFLINEdocumented. - Book —
security-hardening.md. Four new sections:tim doctor, offline mode, W3C Trace Context, validation-endpoint DoS gate.
Merged PRs
- #13 security(log): disable ANSI + per-request access log middleware (audit FN-LOG-1, FN-LOG-2, FN-LOG-3)
- #14 router(413): structured JSON body on payload-too-large (audit FN3)
- #15 fix: h2ck.me v1 PR-review nits (empty jwks_uri pin, case-insensitive Basic, bind loopback)
- #16 docs(claude): playbook for shipping a breaking change
- #17 introspect(BREAKING): flip required_client_auth default to true (audit FN1)
- #18 access_log: propagate W3C traceparent + x-trace-id on response (fleet §1.6)
- #19 feat:
tim doctor— pre-boot config + env validator (fleet §8.2) - #20 feat: TIM_OFFLINE=1 refuses every outbound HTTP call (fleet §9.1)
- #21 chore:
#[serde(deny_unknown_fields)]on modern request DTOs (fleet §2.2) - #22 docs(book+claude): tim doctor, TIM_OFFLINE, FN1 default, traceparent, deny_unknown
- #23 security: gate /jwt/custom/validate + JVM compat validation endpoints (audit F-TIM-2, F-TIM-6)
0.3.0-alpha - 2026-09-06
Post-audit release. Nine PRs (h2ck.me v1 audit findings + one Snyk
base-image bump) landed on dev between 2026-09-04 and 2026-09-06
as one coordinated batch. Every finding was independently reviewed
by h2ck.me and closed with verdict ✅ pass.
Upgrading from 0.2.x
One breaking change. OIDC discovery is fail-closed on plain
HTTP by default (see ### Changed below). To find and fix
affected configs before upgrading:
# Any plain-http discovery_url in your tim.yaml:
grep -nE 'discovery_url:\s*http://' tim.yaml
# Anywhere in a mounted config directory:
grep -rnE 'discovery_url:\s*http://' /path/to/config/
If a hit is intentional (dev against a non-TLS mock IdP), set
oauth2.providers.<id>.allow_http_discovery: true alongside the
plain-http URL. Otherwise, switch to https:// before upgrading.
The check also enforces HTTPS on endpoints inside the returned
discovery document — a provider that publishes HTTP endpoints in
its .well-known/openid-configuration will fail login regardless
of the URL you configured, and needs the same opt-in.
Two soft behaviour changes worth noting:
- Legacy
?session_id=<id>query-string transport now logs at WARN (was DEBUG). Log-volume alerting keyed on WARN counts may fire on deployments still using the query transport. Migrate callers toAuthorization: Bearer sess_<id>orX-TIM-Session. - JWT validate
reasonfield values may differ for previously mis-classified errors (see### Fixedonjwt/service.rs). Dashboards keyed on the exactreasonstring may need updating.
No schema migration needed. The pkce_verifier column used by the
PKCE work was reserved in migrations/0001_init.sql since the
first alpha; existing databases already have it.
Added
- Boot-time diagnostic in
AppConfig::diagnosenow warns loudly on two long-standing operator footguns:- CORS wildcard exposes cross-origin reads. When
security.cors_allowed_originscontains"*", TIM logs that every unauthenticated read endpoint (/health,/auth/providers, ...) is now reachable cross-origin. - HSTS + non-loopback bind without
preload. When bind is not loopback andstrict_transport_securitylackspreload, TIM names both facts in one line and points athttps://hstspreload.org. First-request MITM against non-preloaded HSTS deployments leaks bearer tokens in the clear.
- CORS wildcard exposes cross-origin reads. When
src/oauth2/flow.rs— OAuth2 authorization requests now send a per-requestcode_challenge(SHA-256 base64url-nopad) pluscode_challenge_method=S256per RFC 7636 (PKCE). The 32-byte verifier is persisted alongsidestateinauth.oauth_stateand replayed on the token endpoint. Unblocks IdP registrations that mandate PKCE (some TARA/Google/Microsoft clients) and protects the authorization code against on-path interception on registrations that permit non-PKCE.oauth2.providers.<id>.jwks_uri: Option<String>— pin the JWKS URI expected in the discovery document. When set, TIM refuses discovery whosejwks_uridiffers, closing the empty-JWKS DoS path against a MITM'd discovery response. Default: unset (no pin), preserving existing behaviour.POST /introspectnow supports optional Basic-auth client authentication per RFC 7662 §2.1. Configured via a newintrospectionsection:introspection.required_client_auth: bool(default false for backwards compatibility)introspection.clients: [{ client_id, client_secret_env }]Secrets are compared constant-time (subtle::ConstantTimeEq). When required, missing/wrong credentials → 401; the endpoint no longer accepts every request against the denylist SELECT.
- New module
src/security/introspect_auth.rs+IntrospectionGateboot resolver. Fails startup if any referencedclient_secret_envis unset when the gate is required.
Changed
src/oauth2/flow.rs,src/oauth2/state_sweeper.rs—auth.oauth_stateinterval expressions rewritten asnow() - make_interval(secs => $N::int)instead of the string-concat- then-cast form. Semantics identical (bind is still parameterised — no injection path either way); the new form reads what it does.- OIDC discovery is now fail-closed on plain HTTP.
provider. discovery_urland endpoints inside the discovery document (authorization_endpoint,token_endpoint,jwks_uri) must all usehttps://or startup / login refuses. Operators intentionally running against a non-TLS mock IdP for dev must setoauth2.providers.<id>.allow_http_discovery: true. Closes MITM substitution of the JWKS URI on the discovery fetch. src/security/session_auth.rs— the legacy?session_id=query transport now emits WARN (was DEBUG). Operators grepping their logs can identify remaining callers before removing the fallback. Payload/behaviour otherwise unchanged.
Fixed
src/jwt/service.rs::validate— reason-code classification now matches onjsonwebtoken::errors::ErrorKindvariants instead offormat!("{e}").contains("expired"). The prior pattern would have silently reclassified every non-expiry error assignature_mismatchon ajsonwebtokentext-format change, hiding real bugs and breaking monitoring keyed on the reason string. NewJwtSigner::verify_rawexposes the typed error so classifier logic doesn't lose the kind through theTimErrorwrapper.src/oauth2/session/postgres.rs—PostgresStore::getnow filters expired rows in the SELECT (AND expires_at > now()) instead of doing a check-then-DELETE in Rust. Removes the two-writer race where concurrent gets on an expiring session both saw the row as expired and raced the DELETE (one won, the other errored — visible as inconsistent 404/401 pairs). Expired rows are now removed only bysweep_expired, which is already scheduled by the state sweeper.
Testing
- New
tests/it_oauth_state_race.rspins the atomic single-use contract onDELETE ... RETURNING: 32 concurrent callbacks with the samestatevalue produce exactly one winner. Also asserts that an aged-past-cap row cannot be consumed even before the sweeper reaches it (closes the sweeper vs. consumer race).
0.2.1-alpha - 2026-08-31
Two OAuth2/OIDC defects, both surfaced against TARA
(tara-test.ria.ee). Thanks to Ermo Mägi for the diagnosis
against the live endpoint.
Fixed
src/oauth2/flow.rs— token exchange now authenticates via HTTP Basic (client_secret_basic) instead of postingclient_id/client_secretas form fields (client_secret_post). OIDC Core §9 makes Basic the default when the client registration is silent, and TARA's registration is silent — it rejectsclient_secret_postwith401 invalid_client, which surfaced in TIM as a bare 502 and blocked every TARA login. Providers that accept both methods (Google, Auth0, Okta, Microsoft, Apple) keep working; providers that only acceptclient_secret_postare not currently supported (no user has one).src/oauth2/idtoken.rs— claim mappings now walk dot-separated paths into nested JSON objects viaresolve_claim_path. TARA carriesgiven_nameandfamily_nameonly underprofile_attributes, and the previous flat lookup returnedNonefor any dotted mapping, silently producing sessions with empty names. A name without a dot is still a plain top-level lookup (behaviour unchanged); a dotted path that does not exist yieldsNoneand does not fall back to a top-level claim with the same trailing segment.src/oauth2/flow.rs— theBadGatewaymessage from a failed token exchange now includes the upstream response body (bounded to 512 characters). OAuth2 error responses name the actual problem (invalid_client,invalid_grant, ...); dropping it left operators with a bare status code and no way to diagnose without reproducing the request by hand.
Testing
- Regression tests cover: token endpoint receives Basic auth with
no client credentials in the form body; upstream 401 surfaces as
502 without panicking on
resp.text(); dotted mappingprofile_attributes.given_nameresolves the nested value end-to-end; a dotted-path miss does not fall back to a top-level claim; and aprofile_from_claimsseam test pinning theresolve_claim_pathdispatch. All would have caught the originals; verified by reverting each fix and re-running.
Container images
Users pulling docker.io/turnerrainer/tim:alpha or
ghcr.io/turnerrainer/tim:alpha get this version automatically.
Pinned users should switch from :0.2.0-alpha.2 to
:0.2.1-alpha.
0.2.0-alpha.2 - 2026-08-05
CI-only fix. Same runtime behaviour as 0.2.0-alpha.1.
The 0.2.0-alpha.1 container images were published to Docker Hub
and GHCR but the publish workflow's smoke test failed (missing
TIM_ADMIN_TOKEN env var — the shipped tim.yaml sets
security.require_admin_token: true), which skipped the cosign
signing step. 0.2.0-alpha.2 re-publishes with the smoke test
fixed and with cosign signatures attached.
Users pulling docker.io/turnerrainer/tim:alpha or
ghcr.io/turnerrainer/tim:alpha get this version automatically.
Users who explicitly pinned to :0.2.0-alpha.1 should switch to
:0.2.0-alpha.2 for a cosign-signed image.
Fixed
.github/workflows/publish.yml— smoke test now setsTIM_ADMIN_TOKEN=smoke-only-not-a-real-secretwhen launching the container. Fix for the failed alpha.1 publish.
0.2.0-alpha.1 - 2026-08-05
Second alpha. Post-audit release: fixes silent-drop bugs from 0.1.0-alpha.1, restores JVM 1.x + JVM 2.0 contract parity where downstream DSLs depend on it, adds TARA integration coverage, adds an admin-token gate on state-changing endpoints, and lands a Postgres session store as an alternative to the default in-memory one.
Still alpha. Two significant features are spec'd but not implemented:
mint-jwt-from-session— no endpoint yet for deriving a TIM-signed service JWT from an OAuth2 session. Downstream services calling TIM-behind-Ruuter for authorised APIs still need to hit/auth/session/validateper request or generate a fresh JWT via the admin gate.- PKCE — the authorization code flow does not send PKCE parameters. Providers that mandate PKCE (some TARA and Google client registrations do) will reject the login.
Live-fire testing against real TARA / Google sandboxes has NOT been done — the TARA integration tests use a mock IdP.
Test coverage at release
96 tests total, --test-threads=1:
| Binary | Count | Purpose |
|---|---|---|
cargo test --lib | 42 | Config validation, crypto primitives, session-store semantics, admin gate, JWKS parsing, ID-token helpers |
it_jwt_lifecycle | 7 | Custom JWT generate → validate → extend → revoke |
it_legacy_compat | 15 | All eight JVM 1.x cookie-borne endpoints end-to-end |
it_oauth2 | 6 | Provider registry, session-auth surfaces, health |
it_oauth2_callback | 3 | End-to-end OAuth2 callback with a mock IdP |
it_oauth2_tara | 7 | TARA-specific claim shape + five rejection paths |
it_regression_findings | 11 | Regression tests for behaviours fixed post-audit |
Fixed — security-relevant
- OIDC ID-token verification is now performed on every callback.
Signature (via the provider's cached JWKS),
iss(must matchdiscovery.issuer),aud(must containclient_id),exp,nbf,iat(with configurable clock skew), and mandatorynoncecomparison — all constant-time where relevant. Refusesalg=noneand symmetric algorithms outright. The 0.1.0-alpha.1 callback did not verify the ID token at all. - Mandatory
nonceon ID tokens. A missingnonceclaim is now a hard rejection; the previous behaviour silently accepted tokens without a nonce claim. oauth2.session_storeconfig value is enforced. Values other than"memory"or"postgres"fail at startup.- Session TTL is capped at
min(configured_ttl_seconds, expires_in-from-IdP); oversizedexpires_inno longer produces an immortal session. POST /jwt/custom/list/mechecks the denylist. Revoked bearer tokens can no longer enumerate the caller's other tokens until natural expiry.- Admin-token gate on state-changing custom-JWT endpoints.
/jwt/custom/generate,/revoke,/revoke/bulk,/extendnow requireX-TIM-Admin-Token:orAuthorization: Bearer <admin>. Configured viasecurity.admin_token_env. Startup refuses whenrequire_admin_token: true(default) and the env var is missing.
Fixed — OAuth2 / OIDC
- Callback bubbles IdP
error=responses as structured 400 instead of "missing field code" schema-validation errors. redirect_uriper-provider allow-list viaoauth2.providers.<id>.allowed_redirect_uris. Caller-supplied URIs must match an entry exactly; falls back to the first entry when the caller omits.- Discovery documents are validated for required fields plus
grant_types_supported: authorization_codeandresponse_types_supported: code. - Discovery fetch retries with exponential backoff on 5xx and network errors (three attempts). 4xx fails fast.
token_validation.clock_skew_seconds/cache_ttl_secondsare consumed by the ID-token verifier — previously they were parsed but ignored.auth.oauth_staterows have an age cap enforced in theDELETE ... RETURNINGclause. Default 300 s (JVM 2.0 parity). A background sweeper reaps stale rows everysession_sweep_interval_seconds(default 60 s).- Session ID transport moved to headers —
Authorization: Bearer sess_<id>orX-TIM-Session: <id>are the primary transports. Legacy?session_id=<id>query still accepted for backward compatibility. server.public_base_urlconfig field replaces the hardcodedhttp://localhost:8085callback synthesis. Empty means "caller must pass?redirect_uri=explicitly."provider.claim_mappingscan now target registered JWT claims (sub,iss,aud). TARA's personal-code mapping (personal_code: "sub") works correctly.
Fixed — Custom JWT lifecycle
POST /jwt/custom/revokereturns 409 on idempotent repeat; matches JVM 2.0's semantics.POST /jwt/custom/validatereturns 401 on invalid/expired/ revoked tokens; the body'svalid/active/reasonfields still carry the details. Matches JVM 2.0.POST /jwt/custom/generatereturnsstatus: "created";POST /jwt/custom/extendreturnsstatus: "extended". Response-shape parity with JVM 2.0.setCookie: truein request body actually emitsSet-Cookieon the response. Attributes:Path=/; HttpOnly; Secure; SameSite=Lax(addsSecure+SameSitebeyond JVM defaults).token_type: "custom_jwt"claim is signed into every custom JWT at generate time; extended tokens preserve or backfill it.POST /jwt/custom/extenddefault TTL is 60 minutes when the caller omitsexpirationInMinutes(JVM 2.0 parity).POST /jwt/custom/list/mepagination accepts JVMpagesemantics (offset= page number,limit= page size, default 20); response carries bothpage/size/total_pagesandoffset/limit(row shape). Opt-inby_row: trueinterpretsoffsetas row offset.jwt_namefilter is honoured onPOST /jwt/custom/list/me(was silently ignored in JVM 2.0).POST /introspectreturns uniform{"active": false}on every inactive path (unknown, revoked, expired, wrong issuer, bad signature).POST /introspectaccepts JSON or form even without a Content-Type header (best-effort parse).
Added — legacy compatibility endpoints
Restored the eight cookie-borne endpoints the original Buerokratt TIM exposed and JVM 2.0 dropped. These coexist with the modern header/body shapes — nothing was replaced.
GET /healthz— alias forGET /health.GET /jwt/verification-key— signing public key as PKCS#1 PEM.GET /jwt/userinfo— read JWT from configured cookie name.POST /jwt/custom-jwt-verify— verify JWT from cookie named in body.POST /jwt/custom-jwt-userinfo— read JWT from cookie named in body.POST /jwt/custom-jwt-extend— admin-gated; extend + refresh cookie.GET /jwt/extend-jwt-session— admin-gated; extend default cookie.POST /jwt/custom-jwt-blacklist— admin-gated; body = cookie name.POST /jwt/blacklist— admin-gated; three modes (cookie /?jwt=<uuid>/?sessionId=<id>). Returns real status codes (200 / 409 / 404) instead of JVM 1.x's "always 200."
Config knob for the cookie name: jwt.cookie_name (default "jwt";
set to "JWTTOKEN" for JVM 1.x DSL parity).
Added — TARA (Estonian eID) integration
Config-only integration. Full "TARA" section added to the OAuth2 book chapter covering:
- Provider block for
tara-test.ria.eeandtara.ria.ee. - Claim mapping:
personal_code: "sub",first_name: "given_name",last_name: "family_name",acr,amr,date_of_birth. - Scope semantics (
openid,openid phone,openid idcard,openid mid). - Test-vs-prod discovery URL swap.
- LoA policy hand-off (target extracts
acr; downstream services enforce policy).
Integration coverage: 7 test cases exercising personal-code
- Estonian UTF-8 round-trip,
acr/amrarray shape, issuer/kid/alg=none/expiry rejection paths, andprofile_attributesnot being silently promoted.
Added — HTTP security posture
security.admin_token_env— env var name holding the privileged-endpoint token. Constant-time comparison.- CORS layer via
security.cors_allowed_origins. - Response-header middleware —
Content-Security-Policy,Strict-Transport-Security,X-Frame-Options,X-Content-Type-Options,Referrer-Policy— all configurable, emitted by default with conservative values. - Boot-time diagnostic pass —
AppConfig::diagnose()logs every parsed config field at INFO with WARN on non-secure or operator-attention-required settings. Grep fortim::config::diagnosein logs.
Added — Postgres session store
oauth2.session_store: "postgres"persists sessions across process restart and spans replicas. Profile data (which may contain IdP-derived PII) is AEAD-encrypted at rest via chacha20poly1305 using a 32-byte key fromoauth2.session_encryption_key_env(defaultTIM_SESSION_ENCRYPTION_KEY). Startup refuses if the key env var is unset or malformed.- Background sweeper deletes expired sessions + stale
oauth_state rows every
oauth2.session_sweep_interval_seconds(default 60 s). SessionStoretrait withMemoryStoreandPostgresStorebackends. Selected by config at startup.
Added — Config / lifecycle knobs
server.public_base_url— externally-reachable URL used to synthesise the default OAuth2 callback URL.database.acquire_timeout_seconds/idle_timeout_seconds/max_lifetime_seconds— pool tuning.test_before_acquire(true)transparently to PgBouncer bouncing.oauth2.session_ttl_seconds(24 h default),state_max_age_seconds(5 min default),session_sweep_interval_seconds(60 s default).serde(deny_unknown_fields)onAppConfigand every nested struct — a typo intim.yamlnow fails at startup rather than silently defaulting.
Known API-shape changes vs. JVM 2.0
Additive or documented; no field removed. Callers unaffected in the common case:
GET /jwt/keys/publicreturns a bare RFC 7517 JWKS ({"keys":[…]}), not JVM 2.0's{"jwk": "<stringified JWKS>"}wrapper. Legacy callers useGET /jwt/verification-keyfor the PKCS#1 PEM shape instead.- List response carries both pagination shapes
(
page/size/total_pagesANDoffset/limit). Set-Cookieattributes addSecureandSameSite=Laxwhere JVM 1.x omitted both.
0.1.0-alpha.1 - 2026-07-30
First alpha release. Rust rewrite of TIM (Java / Spring Boot 3.3.3), covering the endpoints enumerated in the design document.
Known limitations at time of release
- ID-token signature verification NOT implemented — deferred and treated as a critical bug by the post-release audit. Fixed in 0.2.0-alpha.1 above.
- Session store hard-coded to in-memory
DashMap; theoauth2.session_storeconfig knob was accepted but ignored. - No admin gate on
/jwt/custom/generateor related privileged endpoints.
Added — Custom JWT lifecycle
POST /jwt/custom/generate— generate an RS256-signed JWT with a custom claims payload, configurable expiration, and optional audience. Persists tocustom_jwt.jwt_metadatawithoriginal_jwt_uuidset to the new token'sjti(chain root).POST /jwt/custom/validate— signature, expiration, denylist, optional audience + issuer.POST /jwt/custom/validate/boolean— same checks, plain-texttrue/falseresponse.POST /jwt/custom/extend— issue a fresh token preserving the original claims + audience; immediately denylists the old one; links the new token viasupersedes+original_jwt_uuid.POST /jwt/custom/revoke— insert the token'sjtiintocustom_jwt.denylist.POST /jwt/custom/revoke/bulk— up to 100 tokens per request (configurable viajwt.bulk_revoke_max); returns 207-style body with per-token results.POST /jwt/custom/list/me— paginated list of the caller's tokens (bearer JWT inAuthorization).GET /jwt/keys/public— JWK Set advertising the signing public key.
Added — OAuth2 / OIDC (MVP)
GET /auth/providers,GET /auth/providers/{provider_id}.GET /auth/login/{provider_id}— authorization code flow init.GET /auth/callback/{provider_id}— token exchange + session creation. See "Known limitations" above — this path did not validate the ID token in this release.GET /auth/session/validate?session_id=...,GET /auth/profile?session_id=...,POST /auth/logout?session_id=...,GET /auth/health.- OIDC discovery + JWKS cached per-provider (
moka, TTL from config). - Config-driven provider list.
Added — RFC 7662 introspection
POST /introspect(form + JSON),GET /introspect/types.
Added — Framework
- Config loading (CLI → env →
./tim.yaml→ defaults). Secrets via<field>_env: NAMEpattern. TimErrorenum with per-variant HTTP status mapping.- Postgres pool via
sqlx. Migrations auto-applied whendatabase.auto_migrate: true. - RSA private key loaded once at startup (PKCS#8 PEM).
- Request body size cap, per-request timeout.
- Structured tracing via
tracing_subscriber::EnvFilter.
Added — Repository, CI, docs
.github/workflows/: tests, security, publish, docs.book/mdBook.- Hardened container: multi-stage build, non-root user, tini init.
- Hardened compose:
read_only,cap_drop: ALL,no-new-privileges, tmpfs/tmp, resource limits, healthcheck. deny.toml+.cargo/audit.toml.