MultiPaaS

Test each pull request in its own environment

A CI job can give every pull request its own environment, with its own app-tenants and data, and delete it when the pull request closes. The job signs in as a deployer: a credential that can create environments and delete only the ones it created. In those environments it can create app-tenants and app identities, give those app identities roles, and invite people by email to an app-tenant there, with a role that doesn't change the model or manage environments. It can't change the model, role definitions, sign-in clients, API versions or imports, and it can't reach any other environment, including the default one. The deployer commands need CLI 1.5.0 or later, and envs delete needs 1.7.0 or later.

Create the deployer

Someone who holds access.manage.application from a role granted in every environment, or a client admin who holds it in the application's default environment, creates it once:

multipaas deployers create --app APP_ID --name "CI"

It prints the deployer's client ID and secret. The secret is shown once. Store the two as CI secrets named MULTIPAAS_CLIENT_ID and MULTIPAAS_CLIENT_SECRET, never in the repo. If the pull request's preview signs users in, also set a repository variable named SIGN_IN_CLIENT_ID that holds your sign-in client's id (the oauthClientId in multipaas.json); see "Sign-in for the preview" below.

When a pull request opens, reopens or changes

On GitHub Actions, run this setup job on the opened, reopened and synchronize activity types, so every push is tested in the pull request's environment. A deleted environment no longer holds its name, so a reopened pull request can create pr-REPO_ID-NUMBER again.

Read each --json answer into a variable, and never print it in your own steps. app-identity create prints its secret once, and the job log would keep what is printed. The deployer secrets never reach a log. Start the script with set -euo pipefail, so a refused command stops the job instead of passing an empty or null id on. The tenants invite step is the one deliberate exception: it handles two refusals itself, as described below.

With both variables set, the CLI acts as the deployer and needs no multipaas login:

set -euo pipefail
ENV_ID=$(multipaas envs list --app APP_ID --json | jq -r --arg name "pr-$REPO_ID-$PR_NUMBER" '.[] | select(.name == $name) | .id')
if [ -z "$ENV_ID" ]; then
  ENV_ID=$(multipaas envs create --app APP_ID --name "pr-$REPO_ID-$PR_NUMBER" --json | jq -r .environment.id)
fi
if [ -n "${SIGN_IN_CLIENT_ID:-}" ]; then
  multipaas envs redirect-uris set --app APP_ID --env "$ENV_ID" --sign-in-client "$SIGN_IN_CLIENT_ID" --redirect-uri "https://pr${PR_NUMBER}.example.com/callback" --json > /dev/null
fi
APP_TENANT_ID=$(multipaas tenants list --app APP_ID --env "$ENV_ID" --json | jq -r --arg name "PR test" 'first(.[] | select(.name == $name) | .id) // empty')
if [ -z "$APP_TENANT_ID" ]; then
  APP_TENANT_ID=$(multipaas tenants create --app APP_ID --env "$ENV_ID" --name "PR test" --json | jq -r .appTenant.id)
fi
if ! INVITE=$(multipaas tenants invite --app APP_ID --tenant "$APP_TENANT_ID" --role member --email reviewer@example.com --json); then
  case "$(jq -r .error.code <<< "$INVITE")" in
    DUPLICATE_INVITATION|ALREADY_MEMBER) ;;
    *) echo "$INVITE" >&2; exit 1 ;;
  esac
fi
IDENTITY=$(multipaas app-identity create --app APP_ID --env "$ENV_ID" --name "PR job" --json)
CLIENT_ID=$(jq -r .appIdentity.id <<< "$IDENTITY")
CLIENT_SECRET=$(jq -r .secret <<< "$IDENTITY")
multipaas app-identity role add "$CLIENT_ID" --app APP_ID --tenant "$APP_TENANT_ID" --role KEY --json
{
  echo "env_id=$ENV_ID"
  echo "app_tenant_id=$APP_TENANT_ID"
  echo "client_id=$CLIENT_ID"
  echo "client_secret=$CLIENT_SECRET"
} >> "$GITHUB_OUTPUT"

The script doesn't mask the secret, because GitHub drops a job output that holds a masked value. The secret passes through the job outputs to the test job, which masks it in its first step. The runner prints that step's env in the log before the step can mask it, so the identity's secret appears once in the test job's log. Anyone who can read the repository's Actions logs can see it, and on a public repository that is everyone. That is acceptable, because the identity holds roles in that pull request's environment only, and the cleanup job deletes the environment when the pull request closes. With a reviewer invited, the identity's token can also read what the reviewer enters at that app-tenant, as far as its role allows, so on a public repository reviewers should enter test data only. The masking step stops every later step from printing the secret again.

The name carries the repository's numeric id because environment names are unique in an application, which several repositories can share, and repository names repeat across owners. The job looks for pr-REPO_ID-NUMBER first and creates the environment and app-tenant only when they are missing, so a re-run, or a reopen that replaced a queued close, reuses them. App-tenant names aren't unique, so the selection takes the first match and uses that one id from there on. An app identity's secret is shown only once, so each run creates a new identity, and the earlier one stays until the environment is removed.

The application's manager can see and manage roles in a preview environment, because they hold App manager in every environment, and can give a teammate a role there.

Run as the deployer, app-identity role add refuses a role that can change the model or manage environments, such as the App manager role. The app identity's token works as Run background jobs describes.

The tenants invite step in the script invites a person to an app-tenant in an environment the deployer created, a reviewer of the pull request, for example. It needs CLI 1.12.0 or later. The person gets the role when they accept the emailed link. The deployer can't invite to an app-tenant outside its own environments, into a group, at the client level, or to a role that can change the model or manage environments. In those app-tenants it can also run tenants members to list the members and the pending invitations it could itself have sent, those with no group and only roles it could give, and tenants invitation update to replace the roles of a pending one, under the same limits and from CLI 1.12.0 or later.

The step runs on every run, so a run that failed after the app-tenant was created still invites the reviewer when it is run again. A run after one that already invited the address is refused with DUPLICATE_INVITATION, or with ALREADY_MEMBER once the person has accepted, and the script treats both as done. Any other refusal stops the job. If sending the invitation email fails, the step fails with INVITATION_NOT_SENT and creates no invitation, so the job stops there on that run and a later run invites the reviewer once the email can be sent. If it keeps failing, check the address. An invitation expires after 7 days. After that, someone who manages access at that app-tenant, such as the application's manager, resends it from the app-tenant's Members page in the web app, under Invitations. The deployer can't resend or delete one. When the environment is deleted, an invitation the person hasn't accepted stops working at once: accepting it is refused.

Run the tests in it

Your project's multipaas.json names another environment and app-tenant, so the tests would still run there. Pass the new ENV_ID, APP_TENANT_ID, CLIENT_ID and CLIENT_SECRET to the test run as environment variables that your app's test configuration reads in place of environmentId and testAppTenantId. Never pass the secret as a command-line argument.

Sign-in for the preview

If the pull request's preview signs users in, the envs redirect-uris set step above registers the preview's callback URL on its environment. It runs on every run, so an environment created before the variable was set gets the callback too, and because set replaces the environment's callbacks for that client, running it again changes nothing. SIGN_IN_CLIENT_ID is your app's sign-in client id: the oauthClientId in multipaas.json, or the ID column of multipaas oauth-client list --app APP_ID. Set it as a repository variable; the script adds the callback only when the variable is set. The --redirect-uri is the preview's own callback. The deployer can set an environment's callbacks only in environments it created. multipaas envs create also takes --sign-in-client and --redirect-uri, to register them when it creates the environment. An environment accepts at most 10 per sign-in client, under the same rules as the client's own redirect URIs.

The preview's authorize request must carry environment=ENV_ID. Without it the environment's callback is refused, because it works only when the sign-in names that environment. The callback goes away with the environment, so the cleanup job needs no extra step.

Keep the deployer secrets away from the pull request's code

Code from a pull request can read any secret in the job it runs in, and a later step of the same job can read one an earlier step used. So run the deployer only in jobs that never run the pull request's code: no checkout of its head followed by a build script, a package install or a test. Use three jobs. The setup and cleanup jobs get MULTIPAAS_CLIENT_ID and MULTIPAAS_CLIENT_SECRET. The test job needs the setup job, gets no deployer secret, and masks the identity's secret in its first step:

on:
  pull_request:
    types: [opened, reopened, synchronize, closed]
concurrency:
  group: deployer-pr-${{ github.event.pull_request.number }}
jobs:
  setup:
    if: github.event.action != 'closed' && github.event.pull_request.head.repo.full_name == github.repository && github.event.pull_request.user.login != 'dependabot[bot]'
    runs-on: ubuntu-latest
    outputs:
      env_id: ${{ steps.deployer.outputs.env_id }}
      app_tenant_id: ${{ steps.deployer.outputs.app_tenant_id }}
      client_id: ${{ steps.deployer.outputs.client_id }}
      client_secret: ${{ steps.deployer.outputs.client_secret }}
    steps:
      - id: deployer
        env:
          REPO_ID: ${{ github.event.repository.id }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
          SIGN_IN_CLIENT_ID: ${{ vars.SIGN_IN_CLIENT_ID }}
          MULTIPAAS_CLIENT_ID: ${{ secrets.MULTIPAAS_CLIENT_ID }}
          MULTIPAAS_CLIENT_SECRET: ${{ secrets.MULTIPAAS_CLIENT_SECRET }}
        run: ... # the setup script above, after installing the CLI
  test:
    needs: setup
    runs-on: ubuntu-latest
    steps:
      - env:
          CLIENT_SECRET: ${{ needs.setup.outputs.client_secret }}
        run: echo "::add-mask::$CLIENT_SECRET"
      - uses: actions/checkout@v4
      - run: ... # the tests, with the four values in environment variables
  cleanup:
    if: github.event.action == 'closed' && github.event.pull_request.head.repo.full_name == github.repository && github.event.pull_request.user.login != 'dependabot[bot]'
    runs-on: ubuntu-latest
    steps:
      - env:
          REPO_ID: ${{ github.event.repository.id }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
          MULTIPAAS_CLIENT_ID: ${{ secrets.MULTIPAAS_CLIENT_ID }}
          MULTIPAAS_CLIENT_SECRET: ${{ secrets.MULTIPAAS_CLIENT_SECRET }}
        run: ... # the close script below, after installing the CLI

On a pull_request run GitHub uses the workflow file from the pull request, so anyone whose pull request runs with these secrets can read them by changing the workflow. Use a deployer only in a repository where everyone who can push a branch is trusted with it.

A pull_request run from a fork gets no secrets unless a private repository turns on GitHub's "Send secrets to workflows from pull requests" setting. Keep that setting off: with it on, a fork could remove the if and read the deployer's secrets. With it off, the CLI would answer NOT_SIGNED_IN in a fork's run, so the if skips the jobs when the head repository isn't this one. A run that Dependabot itself triggers gets Dependabot secrets, not the deployer's Actions secrets, so it can't sign in as the deployer. The if therefore checks the pull request's author, not who triggered the run, so every run of a Dependabot pull request is skipped, including one a person triggers. Otherwise a person's push could create an environment that is never deleted: when Dependabot closes a pull request it has superseded, that close is a Dependabot-triggered run without the deployer's secrets. To test Dependabot pull requests, store the two deployer values as Dependabot secrets as well, which trusts them like anyone who can push a branch, and remove the dependabot[bot] condition from every job's if. A skipped job reports success, even as a required status check, and the test job is skipped whenever setup fails. So require the setup job as well as the test job: a failed setup then blocks merging. A pull request from a fork or from Dependabot skips both, so it can still merge without these tests: to gate merging on tests for those, require a check that runs without the deployer's secrets as well. Never switch to pull_request_target to get the secrets: it makes them available, and it must never check out or run the fork's code.

When it closes

On GitHub Actions, the cleanup job runs on the closed activity type.

A live environment's name is unique in its application, so the name pr-REPO_ID-NUMBER finds it. envs list shows the deployer only the environments it created:

set -euo pipefail
ENV_ID=$(multipaas envs list --app APP_ID --json | jq -r --arg name "pr-$REPO_ID-$PR_NUMBER" '.[] | select(.name == $name) | .id')
if [ -n "$ENV_ID" ]; then
  multipaas envs delete --app APP_ID --env "$ENV_ID" --json
fi

When nothing is selected, the environment was never created or is already deleted, and the job has nothing to delete.

The environment is deleted only when this job succeeds. If it fails, or never runs because Actions was disabled or down when the pull request closed, or GitHub didn't run it because the pull request had a merge conflict (GitHub runs no pull_request workflow while one has a conflict), the environment, its app identities and the secrets logged for them stay valid, with their roles. While the pull request is still closed, re-run the failed job, or delete the environment by hand with multipaas envs delete --app APP_ID --env ENV_ID, using the id of pr-REPO_ID-NUMBER from multipaas envs list --app APP_ID --json. Once it is reopened the environment is in use again: do neither, and the next close deletes it. A person can run it signed in as themselves if they are a client admin (someone who manages the client's access: its people and roles) or hold environment.manage from a role granted in every environment, such as App manager in every environment; anyone else is refused. They run it with MULTIPAAS_CLIENT_ID and MULTIPAAS_CLIENT_SECRET unset, since while both are set the CLI acts as the deployer. The deployer can run it with its own credentials (MULTIPAAS_CLIENT_ID and MULTIPAAS_CLIENT_SECRET).

Run the two jobs one at a time

Run the setup and cleanup for a pull request one at a time. Otherwise a close can run before the setup has created the environment, find nothing, and leave an environment that no later job deletes. On GitHub Actions, the workflow-level concurrency group in the workflow above is keyed on the pull request number, and it must not set cancel-in-progress. A close then waits for a running setup, and a newer queued run replaces an older queued one.

Stop a deployer

deployers delete needs CLI 1.9.0 or later; deployers retire is the deprecated name and still works.

To stop a deployer at once, delete it:

multipaas deployers delete --app APP_ID --id CLIENT_ID

Its tokens stop working immediately, and this can't be undone. After you delete a deployer, a client admin can still delete its environments signed in as themselves, with MULTIPAAS_CLIENT_ID and MULTIPAAS_CLIENT_SECRET unset.

A replacement deployer can't see the deleted deployer's environments, so the cleanup job for a pull request whose environment the deleted deployer created succeeds without deleting anything. After you replace a deployer, a client admin signs in as themselves, with MULTIPAAS_CLIENT_ID and MULTIPAAS_CLIENT_SECRET unset (while both are set the CLI acts as the deployer and lists only its environments), and lists the application's environments with multipaas envs list --app APP_ID --json. For each repository that used the deleted deployer, they delete every live environment whose name starts with pr-REPO_ID- (REPO_ID is that repository's id) with multipaas envs delete --app APP_ID --env ENV_ID, including any the replacement has already created. If a delete is refused with environment_protected, someone holding environment.manage from a role granted in every environment, such as App manager in every environment, first runs multipaas envs unprotect --app APP_ID --env ENV_ID; a client admin can't unprotect it without that permission. Then run the delete again. That covers open pull requests too: push to each open pull request, resolving any merge conflict first, so the new deployer creates a fresh environment from the current commit. This differs from the closed-only rule for a failed cleanup because the replacement deployer can neither see nor use the old environment: deleting it costs an open pull request nothing, while leaving it keeps the name taken, and the new deployer's envs create fails on every push.