From 91e528ec554863075d5fc5e2cd45518335d54951 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 12:06:55 +0000 Subject: [PATCH] ci(deploy): reusable deploy workflows with the approval of RASGO Core deploy-laravel.yml (laravel-ploi and monorepo-ploi), deploy-wordpress.yml (Ploi deploy webhook, chosen by Sergio on 4 Nov) and deploy-static.yml (Cloudflare Pages, Direct Upload) follow one order: contract, secrets, deploy-start in Core, deploy, health and deploy-finish. Production only deploys with an approval_id that Core confirms; without Core nothing deploys. The Ploi workflows stop when the branch the site pulls is not at the commit of the run. The steps live in actions/deploy-core with 74 tests, run by the new test workflow with ShellCheck. OS-Ref: WFA-01.1 Refs: RINF-54 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fk5Z87VM8EWrxKi79DrFju --- .github/workflows/deploy-laravel.yml | 138 +++++++++ .github/workflows/deploy-static.yml | 170 +++++++++++ .github/workflows/deploy-wordpress.yml | 131 +++++++++ .github/workflows/test.yml | 25 ++ README.md | 80 ++++- actions/deploy-core/action.yml | 24 ++ actions/deploy-core/core.sh | 326 +++++++++++++++++++++ tests/deploy-core.test.sh | 386 +++++++++++++++++++++++++ 8 files changed, 1268 insertions(+), 12 deletions(-) create mode 100644 .github/workflows/deploy-laravel.yml create mode 100644 .github/workflows/deploy-static.yml create mode 100644 .github/workflows/deploy-wordpress.yml create mode 100644 .github/workflows/test.yml create mode 100644 actions/deploy-core/action.yml create mode 100755 actions/deploy-core/core.sh create mode 100644 tests/deploy-core.test.sh diff --git a/.github/workflows/deploy-laravel.yml b/.github/workflows/deploy-laravel.yml new file mode 100644 index 0000000..8ec7263 --- /dev/null +++ b/.github/workflows/deploy-laravel.yml @@ -0,0 +1,138 @@ +# Reusable RASGO deploy, Laravel on Ploi (RINF-54, WFA-01.1, D-104): reads rasgo.deploy.yml, asks RASGO Core with +# deploy-start, calls the Ploi deploy webhook of the site, waits until /version answers with this commit and closes +# the deploy in Core with deploy-finish. Production only deploys with an approval_id that Core confirms. +# Also deploys rasgo-core (adapter monorepo-ploi): one Ploi site per environment. +# Usage in each repository (.github/workflows/deploy.yml), with the secrets in its staging and production environments: +# +# name: Deploy +# on: +# push: +# branches: [main] +# workflow_dispatch: +# inputs: +# environment: { type: choice, options: [production, staging], default: production } +# approval_id: { type: string, required: false } +# rollback_of: { type: string, required: false } +# task: { type: string, required: false } +# jobs: +# deploy: +# uses: rasgo-studio/.github/.github/workflows/deploy-laravel.yml@main +# with: +# environment: ${{ inputs.environment || 'staging' }} +# approval_id: ${{ inputs.approval_id }} +# rollback_of: ${{ inputs.rollback_of }} +# task: ${{ inputs.task }} +# secrets: inherit +# +name: Deploy + +on: + workflow_call: + inputs: + environment: + description: staging or production, as in rasgo.deploy.yml + type: string + required: true + approval_id: + description: Approval of Core for this commit (production, and any environment with approval core) + type: string + default: "" + rollback_of: + description: deployment_id of the failed deploy that this one undoes (Core allows it without a new approval) + type: string + default: "" + task: + description: Plane task code (ACME01WEB-23), so Core can report the result on it + type: string + default: "" + app: + description: App name in Core, when it is not the component of the contract + type: string + default: "" + version: + description: Version to record in Core; by default the number of the tag, or the short commit + type: string + default: "" + versions: + description: JSON object with the version of each app (a monorepo such as rasgo-core) + type: string + default: "" + ploi-branch: + description: Branch the Ploi site pulls, when the environment deploys a tag + type: string + default: main + secrets: + RASGO_CORE_DEPLOY_TOKEN: + description: Core token of the deploy actor (ops 1) + required: false + PLOI_DEPLOY_WEBHOOK: + description: Deploy webhook of the Ploi site of this environment + required: false + +permissions: + contents: read + +jobs: + deploy: + runs-on: ubuntu-latest + # The secrets come from this environment of the calling repository (DEV-07). + environment: ${{ inputs.environment }} + concurrency: + group: deploy-${{ github.repository }}-${{ inputs.environment }} + cancel-in-progress: false + env: + DEPLOY_ENVIRONMENT: ${{ inputs.environment }} + DEPLOY_ADAPTERS: laravel-ploi monorepo-ploi + APPROVAL_ID: ${{ inputs.approval_id }} + ROLLBACK_OF: ${{ inputs.rollback_of }} + TASK: ${{ inputs.task }} + APP: ${{ inputs.app }} + VERSION: ${{ inputs.version }} + VERSIONS: ${{ inputs.versions }} + PLOI_BRANCH: ${{ inputs.ploi-branch }} + CORE_URL: ${{ vars.RASGO_CORE_URL || 'https://api.rasgo.studio' }} + steps: + - uses: actions/checkout@v4 + with: + sparse-checkout: rasgo.deploy.yml + sparse-checkout-cone-mode: false + - name: Contract + uses: rasgo-studio/.github/actions/deploy-core@main + with: + command: contract + - name: Secrets + uses: rasgo-studio/.github/actions/deploy-core@main + env: + RASGO_CORE_DEPLOY_TOKEN: ${{ secrets.RASGO_CORE_DEPLOY_TOKEN }} + PLOI_DEPLOY_WEBHOOK: ${{ secrets.PLOI_DEPLOY_WEBHOOK }} + with: + command: require + args: RASGO_CORE_DEPLOY_TOKEN PLOI_DEPLOY_WEBHOOK + # Ploi pulls the head of its branch, not a commit: only that head can be the approved commit. + - name: Branch the server pulls + uses: rasgo-studio/.github/actions/deploy-core@main + with: + command: branch-head + - name: Start (Core checks the approval) + uses: rasgo-studio/.github/actions/deploy-core@main + env: + CORE_TOKEN: ${{ secrets.RASGO_CORE_DEPLOY_TOKEN }} + with: + command: start + - name: Deploy (Ploi) + env: + WEBHOOK: ${{ secrets.PLOI_DEPLOY_WEBHOOK }} + run: | + curl -fsS -X POST --max-time 30 -o /dev/null "$WEBHOOK" + echo "Despliegue pedido a Ploi." + - name: Health + uses: rasgo-studio/.github/actions/deploy-core@main + with: + command: health + - name: Finish (record in Core) + if: always() + uses: rasgo-studio/.github/actions/deploy-core@main + env: + CORE_TOKEN: ${{ secrets.RASGO_CORE_DEPLOY_TOKEN }} + with: + command: finish diff --git a/.github/workflows/deploy-static.yml b/.github/workflows/deploy-static.yml new file mode 100644 index 0000000..abfb9a4 --- /dev/null +++ b/.github/workflows/deploy-static.yml @@ -0,0 +1,170 @@ +# Reusable RASGO deploy, static site on Cloudflare Pages (RINF-54, WFA-01.1, D-104): reads rasgo.deploy.yml, builds +# this commit, asks RASGO Core with deploy-start, uploads the build with wrangler (Direct Upload), waits until the +# health path answers with this commit and closes the deploy in Core with deploy-finish. Production only deploys +# with an approval_id that Core confirms. The build gets a version.json (component, version, commit) unless it has one. +# The Pages project is a Direct Upload project: its Git integration, if any, does not deploy production by itself. +# Usage in each repository (.github/workflows/deploy.yml), with the secrets in its staging and production environments: +# +# name: Deploy +# on: +# push: +# branches: [main] +# workflow_dispatch: +# inputs: +# environment: { type: choice, options: [production, staging], default: production } +# approval_id: { type: string, required: false } +# rollback_of: { type: string, required: false } +# task: { type: string, required: false } +# jobs: +# deploy: +# uses: rasgo-studio/.github/.github/workflows/deploy-static.yml@main +# with: +# environment: ${{ inputs.environment || 'staging' }} +# approval_id: ${{ inputs.approval_id }} +# rollback_of: ${{ inputs.rollback_of }} +# task: ${{ inputs.task }} +# pages-project: example-org +# secrets: inherit +# +name: Deploy + +on: + workflow_call: + inputs: + environment: + description: staging or production, as in rasgo.deploy.yml + type: string + required: true + approval_id: + description: Approval of Core for this commit (production, and any environment with approval core) + type: string + default: "" + rollback_of: + description: deployment_id of the failed deploy that this one undoes (Core allows it without a new approval) + type: string + default: "" + task: + description: Plane task code (ACME01WEB-23), so Core can report the result on it + type: string + default: "" + app: + description: App name in Core, when it is not the component of the contract + type: string + default: "" + version: + description: Version to record in Core; by default the number of the tag, or the short commit + type: string + default: "" + pages-project: + description: Name of the Cloudflare Pages project + type: string + required: true + production-branch: + description: Production branch of the Pages project + type: string + default: main + staging-branch: + description: Pages branch (preview alias) that serves staging + type: string + default: staging + build-command: + description: Command that builds the site (Nuxt by default, as ci-static.yml) + type: string + default: npm ci && npm run generate + output-dir: + description: Folder the build publishes + type: string + default: .output/public + node-version: + type: string + default: "22" + wrangler-version: + description: Exact version of wrangler, the Cloudflare CLI that uploads the build + type: string + default: 4.151.0 + secrets: + RASGO_CORE_DEPLOY_TOKEN: + description: Core token of the deploy actor (ops 1) + required: false + CLOUDFLARE_API_TOKEN: + description: Cloudflare token with Pages edit on the account + required: false + CLOUDFLARE_ACCOUNT_ID: + description: Cloudflare account of the Pages project + required: false + +permissions: + contents: read + +jobs: + deploy: + runs-on: ubuntu-latest + # The secrets come from this environment of the calling repository (DEV-07). + environment: ${{ inputs.environment }} + concurrency: + group: deploy-${{ github.repository }}-${{ inputs.environment }} + cancel-in-progress: false + env: + DEPLOY_ENVIRONMENT: ${{ inputs.environment }} + DEPLOY_ADAPTERS: static + APPROVAL_ID: ${{ inputs.approval_id }} + ROLLBACK_OF: ${{ inputs.rollback_of }} + TASK: ${{ inputs.task }} + APP: ${{ inputs.app }} + VERSION: ${{ inputs.version }} + CORE_URL: ${{ vars.RASGO_CORE_URL || 'https://api.rasgo.studio' }} + OUTPUT_DIR: ${{ inputs.output-dir }} + steps: + - uses: actions/checkout@v4 + - name: Contract + uses: rasgo-studio/.github/actions/deploy-core@main + with: + command: contract + - name: Secrets + uses: rasgo-studio/.github/actions/deploy-core@main + env: + RASGO_CORE_DEPLOY_TOKEN: ${{ secrets.RASGO_CORE_DEPLOY_TOKEN }} + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + with: + command: require + args: RASGO_CORE_DEPLOY_TOKEN CLOUDFLARE_API_TOKEN CLOUDFLARE_ACCOUNT_ID + # The build comes before deploy-start, so a broken build does not spend the approval. + - uses: actions/setup-node@v4 + with: + node-version: ${{ inputs.node-version }} + - name: Build + env: + BUILD_COMMAND: ${{ inputs.build-command }} + run: bash -euo pipefail -c "$BUILD_COMMAND" + - name: Version file + uses: rasgo-studio/.github/actions/deploy-core@main + with: + command: version-file + - name: Start (Core checks the approval) + uses: rasgo-studio/.github/actions/deploy-core@main + env: + CORE_TOKEN: ${{ secrets.RASGO_CORE_DEPLOY_TOKEN }} + with: + command: start + - name: Deploy (Cloudflare Pages) + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + PAGES_PROJECT: ${{ inputs.pages-project }} + PAGES_BRANCH: ${{ inputs.environment == 'production' && inputs.production-branch || inputs.staging-branch }} + WRANGLER_VERSION: ${{ inputs.wrangler-version }} + run: | + npx --yes "wrangler@${WRANGLER_VERSION}" pages deploy "$OUTPUT_DIR" --project-name="$PAGES_PROJECT" \ + --branch="$PAGES_BRANCH" --commit-hash="$GITHUB_SHA" --commit-dirty=true + - name: Health + uses: rasgo-studio/.github/actions/deploy-core@main + with: + command: health + - name: Finish (record in Core) + if: always() + uses: rasgo-studio/.github/actions/deploy-core@main + env: + CORE_TOKEN: ${{ secrets.RASGO_CORE_DEPLOY_TOKEN }} + with: + command: finish diff --git a/.github/workflows/deploy-wordpress.yml b/.github/workflows/deploy-wordpress.yml new file mode 100644 index 0000000..f91918f --- /dev/null +++ b/.github/workflows/deploy-wordpress.yml @@ -0,0 +1,131 @@ +# Reusable RASGO deploy, WordPress on Ploi (RINF-54, WFA-01.1, D-104): reads rasgo.deploy.yml, asks RASGO Core with +# deploy-start, calls the Ploi deploy webhook of the site (its deploy script pulls the repository and builds the +# theme), checks the health path and closes the deploy in Core with deploy-finish. Production only deploys with an +# approval_id that Core confirms. Since RINF-4 an Action no longer reaches the servers by SSH: Ploi does the deploy. +# Usage in each repository (.github/workflows/deploy.yml), with the secrets in its staging and production environments: +# +# name: Deploy +# on: +# workflow_dispatch: +# inputs: +# environment: { type: choice, options: [production, staging], default: production } +# approval_id: { type: string, required: false } +# rollback_of: { type: string, required: false } +# task: { type: string, required: false } +# jobs: +# deploy: +# uses: rasgo-studio/.github/.github/workflows/deploy-wordpress.yml@main +# with: +# environment: ${{ inputs.environment }} +# approval_id: ${{ inputs.approval_id }} +# rollback_of: ${{ inputs.rollback_of }} +# task: ${{ inputs.task }} +# secrets: inherit +# +name: Deploy + +on: + workflow_call: + inputs: + environment: + description: staging or production, as in rasgo.deploy.yml + type: string + required: true + approval_id: + description: Approval of Core for this commit (production, and any environment with approval core) + type: string + default: "" + rollback_of: + description: deployment_id of the failed deploy that this one undoes (Core allows it without a new approval) + type: string + default: "" + task: + description: Plane task code (ACME01WEB-23), so Core can report the result on it + type: string + default: "" + app: + description: App name in Core, when it is not the component of the contract + type: string + default: "" + version: + description: Version to record in Core; by default the number of the tag, or the short commit + type: string + default: "" + ploi-branch: + description: Branch the Ploi site pulls, when the environment deploys a tag + type: string + default: main + secrets: + RASGO_CORE_DEPLOY_TOKEN: + description: Core token of the deploy actor (ops 1) + required: false + PLOI_DEPLOY_WEBHOOK: + description: Deploy webhook of the Ploi site of this environment + required: false + +permissions: + contents: read + +jobs: + deploy: + runs-on: ubuntu-latest + # The secrets come from this environment of the calling repository (DEV-07). + environment: ${{ inputs.environment }} + concurrency: + group: deploy-${{ github.repository }}-${{ inputs.environment }} + cancel-in-progress: false + env: + DEPLOY_ENVIRONMENT: ${{ inputs.environment }} + DEPLOY_ADAPTERS: wordpress + APPROVAL_ID: ${{ inputs.approval_id }} + ROLLBACK_OF: ${{ inputs.rollback_of }} + TASK: ${{ inputs.task }} + APP: ${{ inputs.app }} + VERSION: ${{ inputs.version }} + PLOI_BRANCH: ${{ inputs.ploi-branch }} + CORE_URL: ${{ vars.RASGO_CORE_URL || 'https://api.rasgo.studio' }} + steps: + - uses: actions/checkout@v4 + with: + sparse-checkout: rasgo.deploy.yml + sparse-checkout-cone-mode: false + - name: Contract + uses: rasgo-studio/.github/actions/deploy-core@main + with: + command: contract + - name: Secrets + uses: rasgo-studio/.github/actions/deploy-core@main + env: + RASGO_CORE_DEPLOY_TOKEN: ${{ secrets.RASGO_CORE_DEPLOY_TOKEN }} + PLOI_DEPLOY_WEBHOOK: ${{ secrets.PLOI_DEPLOY_WEBHOOK }} + with: + command: require + args: RASGO_CORE_DEPLOY_TOKEN PLOI_DEPLOY_WEBHOOK + # Ploi pulls the head of its branch, not a commit: only that head can be the approved commit. + - name: Branch the server pulls + uses: rasgo-studio/.github/actions/deploy-core@main + with: + command: branch-head + - name: Start (Core checks the approval) + uses: rasgo-studio/.github/actions/deploy-core@main + env: + CORE_TOKEN: ${{ secrets.RASGO_CORE_DEPLOY_TOKEN }} + with: + command: start + - name: Deploy (Ploi) + env: + WEBHOOK: ${{ secrets.PLOI_DEPLOY_WEBHOOK }} + run: | + curl -fsS -X POST --max-time 30 -o /dev/null "$WEBHOOK" + echo "Despliegue pedido a Ploi." + - name: Health + uses: rasgo-studio/.github/actions/deploy-core@main + with: + command: health + - name: Finish (record in Core) + if: always() + uses: rasgo-studio/.github/actions/deploy-core@main + env: + CORE_TOKEN: ${{ secrets.RASGO_CORE_DEPLOY_TOKEN }} + with: + command: finish diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..5a7b0d3 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,25 @@ +# Checks of this repository (RINF-54): the shared deploy steps, their tests and that every workflow parses. +name: test + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + deploy-core: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: ShellCheck + run: shellcheck actions/deploy-core/core.sh tests/*.sh + - name: Tests + run: bash tests/deploy-core.test.sh + - name: Workflows and actions parse + run: | + for file in .github/workflows/*.yml actions/*/action.yml; do + yq -e '.jobs // .runs' "$file" > /dev/null || { echo "::error file=$file::no es un workflow o una action válida"; exit 1; } + done diff --git a/README.md b/README.md index 14cc03a..26a0fd2 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,9 @@ # .github Shared GitHub configuration for the rasgo-studio organization: the default pull request template -(`.github/PULL_REQUEST_TEMPLATE.md`) and the reusable CI workflows (`.github/workflows/ci-*.yml`), -called from each repository with `uses: rasgo-studio/.github/.github/workflows/@main`. +(`.github/PULL_REQUEST_TEMPLATE.md`), the reusable CI workflows (`.github/workflows/ci-*.yml`) and the reusable +deploy workflows (`.github/workflows/deploy-*.yml`), called from each repository with +`uses: rasgo-studio/.github/.github/workflows/@main`. ## Deploy contract: `rasgo.deploy.yml` @@ -16,11 +17,11 @@ keeps only what exists today: the adapters are the current ways of deploying, be | `version` | yes | `1` | | `component` | yes | Its name in the Registry of RASGO Core: the repository, or the site it publishes | | `stack` | yes | `laravel`, `wordpress`, `static`, `monorepo` or `n8n`, as the `stack` property of the repository (DEV-02.2) | -| `adapter` | yes | `laravel-ploi` (Ploi deploy webhook), `wordpress`, `static`, `monorepo-ploi` (rasgo-core, one Ploi site per environment) or `n8n` (rasgo-motor) | +| `adapter` | yes | `laravel-ploi` (Ploi deploy webhook), `wordpress` (Ploi deploy webhook too), `static` (Cloudflare Pages), `monorepo-ploi` (rasgo-core, one Ploi site per environment) or `n8n` (rasgo-motor) | | `environments` | yes | `staging` and `production`, each with `ref` (a branch, or `tag` for the published release), `url`, `approval` and `secrets` | | `migrations` | no | The command the deploy runs after the code; it is shown in the approval | | `health` | yes | `path` on the environment `url` that answers with the deployed version (`expect: version`), or only its status | -| `rollback` | yes | `previous-tag` (a deploy of the tag before, with its own approval) or `none` | +| `rollback` | yes | `previous-tag` (a deploy of the tag before: Core allows it without a new approval up to 24 hours after the failed deploy) or `none` (going back is not done by the system) | Rules of the contract: @@ -52,10 +53,11 @@ environments: migrations: php artisan migrate --force health: path: /version -rollback: previous-tag + timeout_s: 300 +rollback: none ``` -WordPress site (theme and configuration by Action, WPR-08): +WordPress site, deployed by its Ploi site (WPR-08): ```yaml version: 1 @@ -67,11 +69,12 @@ environments: ref: tag url: https://example.com approval: core - secrets: [DEPLOY_SSH_KEY] + secrets: [PLOI_DEPLOY_WEBHOOK] health: path: / expect: status -rollback: previous-tag + timeout_s: 120 +rollback: none ``` Static site (Cloudflare Pages): @@ -86,13 +89,66 @@ environments: ref: main url: https://staging.example.org approval: none - secrets: [CLOUDFLARE_API_TOKEN] + secrets: [CLOUDFLARE_API_TOKEN, CLOUDFLARE_ACCOUNT_ID] production: ref: tag url: https://example.org approval: core - secrets: [CLOUDFLARE_API_TOKEN] + secrets: [CLOUDFLARE_API_TOKEN, CLOUDFLARE_ACCOUNT_ID] health: - path: /version.txt -rollback: none + path: /version.json +rollback: previous-tag ``` + +## Deploy workflows + +Three reusable workflows deploy what a contract describes, one per way of deploying (RINF-54). Each repository calls +the one of its `adapter` from its own `.github/workflows/deploy.yml`; the header of each file has the call to copy. + +| Workflow | Adapters | How the code reaches the server | +| --- | --- | --- | +| `deploy-laravel.yml` | `laravel-ploi`, `monorepo-ploi` | Calls the Ploi deploy webhook of the site; its deploy script pulls and builds | +| `deploy-wordpress.yml` | `wordpress` | The same: the Ploi site pulls the repository and builds the theme | +| `deploy-static.yml` | `static` | Builds this commit in the Action and uploads it to Cloudflare Pages with wrangler (Direct Upload) | + +Every deploy follows the same order, and stops at the first step that fails: + +1. **Contract.** Reads `rasgo.deploy.yml` and checks it against the run: the adapter is the one of the workflow, the + environment exists, production has `approval: core`, an environment with `approval: core` got an `approval_id`, + and the run comes from what the environment deploys (its branch, or a tag when `ref: tag`). +2. **Secrets.** The secrets the adapter reads are set in the environment of the calling repository. +3. **deploy-start.** Asks RASGO Core with the repository, app, environment, commit and `approval_id`. Core answers with + a `deployment_id`, or with 403 and the reason (`pending`, `expired`, `used`, `mismatch`…), and then nothing touches + the server (WFA-01.1, D-104). If Core does not answer, nothing deploys: there is no emergency exit. +4. **Deploy.** The adapter: the Ploi webhook, or the upload to Cloudflare Pages. +5. **Health.** Asks `url` + `health.path` until it answers with this commit (full or short) or this version, up to + `health.timeout_s`. With `expect: status` it only checks that the site answers, which does not prove the new code is live. +6. **deploy-finish.** Closes the deploy in Core with `success`, `failure` or, for a healthy rollback, `rolled_back`. + It runs even when an earlier step failed, so failed deploys are recorded too. + +Calling them: + +- **Inputs.** `environment` (required), `approval_id`, `rollback_of` (the `deployment_id` of the failed deploy that + this one undoes) and `task` (the Plane code, so Core can report on it), plus `app`, `version` and, for a monorepo, + `versions` (a JSON object with the version of each app). `deploy-static.yml` also takes `pages-project`, + `build-command`, `output-dir`, `production-branch` and `staging-branch`. +- **Secrets** live in the `staging` and `production` environments of the calling repository, with the names its + contract lists (DEV-07): `RASGO_CORE_DEPLOY_TOKEN` always (the Core token of the deploy actor, ops 1), then + `PLOI_DEPLOY_WEBHOOK`, or `CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_ACCOUNT_ID`. The repository variable + `RASGO_CORE_URL` points to another Core, for tests. +- **Production** runs from `workflow_dispatch` once Sergio has approved it in the Hub, on the tag it deploys: + `gh workflow run deploy.yml --ref acme-v1.4.0 -f environment=production -f approval_id=`. Each approval serves + one deploy of one commit and lasts 24 hours (spec 003 of rasgo-core). Staging with `approval: none` can deploy on + each push to its branch. +- **Ploi deploys the head of its branch**, not a given commit. So both Ploi workflows stop before deploy-start when + that head (`ref`, or `ploi-branch` for a tag, `main` by default) is not the commit of the run: with release-please, + deploy the tag right after merging the release. For the same reason a Ploi rollback to an older tag cannot pass; + going back there is a revert merged into the branch, deployed with a new approval, or the rollback of the Ploi panel + (Sergio); their contracts say `rollback: none`. `deploy-static.yml` builds the commit it runs on, so + `rollback: previous-tag` works there. +- **Static sites** get `version.json` (`component`, `version`, `commit`) in the published folder unless the build + writes one, so `health.path: /version.json` checks the deployed commit. + +The steps live in `actions/deploy-core` (`core.sh`, with its tests in `tests/`). The workflows call it at `@main`, +like the repositories call the workflows: a change here reaches every deploy at once, so it comes with its tests and +the `test` workflow green. diff --git a/actions/deploy-core/action.yml b/actions/deploy-core/action.yml new file mode 100644 index 0000000..283a6a0 --- /dev/null +++ b/actions/deploy-core/action.yml @@ -0,0 +1,24 @@ +name: RASGO deploy steps +description: >- + One step of a RASGO deploy (RINF-54): read rasgo.deploy.yml, ask RASGO Core with deploy-start, check the health + of the environment and close the deploy in Core. Used by the reusable deploy-*.yml workflows of this repository; + the deploy state lives in RUNNER_TEMP between steps. Settings come as environment variables of the step. +inputs: + command: + description: require, contract, branch-head, version-file, start, health or finish + required: true + args: + description: Arguments of the command (secret names for require, the published folder for version-file) + required: false + default: "" +runs: + using: composite + steps: + - shell: bash + env: + COMMAND: ${{ inputs.command }} + ARGS: ${{ inputs.args }} + # ARGS splits on purpose: secret names or one folder, never user text. + run: | + # shellcheck disable=SC2086 + "$GITHUB_ACTION_PATH/core.sh" "$COMMAND" $ARGS diff --git a/actions/deploy-core/core.sh b/actions/deploy-core/core.sh new file mode 100755 index 0000000..5475851 --- /dev/null +++ b/actions/deploy-core/core.sh @@ -0,0 +1,326 @@ +#!/usr/bin/env bash +# Steps shared by the reusable deploy workflows of rasgo-studio (RINF-54, WFA-01.1, D-104). +# +# core.sh require NAME... the named environment variables (the secrets the adapter reads) are set +# core.sh contract reads rasgo.deploy.yml, checks it against this run and saves the deploy state +# core.sh branch-head the branch the Ploi site pulls is still at the commit of this run +# core.sh version-file [DIR] writes DIR (or OUTPUT_DIR)/version.json with component, version and commit +# core.sh start deploy-start in RASGO Core: it only goes on with an approval Core confirms +# core.sh health waits until the environment answers with this commit or version +# core.sh finish deploy-finish in RASGO Core with the result +# +# Core is the barrier: without an answer from Core nothing deploys, and there is no emergency exit (RINF-54). +# The state of one deploy lives in a JSON file between steps; it holds names and ids, never a secret. +# Messages are in Spanish, for the person who reads the run (AGT-03). +set -euo pipefail + +STATE="${RASGO_STATE:-${RUNNER_TEMP:-/tmp}/rasgo-deploy.json}" +CORE_URL="${CORE_URL:-https://api.rasgo.studio}" +CORE_URL="${CORE_URL%/}" + +fail() { + printf '::error::%s\n' "$*" + summary "- $*" + exit 1 +} + +note() { printf '%s\n' "$*"; } + +summary() { + if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then printf '%s\n' "$*" >> "$GITHUB_STEP_SUMMARY"; fi +} + +short() { printf '%s' "${1:0:7}"; } + +state_get() { jq -r --arg k "$1" '.[$k] // empty' "$STATE"; } + +state_set() { + local tmp + tmp="$(mktemp)" + jq --arg k "$1" --arg v "$2" '.[$k] = $v' "$STATE" > "$tmp" + mv "$tmp" "$STATE" +} + +# The runners bring the yq of mikefarah; elsewhere (a Mac, the tests) PyYAML does the same job. +yaml_to_json() { + if yq --version 2>/dev/null | grep -q mikefarah; then + yq -o=json '.' "$1" + else + python3 -c 'import json, sys, yaml; print(json.dumps(yaml.safe_load(open(sys.argv[1]))))' "$1" + fi +} + +# POST to Core: path, request file, response file. Prints the HTTP code; fails only when Core cannot be reached. +# The token goes in a header file, so it never shows in the command line of the runner. +core_post() { + local path="$1" request="$2" response="$3" headers code rc=0 + shift 3 + headers="$(mktemp)" + chmod 600 "$headers" + printf 'Authorization: Bearer %s\n' "${CORE_TOKEN:-}" > "$headers" + code="$(curl -sS --max-time 30 "$@" -X POST -H @"$headers" -H 'Content-Type: application/json' \ + -H 'Accept: application/json' --data-binary @"$request" -o "$response" -w '%{http_code}' \ + "$CORE_URL/api/v1/$path")" || rc=$? + rm -f "$headers" + [ "$rc" -eq 0 ] || return "$rc" + printf '%s' "$code" +} + +cmd_require() { + local name missing="" + for name in "$@"; do + if [ -z "${!name:-}" ]; then missing="$missing $name"; fi + done + [ -z "$missing" ] || fail "Faltan secretos en el entorno ${DEPLOY_ENVIRONMENT:-}:$missing. Van en el entorno del repositorio, con el nombre que lista rasgo.deploy.yml (DEV-07)." + note "Secretos presentes: $*" +} + +cmd_contract() { + local file="${CONTRACT_FILE:-rasgo.deploy.yml}" env="${DEPLOY_ENVIRONMENT:-}" json + local adapter component ref url approval path expect timeout version app branch public tag + + case "$env" in + staging | production) ;; + *) fail "Entorno «$env» desconocido: el contrato v1 solo tiene staging y production." ;; + esac + [ -f "$file" ] || fail "No encuentro $file en la raíz del repositorio: es el contrato de despliegue (RINF-54)." + json="$(yaml_to_json "$file")" || fail "$file no es un YAML válido." + [ "$(jq -r '.version' <<< "$json")" = 1 ] || fail "$file no es la versión 1 del contrato de despliegue." + + adapter="$(jq -r '.adapter // empty' <<< "$json")" + case " ${DEPLOY_ADAPTERS:-} " in + *" $adapter "*) ;; + *) fail "Este workflow despliega «${DEPLOY_ADAPTERS:-}» y el contrato dice adapter: «$adapter»." ;; + esac + component="$(jq -r '.component // empty' <<< "$json")" + [ -n "$component" ] || fail "Al contrato le falta component." + jq -e --arg e "$env" '.environments[$e]' <<< "$json" > /dev/null || fail "El contrato no tiene el entorno $env." + + ref="$(jq -r --arg e "$env" '.environments[$e].ref // empty' <<< "$json")" + url="$(jq -r --arg e "$env" '.environments[$e].url // empty' <<< "$json")" + approval="$(jq -r --arg e "$env" '.environments[$e].approval // "none"' <<< "$json")" + [ -n "$ref" ] && [ -n "$url" ] || fail "Al entorno $env le falta ref o url." + case "$url" in https://*) ;; *) fail "La url de $env no es https." ;; esac + + # Production always deploys with an approval of Core (WFA-01.1, level 3), whatever the contract says. + if [ "$env" = production ] && [ "$approval" != core ]; then + fail "Producción solo despliega con aprobación de Core (approval: core, WFA-01.1); el contrato dice «$approval»." + fi + if [ "$approval" = core ] && [ -z "${APPROVAL_ID:-}" ] && [ -z "${ROLLBACK_OF:-}" ]; then + fail "Falta approval_id: $env solo despliega con una aprobación de Core para este commit (WFA-01.1). Pídela con approval.request y lanza el workflow con ella." + fi + + # What runs is what the contract says deploys: the published tag, or that branch. + if [ "$ref" = tag ]; then + [ "${GITHUB_REF_TYPE:-}" = tag ] || fail "$env despliega una etiqueta publicada y esta ejecución es de la rama ${GITHUB_REF_NAME:-}: lánzalo sobre la etiqueta (gh workflow run … --ref )." + tag="$GITHUB_REF_NAME" + branch="${PLOI_BRANCH:-main}" + else + [ "${GITHUB_REF_TYPE:-}" = branch ] && [ "${GITHUB_REF_NAME:-}" = "$ref" ] \ + || fail "$env despliega la rama $ref y esta ejecución es de ${GITHUB_REF_TYPE:-?} ${GITHUB_REF_NAME:-?}." + tag="" + branch="$ref" + fi + + path="$(jq -r '.health.path // empty' <<< "$json")" + expect="$(jq -r '.health.expect // "version"' <<< "$json")" + timeout="$(jq -r '.health.timeout_s // 60' <<< "$json")" + [ -n "$path" ] || fail "Al contrato le falta health.path." + + # The version recorded in Core: the input, else the number of the tag (acme-v1.2.3 → 1.2.3), else the short commit. + version="${VERSION:-}" + if [ -z "$version" ] && [ -n "$tag" ]; then + version="${tag##*v}" + case "$version" in [0-9]*) ;; *) version="$tag" ;; esac + fi + [ -n "$version" ] || version="$(short "$GITHUB_SHA")" + app="${APP:-$component}" + + # Core keeps the contract it receives (spec 003, Clarify 7), without the names of the secrets. + public="$(jq -c 'del(.environments[]?.secrets)' <<< "$json")" + + jq -n --arg component "$component" --arg app "$app" --arg adapter "$adapter" --arg environment "$env" \ + --arg ref "$ref" --arg tag "$tag" --arg branch "$branch" --arg url "${url%/}" --arg approval "$approval" \ + --arg health_path "$path" --arg health_expect "$expect" --arg health_timeout "$timeout" \ + --arg version "$version" --arg commit "${GITHUB_SHA:?}" --arg approval_id "${APPROVAL_ID:-}" \ + --arg rollback_of "${ROLLBACK_OF:-}" --arg task "${TASK:-}" --argjson contract "$public" \ + '{component: $component, app: $app, adapter: $adapter, environment: $environment, ref: $ref, tag: $tag, + branch: $branch, url: $url, approval: $approval, health_path: $health_path, health_expect: $health_expect, + health_timeout: $health_timeout, version: $version, commit: $commit, approval_id: $approval_id, + rollback_of: $rollback_of, task: $task, contract: $contract}' > "$STATE" + + note "Contrato correcto: $component ($adapter) a $env, $url, versión $version, commit $(short "$GITHUB_SHA"), aprobación: $approval." + summary "- Contrato: $component ($adapter) a $env, versión $version, commit $(short "$GITHUB_SHA")." +} + +# Ploi pulls the head of a branch: deploying is only safe when that head is the commit approved in this run. +cmd_branch_head() { + local branch head + branch="$(state_get branch)" + head="$(git ls-remote --exit-code origin "refs/heads/$branch" | cut -f1)" \ + || fail "No encuentro la rama $branch en el repositorio." + [ "$head" = "$GITHUB_SHA" ] \ + || fail "Ploi despliega la cabeza de $branch ($(short "$head")) y esta ejecución es de $(short "$GITHUB_SHA"): el servidor no recibiría el commit aprobado. No se despliega." + note "La rama $branch está en $(short "$head"), el commit de esta ejecución." +} + +cmd_version_file() { + local dir="${1:-${OUTPUT_DIR:-}}" + [ -d "$dir" ] || fail "No existe la carpeta publicada «$dir»." + if [ -e "$dir/version.json" ]; then + note "$dir/version.json ya existe: no se toca." + return + fi + jq -n --arg component "$(state_get component)" --arg version "$(state_get version)" --arg commit "$GITHUB_SHA" \ + '{component: $component, version: $version, commit: $commit}' > "$dir/version.json" + note "Escrito $dir/version.json con la versión $(state_get version)." +} + +reason_text() { + case "$1" in + missing) printf 'falta approval_id' ;; + not_found) printf 'esa aprobación no existe' ;; + pending) printf 'la aprobación sigue pendiente: apruébala en el Hub y vuelve a lanzarlo' ;; + rejected) printf 'la aprobación está rechazada' ;; + expired) printf 'la aprobación caducó (24 horas)' ;; + used) printf 'la aprobación ya se usó: cada una sirve para un despliegue' ;; + mismatch) printf 'la aprobación es para otro repositorio, app, entorno o commit' ;; + rollback_not_allowed) printf 'el rollback no cumple las condiciones de Core (al último despliegue correcto, antes de 24 horas)' ;; + *) printf '%s' "$1" ;; + esac +} + +cmd_start() { + local request response code id reason rule + [ -f "$STATE" ] || fail "Falta el paso contract antes de deploy-start." + [ -n "${CORE_TOKEN:-}" ] || fail "Falta el secreto RASGO_CORE_DEPLOY_TOKEN." + request="$(mktemp)" + response="$(mktemp)" + jq --arg repository "${GITHUB_REPOSITORY:?}" \ + --arg run_url "${GITHUB_SERVER_URL:-https://github.com}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID:-0}" \ + '{repository: $repository, app, environment, commit_sha: .commit, run_url: $run_url, contract} + + (if .approval_id != "" then {approval_id} else {} end) + + (if .rollback_of != "" then {rollback_of} else {} end) + + (if .task != "" then {task} else {} end)' "$STATE" > "$request" + + code="$(core_post deploy-start "$request" "$response")" \ + || fail "No llego a Core ($CORE_URL). Sin respuesta de Core no se despliega (RINF-54)." + case "$code" in + 200 | 201) + id="$(jq -r '.deployment_id // empty' "$response" 2> /dev/null || true)" + [ -n "$id" ] || fail "Core respondió $code a deploy-start sin deployment_id. No se despliega." + state_set deployment_id "$id" + note "Core confirma el despliegue $id." + summary "- Core: despliegue $id empezado." + ;; + 403) + reason="$(jq -r '.reason // "desconocido"' "$response" 2> /dev/null || printf 'desconocido')" + rule="$(jq -r '.rule // "WFA-01.1"' "$response" 2> /dev/null || printf 'WFA-01.1')" + fail "Core no confirma la aprobación: $(reason_text "$reason") ($rule). No se toca el servidor." + ;; + 401) fail "Core no acepta el token de despliegue (401): revisa RASGO_CORE_DEPLOY_TOKEN. No se despliega." ;; + *) fail "Core respondió $code a deploy-start. No se despliega." ;; + esac + rm -f "$request" "$response" +} + +body_has_version() { + local body="$1" commit version pattern + commit="$(state_get commit)" + version="$(state_get version)" + grep -Fq "$commit" "$body" && return 0 + grep -Fq "$(short "$commit")" "$body" && return 0 + [ -n "$version" ] || return 1 + pattern="${version//./\\.}" + grep -Eq "(^|[^0-9A-Za-z.])${pattern}([^0-9A-Za-z.]|$)" "$body" +} + +cmd_health() { + local target expect timeout interval deadline body code + [ -f "$STATE" ] || fail "Falta el paso contract antes de la comprobación." + target="$(state_get url)$(state_get health_path)" + expect="$(state_get health_expect)" + timeout="$(state_get health_timeout)" + interval="${HEALTH_INTERVAL:-5}" + deadline=$(($(date +%s) + timeout)) + body="$(mktemp)" + while :; do + code="$(curl -sS -L --max-time 10 -H 'Cache-Control: no-cache' -o "$body" -w '%{http_code}' "$target" 2> /dev/null)" || code=000 + case "$code" in '' | *[!0-9]*) code=000 ;; esac + if [ "$expect" = status ]; then + if [ "$code" -ge 200 ] && [ "$code" -lt 400 ]; then + state_set health ok + note "$target responde $code." + summary "- Salud: $target responde $code (solo el estado HTTP)." + return + fi + elif [ "$code" = 200 ] && body_has_version "$body"; then + state_set health ok + note "$target ya sirve la versión $(state_get version) ($(short "$(state_get commit)"))." + summary "- Salud: $target sirve la versión $(state_get version)." + return + fi + [ "$(date +%s)" -lt "$deadline" ] || break + sleep "$interval" + done + state_set health failed + fail "$target no sirve la versión $(state_get version) tras ${timeout} s (último código: $code)." +} + +cmd_finish() { + local id result request response code + if [ ! -f "$STATE" ]; then + note "No hay despliegue que cerrar en Core: el contrato no llegó a leerse." + return + fi + id="$(state_get deployment_id)" + if [ -z "$id" ]; then + note "No hay despliegue que cerrar en Core: deploy-start no llegó a crearlo." + return + fi + [ -n "${CORE_TOKEN:-}" ] || fail "Falta el secreto RASGO_CORE_DEPLOY_TOKEN: el despliegue $id queda abierto en Core." + # A rollback that serves the version it went back to closes as rolled_back; anything else that is not healthy failed. + if [ "$(state_get health)" = ok ]; then + if [ -n "$(state_get rollback_of)" ]; then result=rolled_back; else result=success; fi + else + result=failure + fi + if [ -n "${VERSIONS:-}" ]; then + jq -e 'type == "object"' <<< "$VERSIONS" > /dev/null 2>&1 || fail "versions no es un objeto JSON: $VERSIONS" + fi + request="$(mktemp)" + response="$(mktemp)" + jq --arg result "$result" --arg finished_at "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --argjson versions "${VERSIONS:-null}" \ + '{deployment_id, result: $result, version, finished_at: $finished_at} + + (if $versions != null then {versions: $versions} else {} end)' "$STATE" > "$request" + code="$(core_post deploy-finish "$request" "$response" --retry 3 --retry-connrefused)" \ + || fail "No llego a Core ($CORE_URL): el despliegue $id ($result) queda abierto en Core." + case "$code" in + 200 | 201) + note "Core registra el despliegue $id: $result." + summary "- Core: despliegue $id cerrado como $result." + ;; + *) fail "Core respondió $code a deploy-finish: el despliegue $id ($result) queda abierto en Core." ;; + esac + rm -f "$request" "$response" +} + +main() { + local command="${1:-}" + shift || true + case "$command" in + require) cmd_require "$@" ;; + contract) cmd_contract ;; + branch-head) cmd_branch_head ;; + version-file) cmd_version_file "$@" ;; + start) cmd_start ;; + health) cmd_health ;; + finish) cmd_finish ;; + *) + note "Uso: core.sh require|contract|branch-head|version-file|start|health|finish" + exit 2 + ;; + esac +} + +main "$@" diff --git a/tests/deploy-core.test.sh b/tests/deploy-core.test.sh new file mode 100644 index 0000000..e672b0d --- /dev/null +++ b/tests/deploy-core.test.sh @@ -0,0 +1,386 @@ +#!/usr/bin/env bash +# Tests of actions/deploy-core/core.sh (RINF-54). Core, Ploi and the sites are fakes: a curl and a git in PATH that +# answer from files and record each call. Run: bash tests/deploy-core.test.sh +set -u + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +CORE="$ROOT/actions/deploy-core/core.sh" +SHA="0123456789abcdef0123456789abcdef01234567" +PASS=0 +FAILED=0 +BASE="$(mktemp -d)" +export TMPDIR="$BASE" +trap 'rm -rf "$BASE"' EXIT + +ok() { + PASS=$((PASS + 1)) + printf 'ok %s\n' "$1" +} + +ko() { + FAILED=$((FAILED + 1)) + printf 'FAIL %s\n' "$1" + [ -z "${2:-}" ] || printf ' %s\n' "$2" + [ ! -f "${OUT:-}" ] || sed 's/^/ | /' "$OUT" +} + +# A clean run: a repository with its contract, fake curl and git, and the variables GitHub sets. +setup() { + WORK="$(mktemp -d "$BASE/run.XXXXXX")" + FAKE="$WORK/fake" + mkdir -p "$FAKE/bin" "$WORK/repo" + OUT="$WORK/out" + cat > "$FAKE/bin/curl" << 'EOF' +#!/usr/bin/env bash +out="" data="" url="" +printf '%s\n' "$*" >> "$FAKE_DIR/args" +while [ $# -gt 0 ]; do + case "$1" in + -o) out="$2"; shift 2 ;; + --data-binary) data="${2#@}"; shift 2 ;; + -H) case "$2" in @*) cat "${2#@}" >> "$FAKE_DIR/headers" ;; esac; shift 2 ;; + -w | -X | --max-time | --retry) shift 2 ;; + -*) shift ;; + *) url="$1"; shift ;; + esac +done +case "$url" in + */api/v1/deploy-start) key=start ;; + */api/v1/deploy-finish) key=finish ;; + *) key=health ;; +esac +n=$(($(cat "$FAKE_DIR/count.$key" 2> /dev/null || echo 0) + 1)) +echo "$n" > "$FAKE_DIR/count.$key" +echo "$url" >> "$FAKE_DIR/urls" +if [ -n "$data" ]; then cp "$data" "$FAKE_DIR/request.$key.json"; fi +if [ -f "$FAKE_DIR/$key.unreachable" ]; then exit 7; fi +body="$FAKE_DIR/$key.$n.body"; [ -f "$body" ] || body="$FAKE_DIR/$key.body" +code="$FAKE_DIR/$key.$n.code"; [ -f "$code" ] || code="$FAKE_DIR/$key.code" +if [ -n "$out" ]; then if [ -f "$body" ]; then cp "$body" "$out"; else : > "$out"; fi; fi +cat "$code" 2> /dev/null || printf '000' +EOF + cat > "$FAKE/bin/git" << 'EOF' +#!/usr/bin/env bash +[ "$1" = ls-remote ] || exit 1 +[ -f "$FAKE_DIR/head" ] || exit 2 +printf '%s\t%s\n' "$(cat "$FAKE_DIR/head")" "$4" +EOF + chmod +x "$FAKE/bin/curl" "$FAKE/bin/git" + cat > "$WORK/repo/rasgo.deploy.yml" << 'EOF' +version: 1 +component: acme-portal +stack: laravel +adapter: laravel-ploi +environments: + staging: + ref: main + url: https://staging.example.com + approval: none + secrets: [PLOI_DEPLOY_WEBHOOK] + production: + ref: tag + url: https://example.com/ + approval: core + secrets: [PLOI_DEPLOY_WEBHOOK] +migrations: php artisan migrate --force +health: + path: /version + timeout_s: 5 +rollback: previous-tag +EOF + unset APPROVAL_ID ROLLBACK_OF TASK APP VERSION VERSIONS PLOI_BRANCH CORE_TOKEN OUTPUT_DIR CONTRACT_FILE + export FAKE_DIR="$FAKE" PATH="$FAKE/bin:$PATH" RASGO_STATE="$WORK/state.json" HEALTH_INTERVAL=0 + export GITHUB_SHA="$SHA" GITHUB_REPOSITORY="rasgo-studio/acme-portal" GITHUB_SERVER_URL="https://github.com" + export GITHUB_RUN_ID=42 GITHUB_REF_TYPE=branch GITHUB_REF_NAME=main GITHUB_STEP_SUMMARY="$WORK/summary" + export DEPLOY_ENVIRONMENT=staging DEPLOY_ADAPTERS="laravel-ploi monorepo-ploi" CORE_URL="https://core.test/" + cd "$WORK/repo" || exit 1 +} + +answer() { # key code [body] + printf '%s' "$2" > "$FAKE/$1.code" + if [ -n "${3:-}" ]; then printf '%s' "$3" > "$FAKE/$1.body"; fi +} + +core() { "$CORE" "$@" > "$OUT" 2>&1; } +has() { grep -Fq -- "$1" "$OUT"; } +state() { jq -r ".$1 // empty" "$RASGO_STATE"; } + +expect_ok() { # name command... + local name="$1" + shift + if core "$@"; then ok "$name"; else ko "$name" "exited $?"; fi +} + +expect_fail() { # name text command... + local name="$1" text="$2" + shift 2 + if core "$@"; then + ko "$name" "expected a failure" + elif has "$text"; then + ok "$name" + else + ko "$name" "missing: $text" + fi +} + +check() { # name condition... + local name="$1" + shift + if "$@"; then ok "$name"; else ko "$name" "condition: $*"; fi +} + +# --- contract --------------------------------------------------------------------------------------------------- + +setup +expect_ok "contract: staging from its branch" contract +check "contract: state has the url without the trailing slash" test "$(state url)" = "https://staging.example.com" +check "contract: version is the short commit off a tag" test "$(state version)" = "0123456" +check "contract: the contract sent to Core drops the secret names" test "$(jq '.contract | tostring | test("PLOI_DEPLOY_WEBHOOK")' "$RASGO_STATE")" = false +check "contract: app defaults to the component" test "$(state app)" = acme-portal + +setup +export DEPLOY_ENVIRONMENT=production GITHUB_REF_TYPE=tag GITHUB_REF_NAME=acme-v1.4.0 +expect_fail "contract: production needs an approval_id" "Falta approval_id" contract +check "contract: the message cites WFA-01.1" has "WFA-01.1" + +setup +export DEPLOY_ENVIRONMENT=production APPROVAL_ID=01JAPPROVAL +expect_fail "contract: production deploys a tag, not a branch" "etiqueta publicada" contract + +setup +export DEPLOY_ENVIRONMENT=production APPROVAL_ID=01JAPPROVAL GITHUB_REF_TYPE=tag GITHUB_REF_NAME=acme-v1.4.0 +expect_ok "contract: production on a tag with an approval" contract +check "contract: version is the number of the tag" test "$(state version)" = "1.4.0" +check "contract: a tag deploy follows the Ploi branch (main)" test "$(state branch)" = main +check "contract: the trailing slash of the url goes" test "$(state url)" = "https://example.com" + +setup +export DEPLOY_ENVIRONMENT=production ROLLBACK_OF=01JFAILED GITHUB_REF_TYPE=tag GITHUB_REF_NAME=v1.3.0 PLOI_BRANCH=release +expect_ok "contract: a rollback goes on without approval_id (Core decides)" contract +check "contract: PLOI_BRANCH for a tag" test "$(state branch)" = release + +setup +sed -i 's/approval: core/approval: none/' rasgo.deploy.yml +export DEPLOY_ENVIRONMENT=production APPROVAL_ID=01JAPPROVAL GITHUB_REF_TYPE=tag GITHUB_REF_NAME=v1.4.0 +expect_fail "contract: production without approval core is refused" "Producción solo despliega" contract + +setup +export DEPLOY_ADAPTERS=static +expect_fail "contract: another adapter is refused" "adapter: «laravel-ploi»" contract + +setup +export GITHUB_REF_NAME=feature-x +expect_fail "contract: staging only from its branch" "despliega la rama main" contract + +setup +export DEPLOY_ENVIRONMENT=preview +expect_fail "contract: unknown environment" "desconocido" contract + +setup +rm rasgo.deploy.yml +expect_fail "contract: no contract, no deploy" "No encuentro rasgo.deploy.yml" contract + +if python3 -c 'import jsonschema' 2> /dev/null; then + setup + if python3 - "$ROOT/schemas/deploy-contract.json" rasgo.deploy.yml << 'EOF'; then ok "contract: the fixture follows the schema"; else ko "contract: the fixture follows the schema"; fi +import json, sys, yaml, jsonschema +jsonschema.validate(yaml.safe_load(open(sys.argv[2])), json.load(open(sys.argv[1]))) +EOF + # Every contract example of the README follows the schema too. + if python3 - "$ROOT/schemas/deploy-contract.json" "$ROOT/README.md" << 'EOF'; then ok "contract: the README examples follow the schema"; else ko "contract: the README examples follow the schema"; fi +import json, re, sys, yaml, jsonschema +schema = json.load(open(sys.argv[1])) +blocks = [b for b in re.findall(r"```yaml\n(.*?)```", open(sys.argv[2]).read(), re.S) if b.startswith("version: 1")] +assert len(blocks) >= 3, blocks +for block in blocks: + jsonschema.validate(yaml.safe_load(block), schema) +EOF +fi + +# --- require ---------------------------------------------------------------------------------------------------- + +setup +export PLOI_DEPLOY_WEBHOOK="" +expect_fail "require: a missing secret stops the deploy" "PLOI_DEPLOY_WEBHOOK" require RASGO_CORE_DEPLOY_TOKEN PLOI_DEPLOY_WEBHOOK +export PLOI_DEPLOY_WEBHOOK=x RASGO_CORE_DEPLOY_TOKEN=y +expect_ok "require: all secrets present" require RASGO_CORE_DEPLOY_TOKEN PLOI_DEPLOY_WEBHOOK +check "require: the values are not printed" test "$(grep -c '^x$\|^y$' "$OUT")" = 0 +unset PLOI_DEPLOY_WEBHOOK RASGO_CORE_DEPLOY_TOKEN + +# --- branch-head ------------------------------------------------------------------------------------------------ + +setup +core contract +printf '%s' "$SHA" > "$FAKE/head" +expect_ok "branch-head: the branch is at the commit of the run" branch-head +printf '%s' "fedcba9876543210fedcba9876543210fedcba98" > "$FAKE/head" +expect_fail "branch-head: a branch that moved stops the deploy" "no recibiría el commit aprobado" branch-head + +# --- start ------------------------------------------------------------------------------------------------------ + +setup +export DEPLOY_ENVIRONMENT=production APPROVAL_ID=01JAPPROVAL TASK=ACME01WEB-23 GITHUB_REF_TYPE=tag GITHUB_REF_NAME=v1.4.0 +core contract +export CORE_TOKEN=token-secret-value +answer start 201 '{"deployment_id":"01JDEPLOY"}' +expect_ok "start: Core confirms the approval" start +check "start: the deployment_id is saved" test "$(state deployment_id)" = 01JDEPLOY +check "start: calls deploy-start on Core" grep -Fxq "https://core.test/api/v1/deploy-start" "$FAKE/urls" +check "start: the body carries the approval tuple" test "$(jq -r '[.repository, .app, .environment, .commit_sha, .approval_id, .task] | join(" ")' "$FAKE/request.start.json")" = "rasgo-studio/acme-portal acme-portal production $SHA 01JAPPROVAL ACME01WEB-23" +check "start: the body carries the run url" test "$(jq -r .run_url "$FAKE/request.start.json")" = "https://github.com/rasgo-studio/acme-portal/actions/runs/42" +check "start: no rollback_of when there is none" test "$(jq 'has("rollback_of")' "$FAKE/request.start.json")" = false +check "start: the token goes in a header" grep -Fq "Authorization: Bearer token-secret-value" "$FAKE/headers" +check "start: the token is not on the command line" test "$(grep -c token-secret-value "$FAKE/args")" = 0 + +setup +core contract +export CORE_TOKEN=t +answer start 403 '{"error":"Approval already used","reason":"used","rule":"WFA-01.1"}' +expect_fail "start: a used approval stops the deploy" "ya se usó" start +check "start: the rule is shown" has "(WFA-01.1)" +check "start: no deployment_id after a 403" test -z "$(state deployment_id)" + +setup +core contract +export CORE_TOKEN=t +answer start 403 '{"reason":"mismatch","rule":"WFA-01.1"}' +expect_fail "start: an approval for another commit stops the deploy" "otro repositorio, app, entorno o commit" start + +setup +core contract +export CORE_TOKEN=t +answer start 500 '{}' +expect_fail "start: an error of Core stops the deploy" "respondió 500" start + +setup +core contract +export CORE_TOKEN=t +touch "$FAKE/start.unreachable" +expect_fail "start: without Core nothing deploys" "No llego a Core" start + +setup +core contract +answer start 201 '{"deployment_id":"01JDEPLOY"}' +expect_fail "start: without the token nothing deploys" "RASGO_CORE_DEPLOY_TOKEN" start + +setup +core contract +export CORE_TOKEN=t +answer start 201 '{}' +expect_fail "start: a 201 without deployment_id stops the deploy" "sin deployment_id" start + +# --- health ----------------------------------------------------------------------------------------------------- + +setup +core contract +printf '200' > "$FAKE/health.1.code" +printf '{"version":"0.9.0","commit":"aaaaaaa"}' > "$FAKE/health.1.body" +answer health 200 '{"version":"0.9.1","commit":"0123456"}' +expect_ok "health: waits until the short commit is served" health +check "health: asked twice" test "$(cat "$FAKE/count.health")" = 2 +check "health: asks url plus path" grep -Fxq "https://staging.example.com/version" "$FAKE/urls" +check "health: state ok" test "$(state health)" = ok + +setup +export DEPLOY_ENVIRONMENT=production APPROVAL_ID=a GITHUB_REF_TYPE=tag GITHUB_REF_NAME=acme-v1.4.0 +core contract +answer health 200 '{"app":"acme-portal","version":"1.4.0"}' +expect_ok "health: the version number counts" health + +setup +export DEPLOY_ENVIRONMENT=production APPROVAL_ID=a GITHUB_REF_TYPE=tag GITHUB_REF_NAME=acme-v1.4.0 +core contract +jq '.health_timeout = "1"' "$RASGO_STATE" > "$RASGO_STATE.tmp" && mv "$RASGO_STATE.tmp" "$RASGO_STATE" +export HEALTH_INTERVAL=1 +answer health 200 '{"version":"11.4.0"}' +expect_fail "health: another version is not this one (timeout)" "no sirve la versión 1.4.0" health +check "health: state failed" test "$(state health)" = failed + +setup +sed -i 's| timeout_s: 5| expect: status\n timeout_s: 5|' rasgo.deploy.yml +core contract +answer health 200 'hello' +expect_ok "health: status only" health +jq '.health_timeout = "1"' "$RASGO_STATE" > "$RASGO_STATE.tmp" && mv "$RASGO_STATE.tmp" "$RASGO_STATE" +export HEALTH_INTERVAL=1 +answer health 503 'down' +expect_fail "health: a 503 is not healthy" "último código: 503" health + +# --- finish ----------------------------------------------------------------------------------------------------- + +setup +core contract +export CORE_TOKEN=t +jq '.deployment_id = "01JDEPLOY" | .health = "ok"' "$RASGO_STATE" > "$RASGO_STATE.tmp" && mv "$RASGO_STATE.tmp" "$RASGO_STATE" +answer finish 200 '{}' +export VERSIONS='{"api":"1.2.0","hub":"0.4.0"}' +expect_ok "finish: a healthy deploy" finish +check "finish: result success" test "$(jq -r .result "$FAKE/request.finish.json")" = success +check "finish: deployment_id and version" test "$(jq -r '[.deployment_id, .version] | join(" ")' "$FAKE/request.finish.json")" = "01JDEPLOY 0123456" +check "finish: versions of a monorepo" test "$(jq -r .versions.hub "$FAKE/request.finish.json")" = 0.4.0 +check "finish: finished_at in UTC" grep -Eq '"finished_at": "[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]{8}Z"' "$FAKE/request.finish.json" +check "finish: retries only when Core cannot be reached" grep -Fq -- "--retry 3 --retry-connrefused" "$FAKE/args" + +setup +export DEPLOY_ENVIRONMENT=production ROLLBACK_OF=01JFAILED GITHUB_REF_TYPE=tag GITHUB_REF_NAME=v1.3.0 +core contract +export CORE_TOKEN=t +jq '.deployment_id = "01JDEPLOY" | .health = "ok"' "$RASGO_STATE" > "$RASGO_STATE.tmp" && mv "$RASGO_STATE.tmp" "$RASGO_STATE" +answer finish 200 '{}' +expect_ok "finish: a rollback" finish +check "finish: a healthy rollback is rolled_back" test "$(jq -r .result "$FAKE/request.finish.json")" = rolled_back + +setup +core contract +export CORE_TOKEN=t +jq '.deployment_id = "01JDEPLOY" | .health = "failed"' "$RASGO_STATE" > "$RASGO_STATE.tmp" && mv "$RASGO_STATE.tmp" "$RASGO_STATE" +answer finish 200 '{}' +expect_ok "finish: records a failed deploy" finish +check "finish: result failure" test "$(jq -r .result "$FAKE/request.finish.json")" = failure + +setup +core contract +export CORE_TOKEN=t +jq '.deployment_id = "01JDEPLOY"' "$RASGO_STATE" > "$RASGO_STATE.tmp" && mv "$RASGO_STATE.tmp" "$RASGO_STATE" +answer finish 200 '{}' +expect_ok "finish: a deploy that never got checked" finish +check "finish: without health it is a failure" test "$(jq -r .result "$FAKE/request.finish.json")" = failure + +setup +core contract +export CORE_TOKEN=t +expect_ok "finish: nothing to close when deploy-start did not create it" finish +check "finish: no call to Core" test ! -f "$FAKE/request.finish.json" + +setup +expect_ok "finish: nothing to close without a contract" finish + +setup +core contract +export CORE_TOKEN=t +jq '.deployment_id = "01JDEPLOY" | .health = "ok"' "$RASGO_STATE" > "$RASGO_STATE.tmp" && mv "$RASGO_STATE.tmp" "$RASGO_STATE" +answer finish 500 '{}' +expect_fail "finish: says when the deploy stays open in Core" "queda abierto en Core" finish + +setup +core contract +export CORE_TOKEN=t VERSIONS='not json' +jq '.deployment_id = "01JDEPLOY" | .health = "ok"' "$RASGO_STATE" > "$RASGO_STATE.tmp" && mv "$RASGO_STATE.tmp" "$RASGO_STATE" +expect_fail "finish: versions must be a JSON object" "no es un objeto JSON" finish + +# --- version-file ----------------------------------------------------------------------------------------------- + +setup +core contract +mkdir -p .output/public +export OUTPUT_DIR=.output/public +expect_ok "version-file: writes version.json" version-file +check "version-file: with the commit" test "$(jq -r .commit .output/public/version.json)" = "$SHA" +check "version-file: with the component" test "$(jq -r .component .output/public/version.json)" = acme-portal +printf '{"mine":true}' > .output/public/version.json +expect_ok "version-file: an existing version.json stays" version-file +check "version-file: untouched" test "$(jq -r .mine .output/public/version.json)" = true +expect_fail "version-file: a folder that does not exist" "No existe la carpeta" version-file dist + +printf '\n%s passed, %s failed\n' "$PASS" "$FAILED" +[ "$FAILED" -eq 0 ]