Compare commits

..
Author SHA1 Message Date
Parker BrownandCopilot 60ab571217 Merge origin/main into enterprise-app-enterprise-slug
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-04-30 12:00:48 -07:00
Parker BrownandCopilot de40320cff Test enterprise retry path
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-20 23:11:27 -07:00
Parker BrownandCopilot 8b90615b3f Extract installation auth helper
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-20 23:07:08 -07:00
Parker BrownandCopilot a2a14fd880 Simplify enterprise target flow
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-20 22:49:57 -07:00
Parker BrownandCopilot 7b2a5fbdc3 Restore failure semantics
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-20 22:43:14 -07:00
Parker BrownandCopilot c28e731c85 Clarify enterprise input wording
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-20 22:39:53 -07:00
Parker BrownandCopilot f942b7797f Rename enterprise input
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-20 22:34:06 -07:00
Parker BrownandCopilot 17e8e94b15 Build dist files for testing
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-19 23:05:50 -07:00
Parker BrownandCopilot 50b5a08363 Stabilize stderr snapshots
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-13 19:05:44 -07:00
Parker Brown 9175c03232 Upgrade GitHub Action to v3 2026-03-13 18:35:48 -07:00
Parker BrownandCopilot f90c44a773 Remove redundant enterprise tests
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-13 18:32:08 -07:00
Parker Brown 7b114ed594 Add newline to .gitignore 2026-03-13 18:25:06 -07:00
Parker BrownandCopilot c7725c064d Apply suggestions from code review
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-03-13 18:24:24 -07:00
Parker BrownandCopilot 4f9eeddfa7 Use direct enterprise installation route
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-13 18:14:05 -07:00
Parker BrownandCopilot 77d42ce310 Merge latest origin/main
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-13 18:06:24 -07:00
Parker BrownandCopilot 2156e19368 Remove dist changes
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-13 16:03:39 -07:00
Parker BrownandCopilot b24274086f Merge origin/main into enterprise-app-enterprise-slug
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-13 16:01:58 -07:00
Stefan Petrushevski 14350b6aaa bump version 2025-08-28 10:26:30 +02:00
Stefan Petrushevski 6cf7b5f22a update tests with enterprise-slug 2025-08-28 10:23:07 +02:00
StefanandParker Brown 22e6bc6b49 Update lib/main.js
Co-authored-by: Parker Brown <17183625+parkerbxyz@users.noreply.github.com>
2025-08-28 09:34:44 +02:00
StefanandParker Brown 3b3f07c3d1 Update lib/main.js
Co-authored-by: Parker Brown <17183625+parkerbxyz@users.noreply.github.com>
2025-08-28 09:34:29 +02:00
StefanandParker Brown 7b860611c2 Update lib/main.js
Co-authored-by: Parker Brown <17183625+parkerbxyz@users.noreply.github.com>
2025-08-28 09:34:21 +02:00
StefanandParker Brown a84c82dc20 Update action.yml
Co-authored-by: Parker Brown <17183625+parkerbxyz@users.noreply.github.com>
2025-08-28 09:34:12 +02:00
StefanandParker Brown 81e8c224df Update README.md
Co-authored-by: Parker Brown <17183625+parkerbxyz@users.noreply.github.com>
2025-08-28 09:34:01 +02:00
StefanandParker Brown 7434028a6d Update README.md
Co-authored-by: Parker Brown <17183625+parkerbxyz@users.noreply.github.com>
2025-08-28 09:33:49 +02:00
Stefan Petrushevski 46f9f788b8 improve installation match; refactor test per copilot review 2025-07-08 17:52:25 +02:00
Stefan Petrushevski 3c69395e16 update package version 2025-07-08 17:22:19 +02:00
Stefan Petrushevski 55b8c24e8d tests; update README 2025-07-08 17:05:18 +02:00
Stefan Petrushevski cbc2930e9b enterprise input; logic to generate ent token 2025-07-08 15:04:32 +02:00
42 changed files with 1533 additions and 3866 deletions

No files matched your search

+13 -57
View File
@@ -1,7 +1,6 @@
name: release
on:
workflow_dispatch:
push:
branches:
- "*.x"
@@ -18,67 +17,24 @@ jobs:
name: release
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
# build local version to create token
- uses: actions/checkout@v6
with:
persist-credentials: false
- uses: actions/setup-node@v6
with:
node-version-file: package.json
- run: npm ci
- run: npm run build
- uses: ./
id: app-token
with:
app-id: ${{ vars.RELEASER_APP_ID }}
private-key: ${{ secrets.RELEASER_APP_PRIVATE_KEY }}
- uses: googleapis/release-please-action@45996ed1f6d02564a971a2fa1b5860e934307cf7 # v5.0.0
id: release-please
with:
token: ${{ steps.app-token.outputs.token }}
config-file: ${{ github.ref_name == 'beta' && 'release-please-config.beta.json' || 'release-please-config.json' }}
manifest-file: .release-please-manifest.json
target-branch: ${{ github.ref_name }}
- uses: actions/checkout@v7
if: steps.release-please.outputs.prs_created == 'true'
with:
ref: ${{ fromJSON(steps.release-please.outputs.pr).headBranchName }}
token: ${{ steps.app-token.outputs.token }}
- uses: actions/setup-node@v6
if: steps.release-please.outputs.prs_created == 'true'
with:
node-version-file: package.json
- run: npm ci
if: steps.release-please.outputs.prs_created == 'true'
- run: npm run build
if: steps.release-please.outputs.prs_created == 'true'
- run: git add dist
if: steps.release-please.outputs.prs_created == 'true'
- uses: dsanders11/github-app-commit-action@2bbcd331016d8c950b05a24b56e7eb9cb50d545e # v2.1.0
if: steps.release-please.outputs.prs_created == 'true'
with:
message: "chore: update dist files"
token: ${{ steps.app-token.outputs.token }}
fail-on-no-changes: false
- name: Update major version tag
id: update-major-tag
if: steps.release-please.outputs.release_created == 'true' && github.ref_name != 'beta'
uses: octokit/request-action@b91aabaa861c777dcdb14e2387e30eddf04619ae # v3.0.0
continue-on-error: true
with:
route: PATCH /repos/${{ github.repository }}/git/refs/tags/v${{ steps.release-please.outputs.major }}
sha: ${{ steps.release-please.outputs.sha }}
force: true
env:
GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
- name: Create major version tag
if: steps.release-please.outputs.release_created == 'true' && github.ref_name != 'beta' && steps.update-major-tag.outcome == 'failure'
uses: octokit/request-action@b91aabaa861c777dcdb14e2387e30eddf04619ae # v3.0.0
with:
route: POST /repos/${{ github.repository }}/git/refs
ref: refs/tags/v${{ steps.release-please.outputs.major }}
sha: ${{ steps.release-please.outputs.sha }}
# install release dependencies and release
- run: npm install --no-save @semantic-release/git semantic-release-plugin-github-breaking-version-tag
- run: npx semantic-release --debug
env:
GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
+3 -3
View File
@@ -21,7 +21,7 @@ jobs:
name: integration
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
@@ -36,7 +36,7 @@ jobs:
# do not run from forks, as forks don’t have access to repository secrets
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.owner.login == github.event.pull_request.base.repo.owner.login
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version-file: package.json
@@ -61,7 +61,7 @@ jobs:
# do not run from forks, as forks don’t have access to repository secrets
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.owner.login == github.event.pull_request.base.repo.owner.login
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version-file: package.json
@@ -21,7 +21,7 @@ jobs:
env:
COMMIT_MESSAGE: 'feat: update permission inputs'
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version-file: package.json
@@ -31,7 +31,7 @@ jobs:
run: node scripts/update-permission-inputs.js
- name: Commit changes
id: auto-commit
uses: stefanzweifel/git-auto-commit-action@4a55954c782fc1ea30b9056cd3e7a2b40ca8887d # v7.2.0
uses: stefanzweifel/git-auto-commit-action@04702edda442b2e678b25b537cec683a1493fcb9 # v7.1.0
with:
commit_message: ${{ env.COMMIT_MESSAGE }}
- name: Update PR title
-3
View File
@@ -1,3 +0,0 @@
{
".": "3.4.0-beta"
}
-35
View File
@@ -1,35 +0,0 @@
# Changelog
## [3.4.0-beta](https://github.com/actions/create-github-app-token/compare/v3.3.0...v3.4.0-beta) (2026-11-17)
### Features
* support GitHub Actions OIDC authentication ([#411](https://github.com/actions/create-github-app-token/issues/411)) ([8240f10](https://github.com/actions/create-github-app-token/commit/8240f10d3ae05b4d450da83e8e247111a36eaf2c))
## [3.3.0](https://github.com/actions/create-github-app-token/compare/v3.2.0...v3.3.0) (2026-10-12)
### Features
* update permission inputs ([#399](https://github.com/actions/create-github-app-token/issues/399)) ([a47236f](https://github.com/actions/create-github-app-token/commit/a47236f79f79fcbc3532af49fe3a5ded89529b6e))
### Bug Fixes
* **deps:** bump nested undici from 6.24.0 to 6.29.0 ([#403](https://github.com/actions/create-github-app-token/issues/403)) ([12461a3](https://github.com/actions/create-github-app-token/commit/12461a3a794e67c032f1eff5bb95ece9427eb4fb))
* **deps:** bump the production-dependencies group across 1 directory with 3 updates ([#395](https://github.com/actions/create-github-app-token/issues/395)) ([a69c19d](https://github.com/actions/create-github-app-token/commit/a69c19ddfdf8e1ab093900e0064524ce9309c807))
## [3.2.0](https://github.com/actions/create-github-app-token/compare/v3.1.1...v3.2.0) (2026-05-12)
### Features
* add support for enterprise-level GitHub Apps ([#263](https://github.com/actions/create-github-app-token/issues/263)) ([952a2a7](https://github.com/actions/create-github-app-token/commit/952a2a7073df6bfa5f49bc469ec895b6ec1acea4))
* support full repository names in `repositories` input ([#372](https://github.com/actions/create-github-app-token/issues/372)) ([85eb8dd](https://github.com/actions/create-github-app-token/commit/85eb8dd41472213aed25d1a126460e0069138ab6))
### Bug Fixes
* **deps:** bump @actions/core from 3.0.0 to 3.0.1 in the production-dependencies group ([#364](https://github.com/actions/create-github-app-token/issues/364)) ([43e5c34](https://github.com/actions/create-github-app-token/commit/43e5c345bfd4d4f3ecea019ad0042001a09dd857))
* validate private-key input ([#376](https://github.com/actions/create-github-app-token/issues/376)) ([f24bbd8](https://github.com/actions/create-github-app-token/commit/f24bbd89643991c0de27ae823c01791b2c6bafdd))
+15 -28
View File
@@ -64,7 +64,7 @@ jobs:
github_token: ${{ steps.app-token.outputs.token }}
```
### Create a Git committer string for an app installation
### Create a git committer string for an app installation
```yaml
on: [pull_request]
@@ -89,7 +89,7 @@ jobs:
- run: echo "committer string is ${{ steps.committer.outputs.string }}"
```
### Configure Git CLI for an app's bot user
### Configure git CLI for an app's bot user
```yaml
on: [pull_request]
@@ -104,7 +104,6 @@ jobs:
# required
client-id: ${{ vars.APP_CLIENT_ID }}
private-key: ${{ secrets.APP_PRIVATE_KEY }}
permission-contents: write
- name: Get GitHub App User ID
id: get-user-id
run: echo "user-id=$(gh api "/users/${{ steps.app-token.outputs.app-slug }}[bot]" --jq .id)" >> "$GITHUB_OUTPUT"
@@ -113,10 +112,7 @@ jobs:
- run: |
git config --global user.name '${{ steps.app-token.outputs.app-slug }}[bot]'
git config --global user.email '${{ steps.get-user-id.outputs.user-id }}+${{ steps.app-token.outputs.app-slug }}[bot]@users.noreply.github.com'
gh auth setup-git
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
# Git commands like commit and push work using the bot user
# git commands like commit work using the bot user
- run: |
git add .
git commit -m "Auto-generated changes"
@@ -177,12 +173,6 @@ jobs:
body: "Hello, World!"
```
You can include the current repository in the list with `${{ github.repository }}`:
```yaml
repositories: ${{ github.repository }},repo2
```
### Create a token for all repositories in another owner's installation
```yaml
@@ -217,8 +207,8 @@ jobs:
- uses: actions/create-github-app-token@v3
id: app-token
with:
client-id: ${{ vars.APP_CLIENT_ID }}
private-key: ${{ secrets.APP_PRIVATE_KEY }}
app-id: ${{ vars.APP_ID }}
private-key: ${{ secrets.PRIVATE_KEY }}
enterprise: my-enterprise-slug
- name: Call enterprise management REST API with gh
run: |
@@ -230,7 +220,7 @@ jobs:
### Create a token with specific permissions
> [!NOTE]
> Selected permissions must be granted to the specified app installation. Setting a permission that the installation does not have will result in an error.
> Selected permissions must be granted to the installation of the specified app and repository owner. Setting a permission that the installation does not have will result in an error.
```yaml
on: [issues]
@@ -386,16 +376,14 @@ steps:
**Optional:** Comma or newline-separated list of repositories to grant access to.
> [!NOTE]
> If `owner` is set explicitly and `repositories` is empty, access will be scoped to all repositories in the provided repository owner's installation. If `owner` and `repositories` are empty, access will be scoped to only the current repository.
>
> Repository entries may include an owner, for example `owner/repo1`. The owner portion must match the `owner` input, or the current repository owner if `owner` is unset.
> If `owner` is set and `repositories` is empty, access will be scoped to all repositories in the provided repository owner's installation. If `owner` and `repositories` are empty, access will be scoped to only the current repository.
### `enterprise`
**Optional:** The slug of the enterprise account to generate a token for an enterprise installation.
**Optional:** The slug version of the enterprise name to generate a token for enterprise-level app installations.
> [!NOTE]
> The `enterprise` input is mutually exclusive with `owner` and `repositories`. Use it when the GitHub App is installed on an enterprise account. Enterprise installation tokens can call enterprise APIs, but do not grant organization or repository access.
> The `enterprise` input is mutually exclusive with `owner` and `repositories`. GitHub Apps can be installed on enterprise accounts with permissions that let them call enterprise management APIs. Enterprise installations do not grant access to organization or repository resources.
### `permission-<permission name>`
@@ -427,14 +415,13 @@ GitHub App slug.
## How it works
The action creates an installation access token using [the `POST /app/installations/{installation_id}/access_tokens` endpoint](https://docs.github.com/rest/apps/apps?apiVersion=2022-11-28#create-an-installation-access-token-for-an-app).
The action creates an installation access token using [the `POST /app/installations/{installation_id}/access_tokens` endpoint](https://docs.github.com/rest/apps/apps?apiVersion=2022-11-28#create-an-installation-access-token-for-an-app). By default,
The token target depends on the inputs: `enterprise` creates a token for an enterprise installation, `owner` without `repositories` creates a token for all repositories in the owner's installation, `repositories` scopes the token to those repositories, and no target inputs scopes the token to the current repository.
1. The token inherits all the installation's permissions.
2. The token is set as output `token` which can be used in subsequent steps.
3. Unless the `skip-token-revoke` input is set to true, the token is revoked in the `post` step of the action, which means it cannot be passed to another job.
4. The token is masked, it cannot be logged accidentally.
1. The token is scoped to the current repository or `repositories` if set.
2. The token inherits all the installation's permissions.
3. The token is set as output `token` which can be used in subsequent steps.
4. Unless the `skip-token-revoke` input is set to true, the token is revoked in the `post` step of the action, which means it cannot be passed to another job.
5. The token is masked, it cannot be logged accidentally.
> [!NOTE]
> Installation permissions can differ from the app's permissions they belong to. Installation permissions are set when an app is installed on an account. When the app adds more permissions after the installation, an account administrator will have to approve the new permissions before they are set on the installation.
+7 -11
View File
@@ -13,16 +13,16 @@ inputs:
required: false
deprecationMessage: "Use 'client-id' instead."
private-key:
description: "GitHub App private key. If omitted, authenticate using GitHub Actions OIDC (requires client-id and id-token: write, and a private app owned by the workflow repository's organization)."
required: false
description: "GitHub App private key"
required: true
owner:
description: "The owner of the GitHub App installation (defaults to current repository owner)"
required: false
repositories:
description: "Comma or newline-separated list of repositories to grant the token access to (defaults to current repository if owner is unset)"
description: "Comma or newline-separated list of repositories to install the GitHub App on (defaults to current repository if owner is unset)"
required: false
enterprise:
description: "The slug of the enterprise account where the GitHub App is installed (cannot be used with 'owner' or 'repositories')"
description: "The slug version of the enterprise name for enterprise-level app installations (cannot be used with 'owner' or 'repositories')"
required: false
skip-token-revoke:
description: "If true, the token will not be revoked when the current job is complete"
@@ -44,8 +44,6 @@ inputs:
description: "The level of permission to create and retrieve the access token for repository attestations. Can be set to 'read' or 'write'."
permission-checks:
description: "The level of permission to grant the access token for checks on code. Can be set to 'read' or 'write'."
permission-code-quality:
description: "The level of permission to grant the access token to view and manage code quality data. Can be set to 'read' or 'write'."
permission-codespaces:
description: "The level of permission to grant the access token to create, edit, delete, and list Codespaces. Can be set to 'read' or 'write'."
permission-contents:
@@ -84,10 +82,8 @@ inputs:
description: "The level of permission to grant the access token to manage access to an organization. Can be set to 'read' or 'write'."
permission-organization-announcement-banners:
description: "The level of permission to grant the access token to view and manage announcement banners for an organization. Can be set to 'read' or 'write'."
permission-organization-copilot-agent-settings:
description: "The level of permission to grant the access token to view and manage Copilot cloud agent settings for an organization. Can be set to 'read' or 'write'."
permission-organization-copilot-seat-management:
description: "The level of permission to grant the access token for managing access to GitHub Copilot for members of an organization with a Copilot Business subscription. This property is in public preview and is subject to change. Can be set to 'read' or 'write'."
description: "The level of permission to grant the access token for managing access to GitHub Copilot for members of an organization with a Copilot Business subscription. This property is in public preview and is subject to change. Can be set to 'write'."
permission-organization-custom-org-roles:
description: "The level of permission to grant the access token for custom organization roles management. Can be set to 'read' or 'write'."
permission-organization-custom-properties:
@@ -96,8 +92,6 @@ inputs:
description: "The level of permission to grant the access token for custom repository roles management. Can be set to 'read' or 'write'."
permission-organization-events:
description: "The level of permission to grant the access token to view events triggered by an activity in an organization. Can be set to 'read'."
permission-organization-external-properties-for-repos:
description: "The level of permission to grant the access token for managing external custom properties for repositories in an organization. Can be set to 'read', 'write', or 'admin'."
permission-organization-hooks:
description: "The level of permission to grant the access token to manage the post-receive hooks for an organization. Can be set to 'read' or 'write'."
permission-organization-packages:
@@ -142,6 +136,8 @@ inputs:
description: "The level of permission to grant the access token to list and manage repositories a user is starring. Can be set to 'read' or 'write'."
permission-statuses:
description: "The level of permission to grant the access token for commit statuses. Can be set to 'read' or 'write'."
permission-team-discussions:
description: "The level of permission to grant the access token to manage team discussions and related comments. Can be set to 'read' or 'write'."
permission-vulnerability-alerts:
description: "The level of permission to grant the access token to manage Dependabot alerts. Can be set to 'read' or 'write'."
permission-workflows:
+483 -1412
View File
File diff suppressed because it is too large. Load diff
+387 -1181
View File
File diff suppressed because it is too large. Load diff
-48
View File
@@ -1,48 +0,0 @@
// @ts-check
/**
* Creates an auth strategy compatible with `@octokit/auth-app` that authenticates
* as a GitHub App using a GitHub Actions OIDC token instead of a private key.
*
* @param {string} clientId
* @param {Pick<import("@actions/core"), "getIDToken">} core
* @param {import("@octokit/request").request} request
*/
export async function createOidcAuth(clientId, core, request) {
const audience = `${process.env.GITHUB_SERVER_URL || "https://github.com"}/login/oauth`;
const token = await core.getIDToken(audience);
/**
* @param {{ installationId: number, repositoryNames?: string[], permissions?: Record<string, string> }} options
*/
const auth = async ({ installationId, repositoryNames, permissions }) => {
const { data } = await request(
"POST /app/installations/{installation_id}/access_tokens{?client_id}",
{
installation_id: installationId,
client_id: clientId,
repositories: repositoryNames,
permissions,
headers: { authorization: `Bearer ${token}` },
},
);
return { token: data.token, expiresAt: data.expires_at };
};
/**
* @param {import("@octokit/request").request} hookRequest
* @param {string} route
* @param {Record<string, unknown>} [parameters]
*/
auth.hook = (hookRequest, route, parameters) => {
const endpoint = hookRequest.endpoint(route, parameters);
const url = new URL(endpoint.url);
url.searchParams.set("client_id", clientId);
endpoint.url = url.toString();
endpoint.headers.authorization = `Bearer ${token}`;
return hookRequest(endpoint);
};
return auth;
}
+63 -112
View File
@@ -1,6 +1,4 @@
import pRetry from "p-retry";
import isNetworkError from "is-network-error";
import { createOidcAuth } from "./create-oidc-auth.js";
// @ts-check
/**
@@ -32,26 +30,66 @@ export async function main(
throw new Error("Cannot use 'enterprise' input with 'owner' or 'repositories' inputs");
}
// The enterprise installation lookup endpoint doesn't accept OIDC tokens
if (enterprise && !privateKey) {
throw new Error("The 'enterprise' input requires 'private-key'; OIDC authentication is not supported for enterprise installations.");
}
const target = resolveInstallationTarget(enterprise, owner, repositories, core);
if (!privateKey) {
core.info("No 'private-key' provided; authenticating with GitHub Actions OIDC.");
const auth = createAppAuth({
appId: clientId,
privateKey,
request,
});
let authentication, installationId, appSlug;
if (target.type === "enterprise") {
({ authentication, installationId, appSlug } = await pRetry(
() => getTokenFromEnterprise(request, auth, target.enterprise, permissions),
{
shouldRetry: ({ error }) => error.status >= 500,
onFailedAttempt: (context) => {
core.info(
`Failed to create token for enterprise "${target.enterprise}" (attempt ${context.attemptNumber}): ${context.error.message}`
);
},
retries: 3,
}
));
} else if (target.type === "repository") {
({ authentication, installationId, appSlug } = await pRetry(
() =>
getTokenFromRepository(
request,
auth,
target.owner,
target.repositories,
permissions
),
{
shouldRetry: ({ error }) => error.status >= 500,
onFailedAttempt: (context) => {
core.info(
`Failed to create token for "${target.repositories.join(
","
)}" (attempt ${context.attemptNumber}): ${context.error.message}`
);
},
retries: 3,
}
));
} else {
// Otherwise get the installation for the owner, which can either be an organization or a user account
({ authentication, installationId, appSlug } = await pRetry(
() => getTokenFromOwner(request, auth, target.owner, permissions),
{
onFailedAttempt: (context) => {
core.info(
`Failed to create token for "${target.owner}" (attempt ${context.attemptNumber}): ${context.error.message}`
);
},
retries: 3,
}
));
}
const auth = privateKey
? createAppAuth({ appId: clientId, privateKey, request })
: await createOidcAuth(clientId, core, request);
const { authentication, installationId, appSlug } = await pRetry(
() => getTokenFromTarget(request, auth, target, permissions),
createTokenRetryOptions(core, getTokenRetryDescription(target))
);
// Register the token with the runner as a secret to ensure it is masked in logs
core.setSecret(authentication.token);
@@ -94,112 +132,25 @@ function resolveInstallationTarget(enterprise, owner, repositories, core) {
return { type: "owner", owner };
}
const target = normalizeRepositoryTarget(owner, repositories);
const parsedOwner = owner || String(process.env.GITHUB_REPOSITORY_OWNER);
if (!owner) {
core.info(
`No 'owner' input provided. Using default owner '${target.owner}' to create token for the following repositories:${target.repositories
.map((repo) => `\n- ${target.owner}/${repo}`)
`No 'owner' input provided. Using default owner '${parsedOwner}' to create token for the following repositories:${repositories
.map((repo) => `\n- ${parsedOwner}/${repo}`)
.join("")}`
);
} else {
core.info(
`Inputs 'owner' and 'repositories' are set. Creating token for the following repositories:${target.repositories
.map((repo) => `\n- ${target.owner}/${repo}`)
.join("")}`
`Inputs 'owner' and 'repositories' are set. Creating token for the following repositories:
${repositories.map((repo) => `\n- ${parsedOwner}/${repo}`).join("")}`
);
}
return {
type: "repository",
owner: target.owner,
repositories: target.repositories,
};
}
function normalizeRepositoryTarget(owner, repositories) {
const parsedOwner = owner || String(process.env.GITHUB_REPOSITORY_OWNER);
const parsedRepositories = repositories.map(parseRepositoryInput);
const mismatchedRepository = parsedRepositories.find(
(repository) =>
repository.owner &&
repository.owner.toLowerCase() !== parsedOwner.toLowerCase()
);
if (mismatchedRepository) {
throw new Error(
`Repository '${mismatchedRepository.input}' includes owner '${mismatchedRepository.owner}', which does not match the resolved owner '${parsedOwner}'.`
);
}
return {
owner: parsedOwner,
repositories: parsedRepositories.map((repository) => repository.name),
};
}
function parseRepositoryInput(input) {
const parts = input.split("/");
if (parts.length === 1 && parts[0]) {
return { input, owner: "", name: parts[0] };
}
if (parts.length === 2 && parts[0] && parts[1]) {
return { input, owner: parts[0], name: parts[1] };
}
throw new Error(
`Invalid repository '${input}'. Expected 'repository' or 'owner/repository'.`
);
}
function getTokenRetryDescription(target) {
switch (target.type) {
case "enterprise":
return `enterprise "${target.enterprise}"`;
case "repository":
return `"${target.repositories
.map((repository) => `${target.owner}/${repository}`)
.join(",")}"`;
case "owner":
return `"${target.owner}"`;
/* c8 ignore next 2 */
default:
throw new Error(`Unsupported installation target type: ${target.type}`);
}
}
function getTokenFromTarget(request, auth, target, permissions) {
switch (target.type) {
case "enterprise":
return getTokenFromEnterprise(request, auth, target.enterprise, permissions);
case "repository":
return getTokenFromRepository(
request,
auth,
target.owner,
target.repositories,
permissions
);
case "owner":
return getTokenFromOwner(request, auth, target.owner, permissions);
/* c8 ignore next 2 */
default:
throw new Error(`Unsupported installation target type: ${target.type}`);
}
}
function createTokenRetryOptions(core, targetDescription) {
return {
shouldRetry: ({ error }) => error.status >= 500 || isNetworkError(error),
onFailedAttempt: (context) => {
core.info(
`Failed to create token for ${targetDescription} (attempt ${context.attemptNumber}): ${context.error.message}`
);
},
retries: 3,
repositories,
};
}
@@ -271,7 +222,7 @@ async function getTokenFromEnterprise(request, auth, enterprise, permissions) {
} catch (error) {
if (error.status === 404) {
throw new Error(
`No enterprise installation found matching the enterprise slug "${enterprise}".`
`No enterprise installation found matching the name ${enterprise}.`
);
}
-8
View File
@@ -23,14 +23,6 @@ async function run() {
throw new Error("The 'client-id' (or deprecated 'app-id') input must be set to a non-empty string. If using a secret or variable, ensure it is available in this workflow context.");
}
const privateKey = core.getInput("private-key");
if (!privateKey) {
if (!process.env.ACTIONS_ID_TOKEN_REQUEST_URL || !process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN) {
throw new Error("The 'private-key' input must be set to a non-empty string, or the workflow must have 'id-token: write' permissions to authenticate with OIDC. If using a secret or variable, ensure it is available in this workflow context.");
}
if (!core.getInput("client-id")) {
throw new Error("The 'client-id' input is required for OIDC authentication. The deprecated 'app-id' input is only supported with 'private-key'.");
}
}
const enterprise = core.getInput("enterprise");
const owner = core.getInput("owner");
const repositories = core
+419 -356
View File
File diff suppressed because it is too large. Load diff
+37 -10
View File
@@ -2,7 +2,7 @@
"name": "create-github-app-token",
"private": true,
"type": "module",
"version": "3.4.0-beta",
"version": "3.1.1",
"description": "GitHub Action for creating a GitHub App Installation Access Token",
"engines": {
"node": ">=24.4.0"
@@ -16,18 +16,45 @@
},
"license": "MIT",
"dependencies": {
"@actions/core": "^3.0.1",
"@octokit/auth-app": "^8.3.1",
"@actions/core": "^3.0.0",
"@octokit/auth-app": "^8.2.0",
"@octokit/request": "^10.0.8",
"is-network-error": "^1.3.2",
"p-retry": "^8.0.1"
"p-retry": "^8.0.0"
},
"devDependencies": {
"@octokit/openapi": "^24.0.0",
"c8": "^12.0.0",
"esbuild": "^0.28.2",
"@octokit/openapi": "^22.0.0",
"c8": "^11.0.0",
"esbuild": "^0.27.4",
"open-cli": "^9.0.0",
"undici": "^8.11.2",
"yaml": "^2.9.1"
"undici": "^7.24.6",
"yaml": "^2.8.3"
},
"release": {
"branches": [
"+([0-9]).x",
"main",
{
"name": "beta",
"prerelease": true
}
],
"plugins": [
"@semantic-release/commit-analyzer",
"@semantic-release/release-notes-generator",
"@semantic-release/github",
"@semantic-release/npm",
"semantic-release-plugin-github-breaking-version-tag",
[
"@semantic-release/git",
{
"assets": [
"package.json",
"package-lock.json",
"dist/*"
],
"message": "build(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"
}
]
]
}
}
-12
View File
@@ -1,12 +0,0 @@
{
"$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json",
"packages": {
".": {
"prerelease": true,
"prerelease-type": "beta",
"include-component-in-tag": false,
"release-type": "node",
"versioning": "prerelease"
}
}
}
-9
View File
@@ -1,9 +0,0 @@
{
"$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json",
"packages": {
".": {
"include-component-in-tag": false,
"release-type": "node"
}
}
}
+9 -27
View File
@@ -1,7 +1,7 @@
{
"title": "App Permissions",
"type": "object",
"description": "The permissions granted to the fine-grained access token.",
"description": "The permissions granted to the user access token.",
"properties": {
"actions": {
"type": "string",
@@ -43,14 +43,6 @@
"write"
]
},
"code_quality": {
"type": "string",
"description": "The level of permission to grant the access token to view and manage code quality data.",
"enum": [
"read",
"write"
]
},
"codespaces": {
"type": "string",
"description": "The level of permission to grant the access token to create, edit, delete, and list Codespaces.",
@@ -280,27 +272,9 @@
"type": "string",
"description": "The level of permission to grant the access token for managing access to GitHub Copilot for members of an organization with a Copilot Business subscription. This property is in public preview and is subject to change.",
"enum": [
"read",
"write"
]
},
"organization_copilot_agent_settings": {
"type": "string",
"description": "The level of permission to grant the access token to view and manage Copilot cloud agent settings for an organization.",
"enum": [
"read",
"write"
]
},
"organization_external_properties_for_repos": {
"type": "string",
"description": "The level of permission to grant the access token for managing external custom properties for repositories in an organization.",
"enum": [
"read",
"write",
"admin"
]
},
"organization_announcement_banners": {
"type": "string",
"description": "The level of permission to grant the access token to view and manage announcement banners for an organization.",
@@ -388,6 +362,14 @@
"write"
]
},
"team_discussions": {
"type": "string",
"description": "The level of permission to grant the access token to manage team discussions and related comments.",
"enum": [
"read",
"write"
]
},
"email_addresses": {
"type": "string",
"description": "The level of permission to grant the access token to manage the email addresses belonging to a user.",
-1
View File
@@ -34,4 +34,3 @@ We have tests both for the `main.js` and `post.js` scripts.
- If you do not expect an error, take [main-token-permissions-set.test.js](main-token-permissions-set.test.js) as a starting point.
- If your test has an expected error, take [main-missing-client-and-app-id.test.js](main-missing-client-and-app-id.test.js) as a starting point.
- To authenticate with GitHub Actions OIDC instead of a private key, pass `OIDC_ENV` to `test()`, as in [main-oidc-token-permissions-set.test.js](main-oidc-token-permissions-set.test.js).
+12 -14
View File
@@ -11,17 +11,18 @@ snapshot.setDefaultSnapshotSerializers([
(value) => (typeof value === "string" ? value : undefined),
]);
function normalizeStderr(stderr) {
return stderr
.replaceAll(/\u001B\[[0-9;]*m/g, "")
.replaceAll(process.cwd(), "<cwd>")
.replaceAll(/:\d+:\d+/g, ":<line>:<column>");
}
// Get all files in tests directory
const files = readdirSync("tests");
// Files to ignore
const ignore = [
"index.js",
"index.js.snapshot",
"main.js",
"mock-agent.js",
"README.md",
];
const ignore = ["index.js", "index.js.snapshot", "main.js", "README.md"];
const testFiles = files.filter((file) => !ignore.includes(file)).sort();
@@ -47,12 +48,9 @@ for (const file of testFiles) {
} = process.env;
let stderr, stdout;
try {
// Omit stack traces so snapshots don't change with Node.js or dependency updates
({ stderr, stdout } = await execFileAsync(
"node",
["--stack-trace-limit=0", `tests/${file}`],
{ env },
));
({ stderr, stdout } = await execFileAsync("node", [`tests/${file}`], {
env,
}));
} catch (error) {
if (!(error instanceof Error) || !("stderr" in error) || !("stdout" in error)) {
throw error;
@@ -60,7 +58,7 @@ for (const file of testFiles) {
({ stderr, stdout } = error);
}
const trimmedStderr = stderr.replace(/\r?\n$/, "");
const trimmedStderr = normalizeStderr(stderr).replace(/\r?\n$/, "");
const trimmedStdout = stdout.replace(/\r?\n$/, "");
await t.test("stderr", (t) => {
if (trimmedStderr) t.assert.snapshot(trimmedStderr);
+32 -207
View File
@@ -38,6 +38,7 @@ POST /app/installations/123456/access_tokens
exports[`main-custom-github-api-url.test.js > stdout 1`] = `
Inputs 'owner' and 'repositories' are set. Creating token for the following repositories:
- actions/create-github-app-token
::add-mask::ghs_16C7e42F292c6912E7710c838347Ae178B4a
@@ -74,19 +75,31 @@ null
`;
exports[`main-enterprise-installation-not-found.test.js > stderr 1`] = `
[Error: No enterprise installation found matching the enterprise slug "test-enterprise".]
Error: No enterprise installation found matching the name test-enterprise.
at getTokenFromEnterprise (file://<cwd>/lib/main.js:<line>:<column>)
at process.processTicksAndRejections (node:internal/process/task_queues:<line>:<column>)
at async pRetry (file://<cwd>/node_modules/p-retry/index.js:<line>:<column>)
at async main (file://<cwd>/lib/main.js:<line>:<column>)
at async test (file://<cwd>/tests/main.js:<line>:<column>)
at async file://<cwd>/tests/main-enterprise-installation-not-found.test.js:<line>:<column>
`;
exports[`main-enterprise-installation-not-found.test.js > stdout 1`] = `
Creating enterprise installation token for enterprise "test-enterprise".
Failed to create token for enterprise "test-enterprise" (attempt 1): No enterprise installation found matching the enterprise slug "test-enterprise".
::error::No enterprise installation found matching the enterprise slug "test-enterprise".
Failed to create token for enterprise "test-enterprise" (attempt 1): No enterprise installation found matching the name test-enterprise.
::error::No enterprise installation found matching the name test-enterprise.
--- REQUESTS ---
GET /enterprises/test-enterprise/installation
`;
exports[`main-enterprise-mutual-exclusivity-owner.test.js > stderr 1`] = `
[Error: Cannot use 'enterprise' input with 'owner' or 'repositories' inputs]
Error: Cannot use 'enterprise' input with 'owner' or 'repositories' inputs
at main (file://<cwd>/lib/main.js:<line>:<column>)
at run (file://<cwd>/main.js:<line>:<column>)
at file://<cwd>/main.js:<line>:<column>
at ModuleJob.run (node:internal/modules/esm/module_job:<line>:<column>)
at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:<line>:<column>)
at async file://<cwd>/tests/main-enterprise-mutual-exclusivity-owner.test.js:<line>:<column>
`;
exports[`main-enterprise-mutual-exclusivity-owner.test.js > stdout 1`] = `
@@ -94,7 +107,13 @@ exports[`main-enterprise-mutual-exclusivity-owner.test.js > stdout 1`] = `
`;
exports[`main-enterprise-mutual-exclusivity-repositories.test.js > stderr 1`] = `
[Error: Cannot use 'enterprise' input with 'owner' or 'repositories' inputs]
Error: Cannot use 'enterprise' input with 'owner' or 'repositories' inputs
at main (file://<cwd>/lib/main.js:<line>:<column>)
at run (file://<cwd>/main.js:<line>:<column>)
at file://<cwd>/main.js:<line>:<column>
at ModuleJob.run (node:internal/modules/esm/module_job:<line>:<column>)
at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:<line>:<column>)
at async file://<cwd>/tests/main-enterprise-mutual-exclusivity-repositories.test.js:<line>:<column>
`;
exports[`main-enterprise-mutual-exclusivity-repositories.test.js > stdout 1`] = `
@@ -118,7 +137,7 @@ POST /app/installations/123456/access_tokens
null
`;
exports[`main-enterprise-token-permissions-set.test.js > stdout 1`] = `
exports[`main-enterprise-token-with-permissions.test.js > stdout 1`] = `
Creating enterprise installation token for enterprise "test-enterprise".
::add-mask::ghs_16C7e42F292c6912E7710c838347Ae178B4a
@@ -132,7 +151,7 @@ Creating enterprise installation token for enterprise "test-enterprise".
--- REQUESTS ---
GET /enterprises/test-enterprise/installation
POST /app/installations/123456/access_tokens
{"permissions":{"enterprise_custom_properties_for_organizations":"read"}}
{"permissions":{"enterprise_organizations":"read","enterprise_people":"write"}}
`;
exports[`main-missing-client-and-app-id.test.js > stderr 1`] = `
@@ -147,78 +166,10 @@ exports[`main-missing-owner.test.js > stderr 1`] = `
GITHUB_REPOSITORY_OWNER missing, must be set to '<owner>'
`;
exports[`main-missing-private-key.test.js > stderr 1`] = `
The 'private-key' input must be set to a non-empty string, or the workflow must have 'id-token: write' permissions to authenticate with OIDC. If using a secret or variable, ensure it is available in this workflow context.
`;
exports[`main-missing-private-key.test.js > stdout 1`] = `
::error::The 'private-key' input must be set to a non-empty string, or the workflow must have 'id-token: write' permissions to authenticate with OIDC. If using a secret or variable, ensure it is available in this workflow context.
`;
exports[`main-missing-repository.test.js > stderr 1`] = `
GITHUB_REPOSITORY missing, must be set to '<owner>/<repo>'
`;
exports[`main-oidc-custom-server-url.test.js > stdout 1`] = `
Input 'repositories' is not set. Creating token for all repositories owned by actions.
No 'private-key' provided; authenticating with GitHub Actions OIDC.
::debug::ID token url is http://127.0.0.1:<port>/token?api-version=2.0&audience=https%253A%252F%252Fgithub.example.com%252Flogin%252Foauth
::add-mask::oidc-token
::add-mask::ghs_16C7e42F292c6912E7710c838347Ae178B4a
::set-output name=token::ghs_16C7e42F292c6912E7710c838347Ae178B4a
::set-output name=installation-id::123456
::set-output name=app-slug::github-actions
::save-state name=token::ghs_16C7e42F292c6912E7710c838347Ae178B4a
::save-state name=expiresAt::2016-07-11T22:14:10Z
--- OIDC REQUESTS ---
GET /token?api-version=2.0&audience=https%3A%2F%2Fgithub.example.com%2Flogin%2Foauth
--- REQUESTS ---
GET /users/actions/installation?client_id=Iv1.0123456789abcdef
POST /app/installations/123456/access_tokens?client_id=Iv1.0123456789abcdef
null
`;
exports[`main-oidc-enterprise-requires-private-key.test.js > stderr 1`] = `
The 'enterprise' input requires 'private-key'; OIDC authentication is not supported for enterprise installations.
`;
exports[`main-oidc-enterprise-requires-private-key.test.js > stdout 1`] = `
::error::The 'enterprise' input requires 'private-key'; OIDC authentication is not supported for enterprise installations.
`;
exports[`main-oidc-missing-client-id.test.js > stderr 1`] = `
The 'client-id' input is required for OIDC authentication. The deprecated 'app-id' input is only supported with 'private-key'.
`;
exports[`main-oidc-missing-client-id.test.js > stdout 1`] = `
::error::The 'client-id' input is required for OIDC authentication. The deprecated 'app-id' input is only supported with 'private-key'.
`;
exports[`main-oidc-token-permissions-set.test.js > stdout 1`] = `
Inputs 'owner' and 'repositories' are not set. Creating token for this repository (actions/create-github-app-token).
No 'private-key' provided; authenticating with GitHub Actions OIDC.
::debug::ID token url is http://127.0.0.1:<port>/token?api-version=2.0&audience=https%253A%252F%252Fgithub.com%252Flogin%252Foauth
::add-mask::oidc-token
::add-mask::ghs_16C7e42F292c6912E7710c838347Ae178B4a
::set-output name=token::ghs_16C7e42F292c6912E7710c838347Ae178B4a
::set-output name=installation-id::123456
::set-output name=app-slug::github-actions
::save-state name=token::ghs_16C7e42F292c6912E7710c838347Ae178B4a
::save-state name=expiresAt::2016-07-11T22:14:10Z
--- OIDC REQUESTS ---
GET /token?api-version=2.0&audience=https%3A%2F%2Fgithub.com%2Flogin%2Foauth
--- REQUESTS ---
GET /repos/actions/create-github-app-token/installation?client_id=Iv1.0123456789abcdef
POST /app/installations/123456/access_tokens?client_id=Iv1.0123456789abcdef
{"repositories":["create-github-app-token"],"permissions":{"issues":"write"}}
`;
exports[`main-private-key-with-escaped-newlines.test.js > stdout 1`] = `
Inputs 'owner' and 'repositories' are not set. Creating token for this repository (actions/create-github-app-token).
::add-mask::ghs_16C7e42F292c6912E7710c838347Ae178B4a
@@ -251,6 +202,7 @@ exports[`main-repo-skew.test.js > stderr 1`] = `
exports[`main-repo-skew.test.js > stdout 1`] = `
Inputs 'owner' and 'repositories' are set. Creating token for the following repositories:
- actions/failed-repo
::add-mask::ghs_16C7e42F292c6912E7710c838347Ae178B4a
@@ -268,37 +220,6 @@ POST /app/installations/123456/access_tokens
{"repositories":["failed-repo"]}
`;
exports[`main-token-get-owner-set-client-error.test.js > stderr 1`] = `
[RequestError [HttpError]: Forbidden] {
status: 403,
request: {
method: 'GET',
url: 'https://api.github.com/users/smockle/installation',
headers: {
accept: 'application/vnd.github.v3+json',
'user-agent': 'actions/create-github-app-token',
authorization: 'bearer [REDACTED]'
},
request: { hook: [Function: bound hook] AsyncFunction }
},
response: {
url: 'https://api.github.com/users/smockle/installation',
status: 403,
headers: { 'content-type': 'application/json' },
data: { message: 'Forbidden' }
},
[cause]: undefined
}
`;
exports[`main-token-get-owner-set-client-error.test.js > stdout 1`] = `
Input 'repositories' is not set. Creating token for all repositories owned by smockle.
Failed to create token for "smockle" (attempt 1): Forbidden
::error::Forbidden
--- REQUESTS ---
GET /users/smockle/installation
`;
exports[`main-token-get-owner-set-fail-response.test.js > stdout 1`] = `
Input 'repositories' is not set. Creating token for all repositories owned by smockle.
Failed to create token for "smockle" (attempt 1): GitHub API not available
@@ -320,8 +241,9 @@ null
exports[`main-token-get-owner-set-repo-fail-response.test.js > stdout 1`] = `
Inputs 'owner' and 'repositories' are set. Creating token for the following repositories:
- actions/failed-repo
Failed to create token for "actions/failed-repo" (attempt 1): GitHub API not available
Failed to create token for "failed-repo" (attempt 1): GitHub API not available
::add-mask::ghs_16C7e42F292c6912E7710c838347Ae178B4a
::set-output name=token::ghs_16C7e42F292c6912E7710c838347Ae178B4a
@@ -338,81 +260,9 @@ POST /app/installations/123456/access_tokens
{"repositories":["failed-repo"]}
`;
exports[`main-token-get-owner-set-repo-full-name.test.js > stdout 1`] = `
Inputs 'owner' and 'repositories' are set. Creating token for the following repositories:
- actions/create-github-app-token
::add-mask::ghs_16C7e42F292c6912E7710c838347Ae178B4a
::set-output name=token::ghs_16C7e42F292c6912E7710c838347Ae178B4a
::set-output name=installation-id::123456
::set-output name=app-slug::github-actions
::save-state name=token::ghs_16C7e42F292c6912E7710c838347Ae178B4a
::save-state name=expiresAt::2016-07-11T22:14:10Z
--- REQUESTS ---
GET /repos/actions/create-github-app-token/installation
POST /app/installations/123456/access_tokens
{"repositories":["create-github-app-token"]}
`;
exports[`main-token-get-owner-set-repo-invalid-format.test.js > stderr 1`] = `
[Error: Invalid repository 'octocat/hello-world/extra'. Expected 'repository' or 'owner/repository'.]
`;
exports[`main-token-get-owner-set-repo-invalid-format.test.js > stdout 1`] = `
::error::Invalid repository 'octocat/hello-world/extra'. Expected 'repository' or 'owner/repository'.
`;
exports[`main-token-get-owner-set-repo-network-error.test.js > stdout 1`] = `
Inputs 'owner' and 'repositories' are set. Creating token for the following repositories:
- actions/network-repo
Failed to create token for "actions/network-repo" (attempt 1): fetch failed
::add-mask::ghs_16C7e42F292c6912E7710c838347Ae178B4a
::set-output name=token::ghs_16C7e42F292c6912E7710c838347Ae178B4a
::set-output name=installation-id::123456
::set-output name=app-slug::github-actions
::save-state name=token::ghs_16C7e42F292c6912E7710c838347Ae178B4a
::save-state name=expiresAt::2016-07-11T22:14:10Z
--- REQUESTS ---
GET /repos/actions/network-repo/installation
GET /repos/actions/network-repo/installation
POST /app/installations/123456/access_tokens
{"repositories":["network-repo"]}
`;
exports[`main-token-get-owner-set-repo-non-current-full-name.test.js > stdout 1`] = `
Inputs 'owner' and 'repositories' are set. Creating token for the following repositories:
- actions/toolkit
- actions/checkout
::add-mask::ghs_16C7e42F292c6912E7710c838347Ae178B4a
::set-output name=token::ghs_16C7e42F292c6912E7710c838347Ae178B4a
::set-output name=installation-id::123456
::set-output name=app-slug::github-actions
::save-state name=token::ghs_16C7e42F292c6912E7710c838347Ae178B4a
::save-state name=expiresAt::2016-07-11T22:14:10Z
--- REQUESTS ---
GET /repos/actions/toolkit/installation
POST /app/installations/123456/access_tokens
{"repositories":["toolkit","checkout"]}
`;
exports[`main-token-get-owner-set-repo-owner-mismatch.test.js > stderr 1`] = `
[Error: Repository 'octocat/hello-world' includes owner 'octocat', which does not match the resolved owner 'actions'.]
`;
exports[`main-token-get-owner-set-repo-owner-mismatch.test.js > stdout 1`] = `
::error::Repository 'octocat/hello-world' includes owner 'octocat', which does not match the resolved owner 'actions'.
`;
exports[`main-token-get-owner-set-repo-set-to-many-newline.test.js > stdout 1`] = `
Inputs 'owner' and 'repositories' are set. Creating token for the following repositories:
- actions/create-github-app-token
- actions/toolkit
- actions/checkout
@@ -433,6 +283,7 @@ POST /app/installations/123456/access_tokens
exports[`main-token-get-owner-set-repo-set-to-many.test.js > stdout 1`] = `
Inputs 'owner' and 'repositories' are set. Creating token for the following repositories:
- actions/create-github-app-token
- actions/toolkit
- actions/checkout
@@ -453,6 +304,7 @@ POST /app/installations/123456/access_tokens
exports[`main-token-get-owner-set-repo-set-to-one.test.js > stdout 1`] = `
Inputs 'owner' and 'repositories' are set. Creating token for the following repositories:
- actions/create-github-app-token
::add-mask::ghs_16C7e42F292c6912E7710c838347Ae178B4a
@@ -486,33 +338,6 @@ POST /app/installations/123456/access_tokens
null
`;
exports[`main-token-get-owner-unset-repo-full-name-and-bare.test.js > stdout 1`] = `
No 'owner' input provided. Using default owner 'actions' to create token for the following repositories:
- actions/create-github-app-token
- actions/toolkit
::add-mask::ghs_16C7e42F292c6912E7710c838347Ae178B4a
::set-output name=token::ghs_16C7e42F292c6912E7710c838347Ae178B4a
::set-output name=installation-id::123456
::set-output name=app-slug::github-actions
::save-state name=token::ghs_16C7e42F292c6912E7710c838347Ae178B4a
::save-state name=expiresAt::2016-07-11T22:14:10Z
--- REQUESTS ---
GET /repos/actions/create-github-app-token/installation
POST /app/installations/123456/access_tokens
{"repositories":["create-github-app-token","toolkit"]}
`;
exports[`main-token-get-owner-unset-repo-owner-mismatch.test.js > stderr 1`] = `
[Error: Repository 'octocat/hello-world' includes owner 'octocat', which does not match the resolved owner 'actions'.]
`;
exports[`main-token-get-owner-unset-repo-owner-mismatch.test.js > stdout 1`] = `
::error::Repository 'octocat/hello-world' includes owner 'octocat', which does not match the resolved owner 'actions'.
`;
exports[`main-token-get-owner-unset-repo-set.test.js > stdout 1`] = `
No 'owner' input provided. Using default owner 'actions' to create token for the following repositories:
- actions/create-github-app-token
@@ -1,13 +1,15 @@
import { DEFAULT_ENV } from "./main.js";
// Verify `main` exits with an error when `enterprise` is used with `owner` input.
// Set up environment with enterprise and owner set
for (const [key, value] of Object.entries(DEFAULT_ENV)) {
process.env[key] = value;
try {
// Set up environment with enterprise and owner set
for (const [key, value] of Object.entries(DEFAULT_ENV)) {
process.env[key] = value;
}
process.env.INPUT_ENTERPRISE = "test-enterprise";
process.env.INPUT_OWNER = "test-owner";
await import("../main.js");
} catch (error) {
console.error(error.message);
}
process.env.INPUT_ENTERPRISE = "test-enterprise";
process.env.INPUT_OWNER = "test-owner";
const { default: promise } = await import("../main.js");
await promise;
@@ -1,13 +1,15 @@
import { DEFAULT_ENV } from "./main.js";
// Verify `main` exits with an error when `enterprise` is used with `repositories` input.
// Set up environment with enterprise and repositories set
for (const [key, value] of Object.entries(DEFAULT_ENV)) {
process.env[key] = value;
try {
// Set up environment with enterprise and repositories set
for (const [key, value] of Object.entries(DEFAULT_ENV)) {
process.env[key] = value;
}
process.env.INPUT_ENTERPRISE = "test-enterprise";
process.env.INPUT_REPOSITORIES = "repo1,repo2";
await import("../main.js");
} catch (error) {
console.error(error.message);
}
process.env.INPUT_ENTERPRISE = "test-enterprise";
process.env.INPUT_REPOSITORIES = "repo1,repo2";
const { default: promise } = await import("../main.js");
await promise;
@@ -1,14 +1,12 @@
import { test } from "./main.js";
// Use a declared enterprise permission from the generated schema to verify
// enterprise token requests forward permission inputs to token creation.
// Verify `main` successfully generates enterprise token with specific permissions.
await test((mockPool) => {
process.env.INPUT_ENTERPRISE = "test-enterprise";
delete process.env.INPUT_OWNER;
delete process.env.INPUT_REPOSITORIES;
process.env[
"INPUT_PERMISSION-ENTERPRISE-CUSTOM-PROPERTIES-FOR-ORGANIZATIONS"
] = "read";
process.env["INPUT_PERMISSION-ENTERPRISE-ORGANIZATIONS"] = "read";
process.env["INPUT_PERMISSION-ENTERPRISE-PEOPLE"] = "write";
// Mock the enterprise installation endpoint
const mockInstallationId = "123456";
-22
View File
@@ -1,22 +0,0 @@
import { DEFAULT_ENV } from "./main.js";
for (const [key, value] of Object.entries({
...DEFAULT_ENV,
"INPUT_PRIVATE-KEY": "",
})) {
process.env[key] = value;
}
// Log only the error message, not the full stack trace, because the stack
// trace contains environment-specific paths and ANSI codes that differ
// between local and CI environments.
const _error = console.error;
console.error = (err) => _error(err?.message ?? err);
delete process.env.ACTIONS_ID_TOKEN_REQUEST_URL;
delete process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;
// Verify a missing private-key without OIDC permissions produces an actionable error.
const { default: promise } = await import("../main.js");
await promise;
process.exitCode = 0;
-24
View File
@@ -1,24 +0,0 @@
import { OIDC_ENV, test } from "./main.js";
// Verify the OIDC audience is derived from `GITHUB_SERVER_URL`, using an `owner` target.
await test((mockPool) => {
process.env.GITHUB_SERVER_URL = "https://github.example.com";
process.env.INPUT_OWNER = process.env.GITHUB_REPOSITORY_OWNER;
delete process.env.INPUT_REPOSITORIES;
mockPool
.intercept({
path: `/users/${process.env.INPUT_OWNER}/installation?client_id=${OIDC_ENV["INPUT_CLIENT-ID"]}`,
method: "GET",
headers: {
accept: "application/vnd.github.v3+json",
"user-agent": "actions/create-github-app-token",
authorization: "Bearer oidc-token",
},
})
.reply(
200,
{ id: "123456", app_slug: "github-actions" },
{ headers: { "content-type": "application/json" } },
);
}, OIDC_ENV);
@@ -1,17 +0,0 @@
import { OIDC_ENV } from "./main.js";
for (const [key, value] of Object.entries({
...OIDC_ENV,
ACTIONS_ID_TOKEN_REQUEST_URL: "https://oidc.example/token",
INPUT_ENTERPRISE: "test-enterprise",
})) {
process.env[key] = value;
}
const _error = console.error;
console.error = (err) => _error(err?.message ?? err);
// Verify `main` exits with an error when OIDC authentication is used with the `enterprise` input.
const { default: promise } = await import("../main.js");
await promise;
process.exitCode = 0;
-18
View File
@@ -1,18 +0,0 @@
import { OIDC_ENV } from "./main.js";
for (const [key, value] of Object.entries({
...OIDC_ENV,
"INPUT_CLIENT-ID": "",
"INPUT_APP-ID": "123456",
ACTIONS_ID_TOKEN_REQUEST_URL: "https://oidc.example/token",
})) {
process.env[key] = value;
}
const _error = console.error;
console.error = (err) => _error(err?.message ?? err);
// Verify the deprecated `app-id` input is rejected for OIDC authentication.
const { default: promise } = await import("../main.js");
await promise;
process.exitCode = 0;
@@ -1,8 +0,0 @@
import { OIDC_ENV, test } from "./main.js";
// Verify `main` authenticates with an OIDC token when `private-key` isn’t set, and that the
// OIDC audience falls back to https://github.com when `GITHUB_SERVER_URL` isn’t set.
await test(() => {
delete process.env.GITHUB_SERVER_URL;
process.env["INPUT_PERMISSION-ISSUES"] = "write";
}, OIDC_ENV);
@@ -1,23 +0,0 @@
import { test } from "./main.js";
// Verify client errors are not retried when getting a token for a user or organization.
await test((mockPool) => {
process.env.INPUT_OWNER = "smockle";
delete process.env.INPUT_REPOSITORIES;
mockPool
.intercept({
path: "/users/smockle/installation",
method: "GET",
headers: {
accept: "application/vnd.github.v3+json",
"user-agent": "actions/create-github-app-token",
// Intentionally omitting the `authorization` header, since JWT creation is not idempotent.
},
})
.reply(
403,
{ message: "Forbidden" },
{ headers: { "content-type": "application/json" } },
);
});
@@ -1,8 +0,0 @@
import { test } from "./main.js";
// Verify `main` successfully obtains a token when the `owner` and `repositories` inputs are set, and `repositories` contains a full repository name.
await test(() => {
process.env.INPUT_OWNER = process.env.GITHUB_REPOSITORY_OWNER;
process.env.INPUT_REPOSITORIES = process.env.GITHUB_REPOSITORY;
});
@@ -1,13 +0,0 @@
import { DEFAULT_ENV } from "./main.js";
// Verify `main` exits with an error when a repository entry is neither a repository name nor an owner/repository name.
for (const [key, value] of Object.entries(DEFAULT_ENV)) {
process.env[key] = value;
}
process.env.INPUT_OWNER = process.env.GITHUB_REPOSITORY_OWNER;
process.env.INPUT_REPOSITORIES = "octocat/hello-world/extra";
const { default: promise } = await import("../main.js");
await promise;
@@ -1,39 +0,0 @@
import { test } from "./main.js";
// Verify transient network errors are retried when getting a repository token.
await test((mockPool) => {
process.env.INPUT_OWNER = "actions";
process.env.INPUT_REPOSITORIES = "network-repo";
const owner = process.env.INPUT_OWNER;
const repo = process.env.INPUT_REPOSITORIES;
const mockInstallationId = "123456";
const mockAppSlug = "github-actions";
mockPool
.intercept({
path: `/repos/${owner}/${repo}/installation`,
method: "GET",
headers: {
accept: "application/vnd.github.v3+json",
"user-agent": "actions/create-github-app-token",
// Intentionally omitting the `authorization` header, since JWT creation is not idempotent.
},
})
.replyWithError(new TypeError("fetch failed"));
mockPool
.intercept({
path: `/repos/${owner}/${repo}/installation`,
method: "GET",
headers: {
accept: "application/vnd.github.v3+json",
"user-agent": "actions/create-github-app-token",
// Intentionally omitting the `authorization` header, since JWT creation is not idempotent.
},
})
.reply(
200,
{ id: mockInstallationId, app_slug: mockAppSlug },
{ headers: { "content-type": "application/json" } },
);
});
@@ -1,12 +0,0 @@
import { DEFAULT_ENV, test } from "./main.js";
// Verify `main` normalizes full repository names before installation lookup and token scoping.
await test(
() => {},
{
...DEFAULT_ENV,
INPUT_OWNER: DEFAULT_ENV.GITHUB_REPOSITORY_OWNER,
INPUT_REPOSITORIES: `${DEFAULT_ENV.GITHUB_REPOSITORY_OWNER}/toolkit,checkout`,
},
);
@@ -1,13 +0,0 @@
import { DEFAULT_ENV } from "./main.js";
// Verify `main` exits with an error when a full repository name does not match the `owner` input.
for (const [key, value] of Object.entries(DEFAULT_ENV)) {
process.env[key] = value;
}
process.env.INPUT_OWNER = process.env.GITHUB_REPOSITORY_OWNER;
process.env.INPUT_REPOSITORIES = "octocat/hello-world";
const { default: promise } = await import("../main.js");
await promise;
@@ -1,8 +0,0 @@
import { test } from "./main.js";
// Verify `main` successfully obtains a token when `owner` is omitted and `repositories` mixes a full repository name with bare repository names.
await test(() => {
delete process.env.INPUT_OWNER;
process.env.INPUT_REPOSITORIES = `${process.env.GITHUB_REPOSITORY},toolkit`;
});
@@ -1,13 +0,0 @@
import { DEFAULT_ENV } from "./main.js";
// Verify `main` exits with an error when a full repository name does not match the default owner.
for (const [key, value] of Object.entries(DEFAULT_ENV)) {
process.env[key] = value;
}
delete process.env.INPUT_OWNER;
process.env.INPUT_REPOSITORIES = "octocat/hello-world";
const { default: promise } = await import("../main.js");
await promise;
+10 -69
View File
@@ -1,8 +1,6 @@
// Base for all `main` tests.
// @ts-check
import { createServer } from "node:http";
import { createMockAgent } from "./mock-agent.js";
import { MockAgent, setGlobalDispatcher } from "undici";
export const DEFAULT_ENV = {
GITHUB_REPOSITORY_OWNER: "actions",
@@ -44,48 +42,6 @@ x3WQZRiXlWejSMUAHuMwXrhGlltF3lw83+xAjnqsVp75kGS6OH61
"INPUT_PERMISSION-ADMINISTRATION": "",
};
// Authenticate with GitHub Actions OIDC instead of a private key.
export const OIDC_ENV = {
...DEFAULT_ENV,
"INPUT_PRIVATE-KEY": "",
ACTIONS_ID_TOKEN_REQUEST_TOKEN: "runner-token",
};
/**
* Starts a local server that mimics the Actions OIDC token endpoint, because
* `core.getIDToken()` uses `@actions/http-client`, which `MockAgent` can't intercept.
*/
async function startOidcServer() {
/** @type {string[]} */
const requests = [];
const server = createServer((request, response) => {
requests.push(`${request.method} ${request.url}`);
const authorized = request.headers.authorization === "Bearer runner-token";
response.writeHead(authorized ? 200 : 401, {
"content-type": "application/json",
});
response.end(JSON.stringify(authorized ? { value: "oidc-token" } : { message: "Unauthorized" }));
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve(undefined)));
const { port } = /** @type {import("node:net").AddressInfo} */ (server.address());
process.env.ACTIONS_ID_TOKEN_REQUEST_URL = `http://127.0.0.1:${port}/token?api-version=2.0`;
// `core.getIDToken()` logs the token URL, so replace the random port to keep snapshots stable.
const write = process.stdout.write.bind(process.stdout);
process.stdout.write = /** @type {any} */ (
(/** @type {unknown} */ chunk, /** @type {any[]} */ ...args) =>
write(
typeof chunk === "string" ? chunk.replaceAll(`127.0.0.1:${port}`, "127.0.0.1:<port>") : chunk,
...args
)
);
return {
requests,
close: () => new Promise((resolve) => server.close(() => resolve(undefined))),
};
}
export async function test(cb = (_mockPool) => {}, env = DEFAULT_ENV) {
for (const [key, value] of Object.entries(env)) {
process.env[key] = value;
@@ -94,39 +50,30 @@ export async function test(cb = (_mockPool) => {}, env = DEFAULT_ENV) {
// Set up mocking
const baseUrl = new URL(env["INPUT_GITHUB-API-URL"]);
const basePath = baseUrl.pathname === "/" ? "" : baseUrl.pathname;
const mockAgent = createMockAgent({ enableCallHistory: true });
const mockAgent = new MockAgent({ enableCallHistory: true });
mockAgent.disableNetConnect();
setGlobalDispatcher(mockAgent);
const mockPool = mockAgent.get(baseUrl.origin);
// Calling `auth({ type: "app" })` to obtain a JWT doesn’t make network requests, so no need to intercept.
// Without a private key, the action authenticates with an OIDC token and passes `client_id`.
const oidcServer = env["INPUT_PRIVATE-KEY"] ? undefined : await startOidcServer();
const clientIdQuery = oidcServer ? `?client_id=${env["INPUT_CLIENT-ID"]}` : "";
// JWT creation is not idempotent, so the `authorization` header is only asserted for OIDC.
const authorization = oidcServer ? { authorization: "Bearer oidc-token" } : {};
// Mock installation ID and app slug request
const mockInstallationId = "123456";
const mockAppSlug = "github-actions";
const owner = env.INPUT_OWNER ?? env.GITHUB_REPOSITORY_OWNER;
const currentRepoName = env.GITHUB_REPOSITORY.split("/")[1];
const firstRepositoryInput =
(env.INPUT_REPOSITORIES ?? currentRepoName)
.split(/[\n,]+/)
.map((repository) => repository.trim())
.find(Boolean) ?? currentRepoName;
const repo = encodeURIComponent(
firstRepositoryInput.split("/").pop() || firstRepositoryInput
(env.INPUT_REPOSITORIES ?? currentRepoName).split(",")[0]
);
mockPool
.intercept({
path: `${basePath}/repos/${owner}/${repo}/installation${clientIdQuery}`,
path: `${basePath}/repos/${owner}/${repo}/installation`,
method: "GET",
headers: {
accept: "application/vnd.github.v3+json",
"user-agent": "actions/create-github-app-token",
...authorization,
// Intentionally omitting the `authorization` header, since JWT creation is not idempotent.
},
})
.reply(
@@ -142,12 +89,12 @@ export async function test(cb = (_mockPool) => {}, env = DEFAULT_ENV) {
mockPool
.intercept({
path: `${basePath}/app/installations/${mockInstallationId}/access_tokens${clientIdQuery}`,
path: `${basePath}/app/installations/${mockInstallationId}/access_tokens`,
method: "POST",
headers: {
accept: "application/vnd.github.v3+json",
"user-agent": "actions/create-github-app-token",
...authorization,
// Note: Intentionally omitting the `authorization` header, since JWT creation is not idempotent.
},
})
.reply(
@@ -163,18 +110,12 @@ export async function test(cb = (_mockPool) => {}, env = DEFAULT_ENV) {
const { default: promise } = await import("../main.js");
await promise;
if (oidcServer) {
await oidcServer.close();
console.log("--- OIDC REQUESTS ---");
console.log(oidcServer.requests.join("\n"));
}
console.log("--- REQUESTS ---");
const calls = mockAgent
.getCallHistory()
.calls()
.map((call) => {
const route = `${call.method} ${call.path}${new URL(call.fullUrl).search}`;
const route = `${call.method} ${call.path}`;
if (call.method === "GET") return route;
return `${route}\n${call.body}`;
-12
View File
@@ -1,12 +0,0 @@
import { install, MockAgent, setGlobalDispatcher } from "undici";
// Ensure MockAgent intercepts requests made through global fetch.
install();
export function createMockAgent(options) {
const mockAgent = new MockAgent(options);
mockAgent.disableNetConnect();
setGlobalDispatcher(mockAgent);
return mockAgent;
}
@@ -1,4 +1,4 @@
import { createMockAgent } from "./mock-agent.js";
import { MockAgent, setGlobalDispatcher } from "undici";
// state variables are set as environment variables with the prefix STATE_
// https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#sending-values-to-the-pre-and-post-actions
@@ -14,7 +14,9 @@ process.env.STATE_expiresAt = new Date(
Date.now() + 1000 * 60 * 60
).toISOString();
const mockAgent = createMockAgent();
const mockAgent = new MockAgent();
setGlobalDispatcher(mockAgent);
// Provide the base url to the request
const mockPool = mockAgent.get("https://api.github.com");
+4 -2
View File
@@ -1,4 +1,4 @@
import { createMockAgent } from "./mock-agent.js";
import { MockAgent, setGlobalDispatcher } from "undici";
// state variables are set as environment variables with the prefix STATE_
// https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#sending-values-to-the-pre-and-post-actions
@@ -11,7 +11,9 @@ process.env.STATE_expiresAt = new Date(Date.now() - 1000 * 60 * 60).toISOString(
// https://docs.github.com/en/actions/creating-actions/metadata-syntax-for-github-actions#example-specifying-inputs
process.env["INPUT_SKIP-TOKEN-REVOKE"] = "false";
const mockAgent = createMockAgent();
const mockAgent = new MockAgent();
setGlobalDispatcher(mockAgent);
// Provide the base url to the request
const mockPool = mockAgent.get("https://api.github.com");
+4 -2
View File
@@ -1,4 +1,4 @@
import { createMockAgent } from "./mock-agent.js";
import { MockAgent, setGlobalDispatcher } from "undici";
// state variables are set as environment variables with the prefix STATE_
// https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#sending-values-to-the-pre-and-post-actions
@@ -12,7 +12,9 @@ process.env["INPUT_SKIP-TOKEN-REVOKE"] = "false";
// 1 hour in the future, not expired
process.env.STATE_expiresAt = new Date(Date.now() + 1000 * 60 * 60).toISOString();
const mockAgent = createMockAgent();
const mockAgent = new MockAgent();
setGlobalDispatcher(mockAgent);
// Provide the base url to the request
const mockPool = mockAgent.get("https://api.github.com");
+4 -2
View File
@@ -1,4 +1,4 @@
import { createMockAgent } from "./mock-agent.js";
import { MockAgent, setGlobalDispatcher } from "undici";
// state variables are set as environment variables with the prefix STATE_
// https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#sending-values-to-the-pre-and-post-actions
@@ -8,7 +8,9 @@ process.env.STATE_token = "secret123";
// https://docs.github.com/en/actions/creating-actions/metadata-syntax-for-github-actions#example-specifying-inputs
process.env["INPUT_SKIP-TOKEN-REVOKE"] = "true";
const mockAgent = createMockAgent();
const mockAgent = new MockAgent();
setGlobalDispatcher(mockAgent);
// Provide the base url to the request
const mockPool = mockAgent.get("https://api.github.com");