The portal's Settings/Users page showed design fixtures because the
registry had no membership surface. Two endpoints close that:
- GET /v1/tenants/{id}/members lists the Keycloak organization members
(user id, email, name, org_roles, enabled). A tenant without an
organization answers an empty list, not an error.
- POST /v1/tenants/{id}/invites creates the user if needed, adds the org
member (KC 26: bare user id body), writes the tenant-context
attributes, sends the execute-actions mail and audits user.invited.
Idempotent: an existing member answers 200 with status=member.
User tokens are confined to their own tenant (cross-tenant is a 404) and
need IT_ADMIN or OWNER to invite; service clients are gated per route
group as before. Principal gains the org_roles claim for that check.
Tenants carry admin_email (migration 0006, backfilled from the invite
audit trail) so Settings can show a real contact instead of an em dash.
The members route is registered as GET /v1/tenants/{id}/{sub}: ServeMux
rejects /v1/tenants/{id}/members as conflicting with the by-slug lookup,
because both match /v1/tenants/by-slug/members and neither pattern is
more specific.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
137 lines
5.8 KiB
Go
137 lines
5.8 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
|
)
|
|
|
|
// scopedServer wires the real router (no authn verifier) and injects a
|
|
// principal into every request, so the handler-level tenant scope and
|
|
// org-role checks run exactly as they would behind requireAuth.
|
|
// rules, when non-empty, are parsed into s.Authz *before* the router is built:
|
|
// requireAuthz decides once, at construction, whether to enforce at all.
|
|
func scopedServer(t *testing.T, p *authn.Principal, rules ...string) (*Server, http.Handler, *store.Tenant) {
|
|
t.Helper()
|
|
mem := store.NewMemory()
|
|
tenant, _ := mem.GetTenantBySlug(context.Background(), "acme")
|
|
mock := keycloak.NewMock()
|
|
mock.Members["acme"] = []keycloak.OrgMember{{UserID: "u-1", Email: "ada@acme.test", OrgRoles: []string{"IT_ADMIN"}, Enabled: true}}
|
|
s := &Server{Log: slog.New(slog.NewTextHandler(io.Discard, nil)), Store: mem, Keycloak: mock}
|
|
if len(rules) > 0 && rules[0] != "" {
|
|
s.Authz = ParseAuthzRules(rules[0])
|
|
}
|
|
router := NewRouter(s)
|
|
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
router.ServeHTTP(w, r.WithContext(authn.WithPrincipal(r.Context(), p)))
|
|
})
|
|
return s, h, tenant
|
|
}
|
|
|
|
func TestMembers_userScope(t *testing.T) {
|
|
member := &authn.Principal{Subject: "u-9", ClientID: "portal", TenantID: "00000000-0000-0000-0000-000000000001", Email: "m@acme.test", OrgRoles: []string{"USER"}}
|
|
_, h, tenant := scopedServer(t, member)
|
|
|
|
rr := httptest.NewRecorder()
|
|
h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+tenant.ID+"/members", nil))
|
|
if rr.Code != http.StatusOK || !strings.Contains(rr.Body.String(), "ada@acme.test") {
|
|
t.Fatalf("own tenant members: %d %s", rr.Code, rr.Body.String())
|
|
}
|
|
|
|
// Another tenant: 404, never a hint that it exists.
|
|
other := &authn.Principal{Subject: "u-x", ClientID: "portal", TenantID: "11111111-1111-1111-1111-111111111111", OrgRoles: []string{"IT_ADMIN"}}
|
|
_, h2, _ := scopedServer(t, other)
|
|
rr = httptest.NewRecorder()
|
|
h2.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+tenant.ID+"/members", nil))
|
|
if rr.Code != http.StatusNotFound {
|
|
t.Fatalf("cross-tenant members: %d %s", rr.Code, rr.Body.String())
|
|
}
|
|
rr = httptest.NewRecorder()
|
|
h2.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/v1/tenants/"+tenant.ID+"/invites", strings.NewReader(`{"email":"x@acme.test"}`)))
|
|
if rr.Code != http.StatusNotFound {
|
|
t.Fatalf("cross-tenant invite: %d %s", rr.Code, rr.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestInvite_requiresTenantAdminRole(t *testing.T) {
|
|
tenantID := "00000000-0000-0000-0000-000000000001"
|
|
cases := []struct {
|
|
name string
|
|
roles []string
|
|
want int
|
|
}{
|
|
{"plain user", []string{"USER"}, http.StatusForbidden},
|
|
{"no roles", nil, http.StatusForbidden},
|
|
{"it admin", []string{"IT_ADMIN"}, http.StatusAccepted},
|
|
{"owner", []string{"USER", "OWNER"}, http.StatusAccepted},
|
|
}
|
|
for _, c := range cases {
|
|
t.Run(c.name, func(t *testing.T) {
|
|
p := &authn.Principal{Subject: "u-" + c.name, ClientID: "portal", TenantID: tenantID, Email: "caller@acme.test", OrgRoles: c.roles}
|
|
s, h, tenant := scopedServer(t, p)
|
|
rr := httptest.NewRecorder()
|
|
h.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/v1/tenants/"+tenant.ID+"/invites", strings.NewReader(`{"email":"new@acme.test","role":"USER"}`)))
|
|
if rr.Code != c.want {
|
|
t.Fatalf("status %d, want %d: %s", rr.Code, c.want, rr.Body.String())
|
|
}
|
|
if c.want != http.StatusAccepted {
|
|
if !strings.Contains(rr.Body.String(), "FORBIDDEN_ROLE") {
|
|
t.Errorf("error code: %s", rr.Body.String())
|
|
}
|
|
return
|
|
}
|
|
// Actor is the caller.
|
|
items, _, _ := s.Store.ListAudit(context.Background(), store.AuditFilter{TenantID: tenant.ID, Action: "user.invited"})
|
|
if len(items) != 1 || items[0].ActorID != p.Subject || items[0].ActorName != "caller@acme.test" || items[0].ActorType != "user" {
|
|
t.Errorf("audit actor: %+v", items)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestInvite_serviceClientBypassesRoleCheck(t *testing.T) {
|
|
const rules = "portal-svc-stage:tenants;pruefwerk-svc-stage:tenants.read"
|
|
svc := &authn.Principal{Subject: "svc", ClientID: "portal-svc-stage"}
|
|
s, h, tenant := scopedServer(t, svc, rules)
|
|
rr := httptest.NewRecorder()
|
|
h.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/v1/tenants/"+tenant.ID+"/invites", strings.NewReader(`{"email":"svc-invited@acme.test"}`)))
|
|
if rr.Code != http.StatusAccepted {
|
|
t.Fatalf("service invite: %d %s", rr.Code, rr.Body.String())
|
|
}
|
|
items, _, _ := s.Store.ListAudit(context.Background(), store.AuditFilter{TenantID: tenant.ID, Action: "user.invited"})
|
|
if len(items) != 1 || items[0].ActorType != "service" || items[0].ActorID != "svc" {
|
|
t.Errorf("audit actor: %+v", items)
|
|
}
|
|
|
|
// A read-only client may list members but not invite.
|
|
ro := &authn.Principal{Subject: "svc2", ClientID: "pruefwerk-svc-stage"}
|
|
_, h2, _ := scopedServer(t, ro, rules)
|
|
rr = httptest.NewRecorder()
|
|
h2.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+tenant.ID+"/members", nil))
|
|
if rr.Code != http.StatusOK {
|
|
t.Errorf("read client members: %d %s", rr.Code, rr.Body.String())
|
|
}
|
|
rr = httptest.NewRecorder()
|
|
h2.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/v1/tenants/"+tenant.ID+"/invites", strings.NewReader(`{"email":"x@acme.test"}`)))
|
|
if rr.Code != http.StatusForbidden || !strings.Contains(rr.Body.String(), "FORBIDDEN_CLIENT") {
|
|
t.Errorf("read client invite: %d %s", rr.Code, rr.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestRouteGroup_members(t *testing.T) {
|
|
if g := routeGroup(http.MethodGet, "/v1/tenants/x/members"); g != "tenants.read" {
|
|
t.Errorf("members group %q", g)
|
|
}
|
|
if g := routeGroup(http.MethodPost, "/v1/tenants/x/invites"); g != "tenants.write" {
|
|
t.Errorf("invites group %q", g)
|
|
}
|
|
}
|