如何验证依赖的 Action 哈希?

解读

在国内 Git 面试中,面试官问“如何验证依赖的 Action 哈希”,并不是想听你背诵 Git 命令,而是考察你对“供应链安全”在 GitHub Actions 场景下的落地思路。
核心诉求有三点:

  1. 知道 Action 的“版本”本质上是 Git 仓库的某个 commit,必须锁定到不可变的 40 位 SHA-1/SHA-256。
  2. 能把“锁定”与“验证”拆成两步:CI 流程里先校验,再运行;本地开发时同样能复现校验。
  3. 清楚国内网络隔离、镜像源、企业私服等现实,给出的方案在 Gitee、GitLab-EE、Jenkins 插件市场同样跑得通,而不是只停留在“GitHub 官方文档怎么说”。

知识点

  1. Action 的引用方式
    • owner/action@ref 中 ref 可以是分支、标签或 commit SHA;只有 commit SHA 不可变。
  2. 哈希锁定
    • 在 .github/workflows/*.yml 里把 @v3.1.0 改成 @sha-256:7d4b3c… 或 @a1b2c3…(40 位)。
  3. 校验时机
    • 本地:用 git ls-remote https://github.com/owner/action.git refs/tags/v3.1.0 拿到对应 SHA,与 yml 里写的比对。
    • CI:在 job 最开始加一步 “pin-verify”,用 gh api 或 git ls-remote 再拉一次,确认未被篡改。
  4. 国内加速
    • 把 Action 仓库镜像到 Gitee 或 GitLab-EE,CI 里把 actions/checkout 指向内网地址;校验时同样比对镜像库的 SHA,保证“源头锁定”与“传输过程”双重一致。
  5. 审计留痕
    • 把每次校验结果(SHA、时间、校验人)写到 git notes 或单独 security.log 文件,随仓库一起版本化,方便合规审计。

答案

步骤化落地:

  1. 锁定:在 workflow 文件里一律使用 commit SHA,例如
    uses: actions/checkout@a12a3943a8b9c9c847307a9f4f4b1a890e0ad9f0
    并在注释里写明“对应 tag v3.1.0,验证人张三 2024-06-01”。
  2. 本地验证:
    git ls-remote https://github.com/actions/checkout.git refs/tags/v3.1.0 \
    | awk '{print $1}' \
    | grep -q a12a3943a8b9c9c847307a9f4f4b1a890e0ad9f0 && echo "OK" || echo "TAMPERED"
    
    若公司内网已镜像,只需把 URL 换成 https://gitee.com/mirror/checkout.git 即可。
  3. CI 二次校验:
    在 workflow 最前面加 job:
    verify-pins:
      runs-on: [self-hosted, linux]
      steps:
        - name: Check action SHA
          run: |
            set -e
            for pin in $(grep -h "uses:" .github/workflows/*.yml | awk '{print $2}'); do
              repo=$(echo $pin | cut -d@ -f1)
              sha=$(echo $pin | cut -d@ -f2)
              remote="https://gitee.com/mirror/${repo##*/}.git"
              git ls-remote $remote | awk '{print $1}' | grep -q $sha
            done
    
    校验失败直接 exit 1,阻断后续流程。
  4. 结果留痕:
    把 git ls-remote 输出、校验时间、运行机器指纹追加到 security/action-pin.log,由 git add 随代码一起提交,保证可追溯。

拓展思考

  1. 如果 Action 作者强制推送改写历史,本地和镜像库的 SHA 会同时变化,如何第一时间发现?
    答:在镜像服务器上启用 receive.denyNonFastForwards = true,并给关键 Action 加 git notes 签名;CI 校验阶段再验证签名,防止“合法”但恶意的 force-push。
  2. 国内监管要求“源代码出境审批”,直接把 GitHub Action 拉到公网 Runner 已不合规,如何既锁定哈希又满足数据不出境?
    答:在 GitLab-EE 里用 include:local 方式引入同一套 workflow 模板,Action 仓库通过 git subtree 或 submodule 方式内嵌到内网仓库,CI 校验时比对 subtree 的 commit SHA,实现“完全离线、哈希锁定、代码不出境”。