forked from hashicorp/vault-plugin-auth-jwt
-
Notifications
You must be signed in to change notification settings - Fork 1
/
path_config.go
334 lines (288 loc) · 10.4 KB
/
path_config.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
package jwtauth
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"net/http"
"strings"
"github.com/coreos/go-oidc"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/go-cleanhttp"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/certutil"
"github.com/hashicorp/vault/sdk/logical"
"golang.org/x/oauth2"
)
func pathConfig(b *jwtAuthBackend) *framework.Path {
return &framework.Path{
Pattern: `config`,
Fields: map[string]*framework.FieldSchema{
"oidc_discovery_url": {
Type: framework.TypeString,
Description: `OIDC Discovery URL, without any .well-known component (base path). Cannot be used with "jwks_url" or "jwt_validation_pubkeys".`,
},
"oidc_discovery_ca_pem": {
Type: framework.TypeString,
Description: "The CA certificate or chain of certificates, in PEM format, to use to validate connections to the OIDC Discovery URL. If not set, system certificates are used.",
},
"oidc_client_id": {
Type: framework.TypeString,
Description: "The OAuth Client ID configured with your OIDC provider.",
},
"oidc_client_secret": {
Type: framework.TypeString,
Description: "The OAuth Client Secret configured with your OIDC provider.",
DisplayAttrs: &framework.DisplayAttributes{
Sensitive: true,
},
},
"jwks_url": {
Type: framework.TypeString,
Description: `JWKS URL to use to authenticate signatures. Cannot be used with "oidc_discovery_url" or "jwt_validation_pubkeys".`,
},
"jwks_ca_pem": {
Type: framework.TypeString,
Description: "The CA certificate or chain of certificates, in PEM format, to use to validate connections to the JWKS URL. If not set, system certificates are used.",
},
"default_role": {
Type: framework.TypeString,
Description: "The default role to use if none is provided during login. If not set, a role is required during login.",
},
"jwt_validation_pubkeys": {
Type: framework.TypeCommaStringSlice,
Description: `A list of PEM-encoded public keys to use to authenticate signatures locally. Cannot be used with "jwks_url" or "oidc_discovery_url".`,
},
"jwt_supported_algs": {
Type: framework.TypeCommaStringSlice,
Description: `A list of supported signing algorithms. Defaults to RS256.`,
},
"bound_issuer": {
Type: framework.TypeString,
Description: "The value against which to match the 'iss' claim in a JWT. Optional.",
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathConfigRead,
Summary: "Read the current JWT authentication backend configuration.",
},
logical.UpdateOperation: &framework.PathOperation{
Callback: b.pathConfigWrite,
Summary: "Configure the JWT authentication backend.",
Description: confHelpDesc,
},
},
HelpSynopsis: confHelpSyn,
HelpDescription: confHelpDesc,
}
}
func (b *jwtAuthBackend) config(ctx context.Context, s logical.Storage) (*jwtConfig, error) {
b.l.Lock()
defer b.l.Unlock()
if b.cachedConfig != nil {
return b.cachedConfig, nil
}
entry, err := s.Get(ctx, configPath)
if err != nil {
return nil, err
}
if entry == nil {
return nil, nil
}
result := &jwtConfig{}
if err := entry.DecodeJSON(result); err != nil {
return nil, err
}
for _, v := range result.JWTValidationPubKeys {
key, err := certutil.ParsePublicKeyPEM([]byte(v))
if err != nil {
return nil, errwrap.Wrapf("error parsing public key: {{err}}", err)
}
result.ParsedJWTPubKeys = append(result.ParsedJWTPubKeys, key)
}
b.cachedConfig = result
return result, nil
}
func (b *jwtAuthBackend) pathConfigRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
config, err := b.config(ctx, req.Storage)
if err != nil {
return nil, err
}
if config == nil {
return nil, nil
}
resp := &logical.Response{
Data: map[string]interface{}{
"oidc_discovery_url": config.OIDCDiscoveryURL,
"oidc_discovery_ca_pem": config.OIDCDiscoveryCAPEM,
"oidc_client_id": config.OIDCClientID,
"default_role": config.DefaultRole,
"jwt_validation_pubkeys": config.JWTValidationPubKeys,
"jwt_supported_algs": config.JWTSupportedAlgs,
"jwks_url": config.JWKSURL,
"jwks_ca_pem": config.JWKSCAPEM,
"bound_issuer": config.BoundIssuer,
},
}
return resp, nil
}
func (b *jwtAuthBackend) pathConfigWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
config := &jwtConfig{
OIDCDiscoveryURL: d.Get("oidc_discovery_url").(string),
OIDCDiscoveryCAPEM: d.Get("oidc_discovery_ca_pem").(string),
OIDCClientID: d.Get("oidc_client_id").(string),
OIDCClientSecret: d.Get("oidc_client_secret").(string),
JWKSURL: d.Get("jwks_url").(string),
JWKSCAPEM: d.Get("jwks_ca_pem").(string),
DefaultRole: d.Get("default_role").(string),
JWTValidationPubKeys: d.Get("jwt_validation_pubkeys").([]string),
JWTSupportedAlgs: d.Get("jwt_supported_algs").([]string),
BoundIssuer: d.Get("bound_issuer").(string),
}
// Run checks on values
methodCount := 0
if config.OIDCDiscoveryURL != "" {
methodCount++
}
if len(config.JWTValidationPubKeys) != 0 {
methodCount++
}
if config.JWKSURL != "" {
methodCount++
}
switch {
case methodCount != 1:
return logical.ErrorResponse("exactly one of 'jwt_validation_pubkeys', 'jwks_url' or 'oidc_discovery_url' must be set"), nil
case config.OIDCClientID != "" && config.OIDCClientSecret == "",
config.OIDCClientID == "" && config.OIDCClientSecret != "":
return logical.ErrorResponse("both 'oidc_client_id' and 'oidc_client_secret' must be set for OIDC"), nil
case config.OIDCDiscoveryURL != "":
_, err := b.createProvider(config)
if err != nil {
return logical.ErrorResponse(errwrap.Wrapf("error checking oidc discovery URL: {{err}}", err).Error()), nil
}
case config.OIDCClientID != "" && config.OIDCDiscoveryURL == "":
return logical.ErrorResponse("'oidc_discovery_url' must be set for OIDC"), nil
case config.JWKSURL != "":
ctx, err := b.createCAContext(context.Background(), config.JWKSCAPEM)
if err != nil {
return logical.ErrorResponse(errwrap.Wrapf("error checking jwks_ca_pem: {{err}}", err).Error()), nil
}
keyset := oidc.NewRemoteKeySet(ctx, config.JWKSURL)
// Try to verify a correctly formatted JWT. The signature will fail to match, but other
// errors with fetching the remote keyset should be reported.
testJWT := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.Hf3E3iCHzqC5QIQ0nCqS1kw78IiQTRVzsLTuKoDIpdk"
_, err = keyset.VerifySignature(ctx, testJWT)
if err == nil {
err = errors.New("unexpected verification of JWT")
}
if !strings.Contains(err.Error(), "failed to verify id token signature") {
return logical.ErrorResponse(errwrap.Wrapf("error checking jwks URL: {{err}}", err).Error()), nil
}
case len(config.JWTValidationPubKeys) != 0:
for _, v := range config.JWTValidationPubKeys {
if _, err := certutil.ParsePublicKeyPEM([]byte(v)); err != nil {
return logical.ErrorResponse(errwrap.Wrapf("error parsing public key: {{err}}", err).Error()), nil
}
}
default:
return nil, errors.New("unknown condition")
}
for _, a := range config.JWTSupportedAlgs {
switch a {
case oidc.RS256, oidc.RS384, oidc.RS512, oidc.ES256, oidc.ES384, oidc.ES512, oidc.PS256, oidc.PS384, oidc.PS512:
default:
return logical.ErrorResponse(fmt.Sprintf("Invalid supported algorithm: %s", a)), nil
}
}
entry, err := logical.StorageEntryJSON(configPath, config)
if err != nil {
return nil, err
}
if err := req.Storage.Put(ctx, entry); err != nil {
return nil, err
}
b.reset()
return nil, nil
}
func (b *jwtAuthBackend) createProvider(config *jwtConfig) (*oidc.Provider, error) {
oidcCtx, err := b.createCAContext(b.providerCtx, config.OIDCDiscoveryCAPEM)
if err != nil {
return nil, errwrap.Wrapf("error creating provider: {{err}}", err)
}
provider, err := oidc.NewProvider(oidcCtx, config.OIDCDiscoveryURL)
if err != nil {
return nil, errwrap.Wrapf("error creating provider with given values: {{err}}", err)
}
return provider, nil
}
// createCAContext returns a context with custom TLS client, configured with the root certificates
// from caPEM. If no certificates are configured, the original context is returned.
func (b *jwtAuthBackend) createCAContext(ctx context.Context, caPEM string) (context.Context, error) {
if caPEM == "" {
return ctx, nil
}
certPool := x509.NewCertPool()
if ok := certPool.AppendCertsFromPEM([]byte(caPEM)); !ok {
return nil, errors.New("could not parse CA PEM value successfully")
}
tr := cleanhttp.DefaultPooledTransport()
if certPool != nil {
tr.TLSClientConfig = &tls.Config{
RootCAs: certPool,
}
}
tc := &http.Client{
Transport: tr,
}
caCtx := context.WithValue(ctx, oauth2.HTTPClient, tc)
return caCtx, nil
}
type jwtConfig struct {
OIDCDiscoveryURL string `json:"oidc_discovery_url"`
OIDCDiscoveryCAPEM string `json:"oidc_discovery_ca_pem"`
OIDCClientID string `json:"oidc_client_id"`
OIDCClientSecret string `json:"oidc_client_secret"`
JWKSURL string `json:"jwks_url"`
JWKSCAPEM string `json:"jwks_ca_pem"`
JWTValidationPubKeys []string `json:"jwt_validation_pubkeys"`
JWTSupportedAlgs []string `json:"jwt_supported_algs"`
BoundIssuer string `json:"bound_issuer"`
DefaultRole string `json:"default_role"`
ParsedJWTPubKeys []interface{} `json:"-"`
}
const (
StaticKeys = iota
JWKS
OIDCDiscovery
OIDCFlow
unconfigured
)
// authType classifies the authorization type/flow based on config parameters.
func (c jwtConfig) authType() int {
switch {
case len(c.ParsedJWTPubKeys) > 0:
return StaticKeys
case c.JWKSURL != "":
return JWKS
case c.OIDCDiscoveryURL != "":
if c.OIDCClientID != "" && c.OIDCClientSecret != "" {
return OIDCFlow
}
return OIDCDiscovery
}
return unconfigured
}
const (
confHelpSyn = `
Configures the JWT authentication backend.
`
confHelpDesc = `
The JWT authentication backend validates JWTs (or OIDC) using the configured
credentials. If using OIDC Discovery, the URL must be provided, along
with (optionally) the CA cert to use for the connection. If performing JWT
validation locally, a set of public keys must be provided.
`
)