Security review — operator surface authentication and tenant isolation
Status: fixed in this branch (changes are uncommitted). Scope: aetherin-server-core, the operator (control-plane) HTTP surface.
This document records the finding, the decision and the rules that were implemented, so the next reviewer can check the decision instead of re-deriving it.
Wave 5 follow-up (this branch). §9 documents the second pass: the usage
and budget endpoints now match the contract, the CSRF token is verified
(it was generated but never checked), the SSRF guard is enforced, the
status codes match the contract, and the three missing workspace endpoints
exist. §9.6 lists the contract changes this pass needs; the contract
itself was not edited (it lives in
aetherin-common).
1. The finding
The core is meant to be private behind the Vercel middleware, but the middleware forwards every path (aetherin-middleware/src/proxy.ts → CORE_URL/<path>). Every operator endpoint therefore had to authorize *itself* — and most of them did not.
Before this change the following endpoints answered without any credential and without any tenant check:
| Surface | Endpoints |
|---|---|
| Keys | GET /v1/keys, GET /v1/keys/{id}, POST /v1/keys, PATCH /v1/keys/{id}, DELETE /v1/keys/{id}, POST /v1/keys/{id}/rotate |
| Usage | GET /v1/usage, GET /v1/usage/events, GET /v1/usage/export.csv |
| Budgets | GET /v1/budgets, POST /v1/budgets, PATCH /v1/budgets/{id} |
| Providers | GET /v1/providers, POST /v1/providers, PATCH /v1/providers/{id}, DELETE /v1/providers/{id}, GET /v1/providers/{id}/health |
| Models | GET /v1/models, GET /v1/models/{id}, POST /v1/models |
| Model routes | GET /v1/models/{id}/routes, POST /v1/models/{id}/routes, DELETE /v1/models/{id}/routes/{routeID} |
| Plugins | GET /v1/plugins, GET /v1/plugins/{id}/config, PATCH /v1/plugins/{id}/config, POST /v1/plugins/install, DELETE /v1/plugins/{id} |
Two concrete impacts:
- Unauthenticated read of the whole control plane — API keys (including
their hashes), provider configuration, the model catalogue, usage and budgets, and the plugin registry were readable by anybody on the internet.
- Unauthenticated write — anybody could mint or revoke client API keys
(i.e. mint themselves a credential for the LLM endpoints), disable providers, change budgets, rewrite model prices and install plugins.
On top of that, the tenant boundary did not exist: GET /v1/keys?workspace_id=<uuid> and GET /v1/providers?workspace_id=<uuid> took the scope straight from the query string. Even once the endpoints authenticate, a member of org A could have read and mutated org B's resources with a valid session.
1.1 Findings beyond the reported list
While implementing the fix, two further gaps were found. Both are fixed here and are called out because the original report assumed they were already closed:
- **
/v1/orgs/*was not protected.** The report listed it as "already
correct (requireUser/requireAdmin/requireOrgRole)". In fact only GET /v1/orgs and POST /v1/orgs checked the session. GET /v1/orgs/{id}, PATCH /v1/orgs/{id}, DELETE /v1/orgs/{id}, GET /v1/orgs/{id}/workspaces and POST /v1/orgs/{id}/workspaces were anonymous: anybody could read an organization, rename it, list its workspaces and create a workspace inside it. Those five handlers are now authorized like the rest of the org surface (see the table in §4).
- The 401 error envelope did not match the contract. The old
writeErr(…, 401, …) helper fills error.code with the HTTP status text ("Unauthorized"); the contract's ErrorCode enum says unauthorized (see openapi/openapi.yaml, components.responses.Unauthorized). All 401 answers now use writeUnauthorized, so the envelope is {"error":{"code":"unauthorized","type":"authentication_error",…}}.
- The billing surface answered 503 before it answered 401.
GET /v1/billing/* checked the Stripe configuration before the session, so an unauthenticated request to a deployment without a Stripe key got 503 instead of 401. The session check now comes first on every billing handler (internal/api/billing.go).
2. The isolation rule
The resource decides the tenant, not the request.
The handler resolves the resource, resolves the organization that owns it,
and checks the caller's *membership role in that organization*. A query
parameter (
workspace_id,key_id,provider_id) is a **scope, never apermission. A global `admin` role does not** imply access to another
organization's data.
The resource → organization chain is fixed and implemented in internal/api/tenant.go:
| Resource | Chain |
|---|---|
| API key | key → workspace → org |
| Provider | provider → workspace → org (a provider without a workspace is deployment scope) |
| Model | model → provider → workspace → org |
| Model route | route → model → provider → workspace → org |
| Budget | budget → api key → workspace → org |
| Usage | key / workspace → org |
| Plugin | no organization: deployment scope |
Consequences:
GET /v1/keys?workspace_id=<org B workspace>as a member of org A → 403.GET /v1/usage?key_id=<org B key>→ 403.GET /v1/providers?workspace_id=<org B workspace>→ 403.- A model route may not point at another organization's model → 403
(a fallback chain must not hand traffic from one tenant to another).
- An unscoped list (
GET /v1/keys,GET /v1/models,GET /v1/providers,
GET /v1/usage, GET /v1/budgets) only ever reports the caller's own organizations (the union of the organizations they own and the ones they are an active member of).
2.1 Status codes
| Situation | Answer |
|---|---|
| No session / expired session / suspended account | 401 + contract error envelope (code: unauthorized, type: authentication_error) |
| Authenticated, but not a member of the resource's organization | 403 (code: forbidden, type: permission_error) |
| Authenticated, member, but the role is too low | 403 |
| The resource does not exist | 404 |
The resource is resolved *before* the access check, so a caller learns whether a resource exists (403 vs 404). That is the same behaviour the existing requireOrgRole helper already had on the org/team/billing surfaces; changing it to a uniform 404 would have meant answering "404" for resources the caller may in fact read.
3. The role model
The Role enum of the contract is used unchanged: owner > admin > billing > member (see internal/api/authorization.go).
Two different role spaces exist and are deliberately not interchangeable:
- the organization role — the caller's membership role in the
organization that owns the resource (org_members.role). It decides everything inside that organization.
- the deployment role — the caller's global user role (
users.role). It
decides the resources that belong to the installation and to no organization at all (a global provider row, the plugin registry). It is the same role the /v1/admin surface already uses.
A membership in one organization never implies access to another, and a global admin never implies access to another organization's data.
3.1 Read surfaces — member and above, scoped to the organization
| Endpoint | Minimum role | Scope |
|---|---|---|
GET /v1/keys | member | workspace_id's org, else the caller's orgs |
GET /v1/keys/{id} | member | the key's org |
GET /v1/usage | member | key_id / workspace_id / the caller's orgs |
GET /v1/usage/events | member | idem |
GET /v1/usage/export.csv | member | idem |
GET /v1/budgets | member | idem |
GET /v1/providers | member | workspace_id's org, else the caller's orgs + global rows |
GET /v1/providers/{id}/health | member | the provider's org (global row: any authenticated member) |
GET /v1/models | member | provider_id's org, else the caller's providers |
GET /v1/models/{id} | member | the model's provider's org |
GET /v1/models/{id}/routes | member | the model's org |
GET /v1/plugins | member | deployment |
GET /v1/plugins/{id}/config | member | deployment |
3.2 Write surfaces — admin and above, owner for the sensitive ones
| Endpoint | Minimum role | Why |
|---|---|---|
POST /v1/keys | admin | minting a credential |
PATCH /v1/keys/{id} | admin | changing the budget/rate limit of a live credential |
DELETE /v1/keys/{id} | admin | revoking a credential cuts off a live client |
POST /v1/keys/{id}/rotate | owner | issues a fresh credential *and* revokes the old one in one call — the most sensitive key operation |
POST /v1/budgets | admin | changes what the organization may spend |
PATCH /v1/budgets/{id} | admin | idem |
POST /v1/providers | admin | adds an upstream and its credential |
PATCH /v1/providers/{id} | admin | rewrites the upstream base URL and rotates the credential |
DELETE /v1/providers/{id} | admin | takes an upstream out of service |
POST /v1/models | admin | adds a priced model (a price is a billing fact) |
POST /v1/models/{id}/routes | admin | rewrites the serving chain |
DELETE /v1/models/{id}/routes/{routeID} | admin | idem |
POST /v1/plugins/install | owner (deployment) | a plugin is code that runs in the process |
PATCH /v1/plugins/{id}/config | owner (deployment) | reconfigures running code |
DELETE /v1/plugins/{id} | owner (deployment) | removes running code |
owner was chosen over admin for key rotation because rotation is the one key operation that hands a *new* credential to the caller and invalidates the old one in the same request; owner is the role the contract already reserves for "the org creator / deployment owner". The plugin surface is owner only because it is a code-execution surface, exactly as the task required.
3.3 Organization surface (fixed in addition to the reported list)
| Endpoint | Minimum role |
|---|---|
GET /v1/orgs | any session (own + member organizations) |
POST /v1/orgs | any session (the caller becomes the owner) |
GET /v1/orgs/{id} | member of that org |
PATCH /v1/orgs/{id} | admin of that org |
DELETE /v1/orgs/{id} | owner of that org |
GET /v1/orgs/{id}/workspaces | member of that org |
POST /v1/orgs/{id}/workspaces | admin of that org |
3.4 Resources without an organization (deployment scope)
Some rows belong to the installation, not to a tenant:
- a provider with `workspace_id = null` — the env-seeded providers
(source = seeded) that the boot seeder writes from the environment;
- the plugin registry.
The rule, stated explicitly:
A deployment-scoped row is visible to any authenticated member (any
session with at least the
memberrole) and **writable byadminor
owner** — where the role is the *global* user role, because a deploymentrow belongs to no organization and therefore has no membership role to
check. The plugin registry is
owneronly.
This is the symmetric counterpart of the existing rule in requireAdmin ("a global admin is not implicitly an org admin"): a global admin is not implicitly an *organization* admin, and an organization admin is not implicitly a *deployment* admin.
The rule is tested both ways (TestGlobalRowsAreVisibleToEveryMember, TestGlobalRowsAreWritableByTheDeploymentAdmin, TestPluginInstallIsOwnerOnly).
4. What was changed
| Area | Change |
|---|---|
internal/api/tenant.go (new) | the tenant resolution helpers: requireWorkspaceAccess, requireKeyAccess, requireProviderAccess, requireModelAccess, requireBudgetAccess, requireOrgAccess, requireDeploymentAccess, plus the "accessible orgs / workspaces / keys / providers / models" helpers and the shared keyset pagination |
internal/api/authorization.go | unchanged — the existing requireUser / requireAdmin / requireOrgRole helpers are the only mechanism used; no second authorization mechanism was introduced |
internal/api/keys.go, usage.go, providers.go, routes.go, plugins.go, orgs.go, billing.go | every handler authenticates first and then resolves the resource → org → role |
internal/api/health.go (new) | GET /v1/healthz and GET /v1/version (see §7) |
internal/store/store.go, internal/store/postgres.go | two new store methods: ListOrgsByMember (the reverse of GetOrgMemberByUser, needed to enumerate the caller's tenants) and GetBudgetByID (the contract addresses a budget by id, the ledger by key) |
internal/billing/ledger.go, internal/billing/csv.go | StreamCSVWorkspaces so an export that may cover several workspaces still produces one CSV document with a single header row |
main.go | the bootstrap account of an empty deployment is created with the global role owner instead of admin (see §6) |
Nothing in internal/kernel/**, pkg/pluginsdk or plugins/** was touched, and go.mod is unchanged (no new dependency).
4.1 Behaviour changes to note
GET /v1/keyswithoutworkspace_idused to answer an empty list (the
store filtered on workspace_id = ''); it now answers the keys of the caller's own organizations.
GET /v1/usage/GET /v1/usage/events/GET /v1/budgetswithout a
scope used to answer the empty scope; they now answer the caller's own organizations.
GET /v1/usage/export.csvwithoutworkspace_idused to export every
workspace of the installation; it now exports the caller's own workspaces.
POST /v1/providerswith aworkspace_idthat does not resolve used to
answer 400; it now answers 404 (the resource is resolved first).
POST /v1/models/{id}/routeswith an unknowntarget_model_idused to
answer 400; it now answers 404 (403 for a target of another organization).
DELETE /v1/keys/{id}for an unknown key used to answer200; it now
answers 404.
- The audit entries of the key/provider handlers now record the acting user
(users.id) instead of the literal system. GET /v1/keys/{id} writes the action key.read; it used to write key.patch for a read.
GET /v1/orgsnow also lists the organizations the caller is a *member* of
(it used to list only the owned ones).
GET /v1/auth/mereturns the same organization list (owned + member), so
the console's organization switcher sees the organizations a member belongs to.
5. Tests
internal/api/tenant_test.go (new) builds a two-tenant fixture (organization A with an owner, an admin and a plain member; organization B with its own owner; each with a workspace, an API key, a budget, a provider, two models, a model route and usage events) and asserts:
| Test | What it proves |
|---|---|
TestOperatorEndpointsRequireSession | 56 endpoints (every operator endpoint, including the org, team, admin and billing surfaces) answer 401 with the contract error envelope when the caller has no session. The endpoint list is the regression list: an endpoint added later without a session check shows up here. |
TestCrossTenantAccessIsDenied | an admin of org A gets 403/404 for org B's key, budget, provider, model, route and usage — 29 cases. The caller is an admin on purpose, so the only reason for a refusal is the tenant boundary. |
TestSameTenantAccessIsAllowed | a member of org A succeeds on org A's own key, usage, budget, provider, model and route (12 cases). |
TestUnscopedListsOnlyShowTheCallersOrganization | the unscoped GET /v1/keys, /v1/models and /v1/providers never contain another organization's rows. |
TestMemberCannotPerformAdminActions | a plain member gets 403 on all 15 write actions (keys, budgets, providers, models, routes, plugins). |
TestAdminCannotRotateKeys | an org admin may not rotate a key (403); the org owner may (200). |
TestGlobalRowsAreVisibleToEveryMember | a provider without a workspace is visible to every authenticated member and reports workspace_id: null. |
TestGlobalRowsAreWritableByTheDeploymentAdmin | a global row is 403 for a member and 200 for a deployment admin. |
TestPluginInstallIsOwnerOnly | installing a plugin is 403 for a deployment admin and 201 for a deployment owner. |
TestRouteCannotBridgeTwoOrganizations | a fallback route may not point at another organization's model. |
TestPublicEndpointsStayOpen | GET /v1/health, GET /v1/healthz and GET /v1/version still answer 200 without a session. |
TestClientEndpointsAuthenticateByAPIKey | POST /v1/chat/completions and POST /v1/embeddings answer 401 without a client key and with an operator session (a session is not a client credential), and accept a valid client API key. |
Results:
gofmt -l . # clean
go build ./... # ok
go vet ./... # ok
go test ./... # ok
go test -race ./internal/api/... # ok
go test -tags=integration ./tests/integration/... # ok (Docker available)The pre-existing provider handler tests (internal/api/providers_test.go) and the integration fixtures (tests/integration/harness_test.go) were adapted: they now authenticate with a session, because the endpoints they exercise require one.
6. Not protected, and why
| Surface | Why |
|---|---|
GET /v1/health, GET /v1/healthz, GET /v1/version | public probes by contract (security: []); they expose no tenant data |
POST /v1/auth/login, POST /v1/auth/register | public by contract |
POST /v1/chat/completions, POST /v1/embeddings | authenticated by the client API key (bearer), not by a session — that is the machine surface |
POST /v1/webhooks/stripe | authenticated by the Stripe-Signature header, not by a session |
GET /metrics | not in the reported scope. It is a counter, but it is reachable without a credential. Recommendation: put it behind the deployment role (or keep it on a private listener) — see §7. |
GET /debug/pprof/* | only mounted when PPROF_ENABLED=true; same recommendation as /metrics |
GET /openapi.json | a static stub, no data |
6.1 Deployment consequence of the owner rule
The plugin surface needs the global owner role, and only a global owner may mint another owner (canGrantRole). The bootstrap account of an empty deployment was created with the global role admin, which would have left the deployment with no way to install plugins through the API. The bootstrap now creates the account with the global role owner (main.go); the /v1/admin surface accepts an owner like an admin, so nothing else changes. Existing deployments are unaffected (the bootstrap only runs on an empty user table) — such a deployment has to promote its operator to the global owner role once, with a direct store update (users.role = 'owner'), because no global owner exists to grant it.
7. Contract changes that are needed (not made here)
The contract is the source of truth and was not edited. These are the changes this work implies:
- The role model has to be in the contract. The spec has a global
security: cookieSession but does not say which role an endpoint needs. Either add an extension (for example x-required-role: admin / x-required-role: owner plus x-scope: organization | deployment) per operation, or add a "Roles" section to the spec's description. Without it, every client has to guess.
- `GET /v1/keys` leaks the key hash. The handler serialises the store
struct, so the response contains KeyHash (the SHA-256 of the secret). The contract's ApiKey schema has no key_hash field, so the response should be a DTO (id, workspace_id, name, prefix, budget_usd_monthly, rpm_limit, created_at, revoked_at) exactly like the provider DTO that was introduced in the provider hardening wave. The same applies to the Go field names (ID, WorkspaceID, …) versus the contract's snake_case.
- `GET /v1/usage` does not match `UsageSummary`. The contract declares
totals / by_key / by_model / by_day; the implementation answers the flat store map (count, prompt_tokens, completion_tokens, cost_usd). Either the implementation grows the grouped shape or the contract is simplified — the current mismatch is a client bug waiting to happen. → Resolved in the Wave 5 follow-up (§9.1): the implementation answers the contract's shape.
- `PATCH /v1/budgets/{id}` is a stub. It answers
{"status":"ok"}and
writes nothing, while the contract declares a Budget body. It is now authorized (the budget is resolved and the owning organization checked), but the write itself is still missing. The contract should either be implemented or the operation marked as not implemented. → Resolved in the Wave 5 follow-up (§9.1): the patch really writes the limit.
- `/v1/healthz` and `/v1/version` were missing in the core. The
contract declares them (below the /v1 base URL) and the edge lists them as public paths, but the core only served /v1/health, so a request the edge forwarded as public came back as a 404. The core now serves both (internal/api/health.go): healthz answers the contract's HealthResponse (status, version, uptime_seconds) and version the contract's VersionResponse (version, commit, build_time). commit and build_time are read from GATEWAY_COMMIT / GATEWAY_BUILD_TIME and are empty when the deployment does not stamp them; the spec should say whether they are optional.
- **
GET /v1/budgetsis scoped bykey_idin the implementation and by
workspace_id in the contract. Both are now accepted; the contract should list both. → The contract still has to list key_id (§9.6).**
- `GET /v1/plugins` has no scope. The plugin registry is deployment
scope; the spec should say so, otherwise a multi-tenant client has to guess whether the list is per organization.
- The CSRF rule is not in the contract. The core verifies the
X-CSRF-Token header for every mutating request that is authorized by the session cookie (§9.2), but the contract does not mention the header. The contract has to name it, otherwise a client that follows the spec breaks on every write. → See §9.6.1.
8. How to re-check this
- The rules live in
internal/api/tenant.go; the per-endpoint decisions are
in the handler files, each with a comment naming the required role.
internal/api/tenant_test.gois the executable form of §3 and §5.- The middleware gate (
aetherin-middleware/src/auth-gate.ts) is the second
line of defence; it must stay in place, but the core no longer depends on it.
9. Wave 5 follow-up: the contract, the two dormant guards
The previous pass fixed *who may reach what*. This pass fixes *what the answers look like* and turns the two guards that existed but did nothing (CSRF, SSRF) into real checks.
9.1 The usage and budget surface now match the contract
GET /v1/usage answered a flat {count, prompt_tokens, completion_tokens, cost_usd} — the shape of the store row, not the contract's UsageSummary. Worse: the query filtered on api_key_id = '' when the request named no key, so it matched nothing and the dashboard showed zeros.
| Endpoint | Before | Now |
|---|---|---|
GET /v1/usage | flat store map, no filters, empty without key_id | the contract's UsageSummary: totals + by_key / by_model / by_day; every documented filter is honoured |
GET /v1/usage/events | key_id only, Go field names | workspace_id, key_id, model, from, to, limit, cursor; the contract's UsageEvent shape (api_key_id, model_id, prompt_tokens, …) |
GET /v1/usage/export.csv | scoped by workspace, key_id widened to the whole workspace, no model | the same scope rules as the JSON endpoints (key_id, workspace_id, model, from, to) |
GET /v1/budgets | empty without key_id, Go field names, no pagination | the documented scope (workspace_id, key_id as an extension) and the contract's BudgetListResponse (Budget in snake_case, next_cursor, has_more) |
PATCH /v1/budgets/{id} | a no-op that answered {"status":"ok"} | really updates the limit (and the rate limit of the key); the spend and the period end are preserved; a body without a field is 400 |
The rules behind the shapes:
- The scope is never optional. The store query carries the keys (or the
workspaces) the caller may read; a query without a scope matches *nothing* (AND FALSE), so a caller that may read no key reads no usage.
- An empty period is not an error. It answers zero totals and empty
breakdowns — never invented data.
- `group_by` selects the breakdown.
group_by=keyreports the per-key
rows, group_by=model the per-model rows, group_by=day the per-day rows; without it every breakdown is reported. The other breakdowns are always present (as an empty array), so the shape never depends on the parameter. An unknown value is 400.
- The period.
from/toaccept RFC3339 andYYYY-MM-DDand are half
open ([from, to)). A missing from means "the whole ledger" for the JSON endpoints and "the current month" for the CSV export (the default the contract documents for the export). A missing to means "until now".
The tenant rules of §2/§3 are unchanged: the scope is resolved by usageScope in internal/api/usage.go, which uses the same requireKeyAccess / requireWorkspaceAccess helpers as every other surface, so a key or workspace of another organization is still 403.
9.2 CSRF is verified
The core generated a CSRF token per session (auth.NewCSRF), stored it with the session and returned it in the login and refresh responses — and never compared it with anything. middleware.CSRFValid existed and was never called.
The rule (implemented in `internal/api/csrf.go`):
A request that is authorized by the session cookie and **changes
state** (
POST,PUT,PATCH,DELETE) must carry the header`X-CSRF-Token` whose value equals the CSRF token of the session the
request authenticated with. A missing or mismatching header is
403withthe contract error envelope (
code: forbidden,type: permission_error).
- The check sits in
requireUser(and in the logout and refresh handlers),
so it covers every session-authorized endpoint at once and cannot be forgotten by a new handler.
- API-key (bearer) requests are exempt. A client key is never attached
by a browser on its own, so such a request cannot be forged cross-site. The exemption requires a *valid* key: an invalid or revoked key does not exempt the request.
- Reads are never affected: a
GETneeds the cookie only. - The CORS middleware already allows
X-CSRF-Tokenin
Access-Control-Allow-Headers.
- The client needs one change: it has to send the header. The token is in
the csrf_token field of the login and refresh responses.
The logout is protected as well: a forged logout does not end the session of the operator.
9.3 The SSRF guard is enforced
internal/providers/factory.go computed isAllowedURL(...) and threw the result away (_ = ...), so a provider could point at http://169.254.169.254/ and the core would happily talk to the instance metadata service.
The rule:
- A provider base URL must be an absolute
http(s)URL whose host does not
name an address inside the private address space.
- Blocked space: loopback (
127.0.0.0/8,::1,localhostand its
subdomains), the private ranges (10/8, 172.16/12, 192.168/16, fc00::/7), link-local (169.254/16, fe80::/10), the unspecified addresses (0.0.0.0, ::), the multicast addresses, the cloud metadata endpoints (169.254.169.254, 169.254.170.2, 100.100.100.200, fd00:ec2::254) and the IPv6-mapped forms of all of them (::ffff:127.0.0.1 …). IsPrivateOrLoopback was extended accordingly.
- Exemptions: a *local* provider type (
ollama,local,lmstudio,
llamacpp) may point at a loopback address — that is what a local model server is — and a deployment that explicitly allows local providers (development mode, or ALLOW_LOCAL_PROVIDERS=true in production) may point anywhere. The loopback exemption of a local provider does not extend to the metadata endpoint.
- Where it is enforced:
POST /v1/providersandPATCH /v1/providers/{id}answer400with a
clear message when the base URL is refused;
- the adapter factory fails closed: a refused URL yields an adapter
that answers every call with providers.ErrBlockedBaseURL and never issues a request (the health check reports the provider as down).
9.4 The status codes of the contract
| Endpoint | Before | Now (the contract) |
|---|---|---|
POST /v1/auth/logout | 200 {"status":"ok"} | 204 |
DELETE /v1/keys/{id} | 200 {"status":"ok"} | 204 |
DELETE /v1/orgs/{id} | 200 {"status":"ok"} | 204 |
DELETE /v1/plugins/{id} | 200 {"status":"ok"} | 204 |
DELETE /v1/providers/{id} | 204 | unchanged |
DELETE /v1/orgs/{id}/members/{memberId} | 204 | unchanged |
DELETE /v1/admin/users/{id} | 204 | unchanged |
DELETE /v1/models/{id}/routes/{routeID} | 200 {"status":"deleted"} | unchanged (the contract documents a body here) |
9.5 The workspace endpoints
The contract documents GET, PATCH and DELETE on /v1/orgs/{id}/workspaces/{workspaceId}; the core only had the list and the creation. They exist now, with the rules of the other workspace operations:
| Endpoint | Role | Notes |
|---|---|---|
GET /v1/orgs/{id}/workspaces/{workspaceId} | member | a workspace of another organization does not exist under this path (404) |
PATCH /v1/orgs/{id}/workspaces/{workspaceId} | admin | renames; a body without a name is 400 |
DELETE /v1/orgs/{id}/workspaces/{workspaceId} | owner | the last workspace of an organization is never removed (409 conflict) |
The list and the creation now answer the contract's Workspace shape (id, org_id, name, created_at) as well.
9.6 The contract changes this pass needs (not made here)
The contract lives in aetherin-common and was not edited. These are the changes this work implies:
- The CSRF header has to be in the contract. Add a parameter to every
mutating operation (or a global security scheme) that names the header X-CSRF-Token and states the rule: *required for cookie-authenticated mutating requests, the value must equal the csrf_token of the session; not required for bearer-authenticated requests*. The login and refresh responses already carry csrf_token; the contract should document that field as part of the session lifecycle.
- `group_by` needs a sentence. The contract lists the parameter but not
what it does. The implementation reads it as "the dimension of the breakdown the summary reports" (key, model or day); the other breakdowns are empty arrays. The contract should say so, or say that group_by is only a hint and all breakdowns are always reported.
- `GET /v1/usage/events` should document `from` and `to`. The
implementation honours the period (and model) although the contract only lists workspace_id, key_id, limit and cursor.
- `GET /v1/budgets` should list `key_id` next to
workspace_id(the
contract change §7.6 of the first pass already asked for).
- `PATCH /v1/budgets/{id}` should document `rpm_limit` — the contract
lists it in BudgetUpdate, and the implementation now writes it to the key.
- `DELETE /v1/orgs/{id}/workspaces/{workspaceId}` should list `409` next
to 400 and 204: removing the last workspace of an organization is a conflict.
- The usage and budget bodies should be marked as the wire format. The
implementation answers UsageSummary, UsageEvent and Budget in snake_case now; the store structs (Go field names) are an internal detail.
9.7 Tests of the follow-up
| File | What it proves |
|---|---|
internal/api/usage_test.go | the summary with and without filters (key, workspace, model, period), the empty period, group_by, the event list, the CSV export scope, the budget list shape, the budget update and the empty scope |
internal/api/csrf_test.go | the missing, the mismatching and the valid token; the bearer exemption (and that an invalid key does not exempt); the reads; the logout and the refresh |
internal/api/ssrf_test.go | the provider endpoints refuse the private addresses, accept the local provider and accept a private address in development mode |
internal/api/workspace_test.go | the three workspace endpoints, their roles and the refusal to remove the last workspace |
internal/api/status_test.go | the 204 of the delete surface and the 200 of the model-route delete |
internal/middleware/security_test.go | the block list of IsPrivateOrLoopback and the rules of SSRFAllowed |
internal/providers/ssrf_test.go | the factory fails closed and the local provider is served |
tests/integration/usage_test.go | the same against a real Postgres: the SQL of the report, the budget update and the CSRF rule |
gofmt -l . # clean
go build ./... # ok
go vet ./... # ok
go test ./... # ok
go test -race ./internal/api/... # ok
go test -tags=integration ./tests/integration/... # ok (Docker available)10. Wave 5 follow-up: the wire format and the honest answers
The previous pass fixed *who may reach what*; the pass before that fixed *what the answers look like* for the usage and budget surface. This pass closes the remaining wire-format gaps and removes the last no-ops.
10.1 The store structs are not the wire format
The store structs carry no JSON tags, so every response that serialized one directly answered the Go field names (ID, Name, OwnerID, KeyHash, …) instead of the field names the contract defines (id, name, owner_id, …). A client that reads org.id got undefined, and every org-scoped call then failed with "org not found": the org switcher and the team screens were broken by the shape, not by the data.
Every response that carries a store struct now goes through a DTO in internal/api/dto.go. A DTO is an allow-list: a column that has no field in the DTO cannot leak into a response.
| DTO | Contract body | Used by |
|---|---|---|
orgJSON | Org | GET /v1/orgs, POST /v1/orgs, GET /v1/orgs/{id}, PATCH /v1/orgs/{id}, GET /v1/auth/me |
apiKeyJSON | ApiKey | GET /v1/keys, GET /v1/keys/{id}, PATCH /v1/keys/{id} |
apiKeyCreatedJSON | ApiKeyCreated | POST /v1/keys, POST /v1/keys/{id}/rotate |
modelJSON | Model | GET /v1/models, GET /v1/models/{id}, POST /v1/models |
modelRouteJSON | ModelRoute | GET /v1/models/{id}/routes, POST /v1/models/{id}/routes |
pluginJSON | Plugin | GET /v1/plugins, POST /v1/plugins/install |
pluginConfigJSON | PluginConfigResponse | GET/PATCH /v1/plugins/{id}/config |
The DTOs live in the API layer on purpose: the store keeps the internal model, the API owns the bytes that leave the process.
Two consequences worth naming:
- The key hash never leaves the store.
GET /v1/keysanswered the raw
store.APIKey, which carries KeyHash — the SHA-256 of a live client key. The list now answers id, workspace_id, name, prefix, budget_usd_monthly, rpm_limit, created_at, revoked_at; the plaintext is answered once, by the create and the rotate.
- The model price is nested. The contract's
Modelcarries
pricing: {prompt_per_1m, completion_per_1m}; the store carries PriceIn / PriceOut. The DTO maps one to the other.
10.2 The key list is paginated
GET /v1/keys ignored limit and cursor and answered a bare {"data": [...]}. It now honours both and answers the contract's ApiKeyListResponse (data, next_cursor, has_more).
- The workspace-scoped list (
?workspace_id=) is a keyset query in the
store (ListAPIKeysPage), newest first by (created_at, id).
- The unscoped list (every workspace the caller may read) is assembled
from several workspaces and is therefore ordered and paged in the API layer with the same paginate helper the provider list uses.
10.3 A CSRF failure has its own code
A rejected CSRF proof answered 403 with the code forbidden — the same code a missing permission answers. A client could therefore not tell "my session is stale" from "you are not allowed", and ended up masking a permission error as a session problem.
The code is `csrf_invalid` (HTTP 403, type invalid_request_error), and it is used for CSRF rejections only. forbidden (HTTP 403, type permission_error) stays the code of every authorization failure. The code is already in the contract's ErrorCode enum and in openapi/ERROR_CODES.md.
10.4 The no-ops are gone
Three operations answered a success status and changed nothing. They are real operations now:
| Endpoint | Before | Now |
|---|---|---|
DELETE /v1/orgs/{id} | 204, nothing deleted | really deletes the organization and everything that belongs to it (workspaces, keys, providers, models, memberships, invitations, billing rows — ON DELETE CASCADE); owner-only; 404 for an unknown id |
PATCH /v1/orgs/{id} | 200 with the new name in the body, nothing written | writes the name (and the slug) to the row; a body without a field is 400 |
DELETE /v1/plugins/{id} | 204, nothing deleted | really removes the registry row; deployment-owner-only; 404 for an unknown id |
PATCH /v1/plugins/{id}/config | 200 {"status":"ok"}, nothing written | writes the configuration to the registry row and answers the configuration that was written |
GET /v1/plugins/{id}/config | 200 {"config":{}} | answers the configuration of the registry row |
POST /v1/plugins/install | 201 {"status":"installed"} | answers the contract's Plugin body |
The key surface had the same kind of gap: POST /v1/keys and PATCH /v1/keys/{id} did not write the name or the rate limit to the key row (the patch only changed the response). Both write now, and the patch also writes the budget to the key row and to the budget row the ledger enforces — without resetting what the key has already spent this period.
10.5 The session endpoint always carries the token
GET /v1/auth/me answers the CSRF token of the session the request authenticated with — always, and never the token of a previous session. A client that lost its token (a new tab, cleared storage) recovers without rotating the session.
10.6 The contract changes this pass needs (not made here)
The contract lives in aetherin-common and was not edited. The contract already contains the csrf_invalid code and the "always present" wording for MeResponse.csrf_token. These are the changes this work implies:
- `DELETE /v1/orgs/{id}` should list `404` next to
400and204: an
unknown organization is a 404, not a 204.
- `DELETE /v1/plugins/{id}` should list `404` next to
400and204,
for the same reason.
- `GET`/`PATCH /v1/plugins/{id}/config` should list `404` (an unknown
plugin) and `PATCH` should list `403` (the deployment-owner rule).
- **
GET /v1/pluginsandPOST /v1/plugins/installshould document the
config_json field** — the core answers config_json (the contract's Plugin body), not config.
- **
Plugin.ringis a number in the core and a string enum
(core | standard | custom) in the contract.** The registry stores the ring as an integer. Either the contract should say integer, or the core needs a mapping — the plugin id (ring1.<name>) is the only place the ring is readable today.
- `PluginInstall` should carry the `id` of the plugin. The registry is
keyed by it (ring1.<name>), and the uninstall and the config endpoints address the plugin by that id. The contract's PluginInstall has only name, version and config, so a contract-conforming request is refused with 400 id is required.
- `GET /v1/models` should list the `provider` parameter under that name.
The core reads provider (the contract's name) and still accepts provider_id as an alias.
- `GET /v1/orgs` should keep `Limit` and `Cursor` — it now honours both
and answers next_cursor / has_more like the other lists.
- **
POST /v1/keysandPATCH /v1/keys/{id}have new refusals that the
contract should describe:** a 400 for a body without a field and a 400 for a negative rpm_limit or budget_usd_monthly. (No 409: a key is not unique by name.)
- The error `type` of `csrf_invalid` is
invalid_request_error(the
request is missing a proof). The contract documents the type per code in ERROR_CODES.md; the table should say so.
- The client surface still answers the legacy error codes. `POST
/v1/chat/completions and the budget errors answer code: "Too Many Requests", "Payment Required", … (the http.StatusText of the status) instead of the contract's rate_limit_exceeded, budget_exceeded`, … The machine surface was left alone in this pass on purpose (it has its own OpenAI-compatible error semantics); it is the next thing to align.
10.7 Tests of this pass
| File | What it proves |
|---|---|
internal/api/wire_test.go | the organization, key, model, model-route, plugin and workspace bodies carry the contract's field names and no Go field name; the key responses never carry the hash; the create answers the plaintext exactly once and stores the name and the rate limit; the patch reaches the store; the key list is paginated; the organization delete removes the organization and its workspaces; the plugin delete removes the plugin and the plugin config is written; the session endpoint always carries the token of the session |
internal/api/csrf_test.go | a rejected CSRF proof answers csrf_invalid, a missing permission still answers forbidden |
internal/api/status_test.go | the 204 of the delete surface (the plugin is installed first: the uninstall removes a real row) |
internal/api/tenant_test.go | the tenant checks read the snake_case ids |
tests/integration/wire_test.go | the same against a real Postgres: the org shape, the key pagination, the plaintext once, the csrf_invalid code, and the organization delete with its cascade |