-
Notifications
You must be signed in to change notification settings - Fork 33
/
authpolicy_authconfig.go
570 lines (499 loc) · 19.2 KB
/
authpolicy_authconfig.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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
package controllers
import (
"context"
"errors"
"fmt"
"reflect"
"strings"
"k8s.io/utils/ptr"
"github.com/go-logr/logr"
authorinoapi "github.com/kuadrant/authorino/api/v1beta2"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1"
api "github.com/kuadrant/kuadrant-operator/api/v1beta2"
"github.com/kuadrant/kuadrant-operator/pkg/common"
"github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant"
"github.com/kuadrant/kuadrant-operator/pkg/library/utils"
)
func (r *AuthPolicyReconciler) reconcileAuthConfigs(ctx context.Context, ap *api.AuthPolicy, targetNetworkObject client.Object) error {
logger, err := logr.FromContext(ctx)
if err != nil {
return err
}
authConfig, err := r.desiredAuthConfig(ctx, ap, targetNetworkObject)
if err != nil {
return err
}
err = r.SetOwnerReference(ap, authConfig)
if err != nil {
return err
}
err = r.ReconcileResource(ctx, &authorinoapi.AuthConfig{}, authConfig, authConfigBasicMutator)
if err != nil && !apierrors.IsAlreadyExists(err) {
logger.Error(err, "ReconcileResource failed to create/update AuthConfig resource")
return err
}
return nil
}
func (r *AuthPolicyReconciler) desiredAuthConfig(ctx context.Context, ap *api.AuthPolicy, targetNetworkObject client.Object) (*authorinoapi.AuthConfig, error) {
logger, _ := logr.FromContext(ctx)
logger = logger.WithName("desiredAuthConfig")
authConfig := &authorinoapi.AuthConfig{
TypeMeta: metav1.TypeMeta{
Kind: "AuthConfig",
APIVersion: authorinoapi.GroupVersion.String(),
},
ObjectMeta: metav1.ObjectMeta{
Name: authConfigName(client.ObjectKeyFromObject(ap)),
Namespace: ap.Namespace,
},
Spec: authorinoapi.AuthConfigSpec{},
}
var route *gatewayapiv1.HTTPRoute
var hosts []string
switch obj := targetNetworkObject.(type) {
case *gatewayapiv1.HTTPRoute:
ok, err := routeGatewayHasAuthOverrides(ctx, obj, r.Client())
if err != nil {
return nil, err
}
if ok {
logger.V(1).Info("targeted gateway has authpolicy with atomic overrides, skipping authorino authconfig for the HTTPRoute authpolicy")
utils.TagObjectToDelete(authConfig)
r.OverriddenPolicyMap.SetOverriddenPolicy(ap)
return authConfig, nil
}
route = obj
hosts, err = kuadrant.HostnamesFromHTTPRoute(ctx, obj, r.Client())
if err != nil {
return nil, err
}
case *gatewayapiv1.Gateway:
// fake a single httproute with all rules from all httproutes accepted by the gateway,
// that do not have an authpolicy of its own, so we can generate wasm rules for those cases
gw := kuadrant.GatewayWrapper{Gateway: obj}
gwHostnames := gw.Hostnames()
if len(gwHostnames) == 0 {
gwHostnames = []gatewayapiv1.Hostname{"*"}
}
hosts = utils.HostnamesToStrings(gwHostnames)
rules := make([]gatewayapiv1.HTTPRouteRule, 0)
routes := r.TargetRefReconciler.FetchAcceptedGatewayHTTPRoutes(ctx, ap.TargetKey())
for idx := range routes {
route := routes[idx]
// skip routes that have an authpolicy of its own and Gateway authpolicy does not define atomic overrides
if route.GetAnnotations()[common.AuthPolicyBackRefAnnotation] != "" && !ap.IsAtomicOverride() {
continue
}
rules = append(rules, route.Spec.Rules...)
}
if len(rules) == 0 {
logger.V(1).Info("no httproutes attached to the targeted gateway, skipping authorino authconfig for the gateway authpolicy")
utils.TagObjectToDelete(authConfig)
r.OverriddenPolicyMap.SetOverriddenPolicy(ap)
return authConfig, nil
}
route = &gatewayapiv1.HTTPRoute{
Spec: gatewayapiv1.HTTPRouteSpec{
Hostnames: gwHostnames,
Rules: rules,
},
}
}
// AuthPolicy is not overridden if we still need to create an AuthConfig for it
r.OverriddenPolicyMap.RemoveOverriddenPolicy(ap)
// hosts
authConfig.Spec.Hosts = hosts
commonSpec := ap.Spec.CommonSpec()
// named patterns
if namedPatterns := commonSpec.NamedPatterns; len(namedPatterns) > 0 {
authConfig.Spec.NamedPatterns = namedPatterns
}
// top-level conditions
topLevelConditionsFromRouteSelectors, err := authorinoConditionsFromRouteSelectors(route, commonSpec)
if err != nil {
return nil, err
}
if len(topLevelConditionsFromRouteSelectors) == 0 {
topLevelConditionsFromRouteSelectors = authorinoConditionsFromHTTPRoute(route)
}
if len(topLevelConditionsFromRouteSelectors) > 0 || len(commonSpec.Conditions) > 0 {
authConfig.Spec.Conditions = append(commonSpec.Conditions, topLevelConditionsFromRouteSelectors...)
}
// return early if authScheme is nil
if commonSpec.AuthScheme == nil {
return authConfig, nil
}
// authentication
if authentication := commonSpec.AuthScheme.Authentication; len(authentication) > 0 {
authConfig.Spec.Authentication = authorinoSpecsFromConfigs(authentication, func(config api.AuthenticationSpec) authorinoapi.AuthenticationSpec { return config.AuthenticationSpec })
}
// metadata
if metadata := commonSpec.AuthScheme.Metadata; len(metadata) > 0 {
authConfig.Spec.Metadata = authorinoSpecsFromConfigs(metadata, func(config api.MetadataSpec) authorinoapi.MetadataSpec { return config.MetadataSpec })
}
// authorization
if authorization := commonSpec.AuthScheme.Authorization; len(authorization) > 0 {
authConfig.Spec.Authorization = authorinoSpecsFromConfigs(authorization, func(config api.AuthorizationSpec) authorinoapi.AuthorizationSpec { return config.AuthorizationSpec })
}
// response
if response := commonSpec.AuthScheme.Response; response != nil {
authConfig.Spec.Response = &authorinoapi.ResponseSpec{
Unauthenticated: response.Unauthenticated,
Unauthorized: response.Unauthorized,
Success: authorinoapi.WrappedSuccessResponseSpec{
Headers: authorinoSpecsFromConfigs(response.Success.Headers, func(config api.HeaderSuccessResponseSpec) authorinoapi.HeaderSuccessResponseSpec {
return authorinoapi.HeaderSuccessResponseSpec{SuccessResponseSpec: config.SuccessResponseSpec.SuccessResponseSpec}
}),
DynamicMetadata: authorinoSpecsFromConfigs(response.Success.DynamicMetadata, func(config api.SuccessResponseSpec) authorinoapi.SuccessResponseSpec {
return config.SuccessResponseSpec
}),
},
}
}
// callbacks
if callbacks := commonSpec.AuthScheme.Callbacks; len(callbacks) > 0 {
authConfig.Spec.Callbacks = authorinoSpecsFromConfigs(callbacks, func(config api.CallbackSpec) authorinoapi.CallbackSpec { return config.CallbackSpec })
}
return mergeConditionsFromRouteSelectorsIntoConfigs(ap, route, authConfig)
}
// routeGatewayHasAuthOverrides return true when the gateway which a route is attached to has an attached authPolicy that defines atomic overrides
func routeGatewayHasAuthOverrides(ctx context.Context, route *gatewayapiv1.HTTPRoute, c client.Client) (bool, error) {
for idx := range route.Spec.ParentRefs {
parentRef := route.Spec.ParentRefs[idx]
gw := &gatewayapiv1.Gateway{}
namespace := ptr.Deref(parentRef.Namespace, gatewayapiv1.Namespace(route.GetNamespace()))
err := c.Get(ctx, client.ObjectKey{Name: string(parentRef.Name), Namespace: string(namespace)}, gw)
if err != nil {
return false, err
}
annotation, ok := gw.GetAnnotations()[common.AuthPolicyBackRefAnnotation]
if !ok {
continue
}
otherAP := &api.AuthPolicy{}
err = c.Get(ctx, utils.NamespacedNameToObjectKey(annotation, gw.Namespace), otherAP)
if err != nil {
return false, err
}
if otherAP.IsAtomicOverride() {
return true, nil
}
}
return false, nil
}
// authConfigName returns the name of Authorino AuthConfig CR.
func authConfigName(apKey client.ObjectKey) string {
return fmt.Sprintf("ap-%s-%s", apKey.Namespace, apKey.Name)
}
func authorinoSpecsFromConfigs[T, U any](configs map[string]U, extractAuthorinoSpec func(U) T) map[string]T {
specs := make(map[string]T, len(configs))
for name, config := range configs {
authorinoConfig := extractAuthorinoSpec(config)
specs[name] = authorinoConfig
}
if len(specs) == 0 {
return nil
}
return specs
}
func mergeConditionsFromRouteSelectorsIntoConfigs(ap *api.AuthPolicy, route *gatewayapiv1.HTTPRoute, authConfig *authorinoapi.AuthConfig) (*authorinoapi.AuthConfig, error) {
commonSpec := ap.Spec.CommonSpec()
// authentication
for name, config := range commonSpec.AuthScheme.Authentication {
conditions, err := authorinoConditionsFromRouteSelectors(route, config)
if err != nil {
return nil, err
}
if len(conditions) == 0 {
continue
}
c := authConfig.Spec.Authentication[name]
c.Conditions = append(c.Conditions, conditions...)
authConfig.Spec.Authentication[name] = c
}
// metadata
for name, config := range commonSpec.AuthScheme.Metadata {
conditions, err := authorinoConditionsFromRouteSelectors(route, config)
if err != nil {
return nil, err
}
if len(conditions) == 0 {
continue
}
c := authConfig.Spec.Metadata[name]
c.Conditions = append(c.Conditions, conditions...)
authConfig.Spec.Metadata[name] = c
}
// authorization
for name, config := range commonSpec.AuthScheme.Authorization {
conditions, err := authorinoConditionsFromRouteSelectors(route, config)
if err != nil {
return nil, err
}
if len(conditions) == 0 {
continue
}
c := authConfig.Spec.Authorization[name]
c.Conditions = append(c.Conditions, conditions...)
authConfig.Spec.Authorization[name] = c
}
// response
if response := commonSpec.AuthScheme.Response; response != nil {
// response success headers
for name, config := range response.Success.Headers {
conditions, err := authorinoConditionsFromRouteSelectors(route, config)
if err != nil {
return nil, err
}
if len(conditions) == 0 {
continue
}
c := authConfig.Spec.Response.Success.Headers[name]
c.Conditions = append(c.Conditions, conditions...)
authConfig.Spec.Response.Success.Headers[name] = c
}
// response success dynamic metadata
for name, config := range response.Success.DynamicMetadata {
conditions, err := authorinoConditionsFromRouteSelectors(route, config)
if err != nil {
return nil, err
}
if len(conditions) == 0 {
continue
}
c := authConfig.Spec.Response.Success.DynamicMetadata[name]
c.Conditions = append(c.Conditions, conditions...)
authConfig.Spec.Response.Success.DynamicMetadata[name] = c
}
}
// callbacks
for name, config := range commonSpec.AuthScheme.Callbacks {
conditions, err := authorinoConditionsFromRouteSelectors(route, config)
if err != nil {
return nil, err
}
if len(conditions) == 0 {
continue
}
c := authConfig.Spec.Callbacks[name]
c.Conditions = append(c.Conditions, conditions...)
authConfig.Spec.Callbacks[name] = c
}
return authConfig, nil
}
// authorinoConditionFromRouteSelectors builds a list of Authorino conditions from a config that may specify route selectors
func authorinoConditionsFromRouteSelectors(route *gatewayapiv1.HTTPRoute, config api.RouteSelectorsGetter) ([]authorinoapi.PatternExpressionOrRef, error) {
routeSelectors := config.GetRouteSelectors()
if len(routeSelectors) == 0 {
return nil, nil
}
// build conditions from the rules selected by the route selectors
conditions := []authorinoapi.PatternExpressionOrRef{}
for idx := range routeSelectors {
routeSelector := routeSelectors[idx]
hostnamesForConditions := routeSelector.HostnamesForConditions(route)
for _, rule := range routeSelector.SelectRules(route) {
conditions = append(conditions, authorinoConditionsFromHTTPRouteRule(rule, hostnamesForConditions)...)
}
}
if len(conditions) == 0 {
return nil, errors.New("cannot match any route rules, check for invalid route selectors in the policy")
}
return toAuthorinoOneOfPatternExpressionsOrRefs(conditions), nil
}
// authorinoConditionsFromHTTPRoute builds a list of Authorino conditions from an HTTPRoute, without using route selectors.
func authorinoConditionsFromHTTPRoute(route *gatewayapiv1.HTTPRoute) []authorinoapi.PatternExpressionOrRef {
conditions := []authorinoapi.PatternExpressionOrRef{}
hostnamesForConditions := (&api.RouteSelector{}).HostnamesForConditions(route)
for _, rule := range route.Spec.Rules {
conditions = append(conditions, authorinoConditionsFromHTTPRouteRule(rule, hostnamesForConditions)...)
}
return toAuthorinoOneOfPatternExpressionsOrRefs(conditions)
}
// authorinoConditionsFromHTTPRouteRule builds a list of Authorino conditions from a HTTPRouteRule and a list of hostnames
// * Each combination of HTTPRouteMatch and hostname yields one condition.
// * Rules that specify no explicit HTTPRouteMatch are assumed to match all requests (i.e. implicit catch-all rule.)
// * Empty list of hostnames yields a condition without a hostname pattern expression.
func authorinoConditionsFromHTTPRouteRule(rule gatewayapiv1.HTTPRouteRule, hostnames []gatewayapiv1.Hostname) []authorinoapi.PatternExpressionOrRef {
hosts := []string{}
for _, hostname := range hostnames {
if hostname == "*" {
continue
}
hosts = append(hosts, string(hostname))
}
// no http route matches → we only need one simple authorino condition or even no condition at all
if len(rule.Matches) == 0 {
if len(hosts) == 0 {
return nil
}
return []authorinoapi.PatternExpressionOrRef{hostnameRuleToAuthorinoCondition(hosts)}
}
var oneOf []authorinoapi.PatternExpressionOrRef
// http route matches and possibly hostnames → we need one authorino rule per http route match
for _, match := range rule.Matches {
var allOf []authorinoapi.PatternExpressionOrRef
// hosts
if len(hosts) > 0 {
allOf = append(allOf, hostnameRuleToAuthorinoCondition(hosts))
}
// method
if method := match.Method; method != nil {
allOf = append(allOf, httpMethodRuleToAuthorinoCondition(*method))
}
// path
if path := match.Path; path != nil {
allOf = append(allOf, httpPathRuleToAuthorinoCondition(*path))
}
// headers
if headers := match.Headers; len(headers) > 0 {
allOf = append(allOf, httpHeadersRuleToAuthorinoConditions(headers)...)
}
// query params
if queryParams := match.QueryParams; len(queryParams) > 0 {
allOf = append(allOf, httpQueryParamsRuleToAuthorinoConditions(queryParams)...)
}
if len(allOf) > 0 {
oneOf = append(oneOf, authorinoapi.PatternExpressionOrRef{
All: utils.Map(allOf, toAuthorinoUnstructuredPatternExpressionOrRef),
})
}
}
return toAuthorinoOneOfPatternExpressionsOrRefs(oneOf)
}
func hostnameRuleToAuthorinoCondition(hostnames []string) authorinoapi.PatternExpressionOrRef {
return authorinoapi.PatternExpressionOrRef{
PatternExpression: authorinoapi.PatternExpression{
Selector: "request.host",
Operator: "matches",
Value: hostnamesToRegex(hostnames),
},
}
}
func hostnamesToRegex(hostnames []string) string {
return strings.Join(utils.Map(hostnames, func(hostname string) string {
return strings.ReplaceAll(strings.ReplaceAll(hostname, ".", `\.`), "*", ".*")
}), "|")
}
func httpMethodRuleToAuthorinoCondition(method gatewayapiv1.HTTPMethod) authorinoapi.PatternExpressionOrRef {
return authorinoapi.PatternExpressionOrRef{
PatternExpression: authorinoapi.PatternExpression{
Selector: "request.method",
Operator: "eq",
Value: string(method),
},
}
}
func httpPathRuleToAuthorinoCondition(path gatewayapiv1.HTTPPathMatch) authorinoapi.PatternExpressionOrRef {
value := "/"
if path.Value != nil {
value = *path.Value
}
var operator string
matchType := path.Type
if matchType == nil {
p := gatewayapiv1.PathMatchPathPrefix
matchType = &p // gateway api defaults to PathMatchPathPrefix
}
switch *matchType {
case gatewayapiv1.PathMatchExact:
operator = "eq"
case gatewayapiv1.PathMatchPathPrefix:
operator = "matches"
value += ".*"
case gatewayapiv1.PathMatchRegularExpression:
operator = "matches"
}
return authorinoapi.PatternExpressionOrRef{
PatternExpression: authorinoapi.PatternExpression{
Selector: `request.url_path`,
Operator: authorinoapi.PatternExpressionOperator(operator),
Value: value,
},
}
}
func httpHeadersRuleToAuthorinoConditions(headers []gatewayapiv1.HTTPHeaderMatch) []authorinoapi.PatternExpressionOrRef {
conditions := make([]authorinoapi.PatternExpressionOrRef, 0, len(headers))
for _, header := range headers {
condition := httpHeaderRuleToAuthorinoCondition(header)
conditions = append(conditions, condition)
}
return conditions
}
func httpHeaderRuleToAuthorinoCondition(header gatewayapiv1.HTTPHeaderMatch) authorinoapi.PatternExpressionOrRef {
operator := "eq" // gateway api defaults to HeaderMatchExact
if header.Type != nil && *header.Type == gatewayapiv1.HeaderMatchRegularExpression {
operator = "matches"
}
return authorinoapi.PatternExpressionOrRef{
PatternExpression: authorinoapi.PatternExpression{
Selector: fmt.Sprintf("request.headers.%s", strings.ToLower(string(header.Name))),
Operator: authorinoapi.PatternExpressionOperator(operator),
Value: header.Value,
},
}
}
func httpQueryParamsRuleToAuthorinoConditions(queryParams []gatewayapiv1.HTTPQueryParamMatch) []authorinoapi.PatternExpressionOrRef {
conditions := make([]authorinoapi.PatternExpressionOrRef, 0, len(queryParams))
for _, queryParam := range queryParams {
condition := httpQueryParamRuleToAuthorinoCondition(queryParam)
conditions = append(conditions, condition)
}
return conditions
}
func httpQueryParamRuleToAuthorinoCondition(queryParam gatewayapiv1.HTTPQueryParamMatch) authorinoapi.PatternExpressionOrRef {
operator := "eq" // gateway api defaults to QueryParamMatchExact
if queryParam.Type != nil && *queryParam.Type == gatewayapiv1.QueryParamMatchRegularExpression {
operator = "matches"
}
return authorinoapi.PatternExpressionOrRef{
Any: []authorinoapi.UnstructuredPatternExpressionOrRef{
{
PatternExpressionOrRef: authorinoapi.PatternExpressionOrRef{
PatternExpression: authorinoapi.PatternExpression{
Selector: fmt.Sprintf(`request.path.@extract:{"sep":"?%s=","pos":1}|@extract:{"sep":"&"}`, queryParam.Name),
Operator: authorinoapi.PatternExpressionOperator(operator),
Value: queryParam.Value,
},
},
},
{
PatternExpressionOrRef: authorinoapi.PatternExpressionOrRef{
PatternExpression: authorinoapi.PatternExpression{
Selector: fmt.Sprintf(`request.path.@extract:{"sep":"&%s=","pos":1}|@extract:{"sep":"&"}`, queryParam.Name),
Operator: authorinoapi.PatternExpressionOperator(operator),
Value: queryParam.Value,
},
},
},
},
}
}
func toAuthorinoUnstructuredPatternExpressionOrRef(patternExpressionOrRef authorinoapi.PatternExpressionOrRef) authorinoapi.UnstructuredPatternExpressionOrRef {
return authorinoapi.UnstructuredPatternExpressionOrRef{PatternExpressionOrRef: patternExpressionOrRef}
}
func toAuthorinoOneOfPatternExpressionsOrRefs(oneOf []authorinoapi.PatternExpressionOrRef) []authorinoapi.PatternExpressionOrRef {
return []authorinoapi.PatternExpressionOrRef{
{
Any: utils.Map(oneOf, toAuthorinoUnstructuredPatternExpressionOrRef),
},
}
}
func authConfigBasicMutator(existingObj, desiredObj client.Object) (bool, error) {
existing, ok := existingObj.(*authorinoapi.AuthConfig)
if !ok {
return false, fmt.Errorf("%T is not an *authorinoapi.AuthConfig", existingObj)
}
desired, ok := desiredObj.(*authorinoapi.AuthConfig)
if !ok {
return false, fmt.Errorf("%T is not an *authorinoapi.AuthConfig", desiredObj)
}
if reflect.DeepEqual(existing.Spec, desired.Spec) {
return false, nil
}
existing.Spec = desired.Spec
return true, nil
}