Right way to run action for code checking

In our repository we had and action to run PHP CS check.
We are using pull_request_event but we had issues correctly run the action while a PR from a forked branch.
Here it is the code:

---
name: Backend Coding Standard
on: [ push, pull_request_target ]
jobs:
  backend-lint:
    runs-on: ubuntu-latest
    steps:
    - name: Checkout
      uses: actions/checkout@v2
      with:
          ref: ${{ github.event.pull_request.head.sha }}

    - uses: shivammathur/setup-php@v2
      with:
        php-version: '7.3'

    - name: Add composer repositories
      env:
        USERNAME: ${{ secrets.COMPOSER_MAGENTO_USERNAME }}
        PASSWORD: ${{ secrets.COMPOSER_MAGENTO_PASSWORD }}
      run: composer config repositories.magento composer https://$USERNAME:$PASSWORD@repo.magento.com/

    - name: Install dependencies
      run: composer install --prefer-dist --no-progress --no-suggest

    - name: Run tests
      run: composer run-script test

The only way I found to correctly run the action by a PR from a fork is adding the ref: ${{ github.event.pull_request.head.sha }} in the action/checkout@v2 but I know it is not safe as here exposed Keeping your GitHub Actions and workflows secure: Preventing pwn requests | GitHub Security Lab

I also tried to refactor my code in this test repo, but it doesn’t work on PR from a fork CsTest/.github/workflows at develop · emastyle/CsTest · GitHub

Can anyone suggest how to run the same action via workflow_run instead, or how to run correctly the action?

… Any useful examples?
Thank you!

Hi @emastyle

You’re saying

We are using pull_request_event but we had issues correctly run the action while a PR from a forked branch.

But isn’t the whole point of using pull_request_target is to not expose and allow the github action to run in forked branches? Per the docs:

This event runs in the context of the base of the pull request, rather than in the merge commit as the pull_request event does. This prevents executing unsafe workflow code from the head of the pull request that could alter your repository or steal any secrets you use in your workflow. 

Or more specifically, what is the issue you are trying to fix here?

Thinking of something else now too - perhaps you could make use of Environment Secrets if you want to limit the exposure of sensitive information and this can help you run GitHub Actions in PR from forked repos?