package server import ( "context" "encoding/json" "errors" "net/http" "net/http/httptest" "slices" "strings" "testing" "git.breakpilot.com/platform/tenant-registry/internal/authn" "git.breakpilot.com/platform/tenant-registry/internal/keycloak" ) // capFixture is the team fixture plus an active OWNER (u-own), CXO (u-cxo) // and a USER who was given registry:members.manage (u-user). func capFixture(t *testing.T, p *authn.Principal) *teamFixture { t.Helper() f := newTeamFixture(t, p) f.kc.Members["acme"] = append(f.kc.Members["acme"], keycloak.OrgMember{UserID: "u-own", Email: "own@acme.test", OrgRoles: []string{"OWNER"}, Enabled: true}, keycloak.OrgMember{UserID: "u-cxo", Email: "cxo@acme.test", OrgRoles: []string{"CXO"}, Enabled: true}, keycloak.OrgMember{UserID: "u-user", Email: "user@acme.test", OrgRoles: []string{"USER"}, Enabled: true, ExtraCapabilities: []string{"registry:members.manage"}}, ) return f } func as(uid string) map[string]string { email := strings.TrimPrefix(uid, "u-") + "@acme.test" return map[string]string{headerPortalUserSubject: uid, headerPortalUserEmail: email} } func (f *teamFixture) capCall(t *testing.T, method, path, body string, hdr map[string]string) (int, capabilityResp, string) { t.Helper() req := httptest.NewRequest(method, path, strings.NewReader(body)) for k, v := range hdr { req.Header.Set(k, v) } rr := httptest.NewRecorder() f.h.ServeHTTP(rr, req) var out capabilityResp _ = json.Unmarshal(rr.Body.Bytes(), &out) return rr.Code, out, rr.Body.String() } func (f *teamFixture) capPath(uid string) string { return f.memberPath(uid) + "/capabilities" } func (f *teamFixture) reqPath(id string) string { return "/v1/tenants/" + f.tenant.ID + "/capability-requests/" + id } func (f *teamFixture) member(uid string) keycloak.OrgMember { for _, m := range f.kc.Members["acme"] { if m.UserID == uid { return m } } return keycloak.OrgMember{} } func errCode(raw string) string { var e struct { Error string `json:"error"` } _ = json.Unmarshal([]byte(raw), &e) return e.Error } func TestCapabilities_grantAndRevoke(t *testing.T) { f := capFixture(t, portal) const publish = "werkmeister:process.publish" code, out, raw := f.capCall(t, http.MethodPost, f.capPath("u-fin"), `{"capability":"`+publish+`"}`, asAdmin) if code != http.StatusOK || out.Status != "capability_granted" || !slices.Equal(out.Member.ExtraCapabilities, []string{publish}) { t.Fatalf("grant: %d %s", code, raw) } if !slices.Equal(f.kc.ExtrasSet["u-fin"], []string{publish}) { t.Errorf("keycloak: %v", f.kc.ExtrasSet) } ev := f.audit(t, "user.capability_granted") if len(ev) != 1 || ev[0].ActorID != "u-admin" || ev[0].TargetName != "fin@acme.test" || ev[0].Metadata["capability"] != publish { t.Fatalf("audit: %+v", ev) } // Again: unchanged, nothing written. if code, out, _ := f.capCall(t, http.MethodPost, f.capPath("u-fin"), `{"capability":"`+publish+`"}`, asAdmin); code != http.StatusOK || out.Status != "unchanged" { t.Errorf("again: %d %+v", code, out) } if len(f.audit(t, "user.capability_granted")) != 1 { t.Error("second grant audited") } // Extras are kept in order, without duplicates. f.capCall(t, http.MethodPost, f.capPath("u-fin"), `{"capability":"portal:infra.view"}`, asAdmin) if got := f.member("u-fin").ExtraCapabilities; !slices.Equal(got, []string{"portal:infra.view", publish}) { t.Errorf("two extras: %v", got) } // A role change leaves them as they are. if code, _, raw := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"role":"LEGAL"}`, asAdmin); code != http.StatusOK { t.Fatalf("role change: %d %s", code, raw) } if got := f.member("u-fin").ExtraCapabilities; len(got) != 2 { t.Errorf("extras after role change: %v", got) } code, out, raw = f.capCall(t, http.MethodDelete, f.capPath("u-fin")+"/"+publish, "", asAdmin) if code != http.StatusOK || out.Status != "capability_revoked" || !slices.Equal(out.Member.ExtraCapabilities, []string{"portal:infra.view"}) { t.Fatalf("revoke: %d %s", code, raw) } if ev := f.audit(t, "user.capability_revoked"); len(ev) != 1 || ev[0].Metadata["capability"] != publish { t.Fatalf("revoke audit: %+v", ev) } if code, out, _ := f.capCall(t, http.MethodDelete, f.capPath("u-fin")+"/"+publish, "", asAdmin); code != http.StatusOK || out.Status != "unchanged" { t.Errorf("revoke again: %d %+v", code, out) } f.capCall(t, http.MethodDelete, f.capPath("u-fin")+"/portal:infra.view", "", asAdmin) if got := f.kc.ExtrasSet["u-fin"]; len(got) != 0 { t.Errorf("last extra revoked: %v", got) } } func TestCapabilities_rules(t *testing.T) { f := capFixture(t, portal) for _, c := range []struct { name, uid, body string hdr map[string]string code int err string }{ {"unknown capability", "u-fin", `{"capability":"portal:god.mode"}`, asAdmin, http.StatusBadRequest, "unknown_capability"}, {"bad body", "u-fin", `nope`, asAdmin, http.StatusBadRequest, ""}, {"in the bundle already", "u-fin", `{"capability":"portal:billing.view"}`, asAdmin, http.StatusConflict, "in_bundle"}, {"on oneself", "u-admin", `{"capability":"portal:billing.view"}`, asAdmin, http.StatusConflict, "self"}, {"granter without members.manage", "u-fin", `{"capability":"portal:infra.view"}`, as("u-cxo"), http.StatusForbidden, "FORBIDDEN_ROLE"}, {"granter does not hold it", "u-fin", `{"capability":"portal:infra.view"}`, as("u-user"), http.StatusForbidden, "not_held"}, {"no person named", "u-fin", `{"capability":"portal:infra.view"}`, nil, http.StatusForbidden, "FORBIDDEN_ROLE"}, {"a pending member cannot grant", "u-fin", `{"capability":"portal:infra.view"}`, as("u-inv"), http.StatusForbidden, "FORBIDDEN_ROLE"}, {"unknown member", "u-ghost", `{"capability":"portal:infra.view"}`, asAdmin, http.StatusNotFound, "not_a_member"}, } { code, _, raw := f.capCall(t, http.MethodPost, f.capPath(c.uid), c.body, c.hdr) if code != c.code || (c.err != "" && errCode(raw) != c.err) { t.Errorf("%s: %d %s", c.name, code, raw) } } // A USER who was given members.manage grants what they hold. if code, out, raw := f.capCall(t, http.MethodPost, f.capPath("u-fin"), `{"capability":"werkmeister:task.work"}`, as("u-user")); code != http.StatusOK || out.Status != "capability_granted" { t.Errorf("extra-held members.manage: %d %s", code, raw) } if code, _, raw := f.capCall(t, http.MethodDelete, f.capPath("u-fin")+"/werkmeister:task.work", "", as("u-cxo")); code != http.StatusForbidden { t.Errorf("revoke without members.manage: %d %s", code, raw) } f.kc.FailNext = errors.New("keycloak down") if code, _, raw := f.capCall(t, http.MethodPost, f.capPath("u-fin"), `{"capability":"portal:infra.view"}`, asAdmin); code < 500 { t.Errorf("keycloak failure: %d %s", code, raw) } } func TestCapabilities_fourEyes(t *testing.T) { f := capFixture(t, portal) const manage = "registry:members.manage" code, out, raw := f.capCall(t, http.MethodPost, f.capPath("u-fin"), `{"capability":"`+manage+`"}`, asAdmin) if code != http.StatusAccepted || out.Status != "approval_requested" || out.Request == nil || out.Request.RequestedBy != "u-admin" { t.Fatalf("request: %d %s", code, raw) } if _, set := f.kc.ExtrasSet["u-fin"]; set { t.Fatal("an administration capability must wait for a second person") } reqID := out.Request.ID if code, again, _ := f.capCall(t, http.MethodPost, f.capPath("u-fin"), `{"capability":"`+manage+`"}`, asAdmin); code != http.StatusAccepted || again.Request.ID != reqID { t.Errorf("second request: %d %+v", code, again) } if ev := f.audit(t, "user.capability_requested"); len(ev) != 1 || ev[0].Metadata["request_id"] != reqID { t.Fatalf("request audit: %+v", ev) } // The list. rr := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "/v1/tenants/"+f.tenant.ID+"/capability-requests", nil) for k, v := range asAdmin { req.Header.Set(k, v) } f.h.ServeHTTP(rr, req) var list capabilityRequestsResp if err := json.Unmarshal(rr.Body.Bytes(), &list); err != nil || rr.Code != http.StatusOK || len(list.Requests) != 1 || list.Requests[0].ID != reqID { t.Fatalf("list: %d %s", rr.Code, rr.Body.String()) } if code, _, raw := f.capCall(t, http.MethodPost, f.reqPath(reqID)+"/approve", "", asAdmin); code != http.StatusConflict || errCode(raw) != "four_eyes" { t.Errorf("the requester approves: %d %s", code, raw) } if code, _, raw := f.capCall(t, http.MethodPost, f.reqPath(reqID)+"/approve", "", as("u-cxo")); code != http.StatusForbidden { t.Errorf("approver without members.manage: %d %s", code, raw) } code, out, raw = f.capCall(t, http.MethodPost, f.reqPath(reqID)+"/approve", "", as("u-own")) if code != http.StatusOK || out.Status != "capability_granted" || !slices.Contains(out.Member.ExtraCapabilities, manage) { t.Fatalf("approve: %d %s", code, raw) } ev := f.audit(t, "user.capability_granted") if len(ev) != 1 || ev[0].ActorID != "u-own" || ev[0].Metadata["requested_by"] != "u-admin" { t.Fatalf("approve audit: %+v", ev) } if code, _, _ := f.capCall(t, http.MethodPost, f.reqPath(reqID)+"/approve", "", as("u-own")); code != http.StatusNotFound { t.Errorf("an approved request is gone: %d", code) } // The member cannot approve their own; the requester withdraws by revoking. _, out, _ = f.capCall(t, http.MethodPost, f.capPath("u-fin"), `{"capability":"portal:infra.write"}`, asAdmin) if code, _, raw := f.capCall(t, http.MethodPost, f.reqPath(out.Request.ID)+"/approve", "", as("u-fin")); code != http.StatusConflict || errCode(raw) != "self" { t.Errorf("approving one's own: %d %s", code, raw) } if code, out, raw := f.capCall(t, http.MethodDelete, f.capPath("u-fin")+"/portal:infra.write", "", asAdmin); code != http.StatusOK || out.Status != "request_withdrawn" { t.Errorf("revoke a pending grant: %d %s", code, raw) } // Reject and withdraw. _, out, _ = f.capCall(t, http.MethodPost, f.capPath("u-cxo"), `{"capability":"werkmeister:connection.manage"}`, asAdmin) if code, out, raw := f.capCall(t, http.MethodDelete, f.reqPath(out.Request.ID), "", as("u-own")); code != http.StatusOK || out.Status != "request_rejected" { t.Errorf("reject: %d %s", code, raw) } _, out, _ = f.capCall(t, http.MethodPost, f.capPath("u-cxo"), `{"capability":"werkmeister:connection.manage"}`, asAdmin) if code, out, raw := f.capCall(t, http.MethodDelete, f.reqPath(out.Request.ID), "", asAdmin); code != http.StatusOK || out.Status != "request_withdrawn" { t.Errorf("withdraw: %d %s", code, raw) } if ev := f.audit(t, "user.capability_request_rejected"); len(ev) != 1 || ev[0].TargetName != "cxo@acme.test" { t.Errorf("reject audit: %+v", ev) } if code, _, _ := f.capCall(t, http.MethodDelete, f.reqPath("00000000-0000-0000-0000-000000000000"), "", asAdmin); code != http.StatusNotFound { t.Errorf("unknown request: %d", code) } // A member who left: their request is dropped at approval. _, out, _ = f.capCall(t, http.MethodPost, f.capPath("u-cxo"), `{"capability":"werkmeister:connection.manage"}`, asAdmin) f.kc.Members["acme"] = slices.DeleteFunc(f.kc.Members["acme"], func(m keycloak.OrgMember) bool { return m.UserID == "u-cxo" }) if code, _, raw := f.capCall(t, http.MethodPost, f.reqPath(out.Request.ID)+"/approve", "", as("u-own")); code != http.StatusNotFound || errCode(raw) != "not_a_member" { t.Errorf("left: %d %s", code, raw) } if reqs, _ := f.s.Store.ListCapabilityRequests(context.Background(), f.tenant.ID); len(reqs) != 0 { t.Errorf("left member's request kept: %+v", reqs) } // Removing a member drops their open requests. f.capCall(t, http.MethodPost, f.capPath("u-fin"), `{"capability":"portal:infra.write"}`, asAdmin) if code, _, raw := f.call(t, http.MethodDelete, f.memberPath("u-fin"), "", asAdmin); code != http.StatusOK { t.Fatalf("remove: %d %s", code, raw) } if reqs, _ := f.s.Store.ListCapabilityRequests(context.Background(), f.tenant.ID); len(reqs) != 0 { t.Errorf("removed member's request kept: %+v", reqs) } } func TestCapabilities_userTokens(t *testing.T) { // A person's own token: the registry still asks for a tenant-admin role // first (teamTenantFromUser), then applies the same rules. user := &authn.Principal{Subject: "u-cxo", ClientID: "portal", TenantID: "", OrgRoles: []string{"CXO"}} f := capFixture(t, user) user.TenantID = f.tenant.ID user.Email = "cxo@acme.test" if code, _, raw := f.capCall(t, http.MethodPost, f.capPath("u-fin"), `{"capability":"portal:infra.view"}`, nil); code != http.StatusForbidden { t.Errorf("CXO token: %d %s", code, raw) } admin := &authn.Principal{Subject: "u-admin", ClientID: "portal", Email: "admin@acme.test", OrgRoles: []string{"IT_ADMIN"}} f = capFixture(t, admin) admin.TenantID = f.tenant.ID if code, out, raw := f.capCall(t, http.MethodPost, f.capPath("u-fin"), `{"capability":"portal:infra.view"}`, nil); code != http.StatusOK || out.Status != "capability_granted" { t.Errorf("admin token: %d %s", code, raw) } rr := httptest.NewRecorder() f.h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+f.tenant.ID+"/capability-requests", nil)) if rr.Code != http.StatusOK { t.Errorf("admin token list: %d %s", rr.Code, rr.Body.String()) } }