Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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' });
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
type RunnerConfigStore,
type GitHubAppCredentialsStore,
type RunnerGroupCacheStore,
type RunnerConfigRecord,
} from '@aws-github-runner/storage-providers';
import { Octokit } from '@octokit/rest';

Expand All @@ -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<void>;
}

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}`,
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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),
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ declare global {
| 'prioritized';
SCALE_ERRORS: string;
ENABLE_ON_DEMAND_FAILOVER_FOR_ERRORS: string;
EC2_INSTANCE_ARN_PREFIX: string | undefined;
}
}
}
1 change: 1 addition & 0 deletions lambdas/libs/compute-providers/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>;
}

Expand Down
21 changes: 21 additions & 0 deletions lambdas/libs/storage-providers/aws/dynamodb/client.ts
Original file line number Diff line number Diff line change
@@ -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;
}
37 changes: 37 additions & 0 deletions lambdas/libs/storage-providers/aws/dynamodb/durable-config.ts
Original file line number Diff line number Diff line change
@@ -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<string> {
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;
}
13 changes: 13 additions & 0 deletions lambdas/libs/storage-providers/aws/dynamodb/environment.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export {};

declare global {
namespace NodeJS {
interface ProcessEnv {
RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME?: 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;
}
}
}
29 changes: 29 additions & 0 deletions lambdas/libs/storage-providers/aws/dynamodb/environment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
type DynamoDbEnvironmentVariable =
| 'RUNNER_CONFIG_DYNAMODB_CONFIG_TABLE_NAME'
| '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 {
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;
}
Original file line number Diff line number Diff line change
@@ -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);
});
});
Loading
Loading