diff --git a/lambdas/functions/termination-watcher/src/deregister.test.ts b/lambdas/functions/termination-watcher/src/deregister.test.ts index 3fbf1c767..92ebbef0f 100644 --- a/lambdas/functions/termination-watcher/src/deregister.test.ts +++ b/lambdas/functions/termination-watcher/src/deregister.test.ts @@ -1,7 +1,7 @@ import { request } from '@octokit/request'; import { Instance } from '@aws-sdk/client-ec2'; import { createCommonStorage, type GitHubAppCredentialsStore } from '@aws-github-runner/storage-providers'; -import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { deregisterRunner, handleDeregisterRetry, createThrottleOptions, resetAppCredentialsCache } from './deregister'; import { Config } from './ConfigResolver'; import type { EndpointDefaults } from '@octokit/types'; @@ -19,11 +19,23 @@ vi.mock('@octokit/auth-app', () => ({ createAppAuth: (...args: unknown[]) => mockCreateAppAuth(...args), })); +const mockSqsSend = vi.hoisted(() => vi.fn()); +vi.mock('@aws-sdk/client-sqs', () => ({ + SQSClient: class { + send = mockSqsSend; + }, + SendMessageCommand: class { + constructor(public input: unknown) {} + }, +})); + const mockPaginate = { iterator: vi.fn(), }; const mockActions = { + getSelfHostedRunnerForOrg: vi.fn(), + getSelfHostedRunnerForRepo: vi.fn(), listSelfHostedRunnersForOrg: vi.fn(), listSelfHostedRunnersForRepo: vi.fn(), deleteSelfHostedRunnerFromOrg: vi.fn(), @@ -378,6 +390,100 @@ describe('deregisterRunner', () => { }); }); +describe('deregisterRunner exact-name lookup (ghr:runner_name_prefix present)', () => { + const prefixedOrgInstance: Instance = { + ...orgInstance, + Tags: [...(orgInstance.Tags ?? []), { Key: 'ghr:runner_name_prefix', Value: 'runners-x64_' }], + }; + const prefixedRepoInstance: Instance = { + ...repoInstance, + Tags: [...(repoInstance.Tags ?? []), { Key: 'ghr:runner_name_prefix', Value: 'repo-runner-' }], + }; + + beforeEach(() => { + vi.clearAllMocks(); + resetAppCredentialsCache(); + mockedCreateCommonStorage.mockReturnValue({ githubAppCredentials: credentialsStore }); + setupAuthMocks(); + }); + + it('should look up an org runner by exact name with a single request and delete it', async () => { + mockApps.getOrgInstallation.mockResolvedValue({ data: { id: 999 } }); + mockActions.listSelfHostedRunnersForOrg.mockResolvedValue({ + data: { total_count: 1, runners: [{ id: 42, name: 'runners-x64_i-12345678901234567' }] }, + }); + mockActions.deleteSelfHostedRunnerFromOrg.mockResolvedValue({}); + + await deregisterRunner(prefixedOrgInstance, baseConfig); + + expect(mockActions.listSelfHostedRunnersForOrg).toHaveBeenCalledTimes(1); + expect(mockActions.listSelfHostedRunnersForOrg).toHaveBeenCalledWith({ + org: 'test-org', + name: 'runners-x64_i-12345678901234567', + per_page: 1, + }); + expect(mockPaginate.iterator).not.toHaveBeenCalled(); + expect(mockActions.deleteSelfHostedRunnerFromOrg).toHaveBeenCalledWith({ org: 'test-org', runner_id: 42 }); + }); + + it('should look up a repo runner by exact name with a single request and delete it', async () => { + mockApps.getRepoInstallation.mockResolvedValue({ data: { id: 888 } }); + mockActions.listSelfHostedRunnersForRepo.mockResolvedValue({ + data: { total_count: 1, runners: [{ id: 55, name: 'repo-runner-i-repo12345678901234' }] }, + }); + mockActions.deleteSelfHostedRunnerFromRepo.mockResolvedValue({}); + + await deregisterRunner(prefixedRepoInstance, baseConfig); + + expect(mockActions.listSelfHostedRunnersForRepo).toHaveBeenCalledWith({ + owner: 'test-org', + repo: 'test-repo', + name: 'repo-runner-i-repo12345678901234', + per_page: 1, + }); + expect(mockPaginate.iterator).not.toHaveBeenCalled(); + expect(mockActions.deleteSelfHostedRunnerFromRepo).toHaveBeenCalledWith({ + owner: 'test-org', + repo: 'test-repo', + runner_id: 55, + }); + }); + + it('should scan for legacy registrations when the exact name is not registered', async () => { + mockApps.getOrgInstallation.mockResolvedValue({ data: { id: 999 } }); + mockActions.listSelfHostedRunnersForOrg.mockResolvedValue({ data: { total_count: 0, runners: [] } }); + + mockPaginate.iterator.mockReturnValue( + (async function* () { + yield { data: [] }; + })(), + ); + + await deregisterRunner(prefixedOrgInstance, baseConfig); + + expect(mockActions.listSelfHostedRunnersForOrg).toHaveBeenCalledTimes(1); + expect(mockPaginate.iterator).toHaveBeenCalledTimes(1); + expect(mockActions.deleteSelfHostedRunnerFromOrg).not.toHaveBeenCalled(); + }); + + it('should ignore a runner whose name does not exactly match', async () => { + mockApps.getOrgInstallation.mockResolvedValue({ data: { id: 999 } }); + mockActions.listSelfHostedRunnersForOrg.mockResolvedValue({ + data: { total_count: 1, runners: [{ id: 7, name: 'runners-x64_i-12345678901234567-other' }] }, + }); + + mockPaginate.iterator.mockReturnValue( + (async function* () { + yield { data: [] }; + })(), + ); + + await deregisterRunner(prefixedOrgInstance, baseConfig); + + expect(mockActions.deleteSelfHostedRunnerFromOrg).not.toHaveBeenCalled(); + }); +}); + describe('createThrottleOptions', () => { it('should return false for rate limit and log warning', () => { const options = createThrottleOptions(); @@ -387,3 +493,269 @@ describe('createThrottleOptions', () => { expect(options.onSecondaryRateLimit(60, endpointDefaults)).toBe(false); }); }); + +describe('recorded runner IDs and SQS retries', () => { + beforeEach(() => { + vi.resetAllMocks(); + MockOctokit.plugin.mockReturnValue(MockOctokit); + resetAppCredentialsCache(); + mockedCreateCommonStorage.mockReturnValue({ githubAppCredentials: credentialsStore }); + setupAuthMocks(); + mockApps.getOrgInstallation.mockResolvedValue({ data: { id: 999 } }); + mockApps.getRepoInstallation.mockResolvedValue({ data: { id: 888 } }); + mockActions.getSelfHostedRunnerForOrg.mockImplementation(async ({ runner_id }) => ({ + data: { id: runner_id, name: `jit-${orgInstance.InstanceId}` }, + })); + mockActions.getSelfHostedRunnerForRepo.mockImplementation(async ({ runner_id }) => ({ + data: { id: runner_id, name: `jit-${repoInstance.InstanceId}` }, + })); + mockSqsSend.mockResolvedValue({}); + vi.stubEnv('DEREGISTER_RETRY_QUEUE_URL', 'queue'); + }); + afterEach(() => vi.unstubAllEnvs()); + + it.each([orgInstance, repoInstance])( + 'deletes a recorded ID despite an overridden prefix ($InstanceId)', + async (instance) => { + await deregisterRunner( + { + ...instance, + Tags: [ + ...instance.Tags!, + { Key: 'ghr:runner_name_prefix', Value: 'wrong-' }, + { Key: 'ghr:github_runner_id', Value: '42' }, + ], + }, + baseConfig, + ); + const deletion = + instance === orgInstance + ? mockActions.deleteSelfHostedRunnerFromOrg + : mockActions.deleteSelfHostedRunnerFromRepo; + expect(deletion).toHaveBeenCalledWith(expect.objectContaining({ runner_id: 42 })); + expect(mockPaginate.iterator).not.toHaveBeenCalled(); + expect(mockActions.listSelfHostedRunnersForOrg).not.toHaveBeenCalled(); + expect(mockActions.listSelfHostedRunnersForRepo).not.toHaveBeenCalled(); + }, + ); + + it.each([orgInstance, repoInstance])( + 'rejects an unrelated tagged ID and queued ID ($InstanceId)', + async (instance) => { + const isOrg = instance === orgInstance; + const getter = isOrg ? mockActions.getSelfHostedRunnerForOrg : mockActions.getSelfHostedRunnerForRepo; + getter.mockResolvedValue({ data: { id: 42, name: `runner-${instance.InstanceId}-other` } }); + const list = isOrg ? mockActions.listSelfHostedRunnersForOrg : mockActions.listSelfHostedRunnersForRepo; + list.mockResolvedValue({ data: { runners: [] } }); + await deregisterRunner( + { + ...instance, + Tags: [ + ...instance.Tags!, + { Key: 'ghr:github_runner_id', Value: '42' }, + { Key: 'ghr:registered_runner_name_prefix', Value: 'jit-' }, + ], + }, + baseConfig, + ); + await handleDeregisterRetry('queue', { + instanceId: instance.InstanceId!, + owner: isOrg ? 'test-org' : 'test-org/test-repo', + runnerType: isOrg ? 'Org' : 'Repo', + runnerId: 42, + retryCount: 0, + }); + expect(mockActions.deleteSelfHostedRunnerFromOrg).not.toHaveBeenCalled(); + expect(mockActions.deleteSelfHostedRunnerFromRepo).not.toHaveBeenCalled(); + expect(mockSqsSend).not.toHaveBeenCalled(); + expect(mockPaginate.iterator).not.toHaveBeenCalled(); + }, + ); + + it.each([orgInstance, repoInstance])( + 'does not scan on an authoritative name miss ($InstanceId)', + async (instance) => { + const list = + instance === orgInstance ? mockActions.listSelfHostedRunnersForOrg : mockActions.listSelfHostedRunnersForRepo; + list.mockResolvedValue({ data: { runners: [] } }); + await deregisterRunner( + { + ...instance, + Tags: [ + ...instance.Tags!, + { Key: 'ghr:runner_name_prefix', Value: 'tag-' }, + { Key: 'ghr:registered_runner_name_prefix', Value: '' }, + ], + }, + baseConfig, + ); + expect(list).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ name: instance.InstanceId, per_page: 1 })); + expect(mockPaginate.iterator).not.toHaveBeenCalled(); + expect(mockActions.deleteSelfHostedRunnerFromOrg).not.toHaveBeenCalled(); + expect(mockActions.deleteSelfHostedRunnerFromRepo).not.toHaveBeenCalled(); + }, + ); + + it('uses the authoritative JIT prefix despite a legacy tag override', async () => { + mockActions.listSelfHostedRunnersForOrg.mockResolvedValue({ + data: { runners: [{ id: 42, name: `jit-${orgInstance.InstanceId}` }] }, + }); + await deregisterRunner( + { + ...orgInstance, + Tags: [ + ...orgInstance.Tags!, + { Key: 'ghr:runner_name_prefix', Value: 'tag-' }, + { Key: 'ghr:registered_runner_name_prefix', Value: 'jit-' }, + ], + }, + baseConfig, + ); + expect(mockActions.listSelfHostedRunnersForOrg).toHaveBeenCalledExactlyOnceWith({ + org: 'test-org', + name: `jit-${orgInstance.InstanceId}`, + per_page: 1, + }); + expect(mockActions.deleteSelfHostedRunnerFromOrg).toHaveBeenCalledWith({ org: 'test-org', runner_id: 42 }); + expect(mockPaginate.iterator).not.toHaveBeenCalled(); + }); + + it('treats a missing retry ID as already removed without scanning', async () => { + mockActions.getSelfHostedRunnerForOrg.mockRejectedValue(Object.assign(new Error('gone'), { status: 404 })); + await handleDeregisterRetry('queue', { + instanceId: orgInstance.InstanceId!, + owner: 'test-org', + runnerType: 'Org', + runnerId: 42, + retryCount: 0, + }); + expect(mockActions.deleteSelfHostedRunnerFromOrg).not.toHaveBeenCalled(); + expect(mockPaginate.iterator).not.toHaveBeenCalled(); + expect(mockSqsSend).not.toHaveBeenCalled(); + }); + + it.each([403, 422, 500])('never deletes or queues an unverified ID after lookup error %s', async (status) => { + const error = Object.assign(new Error('lookup failed'), { status }); + mockActions.getSelfHostedRunnerForOrg.mockRejectedValue(error); + await deregisterRunner( + { ...orgInstance, Tags: [...orgInstance.Tags!, { Key: 'ghr:github_runner_id', Value: '42' }] }, + baseConfig, + ); + await expect( + handleDeregisterRetry('queue', { + instanceId: orgInstance.InstanceId!, + owner: 'test-org', + runnerType: 'Org', + runnerId: 42, + retryCount: 0, + }), + ).rejects.toBe(error); + expect(mockActions.deleteSelfHostedRunnerFromOrg).not.toHaveBeenCalled(); + expect(mockSqsSend).not.toHaveBeenCalled(); + }); + + it.each(['', 'invalid', '0', '-1', '1.5', '9007199254740992'])( + 'falls back for invalid recorded ID %s and a mismatched JIT prefix', + async (id) => { + mockActions.listSelfHostedRunnersForOrg.mockResolvedValue({ data: { runners: [] } }); + mockPaginate.iterator.mockReturnValue( + (async function* () { + yield { data: [{ id: 42, name: `jit-${orgInstance.InstanceId}` }] }; + })(), + ); + await deregisterRunner( + { + ...orgInstance, + Tags: [ + ...orgInstance.Tags!, + { Key: 'ghr:runner_name_prefix', Value: 'tag-' }, + { Key: 'ghr:github_runner_id', Value: id }, + ], + }, + baseConfig, + ); + expect(mockActions.deleteSelfHostedRunnerFromOrg).toHaveBeenCalledWith({ org: 'test-org', runner_id: 42 }); + }, + ); + + it('carries an exact-name result through busy retries without further lookups', async () => { + mockActions.listSelfHostedRunnersForOrg.mockResolvedValue({ + data: { runners: [{ id: 42, name: orgInstance.InstanceId }] }, + }); + mockActions.deleteSelfHostedRunnerFromOrg.mockRejectedValueOnce(Object.assign(new Error('busy'), { status: 422 })); + await deregisterRunner( + { ...orgInstance, Tags: [...orgInstance.Tags!, { Key: 'ghr:runner_name_prefix', Value: '' }] }, + baseConfig, + ); + const message = JSON.parse(mockSqsSend.mock.calls[0][0].input.MessageBody); + expect(message).toMatchObject({ runnerId: 42, retryCount: 0 }); + mockActions.deleteSelfHostedRunnerFromOrg.mockRejectedValueOnce(Object.assign(new Error('busy'), { status: 422 })); + await handleDeregisterRetry('queue', message); + const next = JSON.parse(mockSqsSend.mock.calls[1][0].input.MessageBody); + expect(next).toMatchObject({ runnerId: 42, retryCount: 1 }); + await handleDeregisterRetry('queue', next); + expect(mockActions.deleteSelfHostedRunnerFromOrg).toHaveBeenCalledTimes(3); + expect(mockActions.listSelfHostedRunnersForOrg).toHaveBeenCalledTimes(1); + expect(mockPaginate.iterator).not.toHaveBeenCalled(); + }); + + it.each([0, undefined])('upgrades a legacy retry with ID %s after finding a busy runner', async (runnerId) => { + mockPaginate.iterator.mockReturnValue( + (async function* () { + yield { data: [{ id: 55, name: repoInstance.InstanceId }] }; + })(), + ); + mockActions.deleteSelfHostedRunnerFromRepo.mockRejectedValueOnce(Object.assign(new Error('busy'), { status: 422 })); + await handleDeregisterRetry('queue', { + instanceId: repoInstance.InstanceId!, + owner: 'test-org/test-repo', + runnerType: 'Repo', + runnerId, + retryCount: 1, + }); + const next = JSON.parse(mockSqsSend.mock.calls[0][0].input.MessageBody); + expect(next).toMatchObject({ runnerId: 55, retryCount: 2 }); + await handleDeregisterRetry('queue', next); + expect(mockPaginate.iterator).toHaveBeenCalledTimes(1); + expect(mockActions.deleteSelfHostedRunnerFromRepo).toHaveBeenLastCalledWith({ + owner: 'test-org', + repo: 'test-repo', + runner_id: 55, + }); + }); + + it('treats an already removed recorded runner as success initially and on retry', async () => { + mockActions.deleteSelfHostedRunnerFromOrg.mockRejectedValue(Object.assign(new Error('gone'), { status: 404 })); + await deregisterRunner( + { ...orgInstance, Tags: [...orgInstance.Tags!, { Key: 'ghr:github_runner_id', Value: '42' }] }, + baseConfig, + ); + await expect( + handleDeregisterRetry('queue', { + instanceId: orgInstance.InstanceId!, + owner: 'test-org', + runnerType: 'Org', + runnerId: 42, + retryCount: 0, + }), + ).resolves.toBeUndefined(); + expect(mockSqsSend).not.toHaveBeenCalled(); + expect(mockPaginate.iterator).not.toHaveBeenCalled(); + }); + + it.each([403, 500])('propagates retry API error %s for SQS redelivery', async (status) => { + const error = Object.assign(new Error('API failure'), { status }); + mockActions.deleteSelfHostedRunnerFromOrg.mockRejectedValue(error); + await expect( + handleDeregisterRetry('queue', { + instanceId: orgInstance.InstanceId!, + owner: 'test-org', + runnerType: 'Org', + runnerId: 42, + retryCount: 0, + }), + ).rejects.toBe(error); + expect(mockSqsSend).not.toHaveBeenCalled(); + expect(mockPaginate.iterator).not.toHaveBeenCalled(); + }); +}); diff --git a/lambdas/functions/termination-watcher/src/deregister.ts b/lambdas/functions/termination-watcher/src/deregister.ts index 8b5fa9369..65f6a4bc1 100644 --- a/lambdas/functions/termination-watcher/src/deregister.ts +++ b/lambdas/functions/termination-watcher/src/deregister.ts @@ -10,7 +10,7 @@ export interface DeregisterRetryMessage { instanceId: string; owner: string; runnerType: string; - runnerId: number; + runnerId?: number; retryCount: number; } @@ -26,6 +26,76 @@ function getRunnerTypeFromTags(instance: Instance): string | undefined { return instance.Tags?.find((tag) => tag.Key === 'ghr:Type')?.Value; } +function getRunnerNamePrefixFromTags(instance: Instance): string | undefined { + return instance.Tags?.find((tag) => tag.Key === 'ghr:runner_name_prefix')?.Value; +} + +function isRunnerId(value: number | undefined): value is number { + return value !== undefined && Number.isSafeInteger(value) && value > 0; +} + +function isNotFound(error: unknown): boolean { + return error instanceof Error && 'status' in error && error.status === 404; +} + +/** Instance-writable IDs must be checked against GitHub before use. */ +async function findRunnerById( + octokit: Octokit, + owner: string, + runnerId: number, + instanceId: string, + runnerType: string, +): Promise<{ id: number; name: string } | undefined> { + try { + const [repoOwner, repo] = owner.split('/'); + const response = + runnerType === 'Repo' + ? await octokit.actions.getSelfHostedRunnerForRepo({ owner: repoOwner, repo, runner_id: runnerId }) + : await octokit.actions.getSelfHostedRunnerForOrg({ org: owner, runner_id: runnerId }); + const runner = response.data; + if (runner.id === runnerId && runner.name.endsWith(instanceId)) { + return { id: runner.id, name: runner.name }; + } + logger.warn('Runner ID does not belong to the terminating instance', { instanceId, runnerId }); + return undefined; + } catch (error) { + if (isNotFound(error)) return undefined; + throw error; + } +} + +/** + * Looks up a runner by its exact registered name using the `name` filter of the + * list-runners API. One request regardless of how many runners the owner has. + */ +async function findRunnerByName( + octokit: Octokit, + owner: string, + runnerName: string, + runnerType: string, +): Promise<{ id: number; name: string } | undefined> { + const response = + runnerType === 'Repo' + ? await (async () => { + const [repoOwner, repo] = owner.split('/'); + return octokit.actions.listSelfHostedRunnersForRepo({ + owner: repoOwner, + repo, + name: runnerName, + per_page: 1, + }); + })() + : await octokit.actions.listSelfHostedRunnersForOrg({ org: owner, name: runnerName, per_page: 1 }); + + const runner = response.data.runners.find((r) => r.name === runnerName); + return runner ? { id: runner.id, name: runner.name } : undefined; +} + +/** + * Compatibility fallback when the prefix is missing or does not match: scan every page of + * the owner's runners for a name containing the instance id. Cost grows with the + * number of registered runners, so prefer `findRunnerByName` whenever the prefix is known. + */ async function findRunnerByInstanceId( octokit: Octokit, owner: string, @@ -39,7 +109,7 @@ async function findRunnerByInstanceId( repo, per_page: 100, })) { - const runner = response.data.find((r) => r.name.includes(instanceId)); + const runner = response.data.find((r) => r.name.endsWith(instanceId)); if (runner) { return { id: runner.id, name: runner.name }; } @@ -49,7 +119,7 @@ async function findRunnerByInstanceId( org: owner, per_page: 100, })) { - const runner = response.data.find((r) => r.name.includes(instanceId)); + const runner = response.data.find((r) => r.name.endsWith(instanceId)); if (runner) { return { id: runner.id, name: runner.name }; } @@ -89,18 +159,38 @@ export async function deregisterRunner(instance: Instance, config: Config): Prom const owner = getOwnerFromTags(instance); const runnerType = getRunnerTypeFromTags(instance) ?? 'Org'; + const runnerNamePrefix = getRunnerNamePrefixFromTags(instance); + const registeredPrefix = instance.Tags?.find((tag) => tag.Key === 'ghr:registered_runner_name_prefix')?.Value; if (!owner) { logger.warn('ghr:Owner tag not found on instance, cannot deregister runner', { instanceId }); return; } + const taggedRunnerId = Number(instance.Tags?.find((tag) => tag.Key === 'ghr:github_runner_id')?.Value); + let runner: { id: number; name?: string } | undefined; + try { logger.info('Attempting to deregister runner from GitHub', { instanceId, owner, runnerType }); const installationOctokit = await createRunnerInstallationClient(owner, runnerType, config.ghesApiUrl); - const runner = await findRunnerByInstanceId(installationOctokit, owner, instanceId, runnerType); + runner = isRunnerId(taggedRunnerId) + ? await findRunnerById(installationOctokit, owner, taggedRunnerId, instanceId, runnerType) + : undefined; + if (!runner && registeredPrefix !== undefined) { + runner = await findRunnerByName(installationOctokit, owner, `${registeredPrefix}${instanceId}`, runnerType); + if (!runner) return; + } + if (!runner && runnerNamePrefix !== undefined) { + runner = await findRunnerByName(installationOctokit, owner, `${runnerNamePrefix}${instanceId}`, runnerType); + } + if (!runner) { + // JIT registration uses the configured prefix, which can differ from the EC2 tag override. + // Older instances may also have no recorded runner ID or prefix at all. + logger.debug('No runner ID or matching exact name, falling back to scanning all runners', { instanceId }); + runner = await findRunnerByInstanceId(installationOctokit, owner, instanceId, runnerType); + } if (!runner) { logger.info('Runner not found in GitHub, may have already been deregistered', { instanceId, owner }); return; @@ -114,14 +204,18 @@ export async function deregisterRunner(instance: Instance, config: Config): Prom owner, }); } catch (error) { + if (runner && isNotFound(error)) { + logger.info('Runner already deregistered', { instanceId, runnerId: runner.id, owner }); + return; + } // GitHub returns 422 when a runner is currently executing a job. // Queue a delayed retry — the instance will be terminated by EC2 shortly, // and the runner will appear offline when we retry in 5 minutes. const isRunnerBusy = error instanceof Error && 'status' in error && (error as { status: number }).status === 422; - if (isRunnerBusy) { + if (isRunnerBusy && runner) { const queueUrl = process.env.DEREGISTER_RETRY_QUEUE_URL; if (queueUrl) { - await queueDeregisterRetry(queueUrl, { instanceId, owner, runnerType, runnerId: 0, retryCount: 0 }); + await queueDeregisterRetry(queueUrl, { instanceId, owner, runnerType, runnerId: runner?.id, retryCount: 0 }); logger.warn('Runner is busy — queued deregistration retry in 5 minutes via SQS', { instanceId, owner }); } else { logger.warn('Runner is busy and DEREGISTER_RETRY_QUEUE_URL is not set — deregistration skipped', { @@ -151,10 +245,13 @@ export async function handleDeregisterRetry(queueUrl: string, message: Deregiste const { instanceId, owner, runnerType, retryCount } = message; logger.info('Processing deregistration retry from SQS', { instanceId, owner, runnerType, retryCount }); + let runner: { id: number; name?: string } | undefined; try { const installationOctokit = await createRunnerInstallationClient(owner, runnerType, process.env.GHES_URL ?? ''); - const runner = await findRunnerByInstanceId(installationOctokit, owner, instanceId, runnerType); + runner = isRunnerId(message.runnerId) + ? await findRunnerById(installationOctokit, owner, message.runnerId, instanceId, runnerType) + : await findRunnerByInstanceId(installationOctokit, owner, instanceId, runnerType); if (!runner) { logger.info('Runner not found in GitHub — already deregistered or never registered', { instanceId, owner }); return; @@ -169,12 +266,20 @@ export async function handleDeregisterRetry(queueUrl: string, message: Deregiste retryCount, }); } catch (error) { + if (runner && isNotFound(error)) { + logger.info('Runner already deregistered on retry', { instanceId, runnerId: runner.id, owner }); + return; + } const isRunnerBusy = error instanceof Error && 'status' in error && (error as { status: number }).status === 422; - if (isRunnerBusy) { + if (isRunnerBusy && runner) { // Re-enqueue for another retry — SQS maxReceiveCount DLQ will stop after 3 total attempts. // Re-send explicitly so each retry resets the delay (SQS visibility timeout applies on re-receive, // but re-sending gives us the full 5-minute DelaySeconds again). - await queueDeregisterRetry(queueUrl, { ...message, retryCount: retryCount + 1 }); + await queueDeregisterRetry(queueUrl, { + ...message, + runnerId: runner?.id ?? message.runnerId, + retryCount: retryCount + 1, + }); logger.warn('Runner still busy on retry — re-queued for another attempt', { instanceId, owner, diff --git a/modules/runners/main.tf b/modules/runners/main.tf index c24df310c..ffd46f13a 100644 --- a/modules/runners/main.tf +++ b/modules/runners/main.tf @@ -279,7 +279,12 @@ resource "aws_launch_template" "runner" { { "ghr:runner_name_prefix" = var.runner_name_prefix }, - var.runner_ec2_tags + var.runner_ec2_tags, + { + # JIT uses the configured prefix; config.sh uses the overridable EC2 tag. + # Keep this authoritative tag after user tags so cleanup can avoid scans. + "ghr:registered_runner_name_prefix" = var.enable_ephemeral_runners && coalesce(var.enable_jit_config, var.enable_ephemeral_runners) ? var.runner_name_prefix : lookup(var.runner_ec2_tags, "ghr:runner_name_prefix", var.runner_name_prefix) + } ) } diff --git a/modules/runners/tests/launch-template.tftest.hcl b/modules/runners/tests/launch-template.tftest.hcl index a653056fb..ee4a28711 100644 --- a/modules/runners/tests/launch-template.tftest.hcl +++ b/modules/runners/tests/launch-template.tftest.hcl @@ -134,3 +134,63 @@ run "creates_on_demand_override_launch_template_even_when_failover_is_configured error_message = "Neither variant should tag spot-instances-request when on_demand_failover_for_errors is configured." } } + +run "registration_jit_prefix" { + command = plan + variables { + enable_ephemeral_runners = true + enable_jit_config = null + runner_name_prefix = "jit-" + runner_ec2_tags = { + "ghr:runner_name_prefix" = "tag-" + "ghr:registered_runner_name_prefix" = "untrusted-" + } + } + assert { + condition = alltrue([ + for template in values(aws_launch_template.runner) : + one([for tags in template.tag_specifications : tags.tags["ghr:registered_runner_name_prefix"] if tags.resource_type == "instance"]) == "jit-" + ]) + error_message = "Cleanup's authoritative prefix must match the registration path and cannot be overridden by user tags." + } +} + +run "registration_non_jit_prefix" { + command = plan + variables { + enable_ephemeral_runners = true + enable_jit_config = false + runner_name_prefix = "jit-" + runner_ec2_tags = { + "ghr:runner_name_prefix" = "tag-" + "ghr:registered_runner_name_prefix" = "untrusted-" + } + } + assert { + condition = alltrue([ + for template in values(aws_launch_template.runner) : + one([for tags in template.tag_specifications : tags.tags["ghr:registered_runner_name_prefix"] if tags.resource_type == "instance"]) == "tag-" + ]) + error_message = "Cleanup's authoritative prefix must match the registration path and cannot be overridden by user tags." + } +} + +run "registration_persistent_prefix" { + command = plan + variables { + enable_ephemeral_runners = false + enable_jit_config = true + runner_name_prefix = "jit-" + runner_ec2_tags = { + "ghr:runner_name_prefix" = "tag-" + "ghr:registered_runner_name_prefix" = "untrusted-" + } + } + assert { + condition = alltrue([ + for template in values(aws_launch_template.runner) : + one([for tags in template.tag_specifications : tags.tags["ghr:registered_runner_name_prefix"] if tags.resource_type == "instance"]) == "tag-" + ]) + error_message = "Cleanup's authoritative prefix must match the registration path and cannot be overridden by user tags." + } +} diff --git a/modules/termination-watcher/README.md b/modules/termination-watcher/README.md index e919532bf..b465a7d01 100644 --- a/modules/termination-watcher/README.md +++ b/modules/termination-watcher/README.md @@ -55,6 +55,12 @@ To compile all TypeScript/JavaScript sources in a single file [ncc](https://gith yarn run dist ``` +When a tracked instance terminates, the watcher fetches its recorded `ghr:github_runner_id` from GitHub and verifies that the registered name ends with the instance ID before deleting it. The instance role can write this ID tag, so the tag alone is not proof of ownership. SQS retries also verify IDs, including those queued by older watcher versions; lookup errors never authorize deletion or enqueue an unverified ID. + +New instances receive a module-controlled `ghr:registered_runner_name_prefix` tag reflecting the actual registration path: the configured prefix for JIT, or the effective `ghr:runner_name_prefix` override for non-JIT registration. If the recorded ID is missing or does not resolve to this instance, the watcher uses this authoritative prefix for a single exact-name lookup. An exact-name miss is terminal and never triggers a full scan. Applying the updated runners module and launching new instances is required for this tag; updating only the watcher does not add it to existing instances. + +Older instances without the authoritative prefix first try the legacy prefix and then fall back to scanning by instance ID, preserving compatibility with overridden JIT names. Older queued messages without a valid ID also retain this fallback. These legacy scans cost one request per 100 registered runners. Busy retries retain the resolved ID, so subsequent attempts use a bounded ID lookup and deletion instead of scanning. A 404 from a retry lookup or deletion is treated as already deregistered. The scheduled `registration-janitor` module remains the reconciliation path for registrations that outlive their instance. + Deregistration and SQS retries can use additional GitHub Apps through `config.github_app_parameters.additional_apps_manifest` and `additional_app_parameter_arns`. The multi-runner module passes its configured additional Apps automatically. Selection uses observed installation quota, with a one-minute cooldown after throttling and fallback to another App when authentication fails. Each cleanup operation keeps App and installation authentication paired; existing single-App configurations remain supported.