I'm looking for a way to run kubectl auth can-i get pods --as system:serviceaccount:default:test
using kubernetes go-client.
So far I got the below code but it doesn't work as I'm getting a different response in comparison to kubectl auth can-i
. I know this is about impersonation and so I'm adding rest.ImpersonationConfig
but it's still not working.
Steps to reproduce:
kind create cluster
kubectl create sa test
kubectl create role test --verb=get --verb=list --resource=pods
kubectl create rolebinding test --role=test --serviceaccount=default:test
kubectl auth can-i get pod --as system:serviceaccount:default:test
# yes
Code:
package main
import (
"context"
"fmt"
"os"
authv1 "k8s.io/api/authorization/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
kubeconfig := fmt.Sprintf("%s/.kube/config", os.Getenv("HOME"))
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
panic(err.Error())
}
config.Impersonate = rest.ImpersonationConfig{
UserName: "system:serviceaccount:default:test",
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
action := authv1.ResourceAttributes{
Namespace: "default",
Verb: "get",
Resource: "pod",
}
selfCheck := authv1.SelfSubjectAccessReview{
Spec: authv1.SelfSubjectAccessReviewSpec{
ResourceAttributes: &action,
},
}
resp, err := clientset.AuthorizationV1().
SelfSubjectAccessReviews().
Create(context.TODO(), &selfCheck, metav1.CreateOptions{})
if err != nil {
panic(err.Error())
}
if resp.Status.Allowed {
fmt.Println("allowed")
} else {
fmt.Println("denied")
}
}
I figured it out! I used the singular form of "pod" instead of the plural "pods" in ResourceAttributes.
package main
import (
"context"
"fmt"
"os"
authv1 "k8s.io/api/authorization/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
kubeconfig := fmt.Sprintf("%s/.kube/config", os.Getenv("HOME"))
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
panic(err.Error())
}
config.Impersonate = rest.ImpersonationConfig{
UserName: "system:serviceaccount:default:test",
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
action := authv1.ResourceAttributes{
Namespace: "default",
Verb: "get",
Resource: "pods",
}
selfCheck := authv1.SelfSubjectAccessReview{
Spec: authv1.SelfSubjectAccessReviewSpec{
ResourceAttributes: &action,
},
}
resp, err := clientset.AuthorizationV1().
SelfSubjectAccessReviews().
Create(context.TODO(), &selfCheck, metav1.CreateOptions{})
if err != nil {
panic(err.Error())
}
if resp.Status.Allowed {
fmt.Println("allowed")
} else {
fmt.Println("denied")
}
}