API keys & MCP (the mcpserver-link prerequisite from STRATEGY.md): - ApiKey table (migration 017 + schema.sql): hash-only storage of personal "sb_..." Bearer credentials, unique keyHash, owner cascade. - internal/auth/apikeys.go + AuthMiddleware fork: keys resolve before the assertion/cookie channels; gated on the mcp-core connector at issuance AND at every use (downgrade 403s); independent of tokenVersion so "sign out everywhere" never breaks a gateway link; view-as stays browser-only. - /api/keys GET/POST/DELETE: plaintext shown exactly once, 10-key cap under the user lock, owner-scoped revocation; Settings -> API Keys tab. - mcp/: superbrain-mcp, a pip-installable stdio MCP server (listmonk-mcp pattern) with bookmarks/tags/pages tools, version-safe updates; the federated gateway spawns it via config_mcpserver_superbrain() in deploy/federated/lib-superbrain.sh (mints the gateway key in-db, points it at http://superbrain-app:8080). STRATEGY.md records the remaining suite-side registry work. - Tests: TestAPIKeys (plan gate, cap, revocation, tokenVersion semantics, downgrade-at-use); full DB-backed suite, db-converge, live MCP-client smoke all pass. Markdown (Gitea issue #3): add @tailwindcss/typography and enable it in tailwind.config.ts. The prose wrapper was a no-op without it, so Tailwind Preflight flattened headings/blockquotes to body text while bold/italic survived - exactly the reported symptom. Verified in the built CSS. Gitea: #2 and #3 closed with reference notes; #1 stays open pending the Superpanel core-AI walkthrough.
146 lines
5.1 KiB
Go
146 lines
5.1 KiB
Go
package auth
|
|
|
|
// Personal API keys: long-lived Bearer credentials ("sb_...") for machine
|
|
// clients — the superbrain-mcp server the federated mcpserver gateway
|
|
// spawns, or any REST client. They exist because the browser channels are
|
|
// deliberately short-lived (60-second assertions, 30-day cookies) and a
|
|
// gateway needs a stable credential.
|
|
//
|
|
// Storage is hash-only (SHA-256 of the full key; the plaintext is shown
|
|
// exactly once at creation). Revocation is deletion of the row — there is
|
|
// no soft state to drift. Keys are independent of User.tokenVersion:
|
|
// "sign out everywhere" targets browser sessions, and silently killing a
|
|
// gateway link on a password change would be operationally hostile;
|
|
// machine credentials must be revoked explicitly (Settings → API Keys).
|
|
//
|
|
// Issuance AND use are gated on the tenant's mcp-core connector
|
|
// (entitlements catalog), mirroring the notify discipline of gating at
|
|
// creation AND at delivery: a plan downgrade stops existing keys with 403
|
|
// rather than leaving them quietly working.
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"database/sql"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/andrew/superbrain/internal/db"
|
|
)
|
|
|
|
const (
|
|
// APIKeyPrefix is the human-recognizable token prefix (house style for
|
|
// grep-able secrets; also lets the middleware route the Bearer channel
|
|
// without touching the JWT parser).
|
|
APIKeyPrefix = "sb_"
|
|
// apiKeyEntropyBytes is the random payload; base64url renders it as 43
|
|
// characters, so a full key is exactly 46.
|
|
apiKeyEntropyBytes = 32
|
|
// APIKeyDisplayPrefix is how much of a key the list projection shows
|
|
// ("sb_" + 8 chars) — enough to recognize, not enough to narrow a guess.
|
|
APIKeyDisplayPrefix = 11
|
|
)
|
|
|
|
// ErrAPIKeyPlan is returned when a valid key belongs to a tenant whose plan
|
|
// no longer includes the mcp-core connector. Distinct from ErrUnauthorized
|
|
// so the middleware can answer 403 (a plan fact) instead of 401 (a
|
|
// credential fact).
|
|
var ErrAPIKeyPlan = errors.New("auth: api keys not available on this plan")
|
|
|
|
// GenerateAPIKey returns a fresh plaintext key, its stored SHA-256 hash and
|
|
// the display prefix. The plaintext never touches the database.
|
|
func GenerateAPIKey() (plain, hash, displayPrefix string, err error) {
|
|
b := make([]byte, apiKeyEntropyBytes)
|
|
if _, err = rand.Read(b); err != nil {
|
|
return "", "", "", err
|
|
}
|
|
plain = APIKeyPrefix + base64.RawURLEncoding.EncodeToString(b)
|
|
return plain, HashAPIKey(plain), plain[:APIKeyDisplayPrefix], nil
|
|
}
|
|
|
|
// HashAPIKey is the one-way transform used for storage and lookup. SHA-256
|
|
// (not bcrypt) is deliberate: the key is 256 bits of random entropy, so
|
|
// there is nothing to brute-force offline, and lookup must be a single
|
|
// indexed equality probe on every request.
|
|
func HashAPIKey(plain string) string {
|
|
sum := sha256.Sum256([]byte(plain))
|
|
return hex.EncodeToString(sum[:])
|
|
}
|
|
|
|
// IsAPIKeyToken reports whether a Bearer token has the exact shape of an
|
|
// API key (prefix + 43 base64url chars). Shape-checked before any database
|
|
// work so junk tokens never become queries.
|
|
func IsAPIKeyToken(tok string) bool {
|
|
if !strings.HasPrefix(tok, APIKeyPrefix) || len(tok) != 46 {
|
|
return false
|
|
}
|
|
rest := tok[len(APIKeyPrefix):]
|
|
for i := 0; i < len(rest); i++ {
|
|
c := rest[i]
|
|
if (c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') && c != '-' && c != '_' {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// APIKeyFromRequest extracts an API-key Bearer token, if present. Only the
|
|
// exact "Bearer sb_..." shape counts; anything else falls through to the
|
|
// assertion/cookie channels.
|
|
func APIKeyFromRequest(r *http.Request) (string, bool) {
|
|
h := r.Header.Get("Authorization")
|
|
if !strings.HasPrefix(h, "Bearer ") {
|
|
return "", false
|
|
}
|
|
tok := strings.TrimPrefix(h, "Bearer ")
|
|
if !IsAPIKeyToken(tok) {
|
|
return "", false
|
|
}
|
|
return tok, true
|
|
}
|
|
|
|
// ResolveAPIKey authenticates a plaintext key and returns the owner's
|
|
// session skeleton (ID + APIKeyID; Ver stays 0 so the tokenVersion check in
|
|
// AuthMiddleware is skipped by design — see the file comment). The plan
|
|
// gate runs here, on every use. lastUsedAt is touched at most once a
|
|
// minute per key so a chatty MCP client cannot turn every request into a
|
|
// write.
|
|
func ResolveAPIKey(ctx context.Context, d *db.DB, plain string) (*SessionUser, error) {
|
|
var (
|
|
keyID, ownerID string
|
|
tenantID *string
|
|
)
|
|
err := d.QueryRowContext(ctx,
|
|
`SELECT k.id, k."ownerId", u."tenantId" FROM "ApiKey" k JOIN "User" u ON u.id=k."ownerId" WHERE k."keyHash"=$1`,
|
|
HashAPIKey(plain)).Scan(&keyID, &ownerID, &tenantID)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil, ErrUnauthorized
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
tid := ""
|
|
if tenantID != nil {
|
|
tid = *tenantID
|
|
}
|
|
lim, err := db.NewTenantRepo(d).Limits(ctx, tid)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !lim.AllowConnector("mcp-core") {
|
|
return nil, ErrAPIKeyPlan
|
|
}
|
|
_, err = d.ExecContext(ctx,
|
|
`UPDATE "ApiKey" SET "lastUsedAt"=now() WHERE id=$1 AND ("lastUsedAt" IS NULL OR "lastUsedAt" < $2)`,
|
|
keyID, time.Now().Add(-time.Minute))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &SessionUser{ID: ownerID, APIKeyID: keyID}, nil
|
|
}
|