/** * Shared pieces of the live-check scripts: the AWS CLI (independent of the * ts-cloud code under test), the guard, the ledger and the resource queries * the sweep and the ledger scan share. * * Credentials are never read, printed or written here. The AWS CLI resolves * them from the `stacks` profile; the one secret this suite handles (the job * writer's access key) is created in run.ts, kept in memory and handed to the * job launcher through its environment. */ import { appendFileSync, existsSync, readFileSync } from 'node:fs' export const REGION = 'us-east-1' export const TAG_KEY = 'ts-cloud-livecheck' export const REQUIRED_PROFILE = 'stacks' /** Refuse to touch AWS unless the run is pinned to the approved profile and region. */ export function guard(): void { if (process.env.AWS_PROFILE !== REQUIRED_PROFILE) throw new Error(`Refusing to run: AWS_PROFILE must be ${REQUIRED_PROFILE} (got ${JSON.stringify(process.env.AWS_PROFILE ?? '')})`) for (const name of ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN']) { if (process.env[name]) throw new Error(`Refusing to run: ${name} is set (from the environment, or a .env file Bun loaded: run with \`bun --no-env-file\`); the ${REQUIRED_PROFILE} profile must be what authenticates`) } process.env.AWS_REGION = REGION process.env.AWS_DEFAULT_REGION = REGION } export class AwsError extends Error { constructor(message: string, readonly code: string) { super(message) } } /** Run the AWS CLI and parse its JSON. Throws AwsError with the service's error code. */ export function aws(args: string[], options: { region?: string, allowEmpty?: boolean } = {}): any { const result = Bun.spawnSync(['aws', ...args, '--output', 'json', '--region', options.region ?? REGION, '--no-cli-pager'], { env: { ...process.env, AWS_PROFILE: REQUIRED_PROFILE, AWS_PAGER: '' }, stdout: 'pipe', stderr: 'pipe', }) if (result.exitCode !== 0) { const stderr = result.stderr.toString().trim() const code = stderr.match(/\(([A-Za-z.]+)\)/)?.[1] ?? 'Unknown' throw new AwsError(`aws ${args.slice(0, 2).join(' ')} failed: ${stderr.slice(0, 400)}`, code) } const out = result.stdout.toString().trim() if (!out) return options.allowEmpty === false ? null : {} return JSON.parse(out) } /** Not-found errors, which teardown treats as already done. */ export function isGone(error: unknown): boolean { const code = error instanceof AwsError ? error.code : '' const text = error instanceof Error ? error.message : String(error) return /NotFound|NoSuchEntity|NoSuchBucket|InvalidGroup\.NotFound|InvalidKeyPair\.NotFound|InvalidAllocationID\.NotFound|InvalidVolume\.NotFound|InvalidSnapshot\.NotFound|InvalidInstanceID\.NotFound|ResourceNotFound|does not exist/i.test(`${code} ${text}`) } export type ResourceType = | 'instance' | 'volume' | 'snapshot' | 'ami' | 'eip' | 'eni' | 'security-group' | 'key-pair' | 'dlm-policy' | 'iam-role' | 'iam-instance-profile' | 'iam-user' | 'iam-access-key' | 's3-bucket' | 'alarm' | 'sns-topic' | 'ssm-parameter' | 'cfn-stack' export interface LedgerEntry { type: ResourceType id: string region: string /** For an access key: its user. */ owner?: string note?: string createdAt: string } export class Ledger { private readonly seen = new Set() constructor(readonly path: string) { for (const entry of readLedger(path)) this.seen.add(`${entry.type}:${entry.id}`) } /** Append an entry once; returns whether it was new. */ add(type: ResourceType, id: string, extra: Partial> = {}): boolean { const key = `${type}:${id}` if (!id || this.seen.has(key)) return false this.seen.add(key) const entry: LedgerEntry = { type, id, region: extra.region ?? REGION, owner: extra.owner, note: extra.note, createdAt: new Date().toISOString() } // Start on a fresh line even if the file does not end with one. const sep = existsSync(this.path) && !readFileSync(this.path, 'utf8').endsWith('\n') && readFileSync(this.path, 'utf8').length > 0 ? '\n' : '' appendFileSync(this.path, `${sep}${JSON.stringify(entry)}\n`) return true } } export function readLedger(path: string): LedgerEntry[] { if (!existsSync(path)) return [] return readFileSync(path, 'utf8').split('\n').filter(Boolean).map(line => JSON.parse(line) as LedgerEntry) } type Tag = { Key?: string, Value?: string } export const tagValue = (tags: Tag[] | undefined, key: string): string | undefined => tags?.find(tag => tag.Key === key)?.Value export const hasRunTag = (tags: Tag[] | undefined, runId: string): boolean => tagValue(tags, TAG_KEY) === runId export interface Found { type: ResourceType id: string detail: string /** Carries the run tag (the ledger scan only records these). */ tagged: boolean owner?: string } const ec2Filters = (runId: string, project: string): string[][] => [ ['--filters', `Name=tag:${TAG_KEY},Values=${runId}`], ['--filters', `Name=tag:Project,Values=${project}`], ['--filters', `Name=tag:Name,Values=*${project}*`], ] /** * Every resource in the region matching the run tag or named after the * project, across the types the live check can create. Read-only. */ export function findResources(runId: string, project: string): Found[] { const found = new Map() const put = (item: Found): void => { found.set(`${item.type}:${item.id}`, item) } const named = (value: string | undefined): boolean => !!value && value.includes(project) for (const filter of ec2Filters(runId, project)) { for (const reservation of aws(['ec2', 'describe-instances', ...filter]).Reservations ?? []) { for (const instance of reservation.Instances ?? []) { if (instance.State?.Name === 'terminated') continue put({ type: 'instance', id: instance.InstanceId, detail: `${instance.State?.Name} ${tagValue(instance.Tags, 'Name') ?? ''}`, tagged: hasRunTag(instance.Tags, runId) }) } } for (const volume of aws(['ec2', 'describe-volumes', ...filter]).Volumes ?? []) put({ type: 'volume', id: volume.VolumeId, detail: `${volume.State} ${tagValue(volume.Tags, 'Name') ?? ''}`, tagged: hasRunTag(volume.Tags, runId) }) for (const snapshot of aws(['ec2', 'describe-snapshots', '--owner-ids', 'self', ...filter]).Snapshots ?? []) put({ type: 'snapshot', id: snapshot.SnapshotId, detail: `${snapshot.State} of ${snapshot.VolumeId}`, tagged: hasRunTag(snapshot.Tags, runId) }) for (const image of aws(['ec2', 'describe-images', '--owners', 'self', ...filter]).Images ?? []) put({ type: 'ami', id: image.ImageId, detail: image.Name ?? '', tagged: hasRunTag(image.Tags, runId) }) for (const address of aws(['ec2', 'describe-addresses', ...filter]).Addresses ?? []) put({ type: 'eip', id: address.AllocationId, detail: `${address.PublicIp} on ${address.InstanceId ?? 'nothing'}`, tagged: hasRunTag(address.Tags, runId) }) for (const group of aws(['ec2', 'describe-security-groups', ...filter]).SecurityGroups ?? []) put({ type: 'security-group', id: group.GroupId, detail: group.GroupName ?? '', tagged: hasRunTag(group.Tags, runId) }) for (const pair of aws(['ec2', 'describe-key-pairs', ...filter]).KeyPairs ?? []) put({ type: 'key-pair', id: pair.KeyName, detail: pair.KeyPairId ?? '', tagged: hasRunTag(pair.Tags, runId) }) } // Names the tag filters cannot see. for (const group of aws(['ec2', 'describe-security-groups', '--filters', `Name=group-name,Values=*${project}*`]).SecurityGroups ?? []) put({ type: 'security-group', id: group.GroupId, detail: group.GroupName ?? '', tagged: hasRunTag(group.Tags, runId) }) for (const pair of aws(['ec2', 'describe-key-pairs', '--filters', `Name=key-name,Values=*${project}*`]).KeyPairs ?? []) put({ type: 'key-pair', id: pair.KeyName, detail: pair.KeyPairId ?? '', tagged: hasRunTag(pair.Tags, runId) }) for (const image of aws(['ec2', 'describe-images', '--owners', 'self', '--filters', `Name=name,Values=*${project}*`]).Images ?? []) put({ type: 'ami', id: image.ImageId, detail: image.Name ?? '', tagged: hasRunTag(image.Tags, runId) }) // ENIs are created by instances and carry no tags of ours: find them by the // project's security groups, by tag, or by an attachment to a found instance. const groups = [...found.values()].filter(item => item.type === 'security-group').map(item => item.id) const instances = [...found.values()].filter(item => item.type === 'instance').map(item => item.id) const eniQueries = [ ...groups.map(id => ['--filters', `Name=group-id,Values=${id}`]), ...instances.map(id => ['--filters', `Name=attachment.instance-id,Values=${id}`]), ['--filters', `Name=tag:${TAG_KEY},Values=${runId}`], ] for (const query of eniQueries) { for (const eni of aws(['ec2', 'describe-network-interfaces', ...query]).NetworkInterfaces ?? []) put({ type: 'eni', id: eni.NetworkInterfaceId, detail: `${eni.Status} ${eni.Attachment?.InstanceId ?? ''}`, tagged: hasRunTag(eni.TagSet, runId) }) } for (const policy of aws(['dlm', 'get-lifecycle-policies']).Policies ?? []) { const tags = Object.entries(policy.Tags ?? {}).map(([Key, Value]) => ({ Key, Value: String(Value) })) if (hasRunTag(tags, runId) || tagValue(tags, 'Project') === project || named(policy.Description)) put({ type: 'dlm-policy', id: policy.PolicyId, detail: `${policy.State} ${policy.Description ?? ''}`, tagged: hasRunTag(tags, runId) }) } const roleTags = (name: string): Tag[] => aws(['iam', 'list-role-tags', '--role-name', name]).Tags ?? [] for (const role of aws(['iam', 'list-roles']).Roles ?? []) { const candidate = named(role.RoleName) || role.RoleName === 'AWSDataLifecycleManagerDefaultRole' if (!candidate) continue const tags = roleTags(role.RoleName) if (named(role.RoleName) || hasRunTag(tags, runId)) put({ type: 'iam-role', id: role.RoleName, detail: role.Arn, tagged: hasRunTag(tags, runId) }) } for (const profile of aws(['iam', 'list-instance-profiles']).InstanceProfiles ?? []) { if (!named(profile.InstanceProfileName)) continue const tags = aws(['iam', 'list-instance-profile-tags', '--instance-profile-name', profile.InstanceProfileName]).Tags ?? [] put({ type: 'iam-instance-profile', id: profile.InstanceProfileName, detail: (profile.Roles ?? []).map((r: any) => r.RoleName).join(','), tagged: hasRunTag(tags, runId) }) } for (const user of aws(['iam', 'list-users']).Users ?? []) { if (!named(user.UserName)) continue const tags = aws(['iam', 'list-user-tags', '--user-name', user.UserName]).Tags ?? [] put({ type: 'iam-user', id: user.UserName, detail: user.Arn, tagged: hasRunTag(tags, runId) }) for (const key of aws(['iam', 'list-access-keys', '--user-name', user.UserName]).AccessKeyMetadata ?? []) put({ type: 'iam-access-key', id: key.AccessKeyId, owner: user.UserName, detail: `${key.Status} for ${user.UserName}`, tagged: hasRunTag(tags, runId) }) } for (const bucket of aws(['s3api', 'list-buckets']).Buckets ?? []) { if (!named(bucket.Name)) continue let tags: Tag[] = [] try { tags = aws(['s3api', 'get-bucket-tagging', '--bucket', bucket.Name]).TagSet ?? [] } catch {} put({ type: 's3-bucket', id: bucket.Name, detail: bucket.CreationDate ?? '', tagged: hasRunTag(tags, runId) }) } for (const alarm of aws(['cloudwatch', 'describe-alarms', '--alarm-name-prefix', project]).MetricAlarms ?? []) put({ type: 'alarm', id: alarm.AlarmName, detail: alarm.StateValue ?? '', tagged: false }) for (const topic of aws(['sns', 'list-topics']).Topics ?? []) { if (named(topic.TopicArn)) put({ type: 'sns-topic', id: topic.TopicArn, detail: '', tagged: false }) } for (const parameter of aws(['ssm', 'describe-parameters', '--parameter-filters', `Key=Name,Option=Contains,Values=${project}`]).Parameters ?? []) put({ type: 'ssm-parameter', id: parameter.Name, detail: parameter.Type ?? '', tagged: false }) for (const stack of aws(['cloudformation', 'list-stacks']).StackSummaries ?? []) { if (stack.StackStatus !== 'DELETE_COMPLETE' && named(stack.StackName)) put({ type: 'cfn-stack', id: stack.StackName, detail: stack.StackStatus, tagged: false }) } return [...found.values()] } /** Record every run-tagged resource not yet in the ledger (and the ENIs of our instances). */ export function scanIntoLedger(ledger: Ledger, runId: string, project: string): number { let added = 0 for (const item of findResources(runId, project)) { // Alarms, topics, parameters and stacks carry no tag we can list by; they // are project-named, and the project name is unique to this run's date. const ours = item.tagged || ['alarm', 'sns-topic', 'ssm-parameter', 'cfn-stack', 'eni'].includes(item.type) if (ours && ledger.add(item.type, item.id, { owner: item.owner, note: item.detail })) added++ } return added } export const sleep = (ms: number): Promise => new Promise(resolve => setTimeout(resolve, ms))