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-blacklist still 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.yaml and 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 ...).
  • curl and jq.
  • 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".

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.

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

Configuration

TIM loads its config from a YAML file. Search order at startup:

  1. --config <path> CLI flag.
  2. TIM_CONFIG=<path> env var.
  3. ./tim.yaml or ./tim.yml in the working directory.
  4. 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 in tim.yaml.
  • RUST_LOG — standard tracing_subscriber::EnvFilter syntax (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 namePurpose
TIM_DATABASE_URLPostgres connection URL.
TIM_ADMIN_TOKENAdmin token for privileged endpoints.
TIM_SESSION_ENCRYPTION_KEYOnly when session_store: "postgres".
TIM_<PROVIDER>_CLIENT_ID, _CLIENT_SECRETOne pair per OAuth2 provider.
TIM_INTROSPECT_<CALLER>_SECRETOne 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:

  1. Reads the provider's discovery document from discovery_url (with retry-with-backoff on 5xx / network errors — three attempts).
  2. Validates required fields (issuer, authorization_endpoint, token_endpoint, jwks_uri) plus, when advertised, grant_types_supported including authorization_code and response_types_supported including code.
  3. Caches the discovery response for oauth2.discovery_cache_ttl_seconds.
  4. Prepares an on-demand JWKS cache — JWKS is fetched at first ID-token verification and reused until token_validation.cache_ttl_seconds expires.
  5. Resolves client_id_env and client_secret_env — refuses to start if either env var is unset.

Authorization code flow

  1. GET /auth/login/{provider_id}?redirect_uri=<...>

    TIM generates a random state + nonce (256 bits each), persists them to auth.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_uri resolution order:

    1. Caller-supplied query param — accepted only if on the provider's allowed_redirect_uris.
    2. First entry of allowed_redirect_uris if that list is populated.
    3. Synthesised from server.public_base_url as {public_base_url}/auth/callback/{provider_id}.
    4. Error 400 if none of the above resolve.
  2. GET /auth/callback/{provider_id}?code=<...>&state=<...>

    TIM:

    • Validates state (single-use — atomically DELETE ... RETURNING); rejects rows older than oauth2.state_max_age_seconds (default 300 s).
    • Exchanges code for tokens at the provider's token_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"
    }
    
  3. GET /auth/session/validate — session lookup + touch.

  4. GET /auth/profile — canonical profile from the session.

  5. 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:

  1. Header parses; alg is a supported asymmetric algorithm (RS/PS/ES 256/384/512). alg=none and symmetric algorithms are refused outright.
  2. 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.
  3. Signature verifies against the resolved key.
  4. iss claim matches discovery.issuer exactly.
  5. aud claim contains the configured client_id.
  6. exp > now (with token_validation.clock_skew_seconds leeway).
  7. nbf, if present, ≤ now (with leeway).
  8. iat ≤ now + leeway (future-date guard).
  9. nonce MUST be present and MUST match the value TIM stored in auth.oauth_state at 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 (migration 0002_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 (default TIM_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

ClaimTypePurpose
substring (11 digits, e.g. "60001019906")Estonian personal code — legally-attested identity
given_namestring, UTF-8First name; Estonian characters (Kärt, Ööbik) preserved
family_namestring, UTF-8Family name
date_of_birthstring ("YYYY-MM-DD")Optional
acrstring"low" / "substantial" / "high" — Level of Assurance
amrarray of stringsAuthentication method used (["mID"], ["smart-id"], ["idcard"], ["eIDAS"])
profile_attributesobjectNested 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:

  • openid alone — 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:

  1. Create OAuth2 credentials at the provider (client ID + secret).
  2. Register your callback URLs — either {server.public_base_url}/auth/callback/{provider_id} or whatever you put in allowed_redirect_uris.
  3. Add a block to tim.yaml under oauth2.providers.<provider_id>.
  4. Set <CLIENT_ID_ENV> and <CLIENT_SECRET_ENV> in the environment.
  5. Restart TIM. First GET /auth/login/<provider_id> triggers discovery + validation; watch for discovery: provider does not advertise ... errors in the log if the provider's advertisements are non-standard.
  6. 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/generate
  • POST /jwt/custom/revoke
  • POST /jwt/custom/revoke/bulk
  • POST /jwt/custom/extend
  • POST /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):

RouteWhy public
GET /health, GET /healthzLB / K8s liveness probe.
GET /auth/healthOAuth registry status probe.
GET /jwt/keys/publicRFC 7517 JWKS — verifiers pull unauth.
GET /jwt/verification-keyLegacy JVM 1.x PEM mirror of JWKS.
GET /introspect/typesRFC 7662-shaped discovery of supported token types.
GET /auth/providers, GET /auth/providers/:idPublic provider catalogue (client picks a provider before it has a session).
GET /auth/login/:idStarts OAuth flow — must be reachable pre-session.
GET /auth/callback/:idCalled 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, no Access-Control-* headers emitted. Same-origin callers work; cross-origin browser callers get blocked at the browser.
  • ["*"] — wildcard Access-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: true for 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 on custom_jwt.*, no auth access.
  • tim_auth — RW on auth.*, no custom_jwt access.
  • 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:

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/public returns BOTH keys.
  • Newly signed tokens use tim-rs-2 (the current key).
  • POST /introspect accepts 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:

  1. Generate a new PKCS#8 PEM keypair.
  2. Update jwt.key_id to a new value.
  3. Deploy a new TIM instance with the new key + new kid (no jwt.previous_key).
  4. Verify /jwt/keys/public on the new instance advertises the new kid.
  5. 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, no curl / wget, no useradd. Trivy --severity HIGH,CRITICAL baseline: 0. (Old debian:13.6-slim runtime: 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-privileges set.
  • Resource limits (CPU / memory) applied.
  • Healthcheck via tim healthcheck (probes /health via 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 (default true since 0.4.0-alpha).
  • introspection.gate_validation_endpoints — protects /jwt/custom/validate + /validate/boolean (default false).
  • introspection.gate_jvm_compat_endpoints — protects the three JVM 1.x cookie-borne validation compat endpoints (default false — 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 capabilityProtection
Reach the networkAdmin gate on state-changing endpoints (26); reverse-proxy rate limits; CORS if browser-borne
Steal a session IDSession IDs travel via header (27); still short-lived (session_ttl_seconds cap, 9)
Steal an admin tokenConstant-time compare (26); short-token lifetime by rotation; monitor for unusual X-TIM-Admin-Token traffic
Compromise the IdP token endpointID-token JWKS signature verification (01); iss / aud / nonce (02) blocks forged tokens
Compromise the DBSession profile encrypted at rest; JWT tokens hashed to jti in denylist (no plaintext in DB)
Bug in JWT service that touches auth schemaOptional per-schema role isolation (23)
Downgrade to alg=noneRefused 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:

PathMethodPurposeAuth
/healthzGETAlias for /health (same body)public
/jwt/verification-keyGETReturns the JWT signing public key as PEMpublic
/jwt/userinfoGETRead JWT from <jwt.cookie_name> cookie → subject + claimspublic
/jwt/custom-jwt-verifyPOSTVerify JWT from cookie named in bodypublic
/jwt/custom-jwt-userinfoPOSTRead JWT from cookie named in body → subject + claimspublic
/jwt/custom-jwt-extendPOSTExtend JWT from cookie named in body; refresh cookieadmin
/jwt/extend-jwt-sessionGETExtend JWT from <jwt.cookie_name> cookie; refresh cookieadmin
/jwt/custom-jwt-blacklistPOSTRevoke JWT from cookie named in bodyadmin
/jwt/blacklistPOSTRevoke 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 — Cookie header 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:

  1. Cookie mode — Cookie: <jwt.cookie_name>=<jwt> on the request. Revokes that custom JWT.
  2. Jti mode — ?jwt=<uuid> query param. Looks up the token's metadata (for its expiry timestamp) and adds to the denylist.
  3. 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:

StatusMeaning
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.
400None of the three parameter modes supplied.
400?jwt=<uuid> value is not a valid UUID string.
400Cookie 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 ValidateResponse body.
  • 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

EndpointBuerokratt JVM 1.xBuerostack JVM 2.0TIM-on-Rust
GET /healthyesyesyes
GET /jwt/keys/publicyes (wrapped)yes (wrapped)yes (bare JWKS, RFC 7517)
POST /jwt/custom/generate(was /jwt/custom-jwt-generate)yesyes, admin-gated
POST /jwt/custom/validatevia /custom-jwt-verifyyesyes
POST /jwt/custom/validate/boolean—yesyes
POST /jwt/custom/revokevia /custom-jwt-blacklistyesyes, admin-gated
POST /jwt/custom/revoke/bulk—yesyes, admin-gated
POST /jwt/custom/extendvia /custom-jwt-extendyesyes, admin-gated
POST /jwt/custom/list/me—yesyes
POST /introspect—yesyes
GET /introspect/types—yesyes
GET /auth/providers(implicit)yesyes
GET /auth/login/{id}via Spring Security OAuth2yesyes
GET /auth/callback/{id}via /authenticateyesyes (+ real ID-token verification)
GET /auth/session/validate—yesyes
GET /auth/profilevia /userinfo (cookie)yesyes
POST /auth/logoutvia /logoutyesyes
GET /jwt/userinfoyes (cookie)droppedrestored (legacy, public)
POST /jwt/blacklistyesdroppedrestored (legacy, admin-gated)
POST /jwt/custom-jwt-blacklistyesdroppedrestored (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

FieldJVM 2.0TIM-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

FieldJVM 2.0TIM-on-Rust
status"extended""extended" ← parity restored
jwt_name on missing"EXTENDED_TOKEN""EXTENDED_TOKEN" ← parity restored
Default expirationInMinutes6060 ← parity restored
HTTP on expired/revoked401422 (Rust chose 422 as more precise; JVM callers switching on 401 need to add 422 to their branch)

POST /jwt/custom/revoke

SituationJVM 2.0TIM-on-Rust
Newly revoked200 {"status": "revoked"}200 {"status": "revoked", "message": "..."}
Idempotent repeat409 {"status": "already_revoked"}409 {"status": "already_revoked", "message": "..."}

Parity restored.

POST /jwt/custom/validate

SituationJVM 2.0TIM-on-Rust
Valid + active200200
Invalid or revoked401 with response body401 ← 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

FieldJVM 2.0TIM-on-Rust
Request offsetpage numberpage number (opt into row-offset with by_row: true)
Request limitpage size (default 20)page size (default 20)
Request jwtNameaccepted (JVM bug: silently ignored)accepted and honoured
Response pagepresentpresent
Response sizepresentpresent
Response total_pagespresentpresent
Response offsetabsentadditionally present (row offset)
Response limitabsentadditionally present (page size)
Denylist checkyesyes ← now checked (was missing in initial Rust cut)

GET /jwt/keys/public

ShapeJVM 2.0TIM-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

FieldPurposeDefault
server.public_base_urlExternal TIM URL; used for default callback synthesis""
database.acquire_timeout_secondsPool timeout knob30
database.idle_timeout_secondsPool timeout knob600
database.max_lifetime_secondsPool timeout knob1800
jwt.cookie_nameCookie name for legacy endpoints"jwt"
oauth2.state_max_age_secondsoauth_state row max age300
oauth2.session_sweep_interval_secondsSweeper interval60
oauth2.session_encryption_key_envEnv var for AEAD key"TIM_SESSION_ENCRYPTION_KEY"
oauth2.providers.<id>.allowed_redirect_urisPer-provider allow-list[]
security.admin_token_envEnv var for admin token"TIM_ADMIN_TOKEN" (empty in defaults)
security.require_admin_tokenRefuse boot if unresolvedtrue
security.cors_allowed_originsCORS origin list[]
security.content_security_policyCSP header(see Security hardening)
security.strict_transport_securityHSTS header(see Security hardening)
security.referrer_policyReferrer-Policy header"no-referrer"
security.x_frame_optionsX-Frame-Options header"DENY"
security.x_content_type_optionsX-Content-Type-Options header"nosniff"

Migration checklist

For each existing JVM 2.0 deployment:

  1. Generate an admin token and set TIM_ADMIN_TOKEN in the environment.
  2. Set server.public_base_url in tim.yaml.
  3. For every provider block, add allowed_redirect_uris: [<canonical URL>].
  4. Decide session store: keep memory (single replica) or switch to postgres (multi replica). If Postgres, generate a 32-byte hex key and set TIM_SESSION_ENCRYPTION_KEY.
  5. Update client-side callers that switched on body.status == "ok" — the value is now "created" for generate and "extended" for extend.
  6. Update client-side callers that expected 200 for every validate response — invalid tokens now return 401.
  7. Update client-side callers that expected 200 for idempotent revokes — repeat revocations now return 409.
  8. If you consume /jwt/keys/public, unwrap the JVM's {"jwk": "..."} wrapper — TIM-on-Rust returns the bare JWKS.
  9. 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 UserInfo shape from the original /jwt/userinfo has been simplified — Estonian-specific fields (channel type, personal ID) are gone; extract them from the claims map 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

StatusCauseResponse body
200Success.Endpoint-specific JSON.
400Invalid JSON, missing required field, or field out of range.{"error":"bad_request","detail":"..."}
401Bearer / admin token required and missing / malformed.{"error":"unauthorized"}
403Bearer token valid but caller not permitted.{"error":"forbidden"}
404No such route, or entity not found.{"error":"not_found","detail":"..."}
405Method not allowed on that route.{"error":"method_not_allowed"}
408Request exceeded server.request_timeout_seconds.{"error":"request_timeout"}
409Idempotent-conflict (already-revoked / already-blacklisted).{"status":"already_revoked","message":"..."}
413Request body exceeded server.max_request_bytes or jwt.max_claims_bytes.{"error":"payload_too_large","max":<n>}
415Unsupported Content-Type (only introspect enforces this, and only when body parses in neither JSON nor form).{"error":"unsupported_media_type"}
422Semantic validation failure (invalid audience, ID token failed OIDC checks, extend of expired/revoked token).{"error":"unprocessable_entity","detail":"..."}
500Unhandled internal error. Every occurrence logs with the request ID.{"error":"internal_error"} — no internals leaked.
502Upstream (OAuth2 provider or JWKS endpoint) returned a malformed or unexpected response.{"error":"bad_gateway","detail":"..."}
504Upstream OAuth2 provider exceeded the timeout.{"error":"upstream_timeout","detail":"..."}

Custom JWT endpoints

POST /jwt/custom/generate — admin-gated

StatusCause
200Token issued and persisted. status: "created".
400Missing JWTName, missing / invalid expirationInMinutes, malformed content.
401Admin token missing or wrong.
413content payload larger than jwt.max_claims_bytes.
422audience present but validation is enabled and none of the values are in jwt.audience.allowed.

POST /jwt/custom/validate and /validate/boolean

StatusCause
200Token verified and active.
401Token invalid, expired, or revoked — the response body's reason field explains why.
400Missing 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

StatusCause
200Token added to denylist. {"status":"revoked","message":"..."}
409Already denylisted. {"status":"already_revoked","message":"..."}
400Missing token field, or token signature invalid.
401Admin token missing or wrong.

POST /jwt/custom/revoke/bulk — admin-gated

StatusCause
200Every token in the batch newly revoked.
207Multi-status: mix of newly / already / failed.
409All tokens were already revoked (nothing changed).
400tokens empty, larger than jwt.bulk_revoke_max, or every token failed.
401Admin 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

StatusCause
200New token issued, old token added to denylist. status: "extended".
400Missing token field.
401Admin token missing or wrong.
422Old token is already expired or revoked.

POST /jwt/custom/list/me

StatusCause
200Paginated result.
401Missing / malformed Authorization: Bearer <jwt> header, or the bearer JWT is revoked / expired / has an invalid signature.
400limit > 200 or offset negative.

Legacy compat endpoints

GET /jwt/userinfo — public

StatusCause
200Cookie present and JWT valid. Response body carries userinfo object.
400Cookie header absent, or the named cookie missing.
401Cookie present but JWT revoked / expired / bad signature.

POST /jwt/custom-jwt-blacklist — admin-gated

StatusCause
200{"status":"blacklisted"}.
409{"status":"already_blacklisted"}.
404Named cookie not present on the request.
400Body empty, or JWT signature invalid.
401Admin token missing or wrong.

POST /jwt/blacklist — admin-gated

StatusCause
200Custom JWT (cookie / jti) newly revoked OR session (sessionId) logged out.
409Custom JWT already revoked.
404Jti mode: no TIM-issued JWT with that jti. Session mode: no such session.
400None of the three parameter modes supplied; or ?jwt=<uuid> value not a valid UUID; or cookie JWT unparseable.
401Admin token missing or wrong.

OAuth2 endpoints

GET /auth/login/{provider_id}

StatusCause
200Authorization URL returned.
400Caller-supplied redirect_uri not on the provider's allow-list.
400No redirect_uri supplied and neither the allow-list nor server.public_base_url yield a default.
404Unknown provider ID.
502Upstream discovery fetch failed (after retries).
504Discovery fetch timed out.

GET /auth/callback/{provider_id}

StatusCause
200Session created.
400Missing code or state query param.
400IdP returned error= — body includes error and error_description from the provider.
404Unknown provider ID.
422State does not match a persisted state row (CSRF / replay / expired past state_max_age_seconds).
422Token response has no id_token.
422ID-token verification failed (bad iss, aud, nonce, signature, exp, nbf, iat; symmetric or alg=none refused; kid not in JWKS).
502Token exchange with provider failed / JWKS fetch failed.
504Token exchange timed out.

GET /auth/session/validate and /profile

StatusCause
200Session found; body indicates valid + expiry.
401No session ID supplied via any of the three transports.
404Session not found or expired.

POST /auth/logout

StatusCause
200Session existed and was revoked, OR unknown session (idempotent). Body's status distinguishes.
401No 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

StatusCause
200Standard RFC 7662 response (may report active: false).
400Missing 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

SymbolMeaning
—Public (no credentials required).
adminRequires X-TIM-Admin-Token: <secret> or Authorization: Bearer <secret>.
bearerRequires Authorization: Bearer <TIM-issued JWT> — signature, exp, and denylist checked.
sessionRequires Authorization: Bearer sess_<id>, X-TIM-Session: <id>, or legacy ?session_id=<id>.
cookieRequires Cookie: <jwt.cookie_name>=<TIM-issued JWT>.

Framework

RouteAuthPurpose
GET /health—Liveness check. Always {"status":"ok"}.

Custom JWT

RouteAuthPurpose
POST /jwt/custom/generateadminIssue 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/revokeadminSingle-token denylist. 200 new, 409 already.
POST /jwt/custom/revoke/bulkadminUp to jwt.bulk_revoke_max per call.
POST /jwt/custom/extendadminReissue with preserved claims; old goes to denylist.
POST /jwt/custom/list/mebearerPaginated 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. sub is extracted into the signed sub claim; 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 carries Set-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

RouteAuthPurpose
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 — body token=<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

RouteAuthPurpose
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/validatesessionVerify + touch.
GET /auth/profilesessionReturn canonical profile map.
POST /auth/logoutsessionRevoke 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)

RouteAuthPurpose
GET /healthz—Alias for GET /health.
GET /jwt/verification-key—PEM-formatted JWT signing public key.
GET /jwt/userinfocookieDecode cookie JWT → subject + claims.
POST /jwt/custom-jwt-verifycookieVerify JWT from cookie named in body.
POST /jwt/custom-jwt-userinfocookieRead JWT from cookie named in body → subject + claims.
POST /jwt/custom-jwt-extendadmin + cookieExtend JWT from cookie named in body; refresh cookie.
GET /jwt/extend-jwt-sessionadmin + cookieExtend JWT from jwt.cookie_name cookie; refresh cookie.
POST /jwt/custom-jwt-blacklistadmin + cookieRevoke JWT from named cookie (body = cookie name).
POST /jwt/blacklistadminThree 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

FieldTypeDefaultDescription
server.bindstring"0.0.0.0"Bind address.
server.portu168085TCP listener port.
server.max_request_bytesusize1048576Global request body cap.
server.request_timeout_secondsu6430Per-request deadline.
server.public_base_urlstring""Externally-reachable base URL; used to synthesise the default OAuth2 callback.

database

FieldTypeDefaultDescription
database.url_envstring"TIM_DATABASE_URL"Env var name holding the postgres:// URL.
database.min_connectionsu322Pool floor.
database.max_connectionsu3210Pool ceiling.
database.auto_migratebooltrueRun sqlx::migrate! at startup.
database.acquire_timeout_secondsu6430Pool acquire timeout (0 = sqlx default).
database.idle_timeout_secondsu64600Idle-connection reaper (0 = sqlx default).
database.max_lifetime_secondsu641800Connection max lifetime (0 = sqlx default).

Connections are .test_before_acquire(true) — a stale connection after a PgBouncer bounce is refreshed transparently.

jwt

FieldTypeDefaultDescription
jwt.private_key_pathpath"/opt/tim/keys/jwt-private.pem"PKCS#8 PEM RSA private key.
jwt.key_idstring"tim-rs-1"kid advertised in JWS headers + JWKS.
jwt.issuerstring"TIM"iss claim on every issued token.
jwt.audience.validation_enabledboolfalseIf true, POST /jwt/custom/generate rejects unlisted audiences.
jwt.audience.allowedlist[]Allow-list when validation is enabled.
jwt.audience.defaultstring"tim-service"Fallback aud when the caller omits one.
jwt.max_claims_bytesusize32768Cap on custom claim payload size at generate time.
jwt.bulk_revoke_maxusize100Max tokens per /jwt/custom/revoke/bulk call.
jwt.cookie_namestring"jwt"Cookie name used by the legacy compat endpoints.
jwt.rotation_warn_daysu327Days-before-retirement window at which boot emits a WARN that the previous key is approaching its cliff.
jwt.previous_keyobject(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.

FieldTypeDescription
.private_key_pathpathPKCS#8 PEM path of the retiring key.
.key_idstringkid under which the retiring key was advertised. MUST differ from jwt.key_id.
.retires_atRFC 3339Instant past which the previous key is refused on verification and dropped from JWKS.

Rotation flow:

  1. Generate a new PKCS#8 PEM. Add jwt.previous_key pointing at the OLD path + kid, set retires_at some days in the future (long enough for every downstream verifier to refresh its JWKS cache). Repoint jwt.private_key_path + jwt.key_id at the NEW key.
  2. Deploy TIM. GET /jwt/keys/public now returns both keys; all in-flight tokens continue to verify. New signatures use the new key.
  3. On or after retires_at, the previous key is no longer accepted and is dropped from JWKS. Delete the jwt.previous_key block 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

FieldTypeDefaultDescription
oauth2.session_storestring"memory""memory" or "postgres"; anything else fails at startup.
oauth2.discovery_cache_ttl_secondsu643600OIDC discovery cache TTL per provider.
oauth2.session_ttl_secondsu6486400Hard cap on session lifetime.
oauth2.session_sweep_interval_secondsu6460Background sweeper interval; 0 disables.
oauth2.state_max_age_secondsu64300Max age of an auth.oauth_state row at callback time.
oauth2.session_encryption_key_envstring"TIM_SESSION_ENCRYPTION_KEY"Env var holding the 32-byte hex AEAD key; required when session_store: "postgres".
oauth2.providersmap{}Provider ID → provider config.

oauth2.providers.<id>

FieldTypeDefaultDescription
.namestring(required)Human label.
.discovery_urlstring(required).well-known/openid-configuration URL.
.client_id_envstring(required)Env var name holding the client ID.
.client_secret_envstring(required)Env var name holding the client secret.
.scopeslist["openid","profile","email"]Scopes to request.
.claim_mappingsmap<string,string>{}<canonical> → <IdP claim>.
.token_validation.clock_skew_secondsu6460Leeway for exp, nbf, iat.
.token_validation.cache_ttl_secondsu643600JWKS cache TTL.
.allowed_redirect_urislist[]Allow-list of redirect_uri values. Empty = only the synthesised default.

security

FieldTypeDefaultDescription
security.admin_token_envstring""Env var name holding the admin token.
security.require_admin_tokenbooltrueRefuse boot when admin_token_env is set but empty.
security.cors_allowed_originslist[]CORS origins. ["*"] for wildcard; empty = no CORS layer.
security.content_security_policystring"default-src 'none'; frame-ancestors 'none'"CSP header. Empty = skip.
security.strict_transport_securitystring"max-age=63072000; includeSubDomains"HSTS header. Empty = skip.
security.referrer_policystring"no-referrer"Referrer-Policy header.
security.x_frame_optionsstring"DENY"X-Frame-Options header.
security.x_content_type_optionsstring"nosniff"X-Content-Type-Options header.

Command-line + env

SourcePurpose
--config <path>Explicit config path.
TIM_CONFIGSame, via env.
RUST_LOGtracing_subscriber EnvFilter (info, debug, tim=debug,sqlx=warn).

Startup-refusal matrix

Startup fails hard when:

  • database.url_env env var is unset.
  • security.require_admin_token: true and admin_token_env is unset or its target env var is empty.
  • oauth2.session_store: "postgres" and session_encryption_key_env is empty or the target env var is malformed hex / not 32 bytes.
  • oauth2.session_store is anything other than "memory" or "postgres".
  • Any provider's client_id_env or client_secret_env target 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_use in Cargo.toml [lints.clippy]. Rust 1.99.0's new lint flags async fn inside #[async_trait] blocks (the macro layers its own #[must_use] on top of an already-#[must_use] boxed future), breaking cargo clippy --all-targets -- -D warnings on every PR against dev. The offending attribute is in the async-trait crate's macro expansion, not TIM source. Unblocks the tests CI workflow.

Security

  • Suppress RUSTSEC-2024-0449 (unmaintained unsafe-libyaml) in .cargo/audit.toml and deny.toml with rationale + review date. Pulled in only as a transitive dep of serde_yaml_ng, which parses the operator-supplied YAML config file at startup — not reachable from the network. Unblocks the scheduled security CI workflow. Migration away from serde_yaml_ng is tracked as a follow-up.
  • Update tokio 1.53.1 → 1.54.1 (RUSTSEC-2026-0386, AsyncFd::new I/O-safety unsoundness) and the dev-only rustix 1.1.4 → 1.1.6 (RUSTSEC-2026-0486, xattr zero-length buffer unsoundness) via Cargo.lock. Lockfile-only; no Cargo.toml change.
  • Suppress RUSTSEC-2026-0459 (libsqlite3-sys bundled-SQLite uninitialised-memory disclosure) in .cargo/audit.toml and deny.toml with rationale + review date. The crate is present in Cargo.lock only as an unresolved optional dependency of sqlx-macros-core; TIM enables just the sqlx postgres driver, so no SQLite code is compiled or linked. No sqlx release can pick up the patched libsqlite3-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 daily security workflow 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 now gcr.io/distroless/cc-debian12:nonroot. No shell, no apt, no curl. Move any RUN steps into an earlier builder stage.
  • Custom HEALTHCHECK invoking curl — swap to ["CMD", "/app/tim", "healthcheck"]. The tim healthcheck subcommand probes /health via reqwest and exits 0/1; no shell needed.
  • docker exec <container> sh — no shell exists. Use kubectl debug --image=busybox on 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.
  • tini as PID 1 — removed. TIM is a single-process axum server; child-reaping is a no-op. K8s or docker run --init cover PID-1 signal forwarding externally if needed.

No schema migration required.

Added

  • jwt.previous_key config block (T-7 / F-PR-3) — signing-key rotation with a grace period. JWKS emits both keys and /introspect accepts tokens signed by either while retires_at > now; after retires_at the previous key is dropped from JWKS and refused on verification. Boot + tim doctor emit WARN when the retirement cliff is within jwt.rotation_warn_days days (default 7). See book/src/security-hardening.md §Grace-period rotation.
  • tim healthcheck subcommand (T-12) — probes /health via reqwest and exits 0 on 200 / 1 otherwise. Wired as the docker-compose HEALTHCHECK on the distroless image (which has no curl / shell for CMD-SHELL). --url overrides the default http://127.0.0.1:<server.port>/health; --timeout-seconds bounds the probe (default 5s).

Changed

  • Docker runtime image switched to distroless (T-12 / G1). Was debian:13.6-slim; now gcr.io/distroless/cc-debian12:nonroot. Trivy --severity HIGH,CRITICAL count drops from 65 (3 CRITICAL + 62 HIGH) to 0. Image size shrinks from 119 MB to 32 MB. No shell, no package manager, no curl, no useradd. See "Upgrading from 0.4.0-alpha" above.
  • .cargo/audit.toml (T-13) — reviewed RUSTSEC-2023-0071 (rsa Marvin timing) rationale. Confirmed session-at-rest encryption uses ChaCha20-Poly1305 (not RSA), no RsaPrivateKey::decrypt call path exists. Next review 2027-03-18.

Fixed

  • JWKS thundering herd (T-4 / concurrency mini-audit R-3). src/oauth2/jwks.rs replaces the get() + insert() cache-miss path with Moka's try_get_with, coalescing N concurrent misses on the same jwks_uri into 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 via error::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.rs proves TIM refuses alg=none with a valid kid, HS256-signed-with-public-key, and every symmetric algorithm + none forging the signer's kid — all resolve to {"active": false}. Pins the positive control against a future regression that swaps in a permissive Validation.
  • Slow-body Slowloris probe (T-15). Verified that tower_http::timeout::TimeoutLayer bounds body-read too, not just handler execution: a request that trickles bytes past server.request_timeout_seconds is aborted at the configured deadline. Not vulnerable, but pinned by tests/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 behind AdminAuth, every session-scoped read behind SessionAuth, 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-id headers. 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 (--strict flag) (fleet §8.2). Pre-boot validator: parses tim.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. Exits 0 on all-pass (WARN advisory), 1 on 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=1 env 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 incoming traceparent; 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_endpoints protects /jwt/custom/validate*; introspection.gate_jvm_compat_endpoints protects the three JVM 1.x cookie-borne validation compat endpoints. Both share the same introspection.clients list — one gate, one secret rotation policy. Both default false for BC with existing DSL callers.
  • Structured JSON on 413 responses (audit RUNTIME-v1 FN3, fleet §2.3 / §6.1). Wrapped DefaultBodyLimit with a middleware that returns {"error":"payload_too_large","max":N} with Content-Type: application/json — instead of Axum's default bare-text. Added a Content-Length preflight so an oversize- declared body is rejected before any bytes are read.

Changed

  • BREAKING — introspection.required_client_auth now defaults to true (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::Layer gates ANSI on std::io::stderr().is_terminal(). Colours retained when a developer runs cargo run at 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.
  • bind_is_loopback helper widened (audit PR #9 nit). Previously matched only 127.0.0.1 + ::1; now accepts 127.0.0.0/8, localhost (case-insensitive), [::1], ::ffff:127.0.0.1. Applied uniformly in both AppConfig::validate() and diagnose() — one helper, two callers.
  • Basic auth scheme comparison now case-insensitive (audit PR #4 nit, RFC 7235 §2.1). Basic, basic, BASIC, BaSiC all take the same path. Non-basic schemes (bearer, digest, …) still refused in any casing.

Fixed

  • Empty-string oauth2.providers.<id>.jwks_uri pin 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 tim subcommands + 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_OFFLINE documented.
  • 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 to Authorization: Bearer sess_<id> or X-TIM-Session.
  • JWT validate reason field values may differ for previously mis-classified errors (see ### Fixed on jwt/service.rs). Dashboards keyed on the exact reason string 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::diagnose now warns loudly on two long-standing operator footguns:
    • CORS wildcard exposes cross-origin reads. When security.cors_allowed_origins contains "*", 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 and strict_transport_security lacks preload, TIM names both facts in one line and points at https://hstspreload.org. First-request MITM against non-preloaded HSTS deployments leaks bearer tokens in the clear.
  • src/oauth2/flow.rs — OAuth2 authorization requests now send a per-request code_challenge (SHA-256 base64url-nopad) plus code_challenge_method=S256 per RFC 7636 (PKCE). The 32-byte verifier is persisted alongside state in auth.oauth_state and 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 whose jwks_uri differs, closing the empty-JWKS DoS path against a MITM'd discovery response. Default: unset (no pin), preserving existing behaviour.
  • POST /introspect now supports optional Basic-auth client authentication per RFC 7662 §2.1. Configured via a new introspection section:
    • 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 + IntrospectionGate boot resolver. Fails startup if any referenced client_secret_env is unset when the gate is required.

Changed

  • src/oauth2/flow.rs, src/oauth2/state_sweeper.rs — auth.oauth_state interval expressions rewritten as now() - 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_url and endpoints inside the discovery document (authorization_endpoint, token_endpoint, jwks_uri) must all use https:// or startup / login refuses. Operators intentionally running against a non-TLS mock IdP for dev must set oauth2.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 on jsonwebtoken::errors::ErrorKind variants instead of format!("{e}").contains("expired"). The prior pattern would have silently reclassified every non-expiry error as signature_mismatch on a jsonwebtoken text-format change, hiding real bugs and breaking monitoring keyed on the reason string. New JwtSigner::verify_raw exposes the typed error so classifier logic doesn't lose the kind through the TimError wrapper.
  • src/oauth2/session/postgres.rs — PostgresStore::get now 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 by sweep_expired, which is already scheduled by the state sweeper.

Testing

  • New tests/it_oauth_state_race.rs pins the atomic single-use contract on DELETE ... RETURNING: 32 concurrent callbacks with the same state value 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 posting client_id / client_secret as 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 rejects client_secret_post with 401 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 accept client_secret_post are not currently supported (no user has one).
  • src/oauth2/idtoken.rs — claim mappings now walk dot-separated paths into nested JSON objects via resolve_claim_path. TARA carries given_name and family_name only under profile_attributes, and the previous flat lookup returned None for 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 yields None and does not fall back to a top-level claim with the same trailing segment.
  • src/oauth2/flow.rs — the BadGateway message 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 mapping profile_attributes.given_name resolves the nested value end-to-end; a dotted-path miss does not fall back to a top-level claim; and a profile_from_claims seam test pinning the resolve_claim_path dispatch. 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 sets TIM_ADMIN_TOKEN=smoke-only-not-a-real-secret when 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/validate per 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:

BinaryCountPurpose
cargo test --lib42Config validation, crypto primitives, session-store semantics, admin gate, JWKS parsing, ID-token helpers
it_jwt_lifecycle7Custom JWT generate → validate → extend → revoke
it_legacy_compat15All eight JVM 1.x cookie-borne endpoints end-to-end
it_oauth26Provider registry, session-auth surfaces, health
it_oauth2_callback3End-to-end OAuth2 callback with a mock IdP
it_oauth2_tara7TARA-specific claim shape + five rejection paths
it_regression_findings11Regression 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 match discovery.issuer), aud (must contain client_id), exp, nbf, iat (with configurable clock skew), and mandatory nonce comparison — all constant-time where relevant. Refuses alg=none and symmetric algorithms outright. The 0.1.0-alpha.1 callback did not verify the ID token at all.
  • Mandatory nonce on ID tokens. A missing nonce claim is now a hard rejection; the previous behaviour silently accepted tokens without a nonce claim.
  • oauth2.session_store config 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); oversized expires_in no longer produces an immortal session.
  • POST /jwt/custom/list/me checks 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, /extend now require X-TIM-Admin-Token: or Authorization: Bearer <admin>. Configured via security.admin_token_env. Startup refuses when require_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_uri per-provider allow-list via oauth2.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_code and response_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_seconds are consumed by the ID-token verifier — previously they were parsed but ignored.
  • auth.oauth_state rows have an age cap enforced in the DELETE ... RETURNING clause. Default 300 s (JVM 2.0 parity). A background sweeper reaps stale rows every session_sweep_interval_seconds (default 60 s).
  • Session ID transport moved to headers — Authorization: Bearer sess_<id> or X-TIM-Session: <id> are the primary transports. Legacy ?session_id=<id> query still accepted for backward compatibility.
  • server.public_base_url config field replaces the hardcoded http://localhost:8085 callback synthesis. Empty means "caller must pass ?redirect_uri= explicitly."
  • provider.claim_mappings can 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/revoke returns 409 on idempotent repeat; matches JVM 2.0's semantics.
  • POST /jwt/custom/validate returns 401 on invalid/expired/ revoked tokens; the body's valid/active/reason fields still carry the details. Matches JVM 2.0.
  • POST /jwt/custom/generate returns status: "created"; POST /jwt/custom/extend returns status: "extended". Response-shape parity with JVM 2.0.
  • setCookie: true in request body actually emits Set-Cookie on the response. Attributes: Path=/; HttpOnly; Secure; SameSite=Lax (adds Secure + SameSite beyond 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/extend default TTL is 60 minutes when the caller omits expirationInMinutes (JVM 2.0 parity).
  • POST /jwt/custom/list/me pagination accepts JVM page semantics (offset = page number, limit = page size, default 20); response carries both page/size/total_pages and offset/limit (row shape). Opt-in by_row: true interprets offset as row offset.
  • jwt_name filter is honoured on POST /jwt/custom/list/me (was silently ignored in JVM 2.0).
  • POST /introspect returns uniform {"active": false} on every inactive path (unknown, revoked, expired, wrong issuer, bad signature).
  • POST /introspect accepts 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 for GET /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.ee and tara.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/amr array shape, issuer/kid/alg=none/expiry rejection paths, and profile_attributes not 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 for tim::config::diagnose in 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 from oauth2.session_encryption_key_env (default TIM_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).
  • SessionStore trait with MemoryStore and PostgresStore backends. 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) on AppConfig and every nested struct — a typo in tim.yaml now 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/public returns a bare RFC 7517 JWKS ({"keys":[…]}), not JVM 2.0's {"jwk": "<stringified JWKS>"} wrapper. Legacy callers use GET /jwt/verification-key for the PKCS#1 PEM shape instead.
  • List response carries both pagination shapes (page/size/total_pages AND offset/limit).
  • Set-Cookie attributes add Secure and SameSite=Lax where 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; the oauth2.session_store config knob was accepted but ignored.
  • No admin gate on /jwt/custom/generate or 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 to custom_jwt.jwt_metadata with original_jwt_uuid set to the new token's jti (chain root).
  • POST /jwt/custom/validate — signature, expiration, denylist, optional audience + issuer.
  • POST /jwt/custom/validate/boolean — same checks, plain-text true / false response.
  • POST /jwt/custom/extend — issue a fresh token preserving the original claims + audience; immediately denylists the old one; links the new token via supersedes + original_jwt_uuid.
  • POST /jwt/custom/revoke — insert the token's jti into custom_jwt.denylist.
  • POST /jwt/custom/revoke/bulk — up to 100 tokens per request (configurable via jwt.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 in Authorization).
  • 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: NAME pattern.
  • TimError enum with per-variant HTTP status mapping.
  • Postgres pool via sqlx. Migrations auto-applied when database.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.