Compare commits

..

1 Commits

Author SHA1 Message Date
Parker Brown c8ee3265db Create debug.yml 2024-07-25 16:18:55 -07:00
42 changed files with 10875 additions and 18294 deletions
+1 -1
View File
@@ -1 +1 @@
* @actions/create-github-app-token-maintainers
* @gr2m @parkerbxyz @actions/create-github-app-token-maintainers
+11 -22
View File
@@ -1,30 +1,19 @@
version: 2
updates:
- package-ecosystem: 'npm'
directory: '/'
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: 'monthly'
interval: "monthly"
groups:
production-dependencies:
dependency-type: 'production'
update-types:
- minor
- patch
dependency-type: "production"
development-dependencies:
dependency-type: 'development'
update-types:
- minor
- patch
dependency-type: "development"
commit-message:
prefix: 'fix'
prefix-development: 'build'
include: 'scope'
- package-ecosystem: 'github-actions'
directory: '/'
prefix: "fix"
prefix-development: "build"
include: "scope"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: 'monthly'
groups:
github-actions:
update-types:
- minor
- patch
interval: "monthly"
+11
View File
@@ -0,0 +1,11 @@
on:
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Setup tmate session
uses: mxschmitt/action-tmate@v3
env:
test_app_private_key: ${{ secrets.TEST_APP_PRIVATE_KEY }}
@@ -1,17 +0,0 @@
name: 'Publish Immutable Action'
on:
release:
types: [published]
jobs:
publish:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
packages: write
steps:
- uses: actions/checkout@v4
- name: Publish Immutable Action
uses: actions/publish-immutable-action@v0.0.4
-1
View File
@@ -5,7 +5,6 @@ on:
branches:
- main
pull_request:
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
@@ -1,33 +0,0 @@
name: Update Permission Inputs
on:
pull_request:
paths:
- 'package.json'
- 'package-lock.json'
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: write
jobs:
update-permission-inputs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: .node-version
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run permission inputs update script
run: node scripts/update-permission-inputs.js
- name: Commit changes
uses: stefanzweifel/git-auto-commit-action@e348103e9026cc0eee72ae06630dbe30c8bf7a79 # v5.1.0
with:
commit_message: 'feat: update permission inputs'
-15
View File
@@ -1,15 +0,0 @@
# Contributing
Initial setup
```console
npm install
```
Run tests locally
```console
npm test
```
Learn more about how the tests work in [test/README.md](test/README.md).
+21 -59
View File
@@ -86,7 +86,7 @@ jobs:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
- id: committer
run: echo "string=${{ steps.app-token.outputs.app-slug }}[bot] <${{ steps.get-user-id.outputs.user-id }}+${{ steps.app-token.outputs.app-slug }}[bot]@users.noreply.github.com>" >> "$GITHUB_OUTPUT"
- run: echo "committer string is ${{ steps.committer.outputs.string }}"
- run: echo "committer string is ${ {steps.committer.outputs.string }}"
```
### Configure git CLI for an app's bot user
@@ -111,7 +111,7 @@ jobs:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
- 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'
git config --global user.email '${{ steps.get-user-id.outputs.user-id }}+${{ steps.app-token.outputs.app-slug }}[bot]@users.noreply.github.com>'
# git commands like commit work using the bot user
- run: |
git add .
@@ -121,7 +121,7 @@ jobs:
> [!TIP]
> The `<BOT USER ID>` is the numeric user ID of the app's bot user, which can be found under `https://api.github.com/users/<app-slug>%5Bbot%5D`.
>
>
> For example, we can check at `https://api.github.com/users/dependabot[bot]` to see the user ID of Dependabot is 49699333.
>
> Alternatively, you can use the [octokit/request-action](https://github.com/octokit/request-action) to get the ID.
@@ -163,9 +163,7 @@ jobs:
app-id: ${{ vars.APP_ID }}
private-key: ${{ secrets.PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
repositories: |
repo1
repo2
repositories: "repo1,repo2"
- uses: peter-evans/create-or-update-comment@v3
with:
token: ${{ steps.app-token.outputs.token }}
@@ -195,32 +193,6 @@ jobs:
body: "Hello, World!"
```
### Create a token with specific permissions
> [!NOTE]
> 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]
jobs:
hello-world:
runs-on: ubuntu-latest
steps:
- uses: actions/create-github-app-token@v1
id: app-token
with:
app-id: ${{ vars.APP_ID }}
private-key: ${{ secrets.PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
permission-issues: write
- uses: peter-evans/create-or-update-comment@v3
with:
token: ${{ steps.app-token.outputs.token }}
issue-number: ${{ github.event.issue.number }}
body: "Hello, World!"
```
### Create tokens for multiple user or organization accounts
You can use a matrix strategy to create tokens for multiple user or organization accounts.
@@ -277,23 +249,23 @@ jobs:
runs-on: self-hosted
steps:
- name: Create GitHub App token
id: create_token
uses: actions/create-github-app-token@v1
with:
app-id: ${{ vars.GHES_APP_ID }}
private-key: ${{ secrets.GHES_APP_PRIVATE_KEY }}
owner: ${{ vars.GHES_INSTALLATION_ORG }}
github-api-url: ${{ vars.GITHUB_API_URL }}
- name: Create GitHub App token
id: create_token
uses: actions/create-github-app-token@v1
with:
app-id: ${{ vars.GHES_APP_ID }}
private-key: ${{ secrets.GHES_APP_PRIVATE_KEY }}
owner: ${{ vars.GHES_INSTALLATION_ORG }}
github-api-url: ${{ vars.GITHUB_API_URL }}
- name: Create issue
uses: octokit/request-action@v2.x
with:
route: POST /repos/${{ github.repository }}/issues
title: "New issue from workflow"
body: "This is a new issue created from a GitHub Action workflow."
env:
GITHUB_TOKEN: ${{ steps.create_token.outputs.token }}
- name: Create issue
uses: octokit/request-action@v2.x
with:
route: POST /repos/${{ github.repository }}/issues
title: "New issue from workflow"
body: "This is a new issue created from a GitHub Action workflow."
env:
GITHUB_TOKEN: ${{ steps.create_token.outputs.token }}
```
## Inputs
@@ -330,17 +302,11 @@ steps:
### `repositories`
**Optional:** Comma or newline-separated list of repositories to grant access to.
**Optional:** Comma-separated list of repositories to grant access to.
> [!NOTE]
> 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.
### `permission-<permission name>`
**Optional:** The permissions to grant to the token. By default, the token inherits all of the installation's permissions. We recommend to explicitly list the permissions that are required for a use case. This follows GitHub's own recommendation to [control permissions of `GITHUB_TOKEN` in workflows](https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/controlling-permissions-for-github_token). The documentation also lists all available permissions, just prefix the permission key with `permission-` (e.g., `pull-requests``permission-pull-requests`).
The reason we define one `permision-<permission name>` input per permission is to benefit from type intelligence and input validation built into GitHub's action runner.
### `skip-token-revoke`
**Optional:** If truthy, the token will not be revoked when the current job is complete.
@@ -376,10 +342,6 @@ The action creates an installation access token using [the `POST /app/installati
> [!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.
## Contributing
[CONTRIBUTING.md](CONTRIBUTING.md)
## License
[MIT](LICENSE)
+15 -101
View File
@@ -7,122 +7,36 @@ branding:
inputs:
app-id:
description: "GitHub App ID"
required: true
required: false # TODO: When 'app_id' is removed, make 'app-id' required
app_id:
description: "GitHub App ID"
required: false
deprecationMessage: "'app_id' is deprecated and will be removed in a future version. Use 'app-id' instead."
private-key:
description: "GitHub App private key"
required: true
required: false # TODO: When 'private_key' is removed, make 'private-key' required
private_key:
description: "GitHub App private key"
required: false
deprecationMessage: "'private_key' is deprecated and will be removed in a future version. Use 'private-key' instead."
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 install the GitHub App on (defaults to current repository if owner is unset)"
description: "Repositories to install the GitHub App on (defaults to current repository if owner is unset)"
required: false
skip-token-revoke:
description: "If truthy, the token will not be revoked when the current job is complete"
required: false
skip_token_revoke:
description: "If truthy, the token will not be revoked when the current job is complete"
required: false
deprecationMessage: "'skip_token_revoke' is deprecated and will be removed in a future version. Use 'skip-token-revoke' instead."
# Make GitHub API configurable to support non-GitHub Cloud use cases
# see https://github.com/actions/create-github-app-token/issues/77
github-api-url:
description: The URL of the GitHub REST API.
default: ${{ github.api_url }}
# <START GENERATED PERMISSIONS INPUTS>
permission-actions:
description: "The level of permission to grant the access token for GitHub Actions workflows, workflow runs, and artifacts. Can be set to 'read' or 'write'."
permission-administration:
description: "The level of permission to grant the access token for repository creation, deletion, settings, teams, and collaborators creation. 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-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:
description: "The level of permission to grant the access token for repository contents, commits, branches, downloads, releases, and merges. Can be set to 'read' or 'write'."
permission-dependabot-secrets:
description: "The level of permission to grant the access token to manage Dependabot secrets. Can be set to 'read' or 'write'."
permission-deployments:
description: "The level of permission to grant the access token for deployments and deployment statuses. Can be set to 'read' or 'write'."
permission-email-addresses:
description: "The level of permission to grant the access token to manage the email addresses belonging to a user. Can be set to 'read' or 'write'."
permission-environments:
description: "The level of permission to grant the access token for managing repository environments. Can be set to 'read' or 'write'."
permission-followers:
description: "The level of permission to grant the access token to manage the followers belonging to a user. Can be set to 'read' or 'write'."
permission-git-ssh-keys:
description: "The level of permission to grant the access token to manage git SSH keys. Can be set to 'read' or 'write'."
permission-gpg-keys:
description: "The level of permission to grant the access token to view and manage GPG keys belonging to a user. Can be set to 'read' or 'write'."
permission-interaction-limits:
description: "The level of permission to grant the access token to view and manage interaction limits on a repository. Can be set to 'read' or 'write'."
permission-issues:
description: "The level of permission to grant the access token for issues and related comments, assignees, labels, and milestones. Can be set to 'read' or 'write'."
permission-members:
description: "The level of permission to grant the access token for organization teams and members. Can be set to 'read' or 'write'."
permission-metadata:
description: "The level of permission to grant the access token to search repositories, list collaborators, and access repository metadata. Can be set to 'read' or 'write'."
permission-organization-administration:
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-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 '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:
description: "The level of permission to grant the access token for custom property management. Can be set to 'read', 'write', or 'admin'."
permission-organization-custom-roles:
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-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:
description: "The level of permission to grant the access token for organization packages published to GitHub Packages. Can be set to 'read' or 'write'."
permission-organization-personal-access-token-requests:
description: "The level of permission to grant the access token for viewing and managing fine-grained personal access tokens that have been approved by an organization. Can be set to 'read' or 'write'."
permission-organization-personal-access-tokens:
description: "The level of permission to grant the access token for viewing and managing fine-grained personal access token requests to an organization. Can be set to 'read' or 'write'."
permission-organization-plan:
description: "The level of permission to grant the access token for viewing an organization's plan. Can be set to 'read'."
permission-organization-projects:
description: "The level of permission to grant the access token to manage organization projects and projects public preview (where available). Can be set to 'read', 'write', or 'admin'."
permission-organization-secrets:
description: "The level of permission to grant the access token to manage organization secrets. Can be set to 'read' or 'write'."
permission-organization-self-hosted-runners:
description: "The level of permission to grant the access token to view and manage GitHub Actions self-hosted runners available to an organization. Can be set to 'read' or 'write'."
permission-organization-user-blocking:
description: "The level of permission to grant the access token to view and manage users blocked by the organization. Can be set to 'read' or 'write'."
permission-packages:
description: "The level of permission to grant the access token for packages published to GitHub Packages. Can be set to 'read' or 'write'."
permission-pages:
description: "The level of permission to grant the access token to retrieve Pages statuses, configuration, and builds, as well as create new builds. Can be set to 'read' or 'write'."
permission-profile:
description: "The level of permission to grant the access token to manage the profile settings belonging to a user. Can be set to 'write'."
permission-pull-requests:
description: "The level of permission to grant the access token for pull requests and related comments, assignees, labels, milestones, and merges. Can be set to 'read' or 'write'."
permission-repository-custom-properties:
description: "The level of permission to grant the access token to view and edit custom properties for a repository, when allowed by the property. Can be set to 'read' or 'write'."
permission-repository-hooks:
description: "The level of permission to grant the access token to manage the post-receive hooks for a repository. Can be set to 'read' or 'write'."
permission-repository-projects:
description: "The level of permission to grant the access token to manage repository projects, columns, and cards. Can be set to 'read', 'write', or 'admin'."
permission-secret-scanning-alerts:
description: "The level of permission to grant the access token to view and manage secret scanning alerts. Can be set to 'read' or 'write'."
permission-secrets:
description: "The level of permission to grant the access token to manage repository secrets. Can be set to 'read' or 'write'."
permission-security-events:
description: "The level of permission to grant the access token to view and manage security events like code scanning alerts. Can be set to 'read' or 'write'."
permission-single-file:
description: "The level of permission to grant the access token to manage just a single file. Can be set to 'read' or 'write'."
permission-starring:
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:
description: "The level of permission to grant the access token to update GitHub Actions workflow files. Can be set to 'write'."
# <END GENERATED PERMISSIONS INPUTS>
outputs:
token:
description: "GitHub installation access token"
+25
View File
@@ -0,0 +1,25 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="106"
height="20" role="img" aria-label="Coverage: 100%">
<title>Coverage: 100%</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1" />
<stop offset="1" stop-opacity=".1" />
</linearGradient>
<clipPath id="r">
<rect width="106" height="20" rx="3" fill="#fff" />
</clipPath>
<g clip-path="url(#r)">
<rect width="63" height="20" fill="#555" />
<rect x="63" width="43" height="20" fill="#4c1" />
<rect width="106" height="20" fill="url(#s)" />
</g>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif"
text-rendering="geometricPrecision" font-size="110">
<text aria-hidden="true" x="325" y="150" fill="#010101" fill-opacity=".3"
transform="scale(.1)" textLength="530">Coverage</text>
<text x="325" y="140" transform="scale(.1)" fill="#fff" textLength="530">Coverage</text>
<text aria-hidden="true" x="835" y="150" fill="#010101" fill-opacity=".3"
transform="scale(.1)" textLength="330">100%</text>
<text x="835" y="140" transform="scale(.1)" fill="#fff" textLength="330">100%</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

+5640 -8481
View File
File diff suppressed because one or more lines are too long
+4240 -8156
View File
File diff suppressed because one or more lines are too long
-23
View File
@@ -1,23 +0,0 @@
/**
* Finds all permissions passed via `permision-*` inputs and turns them into an object.
*
* @see https://docs.github.com/en/actions/sharing-automations/creating-actions/metadata-syntax-for-github-actions#inputs
* @param {NodeJS.ProcessEnv} env
* @returns {undefined | Record<string, string>}
*/
export function getPermissionsFromInputs(env) {
return Object.entries(env).reduce((permissions, [key, value]) => {
if (!key.startsWith("INPUT_PERMISSION_")) return permissions;
const permission = key.slice("INPUT_PERMISSION_".length).toLowerCase();
if (permissions === undefined) {
return { [permission]: value };
}
return {
// @ts-expect-error - needs to be typed correctly
...permissions,
[permission]: value,
};
}, undefined);
}
+51 -69
View File
@@ -5,8 +5,7 @@ import pRetry from "p-retry";
* @param {string} appId
* @param {string} privateKey
* @param {string} owner
* @param {string[]} repositories
* @param {undefined | Record<string, string>} permissions
* @param {string} repositories
* @param {import("@actions/core")} core
* @param {import("@octokit/auth-app").createAppAuth} createAppAuth
* @param {import("@octokit/request").request} request
@@ -17,55 +16,51 @@ export async function main(
privateKey,
owner,
repositories,
permissions,
core,
createAppAuth,
request,
skipTokenRevoke
) {
let parsedOwner = "";
let parsedRepositoryNames = [];
let parsedRepositoryNames = "";
// If neither owner nor repositories are set, default to current repository
if (!owner && repositories.length === 0) {
const [owner, repo] = String(process.env.GITHUB_REPOSITORY).split("/");
parsedOwner = owner;
parsedRepositoryNames = [repo];
if (!owner && !repositories) {
[parsedOwner, parsedRepositoryNames] = String(
process.env.GITHUB_REPOSITORY
).split("/");
core.info(
`Inputs 'owner' and 'repositories' are not set. Creating token for this repository (${owner}/${repo}).`
`owner and repositories not set, creating token for the current repository ("${parsedRepositoryNames}")`
);
}
// If only an owner is set, default to all repositories from that owner
if (owner && repositories.length === 0) {
if (owner && !repositories) {
parsedOwner = owner;
core.info(
`Input 'repositories' is not set. Creating token for all repositories owned by ${owner}.`
`repositories not set, creating token for all repositories for given owner "${owner}"`
);
}
// If repositories are set, but no owner, default to `GITHUB_REPOSITORY_OWNER`
if (!owner && repositories.length > 0) {
if (!owner && repositories) {
parsedOwner = String(process.env.GITHUB_REPOSITORY_OWNER);
parsedRepositoryNames = repositories;
core.info(
`No 'owner' input provided. Using default owner '${parsedOwner}' to create token for the following repositories:${repositories
.map((repo) => `\n- ${parsedOwner}/${repo}`)
.join("")}`
`owner not set, creating owner for given repositories "${repositories}" in current owner ("${parsedOwner}")`
);
}
// If both owner and repositories are set, use those values
if (owner && repositories.length > 0) {
if (owner && repositories) {
parsedOwner = owner;
parsedRepositoryNames = repositories;
core.info(
`Inputs 'owner' and 'repositories' are set. Creating token for the following repositories:
${repositories.map((repo) => `\n- ${parsedOwner}/${repo}`).join("")}`
`owner and repositories set, creating token for repositories "${repositories}" owned by "${owner}"`
);
}
@@ -78,40 +73,25 @@ export async function main(
let authentication, installationId, appSlug;
// If at least one repository is set, get installation ID from that repository
if (parsedRepositoryNames.length > 0) {
({ authentication, installationId, appSlug } = await pRetry(
() =>
getTokenFromRepository(
request,
auth,
parsedOwner,
parsedRepositoryNames,
permissions
),
{
onFailedAttempt: (error) => {
core.info(
`Failed to create token for "${parsedRepositoryNames.join(
","
)}" (attempt ${error.attemptNumber}): ${error.message}`
);
},
retries: 3,
}
));
if (parsedRepositoryNames) {
({ authentication, installationId, appSlug } = await pRetry(() => getTokenFromRepository(request, auth, parsedOwner, parsedRepositoryNames), {
onFailedAttempt: (error) => {
core.info(
`Failed to create token for "${parsedRepositoryNames}" (attempt ${error.attemptNumber}): ${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, parsedOwner, permissions),
{
onFailedAttempt: (error) => {
core.info(
`Failed to create token for "${parsedOwner}" (attempt ${error.attemptNumber}): ${error.message}`
);
},
retries: 3,
}
));
({ authentication, installationId, appSlug } = await pRetry(() => getTokenFromOwner(request, auth, parsedOwner), {
onFailedAttempt: (error) => {
core.info(
`Failed to create token for "${parsedOwner}" (attempt ${error.attemptNumber}): ${error.message}`
);
},
retries: 3,
}));
}
// Register the token with the runner as a secret to ensure it is masked in logs
@@ -128,40 +108,43 @@ export async function main(
}
}
async function getTokenFromOwner(request, auth, parsedOwner, permissions) {
// https://docs.github.com/rest/apps/apps?apiVersion=2022-11-28#get-a-user-installation-for-the-authenticated-app
// This endpoint works for both users and organizations
const response = await request("GET /users/{username}/installation", {
username: parsedOwner,
async function getTokenFromOwner(request, auth, parsedOwner) {
// https://docs.github.com/en/rest/apps/apps?apiVersion=2022-11-28#get-an-organization-installation-for-the-authenticated-app
const response = await request("GET /orgs/{org}/installation", {
org: parsedOwner,
request: {
hook: auth.hook,
},
}).catch((error) => {
/* c8 ignore next */
if (error.status !== 404) throw error;
// https://docs.github.com/rest/apps/apps?apiVersion=2022-11-28#get-a-user-installation-for-the-authenticated-app
return request("GET /users/{username}/installation", {
username: parsedOwner,
request: {
hook: auth.hook,
},
});
});
// Get token for for all repositories of the given installation
const authentication = await auth({
type: "installation",
installationId: response.data.id,
permissions,
});
const installationId = response.data.id;
const appSlug = response.data["app_slug"];
const appSlug = response.data['app_slug'];
return { authentication, installationId, appSlug };
}
async function getTokenFromRepository(
request,
auth,
parsedOwner,
parsedRepositoryNames,
permissions
) {
async function getTokenFromRepository(request, auth, parsedOwner, parsedRepositoryNames) {
// https://docs.github.com/rest/apps/apps?apiVersion=2022-11-28#get-a-repository-installation-for-the-authenticated-app
const response = await request("GET /repos/{owner}/{repo}/installation", {
owner: parsedOwner,
repo: parsedRepositoryNames[0],
repo: parsedRepositoryNames.split(",")[0],
request: {
hook: auth.hook,
},
@@ -171,12 +154,11 @@ async function getTokenFromRepository(
const authentication = await auth({
type: "installation",
installationId: response.data.id,
repositoryNames: parsedRepositoryNames,
permissions,
repositoryNames: parsedRepositoryNames.split(","),
});
const installationId = response.data.id;
const appSlug = response.data["app_slug"];
const appSlug = response.data['app_slug'];
return { authentication, installationId, appSlug };
}
}
+5 -2
View File
@@ -5,7 +5,9 @@
* @param {import("@octokit/request").request} request
*/
export async function post(core, request) {
const skipTokenRevoke = Boolean(core.getInput("skip-token-revoke"));
const skipTokenRevoke = Boolean(
core.getInput("skip-token-revoke") || core.getInput("skip_token_revoke")
);
if (skipTokenRevoke) {
core.info("Token revocation was skipped");
@@ -33,7 +35,8 @@ export async function post(core, request) {
});
core.info("Token revoked");
} catch (error) {
core.warning(`Token revocation failed: ${error.message}`);
core.warning(
`Token revocation failed: ${error.message}`)
}
}
+1 -1
View File
@@ -17,7 +17,7 @@ const proxyUrl =
const proxyFetch = (url, options) => {
const urlHost = new URL(url).hostname;
const noProxy = (process.env.no_proxy || process.env.NO_PROXY || "").split(
",",
","
);
if (!noProxy.includes(urlHost)) {
+16 -15
View File
@@ -3,7 +3,6 @@
import core from "@actions/core";
import { createAppAuth } from "@octokit/auth-app";
import { getPermissionsFromInputs } from "./lib/get-permissions-from-inputs.js";
import { main } from "./lib/main.js";
import request from "./lib/request.js";
@@ -15,30 +14,32 @@ if (!process.env.GITHUB_REPOSITORY_OWNER) {
throw new Error("GITHUB_REPOSITORY_OWNER missing, must be set to '<owner>'");
}
const appId = core.getInput("app-id");
const privateKey = core.getInput("private-key");
const appId = core.getInput("app-id") || core.getInput("app_id");
if (!appId) {
// The 'app_id' input was previously required, but it and 'app-id' are both optional now, until the former is removed. Still, we want to ensure that at least one of them is set.
throw new Error("Input required and not supplied: app-id");
}
const privateKey = core.getInput("private-key") || core.getInput("private_key");
if (!privateKey) {
// The 'private_key' input was previously required, but it and 'private-key' are both optional now, until the former is removed. Still, we want to ensure that at least one of them is set.
throw new Error("Input required and not supplied: private-key");
}
const owner = core.getInput("owner");
const repositories = core
.getInput("repositories")
.split(/[\n,]+/)
.map((s) => s.trim())
.filter((x) => x !== "");
const repositories = core.getInput("repositories");
const skipTokenRevoke = Boolean(core.getInput("skip-token-revoke"));
const skipTokenRevoke = Boolean(
core.getInput("skip-token-revoke") || core.getInput("skip_token_revoke")
);
const permissions = getPermissionsFromInputs(process.env);
// Export promise for testing
export default main(
main(
appId,
privateKey,
owner,
repositories,
permissions,
core,
createAppAuth,
request,
skipTokenRevoke,
skipTokenRevoke
).catch((error) => {
/* c8 ignore next 3 */
console.error(error);
+643 -550
View File
File diff suppressed because it is too large Load Diff
+13 -15
View File
@@ -2,7 +2,7 @@
"name": "create-github-app-token",
"private": true,
"type": "module",
"version": "2.0.2",
"version": "1.10.3",
"description": "GitHub Action for creating a GitHub App Installation Access Token",
"scripts": {
"build": "esbuild main.js post.js --bundle --outdir=dist --out-extension:.js=.cjs --platform=node --target=node20.0.0 --packages=bundle",
@@ -12,22 +12,21 @@
},
"license": "MIT",
"dependencies": {
"@actions/core": "^1.11.1",
"@octokit/auth-app": "^7.2.0",
"@octokit/request": "^9.2.2",
"p-retry": "^6.2.1",
"undici": "^7.7.0"
"@actions/core": "^1.10.1",
"@octokit/auth-app": "^7.1.0",
"@octokit/request": "^9.0.1",
"p-retry": "^6.2.0",
"undici": "^6.19.2"
},
"devDependencies": {
"@octokit/openapi": "^18.2.0",
"@sinonjs/fake-timers": "^14.0.0",
"ava": "^6.2.0",
"c8": "^10.1.3",
"dotenv": "^16.4.7",
"esbuild": "^0.25.2",
"execa": "^9.5.2",
"@sinonjs/fake-timers": "^11.2.2",
"ava": "^6.1.3",
"c8": "^10.1.2",
"dotenv": "^16.4.5",
"esbuild": "^0.22.0",
"execa": "^9.3.0",
"open-cli": "^8.0.0",
"yaml": "^2.7.1"
"yaml": "^2.4.5"
},
"release": {
"branches": [
@@ -45,7 +44,6 @@
{
"assets": [
"package.json",
"package-lock.json",
"dist/*"
],
"message": "build(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"
-395
View File
@@ -1,395 +0,0 @@
{
"title": "App Permissions",
"type": "object",
"description": "The permissions granted to the user access token.",
"properties": {
"actions": {
"type": "string",
"description": "The level of permission to grant the access token for GitHub Actions workflows, workflow runs, and artifacts.",
"enum": [
"read",
"write"
]
},
"administration": {
"type": "string",
"description": "The level of permission to grant the access token for repository creation, deletion, settings, teams, and collaborators creation.",
"enum": [
"read",
"write"
]
},
"checks": {
"type": "string",
"description": "The level of permission to grant the access token for checks on code.",
"enum": [
"read",
"write"
]
},
"codespaces": {
"type": "string",
"description": "The level of permission to grant the access token to create, edit, delete, and list Codespaces.",
"enum": [
"read",
"write"
]
},
"contents": {
"type": "string",
"description": "The level of permission to grant the access token for repository contents, commits, branches, downloads, releases, and merges.",
"enum": [
"read",
"write"
]
},
"dependabot_secrets": {
"type": "string",
"description": "The level of permission to grant the access token to manage Dependabot secrets.",
"enum": [
"read",
"write"
]
},
"deployments": {
"type": "string",
"description": "The level of permission to grant the access token for deployments and deployment statuses.",
"enum": [
"read",
"write"
]
},
"environments": {
"type": "string",
"description": "The level of permission to grant the access token for managing repository environments.",
"enum": [
"read",
"write"
]
},
"issues": {
"type": "string",
"description": "The level of permission to grant the access token for issues and related comments, assignees, labels, and milestones.",
"enum": [
"read",
"write"
]
},
"metadata": {
"type": "string",
"description": "The level of permission to grant the access token to search repositories, list collaborators, and access repository metadata.",
"enum": [
"read",
"write"
]
},
"packages": {
"type": "string",
"description": "The level of permission to grant the access token for packages published to GitHub Packages.",
"enum": [
"read",
"write"
]
},
"pages": {
"type": "string",
"description": "The level of permission to grant the access token to retrieve Pages statuses, configuration, and builds, as well as create new builds.",
"enum": [
"read",
"write"
]
},
"pull_requests": {
"type": "string",
"description": "The level of permission to grant the access token for pull requests and related comments, assignees, labels, milestones, and merges.",
"enum": [
"read",
"write"
]
},
"repository_custom_properties": {
"type": "string",
"description": "The level of permission to grant the access token to view and edit custom properties for a repository, when allowed by the property.",
"enum": [
"read",
"write"
]
},
"repository_hooks": {
"type": "string",
"description": "The level of permission to grant the access token to manage the post-receive hooks for a repository.",
"enum": [
"read",
"write"
]
},
"repository_projects": {
"type": "string",
"description": "The level of permission to grant the access token to manage repository projects, columns, and cards.",
"enum": [
"read",
"write",
"admin"
]
},
"secret_scanning_alerts": {
"type": "string",
"description": "The level of permission to grant the access token to view and manage secret scanning alerts.",
"enum": [
"read",
"write"
]
},
"secrets": {
"type": "string",
"description": "The level of permission to grant the access token to manage repository secrets.",
"enum": [
"read",
"write"
]
},
"security_events": {
"type": "string",
"description": "The level of permission to grant the access token to view and manage security events like code scanning alerts.",
"enum": [
"read",
"write"
]
},
"single_file": {
"type": "string",
"description": "The level of permission to grant the access token to manage just a single file.",
"enum": [
"read",
"write"
]
},
"statuses": {
"type": "string",
"description": "The level of permission to grant the access token for commit statuses.",
"enum": [
"read",
"write"
]
},
"vulnerability_alerts": {
"type": "string",
"description": "The level of permission to grant the access token to manage Dependabot alerts.",
"enum": [
"read",
"write"
]
},
"workflows": {
"type": "string",
"description": "The level of permission to grant the access token to update GitHub Actions workflow files.",
"enum": [
"write"
]
},
"members": {
"type": "string",
"description": "The level of permission to grant the access token for organization teams and members.",
"enum": [
"read",
"write"
]
},
"organization_administration": {
"type": "string",
"description": "The level of permission to grant the access token to manage access to an organization.",
"enum": [
"read",
"write"
]
},
"organization_custom_roles": {
"type": "string",
"description": "The level of permission to grant the access token for custom repository roles management.",
"enum": [
"read",
"write"
]
},
"organization_custom_org_roles": {
"type": "string",
"description": "The level of permission to grant the access token for custom organization roles management.",
"enum": [
"read",
"write"
]
},
"organization_custom_properties": {
"type": "string",
"description": "The level of permission to grant the access token for custom property management.",
"enum": [
"read",
"write",
"admin"
]
},
"organization_copilot_seat_management": {
"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": [
"write"
]
},
"organization_announcement_banners": {
"type": "string",
"description": "The level of permission to grant the access token to view and manage announcement banners for an organization.",
"enum": [
"read",
"write"
]
},
"organization_events": {
"type": "string",
"description": "The level of permission to grant the access token to view events triggered by an activity in an organization.",
"enum": [
"read"
]
},
"organization_hooks": {
"type": "string",
"description": "The level of permission to grant the access token to manage the post-receive hooks for an organization.",
"enum": [
"read",
"write"
]
},
"organization_personal_access_tokens": {
"type": "string",
"description": "The level of permission to grant the access token for viewing and managing fine-grained personal access token requests to an organization.",
"enum": [
"read",
"write"
]
},
"organization_personal_access_token_requests": {
"type": "string",
"description": "The level of permission to grant the access token for viewing and managing fine-grained personal access tokens that have been approved by an organization.",
"enum": [
"read",
"write"
]
},
"organization_plan": {
"type": "string",
"description": "The level of permission to grant the access token for viewing an organization's plan.",
"enum": [
"read"
]
},
"organization_projects": {
"type": "string",
"description": "The level of permission to grant the access token to manage organization projects and projects public preview (where available).",
"enum": [
"read",
"write",
"admin"
]
},
"organization_packages": {
"type": "string",
"description": "The level of permission to grant the access token for organization packages published to GitHub Packages.",
"enum": [
"read",
"write"
]
},
"organization_secrets": {
"type": "string",
"description": "The level of permission to grant the access token to manage organization secrets.",
"enum": [
"read",
"write"
]
},
"organization_self_hosted_runners": {
"type": "string",
"description": "The level of permission to grant the access token to view and manage GitHub Actions self-hosted runners available to an organization.",
"enum": [
"read",
"write"
]
},
"organization_user_blocking": {
"type": "string",
"description": "The level of permission to grant the access token to view and manage users blocked by the organization.",
"enum": [
"read",
"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.",
"enum": [
"read",
"write"
]
},
"followers": {
"type": "string",
"description": "The level of permission to grant the access token to manage the followers belonging to a user.",
"enum": [
"read",
"write"
]
},
"git_ssh_keys": {
"type": "string",
"description": "The level of permission to grant the access token to manage git SSH keys.",
"enum": [
"read",
"write"
]
},
"gpg_keys": {
"type": "string",
"description": "The level of permission to grant the access token to view and manage GPG keys belonging to a user.",
"enum": [
"read",
"write"
]
},
"interaction_limits": {
"type": "string",
"description": "The level of permission to grant the access token to view and manage interaction limits on a repository.",
"enum": [
"read",
"write"
]
},
"profile": {
"type": "string",
"description": "The level of permission to grant the access token to manage the profile settings belonging to a user.",
"enum": [
"write"
]
},
"starring": {
"type": "string",
"description": "The level of permission to grant the access token to list and manage repositories a user is starring.",
"enum": [
"read",
"write"
]
}
},
"example": {
"contents": "read",
"issues": "read",
"deployments": "write",
"single_file": "read"
}
}
-42
View File
@@ -1,42 +0,0 @@
import { readFile, writeFile } from "node:fs/promises";
import OctokitOpenapi from "@octokit/openapi";
const appPermissionsSchema =
OctokitOpenapi.schemas["api.github.com"].components.schemas[
"app-permissions"
];
await writeFile(
`scripts/generated/app-permissions.json`,
JSON.stringify(appPermissionsSchema, null, 2) + "\n",
"utf8"
);
const permissionsInputs = Object.entries(appPermissionsSchema.properties)
.sort((a, b) => a[0].localeCompare(b[0]))
.reduce((result, [key, value]) => {
const formatter = new Intl.ListFormat("en", {
style: "long",
type: "disjunction",
});
const permissionAccessValues = formatter.format(
value.enum.map((p) => `'${p}'`)
);
const description = `${value.description} Can be set to ${permissionAccessValues}.`;
return `${result}
permission-${key.replace(/_/g, "-")}:
description: "${description}"`;
}, "");
const actionsYamlContent = await readFile("action.yml", "utf8");
// In the action.yml file, replace the content between the `<START GENERATED PERMISSIONS INPUTS>` and `<END GENERATED PERMISSIONS INPUTS>` comments with the new content
const updatedActionsYamlContent = actionsYamlContent.replace(
/(?<=# <START GENERATED PERMISSIONS INPUTS>)(.|\n)*(?=# <END GENERATED PERMISSIONS INPUTS>)/,
permissionsInputs + "\n "
);
await writeFile("action.yml", updatedActionsYamlContent, "utf8");
console.log("Updated action.yml with new permissions inputs");
-11
View File
@@ -17,14 +17,3 @@ or with npm
```
npm test
```
## How the tests work
The output from the tests is captured into a snapshot ([tests/snapshots/index.js.md](snapshots/index.js.md)). It includes all requests sent by our scripts to verify it's working correctly and to prevent regressions.
## How to add a new test
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](tests/main-token-permissions-set.test.js) as a starting point.
- If your test has an expected error, take [main-missing-app-id.test.js](tests/main-missing-app-id.test.js) as a starting point.
+3 -13
View File
@@ -1,21 +1,11 @@
import { readdirSync } from "node:fs";
import test from "ava";
import { execa } from "execa";
import test from "ava";
// Get all files in tests directory
const files = readdirSync("tests");
const tests = readdirSync("tests").filter((file) => file.endsWith(".test.js"));
// Files to ignore
const ignore = ["index.js", "main.js", "README.md", "snapshots"];
const testFiles = files.filter((file) => !ignore.includes(file));
// Throw an error if there is a file that does not end with test.js in the tests directory
for (const file of testFiles) {
if (!file.endsWith(".test.js")) {
throw new Error(`File ${file} does not end with .test.js`);
}
for (const file of tests) {
test(file, async (t) => {
// Override Actions environment variables that change `core`s behavior
const env = {
+2 -3
View File
@@ -1,11 +1,10 @@
import { DEFAULT_ENV, test } from "./main.js";
import { test, DEFAULT_ENV } from "./main.js";
// Verify that main works with a custom GitHub API URL passed as `github-api-url` input
await test(
() => {
process.env.INPUT_OWNER = process.env.GITHUB_REPOSITORY_OWNER;
const currentRepoName = process.env.GITHUB_REPOSITORY.split("/")[1];
process.env.INPUT_REPOSITORIES = currentRepoName;
process.env.INPUT_REPOSITORIES = process.env.GITHUB_REPOSITORY;
},
{
...DEFAULT_ENV,
+9
View File
@@ -0,0 +1,9 @@
process.env.GITHUB_REPOSITORY_OWNER = "actions";
process.env.GITHUB_REPOSITORY = "actions/create-github-app-token";
// Verify `main` exits with an error when neither the `app-id` nor `app_id` input is set.
try {
await import("../main.js");
} catch (error) {
console.error(error.message);
}
+10
View File
@@ -0,0 +1,10 @@
process.env.GITHUB_REPOSITORY_OWNER = "actions";
process.env.GITHUB_REPOSITORY = "actions/create-github-app-token";
process.env["INPUT_APP-ID"] = "123456";
// Verify `main` exits with an error when neither the `private-key` nor `private_key` input is set.
try {
await import("../main.js");
} catch (error) {
console.error(error.message);
}
@@ -0,0 +1,6 @@
import { test, DEFAULT_ENV } from "./main.js";
// Verify `main` works correctly when `private-key` input has escaped newlines
await test(() => {
process.env['INPUT_PRIVATE-KEY'] = DEFAULT_ENV.PRIVATE_KEY.replace(/\n/g, '\\n')
});
@@ -1,9 +0,0 @@
import { DEFAULT_ENV, test } from "./main.js";
// Verify `main` works correctly when `private-key` input has escaped newlines
await test(() => {
process.env["INPUT_PRIVATE-KEY"] = DEFAULT_ENV["INPUT_PRIVATE-KEY"].replace(
/\n/g,
"\\n"
);
});
@@ -4,10 +4,10 @@ import { install } from "@sinonjs/fake-timers";
// Verify `main` retry when the clock has drifted.
await test((mockPool) => {
process.env.INPUT_OWNER = "actions";
process.env.INPUT_REPOSITORIES = "failed-repo";
const owner = process.env.INPUT_OWNER;
const repo = process.env.INPUT_REPOSITORIES;
process.env.INPUT_OWNER = 'actions'
process.env.INPUT_REPOSITORIES = 'failed-repo';
const owner = process.env.INPUT_OWNER
const repo = process.env.INPUT_REPOSITORIES
const mockInstallationId = "123456";
const mockAppSlug = "github-actions";
@@ -25,23 +25,20 @@ await test((mockPool) => {
})
.reply(({ headers }) => {
const [_, jwt] = (headers.authorization || "").split(" ");
const payload = JSON.parse(
Buffer.from(jwt.split(".")[1], "base64").toString(),
);
const payload = JSON.parse(Buffer.from(jwt.split(".")[1], "base64").toString());
if (payload.iat < 0) {
return {
statusCode: 401,
data: {
message:
"'Issued at' claim ('iat') must be an Integer representing the time that the assertion was issued.",
message: "'Issued at' claim ('iat') must be an Integer representing the time that the assertion was issued."
},
responseOptions: {
headers: {
"content-type": "application/json",
date: new Date(Date.now() + 30000).toUTCString(),
},
},
"date": new Date(Date.now() + 30000).toUTCString()
}
}
};
}
@@ -49,14 +46,13 @@ await test((mockPool) => {
statusCode: 200,
data: {
id: mockInstallationId,
app_slug: mockAppSlug,
"app_slug": mockAppSlug
},
responseOptions: {
headers: {
"content-type": "application/json",
},
},
"content-type": "application/json"
}
}
};
})
.times(2);
}).times(2);
});
@@ -33,7 +33,7 @@ await test((mockPool) => {
})
.reply(
200,
{ id: mockInstallationId, app_slug: mockAppSlug },
{ headers: { "content-type": "application/json" } },
{ id: mockInstallationId, "app_slug": mockAppSlug },
{ headers: { "content-type": "application/json" } }
);
});
@@ -1,9 +0,0 @@
import { test } from "./main.js";
// Verify `main` successfully obtains a token when the `owner` and `repositories` inputs are set (and the latter is a list of repos).
await test(() => {
process.env.INPUT_OWNER = process.env.GITHUB_REPOSITORY_OWNER;
const currentRepoName = process.env.GITHUB_REPOSITORY.split("/")[1];
// Intentional unnecessary whitespace to test parsing to array
process.env.INPUT_REPOSITORIES = `\n ${currentRepoName}\ntoolkit \n\n checkout \n`;
});
@@ -3,7 +3,5 @@ import { test } from "./main.js";
// Verify `main` successfully obtains a token when the `owner` and `repositories` inputs are set (and the latter is a list of repos).
await test(() => {
process.env.INPUT_OWNER = process.env.GITHUB_REPOSITORY_OWNER;
const currentRepoName = process.env.GITHUB_REPOSITORY.split("/")[1];
// Intentional unnecessary whitespace to test parsing to array
process.env.INPUT_REPOSITORIES = ` ${currentRepoName}, toolkit ,checkout`;
process.env.INPUT_REPOSITORIES = `${process.env.GITHUB_REPOSITORY},actions/toolkit`;
});
@@ -3,6 +3,5 @@ import { test } from "./main.js";
// Verify `main` successfully obtains a token when the `owner` and `repositories` inputs are set (and the latter is a single repo).
await test(() => {
process.env.INPUT_OWNER = process.env.GITHUB_REPOSITORY_OWNER;
const currentRepoName = process.env.GITHUB_REPOSITORY.split("/")[1];
process.env.INPUT_REPOSITORIES = currentRepoName;
process.env.INPUT_REPOSITORIES = process.env.GITHUB_REPOSITORY;
});
@@ -1,16 +1,16 @@
import { test } from "./main.js";
// Verify `main` successfully obtains a token when the `owner` input is set, and the `repositories` input isnt set.
// Verify `main` successfully obtains a token when the `owner` input is set (to an org), but the `repositories` input isnt set.
await test((mockPool) => {
process.env.INPUT_OWNER = process.env.GITHUB_REPOSITORY_OWNER;
delete process.env.INPUT_REPOSITORIES;
// Mock installation ID and app slug request
// Mock installation id and app slug request
const mockInstallationId = "123456";
const mockAppSlug = "github-actions";
mockPool
.intercept({
path: `/users/${process.env.INPUT_OWNER}/installation`,
path: `/orgs/${process.env.INPUT_OWNER}/installation`,
method: "GET",
headers: {
accept: "application/vnd.github.v3+json",
@@ -20,7 +20,7 @@ await test((mockPool) => {
})
.reply(
200,
{ id: mockInstallationId, app_slug: mockAppSlug },
{ headers: { "content-type": "application/json" } },
{ id: mockInstallationId, "app_slug": mockAppSlug },
{ headers: { "content-type": "application/json" } }
);
});
@@ -1,6 +1,6 @@
import { test } from "./main.js";
// Verify retries work when getting a token for a user or organization fails on the first attempt.
// Verify `main` successfully obtains a token when the `owner` input is set (to a user), but the `repositories` input isnt set.
await test((mockPool) => {
process.env.INPUT_OWNER = "smockle";
delete process.env.INPUT_REPOSITORIES;
@@ -10,7 +10,7 @@ await test((mockPool) => {
const mockAppSlug = "github-actions";
mockPool
.intercept({
path: `/users/smockle/installation`,
path: `/orgs/${process.env.INPUT_OWNER}/installation`,
method: "GET",
headers: {
accept: "application/vnd.github.v3+json",
@@ -21,7 +21,7 @@ await test((mockPool) => {
.reply(500, "GitHub API not available");
mockPool
.intercept({
path: `/users/smockle/installation`,
path: `/orgs/${process.env.INPUT_OWNER}/installation`,
method: "GET",
headers: {
accept: "application/vnd.github.v3+json",
@@ -31,7 +31,7 @@ await test((mockPool) => {
})
.reply(
200,
{ id: mockInstallationId, app_slug: mockAppSlug },
{ headers: { "content-type": "application/json" } },
{ id: mockInstallationId, "app_slug": mockAppSlug },
{ headers: { "content-type": "application/json" } }
);
});
@@ -0,0 +1,37 @@
import { test } from "./main.js";
// Verify `main` successfully obtains a token when the `owner` input is set (to a user), but the `repositories` input isnt set.
await test((mockPool) => {
process.env.INPUT_OWNER = "smockle";
delete process.env.INPUT_REPOSITORIES;
// Mock installation ID and app slug request
const mockInstallationId = "123456";
const mockAppSlug = "github-actions";
mockPool
.intercept({
path: `/orgs/${process.env.INPUT_OWNER}/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(404);
mockPool
.intercept({
path: `/users/${process.env.INPUT_OWNER}/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" } }
);
});
@@ -3,6 +3,5 @@ import { test } from "./main.js";
// Verify `main` successfully obtains a token when the `owner` input is not set, but the `repositories` input is set.
await test(() => {
delete process.env.INPUT_OWNER;
const currentRepoName = process.env.GITHUB_REPOSITORY.split("/")[1];
process.env.INPUT_REPOSITORIES = currentRepoName;
process.env.INPUT_REPOSITORIES = process.env.GITHUB_REPOSITORY;
});
@@ -20,7 +20,7 @@ await test((mockPool) => {
})
.reply(
200,
{ id: mockInstallationId, app_slug: mockAppSlug },
{ headers: { "content-type": "application/json" } },
{ id: mockInstallationId, "app_slug": mockAppSlug },
{ headers: { "content-type": "application/json" } }
);
});
-7
View File
@@ -1,7 +0,0 @@
import { test } from "./main.js";
// Verify `main` successfully sets permissions
await test(() => {
process.env.INPUT_PERMISSION_ISSUES = `write`;
process.env.INPUT_PERMISSION_PULL_REQUESTS = `read`;
});
+7 -24
View File
@@ -46,8 +46,8 @@ 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 = new MockAgent({ enableCallHistory: true });
const basePath = baseUrl.pathname === '/' ? '' : baseUrl.pathname;
const mockAgent = new MockAgent();
mockAgent.disableNetConnect();
setGlobalDispatcher(mockAgent);
const mockPool = mockAgent.get(baseUrl.origin);
@@ -58,11 +58,9 @@ export async function test(cb = (_mockPool) => {}, env = DEFAULT_ENV) {
const mockInstallationId = "123456";
const mockAppSlug = "github-actions";
const owner = env.INPUT_OWNER ?? env.GITHUB_REPOSITORY_OWNER;
const currentRepoName = env.GITHUB_REPOSITORY.split("/")[1];
const repo = encodeURIComponent(
(env.INPUT_REPOSITORIES ?? currentRepoName).split(",")[0],
(env.INPUT_REPOSITORIES ?? env.GITHUB_REPOSITORY).split(",")[0]
);
mockPool
.intercept({
path: `${basePath}/repos/${owner}/${repo}/installation`,
@@ -75,15 +73,14 @@ export async function test(cb = (_mockPool) => {}, env = DEFAULT_ENV) {
})
.reply(
200,
{ id: mockInstallationId, app_slug: mockAppSlug },
{ headers: { "content-type": "application/json" } },
{ id: mockInstallationId, "app_slug": mockAppSlug },
{ headers: { "content-type": "application/json" } }
);
// Mock installation access token request
const mockInstallationAccessToken =
"ghs_16C7e42F292c6912E7710c838347Ae178B4a"; // This token is invalidated. Its from https://docs.github.com/en/rest/apps/apps?apiVersion=2022-11-28#create-an-installation-access-token-for-an-app.
const mockExpiresAt = "2016-07-11T22:14:10Z";
mockPool
.intercept({
path: `${basePath}/app/installations/${mockInstallationId}/access_tokens`,
@@ -97,26 +94,12 @@ export async function test(cb = (_mockPool) => {}, env = DEFAULT_ENV) {
.reply(
201,
{ token: mockInstallationAccessToken, expires_at: mockExpiresAt },
{ headers: { "content-type": "application/json" } },
{ headers: { "content-type": "application/json" } }
);
// Run the callback
cb(mockPool);
// Run the main script
const { default: promise } = await import("../main.js");
await promise;
console.log("--- REQUESTS ---");
const calls = mockAgent
.getCallHistory()
.calls()
.map((call) => {
const route = `${call.method} ${call.path}`;
if (call.method === "GET") return route;
return `${route}\n${call.body}`;
});
console.log(calls.join("\n"));
await import("../main.js");
}
+77 -181
View File
@@ -12,7 +12,9 @@ Generated by [AVA](https://avajs.dev).
> stdout
''
`app_id — 'app_id' is deprecated and will be removed in a future version. Use 'app-id' instead.␊
private_key — 'private_key' is deprecated and will be removed in a future version. Use 'private-key' instead.␊
skip_token_revoke — 'skip_token_revoke' is deprecated and will be removed in a future version. Use 'skip-token-revoke' instead.`
## main-custom-github-api-url.test.js
@@ -22,9 +24,7 @@ Generated by [AVA](https://avajs.dev).
> stdout
`Inputs 'owner' and 'repositories' are set. Creating token for the following repositories:
- actions/create-github-app-token␊
`owner and repositories set, creating token for repositories "actions/create-github-app-token" owned by "actions"
::add-mask::ghs_16C7e42F292c6912E7710c838347Ae178B4a␊
::set-output name=token::ghs_16C7e42F292c6912E7710c838347Ae178B4a␊
@@ -33,11 +33,17 @@ Generated by [AVA](https://avajs.dev).
::set-output name=app-slug::github-actions␊
::save-state name=token::ghs_16C7e42F292c6912E7710c838347Ae178B4a␊
::save-state name=expiresAt::2016-07-11T22:14:10Z
--- REQUESTS ---␊
GET /api/v3/repos/actions/create-github-app-token/installation␊
POST /api/v3/app/installations/123456/access_tokens␊
{"repositories":["create-github-app-token"]}`
::save-state name=expiresAt::2016-07-11T22:14:10Z`
## main-missing-app-id.test.js
> stderr
'Input required and not supplied: app-id'
> stdout
''
## main-missing-owner.test.js
@@ -49,6 +55,16 @@ Generated by [AVA](https://avajs.dev).
''
## main-missing-private-key.test.js
> stderr
'Input required and not supplied: private-key'
> stdout
''
## main-missing-repository.test.js
> stderr
@@ -59,81 +75,6 @@ Generated by [AVA](https://avajs.dev).
''
## main-private-key-with-escaped-newlines.test.js
> stderr
''
> stdout
`Inputs 'owner' and 'repositories' are not set. Creating token for this repository (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"]}`
## main-repo-skew.test.js
> stderr
`'Issued at' claim ('iat') must be an Integer representing the time that the assertion was issued.␊
[@octokit/auth-app] GitHub API time and system time are different by 30 seconds. Retrying request with the difference accounted for.`
> stdout
`Inputs 'owner' and 'repositories' are set. Creating token for the following repositories:␊
- actions/failed-repo␊
::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/failed-repo/installation␊
GET /repos/actions/failed-repo/installation␊
POST /app/installations/123456/access_tokens␊
{"repositories":["failed-repo"]}`
## main-token-get-owner-set-fail-response.test.js
> stderr
''
> stdout
`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␊
::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 /users/smockle/installation␊
GET /users/smockle/installation␊
POST /app/installations/123456/access_tokens␊
null`
## main-token-get-owner-set-repo-fail-response.test.js
> stderr
@@ -142,9 +83,7 @@ Generated by [AVA](https://avajs.dev).
> stdout
`Inputs 'owner' and 'repositories' are set. Creating token for the following repositories:
- actions/failed-repo␊
`owner and repositories set, creating token for repositories "failed-repo" owned by "actions"
Failed to create token for "failed-repo" (attempt 1): GitHub API not available␊
::add-mask::ghs_16C7e42F292c6912E7710c838347Ae178B4a␊
@@ -154,39 +93,7 @@ Generated by [AVA](https://avajs.dev).
::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/failed-repo/installation␊
GET /repos/actions/failed-repo/installation␊
POST /app/installations/123456/access_tokens␊
{"repositories":["failed-repo"]}`
## main-token-get-owner-set-repo-set-to-many-newline.test.js
> stderr
''
> stdout
`Inputs 'owner' and 'repositories' are set. Creating token for the following repositories:␊
- actions/create-github-app-token␊
- 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/create-github-app-token/installation␊
POST /app/installations/123456/access_tokens␊
{"repositories":["create-github-app-token","toolkit","checkout"]}`
::save-state name=expiresAt::2016-07-11T22:14:10Z`
## main-token-get-owner-set-repo-set-to-many.test.js
@@ -196,11 +103,7 @@ Generated by [AVA](https://avajs.dev).
> stdout
`Inputs 'owner' and 'repositories' are set. Creating token for the following repositories:
- actions/create-github-app-token␊
- actions/toolkit␊
- actions/checkout␊
`owner and repositories set, creating token for repositories "actions/create-github-app-token,actions/toolkit" owned by "actions"
::add-mask::ghs_16C7e42F292c6912E7710c838347Ae178B4a␊
::set-output name=token::ghs_16C7e42F292c6912E7710c838347Ae178B4a␊
@@ -209,11 +112,7 @@ Generated by [AVA](https://avajs.dev).
::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","checkout"]}`
::save-state name=expiresAt::2016-07-11T22:14:10Z`
## main-token-get-owner-set-repo-set-to-one.test.js
@@ -223,9 +122,7 @@ Generated by [AVA](https://avajs.dev).
> stdout
`Inputs 'owner' and 'repositories' are set. Creating token for the following repositories:
- actions/create-github-app-token␊
`owner and repositories set, creating token for repositories "actions/create-github-app-token" owned by "actions"
::add-mask::ghs_16C7e42F292c6912E7710c838347Ae178B4a␊
::set-output name=token::ghs_16C7e42F292c6912E7710c838347Ae178B4a␊
@@ -234,13 +131,9 @@ Generated by [AVA](https://avajs.dev).
::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"]}`
::save-state name=expiresAt::2016-07-11T22:14:10Z`
## main-token-get-owner-set-repo-unset.test.js
## main-token-get-owner-set-to-org-repo-unset.test.js
> stderr
@@ -248,7 +141,7 @@ Generated by [AVA](https://avajs.dev).
> stdout
`Input 'repositories' is not set. Creating token for all repositories owned by actions.
`repositories not set, creating token for all repositories for given owner "actions"
::add-mask::ghs_16C7e42F292c6912E7710c838347Ae178B4a␊
::set-output name=token::ghs_16C7e42F292c6912E7710c838347Ae178B4a␊
@@ -257,11 +150,46 @@ Generated by [AVA](https://avajs.dev).
::set-output name=app-slug::github-actions␊
::save-state name=token::ghs_16C7e42F292c6912E7710c838347Ae178B4a␊
::save-state name=expiresAt::2016-07-11T22:14:10Z
--- REQUESTS ---␊
GET /users/actions/installation␊
POST /app/installations/123456/access_tokens␊
null`
::save-state name=expiresAt::2016-07-11T22:14:10Z`
## main-token-get-owner-set-to-user-fail-response.test.js
> stderr
''
> stdout
`repositories not set, creating token for all repositories for given owner "smockle"␊
Failed to create token for "smockle" (attempt 1): GitHub API not available␊
::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`
## main-token-get-owner-set-to-user-repo-unset.test.js
> stderr
''
> stdout
`repositories not set, creating token for all repositories for given owner "smockle"␊
::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`
## main-token-get-owner-unset-repo-set.test.js
@@ -271,8 +199,7 @@ Generated by [AVA](https://avajs.dev).
> stdout
`No 'owner' input provided. Using default owner 'actions' to create token for the following repositories:
- actions/create-github-app-token␊
`owner not set, creating owner for given repositories "actions/create-github-app-token" in current owner ("actions")
::add-mask::ghs_16C7e42F292c6912E7710c838347Ae178B4a␊
::set-output name=token::ghs_16C7e42F292c6912E7710c838347Ae178B4a␊
@@ -281,11 +208,7 @@ Generated by [AVA](https://avajs.dev).
::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"]}`
::save-state name=expiresAt::2016-07-11T22:14:10Z`
## main-token-get-owner-unset-repo-unset.test.js
@@ -295,7 +218,7 @@ Generated by [AVA](https://avajs.dev).
> stdout
`Inputs 'owner' and 'repositories' are not set. Creating token for this repository (actions/create-github-app-token).
`owner and repositories not set, creating token for the current repository ("create-github-app-token")␊
::add-mask::ghs_16C7e42F292c6912E7710c838347Ae178B4a␊
::set-output name=token::ghs_16C7e42F292c6912E7710c838347Ae178B4a␊
@@ -304,34 +227,7 @@ Generated by [AVA](https://avajs.dev).
::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"]}`
## main-token-permissions-set.test.js
> stderr
''
> stdout
`Inputs 'owner' and 'repositories' are not set. Creating token for this repository (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"],"permissions":{"issues":"write","pull_requests":"read"}}`
::save-state name=expiresAt::2016-07-11T22:14:10Z`
## post-revoke-token-fail-response.test.js
Binary file not shown.