# Kubernetes密钥因缺少Base64编码在环境变量中暴露

- **ID:** `security/kubernetes-secret-exposed-in-env-var-without-encoding`
- **领域:** security
- **类别:** config_error
- **错误码:** `SecretDecodeError`
- **验证级别:** ai_generated
- **修复率:** 95%

## 根因

Kubernetes密钥在YAML中定义时必须进行Base64编码，但开发者常忘记编码，导致明文密钥在Pod规范和日志中暴露。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Kubernetes 1.24+ | active | — | — |
| kubectl 1.24.0 | active | — | — |
| Helm 3.10.0 | active | — | — |
| Minikube 1.28.0 | active | — | — |

## 解决方案

1. ```
   Always base64-encode the secret value before placing it in the YAML. For example:

echo -n 'my-secret-password' | base64
# Output: bXktc2VjcmV0LXBhc3N3b3Jk

Then use it in the Secret YAML:

apiVersion: v1
kind: Secret
metadata:
  name: my-secret
type: Opaque
data:
  password: bXktc2VjcmV0LXBhc3N3b3Jk
   ```
2. ```
   Use kubectl to create secrets from literal values, which handles encoding automatically:

kubectl create secret generic my-secret --from-literal=password='my-secret-password'

This command base64-encodes the value and stores it correctly.
   ```
3. ```
   Use external secrets management tools like HashiCorp Vault with the Kubernetes External Secrets Operator to avoid manual encoding entirely:

apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
  name: my-external-secret
spec:
  secretStoreRef:
    name: vault-backend
    kind: SecretStore
  target:
    name: my-secret
  data:
  - secretKey: password
    remoteRef:
      key: /myapp/password
   ```

## 无效尝试

- **Use the secret value directly in the YAML without encoding, assuming Kubernetes will handle it** — Kubernetes requires base64-encoded values; plaintext will either cause a validation error or be stored as-is, exposing the secret. (100% 失败率)
- **Wrap the secret value in single quotes to escape special characters** — Quoting does not encode the value; it only prevents YAML parsing issues but still leaves the secret in plaintext. (95% 失败率)
- **Use a ConfigMap instead of a Secret for sensitive data** — ConfigMaps store data in plaintext and are not designed for secrets; this exposes the data even more. (90% 失败率)
