This repository has been archived by the owner on Aug 1, 2021. It is now read-only.
/
querier.go
546 lines (455 loc) · 16.4 KB
/
querier.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
// Copyright (C) 2020 The CodeActual Go Environment Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//go:generate mockgen -copyright_file=$LICENSE_HEADER -package=mock -destination=$GODIR/mock/querier.go -source=$GODIR/$GOFILE
package identity
import (
"context"
meta "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/pkg/errors"
cage_k8s "github.com/codeactual/kubeauth/internal/cage/kubernetes/v1"
cage_k8s_core "github.com/codeactual/kubeauth/internal/cage/kubernetes/v1/core"
cage_k8s_rbac "github.com/codeactual/kubeauth/internal/cage/kubernetes/v1/rbac"
)
// Querier implementations perform queries of an identity-related object kind, e.g. ServiceAccount.
//
// This decomposition makes a trade-off between more Go types/files and the ability to define the
// sub-queries independently in a more maintainable way.
type Querier interface {
// String returns a unique description of the type of result provided by the querier.
String() string
// Compatible returns true if the implementation can serve the query.
//
// For example, a query may specify an object kind, e.g. ClusterRole, but a querier may not
// know how to query it because it only supports Group.
Compatible(*Query) bool
// Do performs the query.
Do(context.Context, *cage_k8s_core.Clientset, *Query) (*IdentityList, error)
}
// ConfigUserQuerier queries a kubectl context for its user value.
type ConfigUserQuerier struct{}
// String returns a unique description of the type of result provided by the querier.
//
// It implements Querier.
func (q ConfigUserQuerier) String() string {
return "kubeconfig context"
}
// Compatible returns true if the implementation can serve the query.
//
// It implements Querier.
func (q ConfigUserQuerier) Compatible(query *Query) bool {
return (query.Kind == "" || query.Kind == cage_k8s.KindUser)
}
// Do performs the query.
//
// It implements Querier.
func (q ConfigUserQuerier) Do(ctx context.Context, _ *cage_k8s_core.Clientset, query *Query) (*IdentityList, error) {
if query.ClientCmdConfig == nil {
return nil, errors.Errorf("[%s] querier received a nil kubeconfig object", q)
}
select {
case <-ctx.Done():
return nil, errors.Wrap(ctx.Err(), "query cancelled")
default:
}
var found IdentityList
for _, contextObj := range query.ClientCmdConfig.Contexts {
if query.Namespace != "" && query.Namespace != contextObj.Namespace {
continue
}
if query.Name == "" || query.Name == contextObj.AuthInfo {
found.Items = append(found.Items, Identity{
TypeMeta: meta.TypeMeta{Kind: cage_k8s.KindUser},
ObjectMeta: meta.ObjectMeta{Name: contextObj.AuthInfo, Namespace: contextObj.Namespace},
})
}
}
return &found, nil
}
var _ Querier = (*ConfigUserQuerier)(nil)
// CoreGroupQuerier queries a hard-coded set of group names enumerated in the API server source code.
//
// They're included as string literals instead of imported constants in order to avoid k8s.io/apiserver
// and its transitive dependencies.
//
// https://github.com/kubernetes/apiserver/blob/kubernetes-1.17.0/pkg/authentication/user/user.go#L69
type CoreGroupQuerier struct{}
// String returns a unique description of the type of result provided by the querier.
//
// It implements Querier.
func (q CoreGroupQuerier) String() string {
return "system-defined group"
}
// Compatible returns true if the implementation can serve the query.
//
// It implements Querier.
func (q CoreGroupQuerier) Compatible(query *Query) bool {
return query.Kind == "" || query.Kind == cage_k8s.KindGroup
}
// Do performs the query.
//
// It implements Querier.
func (q CoreGroupQuerier) Do(ctx context.Context, _ *cage_k8s_core.Clientset, query *Query) (*IdentityList, error) {
select {
case <-ctx.Done():
return nil, errors.Wrap(ctx.Err(), "query cancelled")
default:
}
ids := []Identity{
{TypeMeta: meta.TypeMeta{Kind: cage_k8s.KindGroup}, ObjectMeta: meta.ObjectMeta{Name: "system:masters"}},
{TypeMeta: meta.TypeMeta{Kind: cage_k8s.KindGroup}, ObjectMeta: meta.ObjectMeta{Name: "system:nodes"}},
{TypeMeta: meta.TypeMeta{Kind: cage_k8s.KindGroup}, ObjectMeta: meta.ObjectMeta{Name: "system:unauthenticated"}},
{TypeMeta: meta.TypeMeta{Kind: cage_k8s.KindGroup}, ObjectMeta: meta.ObjectMeta{Name: "system:authenticated"}},
}
var found IdentityList
for _, id := range ids {
if query.Name == "" || query.Name == id.Name {
found.Items = append(found.Items, id)
}
}
return &found, nil
}
var _ Querier = (*CoreGroupQuerier)(nil)
// CoreGroupQuerier queries a hard-coded set of user names enumerated in the API server source code.
//
// They're included as string literals instead of imported constants in order to avoid k8s.io/apiserver
// and its transitive dependencies.
//
// https://github.com/kubernetes/apiserver/blob/kubernetes-1.17.0/pkg/authentication/user/user.go#L69
type CoreUserQuerier struct{}
// String returns a unique description of the type of result provided by the querier.
//
// It implements Querier.
func (q CoreUserQuerier) String() string {
return "system-defined user"
}
// Compatible returns true if the implementation can serve the query.
//
// It implements Querier.
func (q CoreUserQuerier) Compatible(query *Query) bool {
return query.Kind == "" || query.Kind == cage_k8s.KindUser
}
// Do performs the query.
//
// It implements Querier.
func (q CoreUserQuerier) Do(ctx context.Context, _ *cage_k8s_core.Clientset, query *Query) (*IdentityList, error) {
select {
case <-ctx.Done():
return nil, errors.Wrap(ctx.Err(), "query cancelled")
default:
}
ids := []Identity{
{TypeMeta: meta.TypeMeta{Kind: cage_k8s.KindUser}, ObjectMeta: meta.ObjectMeta{Name: "system:anonymous"}},
{TypeMeta: meta.TypeMeta{Kind: cage_k8s.KindUser}, ObjectMeta: meta.ObjectMeta{Name: "system:apiserver"}},
{TypeMeta: meta.TypeMeta{Kind: cage_k8s.KindUser}, ObjectMeta: meta.ObjectMeta{Name: "system:kube-proxy"}},
{TypeMeta: meta.TypeMeta{Kind: cage_k8s.KindUser}, ObjectMeta: meta.ObjectMeta{Name: "system:kube-controller-manager"}},
{TypeMeta: meta.TypeMeta{Kind: cage_k8s.KindUser}, ObjectMeta: meta.ObjectMeta{Name: "system:kube-scheduler"}},
}
var found IdentityList
for _, id := range ids {
if query.Name == "" || query.Name == id.Name {
found.Items = append(found.Items, id)
}
}
return &found, nil
}
var _ Querier = (*CoreUserQuerier)(nil)
// RoleSubjectQuerier queries the API for role subjects.
type RoleSubjectQuerier struct{}
// String returns a unique description of the type of result provided by the querier.
//
// It implements Querier.
func (q RoleSubjectQuerier) String() string {
return "role binding subject"
}
// Compatible returns true if the implementation can serve the query.
//
// It implements Querier.
func (q RoleSubjectQuerier) Compatible(query *Query) bool {
return query.Kind == "" || query.Kind == cage_k8s.KindUser || query.Kind == cage_k8s.KindGroup
}
// Do performs the query.
//
// It implements Querier.
func (q RoleSubjectQuerier) Do(ctx context.Context, clientset *cage_k8s_core.Clientset, query *Query) (*IdentityList, error) {
select {
case <-ctx.Done():
return nil, errors.Wrap(ctx.Err(), "query cancelled")
default:
}
// Detect names of service accounts and parse them when found. If found and the name includes a namespace,
// verify the namespace exists.
querySaNamespace, querySaName, querySaIsGroup, querySaIsValid := cage_k8s_rbac.ParseServiceAccount(query.Name)
if querySaIsValid {
if querySaNamespace != "" {
if query.Namespace != "" && querySaNamespace != query.Namespace {
return nil, errors.Errorf("query's namespace [%s] does not match query service account [%s]'s namespace [%s] ", query.Namespace, query.Name, querySaNamespace)
}
_, exists, err := clientset.Namespaces.Get(querySaNamespace)
if err != nil {
return nil, errors.WithStack(err)
}
if !exists {
return nil, errors.Errorf("service account [%s] namespace [%s] not found", query.Name, querySaNamespace)
}
}
}
// Scan role bindings for subjects which match the queried name. Apply queried namespace if provided.
res, err := clientset.RoleBindings.List(query.Namespace, meta.ListOptions{})
if err != nil {
return nil, errors.Wrap(err, "failed to get role binding list")
}
var list IdentityList
for _, r := range res.Items {
for _, s := range r.Subjects {
if query.Namespace != "" && query.Namespace != s.Namespace {
continue
}
var match bool
if query.Name == "" {
match = true
} else {
if querySaIsValid {
if querySaIsGroup {
match = s.Kind == cage_k8s.KindGroup && s.Name == query.Name
} else {
match = s.Kind == cage_k8s.KindServiceAccount && s.Name == querySaName
}
} else {
match = (query.Kind == "" || s.Kind == query.Kind) && s.Name == query.Name
}
}
if match {
list.Items = append(list.Items, Identity{
ObjectMeta: meta.ObjectMeta{
Name: s.Name,
Namespace: s.Namespace,
},
TypeMeta: meta.TypeMeta{
Kind: s.Kind,
},
Source: &IdentitySource{
ObjectMeta: meta.ObjectMeta{
Name: r.Name,
Namespace: r.Namespace,
},
TypeMeta: meta.TypeMeta{
Kind: cage_k8s.KindRoleBinding, // as of v0.16.4, r.Kind is empty
},
},
})
}
}
}
return &list, nil
}
var _ Querier = (*RoleSubjectQuerier)(nil)
// ClusterRoleSubjectQuerier queries the API for role subjects.
type ClusterRoleSubjectQuerier struct{}
// String returns a unique description of the type of result provided by the querier.
//
// It implements Querier.
func (q ClusterRoleSubjectQuerier) String() string {
return "cluster role binding subject"
}
// Compatible returns true if the implementation can serve the query.
//
// It implements Querier.
func (q ClusterRoleSubjectQuerier) Compatible(query *Query) bool {
return query.Kind == "" || query.Kind == cage_k8s.KindUser || query.Kind == cage_k8s.KindGroup
}
// Do performs the query.
//
// It implements Querier.
func (q ClusterRoleSubjectQuerier) Do(ctx context.Context, clientset *cage_k8s_core.Clientset, query *Query) (*IdentityList, error) {
select {
case <-ctx.Done():
return nil, errors.Wrap(ctx.Err(), "query cancelled")
default:
}
// Detect names of service accounts and parse them when found. If found and the name includes a namespace,
// verify the namespace exists.
querySaNamespace, querySaName, querySaIsGroup, querySaIsValid := cage_k8s_rbac.ParseServiceAccount(query.Name)
if querySaIsValid {
if querySaNamespace != "" {
if query.Namespace != "" && querySaNamespace != query.Namespace {
return nil, errors.Errorf("query's namespace [%s] does not match query service account [%s]'s namespace [%s] ", query.Namespace, query.Name, querySaNamespace)
}
_, exists, err := clientset.Namespaces.Get(querySaNamespace)
if err != nil {
return nil, errors.WithStack(err)
}
if !exists {
return nil, errors.Errorf("service account [%s] namespace [%s] not found", query.Name, querySaNamespace)
}
}
}
// Scan role bindings for subjects which match the queried name. Apply queried namespace if provided.
res, err := clientset.ClusterRoleBindings.List(meta.ListOptions{})
if err != nil {
return nil, errors.Wrap(err, "failed to get cluster role binding list")
}
var list IdentityList
for _, r := range res.Items {
for _, s := range r.Subjects {
if query.Namespace != "" && query.Namespace != s.Namespace {
continue
}
var match bool
if query.Name == "" {
match = true
} else {
if querySaIsValid {
if querySaIsGroup {
match = s.Kind == cage_k8s.KindGroup && s.Name == query.Name
} else {
match = s.Kind == cage_k8s.KindServiceAccount && s.Name == querySaName
}
} else {
match = (query.Kind == "" || s.Kind == query.Kind) && s.Name == query.Name
}
}
if match {
list.Items = append(list.Items, Identity{
ObjectMeta: meta.ObjectMeta{
Name: s.Name,
Namespace: s.Namespace,
},
TypeMeta: meta.TypeMeta{
Kind: s.Kind,
},
Source: &IdentitySource{
ObjectMeta: meta.ObjectMeta{
Name: r.Name,
Namespace: r.Namespace,
},
TypeMeta: meta.TypeMeta{
Kind: cage_k8s.KindClusterRoleBinding, // as of v0.16.4, r.Kind is empty
},
},
})
}
}
}
return &list, nil
}
var _ Querier = (*ClusterRoleSubjectQuerier)(nil)
// ServiceAccountUserQuerier queries the API for service account based users.
type ServiceAccountUserQuerier struct{}
// String returns a unique description of the type of result provided by the querier.
//
// It implements Querier.
func (q ServiceAccountUserQuerier) String() string {
return "service account based user"
}
// Compatible returns true if the implementation can serve the query.
//
// It implements Querier.
func (q ServiceAccountUserQuerier) Compatible(query *Query) bool {
return query.Kind == "" || query.Kind == cage_k8s.KindUser || query.Kind == cage_k8s.KindServiceAccount
}
// Do performs the query.
//
// It implements Querier.
func (q ServiceAccountUserQuerier) Do(ctx context.Context, clientset *cage_k8s_core.Clientset, query *Query) (*IdentityList, error) {
select {
case <-ctx.Done():
return nil, errors.Wrap(ctx.Err(), "query cancelled")
default:
}
var list IdentityList
var listOpts meta.ListOptions
querySaNamespace, querySaName, querySaIsGroup, querySaIsValid := cage_k8s_rbac.ParseServiceAccount(query.Name)
if !querySaIsValid || querySaIsGroup {
return &list, nil
}
if querySaNamespace != "" {
if query.Namespace != "" && querySaNamespace != query.Namespace {
return nil, errors.Errorf("query's namespace [%s] does not match query service account [%s]'s namespace [%s] ", query.Namespace, query.Name, querySaNamespace)
}
_, exists, err := clientset.Namespaces.Get(querySaNamespace)
if err != nil {
return nil, errors.WithStack(err)
}
if !exists {
return nil, errors.Errorf("service account [%s] namespace [%s] not found", query.Name, querySaNamespace)
}
}
listOpts.FieldSelector = "metadata.name=" + querySaName
res, err := clientset.ServiceAccounts.List(querySaNamespace, listOpts)
if err != nil {
return nil, errors.Wrap(err, "failed to get role list")
}
for _, s := range res.Items {
list.Items = append(list.Items, Identity{
ObjectMeta: meta.ObjectMeta{
Name: s.Name,
Namespace: s.Namespace,
},
TypeMeta: meta.TypeMeta{
Kind: cage_k8s.KindServiceAccount,
},
})
}
return &list, nil
}
var _ Querier = (*ServiceAccountUserQuerier)(nil)
// ServiceAccountGroupQuerier detects valid names of service account based groups
// and queries the API to validate their namespaces if needed. If all validation
// checks pass, the group is returned in the identity list.
type ServiceAccountGroupQuerier struct{}
// String returns a unique description of the type of result provided by the querier.
//
// It implements Querier.
func (q ServiceAccountGroupQuerier) String() string {
return "service account based group"
}
// Compatible returns true if the implementation can serve the query.
//
// It implements Querier.
func (q ServiceAccountGroupQuerier) Compatible(query *Query) bool {
return query.Kind == "" || query.Kind == cage_k8s.KindGroup
}
// Do performs the query.
//
// It implements Querier.
func (q ServiceAccountGroupQuerier) Do(ctx context.Context, clientset *cage_k8s_core.Clientset, query *Query) (*IdentityList, error) {
select {
case <-ctx.Done():
return nil, errors.Wrap(ctx.Err(), "query cancelled")
default:
}
var list IdentityList
if query.Name == "" {
return &list, nil
}
querySaNamespace, _, querySaIsGroup, querySaIsValid := cage_k8s_rbac.ParseServiceAccount(query.Name)
if !querySaIsValid || !querySaIsGroup {
return &list, nil
}
if querySaNamespace != "" {
if query.Namespace != "" && querySaNamespace != query.Namespace {
return nil, errors.Errorf("query's namespace [%s] does not match query service account [%s]'s namespace [%s] ", query.Namespace, query.Name, querySaNamespace)
}
_, exists, err := clientset.Namespaces.Get(querySaNamespace)
if err != nil {
return nil, errors.WithStack(err)
}
if !exists {
return nil, errors.Errorf("service account [%s] namespace [%s] not found", query.Name, querySaNamespace)
}
}
list.Items = append(list.Items, Identity{
ObjectMeta: meta.ObjectMeta{
Name: query.Name,
Namespace: querySaNamespace,
},
TypeMeta: meta.TypeMeta{
Kind: cage_k8s.KindGroup,
},
})
return &list, nil
}
var _ Querier = (*ServiceAccountGroupQuerier)(nil)