Skip to main content

Multi-User Architecture

Status: implemented (the multi-user core, phase 2 of MULTI_USER_PRODUCT_DESIGN.md). Billing, hosted runs and the other items in Follow-ups are not.

One deployment serves many people. Each person has an account and sees and changes only that account's backups, logs, chats, tokens and machines, whether they use the dashboard, the Go API, the MCP server or the Observatory. Anyone with an account can also run the backup worker on their own machine, linked to their account, so its runs show up in the dashboard without the machine ever holding a database connection.

This page describes what was built: the identity model, how each service enforces it, the agent link, the threat model, how to upgrade, and where the implementation differs from the original contract. The route-by-route details live in API_REFERENCE.md, the sign-in setup in AUTH_SETUP.md, the MCP side in MCP_SERVER_DESIGN.md and the worker side in CLI_AUTH_SETUP.md.


Contents​

  1. Accounts
  2. Principals
  3. Isolation
  4. Services
  5. Linking a worker
  6. Threat model
  7. Deploying and upgrading
  8. Differences from the original contract
  9. Follow-ups

Accounts​

An account is one person, identified by their numeric GitHub user id (accounts.github_user_id). Logins, names and email addresses are refreshed on every sign-in, so a GitHub rename keeps the same account and history.

Account 1 is the deployment owner. Migration 000011_accounts creates it unclaimed and gives it every row that existed before accounts, so a single-user deployment keeps all of its history. It belongs to:

  • the GitHub user whose id is OWNER_GITHUB_USER_ID on the API, who claims it on their first GitHub sign-in (audit account.owner_claimed) instead of getting a new account;
  • the Observatory's password login (CHAT_USERNAME);
  • the legacy MCP token (MCP_AUTH_TOKEN), the MCP server's stdio transport by default (MCP_ACCOUNT_ID=1), a self-hosted worker by default (BACKUP_ACCOUNT_ID=1), and requests without credentials to an API running with API_REQUIRE_AUTH=false.

Without OWNER_GITHUB_USER_ID, account 1 stays unclaimed and is reachable only through those last routes.

Some things exist once per deployment and are therefore the owner's alone: the embedding index (managing generations), the Observatory's Prometheus metrics and readiness details, and the MCP host's archive directory.

Who may create an account is decided by the Go API alone (SIGNUP_MODE):

SIGNUP_MODEA new GitHub user gets an account when
allowlist (default)they match ALLOWED_GITHUB_USERS (numeric id, login:id or login) or are the owner
openalways
closednever

Existing accounts can always sign in unless disabled (accounts.disabled_at; there is no admin page yet, so the owner sets it in the database). Only the API reads the two variables: the Observatory admits the GitHub session of any existing, enabled account, so there is no second copy to keep equal. Taking someone off the list stops new accounts, not existing ones; disable the account to shut it out. A disabled account is refused everywhere: by every API process within 2 seconds (each reads identity's revocations at most every 2 s while serving requests), by the Observatory within 60 seconds and by the MCP server within 60 seconds through the API (at once when it checks tokens in the database).

Every account pays (ADR 0022). accounts.plan is pro while a paid period runs and none otherwise; identity sets it from billing's billing.entitlements_v1 (ADR 0018). An account on none signs in, reads its history and export and buys a plan, but links no worker (tenancy.Store.ApproveLink), starts no run (POST /v1/runs) and queues no backup (runstore.QueueRequest): each is 402 PLAN_REQUIRED, read from the database, not the principal cache. The owner's account needs no plan.

Account changes are recorded in audit_events in the same transaction as the change: account.created, account.owner_claimed, token.created, token.revoked, agent.linked and agent.revoked, with the actor (session:<login>, token:<id>, agent:<id>, internal or system).


Principals​

Every request is resolved to one principal: an account, a kind and scopes (tenancy.Principal in src/platform/tenancy, used by the API, the MCP server and the worker). Every query a service runs for the request takes the account from the principal, never from client input; the only exception is X-Account-Id from another platform service (its own credential, or the deprecated INTERNAL_SECRET), and only for the accounts its policy lets it name.

flowchart LR
subgraph creds["Credentials"]
jwt["Session JWT<br/>(dashboard cookie, HS256, JWT_SECRET)"]
pat["Personal access token<br/>ghb_pat_…"]
agt["Agent token<br/>ghb_agt_…"]
sec["Service credential ghb_svc_…<br/>(or INTERNAL_SECRET) + X-Account-Id"]
legacy["Legacy: MCP_AUTH_TOKEN, MCP stdio,<br/>API_REQUIRE_AUTH=false, BACKUP_ACCOUNT_ID"]
end
subgraph resolve["Resolved by"]
verify["VerifySessionJWT<br/>(iss/aud github-backup, account_id required)"]
store["tenancy.Store.ResolveToken<br/>(SHA-256 lookup in api_tokens)"]
hdr["X-Account-Id check<br/>(account exists, not disabled)"]
fixed["Configured account"]
end
p(["Principal<br/>account_id, kind, scopes"])
q[("Every tenant query:<br/>WHERE account_id = principal's")]
jwt --> verify --> p
pat --> store --> p
agt --> store
sec --> hdr --> p
legacy --> fixed --> p
p --> q
CredentialKindScopesAPIMCP serverObservatory
Session JWT, from GitHub sign-in or the password loginsessionread, write✓ (the dashboard's server forwards it)refused✓
Personal access token ghb_pat_personal_tokenread, or read and write✓ except session-only routes✓refused
Agent token ghb_agt_agentagent/v1 run intake onlyrefusedrefused
A service credential ghb_svc_ with X-Account-Id where its policy allowsinternal (service:<name>)read, writeonly the operations its policy gives it(sends it)the routes its policy gives it
INTERNAL_SECRET (deprecated) with X-Account-Idinternalread, write✓ except session-only routes(sends it while it has no credential)✓ on its internal routes
MCP_AUTH_TOKEN (deprecated)owner_legacyread, writeowner only
No credentials, API_REQUIRE_AUTH=falseowner_legacyreadowner only
  • Session JWT. HS256 with the JWT_SECRET shared by the dashboard, the API and the Observatory; iss and aud are github-backup; sub is the login (or CHAT_USERNAME), account_id the account as a JSON number; GitHub sessions add github_id and amr: ["github"]. The dashboard keeps it in the httpOnly ghb_session cookie and its server forwards it as Authorization: Bearer; browser code never sees it. A token without account_id was issued before accounts and is refused everywhere ("sign in again"). Sessions are stateless and last JWT_EXPIRES_MINUTES (60 by default).
  • Personal access tokens are created on Settings > Access Tokens (sessions only), with an expiry of 30, 90 (default) or 365 days or none, at most 20 active per account. The token is ghb_pat_ plus 43 base64url characters of 32 random bytes, shown once; only its SHA-256 and a display form (ghb_pat_…a1b2) are stored. last_used_at is written at most once a minute. Revocation takes effect on the next request (the MCP server without a database caches a verification for up to 60 seconds).
  • Agent tokens are issued only by the link flow, have no expiry and are revoked with their agent on Settings > Agents. An account has at most 10 active agents (tenancy.MaxAgents).
  • Platform services (the dashboard's server, the Observatory, the MCP server) send their own credential in X-Service-Credential (ADR 0009), SERVICE_CREDENTIAL in each, when it is set; otherwise the deprecated INTERNAL_SECRET, never both. The API keeps only hashes and a policy by operationId: each service may call only the operations it uses, and for each it may name no account, only the owner's, or must name one (403 FORBIDDEN, 403 ACCOUNT_NOT_ALLOWED, 400 ACCOUNT_REQUIRED otherwise). The Observatory keeps the same hashes and a policy by route: the dashboard's password logins and the MCP server's search. The MCP server's credential acts for the owner only: its other users reach the API with their own personal token.
  • Internal callers, deprecated (until every service sends its credential) send X-Internal-Secret. To act for an account they also send X-Account-Id; an account-scoped route without it answers 400 ACCOUNT_REQUIRED, an unknown account 404, a disabled one 403 ACCOUNT_DISABLED. The header is ignored without the secret.

Precedence. A service credential wins when several credentials are present, then the internal secret, a bearer is read by its shape (ghb_pat_/ghb_agt_ go to the token store, three dot-separated parts are a JWT), and an invalid credential is 401 even when another one in the same request would be valid. Scope failures are 403 FORBIDDEN with the required scope; write implies read. Credentials in a URL (?token=) are never read.

Session-only routes. Creating, listing and revoking personal tokens, revoking agents, and looking up and approving agent links need a session: a stolen personal token cannot mint more tokens or link machines, and neither can INTERNAL_SECRET.


Isolation​

Isolation is enforced in application code (row-level security is a follow-up):

  • Every read and write of a tenant table carries account_id = $n from the principal. An id that belongs to another account answers 404, exactly like an id that does not exist, never 403, which would reveal that it exists.
  • The tenant tables are backup_runs, backup_results, execution_logs, analytics_snapshots, backup_fixes, backup_run_requests, worker_repo_state, worker_run_lease, ai_chat_sessions, ai_reports, investigations, ai_tool_confirmations and embedding_chunks. Each has account_id BIGINT NOT NULL REFERENCES accounts with no default, so an insert that forgets its account fails instead of landing in the owner's data, and an (account_id, <sort column>) index. idx_backup_results_account_repo_latest serves each account's newest result per repository.
  • research_samples holds research telemetry, which is off unless the account turns it on under Settings > Research (a signed-in session only: /api/me/research, served by the runs service, refuses tokens and the internal caller; consent lives in runs.research_consent, ADR 0012). Its account_id exists so that turning research off deletes the account's samples in the same transaction; no route reads the table. A row has no name, path or file: the repository id and the commits are HMACs keyed with RESEARCH_HMAC_KEY, so samples match each other across runs and match nothing else. Rows are deleted after 365 days.
  • Child tables (backup_run_errors, backup_result_errors, backup_fix_commits, backup_run_fixes, ai_chat_messages, ai_session_metadata, the ai_tool_calls tables, investigation_errors, embedding_chunk_metadata) have no column: code reaches them only through their scoped parent (chat messages through ai_chat_sessions.account_id).
  • worker_repo_state and worker_run_lease are keyed by (account_id, …): every account has its own repository state and its own run lease, so one machine runs each account's backup at a time, and accounts never block each other.
  • The embedding index is one per deployment, but every chunk keeps its source row's account_id and every search filters on it. Because the HNSW index returns candidates of every account before that filter, the Observatory scans it iteratively on pgvector 0.8.0 or later (hnsw.iterative_scan = relaxed_order, at most VECTOR_SEARCH_MAX_SCAN_TUPLES entries), so an account with few chunks next to one with many still gets its own nearest chunks; an older pgvector logs a warning and may return fewer semantic matches for such an account.
  • ai_openrouter_credentials holds one key per account (account_id unique). The table's primary key is still the old username column; new rows store account:<id> there, which no GitHub login can collide with.
  • The live log feed (/api/logs/stream, /ws/live) polls all new rows once and hands each subscriber only its own account's rows, also when resuming. An account may hold 10 live streams at once and an API process 500 (429 TOO_MANY_STREAMS, 503 SERVICE_BUSY), and /ws handshakes count against the rate limits. Both streams end after 5 minutes and check the caller's credential again at every ping (tenancy.Cache.CheckPrincipal, an answer at most 30 s old and forgotten within 2 s of a revocation), so a revoked or expired token, an expired session or a disabled account stops streaming within a ping interval (15 s for SSE, 30 s for the WebSocket) plus those 30 s.
  • src/platform/runstore holds the SQL of backup runs (telemetry, lease, schedule, request queue, repository state), every function taking the account. A self-hosted worker and the API's /v1 intake for linked workers both write through it, so their rows are identical.

Every service has cross-tenant tests: two accounts with data, every route or tool checked for 404 on the other account's ids and for lists holding only its own rows.


Services​

Dashboard​

  • GitHub sign-in (OAuth web flow with PKCE): after GitHub confirms the user, the dashboard's server calls the API's POST /api/internal/accounts/github with its own credential (SERVICE_CREDENTIAL, else the deprecated INTERNAL_SECRET); the answer's account id goes into the session JWT. 403 SIGNUP_CLOSED shows the "not allowed" page with the API's reason, while a refused credential (401, 403 FORBIDDEN or ACCOUNT_NOT_ALLOWED) is "Sign-in is not set up correctly"; an unreachable API is a clear 503. The dashboard keeps no allowlist of its own.
  • Password sign-in goes to the Observatory's /auth/login, whose sessions are account 1.
  • Proxies and server pages send the session as the bearer to the API and the Observatory and never add the dashboard's credential to a browser's request. The backup proxy forwards only the GET calls the browser code makes (src/lib/proxy/core.ts), anything else is 404. Without a session both send no credentials and let the service decide, so a server-rendered page shows what the browser's own calls get (the owner's data, read only, from an API with API_REQUIRE_AUTH=false; 401 and an empty page otherwise). The public landing page calls no backend.
  • Pages: Settings > Access Tokens, Settings > Agents and /link work through Next.js server actions, so the browser never holds a token except a new one, once. /link looks a code up first (POST /api/agents/link/lookup, on the server for a code from ?code=) and shows the machine's name, host, worker version and the code's expiry before it offers Approve. An account at the agent limit (409 TOO_MANY_AGENTS) sees the API's message with a link to Settings > Agents.
  • GET /api/auth/session reports isOwner (the session's account_id is 1); the sidebar lists the embeddings page only for the owner, and the page shows an owner-only notice to anyone else.

Go API​

  • middleware.Authenticate resolves the principal on every /api, /ws, /metrics and /v1 request; RequirePrincipal(scope) and RequireKind(session) guard the routes. The API checks the session's account on every request (a deleted account is 401, a disabled one 403), through a per-process cache (tenancy.Cache) that keeps each answer for 30 s; revoking a token or an agent through the API clears it there at once, and every other API process reads identity's revocations (identity.revocations_v1) at most every 2 s while serving requests and forgets what they name. /metrics (Prometheus, system-wide numbers) needs INTERNAL_SECRET.

  • Account routes: GET /api/me; GET/POST /api/tokens and DELETE /api/tokens/:id; GET /api/agents and DELETE /api/agents/:id; POST /api/agents/link/lookup and /approve; POST /api/requests; DELETE /api/me and the exports GET /api/me/export (identity's rows) and GET /api/runs/export (the backup history), sessions only. Deleting an account removes identity's and the assistant's rows at once and the backup history and dashboard totals within about 12 hours, when the runs and insights services take the account.deleted event (the answer lists them in pending); the dashboard joins the two exports and the assistant's into one download. Internal: POST /api/internal/accounts/github, GET /api/internal/accounts/:id (for operators and other services; the bundled services do not call it) and POST /api/internal/tokens/resolve (the MCP server's token check, below). See API_REFERENCE.md.

  • POST /api/requests (write) queues a backup of one repository (owner/name; a trailing .git is dropped and it is stored in lower case) or of every repository (null), with a reason of at most 500 bytes. It answers 201 with "queued": true for a new request, and 200 with "queued": false and the existing request when the account already has a pending one for the same target, so a retry never queues a second run. requested_by is the principal (session:<login>, token:<id>); only internal callers may name it (the MCP server sends mcp).

  • Rate limits run after authentication, so only a verified credential chooses a bucket (details):

    CallerLimit per minuteKeyed on
    Session or personal token300the account
    Agent token600the agent
    All agent tokens of an account1200the account
    No credentials (and the legacy owner)100the client address
    Internal secret with X-Forwarded-For300the forwarded address
    Internal secret without itnot limited
    Lookups of unknown tokens (not revoked or expired ones)60the client address; for the MCP server's token checks the end client's (X-Client-Address)
    POST /api/internal/tokens/resolvenot limited
    POST /v1/agent/link10the client address
    POST /v1/agent/link/token60the client address
  • The /v1 run intake for linked workers (agent tokens only) is described under Linking a worker. Bodies are limited to 2 MiB, batches to 500 logs or results.

Observatory​

  • get_current_user returns CurrentUser(username, account_id) from the session JWT; every table access (sessions, messages through their session, investigations, reports, confirmations, credentials, search) is scoped to it. A client may choose the id of a new chat session (the dashboard does); an id another account's session already has is ignored on POST /sessions and the chat routes, and the caller gets a new session under a fresh id with the same answer as any new session, so no 404 tells that the other session exists. The chat routes report the session a turn ran in (data.session_id, the stream's info event). The agent's tools call the Go API with the Observatory's own credential (SERVICE_CREDENTIAL, else the deprecated INTERNAL_SECRET) and the user's X-Account-Id. The embedding indexer copies each source row's account_id into embedding_chunks.
  • Personal tokens are not accepted: the Observatory is the AI chat for signed-in users.
  • Internal callers must send X-Account-Id on /search (400 ACCOUNT_REQUIRED); they use the server's OpenRouter key pool, never a user's key.
  • Owner only: every /embeddings/* route (starting, processing, activating, switching, deleting and pruning generations; the model lists stay public), because one index serves every account and a generation built with one account's OpenRouter key would send every account's rows to that key; /metrics and the readiness details (the owner or an internal caller).
  • In the dashboard a report is the assistant's answer, which its Download button saves as Markdown. Reports stored with POST /reports belong to the account, which downloads them with GET /reports/{id}/download (a direct call; the dashboard's proxy does not forward /reports) or GET /me/export. Nothing sends them anywhere, so no account can mail anyone (ADR 0020).
  • A user's connected OpenRouter key is read and written by account_id. The migration leaves every key connected before accounts without one, because a key stored under a username cannot be tied to an account reliably (the only key of a deployment may be an allowlisted collaborator's, which the owner would then spend). Before the owner's first key lookup, each Observatory process gives account 1 the key stored under CHAT_USERNAME (the password login, which GitHub sessions could never use) if the owner has none yet: one idempotent UPDATE, logged. Everyone else connects OpenRouter again once.

MCP server​

  • The HTTP transports (Streamable HTTP /mcp and the legacy SSE transport) accept personal tokens and the deprecated MCP_AUTH_TOKEN (the owner, read and write, with a one-time warning). Tokens are verified by the API (the MCP server has no database), cached for 10 seconds under the token's SHA-256 and dropped as soon as the API refuses the token on a forwarded call (refusals for 30 seconds; an API 429 is passed on with its Retry-After): with the MCP server's own credential (SERVICE_CREDENTIAL, else the deprecated INTERNAL_SECRET) through the internal POST /api/internal/tokens/resolve, which answers what GET /api/me would and counts unknown tokens against the client's address that the MCP server sends in X-Client-Address (a missing or invalid one against one shared bucket); without either through GET /api/me, from the MCP server's own address. Agent tokens and session JWTs get 401 with WWW-Authenticate: Bearer realm="github-backup-mcp".
  • Limits. Like the API, 60 unknown or malformed tokens a minute per client address, then 429 with Retry-After (the client address is the peer's unless it is in TRUSTED_PROXIES, resolved by the same src/platform/clientip as the API's). 120 tool calls a minute per account, then the tool error "rate limit exceeded, retry in Ns". Each process counts on its own.
  • Every tool and resource takes the caller from the context and asks the API, or the Observatory for search, for that account; the MCP server runs no SQL. trigger_backup_run and record_backup_fix need write ("this token is read-only" otherwise). Calls to the API forward the caller's own personal token; for the owner without one (stdio, MCP_AUTH_TOKEN) they send the MCP server's credential with X-Account-Id: 1, the only account the API lets it name, and another account without a token is refused before the call. Without SERVICE_CREDENTIAL they send INTERNAL_SECRET with X-Account-Id for every caller, as before.
  • trigger_backup_run queues through the API's POST /api/requests and record_backup_fix records through POST /api/fixes. Each write carries an Idempotency-Key and is retried once after a transport error or a 5xx; record_backup_fix takes the key as idempotency_key, so a client retrying a call whose answer it lost records one fix (the API keeps one pending request per target either way). A caller the API cannot be called for (the owner without SERVICE_CREDENTIAL or INTERNAL_SECRET, or another account without a token while the server has its credential) gets a tool error.
  • Archive tools read the MCP host's disk, which holds the owner's archives only: other accounts get "archives are on your own machine; use the worker".
  • SSE sessions are bound to their account: the session id is <account id>.<32 random hex digits>, and a message posted to it with another account's token is refused like an unknown session (400).
  • stdio runs as the account of MCP_PERSONAL_TOKEN with that token's scopes, resolved once with the API at startup; without one, as MCP_ACCOUNT_ID (default 1) with read and write, which the API allows for the owner only (another account needs the token). The HTTP transports start when the API can verify personal tokens or MCP_AUTH_TOKEN is set. DATABASE_URL is ignored with a warning, and RATELIMIT_BACKEND=postgres counts in process (use valkey to share the counts).

Worker​

ModeChosen whenLease, schedule, requests, telemetry
Self-hostedDATABASE_URL is setPostgreSQL directly (runstore), for BACKUP_ACCOUNT_ID (default 1)
Linkedno DATABASE_URL, and an agent token is stored for GHB_CONTROL_PLANE_URL (or for the only linked control plane)the API's /v1 routes, for the agent's account; repository state in local SQLite
Local onlyneithernone; state in local SQLite

github-backup-worker link, unlink and auth status manage the link; the agent token is stored like a login under agent:<control plane URL> (OS keychain, or the 0600 credentials file) and is never printed or logged. Details: CLI_AUTH_SETUP.md and the worker's README (src/services/github-backup-worker/README.md, "What a linked run sends").


Linking a worker​

Linking is an OAuth 2.0 device authorization grant (RFC 8628) between the worker, the API and a signed-in dashboard user.

sequenceDiagram
participant W as Worker (github-backup-worker link)
participant A as Go API
participant U as User (dashboard /link)
W->>A: POST /v1/agent/link {name, hostname, version}
A-->>W: device_code, user_code BCDF-GHJK, verification_uri, expires_in 600, interval 5
W->>U: prints the code, opens APP_URL/link?code=BCDF-GHJK
loop every interval
W->>A: POST /v1/agent/link/token {device_code}
A-->>W: 400 authorization_pending (or slow_down)
end
U->>A: POST /api/agents/link/lookup {user_code} (session)
A-->>U: agent name, host, version, expiry
U->>A: POST /api/agents/link/approve {user_code} (session)
W->>A: POST /v1/agent/link/token {device_code}
A-->>W: 200 agent_token ghb_agt_… (once), agent_id, account, control_plane
Note over W: stores the token; later polls get expired_token
  • Codes. The device code is 32 random bytes (43 base64url characters; only its SHA-256 is stored). The user code is 8 letters of BCDFGHJKLMNPQRSTVWXZ (no vowels, nothing ambiguous), shown as ABCD-EFGH and accepted as typed. A request expires after 10 minutes and works once.
  • Polling. Faster than the 5 second interval answers slow_down; the poll route is bounded to 60 calls a minute per address as a safety net, starting a link to 10. expired_token covers expired, redeemed and unknown device codes; access_denied an approving account that was disabled meanwhile.
  • Approval needs a session and binds the request to that account. The agent row and its token are created by the next successful poll (audit agent.linked), not at approval. control_plane in the answer is API_PUBLIC_URL, or empty, in which case the worker keeps the URL it linked with. The API refuses to start with an APP_URL that is not https (plain http only for loopback addresses), and the worker accepts only an https control plane except on loopback.

A linked run (control.Linked in the worker) uses the /v1 routes with the agent token as the bearer; every call times out after 15 seconds, follows no redirect and reads at most 1 MiB of answer; a 401 (revoked) stops the run with a hint to link again.

  • Only the holder writes. Logs, results, progress, the snapshot, the completion and the request queue (claim, finish) are taken only for a running run whose lease, <host>:agent<id>:run<id>, the calling agent holds, checked and written in one transaction that locks the lease row; fail-interrupted needs the account's live lease for one of the agent's runs. Anything else is 409 RUN_NOT_HELD: an agent can write neither into another machine's run nor into a finished one. A completion repeated after a lost reply answers 204 and changes nothing. A run that lost its lease to another machine cannot complete; the abandoned-run job fails it later. The worker treats RUN_NOT_HELD (and the heartbeat's LEASE_LOST) as final: it sends nothing more for the run (no retry, no queued telemetry, snapshot, request outcome or completion, and no "could not release the lease" warning), logs once that the run was taken over and will be failed by the abandoned-run job, and exits 1 as for any lost lease.
  • Lease. POST /v1/runs starts a run and takes the account's lease in one call (409 LEASE_HELD names the holder, <host>:agent<id>:run<run id>, and the worker exits 0). The heartbeat renews it every 60 seconds; it expires 600 seconds after the last renewal. After 409 LEASE_LOST, or when renewals failed for the TTL less one heartbeat interval and one two-attempt renewal, the run stops; a 409 RUN_NOT_HELD to any other call stops it at the next heartbeat. Completing the run releases the lease; a run that ends without a completion is completed as failed, unless its lease was lost.
  • POST /v1/runs is not idempotent. A retry after a lost reply would find the lease held by the first attempt, which also left a running run. The worker therefore never repeats it once it may have reached the API; the orphaned run is failed by the API's abandoned-run job once its lease has expired and it has been quiet.
  • Batching. Logs and results are queued and sent every 2 seconds or as soon as 200 are waiting, at most 1 MiB per call. The worker cleans log messages, result errors and the snapshot's head message before sending them with the API's own runstore.CleanText (invalid UTF-8 replaced with U+FFFD, NUL removed, cut to runstore.MaxTextBytes = 8 KiB on a character boundary with a trailing …); the API applies it again to free text (including the completion's error) and cuts longer text instead of refusing the batch. Logs and progress the API does not take are dropped and counted (at most 10,000 logs wait).
  • Retries. A results batch is retried with backoff for up to 2 minutes; one that still fails for a temporary reason (unreachable, 408, 429, 5xx) goes back to the front of the queue for the next flush instead of counting as lost. A batch the API refuses with 400 (an identifier such as the repository name is invalid) is sent once more with every text cut to 4 KiB; refused again, it counts as lost. The completion is retried for up to 2 minutes; the snapshot is sent at most twice, and a snapshot that does not arrive is only logged. Results are idempotent per run and repository (runstore.InsertResults skips a repository the run already has and keeps the last result of a batch, under the run's row lock), so a retried batch never doubles a result, for linked and self-hosted workers alike.
  • Exit. At the end the background flusher is stopped at once (a results call in flight is put back; a log or progress call in flight is finished, as those are sent once). Then the queued logs get 30 seconds, the results left get one 2-minute budget however many batches wait, and the snapshot and the completion are sent, so an outage no longer holds a run for one budget per queued batch. Results or a completion that could not be delivered make the run exit 1, although the backup itself is stored.

Threat model​

What an attacker holding each credential can and cannot do. "Data" means backup runs, results, logs, analytics, fixes, chats, investigations and reports.

CredentialCanCannotContain it by
INTERNAL_SECRETRead and write every account's data through the API (X-Account-Id); use the Observatory's internal route (search) for any account; resolve or create accounts through /api/internal/accounts/github within the sign-up policy (including claiming an unclaimed owner account by naming OWNER_GITHUB_USER_ID); check whether a personal token it holds is valid, and count unknown tokens against any client address (POST /api/internal/tokens/resolve), which locks that address out of token checks for a minute; read /metrics.Mint sessions; create, list or revoke personal tokens; look up or approve links (session-only routes); use the /v1 run intake; read token values (only hashes are stored) or OpenRouter keys.Rotating it on every service at once (it is shared by the dashboard, API, Observatory and MCP server); unsetting it everywhere once every service sends its own credential and ghb_legacy_internal_requests_total stops growing.
A service credential (ghb_svc_)Only what its service's policy names (routes/service.policy.go; at the Observatory, SERVICE_POLICY). The dashboard's: resolve or create accounts at GitHub sign-in within the sign-up policy, read the owner's landing numbers, send password logins to the Observatory with any client address. The MCP server's: check personal tokens (counting unknown ones against any client address), read the owner's backup data and queue the owner's backups, search the Observatory for any account. The Observatory's: read every account's backup data through the insights operations its tools use.Any other operation or route; act for an account its policy does not allow (403); mint sessions or tokens; read token values or OpenRouter keys.Rotating that one credential (a new hash next to the old, then the old removed) without touching the other services'.
JWT_SECRETForge a session for any account: everything that account's user can do in the dashboard, API and Observatory, including creating personal tokens and approving links, which outlive a rotation.Internal routes, /metrics, the /v1 intake.Rotating it (signs everyone out), then reviewing and revoking tokens and agents created meanwhile (audit_events).
A user's session (stolen cookie)That account only, read and write, including new personal tokens and link approvals, until the JWT expires (60 minutes by default).Other accounts; owner-only functions unless it is the owner's.Sessions cannot be revoked one by one: disable the account (accounts.disabled_at; within 2 s at the API, within 60 s elsewhere) or rotate JWT_SECRET. The cookie is httpOnly, SameSite=Lax and Secure, and account changes go through same-origin server actions.
Personal token, readRead that account's data through the API and the MCP server.Write; anything session-only (tokens, agents, links); the Observatory; other accounts.Revoking it: effective on the next request (60 s for an MCP server without a database; an open log stream ends at its next ping).
Personal token, read writeAlso queue backups (POST /api/requests), and record fixes through the MCP server.The same as read.As above.
Agent tokenFor its account only, through /v1: start runs and hold the account's lease (keeping the account's other machines from running while it renews), write telemetry and results into the run it holds, claim and fail queued requests while it holds the lease, read the schedule (last full run, pending count).Read anything through /api (403); use the MCP server or the Observatory; touch another account (404); write into another machine's run or a finished one (409 RUN_NOT_HELD). 600 requests a minute, 1200 for all of an account's agents.Revoking the agent on Settings > Agents (401 on its next request to the API process that revoked it, within 2 s on any other; an open stream of a revoked credential ends within a ping interval).
A link code someone else startedIf a user is talked into approving an attacker's code, the attacker's machine gets an agent token for that user's account (the row above).Anything without the victim's approval in a signed-in session.The page shows the machine's name, host and version and a warning before Approve; codes expire after 10 minutes and work once.
Guessing someone's pending codeApproving a victim's code would bind the victim's machine to the attacker's account, which would then receive that machine's repository names and run telemetry.In practice: 20⁸ ≈ 2.6 × 10¹⁰ codes live 10 minutes, and each lookup or approval needs a session and counts against its account's 300 requests a minute.
METRICS_TOKENRead /metrics of the API and the Observatory: deployment-wide request counts, latencies and the owner's last backup time.Every other route (401); any account's data.Changing it on the services and in Prometheus.
MCP_AUTH_TOKEN (deprecated)The owner's account, read and write, over the MCP server.Other accounts; the API or Observatory directly.Replacing it with personal tokens and unsetting it.
CHAT_USERNAME/CHAT_PASSWORDSign in as the owner (account 1).Other accounts.5 failed attempts per address per 5 minutes; rotating the password.
The database (DATABASE_URL)Everything: isolation is enforced in application code.Decrypt connected OpenRouter keys without CREDENTIALS_ENCRYPTION_KEY; use any token (only hashes are stored).Row-level security as a second layer is a follow-up.
No credentialsHealth checks; start link requests (10 a minute per address) and poll them; sign up as the policy allows.Any account's data.SIGNUP_MODE; the per-address limits.

Residual risks worth knowing:

  • Signed-in users share one deployment. With SIGNUP_MODE=open, anyone with a GitHub account gets an account; isolation protects the others' data, but nothing limits runs or storage per account until plans are enforced (agents are capped at 10 per account and their intake at 1200 requests a minute).
  • Ids are global sequences. Run, log, result, token, agent and link ids come from deployment-wide sequences, not per-account ones, so the gaps between one account's ids reveal roughly how much the other accounts did in between (runs started, logs written, tokens created). No other account's data is reachable through them (another account's id answers 404); this is accepted as a limitation of sharing one database.
  • Expired link requests are kept (marked expired), so a flood of link starts from many addresses grows agent_link_requests; pruning old rows is a small follow-up.
  • A taken chat session id is still visible by comparison. When a client sends a session id another account has, the new session it gets has a different id, so a client that already knows someone's session id can confirm that it exists (nothing more). Session ids are random UUIDs, and honouring client-chosen ids is what lets the dashboard name a chat before the first answer. The dashboard always continues with the id the Observatory returns (the POST /sessions answer and the stream's info event), so assigning every id on the server would close this without a dashboard change.
  • The owner's account holds deployment-wide powers (the embedding index, metrics, the MCP host's archives); protect the owner's GitHub account and the password login accordingly.

Fixed:

  • One MCP client could lock every MCP user out of token checks. An MCP server without DATABASE_URL checked every token with GET /api/me from its own address, where the API allows 60 unknown tokens a minute, so one client using that budget (or several together) made the API answer 429 to the MCP server for everyone whose token was not cached. With its own credential (or INTERNAL_SECRET) the MCP server now asks the internal POST /api/internal/tokens/resolve and names the client's address (X-Client-Address, from its own peer address or TRUSTED_PROXIES); the API counts unknown tokens against that client, in the same budget as the tokens the client sends it directly (a missing or invalid address in one shared bucket), and does not limit the route per caller address. A client past the limit gets 429 while every other client keeps working. The risk remains only for an MCP server without a credential of its own (SERVICE_CREDENTIAL or INTERNAL_SECRET), which still uses GET /api/me (and, with one warning, for an API that predates the route).

Deploying and upgrading​

Migration 000011_accounts is applied by the first API of this release that starts, or by make migrate (github-backup-worker migrate); a self-hosted worker never migrates on its own and stops until the migration is applied. Both allow the migrations 5 minutes: 000011 validates foreign keys and builds indexes on the large tenant tables inside one transaction, which takes minutes on a long history. After it, a service from an earlier release fails every insert into a tenant table (its inserts name no account_id), so deploy every service of this release together, right after the migration.

  1. Back up the database (sudo ghb backup on a self-hosted machine). 000011_accounts.down.sql exists for reference only; the runner never executes it.

  2. Set the variables. Generate secrets with openssl rand -base64 48.

    ServiceVariables
    Go APIJWT_SECRET (same value as the dashboard's and the Observatory's, 32+ characters; required while API_REQUIRE_AUTH=true), INTERNAL_SECRET (32+), APP_URL (the dashboard's https origin, for <APP_URL>/link), OWNER_GITHUB_USER_ID (your numeric GitHub id: gh api users/<login> --jq .id), SIGNUP_MODE and ALLOWED_GITHUB_USERS, optionally API_PUBLIC_URL
    ObservatoryJWT_SECRET (same), SERVICE_CREDENTIALS (the same hashes as the API's) and its own SERVICE_CREDENTIAL (or the deprecated INTERNAL_SECRET)
    DashboardJWT_SECRET (same), SERVICE_CREDENTIAL (its own, ADR 0009; or the deprecated INTERNAL_SECRET, the same as the API's), APP_URL, optionally PUBLIC_API_URL (shown in the link instructions); it no longer reads ALLOWED_GITHUB_USERS
    MCP serverSERVICE_CREDENTIAL (its own, ADR 0009; or the deprecated INTERNAL_SECRET) and BACKEND_URL for the API fallbacks; MCP_AUTH_TOKEN is optional and deprecated
    Workernothing for a self-hosted machine (BACKUP_ACCOUNT_ID defaults to 1); GHB_CONTROL_PLANE_URL for a linked one

    docker-compose.yml and deploy/selfhost/compose.yaml pass all of these. With APP_ENV=production the API refuses to start without OWNER_GITHUB_USER_ID.

  3. Deploy the API, the dashboard, the Observatory, the MCP server and every self-hosted worker of this release in one window.

  4. Sign in again. Session cookies without account_id count as signed out, so everyone signs in once. The owner signs in with GitHub to claim account 1 (or uses the password login).

  5. Reconnect OpenRouter where needed. Keys connected before accounts stay unassigned. The Observatory gives the owner the key the password login (CHAT_USERNAME) connected, on the owner's first lookup (logged once); anyone else, including an owner who connected theirs through a GitHub session, connects OpenRouter again on Settings.

  6. Move MCP clients to personal tokens (one per client, read or read and write), then unset MCP_AUTH_TOKEN.

  7. Link other machines with github-backup-worker link --control-plane <API URL>, approve them on /link and run make update (setup asks the worker's auth status whether it is linked and then checks daily for a missed backup; GHB_CONTROL_PLANE_URL alone does not count), or keep them self-hosted with DATABASE_URL and the right BACKUP_ACCOUNT_ID.

Rolling back after the migration means restoring the backup from step 1 together with the previous release of every service.

On a self-hosted machine (deploy/selfhost/README.md) ghb deploy dumps the database, runs github-backup-api migrate --roles, then starts every service of the release together and waits until all are healthy. If they are not, it starts the previous release again only when the release applied no migration (a previous release refuses a schema it does not know); otherwise ghb rollback --restore restores the dump made before migrating.


Differences from the original contract​

The services were built in parallel from one contract. These are the places where what was built differs from it or goes beyond it:

  • API rate limits per account, agent and address. The contract only limited the link start per address. Limits now run after authentication and are keyed on the account (sessions and personal tokens), the agent, or the client address (no credentials, failed token lookups); see Go API.
  • POST /api/agents/link/lookup (session only, {"user_code"} → {user_code, agent_name, hostname, version, expires_at}, 404 for an unknown, expired, used or approved code) was added so /link can name the machine before the user approves it, which the contract asked of the page but gave it no route for.
  • POST /api/requests answers 200 with "queued": false and the existing request when one is pending for the same target, instead of always 201; only internal callers may set requested_by; the target is normalized (lower case, no .git).
  • Owner-only embeddings and metrics. The Observatory's /embeddings/* management routes serve the owner only, and its /metrics and readiness details the owner and internal callers only, because the index and the metrics are deployment-wide.
  • ai_openrouter_credentials keys. The primary key stays username; rows written since the migration use account:<id> there and are read by account_id. The migration assigns no existing key; the Observatory gives the owner only the password login's key.
  • Another account's chat session id is not a 404 when creating. POST /sessions and the chat routes treat it like an id they cannot use and create a new session under a fresh id, because a 404 there, next to an unused id that creates a session, told whether the id existed. Routes that read or change a session (GET, PATCH, DELETE /sessions/{id}, its messages) still answer 404.
  • SSE session binding in the MCP server. Legacy SSE session ids carry their account, and messages posted with another account's token are refused.
  • Link polling limit. POST /v1/agent/link/token is bounded to 60 calls a minute per address, in addition to slow_down.
  • POST /api/internal/tokens/resolve (internal only, {"token"} with X-Client-Address) was added so the MCP server's token checks count unknown tokens per MCP client; the contract had the MCP server use GET /api/me, which it still does without a credential of its own.
  • Linked-mode transport rules. Beyond the contract's flush every 2 s or 200 items, a call carries at most 1 MiB, texts are cleaned and cut to 8 KiB, at most 10,000 logs wait, a results batch refused with 400 is sent once more with 4 KiB texts, queued logs get 30 s at the end, and the results left (within one 2-minute budget) and the completion (2 minutes) are retried before the run exits 1; the snapshot is sent at most twice.
  • POST /v1/runs is not idempotent after a lost reply. The worker never repeats it once it may have reached the API; see Linking a worker.
  • trigger_backup_run without a database queues through the API's POST /api/requests instead of always writing directly.
  • Results are idempotent in runstore, so the API's /v1 intake and a self-hosted worker's retried writes share one rule.
  • The intake takes writes only from the run's holder (409 RUN_NOT_HELD), which the contract did not say; a run that lost its lease is no longer completed by its worker but left to the abandoned-run job, and the worker sends nothing more for it once it gets RUN_NOT_HELD or LEASE_LOST.
  • Agents are capped at 10 active per account (409 TOO_MANY_AGENTS at approval and at the poll that would create the eleventh) and share an account-wide intake limit of 1200 requests a minute.
  • Free text is cut, not refused. Log messages, result errors and the snapshot's head message longer than 8 KiB are cut (runstore.CleanText) where the contract refused the batch.
  • Live streams are bounded. Both end after 5 minutes and recheck the credential at every ping; the contract left /ws/live open.

Follow-ups​

  • OAuth 2.1 for MCP remote connectors. Remote clients such as claude.ai's connectors expect an OAuth 2.1 authorization server (authorization code with PKCE, dynamic client registration) and the protected resource metadata of RFC 9728 (/.well-known/oauth-protected-resource, announced in the WWW-Authenticate challenge), not a pasted bearer token. Until then, MCP clients use personal tokens.
  • Row-level security as a second layer. PostgreSQL policies on every tenant table keyed on a per-transaction setting (SET LOCAL app.account_id), so a forgotten WHERE account_id fails closed. It must work with pooled (transaction-mode) connections.
  • Plan limits beyond runs. accounts.plan (none, pro) gates linking, runs and manual runs (ADR 0022); the Observatory, alerts and personal tokens are not gated, and the paid plan has no limit on agents beyond the 10 every account has.
  • Hosted runs. Backups run on our side for accounts without a machine of their own.
  • Idempotent run start. A client-chosen key on POST /v1/runs (or a lease holder the worker picks before the call), so a retry after a lost reply returns the same run instead of LEASE_HELD and an orphaned running run.
  • Smaller items: pruning old agent_link_requests; per-session revocation (sessions are stateless today); an account-scoped index for the "largest archive" query, which still walks the deployment-wide idx_backup_results_size.