From 050cfb693f788e765a8b570aa720a0c568d7927a Mon Sep 17 00:00:00 2001 From: Jan Fajerski Date: Fri, 19 Mar 2021 14:51:34 +0100 Subject: [PATCH 1/6] add union authorizer --- main.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/main.go b/main.go index a477dad98..f7ba05d53 100644 --- a/main.go +++ b/main.go @@ -37,6 +37,7 @@ import ( "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" "k8s.io/apiserver/pkg/authentication/authenticator" + "k8s.io/apiserver/pkg/authentication/union" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" @@ -184,11 +185,14 @@ func main() { } sarClient := kubeClient.AuthorizationV1().SubjectAccessReviews() - authorizer, err := authz.NewAuthorizer(sarClient) + sarAuthorizer, err := authz.NewAuthorizer(sarClient) if err != nil { - klog.Fatalf("Failed to create authorizer: %v", err) + klog.Fatalf("Failed to create sar authorizer: %v", err) } + authorizer = union.New( + sarAuthorizer, + ) auth, err := proxy.New(kubeClient, cfg.auth, authorizer, authenticator) From e6259cba4f8a5778e70d5df3b319dfbdfc22da34 Mon Sep 17 00:00:00 2001 From: Jan Fajerski Date: Mon, 22 Mar 2021 11:16:46 +0100 Subject: [PATCH 2/6] authz: add static authorizer Fixes: https://github.com/brancz/kube-rbac-proxy/issues/110 --- main.go | 10 ++++--- pkg/authz/auth.go | 67 +++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 72 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index f7ba05d53..20a2cd329 100644 --- a/main.go +++ b/main.go @@ -37,7 +37,7 @@ import ( "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" "k8s.io/apiserver/pkg/authentication/authenticator" - "k8s.io/apiserver/pkg/authentication/union" + "k8s.io/apiserver/pkg/authorization/union" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" @@ -185,12 +185,16 @@ func main() { } sarClient := kubeClient.AuthorizationV1().SubjectAccessReviews() - sarAuthorizer, err := authz.NewAuthorizer(sarClient) + sarAuthorizer, err := authz.NewSarAuthorizer(sarClient) if err != nil { klog.Fatalf("Failed to create sar authorizer: %v", err) } - authorizer = union.New( + + staticAuthorizer := authz.NewStaticAuthorizer(cfg.auth.Authorization.Static) + + authorizer := union.New( + staticAuthorizer, sarAuthorizer, ) diff --git a/pkg/authz/auth.go b/pkg/authz/auth.go index 1fcd1524c..25df7bfac 100644 --- a/pkg/authz/auth.go +++ b/pkg/authz/auth.go @@ -17,6 +17,7 @@ limitations under the License. package authz import ( + "context" "errors" "time" @@ -30,6 +31,7 @@ type Config struct { Rewrites *SubjectAccessReviewRewrites `json:"rewrites,omitempty"` ResourceAttributes *ResourceAttributes `json:"resourceAttributes,omitempty"` ResourceAttributesFile string `json:"-"` + Static []StaticAuthorizationConfig `json:"static,omitempty"` } // SubjectAccessReviewRewrites describes how SubjectAccessReview may be @@ -61,8 +63,27 @@ type ResourceAttributes struct { Name string `json:"name,omitempty"` } -// NewAuthorizer creates an authorizer compatible with the kubelet's needs -func NewAuthorizer(client authorizationclient.SubjectAccessReviewInterface) (authorizer.Authorizer, error) { +// StaticAuthorizationConfig describes what is needed to specify a static +// authorization. +type StaticAuthorizationConfig struct { + User UserConfig + Verb string `json:"verb,omitempty"` + Namespace string `json:"namespace,omitempty"` + APIGroup string `json:"apiGroup,omitempty"` + Resource string `json:"resource,omitempty"` + Subresource string `json:"subresource,omitempty"` + Name string `json:"name,omitempty"` + ResourceRequest bool `json:"resourceRequest,omitempty"` + Path string `json:"path,omitempty"` +} + +type UserConfig struct { + Name string `json:"name,omitempty"` + Groups []string `json:"groups,omitempty"` +} + +// NewSarAuthorizer creates an authorizer compatible with the kubelet's needs +func NewSarAuthorizer(client authorizationclient.SubjectAccessReviewInterface) (authorizer.Authorizer, error) { if client == nil { return nil, errors.New("no client provided, cannot use webhook authorization") } @@ -73,3 +94,45 @@ func NewAuthorizer(client authorizationclient.SubjectAccessReviewInterface) (aut } return authorizerConfig.New() } + +type staticAuthorizer struct { + config []StaticAuthorizationConfig +} + +func (saConfig StaticAuthorizationConfig) Equal(a authorizer.Attributes) bool { + isAllowed := func(staticConf string, requestVal string) bool { + if staticConf == "" { + return true + } else { + return staticConf == requestVal + } + } + + if isAllowed(saConfig.User.Name, a.GetUser().GetName()) && + isAllowed(saConfig.Verb, a.GetVerb()) && + isAllowed(saConfig.Namespace, a.GetNamespace()) && + isAllowed(saConfig.APIGroup, a.GetAPIGroup()) && + isAllowed(saConfig.Resource, a.GetResource()) && + isAllowed(saConfig.Subresource, a.GetSubresource()) && + isAllowed(saConfig.Name, a.GetName()) && + isAllowed(saConfig.Path, a.GetPath()) && + saConfig.ResourceRequest == a.IsResourceRequest() { + return true + } + return false +} + +func (sa staticAuthorizer) Authorize(ctx context.Context, a authorizer.Attributes) (authorized authorizer.Decision, reason string, err error) { + // compare a against the configured static auths + for _, saConfig := range sa.config { + if saConfig.Equal(a) { + return authorizer.DecisionAllow, "found corresponding static auth config", nil + } + } + + return authorizer.DecisionNoOpinion, "", nil +} + +func NewStaticAuthorizer(config []StaticAuthorizationConfig) staticAuthorizer { + return staticAuthorizer{config} +} From 86fd16cdc5b9cd9df72fb9d2d6aca534aa984fbe Mon Sep 17 00:00:00 2001 From: Jan Fajerski Date: Mon, 22 Mar 2021 16:55:20 +0100 Subject: [PATCH 3/6] authz: add some tests for new static authorizer. --- pkg/authz/auth_test.go | 124 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 pkg/authz/auth_test.go diff --git a/pkg/authz/auth_test.go b/pkg/authz/auth_test.go new file mode 100644 index 000000000..d50e8433a --- /dev/null +++ b/pkg/authz/auth_test.go @@ -0,0 +1,124 @@ +/* +Copyright 2021 Kube RBAC Proxy Authors rights reserved. + +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 authz + +import ( + "context" + "testing" + + "k8s.io/apiserver/pkg/authentication/user" + "k8s.io/apiserver/pkg/authorization/authorizer" +) + +func TestStaticAuthorizer(t *testing.T) { + tests := []struct { + name string + authorizer authorizer.Authorizer + + shouldPass []authorizer.Attributes + shouldNoOpinion []authorizer.Attributes + }{ + { + name: "pathOnly", + authorizer: NewStaticAuthorizer([]StaticAuthorizationConfig{ + StaticAuthorizationConfig{Path: "/metrics"}, + }), + shouldPass: []authorizer.Attributes{ + authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "get", Path: "/metrics"}, + authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "update", Path: "/metrics"}, + }, + shouldNoOpinion: []authorizer.Attributes{ + // wrong path + authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "get", Path: "/api"}, + }, + }, + { + name: "pathAndVerb", + authorizer: NewStaticAuthorizer([]StaticAuthorizationConfig{ + StaticAuthorizationConfig{Path: "/metrics", Verb: "get"}, + }), + shouldPass: []authorizer.Attributes{ + authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "get", Path: "/metrics"}, + }, + shouldNoOpinion: []authorizer.Attributes{ + // wrong path + authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "get", Path: "/api"}, + // wrong path + authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "update", Path: "/metrics"}, + }, + }, + { + name: "resourceRequestSpecifiedTrue", + authorizer: NewStaticAuthorizer([]StaticAuthorizationConfig{ + StaticAuthorizationConfig{Path: "/metrics", Verb: "get", ResourceRequest: true}, + }), + shouldPass: []authorizer.Attributes{ + authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "get", Path: "/metrics", ResourceRequest: true}, + }, + shouldNoOpinion: []authorizer.Attributes{ + // wrong resourceRequest + authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "get", Path: "/metrics", ResourceRequest: false}, + }, + }, + { + name: "resourceRequestSpecifiedFalse", + authorizer: NewStaticAuthorizer([]StaticAuthorizationConfig{ + StaticAuthorizationConfig{Path: "/metrics", Verb: "get", ResourceRequest: false}, + }), + shouldPass: []authorizer.Attributes{ + authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "get", Path: "/metrics", ResourceRequest: false}, + }, + shouldNoOpinion: []authorizer.Attributes{ + // wrong resourceRequest + authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "get", Path: "/metrics", ResourceRequest: true}, + }, + }, + { + name: "resourceRequestUnspecified", + authorizer: NewStaticAuthorizer([]StaticAuthorizationConfig{ + StaticAuthorizationConfig{Path: "/metrics", Verb: "get"}, + }), + shouldPass: []authorizer.Attributes{ + authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "get", Path: "/metrics", ResourceRequest: false}, + }, + shouldNoOpinion: []authorizer.Attributes{ + // Verb: get and ResourceRequest: true should be + // mutually exclusive + authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "get", Path: "/metrics", ResourceRequest: true}, + // wrong path + authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "get", Path: "/api", ResourceRequest: true}, + // wrong path + authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "update", Path: "/metrics", ResourceRequest: false}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + for _, attr := range tt.shouldPass { + if decision, _, _ := tt.authorizer.Authorize(context.Background(), attr); decision != authorizer.DecisionAllow { + t.Errorf("incorrectly restricted %v", attr) + } + } + + for _, attr := range tt.shouldNoOpinion { + if decision, _, _ := tt.authorizer.Authorize(context.Background(), attr); decision != authorizer.DecisionNoOpinion { + t.Errorf("incorrectly opinionated %v", attr) + } + } + }) + } +} From 78125d6093139e2396ac44aa23a14e08c423b24c Mon Sep 17 00:00:00 2001 From: Jan Fajerski Date: Fri, 26 Mar 2021 15:47:44 +0100 Subject: [PATCH 4/6] doc: add example instructions for static auth in minikube --- examples/static-auth/README.md | 186 ++++++++++++++++++++++++++ examples/static-auth/client-rbac.yaml | 22 +++ examples/static-auth/deployment.yaml | 108 +++++++++++++++ 3 files changed, 316 insertions(+) create mode 100644 examples/static-auth/README.md create mode 100644 examples/static-auth/client-rbac.yaml create mode 100644 examples/static-auth/deployment.yaml diff --git a/examples/static-auth/README.md b/examples/static-auth/README.md new file mode 100644 index 000000000..7ece05557 --- /dev/null +++ b/examples/static-auth/README.md @@ -0,0 +1,186 @@ +# Static Authorization example + +> Note to try this out with minikube, make sure you enable RBAC correctly. Since minikube v0.26.0 the default bootstrapper is kubeadm - which should enable RBAC by default. For older version follow the instructions [here](../minikube-rbac). + +RBAC differentiates in two types, that need to be authorized, resources and non-resources. A resource request authorization, could for example be, that a requesting entity needs to be authorized to perform the `get` action on a particular Kubernetes Deployment. + +In this example we deploy the [prometheus-example-app](https://github.com/brancz/prometheus-example-app) and want to preotect it with kube-rbac-proxy, just as detailed in the [rewrite example](../rewrite/README.md). In this example however we will avoid the recurring SubjectAccessReview requests to the api server by allowing kube-rbac-proxy to authorize these requests statically. This is configured in the file passed to the kube-rbac-proxy with the `--config-file` flag. Additionally the `--upstream` flag has to be set to configure the application that should be proxied to on successful authentication as well as authorization. + +The kube-rbac-proxy itself also requires RBAC access, in order to perform TokenReviews as well as SubjectAccessReviews for requests that are not statically athorized. These are the APIs available from the Kubernetes API to authenticate and then validate the authorization of an entity. + +```bash +$ kubectl create -f deployment.yaml +``` + +The content of this manifest is: + +[embedmd]:# (./deployment.yaml) +```yaml +apiVersion: v1 +kind: ServiceAccount +metadata: + name: kube-rbac-proxy +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: kube-rbac-proxy +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: kube-rbac-proxy +subjects: +- kind: ServiceAccount + name: kube-rbac-proxy + namespace: default +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: kube-rbac-proxy +rules: +- apiGroups: ["authentication.k8s.io"] + resources: + - tokenreviews + verbs: ["create"] +- apiGroups: ["authorization.k8s.io"] + resources: + - subjectaccessreviews + verbs: ["create"] +--- +apiVersion: v1 +kind: Service +metadata: + labels: + app: kube-rbac-proxy + name: kube-rbac-proxy +spec: + ports: + - name: https + port: 8443 + targetPort: https + selector: + app: kube-rbac-proxy +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: kube-rbac-proxy +data: + config-file.yaml: |+ + authorization: + rewrites: + byQueryParameter: + name: "namespace" + resourceAttributes: + apiVersion: v1 + resource: namespace + subresource: metrics + namespace: "{{ .Value }}" + static: + - resourceRequest: true + resource: namespace + subresource: metrics +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: kube-rbac-proxy +spec: + replicas: 1 + selector: + matchLabels: + app: kube-rbac-proxy + template: + metadata: + labels: + app: kube-rbac-proxy + spec: + securityContext: + runAsUser: 65532 + serviceAccountName: kube-rbac-proxy + containers: + - name: kube-rbac-proxy + image: quay.io/brancz/kube-rbac-proxy:v0.8.0 + args: + - "--secure-listen-address=0.0.0.0:8443" + - "--upstream=http://127.0.0.1:8081/" + - "--config-file=/etc/kube-rbac-proxy/config-file.yaml" + - "--logtostderr=true" + - "--v=10" + ports: + - containerPort: 8443 + name: https + volumeMounts: + - name: config + mountPath: /etc/kube-rbac-proxy + securityContext: + allowPrivilegeEscalation: false + - name: prometheus-example-app + image: quay.io/brancz/prometheus-example-app:v0.1.0 + args: + - "--bind=127.0.0.1:8081" + volumes: + - name: config + configMap: + name: kube-rbac-proxy +``` + +Once the prometheus-example-app is up and running, we can test it. In order to test it, we deploy a Job, that performs a `curl` against the above deployment. Because it has the correct RBAC roles, the request will succeed. + +```bash +$ kubectl create -f client-rbac.yaml +``` + +The content of this manifest is: + +[embedmd]:# (./client-rbac.yaml) +```yaml +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: namespace-metrics +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: namespace-metrics +subjects: +- kind: ServiceAccount + name: default + namespace: default +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: namespace-metrics +rules: +- apiGroups: [""] + resources: + - namespace/metrics + verbs: ["get"] +``` + +Now simply run +``` +kubectl run -i -t alpine --image=alpine --restart=Never -- sh -c 'apk add curl; curl -v -s -k -H "Authorization: Bearer `cat /var/run/secrets/kubernetes.io/serviceaccount/token`" https://kube-rbac-proxy.default.svc:8443/metrics?namespace=default' +``` + +The full configuration setting for the static authorization feature looks like this: +``` + config-file.yaml: |+ + authorization: + static: + - user: + name: UserName + groups: + - group1 + - group2 + verb: get + namespace: default + apiGroup: apps + resourceRequest: true + resource: namespace + subresource: metrics + path: /metrics +``` +The values in the above example are just aimed at illustrating what is possible. An omitted configuration setting is interpreted as a wildcard. E.g. if a static-auth configuration omits the `user` setting, any user can be statically authorized if a request fits the remaining configuration. diff --git a/examples/static-auth/client-rbac.yaml b/examples/static-auth/client-rbac.yaml new file mode 100644 index 000000000..2ad696d09 --- /dev/null +++ b/examples/static-auth/client-rbac.yaml @@ -0,0 +1,22 @@ +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: namespace-metrics +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: namespace-metrics +subjects: +- kind: ServiceAccount + name: default + namespace: default +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: namespace-metrics +rules: +- apiGroups: [""] + resources: + - namespace/metrics + verbs: ["get"] diff --git a/examples/static-auth/deployment.yaml b/examples/static-auth/deployment.yaml new file mode 100644 index 000000000..08382c3a2 --- /dev/null +++ b/examples/static-auth/deployment.yaml @@ -0,0 +1,108 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + name: kube-rbac-proxy +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: kube-rbac-proxy +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: kube-rbac-proxy +subjects: +- kind: ServiceAccount + name: kube-rbac-proxy + namespace: default +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: kube-rbac-proxy +rules: +- apiGroups: ["authentication.k8s.io"] + resources: + - tokenreviews + verbs: ["create"] +- apiGroups: ["authorization.k8s.io"] + resources: + - subjectaccessreviews + verbs: ["create"] +--- +apiVersion: v1 +kind: Service +metadata: + labels: + app: kube-rbac-proxy + name: kube-rbac-proxy +spec: + ports: + - name: https + port: 8443 + targetPort: https + selector: + app: kube-rbac-proxy +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: kube-rbac-proxy +data: + config-file.yaml: |+ + authorization: + rewrites: + byQueryParameter: + name: "namespace" + resourceAttributes: + apiVersion: v1 + resource: namespace + subresource: metrics + namespace: "{{ .Value }}" + static: + - resourceRequest: true + resource: namespace + subresource: metrics +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: kube-rbac-proxy +spec: + replicas: 1 + selector: + matchLabels: + app: kube-rbac-proxy + template: + metadata: + labels: + app: kube-rbac-proxy + spec: + securityContext: + runAsUser: 65532 + serviceAccountName: kube-rbac-proxy + containers: + - name: kube-rbac-proxy + image: quay.io/brancz/kube-rbac-proxy:v0.8.0 + args: + - "--secure-listen-address=0.0.0.0:8443" + - "--upstream=http://127.0.0.1:8081/" + - "--config-file=/etc/kube-rbac-proxy/config-file.yaml" + - "--logtostderr=true" + - "--v=10" + ports: + - containerPort: 8443 + name: https + volumeMounts: + - name: config + mountPath: /etc/kube-rbac-proxy + securityContext: + allowPrivilegeEscalation: false + - name: prometheus-example-app + image: quay.io/brancz/prometheus-example-app:v0.1.0 + args: + - "--bind=127.0.0.1:8081" + volumes: + - name: config + configMap: + name: kube-rbac-proxy From 642b7539a8c7779fd4a4f821671905cd059e8985 Mon Sep 17 00:00:00 2001 From: Sergiusz Urbaniak Date: Tue, 4 May 2021 11:47:31 +0200 Subject: [PATCH 5/6] static authorizer: add e2e tests, additional verifications Signed-off-by: Sergiusz Urbaniak --- examples/static-auth/README.md | 17 ++- main.go | 5 +- pkg/authz/auth.go | 17 ++- pkg/authz/auth_test.go | 85 +++++++---- test/e2e/main_test.go | 1 + test/e2e/static-auth/clusterRole.yaml | 14 ++ test/e2e/static-auth/clusterRoleBinding.yaml | 13 ++ .../static-auth/configmap-non-resource.yaml | 13 ++ test/e2e/static-auth/configmap-resource.yaml | 22 +++ test/e2e/static-auth/deployment.yaml | 43 ++++++ test/e2e/static-auth/service.yaml | 14 ++ test/e2e/static-auth/serviceAccount.yaml | 5 + test/e2e/static_authorizer.go | 138 ++++++++++++++++++ test/kubetest/kubernetes.go | 23 +++ 14 files changed, 380 insertions(+), 30 deletions(-) create mode 100644 test/e2e/static-auth/clusterRole.yaml create mode 100644 test/e2e/static-auth/clusterRoleBinding.yaml create mode 100644 test/e2e/static-auth/configmap-non-resource.yaml create mode 100644 test/e2e/static-auth/configmap-resource.yaml create mode 100644 test/e2e/static-auth/deployment.yaml create mode 100644 test/e2e/static-auth/service.yaml create mode 100644 test/e2e/static-auth/serviceAccount.yaml create mode 100644 test/e2e/static_authorizer.go diff --git a/examples/static-auth/README.md b/examples/static-auth/README.md index 7ece05557..61fc4b437 100644 --- a/examples/static-auth/README.md +++ b/examples/static-auth/README.md @@ -165,7 +165,7 @@ Now simply run kubectl run -i -t alpine --image=alpine --restart=Never -- sh -c 'apk add curl; curl -v -s -k -H "Authorization: Bearer `cat /var/run/secrets/kubernetes.io/serviceaccount/token`" https://kube-rbac-proxy.default.svc:8443/metrics?namespace=default' ``` -The full configuration setting for the static authorization feature looks like this: +A configuration setting for the static authorization feature for resource requests looks like this: ``` config-file.yaml: |+ authorization: @@ -181,6 +181,21 @@ The full configuration setting for the static authorization feature looks like t resourceRequest: true resource: namespace subresource: metrics +``` + +A configuration setting for the static authorization feature for non-resource requests looks like this: +``` + config-file.yaml: |+ + authorization: + static: + - user: + name: UserName + groups: + - group1 + - group2 + verb: get + resourceRequest: false path: /metrics ``` + The values in the above example are just aimed at illustrating what is possible. An omitted configuration setting is interpreted as a wildcard. E.g. if a static-auth configuration omits the `user` setting, any user can be statically authorized if a request fits the remaining configuration. diff --git a/main.go b/main.go index 20a2cd329..539a5ea89 100644 --- a/main.go +++ b/main.go @@ -191,7 +191,10 @@ func main() { klog.Fatalf("Failed to create sar authorizer: %v", err) } - staticAuthorizer := authz.NewStaticAuthorizer(cfg.auth.Authorization.Static) + staticAuthorizer, err := authz.NewStaticAuthorizer(cfg.auth.Authorization.Static) + if err != nil { + klog.Fatalf("Failed to create static authorizer: %v", err) + } authorizer := union.New( staticAuthorizer, diff --git a/pkg/authz/auth.go b/pkg/authz/auth.go index 25df7bfac..94b297d40 100644 --- a/pkg/authz/auth.go +++ b/pkg/authz/auth.go @@ -19,6 +19,7 @@ package authz import ( "context" "errors" + "fmt" "time" "k8s.io/apiserver/pkg/authorization/authorizer" @@ -108,7 +109,12 @@ func (saConfig StaticAuthorizationConfig) Equal(a authorizer.Attributes) bool { } } - if isAllowed(saConfig.User.Name, a.GetUser().GetName()) && + userName := "" + if a.GetUser() != nil { + userName = a.GetUser().GetName() + } + + if isAllowed(saConfig.User.Name, userName) && isAllowed(saConfig.Verb, a.GetVerb()) && isAllowed(saConfig.Namespace, a.GetNamespace()) && isAllowed(saConfig.APIGroup, a.GetAPIGroup()) && @@ -133,6 +139,11 @@ func (sa staticAuthorizer) Authorize(ctx context.Context, a authorizer.Attribute return authorizer.DecisionNoOpinion, "", nil } -func NewStaticAuthorizer(config []StaticAuthorizationConfig) staticAuthorizer { - return staticAuthorizer{config} +func NewStaticAuthorizer(config []StaticAuthorizationConfig) (*staticAuthorizer, error) { + for _, c := range config { + if c.ResourceRequest != (c.Path == "") { + return nil, fmt.Errorf("invalid configuration: resource requests must not include a path: %v", config) + } + } + return &staticAuthorizer{config}, nil } diff --git a/pkg/authz/auth_test.go b/pkg/authz/auth_test.go index d50e8433a..608ecb294 100644 --- a/pkg/authz/auth_test.go +++ b/pkg/authz/auth_test.go @@ -26,17 +26,18 @@ import ( func TestStaticAuthorizer(t *testing.T) { tests := []struct { - name string - authorizer authorizer.Authorizer + name string + config []StaticAuthorizationConfig + shouldFail bool shouldPass []authorizer.Attributes shouldNoOpinion []authorizer.Attributes }{ { name: "pathOnly", - authorizer: NewStaticAuthorizer([]StaticAuthorizationConfig{ - StaticAuthorizationConfig{Path: "/metrics"}, - }), + config: []StaticAuthorizationConfig{ + {Path: "/metrics", ResourceRequest: false}, + }, shouldPass: []authorizer.Attributes{ authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "get", Path: "/metrics"}, authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "update", Path: "/metrics"}, @@ -48,9 +49,9 @@ func TestStaticAuthorizer(t *testing.T) { }, { name: "pathAndVerb", - authorizer: NewStaticAuthorizer([]StaticAuthorizationConfig{ - StaticAuthorizationConfig{Path: "/metrics", Verb: "get"}, - }), + config: []StaticAuthorizationConfig{ + {Path: "/metrics", Verb: "get"}, + }, shouldPass: []authorizer.Attributes{ authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "get", Path: "/metrics"}, }, @@ -62,23 +63,24 @@ func TestStaticAuthorizer(t *testing.T) { }, }, { - name: "resourceRequestSpecifiedTrue", - authorizer: NewStaticAuthorizer([]StaticAuthorizationConfig{ - StaticAuthorizationConfig{Path: "/metrics", Verb: "get", ResourceRequest: true}, - }), - shouldPass: []authorizer.Attributes{ - authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "get", Path: "/metrics", ResourceRequest: true}, + name: "nonResourceRequestSpecifiedTrue", + config: []StaticAuthorizationConfig{ + {Path: "/metrics", Verb: "get", ResourceRequest: true}, }, - shouldNoOpinion: []authorizer.Attributes{ - // wrong resourceRequest - authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "get", Path: "/metrics", ResourceRequest: false}, + shouldFail: true, + }, + { + name: "resourceRequestSpecifiedFalse", + config: []StaticAuthorizationConfig{ + {Resource: "namespaces", Verb: "get", ResourceRequest: false}, }, + shouldFail: true, }, { name: "resourceRequestSpecifiedFalse", - authorizer: NewStaticAuthorizer([]StaticAuthorizationConfig{ - StaticAuthorizationConfig{Path: "/metrics", Verb: "get", ResourceRequest: false}, - }), + config: []StaticAuthorizationConfig{ + {Path: "/metrics", Verb: "get", ResourceRequest: false}, + }, shouldPass: []authorizer.Attributes{ authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "get", Path: "/metrics", ResourceRequest: false}, }, @@ -89,9 +91,9 @@ func TestStaticAuthorizer(t *testing.T) { }, { name: "resourceRequestUnspecified", - authorizer: NewStaticAuthorizer([]StaticAuthorizationConfig{ - StaticAuthorizationConfig{Path: "/metrics", Verb: "get"}, - }), + config: []StaticAuthorizationConfig{ + {Path: "/metrics", Verb: "get"}, + }, shouldPass: []authorizer.Attributes{ authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "get", Path: "/metrics", ResourceRequest: false}, }, @@ -105,17 +107,50 @@ func TestStaticAuthorizer(t *testing.T) { authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "update", Path: "/metrics", ResourceRequest: false}, }, }, + { + name: "resourceRequest", + config: []StaticAuthorizationConfig{ + {Resource: "namespaces", Verb: "get", ResourceRequest: true}, + }, + shouldPass: []authorizer.Attributes{ + authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "get", Resource: "namespaces", ResourceRequest: true}, + authorizer.AttributesRecord{Verb: "get", Resource: "namespaces", ResourceRequest: true}, + }, + shouldNoOpinion: []authorizer.Attributes{ + authorizer.AttributesRecord{Verb: "get", Resource: "services", ResourceRequest: true}, + }, + }, + { + name: "resourceRequestSpecificUser", + config: []StaticAuthorizationConfig{ + {User: UserConfig{Name: "system:foo"}, Resource: "namespaces", Verb: "get", ResourceRequest: true}, + }, + shouldPass: []authorizer.Attributes{ + authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "get", Resource: "namespaces", ResourceRequest: true}, + }, + shouldNoOpinion: []authorizer.Attributes{ + authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:bar"}, Verb: "get", Resource: "namespaces", ResourceRequest: true}, + authorizer.AttributesRecord{Verb: "get", Resource: "namespaces", ResourceRequest: true}, + authorizer.AttributesRecord{Verb: "get", Resource: "services", ResourceRequest: true}, + }, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + auth, err := NewStaticAuthorizer(tt.config) + if failed := err != nil; tt.shouldFail != failed { + t.Errorf("static authorizer creation expected to fail: %v, got %v, err: %v", tt.shouldFail, failed, err) + return + } + for _, attr := range tt.shouldPass { - if decision, _, _ := tt.authorizer.Authorize(context.Background(), attr); decision != authorizer.DecisionAllow { + if decision, _, _ := auth.Authorize(context.Background(), attr); decision != authorizer.DecisionAllow { t.Errorf("incorrectly restricted %v", attr) } } for _, attr := range tt.shouldNoOpinion { - if decision, _, _ := tt.authorizer.Authorize(context.Background(), attr); decision != authorizer.DecisionNoOpinion { + if decision, _, _ := auth.Authorize(context.Background(), attr); decision != authorizer.DecisionNoOpinion { t.Errorf("incorrectly opinionated %v", attr) } } diff --git a/test/e2e/main_test.go b/test/e2e/main_test.go index b87176e7c..9c88fef85 100644 --- a/test/e2e/main_test.go +++ b/test/e2e/main_test.go @@ -55,6 +55,7 @@ func Test(t *testing.T) { "AllowPath": testAllowPathsRegexp(suite), "IgnorePath": testIgnorePaths(suite), "TLS": testTLS(suite), + "StaticAuthorizer": testStaticAuthorizer(suite), } for name, tc := range tests { diff --git a/test/e2e/static-auth/clusterRole.yaml b/test/e2e/static-auth/clusterRole.yaml new file mode 100644 index 000000000..e9bc500b7 --- /dev/null +++ b/test/e2e/static-auth/clusterRole.yaml @@ -0,0 +1,14 @@ +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: kube-rbac-proxy + namespace: default +rules: + - apiGroups: ["authentication.k8s.io"] + resources: + - tokenreviews + verbs: ["create"] + - apiGroups: ["authorization.k8s.io"] + resources: + - subjectaccessreviews + verbs: ["create"] diff --git a/test/e2e/static-auth/clusterRoleBinding.yaml b/test/e2e/static-auth/clusterRoleBinding.yaml new file mode 100644 index 000000000..f7be8fa4e --- /dev/null +++ b/test/e2e/static-auth/clusterRoleBinding.yaml @@ -0,0 +1,13 @@ +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: kube-rbac-proxy + namespace: default +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: kube-rbac-proxy +subjects: + - kind: ServiceAccount + name: kube-rbac-proxy + namespace: default diff --git a/test/e2e/static-auth/configmap-non-resource.yaml b/test/e2e/static-auth/configmap-non-resource.yaml new file mode 100644 index 000000000..760d07896 --- /dev/null +++ b/test/e2e/static-auth/configmap-non-resource.yaml @@ -0,0 +1,13 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: kube-rbac-proxy +data: + config-file.yaml: |+ + authorization: + static: + - user: + name: system:serviceaccount:default:default + resourceRequest: false + verbs: get + path: /metrics diff --git a/test/e2e/static-auth/configmap-resource.yaml b/test/e2e/static-auth/configmap-resource.yaml new file mode 100644 index 000000000..6261b5613 --- /dev/null +++ b/test/e2e/static-auth/configmap-resource.yaml @@ -0,0 +1,22 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: kube-rbac-proxy +data: + config-file.yaml: |+ + authorization: + rewrites: + byQueryParameter: + name: "namespace" + resourceAttributes: + resource: namespaces + subresource: metrics + namespace: "{{ .Value }}" + static: + - user: + name: system:serviceaccount:default:default + resourceRequest: true + resource: namespaces + subresource: metrics + namespace: default + verbs: get diff --git a/test/e2e/static-auth/deployment.yaml b/test/e2e/static-auth/deployment.yaml new file mode 100644 index 000000000..21019bd60 --- /dev/null +++ b/test/e2e/static-auth/deployment.yaml @@ -0,0 +1,43 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: kube-rbac-proxy + namespace: default +spec: + replicas: 1 + selector: + matchLabels: + app: kube-rbac-proxy + template: + metadata: + labels: + app: kube-rbac-proxy + spec: + securityContext: + runAsUser: 65532 + serviceAccountName: kube-rbac-proxy + containers: + - name: kube-rbac-proxy + image: quay.io/brancz/kube-rbac-proxy:local + args: + - "--secure-listen-address=0.0.0.0:8443" + - "--upstream=http://127.0.0.1:8081/" + - "--config-file=/etc/kube-rbac-proxy/config-file.yaml" + - "--logtostderr=true" + - "--v=10" + ports: + - containerPort: 8443 + name: https + volumeMounts: + - name: config + mountPath: /etc/kube-rbac-proxy + securityContext: + allowPrivilegeEscalation: false + - name: prometheus-example-app + image: quay.io/brancz/prometheus-example-app:v0.1.0 + args: + - "--bind=127.0.0.1:8081" + volumes: + - name: config + configMap: + name: kube-rbac-proxy diff --git a/test/e2e/static-auth/service.yaml b/test/e2e/static-auth/service.yaml new file mode 100644 index 000000000..b1ae11686 --- /dev/null +++ b/test/e2e/static-auth/service.yaml @@ -0,0 +1,14 @@ +apiVersion: v1 +kind: Service +metadata: + labels: + app: kube-rbac-proxy + name: kube-rbac-proxy + namespace: default +spec: + ports: + - name: https + port: 8443 + targetPort: https + selector: + app: kube-rbac-proxy diff --git a/test/e2e/static-auth/serviceAccount.yaml b/test/e2e/static-auth/serviceAccount.yaml new file mode 100644 index 000000000..45feecc9c --- /dev/null +++ b/test/e2e/static-auth/serviceAccount.yaml @@ -0,0 +1,5 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + name: kube-rbac-proxy + namespace: default diff --git a/test/e2e/static_authorizer.go b/test/e2e/static_authorizer.go new file mode 100644 index 000000000..a80019f20 --- /dev/null +++ b/test/e2e/static_authorizer.go @@ -0,0 +1,138 @@ +/* +Copyright 2017 Frederic Branczyk All rights reserved. + +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 e2e + +import ( + "fmt" + "testing" + + "github.com/brancz/kube-rbac-proxy/test/kubetest" +) + +func testStaticAuthorizer(s *kubetest.Suite) kubetest.TestSuite { + return func(t *testing.T) { + command := `curl --connect-timeout 5 -v -s -k --fail -H "Authorization: Bearer $(cat /var/run/secrets/kubernetes.io/serviceaccount/token)" https://kube-rbac-proxy.default.svc.cluster.local:8443%v` + + for _, tc := range []struct { + name string + given []kubetest.Setup + check []kubetest.Check + }{ + { + name: "resource/namespace/metrics/query rewrite/granted", + given: []kubetest.Setup{ + kubetest.CreatedManifests( + s.KubeClient, + "static-auth/configmap-resource.yaml", + "static-auth/clusterRole.yaml", + "static-auth/clusterRoleBinding.yaml", + "static-auth/deployment.yaml", + "static-auth/service.yaml", + "static-auth/serviceAccount.yaml", + ), + }, + check: []kubetest.Check{ + ClientSucceeds( + s.KubeClient, + fmt.Sprintf(command, "/metrics?namespace=default"), + nil, + ), + }, + }, + { + name: "resource/namespace/metrics/query rewrite/forbidden", + given: []kubetest.Setup{ + kubetest.CreatedManifests( + s.KubeClient, + "static-auth/configmap-resource.yaml", + "static-auth/clusterRole.yaml", + "static-auth/clusterRoleBinding.yaml", + "static-auth/deployment.yaml", + "static-auth/service.yaml", + "static-auth/serviceAccount.yaml", + ), + }, + check: []kubetest.Check{ + ClientFails( + s.KubeClient, + fmt.Sprintf(command, "/metrics?namespace=forbidden"), + nil, + ), + }, + }, + { + name: "non-resource/get/metrics/granted", + given: []kubetest.Setup{ + kubetest.CreatedManifests( + s.KubeClient, + "static-auth/configmap-non-resource.yaml", + "static-auth/clusterRole.yaml", + "static-auth/clusterRoleBinding.yaml", + "static-auth/deployment.yaml", + "static-auth/service.yaml", + "static-auth/serviceAccount.yaml", + ), + }, + check: []kubetest.Check{ + ClientSucceeds( + s.KubeClient, + fmt.Sprintf(command, "/metrics"), + nil, + ), + }, + }, + { + name: "non-resource/get/metrics/forbidden", + given: []kubetest.Setup{ + kubetest.CreatedManifests( + s.KubeClient, + "static-auth/configmap-non-resource.yaml", + "static-auth/clusterRole.yaml", + "static-auth/clusterRoleBinding.yaml", + "static-auth/deployment.yaml", + "static-auth/service.yaml", + "static-auth/serviceAccount.yaml", + ), + }, + check: []kubetest.Check{ + ClientFails( + s.KubeClient, + fmt.Sprintf(command, "/forbidden"), + nil, + ), + }, + }, + } { + kubetest.Scenario{ + Name: tc.name, + Given: kubetest.Setups(tc.given...), + When: kubetest.Conditions( + kubetest.PodsAreReady( + s.KubeClient, + 1, + "app=kube-rbac-proxy", + ), + kubetest.ServiceIsReady( + s.KubeClient, + "kube-rbac-proxy", + ), + ), + Then: kubetest.Checks(tc.check...), + }.Run(t) + } + } +} diff --git a/test/kubetest/kubernetes.go b/test/kubetest/kubernetes.go index 4cc897238..af927e1fa 100644 --- a/test/kubetest/kubernetes.go +++ b/test/kubetest/kubernetes.go @@ -83,6 +83,10 @@ func CreatedManifests(client kubernetes.Interface, paths ...string) Setup { if err := createSecret(client, ctx, content); err != nil { return err } + case "configmap": + if err := createConfigmap(client, ctx, content); err != nil { + return err + } default: return fmt.Errorf("unable to unmarshal manifest with unknown kind: %s", kind) } @@ -243,6 +247,25 @@ func createSecret(client kubernetes.Interface, ctx *ScenarioContext, content []b return err } +func createConfigmap(client kubernetes.Interface, ctx *ScenarioContext, content []byte) error { + r := bytes.NewReader(content) + + var configmap *corev1.ConfigMap + if err := kubeyaml.NewYAMLOrJSONDecoder(r, r.Len()).Decode(&configmap); err != nil { + return err + } + + configmap.Namespace = ctx.Namespace + + _, err := client.CoreV1().ConfigMaps(configmap.Namespace).Create(context.TODO(), configmap, metav1.CreateOptions{}) + + ctx.AddFinalizer(func() error { + return client.CoreV1().ConfigMaps(configmap.Namespace).Delete(context.TODO(), configmap.Name, metav1.DeleteOptions{}) + }) + + return err +} + // PodsAreReady waits for a number if replicas matching the given labels to be ready. // Returns a func directly (not Setup or Conditions) as it can be used in Given and When steps func PodsAreReady(client kubernetes.Interface, replicas int, labels string) func(*ScenarioContext) error { From 4a44b610cd12c4cfe076a2b306283d0598c1bb7a Mon Sep 17 00:00:00 2001 From: Sergiusz Urbaniak Date: Wed, 5 May 2021 17:41:49 +0200 Subject: [PATCH 6/6] examples/static-auth/README.md: fix typo Co-authored-by: Jan Fajerski --- examples/static-auth/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/static-auth/README.md b/examples/static-auth/README.md index 61fc4b437..220e6d537 100644 --- a/examples/static-auth/README.md +++ b/examples/static-auth/README.md @@ -4,7 +4,7 @@ RBAC differentiates in two types, that need to be authorized, resources and non-resources. A resource request authorization, could for example be, that a requesting entity needs to be authorized to perform the `get` action on a particular Kubernetes Deployment. -In this example we deploy the [prometheus-example-app](https://github.com/brancz/prometheus-example-app) and want to preotect it with kube-rbac-proxy, just as detailed in the [rewrite example](../rewrite/README.md). In this example however we will avoid the recurring SubjectAccessReview requests to the api server by allowing kube-rbac-proxy to authorize these requests statically. This is configured in the file passed to the kube-rbac-proxy with the `--config-file` flag. Additionally the `--upstream` flag has to be set to configure the application that should be proxied to on successful authentication as well as authorization. +In this example we deploy the [prometheus-example-app](https://github.com/brancz/prometheus-example-app) and want to protect it with kube-rbac-proxy, just as detailed in the [rewrite example](../rewrite/README.md). In this example however we will avoid the recurring SubjectAccessReview requests to the api server by allowing kube-rbac-proxy to authorize these requests statically. This is configured in the file passed to the kube-rbac-proxy with the `--config-file` flag. Additionally the `--upstream` flag has to be set to configure the application that should be proxied to on successful authentication as well as authorization. The kube-rbac-proxy itself also requires RBAC access, in order to perform TokenReviews as well as SubjectAccessReviews for requests that are not statically athorized. These are the APIs available from the Kubernetes API to authenticate and then validate the authorization of an entity.