diff --git a/examples/static-auth/README.md b/examples/static-auth/README.md new file mode 100644 index 000000000..220e6d537 --- /dev/null +++ b/examples/static-auth/README.md @@ -0,0 +1,201 @@ +# 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 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. + +```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' +``` + +A configuration setting for the static authorization feature for resource requests 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 +``` + +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/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 diff --git a/main.go b/main.go index a477dad98..539a5ea89 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/authorization/union" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" @@ -184,12 +185,22 @@ func main() { } sarClient := kubeClient.AuthorizationV1().SubjectAccessReviews() - authorizer, err := authz.NewAuthorizer(sarClient) + sarAuthorizer, err := authz.NewSarAuthorizer(sarClient) if err != nil { - klog.Fatalf("Failed to create authorizer: %v", err) + klog.Fatalf("Failed to create sar authorizer: %v", err) } + staticAuthorizer, err := authz.NewStaticAuthorizer(cfg.auth.Authorization.Static) + if err != nil { + klog.Fatalf("Failed to create static authorizer: %v", err) + } + + authorizer := union.New( + staticAuthorizer, + sarAuthorizer, + ) + auth, err := proxy.New(kubeClient, cfg.auth, authorizer, authenticator) if err != nil { diff --git a/pkg/authz/auth.go b/pkg/authz/auth.go index 1fcd1524c..94b297d40 100644 --- a/pkg/authz/auth.go +++ b/pkg/authz/auth.go @@ -17,7 +17,9 @@ limitations under the License. package authz import ( + "context" "errors" + "fmt" "time" "k8s.io/apiserver/pkg/authorization/authorizer" @@ -30,6 +32,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 +64,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 +95,55 @@ 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 + } + } + + 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()) && + 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, 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 new file mode 100644 index 000000000..608ecb294 --- /dev/null +++ b/pkg/authz/auth_test.go @@ -0,0 +1,159 @@ +/* +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 + config []StaticAuthorizationConfig + + shouldFail bool + shouldPass []authorizer.Attributes + shouldNoOpinion []authorizer.Attributes + }{ + { + name: "pathOnly", + 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"}, + }, + shouldNoOpinion: []authorizer.Attributes{ + // wrong path + authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "get", Path: "/api"}, + }, + }, + { + name: "pathAndVerb", + config: []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: "nonResourceRequestSpecifiedTrue", + config: []StaticAuthorizationConfig{ + {Path: "/metrics", Verb: "get", ResourceRequest: true}, + }, + shouldFail: true, + }, + { + name: "resourceRequestSpecifiedFalse", + config: []StaticAuthorizationConfig{ + {Resource: "namespaces", Verb: "get", ResourceRequest: false}, + }, + shouldFail: true, + }, + { + name: "resourceRequestSpecifiedFalse", + 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}, + }, + shouldNoOpinion: []authorizer.Attributes{ + // wrong resourceRequest + authorizer.AttributesRecord{User: &user.DefaultInfo{Name: "system:foo"}, Verb: "get", Path: "/metrics", ResourceRequest: true}, + }, + }, + { + name: "resourceRequestUnspecified", + config: []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}, + }, + }, + { + 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, _, _ := auth.Authorize(context.Background(), attr); decision != authorizer.DecisionAllow { + t.Errorf("incorrectly restricted %v", attr) + } + } + + for _, attr := range tt.shouldNoOpinion { + 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 {