From c9238b21d53631e42b5f3257ef17cbdd67978ef7 Mon Sep 17 00:00:00 2001 From: Rishi Balakrishnan Date: Sun, 30 Aug 2026 15:15:19 -0400 Subject: [PATCH] feat(ci): add tracked staging validation --- .../build-and-push-bskyweb-docr-staging.yaml | 152 ++++++++++++++++++ Dockerfile | 4 + bskyweb/cmd/bskyweb/main.go | 5 + bskyweb/cmd/bskyweb/release_test.go | 41 +++++ bskyweb/cmd/bskyweb/server.go | 12 ++ package.json | 2 +- 6 files changed, 215 insertions(+), 1 deletion(-) create mode 100644 bskyweb/cmd/bskyweb/release_test.go diff --git a/.github/workflows/build-and-push-bskyweb-docr-staging.yaml b/.github/workflows/build-and-push-bskyweb-docr-staging.yaml index 42d5bb398..a7843fb73 100644 --- a/.github/workflows/build-and-push-bskyweb-docr-staging.yaml +++ b/.github/workflows/build-and-push-bskyweb-docr-staging.yaml @@ -1,6 +1,28 @@ name: build-and-push-bskyweb-docr-staging on: workflow_dispatch: + inputs: + pull_request: + description: Pull request number to validate + required: true + type: string + commit_sha: + description: Exact 40-character PR head SHA to deploy + required: true + type: string + acceptance_criteria: + description: What Rishi should verify on staging + required: true + type: string + ttl_hours: + description: Hours before this staging claim expires + required: true + default: "72" + type: string + +concurrency: + group: blacksky-community-client-staging + cancel-in-progress: false jobs: bskyweb-container-docr-staging: @@ -8,10 +30,37 @@ jobs: runs-on: ubuntu-latest permissions: contents: read + deployments: write + pull-requests: read steps: - name: Checkout repository uses: actions/checkout@v4 + with: + ref: ${{ inputs.commit_sha }} + + - name: Validate staging request + uses: actions/github-script@v7 + env: + EXPECTED_SHA: ${{ inputs.commit_sha }} + PULL_REQUEST: ${{ inputs.pull_request }} + ACCEPTANCE_CRITERIA: ${{ inputs.acceptance_criteria }} + TTL_HOURS: ${{ inputs.ttl_hours }} + with: + script: | + const sha = process.env.EXPECTED_SHA.trim().toLowerCase() + const prNumber = Number(process.env.PULL_REQUEST) + const ttlHours = Number(process.env.TTL_HOURS) + if (!/^[0-9a-f]{40}$/.test(sha)) throw new Error('commit_sha must be a full 40-character SHA') + if (!Number.isInteger(prNumber) || prNumber <= 0) throw new Error('pull_request must be a positive integer') + if (!Number.isFinite(ttlHours) || ttlHours < 1 || ttlHours > 168) throw new Error('ttl_hours must be between 1 and 168') + if (core.isDebug()) core.info(`Validating PR #${prNumber} at ${sha}`) + const pull = await github.rest.pulls.get({ owner: context.repo.owner, repo: context.repo.repo, pull_number: prNumber }) + if (pull.data.state !== 'open') throw new Error(`PR #${prNumber} is ${pull.data.state}, not open`) + if (pull.data.head.sha.toLowerCase() !== sha) throw new Error(`PR #${prNumber} head is ${pull.data.head.sha}, not ${sha}`) + if (process.env.ACCEPTANCE_CRITERIA.trim().length === 0) throw new Error('acceptance_criteria must not be empty') + + core.info(`Validated PR #${prNumber} at ${sha} with a ${ttlHours}-hour TTL`) - name: Setup Docker buildx uses: docker/setup-buildx-action@v3 @@ -63,3 +112,106 @@ jobs: EXPO_PUBLIC_GROWTHBOOK_CLIENT_KEY=${{ secrets.EXPO_PUBLIC_GROWTHBOOK_CLIENT_KEY }} EXPO_PUBLIC_STRIPE_API_URL=${{ secrets.EXPO_PUBLIC_STRIPE_API_URL }} EXPO_PUBLIC_STRIPE_PUBLISHABLE_KEY=${{ secrets.EXPO_PUBLIC_STRIPE_PUBLISHABLE_KEY }} + + - name: Create staging deployment record + id: deployment + uses: actions/github-script@v7 + env: + EXPECTED_SHA: ${{ inputs.commit_sha }} + PULL_REQUEST: ${{ inputs.pull_request }} + ACCEPTANCE_CRITERIA: ${{ inputs.acceptance_criteria }} + TTL_HOURS: ${{ inputs.ttl_hours }} + IMAGE_DIGEST: ${{ steps.build-and-push.outputs.digest }} + with: + script: | + const sha = process.env.EXPECTED_SHA.trim().toLowerCase() + const prNumber = Number(process.env.PULL_REQUEST) + const expiresAt = new Date(Date.now() + Number(process.env.TTL_HOURS) * 60 * 60 * 1000).toISOString() + const created = await github.rest.repos.createDeployment({ + owner: context.repo.owner, + repo: context.repo.repo, + ref: sha, + auto_merge: false, + required_contexts: [], + environment: 'client-staging', + transient_environment: true, + production_environment: false, + description: `PR #${prNumber} staging validation`, + payload: { + schemaVersion: 1, + kind: 'client-staging-validation', + repository: `${context.repo.owner}/${context.repo.repo}`, + pullRequest: prNumber, + commitSha: sha, + requestedBy: context.actor, + expiresAt, + acceptanceCriteria: process.env.ACCEPTANCE_CRITERIA.trim(), + rollbackImage: `registry.digitalocean.com/blacksky/blacksky-community:staging-${sha}`, + imageDigest: process.env.IMAGE_DIGEST, + }, + }) + core.setOutput('id', String(created.data.id)) + await github.rest.repos.createDeploymentStatus({ + owner: context.repo.owner, + repo: context.repo.repo, + deployment_id: created.data.id, + state: 'in_progress', + description: 'Immutable image built; deploying to staging', + log_url: `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`, + auto_inactive: false, + }) + + - name: Deploy immutable build to App Platform and verify live SHA + env: + EXPECTED_SHA: ${{ inputs.commit_sha }} + STAGING_URL: https://staging.blacksky.community + run: | + set -euo pipefail + app_id="$(doctl apps list --format ID,Spec.Name --no-header | awk '$2 == "blacksky-community-staging" { print $1 }')" + test -n "$app_id" + deployment_id="$(doctl apps create-deployment "$app_id" --format ID --no-header)" + test -n "$deployment_id" + + phase="" + for _ in $(seq 1 60); do + phase="$(doctl apps get-deployment "$app_id" "$deployment_id" --format Phase --no-header)" + case "$phase" in + ACTIVE) break ;; + ERROR|CANCELED|SUPERSEDED) echo "App Platform deployment ended in $phase" >&2; exit 1 ;; + esac + sleep 10 + done + test "$phase" = "ACTIVE" + + for _ in $(seq 1 30); do + if curl --fail --silent --show-error --header 'Cache-Control: no-cache' "$STAGING_URL/_release?expected=$EXPECTED_SHA" \ + | jq --exit-status --arg sha "$EXPECTED_SHA" '.commitSha == $sha' >/dev/null; then + exit 0 + fi + sleep 10 + done + echo "Staging never reported expected SHA $EXPECTED_SHA" >&2 + exit 1 + + - name: Record final staging status + if: always() && steps.deployment.outputs.id != '' + uses: actions/github-script@v7 + env: + DEPLOYMENT_ID: ${{ steps.deployment.outputs.id }} + EXPECTED_SHA: ${{ inputs.commit_sha }} + JOB_STATUS: ${{ job.status }} + with: + script: | + const success = process.env.JOB_STATUS === 'success' + await github.rest.repos.createDeploymentStatus({ + owner: context.repo.owner, + repo: context.repo.repo, + deployment_id: Number(process.env.DEPLOYMENT_ID), + state: success ? 'success' : 'failure', + description: success + ? `Staging serves ${process.env.EXPECTED_SHA.slice(0, 12)}; needs human validation` + : `Staging verification failed for ${process.env.EXPECTED_SHA.slice(0, 12)}`, + environment_url: 'https://staging.blacksky.community', + log_url: `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`, + auto_inactive: false, + }) diff --git a/Dockerfile b/Dockerfile index 81e74d47a..7aab023bf 100644 --- a/Dockerfile +++ b/Dockerfile @@ -99,6 +99,9 @@ FROM golang:1.26-bookworm AS go-build WORKDIR /usr/src/social-app +ARG EXPO_PUBLIC_RELEASE_VERSION +ARG EXPO_PUBLIC_BUNDLE_IDENTIFIER + ENV GODEBUG="netdns=go" ENV GOOS="linux" ENV GOARCH="amd64" @@ -119,6 +122,7 @@ RUN cd bskyweb/ && \ -v \ -trimpath \ -tags timetzdata \ + -ldflags "-X main.releaseCommit=$EXPO_PUBLIC_BUNDLE_IDENTIFIER -X main.releaseVersion=$EXPO_PUBLIC_RELEASE_VERSION" \ -o /bskyweb \ ./cmd/bskyweb diff --git a/bskyweb/cmd/bskyweb/main.go b/bskyweb/cmd/bskyweb/main.go index bcb67ddfe..0bcb9c1e2 100644 --- a/bskyweb/cmd/bskyweb/main.go +++ b/bskyweb/cmd/bskyweb/main.go @@ -11,6 +11,11 @@ import ( var log = logging.Logger("bskyweb") +var ( + releaseCommit = "unknown" + releaseVersion = "unknown" +) + func init() { logging.SetAllLoggers(logging.LevelDebug) //logging.SetAllLoggers(logging.LevelWarn) diff --git a/bskyweb/cmd/bskyweb/release_test.go b/bskyweb/cmd/bskyweb/release_test.go new file mode 100644 index 000000000..d5ec64655 --- /dev/null +++ b/bskyweb/cmd/bskyweb/release_test.go @@ -0,0 +1,41 @@ +package main + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/labstack/echo/v4" +) + +func TestReleaseIdentity(t *testing.T) { + previousCommit, previousVersion := releaseCommit, releaseVersion + releaseCommit, releaseVersion = "0123456789abcdef", "1.2.3" + t.Cleanup(func() { + releaseCommit, releaseVersion = previousCommit, previousVersion + }) + + e := echo.New() + req := httptest.NewRequest(http.MethodGet, "/_release", nil) + rec := httptest.NewRecorder() + ctx := e.NewContext(req, rec) + + if err := (&Server{}).ReleaseIdentity(ctx); err != nil { + t.Fatal(err) + } + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) + } + if got := rec.Header().Get("Cache-Control"); got != "no-store" { + t.Fatalf("Cache-Control = %q, want no-store", got) + } + + var body map[string]string + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + if body["commitSha"] != releaseCommit || body["version"] != releaseVersion { + t.Fatalf("body = %#v", body) + } +} diff --git a/bskyweb/cmd/bskyweb/server.go b/bskyweb/cmd/bskyweb/server.go index 70ee06c39..09d61831e 100644 --- a/bskyweb/cmd/bskyweb/server.go +++ b/bskyweb/cmd/bskyweb/server.go @@ -309,6 +309,10 @@ func serve(cctx *cli.Context) error { // PWA manifest (generated dynamically from brand config) e.GET("/manifest.json", server.WebManifest) + // Immutable build identity used by deployment verification. This intentionally + // contains portable release data only; workflow and BB-local state stay elsewhere. + e.GET("/_release", server.ReleaseIdentity) + // OAuth client metadata (generated dynamically from request host) e.GET("/oauth-client-metadata.json", server.OAuthClientMetadata) e.GET("/oauth-client-metadata-native.json", server.OAuthClientMetadataNative) @@ -484,6 +488,14 @@ func serve(cctx *cli.Context) error { return nil } +func (srv *Server) ReleaseIdentity(c echo.Context) error { + c.Response().Header().Set("Cache-Control", "no-store") + return c.JSON(http.StatusOK, map[string]string{ + "commitSha": releaseCommit, + "version": releaseVersion, + }) +} + func newMetricsHTTPServer(address string) (*http.Server, net.Listener, error) { metricsMux := http.NewServeMux() metricsMux.Handle("/metrics", promhttp.Handler()) diff --git a/package.json b/package.json index d13487e37..bd3ee1d2a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "blacksky.community", - "version": "1.127.1", + "version": "1.128.0", "private": true, "packageManager": "pnpm@11.7.0", "engines": { -- knotmirror 0.0.1