使用 Kyverno 约束制品晋升

功能概述

使用 Skopeo Copy 晋升制品介绍了如何在手动审批步骤之后,将制品从一个 registry 复制到另一个 registry,并将生产环境凭证保存在 Connector 中(在此设置),而不是 Secret 中。该页面可确保模板每次运行时都会经过审批。本指南新增了一组 Kyverno 策略,使模板成为持有生产环境凭证的唯一方式,从而确保无法跳过审批步骤;这些策略的另一个作用是减轻审批者的工作负担。 原本需要谨慎的审批者手动核实的所有事项——这是否属于经过审查的晋升流水线、复制操作是否从已批准的源拉取制品并以相同名称将其写入已批准的目标,以及审批者列表是否为约定的列表——现在都会在准入时自动检查,因此审批本身可以回归其应有的作用:确认意图,而不是逐行检查。

另一半价值在于检查发生的时机:违反晋升约定的请求会在任何操作开始之前就失败,而不是等待人工发现。下面通过一个示例具体说明这一点。不同的晋升操作需要不同的审批者,因此模板可以将其 approvers 作为 PipelineRun 参数接收——但如果仅这样做,启动运行的任何人都可以选择审批者,而审批机制要到很晚才会验证这些名称,即运行已经存在并停留在审批步骤时。因此,晋升页面会将审批者固定在 Pipeline 中。规则 5 可确保运行时表单的安全:传入未列出审批者的运行永远不会被创建;如果模板编辑以字面值或参数默认值的形式指定了约定列表以外的审批者,则会在有人尝试提交该编辑时立即被拒绝。

识别晋升操作的依据并非工具:skopeo-copy 是一个通用 Task,它可以镜像基础镜像并在测试 registry 之间移动制品,而这些操作都不属于晋升。识别依据来自晋升页面已经确立、本指南进一步明确的约定:生产环境 registry 只能通过一个 Connector 访问,并且挂载该 Connector 的运行必须来自某个晋升流水线模板。其他所有镜像复制操作都不受影响。什么算作晋升详细说明了这一约定。

Alauda DevOps Connectors 中的三个术语贯穿本页面的其余部分。Connector 是一个命名空间级对象,用于保存某个外部系统(此处为生产环境 registry)的凭证,并在不暴露凭证的情况下将其提供给工作负载。运行通过 connectors-csi 驱动程序借用该凭证:即一个 workspace(或 volume),其 csi.driver 为 connectors-csi,并通过属性指定 Connector。AccessPolicy 是一个可选对象,可将借用 Connector 的操作设为需要经过审批;本指南不要求使用该对象,谁可以审批说明了何时值得为其承担集群范围的成本。

这些防护措施由十一个相互独立、可组合使用的策略对象构成,每项防护措施对应一个对象。其中九个对象各包含一条规则;另外两个对象各包含一对需要作为一个整体移除或收紧的规则——规则 2 对应的一对规则(TaskRun 规则,以及其 Pod 级配套规则所依赖的 owner-reference 规则)和规则 5 对应的一对规则(同一审批者列表的运行端规则和模板端规则)。可以自由组合:应用所有规则,或者仅应用能够表达组织实际约束的规则。规则中分别解释并列出了每条规则,组合规则则说明了如何将选定的规则子集作为一个整体进行管理。

#规则可防止的情况
1promotion-runs-use-a-template持有生产环境凭证、但并非来自已审查晋升模板的运行:内联 pipelineSpec、其他 Pipeline、基于 resolver 的引用、其他命名空间中的运行、绑定到错误 workspace 的 Connector,或者重定向 registry 主机名解析目标或步骤执行内容的 pod 模板核心
2no-taskrun-outside-a-template使用生产环境凭证直接创建 TaskRun,从而绕过流水线及其审批步骤核心
3no-pod-outside-a-template任何挂载生产环境 Connector、但并非由 Tekton controller 为晋升模板运行创建的 Pod——手动编写的 Pod、Deployment、Job、任何其他 controller 的工作负载,或者在自身定义中声明该 volume 的 Tekton Task核心
4template-changes-by-maintainers-only任何非维护者编辑晋升 Pipeline——包括审批者、Task 引用或参数当模板位于命名空间中时为核心规则;对于通过 catalog 提供的模板则不需要
5promotion-approvers运行或模板编辑指定了命名空间允许列表之外的审批者可选
6sources-from-approved-registries从任意 registry 拉取未经审查的制品可选
7targets-in-approved-registries推送到未获批准的晋升目标 registry可选
8mapping-shape使用空或格式错误的映射来隐藏第二个复制操作可选
9target-path-matches-source将已批准的晋升操作变为重命名操作可选
10templates-expose-only-reviewed-inputs通过编辑模板扩大复制步骤的输入范围:srcImage、dstImages workspace、copy-mappings、skopeoImage、extraCopyArgs、之后添加的任何输入,或者可能使复制步骤不出现在这些列表中的内联 taskSpec可选
11sources-carry-release-tags晋升并非 release 的构建:latest、分支标签、日期标签或无标签引用——即未通过 digest 固定,也未使用已批准 release 格式添加标签的任何内容可选

“核心”规则确保该约定成立——如果缺少规则 1、2 和 3,就没有任何机制将凭证与经过审查的流水线关联起来,而且只需让操作完全不被识别为晋升,即可绕过所有其他规则。规则 1 和规则 2 检查 Tekton 的运行;规则 3 则构成其基础,检查每个请求最终都会生成的 Pod。每条可选规则都以核心规则为前提,并额外添加一项约束;不限制目标名称的团队只需省略规则 7,而模板来自受治理 catalog 的团队则可以省略规则 4。

Kyverno 判断的是请求中包含的内容,而不是 Task 最终如何处理这些内容。限制一节并非可选读物:如果对策略的信任超出其实际能力范围,结果比完全没有策略更糟。

使用场景

  • 减轻人工审查:审批者确认意图,而不是手动重新检查流水线身份、来源、目标和路径。
  • 在准入时拒绝指定约定列表之外审批者的运行,在运行创建之前——早于审批机制自身的检查。
  • 确保只有经过审查的晋升流水线能够持有生产环境 registry 凭证——没有手写运行、TaskRun 或 Pod,也没有其他工作负载。
  • 将晋升的来源和目标固定到已批准的 registry,并确保制品在进入生产环境的过程中保持其 repository 路径不变。
  • 仅采用组织实际拥有的约束,并按命名空间进一步收紧(收紧命名空间)。

什么算作晋升

策略只能约束其能够识别的内容,而晋升没有内在标记:同一个 skopeo-copy Task 使用相同参数时,写入生产环境就是晋升,写入其他位置则是常规镜像。因此,识别必须来自一种约定——晋升始终具备、而其他内容无法获得的特征。本指南使用生产环境凭证本身:

  1. 生产环境 registry 凭证只能作为 Connector 存在。 将其创建为 OCI 或 Harbor Connector——如下方的 <production-connector>——并且不要在任何流水线命名空间中保留生产环境 registry 的 kubernetes.io/dockerconfigjson Secret。运行通过 connectors-csi driver 挂载 Connector 来获得访问权限,这使挂载成为每个晋升都具备、而其他内容无法拥有的唯一属性——策略检查的正是声明该挂载的对象,无论它是 PipelineRun、TaskRun 还是裸 Pod。Pod 永远不会看到 registry 密码:挂载会提供一个 .env 文件,其 HTTPS_PROXY 指向 Connectors proxy,并携带运行的短期令牌;skopeo-copy 会加载该文件,而 proxy 在访问 registry 的过程中注入真实凭证。一旦这一约定成立——凭证不存在其他副本——就无法在不进行挂载的情况下推送到生产环境;限制说明了约定不成立时的情况。
  2. 审批位于模板中。 晋升 Pipeline 在复制前运行其 ApprovalTask,并在模板中列出审批者;手动审批门只接受来自这些身份的响应。结合第一个约定,这就是完整的门禁:运行只有挂载 Connector 才能到达生产环境,而——在下述规则生效后——只有模板的运行才能挂载 Connector,因此没有任何内容能够绕过模板的审批步骤到达生产环境。谁可以审批由模板中的列表决定,该列表由规则 4 和规则 5 保护——请参阅谁可以审批,其中还介绍了一个可选的 AccessPolicy 层,供希望 Connector 在记录审批前暂不提供凭证的团队使用。
  3. 晋升流水线是固定模板。 模板是经过审查的 Pipeline——晋升页面中的 promote-artifacts-with-approval 是其模型——它声明一个 dst-registry-config workspace,并且仅将 imageMappings 和 TLS 开关作为运行时输入;每个 PipelineRun 都会将 Connector 绑定到该 workspace。可以有多个模板,例如每种制品类型一个模板;它们可以位于晋升命名空间中,也可以来自受治理的 catalog。下述规则接受一个模板名称列表,规则 1 至规则 3 针对通过 catalog 解析的引用提供了相应变体。

因此,Kyverno 的职责明确而有限:挂载 <production-connector> 的请求必须属于这些模板之一,模板不得被篡改,并且提供给模板的输入必须描述一次合法的晋升。 未挂载 Connector 的运行完全不会被检查——按照该约定,它无法到达生产环境,因此没有需要约束的内容。

晋升页面会将 Secret 绑定到两个 workspace。要采用这一约定,只需将 PipelineRun 中的目标绑定替换为 Connector——这是唯一必须进行的更改;源端可以继续使用其 Secret,也可以使用自己的 Connector。Connector 可以位于晋升命名空间中,也可以从其他命名空间共享——项目级或集群级 Connector 同样引用为 namespace/name;哪些 Pod 可以挂载它,正是由规则 1、2 和 3 决定的。这是 PipelineRun 的 spec.workspaces 部分——快速检查包含了完全采用这种形式的完整运行示例,可以直接复制:

在此代码块中替换:<connector-namespace>、<connector-name>。

  workspaces:
    - name: src-registry-config
      secret:
        secretName: src-registry-config
    - name: dst-registry-config
      csi:
        driver: connectors-csi
        readOnly: true
        volumeAttributes:
          connector.namespace: <connector-namespace>
          connector.name: <connector-name>
          configuration.names: registry-config

通过 Connector 路由复制操作会带来以下两点。准入时检查无法展示这些内容——因为此时还不会启动 Pod;请参阅使用真实晋升运行进行检查中的检查。

  • 目标仍使用真实 registry 主机写入。 proxy 是透明的:imageMappings 按照使用 Secret 时的方式准确命名 <approved-target-registry>/team/app:1.2.3,而 <approved-target-registry> 只是 Connector 的 spec.address 的主机。skopeo-copy 会像往常一样报告推送后的 digest,并且该 digest 与源 digest 相同。
  • 复制操作两端都经过 proxy,但只有目标连接会重新签名。 .env 会为除 localhost 之外的每个主机设置 HTTPS_PROXY,因此源端拉取也会经过 proxy——但 proxy 仅会为与 Connector 自身地址匹配的 CONNECT 目标替换证书(包括主机和端口),并将其他每个主机原样通过隧道传输。因此,目标连接看到的是由 Connectors CA 签发的证书,而源连接仍然看到源 registry 自己的证书。晋升页面的模板通过将两个 CA workspace 都公开为可选项,并允许每次运行根据其跳转所需绑定相应内容,来保持验证开启:Connector 支持的运行会将 Task 的 dst-ca-bundle 绑定到该挂载,其 ca.crt 文件就是该 CA;当源 registry 使用私有 CA 时,src-ca-bundle 则会使用站点自己的 CA。规则 10 的 allowedCopyWorkspaces 列表已经包含这两个名称,因此采用该方式时无需重新审查任何内容。对于无法绑定挂载的模板,将 dstTLSVerify 设置为 "false" 是一种后备方案。策略不会约束 TLS 开关;请参阅限制。

规则能够识别 connectors-csi volume 中 Connector 的两种命名方式:上面的单 Connector 形式(connector.name,connector.namespace 默认为运行所在的命名空间)以及多 Connector 形式(connectors: ns-a/name-a,ns-b/name-b,在启用 enable-multi-connector feature flag 时可用)。规则会按照 driver 的方式规范化列表——删除条目两端的空格,丢弃空条目,并将不带限定的 name 解析到运行所在的命名空间——因此,带有多余空格或未限定命名空间的生产环境 Connector 拼写仍然可以被识别。其他命名空间中同名的 Connector 是不同的 Connector,不会匹配。

为什么不以 Task 作为锚点?因为 Task 是共享的。规定“每个 skopeo-copy 都必须遵守晋升规则”的规则会拒绝合法的镜像操作;更糟的是,任何绕过该 Task 的复制操作都能满足这一规则,因为没有其他内容能够将其识别为晋升。Connector 不存在这两个问题:它是实现该结果所必需的,并且不会用于其他用途。

晋升流水线中的定位

晋升旨在保证一件事:在生产环境中运行的,正是经过测试且未被更改的制品。按环境重新构建会失去这一保证——相同的源代码在之后的构建中可能解析出不同的基础层或依赖项——因此晋升采用复制而不是重新构建。

要端到端地执行这一保证,需要三个关卡。本指南实现的是中间关卡的准入部分;该关卡的审批部分是模板的 ApprovalTask,由晋升页面构建,谁可以审批则明确了谁可以作出回答。此处概述另外两个关卡,以便明确边界;它们各自都是独立的设计,采用下述策略并不要求实现这两个关卡。

关卡它回答的问题所在位置
1 · 发布此制品是否适合进行晋升?构建流水线
2 · 晋升是否可以执行这一次从此处到彼处的复制——以及谁对此表示同意?本指南
3 · 准入此制品是否可以在目标集群中运行?使用方集群

关卡 1——构建时的证据。 晋升决策的质量取决于对制品的了解程度。catalog 提供了这些组成部分:syft 生成 SBOM,trivy-scanner 生成漏洞判定,cosign 为镜像签名并附加证明。启用 Tekton Chains 且持有签名密钥时,它会为每次运行记录带签名的构建来源信息,而无需流水线发出请求——这是由集群运维人员一次性配置的平台级设置,不是晋升流水线启用的功能。因此,构建的输出不只是一个镜像,而是一个镜像以及一组描述该镜像的声明,之后可以由不信任该流水线的人员进行检查。

验证不必等到目标集群中再进行。要求“只晋升通过验证的内容”的成本最低的位置,是晋升流水线自身中的一个 Task,位于复制之前:可以是 cosign 验证步骤,也可以是扫描判定;当制品不符合要求时,该步骤会使运行失败。这样,审批步骤批准的就是已经完成检查的内容。由于模板受到此策略保护,启动运行的人员无法移除这样的步骤。

关卡 3——使用点的验证。 关卡 1 和关卡 2 约束的是晋升路径。它们都无法约束通过其他方式获得镜像的工作负载。要弥补这一点,需要使用方集群自行验证制品——Kyverno 可以在 Pod 准入前要求有效的签名或证明。这会将晋升路径从约定转变为技术约束:跳过该路径的镜像无法运行。该机制依赖关卡 1 确实执行签名,也依赖该集群中的 Kyverno 能够访问存储签名的 registry——在据此进行规划之前,请先验证这种可达性,因为无法读取 registry 的策略会默认拒绝并拒绝所有内容。

按 digest 晋升,并一并复制签名。 标签在获得批准后仍可重新指向其他内容,而 digest 不会。因此,下方的 parity 规则会比较 repository 路径,基于标签的映射仍然可用;但在映射两端都传递 repo@sha256:…,就能将“制品未被更改”从一种假设变为策略强制执行的要求。skopeo-copy 已经以 repo@sha256:… 形式报告每个目标,原因正在于此。

签名和证明不会自动随镜像一同传输——它们是独立的对象,以从镜像 digest 派生的标签存储在同一 repository 中(sha256-<digest>.sig、sha256-<digest>.att)。因此,晋升它们只需在同一个 imageMappings 列表中添加更多映射;下方的规则允许这些映射通过:两端的 repository 路径相同,只有标签不同。以下两个细节可以确保其在实际使用中正常工作:

  • 保留默认的 multiArch: all。复制完整的 manifest list 会保留 digest,因此,针对该 digest 创建的签名在目标端仍然有效。选择单个架构,或使用 dstImageFormat 转换 manifest,都会产生不同的 digest——针对旧 digest 的每个签名和证明都将不再匹配。
  • 晋升运行自身也会获得来源信息。skopeo-copy 以 Tekton Chains 使用的形式报告其目标,因此,在 Chains 配置了签名密钥的情况下,晋升本身也会获得证明——这是对此次复制的记录,与上述映射中携带过来的构建来源信息不同。

前提条件

  • 使用 Skopeo Copy 晋升制品中的晋升流水线已就绪,并且目标 workspace 已按照将生产凭证保存在 Connector 中所示绑定到 Connector。
  • Alauda DevOps Connectors 已安装,并且生产 registry 存在 OCI 或 Harbor Connector——位于晋升 namespace 中,或在项目级别或集群级别共享。不需要启用任何 Connectors 功能标志;谁可以审批中的可选 AccessPolicy 层是唯一需要功能标志的部分。
  • Kyverno 已安装,并且其所有控制器均已就绪。在 ACP 上,它由 Compliance Management 插件提供。
  • 你可以创建集群范围的 ClusterPolicy 对象——这些规则之所以采用集群范围,是因为无论由谁创建运行都必须适用,也因为 Connector 可以从任意 namespace 挂载。
  • kubectl 可以访问运行 Tekton 和 Kyverno 的集群。本指南中的每条命令都针对该集群运行。

在检查 Kyverno 之前,先定位其安装位置——namespace 是安装时的选择,并非固定名称:

# Kyverno registers its resource webhook under a fixed name; read the namespace from it.
KYVERNO_NS="$(kubectl get validatingwebhookconfiguration kyverno-resource-validating-webhook-cfg \
  -o jsonpath='{.webhooks[0].clientConfig.service.namespace}')"
echo "${KYVERNO_NS:?no Kyverno webhook found - is Kyverno installed?}"

kubectl get pods -n "${KYVERNO_NS}"
# Expect the admission, background, cleanup and reports controllers Running and Ready.

Pod 就绪是前提条件,但不能证明准入服务正在提供服务——下文的 dry-run 检查才是实际的证明。请注意这些策略选择的故障方向:借助它们声明的 fail-closed webhook,不可用的准入控制器不会悄悄停止执行策略,而是拒绝所有匹配的请求,从而完全停止晋升。

要替换的占位符

应用策略之前,请替换每一个出现位置。过期的占位符不会明确报错:它只会悄悄改变匹配的请求,或改变受信任的 registry。

占位符含义如何检查值
<pipeline-namespace>创建晋升运行的 namespace——也可以有多个:每个列出该 namespace 的列表和前置条件都需要为每个 namespace 添加一项。模板位于其中;或者,对于规则 1 至 3 的 catalog 变体,模板由 catalog 提供;任何其他位置的运行只要挂载了 Connector 都会被拒绝。kubectl get pipeline -A,限定在存放晋升模板的位置;使用 catalog 提供的模板时,则填写创建晋升运行的 namespace
<production-connector>生产 registry Connector,填写为 namespace/name:集群级别 Connector 填写 kube-public/prod-harbor,namespace 级别 Connector 填写 devops-prod/prod-harbor。此处的 kube-public 仅表示 Connector 对象所在的位置——即产品用于存放集群级别 Connector 的共享 namespace——绝不表示晋升工作负载运行的位置:Kyverno 的默认资源过滤器会排除该 namespace,因此在那里创建的任何内容都不会被评估——参见限制。kubectl get connectors -A
<promotion-pipeline>晋升 Pipeline 模板的名称,在晋升页面上填写 promote-artifacts-with-approval。它出现的每个列表都可以接受多个条目——每个模板添加一行,并确保所部署规则中的列表保持一致。kubectl get pipeline -n <pipeline-namespace>
<approved-source-registry>制品可以从中晋升的主机,registry 监听端口时需同时包含端口:dev-registry.example.com、registry.example.com:5000。规则 6 在一个条件中以通配符模式列出获准主机——每增加一个主机就添加一项。构建流水线使用的源主机
<approved-target-registry>制品可以晋升到的主机,registry 监听端口时需同时包含端口,例如 prod-registry.example.com。目标直接命名 registry;Connector 代理是透明的。规则 7 以相同方式列出目标——每个获准主机添加一个模式条目。Connector 的 spec.address 主机:kubectl get connector <connector-name> -n <connector-namespace> -o jsonpath='{.spec.address}'
<approved-source-tag-pattern>仅适用于规则 11:源标签必须匹配的正则表达式,计为发布版本;每个模式添加一项。规则 11下方列出了两种模式:严格的 v?major.minor.patch 格式,仅允许 1.2.3 和 v1.2.3;以及默认的 semver.org 语法,带可选的 v 前缀,同时允许 1.2.3-rc.1 和 1.2.3+build.5;两者都不允许 latest、01.2.3、dev-20260902 或分支名称(例如 2026.10.12 这样的点分日期是有效的 semantic version,会通过默认模式——如果这一点很重要,请在自己的模式中要求 v 前缀)。cosign 伴随标签条目在两种模式下都要保留在列表中。固定 digest 的源无需标签。你的发布标签约定;skopeo list-tags docker://<registry>/<repository> 会显示 repository 携带的内容
<allowed-approver>允许在 namespace 中审批晋升的身份,按照 ApprovalTask 预期的方式填写:用户名,或带有 group: 前缀的组。每个身份添加一行。模板中的 approvers,以及 AccessPolicy 所指定的身份——参见谁可以审批
<tekton-controller-identity>Tekton 创建 TaskRun 及其 Pod 时使用的身份,填写为 system:serviceaccount:<tekton-namespace>:tekton-pipelines-controller。kubectl get deploy -A -l app.kubernetes.io/name=controller,app.kubernetes.io/part-of=tekton-pipelines -o jsonpath='{range .items[*]}system:serviceaccount:{.metadata.namespace}:{.spec.template.spec.serviceAccountName}{"\n"}{end}'
<template-maintainer>允许更改晋升 Pipeline 的身份。由团队维护时,请列出多个条目。kubectl auth whoami 会显示当前凭证的身份
<catalog-name>仅适用于规则 1、2 和 3 的 catalog 变体:受信任的、通过 hub resolver 提供晋升模板的 catalog。模板 catalog 中的值,以及晋升页面上的 taskRef、catalog

阅读此表时请注意以下三点:

  • <connector-namespace> 和 <connector-name> 在 PipelineRun 示例中是 <production-connector> 的两个组成部分:使用 devops-prod/prod-harbor 时,Connector 会挂载为 connector.namespace: devops-prod 和 connector.name: prod-harbor。
  • 此表列出了需要替换的每个字符串。不在表中的尖括号字符串是其出现位置专用的表示法,应保持不变:<tekton-namespace> 位于 <tekton-controller-identity> 的现成值中(检查命令会打印完整身份,无需手动填写任何内容),<digest> 描述签名标签模式 sha256-<digest>.sig,而脚本的注释和 jq 表达式则使用各自的尖括号表示法。
  • workspace 名称 dst-registry-config 和 dst-ca-bundle 是字面值而非占位符,因为晋升模板以这些名称声明了它们。如果模板为目标 workspace 或其 CA workspace 使用了不同名称,请相应修改 promotion-runs-use-a-template 中的名称。

规则

以下每条规则都是一个完整、独立的策略对象。这些 YAML 块并不是某个大型策略的一部分:其中任何一个都可以单独保存和应用。全部 11 条规则都带有标签 app.kubernetes.io/part-of: promotion-guardrails,这正是组合规则将你选择的任意子集作为一个单元运行的方式。

本指南中的每个对象都是集群范围的 ClusterPolicy——演示集合就是平台的基线。Kyverno 还提供命名空间范围的 Policy 类型,使用相同的规则语法;团队可以通过它在自己的 namespace 中收紧基线,而不需要集群范围的权限。收紧 namespace对此进行了介绍,并链接到一个完整的参考示例。

每条检查运行的规则都会在其 context 中携带相同的识别前导部分:即什么算作晋升中所述的 connectors-csi 扫描,以 mountsProductionConnector 前置条件结束。它会在每个对象中逐字重复——这是策略可以独立应用所付出的代价——因此,当你更改 Connector 的识别方式时,请在所部署的每条规则中都进行修改。

如何证明已部署的规则集会按照描述运行,而不持久化任何内容,是整个规则集共用的一套操作步骤,详见应用和验证。

规则 1:持有生产凭证的运行必须是模板

promotion-runs-use-a-template 会匹配集群上每个 PipelineRun 的创建请求,但其前置条件会使它保持静默,除非某个 connectors-csi 卷命名为 <production-connector>。该规则会检查此类卷可能声明的所有位置——workspace 绑定、Pod 模板(taskRunTemplate、taskRunSpecs),以及任何内联 taskSpec 的 volumes——因此,将 Connector 作为原始卷而不是 workspace 挂载,也会以同样方式被识别。 一旦发现这种情况,运行必须在 <pipeline-namespace> 中创建,并引用 templateNames 中的一个——在下面的基础规则中按本地名称引用;当模板由 catalog 提供时,则使用固定的 hub-resolver 形式(策略之后的来自 catalog 的模板)——绝不能使用内联 pipelineSpec,并且只能将 Connector 作为 dst-registry-config workspace 绑定:任何其他 workspace,以及任何命名该 Connector 的 Pod 模板卷或内联 Task 卷,都会被拒绝。它接受的另一个 workspace 名称是 dst-ca-bundle;Connector 支持的运行会将该 workspace 绑定到完全相同的挂载点,使目标 CA 成为该挂载点自身的 ca.crt——即同一 Pod 中、同一个经审查的 Task 里的相同文件,因此不会暴露凭证绑定之外的任何内容。任何其他持有该凭证的内容都会在启动前被拒绝,无论它打算用该凭证做什么。

workspace 检查很重要,因为模板的源 workspace 同样是凭证挂载点:如果将生产 Connector 绑定到那里,运行就可以读取生产环境,而晋升从来不需要这样做。

还有两个细节可以堵住审查者可能发现的漏洞。该规则还会拒绝携带 hostAliases、dnsConfig、dnsPolicy、hostNetwork 或 env 的 taskRunTemplate.podTemplate 或 taskRunSpecs[].podTemplate。这些字段单独使用时没有问题——不挂载 Connector 的运行仍可完整使用它们——但它们与已挂载的凭证结合后,会改变运行对凭证的使用方式:前四项会改变代理和 registry 主机名的解析位置,因此,一个命名获准目标(并通过规则 6 和 7)的 mapping,可以被操纵为在 pod 模板将该名称指向的任意地址登录——并出示生产凭证;env 可以重写 PATH,使 workspace 中植入的二进制替代 skopeo 运行,而凭证就挂载在其旁边。之所以检查这些键,而不是检查是否存在 Pod 模板,是因为 Tekton 会在该策略看到每个运行之前,将其配置的默认 Pod 模板(ACP 上为 securityContext)注入每个运行中。所有 Tekton 类型也只会作为 tekton.dev/v1/... 进行匹配,尽管 Tekton 会同时提供 v1beta1 和 v1:Kyverno 为仅包含 v1 规则生成的 webhook 会注册 matchPolicy: Equivalent,因此 API server 会在 Kyverno 看到请求之前,将 v1beta1 请求转换为 v1——顶层的 podTemplate 会变成 taskRunTemplate.podTemplate,taskRunSpecs[].taskPodTemplate 会变成 taskRunSpecs[].podTemplate——而该规则只读取 v1 字段名称。不要为了“安全起见”将 v1beta1 添加到 kinds:这样也会注册该版本,转换会停止,之后每个重命名字段都必须手动按两种拼写读取。要证明转换在你的集群上有效,请提交一个挂载 Connector 的 v1beta1 运行,并将其作为 server dry run 执行:规则 1 会按名称拒绝它。

完整策略 YAML —

promotion-runs-use-a-template(可直接复制粘贴)

请在此块中替换:<promotion-pipeline>、<production-connector>、<pipeline-namespace>。

# Rule 1: a run that mounts the production registry Connector must be one of the promotion templates.
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: promotion-runs-use-a-template
  labels:
    app.kubernetes.io/part-of: promotion-guardrails
spec:
  admission: true
  background: false
  webhookConfiguration:
    failurePolicy: Fail
  rules:
    - name: promotion-runs-use-a-template
      match:
        any:
          - resources:
              kinds:
                - tekton.dev/v1/PipelineRun
              operations:
                - CREATE
      context:
        # The approved promotion templates: add one entry per template.
        - name: templateNames
          variable:
            value:
              - <promotion-pipeline>
        # Every place a connectors-csi volume can be declared on a run: workspace bindings, pod
        # templates (spec.podTemplate on a TaskRun, taskRunTemplate and taskRunSpecs on a
        # PipelineRun -- one list serves both kinds), and the volumes of an inline Task spec.
        - name: csiVolumes
          variable:
            jmesPath: "[request.object.spec.workspaces, request.object.spec.podTemplate.volumes, request.object.spec.taskRunTemplate.podTemplate.volumes, (request.object.spec.taskRunSpecs || `[]`)[].podTemplate.volumes, request.object.spec.taskSpec.volumes, (request.object.spec.pipelineSpec.tasks || `[]`)[].taskSpec.volumes, (request.object.spec.pipelineSpec.finally || `[]`)[].taskSpec.volumes] | [] | [?@ != null] | []"
        - name: csiAttrs
          variable:
            jmesPath: "csiVolumes[?csi.driver=='connectors-csi'].csi.volumeAttributes"
        # Single-Connector form: connector.name plus an optional connector.namespace.
        - name: singleRefs
          variable:
            jmesPath: "csiAttrs[?\"connector.name\" != null].join('/', [\"connector.namespace\" || '{{request.namespace}}', \"connector.name\"])"
        # Multi-Connector form: a comma-separated list of namespace/name references.
        - name: rawPluralRefs
          variable:
            jmesPath: "csiAttrs[?connectors != null].connectors | join(',', @) | split(@, ',')"
        # The driver trims whitespace around each entry, drops empty entries, and resolves a
        # bare "name" in the run's namespace; mirror that before comparing, or a padded or
        # unqualified spelling of the production Connector escapes detection.
        - name: pluralRefs
          variable:
            jmesPath: "rawPluralRefs | map(&trim(@, ' \t\n\r'), @) | [?@ != ''] | map(&(contains(@, '/') && @ || join('/', ['{{request.namespace}}', @])), @)"
        - name: connectorRefs
          variable:
            jmesPath: "[singleRefs, pluralRefs] | [] | [?@ != '']"
        - name: mountsProductionConnector
          variable:
            jmesPath: "contains(connectorRefs, '<production-connector>')"
        - name: pipelineName
          variable:
            jmesPath: "request.object.spec.pipelineRef.name || ''"
            default: ""
        - name: pipelineResolver
          variable:
            jmesPath: "request.object.spec.pipelineRef.resolver || ''"
            default: ""
        - name: hasInlineSpec
          variable:
            jmesPath: "request.object.spec.pipelineSpec != null"
        # A plain by-name reference to one of the approved templates. An inline pipelineSpec has
        # no name and a resolver reference has no local name, so both fail this test.
        - name: refIsApprovedTemplate
          variable:
            jmesPath: "pipelineResolver == '' && contains(templateNames, pipelineName)"
        # Pod template keys that change where the Connector proxy hostname resolves, or what
        # the step executes (env can rewrite PATH). Tekton injects its default pod template
        # (securityContext) before this policy runs, so the check is per key, not "any podTemplate".
        - name: podTemplateKeys
          variable:
            jmesPath: "[keys(request.object.spec.taskRunTemplate.podTemplate || `{}`), (request.object.spec.taskRunSpecs || `[]`)[].podTemplate | [?@ != null] | map(&keys(@), @) | []] | []"
        - name: networkOverrides
          variable:
            jmesPath: "podTemplateKeys[?contains(`[\"hostAliases\", \"dnsConfig\", \"dnsPolicy\", \"hostNetwork\", \"env\"]`, @)]"
        # The Connector may be bound to two workspaces of the template: dst-registry-config,
        # the credential, and dst-ca-bundle, where a Connector-backed run binds the same mount
        # again so the destination CA is the mount's own ca.crt. That second binding is the same
        # mount, in the same Pod, of the same reviewed Task -- the same files -- so it exposes
        # nothing dst-registry-config does not already expose. Any other workspace, and any pod
        # template or inline Task volume, still counts as misbound.
        - name: misboundAttrs
          variable:
            jmesPath: "[(request.object.spec.workspaces || `[]`)[?name!='dst-registry-config' && name!='dst-ca-bundle'], request.object.spec.taskRunTemplate.podTemplate.volumes, (request.object.spec.taskRunSpecs || `[]`)[].podTemplate.volumes, (request.object.spec.pipelineSpec.tasks || `[]`)[].taskSpec.volumes, (request.object.spec.pipelineSpec.finally || `[]`)[].taskSpec.volumes] | [] | [?@ != null] | [] | [?csi.driver=='connectors-csi'].csi.volumeAttributes"
        - name: rawMisboundRefs
          variable:
            jmesPath: "[misboundAttrs[?\"connector.name\" != null].join('/', [\"connector.namespace\" || '{{request.namespace}}', \"connector.name\"]), misboundAttrs[?connectors != null].connectors | join(',', @) | split(@, ',')] | [] | [?@ != '']"
        # Normalized exactly like pluralRefs, or a padded or bare spelling on the wrong
        # workspace would escape the misbound check while the driver still mounts it.
        - name: misboundRefs
          variable:
            jmesPath: "rawMisboundRefs | map(&trim(@, ' \t\n\r'), @) | [?@ != ''] | map(&(contains(@, '/') && @ || join('/', ['{{request.namespace}}', @])), @)"
      preconditions:
        all:
          - key: "{{ mountsProductionConnector }}"
            operator: Equals
            value: true
      validate:
        failureAction: Enforce
        message: >-
          This run mounts the production registry Connector <production-connector>, so it must
          be a promotion: created in <pipeline-namespace>, referencing an approved promotion
          template by name — no resolver, no inline pipelineSpec — with no hostAliases/dnsConfig/
          dnsPolicy/hostNetwork/env in any pod template, and the Connector bound only to the
          dst-registry-config and dst-ca-bundle workspaces. got namespace={{ request.namespace }}
          pipelineRef.name={{ pipelineName }} resolver={{ pipelineResolver }}
          inlineSpec={{ hasInlineSpec }} networkOverrides={{ networkOverrides }}
          misbound={{ misboundRefs }}.
        deny:
          conditions:
            any:
              # One entry per namespace promotion runs are created in.
              - key: "{{ request.namespace }}"
                operator: AnyNotIn
                value:
                  - <pipeline-namespace>
              - key: "{{ refIsApprovedTemplate }}"
                operator: Equals
                value: false
              # Refused even next to a valid ref: Tekton rejects the combination too, but the
              # rule does not lean on that webhook being deployed and healthy.
              - key: "{{ hasInlineSpec }}"
                operator: Equals
                value: true
              - key: "{{ length(networkOverrides) }}"
                operator: GreaterThan
                value: 0
              - key: "{{ contains(misboundRefs, '<production-connector>') }}"
                operator: Equals
                value: true

来自 catalog 的模板

当模板由内部 hub 从受治理的 catalog 提供,而不是作为 namespace 中的 Pipeline 对象创建时,运行会通过 hub resolver 引用模板——基础规则会拒绝这种引用,因为 resolver 引用不是本地名称。若要同时接受 hub 引用——将其固定到受信任的 catalog、pipeline 类型以及同一个 templateNames 列表中的名称,并且特意不比较 version 参数,以接受 catalog 以该名称提供的任何版本(限制下的 catalog 条目对此进行了权衡)——请编辑上面的折叠策略:在规则的 context 列表中,将唯一的 refIsApprovedTemplate 条目替换为下面的七个条目(所需的六个 ref* 变量必须先出现,并且顺序完全一致)。这样,信任就建立在 catalog 自身的治理机制上,而不是规则 4 上。两个条目用于堵住这样一种路径:hub 引用在保留获准坐标的同时,被指向另一个 hub。hub resolver 接受请求级别的 url 参数,该参数会替换集群配置的 hub endpoint;还接受 type 参数,将其切换到 Tekton Hub endpoint 集合——无论使用哪一个,同一个 catalog 和名称都会解析到另一个 hub 提供的内容。此变体会拒绝任何 url,并且仅在 type 被省略或为 artifact 时接受它。只有当集群的 hub resolver 默认使用 artifact 时,省略 type 才是安全的;请确认一次,并让每个模板引用在未指定时都写入 type: artifact:

# The resolvers' ConfigMaps live in the namespace the operator installs Tekton into.
NS="$(kubectl get tektonconfig config -o jsonpath='{.spec.targetNamespace}')"
T="$(kubectl get configmap hubresolver-config -n "$NS" -o jsonpath='{.data.default-type}')"
[ "$T" = artifact ] || { echo "hub resolver default-type is '$T', not artifact"; exit 1; }

该变体仍然信任的是集群配置的 hub endpoint 本身:任何能够更改 hubresolver-config 的人,都可以改变固定名称解析到的内容,因此该平台配置应像 ClusterPolicy 一样受到控制——参见限制。

请在此块中替换:<catalog-name>。

        - name: refParams
          variable:
            jmesPath: "(request.object.spec.pipelineRef.params || `[]`)"
        - name: refCatalog
          variable:
            jmesPath: "refParams[?name=='catalog'].value | [0] || ''"
        - name: refKind
          variable:
            jmesPath: "refParams[?name=='kind'].value | [0] || ''"
        - name: refTemplateName
          variable:
            jmesPath: "refParams[?name=='name'].value | [0] || ''"
        # A request-level url replaces the cluster-configured hub endpoint, and a type other than
        # artifact switches to the Tekton Hub endpoints: the same coordinates would then resolve
        # on another hub. Refuse url; accept type only omitted or as a single 'artifact'.
        - name: refUrlCount
          variable:
            jmesPath: "length(refParams[?name=='url'])"
        - name: refTypeIsArtifact
          variable:
            jmesPath: "length(refParams[?name=='type']) == `0` || (length(refParams[?name=='type']) == `1` && (refParams[?name=='type'].value | [0]) == 'artifact')"
        # A by-name reference to an approved template, or a hub-resolver reference to an
        # approved template in the trusted catalog, on the cluster-configured hub.
        - name: refIsApprovedTemplate
          variable:
            jmesPath: "(pipelineResolver == '' && contains(templateNames, pipelineName)) || (pipelineResolver == 'hub' && refUrlCount == `0` && refTypeIsArtifact && refCatalog == '<catalog-name>' && refKind == 'pipeline' && contains(templateNames, refTemplateName))"

使用 server dry run 按照检查基础规则的相同方式检查此变体:引用中携带 url 参数的运行,或其 type 不是 artifact 的运行,会按名称被拒绝;而对获准模板的普通引用会被接受。在安装了规则 2 和 3 的父级测试后,规则 2 和 3 的父级链也同样适用。

规则 2:TaskRun 不得位于模板之外

Tekton 会自行创建 PipelineRun 的 TaskRun,创建为 <tekton-controller-identity>,并为每个对象添加其所属 PipelineRun 的标签。任何有权创建 TaskRun 的人,都可以手动编写一个对象,挂载 Connector,从而跳过流水线及其审批步骤。no-taskrun-outside-a-template 会堵住这条路径:挂载 <production-connector> 的 TaskRun——无论是作为 workspace、Pod 模板卷,还是内联 taskSpec 的卷——都必须由 Tekton controller 在 <pipeline-namespace> 中创建,并且属于一个按名称引用这些模板之一的 PipelineRun。

最后一个条件会针对父级运行本身进行检查,该运行通过 TaskRun 的控制 ownerReference到达,而不是通过标签到达。规则会读取 ownerReferences 条目中由 controller: true 指定的 PipelineRun,通过 Kyverno API 调用查找它,并应用规则 1 对运行执行的相同检查:按名称引用获准模板、没有 resolver、没有内联 pipelineSpec。owner reference 是规则 2 的第二条规则为 Tekton controller 保留的父级指针;controller 会根据它正在协调的运行写入该指针:手写的 TaskRun 可能携带该指针,但除非由 controller 写入,否则会被拒绝。相比之下,子对象上的每个 tekton.dev/* 标签都可以由运行作者自由设置——taskRunSpecs[].metadata.labels 会先被复制到 TaskRun 上,并覆盖 controller 自身的值,因此运行可以携带一个命名另一个运行的 tekton.dev/pipelineRun 标签;当流水线为内联时,tekton.dev/pipeline 则根据运行的名称派生。我们已验证:一个以内联方式创建、以模板命名的运行,引用一个在自身定义中声明 Connector 卷的 Task,可以在每个对象上绕过基于标签的检查。只有对挂载 Connector 的 TaskRun 才会执行查找——Kyverno 会在前置条件之后首次使用时加载 context 条目;将该调用指向一个不存在的路径并观察普通请求仍被接受,已经证实了这一点——因此,它不会对不符合该约定的运行增加任何影响。admission controller 需要拥有列出 PipelineRun 的权限;在 ACP 上它已经具备该权限。

owner reference 的可信度取决于其写入者,手动编写的 TaskRun 同样可以携带一个 owner reference。这对上面的规则没有影响——手写的 TaskRun 无论如何都会因创建者检查失败——但对规则 3很重要,因为规则 3 会通过 Pod 的 TaskRun 访问父级:一个自身不挂载任何内容、引用声明了 Connector 卷的 Task,并伪造指向真实晋升运行的 owner reference 的 TaskRun,会将一个 owner 链看似合法的 Pod 交给 controller。因此,该对象携带第二条规则 taskrun-owner-references-set-by-the-controller:在 <pipeline-namespace> 中,任何新增控制 PipelineRun owner reference 的 TaskRun——无论是在创建时新增,还是通过更新新增——都必须由 Tekton controller 创建或更新。它没有 Connector 前置条件,因为正是它让 namespace 中每个 TaskRun 的 owner reference 都具有其所声明的含义;代价是每个 TaskRun 请求都要比较两个简短列表。比较针对的是整个引用——连接后的 apiVersion、kind、name 和 uid——而不只是 uid,因此更改已有引用的任何字段都会被视为新增引用。由于规则 2 和 3 按名称获取父级运行,它们还要求找到的运行携带该引用所命名的 uid:将引用重命名为另一个运行后,它将不再指向任何对象。删除 owner reference 的操作不受干预(运行成为孤立对象时由垃圾回收器处理),controller 自身的标签和 annotation 更新也不受干预。

TaskRun 并不是声明挂载的最后一个位置:手动编写的 Pod,或由 Tekton 之外的任何 controller 生成的 Pod,都不会经过此规则;而在自身定义中声明该卷的 Task 只会在 Pod 上显露该挂载,因为引用它的 TaskRun 不携带卷。规则 3覆盖这些情况;请将两条规则一起部署。由 catalog 提供的模板需要以与规则 1 相同的方式扩展父级检查——下面的规则 2 和 3 的父级测试同时适用于这两条规则。

完整策略 YAML —

no-taskrun-outside-a-template(可直接复制粘贴)

请在此块中替换:<promotion-pipeline>、<production-connector>、<pipeline-namespace>、<tekton-controller-identity>。

# Rule 2: a TaskRun that mounts the Connector must have been created by Tekton for a PipelineRun of a template.
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: no-taskrun-outside-a-template
  labels:
    app.kubernetes.io/part-of: promotion-guardrails
spec:
  admission: true
  background: false
  webhookConfiguration:
    failurePolicy: Fail
  rules:
    - name: no-taskrun-outside-a-template
      match:
        any:
          - resources:
              kinds:
                - tekton.dev/v1/TaskRun
              operations:
                - CREATE
      context:
        # The approved promotion templates: keep this list in step with rules 1 and 3.
        - name: templateNames
          variable:
            value:
              - <promotion-pipeline>
        # Every place a connectors-csi volume can be declared on a run: workspace bindings, pod
        # templates (spec.podTemplate on a TaskRun, taskRunTemplate and taskRunSpecs on a
        # PipelineRun -- one list serves both kinds), and the volumes of an inline Task spec.
        - name: csiVolumes
          variable:
            jmesPath: "[request.object.spec.workspaces, request.object.spec.podTemplate.volumes, request.object.spec.taskRunTemplate.podTemplate.volumes, (request.object.spec.taskRunSpecs || `[]`)[].podTemplate.volumes, request.object.spec.taskSpec.volumes, (request.object.spec.pipelineSpec.tasks || `[]`)[].taskSpec.volumes, (request.object.spec.pipelineSpec.finally || `[]`)[].taskSpec.volumes] | [] | [?@ != null] | []"
        - name: csiAttrs
          variable:
            jmesPath: "csiVolumes[?csi.driver=='connectors-csi'].csi.volumeAttributes"
        - name: singleRefs
          variable:
            jmesPath: "csiAttrs[?\"connector.name\" != null].join('/', [\"connector.namespace\" || '{{request.namespace}}', \"connector.name\"])"
        - name: rawPluralRefs
          variable:
            jmesPath: "csiAttrs[?connectors != null].connectors | join(',', @) | split(@, ',')"
        # The driver trims whitespace around each entry, drops empty entries, and resolves a
        # bare "name" in the run's namespace; mirror that before comparing, or a padded or
        # unqualified spelling of the production Connector escapes detection.
        - name: pluralRefs
          variable:
            jmesPath: "rawPluralRefs | map(&trim(@, ' \t\n\r'), @) | [?@ != ''] | map(&(contains(@, '/') && @ || join('/', ['{{request.namespace}}', @])), @)"
        - name: connectorRefs
          variable:
            jmesPath: "[singleRefs, pluralRefs] | [] | [?@ != '']"
        - name: mountsProductionConnector
          variable:
            jmesPath: "contains(connectorRefs, '<production-connector>')"
        # The parent PipelineRun, from the controlling ownerReference the Tekton controller
        # writes on every TaskRun of a run (Kubernetes allows one controller reference per
        # object). Not the tekton.dev/pipelineRun label: taskRunSpecs[].metadata.labels
        # overrides it, so a run's author can make the controller stamp any run's name.
        - name: runName
          variable:
            jmesPath: "(request.object.metadata.ownerReferences || `[]`)[?controller == `true` && kind == 'PipelineRun'].name | [0] || ''"
            default: ""
        # The uid of that same reference: the parent is looked up by name, and the uid is what
        # proves the object found under that name is the one the reference points at.
        - name: runUid
          variable:
            jmesPath: "(request.object.metadata.ownerReferences || `[]`)[?controller == `true` && kind == 'PipelineRun'].uid | [0] || ''"
            default: ""
        # Read the parent run back. A list query with a name selector returns an empty list --
        # not an error -- when the reference is missing or names a run that does not exist.
        - name: parentRuns
          apiCall:
            urlPath: "/apis/tekton.dev/v1/namespaces/{{request.namespace}}/pipelineruns?fieldSelector=metadata.name={{runName}}"
            jmesPath: "items || `[]`"
        - name: parentRef
          variable:
            jmesPath: "parentRuns[0].spec.pipelineRef || `{}`"
        # The same test rule 1 applies to a run: a by-name reference to an approved template, no
        # resolver, no inline pipelineSpec. The uid comparison keeps the lookup honest: the run
        # fetched by name must be the object the owner reference points at, so a reference whose
        # name was changed to another run resolves to no parent. Catalog-served templates:
        # replace this entry with the seven under "Catalog-served templates: the parent test for
        # rules 2 and 3" (under rule 2 in the guide).
        - name: parentIsApprovedTemplate
          variable:
            jmesPath: "length(parentRuns) == `1` && parentRuns[0].metadata.uid == runUid && (parentRef.resolver || '') == '' && contains(templateNames, parentRef.name || '') && parentRuns[0].spec.pipelineSpec == null"
      preconditions:
        all:
          - key: "{{ mountsProductionConnector }}"
            operator: Equals
            value: true
      validate:
        failureAction: Enforce
        message: >-
          A TaskRun that mounts the production registry Connector <production-connector> may only
          be created by the Tekton controller for a PipelineRun in <pipeline-namespace> that references an
          approved promotion template. got namespace={{ request.namespace }}
          creator={{ request.userInfo.username }} owner pipelineRun={{ runName }} parentRef={{ parentRef }}.
        deny:
          conditions:
            any:
              # One entry per namespace promotion runs are created in.
              - key: "{{ request.namespace }}"
                operator: AnyNotIn
                value:
                  - <pipeline-namespace>
              - key: "{{ request.userInfo.username }}"
                operator: NotEquals
                value: <tekton-controller-identity>
              - key: "{{ parentIsApprovedTemplate }}"
                operator: Equals
                value: false
    # 2b: a controlling PipelineRun ownerReference on a TaskRun is written by the Tekton
    # controller, never by a requester. Rule 3 walks a Pod's owner chain and relies on this.
    - name: taskrun-owner-references-set-by-the-controller
      match:
        any:
          - resources:
              kinds:
                - tekton.dev/v1/TaskRun
              operations:
                - CREATE
                - UPDATE
              # One entry per namespace promotion runs are created in.
              namespaces:
                - <pipeline-namespace>
      context:
        # The whole reference, not the uid alone: a rename that keeps the uid must count as a
        # change too, because rules 2 and 3 look the parent up by name. apiVersion, kind, name
        # and uid are all required fields of an ownerReference, so the join never sees a null.
        - name: newOwnerRuns
          variable:
            jmesPath: "(request.object.metadata.ownerReferences || `[]`)[?controller == `true` && kind == 'PipelineRun'].join('/', [apiVersion, kind, name, uid])"
        # Empty on CREATE, where there is no old object.
        - name: oldOwnerRuns
          variable:
            jmesPath: "(request.oldObject.metadata.ownerReferences || `[]`)[?controller == `true` && kind == 'PipelineRun'].join('/', [apiVersion, kind, name, uid])"
        # The controlling PipelineRun references this request adds. Inside a JMESPath filter the
        # context is the element, so the old list is injected by substitution.
        - name: addedOwnerRuns
          variable:
            jmesPath: "newOwnerRuns[?!contains(`{{ oldOwnerRuns }}`, @)]"
      preconditions:
        all:
          - key: "{{ length(addedOwnerRuns) }}"
            operator: GreaterThan
            value: 0
      validate:
        failureAction: Enforce
        # The deny depends on the requester: without this an UPDATE that adds the reference
        # would be waved through as a pre-existing violation, as in rule 4.
        allowExistingViolations: false
        message: >-
          A TaskRun in <pipeline-namespace> may carry a controlling PipelineRun ownerReference
          only when the Tekton controller creates it or adds it; rule 3 trusts that reference.
          got creator={{ request.userInfo.username }} added={{ addedOwnerRuns }}.
        deny:
          conditions:
            any:
              - key: "{{ request.userInfo.username }}"
                operator: NotEquals
                value: <tekton-controller-identity>

Catalog 提供的模板:规则 2 和 3 的父级测试

上面策略中的 parentIsApprovedTemplate 条目,以及规则 3 中的同一条目,只接受按名称引用的 namespace 本地 Pipeline。在规则 1 使用 catalog 变体时,合法的晋升运行会通过 hub resolver 引用其模板,而规则 2 和 3 中的父级测试必须接受相同形式。在这两个策略中,均将唯一的 parentIsApprovedTemplate 条目替换为下面的七个条目(所需的六个 parentRef* 变量必须先出现,并且顺序完全一致)。该比较会固定 catalog、pipeline 类型以及同一个 templateNames 列表中的模板名称——而不是 version 参数;此处与规则 1 的变体一样,不比较该参数(限制下的 catalog 条目对此进行了权衡)——并且会拒绝请求级别的 url,或拒绝任何不是 artifact 的 type,原因与规则 1 的变体相同。

请在此块中替换:<catalog-name>。

        - name: parentRefParams
          variable:
            jmesPath: "(parentRef.params || `[]`)"
        - name: parentRefCatalog
          variable:
            jmesPath: "parentRefParams[?name=='catalog'].value | [0] || ''"
        - name: parentRefKind
          variable:
            jmesPath: "parentRefParams[?name=='kind'].value | [0] || ''"
        - name: parentRefTemplateName
          variable:
            jmesPath: "parentRefParams[?name=='name'].value | [0] || ''"
        # As in rule 1's variant: no request-level url, and type only omitted or 'artifact'.
        - name: parentRefUrlCount
          variable:
            jmesPath: "length(parentRefParams[?name=='url'])"
        - name: parentRefTypeIsArtifact
          variable:
            jmesPath: "length(parentRefParams[?name=='type']) == `0` || (length(parentRefParams[?name=='type']) == `1` && (parentRefParams[?name=='type'].value | [0]) == 'artifact')"
        # A by-name reference to an approved template, or a hub-resolver reference to an
        # approved template in the trusted catalog -- the same choice rule 1's variant makes.
        # The uid comparison is the same one the base entry makes: the run fetched by name must
        # be the object the owner reference points at. Both rules define runUid, so this entry
        # is substituted into rule 2 and rule 3 unchanged.
        - name: parentIsApprovedTemplate
          variable:
            jmesPath: "length(parentRuns) == `1` && parentRuns[0].metadata.uid == runUid && parentRuns[0].spec.pipelineSpec == null && (((parentRef.resolver || '') == '' && contains(templateNames, parentRef.name || '')) || ((parentRef.resolver || '') == 'hub' && parentRefUrlCount == `0` && parentRefTypeIsArtifact && parentRefCatalog == '<catalog-name>' && parentRefKind == 'pipeline' && contains(templateNames, parentRefTemplateName)))"

规则 3:Pod 不得位于模板之外

规则 1 和规则 2 判断 Tekton 自身的对象。无论它们接纳了什么——以及无论什么对象从未到达它们——最终都会变成一个 Pod,而 Pod 正是 driver 交出凭证的地方:connectors-csi 会为任何其 volume 名称引用 Connector 的 Pod 挂载,无论该 Pod 是如何创建的。手动编写的 Pod、Deployment、Job、CronJob,或任何其他 controller 的挂载 <production-connector> 的工作负载,都不会经过这两条规则——声明了自身定义中该 volume 的 Tekton Task 也不会经过,因为引用它的 run 和 TaskRun 都不携带 volume;只有 Pod 携带。no-pod-outside-a-template 在所有路径汇聚的唯一位置封住了这一切:挂载 Connector 的 Pod 必须由 Tekton controller 在 <pipeline-namespace> 中创建,且属于一个 PipelineRun,该对象按名称引用其中一个模板——父级通过 Pod 的控制 ownerReference 到达其 TaskRun,再通过该 TaskRun 的控制 ownerReference 到达 run:两次 API 调用,而规则 2 的同一测试最终仍然适用。不检查 Labels;controller 加到 Pod 上的标签包括 run 的作者自行选择的任意 taskRunSpecs[].metadata.labels。第二个链接成立,是因为规则 2 的 taskrun-owner-references-set-by-the-controller 从一开始就阻止手写的 TaskRun 携带控制 PipelineRun 引用——从规则安装的那一刻起,因为它以 background: false 运行,只判断准入时的创建和更新,却不会重新扫描已经存在的对象;在 apply 之前就存在的 TaskRun 会保留其获得的引用,而清理这些对象是 rollout 步骤的工作(Rolling out)——并且因为它比较完整的引用,所以现有引用无法在保留其 uid 的同时重命名到另一个 run。每一跳还会检查按名称获取的对象是否携带其引用所命名的 uid,因此重命名后的引用将指向空处。这也是应同时部署规则 2 和规则 3 的另一个原因。

这是整组规则的底线。规则 1 和规则 2 会更早拒绝错误请求,并在消息中指出 run 出错的地方;规则 3 则让“只能由 Tekton 创建,且只能来自模板”对所有其他能够声明 volume 的对象都成立。部署规则 1 和规则 2 时,也请一并部署它。父级测试是一个引用测试:父级的内容——其 mappings、其 Pod 模板——在父级创建时已由规则 1 以及所部署的规则 5 到 11 中相应规则进行判断,这也是为什么早于这组规则存在的 run 必须在信任这组规则之前完成清理(Rolling out)。Pod 只在一个位置声明 volumes,即 spec.volumes,所以其识别前导部分比 run 规则更短;两种 Connector 写法也会以相同方式规范化。

应用该 Pod 规则前,有两个特性值得了解。Kyverno 也会将它应用到生成 Pod 的工作负载类型——Deployment、StatefulSet、DaemonSet、Job、ReplicaSet、ReplicationController 和 CronJob——方法是为每种类型生成一个匹配规则(autogen-no-pod-outside-a-template、autogen-cronjob-no-pod-outside-a-template),因此,挂载 Connector 的 Deployment 会在创建 Deployment 时被拒绝,而不是等到其 controller 尝试启动 Pod 时才拒绝;拒绝消息会指出生成的规则。并且由于该规则匹配集群中的每次 Pod 创建,它所声明的故障关闭 webhook 会在 Kyverno 不可用期间阻止所有 Pod 创建,而不仅仅是晋升操作——Limits会权衡这一取舍。

完整策略 YAML —

no-pod-outside-a-template(可直接复制粘贴)

请在此块中替换:<promotion-pipeline>、<production-connector>、<pipeline-namespace>、<tekton-controller-identity>。

# Rule 3: a Pod that mounts the Connector must have been created by Tekton for a PipelineRun of a template.
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: no-pod-outside-a-template
  labels:
    app.kubernetes.io/part-of: promotion-guardrails
spec:
  admission: true
  background: false
  webhookConfiguration:
    failurePolicy: Fail
  rules:
    - name: no-pod-outside-a-template
      match:
        any:
          - resources:
              kinds:
                - Pod
              operations:
                - CREATE
      context:
        # The approved promotion templates: keep this list in step with rules 1 and 2.
        - name: templateNames
          variable:
            value:
              - <promotion-pipeline>
        # A Pod declares volumes in exactly one place.
        - name: csiAttrs
          variable:
            jmesPath: "(request.object.spec.volumes || `[]`)[?csi.driver=='connectors-csi'].csi.volumeAttributes"
        - name: singleRefs
          variable:
            jmesPath: "csiAttrs[?\"connector.name\" != null].join('/', [\"connector.namespace\" || '{{request.namespace}}', \"connector.name\"])"
        - name: rawPluralRefs
          variable:
            jmesPath: "csiAttrs[?connectors != null].connectors | join(',', @) | split(@, ',')"
        - name: pluralRefs
          variable:
            jmesPath: "rawPluralRefs | map(&trim(@, ' \t\n\r'), @) | [?@ != ''] | map(&(contains(@, '/') && @ || join('/', ['{{request.namespace}}', @])), @)"
        - name: connectorRefs
          variable:
            jmesPath: "[singleRefs, pluralRefs] | [] | [?@ != '']"
        - name: mountsProductionConnector
          variable:
            jmesPath: "contains(connectorRefs, '<production-connector>')"
        # The Pod's TaskRun, from the controlling ownerReference the Tekton controller writes on
        # every Pod it creates. Not a label: taskRunSpecs[].metadata.labels reach the Pod too.
        - name: taskRunName
          variable:
            jmesPath: "(request.object.metadata.ownerReferences || `[]`)[?controller == `true` && kind == 'TaskRun'].name | [0] || ''"
            default: ""
        # The uid of that same reference: the TaskRun is fetched by name, and the uid is what
        # proves the object found under that name is the one the reference points at.
        - name: taskRunUid
          variable:
            jmesPath: "(request.object.metadata.ownerReferences || `[]`)[?controller == `true` && kind == 'TaskRun'].uid | [0] || ''"
            default: ""
        # Read that TaskRun back: an empty list, not an error, when there is none.
        - name: ownerTaskRuns
          apiCall:
            urlPath: "/apis/tekton.dev/v1/namespaces/{{request.namespace}}/taskruns?fieldSelector=metadata.name={{taskRunName}}"
            jmesPath: "items || `[]`"
        # The parent PipelineRun, from that TaskRun's controlling ownerReference -- which rule 2's
        # second rule reserves for the Tekton controller to write.
        - name: runName
          variable:
            jmesPath: "(length(ownerTaskRuns) == `1` && ownerTaskRuns[0].metadata.uid == taskRunUid && ((ownerTaskRuns[0].metadata.ownerReferences || `[]`)[?controller == `true` && kind == 'PipelineRun'].name | [0])) || ''"
            default: ""
        # The uid of the same reference, read from the same TaskRun, for the parent test below.
        - name: runUid
          variable:
            jmesPath: "(length(ownerTaskRuns) == `1` && ownerTaskRuns[0].metadata.uid == taskRunUid && ((ownerTaskRuns[0].metadata.ownerReferences || `[]`)[?controller == `true` && kind == 'PipelineRun'].uid | [0])) || ''"
            default: ""
        # Read the parent run back. A list query with a name selector returns an empty list --
        # not an error -- when the reference is missing or names a run that does not exist.
        - name: parentRuns
          apiCall:
            urlPath: "/apis/tekton.dev/v1/namespaces/{{request.namespace}}/pipelineruns?fieldSelector=metadata.name={{runName}}"
            jmesPath: "items || `[]`"
        - name: parentRef
          variable:
            jmesPath: "parentRuns[0].spec.pipelineRef || `{}`"
        # The same test rule 1 applies to a run: a by-name reference to an approved template, no
        # resolver, no inline pipelineSpec. The uid comparison keeps the lookup honest: the run
        # fetched by name must be the object the owner reference points at, so a reference whose
        # name was changed to another run resolves to no parent. Catalog-served templates:
        # replace this entry with the seven under "Catalog-served templates: the parent test for
        # rules 2 and 3" (under rule 2 in the guide).
        - name: parentIsApprovedTemplate
          variable:
            jmesPath: "length(parentRuns) == `1` && parentRuns[0].metadata.uid == runUid && (parentRef.resolver || '') == '' && contains(templateNames, parentRef.name || '') && parentRuns[0].spec.pipelineSpec == null"
      preconditions:
        all:
          - key: "{{ mountsProductionConnector }}"
            operator: Equals
            value: true
      validate:
        failureAction: Enforce
        message: >-
          A Pod that mounts the production registry Connector <production-connector> may only
          be created by the Tekton controller for a PipelineRun in <pipeline-namespace> that
          references an approved promotion template. got namespace={{ request.namespace }}
          creator={{ request.userInfo.username }} owner taskRun={{ taskRunName }}
          pipelineRun={{ runName }} parentRef={{ parentRef }}.
        deny:
          conditions:
            any:
              # One entry per namespace promotion runs are created in.
              - key: "{{ request.namespace }}"
                operator: AnyNotIn
                value:
                  - <pipeline-namespace>
              - key: "{{ request.userInfo.username }}"
                operator: NotEquals
                value: <tekton-controller-identity>
              - key: "{{ parentIsApprovedTemplate }}"
                operator: Equals
                value: false

Catalog 提供的模板。 请按照规则 2 中规则 2 和规则 3 的父级测试的说明,准确替换上面的 parentIsApprovedTemplate 条目;两个策略中的替换内容相同。

规则 4:只有维护者可以更改模板

对于模板完整性,首选的答案不是策略。 由受治理 catalog 提供的模板(规则 1 的 catalog 变体)受到 catalog 自身发布流程和访问控制的保护,因此根本不需要此规则——请将其省略。当模板以 Pipeline 对象的形式存储在 namespace 中时,再使用此规则,并注意其中的取舍:拥有模板的团队通过维护者身份编辑模板,因此必须持续维护下面的维护者列表。

晋升页面将 approvers 和 Task 引用保存在 Pipeline 中,使 run 无法覆盖它们。这种保护的强度取决于 Pipeline 对象本身。template-changes-by-maintainers-only 匹配 <pipeline-namespace> 中指定模板的创建、更新和删除操作,并拒绝任何不在 <template-maintainer> 列表中的请求者。它保护 namespace 本地模板;由 catalog 提供的模板则由 catalog 管理,这正是该规则可选的原因。

该规则设置 allowExistingViolations: false。其条件取决于请求者而不是对象;如果没有此设置,Kyverno 也会根据旧对象评估更新,在旧对象中发现相同的“违规”,并将更新作为预先存在的状态接纳——这样一来,恰恰是该规则要防护的操作就会失去保护。

完整策略 YAML —

template-changes-by-maintainers-only(可直接复制粘贴)

请在此块中替换:<pipeline-namespace>、<promotion-pipeline>、<template-maintainer>。

# Rule 4: the templates themselves may only be changed by their maintainers.
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: template-changes-by-maintainers-only
  labels:
    app.kubernetes.io/part-of: promotion-guardrails
spec:
  admission: true
  background: false
  webhookConfiguration:
    failurePolicy: Fail
  rules:
    - name: template-changes-by-maintainers-only
      match:
        any:
          - resources:
              kinds:
                - tekton.dev/v1/Pipeline
              # One entry per namespace promotion runs are created in.
              namespaces:
                - <pipeline-namespace>
              # Add one entry per approved template, as in rule 1.
              names:
                - <promotion-pipeline>
              operations:
                - CREATE
                - UPDATE
                - DELETE
      validate:
        failureAction: Enforce
        # The deny condition depends on the requester, not on the object. Without this, Kyverno
        # also evaluates the old object on UPDATE, finds the same "violation" and waves the
        # update through as pre-existing.
        allowExistingViolations: false
        message: >-
          This Pipeline is a promotion template and may only be changed by its
          maintainers. got {{ request.userInfo.username }}.
        deny:
          conditions:
            all:
              - key: "{{ request.userInfo.username }}"
                operator: AnyNotIn
                value:
                  - <template-maintainer>

规则 5:approvers 必须来自 namespace 的允许列表

模板会命名其 approvers,规则 4 防止这些内容被编辑——但这种保护仅限于 namespace,且粒度较粗:任何维护者编辑都被允许,而让模板通过 run 参数接收 approvers,则会让启动 run 的人选择 approver。promotion-approvers 固定这些值:一个策略对象,其中的两条规则共享一个 allowedApprovers 列表。run-approvers-from-the-allowed-list 会拒绝 approvers 参数列出该列表之外任何人的晋升 run——无论由谁创建 run,也无论模板如何处理该参数。template-approvers-from-the-allowed-list 会拒绝 Pipeline——无论它是否为模板,也无论请求者是不是维护者——只要其 ApprovalTask 步骤列出了列表之外的任何人。它判断创建和编辑操作,而不是判断已经存在的内容:在 rollout 时对预先存在的模板执行一次审计(Rolling out)。

审批机制本身稍后也会检查同一个列表(Who May Approve),但“稍后”正是关键:该规则会在准入时拒绝请求,早于创建一个可能被未列出的 approver 放行的 run,而不是等到 pipeline 已经启动并停在一个无人信任其有权执行的审批步骤之后才拒绝。

无论参数是数组还是单个字符串,两条规则都会读取该参数。不传入 approvers 参数的 run 不受影响——此时使用模板自身经过审查的列表,或参数的默认值,并且这两者也都由第二条规则根据 allowedApprovers 进行约束。参数名称 approvers 已固定;名称不同的模板需要相应调整规则。

有两个后果值得明确说明。建议的默认方式仍然是在模板中使用固定且经过审查的 approver 范围(Who May Approve);运行时 approvers 适用于晋升确实需要动态指定 approver 的团队,并且只支持一种形式:模板可以将名为 approvers 的参数传入其 ApprovalTask(数组使用 value: $(params.approvers[*]),字符串使用 value: $(params.approvers))——run 侧随后判断每次 run 提供的值,而模板侧判断该参数的默认值。对任何其他参数名称的引用都会作为未列出的字面量被拒绝,这是有意为之:run 侧只读取名为 approvers 的参数,因此名称不同的参数会绕过该规则偷偷传入人员名称。模板侧只判断 Pipeline 中的 <pipeline-namespace> 对象:由 catalog 提供的模板不会经过集群准入,因此其硬编码 approvers 属于经过审查的 catalog 内容——与规则 1 的 catalog 变体具有相同的信任边界——而审批机制自身较晚执行的检查仍会作用于 run 最终等待的任何审批。

完整策略 YAML —

promotion-approvers(可直接复制粘贴)

请在此块中替换:<allowed-approver>、<production-connector>、<pipeline-namespace>。

# Rule 5: promotion approvers must come from the allowed list.
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: promotion-approvers
  labels:
    app.kubernetes.io/part-of: promotion-guardrails
spec:
  admission: true
  background: false
  webhookConfiguration:
    failurePolicy: Fail
  rules:
    # 5a: a run that passes an approvers parameter may only name allowed approvers.
    - name: run-approvers-from-the-allowed-list
      match:
        any:
          - resources:
              kinds:
                - tekton.dev/v1/PipelineRun
              operations:
                - CREATE
      context:
        # Who may approve promotions in this namespace: add one entry per identity or group.
        - name: allowedApprovers
          variable:
            value:
              - <allowed-approver>
        # Every place a connectors-csi volume can be declared on a run: workspace bindings, pod
        # templates (spec.podTemplate on a TaskRun, taskRunTemplate and taskRunSpecs on a
        # PipelineRun -- one list serves both kinds), and the volumes of an inline Task spec.
        - name: csiVolumes
          variable:
            jmesPath: "[request.object.spec.workspaces, request.object.spec.podTemplate.volumes, request.object.spec.taskRunTemplate.podTemplate.volumes, (request.object.spec.taskRunSpecs || `[]`)[].podTemplate.volumes, request.object.spec.taskSpec.volumes, (request.object.spec.pipelineSpec.tasks || `[]`)[].taskSpec.volumes, (request.object.spec.pipelineSpec.finally || `[]`)[].taskSpec.volumes] | [] | [?@ != null] | []"
        - name: csiAttrs
          variable:
            jmesPath: "csiVolumes[?csi.driver=='connectors-csi'].csi.volumeAttributes"
        - name: singleRefs
          variable:
            jmesPath: "csiAttrs[?\"connector.name\" != null].join('/', [\"connector.namespace\" || '{{request.namespace}}', \"connector.name\"])"
        - name: rawPluralRefs
          variable:
            jmesPath: "csiAttrs[?connectors != null].connectors | join(',', @) | split(@, ',')"
        # The driver trims whitespace around each entry, drops empty entries, and resolves a
        # bare "name" in the run's namespace; mirror that before comparing, or a padded or
        # unqualified spelling of the production Connector escapes detection.
        - name: pluralRefs
          variable:
            jmesPath: "rawPluralRefs | map(&trim(@, ' \t\n\r'), @) | [?@ != ''] | map(&(contains(@, '/') && @ || join('/', ['{{request.namespace}}', @])), @)"
        - name: mountsProductionConnector
          variable:
            jmesPath: "contains([singleRefs, pluralRefs] | [] | [?@ != ''], '<production-connector>')"
        # The run's approvers parameter, whether declared as an array or a single string.
        - name: runApprovers
          variable:
            jmesPath: "to_array((request.object.spec.params || `[]`)[?name=='approvers'].value | [0] || `[]`)"
        # Inside a JMESPath filter the context is the element, so the allowed list is injected
        # by substitution rather than referenced by name.
        - name: badApprovers
          variable:
            jmesPath: "runApprovers[?!contains(`{{ allowedApprovers }}`, @)]"
      preconditions:
        all:
          - key: "{{ mountsProductionConnector }}"
            operator: Equals
            value: true
      validate:
        failureAction: Enforce
        message: >-
          Promotion approvers must come from the allowed list
          {{ allowedApprovers }}. offending approvers {{ badApprovers }}.
        deny:
          conditions:
            any:
              - key: "{{ length(badApprovers) }}"
                operator: GreaterThan
                value: 0
    # 5b: the template's own ApprovalTask steps may only name allowed approvers.
    - name: template-approvers-from-the-allowed-list
      match:
        any:
          - resources:
              kinds:
                - tekton.dev/v1/Pipeline
              operations:
                - CREATE
                - UPDATE
              # Approver conventions are per namespace: only the promotion namespaces'
              # Pipelines are judged (one entry per namespace), other namespaces are left alone.
              namespaces:
                - <pipeline-namespace>
      context:
        # Keep this list identical to the one in run-approvers-from-the-allowed-list.
        - name: allowedApprovers
          variable:
            value:
              - <allowed-approver>
        # Every approvers value of every ApprovalTask step, in tasks and finally alike.
        - name: rawTemplateApprovers
          variable:
            jmesPath: "[(request.object.spec.tasks || `[]`), (request.object.spec.finally || `[]`)] | [] | [?taskRef.kind=='ApprovalTask'] | [].params | [] | [?name=='approvers'] | [].value"
        # Each value may be an array or a single string; coerce and flatten.
        - name: templateApprovers
          variable:
            jmesPath: "map(&to_array(@), rawTemplateApprovers) | []"
        # Run-time approvers are supported through exactly one shape: plumbing from a Pipeline
        # parameter named "approvers", whose values the run rule validates at admission. A
        # reference to any other parameter is judged as a literal, because a differently named
        # parameter would escape the run rule. The dollar and parentheses are regex-escaped so
        # Kyverno does not mistake the Tekton reference for one of its own variables.
        - name: literalApprovers
          variable:
            jmesPath: "templateApprovers[?!regex_match('^\\$\\(params\\.approvers(\\[\\*\\])?\\)$', @)]"
        # The parameter's default applies whenever a run omits approvers, and the run rule
        # never sees it — judge it here alongside the literals.
        - name: approverDefaults
          variable:
            jmesPath: "to_array((request.object.spec.params || `[]`)[?name=='approvers'].default | [0] || `[]`)"
        # Inside a JMESPath filter the context is the element, so the allowed list is injected
        # by substitution rather than referenced by name.
        - name: badApprovers
          variable:
            jmesPath: "[literalApprovers, approverDefaults] | [] | [?!contains(`{{ allowedApprovers }}`, @)]"
      validate:
        failureAction: Enforce
        # As in rule 4: without this, an UPDATE that keeps a pre-existing offending approver
        # would be admitted as a pre-existing violation.
        allowExistingViolations: false
        message: >-
          ApprovalTask approvers in <pipeline-namespace> must come from the allowed list
          {{ allowedApprovers }}, or be plumbed from a run parameter named approvers.
          offending approvers {{ badApprovers }}.
        deny:
          conditions:
            any:
              - key: "{{ length(badApprovers) }}"
                operator: GreaterThan
                value: 0

规则 6:sources 必须来自批准的 registry

每个 imageMappings source 都必须以 docker:// 加上一个批准的主机开头。晋升会将 artifact 从其构建和测试所在的 registry 移出;来自其他位置的 source 不具备这样的历史记录。该检查是针对 mappings 的 foreach:在单个条件中将每个 source 与批准的 registry 通配符模式列表进行比较——信任另一个 registry 只需向该列表添加一个条目,而不必编写新条件:

完整策略 YAML —

sources-from-approved-registries(可直接复制粘贴)

请在此块中替换:<production-connector>、<approved-source-registry>。

# Rule 6: sources must come from an approved source registry.
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: sources-from-approved-registries
  labels:
    app.kubernetes.io/part-of: promotion-guardrails
spec:
  admission: true
  background: false
  webhookConfiguration:
    failurePolicy: Fail
  rules:
    - name: sources-from-approved-registries
      match:
        any:
          - resources:
              kinds:
                - tekton.dev/v1/PipelineRun
              operations:
                - CREATE
      context:
        # Every place a connectors-csi volume can be declared on a run: workspace bindings, pod
        # templates (spec.podTemplate on a TaskRun, taskRunTemplate and taskRunSpecs on a
        # PipelineRun -- one list serves both kinds), and the volumes of an inline Task spec.
        - name: csiVolumes
          variable:
            jmesPath: "[request.object.spec.workspaces, request.object.spec.podTemplate.volumes, request.object.spec.taskRunTemplate.podTemplate.volumes, (request.object.spec.taskRunSpecs || `[]`)[].podTemplate.volumes, request.object.spec.taskSpec.volumes, (request.object.spec.pipelineSpec.tasks || `[]`)[].taskSpec.volumes, (request.object.spec.pipelineSpec.finally || `[]`)[].taskSpec.volumes] | [] | [?@ != null] | []"
        - name: csiAttrs
          variable:
            jmesPath: "csiVolumes[?csi.driver=='connectors-csi'].csi.volumeAttributes"
        - name: singleRefs
          variable:
            jmesPath: "csiAttrs[?\"connector.name\" != null].join('/', [\"connector.namespace\" || '{{request.namespace}}', \"connector.name\"])"
        - name: rawPluralRefs
          variable:
            jmesPath: "csiAttrs[?connectors != null].connectors | join(',', @) | split(@, ',')"
        # The driver trims whitespace around each entry, drops empty entries, and resolves a
        # bare "name" in the run's namespace; mirror that before comparing, or a padded or
        # unqualified spelling of the production Connector escapes detection.
        - name: pluralRefs
          variable:
            jmesPath: "rawPluralRefs | map(&trim(@, ' \t\n\r'), @) | [?@ != ''] | map(&(contains(@, '/') && @ || join('/', ['{{request.namespace}}', @])), @)"
        - name: mountsProductionConnector
          variable:
            jmesPath: "contains([singleRefs, pluralRefs] | [] | [?@ != ''], '<production-connector>')"
        # Coerced to a list so that even a single-string value is judged; the shape rule
        # separately refuses the non-list form.
        - name: mappings
          variable:
            jmesPath: "to_array((request.object.spec.params || `[]`)[?name=='imageMappings'].value | [0] || `[]`)"
      preconditions:
        all:
          - key: "{{ mountsProductionConnector }}"
            operator: Equals
            value: true
      validate:
        failureAction: Enforce
        message: >-
          Every imageMappings source must come from an approved source registry.
          got {{ mappings }}.
        foreach:
          - list: "mappings"
            context:
              - name: src
                variable:
                  jmesPath: "split(element, ' ') | [0] || ''"
            deny:
              conditions:
                # The approved source registries, one wildcard pattern per entry. A source
                # matching none of the patterns is refused; to trust another registry, add
                # its entry to this list.
                any:
                  - key: "{{ src }}"
                    operator: AllNotIn
                    value:
                      - "docker://<approved-source-registry>/*"

规则 7:destinations 必须落入批准的 registry

每个 imageMappings destination 都必须以 docker:// 加上一个批准的目标主机开头。Connector 已经限制了凭证可以在哪些位置生效;此规则限制了run 可以指向哪些位置,因此指向其他位置的 mapping 会在前置阶段被拒绝,而不是在复制过程中失败。不限制 destination 名称的团队无需应用此规则。其形式与规则 6 对称——每个批准的主机对应一个通配符模式条目:

完整策略 YAML —

targets-in-approved-registries(可直接复制粘贴)

请在此块中替换:<production-connector>、<approved-target-registry>。

# Rule 7: destinations must land in an approved target registry.
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: targets-in-approved-registries
  labels:
    app.kubernetes.io/part-of: promotion-guardrails
spec:
  admission: true
  background: false
  webhookConfiguration:
    failurePolicy: Fail
  rules:
    - name: targets-in-approved-registries
      match:
        any:
          - resources:
              kinds:
                - tekton.dev/v1/PipelineRun
              operations:
                - CREATE
      context:
        # Every place a connectors-csi volume can be declared on a run: workspace bindings, pod
        # templates (spec.podTemplate on a TaskRun, taskRunTemplate and taskRunSpecs on a
        # PipelineRun -- one list serves both kinds), and the volumes of an inline Task spec.
        - name: csiVolumes
          variable:
            jmesPath: "[request.object.spec.workspaces, request.object.spec.podTemplate.volumes, request.object.spec.taskRunTemplate.podTemplate.volumes, (request.object.spec.taskRunSpecs || `[]`)[].podTemplate.volumes, request.object.spec.taskSpec.volumes, (request.object.spec.pipelineSpec.tasks || `[]`)[].taskSpec.volumes, (request.object.spec.pipelineSpec.finally || `[]`)[].taskSpec.volumes] | [] | [?@ != null] | []"
        - name: csiAttrs
          variable:
            jmesPath: "csiVolumes[?csi.driver=='connectors-csi'].csi.volumeAttributes"
        - name: singleRefs
          variable:
            jmesPath: "csiAttrs[?\"connector.name\" != null].join('/', [\"connector.namespace\" || '{{request.namespace}}', \"connector.name\"])"
        - name: rawPluralRefs
          variable:
            jmesPath: "csiAttrs[?connectors != null].connectors | join(',', @) | split(@, ',')"
        # The driver trims whitespace around each entry, drops empty entries, and resolves a
        # bare "name" in the run's namespace; mirror that before comparing, or a padded or
        # unqualified spelling of the production Connector escapes detection.
        - name: pluralRefs
          variable:
            jmesPath: "rawPluralRefs | map(&trim(@, ' \t\n\r'), @) | [?@ != ''] | map(&(contains(@, '/') && @ || join('/', ['{{request.namespace}}', @])), @)"
        - name: mountsProductionConnector
          variable:
            jmesPath: "contains([singleRefs, pluralRefs] | [] | [?@ != ''], '<production-connector>')"
        # Coerced to a list so that even a single-string value is judged; the shape rule
        # separately refuses the non-list form.
        - name: mappings
          variable:
            jmesPath: "to_array((request.object.spec.params || `[]`)[?name=='imageMappings'].value | [0] || `[]`)"
      preconditions:
        all:
          - key: "{{ mountsProductionConnector }}"
            operator: Equals
            value: true
      validate:
        failureAction: Enforce
        message: >-
          Every imageMappings destination must land in an approved target registry.
          got {{ mappings }}.
        foreach:
          - list: "mappings"
            context:
              - name: dst
                variable:
                  jmesPath: "split(element, ' ') | [1] || ''"
            deny:
              conditions:
                # The approved target registries, one wildcard pattern per entry, as in the
                # sources rule.
                any:
                  - key: "{{ dst }}"
                    operator: AllNotIn
                    value:
                      - "docker://<approved-target-registry>/*"

规则 8:mappings 必须存在且格式正确

imageMappings 必须是非空的列表,其中每一项都必须严格为 SRC DST:两个以空格分隔的引用,且不得包含嵌入的换行、制表符或回车符。没有 mappings 的 run 会持有凭证却不复制任何内容,这绝不算晋升;格式错误的项会被拒绝,因为负责判断内容的规则无法判断无法解析的内容。这也是负责列表要求的规则:规则 6、7、9 和 11 会将单字符串值转换后判断其内容,但只有此规则会拒绝非列表形式(Tekton 在运行时根据模板的 array 参数也会拒绝该形式)。

完整策略 YAML —

mapping-shape(可直接复制粘贴)

请在此块中替换:<production-connector>。

# Rule 8: mappings must be present, and each one a single-line "SRC DST" pair.
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: mapping-shape
  labels:
    app.kubernetes.io/part-of: promotion-guardrails
spec:
  admission: true
  background: false
  webhookConfiguration:
    failurePolicy: Fail
  rules:
    - name: mapping-shape
      match:
        any:
          - resources:
              kinds:
                - tekton.dev/v1/PipelineRun
              operations:
                - CREATE
      context:
        # Every place a connectors-csi volume can be declared on a run: workspace bindings, pod
        # templates (spec.podTemplate on a TaskRun, taskRunTemplate and taskRunSpecs on a
        # PipelineRun -- one list serves both kinds), and the volumes of an inline Task spec.
        - name: csiVolumes
          variable:
            jmesPath: "[request.object.spec.workspaces, request.object.spec.podTemplate.volumes, request.object.spec.taskRunTemplate.podTemplate.volumes, (request.object.spec.taskRunSpecs || `[]`)[].podTemplate.volumes, request.object.spec.taskSpec.volumes, (request.object.spec.pipelineSpec.tasks || `[]`)[].taskSpec.volumes, (request.object.spec.pipelineSpec.finally || `[]`)[].taskSpec.volumes] | [] | [?@ != null] | []"
        - name: csiAttrs
          variable:
            jmesPath: "csiVolumes[?csi.driver=='connectors-csi'].csi.volumeAttributes"
        - name: singleRefs
          variable:
            jmesPath: "csiAttrs[?\"connector.name\" != null].join('/', [\"connector.namespace\" || '{{request.namespace}}', \"connector.name\"])"
        - name: rawPluralRefs
          variable:
            jmesPath: "csiAttrs[?connectors != null].connectors | join(',', @) | split(@, ',')"
        # The driver trims whitespace around each entry, drops empty entries, and resolves a
        # bare "name" in the run's namespace; mirror that before comparing, or a padded or
        # unqualified spelling of the production Connector escapes detection.
        - name: pluralRefs
          variable:
            jmesPath: "rawPluralRefs | map(&trim(@, ' \t\n\r'), @) | [?@ != ''] | map(&(contains(@, '/') && @ || join('/', ['{{request.namespace}}', @])), @)"
        - name: mountsProductionConnector
          variable:
            jmesPath: "contains([singleRefs, pluralRefs] | [] | [?@ != ''], '<production-connector>')"
        # The raw value: this rule is the one that checks it IS a list, so no coercion here.
        - name: mappings
          variable:
            jmesPath: "(request.object.spec.params || `[]`)[?name=='imageMappings'].value | [0] || `[]`"
        # imageMappings must be a list; a single string is refused explicitly below.
        - name: mappingsIsList
          variable:
            jmesPath: "type(mappings) == 'array'"
        - name: malformed
          variable:
            jmesPath: "to_array(mappings)[?length(split(@, ' ')) != `2` || contains(@, '\n') || contains(@, '\t') || contains(@, '\r')]"
      preconditions:
        all:
          - key: "{{ mountsProductionConnector }}"
            operator: Equals
            value: true
      validate:
        failureAction: Enforce
        message: >-
          imageMappings must be a non-empty list of single-line "SRC DST" pairs.
          isList={{ mappingsIsList }} count={{ length(mappings) }} malformed={{ malformed }}.
        deny:
          conditions:
            any:
              - key: "{{ mappingsIsList }}"
                operator: Equals
                value: false
              - key: "{{ length(mappings) }}"
                operator: Equals
                value: 0
              - key: "{{ length(malformed) }}"
                operator: GreaterThan
                value: 0

规则 9:destination repository 必须与 source 匹配

target-path-matches-source 会比较每个 mapping 两侧的 repository path——registry host 之后、tag 或 digest 之前的全部内容。team/app 必须落入 team/app。主机上的端口属于主机而不是路径:registry.example.com:5000/team/app 和 registry.example.com/team/app 共享路径 team/app,并且由于在检查 tag 之前会去除主机,端口的冒号不会进入 tag 比较。tag 或 digest 可以不同,因此 app:1.2.3 可以作为 app:stable 晋升,而 .sig 和 .att 这两个 digest-pinned image 的 companion 也会原样通过。目标位于不同 repository 时会被拒绝:审批针对的是 artifact,而不是重命名。两条路径在 JMESPath 中进行比较,而不是使用 Kyverno operator,因为 operator 会将纯数字字符串读取为数字——否则 0123 会等于 123,从而接纳重命名操作。

完整策略 YAML —

target-path-matches-source(可直接复制粘贴)

请在此块中替换:<production-connector>。

# Rule 9: the destination repository must match the source repository (a promotion is not a rename).
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: target-path-matches-source
  labels:
    app.kubernetes.io/part-of: promotion-guardrails
spec:
  admission: true
  background: false
  webhookConfiguration:
    failurePolicy: Fail
  rules:
    - name: target-path-matches-source
      match:
        any:
          - resources:
              kinds:
                - tekton.dev/v1/PipelineRun
              operations:
                - CREATE
      context:
        # Every place a connectors-csi volume can be declared on a run: workspace bindings, pod
        # templates (spec.podTemplate on a TaskRun, taskRunTemplate and taskRunSpecs on a
        # PipelineRun -- one list serves both kinds), and the volumes of an inline Task spec.
        - name: csiVolumes
          variable:
            jmesPath: "[request.object.spec.workspaces, request.object.spec.podTemplate.volumes, request.object.spec.taskRunTemplate.podTemplate.volumes, (request.object.spec.taskRunSpecs || `[]`)[].podTemplate.volumes, request.object.spec.taskSpec.volumes, (request.object.spec.pipelineSpec.tasks || `[]`)[].taskSpec.volumes, (request.object.spec.pipelineSpec.finally || `[]`)[].taskSpec.volumes] | [] | [?@ != null] | []"
        - name: csiAttrs
          variable:
            jmesPath: "csiVolumes[?csi.driver=='connectors-csi'].csi.volumeAttributes"
        - name: singleRefs
          variable:
            jmesPath: "csiAttrs[?\"connector.name\" != null].join('/', [\"connector.namespace\" || '{{request.namespace}}', \"connector.name\"])"
        - name: rawPluralRefs
          variable:
            jmesPath: "csiAttrs[?connectors != null].connectors | join(',', @) | split(@, ',')"
        # The driver trims whitespace around each entry, drops empty entries, and resolves a
        # bare "name" in the run's namespace; mirror that before comparing, or a padded or
        # unqualified spelling of the production Connector escapes detection.
        - name: pluralRefs
          variable:
            jmesPath: "rawPluralRefs | map(&trim(@, ' \t\n\r'), @) | [?@ != ''] | map(&(contains(@, '/') && @ || join('/', ['{{request.namespace}}', @])), @)"
        - name: mountsProductionConnector
          variable:
            jmesPath: "contains([singleRefs, pluralRefs] | [] | [?@ != ''], '<production-connector>')"
        # Coerced to a list so that even a single-string value is judged; the shape rule
        # separately refuses the non-list form.
        - name: mappings
          variable:
            jmesPath: "to_array((request.object.spec.params || `[]`)[?name=='imageMappings'].value | [0] || `[]`)"
      preconditions:
        all:
          - key: "{{ mountsProductionConnector }}"
            operator: Equals
            value: true
      validate:
        failureAction: Enforce
        message: >-
          The destination repository must equal the source repository; only the registry host and
          the tag or digest may differ. got {{ mappings }}.
        foreach:
          - list: "mappings"
            context:
              # Repository path = everything after the registry host, before the tag (:) or
              # digest (@). The host — port and all — is dropped first, so a port's colon can
              # never be mistaken for the tag separator.
              - name: srcRepo
                variable:
                  jmesPath: "split(element, ' ') | [0] | split(@, '://') | [1] || '' | split(@, '/') | [1:] | join('/', @) | split(@, '@') | [0] | split(@, ':') | [0]"
              - name: dstRepo
                variable:
                  jmesPath: "split(element, ' ') | [1] | split(@, '://') | [1] || '' | split(@, '/') | [1:] | join('/', @) | split(@, '@') | [0] | split(@, ':') | [0]"
              # Compared here, not by a Kyverno operator: an operator reads a purely numeric
              # repository name as a number, and "0123" would then equal "123".
              - name: repoMismatch
                variable:
                  jmesPath: "srcRepo != dstRepo"
            deny:
              conditions:
                any:
                  - key: "{{ repoMismatch }}"
                    operator: Equals
                    value: true

更严格的变体:同时禁止重新标记。 在上面的合并策略中,将 foreach 块的 context 中名为 srcRepo 和 dstRepo 的两条条目以及注释替换为下面的块——注释也要一并替换,因为它描述的是基础规则的解析方式,而此变体会保留 tag:

              # Repository path plus the tag or digest = everything after the registry host.
              # The host — port and all — is still dropped first; only the reference it
              # carries is compared, so a port's colon is never part of the comparison.
              - name: srcRepo
                variable:
                  jmesPath: "split(element, ' ') | [0] | split(@, '://') | [1] || '' | split(@, '/') | [1:] | join('/', @)"
              - name: dstRepo
                variable:
                  jmesPath: "split(element, ' ') | [1] | split(@, '://') | [1] || '' | split(@, '/') | [1:] | join('/', @)"

使用此变体时,将 app:1.2.3 作为 app:stable 晋升会被拒绝,晋升页面在将一个 Image 晋升到多个 Destination下记录的多 tag 模式也会被拒绝。

规则 10:模板只公开经过审查的输入

这些防护规则会读取 imageMappings 和 approvers,因为这些是经过审查的模板公开的输入——而 skopeo-copy 本身接受更多输入:srcImage 和 dstImages 指定要复制的内容,copy-mappings workspace 从文件中导入 mappings,skopeoImage 替换执行 image,而 extraCopyArgs 替换其参数。run 无法使用其中任何一个:规则 1 将 run 固定到模板,而 Tekton 会静默丢弃模板未声明的参数。唯一剩下的路径是维护者编辑模板本身以扩大其范围,而 templates-expose-only-reviewed-inputs 会封住这一点:对于指定模板,复制步骤的 parameters 和 workspaces 是白名单,因此后来添加的输入——包括本指南从未涉及的输入——在经过审查并加入列表之前都会被拒绝。CA bundle workspaces 就是已经实现的示例:晋升页面的模板将 src-ca-bundle 和 dst-ca-bundle 暴露为可选 workspaces,使经过 proxy 的复制仍能保持 TLS 验证——由 Connector 支持的 run 会将 destination workspace 绑定到其 ca.crt 的 Connector mount,而 source workspace 则接收站点自身的 CA——这两个名称都位于下面的 allowedCopyWorkspaces 中。该规则还会拒绝模板中任何位置的内联 taskSpec。这并不是第二个独立问题,而是同一个问题:白名单通过其 taskRef 找到复制步骤,因此内联重写的步骤不会提供任何 parameters 或 workspaces 供比较,却会在运行任意内容的同时通过所有检查。晋升模板会引用它们运行的每个 task——无论来自 namespace 还是 catalog——所以拒绝内联不会损失任何经过审查的结构。晋升页面的 srcImage/dstImages alternative 则不同——在此处将其列入白名单并不会使其安全,因为规则 6–9 和 11 只判断 imageMappings,永远看不到它复制的内容;正如该形式所属章节所述,它仍然不在这些防护规则的范围内。namespace 中的其他 Pipeline 不受影响;如果其中某个 Pipeline 挂载 Connector,规则 1 已会拒绝它。由 catalog 提供的模板不是 namespace 中的 Pipeline 对象,因此此规则无法看到它们:其输入范围由 catalog 自身的发布流程管理,正如规则 4 将其编辑权限交给 catalog 管理一样。

完整策略 YAML —

templates-expose-only-reviewed-inputs(可直接复制粘贴)

请在此块中替换:<promotion-pipeline>、<pipeline-namespace>。

# Rule 10: the promotion templates' copy step exposes only the reviewed inputs.
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: templates-expose-only-reviewed-inputs
  labels:
    app.kubernetes.io/part-of: promotion-guardrails
spec:
  admission: true
  background: false
  webhookConfiguration:
    failurePolicy: Fail
  rules:
    - name: templates-expose-only-reviewed-inputs
      match:
        any:
          - resources:
              kinds:
                - tekton.dev/v1/Pipeline
              operations:
                - CREATE
                - UPDATE
              # Only the promotion templates are judged: another Pipeline in the namespace may
              # use skopeo-copy however it likes — if it mounts the Connector, rule 1 refuses
              # it for not being a template.
              names:
                - <promotion-pipeline>
              # One entry per namespace promotion runs are created in.
              namespaces:
                - <pipeline-namespace>
      context:
        # The copy inputs the reviewed templates pass. Anything else — srcImage, dstImages,
        # skopeoImage, extraCopyArgs, or a parameter added later — is refused until it is
        # reviewed into this list.
        - name: allowedCopyParams
          variable:
            value:
              - imageMappings
              - srcTLSVerify
              - dstTLSVerify
        # The workspaces the reviewed templates bind. Keeps copy-mappings — a file-based second
        # way to feed mappings — from appearing unreviewed. The two CA-bundle workspaces are
        # reviewed in: the promotion template exposes both so a run can keep TLS verification on
        # instead of turning it off — a Connector-backed run binds the destination one to the
        # mount holding the proxy's ca.crt, and the source one takes the site's own CA.
        - name: allowedCopyWorkspaces
          variable:
            value:
              - src-registry-config
              - dst-registry-config
              - src-ca-bundle
              - dst-ca-bundle
        # Every task, in tasks and finally alike, that runs skopeo-copy: referenced through a
        # resolver whose name parameter says so, or directly by name.
        - name: copySteps
          variable:
            jmesPath: "[(request.object.spec.tasks || `[]`), (request.object.spec.finally || `[]`)] | [] | [?taskRef.name=='skopeo-copy' || contains((taskRef.params || `[]`)[?name=='name'].value, 'skopeo-copy')]"
        # A copy step rewritten as an inline taskSpec has no taskRef for the filter above to
        # recognise, so the allowlists would be empty. Promotion templates reference every task.
        - name: inlineTasks
          variable:
            jmesPath: "[(request.object.spec.tasks || `[]`), (request.object.spec.finally || `[]`)] | [] | [?taskSpec != null].name"
        # Inside a JMESPath filter the context is the element, so the allowed lists are
        # injected by substitution rather than referenced by name.
        - name: unexpectedParams
          variable:
            jmesPath: "map(&(params || `[]`)[].name, copySteps) | [] | [?!contains(`{{ allowedCopyParams }}`, @)]"
        - name: unexpectedWorkspaces
          variable:
            jmesPath: "map(&(workspaces || `[]`)[].name, copySteps) | [] | [?!contains(`{{ allowedCopyWorkspaces }}`, @)]"
      validate:
        failureAction: Enforce
        # As in rule 5's template side: catch the edit that introduces the input, not only a
        # brand-new Pipeline.
        allowExistingViolations: false
        message: >-
          The copy step of a promotion template takes only the reviewed inputs: params
          {{ allowedCopyParams }}, workspaces {{ allowedCopyWorkspaces }}, and every task
          referenced rather than inlined. unexpected params {{ unexpectedParams }}, unexpected
          workspaces {{ unexpectedWorkspaces }}, inline tasks {{ inlineTasks }}.
        deny:
          conditions:
            any:
              - key: "{{ length(unexpectedParams) }}"
                operator: GreaterThan
                value: 0
              - key: "{{ length(unexpectedWorkspaces) }}"
                operator: GreaterThan
                value: 0
              # An inline taskSpec hides the copy step from both allowlists, so it is refused
              # on its own -- the two lists above would have nothing to judge.
              - key: "{{ length(inlineTasks) }}"
                operator: GreaterThan
                value: 0

规则 11:sources 必须携带 release tag

仓库一致性规则将晋升限制在同一个仓库内;但它没有说明该仓库中的哪个构建版本可以晋升。app:latest、app:dev-20260902、分支 tag 或未标记的引用(隐式的 latest)都满足规则 6 到 9,并会在获得批准后晋升。此规则要求每个 imageMappings source 都必须是 release artifact:通过 digest 固定(@sha256: 后跟 64 个十六进制数字),或携带与某个批准模式匹配的 tag——每个条目对应一个正则表达式,默认使用带可选 v 前缀的 semver.org 语法。第二个默认条目允许 cosign 存储在 digest 固定 image 旁的 sha256-<digest>.sig / .att / .sbom tag,因此签名 image 会与其签名和 attestation 一起晋升。Destination 不进行判断:在进入时将 app:1.2.3 重新标记为 app:stable 仍然允许,这正是仓库一致性规则的意图。release tag 遵循其他约定的团队可以将其模式放入列表;不以 tag 作为门禁条件的团队则不应用此规则。tag 从引用的最后一个路径段读取,因此 registry 端口(host:5000/team/app:1.2.3)不会被误认为 tag。

下面提供了两种可直接复制到 <approved-source-tag-pattern> 中的模式。默认模式是 semver.org 语法,v 前缀可选——它允许预发布和构建元数据 tag,例如 1.2.3-rc.1,适用于通过相同路径晋升 release candidate 的团队:

^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-((0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(\.(0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*))?(\+([0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*))?$

严格模式仅允许 v?major.minor.patch——允许 1.2.3 和 v1.2.3,但不允许 1.2.3-rc.1、1.2.3+build.5 或 01.2.3——适用于生产环境只能携带最终 release 的团队:

^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$
完整策略 YAML —

sources-carry-release-tags(可直接复制粘贴)

请在此块中替换:<production-connector>、<approved-source-tag-pattern>。

# Rule 11: sources must be release artifacts -- pinned by digest or carrying a release tag.
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: sources-carry-release-tags
  labels:
    app.kubernetes.io/part-of: promotion-guardrails
spec:
  admission: true
  background: false
  webhookConfiguration:
    failurePolicy: Fail
  rules:
    - name: sources-carry-release-tags
      match:
        any:
          - resources:
              kinds:
                - tekton.dev/v1/PipelineRun
              operations:
                - CREATE
      context:
        # Every place a connectors-csi volume can be declared on a run: workspace bindings, pod
        # templates (spec.podTemplate on a TaskRun, taskRunTemplate and taskRunSpecs on a
        # PipelineRun -- one list serves both kinds), and the volumes of an inline Task spec.
        - name: csiVolumes
          variable:
            jmesPath: "[request.object.spec.workspaces, request.object.spec.podTemplate.volumes, request.object.spec.taskRunTemplate.podTemplate.volumes, (request.object.spec.taskRunSpecs || `[]`)[].podTemplate.volumes, request.object.spec.taskSpec.volumes, (request.object.spec.pipelineSpec.tasks || `[]`)[].taskSpec.volumes, (request.object.spec.pipelineSpec.finally || `[]`)[].taskSpec.volumes] | [] | [?@ != null] | []"
        - name: csiAttrs
          variable:
            jmesPath: "csiVolumes[?csi.driver=='connectors-csi'].csi.volumeAttributes"
        - name: singleRefs
          variable:
            jmesPath: "csiAttrs[?\"connector.name\" != null].join('/', [\"connector.namespace\" || '{{request.namespace}}', \"connector.name\"])"
        - name: rawPluralRefs
          variable:
            jmesPath: "csiAttrs[?connectors != null].connectors | join(',', @) | split(@, ',')"
        - name: pluralRefs
          variable:
            jmesPath: "rawPluralRefs | map(&trim(@, ' \t\n\r'), @) | [?@ != ''] | map(&(contains(@, '/') && @ || join('/', ['{{request.namespace}}', @])), @)"
        - name: mountsProductionConnector
          variable:
            jmesPath: "contains([singleRefs, pluralRefs] | [] | [?@ != ''], '<production-connector>')"
        - name: mappings
          variable:
            jmesPath: "to_array((request.object.spec.params || `[]`)[?name=='imageMappings'].value | [0] || `[]`)"
        # The tag formats that mark a release artifact, one regular expression per entry; a
        # source pinned by digest (@sha256:...) is always accepted. The second entry keeps the
        # signature, attestation and SBOM tags cosign stores beside a digest-pinned image
        # promotable together with it.
        - name: approvedSourceTagPatterns
          variable:
            value:
              # Single-quoted so the backslashes in a pattern need no escaping.
              - '<approved-source-tag-pattern>'
              - '^sha256-[0-9a-f]{64}\.(sig|att|sbom)$'
      preconditions:
        all:
          - key: "{{ mountsProductionConnector }}"
            operator: Equals
            value: true
      validate:
        failureAction: Enforce
        message: >-
          Every imageMappings source must be pinned by digest or carry a release tag matching
          the approved patterns; an untagged source (implicit latest) is refused.
          got {{ mappings }}.
        foreach:
          - list: "mappings"
            context:
              - name: src
                variable:
                  jmesPath: "split(element, ' ') | [0] || ''"
              # A reference must carry a repository path after the transport and host
              # ("docker://host/repo..."); a host-only reference has nothing to promote, and
              # its port must not be read as a tag.
              - name: hasRepositoryPath
                variable:
                  jmesPath: "contains(split(src, '//') | [-1] || '', '/')"
              # The last path segment holds the tag or digest: "app:1.2.3", "app@sha256:...", "app".
              # Taking it after the last "/" keeps a registry port ("host:5000/...") out of the way.
              - name: lastSegment
                variable:
                  jmesPath: "split(src, '/') | [-1] || ''"
              # Pinned means a real digest: "@sha256:" followed by 64 hex digits, so that
              # "app@foo" or a truncated digest does not pass as pinned.
              # The repository name is what is left of the last segment before any ":" or "@";
              # "docker://host/:1.2.3" has none and is refused.
              - name: repositoryName
                variable:
                  jmesPath: "split(split(lastSegment, '@') | [0] || '', ':') | [0] || ''"
              - name: digestPinned
                variable:
                  jmesPath: "regex_match('@sha256:[0-9a-f]{64}$', lastSegment)"
              - name: tag
                variable:
                  jmesPath: "contains(lastSegment, ':') && (split(lastSegment, ':') | [-1]) || ''"
              # The patterns (trusted, from this policy) are joined into one alternation and the
              # tag is passed as a value, never spliced into the expression: a tag carrying a
              # quote is simply refused instead of breaking the evaluation.
              - name: tagApproved
                variable:
                  jmesPath: "tag != '' && regex_match(join('|', map(&join('', ['(', @, ')']), approvedSourceTagPatterns)), tag)"
            deny:
              conditions:
                any:
                  - key: "{{ hasRepositoryPath }}"
                    operator: Equals
                    value: false
                  - key: "{{ repositoryName }}"
                    operator: Equals
                    value: ""
                  - key: "{{ digestPinned || tagApproved }}"
                    operator: Equals
                    value: false

组合规则

采用这些防护措施,就是选择其中一组并将其作为一个整体运行。这一子集有一个 最低要求:始终包括规则 1、2 和 3;如果模板是命名空间中的 Pipeline 对象,则还必须包括规则 4 —— 否则,任何能够更新该命名空间中 Pipeline 的人,都可以在其已批准的名称下替换经过审查的 模板,而规则 1、2 和 3 仍会继续信任该名称。保存每个所选规则的对象 — 或将所有对象放在一个文件中,并用 --- 分隔,或者按照 将规则组合成更少的对象 中的方式构建几个捆绑包 — 替换占位符,将 文件保存在版本控制中,然后应用它。共享标签是后续所有操作的句柄:

kubectl apply -f promotion-guardrails.yaml

kubectl get clusterpolicy -l app.kubernetes.io/part-of=promotion-guardrails
# Expect ADMISSION=true and READY=True with MESSAGE=Ready on every row. A rule that fails to
# compile is reported in these columns, not at run time.

# READY says a policy compiled, not that it blocks anything. Read each rule's action:
for p in $(kubectl get clusterpolicy -l app.kubernetes.io/part-of=promotion-guardrails -o name); do
  kubectl get "$p" -o jsonpath='{.metadata.name}{"\t"}{.spec.rules[*].validate.failureAction}{"\n"}'
done
# Expect Enforce in every column (rules 2 and 5 print one action per rule). A rule left on
# Audit records and admits.

这种每个防护措施对应一个对象的结构有三个后果值得明确说明:

  • 删除防护措施就是删除对象,而不是编辑共享策略中的 YAML — 之后再添加防护措施也不会影响已经运行的对象。
  • 拒绝信息会标明规则。 一个违反多个已部署规则的有缺陷请求只会被拒绝一次,但消息中会在各自的策略名称下列出每条被违反的规则。
  • 报告会按规则归属。 每个策略都会生成自己的 PolicyReport 结果,因此在 Audit 观察窗口内,可以按规则读取“此次运行会违反哪项约束”。

将规则组合成更少的对象

本指南采用每个防护措施对应一个对象的结构,因为这样可以分别应用、审计和删除每条规则。并非必须如此:一个 ClusterPolicy 可以在 spec.rules 下包含任意数量的条目,每个条目都有自己的 match、context、preconditions 和 validate;规则 2 和规则 5 的对象本身已经各包含两个条目。以下三种技术会逐步减少对象数量或重复内容。第一种和第三种只会改变 部署对象,不会改变被拒绝的内容:验证后,相同的请求仍会由相同的规则名称拒绝,只是替换了对象。第二种已通过服务器 dry run 验证,结果显示了别名的展开。

连接规则列表。 整组规则中的规则名称都是唯一的,因此组合时无需重命名。请按生命周期而不是数量分组:需要一起启用、审计和回滚的规则应归为一组 —— 核心三项(规则 1 至 3)、模板规则(规则 4、5 和 10)以及内容规则(规则 6 至 9 和 11)。使用 yq (Mike Farah 的 yq v4,yq --version)从上面的策略文件构建捆绑包 — 每个防护措施对应一个文件;规则 5 的文件 贡献其中的两个规则。该表达式会保留第一个文件的所有字段,但 rules 会变为连接后的内容, metadata.name 会由它设置,因此输入文件的其他字段必须一致 — 本指南中的文件已经一致;请特别检查 background、admission、webhookConfiguration、applyRules 以及你可能添加的任何 validationFailureAction,因为这些字段的差异会被静默地从第一个文件中取用:

请在此块中替换:<bundle-name>、<first-rule-file>、<next-rule-file>。

# One command per bundle; one argument per policy file, in the order you want the rules
# evaluated -- three for the core trio, five for the content rules.
yq eval-all '([.spec.rules[]]) as $r | select(fileIndex == 0) | .spec.rules = $r | .metadata.name = "<bundle-name>"' \
  <first-rule-file>.yaml <next-rule-file>.yaml ... > <bundle-name>.yaml

# Expect: the bundle name, then two equal numbers -- the rules counted, and the distinct
# rule names. A smaller second number means duplicate rule names, for example a file listed
# twice.
yq '.metadata.name, (.spec.rules | length), ([.spec.rules[].name] | unique | length)' <bundle-name>.yaml

规则共享一个对象后会有四项变化,但规则的判定内容不会改变:

  • 一条无效规则会使整个捆绑包停止服务。 Kyverno 会在 kubectl apply 阶段拒绝某些错误;其他错误则会通过,并使对象处于 READY=False 状态 — 而尚未就绪的策略不会评估其中的任何规则,因此该捆绑包中的所有防护措施都会在编译完成前静默缺失。(failurePolicy: Fail 针对的是 webhook 无法访问,或规则在评估期间出错;它不涵盖从未加载成功的策略。)每次应用后都要检查 READY,正如 组合规则 中已经执行的那样,并在测试集群上尝试新的捆绑包 — 或者将其作为命名空间级的 Policy 副本 放入临时命名空间 — 然后再让它承载生产环境。
  • 回滚粒度是捆绑包。 推出 下的紧急删除操作会移除整个捆绑包;其中的 Audit 开关会修补每个对象的每条规则,无需更改。
  • 报告和拒绝信息会标明捆绑包。 PolicyReport 结果会在 policy 中携带捆绑包,在 rule 中携带规则; 拒绝消息以捆绑包名称为标题,下面列出规则。针对真实 promotion run 进行检查 中的运行后检查会按策略名称进行筛选 —— 将其 jq 列表中的单规则名称替换为你的捆绑包名称;它所比较的 kind/rule=result 行无需更改。
  • context 仍按规则保留。 Kyverno 不会在规则之间共享任何内容,因此 Connector 识别前导部分仍会在每条识别 Connector 的规则中重复 —— 十三条规则条目中有九条如此;规则 4、规则 10 以及规则 5 的模板侧会判断 Pipeline 对象,规则 2 的所有者引用规则会判断每个 TaskRun,因此这四条不包含该前导部分。组合规则会减少对象数量,而不会减少 YAML。下面的两种技术用于处理这一点。

请按安全顺序替换:先应用捆绑包,等待 READY=True,然后删除它们所替代的每个防护措施对象 — 反向操作时也遵循相同顺序。两种对象同时存在期间,Connector 仍受保护, 但每个请求都会被判断两次:拒绝信息会列出两个对象,PolicyReport 会在每次检查中携带两行,而 针对真实 promotion run 进行检查 下的精确计数检查会一直失败,直到旧对象被删除。删除和应用之间出现间隙会更糟,因为 Connector 在这段时间内没有任何保护。两种结构都带有共享标签,因此推出过程中的标签选择器可以找到任意一种。

使用 YAML anchor 只定义一次前导部分。 在一个文件中,YAML anchor 允许捆绑包只声明一次识别前导部分,然后在每条规则中引用它 —— 服务器接收到的是展开后的副本,因此运行时不会发生变化,但前导部分的编辑只需在一处完成:

  rules:
    - name: promotion-runs-use-a-template
      match: ...
      context: &connector-preamble
        - name: csiVolumes
          variable:
            jmesPath: "..."
        # ... the rest of the preamble, exactly as in the single-rule object
      validate: ...
    - name: no-taskrun-outside-a-template
      match: ...
      context: *connector-preamble
      validate: ...

kubectl 会在发送对象之前解析别名;对此类捆绑包执行服务器 dry run,会显示第二条规则及其完整的上下文列表。Anchor 不会跨文档生效,因此 这种方法只适用于一个捆绑包内部;需要额外条目的规则也不能追加到别名列表中 — 为它提供自己的列表。

将形状相同的规则折叠为一条规则。 内容规则(规则 6 至 9 和 11)共享其 match、 前置条件和 imageMappings 提取逻辑;它们可以变成一条规则,使用一个前导部分、一个针对 mappings 的 foreach, 并将每项检查作为同一 deny 的条件。这样放弃的是归属信息:一条规则只会生成一个结果和一条消息,因此只有从消息回显的值中才能看出 是哪项检查拒绝了请求;PolicyReport 会为这五项显示一行,拒绝信息会标明 promotion-content,而不再标明五项中的某一项 (被拒绝的请求不变,只有名称发生变化)。针对真实 promotion run 进行检查 下的检查也会相应变化:在运行后脚本中, 将 promotion-content 列入 jq 策略筛选器,并将 expected 中的五个 PipelineRun/<content rule>=pass 条目替换为一个 PipelineRun/promotion-content=pass(脚本注释随后会统计三条 PipelineRun 规则,而不是七条);重命名副本检查必须查找 promotion-content: 标题,而不是 target-path-matches-source:。如果你希望用一个 “content”开关,请选择这种方式;如果需要查看具体触发的是哪条规则,则保留分开的规则。

完整策略 YAML —

promotion-content,将五条内容规则合并为一条(可直接复制粘贴)

请在此块中替换:<production-connector>、<approved-source-registry>、<approved-target-registry>、<approved-source-tag-pattern>。

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: promotion-content
  labels:
    app.kubernetes.io/part-of: promotion-guardrails
spec:
  admission: true
  background: false
  webhookConfiguration:
    failurePolicy: Fail
  rules:
  - name: promotion-content
    match:
      any:
      - resources:
          kinds:
          - tekton.dev/v1/PipelineRun
          operations:
          - CREATE
    context:
    - name: csiVolumes
      variable:
        jmesPath: '[request.object.spec.workspaces, request.object.spec.podTemplate.volumes, request.object.spec.taskRunTemplate.podTemplate.volumes, (request.object.spec.taskRunSpecs || `[]`)[].podTemplate.volumes, request.object.spec.taskSpec.volumes, (request.object.spec.pipelineSpec.tasks || `[]`)[].taskSpec.volumes, (request.object.spec.pipelineSpec.finally || `[]`)[].taskSpec.volumes] | [] | [?@ != null] | []'
    - name: csiAttrs
      variable:
        jmesPath: csiVolumes[?csi.driver=='connectors-csi'].csi.volumeAttributes
    - name: singleRefs
      variable:
        jmesPath: csiAttrs[?"connector.name" != null].join('/', ["connector.namespace" || '{{request.namespace}}', "connector.name"])
    - name: rawPluralRefs
      variable:
        jmesPath: csiAttrs[?connectors != null].connectors | join(',', @) | split(@, ',')
    - name: pluralRefs
      variable:
        jmesPath: "rawPluralRefs | map(&trim(@, ' \t\n\r'), @) | [?@ != ''] | map(&(contains(@, '/') && @ || join('/', ['{{request.namespace}}', @])), @)"
    - name: mountsProductionConnector
      variable:
        jmesPath: contains([singleRefs, pluralRefs] | [] | [?@ != ''], '<production-connector>')
    - name: mappings
      variable:
        jmesPath: (request.object.spec.params || `[]`)[?name=='imageMappings'].value | [0] || `[]`
    - name: mappingsForEach
      variable:
        jmesPath: to_array(mappings)
    - name: mappingsIsList
      variable:
        jmesPath: type(mappings) == 'array'
    - name: malformed
      variable:
        jmesPath: "to_array(mappings)[?length(split(@, ' ')) != `2` || contains(@, '\n') || contains(@, '\t') || contains(@, '\r')]"
    - name: approvedSourceTagPatterns
      variable:
        value:
        - '<approved-source-tag-pattern>'
        - '^sha256-[0-9a-f]{64}\.(sig|att|sbom)$'
    preconditions:
      all:
      - key: '{{ mountsProductionConnector }}'
        operator: Equals
        value: true
    validate:
      failureAction: Enforce
      message: 'Promotion content refused: imageMappings must be a non-empty list of single-line "SRC DST" pairs whose sources come from an approved registry and are release artifacts (digest or release tag), and whose destinations land in an approved registry under the same repository path. isList={{ mappingsIsList }} count={{ length(mappings) }} malformed={{ length(malformed) }} mappings={{ mappings }}.'
      foreach:
      - list: '`[1]`'
        deny:
          conditions:
            any:
            - key: '{{ mappingsIsList }}'
              operator: Equals
              value: false
            - key: '{{ length(mappings) }}'
              operator: Equals
              value: 0
            - key: '{{ length(malformed) }}'
              operator: GreaterThan
              value: 0
      - list: mappingsForEach
        context:
        - name: src
          variable:
            jmesPath: split(element, ' ') | [0] || ''
        - name: dst
          variable:
            jmesPath: split(element, ' ') | [1] || ''
        - name: srcRepo
          variable:
            jmesPath: split(element, ' ') | [0] | split(@, '://') | [1] || '' | split(@, '/') | [1:] | join('/', @) | split(@, '@') | [0] | split(@, ':') | [0]
        - name: dstRepo
          variable:
            jmesPath: split(element, ' ') | [1] | split(@, '://') | [1] || '' | split(@, '/') | [1:] | join('/', @) | split(@, '@') | [0] | split(@, ':') | [0]
        - name: repoMismatch
          variable:
            jmesPath: srcRepo != dstRepo
        - name: hasRepositoryPath
          variable:
            jmesPath: contains(split(src, '//') | [-1] || '', '/')
        - name: lastSegment
          variable:
            jmesPath: split(src, '/') | [-1] || ''
        - name: repositoryName
          variable:
            jmesPath: split(split(lastSegment, '@') | [0] || '', ':') | [0] || ''
        - name: digestPinned
          variable:
            jmesPath: regex_match('@sha256:[0-9a-f]{64}$', lastSegment)
        - name: tag
          variable:
            jmesPath: contains(lastSegment, ':') && (split(lastSegment, ':') | [-1]) || ''
        - name: tagApproved
          variable:
            jmesPath: tag != '' && regex_match(join('|', map(&join('', ['(', @, ')']), approvedSourceTagPatterns)), tag)
        deny:
          conditions:
            any:
            - key: '{{ src }}'
              operator: AllNotIn
              value:
              - docker://<approved-source-registry>/*
            - key: '{{ dst }}'
              operator: AllNotIn
              value:
              - docker://<approved-target-registry>/*
            - key: '{{ repoMismatch }}'
              operator: Equals
              value: true
            - key: '{{ hasRepositoryPath }}'
              operator: Equals
              value: false
            - key: '{{ repositoryName }}'
              operator: Equals
              value: ''
            - key: '{{ digestPinned || tagApproved }}'
              operator: Equals
              value: false

除此之外,Kyverno 基于 CEL 的 ValidatingPolicy(policies.kyverno.io/v1alpha1)提供了兼具两者的结构:每个请求只计算一次 variables,并由 validations 中的每个条目共享,同时每个条目都有自己的消息。这是将每条规则重写为 CEL,而不是重新排列规则, 因此本指南不对此展开;请参阅限制。

使用 Policy 收紧命名空间

集群范围的规则集是平台的基线;不同团队的需求各不相同,命名空间可以在不要求平台更改基线的情况下变得更严格。这正是 Kyverno 的命名空间级 Policy kind 的用途:规则语法与 ClusterPolicy 完全相同,但对象位于某个命名空间中,只评估该命名空间的请求, 并由该命名空间的所有者管理 — 不涉及集群范围的权限。将本指南中的任意运行规则复制到 Policy 中,设置更严格的值(更短的 approver 列表、单一的已批准 source),然后在该命名空间中应用它。分层机制天然安全:每个策略的每条匹配规则都必须通过,因此新增的 Policy 只会收紧要求 — 不会放宽基线,也无需考虑优先级。

本指南有意在此结束。双层模型 — 将平台基线作为 ClusterPolicy,再通过 Policy 按项目收紧,包括如何安全地限定基线范围,以及为什么 基线不能依赖命名空间标签 — 已在使用 Tekton 和 Kyverno 的 Pipeline 策略约束中通过示例进行了说明。

应用和验证

请从两个方向进行验证:只针对违规情况测试过的门禁,只完成了一半的测试 — 会中断发布的情况,是合规的 promotion 被拒绝;会影响其他所有人的情况,则是被捕获的普通复制操作。

快速检查:一次拒绝,一次准入

两项检查都使用服务器端 dry run — 实际执行准入评估,但不会创建任何对象。先检查必须失败的方向:使用 promotion pipeline 生成的同一个 run,不同之处在于它指定的 Pipeline 不是 promotion template。替换占位符(见上表),并将其作为一个代码块运行:

在此代码块中替换:<pipeline-namespace>、<approved-source-registry>、<approved-target-registry>、<connector-namespace>、<connector-name>。

kubectl create --dry-run=server -f - <<'YAML'
apiVersion: tekton.dev/v1
kind: PipelineRun
metadata:
  generateName: guardrail-smoke-
  namespace: <pipeline-namespace>
spec:
  pipelineRef:
    name: nightly-mirror        # deliberately not one of the promotion templates
  params:
    - name: imageMappings
      value:
        - "docker://<approved-source-registry>/team/app:1.2.3 docker://<approved-target-registry>/team/app:1.2.3"
  workspaces:
    - name: src-registry-config
      secret:
        secretName: src-registry-config
    - name: dst-registry-config
      csi:
        driver: connectors-csi
        readOnly: true
        volumeAttributes:
          connector.namespace: <connector-namespace>
          connector.name: <connector-name>
          configuration.names: registry-config
YAML
# Expect: the request is refused, and the message names promotion-runs-use-a-template.

然后检查必须成功的方向 — 使用完全相同的请求,将 pipelineRef.name 更改为你的 promotion template(<promotion-pipeline>)。部署 catalog 变体后,改为按照 runs 的方式引用 template — 使用带有 catalog、kind 和 name 参数的 resolver: hub,而不是 pipelineRef.name。无论采用哪种方式,此检查都不要求 template 作为本地 Pipeline 存在:准入判断的是引用,Tekton 仅在 run 实际启动时解析它。

在此代码块中替换:<pipeline-namespace>、<promotion-pipeline>、<approved-source-registry>、<approved-target-registry>、<connector-namespace>、<connector-name>。

kubectl create --dry-run=server -f - <<'YAML'
apiVersion: tekton.dev/v1
kind: PipelineRun
metadata:
  generateName: guardrail-smoke-
  namespace: <pipeline-namespace>
spec:
  pipelineRef:
    name: <promotion-pipeline>
  params:
    - name: imageMappings
      value:
        - "docker://<approved-source-registry>/team/app:1.2.3 docker://<approved-target-registry>/team/app:1.2.3"
  workspaces:
    - name: src-registry-config
      secret:
        secretName: src-registry-config
    - name: dst-registry-config
      csi:
        driver: connectors-csi
        readOnly: true
        volumeAttributes:
          connector.namespace: <connector-namespace>
          connector.name: <connector-name>
          configuration.names: registry-config
YAML
# Expect: "created (server dry run)" — a compliant promotion is admitted.

如果这里被拒绝,说明某个占位符与环境不匹配 — 最常见的是 template 名称、registry 主机或 Connector 坐标;如果已根据你自己的 pattern 列表部署 rule 11,还可能是示例中的 1.2.3 tag,因为它必须匹配某个 pattern。拒绝消息会指出提出异议的 rule;故障排除将各个 rule 与其通常原因对应起来。

使用真实 promotion run 进行检查

上面的所有内容都是合成测试:它证明 rules 能够处理本页编写的请求,但不能证明它们能够匹配你的 pipeline生成的请求 — 而且这种不匹配是无提示的,因为前置条件从未触发的 rule 既不会产生拒绝,也不会产生报告条目。在信任这些 policies 之前,先弥合这一差距。

使用 template 和 Connector 启动一次真实的 promotion,并让它完成。然后运行下面的脚本;每项检查都会输出 PASS 或 FAIL,如果有任何检查失败,脚本会以非零状态退出。检查 2 需要 skopeo,并且需要从运行脚本的位置访问 source registry;检查 1、2 和 4 需要 jq。检查 3 验证 success=1,即 Task 中已复制 mapping 的数量:如果一次 run 携带多个 mapping,请相应调整。保存脚本时,只复制代码块的内容 — 不要复制外围的三反引号行,因为 shell 文件中多余的反引号序列会开启 command substitution,并吞掉脚本的其余部分。

检查 1 读取 PolicyReport 对象,而 reports controller 会在准入之后按照自己的调度写入这些对象。请在 run 完成后立即运行脚本,此时检查 1 可能已经列出 PipelineRun rules,但尚未列出 TaskRun 或 Pod rules,这会被显示为失败,但实际上只是竞争条件 — 等待一会儿让 reports 生成,然后再次运行脚本,再开始调查。

运行后验证脚本(四项检查,可直接复制粘贴)

如果 source registry 使用自签名证书,请在此代码块中替换:<pipeline-namespace>、<promotion-pipeline>、<production-connector> 和 SRC_TLS_VERIFY。

#!/usr/bin/env bash
# Four checks against the newest promotion run. Each prints PASS or FAIL; the script exits
# non-zero if any failed.
set -uo pipefail
NS=<pipeline-namespace>
SRC_TLS_VERIFY=true   # set to false for a self-signed source registry, as the run's srcTLSVerify parameter does
pass=0; fail=0
verdict() { if [ "$1" -eq 0 ]; then echo "PASS $2"; pass=$((pass+1)); else echo "FAIL $2: $3"; fail=$((fail+1)); fi; }

# The newest run that references the template -- by name, or through the `name` parameter of the
# catalog variant's hub reference. Not the tekton.dev/pipeline label: Tekton derives that from
# the run's own name when the pipeline is inline, so it can be worn by a run that is not a
# promotion.
PR="$(kubectl get pipelinerun -n "$NS" -o json | jq -r '
  [ .items[] | select(
      (.spec.pipelineRef.name
        // ((.spec.pipelineRef.params // []) | map(select(.name == "name")) | .[0].value // ""))
      == "<promotion-pipeline>") ]
  | sort_by(.metadata.creationTimestamp) | last | .metadata.name // empty')"
test -n "$PR" || { echo "no promotion run found in $NS"; exit 1; }
# The join key is the controlling ownerReference, not the tekton.dev/pipelineRun label: that
# label is one of the labels taskRunSpecs[].metadata.labels lets a run's author overwrite, so it
# can name another run. The pipelineTask label is only used to choose among the run's own
# children, which the owner reference has already narrowed the list to.
PR_UID="$(kubectl get pipelinerun -n "$NS" "$PR" -o jsonpath='{.metadata.uid}')"
TR="$(kubectl get taskrun -n "$NS" -o json | jq -r --arg uid "$PR_UID" '
  .items[]
  | select(any(.metadata.ownerReferences[]?;
      .controller == true and .kind == "PipelineRun" and .uid == $uid))
  | select(.metadata.labels["tekton.dev/pipelineTask"] == "promote-images")
  | .metadata.name')"
POD="$(kubectl get taskrun -n "$NS" "$TR" -o jsonpath='{.status.podName}')"

# 1. All three objects were evaluated: the seven PipelineRun rules on the run, the TaskRun rule on
#    its TaskRun and the Pod rule on its Pod, every one of them "pass" -- each attributed to its own policy. A short list
#    right after the run usually means the reports controller has not written that object's
#    report yet: run the script again before reading it as a finding.
#    Rule 2's owner-reference rule is left out on purpose: it also matches the controller's later
#    updates of the TaskRun, which add no reference and are recorded as skip, so its row is not stable.
#    If it stays short, a policy did not see the run: recheck the Connector reference in its
#    workspaces against <production-connector>, and drop the rules you chose not to deploy
#    from the jq list and the expected string.
reported="$(kubectl get policyreport -n "$NS" -o json | jq -r --arg pr "$PR" --arg tr "$TR" --arg pod "$POD" '
  [ .items[] | select(.scope.name == $pr or .scope.name == $tr or .scope.name == $pod)
    | .scope.kind as $k | .results[]
    | select(.rule != "taskrun-owner-references-set-by-the-controller")
    | select([.policy] | inside(["promotion-runs-use-a-template","no-taskrun-outside-a-template",
        "no-pod-outside-a-template","promotion-approvers","sources-from-approved-registries",
        "targets-in-approved-registries","mapping-shape","target-path-matches-source",
        "sources-carry-release-tags"]))
    | "\($k)/\(.rule)=\(.result)" ] | sort | join(" ")')"
expected="PipelineRun/mapping-shape=pass PipelineRun/promotion-runs-use-a-template=pass PipelineRun/run-approvers-from-the-allowed-list=pass PipelineRun/sources-carry-release-tags=pass PipelineRun/sources-from-approved-registries=pass PipelineRun/target-path-matches-source=pass PipelineRun/targets-in-approved-registries=pass Pod/no-pod-outside-a-template=pass TaskRun/no-taskrun-outside-a-template=pass"
[ "$reported" = "$expected" ]; verdict $? "rules-evaluated-on-real-run" "got: ${reported:-nothing}"

# 2. For every mapping, the digest the Task reports at the destination equals the source's
#    current digest. The array result dst-image-urls lists each destination as url@digest (older
#    Tekton versions deliver it as a JSON string; both are handled). Two caveats: results are
#    size-limited by Tekton, so a run with enough mappings truncates dst-image-urls and this
#    check would report a false failure -- inspect those destinations directly instead; and a
#    tag-based source is read as it is NOW, so this proves the destination matches the source's
#    current content, not that nothing changed since the promotion. Promote by digest (the source
#    reference is repo@sha256:...) and the comparison is exact and immutable.
while read -r src dst; do
  reported="$(kubectl get taskrun -n "$NS" "$TR" -o json \
    | jq -r --arg d "${dst#docker://}" '.status.results[] | select(.name=="dst-image-urls") | .value
        | (if type == "string" then fromjson else . end)[] | select(startswith($d + "@")) | sub("^.*@"; "")')"
  expected="$(skopeo inspect --tls-verify="$SRC_TLS_VERIFY" --format '{{.Digest}}' "$src")"
  [ -n "$reported" ] && [ "$reported" = "$expected" ]; verdict $? "digest-preserved $dst" "source=$expected reported=${reported:-none}"
done < <(kubectl get pipelinerun -n "$NS" "$PR" -o json | jq -r '.spec.params[] | select(.name=="imageMappings") | .value[]')

# 3. The copy went through the Connector. By construction the mount carries proxy settings, not
#    a registry password (see What Counts as a Promotion); this check does not re-prove that, it
#    confirms the step loaded those settings and the Task counted the copy as successful. A push
#    that succeeds with no password in the Pod is only possible if the proxy injected the
#    credential -- so checks 2 and 3 together are the evidence, not the log line alone.
LOG="$(kubectl logs -n "$NS" "$POD" -c step-copy-images)"
grep -q 'Loading env config: /workspace/dst-registry-config/.env' <<<"$LOG" \
  && grep -q 'HTTPS_PROXY set' <<<"$LOG" && grep -q 'success=1' <<<"$LOG"
verdict $? "copied-through-connector-proxy" "expected .env loaded, HTTPS_PROXY set and success=1 in the step log"

# 4. The rules actually see such a request: the same run with its destination repository renamed
#    must be denied, by the parity rule, when submitted as a dry run. Capture first, then inspect:
#    the denial's non-zero exit must not mask the match.
kubectl get pipelinerun -n "$NS" "$PR" -o json \
  | jq 'del(.metadata.name, .metadata.uid, .metadata.resourceVersion, .metadata.creationTimestamp,
            .metadata.generation, .metadata.managedFields, .metadata.labels, .metadata.annotations, .status)
        | .metadata.generateName = "policy-acceptance-"
        | .spec.params = [ .spec.params[]
            | if .name == "imageMappings"
              then .value = [ (.value[0] | split(" ")
                    | .[0] + " " + (.[1] | sub("://(?<h>[^/]+)/"; "://\(.h)/renamed-by-acceptance-check/"))) ]
              else . end ]' > /tmp/policy-acceptance.json
DENIAL="$(kubectl create --dry-run=server -f /tmp/policy-acceptance.json 2>&1)" || true
grep -q '^ *target-path-matches-source:' <<<"$DENIAL"; verdict $? "renamed-copy-denied" "the policy does not match your runs"

echo "== result: $pass pass / $fail fail =="
[ "$fail" -eq 0 ]

检查 2 和检查 3 也能复现什么算作 Promotion下列出的两个结果:检查 2 验证 digest 相等,检查 3 验证 proxy 路由。

发布和回滚

如果要在强制执行前观察结果,请在要引入的 rules 上将 validate.failureAction 设置为 Audit,运行真实的 promotions,然后读取生成的 PolicyReport 对象:

在此代码块中替换:<pipeline-namespace>。

# Switch every guardrail to Audit at once: every rule of every object, so it also covers
# the second rules of rules 2 and 5 and any bundle built as in Composing.
for p in $(kubectl get clusterpolicy -l app.kubernetes.io/part-of=promotion-guardrails -o name); do
  n=$(kubectl get "$p" -o jsonpath='{.spec.rules[*].name}' | wc -w)
  for i in $(seq 0 $((n - 1))); do
    kubectl patch "$p" --type=json \
      -p "[{\"op\":\"replace\",\"path\":\"/spec/rules/$i/validate/failureAction\",\"value\":\"Audit\"}]"
  done
done

# One report per evaluated resource, named after its UID; the columns count results. Expect one
# pass row per guardrail rule that matched -- seven for the PipelineRun, one each for the TaskRun
# and the Pod -- while the PASS/SKIP totals can be larger on a cluster where other Kyverno
# policies also match these kinds. The rows below are illustrative; your totals may differ.
kubectl get policyreport -n <pipeline-namespace>
# NAME                                   KIND          NAME                     PASS   FAIL   ...
# 78738908-3ac3-47db-abd3-3bc4a6fe2794   PipelineRun   promote-run-x9k2         7      0
# 1f0c5a2e-7b4d-4e0f-9c6a-2d8e3b5f7a91   Pod           promote-run-x9k2-promote-images-pod   1   0

# Which policy and rule produced each result.
kubectl get policyreport -n <pipeline-namespace> \
  -o jsonpath='{range .items[*].results[*]}{.policy}{"\t"}{.rule}{"\t"}{.result}{"\n"}{end}'

Reports 会附加到被评估的对象上:删除 run 会同时删除其 report。Run rules 仅匹配 CREATE,而 policies 使用 background: false 运行,因此在 policy 安装时已经存在的 run 不会被评估,也不会出现在 report 中。之后也无法再对其进行判断,而且也没有必要这样做:Tekton 自身的验证会拒绝对 run 的 spec 所做的任何更改,只有用于取消 run 或释放待处理 run 的 status 控制字段除外 — 无论该 run 是否已经启动。使用 spec.status: PipelineRunPending 创建的 run 是需要特别确认的情况,因为它可以根据需要一直处于未启动状态:验证结果显示,在等待期间无法重写其 mappings(来自 Tekton webhook 的 Once the PipelineRun has started, only status updates are allowed,即使该 run 没有启动时间),并且释放操作也被接受。因此,run 获准使用的内容,就是它实际运行时使用的内容。这对一种 run 尤其重要:早于该规则集创建、仍停留在 approval task 处等待的 promotion。获批后,它会生成一个 TaskRun 和一个 Pod,而 rules 2 和 3 会接受它,因为其 parent 确实引用了 template — 但 rules 1 和 5 到 11 从未检查过它的 mappings 和 Pod template。在安装规则集时清理这些 run:列出仍在进行中的内容,并取消和重新创建所有本来不会获准的 run。

在此代码块中替换:<pipeline-namespace>、<run>。

# Every promotion run still in progress. The ones to drain are those whose creationTimestamp
# is earlier than the moment the policies were applied.
kubectl get pipelinerun -n <pipeline-namespace> -o json | jq -r '
  .items[] | select(.status.conditions[0].status == "Unknown")
  | [.metadata.name, .metadata.creationTimestamp,
     (.spec.pipelineRef.name
       // ((.spec.pipelineRef.params // []) | map(select(.name == "name")) | .[0].value)
       // "inline")] | @tsv'
# Cancel one you would not have admitted; recreate it once the set is in place.
kubectl patch pipelinerun <run> -n <pipeline-namespace> --type=merge -p '{"spec":{"status":"CancelledRunFinally"}}'
# Anything else already holding a Connector mount -- a TaskRun created directly, or a Pod that
# belongs to no run -- was never judged by rules 2 and 3 either. Delete what you would not
# have admitted; the third column is the parent run read from the controlling ownerReference --
# not from the tekton.dev/pipelineRun label, which a run's author can overwrite -- or "none".
kubectl get pods,taskruns -n <pipeline-namespace> -o json | jq -r '
  .items[] | select([.. | objects | select(.driver? == "connectors-csi")] | length > 0)
  | [.kind, .metadata.name,
     ((.metadata.ownerReferences // [])
       | map(select(.controller == true and .kind == "PipelineRun")) | .[0].name // "none")] | @tsv'

# A TaskRun that carries no Connector mount of its own is not in the list above, and the owner
# rule never judged it either if it predates the apply: that rule also runs with
# background: false, so the chain rule 3 walks when the controller creates that TaskRun's Pod --
# after a controller backlog, or a restart during the rollout -- was never checked. Drain the
# ones created before the apply time together with the runs they name.
kubectl get taskrun -n <pipeline-namespace> -o json | jq -r '
  .items[] | select(.status.conditions[0].status == "Unknown")
  | (((.metadata.ownerReferences // [])
       | map(select(.controller == true and .kind == "PipelineRun")) | .[0].name)) as $parent
  | select($parent != null)
  | [.metadata.name, .metadata.creationTimestamp, $parent] | @tsv'

Templates 则有所不同。Pipeline 是可变且长期存在的对象,而在 policies 之前创建的 template 是一个真实的盲点:rule 5 的 template 一侧不会重新扫描它,rule 1 会允许引用其名称的 runs 通过,而 allowExistingViolations: false 只有在它下次被编辑时才能捕获它 — 在有人编辑它之前,旧 template 中固化的未列出 approver 仍会持续收到 approval requests。安装规则集时,请对命名空间执行一次审计:

在此代码块中替换:<pipeline-namespace>。

# Every ApprovalTask approver named by every Pipeline in the namespace, one row per value.
kubectl get pipeline -n <pipeline-namespace> -o json | jq -r '
  .items[] | . as $p
  | [(.spec.tasks // [])[], (.spec.finally // [])[]]
  | .[] | select(.taskRef.kind == "ApprovalTask")
  | (.params // [])[] | select(.name == "approvers")
  | .value | (if type == "array" then .[] else . end)
  | [$p.metadata.name, .] | @tsv'
# Any name outside the allowed list: have a maintainer fix that template. The edit itself is
# the moment rule 5 starts judging it.

空 report 具有歧义:它既可能意味着“没有违规”,也可能意味着“没有匹配项”。真实 run 部分的检查 1 可以区分这两种情况 — 它会统计针对特定 run 生成 report 的 rules — 因此请先运行该检查,再决定观察窗口是否干净;然后将 rules 切换回 Enforce(使用同一个循环,只需翻转该值),并重新读取组合 Rules中列出的每条 rule 的 action。

由于该规则集采用 fail-closed,应该在需要之前就规划好解除方式。删除 policies 是最快的解除阻塞方法,并且会立即生效 — label 使其只需一条命令:

# Emergency: stop the guardrails from blocking promotions.
kubectl delete clusterpolicy -l app.kubernetes.io/part-of=promotion-guardrails

# Softer alternative: the Audit loop above keeps the reporting and stops the blocking.
# A namespace's own stricter Policy objects, if any, are that namespace's to remove.

这两种操作都不会恢复已经被拒绝的 run:准入只在创建时发生一次,因此更改后必须重新创建 run。重新应用版本控制中的文件即可将规则集恢复到原来的状态。

谁可以批准

Kyverno 不执行审批。谁可以批准 promotion 由两个位置决定,而推荐的形式只需要第一个位置:

  • template 命名 approver,approval gate 强制执行这些 approver。 promotion 页面会在 Pipeline 中固定 approvers 和 numberOfApprovalsRequired。手动 approval gate 自身的 admission webhook 只接受来自该列表中某个身份对 ApprovalTask 的响应 — 该身份可以是以本人身份操作的指定用户,也可以是指定组的成员 — 并且只能修改该身份自己的条目;其他人的更新都会被拒绝。因此,template 中的列表就是 approval policy,而这些保护措施用于确保它保持不变:rule 4 防止非维护者编辑 template,rule 5 将即使是维护者的编辑也限制在 allowedApprovers 内,而 rules 1、2 和 3 确保只有 template 的 run 才能持有 production credential — 跳过 approval step 的 run 无法到达 production,因为没有任何规则允许它挂载 Connector。template 也可以将 approvers 作为 run 参数 — 这是为确实需要每个 run 使用不同 approver 的团队提供的变体 — 而 rule 5 正是确保该变体安全的规则:无论是字面值、默认值还是由 run 提供的值,都会在 run 存在之前进行检查。
  • 可选:Connector 在记录该 approval 之前不提供 credential。 production Connector 上的 AccessPolicy 可以让 driver 仅在内置检查 connectors-approvals-in-pipeline 找到携带请求 Pod 的 tekton.dev/pipelineRun label 且已获批准的 ApprovalTask 后,才释放挂载;当这些参数已设置时,必须至少由 approvers 所命名的 numberOfApprovalsRequired 个不同身份批准;组使用 group: 前缀表示,每个批准成员均单独计数。这样会将强制执行推迟到 credential 发放时 — 但单独使用它并不够:该检查通过请求 Pod 的 tekton.dev/pipelineRun label 识别 run,而 label 的内容由创建 Pod 的对象任意写入。如果缺少 rules 2 和 3,命名空间中的任意 Pod 都可以携带已批准 run 的 label,并在 approval 有效期间借用 credential — 这可以是手动编写的 Pod,也可以是 controller 为某个 run 创建的 Pod,而该 run 的 taskRunSpecs[].metadata.labels 命名了已批准的 run。该 gate 在 credential 一侧增加了谁可以批准的限制;rules 2 和 3 仍负责将 credential 绑定到已批准 run 自身的 Pod,并且它们读取的是 owner references,而不是 labels — 每一跳都会同时通过名称和 uid 进行匹配,因此重命名后的引用不会解析到任何父对象。这不是第二次 approval — 该检查读取同一个 ApprovalTask 的已记录响应,并且它生成的 AccessRequest 会自动创建和解析。这需要两个改变集群中每个 Connector 行为的集群范围 feature flag;promotion 页面中的可选:仅在 approval 后释放 credential会权衡这一点,并端到端配置好该层。

选择哪种形式:

  • 默认 — template approver,由 rules 4 和 5 保护。 不改变集群范围的配置,只需维护一个列表。本页面的其他所有内容都假定采用此形式。
  • 在 credential 的所有者不是 pipeline 所有者时,添加 AccessPolicy 层 — platform 或 security 管理员拥有 production Connector,而 application 团队拥有 pipelines — 并且集群已经启用 Connectors approval flags,或准备为每个 Connector 启用这些 flags。在 policy 中命名这些身份;无论 template 命名了谁,管理员都能保留最终决定权。如果同一个团队同时拥有两者,请使用不带 approvers 参数的 policy:run 的 ApprovalTask 获得任何 approval 后,credential 即会释放,而 template 的列表仍是唯一需要维护的列表。

启用该层后,promotion 页面会记录经过验证的运行时行为:待处理的 approval 会使 copy Pod 在 volume mount 处等待;不在 policy 列表中的人员进行 approval 时,检查会以 ApproverMismatch 失败,并且 Pod 会获得 .error.json 标记而不是 configuration,从而及时使 step 失败;rejection 会使 pipeline 停在 approval task 处。以下是这种形式的 AccessPolicy,其中命名了哪些特定身份的 approval 可以释放 production credential:

在此代码块中替换:<connector-namespace>、<connector-name>、<allowed-approver>。

apiVersion: connectors.alauda.io/v1alpha1
kind: AccessPolicy
metadata:
  name: production-registry-approval
  namespace: <connector-namespace>
spec:
  connector:
    names:
      - <connector-name>
  checkGrantedPermission:
    spec:
      checks:
        - name: manual-approval
          ref:
            configMap:
              name: connectors-approvals-in-pipeline
          params:
            # One entry per identity; keep it identical to the template's approvers list.
            - name: approvers
              value:
                - <allowed-approver>
            - name: numberOfApprovalsRequired
              value: "1"
      roleTemplate:
        ref:
          configMap:
            name: connectors-use-connectors-proxy-in-pod

引用的两个 ConfigMap 由 Alauda DevOps Connectors 安装在其自身的 system namespace 中;两个 ref 都必须指向该 namespace。受 approval gate 控制的访问需要 enable-connectors-approval 和 enable-connector-proxy-permissions feature flags — promotion 页面介绍了如何启用它们,而

Connectors Approval & Permission Gating

介绍了如何在切换期间保持现有 Connector consumer 正常工作;在依赖该层之前,请确认这些 flags 已启用:

kubectl get connectorscore -A \
  -o jsonpath='{range .items[*]}{.metadata.name}{": "}{.spec.featureFlags.enable-connectors-approval}{" "}{.spec.featureFlags.enable-connector-proxy-permissions}{"\n"}{end}'

关闭 flags 时 — 这是默认状态 — AccessPolicy webhook 会拒绝创建任何 policies,而由 rules 4 和 5 保护的 template 列表就是完整的 approval policy。启用 flags 后,以下两个契约会使各层保持一致,并且我们已通过针对真实 Connector 运行真实 promotion 对两者进行了确认:

  • AccessPolicy 命名的每个身份也必须出现在 template 的 approver 范围内 — 推荐的默认做法是让两个列表完全相同。 该检查读取 ApprovalTask 的已记录响应,而这些响应与 template 的 approver 条目相对应:policy 中的用户名只有在该用户以本人身份批准时才算满足,而 group: 条目只有在同一组的成员通过该组进行批准时才算满足。通过 policy 未命名条目进行的 approval — 即使在 pipeline 一侧完全合理 — 也会使检查停留在 ApproverMismatch,credential 继续被 withheld。这就是为什么 template 范围比 policy 更宽 是陷阱而不是便利:使用 numberOfApprovalsRequired: "1" 时,第一个响应就会完成 ApprovalTask,因此 template 列表中但不在 policy 中的人员出于好意进行 approval,会直接使 run 失败(实时观察结果:pipeline 已批准,检查为 ApproverMismatch,copy step 失败) — 它不会等待正确的人员。保持两个列表一致,就不会意外出现不匹配;此时 ApproverMismatch 只会表示篡改。只有在 template 为每个 run 收集多项 approval 时,才应让 template 宽于 policy(其 numberOfApprovalsRequired 大于 1,以便 policy 中命名的身份仍可在其他人完成 approval 后作出响应) — 即使如此,如果某个 run 仅由额外身份签署批准,该 run 仍会失败。
  • Rule 5 的 allowedApprovers 必须覆盖 template 范围,包括 policy 中的身份。 这些相同的身份会以固定关系出现在三个位置:template 的 approvers(会被请求批准的人员)是 rule 5 的 allowedApprovers(可被命名的人员)的子集,而 AccessPolicy 的 approvers(其响应会释放 credential 的人员)是 template 列表的子集。Rule 5 以机制保证前两者的关联;AccessPolicy 是 Connector 自身的对象,因此第二个关联需要通过审查建立。如果 policy 要求的身份或数量超出 template 能够提供的范围,每个 run 都会在 copy step 以 ApproverMismatch 失败 — 该错误会显示在 AccessRequest 上,而不是表现为挂起。

实时测试还发现了另一种形式:完全没有 ApprovalTask 的 pipeline,单独依赖 Connector。它无法与内置套件配合工作 — 检查通过 run 的 label 匹配 ApprovalTask 对象,而手动创建的对象不会被 approval controller 调谐,因此请求会保持在 Pending,直到 run 超时。AccessPolicy 检查机制本身是通用的(自定义检查 template 可以匹配其他对象),但使用内置 templates 时,pipeline 中的 ApprovalTask 仍是受支持的交互点 — 请保留它。

限制

这些 policies 会在请求创建时判断请求声明的内容。以下所有内容都不在它们的作用范围内,必须在其他位置处理:

  • 约定是信任锚点。 上述每项保证都建立在 production credential 仅作为 Connector 存在这一前提上。任何 namespace 中用于 production registry 的 dockerconfigjson Secret,都是 policies 无法看到的 promotion 路径。在依赖这些 guardrails 之前,请搜索此类 Secret,并限制可以创建它们的人员。

  • templates 的契约就是 policies 的契约。 Rules 6 至 9 和 11 读取 imageMappings,rule 5 读取 approvers,因为这些是 templates 暴露的输入。Rule 10 会拒绝扩大 copy step 操作面的编辑 — srcImage、dstImages、copy-mappings workspace、skopeoImage、extraCopyArgs 或任何更新的内容;出于实际需要扩大操作面时,必须先将新输入审查并加入 rule 10 的列表,同时添加匹配的 rule。更改 Task reference 的 template 仍需要经过审查:rule 4 确保此类更改由维护者执行,而不是保证这些更改本身安全。

  • catalog variant 信任 catalog — 以及 hub endpoint。 使用 rule 1 的 variant 时,template 内容就是受信任 catalog 在固定名称下提供的内容 — 包括更新版本,因为不会比较 version 参数。如果这过于宽松,请使用 version resolver 参数扩展 variant 的比较,并将 catalog 发布权限视为 rule 4 针对 namespace 内 templates 所处理的权限。该 variant 会拒绝使用两个从其他 hub 获取固定名称的 resolver 参数(url,以及不是 artifact 的 type),因此 hubresolver-config 中由 cluster 配置的 endpoint 就是信任根:能够更改它的身份不需要绕过机制,已批准的坐标只会解析到其他位置。应像控制 ClusterPolicy 一样控制对此配置的写入权限。

  • 目标 artifact 尚不存在。 Admission 可以检查 reference,但永远无法检查即将由 copy 生成的内容。Promoted artifact 的属性只能在其落地后由使用方进行检查。

  • 不包含对源 artifact 自身属性的验证。 读取 image label 或其他内容的 rules 需要 Kyverno 能够访问 registry(context.imageRegistry),并且会默认拒绝:当 registry 无法读取时,rule 会出错,所有匹配的 promotion 都会被拒绝。这种失败并非假设。在某个环境中,所有此类 rules 都因 invalid realm in www-authenticate: realm host "192.0.2.10" is a private or link-local address 而被拒绝,即使 registry 可访问且可读取 — Kyverno 的 registry client 拒绝了 token realm,因为其 host 是 private IP literal;后续版本在 realm host 与 registry host 相同时会放宽这一检查。因此,这些 rules 是否有效取决于你的 Kyverno build,而不仅仅是你的 registry:在围绕 image-attribute rules 进行设计之前,先应用一个试验 rule 并确认它成功。应将此类 rules 视为单独的项目,单独设计其连接性和凭证,而不是将其作为可添加到这组 rules 中的一行。

  • parity rule 比较的是 repository,而不是 tag。 按设计,将 app:1.2.3 promotion 到 app:stable 是允许的;禁止的是落入不同的 repository。还禁止 retagging 的团队必须采用更严格的 variant。哪些 build 可以进行 promotion,是 rule 11 要解决的问题 — 没有它,app:latest 与 app:1.2.3 一样都可以被 promotion。

  • TLS verification 仍是运行时输入。 srcTLSVerify 和 dstTLSVerify 由 template 暴露,且未在此处受到约束:它们改变 copy 对 endpoint 的信任方式,而不是改变其写入的 endpoint。Connector 位于路径中时,目标连接会提供 Connectors CA,而源连接会通过 tunnel 传输并提供其自身的 CA;promotion 页面中的 template 通过暴露 Task 的 src-ca-bundle / dst-ca-bundle workspace 来处理这一点,供 run 进行绑定 — 目标 workspace 绑定到包含 ca.crt 的 mount,源 workspace 则绑定到源 registry 所需的站点自身 CA。Rule 10 列出了这两个名称,因此采用这两个名称无需审查。Run 仍可以将任一开关设置为 "false";如果你的 policy 禁止弱化这些设置,请针对这两个参数添加 rule。

  • controller identity 受信任。 Rules 2 和 3 接受 TaskRun 或 Pod,是因为 Tekton controller 为 template 的某个 run 创建了它,并通过 controller 写入的 owner reference 找到该 run — 既按名称,也按 uid,因此在 reference 名称下找到的对象如果不是被 reference 的对象,就不是 parent。任何能够以该 service account 行事的人 — 或任何能够通过使用该 service account 运行的其他 controller 创建 TaskRun 或 Pod 的人 — 都处于信任边界之内。Label 不属于信任依据:taskRunSpecs[].metadata.labels 允许 run 的作者选择其子对象的 tekton.dev/* label,这就是为什么这里没有任何 rule 读取 label。

  • 运行中的 promotion Pod 可被任何能够访问它的人读取。 Policies 判断的是创建操作。任何获准向 <pipeline-namespace> 中的 Pod 执行 exec,或向其附加 ephemeral container 的人,都可以在 copy step 运行期间读取挂载的 token 和 proxy 设置 — 这是该 namespace 的 RBAC 边界,而不是 admission 可以封闭的范围。

  • 在这些 policies 之外,mount 仅由 RBAC 控制。 在 Connectors approval flags 关闭时 — 这是默认状态 — driver 会为 service account 可以 get 的任何 Pod mount Connector,而产品会将该权限授予 Connector 作用域内的每个 service account:对于普通 Connector,是其自身的 namespace;对于 project-level Connector,是项目中的每个 namespace;对于 kube-public 中的 cluster-level Connector,则是整个 cluster。Rule 3 将其转变为“仅限 Tekton,且只能来自 template”;没有该 rule,将凭证移入 Connector 后,虽然 namespace 中不再存在明文密码,但仍未移除使用该凭证进行 push 的能力。

  • Step override 无法改变实际运行的内容。 taskRunSpecs[].stepSpecs(转换后为 v1beta1 stepOverrides)仅携带计算资源,因此 run 无法通过它们替换 copy step 的 image 或 command;这些内容不受约束。

  • pod-template 检查采用 denylist。 Rule 1 会拒绝已知可重定向流量或执行的五个 key。未来 Tekton 或 Kubernetes 中具有相同效果的字段,在加入列表之前不会受到覆盖。

  • 一个 Connector,一个 namespace。 Connector 是 namespaced API object,产品的 Connector level 则是在此基础上的 namespace 约定:cluster-level Connector 位于指定的共享 namespace(Connectors 文档中的 kube-public),并且可在整个 cluster 中读取 — 在没有 rule 3 时也可在整个 cluster 中 mount;project-level Connector 位于项目的 namespace,普通 Connector 位于其自身的 namespace。每个 level 都以相同方式引用 — 使用显式的 namespace/name;裸名称始终解析到 run 自身的 namespace,绝不会解析到共享 namespace — 因此固定的 reference 对任意 level 都有效:位于 cluster level 的 production Connector 固定为 kube-public/<name>。另一个 namespace 中同名的 Connector 是不同的 object,按设计不计入。Precondition 会与单个 <production-connector> 进行比较;只有在将每个 mountsProductionConnector variable 扩展为 reference 列表后,才会评估第二个 production Connector。在下方的替换内容中,使用的是 singleRefs 和 pluralRefs,也就是每个 rule 的 recognition preamble 所定义的两个 variable,因此同一个条目可以粘贴到你部署的每个 rule 的 mountsProductionConnector 条目上 — 只命名 connectorRefs 的形式虽然可以编译,但在未定义该变量的 rules 中会解析失败,而 precondition 出错的 rule 会拒绝所有匹配的请求:

    - name: mountsProductionConnector
      variable:
        jmesPath: "length([singleRefs, pluralRefs] | [] | [?@ != ''] | [?contains(['ns-a/prod-a', 'ns-b/prod-b'], @)]) > `0`"

    mount Connector 的 run 如果位于 <pipeline-namespace> 列表之外的 namespace 中,就会被拒绝。来自多个 namespace 的 promotion 可以共享一个集合 — 只要在每个 rule 中列出所有 namespace,并且它们共享 template 名称以及 approver 和 maintainer 列表;需要独立列表的 namespace 则应使用 namespaced Policy(使用 Policy 收紧 namespace)。Task 的新版本属于 template 更改:采用前请重新读取其 parameter 和 result 契约。

  • Kyverno 的 resource filters 不在 policies 的作用范围内。 默认情况下,Kyverno 完全不会评估 kube-system、kube-public、kube-node-lease 以及其自身 namespace 中的请求。在这些 namespace 中创建的 Pod、TaskRun 或 PipelineRun,无论 mount 了什么,都不会被本页面的任何 rule 看到;在这些 namespace 中创建 workload 是管理员的权限,并且仍然如此。

  • Audit 不会阻止任何操作。 它只负责记录。观察窗口结束后仍处于 Audit 的 rule,就是已被悄然关闭的 rule。

  • 这里没有表达“提交者不得批准自己的 promotion”。 职责分离需要将 run 的发起者与 approver 进行关联,而 AccessPolicy check 和 rule 5 都不会执行此操作 — rule 5 限制的是名称集合,而不是谁作出响应。

  • 跨 rules 的共享 context 不是 ClusterPolicy feature。 每个 rule 都携带自己的 context,因此在识别 Connector 的九个 rule 条目中都会重复 Connector recognition preamble;减少重复的方法请参阅将 rules 合并到更少的 objects。Kyverno 基于 CEL 的 ValidatingPolicy 会计算一次 variables,并在相关的 validations 之间共享它们;其 image() library 则解析 registry、repository、tag 和 digest — 这是这些 rules 的自然后续归宿,但代价是需要用 CEL 重写它们。

  • Kyverno 的可用性属于契约的一部分。 每个 policy 都声明 webhookConfiguration.failurePolicy: Fail,因此 Kyverno 不可用时,匹配的请求会被拒绝,而不是未经检查就被允许。由于 run rules 会匹配 cluster 上每个 PipelineRun 和 TaskRun 的创建 — 成本很低,因为 precondition 只是字符串比较 — 一次 outage 会停止所有 Tekton run,而不仅是 promotion;又由于 rule 3 会匹配每个 Pod 的创建,部署该 rule 后,一次 outage 会停止整个 cluster 中的每个 Pod — 以及通过生成的 controller rules 停止每个 Deployment、Job 等对象。请据此规划 Kyverno deployment 的规模。将 rule 3 的 match 缩小到能够访问 Connector 的 namespace,是一种合理的权衡;这样,来自未列出 namespace 的 mount 就会交由 driver 自身的 RBAC 检查处理,相关说明见上面相隔两项的内容。

  • Tekton 的 validation webhook 也属于其中一环。 Run rules 之所以只匹配 CREATE,是因为 Tekton 自身的 validating webhook 会拒绝对 run 的 spec 进行除 spec.status(推出)之外的任何更改,因此 run 被 admission 时采用的内容就是它实际运行的内容。该前提又依赖于 webhook 处于 failurePolicy: Fail 状态:当它不可用时,PipelineRun 更新会被 API server 拒绝,而不是未经检查就被允许。弱化或移除其 webhook 配置是 cluster 管理员的操作,不在本页面模型的范围内。

排查

  • 合规的 promotion 被拒绝。 阅读拒绝消息:其中会列出 policy 和 rule,并打印违规值。最常见的原因是某个 placeholder 未在所有位置完成替换、Connector reference 的 namespace 与 <production-connector> 不同,以及 rule 1、2、3 和 4 之间的 template 列表发生了偏差。
  • 普通 copy 被拒绝。 它 mount 了 production Connector — 检查其 workspaces。不需要 production 的 copy 不得持有 production credential;请为其提供 Secret 或其他 Connector。
  • promotion 被 sources-carry-release-tags 拒绝。 source tag 与任何 approved pattern 都不匹配,或者 reference 完全不带 tag(隐式的 latest)。请 promotion 带有 release tag 的 build 或 image 的 digest;如需接受其他约定,请将其 pattern 添加到列表中。digest-pinned image 的 .sig/.att companion 会被默认列表接受。使用Bundling中的折叠式 promotion-content rule 时,这项拒绝以及另外四项内容拒绝都会显示在该标题下;消息中回显的值可用于区分它们。
  • 命名了合法 approver 的 run 被拒绝。 该 identity 未出现在 promotion-approvers 中的 allowedApprovers,或者其中的拼写与 ApprovalTask 预期的拼写不同(包括 group: prefix)。拒绝消息会打印这两个列表。
  • 启用可选的 AccessPolicy 层后,ApprovalTask 为 approved,但 promotion Pod 始终没有获得 credential。 Connector 通过 AccessRequest 释放 credential;请检查该对象及其依赖的三项内容:kubectl get accessrequest -n <connector-namespace>(request 位于 Connector 的 namespace 中;其 status 会指出未通过的 check)、AccessPolicy 的 approvers 和 numberOfApprovalsRequired 是否满足 ApprovalTask 上的 status.approversResponse(Connector 可能要求的 approver 与 template 收集的 approver 不同,或要求更多 approver),以及谁可以批准中列出的 feature flags。
  • 尽管 srcTLSVerify 或 dstTLSVerify 为 "false",copy 仍因 x509: certificate signed by unknown authority 失败。 template 未声明该 parameter,因此 Tekton 会将其从 run 中丢弃,而 Task 会回退到其默认值 "true"。请使用 promotion 页面中的 template,该 template 声明了两者。
  • 真实 promotion run 的 Pod 被 no-pod-outside-a-template 拒绝,或者其 TaskRun 被 no-taskrun-outside-a-template 拒绝。 消息会打印 creator、owner chain(Pod 的 TaskRun,然后是 PipelineRun)以及 parent run 被发现带有的 pipelineRef。空的 parentRef 表示 owner references 在该 namespace 中未指向任何 run — 该对象不是由 run 的 controller 创建的,Pod 的 TaskRun 不属于某个 run,或者 reference 名称下确实存在对象,但它带有不同的 uid,rules 会将其视为完全没有 parent;对于被拒绝的非空值,其名称可能是位于该 rule 的 templateNames 之外的 template、resolver(对于 catalog-served templates,请同时采用两个 variant:rule 1 的 variant 用于 run,以及rules 2 和 3 的 parent test)、带有 url 的 hub reference、非 type 的 artifact parameter,或 inline pipelineSpec。确保 templateNames 在 rules 1、2 和 3 中完全一致。
  • 手写的 TaskRun 被 taskrun-owner-references-set-by-the-controller 拒绝。 它带有一个 ownerReferences 条目,其中的 controller: true 命名了一个 PipelineRun,该值只能由 Tekton controller 写入 — rule 3 信任该值。该 rule 会比较整个 reference,因此,对已有 reference 的某个字段进行编辑也会以相同方式被拒绝。请删除该 reference:直接创建的 TaskRun 不属于任何 run。
  • Deployment、Job 或其他 workload 被 autogen-no-pod-outside-a-template 拒绝。 它 mount 了 production Connector,而 rule 3 将该 Connector 保留给 Tekton controller 为 promotion template 创建的 Pod — 这是设计如此;此类 workload 不得持有 production credential。
  • 违规的 run 被允许通过。 首先检查该 rule 的 policy 是否确实已部署 — 如果只部署了子集,缺失 rules 所覆盖的情况按设计会被允许。然后检查 precondition 是否触发:run 必须在 connectors-csi workspace 上命名该 Connector,且使用什么算作 promotion中显示的两种形式之一。永不匹配的 precondition 不会产生拒绝或 report 条目 — 此处的沉默表示“未评估”,而不是“合规”。
  • 非 maintainer 可以更新 template,但无法创建或删除它。 该 rule 缺少 allowExistingViolations: false,Kyverno 将此次更新视为预先存在的违规。admission controller 日志会为该 request 显示 skipping the rule evaluation as pre-existing violations are allowed。
  • policy 显示 READY=False。 其 rule 编译失败。失败 policy 上的 kubectl describe clusterpolicy 会报告违规 expression。
  • 拒绝消息呈现为空字符串。 该消息引用了未解析的 context variable。请检查 Kyverno admission controller 日志以获取底层错误;context loader 失败会记录在那里,而不会显示在拒绝消息中。
  • 完全没有 PolicyReport。 Reports 由 reports controller 生成;请确认它正在运行,并记住 background: false policies 只会针对 admission requests 生成 report。
  • promotion pipeline 本身无法更新。 requester 要么未被列为 <template-maintainer> — 请添加 identity kubectl auth whoami reports,或让列表中的 identity 执行更改 — 要么此次编辑指定了 allowedApprovers 之外的 approver,而 rule 5 无论请求者是谁都会拒绝该编辑。

了解更多