Add personal API keys, superbrain-mcp, and fix Markdown prose styling

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.
This commit is contained in:
Andrew S Erwin
2026-11-02 14:27:58 -06:00
parent febc7b2195
commit e6ab778bd5
20 changed files with 1283 additions and 14 deletions
+168
View File
@@ -0,0 +1,168 @@
package http
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/cookiejar"
"strings"
"testing"
"github.com/andrew/superbrain/internal/db"
)
// machineReq calls the API with an API-key Bearer header and no cookies —
// the shape a gateway-spawned MCP server uses.
func machineReq(t *testing.T, base, method, path, apiKey string, body any) (int, map[string]any) {
t.Helper()
var b io.Reader
if body != nil {
raw, _ := json.Marshal(body)
b = bytes.NewReader(raw)
}
req, _ := http.NewRequest(method, base+path, b)
req.Header.Set("Content-Type", "application/json")
if apiKey != "" {
req.Header.Set("Authorization", "Bearer "+apiKey)
}
res, e := http.DefaultClient.Do(req)
if e != nil {
t.Fatal(e)
}
defer res.Body.Close()
raw, _ := io.ReadAll(res.Body)
var v map[string]any
json.Unmarshal(raw, &v)
return res.StatusCode, v
}
func TestAPIKeys(t *testing.T) {
srv, d := testServerDB(t)
newClient := func() apiClient { jar, _ := cookiejar.New(nil); return apiClient{t, &http.Client{Jar: jar}, srv.URL} }
alice, bob := newClient(), newClient()
post := func(email string) map[string]any {
return map[string]any{"email": email, "password": "a-long-test-password"}
}
alice.request("POST", "/api/signup", post("alice@superbrain.test"), 201)
alice.request("POST", "/api/auth/login", post("alice@superbrain.test"), 200)
bob.request("POST", "/api/signup", post("bob@superbrain.test"), 201)
bob.request("POST", "/api/auth/login", post("bob@superbrain.test"), 200)
au := meID(alice)
// Plan gate: the test deployment derives the selfhosted plan, whose
// connectors do NOT include mcp-core — issuance is refused and the list
// reports the feature as unavailable (the UI gates on this flag).
alice.request("POST", "/api/keys", map[string]any{"name": "mcpserver"}, 403)
v := alice.request("GET", "/api/keys", nil, 200)
if v["allowed"] != false {
t.Fatalf("expected allowed=false on a plan without mcp-core: %v", v)
}
// Upgrade the implicit tenant to the core plan (catalog data, not env).
if _, e := d.Exec(`UPDATE "Tenant" SET plan='core' WHERE id=$1`, db.DefaultTenantID); e != nil {
t.Fatal(e)
}
out := alice.request("POST", "/api/keys", map[string]any{"name": "mcpserver"}, 201)
key, _ := out["key"].(string)
if !strings.HasPrefix(key, "sb_") || len(key) != 46 {
t.Fatalf("unexpected key shape: %q", key)
}
if out["prefix"] != key[:11] {
t.Fatalf("prefix %v does not match key", out["prefix"])
}
if _, leaked := out["keyHash"]; leaked {
t.Fatal("keyHash leaked into the API response")
}
id, _ := out["id"].(string)
// Bad input.
alice.request("POST", "/api/keys", map[string]any{"name": ""}, 400)
alice.request("POST", "/api/keys", map[string]any{"name": strings.Repeat("x", 101)}, 400)
// The key authenticates machine requests: identity resolves to the
// owner and data endpoints work without any cookie.
code, body := machineReq(t, srv.URL, "GET", "/api/me", key, nil)
if code != 200 || body["user"].(map[string]any)["id"] != au {
t.Fatalf("api key did not resolve to its owner: %d %v", code, body)
}
code, _ = machineReq(t, srv.URL, "POST", "/api/bookmarks", key,
map[string]any{"url": "https://127.0.0.1/mcp", "title": "via key"})
if code != 201 {
t.Fatalf("bookmark create with api key: wanted 201, got %d", code)
}
// Unknown and malformed keys are 401 (a malformed token falls through
// to the assertion channel, which also rejects it).
code, _ = machineReq(t, srv.URL, "GET", "/api/me", "sb_"+strings.Repeat("A", 43), nil)
if code != 401 {
t.Fatalf("unknown api key: wanted 401, got %d", code)
}
code, _ = machineReq(t, srv.URL, "GET", "/api/me", "sb_short", nil)
if code != 401 {
t.Fatalf("malformed api key: wanted 401, got %d", code)
}
// List projection: masked, owner-scoped, lastUsedAt touched by the use
// above (throttled to once a minute, but this is the first use).
v = alice.request("GET", "/api/keys", nil, 200)
if v["allowed"] != true {
t.Fatalf("expected allowed=true on the core plan: %v", v)
}
keys := v["keys"].([]any)
first := keys[0].(map[string]any)
if first["name"] != "mcpserver" || first["lastUsedAt"] == nil {
t.Fatalf("unexpected list projection: %v", first)
}
if _, hasKey := first["key"]; hasKey {
t.Fatal("plaintext key echoed by the list endpoint")
}
// Owner-scoped revocation.
bob.request("DELETE", "/api/keys/"+id, nil, 404)
// Cap: 10 live keys per user (1 exists; create 9 more, then refuse).
for i := 0; i < maxTestKeys-1; i++ {
alice.request("POST", "/api/keys", map[string]any{"name": "script"}, 201)
}
alice.request("POST", "/api/keys", map[string]any{"name": "one-too-many"}, 400)
// Revocation is immediate: the row is deleted and the key stops working.
alice.request("DELETE", "/api/keys/"+id, nil, 200)
code, _ = machineReq(t, srv.URL, "GET", "/api/me", key, nil)
if code != 401 {
t.Fatalf("revoked api key: wanted 401, got %d", code)
}
// Deliberate semantics (apikeys.go): keys are independent of
// tokenVersion. A revocation bump kills the browser session (existing
// SEC-02 contract) but NOT the machine credential — gateways must not
// break because a user changed their password.
keys = alice.request("GET", "/api/keys", nil, 200)["keys"].([]any)
alice.request("DELETE", "/api/keys/"+keys[0].(map[string]any)["id"].(string), nil, 200)
out = alice.request("POST", "/api/keys", map[string]any{"name": "survivor"}, 201)
key2 := out["key"].(string)
if _, e := d.Exec(`UPDATE "User" SET "tokenVersion"="tokenVersion"+1 WHERE id=$1`, au); e != nil {
t.Fatal(e)
}
alice.request("GET", "/api/me", nil, 401) // cookie session revoked (SEC-02)
code, _ = machineReq(t, srv.URL, "GET", "/api/me", key2, nil)
if code != 200 {
t.Fatalf("api key must survive a tokenVersion bump: got %d", code)
}
// Downgrade fails closed at USE time too: the key is valid but the plan
// no longer includes mcp-core.
if _, e := d.Exec(`UPDATE "Tenant" SET plan='free' WHERE id=$1`, db.DefaultTenantID); e != nil {
t.Fatal(e)
}
code, _ = machineReq(t, srv.URL, "GET", "/api/me", key2, nil)
if code != 403 {
t.Fatalf("downgraded plan: wanted 403 for a valid key, got %d", code)
}
}
// maxTestKeys mirrors handlers.maxAPIKeys (kept local so the test states the
// product number explicitly).
const maxTestKeys = 10