forked from envoyproxy/gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackendtlspolicy.go
More file actions
671 lines (603 loc) · 23 KB
/
Copy pathbackendtlspolicy.go
File metadata and controls
671 lines (603 loc) · 23 KB
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
// 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 gatewayapi
import (
"errors"
"fmt"
"reflect"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/utils/ptr"
gwapiv1 "sigs.k8s.io/gateway-api/apis/v1"
egv1a1 "github.com/envoyproxy/gateway/api/v1alpha1"
"github.com/envoyproxy/gateway/internal/gatewayapi/resource"
"github.com/envoyproxy/gateway/internal/gatewayapi/status"
"github.com/envoyproxy/gateway/internal/ir"
"github.com/envoyproxy/gateway/internal/utils"
)
var (
ErrRefNotPermitted = fmt.Errorf("cross-namespace reference is not permitted by any ReferenceGrant")
ErrInvalidCACertificateKind = fmt.Errorf("Unsupported reference kind, supported kinds are ConfigMap, Secret, and ClusterTrustBundle")
ErrNoValidCACertificate = fmt.Errorf(
"no valid CA certificate found in referenced resources",
)
)
// ProcessBackendTLSPolicyStatus is called to post-process Backend TLS Policy status
// after they were applied in all relevant translations.
func (t *Translator) ProcessBackendTLSPolicyStatus(btlsp []*gwapiv1.BackendTLSPolicy) {
targetRefs := map[string]*gwapiv1.BackendTLSPolicy{}
for _, policy := range btlsp {
conflicted, conflictPolicy := false, &gwapiv1.BackendTLSPolicy{}
for _, ref := range policy.Spec.TargetRefs {
key := localPolicyTargetReferenceWithSectionNameToKey(policy.Namespace, ref)
p, exists := targetRefs[key]
if exists {
conflicted = true
conflictPolicy = p
break
}
// TODO: do we need to verify a backend(Ref) used in somewhere?
targetRefs[key] = policy
}
if conflicted {
// let's copy the ancestorRefs from the conflictPolicy.
ancestorRefs := make([]*gwapiv1.ParentReference, 0, len(policy.Status.Ancestors))
for _, ancestor := range conflictPolicy.Status.Ancestors {
ancestorRefs = append(ancestorRefs, &ancestor.AncestorRef)
}
status.SetConditionForPolicyAncestors(&policy.Status,
ancestorRefs,
t.GatewayControllerName,
gwapiv1.PolicyConditionAccepted,
metav1.ConditionFalse,
gwapiv1.PolicyReasonConflicted,
fmt.Sprintf("Policy conflicts with BackendTLSPolicy %s.", utils.NamespacedName(conflictPolicy).String()),
policy.Generation,
)
}
// Truncate Ancestor list of longer than 16
if len(policy.Status.Ancestors) > 16 {
status.TruncatePolicyAncestors(&policy.Status, t.GatewayControllerName, policy.Generation)
}
}
}
func localPolicyTargetReferenceWithSectionNameToKey(ns string, targetRef gwapiv1.LocalPolicyTargetReferenceWithSectionName) string {
sectionName := ptr.Deref(targetRef.SectionName, "")
return fmt.Sprintf("%s/%s/%s/%s/%v", ns, targetRef.Group, targetRef.Kind, targetRef.Name, sectionName)
}
// applyBackendTLSSetting processes TLS settings from Backend resource, BackendTLSPolicy, and EnvoyProxy resource.
// It merges the TLS settings from these resources and returns the final TLS config to be applied to the upstream cluster.
func (t *Translator) applyBackendTLSSetting(
backendRef gwapiv1.BackendObjectReference,
backendNamespace string,
parent gwapiv1.ParentReference,
resources *resource.Resources,
gtwCtx *GatewayContext,
) (*ir.TLSUpstreamConfig, error) {
var (
backendValidationTLSConfig *ir.TLSUpstreamConfig // the TLS config to validate the server cert from Backend TLS settings
btpValidationTLSConfig *ir.TLSUpstreamConfig // the TLS config to validate the server cert from BackendTLSPolicy
backendClientTLSConfig *ir.TLSConfig // the TLS config for client cert and common TLS settings from Backend TLS settings
envoyProxyClientTLSConfig *ir.TLSConfig // the TLS config for client cert and common TLS settings from EnvoyProxy BackendTLS
mergedClientTLSConfig *ir.TLSConfig // the final merged client TLS config to return
mergedTLSConfig *ir.TLSUpstreamConfig // the final merged TLS config to return
err error
)
// If the backendRef is a Backend resource, we need to check if it has TLS settings.
if KindDerefOr(backendRef.Kind, resource.KindService) == egv1a1.KindBackend {
backend := t.GetBackend(backendNamespace, string(backendRef.Name))
if backend == nil {
return nil, fmt.Errorf("backend %s not found", backendRef.Name)
}
if backend.Spec.TLS != nil {
// Get the server certificate validation settings from Backend resource.
if backendValidationTLSConfig, err = t.processServerValidationTLSSettings(backend); err != nil {
return nil, err
}
// Get the client certificate and common TLS settings from Backend resource.
if backend.Spec.TLS.BackendTLSConfig != nil {
if backendClientTLSConfig, err = t.processClientTLSSettings(
backend.Spec.TLS.BackendTLSConfig, &ResourceMetadata{
Name: backend.Name,
Namespace: backend.Namespace,
Kind: egv1a1.KindBackend,
}); err != nil {
return nil, err
}
}
}
}
// Get the backend certificate validation settings from BackendTLSPolicy.
if btpValidationTLSConfig, err = t.processBackendTLSPolicy(backendRef, backendNamespace, parent, resources); err != nil {
return nil, err
}
// Merge server validation TLS settings from Backend resource and BackendTLSPolicy.
// BackendTLSPolicy takes precedence over Backend resource for identical attributes that are set in both.
mergedTLSConfig = mergeServerValidationTLSConfigs(backendValidationTLSConfig, btpValidationTLSConfig)
// If neither Backend resource nor BackendTLSPolicy has TLS settings, no TLS is needed.
if mergedTLSConfig == nil {
return nil, nil
}
if !mergedTLSConfig.InsecureSkipVerify && mergedTLSConfig.CACertificate == nil {
return nil, fmt.Errorf("CACertificate must be specified when InsecureSkipVerify is false")
}
// Get the client certificate and common TLS settings from EnvoyProxy resource.
if gtwCtx != nil {
if gtwBackendTLSConfig, owner := gtwCtx.GetBackendTLSConfig(); gtwBackendTLSConfig != nil {
if envoyProxyClientTLSConfig, err = t.processClientTLSSettings(
gtwBackendTLSConfig, owner); err != nil {
return nil, err
}
}
}
// Merge client TLS settings from Backend resource and EnvoyProxy resource.
// Backend resource client TLS settings take precedence over EnvoyProxy client TLS settings.
mergedClientTLSConfig = mergeClientTLSConfigs(backendClientTLSConfig, envoyProxyClientTLSConfig)
if mergedClientTLSConfig != nil {
mergedTLSConfig.TLSConfig = *mergedClientTLSConfig
}
// Set to the default TLS protocol versions (min 1.2, max 1.3) when
// not explicitly configured.
if mergedTLSConfig.MinVersion == nil {
mergedTLSConfig.MinVersion = new(ir.TLSv12)
}
if mergedTLSConfig.MaxVersion == nil {
mergedTLSConfig.MaxVersion = new(ir.TLSv13)
}
return mergedTLSConfig, nil
}
// Merges TLS settings from Gateway API BackendTLSPolicy and Envoy Gateway Backend TL.
// BackendTLSPolicy takes precedence for identical attributes that are set in both.
func mergeServerValidationTLSConfigs(
backendValidationTLSConfig *ir.TLSUpstreamConfig,
btpValidationTLSConfig *ir.TLSUpstreamConfig,
) *ir.TLSUpstreamConfig {
if backendValidationTLSConfig == nil && btpValidationTLSConfig == nil {
return nil
}
if backendValidationTLSConfig == nil {
return btpValidationTLSConfig
}
if btpValidationTLSConfig == nil {
return backendValidationTLSConfig
}
// We don't use DeepCopy here to avoid unnecessary memory allocation.
mergedConfig := backendValidationTLSConfig
if btpValidationTLSConfig.CACertificate != nil {
mergedConfig.CACertificate = btpValidationTLSConfig.CACertificate
}
if btpValidationTLSConfig.SNI != nil { // BTP takes precedence for SNI, if set, it will override Backend resource SNI and disable AutoSNIFromEndpointHostname
mergedConfig.SNI = btpValidationTLSConfig.SNI
mergedConfig.AutoSNIFromEndpointHostname = false
}
if btpValidationTLSConfig.UseSystemTrustStore {
mergedConfig.UseSystemTrustStore = btpValidationTLSConfig.UseSystemTrustStore
}
if btpValidationTLSConfig.SubjectAltNames != nil {
mergedConfig.SubjectAltNames = btpValidationTLSConfig.SubjectAltNames
}
return mergedConfig
}
// Merges client TLS settings from backend TLS settings and EnvoyProxy BackendTLS settings.
// Backend TLS settings take precedence for identical attributes that are set in both.
func mergeClientTLSConfigs(
backendClientTLSConfig *ir.TLSConfig,
envoyProxyClientTLSConfig *ir.TLSConfig,
) *ir.TLSConfig {
if backendClientTLSConfig == nil && envoyProxyClientTLSConfig == nil {
return nil
}
if backendClientTLSConfig == nil {
return envoyProxyClientTLSConfig
}
if envoyProxyClientTLSConfig == nil {
return backendClientTLSConfig
}
// We don't use DeepCopy here to avoid unnecessary memory allocation.
mergedConfig := envoyProxyClientTLSConfig
if len(backendClientTLSConfig.ClientCertificates) > 0 {
mergedConfig.ClientCertificates = backendClientTLSConfig.ClientCertificates
}
if backendClientTLSConfig.MinVersion != nil {
minVersion := *backendClientTLSConfig.MinVersion
mergedConfig.MinVersion = &minVersion
}
if backendClientTLSConfig.MaxVersion != nil {
maxVersion := *backendClientTLSConfig.MaxVersion
mergedConfig.MaxVersion = &maxVersion
}
if len(backendClientTLSConfig.Ciphers) > 0 {
mergedConfig.Ciphers = backendClientTLSConfig.Ciphers
}
if len(backendClientTLSConfig.ECDHCurves) > 0 {
mergedConfig.ECDHCurves = backendClientTLSConfig.ECDHCurves
}
if len(backendClientTLSConfig.SignatureAlgorithms) > 0 {
mergedConfig.SignatureAlgorithms = backendClientTLSConfig.SignatureAlgorithms
}
if backendClientTLSConfig.ALPNProtocols != nil {
mergedConfig.ALPNProtocols = backendClientTLSConfig.ALPNProtocols
}
return mergedConfig
}
func (t *Translator) processServerValidationTLSSettings(
backend *egv1a1.Backend,
) (*ir.TLSUpstreamConfig, error) {
tlsConfig := &ir.TLSUpstreamConfig{
InsecureSkipVerify: ptr.Deref(backend.Spec.TLS.InsecureSkipVerify, false),
AutoSNIFromEndpointHostname: ptr.Deref(backend.Spec.TLS.AutoSNIFromEndpointHostname, false),
}
if backend.Spec.TLS.SNI != nil {
tlsConfig.SNI = new(string(*backend.Spec.TLS.SNI))
}
if !tlsConfig.InsecureSkipVerify {
tlsConfig.UseSystemTrustStore = ptr.Deref(backend.Spec.TLS.WellKnownCACertificates, "") == gwapiv1.WellKnownCACertificatesSystem
if tlsConfig.UseSystemTrustStore {
tlsConfig.CACertificate = &ir.TLSCACertificate{
Name: fmt.Sprintf("%s/%s-ca", backend.Name, backend.Namespace),
}
} else if len(backend.Spec.TLS.CACertificateRefs) > 0 {
caRefs := getObjectReferences(gwapiv1.Namespace(backend.Namespace), backend.Spec.TLS.CACertificateRefs)
// Backend doesn't allow cross-namespace reference, so pass nil resources here.
caCert, sds, err := t.getCaCertsFromCARefs(nil, caRefs, resource.ResourceMetadata{
Name: backend.Name,
Namespace: backend.Namespace,
Kind: resource.KindBackendTLSPolicy,
Group: egv1a1.GroupName,
})
if err != nil {
return nil, err
}
tlsConfig.CACertificate = &ir.TLSCACertificate{
Certificate: caCert,
Name: fmt.Sprintf("%s/%s-ca", backend.Name, backend.Namespace),
SDS: sds,
}
}
}
return tlsConfig, nil
}
func (t *Translator) processBackendTLSPolicy(
backendRef gwapiv1.BackendObjectReference,
backendNamespace string,
parent gwapiv1.ParentReference,
resources *resource.Resources,
) (*ir.TLSUpstreamConfig, error) {
policy := t.getBackendTLSPolicy(resources.BackendTLSPolicies, backendRef, backendNamespace)
if policy == nil {
return nil, nil
}
tlsBundle, err := t.getBackendTLSBundle(policy)
ancestorRefs := getAncestorRefs(policy)
ancestorRefs = append(ancestorRefs, &parent)
if err != nil {
acceptedReason := gwapiv1.BackendTLSPolicyReasonNoValidCACertificate
resolvedReason := gwapiv1.BackendTLSPolicyReasonInvalidCACertificateRef
if errors.Is(err, ErrInvalidCACertificateKind) {
// Accepted MUST remain NoValidCACertificate (per Gateway API conformance)
resolvedReason = gwapiv1.BackendTLSPolicyReasonInvalidKind
}
status.SetConditionForPolicyAncestors(
&policy.Status,
ancestorRefs,
t.GatewayControllerName,
gwapiv1.PolicyConditionAccepted,
metav1.ConditionFalse,
acceptedReason,
status.Error2ConditionMsg(err),
policy.Generation,
)
status.SetConditionForPolicyAncestors(
&policy.Status,
ancestorRefs,
t.GatewayControllerName,
gwapiv1.BackendTLSPolicyConditionResolvedRefs,
metav1.ConditionFalse,
resolvedReason,
status.Error2ConditionMsg(err),
policy.Generation,
)
return nil, err
}
status.SetConditionForPolicyAncestors(&policy.Status,
ancestorRefs,
t.GatewayControllerName,
gwapiv1.BackendTLSPolicyConditionResolvedRefs,
metav1.ConditionTrue,
gwapiv1.BackendTLSPolicyReasonResolvedRefs,
"Resolved all the Object references.",
policy.Generation,
)
status.SetAcceptedForPolicyAncestors(&policy.Status, ancestorRefs, t.GatewayControllerName, policy.Generation)
return tlsBundle, nil
}
func (t *Translator) processClientTLSSettings(
clientTLS *egv1a1.BackendTLSConfig,
owner *ResourceMetadata,
) (*ir.TLSConfig, error) {
tlsConfig := &ir.TLSConfig{}
if len(clientTLS.Ciphers) > 0 {
tlsConfig.Ciphers = clientTLS.Ciphers
}
if len(clientTLS.ECDHCurves) > 0 {
tlsConfig.ECDHCurves = clientTLS.ECDHCurves
}
if len(clientTLS.SignatureAlgorithms) > 0 {
tlsConfig.SignatureAlgorithms = clientTLS.SignatureAlgorithms
}
if clientTLS.MinVersion != nil {
tlsConfig.MinVersion = new(ir.TLSVersion(*clientTLS.MinVersion))
}
if clientTLS.MaxVersion != nil {
tlsConfig.MaxVersion = new(ir.TLSVersion(*clientTLS.MaxVersion))
}
// An empty list of ALPNProtocols means ALPN is disabled, while a nil value means it is not set.
if clientTLS.ALPNProtocols != nil {
tlsConfig.ALPNProtocols = make([]string, len(clientTLS.ALPNProtocols))
for i := range clientTLS.ALPNProtocols {
tlsConfig.ALPNProtocols[i] = string(clientTLS.ALPNProtocols[i])
}
}
if clientTLS.ClientCertificateRef != nil {
var err error
ownerResource := owner.Kind
ns := NamespaceDerefOr(clientTLS.ClientCertificateRef.Namespace, owner.Namespace)
// cross-namespace Gateway.spec.tls.backend.clientCertificateRef is validated,
// we don't need to check again here.
if owner.Kind != resource.KindGateway && ns != owner.Namespace {
err = fmt.Errorf("ClientCertificateRef Secret is not located in the same namespace as %s. Secret namespace: %s does not match %s namespace: %s", ownerResource, ns, ownerResource, owner.Namespace)
return tlsConfig, err
}
secret := t.GetSecret(ns, string(clientTLS.ClientCertificateRef.Name))
if secret == nil {
err = fmt.Errorf(
"failed to locate TLS secret for client auth: %s specified in %s %s",
types.NamespacedName{
Namespace: owner.Namespace,
Name: string(clientTLS.ClientCertificateRef.Name),
}.String(),
ownerResource,
types.NamespacedName{
Namespace: owner.Namespace,
Name: owner.Name,
}.String(),
)
return tlsConfig, err
}
// Check if this is an SDS reference secret
if secret.Type == egv1a1.SDSSecretType {
if !t.SDSSecretRefEnabled {
return tlsConfig, fmt.Errorf("SDS Secret reference is not enabled in EnvoyGateway configuration")
}
// For SDS reference secrets, extract the SDS secret name and URL from data
s, err := ir.NewSDSConfig(secret)
if err != nil {
return tlsConfig, fmt.Errorf("invalid SDS reference secret: %w", err)
}
tlsConfig.ClientCertificates = []ir.TLSCertificate{
{
SDS: s,
},
}
} else {
// Regular secret processing
tlsConfig.ClientCertificates = append(tlsConfig.ClientCertificates, getTLSCertificateFromSecret(secret))
}
}
return tlsConfig, nil
}
func backendTLSTargetMatched(policy *gwapiv1.BackendTLSPolicy, target gwapiv1.LocalPolicyTargetReferenceWithSectionName, backendNamespace string, shouldSectionNameMatch bool) bool {
for _, currTarget := range policy.Spec.TargetRefs {
if target.Group == currTarget.Group &&
target.Kind == currTarget.Kind &&
backendNamespace == policy.Namespace &&
target.Name == currTarget.Name {
// if section name is not set, then it targets the entire backend
if currTarget.SectionName == nil && target.SectionName != nil {
return !shouldSectionNameMatch
} else if reflect.DeepEqual(currTarget.SectionName, target.SectionName) {
return true
}
}
}
return false
}
func (t *Translator) getBackendTLSPolicy(
policies []*gwapiv1.BackendTLSPolicy,
backendRef gwapiv1.BackendObjectReference,
backendNamespace string,
) *gwapiv1.BackendTLSPolicy {
// SectionName is port number for EG Backend object
target := t.getTargetBackendReference(backendRef, backendNamespace)
if target.SectionName != nil {
for _, policy := range policies {
if backendTLSTargetMatched(policy, target, backendNamespace, true) {
// prefer policies that target this specific section over wildcard matches
return policy
}
}
}
for _, policy := range policies {
if backendTLSTargetMatched(policy, target, backendNamespace, false) {
return policy
}
}
return nil
}
func (t *Translator) getBackendTLSBundle(backendTLSPolicy *gwapiv1.BackendTLSPolicy) (*ir.TLSUpstreamConfig, error) {
// Translate SubjectAltNames from gwapiv1a3 to ir
subjectAltNames := make([]ir.SubjectAltName, 0, len(backendTLSPolicy.Spec.Validation.SubjectAltNames))
for _, san := range backendTLSPolicy.Spec.Validation.SubjectAltNames {
var subjectAltName ir.SubjectAltName
switch san.Type {
case gwapiv1.HostnameSubjectAltNameType:
subjectAltName.Hostname = new(string(san.Hostname))
case gwapiv1.URISubjectAltNameType:
subjectAltName.URI = new(string(san.URI))
default:
continue // skip unknown types
}
subjectAltNames = append(subjectAltNames, subjectAltName)
}
tlsBundle := &ir.TLSUpstreamConfig{
SNI: new(string(backendTLSPolicy.Spec.Validation.Hostname)),
UseSystemTrustStore: ptr.Deref(backendTLSPolicy.Spec.Validation.WellKnownCACertificates, "") == gwapiv1.WellKnownCACertificatesSystem,
SubjectAltNames: subjectAltNames,
}
if tlsBundle.UseSystemTrustStore {
tlsBundle.CACertificate = &ir.TLSCACertificate{
Name: fmt.Sprintf("%s/%s-ca", backendTLSPolicy.Name, backendTLSPolicy.Namespace),
}
return tlsBundle, nil
}
caRefs := getObjectReferences(gwapiv1.Namespace(backendTLSPolicy.Namespace), backendTLSPolicy.Spec.Validation.CACertificateRefs)
// BackendTLSPolicy doesn't allow cross-namespace reference,
// so pass nil resources here
caCert, sds, err := t.getCaCertsFromCARefs(nil, caRefs, resource.ResourceMetadata{
Group: egv1a1.GroupName,
Name: backendTLSPolicy.Name,
Namespace: backendTLSPolicy.Namespace,
Kind: resource.KindBackendTLSPolicy,
})
if err != nil {
return nil, err
}
tlsBundle.CACertificate = &ir.TLSCACertificate{
Certificate: caCert,
Name: fmt.Sprintf("%s/%s-ca", backendTLSPolicy.Name, backendTLSPolicy.Namespace),
SDS: sds,
}
return tlsBundle, nil
}
func getObjectReferences(ns gwapiv1.Namespace, refs []gwapiv1.LocalObjectReference) []gwapiv1.ObjectReference {
caRefs := make([]gwapiv1.ObjectReference, 0, len(refs))
for _, caRef := range refs {
caRefs = append(caRefs, gwapiv1.ObjectReference{
Group: caRef.Group,
Kind: caRef.Kind,
Name: caRef.Name,
Namespace: new(ns),
})
}
return caRefs
}
// getCaCertsFromCARefs retrieves CA certificates from the given CA refs. It supports ConfigMap, Secret, and ClusterTrustBundle kinds.
// TODO: move out of backendtlspolicy.go
func (t *Translator) getCaCertsFromCARefs(resources *resource.Resources, caCertificates []gwapiv1.ObjectReference, meta resource.ResourceMetadata,
) (caCert []byte, sds *ir.SDSConfig, err error) {
ca := ""
foundSupportedRef := false
var foundSDSConfig *ir.SDSConfig
for _, caRef := range caCertificates {
kind := string(caRef.Kind)
var caRefNs string
if caRef.Namespace == nil {
caRefNs = meta.Namespace
} else {
caRefNs = string(*caRef.Namespace)
}
if caRefNs != meta.Namespace && resources != nil {
// check reference grant
if !isCrossNamespaceReferencePermitted(
crossNamespaceFrom{
group: meta.Group,
kind: meta.Kind,
namespace: meta.Namespace,
},
crossNamespaceTo{
group: string(caRef.Group),
kind: kind,
namespace: caRefNs,
name: string(caRef.Name),
},
resources.ReferenceGrants,
) {
return nil, nil, fmt.Errorf("%w for caCertificateRef %s/%s (kind: %s, namespace: %s)", ErrRefNotPermitted, caRef.Group, caRef.Name, kind, caRefNs)
}
}
switch kind {
case resource.KindConfigMap:
foundSupportedRef = true
cm := t.GetConfigMap(caRefNs, string(caRef.Name))
if cm != nil {
if crt, dataOk := getOrFirstFromData(cm.Data, CACertKey); dataOk {
if ca != "" {
ca += "\n"
}
ca += crt
} else {
return nil, nil, fmt.Errorf("no ca found in configmap %s", cm.Name)
}
} else {
return nil, nil, fmt.Errorf("configmap %s not found in namespace %s", caRef.Name, caRefNs)
}
case resource.KindSecret:
foundSupportedRef = true
secret := t.GetSecret(caRefNs, string(caRef.Name))
if secret != nil {
// Check if this is an SDS reference secret
if secret.Type == egv1a1.SDSSecretType {
if !t.SDSSecretRefEnabled {
return nil, nil, fmt.Errorf("SDS Secret reference is not enabled in EnvoyGateway configuration")
}
if foundSDSConfig != nil {
return nil, nil, fmt.Errorf("multiple SDS reference secrets are not supported")
}
// For SDS reference secrets, extract the SDS secret name and URL from data
foundSDSConfig, err = ir.NewSDSConfig(secret)
if err != nil {
return nil, nil, fmt.Errorf("invalid SDS reference secret %s: %w", secret.Name, err)
}
continue
}
// Regular secret processing
if crt, dataOk := getOrFirstFromData(secret.Data, CACertKey); dataOk {
if ca != "" {
ca += "\n"
}
ca += string(crt)
} else {
return nil, nil, fmt.Errorf("no ca found in secret %s", secret.Name)
}
} else {
return nil, nil, fmt.Errorf("secret %s not found in namespace %s", caRef.Name, caRefNs)
}
case resource.KindClusterTrustBundle:
foundSupportedRef = true
ctb := t.GetClusterTrustBundle(string(caRef.Name))
if ctb != nil {
if ca != "" {
ca += "\n"
}
ca += ctb.Spec.TrustBundle
} else {
return nil, nil, fmt.Errorf("cluster trust bundle %s not found", caRef.Name)
}
}
}
// Validate that SDS is not mixed with regular certificates
if foundSDSConfig != nil && ca != "" {
return nil, nil, fmt.Errorf("cannot mix SDS reference secrets with other CA certificate types")
}
// Return SDS config if found
if foundSDSConfig != nil {
return nil, foundSDSConfig, nil
}
// Return regular certificates if found
if ca == "" {
if !foundSupportedRef {
return nil, nil, fmt.Errorf("%w in caCertificateRefs", ErrInvalidCACertificateKind)
}
return nil, nil, ErrNoValidCACertificate
}
return []byte(ca), nil, nil
}
func getAncestorRefs(policy *gwapiv1.BackendTLSPolicy) []*gwapiv1.ParentReference {
ret := make([]*gwapiv1.ParentReference, len(policy.Status.Ancestors))
for i, ancestor := range policy.Status.Ancestors {
ret[i] = &ancestor.AncestorRef
}
return ret
}