The Gitea repository was renamed brain -> superbrain (server-side redirect already in place; local origin updated at 0.3.5). Carry the rename through for accurate identity, the 0.3.2 precedent: go.mod + every internal import, the agent's outbound User-Agent contact URL, README/RUNNING clone URLs and local notes. CHANGELOG history entries stay as written. Pure identifier rename, no runtime behavior change; verified with build + vet + unit tests and the full database integration suite under -race.
343 lines
11 KiB
Go
343 lines
11 KiB
Go
package handlers
|
|
|
|
// MCP connections (Settings → MCP): user-registered outbound MCP servers,
|
|
// Notion-style. Superbrain dials them as a client (internal/mcpclient) so
|
|
// the assistant can later use their tools; this file is the management
|
|
// surface — CRUD with the house credential and concurrency disciplines:
|
|
//
|
|
// - secrets encrypted at rest (internal/crypto, same versioned format as
|
|
// IMAP passwords and channel secrets), masked in EVERY response,
|
|
// write-only: a PATCH echoing the mask (or omitting the field) keeps the
|
|
// stored value;
|
|
// - mutating PATCH carries the row version (409 on stale);
|
|
// - test/dial draws from the shared outbound budget and a per-user
|
|
// limiter, and every dial is netguard-pinned (no private ranges, ports
|
|
// 80/443 outside tests) — a user-supplied URL gets no exemption;
|
|
// - per-user cap on live connections, enforced under the user lock.
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"net/http"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
|
|
"gitea.federated.computer/Federated_Computer/superbrain/internal/auth"
|
|
crypt "gitea.federated.computer/Federated_Computer/superbrain/internal/crypto"
|
|
"gitea.federated.computer/Federated_Computer/superbrain/internal/config"
|
|
"gitea.federated.computer/Federated_Computer/superbrain/internal/db"
|
|
"gitea.federated.computer/Federated_Computer/superbrain/internal/mcpclient"
|
|
"gitea.federated.computer/Federated_Computer/superbrain/internal/outbound"
|
|
)
|
|
|
|
const (
|
|
mcpSecretMask = "••••••••"
|
|
maxMcpConns = 10
|
|
maxMcpSecretLen = 2000
|
|
maxMcpNameLen = 100
|
|
maxMcpHeaderLen = 100
|
|
mcpTestTimeout = 25 * time.Second
|
|
mcpTestListTools = 200
|
|
)
|
|
|
|
// headerNamePattern keeps custom header names to RFC 7230 tokens so a
|
|
// stored name can never smuggle CRLF into a dialed request.
|
|
var headerNamePattern = regexp.MustCompile(`^[!#$%&'*+\-.^_|~A-Za-z0-9]+$`)
|
|
|
|
func mcpProjection(row object) object {
|
|
secret := ""
|
|
if s, _ := row["secret"].(string); s != "" {
|
|
secret = mcpSecretMask
|
|
}
|
|
return object{
|
|
"id": row["id"], "name": row["name"], "url": row["url"],
|
|
"transport": row["transport"], "authKind": row["authKind"],
|
|
"headerName": row["headerName"], "secret": secret,
|
|
"enabled": row["enabled"], "version": row["version"],
|
|
"createdAt": row["createdAt"], "updatedAt": row["updatedAt"],
|
|
}
|
|
}
|
|
|
|
// HandleMcpConnectionsList returns the caller's connections, masked.
|
|
func HandleMcpConnectionsList(w http.ResponseWriter, r *http.Request) {
|
|
rows, e := db.Many(r.Context(), database(r),
|
|
`SELECT to_jsonb(t) FROM "McpConnection" t WHERE "ownerId"=$1 ORDER BY "createdAt"`, user(r))
|
|
if e != nil {
|
|
respond(w, 0, nil, e)
|
|
return
|
|
}
|
|
out := make([]object, 0, len(rows))
|
|
for _, row := range rows {
|
|
out = append(out, mcpProjection(row))
|
|
}
|
|
respond(w, 200, object{"connections": out}, nil)
|
|
}
|
|
|
|
func cleanMcpFields(b object, create bool) (object, error) {
|
|
out := object{}
|
|
name := strings.TrimSpace(str(b, "name"))
|
|
if create || b["name"] != nil {
|
|
if name == "" || len([]rune(name)) > maxMcpNameLen {
|
|
return nil, bad("name is required (max 100 characters)")
|
|
}
|
|
out["name"] = name
|
|
}
|
|
if _, present := b["url"]; present || create {
|
|
url := strings.TrimSpace(str(b, "url"))
|
|
if !validURL(url) || len(url) > 2048 {
|
|
return nil, bad("url must be an absolute http(s) URL")
|
|
}
|
|
out["url"] = url
|
|
}
|
|
if _, present := b["transport"]; present || create {
|
|
transport := str(b, "transport")
|
|
if transport != "streamable-http" && transport != "sse" {
|
|
return nil, bad("transport must be streamable-http or sse")
|
|
}
|
|
out["transport"] = transport
|
|
}
|
|
if _, present := b["authKind"]; present || create {
|
|
kind := str(b, "authKind")
|
|
if kind != "none" && kind != "bearer" && kind != "header" {
|
|
return nil, bad("authKind must be none, bearer or header")
|
|
}
|
|
out["authKind"] = kind
|
|
}
|
|
if _, present := b["headerName"]; present || create {
|
|
header := strings.TrimSpace(str(b, "headerName"))
|
|
if header != "" && (len(header) > maxMcpHeaderLen || !headerNamePattern.MatchString(header)) {
|
|
return nil, bad("headerName must be a valid HTTP header name")
|
|
}
|
|
out["headerName"] = header
|
|
}
|
|
if v, present := b["enabled"]; present {
|
|
ev, ok := v.(bool)
|
|
if !ok {
|
|
return nil, bad("enabled must be boolean")
|
|
}
|
|
out["enabled"] = ev
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// mcpSecretFor resolves the submitted secret against the stored one:
|
|
// missing or the mask keeps the stored value; anything else is a new
|
|
// plaintext secret to encrypt. Returns "" when unchanged.
|
|
func mcpSecretFor(b object, storedEnc string, authKind string, create bool) (newEnc string, keep bool, e error) {
|
|
submitted, present := b["secret"]
|
|
if !present {
|
|
if create && authKind != "none" {
|
|
return "", false, bad("secret is required for bearer and header auth")
|
|
}
|
|
return "", true, nil
|
|
}
|
|
s, _ := submitted.(string)
|
|
if s == "" || s == mcpSecretMask {
|
|
if create && authKind != "none" {
|
|
return "", false, bad("secret is required for bearer and header auth")
|
|
}
|
|
return "", true, nil
|
|
}
|
|
if len(s) > maxMcpSecretLen {
|
|
return "", false, bad("secret is too long")
|
|
}
|
|
enc, e := crypt.Encrypt(s, config.Load().EncryptionSecret())
|
|
if e != nil {
|
|
return "", false, e
|
|
}
|
|
return enc, false, nil
|
|
}
|
|
|
|
// HandleMcpConnectionsCreate registers a new connection.
|
|
func HandleMcpConnectionsCreate(w http.ResponseWriter, r *http.Request) {
|
|
b, ok := read(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
fields, e := cleanMcpFields(b, true)
|
|
if e != nil {
|
|
respond(w, 0, nil, e)
|
|
return
|
|
}
|
|
authKind, _ := fields["authKind"].(string)
|
|
if authKind == "header" && fields["headerName"] == "" {
|
|
respond(w, 0, nil, bad("headerName is required for header auth"))
|
|
return
|
|
}
|
|
enc, _, e := mcpSecretFor(b, "", authKind, true)
|
|
if e != nil {
|
|
respond(w, 0, nil, e)
|
|
return
|
|
}
|
|
var row object
|
|
e = db.Transaction(r.Context(), database(r), func(tx *sql.Tx) error {
|
|
if e := lockUser(r, tx); e != nil {
|
|
return e
|
|
}
|
|
var n int
|
|
if e := tx.QueryRowContext(r.Context(),
|
|
`SELECT count(*) FROM "McpConnection" WHERE "ownerId"=$1`, user(r)).Scan(&n); e != nil {
|
|
return e
|
|
}
|
|
if n >= maxMcpConns {
|
|
return bad("MCP connection limit reached; remove one first")
|
|
}
|
|
data := object{
|
|
"id": db.NewID(), "ownerId": user(r),
|
|
"name": fields["name"], "url": fields["url"],
|
|
"transport": fields["transport"], "authKind": authKind,
|
|
"headerName": fields["headerName"], "secret": enc,
|
|
"enabled": true,
|
|
}
|
|
if v, present := fields["enabled"]; present {
|
|
data["enabled"] = v
|
|
}
|
|
row, e = db.Insert(r.Context(), tx, "McpConnection", data)
|
|
return e
|
|
})
|
|
if e != nil {
|
|
respond(w, 0, nil, e)
|
|
return
|
|
}
|
|
respond(w, 201, mcpProjection(row), nil)
|
|
}
|
|
|
|
// HandleMcpConnectionsUpdate patches one connection under the version
|
|
// contract; the secret is write-only (mask or omission keeps it).
|
|
func HandleMcpConnectionsUpdate(w http.ResponseWriter, r *http.Request) {
|
|
id := r.PathValue("id")
|
|
existing, e := owned(r, database(r), "McpConnection", id, "ownerId")
|
|
if e != nil {
|
|
respond(w, 0, nil, e)
|
|
return
|
|
}
|
|
b, ok := read(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
baseVersion, e := requiredVersion(b)
|
|
if e != nil {
|
|
respond(w, 0, nil, e)
|
|
return
|
|
}
|
|
if stored, _ := existing["version"].(float64); int(stored) != baseVersion {
|
|
respond(w, 0, nil, conflict("Connection was modified elsewhere; reload to see the latest version"))
|
|
return
|
|
}
|
|
fields, e := cleanMcpFields(b, false)
|
|
if e != nil {
|
|
respond(w, 0, nil, e)
|
|
return
|
|
}
|
|
// Effective authKind/headerName after this patch, for cross-field rules.
|
|
authKind, _ := existing["authKind"].(string)
|
|
if v, present := fields["authKind"]; present {
|
|
authKind, _ = v.(string)
|
|
}
|
|
headerName, _ := existing["headerName"].(string)
|
|
if v, present := fields["headerName"]; present {
|
|
headerName, _ = v.(string)
|
|
}
|
|
if authKind == "header" && strings.TrimSpace(headerName) == "" {
|
|
respond(w, 0, nil, bad("headerName is required for header auth"))
|
|
return
|
|
}
|
|
storedEnc, _ := existing["secret"].(string)
|
|
enc, keep, e := mcpSecretFor(b, storedEnc, authKind, false)
|
|
if e != nil {
|
|
respond(w, 0, nil, e)
|
|
return
|
|
}
|
|
// Switching an unauthenticated row to bearer/header without supplying a
|
|
// secret (mask or omission) would store a credential-less connection.
|
|
if keep && authKind != "none" && storedEnc == "" {
|
|
respond(w, 0, nil, bad("secret is required for bearer and header auth"))
|
|
return
|
|
}
|
|
if !keep {
|
|
fields["secret"] = enc
|
|
}
|
|
if authKind == "none" {
|
|
fields["secret"] = ""
|
|
}
|
|
if len(fields) == 0 {
|
|
// A mask-only (or empty) PATCH is a legitimate no-op under the
|
|
// write-only secret contract: answer with the current projection
|
|
// rather than an error, without bumping the version.
|
|
respond(w, 200, mcpProjection(existing), nil)
|
|
return
|
|
}
|
|
row, e := patchVersioned(r, "McpConnection", id, baseVersion, fields)
|
|
if e != nil {
|
|
respond(w, 0, nil, e)
|
|
return
|
|
}
|
|
respond(w, 200, mcpProjection(row), nil)
|
|
}
|
|
|
|
// HandleMcpConnectionsDelete removes one connection.
|
|
func HandleMcpConnectionsDelete(w http.ResponseWriter, r *http.Request) {
|
|
if e := remove(r, "McpConnection", r.PathValue("id"), "ownerId"); e != nil {
|
|
respond(w, 0, nil, e)
|
|
return
|
|
}
|
|
respond(w, 200, object{"ok": true}, nil)
|
|
}
|
|
|
|
// mcpTestLimiter bounds connection tests per USER: each test opens outbound
|
|
// sessions to a third party, so the account (not the IP) is the cost center.
|
|
var mcpTestLimiter = auth.NewLimiterStore()
|
|
|
|
// McpTestLimiter rate-limits MCP connection tests per authenticated user.
|
|
func McpTestLimiter(next http.HandlerFunc) http.HandlerFunc {
|
|
return auth.LimiterKeyed(mcpTestLimiter, 30, time.Hour, user)(next)
|
|
}
|
|
|
|
// HandleMcpConnectionsTest dials the connection (initialize + tools/list)
|
|
// and reports what the server offers. Failures are 502 with the server's
|
|
// error class, never a silent ok.
|
|
func HandleMcpConnectionsTest(w http.ResponseWriter, r *http.Request) {
|
|
row, e := owned(r, database(r), "McpConnection", r.PathValue("id"), "ownerId")
|
|
if e != nil {
|
|
respond(w, 0, nil, e)
|
|
return
|
|
}
|
|
secretEnc, _ := row["secret"].(string)
|
|
secret := ""
|
|
if secretEnc != "" {
|
|
dec, e := crypt.Decrypt(secretEnc, config.Load().EncryptionSecret())
|
|
if e != nil {
|
|
respond(w, 0, nil, e)
|
|
return
|
|
}
|
|
secret = dec
|
|
}
|
|
conn := mcpclient.Conn{
|
|
URL: str(row, "url"),
|
|
Transport: str(row, "transport"),
|
|
AuthKind: str(row, "authKind"),
|
|
HeaderName: str(row, "headerName"),
|
|
Secret: secret,
|
|
}
|
|
// Shared outbound budget (review M-2): a user cannot open unbounded
|
|
// third-party sessions.
|
|
release, retry, ok := outbound.Reserve("mcp-test:"+user(r), 10, time.Minute)
|
|
if !ok {
|
|
outboundBusy(w, retry)
|
|
return
|
|
}
|
|
defer release()
|
|
ctx, cancel := context.WithTimeout(r.Context(), mcpTestTimeout)
|
|
defer cancel()
|
|
tools, e := mcpclient.ListTools(ctx, conn)
|
|
if e != nil {
|
|
respond(w, 502, object{"ok": false, "error": "Could not reach the MCP server: " + truncate(e.Error(), 200)}, nil)
|
|
return
|
|
}
|
|
if len(tools) > mcpTestListTools {
|
|
tools = tools[:mcpTestListTools]
|
|
}
|
|
respond(w, 200, object{"ok": true, "tools": tools, "count": len(tools)}, nil)
|
|
}
|