Files
sharangandSharang Parnerkar 99214c088b
ci / shared (push) Successful in 13s
ci / test (push) Successful in 22m21s
ci / image (push) Successful in 25s
feat(members): tenant organization members, invites, admin email (#28)
Demonstration plan, phase D1 (registry side). The portal's Settings/Users page renders design fixtures today and its "Invite member" button posts to a route that does not exist, because the registry had no membership surface.

**`GET /v1/tenants/{id}/members`** lists the tenant's Keycloak organization members — user id, email, first/last name, `org_roles`, `enabled`, `created_at`. A tenant whose organization was never created (sales-led) answers an empty list rather than an error.

**`POST /v1/tenants/{id}/invites`** `{email, first_name?, last_name?, role?}` creates the Keycloak user if missing, adds the organization member (KC 26: the member body is the bare user id), writes the tenant-context user attributes, sends the same execute-actions mail the first admin gets, and audits `user.invited` with the caller as actor. Idempotent: an existing member answers `200 {status:"member"}` and sends no mail; a new one `202 {status:"invited"}`.

**Scope.** A user token may only touch its own tenant — another tenant's id is a 404, never a hint that it exists. Inviting needs the `IT_ADMIN` or `OWNER` org role, so `Principal` now carries the `org_roles` claim and `IsTenantAdmin()`. Service clients stay gated by `AUTHZ_RULES` route groups: members on `tenants.read`, invites on `tenants.write`.

**`admin_email` on the tenant** (migration `0006`, backfilled from the `keycloak.invite_sent` audit trail, and from `keycloak.provision_failed` metadata where the first invite failed) so Settings can show a real contact instead of an em dash. The first `IT_ADMIN`/`OWNER` invite fills it in when it was empty.

**Routing note worth keeping:** `GET /v1/tenants/{id}/members` cannot be registered — Go's ServeMux calls it a conflict with `GET /v1/tenants/by-slug/{slug}`, since both match `/v1/tenants/by-slug/members` and neither pattern is more specific. It is registered as `GET /v1/tenants/{id}/{sub}` instead, which *is* less specific than the by-slug lookup, so the two coexist; anything but `members` answers 404.

`openapi.yaml` documents both endpoints, the `OrgMember`/`Invite` schemas, `admin_email` and a `Forbidden` response.

Verified locally: `go vet ./...`, `gofmt` clean, `go test ./...` green, CI coverage command at **74.3%** (gate 70%).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Reviewed-on: #28
2026-09-14 08:27:12 +00:00

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)
}
}