From f916f110fb9fdaf4e6b08ffd6464c96a96d658b3 Mon Sep 17 00:00:00 2001 From: Ronnie Coleman Date: Mon, 2 Nov 2026 22:10:56 -0800 Subject: [PATCH 1/3] fix(termination-watcher): look up the runner by exact name instead of paginating all runners On every instance termination the watcher resolved the runner's GitHub registration by iterating every page of the owner's runner list and matching `name.includes(instanceId)`. The cost of that lookup grows with the number of registered runners (one request per 100), and on an ephemeral fleet the registration is normally already gone when the termination event arrives, so the common outcome is a full scan that finds nothing. The runner modules tag every instance with `ghr:runner_name_prefix`, and runners are registered as ``. Use that to call the list-runners API with its `name` filter, which returns the single matching runner (or none) in one request. Instances without the tag keep the previous paginated scan as a fallback. The behaviour is otherwise unchanged: a found runner is deleted, a busy runner (422) is retried through SQS, and a missing runner is logged. --- .../src/deregister.test.ts | 82 +++++++++++++++++++ .../termination-watcher/src/deregister.ts | 47 ++++++++++- modules/termination-watcher/README.md | 2 + 3 files changed, 130 insertions(+), 1 deletion(-) diff --git a/lambdas/functions/termination-watcher/src/deregister.test.ts b/lambdas/functions/termination-watcher/src/deregister.test.ts index 3fbf1c7671..c4188dc978 100644 --- a/lambdas/functions/termination-watcher/src/deregister.test.ts +++ b/lambdas/functions/termination-watcher/src/deregister.test.ts @@ -378,6 +378,88 @@ 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 not scan all runners when the exact name is not registered', async () => { + mockApps.getOrgInstallation.mockResolvedValue({ data: { id: 999 } }); + mockActions.listSelfHostedRunnersForOrg.mockResolvedValue({ data: { total_count: 0, runners: [] } }); + + await deregisterRunner(prefixedOrgInstance, baseConfig); + + expect(mockActions.listSelfHostedRunnersForOrg).toHaveBeenCalledTimes(1); + expect(mockPaginate.iterator).not.toHaveBeenCalled(); + 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' }] }, + }); + + await deregisterRunner(prefixedOrgInstance, baseConfig); + + expect(mockActions.deleteSelfHostedRunnerFromOrg).not.toHaveBeenCalled(); + }); +}); + describe('createThrottleOptions', () => { it('should return false for rate limit and log warning', () => { const options = createThrottleOptions(); diff --git a/lambdas/functions/termination-watcher/src/deregister.ts b/lambdas/functions/termination-watcher/src/deregister.ts index 8b5fa93696..8572a757b9 100644 --- a/lambdas/functions/termination-watcher/src/deregister.ts +++ b/lambdas/functions/termination-watcher/src/deregister.ts @@ -26,6 +26,42 @@ 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; +} + +/** + * 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; +} + +/** + * Fallback for instances without a `ghr:runner_name_prefix` tag: 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, @@ -89,6 +125,7 @@ export async function deregisterRunner(instance: Instance, config: Config): Prom const owner = getOwnerFromTags(instance); const runnerType = getRunnerTypeFromTags(instance) ?? 'Org'; + const runnerNamePrefix = getRunnerNamePrefixFromTags(instance); if (!owner) { logger.warn('ghr:Owner tag not found on instance, cannot deregister runner', { instanceId }); @@ -100,7 +137,15 @@ export async function deregisterRunner(instance: Instance, config: Config): Prom const installationOctokit = await createRunnerInstallationClient(owner, runnerType, config.ghesApiUrl); - const runner = await findRunnerByInstanceId(installationOctokit, owner, instanceId, runnerType); + let runner: { id: number; name: string } | undefined; + if (runnerNamePrefix !== undefined) { + runner = await findRunnerByName(installationOctokit, owner, `${runnerNamePrefix}${instanceId}`, runnerType); + } else { + logger.debug('ghr:runner_name_prefix tag not found on instance, 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; diff --git a/modules/termination-watcher/README.md b/modules/termination-watcher/README.md index e919532bfc..3158a780da 100644 --- a/modules/termination-watcher/README.md +++ b/modules/termination-watcher/README.md @@ -55,6 +55,8 @@ To compile all TypeScript/JavaScript sources in a single file [ncc](https://gith yarn run dist ``` +When a tracked instance terminates, the watcher resolves its GitHub registration from the `ghr:runner_name_prefix` tag the runner modules place on every instance: the registered name is ``, so the lookup is a single `name`-filtered list-runners request regardless of fleet size. Instances without that tag fall back to paginating every runner of the owner and matching on instance id, which costs one request per 100 registered runners. On ephemeral fleets the registration is normally already gone when the termination event arrives, because GitHub removes an ephemeral runner as soon as its job completes, so the per-event lookup is mostly confirmation; the scheduled `registration-janitor` module is 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. From 8b422e712c7d37cea4641dace10d7a3f29d099b6 Mon Sep 17 00:00:00 2001 From: Guilherme Caulada Date: Thu, 12 Nov 2026 12:49:21 -0300 Subject: [PATCH 2/3] fix(termination-watcher): preserve runner IDs for deregistration retries --- .../src/deregister.test.ts | 173 +++++++++++++++++- .../termination-watcher/src/deregister.ts | 49 +++-- modules/termination-watcher/README.md | 4 +- 3 files changed, 211 insertions(+), 15 deletions(-) diff --git a/lambdas/functions/termination-watcher/src/deregister.test.ts b/lambdas/functions/termination-watcher/src/deregister.test.ts index c4188dc978..98830ec1ae 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,6 +19,16 @@ 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(), }; @@ -437,14 +447,20 @@ describe('deregisterRunner exact-name lookup (ghr:runner_name_prefix present)', }); }); - it('should not scan all runners when the exact name is not registered', async () => { + 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).not.toHaveBeenCalled(); + expect(mockPaginate.iterator).toHaveBeenCalledTimes(1); expect(mockActions.deleteSelfHostedRunnerFromOrg).not.toHaveBeenCalled(); }); @@ -454,6 +470,12 @@ describe('deregisterRunner exact-name lookup (ghr:runner_name_prefix present)', 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(); @@ -469,3 +491,148 @@ 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 } }); + 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(['', '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 8572a757b9..ba0813a2f9 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; } @@ -30,6 +30,14 @@ 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; +} + /** * 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. @@ -58,7 +66,7 @@ async function findRunnerByName( } /** - * Fallback for instances without a `ghr:runner_name_prefix` tag: scan every page of + * 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. */ @@ -132,18 +140,22 @@ export async function deregisterRunner(instance: Instance, config: Config): Prom 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); - let runner: { id: number; name: string } | undefined; - if (runnerNamePrefix !== undefined) { + runner = isRunnerId(taggedRunnerId) ? { id: taggedRunnerId } : undefined; + if (!runner && runnerNamePrefix !== undefined) { runner = await findRunnerByName(installationOctokit, owner, `${runnerNamePrefix}${instanceId}`, runnerType); - } else { - logger.debug('ghr:runner_name_prefix tag not found on instance, falling back to scanning all runners', { - instanceId, - }); + } + 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) { @@ -159,6 +171,10 @@ 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. @@ -166,7 +182,7 @@ export async function deregisterRunner(instance: Instance, config: Config): Prom if (isRunnerBusy) { 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', { @@ -196,10 +212,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) + ? { id: message.runnerId } + : await findRunnerByInstanceId(installationOctokit, owner, instanceId, runnerType); if (!runner) { logger.info('Runner not found in GitHub — already deregistered or never registered', { instanceId, owner }); return; @@ -214,12 +233,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) { // 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/termination-watcher/README.md b/modules/termination-watcher/README.md index 3158a780da..300494fe1a 100644 --- a/modules/termination-watcher/README.md +++ b/modules/termination-watcher/README.md @@ -55,7 +55,9 @@ To compile all TypeScript/JavaScript sources in a single file [ncc](https://gith yarn run dist ``` -When a tracked instance terminates, the watcher resolves its GitHub registration from the `ghr:runner_name_prefix` tag the runner modules place on every instance: the registered name is ``, so the lookup is a single `name`-filtered list-runners request regardless of fleet size. Instances without that tag fall back to paginating every runner of the owner and matching on instance id, which costs one request per 100 registered runners. On ephemeral fleets the registration is normally already gone when the termination event arrives, because GitHub removes an ephemeral runner as soon as its job completes, so the per-event lookup is mostly confirmation; the scheduled `registration-janitor` module is the reconciliation path for registrations that outlive their instance. +When a tracked instance terminates, the watcher prefers its recorded `ghr:github_runner_id` and deletes that registration directly. Otherwise, it tries a single `name`-filtered lookup using ``. If the prefix is missing or the exact name is not found, it falls back to scanning the owner's runners by instance ID for compatibility with older instances and JIT registrations whose configured prefix differs from an EC2 tag override. This fallback costs one request per 100 registered runners, including when the registration is already gone and no ID was recorded. + +Busy-runner SQS retries carry the resolved runner ID and delete it directly without another lookup. Older queued messages with a missing or zero ID still use the compatibility scan; any subsequent busy retry retains the resolved ID. A deletion returning 404 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. From 14ebbb396da53ab3094d7eaa8812f4a85059786d Mon Sep 17 00:00:00 2001 From: Guilherme Caulada Date: Thu, 12 Nov 2026 13:00:56 -0300 Subject: [PATCH 3/3] fix(termination-watcher): verify runner identity and bound name misses --- .../src/deregister.test.ts | 123 ++++++++++++++++++ .../termination-watcher/src/deregister.ts | 45 ++++++- modules/runners/main.tf | 7 +- .../runners/tests/launch-template.tftest.hcl | 60 +++++++++ modules/termination-watcher/README.md | 6 +- 5 files changed, 232 insertions(+), 9 deletions(-) diff --git a/lambdas/functions/termination-watcher/src/deregister.test.ts b/lambdas/functions/termination-watcher/src/deregister.test.ts index 98830ec1ae..92ebbef0f8 100644 --- a/lambdas/functions/termination-watcher/src/deregister.test.ts +++ b/lambdas/functions/termination-watcher/src/deregister.test.ts @@ -34,6 +34,8 @@ const mockPaginate = { }; const mockActions = { + getSelfHostedRunnerForOrg: vi.fn(), + getSelfHostedRunnerForRepo: vi.fn(), listSelfHostedRunnersForOrg: vi.fn(), listSelfHostedRunnersForRepo: vi.fn(), deleteSelfHostedRunnerFromOrg: vi.fn(), @@ -501,6 +503,12 @@ describe('recorded runner IDs and SQS retries', () => { 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'); }); @@ -531,6 +539,121 @@ describe('recorded runner IDs and SQS retries', () => { }, ); + 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) => { diff --git a/lambdas/functions/termination-watcher/src/deregister.ts b/lambdas/functions/termination-watcher/src/deregister.ts index ba0813a2f9..65f6a4bc1e 100644 --- a/lambdas/functions/termination-watcher/src/deregister.ts +++ b/lambdas/functions/termination-watcher/src/deregister.ts @@ -38,6 +38,32 @@ 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. @@ -83,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 }; } @@ -93,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 }; } @@ -134,6 +160,7 @@ 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 }); @@ -148,7 +175,13 @@ export async function deregisterRunner(instance: Instance, config: Config): Prom const installationOctokit = await createRunnerInstallationClient(owner, runnerType, config.ghesApiUrl); - runner = isRunnerId(taggedRunnerId) ? { id: taggedRunnerId } : undefined; + 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); } @@ -179,7 +212,7 @@ export async function deregisterRunner(instance: Instance, config: Config): Prom // 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: runner?.id, retryCount: 0 }); @@ -217,7 +250,7 @@ export async function handleDeregisterRetry(queueUrl: string, message: Deregiste const installationOctokit = await createRunnerInstallationClient(owner, runnerType, process.env.GHES_URL ?? ''); runner = isRunnerId(message.runnerId) - ? { id: 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 }); @@ -238,7 +271,7 @@ export async function handleDeregisterRetry(queueUrl: string, message: Deregiste 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). diff --git a/modules/runners/main.tf b/modules/runners/main.tf index c24df310ce..ffd46f13a0 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 a653056fb2..ee4a287118 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 300494fe1a..b465a7d01b 100644 --- a/modules/termination-watcher/README.md +++ b/modules/termination-watcher/README.md @@ -55,9 +55,11 @@ To compile all TypeScript/JavaScript sources in a single file [ncc](https://gith yarn run dist ``` -When a tracked instance terminates, the watcher prefers its recorded `ghr:github_runner_id` and deletes that registration directly. Otherwise, it tries a single `name`-filtered lookup using ``. If the prefix is missing or the exact name is not found, it falls back to scanning the owner's runners by instance ID for compatibility with older instances and JIT registrations whose configured prefix differs from an EC2 tag override. This fallback costs one request per 100 registered runners, including when the registration is already gone and no ID was recorded. +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. -Busy-runner SQS retries carry the resolved runner ID and delete it directly without another lookup. Older queued messages with a missing or zero ID still use the compatibility scan; any subsequent busy retry retains the resolved ID. A deletion returning 404 is treated as already deregistered. The scheduled `registration-janitor` module remains the reconciliation path for registrations that outlive their instance. +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.