-
Notifications
You must be signed in to change notification settings - Fork 289
/
oidc.go
354 lines (308 loc) · 9.43 KB
/
oidc.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
// Copyright Envoy Gateway Authors
// SPDX-License-Identifier: Apache-2.0
// The full text of the Apache license is available in the LICENSE file at
// the root of the repo.
package translator
import (
"errors"
"fmt"
corev3 "github.com/envoyproxy/go-control-plane/envoy/config/core/v3"
routev3 "github.com/envoyproxy/go-control-plane/envoy/config/route/v3"
oauth2v3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/oauth2/v3"
hcmv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3"
tlsv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/transport_sockets/tls/v3"
matcherv3 "github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3"
"google.golang.org/protobuf/types/known/anypb"
"google.golang.org/protobuf/types/known/durationpb"
"k8s.io/utils/ptr"
"github.com/envoyproxy/gateway/internal/ir"
"github.com/envoyproxy/gateway/internal/xds/types"
)
const (
oauth2Filter = "envoy.filters.http.oauth2"
)
func init() {
registerHTTPFilter(&oidc{})
}
type oidc struct{}
var _ httpFilter = &oidc{}
// patchHCM builds and appends the oauth2 Filters to the HTTP Connection Manager
// if applicable, and it does not already exist.
// Note: this method creates an oauth2 filter for each route that contains an OIDC config.
// the filter is disabled by default. It is enabled on the route level.
func (*oidc) patchHCM(mgr *hcmv3.HttpConnectionManager, irListener *ir.HTTPListener) error {
var errs error
if mgr == nil {
return errors.New("hcm is nil")
}
if irListener == nil {
return errors.New("ir listener is nil")
}
for _, route := range irListener.Routes {
if !routeContainsOIDC(route) {
continue
}
// Only generates one BasicAuth Envoy filter for each unique name.
// For example, if there are two routes under the same gateway with the
// same BasicAuth config, only one BasicAuth filter will be generated.
if hcmContainsFilter(mgr, oauth2FilterName(route.Security.OIDC)) {
continue
}
filter, err := buildHCMOAuth2Filter(route.Security.OIDC)
if err != nil {
errs = errors.Join(errs, err)
continue
}
mgr.HttpFilters = append(mgr.HttpFilters, filter)
}
return errs
}
// buildHCMOAuth2Filter returns an OAuth2 HTTP filter from the provided IR HTTPRoute.
func buildHCMOAuth2Filter(oidc *ir.OIDC) (*hcmv3.HttpFilter, error) {
oauth2Proto, err := oauth2Config(oidc)
if err != nil {
return nil, err
}
if err := oauth2Proto.ValidateAll(); err != nil {
return nil, err
}
OAuth2Any, err := anypb.New(oauth2Proto)
if err != nil {
return nil, err
}
return &hcmv3.HttpFilter{
Name: oauth2FilterName(oidc),
Disabled: true,
ConfigType: &hcmv3.HttpFilter_TypedConfig{
TypedConfig: OAuth2Any,
},
}, nil
}
func oauth2FilterName(oidc *ir.OIDC) string {
return perRouteFilterName(oauth2Filter, oidc.Name)
}
func oauth2Config(oidc *ir.OIDC) (*oauth2v3.OAuth2, error) {
cluster, err := url2Cluster(oidc.Provider.TokenEndpoint)
if err != nil {
return nil, err
}
if cluster.endpointType == EndpointTypeStatic {
return nil, fmt.Errorf(
"static IP cluster is not allowed: %s",
oidc.Provider.TokenEndpoint)
}
oauth2 := &oauth2v3.OAuth2{
Config: &oauth2v3.OAuth2Config{
TokenEndpoint: &corev3.HttpUri{
Uri: oidc.Provider.TokenEndpoint,
HttpUpstreamType: &corev3.HttpUri_Cluster{
Cluster: cluster.name,
},
Timeout: &durationpb.Duration{
Seconds: defaultExtServiceRequestTimeout,
},
},
AuthorizationEndpoint: oidc.Provider.AuthorizationEndpoint,
RedirectUri: oidc.RedirectURL,
RedirectPathMatcher: &matcherv3.PathMatcher{
Rule: &matcherv3.PathMatcher_Path{
Path: &matcherv3.StringMatcher{
MatchPattern: &matcherv3.StringMatcher_Exact{
Exact: oidc.RedirectPath,
},
},
},
},
SignoutPath: &matcherv3.PathMatcher{
Rule: &matcherv3.PathMatcher_Path{
Path: &matcherv3.StringMatcher{
MatchPattern: &matcherv3.StringMatcher_Exact{
Exact: oidc.LogoutPath,
},
},
},
},
ForwardBearerToken: true,
Credentials: &oauth2v3.OAuth2Credentials{
ClientId: oidc.ClientID,
TokenSecret: &tlsv3.SdsSecretConfig{
Name: oauth2ClientSecretName(oidc),
SdsConfig: makeConfigSource(),
},
TokenFormation: &oauth2v3.OAuth2Credentials_HmacSecret{
HmacSecret: &tlsv3.SdsSecretConfig{
Name: oauth2HMACSecretName(oidc),
SdsConfig: makeConfigSource(),
},
},
CookieNames: &oauth2v3.OAuth2Credentials_CookieNames{
BearerToken: fmt.Sprintf("BearerToken-%s", oidc.CookieSuffix),
OauthHmac: fmt.Sprintf("OauthHMAC-%s", oidc.CookieSuffix),
OauthExpires: fmt.Sprintf("OauthExpires-%s", oidc.CookieSuffix),
IdToken: fmt.Sprintf("IdToken-%s", oidc.CookieSuffix),
RefreshToken: fmt.Sprintf("RefreshToken-%s", oidc.CookieSuffix),
},
},
// every OIDC provider supports basic auth
AuthType: oauth2v3.OAuth2Config_BASIC_AUTH,
AuthScopes: oidc.Scopes,
Resources: oidc.Resources,
},
}
return oauth2, nil
}
// routeContainsOIDC returns true if OIDC exists for the provided route.
func routeContainsOIDC(irRoute *ir.HTTPRoute) bool {
if irRoute != nil &&
irRoute.Security != nil &&
irRoute.Security.OIDC != nil {
return true
}
return false
}
func (*oidc) patchResources(tCtx *types.ResourceVersionTable,
routes []*ir.HTTPRoute,
) error {
if err := createOAuth2TokenEndpointClusters(tCtx, routes); err != nil {
return err
}
if err := createOAuth2Secrets(tCtx, routes); err != nil {
return err
}
return nil
}
// createOAuth2TokenEndpointClusters creates token endpoint clusters from the
// provided routes, if needed.
func createOAuth2TokenEndpointClusters(tCtx *types.ResourceVersionTable,
routes []*ir.HTTPRoute,
) error {
if tCtx == nil || tCtx.XdsResources == nil {
return errors.New("xds resource table is nil")
}
var errs error
for _, route := range routes {
if !routeContainsOIDC(route) {
continue
}
var (
cluster *urlCluster
ds *ir.DestinationSetting
tSocket *corev3.TransportSocket
err error
)
cluster, err = url2Cluster(route.Security.OIDC.Provider.TokenEndpoint)
if err != nil {
errs = errors.Join(errs, err)
continue
}
// EG does not support static IP clusters for token endpoint clusters.
// This validation could be removed since it's already validated in the
// Gateway API translator.
if cluster.endpointType == EndpointTypeStatic {
errs = errors.Join(errs, fmt.Errorf(
"static IP cluster is not allowed: %s",
route.Security.OIDC.Provider.TokenEndpoint))
continue
}
ds = &ir.DestinationSetting{
Weight: ptr.To[uint32](1),
Endpoints: []*ir.DestinationEndpoint{
ir.NewDestEndpoint(
cluster.hostname,
cluster.port),
},
}
clusterArgs := &xdsClusterArgs{
name: cluster.name,
settings: []*ir.DestinationSetting{ds},
tSocket: tSocket,
endpointType: cluster.endpointType,
}
if cluster.tls {
tSocket, err = buildXdsUpstreamTLSSocket(cluster.hostname)
if err != nil {
errs = errors.Join(errs, err)
continue
}
clusterArgs.tSocket = tSocket
}
if err = addXdsCluster(tCtx, clusterArgs); err != nil && !errors.Is(err, ErrXdsClusterExists) {
errs = errors.Join(errs, err)
}
}
return errs
}
// createOAuth2Secrets creates OAuth2 client and HMAC secrets from the provided
// routes, if needed.
func createOAuth2Secrets(tCtx *types.ResourceVersionTable, routes []*ir.HTTPRoute) error {
var errs error
for _, route := range routes {
if !routeContainsOIDC(route) {
continue
}
// a separate secret is created for each route, even they share the same
// oauth2 client ID and secret.
clientSecret := buildOAuth2ClientSecret(route.Security.OIDC)
if err := addXdsSecret(tCtx, clientSecret); err != nil {
errs = errors.Join(errs, err)
}
if err := addXdsSecret(tCtx, buildOAuth2HMACSecret(route.Security.OIDC)); err != nil {
errs = errors.Join(errs, err)
}
}
return errs
}
func buildOAuth2ClientSecret(oidc *ir.OIDC) *tlsv3.Secret {
clientSecret := &tlsv3.Secret{
Name: oauth2ClientSecretName(oidc),
Type: &tlsv3.Secret_GenericSecret{
GenericSecret: &tlsv3.GenericSecret{
Secret: &corev3.DataSource{
Specifier: &corev3.DataSource_InlineBytes{
InlineBytes: oidc.ClientSecret,
},
},
},
},
}
return clientSecret
}
func buildOAuth2HMACSecret(oidc *ir.OIDC) *tlsv3.Secret {
hmacSecret := &tlsv3.Secret{
Name: oauth2HMACSecretName(oidc),
Type: &tlsv3.Secret_GenericSecret{
GenericSecret: &tlsv3.GenericSecret{
Secret: &corev3.DataSource{
Specifier: &corev3.DataSource_InlineBytes{
InlineBytes: oidc.HMACSecret,
},
},
},
},
}
return hmacSecret
}
func oauth2ClientSecretName(oidc *ir.OIDC) string {
return fmt.Sprintf("oauth2/client_secret/%s", oidc.Name)
}
func oauth2HMACSecretName(oidc *ir.OIDC) string {
return fmt.Sprintf("oauth2/hmac_secret/%s", oidc.Name)
}
// patchRoute patches the provided route with the oauth2 config if applicable.
// Note: this method enables the corresponding oauth2 filter for the provided route.
func (*oidc) patchRoute(route *routev3.Route, irRoute *ir.HTTPRoute) error {
if route == nil {
return errors.New("xds route is nil")
}
if irRoute == nil {
return errors.New("ir route is nil")
}
if irRoute.Security == nil || irRoute.Security.OIDC == nil {
return nil
}
filterName := oauth2FilterName(irRoute.Security.OIDC)
if err := enableFilterOnRoute(route, filterName); err != nil {
return err
}
return nil
}