From 8a7175fd93fbc8038977ca78b68e0f6b267eb2d5 Mon Sep 17 00:00:00 2001 From: edersonbrilhante Date: Wed, 19 Aug 2026 11:52:51 +0200 Subject: [PATCH 01/11] feat(storage): add DynamoDB provider (cherry picked from commit 8b2fef46548bc48b72f412e70012f50e9a2f4402) Signed-off-by: tehlers320 <16598119+tehlers320@users.noreply.github.com> --- .../storage-providers/aws/dynamodb/client.ts | 21 ++++ .../aws/dynamodb/environment.d.ts | 13 ++ .../aws/dynamodb/environment.ts | 29 +++++ .../aws/dynamodb/runner-config-store.test.ts | 117 ++++++++++++++++++ .../aws/dynamodb/runner-config-store.ts | 64 ++++++++++ .../dynamodb/runner-group-cache-store.test.ts | 105 ++++++++++++++++ .../aws/dynamodb/runner-group-cache-store.ts | 78 ++++++++++++ .../runner-matcher-config-store.test.ts | 94 ++++++++++++++ .../dynamodb/runner-matcher-config-store.ts | 53 ++++++++ .../github-app-credentials.test.ts | 70 +++++++++++ .../github-app-credentials.ts | 15 +++ .../github-webhook-secret.test.ts | 35 ++---- .../github-webhook-secret.ts | 12 +- lambdas/libs/storage-providers/index.ts | 3 + lambdas/libs/storage-providers/package.json | 1 + lambdas/libs/storage-providers/provider.ts | 3 +- .../storage-providers/runner-config.test.ts | 108 ++++++++++++++++ .../libs/storage-providers/runner-config.ts | 25 ++++ .../runner-group-cache.test.ts | 106 ++++++++++++++++ .../storage-providers/runner-group-cache.ts | 25 ++++ .../runner-matcher-config.test.ts | 23 ++++ .../runner-matcher-config.ts | 2 + 22 files changed, 967 insertions(+), 35 deletions(-) create mode 100644 lambdas/libs/storage-providers/aws/dynamodb/client.ts create mode 100644 lambdas/libs/storage-providers/aws/dynamodb/environment.d.ts create mode 100644 lambdas/libs/storage-providers/aws/dynamodb/environment.ts create mode 100644 lambdas/libs/storage-providers/aws/dynamodb/runner-config-store.test.ts create mode 100644 lambdas/libs/storage-providers/aws/dynamodb/runner-config-store.ts create mode 100644 lambdas/libs/storage-providers/aws/dynamodb/runner-group-cache-store.test.ts create mode 100644 lambdas/libs/storage-providers/aws/dynamodb/runner-group-cache-store.ts create mode 100644 lambdas/libs/storage-providers/aws/dynamodb/runner-matcher-config-store.test.ts create mode 100644 lambdas/libs/storage-providers/aws/dynamodb/runner-matcher-config-store.ts create mode 100644 lambdas/libs/storage-providers/github-app-credentials.test.ts create mode 100644 lambdas/libs/storage-providers/github-app-credentials.ts create mode 100644 lambdas/libs/storage-providers/runner-config.test.ts create mode 100644 lambdas/libs/storage-providers/runner-config.ts create mode 100644 lambdas/libs/storage-providers/runner-group-cache.test.ts create mode 100644 lambdas/libs/storage-providers/runner-group-cache.ts diff --git a/lambdas/libs/storage-providers/aws/dynamodb/client.ts b/lambdas/libs/storage-providers/aws/dynamodb/client.ts new file mode 100644 index 0000000000..86493cc23f --- /dev/null +++ b/lambdas/libs/storage-providers/aws/dynamodb/client.ts @@ -0,0 +1,21 @@ +import { getTracedAWSV3Client } from '@aws-github-runner/aws-powertools-util'; +import { DynamoDBClient } from '@aws-sdk/client-dynamodb'; + +let memoisedClient: DynamoDBClient | undefined; + +export function getDynamoDbClient(): DynamoDBClient { + memoisedClient ??= getTracedAWSV3Client( + new DynamoDBClient({ + region: process.env.AWS_REGION, + maxAttempts: 10, + // One client serves two tables, so avoid an adaptive rate bucket coupling their throttling behavior. + retryMode: 'standard', + }), + ); + return memoisedClient; +} + +// Test-only reset for cases that need a fresh AWS SDK client. +export function resetDynamoDbClient(): void { + memoisedClient = undefined; +} diff --git a/lambdas/libs/storage-providers/aws/dynamodb/environment.d.ts b/lambdas/libs/storage-providers/aws/dynamodb/environment.d.ts new file mode 100644 index 0000000000..80f6cd76b4 --- /dev/null +++ b/lambdas/libs/storage-providers/aws/dynamodb/environment.d.ts @@ -0,0 +1,13 @@ +export {}; + +declare global { + namespace NodeJS { + interface ProcessEnv { + RUNNER_CONFIG_DYNAMODB_CONFIG_KEY_PREFIX?: string; + RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME?: string; + RUNNER_CONFIG_DYNAMODB_TABLE_NAME?: string; + RUNNER_CONFIG_DYNAMODB_TOKEN_KEY_PREFIX?: string; + RUNNER_CONFIG_DYNAMODB_TTL_SECONDS?: string; + } + } +} diff --git a/lambdas/libs/storage-providers/aws/dynamodb/environment.ts b/lambdas/libs/storage-providers/aws/dynamodb/environment.ts new file mode 100644 index 0000000000..008df063f7 --- /dev/null +++ b/lambdas/libs/storage-providers/aws/dynamodb/environment.ts @@ -0,0 +1,29 @@ +type DynamoDbEnvironmentVariable = + | 'RUNNER_CONFIG_DYNAMODB_CONFIG_KEY_PREFIX' + | 'RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME' + | 'RUNNER_CONFIG_DYNAMODB_TABLE_NAME' + | 'RUNNER_CONFIG_DYNAMODB_TOKEN_KEY_PREFIX' + | 'RUNNER_CONFIG_DYNAMODB_TTL_SECONDS'; + +export function requiredEnvironmentValue(name: DynamoDbEnvironmentVariable): string { + const value = process.env[name]?.trim(); + if (!value) { + throw new Error(`Environment variable ${name} is not set`); + } + + return value; +} + +export function positiveIntegerEnvironmentValue(name: DynamoDbEnvironmentVariable): number { + const value = requiredEnvironmentValue(name); + if (!/^[1-9]\d*$/.test(value)) { + throw new Error(`Environment variable ${name} must be a positive integer`); + } + + const parsed = Number(value); + if (!Number.isSafeInteger(parsed)) { + throw new Error(`Environment variable ${name} must be a positive integer`); + } + + return parsed; +} diff --git a/lambdas/libs/storage-providers/aws/dynamodb/runner-config-store.test.ts b/lambdas/libs/storage-providers/aws/dynamodb/runner-config-store.test.ts new file mode 100644 index 0000000000..0801ba666f --- /dev/null +++ b/lambdas/libs/storage-providers/aws/dynamodb/runner-config-store.test.ts @@ -0,0 +1,117 @@ +import { DynamoDBClient, PutItemCommand } from '@aws-sdk/client-dynamodb'; +import { mockClient } from 'aws-sdk-client-mock'; +import 'aws-sdk-client-mock-jest/vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { resetDynamoDbClient } from './client'; +import { createAwsDynamoDbRunnerConfigStore } from './runner-config-store'; + +const mockDynamoDbClient = mockClient(DynamoDBClient); +const cleanEnv = process.env; + +describe('aws_dynamodb runner config store', () => { + beforeEach(() => { + mockDynamoDbClient.reset(); + resetDynamoDbClient(); + process.env = { ...cleanEnv }; + process.env.AWS_REGION = 'eu-west-1'; + process.env.RUNNER_CONFIG_DYNAMODB_TABLE_NAME = 'runner-config'; + process.env.RUNNER_CONFIG_DYNAMODB_TOKEN_KEY_PREFIX = 'tokens#'; + process.env.RUNNER_CONFIG_DYNAMODB_TTL_SECONDS = '3600'; + vi.useFakeTimers(); + vi.setSystemTime(new Date('2025-01-01T00:00:00.000Z')); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it('creates an expiring runner config without overwriting an existing record', async () => { + const store = createAwsDynamoDbRunnerConfigStore(); + + await store.create({ runnerId: 'runner-123', value: 'encoded-jit-config' }); + + expect(store.maxWritesPerSecond).toBeUndefined(); + expect(mockDynamoDbClient).toHaveReceivedCommandWith(PutItemCommand, { + TableName: 'runner-config', + Item: { + id: { S: 'tokens#runner-123' }, + value: { S: 'encoded-jit-config' }, + expires_at: { N: '1735693200' }, + }, + ConditionExpression: 'attribute_not_exists(#id)', + ExpressionAttributeNames: { + '#id': 'id', + }, + }); + }); + + it('stores provider-neutral metadata without exposing it as top-level attributes', async () => { + const store = createAwsDynamoDbRunnerConfigStore(); + + await store.create( + { runnerId: 'runner-123', value: 'registration-config' }, + { + metadata: [ + { key: 'InstanceId', value: 'i-123' }, + { key: 'Environment', value: 'test' }, + ], + }, + ); + + const command = mockDynamoDbClient.commandCalls(PutItemCommand)[0].args[0]; + expect(command.input.Item?.metadata).toEqual({ + L: [ + { M: { key: { S: 'InstanceId' }, value: { S: 'i-123' } } }, + { M: { key: { S: 'Environment' }, value: { S: 'test' } } }, + ], + }); + }); + + it('does not write metadata for an empty metadata list', async () => { + const store = createAwsDynamoDbRunnerConfigStore(); + + await store.create({ runnerId: 'runner-123', value: 'registration-config' }, { metadata: [] }); + + const command = mockDynamoDbClient.commandCalls(PutItemCommand)[0].args[0]; + expect(command.input.Item).not.toHaveProperty('metadata'); + }); + + it('relies on DynamoDB TTL instead of scanning or deleting during housekeeping', async () => { + const store = createAwsDynamoDbRunnerConfigStore(); + + await expect(store.houseKeeper()).resolves.toBeUndefined(); + + expect(mockDynamoDbClient.calls()).toHaveLength(0); + }); + + it.each([ + 'RUNNER_CONFIG_DYNAMODB_TABLE_NAME', + 'RUNNER_CONFIG_DYNAMODB_TOKEN_KEY_PREFIX', + 'RUNNER_CONFIG_DYNAMODB_TTL_SECONDS', + ] as const)('rejects a missing or blank %s', (name) => { + delete process.env[name]; + expect(() => createAwsDynamoDbRunnerConfigStore()).toThrow(`Environment variable ${name} is not set`); + + process.env[name] = ' '; + expect(() => createAwsDynamoDbRunnerConfigStore()).toThrow(`Environment variable ${name} is not set`); + expect(mockDynamoDbClient.calls()).toHaveLength(0); + }); + + it.each(['0', '-1', '1.5', 'not-a-number', '9007199254740992'])('rejects invalid TTL seconds %j', (ttlSeconds) => { + process.env.RUNNER_CONFIG_DYNAMODB_TTL_SECONDS = ttlSeconds; + + expect(() => createAwsDynamoDbRunnerConfigStore()).toThrow( + 'Environment variable RUNNER_CONFIG_DYNAMODB_TTL_SECONDS must be a positive integer', + ); + expect(mockDynamoDbClient.calls()).toHaveLength(0); + }); + + it('propagates DynamoDB write errors without handling the stored value', async () => { + const error = new Error('conditional request failed'); + mockDynamoDbClient.on(PutItemCommand).rejects(error); + const store = createAwsDynamoDbRunnerConfigStore(); + + await expect(store.create({ runnerId: 'runner-123', value: 'sensitive-config' })).rejects.toBe(error); + }); +}); diff --git a/lambdas/libs/storage-providers/aws/dynamodb/runner-config-store.ts b/lambdas/libs/storage-providers/aws/dynamodb/runner-config-store.ts new file mode 100644 index 0000000000..5d4baf2612 --- /dev/null +++ b/lambdas/libs/storage-providers/aws/dynamodb/runner-config-store.ts @@ -0,0 +1,64 @@ +import { PutItemCommand, type AttributeValue } from '@aws-sdk/client-dynamodb'; + +import type { RunnerConfigMetadata, RunnerConfigRecord, RunnerConfigStore } from '../../core'; +import { getDynamoDbClient } from './client'; +import { positiveIntegerEnvironmentValue, requiredEnvironmentValue } from './environment'; + +const ID_ATTRIBUTE = 'id'; +const VALUE_ATTRIBUTE = 'value'; +const EXPIRES_AT_ATTRIBUTE = 'expires_at'; +const METADATA_ATTRIBUTE = 'metadata'; + +interface AwsDynamoDbRunnerConfigStoreConfig { + tableName: string; + tokenKeyPrefix: string; + ttlSeconds: number; +} + +export function createAwsDynamoDbRunnerConfigStore(): RunnerConfigStore { + return new AwsDynamoDbRunnerConfigStore({ + tableName: requiredEnvironmentValue('RUNNER_CONFIG_DYNAMODB_TABLE_NAME'), + tokenKeyPrefix: requiredEnvironmentValue('RUNNER_CONFIG_DYNAMODB_TOKEN_KEY_PREFIX'), + ttlSeconds: positiveIntegerEnvironmentValue('RUNNER_CONFIG_DYNAMODB_TTL_SECONDS'), + }); +} + +class AwsDynamoDbRunnerConfigStore implements RunnerConfigStore { + constructor(private readonly config: AwsDynamoDbRunnerConfigStoreConfig) {} + + async create(record: RunnerConfigRecord, options: { metadata?: RunnerConfigMetadata[] } = {}): Promise { + const item: Record = { + [ID_ATTRIBUTE]: { S: `${this.config.tokenKeyPrefix}${record.runnerId}` }, + [VALUE_ATTRIBUTE]: { S: record.value }, + [EXPIRES_AT_ATTRIBUTE]: { + N: (Math.floor(Date.now() / 1000) + this.config.ttlSeconds).toString(), + }, + }; + + if (options.metadata && options.metadata.length > 0) { + item[METADATA_ATTRIBUTE] = { + L: options.metadata.map(({ key, value }) => ({ + M: { + key: { S: key }, + value: { S: value }, + }, + })), + }; + } + + await getDynamoDbClient().send( + new PutItemCommand({ + TableName: this.config.tableName, + Item: item, + ConditionExpression: 'attribute_not_exists(#id)', + ExpressionAttributeNames: { + '#id': ID_ATTRIBUTE, + }, + }), + ); + } + + async houseKeeper(): Promise { + // DynamoDB TTL removes expired runner config records without a scan/delete job. + } +} diff --git a/lambdas/libs/storage-providers/aws/dynamodb/runner-group-cache-store.test.ts b/lambdas/libs/storage-providers/aws/dynamodb/runner-group-cache-store.test.ts new file mode 100644 index 0000000000..2bb335874b --- /dev/null +++ b/lambdas/libs/storage-providers/aws/dynamodb/runner-group-cache-store.test.ts @@ -0,0 +1,105 @@ +import { DynamoDBClient, GetItemCommand, PutItemCommand } from '@aws-sdk/client-dynamodb'; +import { mockClient } from 'aws-sdk-client-mock'; +import 'aws-sdk-client-mock-jest/vitest'; +import { beforeEach, describe, expect, it } from 'vitest'; + +import { resetDynamoDbClient } from './client'; +import { createAwsDynamoDbRunnerGroupCacheStore } from './runner-group-cache-store'; + +const mockDynamoDbClient = mockClient(DynamoDBClient); +const cleanEnv = process.env; + +describe('aws_dynamodb runner group cache store', () => { + beforeEach(() => { + mockDynamoDbClient.reset(); + resetDynamoDbClient(); + process.env = { ...cleanEnv }; + process.env.AWS_REGION = 'eu-west-1'; + process.env.RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME = 'runner-configuration'; + process.env.RUNNER_CONFIG_DYNAMODB_CONFIG_KEY_PREFIX = 'config#'; + }); + + it('gets a runner group id with a strongly consistent projected read', async () => { + mockDynamoDbClient.on(GetItemCommand).resolves({ Item: { value: { S: '42' } } }); + const store = createAwsDynamoDbRunnerGroupCacheStore(); + + await expect(store.get('Default')).resolves.toBe(42); + expect(mockDynamoDbClient).toHaveReceivedCommandWith(GetItemCommand, { + TableName: 'runner-configuration', + Key: { + id: { S: 'config#runner-group#Default' }, + }, + ConsistentRead: true, + ProjectionExpression: '#value', + ExpressionAttributeNames: { + '#value': 'value', + }, + }); + }); + + it('returns undefined when the runner group is not cached', async () => { + mockDynamoDbClient.on(GetItemCommand).resolves({}); + const store = createAwsDynamoDbRunnerGroupCacheStore(); + + await expect(store.get('Default')).resolves.toBeUndefined(); + }); + + it.each([ + [{ value: { N: '42' } }, 'non-string value'], + [{ value: { S: '42cached' } }, 'partially numeric value'], + [{ value: { S: '9007199254740992' } }, 'unsafe integer value'], + ])('rejects an invalid cached runner group id: %s', async (item) => { + mockDynamoDbClient.on(GetItemCommand).resolves({ Item: item }); + const store = createAwsDynamoDbRunnerGroupCacheStore(); + + await expect(store.get('Default')).rejects.toThrow( + "Runner group cache item 'config#runner-group#Default' has an invalid value", + ); + }); + + it('creates a runner group cache record without overwriting an existing record', async () => { + const store = createAwsDynamoDbRunnerGroupCacheStore(); + + await store.create({ runnerGroupName: 'Default', runnerGroupId: 42 }); + + expect(mockDynamoDbClient).toHaveReceivedCommandWith(PutItemCommand, { + TableName: 'runner-configuration', + Item: { + id: { S: 'config#runner-group#Default' }, + value: { S: '42' }, + }, + ConditionExpression: 'attribute_not_exists(#id)', + ExpressionAttributeNames: { + '#id': 'id', + }, + }); + }); + + it.each(['RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME', 'RUNNER_CONFIG_DYNAMODB_CONFIG_KEY_PREFIX'] as const)( + 'rejects a missing or blank %s', + (name) => { + delete process.env[name]; + expect(() => createAwsDynamoDbRunnerGroupCacheStore()).toThrow(`Environment variable ${name} is not set`); + + process.env[name] = ' '; + expect(() => createAwsDynamoDbRunnerGroupCacheStore()).toThrow(`Environment variable ${name} is not set`); + expect(mockDynamoDbClient.calls()).toHaveLength(0); + }, + ); + + it('propagates DynamoDB read errors', async () => { + const error = new Error('read failed'); + mockDynamoDbClient.on(GetItemCommand).rejects(error); + const store = createAwsDynamoDbRunnerGroupCacheStore(); + + await expect(store.get('Default')).rejects.toBe(error); + }); + + it('propagates DynamoDB write errors', async () => { + const error = new Error('conditional request failed'); + mockDynamoDbClient.on(PutItemCommand).rejects(error); + const store = createAwsDynamoDbRunnerGroupCacheStore(); + + await expect(store.create({ runnerGroupName: 'Default', runnerGroupId: 42 })).rejects.toBe(error); + }); +}); diff --git a/lambdas/libs/storage-providers/aws/dynamodb/runner-group-cache-store.ts b/lambdas/libs/storage-providers/aws/dynamodb/runner-group-cache-store.ts new file mode 100644 index 0000000000..4ac2b3587e --- /dev/null +++ b/lambdas/libs/storage-providers/aws/dynamodb/runner-group-cache-store.ts @@ -0,0 +1,78 @@ +import { GetItemCommand, PutItemCommand } from '@aws-sdk/client-dynamodb'; + +import type { RunnerGroupCacheRecord, RunnerGroupCacheStore } from '../../core'; +import { getDynamoDbClient } from './client'; +import { requiredEnvironmentValue } from './environment'; + +const ID_ATTRIBUTE = 'id'; +const VALUE_ATTRIBUTE = 'value'; +const RUNNER_GROUP_KEY = 'runner-group#'; + +interface AwsDynamoDbRunnerGroupCacheStoreConfig { + tableName: string; + configKeyPrefix: string; +} + +export function createAwsDynamoDbRunnerGroupCacheStore(): RunnerGroupCacheStore { + return new AwsDynamoDbRunnerGroupCacheStore({ + tableName: requiredEnvironmentValue('RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME'), + configKeyPrefix: requiredEnvironmentValue('RUNNER_CONFIG_DYNAMODB_CONFIG_KEY_PREFIX'), + }); +} + +class AwsDynamoDbRunnerGroupCacheStore implements RunnerGroupCacheStore { + constructor(private readonly config: AwsDynamoDbRunnerGroupCacheStoreConfig) {} + + async get(runnerGroupName: string): Promise { + const id = this.itemId(runnerGroupName); + const result = await getDynamoDbClient().send( + new GetItemCommand({ + TableName: this.config.tableName, + Key: { + [ID_ATTRIBUTE]: { S: id }, + }, + ConsistentRead: true, + ProjectionExpression: '#value', + ExpressionAttributeNames: { + '#value': VALUE_ATTRIBUTE, + }, + }), + ); + + if (!result.Item) { + return undefined; + } + + const value = result.Item[VALUE_ATTRIBUTE]?.S; + if (value === undefined || !/^\d+$/.test(value)) { + throw new Error(`Runner group cache item '${id}' has an invalid value`); + } + + const runnerGroupId = Number(value); + if (!Number.isSafeInteger(runnerGroupId)) { + throw new Error(`Runner group cache item '${id}' has an invalid value`); + } + + return runnerGroupId; + } + + async create(record: RunnerGroupCacheRecord): Promise { + await getDynamoDbClient().send( + new PutItemCommand({ + TableName: this.config.tableName, + Item: { + [ID_ATTRIBUTE]: { S: this.itemId(record.runnerGroupName) }, + [VALUE_ATTRIBUTE]: { S: record.runnerGroupId.toString() }, + }, + ConditionExpression: 'attribute_not_exists(#id)', + ExpressionAttributeNames: { + '#id': ID_ATTRIBUTE, + }, + }), + ); + } + + private itemId(runnerGroupName: string): string { + return `${this.config.configKeyPrefix}${RUNNER_GROUP_KEY}${runnerGroupName}`; + } +} diff --git a/lambdas/libs/storage-providers/aws/dynamodb/runner-matcher-config-store.test.ts b/lambdas/libs/storage-providers/aws/dynamodb/runner-matcher-config-store.test.ts new file mode 100644 index 0000000000..a8960e3f56 --- /dev/null +++ b/lambdas/libs/storage-providers/aws/dynamodb/runner-matcher-config-store.test.ts @@ -0,0 +1,94 @@ +import { DynamoDBClient, GetItemCommand } from '@aws-sdk/client-dynamodb'; +import { mockClient } from 'aws-sdk-client-mock'; +import 'aws-sdk-client-mock-jest/vitest'; +import { beforeEach, describe, expect, it } from 'vitest'; + +import { resetDynamoDbClient } from './client'; +import { createAwsDynamoDbRunnerMatcherConfigStore } from './runner-matcher-config-store'; + +const mockDynamoDbClient = mockClient(DynamoDBClient); +const cleanEnv = process.env; + +describe('aws_dynamodb runner matcher config store', () => { + beforeEach(() => { + mockDynamoDbClient.reset(); + resetDynamoDbClient(); + process.env = { ...cleanEnv }; + process.env.AWS_REGION = 'eu-west-1'; + process.env.RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME = 'runner-configuration'; + process.env.RUNNER_CONFIG_DYNAMODB_CONFIG_KEY_PREFIX = 'config#'; + }); + + it('gets the matcher config with a strongly consistent projected read', async () => { + mockDynamoDbClient.on(GetItemCommand).resolves({ Item: { value: { S: '[{"id":"runner"}]' } } }); + const store = createAwsDynamoDbRunnerMatcherConfigStore(); + + await expect(store.get()).resolves.toBe('[{"id":"runner"}]'); + expect(mockDynamoDbClient).toHaveReceivedCommandWith(GetItemCommand, { + TableName: 'runner-configuration', + Key: { + id: { S: 'config#runner-matcher-config' }, + }, + ConsistentRead: true, + ProjectionExpression: '#value', + ExpressionAttributeNames: { + '#value': 'value', + }, + }); + }); + + it('returns an empty stored string for validation by the webhook config loader', async () => { + mockDynamoDbClient.on(GetItemCommand).resolves({ Item: { value: { S: '' } } }); + const store = createAwsDynamoDbRunnerMatcherConfigStore(); + + await expect(store.get()).resolves.toBe(''); + }); + + it('rejects a missing matcher config item', async () => { + mockDynamoDbClient.on(GetItemCommand).resolves({}); + const store = createAwsDynamoDbRunnerMatcherConfigStore(); + + await expect(store.get()).rejects.toThrow( + "Runner matcher config item 'config#runner-matcher-config' was not found", + ); + }); + + it('rejects a matcher config item without a string value', async () => { + mockDynamoDbClient.on(GetItemCommand).resolves({ Item: { value: { N: '1' } } }); + const store = createAwsDynamoDbRunnerMatcherConfigStore(); + + await expect(store.get()).rejects.toThrow( + "Runner matcher config item 'config#runner-matcher-config' does not contain a string value", + ); + }); + + it.each(['RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME', 'RUNNER_CONFIG_DYNAMODB_CONFIG_KEY_PREFIX'] as const)( + 'rejects a missing or blank %s', + (name) => { + delete process.env[name]; + expect(() => createAwsDynamoDbRunnerMatcherConfigStore()).toThrow(`Environment variable ${name} is not set`); + + process.env[name] = ' '; + expect(() => createAwsDynamoDbRunnerMatcherConfigStore()).toThrow(`Environment variable ${name} is not set`); + expect(mockDynamoDbClient.calls()).toHaveLength(0); + }, + ); + + it('propagates DynamoDB read errors', async () => { + const error = new Error('read failed'); + mockDynamoDbClient.on(GetItemCommand).rejects(error); + const store = createAwsDynamoDbRunnerMatcherConfigStore(); + + await expect(store.get()).rejects.toBe(error); + }); + + it('reuses the memoised client across reads', async () => { + mockDynamoDbClient.on(GetItemCommand).resolves({ Item: { value: { S: '[]' } } }); + const store = createAwsDynamoDbRunnerMatcherConfigStore(); + + await store.get(); + await store.get(); + + expect(mockDynamoDbClient.commandCalls(GetItemCommand)).toHaveLength(2); + }); +}); diff --git a/lambdas/libs/storage-providers/aws/dynamodb/runner-matcher-config-store.ts b/lambdas/libs/storage-providers/aws/dynamodb/runner-matcher-config-store.ts new file mode 100644 index 0000000000..dce975b5de --- /dev/null +++ b/lambdas/libs/storage-providers/aws/dynamodb/runner-matcher-config-store.ts @@ -0,0 +1,53 @@ +import { GetItemCommand } from '@aws-sdk/client-dynamodb'; + +import type { RunnerMatcherConfigStore } from '../../core'; +import { getDynamoDbClient } from './client'; +import { requiredEnvironmentValue } from './environment'; + +const ID_ATTRIBUTE = 'id'; +const VALUE_ATTRIBUTE = 'value'; +const RUNNER_MATCHER_CONFIG_KEY = 'runner-matcher-config'; + +interface AwsDynamoDbRunnerMatcherConfigStoreConfig { + tableName: string; + configKeyPrefix: string; +} + +export function createAwsDynamoDbRunnerMatcherConfigStore(): RunnerMatcherConfigStore { + return new AwsDynamoDbRunnerMatcherConfigStore({ + tableName: requiredEnvironmentValue('RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME'), + configKeyPrefix: requiredEnvironmentValue('RUNNER_CONFIG_DYNAMODB_CONFIG_KEY_PREFIX'), + }); +} + +class AwsDynamoDbRunnerMatcherConfigStore implements RunnerMatcherConfigStore { + constructor(private readonly config: AwsDynamoDbRunnerMatcherConfigStoreConfig) {} + + async get(): Promise { + const id = `${this.config.configKeyPrefix}${RUNNER_MATCHER_CONFIG_KEY}`; + const result = await getDynamoDbClient().send( + new GetItemCommand({ + TableName: this.config.tableName, + Key: { + [ID_ATTRIBUTE]: { S: id }, + }, + ConsistentRead: true, + ProjectionExpression: '#value', + ExpressionAttributeNames: { + '#value': VALUE_ATTRIBUTE, + }, + }), + ); + + if (!result.Item) { + throw new Error(`Runner matcher config item '${id}' was not found`); + } + + const value = result.Item[VALUE_ATTRIBUTE]?.S; + if (value === undefined) { + throw new Error(`Runner matcher config item '${id}' does not contain a string value`); + } + + return value; + } +} diff --git a/lambdas/libs/storage-providers/github-app-credentials.test.ts b/lambdas/libs/storage-providers/github-app-credentials.test.ts new file mode 100644 index 0000000000..f043f789ad --- /dev/null +++ b/lambdas/libs/storage-providers/github-app-credentials.test.ts @@ -0,0 +1,70 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { createAwsSsmGitHubAppCredentialsStore } from './aws/ssm/github-app-credentials-store'; +import type { GitHubAppCredentialsStore } from './core'; +import { getGitHubAppCredentialsStore, resetGitHubAppCredentialsStore } from './github-app-credentials'; + +vi.mock('./aws/ssm/github-app-credentials-store', () => ({ + createAwsSsmGitHubAppCredentialsStore: vi.fn(), +})); + +const createAwsSsmGitHubAppCredentialsStoreMock = vi.mocked(createAwsSsmGitHubAppCredentialsStore); +const cleanEnv = process.env; + +describe('GitHub App credentials store', () => { + beforeEach(() => { + vi.clearAllMocks(); + process.env = { ...cleanEnv }; + delete process.env.RUNNER_CONFIG_STORAGE_PROVIDER; + resetGitHubAppCredentialsStore(); + }); + + it.each([undefined, 'aws_ssm', 'aws_dynamodb', 'not-registered'])( + 'remains on aws_ssm for runner config provider input %j', + (provider) => { + setProvider(provider); + const store = stubStore(); + + expect(getGitHubAppCredentialsStore()).toBe(store); + expect(createAwsSsmGitHubAppCredentialsStoreMock).toHaveBeenCalledOnce(); + }, + ); + + it('creates the store lazily and caches it', () => { + const store = stubStore(); + + expect(createAwsSsmGitHubAppCredentialsStoreMock).not.toHaveBeenCalled(); + const first = getGitHubAppCredentialsStore(); + const second = getGitHubAppCredentialsStore(); + + expect(first).toBe(store); + expect(second).toBe(store); + expect(createAwsSsmGitHubAppCredentialsStoreMock).toHaveBeenCalledOnce(); + }); + + it('selects again after the test reset', () => { + const firstStore = stubStore(); + expect(getGitHubAppCredentialsStore()).toBe(firstStore); + + const secondStore = { get: vi.fn() } satisfies GitHubAppCredentialsStore; + createAwsSsmGitHubAppCredentialsStoreMock.mockReturnValue(secondStore); + resetGitHubAppCredentialsStore(); + + expect(getGitHubAppCredentialsStore()).toBe(secondStore); + expect(createAwsSsmGitHubAppCredentialsStoreMock).toHaveBeenCalledTimes(2); + }); +}); + +function setProvider(provider: string | undefined): void { + if (provider === undefined) { + delete process.env.RUNNER_CONFIG_STORAGE_PROVIDER; + } else { + process.env.RUNNER_CONFIG_STORAGE_PROVIDER = provider; + } +} + +function stubStore(): GitHubAppCredentialsStore { + const store = { get: vi.fn() } satisfies GitHubAppCredentialsStore; + createAwsSsmGitHubAppCredentialsStoreMock.mockReturnValue(store); + return store; +} diff --git a/lambdas/libs/storage-providers/github-app-credentials.ts b/lambdas/libs/storage-providers/github-app-credentials.ts new file mode 100644 index 0000000000..c6189bb604 --- /dev/null +++ b/lambdas/libs/storage-providers/github-app-credentials.ts @@ -0,0 +1,15 @@ +import { createAwsSsmGitHubAppCredentialsStore } from './aws/ssm/github-app-credentials-store'; +import type { GitHubAppCredentialsStore } from './core'; + +let githubAppCredentialsStore: GitHubAppCredentialsStore | undefined; + +export function getGitHubAppCredentialsStore(): GitHubAppCredentialsStore { + // GitHub App credentials remain in SSM independently of runner config storage selection. + githubAppCredentialsStore ??= createAwsSsmGitHubAppCredentialsStore(); + return githubAppCredentialsStore; +} + +// Test-only reset for cases that need to exercise first-use environment selection. +export function resetGitHubAppCredentialsStore(): void { + githubAppCredentialsStore = undefined; +} diff --git a/lambdas/libs/storage-providers/github-webhook-secret.test.ts b/lambdas/libs/storage-providers/github-webhook-secret.test.ts index 5888e735b0..b4b742733a 100644 --- a/lambdas/libs/storage-providers/github-webhook-secret.test.ts +++ b/lambdas/libs/storage-providers/github-webhook-secret.test.ts @@ -11,7 +11,7 @@ vi.mock('./aws/ssm/github-webhook-secret-store', () => ({ const createAwsSsmGitHubWebhookSecretStoreMock = vi.mocked(createAwsSsmGitHubWebhookSecretStore); const cleanEnv = process.env; -describe('GitHub webhook secret store selection', () => { +describe('GitHub webhook secret store', () => { beforeEach(() => { vi.clearAllMocks(); process.env = { ...cleanEnv }; @@ -19,35 +19,22 @@ describe('GitHub webhook secret store selection', () => { resetGitHubWebhookSecretStore(); }); - it.each([undefined, '', ' '])('uses aws_ssm for default selector input %j', (provider) => { - setProvider(provider); - const store = stubStore(); - - expect(getGitHubWebhookSecretStore()).toBe(store); - expect(createAwsSsmGitHubWebhookSecretStoreMock).toHaveBeenCalledOnce(); - }); - - it.each(['aws_ssm', ' AWS_SSM '])('uses aws_ssm for explicit selector input %j', (provider) => { - process.env.RUNNER_CONFIG_STORAGE_PROVIDER = provider; - const store = stubStore(); + it.each([undefined, 'aws_ssm', 'aws_dynamodb', 'not-registered'])( + 'remains on aws_ssm for runner config provider input %j', + (provider) => { + setProvider(provider); + const store = stubStore(); - expect(getGitHubWebhookSecretStore()).toBe(store); - expect(createAwsSsmGitHubWebhookSecretStoreMock).toHaveBeenCalledOnce(); - }); - - it('rejects an unsupported provider on first use', () => { - process.env.RUNNER_CONFIG_STORAGE_PROVIDER = 'not-registered'; - - expect(() => getGitHubWebhookSecretStore()).toThrow("Unsupported runner config storage provider 'not-registered'"); - expect(createAwsSsmGitHubWebhookSecretStoreMock).not.toHaveBeenCalled(); - }); + expect(getGitHubWebhookSecretStore()).toBe(store); + expect(createAwsSsmGitHubWebhookSecretStoreMock).toHaveBeenCalledOnce(); + }, + ); - it('selects lazily and caches the created store', () => { + it('creates the store lazily and caches it', () => { const store = stubStore(); expect(createAwsSsmGitHubWebhookSecretStoreMock).not.toHaveBeenCalled(); const first = getGitHubWebhookSecretStore(); - process.env.RUNNER_CONFIG_STORAGE_PROVIDER = 'not-registered'; const second = getGitHubWebhookSecretStore(); expect(first).toBe(store); diff --git a/lambdas/libs/storage-providers/github-webhook-secret.ts b/lambdas/libs/storage-providers/github-webhook-secret.ts index f13df08718..f6abfc5349 100644 --- a/lambdas/libs/storage-providers/github-webhook-secret.ts +++ b/lambdas/libs/storage-providers/github-webhook-secret.ts @@ -1,19 +1,11 @@ import { createAwsSsmGitHubWebhookSecretStore } from './aws/ssm/github-webhook-secret-store'; import type { GitHubWebhookSecretStore } from './core'; -import type {} from './environment'; -import { resolveRunnerConfigStorageProvider, type RunnerConfigStorageProvider } from './provider'; - -type GitHubWebhookSecretStoreFactory = () => GitHubWebhookSecretStore; - -const providerFactories = { - aws_ssm: createAwsSsmGitHubWebhookSecretStore, -} as const satisfies Record; let githubWebhookSecretStore: GitHubWebhookSecretStore | undefined; export function getGitHubWebhookSecretStore(): GitHubWebhookSecretStore { - githubWebhookSecretStore ??= - providerFactories[resolveRunnerConfigStorageProvider(process.env.RUNNER_CONFIG_STORAGE_PROVIDER)](); + // The webhook secret remains in SSM independently of runner config storage selection. + githubWebhookSecretStore ??= createAwsSsmGitHubWebhookSecretStore(); return githubWebhookSecretStore; } diff --git a/lambdas/libs/storage-providers/index.ts b/lambdas/libs/storage-providers/index.ts index fcd4bd9338..b4b28622cb 100644 --- a/lambdas/libs/storage-providers/index.ts +++ b/lambdas/libs/storage-providers/index.ts @@ -22,5 +22,8 @@ export { export type { RunnerConfigStorageProvider } from './provider'; export { createCommonStorage, createStorageProviders } from './storage-providers'; export type { StorageProviders, RunnerConfigStorage, CommonStorage } from './core'; +export { getGitHubAppCredentialsStore, resetGitHubAppCredentialsStore } from './github-app-credentials'; +export { getRunnerConfigStore, resetRunnerConfigStore } from './runner-config'; +export { getRunnerGroupCacheStore, resetRunnerGroupCacheStore } from './runner-group-cache'; export { getGitHubWebhookSecretStore, resetGitHubWebhookSecretStore } from './github-webhook-secret'; export { getRunnerMatcherConfigStore, resetRunnerMatcherConfigStore } from './runner-matcher-config'; diff --git a/lambdas/libs/storage-providers/package.json b/lambdas/libs/storage-providers/package.json index 330d60a3f6..1a8687ef32 100644 --- a/lambdas/libs/storage-providers/package.json +++ b/lambdas/libs/storage-providers/package.json @@ -20,6 +20,7 @@ "dependencies": { "@aws-github-runner/aws-powertools-util": "*", "@aws-github-runner/aws-ssm-util": "*", + "@aws-sdk/client-dynamodb": "^3.1009.0", "@aws-sdk/client-ssm": "^3.1009.0" }, "devDependencies": { diff --git a/lambdas/libs/storage-providers/provider.ts b/lambdas/libs/storage-providers/provider.ts index ff9ecb73cc..cf1e965085 100644 --- a/lambdas/libs/storage-providers/provider.ts +++ b/lambdas/libs/storage-providers/provider.ts @@ -1,7 +1,8 @@ export const runnerConfigStorageProvider = { awsSsm: 'aws_ssm', + awsDynamodb: 'aws_dynamodb', } as const; -export const runnerConfigStorageProviders = [runnerConfigStorageProvider.awsSsm] as const; +export const runnerConfigStorageProviders = [runnerConfigStorageProvider.awsSsm, runnerConfigStorageProvider.awsDynamodb] as const; export type RunnerConfigStorageProvider = (typeof runnerConfigStorageProviders)[number]; diff --git a/lambdas/libs/storage-providers/runner-config.test.ts b/lambdas/libs/storage-providers/runner-config.test.ts new file mode 100644 index 0000000000..0c85093fa0 --- /dev/null +++ b/lambdas/libs/storage-providers/runner-config.test.ts @@ -0,0 +1,108 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { createAwsDynamoDbRunnerConfigStore } from './aws/dynamodb/runner-config-store'; +import { createAwsSsmRunnerConfigStore } from './aws/ssm/runner-config-store'; +import type { RunnerConfigStore } from './core'; +import { getRunnerConfigStore, resetRunnerConfigStore } from './runner-config'; + +vi.mock('./aws/dynamodb/runner-config-store', () => ({ + createAwsDynamoDbRunnerConfigStore: vi.fn(), +})); +vi.mock('./aws/ssm/runner-config-store', () => ({ + createAwsSsmRunnerConfigStore: vi.fn(), +})); + +const createAwsDynamoDbRunnerConfigStoreMock = vi.mocked(createAwsDynamoDbRunnerConfigStore); +const createAwsSsmRunnerConfigStoreMock = vi.mocked(createAwsSsmRunnerConfigStore); +const cleanEnv = process.env; + +describe('runner config store selection', () => { + beforeEach(() => { + vi.clearAllMocks(); + process.env = { ...cleanEnv }; + delete process.env.RUNNER_CONFIG_STORAGE_PROVIDER; + resetRunnerConfigStore(); + }); + + it.each([undefined, '', ' '])('uses aws_ssm for default selector input %j', (provider) => { + setProvider(provider); + const store = stubStore(); + + expect(getRunnerConfigStore()).toBe(store); + expect(createAwsSsmRunnerConfigStoreMock).toHaveBeenCalledOnce(); + expect(createAwsDynamoDbRunnerConfigStoreMock).not.toHaveBeenCalled(); + }); + + it.each(['aws_ssm', ' AWS_SSM '])('uses aws_ssm for explicit selector input %j', (provider) => { + process.env.RUNNER_CONFIG_STORAGE_PROVIDER = provider; + const store = stubStore(); + + expect(getRunnerConfigStore()).toBe(store); + expect(createAwsSsmRunnerConfigStoreMock).toHaveBeenCalledOnce(); + expect(createAwsDynamoDbRunnerConfigStoreMock).not.toHaveBeenCalled(); + }); + + it.each(['aws_dynamodb', ' AWS_DYNAMODB '])('uses aws_dynamodb for explicit selector input %j', (provider) => { + process.env.RUNNER_CONFIG_STORAGE_PROVIDER = provider; + const store = stubDynamoDbStore(); + + expect(getRunnerConfigStore()).toBe(store); + expect(createAwsDynamoDbRunnerConfigStoreMock).toHaveBeenCalledOnce(); + expect(createAwsSsmRunnerConfigStoreMock).not.toHaveBeenCalled(); + }); + + it('rejects an unsupported provider on first use', () => { + process.env.RUNNER_CONFIG_STORAGE_PROVIDER = 'not-registered'; + + expect(createAwsSsmRunnerConfigStoreMock).not.toHaveBeenCalled(); + expect(createAwsDynamoDbRunnerConfigStoreMock).not.toHaveBeenCalled(); + expect(() => getRunnerConfigStore()).toThrow("Unsupported runner config storage provider 'not-registered'"); + expect(createAwsSsmRunnerConfigStoreMock).not.toHaveBeenCalled(); + expect(createAwsDynamoDbRunnerConfigStoreMock).not.toHaveBeenCalled(); + }); + + it('selects lazily and caches the created store', () => { + const store = stubStore(); + + expect(createAwsSsmRunnerConfigStoreMock).not.toHaveBeenCalled(); + const first = getRunnerConfigStore(); + process.env.RUNNER_CONFIG_STORAGE_PROVIDER = 'not-registered'; + const second = getRunnerConfigStore(); + + expect(first).toBe(store); + expect(second).toBe(store); + expect(createAwsSsmRunnerConfigStoreMock).toHaveBeenCalledOnce(); + }); + + it('selects again after the test reset', () => { + const firstStore = stubStore(); + expect(getRunnerConfigStore()).toBe(firstStore); + + const secondStore = { create: vi.fn(), houseKeeper: vi.fn() } satisfies RunnerConfigStore; + createAwsSsmRunnerConfigStoreMock.mockReturnValue(secondStore); + resetRunnerConfigStore(); + + expect(getRunnerConfigStore()).toBe(secondStore); + expect(createAwsSsmRunnerConfigStoreMock).toHaveBeenCalledTimes(2); + }); +}); + +function setProvider(provider: string | undefined): void { + if (provider === undefined) { + delete process.env.RUNNER_CONFIG_STORAGE_PROVIDER; + } else { + process.env.RUNNER_CONFIG_STORAGE_PROVIDER = provider; + } +} + +function stubStore(): RunnerConfigStore { + const store = { create: vi.fn(), houseKeeper: vi.fn() } satisfies RunnerConfigStore; + createAwsSsmRunnerConfigStoreMock.mockReturnValue(store); + return store; +} + +function stubDynamoDbStore(): RunnerConfigStore { + const store = { create: vi.fn(), houseKeeper: vi.fn() } satisfies RunnerConfigStore; + createAwsDynamoDbRunnerConfigStoreMock.mockReturnValue(store); + return store; +} diff --git a/lambdas/libs/storage-providers/runner-config.ts b/lambdas/libs/storage-providers/runner-config.ts new file mode 100644 index 0000000000..d4d3998d15 --- /dev/null +++ b/lambdas/libs/storage-providers/runner-config.ts @@ -0,0 +1,25 @@ +import { createAwsDynamoDbRunnerConfigStore } from './aws/dynamodb/runner-config-store'; +import { createAwsSsmRunnerConfigStore } from './aws/ssm/runner-config-store'; +import type { RunnerConfigStore } from './core'; +import type {} from './environment'; +import { resolveRunnerConfigStorageProvider, type RunnerConfigStorageProvider } from './provider'; + +type RunnerConfigStoreFactory = () => RunnerConfigStore; + +const providerFactories = { + aws_ssm: createAwsSsmRunnerConfigStore, + aws_dynamodb: createAwsDynamoDbRunnerConfigStore, +} as const satisfies Record; + +let runnerConfigStore: RunnerConfigStore | undefined; + +export function getRunnerConfigStore(): RunnerConfigStore { + runnerConfigStore ??= + providerFactories[resolveRunnerConfigStorageProvider(process.env.RUNNER_CONFIG_STORAGE_PROVIDER)](); + return runnerConfigStore; +} + +// Test-only reset for cases that need to exercise first-use environment selection. +export function resetRunnerConfigStore(): void { + runnerConfigStore = undefined; +} diff --git a/lambdas/libs/storage-providers/runner-group-cache.test.ts b/lambdas/libs/storage-providers/runner-group-cache.test.ts new file mode 100644 index 0000000000..029e33be8a --- /dev/null +++ b/lambdas/libs/storage-providers/runner-group-cache.test.ts @@ -0,0 +1,106 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { createAwsDynamoDbRunnerGroupCacheStore } from './aws/dynamodb/runner-group-cache-store'; +import { createAwsSsmRunnerGroupCacheStore } from './aws/ssm/runner-group-cache-store'; +import type { RunnerGroupCacheStore } from './core'; +import { getRunnerGroupCacheStore, resetRunnerGroupCacheStore } from './runner-group-cache'; + +vi.mock('./aws/dynamodb/runner-group-cache-store', () => ({ + createAwsDynamoDbRunnerGroupCacheStore: vi.fn(), +})); +vi.mock('./aws/ssm/runner-group-cache-store', () => ({ + createAwsSsmRunnerGroupCacheStore: vi.fn(), +})); + +const createAwsDynamoDbRunnerGroupCacheStoreMock = vi.mocked(createAwsDynamoDbRunnerGroupCacheStore); +const createAwsSsmRunnerGroupCacheStoreMock = vi.mocked(createAwsSsmRunnerGroupCacheStore); +const cleanEnv = process.env; + +describe('runner group cache store selection', () => { + beforeEach(() => { + vi.clearAllMocks(); + process.env = { ...cleanEnv }; + delete process.env.RUNNER_CONFIG_STORAGE_PROVIDER; + resetRunnerGroupCacheStore(); + }); + + it.each([undefined, '', ' '])('uses aws_ssm for default selector input %j', (provider) => { + setProvider(provider); + const store = stubStore(); + + expect(getRunnerGroupCacheStore()).toBe(store); + expect(createAwsSsmRunnerGroupCacheStoreMock).toHaveBeenCalledOnce(); + expect(createAwsDynamoDbRunnerGroupCacheStoreMock).not.toHaveBeenCalled(); + }); + + it.each(['aws_ssm', ' AWS_SSM '])('uses aws_ssm for explicit selector input %j', (provider) => { + process.env.RUNNER_CONFIG_STORAGE_PROVIDER = provider; + const store = stubStore(); + + expect(getRunnerGroupCacheStore()).toBe(store); + expect(createAwsSsmRunnerGroupCacheStoreMock).toHaveBeenCalledOnce(); + expect(createAwsDynamoDbRunnerGroupCacheStoreMock).not.toHaveBeenCalled(); + }); + + it.each(['aws_dynamodb', ' AWS_DYNAMODB '])('uses aws_dynamodb for explicit selector input %j', (provider) => { + process.env.RUNNER_CONFIG_STORAGE_PROVIDER = provider; + const store = stubDynamoDbStore(); + + expect(getRunnerGroupCacheStore()).toBe(store); + expect(createAwsDynamoDbRunnerGroupCacheStoreMock).toHaveBeenCalledOnce(); + expect(createAwsSsmRunnerGroupCacheStoreMock).not.toHaveBeenCalled(); + }); + + it('rejects an unsupported provider on first use', () => { + process.env.RUNNER_CONFIG_STORAGE_PROVIDER = 'not-registered'; + + expect(() => getRunnerGroupCacheStore()).toThrow("Unsupported runner config storage provider 'not-registered'"); + expect(createAwsSsmRunnerGroupCacheStoreMock).not.toHaveBeenCalled(); + expect(createAwsDynamoDbRunnerGroupCacheStoreMock).not.toHaveBeenCalled(); + }); + + it('selects lazily and caches the created store', () => { + const store = stubStore(); + + expect(createAwsSsmRunnerGroupCacheStoreMock).not.toHaveBeenCalled(); + const first = getRunnerGroupCacheStore(); + process.env.RUNNER_CONFIG_STORAGE_PROVIDER = 'not-registered'; + const second = getRunnerGroupCacheStore(); + + expect(first).toBe(store); + expect(second).toBe(store); + expect(createAwsSsmRunnerGroupCacheStoreMock).toHaveBeenCalledOnce(); + }); + + it('selects again after the test reset', () => { + const firstStore = stubStore(); + expect(getRunnerGroupCacheStore()).toBe(firstStore); + + const secondStore = { get: vi.fn(), create: vi.fn() } satisfies RunnerGroupCacheStore; + createAwsSsmRunnerGroupCacheStoreMock.mockReturnValue(secondStore); + resetRunnerGroupCacheStore(); + + expect(getRunnerGroupCacheStore()).toBe(secondStore); + expect(createAwsSsmRunnerGroupCacheStoreMock).toHaveBeenCalledTimes(2); + }); +}); + +function setProvider(provider: string | undefined): void { + if (provider === undefined) { + delete process.env.RUNNER_CONFIG_STORAGE_PROVIDER; + } else { + process.env.RUNNER_CONFIG_STORAGE_PROVIDER = provider; + } +} + +function stubStore(): RunnerGroupCacheStore { + const store = { get: vi.fn(), create: vi.fn() } satisfies RunnerGroupCacheStore; + createAwsSsmRunnerGroupCacheStoreMock.mockReturnValue(store); + return store; +} + +function stubDynamoDbStore(): RunnerGroupCacheStore { + const store = { get: vi.fn(), create: vi.fn() } satisfies RunnerGroupCacheStore; + createAwsDynamoDbRunnerGroupCacheStoreMock.mockReturnValue(store); + return store; +} diff --git a/lambdas/libs/storage-providers/runner-group-cache.ts b/lambdas/libs/storage-providers/runner-group-cache.ts new file mode 100644 index 0000000000..3a91437755 --- /dev/null +++ b/lambdas/libs/storage-providers/runner-group-cache.ts @@ -0,0 +1,25 @@ +import { createAwsDynamoDbRunnerGroupCacheStore } from './aws/dynamodb/runner-group-cache-store'; +import { createAwsSsmRunnerGroupCacheStore } from './aws/ssm/runner-group-cache-store'; +import type { RunnerGroupCacheStore } from './core'; +import type {} from './environment'; +import { resolveRunnerConfigStorageProvider, type RunnerConfigStorageProvider } from './provider'; + +type RunnerGroupCacheStoreFactory = () => RunnerGroupCacheStore; + +const providerFactories = { + aws_ssm: createAwsSsmRunnerGroupCacheStore, + aws_dynamodb: createAwsDynamoDbRunnerGroupCacheStore, +} as const satisfies Record; + +let runnerGroupCacheStore: RunnerGroupCacheStore | undefined; + +export function getRunnerGroupCacheStore(): RunnerGroupCacheStore { + runnerGroupCacheStore ??= + providerFactories[resolveRunnerConfigStorageProvider(process.env.RUNNER_CONFIG_STORAGE_PROVIDER)](); + return runnerGroupCacheStore; +} + +// Test-only reset for cases that need to exercise first-use environment selection. +export function resetRunnerGroupCacheStore(): void { + runnerGroupCacheStore = undefined; +} diff --git a/lambdas/libs/storage-providers/runner-matcher-config.test.ts b/lambdas/libs/storage-providers/runner-matcher-config.test.ts index 0dd7f42ad3..981ff28567 100644 --- a/lambdas/libs/storage-providers/runner-matcher-config.test.ts +++ b/lambdas/libs/storage-providers/runner-matcher-config.test.ts @@ -1,13 +1,18 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { createAwsDynamoDbRunnerMatcherConfigStore } from './aws/dynamodb/runner-matcher-config-store'; import { createAwsSsmRunnerMatcherConfigStore } from './aws/ssm/runner-matcher-config-store'; import type { RunnerMatcherConfigStore } from './core'; import { getRunnerMatcherConfigStore, resetRunnerMatcherConfigStore } from './runner-matcher-config'; +vi.mock('./aws/dynamodb/runner-matcher-config-store', () => ({ + createAwsDynamoDbRunnerMatcherConfigStore: vi.fn(), +})); vi.mock('./aws/ssm/runner-matcher-config-store', () => ({ createAwsSsmRunnerMatcherConfigStore: vi.fn(), })); +const createAwsDynamoDbRunnerMatcherConfigStoreMock = vi.mocked(createAwsDynamoDbRunnerMatcherConfigStore); const createAwsSsmRunnerMatcherConfigStoreMock = vi.mocked(createAwsSsmRunnerMatcherConfigStore); const cleanEnv = process.env; @@ -25,6 +30,7 @@ describe('runner matcher config store selection', () => { expect(getRunnerMatcherConfigStore()).toBe(store); expect(createAwsSsmRunnerMatcherConfigStoreMock).toHaveBeenCalledOnce(); + expect(createAwsDynamoDbRunnerMatcherConfigStoreMock).not.toHaveBeenCalled(); }); it.each(['aws_ssm', ' AWS_SSM '])('uses aws_ssm for explicit selector input %j', (provider) => { @@ -33,6 +39,16 @@ describe('runner matcher config store selection', () => { expect(getRunnerMatcherConfigStore()).toBe(store); expect(createAwsSsmRunnerMatcherConfigStoreMock).toHaveBeenCalledOnce(); + expect(createAwsDynamoDbRunnerMatcherConfigStoreMock).not.toHaveBeenCalled(); + }); + + it.each(['aws_dynamodb', ' AWS_DYNAMODB '])('uses aws_dynamodb for explicit selector input %j', (provider) => { + process.env.RUNNER_CONFIG_STORAGE_PROVIDER = provider; + const store = stubDynamoDbStore(); + + expect(getRunnerMatcherConfigStore()).toBe(store); + expect(createAwsDynamoDbRunnerMatcherConfigStoreMock).toHaveBeenCalledOnce(); + expect(createAwsSsmRunnerMatcherConfigStoreMock).not.toHaveBeenCalled(); }); it('rejects an unsupported provider on first use', () => { @@ -40,6 +56,7 @@ describe('runner matcher config store selection', () => { expect(() => getRunnerMatcherConfigStore()).toThrow("Unsupported runner config storage provider 'not-registered'"); expect(createAwsSsmRunnerMatcherConfigStoreMock).not.toHaveBeenCalled(); + expect(createAwsDynamoDbRunnerMatcherConfigStoreMock).not.toHaveBeenCalled(); }); it('selects lazily and caches the created store', () => { @@ -81,3 +98,9 @@ function stubStore(): RunnerMatcherConfigStore { createAwsSsmRunnerMatcherConfigStoreMock.mockReturnValue(store); return store; } + +function stubDynamoDbStore(): RunnerMatcherConfigStore { + const store = { get: vi.fn() } satisfies RunnerMatcherConfigStore; + createAwsDynamoDbRunnerMatcherConfigStoreMock.mockReturnValue(store); + return store; +} diff --git a/lambdas/libs/storage-providers/runner-matcher-config.ts b/lambdas/libs/storage-providers/runner-matcher-config.ts index 6d56d49754..c121fc2aaf 100644 --- a/lambdas/libs/storage-providers/runner-matcher-config.ts +++ b/lambdas/libs/storage-providers/runner-matcher-config.ts @@ -1,3 +1,4 @@ +import { createAwsDynamoDbRunnerMatcherConfigStore } from './aws/dynamodb/runner-matcher-config-store'; import { createAwsSsmRunnerMatcherConfigStore } from './aws/ssm/runner-matcher-config-store'; import type { RunnerMatcherConfigStore } from './core'; import type {} from './environment'; @@ -7,6 +8,7 @@ type RunnerMatcherConfigStoreFactory = () => RunnerMatcherConfigStore; const providerFactories = { aws_ssm: createAwsSsmRunnerMatcherConfigStore, + aws_dynamodb: createAwsDynamoDbRunnerMatcherConfigStore, } as const satisfies Record; let runnerMatcherConfigStore: RunnerMatcherConfigStore | undefined; From bc402ab4fee128b1496c30049550d759649ec86b Mon Sep 17 00:00:00 2001 From: edersonbrilhante Date: Mon, 21 Sep 2026 22:24:38 +0200 Subject: [PATCH 02/11] feat(storage): add AWS DynamoDB storage provider (cherry picked from commit fc9cf6d80b517792c628824c7bc29d071e7c41c2) Signed-off-by: tehlers320 <16598119+tehlers320@users.noreply.github.com> --- .../aws/dynamodb/durable-config.ts | 37 +++ .../aws/dynamodb/environment.d.ts | 6 +- .../aws/dynamodb/environment.ts | 6 +- .../github-app-credentials-store.test.ts | 103 +++++++ .../dynamodb/github-app-credentials-store.ts | 89 ++++++ .../github-webhook-secret-store.test.ts | 74 +++++ .../dynamodb/github-webhook-secret-store.ts | 21 ++ .../aws/dynamodb/keys.test.ts | 50 ++++ .../storage-providers/aws/dynamodb/keys.ts | 34 +++ .../aws/dynamodb/runner-config-store.test.ts | 71 +++-- .../aws/dynamodb/runner-config-store.ts | 18 +- .../dynamodb/runner-group-cache-store.test.ts | 15 +- .../aws/dynamodb/runner-group-cache-store.ts | 32 +- .../runner-matcher-config-store.test.ts | 31 +- .../dynamodb/runner-matcher-config-store.ts | 40 +-- .../aws/dynamodb/capabilities.tf | 283 ++++++++++++++++++ .../aws/dynamodb/config-version.tf | 23 ++ .../storage-providers/aws/dynamodb/items.tf | 56 ++++ .../storage-providers/aws/dynamodb/outputs.tf | 71 +++++ .../storage-providers/aws/dynamodb/tables.tf | 62 ++++ .../aws/dynamodb/variables.tf | 84 ++++++ .../aws/dynamodb/versions.tf | 10 + 22 files changed, 1113 insertions(+), 103 deletions(-) create mode 100644 lambdas/libs/storage-providers/aws/dynamodb/durable-config.ts create mode 100644 lambdas/libs/storage-providers/aws/dynamodb/github-app-credentials-store.test.ts create mode 100644 lambdas/libs/storage-providers/aws/dynamodb/github-app-credentials-store.ts create mode 100644 lambdas/libs/storage-providers/aws/dynamodb/github-webhook-secret-store.test.ts create mode 100644 lambdas/libs/storage-providers/aws/dynamodb/github-webhook-secret-store.ts create mode 100644 lambdas/libs/storage-providers/aws/dynamodb/keys.test.ts create mode 100644 lambdas/libs/storage-providers/aws/dynamodb/keys.ts create mode 100644 modules/storage-providers/aws/dynamodb/capabilities.tf create mode 100644 modules/storage-providers/aws/dynamodb/config-version.tf create mode 100644 modules/storage-providers/aws/dynamodb/items.tf create mode 100644 modules/storage-providers/aws/dynamodb/outputs.tf create mode 100644 modules/storage-providers/aws/dynamodb/tables.tf create mode 100644 modules/storage-providers/aws/dynamodb/variables.tf create mode 100644 modules/storage-providers/aws/dynamodb/versions.tf diff --git a/lambdas/libs/storage-providers/aws/dynamodb/durable-config.ts b/lambdas/libs/storage-providers/aws/dynamodb/durable-config.ts new file mode 100644 index 0000000000..f22fde3269 --- /dev/null +++ b/lambdas/libs/storage-providers/aws/dynamodb/durable-config.ts @@ -0,0 +1,37 @@ +import { GetItemCommand } from '@aws-sdk/client-dynamodb'; + +import { getDynamoDbClient } from './client'; +import { ID_ATTRIBUTE, SCOPE_ATTRIBUTE, VALUE_ATTRIBUTE } from './keys'; + +export async function getDurableConfigValue( + tableName: string, + scope: string, + id: string, + description: string, +): Promise { + const result = await getDynamoDbClient().send( + new GetItemCommand({ + TableName: tableName, + Key: { + [SCOPE_ATTRIBUTE]: { S: scope }, + [ID_ATTRIBUTE]: { S: id }, + }, + ConsistentRead: true, + ProjectionExpression: '#value', + ExpressionAttributeNames: { + '#value': VALUE_ATTRIBUTE, + }, + }), + ); + + if (!result.Item) { + throw new Error(`${description} item '${scope}/${id}' was not found`); + } + + const value = result.Item[VALUE_ATTRIBUTE]?.S; + if (value === undefined) { + throw new Error(`${description} item '${scope}/${id}' does not contain a string value`); + } + + return value; +} diff --git a/lambdas/libs/storage-providers/aws/dynamodb/environment.d.ts b/lambdas/libs/storage-providers/aws/dynamodb/environment.d.ts index 80f6cd76b4..59be4dbf10 100644 --- a/lambdas/libs/storage-providers/aws/dynamodb/environment.d.ts +++ b/lambdas/libs/storage-providers/aws/dynamodb/environment.d.ts @@ -3,10 +3,10 @@ export {}; declare global { namespace NodeJS { interface ProcessEnv { - RUNNER_CONFIG_DYNAMODB_CONFIG_KEY_PREFIX?: string; RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME?: string; - RUNNER_CONFIG_DYNAMODB_TABLE_NAME?: string; - RUNNER_CONFIG_DYNAMODB_TOKEN_KEY_PREFIX?: string; + RUNNER_CONFIG_DYNAMODB_ENTRY_ID?: string; + RUNNER_CONFIG_DYNAMODB_RUNNER_STATE_TABLE_NAME?: string; + RUNNER_CONFIG_DYNAMODB_RUNNER_STATE_TTL_SECONDS?: string; RUNNER_CONFIG_DYNAMODB_TTL_SECONDS?: string; } } diff --git a/lambdas/libs/storage-providers/aws/dynamodb/environment.ts b/lambdas/libs/storage-providers/aws/dynamodb/environment.ts index 008df063f7..fc0a394139 100644 --- a/lambdas/libs/storage-providers/aws/dynamodb/environment.ts +++ b/lambdas/libs/storage-providers/aws/dynamodb/environment.ts @@ -1,8 +1,8 @@ type DynamoDbEnvironmentVariable = - | 'RUNNER_CONFIG_DYNAMODB_CONFIG_KEY_PREFIX' | 'RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME' - | 'RUNNER_CONFIG_DYNAMODB_TABLE_NAME' - | 'RUNNER_CONFIG_DYNAMODB_TOKEN_KEY_PREFIX' + | 'RUNNER_CONFIG_DYNAMODB_ENTRY_ID' + | 'RUNNER_CONFIG_DYNAMODB_RUNNER_STATE_TABLE_NAME' + | 'RUNNER_CONFIG_DYNAMODB_RUNNER_STATE_TTL_SECONDS' | 'RUNNER_CONFIG_DYNAMODB_TTL_SECONDS'; export function requiredEnvironmentValue(name: DynamoDbEnvironmentVariable): string { diff --git a/lambdas/libs/storage-providers/aws/dynamodb/github-app-credentials-store.test.ts b/lambdas/libs/storage-providers/aws/dynamodb/github-app-credentials-store.test.ts new file mode 100644 index 0000000000..500ad90749 --- /dev/null +++ b/lambdas/libs/storage-providers/aws/dynamodb/github-app-credentials-store.test.ts @@ -0,0 +1,103 @@ +import { DynamoDBClient, GetItemCommand } from '@aws-sdk/client-dynamodb'; +import { mockClient } from 'aws-sdk-client-mock'; +import 'aws-sdk-client-mock-jest/vitest'; +import { beforeEach, describe, expect, it } from 'vitest'; + +import { resetDynamoDbClient } from './client'; +import { createAwsDynamoDbGitHubAppCredentialsStore } from './github-app-credentials-store'; + +const mockDynamoDbClient = mockClient(DynamoDBClient); +const cleanEnv = process.env; + +describe('aws_dynamodb GitHub App credentials store', () => { + beforeEach(() => { + mockDynamoDbClient.reset(); + resetDynamoDbClient(); + process.env = { ...cleanEnv }; + process.env.AWS_REGION = 'eu-west-1'; + process.env.RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME = 'runner-configuration'; + }); + + it('strongly reads and decodes an ordered credential array', async () => { + const value = JSON.stringify([ + { appId: 123, privateKeyBase64: Buffer.from('primary\\nkey').toString('base64') }, + { + appId: 456, + privateKeyBase64: Buffer.from('additional-key').toString('base64'), + installationId: 789, + }, + ]); + mockDynamoDbClient.on(GetItemCommand).resolves({ Item: { value: { S: value } } }); + const store = createAwsDynamoDbGitHubAppCredentialsStore(); + + await expect(store.get()).resolves.toEqual([ + { appId: 123, privateKey: 'primary\nkey', installationId: undefined }, + { appId: 456, privateKey: 'additional-key', installationId: 789 }, + ]); + expect(mockDynamoDbClient).toHaveReceivedCommandWith(GetItemCommand, { + TableName: 'runner-configuration', + Key: { + scope: { S: 'global#github-app' }, + id: { S: 'github-app-credentials' }, + }, + ConsistentRead: true, + ProjectionExpression: '#value', + ExpressionAttributeNames: { '#value': 'value' }, + }); + }); + + it.each([ + ['not-json', 'contains invalid JSON'], + ['[]', 'must contain a non-empty array'], + [JSON.stringify([null]), 'credential at index 0 has an invalid stored value'], + [JSON.stringify([{ appId: 0, privateKeyBase64: 'a2V5' }]), 'credential at index 0 has an invalid stored value'], + [ + JSON.stringify([{ appId: 1, privateKeyBase64: 'not-base64' }]), + 'credential at index 0 has an invalid stored value', + ], + [ + JSON.stringify([{ appId: 1, privateKeyBase64: 'a2V5', installationId: 1.5 }]), + 'credential at index 0 has an invalid stored value', + ], + ])('rejects malformed stored credentials without returning their value', async (value, message) => { + mockDynamoDbClient.on(GetItemCommand).resolves({ Item: { value: { S: value } } }); + const store = createAwsDynamoDbGitHubAppCredentialsStore(); + + await expect(store.get()).rejects.toThrow(message); + }); + + it('rejects a missing credentials item', async () => { + mockDynamoDbClient.on(GetItemCommand).resolves({}); + + await expect(createAwsDynamoDbGitHubAppCredentialsStore().get()).rejects.toThrow( + "GitHub App credentials item 'global#github-app/github-app-credentials' was not found", + ); + }); + + it('rejects a non-string credentials value', async () => { + mockDynamoDbClient.on(GetItemCommand).resolves({ Item: { value: { L: [] } } }); + + await expect(createAwsDynamoDbGitHubAppCredentialsStore().get()).rejects.toThrow( + "GitHub App credentials item 'global#github-app/github-app-credentials' does not contain a string value", + ); + }); + + it.each([undefined, '', ' '])('requires the durable table name for input %j', (tableName) => { + if (tableName === undefined) { + delete process.env.RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME; + } else { + process.env.RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME = tableName; + } + + expect(() => createAwsDynamoDbGitHubAppCredentialsStore()).toThrow( + 'Environment variable RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME is not set', + ); + }); + + it('propagates reads errors without exposing stored credentials', async () => { + const error = new Error('access denied'); + mockDynamoDbClient.on(GetItemCommand).rejects(error); + + await expect(createAwsDynamoDbGitHubAppCredentialsStore().get()).rejects.toBe(error); + }); +}); diff --git a/lambdas/libs/storage-providers/aws/dynamodb/github-app-credentials-store.ts b/lambdas/libs/storage-providers/aws/dynamodb/github-app-credentials-store.ts new file mode 100644 index 0000000000..e9b1a56c18 --- /dev/null +++ b/lambdas/libs/storage-providers/aws/dynamodb/github-app-credentials-store.ts @@ -0,0 +1,89 @@ +import type { GitHubAppCredential, GitHubAppCredentialsStore } from '../../core'; +import { getDurableConfigValue } from './durable-config'; +import { requiredEnvironmentValue } from './environment'; +import { GITHUB_APP_CREDENTIALS_ID, GITHUB_APP_SCOPE } from './keys'; + +interface StoredGitHubAppCredential { + appId: number; + privateKeyBase64: string; + installationId?: number; +} + +export function createAwsDynamoDbGitHubAppCredentialsStore(): GitHubAppCredentialsStore { + return new AwsDynamoDbGitHubAppCredentialsStore(requiredEnvironmentValue('RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME')); +} + +class AwsDynamoDbGitHubAppCredentialsStore implements GitHubAppCredentialsStore { + constructor(private readonly tableName: string) {} + + async get(): Promise { + const value = await getDurableConfigValue( + this.tableName, + GITHUB_APP_SCOPE, + GITHUB_APP_CREDENTIALS_ID, + 'GitHub App credentials', + ); + const credentials = parseCredentials(value); + + return credentials.map((credential) => ({ + appId: credential.appId, + privateKey: decodePrivateKey(credential.privateKeyBase64), + installationId: credential.installationId, + })); + } +} + +function parseCredentials(value: string): StoredGitHubAppCredential[] { + let parsed: unknown; + try { + parsed = JSON.parse(value); + } catch { + throw new Error('GitHub App credentials item contains invalid JSON'); + } + + if (!Array.isArray(parsed) || parsed.length === 0) { + throw new Error('GitHub App credentials item must contain a non-empty array'); + } + + return parsed.map((credential, index) => parseCredential(credential, index)); +} + +function parseCredential(value: unknown, index: number): StoredGitHubAppCredential { + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + throw invalidCredential(index); + } + + const credential = value as Record; + if (!isPositiveSafeInteger(credential.appId) || !isValidBase64(credential.privateKeyBase64)) { + throw invalidCredential(index); + } + if (credential.installationId !== undefined && !isPositiveSafeInteger(credential.installationId)) { + throw invalidCredential(index); + } + + return { + appId: credential.appId, + privateKeyBase64: credential.privateKeyBase64, + installationId: credential.installationId, + }; +} + +function isPositiveSafeInteger(value: unknown): value is number { + return typeof value === 'number' && Number.isSafeInteger(value) && value > 0; +} + +function isValidBase64(value: unknown): value is string { + if (typeof value !== 'string' || value.length === 0 || value.length % 4 !== 0) { + return false; + } + + return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value); +} + +function decodePrivateKey(privateKeyBase64: string): string { + return Buffer.from(privateKeyBase64, 'base64').toString().replace(/\\n/g, '\n'); +} + +function invalidCredential(index: number): Error { + return new Error(`GitHub App credential at index ${index} has an invalid stored value`); +} diff --git a/lambdas/libs/storage-providers/aws/dynamodb/github-webhook-secret-store.test.ts b/lambdas/libs/storage-providers/aws/dynamodb/github-webhook-secret-store.test.ts new file mode 100644 index 0000000000..c66272c2c7 --- /dev/null +++ b/lambdas/libs/storage-providers/aws/dynamodb/github-webhook-secret-store.test.ts @@ -0,0 +1,74 @@ +import { DynamoDBClient, GetItemCommand } from '@aws-sdk/client-dynamodb'; +import { mockClient } from 'aws-sdk-client-mock'; +import 'aws-sdk-client-mock-jest/vitest'; +import { beforeEach, describe, expect, it } from 'vitest'; + +import { resetDynamoDbClient } from './client'; +import { createAwsDynamoDbGitHubWebhookSecretStore } from './github-webhook-secret-store'; + +const mockDynamoDbClient = mockClient(DynamoDBClient); +const cleanEnv = process.env; + +describe('aws_dynamodb GitHub webhook secret store', () => { + beforeEach(() => { + mockDynamoDbClient.reset(); + resetDynamoDbClient(); + process.env = { ...cleanEnv }; + process.env.AWS_REGION = 'eu-west-1'; + process.env.RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME = 'runner-configuration'; + }); + + it('strongly reads the global webhook secret', async () => { + mockDynamoDbClient.on(GetItemCommand).resolves({ Item: { value: { S: 'webhook-secret' } } }); + + await expect(createAwsDynamoDbGitHubWebhookSecretStore().get()).resolves.toBe('webhook-secret'); + expect(mockDynamoDbClient).toHaveReceivedCommandWith(GetItemCommand, { + TableName: 'runner-configuration', + Key: { + scope: { S: 'global#webhook' }, + id: { S: 'github-webhook-secret' }, + }, + ConsistentRead: true, + ProjectionExpression: '#value', + ExpressionAttributeNames: { '#value': 'value' }, + }); + }); + + it('leaves empty-value validation to the webhook config loader', async () => { + mockDynamoDbClient.on(GetItemCommand).resolves({ Item: { value: { S: '' } } }); + + await expect(createAwsDynamoDbGitHubWebhookSecretStore().get()).resolves.toBe(''); + }); + + it('rejects a missing secret item without logging or returning a value', async () => { + mockDynamoDbClient.on(GetItemCommand).resolves({}); + + await expect(createAwsDynamoDbGitHubWebhookSecretStore().get()).rejects.toThrow( + "GitHub webhook secret item 'global#webhook/github-webhook-secret' was not found", + ); + }); + + it('rejects a non-string secret item', async () => { + mockDynamoDbClient.on(GetItemCommand).resolves({ Item: { value: { B: new Uint8Array() } } }); + + await expect(createAwsDynamoDbGitHubWebhookSecretStore().get()).rejects.toThrow( + "GitHub webhook secret item 'global#webhook/github-webhook-secret' does not contain a string value", + ); + }); + + it('requires the durable table name before reading', () => { + delete process.env.RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME; + + expect(() => createAwsDynamoDbGitHubWebhookSecretStore()).toThrow( + 'Environment variable RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME is not set', + ); + expect(mockDynamoDbClient.calls()).toHaveLength(0); + }); + + it('propagates read errors without handling the secret value', async () => { + const error = new Error('access denied'); + mockDynamoDbClient.on(GetItemCommand).rejects(error); + + await expect(createAwsDynamoDbGitHubWebhookSecretStore().get()).rejects.toBe(error); + }); +}); diff --git a/lambdas/libs/storage-providers/aws/dynamodb/github-webhook-secret-store.ts b/lambdas/libs/storage-providers/aws/dynamodb/github-webhook-secret-store.ts new file mode 100644 index 0000000000..6fbf8f81b4 --- /dev/null +++ b/lambdas/libs/storage-providers/aws/dynamodb/github-webhook-secret-store.ts @@ -0,0 +1,21 @@ +import type { GitHubWebhookSecretStore } from '../../core'; +import { getDurableConfigValue } from './durable-config'; +import { requiredEnvironmentValue } from './environment'; +import { GITHUB_WEBHOOK_SCOPE, GITHUB_WEBHOOK_SECRET_ID } from './keys'; + +export function createAwsDynamoDbGitHubWebhookSecretStore(): GitHubWebhookSecretStore { + return new AwsDynamoDbGitHubWebhookSecretStore(requiredEnvironmentValue('RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME')); +} + +class AwsDynamoDbGitHubWebhookSecretStore implements GitHubWebhookSecretStore { + constructor(private readonly tableName: string) {} + + async get(): Promise { + return await getDurableConfigValue( + this.tableName, + GITHUB_WEBHOOK_SCOPE, + GITHUB_WEBHOOK_SECRET_ID, + 'GitHub webhook secret', + ); + } +} diff --git a/lambdas/libs/storage-providers/aws/dynamodb/keys.test.ts b/lambdas/libs/storage-providers/aws/dynamodb/keys.test.ts new file mode 100644 index 0000000000..ac651df069 --- /dev/null +++ b/lambdas/libs/storage-providers/aws/dynamodb/keys.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from 'vitest'; + +import { + GITHUB_APP_CREDENTIALS_ID, + GITHUB_APP_SCOPE, + GITHUB_WEBHOOK_SCOPE, + GITHUB_WEBHOOK_SECRET_ID, + RUNNER_BOOTSTRAP_CONFIG_ID, + RUNNER_CONFIG_ID, + RUNNER_MATCHER_CONFIG_ID, + RUNNER_MATCHER_SCOPE, + runnerBootstrapScope, + runnerGroupId, + runnerGroupScope, + runnerStateId, + runnerStateScope, +} from './keys'; + +describe('aws_dynamodb storage keys', () => { + it('isolates whole-deployment durable records by capability', () => { + expect({ scope: GITHUB_APP_SCOPE, id: GITHUB_APP_CREDENTIALS_ID }).toEqual({ + scope: 'global#github-app', + id: 'github-app-credentials', + }); + expect({ scope: GITHUB_WEBHOOK_SCOPE, id: GITHUB_WEBHOOK_SECRET_ID }).toEqual({ + scope: 'global#webhook', + id: 'github-webhook-secret', + }); + expect({ scope: RUNNER_MATCHER_SCOPE, id: RUNNER_MATCHER_CONFIG_ID }).toEqual({ + scope: 'global#matcher', + id: 'runner-matcher-config', + }); + }); + + it('isolates entry records by access boundary', () => { + expect({ scope: runnerBootstrapScope('linux-x64'), id: RUNNER_BOOTSTRAP_CONFIG_ID }).toEqual({ + scope: 'entry#linux-x64#bootstrap', + id: 'runner-config', + }); + expect({ scope: runnerGroupScope('linux-x64'), id: runnerGroupId('Default') }).toEqual({ + scope: 'entry#linux-x64#runner-group', + id: 'runner-group#Default', + }); + expect(RUNNER_CONFIG_ID).toBe('config'); + expect({ scope: runnerStateScope('linux-x64'), id: runnerStateId('runner-123') }).toEqual({ + scope: 'entry#linux-x64#runner-state', + id: 'runner#runner-123', + }); + }); +}); diff --git a/lambdas/libs/storage-providers/aws/dynamodb/keys.ts b/lambdas/libs/storage-providers/aws/dynamodb/keys.ts new file mode 100644 index 0000000000..cef92af6bb --- /dev/null +++ b/lambdas/libs/storage-providers/aws/dynamodb/keys.ts @@ -0,0 +1,34 @@ +export const SCOPE_ATTRIBUTE = 'scope'; +export const ID_ATTRIBUTE = 'id'; +export const VALUE_ATTRIBUTE = 'value'; +export const EXPIRES_AT_ATTRIBUTE = 'expires_at'; + +export const GITHUB_APP_SCOPE = 'global#github-app'; +export const GITHUB_WEBHOOK_SCOPE = 'global#webhook'; +export const RUNNER_MATCHER_SCOPE = 'global#matcher'; + +export const GITHUB_APP_CREDENTIALS_ID = 'github-app-credentials'; +export const GITHUB_WEBHOOK_SECRET_ID = 'github-webhook-secret'; +export const RUNNER_MATCHER_CONFIG_ID = 'runner-matcher-config'; +export const RUNNER_BOOTSTRAP_CONFIG_ID = 'runner-config'; +export const RUNNER_CONFIG_ID = 'config'; + +export function runnerBootstrapScope(entryId: string): string { + return `entry#${entryId}#bootstrap`; +} + +export function runnerGroupScope(entryId: string): string { + return `entry#${entryId}#runner-group`; +} + +export function runnerStateScope(entryId: string): string { + return `entry#${entryId}#runner-state`; +} + +export function runnerStateId(runnerId: string): string { + return `runner#${runnerId}`; +} + +export function runnerGroupId(runnerGroupName: string): string { + return `runner-group#${runnerGroupName}`; +} diff --git a/lambdas/libs/storage-providers/aws/dynamodb/runner-config-store.test.ts b/lambdas/libs/storage-providers/aws/dynamodb/runner-config-store.test.ts index 0801ba666f..1afb6c7fe9 100644 --- a/lambdas/libs/storage-providers/aws/dynamodb/runner-config-store.test.ts +++ b/lambdas/libs/storage-providers/aws/dynamodb/runner-config-store.test.ts @@ -15,8 +15,8 @@ describe('aws_dynamodb runner config store', () => { resetDynamoDbClient(); process.env = { ...cleanEnv }; process.env.AWS_REGION = 'eu-west-1'; - process.env.RUNNER_CONFIG_DYNAMODB_TABLE_NAME = 'runner-config'; - process.env.RUNNER_CONFIG_DYNAMODB_TOKEN_KEY_PREFIX = 'tokens#'; + process.env.RUNNER_CONFIG_DYNAMODB_RUNNER_STATE_TABLE_NAME = 'runner-state'; + delete process.env.RUNNER_CONFIG_DYNAMODB_ENTRY_ID; process.env.RUNNER_CONFIG_DYNAMODB_TTL_SECONDS = '3600'; vi.useFakeTimers(); vi.setSystemTime(new Date('2025-01-01T00:00:00.000Z')); @@ -29,18 +29,24 @@ describe('aws_dynamodb runner config store', () => { it('creates an expiring runner config without overwriting an existing record', async () => { const store = createAwsDynamoDbRunnerConfigStore(); - await store.create({ runnerId: 'runner-123', value: 'encoded-jit-config' }); + await store.create({ + runnerId: 'runner-123', + value: 'encoded-jit-config', + accessScope: 'arn:aws:ec2:eu-west-1:123456789012:instance/i-123', + }); expect(store.maxWritesPerSecond).toBeUndefined(); expect(mockDynamoDbClient).toHaveReceivedCommandWith(PutItemCommand, { - TableName: 'runner-config', + TableName: 'runner-state', Item: { - id: { S: 'tokens#runner-123' }, + scope: { S: 'arn:aws:ec2:eu-west-1:123456789012:instance/i-123' }, + id: { S: 'config' }, value: { S: 'encoded-jit-config' }, expires_at: { N: '1735693200' }, }, - ConditionExpression: 'attribute_not_exists(#id)', + ConditionExpression: 'attribute_not_exists(#scope) AND attribute_not_exists(#id)', ExpressionAttributeNames: { + '#scope': 'scope', '#id': 'id', }, }); @@ -50,7 +56,11 @@ describe('aws_dynamodb runner config store', () => { const store = createAwsDynamoDbRunnerConfigStore(); await store.create( - { runnerId: 'runner-123', value: 'registration-config' }, + { + runnerId: 'runner-123', + value: 'registration-config', + accessScope: 'arn:aws:ec2:eu-west-1:123456789012:instance/i-123', + }, { metadata: [ { key: 'InstanceId', value: 'i-123' }, @@ -71,7 +81,14 @@ describe('aws_dynamodb runner config store', () => { it('does not write metadata for an empty metadata list', async () => { const store = createAwsDynamoDbRunnerConfigStore(); - await store.create({ runnerId: 'runner-123', value: 'registration-config' }, { metadata: [] }); + await store.create( + { + runnerId: 'runner-123', + value: 'registration-config', + accessScope: 'arn:aws:ec2:eu-west-1:123456789012:instance/i-123', + }, + { metadata: [] }, + ); const command = mockDynamoDbClient.commandCalls(PutItemCommand)[0].args[0]; expect(command.input.Item).not.toHaveProperty('metadata'); @@ -85,18 +102,17 @@ describe('aws_dynamodb runner config store', () => { expect(mockDynamoDbClient.calls()).toHaveLength(0); }); - it.each([ - 'RUNNER_CONFIG_DYNAMODB_TABLE_NAME', - 'RUNNER_CONFIG_DYNAMODB_TOKEN_KEY_PREFIX', - 'RUNNER_CONFIG_DYNAMODB_TTL_SECONDS', - ] as const)('rejects a missing or blank %s', (name) => { - delete process.env[name]; - expect(() => createAwsDynamoDbRunnerConfigStore()).toThrow(`Environment variable ${name} is not set`); + it.each(['RUNNER_CONFIG_DYNAMODB_RUNNER_STATE_TABLE_NAME', 'RUNNER_CONFIG_DYNAMODB_TTL_SECONDS'] as const)( + 'rejects a missing or blank %s', + (name) => { + delete process.env[name]; + expect(() => createAwsDynamoDbRunnerConfigStore()).toThrow(`Environment variable ${name} is not set`); - process.env[name] = ' '; - expect(() => createAwsDynamoDbRunnerConfigStore()).toThrow(`Environment variable ${name} is not set`); - expect(mockDynamoDbClient.calls()).toHaveLength(0); - }); + process.env[name] = ' '; + expect(() => createAwsDynamoDbRunnerConfigStore()).toThrow(`Environment variable ${name} is not set`); + expect(mockDynamoDbClient.calls()).toHaveLength(0); + }, + ); it.each(['0', '-1', '1.5', 'not-a-number', '9007199254740992'])('rejects invalid TTL seconds %j', (ttlSeconds) => { process.env.RUNNER_CONFIG_DYNAMODB_TTL_SECONDS = ttlSeconds; @@ -107,11 +123,26 @@ describe('aws_dynamodb runner config store', () => { expect(mockDynamoDbClient.calls()).toHaveLength(0); }); + it.each([undefined, '', ' '])('rejects invalid access scope %j before writing', async (accessScope) => { + const store = createAwsDynamoDbRunnerConfigStore(); + + await expect(store.create({ runnerId: 'runner-123', value: 'sensitive-config', accessScope })).rejects.toThrow( + "Runner config field 'accessScope' must be a non-empty string for aws_dynamodb", + ); + expect(mockDynamoDbClient.calls()).toHaveLength(0); + }); + it('propagates DynamoDB write errors without handling the stored value', async () => { const error = new Error('conditional request failed'); mockDynamoDbClient.on(PutItemCommand).rejects(error); const store = createAwsDynamoDbRunnerConfigStore(); - await expect(store.create({ runnerId: 'runner-123', value: 'sensitive-config' })).rejects.toBe(error); + await expect( + store.create({ + runnerId: 'runner-123', + value: 'sensitive-config', + accessScope: 'arn:aws:ec2:eu-west-1:123456789012:instance/i-123', + }), + ).rejects.toBe(error); }); }); diff --git a/lambdas/libs/storage-providers/aws/dynamodb/runner-config-store.ts b/lambdas/libs/storage-providers/aws/dynamodb/runner-config-store.ts index 5d4baf2612..79de2b6b71 100644 --- a/lambdas/libs/storage-providers/aws/dynamodb/runner-config-store.ts +++ b/lambdas/libs/storage-providers/aws/dynamodb/runner-config-store.ts @@ -3,22 +3,18 @@ import { PutItemCommand, type AttributeValue } from '@aws-sdk/client-dynamodb'; import type { RunnerConfigMetadata, RunnerConfigRecord, RunnerConfigStore } from '../../core'; import { getDynamoDbClient } from './client'; import { positiveIntegerEnvironmentValue, requiredEnvironmentValue } from './environment'; +import { EXPIRES_AT_ATTRIBUTE, ID_ATTRIBUTE, RUNNER_CONFIG_ID, SCOPE_ATTRIBUTE, VALUE_ATTRIBUTE } from './keys'; -const ID_ATTRIBUTE = 'id'; -const VALUE_ATTRIBUTE = 'value'; -const EXPIRES_AT_ATTRIBUTE = 'expires_at'; const METADATA_ATTRIBUTE = 'metadata'; interface AwsDynamoDbRunnerConfigStoreConfig { tableName: string; - tokenKeyPrefix: string; ttlSeconds: number; } export function createAwsDynamoDbRunnerConfigStore(): RunnerConfigStore { return new AwsDynamoDbRunnerConfigStore({ - tableName: requiredEnvironmentValue('RUNNER_CONFIG_DYNAMODB_TABLE_NAME'), - tokenKeyPrefix: requiredEnvironmentValue('RUNNER_CONFIG_DYNAMODB_TOKEN_KEY_PREFIX'), + tableName: requiredEnvironmentValue('RUNNER_CONFIG_DYNAMODB_RUNNER_STATE_TABLE_NAME'), ttlSeconds: positiveIntegerEnvironmentValue('RUNNER_CONFIG_DYNAMODB_TTL_SECONDS'), }); } @@ -27,8 +23,13 @@ class AwsDynamoDbRunnerConfigStore implements RunnerConfigStore { constructor(private readonly config: AwsDynamoDbRunnerConfigStoreConfig) {} async create(record: RunnerConfigRecord, options: { metadata?: RunnerConfigMetadata[] } = {}): Promise { + if (typeof record.accessScope !== 'string' || record.accessScope.trim() === '') { + throw new Error("Runner config field 'accessScope' must be a non-empty string for aws_dynamodb"); + } + const item: Record = { - [ID_ATTRIBUTE]: { S: `${this.config.tokenKeyPrefix}${record.runnerId}` }, + [SCOPE_ATTRIBUTE]: { S: record.accessScope }, + [ID_ATTRIBUTE]: { S: RUNNER_CONFIG_ID }, [VALUE_ATTRIBUTE]: { S: record.value }, [EXPIRES_AT_ATTRIBUTE]: { N: (Math.floor(Date.now() / 1000) + this.config.ttlSeconds).toString(), @@ -50,8 +51,9 @@ class AwsDynamoDbRunnerConfigStore implements RunnerConfigStore { new PutItemCommand({ TableName: this.config.tableName, Item: item, - ConditionExpression: 'attribute_not_exists(#id)', + ConditionExpression: 'attribute_not_exists(#scope) AND attribute_not_exists(#id)', ExpressionAttributeNames: { + '#scope': SCOPE_ATTRIBUTE, '#id': ID_ATTRIBUTE, }, }), diff --git a/lambdas/libs/storage-providers/aws/dynamodb/runner-group-cache-store.test.ts b/lambdas/libs/storage-providers/aws/dynamodb/runner-group-cache-store.test.ts index 2bb335874b..2fbac5b69d 100644 --- a/lambdas/libs/storage-providers/aws/dynamodb/runner-group-cache-store.test.ts +++ b/lambdas/libs/storage-providers/aws/dynamodb/runner-group-cache-store.test.ts @@ -16,7 +16,7 @@ describe('aws_dynamodb runner group cache store', () => { process.env = { ...cleanEnv }; process.env.AWS_REGION = 'eu-west-1'; process.env.RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME = 'runner-configuration'; - process.env.RUNNER_CONFIG_DYNAMODB_CONFIG_KEY_PREFIX = 'config#'; + process.env.RUNNER_CONFIG_DYNAMODB_ENTRY_ID = 'linux-x64'; }); it('gets a runner group id with a strongly consistent projected read', async () => { @@ -27,7 +27,8 @@ describe('aws_dynamodb runner group cache store', () => { expect(mockDynamoDbClient).toHaveReceivedCommandWith(GetItemCommand, { TableName: 'runner-configuration', Key: { - id: { S: 'config#runner-group#Default' }, + scope: { S: 'entry#linux-x64#runner-group' }, + id: { S: 'runner-group#Default' }, }, ConsistentRead: true, ProjectionExpression: '#value', @@ -53,7 +54,7 @@ describe('aws_dynamodb runner group cache store', () => { const store = createAwsDynamoDbRunnerGroupCacheStore(); await expect(store.get('Default')).rejects.toThrow( - "Runner group cache item 'config#runner-group#Default' has an invalid value", + "Runner group cache item 'entry#linux-x64#runner-group/runner-group#Default' has an invalid value", ); }); @@ -65,17 +66,19 @@ describe('aws_dynamodb runner group cache store', () => { expect(mockDynamoDbClient).toHaveReceivedCommandWith(PutItemCommand, { TableName: 'runner-configuration', Item: { - id: { S: 'config#runner-group#Default' }, + scope: { S: 'entry#linux-x64#runner-group' }, + id: { S: 'runner-group#Default' }, value: { S: '42' }, }, - ConditionExpression: 'attribute_not_exists(#id)', + ConditionExpression: 'attribute_not_exists(#scope) AND attribute_not_exists(#id)', ExpressionAttributeNames: { + '#scope': 'scope', '#id': 'id', }, }); }); - it.each(['RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME', 'RUNNER_CONFIG_DYNAMODB_CONFIG_KEY_PREFIX'] as const)( + it.each(['RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME', 'RUNNER_CONFIG_DYNAMODB_ENTRY_ID'] as const)( 'rejects a missing or blank %s', (name) => { delete process.env[name]; diff --git a/lambdas/libs/storage-providers/aws/dynamodb/runner-group-cache-store.ts b/lambdas/libs/storage-providers/aws/dynamodb/runner-group-cache-store.ts index 4ac2b3587e..a90a79e46e 100644 --- a/lambdas/libs/storage-providers/aws/dynamodb/runner-group-cache-store.ts +++ b/lambdas/libs/storage-providers/aws/dynamodb/runner-group-cache-store.ts @@ -3,20 +3,23 @@ import { GetItemCommand, PutItemCommand } from '@aws-sdk/client-dynamodb'; import type { RunnerGroupCacheRecord, RunnerGroupCacheStore } from '../../core'; import { getDynamoDbClient } from './client'; import { requiredEnvironmentValue } from './environment'; - -const ID_ATTRIBUTE = 'id'; -const VALUE_ATTRIBUTE = 'value'; -const RUNNER_GROUP_KEY = 'runner-group#'; +import { + ID_ATTRIBUTE, + runnerGroupId as runnerGroupItemId, + runnerGroupScope, + SCOPE_ATTRIBUTE, + VALUE_ATTRIBUTE, +} from './keys'; interface AwsDynamoDbRunnerGroupCacheStoreConfig { tableName: string; - configKeyPrefix: string; + scope: string; } export function createAwsDynamoDbRunnerGroupCacheStore(): RunnerGroupCacheStore { return new AwsDynamoDbRunnerGroupCacheStore({ tableName: requiredEnvironmentValue('RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME'), - configKeyPrefix: requiredEnvironmentValue('RUNNER_CONFIG_DYNAMODB_CONFIG_KEY_PREFIX'), + scope: runnerGroupScope(requiredEnvironmentValue('RUNNER_CONFIG_DYNAMODB_ENTRY_ID')), }); } @@ -24,11 +27,12 @@ class AwsDynamoDbRunnerGroupCacheStore implements RunnerGroupCacheStore { constructor(private readonly config: AwsDynamoDbRunnerGroupCacheStoreConfig) {} async get(runnerGroupName: string): Promise { - const id = this.itemId(runnerGroupName); + const id = runnerGroupItemId(runnerGroupName); const result = await getDynamoDbClient().send( new GetItemCommand({ TableName: this.config.tableName, Key: { + [SCOPE_ATTRIBUTE]: { S: this.config.scope }, [ID_ATTRIBUTE]: { S: id }, }, ConsistentRead: true, @@ -45,12 +49,12 @@ class AwsDynamoDbRunnerGroupCacheStore implements RunnerGroupCacheStore { const value = result.Item[VALUE_ATTRIBUTE]?.S; if (value === undefined || !/^\d+$/.test(value)) { - throw new Error(`Runner group cache item '${id}' has an invalid value`); + throw new Error(`Runner group cache item '${this.config.scope}/${id}' has an invalid value`); } const runnerGroupId = Number(value); if (!Number.isSafeInteger(runnerGroupId)) { - throw new Error(`Runner group cache item '${id}' has an invalid value`); + throw new Error(`Runner group cache item '${this.config.scope}/${id}' has an invalid value`); } return runnerGroupId; @@ -61,18 +65,16 @@ class AwsDynamoDbRunnerGroupCacheStore implements RunnerGroupCacheStore { new PutItemCommand({ TableName: this.config.tableName, Item: { - [ID_ATTRIBUTE]: { S: this.itemId(record.runnerGroupName) }, + [SCOPE_ATTRIBUTE]: { S: this.config.scope }, + [ID_ATTRIBUTE]: { S: runnerGroupItemId(record.runnerGroupName) }, [VALUE_ATTRIBUTE]: { S: record.runnerGroupId.toString() }, }, - ConditionExpression: 'attribute_not_exists(#id)', + ConditionExpression: 'attribute_not_exists(#scope) AND attribute_not_exists(#id)', ExpressionAttributeNames: { + '#scope': SCOPE_ATTRIBUTE, '#id': ID_ATTRIBUTE, }, }), ); } - - private itemId(runnerGroupName: string): string { - return `${this.config.configKeyPrefix}${RUNNER_GROUP_KEY}${runnerGroupName}`; - } } diff --git a/lambdas/libs/storage-providers/aws/dynamodb/runner-matcher-config-store.test.ts b/lambdas/libs/storage-providers/aws/dynamodb/runner-matcher-config-store.test.ts index a8960e3f56..66e8d07c2e 100644 --- a/lambdas/libs/storage-providers/aws/dynamodb/runner-matcher-config-store.test.ts +++ b/lambdas/libs/storage-providers/aws/dynamodb/runner-matcher-config-store.test.ts @@ -16,7 +16,6 @@ describe('aws_dynamodb runner matcher config store', () => { process.env = { ...cleanEnv }; process.env.AWS_REGION = 'eu-west-1'; process.env.RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME = 'runner-configuration'; - process.env.RUNNER_CONFIG_DYNAMODB_CONFIG_KEY_PREFIX = 'config#'; }); it('gets the matcher config with a strongly consistent projected read', async () => { @@ -27,7 +26,8 @@ describe('aws_dynamodb runner matcher config store', () => { expect(mockDynamoDbClient).toHaveReceivedCommandWith(GetItemCommand, { TableName: 'runner-configuration', Key: { - id: { S: 'config#runner-matcher-config' }, + scope: { S: 'global#matcher' }, + id: { S: 'runner-matcher-config' }, }, ConsistentRead: true, ProjectionExpression: '#value', @@ -49,7 +49,7 @@ describe('aws_dynamodb runner matcher config store', () => { const store = createAwsDynamoDbRunnerMatcherConfigStore(); await expect(store.get()).rejects.toThrow( - "Runner matcher config item 'config#runner-matcher-config' was not found", + "Runner matcher config item 'global#matcher/runner-matcher-config' was not found", ); }); @@ -58,21 +58,22 @@ describe('aws_dynamodb runner matcher config store', () => { const store = createAwsDynamoDbRunnerMatcherConfigStore(); await expect(store.get()).rejects.toThrow( - "Runner matcher config item 'config#runner-matcher-config' does not contain a string value", + "Runner matcher config item 'global#matcher/runner-matcher-config' does not contain a string value", ); }); - it.each(['RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME', 'RUNNER_CONFIG_DYNAMODB_CONFIG_KEY_PREFIX'] as const)( - 'rejects a missing or blank %s', - (name) => { - delete process.env[name]; - expect(() => createAwsDynamoDbRunnerMatcherConfigStore()).toThrow(`Environment variable ${name} is not set`); - - process.env[name] = ' '; - expect(() => createAwsDynamoDbRunnerMatcherConfigStore()).toThrow(`Environment variable ${name} is not set`); - expect(mockDynamoDbClient.calls()).toHaveLength(0); - }, - ); + it('rejects a missing or blank durable table name', () => { + delete process.env.RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME; + expect(() => createAwsDynamoDbRunnerMatcherConfigStore()).toThrow( + 'Environment variable RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME is not set', + ); + + process.env.RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME = ' '; + expect(() => createAwsDynamoDbRunnerMatcherConfigStore()).toThrow( + 'Environment variable RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME is not set', + ); + expect(mockDynamoDbClient.calls()).toHaveLength(0); + }); it('propagates DynamoDB read errors', async () => { const error = new Error('read failed'); diff --git a/lambdas/libs/storage-providers/aws/dynamodb/runner-matcher-config-store.ts b/lambdas/libs/storage-providers/aws/dynamodb/runner-matcher-config-store.ts index dce975b5de..f840345983 100644 --- a/lambdas/libs/storage-providers/aws/dynamodb/runner-matcher-config-store.ts +++ b/lambdas/libs/storage-providers/aws/dynamodb/runner-matcher-config-store.ts @@ -1,22 +1,15 @@ -import { GetItemCommand } from '@aws-sdk/client-dynamodb'; - import type { RunnerMatcherConfigStore } from '../../core'; -import { getDynamoDbClient } from './client'; +import { getDurableConfigValue } from './durable-config'; import { requiredEnvironmentValue } from './environment'; - -const ID_ATTRIBUTE = 'id'; -const VALUE_ATTRIBUTE = 'value'; -const RUNNER_MATCHER_CONFIG_KEY = 'runner-matcher-config'; +import { RUNNER_MATCHER_CONFIG_ID, RUNNER_MATCHER_SCOPE } from './keys'; interface AwsDynamoDbRunnerMatcherConfigStoreConfig { tableName: string; - configKeyPrefix: string; } export function createAwsDynamoDbRunnerMatcherConfigStore(): RunnerMatcherConfigStore { return new AwsDynamoDbRunnerMatcherConfigStore({ tableName: requiredEnvironmentValue('RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME'), - configKeyPrefix: requiredEnvironmentValue('RUNNER_CONFIG_DYNAMODB_CONFIG_KEY_PREFIX'), }); } @@ -24,30 +17,11 @@ class AwsDynamoDbRunnerMatcherConfigStore implements RunnerMatcherConfigStore { constructor(private readonly config: AwsDynamoDbRunnerMatcherConfigStoreConfig) {} async get(): Promise { - const id = `${this.config.configKeyPrefix}${RUNNER_MATCHER_CONFIG_KEY}`; - const result = await getDynamoDbClient().send( - new GetItemCommand({ - TableName: this.config.tableName, - Key: { - [ID_ATTRIBUTE]: { S: id }, - }, - ConsistentRead: true, - ProjectionExpression: '#value', - ExpressionAttributeNames: { - '#value': VALUE_ATTRIBUTE, - }, - }), + return await getDurableConfigValue( + this.config.tableName, + RUNNER_MATCHER_SCOPE, + RUNNER_MATCHER_CONFIG_ID, + 'Runner matcher config', ); - - if (!result.Item) { - throw new Error(`Runner matcher config item '${id}' was not found`); - } - - const value = result.Item[VALUE_ATTRIBUTE]?.S; - if (value === undefined) { - throw new Error(`Runner matcher config item '${id}' does not contain a string value`); - } - - return value; } } diff --git a/modules/storage-providers/aws/dynamodb/capabilities.tf b/modules/storage-providers/aws/dynamodb/capabilities.tf new file mode 100644 index 0000000000..bed090425d --- /dev/null +++ b/modules/storage-providers/aws/dynamodb/capabilities.tf @@ -0,0 +1,283 @@ +locals { + config_environment_variables = { + RUNNER_CONFIG_STORAGE_PROVIDER = "aws_dynamodb" + RUNNER_CONFIG_STORAGE_VERSION = terraform_data.config_version.id + RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME = aws_dynamodb_table.config.name + } + + matcher_environment_variables = merge(local.config_environment_variables, { + RUNNER_MATCHER_CONFIG_VERSION = nonsensitive(sha256(var.global_records.runner_matcher_config)) + }) + + runner_state_environment_variables = { + RUNNER_CONFIG_DYNAMODB_RUNNER_STATE_TABLE_NAME = aws_dynamodb_table.runner_state.name + RUNNER_CONFIG_DYNAMODB_RUNNER_STATE_TTL_SECONDS = tostring(var.runner_state_ttl_seconds) + } + + runner_config_environment_variables = { + RUNNER_CONFIG_DYNAMODB_TTL_SECONDS = tostring(var.runner_config_ttl_seconds) + } + + global_scopes = { + github_app = "global#github-app" + webhook = "global#webhook" + matcher = "global#matcher" + } + + entry_scopes = { + for entry_id in var.entry_ids : entry_id => { + bootstrap = "entry#${entry_id}#bootstrap" + runner_group = "entry#${entry_id}#runner-group" + runner_state = "entry#${entry_id}#runner-state" + } + } + + entry_environment_variables = { + for entry_id, scopes in local.entry_scopes : entry_id => merge(local.config_environment_variables, { + RUNNER_CONFIG_DYNAMODB_ENTRY_ID = entry_id + }) + } + + scale_up_environment_variables = { + for entry_id in var.entry_ids : entry_id => merge( + local.entry_environment_variables[entry_id], + local.runner_state_environment_variables, + local.runner_config_environment_variables, + ) + } + + scale_down_environment_variables = { + for entry_id in var.entry_ids : entry_id => merge( + local.entry_environment_variables[entry_id], + local.runner_state_environment_variables, + ) + } + + github_app_read_statement = { + Effect = "Allow" + Action = ["dynamodb:GetItem"] + Resource = [aws_dynamodb_table.config.arn] + Condition = { + "ForAllValues:StringEquals" = { + "dynamodb:LeadingKeys" = [local.global_scopes.github_app] + } + } + } + + direct_webhook_read_statement = { + Effect = "Allow" + Action = ["dynamodb:GetItem"] + Resource = [aws_dynamodb_table.config.arn] + Condition = { + "ForAllValues:StringEquals" = { + "dynamodb:LeadingKeys" = [local.global_scopes.webhook, local.global_scopes.matcher] + } + } + } + + eventbridge_webhook_read_statement = { + Effect = "Allow" + Action = ["dynamodb:GetItem"] + Resource = [aws_dynamodb_table.config.arn] + Condition = { + "ForAllValues:StringEquals" = { + "dynamodb:LeadingKeys" = [local.global_scopes.webhook] + } + } + } + + dispatcher_read_statement = { + Effect = "Allow" + Action = ["dynamodb:GetItem"] + Resource = [aws_dynamodb_table.config.arn] + Condition = { + "ForAllValues:StringEquals" = { + "dynamodb:LeadingKeys" = [local.global_scopes.matcher] + } + } + } + + config_kms_decrypt_statements = var.config.config.kms_key_arn == null ? [] : [{ + Effect = "Allow" + Action = ["kms:Decrypt"] + Resource = [var.config.config.kms_key_arn] + }] + + runner_state_kms_decrypt_statements = var.config.runner_state.kms_key_arn == null ? [] : [{ + Effect = "Allow" + Action = ["kms:Decrypt"] + Resource = [var.config.runner_state.kms_key_arn] + }] + + direct_webhook_iam_policy_json = jsonencode({ + Version = "2012-10-17" + Statement = concat( + [local.direct_webhook_read_statement], + local.config_kms_decrypt_statements, + ) + }) + + eventbridge_webhook_iam_policy_json = jsonencode({ + Version = "2012-10-17" + Statement = concat( + [local.eventbridge_webhook_read_statement], + local.config_kms_decrypt_statements, + ) + }) + + dispatcher_iam_policy_json = jsonencode({ + Version = "2012-10-17" + Statement = concat( + [local.dispatcher_read_statement], + local.config_kms_decrypt_statements, + ) + }) + + entry_runner_group_statements = { + for entry_id, scopes in local.entry_scopes : entry_id => { + Effect = "Allow" + Action = ["dynamodb:GetItem", "dynamodb:PutItem"] + Resource = [aws_dynamodb_table.config.arn] + Condition = { + "ForAllValues:StringEquals" = { + "dynamodb:LeadingKeys" = [scopes.runner_group] + } + } + } + } + + runner_config_write_statements = { + for entry_id, scopes in local.entry_scopes : entry_id => { + Effect = "Allow" + Action = ["dynamodb:PutItem"] + Resource = [aws_dynamodb_table.runner_state.arn] + Condition = { + "ForAllValues:StringLike" = { + "dynamodb:LeadingKeys" = ["${lookup(var.runner_config_access_scope_prefixes, entry_id, "__missing_runner_config_access_scope__")}*"] + } + } + } + } + + runner_state_write_statements = { + for entry_id, scopes in local.entry_scopes : entry_id => { + Effect = "Allow" + Action = [ + "dynamodb:PutItem", + "dynamodb:Query", + "dynamodb:UpdateItem", + ] + Resource = [aws_dynamodb_table.runner_state.arn] + Condition = { + "ForAllValues:StringEquals" = { + "dynamodb:LeadingKeys" = [scopes.runner_state] + } + } + } + } + + runner_state_reconcile_statements = { + for entry_id, scopes in local.entry_scopes : entry_id => { + Effect = "Allow" + Action = [ + "dynamodb:DeleteItem", + "dynamodb:Query", + "dynamodb:UpdateItem", + ] + Resource = [aws_dynamodb_table.runner_state.arn] + Condition = { + "ForAllValues:StringEquals" = { + "dynamodb:LeadingKeys" = [scopes.runner_state] + } + } + } + } + + scale_up_iam_policy_json = { + for entry_id in var.entry_ids : entry_id => jsonencode({ + Version = "2012-10-17" + Statement = concat( + [ + local.github_app_read_statement, + local.entry_runner_group_statements[entry_id], + local.runner_config_write_statements[entry_id], + local.runner_state_write_statements[entry_id], + ], + local.config_kms_decrypt_statements, + local.runner_state_kms_decrypt_statements, + ) + }) + } + + scale_down_iam_policy_json = { + for entry_id in var.entry_ids : entry_id => jsonencode({ + Version = "2012-10-17" + Statement = concat( + [local.github_app_read_statement, local.runner_state_reconcile_statements[entry_id]], + local.config_kms_decrypt_statements, + local.runner_state_kms_decrypt_statements, + ) + }) + } + + pool_iam_policy_json = { + for entry_id in var.entry_ids : entry_id => jsonencode({ + Version = "2012-10-17" + Statement = concat( + [ + local.github_app_read_statement, + local.entry_runner_group_statements[entry_id], + local.runner_config_write_statements[entry_id], + local.runner_state_write_statements[entry_id], + ], + local.config_kms_decrypt_statements, + local.runner_state_kms_decrypt_statements, + ) + }) + } + + job_retry_iam_policy_json = { + for entry_id in var.entry_ids : entry_id => jsonencode({ + Version = "2012-10-17" + Statement = concat( + [local.github_app_read_statement], + local.config_kms_decrypt_statements, + ) + }) + } + + runner_iam_policy_json = { + for entry_id, scopes in local.entry_scopes : entry_id => jsonencode({ + Version = "2012-10-17" + Statement = concat( + [ + { + Effect = "Allow" + Action = ["dynamodb:GetItem"] + Resource = [aws_dynamodb_table.config.arn] + Condition = { + "ForAllValues:StringEquals" = { + "dynamodb:LeadingKeys" = [scopes.bootstrap] + } + } + }, + { + Effect = "Allow" + Action = [ + "dynamodb:DeleteItem", + "dynamodb:GetItem", + ] + Resource = [aws_dynamodb_table.runner_state.arn] + Condition = { + "ForAllValues:StringEquals" = { + "dynamodb:LeadingKeys" = ["$${ec2:SourceInstanceARN}"] + } + } + }, + ], + local.config_kms_decrypt_statements, + local.runner_state_kms_decrypt_statements, + ) + }) + } +} diff --git a/modules/storage-providers/aws/dynamodb/config-version.tf b/modules/storage-providers/aws/dynamodb/config-version.tf new file mode 100644 index 0000000000..a0bd45605c --- /dev/null +++ b/modules/storage-providers/aws/dynamodb/config-version.tf @@ -0,0 +1,23 @@ +resource "terraform_data" "config_version" { + triggers_replace = sensitive({ + global_records = sha256(jsonencode(var.global_records)) + entry_records = sha256(jsonencode(var.entry_records)) + }) + + lifecycle { + precondition { + condition = toset(keys(var.runner_config_access_scope_prefixes)) == var.entry_ids && alltrue([for prefix in values(var.runner_config_access_scope_prefixes) : trimspace(prefix) != ""]) + error_message = "runner_config_access_scope_prefixes must contain one non-empty prefix for every entry_id." + } + + precondition { + condition = var.runner_state_ttl_seconds > var.runner_config_ttl_seconds && floor(var.runner_state_ttl_seconds) == var.runner_state_ttl_seconds + error_message = "runner_state_ttl_seconds must be an integer greater than runner_config_ttl_seconds." + } + + precondition { + condition = toset(keys(var.entry_records)) == var.entry_ids + error_message = "entry_records must contain exactly one durable bootstrap record for every entry_id." + } + } +} diff --git a/modules/storage-providers/aws/dynamodb/items.tf b/modules/storage-providers/aws/dynamodb/items.tf new file mode 100644 index 0000000000..bc34f70e19 --- /dev/null +++ b/modules/storage-providers/aws/dynamodb/items.tf @@ -0,0 +1,56 @@ +resource "aws_dynamodb_table_item" "github_app_credentials" { + table_name = aws_dynamodb_table.config.name + hash_key = aws_dynamodb_table.config.hash_key + range_key = aws_dynamodb_table.config.range_key + + item = jsonencode({ + scope = { S = local.global_scopes.github_app } + id = { S = "github-app-credentials" } + value = { S = var.global_records.github_app_credentials } + }) +} + +resource "aws_dynamodb_table_item" "github_webhook_secret" { + table_name = aws_dynamodb_table.config.name + hash_key = aws_dynamodb_table.config.hash_key + range_key = aws_dynamodb_table.config.range_key + + item = jsonencode({ + scope = { S = local.global_scopes.webhook } + id = { S = "github-webhook-secret" } + value = { S = var.global_records.github_webhook_secret } + }) +} + +resource "aws_dynamodb_table_item" "runner_matcher_config" { + table_name = aws_dynamodb_table.config.name + hash_key = aws_dynamodb_table.config.hash_key + range_key = aws_dynamodb_table.config.range_key + + item = jsonencode({ + scope = { S = local.global_scopes.matcher } + id = { S = "runner-matcher-config" } + value = { S = var.global_records.runner_matcher_config } + }) +} + +resource "aws_dynamodb_table_item" "runner_config" { + for_each = var.entry_records + + table_name = aws_dynamodb_table.config.name + hash_key = aws_dynamodb_table.config.hash_key + range_key = aws_dynamodb_table.config.range_key + + item = jsonencode({ + scope = { S = local.entry_scopes[each.key].bootstrap } + id = { S = "runner-config" } + value = { S = jsonencode(merge(each.value, { + runner_config_storage = { + provider = "aws_dynamodb" + table_name = aws_dynamodb_table.runner_state.name + access_scope = "compute-resource" + id = "config" + } + })) } + }) +} diff --git a/modules/storage-providers/aws/dynamodb/outputs.tf b/modules/storage-providers/aws/dynamodb/outputs.tf new file mode 100644 index 0000000000..4c337b212d --- /dev/null +++ b/modules/storage-providers/aws/dynamodb/outputs.tf @@ -0,0 +1,71 @@ +output "config_table" { + description = "Shared durable configuration table. Global and runner-entry records are separated by the `scope` partition key." + value = { + arn = aws_dynamodb_table.config.arn + name = aws_dynamodb_table.config.name + } +} + +output "runner_state_table" { + description = "Shared TTL-backed table containing ephemeral runner configuration and provider-neutral runner lifecycle records." + value = { + arn = aws_dynamodb_table.runner_state.arn + name = aws_dynamodb_table.runner_state.name + ttl_attribute_name = "expires_at" + } +} + +output "capabilities" { + description = "Opaque environment and least-privilege IAM additions consumed by the shared webhook and each runner entry's control-plane functions." + depends_on = [ + aws_dynamodb_table_item.github_app_credentials, + aws_dynamodb_table_item.github_webhook_secret, + aws_dynamodb_table_item.runner_matcher_config, + aws_dynamodb_table_item.runner_config, + terraform_data.config_version, + ] + value = { + webhook = { + direct = { + environment_variables = tomap(local.matcher_environment_variables) + iam_policy_json = local.direct_webhook_iam_policy_json + } + eventbridge = { + webhook = { + environment_variables = tomap(local.config_environment_variables) + iam_policy_json = local.eventbridge_webhook_iam_policy_json + } + dispatcher = { + environment_variables = tomap(local.matcher_environment_variables) + iam_policy_json = local.dispatcher_iam_policy_json + } + } + } + entries = { + for entry_id in var.entry_ids : entry_id => { + scale_up = { + environment_variables = tomap(local.scale_up_environment_variables[entry_id]) + iam_policy_json = local.scale_up_iam_policy_json[entry_id] + } + scale_down = { + environment_variables = tomap(local.scale_down_environment_variables[entry_id]) + iam_policy_json = local.scale_down_iam_policy_json[entry_id] + } + pool = { + environment_variables = tomap(local.scale_up_environment_variables[entry_id]) + iam_policy_json = local.pool_iam_policy_json[entry_id] + } + job_retry = { + environment_variables = tomap(local.config_environment_variables) + iam_policy_json = local.job_retry_iam_policy_json[entry_id] + } + runner = { + config_table_name = aws_dynamodb_table.config.name + runner_state_table_name = aws_dynamodb_table.runner_state.name + scope = local.entry_scopes[entry_id].bootstrap + iam_policy_json = local.runner_iam_policy_json[entry_id] + } + } + } + } +} diff --git a/modules/storage-providers/aws/dynamodb/tables.tf b/modules/storage-providers/aws/dynamodb/tables.tf new file mode 100644 index 0000000000..12cd94867c --- /dev/null +++ b/modules/storage-providers/aws/dynamodb/tables.tf @@ -0,0 +1,62 @@ +resource "aws_dynamodb_table" "config" { + name = "${var.prefix}-config" + billing_mode = "PAY_PER_REQUEST" + hash_key = "scope" + range_key = "id" + + attribute { + name = "scope" + type = "S" + } + + attribute { + name = "id" + type = "S" + } + + point_in_time_recovery { + enabled = var.config.config.point_in_time_recovery_enabled + } + + server_side_encryption { + enabled = true + kms_key_arn = var.config.config.kms_key_arn + } + + deletion_protection_enabled = var.config.config.deletion_protection_enabled + tags = merge(var.tags, var.config.config.tags) +} + +resource "aws_dynamodb_table" "runner_state" { + name = "${var.prefix}-runner-state" + billing_mode = "PAY_PER_REQUEST" + hash_key = "scope" + range_key = "id" + + attribute { + name = "scope" + type = "S" + } + + attribute { + name = "id" + type = "S" + } + + ttl { + attribute_name = "expires_at" + enabled = true + } + + point_in_time_recovery { + enabled = var.config.runner_state.point_in_time_recovery_enabled + } + + server_side_encryption { + enabled = true + kms_key_arn = var.config.runner_state.kms_key_arn + } + + deletion_protection_enabled = var.config.runner_state.deletion_protection_enabled + tags = merge(var.tags, var.config.runner_state.tags) +} diff --git a/modules/storage-providers/aws/dynamodb/variables.tf b/modules/storage-providers/aws/dynamodb/variables.tf new file mode 100644 index 0000000000..dc4e90badc --- /dev/null +++ b/modules/storage-providers/aws/dynamodb/variables.tf @@ -0,0 +1,84 @@ +variable "prefix" { + description = "Multi-runner prefix used to name the two shared DynamoDB tables." + type = string +} + +variable "tags" { + description = "Base tags added to both shared DynamoDB tables. Table-specific tags override matching keys." + type = map(string) + default = {} +} + +variable "entry_ids" { + description = "Runner-entry identifiers used to build entry-scoped Lambda capabilities." + type = set(string) +} + +variable "runner_config_access_scope_prefixes" { + description = "Per-entry compute-resource scope prefixes used to constrain one-time runner-config writes." + type = map(string) +} + +variable "runner_config_ttl_seconds" { + description = "TTL in seconds for one-time registration and JIT configuration records." + type = number + + validation { + condition = var.runner_config_ttl_seconds > 0 && floor(var.runner_config_ttl_seconds) == var.runner_config_ttl_seconds + error_message = "runner_config_ttl_seconds must be a positive integer." + } +} + +variable "runner_state_ttl_seconds" { + description = "Safety TTL in seconds applied only while lifecycle records are provisioning or terminating; active and orphan inventory has no expiry." + type = number +} + +variable "global_records" { + description = "Terraform-managed values stored under the shared global scope." + type = object({ + github_app_credentials = string + github_webhook_secret = string + runner_matcher_config = string + }) + sensitive = true +} + +variable "entry_records" { + description = "Resolved durable runner bootstrap configuration keyed by runner-entry identifier." + type = map(object({ + run_as = string + agent_mode = string + disable_default_labels = bool + enable_jit_config = bool + })) +} + +variable "config" { + description = <<-EOT + Settings for the shared durable configuration table and ephemeral runner-state table. + + - `config.kms_key_arn`: Optional customer-managed KMS key ARN for durable configuration encryption. Null uses the AWS-owned DynamoDB key. + - `config.point_in_time_recovery_enabled`: Enables point-in-time recovery for durable configuration. + - `config.deletion_protection_enabled`: Enables deletion protection for the durable table. + - `config.tags`: Tags applied after the shared tag map. + - `runner_state.kms_key_arn`: Optional customer-managed KMS key ARN for runner-state encryption. Null uses the AWS-owned DynamoDB key. + - `runner_state.point_in_time_recovery_enabled`: Enables point-in-time recovery for ephemeral runner state. + - `runner_state.deletion_protection_enabled`: Enables deletion protection for the runner-state table. + - `runner_state.tags`: Tags applied after the shared tag map. + EOT + type = object({ + config = object({ + kms_key_arn = optional(string, null) + point_in_time_recovery_enabled = optional(bool, true) + deletion_protection_enabled = optional(bool, false) + tags = optional(map(string), {}) + }) + runner_state = object({ + kms_key_arn = optional(string, null) + point_in_time_recovery_enabled = optional(bool, false) + deletion_protection_enabled = optional(bool, false) + tags = optional(map(string), {}) + }) + }) +} diff --git a/modules/storage-providers/aws/dynamodb/versions.tf b/modules/storage-providers/aws/dynamodb/versions.tf new file mode 100644 index 0000000000..3ef011ea0a --- /dev/null +++ b/modules/storage-providers/aws/dynamodb/versions.tf @@ -0,0 +1,10 @@ +terraform { + required_version = ">= 1.4.0" + + required_providers { + aws = { + source = "hashicorp/aws" + version = ">= 6.33" + } + } +} From cf54c51caab6515daf88816acb9120ffe86972aa Mon Sep 17 00:00:00 2001 From: edersonbrilhante Date: Mon, 21 Sep 2026 22:45:44 +0200 Subject: [PATCH 03/11] fix(storage): add DynamoDB dependency and Terraform compatibility (cherry picked from commit 409206e3e1234a2ad3451168e8b1f5769f94ca42) Signed-off-by: tehlers320 <16598119+tehlers320@users.noreply.github.com> --- modules/storage-providers/aws/dynamodb/versions.tf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/storage-providers/aws/dynamodb/versions.tf b/modules/storage-providers/aws/dynamodb/versions.tf index 3ef011ea0a..0bedc91fd5 100644 --- a/modules/storage-providers/aws/dynamodb/versions.tf +++ b/modules/storage-providers/aws/dynamodb/versions.tf @@ -1,5 +1,5 @@ terraform { - required_version = ">= 1.4.0" + required_version = ">= 1.5.6" required_providers { aws = { From 04e3efdb92901a22e2e5ae0cc06d01bb1b1e9f10 Mon Sep 17 00:00:00 2001 From: edersonbrilhante Date: Fri, 18 Sep 2026 22:07:43 +0200 Subject: [PATCH 04/11] fix(storage): add KMS permissions for DynamoDB consumers (cherry picked from commit 9e04ba18239d2aaec1ce7d9c380155753d016fea) Signed-off-by: tehlers320 <16598119+tehlers320@users.noreply.github.com> --- .../aws/dynamodb/tests/provider.tftest.hcl | 304 ++++++++++++++++++ 1 file changed, 304 insertions(+) create mode 100644 modules/storage-providers/aws/dynamodb/tests/provider.tftest.hcl diff --git a/modules/storage-providers/aws/dynamodb/tests/provider.tftest.hcl b/modules/storage-providers/aws/dynamodb/tests/provider.tftest.hcl new file mode 100644 index 0000000000..231b4111d9 --- /dev/null +++ b/modules/storage-providers/aws/dynamodb/tests/provider.tftest.hcl @@ -0,0 +1,304 @@ +mock_provider "aws" { + mock_resource "aws_dynamodb_table" { + defaults = { + arn = "arn:aws:dynamodb:eu-west-1:123456789012:table/test" + } + } +} + +variables { + prefix = "github-actions" + entry_ids = ["linux", "microvm"] + runner_config_access_scope_prefixes = { + linux = "arn:aws:ec2:eu-west-1:123456789012:instance/" + microvm = "arn:aws:ec2:eu-west-1:123456789012:instance/" + } + runner_config_ttl_seconds = 3600 + runner_state_ttl_seconds = 604800 + global_records = { + github_app_credentials = jsonencode([{ appId = 123456, privateKeyBase64 = "dGVzdA==" }]) + github_webhook_secret = "test-secret" + runner_matcher_config = jsonencode([{ key = "linux" }]) + } + entry_records = { + linux = { + run_as = "runner" + agent_mode = "ephemeral" + disable_default_labels = false + enable_jit_config = true + } + microvm = { + run_as = "root" + agent_mode = "ephemeral" + disable_default_labels = true + enable_jit_config = true + } + } + tags = { + Environment = "test" + Shared = "base" + } + config = { + config = { + kms_key_arn = "arn:aws:kms:eu-west-1:123456789012:key/config" + point_in_time_recovery_enabled = true + deletion_protection_enabled = true + tags = { + Shared = "config" + } + } + runner_state = { + kms_key_arn = "arn:aws:kms:eu-west-1:123456789012:key/runner-state" + point_in_time_recovery_enabled = false + deletion_protection_enabled = false + tags = { + Shared = "runner-state" + } + } + } +} + +run "creates_two_shared_scoped_tables" { + command = apply + + assert { + condition = ( + aws_dynamodb_table.config.name == "github-actions-config" + && aws_dynamodb_table.config.billing_mode == "PAY_PER_REQUEST" + && aws_dynamodb_table.config.hash_key == "scope" + && aws_dynamodb_table.config.range_key == "id" + && aws_dynamodb_table.config.point_in_time_recovery[0].enabled + && aws_dynamodb_table.config.deletion_protection_enabled + && aws_dynamodb_table.config.server_side_encryption[0].kms_key_arn == "arn:aws:kms:eu-west-1:123456789012:key/config" + && aws_dynamodb_table.config.tags["Shared"] == "config" + ) + error_message = "The durable provider table must be one encrypted, scoped, on-demand table for the whole multi-runner deployment." + } + + assert { + condition = ( + aws_dynamodb_table.runner_state.name == "github-actions-runner-state" + && aws_dynamodb_table.runner_state.billing_mode == "PAY_PER_REQUEST" + && aws_dynamodb_table.runner_state.hash_key == "scope" + && aws_dynamodb_table.runner_state.range_key == "id" + && aws_dynamodb_table.runner_state.ttl[0].enabled + && aws_dynamodb_table.runner_state.ttl[0].attribute_name == "expires_at" + && !aws_dynamodb_table.runner_state.point_in_time_recovery[0].enabled + && !aws_dynamodb_table.runner_state.deletion_protection_enabled + && aws_dynamodb_table.runner_state.server_side_encryption[0].kms_key_arn == "arn:aws:kms:eu-west-1:123456789012:key/runner-state" + && aws_dynamodb_table.runner_state.tags["Shared"] == "runner-state" + ) + error_message = "The runner-state provider table must be one encrypted, TTL-backed, scoped, on-demand table for the whole multi-runner deployment." + } + + assert { + condition = ( + output.config_table.name == "github-actions-config" + && output.runner_state_table.name == "github-actions-runner-state" + && output.runner_state_table.ttl_attribute_name == "expires_at" + ) + error_message = "The provider outputs must expose the two shared table contracts." + } + + assert { + condition = ( + output.capabilities.webhook.direct.environment_variables["RUNNER_CONFIG_STORAGE_PROVIDER"] == "aws_dynamodb" + && output.capabilities.webhook.direct.environment_variables["RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME"] == "github-actions-config" + && output.capabilities.webhook.direct.environment_variables["RUNNER_CONFIG_STORAGE_VERSION"] == terraform_data.config_version.id + && output.capabilities.webhook.eventbridge.webhook.environment_variables["RUNNER_CONFIG_STORAGE_VERSION"] == terraform_data.config_version.id + && output.capabilities.webhook.eventbridge.dispatcher.environment_variables["RUNNER_CONFIG_STORAGE_VERSION"] == terraform_data.config_version.id + && output.capabilities.webhook.direct.environment_variables["RUNNER_MATCHER_CONFIG_VERSION"] == sha256(jsonencode([{ key = "linux" }])) + && !contains(keys(output.capabilities.webhook.direct.environment_variables), "RUNNER_CONFIG_DYNAMODB_RUNNER_STATE_TABLE_NAME") + && !contains(keys(output.capabilities.webhook.direct.environment_variables), "RUNNER_CONFIG_DYNAMODB_TTL_SECONDS") + && !contains(keys(output.capabilities.webhook.eventbridge.webhook.environment_variables), "RUNNER_MATCHER_CONFIG_VERSION") + && output.capabilities.webhook.eventbridge.dispatcher.environment_variables["RUNNER_MATCHER_CONFIG_VERSION"] == sha256(jsonencode([{ key = "linux" }])) + && output.capabilities.entries["linux"].scale_up.environment_variables["RUNNER_CONFIG_DYNAMODB_ENTRY_ID"] == "linux" + && output.capabilities.entries["linux"].scale_up.environment_variables["RUNNER_CONFIG_STORAGE_VERSION"] == terraform_data.config_version.id + && !contains(keys(output.capabilities.entries["linux"].scale_up.environment_variables), "RUNNER_MATCHER_CONFIG_VERSION") + && output.capabilities.entries["microvm"].scale_down.environment_variables["RUNNER_CONFIG_DYNAMODB_ENTRY_ID"] == "microvm" + && output.capabilities.entries["microvm"].scale_down.environment_variables["RUNNER_CONFIG_STORAGE_VERSION"] == terraform_data.config_version.id + && output.capabilities.entries["linux"].pool.environment_variables["RUNNER_CONFIG_DYNAMODB_TTL_SECONDS"] == "3600" + && output.capabilities.entries["linux"].scale_down.environment_variables["RUNNER_CONFIG_DYNAMODB_RUNNER_STATE_TTL_SECONDS"] == "604800" + && !contains(keys(output.capabilities.entries["linux"].scale_down.environment_variables), "RUNNER_CONFIG_DYNAMODB_TTL_SECONDS") + && !contains(keys(output.capabilities.entries["linux"].job_retry.environment_variables), "RUNNER_CONFIG_DYNAMODB_ENTRY_ID") + && !contains(keys(output.capabilities.entries["linux"].job_retry.environment_variables), "RUNNER_CONFIG_DYNAMODB_RUNNER_STATE_TABLE_NAME") + && output.capabilities.entries["linux"].job_retry.environment_variables["RUNNER_CONFIG_STORAGE_VERSION"] == terraform_data.config_version.id + && output.capabilities.entries["linux"].runner.config_table_name == "github-actions-config" + && output.capabilities.entries["linux"].runner.runner_state_table_name == "github-actions-runner-state" + && output.capabilities.entries["linux"].runner.scope == "entry#linux#bootstrap" + ) + error_message = "The provider must expose one global and entry-scoped Lambda environment contract over the same two tables." + } + + assert { + condition = ( + jsondecode(output.capabilities.webhook.direct.iam_policy_json).Statement[0].Condition["ForAllValues:StringEquals"]["dynamodb:LeadingKeys"] == ["global#webhook", "global#matcher"] + && jsondecode(output.capabilities.webhook.eventbridge.webhook.iam_policy_json).Statement[0].Condition["ForAllValues:StringEquals"]["dynamodb:LeadingKeys"] == ["global#webhook"] + && jsondecode(output.capabilities.webhook.eventbridge.dispatcher.iam_policy_json).Statement[0].Condition["ForAllValues:StringEquals"]["dynamodb:LeadingKeys"] == ["global#matcher"] + && jsondecode(output.capabilities.entries["linux"].scale_up.iam_policy_json).Statement[0].Action == ["dynamodb:GetItem"] + && jsondecode(output.capabilities.entries["linux"].scale_up.iam_policy_json).Statement[0].Condition["ForAllValues:StringEquals"]["dynamodb:LeadingKeys"] == ["global#github-app"] + && jsondecode(output.capabilities.entries["linux"].scale_up.iam_policy_json).Statement[1].Action == ["dynamodb:GetItem", "dynamodb:PutItem"] + && jsondecode(output.capabilities.entries["linux"].scale_up.iam_policy_json).Statement[1].Condition["ForAllValues:StringEquals"]["dynamodb:LeadingKeys"] == ["entry#linux#runner-group"] + && jsondecode(output.capabilities.entries["linux"].scale_up.iam_policy_json).Statement[2].Action == ["dynamodb:PutItem"] + && jsondecode(output.capabilities.entries["linux"].scale_up.iam_policy_json).Statement[2].Condition["ForAllValues:StringLike"]["dynamodb:LeadingKeys"] == ["arn:aws:ec2:eu-west-1:123456789012:instance/*"] + && jsondecode(output.capabilities.entries["linux"].scale_up.iam_policy_json).Statement[3].Action == ["dynamodb:PutItem", "dynamodb:Query", "dynamodb:UpdateItem"] + && jsondecode(output.capabilities.entries["linux"].scale_up.iam_policy_json).Statement[3].Condition["ForAllValues:StringEquals"]["dynamodb:LeadingKeys"] == ["entry#linux#runner-state"] + && jsondecode(output.capabilities.entries["microvm"].scale_down.iam_policy_json).Statement[1].Action == ["dynamodb:DeleteItem", "dynamodb:Query", "dynamodb:UpdateItem"] + && jsondecode(output.capabilities.entries["microvm"].scale_down.iam_policy_json).Statement[1].Condition["ForAllValues:StringEquals"]["dynamodb:LeadingKeys"] == ["entry#microvm#runner-state"] + && !contains(jsondecode(output.capabilities.entries["linux"].pool.iam_policy_json).Statement[3].Action, "dynamodb:DeleteItem") + && jsondecode(output.capabilities.entries["linux"].runner.iam_policy_json).Statement[0].Condition["ForAllValues:StringEquals"]["dynamodb:LeadingKeys"] == ["entry#linux#bootstrap"] + && jsondecode(output.capabilities.entries["linux"].runner.iam_policy_json).Statement[1].Condition["ForAllValues:StringEquals"]["dynamodb:LeadingKeys"] == ["$${ec2:SourceInstanceARN}"] + && anytrue([ + for statement in jsondecode(output.capabilities.webhook.direct.iam_policy_json).Statement : + statement.Action == ["kms:Decrypt"] && statement.Resource == ["arn:aws:kms:eu-west-1:123456789012:key/config"] + ]) + && anytrue([ + for statement in jsondecode(output.capabilities.entries["linux"].scale_up.iam_policy_json).Statement : + statement.Action == ["kms:Decrypt"] && statement.Resource == ["arn:aws:kms:eu-west-1:123456789012:key/config"] + ]) + && anytrue([ + for statement in jsondecode(output.capabilities.entries["linux"].scale_up.iam_policy_json).Statement : + statement.Action == ["kms:Decrypt"] && statement.Resource == ["arn:aws:kms:eu-west-1:123456789012:key/runner-state"] + ]) + && anytrue([ + for statement in jsondecode(output.capabilities.entries["linux"].runner.iam_policy_json).Statement : + statement.Action == ["kms:Decrypt"] && statement.Resource == ["arn:aws:kms:eu-west-1:123456789012:key/config"] + ]) + && anytrue([ + for statement in jsondecode(output.capabilities.entries["linux"].runner.iam_policy_json).Statement : + statement.Action == ["kms:Decrypt"] && statement.Resource == ["arn:aws:kms:eu-west-1:123456789012:key/runner-state"] + ]) + ) + error_message = "Provider IAM capabilities must restrict global and entry operations with DynamoDB leading-key conditions." + } + + + assert { + condition = ( + jsondecode(aws_dynamodb_table_item.github_app_credentials.item).scope.S == "global#github-app" + && jsondecode(aws_dynamodb_table_item.github_webhook_secret.item).scope.S == "global#webhook" + && jsondecode(aws_dynamodb_table_item.runner_matcher_config.item).scope.S == "global#matcher" + && jsondecode(aws_dynamodb_table_item.runner_config["linux"].item).scope.S == "entry#linux#bootstrap" + && jsondecode(aws_dynamodb_table_item.runner_config["linux"].item).id.S == "runner-config" + && jsondecode(jsondecode(aws_dynamodb_table_item.runner_config["linux"].item).value.S).run_as == "runner" + && jsondecode(jsondecode(aws_dynamodb_table_item.runner_config["linux"].item).value.S).runner_config_storage.table_name == "github-actions-runner-state" + && jsondecode(jsondecode(aws_dynamodb_table_item.runner_config["linux"].item).value.S).runner_config_storage.access_scope == "compute-resource" + && jsondecode(jsondecode(aws_dynamodb_table_item.runner_config["linux"].item).value.S).runner_config_storage.id == "config" + ) + error_message = "Each entry must receive one durable bootstrap record that points at its scope in the shared runner-state table." + } +} + +run "storage_version_tracks_global_record_changes" { + command = apply + + variables { + global_records = { + github_app_credentials = jsonencode([{ appId = 123456, privateKeyBase64 = "dGVzdA==" }]) + github_webhook_secret = "rotated-test-secret" + runner_matcher_config = jsonencode([{ key = "linux" }]) + } + } + + assert { + condition = ( + output.capabilities.webhook.direct.environment_variables["RUNNER_CONFIG_STORAGE_VERSION"] == terraform_data.config_version.id + && output.capabilities.entries["linux"].job_retry.environment_variables["RUNNER_CONFIG_STORAGE_VERSION"] == terraform_data.config_version.id + ) + error_message = "A durable global-record update must publish the replacement storage resource ID to every Lambda capability." + } +} + +run "matcher_version_tracks_matcher_content" { + command = apply + + variables { + global_records = { + github_app_credentials = jsonencode([{ appId = 123456, privateKeyBase64 = "dGVzdA==" }]) + github_webhook_secret = "rotated-test-secret" + runner_matcher_config = jsonencode([{ key = "microvm" }]) + } + } + + assert { + condition = ( + output.capabilities.webhook.direct.environment_variables["RUNNER_MATCHER_CONFIG_VERSION"] == sha256(jsonencode([{ key = "microvm" }])) + && output.capabilities.webhook.direct.environment_variables["RUNNER_MATCHER_CONFIG_VERSION"] != sha256(jsonencode([{ key = "linux" }])) + && output.capabilities.webhook.direct.environment_variables["RUNNER_CONFIG_STORAGE_VERSION"] == terraform_data.config_version.id + ) + error_message = "The matcher and opaque storage versions must change without exposing the matcher payload whenever the durable matcher record changes." + } +} + +run "storage_version_tracks_entry_record_changes" { + command = apply + + variables { + global_records = { + github_app_credentials = jsonencode([{ appId = 123456, privateKeyBase64 = "dGVzdA==" }]) + github_webhook_secret = "rotated-test-secret" + runner_matcher_config = jsonencode([{ key = "microvm" }]) + } + entry_records = { + linux = { + run_as = "root" + agent_mode = "ephemeral" + disable_default_labels = false + enable_jit_config = true + } + microvm = { + run_as = "root" + agent_mode = "ephemeral" + disable_default_labels = true + enable_jit_config = true + } + } + } + + assert { + condition = ( + output.capabilities.entries["linux"].scale_up.environment_variables["RUNNER_CONFIG_STORAGE_VERSION"] == terraform_data.config_version.id + && output.capabilities.webhook.eventbridge.webhook.environment_variables["RUNNER_CONFIG_STORAGE_VERSION"] == terraform_data.config_version.id + ) + error_message = "A durable entry-record update must publish the replacement storage resource ID to every Lambda capability." + } +} + +run "rejects_missing_runner_config_access_scope_prefix" { + command = plan + + variables { + runner_config_access_scope_prefixes = { + linux = "arn:aws:ec2:eu-west-1:123456789012:instance/" + } + } + + expect_failures = [terraform_data.config_version] +} + +run "rejects_runner_state_ttl_not_greater_than_runner_config_ttl" { + command = plan + + variables { + runner_state_ttl_seconds = 3600 + } + + expect_failures = [terraform_data.config_version] +} + +run "rejects_missing_entry_record" { + command = plan + + variables { + entry_records = { + linux = { + run_as = "runner" + agent_mode = "ephemeral" + disable_default_labels = false + enable_jit_config = true + } + } + } + + expect_failures = [terraform_data.config_version] +} From 720d07333514d2e544c4c06d335ae75d6b995fca Mon Sep 17 00:00:00 2001 From: tehlers320 <16598119+tehlers320@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:10:23 +0000 Subject: [PATCH 05/11] feat(storage): add optional accessScope to RunnerConfigRecord Prerequisite contract for the DynamoDB runner config store ported from #5279/#5458 (see review on #5458: core lacked RunnerConfigRecord.accessScope). Optional, so the SSM provider is unaffected. Signed-off-by: tehlers320 <16598119+tehlers320@users.noreply.github.com> Co-Authored-By: Claude Sonnet 5.5 --- lambdas/libs/storage-providers/core/index.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/lambdas/libs/storage-providers/core/index.ts b/lambdas/libs/storage-providers/core/index.ts index 86950eb2c7..e56cf2bdef 100644 --- a/lambdas/libs/storage-providers/core/index.ts +++ b/lambdas/libs/storage-providers/core/index.ts @@ -9,6 +9,7 @@ export interface RunnerConfigMetadata { export interface RunnerConfigRecord { runnerId: string; value: string; + accessScope?: string; } export interface RunnerConfigStore { From 68df029448456578016b1be9329fea58d57a42d2 Mon Sep 17 00:00:00 2001 From: tehlers320 <16598119+tehlers320@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:10:23 +0000 Subject: [PATCH 06/11] chore(deps): refresh lambda lockfile for @aws-sdk/client-dynamodb Signed-off-by: tehlers320 <16598119+tehlers320@users.noreply.github.com> Co-Authored-By: Claude Sonnet 5.5 --- lambdas/yarn.lock | 324 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 324 insertions(+) diff --git a/lambdas/yarn.lock b/lambdas/yarn.lock index e19e4a2f28..c4ba1158e9 100644 --- a/lambdas/yarn.lock +++ b/lambdas/yarn.lock @@ -152,6 +152,7 @@ __metadata: dependencies: "@aws-github-runner/aws-powertools-util": "npm:*" "@aws-github-runner/aws-ssm-util": "npm:*" + "@aws-sdk/client-dynamodb": "npm:^3.1009.0" "@aws-sdk/client-ssm": "npm:^3.1009.0" aws-sdk-client-mock: "npm:^4.1.0" aws-sdk-client-mock-jest: "npm:^4.1.0" @@ -304,6 +305,24 @@ __metadata: languageName: node linkType: hard +"@aws-sdk/client-dynamodb@npm:^3.1009.0": + version: 3.1166.0 + resolution: "@aws-sdk/client-dynamodb@npm:3.1166.0" + dependencies: + "@aws-sdk/core": "npm:^3.981.0" + "@aws-sdk/credential-provider-node": "npm:^3.972.96" + "@aws-sdk/dynamodb-codec": "npm:^3.973.58" + "@aws-sdk/middleware-endpoint-discovery": "npm:^3.972.39" + "@aws-sdk/types": "npm:^3.975.1" + "@smithy/core": "npm:^3.40.0" + "@smithy/fetch-http-handler": "npm:^5.8.1" + "@smithy/node-http-handler": "npm:^4.14.2" + "@smithy/types": "npm:^4.20.0" + tslib: "npm:^2.6.2" + checksum: 10c0/e6853d81bfdcbe9808be11b1b41676f1325eb518921256f79e7e3bf19e350f4d202d711b09808b98cdcf318a8471e63a303f118d0a723abf4ccdfe5fb9718da8 + languageName: node + linkType: hard + "@aws-sdk/client-ec2@npm:^3.1009.0": version: 3.1151.0 resolution: "@aws-sdk/client-ec2@npm:3.1151.0" @@ -406,6 +425,22 @@ __metadata: languageName: node linkType: hard +"@aws-sdk/core@npm:^3.981.0": + version: 3.981.0 + resolution: "@aws-sdk/core@npm:3.981.0" + dependencies: + "@aws-sdk/types": "npm:^3.975.1" + "@aws-sdk/xml-builder": "npm:^3.972.43" + "@aws/lambda-invoke-store": "npm:^0.3.0" + "@smithy/core": "npm:^3.40.0" + "@smithy/signature-v4": "npm:^5.7.5" + "@smithy/types": "npm:^4.20.0" + bowser: "npm:^2.11.0" + tslib: "npm:^2.6.2" + checksum: 10c0/4108dfaac2488e6d87c3c0cd14ded569e3545bdcb2cf17597321ba666d9b29eb28372ebd953995318eca47e225cf1f47d98e8089a253af64e5f9cd9bb113b743 + languageName: node + linkType: hard + "@aws-sdk/credential-provider-cognito-identity@npm:^3.972.73": version: 3.972.73 resolution: "@aws-sdk/credential-provider-cognito-identity@npm:3.972.73" @@ -432,6 +467,19 @@ __metadata: languageName: node linkType: hard +"@aws-sdk/credential-provider-env@npm:^3.972.84": + version: 3.972.84 + resolution: "@aws-sdk/credential-provider-env@npm:3.972.84" + dependencies: + "@aws-sdk/core": "npm:^3.981.0" + "@aws-sdk/types": "npm:^3.975.1" + "@smithy/core": "npm:^3.40.0" + "@smithy/types": "npm:^4.20.0" + tslib: "npm:^2.6.2" + checksum: 10c0/0533a619ff4376e560fa38473746d81f5456cf8c862e5ff02c7af8a662b2e46c9c5d908f60c45c136fb5b54848948c22e3d9052662053efac96dcb4f78902d90 + languageName: node + linkType: hard + "@aws-sdk/credential-provider-http@npm:^3.972.76": version: 3.972.76 resolution: "@aws-sdk/credential-provider-http@npm:3.972.76" @@ -447,6 +495,21 @@ __metadata: languageName: node linkType: hard +"@aws-sdk/credential-provider-http@npm:^3.972.86": + version: 3.972.86 + resolution: "@aws-sdk/credential-provider-http@npm:3.972.86" + dependencies: + "@aws-sdk/core": "npm:^3.981.0" + "@aws-sdk/types": "npm:^3.975.1" + "@smithy/core": "npm:^3.40.0" + "@smithy/fetch-http-handler": "npm:^5.8.1" + "@smithy/node-http-handler": "npm:^4.14.2" + "@smithy/types": "npm:^4.20.0" + tslib: "npm:^2.6.2" + checksum: 10c0/f41177c69e086fccbea8b53a39c7809f5898e861af8f8743bb96a79ac77a90f18f180b8f0ea5889f80982e516ec655debfea38273d65d67777e8d5c65a90c327 + languageName: node + linkType: hard + "@aws-sdk/credential-provider-ini@npm:^3.973.19": version: 3.973.19 resolution: "@aws-sdk/credential-provider-ini@npm:3.973.19" @@ -468,6 +531,27 @@ __metadata: languageName: node linkType: hard +"@aws-sdk/credential-provider-ini@npm:^3.973.29": + version: 3.973.29 + resolution: "@aws-sdk/credential-provider-ini@npm:3.973.29" + dependencies: + "@aws-sdk/core": "npm:^3.981.0" + "@aws-sdk/credential-provider-env": "npm:^3.972.84" + "@aws-sdk/credential-provider-http": "npm:^3.972.86" + "@aws-sdk/credential-provider-login": "npm:^3.972.91" + "@aws-sdk/credential-provider-process": "npm:^3.972.84" + "@aws-sdk/credential-provider-sso": "npm:^3.973.28" + "@aws-sdk/credential-provider-web-identity": "npm:^3.972.90" + "@aws-sdk/nested-clients": "npm:^3.998.3" + "@aws-sdk/types": "npm:^3.975.1" + "@smithy/core": "npm:^3.40.0" + "@smithy/credential-provider-imds": "npm:^4.5.2" + "@smithy/types": "npm:^4.20.0" + tslib: "npm:^2.6.2" + checksum: 10c0/4309698bdd805d46fa29358ef20addb93aefadc0d6ccf04bda83121c76e6cf52bce0ba331ef0af56c66e23c12374a6fec1ce9bd12f2c47100556d40fbd535c99 + languageName: node + linkType: hard + "@aws-sdk/credential-provider-login@npm:^3.972.81": version: 3.972.81 resolution: "@aws-sdk/credential-provider-login@npm:3.972.81" @@ -482,6 +566,20 @@ __metadata: languageName: node linkType: hard +"@aws-sdk/credential-provider-login@npm:^3.972.91": + version: 3.972.91 + resolution: "@aws-sdk/credential-provider-login@npm:3.972.91" + dependencies: + "@aws-sdk/core": "npm:^3.981.0" + "@aws-sdk/nested-clients": "npm:^3.998.3" + "@aws-sdk/types": "npm:^3.975.1" + "@smithy/core": "npm:^3.40.0" + "@smithy/types": "npm:^4.20.0" + tslib: "npm:^2.6.2" + checksum: 10c0/3dd88dbbe0b797400baf691bc91ff88f44e46d729ee6d1f282b78facfae3e2b6accd78abc93ba1723b3ed1cc19dcba1b2bdb5572d75d7bde2cdc698e0afb872d + languageName: node + linkType: hard + "@aws-sdk/credential-provider-node@npm:^3.972.86": version: 3.972.86 resolution: "@aws-sdk/credential-provider-node@npm:3.972.86" @@ -501,6 +599,25 @@ __metadata: languageName: node linkType: hard +"@aws-sdk/credential-provider-node@npm:^3.972.96": + version: 3.972.96 + resolution: "@aws-sdk/credential-provider-node@npm:3.972.96" + dependencies: + "@aws-sdk/credential-provider-env": "npm:^3.972.84" + "@aws-sdk/credential-provider-http": "npm:^3.972.86" + "@aws-sdk/credential-provider-ini": "npm:^3.973.29" + "@aws-sdk/credential-provider-process": "npm:^3.972.84" + "@aws-sdk/credential-provider-sso": "npm:^3.973.28" + "@aws-sdk/credential-provider-web-identity": "npm:^3.972.90" + "@aws-sdk/types": "npm:^3.975.1" + "@smithy/core": "npm:^3.40.0" + "@smithy/credential-provider-imds": "npm:^4.5.2" + "@smithy/types": "npm:^4.20.0" + tslib: "npm:^2.6.2" + checksum: 10c0/f332e6379d65bba4b71e17eefc7041715ef49e8700c1f248760e645a2be55e6a586387a99307cdee5166b4c98d37128b99a51cd54155a8dac5d1334f07cb9ec0 + languageName: node + linkType: hard + "@aws-sdk/credential-provider-process@npm:^3.972.74": version: 3.972.74 resolution: "@aws-sdk/credential-provider-process@npm:3.972.74" @@ -514,6 +631,19 @@ __metadata: languageName: node linkType: hard +"@aws-sdk/credential-provider-process@npm:^3.972.84": + version: 3.972.84 + resolution: "@aws-sdk/credential-provider-process@npm:3.972.84" + dependencies: + "@aws-sdk/core": "npm:^3.981.0" + "@aws-sdk/types": "npm:^3.975.1" + "@smithy/core": "npm:^3.40.0" + "@smithy/types": "npm:^4.20.0" + tslib: "npm:^2.6.2" + checksum: 10c0/062e5b402aede176738310ac2421e9ea25f7c878a17b127205145e312fad8412777ca155d3e97cb4b1fb611d4c439d71bf834668a24eb9fc1f6efa551dee1083 + languageName: node + linkType: hard + "@aws-sdk/credential-provider-sso@npm:^3.973.18": version: 3.973.18 resolution: "@aws-sdk/credential-provider-sso@npm:3.973.18" @@ -529,6 +659,21 @@ __metadata: languageName: node linkType: hard +"@aws-sdk/credential-provider-sso@npm:^3.973.28": + version: 3.973.28 + resolution: "@aws-sdk/credential-provider-sso@npm:3.973.28" + dependencies: + "@aws-sdk/core": "npm:^3.981.0" + "@aws-sdk/nested-clients": "npm:^3.998.3" + "@aws-sdk/token-providers": "npm:3.1166.0" + "@aws-sdk/types": "npm:^3.975.1" + "@smithy/core": "npm:^3.40.0" + "@smithy/types": "npm:^4.20.0" + tslib: "npm:^2.6.2" + checksum: 10c0/76db06bdd3de816dda5829e160bdb9c89a2fa560dad93178909fd7d0f63c68e922a5ebc3375f5fb6a289bd42ef1ba555bee2b289b041a9fbda769cea0c085c46 + languageName: node + linkType: hard + "@aws-sdk/credential-provider-web-identity@npm:^3.972.80": version: 3.972.80 resolution: "@aws-sdk/credential-provider-web-identity@npm:3.972.80" @@ -543,6 +688,20 @@ __metadata: languageName: node linkType: hard +"@aws-sdk/credential-provider-web-identity@npm:^3.972.90": + version: 3.972.90 + resolution: "@aws-sdk/credential-provider-web-identity@npm:3.972.90" + dependencies: + "@aws-sdk/core": "npm:^3.981.0" + "@aws-sdk/nested-clients": "npm:^3.998.3" + "@aws-sdk/types": "npm:^3.975.1" + "@smithy/core": "npm:^3.40.0" + "@smithy/types": "npm:^4.20.0" + tslib: "npm:^2.6.2" + checksum: 10c0/54a7afdf948e1be8e55a1cd825ea48d5ae5f0d845997e0f199e8b5e76dcc5c6bbe9dc2924218175e2e6eaeafc2896eee97d1c4f11504c48899bf3f3ee97103ca + languageName: node + linkType: hard + "@aws-sdk/credential-providers@npm:^3.1009.0": version: 3.1151.0 resolution: "@aws-sdk/credential-providers@npm:3.1151.0" @@ -567,6 +726,28 @@ __metadata: languageName: node linkType: hard +"@aws-sdk/dynamodb-codec@npm:^3.973.58": + version: 3.973.58 + resolution: "@aws-sdk/dynamodb-codec@npm:3.973.58" + dependencies: + "@aws-sdk/core": "npm:^3.981.0" + "@smithy/core": "npm:^3.40.0" + "@smithy/types": "npm:^4.20.0" + tslib: "npm:^2.6.2" + checksum: 10c0/0dbbca5f70986546853753b23c297bcd9d0ecaea7862e681061b77710537940ff6b589fdff97d53c86099a4a08de3c7c4206ce5df8bf170c3a2ac64af9f28c96 + languageName: node + linkType: hard + +"@aws-sdk/endpoint-cache@npm:^3.972.11": + version: 3.972.11 + resolution: "@aws-sdk/endpoint-cache@npm:3.972.11" + dependencies: + mnemonist: "npm:0.38.3" + tslib: "npm:^2.6.2" + checksum: 10c0/8f3c039fb2dd8e434cd2992bce2a840e6f6470be5ae6d71c762f6cb842149fb60d5566ca470319d5abcf90b115d2c1a0114ed3328afbfc0abed4cbcd52ad03a1 + languageName: node + linkType: hard + "@aws-sdk/lib-storage@npm:^3.1009.0": version: 3.1151.0 resolution: "@aws-sdk/lib-storage@npm:3.1151.0" @@ -583,6 +764,19 @@ __metadata: languageName: node linkType: hard +"@aws-sdk/middleware-endpoint-discovery@npm:^3.972.39": + version: 3.972.39 + resolution: "@aws-sdk/middleware-endpoint-discovery@npm:3.972.39" + dependencies: + "@aws-sdk/endpoint-cache": "npm:^3.972.11" + "@aws-sdk/types": "npm:^3.975.1" + "@smithy/core": "npm:^3.40.0" + "@smithy/types": "npm:^4.20.0" + tslib: "npm:^2.6.2" + checksum: 10c0/2cb7e7ba6ea0c0de7b3658f1c4365b394845709bc31ccc98dbc113643d334028db25cdb9f3df5cdecf731d1a79a476069cf78ff6bcdb1981f7b79ff864ee950d + languageName: node + linkType: hard + "@aws-sdk/middleware-sdk-ec2@npm:^3.972.62": version: 3.972.62 resolution: "@aws-sdk/middleware-sdk-ec2@npm:3.972.62" @@ -639,6 +833,22 @@ __metadata: languageName: node linkType: hard +"@aws-sdk/nested-clients@npm:^3.998.3": + version: 3.998.3 + resolution: "@aws-sdk/nested-clients@npm:3.998.3" + dependencies: + "@aws-sdk/core": "npm:^3.981.0" + "@aws-sdk/signature-v4-multi-region": "npm:^3.996.52" + "@aws-sdk/types": "npm:^3.975.1" + "@smithy/core": "npm:^3.40.0" + "@smithy/fetch-http-handler": "npm:^5.8.1" + "@smithy/node-http-handler": "npm:^4.14.2" + "@smithy/types": "npm:^4.20.0" + tslib: "npm:^2.6.2" + checksum: 10c0/a3952f348754f1f67b63115f040bc03557bc569882a99ca86ccd35cda10228c388df1706e13311d60e5ce879089f07fde165dc725f619d518701b79aeaae8467 + languageName: node + linkType: hard + "@aws-sdk/signature-v4-multi-region@npm:^3.996.48": version: 3.996.48 resolution: "@aws-sdk/signature-v4-multi-region@npm:3.996.48" @@ -651,6 +861,18 @@ __metadata: languageName: node linkType: hard +"@aws-sdk/signature-v4-multi-region@npm:^3.996.52": + version: 3.996.52 + resolution: "@aws-sdk/signature-v4-multi-region@npm:3.996.52" + dependencies: + "@aws-sdk/types": "npm:^3.975.1" + "@smithy/signature-v4": "npm:^5.7.5" + "@smithy/types": "npm:^4.20.0" + tslib: "npm:^2.6.2" + checksum: 10c0/6c88d7ddc206382411efb218c28dc24edb66fc9a66eef613f92574a70b188757bf8252791c00059722cb0f1dd879e976027e73ea1e86896afeb5a4c462a4718b + languageName: node + linkType: hard + "@aws-sdk/token-providers@npm:3.1150.0": version: 3.1150.0 resolution: "@aws-sdk/token-providers@npm:3.1150.0" @@ -665,6 +887,20 @@ __metadata: languageName: node linkType: hard +"@aws-sdk/token-providers@npm:3.1166.0": + version: 3.1166.0 + resolution: "@aws-sdk/token-providers@npm:3.1166.0" + dependencies: + "@aws-sdk/core": "npm:^3.981.0" + "@aws-sdk/nested-clients": "npm:^3.998.3" + "@aws-sdk/types": "npm:^3.975.1" + "@smithy/core": "npm:^3.40.0" + "@smithy/types": "npm:^4.20.0" + tslib: "npm:^2.6.2" + checksum: 10c0/40a58934cda03a4cbeafff446cca1debc1381954759705d45dc29950541e0017f9d9d43749609c0156ac490921bf6e7839488ba07361295d532afca97eeaddad + languageName: node + linkType: hard + "@aws-sdk/types@npm:^3.4.1, @aws-sdk/types@npm:^3.973.6, @aws-sdk/types@npm:^3.974.6": version: 3.974.6 resolution: "@aws-sdk/types@npm:3.974.6" @@ -675,6 +911,16 @@ __metadata: languageName: node linkType: hard +"@aws-sdk/types@npm:^3.975.1": + version: 3.975.1 + resolution: "@aws-sdk/types@npm:3.975.1" + dependencies: + "@smithy/types": "npm:^4.20.0" + tslib: "npm:^2.6.2" + checksum: 10c0/74075c70c528f64af375e69361bf2b04886e1c23de3fac2be1e15b6fc048f2873c3d8fa00ec01ba0d36210e4db0037ea6feabec641e80377a9741a8118290333 + languageName: node + linkType: hard + "@aws-sdk/xml-builder@npm:^3.972.41": version: 3.972.41 resolution: "@aws-sdk/xml-builder@npm:3.972.41" @@ -685,6 +931,16 @@ __metadata: languageName: node linkType: hard +"@aws-sdk/xml-builder@npm:^3.972.43": + version: 3.972.43 + resolution: "@aws-sdk/xml-builder@npm:3.972.43" + dependencies: + "@smithy/types": "npm:^4.20.0" + tslib: "npm:^2.6.2" + checksum: 10c0/ed0806481ad42c36003f44de54eea0615020e6640542011b6e4cf46e54976a6f7597df35be3fc3b143a02f5291ca62cb19aaf28ae6b816fda66685ce998a8b44 + languageName: node + linkType: hard + "@aws/lambda-invoke-store@npm:0.3.0, @aws/lambda-invoke-store@npm:^0.3.0": version: 0.3.0 resolution: "@aws/lambda-invoke-store@npm:0.3.0" @@ -3616,6 +3872,16 @@ __metadata: languageName: node linkType: hard +"@smithy/core@npm:^3.38.0, @smithy/core@npm:^3.39.0, @smithy/core@npm:^3.40.0": + version: 3.40.0 + resolution: "@smithy/core@npm:3.40.0" + dependencies: + "@smithy/types": "npm:^4.20.0" + tslib: "npm:^2.6.2" + checksum: 10c0/b39226a667990fd7b3679e96ff202ab815fca960a9ebf8174d608ac3abb01378b2fbd9ba05331edee628b7be00bb274059a3b7ee27073841252159da5968604e + languageName: node + linkType: hard + "@smithy/credential-provider-imds@npm:^4.5.2": version: 4.5.2 resolution: "@smithy/credential-provider-imds@npm:4.5.2" @@ -3638,6 +3904,17 @@ __metadata: languageName: node linkType: hard +"@smithy/fetch-http-handler@npm:^5.8.1": + version: 5.8.1 + resolution: "@smithy/fetch-http-handler@npm:5.8.1" + dependencies: + "@smithy/core": "npm:^3.39.0" + "@smithy/types": "npm:^4.20.0" + tslib: "npm:^2.6.2" + checksum: 10c0/d1715fe9cc4845f172f974c17499cabaf0df17ae746187a9b5806237427aef4fda42ba9ce182e1e44262246264f9dd0c3612e04e1a70e21912c7a28f70ad2c83 + languageName: node + linkType: hard + "@smithy/node-http-handler@npm:^4.12.1": version: 4.12.1 resolution: "@smithy/node-http-handler@npm:4.12.1" @@ -3649,6 +3926,17 @@ __metadata: languageName: node linkType: hard +"@smithy/node-http-handler@npm:^4.14.2": + version: 4.14.2 + resolution: "@smithy/node-http-handler@npm:4.14.2" + dependencies: + "@smithy/core": "npm:^3.39.0" + "@smithy/types": "npm:^4.20.0" + tslib: "npm:^2.6.2" + checksum: 10c0/4cc882ecbc34fd763ed18a8a8325a425252f7a75d1231d1f6a7d916382d917bbef9b4c74c107875ad1ffa81578bda2867c65889c5e2c0be8fb0de6b1ce997f90 + languageName: node + linkType: hard + "@smithy/service-error-classification@npm:^2.0.4": version: 2.1.5 resolution: "@smithy/service-error-classification@npm:2.1.5" @@ -3669,6 +3957,17 @@ __metadata: languageName: node linkType: hard +"@smithy/signature-v4@npm:^5.7.5": + version: 5.7.5 + resolution: "@smithy/signature-v4@npm:5.7.5" + dependencies: + "@smithy/core": "npm:^3.38.0" + "@smithy/types": "npm:^4.19.0" + tslib: "npm:^2.6.2" + checksum: 10c0/f75e2e64c98f8ccfd723293b67fcdcc43fbac095ba7575e7897313bc8347180e1b37a1eb9e5afb25a680837b240e6af640ea59c1883097f6052d5b69b6d40ad8 + languageName: node + linkType: hard + "@smithy/types@npm:^2.12.0": version: 2.12.0 resolution: "@smithy/types@npm:2.12.0" @@ -3687,6 +3986,15 @@ __metadata: languageName: node linkType: hard +"@smithy/types@npm:^4.20.0": + version: 4.20.0 + resolution: "@smithy/types@npm:4.20.0" + dependencies: + tslib: "npm:^2.6.2" + checksum: 10c0/dc105f8ca1c3e1475da470a5b442ab73947144282e5d22c57dad22854983979a23725346d6227686f77c7621690ab5f28b3def286acf839258fb93691f7a02ec + languageName: node + linkType: hard + "@standard-schema/spec@npm:^1.1.0": version: 1.1.0 resolution: "@standard-schema/spec@npm:1.1.0" @@ -7313,6 +7621,15 @@ __metadata: languageName: node linkType: hard +"mnemonist@npm:0.38.3": + version: 0.38.3 + resolution: "mnemonist@npm:0.38.3" + dependencies: + obliterator: "npm:^1.6.1" + checksum: 10c0/064aa1ee1a89fce2754423b3617c598fd65bc34311eb3c01dc063976f6b819b073bd23532415cf8c92240157b4c8fbb7ec5d79d717f2bd4fcd95d8131cb23acb + languageName: node + linkType: hard + "moment-timezone@npm:^0.6.0": version: 0.6.5 resolution: "moment-timezone@npm:0.6.5" @@ -7619,6 +7936,13 @@ __metadata: languageName: node linkType: hard +"obliterator@npm:^1.6.1": + version: 1.6.1 + resolution: "obliterator@npm:1.6.1" + checksum: 10c0/5fad57319aae0ef6e34efa640541d41c2dd9790a7ab808f17dcb66c83a81333963fc2dfcfa6e1b62158e5cef6291cdcf15c503ad6c3de54b2227dd4c3d7e1b55 + languageName: node + linkType: hard + "obug@npm:^2.1.1": version: 2.2.1 resolution: "obug@npm:2.2.1" From fda9dee9ea0c58e822f88544ba4a5f1628bae48c Mon Sep 17 00:00:00 2001 From: tehlers320 <16598119+tehlers320@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:12:16 +0000 Subject: [PATCH 07/11] feat(storage): select the aws_dynamodb provider in createStorageProviders Compose the DynamoDB runner config, runner group cache and GitHub App credentials stores when RUNNER_CONFIG_STORAGE_PROVIDER=aws_dynamodb, and make RunnerConfigStorage.consumer optional (EC2 runners consume their own config in the instance bootstrap, the control plane never calls it). Builds on #5279 / #5458 (edersonbrilhante) and #5266 (wadherv). Signed-off-by: tehlers320 <16598119+tehlers320@users.noreply.github.com> Co-Authored-By: Claude Sonnet 5.5 --- lambdas/libs/storage-providers/core/index.ts | 3 +- lambdas/libs/storage-providers/provider.ts | 5 ++- .../storage-providers.test.ts | 44 ++++++++++++------- .../storage-providers/storage-providers.ts | 20 +++++++++ 4 files changed, 53 insertions(+), 19 deletions(-) diff --git a/lambdas/libs/storage-providers/core/index.ts b/lambdas/libs/storage-providers/core/index.ts index e56cf2bdef..12d88775fc 100644 --- a/lambdas/libs/storage-providers/core/index.ts +++ b/lambdas/libs/storage-providers/core/index.ts @@ -44,7 +44,8 @@ export interface RunnerConfigConsumer { export interface RunnerConfigStorage { runnerConfig: RunnerConfigStore; runnerGroupCache: RunnerGroupCacheStore; - consumer: RunnerConfigConsumer; + // Not provided by aws_dynamodb: EC2 runners consume their config in the instance bootstrap. + consumer?: RunnerConfigConsumer; } export interface CommonStorage { diff --git a/lambdas/libs/storage-providers/provider.ts b/lambdas/libs/storage-providers/provider.ts index cf1e965085..9a36fb8f69 100644 --- a/lambdas/libs/storage-providers/provider.ts +++ b/lambdas/libs/storage-providers/provider.ts @@ -2,7 +2,10 @@ export const runnerConfigStorageProvider = { awsSsm: 'aws_ssm', awsDynamodb: 'aws_dynamodb', } as const; -export const runnerConfigStorageProviders = [runnerConfigStorageProvider.awsSsm, runnerConfigStorageProvider.awsDynamodb] as const; +export const runnerConfigStorageProviders = [ + runnerConfigStorageProvider.awsSsm, + runnerConfigStorageProvider.awsDynamodb, +] as const; export type RunnerConfigStorageProvider = (typeof runnerConfigStorageProviders)[number]; diff --git a/lambdas/libs/storage-providers/storage-providers.test.ts b/lambdas/libs/storage-providers/storage-providers.test.ts index f46b593a59..25c011b81c 100644 --- a/lambdas/libs/storage-providers/storage-providers.test.ts +++ b/lambdas/libs/storage-providers/storage-providers.test.ts @@ -1,11 +1,14 @@ import { describe, expect, it, vi } from 'vitest'; -import { createStorageProviders } from './storage-providers'; import { createAwsSsmRunnerConfigStore } from './aws/ssm/runner-config-store'; +import { createCommonStorage, createStorageProviders } from './storage-providers'; +import { getGitHubAppCredentialsStore } from './github-app-credentials'; +import { getRunnerConfigStore } from './runner-config'; +import { getRunnerGroupCacheStore } from './runner-group-cache'; + vi.mock('./aws/ssm/runner-config-store', () => ({ createAwsSsmRunnerConfigStore: vi.fn(() => ({ create: vi.fn() })), - resolveMaxWritesPerSecond: vi.fn((rawValue: string | undefined) => (rawValue ? parseInt(rawValue, 10) : 40)), })); vi.mock('./aws/ssm/runner-group-cache-store', () => ({ createAwsSsmRunnerGroupCacheStore: vi.fn(() => ({ get: vi.fn(), create: vi.fn() })), @@ -17,6 +20,28 @@ vi.mock('./aws/ssm/github-app-credentials-store', () => ({ createAwsSsmGitHubAppCredentialsStore: vi.fn(() => ({ get: vi.fn() })), })); +vi.mock('./runner-config', () => ({ getRunnerConfigStore: vi.fn(() => ({ create: vi.fn() })) })); +vi.mock('./runner-group-cache', () => ({ getRunnerGroupCacheStore: vi.fn(() => ({ get: vi.fn(), create: vi.fn() })) })); +vi.mock('./github-app-credentials', () => ({ getGitHubAppCredentialsStore: vi.fn(() => ({ get: vi.fn() })) })); + +describe('createStorageProviders with aws_dynamodb', () => { + it('composes the DynamoDB-backed stores without SSM paths and without a consumer', () => { + const storage = createStorageProviders({ RUNNER_CONFIG_STORAGE_PROVIDER: 'aws_dynamodb' }); + + expect(getRunnerConfigStore).toHaveBeenCalled(); + expect(getRunnerGroupCacheStore).toHaveBeenCalled(); + expect(getGitHubAppCredentialsStore).toHaveBeenCalled(); + expect(storage.consumer).toBeUndefined(); + expect(Object.keys(storage).sort()).toEqual(['githubAppCredentials', 'runnerConfig', 'runnerGroupCache']); + }); + + it('selects the DynamoDB GitHub App credentials store for common storage', () => { + createCommonStorage({ RUNNER_CONFIG_STORAGE_PROVIDER: 'aws_dynamodb' }); + + expect(getGitHubAppCredentialsStore).toHaveBeenCalled(); + }); +}); + describe('createStorageProviders', () => { it('parses environment once and composes independent runner and common capabilities', () => { const environment = Object.freeze({ @@ -44,21 +69,6 @@ describe('createStorageProviders', () => { }); }); - it('forwards SSM_PARAMETER_STORE_MAX_WRITES_PER_SECOND to the runner config store', () => { - const environment = Object.freeze({ - RUNNER_CONFIG_STORAGE_PROVIDER: 'AWS_SSM', - SSM_TOKEN_PATH: '/runners/tokens', - SSM_CONFIG_PATH: '/runners/config', - SSM_PARAMETER_STORE_MAX_WRITES_PER_SECOND: '10000', - PARAMETER_GITHUB_APP_ID_NAME: 'app-id', - PARAMETER_GITHUB_APP_KEY_BASE64_NAME: 'app-key', - }); - - createStorageProviders(environment); - - expect(createAwsSsmRunnerConfigStore).toHaveBeenCalledWith(expect.objectContaining({ maxWritesPerSecond: 10000 })); - }); - it('rejects an invalid token TTL before creating a storage provider', () => { vi.clearAllMocks(); expect(() => diff --git a/lambdas/libs/storage-providers/storage-providers.ts b/lambdas/libs/storage-providers/storage-providers.ts index 57e5482edd..3c135696de 100644 --- a/lambdas/libs/storage-providers/storage-providers.ts +++ b/lambdas/libs/storage-providers/storage-providers.ts @@ -7,6 +7,9 @@ import type { CommonStorage, StorageProviders } from './core'; import { loadRunnerConfigConsumerConfigFromEnvironment } from './runner-config-consumer'; import { loadSsmParameterStoreTagsFromEnvironment } from './aws/ssm/parameter-store-tags'; import { resolveRunnerConfigStorageProvider, runnerConfigStorageProvider } from './provider'; +import { getGitHubAppCredentialsStore } from './github-app-credentials'; +import { getRunnerConfigStore } from './runner-config'; +import { getRunnerGroupCacheStore } from './runner-group-cache'; import { parseSsmTokenTtlSeconds } from './aws/ssm/token-ttl'; @@ -16,6 +19,17 @@ const logger = createChildLogger('storage-providers'); export function createStorageProviders(environment: Environment = process.env): StorageProviders { const provider = resolveRunnerConfigStorageProvider(environment.RUNNER_CONFIG_STORAGE_PROVIDER); + if (provider === runnerConfigStorageProvider.awsDynamodb) { + logger.info('Composing runner configuration storage providers', { + storageProvider: provider, + capabilities: ['runnerConfig', 'runnerGroupCache', 'githubAppCredentials'], + }); + return { + runnerConfig: getRunnerConfigStore(), + runnerGroupCache: getRunnerGroupCacheStore(), + githubAppCredentials: getGitHubAppCredentialsStore(), + }; + } if (provider !== runnerConfigStorageProvider.awsSsm) { throw new Error(`Unsupported runner config storage provider '${provider}'`); } @@ -45,6 +59,12 @@ export function createStorageProviders(environment: Environment = process.env): } export function createCommonStorage(environment: Environment = process.env): CommonStorage { + if ( + resolveRunnerConfigStorageProvider(environment.RUNNER_CONFIG_STORAGE_PROVIDER) === + runnerConfigStorageProvider.awsDynamodb + ) { + return { githubAppCredentials: getGitHubAppCredentialsStore() }; + } const store = createAwsSsmGitHubAppCredentialsStore(environment); let credentials: ReturnType | undefined; From aa53d581b8be847b4ddd0d2dded15babd50bf2b0 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Tue, 17 Nov 2026 21:26:06 +0000 Subject: [PATCH 08/11] docs: auto update terraform docs --- .../storage-providers/aws/dynamodb/README.md | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 modules/storage-providers/aws/dynamodb/README.md diff --git a/modules/storage-providers/aws/dynamodb/README.md b/modules/storage-providers/aws/dynamodb/README.md new file mode 100644 index 0000000000..27d1daed3b --- /dev/null +++ b/modules/storage-providers/aws/dynamodb/README.md @@ -0,0 +1,53 @@ + +## Requirements + +| Name | Version | +|------|---------| +| [terraform](#requirement\_terraform) | >= 1.5.6 | +| [aws](#requirement\_aws) | >= 6.33 | + +## Providers + +| Name | Version | +|------|---------| +| [aws](#provider\_aws) | >= 6.33 | +| [terraform](#provider\_terraform) | n/a | + +## Modules + +No modules. + +## Resources + +| Name | Type | +|------|------| +| [aws_dynamodb_table.config](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/dynamodb_table) | resource | +| [aws_dynamodb_table.runner_state](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/dynamodb_table) | resource | +| [aws_dynamodb_table_item.github_app_credentials](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/dynamodb_table_item) | resource | +| [aws_dynamodb_table_item.github_webhook_secret](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/dynamodb_table_item) | resource | +| [aws_dynamodb_table_item.runner_config](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/dynamodb_table_item) | resource | +| [aws_dynamodb_table_item.runner_matcher_config](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/dynamodb_table_item) | resource | +| [terraform_data.config_version](https://registry.terraform.io/providers/hashicorp/terraform/latest/docs/resources/data) | resource | + +## Inputs + +| Name | Description | Type | Default | Required | +|------|-------------|------|---------|:--------:| +| [config](#input\_config) | Settings for the shared durable configuration table and ephemeral runner-state table.

- `config.kms_key_arn`: Optional customer-managed KMS key ARN for durable configuration encryption. Null uses the AWS-owned DynamoDB key.
- `config.point_in_time_recovery_enabled`: Enables point-in-time recovery for durable configuration.
- `config.deletion_protection_enabled`: Enables deletion protection for the durable table.
- `config.tags`: Tags applied after the shared tag map.
- `runner_state.kms_key_arn`: Optional customer-managed KMS key ARN for runner-state encryption. Null uses the AWS-owned DynamoDB key.
- `runner_state.point_in_time_recovery_enabled`: Enables point-in-time recovery for ephemeral runner state.
- `runner_state.deletion_protection_enabled`: Enables deletion protection for the runner-state table.
- `runner_state.tags`: Tags applied after the shared tag map. |
object({
config = object({
kms_key_arn = optional(string, null)
point_in_time_recovery_enabled = optional(bool, true)
deletion_protection_enabled = optional(bool, false)
tags = optional(map(string), {})
})
runner_state = object({
kms_key_arn = optional(string, null)
point_in_time_recovery_enabled = optional(bool, false)
deletion_protection_enabled = optional(bool, false)
tags = optional(map(string), {})
})
})
| n/a | yes | +| [entry\_ids](#input\_entry\_ids) | Runner-entry identifiers used to build entry-scoped Lambda capabilities. | `set(string)` | n/a | yes | +| [entry\_records](#input\_entry\_records) | Resolved durable runner bootstrap configuration keyed by runner-entry identifier. |
map(object({
run_as = string
agent_mode = string
disable_default_labels = bool
enable_jit_config = bool
}))
| n/a | yes | +| [global\_records](#input\_global\_records) | Terraform-managed values stored under the shared global scope. |
object({
github_app_credentials = string
github_webhook_secret = string
runner_matcher_config = string
})
| n/a | yes | +| [prefix](#input\_prefix) | Multi-runner prefix used to name the two shared DynamoDB tables. | `string` | n/a | yes | +| [runner\_config\_access\_scope\_prefixes](#input\_runner\_config\_access\_scope\_prefixes) | Per-entry compute-resource scope prefixes used to constrain one-time runner-config writes. | `map(string)` | n/a | yes | +| [runner\_config\_ttl\_seconds](#input\_runner\_config\_ttl\_seconds) | TTL in seconds for one-time registration and JIT configuration records. | `number` | n/a | yes | +| [runner\_state\_ttl\_seconds](#input\_runner\_state\_ttl\_seconds) | Safety TTL in seconds applied only while lifecycle records are provisioning or terminating; active and orphan inventory has no expiry. | `number` | n/a | yes | +| [tags](#input\_tags) | Base tags added to both shared DynamoDB tables. Table-specific tags override matching keys. | `map(string)` | `{}` | no | + +## Outputs + +| Name | Description | +|------|-------------| +| [capabilities](#output\_capabilities) | Opaque environment and least-privilege IAM additions consumed by the shared webhook and each runner entry's control-plane functions. | +| [config\_table](#output\_config\_table) | Shared durable configuration table. Global and runner-entry records are separated by the `scope` partition key. | +| [runner\_state\_table](#output\_runner\_state\_table) | Shared TTL-backed table containing ephemeral runner configuration and provider-neutral runner lifecycle records. | + \ No newline at end of file From 1e0e8346498deb1999033d133fac044308f308a5 Mon Sep 17 00:00:00 2001 From: edersonbrilhante Date: Wed, 19 Aug 2026 15:01:39 +0200 Subject: [PATCH 09/11] feat(terraform): wire shared DynamoDB storage Adapted to v8.1.1 (changes by the fork maintainer): - keep upstream's storage_provider capability hooks in orchestration-providers as they are - merge the DynamoDB capabilities into the existing storage_provider variables of modules/webhook, compute-providers/aws/ec2 and runner-config instead of adding second variables - extend global_config_storage_provider with an optional aws.dynamodb block and forward the selected type and per-entry capabilities from multi-runner through runner-config - fix the ec2 module test fixtures for the for_each launch template and merged variable (cherry picked from commit 4148f809073c38304689a2ebbec601d50dc2263e) Signed-off-by: tehlers320 <16598119+tehlers320@users.noreply.github.com> --- .../aws/ec2/control-plane.tf | 6 +- .../aws/ec2/policies-runner.tf | 8 +- .../aws/ec2/runner-config.tf | 12 ++ .../aws/ec2/runner-instances.tf | 7 +- .../aws/ec2/templates/start-runner-osx.sh | 63 +++++++ .../aws/ec2/templates/start-runner.ps1 | 73 ++++++++ .../aws/ec2/templates/start-runner.sh | 64 +++++++ .../aws/ec2/tests/provider.tftest.hcl | 93 +++++++++- .../compute-providers/aws/ec2/variables.tf | 26 ++- .../config.experimental.translation.tf | 1 + modules/multi-runner/runners.experimental.tf | 11 +- modules/multi-runner/storage-provider.tf | 160 ++++++++++++++++++ ...variables.experimental.storage-provider.tf | 29 ++++ modules/multi-runner/webhook.tf | 7 +- .../runner-config/orchestration-provider.tf | 4 + modules/runner-config/variables.tf | 26 +++ modules/webhook/direct/variables.tf | 25 +-- modules/webhook/direct/webhook.tf | 19 ++- modules/webhook/eventbridge/dispatcher.tf | 17 +- modules/webhook/eventbridge/variables.tf | 31 ++-- modules/webhook/eventbridge/webhook.tf | 17 +- modules/webhook/variables.tf | 29 +++- modules/webhook/webhook.tf | 65 +++---- 23 files changed, 708 insertions(+), 85 deletions(-) create mode 100644 modules/multi-runner/storage-provider.tf diff --git a/modules/compute-providers/aws/ec2/control-plane.tf b/modules/compute-providers/aws/ec2/control-plane.tf index 78175d1fa3..ac2374a3cb 100644 --- a/modules/compute-providers/aws/ec2/control-plane.tf +++ b/modules/compute-providers/aws/ec2/control-plane.tf @@ -203,7 +203,7 @@ data "aws_iam_policy_document" "service_linked_role" { } locals { - scale_up_environment_variables = { + scale_up_environment_variables = merge({ AMI_ID_SSM_PARAMETER_NAME = local.ami_id_ssm_parameter_name INSTANCE_ALLOCATION_STRATEGY = var.config.instance_allocation_strategy INSTANCE_MAX_SPOT_PRICE = var.config.instance_max_spot_price @@ -216,7 +216,9 @@ locals { ENABLE_ON_DEMAND_FAILOVER_FOR_ERRORS = jsonencode(var.config.on_demand_failover_for_errors) SCALE_ERRORS = jsonencode(var.config.scale_errors) USE_DEDICATED_HOST = var.config.use_dedicated_host - } + }, var.storage_provider.type == "aws_dynamodb" ? { + EC2_INSTANCE_ARN_PREFIX = local.ec2_instance_arn_prefix + } : {}) scale_down_environment_variables = {} diff --git a/modules/compute-providers/aws/ec2/policies-runner.tf b/modules/compute-providers/aws/ec2/policies-runner.tf index f416661b71..c3decac6d2 100644 --- a/modules/compute-providers/aws/ec2/policies-runner.tf +++ b/modules/compute-providers/aws/ec2/policies-runner.tf @@ -4,6 +4,7 @@ data "aws_caller_identity" "current" {} locals { ssm_parameter_arn_prefix = "arn:${var.aws_partition}:ssm:${var.aws_region}:${data.aws_caller_identity.current.account_id}:parameter" + ec2_instance_arn_prefix = "arn:${var.aws_partition}:ec2:${var.aws_region}:${data.aws_caller_identity.current.account_id}:instance/" ssm_config_arn = "${local.ssm_parameter_arn_prefix}${var.storage_provider.aws.ssm.paths.root}/${var.storage_provider.aws.ssm.paths.config}" cloudwatch_config_arn = "${local.ssm_config_arn}/cloudwatch_agent_config_runner" } @@ -180,11 +181,16 @@ locals { policy_json = data.aws_iam_policy_document.terminate_self.json } }, - { + var.storage_provider.type == "aws_ssm" ? { ssm_parameters = { name = "runner-ssm-parameters" policy_json = data.aws_iam_policy_document.ssm_parameters.json } + } : { + runner_config_storage = { + name = "runner-config-storage" + policy_json = var.storage_provider.runner.iam_policy_json + } }, var.config.ssm_enabled ? { session_manager = { diff --git a/modules/compute-providers/aws/ec2/runner-config.tf b/modules/compute-providers/aws/ec2/runner-config.tf index 8685a7822a..ef043684a3 100644 --- a/modules/compute-providers/aws/ec2/runner-config.tf +++ b/modules/compute-providers/aws/ec2/runner-config.tf @@ -1,4 +1,5 @@ resource "aws_ssm_parameter" "runner_config_run_as" { + count = var.storage_provider.type == "aws_ssm" ? 1 : 0 name = "${var.storage_provider.aws.ssm.paths.root}/${var.storage_provider.aws.ssm.paths.config}/run_as" type = "String" value = var.runner.run_as_root ? "root" : var.runner.run_as @@ -6,8 +7,19 @@ resource "aws_ssm_parameter" "runner_config_run_as" { } resource "aws_ssm_parameter" "runner_enable_cloudwatch" { + count = var.storage_provider.type == "aws_ssm" ? 1 : 0 name = "${var.storage_provider.aws.ssm.paths.root}/${var.storage_provider.aws.ssm.paths.config}/enable_cloudwatch" type = "String" value = var.config.cloudwatch_agent.enabled tags = local.ssm_parameter_tags } + +moved { + from = aws_ssm_parameter.runner_config_run_as + to = aws_ssm_parameter.runner_config_run_as[0] +} + +moved { + from = aws_ssm_parameter.runner_enable_cloudwatch + to = aws_ssm_parameter.runner_enable_cloudwatch[0] +} diff --git a/modules/compute-providers/aws/ec2/runner-instances.tf b/modules/compute-providers/aws/ec2/runner-instances.tf index 8a477ad35c..0e869740c4 100644 --- a/modules/compute-providers/aws/ec2/runner-instances.tf +++ b/modules/compute-providers/aws/ec2/runner-instances.tf @@ -95,7 +95,12 @@ locals { hook_job_started = var.runner.hooks.job_started hook_job_completed = var.runner.hooks.job_completed start_runner = templatefile(local.userdata_start_runner[var.runner.os], { - metadata_tags = var.config.metadata_options != null ? var.config.metadata_options.instance_metadata_tags : "enabled" + metadata_tags = var.config.metadata_options != null ? var.config.metadata_options.instance_metadata_tags : "enabled" + storage_provider_type = var.storage_provider.type + dynamodb_config_table_name_base64 = var.storage_provider.type == "aws_dynamodb" ? base64encode(var.storage_provider.runner.config_table_name) : "" + dynamodb_scope_base64 = var.storage_provider.type == "aws_dynamodb" ? base64encode(var.storage_provider.runner.scope) : "" + ec2_instance_arn_prefix_base64 = var.storage_provider.type == "aws_dynamodb" ? base64encode(local.ec2_instance_arn_prefix) : "" + enable_cloudwatch_agent = var.config.cloudwatch_agent.enabled }) ghes_url = var.github.enterprise_server.url ghes_ssl_verify = var.github.enterprise_server.ssl_verify diff --git a/modules/compute-providers/aws/ec2/templates/start-runner-osx.sh b/modules/compute-providers/aws/ec2/templates/start-runner-osx.sh index a6da66116d..c0a274bb45 100644 --- a/modules/compute-providers/aws/ec2/templates/start-runner-osx.sh +++ b/modules/compute-providers/aws/ec2/templates/start-runner-osx.sh @@ -88,6 +88,37 @@ echo "Retrieved ghr:environment tag - ($environment)" echo "Retrieved ghr:ssm_config_path tag - ($ssm_config_path)" echo "Retrieved ghr:runner_name_prefix tag - ($runner_name_prefix)" +%{ if storage_provider_type == "aws_dynamodb" } +dynamodb_config_table_name=$(printf '%s' "${dynamodb_config_table_name_base64}" | openssl base64 -d -A) +dynamodb_scope=$(printf '%s' "${dynamodb_scope_base64}" | openssl base64 -d -A) +ec2_instance_arn_prefix=$(printf '%s' "${ec2_instance_arn_prefix_base64}" | openssl base64 -d -A) + +echo "Retrieving runner bootstrap configuration from DynamoDB" +runner_config_key=$(jq -cn --arg scope "$dynamodb_scope" '{scope:{S:$scope},id:{S:"runner-config"}}') +runner_config_record=$(aws dynamodb get-item \ + --table-name "$dynamodb_config_table_name" \ + --key "$runner_config_key" \ + --consistent-read \ + --projection-expression "#value" \ + --expression-attribute-names '{"#value":"value"}' \ + --region "$region") +runner_config=$(printf '%s' "$runner_config_record" | jq -er '.Item.value.S | fromjson') +unset runner_config_record + +run_as=$(printf '%s' "$runner_config" | jq -r '.run_as') +agent_mode=$(printf '%s' "$runner_config" | jq -r '.agent_mode') +disable_default_labels=$(printf '%s' "$runner_config" | jq -r '.disable_default_labels') +enable_jit_config=$(printf '%s' "$runner_config" | jq -r '.enable_jit_config') +dynamodb_runner_state_table_name=$(printf '%s' "$runner_config" | jq -er '.runner_config_storage.table_name') +dynamodb_access_scope_type=$(printf '%s' "$runner_config" | jq -er '.runner_config_storage.access_scope') +dynamodb_config_id=$(printf '%s' "$runner_config" | jq -er '.runner_config_storage.id') +if [[ "$dynamodb_access_scope_type" != "compute-resource" ]]; then + echo "Unsupported runner configuration access scope" + exit 1 +fi +dynamodb_access_scope="$${ec2_instance_arn_prefix}$instance_id" +unset runner_config +%{ else } parameters=$(aws ssm get-parameters-by-path \ --path "$ssm_config_path" \ --region "$region" \ @@ -108,7 +139,38 @@ echo "Retrieved /$ssm_config_path/enable_jit_config parameter - ($enable_jit_con token_path=$(echo "$parameters" | jq -r '.[] | select(.Name == "'$ssm_config_path'/token_path") | .Value') echo "Retrieved /$ssm_config_path/token_path parameter - ($token_path)" +%{ endif } + +%{ if storage_provider_type == "aws_dynamodb" } +echo "Retrieving one-time runner configuration from DynamoDB" +runner_state_key=$(jq -cn --arg scope "$dynamodb_access_scope" --arg id "$dynamodb_config_id" '{scope:{S:$scope},id:{S:$id}}') +config="" +retrycount=0 +while [[ -z "$config" ]]; do + now_epoch=$(date +%s) + expression_values=$(jq -cn --arg now "$now_epoch" '{":now":{N:$now}}') + if config_record=$(aws dynamodb delete-item \ + --table-name "$dynamodb_runner_state_table_name" \ + --key "$runner_state_key" \ + --condition-expression "attribute_exists(#expires_at) AND #expires_at > :now" \ + --expression-attribute-names '{"#expires_at":"expires_at"}' \ + --expression-attribute-values "$expression_values" \ + --return-values ALL_OLD \ + --region "$region" 2>/dev/null); then + config=$(printf '%s' "$config_record" | jq -er '.Attributes.value.S') + unset config_record + break + fi + retrycount=$((retrycount + 1)) + if [[ $retrycount -gt 40 ]]; then + echo "Runner configuration was unavailable or expired" + exit 1 + fi + echo "Waiting for runner configuration to become available in DynamoDB" + sleep 1 +done +%{ else } echo "Get GH Runner config from AWS SSM" config=$(aws ssm get-parameter --name "$token_path"/"$instance_id" --with-decryption --region "$region" | jq -r ".Parameter | .Value") while [[ -z "$config" ]]; do @@ -119,6 +181,7 @@ done echo "Delete GH Runner token from AWS SSM" aws ssm delete-parameter --name "$token_path"/"$instance_id" --region "$region" +%{ endif } if [ -z "$run_as" ]; then echo "No user specified, using default ec2-user account" diff --git a/modules/compute-providers/aws/ec2/templates/start-runner.ps1 b/modules/compute-providers/aws/ec2/templates/start-runner.ps1 index ae2eeff3c9..8d88b37e8b 100644 --- a/modules/compute-providers/aws/ec2/templates/start-runner.ps1 +++ b/modules/compute-providers/aws/ec2/templates/start-runner.ps1 @@ -77,6 +77,43 @@ Write-Host "Retrieved ghr:runner_name_prefix tag - ($runner_name_prefix)" $ssm_config_path=$tags.Tags.where( {$_.Key -eq 'ghr:ssm_config_path'}).value Write-Host "Retrieved ghr:ssm_config_path tag - ($ssm_config_path)" +%{ if storage_provider_type == "aws_dynamodb" } +$DynamoDbConfigTableName = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("${dynamodb_config_table_name_base64}")) +$DynamoDbScope = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("${dynamodb_scope_base64}")) +$Ec2InstanceArnPrefix = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("${ec2_instance_arn_prefix_base64}")) + +Write-Host "Retrieving runner bootstrap configuration from DynamoDB" +$RunnerConfigKey = @{ + scope = @{ S = $DynamoDbScope } + id = @{ S = "runner-config" } +} | ConvertTo-Json -Compress +$RunnerConfigRecord = aws dynamodb get-item ` + --table-name $DynamoDbConfigTableName ` + --key $RunnerConfigKey ` + --consistent-read ` + --projection-expression "#value" ` + --expression-attribute-names '{"#value":"value"}' ` + --region $Region | ConvertFrom-Json +if ($LASTEXITCODE -ne 0 -or -not $RunnerConfigRecord.Item.value.S) { + throw "Runner bootstrap configuration is unavailable" +} +$RunnerConfig = $RunnerConfigRecord.Item.value.S | ConvertFrom-Json +$RunnerConfigRecord = $null + +$run_as = $RunnerConfig.run_as +$agent_mode = $RunnerConfig.agent_mode +$disable_default_labels = $RunnerConfig.disable_default_labels.ToString().ToLowerInvariant() +$enable_jit_config = $RunnerConfig.enable_jit_config.ToString().ToLowerInvariant() +$enable_cloudwatch_agent = "${enable_cloudwatch_agent}" +$DynamoDbRunnerStateTableName = $RunnerConfig.runner_config_storage.table_name +$DynamoDbAccessScopeType = $RunnerConfig.runner_config_storage.access_scope +$DynamoDbConfigId = $RunnerConfig.runner_config_storage.id +if ($DynamoDbAccessScopeType -ne "compute-resource") { + throw "Unsupported runner configuration access scope" +} +$DynamoDbAccessScope = "$Ec2InstanceArnPrefix$InstanceId" +$RunnerConfig = $null +%{ else } $parameters=$(aws ssm get-parameters-by-path --path "$ssm_config_path" --region "$Region" --query "Parameters[*].{Name:Name,Value:Value}") | ConvertFrom-Json Write-Host "Retrieved parameters from AWS SSM" @@ -97,6 +134,7 @@ Write-Host "Retrieved $ssm_config_path/enable_jit_config parameter - ($enable_j $token_path=$parameters.where( {$_.Name -eq "$ssm_config_path/token_path"}).value Write-Host "Retrieved $ssm_config_path/token_path parameter - ($token_path)" +%{ endif } if ($enable_cloudwatch_agent -eq "true") @@ -107,6 +145,40 @@ if ($enable_cloudwatch_agent -eq "true") ## Configure the runner +%{ if storage_provider_type == "aws_dynamodb" } +Write-Host "Retrieving one-time runner configuration from DynamoDB" +$RunnerStateKey = @{ + scope = @{ S = $DynamoDbAccessScope } + id = @{ S = $DynamoDbConfigId } +} | ConvertTo-Json -Compress +$config = $null +$i = 0 +do { + $NowEpoch = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds().ToString() + $ExpressionValues = @{ ":now" = @{ N = $NowEpoch } } | ConvertTo-Json -Compress + $ConfigRecordRaw = aws dynamodb delete-item ` + --table-name $DynamoDbRunnerStateTableName ` + --key $RunnerStateKey ` + --condition-expression "attribute_exists(#expires_at) AND #expires_at > :now" ` + --expression-attribute-names '{"#expires_at":"expires_at"}' ` + --expression-attribute-values $ExpressionValues ` + --return-values ALL_OLD ` + --region $Region 2>$null + if ($LASTEXITCODE -eq 0) { + $config = ($ConfigRecordRaw | ConvertFrom-Json).Attributes.value.S + $ConfigRecordRaw = $null + break + } + + Write-Host "Waiting for runner configuration to become available in DynamoDB ($i/40)" + Start-Sleep 1 + $i++ +} while (($null -eq $config) -and ($i -lt 40)) + +if ($null -eq $config) { + throw "Runner configuration was unavailable or expired" +} +%{ else } Write-Host "Get GH Runner config from AWS SSM" $config = $null $i = 0 @@ -119,6 +191,7 @@ do { Write-Host "Delete GH Runner token from AWS SSM" aws ssm delete-parameter --name "$token_path/$InstanceId" --region $Region +%{ endif } # Create or update user if (-not($run_as)) { diff --git a/modules/compute-providers/aws/ec2/templates/start-runner.sh b/modules/compute-providers/aws/ec2/templates/start-runner.sh index 7f2c0f82c5..b6533df1dc 100644 --- a/modules/compute-providers/aws/ec2/templates/start-runner.sh +++ b/modules/compute-providers/aws/ec2/templates/start-runner.sh @@ -159,6 +159,38 @@ echo "Retrieved ghr:environment tag - ($environment)" echo "Retrieved ghr:ssm_config_path tag - ($ssm_config_path)" echo "Retrieved ghr:runner_name_prefix tag - ($runner_name_prefix)" +%{ if storage_provider_type == "aws_dynamodb" } +dynamodb_config_table_name=$(printf '%s' "${dynamodb_config_table_name_base64}" | openssl base64 -d -A) +dynamodb_scope=$(printf '%s' "${dynamodb_scope_base64}" | openssl base64 -d -A) +ec2_instance_arn_prefix=$(printf '%s' "${ec2_instance_arn_prefix_base64}" | openssl base64 -d -A) + +echo "Retrieving runner bootstrap configuration from DynamoDB" +runner_config_key=$(jq -cn --arg scope "$dynamodb_scope" '{scope:{S:$scope},id:{S:"runner-config"}}') +runner_config_record=$(aws dynamodb get-item \ + --table-name "$dynamodb_config_table_name" \ + --key "$runner_config_key" \ + --consistent-read \ + --projection-expression "#value" \ + --expression-attribute-names '{"#value":"value"}' \ + --region "$region") +runner_config=$(printf '%s' "$runner_config_record" | jq -er '.Item.value.S | fromjson') +unset runner_config_record + +run_as=$(printf '%s' "$runner_config" | jq -r '.run_as') +agent_mode=$(printf '%s' "$runner_config" | jq -r '.agent_mode') +disable_default_labels=$(printf '%s' "$runner_config" | jq -r '.disable_default_labels') +enable_jit_config=$(printf '%s' "$runner_config" | jq -r '.enable_jit_config') +enable_cloudwatch_agent="${enable_cloudwatch_agent}" +dynamodb_runner_state_table_name=$(printf '%s' "$runner_config" | jq -er '.runner_config_storage.table_name') +dynamodb_access_scope_type=$(printf '%s' "$runner_config" | jq -er '.runner_config_storage.access_scope') +dynamodb_config_id=$(printf '%s' "$runner_config" | jq -er '.runner_config_storage.id') +if [[ "$dynamodb_access_scope_type" != "compute-resource" ]]; then + echo "Unsupported runner configuration access scope" + exit 1 +fi +dynamodb_access_scope="$${ec2_instance_arn_prefix}$instance_id" +unset runner_config +%{ else } parameters=$(aws ssm get-parameters-by-path --path "$ssm_config_path" --region "$region" --query "Parameters[*].{Name:Name,Value:Value}") echo "Retrieved parameters from AWS SSM ($parameters)" @@ -179,6 +211,7 @@ echo "Retrieved /$ssm_config_path/enable_jit_config parameter - ($enable_jit_con token_path=$(echo "$parameters" | jq --arg ssm_config_path "$ssm_config_path" -r '.[] | select(.Name == "'$ssm_config_path'/token_path") | .Value') echo "Retrieved /$ssm_config_path/token_path parameter - ($token_path)" +%{ endif } if [[ "$xray_trace_id" != "" ]]; then # run xray service @@ -199,6 +232,36 @@ fi ## Configure the runner +%{ if storage_provider_type == "aws_dynamodb" } +echo "Retrieving one-time runner configuration from DynamoDB" +runner_state_key=$(jq -cn --arg scope "$dynamodb_access_scope" --arg id "$dynamodb_config_id" '{scope:{S:$scope},id:{S:$id}}') +config="" +retrycount=0 +while [[ -z "$config" ]]; do + now_epoch=$(date +%s) + expression_values=$(jq -cn --arg now "$now_epoch" '{":now":{N:$now}}') + if config_record=$(aws dynamodb delete-item \ + --table-name "$dynamodb_runner_state_table_name" \ + --key "$runner_state_key" \ + --condition-expression "attribute_exists(#expires_at) AND #expires_at > :now" \ + --expression-attribute-names '{"#expires_at":"expires_at"}' \ + --expression-attribute-values "$expression_values" \ + --return-values ALL_OLD \ + --region "$region" 2>/dev/null); then + config=$(printf '%s' "$config_record" | jq -er '.Attributes.value.S') + unset config_record + break + fi + + retrycount=$((retrycount + 1)) + if [[ $retrycount -gt 40 ]]; then + echo "Runner configuration was unavailable or expired" + exit 1 + fi + echo "Waiting for runner configuration to become available in DynamoDB" + sleep 1 +done +%{ else } echo "Get GH Runner config from AWS SSM" config=$(aws ssm get-parameter --name "$token_path"/"$instance_id" --with-decryption --region "$region" | jq -r ".Parameter | .Value") while [[ -z "$config" ]]; do @@ -209,6 +272,7 @@ done echo "Delete GH Runner token from AWS SSM" aws ssm delete-parameter --name "$token_path"/"$instance_id" --region "$region" +%{ endif } if [ -z "$run_as" ]; then echo "No user specified, using default ec2-user account" diff --git a/modules/compute-providers/aws/ec2/tests/provider.tftest.hcl b/modules/compute-providers/aws/ec2/tests/provider.tftest.hcl index 4b459a5142..94e2eebc0a 100644 --- a/modules/compute-providers/aws/ec2/tests/provider.tftest.hcl +++ b/modules/compute-providers/aws/ec2/tests/provider.tftest.hcl @@ -414,11 +414,11 @@ run "separates_provider_runner_and_ssm_tags" { assert { condition = ( - aws_ssm_parameter.runner_config_run_as.tags["Name"] == "ssm-name" - && aws_ssm_parameter.runner_config_run_as.tags["Scope"] == "ssm" - && aws_ssm_parameter.runner_config_run_as.tags["SsmOnly"] == "ssm" - && !contains(keys(aws_ssm_parameter.runner_config_run_as.tags), "RunnerOnly") - && !contains(keys(aws_ssm_parameter.runner_config_run_as.tags), "ghr:environment") + aws_ssm_parameter.runner_config_run_as[0].tags["Name"] == "ssm-name" + && aws_ssm_parameter.runner_config_run_as[0].tags["Scope"] == "ssm" + && aws_ssm_parameter.runner_config_run_as[0].tags["SsmOnly"] == "ssm" + && !contains(keys(aws_ssm_parameter.runner_config_run_as[0].tags), "RunnerOnly") + && !contains(keys(aws_ssm_parameter.runner_config_run_as[0].tags), "ghr:environment") ) error_message = "EC2 SSM parameters must merge SSM component tags over provider tags." } @@ -692,3 +692,86 @@ run "requires_distribution_object_when_sync_is_enabled" { expect_failures = [terraform_data.validate_config] } + +run "dynamodb_bootstrap_is_opt_in_and_compute_scoped" { + command = plan + + variables { + config = { + vpc_id = "vpc-12345678" + subnet_ids = ["subnet-12345678"] + instance_types = ["m5.large"] + ami = { + filter = { state = ["available"] } + owners = ["amazon"] + id_ssm_parameter = { + arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/github-runner/ami-id" + } + kms_key = null + } + binaries_syncer = { + enabled = false + } + cloudwatch_agent = { + enabled = false + } + managed_security_group_enabled = true + } + + runner = { + os = "windows" + architecture = "x64" + iam = { + role = { + arn = "arn:aws:iam::123456789012:role/provider-test-runner" + name = "provider-test-runner" + } + } + } + + storage_provider = { + type = "aws_dynamodb" + aws = { + ssm = { + paths = { + root = "/github-runner/provider-test" + tokens = "tokens" + config = "config" + } + } + } + runner = { + config_table_name = "provider-test-config" + runner_state_table_name = "provider-test-runner-state" + scope = "entry#unsafe-$(value)#bootstrap" + iam_policy_json = jsonencode({ Version = "2012-10-17", Statement = [] }) + } + } + } + + assert { + condition = ( + length(aws_ssm_parameter.runner_config_run_as) == 0 + && length(aws_ssm_parameter.runner_enable_cloudwatch) == 0 + && contains(keys(output.provider.policies.runner.inline_policies), "runner_config_storage") + && !contains(keys(output.provider.policies.runner.inline_policies), "ssm_parameters") + && output.provider.environment_variables.scale_up["EC2_INSTANCE_ARN_PREFIX"] == "arn:aws:ec2:eu-west-1:123456789012:instance/" + && output.provider.environment_variables.pool["EC2_INSTANCE_ARN_PREFIX"] == "arn:aws:ec2:eu-west-1:123456789012:instance/" + ) + error_message = "DynamoDB-selected EC2 runners must replace SSM bootstrap resources and expose the matching compute-resource ARN prefix." + } + + assert { + condition = ( + strcontains(base64decode(aws_launch_template.runner["default"].user_data), base64encode("provider-test-config")) + && strcontains(base64decode(aws_launch_template.runner["default"].user_data), base64encode("entry#unsafe-$(value)#bootstrap")) + && strcontains(base64decode(aws_launch_template.runner["default"].user_data), base64encode("arn:aws:ec2:eu-west-1:123456789012:instance/")) + && !strcontains(base64decode(aws_launch_template.runner["default"].user_data), "entry#unsafe-$(value)#bootstrap") + && strcontains(base64decode(aws_launch_template.runner["default"].user_data), "aws dynamodb delete-item") + && strcontains(base64decode(aws_launch_template.runner["default"].user_data), "attribute_exists(#expires_at) AND #expires_at > :now") + && strcontains(base64decode(aws_launch_template.runner["default"].user_data), "--return-values ALL_OLD") + && !strcontains(base64decode(aws_launch_template.runner["default"].user_data), "aws ssm get-parameters --names") + ) + error_message = "DynamoDB bootstrap must base64-embed user-controlled locators and atomically consume only an unexpired per-instance record." + } +} diff --git a/modules/compute-providers/aws/ec2/variables.tf b/modules/compute-providers/aws/ec2/variables.tf index e1fd17428c..2c63f49a07 100644 --- a/modules/compute-providers/aws/ec2/variables.tf +++ b/modules/compute-providers/aws/ec2/variables.tf @@ -360,14 +360,17 @@ variable "storage_provider" { description = <<-EOT Storage-provider configuration available to compute-provider bootstrap resources. - - `aws.ssm`: AWS Systems Manager Parameter Store configuration, when SSM is selected. + - `type`: Selected runner-config storage provider, `aws_ssm` (default) or `aws_dynamodb`. + - `aws.ssm`: AWS Systems Manager Parameter Store configuration, used when `type` is `aws_ssm`. - `aws.ssm.paths.root`: Root Parameter Store path for the runner configuration. - `aws.ssm.paths.tokens`: Path segment used for registration tokens and just-in-time configuration. - `aws.ssm.paths.config`: Path segment used for persistent runner and provider configuration. - `aws.ssm.tags`: Shared SSM tags that override module-level `tags`. - `aws.ssm.parameters.tags`: Parameter-specific tags that override module-level and shared SSM tags. + - `runner`: Runner-side DynamoDB locators and the opaque IAM policy supplied by runner-config, required when `type` is `aws_dynamodb`. EOT type = object({ + type = optional(string, "aws_ssm") aws = object({ ssm = object({ paths = object({ @@ -381,9 +384,30 @@ variable "storage_provider" { }), {}) }) }) + runner = optional(object({ + config_table_name = optional(string, null) + runner_state_table_name = optional(string, null) + scope = optional(string, null) + iam_policy_json = optional(string, null) + }), {}) }) nullable = false + + validation { + condition = contains(["aws_ssm", "aws_dynamodb"], var.storage_provider.type) + error_message = "storage_provider.type must be aws_ssm or aws_dynamodb." + } + + validation { + condition = var.storage_provider.type != "aws_dynamodb" || ( + var.storage_provider.runner.config_table_name != null && + var.storage_provider.runner.runner_state_table_name != null && + var.storage_provider.runner.scope != null && + var.storage_provider.runner.iam_policy_json != null + ) + error_message = "aws_dynamodb storage requires non-null runner config table, runner-state table, bootstrap scope, and IAM policy capabilities." + } } variable "observability" { diff --git a/modules/multi-runner/config.experimental.translation.tf b/modules/multi-runner/config.experimental.translation.tf index ee55b05b1b..8329e91eda 100644 --- a/modules/multi-runner/config.experimental.translation.tf +++ b/modules/multi-runner/config.experimental.translation.tf @@ -63,6 +63,7 @@ locals { stable_to_v2_storage_provider = { aws = { + dynamodb = null ssm = { paths = { root = "/${var.ssm_paths.root}/${var.prefix}" diff --git a/modules/multi-runner/runners.experimental.tf b/modules/multi-runner/runners.experimental.tf index 3635b239dd..241fabdb65 100644 --- a/modules/multi-runner/runners.experimental.tf +++ b/modules/multi-runner/runners.experimental.tf @@ -39,8 +39,15 @@ module "runner_configs" { } scale_set = each.value.orchestration_provider.scale_set } - storage_provider = each.value.storage_provider - observability = each.value.observability + storage_provider = merge(each.value.storage_provider, { + type = local.storage_provider_type + scale_up = local.storage_provider_capabilities.entries[each.key].scale_up + scale_down = local.storage_provider_capabilities.entries[each.key].scale_down + pool = local.storage_provider_capabilities.entries[each.key].pool + job_retry = local.storage_provider_capabilities.entries[each.key].job_retry + runner = local.storage_provider_capabilities.entries[each.key].runner + }) + observability = each.value.observability compute_provider = merge(each.value.compute_provider, { aws = merge(each.value.compute_provider.aws, { ec2 = each.value.compute_provider.aws.ec2 == null ? null : merge(each.value.compute_provider.aws.ec2, { diff --git a/modules/multi-runner/storage-provider.tf b/modules/multi-runner/storage-provider.tf new file mode 100644 index 0000000000..c680a5a305 --- /dev/null +++ b/modules/multi-runner/storage-provider.tf @@ -0,0 +1,160 @@ +locals { + requested_storage_provider_types = compact([ + try(local.normalized_config.storage_provider.aws.dynamodb, null) != null ? "aws_dynamodb" : "", + try(local.normalized_config.storage_provider.aws.ssm, null) != null ? "aws_ssm" : "", + ]) + + storage_provider_type = local.use_v2_config ? ( + length(local.requested_storage_provider_types) == 0 + ? "aws_ssm" + : one(local.requested_storage_provider_types) + ) : "aws_ssm" + + default_dynamodb_storage_provider = { + config = { + kms_key_arn = null + point_in_time_recovery_enabled = true + deletion_protection_enabled = false + tags = {} + } + runner_state = { + kms_key_arn = null + point_in_time_recovery_enabled = false + deletion_protection_enabled = false + runner_config_ttl_seconds = 86400 + runner_state_ttl_seconds = 604800 + tags = {} + } + } + + dynamodb_storage_provider = coalesce( + try(local.normalized_config.storage_provider.aws.dynamodb, null), + local.default_dynamodb_storage_provider, + ) + + storage_runner_matcher_config_by_key = { + for k, v in local.runner_matcher_config : format("%03d-%s", v.matcherConfig.priority, k) => merge(v, { + key = k + computeProvider = lower(trimspace(v.computeProvider)) + }) + } + storage_runner_matcher_config = [ + for k in sort(keys(local.storage_runner_matcher_config_by_key)) : local.storage_runner_matcher_config_by_key[k] + ] + + dynamodb_global_records = local.storage_provider_type == "aws_dynamodb" ? { + github_app_credentials = sensitive(jsonencode(concat( + [{ + appId = try(tonumber(local.normalized_config.github.app.id), 0) + privateKeyBase64 = local.normalized_config.github.app.key_base64 + }], + [for app in local.normalized_config.github.additional_apps : merge( + { + appId = try(tonumber(app.id), 0) + privateKeyBase64 = app.key_base64 + }, + app.installation_id == null ? {} : { + installationId = try(tonumber(app.installation_id), 0) + }, + )], + ))) + github_webhook_secret = sensitive(local.normalized_config.github.app.webhook_secret) + runner_matcher_config = jsonencode(local.storage_runner_matcher_config) + } : { + github_app_credentials = sensitive("") + github_webhook_secret = sensitive("") + runner_matcher_config = "" + } + + dynamodb_entry_records = { + for entry_id, entry in local.effective_config.multi_runner_config : entry_id => { + run_as = entry.runner.run_as_root ? "root" : entry.runner.run_as + agent_mode = entry.orchestration_provider.webhook.runner.ephemeral ? "ephemeral" : "persistent" + disable_default_labels = entry.runner.disable_default_labels + enable_jit_config = entry.orchestration_provider.webhook.runner.jit_config_enabled + } + if local.storage_provider_type == "aws_dynamodb" + } +} + +data "aws_caller_identity" "storage" { + count = local.storage_provider_type == "aws_dynamodb" ? 1 : 0 +} + +module "storage_aws_dynamodb" { + source = "../storage-providers/aws/dynamodb" + count = local.storage_provider_type == "aws_dynamodb" ? 1 : 0 + + prefix = var.prefix + tags = merge( + local.effective_config.tags, + { "ghr:environment" = var.prefix }, + ) + config = { + config = local.dynamodb_storage_provider.config + runner_state = { + kms_key_arn = local.dynamodb_storage_provider.runner_state.kms_key_arn + point_in_time_recovery_enabled = local.dynamodb_storage_provider.runner_state.point_in_time_recovery_enabled + deletion_protection_enabled = local.dynamodb_storage_provider.runner_state.deletion_protection_enabled + tags = local.dynamodb_storage_provider.runner_state.tags + } + } + entry_ids = keys(local.effective_config.multi_runner_config) + runner_config_access_scope_prefixes = { + for entry_id in keys(local.effective_config.multi_runner_config) : + entry_id => "arn:${var.aws_partition}:ec2:${var.aws_region}:${data.aws_caller_identity.storage[0].account_id}:instance/" + } + runner_config_ttl_seconds = local.dynamodb_storage_provider.runner_state.runner_config_ttl_seconds + runner_state_ttl_seconds = local.dynamodb_storage_provider.runner_state.runner_state_ttl_seconds + global_records = local.dynamodb_global_records + entry_records = local.dynamodb_entry_records +} + +locals { + dynamodb_storage_capabilities = one(module.storage_aws_dynamodb[*].capabilities) + + storage_provider_capabilities = local.storage_provider_type == "aws_dynamodb" ? local.dynamodb_storage_capabilities : { + webhook = { + direct = { + environment_variables = tomap({}) + iam_policy_json = null + } + eventbridge = { + webhook = { + environment_variables = tomap({}) + iam_policy_json = null + } + dispatcher = { + environment_variables = tomap({}) + iam_policy_json = null + } + } + } + entries = { + for entry_id in keys(local.effective_config.multi_runner_config) : entry_id => { + scale_up = { + environment_variables = tomap({}) + iam_policy_json = null + } + scale_down = { + environment_variables = tomap({}) + iam_policy_json = null + } + pool = { + environment_variables = tomap({}) + iam_policy_json = null + } + job_retry = { + environment_variables = tomap({}) + iam_policy_json = null + } + runner = { + config_table_name = null + runner_state_table_name = null + scope = null + iam_policy_json = null + } + } + } + } +} diff --git a/modules/multi-runner/variables.experimental.storage-provider.tf b/modules/multi-runner/variables.experimental.storage-provider.tf index d7ea966baf..bf96a40723 100644 --- a/modules/multi-runner/variables.experimental.storage-provider.tf +++ b/modules/multi-runner/variables.experimental.storage-provider.tf @@ -25,7 +25,20 @@ variable "global_config_storage_provider" { aws.ssm.housekeeper.config.tokenPath: "Parameter path containing runner tokens to clean up." aws.ssm.housekeeper.config.minimumDaysOld: "Minimum age in days before an old token is eligible for cleanup." aws.ssm.housekeeper.config.dryRun: "Whether the SSM housekeeper reports cleanup without deleting parameters." + aws.dynamodb.config.kms_key_arn: "Optional customer-managed KMS key ARN for the durable configuration table." + aws.dynamodb.config.point_in_time_recovery_enabled: "Enables point-in-time recovery for the durable configuration table." + aws.dynamodb.config.deletion_protection_enabled: "Enables deletion protection for the durable configuration table." + aws.dynamodb.config.tags: "Tags applied to the durable configuration table." + aws.dynamodb.runner_state.kms_key_arn: "Optional customer-managed KMS key ARN for the runner-state table." + aws.dynamodb.runner_state.point_in_time_recovery_enabled: "Enables point-in-time recovery for the runner-state table." + aws.dynamodb.runner_state.deletion_protection_enabled: "Enables deletion protection for the runner-state table." + aws.dynamodb.runner_state.runner_config_ttl_seconds: "TTL in seconds for one-time registration and JIT configuration records." + aws.dynamodb.runner_state.runner_state_ttl_seconds: "Safety TTL in seconds for provisioning and terminating lifecycle records." + aws.dynamodb.runner_state.tags: "Tags applied to the runner-state table." } + + Setting aws.dynamodb moves runner configuration, GitHub App credentials, the webhook secret and the runner matcher + configuration to DynamoDB. Omitting it keeps the SSM backend; aws.ssm continues to supply paths for remaining SSM resources. EOT type = object({ aws = optional(object({ @@ -66,6 +79,22 @@ variable "global_config_storage_provider" { }), {}) }), {}) }), {}) + dynamodb = optional(object({ + config = optional(object({ + kms_key_arn = optional(string, null) + point_in_time_recovery_enabled = optional(bool, true) + deletion_protection_enabled = optional(bool, false) + tags = optional(map(string), {}) + }), {}) + runner_state = optional(object({ + kms_key_arn = optional(string, null) + point_in_time_recovery_enabled = optional(bool, false) + deletion_protection_enabled = optional(bool, false) + runner_config_ttl_seconds = optional(number, 86400) + runner_state_ttl_seconds = optional(number, 604800) + tags = optional(map(string), {}) + }), {}) + }), null) }), {}) }) default = {} diff --git a/modules/multi-runner/webhook.tf b/modules/multi-runner/webhook.tf index 250af4a214..19d1edbdd3 100644 --- a/modules/multi-runner/webhook.tf +++ b/modules/multi-runner/webhook.tf @@ -20,14 +20,15 @@ locals { } } - webhook_storage_kms_key_arn = local.effective_config.storage_provider.aws.ssm.kms_key_id + webhook_storage_kms_key_arn = local.storage_provider_type == "aws_ssm" ? local.effective_config.storage_provider.aws.ssm.kms_key_id : null } module "webhook" { source = "../webhook" prefix = var.prefix tags = local.tags - storage_provider = { + storage_provider = merge(local.storage_provider_capabilities.webhook, { + type = local.storage_provider_type aws = { kms_key_id = local.webhook_storage_kms_key_arn ssm = { @@ -37,7 +38,7 @@ module "webhook" { } } } - } + }) eventbridge = { enable = local.effective_config.orchestration_provider.webhook.eventbridge.enabled accept_events = local.effective_config.orchestration_provider.webhook.eventbridge.accept_events diff --git a/modules/runner-config/orchestration-provider.tf b/modules/runner-config/orchestration-provider.tf index b049c70196..356f4cf97e 100644 --- a/modules/runner-config/orchestration-provider.tf +++ b/modules/runner-config/orchestration-provider.tf @@ -57,6 +57,10 @@ module "orchestration_webhook" { parameter_store_max_writes_per_second = var.storage_provider.aws.ssm.parameters.max_writes_per_second } } + scale_up = var.storage_provider.scale_up + scale_down = var.storage_provider.scale_down + pool = var.storage_provider.pool + job_retry = var.storage_provider.job_retry } observability = var.observability diff --git a/modules/runner-config/variables.tf b/modules/runner-config/variables.tf index f08d977d37..4dad7c4f76 100644 --- a/modules/runner-config/variables.tf +++ b/modules/runner-config/variables.tf @@ -164,6 +164,9 @@ variable "storage_provider" { - `storage_provider.aws.ssm.housekeeper.config.tokenPath`: Parameter Store token path cleaned by the housekeeper. When omitted, the configured runner token path is used. - `storage_provider.aws.ssm.housekeeper.config.minimumDaysOld`: Minimum parameter age in days before deletion is allowed. - `storage_provider.aws.ssm.housekeeper.config.dryRun`: Reports eligible parameters without deleting them when true. + - `storage_provider.type`: Selected runner-config storage provider, `aws_ssm` (default) or `aws_dynamodb`. + - `storage_provider.scale_up`, `scale_down`, `pool`, `job_retry`: Provider-owned control-plane environment variables and IAM policy fragments, supplied by the selected storage provider. + - `storage_provider.runner`: Runner-side DynamoDB locators and IAM policy, required when `type` is `aws_dynamodb`. EOT type = object({ aws = object({ @@ -203,6 +206,29 @@ variable "storage_provider" { }), {}) }) }) + type = optional(string, "aws_ssm") + scale_up = optional(object({ + environment_variables = optional(map(string), {}) + iam_policy_json = optional(string, null) + }), {}) + scale_down = optional(object({ + environment_variables = optional(map(string), {}) + iam_policy_json = optional(string, null) + }), {}) + pool = optional(object({ + environment_variables = optional(map(string), {}) + iam_policy_json = optional(string, null) + }), {}) + job_retry = optional(object({ + environment_variables = optional(map(string), {}) + iam_policy_json = optional(string, null) + }), {}) + runner = optional(object({ + config_table_name = optional(string, null) + runner_state_table_name = optional(string, null) + scope = optional(string, null) + iam_policy_json = optional(string, null) + }), {}) }) } diff --git a/modules/webhook/direct/variables.tf b/modules/webhook/direct/variables.tf index cf3595bc0f..20613fda24 100644 --- a/modules/webhook/direct/variables.tf +++ b/modules/webhook/direct/variables.tf @@ -28,17 +28,10 @@ variable "config" { }), null) repository_white_list = optional(list(string), []) queue_selection_strategy = optional(string, "first") - storage_provider = object({ - aws = object({ - ssm = object({ - kms_key_id = optional(string, null) - }) - }) - }) - log_level = optional(string, "info") - lambda_runtime = optional(string, "nodejs24.x") - aws_partition = optional(string, "aws") - lambda_architecture = optional(string, "arm64") + log_level = optional(string, "info") + lambda_runtime = optional(string, "nodejs24.x") + aws_partition = optional(string, "aws") + lambda_architecture = optional(string, "arm64") github_app_parameters = object({ webhook_secret = map(string) }) @@ -55,5 +48,15 @@ variable "config" { version = string })) ssm_parameter_runner_matcher_config_arn_pattern = string + storage_provider = object({ + type = optional(string, "aws_ssm") + aws = object({ + ssm = object({ + kms_key_id = optional(string, null) + }) + }) + environment_variables = optional(map(string), {}) + iam_policy_json = optional(string, null) + }) }) } diff --git a/modules/webhook/direct/webhook.tf b/modules/webhook/direct/webhook.tf index 0a05ddd089..e9e6288c29 100644 --- a/modules/webhook/direct/webhook.tf +++ b/modules/webhook/direct/webhook.tf @@ -26,13 +26,13 @@ resource "aws_lambda_function" "webhook" { POWERTOOLS_TRACE_ENABLED = var.config.tracing_config.mode != null ? true : false POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS = var.config.tracing_config.capture_http_requests POWERTOOLS_TRACER_CAPTURE_ERROR = var.config.tracing_config.capture_error - PARAMETER_GITHUB_APP_WEBHOOK_SECRET = var.config.github_app_parameters.webhook_secret.name + PARAMETER_GITHUB_APP_WEBHOOK_SECRET = var.config.storage_provider.type == "aws_ssm" ? var.config.github_app_parameters.webhook_secret.name : null REPOSITORY_ALLOW_LIST = jsonencode(var.config.repository_white_list) QUEUE_SELECTION_STRATEGY = var.config.queue_selection_strategy - PARAMETER_RUNNER_MATCHER_CONFIG_PATH = join(":", [for p in var.config.ssm_parameter_runner_matcher_config : p.name]) - PARAMETER_RUNNER_MATCHER_VERSION = join(":", [for p in var.config.ssm_parameter_runner_matcher_config : p.version]) # enforce cold start after Changes in SSM parameter + PARAMETER_RUNNER_MATCHER_CONFIG_PATH = var.config.storage_provider.type == "aws_ssm" ? join(":", [for p in var.config.ssm_parameter_runner_matcher_config : p.name]) : null + PARAMETER_RUNNER_MATCHER_VERSION = var.config.storage_provider.type == "aws_ssm" ? join(":", [for p in var.config.ssm_parameter_runner_matcher_config : p.version]) : null # enforce cold start after Changes in SSM parameter } : k => v if v != null - }) + }, var.config.storage_provider.environment_variables) } dynamic "vpc_config" { @@ -125,6 +125,8 @@ resource "aws_iam_role_policy" "webhook_sqs" { } resource "aws_iam_role_policy" "webhook_kms" { + count = var.config.storage_provider.type == "aws_ssm" ? 1 : 0 + name = "kms-policy" role = aws_iam_role.webhook_lambda.name @@ -133,18 +135,23 @@ resource "aws_iam_role_policy" "webhook_kms" { }) } +moved { + from = aws_iam_role_policy.webhook_kms + to = aws_iam_role_policy.webhook_kms[0] +} + resource "aws_iam_role_policy" "webhook_ssm" { name = "publish-ssm-policy" role = aws_iam_role.webhook_lambda.name - policy = templatefile("${path.module}/../policies/lambda-ssm.json", { + policy = var.config.storage_provider.type == "aws_ssm" ? templatefile("${path.module}/../policies/lambda-ssm.json", { resource_arns = jsonencode( concat( [var.config.github_app_parameters.webhook_secret.arn], [var.config.ssm_parameter_runner_matcher_config_arn_pattern] ) ) - }) + }) : var.config.storage_provider.iam_policy_json } resource "aws_iam_role_policy" "xray" { diff --git a/modules/webhook/eventbridge/dispatcher.tf b/modules/webhook/eventbridge/dispatcher.tf index b92376ba99..bb50808b37 100644 --- a/modules/webhook/eventbridge/dispatcher.tf +++ b/modules/webhook/eventbridge/dispatcher.tf @@ -49,12 +49,12 @@ resource "aws_lambda_function" "dispatcher" { POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS = var.config.tracing_config.capture_http_requests POWERTOOLS_TRACER_CAPTURE_ERROR = var.config.tracing_config.capture_error # Parameters required for lambda configuration - PARAMETER_RUNNER_MATCHER_CONFIG_PATH = join(":", [for p in var.config.ssm_parameter_runner_matcher_config : p.name]) - PARAMETER_RUNNER_MATCHER_VERSION = join(":", [for p in var.config.ssm_parameter_runner_matcher_config : p.version]) # enforce cold start after Changes in SSM parameter + PARAMETER_RUNNER_MATCHER_CONFIG_PATH = var.config.storage_provider.type == "aws_ssm" ? join(":", [for p in var.config.ssm_parameter_runner_matcher_config : p.name]) : null + PARAMETER_RUNNER_MATCHER_VERSION = var.config.storage_provider.type == "aws_ssm" ? join(":", [for p in var.config.ssm_parameter_runner_matcher_config : p.version]) : null # enforce cold start after Changes in SSM parameter REPOSITORY_ALLOW_LIST = jsonencode(var.config.repository_white_list) QUEUE_SELECTION_STRATEGY = var.config.queue_selection_strategy } : k => v if v != null - }) + }, var.config.storage_provider.dispatcher.environment_variables) } dynamic "vpc_config" { @@ -123,6 +123,8 @@ resource "aws_iam_role_policy" "dispatcher_sqs" { } resource "aws_iam_role_policy" "dispatcher_kms" { + count = var.config.storage_provider.type == "aws_ssm" ? 1 : 0 + name = "kms-policy" role = aws_iam_role.dispatcher_lambda.name @@ -131,17 +133,22 @@ resource "aws_iam_role_policy" "dispatcher_kms" { }) } +moved { + from = aws_iam_role_policy.dispatcher_kms + to = aws_iam_role_policy.dispatcher_kms[0] +} + resource "aws_iam_role_policy" "dispatcher_ssm" { name = "publish-ssm-policy" role = aws_iam_role.dispatcher_lambda.name - policy = templatefile("${path.module}/../policies/lambda-ssm.json", { + policy = var.config.storage_provider.type == "aws_ssm" ? templatefile("${path.module}/../policies/lambda-ssm.json", { resource_arns = jsonencode( concat( [var.config.ssm_parameter_runner_matcher_config_arn_pattern] ) ) - }) + }) : var.config.storage_provider.dispatcher.iam_policy_json } resource "aws_iam_role_policy" "dispatcher_xray" { diff --git a/modules/webhook/eventbridge/variables.tf b/modules/webhook/eventbridge/variables.tf index f7ad54152d..214baac458 100644 --- a/modules/webhook/eventbridge/variables.tf +++ b/modules/webhook/eventbridge/variables.tf @@ -28,17 +28,10 @@ variable "config" { }), null) repository_white_list = optional(list(string), []) queue_selection_strategy = optional(string, "first") - storage_provider = object({ - aws = object({ - ssm = object({ - kms_key_id = optional(string, null) - }) - }) - }) - log_level = optional(string, "info") - lambda_runtime = optional(string, "nodejs24.x") - aws_partition = optional(string, "aws") - lambda_architecture = optional(string, "arm64") + log_level = optional(string, "info") + lambda_runtime = optional(string, "nodejs24.x") + aws_partition = optional(string, "aws") + lambda_architecture = optional(string, "arm64") github_app_parameters = object({ webhook_secret = map(string) }) @@ -56,5 +49,21 @@ variable "config" { })) ssm_parameter_runner_matcher_config_arn_pattern = string accept_events = optional(list(string), null) + storage_provider = object({ + type = optional(string, "aws_ssm") + aws = object({ + ssm = object({ + kms_key_id = optional(string, null) + }) + }) + webhook = optional(object({ + environment_variables = optional(map(string), {}) + iam_policy_json = optional(string, null) + }), {}) + dispatcher = optional(object({ + environment_variables = optional(map(string), {}) + iam_policy_json = optional(string, null) + }), {}) + }) }) } diff --git a/modules/webhook/eventbridge/webhook.tf b/modules/webhook/eventbridge/webhook.tf index 9777188187..98d7e0e58c 100644 --- a/modules/webhook/eventbridge/webhook.tf +++ b/modules/webhook/eventbridge/webhook.tf @@ -35,10 +35,10 @@ resource "aws_lambda_function" "webhook" { # Parameters required for lambda configuration ACCEPT_EVENTS = jsonencode(var.config.accept_events) EVENT_BUS_NAME = aws_cloudwatch_event_bus.main.name - PARAMETER_GITHUB_APP_WEBHOOK_SECRET = var.config.github_app_parameters.webhook_secret.name - PARAMETER_RUNNER_MATCHER_CONFIG_PATH = join(":", [for p in var.config.ssm_parameter_runner_matcher_config : p.name]) + PARAMETER_GITHUB_APP_WEBHOOK_SECRET = var.config.storage_provider.type == "aws_ssm" ? var.config.github_app_parameters.webhook_secret.name : null + PARAMETER_RUNNER_MATCHER_CONFIG_PATH = var.config.storage_provider.type == "aws_ssm" ? join(":", [for p in var.config.ssm_parameter_runner_matcher_config : p.name]) : null } : k => v if v != null - }) + }, var.config.storage_provider.webhook.environment_variables) } dynamic "vpc_config" { @@ -129,12 +129,14 @@ resource "aws_iam_role_policy" "webhook_ssm" { name = "publish-ssm-policy" role = aws_iam_role.webhook_lambda.name - policy = templatefile("${path.module}/../policies/lambda-ssm.json", { + policy = var.config.storage_provider.type == "aws_ssm" ? templatefile("${path.module}/../policies/lambda-ssm.json", { resource_arns = jsonencode([var.config.github_app_parameters.webhook_secret.arn]) - }) + }) : var.config.storage_provider.webhook.iam_policy_json } resource "aws_iam_role_policy" "webhook_kms" { + count = var.config.storage_provider.type == "aws_ssm" ? 1 : 0 + name = "kms-policy" role = aws_iam_role.webhook_lambda.name @@ -143,6 +145,11 @@ resource "aws_iam_role_policy" "webhook_kms" { }) } +moved { + from = aws_iam_role_policy.webhook_kms + to = aws_iam_role_policy.webhook_kms[0] +} + resource "aws_iam_role_policy" "xray" { count = var.config.tracing_config.mode != null ? 1 : 0 name = "xray-policy" diff --git a/modules/webhook/variables.tf b/modules/webhook/variables.tf index d4b25d7d70..6eb22cb135 100644 --- a/modules/webhook/variables.tf +++ b/modules/webhook/variables.tf @@ -238,8 +238,16 @@ variable "matcher_config_parameter_store_tier" { } variable "storage_provider" { - description = "Storage-provider configuration used by the webhook resources." + description = <<-EOT + Storage-provider configuration used by the webhook resources. + + - `type`: Selected runner-config storage provider, `aws_ssm` (default) or `aws_dynamodb`. + - `aws.kms_key_id` / `aws.ssm.paths`: Parameter Store settings used when `type` is `aws_ssm`. + - `direct`: Environment variables and optional IAM policy for the direct webhook Lambda. + - `eventbridge`: Environment variables and optional IAM policies for the EventBridge webhook and dispatcher Lambdas. + EOT type = object({ + type = optional(string, "aws_ssm") aws = object({ kms_key_id = optional(string, null) ssm = object({ @@ -249,8 +257,27 @@ variable "storage_provider" { }) }) }) + direct = optional(object({ + environment_variables = optional(map(string), {}) + iam_policy_json = optional(string, null) + }), {}) + eventbridge = optional(object({ + webhook = optional(object({ + environment_variables = optional(map(string), {}) + iam_policy_json = optional(string, null) + }), {}) + dispatcher = optional(object({ + environment_variables = optional(map(string), {}) + iam_policy_json = optional(string, null) + }), {}) + }), {}) }) nullable = false + + validation { + condition = contains(["aws_ssm", "aws_dynamodb"], var.storage_provider.type) + error_message = "storage_provider.type must be aws_ssm or aws_dynamodb." + } } variable "eventbridge" { diff --git a/modules/webhook/webhook.tf b/modules/webhook/webhook.tf index 5677290fe3..414eb4b956 100644 --- a/modules/webhook/webhook.tf +++ b/modules/webhook/webhook.tf @@ -52,7 +52,7 @@ data "aws_region" "current" {} # New names per config version, so the Lambdas switch before old chunks are deleted. resource "aws_ssm_parameter" "runner_matcher_config" { - count = local.total_chunks + count = var.storage_provider.type == "aws_ssm" ? local.total_chunks : 0 name = "${local.matcher_config_path}-${local.matcher_config_hash}-${count.index}" type = "String" @@ -89,21 +89,14 @@ module "direct" { lambda_apigateway_access_log_settings = var.webhook_lambda_apigateway_access_log_settings, repository_white_list = var.repository_white_list, queue_selection_strategy = var.queue_selection_strategy, - storage_provider = { - aws = { - ssm = { - kms_key_id = var.storage_provider.aws.kms_key_id - } - } - } - log_level = var.log_level, - lambda_runtime = var.lambda_runtime, - aws_partition = var.aws_partition, - lambda_architecture = var.lambda_architecture, - github_app_parameters = var.github_app_parameters, - tracing_config = var.tracing_config, - lambda_tags = var.lambda_tags, - api_gw_source_arn = "${aws_apigatewayv2_api.webhook.execution_arn}/*/*/${local.webhook_endpoint}" + log_level = var.log_level, + lambda_runtime = var.lambda_runtime, + aws_partition = var.aws_partition, + lambda_architecture = var.lambda_architecture, + github_app_parameters = var.github_app_parameters, + tracing_config = var.tracing_config, + lambda_tags = var.lambda_tags, + api_gw_source_arn = "${aws_apigatewayv2_api.webhook.execution_arn}/*/*/${local.webhook_endpoint}" ssm_parameter_runner_matcher_config = [ for p in aws_ssm_parameter.runner_matcher_config : { name = p.name @@ -112,6 +105,14 @@ module "direct" { } ] ssm_parameter_runner_matcher_config_arn_pattern = local.matcher_config_arn_pattern + storage_provider = merge(var.storage_provider.direct, { + type = var.storage_provider.type + aws = { + ssm = { + kms_key_id = var.storage_provider.aws.kms_key_id + } + } + }) } } @@ -139,21 +140,14 @@ module "eventbridge" { lambda_apigateway_access_log_settings = var.webhook_lambda_apigateway_access_log_settings, repository_white_list = var.repository_white_list, queue_selection_strategy = var.queue_selection_strategy, - storage_provider = { - aws = { - ssm = { - kms_key_id = var.storage_provider.aws.kms_key_id - } - } - } - log_level = var.log_level, - lambda_runtime = var.lambda_runtime, - aws_partition = var.aws_partition, - lambda_architecture = var.lambda_architecture, - github_app_parameters = var.github_app_parameters, - tracing_config = var.tracing_config, - lambda_tags = var.lambda_tags, - api_gw_source_arn = "${aws_apigatewayv2_api.webhook.execution_arn}/*/*/${local.webhook_endpoint}" + log_level = var.log_level, + lambda_runtime = var.lambda_runtime, + aws_partition = var.aws_partition, + lambda_architecture = var.lambda_architecture, + github_app_parameters = var.github_app_parameters, + tracing_config = var.tracing_config, + lambda_tags = var.lambda_tags, + api_gw_source_arn = "${aws_apigatewayv2_api.webhook.execution_arn}/*/*/${local.webhook_endpoint}" ssm_parameter_runner_matcher_config = [ for p in aws_ssm_parameter.runner_matcher_config : { name = p.name @@ -163,6 +157,15 @@ module "eventbridge" { ] ssm_parameter_runner_matcher_config_arn_pattern = local.matcher_config_arn_pattern accept_events = var.eventbridge.accept_events + storage_provider = merge(var.storage_provider.eventbridge, { + type = var.storage_provider.type + aws = { + ssm = { + kms_key_id = var.storage_provider.aws.kms_key_id + } + } + }) + accept_events = var.eventbridge.accept_events } } From 93ef0a7346d43a8b623069c6f6e98386c1a7e7d4 Mon Sep 17 00:00:00 2001 From: tehlers320 <16598119+tehlers320@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:45:11 +0000 Subject: [PATCH 10/11] feat(control-plane): pass the compute access scope to the runner config store The DynamoDB runner config store keys one-time registration/JIT config on the compute identity so that IAM can restrict each runner to its own record. Add an optional getRunnerConfigAccessScope hook to StartRunnerConfigOptions and have the EC2 provider supply the instance ARN from EC2_INSTANCE_ARN_PREFIX (set by the DynamoDB wiring). SSM deployments never set it and keep writing the same record. Based on the accessScope handling in #5279. Signed-off-by: tehlers320 <16598119+tehlers320@users.noreply.github.com> --- .../src/scale-runners/github-runner.test.ts | 52 +++++++++++++++++++ .../src/scale-runners/github-runner.ts | 25 ++++++--- .../ec2/src/control-plane/runner-creation.ts | 2 + .../aws/ec2/src/environment.d.ts | 1 + lambdas/libs/compute-providers/core/index.ts | 1 + 5 files changed, 75 insertions(+), 6 deletions(-) diff --git a/lambdas/functions/control-plane/src/scale-runners/github-runner.test.ts b/lambdas/functions/control-plane/src/scale-runners/github-runner.test.ts index 22cf557eeb..22295ca435 100644 --- a/lambdas/functions/control-plane/src/scale-runners/github-runner.test.ts +++ b/lambdas/functions/control-plane/src/scale-runners/github-runner.test.ts @@ -183,4 +183,56 @@ describe('Test createJitConfig rate-limit metric on error', () => { expect(failedRunnerIds).toEqual(['i-1']); expect(mockedMetricGitHubAppRateLimit).not.toHaveBeenCalled(); }); + + it('stores the one-time JIT config under the compute access scope when one is provided', async () => { + const create = vi.fn(); + const client = { + actions: { + generateRunnerJitconfigForRepo: vi.fn().mockResolvedValue({ + headers: {}, + data: { runner: { id: 7 }, encoded_jit_config: 'encoded-jit' }, + }), + }, + } as unknown as Octokit; + + const failedRunnerIds = await createStartRunnerConfig( + { ...githubRunnerConfig, ephemeral: true, enableJitConfig: true }, + ['i-1'], + client, + { + runnerConfigStore: { create } as unknown as RunnerConfigStore, + runnerGroupCacheStore: { get: vi.fn().mockResolvedValue(1), create: vi.fn() }, + getRunnerConfigAccessScope: (id) => `arn:aws:ec2:eu-west-1:123456789012:instance/${id}`, + }, + ); + + expect(failedRunnerIds).toEqual([]); + expect(create).toHaveBeenCalledWith( + { + runnerId: 'i-1', + value: 'encoded-jit', + accessScope: 'arn:aws:ec2:eu-west-1:123456789012:instance/i-1', + }, + expect.anything(), + ); + }); + + it('omits the access scope when no scope provider is configured', async () => { + const create = vi.fn(); + const client = { + actions: { + generateRunnerJitconfigForRepo: vi.fn().mockResolvedValue({ + headers: {}, + data: { runner: { id: 7 }, encoded_jit_config: 'encoded-jit' }, + }), + }, + } as unknown as Octokit; + + await createStartRunnerConfig({ ...githubRunnerConfig, ephemeral: true, enableJitConfig: true }, ['i-1'], client, { + runnerConfigStore: { create } as unknown as RunnerConfigStore, + runnerGroupCacheStore: { get: vi.fn().mockResolvedValue(1), create: vi.fn() }, + }); + + expect(create.mock.calls[0][0]).toEqual({ runnerId: 'i-1', value: 'encoded-jit' }); + }); }); diff --git a/lambdas/functions/control-plane/src/scale-runners/github-runner.ts b/lambdas/functions/control-plane/src/scale-runners/github-runner.ts index 1001f0a901..74936c3c7c 100644 --- a/lambdas/functions/control-plane/src/scale-runners/github-runner.ts +++ b/lambdas/functions/control-plane/src/scale-runners/github-runner.ts @@ -5,6 +5,7 @@ import { type RunnerConfigStore, type GitHubAppCredentialsStore, type RunnerGroupCacheStore, + type RunnerConfigRecord, } from '@aws-github-runner/storage-providers'; import { Octokit } from '@octokit/rest'; @@ -22,9 +23,20 @@ export interface StartRunnerConfigOptions { runnerConfigStore?: RunnerConfigStore; runnerGroupCacheStore?: RunnerGroupCacheStore; getRunnerConfigMetadata?: (runnerId: string) => RunnerConfigMetadata[]; + // Compute identity (for EC2 the instance ARN) that alone may read a runner's one-time configuration. + getRunnerConfigAccessScope?: (runnerId: string) => string | undefined; onJitConfigCreated?: (runnerId: string, metadata: GitHubRunnerMetadata) => Promise; } +function createRunnerConfigRecord( + runnerId: string, + value: string, + options: StartRunnerConfigOptions, +): RunnerConfigRecord { + const accessScope = options.getRunnerConfigAccessScope?.(runnerId); + return { runnerId, value, ...(accessScope === undefined ? {} : { accessScope }) }; +} + function generateRunnerServiceConfig(githubRunnerConfig: CreateGitHubRunnerConfig, token: string) { const config = [ `--url ${githubRunnerConfig.ghesBaseUrl ?? 'https://github.com'}/${githubRunnerConfig.runnerOwner}`, @@ -243,10 +255,9 @@ async function createRegistrationTokenConfig( }); for (const runnerId of runnerIds) { - await runnerConfigStore.create( - { runnerId, value: runnerServiceConfig.join(' ') }, - { metadata: options.getRunnerConfigMetadata?.(runnerId) }, - ); + await runnerConfigStore.create(createRunnerConfigRecord(runnerId, runnerServiceConfig.join(' '), options), { + metadata: options.getRunnerConfigMetadata?.(runnerId), + }); if (isDelay) { // Delay to stay within the selected store's maximum write throughput. await delay(delayMilliseconds); @@ -310,8 +321,10 @@ async function createJitConfig( instance: runnerId, }); await runnerConfigStore.create( - { runnerId, value: runnerConfig.data.encoded_jit_config }, - { metadata: options.getRunnerConfigMetadata?.(runnerId) }, + createRunnerConfigRecord(runnerId, runnerConfig.data.encoded_jit_config, options), + { + metadata: options.getRunnerConfigMetadata?.(runnerId), + }, ); if (isDelay) { // Delay to stay within the selected store's maximum write throughput. diff --git a/lambdas/libs/compute-providers/aws/ec2/src/control-plane/runner-creation.ts b/lambdas/libs/compute-providers/aws/ec2/src/control-plane/runner-creation.ts index 60f3839b9f..ce2cf6166c 100644 --- a/lambdas/libs/compute-providers/aws/ec2/src/control-plane/runner-creation.ts +++ b/lambdas/libs/compute-providers/aws/ec2/src/control-plane/runner-creation.ts @@ -193,6 +193,8 @@ function createEc2StartRunnerConfigOptions( runnerConfigStore: storage?.runnerConfig, runnerGroupCacheStore: storage?.runnerGroupCache, getRunnerConfigMetadata: (instanceId) => [{ key: 'InstanceId', value: instanceId }], + getRunnerConfigAccessScope: (instanceId) => + process.env.EC2_INSTANCE_ARN_PREFIX ? `${process.env.EC2_INSTANCE_ARN_PREFIX}${instanceId}` : undefined, onJitConfigCreated: async (instanceId, metadata) => await tagEc2RunnerMetadata(ec2Operations, instanceId, metadata), }; } diff --git a/lambdas/libs/compute-providers/aws/ec2/src/environment.d.ts b/lambdas/libs/compute-providers/aws/ec2/src/environment.d.ts index c2d76c32cd..4dc2566814 100644 --- a/lambdas/libs/compute-providers/aws/ec2/src/environment.d.ts +++ b/lambdas/libs/compute-providers/aws/ec2/src/environment.d.ts @@ -18,6 +18,7 @@ declare global { | 'prioritized'; SCALE_ERRORS: string; ENABLE_ON_DEMAND_FAILOVER_FOR_ERRORS: string; + EC2_INSTANCE_ARN_PREFIX: string | undefined; } } } diff --git a/lambdas/libs/compute-providers/core/index.ts b/lambdas/libs/compute-providers/core/index.ts index 5811061ba9..fbf9ca45ab 100644 --- a/lambdas/libs/compute-providers/core/index.ts +++ b/lambdas/libs/compute-providers/core/index.ts @@ -32,6 +32,7 @@ export interface StartRunnerConfigOptions { runnerConfigStore?: import('@aws-github-runner/storage-providers').RunnerConfigStore; runnerGroupCacheStore?: import('@aws-github-runner/storage-providers').RunnerGroupCacheStore; getRunnerConfigMetadata?: (runnerId: string) => { key: string; value: string }[]; + getRunnerConfigAccessScope?: (runnerId: string) => string | undefined; onJitConfigCreated?: (runnerId: string, metadata: GitHubRunnerMetadata) => Promise; } From e7a7aa69aa5d533b6bdc7518082a4f1cdc936024 Mon Sep 17 00:00:00 2001 From: tehlers Date: Mon, 23 Nov 2026 16:58:41 +0000 Subject: [PATCH 11/11] docs: auto update terraform docs # Conflicts: # modules/multi-runner/README.md # modules/runner-config/README.md # modules/webhook/direct/README.md # modules/webhook/eventbridge/README.md --- modules/compute-providers/aws/ec2/README.md | 2 +- modules/multi-runner/README.md | 4 +++- modules/runner-config/README.md | 2 +- modules/webhook/README.md | 2 +- modules/webhook/direct/README.md | 2 +- modules/webhook/eventbridge/README.md | 2 +- 6 files changed, 8 insertions(+), 6 deletions(-) diff --git a/modules/compute-providers/aws/ec2/README.md b/modules/compute-providers/aws/ec2/README.md index d8ecf5a89f..c448ed25ec 100644 --- a/modules/compute-providers/aws/ec2/README.md +++ b/modules/compute-providers/aws/ec2/README.md @@ -66,7 +66,7 @@ No modules. | [observability](#input\_observability) | CloudWatch Logs settings available to compute-provider runner log groups.

- `logs.retention_in_days`: Retention period for provider-owned runner log groups.
- `logs.kms_key_id`: Optional KMS key ID or ARN used to encrypt runner log groups.
- `logs.tags`: Shared log-group tags that override module-level `tags`. |
object({
logs = optional(object({
retention_in_days = optional(number, 180)
kms_key_id = optional(string, null)
tags = optional(map(string), {})
}), {})
})
| `{}` | no | | [prefix](#input\_prefix) | Prefix used to identify resources created for the runner configuration. | `string` | `"github-actions"` | no | | [runner](#input\_runner) | Provider-neutral runner settings consumed by compute providers.

- `os`: Runner operating system. Supported values are `linux`, `osx`, and `windows`.
- `architecture`: Runner distribution architecture.
- `name_prefix`: Prefix added to registered runner names.
- `run_as_root`: Runs the runner service as root.
- `run_as`: Operating-system user used when `run_as_root` is false.
- `hooks.job_started`: Script installed as the runner job-started hook.
- `hooks.job_completed`: Script installed as the runner job-completed hook.
- `iam.role.arn`: Resolved runner-role ARN referenced by provider policies and resources.
- `iam.role.name`: Resolved runner-role name used by provider resources.
- `iam.role.managed`: Whether runner-config manages the resolved runner role.
- `iam.managed_policy_arns`: Common managed-policy ARNs returned with the provider-specific runner policies for attachment by runner-config.
- `iam.path`: IAM path available to provider-managed IAM resources. Null derives the path from `prefix`. |
object({
os = optional(string, "linux")
architecture = optional(string, "x64")
name_prefix = optional(string, "")
run_as_root = optional(bool, false)
run_as = optional(string, "ec2-user")
hooks = optional(object({
job_started = optional(string, "")
job_completed = optional(string, "")
}), {})
iam = object({
role = object({
arn = string
name = string
managed = optional(bool, true)
})
managed_policy_arns = optional(map(string), {})
path = optional(string, null)
})
})
| n/a | yes | -| [storage\_provider](#input\_storage\_provider) | Storage-provider configuration available to compute-provider bootstrap resources.

- `aws.ssm`: AWS Systems Manager Parameter Store configuration, when SSM is selected.
- `aws.ssm.paths.root`: Root Parameter Store path for the runner configuration.
- `aws.ssm.paths.tokens`: Path segment used for registration tokens and just-in-time configuration.
- `aws.ssm.paths.config`: Path segment used for persistent runner and provider configuration.
- `aws.ssm.tags`: Shared SSM tags that override module-level `tags`.
- `aws.ssm.parameters.tags`: Parameter-specific tags that override module-level and shared SSM tags. |
object({
aws = object({
ssm = object({
paths = object({
root = string
tokens = string
config = string
})
tags = optional(map(string), {})
parameters = optional(object({
tags = optional(map(string), {})
}), {})
})
})
})
| n/a | yes | +| [storage\_provider](#input\_storage\_provider) | Storage-provider configuration available to compute-provider bootstrap resources.

- `type`: Selected runner-config storage provider, `aws_ssm` (default) or `aws_dynamodb`.
- `aws.ssm`: AWS Systems Manager Parameter Store configuration, used when `type` is `aws_ssm`.
- `aws.ssm.paths.root`: Root Parameter Store path for the runner configuration.
- `aws.ssm.paths.tokens`: Path segment used for registration tokens and just-in-time configuration.
- `aws.ssm.paths.config`: Path segment used for persistent runner and provider configuration.
- `aws.ssm.tags`: Shared SSM tags that override module-level `tags`.
- `aws.ssm.parameters.tags`: Parameter-specific tags that override module-level and shared SSM tags.
- `runner`: Runner-side DynamoDB locators and the opaque IAM policy supplied by runner-config, required when `type` is `aws_dynamodb`. |
object({
type = optional(string, "aws_ssm")
aws = object({
ssm = object({
paths = object({
root = string
tokens = string
config = string
})
tags = optional(map(string), {})
parameters = optional(object({
tags = optional(map(string), {})
}), {})
})
})
runner = optional(object({
config_table_name = optional(string, null)
runner_state_table_name = optional(string, null)
scope = optional(string, null)
iam_policy_json = optional(string, null)
}), {})
})
| n/a | yes | | [tags](#input\_tags) | Base tags available to taggable compute-provider resources. Provider-specific tags override this map within their documented scopes. | `map(string)` | `{}` | no | ## Outputs diff --git a/modules/multi-runner/README.md b/modules/multi-runner/README.md index dcda7dc0fa..aa63584fcd 100644 --- a/modules/multi-runner/README.md +++ b/modules/multi-runner/README.md @@ -124,6 +124,7 @@ module "multi-runner" { | [runner\_configs](#module\_runner\_configs) | ../runner-config | n/a | | [runners](#module\_runners) | ../runners | n/a | | [ssm](#module\_ssm) | ../storage-providers/aws/ssm | n/a | +| [storage\_aws\_dynamodb](#module\_storage\_aws\_dynamodb) | ../storage-providers/aws/dynamodb | n/a | | [webhook](#module\_webhook) | ../webhook | n/a | ## Resources @@ -137,6 +138,7 @@ module "multi-runner" { | [random_string.random](https://registry.terraform.io/providers/hashicorp/random/latest/docs/resources/string) | resource | | [terraform_data.validate_v1](https://registry.terraform.io/providers/hashicorp/terraform/latest/docs/resources/data) | resource | | [terraform_data.validate_v2](https://registry.terraform.io/providers/hashicorp/terraform/latest/docs/resources/data) | resource | +| [aws_caller_identity.storage](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/caller_identity) | data source | | [aws_iam_policy_document.deny_insecure_transport](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source | ## Inputs @@ -168,7 +170,7 @@ module "multi-runner" { | [global\_config\_lambda](#input\_global\_config\_lambda) | Global Lambda configuration shared by all runner lanes.

global\_config\_lambda = {
artifact.s3.bucket: "S3 bucket containing Lambda deployment artifacts."
runtime: "Default Lambda runtime."
architecture: "Default Lambda instruction-set architecture."
principals: "Additional AWS principals allowed to invoke the Lambda functions."
principals.type: "Principal type, such as AWS account, service, or organization."
principals.identifiers: "Identifiers allowed for the principal type."
subnet\_ids: "Subnets used by Lambda functions."
security\_group\_ids: "Security groups attached to Lambda functions."
tags: "Tags applied to Lambda functions and related resources."
role.path: "IAM path used for Lambda execution roles."
role.permissions\_boundary: "Optional IAM permissions boundary ARN for Lambda execution roles."
} |
object({
artifact = optional(object({
s3 = optional(object({
bucket = optional(string, null)
}), {})
}), {})
runtime = optional(string, "nodejs24.x")
architecture = optional(string, "arm64")
principals = optional(list(object({
type = string
identifiers = list(string)
})), [])
subnet_ids = optional(list(string), [])
security_group_ids = optional(list(string), [])
tags = optional(map(string), {})
role = optional(object({
path = optional(string, null)
permissions_boundary = optional(string, null)
}), {})
})
| `{}` | no | | [global\_config\_observability](#input\_global\_config\_observability) | Global observability configuration shared by all runner lanes.

global\_config\_observability = {
logs.level: "Log level for module resources."
logs.retention\_in\_days: "CloudWatch log retention period in days."
logs.kms\_key\_id: "KMS key ID used to encrypt CloudWatch log groups."
logs.class: "CloudWatch log group class."
logs.tags: "Tags applied to CloudWatch log groups."
tracing.mode: "Tracing mode used by instrumented resources."
tracing.capture\_http\_requests: "Whether HTTP requests are captured by tracing."
tracing.capture\_error: "Whether errors are captured by tracing."
metrics.enabled: "Whether module metrics are enabled."
metrics.namespace: "CloudWatch namespace used for module metrics."
metrics.metric.github\_app\_rate\_limit.enabled: "Whether GitHub App rate-limit metrics are emitted."
metrics.metric.job\_retry.enabled: "Whether job-retry metrics are emitted."
metrics.metric.spot\_termination\_warning.enabled: "Whether spot-termination warning metrics are emitted."
} |
object({
logs = optional(object({
level = optional(string, "info")
retention_in_days = optional(number, 180)
kms_key_id = optional(string, null)
class = optional(string, "STANDARD")
tags = optional(map(string), {})
}), {})
tracing = optional(object({
mode = optional(string, null)
capture_http_requests = optional(bool, false)
capture_error = optional(bool, false)
}), {})
metrics = optional(object({
enabled = optional(bool, false)
namespace = optional(string, "GitHub Runners")
metric = optional(object({
github_app_rate_limit = optional(object({
enabled = optional(bool, true)
}), {})
job_retry = optional(object({
enabled = optional(bool, true)
}), {})
spot_termination_warning = optional(object({
enabled = optional(bool, true)
}), {})
}), {})
}), {})
})
| `{}` | no | | [global\_config\_orchestration\_provider](#input\_global\_config\_orchestration\_provider) | Global orchestration-provider configuration shared by all runner lanes.

global\_config\_orchestration\_provider = {
webhook: {
queue\_selection\_strategy: "Strategy used to select the build queue for a webhook event."
eventbridge.enabled: "Whether EventBridge integration is enabled for webhook events."
eventbridge.accept\_events: "Event types accepted by the EventBridge integration."
matcher\_config\_parameter\_store\_tier: "SSM Parameter Store tier used for matcher configuration."
runner.boot\_time\_in\_minutes: "Expected runner boot time used by orchestration."
runner.ephemeral: "Whether runners created by the orchestration provider are ephemeral."
runner.jit\_config\_enabled: "Whether JIT runner configuration is enabled."
runner.maximum\_count: "Maximum number of runners that orchestration may create."
github.repository\_white\_list: "Repositories allowed to use the webhook configuration."
lambda.artifact.zip: "Local ZIP artifact used for orchestration Lambda functions."
lambda.artifact.s3.key: "S3 object key for the orchestration Lambda artifact."
lambda.artifact.s3.object\_version: "Optional S3 object version for the orchestration Lambda artifact."
lambda.scale.up.memory\_size: "Memory allocated to the scale-up Lambda."
lambda.scale.up.timeout: "Timeout in seconds for the scale-up Lambda."
lambda.scale.up.reserved\_concurrent\_executions: "Reserved concurrent executions for the scale-up Lambda."
lambda.scale.up.job\_queued\_check\_enabled: "Whether the scale-up Lambda checks queued jobs."
lambda.scale.up.event\_source\_mapping.batch\_size: "Maximum records passed to one scale-up Lambda invocation."
lambda.scale.up.event\_source\_mapping.maximum\_batching\_window\_in\_seconds: "Maximum time to batch records before invoking the scale-up Lambda."
lambda.scale.up.tags: "Tags applied to the scale-up Lambda."
lambda.scale.down.memory\_size: "Memory allocated to the scale-down Lambda."
lambda.scale.down.timeout: "Timeout in seconds for the scale-down Lambda."
lambda.scale.down.schedule\_expression: "Schedule expression for scale-down processing."
lambda.scale.down.minimum\_running\_time\_in\_minutes: "Minimum runner lifetime before scale-down."
lambda.scale.down.idle\_confirmation\_seconds: "Seconds a runner must consistently report not-busy before scale-down terminates it; 0 disables the confirmation window."
lambda.scale.down.idle\_config: "Scheduled minimum idle-runner pool settings."
lambda.scale.down.idle\_config.cron: "Cron expression defining when the idle-runner count applies."
lambda.scale.down.idle\_config.timeZone: "Time zone used to evaluate the idle-runner schedule."
lambda.scale.down.idle\_config.idleCount: "Minimum number of idle runners maintained during the schedule."
lambda.scale.down.idle\_config.evictionStrategy: "Strategy used when evicting idle runners."
lambda.scale.down.tags: "Tags applied to the scale-down Lambda."
lambda.webhook.artifact.zip: "Local ZIP artifact used for the webhook Lambda."
lambda.webhook.artifact.s3.key: "S3 object key for the webhook Lambda artifact."
lambda.webhook.artifact.s3.object\_version: "Optional S3 object version for the webhook Lambda artifact."
lambda.webhook.api\_gateway\_access\_log\_settings: "API Gateway access-log destination and format."
lambda.webhook.api\_gateway\_access\_log\_settings.destination\_arn: "ARN of the API Gateway access-log destination."
lambda.webhook.api\_gateway\_access\_log\_settings.format: "API Gateway access-log format."
lambda.webhook.memory\_size: "Memory allocated to the webhook Lambda."
lambda.webhook.timeout: "Timeout in seconds for the webhook Lambda."
lambda.webhook.tags: "Tags applied to the webhook Lambda."
lambda.pool.memory\_size: "Memory allocated to the pool Lambda."
lambda.pool.timeout: "Timeout in seconds for the pool Lambda."
lambda.pool.reserved\_concurrent\_executions: "Reserved concurrent executions for the pool Lambda."
lambda.pool.config: "Scheduled runner-pool size configuration."
lambda.pool.config.schedule\_expression: "Schedule expression for the pool size."
lambda.pool.config.schedule\_expression\_timezone: "Time zone used to evaluate the pool schedule."
lambda.pool.config.size: "Runner pool size applied by the schedule."
lambda.pool.include\_busy\_runners: "Whether busy runners are included in pool sizing."
lambda.pool.runner\_owner: "GitHub organization that owns the runner pool."
lambda.pool.tags: "Tags applied to the pool Lambda."
queue.delay\_webhook\_event: "Seconds a webhook event remains invisible in the build queue before processing."
queue.job\_queue\_retention\_in\_seconds: "Seconds a queued job is retained before it is purged."
queue.visibility\_timeout\_seconds: "Build queue visibility timeout in seconds."
queue.redrive\_build\_queue.enabled: "Whether the build queue dead-letter queue is enabled."
queue.redrive\_build\_queue.maxReceiveCount: "Maximum receives before a message is moved to the dead-letter queue."
queue.tags: "Tags applied to build queues."
queue.encryption.kms\_data\_key\_reuse\_period\_seconds: "KMS data-key reuse period for queue encryption."
queue.encryption.kms\_master\_key\_id: "KMS key ID used for queue encryption."
queue.encryption.sqs\_managed\_sse\_enabled: "Whether SQS-managed server-side encryption is enabled."
}
} |
object({
webhook = optional(object({
queue_selection_strategy = optional(string, "first")
eventbridge = optional(object({
enabled = optional(bool, true)
accept_events = optional(list(string), [])
}), {})
matcher_config_parameter_store_tier = optional(string, "Standard")
runner = optional(object({
boot_time_in_minutes = optional(number, 5)
ephemeral = optional(bool, false)
jit_config_enabled = optional(bool, null)
maximum_count = optional(number, null)
}), {})

github = optional(object({
repository_white_list = optional(list(string), [])
}), {})

lambda = optional(object({
artifact = optional(object({
zip = optional(string, null)
s3 = optional(object({
key = string
object_version = optional(string, null)
}), null)
}), {})
scale = optional(object({
up = optional(object({
memory_size = optional(number, 512)
timeout = optional(number, 30)
reserved_concurrent_executions = optional(number, 1)
job_queued_check_enabled = optional(bool, null)
event_source_mapping = optional(object({
batch_size = optional(number, 10)
maximum_batching_window_in_seconds = optional(number, 0)
}), {})
tags = optional(map(string), {})
}), {})
down = optional(object({
memory_size = optional(number, 512)
timeout = optional(number, 60)
schedule_expression = optional(string, "cron(*/5 * * * ? *)")
minimum_running_time_in_minutes = optional(number, null)
idle_confirmation_seconds = optional(number, 0)
idle_config = optional(list(object({
cron = string
timeZone = string
idleCount = number
evictionStrategy = optional(string, "oldest_first")
})), [])
tags = optional(map(string), {})
}), {})
}), {})
webhook = optional(object({
artifact = optional(object({
zip = optional(string, null)
s3 = optional(object({
key = string
object_version = optional(string, null)
}), null)
}), {})
api_gateway_access_log_settings = optional(object({
destination_arn = string
format = string
}), null)
memory_size = optional(number, 256)
timeout = optional(number, 10)
tags = optional(map(string), {})
}), {})
pool = optional(object({
memory_size = optional(number, 512)
timeout = optional(number, 60)
reserved_concurrent_executions = optional(number, 1)
config = optional(list(object({
schedule_expression = string
schedule_expression_timezone = optional(string)
size = number
})), [])
include_busy_runners = optional(bool, false)
runner_owner = optional(string, null)
tags = optional(map(string), {})
}), {})
}), {})

queue = optional(object({
delay_webhook_event = optional(number, 30)
job_queue_retention_in_seconds = optional(number, 86400)
visibility_timeout_seconds = optional(number, 180)
redrive_build_queue = optional(object({
enabled = optional(bool, false)
maxReceiveCount = optional(number, null)
}), {
enabled = false
maxReceiveCount = null
})
tags = optional(map(string), {})
encryption = optional(object({
kms_data_key_reuse_period_seconds = number
kms_master_key_id = string
sqs_managed_sse_enabled = bool
}), {
kms_data_key_reuse_period_seconds = null
kms_master_key_id = null
sqs_managed_sse_enabled = true
})
}), {})

}), {})

scale_set = optional(object({
grouping = optional(object({
strategy = optional(string, "compute_provider")
custom = optional(object({
groups = map(object({
runner_configs = set(string)
}))
}), null)
}), {})
container = optional(object({
image = optional(string, null)
user = optional(string, "10001:10001")
health_port = optional(number, 8080)
health_path = optional(string, "/healthz")
health_check_command = optional(list(string), null)
health_check_interval = optional(number, 30)
health_check_timeout = optional(number, 5)
health_check_retries = optional(number, 3)
health_check_start_period = optional(number, 30)
health_stale_after_seconds = optional(number, 180)
shutdown_timeout_seconds = optional(number, 110)
session_close_timeout_seconds = optional(number, 10)
reconnect_initial_backoff_seconds = optional(number, 1)
reconnect_max_backoff_seconds = optional(number, 30)
stop_timeout_seconds = optional(number, 120)
}), {})
config_store = optional(object({
path_prefix = optional(string, null)
tier = optional(string, "Standard")
tags = optional(map(string), {})
}), {})
ecs = optional(object({
cluster = optional(object({
mode = optional(string, "managed")
arn = optional(string, null)
name = optional(string, null)
container_insights = optional(bool, true)
}), {})
task = optional(object({
cpu = optional(number, 512)
memory = optional(number, 1024)
cpu_architecture = optional(string, "X86_64")
ephemeral_storage = optional(object({
size_in_gib = number
}), null)
}), {})
service = optional(object({
platform_version = optional(string, "LATEST")
}), {})
iam = optional(object({
path = optional(string, "/")
permissions_boundary = optional(string, null)
}), {})
}), {})
network = optional(object({
vpc_id = optional(string, null)
subnet_ids = optional(set(string), null)
https_egress = optional(object({
ipv4_cidrs = optional(set(string), ["0.0.0.0/0"])
ipv6_cidrs = optional(set(string), [])
}), {})
}), {})
logging = optional(object({
retention_in_days = optional(number, 180)
kms_key_id = optional(string, null)
log_group_class = optional(string, "STANDARD")
tags = optional(map(string), {})
}), {})
tags = optional(map(string), {})
}), {})
})
| `{}` | no | -| [global\_config\_storage\_provider](#input\_global\_config\_storage\_provider) | Global storage-provider configuration shared by all runner lanes.

global\_config\_storage\_provider = {
aws.ssm.paths.root: "Root path for SSM parameters."
aws.ssm.paths.app: "Path segment for application parameters."
aws.ssm.paths.webhook: "Path segment for webhook parameters."
aws.ssm.paths.tokens: "Path segment for runner token parameters."
aws.ssm.paths.config: "Path segment for runner configuration parameters."
aws.ssm.kms\_key\_id: "KMS key ID used to encrypt SSM parameters."
aws.ssm.tags: "Tags applied to SSM resources."
aws.ssm.parameters.tags: "Tags applied to runner configuration parameters."
aws.ssm.parameters.max\_concurrent\_invocations: "Expected number of concurrent scale-up and pool Lambda invocations writing to Parameter Store, used to pace each invocation's writes to a share of the account-wide write-rate limit."
aws.ssm.parameters.max\_writes\_per\_second: "Parameter Store write rate to pace against, in writes per second. AWS documents a PutParameter quota of 3 TPS per account and Region (10 TPS with higher throughput enabled). The default of 40 keeps the previous pacing; lower it if PutParameter calls are throttled."
aws.ssm.housekeeper.schedule\_expression: "Schedule for the SSM parameter housekeeper."
aws.ssm.housekeeper.state: "EventBridge rule state for the SSM housekeeper."
aws.ssm.housekeeper.tags: "Tags applied to the SSM housekeeper resources."
aws.ssm.housekeeper.lambda.artifact.zip: "Local ZIP artifact used for the SSM housekeeper Lambda."
aws.ssm.housekeeper.lambda.artifact.s3.key: "S3 object key for the SSM housekeeper Lambda."
aws.ssm.housekeeper.lambda.artifact.s3.object\_version: "Optional S3 object version for the SSM housekeeper artifact."
aws.ssm.housekeeper.lambda.memory\_size: "Memory allocated to the SSM housekeeper Lambda."
aws.ssm.housekeeper.lambda.timeout: "Timeout in seconds for the SSM housekeeper Lambda."
aws.ssm.housekeeper.config.tokenPath: "Parameter path containing runner tokens to clean up."
aws.ssm.housekeeper.config.minimumDaysOld: "Minimum age in days before an old token is eligible for cleanup."
aws.ssm.housekeeper.config.dryRun: "Whether the SSM housekeeper reports cleanup without deleting parameters."
} |
object({
aws = optional(object({
ssm = optional(object({
paths = optional(object({
root = optional(string, null)
app = optional(string, "app")
webhook = optional(string, "webhook")
tokens = optional(string, "runners/tokens")
config = optional(string, "runners/config")
}), {})
kms_key_id = optional(string, null)
tags = optional(map(string), {})
parameters = optional(object({
tags = optional(map(string), {})
max_concurrent_invocations = optional(number, 1)
max_writes_per_second = optional(number, 40)
}), {})
housekeeper = optional(object({
schedule_expression = optional(string, "rate(1 day)")
state = optional(string, "ENABLED")
tags = optional(map(string), {})
lambda = optional(object({
artifact = optional(object({
zip = optional(string, null)
s3 = optional(object({
key = string
object_version = optional(string, null)
}), null)
}), {})
memory_size = optional(number, 512)
timeout = optional(number, 60)
}), {})
config = optional(object({
tokenPath = optional(string, null)
minimumDaysOld = optional(number, 1)
dryRun = optional(bool, false)
}), {})
}), {})
}), {})
}), {})
})
| `{}` | no | +| [global\_config\_storage\_provider](#input\_global\_config\_storage\_provider) | Global storage-provider configuration shared by all runner lanes.

global\_config\_storage\_provider = {
aws.ssm.paths.root: "Root path for SSM parameters."
aws.ssm.paths.app: "Path segment for application parameters."
aws.ssm.paths.webhook: "Path segment for webhook parameters."
aws.ssm.paths.tokens: "Path segment for runner token parameters."
aws.ssm.paths.config: "Path segment for runner configuration parameters."
aws.ssm.kms\_key\_id: "KMS key ID used to encrypt SSM parameters."
aws.ssm.tags: "Tags applied to SSM resources."
aws.ssm.parameters.tags: "Tags applied to runner configuration parameters."
aws.ssm.parameters.max\_concurrent\_invocations: "Expected number of concurrent scale-up and pool Lambda invocations writing to Parameter Store, used to pace each invocation's writes to a share of the account-wide write-rate limit."
aws.ssm.parameters.max\_writes\_per\_second: "Parameter Store write rate to pace against, in writes per second. AWS documents a PutParameter quota of 3 TPS per account and Region (10 TPS with higher throughput enabled). The default of 40 keeps the previous pacing; lower it if PutParameter calls are throttled."
aws.ssm.housekeeper.schedule\_expression: "Schedule for the SSM parameter housekeeper."
aws.ssm.housekeeper.state: "EventBridge rule state for the SSM housekeeper."
aws.ssm.housekeeper.tags: "Tags applied to the SSM housekeeper resources."
aws.ssm.housekeeper.lambda.artifact.zip: "Local ZIP artifact used for the SSM housekeeper Lambda."
aws.ssm.housekeeper.lambda.artifact.s3.key: "S3 object key for the SSM housekeeper Lambda."
aws.ssm.housekeeper.lambda.artifact.s3.object\_version: "Optional S3 object version for the SSM housekeeper artifact."
aws.ssm.housekeeper.lambda.memory\_size: "Memory allocated to the SSM housekeeper Lambda."
aws.ssm.housekeeper.lambda.timeout: "Timeout in seconds for the SSM housekeeper Lambda."
aws.ssm.housekeeper.config.tokenPath: "Parameter path containing runner tokens to clean up."
aws.ssm.housekeeper.config.minimumDaysOld: "Minimum age in days before an old token is eligible for cleanup."
aws.ssm.housekeeper.config.dryRun: "Whether the SSM housekeeper reports cleanup without deleting parameters."
aws.dynamodb.config.kms\_key\_arn: "Optional customer-managed KMS key ARN for the durable configuration table."
aws.dynamodb.config.point\_in\_time\_recovery\_enabled: "Enables point-in-time recovery for the durable configuration table."
aws.dynamodb.config.deletion\_protection\_enabled: "Enables deletion protection for the durable configuration table."
aws.dynamodb.config.tags: "Tags applied to the durable configuration table."
aws.dynamodb.runner\_state.kms\_key\_arn: "Optional customer-managed KMS key ARN for the runner-state table."
aws.dynamodb.runner\_state.point\_in\_time\_recovery\_enabled: "Enables point-in-time recovery for the runner-state table."
aws.dynamodb.runner\_state.deletion\_protection\_enabled: "Enables deletion protection for the runner-state table."
aws.dynamodb.runner\_state.runner\_config\_ttl\_seconds: "TTL in seconds for one-time registration and JIT configuration records."
aws.dynamodb.runner\_state.runner\_state\_ttl\_seconds: "Safety TTL in seconds for provisioning and terminating lifecycle records."
aws.dynamodb.runner\_state.tags: "Tags applied to the runner-state table."
}

Setting aws.dynamodb moves runner configuration, GitHub App credentials, the webhook secret and the runner matcher
configuration to DynamoDB. Omitting it keeps the SSM backend; aws.ssm continues to supply paths for remaining SSM resources. |
object({
aws = optional(object({
ssm = optional(object({
paths = optional(object({
root = optional(string, null)
app = optional(string, "app")
webhook = optional(string, "webhook")
tokens = optional(string, "runners/tokens")
config = optional(string, "runners/config")
}), {})
kms_key_id = optional(string, null)
tags = optional(map(string), {})
parameters = optional(object({
tags = optional(map(string), {})
max_concurrent_invocations = optional(number, 1)
max_writes_per_second = optional(number, 40)
}), {})
housekeeper = optional(object({
schedule_expression = optional(string, "rate(1 day)")
state = optional(string, "ENABLED")
tags = optional(map(string), {})
lambda = optional(object({
artifact = optional(object({
zip = optional(string, null)
s3 = optional(object({
key = string
object_version = optional(string, null)
}), null)
}), {})
memory_size = optional(number, 512)
timeout = optional(number, 60)
}), {})
config = optional(object({
tokenPath = optional(string, null)
minimumDaysOld = optional(number, 1)
dryRun = optional(bool, false)
}), {})
}), {})
}), {})
dynamodb = optional(object({
config = optional(object({
kms_key_arn = optional(string, null)
point_in_time_recovery_enabled = optional(bool, true)
deletion_protection_enabled = optional(bool, false)
tags = optional(map(string), {})
}), {})
runner_state = optional(object({
kms_key_arn = optional(string, null)
point_in_time_recovery_enabled = optional(bool, false)
deletion_protection_enabled = optional(bool, false)
runner_config_ttl_seconds = optional(number, 86400)
runner_state_ttl_seconds = optional(number, 604800)
tags = optional(map(string), {})
}), {})
}), null)
}), {})
})
| `{}` | no | | [iam\_overrides](#input\_iam\_overrides) | This map provides the possibility to override some IAM defaults. The following attributes are supported: `instance_profile_name` overrides the instance profile name used in the launch template. `runner_role_arn` overrides the IAM role ARN used for the runner instances. |
object({
override_instance_profile = optional(bool, null)
instance_profile_name = optional(string, null)
override_runner_role = optional(bool, null)
runner_role_arn = optional(string, null)
})
|
{
"instance_profile_name": null,
"override_instance_profile": false,
"override_runner_role": false,
"runner_role_arn": null
}
| no | | [instance\_profile\_path](#input\_instance\_profile\_path) | The path that will be added to the instance\_profile, if not set the environment name will be used. | `string` | `null` | no | | [instance\_termination\_watcher](#input\_instance\_termination\_watcher) | Configuration for the spot termination watcher lambda function. This feature is Beta, changes will not trigger a major release as long in beta.

`enable`: Enable or disable the spot termination watcher.
`enable_runner_deregistration`: Enable or disable deregistering the runner from GitHub when its EC2 instance is terminated.
`environment_variables`: Additional environment variables to merge into the Lambda configuration.
`memory_size`: Memory size limit in MB of the lambda.
`s3_key`: S3 key for syncer lambda function. Required if using S3 bucket to specify lambdas.
`s3_object_version`: S3 object version for syncer lambda function. Useful if S3 versioning is enabled on source bucket.
`timeout`: Time out of the lambda in seconds.
`zip`: File location of the lambda zip file. |
object({
enable = optional(bool, false)
features = optional(object({
enable_spot_termination_handler = optional(bool, true)
enable_spot_termination_notification_watcher = optional(bool, true)
}), {})
enable_runner_deregistration = optional(bool, true)
environment_variables = optional(map(string), {})
memory_size = optional(number, null)
s3_key = optional(string, null)
s3_object_version = optional(string, null)
timeout = optional(number, null)
zip = optional(string, null)
})
| `{}` | no | diff --git a/modules/runner-config/README.md b/modules/runner-config/README.md index 11a0ac8721..77e64e5c95 100644 --- a/modules/runner-config/README.md +++ b/modules/runner-config/README.md @@ -116,7 +116,7 @@ yarn run dist | [orchestration\_provider](#input\_orchestration\_provider) | Runner demand-orchestration provider configuration. Exactly one provider block must be non-null. Wrapper presence selects the provider and must therefore be known during planning; values inside the selected provider may remain unknown until apply.

- `webhook`: Selects the workflow-job webhook control plane. It owns runner lifecycle and capacity, the build queue reference, the runner-control artifact, scale-up, scale-down, scheduled pool, and optional job-retry controls.
- `scale_set`: Selects scale-set orchestration for this runner config. The multi-runner topology owns the shared controller service and passes this plan-known selection marker to runner-config. Scale-set runners always use ephemeral JIT registration.
- `webhook.runner`: Runner lifecycle, boot timeout, and capacity settings owned by webhook orchestration.
- `webhook.runner.boot_time_in_minutes`: Expected runner boot duration used by scale-down and pool controls. The default is `5`.
- `webhook.runner.ephemeral`: Registers runners in ephemeral mode. The default is `false`.
- `webhook.runner.jit_config_enabled`: Explicitly enables or disables just-in-time configuration. The default is null, which follows `runner.ephemeral`.
- `webhook.runner.maximum_count`: Maximum number of runners managed for this runner configuration. The default is `3`.
- `webhook.github.organization_runners`: Registers runners at organization scope when true; otherwise registration is repository-scoped.
- `webhook.queue.build.arn`: ARN of the runner configuration's build queue.
- `webhook.queue.build.url`: URL of the runner configuration's build queue.
- `webhook.queue.kms_key_id`: Optional KMS key ARN encrypting the build queue. The default is null and is independent from the Parameter Store KMS key.
- `webhook.queue.tags`: Tags inherited by queue-related provider resources before component-specific overrides. The default is `{}`.
- `webhook.lambda.artifact`: Runner-control artifact shared by scale, pool, and job-retry components. Set at most one of `zip` or `s3`; no selection uses the packaged runner archive.
- `webhook.lambda.artifact.zip`: Optional local path to the runner-control Lambda archive. The default is null.
- `webhook.lambda.artifact.s3`: Optional S3 object selector in the common `lambda.artifact.s3.bucket`. Wrapper presence must be known during planning, selecting it requires a non-null common bucket, and the default is null.
- `webhook.lambda.artifact.s3.key`: Object key of the runner-control Lambda archive.
- `webhook.lambda.artifact.s3.object_version`: Optional object version of the runner-control Lambda archive. The default is null.
- `webhook.lambda.scale.up.memory_size`: Memory allocated to the scale-up Lambda in MB. The default is `512`.
- `webhook.lambda.scale.up.timeout`: Scale-up Lambda timeout in seconds. The default is `60`.
- `webhook.lambda.scale.up.reserved_concurrent_executions`: Reserved concurrency for scale-up. The default is `1`; use `-1` for unreserved concurrency.
- `webhook.lambda.scale.up.job_queued_check_enabled`: Enables queued-job verification before scaling. The default is null, which follows the resolved runner mode.
- `webhook.lambda.scale.up.event_source_mapping.batch_size`: Maximum build-queue records delivered per scale-up invocation. The default is `10`.
- `webhook.lambda.scale.up.event_source_mapping.maximum_batching_window_in_seconds`: Maximum batching window for build-queue records. The default is `0`.
- `webhook.lambda.scale.up.tags`: Tags applied within scale-up resource scopes after common provider tags. The default is `{}`.
- `webhook.lambda.scale.down.memory_size`: Memory allocated to the scale-down Lambda in MB. The default is `512`.
- `webhook.lambda.scale.down.timeout`: Scale-down Lambda timeout in seconds. The default is `60`.
- `webhook.lambda.scale.down.schedule_expression`: EventBridge schedule expression that invokes scale-down. The default is `cron(*/5 * * * ? *)`.
- `webhook.lambda.scale.down.minimum_running_time_in_minutes`: Optional minimum runner age before scale-down may terminate it. The default is null, which selects the operating-system default.
- `webhook.lambda.scale.down.idle_confirmation_seconds`: Number of seconds a runner must consistently report not-busy before scale-down terminates it. The default is `0`, which preserves the single-reading behavior.
- `webhook.lambda.scale.down.idle_config`: Time-based desired idle-runner configurations. The default is `[]`.
- `webhook.lambda.scale.down.idle_config[].cron`: Cron expression identifying when the idle configuration applies.
- `webhook.lambda.scale.down.idle_config[].timeZone`: IANA time zone used to evaluate the cron expression.
- `webhook.lambda.scale.down.idle_config[].idleCount`: Number of idle runners retained during the matching period.
- `webhook.lambda.scale.down.idle_config[].evictionStrategy`: Selection strategy used when excess idle runners are removed. The default is `oldest_first`.
- `webhook.lambda.scale.down.tags`: Tags applied within scale-down resource scopes after common provider tags. The default is `{}`.
- `webhook.lambda.pool.memory_size`: Memory allocated to the pool Lambda in MB. The default is `512`.
- `webhook.lambda.pool.timeout`: Pool Lambda timeout in seconds. The default is `60`.
- `webhook.lambda.pool.reserved_concurrent_executions`: Reserved concurrency for the pool Lambda. The default is `1`; use `-1` for unreserved concurrency.
- `webhook.lambda.pool.config`: Scheduled target pool sizes. The default is `[]`, which disables the pool component.
- `webhook.lambda.pool.config[].schedule_expression`: Scheduler expression that activates the target size.
- `webhook.lambda.pool.config[].schedule_expression_timezone`: Optional IANA time zone used to evaluate the schedule.
- `webhook.lambda.pool.config[].size`: Desired number of runners for the schedule.
- `webhook.lambda.pool.include_busy_runners`: Includes busy runners when reconciling scheduled pool capacity. The default is `false`.
- `webhook.lambda.pool.runner_owner`: Optional GitHub organization or repository owner used for pooled runners. The default is null.
- `webhook.lambda.pool.tags`: Tags applied within pool resource scopes after common provider tags. The default is `{}`.
- `webhook.job_retry.enabled`: Creates the retry queue, Lambda function, event-source mapping, and related IAM resources. The default is `false`.
- `webhook.job_retry.delay_in_seconds`: Initial delay before a queued-job retry check. The default is `300`.
- `webhook.job_retry.delay_backoff`: Multiplier applied to the delay after each unsuccessful check. The default is `2`.
- `webhook.job_retry.max_attempts`: Maximum retry-check attempts before the message is no longer republished. The default is `1`.
- `webhook.job_retry.tags`: Tags applied within job-retry resource scopes after common provider tags. The default is `{}`.
- `webhook.job_retry.lambda.memory_size`: Memory allocated to the job-retry Lambda in MB. The default is `256`.
- `webhook.job_retry.lambda.reserved_concurrent_executions`: Reserved concurrency for job retry. The default is unreserved; set a positive value to limit concurrency or `0` to disable invocations.
- `webhook.job_retry.lambda.timeout`: Job-retry Lambda timeout in seconds and visibility timeout for its retry queue. The default is `30`. |
object({
webhook = optional(object({
runner = optional(object({
boot_time_in_minutes = optional(number, 5)
ephemeral = optional(bool, false)
jit_config_enabled = optional(bool, null)
maximum_count = optional(number, 3)
}), {})
github = object({
organization_runners = bool
})
queue = object({
build = object({
arn = string
url = string
})
kms_key_id = optional(string, null)
tags = optional(map(string), {})
})
lambda = optional(object({
artifact = optional(object({
zip = optional(string, null)
s3 = optional(object({
key = string
object_version = optional(string, null)
}), null)
}), {})
scale = optional(object({
up = optional(object({
memory_size = optional(number, 512)
timeout = optional(number, 60)
reserved_concurrent_executions = optional(number, 1)
job_queued_check_enabled = optional(bool, null)
event_source_mapping = optional(object({
batch_size = optional(number, 10)
maximum_batching_window_in_seconds = optional(number, 0)
}), {})
tags = optional(map(string), {})
}), {})
down = optional(object({
memory_size = optional(number, 512)
timeout = optional(number, 60)
schedule_expression = optional(string, "cron(*/5 * * * ? *)")
minimum_running_time_in_minutes = optional(number, null)
idle_confirmation_seconds = optional(number, 0)
idle_config = optional(list(object({
cron = string
timeZone = string
idleCount = number
evictionStrategy = optional(string, "oldest_first")
})), [])
tags = optional(map(string), {})
}), {})
}), {})
pool = optional(object({
memory_size = optional(number, 512)
timeout = optional(number, 60)
reserved_concurrent_executions = optional(number, 1)
config = optional(list(object({
schedule_expression = string
schedule_expression_timezone = optional(string)
size = number
})), [])
include_busy_runners = optional(bool, false)
runner_owner = optional(string, null)
tags = optional(map(string), {})
}), {})
}), {})
job_retry = optional(object({
enabled = optional(bool, false)
delay_in_seconds = optional(number, 300)
delay_backoff = optional(number, 2)
max_attempts = optional(number, 1)
tags = optional(map(string), {})
lambda = optional(object({
memory_size = optional(number, 256)
reserved_concurrent_executions = optional(number, null)
timeout = optional(number, 30)
}), {})
}), {})
}), null)
scale_set = optional(object({
name = string
runner = optional(object({
min_runners = optional(number, 0)
max_runners = optional(number, 10)
boot_time_in_minutes = optional(number, 10)
}), {})
}), null)
})
| n/a | yes | | [prefix](#input\_prefix) | The prefix used for naming resources. | `string` | `"github-actions"` | no | | [runner](#input\_runner) | Provider-neutral GitHub runner configuration.

- `os`: Runner operating system. Supported values are `linux`, `osx`, and `windows`.
- `architecture`: Runner distribution architecture, such as `x64` or `arm64`.
- `disable_default_labels`: Prevents GitHub's default self-hosted, operating-system, and architecture labels from being registered.
- `labels`: Complete set of labels supplied to the control-plane functions.
- `group_name`: GitHub runner group used during registration.
- `name_prefix`: Prefix added to registered runner names.
- `run_as_root`: Runs the runner service as root when supported by the compute provider.
- `run_as`: Operating-system user used when `run_as_root` is false.
- `auto_update_disabled`: Disables the GitHub runner application's built-in updater.
- `tags`: Additional tags for common runner resources, currently the managed runner IAM role. These override module-level `tags` with the same key.
- `hooks.job_started`: Script content installed as the runner job-started hook.
- `hooks.job_completed`: Script content installed as the runner job-completed hook.
- `iam.role.arn`: ARN of an externally managed runner role. When set, this module does not create or modify that role.
- `iam.managed_policy_arns`: Named managed-policy ARNs attached to the module-managed runner role.
- `iam.additional_trust_policy_json`: Optional IAM policy document merged with the selected compute provider's default runner-role trust policy.
- `iam.path`: IAM path for the module-managed runner role. Defaults to a path derived from `prefix`.
- `iam.permissions_boundary`: Permissions-boundary ARN for the module-managed runner role. |
object({
os = optional(string, "linux")
architecture = optional(string, "x64")
disable_default_labels = optional(bool, false)
labels = list(string)
group_name = optional(string, "Default")
name_prefix = optional(string, "")
run_as_root = optional(bool, false)
run_as = optional(string, "ec2-user")
auto_update_disabled = optional(bool, false)
tags = optional(map(string), {})
hooks = optional(object({
job_started = optional(string, "")
job_completed = optional(string, "")
}), {})
iam = optional(object({
role = optional(object({
arn = string
}), null)
managed_policy_arns = optional(map(string), {})
additional_trust_policy_json = optional(string, null)
path = optional(string, null)
permissions_boundary = optional(string, null)
}), {})
})
| n/a | yes | -| [storage\_provider](#input\_storage\_provider) | Parameter Store paths, encryption, tag scopes, and housekeeper configuration.

- `storage_provider.aws.ssm.paths.root`: Root Parameter Store path for this runner configuration.
- `storage_provider.aws.ssm.paths.tokens`: Path segment under `paths.root` used for registration tokens and just-in-time configuration.
- `storage_provider.aws.ssm.paths.config`: Path segment under `paths.root` used for persistent runner configuration.
- `storage_provider.aws.ssm.kms_key_id`: Optional customer-managed KMS key ARN used by control-plane IAM policies to decrypt shared GitHub App parameters. The ARN may be unknown until apply; null omits the provider-owned KMS statements. It does not select encryption for runtime-created runner parameters.
- `storage_provider.aws.ssm.tags`: Shared tags for SSM-related resources. These override module-level `tags` and are inherited by parameter and housekeeper resources.
- `storage_provider.aws.ssm.parameters.max_concurrent_invocations`: Expected number of concurrent scale-up and pool Lambda invocations writing to Parameter Store. Each invocation paces its writes to a share of the account-wide write-rate limit. The default is `1`.
- `storage_provider.aws.ssm.parameters.max_writes_per_second`: Parameter Store write rate to pace against, in writes per second. AWS documents a `PutParameter` quota of 3 TPS per account and Region (10 TPS with higher throughput enabled). The default of 40 keeps the previous pacing; lower it if `PutParameter` calls are throttled.
- `storage_provider.aws.ssm.parameters.tags`: Tags for Terraform-managed runner configuration parameters and temporary parameters created by the scale-up and pool Lambdas. These override module-level and `storage_provider.aws.ssm.tags` values with the same key.
- `storage_provider.aws.ssm.housekeeper.schedule_expression`: EventBridge schedule expression that invokes the SSM housekeeper.
- `storage_provider.aws.ssm.housekeeper.state`: EventBridge rule state, such as `ENABLED` or `DISABLED`.
- `storage_provider.aws.ssm.housekeeper.tags`: Tags for housekeeper resources, including the Lambda function, log group, EventBridge rule, and IAM role. These override module-level, `storage_provider.aws.ssm.tags`, shared Lambda, and shared log tags when keys conflict.
- `storage_provider.aws.ssm.housekeeper.lambda.artifact`: Component-owned SSM-housekeeper artifact selection. Set at most one of `zip` or `s3`; when neither is selected, the module uses its packaged runner control-plane archive. This selector does not inherit an orchestration-provider artifact.
- `storage_provider.aws.ssm.housekeeper.lambda.artifact.zip`: Optional local path to the SSM-housekeeper Lambda archive.
- `storage_provider.aws.ssm.housekeeper.lambda.artifact.s3`: Optional object key and version in the shared `lambda.artifact.s3.bucket`. Selecting S3 requires that common bucket.
- `storage_provider.aws.ssm.housekeeper.lambda.artifact.s3.key`: Object key of the SSM-housekeeper Lambda archive.
- `storage_provider.aws.ssm.housekeeper.lambda.artifact.s3.object_version`: Optional object version of the SSM-housekeeper Lambda archive.
- `storage_provider.aws.ssm.housekeeper.lambda.memory_size`: Memory allocated to the SSM housekeeper Lambda in MB.
- `storage_provider.aws.ssm.housekeeper.lambda.timeout`: SSM housekeeper Lambda timeout in seconds.
- `storage_provider.aws.ssm.housekeeper.config.tokenPath`: Parameter Store token path cleaned by the housekeeper. When omitted, the configured runner token path is used.
- `storage_provider.aws.ssm.housekeeper.config.minimumDaysOld`: Minimum parameter age in days before deletion is allowed.
- `storage_provider.aws.ssm.housekeeper.config.dryRun`: Reports eligible parameters without deleting them when true. |
object({
aws = object({
ssm = object({
paths = object({
root = string
tokens = string
config = string
})
kms_key_id = optional(string, null)
tags = optional(map(string), {})
parameters = optional(object({
tags = optional(map(string), {})
max_concurrent_invocations = optional(number, 1)
max_writes_per_second = optional(number, 40)
}), {})
housekeeper = optional(object({
schedule_expression = optional(string, "rate(1 day)")
state = optional(string, "ENABLED")
tags = optional(map(string), {})
lambda = optional(object({
artifact = optional(object({
zip = optional(string, null)
s3 = optional(object({
key = string
object_version = optional(string, null)
}), null)
}), {})
memory_size = optional(number, 512)
timeout = optional(number, 60)
}), {})
config = optional(object({
tokenPath = optional(string)
minimumDaysOld = optional(number, 1)
dryRun = optional(bool, false)
}), {})
}), {})
})
})
})
| n/a | yes | +| [storage\_provider](#input\_storage\_provider) | Parameter Store paths, encryption, tag scopes, and housekeeper configuration.

- `storage_provider.aws.ssm.paths.root`: Root Parameter Store path for this runner configuration.
- `storage_provider.aws.ssm.paths.tokens`: Path segment under `paths.root` used for registration tokens and just-in-time configuration.
- `storage_provider.aws.ssm.paths.config`: Path segment under `paths.root` used for persistent runner configuration.
- `storage_provider.aws.ssm.kms_key_id`: Optional customer-managed KMS key ARN used by control-plane IAM policies to decrypt shared GitHub App parameters. The ARN may be unknown until apply; null omits the provider-owned KMS statements. It does not select encryption for runtime-created runner parameters.
- `storage_provider.aws.ssm.tags`: Shared tags for SSM-related resources. These override module-level `tags` and are inherited by parameter and housekeeper resources.
- `storage_provider.aws.ssm.parameters.max_concurrent_invocations`: Expected number of concurrent scale-up and pool Lambda invocations writing to Parameter Store. Each invocation paces its writes to a share of the account-wide write-rate limit. The default is `1`.
- `storage_provider.aws.ssm.parameters.max_writes_per_second`: Parameter Store write rate to pace against, in writes per second. AWS documents a `PutParameter` quota of 3 TPS per account and Region (10 TPS with higher throughput enabled). The default of 40 keeps the previous pacing; lower it if `PutParameter` calls are throttled.
- `storage_provider.aws.ssm.parameters.tags`: Tags for Terraform-managed runner configuration parameters and temporary parameters created by the scale-up and pool Lambdas. These override module-level and `storage_provider.aws.ssm.tags` values with the same key.
- `storage_provider.aws.ssm.housekeeper.schedule_expression`: EventBridge schedule expression that invokes the SSM housekeeper.
- `storage_provider.aws.ssm.housekeeper.state`: EventBridge rule state, such as `ENABLED` or `DISABLED`.
- `storage_provider.aws.ssm.housekeeper.tags`: Tags for housekeeper resources, including the Lambda function, log group, EventBridge rule, and IAM role. These override module-level, `storage_provider.aws.ssm.tags`, shared Lambda, and shared log tags when keys conflict.
- `storage_provider.aws.ssm.housekeeper.lambda.artifact`: Component-owned SSM-housekeeper artifact selection. Set at most one of `zip` or `s3`; when neither is selected, the module uses its packaged runner control-plane archive. This selector does not inherit an orchestration-provider artifact.
- `storage_provider.aws.ssm.housekeeper.lambda.artifact.zip`: Optional local path to the SSM-housekeeper Lambda archive.
- `storage_provider.aws.ssm.housekeeper.lambda.artifact.s3`: Optional object key and version in the shared `lambda.artifact.s3.bucket`. Selecting S3 requires that common bucket.
- `storage_provider.aws.ssm.housekeeper.lambda.artifact.s3.key`: Object key of the SSM-housekeeper Lambda archive.
- `storage_provider.aws.ssm.housekeeper.lambda.artifact.s3.object_version`: Optional object version of the SSM-housekeeper Lambda archive.
- `storage_provider.aws.ssm.housekeeper.lambda.memory_size`: Memory allocated to the SSM housekeeper Lambda in MB.
- `storage_provider.aws.ssm.housekeeper.lambda.timeout`: SSM housekeeper Lambda timeout in seconds.
- `storage_provider.aws.ssm.housekeeper.config.tokenPath`: Parameter Store token path cleaned by the housekeeper. When omitted, the configured runner token path is used.
- `storage_provider.aws.ssm.housekeeper.config.minimumDaysOld`: Minimum parameter age in days before deletion is allowed.
- `storage_provider.aws.ssm.housekeeper.config.dryRun`: Reports eligible parameters without deleting them when true.
- `storage_provider.type`: Selected runner-config storage provider, `aws_ssm` (default) or `aws_dynamodb`.
- `storage_provider.scale_up`, `scale_down`, `pool`, `job_retry`: Provider-owned control-plane environment variables and IAM policy fragments, supplied by the selected storage provider.
- `storage_provider.runner`: Runner-side DynamoDB locators and IAM policy, required when `type` is `aws_dynamodb`. |
object({
aws = object({
ssm = object({
paths = object({
root = string
tokens = string
config = string
})
kms_key_id = optional(string, null)
tags = optional(map(string), {})
parameters = optional(object({
tags = optional(map(string), {})
max_concurrent_invocations = optional(number, 1)
max_writes_per_second = optional(number, 40)
}), {})
housekeeper = optional(object({
schedule_expression = optional(string, "rate(1 day)")
state = optional(string, "ENABLED")
tags = optional(map(string), {})
lambda = optional(object({
artifact = optional(object({
zip = optional(string, null)
s3 = optional(object({
key = string
object_version = optional(string, null)
}), null)
}), {})
memory_size = optional(number, 512)
timeout = optional(number, 60)
}), {})
config = optional(object({
tokenPath = optional(string)
minimumDaysOld = optional(number, 1)
dryRun = optional(bool, false)
}), {})
}), {})
})
})
type = optional(string, "aws_ssm")
scale_up = optional(object({
environment_variables = optional(map(string), {})
iam_policy_json = optional(string, null)
}), {})
scale_down = optional(object({
environment_variables = optional(map(string), {})
iam_policy_json = optional(string, null)
}), {})
pool = optional(object({
environment_variables = optional(map(string), {})
iam_policy_json = optional(string, null)
}), {})
job_retry = optional(object({
environment_variables = optional(map(string), {})
iam_policy_json = optional(string, null)
}), {})
runner = optional(object({
config_table_name = optional(string, null)
runner_state_table_name = optional(string, null)
scope = optional(string, null)
iam_policy_json = optional(string, null)
}), {})
})
| n/a | yes | | [tags](#input\_tags) | Base tags added to taggable resources created by this runner configuration. Shared, component, and compute-provider tag maps override matching keys within their documented resource scopes. | `map(string)` | `{}` | no | ## Outputs diff --git a/modules/webhook/README.md b/modules/webhook/README.md index 6488687bab..6a9af3ea53 100644 --- a/modules/webhook/README.md +++ b/modules/webhook/README.md @@ -91,7 +91,7 @@ yarn run dist | [role\_path](#input\_role\_path) | The path that will be added to the role; if not set, the environment name will be used. | `string` | `null` | no | | [role\_permissions\_boundary](#input\_role\_permissions\_boundary) | Permissions boundary that will be added to the created role for the lambda. | `string` | `null` | no | | [runner\_matcher\_config](#input\_runner\_matcher\_config) | SQS queue to publish accepted build events based on the runner type. `computeProvider` defaults to `ec2`; EC2 is the only provider currently implemented. When exact match is disabled the webhook accepts the event if one of the workflow job labels is part of the matcher. The priority defines the order the matchers are applied. Optional `matcherConfig.enableDynamicLabels` and `matcherConfig.awsDynamicLabelsPolicy` are evaluated by the dispatcher to gate provider dynamic labels per runner. The policy supports `allowed_keys = []`, `blocked_keys = []` (cannot be used together with `allowed_keys`), and `restricted_keys = { = { allowed = [globs], denied = [globs], max = number|string } }`; keys use the provider dynamic label suffix form, for example `instance-type` for `ghr-ec2-instance-type`. |
map(object({
arn = string
id = string
computeProvider = optional(string, "ec2")
matcherConfig = object({
labelMatchers = list(list(string))
exactMatch = bool
bidirectionalLabelMatch = optional(bool, false)
priority = optional(number, 999)
enableDynamicLabels = optional(bool, false)
awsDynamicLabelsPolicy = optional(object({
allowed_keys = optional(list(string), [])
blocked_keys = optional(list(string), [])
restricted_keys = optional(map(object({
allowed = optional(list(string), [])
denied = optional(list(string), [])
max = optional(string, null)
})), {})
}), null)
})
}))
| n/a | yes | -| [storage\_provider](#input\_storage\_provider) | Storage-provider configuration used by the webhook resources. |
object({
aws = object({
kms_key_id = optional(string, null)
ssm = object({
paths = object({
root = string
webhook = string
})
})
})
})
| n/a | yes | +| [storage\_provider](#input\_storage\_provider) | Storage-provider configuration used by the webhook resources.

- `type`: Selected runner-config storage provider, `aws_ssm` (default) or `aws_dynamodb`.
- `aws.kms_key_id` / `aws.ssm.paths`: Parameter Store settings used when `type` is `aws_ssm`.
- `direct`: Environment variables and optional IAM policy for the direct webhook Lambda.
- `eventbridge`: Environment variables and optional IAM policies for the EventBridge webhook and dispatcher Lambdas. |
object({
type = optional(string, "aws_ssm")
aws = object({
kms_key_id = optional(string, null)
ssm = object({
paths = object({
root = string
webhook = string
})
})
})
direct = optional(object({
environment_variables = optional(map(string), {})
iam_policy_json = optional(string, null)
}), {})
eventbridge = optional(object({
webhook = optional(object({
environment_variables = optional(map(string), {})
iam_policy_json = optional(string, null)
}), {})
dispatcher = optional(object({
environment_variables = optional(map(string), {})
iam_policy_json = optional(string, null)
}), {})
}), {})
})
| n/a | yes | | [tags](#input\_tags) | Map of tags that will be added to created resources. By default resources will be tagged with name and environment. | `map(string)` | `{}` | no | | [tracing\_config](#input\_tracing\_config) | Configuration for lambda tracing. |
object({
mode = optional(string, null)
capture_http_requests = optional(bool, false)
capture_error = optional(bool, false)
})
| `{}` | no | | [webhook\_lambda\_apigateway\_access\_log\_settings](#input\_webhook\_lambda\_apigateway\_access\_log\_settings) | Access log settings for webhook API gateway. |
object({
destination_arn = string
format = string
})
| `null` | no | diff --git a/modules/webhook/direct/README.md b/modules/webhook/direct/README.md index cad59b502b..4e6dc1000c 100644 --- a/modules/webhook/direct/README.md +++ b/modules/webhook/direct/README.md @@ -40,7 +40,7 @@ No modules. | Name | Description | Type | Default | Required | |------|-------------|------|---------|:--------:| -| [config](#input\_config) | Configuration object for all variables. |
object({
prefix = string
archive = optional(object({
enable = optional(bool, true)
retention_days = optional(number, 7)
}), {})
tags = optional(map(string), {})

lambda_subnet_ids = optional(list(string), [])
lambda_security_group_ids = optional(list(string), [])
sqs_job_queues_arns = list(string)
lambda_zip = optional(string, null)
lambda_memory_size = optional(number, 256)
lambda_timeout = optional(number, 10)
role_permissions_boundary = optional(string, null)
role_path = optional(string, null)
logging_retention_in_days = optional(number, 180)
logging_kms_key_id = optional(string, null)
log_class = optional(string, "STANDARD")
lambda_s3_bucket = optional(string, null)
lambda_s3_key = optional(string, null)
lambda_s3_object_version = optional(string, null)
lambda_apigateway_access_log_settings = optional(object({
destination_arn = string
format = string
}), null)
repository_white_list = optional(list(string), [])
queue_selection_strategy = optional(string, "first")
storage_provider = object({
aws = object({
ssm = object({
kms_key_id = optional(string, null)
})
})
})
log_level = optional(string, "info")
lambda_runtime = optional(string, "nodejs24.x")
aws_partition = optional(string, "aws")
lambda_architecture = optional(string, "arm64")
github_app_parameters = object({
webhook_secret = map(string)
})
tracing_config = optional(object({
mode = optional(string, null)
capture_http_requests = optional(bool, false)
capture_error = optional(bool, false)
}), {})
lambda_tags = optional(map(string), {})
api_gw_source_arn = string
ssm_parameter_runner_matcher_config = list(object({
name = string
arn = string
version = string
}))
ssm_parameter_runner_matcher_config_arn_pattern = string
})
| n/a | yes | +| [config](#input\_config) | Configuration object for all variables. |
object({
prefix = string
archive = optional(object({
enable = optional(bool, true)
retention_days = optional(number, 7)
}), {})
tags = optional(map(string), {})

lambda_subnet_ids = optional(list(string), [])
lambda_security_group_ids = optional(list(string), [])
sqs_job_queues_arns = list(string)
lambda_zip = optional(string, null)
lambda_memory_size = optional(number, 256)
lambda_timeout = optional(number, 10)
role_permissions_boundary = optional(string, null)
role_path = optional(string, null)
logging_retention_in_days = optional(number, 180)
logging_kms_key_id = optional(string, null)
log_class = optional(string, "STANDARD")
lambda_s3_bucket = optional(string, null)
lambda_s3_key = optional(string, null)
lambda_s3_object_version = optional(string, null)
lambda_apigateway_access_log_settings = optional(object({
destination_arn = string
format = string
}), null)
repository_white_list = optional(list(string), [])
queue_selection_strategy = optional(string, "first")
log_level = optional(string, "info")
lambda_runtime = optional(string, "nodejs24.x")
aws_partition = optional(string, "aws")
lambda_architecture = optional(string, "arm64")
github_app_parameters = object({
webhook_secret = map(string)
})
tracing_config = optional(object({
mode = optional(string, null)
capture_http_requests = optional(bool, false)
capture_error = optional(bool, false)
}), {})
lambda_tags = optional(map(string), {})
api_gw_source_arn = string
ssm_parameter_runner_matcher_config = list(object({
name = string
arn = string
version = string
}))
ssm_parameter_runner_matcher_config_arn_pattern = string
storage_provider = object({
type = optional(string, "aws_ssm")
aws = object({
ssm = object({
kms_key_id = optional(string, null)
})
})
environment_variables = optional(map(string), {})
iam_policy_json = optional(string, null)
})
})
| n/a | yes | ## Outputs diff --git a/modules/webhook/eventbridge/README.md b/modules/webhook/eventbridge/README.md index 9358ba99de..0168123951 100644 --- a/modules/webhook/eventbridge/README.md +++ b/modules/webhook/eventbridge/README.md @@ -54,7 +54,7 @@ No modules. | Name | Description | Type | Default | Required | |------|-------------|------|---------|:--------:| -| [config](#input\_config) | Configuration object for all variables. |
object({
prefix = string
archive = optional(object({
enable = optional(bool, true)
retention_days = optional(number, 7)
}), {})
tags = optional(map(string), {})

lambda_subnet_ids = optional(list(string), [])
lambda_security_group_ids = optional(list(string), [])
sqs_job_queues_arns = list(string)
lambda_zip = optional(string, null)
lambda_memory_size = optional(number, 256)
lambda_timeout = optional(number, 10)
role_permissions_boundary = optional(string, null)
role_path = optional(string, null)
logging_retention_in_days = optional(number, 180)
logging_kms_key_id = optional(string, null)
log_class = optional(string, "STANDARD")
lambda_s3_bucket = optional(string, null)
lambda_s3_key = optional(string, null)
lambda_s3_object_version = optional(string, null)
lambda_apigateway_access_log_settings = optional(object({
destination_arn = string
format = string
}), null)
repository_white_list = optional(list(string), [])
queue_selection_strategy = optional(string, "first")
storage_provider = object({
aws = object({
ssm = object({
kms_key_id = optional(string, null)
})
})
})
log_level = optional(string, "info")
lambda_runtime = optional(string, "nodejs24.x")
aws_partition = optional(string, "aws")
lambda_architecture = optional(string, "arm64")
github_app_parameters = object({
webhook_secret = map(string)
})
tracing_config = optional(object({
mode = optional(string, null)
capture_http_requests = optional(bool, false)
capture_error = optional(bool, false)
}), {})
lambda_tags = optional(map(string), {})
api_gw_source_arn = string
ssm_parameter_runner_matcher_config = list(object({
name = string
arn = string
version = string
}))
ssm_parameter_runner_matcher_config_arn_pattern = string
accept_events = optional(list(string), null)
})
| n/a | yes | +| [config](#input\_config) | Configuration object for all variables. |
object({
prefix = string
archive = optional(object({
enable = optional(bool, true)
retention_days = optional(number, 7)
}), {})
tags = optional(map(string), {})

lambda_subnet_ids = optional(list(string), [])
lambda_security_group_ids = optional(list(string), [])
sqs_job_queues_arns = list(string)
lambda_zip = optional(string, null)
lambda_memory_size = optional(number, 256)
lambda_timeout = optional(number, 10)
role_permissions_boundary = optional(string, null)
role_path = optional(string, null)
logging_retention_in_days = optional(number, 180)
logging_kms_key_id = optional(string, null)
log_class = optional(string, "STANDARD")
lambda_s3_bucket = optional(string, null)
lambda_s3_key = optional(string, null)
lambda_s3_object_version = optional(string, null)
lambda_apigateway_access_log_settings = optional(object({
destination_arn = string
format = string
}), null)
repository_white_list = optional(list(string), [])
queue_selection_strategy = optional(string, "first")
log_level = optional(string, "info")
lambda_runtime = optional(string, "nodejs24.x")
aws_partition = optional(string, "aws")
lambda_architecture = optional(string, "arm64")
github_app_parameters = object({
webhook_secret = map(string)
})
tracing_config = optional(object({
mode = optional(string, null)
capture_http_requests = optional(bool, false)
capture_error = optional(bool, false)
}), {})
lambda_tags = optional(map(string), {})
api_gw_source_arn = string
ssm_parameter_runner_matcher_config = list(object({
name = string
arn = string
version = string
}))
ssm_parameter_runner_matcher_config_arn_pattern = string
accept_events = optional(list(string), null)
storage_provider = object({
type = optional(string, "aws_ssm")
aws = object({
ssm = object({
kms_key_id = optional(string, null)
})
})
webhook = optional(object({
environment_variables = optional(map(string), {})
iam_policy_json = optional(string, null)
}), {})
dispatcher = optional(object({
environment_variables = optional(map(string), {})
iam_policy_json = optional(string, null)
}), {})
})
})
| n/a | yes | ## Outputs