feat(api): enforce roles, org sign-in policies, invitations and api tokens

Every org route resolves a principal from the session or a bearer token
and checks a permission. Nobody can grant, revoke or remove more than
they hold. Tokens are capped by their owner's current rights and cannot
manage credentials. Orgs can require TOTP or SSO; the owner keeps a
password fallback for SSO.

Closes #6
Closes #7
Closes #8
Closes #9
Closes #41
Closes #45

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-22 00:49:35 +01:00
1 parent 30409697f7
commit d7d4821e3e
24 files changed
+4677 -439

No files matched your search

+211
View File
@@ -0,0 +1,211 @@
package api_test
import (
"net/http"
"strings"
"testing"
"time"
"github.com/pquerna/otp/totp"
)
const password = "correct horse battery"
// invite creates an invitation from b and returns its token.
func (b *browser) invite(email, roleID string) string {
b.t.Helper()
st, body := b.do("POST", "/api/v1/org/invitations", map[string]any{"email": email, "role_id": roleID})
if st != http.StatusCreated {
b.t.Fatalf("invite(%s) = %d %v, want 201", email, st, body)
}
u := body["url"].(string)
return u[strings.LastIndex(u, "/")+1:]
}
// joinVia signs up a new account through an invitation.
func (e *env) joinVia(t *testing.T, tok string) *browser {
t.Helper()
b := e.browser(t)
st, body := b.do("POST", "/api/v1/invitations/"+tok+"/signup", map[string]any{"password": password})
if st != http.StatusOK {
t.Fatalf("invite signup = %d %v, want 200", st, body)
}
return b
}
func (b *browser) roleID(key string) string {
b.t.Helper()
_, body := b.do("GET", "/api/v1/org/roles", nil)
for _, r := range body["roles"].([]any) {
r := r.(map[string]any)
if r["key"] == key || r["name"] == key {
return r["id"].(string)
}
}
b.t.Fatalf("role %q not found in %v", key, body)
return ""
}
func (b *browser) userID(email string) string {
b.t.Helper()
_, body := b.do("GET", "/api/v1/org/members", nil)
for _, m := range body["members"].([]any) {
m := m.(map[string]any)
if m["email"] == email {
return m["user_id"].(string)
}
}
b.t.Fatalf("member %q not found", email)
return ""
}
func expect(t *testing.T, what string, st int, body map[string]any, wantStatus int, wantCode string) {
t.Helper()
if st != wantStatus || (wantCode != "" && body["error"] != wantCode) {
t.Errorf("%s = %d %v, want %d %s", what, st, body["error"], wantStatus, wantCode)
}
}
func TestPermissions(t *testing.T) {
e := newEnv(t)
domain := uniq("p") + ".test"
owner := e.browser(t)
owner.signup("owner@"+domain, uniq("perm-"))
editorTok := owner.invite("editor@"+domain, owner.roleID("editor"))
editor := e.joinVia(t, editorTok)
t.Run("invitation works once", func(t *testing.T) {
st, body := e.browser(t).do("POST", "/api/v1/invitations/"+editorTok+"/signup", map[string]any{"password": password})
expect(t, "second use", st, body, http.StatusGone, "invitation_invalid")
})
t.Run("editor permissions", func(t *testing.T) {
st, body := editor.do("GET", "/api/v1/org/members", nil)
expect(t, "editor GET members", st, body, http.StatusOK, "")
st, body = editor.do("GET", "/api/v1/org/sso", nil)
expect(t, "editor GET sso", st, body, http.StatusForbidden, "forbidden")
st, body = editor.do("POST", "/api/v1/org/invitations", map[string]any{"email": "x@" + domain, "role_id": owner.roleID("viewer")})
expect(t, "editor invite", st, body, http.StatusForbidden, "forbidden")
})
// A delegated people manager may only hand out what they hold.
st, body := owner.do("POST", "/api/v1/org/roles", map[string]any{"name": "People", "permissions": []string{"members.manage"}})
expect(t, "create role", st, body, http.StatusCreated, "")
st, body = owner.do("POST", "/api/v1/org/roles", map[string]any{"name": "Readers", "permissions": []string{"members.read"}})
expect(t, "create role", st, body, http.StatusCreated, "")
manager := e.joinVia(t, owner.invite("manager@"+domain, owner.roleID("People")))
t.Run("no escalation through delegation", func(t *testing.T) {
editorID := owner.userID("editor@" + domain)
st, body := manager.do("POST", "/api/v1/org/members/"+editorID+"/roles", map[string]any{"role_id": owner.roleID("admin")})
expect(t, "manager assigns admin", st, body, http.StatusForbidden, "permission_escalation")
st, body = manager.do("POST", "/api/v1/org/members/"+editorID+"/roles", map[string]any{"role_id": owner.roleID("Readers")})
expect(t, "manager assigns readers", st, body, http.StatusCreated, "")
st, body = manager.do("DELETE", "/api/v1/org/members/"+editorID, nil)
expect(t, "manager removes stronger editor", st, body, http.StatusForbidden, "permission_escalation")
st, body = manager.do("DELETE", "/api/v1/org/members/"+owner.userID("owner@"+domain), nil)
expect(t, "manager removes owner", st, body, http.StatusForbidden, "owner_cannot_be_removed")
st, body = manager.do("POST", "/api/v1/org/invitations", map[string]any{"email": "y@" + domain, "role_id": owner.roleID("editor")})
expect(t, "manager invites editor", st, body, http.StatusForbidden, "permission_escalation")
st, body = manager.do("POST", "/api/v1/org/roles", map[string]any{"name": "Sneaky", "permissions": []string{"org.manage"}})
expect(t, "manager creates role", st, body, http.StatusForbidden, "forbidden")
})
t.Run("settings pages", func(t *testing.T) {
pages := []string{"/settings/members", "/settings/roles", "/settings/tokens", "/settings/org", "/settings/sso", "/settings/security", "/"}
for _, path := range pages {
if got := owner.visit(path); got.Path != path {
t.Errorf("owner GET %s ended at %s", path, got.Path)
}
}
for path, want := range map[string]string{"/settings/sso": "/", "/settings/org": "/", "/settings/members": "/settings/members", "/settings/tokens": "/settings/tokens"} {
if got := editor.visit(path); got.Path != want {
t.Errorf("editor GET %s ended at %s, want %s", path, got.Path, want)
}
}
})
t.Run("built-in roles are read-only", func(t *testing.T) {
st, body := owner.do("PUT", "/api/v1/org/roles/"+owner.roleID("viewer"), map[string]any{"name": "Viewer", "permissions": []string{"org.manage"}})
expect(t, "update built-in", st, body, http.StatusConflict, "role_built_in")
st, body = owner.do("DELETE", "/api/v1/org/roles/"+owner.roleID("People"), nil)
expect(t, "delete role in use", st, body, http.StatusConflict, "role_in_use")
})
t.Run("api tokens follow their owner", func(t *testing.T) {
st, body := editor.do("POST", "/api/v1/org/tokens", map[string]any{"name": "too much", "permissions": []string{"org.manage"}})
expect(t, "token beyond own rights", st, body, http.StatusForbidden, "permission_escalation")
st, body = editor.do("POST", "/api/v1/org/tokens", map[string]any{"name": "ci", "permissions": []string{"members.read", "monitors.write"}, "expires_in_days": 30})
expect(t, "create token", st, body, http.StatusCreated, "")
api := &browser{t: t, base: editor.base, hc: e.srv.Client(), bearer: body["token"].(string)}
st, body = api.do("GET", "/api/v1/org/members", nil)
expect(t, "token GET members", st, body, http.StatusOK, "")
st, body = api.do("GET", "/api/v1/org/sso", nil)
expect(t, "token GET sso", st, body, http.StatusForbidden, "forbidden")
st, body = api.do("POST", "/api/v1/org/tokens", map[string]any{"name": "child", "permissions": []string{"members.read"}})
expect(t, "token mints token", st, body, http.StatusForbidden, "session_required")
// Losing the role that granted members.read removes it from the token.
editorID := owner.userID("editor@" + domain)
_, members := owner.do("GET", "/api/v1/org/members", nil)
for _, m := range members["members"].([]any) {
m := m.(map[string]any)
if m["user_id"] != editorID {
continue
}
for _, a := range m["assignments"].([]any) {
owner.do("DELETE", "/api/v1/org/assignments/"+a.(map[string]any)["id"].(string), nil)
}
}
st, body = api.do("GET", "/api/v1/org/members", nil)
expect(t, "token after role removal", st, body, http.StatusForbidden, "forbidden")
st, body = owner.do("DELETE", "/api/v1/org/members/"+editorID, nil)
expect(t, "owner removes editor", st, body, http.StatusNoContent, "")
st, body = api.do("GET", "/api/v1/org/members", nil)
expect(t, "token after removal", st, body, http.StatusUnauthorized, "unauthenticated")
st, _ = editor.do("GET", "/api/v1/me", nil)
if st != http.StatusUnauthorized {
t.Errorf("removed member's session GET /me = %d, want 401", st)
}
})
t.Run("org policies", func(t *testing.T) {
st, body := owner.do("PUT", "/api/v1/org/policy", map[string]any{"require_sso": true})
expect(t, "require sso without provider", st, body, http.StatusConflict, "sso_no_provider")
st, body = owner.do("PUT", "/api/v1/org/policy", map[string]any{"require_totp": true})
expect(t, "require totp without own totp", st, body, http.StatusConflict, "policy_would_lock_you_out")
owner.enableTOTP()
st, body = owner.do("PUT", "/api/v1/org/policy", map[string]any{"require_totp": true})
expect(t, "require totp", st, body, http.StatusOK, "")
st, body = manager.do("GET", "/api/v1/org/members", nil)
expect(t, "password-only member", st, body, http.StatusForbidden, "totp_required_by_org")
// The manager enables TOTP in the current session and is let in.
_, setup := manager.do("POST", "/api/v1/me/totp/setup", nil)
code, _ := totp.GenerateCode(setup["secret"].(string), time.Now())
manager.do("POST", "/api/v1/me/totp/enable", map[string]any{"code": code})
st, body = manager.do("GET", "/api/v1/org/members", nil)
expect(t, "member after enabling totp", st, body, http.StatusOK, "")
})
t.Run("invitation for another address", func(t *testing.T) {
tok := owner.invite("someone@"+domain, owner.roleID("viewer"))
st, body := manager.do("POST", "/api/v1/invitations/"+tok+"/accept", nil)
expect(t, "accept as other user", st, body, http.StatusForbidden, "invitation_email_mismatch")
})
t.Run("custom roles stay in their org", func(t *testing.T) {
other := e.browser(t)
other.signup("x@"+uniq("o")+".test", uniq("other-"))
_, body := other.do("GET", "/api/v1/org/roles", nil)
for _, r := range body["roles"].([]any) {
if name := r.(map[string]any)["name"]; name == "People" || name == "Readers" {
t.Errorf("other org sees custom role %v", name)
}
}
})
}