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
130 lines
4.7 KiB
Go
130 lines
4.7 KiB
Go
package keycloak
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
// stubStatusKC models the org → members → user attribute round-trip that
|
|
// SyncTenantStatus performs. `puts` collects the attribute payloads.
|
|
func stubStatusKC(t *testing.T, orgs map[string]string, members map[string][]string, users map[string]userRepresentation, puts map[string]map[string][]string, failUser string) *httptest.Server {
|
|
t.Helper()
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("/realms/test-realm/protocol/openid-connect/token", func(w http.ResponseWriter, _ *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"access_token": "test-token", "expires_in": 60})
|
|
})
|
|
mux.HandleFunc("GET /admin/realms/test-realm/organizations", func(w http.ResponseWriter, r *http.Request) {
|
|
alias := r.URL.Query().Get("search")
|
|
out := []map[string]string{}
|
|
if id, ok := orgs[alias]; ok {
|
|
out = append(out, map[string]string{"id": id, "alias": alias})
|
|
}
|
|
_ = json.NewEncoder(w).Encode(out)
|
|
})
|
|
mux.HandleFunc("GET /admin/realms/test-realm/organizations/{id}/members", func(w http.ResponseWriter, r *http.Request) {
|
|
out := []map[string]string{}
|
|
for _, m := range members[r.PathValue("id")] {
|
|
out = append(out, map[string]string{"id": m})
|
|
}
|
|
_ = json.NewEncoder(w).Encode(out)
|
|
})
|
|
mux.HandleFunc("GET /admin/realms/test-realm/users/{id}", func(w http.ResponseWriter, r *http.Request) {
|
|
u, ok := users[r.PathValue("id")]
|
|
if !ok {
|
|
w.WriteHeader(http.StatusNotFound)
|
|
return
|
|
}
|
|
_ = json.NewEncoder(w).Encode(u)
|
|
})
|
|
mux.HandleFunc("PUT /admin/realms/test-realm/users/{id}", func(w http.ResponseWriter, r *http.Request) {
|
|
if r.PathValue("id") == failUser {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
_, _ = w.Write([]byte("boom"))
|
|
return
|
|
}
|
|
var body struct {
|
|
Attributes map[string][]string `json:"attributes"`
|
|
}
|
|
_ = json.NewDecoder(r.Body).Decode(&body)
|
|
puts[r.PathValue("id")] = body.Attributes
|
|
w.WriteHeader(http.StatusNoContent)
|
|
})
|
|
srv := httptest.NewServer(mux)
|
|
t.Cleanup(srv.Close)
|
|
return srv
|
|
}
|
|
|
|
func TestHTTPAdapter_SyncTenantStatus(t *testing.T) {
|
|
puts := map[string]map[string][]string{}
|
|
srv := stubStatusKC(t,
|
|
map[string]string{"acme": "org-1"},
|
|
map[string][]string{"org-1": {"u-1", "u-2", "u-missing"}},
|
|
map[string]userRepresentation{
|
|
"u-1": {ID: "u-1", Attributes: map[string][]string{"org_roles": {"IT_ADMIN"}, "tenant_status": {"trial"}}},
|
|
"u-2": {ID: "u-2"},
|
|
},
|
|
puts, "")
|
|
a := usersAdapter(srv)
|
|
|
|
err := a.SyncTenantStatus(context.Background(), "acme", "restricted")
|
|
if err == nil || !strings.Contains(err.Error(), "u-missing") {
|
|
t.Fatalf("expected the missing member to surface as first error, got %v", err)
|
|
}
|
|
if got := puts["u-1"]["tenant_status"]; len(got) != 1 || got[0] != "restricted" {
|
|
t.Fatalf("u-1 tenant_status = %v", got)
|
|
}
|
|
if got := puts["u-1"]["org_roles"]; len(got) != 1 || got[0] != "IT_ADMIN" {
|
|
t.Fatalf("org_roles must be preserved, got %v", puts["u-1"])
|
|
}
|
|
if got := puts["u-2"]["tenant_status"]; len(got) != 1 || got[0] != "restricted" {
|
|
t.Fatalf("u-2 (no attributes) tenant_status = %v", got)
|
|
}
|
|
}
|
|
|
|
func TestHTTPAdapter_SyncTenantStatus_errors(t *testing.T) {
|
|
puts := map[string]map[string][]string{}
|
|
srv := stubStatusKC(t,
|
|
map[string]string{"acme": "org-1"},
|
|
map[string][]string{"org-1": {"u-1"}},
|
|
map[string]userRepresentation{"u-1": {ID: "u-1"}},
|
|
puts, "u-1")
|
|
a := usersAdapter(srv)
|
|
|
|
if err := a.SyncTenantStatus(context.Background(), "nope", "active"); !errors.Is(err, ErrOrgNotFound) {
|
|
t.Fatalf("unknown org: %v", err)
|
|
}
|
|
if err := a.SyncTenantStatus(context.Background(), "acme", "active"); err == nil || !strings.Contains(err.Error(), "update user u-1: 500") {
|
|
t.Fatalf("update failure must be reported: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestHTTPAdapter_findUserByEmail(t *testing.T) {
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("/realms/test-realm/protocol/openid-connect/token", func(w http.ResponseWriter, _ *http.Request) {
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"access_token": "t", "expires_in": 60})
|
|
})
|
|
mux.HandleFunc("GET /admin/realms/test-realm/users", func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Query().Get("email") == "Ada@Example.com" {
|
|
_ = json.NewEncoder(w).Encode([]map[string]string{{"id": "u-ada", "email": "ada@example.com"}})
|
|
return
|
|
}
|
|
_ = json.NewEncoder(w).Encode([]map[string]string{})
|
|
})
|
|
srv := httptest.NewServer(mux)
|
|
t.Cleanup(srv.Close)
|
|
a := usersAdapter(srv)
|
|
id, err := a.findUserByEmail(context.Background(), "Ada@Example.com")
|
|
if err != nil || id != "u-ada" {
|
|
t.Fatalf("got %q, %v", id, err)
|
|
}
|
|
if _, err := a.findUserByEmail(context.Background(), "nobody@example.com"); err == nil {
|
|
t.Fatal("expected not found")
|
|
}
|
|
}
|