brain_read returns a note verbatim; brain_edit is str_replace with an exactly-once match. Both operate on INGEST_BRAIN_DIR, which is the pod's mount of /var/lib/supervisor/brain — the tree brain-sync commits from, so an edit reaches gitea on the next cycle rather than landing somewhere the sync cannot see it (brain#2). An adversarial design review before implementation changed three things, each of which would otherwise have shipped: 1. Governance files are NOT in the model-facing tool. The original plan allowed root *.md so CLAUDE.md had an MCP path at all — the absence of one is what pushed a session to edit via the gitea REST API on 2026-06-16 and wedge the sync. But brain content is ingested from the outside world, reaches a model's context via brain_query, and that model would hold the editor: one poisoned page could rewrite the CLAUDE.md a .dispatch-allow agent later loads as instructions. Worse, brain-sync merges with --strategy-option=ours, so the live tree wins against a human's corrective push on exactly the conflicting lines. CLAUDE.md now goes through brain_edit_root: de-surfaced from tools/list (the brain_index precedent, ADR-0012 rule 4) and gated on the local static principal, so a claude.ai-origin session is refused. The two scopes are disjoint — the privileged door has the smaller reach. 2. Reads needed the same allowlist, and brain_get already lacked it. api.ReadNote resolves any brain-relative path and parseFrontmatter returns the whole file when there is no fence, so brain_get reads verbatim session transcripts under archive/ (up to 500 KB, never BM25-indexed, so nobody thinks of them as reachable). A test proves the exposure was live; the same Resolve now gates brain_get. 3. Canonicalise before allowlisting. A prefix check on the raw argument accepts knowledge/../.git/hooks/post-commit, which Clean collapses to a git hook that brain-sync executes inside a pod holding the Gitea push credentials. Traversal, symlink escape, dotfiles, .git/, archive/, sessions/ and raw/ are refused by a static backstop that does not depend on the allowlist being right. There were no traversal tests in this repo before. Also from the review: overlapping match counting (bytes.Count says "aa" occurs once in "aaa", so a Count-based uniqueness check accepts an ambiguous edit); UTF-8 validation on both sides, because encoding/json substitutes U+FFFD and would hand back bytes the file does not contain, making every derived old_str unmatchable; refusal while .git/MERGE_HEAD or index.lock exists, since an edit racing brain-sync's merge is either hard-reset away or committed as a wrongly resolved conflict; flock plus a per-path mutex with the read taken inside the lock, because two pods share the hostPath during a RollingUpdate and uniqueness evaluated against a stale read loses an update while reporting success; same-dir *.tmp + rename + chmod 0644 + fsync of file and parent; and reindex only when the edit touches frontmatter, since BM25 walks live and embeddings are mtime-driven. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BeAp5LTscnz2W7Ubt4eJ6m
150 lines
5.0 KiB
Go
150 lines
5.0 KiB
Go
package mcp_test
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/mathiasbq/hyperguild/ingestion/internal/capture"
|
|
"github.com/mathiasbq/hyperguild/ingestion/internal/mcp"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func body(t *testing.T, v any) *bytes.Buffer {
|
|
t.Helper()
|
|
b, err := json.Marshal(v)
|
|
require.NoError(t, err)
|
|
return bytes.NewBuffer(b)
|
|
}
|
|
|
|
func TestServerInitialize(t *testing.T) {
|
|
srv := mcp.NewServer(t.TempDir(), nil, nil, nil)
|
|
|
|
req := httptest.NewRequest(http.MethodPost, "/mcp", body(t, map[string]any{
|
|
"jsonrpc": "2.0", "id": 1, "method": "initialize",
|
|
"params": map[string]any{},
|
|
}))
|
|
rr := httptest.NewRecorder()
|
|
srv.ServeHTTP(rr, req)
|
|
|
|
assert.Equal(t, http.StatusOK, rr.Code)
|
|
var resp map[string]any
|
|
require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &resp))
|
|
result := resp["result"].(map[string]any)
|
|
assert.Equal(t, "2024-11-05", result["protocolVersion"])
|
|
}
|
|
|
|
func TestServerToolsList(t *testing.T) {
|
|
srv := mcp.NewServer(t.TempDir(), nil, nil, nil)
|
|
|
|
req := httptest.NewRequest(http.MethodPost, "/mcp", body(t, map[string]any{
|
|
"jsonrpc": "2.0", "id": 2, "method": "tools/list",
|
|
}))
|
|
rr := httptest.NewRecorder()
|
|
srv.ServeHTTP(rr, req)
|
|
|
|
assert.Equal(t, http.StatusOK, rr.Code)
|
|
var resp map[string]any
|
|
require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &resp))
|
|
tools := resp["result"].(map[string]any)["tools"].([]any)
|
|
names := make([]string, 0, len(tools))
|
|
for _, t := range tools {
|
|
names = append(names, t.(map[string]any)["name"].(string))
|
|
}
|
|
assert.ElementsMatch(t, []string{
|
|
"brain_query", "brain_write", "brain_update", "brain_get",
|
|
"brain_pending", "brain_promote",
|
|
"brain_read", "brain_edit",
|
|
"brain_tunnel",
|
|
"brain_ingest_raw", "brain_ingest",
|
|
"brain_answer", "brain_classify", "brain_graph", "brain_context",
|
|
"session_log",
|
|
}, names)
|
|
|
|
// brain_index is auto-called after every brain_write, so surfacing it as
|
|
// a caller verb is cognitive load with no decision behind it (ADR-0012
|
|
// rule 4, #78). The capability stays reachable — see the admin test below.
|
|
assert.NotContains(t, names, "brain_index")
|
|
|
|
// brain_edit_root is de-surfaced for a sharper reason than brain_index:
|
|
// brain content is ingested from the outside world and reaches a model's
|
|
// context, so a listed governance-file editor would be a durable
|
|
// prompt-injection path — one poisoned page rewriting the CLAUDE.md a
|
|
// .dispatch-allow agent later loads as instructions.
|
|
assert.NotContains(t, names, "brain_edit_root")
|
|
}
|
|
|
|
func TestBrainIndexStaysCallableForAdminUseAfterDeSurfacing(t *testing.T) {
|
|
// De-surfacing hides the verb from the model-facing list; it must not
|
|
// remove the operation. A maintenance caller still needs to rebuild a
|
|
// Map of Content by hand.
|
|
srv := mcp.NewServer(t.TempDir(), nil, nil, nil)
|
|
|
|
req := httptest.NewRequest(http.MethodPost, "/mcp", body(t, map[string]any{
|
|
"jsonrpc": "2.0", "id": 3, "method": "tools/call",
|
|
"params": map[string]any{"name": "brain_index", "arguments": map[string]any{}},
|
|
}))
|
|
rr := httptest.NewRecorder()
|
|
srv.ServeHTTP(rr, req)
|
|
|
|
require.Equal(t, http.StatusOK, rr.Code)
|
|
var resp map[string]any
|
|
require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &resp))
|
|
assert.NotContains(t, resp, "error", "brain_index must still dispatch: %v", resp["error"])
|
|
}
|
|
|
|
func TestServerNotificationGetsNoBody(t *testing.T) {
|
|
srv := mcp.NewServer(t.TempDir(), nil, nil, nil)
|
|
|
|
req := httptest.NewRequest(http.MethodPost, "/mcp", body(t, map[string]any{
|
|
"jsonrpc": "2.0", "method": "notifications/initialized",
|
|
}))
|
|
rr := httptest.NewRecorder()
|
|
srv.ServeHTTP(rr, req)
|
|
|
|
assert.Equal(t, http.StatusOK, rr.Code)
|
|
assert.Empty(t, strings.TrimSpace(rr.Body.String()))
|
|
}
|
|
|
|
func TestServerUnknownMethodReturnsError(t *testing.T) {
|
|
srv := mcp.NewServer(t.TempDir(), nil, nil, nil)
|
|
|
|
req := httptest.NewRequest(http.MethodPost, "/mcp", body(t, map[string]any{
|
|
"jsonrpc": "2.0", "id": 3, "method": "unknown/method",
|
|
}))
|
|
rr := httptest.NewRecorder()
|
|
srv.ServeHTTP(rr, req)
|
|
|
|
assert.Equal(t, http.StatusOK, rr.Code)
|
|
var resp map[string]any
|
|
require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &resp))
|
|
require.NotNil(t, resp["error"])
|
|
errObj := resp["error"].(map[string]any)
|
|
assert.Equal(t, float64(-32601), errObj["code"])
|
|
assert.Contains(t, errObj["message"].(string), "unknown/method")
|
|
}
|
|
|
|
type stubTracker struct{}
|
|
|
|
func (stubTracker) CreateIssue(context.Context, string, string, string) (capture.IssueRef, error) {
|
|
return capture.IssueRef{}, nil
|
|
}
|
|
func (stubTracker) CloseIssue(context.Context, string, int, string) (capture.IssueRef, error) {
|
|
return capture.IssueRef{}, nil
|
|
}
|
|
func (stubTracker) CommentIssue(context.Context, string, int, string) (capture.IssueRef, error) {
|
|
return capture.IssueRef{}, nil
|
|
}
|
|
|
|
func TestWithIssueTrackerInjects(t *testing.T) {
|
|
srv := mcp.NewServer(t.TempDir(), nil, nil, nil)
|
|
assert.Nil(t, srv.IssueTracker(), "tracker is off by default")
|
|
srv = srv.WithIssueTracker(stubTracker{})
|
|
assert.NotNil(t, srv.IssueTracker(), "tracker injected behind the interface")
|
|
}
|