# 错误：容器设置了 runAsNonRoot，但镜像将以 root 身份运行。PodSecurityPolicy：不允许特权容器。

- **ID:** `policy/kubernetes-podsecuritypolicy-privileged-container-blocked`
- **领域:** policy
- **类别:** config_error
- **错误码:** `Forbidden`
- **验证级别:** ai_generated
- **修复率:** 82%

## 根因

Kubernetes PodSecurityPolicy（或 OPA/Gatekeeper）拒绝 Pod，因为容器镜像以 root 身份运行，但安全上下文要求非 root，或者容器是特权的。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Kubernetes 1.24 | active | — | — |
| kubectl 1.28 | active | — | — |

## 解决方案

1. ```
   Modify the container image to run as a non-root user. Add a USER directive in the Dockerfile: 'FROM node:18-alpine USER node' then rebuild and push the image.
   ```
2. ```
   Set a specific runAsUser in the pod security context that matches a non-root user in the image: 'securityContext: runAsUser: 1000' (ensure user 1000 exists in the image).
   ```
3. ```
   Request an exception from the cluster administrator to allow the privileged container. This may involve creating a RoleBinding or ClusterRoleBinding that grants access to a less restrictive PSP.
   ```

## 无效尝试

- **Set 'runAsNonRoot: false' in the pod security context.** — The PodSecurityPolicy may still block the pod if it requires non-root. The policy is enforced regardless of the pod's security context. (70% 失败率)
- **Remove the security context entirely and let the image run as root.** — The PodSecurityPolicy may have a rule that requires non-root, so removing the context doesn't bypass the policy; it may default to the image's user, which is root. (80% 失败率)
- **Use a different namespace where the policy is not applied.** — PodSecurityPolicies are cluster-scoped or namespace-scoped depending on configuration. If cluster-scoped, all namespaces are affected. Even if namespace-scoped, the policy may still apply to the target namespace. (60% 失败率)
