/
grantconfig.go
355 lines (292 loc) · 9.93 KB
/
grantconfig.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
package auth
import (
"errors"
"fmt"
"net"
"net/http"
"path/filepath"
"strings"
"time"
"github.com/opentracing/opentracing-go"
"github.com/zalando/skipper/filters"
snet "github.com/zalando/skipper/net"
"github.com/zalando/skipper/routing"
"github.com/zalando/skipper/secrets"
"golang.org/x/oauth2"
)
type OAuthConfig struct {
initialized bool
flowState *flowState
grantTokeninfoKeysLookup map[string]struct{}
getClientId func(*http.Request) (string, error)
getClientSecret func(*http.Request) (string, error)
// TokeninfoURL is the URL of the service to validate OAuth2 tokens.
TokeninfoURL string
// Secrets is a secret registry to access secret keys used for encrypting
// auth flow state and auth cookies.
Secrets *secrets.Registry
// SecretFile contains the filename with the encryption key for the authentication
// cookie and grant flow state stored in Secrets.
SecretFile string
// AuthURL, the url to redirect the requests to when login is required.
AuthURL string
// TokenURL, the url where the access code should be exchanged for the
// access token.
TokenURL string
// RevokeTokenURL, the url where the access and revoke tokens can be
// revoked during a logout.
RevokeTokenURL string
// CallbackPath contains the path where the callback requests with the
// authorization code should be redirected to.
CallbackPath string
// ClientID, the OAuth2 client id of the current service, used to exchange
// the access code. Must be set if ClientIDFile is not provided.
ClientID string
// ClientSecret, the secret associated with the ClientID, used to exchange
// the access code. Must be set if ClientSecretFile is not provided.
ClientSecret string
// ClientIDFile, the path to the file containing the OAuth2 client id of
// the current service, used to exchange the access code.
// Must be set if ClientID is not provided.
// File name may contain {host} placeholder which will be replaced by the request host.
// Requires SecretsProvider, the path (or path's directory if placeholder is present) will be added to it.
ClientIDFile string
// ClientSecretFile, the path to the file containing the secret associated
// with the ClientID, used to exchange the access code.
// Must be set if ClientSecret is not provided.
// File name may contain {host} placeholder which will be replaced by the request host.
// Requires SecretsProvider, the path (or path's directory if placeholder is present) will be added to it.
ClientSecretFile string
// SecretsProvider is used to read ClientIDFile and ClientSecretFile from the
// file system. Supports secret rotation.
SecretsProvider secrets.SecretsProvider
// TokeninfoClient, optional. When set, it will be used for the
// authorization requests to TokeninfoURL. When not set, a new default
// client is created.
TokeninfoClient *authClient
// AuthClient, optional. When set, it will be used for the
// access code exchange requests to TokenURL. When not set, a new default
// client is created.
AuthClient *snet.Client
// AuthURLParameters, optional. Extra URL parameters to add when calling
// the OAuth2 authorize or token endpoints.
AuthURLParameters map[string]string
// AccessTokenHeaderName, optional. When set, the access token will be set
// on the request to a header with this name.
AccessTokenHeaderName string
// GrantTokeninfoKeys, optional. When not empty, keys not in this list are removed from the tokeninfo map.
GrantTokeninfoKeys []string
// TokeninfoSubjectKey, optional. When set, it is used to look up the subject
// ID in the tokeninfo map received from a tokeninfo endpoint request.
TokeninfoSubjectKey string
// TokenCookieName, optional. The name of the cookie used to store the
// encrypted access token after a successful token exchange.
TokenCookieName string
// TokenCookieRemoveSubdomains sets the number of subdomains to remove from
// the callback request hostname to obtain token cookie domain.
// Init converts default nil to 1.
TokenCookieRemoveSubdomains *int
// ConnectionTimeout used for tokeninfo, access-token and refresh-token endpoint.
ConnectionTimeout time.Duration
// MaxIdleConnectionsPerHost used for tokeninfo, access-token and refresh-token endpoint.
MaxIdleConnectionsPerHost int
// Tracer used for tokeninfo, access-token and refresh-token endpoint.
Tracer opentracing.Tracer
}
var (
ErrMissingClientID = errors.New("missing client ID")
ErrMissingClientSecret = errors.New("missing client secret")
ErrMissingSecretsProvider = errors.New("missing secrets provider")
ErrMissingSecretsRegistry = errors.New("missing secrets registry")
ErrMissingSecretFile = errors.New("missing secret file")
ErrMissingTokeninfoURL = errors.New("missing tokeninfo URL")
ErrMissingProviderURLs = errors.New("missing provider URLs")
)
func (c *OAuthConfig) Init() error {
if c.initialized {
return nil
}
if c.TokeninfoURL == "" {
return ErrMissingTokeninfoURL
}
if c.AuthURL == "" || c.TokenURL == "" {
return ErrMissingProviderURLs
}
if c.Secrets == nil {
return ErrMissingSecretsRegistry
}
if c.SecretFile == "" {
return ErrMissingSecretFile
}
if c.CallbackPath == "" {
c.CallbackPath = defaultCallbackPath
}
if c.TokenCookieName == "" {
c.TokenCookieName = defaultTokenCookieName
}
if c.TokenCookieRemoveSubdomains == nil {
one := 1
c.TokenCookieRemoveSubdomains = &one
} else if *c.TokenCookieRemoveSubdomains < 0 {
return fmt.Errorf("invalid number of cookie subdomains to remove")
}
if c.TokeninfoClient == nil {
client, err := newAuthClient(
c.TokeninfoURL,
"granttokeninfo",
c.ConnectionTimeout,
c.MaxIdleConnectionsPerHost,
c.Tracer,
)
if err != nil {
return err
}
c.TokeninfoClient = client
}
if c.AuthClient == nil {
c.AuthClient = snet.NewClient(snet.Options{
ResponseHeaderTimeout: c.ConnectionTimeout,
TLSHandshakeTimeout: c.ConnectionTimeout,
MaxIdleConnsPerHost: c.MaxIdleConnectionsPerHost,
Tracer: c.Tracer,
OpentracingComponentTag: "skipper",
OpentracingSpanName: "grantauth",
})
}
c.flowState = newFlowState(c.Secrets, c.SecretFile)
if c.ClientID != "" {
c.getClientId = func(*http.Request) (string, error) {
return c.ClientID, nil
}
} else if c.ClientIDFile != "" {
if c.SecretsProvider == nil {
return ErrMissingSecretsProvider
}
if hasPlaceholders(c.ClientIDFile) {
c.getClientId = func(req *http.Request) (string, error) {
return c.getSecret(resolvePlaceholders(c.ClientIDFile, req))
}
if err := c.SecretsProvider.Add(filepath.Dir(c.ClientIDFile)); err != nil {
return err
}
} else {
c.getClientId = func(*http.Request) (string, error) {
return c.getSecret(c.ClientIDFile)
}
if err := c.SecretsProvider.Add(c.ClientIDFile); err != nil {
return err
}
}
} else {
return ErrMissingClientID
}
if c.ClientSecret != "" {
c.getClientSecret = func(*http.Request) (string, error) {
return c.ClientSecret, nil
}
} else if c.ClientSecretFile != "" {
if c.SecretsProvider == nil {
return ErrMissingSecretsProvider
}
if hasPlaceholders(c.ClientSecretFile) {
c.getClientSecret = func(req *http.Request) (string, error) {
return c.getSecret(resolvePlaceholders(c.ClientSecretFile, req))
}
if err := c.SecretsProvider.Add(filepath.Dir(c.ClientSecretFile)); err != nil {
return err
}
} else {
c.getClientSecret = func(*http.Request) (string, error) {
return c.getSecret(c.ClientSecretFile)
}
if err := c.SecretsProvider.Add(c.ClientSecretFile); err != nil {
return err
}
}
} else {
return ErrMissingClientSecret
}
if len(c.GrantTokeninfoKeys) > 0 {
c.grantTokeninfoKeysLookup = make(map[string]struct{}, len(c.GrantTokeninfoKeys))
for _, key := range c.GrantTokeninfoKeys {
c.grantTokeninfoKeysLookup[key] = struct{}{}
}
}
c.initialized = true
return nil
}
func (c *OAuthConfig) NewGrant() filters.Spec {
return &grantSpec{config: c}
}
func (c *OAuthConfig) NewGrantCallback() filters.Spec {
return &grantCallbackSpec{config: c}
}
func (c *OAuthConfig) NewGrantClaimsQuery() filters.Spec {
return &grantClaimsQuerySpec{
oidcSpec: oidcIntrospectionSpec{
typ: checkOIDCQueryClaims,
},
}
}
func (c *OAuthConfig) NewGrantLogout() filters.Spec {
return &grantLogoutSpec{config: c}
}
func (c *OAuthConfig) NewGrantPreprocessor() routing.PreProcessor {
return &grantPrep{config: c}
}
func (c *OAuthConfig) GetConfig(req *http.Request) (*oauth2.Config, error) {
var err error
authConfig := &oauth2.Config{
Endpoint: oauth2.Endpoint{
AuthURL: c.AuthURL,
TokenURL: c.TokenURL,
},
}
authConfig.ClientID, err = c.getClientId(req)
if err != nil {
return nil, err
}
authConfig.ClientSecret, err = c.getClientSecret(req)
if err != nil {
return nil, err
}
return authConfig, nil
}
func (c *OAuthConfig) getSecret(file string) (string, error) {
if secret, ok := c.SecretsProvider.GetSecret(file); ok {
return string(secret), nil
} else {
return "", fmt.Errorf("secret %s does not exist", file)
}
}
func resolvePlaceholders(s string, r *http.Request) string {
h, _, err := net.SplitHostPort(r.Host)
if err != nil {
h = r.Host
}
return strings.ReplaceAll(s, "{host}", h)
}
func hasPlaceholders(s string) bool {
return resolvePlaceholders(s, &http.Request{Host: "example.org"}) != s
}
func (c *OAuthConfig) GetAuthURLParameters(redirectURI string) []oauth2.AuthCodeOption {
params := []oauth2.AuthCodeOption{oauth2.SetAuthURLParam("redirect_uri", redirectURI)}
if c.AuthURLParameters != nil {
for k, v := range c.AuthURLParameters {
params = append(params, oauth2.SetAuthURLParam(k, v))
}
}
return params
}
// RedirectURLs constructs the redirect URI based on the request and the
// configured CallbackPath.
func (c *OAuthConfig) RedirectURLs(req *http.Request) (redirect, original string) {
u := *req.URL
u.Scheme = "https"
u.Host = req.Host
original = u.String()
u.Path = c.CallbackPath
u.RawQuery = ""
redirect = u.String()
return
}