-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
resource_filters.go
806 lines (763 loc) · 29.8 KB
/
resource_filters.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
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
// Copyright 2022 Gravitational, Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package proxy
import (
"bytes"
"io"
"mime"
"net/http"
"github.com/gravitational/trace"
"github.com/sirupsen/logrus"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
certificatesv1 "k8s.io/api/certificates/v1"
corev1 "k8s.io/api/core/v1"
extensionsv1beta1 "k8s.io/api/extensions/v1beta1"
networkingv1 "k8s.io/api/networking/v1"
authv1 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/lib/kube/proxy/responsewriters"
"github.com/gravitational/teleport/lib/utils"
)
// newResourceFilterer creates a wrapper function that once executed creates
// a runtime filter for kubernetes resources.
// The filter exclusion criteria is:
// - deniedResources: excluded if (namespace,name) matches an entry even if it matches
// the allowedResources's list.
// - allowedResources: excluded if (namespace,name) not match a single entry.
func newResourceFilterer(kind, verb string, codecs *serializer.CodecFactory, allowedResources, deniedResources []types.KubernetesResource, log logrus.FieldLogger) responsewriters.FilterWrapper {
// If the list of allowed resources contains a wildcard and no deniedResources, then we
// don't need to filter anything.
if containsWildcard(allowedResources) && len(deniedResources) == 0 {
return nil
}
return func(contentType string, responseCode int) (responsewriters.Filter, error) {
negotiator := newClientNegotiator(codecs)
encoder, decoder, err := newEncoderAndDecoderForContentType(contentType, negotiator)
if err != nil {
return nil, trace.Wrap(err)
}
return &resourceFilterer{
encoder: encoder,
decoder: decoder,
contentType: contentType,
responseCode: responseCode,
negotiator: negotiator,
allowedResources: allowedResources,
deniedResources: deniedResources,
log: log,
kind: kind,
verb: verb,
}, nil
}
}
// wildcardFilter is a filter that matches all pods.
var wildcardFilter = types.KubernetesResource{
Kind: types.Wildcard,
Namespace: types.Wildcard,
Name: types.Wildcard,
Verbs: []string{types.Wildcard},
}
// containsWildcard returns true if the list of resources contains a wildcard filter.
func containsWildcard(resources []types.KubernetesResource) bool {
for _, r := range resources {
if r.Kind == wildcardFilter.Kind &&
r.Name == wildcardFilter.Name &&
r.Namespace == wildcardFilter.Namespace &&
len(r.Verbs) == 1 && r.Verbs[0] == wildcardFilter.Verbs[0] {
return true
}
}
return false
}
// resourceFilterer is a resource filterer instance.
type resourceFilterer struct {
encoder runtime.Encoder
decoder runtime.Decoder
// contentType is the response "Content-Type" header.
contentType string
// responseCode is the response status code.
responseCode int
// negotiator is an instance of a client negotiator.
negotiator runtime.ClientNegotiator
// allowedResources is the list of kubernetes resources the user has access to.
allowedResources []types.KubernetesResource
// deniedResources is the list of kubernetes resources the user must not access.
deniedResources []types.KubernetesResource
// log is the logger.
log logrus.FieldLogger
// kind is the type of the resource.
kind string
// verb is the kube API verb based on HTTP verb.
verb string
}
// FilterBuffer receives a byte array, decodes the response into the appropriate
// type and filters the resources based on allowed and denied rules configured.
// After filtering them, it serializes the response and dumps it into output buffer.
// If any error occurs, the call returns an error.
func (d *resourceFilterer) FilterBuffer(buf []byte, output io.Writer) error {
// decode the response into the appropriate Kubernetes API type.
obj, bf, err := d.decode(buf)
if err != nil {
return trace.Wrap(err)
}
// if bf is not empty, it means that response does not contain any valid response
// and it should be safe to write it back into the buffer.
if len(bf) > 0 {
_, err = output.Write(buf)
return trace.Wrap(err)
}
switch allowed, isList, err := d.FilterObj(obj); {
case err != nil:
return trace.Wrap(err)
case isList:
case !allowed:
// if the object is not a list and it's not allowed, then we should
// return an error.
return trace.AccessDenied("access denied")
}
// encode the filterer response back to the user.
return d.encode(obj, output)
}
func arrayToPointerArray[T any](arr []T) []*T {
out := make([]*T, len(arr))
for i := range arr {
out[i] = &arr[i]
}
return out
}
func pointerArrayToArray[T any](arr []*T) []T {
out := make([]T, len(arr))
for i := range arr {
if arr[i] == nil {
continue
}
out[i] = *arr[i]
}
return out
}
// FilterObj receives a runtime.Object type and filters the resources on it
// based on allowed and denied rules.
// After filtering them, the obj is manipulated to hold the filtered information.
// The isAllowed boolean returned indicates if the client is allowed to receive the event
// with the object.
// The isListObj boolean returned indicates if the object is a list of resources.
func (d *resourceFilterer) FilterObj(obj runtime.Object) (isAllowed bool, isList bool, err error) {
switch o := obj.(type) {
case *metav1.Status:
// Status object is returned when the Kubernetes API returns an error and
// should be forwarded to the user.
return true, false, nil
case *corev1.Pod:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *corev1.PodList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *corev1.Secret:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *corev1.SecretList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *corev1.ConfigMap:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *corev1.ConfigMapList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *corev1.Namespace:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *corev1.NamespaceList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *corev1.Service:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *corev1.ServiceList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *corev1.Endpoints:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *corev1.EndpointsList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *corev1.ServiceAccount:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *corev1.ServiceAccountList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *corev1.Node:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *corev1.NodeList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *corev1.PersistentVolume:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *corev1.PersistentVolumeList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *corev1.PersistentVolumeClaim:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *corev1.PersistentVolumeClaimList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *appsv1.Deployment:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *appsv1.DeploymentList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *appsv1.ReplicaSet:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *appsv1.ReplicaSetList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *appsv1.StatefulSet:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *appsv1.StatefulSetList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *appsv1.DaemonSet:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *appsv1.DaemonSetList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *authv1.ClusterRole:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *authv1.ClusterRoleList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *authv1.Role:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *authv1.RoleList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *authv1.ClusterRoleBinding:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *authv1.ClusterRoleBindingList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *authv1.RoleBinding:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *authv1.RoleBindingList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *batchv1.CronJob:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *batchv1.CronJobList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *batchv1.Job:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *batchv1.JobList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *certificatesv1.CertificateSigningRequest:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *certificatesv1.CertificateSigningRequestList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *networkingv1.Ingress:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *networkingv1.IngressList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *extensionsv1beta1.Ingress:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *extensionsv1beta1.IngressList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *extensionsv1beta1.DaemonSet:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *extensionsv1beta1.DaemonSetList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *extensionsv1beta1.Deployment:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *extensionsv1beta1.DeploymentList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *extensionsv1beta1.ReplicaSet:
result, err := filterResource(d.kind, d.verb, o, d.allowedResources, d.deniedResources)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *extensionsv1beta1.ReplicaSetList:
o.Items = pointerArrayToArray(
filterResourceList(
d.kind, d.verb,
arrayToPointerArray(o.Items), d.allowedResources, d.deniedResources, d.log),
)
return len(o.Items) > 0, true, nil
case *unstructured.Unstructured:
if o.IsList() {
hasElemts := filterUnstructuredList(d.verb, o, d.allowedResources, d.deniedResources, d.log)
return hasElemts, true, nil
}
r := getKubeResource(utils.KubeCustomResource, d.verb, o)
result, err := matchKubernetesResource(
r,
d.allowedResources, d.deniedResources,
)
if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expressions within kubernetes_resources.")
}
// if err is not nil or result is false, we should not include it.
return result, false, nil
case *metav1.Table:
_, err := d.filterMetaV1Table(o, d.allowedResources, d.deniedResources)
if err != nil {
return false, false, trace.Wrap(err)
}
return len(o.Rows) > 0, true, nil
default:
// It's important default types are never blindly forwarded or protocol
// extensions could result in information disclosures.
return false, false, trace.BadParameter("unexpected type received; got %T", obj)
}
}
// decode decodes the buffer into the appropriate type if the responseCode
// belongs to the range 200(OK)-206(PartialContent).
// If it does not belong, it returns the buffer unchanged since it contains
// an error message from the Kubernetes API server and it's safe to return
// it back to the user.
func (d *resourceFilterer) decode(buffer []byte) (runtime.Object, []byte, error) {
switch {
case d.responseCode == http.StatusSwitchingProtocols:
// no-op, we've been upgraded
return nil, buffer, nil
case d.responseCode < http.StatusOK /* 200 */ || d.responseCode > http.StatusPartialContent /* 206 */ :
// calculate an unstructured error from the response which the Result object may use if the caller
// did not return a structured error.
// Logic from: https://github.com/kubernetes/client-go/blob/58ff029093df37cad9fa28778a37f11fa495d9cf/rest/request.go#L1040
return nil, buffer, nil
default:
out, err := decodeAndSetGVK(d.decoder, buffer)
return out, nil, trace.Wrap(err)
}
}
// decodePartialObjectMetadata decodes the metav1.PartialObjectMetadata present
// in the metav1.TableRow entry. This information comes from server side and
// includes the resource name and namespace as a structured object.
func (d *resourceFilterer) decodePartialObjectMetadata(row *metav1.TableRow) error {
if row.Object.Object != nil {
return nil
}
var err error
// decode only if row.Object.Object was not decoded before.
row.Object.Object, err = decodeAndSetGVK(d.decoder, row.Object.Raw)
return trace.Wrap(err)
}
// encode encodes the filtered object into the io.Writer using the same
// content-type.
func (d *resourceFilterer) encode(obj runtime.Object, w io.Writer) error {
return trace.Wrap(d.encoder.Encode(obj, w))
}
// filterResourceList excludes resources the user should not have access to.
func filterResourceList[T kubeObjectInterface](kind, verb string, originalList []T, allowed, denied []types.KubernetesResource, log logrus.FieldLogger) []T {
filteredList := make([]T, 0, len(originalList))
for _, resource := range originalList {
if result, err := filterResource(kind, verb, resource, allowed, denied); err == nil && result {
filteredList = append(filteredList, resource)
} else if err != nil {
log.WithError(err).Warnf("Unable to compile regex expressions within kubernetes_resources.")
}
}
return filteredList
}
// kubeObjectInterface is an interface that all Kubernetes objects must
// implement to be able to filter them. It is used to extract the kind of the
// object from the GroupVersionKind object, the namespace and the name.
type kubeObjectInterface interface {
GetNamespace() string
GetName() string
}
// filterResource validates if the user should access the current resource.
func filterResource(kind, verb string, resource kubeObjectInterface, allowed, denied []types.KubernetesResource) (bool, error) {
result, err := matchKubernetesResource(
getKubeResource(kind, verb, resource),
allowed, denied,
)
return result, trace.Wrap(err)
}
func getKubeResource(kind, verb string, obj kubeObjectInterface) types.KubernetesResource {
return types.KubernetesResource{
Kind: kind,
Namespace: obj.GetNamespace(),
Name: obj.GetName(),
Verbs: []string{verb},
}
}
// filterMetaV1Table filters the serverside printed table to exclude resources
// that the user must not have access to.
func (d *resourceFilterer) filterMetaV1Table(table *metav1.Table, allowedResources, deniedResources []types.KubernetesResource) (*metav1.Table, error) {
resources := make([]metav1.TableRow, 0, len(table.Rows))
for i := range table.Rows {
row := &(table.Rows[i])
if err := d.decodePartialObjectMetadata(row); err != nil {
return nil, trace.Wrap(err)
}
resource, err := getKubeResourcePartialMetadataObject(d.kind, d.verb, row.Object.Object)
if err != nil {
return nil, trace.Wrap(err)
}
if result, err := matchKubernetesResource(resource, allowedResources, deniedResources); err == nil && result {
resources = append(resources, *row)
} else if err != nil {
d.log.WithError(err).Warn("Unable to compile regex expression.")
}
}
table.Rows = resources
return table, nil
}
// getKubeResourcePartialMetadataObject checks if obj is of type *metav1.PartialObjectMetadata
// otherwise returns an error.
func getKubeResourcePartialMetadataObject(kind, verb string, obj runtime.Object) (types.KubernetesResource, error) {
switch o := obj.(type) {
case *metav1.PartialObjectMetadata:
return types.KubernetesResource{
Namespace: o.Namespace,
Name: o.Name,
Kind: kind,
Verbs: []string{verb},
}, nil
default:
return types.KubernetesResource{}, trace.BadParameter("expected *metav1.PartialObjectMetadata object, got %T", obj)
}
}
// newEncoderAndDecoderForContentType creates a new encoder and decoder instances
// for the given contentType.
// If the contentType is invalid or not supported this function returns an error.
// Supported content types:
// - "application/json"
// - "application/yaml"
// - "application/vnd.kubernetes.protobuf"
func newEncoderAndDecoderForContentType(contentType string, negotiator runtime.ClientNegotiator) (runtime.Encoder, runtime.Decoder, error) {
mediaType, params, err := mime.ParseMediaType(contentType)
if err != nil {
return nil, nil, trace.WrapWithMessage(err, "unable to parse %q header %q", responsewriters.ContentTypeHeader, contentType)
}
dec, err := negotiator.Decoder(mediaType, params)
if err != nil {
return nil, nil, trace.Wrap(err)
}
enc, err := negotiator.Encoder(mediaType, params)
if err != nil {
return nil, nil, trace.Wrap(err)
}
return enc, dec, nil
}
// decodeAndSetGVK decodes the payload into the appropriate type using the decoder
// provider and sets the GVK if available.
func decodeAndSetGVK(decoder runtime.Decoder, payload []byte) (runtime.Object, error) {
obj, gvk, err := decoder.Decode(payload, nil, nil)
if err != nil {
return nil, trace.Wrap(err)
}
if gvk != nil {
// objects from decode do not contain GroupVersionKind.
// We force it to be present for later encoding.
obj.GetObjectKind().SetGroupVersionKind(*gvk)
}
return obj, nil
}
// filterBuffer filters the response buffer before writing it into the original
// MemoryResponseWriter.
func filterBuffer(filterWrapper responsewriters.FilterWrapper, src *responsewriters.MemoryResponseWriter) error {
if filterWrapper == nil {
return nil
}
filter, err := filterWrapper(responsewriters.GetContentTypeHeader(src.Header()), src.Status())
if err != nil {
return trace.Wrap(err)
}
// copy body into another slice so we can manipulate it.
b := bytes.NewBuffer(make([]byte, 0, src.Buffer().Len()))
// get the compressor and decompressor for the response based on the content type.
compressor, decompressor, err := getResponseCompressorDecompressor(src.Header())
if err != nil {
return trace.Wrap(err)
}
// decompress the response body into b.
if err := decompressor(b, src.Buffer()); err != nil {
return trace.Wrap(err)
}
// filter.FilterBuffer encodes the filtered payload into src.Buffer, so we need to
// reset it to discard the old payload.
src.Buffer().Reset()
// creates a compressor that writes the filtered payload into src.Buffer.
comp := compressor(src.Buffer())
// Close is a no-op operation into src but it's required to put the gzip writer
// into the sync.Pool.
defer comp.Close()
return trace.Wrap(filter.FilterBuffer(b.Bytes(), comp))
}
// filterUnstructuredList filters the unstructured list object to exclude resources
// that the user must not have access to.
// The filtered list is re-assigned to `obj.Object["items"]`.
func filterUnstructuredList(verb string, obj *unstructured.Unstructured, allowed, denied []types.KubernetesResource, log logrus.FieldLogger) (hasElems bool) {
const (
itemsKey = "items"
)
if obj == nil || obj.Object == nil {
return false
}
objList, err := obj.ToList()
if err != nil {
// This should never happen, but if it does, we should log it.
log.WithError(err).Warnf("Unable to convert unstructured object to list.")
return false
}
filteredList := make([]any, 0, len(objList.Items))
for _, resource := range objList.Items {
r := getKubeResource(utils.KubeCustomResource, verb, &resource)
if result, err := matchKubernetesResource(
r,
allowed, denied,
); result {
filteredList = append(filteredList, resource.Object)
} else if err != nil {
log.WithError(err).Warnf("Unable to compile regex expressions within kubernetes_resources.")
}
}
obj.Object[itemsKey] = filteredList
return len(filteredList) > 0
}