test: cover tenant listing, status ladder, authz gate, KC status sync
ci / shared (pull_request) Successful in 14s
ci / test (pull_request) Successful in 22m5s
ci / image (pull_request) Skipped

Coverage gate (70%) fell to 67.6% with the new M-MIG-5 code paths.
Adds tests for GET /v1/tenants pagination + filters + validation,
GET /v1/tenants/{id}, POST /v1/tenants/{id}/status validation and the
Keycloak-failure audit path, /readyz, the requireAuthz middleware and
LogAuthz, and HTTPAdapter.SyncTenantStatus / findUserByEmail against a
stub Keycloak admin API. CI package set now reports 73.5%.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
This commit is contained in:
Sharang ParnerkarandClaude Fable 5.1 committed 2026-09-11 18:05:48 +02:00
1 parent 5a74d84681
commit 9b50b98678
3 files changed
+334

No files matched your search

+128
View File
@@ -0,0 +1,128 @@
package keycloak
import (
"context"
"encoding/json"
"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"); err == nil || !strings.Contains(err.Error(), "org not found") {
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")
}
}
+63
View File
@@ -0,0 +1,63 @@
package server
import (
"bytes"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.breakpilot.com/platform/tenant-registry/internal/authn"
)
func TestRequireAuthz_middleware(t *testing.T) {
ok := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) })
s := &Server{Log: slog.New(slog.NewTextHandler(io.Discard, nil))}
// nil rules → passthrough
rr := httptest.NewRecorder()
s.requireAuthz(ok).ServeHTTP(rr, httptest.NewRequest("POST", "/v1/tenants", nil))
if rr.Code != http.StatusNoContent {
t.Fatalf("nil rules: %d", rr.Code)
}
s.Authz = ParseAuthzRules("pruefwerk-svc:entitlements,tenants.read")
// no principal (auth disabled) → passthrough
rr = httptest.NewRecorder()
s.requireAuthz(ok).ServeHTTP(rr, httptest.NewRequest("POST", "/v1/tenants", nil))
if rr.Code != http.StatusNoContent {
t.Fatalf("no principal: %d", rr.Code)
}
// allowed group
req := httptest.NewRequest("GET", "/v1/tenants", nil)
req = req.WithContext(authn.WithPrincipal(req.Context(), &authn.Principal{Subject: "svc", ClientID: "pruefwerk-svc"}))
rr = httptest.NewRecorder()
s.requireAuthz(ok).ServeHTTP(rr, req)
if rr.Code != http.StatusNoContent {
t.Fatalf("allowed: %d", rr.Code)
}
// forbidden group
req = httptest.NewRequest("POST", "/v1/tenants", nil)
req = req.WithContext(authn.WithPrincipal(req.Context(), &authn.Principal{Subject: "svc", ClientID: "pruefwerk-svc"}))
rr = httptest.NewRecorder()
s.requireAuthz(ok).ServeHTTP(rr, req)
if rr.Code != http.StatusForbidden || !strings.Contains(rr.Body.String(), "FORBIDDEN_CLIENT") {
t.Fatalf("forbidden: %d %s", rr.Code, rr.Body.String())
}
}
func TestLogAuthz(t *testing.T) {
var buf bytes.Buffer
log := slog.New(slog.NewTextHandler(&buf, nil))
LogAuthz(log, nil)
if !strings.Contains(buf.String(), "AUTHZ_RULES not set") {
t.Fatalf("nil rules must warn: %s", buf.String())
}
buf.Reset()
LogAuthz(log, ParseAuthzRules("portal-svc:tenants;root:*"))
if !strings.Contains(buf.String(), "portal-svc") || !strings.Contains(buf.String(), "root") {
t.Fatalf("rules must be logged: %s", buf.String())
}
}
+143
View File
@@ -0,0 +1,143 @@
package server_test
import (
"bytes"
"fmt"
"net/http"
"testing"
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
type tenantPage struct {
Items []store.Tenant `json:"items"`
NextCursor string `json:"next_cursor"`
}
func TestListTenants_pagination_and_filters(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
for i := 0; i < 3; i++ {
slug := fmt.Sprintf("list-co-%d", i)
if resp, raw := h.do("POST", "/v1/tenants", map[string]any{"slug": slug, "name": slug}); resp.StatusCode != 201 {
t.Fatalf("create %s: %d %s", slug, resp.StatusCode, raw)
}
}
// walk with limit=2: acme + 3 new = 4 tenants → 2 pages
seen := map[string]bool{}
cursor := ""
pages := 0
for {
path := "/v1/tenants?limit=2"
if cursor != "" {
path += "&cursor=" + cursor
}
resp, raw := h.do("GET", path, nil)
if resp.StatusCode != http.StatusOK {
t.Fatalf("list: %d %s", resp.StatusCode, raw)
}
page := decode[tenantPage](t, raw)
pages++
for _, it := range page.Items {
if seen[it.ID] {
t.Fatalf("tenant %s returned twice", it.Slug)
}
seen[it.ID] = true
}
if page.NextCursor == "" {
break
}
cursor = page.NextCursor
if pages > 5 {
t.Fatal("cursor never terminates")
}
}
if len(seen) != 4 || pages < 2 {
t.Fatalf("seen=%d pages=%d", len(seen), pages)
}
// status filter: move one tenant to halted and list only those
var target string
for id := range seen {
if id != h.tenant.ID {
target = id
break
}
}
if resp, raw := h.do("POST", "/v1/tenants/"+target+"/status", map[string]any{"status": "halted", "source": "test"}); resp.StatusCode != 200 {
t.Fatalf("status: %d %s", resp.StatusCode, raw)
}
resp, raw := h.do("GET", "/v1/tenants?status=halted", nil)
page := decode[tenantPage](t, raw)
if resp.StatusCode != 200 || len(page.Items) != 1 || page.Items[0].ID != target {
t.Fatalf("status filter: %d %+v", resp.StatusCode, page.Items)
}
// kind filter (all are customer kind by default)
resp, raw = h.do("GET", "/v1/tenants?kind=customer", nil)
page = decode[tenantPage](t, raw)
if resp.StatusCode != 200 || len(page.Items) != 4 {
t.Fatalf("kind filter: %d %d", resp.StatusCode, len(page.Items))
}
// validation errors
for _, q := range []string{"?status=bogus", "?limit=0", "?limit=abc", "?limit=9999"} {
if resp, _ := h.do("GET", "/v1/tenants"+q, nil); resp.StatusCode != http.StatusBadRequest {
t.Fatalf("%s: %d, want 400", q, resp.StatusCode)
}
}
})
}
func TestGetTenant_byID(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
resp, raw := h.do("GET", "/v1/tenants/"+h.tenant.ID, nil)
if resp.StatusCode != http.StatusOK {
t.Fatalf("get: %d %s", resp.StatusCode, raw)
}
if got := decode[store.Tenant](t, raw); got.Slug != "acme" {
t.Fatalf("slug = %q", got.Slug)
}
if resp, _ := h.do("GET", "/v1/tenants/00000000-0000-0000-0000-000000000000", nil); resp.StatusCode != http.StatusNotFound {
t.Fatalf("unknown id: %d", resp.StatusCode)
}
})
}
func TestSetTenantStatus_validation_and_keycloakFailure(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
// frozen is legacy and not settable; bogus is unknown
for _, st := range []string{"frozen", "bogus", ""} {
if resp, _ := h.do("POST", "/v1/tenants/"+h.tenant.ID+"/status", map[string]any{"status": st}); resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status %q: %d, want 400", st, resp.StatusCode)
}
}
if resp, _ := h.do("POST", "/v1/tenants/00000000-0000-0000-0000-000000000000/status", map[string]any{"status": "warning"}); resp.StatusCode != http.StatusNotFound {
t.Fatalf("unknown tenant: %d", resp.StatusCode)
}
// Keycloak sync failure must not fail the transition; it is audited.
h.kcMock.FailNext = keycloak.ErrOrgConflict
resp, raw := h.do("POST", "/v1/tenants/"+h.tenant.ID+"/status", map[string]any{"status": "warning", "source": "erp", "reason": "invoice overdue"})
if resp.StatusCode != http.StatusOK {
t.Fatalf("status with kc failure: %d %s", resp.StatusCode, raw)
}
if got := decode[store.Tenant](t, raw); got.Status != "warning" {
t.Fatalf("status = %q", got.Status)
}
_, raw = h.do("GET", "/v1/audit?tenant_id="+h.tenant.ID+"&limit=50", nil)
if !containsAction(raw, "keycloak.status_sync_failed") || !containsAction(raw, "tenant.status_changed") {
t.Fatalf("audit trail missing: %s", raw)
}
})
}
func TestReadyz(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
if resp, raw := h.do("GET", "/readyz", nil); resp.StatusCode != http.StatusOK {
t.Fatalf("readyz: %d %s", resp.StatusCode, raw)
}
})
}
func containsAction(raw []byte, action string) bool {
return bytes.Contains(raw, []byte(`"action":"`+action+`"`))
}