解决 Bazel 报错 Remote cache upload failed 403 远程缓存写入被拒修复
排查 Bazel 编译大型 C++/Java/Go 单体仓库报 WARNING: Remote cache upload failed: 403 Forbidden,分析 远端缓存鉴权与 --remote_upload_local_results 设定。
问题现象
在 CI/CD 流水线中运行 Bazel 构建时,虽然命中缓存,但构建结束时终端密集输出警告:
WARNING: Remote cache upload failed: 403 Forbidden: PUT https://cache.internal.corp:8080/ac/a91b... failed: unauthorized
INFO: 1482 processes: 1200 remote cache hit, 282 local.
触发根因
- Bazel 命令行配置了
--remote_upload_local_results=true尝试向远端构建缓存(如 bazel-remote 或 BuildBarn)上传编译产物; - CI 构建机器使用的 API Token 或 mTLS 证书只被授予了只读(Read-Only)权限,缺少对 Action Cache (AC) 和 Content Addressed Storage (CAS) 的写入特权;
- 远端 HTTP 缓存后端限制了单条 Action 结果的体积上限。
解决步骤
针对开发人员机器关闭写入仅保留读取加速
在非主干 CI 分支中仅允许下载缓存:
# .bazelrc
build:local --remote_cache=https://cache.internal.corp:8080
build:local --remote_upload_local_results=false
为受信任的 CI 主干构建流水线提供写权限 Token
在流水线环境变量中传递特权头部:
build:ci --remote_header=Authorization="Bearer ${BAZEL_CACHE_WRITE_TOKEN}"
build:ci --remote_upload_local_results=true
确保服务端 bazel-remote 配置了正确的写入用户组
调整服务器端 --htpasswd-file 或认证策略以放行 CI 节点网段。
验证确认
重新执行 CI 构建验证:
本地编译产物秒级推入远程缓存,403 警告彻底清除,全团队构建耗时缩短 80%。


