来自Fork的PR中github-actions[bot]仓库权限被拒的解决方法咨询
解决Fork PR中GitHub Actions无法修改文件的权限问题
核心原因
来自Fork的PR触发的pull_request事件,GitHub会强制限制默认GITHUB_TOKEN为只读权限,同时该事件无法访问原仓库的敏感密钥——这是GitHub的安全机制,防止恶意Fork通过Action获取仓库权限。
可行解决方案
1. 结合pull_request_target事件与个人访问令牌(PAT)
这是最常用的方案,既绕开权限限制,又能安全完成文件修改:
- 生成PAT:在GitHub账号设置中创建一个带
repo全权限的个人访问令牌,仅勾选必要权限,避免过度授权。 - 存储PAT:在原仓库的「Settings → Secrets and variables → Actions」中添加该令牌,命名为
FORK_PR_WRITE_TOKEN。 - 修改Action配置:将触发事件改为
pull_request_target(该事件运行在原仓库上下文,可访问密钥),并在推送步骤使用PAT:
name: Auto Format Code on: pull_request_target: types: [opened, synchronize] jobs: format: runs-on: ubuntu-latest steps: - name: Checkout PR Branch uses: actions/checkout@v4 with: ref: ${{ github.event.pull_request.head.ref }} repository: ${{ github.event.pull_request.head.repo.full_name }} persist-credentials: false # 禁用默认令牌,避免冲突 - name: Run Format Command run: | # 替换为你的格式化命令,比如 go fmt / npm run fmt 等 go fmt ./... - name: Commit & Push Changes run: | git config --global user.name "github-actions[bot]" git config --global user.email "github-actions[bot]@users.noreply.github.com" git add . # 无变更则直接退出 if git diff --cached --quiet; then echo "No formatting changes needed" exit 0 fi git commit -m "chore: auto format code" # 使用PAT推送到Fork仓库的分支 git push https://${{ secrets.FORK_PR_WRITE_TOKEN }}@github.com/${{ github.event.pull_request.head.repo.full_name }}.git ${{ github.event.pull_request.head.ref }}
- 安全提示:
pull_request_target会加载原仓库的环境,务必避免执行Fork仓库中的自定义脚本或未知代码,仅使用官方格式化工具。
2. 要求贡献者在Fork仓库本地完成格式化
直接在贡献指南中明确要求:
- 贡献者提交PR前,本地运行格式化命令(如
fmt)并提交变更。 - 在原仓库配置
pull_request事件的Action,仅检查代码是否符合格式化规范,不做修改——如果不符合,直接在PR评论中提示贡献者自行调整。
3. 使用GitHub App替代PAT(适合团队场景)
如果是组织级仓库,更安全的方式是创建GitHub App:
- 注册一个GitHub App,分配「仓库内容读写」权限。
- 将App安装到原仓库及需要处理的Fork仓库(需Fork仓库管理员配合)。
- 在Action中使用App生成的临时令牌进行推送操作,避免使用个人账号的PAT,权限更可控。
内容的提问来源于stack exchange,提问作者Kinwolf
相关产品推荐
相关产品推荐

