-
Notifications
You must be signed in to change notification settings - Fork 10
/
basic.go
404 lines (330 loc) · 10.4 KB
/
basic.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
package provider
import (
"context"
"fmt"
"net/url"
"strings"
gooidc "github.com/coreos/go-oidc"
"github.com/puppetlabs/leg/errmap/pkg/errmark"
"github.com/puppetlabs/vault-plugin-secrets-oauthapp/v3/pkg/oauth2ext/clientctx"
"github.com/puppetlabs/vault-plugin-secrets-oauthapp/v3/pkg/oauth2ext/devicecode"
"github.com/puppetlabs/vault-plugin-secrets-oauthapp/v3/pkg/oauth2ext/semerr"
"golang.org/x/oauth2"
"golang.org/x/oauth2/bitbucket"
"golang.org/x/oauth2/clientcredentials"
"golang.org/x/oauth2/github"
"golang.org/x/oauth2/gitlab"
"golang.org/x/oauth2/microsoft"
"golang.org/x/oauth2/slack"
)
func init() {
GlobalRegistry.MustRegister("bitbucket", BasicFactory(Endpoint{Endpoint: bitbucket.Endpoint}))
GlobalRegistry.MustRegister("github", BasicFactory(Endpoint{
Endpoint: github.Endpoint,
DeviceURL: "https://github.com/login/device/code", // https://docs.github.com/en/developers/apps/authorizing-oauth-apps#device-flow
}))
GlobalRegistry.MustRegister("gitlab", BasicFactory(Endpoint{Endpoint: gitlab.Endpoint}))
GlobalRegistry.MustRegister("microsoft_azure_ad", AzureADFactory)
GlobalRegistry.MustRegister("slack", BasicFactory(Endpoint{Endpoint: slack.Endpoint}))
GlobalRegistry.MustRegister("custom", CustomFactory)
}
type basicOperations struct {
vsn int
endpointFactory EndpointFactoryFunc
clientID string
clientSecret string
}
func (bo *basicOperations) AuthCodeURL(state string, opts ...AuthCodeURLOption) (string, bool) {
o := &AuthCodeURLOptions{}
o.ApplyOptions(opts)
endpoint := bo.endpointFactory(o.ProviderOptions)
if endpoint.AuthURL == "" {
return "", false
}
cfg := &oauth2.Config{
Endpoint: endpoint.Endpoint,
ClientID: bo.clientID,
Scopes: o.Scopes,
RedirectURL: o.RedirectURL,
}
return cfg.AuthCodeURL(state, o.AuthCodeOptions...), true
}
func (bo *basicOperations) DeviceCodeAuth(ctx context.Context, opts ...DeviceCodeAuthOption) (*devicecode.Auth, bool, error) {
o := &DeviceCodeAuthOptions{}
o.ApplyOptions(opts)
endpoint := bo.endpointFactory(o.ProviderOptions)
if endpoint.DeviceURL == "" {
return nil, false, nil
}
cfg := &devicecode.Config{
Config: &oauth2.Config{
Endpoint: endpoint.Endpoint,
ClientID: bo.clientID,
Scopes: o.Scopes,
},
DeviceURL: endpoint.DeviceURL,
}
auth, err := cfg.DeviceCodeAuth(ctx)
return auth, err == nil, semerr.Map(err)
}
func (bo *basicOperations) DeviceCodeExchange(ctx context.Context, deviceCode string, opts ...DeviceCodeExchangeOption) (*Token, error) {
o := &DeviceCodeExchangeOptions{}
o.ApplyOptions(opts)
endpoint := bo.endpointFactory(o.ProviderOptions)
cfg := &devicecode.Config{
Config: &oauth2.Config{
Endpoint: endpoint.Endpoint,
ClientID: bo.clientID,
},
DeviceURL: endpoint.DeviceURL,
}
tok, err := cfg.DeviceCodeExchange(ctx, deviceCode)
if err != nil {
err = semerr.Map(err)
err = errmark.MarkUserIf(
err,
errmark.RuleAny(
semerr.RuleCode("access_denied"),
semerr.RuleCode("expired_token"),
),
)
return nil, err
}
return &Token{
Token: tok,
ProviderVersion: bo.vsn,
ProviderOptions: o.ProviderOptions,
}, nil
}
func (bo *basicOperations) AuthCodeExchange(ctx context.Context, code string, opts ...AuthCodeExchangeOption) (*Token, error) {
if bo.clientSecret == "" {
return nil, errmark.MarkUser(ErrMissingClientSecret)
}
o := &AuthCodeExchangeOptions{}
o.ApplyOptions(opts)
endpoint := bo.endpointFactory(o.ProviderOptions)
cfg := &oauth2.Config{
Endpoint: endpoint.Endpoint,
ClientID: bo.clientID,
ClientSecret: bo.clientSecret,
RedirectURL: o.RedirectURL,
}
tok, err := cfg.Exchange(ctx, code, o.AuthCodeOptions...)
if err != nil {
return nil, semerr.Map(err)
}
return &Token{
Token: tok,
ProviderVersion: bo.vsn,
ProviderOptions: o.ProviderOptions,
}, nil
}
func (bo *basicOperations) RefreshToken(ctx context.Context, t *Token, opts ...RefreshTokenOption) (*Token, error) {
o := &RefreshTokenOptions{}
WithProviderOptions(t.ProviderOptions).ApplyToRefreshTokenOptions(o)
o.ApplyOptions(opts)
endpoint := bo.endpointFactory(o.ProviderOptions)
cfg := &oauth2.Config{
Endpoint: endpoint.Endpoint,
ClientID: bo.clientID,
ClientSecret: bo.clientSecret,
}
tok, err := cfg.TokenSource(ctx, &oauth2.Token{
RefreshToken: t.RefreshToken,
}).Token()
if err != nil {
return nil, semerr.Map(err)
}
return &Token{
Token: tok,
ProviderVersion: bo.vsn,
ProviderOptions: o.ProviderOptions,
}, nil
}
func (bo *basicOperations) ClientCredentials(ctx context.Context, opts ...ClientCredentialsOption) (*Token, error) {
if bo.clientSecret == "" {
return nil, errmark.MarkUser(ErrMissingClientSecret)
}
o := &ClientCredentialsOptions{}
o.ApplyOptions(opts)
endpoint := bo.endpointFactory(o.ProviderOptions)
cc := &clientcredentials.Config{
ClientID: bo.clientID,
ClientSecret: bo.clientSecret,
TokenURL: endpoint.TokenURL,
AuthStyle: endpoint.AuthStyle,
Scopes: o.Scopes,
EndpointParams: o.EndpointParams,
}
tok, err := cc.Token(ctx)
if err != nil {
return nil, semerr.Map(err)
}
return &Token{
Token: tok,
ProviderVersion: bo.vsn,
ProviderOptions: o.ProviderOptions,
}, nil
}
func (bo *basicOperations) TokenExchange(ctx context.Context, t *Token, opts ...TokenExchangeOption) (*Token, error) {
if bo.clientSecret == "" {
return nil, errmark.MarkUser(ErrMissingClientSecret)
}
o := &TokenExchangeOptions{}
o.ApplyOptions(opts)
endpoint := bo.endpointFactory(o.ProviderOptions)
cfg := &oauth2.Config{
Endpoint: endpoint.Endpoint,
ClientID: bo.clientID,
ClientSecret: bo.clientSecret,
}
// Add audiences and resources, which require multiple instances of the same
// parameter to be specified, and therefore can't use oauth2.AuthCodeOption.
ctx = clientctx.WithUpdatedRequestBody(ctx, func(body []byte) ([]byte, error) {
vs, err := url.ParseQuery(string(body))
if err != nil {
return nil, err
}
if len(o.Audiences) > 0 {
vs["audience"] = o.Audiences
}
if len(o.Resources) > 0 {
vs["resource"] = o.Resources
}
return []byte(vs.Encode()), nil
})
o.AuthCodeOptions = append(
o.AuthCodeOptions,
oauth2.SetAuthURLParam("grant_type", "urn:ietf:params:oauth:grant-type:token-exchange"),
oauth2.SetAuthURLParam("subject_token_type", "urn:ietf:params:oauth:token-type:access_token"),
oauth2.SetAuthURLParam("subject_token", t.AccessToken),
oauth2.SetAuthURLParam("requested_token_type", "urn:ietf:params:oauth:token-type:access_token"),
)
if len(o.Scopes) > 0 {
o.AuthCodeOptions = append(o.AuthCodeOptions, oauth2.SetAuthURLParam("scope", strings.Join(o.Scopes, " ")))
}
// Sending an empty code is harmless and this is the only way to use the
// regular token endpoint while switching the grant type.
tok, err := cfg.Exchange(ctx, "", o.AuthCodeOptions...)
if err != nil {
return nil, semerr.Map(err)
}
return &Token{
Token: tok,
ProviderVersion: bo.vsn,
ProviderOptions: o.ProviderOptions,
}, nil
}
type basic struct {
vsn int
endpointFactory EndpointFactoryFunc
}
func (b *basic) Version() int {
return b.vsn
}
func (b *basic) Public(clientID string) PublicOperations {
return b.Private(clientID, "")
}
func (b *basic) Private(clientID, clientSecret string) PrivateOperations {
return &basicOperations{
vsn: b.vsn,
endpointFactory: b.endpointFactory,
clientID: clientID,
clientSecret: clientSecret,
}
}
func BasicFactory(endpoint Endpoint) FactoryFunc {
return func(ctx context.Context, vsn int, opts map[string]string) (Provider, error) {
vsn = selectVersion(vsn, 1)
switch vsn {
case 1:
default:
return nil, ErrNoProviderWithVersion
}
if len(opts) != 0 {
return nil, ErrNoOptions
}
p := &basic{
vsn: vsn,
endpointFactory: StaticEndpointFactory(endpoint),
}
return p, nil
}
}
func AzureADFactory(ctx context.Context, vsn int, opts map[string]string) (Provider, error) {
vsn = selectVersion(vsn, 2)
tenant := opts["tenant"]
switch vsn {
case 2:
case 1:
if tenant == "" {
return nil, &OptionError{Option: "tenant", Cause: fmt.Errorf("tenant is required")}
}
default:
return nil, ErrNoProviderWithVersion
}
p := &basic{
vsn: vsn,
endpointFactory: func(credOpts map[string]string) Endpoint {
chosenTenant := "organizations" // https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-protocols#endpoints
if tenant != "" {
chosenTenant = tenant
} else if credTenant := credOpts["tenant"]; credTenant != "" {
chosenTenant = credTenant
}
// Upstream function does not escape this name, so we will here.
chosenTenant = url.PathEscape(chosenTenant)
return Endpoint{
Endpoint: microsoft.AzureADEndpoint(chosenTenant),
DeviceURL: "https://login.microsoftonline.com/" + chosenTenant + "/oauth2/v2.0/devicecode", // https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-device-code
}
},
}
return p, nil
}
func CustomFactory(ctx context.Context, vsn int, opts map[string]string) (Provider, error) {
vsn = selectVersion(vsn, 2)
switch vsn {
case 2:
case 1:
// discovery_url is now deprecated since we have a complete OIDC
// provider, but will be honored for existing configurations.
discoveryURL := opts["discovery_url"]
if discoveryURL != "" {
provider, err := gooidc.NewProvider(ctx, discoveryURL)
if err != nil {
return nil, &OptionError{Option: "discovery_url", Cause: fmt.Errorf("error making new provider: %w", err)}
}
opts["auth_code_url"] = provider.Endpoint().AuthURL
opts["token_url"] = provider.Endpoint().TokenURL
}
default:
return nil, ErrNoProviderWithVersion
}
if opts["token_url"] == "" {
return nil, &OptionError{Option: "token_url", Cause: fmt.Errorf("token URL is required")}
}
authStyle := oauth2.AuthStyleAutoDetect
switch opts["auth_style"] {
case "in_header":
authStyle = oauth2.AuthStyleInHeader
case "in_params":
authStyle = oauth2.AuthStyleInParams
case "":
default:
return nil, &OptionError{Option: "auth_style", Cause: fmt.Errorf(`unknown authentication style; expected one of "in_header" or "in_params"`)}
}
endpoint := Endpoint{
Endpoint: oauth2.Endpoint{
AuthURL: opts["auth_code_url"],
TokenURL: opts["token_url"],
AuthStyle: authStyle,
},
DeviceURL: opts["device_code_url"],
}
p := &basic{
vsn: vsn,
endpointFactory: StaticEndpointFactory(endpoint),
}
return p, nil
}