GithubHelp home page GithubHelp logo

tibdex / github-app-token Goto Github PK

View Code? Open in Web Editor NEW
487.0 8.0 141.0 855 KB

Impersonate a GitHub App in a GitHub Action

License: MIT License

JavaScript 3.94% TypeScript 96.06%
github-action javascript-github-action github-app impersonate github-token

github-app-token's Introduction

GitHub App Token

This JavaScript GitHub Action can be used to impersonate a GitHub App when secrets.GITHUB_TOKEN's limitations are too restrictive and a personal access token is not suitable.

For instance, from GitHub Actions' docs:

When you use the repository's GITHUB_TOKEN to perform tasks, events triggered by the GITHUB_TOKEN, with the exception of workflow_dispatch and repository_dispatch, will not create a new workflow run. This prevents you from accidentally creating recursive workflow runs. For example, if a workflow run pushes code using the repository's GITHUB_TOKEN, a new workflow will not run even when the repository contains a workflow configured to run when push events occur.

A workaround is to use a personal access token from a personal user/bot account. However, for organizations, GitHub Apps are a more appropriate automation solution.

Example Workflow

jobs:
  job:
    runs-on: ubuntu-latest
    steps:
      - id: create_token
        uses: tibdex/github-app-token@v2
        with:
          app_id: ${{ secrets.APP_ID }}

          # Optional.
          # github_api_url: https://api.example.com

          # Optional.
          # installation_retrieval_mode: id

          # Optional.
          # installation_retrieval_payload: 1337

          # Optional.
          # Using a YAML multiline string to avoid escaping the JSON quotes.
          # permissions: >-
          #   {"pull_requests": "read"}

          private_key: ${{ secrets.PRIVATE_KEY }}

          # Optional.
          # repositories: >-
          #   ["actions/toolkit", "github/docs"]

          # Optional.
          # revoke: false

      - run: "echo 'The created token is masked: ${{ steps.create_token.outputs.token }}'"

Another use case for this action can (or could) be found in GitHub's own docs.

github-app-token's People

Contributors

abebehailu avatar armanbilge avatar cliffchapmanrbx avatar freshollie avatar kevinneville avatar retiman avatar saviq avatar tibdex avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

github-app-token's Issues

Release notes

There are currently no release notes for 2.0 .

Can you provide some?

Revoke token when finished

The default ${{ github.token }} is only valid for the duration of a CI run. As soon as it's done it's unusable -- you can tell if you exfiltrate it and try to clone a private repo with it.

But are the tokens issued by this action ever revoked? Do they time out? Can you add a clean-up step to make sure they're revoked?

Not able to refer the value from one job to another

I have 3 github actions jobs in same workflow, where all 3 of the jobs needs this generate token step. I added the step in just one job and tried to refer it to he next two jobs by outputing in job1 and using $ {{ needs.job1.outputs.token }}, but it didnt work. I also tried passing it as env value to jobs/also steps, but that didnt work either.

I cannot create installation access token

image

I can assure both app_id and installation_id are correct. I grant this app with "metadata:read, issues:write, pull_requests:write, actions:write" permissions. PRIVATE_KEY is generated in app settings page. But it shows:

image

I'd like to know if there is some mistakes I made.

How to upgrade from v1 to v2?

I have the following code in my workflow:

steps:
      - uses: tibdex/github-app-token@v1
        id: get-token
        with:
          app_id: ${{ secrets.a }}
          private_key: ${{ secrets.b }}
          repository: example/repository

How would I update that to v2 of the action? I took a look at the readme, but it looks like the scopes changes?

Post job cleanup - Error: Could not revoke installation access token

Hello
The workflow is going well until, the post job cleanup

I get this weird error, in Post job cleanup.

Any idea why I get this error?

 Error: Could not revoke installation access token.
     at revokeInstallationAccessToken (file:///D:/a/_actions/tibdex/github-app-token/v2/dist/post/index.js:7:70955)
     at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
     at async file:///D:/a/_actions/tibdex/github-app-token/v2/dist/post/index.js:7:70644
     at async run (file:///D:/a/_actions/tibdex/github-app-token/v2/dist/post/index.js:7:71110)
     at async file:///D:/a/_actions/tibdex/github-app-token/v2/dist/post/index.js:7:70457 {
   [cause]: RequestError [HttpError]: Bad credentials
       at file:///D:/a/_actions/tibdex/github-app-token/v2/dist/post/index.js:1:45703
       at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
       at async revokeInstallationAccessToken (file:///D:/a/_actions/tibdex/github-app-token/v2/dist/post/index.js:7:70894)
       at async file:///D:/a/_actions/tibdex/github-app-token/v2/dist/post/index.js:7:70644
       at async run (file:///D:/a/_actions/tibdex/github-app-token/v2/dist/post/index.js:7:71110)
       at async file:///D:/a/_actions/tibdex/github-app-token/v2/dist/post/index.js:7:70457 {
     status: 401,
     response: {
       url: 'https://api.github.com/installation/token',
       status: 401,
       headers: [Object],
       data: [Object]
     },
     request: {
       method: 'DELETE',
       url: 'https://api.github.com/installation/token',
       headers: [Object],
       request: [Object]
     }
   }
 } 

Action does not work behind a proxy - creating installation access token

Issue: The part of the action that creates installation token does not work behind a proxy.

Reason: That part uses the @Octokit/request library to make a request to the access_token endpoint. That library in turn uses the library noda-fetch without sending in any proxy agent. The noda-fetch library does not check for http_proxy environment variables (node-fetch/node-fetch#195).

The call that fetches repo installation uses Octokit from the @actions/github library, which supports running behind a proxy.

Fix: Use @actions/github also for creating access token.

I have a simple fix for this but I need write access to be able to contribute.

Deprecation notice for @octokit/app

Hey, thanks for this! super useful.

js isn't my forte so i'm not confident enough to try to drop in the changes :) this is probably obvious but just putting it here for good measure.

[@octokit/app] Deprecated. Use @octokit/app-auth instead. See https://github.com/octokit/app.js/#deprecated

Breaking change in v1.9 release (node update)

Hi tibdex,

thank you for the awesome action. We are using it extensively on our GitHub Enterprise (GHES) instance. The change to node20 however has caused some problems for us since node20 is only available with GHES 3.10 which is relatively new.
Is there any chance you could create a patch release for 1.9 that reverts back do node16?
I would imagine other users of GHES might run into the same problem.

There are workarounds, like referencing v1.8 instead of v1 in the workflow scripts, but they have their own downsides.

Regards,
Stefan

Thank you

This is just what I needed. Had planned on creating something like this myself. Discovered through Marketplace! Thank you!

Post run failure

Description:

We started seeing this following error and we didn't upgrade any of our custom runners, we were using v1. We tried v2.0 still the same issue.

error:

image

Please use environment files instead of set-output

Per the GitHub blog, using set-output to define action outputs is deprecated in favour of using environment files. It looks like this action still uses set-output, which results in warnings being posted in the workflow output.

Please consider updating the action to use environment files instead? I would ordinarily send a PR, but the action source appears to be compiled from somewhere else, so I assume you'd prefer me not to edit it as-committed. (If that's wrong, and you can point me to where the change should be made, I'm happy to follow up with a PR).

Include yarn.lock in distributed files

Hey 👋

Would it be possible to add yarn.lock to the files in package.json?

In a world where supply chain security becomes more prevalent, it would be nice to be able to track exactly what the action was built on. For example, if I wanted to know what libraries were used in release v1.4.0 I'd have to look at the history of package.json in order to know what content was used to create this release.

This happens because, the way this action is released (create separate branch, move only some of the files) makes it difficult to trace back what the release was built on.

If yarn.lock was included in the files in package.json, and it would be included in the distributed files (tar.gz) and therefore, it would be possible to take a tag (e.g. v1.4.0), look at the yarn.lock and know what exact versions of libraries were used.

I'm happy to create a PR if you agree.

Thanks

The example of the input `repositories` is wrong.

The example is wrong.

# Optional.
# repositories: >-
# ["actions/toolkit", "github/docs"]

repositories must be a list of repository names, not repository full names.

Please see the example of the official API document.

https://docs.github.com/en/rest/apps/apps?apiVersion=2022-11-28#create-an-installation-access-token-for-an-app

curl -L \
  -X POST \
  -H "Accept: application/vnd.github+json" \
  -H "Authorization: Bearer <YOUR-TOKEN>" \
  -H "X-GitHub-Api-Version: 2022-11-28" \
  https://api.github.com/app/installations/1/access_tokens \
  -d '{"repository":"Hello-World","permissions":{"issues":"write","contents":"read"}}'

If we pass repository full names, this action can't issue tokens.

https://github.com/suzuki-shunsuke/test-github-action/actions/runs/6992873445/job/19024947554

Run tibdex/github-app-token@3beb63f4bd073e61482598c45c71c1019b59b73a
Error: Could not create installation access token.

  [cause]: RequestError [HttpError]: There is at least one repository that does not exist or is not accessible to the parent installation.

Currently seeing Error: Error: Could not get repo installation. Is the app installed on this repo?

Hello, as title states I am currently receiving a "Error: Error: Could not get repo installation. Is the app installed on this repo?" when trying to create a token for one of my sample apps. I have attached two images. One showing the error and the second showing how I am using the action. I am trying to checkout the local repo (projectA/aagent-deploy-kubernetes) and take a file from that repo and put it in the aagent-sample-app (projectB). However, I am failling on the generate token as you can see. This action is being run on Ubuntu-latest. Both the app_id and private key are in each repo as well. (I have verified the token hasnt expired.). I also want to note that this is working in other places however, it is just not working here.

Setup instructions

👋

We're using tibdex/autosquash at my company and are very happy with it. It's setup to use a the personal access token of a shared account we have, sadly that account is so broadly used that it is using up a lot of our access tokens and gets rate limited often enough that it is starting to become an annoyance.

In my research - I found this repository and wondered how I would go about setting this up, and if it would resolve our issue?

With the abundance of options to setup a new GitHub App I was a bit stunned to say the least, is there a default set of options that needs to be setup that you could share?

Installation ID maybe not following github_api_url

Very excited to see the V2 update features!

I'm using GitHub Enterprise server. It looks like the update may not be following the github_api_url input. Tried with both retrieval mode=organization (gets a 404, but no useful log) & mode=id (log below).

Would also be useful to get an example of what "JSON-stringified permissions" should look like. I used '{ "metadata": "read","contents": "read"}'

Thanks!

Run tibdex/github-app-token@v2
Error: Could not create installation access token.
    at createInstallationAccessToken (file:///home/runner/work/_actions/tibdex/github-app-token/v2/dist/main/index.js:9:86267)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async file:///home/runner/work/_actions/tibdex/github-app-token/v2/dist/main/index.js:9:875[18](https://github.com/bosch-tamer/arc-runner/actions/runs/6421442387/job/17435810580#step:2:19)
    at async run (file:///home/runner/work/_actions/tibdex/github-app-token/v2/dist/main/index.js:9:88811)
    at async file:///home/runner/work/_actions/tibdex/github-app-token/v2/dist/main/index.js:9:87468 {
  [cause]: RequestError [HttpError]: Not Found
      at file:///home/runner/work/_actions/tibdex/github-app-token/v2/dist/main/index.js:1:64431
      at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
      at async createInstallationAccessToken (file:///home/runner/work/_actions/tibdex/github-app-token/v2/dist/main/index.js:9:861[19](https://github.com/bosch-tamer/arc-runner/actions/runs/6421442387/job/17435810580#step:2:20))
      at async file:///home/runner/work/_actions/tibdex/github-app-token/v2/dist/main/index.js:9:87518
      at async run (file:///home/runner/work/_actions/tibdex/github-app-token/v2/dist/main/index.js:9:88811)
      at async file:///home/runner/work/_actions/tibdex/github-app-token/v2/dist/main/index.js:9:87468 {
    status: 404,
    response: {
      url: 'https://api.github.com/app/installations/[26](https://github.com/bosch-tamer/arc-runner/actions/runs/6421442387/job/17435810580#step:2:27)32/access_tokens',
      status: 404,
      headers: [Object],
      data: [Object]
    },
    request: {
      method: 'POST',
      url: 'https://api.github.com/app/installations/2632/access_tokens',
      headers: [Object],
      body: '{"permissions":{"metadata":"read","contents":"read"}}',
      request: [Object]
    }
  }
}

Deprecation warnings from set-env and add-path

Hi,

I noticed the following deprecation warnings when trying to use your action:

Warning: The `set-env` command is deprecated and will be disabled soon. Please upgrade to using Environment Files. For more information see: https://github.blog/changelog/2020-10-01-github-actions-deprecating-set-env-and-add-path-commands/
Warning: The `add-path` command is deprecated and will be disabled soon. Please upgrade to using Environment Files. For more information see: https://github.blog/changelog/2020-10-01-github-actions-deprecating-set-env-and-add-path-commands/

Will this PR fix this? #8

Not working with PR from fork

tibdex/backport#33 recommends setting up this action job to work around the limitations of the GITHUB_TOKEN.

However, it seems like the same limitation applies to an app ID and client secret if it is injected via (organisation) secrets:

Secrets are not passed to workflows that are triggered by a pull request from a fork. Learn more.

So, how is this supposed to work exactly?

Error: Error: error:0909006C:PEM routines:get_name:no start line

Getting a weird error when running it and I can't figure out what is wrong.

Error: Error: error:0909006C:PEM routines:get_name:no start line

I am generating two tokens - the first time it works (with the first app) and the second time it fails (with the second app)

Support for generating tokens for different servers

We're currently working on a workflow that involves automating acceptance tests for a staging deployment of GitHub Enterprise. The tests are run from our primary GitHub Enterprise server while the staging server is not in a state to run GHA workflows itself yet.

We've determined you cannot override the env vars that are set automatically in a way that this Action would be able to detect.

Please add an input to allow for an arbitrary server URL to be used as the baseURL parameter, so we can selectively override it when necessary. It should likely still default to the GITHUB_API_URL env var.

Thank you for the very useful action!

RequestError [HttpError]: 'Issued at' claim ('iat') must be an Integer representing the time that the assertion was issued

We often see this issue on macos-12 and macos-13 GitHub hosted runners (but not on Windows or Ubuntu).

Run tibdex/github-app-token@3beb63f4bd073e61482598c45c71c1019b59b73a
  with:
    app_id: 291899
    installation_retrieval_mode: id
    installation_retrieval_payload: 34040165
    private_key: ***
    permissions: {
    "administration": "write",
    "contents": "write",
    "metadata": "read",
    "packages": "write",
    "pages": "write",
    "pull_requests": "read"
  }
    github_api_url: https://api.github.com/
    revoke: true
  env:
    NPM_REGISTRY: https://registry.npmjs.org/
    CARGO_REGISTRY: crates.io
Error: Could not create installation access token.
    at createInstallationAccessToken (file:///Users/runner/work/_actions/tibdex/github-app-token/3beb63f4bd073e61482598c45c71c1019b59b73a/dist/main/index.js:9:86267)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async file:///Users/runner/work/_actions/tibdex/github-app-token/3beb63f4bd073e61482598c45c71c1019b59b73a/dist/main/index.js:9:87518
    at async run (file:///Users/runner/work/_actions/tibdex/github-app-token/3beb63f4bd073e61482598c45c71c1019b59b73a/dist/main/index.js:9:88811)
    at async file:///Users/runner/work/_actions/tibdex/github-app-token/3beb63f4bd073e61482598c45c71c1019b59b73a/dist/main/index.js:9:87468 {
  [cause]: RequestError [HttpError]: 'Issued at' claim ('iat') must be an Integer representing the time that the assertion was issued
      at file:///Users/runner/work/_actions/tibdex/github-app-token/3beb63f4bd073e61482598c45c71c1019b59b73a/dist/main/index.js:1:64431
      at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
      at async createInstallationAccessToken (file:///Users/runner/work/_actions/tibdex/github-app-token/3beb63f4bd073e61482598c45c71c1019b59b73a/dist/main/index.js:9:86119)
      at async file:///Users/runner/work/_actions/tibdex/github-app-token/3beb63f4bd073e61482598c45c71c1019b59b73a/dist/main/index.js:9:87518
      at async run (file:///Users/runner/work/_actions/tibdex/github-app-token/3beb63f4bd073e61482598c45c71c1019b59b73a/dist/main/index.js:9:88811)
      at async file:///Users/runner/work/_actions/tibdex/github-app-token/3beb63f4bd073e61482598c45c71c1019b59b73a/dist/main/index.js:9:87468 {
    status: 401,
    response: {
      url: 'https://api.github.com/app/installations/34040165/access_tokens',
      status: 401,
      headers: [Object],
      data: [Object]
    },
    request: {
      method: 'POST',
      url: 'https://api.github.com/app/installations/34040165/access_tokens',
      headers: [Object],
      body: '{"permissions":{"administration":"write","contents":"write","metadata":"read","packages":"write","pages":"write","pull_requests":"read"}}',
      request: [Object]
    }
  }
}

Sometimes a retry will work, but it seems pretty random. On every run there's maybe a 50% chance of hitting this failure.

It looks like it might be an issue with the time sync on the GitHub hosted macos runners, but thought I would open an issue here in case there is a known workaround or root cause.

Is there any other information I can provide?

V1 contains breaking changes and switch on node20, even tough it should not

388799a - this should not be part of tag v1 right? seems like all release point to some wired commits.

System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. (Parameter ''using: node20' is not supported, use 'docker', 'node12' or 'node16' instead.')
at GitHub.Runner.Worker.ActionManifestManager.ConvertRuns(IExecutionContext executionContext, TemplateContext templateContext, TemplateToken inputsToken, String fileRelativePath, MappingToken outputs)
at GitHub.Runner.Worker.ActionManifestManager.Load(IExecutionContext executionContext, String manifestFile)

Make errors more verbose?

Hi,

I just configured an organization app and setup this action. My workflow fails with the message below:

Run tibdex/github-app-token@v1
  with:
    app_id: ***
    private_key: ***
##[error]Not Found

The string Not Found doesn't seem to even appear in this repo, so I don't have any other option but go create a personal token instead. A more verbose error would have helped.

For action@v1 the change between 1.8.x and 1.9.x might be breaking

Just a quick note on the compatibility of the minor semver upgrade from 1.8.x to 1.9.0. There was an upgrade from node16 to node20 that causes a potential slew of OS related issues. We were using a major semver pinning of @v1. I think we assumed the below semver guidelines. For our self hosted runners this caused a breakage:

Screenshot 2023-09-12 at 9 31 22 AM

We changed to pin version tibdex/[email protected] and our issue is resolved for now, but 1.9.0 might be a breaking change for others as well.

Changes

Screenshot 2023-09-12 at 9 27 34 AM

Semver Guidelines

Given a version number MAJOR.MINOR.PATCH, increment the:

MAJOR version when you make incompatible API changes
MINOR version when you add functionality in a backward compatible manner
PATCH version when you make backward compatible bug fixes
Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format.

Give clearer error when app isn't installed

I spent a while puzzling over this error

Screenshot 2022-04-09 at 02-13-49 Sync Upstream · neuropoly_gitea@fb17c4b

Eventually I debugged it and figured out it was failing in

} = await octokit.rest.apps.getRepoInstallation({ owner, repo }));

which is because I'd neglected to Install the OAuth app I'd created to my repo.

Do you think there's a way to make this clearer? Could we put an extra try-catch around that line with a link to https://docs.github.com/en/developers/apps/managing-github-apps/installing-github-apps?

Plans for this action given the new official `actions/create-github-app-token`?

The readme in this repo links to an old version of the docs:
https://web.archive.org/web/20230115194214/https://docs.github.com/en/issues/planning-and-tracking-with-projects/automating-your-project/automating-projects-using-actions#example-workflow-authenticating-with-a-github-app

...which have now been updated here:
https://docs.github.com/en/issues/planning-and-tracking-with-projects/automating-your-project/automating-projects-using-actions#example-workflow-authenticating-with-a-github-app

...to use the new official action:

...which now in a few weeks seems to have gained the equivalent feature set (and hopefully stays maintained/improved).

Just thought I'd raise this issue to surface any thoughts on how these two actions relate to each other.

There also seems to be a bunch of others in the same field:

Provide a Pre-Exisiting Installation ID

@tibdex 👋

Would you be open to a pull request that adds the capability to provide a pre-existing Installation ID? 🤔

the majority of this GitHub Action does what we need, however, we have a use case where we just need a create a JWT from a pre-installed GitHub App, vs creating a new "installation".

We could keep installationID optional? Would love your thoughts? 💯

Also open to creating a few unit tests if you're interested 👍 Something like this. I think I can make it work so it would just be a "minor" release, e.g. new feature 👍

Thanks!

Error: HttpError: Not Found

When using the bare minimum example i get following error:

Error: HttpError: Not Found

I think that might relates to the GITHUB_API_URL in the fetch request?

Code:

jobs:
  track_pr:
    runs-on: ubuntu-latest
    steps:
      - name: Generate token
        id: generate_token
        uses: tibdex/github-app-token@v1
        with:
          app_id: ${{ secrets.APP_ID }}
          private_key: ${{ secrets.APP_PEM }}

Usage without repository scope

Hello,

is it possible to use the action without mentioning a repository so that the token is valid for multiple repositories the app has permissions to?

I get the following error:
image

Best regards,
Markus

Degradation due to 'token revocation' post script

Token revocation has introduced a degradation to our workflows as we're using the token after the github action job is finished.
A switch whether a token should be deleted via post script or keep the old behaviour would be much appreciated.

Fail with node20

Thank you for the great action! With the recent updates, following the action gives the following error:

Error: System.ArgumentOutOfRangeException: Specified
argument was out of the range of valid values. (Parameter
''using: node20' is not supported, use 'docker', 'node12' or 'node16' instead.')
at GitHub.Runner.Worker.ActionManifestManager.
ConvertRuns(IExecutionContext executionContext, TemplateContext
templateContext, TemplateToken inputsToken, String fileRelativePath,
MappingToken outputs)
at GitHub.Runner.Worker.ActionManifestManager.Load(IExecutionContext
executionContext, String manifestFile)
Error: Fail to load tibdex/github-app-token/v1/action.yml

What can be done in this case? I've tried to pin to previous versions of action but nothing works.

Version `GLIBC_2.27' not found

Hi there, we've started seeing a few errors with the recent release of 1.9.0:

Post job cleanup.
/usr/local/bin/docker exec  348966fe710361d7[2](https://github.com/xyz/actions/runs/6144996350/job/16671534902#step:31:2)21acd20e2e7c6fba46[3](https://github.com/xyz/actions/runs/6144996350/job/16671534902#step:31:3)cda8f5d5689f73507bd67242954a sh -c "cat /etc/*release | grep ^ID"
/__e/node20/bin/node: /lib64/libm.so.6: version `GLIBC_2.27' not found (required by /__e/node20/bin/node)
/__e/node20/bin/node: /lib6[4](https://github.com/xyz/actions/runs/6144996350/job/16671534902#step:31:4)/libstdc++.so.6: version `GLIBCXX_3.4.20' not found (required by /__e/node20/bin/node)
/__e/node20/bin/node: /lib64/libstdc++.so.6: version `CXXABI_1.3.9' not found (required by /__e/node20/bin/node)
/__e/node20/bin/node: /lib64/libstdc++.so.6: version `GLIBCXX_3.4.21' not found (required by /__e/node20/bin/node)
/__e/node20/bin/node: /lib64/libc.so.6: version `GLIBC_2.28' not found (required by /__e/node20/bin/node)
/__e/node20/bin/node: /lib64/libc.so.6: version `GLIBC_2.2[5](https://github.com/xyz/actions/runs/6144996350/job/16671534902#step:31:5)' not found (required by /__e/node20/bin/node)

When we manually pin the version back to 1.8.2 our previous workflows run fine. Think there may be some breaking changes in the latest 1.x version?

Add an optional input `repository_ids`

What?

Add an optional input repository_ids, which is a list of repository IDs that the token should have access to.

https://docs.github.com/en/rest/apps/apps?apiVersion=2022-11-28#create-an-installation-access-token-for-an-app

          repository_ids: >-
            [${{github.repository_id}}]

Why?

To limit repositories.
The advantage of repository_ids compared with repositories is that we can get repository_id from github context's github.repository easily.
On the other hand, it is a little difficult to get a repository name from github context.

Question: not working with my current set-up?

  1. Does this action works and allows to replace a personnal access token with a github app token in every situation? Or are there limitations when using this action?

  2. In my current setup I have an action to automatically merge dependabot MR.

I have added the github app app_id as GH_APP_ID in the repository action secrets, and I have generated a private key in my app. I have added the key in its entirety (including the BEGIN RSA and END RSA) as GH_APP_KEY also in the repository action secrets.

However, when running this action, I get the following error at the github-app-token generating key step:
Error: Input required and not supplied: private_key

Here is the code for the action.

name: Dependabot-merge

on:
  pull_request:

jobs:
  auto-merge:
    runs-on: ubuntu-latest
    steps:
      - name: Generate GH token
        id: generate_token
        uses: tibdex/github-app-token@v1
        with:
          app_id: ${{ secrets.GH_APP_ID }}
          private_key: ${{ secrets.GH_APP_PKEY }}
      - uses: actions/checkout@v3
      - name: Automerge Dependabot PR
        uses: ahmadnassri/action-dependabot-auto-merge@v2
        with:
          target: minor
          github-token: ${{ secrets.generate_token.outputs.token }}

What am I doing wrong?

I also want to highlight that for some reason, it "almost" works with another action I have. The error is different though: here the link to the issue in the other action repository.

Thanks in advance

Workflow still not running with Labeler

I seem to have no success with github_app-token + labeler. Here is my workflow:

name: Labeler
on: [pull_request_target]

jobs:
  triage:
    runs-on: ubuntu-latest

    permissions:
      contents: read
      pull-requests: write

    steps:
      - uses: actions/checkout@v2

      - name: Generate unique app token
        uses: tibdex/github-app-token@v1
        id: generate-token
        with:
          app_id: ${{ secrets.SPECIAL_APP_ID }}
          private_key: ${{ secrets.SPECIAL_APP_PRIVATE_KEY }}

      - name: Apply PR labels
        uses: actions/labeler@v3
        with:
          repo-token: ${{ steps.generate-token.outputs.token }}

labeler runs perfectly whenever a PR is put up by a contributor. But, if github-actions opens a PR, this check is never run. The one workflow triggering the effected PR is changesets/action@v1.

I'm curious if anyone else has run into this? Perhaps this is an issue with pull_request_target and/or permissions?

Any help is appreciated!

permissions input needs to use underscore instead of hyphen

The permissions input of this action has no documented valid items. So I assumed it was the same as the native GITHUB_TOKEN permissions. However, I tried putting in "pull-requests": "write" and it didn't work, error message was "Error: Could not create installation access token."
I used "pull_requests": "write" instead and it worked.

Don't know if this should be seen as a bug, but I thought it could be good to have a record of it somewhere. If the behavior won't be changed, maybe add some information to the README.

Thanks for creating this action, everything else is working great!

Test Workflow Does Not Test Against Expectations - Use Mocks Instead of GitHub App

Problem

Respectfully, pull request 64 from pull request 55 and issue 54 just broke all 78 forks of your project and increased the barrier to entry for contributors to submit pull requests.

For example, here I pushed a commit to my fork of your project containing my proof that P = NP, and here you can see your workflow fails in my fork because I have not installed a GitHub App that satisfies the new test. This can also happen on base branches, release branches, and tags in forks and people may incorrectly believe your action is broken when it is not. While it may sound simple to you and I to install an app that satisfies your test, that process is undocumented and it requires admin approval in organizations that could be prohibitive for developers to obtain.

A test that relies on a GitHub repo to be configured in a specific way such that it fails on forks is not a robust or reliable test. There are several reasons why a test should not rely on external factors like this:

  1. Non-deterministic results: Tests that rely on external factors like the configuration of a GitHub repo may produce inconsistent or non-deterministic results, making it difficult to know if the system is working correctly or not.
  2. Environment-specific: Tests that rely on external factors may only work in specific environments and may not be portable across different development, staging, or production environments.
  3. Maintenance: Tests that rely on external factors may require additional maintenance to ensure that they continue to work correctly as the external factors change over time.
  4. Lack of isolation: Tests that rely on external factors are not properly isolated from the environment and other dependencies, and therefore they may be affected by changes that are unrelated to the code being tested.
  5. Lack of scalability: Tests that rely on external factors may not be able to scale as the system or the number of users grows, leading to performance issues or time-consuming tests.

It is important to design tests that are robust, reliable, and isolated from external factors to ensure that they can produce consistent and accurate results and can be easily maintained over time.

Consider the purpose of your test and what it is fundamentally testing. Your existing test does not only test code correctness, it also tests for the existence of a GitHub App. We should write a test that tests for code correctness and nothing else.

Solution

There are a lot of valid ways to solve this problem. I, personally, really love the jest test framework. It allows you to mock libraries including octokit very easily.

Here is an example written by ChatGPT using jest to mock octokit and implementing a test against your fetchInstallationToken function in fetch-installation-token.ts.

import { fetchInstallationToken } from "./fetchInstallationToken";
import { getOctokit } from "@actions/github";
import { request } from "@octokit/request";

// mocks
jest.mock("@octokit/rest", () => {
  return {
    apps: {
      getRepoInstallation: jest.fn().mockResolvedValue({
        data: { id: 123 }
      }),
      createInstallationAccessToken: jest.fn().mockResolvedValue({
        data: { token: 'installation-token' }
      })
    }
  }
});

jest.mock("@actions/github", () => {
  return {
    getOctokit: jest.fn()
  }
});

jest.mock("@octokit/request", () => {
  return {
    defaults: jest.fn()
  }
});

// clean up after each test
afterEach(() => {
  jest.clearAllMocks();
});

// test suite
describe("fetchInstallationToken", () => {
  test("should fetch the installation token", async () => {
    const result = await fetchInstallationToken({
      appId: "123",
      githubApiUrl: new URL("https://api.github.com"),
      owner: "owner",
      repo: "repo",
      privateKey: "private-key"
    });

    expect(result).toBe("installation-token");
    expect(getOctokit).toHaveBeenCalledWith("installation-token");
    expect(request.defaults).toHaveBeenCalledWith({
      baseUrl: "https://api.github.com"
    });
  });
});

Instead of jest mocks, you could also use nock to intercept the REST API calls octokit makes to the Internet. Here is an example of that from ChatGPT.

import nock from "nock";
import { fetchInstallationToken } from "./fetchInstallationToken";

describe("fetchInstallationToken", () => {
  afterEach(() => {
    jest.clearAllMocks();
    nock.cleanAll();
  });

  test("should return installation token", async () => {
    const appId = "123";
    const githubApiUrl = new URL("https://api.github.com");
    const installationId = 1234;
    const owner = "octocat";
    const repo = "hello-world";
    const privateKey = "-----BEGIN RSA PRIVATE KEY-----\n...";

    const installationAccessToken = "abcdefghijklmnopqrstuvwxyz";

    nock(githubApiUrl.toString())
      .post("/app/installations/1234/access_tokens", {})
      .reply(200, {
        token: installationAccessToken,
      });

    const token = await fetchInstallationToken({
      appId,
      githubApiUrl,
      installationId,
      owner,
      privateKey,
      repo,
    });

    expect(token).toEqual(installationAccessToken);
  });
});

I strongly recommend against this solution because the purpose of the test is to test this GitHub Action for correctness, not to test octokit for correctness. The jest mock example solely tests this GitHub Action for correctness, whereas the nock example tests both the GitHub Action and octokit for correctness. If GitHub changed the implementation of their REST API and octokit changed in kind, this test would fail on passing code. I included an example with nock because it does remove the GitHub repo configuration as a variable and it is a tool worth knowing about.


I also like to add this to my package.json when working with jest.

{
  "scripts": {
    "test": "jest --coverage"
  },
  "jest": {
    "clearMocks": true,
    "collectCoverage": true,
    "collectCoverageFrom": [
      "**/*.js",
      "**/*.ts"
    ],
    "coveragePathIgnorePatterns": [
      "coverage",
      "dist",
      "node_modules"
    ],
    "coverageThreshold": {
      "global": {
        "branches": 100,
        "functions": 100,
        "lines": 100,
        "statements": 100
      }
    },
    "testPathIgnorePatterns": [
      "coverage",
      "dist",
      "node_modules"
    ]
  }
}

This allows you to run jest using yarn test, and requires full test coverage.

Your GitHub Action test workflow would become:

name: Test
on:
  push:
    branches-ignore:
      - main

jobs:
  test:
    name: Test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - run: yarn install --frozen-lockfile
      - run: yarn run yarn-deduplicate --fail --strategy fewer
      - run: yarn run build
      - run: yarn run prettier --check
      - run: yarn run xo
      - run: yarn test

Legal notice:
This document was generated in collaboration with the 2023-01-09 version of ChatGPT from OpenAI, a machine learning algorithm or weak artificial intelligence (AI). At the time of this writing, the OpenAI terms of service agreement §3.a states:

Your Content. You may provide input to the Services (“Input”), and receive output generated and returned by the Services based on the Input (“Output”). Input and Output are collectively “Content.” As between the parties and to the extent permitted by applicable law, you own all Input, and subject to your compliance with these Terms, OpenAI hereby assigns to you all its right, title and interest in and to Output.

I release this content under the MIT license.

This notice is required in some countries.

Action fails on ubuntu-jammy runner

Description

When using the action on a github runner with ubuntu-jammy (22.04) it fails with:

Error

Error: Error: error:25066067:DSO support routines:dlfcn_load:could not load the shared library

Usage

jobs:
    build:
    runs-on: ubuntu-jammy
        steps:
          - name: Generate token from github app
            id: generate_token
            uses: tibdex/[email protected]
            with:
              app_id: ${{ secrets.APP_ID }}
              private_key: ${{ secrets.APP_KEY }}

References

Support org-level installation ID retrieval.

When a GitHub App is installed into an organization it's more appropriate to get the installation ID using the /orgs/{org}/installations API. Currently we work around this issue by providing a known-existing repository, but are getting closer to situations where we don't (or don't want to) know what repos are available.

Adding an organization input, similar to the current repository input, would provide a better experience for that use case.

I can take some time to submit a PR for this either later this week or next if someone else doesn't beat me to it.

private_key only supports actions secrets?

I appreciate such a handy Github Action!
I have something to ask.
Would it only work with a private_key stored as an actions secret?

I'm running my actions on a self-hosted runner and I'm trying to pass a raw private_key of my Github App, which is stored in the GCP's secret manager in JSON format with Github App ID and Github App Installation ID and retrieved from it in another step, to github-app-token as the step's output.

That causes this error.

2022-06-23T05:54:09.8957322Z ##[error]Error: error:0909006C:PEM routines:get_name:no start line

My workflow steps look like these.

    - name: Github App Private Key
      id: github_app
      run: |
        gcloud secrets versions access latest --project=my-gcp-project --secret=github-app > github-app
        cat github-app | jq -r .github_app_id | xargs -I {} echo "::set-output name=github_app_id::{}"
        cat github-app | jq -r .github_app_installation_id | xargs -I {} echo "::set-output name=github_app_installation_id::{}"
        cat github-app | jq -r .github_app_private_key > github_app_private_key
        echo "::set-output name=github_app_private_key::${github_app_private_key//$'\n'/\\n}"
    - name: Generate Github Token
      id: generate_github_token
      uses: tibdex/github-app-token@v1
      with:
        app_id: ${{ steps.github_app.outputs.github_app_id }}
        private_key: ${{ steps.github_app.outputs.github_app_private_key }}
        installation_id: ${{ steps.github_app.outputs.github_app_installation_id }}
        repository: myorg/myrepo

Are there any way to pass non-actions-secret private_key as a private_key, or am I doing something wrong in the steps?

Error: secretOrPrivateKey must be an asymmetric key when using RS256

The action worked a couple of days ago but started failing with the error in the subj.

I've tried multiple workarounds to no avail:

The same workflow worked just a few days ago: https://github.com/gravitational/teleport/actions/runs/4566287502.

Any idea what's wrong and how to fix it?

Thanks!

PEM routines:get_name:no start line

Hi, I'm trying to get this action running to use with peter-evans/create-pull-request.

I'm using it like this:

- uses: tibdex/github-app-token@v1
  id: generate-token
  with:
    app_id: ${{ secrets.PR_APP_ID }}
    private_key: ${{ secrets.PR_APP_PRIV_KEY }}

and the error is

2021-04-29T19:57:42.4816536Z ##[group]Run tibdex/github-app-token@v1
2021-04-29T19:57:42.4817128Z with:
2021-04-29T19:57:42.4817976Z   app_id: ***
2021-04-29T19:57:42.4818651Z   private_key: ***
2021-04-29T19:57:42.4819098Z ##[endgroup]
2021-04-29T19:57:42.5590518Z ##[error]Error: error:0909006C:PEM routines:get_name:no start line

I don’t have any ideas of how to debug this since I'm pretty new to using github actions. Any help would be appreciated.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.