Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

33.9 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 BoxLite AI

import assert from 'node:assert/strict'
import test from 'node:test'

import {
  GcpBootstrapError,
  attributeCondition,
  bootstrapGcp,
  promotionSourceFor,
  type Run,
  type RunResult,
} from './gcp.js'

const GITHUB = {
  issuer: 'https://token.actions.githubusercontent.com',
  owner: 'boxlite-ai',
  ownerId: '123456',
  repository: 'boxlite',
  repositoryId: '789012',
}

/** The calls this file treats as questions rather than changes. */
const QUERIES = [
  'secrets describe',
  'secrets versions access',
  'storage buckets describe',
  'iam workload-identity-pools describe',
  'iam workload-identity-pools providers describe',
  'iam service-accounts describe',
  'artifacts repositories describe',
]

/**
 * A `run` that records what it was asked to do. `existing` decides how the
 * existence questions are answered; every change succeeds, which is what
 * makes a failing change its own test below.
 */
const recorder = ({
  existing = false,
  readsBeforeVisible = 0,
  etagConflicts = 0,
  conditioned = [],
}: {
  existing?: boolean
  readsBeforeVisible?: number
  etagConflicts?: number
  /** Policies this fixture says already hold a condition, by the name the binding names them. */
  conditioned?: string[]
} = {}) => {
  const calls: string[][] = []
  const stdin: string[] = []
  /*
   * How many policy writes lose the read-modify-write race before one lands.
   *
   * `add-iam-policy-binding` reads the policy, edits it and writes it back
   * against the ETag it read. Another writer in between makes the write a
   * conflict, which this project has because it is shared with the other
   * BoxLite apps. Counted across every policy write rather than per binding:
   * the conflict is with whoever else is editing, not with this run.
   */
  let conflictsLeft = etagConflicts
  /*
   * How many `describe` reads a just-created service account answers NOT_FOUND
   * for before it is visible. Zero is an API that is immediately consistent;
   * the real one is not, and answers `Service account <email> does not exist`
   * to the grant that follows `create`. Modelled per account, because that is
   * how the window behaves.
   */
  const pending = new Map<string, number>()
  const run: Run = async (command, args, options = {}) => {
    calls.push([command, ...args])
    if (options.stdin !== undefined && options.stdin !== '') stdin.push(options.stdin)
    const asked = args.join(' ')
    if (asked.startsWith('iam service-accounts create')) {
      pending.set(`${args[3]}@boxlite-gcp-dev.iam.gserviceaccount.com`, readsBeforeVisible)
      return { code: 0, stdout: '', stderr: '' }
    }
    if (asked.startsWith('iam service-accounts describe')) {
      const email = args[3] as string
      if (!pending.has(email)) return existing ? { code: 0, stdout: '{}', stderr: '' } : { code: 254, stdout: '', stderr: 'NOT_FOUND' }
      const left = pending.get(email) as number
      if (left <= 0) return { code: 0, stdout: '{}', stderr: '' }
      pending.set(email, left - 1)
      return { code: 254, stdout: '', stderr: 'NOT_FOUND' }
    }
    /*
     * The refusal the propagation window actually produces. A grant attempted
     * before the account is visible does not queue — it fails, naming as absent
     * the account the line above created.
     */
    if (asked.includes('add-iam-policy-binding')) {
      /*
       * gcloud's own refusal, raised between the read and the write.
       *
       * A policy that already holds a condition will not take a binding that
       * says nothing about having one: a terminal prompts for it, and `--quiet`
       * over a closed stdin — what `execRun` gives every call — is this error.
       * First in this branch because that is where gcloud raises it: no policy
       * is written, so neither the propagation window below nor an ETag
       * conflict can be what a caller sees.
       */
      const target = args[args.indexOf('add-iam-policy-binding') + 1] as string
      if (conditioned.includes(target) && !args.some((argument) => argument.startsWith('--condition'))) {
        return {
          code: 1,
          stdout: '',
          stderr:
            `ERROR: (gcloud.${args.slice(0, args.indexOf('add-iam-policy-binding') + 1).join('.')}) Adding a ` +
            'binding without specifying a condition to a policy containing conditions is prohibited in ' +
            'non-interactive mode. Run the command again with `--condition=None`',
        }
      }
      const member = args.find((argument) => argument.startsWith('--member=serviceAccount:'))
      const email = member?.replace('--member=serviceAccount:', '') ?? ''
      if ((pending.get(email) ?? 0) > 0) {
        return { code: 1, stdout: '', stderr: `INVALID_ARGUMENT: Service account ${email} does not exist.` }
      }
      if (conflictsLeft > 0) {
        conflictsLeft -= 1
        // gcloud's own words, from the run that hit this, with this fixture's own
        // project in place of the one that ran.
        return {
          code: 1,
          stdout: '',
          stderr:
            'ERROR: (gcloud.projects.add-iam-policy-binding) Resource in projects ' +
            '[boxlite-gcp-dev:setIamPolicy] is the subject of a conflict: There were concurrent ' +
            "policy changes. Please retry the whole read-modify-write with exponential backoff. The request's " +
            "ETag '\\007\\006[/\\320T\\264\\254' did not match the current policy's ETag '\\007\\006[/\\320\\201\\033h'.",
        }
      }
      return { code: 0, stdout: '', stderr: '' }
    }
    if (asked.startsWith('projects describe')) return { code: 0, stdout: '999999999999\n', stderr: '' }
    // A project already bootstrapped names its bucket here, which is what makes
    // the re-run path reachable at all; an absent record is the first run.
    if (asked.startsWith('secrets versions access')) {
      return existing
        ? { code: 0, stdout: JSON.stringify({ state: 'mstage-state-0123456789abcdef' }), stderr: '' }
        : { code: 254, stdout: '', stderr: 'NOT_FOUND' }
    }
    // Nothing enabled yet, so every service in the list is missing.
    if (asked.startsWith('services list')) return { code: 0, stdout: '', stderr: '' }
    if (QUERIES.some((query) => asked.startsWith(query))) {
      return existing ? { code: 0, stdout: '{}', stderr: '' } : { code: 254, stdout: '', stderr: 'NOT_FOUND' }
    }
    return { code: 0, stdout: '', stderr: '' }
  }
  const applied = (...needles: string[]): string[][] =>
    calls.filter((call) => needles.every((needle) => call.join(' ').includes(needle)))
  return { run, calls, stdin, applied }
}

/** One invocation, with the coordinates a real run would read from mstage/mbuild config. */
const invoke = (run: Run, overrides: Partial<Parameters<typeof bootstrapGcp>[0]> = {}) =>
  bootstrapGcp({
    run,
    project: 'boxlite-gcp-dev',
    region: 'asia-southeast1',
    app: 'boxlite',
    appShort: 'bl-app',
    stage: 'gcp-dev',
    repository: 'boxlite-app-gcp-dev',
    immutableTags: true,
    github: GITHUB,
    log: () => {},
    // The retry is proved without spending it; the real default is a timer.
    wait: async () => {},
    ...overrides,
  })

/**
 * Which projects a run reached, read off the calls rather than counted.
 *
 * `gcloudFor` puts `--project` on every call, so this is the whole of "did
 * anything touch a project other than this stage's" — the property the
 * promotion grants are the only exception to.
 */
const projectsTouched = (calls: string[][]): string[] =>
  [...new Set(calls.map((call) => call[call.indexOf('--project') + 1] as string))].sort()

const SOURCE = {
  stage: 'gcp-src',
  project: 'boxlite-gcp-src',
  bucket: 'boxlite-gcp-src-artifacts-boxlite-gcp-src',
}

test('a fresh project gets every prerequisite mdeploy and mbuild cannot create for themselves', async () => {
  const gcloud = recorder()
  const result = await invoke(gcloud.run)

  assert.equal(gcloud.applied('services enable').length, 1, 'no APIs were enabled')
  // One argument equal to the service, not a string containing its name: these
  // are argv arrays, and `includes` on one is exact — spelled as a comparison so
  // that reads the same to anything that cannot narrow the type.
  const enabled = gcloud.applied('services enable')[0] ?? []
  assert.ok(
    enabled.some((argument) => argument === 'container.googleapis.com'),
    'the GKE API was not enabled',
  )
  assert.ok(
    enabled.some((argument) => argument === 'file.googleapis.com'),
    'the Filestore API was not enabled',
  )
  assert.equal(gcloud.applied('storage buckets create').length, 2, 'the state and artifacts buckets')
  /*
   * The runner's staging bucket, named by the rule `mdeploy/stack/runner-binary
   * .ts` resolves addresses from. Created here for the ordering reason the image
   * repository is: `runner:build` stages an object before any stack could
   * consume one, so the consumer cannot create its own input.
   */
  assert.equal(
    gcloud.applied('storage buckets create', 'gs://boxlite-gcp-dev-artifacts-boxlite-gcp-dev').length,
    1,
    'no bucket for a build-mode runner binary',
  )
  assert.equal(gcloud.applied('storage buckets update', '--versioning').length, 1, 'the bucket is unversioned')
  assert.equal(gcloud.applied('secrets create', 'mstage-bootstrap').length, 1, 'nothing names the bucket')
  assert.equal(
    gcloud.applied('secrets create', 'mstage-passphrase-boxlite-gcp-dev').length,
    1,
    'the store has nothing to be sealed with',
  )
  assert.equal(gcloud.applied('workload-identity-pools create').length, 1, 'no pool for CI to federate into')
  assert.equal(gcloud.applied('providers create-oidc').length, 1, 'no provider trusting GitHub')
  assert.equal(gcloud.applied('service-accounts create', 'bl-app-gcp-dev-deploy').length, 1, 'no deployer')
  assert.equal(gcloud.applied('service-accounts create', 'bl-app-publish').length, 1, 'no image publisher')
  assert.equal(gcloud.applied('artifacts repositories create', 'boxlite-app-gcp-dev').length, 1, 'no docker repository')
  /*
   * What lets a deploy reach a host it can never re-create: the OS Config agent
   * reads project metadata, so turning it on here covers the runners that are
   * already running with their boot script frozen.
   */
  assert.equal(
    gcloud.applied('project-info add-metadata', 'enable-osconfig=TRUE').length,
    1,
    'the OS Config agent is never turned on, so no policy can reach a host',
  )
  /*
   * The declaration mbuild reads, honoured at the one moment it can be: tag
   * immutability is fixed at creation and no command changes it afterwards. A
   * repository made without it is one mbuild then refuses to publish into, so
   * the mismatch costs a repository that has to be deleted by hand.
   */
  assert.ok(
    gcloud.applied('artifacts repositories create', '--immutable-tags').length === 1,
    'the repository was created with movable tags',
  )

  assert.equal(result.deployerEmail, '[email protected]')
  assert.equal(result.publisherEmail, '[email protected]')
  assert.match(result.workloadIdentityProvider, /^projects\/999999999999\/.*\/workloadIdentityPools\/bl-app\/providers\/github$/)
})

test('re-running reconciles what is there instead of creating it again', async () => {
  const gcloud = recorder({ existing: true })
  await invoke(gcloud.run)

  for (const created of ['service-accounts create', 'storage buckets create', 'secrets create']) {
    assert.deepEqual(gcloud.applied(created), [], `${created} ran against a project that already has it`)
  }
  assert.deepEqual(gcloud.applied('workload-identity-pools create'), [])
  assert.deepEqual(gcloud.applied('artifacts repositories create'), [])
  // The provider is still reapplied: its attribute condition is the fence, and
  // a rerun with a different repository has to reach GCP somehow.
  assert.equal(gcloud.applied('providers update-oidc').length, 1)
})

test('every call carries the project and never waits on a prompt', async () => {
  const gcloud = recorder()
  await invoke(gcloud.run)
  assert.ok(gcloud.calls.length > 0)
  for (const call of gcloud.calls) {
    assert.equal(call[0], 'gcloud')
    assert.ok(call.includes('boxlite-gcp-dev'), `no project on: ${call.join(' ')}`)
    assert.ok(call.includes('--quiet'), `no --quiet on: ${call.join(' ')}`)
  }
})

test('the deployer may act as the stage environment, and the publisher as main and the stage', async () => {
  const gcloud = recorder()
  await invoke(gcloud.run)

  const deployerGrant = gcloud
    .applied('service-accounts add-iam-policy-binding', 'bl-app-gcp-dev-deploy@')[0]!
    .join(' ')
  assert.match(deployerGrant, /attribute\.environment\/gcp-dev/)

  const publisherGrants = gcloud.applied('service-accounts add-iam-policy-binding', 'bl-app-publish@')
  assert.equal(publisherGrants.length, 2, 'the publisher needs both claim shapes')
  assert.ok(publisherGrants.some((call) => call.join(' ').includes('attribute.ref/refs/heads/main')))
  assert.ok(publisherGrants.some((call) => call.join(' ').includes('attribute.environment/gcp-dev')))
})

test('a service account is probed by the name gcloud accepts, not the one it is created with', async () => {
  // `create` takes the bare id and `describe` takes the full email — probing
  // with the id would make every re-run try to create an account already there.
  const gcloud = recorder()
  await invoke(gcloud.run)
  const probes = gcloud.applied('service-accounts describe')
  assert.ok(probes.length >= 2, 'the deployer and the publisher are both probed')
  for (const probe of probes) {
    assert.ok(probe.some((argument) => argument.endsWith('.iam.gserviceaccount.com')), `probed with: ${probe.join(' ')}`)
  }
})

test('a service account is granted its roles on the run that created it', async () => {
  /*
   * `create` returns before the account is visible to the IAM policy API, so
   * the grant that follows was refused with `Service account <email> does not
   * exist` — naming as absent the account the line above had just made. A first
   * bootstrap died there with the deployer created and none of its roles
   * attached, and only a second run completed. Reconciling on re-run is not the
   * same as working.
   *
   * Every role is named here rather than counted, and none of it is read back
   * from `gcp.ts`: this is the privilege a CI identity holds over the whole
   * project, so the declaration and the assertion have to be two independent
   * statements. A count would accept a role swapped for another, and reading
   * the list from production would accept anything at all. Adding a privilege
   * is meant to cost an edit here — that edit is the review. The last two are
   * this change's, and are the reason the weaker form was not enough.
   */
  const gcloud = recorder({ readsBeforeVisible: 2 })
  const result = await invoke(gcloud.run)

  const grants = gcloud.applied('projects add-iam-policy-binding', 'bl-app-gcp-dev-deploy@')
  assert.deepEqual(
    grants.map((argv: string[]) => argv.find((arg) => arg.startsWith('--role='))?.slice('--role='.length)).sort(),
    [
      'roles/artifactregistry.reader',
      'roles/certificatemanager.owner',
      'roles/cloudsql.admin',
      'roles/compute.admin',
      'roles/compute.osAdminLogin',
      'roles/container.admin',
      'roles/dns.admin',
      'roles/iam.roleAdmin',
      'roles/iam.serviceAccountAdmin',
      'roles/iam.serviceAccountUser',
      'roles/iap.tunnelResourceAccessor',
      'roles/logging.configWriter',
      'roles/monitoring.editor',
      'roles/osconfig.osPolicyAssignmentAdmin',
      'roles/redis.admin',
      'roles/resourcemanager.projectIamAdmin',
      'roles/run.admin',
      'roles/secretmanager.admin',
      'roles/servicenetworking.networksAdmin',
      'roles/storage.admin',
    ],
    'the roles the deployer receives are not the roles this repository grants',
  )
  assert.ok(result.deployerEmail.startsWith('bl-app-gcp-dev-deploy@'))
  // The wait is a read loop, not a blind sleep: it stops as soon as the account
  // answers, so an immediately consistent API costs one extra read and no time.
  const probes = gcloud.applied('service-accounts describe', 'bl-app-gcp-dev-deploy@')
  assert.equal(probes.length, 4, `expected one absent probe, two retries and the answer: ${probes.length}`)
})

test('the publisher may read the findings its own scan gate blocks on', async () => {
  /*
   * A publish that pushed the image and then died reading it:
   *
   *   Permission 'containeranalysis.occurrences.list' denied on resource
   *   'projects/...' (or it may not exist)
   *
   * The push and the read are two services. `artifactregistry.writer` carries
   * the push; the gate's `gcloud artifacts docker images describe
   * --show-package-vulnerability` lists occurrences out of Container Analysis,
   * and nothing in the registry's role reaches them. mbuild reads that refusal
   * as a failed publish and spends three attempts on it.
   *
   * Named rather than counted, and not read back from `gcp.ts`, for the reason
   * the deployer's list above is: this is project-wide privilege, so the
   * declaration and the assertion are two independent statements.
   */
  const gcloud = recorder()
  await invoke(gcloud.run)

  const grants = gcloud.applied('projects add-iam-policy-binding', 'bl-app-publish@')
  assert.deepEqual(
    grants.map((argv: string[]) => argv.find((arg) => arg.startsWith('--role='))?.slice('--role='.length)).sort(),
    ['roles/artifactregistry.writer', 'roles/containeranalysis.occurrences.viewer'],
    'the roles the publisher receives are not the roles this repository grants',
  )
})

test('the API the scan gate reads through is on, not merely reachable by accident', async () => {
  /*
   * The permission above buys the read; this buys the endpoint. Enabled
   * explicitly rather than left to Artifact Registry, which turns Container
   * Analysis on as a side effect — a dependency that holds until it does not,
   * and the failure then is a publish that pushed and could not finish.
   *
   * What writes the findings it reads is Artifact Analysis, and that is off on
   * purpose (it bills per image), so the gate currently blocks on nothing.
   */
  const gcloud = recorder()
  await invoke(gcloud.run)

  const enabled = gcloud.applied('services enable')[0] ?? []
  assert.ok(
    enabled.some((argument: string) => argument === 'containeranalysis.googleapis.com'),
    'the scan gate reads through an API nothing turned on',
  )
})

test('a policy write that lost the read-modify-write race is retried, not reported', async () => {
  /*
   * What a real run answered on the first project-level grant:
   *
   *   Resource in projects [...:setIamPolicy] is the subject of a conflict:
   *   There were concurrent policy changes. Please retry the whole
   *   read-modify-write with exponential backoff.
   *
   * It killed the bootstrap with the deployer created and not one of its
   * roles attached. The project is shared with the other BoxLite apps, so
   * another writer between this run's read and its write is the ordinary case
   * rather than bad luck — and the message says what to do about it.
   *
   * `add-iam-policy-binding` is itself the whole read-modify-write, so the
   * retry is the same command again. Asserted through `bootstrapGcp` rather
   * than on a helper: what matters is that the run completes.
   */
  const gcloud = recorder({ etagConflicts: 3 })
  const result = await invoke(gcloud.run)

  assert.ok(result.deployerEmail.startsWith('bl-app-gcp-dev-deploy@'))
  const grants = gcloud.applied('projects add-iam-policy-binding', 'bl-app-gcp-dev-deploy@')
  const roles = new Set(
    grants.map((argv: string[]) => argv.find((arg) => arg.startsWith('--role='))?.slice('--role='.length)),
  )
  assert.equal(roles.size, 20, 'every role has to land, whichever attempt lands it')
  // Three conflicts, three retries: the attempts exceed the roles by exactly
  // what was refused, so nothing was skipped and nothing retried blindly.
  assert.equal(grants.length, roles.size + 3, `attempts: ${grants.length}`)
})

test('a conflict that never clears is reported with what gcloud said', async () => {
  // Finite, like the visibility budget. A project whose policy is rewritten
  // continuously is not something a longer loop fixes, and the refusal has to
  // name the role it was attaching.
  const gcloud = recorder({ etagConflicts: 99 })
  await assert.rejects(() => invoke(gcloud.run), /Could not grant \S+ to bl-app-gcp-dev-deploy@/)
  await assert.rejects(() => invoke(gcloud.run), /concurrent policy changes/i)
})

test('an account that never becomes visible is reported rather than waited on forever', async () => {
  // The budget is finite: the grant below reports its own refusal, which names
  // the role it was attaching and says more than a timeout here would.
  const gcloud = recorder({ readsBeforeVisible: 99 })
  await assert.rejects(() => invoke(gcloud.run), /Could not grant \S+ to bl-app-gcp-dev-deploy@/)
})

test('neither secret reaches the process table', async () => {
  const gcloud = recorder()
  await invoke(gcloud.run)
  for (const call of gcloud.applied('secrets create')) {
    assert.ok(call.includes('--data-file=-'), `a secret was not fed through stdin: ${call.join(' ')}`)
  }
  assert.equal(gcloud.stdin.length, 2, 'expected the bootstrap record and the passphrase')
  const passphrase = gcloud.stdin.find((value) => !value.startsWith('{'))
  assert.ok(passphrase, 'no passphrase was written')
  assert.equal(Buffer.from(passphrase, 'base64').length, 32)
})

test('the state bucket never reaches the log', async () => {
  const gcloud = recorder()
  const lines: string[] = []
  await bootstrapGcp({
    run: gcloud.run,
    project: 'boxlite-gcp-dev',
    region: 'asia-southeast1',
    app: 'boxlite',
    appShort: 'bl-app',
    stage: 'gcp-dev',
    repository: 'boxlite-app-gcp-dev',
    immutableTags: true,
    github: GITHUB,
    log: (line) => lines.push(line),
  })
  const created = gcloud.applied('storage buckets create')[0]!
  const bucket = created.find((argument) => argument.startsWith('gs://'))!.replace('gs://', '')
  assert.match(bucket, /^mstage-state-[0-9a-f]{16}$/, 'the bucket name is guessable')
  assert.ok(!lines.some((line) => line.includes(bucket)), 'the state bucket name was logged')
})

test('the identity provider pins the repository, and never the audience', () => {
  const condition = attributeCondition(GITHUB)
  assert.match(condition, /repository_owner_id == '123456'/)
  assert.match(condition, /repository_id == '789012'/)
  assert.doesNotMatch(condition, /repository ==/, 'the condition pins a mutable name')
})

const invokeWith = (run: Run) =>
  bootstrapGcp({
    run,
    project: 'boxlite-gcp-dev',
    region: 'asia-southeast1',
    app: 'boxlite',
    appShort: 'bl-app',
    stage: 'gcp-dev',
    repository: 'boxlite-app-gcp-dev',
    immutableTags: true,
    github: GITHUB,
    log: () => {},
  })

test('a project described with no number stops the run before anything is created', async () => {
  /*
   * A guard rather than a diagnosis, and the message says so instead of naming
   * a cause. Every route that was worth suspecting exits non-zero and is caught
   * one branch up — `projects describe` given a project's display name answers
   * `INVALID_ARGUMENT`, not an empty number. What is left is a success with
   * nothing in it, which nothing here can explain and every principalSet below
   * would be built from.
   *
   * The command is asserted along with the refusal. A message that can name no
   * cause has to hand over something to run, or the only way forward is to read
   * this file.
   */
  await assert.rejects(
    () => invokeWith(async () => ({ code: 0, stdout: '', stderr: '' })),
    (error: Error) => {
      assert.ok(error instanceof GcpBootstrapError)
      assert.match(error.message, /printed no project number/, 'what happened')
      assert.match(error.message, /gcloud projects describe boxlite-gcp-dev --format='value\(projectNumber\)'/, 'what to run')
      return true
    },
  )
})

test('a read that failed carries gcloud’s own words, not a guess about why', async () => {
  /*
   * The reason this is asserted rather than left to the message that reads best:
   * every call here carries `--quiet`, so a session needing reauth cannot
   * prompt and gcloud exits non-zero with `Reauthentication failed. cannot
   * prompt during non-interactive execution`. Swallowing that reported it as
   * "check that the project exists", which is the wrong place to look — and
   * `bootstrap.ts`'s `requireGhAuthenticated` keeps gh's stderr for exactly the
   * same reason.
   */
  const reauth = 'ERROR: (gcloud.projects.describe) There was a problem refreshing your current auth tokens'
  await assert.rejects(
    () => invokeWith(async () => ({ code: 1, stdout: '', stderr: reauth })),
    (error: Error) => {
      assert.ok(error instanceof GcpBootstrapError)
      assert.match(error.message, /reading the number of project boxlite-gcp-dev/, 'which read failed')
      assert.match(error.message, /problem refreshing your current auth tokens/, 'and what gcloud said about it')
      return true
    },
  )
})

test('a failing gcloud call stops the run and carries the reason', async () => {
  const run: Run = async (_command, args): Promise<RunResult> => {
    if (args.join(' ').startsWith('projects describe')) return { code: 0, stdout: '999999999999', stderr: '' }
    if (args.join(' ').startsWith('services list')) return { code: 0, stdout: '', stderr: '' }
    return { code: 1, stdout: '', stderr: 'PERMISSION_DENIED: caller lacks serviceusage.services.enable' }
  }
  await assert.rejects(
    () => invoke(run),
    (error: Error) => error instanceof GcpBootstrapError && /PERMISSION_DENIED/.test(error.message),
  )
})

/*
 * The grants a promotion needs, made in the project that has to admit them.
 *
 * One session does the whole move — the destination's, because that is the one
 * that writes — so the accounts reading the source belong to the stage being
 * bootstrapped while the policies admitting them belong to the source. Neither
 * end can make the grant alone, and the destination is the end that knows both
 * account names because it just created them.
 */
test('a stage promoted into lets both of its accounts read the source', async () => {
  const gcloud = recorder()
  await invoke(gcloud.run, { promotionSource: SOURCE })

  assert.deepEqual(
    projectsTouched(gcloud.calls),
    ['boxlite-gcp-dev', 'boxlite-gcp-src'],
    'the source project is the one place a bootstrap reaches outside its own',
  )

  /*
   * Two accounts, not one, and that asymmetry is the bug this was written for:
   * `mbuild.yml` federates `GCP_IMAGE_PUBLISHER` while `mdeploy-all.yml` federates
   * `GCP_DEPLOYER`, so granting the deployer both would leave the image leg
   * failing on `artifactregistry.repositories.get` while the runner leg passed.
   */
  const registry = gcloud.applied('projects add-iam-policy-binding', 'boxlite-gcp-src')
  assert.equal(registry.length, 1, 'the registry grant is made once, on the source project')
  assert.ok(
    registry[0]!.includes('--member=serviceAccount:[email protected]'),
    'the account mbuild.yml federates cannot pull the source images',
  )
  assert.ok(registry[0]!.includes('--role=roles/artifactregistry.reader'), 'the registry grant is not a read')

  const bucket = gcloud.applied('storage buckets add-iam-policy-binding')
  assert.equal(bucket.length, 1, 'the bucket grant is made once')
  assert.ok(bucket[0]!.includes(`gs://${SOURCE.bucket}`), 'the grant reaches a bucket that is not the source')
  assert.ok(
    bucket[0]!.includes('--member=serviceAccount:[email protected]'),
    'the account mdeploy-all.yml federates cannot read the staged binary',
  )
  /*
   * Object reads, and the bucket rather than the project. `runner:promote`
   * lists the prefix and copies what is under it and asks the bucket itself
   * nothing, so nothing here needs `storage.buckets.get` — which is in no
   * object role, and whose absence is what a wider-looking role would hide.
   */
  assert.ok(bucket[0]!.includes('--role=roles/storage.objectViewer'), 'the bucket grant is wider than the reads it serves')
})

/*
 * The refusal that made this grant a no-op for a whole promotion.
 *
 * A source stage that stages its runner binary rather than installing a release
 * holds a condition on the very bucket a promotion reads from — the deploy
 * attaches `runner-artifacts-only` to it so a runner host reads the staged
 * binary and nothing else of that bucket — and `add-iam-policy-binding` will
 * not add an unconditioned binding to such a policy unless the command says
 * that is what it means. Refused between reading that policy and writing it
 * back, so the bucket keeps the policy it had and the admin-activity log a made
 * grant would appear in stays empty — and the promotion fails days later at
 * `storage.objects.get`.
 */
test('a source bucket whose policy already holds a condition still takes the grant', async () => {
  const gcloud = recorder({ conditioned: [`gs://${SOURCE.bucket}`] })
  const lines: string[] = []
  await invoke(gcloud.run, { promotionSource: SOURCE, log: (line) => lines.push(line) })
  assert.match(lines.join('\n'), /both grants applied/, 'the bucket grant never reached the source')
})

/*
 * The same rule one policy earlier.
 *
 * Service-account policies carry no conditions today, so this site cannot fail
 * against a real project yet — which is the reason to pin it rather than wait:
 * the binding that decides who may act as the deployer is a poor place to
 * discover that someone added a condition upstream.
 */
test('a deployer whose policy already holds a condition still takes its impersonation binding', async () => {
  const deployer = '[email protected]'
  const gcloud = recorder({ conditioned: [deployer] })
  const lines: string[] = []
  await invoke(gcloud.run, { log: (line) => lines.push(line) })
  /*
   * The line `bootstrapGcp` prints once the grant returns, rather than the call
   * having been made: the refusal happens after the argv is composed, so a
   * recorded call proves only that the attempt was spelled, not that it landed.
   * Refused, this run throws out of `allowImpersonation` before printing it.
   */
  assert.match(
    lines.join('\n'),
    /environment gcp-dev may act as it/,
    'the binding that lets the stage environment act as the deployer never landed',
  )
})

test('a stage with no source reaches no project but its own', async () => {
  const gcloud = recorder()
  await invoke(gcloud.run)
  assert.deepEqual(projectsTouched(gcloud.calls), ['boxlite-gcp-dev'])
})

test('a source that refuses the grant is reported with the command, not thrown', async () => {
  /*
   * An operator who administers this stage and not the source is ordinary —
   * the two projects need not have the same administrators — and everything
   * above this step has already happened. Throwing would discard a bootstrap
   * that otherwise completed and leave the GitHub variables unwritten, so the
   * refusal is carried out as the two commands and whoever holds that project
   * runs them.
   */
  const gcloud = recorder()
  const lines: string[] = []
  const denied: Run = async (command, args, options) => {
    const asked = args.join(' ')
    if (asked.includes('add-iam-policy-binding') && asked.includes('boxlite-gcp-src')) {
      return { code: 1, stdout: '', stderr: 'PERMISSION_DENIED: caller lacks resourcemanager.projects.setIamPolicy' }
    }
    return gcloud.run(command, args, options)
  }

  const result = await invoke(denied, { promotionSource: SOURCE, log: (line) => lines.push(line) })
  assert.equal(
    result.publisherEmail,
    '[email protected]',
    'a bootstrap that completed must not be thrown away over a project it does not own',
  )
  const printed = lines.join('\n')
  assert.match(printed, /gcloud projects add-iam-policy-binding boxlite-gcp-src/, 'the registry grant to run by hand')
  /*
   * With `--condition=None`, which is what makes it a command rather than a
   * shape: without it an operator pasting this is prompted for a condition, and
   * a non-interactive rerun is refused by the same rule that sent it here.
   */
  assert.match(
    printed,
    /gcloud storage buckets add-iam-policy-binding gs:\/\/boxlite-gcp-src-artifacts\S+ [^\n]*--condition=None/,
    'and the bucket one, runnable as printed',
  )
  assert.match(printed, /PERMISSION_DENIED/, 'why it could not be made here')
})

/*
 * The name is resolved against a whole file, which is the only place it can be.
 *
 * `mstage/config` deliberately lets a `promoteFrom` naming an absent stage
 * through, because a CI job restores one declaration and not the file. That
 * makes this the only check standing between a typo and a bootstrap that
 * granted nothing — found when prod promotes, months later.
 */
test('a promoteFrom that resolves to nothing is refused here, where the whole file is readable', () => {
  const config = {
    app: 'boxlite',
    path: '/repo/.mstage.config.json',
    stages: {
      dev2: { project: 'boxlite-gcp-src' },
      prod2: { project: 'boxlite-gcp-dev', promoteFrom: 'dev-2' },
    },
  }
  assert.throws(
    () => promotionSourceFor({ config, stage: 'prod2' }),
    /promotes from "dev-2" in \/repo\/\.mstage\.config\.json, which declares no such stage/,
  )

  assert.deepEqual(promotionSourceFor({ config: { ...config, stages: { ...config.stages, prod2: { project: 'boxlite-gcp-dev', promoteFrom: 'dev2' } } }, stage: 'prod2' }), {
    stage: 'dev2',
    project: 'boxlite-gcp-src',
    // Composed by the rule `mdeploy/stack/runner-binary.ts` resolves addresses
    // from, so the grant reaches the bucket `runner:promote` actually reads.
    bucket: 'boxlite-dev2-artifacts-boxlite-gcp-src',
  })

  // Two stages in one project cross no boundary, and a binding saying so would
  // read as one that is not there.
  assert.equal(
    promotionSourceFor({
      config: { ...config, stages: { dev2: { project: 'p' }, prod2: { project: 'p', promoteFrom: 'dev2' } } },
      stage: 'prod2',
    }),
    undefined,
  )
  assert.equal(promotionSourceFor({ config, stage: 'dev2' }), undefined, 'a stage nothing promotes into')
})