テック技報最新号へ →
コード

Google Cloud のアプリから GitHub API を叩くとき、PAT も App の秘密鍵も持たずに Octo STS で短命トークンをもらう

Cloud Run / GAE / GCE のサービスアカウントの OIDC ID トークンを Octo STS に渡すと、Trust Policy で検証したうえで権限を絞った GitHub App のインストールトークン(短命)が返ってくる。新しい GitHub App も、秘密鍵や PAT の保管も要らない。

@azu_re · 投稿 2026-04-16公開
#github#oidc#google-cloud#security#token

どんなときに使うか

Slack bot が Issue を作る、バッチが PR にコメントする、など GitHub Actions の外から GitHub API を呼びたいとき。PAT は個人に紐づき、GitHub App を作ると秘密鍵の管理が必要になる。Octo STS(Chainguard の OSS)をすでに Actions 用に動かしているなら、Google のトークンもそのまま受け付けられる。

流れ

  1. アプリがメタデータサーバーから ID トークンを取る(aud は Octo STS のドメイン)。
  2. Octo STS の交換エンドポイントに Bearer で渡す。
  3. Octo STS がリポジトリの Trust Policy と照合し、ghs_... のトークンを返す。
  4. そのトークンで Octokit などから API を呼ぶ。トークンは使い捨て。

1. ID トークンを取る

Cloud Run・GAE・GCE などではメタデータサーバーから直接取れる。IAM Credentials API を呼んだり roles/iam.serviceAccountOpenIdTokenCreator を付けたりは不要。

ts
import { GoogleAuth } from "google-auth-library";

const AUDIENCE = "octo-sts.example.com";
const client = await new GoogleAuth().getIdTokenClient(AUDIENCE);
const idToken = await client.idTokenProvider.fetchIdToken(AUDIENCE);
// iss: https://accounts.google.com / sub: サービスアカウントの数値 ID / email: ...gserviceaccount.com

2. Trust Policy をリポジトリに置く

API を叩きたいリポジトリの .github/chainguard/<identity>.sts.yaml。

yaml
issuer: https://accounts.google.com
subject: "123456789012345678901"   # サービスアカウントの数値 ID(メールではない・変わらない)
claim_pattern:
  email: "my-app@my-project\\.iam\\.gserviceaccount\\.com"
permissions:
  issues: write

権限が管理画面ではなくファイルになるので、PR でレビューでき履歴も残る。

3. 交換して使う

ts
const res = await fetch(
  "https://octo-sts.example.com/sts/exchange?scope=myorg/myrepo&identity=my_bot_issue_writer",
  { headers: { Authorization: `Bearer ${idToken}` } },
);
const { token } = await res.json();          // {"token":"ghs_..."}
const octokit = new Octokit({ auth: token });
await octokit.issues.create({ owner: "myorg", repo: "myrepo", title: "..." });

注意点

  • 渡せる権限は、Octo STS が使っている GitHub App に付けた権限の範囲まで。足りなければ App 側を広げる必要がある。
  • subject は数値 ID で固定し、email も claim_pattern で照合して、同じ issuer(accounts.google.com)の別アカウントのトークンを通さない。aud も Octo STS のドメインにする。
  • 前提として Octo STS を自分たちでデプロイしている(または公開インスタンスを使う)こと。
  • GitHub Actions からなら、Actions の OIDC(token.actions.githubusercontent.com)で同じ仕組みが使える。

関連

出典

関連記事