#!/usr/bin/env bash # Forced-command deploy wrapper — the ONLY thing the CI deploy key is allowed to run on a # target host. Install it OUTSIDE the git checkout (so `git checkout` here can never rewrite # the running script) and pin it as the forced command for the CI key in authorized_keys: # # from="",restrict,command="/home/deploy/ci-deploy-wrapper.sh" ssh-ed25519 AAAA... gitea-ci-deploy # # With that line, the CI runner can only ever trigger a deploy of a validated image tag on # THIS host — never an arbitrary shell command, port-forward, or PTY. The tag the runner asks # for arrives as $SSH_ORIGINAL_COMMAND (ignored as a command, read here as data). # # Also runnable by hand for break-glass deploys / rollbacks: ./ci-deploy-wrapper.sh v1.2.3 set -euo pipefail # Host-specific config lives next to the installed wrapper, so this script stays byte-identical # across hosts. Create it once, e.g.: echo 'DEPLOY_DIR=/opt/termportal-prod' > ci-deploy.conf conf="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/ci-deploy.conf" # shellcheck source=/dev/null [[ -f "$conf" ]] && source "$conf" : "${DEPLOY_DIR:?set DEPLOY_DIR in ci-deploy.conf next to the wrapper}" # Tag from the argument (manual use) or the forced-command's SSH_ORIGINAL_COMMAND (CI use). tag="${1:-${SSH_ORIGINAL_COMMAND:-}}" # Strict allow-list, matched against the WHOLE value (no tokenizing) so multi-token or # metacharacter input fails closed and loud. Registry tags are [A-Za-z0-9._-]; the leading-char # anchor also blocks option injection (a tag can't start with '-'). This stops a compromised # Gitea/workflow from smuggling anything but a bare tag through SSH_ORIGINAL_COMMAND. if [[ ! "$tag" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]]; then echo "ci-deploy-wrapper: refusing invalid tag: '${tag}'" >&2 exit 2 fi ref="${tag#sha-}" # sha-abc1234 -> abc1234 ; v1.2.3 stays v1.2.3 echo "+ deploy tag=${tag} ref=${ref} dir=${DEPLOY_DIR}" >&2 cd "$DEPLOY_DIR" git fetch --tags --prune origin git checkout --force "$ref" export IMAGE_TAG="$tag" # picked up by docker compose via run-prod.sh echo "$tag" >.deployed_tag # small audit trail of what is running ./run-prod.sh pull ./run-prod.sh up -d docker image prune -f