Files
supermarket/internal/web/approvals_test.go
T
davidandClaude Opus 5.5 311d2e815b Phase 11, part 3: approvals for what agents send out
Agents can now ask to publish or schedule a post, send an email, add
someone to a mailing list, or apply an SEO change. Each waits on the
Approvals page (with a count in the sidebar) for an admin or a member with
edit on its module, who can edit it first, approve or refuse it, and let
the agent take that class of action on its own with a cap per day. A
rotation after a leak revokes the old keys and withdraws everything
allowed. All of it is in the audit log.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 10:54:53 -07:00

189 lines
8.3 KiB
Go

package web
import (
"encoding/json"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"testing"
"time"
"supermarket/internal/approvals"
"supermarket/internal/content"
"supermarket/internal/posting"
"supermarket/internal/profile"
"supermarket/internal/prospects"
"supermarket/internal/users"
)
var requestRe = regexp.MustCompile(`request (\d+)`)
func TestAgentDayThroughApprovals(t *testing.T) {
s, h := newServerEdition(t)
sent := &fakePosts{}
s.testPublisher = func(a *posting.Account) content.Publisher { return fakePub{sent, a} }
profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.", Websites: []profile.Website{{URL: "https://acme.example"}}})
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
oc := sessionFor(t, s, owner)
viewerOnly := addUser(t, s, "vi@example.com", users.Member, map[string]users.Access{"content": users.View})
seoOnly := addUser(t, s, "sam@example.com", users.Member, map[string]users.Access{"seo": users.Edit})
company := &posting.Account{Network: posting.X, Name: "@acme", External: "acme"}
posting.Save(s.DB, s.Secrets, company, "t", "", time.Now())
agent, key := newAgent(t, s, "Morning writer", map[string]users.Access{"content": users.Edit, "seo": users.View})
// A day's work: read the morning check and What to write next…
_, tools := mcpTools(h, key)
got := " " + strings.Join(tools, " ") + " "
for _, not := range []string{"seo_edit_change", "seo_apply_change"} {
if strings.Contains(got, " "+not+" ") {
t.Errorf("an SEO tool that changes things is offered: %s", not)
}
}
mcpCall(t, h, key, "seo_morning_check", map[string]any{})
mcpCall(t, h, key, "seo_next", map[string]any{})
// …write a draft, and schedule it.
text, _ := mcpCall(t, h, key, "content_create_draft", map[string]any{"channel": "x", "text": "Widgets, faster."})
var d draftView
json.Unmarshal([]byte(text), &d)
// It may not post to the company's account until it's on the grid.
at := time.Now().Add(3 * time.Hour).Format(dateTimeLocal)
if text, isErr := mcpCall(t, h, key, "content_publish", map[string]any{"draft_id": d.ID, "at": at}); !isErr || !strings.Contains(text, "may not post as X @acme") {
t.Errorf("not on the grid: %v %s", isErr, text)
}
posting.SetGrants(s.DB, map[int64][]int64{company.ID: {agent.ID}})
text, isErr := mcpCall(t, h, key, "content_publish", map[string]any{"draft_id": d.ID, "at": at})
if isErr || !strings.Contains(text, "Waiting for approval") {
t.Fatalf("publish: %s", text)
}
reqID, _ := strconv.ParseInt(requestRe.FindStringSubmatch(text)[1], 10, 64)
// Asking again doesn't make a second request.
if text, _ := mcpCall(t, h, key, "content_publish", map[string]any{"draft_id": d.ID, "at": at}); !strings.Contains(text, "Already waiting") {
t.Errorf("asked twice: %s", text)
}
if dr, _ := content.GetDraft(s.DB, d.ID); dr.Status != content.StatusDraft || len(sent.sent) != 0 {
t.Errorf("went out without approval: %+v", dr)
}
// Who sees it: the owner, not a Content viewer, not an SEO member.
if body := as(h, oc, http.MethodGet, "/", nil).Body.String(); !strings.Contains(body, `title="1 waiting for you"`) {
t.Error("no count in the sidebar")
}
page := as(h, oc, http.MethodGet, "/approvals", nil).Body.String()
if !strings.Contains(page, "Morning writer") || !strings.Contains(page, "Widgets, faster.") {
t.Errorf("approvals page: %s", page)
}
for _, u := range []*users.User{viewerOnly, seoOnly} {
c := sessionFor(t, s, u)
if body := as(h, c, http.MethodGet, "/approvals", nil).Body.String(); strings.Contains(body, "Widgets, faster.") {
t.Errorf("%s sees it", u.Email)
}
if rec := as(h, c, http.MethodPost, "/approvals/"+strconv.FormatInt(reqID, 10)+"/approve", url.Values{}); rec.Code != http.StatusForbidden {
t.Errorf("%s approves: %d", u.Email, rec.Code)
}
}
// The owner edits it, approves it, and lets it schedule to @acme on its
// own, once a day.
rec := as(h, oc, http.MethodPost, "/approvals/"+strconv.FormatInt(reqID, 10)+"/approve", url.Values{
"content": {"Widgets, much faster."}, "account": {strconv.FormatInt(company.ID, 10)}, "trust": {"on"}, "cap": {"1"}})
if rec.Code != http.StatusSeeOther {
t.Fatalf("approve: %d %s", rec.Code, rec.Body.String())
}
dr, _ := content.GetDraft(s.DB, d.ID)
if dr.Status != content.StatusScheduled || dr.Content != "Widgets, much faster." || dr.AccountID != company.ID || dr.PostedBy != owner.ID {
t.Errorf("scheduled: %+v", dr)
}
if text, _ := mcpCall(t, h, key, "approvals_status", map[string]any{"id": reqID}); !strings.Contains(text, `"Status": "done"`) {
t.Errorf("status: %s", text)
}
if rec := as(h, oc, http.MethodPost, "/approvals/"+strconv.FormatInt(reqID, 10)+"/approve", url.Values{}); rec.Code == http.StatusSeeOther {
t.Error("approved twice")
}
// Now on its own, once; the next waits again.
text, _ = mcpCall(t, h, key, "content_create_draft", map[string]any{"channel": "x", "text": "Second."})
json.Unmarshal([]byte(text), &d)
if text, _ := mcpCall(t, h, key, "content_publish", map[string]any{"draft_id": d.ID}); !strings.Contains(text, "Done (allowed on its own): published as X @acme") {
t.Errorf("on its own: %s", text)
}
if len(sent.sent) != 1 || sent.sent[0] != "X @acme: Second." {
t.Errorf("sent %v", sent.sent)
}
text, _ = mcpCall(t, h, key, "content_create_draft", map[string]any{"channel": "x", "text": "Third."})
json.Unmarshal([]byte(text), &d)
text, _ = mcpCall(t, h, key, "content_publish", map[string]any{"draft_id": d.ID})
if !strings.Contains(text, "Waiting for approval") {
t.Errorf("over the cap: %s", text)
}
third, _ := strconv.ParseInt(requestRe.FindStringSubmatch(text)[1], 10, 64)
// Refused: nothing goes, and the agent can read why.
as(h, oc, http.MethodPost, "/approvals/"+strconv.FormatInt(third, 10)+"/refuse", url.Values{})
if r, _ := approvals.Get(s.DB, third); r.Status != approvals.Refused || len(sent.sent) != 1 {
t.Errorf("refused: %+v", r)
}
// The agent's page lists what it may do on its own; the log has it all.
body := as(h, oc, http.MethodGet, "/settings/agents/"+strconv.FormatInt(agent.ID, 10), nil).Body.String()
if !strings.Contains(body, "publish posts to X @acme") || !strings.Contains(body, "up to 1 a day") {
t.Errorf("agent page: %s", body)
}
act := as(h, oc, http.MethodGet, "/settings/activity", nil).Body.String()
for _, want := range []string{"asked for approval to", "approved", "let an agent act on its own:", "did on its own:", "refused"} {
if !strings.Contains(act, want) {
t.Errorf("activity lacks %q", want)
}
}
// The key leaked: rotated with "it leaked", the old key stops at once and
// nothing is allowed on its own.
rec = as(h, oc, http.MethodPost, "/settings/agents/"+strconv.FormatInt(agent.ID, 10)+"/rotate", url.Values{"leaked": {"on"}})
newKey := keyRe.FindStringSubmatch(rec.Body.String())[1]
if code, _ := mcpTools(h, key); code != http.StatusUnauthorized {
t.Errorf("leaked key still works: %d", code)
}
if gs, _ := approvals.Grants(s.DB, agent.ID); len(gs) != 0 {
t.Errorf("grants kept: %+v", gs)
}
if code, _ := mcpTools(h, newKey); code != http.StatusOK {
t.Errorf("new key: %d", code)
}
// Revoking the key stops it at once.
keys, _ := users.Keys(s.DB, agent.ID)
for _, k := range keys {
users.Revoke(s.DB, agent.ID, k.ID, time.Now())
}
if code, _ := mcpTools(h, newKey); code != http.StatusUnauthorized {
t.Errorf("revoked: %d", code)
}
}
func TestApprovalThatFails(t *testing.T) {
s, h := newTestServer(t, nil)
_, key := newAgent(t, s, "Lister", map[string]users.Access{"prospects": users.Edit})
id, _, err := prospectsAdd(s)
if err != nil {
t.Fatal(err)
}
text, _ := mcpCall(t, h, key, "mailing_list_add", map[string]any{"contact_id": id, "list_id": "3"})
m := requestRe.FindStringSubmatch(text)
if m == nil {
t.Fatalf("add: %s", text)
}
// Listmonk isn't set up: approving says so, and the request is failed.
rec := postForm(h, "/approvals/"+m[1]+"/approve", url.Values{})
if !strings.Contains(rec.Body.String(), "set up Listmonk") {
t.Errorf("approve: %s", rec.Body.String())
}
rid, _ := strconv.ParseInt(m[1], 10, 64)
if r, _ := approvals.Get(s.DB, rid); r.Status != approvals.Failed {
t.Errorf("status %s", r.Status)
}
}
func prospectsAdd(s *Server) (int64, bool, error) {
return prospects.AddContact(s.DB, prospects.Contact{FirstName: "Kim", LastName: "Lee", Email: "kim@example.org", Source: "manual"}, time.Now())
}