Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014aRnCGqELxoix5TfpX8Ejf
233 lines
11 KiB
Go
233 lines
11 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/roles"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
|
)
|
|
|
|
// roleFixture: tenant acme, the stage AUTHZ_RULES shape, and principals by
|
|
// name: the portal's sign-in client for users, its service client, and
|
|
// Werkmeister's service client.
|
|
type roleFixture struct {
|
|
s *Server
|
|
h http.Handler
|
|
tenant *store.Tenant
|
|
as map[string]*authn.Principal
|
|
}
|
|
|
|
func newRoleFixture(t *testing.T) *roleFixture {
|
|
t.Helper()
|
|
mem := store.NewMemory()
|
|
tenant, _ := mem.GetTenantBySlug(context.Background(), "acme")
|
|
other, err := mem.CreateTenant(context.Background(), store.TenantCreate{Slug: "other", Name: "Other"})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
user := func(sub, tenantID string, roles ...string) *authn.Principal {
|
|
return &authn.Principal{Subject: sub, ClientID: "portal-stage", TenantID: tenantID, Email: sub + "@acme.test", OrgRoles: roles}
|
|
}
|
|
f := &roleFixture{tenant: tenant, as: map[string]*authn.Principal{
|
|
"signup": user("u-signup", tenant.ID, "CXO"),
|
|
"itadmin": user("u-it", tenant.ID, "IT_ADMIN"),
|
|
"ceo": user("u-ceo", tenant.ID, "CXO"),
|
|
"staff": user("u-staff", tenant.ID, "USER"),
|
|
"stranger": user("u-x", other.ID, "CXO"),
|
|
"portal": {Subject: "svc-portal", ClientID: "portal-svc"},
|
|
"werkmeister": {Subject: "svc-wm", ClientID: "werkmeister-svc"},
|
|
}}
|
|
f.s = &Server{Log: slog.New(slog.NewTextHandler(io.Discard, nil)), Store: mem, Keycloak: keycloak.NewMock(),
|
|
Authz: ParseAuthzRules("portal-svc:tenants,users;portal-stage:role-dataset.user;werkmeister-svc:tenants.read")}
|
|
router := NewRouter(f.s)
|
|
f.h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if p := f.as[r.Header.Get("X-Test-As")]; p != nil {
|
|
r = r.WithContext(authn.WithPrincipal(r.Context(), p))
|
|
}
|
|
router.ServeHTTP(w, r)
|
|
})
|
|
return f
|
|
}
|
|
|
|
func (f *roleFixture) do(t *testing.T, as, method, path, body string, hdr ...string) (int, map[string]any, string) {
|
|
t.Helper()
|
|
var rd io.Reader
|
|
if body != "" {
|
|
rd = strings.NewReader(body)
|
|
}
|
|
req := httptest.NewRequest(method, path, rd)
|
|
req.Header.Set("X-Test-As", as)
|
|
for i := 0; i+1 < len(hdr); i += 2 {
|
|
req.Header.Set(hdr[i], hdr[i+1])
|
|
}
|
|
rr := httptest.NewRecorder()
|
|
f.h.ServeHTTP(rr, req)
|
|
var out map[string]any
|
|
_ = json.Unmarshal(rr.Body.Bytes(), &out)
|
|
return rr.Code, out, rr.Body.String()
|
|
}
|
|
|
|
func (f *roleFixture) path(sub string) string {
|
|
return "/v1/tenants/" + f.tenant.ID + "/role-dataset" + sub
|
|
}
|
|
|
|
func saveBody(data string, expected int, authorize ...string) string {
|
|
a, _ := json.Marshal(authorize)
|
|
if authorize == nil {
|
|
a = []byte("[]")
|
|
}
|
|
return `{"catalogue_version":"` + roles.CatalogueVersion + `","expected_revision":` + itoa(expected) + `,"authorize":` + string(a) + `,"data":` + data + `}`
|
|
}
|
|
|
|
const (
|
|
mgmtOnly = `{"assignments":[{"id":"a-ceo","function":"r1.geschaeftsleitung","holder":{"kind":"member","sub":"u-ceo"},"scope":null}]}`
|
|
withDeputyDS = `{"assignments":[{"id":"a-ceo","function":"r1.geschaeftsleitung","holder":{"kind":"member","sub":"u-ceo"},"scope":null}],` +
|
|
`"deputies":[{"id":"d-1","function":"r1.geschaeftsleitung","holder":{"kind":"member","sub":"u-staff"},"scope":null,` +
|
|
`"decision_types":["r1.release_d01"],"basis":{"text":"Vertretungsregelung"},"may_edit":false,"authorized_by":"u-ceo"}]}`
|
|
)
|
|
|
|
func TestRoleDataset_lifecycle(t *testing.T) {
|
|
f := newRoleFixture(t)
|
|
|
|
code, out, raw := f.do(t, "werkmeister", "GET", f.path(""), "")
|
|
if code != http.StatusOK || out["revision"].(float64) != 0 || out["catalogue"] == nil {
|
|
t.Fatalf("empty dataset: %d %s", code, raw)
|
|
}
|
|
if code, _, raw := f.do(t, "signup", "PUT", f.path(""), `{"catalogue_version":"`+roles.CatalogueVersion+`","data":{}}`); code != http.StatusBadRequest || !strings.Contains(raw, "expected_revision_required") {
|
|
t.Fatalf("without expected_revision: %d %s", code, raw)
|
|
}
|
|
if code, _, raw := f.do(t, "signup", "PUT", f.path(""), strings.Replace(saveBody(mgmtOnly, 0), roles.CatalogueVersion, "r1-old", 1)); code != http.StatusConflict || !strings.Contains(raw, "catalogue_outdated") {
|
|
t.Fatalf("old catalogue: %d %s", code, raw)
|
|
}
|
|
// The technical admin does not name management.
|
|
if code, _, raw := f.do(t, "itadmin", "PUT", f.path(""), saveBody(mgmtOnly, 0)); code != http.StatusForbidden || !strings.Contains(raw, "not_permitted") {
|
|
t.Fatalf("IT_ADMIN bootstrap: %d %s", code, raw)
|
|
}
|
|
// First entry by the CXO sign-in role: management only.
|
|
code, out, raw = f.do(t, "signup", "PUT", f.path(""), saveBody(mgmtOnly, 0))
|
|
if code != http.StatusOK || out["revision"].(float64) != 1 || out["updated_by"] != "u-signup" {
|
|
t.Fatalf("bootstrap: %d %s", code, raw)
|
|
}
|
|
if code, _, raw := f.do(t, "ceo", "PUT", f.path(""), saveBody(mgmtOnly, 0)); code != http.StatusConflict || !strings.Contains(raw, "revision_conflict") {
|
|
t.Fatalf("stale revision: %d %s", code, raw)
|
|
}
|
|
if code, _, raw := f.do(t, "staff", "PUT", f.path(""), saveBody(withDeputyDS, 1)); code != http.StatusForbidden || !strings.Contains(raw, "not_permitted") {
|
|
t.Fatalf("person without function: %d %s", code, raw)
|
|
}
|
|
// Management records a deputy: the body's authorized_by is ignored, the
|
|
// save itself is the authorization (B7).
|
|
code, out, raw = f.do(t, "ceo", "PUT", f.path(""), saveBody(withDeputyDS, 1))
|
|
if code != http.StatusOK || out["revision"].(float64) != 2 {
|
|
t.Fatalf("deputy: %d %s", code, raw)
|
|
}
|
|
data := out["data"].(map[string]any)
|
|
dep := data["deputies"].([]any)[0].(map[string]any)
|
|
if dep["recorded_by"] != "u-ceo" || dep["authorized_by"] != "u-ceo" {
|
|
t.Fatalf("stamps: %v", dep)
|
|
}
|
|
states := out["derived"].(map[string]any)["deputies"].([]any)
|
|
if states[0].(map[string]any)["state"] != roles.StateEffective {
|
|
t.Fatalf("derived: %v", states)
|
|
}
|
|
// Saving the same again creates no revision.
|
|
if code, out, _ := f.do(t, "ceo", "PUT", f.path(""), saveBody(withDeputyDS, 2)); code != http.StatusOK || out["revision"].(float64) != 2 {
|
|
t.Fatalf("unchanged save: %d %v", code, out["revision"])
|
|
}
|
|
|
|
code, out, raw = f.do(t, "werkmeister", "GET", f.path("/resolve?decision_type=r1.release_d01"), "")
|
|
if code != http.StatusOK || out["status"] != roles.StatusFilled || out["revision"].(float64) != 2 || len(out["deputies"].([]any)) != 1 {
|
|
t.Fatalf("resolve: %d %s", code, raw)
|
|
}
|
|
if code, out, _ := f.do(t, "werkmeister", "GET", f.path("/resolve?decision_type=r1.escalation"), ""); code != http.StatusOK || out["status"] != roles.StatusOpen {
|
|
t.Fatalf("unset decision type: %d %v", code, out)
|
|
}
|
|
if code, _, _ := f.do(t, "werkmeister", "GET", f.path("/resolve?decision_type=r1.nope"), ""); code != http.StatusBadRequest {
|
|
t.Fatalf("unknown decision type: %d", code)
|
|
}
|
|
code, out, raw = f.do(t, "werkmeister", "GET", f.path("/revisions/1"), "")
|
|
if code != http.StatusOK || out["revision"].(float64) != 1 || out["updated_by"] != "u-signup" {
|
|
t.Fatalf("revision 1: %d %s", code, raw)
|
|
}
|
|
if code, _, _ := f.do(t, "werkmeister", "GET", f.path("/revisions/9"), ""); code != http.StatusNotFound {
|
|
t.Fatalf("unknown revision: %d", code)
|
|
}
|
|
|
|
items, _, err := f.s.Store.ListAudit(context.Background(), store.AuditFilter{TenantID: f.tenant.ID, Action: "role_dataset.saved"})
|
|
if err != nil || len(items) != 2 {
|
|
t.Fatalf("audit: %v %v", items, err)
|
|
}
|
|
ev := items[0]
|
|
if ev.ActorID != "u-ceo" {
|
|
ev = items[1]
|
|
}
|
|
b, _ := json.Marshal(ev.Metadata)
|
|
if ev.ActorID != "u-ceo" || ev.ActorType != "user" || !strings.Contains(string(b), `"deputies":["d-1"]`) || strings.Contains(string(b), "Vertretungsregelung") {
|
|
t.Fatalf("audit entry: %+v %s", ev, b)
|
|
}
|
|
}
|
|
|
|
func TestRoleDataset_writesNeedTheUsersToken(t *testing.T) {
|
|
f := newRoleFixture(t)
|
|
// The portal's service client, naming a user: refused, the header counts for nothing.
|
|
if code, _, raw := f.do(t, "portal", "PUT", f.path(""), saveBody(mgmtOnly, 0), headerPortalUserSubject, "u-signup"); code != http.StatusForbidden || !strings.Contains(raw, "user_token_required") {
|
|
t.Fatalf("service token write: %d %s", code, raw)
|
|
}
|
|
// Werkmeister reads but cannot write (tenants.read only).
|
|
if code, _, _ := f.do(t, "werkmeister", "PUT", f.path(""), saveBody(mgmtOnly, 0)); code != http.StatusForbidden {
|
|
t.Fatalf("werkmeister write: %d", code)
|
|
}
|
|
// A user of another tenant sees nothing.
|
|
if code, _, _ := f.do(t, "stranger", "GET", f.path(""), ""); code != http.StatusNotFound {
|
|
t.Fatalf("cross-tenant read: %d", code)
|
|
}
|
|
if code, _, _ := f.do(t, "stranger", "PUT", f.path(""), saveBody(mgmtOnly, 0)); code != http.StatusNotFound {
|
|
t.Fatalf("cross-tenant write: %d", code)
|
|
}
|
|
// The portal's sign-in client reaches the role dataset only.
|
|
if code, _, _ := f.do(t, "ceo", "GET", f.path(""), ""); code != http.StatusOK {
|
|
t.Fatalf("user read: %d", code)
|
|
}
|
|
if code, _, raw := f.do(t, "ceo", "GET", "/v1/tenants/"+f.tenant.ID+"/members", ""); code != http.StatusForbidden || !strings.Contains(raw, "FORBIDDEN_CLIENT") {
|
|
t.Fatalf("user token elsewhere: %d %s", code, raw)
|
|
}
|
|
if code, _, raw := f.do(t, "ceo", "GET", "/v1/tenants/"+f.tenant.ID+"/company-profile", ""); code != http.StatusForbidden || !strings.Contains(raw, "FORBIDDEN_CLIENT") {
|
|
t.Fatalf("user token on the company profile: %d %s", code, raw)
|
|
}
|
|
// B8 through the API.
|
|
if code, _, _ := f.do(t, "signup", "PUT", f.path(""), saveBody(mgmtOnly, 0)); code != http.StatusOK {
|
|
t.Fatal("bootstrap")
|
|
}
|
|
b8 := `{"assignments":[{"id":"a-ceo","function":"r1.geschaeftsleitung","holder":{"kind":"member","sub":"u-ceo"},"scope":null}],"authority":[{"decision_type":"r1.release_d02_update","function":"r1.freigabestelle"}]}`
|
|
if code, _, raw := f.do(t, "ceo", "PUT", f.path(""), saveBody(b8, 1)); code != http.StatusBadRequest || !strings.Contains(raw, "d02_reference_required") {
|
|
t.Fatalf("B8: %d %s", code, raw)
|
|
}
|
|
if code, _, raw := f.do(t, "ceo", "PUT", f.path(""), saveBody(`{"assignments":[],"owner":"x"}`, 1)); code != http.StatusBadRequest || !strings.Contains(raw, "invalid_role_dataset") {
|
|
t.Fatalf("unknown key: %d %s", code, raw)
|
|
}
|
|
}
|
|
|
|
func TestRoleDatasetPath(t *testing.T) {
|
|
for path, want := range map[string]bool{
|
|
"/v1/tenants/x/role-dataset": true,
|
|
"/v1/tenants/x/role-dataset/resolve": true,
|
|
"/v1/tenants/x/role-dataset/revisions/2": true,
|
|
"/v1/tenants/x/members": false,
|
|
"/v1/tenants/role-dataset": false,
|
|
"/v1/admin/tenants/x/role-dataset": false,
|
|
"/v1/tenants/x/projects/role-dataset/targets": false,
|
|
} {
|
|
if got := isRoleDatasetPath(path); got != want {
|
|
t.Errorf("%s: %v", path, got)
|
|
}
|
|
}
|
|
}
|