🚨

PRを自動作成するGitHub Actionsで403エラーが発生したときの対応方法

2024/03/31に公開

事象

YAMLファイルを新規作成し、GitHub Actionsが実行されたところ、以下のエラーが発生しました。

GET https://api.github.com/repos/{アカウント名}/{リポジトリ名}/pulls/1: 403 - Resource not accessible by integration // See: https://docs.github.com/rest/pulls/pulls#get-a-pull-request

なお参考までに、今回実行しようとしたYAMLファイルは、指定したブランチのpushをトリガーにリリースPRを自動で作成してくれる git-pr-release[1] を実行するためのものです。

原因

このリポジトリでGitHub Actionsのワークフローを実行するときに必要なGITHUB_TOKENに付与された権限が、PRの作成を許可していないことが原因です。

対応方法

権限の変更方法2つ

  1. このリポジトリでワークフローを実行するときに、GITHUB_TOKENに付与されたデフォルトの権限を選択できます。
  2. また、YAMLを使用して、ワークフローでより詳細な権限を指定することもできます。

後者の「2」の方がより安全と思われます。

1. このリポジトリでワークフローを実行するときに、GITHUB_TOKENに付与されたデフォルトの権限を選択する方法

リポジトリの [Settings] から、 [Code and automation] > [Actions] > [General] を選択します。

設定画面

やや下方に、 [Workflow permissions] という欄があり、ここからGITHUB_TOKENに付与されたデフォルトの権限を選択できます。

Workflow permissions

ここの設定を、 Read and write permissions に変更し、さらに Allow GitHub Actions to create and approve pull requests をチェックすると、GitHub ActionsによるPRの作成ができるようになります。

しかし、なんでも許可してしまうのは良くない気がしますね。

2. YAMLを使用して、ワークフローでより詳細な権限を指定する方法

GITHUB_TOKENに付与されたデフォルトの権限は、 Read repository contents and packages permissions のままにしておき、
YAMLファイルに権限[2]を明示的に記載します。

permissionsの種類:

permissions:
  actions: read|write|none
  checks: read|write|none
  contents: read|write|none
  deployments: read|write|none
  id-token: read|write|none
  issues: read|write|none
  discussions: read|write|none
  packages: read|write|none
  pages: read|write|none
  pull-requests: read|write|none
  repository-projects: read|write|none
  security-events: read|write|none
  statuses: read|write|none

記載例

今回は、GitHub ActionsのワークフローでPRの作成を許可したいので、

pull-requests: write

を記載する必要があります。
さらに、リポジトリのコンテンツを読み取るために

contents: read

の権限も必要です。これがないと今度は以下のエラーが発生します。

remote: Repository not found.
Error: fatal: repository 'https://github.com/{アカウント名}/{リポジトリ名}/' not found

(デフォルトの権限が上書きされるのかな...?)

よって、記載例としては次のようなものになります。

name: Create a release pull request

# https://docs.github.com/en/actions/using-jobs/assigning-permissions-to-jobs#defining-access-for-the-github_token-scopes
permissions:
  contents: read
  pull-requests: write

jobs:
  create-release-pr:
  # ...

全文: Gist

脚注
  1. https://github.com/x-motemen/git-pr-release ↩︎

  2. https://docs.github.com/en/actions/using-jobs/assigning-permissions-to-jobs#defining-access-for-the-github_token-scopes ↩︎

Discussion