/** * The live-check tools against a fake `aws` on PATH: guards, the sweep's exit * codes, and teardown deleting only ledger entries that carry the run tag, * idempotently. No AWS call is made. */ import { describe, expect, it, setDefaultTimeout } from 'bun:test' import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' // Each case starts Bun and dozens of fake-CLI (Python) processes: one per AWS query. setDefaultTimeout(60_000) const here = import.meta.dir const RUN = 'lc-test1' const PROJECT = 'tscloud-livecheck-20261202' /** * A fake AWS CLI: answers from `world.json`, records every call in `calls`, * and removes what a delete names so a second teardown finds it gone. */ const FAKE = `#!/usr/bin/env python3 import json, os, sys root = os.environ['FAKE_AWS_ROOT'] args = [a for a in sys.argv[1:]] with open(os.path.join(root, 'calls'), 'a') as out: out.write(' '.join(args[:6]) + '\\n') world = json.load(open(os.path.join(root, 'world.json'))) def save(): json.dump(world, open(os.path.join(root, 'world.json'), 'w')) def arg(name): return args[args.index(name) + 1] if name in args else None def gone(kind): sys.stderr.write('An error occurred (%s) when calling: not found\\n' % kind); sys.exit(254) service, op = args[0], args[1] tag = lambda key, value: {'Key': key, 'Value': value} if (service, op) == ('ec2', 'describe-instances'): ids = [arg('--instance-ids')] if arg('--instance-ids') else None found = [i for i in world['instances'] if ids is None or i['InstanceId'] in ids] if ids and not found: gone('InvalidInstanceID.NotFound') if ids is None: found = [i for i in found if any(t['Key'] == 'ts-cloud-livecheck' for t in i['Tags']) and any(f.endswith('=' + t['Value']) for f in args for t in i['Tags'])] print(json.dumps({'Reservations': [{'Instances': found}]})) elif (service, op) == ('ec2', 'terminate-instances'): for i in world['instances']: if i['InstanceId'] == arg('--instance-ids'): i['State'] = {'Name': 'terminated'} save(); print('{}') elif (service, op) == ('ec2', 'describe-key-pairs'): name = arg('--key-names') found = [k for k in world['keys'] if name is None or k['KeyName'] == name] if name and not found: gone('InvalidKeyPair.NotFound') print(json.dumps({'KeyPairs': found if name else []})) elif (service, op) == ('ec2', 'delete-key-pair'): world['keys'] = [k for k in world['keys'] if k['KeyName'] != arg('--key-name')]; save(); print('{}') elif service in ('ec2', 'dlm', 'iam', 's3api', 'cloudwatch', 'sns', 'ssm', 'cloudformation', 'sts'): empty = {'describe-volumes': {'Volumes': []}, 'describe-snapshots': {'Snapshots': []}, 'describe-images': {'Images': []}, 'describe-addresses': {'Addresses': []}, 'describe-security-groups': {'SecurityGroups': []}, 'describe-network-interfaces': {'NetworkInterfaces': []}, 'get-lifecycle-policies': {'Policies': []}, 'list-roles': {'Roles': []}, 'list-instance-profiles': {'InstanceProfiles': []}, 'list-users': {'Users': []}, 'list-buckets': {'Buckets': []}, 'describe-alarms': {'MetricAlarms': []}, 'list-topics': {'Topics': []}, 'describe-parameters': {'Parameters': []}, 'list-stacks': {'StackSummaries': []}} print(json.dumps(empty.get(op, {}))) else: sys.exit(2) ` function fixture(world: Record, ledger: object[]) { const root = mkdtempSync(join(tmpdir(), 'livecheck-fake-')) const bin = join(root, 'bin') mkdirSync(bin) writeFileSync(join(bin, 'aws'), FAKE) chmodSync(join(bin, 'aws'), 0o755) writeFileSync(join(root, 'world.json'), JSON.stringify(world)) writeFileSync(join(root, 'ledger.jsonl'), ledger.map(entry => JSON.stringify(entry)).join('\n')) const run = (script: string, args: string[], profile = 'stacks') => { const result = Bun.spawnSync(['bun', '--no-env-file', join(here, script), ...args], { env: { PATH: `${bin}:${process.env.PATH}`, HOME: root, FAKE_AWS_ROOT: root, ...(profile ? { AWS_PROFILE: profile } : {}) }, stdout: 'pipe', stderr: 'pipe', }) return { code: result.exitCode, out: `${result.stdout}${result.stderr}` } } return { root, run, calls: () => readFileSync(join(root, 'calls'), 'utf8').trim().split('\n'), world: () => JSON.parse(readFileSync(join(root, 'world.json'), 'utf8')), cleanup: () => rmSync(root, { recursive: true, force: true }), } } const runTag = [{ Key: 'ts-cloud-livecheck', Value: RUN }, { Key: 'Project', Value: PROJECT }] const entry = (type: string, id: string) => ({ type, id, region: 'us-east-1', createdAt: '2026-12-02T00:00:00Z' }) describe('livecheck guards', () => { it('refuse to touch AWS without the stacks profile', () => { const f = fixture({ instances: [], keys: [] }, []) try { expect(f.run('sweep.ts', [RUN, PROJECT], 'default').code).toBe(2) expect(f.run('teardown.ts', [join(f.root, 'ledger.jsonl'), '--run', RUN, '--project', PROJECT], 'default').code).not.toBe(0) expect(f.run('run.ts', ['setup', '--run', RUN, '--project', PROJECT, '--ledger', join(f.root, 'l.jsonl')], 'default').code).not.toBe(0) } finally { f.cleanup() } }) }) describe('sweep', () => { it('exits 0 only when nothing is found', () => { const empty = fixture({ instances: [], keys: [] }, []) try { expect(empty.run('sweep.ts', [RUN, PROJECT])).toMatchObject({ code: 0 }) } finally { empty.cleanup() } const left = fixture({ instances: [{ InstanceId: 'i-left', State: { Name: 'running' }, Tags: runTag }], keys: [] }, []) try { const result = left.run('sweep.ts', [RUN, PROJECT]) expect(result.code).toBe(1) expect(result.out).toContain('i-left') } finally { left.cleanup() } }) }) describe('teardown', () => { it('deletes ledger entries carrying the run tag, refuses the rest, and is idempotent', () => { const f = fixture({ instances: [ { InstanceId: 'i-ours', State: { Name: 'running' }, Tags: runTag }, { InstanceId: 'i-foreign', State: { Name: 'running' }, Tags: [{ Key: 'Project', Value: 'someone-else' }] }, { InstanceId: 'i-unlisted', State: { Name: 'running' }, Tags: runTag }, ], keys: [{ KeyName: 'k-ours', Tags: runTag }, { KeyName: 'k-other-run', Tags: [{ Key: 'ts-cloud-livecheck', Value: 'lc-other' }] }], }, [entry('instance', 'i-ours'), entry('instance', 'i-foreign'), entry('key-pair', 'k-ours'), entry('key-pair', 'k-other-run')]) try { const args = [join(f.root, 'ledger.jsonl'), '--run', RUN, '--project', PROJECT] const first = f.run('teardown.ts', args) expect(first.code).toBe(0) expect(first.out).toContain('terminate instance i-ours') expect(first.out).toContain('instance i-foreign: no ts-cloud-livecheck=lc-test1 tag') expect(first.out).toContain('key-pair k-other-run: no ts-cloud-livecheck=lc-test1 tag') const world = f.world() expect(world.instances.find((i: any) => i.InstanceId === 'i-ours').State.Name).toBe('terminated') // Not in the ledger, so untouched although it carries the tag. expect(world.instances.find((i: any) => i.InstanceId === 'i-unlisted').State.Name).toBe('running') expect(world.instances.find((i: any) => i.InstanceId === 'i-foreign').State.Name).toBe('running') expect(world.keys.map((k: any) => k.KeyName)).toEqual(['k-other-run']) const second = f.run('teardown.ts', args) expect(second.code).toBe(0) expect(second.out).toContain('already gone: instance i-ours') expect(second.out).toContain('already gone: key-pair k-ours') } finally { f.cleanup() } }, 60_000) })