package server import ( "context" "encoding/json" "io" "log/slog" "net/http" "net/http/httptest" "slices" "strings" "testing" "time" "git.breakpilot.com/platform/tenant-registry/internal/authn" "git.breakpilot.com/platform/tenant-registry/internal/keycloak" "git.breakpilot.com/platform/tenant-registry/internal/store" ) // teamFixture: tenant "acme" with an active IT_ADMIN (u-admin), an active // FINANCE member (u-fin) and a pending CXO invitation (u-inv). type teamFixture struct { s *Server h http.Handler kc *keycloak.Mock tenant *store.Tenant } func newTeamFixture(t *testing.T, p *authn.Principal, rules ...string) *teamFixture { t.Helper() mem := store.NewMemory() tenant, _ := mem.GetTenantBySlug(context.Background(), "acme") kc := keycloak.NewMock() kc.Members["acme"] = []keycloak.OrgMember{ {UserID: "u-admin", Email: "admin@acme.test", OrgRoles: []string{"IT_ADMIN"}, Enabled: true}, {UserID: "u-fin", Email: "fin@acme.test", OrgRoles: []string{"FINANCE"}, Enabled: true}, {UserID: "u-inv", Email: "inv@acme.test", OrgRoles: []string{"CXO"}, Enabled: true, Pending: true}, } kc.Users["inv@acme.test"] = "u-inv" s := &Server{Log: slog.New(slog.NewTextHandler(io.Discard, nil)), Store: mem, Keycloak: kc} if len(rules) > 0 { s.Authz = ParseAuthzRules(rules[0]) } router := NewRouter(s) h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if p != nil { r = r.WithContext(authn.WithPrincipal(r.Context(), p)) } router.ServeHTTP(w, r) }) return &teamFixture{s: s, h: h, kc: kc, tenant: tenant} } // portal is the portal's service client acting for the signed-in admin. var portal = &authn.Principal{Subject: "svc-portal", ClientID: "portal-svc"} func (f *teamFixture) call(t *testing.T, method, path, body string, hdr map[string]string) (int, memberActionResp, string) { t.Helper() var rd io.Reader if body != "" { rd = strings.NewReader(body) } req := httptest.NewRequest(method, path, rd) for k, v := range hdr { req.Header.Set(k, v) } rr := httptest.NewRecorder() f.h.ServeHTTP(rr, req) var out memberActionResp _ = json.Unmarshal(rr.Body.Bytes(), &out) return rr.Code, out, rr.Body.String() } func (f *teamFixture) memberPath(uid string) string { return "/v1/tenants/" + f.tenant.ID + "/members/" + uid } func (f *teamFixture) audit(t *testing.T, action string) []store.AuditEvent { t.Helper() items, _, err := f.s.Store.ListAudit(context.Background(), store.AuditFilter{TenantID: f.tenant.ID, Action: action}) if err != nil { t.Fatal(err) } return items } var asAdmin = map[string]string{headerPortalUserSubject: "u-admin", headerPortalUserEmail: "admin@acme.test"} func TestTeam_changeRole(t *testing.T) { f := newTeamFixture(t, portal) code, out, raw := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"role":"cxo"}`, asAdmin) if code != http.StatusOK || out.Status != "role_changed" || out.Member == nil || out.Member.OrgRoles[0] != "CXO" { t.Fatalf("role change: %d %s", code, raw) } if f.kc.RoleSet["u-fin"] != "CXO" { t.Errorf("keycloak role: %v", f.kc.RoleSet) } ev := f.audit(t, "user.role_changed") if len(ev) != 1 || ev[0].ActorID != "u-admin" || ev[0].ActorName != "admin@acme.test" || ev[0].ActorType != "user" || ev[0].TargetName != "fin@acme.test" || ev[0].Metadata["to"] != "CXO" { t.Fatalf("audit: %+v", ev) } if from, _ := ev[0].Metadata["from"].([]string); !slices.Equal(from, []string{"FINANCE"}) { t.Errorf("audit from: %#v", ev[0].Metadata["from"]) } // Same role again: unchanged, no second audit entry. code, out, _ = f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"role":"CXO"}`, asAdmin) if code != http.StatusOK || out.Status != "unchanged" || len(f.audit(t, "user.role_changed")) != 1 { t.Fatalf("unchanged: %d %+v", code, out) } } func TestTeam_patchValidation(t *testing.T) { f := newTeamFixture(t, portal) for _, body := range []string{`{}`, `{"role":"CXO","blocked":true}`, `{"role":"GOD"}`, `nope`} { if code, _, raw := f.call(t, http.MethodPatch, f.memberPath("u-fin"), body, asAdmin); code != http.StatusBadRequest { t.Errorf("%s: %d %s", body, code, raw) } } if code, _, raw := f.call(t, http.MethodPatch, f.memberPath("u-ghost"), `{"role":"CXO"}`, asAdmin); code != http.StatusNotFound || !strings.Contains(raw, "not_a_member") { t.Errorf("unknown member: %d %s", code, raw) } if code, _, _ := f.call(t, http.MethodPatch, "/v1/tenants/00000000-0000-0000-0000-0000000000ff/members/u-fin", `{"role":"CXO"}`, asAdmin); code != http.StatusNotFound { t.Errorf("unknown tenant: %d", code) } f.kc.FailNext = keycloak.ErrUnavailable if code, _, _ := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"role":"CXO"}`, asAdmin); code != http.StatusServiceUnavailable { t.Errorf("kc down on list: %d", code) } delete(f.kc.Members, "acme") if code, _, _ := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"role":"CXO"}`, asAdmin); code != http.StatusNotFound { t.Errorf("no org: %d", code) } } func TestTeam_guards(t *testing.T) { f := newTeamFixture(t, portal) // Nobody acts on themselves — by subject or by e-mail. for _, c := range []struct{ method, body string }{ {http.MethodPatch, `{"role":"USER"}`}, {http.MethodPatch, `{"blocked":true}`}, {http.MethodDelete, ``}, } { code, _, raw := f.call(t, c.method, f.memberPath("u-admin"), c.body, asAdmin) if code != http.StatusConflict || !strings.Contains(raw, `"self"`) { t.Errorf("self %s %s: %d %s", c.method, c.body, code, raw) } } byMail := map[string]string{headerPortalUserSubject: "other-id", headerPortalUserEmail: "ADMIN@acme.test"} if code, _, raw := f.call(t, http.MethodDelete, f.memberPath("u-admin"), "", byMail); code != http.StatusConflict || !strings.Contains(raw, `"self"`) { t.Errorf("self by mail: %d %s", code, raw) } // The last active IT_ADMIN: staff (no self) still cannot demote, block or // remove them. The pending CXO does not count as an admin. staff := map[string]string{headerStaffSubject: "staff-1", headerStaffEmail: "ops@breakpilot.test"} for _, c := range []struct{ method, body string }{ {http.MethodPatch, `{"role":"USER"}`}, {http.MethodPatch, `{"blocked":true}`}, {http.MethodDelete, ``}, } { code, _, raw := f.call(t, c.method, f.memberPath("u-admin"), c.body, staff) if code != http.StatusConflict || !strings.Contains(raw, "last_admin") { t.Errorf("last admin %s %s: %d %s", c.method, c.body, code, raw) } } // Admin → OWNER keeps an admin role: allowed. if code, _, raw := f.call(t, http.MethodPatch, f.memberPath("u-admin"), `{"role":"OWNER"}`, staff); code != http.StatusOK { t.Errorf("admin to owner: %d %s", code, raw) } // With a second active admin the first may be demoted. if code, _, raw := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"role":"IT_ADMIN"}`, staff); code != http.StatusOK { t.Fatalf("promote: %d %s", code, raw) } if code, _, raw := f.call(t, http.MethodPatch, f.memberPath("u-admin"), `{"role":"USER"}`, staff); code != http.StatusOK { t.Errorf("demote with second admin: %d %s", code, raw) } } func TestTeam_blockAndUnblock(t *testing.T) { f := newTeamFixture(t, portal) ctx := context.Background() mine, _ := f.s.Store.CreateAPIKey(ctx, store.APIKeyCreate{TenantID: f.tenant.ID, Name: "ci", Prefix: "bp_aaaa1", Hash: "h1", CreatedBy: "fin@acme.test"}) _, _ = f.s.Store.CreateAPIKey(ctx, store.APIKeyCreate{TenantID: f.tenant.ID, Name: "other", Prefix: "bp_aaaa2", Hash: "h2", CreatedBy: "admin@acme.test"}) gone, _ := f.s.Store.CreateAPIKey(ctx, store.APIKeyCreate{TenantID: f.tenant.ID, Name: "old", Prefix: "bp_aaaa3", Hash: "h3", CreatedBy: "u-fin"}) _ = f.s.Store.RevokeAPIKey(ctx, gone.ID, "") code, out, raw := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"blocked":true}`, asAdmin) if code != http.StatusOK || out.Status != "blocked" || out.Member.Status != "blocked" || !out.SessionsEnded { t.Fatalf("block: %d %s", code, raw) } if len(out.APIKeys) != 1 || out.APIKeys[0].ID != mine.ID { t.Errorf("api keys offered: %+v", out.APIKeys) } if !slices.Contains(f.kc.Blocked["u-fin"], f.tenant.ID) || !slices.Equal(f.kc.LoggedOut, []string{"u-fin"}) { t.Errorf("keycloak: blocked=%v logout=%v", f.kc.Blocked, f.kc.LoggedOut) } if ev := f.audit(t, "user.blocked"); len(ev) != 1 || ev[0].Metadata["sessions_ended"] != true { t.Errorf("audit: %+v", ev) } // The key is listed, not revoked. if keys, _ := f.s.Store.ListAPIKeys(ctx, f.tenant.ID); keys[0].RevokedAt != nil && keys[0].ID == mine.ID { t.Error("api key was revoked silently") } // The list shows the status. rr := httptest.NewRecorder() f.h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+f.tenant.ID+"/members", nil)) if !strings.Contains(rr.Body.String(), `"status":"blocked"`) || !strings.Contains(rr.Body.String(), `"status":"invited"`) { t.Errorf("list statuses: %s", rr.Body.String()) } // Blocking again is a no-op. if code, out, _ := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"blocked":true}`, asAdmin); code != http.StatusOK || out.Status != "unchanged" { t.Errorf("block twice: %d %+v", code, out) } code, out, raw = f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"blocked":false}`, asAdmin) if code != http.StatusOK || out.Status != "unblocked" || out.Member.Status != "active" { t.Fatalf("unblock: %d %s", code, raw) } if slices.Contains(f.kc.Blocked["u-fin"], f.tenant.ID) || len(f.audit(t, "user.unblocked")) != 1 { t.Errorf("unblock state: %v", f.kc.Blocked) } } func TestTeam_blockLogoutFailureIsNotFatal(t *testing.T) { f := newTeamFixture(t, portal) f.kc.LoggedOut = nil // FailNext hits the first Keycloak call; make the logout the one that fails // by blocking through a mock that fails only LogoutUser. kc := &logoutFails{Mock: f.kc} f.s.Keycloak = kc code, out, raw := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"blocked":true}`, asAdmin) if code != http.StatusOK || out.SessionsEnded { t.Fatalf("block with failed logout: %d %s", code, raw) } } type logoutFails struct{ *keycloak.Mock } func (l *logoutFails) LogoutUser(context.Context, string) error { return keycloak.ErrUnavailable } func TestTeam_removeAndRevoke(t *testing.T) { f := newTeamFixture(t, portal) code, out, raw := f.call(t, http.MethodDelete, f.memberPath("u-fin"), "", asAdmin) if code != http.StatusOK || out.Status != "removed" || !out.SessionsEnded || len(out.APIKeys) != 0 { t.Fatalf("remove: %d %s", code, raw) } if !slices.Equal(f.kc.Removed, []string{"u-fin"}) || len(f.kc.Deleted) != 0 || !slices.Equal(f.kc.LoggedOut, []string{"u-fin"}) { t.Errorf("keycloak: removed=%v deleted=%v logout=%v", f.kc.Removed, f.kc.Deleted, f.kc.LoggedOut) } if len(f.audit(t, "user.removed")) != 1 { t.Error("user.removed not audited") } // A pending invitation the tenant's invite did NOT create: membership only. code, out, raw = f.call(t, http.MethodDelete, f.memberPath("u-inv"), "", asAdmin) if code != http.StatusOK || out.Status != "invite_revoked" || out.UserDeleted { t.Fatalf("revoke (existing account): %d %s", code, raw) } if ev := f.audit(t, "user.invite_revoked"); len(ev) != 1 || ev[0].Metadata["user_deleted"] != false { t.Errorf("audit: %+v", ev) } } func TestTeam_revokeDeletesAccountTheInviteCreated(t *testing.T) { f := newTeamFixture(t, portal) f.s.emitAudit(context.Background(), nil, store.AuditEvent{TenantID: f.tenant.ID, Action: "user.invited", TargetID: "inv@acme.test", Metadata: map[string]interface{}{"user_id": "u-inv", "user_created": true}}) code, out, raw := f.call(t, http.MethodDelete, f.memberPath("u-inv"), "", asAdmin) if code != http.StatusOK || out.Status != "invite_revoked" || !out.UserDeleted { t.Fatalf("revoke: %d %s", code, raw) } if !slices.Equal(f.kc.Deleted, []string{"u-inv"}) || len(f.kc.LoggedOut) != 0 { t.Errorf("keycloak: deleted=%v logout=%v", f.kc.Deleted, f.kc.LoggedOut) } // Member of another org too: the account stays. g := newTeamFixture(t, portal) g.kc.Members["other"] = []keycloak.OrgMember{{UserID: "u-inv", Email: "inv@acme.test"}} g.s.emitAudit(context.Background(), nil, store.AuditEvent{TenantID: g.tenant.ID, Action: "user.invited", Metadata: map[string]interface{}{"user_id": "u-inv", "user_created": true}}) if _, out, raw := g.call(t, http.MethodDelete, g.memberPath("u-inv"), "", asAdmin); out.UserDeleted || out.Status != "invite_revoked" { t.Fatalf("revoke (other org): %s", raw) } } func TestTeam_resend(t *testing.T) { f := newTeamFixture(t, portal) code, out, raw := f.call(t, http.MethodPost, f.memberPath("u-inv")+"/resend", "", asAdmin) if code != http.StatusAccepted || out.Status != "invite_resent" || !slices.Equal(f.kc.Resent, []string{"inv@acme.test"}) { t.Fatalf("resend: %d %s", code, raw) } if len(f.audit(t, "user.invite_resent")) != 1 { t.Error("resend not audited") } if code, _, raw := f.call(t, http.MethodPost, f.memberPath("u-fin")+"/resend", "", asAdmin); code != http.StatusConflict || !strings.Contains(raw, "not_pending") { t.Errorf("resend to active member: %d %s", code, raw) } } func TestTeam_keycloakFailures(t *testing.T) { f := newTeamFixture(t, portal) kc := &failAfterList{Mock: f.kc} f.s.Keycloak = kc for _, c := range []struct{ method, path, body string }{ {http.MethodPatch, f.memberPath("u-fin"), `{"role":"CXO"}`}, {http.MethodPatch, f.memberPath("u-fin"), `{"blocked":true}`}, {http.MethodDelete, f.memberPath("u-fin"), ``}, {http.MethodDelete, f.memberPath("u-inv"), ``}, {http.MethodPost, f.memberPath("u-inv") + "/resend", ``}, } { if code, _, raw := f.call(t, c.method, c.path, c.body, asAdmin); code != http.StatusBadGateway { t.Errorf("%s %s %s: %d %s", c.method, c.path, c.body, code, raw) } } } // failAfterList lists members normally and fails every write. type failAfterList struct{ *keycloak.Mock } func (k *failAfterList) SetMemberRole(context.Context, string, string) error { return io.ErrUnexpectedEOF } func (k *failAfterList) SetMemberBlocked(context.Context, string, string, bool) error { return io.ErrUnexpectedEOF } func (k *failAfterList) RemoveMember(context.Context, string, string, string, bool) (bool, error) { return false, io.ErrUnexpectedEOF } func (k *failAfterList) ResendInvite(context.Context, string, string) error { return io.ErrUnexpectedEOF } func TestTeam_userTokens(t *testing.T) { tenantID := "00000000-0000-0000-0000-000000000001" // A plain member may not manage the team. user := &authn.Principal{Subject: "u-fin", ClientID: "cli", TenantID: tenantID, Email: "fin@acme.test", OrgRoles: []string{"FINANCE"}} f := newTeamFixture(t, user) if code, _, raw := f.call(t, http.MethodPatch, f.memberPath("u-inv"), `{"role":"USER"}`, nil); code != http.StatusForbidden || !strings.Contains(raw, "FORBIDDEN_ROLE") { t.Errorf("plain user: %d %s", code, raw) } // An IT_ADMIN token acts with its own identity; the portal header is ignored. admin := &authn.Principal{Subject: "u-admin", ClientID: "cli", TenantID: tenantID, Email: "admin@acme.test", OrgRoles: []string{"IT_ADMIN"}} f = newTeamFixture(t, admin) if code, _, raw := f.call(t, http.MethodDelete, f.memberPath("u-admin"), "", map[string]string{headerPortalUserSubject: "someone"}); code != http.StatusConflict { t.Errorf("admin token self: %d %s", code, raw) } if code, _, raw := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"role":"LEGAL"}`, nil); code != http.StatusOK { t.Errorf("admin token: %d %s", code, raw) } if ev := f.audit(t, "user.role_changed"); len(ev) != 1 || ev[0].ActorID != "u-admin" || ev[0].ActorType != "user" { t.Errorf("audit actor: %+v", ev) } // Another tenant's admin: 404. other := &authn.Principal{Subject: "u-x", ClientID: "cli", TenantID: "11111111-1111-1111-1111-111111111111", OrgRoles: []string{"IT_ADMIN"}} f = newTeamFixture(t, other) if code, _, _ := f.call(t, http.MethodDelete, f.memberPath("u-fin"), "", nil); code != http.StatusNotFound { t.Errorf("cross tenant: %d", code) } } func TestTeam_serviceWithoutPortalUser(t *testing.T) { f := newTeamFixture(t, portal) if code, _, raw := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"role":"USER"}`, nil); code != http.StatusOK { t.Fatalf("service: %d %s", code, raw) } if ev := f.audit(t, "user.role_changed"); len(ev) != 1 || ev[0].ActorType != "service" || ev[0].ActorID != "svc-portal" { t.Errorf("audit actor: %+v", ev) } // Auth disabled: no principal at all. g := newTeamFixture(t, nil) if code, _, raw := g.call(t, http.MethodPatch, g.memberPath("u-fin"), `{"role":"USER"}`, nil); code != http.StatusOK { t.Fatalf("no principal: %d %s", code, raw) } } func TestTeam_adminRoutes(t *testing.T) { const rules = "portal-svc:tenants,admin;pruefwerk-svc:tenants.read" f := newTeamFixture(t, portal, rules) staff := map[string]string{headerStaffSubject: "staff-1", headerStaffEmail: "ops@breakpilot.test"} base := "/v1/admin/tenants/" + f.tenant.ID + "/members/" if code, _, raw := f.call(t, http.MethodPatch, base+"u-fin", `{"blocked":true}`, staff); code != http.StatusOK { t.Fatalf("staff block: %d %s", code, raw) } if ev := f.audit(t, "user.blocked"); len(ev) != 1 || ev[0].ActorType != "staff" || ev[0].ActorID != "staff-1" || ev[0].ActorName != "ops@breakpilot.test" { t.Errorf("audit actor: %+v", ev) } if code, _, raw := f.call(t, http.MethodPost, base+"u-inv/resend", "", staff); code != http.StatusAccepted { t.Errorf("staff resend: %d %s", code, raw) } if code, _, raw := f.call(t, http.MethodDelete, base+"u-fin", "", staff); code != http.StatusOK { t.Errorf("staff remove: %d %s", code, raw) } if code, _, _ := f.call(t, http.MethodDelete, "/v1/admin/tenants/00000000-0000-0000-0000-0000000000ff/members/u-fin", "", staff); code != http.StatusNotFound { t.Errorf("unknown tenant: %d", code) } // The detail page carries the statuses. rr := httptest.NewRecorder() f.h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/admin/tenants/"+f.tenant.ID, nil)) if !strings.Contains(rr.Body.String(), `"status":"invited"`) { t.Errorf("admin detail statuses: %s", rr.Body.String()) } // A read-only product client may neither manage nor reach admin routes. ro := newTeamFixture(t, &authn.Principal{Subject: "svc2", ClientID: "pruefwerk-svc"}, rules) if code, _, _ := ro.call(t, http.MethodPatch, ro.memberPath("u-fin"), `{"role":"USER"}`, nil); code != http.StatusForbidden { t.Errorf("read client patch: %d", code) } if code, _, _ := ro.call(t, http.MethodDelete, "/v1/admin/tenants/"+ro.tenant.ID+"/members/u-fin", "", nil); code != http.StatusForbidden { t.Errorf("read client admin: %d", code) } } func TestRequireMember(t *testing.T) { tenantID := "00000000-0000-0000-0000-000000000001" user := &authn.Principal{Subject: "u-fin", ClientID: "cli", TenantID: tenantID, Email: "fin@acme.test", OrgRoles: []string{"FINANCE"}} f := newTeamFixture(t, user) now := time.Date(2026, 10, 5, 12, 0, 0, 0, time.UTC) f.s.Now = func() time.Time { return now } get := func() (int, string) { rr := httptest.NewRecorder() f.h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+tenantID+"/members", nil)) return rr.Code, rr.Body.String() } if code, raw := get(); code != http.StatusOK { t.Fatalf("member: %d %s", code, raw) } // Blocked behind the registry's back: the cached "not blocked" holds for // blockTTL, then the block bites. f.kc.Blocked["u-fin"] = []string{tenantID} if code, _ := get(); code != http.StatusOK { t.Errorf("cached decision: %d", code) } now = now.Add(blockTTL + time.Second) if code, raw := get(); code != http.StatusForbidden || !strings.Contains(raw, "MEMBER_BLOCKED") { t.Errorf("blocked: %d %s", code, raw) } // A block made through the registry is effective at once. f.kc.Blocked["u-fin"] = nil f.s.blocks.forget("u-fin") if code, _ := get(); code != http.StatusOK { t.Errorf("unblocked: %d", code) } // The org_blocked claim alone is enough. claimed := *user claimed.OrgBlocked = []string{tenantID} g := newTeamFixture(t, &claimed) rr := httptest.NewRecorder() g.h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+tenantID+"/members", nil)) if rr.Code != http.StatusForbidden { t.Errorf("claim: %d", rr.Code) } // Deleted account: refused. Keycloak down: allowed (fails open, logged). g = newTeamFixture(t, user) g.kc.FailNext = keycloak.ErrUserNotFound rr = httptest.NewRecorder() g.h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+tenantID+"/members", nil)) if rr.Code != http.StatusForbidden || !strings.Contains(rr.Body.String(), "USER_UNKNOWN") { t.Errorf("deleted user: %d %s", rr.Code, rr.Body.String()) } g.kc.FailNext = keycloak.ErrUnavailable rr = httptest.NewRecorder() g.h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+tenantID+"/members", nil)) if rr.Code != http.StatusOK { t.Errorf("kc down: %d %s", rr.Code, rr.Body.String()) } } func TestEntitlementCheck_blockedMember(t *testing.T) { f := newTeamFixture(t, portal) ctx := context.Background() tp := store.TenantProduct{TenantID: f.tenant.ID, Product: "pruefwerk", Enabled: true, Config: map[string]interface{}{}} if _, err := f.s.Store.UpsertTenantProduct(ctx, tp); err != nil { t.Fatal(err) } check := func(user string) EntitlementCheck { t.Helper() body := `{"tenant_id":"` + f.tenant.ID + `","product":"pruefwerk","user_id":"` + user + `"}` rr := httptest.NewRecorder() f.h.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/v1/internal/entitlements/check", strings.NewReader(body))) var out EntitlementCheck _ = json.Unmarshal(rr.Body.Bytes(), &out) return out } if got := check("u-fin"); !got.Allowed { t.Fatalf("member: %+v", got) } f.kc.Blocked["u-blocked"] = []string{f.tenant.ID} if got := check("u-blocked"); got.Allowed || got.Reason != "member_blocked" { t.Errorf("blocked: %+v", got) } f.kc.FailNext = keycloak.ErrUserNotFound if got := check("u-gone"); got.Allowed || got.Reason != "user_unknown" { t.Errorf("unknown: %+v", got) } f.kc.FailNext = keycloak.ErrUnavailable if got := check("u-down"); !got.Allowed { t.Errorf("kc down fails open: %+v", got) } } func TestUserMemberships_excludeBlocked(t *testing.T) { f := newTeamFixture(t, portal) f.kc.Claims["u-fin"] = keycloak.Claims{TenantID: f.tenant.ID, TenantSlug: "acme", OrgRoles: []string{"FINANCE"}} get := func() string { rr := httptest.NewRecorder() f.h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/users/u-fin/memberships", nil)) return rr.Body.String() } if !strings.Contains(get(), `"tenant_slug":"acme"`) { t.Fatal("membership missing") } if code, _, _ := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"blocked":true}`, asAdmin); code != http.StatusOK { t.Fatal(code) } if raw := get(); strings.Contains(raw, "acme") { t.Errorf("blocked membership listed: %s", raw) } }