Search code examples
kubernetesrback8s-serviceaccount

Can Kubernetes RoleBinding have subjects in a different namespace?


RoleBinding subjects do have a namespace field, but when i create a RoleBinding in one namespace with subject in another, it doesn't seem it works.

Full example:

apiVersion: v1
kind: Namespace
metadata:
  name: namespace1

---

apiVersion: v1
kind: Namespace
metadata:
  name: namespace2

---

apiVersion: v1
kind: ServiceAccount
metadata:
  name: test-sa
  namespace: namespace1

---

apiVersion: v1
kind: Secret
metadata:
  name: test-secret
  namespace: namespace2
type: Opaque
data:
  foo: "Zm9vCg=="

---
 
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: test-secret-reader
  namespace: namespace2
rules:
- apiGroups: [""]
  resources: ["secret"]
  verbs: ["get"]
 
---

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: test-secret-reader
  namespace: namespace2
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: test-secret-reader
subjects:
- kind: ServiceAccount
  name: test-sa
  namespace: namespace1

Test with kubectl auth can-i:

$ kubectl auth can-i get secret -n namespace2 --as system:serviceaccount:namespace1:test-sa
no

Solution

  • Despite the fact that Roles and RoleBindings are namespace scoped resources, they can be used to authorize access to subjects in different namespaces.

    The issue with example in question is that rule resources must be in plural:

    apiVersion: rbac.authorization.k8s.io/v1
    kind: Role
    metadata:
      name: test-secret-reader
      namespace: namespace2
    rules:
    - apiGroups: [""]
      resources: ["secrets"]
      verbs: ["get"]
    

    Full example: https://gist.github.com/draganHR/d073d41fc119c8625fa505a5052b133e
    (Tested on Kubernetes 1.27+).