From d35ed7cbb2613e85a3adcdcdc6ee51736b901789 Mon Sep 17 00:00:00 2001 From: David Young Date: Wed, 25 Nov 2026 12:35:53 -0700 Subject: [PATCH] Phase 13, part 7: the platform's own admin The people running the multi-tenant service (SUPERMARKET_PLATFORM_ADMINS, with two-factor sign-in) see every team at /platform with its size, people and what failed lately, and can suspend or restore a team, resend its invitations and release its domain. They don't see a team's data unless they view as it: with a reason, for at most an hour, read-only, recorded in the team's own audit log. Co-Authored-By: Claude Opus 5.5 --- PLAN.md | 23 ++- internal/config/config.go | 17 ++ internal/db/migrations.go | 9 + internal/users/sessions.go | 11 +- internal/users/teams.go | 14 ++ internal/web/access.go | 3 + internal/web/activity.go | 3 +- internal/web/auth.go | 42 ++++- internal/web/platform.go | 224 ++++++++++++++++++++++++ internal/web/server.go | 8 + internal/web/signin.go | 2 +- internal/web/teams_test.go | 72 ++++++++ internal/web/templates/layout.html | 3 + internal/web/templates/platform.html | 30 ++++ internal/web/templates/team-closed.html | 8 + 15 files changed, 459 insertions(+), 10 deletions(-) create mode 100644 internal/web/platform.go create mode 100644 internal/web/templates/platform.html create mode 100644 internal/web/templates/team-closed.html diff --git a/PLAN.md b/PLAN.md index 487b909..1029b64 100644 --- a/PLAN.md +++ b/PLAN.md @@ -55,7 +55,7 @@ tools over MCP, approvals, limits and visibility, and the JSON API. Schema 39. **Phase 13 (multi-tenant) is under way** on branch `phase13`, with a -Postgres schema per team (decided 2026-11-26); parts 1–6 are built. +Postgres schema per team (decided 2026-11-26); parts 1–7 are built. **Phase 12 (signing in with the Core, OIDC) is set aside for now** (2026-11-26): before it starts, the user will share the Federated Core's @@ -2895,6 +2895,27 @@ stand. and the hand setup are the local edition's. The platform never holds a Core's admin credentials. +**Part 7 built 2026-11-26** on `phase13`. +- `SUPERMARKET_PLATFORM_ADMINS` lists the platform's admins by email + (multi-tenant only). They sign in like anyone, and may belong to no team: + their session then works in team 0, the platform, and everything but + `/platform` and their own account leads there. `/platform` needs their + two-factor sign-in on, and says so until it is. +- `/platform` lists every team: its status, domain (proved or not), people + and pending invitations, the size of its schema, what failed in the last + week (posts, outreach emails, agents' requests: counted, never read) and + its last activity. For each: *Suspend* (with why), *Restore*, *Resend + invitations*, *Release the domain*, *View as*. +- A suspended team (or one being deleted) is closed to its people: a page + says so; they can still switch teams and reach their account. Its jobs + wait (part 5). +- *View as* needs a reason and a length, at most an hour (schema 42: + `sessions.view_until` and `view_reason`). The admin's session points at + the team, read-only (every module to view; no Settings); a banner says so, + with *Stop viewing*; it ends by itself. The team's own audit log records + who looked, why and for how long, as it does a suspension, a restore, a + release and resent invitations. + 1. **Teams everywhere.** - Every table that holds a company's data gets `team_id`, and its unique keys include it. The settings table's key becomes diff --git a/internal/config/config.go b/internal/config/config.go index 90a9dfe..da82fd3 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -95,6 +95,9 @@ type Config struct { Storage Storage Mail *Mail // nil if not set PGBackups string // where the server's nightly dumps are, to list them; "" if not known + // PlatformAdmins are the email addresses of the people running the + // multi-tenant service (its /platform area). + PlatformAdmins []string } // Environment variables. @@ -117,6 +120,7 @@ const ( EnvMailURL = "SUPERMARKET_MAIL_URL" EnvMailFrom = "SUPERMARKET_MAIL_FROM" EnvPGBackups = "SUPERMARKET_PG_BACKUPS" + EnvPlatform = "SUPERMARKET_PLATFORM_ADMINS" ) // Load reads the settings through getenv (os.Getenv) and checks them. All @@ -211,6 +215,19 @@ func Load(getenv func(string) string) (*Config, error) { } c.PGBackups = get(EnvPGBackups, "") + for _, a := range strings.Split(get(EnvPlatform, ""), ",") { + if a = strings.ToLower(strings.TrimSpace(a)); a == "" { + continue + } + if _, err := mail.ParseAddress(a); err != nil { + bad("%s: %q isn't an email address", EnvPlatform, a) + continue + } + c.PlatformAdmins = append(c.PlatformAdmins, a) + } + if len(c.PlatformAdmins) > 0 && c.Edition != Multi { + bad("%s is for the multi-tenant edition", EnvPlatform) + } if len(problems) > 0 { return c, errors.New(strings.Join(problems, "\n")) diff --git a/internal/db/migrations.go b/internal/db/migrations.go index f70c755..2a38e30 100644 --- a/internal/db/migrations.go +++ b/internal/db/migrations.go @@ -282,6 +282,15 @@ ALTER TABLE teams ADD COLUMN verify_token TEXT NOT NULL DEFAULT ''; -- what the ALTER TABLE teams ADD COLUMN verified_at TEXT NOT NULL DEFAULT ''; -- '' until proved ALTER TABLE teams ADD COLUMN verified_by TEXT NOT NULL DEFAULT ''; -- dns, file or search-console CREATE UNIQUE INDEX teams_proved_domain ON teams(domain) WHERE verified_at <> ''; +`, + }, + // 42 + { + Note: "the platform's admins looking at a team, with a reason, for a while", + Platform: true, + SQLite: ` +ALTER TABLE sessions ADD COLUMN view_until TEXT NOT NULL DEFAULT ''; -- a platform admin viewing a team: until then +ALTER TABLE sessions ADD COLUMN view_reason TEXT NOT NULL DEFAULT ''; `, }, } diff --git a/internal/users/sessions.go b/internal/users/sessions.go index 07f5cea..7fc244d 100644 --- a/internal/users/sessions.go +++ b/internal/users/sessions.go @@ -33,6 +33,9 @@ type Session struct { IP string UserAgent string Team int64 // the team it works in (multi-tenant: switchable) + // A platform admin viewing a team: until when, and why. + ViewUntil time.Time + ViewReason string } // ErrNoSession is a cookie that leads nowhere: unknown, ended or expired, @@ -85,15 +88,15 @@ func expiry(created, seen time.Time) time.Time { return max } -const sessionCols = `id, user_id, created_at, seen_at, expires_at, ip, user_agent, team_id` +const sessionCols = `id, user_id, created_at, seen_at, expires_at, ip, user_agent, team_id, view_until, view_reason` func scanSession(row interface{ Scan(...any) error }) (*Session, error) { var s Session - var created, seen, expires string - if err := row.Scan(&s.ID, &s.User, &created, &seen, &expires, &s.IP, &s.UserAgent, &s.Team); err != nil { + var created, seen, expires, until string + if err := row.Scan(&s.ID, &s.User, &created, &seen, &expires, &s.IP, &s.UserAgent, &s.Team, &until, &s.ViewReason); err != nil { return nil, err } - s.Created, s.Seen, s.Expires = parseTS(created), parseTS(seen), parseTS(expires) + s.Created, s.Seen, s.Expires, s.ViewUntil = parseTS(created), parseTS(seen), parseTS(expires), parseTS(until) return &s, nil } diff --git a/internal/users/teams.go b/internal/users/teams.go index dca4817..276b8ad 100644 --- a/internal/users/teams.go +++ b/internal/users/teams.go @@ -183,3 +183,17 @@ func ReleaseDomain(d *db.DB, team int64) error { _, err := d.Exec(`UPDATE teams SET verified_at = '', verified_by = '' WHERE id = ?`, team) return err } + +// ViewAs points a platform admin's session at a team for a while, with +// the reason; team 0, and no time, ends it. +func ViewAs(d *db.DB, sessionID string, team int64, until time.Time, reason string) error { + _, err := d.Exec(`UPDATE sessions SET team_id = ?, view_until = ?, view_reason = ? WHERE id = ?`, team, tsOrEmpty(until), reason, sessionID) + return err +} + +// TeamCounts are a team's members and pending invitations. +func TeamCounts(d *db.DB, team int64) (members, invited int, err error) { + err = d.QueryRow(`SELECT count(*), coalesce(sum(CASE WHEN u.status = 'invited' THEN 1 ELSE 0 END), 0) FROM memberships m JOIN users u ON u.id = m.user_id + WHERE m.team_id = ? AND u.kind = 'person'`, team).Scan(&members, &invited) + return members, invited, err +} diff --git a/internal/web/access.go b/internal/web/access.go index 400f623..0a7f644 100644 --- a/internal/web/access.go +++ b/internal/web/access.go @@ -40,6 +40,7 @@ var routeAreas = map[string]string{ "=/profile": areaSignedIn, "=/core": areaSignedIn, "/settings": areaAdmin, + "/platform": areaPlatform, // Signing in to a posting account: admins for the company's, anyone // with Content for their own (oauthStart checks which). "/auth": areaSignedIn, @@ -91,6 +92,8 @@ func (v *viewer) can(area string, write bool) bool { return v.User != nil || v == localOwner case areaAdmin: return v.Member.Admin() + case areaPlatform: + return v.Platform } return v.Member.Can(area, write) } diff --git a/internal/web/activity.go b/internal/web/activity.go index 87e84f3..a0c3a52 100644 --- a/internal/web/activity.go +++ b/internal/web/activity.go @@ -180,7 +180,8 @@ var actionLabels = map[string]string{ "key-made": "made a new key for", "key-revoked": "revoked a key of", "asked-approval": "asked for approval to", "did-on-its-own": "did on its own:", "approved": "approved", "refused": "refused", "allowed-on-its-own": "let an agent act on its own:", "withdrew-on-its-own": "took back what an agent may do on its own:", - "team-created": "set up the team", "domain-proved": "proved the domain", "agent-paused": "paused the agent", "agent-resumed": "resumed the agent", "agent-limits": "changed the limits of", + "team-created": "set up the team", "viewed-as": "looked at the team's data:", "team-suspended": "suspended the team", "team-restored": "restored the team", + "domain-released": "released the domain", "invitations-resent": "sent the invitations again:", "domain-proved": "proved the domain", "agent-paused": "paused the agent", "agent-resumed": "resumed the agent", "agent-limits": "changed the limits of", "wrote-draft": "wrote a draft:", "edited-draft": "edited a draft:", "edited-change": "edited a proposed change to", "market-added": "added to the Market", "market-changed": "changed in the Market", } diff --git a/internal/web/auth.go b/internal/web/auth.go index 9f76876..7da4fcb 100644 --- a/internal/web/auth.go +++ b/internal/web/auth.go @@ -27,6 +27,9 @@ type viewer struct { User *users.User // nil on the local edition Member users.Membership Session *users.Session // nil on the local edition + + Platform bool // runs the multi-tenant platform (SUPERMARKET_PLATFORM_ADMINS) + Viewing bool // a platform admin viewing a team, read-only } // localOwner is the local edition's one user. @@ -109,6 +112,21 @@ func (s *Server) sessions(next http.Handler) http.Handler { s.toSignIn(w, r) return } + if s.multi() && v.Session != nil && !publicPath(r.URL.Path) && !platformPath(r.URL.Path) { + // A platform admin outside any team: the platform's pages. + if v.Session.Team == 0 { + http.Redirect(w, r, "/platform", http.StatusSeeOther) + return + } + // A team that's suspended or being deleted is closed, but for + // switching teams, one's account, and the platform's admins. + if !v.Viewing && !strings.HasPrefix(r.URL.Path, "/teams/") { + if t, err := users.GetTeam(s.platform(), v.Session.Team); err == nil && t.Status != users.TeamActive { + s.teamClosed(w, r, t) + return + } + } + } next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), viewerKey, v))) }) } @@ -119,10 +137,28 @@ func (s *Server) lookupSession(r *http.Request) (*viewer, error) { if err != nil { return nil, users.ErrNoSession } - sess, u, err := users.Lookup(s.platform(), c.Value, time.Now()) + now := time.Now() + sess, u, err := users.Lookup(s.platform(), c.Value, now) if err != nil { return nil, err } + pa := s.isPlatformAdmin(u) + if s.multi() && !sess.ViewUntil.IsZero() { + if pa && now.Before(sess.ViewUntil) { + return &viewer{User: u, Member: readOnly(sess.Team), Session: sess, Platform: true, Viewing: true}, nil + } + // Ran out: back to the platform. + if err := users.ViewAs(s.platform(), sess.ID, 0, time.Time{}, ""); err != nil { + return nil, err + } + sess.Team, sess.ViewUntil, sess.ViewReason = 0, time.Time{}, "" + } + if s.multi() && sess.Team == 0 { + if !pa { + return nil, users.ErrNoSession + } + return &viewer{User: u, Member: users.Membership{Team: 0, Role: users.Member}, Session: sess, Platform: true}, nil + } m, err := users.MembershipOf(s.platform(), sess.Team, u.ID) if errors.Is(err, users.ErrNotFound) { return nil, users.ErrNoSession // no longer in the team @@ -130,7 +166,7 @@ func (s *Server) lookupSession(r *http.Request) (*viewer, error) { if err != nil { return nil, err } - return &viewer{User: u, Member: m, Session: sess}, nil + return &viewer{User: u, Member: m, Session: sess, Platform: pa}, nil } // toSignIn sends someone who isn't signed in to the sign-in page, and @@ -167,7 +203,7 @@ func (s *Server) startSession(w http.ResponseWriter, r *http.Request, u *users.U team = t.ID } } - if team == 0 { + if team == 0 && !s.isPlatformAdmin(u) { return errors.New("you aren't in any team that's open") } } diff --git a/internal/web/platform.go b/internal/web/platform.go new file mode 100644 index 0000000..d68de33 --- /dev/null +++ b/internal/web/platform.go @@ -0,0 +1,224 @@ +package web + +import ( + "fmt" + "net/http" + "strconv" + "strings" + "time" + + "supermarket/internal/audit" + "supermarket/internal/users" +) + +// The platform's own admin (multi-tenant): the people running the service, +// listed in SUPERMARKET_PLATFORM_ADMINS, at /platform, with two-factor +// sign-in. They see the teams and their health, suspend a team, resend its +// invitations, release a proved domain; they don't see a team's data, +// unless they *view as* it: with a reason, for at most an hour, read-only, +// and recorded in the team's own audit log. + +const areaPlatform = "platform" + +// maxViewAs is the longest a platform admin views a team. +const maxViewAs = time.Hour + +// isPlatformAdmin says whether a person runs the platform. +func (s *Server) isPlatformAdmin(u *users.User) bool { + if !s.multi() || s.Config == nil || u == nil || u.Kind != users.Person { + return false + } + for _, a := range s.Config.PlatformAdmins { + if strings.EqualFold(a, u.Email) { + return true + } + } + return false +} + +// readOnly is a membership that sees every module and changes nothing: +// a platform admin viewing a team. +func readOnly(team int64) users.Membership { + m := users.Membership{Team: team, Role: users.Member, Modules: map[string]users.Access{}} + for _, g := range grants() { + m.Modules[g.ID] = users.View + } + return m +} + +// platformPaths are what a platform admin's session outside any team may +// reach. +func platformPath(p string) bool { + return strings.HasPrefix(p, "/platform") || strings.HasPrefix(p, "/settings/account") || p == "/signout" || + strings.HasPrefix(p, "/users/") || strings.HasPrefix(p, "/static/") || p == "/favicon.ico" +} + +// teamRow is a team on the platform page. +type teamRow struct { + users.TeamInfo + Members, Invited int + Bytes int64 + FailedPosts int + FailedEmails int + FailedRequests int + LastActivity time.Time + Err string +} + +func (s *Server) platformPage(w http.ResponseWriter, r *http.Request) { + v := viewerOf(r) + if !v.Platform { + s.forbidden(w, r) + return + } + u, err := users.ByID(s.platform(), v.User.ID) + if err != nil { + s.serverError(w, err) + return + } + if !u.TwoFactor { + s.render(w, r, "platform", page{Title: "Platform", Nav: "platform", Data: map[string]any{"Need2FA": true}}) + return + } + list, err := users.ListTeams(s.platform()) + if err != nil { + s.serverError(w, err) + return + } + week := time.Now().AddDate(0, 0, -7).UTC() + var rows []teamRow + for _, t := range list { + row := teamRow{TeamInfo: t} + row.Members, row.Invited, _ = users.TeamCounts(s.platform(), t.ID) + _ = s.platform().QueryRow(`SELECT coalesce(sum(pg_total_relation_size(c.oid)), 0) FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = ? AND c.relkind = 'r'`, s.Teams.Schema(t.ID)).Scan(&row.Bytes) + // Health: what failed in the last week, counted, never read. + if ts, err := s.forTeam(t.ID); err != nil { + row.Err = err.Error() + } else { + wk := week.Format("2006-01-02T15:04:05Z") + _ = ts.DB.QueryRow(`SELECT count(*) FROM drafts WHERE status = 'failed' AND updated_at >= ?`, wk).Scan(&row.FailedPosts) + _ = ts.DB.QueryRow(`SELECT count(*) FROM outreach WHERE status = 'failed' AND created_at >= ?`, wk).Scan(&row.FailedEmails) + _ = ts.DB.QueryRow(`SELECT count(*) FROM approvals WHERE status = 'failed' AND created_at >= ?`, week.Format("2006-01-02T15:04:05.000Z")).Scan(&row.FailedRequests) + var last string + _ = ts.DB.QueryRow(`SELECT coalesce(max(at), '') FROM audit_log`).Scan(&last) + row.LastActivity, _ = time.Parse("2006-01-02T15:04:05.000Z", last) + } + rows = append(rows, row) + } + s.render(w, r, "platform", page{Title: "Platform", Nav: "platform", Data: map[string]any{"Teams": rows, "MaxView": int(maxViewAs / time.Minute)}}) +} + +// platformAction: suspend, restore, resend, release-domain, view-as. +func (s *Server) platformAction(w http.ResponseWriter, r *http.Request) { + v := viewerOf(r) + if !v.Platform { + s.forbidden(w, r) + return + } + if u, err := users.ByID(s.platform(), v.User.ID); err != nil || !u.TwoFactor { + http.Redirect(w, r, "/platform", http.StatusSeeOther) + return + } + id, _ := strconv.ParseInt(r.PathValue("id"), 10, 64) + t, err := users.GetTeam(s.platform(), id) + if err != nil { + http.NotFound(w, r) + return + } + ts, err := s.forTeam(id) + if err != nil { + s.serverError(w, err) + return + } + who := displayName(v.User) + " (the platform's admin)" + log := func(action, detail string) { + ts.record(audit.Entry{UserID: v.User.ID, UserName: who, Action: action, Target: t.Name, Detail: detail, IP: clientIP(r)}) + s.Log.Info("platform: "+action, "team", t.ID, "by", v.User.Email, "detail", detail) + } + now := time.Now() + switch r.PathValue("action") { + case "suspend": + if err := users.SetTeamStatus(s.platform(), id, users.TeamSuspended, time.Time{}); err != nil { + s.serverError(w, err) + return + } + log("team-suspended", r.PostFormValue("reason")) + redirect(w, r, "/platform", "team-suspended") + case "restore": + if err := users.SetTeamStatus(s.platform(), id, users.TeamActive, time.Time{}); err != nil { + s.serverError(w, err) + return + } + log("team-restored", "") + redirect(w, r, "/platform", "team-restored") + case "release-domain": + if err := users.ReleaseDomain(s.platform(), id); err != nil { + s.serverError(w, err) + return + } + log("domain-released", t.Domain) + redirect(w, r, "/platform", "domain-released") + case "resend": + members, err := users.Members(s.platform(), id) + if err != nil { + s.serverError(w, err) + return + } + n := 0 + for _, m := range members { + if m.Status == users.Invited && m.Kind == users.Person { + if err := ts.sendInvitation(v, m.User); err != nil { + s.serverError(w, err) + return + } + n++ + } + } + log("invitations-resent", fmt.Sprintf("%d", n)) + redirectCounts(w, r, "/platform", "invitations-resent", n) + case "view-as": + reason := strings.TrimSpace(r.PostFormValue("reason")) + mins, _ := strconv.Atoi(r.PostFormValue("minutes")) + if reason == "" || mins <= 0 { + redirect(w, r, "/platform", "view-needs-reason") + return + } + d := time.Duration(mins) * time.Minute + if d > maxViewAs { + d = maxViewAs + } + if err := users.ViewAs(s.platform(), v.Session.ID, id, now.Add(d), reason); err != nil { + s.serverError(w, err) + return + } + log("viewed-as", fmt.Sprintf("%s (for %d minutes)", reason, int(d/time.Minute))) + http.Redirect(w, r, "/", http.StatusSeeOther) + default: + http.NotFound(w, r) + } +} + +// platformStopViewing ends a view-as. +func (s *Server) platformStopViewing(w http.ResponseWriter, r *http.Request) { + v := viewerOf(r) + if !v.Platform || v.Session == nil { + s.forbidden(w, r) + return + } + if err := users.ViewAs(s.platform(), v.Session.ID, 0, time.Time{}, ""); err != nil { + s.serverError(w, err) + return + } + http.Redirect(w, r, "/platform", http.StatusSeeOther) +} + +// teamClosed is what a suspended team's people see. +func (s *Server) teamClosed(w http.ResponseWriter, r *http.Request, t *users.TeamInfo) { + if r.Header.Get("HX-Request") != "" || !safeMethod(r.Method) { + http.Error(w, "This team is "+t.Status+".", http.StatusForbidden) + return + } + w.WriteHeader(http.StatusForbidden) + s.render(w, r, "team-closed", page{Title: t.Name, Bare: true, Data: t}) +} diff --git a/internal/web/server.go b/internal/web/server.go index 7d1bf0d..9dd8fdc 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -331,6 +331,9 @@ func (s *Server) Handler() (http.Handler, error) { // Signing in (the server edition). mux.HandleFunc("GET /setup/{token}", (*Server).setupPage) mux.HandleFunc("POST /setup/{token}", (*Server).setupSave) + mux.HandleFunc("GET /platform", (*Server).platformPage) + mux.HandleFunc("POST /platform/stop-viewing", (*Server).platformStopViewing) + mux.HandleFunc("POST /platform/teams/{id}/{action}", (*Server).platformAction) mux.HandleFunc("GET /signup", (*Server).signupPage) mux.HandleFunc("POST /signup", (*Server).signup) mux.HandleFunc("POST /teams/switch", (*Server).teamSwitch) @@ -920,6 +923,11 @@ var flashes = map[string]string{ "added": "Added: they're told by email, and sign in as they do.", "prove-first": "First prove the team's domain is yours: Supermarket only crawls, reads or publishes to a website its team has proved.", "domain-proved": "Proved: the domain is the team's.", + "team-suspended": "Suspended: its people see that it is, and its work waits.", + "team-restored": "Restored.", + "domain-released": "Released: another team can prove the domain now.", + "invitations-resent": "Sent %d invitations again.", + "view-needs-reason": "Give a reason and how long: it's recorded in the team's own log.", "account-removed": "Signed out: posts scheduled to it are back in Posts.", "own-account-connected": "Connected: you can post as it, and an admin can let others.", "deleted": "Deleted.", diff --git a/internal/web/signin.go b/internal/web/signin.go index dbe743d..5fbdbc3 100644 --- a/internal/web/signin.go +++ b/internal/web/signin.go @@ -116,7 +116,7 @@ func (s *Server) cannotSignIn(u *users.User) string { return badSignIn } if s.multi() { - if list, err := users.TeamsOf(s.platform(), u.ID); err != nil || len(list) == 0 { + if list, err := users.TeamsOf(s.platform(), u.ID); (err != nil || len(list) == 0) && !s.isPlatformAdmin(u) { return "This account isn't part of any team any more." } return "" diff --git a/internal/web/teams_test.go b/internal/web/teams_test.go index fe6f575..1370c99 100644 --- a/internal/web/teams_test.go +++ b/internal/web/teams_test.go @@ -12,6 +12,7 @@ import ( "testing" "time" + "supermarket/internal/audit" "supermarket/internal/config" "supermarket/internal/content" "supermarket/internal/db" @@ -380,3 +381,74 @@ func TestCorePerTeam(t *testing.T) { t.Error("not on Connections") } } + +func TestPlatformAdmin(t *testing.T) { + s, h := newMultiEdition(t) + s.Config.PlatformAdmins = []string{"ops@platform.example"} + a, _, ac := newTeam(t, s, "Acme", "olu@acme.example") + as(h, ac, http.MethodPost, "/settings/profile", url.Values{"name": {"Acme Inc"}, "description": {"Secret plans"}}) + as(h, ac, http.MethodPost, "/market/save", url.Values{"name": {"Rival"}, "relationship": {"competitor"}, "description": {"x"}}) + + ops := &users.User{Email: "ops@platform.example", Name: "Ops", Status: users.Active} + users.Create(s.platform(), ops, time.Now()) + users.SetPassword(s.platform(), ops, "a long enough one") + // Not in any team, they can still sign in, to the platform. + rec := signin(h, "203.0.113.9", url.Values{"email": {"ops@platform.example"}, "password": {"a long enough one"}}) + oc := cookieOf(rec, sessionCookie) + if oc == nil { + t.Fatalf("sign in: %d %s", rec.Code, rec.Body.String()) + } + if rec := as(h, oc, http.MethodGet, "/market", nil); rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/platform" { + t.Errorf("a team page: %d %s", rec.Code, rec.Header().Get("Location")) + } + if body := as(h, oc, http.MethodGet, "/platform", nil).Body.String(); !strings.Contains(body, "two-factor") { + t.Error("no two-factor demanded") + } + users.SetTwoFactor(s.platform(), ops, true, []string{"x"}) + body := as(h, oc, http.MethodGet, "/platform", nil).Body.String() + if !strings.Contains(body, "Acme") || !strings.Contains(body, "acme.example") || strings.Contains(body, "Secret plans") || strings.Contains(body, "Rival") { + t.Errorf("platform page: %s", body) + } + // A team's owner isn't a platform admin. + if rec := as(h, ac, http.MethodGet, "/platform", nil); rec.Code != http.StatusForbidden { + t.Errorf("owner on /platform: %d", rec.Code) + } + + id := strconv.FormatInt(a.ID, 10) + // Suspend: the team's people see it closed; restore. + as(h, oc, http.MethodPost, "/platform/teams/"+id+"/suspend", url.Values{"reason": {"unpaid"}}) + if rec := as(h, ac, http.MethodGet, "/market", nil); rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "suspended") { + t.Errorf("suspended: %d", rec.Code) + } + as(h, oc, http.MethodPost, "/platform/teams/"+id+"/restore", url.Values{}) + if rec := as(h, ac, http.MethodGet, "/market", nil); rec.Code != http.StatusOK { + t.Errorf("restored: %d", rec.Code) + } + + // View as: a reason, a while, read-only, and in the team's log. + if rec := as(h, oc, http.MethodPost, "/platform/teams/"+id+"/view-as", url.Values{"minutes": {"10"}}); !strings.Contains(rec.Header().Get("Location"), "view-needs-reason") { + t.Error("viewed without a reason") + } + as(h, oc, http.MethodPost, "/platform/teams/"+id+"/view-as", url.Values{"reason": {"ticket 42"}, "minutes": {"600"}}) + body = as(h, oc, http.MethodGet, "/market", nil).Body.String() + if !strings.Contains(body, "Rival") || !strings.Contains(body, "Viewing this team as the platform") || !strings.Contains(body, "ticket 42") { + t.Errorf("view as: %s", body) + } + if rec := as(h, oc, http.MethodPost, "/market/save", url.Values{"name": {"X"}, "relationship": {"partner"}}); rec.Code != http.StatusForbidden { + t.Errorf("changed while viewing: %d", rec.Code) + } + if rec := as(h, oc, http.MethodGet, "/settings/profile", nil); rec.Code != http.StatusForbidden { + t.Errorf("Settings while viewing: %d", rec.Code) + } + ts, _ := s.forTeam(a.ID) + entries, _ := audit.List(ts.DB, audit.Filter{Action: "viewed-as"}, 5) + if len(entries) != 1 || !strings.Contains(entries[0].Detail, "ticket 42 (for 60 minutes)") || !strings.Contains(entries[0].UserName, "platform") { + t.Errorf("team's log: %+v", entries) + } + // It runs out. + sess, _, _ := users.Lookup(s.platform(), oc.Value, time.Now()) + users.ViewAs(s.platform(), sess.ID, a.ID, time.Now().Add(-time.Minute), "ticket 42") + if rec := as(h, oc, http.MethodGet, "/market", nil); rec.Header().Get("Location") != "/platform" { + t.Errorf("after the time: %d", rec.Code) + } +} diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index 4b5d9c4..f41e5c9 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -41,6 +41,7 @@
+ {{with .Viewer}}{{if .Viewing}}

Viewing this team as the platform's admin, read-only, until {{.Session.ViewUntil.Local.Format "15:04"}}: {{.Session.ViewReason}}

+
{{end}}{{end}} {{if .Flash}}

{{.Flash}}

{{end}} {{if .Error}}{{end}} {{template "content" .}} diff --git a/internal/web/templates/platform.html b/internal/web/templates/platform.html new file mode 100644 index 0000000..1e5021f --- /dev/null +++ b/internal/web/templates/platform.html @@ -0,0 +1,30 @@ +{{define "content"}}{{with .Data}} +

Platform

+

The teams on this Supermarket, and how they're doing. You don't see a team's data: to look, view as it, with a reason, for a while; it's recorded in the team's own log.

+{{if .Need2FA}} +

The platform's admin pages need two-factor sign-in. Turn it on, then come back.

+{{else}} +
+ + + {{range .Teams}} + + + + + + + + {{else}}{{end}} +
TeamDomainPeopleDataLast weekLast active
{{.Name}} {{if ne .Status "active"}}{{.Status}}{{end}}
since {{.Created.Local.Format "2 Jan 2006"}}{{with .Err}}
{{.}}{{end}}
{{.Domain}} {{if .Proved}}proved{{else}}not proved{{end}}{{.Members}}{{if .Invited}} ({{.Invited}} invited){{end}}{{bytes .Bytes}}{{if or .FailedPosts .FailedEmails .FailedRequests}}{{with .FailedPosts}}{{.}} posts failed. {{end}}{{with .FailedEmails}}{{.}} emails failed. {{end}}{{with .FailedRequests}}{{.}} agent requests failed.{{end}}{{else}}nothing failed{{end}}{{ago .LastActivity}}
Act +
+ {{if eq .Status "active"}}
+ {{else}}
{{end}} + {{if .Invited}}
{{end}} + {{if .Proved}}
{{end}} +
min
+
+
No teams yet.
+
+{{end}} +{{end}}{{end}} diff --git a/internal/web/templates/team-closed.html b/internal/web/templates/team-closed.html new file mode 100644 index 0000000..c52d21a --- /dev/null +++ b/internal/web/templates/team-closed.html @@ -0,0 +1,8 @@ +{{define "content"}}{{with .Data}} +

{{.Name}} is {{.Status}}

+
+ {{if eq .Status "suspended"}}

The people running Supermarket have suspended this team. Its data is kept, and its work waits. Ask them why, or for it to be restored.

+ {{else}}

This team is being deleted. Its owner can still undo it, until {{.DeleteAt.Local.Format "2 Jan 2006"}}.

{{end}} +

Your account ·

+
+{{end}}{{end}}