-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpath_client_secret.go
More file actions
378 lines (326 loc) · 11.1 KB
/
path_client_secret.go
File metadata and controls
378 lines (326 loc) · 11.1 KB
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
package keycloak
import (
"context"
"errors"
"fmt"
"io"
"net"
"net/url"
"syscall"
"time"
"github.com/Serviceware/vault-plugin-secrets-keycloak/keycloak"
"github.com/Serviceware/vault-plugin-secrets-keycloak/util/jwt"
retry "github.com/avast/retry-go/v5"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/logical"
)
const (
// optionalSecretReadRetryAttempts is the maximum number of attempts for transient-error retries on the optional-secret route.
optionalSecretReadRetryAttempts = 4
// optionalSecretReadRetryDelay is the base delay for the exponential back-off between retry attempts.
optionalSecretReadRetryDelay = 500 * time.Millisecond
)
func pathClientSecretDeprecated(b *backend) *framework.Path {
return &framework.Path{
Pattern: "client-secret/" + framework.GenericNameRegex("clientId"),
Fields: map[string]*framework.FieldSchema{
"clientId": {
Type: framework.TypeString,
Description: "Name of the client.",
},
},
Deprecated: true,
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: b.pathClientSecretReadDeprecated,
},
}
}
func (b *backend) pathClientSecretReadDeprecated(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
clientId := d.Get("clientId").(string)
if clientId == "" {
return logical.ErrorResponse("missing client"), nil
}
config, err := readConfig(ctx, req.Storage)
if err != nil {
return logical.ErrorResponse("failed to read config"), err
}
clientSecret, err := b.readClientSecret(ctx, clientId, config)
if err != nil {
return logical.ErrorResponse("could not retrieve client secret"), err
}
// Generate the response
issuerUrl := config.ServerUrl + "/realms/" + config.Realm
response := &logical.Response{
Data: map[string]interface{}{
"client_secret": clientSecret,
"client_id": clientId,
"issuer_url": issuerUrl,
},
}
return response, nil
}
func pathClientSecret(b *backend) *framework.Path {
return &framework.Path{
Pattern: "clients/" + framework.GenericNameRegex("clientId") + "/secret",
Fields: map[string]*framework.FieldSchema{
"clientId": {
Type: framework.TypeString,
Description: "Name of the client.",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: b.pathClientSecretRead,
},
}
}
func (b *backend) pathClientSecretRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
clientId := d.Get("clientId").(string)
if clientId == "" {
return logical.ErrorResponse("missing client"), nil
}
config, err := readConfig(ctx, req.Storage)
if err != nil {
return logical.ErrorResponse("failed to read config"), err
}
clientSecret, err := b.readClientSecret(ctx, clientId, config)
if err != nil {
return logical.ErrorResponse("could not retrieve client secret"), err
}
openIdConifg, err := b.getGetWellKnownOpenidConfiguration(ctx, config, config.Realm)
if err != nil {
return logical.ErrorResponse("could not retrieve issuer"), err
}
// Generate the response
response := &logical.Response{
Data: map[string]interface{}{
"client_secret": clientSecret,
"client_id": clientId,
"issuer": openIdConifg.Issuer,
},
}
return response, nil
}
func (b *backend) getGetWellKnownOpenidConfiguration(ctx context.Context, config ConnectionConfig, realm string) (*keycloak.WellKnownOpenidConfiguration, error) {
client := b.KeycloakServiceFactory(config.ServerUrl)
return client.GetWellKnownOpenidConfiguration(ctx, realm)
}
// retryOnTransientNetworkError executes fn and retries up to optionalSecretReadRetryAttempts times
// on transient network errors, using exponential back-off. It is only used for the optional-secret
// route so that a temporarily unreachable Keycloak returns a graceful empty response instead of an error.
func retryOnTransientNetworkError[T any](ctx context.Context, fn func() (T, error)) (T, error) {
return retry.NewWithData[T](
retry.Attempts(optionalSecretReadRetryAttempts),
retry.Context(ctx),
retry.Delay(optionalSecretReadRetryDelay),
retry.DelayType(retry.BackOffDelay),
retry.LastErrorOnly(true),
retry.RetryIf(isTransientNetworkError),
).Do(fn)
}
// isTransientNetworkError reports whether err represents a transient network condition
// that warrants a retry (e.g. connection reset, EOF, timeout).
func isTransientNetworkError(err error) bool {
if err == nil {
return false
}
if errors.Is(err, context.DeadlineExceeded) ||
errors.Is(err, io.EOF) ||
errors.Is(err, io.ErrUnexpectedEOF) ||
errors.Is(err, syscall.ECONNABORTED) ||
errors.Is(err, syscall.ECONNREFUSED) ||
errors.Is(err, syscall.ECONNRESET) ||
errors.Is(err, syscall.EPIPE) ||
errors.Is(err, syscall.ETIMEDOUT) {
return true
}
var urlErr *url.Error
if errors.As(err, &urlErr) && urlErr.Err != nil {
return urlErr.Timeout() || isTransientNetworkError(urlErr.Err)
}
var opErr *net.OpError
if errors.As(err, &opErr) && opErr.Err != nil {
return opErr.Timeout() || isTransientNetworkError(opErr.Err)
}
var netErr net.Error
if errors.As(err, &netErr) {
return netErr.Timeout()
}
return false
}
func (b *backend) readClientSecret(ctx context.Context, clientId string, config ConnectionConfig) (string, error) {
return b.readClientSecretOfRealm(ctx, config.Realm, clientId, config)
}
func (b *backend) readClientSecretOfRealm(ctx context.Context, realm string, clientId string, config ConnectionConfig) (string, error) {
goclaokClient, token, err := b.getClientAndAccessToken(ctx, config)
if err != nil {
return "", err
}
clients, err := goclaokClient.GetClients(ctx, token.AccessToken, realm, keycloak.GetClientsParams{
ClientID: &clientId,
})
if err != nil {
return "", err
}
if len(clients) != 1 {
return "", fmt.Errorf("found %d clients for %s", len(clients), clientId)
}
client := clients[0]
creds, err := goclaokClient.GetClientSecret(ctx, token.AccessToken, realm, *client.ID)
if err != nil {
return "", err
}
return *creds.Value, nil
}
func (b *backend) getClientAndAccessToken(ctx context.Context, config ConnectionConfig) (keycloak.Service, *keycloak.JWT, error) {
goclaokClient := b.KeycloakServiceFactory(config.ServerUrl)
b.jwtMutex.Lock()
defer b.jwtMutex.Unlock()
if token, ok := b.jwt[config]; ok && jwt.IsValidIn(token.AccessToken, time.Duration(5)*time.Second) {
return goclaokClient, token, nil
}
token, err := goclaokClient.LoginClient(ctx, config.ClientId, config.ClientSecret, config.Realm)
if err != nil {
return nil, nil, fmt.Errorf("failed to login: %w", err)
}
b.jwt[config] = token
return goclaokClient, token, nil
}
func pathRealmClientSecret(b *backend) *framework.Path {
return &framework.Path{
Pattern: "realms/" + framework.GenericNameRegex("realm") + "/clients/" + framework.GenericNameRegex("clientId") + "/secret",
Fields: map[string]*framework.FieldSchema{
"clientId": {
Type: framework.TypeString,
Description: "Name of the client.",
},
"realm": {
Type: framework.TypeString,
Description: "Name of the realm.",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: b.pathRealmClientSecretRead,
},
}
}
func (b *backend) pathRealmClientSecretRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
realm := d.Get("realm").(string)
if realm == "" {
return logical.ErrorResponse("missing realm"), nil
}
clientId := d.Get("clientId").(string)
if clientId == "" {
return logical.ErrorResponse("missing client"), nil
}
config, err := readConfigForKey(ctx, req.Storage, fmt.Sprintf(storagePerRealmKey, realm))
if err != nil {
return logical.ErrorResponse("failed to read config"), err
}
// if config is empty, try to read the default config
if config.ServerUrl == "" {
config, err = readConfig(ctx, req.Storage)
if err != nil {
return logical.ErrorResponse("failed to read config"), err
}
}
clientSecret, err := b.readClientSecretOfRealm(ctx, realm, clientId, config)
if err != nil {
return logical.ErrorResponse("could not retrieve client secret"), err
}
openidConfig, err := b.getGetWellKnownOpenidConfiguration(ctx, config, realm)
if err != nil {
return logical.ErrorResponse("could not retrieve issuer"), err
}
// Generate the response
issuerUrl := openidConfig.Issuer
response := &logical.Response{
Data: map[string]interface{}{
"client_secret": clientSecret,
"client_id": clientId,
"issuer": issuerUrl,
},
}
return response, nil
}
func pathRealmClientOptionalSecret(b *backend) *framework.Path {
return &framework.Path{
Pattern: "realms/" + framework.GenericNameRegex("realm") + "/clients/" + framework.GenericNameRegex("clientId") + "/optional-secret",
Fields: map[string]*framework.FieldSchema{
"clientId": {
Type: framework.TypeString,
Description: "Name of the client.",
},
"realm": {
Type: framework.TypeString,
Description: "Name of the realm.",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: b.pathRealmClientOptionalSecretRead,
},
}
}
func (b *backend) pathRealmClientOptionalSecretRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
realm := d.Get("realm").(string)
if realm == "" {
return logical.ErrorResponse("missing realm"), nil
}
clientId := d.Get("clientId").(string)
if clientId == "" {
return logical.ErrorResponse("missing client"), nil
}
config, err := readConfigForKey(ctx, req.Storage, fmt.Sprintf(storagePerRealmKey, realm))
if err != nil {
return logical.ErrorResponse("failed to read config"), err
}
// if config is empty, try to read the default config
if config.ServerUrl == "" {
config, err = readConfig(ctx, req.Storage)
if err != nil {
return logical.ErrorResponse("failed to read config"), err
}
}
clientSecret, err := retryOnTransientNetworkError(ctx, func() (string, error) {
return b.readClientSecretOfRealm(ctx, realm, clientId, config)
})
if err != nil {
message := fmt.Sprintf("could not retrieve client secret for client %s in realm %s: %s", clientId, realm, err.Error())
resp := &logical.Response{
Data: map[string]interface{}{
"client_secret": "",
"client_id": clientId,
"issuer": "",
"error": message,
},
}
resp.AddWarning(message)
return resp, nil
}
openidConfig, err := retryOnTransientNetworkError(ctx, func() (*keycloak.WellKnownOpenidConfiguration, error) {
return b.getGetWellKnownOpenidConfiguration(ctx, config, realm)
})
if err != nil {
message := fmt.Sprintf("could not retrieve issuer for client %s in realm %s: %s", clientId, realm, err.Error())
resp := &logical.Response{
Data: map[string]interface{}{
"client_secret": "",
"client_id": clientId,
"issuer": "",
"error": message,
},
}
resp.AddWarning(message)
return resp, nil
}
// Generate the response
issuerUrl := openidConfig.Issuer
response := &logical.Response{
Data: map[string]interface{}{
"client_secret": clientSecret,
"client_id": clientId,
"issuer": issuerUrl,
"error": nil,
},
}
return response, nil
}