Skip to content

Commit d2551b6

Browse files
authored
fix(keycloak): keep KeycloakRealmUser roles when spec.roles is unset (#3531)
<!-- Thank you for making a contribution! Here are some tips for you: - Use Conventional Commits for the PR title: `type(scope): description` - Types: feat, fix, docs, style, refactor, perf, test, build, ci, chore - Scopes are not an exhaustive list — pick the most specific scope for the change and extend the list when a genuinely new area appears. Examples: - System components: dashboard, platform, operator, cilium, kube-ovn, linstor, fluxcd, cluster-api - Managed apps: postgres, mariadb, redis, kafka, clickhouse, virtual-machine, kubernetes - Development and maintenance: api, hack, tests, ci, docs, maintenance - Breaking changes: append `!` after type/scope (`feat(api)!: ...`) or add a `BREAKING CHANGE:` footer - If it's a work in progress, consider creating this PR as a draft. - Don't hesistate to ask for opinion and review in the community chats, even if it's still a draft. - Add the label `backport` if it's a bugfix that needs to be backported to a previous version. --> ## What this PR does The vendored keycloak-operator image is built from a pinned upstream commit with `images/keycloak-operator/patches/*.diff` applied at build time. This patch is a backport of epam/edp-keycloak-operator#372 onto that pin, so it is dropped in the same commit that moves `COMMIT_REF` past the upstream merge. The bug is epam/edp-keycloak-operator#371. Under the default `full` strategy the operator treats `spec.roles` and `spec.clientRoles[].roles` as authoritative sets: after adding what is missing, it deletes every mapping the spec does not list. A resource that manages the user record and leaves those fields out therefore loses all of its realm roles on the first reconcile, `default-roles-<realm>` included, and with it `offline_access`, `uma_authorization` and the `account` client roles. The user keeps logging in and stops being able to do anything. Upstream fixes this in two halves that only work together. The controller returns early when the desired list is nil, so an omitted field means "not managed" while an explicit `roles: []` keeps its meaning of "remove every role". The json tags on `Roles` and `ClientRoles[].Roles` lose `omitempty`, because with it an explicit empty list is erased the first time the operator writes the object back, which adding its own finalizer already does, and comes back indistinguishable from an omitted field. Take that half away and the distinction holds only until the operator next touches the object. All eight files from the upstream PR are here. Six apply to the pin unchanged. `sync_user_roles.go` and its test are rewritten against the pinned context, where the generated client package is still named `keycloakv2` (upstream renamed it to `keycloakapi` after the pin, which is the only reason those two do not apply as-is). Tests match upstream: four controller cases for unset and empty realm and client roles, two in `api/v1` for the serialization round trip. Checked by extracting the pinned tarball, applying every `.diff` in the patches directory in the order the Dockerfile globs them, then `go build ./...` and `go test ./internal/controller/keycloakrealmuser/... ./api/...`, all green. Reverting each of the three conditions in turn fails exactly the tests that cover it, and nothing else. One caveat a reader deserves up front: this patch does not reach any cluster yet. No CI path rebuilds this package, so `hack/build-matrix.sh` returns an empty matrix for a change confined to it, and `values.yaml` keeps pointing at an image built by hand in March. The same happened to `9c5fbb69a` and `5b9b420ff`, which edited this Dockerfile and left the pin alone, so the running binary is already older than the tree says. That gap is tracked in #3416 and is deliberately not addressed here: the fix for it is a choice between adding these packages to the build list and dropping the in-repo build, and the first option wakes a known mirror gap for split-host references. Landing the patch now means it is in place the moment that is resolved. ### Screenshots <!-- REQUIRED for UI changes: attach screenshots or screen recordings demonstrating the visual impact of your changes. PRs with UI changes without screenshots will not be merged. --> Not a UI change. ### Downstream repositories <!-- Cozystack is upstream for repositories that are NOT kept in sync with it automatically, and nothing in CI compares the two sides, so a change here can break them silently. Which change forces what, and which file to touch, is the trigger map in docs/agents/contributing.md under "Downstream Repositories". Walk it before you tick anything. IF YOU ARE AN AI AGENT OR AN LLM, THIS IS PART OF THE TASK, NOT A FORM TO FILL IN: 1. Walk the trigger map against the actual diff of this PR, file by file. Do not decide from the PR title or from your memory of what you changed. 2. For every repository you tick, open the follow-up PR there and link it on the same line. A ticked box with no link claims work that does not exist, which is worse than an empty box. Search that repository for an open PR or issue covering it first, and link that instead of filing a duplicate. 3. When the follow-up is out of scope, or needs a decision that is not yours to make, open an issue in that repository instead, link that, and say so in the PR body. Do not push a speculative PR into another repository just to fill a line here. 4. Do not tick "No downstream repository is affected" to make the checklist go away. If you are unsure, leave every box empty and say so in the PR body, so a human decides. --> Walked the trigger map against the diff. It touches one build-time patch file under `packages/system/keycloak-operator/images/`, adds no package under `packages/apps/` or `packages/extra/`, and changes no values key, schema, enum, default, CRD, `ApplicationDefinition`, namespace, label, annotation, metric, release asset, variant or node prerequisite. Nothing in the map fires. - [x] No downstream repository is affected by this change - [ ] [cozystack/website](https://github.com/cozystack/website) - follow-up: - [ ] [cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack) - follow-up: - [ ] [cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack) - follow-up: - [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up: - [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up: - [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) - follow-up: - [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) - follow-up: - [ ] [cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server) - follow-up: - [ ] [cozystack/external-apps-example](https://github.com/cozystack/external-apps-example) - follow-up: - [ ] [cozystack/examples](https://github.com/cozystack/examples) - follow-up: ### Release note <!-- Write a release note: - Explain what has changed internally and for users. - Start with the same `type(scope):` prefix as in the PR title - Follow the guidelines at https://github.com/kubernetes/community/blob/master/contributors/guide/release-notes.md. --> ```release-note fix(keycloak): a `KeycloakRealmUser` that omits `spec.roles` or leaves `roles` out of a `spec.clientRoles` entry no longer has the matching Keycloak role mappings deleted under the default `full` reconciliation strategy. Users keep `default-roles-<realm>` and the `offline_access`, `uma_authorization` and `account` roles it grants. Setting an explicit empty list still removes every role. ``` <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved Keycloak role management for realm users and client roles. * Leaving a role list unspecified now preserves existing roles. * Explicitly providing an empty role list now removes all assigned roles. * **Documentation** * Updated API and resource documentation to clarify role-list behavior. * **Tests** * Added coverage for omitted, empty, managed, and unmanaged role configurations. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
2 parents 3d4e8c0 + 5f8a820 commit d2551b6

1 file changed

Lines changed: 343 additions & 0 deletions

File tree

Lines changed: 343 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,343 @@
1+
Backport of epam/edp-keycloak-operator#372 (https://github.com/epam/edp-keycloak-operator/pull/372), which fixes epam/edp-keycloak-operator#371 (https://github.com/epam/edp-keycloak-operator/issues/371): a KeycloakRealmUser that leaves spec.roles out gets every realm role stripped from the Keycloak user, including the default-roles-<realm> that Keycloak grants on creation. After the fix an omitted list means "not managed", and an explicit empty list still removes everything.
2+
3+
Dropping omitempty from the json tags is the other half of the fix. Without it an explicit "roles: []" disappears the first time the operator writes the object back (adding its own finalizer is enough) and comes back indistinguishable from an omitted field, so the nil-vs-empty distinction does not survive a round trip.
4+
5+
Applies to: epam/edp-keycloak-operator @ facbc36, pinned as COMMIT_REF in the Dockerfile one level up.
6+
7+
Six of the eight files are taken from the upstream PR unchanged. internal/controller/keycloakrealmuser/chain/sync_user_roles.go and its test carry the same change rewritten against facbc36, where the generated client package is still called keycloakv2. Upstream renamed it to keycloakapi in b611ea75, after this pin.
8+
9+
Drop this file when COMMIT_REF moves past the upstream merge commit.
10+
11+
diff --git a/api/v1/keycloakclient_types.go b/api/v1/keycloakclient_types.go
12+
index 28df6eb..74100c6 100644
13+
--- a/api/v1/keycloakclient_types.go
14+
+++ b/api/v1/keycloakclient_types.go
15+
@@ -237,7 +237,7 @@ type UserClientRole struct {
16+
// Roles is a list of client roles names assigned to user.
17+
// +nullable
18+
// +optional
19+
- Roles []string `json:"roles,omitempty"`
20+
+ Roles []string `json:"roles"` // no omitempty: an empty list has to stay distinguishable from an omitted one
21+
}
22+
23+
type ClientRole struct {
24+
diff --git a/api/v1/keycloakrealmuser_types.go b/api/v1/keycloakrealmuser_types.go
25+
index 5773150..541b8b8 100644
26+
--- a/api/v1/keycloakrealmuser_types.go
27+
+++ b/api/v1/keycloakrealmuser_types.go
28+
@@ -40,12 +40,16 @@ type KeycloakRealmUserSpec struct {
29+
// +optional
30+
RequiredUserActions []string `json:"requiredUserActions,omitempty"`
31+
32+
- // Roles is a list of roles assigned to user.
33+
+ // Roles is a list of realm roles assigned to user.
34+
+ // Omitting the field, or setting it to null, leaves the realm roles the user already has untouched,
35+
+ // including the defaults Keycloak grants on creation.
36+
+ // An explicit empty list removes every realm role from the user.
37+
// +nullable
38+
// +optional
39+
- Roles []string `json:"roles,omitempty"`
40+
+ Roles []string `json:"roles"` // no omitempty: an empty list has to stay distinguishable from an omitted one
41+
42+
// ClientRoles is a list of client roles assigned to user.
43+
+ // The same rule as for Roles applies per client: omitting an entry's roles list leaves that client's roles untouched, an empty list removes all of them.
44+
// +nullable
45+
// +optional
46+
ClientRoles []UserClientRole `json:"clientRoles,omitempty"`
47+
diff --git a/api/v1/keycloakrealmuser_types_test.go b/api/v1/keycloakrealmuser_types_test.go
48+
new file mode 100644
49+
index 0000000..18eae79
50+
--- /dev/null
51+
+++ b/api/v1/keycloakrealmuser_types_test.go
52+
@@ -0,0 +1,55 @@
53+
+package v1
54+
+
55+
+import (
56+
+ "encoding/json"
57+
+ "testing"
58+
+
59+
+ "github.com/stretchr/testify/assert"
60+
+ "github.com/stretchr/testify/require"
61+
+)
62+
+
63+
+// The user controller reads an omitted role list as "not managed" and an empty one as "remove
64+
+// every role". The controller also rewrites the whole resource when it adds its finalizer or
65+
+// migrates attributes, so an empty list has to survive a marshal/unmarshal cycle: with omitempty
66+
+// on the json tag it would come back as omitted and silently downgrade to "not managed".
67+
+func TestKeycloakRealmUserSpec_EmptyRoleListsSurviveSerialization(t *testing.T) {
68+
+ spec := KeycloakRealmUserSpec{
69+
+ Username: "testuser",
70+
+ Roles: []string{},
71+
+ ClientRoles: []UserClientRole{
72+
+ {ClientID: "client1", Roles: []string{}},
73+
+ },
74+
+ }
75+
+
76+
+ raw, err := json.Marshal(spec)
77+
+ require.NoError(t, err)
78+
+
79+
+ var decoded KeycloakRealmUserSpec
80+
+
81+
+ require.NoError(t, json.Unmarshal(raw, &decoded))
82+
+
83+
+ assert.NotNil(t, decoded.Roles, "empty spec.roles must not decode back as omitted")
84+
+ assert.Empty(t, decoded.Roles)
85+
+
86+
+ require.Len(t, decoded.ClientRoles, 1)
87+
+ assert.NotNil(t, decoded.ClientRoles[0].Roles, "empty spec.clientRoles[].roles must not decode back as omitted")
88+
+ assert.Empty(t, decoded.ClientRoles[0].Roles)
89+
+}
90+
+
91+
+// An omitted role list must stay omitted, so that "not managed" is not confused with "remove
92+
+// every role" in the other direction either.
93+
+func TestKeycloakRealmUserSpec_OmittedRoleListsStayOmitted(t *testing.T) {
94+
+ raw, err := json.Marshal(KeycloakRealmUserSpec{
95+
+ Username: "testuser",
96+
+ ClientRoles: []UserClientRole{{ClientID: "client1"}},
97+
+ })
98+
+ require.NoError(t, err)
99+
+
100+
+ var decoded KeycloakRealmUserSpec
101+
+
102+
+ require.NoError(t, json.Unmarshal(raw, &decoded))
103+
+
104+
+ assert.Nil(t, decoded.Roles)
105+
+ require.Len(t, decoded.ClientRoles, 1)
106+
+ assert.Nil(t, decoded.ClientRoles[0].Roles)
107+
+}
108+
diff --git a/config/crd/bases/v1.edp.epam.com_keycloakrealmusers.yaml b/config/crd/bases/v1.edp.epam.com_keycloakrealmusers.yaml
109+
index 80611b9..de2ab0d 100644
110+
--- a/config/crd/bases/v1.edp.epam.com_keycloakrealmusers.yaml
111+
+++ b/config/crd/bases/v1.edp.epam.com_keycloakrealmusers.yaml
112+
@@ -63,7 +63,9 @@ spec:
113+
nullable: true
114+
type: object
115+
clientRoles:
116+
- description: ClientRoles is a list of client roles assigned to user.
117+
+ description: |-
118+
+ ClientRoles is a list of client roles assigned to user.
119+
+ The same rule as for Roles applies per client: omitting an entry's roles list leaves that client's roles untouched, an empty list removes all of them.
120+
items:
121+
properties:
122+
clientId:
123+
@@ -177,7 +179,11 @@ spec:
124+
nullable: true
125+
type: array
126+
roles:
127+
- description: Roles is a list of roles assigned to user.
128+
+ description: |-
129+
+ Roles is a list of realm roles assigned to user.
130+
+ Omitting the field, or setting it to null, leaves the realm roles the user already has untouched,
131+
+ including the defaults Keycloak grants on creation.
132+
+ An explicit empty list removes every realm role from the user.
133+
items:
134+
type: string
135+
nullable: true
136+
diff --git a/deploy-templates/crds/v1.edp.epam.com_keycloakrealmusers.yaml b/deploy-templates/crds/v1.edp.epam.com_keycloakrealmusers.yaml
137+
index 80611b9..de2ab0d 100644
138+
--- a/deploy-templates/crds/v1.edp.epam.com_keycloakrealmusers.yaml
139+
+++ b/deploy-templates/crds/v1.edp.epam.com_keycloakrealmusers.yaml
140+
@@ -63,7 +63,9 @@ spec:
141+
nullable: true
142+
type: object
143+
clientRoles:
144+
- description: ClientRoles is a list of client roles assigned to user.
145+
+ description: |-
146+
+ ClientRoles is a list of client roles assigned to user.
147+
+ The same rule as for Roles applies per client: omitting an entry's roles list leaves that client's roles untouched, an empty list removes all of them.
148+
items:
149+
properties:
150+
clientId:
151+
@@ -177,7 +179,11 @@ spec:
152+
nullable: true
153+
type: array
154+
roles:
155+
- description: Roles is a list of roles assigned to user.
156+
+ description: |-
157+
+ Roles is a list of realm roles assigned to user.
158+
+ Omitting the field, or setting it to null, leaves the realm roles the user already has untouched,
159+
+ including the defaults Keycloak grants on creation.
160+
+ An explicit empty list removes every realm role from the user.
161+
items:
162+
type: string
163+
nullable: true
164+
diff --git a/docs/api.md b/docs/api.md
165+
index 9013abd..10adc8a 100644
166+
--- a/docs/api.md
167+
+++ b/docs/api.md
168+
@@ -7264,7 +7264,8 @@ Each attribute can have multiple values.<br/>
169+
<td><b><a href="#keycloakrealmuserspecclientrolesindex">clientRoles</a></b></td>
170+
<td>[]object</td>
171+
<td>
172+
- ClientRoles is a list of client roles assigned to user.<br/>
173+
+ ClientRoles is a list of client roles assigned to user.
174+
+The same rule as for Roles applies per client: omitting an entry's roles list leaves that client's roles untouched, an empty list removes all of them.<br/>
175+
</td>
176+
<td>false</td>
177+
</tr><tr>
178+
@@ -7365,7 +7366,10 @@ If set to full, user will be created if it does not exist, or updated if it exis
179+
<td><b>roles</b></td>
180+
<td>[]string</td>
181+
<td>
182+
- Roles is a list of roles assigned to user.<br/>
183+
+ Roles is a list of realm roles assigned to user.
184+
+Omitting the field, or setting it to null, leaves the realm roles the user already has untouched,
185+
+including the defaults Keycloak grants on creation.
186+
+An explicit empty list removes every realm role from the user.<br/>
187+
</td>
188+
<td>false</td>
189+
</tr></tbody>
190+
diff --git a/internal/controller/keycloakrealmuser/chain/sync_user_roles.go b/internal/controller/keycloakrealmuser/chain/sync_user_roles.go
191+
index 8a96543..3ef686d 100644
192+
--- a/internal/controller/keycloakrealmuser/chain/sync_user_roles.go
193+
+++ b/internal/controller/keycloakrealmuser/chain/sync_user_roles.go
194+
@@ -49,6 +49,14 @@ func (h *SyncUserRoles) syncRealmRoles(
195+
desiredRoleNames []string,
196+
addOnly bool,
197+
) error {
198+
+ // A nil desired list means the field was omitted, so the resource does not manage realm roles
199+
+ // at all and Keycloak is left alone. An empty but non-nil list still means "no roles" and
200+
+ // clears every mapping. Normalising the field anywhere upstream would silently turn
201+
+ // "not managed" into "delete everything".
202+
+ if desiredRoleNames == nil {
203+
+ return nil
204+
+ }
205+
+
206+
currentRoles, _, err := h.kClientV2.Users.GetUserRealmRoleMappings(ctx, realmName, userID)
207+
if err != nil {
208+
return fmt.Errorf("unable to get user realm role mappings: %w", err)
209+
@@ -113,6 +121,12 @@ func (h *SyncUserRoles) syncClientRoles(
210+
addOnly bool,
211+
) error {
212+
for _, cr := range clientRoles {
213+
+ // As in syncRealmRoles, an omitted role list means this client's roles are not managed,
214+
+ // which leaves nothing to do for the entry at all.
215+
+ if cr.Roles == nil {
216+
+ continue
217+
+ }
218+
+
219+
clients, _, err := h.kClientV2.Clients.GetClients(ctx, realmName, &keycloakv2.GetClientsParams{ClientId: &cr.ClientID})
220+
if err != nil {
221+
return fmt.Errorf("unable to get client %q: %w", cr.ClientID, err)
222+
diff --git a/internal/controller/keycloakrealmuser/chain/sync_user_roles_test.go b/internal/controller/keycloakrealmuser/chain/sync_user_roles_test.go
223+
index d7a3cb5..cd1286c 100644
224+
--- a/internal/controller/keycloakrealmuser/chain/sync_user_roles_test.go
225+
+++ b/internal/controller/keycloakrealmuser/chain/sync_user_roles_test.go
226+
@@ -97,6 +97,87 @@ func TestSyncUserRoles_Serve(t *testing.T) {
227+
},
228+
wantErr: require.NoError,
229+
},
230+
+ {
231+
+ name: "success - unset roles keep existing realm roles (full strategy)",
232+
+ user: &keycloakApi.KeycloakRealmUser{
233+
+ ObjectMeta: metav1.ObjectMeta{Name: "u", Namespace: "default"},
234+
+ Spec: keycloakApi.KeycloakRealmUserSpec{},
235+
+ },
236+
+ userCtx: &UserContext{UserID: "user-unset"},
237+
+ mockSetup: func(_ *v2mocks.MockUsersClient, _ *v2mocks.MockRolesClient, _ *v2mocks.MockClientsClient) {
238+
+ // Keycloak must not be touched at all: spec.roles is unset, so realm roles
239+
+ // (including the default-roles-<realm> Keycloak grants on creation) are unmanaged.
240+
+ },
241+
+ wantErr: require.NoError,
242+
+ },
243+
+ {
244+
+ name: "success - empty roles remove every realm role (full strategy)",
245+
+ user: &keycloakApi.KeycloakRealmUser{
246+
+ ObjectMeta: metav1.ObjectMeta{Name: "u", Namespace: "default"},
247+
+ Spec: keycloakApi.KeycloakRealmUserSpec{
248+
+ Roles: []string{},
249+
+ },
250+
+ },
251+
+ userCtx: &UserContext{UserID: "user-empty"},
252+
+ mockSetup: func(u *v2mocks.MockUsersClient, r *v2mocks.MockRolesClient, c *v2mocks.MockClientsClient) {
253+
+ u.EXPECT().GetUserRealmRoleMappings(context.Background(), "test-realm", "user-empty").
254+
+ Return([]keycloakv2.RoleRepresentation{
255+
+ {Id: ptr.To("id1"), Name: ptr.To("role1")},
256+
+ }, nil, nil)
257+
+ u.EXPECT().DeleteUserRealmRoles(context.Background(), "test-realm", "user-empty", []keycloakv2.RoleRepresentation{
258+
+ {Id: ptr.To("id1"), Name: ptr.To("role1")},
259+
+ }).Return(nil, nil)
260+
+ },
261+
+ wantErr: require.NoError,
262+
+ },
263+
+ {
264+
+ name: "success - unset client roles keep existing client roles (full strategy)",
265+
+ user: &keycloakApi.KeycloakRealmUser{
266+
+ ObjectMeta: metav1.ObjectMeta{Name: "u", Namespace: "default"},
267+
+ Spec: keycloakApi.KeycloakRealmUserSpec{
268+
+ ClientRoles: []keycloakApi.UserClientRole{
269+
+ {ClientID: "client-unset"},
270+
+ {ClientID: "client-managed", Roles: []string{"crole1"}},
271+
+ },
272+
+ },
273+
+ },
274+
+ userCtx: &UserContext{UserID: "user-unset-client"},
275+
+ mockSetup: func(u *v2mocks.MockUsersClient, _ *v2mocks.MockRolesClient, c *v2mocks.MockClientsClient) {
276+
+ // client-unset is skipped whole: not even looked up, so a stale or misspelled
277+
+ // clientId in an unmanaged entry cannot fail the reconciliation.
278+
+ c.EXPECT().GetClients(context.Background(), "test-realm", &keycloakv2.GetClientsParams{ClientId: ptr.To("client-managed")}).
279+
+ Return([]keycloakv2.ClientRepresentation{{Id: ptr.To("client-uuid-2")}}, nil, nil)
280+
+ u.EXPECT().GetUserClientRoleMappings(context.Background(), "test-realm", "user-unset-client", "client-uuid-2").
281+
+ Return([]keycloakv2.RoleRepresentation{
282+
+ {Id: ptr.To("crid1"), Name: ptr.To("crole1")},
283+
+ }, nil, nil)
284+
+ },
285+
+ wantErr: require.NoError,
286+
+ },
287+
+ {
288+
+ name: "success - empty client roles remove every client role (full strategy)",
289+
+ user: &keycloakApi.KeycloakRealmUser{
290+
+ ObjectMeta: metav1.ObjectMeta{Name: "u", Namespace: "default"},
291+
+ Spec: keycloakApi.KeycloakRealmUserSpec{
292+
+ ClientRoles: []keycloakApi.UserClientRole{
293+
+ {ClientID: "client-empty", Roles: []string{}},
294+
+ },
295+
+ },
296+
+ },
297+
+ userCtx: &UserContext{UserID: "user-empty-client"},
298+
+ mockSetup: func(u *v2mocks.MockUsersClient, _ *v2mocks.MockRolesClient, c *v2mocks.MockClientsClient) {
299+
+ c.EXPECT().GetClients(context.Background(), "test-realm", &keycloakv2.GetClientsParams{ClientId: ptr.To("client-empty")}).
300+
+ Return([]keycloakv2.ClientRepresentation{{Id: ptr.To("client-uuid-1")}}, nil, nil)
301+
+ u.EXPECT().GetUserClientRoleMappings(context.Background(), "test-realm", "user-empty-client", "client-uuid-1").
302+
+ Return([]keycloakv2.RoleRepresentation{
303+
+ {Id: ptr.To("crid1"), Name: ptr.To("crole1")},
304+
+ }, nil, nil)
305+
+ u.EXPECT().DeleteUserClientRoles(context.Background(), "test-realm", "user-empty-client", "client-uuid-1", []keycloakv2.RoleRepresentation{
306+
+ {Id: ptr.To("crid1"), Name: ptr.To("crole1")},
307+
+ }).Return(nil, nil)
308+
+ },
309+
+ wantErr: require.NoError,
310+
+ },
311+
{
312+
name: "success - sync client roles",
313+
user: &keycloakApi.KeycloakRealmUser{
314+
@@ -109,9 +190,6 @@ func TestSyncUserRoles_Serve(t *testing.T) {
315+
},
316+
userCtx: &UserContext{UserID: "user-4"},
317+
mockSetup: func(u *v2mocks.MockUsersClient, r *v2mocks.MockRolesClient, c *v2mocks.MockClientsClient) {
318+
- // no realm roles
319+
- u.EXPECT().GetUserRealmRoleMappings(context.Background(), "test-realm", "user-4").
320+
- Return(nil, nil, nil)
321+
// client lookup
322+
c.EXPECT().GetClients(context.Background(), "test-realm", &keycloakv2.GetClientsParams{ClientId: ptr.To("client1")}).
323+
Return([]keycloakv2.ClientRepresentation{{Id: ptr.To("client-uuid-1")}}, nil, nil)
324+
@@ -141,8 +219,6 @@ func TestSyncUserRoles_Serve(t *testing.T) {
325+
},
326+
userCtx: &UserContext{UserID: "user-5"},
327+
mockSetup: func(u *v2mocks.MockUsersClient, r *v2mocks.MockRolesClient, c *v2mocks.MockClientsClient) {
328+
- u.EXPECT().GetUserRealmRoleMappings(context.Background(), "test-realm", "user-5").
329+
- Return(nil, nil, nil)
330+
c.EXPECT().GetClients(context.Background(), "test-realm", &keycloakv2.GetClientsParams{ClientId: ptr.To("client1")}).
331+
Return([]keycloakv2.ClientRepresentation{{Id: ptr.To("client-uuid-1")}}, nil, nil)
332+
u.EXPECT().GetUserClientRoleMappings(context.Background(), "test-realm", "user-5", "client-uuid-1").
333+
@@ -206,9 +282,7 @@ func TestSyncUserRoles_Serve(t *testing.T) {
334+
},
335+
},
336+
userCtx: &UserContext{UserID: "user-err3"},
337+
- mockSetup: func(u *v2mocks.MockUsersClient, r *v2mocks.MockRolesClient, c *v2mocks.MockClientsClient) {
338+
- u.EXPECT().GetUserRealmRoleMappings(context.Background(), "test-realm", "user-err3").
339+
- Return(nil, nil, nil)
340+
+ mockSetup: func(_ *v2mocks.MockUsersClient, _ *v2mocks.MockRolesClient, c *v2mocks.MockClientsClient) {
341+
c.EXPECT().GetClients(context.Background(), "test-realm", &keycloakv2.GetClientsParams{ClientId: ptr.To("no-such-client")}).
342+
Return(nil, nil, nil)
343+
},

0 commit comments

Comments
 (0)