From b1156f259c7226a2e3db1a660ba200ff3c3e5690 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Sat, 12 Sep 2026 11:13:29 +0200 Subject: [PATCH 1/2] fix(keycloak): KC 26 org member body is the bare user id; set org tenant_id MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Live stage run: CreateOrgAndInvite created the org and the user but POST /organizations/{id}/members with {"id": …} answered 400 "User does not exist" — Keycloak 26 expects the id as a JSON string. Also writes the tenant_id attribute with a PUT after create (ignored on create). Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB --- internal/keycloak/client_test.go | 25 ++++++++++++++- internal/keycloak/orgs.go | 53 ++++++++++++++++++++++++++++++-- 2 files changed, 75 insertions(+), 3 deletions(-) diff --git a/internal/keycloak/client_test.go b/internal/keycloak/client_test.go index 8452ace..67b90bc 100644 --- a/internal/keycloak/client_test.go +++ b/internal/keycloak/client_test.go @@ -22,6 +22,7 @@ type stubKC struct { orgCalls atomic.Int32 userCalls atomic.Int32 memberCalls atomic.Int32 + orgAttrCalls atomic.Int32 emailCalls atomic.Int32 healthCalls atomic.Int32 syncCalls atomic.Int32 @@ -66,9 +67,31 @@ func newStubKC(t *testing.T) *stubKC { mux.HandleFunc("/admin/realms/test-realm/organizations/org-xyz/members", func(w http.ResponseWriter, r *http.Request) { s.memberCalls.Add(1) + // Keycloak 26 wants the bare user id as a JSON string. + var id string + if err := json.NewDecoder(r.Body).Decode(&id); err != nil || id != "user-abc" { + http.Error(w, `{"errorMessage":"User does not exist"}`, http.StatusBadRequest) + return + } w.WriteHeader(http.StatusCreated) }) + mux.HandleFunc("/admin/realms/test-realm/organizations/org-xyz", func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + _ = json.NewEncoder(w).Encode(map[string]any{"id": "org-xyz", "alias": "acme", "attributes": map[string]any{}}) + case http.MethodPut: + var org map[string]any + _ = json.NewDecoder(r.Body).Decode(&org) + if attrs, _ := org["attributes"].(map[string]any); attrs["tenant_id"] == nil { + http.Error(w, "missing tenant_id", http.StatusBadRequest) + return + } + s.orgAttrCalls.Add(1) + w.WriteHeader(http.StatusNoContent) + } + }) + mux.HandleFunc("/admin/realms/test-realm/users", func(w http.ResponseWriter, r *http.Request) { s.userCalls.Add(1) if r.Method == http.MethodPost { @@ -135,7 +158,7 @@ func TestHTTPAdapter_createOrgAndInvite(t *testing.T) { t.Errorf("unexpected ids: %+v", res) } if s.orgCalls.Load() != 1 || s.userCalls.Load() != 1 || - s.memberCalls.Load() != 1 || s.emailCalls.Load() != 1 { + s.memberCalls.Load() != 1 || s.emailCalls.Load() != 1 || s.orgAttrCalls.Load() != 1 { t.Errorf("call counts: org=%d user=%d member=%d email=%d", s.orgCalls.Load(), s.userCalls.Load(), s.memberCalls.Load(), s.emailCalls.Load()) } diff --git a/internal/keycloak/orgs.go b/internal/keycloak/orgs.go index 4db20e6..3979487 100644 --- a/internal/keycloak/orgs.go +++ b/internal/keycloak/orgs.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "io" + "log/slog" "net/http" "net/url" "path" @@ -95,6 +96,11 @@ func (a *HTTPAdapter) CreateOrgAndInvite(ctx context.Context, in InviteInput) (* return nil, fmt.Errorf("create org: missing Location and lookup failed: %w", err) } } + // Keycloak 26 ignores attributes on create; write them with a PUT so the + // org carries tenant_id (non-fatal: the alias stays the correlation key). + if err := a.ensureOrgAttributes(ctx, orgID, orgPayload.Attributes); err != nil { + slogWarn("keycloak org attributes not set", orgID, err) + } // 2. Create the user (disabled until they set a password). first, last := splitName(in.AdminName) @@ -137,9 +143,10 @@ func (a *HTTPAdapter) CreateOrgAndInvite(ctx context.Context, in InviteInput) (* } // 3. Add user to organization (member). - addBody := map[string]string{"id": userID} + // Keycloak 26: the member endpoint takes the bare user id as the JSON + // body (a string), not an object — an object yields "User does not exist". resp, err = a.adminCall(ctx, http.MethodPost, - fmt.Sprintf("/organizations/%s/members", orgID), addBody, nil) + fmt.Sprintf("/organizations/%s/members", orgID), userID, nil) if err != nil { return nil, fmt.Errorf("add member: %w", err) } @@ -329,3 +336,45 @@ func (a *HTTPAdapter) SyncTenantStatus(ctx context.Context, slug, status string) } return firstErr } + +// ensureOrgAttributes merges attrs into the organization representation. +func (a *HTTPAdapter) ensureOrgAttributes(ctx context.Context, orgID string, attrs map[string][]string) error { + var org map[string]any + resp, err := a.adminCall(ctx, http.MethodGet, "/organizations/"+orgID, nil, &org) + if err != nil { + return err + } + _ = resp.Body.Close() + if resp.StatusCode/100 != 2 || org == nil { + return fmt.Errorf("get org: %d", resp.StatusCode) + } + existing, _ := org["attributes"].(map[string]any) + if existing == nil { + existing = map[string]any{} + } + changed := false + for k, v := range attrs { + if _, ok := existing[k]; !ok { + existing[k] = v + changed = true + } + } + if !changed { + return nil + } + org["attributes"] = existing + resp, err = a.adminCall(ctx, http.MethodPut, "/organizations/"+orgID, org, nil) + if err != nil { + return err + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode/100 != 2 { + body, _ := io.ReadAll(resp.Body) + return fmt.Errorf("put org: %d %s", resp.StatusCode, body) + } + return nil +} + +func slogWarn(msg, orgID string, err error) { + slog.Warn(msg, "org_id", orgID, "err", err) +} -- 2.54.1 From 43e0fec9edeaaceef44cff48748a8561e51f8bec Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Sat, 12 Sep 2026 11:13:41 +0200 Subject: [PATCH 2/2] chore: gofmt Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB --- internal/keycloak/client_test.go | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/internal/keycloak/client_test.go b/internal/keycloak/client_test.go index 67b90bc..aafe069 100644 --- a/internal/keycloak/client_test.go +++ b/internal/keycloak/client_test.go @@ -17,16 +17,16 @@ import ( // paths the HTTPAdapter actually calls. Each path is a single handler that // asserts the request shape and returns the bare-minimum valid response. type stubKC struct { - srv *httptest.Server - tokenCalls atomic.Int32 - orgCalls atomic.Int32 - userCalls atomic.Int32 - memberCalls atomic.Int32 + srv *httptest.Server + tokenCalls atomic.Int32 + orgCalls atomic.Int32 + userCalls atomic.Int32 + memberCalls atomic.Int32 orgAttrCalls atomic.Int32 - emailCalls atomic.Int32 - healthCalls atomic.Int32 - syncCalls atomic.Int32 - lastOrgBody string + emailCalls atomic.Int32 + healthCalls atomic.Int32 + syncCalls atomic.Int32 + lastOrgBody string tokenFails atomic.Bool // when true, /token returns 401 once } -- 2.54.1