Phase 13, part 9: running at scale, and the proof

The multi-tenant edition starts. compose.multi.yaml runs several copies
behind Caddy, with the managed Postgres and Garage outside. A test walks
every page and fragment, with ids filled in, and every MCP tool, as one
team, and none shows another team's data or changes it; another has three
copies share six teams' work, each team's turn once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 12:46:01 -07:00
co-authored by Claude Opus 5.5
parent b8a64e258a
commit f4c31c9fa3
13 changed files with 453 additions and 14 deletions
+3 -9
View File
@@ -324,15 +324,9 @@ func NewKey() (string, error) {
return hex.EncodeToString(b), nil
}
// Ready says whether this version of Supermarket can run the edition. The
// server and multi-tenant editions are planned (PLAN.md, Phases 9–14) and
// come in steps; until they're built, only the settings are checked.
func (c *Config) Ready() error {
if c.Edition != Multi {
return nil
}
return fmt.Errorf("This version of Supermarket runs the local and server editions: the %s edition isn't built yet. Its settings are fine", c.Edition.Name())
}
// Ready says whether this version of Supermarket can run the edition:
// every edition, since Phase 13.
func (c *Config) Ready() error { return nil }
// Item is one line of the settings, to show.
type Item struct {
+1 -1
View File
@@ -121,7 +121,7 @@ func TestMulti(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if err := c.Ready(); err == nil || !strings.Contains(err.Error(), "isn't built yet") {
if err := c.Ready(); err != nil {
t.Fatal(err)
}
s := c.Storage
+2
View File
@@ -112,6 +112,7 @@ type routes struct {
s *Server
mux *http.ServeMux
unmapped []string
patterns []string // every route, for the tests that walk them all
}
// HandleFunc registers a handler: a method expression such as
@@ -147,6 +148,7 @@ func (rt *routes) Handle(pattern string, h http.Handler) {
rt.unmapped = append(rt.unmapped, pattern)
return
}
rt.patterns = append(rt.patterns, pattern)
rt.mux.Handle(pattern, rt.s.allow(area, rt.s.guardDomain(pattern, rt.s.audited(pattern, h))))
}
+13
View File
@@ -12,6 +12,7 @@ import (
"supermarket/internal/appmail"
"supermarket/internal/audit"
"supermarket/internal/content"
"supermarket/internal/storage"
"supermarket/internal/transfer"
"supermarket/internal/users"
@@ -297,3 +298,15 @@ func (s *Server) purgeTeam(ctx context.Context, id int64) error {
}
func teamFilesPrefix(id int64) string { return "teams/" + strconv.FormatInt(id, 10) }
// RecoverTeams marks each team's drafts left "publishing" by a stopped app
// as failed, for review (the multi-tenant edition's start).
func (s *Server) RecoverTeams(ctx context.Context) {
s.eachTeam(ctx, func(_ context.Context, ts *Server) {
if n, err := content.RecoverInterrupted(ts.DB); err != nil {
ts.Log.Error("recovering drafts", "team", ts.team(), "err", err)
} else if n > 0 {
ts.Log.Warn("drafts were being published when Supermarket stopped; marked failed for review", "team", ts.team(), "count", n)
}
})
}
+186
View File
@@ -0,0 +1,186 @@
package web
import (
"context"
"net/http"
"net/url"
"regexp"
"sort"
"strings"
"testing"
"time"
"supermarket/internal/content"
"supermarket/internal/inventory"
"supermarket/internal/profile"
"supermarket/internal/prospects"
"supermarket/internal/signals"
"supermarket/internal/users"
)
// marker is in everything team B has: it must never reach team A.
const marker = "ZEBRAMARK"
// seedTeam fills a team with data carrying a marker, in many tables.
func seedTeam(t *testing.T, ts *Server, mark string) {
t.Helper()
d := ts.DB
must := func(err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
must(profile.Save(d, &profile.Profile{Name: mark + " Inc", Description: mark + " widgets", Keywords: []string{mark}}))
for i := 0; i < 3; i++ {
must(inventory.Save(d, &inventory.Entry{Name: mark + " rival " + string(rune('a'+i)), Relationship: "competitor", Description: mark}))
}
sig := &signals.Signal{Name: mark + " signal", Hypothesis: mark}
must(signals.Save(d, sig))
_, _, err := prospects.AddCompany(d, prospects.Company{Name: mark + " Corp", Domain: strings.ToLower(mark) + ".example", Source: "manual"}, time.Now())
must(err)
_, _, err = prospects.AddContact(d, prospects.Contact{FirstName: mark, LastName: "Lee", Email: "kim@" + strings.ToLower(mark) + ".example", Source: "manual"}, time.Now())
must(err)
_, err = content.CreateDrafts(d, []content.Draft{{Channel: content.ChannelX, Content: mark + " post"}, {Channel: content.ChannelLinkedIn, Content: mark + " update"}})
must(err)
must(prospects.Suppress(d, "domain", strings.ToLower(mark)+"-blocked.example", mark, time.Now()))
must(d.PutJSON("seo:indexnow-key", mark))
must(ts.Secrets.Set(map[string]string{"hunter.api_key": mark}))
}
// sampleValues fill a route's wildcards: ids and names that exist in the
// other team's schema.
var wildcard = regexp.MustCompile(`\{([a-z]+)(\.\.\.)?\}`)
func fillPattern(pattern, v string) string {
return wildcard.ReplaceAllStringFunc(pattern, func(w string) string {
switch {
case strings.Contains(w, "provider"):
return "x"
case strings.Contains(w, "kind"):
return "company"
case strings.Contains(w, "month"):
return "2026-11"
case strings.Contains(w, "token"):
return "nothing"
}
return v
})
}
// TestTeamsIsolatedEverywhere is Phase 13's proof: team A, signed in as its
// owner and through its agent with every scope, reaches every page,
// fragment and tool, and never sees team B's data, nor changes it.
func TestTeamsIsolatedEverywhere(t *testing.T) {
s, h := newMultiEdition(t)
a, _, ac := newTeam(t, s, "Acme", "olu@acme.example")
b, _, bc := newTeam(t, s, "Bolt", "bea@bolt.example")
ta, _ := s.forTeam(a.ID)
tb, _ := s.forTeam(b.ID)
seedTeam(t, ta, "OWNMARK")
seedTeam(t, tb, marker)
// Both prove their domains, so nothing is held back by that.
users.Prove(s.platform(), a.ID, "dns", time.Now())
users.Prove(s.platform(), b.ID, "dns", time.Now())
leaks := func(where, body string) {
t.Helper()
if strings.Contains(body, marker) || strings.Contains(strings.ToLower(body), strings.ToLower(marker)) {
i := strings.Index(strings.ToLower(body), strings.ToLower(marker))
t.Errorf("%s shows team B's data: …%s…", where, body[max(0, i-80):min(len(body), i+80)])
}
}
// The check can see a leak: B's own owner sees the marker.
for _, p := range []string{"/market", "/signals", "/posts", "/prospects", "/settings/profile", "/search?q=" + marker[:5]} {
if body := as(h, bc, http.MethodGet, p, nil).Body.String(); !strings.Contains(body, marker) {
t.Errorf("control: B's own %s lacks the marker", p)
}
}
// Every page and fragment (GET), with its ids filled in.
patterns := append([]string(nil), s.st().patterns...)
sort.Strings(patterns)
n := 0
for _, p := range patterns {
method, path, _ := strings.Cut(p, " ")
if method != http.MethodGet || strings.HasPrefix(path, "/static") || path == "/mcp" {
continue
}
for _, v := range []string{"1", "2", "3"} {
u := strings.TrimSuffix(fillPattern(path, v), "{$}")
for _, q := range []string{"", "?site=0", "?q=" + url.QueryEscape(marker[:5])} {
rec := as(h, ac, http.MethodGet, u+q, nil)
leaks("GET "+u+q, rec.Body.String())
n++
}
}
}
if n < 300 {
t.Errorf("only %d requests", n)
}
// Every MCP tool, as A's agent with every scope.
all := map[string]users.Access{}
for _, g := range agentGrants() {
all[g.ID] = users.Edit
}
_, key := newAgentIn(t, ta, "A's agent", all)
_, tools := mcpTools(h, key)
if len(tools) < 30 {
t.Fatalf("only %d tools", len(tools))
}
for _, tool := range tools {
for _, args := range []map[string]any{{}, {"id": 1, "site": 0, "status": "waiting", "entry": marker + " rival a", "tab": "drafts"},
{"id": 2, "draft_id": 1, "message_id": 1, "contact_id": 1, "change_id": 1}} {
text, _ := mcpCall(t, h, key, tool, args)
leaks("tool "+tool, text)
}
}
// Changes by A, aimed at B's ids, change nothing of B's.
for _, p := range []string{"/market/1/delete", "/market/2/delete", "/signals/1/delete", "/drafts/1/discard", "/drafts/2/discard",
"/prospects/company/1/reject", "/prospects/contact/1/delete"} {
as(h, ac, http.MethodPost, p, url.Values{})
}
if list, _ := inventory.List(tb.DB, ""); len(list) != 3 {
t.Errorf("B's Market: %d", len(list))
}
if list, _ := signals.List(tb.DB); len(list) != 1 {
t.Errorf("B's signals: %d", len(list))
}
if list, _ := content.ListDrafts(tb.DB, 10, content.StatusDraft); len(list) != 2 {
t.Errorf("B's drafts: %d", len(list))
}
if cs, ps, _ := prospects.Review(tb.DB, prospects.StatusNew, 0, 10); len(cs) != 1 || len(ps) != 1 {
t.Errorf("B's prospects: %d %d", len(cs), len(ps))
}
if tb.Secrets.Get("hunter.api_key") != marker {
t.Error("B's key changed")
}
// And the background jobs: one round of each, for both teams, leaves
// B's data B's (and A's job never ran on B's schema: B's drafts are
// where they were).
sent := &fakePosts{}
s.testPublisher = nil
_ = sent
for _, name := range []string{"scheduler", "accounts"} {
s.jobDo(t.Context(), name, func(ctx context.Context, ts *Server) {
if name == "scheduler" {
ts.publishDue(ctx, time.Now())
}
})
}
if list, _ := inventory.List(ta.DB, ""); strings.Contains(entryNames(list), marker) {
t.Error("B's entries in A's schema")
}
}
func entryNames(list []inventory.Entry) string {
var b strings.Builder
for _, e := range list {
b.WriteString(e.Name + " ")
}
return b.String()
}
+2
View File
@@ -94,6 +94,7 @@ type state struct {
runner *jobs.Runner
setupDone atomic.Bool // the team has its owner (server edition)
rotation atomic.Uint64 // which team's turn comes first (eachTeam)
patterns []string // every route's pattern
mu sync.Mutex
copies map[int64]*Server // each team's Server
@@ -574,6 +575,7 @@ func (s *Server) Handler() (http.Handler, error) {
if err := mux.err(); err != nil {
return nil, err
}
s.st().patterns = mux.patterns
return s.guard(s.csrf(s.sessions(mux.mux))), nil
}
+66
View File
@@ -11,6 +11,7 @@ import (
"regexp"
"strconv"
"strings"
"sync"
"testing"
"time"
@@ -551,3 +552,68 @@ func sessionIn(t *testing.T, s *Server, u *users.User, team int64) *http.Cookie
}
return &http.Cookie{Name: sessionCookie, Value: tok}
}
// Three copies of the app, behind a load balancer, share the teams' work:
// each team's turn runs once, and the copies each take some.
func TestThreeCopiesShareTheWork(t *testing.T) {
s, h := newMultiEdition(t)
var ids []int64
for i := 0; i < 6; i++ {
tm, _, _ := newTeam(t, s, "Team"+strconv.Itoa(i), "o"+strconv.Itoa(i)+"@x.example")
ids = append(ids, tm.ID)
}
copies := []*Server{s}
for i := 0; i < 2; i++ {
teams, err := s.platform().Teams()
if err != nil {
t.Fatal(err)
}
t.Cleanup(teams.Close)
c := &Server{DB: s.platform(), Platform: s.platform(), Teams: teams, Secrets: s.Secrets, Config: s.Config, DataDir: t.TempDir(),
PublicURL: s.PublicURL, Version: "test", Log: s.Log}
if _, err := c.Handler(); err != nil {
t.Fatal(err)
}
copies = append(copies, c)
}
var mu sync.Mutex
runs := map[int64]int{} // team → turns
byCopy := map[int]int{} // copy → turns it ran
var wg sync.WaitGroup
for i, c := range copies {
wg.Add(1)
go func() {
defer wg.Done()
c.jobDo(context.Background(), "scheduler", func(ctx context.Context, ts *Server) {
time.Sleep(150 * time.Millisecond) // a turn takes a while
mu.Lock()
runs[ts.team()]++
byCopy[i]++
mu.Unlock()
})
}()
}
wg.Wait()
for _, id := range ids {
if runs[id] != 1 {
t.Errorf("team %d ran %d times", id, runs[id])
}
}
shared := 0
for _, n := range byCopy {
if n > 0 {
shared++
}
}
if shared < 2 {
t.Errorf("one copy did it all: %v", byCopy)
}
// Any copy answers any request: a team's owner, signed in, on another
// copy.
_, _, c0 := newTeamOwnerCookie(t, s, ids[0])
h2, _ := copies[2].Handler()
if rec := as(h2, c0, http.MethodGet, "/settings/profile", nil); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Team0") {
t.Errorf("on another copy: %d", rec.Code)
}
_ = h
}