# RBAC for lifecycle sidecar - allows self-deletion only
# Each sandbox pod gets this ServiceAccount and can only delete its own deployment
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: sandbox-lifecycle
  namespace: sandbox
---
# Role allowing deletion of deployments and PVCs
# This is scoped to the sandbox namespace
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: sandbox-self-delete
  namespace: sandbox
rules:
  # Allow getting and deleting deployments
  - apiGroups: ["apps"]
    resources: ["deployments"]
    verbs: ["get", "delete"]

  # Allow getting and deleting PVCs (for anonymous users)
  - apiGroups: [""]
    resources: ["persistentvolumeclaims"]
    verbs: ["get", "delete"]

  # Read-only access to pods (for status checking)
  - apiGroups: [""]
    resources: ["pods"]
    verbs: ["get", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: sandbox-self-delete
  namespace: sandbox
subjects:
  - kind: ServiceAccount
    name: sandbox-lifecycle
    namespace: sandbox
roleRef:
  kind: Role
  name: sandbox-self-delete
  apiGroup: rbac.authorization.k8s.io
---
# Additional security: ValidatingWebhookConfiguration to restrict deletion
# This ensures sidecars can only delete their own deployment
# Requires a validating webhook server (can be added later)
# For now, we rely on:
# 1. Sidecar only knowing its own deployment name (from env)
# 2. RBAC limiting to sandbox namespace
# 3. Admission policy restricting deployment creation (already defined)
