Background jobs run for each active team on its own Server and under its own locks, a few teams at a time and from a different team each round, so the work is shared between copies of the app and no team holds up another. Each team's files are under its own prefix, and an OAuth sign-in comes back only to the team that started it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
361 lines
14 KiB
Go
361 lines
14 KiB
Go
package web
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"supermarket/internal/config"
|
|
"supermarket/internal/content"
|
|
"supermarket/internal/db"
|
|
"supermarket/internal/inventory"
|
|
"supermarket/internal/posting"
|
|
"supermarket/internal/users"
|
|
)
|
|
|
|
// newMultiEdition is a test server run as the multi-tenant edition: each
|
|
// team in its own schema. Postgres only.
|
|
func newMultiEdition(t *testing.T) (*Server, http.Handler) {
|
|
t.Helper()
|
|
if !db.OnPostgres() {
|
|
t.Skip("the multi-tenant edition needs Postgres")
|
|
}
|
|
s, h := newServerEdition(t)
|
|
s.Config = &config.Config{Edition: config.Multi}
|
|
teams, err := s.DB.Teams()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(teams.Close)
|
|
s.Teams, s.Platform = teams, s.DB
|
|
return s, h
|
|
}
|
|
|
|
// newTeam makes a team with its schema and an owner, signed in.
|
|
func newTeam(t *testing.T, s *Server, name, owner string) (*users.TeamInfo, *users.User, *http.Cookie) {
|
|
t.Helper()
|
|
team, err := users.CreateTeam(s.platform(), name, strings.ToLower(name)+".example", time.Now())
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := s.Teams.Create(team.ID); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
u := &users.User{Email: owner, Name: name + " owner", Status: users.Active}
|
|
if err := users.Create(s.platform(), u, time.Now()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
users.SetPassword(s.platform(), u, "a long enough one")
|
|
if err := users.Join(s.platform(), team.ID, u.ID, users.Owner, nil, time.Now()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
token, _, err := users.StartSessionIn(s.platform(), u.ID, team.ID, "", "", time.Now())
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return team, u, &http.Cookie{Name: sessionCookie, Value: token}
|
|
}
|
|
|
|
func TestTeamsDontSeeEachOther(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")
|
|
|
|
// Each saves its profile and a Market entry, through the pages.
|
|
for _, c := range []struct {
|
|
cookie *http.Cookie
|
|
name string
|
|
}{{ac, "Acme"}, {bc, "Bolt"}} {
|
|
if rec := as(h, c.cookie, http.MethodPost, "/settings/profile", url.Values{"name": {c.name + " Inc"}, "description": {"We are " + c.name}}); rec.Code != http.StatusSeeOther {
|
|
t.Fatalf("%s profile: %d %s", c.name, rec.Code, rec.Body.String())
|
|
}
|
|
if rec := as(h, c.cookie, http.MethodPost, "/market/save", url.Values{"name": {c.name + "'s rival"}, "relationship": {"competitor"}, "description": {"x"}}); rec.Code != http.StatusSeeOther {
|
|
t.Fatalf("%s market: %d %s", c.name, rec.Code, rec.Body.String())
|
|
}
|
|
}
|
|
for _, c := range []struct {
|
|
cookie *http.Cookie
|
|
mine, other string
|
|
}{{ac, "Acme", "Bolt"}, {bc, "Bolt", "Acme"}} {
|
|
for _, p := range []string{"/settings/profile", "/market", "/search?q=rival", "/"} {
|
|
body := as(h, c.cookie, http.MethodGet, p, nil).Body.String()
|
|
if strings.Contains(body, c.other) {
|
|
t.Errorf("%s sees %s on %s", c.mine, c.other, p)
|
|
}
|
|
}
|
|
if body := as(h, c.cookie, http.MethodGet, "/market", nil).Body.String(); !strings.Contains(body, c.mine+"'s rival") {
|
|
t.Errorf("%s doesn't see its own entry", c.mine)
|
|
}
|
|
}
|
|
// In the database: each team's rows in its own schema, none in the main.
|
|
if list, _ := inventory.List(s.platform(), ""); len(list) != 0 {
|
|
t.Errorf("rows in the main schema: %v", list)
|
|
}
|
|
ta, _ := s.forTeam(a.ID)
|
|
tb, _ := s.forTeam(b.ID)
|
|
if la, _ := inventory.List(ta.DB, ""); len(la) != 1 || la[0].Name != "Acme's rival" {
|
|
t.Errorf("team a: %v", la)
|
|
}
|
|
if lb, _ := inventory.List(tb.DB, ""); len(lb) != 1 || lb[0].Name != "Bolt's rival" {
|
|
t.Errorf("team b: %v", lb)
|
|
}
|
|
|
|
// Agents: each team's agent sees its own team's data only.
|
|
_, key := newAgentIn(t, ta, "A's agent", map[string]users.Access{"market": users.View})
|
|
text, _ := mcpCall(t, h, key, "market_list", map[string]any{})
|
|
if !strings.Contains(text, "Acme's rival") || strings.Contains(text, "Bolt") {
|
|
t.Errorf("agent's market: %s", text)
|
|
}
|
|
text, _ = mcpCall(t, h, key, "profile_get", map[string]any{})
|
|
if !strings.Contains(text, "Acme Inc") {
|
|
t.Errorf("agent's profile: %s", text)
|
|
}
|
|
// Secrets too: each team's own.
|
|
as(h, ac, http.MethodPost, "/settings/sources", url.Values{"hunter.api_key": {"acme-key"}})
|
|
if ta.Secrets.Get("hunter.api_key") != "acme-key" || tb.Secrets.Has("hunter.api_key") {
|
|
t.Error("secrets shared between teams")
|
|
}
|
|
}
|
|
|
|
// newAgentIn makes an agent in a team.
|
|
func newAgentIn(t *testing.T, ts *Server, name string, scopes map[string]users.Access) (*users.User, string) {
|
|
t.Helper()
|
|
u, err := users.CreateAgent(ts.platform(), name, "", time.Now())
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := users.Join(ts.platform(), ts.team(), u.ID, users.Member, scopes, time.Now()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
key, _, err := users.NewKey(ts.platform(), u.ID, time.Time{}, time.Now())
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return u, key
|
|
}
|
|
|
|
func TestRegisteredDomain(t *testing.T) {
|
|
for in, want := range map[string]string{"example.com": "example.com", "https://www.Example.com/x": "example.com",
|
|
"shop.example.co.uk": "example.co.uk", "http://cloud.acme.io:8080": "acme.io"} {
|
|
if got, err := registeredDomain(in); err != nil || got != want {
|
|
t.Errorf("%s: %q %v", in, got, err)
|
|
}
|
|
}
|
|
for _, bad := range []string{"", "localhost", "co.uk"} {
|
|
if _, err := registeredDomain(bad); err == nil {
|
|
t.Errorf("%q accepted", bad)
|
|
}
|
|
}
|
|
if !onDomain("https://enterprise.acme.io", "acme.io") || onDomain("https://acme.io.evil.com", "acme.io") {
|
|
t.Error("onDomain")
|
|
}
|
|
}
|
|
|
|
func TestSignUpAndSwitchTeams(t *testing.T) {
|
|
s, h := newMultiEdition(t)
|
|
form := url.Values{"name": {"Olu"}, "email": {"olu@acme.example"}, "password": {"a long enough one"}, "company": {"Acme"}, "website": {"www.acme.io"}}
|
|
if rec := do(h, http.MethodGet, "/signin", nil, nil); !strings.Contains(rec.Body.String(), `href="/signup"`) {
|
|
t.Error("no sign-up link")
|
|
}
|
|
rec := postForm(h, "/signup", form)
|
|
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/settings/profile?msg=team-created" {
|
|
t.Fatalf("sign up: %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
c := cookieOf(rec, sessionCookie)
|
|
u, _ := users.ByEmail(s.platform(), "olu@acme.example")
|
|
list, _ := users.TeamsOf(s.platform(), u.ID)
|
|
if len(list) != 1 || list[0].Domain != "acme.io" || list[0].Name != "Acme" {
|
|
t.Fatalf("teams %+v", list)
|
|
}
|
|
body := as(h, c, http.MethodGet, "/settings/profile", nil).Body.String()
|
|
if !strings.Contains(body, "https://www.acme.io") {
|
|
t.Error("profile not started")
|
|
}
|
|
// Same address again: sign in instead.
|
|
if rec := postForm(h, "/signup", form); rec.Code != http.StatusConflict {
|
|
t.Errorf("twice: %d", rec.Code)
|
|
}
|
|
// The profile keeps to the team's domain.
|
|
rec = as(h, c, http.MethodPost, "/settings/profile", url.Values{"name": {"Acme"}, "description": {"x"}, "website_url": {"https://other.example"}})
|
|
if !strings.Contains(rec.Body.String(), "isn't on acme.io") {
|
|
t.Errorf("another domain accepted: %s", rec.Body.String())
|
|
}
|
|
|
|
// A second team, from inside; the menu switches.
|
|
rec = as(h, c, http.MethodPost, "/teams/new", url.Values{"company": {"Acme Labs"}, "website": {"acmelabs.dev"}})
|
|
if rec.Code != http.StatusSeeOther {
|
|
t.Fatalf("new team: %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
list, _ = users.TeamsOf(s.platform(), u.ID)
|
|
if len(list) != 2 {
|
|
t.Fatalf("teams %+v", list)
|
|
}
|
|
body = as(h, c, http.MethodGet, "/", nil).Body.String()
|
|
if !strings.Contains(body, `<option value="`) || !strings.Contains(body, "Acme Labs") {
|
|
t.Error("no team menu")
|
|
}
|
|
var acme, labs int64
|
|
for _, tm := range list {
|
|
if tm.Name == "Acme" {
|
|
acme = tm.ID
|
|
} else {
|
|
labs = tm.ID
|
|
}
|
|
}
|
|
if body := as(h, c, http.MethodGet, "/settings/profile", nil).Body.String(); !strings.Contains(body, "acmelabs.dev") {
|
|
t.Error("not in the new team")
|
|
}
|
|
as(h, c, http.MethodPost, "/teams/switch", url.Values{"team": {strconv.FormatInt(acme, 10)}})
|
|
if body := as(h, c, http.MethodGet, "/settings/profile", nil).Body.String(); !strings.Contains(body, "www.acme.io") {
|
|
t.Error("didn't switch")
|
|
}
|
|
// Not someone else's team.
|
|
other, _, _ := newTeam(t, s, "Bolt", "bea@bolt.example")
|
|
if rec := as(h, c, http.MethodPost, "/teams/switch", url.Values{"team": {strconv.FormatInt(other.ID, 10)}}); rec.Code != http.StatusForbidden {
|
|
t.Errorf("switched into another's team: %d", rec.Code)
|
|
}
|
|
_ = labs
|
|
|
|
// Bolt's owner invites Olu: Olu joins with the account he has.
|
|
_, _, bc := newTeamOwnerCookie(t, s, other.ID)
|
|
rec = as(h, bc, http.MethodPost, "/settings/users", url.Values{"email": {"olu@acme.example"}, "name": {"Olu"}, "role": {"member"}, "module:seo": {"view"}})
|
|
if rec.Code != http.StatusSeeOther || !strings.Contains(rec.Header().Get("Location"), "added") {
|
|
t.Fatalf("add existing: %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
if list, _ = users.TeamsOf(s.platform(), u.ID); len(list) != 3 {
|
|
t.Errorf("not added: %+v", list)
|
|
}
|
|
waitMail(t, s, "olu@acme.example", 1)
|
|
// Signing in again opens the team used last.
|
|
rec = signin(h, "203.0.113.50", url.Values{"email": {"olu@acme.example"}, "password": {"a long enough one"}})
|
|
nc := cookieOf(rec, sessionCookie)
|
|
if body := as(h, nc, http.MethodGet, "/settings/profile", nil).Body.String(); !strings.Contains(body, "www.acme.io") {
|
|
t.Error("signed in to another team than the last")
|
|
}
|
|
}
|
|
|
|
// newTeamOwnerCookie signs in a team's owner.
|
|
func newTeamOwnerCookie(t *testing.T, s *Server, team int64) (*users.User, int64, *http.Cookie) {
|
|
t.Helper()
|
|
list, _ := users.Members(s.platform(), team)
|
|
for _, m := range list {
|
|
if m.Role == users.Owner {
|
|
token, _, _ := users.StartSessionIn(s.platform(), m.ID, team, "", "", time.Now())
|
|
return m.User, team, &http.Cookie{Name: sessionCookie, Value: token}
|
|
}
|
|
}
|
|
t.Fatal("no owner")
|
|
return nil, 0, nil
|
|
}
|
|
|
|
func TestProvingTheDomain(t *testing.T) {
|
|
s, h := newMultiEdition(t)
|
|
a, _, ac := newTeam(t, s, "Acme", "olu@acme.example")
|
|
// Before the proof, what touches the site waits.
|
|
rec := as(h, ac, http.MethodPost, "/seo/audit?site=0", url.Values{})
|
|
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/settings/domain?msg=prove-first" {
|
|
t.Errorf("audit before the proof: %d %s", rec.Code, rec.Header().Get("Location"))
|
|
}
|
|
body := as(h, ac, http.MethodGet, "/settings/domain", nil).Body.String()
|
|
team, _ := users.GetTeam(s.platform(), a.ID)
|
|
if team.VerifyToken == "" || !strings.Contains(body, team.VerifyToken) || !strings.Contains(body, "acme.example") {
|
|
t.Fatalf("domain page: %s", body)
|
|
}
|
|
|
|
// DNS: wrong, then right.
|
|
records := []string{"v=spf1 -all"}
|
|
lookupTXT = func(_ context.Context, name string) ([]string, error) {
|
|
if name != "acme.example" {
|
|
return nil, errors.New("nxdomain")
|
|
}
|
|
return records, nil
|
|
}
|
|
defer func() { lookupTXT = net.DefaultResolver.LookupTXT }()
|
|
if rec := as(h, ac, http.MethodPost, "/settings/domain/check/dns", url.Values{}); rec.Code != http.StatusUnprocessableEntity {
|
|
t.Errorf("no record: %d", rec.Code)
|
|
}
|
|
records = append(records, team.VerifyToken)
|
|
if rec := as(h, ac, http.MethodPost, "/settings/domain/check/dns", url.Values{}); rec.Code != http.StatusSeeOther {
|
|
t.Fatalf("record: %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
if tm, _ := users.GetTeam(s.platform(), a.ID); !tm.Proved() || tm.VerifiedBy != "dns" {
|
|
t.Errorf("not proved: %+v", tm)
|
|
}
|
|
if rec := as(h, ac, http.MethodPost, "/seo/audit?site=0", url.Values{}); rec.Header().Get("Location") == "/settings/domain?msg=prove-first" {
|
|
t.Error("still waiting after the proof")
|
|
}
|
|
|
|
// Another team on the same domain can't prove it while Acme holds it,
|
|
// even with the file in place.
|
|
other, _ := users.CreateTeam(s.platform(), "Impostor", "acme.example", time.Now())
|
|
s.Teams.Create(other.ID)
|
|
imp := &users.User{Email: "eve@evil.example", Status: users.Active}
|
|
users.Create(s.platform(), imp, time.Now())
|
|
users.Join(s.platform(), other.ID, imp.ID, users.Owner, nil, time.Now())
|
|
tok, _, _ := users.StartSessionIn(s.platform(), imp.ID, other.ID, "", "", time.Now())
|
|
ic := &http.Cookie{Name: sessionCookie, Value: tok}
|
|
otherTok, _ := users.VerifyToken(s.platform(), other.ID)
|
|
site := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path == verifyPath {
|
|
w.Write([]byte(otherTok + "\n"))
|
|
return
|
|
}
|
|
http.NotFound(w, r)
|
|
}))
|
|
defer site.Close()
|
|
fileBase = func(string) string { return site.URL }
|
|
defer func() { fileBase = func(host string) string { return "https://" + host } }()
|
|
rec = as(h, ic, http.MethodPost, "/settings/domain/check/file", url.Values{})
|
|
if rec.Code != http.StatusConflict || !strings.Contains(rec.Body.String(), "Another team") {
|
|
t.Errorf("second team: %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
// Released, the file proves it.
|
|
users.ReleaseDomain(s.platform(), a.ID)
|
|
if rec := as(h, ic, http.MethodPost, "/settings/domain/check/file", url.Values{}); rec.Code != http.StatusSeeOther {
|
|
t.Errorf("file: %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestJobsRunPerTeam(t *testing.T) {
|
|
s, _ := newMultiEdition(t)
|
|
sent := &fakePosts{}
|
|
s.testPublisher = func(a *posting.Account) content.Publisher { return fakePub{sent, a} }
|
|
var teams []*users.TeamInfo
|
|
for _, name := range []string{"Acme", "Bolt", "Calm"} {
|
|
tm, _, _ := newTeam(t, s, name, strings.ToLower(name)+"@x.example")
|
|
teams = append(teams, tm)
|
|
ts, err := s.forTeam(tm.ID)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
acct := &posting.Account{Network: posting.X, Name: "@" + strings.ToLower(name), External: strings.ToLower(name)}
|
|
posting.Save(ts.DB, ts.Secrets, acct, "t", "", time.Now())
|
|
content.CreateDrafts(ts.DB, []content.Draft{{Channel: content.ChannelX, Content: name + " news"}})
|
|
ds, _ := content.ListDrafts(ts.DB, 1, content.StatusDraft)
|
|
content.Schedule(ts.DB, ds[0].ID, time.Now().Add(time.Minute))
|
|
}
|
|
// Calm is suspended: its work waits.
|
|
users.SetTeamStatus(s.platform(), teams[2].ID, users.TeamSuspended, time.Time{})
|
|
s.jobDo(context.Background(), "scheduler", func(ctx context.Context, ts *Server) { ts.publishDue(ctx, time.Now().Add(2*time.Minute)) })
|
|
got := strings.Join(sent.sent, "|")
|
|
if len(sent.sent) != 2 || !strings.Contains(got, "X @acme: Acme news") || !strings.Contains(got, "X @bolt: Bolt news") {
|
|
t.Errorf("sent %v", sent.sent)
|
|
}
|
|
// Each team's lock is its own.
|
|
ts, _ := s.forTeam(teams[0].ID)
|
|
if ts.lockName("job:seo") == s.lockName("job:seo") || !strings.HasPrefix(ts.lockName("job:seo"), "team:") {
|
|
t.Errorf("lock %s", ts.lockName("job:seo"))
|
|
}
|
|
// Its files are under its own prefix.
|
|
if ts.Files != nil && !strings.Contains(ts.Files.String(), "teams/") {
|
|
t.Errorf("files %s", ts.Files.String())
|
|
}
|
|
}
|