fix(keycloak): KC 26 org member body is the bare user id; set org tenant_id (#27)
ci / shared (push) Successful in 13s
ci / test (push) Successful in 21m54s
ci / image (push) Successful in 22s

This commit was merged in pull request #27.
This commit is contained in:
sharang committed 2026-09-12 09:39:27 +00:00
1 parent 8388e47742
commit 8f5c9ba0b9
2 files changed
+84 -12

No files matched your search

+33 -10
View File
@@ -17,15 +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
emailCalls atomic.Int32
healthCalls atomic.Int32
syncCalls atomic.Int32
lastOrgBody string
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
tokenFails atomic.Bool // when true, /token returns 401 once
}
@@ -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())
}
+51 -2
View File
@@ -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)
}