-
Notifications
You must be signed in to change notification settings - Fork 41
/
client.go
383 lines (338 loc) · 12.2 KB
/
client.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
package keycloak
import (
"context"
"crypto/tls"
"fmt"
"net/http"
"time"
"github.com/bf2fc6cc711aee1a0c2a/kas-fleet-manager/pkg/shared/utils/arrays"
"github.com/Nerzal/gocloak/v11"
"github.com/golang-jwt/jwt/v4"
"github.com/patrickmn/go-cache"
"github.com/pkg/errors"
)
const (
// gocloak access token duration before expiration
tokenLifeDuration = 5 * time.Minute
cacheCleanupInterval = 5 * time.Minute
OrgKey = "rh-org-id"
UserKey = "rh-user-id"
)
var (
protocol = "openid-connect"
mapper = "oidc-usermodel-attribute-mapper"
)
//go:generate moq -out client_moq.go . KcClient
type KcClient interface {
CreateClient(client gocloak.Client, accessToken string) (string, error)
GetToken() (string, error)
GetCachedToken(tokenKey string) (string, error)
DeleteClient(internalClientID string, accessToken string) error
GetClientSecret(internalClientId string, accessToken string) (string, error)
GetClient(clientId string, accessToken string) (*gocloak.Client, error)
IsClientExist(clientId string, accessToken string) (string, error)
GetConfig() *KeycloakConfig
GetRealmConfig() *KeycloakRealmConfig
GetClientById(id string, accessToken string) (*gocloak.Client, error)
ClientConfig(client ClientRepresentation) gocloak.Client
CreateProtocolMapperConfig(string) []gocloak.ProtocolMapperRepresentation
GetClientServiceAccount(accessToken string, internalClient string) (*gocloak.User, error)
UpdateServiceAccountUser(accessToken string, serviceAccountUser gocloak.User) error
// GetClients returns keycloak clients using the given method parameters. If max is less than 0, then returns all the clients.
// If it is 0, then default to using the default max allowed service accounts configuration.
GetClients(accessToken string, first int, max int, attribute string) ([]*gocloak.Client, error)
IsSameOrg(client *gocloak.Client, orgId string) bool
IsOwner(client *gocloak.Client, userId string) bool
RegenerateClientSecret(accessToken string, id string) (*gocloak.CredentialRepresentation, error)
GetRealmRole(accessToken string, roleName string) (*gocloak.Role, error)
CreateRealmRole(accessToken string, roleName string) (*gocloak.Role, error)
UserHasRealmRole(accessToken string, userId string, roleName string) (*gocloak.Role, error)
AddRealmRoleToUser(accessToken string, userId string, role gocloak.Role) error
}
type ClientRepresentation struct {
Name string
ClientID string
ServiceAccountsEnabled bool
Secret *string
StandardFlowEnabled bool
Attributes map[string]string
AuthorizationServicesEnabled bool
ProtocolMappers []gocloak.ProtocolMapperRepresentation
Description string
RedirectURIs *[]string
}
type kcClient struct {
kcClient goCloakClientInterface
ctx context.Context
config *KeycloakConfig
realmConfig *KeycloakRealmConfig
cache *cache.Cache
}
var _ KcClient = &kcClient{}
func NewClient(config *KeycloakConfig, realmConfig *KeycloakRealmConfig) *kcClient {
setTokenEndpoints(config, realmConfig)
client := gocloak.NewClient(realmConfig.BaseURL)
client.RestyClient().SetDebug(config.Debug)
client.RestyClient().SetTLSClientConfig(&tls.Config{InsecureSkipVerify: config.InsecureSkipVerify})
return &kcClient{
kcClient: client,
ctx: context.Background(),
config: config,
realmConfig: realmConfig,
cache: cache.New(tokenLifeDuration, cacheCleanupInterval),
}
}
func (kc *kcClient) ClientConfig(client ClientRepresentation) gocloak.Client {
publicClient := false
directAccess := false
return gocloak.Client{
Name: &client.Name,
ClientID: &client.ClientID,
ServiceAccountsEnabled: &client.ServiceAccountsEnabled,
StandardFlowEnabled: &client.StandardFlowEnabled,
Attributes: &client.Attributes,
AuthorizationServicesEnabled: &client.AuthorizationServicesEnabled,
ProtocolMappers: &client.ProtocolMappers,
Description: &client.Description,
RedirectURIs: client.RedirectURIs,
Protocol: &protocol,
PublicClient: &publicClient,
DirectAccessGrantsEnabled: &directAccess,
}
}
func (kc *kcClient) CreateProtocolMapperConfig(name string) []gocloak.ProtocolMapperRepresentation {
protocolMapper := []gocloak.ProtocolMapperRepresentation{
{
Name: &name,
Protocol: &protocol,
ProtocolMapper: &mapper,
Config: &map[string]string{
"access.token.claim": "true",
"claim.name": name,
"id.token.claim": "true",
"jsonType.label": "String",
"user.attribute": name,
"userinfo.token.claim": "true",
},
},
}
return protocolMapper
}
func setTokenEndpoints(config *KeycloakConfig, realmConfig *KeycloakRealmConfig) {
realmConfig.JwksEndpointURI = realmConfig.BaseURL + "/auth/realms/" + realmConfig.Realm + "/protocol/openid-connect/certs"
realmConfig.TokenEndpointURI = realmConfig.BaseURL + "/auth/realms/" + realmConfig.Realm + "/protocol/openid-connect/token"
realmConfig.ValidIssuerURI = realmConfig.BaseURL + "/auth/realms/" + realmConfig.Realm
}
func (kc *kcClient) CreateClient(client gocloak.Client, accessToken string) (string, error) {
internalClientID, err := kc.kcClient.CreateClient(kc.ctx, accessToken, kc.realmConfig.Realm, client)
if err != nil {
return "", err
}
return internalClientID, err
}
func (kc *kcClient) GetClient(clientId string, accessToken string) (*gocloak.Client, error) {
params := gocloak.GetClientsParams{
ClientID: &clientId,
}
clients, err := kc.kcClient.GetClients(kc.ctx, accessToken, kc.realmConfig.Realm, params)
if err != nil {
return nil, err
}
_, client := arrays.FindFirst(clients, func(c *gocloak.Client) bool { return *c.ClientID == clientId })
return client, nil
}
func (kc *kcClient) GetToken() (string, error) {
options := gocloak.TokenOptions{
ClientID: &kc.realmConfig.ClientID,
GrantType: &kc.realmConfig.GrantType,
ClientSecret: &kc.realmConfig.ClientSecret,
}
cachedTokenKey := fmt.Sprintf("%s%s", kc.realmConfig.ValidIssuerURI, kc.realmConfig.ClientID)
cachedToken, _ := kc.GetCachedToken(cachedTokenKey)
if cachedToken != "" && !IsJWTTokenExpired(cachedToken) {
return cachedToken, nil
}
tokenResp, err := kc.kcClient.GetToken(kc.ctx, kc.realmConfig.Realm, options)
if err != nil {
return "", errors.Wrap(err, "failed to get new token from gocloak with error")
}
kc.cache.Set(cachedTokenKey, tokenResp.AccessToken, cacheCleanupInterval)
return tokenResp.AccessToken, nil
}
// IsJWTTokenExpired returns false if JWT token is not expired, otherwise returns true
// This method does NOT validate the token, and should not be used when validation is necessary
func IsJWTTokenExpired(accessToken string) bool {
if token, _ := jwt.Parse(accessToken, nil); token != nil {
tokenClaims := token.Claims.(jwt.MapClaims)
if _, ok := tokenClaims["exp"]; ok {
expTime := time.Unix(int64(tokenClaims["exp"].(float64)), 0)
return time.Now().After(expTime)
}
}
return true
}
func (kc *kcClient) GetCachedToken(tokenKey string) (string, error) {
cachedToken, isCached := kc.cache.Get(tokenKey)
ct, _ := cachedToken.(string)
if isCached {
return ct, nil
}
return "", errors.Errorf("failed to retrieve cached token")
}
func (kc *kcClient) GetClientSecret(internalClientId string, accessToken string) (string, error) {
resp, err := kc.kcClient.GetClientSecret(kc.ctx, accessToken, kc.realmConfig.Realm, internalClientId)
if err != nil {
return "", err
}
if resp.Value == nil {
return "", errors.Errorf("failed to retrieve credentials")
}
return *resp.Value, err
}
func (kc *kcClient) DeleteClient(internalClientID string, accessToken string) error {
return kc.kcClient.DeleteClient(kc.ctx, accessToken, kc.realmConfig.Realm, internalClientID)
}
func (kc *kcClient) getClient(clientId string, accessToken string) ([]*gocloak.Client, error) {
params := gocloak.GetClientsParams{
ClientID: &clientId,
}
client, err := kc.kcClient.GetClients(kc.ctx, accessToken, kc.realmConfig.Realm, params)
if err != nil {
return nil, err
}
return client, err
}
func (kc *kcClient) GetClientById(internalId string, accessToken string) (*gocloak.Client, error) {
client, err := kc.kcClient.GetClient(kc.ctx, accessToken, kc.realmConfig.Realm, internalId)
if err != nil {
return nil, err
}
return client, err
}
func (kc *kcClient) GetConfig() *KeycloakConfig {
return kc.config
}
func (kc *kcClient) GetRealmConfig() *KeycloakRealmConfig {
return kc.realmConfig
}
func (kc *kcClient) IsClientExist(clientId string, accessToken string) (string, error) {
if clientId == "" {
return "", errors.New("clientId cannot be empty")
}
clients, err := kc.getClient(clientId, accessToken)
if err != nil {
return "", err
}
for _, client := range clients {
if *client.ClientID == clientId {
return *client.ID, nil
}
}
return "", err
}
func (kc *kcClient) GetClientServiceAccount(accessToken string, internalClient string) (*gocloak.User, error) {
serviceAccountUser, err := kc.kcClient.GetClientServiceAccount(kc.ctx, accessToken, kc.realmConfig.Realm, internalClient)
if err != nil {
return nil, err
}
return serviceAccountUser, err
}
func (kc *kcClient) UpdateServiceAccountUser(accessToken string, serviceAccountUser gocloak.User) error {
err := kc.kcClient.UpdateUser(kc.ctx, accessToken, kc.realmConfig.Realm, serviceAccountUser)
if err != nil {
return err
}
return err
}
func (kc *kcClient) GetClients(accessToken string, first int, max int, attribute string) ([]*gocloak.Client, error) {
params := gocloak.GetClientsParams{
First: &first,
SearchableAttributes: &attribute,
}
if max == 0 {
max = kc.config.MaxLimitForGetClients
}
if max > 0 {
params.Max = &max
}
clients, err := kc.kcClient.GetClients(kc.ctx, accessToken, kc.realmConfig.Realm, params)
if err != nil {
return nil, err
}
return clients, err
}
func (kc *kcClient) IsSameOrg(client *gocloak.Client, orgId string) bool {
if orgId == "" {
return false
}
attributes := *client.Attributes
return attributes[OrgKey] == orgId
}
func (kc *kcClient) IsOwner(client *gocloak.Client, userId string) bool {
if userId == "" {
return false
}
attributes := *client.Attributes
if rhUserId, found := attributes[UserKey]; found {
return rhUserId == userId
}
return false
}
func (kc *kcClient) RegenerateClientSecret(accessToken string, id string) (*gocloak.CredentialRepresentation, error) {
credRep, err := kc.kcClient.RegenerateClientSecret(kc.ctx, accessToken, kc.realmConfig.Realm, id)
if err != nil {
return nil, err
}
return credRep, err
}
func (kc *kcClient) GetRealmRole(accessToken string, roleName string) (*gocloak.Role, error) {
r, err := kc.kcClient.GetRealmRole(kc.ctx, accessToken, kc.realmConfig.Realm, roleName)
if err != nil {
if isNotFoundError(err) {
return nil, nil
}
return nil, err
}
return r, err
}
func (kc *kcClient) CreateRealmRole(accessToken string, roleName string) (*gocloak.Role, error) {
r := &gocloak.Role{
Name: &roleName,
}
_, err := kc.kcClient.CreateRealmRole(kc.ctx, accessToken, kc.realmConfig.Realm, *r)
if err != nil {
return nil, err
}
// for some reason, the internal id of the role is not returned by kcClient.CreateRealmRole, so we have to get the role again to get the full details
r, err = kc.kcClient.GetRealmRole(kc.ctx, accessToken, kc.realmConfig.Realm, roleName)
if err != nil {
return nil, err
}
return r, nil
}
func (kc *kcClient) UserHasRealmRole(accessToken string, userId string, roleName string) (*gocloak.Role, error) {
roles, err := kc.kcClient.GetRealmRolesByUserID(kc.ctx, accessToken, kc.realmConfig.Realm, userId)
if err != nil {
return nil, err
}
for _, r := range roles {
if *r.Name == roleName {
return r, nil
}
}
return nil, nil
}
func (kc *kcClient) AddRealmRoleToUser(accessToken string, userId string, role gocloak.Role) error {
roles := []gocloak.Role{role}
err := kc.kcClient.AddRealmRoleToUser(kc.ctx, accessToken, kc.realmConfig.Realm, userId, roles)
if err != nil {
return err
}
return nil
}
func isNotFoundError(err error) bool {
if e, ok := err.(*gocloak.APIError); ok {
return e.Code == http.StatusNotFound
}
return false
}