使用 OPA Gatekeeper 拒绝高风险镜像

解读

在国内云原生落地场景中,**“高风险镜像”**通常指:

  1. 来自非公司 Harbor 或未通过安全扫描的镜像;
  2. tag 为 latest 或 未带数字签名;
  3. 包含已知 CVE 等级≥Critical 的基础镜像;
  4. 仓库地址命中工信部备案黑名单或公司自定义黑名单。

面试官想考察:

  • 能否把Groovy 脚本化能力与Gatekeeper ConstraintTemplate结合,快速交付可落地的策略;
  • 是否熟悉国产发行版 Kubernetes(如阿里 ACK、腾讯 TKE、华为 CCE)的OPA 插件安装差异;
  • 能否在Gradle 构建流水线里自动同步策略到集群,实现**“代码即策略”**。

知识点

  1. Groovy 与 OPA 的交互方式

    • 用 Groovy 的 JsonOutput 把策略参数序列化为 YAML,通过 kubectl apply -f - 直接写入集群;
    • 利用 GroovyShell 在 Jenkins shared-library 里动态渲染 ConstraintTemplate 的 Rego 字段,实现**“同一套模板,多套环境阈值不同”**。
  2. Gatekeeper 核心模型

    • ConstraintTemplate:定义rego 规则与输入参数 schema;
    • Constraint:实例化模板,绑定到命名空间或集群级;
    • Violation:命中策略时返回的结构化错误,可被 Groovy 解析后回写企业微信/飞书。
  3. 国产集群的坑

    • 阿里 ACK 的 managed-kube-apiserver 默认关闭 ValidatingAdmissionWebhook 的 failurePolicy=Fail,需显式在 Groovy 脚本里调用 ack-cli 开启;
    • 华为 CCE 的 Everest 插件会缓存镜像元数据,导致 Gatekeeper 拉取不到最新 CVE 数据,需在 Groovy 流水线里强制刷新镜像缓存。
  4. Gradle 插件化封装

    • 自定义 gatekeeper-plugin,task 包括:
      • gkRender:用 GroovyTemplateEngine 把 src/gatekeeper/*.groovy 渲染成 YAML;
      • gkDryRun:调用 opa test 做单元测试;
      • gkApply:通过 KubeHTTPClient(基于 Groovy HttpBuilder-NG)灰度发布到集群。

答案

以下示例演示“拒绝 latest 镜像 + 拒绝非公司 Harbor”双规则,全部用 Groovy 脚本一次性交付。

  1. 创建 ConstraintTemplate(deny-highrisk-image.tmpl.groovy)
@Grab('org.yaml:snakeyaml:1.33')
import groovy.json.JsonOutput
import org.yaml.snakeyaml.Yaml

def schema = [
  openAPIV3Schema: [
    type: 'object',
    properties: [
      allowedRegistries: [type: 'array', items: [type: 'string]],
      denyLatest      : [type: 'boolean']
    ]
  ]
]

def rego = '''
package k8s.highriskimage

violation[{"msg": msg}] {
  container := input.review.object.spec.containers[_]
  image := container.image
  denyLatest
  endswith(image, ":latest")
  msg := sprintf("容器 <%v> 使用 latest 镜像 <%v>,禁止部署", [container.name, image])
}

violation[{"msg": msg}] {
  container := input.review.object.spec.containers[_]
  image := container.image
  not startswith(image, concat("/", allowedRegistries[_]))
  msg := sprintf("镜像 <%v> 不在允许仓库列表 <%v> 中", [image, allowedRegistries])
}
'''.stripIndent()

def tpl = [
  apiVersion: 'templates.gatekeeper.sh/v1',
  kind      : 'ConstraintTemplate',
  metadata  : [name: 'denyhighriskimage'],
  spec      : [
    crd     : [spec: [names: [kind: 'DenyHighRiskImage'], validation: schema]],
    targets : [[
      target: 'admission.k8s.gatekeeper.sh',
      rego  : rego
    ]]
  ]
]

println new Yaml().dump(tpl)
  1. 创建 Constraint(deny-highrisk-image-constraint.groovy)
@Grab('org.yaml:snakeyaml:1.33')
import org.yaml.snakeyaml.Yaml

def constraint = [
  apiVersion: 'constraints.gatekeeper.sh/v1beta1',
  kind      : 'DenyHighRiskImage',
  metadata  : [name: 'no-highrisk-image'],
  spec      : [
    match: [
      kinds: [[apiGroups: [""], kinds: ["Pod"]]],
      namespaces: ["prod", "staging"]
    ],
    parameters: [
      allowedRegistries: ["harbor.company.cn", "registry.cn-hangzhou.aliyuncs.com/company"],
      denyLatest: true
    ]
  ]
]

println new Yaml().dump(constraint)
  1. Gradle 任务一键下发(build.gradle 片段)
task applyGatekeeper(type: JavaExec) {
  classpath = configurations.gatekeeper
  mainClass = 'gkclient.GroovyKubeClient'
  args = [
    file("$buildDir/resources/gatekeeper").absolutePath,
    System.getenv("KUBECONFIG") ?: "${System.getProperty('user.home')}/.kube/config"
  ]
}

其中 GroovyKubeClient 用 HttpBuilder-NG 调用 /apis/admissionregistration.k8s.io/v1/validatingwebhookconfigurations 做灰度发布,失败自动回滚。

  1. 验证
kubectl run test --image=nginx:latest -n prod
# 立即收到 Gatekeeper 拒绝事件:
# Error from server (Forbidden): admission webhook "validation.gatekeeper.sh" denied the request: [no-highrisk-image] 容器 <test> 使用 latest 镜像 <nginx:latest>,禁止部署

拓展思考

  1. 动态黑名单
    把工信部备案黑名单和公司安全部 CVE 数据库做成 ConfigMap,Groovy 定时任务每 10 分钟拉取一次,热更新 Constraint 参数,无需重启 Gatekeeper。

  2. 镜像签名验证
    在 Groovy 脚本里调用国产签名服务(如阿里云镜像签名或华为签名中心),把cosign 验证逻辑嵌入 rego,拒绝未签名的中间层镜像。

  3. 多集群灰度
    用 Groovy 的 @Parallel 注解同时向华北-华东-华南三个 ACK 集群下发策略,结合 Argo Rollout 做金丝雀发布,策略异常一键回滚。

  4. 性能调优
    对超大规模集群(>5k 节点),把 Gatekeeper audit-from-cache 打开,Groovy 脚本定期调用 prometheus API 抓取 gatekeeper_audit_duration_seconds 指标,动态调整 --operation=audit 的并发度,把 P99 延迟压到 200 ms 以内。

掌握以上思路,面试时既能展示Groovy 脚本化敏捷性,又能体现对国内云原生生态的深入落地经验,可拿到技术终面直通卡。