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
226 lines
8.7 KiB
Go
226 lines
8.7 KiB
Go
package server_test
|
|
|
|
import (
|
|
"net/http"
|
|
"testing"
|
|
|
|
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
|
)
|
|
|
|
type membersBody struct {
|
|
Members []keycloak.OrgMember `json:"members"`
|
|
}
|
|
|
|
type inviteBody struct {
|
|
UserID string `json:"user_id"`
|
|
Email string `json:"email"`
|
|
Status string `json:"status"`
|
|
}
|
|
|
|
func TestListTenantMembers(t *testing.T) {
|
|
eachStore(t, func(t *testing.T, h *testHarness) {
|
|
h.kcMock.Members["acme"] = []keycloak.OrgMember{
|
|
{UserID: "u-1", Email: "ada@acme.test", FirstName: "Ada", LastName: "Admin", OrgRoles: []string{"IT_ADMIN"}, Enabled: true},
|
|
}
|
|
resp, raw := h.do(http.MethodGet, "/v1/tenants/"+h.tenant.ID+"/members", nil)
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("status %d: %s", resp.StatusCode, raw)
|
|
}
|
|
body := decode[membersBody](t, raw)
|
|
if len(body.Members) != 1 || body.Members[0].Email != "ada@acme.test" || body.Members[0].OrgRoles[0] != "IT_ADMIN" {
|
|
t.Fatalf("unexpected body: %s", raw)
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestListTenantMembers_noOrgIsEmpty(t *testing.T) {
|
|
eachStore(t, func(t *testing.T, h *testHarness) {
|
|
resp, raw := h.do(http.MethodGet, "/v1/tenants/"+h.tenant.ID+"/members", nil)
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("status %d: %s", resp.StatusCode, raw)
|
|
}
|
|
if body := decode[membersBody](t, raw); body.Members == nil || len(body.Members) != 0 {
|
|
t.Fatalf("want empty members array, got %s", raw)
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestListTenantMembers_errors(t *testing.T) {
|
|
eachStore(t, func(t *testing.T, h *testHarness) {
|
|
resp, _ := h.do(http.MethodGet, "/v1/tenants/00000000-0000-0000-0000-0000000000ff/members", nil)
|
|
if resp.StatusCode != http.StatusNotFound {
|
|
t.Fatalf("unknown tenant: %d", resp.StatusCode)
|
|
}
|
|
h.kcMock.Members["acme"] = []keycloak.OrgMember{}
|
|
h.kcMock.FailNext = keycloak.ErrUnavailable
|
|
resp, raw := h.do(http.MethodGet, "/v1/tenants/"+h.tenant.ID+"/members", nil)
|
|
if resp.StatusCode != http.StatusServiceUnavailable {
|
|
t.Fatalf("kc down: %d %s", resp.StatusCode, raw)
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestInviteTenantMember(t *testing.T) {
|
|
eachStore(t, func(t *testing.T, h *testHarness) {
|
|
h.kcMock.Members["acme"] = []keycloak.OrgMember{}
|
|
resp, raw := h.do(http.MethodPost, "/v1/tenants/"+h.tenant.ID+"/invites", map[string]any{
|
|
"email": " Bob@Acme.test ", "first_name": "Bob", "last_name": "Builder",
|
|
})
|
|
if resp.StatusCode != http.StatusAccepted {
|
|
t.Fatalf("status %d: %s", resp.StatusCode, raw)
|
|
}
|
|
out := decode[inviteBody](t, raw)
|
|
if out.Status != "invited" || out.Email != "bob@acme.test" || out.UserID == "" {
|
|
t.Fatalf("unexpected body: %s", raw)
|
|
}
|
|
if len(h.kcMock.Invites) != 1 {
|
|
t.Fatalf("want one KC invite, got %d", len(h.kcMock.Invites))
|
|
}
|
|
inv := h.kcMock.Invites[0]
|
|
if inv.TenantID != h.tenant.ID || inv.Slug != "acme" || inv.TenantStatus != h.tenant.Status || inv.Role != "USER" || inv.FirstName != "Bob" {
|
|
t.Errorf("invite input: %+v", inv)
|
|
}
|
|
|
|
// Audit: user.invited, target = email.
|
|
_, araw := h.do(http.MethodGet, "/v1/audit?tenant_id="+h.tenant.ID+"&action=user.invited", nil)
|
|
audit := decode[struct {
|
|
Items []store.AuditEvent `json:"items"`
|
|
}](t, araw)
|
|
if len(audit.Items) != 1 || audit.Items[0].TargetID != "bob@acme.test" || audit.Items[0].TargetType != "user" {
|
|
t.Errorf("audit: %s", araw)
|
|
}
|
|
if audit.Items[0].Metadata["role"] != "USER" {
|
|
t.Errorf("audit role: %v", audit.Items[0].Metadata)
|
|
}
|
|
|
|
// Idempotent: second invite is a 200 member, no extra mail, no audit.
|
|
resp, raw = h.do(http.MethodPost, "/v1/tenants/"+h.tenant.ID+"/invites", map[string]any{"email": "bob@acme.test"})
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("repeat status %d: %s", resp.StatusCode, raw)
|
|
}
|
|
if out := decode[inviteBody](t, raw); out.Status != "member" {
|
|
t.Fatalf("repeat body: %s", raw)
|
|
}
|
|
if len(h.kcMock.Invites) != 1 {
|
|
t.Errorf("repeat invite must not send mail: %d", len(h.kcMock.Invites))
|
|
}
|
|
_, araw = h.do(http.MethodGet, "/v1/audit?tenant_id="+h.tenant.ID+"&action=user.invited", nil)
|
|
if n := len(decode[struct {
|
|
Items []store.AuditEvent `json:"items"`
|
|
}](t, araw).Items); n != 1 {
|
|
t.Errorf("repeat invite must not audit: %d", n)
|
|
}
|
|
|
|
// Members list now shows the invitee.
|
|
_, mraw := h.do(http.MethodGet, "/v1/tenants/"+h.tenant.ID+"/members", nil)
|
|
if m := decode[membersBody](t, mraw).Members; len(m) != 1 || m[0].Email != "bob@acme.test" {
|
|
t.Errorf("members after invite: %s", mraw)
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestInviteTenantMember_firstAdminSetsAdminEmail(t *testing.T) {
|
|
eachStore(t, func(t *testing.T, h *testHarness) {
|
|
h.kcMock.Members["acme"] = []keycloak.OrgMember{}
|
|
if h.tenant.AdminEmail != "" {
|
|
t.Fatalf("seed tenant must start without admin_email")
|
|
}
|
|
resp, raw := h.do(http.MethodPost, "/v1/tenants/"+h.tenant.ID+"/invites", map[string]any{"email": "owner@acme.test", "role": "owner"})
|
|
if resp.StatusCode != http.StatusAccepted {
|
|
t.Fatalf("status %d: %s", resp.StatusCode, raw)
|
|
}
|
|
_, traw := h.do(http.MethodGet, "/v1/tenants/"+h.tenant.ID, nil)
|
|
if tt := decode[store.Tenant](t, traw); tt.AdminEmail != "owner@acme.test" {
|
|
t.Fatalf("admin_email not recorded: %s", traw)
|
|
}
|
|
// A later admin does not displace the first.
|
|
h.do(http.MethodPost, "/v1/tenants/"+h.tenant.ID+"/invites", map[string]any{"email": "second@acme.test", "role": "IT_ADMIN"})
|
|
_, traw = h.do(http.MethodGet, "/v1/tenants/by-slug/acme", nil)
|
|
if tt := decode[store.Tenant](t, traw); tt.AdminEmail != "owner@acme.test" {
|
|
t.Fatalf("admin_email displaced: %s", traw)
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestInviteTenantMember_validation(t *testing.T) {
|
|
eachStore(t, func(t *testing.T, h *testHarness) {
|
|
h.kcMock.Members["acme"] = []keycloak.OrgMember{}
|
|
base := "/v1/tenants/" + h.tenant.ID + "/invites"
|
|
cases := []struct {
|
|
name string
|
|
body any
|
|
want int
|
|
code string
|
|
}{
|
|
{"bad json", "{", http.StatusBadRequest, "invalid_body"},
|
|
{"missing email", map[string]any{}, http.StatusBadRequest, "invalid_email"},
|
|
{"display-name email", map[string]any{"email": "Bob <bob@acme.test>"}, http.StatusBadRequest, "invalid_email"},
|
|
{"bad role", map[string]any{"email": "x@acme.test", "role": "not a role"}, http.StatusBadRequest, "invalid_role"},
|
|
{"long name", map[string]any{"email": "x@acme.test", "first_name": string(make([]byte, 101))}, http.StatusBadRequest, "invalid_name"},
|
|
}
|
|
for _, c := range cases {
|
|
var resp *http.Response
|
|
var raw []byte
|
|
if s, ok := c.body.(string); ok {
|
|
resp, raw = h.doRaw(http.MethodPost, base, s)
|
|
} else {
|
|
resp, raw = h.do(http.MethodPost, base, c.body)
|
|
}
|
|
if resp.StatusCode != c.want {
|
|
t.Errorf("%s: status %d: %s", c.name, resp.StatusCode, raw)
|
|
continue
|
|
}
|
|
if e := decode[struct {
|
|
Error string `json:"error"`
|
|
}](t, raw); e.Error != c.code {
|
|
t.Errorf("%s: error %q, want %q", c.name, e.Error, c.code)
|
|
}
|
|
}
|
|
if resp, _ := h.do(http.MethodPost, "/v1/tenants/00000000-0000-0000-0000-0000000000ff/invites", map[string]any{"email": "x@acme.test"}); resp.StatusCode != http.StatusNotFound {
|
|
t.Errorf("unknown tenant: %d", resp.StatusCode)
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestInviteTenantMember_keycloakErrors(t *testing.T) {
|
|
eachStore(t, func(t *testing.T, h *testHarness) {
|
|
// No org yet (sales-led tenant): the portal must invite the first
|
|
// admin through tenant creation.
|
|
resp, raw := h.do(http.MethodPost, "/v1/tenants/"+h.tenant.ID+"/invites", map[string]any{"email": "x@acme.test"})
|
|
if resp.StatusCode != http.StatusConflict {
|
|
t.Fatalf("no org: %d %s", resp.StatusCode, raw)
|
|
}
|
|
h.kcMock.Members["acme"] = []keycloak.OrgMember{}
|
|
h.kcMock.FailNext = keycloak.ErrUnauthorized
|
|
if resp, _ := h.do(http.MethodPost, "/v1/tenants/"+h.tenant.ID+"/invites", map[string]any{"email": "x@acme.test"}); resp.StatusCode != http.StatusServiceUnavailable {
|
|
t.Errorf("kc unauthorized: %d", resp.StatusCode)
|
|
}
|
|
h.kcMock.FailNext = errAny
|
|
if resp, _ := h.do(http.MethodPost, "/v1/tenants/"+h.tenant.ID+"/invites", map[string]any{"email": "x@acme.test"}); resp.StatusCode != http.StatusBadGateway {
|
|
t.Errorf("kc generic error: %d", resp.StatusCode)
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestCreateTenant_storesAdminEmail(t *testing.T) {
|
|
eachStore(t, func(t *testing.T, h *testHarness) {
|
|
resp, body := h.do("POST", "/v1/tenants", map[string]any{
|
|
"slug": "gamma-co", "name": "Gamma", "admin_email": "Root@Gamma.test", "admin_name": "Root User",
|
|
})
|
|
if resp.StatusCode != http.StatusCreated {
|
|
t.Fatalf("status = %d, body=%s", resp.StatusCode, body)
|
|
}
|
|
out := decode[struct {
|
|
Tenant *store.Tenant `json:"tenant"`
|
|
}](t, body)
|
|
if out.Tenant.AdminEmail != "root@gamma.test" {
|
|
t.Errorf("admin_email = %q", out.Tenant.AdminEmail)
|
|
}
|
|
_, traw := h.do("GET", "/v1/tenants/"+out.Tenant.ID, nil)
|
|
if tt := decode[store.Tenant](t, traw); tt.AdminEmail != "root@gamma.test" {
|
|
t.Errorf("admin_email not persisted: %s", traw)
|
|
}
|
|
})
|
|
}
|