-
Notifications
You must be signed in to change notification settings - Fork 59
/
keycloak.go
408 lines (303 loc) · 10.5 KB
/
keycloak.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
package syncer
import (
"context"
"crypto/tls"
"fmt"
"net/url"
"strings"
"crypto/x509"
"github.com/Nerzal/gocloak/v13"
userv1 "github.com/openshift/api/user/v1"
redhatcopv1alpha1 "github.com/redhat-cop/group-sync-operator/api/v1alpha1"
"github.com/redhat-cop/group-sync-operator/pkg/constants"
"github.com/redhat-cop/operator-utils/pkg/util"
corev1 "k8s.io/api/core/v1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/validation"
logf "sigs.k8s.io/controller-runtime/pkg/log"
)
const (
masterRealm = "master"
)
var (
keycloakLogger = logf.Log.WithName("syncer_keycloak")
truthy = true
iterationMax = 100
)
type KeycloakSyncer struct {
Name string
GroupSync *redhatcopv1alpha1.GroupSync
Provider *redhatcopv1alpha1.KeycloakProvider
GoCloak *gocloak.GoCloak
Context context.Context
URL *url.URL
Token *gocloak.JWT
CachedGroups map[string]*gocloak.Group
CachedGroupMembers map[string][]*gocloak.User
ReconcilerBase util.ReconcilerBase
CredentialsSecret *corev1.Secret
CaCertificate []byte
}
func (k *KeycloakSyncer) Init() bool {
k.Context = context.Background()
changed := false
k.CachedGroupMembers = make(map[string][]*gocloak.User)
k.CachedGroups = make(map[string]*gocloak.Group)
if k.Provider.LoginRealm == "" {
k.Provider.LoginRealm = masterRealm
changed = true
}
if k.Provider.Scope == "" {
k.Provider.Scope = redhatcopv1alpha1.SubSyncScope
changed = true
}
return changed
}
func (k *KeycloakSyncer) Validate() error {
validationErrors := []error{}
// Verify Secret Containing Username and Password Exists with Valid Keys
credentialsSecret := &corev1.Secret{}
err := k.ReconcilerBase.GetClient().Get(context.TODO(), types.NamespacedName{Name: k.Provider.CredentialsSecret.Name, Namespace: k.Provider.CredentialsSecret.Namespace}, credentialsSecret)
if err != nil {
validationErrors = append(validationErrors, err)
} else {
// Username key validation
if _, found := credentialsSecret.Data[secretUsernameKey]; !found {
validationErrors = append(validationErrors, fmt.Errorf("Could not find 'username' key in secret '%s' in namespace '%s'", k.Provider.CredentialsSecret.Name, k.Provider.CredentialsSecret.Namespace))
}
// Password key validation
if _, found := credentialsSecret.Data[secretPasswordKey]; !found {
validationErrors = append(validationErrors, fmt.Errorf("Could not find 'password' key in secret '%s' in namespace '%s'", k.Provider.CredentialsSecret.Name, k.Provider.CredentialsSecret.Namespace))
}
k.CredentialsSecret = credentialsSecret
}
if k.URL, err = url.ParseRequestURI(k.Provider.URL); err != nil {
validationErrors = append(validationErrors, err)
}
providerCaResource := determineFromDeprecatedObjectRef(k.Provider.Ca, k.Provider.CaSecret)
if providerCaResource != nil {
caResource, err := getObjectRefData(k.Context, k.ReconcilerBase.GetClient(), providerCaResource)
if err != nil {
validationErrors = append(validationErrors, err)
}
var resourceCaKey string
if providerCaResource.Key != "" {
resourceCaKey = providerCaResource.Key
} else {
resourceCaKey = defaultResourceCaKey
}
// Certificate key validation
if _, found := caResource[resourceCaKey]; !found {
validationErrors = append(validationErrors, fmt.Errorf("Could not find '%s' key in %s '%s' in namespace '%s'", resourceCaKey, providerCaResource.Kind, providerCaResource.Name, providerCaResource.Namespace))
}
k.CaCertificate = caResource[resourceCaKey]
}
return utilerrors.NewAggregate(validationErrors)
}
func (k *KeycloakSyncer) Bind() error {
k.GoCloak = gocloak.NewClient(k.Provider.URL)
restyClient := k.GoCloak.RestyClient()
if k.Provider.Insecure {
restyClient.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
}
// Add trusted certificate if provided
if len(k.CaCertificate) > 0 {
tlsConfig := &tls.Config{}
if tlsConfig.RootCAs == nil {
tlsConfig.RootCAs = x509.NewCertPool()
}
tlsConfig.RootCAs.AppendCertsFromPEM(k.CaCertificate)
restyClient.SetTLSClientConfig(tlsConfig)
}
k.GoCloak.SetRestyClient(restyClient)
token, err := k.GoCloak.LoginAdmin(k.Context, string(k.CredentialsSecret.Data[secretUsernameKey]), string(k.CredentialsSecret.Data[secretPasswordKey]), k.Provider.LoginRealm)
k.Token = token
if err != nil {
return err
}
keycloakLogger.Info("Successfully Authenticated with Keycloak Provider")
return nil
}
func (k *KeycloakSyncer) Sync() ([]userv1.Group, error) {
// Get Groups
groups, err := k.getGroups()
if err != nil {
keycloakLogger.Error(err, "Failed to get Groups", "Provider", k.Name)
return nil, err
}
for _, group := range groups {
if _, groupFound := k.CachedGroups[*group.ID]; !groupFound {
k.processGroupsAndMembers(group, nil, k.Provider.Scope)
}
}
ocpGroups := []userv1.Group{}
for _, cachedGroup := range k.CachedGroups {
groupAttributes := map[string]string{}
if cachedGroup.Attributes != nil {
cachedGroupAttributes := *cachedGroup.Attributes
for key, value := range cachedGroupAttributes {
// we add the annotation that qualify for OCP annotations and log for the ones that don't
if errs := validation.IsQualifiedName(key); len(errs) == 0 {
groupAttributes[key] = strings.Join(value, "'")
} else {
keycloakLogger.Info("unable to add annotation to", "group", cachedGroup.Name, "key", key, "value", value)
}
}
}
ocpGroup := userv1.Group{
TypeMeta: v1.TypeMeta{
Kind: "Group",
APIVersion: userv1.GroupVersion.String(),
},
ObjectMeta: v1.ObjectMeta{
Name: *cachedGroup.Name,
Annotations: groupAttributes,
Labels: map[string]string{},
},
Users: []string{},
}
childrenGroups := []string{}
if cachedGroup.SubGroups != nil {
cachedGroupSubgroups := *cachedGroup.SubGroups
for _, subgroup := range cachedGroupSubgroups {
childrenGroups = append(childrenGroups, *subgroup.Name)
}
}
parentGroups := []string{}
for _, group := range k.CachedGroups {
if group.SubGroups != nil {
groupSubGroups := *group.SubGroups
for _, subgroup := range groupSubGroups {
if *subgroup.Name == *cachedGroup.Name {
parentGroups = append(parentGroups, *group.Name)
}
}
}
}
// Set Host Specific Details
ocpGroup.GetAnnotations()[constants.SyncSourceHost] = k.URL.Host
ocpGroup.GetAnnotations()[constants.SyncSourceUID] = *cachedGroup.ID
if len(childrenGroups) > 0 {
ocpGroup.GetAnnotations()[constants.HierarchyChildren] = strings.Join(childrenGroups, ",")
}
if len(parentGroups) == 1 {
ocpGroup.GetAnnotations()[constants.HierarchyParent] = parentGroups[0]
}
if len(parentGroups) > 1 {
ocpGroup.GetAnnotations()[constants.HierarchyParents] = strings.Join(parentGroups, ",")
}
for _, user := range k.CachedGroupMembers[*cachedGroup.ID] {
ocpGroup.Users = append(ocpGroup.Users, *user.Username)
}
ocpGroups = append(ocpGroups, ocpGroup)
}
return ocpGroups, nil
}
func (k *KeycloakSyncer) processGroupsAndMembers(group, parentGroup *gocloak.Group, scope redhatcopv1alpha1.SyncScope) error {
if parentGroup == nil && !isGroupAllowed(*group.Name, k.Provider.Groups) {
return nil
}
k.CachedGroups[*group.ID] = group
groupMembers, err := k.getGroupMembers(*group.ID)
if err != nil {
return err
}
k.CachedGroupMembers[*group.ID] = groupMembers
// Add Group Members to Primary Group
if parentGroup != nil {
usersToAdd, _ := k.diff(groupMembers, k.CachedGroupMembers[*parentGroup.ID])
k.CachedGroupMembers[*parentGroup.ID] = append(k.CachedGroupMembers[*parentGroup.ID], usersToAdd...)
}
// Process Subgroups
if redhatcopv1alpha1.SubSyncScope == scope && group.SubGroups != nil {
groupSubGroups := *group.SubGroups
for _, subGroup := range groupSubGroups {
if _, subGroupFound := k.CachedGroups[*subGroup.ID]; !subGroupFound {
k.processGroupsAndMembers(&subGroup, group, scope)
}
}
}
return nil
}
func (k *KeycloakSyncer) diff(lhsSlice, rhsSlice []*gocloak.User) (lhsOnly []*gocloak.User, rhsOnly []*gocloak.User) {
return k.singleDiff(lhsSlice, rhsSlice), k.singleDiff(rhsSlice, lhsSlice)
}
func (k *KeycloakSyncer) singleDiff(lhsSlice, rhsSlice []*gocloak.User) (lhsOnly []*gocloak.User) {
for _, lhs := range lhsSlice {
found := false
for _, rhs := range rhsSlice {
if *lhs.ID == *rhs.ID {
found = true
break
}
}
if !found {
lhsOnly = append(lhsOnly, lhs)
}
}
return lhsOnly
}
func (k *KeycloakSyncer) setGroupsAttributes(groups []*gocloak.Group) {
for _, group := range groups {
g, err := k.GoCloak.GetGroup(k.Context, k.Token.AccessToken, k.Provider.Realm, *group.ID)
if err != nil {
continue
}
if g.Attributes != nil && len(*g.Attributes) > 0 {
group.Attributes = g.Attributes
}
if group.SubGroups != nil && len(*group.SubGroups) > 0 {
groupSubGroupsSlice := make([]*gocloak.Group, 0, len(*group.SubGroups))
groupSubGroups := *group.SubGroups
for _, group := range groupSubGroups {
groupSubGroupsSlice = append(groupSubGroupsSlice, &group)
}
k.setGroupsAttributes(groupSubGroupsSlice)
}
}
}
func (k *KeycloakSyncer) getGroups() ([]*gocloak.Group, error) {
groups := []*gocloak.Group{}
iteration := 0
for {
gIteration := iteration * iterationMax
groupsParams := gocloak.GetGroupsParams{First: &gIteration, Max: &iterationMax, BriefRepresentation: &truthy}
groupsResponse, err := k.GoCloak.GetGroups(k.Context, k.Token.AccessToken, k.Provider.Realm, groupsParams)
if err != nil {
return nil, err
}
if len(groupsResponse) == 0 {
break
}
k.setGroupsAttributes(groupsResponse)
groups = append(groups, groupsResponse...)
iteration = iteration + 1
}
return groups, nil
}
func (k *KeycloakSyncer) getGroupMembers(groupId string) ([]*gocloak.User, error) {
members := []*gocloak.User{}
iteration := 0
for {
uIteration := iteration * iterationMax
groupMemberParams := gocloak.GetGroupsParams{First: &uIteration, Max: &iterationMax, BriefRepresentation: &truthy}
groupMembers, err := k.GoCloak.GetGroupMembers(k.Context, k.Token.AccessToken, k.Provider.Realm, groupId, groupMemberParams)
if err != nil {
return nil, err
}
if len(groupMembers) == 0 {
break
}
members = append(members, groupMembers...)
iteration = iteration + 1
}
return members, nil
}
func (k *KeycloakSyncer) GetProviderName() string {
return k.Name
}
func (k *KeycloakSyncer) GetPrune() bool {
return k.Provider.Prune
}