Files
superbrain/internal/handlers/apikeys.go
T
Andrew S Erwin 5684757d24 Rename Go module to gitea.federated.computer/Federated_Computer/brain
The module path claimed a nonexistent GitHub repo. Point it (and the
agent User-Agent contact URL, README/RUNNING clone URLs) at the real
Gitea repository. Pure identifier rename: no runtime behavior change.

Verified: build, vet, unit + full DB integration (-race), db-converge,
web lint/SSR/build, browser regressions, e2e against rebuilt stack.
2026-11-22 02:46:40 -06:00

146 lines
4.5 KiB
Go

package handlers
// Personal API keys (Settings → API Keys): long-lived "sb_..." Bearer
// credentials for machine clients — the superbrain-mcp server the federated
// mcpserver gateway spawns, or any REST client talking to the Go API
// directly. The web proxy signs browser assertions and never forwards a
// client-supplied Authorization header, so keys are a direct-API surface by
// design (see internal/auth/apikeys.go for the auth channel).
//
// Secrets are write-once like every other credential in the product: the
// plaintext is returned exactly once by POST and never again; list
// responses carry only the display prefix. Revocation is deletion.
// Issuance is gated on the tenant's mcp-core connector (entitlements
// catalog: core plan) and use is gated again in the auth middleware, so a
// downgrade stops existing keys (the notify creation+delivery discipline).
import (
"database/sql"
"net/http"
"strings"
"unicode/utf8"
"gitea.federated.computer/Federated_Computer/brain/internal/auth"
"gitea.federated.computer/Federated_Computer/brain/internal/db"
)
// maxAPIKeys caps live keys per user — a product limit against credential
// sprawl, not a storage limit. Gateways need one; a handful of scripts is
// the realistic ceiling.
const maxAPIKeys = 10
// mcpCoreAllowed resolves the caller's tenant limits and reports whether
// the mcp-core connector is included (mirrors userTenantAllows, which is
// channel-shaped).
func mcpCoreAllowed(r *http.Request) (bool, error) {
var tenantID *string
if e := database(r).QueryRowContext(r.Context(),
`SELECT "tenantId" FROM "User" WHERE id=$1`, user(r)).Scan(&tenantID); e != nil {
return false, e
}
tid := ""
if tenantID != nil {
tid = *tenantID
}
lim, e := db.NewTenantRepo(database(r)).Limits(r.Context(), tid)
if e != nil {
return false, e
}
return lim.AllowConnector("mcp-core"), nil
}
// apiKeyProjection is the only shape key data ever leaves the server in.
// The hash is internal; the plaintext exists solely in the POST response.
func apiKeyProjection(row object) object {
return object{
"id": row["id"], "name": row["name"], "prefix": row["prefix"],
"createdAt": row["createdAt"], "lastUsedAt": row["lastUsedAt"],
}
}
// HandleAPIKeysList returns the caller's keys (masked) plus whether their
// plan allows issuing new ones, so the UI can gate without guessing
// entitlements client-side.
func HandleAPIKeysList(w http.ResponseWriter, r *http.Request) {
rows, e := db.Many(r.Context(), database(r),
`SELECT to_jsonb(t) FROM "ApiKey" t WHERE "ownerId"=$1 ORDER BY "createdAt" DESC`, user(r))
if e != nil {
respond(w, 0, nil, e)
return
}
allowed, e := mcpCoreAllowed(r)
if e != nil {
respond(w, 0, nil, e)
return
}
keys := make([]object, 0, len(rows))
for _, row := range rows {
keys = append(keys, apiKeyProjection(row))
}
respond(w, 200, object{"keys": keys, "allowed": allowed}, nil)
}
// HandleAPIKeysCreate mints a key. The plaintext is returned once, here.
func HandleAPIKeysCreate(w http.ResponseWriter, r *http.Request) {
allowed, e := mcpCoreAllowed(r)
if e != nil {
respond(w, 0, nil, e)
return
}
if !allowed {
planGate(w)
return
}
b, ok := read(w, r)
if !ok {
return
}
name := strings.TrimSpace(str(b, "name"))
if name == "" || utf8.RuneCountInString(name) > 100 {
respond(w, 0, nil, bad("name is required (max 100 characters)"))
return
}
plain, hash, prefix, e := auth.GenerateAPIKey()
if e != nil {
respond(w, 0, nil, e)
return
}
var row object
e = db.Transaction(r.Context(), database(r), func(tx *sql.Tx) error {
// Count under the user lock so two racing creates cannot both slip
// under the cap (the house discipline for version-bump paths).
if e := lockUser(r, tx); e != nil {
return e
}
var n int
if e := tx.QueryRowContext(r.Context(),
`SELECT count(*) FROM "ApiKey" WHERE "ownerId"=$1`, user(r)).Scan(&n); e != nil {
return e
}
if n >= maxAPIKeys {
return bad("API key limit reached; revoke an existing key first")
}
row, e = db.Insert(r.Context(), tx, "ApiKey", object{
"id": db.NewID(), "ownerId": user(r), "name": name,
"prefix": prefix, "keyHash": hash,
})
return e
})
if e != nil {
respond(w, 0, nil, e)
return
}
out := apiKeyProjection(row)
out["key"] = plain
respond(w, 201, out, nil)
}
// HandleAPIKeysDelete revokes (deletes) one of the caller's keys.
func HandleAPIKeysDelete(w http.ResponseWriter, r *http.Request) {
if e := remove(r, "ApiKey", r.PathValue("id"), "ownerId"); e != nil {
respond(w, 0, nil, e)
return
}
respond(w, 200, object{"ok": true}, nil)
}