RBAC Least-Privilege cho Application ServiceAccount
🎯 Mục tiêu: Tạo ServiceAccount riêng cho một app, gán Role tối thiểu chỉ đọc ConfigMap trong namespace của nó; xác nhận app không thể đọc Secret hoặc tài nguyên namespace khác.
🧰 Công cụ / nền tảng: kubectl, kind (local cluster), terminal Linux/WSL2.
📦 Chuẩn bị: Có cluster kind đang chạy (kind create cluster --name sec-lab); kubectl context trỏ đúng.
▶️ Các bước:
# 1. Tạo namespace và ServiceAccount
kubectl create namespace app-ns
kubectl create serviceaccount app-reader -n app-ns
# 2. Tạo Role chỉ cho phép get/list ConfigMap
cat <<EOF | kubectl apply -f -
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: configmap-reader
namespace: app-ns
rules:
- apiGroups: [""]
resources: ["configmaps"]
verbs: ["get", "list"]
EOF
# 3. Bind Role vào ServiceAccount
cat <<EOF | kubectl apply -f -
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: app-reader-binding
namespace: app-ns
subjects:
- kind: ServiceAccount
name: app-reader
namespace: app-ns
roleRef:
kind: Role
name: configmap-reader
apiGroup: rbac.authorization.k8s.io
EOF
# 4. Kiểm tra quyền: ĐƯỢC đọc ConfigMap
kubectl auth can-i get configmaps \
--as=system:serviceaccount:app-ns:app-reader \
-n app-ns
# Expected: yes
# 5. Kiểm tra quyền: KHÔNG được đọc Secret
kubectl auth can-i get secrets \
--as=system:serviceaccount:app-ns:app-reader \
-n app-ns
# Expected: no
# 6. Kiểm tra KHÔNG có quyền ở namespace khác
kubectl auth can-i get configmaps \
--as=system:serviceaccount:app-ns:app-reader \
-n default
# Expected: no
# 7. List toàn bộ quyền của SA này
kubectl auth can-i --list \
--as=system:serviceaccount:app-ns:app-reader \
-n app-ns
✅ Kết quả mong đợi: Bước 4 trả về yes; bước 5 và 6 trả về no. Output của bước 7 chỉ liệt kê configmaps với verbs get/list.
🧹 Cleanup: kubectl delete namespace app-ns