package web import ( "bytes" "encoding/json" "net/http" "net/url" "regexp" "strconv" "strings" "testing" "time" "supermarket/internal/users" ) // mcpTools lists the tools a key is offered, or returns the status. func mcpTools(h http.Handler, key string) (int, []string) { raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}) rec := do(h, http.MethodPost, "/mcp", bytes.NewReader(raw), map[string]string{ "Content-Type": "application/json", "Accept": "application/json, text/event-stream", "Authorization": "Bearer " + key}) if rec.Code != http.StatusOK { return rec.Code, nil } var out struct { Result struct { Tools []struct{ Name string } `json:"tools"` } `json:"result"` } json.Unmarshal(rec.Body.Bytes(), &out) var names []string for _, t := range out.Result.Tools { names = append(names, t.Name) } return rec.Code, names } var keyRe = regexp.MustCompile(`
(sm_[A-Za-z0-9]+)`) func TestLocalHermesAgent(t *testing.T) { s, h := newTestServer(t, nil) // mcp-token is the built-in Hermes' key: CRM, and reading the Market. code, tools := mcpTools(h, testToken) got := strings.Join(tools, " ") if code != http.StatusOK || !strings.Contains(got, "crm_pending_actions") || !strings.Contains(got, "inventory_list") { t.Fatalf("hermes: %d %v", code, tools) } body := do(h, http.MethodGet, "/settings/agents", nil, nil).Body.String() if !strings.Contains(body, ">Hermes built in") || !strings.Contains(body, "CRM through the Core (read and act)") { t.Errorf("agents page: %s", body) } // Starting again doesn't make a second Hermes. if err := s.EnsureHermes(testToken); err != nil { t.Fatal(err) } if n, _ := users.Count(s.DB); n != 1 { t.Errorf("%d users", n) } // Rotating Hermes' key writes it to mcp-token. var id int64 s.DB.GetJSON(hermesKey, &id) rec := postForm(h, "/settings/agents/"+strconv.FormatInt(id, 10)+"/rotate", url.Values{}) m := keyRe.FindStringSubmatch(rec.Body.String()) if m == nil || s.MCPToken != m[1] || rec.Header().Get("Cache-Control") != "no-store" { t.Fatalf("rotate: %s", rec.Body.String()) } // Both work for a day. for _, k := range []string{testToken, m[1]} { if code, _ := mcpTools(h, k); code != http.StatusOK { t.Errorf("after rotating, %s…: %d", k[:6], code) } } // Hermes can't be removed, only turned off. if rec := postForm(h, "/settings/agents/"+strconv.FormatInt(id, 10)+"/remove", url.Values{}); rec.Code != http.StatusUnprocessableEntity { t.Errorf("remove hermes: %d", rec.Code) } } func TestAgents(t *testing.T) { s, h := newServerEdition(t) owner := addUser(t, s, "owner@example.com", users.Owner, nil) oc := sessionFor(t, s, owner) member := addUser(t, s, "sam@example.com", users.Member, map[string]users.Access{"seo": users.Edit}) if rec := as(h, sessionFor(t, s, member), http.MethodGet, "/settings/agents", nil); rec.Code != http.StatusForbidden { t.Errorf("member: %d", rec.Code) } // No built-in Hermes on a server, and no key works yet. if code, _ := mcpTools(h, testToken); code != http.StatusUnauthorized { t.Errorf("mcp-token on a server: %d", code) } if rec := as(h, oc, http.MethodPost, "/settings/agents", url.Values{"name": {"Writer"}}); rec.Code != http.StatusUnprocessableEntity { t.Errorf("no scopes: %d", rec.Code) } if rec := as(h, oc, http.MethodPost, "/settings/agents", url.Values{"name": {"Writer"}, "scope:seo": {"read"}, "expires": {"2020-01-01"}}); rec.Code != http.StatusUnprocessableEntity { t.Errorf("expiry passed: %d", rec.Code) } rec := as(h, oc, http.MethodPost, "/settings/agents", url.Values{"name": {"Writer"}, "description": {"Drafts"}, "scope:content": {"act"}, "scope:seo": {"read"}, "scope:market": {"read"}, "expires": {time.Now().AddDate(0, 1, 0).Format("2006-01-02")}}) m := keyRe.FindStringSubmatch(rec.Body.String()) if rec.Code != http.StatusOK || m == nil { t.Fatalf("create: %d %s", rec.Code, rec.Body.String()) } key := m[1] if !strings.Contains(rec.Body.String(), "https://") && !strings.Contains(rec.Body.String(), "/mcp") { t.Error("no address to use it at") } code, tools := mcpTools(h, key) got := strings.Join(tools, " ") if code != http.StatusOK || !strings.Contains(got, "inventory_list") || strings.Contains(got, "crm_") { t.Errorf("writer's tools: %d %v", code, tools) } agent, _ := users.ByEmail(s.DB, mustAgentEmail(t, s, "Writer")) page := as(h, oc, http.MethodGet, "/settings/agents/"+strconv.FormatInt(agent.ID, 10), nil).Body.String() if !strings.Contains(page, key[:10]+"…") || strings.Contains(page, key) || !strings.Contains(page, "from 192.0.2.1") { t.Errorf("agent page: %s", page) } // Agents aren't people: not on Users, no sign-in. if body := as(h, oc, http.MethodGet, "/settings/users", nil).Body.String(); strings.Contains(body, "Writer") { t.Error("an agent on the Users page") } // Revoking stops the key at once. keys, _ := users.Keys(s.DB, agent.ID) as(h, oc, http.MethodPost, "/settings/agents/"+strconv.FormatInt(agent.ID, 10)+"/revoke", url.Values{"key": {strconv.FormatInt(keys[0].ID, 10)}}) if code, _ := mcpTools(h, key); code != http.StatusUnauthorized { t.Errorf("revoked: %d", code) } // A new key, then the agent turned off: no key works. rec = as(h, oc, http.MethodPost, "/settings/agents/"+strconv.FormatInt(agent.ID, 10)+"/new-key", url.Values{}) key2 := keyRe.FindStringSubmatch(rec.Body.String())[1] if code, _ := mcpTools(h, key2); code != http.StatusOK { t.Errorf("new key: %d", code) } as(h, oc, http.MethodPost, "/settings/agents/"+strconv.FormatInt(agent.ID, 10)+"/disable", url.Values{}) if code, _ := mcpTools(h, key2); code != http.StatusUnauthorized { t.Errorf("turned off: %d", code) } // Changing its scopes changes its tools. as(h, oc, http.MethodPost, "/settings/agents/"+strconv.FormatInt(agent.ID, 10)+"/enable", url.Values{}) as(h, oc, http.MethodPost, "/settings/agents/"+strconv.FormatInt(agent.ID, 10)+"/save", url.Values{"name": {"Writer"}, "scope:seo": {"read"}}) if _, tools := mcpTools(h, key2); strings.Contains(strings.Join(tools, " "), "inventory_list") { t.Errorf("market taken away, still offered: %v", tools) } // The log. body := as(h, oc, http.MethodGet, "/settings/activity", nil).Body.String() for _, want := range []string{"made the agent", "revoked a key of", "changed what this agent may do:"} { if !strings.Contains(body, want) { t.Errorf("activity lacks %q", want) } } // Many wrong keys from one address: refused for a while. for i := 0; i < users.MaxFailsPerIP; i++ { mcpTools(h, "sm_wrong") } if code, _ := mcpTools(h, key2); code != http.StatusUnauthorized { t.Errorf("after many wrong keys: %d", code) } } func mustAgentEmail(t *testing.T, s *Server, name string) string { t.Helper() list, _ := users.Members(s.DB, users.Team) for _, m := range list { if m.Kind == users.Agent && m.Name == name { return m.Email } } t.Fatalf("no agent %s", name) return "" }