如何以编程方式确定 Bitbucket API token 执行 Git 操作所需的 scopes?
结论
通过 HTTPS 使用 Bitbucket Cloud API token 执行 git push,需要同时授予以下两个 scopes:
read:repository:bitbucket
write:repository:bitbucket
你当前只配置了写权限,还需要补充 read:repository:bitbucket。官方文档 Using API tokens 列出了 Git 克隆和推送所需的权限组合。
仅凭题目中的 403 错误,无法以编程方式获得完整的缺失 scopes 列表。响应头可以辅助诊断,但需要确认它们是否适用于当前凭据类型和请求。
为什么写权限还不够
API token 的 scopes 相互独立。write:repository:bitbucket 允许修改仓库数据,但不会自动授予 read:repository:bitbucket;增加 Admin scope 也不会自动获得仓库读写权限。API token permissions 对此有说明。
因此,不能仅根据 Modify your repositories 这句描述,就认定 token 具备 Git 推送所需的全部权限。
如何修复并验证
创建一个同时包含上述两个 scopes 的 Bitbucket Cloud API token,然后让 Git 使用新 token。
先检查远程地址:
git remote -v
题目中的地址使用 HTTPS,可以将其设置为包含 Bitbucket username 的形式:
git remote set-url origin https://myself@bitbucket.org/myself/therepo.git
第一个 myself 是用于认证的 Bitbucket username,路径中的 myself 是 workspace 标识,使用时需要分别替换。username 区分大小写,应与账号设置一致;出现 password 提示时,输入 API token。认证方式说明
如果怀疑 credential helper 仍在提供旧凭据,可以仅在本次命令中禁用它:
git -c credential.helper= ls-remote origin
成功列出 refs 可以验证读取访问,但不能证明写入权限可用。有待推送的提交时,再执行推送:
git -c credential.helper= push origin HEAD:master
这条命令会实际推送当前提交到远端 master,请按目标分支调整。不要把 API token 直接写入远程 URL,以免将凭据保存在 Git 配置中。
能否通过程序查询所需 scopes
需要区分当前凭据拥有哪些 scopes,以及目标操作要求哪些 scopes。题目中的错误只说明权限不足,没有返回两者的差集。
Atlassian 提供了通过响应头查看 token scopes 的命令行示例,其中使用 x-oauth-scopes。该示例针对 access token,凭据类型是 repo_access_token,不能直接保证个人 API token 也会返回相同字段。
对于 API token,可以先检查一个实际 REST 请求的响应头:
curl --silent --show-error \
--dump-header - \
--output /dev/null \
--user 'YOUR_ATLASSIAN_EMAIL' \
'https://api.bitbucket.org/2.0/repositories/myself/therepo'
curl 提示输入密码时,输入 API token。这里调用的是 REST API,Basic authentication 使用 Atlassian account email;前面的 Git HTTPS 示例使用 Bitbucket username。API 认证说明
如果响应包含 x-oauth-scopes 或 x-accepted-oauth-scopes,可以将它们作为诊断线索。某个 REST endpoint 的 scope 要求不能直接视为 git push 的完整要求,响应头缺失也不代表 token 没有权限。
对于自动化脚本,可以维护经过官方文档确认的操作与 scopes 映射,并记录创建 token 时选择的权限。本题中,push 对应上述读取和写入两个 scopes。REST API 操作则应查看对应 endpoint 文档,使用其中针对 API token 的权限要求,避免与 OAuth scopes 混用。
SSH 和强制推送需要注意什么
题目中的远程地址是 https://...,这次认证不会使用你上传的 SSH key。如果希望使用该密钥,需要将远程地址改为 SSH 形式:
git remote set-url origin git@bitbucket.org:myself/therepo.git
此时 Git 使用 SSH 身份验证,不再使用 HTTPS API token。前提是对应私钥可用,且绑定账号拥有仓库访问权限。
git push -f 没有单独的 API token scope。它仍需要仓库读写 scopes,还要满足分支权限中关于重写历史的限制。即使 token 权限齐全,服务器也可能拒绝强制推送,此时应检查 branch permissions。
原日志中的 You are using an app password for Git over HTTPS 表明,成功推送时使用的是 app password。这只能说明旧凭据那次认证成功,不能证明新 API token 的 scopes 已经足够。日志里的停用日期是当时的提示,不影响本次缺少读取 scope 的判断。
备注:内容仅供参考。
