Files
Sebastian UnterschützandClaude Opus 5.5 db3ff19983
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 9m19s
ci / test (pull_request) Successful in 9m25s
ci / build (pull_request) Successful in 15m40s
ci / image (pull_request) Successful in 4m26s
feat: several owners per organization, and handing ownership over
An organization may now have several owners; the unique index allowing
only one is gone. Owners make members owners or take it back, their own
included, through PUT /api/v1/org/members/:user/owner; handing an
organization over is making someone else owner and stepping down. The
last owner cannot step down, and changes serialize on a per-organization
lock so two owners stepping down at once cannot leave none. A former
owner without roles keeps working as Admin. Owners still cannot be
removed while they are owners.

Deleting an account now takes along only the organizations it is the
last owner of, counted under the same lock; it just leaves those with
further owners. The members page offers "Make owner", "Remove as owner"
and "Step down as owner" to owners.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 22:38:04 +01:00

293 lines
11 KiB
Go

package api_test
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"os/exec"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
// download fetches path and returns status, content type and body.
func (b *browser) download(path string) (int, string, []byte) {
b.t.Helper()
resp, err := b.hc.Get(b.base + path)
if err != nil {
b.t.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
raw, _ := io.ReadAll(resp.Body)
return resp.StatusCode, resp.Header.Get("Content-Type"), raw
}
func pdfText(t *testing.T, raw []byte) string {
t.Helper()
if !bytes.HasPrefix(raw, []byte("%PDF-")) {
t.Fatalf("not a PDF: %.40q", raw)
}
if _, err := exec.LookPath("pdftotext"); err != nil {
return ""
}
cmd := exec.Command("pdftotext", "-", "-")
cmd.Stdin = bytes.NewReader(raw)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("pdftotext: %v\n%s", err, out)
}
return string(out)
}
func TestExports(t *testing.T) {
e := newEnv(t)
_, region := e.platformChecker(t, uniq("eu-"))
owner := e.browser(t)
email := "jörg@" + uniq("ex") + ".test"
owner.signup(email, uniq("ex-"))
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "Shop", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region},
})
if st != http.StatusCreated {
t.Fatal(body)
}
_, ch := owner.do("POST", "/api/v1/org/channels", map[string]any{"name": "Hook", "type": "webhook", "url": "https://hooks.example.com/x"})
signing := ch["signing_secret"].(string)
_, tok := owner.do("POST", "/api/v1/org/tokens", map[string]any{"name": "ci", "permissions": []string{"monitors.read"}})
token := tok["token"].(string)
st, ctype, raw := owner.download("/api/v1/me/export?format=json")
if st != http.StatusOK || !strings.HasPrefix(ctype, "application/json") {
t.Fatalf("account export = %d %s", st, ctype)
}
var acc map[string]any
if err := json.Unmarshal(raw, &acc); err != nil {
t.Fatal(err)
}
if acc["account"].(map[string]any)["email"] != email || len(acc["organizations"].([]any)) != 1 ||
len(acc["api_tokens"].([]any)) != 1 || len(acc["activity"].([]any)) == 0 {
t.Errorf("account export = %s", raw)
}
for _, secret := range []string{token, signing, "password_hash", "totp_secret", "token_hash"} {
if bytes.Contains(raw, []byte(secret)) {
t.Errorf("account export contains %q", secret)
}
}
st, ctype, raw = owner.download("/api/v1/me/export?format=pdf")
if st != http.StatusOK || ctype != "application/pdf" {
t.Fatalf("account PDF = %d %s", st, ctype)
}
if text := pdfText(t, raw); text != "" && !strings.Contains(text, email) {
t.Errorf("account PDF lacks the email address:\n%.500s", text)
}
st, _, raw = owner.download("/api/v1/org/export?format=json")
if st != http.StatusOK {
t.Fatalf("org export = %d", st)
}
var org map[string]any
if err := json.Unmarshal(raw, &org); err != nil {
t.Fatal(err)
}
groups := org["alert_groups"].([]any)
monitors := org["monitors"].([]any)
if len(groups) != 1 || len(monitors) != 1 {
t.Fatalf("export groups/monitors = %v/%v", groups, monitors)
}
group := groups[0].(map[string]any)
assigned := monitors[0].(map[string]any)["alert_group_ids"].([]any)
if group["is_default"] != true || len(group["channel_ids"].([]any)) != 1 || len(group["quiet_hours"].([]any)) != 0 || len(assigned) != 1 || assigned[0] != group["id"] {
t.Fatalf("export lost alert routing: group=%v assignments=%v", group, assigned)
}
if !bytes.Contains(raw, []byte(`"Shop"`)) || !bytes.Contains(raw, []byte(`"Hook"`)) {
t.Errorf("org export lacks monitor or channel")
}
for _, secret := range []string{token, signing, "client_secret", "domain_token"} {
if bytes.Contains(raw, []byte(secret)) {
t.Errorf("org export contains %q", secret)
}
}
_, _, raw = owner.download("/api/v1/org/export?format=pdf")
if text := pdfText(t, raw); text != "" && (!strings.Contains(text, "Shop") || !strings.Contains(text, "example.com:443")) {
t.Errorf("org PDF lacks the monitor:\n%.800s", text)
}
// Exports are recorded.
_, audit := owner.do("GET", "/api/v1/org/audit", nil)
if !strings.Contains(mustJSON(audit), "org.export") {
t.Error("org export is not in the audit log")
}
viewer := e.joinVia(t, owner.invite("v@"+uniq("ex")+".test", owner.roleID("viewer")))
if st, _, _ := viewer.download("/api/v1/org/export"); st != http.StatusForbidden {
t.Errorf("viewer org export = %d, want 403", st)
}
}
func mustJSON(v any) string {
raw, _ := json.Marshal(v)
return string(raw)
}
func (e *env) count(t *testing.T, query string, args ...any) int {
t.Helper()
var n int
if err := e.asSystem(t, func(tx pgx.Tx) error { return tx.QueryRow(context.Background(), query, args...).Scan(&n) }); err != nil {
t.Fatal(err)
}
return n
}
func (e *env) seedResults(t *testing.T, org, monitor uuid.UUID) {
t.Helper()
ctx := context.Background()
for h := 1; h <= 30; h++ {
if _, err := e.dbPool.Exec(ctx, `INSERT INTO check_results (time, org_id, monitor_id, region, checker_id, ok, latency_ms) VALUES ($1, $2, $3, 'eu', $4, true, 10)`,
time.Now().Add(-time.Duration(h)*time.Hour), org, monitor, uuid.New()); err != nil {
t.Fatal(err)
}
}
if _, err := e.dbPool.Exec(ctx, `CALL refresh_continuous_aggregate('check_results_1h', NULL, NULL)`); err != nil {
t.Fatal(err)
}
}
func TestDeleteOrganization(t *testing.T) {
e := newEnv(t)
_, region := e.platformChecker(t, uniq("eu-"))
owner := e.browser(t)
slug := uniq("del-")
owner.signup("o@"+uniq("d")+".test", slug)
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "M", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region},
})
org := uuid.MustParse(owner.orgID())
e.seedResults(t, org, uuid.MustParse(m["id"].(string)))
keep := e.browser(t)
keep.signup("k@"+uniq("d")+".test", uniq("keep-"))
_, km := keep.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "K", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region},
})
keepOrg := uuid.MustParse(keep.orgID())
e.seedResults(t, keepOrg, uuid.MustParse(km["id"].(string)))
admin := e.joinVia(t, owner.invite("a@"+uniq("d")+".test", owner.roleID("admin")))
if st, body := admin.do("POST", "/api/v1/org/delete", map[string]any{"slug": slug, "password": password}); st != http.StatusForbidden {
t.Errorf("admin deletes org = %d %v, want 403", st, body)
}
if st, _ := owner.do("POST", "/api/v1/org/delete", map[string]any{"slug": "wrong", "password": password}); st != http.StatusForbidden {
t.Errorf("wrong slug = %d, want 403", st)
}
if st, _ := owner.do("POST", "/api/v1/org/delete", map[string]any{"slug": slug, "password": "wrong password"}); st != http.StatusForbidden {
t.Errorf("wrong password = %d, want 403", st)
}
if st, body := owner.do("POST", "/api/v1/org/delete", map[string]any{"slug": slug, "password": password}); st != http.StatusOK {
t.Fatalf("owner deletes org = %d %v", st, body)
}
for query, want := range map[string]int{
`SELECT count(*) FROM orgs WHERE id = $1`: 0,
`SELECT count(*) FROM monitors WHERE org_id = $1`: 0,
`SELECT count(*) FROM check_results WHERE org_id = $1`: 0,
`SELECT count(*) FROM check_results_1h WHERE org_id = $1`: 0,
`SELECT count(*) FROM audit_events WHERE org_id = $1`: 0,
} {
if got := e.count(t, query, org); got != want {
t.Errorf("%s = %d, want %d", query, got, want)
}
}
if e.count(t, `SELECT count(*) FROM check_results_1h WHERE org_id = $1`, keepOrg) == 0 {
t.Error("another organization's aggregates were deleted")
}
if e.count(t, `SELECT count(*) FROM audit_events WHERE action = 'org.delete' AND details->>'slug' = $1`, slug) != 1 {
t.Error("deletion is not in the platform log")
}
// Former members keep working accounts without the organization.
for _, b := range []*browser{owner, admin} {
if st, _, _ := b.page("/"); st != http.StatusOK {
t.Errorf("console after deletion = %d", st)
}
if st, me := b.do("GET", "/api/v1/me", nil); st != http.StatusOK || len(me["orgs"].([]any)) != 0 {
t.Errorf("GET /me after deletion = %d %v", st, me)
}
}
}
func TestDeleteAccount(t *testing.T) {
e := newEnv(t)
owner := e.browser(t)
owner.signup("o@"+uniq("da")+".test", uniq("da-"))
memberEmail := "m@" + uniq("da") + ".test"
member := e.joinVia(t, owner.invite(memberEmail, owner.roleID("admin")))
memberID := member.userIDSelf()
member.do("POST", "/api/v1/org/groups", map[string]any{"name": "By member"})
if st, _ := member.do("POST", "/api/v1/me/delete", map[string]any{"password": "wrong password"}); st != http.StatusForbidden {
t.Errorf("wrong password = %d, want 403", st)
}
if st, body := member.do("POST", "/api/v1/me/delete", map[string]any{"password": password}); st != http.StatusOK {
t.Fatalf("member deletes account = %d %v", st, body)
}
if st, _ := member.do("GET", "/api/v1/me", nil); st != http.StatusUnauthorized {
t.Errorf("old session after deletion = %d, want 401", st)
}
for query, want := range map[string]int{
`SELECT count(*) FROM users WHERE id = $1`: 0,
`SELECT count(*) FROM audit_events WHERE actor_user_id = $1`: 0,
`SELECT count(*) FROM audit_events WHERE details::text LIKE '%' || $1::text || '%'`: 0,
} {
arg := any(memberID)
if strings.Contains(query, "LIKE") {
arg = memberEmail
}
if got := e.count(t, query, arg); got != want {
t.Errorf("%s = %d, want %d", query, got, want)
}
}
if st, _ := e.browser(t).do("POST", "/api/v1/auth/login", map[string]any{"email": memberEmail, "password": password}); st != http.StatusUnauthorized {
t.Errorf("login after deletion = %d, want 401", st)
}
// The organization's log still shows what happened, by a deleted user.
_, _, html := owner.page("/settings/audit")
if !strings.Contains(html, "By member") || !strings.Contains(html, "Deleted user") {
t.Error("audit page lacks the group created by the deleted member")
}
// A sole owner's organization goes with the account.
solo := e.browser(t)
solo.signup("s@"+uniq("da")+".test", uniq("solo-"))
soloOrg := uuid.MustParse(solo.orgID())
if st, body := solo.do("POST", "/api/v1/me/delete", map[string]any{"password": password}); st != http.StatusOK {
t.Fatalf("sole owner deletes account = %d %v", st, body)
}
if e.count(t, `SELECT count(*) FROM orgs WHERE id = $1`, soloOrg) != 0 {
t.Error("sole owner's organization survived")
}
// The owner takes the organization along, monitors and all, even when
// others still belong to it; the security page says so first.
org := uuid.MustParse(owner.orgID())
owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "web", "type": "heartbeat", "interval_seconds": 3600})
other := e.joinVia(t, owner.invite("x@"+uniq("da")+".test", owner.roleID("viewer")))
if _, _, html := owner.page("/settings/security"); !strings.Contains(html, "You are the last owner of these organizations") {
t.Error("the security page does not warn that the organization goes with the account")
}
if st, body := owner.do("POST", "/api/v1/me/delete", map[string]any{"password": password}); st != http.StatusOK {
t.Fatalf("last owner deletes account = %d %v", st, body)
}
for _, q := range []string{`SELECT count(*) FROM orgs WHERE id = $1`, `SELECT count(*) FROM monitors WHERE org_id = $1`} {
if n := e.count(t, q, org); n != 0 {
t.Errorf("%s = %d after the last owner left", q, n)
}
}
if st, me := other.do("GET", "/api/v1/me", nil); st != http.StatusOK || len(me["orgs"].([]any)) != 0 {
t.Errorf("remaining member = %d %v, want an account without the organization", st, me)
}
}