容器安全
Vibe Prompt
「幫我在 CI/CD 中加入 Docker Image 安全掃描(Trivy),並設定 K8s Pod Security Standards。」
Trivy 掃描
- name: Scan Docker Image
uses: aquasecurity/trivy-action@master
with:
image-ref: 'ghcr.io/myorg/myapp:latest'
format: 'table'
exit-code: '1'
severity: 'HIGH,CRITICAL'
Dockerfile 安全最佳實踐
# ❌ 不安全寫法
FROM node:latest # 不指定版本
RUN npm install # 包含 dev 套件
USER root # root 執行
# ✅ 安全寫法
FROM node:20-alpine@sha256:abc123 # 固定 digest
RUN npm ci --only=production # 只安裝正式依賴
USER node # 非 root 執行
COPY --chown=node:node . /app # 設定擁有者
HEALTHCHECK CMD wget -qO- http://localhost:3000/health || exit 1
K8s Pod Security Standards
apiVersion: v1
kind: Namespace
metadata:
name: production
labels:
pod-security.kubernetes.io/enforce: restricted
pod-security.kubernetes.io/audit: restricted
pod-security.kubernetes.io/warn: restricted
三種層級
| 層級 | 說明 | |------|------| | privileged | 無限制(不建議) | | baseline | 最低安全標準(建議) | | restricted | 最嚴格(建議正式環境) |
禁止的設定(restricted)
- ❌ privileged containers
- ❌ hostNetwork / hostPort
- ❌ hostPID / hostIPC
- ❌ 可寫入的 hostPath Volume
- ❌ 允許提升權限(allowPrivilegeEscalation=true)
- ❌ 以 root 執行
Vibe Prompt
「幫我檢查這個 Deployment 是否符合 Pod Security restricted 標準。」
# 需要修正
spec:
securityContext:
runAsNonRoot: true
seccompProfile:
type: RuntimeDefault
containers:
- securityContext:
allowPrivilegeEscalation: false
capabilities:
drop: ["ALL"]
readOnlyRootFilesystem: true