Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add kubectl can-i to see if you can perform an action #41077

Merged
merged 1 commit into from
Feb 26, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/.generated_docs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ docs/man/man1/kubectl-api-versions.1
docs/man/man1/kubectl-apply-view-last-applied.1
docs/man/man1/kubectl-apply.1
docs/man/man1/kubectl-attach.1
docs/man/man1/kubectl-auth-can-i.1
docs/man/man1/kubectl-auth.1
docs/man/man1/kubectl-autoscale.1
docs/man/man1/kubectl-certificate-approve.1
docs/man/man1/kubectl-certificate-deny.1
Expand Down Expand Up @@ -101,6 +103,8 @@ docs/user-guide/kubectl/kubectl_api-versions.md
docs/user-guide/kubectl/kubectl_apply.md
docs/user-guide/kubectl/kubectl_apply_view-last-applied.md
docs/user-guide/kubectl/kubectl_attach.md
docs/user-guide/kubectl/kubectl_auth.md
docs/user-guide/kubectl/kubectl_auth_can-i.md
docs/user-guide/kubectl/kubectl_autoscale.md
docs/user-guide/kubectl/kubectl_certificate.md
docs/user-guide/kubectl/kubectl_certificate_approve.md
Expand Down Expand Up @@ -183,6 +187,7 @@ docs/yaml/kubectl/kubectl_annotate.yaml
docs/yaml/kubectl/kubectl_api-versions.yaml
docs/yaml/kubectl/kubectl_apply.yaml
docs/yaml/kubectl/kubectl_attach.yaml
docs/yaml/kubectl/kubectl_auth.yaml
docs/yaml/kubectl/kubectl_autoscale.yaml
docs/yaml/kubectl/kubectl_certificate.yaml
docs/yaml/kubectl/kubectl_cluster-info.yaml
Expand Down
3 changes: 3 additions & 0 deletions docs/man/man1/kubectl-auth-can-i.1
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
This file is autogenerated, but we've stopped checking such files into the
repository to reduce the need for rebases. Please run hack/generate-docs.sh to
populate this file.
3 changes: 3 additions & 0 deletions docs/man/man1/kubectl-auth.1
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
This file is autogenerated, but we've stopped checking such files into the
repository to reduce the need for rebases. Please run hack/generate-docs.sh to
populate this file.
3 changes: 3 additions & 0 deletions docs/user-guide/kubectl/kubectl_auth.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
This file is autogenerated, but we've stopped checking such files into the
repository to reduce the need for rebases. Please run hack/generate-docs.sh to
populate this file.
3 changes: 3 additions & 0 deletions docs/user-guide/kubectl/kubectl_auth_can-i.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
This file is autogenerated, but we've stopped checking such files into the
repository to reduce the need for rebases. Please run hack/generate-docs.sh to
populate this file.
3 changes: 3 additions & 0 deletions docs/yaml/kubectl/kubectl_auth.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
This file is autogenerated, but we've stopped checking such files into the
repository to reduce the need for rebases. Please run hack/generate-docs.sh to
populate this file.
1 change: 1 addition & 0 deletions hack/verify-flags/known-flags.txt
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,7 @@ pv-recycler-pod-template-filepath-hostpath
pv-recycler-pod-template-filepath-nfs
pv-recycler-timeout-increment-hostpath
pvclaimbinder-sync-period
quiet
read-only-port
really-crash-for-testing
reconcile-cidr
Expand Down
2 changes: 2 additions & 0 deletions pkg/kubectl/cmd/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ go_library(
"//pkg/client/unversioned:go_default_library",
"//pkg/client/unversioned/remotecommand:go_default_library",
"//pkg/kubectl:go_default_library",
"//pkg/kubectl/cmd/auth:go_default_library",
"//pkg/kubectl/cmd/config:go_default_library",
"//pkg/kubectl/cmd/rollout:go_default_library",
"//pkg/kubectl/cmd/set:go_default_library",
Expand Down Expand Up @@ -238,6 +239,7 @@ filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//pkg/kubectl/cmd/auth:all-srcs",
"//pkg/kubectl/cmd/config:all-srcs",
"//pkg/kubectl/cmd/rollout:all-srcs",
"//pkg/kubectl/cmd/set:all-srcs",
Expand Down
54 changes: 54 additions & 0 deletions pkg/kubectl/cmd/auth/BUILD
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package(default_visibility = ["//visibility:public"])

licenses(["notice"])

load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)

go_library(
name = "go_default_library",
srcs = [
"auth.go",
"cani.go",
],
tags = ["automanaged"],
deps = [
"//pkg/apis/authorization:go_default_library",
"//pkg/client/clientset_generated/internalclientset/typed/authorization/internalversion:go_default_library",
"//pkg/kubectl/cmd/templates:go_default_library",
"//pkg/kubectl/cmd/util:go_default_library",
"//vendor:github.com/spf13/cobra",
"//vendor:k8s.io/apimachinery/pkg/api/meta",
"//vendor:k8s.io/apimachinery/pkg/runtime/schema",
"//vendor:k8s.io/apimachinery/pkg/util/errors",
],
)

filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)

filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)

go_test(
name = "go_default_test",
srcs = ["cani_test.go"],
library = ":go_default_library",
tags = ["automanaged"],
deps = [
"//pkg/api:go_default_library",
"//pkg/kubectl/cmd/testing:go_default_library",
"//vendor:k8s.io/client-go/rest",
"//vendor:k8s.io/client-go/rest/fake",
],
)
39 changes: 39 additions & 0 deletions pkg/kubectl/cmd/auth/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
Copyright 2014 The Kubernetes Authors.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: should this be the current year?


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 auth

import (
"io"

"github.com/spf13/cobra"

cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
)

func NewCmdAuth(f cmdutil.Factory, out, errOut io.Writer) *cobra.Command {
// Parent command to which all subcommands are added.
cmds := &cobra.Command{
Use: "auth",
Short: "Inspect authorization",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will the sub commands always be about inspection? What about setting / creating things?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will the sub commands always be about inspection? What about setting / creating things?

Because kube isn't opinionated about authentication and authorization, its very difficult (maybe impossible) to provide generic mutation functionality. We can provide generic inspection since it mirrors API server needs, but not generic mutation.

Long: `Inspect authorization`,
Run: cmdutil.DefaultSubCommandRun(errOut),
}

cmds.AddCommand(NewCmdCanI(f, out, errOut))

return cmds
}
196 changes: 196 additions & 0 deletions pkg/kubectl/cmd/auth/cani.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
/*
Copyright 2017 The Kubernetes Authors.

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 auth

import (
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"strings"

"github.com/spf13/cobra"

"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime/schema"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
authorizationapi "k8s.io/kubernetes/pkg/apis/authorization"
internalauthorizationclient "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/authorization/internalversion"
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
)

// CanIOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of
// referencing the cmd.Flags()
type CanIOptions struct {
AllNamespaces bool
Quiet bool
Namespace string
SelfSARClient internalauthorizationclient.SelfSubjectAccessReviewsGetter

Verb string
Resource schema.GroupVersionResource
ResourceName string

Out io.Writer
Err io.Writer
}

var (
canILong = templates.LongDesc(`
Check whether an action is allowed.

VERB is a logical Kubernetes API verb like 'get', 'list', 'watch', 'delete', etc.
TYPE is a Kubernetes resource. Shortcuts and groups will be resolved.
NAME is the name of a particular Kubernetes resource.`)

canIExample = templates.Examples(`
# Check to see if I can create pods in any namespace
kubectl auth can-i create pods --all-namespaces

# Check to see if I can list deployments in my current namespace
kubectl auth can-i list deployments.extensions
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this standard syntax to have kind.group? Do we do group.kind anywhere?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this standard syntax to have kind.group? Do we do group.kind anywhere?

kubectl get, patch, update, delete, apply and everywhere that uses a resource builder uses resource.group that matches this help.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very interesting. This is the first time I have noticed it in the help documentation.


# Check to see if I can get the job named "bar" in namespace "foo"
kubectl auth can-i list jobs.batch/bar -n foo`)
)

func NewCmdCanI(f cmdutil.Factory, out, err io.Writer) *cobra.Command {
o := &CanIOptions{
Out: out,
Err: err,
}

cmd := &cobra.Command{
Use: "can-i VERB [TYPE | TYPE/NAME]",
Short: "Check whether an action is allowed",
Long: canILong,
Example: canIExample,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(o.Complete(f, args))
cmdutil.CheckErr(o.Validate())

allowed, err := o.RunAccessCheck()
if err == nil {
return
}

if o.Quiet && !allowed {
os.Exit(1)
}

cmdutil.CheckErr(err)
},
}

cmd.Flags().BoolVar(&o.AllNamespaces, "all-namespaces", o.AllNamespaces, "If true, check the specified action in all namespaces.")
cmd.Flags().BoolVarP(&o.Quiet, "quiet", "q", o.Quiet, "If true, suppress output and just return the exit code.")
return cmd
}

func (o *CanIOptions) Complete(f cmdutil.Factory, args []string) error {
switch len(args) {
case 2:
resourceTokens := strings.SplitN(args[1], "/", 2)
restMapper, _ := f.Object()
o.Verb = args[0]
o.Resource = resourceFor(restMapper, resourceTokens[0])
if len(resourceTokens) > 1 {
o.ResourceName = resourceTokens[1]
}
default:
return errors.New("you must specify two or three arguments: verb, resource, and optional resourceName")
}

var err error
client, err := f.ClientSet()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIUC, this will only work for core-apiservers and can't use user-apiservers directly. Is that fine?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing stops user apiservers from including SAR and not registering it to be aggregated. In fact, I would encourage that

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIUC, this will only work for core-apiservers and can't use user-apiservers directly. Is that fine?

Consider cases like a someone evaluating a new API server before turning it one. He'll proxy to the service and then do things to check functionality and permissions.

if err != nil {
return err
}
o.SelfSARClient = client.Authorization()

o.Namespace = ""
if !o.AllNamespaces {
o.Namespace, _, err = f.DefaultNamespace()
if err != nil {
return err
}
}

if o.Quiet {
o.Out = ioutil.Discard
}

return nil
}

func (o *CanIOptions) Validate() error {
errors := []error{}
return utilerrors.NewAggregate(errors)
}

func (o *CanIOptions) RunAccessCheck() (bool, error) {
sar := &authorizationapi.SelfSubjectAccessReview{
Spec: authorizationapi.SelfSubjectAccessReviewSpec{
ResourceAttributes: &authorizationapi.ResourceAttributes{
Namespace: o.Namespace,
Verb: o.Verb,
Group: o.Resource.Group,
Resource: o.Resource.Resource,
Name: o.ResourceName,
},
},
}

response, err := o.SelfSARClient.SelfSubjectAccessReviews().Create(sar)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Should we provide a user friendly message in the event the api is not enabled?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Should we provide a user friendly message in the event the api is not enabled?

This would return our 404, which gets processed through our normal checkerr path and should come back looking reasonable to a user. A general prereq discovery pattern for kubectl would be neat though. Especially as we get more API servers.

if err != nil {
return false, err
}

if response.Status.Allowed {
fmt.Fprintln(o.Out, "yes")
} else {
fmt.Fprint(o.Out, "no")
if len(response.Status.Reason) > 0 {
fmt.Fprintf(o.Out, " - %v", response.Status.Reason)
}
if len(response.Status.EvaluationError) > 0 {
fmt.Fprintf(o.Out, " - %v", response.Status.EvaluationError)
}
fmt.Fprintln(o.Out)
}

return response.Status.Allowed, nil
}

func resourceFor(mapper meta.RESTMapper, resourceArg string) schema.GroupVersionResource {
fullySpecifiedGVR, groupResource := schema.ParseResourceArg(strings.ToLower(resourceArg))
gvr := schema.GroupVersionResource{}
if fullySpecifiedGVR != nil {
gvr, _ = mapper.ResourceFor(*fullySpecifiedGVR)
}
if gvr.Empty() {
var err error
gvr, err = mapper.ResourceFor(groupResource.WithVersion(""))
if err != nil {
return schema.GroupVersionResource{Resource: resourceArg}
}
}

return gvr
}