EpsimoAI backend2: authentication guide

This document describes every authentication mechanism backend2 supports, what each is for, and how to use it from a CLI, a script or another service.

Audience. Developers integrating with backend2, building CLI tools, embedding assistants in third-party platforms, wiring up SSO from Cognito, or running a service (LeadGenius) that acts on users' projects.

backend2 shares its database with the legacy backend (https://backend.epsimoagents.com). Login JWTs and normal epsimo_ API keys work on both. Restricted epsimopk_ keys and service tokens work only on backend2.


At a glance

# Mechanism How to get it Sent as Lifetime Revocable Best for
1 Login JWT (email + password) POST /auth/login Authorization: Bearer <jwt> 30 days No Frontend login, personal CLI
2 Google OAuth JWT GET /auth/google/login → /auth/google/callback Authorization: Bearer <jwt> 30 days No "Sign in with Google"
3 Project JWT GET /projects/{project_id} Authorization: Bearer <jwt> 30 days No Pinning a token to one project
4 Revocable session / project token POST /auth/tokens Authorization: Bearer <jwt> 1-720 h (default 24 h) Yes, DELETE /auth/tokens/{token_id} Scripts that need a JWT you can kill
5 API key (normal) POST /auth/api-keys Authorization: Bearer epsimo_... Until revoked Yes, DELETE /auth/api-keys/{id} CLI, CI, scripts acting for the user
6 API key (restricted) POST /auth/api-keys with "restricted": true Authorization: Bearer epsimopk_... Until revoked Yes A script or integration that must stay inside one project
7 Cognito exchange JWT POST /auth/exchange with a Cognito ID token Authorization: Bearer <jwt> 1 hour No SSO from a Cognito-protected app
8 Service principal token Signed by the service (KMS, RS256) Authorization: Bearer <jwt> At most 300 s Grant revoked at once LeadGenius worker acting on allowlisted projects
9 Agent (public) token PUT /auth/agent-access/{assistant_id} Authorization: Bearer epsimo_pub_... or X-Public-Bot-Token Until rotated Rotate with POST /auth/agent-access/{id}/rotate Embedding one assistant (Typebot, Zapier)
10 Public no-auth assistant Assistant config none n/a n/a Open demo bots
11 Admin token ADMIN_TOKEN env var on the service X-Admin-Token: <token> Until rotated Rotate the env var /admin/* routes only

All JWTs that backend2 mints (login, Google, project, revocable tokens, Cognito exchange) are HS256, signed with the service's JWT key and checked against JWT_ISS (revocable tokens use their own audience). The only RS256 tokens backend2 accepts are service principal tokens, which it verifies against pinned public keys.


1. Email + password login

POST /auth/login
Content-Type: application/json

{"email": "user@example.com", "password": "your-password"}

Response:

{"jwt_token": "eyJ...", "main_agent_id": "<assistant-id>", "main_thread_id": "<thread-id>"}

The JWT carries user_id, project_id (the user's main project), iss, aud and exp (30 days). Send it as Authorization: Bearer <jwt_token>. There is no refresh and no revocation: re-login for a new token. Rotating the service's JWT key invalidates every login token.

Signup is POST /auth/signup, then POST /auth/verify-email with the emailed code, then login. Signup does not return a JWT.

2. Google OAuth

Browser-only flow. GET /auth/google/login redirects to Google; /auth/google/callback mints the same HS256 JWT as login and redirects to <FRONTEND_URL>/auth-callback?jwt_token=.... Server config: BACKEND_URL, FRONTEND_URL, GOOGLE_OAUTH_CLIENT_ID, GOOGLE_OAUTH_SECRET_ID. The Google client must list <BACKEND_URL>/auth/google/callback as an authorized redirect URI. An existing email/password account with the same email cannot sign in with Google (no account merging).

3. Project JWT

GET /projects/{project_id}
Authorization: Bearer <user credential>

Returns {"jwt_token": "..."}: a 30-day HS256 token whose project_id claim is the requested project. 404 if the caller does not own the project. This is a convenience, not an isolation boundary: the token can still open the user's other projects. Use a restricted API key (section 6) when a credential must stay inside one project.

4. Revocable session and project tokens

POST /auth/tokens
Authorization: Bearer <user credential>
Content-Type: application/json

{"kind": "session", "project_id": "<optional project uuid>", "expires_in_hours": 24, "name": "nightly job"}

kind is session or project; expires_in_hours is 1-720 (default 24). The response contains token_id, jwt_token, project_id, expires_at. The JWT carries a jti and a dedicated audience; every request checks the jti against the issued-token table, so DELETE /auth/tokens/{token_id} stops it at once. GET /auth/tokens lists live tokens (never the tokens themselves). Limit: 50 live tokens per user.

5. API keys (normal)

POST /auth/api-keys
Authorization: Bearer <user credential>
Content-Type: application/json

{"name": "CLI", "scope": "project", "project_id": "<project uuid>"}

6. API keys (restricted)

Add "restricted": true to keep a key inside one project:

{"name": "company 42", "scope": "project", "project_id": "<project uuid>", "restricted": true}

7. Cognito → backend2 exchange

POST /auth/exchange
Authorization: Bearer <cognito-id-token>

Response: {"token": "eyJ..."}, an HS256 JWT valid for 1 hour, with the user's user_id, main project_id and email. Use it like a login JWT.

backend2 verifies the Cognito token against the pool's JWKS (signature, iss, aud = app client, expiry) and requires token_use = id (access tokens are refused) and email_verified = true. It then finds or creates the user (provider="cognito") and ensures a main project.

Server config:

Env var Purpose
COGNITO_USER_POOL_ID User pool whose ID tokens are accepted, e.g. us-east-1_AbCdEfGhI
COGNITO_APP_CLIENT_ID App client the tokens must be issued for (aud)
AWS_REGION Region of the user pool

Without these the endpoint returns a configuration error.

7b. Handoff codes (partner apps to chat2)

A signed-in user's server (LeadGenius, ContentGenius) asks for a single-use code; a frontend (chat2) redeems it for a session token. The bearer token never travels in a URL.

POST /auth/handoff
Authorization: Bearer <user JWT>
{"audience": "chat2"}

201 {"code": "<43 chars, A-Z a-z 0-9 _ ->", "audience": "chat2", "expires_in": 60, "expires_at": "<ISO 8601>"}, with Cache-Control: no-store.

POST /auth/handoff/redeem
{"code": "<code>", "audience": "chat2"}

No bearer token. 200 {"jwt_token": "eyJ...", "token_type": "Bearer", "expires_at": "<ISO 8601>", "project_id": "<uuid or null>", "email": "<email or null>"}, with Cache-Control: no-store. The token is a 30-day session token like the one /auth/login returns, but revocable: it carries a jti (audience epsimoai-revocable) recorded as kind handoff:chat2, and stops working when it is revoked. These sessions are not listed by GET /auth/tokens and do not count toward its limit.

POST /auth/handoff/revoke
Authorization: Bearer <user JWT>
{"audience": "chat2"}

200 {"revoked": <n>}, with Cache-Control: no-store. Revokes every live session the user's handoff codes were redeemed for (in every browser); requests with them get 401 Invalid token: this token was revoked or has expired. The partner app calls it when the user signs out there. The same callers as POST /auth/handoff may call it (API keys 403; restricted keys and service tokens get the route-allowlist 403). Log event: handoff_sessions_revoked.

8. Service principal (LeadGenius)

A service principal lets a backend service act on specific projects without a user password or a long-lived secret. backend2 accepts it only for allowlisted projects: an operator grants them, or the project's owner does (see "Owner self-service grants" below).

Token format. A JWT signed with an asymmetric KMS key (RSA_2048, RSASSA_PKCS1_V1_5_SHA_256):

Who pays. Without bill_to_user_id the project's owner pays, as before. With it, the named user is charged by POST /threads/ (the assistant's thread price) and POST /threads/increment-counter, and GET /auth/thread-info returns that user's counters with "billing": "named_user". The thread itself still lives in the token's project, and the POST /threads/ idempotency key stays scoped to the project owner and project. backend2 accepts the claim only if the named user owns at least one project with a live grant to the same service: connecting a project to the service is the consent to be billed by it. Otherwise every request carrying the claim, on any route, gets 403 This service may not bill the named user. and nothing is charged. The check runs on every request (no cache), so revoking the user's last grant stops billing at once. Audit logs carry bill_to_prefix (the first 8 characters), never the full id.

Allowed routes. A service token may call only: POST /threads/, GET /threads/{tid}/state, POST /threads/{tid}/state, POST /threads/increment-counter, POST /runs/stream, GET /auth/thread-info, GET /price/agent, GET /assistants/{aid}, and the three Workbench assistant routes below. Everything else returns 403 This credential is limited to one project .... Restricted epsimopk_ keys do not get the two assistant write routes or POST /threads/{tid}/state.

Thread state writes by a service. POST /threads/{tid}/state accepts only {"values": {"workflow_run": ...}} from a service token. Any other key, a message list, or an empty object returns 403 Service principals may only write the 'workflow_run' key of a thread's state. The thread must be in the token's project, otherwise 404 Thread not found (404 Assistant not found or not accessible. if its assistant is outside the project). Config overrides are refused as for restricted keys.

LeadGenius assistants only. POST /assistants/, GET /assistants/ and PUT /assistants/{aid} are limited to assistants whose metadata.source is one of (stored as config.metadata; the request body accepts a top-level metadata object): - leadgenius-workbench: the Workbench assistant, plain tools allowed (rules below); - leadgenius-sdr-default: the default SDR assistants LeadGenius creates on Start. Same rules, and no tools: type==agent/tools must be absent or [].

Price per assistant. GET /price/agent?assistant_id=<uuid> returns {"price": <float>}, the amount POST /threads/ charges for that assistant (its model's price, default 1). 400 for a non-UUID, 404 when the assistant is not in the caller's reach (a service token sees only its project). Without the parameter the route is unchanged.

Server config. SERVICE_JWT_KEYS_B64 is base64 of a JSON array [{"kid": "...", "service_id": "leadgenius", "public_key": "<PEM or base64 DER from kms:GetPublicKey>"}]. These are public keys. Unset means service auth is off. An invalid value stops the task from starting. Rotation: add a second entry with a new kid, switch signing, remove the old entry.

Allowlist. Grants live in the database and are managed with X-Admin-Token:

Route Effect
GET /admin/service-principals?include_revoked=false Configured services (ids and kids) and grants
PUT /admin/service-principals/{service_id}/projects/{project_id} with {"note": "..."} Grant (or re-grant) a project. The note is required (1-200 characters, no secrets): who approved it and why, for example company 42, approved by <name>. 400 unknown service, 404 unknown project, 422 non-UUID id or bad note
DELETE /admin/service-principals/{service_id}/projects/{project_id} Revoke. Takes effect on the next request (no cache). 404 if there is no live grant

Owner self-service grants

A project's owner can enable or revoke a service on that project without the operator. LeadGenius uses this for its "Connect this project" button: its server exchanges the admin's Cognito ID token (/auth/exchange) and calls PUT with that user's own token. LeadGenius never holds ADMIN_TOKEN and never calls DELETE.

Route Effect
PUT /projects/{project_id}/service-grants/{service_id} with {"note": "..."} Grant your project. 201 with created: true when the grant is created or re-activated; 200 with created: false and the existing grant (note unchanged, including an operator's grant) when it is already live
DELETE /projects/{project_id}/service-grants/{service_id} Revoke the live grant, whoever created it. 200 {"revoked": true}. Takes effect on the next service request

The note is 1-160 printable characters after trimming, no secrets. It is stored as self-service by user <user_id>: <note>.

Checks, in order:

  1. Malformed JSON body: 422 (before authentication).
  2. No or invalid bearer: 401.
  3. Restricted key (epsimopk_) or service token: 403 This credential is limited to one project ... (the routes are in neither RESTRICTED_ROUTES nor SERVICE_ROUTES).
  4. Bad note: 422.
  5. The service is not listed in SERVICE_SELF_GRANT_SERVICES, or has no key in SERVICE_JWT_KEYS_B64: 404 Not Found.
  6. Not a user session (for example an unrestricted epsimo_ API key): 403 Service grants need a signed-in user session. User JWTs, Cognito exchange tokens and revocable session tokens are accepted.
  7. project_id not a UUID: 422 project_id must be a UUID.
  8. Project missing or owned by someone else: 404 Project not found (same response for both).
  9. DELETE only, no live grant: 404 Grant not found.

A grant is inert until the service maps the project on its side (for LeadGenius, the company's project mapping). Revoking stops the service for every customer of the service mapped to that project. Logs: service_grant_self_added, service_grant_self_exists, service_grant_self_revoked (info) and service_grant_self_refused (warning, reason = not_user_principal, not_owner or no_grant); tokens are never logged.

Billing. Thread charges go to the balance of the project owner.

Audit. Every service request logs service_request with the service id, kid, project, owner, on_behalf_of, jti, method and route. Failures log service_auth_failed with a reason code; tokens are never logged. Grants log service_grant_added and service_grant_revoked with the note.

Errors. 401 Invalid service token. (signature, claims, lifetime); 403 This project is not enabled for service {service_id}. (no live grant, deleted project or owner); 403 This credential is limited to one project ... (route outside SERVICE_ROUTES); 503 + Retry-After: 5 when the grant lookup fails.

Trust change. With these routes, whoever holds ADMIN_TOKEN can enable the service on any project in the shared database without the owner's consent, which lets the service read and run that project's threads. Before, the admin token could not reach conversations. Each grant needs a logged note, and only services whose public key is pinned in the ECS environment can be enabled. Owners can revoke any grant on their projects with the self-service DELETE above.

9. Agent (public) tokens

For embedding one assistant in an external platform. Per assistant, not per user.

Calling, OpenAI-compatible:

curl https://backend2.epsimoagents.com/public/openai/v1/chat/completions \
  -H "Authorization: Bearer <agent-token>" \
  -H "Content-Type: application/json" \
  -d '{"model": "gpt-4o", "messages": [{"role": "user", "content": "Hello"}], "stream": false}'

Or the native stream: POST /public/runs/stream with X-Public-Bot-Token: <agent-token> (or the body token field) and assistant_id. The token identifies the assistant; there is no per-caller identity.

10. Public no-auth assistant

Access mode public_no_auth: the same public endpoints accept calls with no token. Anyone can use the assistant and spend its owner's LLM budget.

11. Admin token

Set ADMIN_TOKEN on the service and send it in the X-Admin-Token header. The old admin_token query parameter is no longer accepted.

curl https://backend2.epsimoagents.com/admin/system-stats -H "X-Admin-Token: $ADMIN_TOKEN"

Results: 500 if ADMIN_TOKEN is not set on the service, 401 if the header is missing, 403 if it is wrong. The admin token authorizes only /admin/* (cleanup, stats, service-principal grants). It does not authorize /threads, /assistants or /runs.


How requests are authorized

Authenticated routes read Authorization: Bearer <credential>:

  1. epsimo_... or epsimopk_... → API key lookup. The prefix and the key's restricted flag must agree, otherwise 401 Invalid API key.
  2. A JWT whose header kid matches a configured service key → service principal verification. It never falls back to user-JWT checks.
  3. Any other token → HS256 user JWT: signature, iss, aud, exp; tokens minted by POST /auth/tokens (their own audience) must also be live in the issued-token table.

Missing, malformed, expired or revoked credentials return 401. If AUTH_TYPE, JWT_ISS, JWT_AUD, JWT_ALG or JWT_DECODE_KEY_B64 is missing or invalid, the service does not start.

Restricted principals

Restricted API keys and service principals are tied to one project. Three layers apply:

  1. Route allowlist. Each route template must be in the set for the credential, otherwise 403 This credential is limited to one project and cannot call {METHOD} {path}. New routes are closed until added.

RESTRICTED_ROUTES (restricted API keys):

GET /threads/ POST /threads/ GET /threads/{tid} PUT /threads/{tid} DELETE /threads/{tid} GET /threads/{tid}/state POST /threads/increment-counter POST /runs/ POST /runs/stream GET /assistants/ GET /assistants/{aid} GET /auth/thread-info GET /price/agent

SERVICE_ROUTES (service principals), a subset:

POST /threads/ GET /threads/{tid}/state POST /threads/increment-counter POST /runs/stream GET /assistants/{aid} GET /auth/thread-info GET /price/agent

Neither set includes GET /threads/{tid}/history, /projects/*, /auth/api-keys, /auth/tokens, /auth/agent-access*, /user/*, /billing/*, /checkout/*, /tools/*, assistant writes or files. 2. Project filter. Thread, assistant and project lookups only return rows in the credential's project. Ids in other projects and other users' public assistants return 404, with the same messages as unknown ids. 3. No run-time overrides. Sending config.configurable keys that differ from the assistant's stored config returns 403. Send config: {}.

Restricted principals always get the redacted assistant view, even for the owner's own assistants: no openai_account, no public token, tools without config/headers/env, secret-named keys blanked.

Threads whose assistant is outside the project. A thread inside the project may use another user's public assistant, or an assistant from another of the owner's projects. A restricted credential can neither read nor run such a thread: GET /threads/{tid}/state returns 404 Assistant not found or not accessible. and POST /runs/stream returns 404 Assistant not found. Use the owner's normal credentials for these threads.

Thread state writes (every caller)

POST /threads/{tid}/state always writes into the path thread: a config.configurable.thread_id naming another thread is ignored and a config.configurable.user_id is dropped. Only the assistant's owner may send config.configurable overrides; others get 403.

Server-side env vars for authentication

Env var Purpose
AUTH_TYPE jwt_local in production
JWT_ISS, JWT_AUD Required issuer and audience of user JWTs
JWT_ALG HS256
JWT_DECODE_KEY_B64 Base64 signing and verification key for user JWTs
SERVICE_JWT_KEYS_B64, SERVICE_JWT_AUDIENCE, SERVICE_JWT_MAX_LIFETIME_SECONDS Service principal keys, audience (default epsimo-backend2) and maximum token lifetime (default 300 s)
SERVICE_SELF_GRANT_SERVICES Comma list of service ids whose grants project owners may manage themselves (for example leadgenius). Unset or empty: the owner self-service grant routes return 404. An invalid id stops the task from starting
COGNITO_USER_POOL_ID, COGNITO_APP_CLIENT_ID, AWS_REGION Cognito exchange
ADMIN_TOKEN Admin routes

Store every secret in AWS Secrets Manager and reference it from the ECS task definition secrets field, never environment. Never log secret values.


Idempotent thread creation

POST /threads/ accepts an optional Idempotency-Key header (1-255 visible ASCII characters, scoped to the user and project, kept for IDEMPOTENCY_KEY_TTL_HOURS, default 168). The balance charge and the thread insert commit together.

Result Meaning
200 + Idempotent-Replayed: true Replay of an earlier request with the same key and body; no second charge
400 Invalid key
404 The thread created for this key was deleted
409 + Retry-After: 5 A request with this key is still in progress
422 The key was used with a different body
503 + Retry-After Thread creation busy (5 s) or key storage unavailable (30 s)
504 Timed out: retry once with the same Idempotency-Key

Do not use PUT /threads/{tid} for idempotency: it never creates threads.

POST /threads/increment-counter?count=N accepts the same optional Idempotency-Key header. The key is scoped to the charged user (not to a project) and commits with the charge.

Result Meaning
200, "replayed": false Charged. The body also carries "billing": "named_user" when a service token's bill_to_user_id chose the user
200, "replayed": true + Idempotent-Replayed: true Replay of an earlier charge with the same key and count; no second charge. The counters are the current ones
400 Invalid key or count, or Thread limit would be exceeded. .... A charge refused at the limit does not keep the key, so a retry after a top-up charges
409 + Retry-After: 5 A request with this key is still in progress
422 The key was used with a different count
503 + Retry-After The balance is busy (5 s) or key storage unavailable (30 s)

Without the header the route and its body are unchanged (no replayed field).

Errors and limits

Status When What to do
401 Missing, invalid, expired or revoked credential Fix the credential; do not retry
403 Route outside the credential's allowlist, project not enabled for the service, or run-time config overrides Terminal
404 Id unknown or outside the credential's project Terminal
409 Idempotency-Key in progress Retry after Retry-After
429 Too many runs in flight for this credential on POST /runs/stream or POST /runs/ (RUNS_MAX_INFLIGHT_PER_CREDENTIAL, default 10 per task) Retry after Retry-After
429 More than 10 handoff codes for one user in 60 s on POST /auth/handoff (Retry-After: 60) Retry after Retry-After
503 The task is shutting down (deploy or scale-in), thread creation is busy, or a dependency is unavailable Retry after Retry-After

Headers on these errors, including Retry-After, reach the client.


CORS

The service allows credentialed requests from a fixed origin list (default list in app/server.py, or CORS_ORIGINS, comma-separated). Browser apps on other origins are blocked.

CLI quick start

BASE=https://backend2.epsimoagents.com

# Login once, then create a key (the secret is shown once)
JWT=$(curl -s -X POST $BASE/auth/login -H "Content-Type: application/json" \
  -d '{"email":"you@example.com","password":"..."}' | jq -r .jwt_token)
KEY=$(curl -s -X POST $BASE/auth/api-keys -H "Authorization: Bearer $JWT" \
  -H "Content-Type: application/json" -d '{"name":"CLI"}' | jq -r .api_key)

curl $BASE/threads/ -H "Authorization: Bearer $KEY"

OpenAPI contract and versioning

docs/public/reference/openapi.json is generated by scripts/export_openapi.py and committed. tests/agent/test_openapi_contract.py fails when it is stale. After any change to routes, parameters, models or route docs, run .venv/bin/python scripts/export_openapi.py and commit the file. Bump info.version in app/server.py by a minor version for additive changes and by a major version for breaking ones. This release is 1.3.0.

File map

File Responsibility
app/api/authentication.py /auth/*: login, signup, Google, exchange, API keys, tokens, agent access
app/api/handoff.py, app/handoff.py /auth/handoff and /auth/handoff/redeem; the auth_handoff_code table
app/api/projects.py /projects/*, including the project JWT
app/auth/handlers.py Bearer verification and the AuthedUser dependency
app/auth/scope.py RESTRICTED_ROUTES, SERVICE_ROUTES, project scope
app/auth/service.py Service principal token verification
app/api/admin_service_principals.py /admin/service-principals grants
app/api/service_grants.py /projects/{project_id}/service-grants/{service_id} owner self-service grants
app/api/admin_cleanup.py /admin/* maintenance routes and X-Admin-Token check
app/api/public_runs.py, app/api/openai_v1.py Public and OpenAI-compatible endpoints