mirror of
https://github.com/game-ci/unity-builder.git
synced 2026-06-01 06:16:14 -07:00
Compare commits
5 Commits
feature/ci
...
feature/pr
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e0e7b225a1 | ||
|
|
b9f70d35a1 | ||
|
|
1f3affe097 | ||
|
|
7f895304f4 | ||
|
|
e4c156e7b0 |
73
action.yml
73
action.yml
@@ -182,8 +182,8 @@ inputs:
|
||||
required: false
|
||||
default: ''
|
||||
description:
|
||||
'[Orchestrator] Run a custom job instead of the standard build automation for orchestrator (in yaml format with
|
||||
the keys image, secrets (name, value object array), command line string)'
|
||||
'[Orchestrator] Run a custom job instead of the standard build automation for orchestrator (in yaml format with the
|
||||
keys image, secrets (name, value object array), command line string)'
|
||||
awsStackName:
|
||||
default: 'game-ci'
|
||||
required: false
|
||||
@@ -194,6 +194,15 @@ inputs:
|
||||
description:
|
||||
'[Orchestrator] Either local, k8s or aws can be used to run builds on a remote cluster. Additional parameters must
|
||||
be configured.'
|
||||
secretSource:
|
||||
default: ''
|
||||
required: false
|
||||
description:
|
||||
'[Orchestrator] Premade secret source for pulling build secrets. Supported values: aws-secrets-manager,
|
||||
aws-parameter-store, gcp-secret-manager, azure-key-vault, hashicorp-vault, hashicorp-vault-kv1,
|
||||
vault (alias for hashicorp-vault), env. Can also be a custom shell command with {0} placeholder
|
||||
for the key, or a path to a YAML file defining custom sources. Takes precedence over
|
||||
inputPullCommand when set.'
|
||||
resourceTracking:
|
||||
default: 'false'
|
||||
required: false
|
||||
@@ -279,66 +288,6 @@ inputs:
|
||||
description:
|
||||
'[Orchestrator] Specifies the repo for the unity builder. Useful if you forked the repo for testing, features, or
|
||||
fixes.'
|
||||
remotePowershellHost:
|
||||
default: ''
|
||||
required: false
|
||||
description: '[Orchestrator] Remote PowerShell host (hostname or IP) for the remote-powershell provider'
|
||||
remotePowershellCredential:
|
||||
default: ''
|
||||
required: false
|
||||
description: '[Orchestrator] Remote PowerShell credential (username:password or certificate path)'
|
||||
remotePowershellTransport:
|
||||
default: 'wsman'
|
||||
required: false
|
||||
description: '[Orchestrator] Remote PowerShell transport protocol (wsman or ssh)'
|
||||
githubActionsRepo:
|
||||
default: ''
|
||||
required: false
|
||||
description: '[Orchestrator] Target repository (owner/repo) for the github-actions provider'
|
||||
githubActionsWorkflow:
|
||||
default: ''
|
||||
required: false
|
||||
description: '[Orchestrator] Workflow filename or ID to dispatch for the github-actions provider'
|
||||
githubActionsToken:
|
||||
default: ''
|
||||
required: false
|
||||
description: '[Orchestrator] PAT with actions:write scope for the github-actions provider'
|
||||
githubActionsRef:
|
||||
default: 'main'
|
||||
required: false
|
||||
description: '[Orchestrator] Branch/ref to run the workflow on for the github-actions provider'
|
||||
gitlabProjectId:
|
||||
default: ''
|
||||
required: false
|
||||
description: '[Orchestrator] GitLab project ID or URL-encoded path for the gitlab-ci provider'
|
||||
gitlabTriggerToken:
|
||||
default: ''
|
||||
required: false
|
||||
description: '[Orchestrator] Pipeline trigger token for the gitlab-ci provider'
|
||||
gitlabApiUrl:
|
||||
default: 'https://gitlab.com'
|
||||
required: false
|
||||
description: '[Orchestrator] GitLab API URL (for self-hosted instances) for the gitlab-ci provider'
|
||||
gitlabRef:
|
||||
default: 'main'
|
||||
required: false
|
||||
description: '[Orchestrator] Branch/ref to trigger the pipeline on for the gitlab-ci provider'
|
||||
ansibleInventory:
|
||||
default: ''
|
||||
required: false
|
||||
description: '[Orchestrator] Path to Ansible inventory file or dynamic inventory script'
|
||||
ansiblePlaybook:
|
||||
default: ''
|
||||
required: false
|
||||
description: '[Orchestrator] Path to Ansible playbook for Unity builds'
|
||||
ansibleExtraVars:
|
||||
default: ''
|
||||
required: false
|
||||
description: '[Orchestrator] Additional Ansible variables as JSON'
|
||||
ansibleVaultPassword:
|
||||
default: ''
|
||||
required: false
|
||||
description: '[Orchestrator] Path to Ansible vault password file'
|
||||
|
||||
outputs:
|
||||
volume:
|
||||
|
||||
1290
dist/index.js
generated
vendored
1290
dist/index.js
generated
vendored
File diff suppressed because it is too large
Load Diff
2
dist/index.js.map
generated
vendored
2
dist/index.js.map
generated
vendored
File diff suppressed because one or more lines are too long
@@ -107,29 +107,6 @@ class BuildParameters {
|
||||
public unityHubVersionOnMac!: string;
|
||||
public dockerWorkspacePath!: string;
|
||||
|
||||
// Remote PowerShell provider
|
||||
public remotePowershellHost!: string;
|
||||
public remotePowershellCredential!: string;
|
||||
public remotePowershellTransport!: string;
|
||||
|
||||
// GitHub Actions provider
|
||||
public githubActionsRepo!: string;
|
||||
public githubActionsWorkflow!: string;
|
||||
public githubActionsToken!: string;
|
||||
public githubActionsRef!: string;
|
||||
|
||||
// GitLab CI provider
|
||||
public gitlabProjectId!: string;
|
||||
public gitlabTriggerToken!: string;
|
||||
public gitlabApiUrl!: string;
|
||||
public gitlabRef!: string;
|
||||
|
||||
// Ansible provider
|
||||
public ansibleInventory!: string;
|
||||
public ansiblePlaybook!: string;
|
||||
public ansibleExtraVars!: string;
|
||||
public ansibleVaultPassword!: string;
|
||||
|
||||
public static shouldUseRetainedWorkspaceMode(buildParameters: BuildParameters) {
|
||||
return buildParameters.maxRetainedWorkspaces > 0 && Orchestrator.lockedWorkspace !== ``;
|
||||
}
|
||||
@@ -265,29 +242,6 @@ class BuildParameters {
|
||||
cacheUnityInstallationOnMac: Input.cacheUnityInstallationOnMac,
|
||||
unityHubVersionOnMac: Input.unityHubVersionOnMac,
|
||||
dockerWorkspacePath: Input.dockerWorkspacePath,
|
||||
|
||||
// Remote PowerShell provider
|
||||
remotePowershellHost: Input.remotePowershellHost,
|
||||
remotePowershellCredential: Input.remotePowershellCredential,
|
||||
remotePowershellTransport: Input.remotePowershellTransport,
|
||||
|
||||
// GitHub Actions provider
|
||||
githubActionsRepo: Input.githubActionsRepo,
|
||||
githubActionsWorkflow: Input.githubActionsWorkflow,
|
||||
githubActionsToken: Input.githubActionsToken,
|
||||
githubActionsRef: Input.githubActionsRef,
|
||||
|
||||
// GitLab CI provider
|
||||
gitlabProjectId: Input.gitlabProjectId,
|
||||
gitlabTriggerToken: Input.gitlabTriggerToken,
|
||||
gitlabApiUrl: Input.gitlabApiUrl,
|
||||
gitlabRef: Input.gitlabRef,
|
||||
|
||||
// Ansible provider
|
||||
ansibleInventory: Input.ansibleInventory,
|
||||
ansiblePlaybook: Input.ansiblePlaybook,
|
||||
ansibleExtraVars: Input.ansibleExtraVars,
|
||||
ansibleVaultPassword: Input.ansibleVaultPassword,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -282,82 +282,6 @@ class Input {
|
||||
return Input.getInput('skipActivation')?.toLowerCase() ?? 'false';
|
||||
}
|
||||
|
||||
// ### ### ###
|
||||
// Remote PowerShell provider
|
||||
// ### ### ###
|
||||
|
||||
static get remotePowershellHost(): string {
|
||||
return Input.getInput('remotePowershellHost') ?? '';
|
||||
}
|
||||
|
||||
static get remotePowershellCredential(): string {
|
||||
return Input.getInput('remotePowershellCredential') ?? '';
|
||||
}
|
||||
|
||||
static get remotePowershellTransport(): string {
|
||||
return Input.getInput('remotePowershellTransport') ?? 'wsman';
|
||||
}
|
||||
|
||||
// ### ### ###
|
||||
// GitHub Actions provider
|
||||
// ### ### ###
|
||||
|
||||
static get githubActionsRepo(): string {
|
||||
return Input.getInput('githubActionsRepo') ?? '';
|
||||
}
|
||||
|
||||
static get githubActionsWorkflow(): string {
|
||||
return Input.getInput('githubActionsWorkflow') ?? '';
|
||||
}
|
||||
|
||||
static get githubActionsToken(): string {
|
||||
return Input.getInput('githubActionsToken') ?? '';
|
||||
}
|
||||
|
||||
static get githubActionsRef(): string {
|
||||
return Input.getInput('githubActionsRef') ?? 'main';
|
||||
}
|
||||
|
||||
// ### ### ###
|
||||
// GitLab CI provider
|
||||
// ### ### ###
|
||||
|
||||
static get gitlabProjectId(): string {
|
||||
return Input.getInput('gitlabProjectId') ?? '';
|
||||
}
|
||||
|
||||
static get gitlabTriggerToken(): string {
|
||||
return Input.getInput('gitlabTriggerToken') ?? '';
|
||||
}
|
||||
|
||||
static get gitlabApiUrl(): string {
|
||||
return Input.getInput('gitlabApiUrl') ?? 'https://gitlab.com';
|
||||
}
|
||||
|
||||
static get gitlabRef(): string {
|
||||
return Input.getInput('gitlabRef') ?? 'main';
|
||||
}
|
||||
|
||||
// ### ### ###
|
||||
// Ansible provider
|
||||
// ### ### ###
|
||||
|
||||
static get ansibleInventory(): string {
|
||||
return Input.getInput('ansibleInventory') ?? '';
|
||||
}
|
||||
|
||||
static get ansiblePlaybook(): string {
|
||||
return Input.getInput('ansiblePlaybook') ?? '';
|
||||
}
|
||||
|
||||
static get ansibleExtraVars(): string {
|
||||
return Input.getInput('ansibleExtraVars') ?? '';
|
||||
}
|
||||
|
||||
static get ansibleVaultPassword(): string {
|
||||
return Input.getInput('ansibleVaultPassword') ?? '';
|
||||
}
|
||||
|
||||
public static ToEnvVarFormat(input: string) {
|
||||
if (input.toUpperCase() === input) {
|
||||
return input;
|
||||
|
||||
@@ -190,6 +190,10 @@ class OrchestratorOptions {
|
||||
return OrchestratorOptions.getInput('pullInputList')?.split(`,`) || [];
|
||||
}
|
||||
|
||||
static get secretSource(): string {
|
||||
return OrchestratorOptions.getInput('secretSource') || '';
|
||||
}
|
||||
|
||||
static get inputPullCommand(): string {
|
||||
const value = OrchestratorOptions.getInput('inputPullCommand');
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import * as core from '@actions/core';
|
||||
import Input from '../../input';
|
||||
import { GenericInputReader } from '../../input-readers/generic-input-reader';
|
||||
import OrchestratorOptions from './orchestrator-options';
|
||||
import { SecretSourceService, validateSecretKey } from '../services/secrets/secret-source-service';
|
||||
import OrchestratorLogger from '../services/core/orchestrator-logger';
|
||||
|
||||
const formatFunction = (value: string, arguments_: any[]) => {
|
||||
for (const element of arguments_) {
|
||||
@@ -13,8 +16,6 @@ const formatFunction = (value: string, arguments_: any[]) => {
|
||||
class OrchestratorQueryOverride {
|
||||
static queryOverrides: { [key: string]: string } | undefined;
|
||||
|
||||
// TODO accept premade secret sources or custom secret source definition yamls
|
||||
|
||||
public static query(key: string, alternativeKey: string) {
|
||||
if (OrchestratorQueryOverride.queryOverrides && OrchestratorQueryOverride.queryOverrides[key] !== undefined) {
|
||||
return OrchestratorQueryOverride.queryOverrides[key];
|
||||
@@ -49,14 +50,62 @@ class OrchestratorQueryOverride {
|
||||
throw new Error(`Should not be trying to run override query on ${query}`);
|
||||
}
|
||||
|
||||
return await GenericInputReader.Run(
|
||||
// Validate the query key before interpolating it into a shell command
|
||||
validateSecretKey(query);
|
||||
|
||||
const result = await GenericInputReader.Run(
|
||||
formatFunction(OrchestratorOptions.inputPullCommand, [{ key: 0, value: query }]),
|
||||
);
|
||||
|
||||
// Mask the fetched secret value so it does not appear in GitHub Actions logs
|
||||
if (result && result.trim().length > 0) {
|
||||
core.setSecret(result);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Populate query overrides using either:
|
||||
* 1. Premade/custom secret sources (via secretSource input), or
|
||||
* 2. Shell command (via inputPullCommand, legacy approach)
|
||||
*
|
||||
* The secretSource input takes precedence if set. It supports:
|
||||
* - Premade names: 'aws-secrets-manager', 'aws-parameter-store', 'gcp-secret-manager', 'azure-key-vault', 'env'
|
||||
* - Custom commands: any string containing {0} placeholder
|
||||
* - YAML file path: a path ending in .yml or .yaml containing custom source definitions
|
||||
*/
|
||||
public static async PopulateQueryOverrideInput() {
|
||||
const queries = OrchestratorOptions.pullInputList;
|
||||
OrchestratorQueryOverride.queryOverrides = {};
|
||||
|
||||
const secretSource = OrchestratorOptions.secretSource;
|
||||
|
||||
// Use SecretSourceService if secretSource is configured
|
||||
if (secretSource) {
|
||||
OrchestratorLogger.log(`Using secret source: ${secretSource}`);
|
||||
|
||||
// YAML file: load definitions and use the first source
|
||||
if (secretSource.endsWith('.yml') || secretSource.endsWith('.yaml')) {
|
||||
const definitions = SecretSourceService.loadFromYaml(secretSource);
|
||||
if (definitions.length > 0) {
|
||||
OrchestratorLogger.log(`Loaded ${definitions.length} secret source(s) from ${secretSource}`);
|
||||
for (const key of queries) {
|
||||
OrchestratorQueryOverride.queryOverrides[key] = await SecretSourceService.fetchSecret(definitions[0], key);
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Premade or custom command source
|
||||
const results = await SecretSourceService.fetchAll(secretSource, queries);
|
||||
Object.assign(OrchestratorQueryOverride.queryOverrides, results);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Legacy: use inputPullCommand if set
|
||||
for (const element of queries) {
|
||||
if (OrchestratorQueryOverride.shouldUseOverride(element)) {
|
||||
OrchestratorQueryOverride.queryOverrides[element] = await OrchestratorQueryOverride.queryOverride(element);
|
||||
|
||||
@@ -13,10 +13,6 @@ import OrchestratorEnvironmentVariable from './options/orchestrator-environment-
|
||||
import TestOrchestrator from './providers/test';
|
||||
import LocalOrchestrator from './providers/local';
|
||||
import LocalDockerOrchestrator from './providers/docker';
|
||||
import RemotePowershellProvider from './providers/remote-powershell';
|
||||
import GitHubActionsProvider from './providers/github-actions';
|
||||
import GitLabCIProvider from './providers/gitlab-ci';
|
||||
import AnsibleProvider from './providers/ansible';
|
||||
import loadProvider from './providers/provider-loader';
|
||||
import GitHub from '../github';
|
||||
import SharedWorkspaceLocking from './services/core/shared-workspace-locking';
|
||||
@@ -162,18 +158,6 @@ class Orchestrator {
|
||||
case 'local':
|
||||
Orchestrator.Provider = new LocalOrchestrator();
|
||||
break;
|
||||
case 'remote-powershell':
|
||||
Orchestrator.Provider = new RemotePowershellProvider(Orchestrator.buildParameters);
|
||||
break;
|
||||
case 'github-actions':
|
||||
Orchestrator.Provider = new GitHubActionsProvider(Orchestrator.buildParameters);
|
||||
break;
|
||||
case 'gitlab-ci':
|
||||
Orchestrator.Provider = new GitLabCIProvider(Orchestrator.buildParameters);
|
||||
break;
|
||||
case 'ansible':
|
||||
Orchestrator.Provider = new AnsibleProvider(Orchestrator.buildParameters);
|
||||
break;
|
||||
default:
|
||||
// Try to load provider using the dynamic loader for unknown providers
|
||||
try {
|
||||
|
||||
@@ -1,291 +0,0 @@
|
||||
import AnsibleProvider from '.';
|
||||
import BuildParameters from '../../../build-parameters';
|
||||
import { OrchestratorSystem } from '../../services/core/orchestrator-system';
|
||||
import OrchestratorLogger from '../../services/core/orchestrator-logger';
|
||||
import * as core from '@actions/core';
|
||||
|
||||
jest.mock('../../services/core/orchestrator-system');
|
||||
jest.mock('../../services/core/orchestrator-logger');
|
||||
jest.mock('@actions/core', () => ({
|
||||
info: jest.fn(),
|
||||
warning: jest.fn(),
|
||||
error: jest.fn(),
|
||||
setOutput: jest.fn(),
|
||||
getInput: jest.fn(() => ''),
|
||||
}));
|
||||
|
||||
const mockRun = OrchestratorSystem.Run as jest.MockedFunction<typeof OrchestratorSystem.Run>;
|
||||
const mockLog = OrchestratorLogger.log as jest.MockedFunction<typeof OrchestratorLogger.log>;
|
||||
const mockLogWarning = OrchestratorLogger.logWarning as jest.MockedFunction<typeof OrchestratorLogger.logWarning>;
|
||||
|
||||
function createBuildParameters(overrides: Partial<BuildParameters> = {}): BuildParameters {
|
||||
return {
|
||||
ansibleInventory: '/etc/ansible/hosts',
|
||||
ansiblePlaybook: '/playbooks/unity-build.yml',
|
||||
ansibleExtraVars: '',
|
||||
ansibleVaultPassword: '',
|
||||
...overrides,
|
||||
} as BuildParameters;
|
||||
}
|
||||
|
||||
describe('AnsibleProvider', () => {
|
||||
let provider: AnsibleProvider;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
provider = new AnsibleProvider(createBuildParameters());
|
||||
});
|
||||
|
||||
describe('constructor', () => {
|
||||
it('initializes with all provided parameters', () => {
|
||||
const params = createBuildParameters({
|
||||
ansibleInventory: '/custom/inventory',
|
||||
ansiblePlaybook: '/custom/playbook.yml',
|
||||
ansibleExtraVars: '{"key":"value"}',
|
||||
ansibleVaultPassword: '/vault/pass',
|
||||
});
|
||||
const p = new AnsibleProvider(params);
|
||||
expect(p).toBeDefined();
|
||||
});
|
||||
|
||||
it('handles missing optional parameters gracefully', () => {
|
||||
const params = createBuildParameters({
|
||||
ansiblePlaybook: undefined,
|
||||
ansibleExtraVars: undefined,
|
||||
ansibleVaultPassword: undefined,
|
||||
});
|
||||
const p = new AnsibleProvider(params);
|
||||
expect(p).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('setupWorkflow', () => {
|
||||
it('verifies ansible binary, ansible-playbook binary, and inventory exist', async () => {
|
||||
mockRun.mockResolvedValueOnce('ansible [core 2.14.0]'); // ansible --version
|
||||
mockRun.mockResolvedValueOnce('/usr/bin/ansible-playbook'); // ansible-playbook check
|
||||
mockRun.mockResolvedValueOnce(''); // test -e inventory
|
||||
|
||||
await provider.setupWorkflow('guid-123', createBuildParameters(), 'main', []);
|
||||
|
||||
expect(mockRun).toHaveBeenCalledTimes(3);
|
||||
expect(mockRun.mock.calls[0][0]).toContain('ansible --version');
|
||||
expect(mockRun.mock.calls[1][0]).toContain('ansible-playbook');
|
||||
expect(mockRun.mock.calls[2][0]).toContain('test -e "/etc/ansible/hosts"');
|
||||
expect(mockLog).toHaveBeenCalledWith(expect.stringContaining('ansible'));
|
||||
expect(mockLog).toHaveBeenCalledWith(expect.stringContaining('ansible-playbook binary verified'));
|
||||
});
|
||||
|
||||
it('throws when inventory is not configured', async () => {
|
||||
const params = createBuildParameters({ ansibleInventory: '' });
|
||||
provider = new AnsibleProvider(params);
|
||||
|
||||
await expect(provider.setupWorkflow('guid-123', params, 'main', [])).rejects.toThrow(
|
||||
'ansibleInventory is required',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when ansible binary is not found on PATH', async () => {
|
||||
mockRun.mockRejectedValueOnce(new Error('command not found: ansible'));
|
||||
|
||||
await expect(provider.setupWorkflow('guid-123', createBuildParameters(), 'main', [])).rejects.toThrow(
|
||||
'Ansible not found on PATH',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when ansible-playbook binary is not found', async () => {
|
||||
mockRun.mockResolvedValueOnce('ansible [core 2.14.0]'); // ansible version OK
|
||||
mockRun.mockRejectedValueOnce(new Error('command not found')); // ansible-playbook missing
|
||||
|
||||
await expect(provider.setupWorkflow('guid-123', createBuildParameters(), 'main', [])).rejects.toThrow(
|
||||
'ansible-playbook not found on PATH',
|
||||
);
|
||||
|
||||
expect(core.error).toHaveBeenCalledWith('ansible-playbook not found. Install Ansible or ensure it is in PATH.');
|
||||
});
|
||||
|
||||
it('throws when inventory file does not exist', async () => {
|
||||
mockRun.mockResolvedValueOnce('ansible [core 2.14.0]'); // ansible version OK
|
||||
mockRun.mockResolvedValueOnce('/usr/bin/ansible-playbook'); // ansible-playbook OK
|
||||
mockRun.mockRejectedValueOnce(new Error('test -e failed')); // inventory missing
|
||||
|
||||
await expect(provider.setupWorkflow('guid-123', createBuildParameters(), 'main', [])).rejects.toThrow(
|
||||
'Inventory not found: /etc/ansible/hosts',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('runTaskInWorkflow', () => {
|
||||
it('constructs ansible-playbook command with correct variables and returns output', async () => {
|
||||
mockRun.mockResolvedValueOnce('PLAY [build] *****\nok: [server1]\nPLAY RECAP');
|
||||
|
||||
const result = await provider.runTaskInWorkflow(
|
||||
'guid-run1',
|
||||
'unityci/editor:2021.3',
|
||||
'echo build',
|
||||
'/mount',
|
||||
'/workspace',
|
||||
[],
|
||||
[],
|
||||
);
|
||||
|
||||
expect(result).toContain('PLAY [build]');
|
||||
|
||||
const command = mockRun.mock.calls[0][0];
|
||||
expect(command).toContain('ansible-playbook');
|
||||
expect(command).toContain('-i "/etc/ansible/hosts"');
|
||||
expect(command).toContain('"/playbooks/unity-build.yml"');
|
||||
expect(command).toContain('--no-color');
|
||||
expect(command).toContain('build_guid');
|
||||
expect(command).toContain('guid-run1');
|
||||
expect(command).toContain('build_image');
|
||||
expect(command).toContain('unityci/editor:2021.3');
|
||||
expect(command).toContain('build_commands');
|
||||
expect(command).toContain('mount_dir');
|
||||
expect(command).toContain('working_dir');
|
||||
});
|
||||
|
||||
it('throws when playbook is not configured', async () => {
|
||||
const params = createBuildParameters({ ansiblePlaybook: '' });
|
||||
provider = new AnsibleProvider(params);
|
||||
|
||||
await expect(provider.runTaskInWorkflow('guid-nopb', 'img', 'cmd', '/m', '/w', [], [])).rejects.toThrow(
|
||||
'ansiblePlaybook is required',
|
||||
);
|
||||
});
|
||||
|
||||
it('passes environment variables as extra-vars in snake_case', async () => {
|
||||
mockRun.mockResolvedValueOnce('ok');
|
||||
|
||||
const env = [
|
||||
{ name: 'UNITY_LICENSE', value: 'lic-data' },
|
||||
{ name: 'BUILD_TARGET', value: 'Linux64' },
|
||||
];
|
||||
|
||||
await provider.runTaskInWorkflow('guid-env', 'img', 'cmd', '/m', '/w', env as any, []);
|
||||
|
||||
const command = mockRun.mock.calls[0][0];
|
||||
// Environment variable names are lowercased as Ansible variables
|
||||
expect(command).toContain('unity_license');
|
||||
expect(command).toContain('lic-data');
|
||||
expect(command).toContain('build_target');
|
||||
expect(command).toContain('Linux64');
|
||||
});
|
||||
|
||||
it('merges user-provided extra vars from JSON string', async () => {
|
||||
const params = createBuildParameters({
|
||||
ansibleExtraVars: JSON.stringify({ custom_var: 'custom_value', another: '42' }),
|
||||
});
|
||||
provider = new AnsibleProvider(params);
|
||||
mockRun.mockResolvedValueOnce('ok');
|
||||
|
||||
await provider.runTaskInWorkflow('guid-extra', 'img', 'cmd', '/m', '/w', [], []);
|
||||
|
||||
const command = mockRun.mock.calls[0][0];
|
||||
expect(command).toContain('custom_var');
|
||||
expect(command).toContain('custom_value');
|
||||
expect(command).toContain('another');
|
||||
});
|
||||
|
||||
it('logs warning when extra vars JSON is invalid but continues', async () => {
|
||||
const params = createBuildParameters({ ansibleExtraVars: 'not-valid-json{{{' });
|
||||
provider = new AnsibleProvider(params);
|
||||
mockRun.mockResolvedValueOnce('ok');
|
||||
|
||||
await provider.runTaskInWorkflow('guid-badjson', 'img', 'cmd', '/m', '/w', [], []);
|
||||
|
||||
expect(mockLogWarning).toHaveBeenCalledWith(expect.stringContaining('Failed to parse ansibleExtraVars'));
|
||||
});
|
||||
|
||||
it('includes vault password file flag when configured', async () => {
|
||||
const params = createBuildParameters({ ansibleVaultPassword: '/secure/vault-pass.txt' });
|
||||
provider = new AnsibleProvider(params);
|
||||
mockRun.mockResolvedValueOnce('ok');
|
||||
|
||||
await provider.runTaskInWorkflow('guid-vault', 'img', 'cmd', '/m', '/w', [], []);
|
||||
|
||||
const command = mockRun.mock.calls[0][0];
|
||||
expect(command).toContain('--vault-password-file "/secure/vault-pass.txt"');
|
||||
});
|
||||
|
||||
it('does not include vault password flag when not configured', async () => {
|
||||
mockRun.mockResolvedValueOnce('ok');
|
||||
|
||||
await provider.runTaskInWorkflow('guid-novault', 'img', 'cmd', '/m', '/w', [], []);
|
||||
|
||||
const command = mockRun.mock.calls[0][0];
|
||||
expect(command).not.toContain('--vault-password-file');
|
||||
});
|
||||
|
||||
it('prefixes secrets as environment variables in the command', async () => {
|
||||
mockRun.mockResolvedValueOnce('ok');
|
||||
|
||||
const secrets = [
|
||||
{ ParameterKey: 'key1', EnvironmentVariable: 'SECRET_TOKEN', ParameterValue: 'tok-abc' },
|
||||
{ ParameterKey: 'key2', EnvironmentVariable: 'DEPLOY_KEY', ParameterValue: 'dk-xyz' },
|
||||
];
|
||||
|
||||
await provider.runTaskInWorkflow('guid-secrets', 'img', 'cmd', '/m', '/w', [], secrets as any);
|
||||
|
||||
const command = mockRun.mock.calls[0][0];
|
||||
expect(command).toMatch(/^SECRET_TOKEN='tok-abc'/);
|
||||
expect(command).toContain("DEPLOY_KEY='dk-xyz'");
|
||||
expect(command).toContain('ansible-playbook');
|
||||
});
|
||||
|
||||
it('throws and logs warning when playbook execution fails', async () => {
|
||||
const execError = new Error('UNREACHABLE! Host unreachable');
|
||||
mockRun.mockRejectedValueOnce(execError);
|
||||
|
||||
await expect(provider.runTaskInWorkflow('guid-hostfail', 'img', 'cmd', '/m', '/w', [], [])).rejects.toThrow(
|
||||
'UNREACHABLE',
|
||||
);
|
||||
|
||||
expect(mockLogWarning).toHaveBeenCalledWith(expect.stringContaining('Playbook failed'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('cleanupWorkflow', () => {
|
||||
it('completes without error and logs cleanup message', async () => {
|
||||
await provider.cleanupWorkflow(createBuildParameters(), 'main', []);
|
||||
expect(mockLog).toHaveBeenCalledWith(expect.stringContaining('Cleanup complete'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('garbageCollect', () => {
|
||||
it('returns empty string (no-op)', async () => {
|
||||
const result = await provider.garbageCollect('', false, 0, false, false);
|
||||
expect(result).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('listResources', () => {
|
||||
it('returns inventory path as a resource when configured', async () => {
|
||||
const resources = await provider.listResources();
|
||||
|
||||
expect(resources).toHaveLength(1);
|
||||
expect(resources[0].Name).toBe('/etc/ansible/hosts');
|
||||
});
|
||||
|
||||
it('returns empty array when inventory is not configured', async () => {
|
||||
const params = createBuildParameters({ ansibleInventory: '' });
|
||||
provider = new AnsibleProvider(params);
|
||||
|
||||
const resources = await provider.listResources();
|
||||
expect(resources).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('listWorkflow', () => {
|
||||
it('returns empty array (not implemented)', async () => {
|
||||
const workflows = await provider.listWorkflow();
|
||||
expect(workflows).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('watchWorkflow', () => {
|
||||
it('returns empty string (not implemented)', async () => {
|
||||
const result = await provider.watchWorkflow();
|
||||
expect(result).toBe('');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,197 +0,0 @@
|
||||
import * as core from '@actions/core';
|
||||
import BuildParameters from '../../../build-parameters';
|
||||
import { OrchestratorSystem } from '../../services/core/orchestrator-system';
|
||||
import OrchestratorEnvironmentVariable from '../../options/orchestrator-environment-variable';
|
||||
import OrchestratorLogger from '../../services/core/orchestrator-logger';
|
||||
import { ProviderInterface } from '../provider-interface';
|
||||
import OrchestratorSecret from '../../options/orchestrator-secret';
|
||||
import { ProviderResource } from '../provider-resource';
|
||||
import { ProviderWorkflow } from '../provider-workflow';
|
||||
|
||||
/**
|
||||
* Ansible provider — executes Unity builds via Ansible playbooks
|
||||
* against managed inventory.
|
||||
*
|
||||
* Use case: Teams with existing Ansible infrastructure for server
|
||||
* management who want to leverage their inventory for build distribution.
|
||||
*/
|
||||
class AnsibleProvider implements ProviderInterface {
|
||||
private buildParameters: BuildParameters;
|
||||
private inventory: string;
|
||||
private playbook: string;
|
||||
private extraVariables: string;
|
||||
private vaultPassword: string;
|
||||
|
||||
constructor(buildParameters: BuildParameters) {
|
||||
this.buildParameters = buildParameters;
|
||||
this.inventory = buildParameters.ansibleInventory || '';
|
||||
this.playbook = buildParameters.ansiblePlaybook || '';
|
||||
this.extraVariables = buildParameters.ansibleExtraVars || '';
|
||||
this.vaultPassword = buildParameters.ansibleVaultPassword || '';
|
||||
}
|
||||
|
||||
async setupWorkflow(
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
buildGuid: string,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
buildParameters: BuildParameters,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
branchName: string,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
defaultSecretsArray: { ParameterKey: string; EnvironmentVariable: string; ParameterValue: string }[],
|
||||
): Promise<void> {
|
||||
OrchestratorLogger.log(`[Ansible] Setting up playbook execution`);
|
||||
|
||||
if (!this.inventory) {
|
||||
throw new Error('ansibleInventory is required for the ansible provider');
|
||||
}
|
||||
|
||||
// Verify ansible is available
|
||||
try {
|
||||
const version = await OrchestratorSystem.Run('ansible --version | head -1');
|
||||
OrchestratorLogger.log(`[Ansible] ${version.trim()}`);
|
||||
} catch (error: any) {
|
||||
throw new Error(`Ansible not found on PATH: ${error.message || error}`);
|
||||
}
|
||||
|
||||
// Verify ansible-playbook binary exists (may be separate from ansible)
|
||||
try {
|
||||
await OrchestratorSystem.Run('command -v ansible-playbook || which ansible-playbook || where ansible-playbook');
|
||||
OrchestratorLogger.log(`[Ansible] ansible-playbook binary verified`);
|
||||
} catch (error: any) {
|
||||
core.error('ansible-playbook not found. Install Ansible or ensure it is in PATH.');
|
||||
throw new Error(`ansible-playbook not found on PATH: ${error.message || error}`);
|
||||
}
|
||||
|
||||
// Verify inventory exists
|
||||
try {
|
||||
await OrchestratorSystem.Run(`test -e "${this.inventory}"`);
|
||||
} catch {
|
||||
throw new Error(`Inventory not found: ${this.inventory}`);
|
||||
}
|
||||
}
|
||||
|
||||
async runTaskInWorkflow(
|
||||
buildGuid: string,
|
||||
image: string,
|
||||
commands: string,
|
||||
mountdir: string,
|
||||
workingdir: string,
|
||||
environment: OrchestratorEnvironmentVariable[],
|
||||
secrets: OrchestratorSecret[],
|
||||
): Promise<string> {
|
||||
OrchestratorLogger.log(`[Ansible] Running playbook against inventory ${this.inventory}`);
|
||||
|
||||
if (!this.playbook) {
|
||||
throw new Error(
|
||||
'ansiblePlaybook is required — no default playbook is provided yet. ' +
|
||||
'Provide a playbook that accepts build_guid, build_image, build_commands, mount_dir, and working_dir variables.',
|
||||
);
|
||||
}
|
||||
|
||||
// Build extra-vars JSON
|
||||
// These use snake_case because they are Ansible variable names passed to playbooks
|
||||
const playbookVariables: Record<string, string> = {
|
||||
// eslint-disable-next-line camelcase
|
||||
build_guid: buildGuid,
|
||||
// eslint-disable-next-line camelcase
|
||||
build_image: image,
|
||||
// eslint-disable-next-line camelcase
|
||||
build_commands: commands,
|
||||
// eslint-disable-next-line camelcase
|
||||
mount_dir: mountdir,
|
||||
// eslint-disable-next-line camelcase
|
||||
working_dir: workingdir,
|
||||
};
|
||||
|
||||
for (const element of environment) {
|
||||
playbookVariables[element.name.toLowerCase()] = element.value;
|
||||
}
|
||||
|
||||
// Merge user-provided extra vars
|
||||
if (this.extraVariables) {
|
||||
try {
|
||||
const userVariables = JSON.parse(this.extraVariables);
|
||||
Object.assign(playbookVariables, userVariables);
|
||||
} catch {
|
||||
OrchestratorLogger.logWarning(`[Ansible] Failed to parse ansibleExtraVars as JSON, using as-is`);
|
||||
}
|
||||
}
|
||||
|
||||
const extraVariablesJson = JSON.stringify(playbookVariables).replace(/'/g, "'\\''");
|
||||
|
||||
// Build ansible-playbook command
|
||||
const commandParts = [
|
||||
'ansible-playbook',
|
||||
`-i "${this.inventory}"`,
|
||||
`"${this.playbook}"`,
|
||||
`-e '${extraVariablesJson}'`,
|
||||
'--no-color',
|
||||
];
|
||||
|
||||
if (this.vaultPassword) {
|
||||
commandParts.push(`--vault-password-file "${this.vaultPassword}"`);
|
||||
}
|
||||
|
||||
// Add secret variables as extra environment
|
||||
const environmentPrefix = secrets
|
||||
.map((secret) => `${secret.EnvironmentVariable}='${secret.ParameterValue}'`)
|
||||
.join(' ');
|
||||
|
||||
const fullCommand = environmentPrefix ? `${environmentPrefix} ${commandParts.join(' ')}` : commandParts.join(' ');
|
||||
|
||||
try {
|
||||
const output = await OrchestratorSystem.Run(fullCommand);
|
||||
OrchestratorLogger.log(`[Ansible] Playbook completed successfully`);
|
||||
|
||||
return output;
|
||||
} catch (error: any) {
|
||||
OrchestratorLogger.logWarning(`[Ansible] Playbook failed: ${error.message || error}`);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async cleanupWorkflow(
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
buildParameters: BuildParameters,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
branchName: string,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
defaultSecretsArray: { ParameterKey: string; EnvironmentVariable: string; ParameterValue: string }[],
|
||||
): Promise<void> {
|
||||
OrchestratorLogger.log(`[Ansible] Cleanup complete`);
|
||||
}
|
||||
|
||||
async garbageCollect(
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
filter: string,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
previewOnly: boolean,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
olderThan: Number,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
fullCache: boolean,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
baseDependencies: boolean,
|
||||
): Promise<string> {
|
||||
return '';
|
||||
}
|
||||
|
||||
async listResources(): Promise<ProviderResource[]> {
|
||||
if (!this.inventory) return [];
|
||||
|
||||
const resource = new ProviderResource();
|
||||
resource.Name = this.inventory;
|
||||
|
||||
return [resource];
|
||||
}
|
||||
|
||||
async listWorkflow(): Promise<ProviderWorkflow[]> {
|
||||
return [];
|
||||
}
|
||||
|
||||
async watchWorkflow(): Promise<string> {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
export default AnsibleProvider;
|
||||
@@ -1,333 +0,0 @@
|
||||
import GitHubActionsProvider from '.';
|
||||
import BuildParameters from '../../../build-parameters';
|
||||
import { OrchestratorSystem } from '../../services/core/orchestrator-system';
|
||||
import OrchestratorLogger from '../../services/core/orchestrator-logger';
|
||||
import * as core from '@actions/core';
|
||||
|
||||
jest.mock('../../services/core/orchestrator-system');
|
||||
jest.mock('../../services/core/orchestrator-logger');
|
||||
jest.mock('@actions/core', () => ({
|
||||
info: jest.fn(),
|
||||
warning: jest.fn(),
|
||||
error: jest.fn(),
|
||||
setOutput: jest.fn(),
|
||||
getInput: jest.fn(() => ''),
|
||||
}));
|
||||
|
||||
const mockRun = OrchestratorSystem.Run as jest.MockedFunction<typeof OrchestratorSystem.Run>;
|
||||
const mockLog = OrchestratorLogger.log as jest.MockedFunction<typeof OrchestratorLogger.log>;
|
||||
|
||||
function createBuildParameters(overrides: Partial<BuildParameters> = {}): BuildParameters {
|
||||
return {
|
||||
githubActionsRepo: 'owner/repo',
|
||||
githubActionsWorkflow: 'build.yml',
|
||||
githubActionsToken: 'ghp_test_token_123',
|
||||
githubActionsRef: 'main',
|
||||
...overrides,
|
||||
} as BuildParameters;
|
||||
}
|
||||
|
||||
// Override setTimeout to execute callbacks immediately so polling loops complete fast
|
||||
const originalSetTimeout = global.setTimeout;
|
||||
beforeAll(() => {
|
||||
global.setTimeout = ((fn: (...args: any[]) => void, _ms?: number, ...args: any[]) => {
|
||||
return originalSetTimeout(fn, 0, ...args);
|
||||
}) as any;
|
||||
});
|
||||
afterAll(() => {
|
||||
global.setTimeout = originalSetTimeout;
|
||||
});
|
||||
|
||||
describe('GitHubActionsProvider', () => {
|
||||
let provider: GitHubActionsProvider;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
provider = new GitHubActionsProvider(createBuildParameters());
|
||||
});
|
||||
|
||||
describe('constructor', () => {
|
||||
it('sets default ref to main when not specified', () => {
|
||||
const params = createBuildParameters({ githubActionsRef: undefined });
|
||||
const p = new GitHubActionsProvider(params);
|
||||
expect(p).toBeDefined();
|
||||
});
|
||||
|
||||
it('uses provided ref when specified', () => {
|
||||
const params = createBuildParameters({ githubActionsRef: 'develop' });
|
||||
const p = new GitHubActionsProvider(params);
|
||||
expect(p).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('setupWorkflow', () => {
|
||||
it('verifies workflow exists via gh api and logs success', async () => {
|
||||
mockRun.mockResolvedValueOnce('12345\n');
|
||||
|
||||
await provider.setupWorkflow('guid-123', createBuildParameters(), 'main', []);
|
||||
|
||||
expect(mockRun).toHaveBeenCalledTimes(1);
|
||||
const command = mockRun.mock.calls[0][0];
|
||||
expect(command).toContain('gh api repos/owner/repo/actions/workflows/build.yml');
|
||||
expect(command).toContain("--jq '.id'");
|
||||
expect(command).toContain('GH_TOKEN=ghp_test_token_123');
|
||||
expect(mockLog).toHaveBeenCalledWith(expect.stringContaining('Workflow verified'));
|
||||
});
|
||||
|
||||
it('throws when repo is not configured', async () => {
|
||||
const params = createBuildParameters({ githubActionsRepo: '' });
|
||||
provider = new GitHubActionsProvider(params);
|
||||
|
||||
await expect(provider.setupWorkflow('guid-123', params, 'main', [])).rejects.toThrow(
|
||||
'githubActionsRepo and githubActionsWorkflow are required',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when workflow is not configured', async () => {
|
||||
const params = createBuildParameters({ githubActionsWorkflow: '' });
|
||||
provider = new GitHubActionsProvider(params);
|
||||
|
||||
await expect(provider.setupWorkflow('guid-123', params, 'main', [])).rejects.toThrow(
|
||||
'githubActionsRepo and githubActionsWorkflow are required',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when token is missing', async () => {
|
||||
const params = createBuildParameters({ githubActionsToken: '' });
|
||||
provider = new GitHubActionsProvider(params);
|
||||
|
||||
await expect(provider.setupWorkflow('guid-123', params, 'main', [])).rejects.toThrow(
|
||||
'githubActionsToken is required',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws descriptive error when workflow verification fails', async () => {
|
||||
mockRun.mockRejectedValueOnce(new Error('Not Found'));
|
||||
|
||||
await expect(provider.setupWorkflow('guid-123', createBuildParameters(), 'main', [])).rejects.toThrow(
|
||||
'Failed to verify workflow build.yml in owner/repo',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('runTaskInWorkflow', () => {
|
||||
it('dispatches workflow with correct inputs and returns logs on success', async () => {
|
||||
// Dispatch succeeds
|
||||
mockRun.mockResolvedValueOnce('');
|
||||
// First poll finds the run
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ id: 99001, status: 'in_progress' }));
|
||||
// Status poll returns completed
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ status: 'completed', conclusion: 'success' }));
|
||||
// Log fetch succeeds
|
||||
mockRun.mockResolvedValueOnce('Build output log content here');
|
||||
|
||||
const result = await provider.runTaskInWorkflow(
|
||||
'guid-abc',
|
||||
'unityci/editor:2021.3',
|
||||
'echo build',
|
||||
'/mount',
|
||||
'/work',
|
||||
[],
|
||||
[],
|
||||
);
|
||||
|
||||
expect(result).toBe('Build output log content here');
|
||||
|
||||
// Verify dispatch command
|
||||
const dispatchCommand = mockRun.mock.calls[0][0];
|
||||
expect(dispatchCommand).toContain('dispatches');
|
||||
expect(dispatchCommand).toContain('-X POST');
|
||||
expect(dispatchCommand).toContain("ref='main'");
|
||||
|
||||
// Verify log fetch command
|
||||
const logCommand = mockRun.mock.calls[3][0];
|
||||
expect(logCommand).toContain('gh run view');
|
||||
expect(logCommand).toContain('--log');
|
||||
expect(logCommand).toContain('--repo owner/repo');
|
||||
});
|
||||
|
||||
it('base64 encodes commands in the inputs payload', async () => {
|
||||
mockRun.mockResolvedValueOnce(''); // dispatch
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ id: 100, status: 'completed' })); // run found
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ status: 'completed', conclusion: 'success' })); // status
|
||||
mockRun.mockResolvedValueOnce('logs'); // logs
|
||||
|
||||
await provider.runTaskInWorkflow('guid-1', 'image:latest', 'echo hello && build', '/mnt', '/w', [], []);
|
||||
|
||||
const dispatchCommand = mockRun.mock.calls[0][0];
|
||||
const expectedB64 = Buffer.from('echo hello && build').toString('base64');
|
||||
expect(dispatchCommand).toContain(expectedB64);
|
||||
});
|
||||
|
||||
it('includes environment variables as JSON input', async () => {
|
||||
mockRun.mockResolvedValueOnce(''); // dispatch
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ id: 200, status: 'completed' })); // run found
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ status: 'completed', conclusion: 'success' })); // status
|
||||
mockRun.mockResolvedValueOnce('logs'); // logs
|
||||
|
||||
const env = [
|
||||
{ name: 'UNITY_LICENSE', value: 'license-data' },
|
||||
{ name: 'BUILD_TARGET', value: 'StandaloneWindows64' },
|
||||
];
|
||||
|
||||
await provider.runTaskInWorkflow('guid-2', 'img', 'cmd', '/m', '/w', env as any, []);
|
||||
|
||||
const dispatchCommand = mockRun.mock.calls[0][0];
|
||||
expect(dispatchCommand).toContain('UNITY_LICENSE');
|
||||
expect(dispatchCommand).toContain('BUILD_TARGET');
|
||||
});
|
||||
|
||||
it('throws when workflow dispatch fails', async () => {
|
||||
mockRun.mockRejectedValueOnce(new Error('403 Forbidden'));
|
||||
|
||||
await expect(provider.runTaskInWorkflow('guid-err', 'img', 'cmd', '/m', '/w', [], [])).rejects.toThrow(
|
||||
'Failed to dispatch workflow',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when workflow run does not start within timeout', async () => {
|
||||
mockRun.mockResolvedValueOnce(''); // dispatch succeeds
|
||||
|
||||
// All 30 poll attempts fail
|
||||
for (let i = 0; i < 30; i++) {
|
||||
mockRun.mockRejectedValueOnce(new Error('not found'));
|
||||
}
|
||||
|
||||
await expect(provider.runTaskInWorkflow('guid-timeout', 'img', 'cmd', '/m', '/w', [], [])).rejects.toThrow(
|
||||
'Workflow run did not start within',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when workflow run fails with non-success conclusion', async () => {
|
||||
mockRun.mockResolvedValueOnce(''); // dispatch
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ id: 300, status: 'in_progress' })); // run appears
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ status: 'completed', conclusion: 'failure' })); // fails
|
||||
|
||||
await expect(provider.runTaskInWorkflow('guid-fail', 'img', 'cmd', '/m', '/w', [], [])).rejects.toThrow(
|
||||
'Workflow run failed with conclusion: failure',
|
||||
);
|
||||
});
|
||||
|
||||
it('returns fallback message when log fetch fails', async () => {
|
||||
mockRun.mockResolvedValueOnce(''); // dispatch
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ id: 400, status: 'completed' })); // run appears
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ status: 'completed', conclusion: 'success' })); // completes
|
||||
mockRun.mockRejectedValueOnce(new Error('logs unavailable')); // log fetch fails
|
||||
|
||||
const result = await provider.runTaskInWorkflow('guid-nologs', 'img', 'cmd', '/m', '/w', [], []);
|
||||
|
||||
expect(result).toContain('completed successfully');
|
||||
expect(result).toContain('logs unavailable');
|
||||
});
|
||||
|
||||
it('handles cancelled workflow run conclusion', async () => {
|
||||
mockRun.mockResolvedValueOnce(''); // dispatch
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ id: 500, status: 'in_progress' })); // run
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ status: 'completed', conclusion: 'cancelled' })); // cancelled
|
||||
|
||||
await expect(provider.runTaskInWorkflow('guid-cancel', 'img', 'cmd', '/m', '/w', [], [])).rejects.toThrow(
|
||||
'Workflow run failed with conclusion: cancelled',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws timeout error when polling exceeds maximum duration', async () => {
|
||||
// Save real Date.now
|
||||
const realDateNow = Date.now;
|
||||
let callCount = 0;
|
||||
|
||||
// dispatch succeeds
|
||||
mockRun.mockResolvedValueOnce('');
|
||||
// run appears
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ id: 600, status: 'in_progress' }));
|
||||
// Status always returns in_progress
|
||||
mockRun.mockImplementation(() => Promise.resolve(JSON.stringify({ status: 'in_progress' })));
|
||||
|
||||
// First call returns normal time, subsequent calls simulate 5 hours elapsed
|
||||
Date.now = () => {
|
||||
callCount++;
|
||||
if (callCount <= 2) return realDateNow.call(Date);
|
||||
return realDateNow.call(Date) + 14_400_001; // 4 hours + 1ms
|
||||
};
|
||||
|
||||
try {
|
||||
await expect(provider.runTaskInWorkflow('guid-poll-timeout', 'img', 'cmd', '/m', '/w', [], [])).rejects.toThrow(
|
||||
'did not complete within 4 hours',
|
||||
);
|
||||
|
||||
expect(core.error).toHaveBeenCalledWith(expect.stringContaining('did not complete within 4 hours'));
|
||||
} finally {
|
||||
Date.now = realDateNow;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('cleanupWorkflow', () => {
|
||||
it('completes without error and logs cleanup message', async () => {
|
||||
await provider.cleanupWorkflow(createBuildParameters(), 'main', []);
|
||||
expect(mockLog).toHaveBeenCalledWith(expect.stringContaining('Cleanup complete'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('garbageCollect', () => {
|
||||
it('returns empty string (no-op)', async () => {
|
||||
const result = await provider.garbageCollect('', false, 0, false, false);
|
||||
expect(result).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('listResources', () => {
|
||||
it('returns runner names from the repository', async () => {
|
||||
mockRun.mockResolvedValueOnce('runner-1\nrunner-2\nrunner-3\n');
|
||||
|
||||
const resources = await provider.listResources();
|
||||
|
||||
expect(resources).toHaveLength(3);
|
||||
expect(resources[0].Name).toBe('runner-1');
|
||||
expect(resources[1].Name).toBe('runner-2');
|
||||
expect(resources[2].Name).toBe('runner-3');
|
||||
});
|
||||
|
||||
it('returns empty array when repo or token is missing', async () => {
|
||||
const params = createBuildParameters({ githubActionsRepo: '' });
|
||||
provider = new GitHubActionsProvider(params);
|
||||
|
||||
const resources = await provider.listResources();
|
||||
expect(resources).toEqual([]);
|
||||
expect(mockRun).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns empty array when API call fails', async () => {
|
||||
mockRun.mockRejectedValueOnce(new Error('API error'));
|
||||
|
||||
const resources = await provider.listResources();
|
||||
expect(resources).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('listWorkflow', () => {
|
||||
it('returns recent workflow run names', async () => {
|
||||
mockRun.mockResolvedValueOnce('Build Unity\nRun Tests\n');
|
||||
|
||||
const workflows = await provider.listWorkflow();
|
||||
|
||||
expect(workflows).toHaveLength(2);
|
||||
expect(workflows[0].Name).toBe('Build Unity');
|
||||
expect(workflows[1].Name).toBe('Run Tests');
|
||||
});
|
||||
|
||||
it('returns empty array when credentials missing', async () => {
|
||||
const params = createBuildParameters({ githubActionsToken: '' });
|
||||
provider = new GitHubActionsProvider(params);
|
||||
|
||||
const workflows = await provider.listWorkflow();
|
||||
expect(workflows).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('watchWorkflow', () => {
|
||||
it('returns message when no active run exists', async () => {
|
||||
const result = await provider.watchWorkflow();
|
||||
expect(result).toBe('No active run to watch');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,284 +0,0 @@
|
||||
import * as core from '@actions/core';
|
||||
import BuildParameters from '../../../build-parameters';
|
||||
import { OrchestratorSystem } from '../../services/core/orchestrator-system';
|
||||
import OrchestratorEnvironmentVariable from '../../options/orchestrator-environment-variable';
|
||||
import OrchestratorLogger from '../../services/core/orchestrator-logger';
|
||||
import { ProviderInterface } from '../provider-interface';
|
||||
import OrchestratorSecret from '../../options/orchestrator-secret';
|
||||
import { ProviderResource } from '../provider-resource';
|
||||
import { ProviderWorkflow } from '../provider-workflow';
|
||||
|
||||
const MAX_POLLING_DURATION_MS = 14_400_000; // 4 hours
|
||||
|
||||
/**
|
||||
* GitHub Actions provider — triggers builds as workflow_dispatch events
|
||||
* on a target repository via the GitHub API.
|
||||
*
|
||||
* Use case: Distribute builds across orgs, use specialized runner pools,
|
||||
* or trigger builds in repos with Unity licenses.
|
||||
*/
|
||||
class GitHubActionsProvider implements ProviderInterface {
|
||||
private buildParameters: BuildParameters;
|
||||
private repo: string;
|
||||
private workflow: string;
|
||||
private token: string;
|
||||
private ref: string;
|
||||
private runId: number = 0;
|
||||
|
||||
constructor(buildParameters: BuildParameters) {
|
||||
this.buildParameters = buildParameters;
|
||||
this.repo = buildParameters.githubActionsRepo || '';
|
||||
this.workflow = buildParameters.githubActionsWorkflow || '';
|
||||
this.token = buildParameters.githubActionsToken || '';
|
||||
this.ref = buildParameters.githubActionsRef || 'main';
|
||||
}
|
||||
|
||||
async setupWorkflow(
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
buildGuid: string,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
buildParameters: BuildParameters,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
branchName: string,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
defaultSecretsArray: { ParameterKey: string; EnvironmentVariable: string; ParameterValue: string }[],
|
||||
): Promise<void> {
|
||||
OrchestratorLogger.log(`[GitHubActions] Setting up workflow dispatch to ${this.repo}`);
|
||||
|
||||
if (!this.repo || !this.workflow) {
|
||||
throw new Error('githubActionsRepo and githubActionsWorkflow are required for the github-actions provider');
|
||||
}
|
||||
|
||||
if (!this.token) {
|
||||
throw new Error('githubActionsToken is required (PAT with actions:write scope)');
|
||||
}
|
||||
|
||||
// Verify repository and workflow exist
|
||||
try {
|
||||
const result = await OrchestratorSystem.Run(
|
||||
`GH_TOKEN=${this.token} gh api repos/${this.repo}/actions/workflows/${this.workflow} --jq '.id'`,
|
||||
);
|
||||
OrchestratorLogger.log(`[GitHubActions] Workflow verified: ${this.workflow} (ID: ${result.trim()})`);
|
||||
} catch (error: any) {
|
||||
throw new Error(`Failed to verify workflow ${this.workflow} in ${this.repo}: ${error.message || error}`);
|
||||
}
|
||||
}
|
||||
|
||||
async runTaskInWorkflow(
|
||||
buildGuid: string,
|
||||
image: string,
|
||||
commands: string,
|
||||
mountdir: string,
|
||||
workingdir: string,
|
||||
environment: OrchestratorEnvironmentVariable[],
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
secrets: OrchestratorSecret[],
|
||||
): Promise<string> {
|
||||
OrchestratorLogger.log(`[GitHubActions] Dispatching workflow ${this.workflow} on ${this.repo}@${this.ref}`);
|
||||
|
||||
// Build inputs payload
|
||||
const inputs: Record<string, string> = {
|
||||
buildGuid,
|
||||
image,
|
||||
commands: Buffer.from(commands).toString('base64'),
|
||||
mountdir,
|
||||
workingdir,
|
||||
};
|
||||
|
||||
// Add environment variables as a JSON input
|
||||
if (environment.length > 0) {
|
||||
inputs.environment = JSON.stringify(environment.map((element) => ({ name: element.name, value: element.value })));
|
||||
}
|
||||
|
||||
// Record the time before dispatch to identify the run
|
||||
const beforeDispatch = new Date().toISOString();
|
||||
|
||||
// Dispatch the workflow
|
||||
const inputsJson = JSON.stringify(inputs).replace(/'/g, "'\\''");
|
||||
try {
|
||||
await OrchestratorSystem.Run(
|
||||
`GH_TOKEN=${this.token} gh api repos/${this.repo}/actions/workflows/${this.workflow}/dispatches -X POST -f ref='${this.ref}' -f "inputs=${inputsJson}"`,
|
||||
);
|
||||
OrchestratorLogger.log(`[GitHubActions] Workflow dispatched`);
|
||||
} catch (error: any) {
|
||||
throw new Error(`Failed to dispatch workflow: ${error.message || error}`);
|
||||
}
|
||||
|
||||
// Poll for the run to appear
|
||||
OrchestratorLogger.log(`[GitHubActions] Waiting for workflow run to start...`);
|
||||
let attempts = 0;
|
||||
const maxAttempts = 30;
|
||||
|
||||
while (attempts < maxAttempts) {
|
||||
attempts++;
|
||||
await new Promise((resolve) => setTimeout(resolve, 10_000));
|
||||
|
||||
try {
|
||||
const runsJson = await OrchestratorSystem.Run(
|
||||
`GH_TOKEN=${this.token} gh api "repos/${this.repo}/actions/workflows/${this.workflow}/runs?created=>${beforeDispatch}&per_page=5" --jq '.workflow_runs[0] | {id, status, conclusion}'`,
|
||||
true,
|
||||
);
|
||||
|
||||
const run = JSON.parse(runsJson.trim());
|
||||
if (run.id) {
|
||||
this.runId = run.id;
|
||||
OrchestratorLogger.log(`[GitHubActions] Run started: ${this.runId} (status: ${run.status})`);
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
// Run not yet available
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.runId) {
|
||||
throw new Error(`Workflow run did not start within ${maxAttempts * 10}s`);
|
||||
}
|
||||
|
||||
// Poll until completion and stream logs (with maximum duration guard)
|
||||
let status = 'in_progress';
|
||||
const pollingStartTime = Date.now();
|
||||
const runUrl = `https://github.com/${this.repo}/actions/runs/${this.runId}`;
|
||||
|
||||
while (status === 'in_progress' || status === 'queued') {
|
||||
const elapsedMs = Date.now() - pollingStartTime;
|
||||
if (elapsedMs >= MAX_POLLING_DURATION_MS) {
|
||||
const hours = Math.round(MAX_POLLING_DURATION_MS / 3_600_000);
|
||||
const message = `GitHub Actions workflow did not complete within ${hours} hours. Run URL: ${runUrl}`;
|
||||
core.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 15_000));
|
||||
|
||||
try {
|
||||
const statusJson = await OrchestratorSystem.Run(
|
||||
`GH_TOKEN=${this.token} gh api repos/${this.repo}/actions/runs/${this.runId} --jq '{status, conclusion}'`,
|
||||
true,
|
||||
);
|
||||
|
||||
const result = JSON.parse(statusJson.trim());
|
||||
status = result.status;
|
||||
|
||||
if (status === 'completed') {
|
||||
OrchestratorLogger.log(`[GitHubActions] Run ${this.runId} completed: ${result.conclusion}`);
|
||||
|
||||
if (result.conclusion !== 'success') {
|
||||
throw new Error(`Workflow run failed with conclusion: ${result.conclusion}`);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
OrchestratorLogger.log(`[GitHubActions] Run ${this.runId} status: ${status}`);
|
||||
} catch (error: any) {
|
||||
if (error.message && error.message.includes('conclusion')) {
|
||||
throw error;
|
||||
}
|
||||
if (error.message && error.message.includes('did not complete within')) {
|
||||
throw error;
|
||||
}
|
||||
OrchestratorLogger.logWarning(`[GitHubActions] Status check error: ${error.message || error}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch logs
|
||||
try {
|
||||
const logs = await OrchestratorSystem.Run(
|
||||
`GH_TOKEN=${this.token} gh run view ${this.runId} --repo ${this.repo} --log`,
|
||||
true,
|
||||
);
|
||||
|
||||
return logs;
|
||||
} catch {
|
||||
return `Run ${this.runId} completed successfully (logs unavailable)`;
|
||||
}
|
||||
}
|
||||
|
||||
async cleanupWorkflow(
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
buildParameters: BuildParameters,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
branchName: string,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
defaultSecretsArray: { ParameterKey: string; EnvironmentVariable: string; ParameterValue: string }[],
|
||||
): Promise<void> {
|
||||
OrchestratorLogger.log(`[GitHubActions] Cleanup complete (no resources to tear down)`);
|
||||
}
|
||||
|
||||
async garbageCollect(
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
filter: string,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
previewOnly: boolean,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
olderThan: Number,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
fullCache: boolean,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
baseDependencies: boolean,
|
||||
): Promise<string> {
|
||||
return '';
|
||||
}
|
||||
|
||||
async listResources(): Promise<ProviderResource[]> {
|
||||
if (!this.repo || !this.token) return [];
|
||||
|
||||
try {
|
||||
const runnersJson = await OrchestratorSystem.Run(
|
||||
`GH_TOKEN=${this.token} gh api repos/${this.repo}/actions/runners --jq '.runners[] | .name'`,
|
||||
true,
|
||||
);
|
||||
|
||||
return runnersJson
|
||||
.trim()
|
||||
.split('\n')
|
||||
.filter(Boolean)
|
||||
.map((name) => {
|
||||
const resource = new ProviderResource();
|
||||
resource.Name = name.trim();
|
||||
|
||||
return resource;
|
||||
});
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async listWorkflow(): Promise<ProviderWorkflow[]> {
|
||||
if (!this.repo || !this.token) return [];
|
||||
|
||||
try {
|
||||
const runsJson = await OrchestratorSystem.Run(
|
||||
`GH_TOKEN=${this.token} gh api repos/${this.repo}/actions/runs?per_page=10 --jq '.workflow_runs[] | .name'`,
|
||||
true,
|
||||
);
|
||||
|
||||
return runsJson
|
||||
.trim()
|
||||
.split('\n')
|
||||
.filter(Boolean)
|
||||
.map((name) => {
|
||||
const workflow = new ProviderWorkflow();
|
||||
workflow.Name = name.trim();
|
||||
|
||||
return workflow;
|
||||
});
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async watchWorkflow(): Promise<string> {
|
||||
if (!this.runId) return 'No active run to watch';
|
||||
|
||||
try {
|
||||
return await OrchestratorSystem.Run(
|
||||
`GH_TOKEN=${this.token} gh run watch ${this.runId} --repo ${this.repo}`,
|
||||
true,
|
||||
);
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
}
|
||||
export default GitHubActionsProvider;
|
||||
@@ -1,329 +0,0 @@
|
||||
import GitLabCIProvider from '.';
|
||||
import BuildParameters from '../../../build-parameters';
|
||||
import { OrchestratorSystem } from '../../services/core/orchestrator-system';
|
||||
import OrchestratorLogger from '../../services/core/orchestrator-logger';
|
||||
import * as core from '@actions/core';
|
||||
|
||||
jest.mock('../../services/core/orchestrator-system');
|
||||
jest.mock('../../services/core/orchestrator-logger');
|
||||
jest.mock('@actions/core', () => ({
|
||||
info: jest.fn(),
|
||||
warning: jest.fn(),
|
||||
error: jest.fn(),
|
||||
setOutput: jest.fn(),
|
||||
getInput: jest.fn(() => ''),
|
||||
}));
|
||||
|
||||
const mockRun = OrchestratorSystem.Run as jest.MockedFunction<typeof OrchestratorSystem.Run>;
|
||||
const mockLog = OrchestratorLogger.log as jest.MockedFunction<typeof OrchestratorLogger.log>;
|
||||
const mockLogWarning = OrchestratorLogger.logWarning as jest.MockedFunction<typeof OrchestratorLogger.logWarning>;
|
||||
|
||||
function createBuildParameters(overrides: Partial<BuildParameters> = {}): BuildParameters {
|
||||
return {
|
||||
gitlabProjectId: 'my-group/my-project',
|
||||
gitlabTriggerToken: 'glptt-test-token-456',
|
||||
gitlabApiUrl: 'https://gitlab.example.com',
|
||||
gitlabRef: 'main',
|
||||
...overrides,
|
||||
} as BuildParameters;
|
||||
}
|
||||
|
||||
// Override setTimeout to execute callbacks immediately so polling loops complete fast
|
||||
const originalSetTimeout = global.setTimeout;
|
||||
beforeAll(() => {
|
||||
global.setTimeout = ((fn: (...args: any[]) => void, _ms?: number, ...args: any[]) => {
|
||||
return originalSetTimeout(fn, 0, ...args);
|
||||
}) as any;
|
||||
});
|
||||
afterAll(() => {
|
||||
global.setTimeout = originalSetTimeout;
|
||||
});
|
||||
|
||||
describe('GitLabCIProvider', () => {
|
||||
let provider: GitLabCIProvider;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
provider = new GitLabCIProvider(createBuildParameters());
|
||||
});
|
||||
|
||||
describe('constructor', () => {
|
||||
it('strips trailing slashes from apiUrl', () => {
|
||||
const params = createBuildParameters({ gitlabApiUrl: 'https://gitlab.example.com///' });
|
||||
const p = new GitLabCIProvider(params);
|
||||
expect(p).toBeDefined();
|
||||
});
|
||||
|
||||
it('defaults apiUrl to https://gitlab.com when not provided', () => {
|
||||
const params = createBuildParameters({ gitlabApiUrl: undefined });
|
||||
const p = new GitLabCIProvider(params);
|
||||
expect(p).toBeDefined();
|
||||
});
|
||||
|
||||
it('defaults ref to main when not provided', () => {
|
||||
const params = createBuildParameters({ gitlabRef: undefined });
|
||||
const p = new GitLabCIProvider(params);
|
||||
expect(p).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('setupWorkflow', () => {
|
||||
it('verifies project access via curl and logs success', async () => {
|
||||
mockRun.mockResolvedValueOnce('');
|
||||
|
||||
await provider.setupWorkflow('guid-123', createBuildParameters(), 'main', []);
|
||||
|
||||
expect(mockRun).toHaveBeenCalledTimes(1);
|
||||
const command = mockRun.mock.calls[0][0];
|
||||
expect(command).toContain('curl -sf');
|
||||
expect(command).toContain('PRIVATE-TOKEN: glptt-test-token-456');
|
||||
expect(command).toContain('gitlab.example.com/api/v4/projects/');
|
||||
expect(command).toContain(encodeURIComponent('my-group/my-project'));
|
||||
expect(mockLog).toHaveBeenCalledWith(expect.stringContaining('Project access verified'));
|
||||
});
|
||||
|
||||
it('throws when projectId is not configured', async () => {
|
||||
const params = createBuildParameters({ gitlabProjectId: '' });
|
||||
provider = new GitLabCIProvider(params);
|
||||
|
||||
await expect(provider.setupWorkflow('guid-123', params, 'main', [])).rejects.toThrow(
|
||||
'gitlabProjectId and gitlabTriggerToken are required',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when triggerToken is not configured', async () => {
|
||||
const params = createBuildParameters({ gitlabTriggerToken: '' });
|
||||
provider = new GitLabCIProvider(params);
|
||||
|
||||
await expect(provider.setupWorkflow('guid-123', params, 'main', [])).rejects.toThrow(
|
||||
'gitlabProjectId and gitlabTriggerToken are required',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws descriptive error when project access check fails', async () => {
|
||||
mockRun.mockRejectedValueOnce(new Error('401 Unauthorized'));
|
||||
|
||||
await expect(provider.setupWorkflow('guid-123', createBuildParameters(), 'main', [])).rejects.toThrow(
|
||||
'Failed to access GitLab project my-group/my-project',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('runTaskInWorkflow', () => {
|
||||
it('triggers pipeline and returns job logs on success', async () => {
|
||||
// Pipeline trigger response
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ id: 5001, status: 'pending' }));
|
||||
// Status poll returns success
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ status: 'success' }));
|
||||
// Jobs list
|
||||
mockRun.mockResolvedValueOnce(
|
||||
JSON.stringify([
|
||||
{ id: 10001, name: 'build-unity', status: 'success' },
|
||||
{ id: 10002, name: 'test-unity', status: 'success' },
|
||||
]),
|
||||
);
|
||||
// Job traces
|
||||
mockRun.mockResolvedValueOnce('Building Unity project...\nDone.');
|
||||
mockRun.mockResolvedValueOnce('Running tests...\nAll passed.');
|
||||
|
||||
const result = await provider.runTaskInWorkflow(
|
||||
'guid-gl1',
|
||||
'unityci/editor:2021.3',
|
||||
'echo build',
|
||||
'/mount',
|
||||
'/work',
|
||||
[],
|
||||
[],
|
||||
);
|
||||
|
||||
expect(result).toContain('build-unity');
|
||||
expect(result).toContain('test-unity');
|
||||
expect(result).toContain('Building Unity project');
|
||||
expect(result).toContain('Running tests');
|
||||
|
||||
// Verify trigger command
|
||||
const triggerCommand = mockRun.mock.calls[0][0];
|
||||
expect(triggerCommand).toContain('trigger/pipeline');
|
||||
expect(triggerCommand).toContain(`token=${createBuildParameters().gitlabTriggerToken}`);
|
||||
expect(triggerCommand).toContain('ref=main');
|
||||
});
|
||||
|
||||
it('passes build variables including base64-encoded commands', async () => {
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ id: 5002, status: 'success' }));
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ status: 'success' }));
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify([]));
|
||||
|
||||
await provider.runTaskInWorkflow(
|
||||
'guid-vars',
|
||||
'ubuntu:20.04',
|
||||
'make build',
|
||||
'/mnt/data',
|
||||
'/workspace',
|
||||
[{ name: 'UNITY_VERSION', value: '2021.3.1f1' } as any],
|
||||
[],
|
||||
);
|
||||
|
||||
const triggerCommand = mockRun.mock.calls[0][0];
|
||||
const expectedB64 = Buffer.from('make build').toString('base64');
|
||||
expect(triggerCommand).toContain(`variables[BUILD_COMMANDS]=${expectedB64}`);
|
||||
expect(triggerCommand).toContain('variables[BUILD_GUID]=guid-vars');
|
||||
expect(triggerCommand).toContain('variables[BUILD_IMAGE]=ubuntu:20.04');
|
||||
expect(triggerCommand).toContain('variables[MOUNT_DIR]=/mnt/data');
|
||||
expect(triggerCommand).toContain('variables[WORKING_DIR]=/workspace');
|
||||
expect(triggerCommand).toContain('variables[UNITY_VERSION]=2021.3.1f1');
|
||||
});
|
||||
|
||||
it('throws when pipeline trigger fails', async () => {
|
||||
mockRun.mockRejectedValueOnce(new Error('404 Not Found'));
|
||||
|
||||
await expect(provider.runTaskInWorkflow('guid-err', 'img', 'cmd', '/m', '/w', [], [])).rejects.toThrow(
|
||||
'Failed to trigger pipeline',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when pipeline finishes with failure status', async () => {
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ id: 5003, status: 'pending' }));
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ status: 'failed' }));
|
||||
|
||||
await expect(provider.runTaskInWorkflow('guid-fail', 'img', 'cmd', '/m', '/w', [], [])).rejects.toThrow(
|
||||
'Pipeline 5003 finished with status: failed',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when pipeline is canceled', async () => {
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ id: 5004, status: 'pending' }));
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ status: 'canceled' }));
|
||||
|
||||
await expect(provider.runTaskInWorkflow('guid-cancel', 'img', 'cmd', '/m', '/w', [], [])).rejects.toThrow(
|
||||
'Pipeline 5004 finished with status: canceled',
|
||||
);
|
||||
});
|
||||
|
||||
it('handles job log fetch failures gracefully', async () => {
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ id: 5005, status: 'success' }));
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ status: 'success' }));
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify([{ id: 20001, name: 'build', status: 'success' }]));
|
||||
// Job trace fetch fails
|
||||
mockRun.mockRejectedValueOnce(new Error('trace unavailable'));
|
||||
|
||||
const result = await provider.runTaskInWorkflow('guid-nologs', 'img', 'cmd', '/m', '/w', [], []);
|
||||
|
||||
expect(result).toContain('build');
|
||||
expect(result).toContain('logs unavailable');
|
||||
});
|
||||
|
||||
it('returns fallback message when entire job fetch fails', async () => {
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ id: 5006, status: 'success' }));
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ status: 'success' }));
|
||||
// Jobs list fails
|
||||
mockRun.mockRejectedValueOnce(new Error('API error'));
|
||||
|
||||
const result = await provider.runTaskInWorkflow('guid-noapi', 'img', 'cmd', '/m', '/w', [], []);
|
||||
|
||||
expect(result).toContain('Pipeline 5006 completed successfully');
|
||||
expect(result).toContain('logs unavailable');
|
||||
});
|
||||
|
||||
it('continues polling through status check errors until completion', async () => {
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ id: 5007, status: 'pending' }));
|
||||
// First status check fails
|
||||
mockRun.mockRejectedValueOnce(new Error('network blip'));
|
||||
// Second status check succeeds
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ status: 'success' }));
|
||||
// Jobs/logs
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify([]));
|
||||
|
||||
await provider.runTaskInWorkflow('guid-retry', 'img', 'cmd', '/m', '/w', [], []);
|
||||
|
||||
expect(mockLogWarning).toHaveBeenCalledWith(expect.stringContaining('Status check error'));
|
||||
});
|
||||
|
||||
it('throws timeout error when polling exceeds maximum duration', async () => {
|
||||
const realDateNow = Date.now;
|
||||
let callCount = 0;
|
||||
|
||||
// Trigger pipeline succeeds
|
||||
mockRun.mockResolvedValueOnce(JSON.stringify({ id: 5008, status: 'running' }));
|
||||
// Status always returns running
|
||||
mockRun.mockImplementation(() => Promise.resolve(JSON.stringify({ status: 'running' })));
|
||||
|
||||
// After first call, simulate 5 hours elapsed
|
||||
Date.now = () => {
|
||||
callCount++;
|
||||
if (callCount <= 1) return realDateNow.call(Date);
|
||||
return realDateNow.call(Date) + 14_400_001; // 4 hours + 1ms
|
||||
};
|
||||
|
||||
try {
|
||||
await expect(provider.runTaskInWorkflow('guid-poll-timeout', 'img', 'cmd', '/m', '/w', [], [])).rejects.toThrow(
|
||||
'did not complete within 4 hours',
|
||||
);
|
||||
|
||||
expect(core.error).toHaveBeenCalledWith(expect.stringContaining('did not complete within 4 hours'));
|
||||
} finally {
|
||||
Date.now = realDateNow;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('cleanupWorkflow', () => {
|
||||
it('completes without error and logs cleanup message', async () => {
|
||||
await provider.cleanupWorkflow(createBuildParameters(), 'main', []);
|
||||
expect(mockLog).toHaveBeenCalledWith(expect.stringContaining('Cleanup complete'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('garbageCollect', () => {
|
||||
it('returns empty string (no-op)', async () => {
|
||||
const result = await provider.garbageCollect('', false, 0, false, false);
|
||||
expect(result).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('listResources', () => {
|
||||
it('returns empty array (not implemented)', async () => {
|
||||
const resources = await provider.listResources();
|
||||
expect(resources).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('listWorkflow', () => {
|
||||
it('returns recent pipeline names when credentials are available', async () => {
|
||||
mockRun.mockResolvedValueOnce(
|
||||
JSON.stringify([
|
||||
{ id: 100, status: 'success' },
|
||||
{ id: 101, status: 'failed' },
|
||||
]),
|
||||
);
|
||||
|
||||
const workflows = await provider.listWorkflow();
|
||||
|
||||
expect(workflows).toHaveLength(2);
|
||||
expect(workflows[0].Name).toBe('Pipeline #100 (success)');
|
||||
expect(workflows[1].Name).toBe('Pipeline #101 (failed)');
|
||||
});
|
||||
|
||||
it('returns empty array when credentials are missing', async () => {
|
||||
const params = createBuildParameters({ gitlabProjectId: '' });
|
||||
provider = new GitLabCIProvider(params);
|
||||
|
||||
const workflows = await provider.listWorkflow();
|
||||
expect(workflows).toEqual([]);
|
||||
expect(mockRun).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns empty array when API call fails', async () => {
|
||||
mockRun.mockRejectedValueOnce(new Error('API error'));
|
||||
|
||||
const workflows = await provider.listWorkflow();
|
||||
expect(workflows).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('watchWorkflow', () => {
|
||||
it('returns empty string (not implemented)', async () => {
|
||||
const result = await provider.watchWorkflow();
|
||||
expect(result).toBe('');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,224 +0,0 @@
|
||||
import * as core from '@actions/core';
|
||||
import BuildParameters from '../../../build-parameters';
|
||||
import { OrchestratorSystem } from '../../services/core/orchestrator-system';
|
||||
import OrchestratorEnvironmentVariable from '../../options/orchestrator-environment-variable';
|
||||
import OrchestratorLogger from '../../services/core/orchestrator-logger';
|
||||
import { ProviderInterface } from '../provider-interface';
|
||||
import OrchestratorSecret from '../../options/orchestrator-secret';
|
||||
import { ProviderResource } from '../provider-resource';
|
||||
import { ProviderWorkflow } from '../provider-workflow';
|
||||
|
||||
const MAX_POLLING_DURATION_MS = 14_400_000; // 4 hours
|
||||
|
||||
/**
|
||||
* GitLab CI provider — triggers builds as GitLab CI pipelines
|
||||
* via the GitLab API.
|
||||
*
|
||||
* Use case: Teams using GitLab CI, hybrid GitHub/GitLab setups,
|
||||
* or GitLab runners with Unity licenses.
|
||||
*/
|
||||
class GitLabCIProvider implements ProviderInterface {
|
||||
private buildParameters: BuildParameters;
|
||||
private projectId: string;
|
||||
private triggerToken: string;
|
||||
private apiUrl: string;
|
||||
private ref: string;
|
||||
private pipelineId: number = 0;
|
||||
|
||||
constructor(buildParameters: BuildParameters) {
|
||||
this.buildParameters = buildParameters;
|
||||
this.projectId = buildParameters.gitlabProjectId || '';
|
||||
this.triggerToken = buildParameters.gitlabTriggerToken || '';
|
||||
this.apiUrl = (buildParameters.gitlabApiUrl || 'https://gitlab.com').replace(/\/+$/, '');
|
||||
this.ref = buildParameters.gitlabRef || 'main';
|
||||
}
|
||||
|
||||
async setupWorkflow(
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
buildGuid: string,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
buildParameters: BuildParameters,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
branchName: string,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
defaultSecretsArray: { ParameterKey: string; EnvironmentVariable: string; ParameterValue: string }[],
|
||||
): Promise<void> {
|
||||
OrchestratorLogger.log(`[GitLabCI] Setting up pipeline trigger for project ${this.projectId}`);
|
||||
|
||||
if (!this.projectId || !this.triggerToken) {
|
||||
throw new Error('gitlabProjectId and gitlabTriggerToken are required for the gitlab-ci provider');
|
||||
}
|
||||
|
||||
// Verify project access
|
||||
const encodedProject = encodeURIComponent(this.projectId);
|
||||
try {
|
||||
await OrchestratorSystem.Run(
|
||||
`curl -sf -H "PRIVATE-TOKEN: ${this.triggerToken}" "${this.apiUrl}/api/v4/projects/${encodedProject}" -o /dev/null`,
|
||||
);
|
||||
OrchestratorLogger.log(`[GitLabCI] Project access verified`);
|
||||
} catch (error: any) {
|
||||
throw new Error(`Failed to access GitLab project ${this.projectId}: ${error.message || error}`);
|
||||
}
|
||||
}
|
||||
|
||||
async runTaskInWorkflow(
|
||||
buildGuid: string,
|
||||
image: string,
|
||||
commands: string,
|
||||
mountdir: string,
|
||||
workingdir: string,
|
||||
environment: OrchestratorEnvironmentVariable[],
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
secrets: OrchestratorSecret[],
|
||||
): Promise<string> {
|
||||
OrchestratorLogger.log(`[GitLabCI] Triggering pipeline on project ${this.projectId}@${this.ref}`);
|
||||
|
||||
const encodedProject = encodeURIComponent(this.projectId);
|
||||
|
||||
// Build variables for the pipeline
|
||||
const pipelineVariables: string[] = [
|
||||
`-f "variables[BUILD_GUID]=${buildGuid}"`,
|
||||
`-f "variables[BUILD_IMAGE]=${image}"`,
|
||||
`-f "variables[BUILD_COMMANDS]=${Buffer.from(commands).toString('base64')}"`,
|
||||
`-f "variables[MOUNT_DIR]=${mountdir}"`,
|
||||
`-f "variables[WORKING_DIR]=${workingdir}"`,
|
||||
];
|
||||
|
||||
for (const element of environment) {
|
||||
pipelineVariables.push(`-f "variables[${element.name}]=${element.value}"`);
|
||||
}
|
||||
|
||||
// Trigger pipeline
|
||||
try {
|
||||
const response = await OrchestratorSystem.Run(
|
||||
`curl -sf -X POST "${this.apiUrl}/api/v4/projects/${encodedProject}/trigger/pipeline" -f "token=${
|
||||
this.triggerToken
|
||||
}" -f "ref=${this.ref}" ${pipelineVariables.join(' ')}`,
|
||||
);
|
||||
|
||||
const pipeline = JSON.parse(response);
|
||||
this.pipelineId = pipeline.id;
|
||||
OrchestratorLogger.log(`[GitLabCI] Pipeline triggered: ${this.pipelineId} (status: ${pipeline.status})`);
|
||||
} catch (error: any) {
|
||||
throw new Error(`Failed to trigger pipeline: ${error.message || error}`);
|
||||
}
|
||||
|
||||
// Poll until completion (with maximum duration guard)
|
||||
let status = 'pending';
|
||||
const terminalStatuses = new Set(['success', 'failed', 'canceled', 'skipped']);
|
||||
const pollingStartTime = Date.now();
|
||||
const pipelineUrl = `${this.apiUrl}/${this.projectId}/-/pipelines/${this.pipelineId}`;
|
||||
|
||||
while (!terminalStatuses.has(status)) {
|
||||
const elapsedMs = Date.now() - pollingStartTime;
|
||||
if (elapsedMs >= MAX_POLLING_DURATION_MS) {
|
||||
const hours = Math.round(MAX_POLLING_DURATION_MS / 3_600_000);
|
||||
const message = `GitLab CI pipeline did not complete within ${hours} hours. Pipeline URL: ${pipelineUrl}`;
|
||||
core.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 15_000));
|
||||
|
||||
try {
|
||||
const statusResponse = await OrchestratorSystem.Run(
|
||||
`curl -sf -H "PRIVATE-TOKEN: ${this.triggerToken}" "${this.apiUrl}/api/v4/projects/${encodedProject}/pipelines/${this.pipelineId}"`,
|
||||
true,
|
||||
);
|
||||
|
||||
const pipelineStatus = JSON.parse(statusResponse);
|
||||
status = pipelineStatus.status;
|
||||
OrchestratorLogger.log(`[GitLabCI] Pipeline ${this.pipelineId} status: ${status}`);
|
||||
} catch (error: any) {
|
||||
OrchestratorLogger.logWarning(`[GitLabCI] Status check error: ${error.message || error}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (status !== 'success') {
|
||||
throw new Error(`Pipeline ${this.pipelineId} finished with status: ${status}`);
|
||||
}
|
||||
|
||||
// Fetch job logs
|
||||
try {
|
||||
const jobsResponse = await OrchestratorSystem.Run(
|
||||
`curl -sf -H "PRIVATE-TOKEN: ${this.triggerToken}" "${this.apiUrl}/api/v4/projects/${encodedProject}/pipelines/${this.pipelineId}/jobs"`,
|
||||
true,
|
||||
);
|
||||
|
||||
const jobs = JSON.parse(jobsResponse);
|
||||
const logs: string[] = [];
|
||||
|
||||
for (const job of jobs) {
|
||||
try {
|
||||
const jobLog = await OrchestratorSystem.Run(
|
||||
`curl -sf -H "PRIVATE-TOKEN: ${this.triggerToken}" "${this.apiUrl}/api/v4/projects/${encodedProject}/jobs/${job.id}/trace"`,
|
||||
true,
|
||||
);
|
||||
logs.push(`=== Job: ${job.name} (${job.status}) ===\n${jobLog}`);
|
||||
} catch {
|
||||
logs.push(`=== Job: ${job.name} (${job.status}) === (logs unavailable)`);
|
||||
}
|
||||
}
|
||||
|
||||
return logs.join('\n\n');
|
||||
} catch {
|
||||
return `Pipeline ${this.pipelineId} completed successfully (logs unavailable)`;
|
||||
}
|
||||
}
|
||||
|
||||
async cleanupWorkflow(
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
buildParameters: BuildParameters,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
branchName: string,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
defaultSecretsArray: { ParameterKey: string; EnvironmentVariable: string; ParameterValue: string }[],
|
||||
): Promise<void> {
|
||||
OrchestratorLogger.log(`[GitLabCI] Cleanup complete`);
|
||||
}
|
||||
|
||||
async garbageCollect(
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
filter: string,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
previewOnly: boolean,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
olderThan: Number,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
fullCache: boolean,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
baseDependencies: boolean,
|
||||
): Promise<string> {
|
||||
return '';
|
||||
}
|
||||
|
||||
async listResources(): Promise<ProviderResource[]> {
|
||||
return [];
|
||||
}
|
||||
|
||||
async listWorkflow(): Promise<ProviderWorkflow[]> {
|
||||
if (!this.projectId || !this.triggerToken) return [];
|
||||
|
||||
try {
|
||||
const encodedProject = encodeURIComponent(this.projectId);
|
||||
const response = await OrchestratorSystem.Run(
|
||||
`curl -sf -H "PRIVATE-TOKEN: ${this.triggerToken}" "${this.apiUrl}/api/v4/projects/${encodedProject}/pipelines?per_page=10"`,
|
||||
true,
|
||||
);
|
||||
|
||||
return JSON.parse(response).map((pipeline: any) => {
|
||||
const workflow = new ProviderWorkflow();
|
||||
workflow.Name = `Pipeline #${pipeline.id} (${pipeline.status})`;
|
||||
|
||||
return workflow;
|
||||
});
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async watchWorkflow(): Promise<string> {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
export default GitLabCIProvider;
|
||||
@@ -1,164 +0,0 @@
|
||||
import BuildParameters from '../../build-parameters';
|
||||
import RemotePowershellProvider from './remote-powershell';
|
||||
import GitHubActionsProvider from './github-actions';
|
||||
import GitLabCIProvider from './gitlab-ci';
|
||||
import AnsibleProvider from './ansible';
|
||||
|
||||
/**
|
||||
* Tests for provider selection logic in Orchestrator.setProvider.
|
||||
*
|
||||
* These tests verify that the correct provider class is instantiated based on
|
||||
* the providerStrategy field in BuildParameters. Rather than invoking the full
|
||||
* Orchestrator.setProvider (which has heavy dependencies on OrchestratorOptions,
|
||||
* AWS detection, etc.), we test the provider constructors directly to verify
|
||||
* they produce the right provider type from the same build parameters the
|
||||
* orchestrator switch statement uses.
|
||||
*/
|
||||
describe('Provider Selection', () => {
|
||||
describe('remote-powershell provider', () => {
|
||||
it('creates RemotePowershellProvider from build parameters', () => {
|
||||
const params = {
|
||||
providerStrategy: 'remote-powershell',
|
||||
remotePowershellHost: 'build-server.local',
|
||||
remotePowershellTransport: 'wsman',
|
||||
remotePowershellCredential: 'user:pass',
|
||||
} as BuildParameters;
|
||||
|
||||
const provider = new RemotePowershellProvider(params);
|
||||
|
||||
expect(provider).toBeInstanceOf(RemotePowershellProvider);
|
||||
expect(provider.constructor.name).toBe('RemotePowershellProvider');
|
||||
});
|
||||
});
|
||||
|
||||
describe('github-actions provider', () => {
|
||||
it('creates GitHubActionsProvider from build parameters', () => {
|
||||
const params = {
|
||||
providerStrategy: 'github-actions',
|
||||
githubActionsRepo: 'org/repo',
|
||||
githubActionsWorkflow: 'ci.yml',
|
||||
githubActionsToken: 'ghp_token',
|
||||
githubActionsRef: 'main',
|
||||
} as BuildParameters;
|
||||
|
||||
const provider = new GitHubActionsProvider(params);
|
||||
|
||||
expect(provider).toBeInstanceOf(GitHubActionsProvider);
|
||||
expect(provider.constructor.name).toBe('GitHubActionsProvider');
|
||||
});
|
||||
});
|
||||
|
||||
describe('gitlab-ci provider', () => {
|
||||
it('creates GitLabCIProvider from build parameters', () => {
|
||||
const params = {
|
||||
providerStrategy: 'gitlab-ci',
|
||||
gitlabProjectId: 'group/project',
|
||||
gitlabTriggerToken: 'glptt-token',
|
||||
gitlabApiUrl: 'https://gitlab.com',
|
||||
gitlabRef: 'main',
|
||||
} as BuildParameters;
|
||||
|
||||
const provider = new GitLabCIProvider(params);
|
||||
|
||||
expect(provider).toBeInstanceOf(GitLabCIProvider);
|
||||
expect(provider.constructor.name).toBe('GitLabCIProvider');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ansible provider', () => {
|
||||
it('creates AnsibleProvider from build parameters', () => {
|
||||
const params = {
|
||||
providerStrategy: 'ansible',
|
||||
ansibleInventory: '/etc/ansible/hosts',
|
||||
ansiblePlaybook: '/playbooks/build.yml',
|
||||
ansibleExtraVars: '',
|
||||
ansibleVaultPassword: '',
|
||||
} as BuildParameters;
|
||||
|
||||
const provider = new AnsibleProvider(params);
|
||||
|
||||
expect(provider).toBeInstanceOf(AnsibleProvider);
|
||||
expect(provider.constructor.name).toBe('AnsibleProvider');
|
||||
});
|
||||
});
|
||||
|
||||
describe('provider strategy routing', () => {
|
||||
it('each provider strategy maps to a distinct provider class', () => {
|
||||
const strategies: Record<string, new (params: BuildParameters) => any> = {
|
||||
'remote-powershell': RemotePowershellProvider,
|
||||
'github-actions': GitHubActionsProvider,
|
||||
'gitlab-ci': GitLabCIProvider,
|
||||
ansible: AnsibleProvider,
|
||||
};
|
||||
|
||||
const params = {
|
||||
remotePowershellHost: 'host',
|
||||
remotePowershellTransport: 'wsman',
|
||||
remotePowershellCredential: '',
|
||||
githubActionsRepo: 'org/repo',
|
||||
githubActionsWorkflow: 'ci.yml',
|
||||
githubActionsToken: 'token',
|
||||
githubActionsRef: 'main',
|
||||
gitlabProjectId: 'proj',
|
||||
gitlabTriggerToken: 'tok',
|
||||
gitlabApiUrl: 'https://gitlab.com',
|
||||
gitlabRef: 'main',
|
||||
ansibleInventory: '/inv',
|
||||
ansiblePlaybook: '/pb.yml',
|
||||
ansibleExtraVars: '',
|
||||
ansibleVaultPassword: '',
|
||||
} as BuildParameters;
|
||||
|
||||
const instances = Object.entries(strategies).map(([strategy, ProviderClass]) => {
|
||||
const provider = new ProviderClass(params);
|
||||
return { strategy, className: provider.constructor.name };
|
||||
});
|
||||
|
||||
// Verify all four strategies produce different provider classes
|
||||
const classNames = instances.map((i) => i.className);
|
||||
const uniqueClassNames = new Set(classNames);
|
||||
expect(uniqueClassNames.size).toBe(4);
|
||||
|
||||
// Verify expected mapping
|
||||
expect(instances.find((i) => i.strategy === 'remote-powershell')!.className).toBe('RemotePowershellProvider');
|
||||
expect(instances.find((i) => i.strategy === 'github-actions')!.className).toBe('GitHubActionsProvider');
|
||||
expect(instances.find((i) => i.strategy === 'gitlab-ci')!.className).toBe('GitLabCIProvider');
|
||||
expect(instances.find((i) => i.strategy === 'ansible')!.className).toBe('AnsibleProvider');
|
||||
});
|
||||
|
||||
it('all providers implement ProviderInterface methods', () => {
|
||||
const params = {
|
||||
remotePowershellHost: 'host',
|
||||
githubActionsRepo: 'org/repo',
|
||||
githubActionsWorkflow: 'ci.yml',
|
||||
githubActionsToken: 'token',
|
||||
gitlabProjectId: 'proj',
|
||||
gitlabTriggerToken: 'tok',
|
||||
ansibleInventory: '/inv',
|
||||
} as BuildParameters;
|
||||
|
||||
const providers = [
|
||||
new RemotePowershellProvider(params),
|
||||
new GitHubActionsProvider(params),
|
||||
new GitLabCIProvider(params),
|
||||
new AnsibleProvider(params),
|
||||
];
|
||||
|
||||
const requiredMethods = [
|
||||
'setupWorkflow',
|
||||
'runTaskInWorkflow',
|
||||
'cleanupWorkflow',
|
||||
'garbageCollect',
|
||||
'listResources',
|
||||
'listWorkflow',
|
||||
'watchWorkflow',
|
||||
];
|
||||
|
||||
for (const provider of providers) {
|
||||
for (const method of requiredMethods) {
|
||||
expect(typeof (provider as any)[method]).toBe('function');
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,166 +0,0 @@
|
||||
import BuildParameters from '../../../build-parameters';
|
||||
import { OrchestratorSystem } from '../../services/core/orchestrator-system';
|
||||
import OrchestratorEnvironmentVariable from '../../options/orchestrator-environment-variable';
|
||||
import OrchestratorLogger from '../../services/core/orchestrator-logger';
|
||||
import { ProviderInterface } from '../provider-interface';
|
||||
import OrchestratorSecret from '../../options/orchestrator-secret';
|
||||
import { ProviderResource } from '../provider-resource';
|
||||
import { ProviderWorkflow } from '../provider-workflow';
|
||||
|
||||
/**
|
||||
* Remote PowerShell provider — executes Unity builds on remote machines
|
||||
* via PowerShell Remoting (WinRM or SSH).
|
||||
*
|
||||
* Use case: Teams with dedicated build machines not part of a CI system.
|
||||
*/
|
||||
class RemotePowershellProvider implements ProviderInterface {
|
||||
private buildParameters: BuildParameters;
|
||||
private host: string;
|
||||
private transport: string;
|
||||
private credential: string;
|
||||
private sessionId: string = '';
|
||||
|
||||
constructor(buildParameters: BuildParameters) {
|
||||
this.buildParameters = buildParameters;
|
||||
this.host = buildParameters.remotePowershellHost || '';
|
||||
this.transport = buildParameters.remotePowershellTransport || 'wsman';
|
||||
this.credential = buildParameters.remotePowershellCredential || '';
|
||||
}
|
||||
|
||||
async setupWorkflow(
|
||||
buildGuid: string,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
buildParameters: BuildParameters,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
branchName: string,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
defaultSecretsArray: { ParameterKey: string; EnvironmentVariable: string; ParameterValue: string }[],
|
||||
): Promise<void> {
|
||||
OrchestratorLogger.log(`[RemotePowershell] Setting up remote session to ${this.host} via ${this.transport}`);
|
||||
|
||||
if (!this.host) {
|
||||
throw new Error('remotePowershellHost is required for the remote-powershell provider');
|
||||
}
|
||||
|
||||
// Test connectivity
|
||||
const testCommand = this.buildPwshCommand(`Test-WSMan -ComputerName "${this.host}" -ErrorAction Stop`);
|
||||
try {
|
||||
await OrchestratorSystem.Run(testCommand);
|
||||
OrchestratorLogger.log(`[RemotePowershell] Connection test passed`);
|
||||
} catch (error: any) {
|
||||
throw new Error(`Failed to connect to remote host ${this.host}: ${error.message || error}`);
|
||||
}
|
||||
|
||||
this.sessionId = buildGuid;
|
||||
OrchestratorLogger.log(`[RemotePowershell] Session ${this.sessionId} ready`);
|
||||
}
|
||||
|
||||
async runTaskInWorkflow(
|
||||
buildGuid: string,
|
||||
image: string,
|
||||
commands: string,
|
||||
mountdir: string,
|
||||
workingdir: string,
|
||||
environment: OrchestratorEnvironmentVariable[],
|
||||
secrets: OrchestratorSecret[],
|
||||
): Promise<string> {
|
||||
OrchestratorLogger.log(`[RemotePowershell] Executing task on ${this.host}`);
|
||||
|
||||
// Build environment variable block for remote session
|
||||
const environmentBlock = environment.map((element) => `$env:${element.name} = '${element.value}'`).join('; ');
|
||||
|
||||
const secretBlock = secrets
|
||||
.map((secret) => `$env:${secret.EnvironmentVariable} = '${secret.ParameterValue}'`)
|
||||
.join('; ');
|
||||
|
||||
// Wrap commands for remote execution
|
||||
const remoteScript = [environmentBlock, secretBlock, `Set-Location "${workingdir}"`, commands]
|
||||
.filter(Boolean)
|
||||
.join('; ');
|
||||
|
||||
const invokeCommand = this.buildInvokeCommand(remoteScript);
|
||||
|
||||
try {
|
||||
const output = await OrchestratorSystem.Run(invokeCommand);
|
||||
OrchestratorLogger.log(`[RemotePowershell] Task completed successfully`);
|
||||
|
||||
return output;
|
||||
} catch (error: any) {
|
||||
OrchestratorLogger.logWarning(`[RemotePowershell] Task failed: ${error.message || error}`);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async cleanupWorkflow(
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
buildParameters: BuildParameters,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
branchName: string,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
defaultSecretsArray: { ParameterKey: string; EnvironmentVariable: string; ParameterValue: string }[],
|
||||
): Promise<void> {
|
||||
OrchestratorLogger.log(`[RemotePowershell] Cleaning up session ${this.sessionId}`);
|
||||
|
||||
// Remote sessions are stateless per invocation — no cleanup needed
|
||||
}
|
||||
|
||||
async garbageCollect(
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
filter: string,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
previewOnly: boolean,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
olderThan: Number,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
fullCache: boolean,
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
baseDependencies: boolean,
|
||||
): Promise<string> {
|
||||
OrchestratorLogger.log(`[RemotePowershell] Garbage collection not supported for remote PowerShell provider`);
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
async listResources(): Promise<ProviderResource[]> {
|
||||
const resource = new ProviderResource();
|
||||
resource.Name = this.host;
|
||||
|
||||
return [resource];
|
||||
}
|
||||
|
||||
async listWorkflow(): Promise<ProviderWorkflow[]> {
|
||||
return [];
|
||||
}
|
||||
|
||||
async watchWorkflow(): Promise<string> {
|
||||
return '';
|
||||
}
|
||||
|
||||
private buildPwshCommand(script: string): string {
|
||||
return `pwsh -NoProfile -NonInteractive -Command "${script.replace(/"/g, '\\"')}"`;
|
||||
}
|
||||
|
||||
private buildInvokeCommand(remoteScript: string): string {
|
||||
const escapedScript = remoteScript.replace(/"/g, '\\"').replace(/'/g, "''");
|
||||
|
||||
if (this.transport === 'ssh') {
|
||||
return `pwsh -NoProfile -NonInteractive -Command "Invoke-Command -HostName '${this.host}' -ScriptBlock { ${escapedScript} }"`;
|
||||
}
|
||||
|
||||
// WinRM (default)
|
||||
// Split on the FIRST colon only — passwords may contain colons
|
||||
let credentialPart = '';
|
||||
if (this.credential) {
|
||||
const colonIndex = this.credential.indexOf(':');
|
||||
if (colonIndex === -1) {
|
||||
throw new Error('remotePowershellCredential must be in "username:password" format (no colon found)');
|
||||
}
|
||||
const user = this.credential.substring(0, colonIndex);
|
||||
const pass = this.credential.substring(colonIndex + 1);
|
||||
credentialPart = `-Credential (New-Object PSCredential('${user}', (ConvertTo-SecureString '${pass}' -AsPlainText -Force)))`;
|
||||
}
|
||||
|
||||
return `pwsh -NoProfile -NonInteractive -Command "Invoke-Command -ComputerName '${this.host}' ${credentialPart} -ScriptBlock { ${escapedScript} }"`;
|
||||
}
|
||||
}
|
||||
export default RemotePowershellProvider;
|
||||
@@ -1,264 +0,0 @@
|
||||
import RemotePowershellProvider from '.';
|
||||
import BuildParameters from '../../../build-parameters';
|
||||
import { OrchestratorSystem } from '../../services/core/orchestrator-system';
|
||||
import OrchestratorLogger from '../../services/core/orchestrator-logger';
|
||||
|
||||
jest.mock('../../services/core/orchestrator-system');
|
||||
jest.mock('../../services/core/orchestrator-logger');
|
||||
|
||||
const mockRun = OrchestratorSystem.Run as jest.MockedFunction<typeof OrchestratorSystem.Run>;
|
||||
const mockLog = OrchestratorLogger.log as jest.MockedFunction<typeof OrchestratorLogger.log>;
|
||||
const mockLogWarning = OrchestratorLogger.logWarning as jest.MockedFunction<typeof OrchestratorLogger.logWarning>;
|
||||
|
||||
function createBuildParameters(overrides: Partial<BuildParameters> = {}): BuildParameters {
|
||||
return {
|
||||
remotePowershellHost: 'build-server-01.internal',
|
||||
remotePowershellTransport: 'wsman',
|
||||
remotePowershellCredential: 'admin:P@ssw0rd!',
|
||||
...overrides,
|
||||
} as BuildParameters;
|
||||
}
|
||||
|
||||
describe('RemotePowershellProvider', () => {
|
||||
let provider: RemotePowershellProvider;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
provider = new RemotePowershellProvider(createBuildParameters());
|
||||
});
|
||||
|
||||
describe('constructor', () => {
|
||||
it('defaults transport to wsman when not specified', () => {
|
||||
const params = createBuildParameters({ remotePowershellTransport: undefined });
|
||||
const p = new RemotePowershellProvider(params);
|
||||
expect(p).toBeDefined();
|
||||
});
|
||||
|
||||
it('accepts ssh transport', () => {
|
||||
const params = createBuildParameters({ remotePowershellTransport: 'ssh' });
|
||||
const p = new RemotePowershellProvider(params);
|
||||
expect(p).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('setupWorkflow', () => {
|
||||
it('tests WinRM connectivity via Test-WSMan and logs success', async () => {
|
||||
mockRun.mockResolvedValueOnce('wsman output');
|
||||
|
||||
await provider.setupWorkflow('guid-123', createBuildParameters(), 'main', []);
|
||||
|
||||
expect(mockRun).toHaveBeenCalledTimes(1);
|
||||
const command = mockRun.mock.calls[0][0];
|
||||
expect(command).toContain('pwsh -NoProfile -NonInteractive');
|
||||
expect(command).toContain('Test-WSMan');
|
||||
expect(command).toContain('build-server-01.internal');
|
||||
expect(mockLog).toHaveBeenCalledWith(expect.stringContaining('Connection test passed'));
|
||||
});
|
||||
|
||||
it('sets session ID to the build GUID', async () => {
|
||||
mockRun.mockResolvedValueOnce('');
|
||||
|
||||
await provider.setupWorkflow('my-build-guid', createBuildParameters(), 'main', []);
|
||||
|
||||
expect(mockLog).toHaveBeenCalledWith(expect.stringContaining('my-build-guid'));
|
||||
expect(mockLog).toHaveBeenCalledWith(expect.stringContaining('ready'));
|
||||
});
|
||||
|
||||
it('throws when host is not configured', async () => {
|
||||
const params = createBuildParameters({ remotePowershellHost: '' });
|
||||
provider = new RemotePowershellProvider(params);
|
||||
|
||||
await expect(provider.setupWorkflow('guid-123', params, 'main', [])).rejects.toThrow(
|
||||
'remotePowershellHost is required',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws descriptive error when connectivity test fails', async () => {
|
||||
mockRun.mockRejectedValueOnce(new Error('WinRM service not running'));
|
||||
|
||||
await expect(provider.setupWorkflow('guid-123', createBuildParameters(), 'main', [])).rejects.toThrow(
|
||||
'Failed to connect to remote host build-server-01.internal',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('runTaskInWorkflow', () => {
|
||||
it('constructs WinRM Invoke-Command with credential and returns output', async () => {
|
||||
mockRun.mockResolvedValueOnce('Build succeeded!');
|
||||
|
||||
const result = await provider.runTaskInWorkflow(
|
||||
'guid-run1',
|
||||
'unused-image',
|
||||
'Unity.exe -batchmode -buildTarget Win64',
|
||||
'/mount',
|
||||
'C:\\Projects\\MyGame',
|
||||
[],
|
||||
[],
|
||||
);
|
||||
|
||||
expect(result).toBe('Build succeeded!');
|
||||
|
||||
const command = mockRun.mock.calls[0][0];
|
||||
expect(command).toContain('pwsh -NoProfile -NonInteractive');
|
||||
expect(command).toContain("Invoke-Command -ComputerName 'build-server-01.internal'");
|
||||
expect(command).toContain('-Credential');
|
||||
expect(command).toContain('New-Object PSCredential');
|
||||
expect(command).toContain('-ScriptBlock');
|
||||
expect(command).toContain('Set-Location');
|
||||
});
|
||||
|
||||
it('constructs SSH Invoke-Command when transport is ssh', async () => {
|
||||
const params = createBuildParameters({ remotePowershellTransport: 'ssh' });
|
||||
provider = new RemotePowershellProvider(params);
|
||||
mockRun.mockResolvedValueOnce('SSH build output');
|
||||
|
||||
const result = await provider.runTaskInWorkflow('guid-ssh', 'img', 'build', '/m', '/w', [], []);
|
||||
|
||||
expect(result).toBe('SSH build output');
|
||||
|
||||
const command = mockRun.mock.calls[0][0];
|
||||
expect(command).toContain("Invoke-Command -HostName 'build-server-01.internal'");
|
||||
expect(command).not.toContain('-ComputerName');
|
||||
expect(command).not.toContain('-Credential');
|
||||
});
|
||||
|
||||
it('includes environment variables in the remote script block', async () => {
|
||||
mockRun.mockResolvedValueOnce('output');
|
||||
|
||||
const env = [
|
||||
{ name: 'UNITY_LICENSE', value: 'license-data-abc' },
|
||||
{ name: 'BUILD_TARGET', value: 'StandaloneWindows64' },
|
||||
];
|
||||
|
||||
await provider.runTaskInWorkflow('guid-env', 'img', 'build-cmd', '/m', '/w', env as any, []);
|
||||
|
||||
const command = mockRun.mock.calls[0][0];
|
||||
expect(command).toContain('$env:UNITY_LICENSE');
|
||||
expect(command).toContain('$env:BUILD_TARGET');
|
||||
});
|
||||
|
||||
it('includes secrets in the remote script block', async () => {
|
||||
mockRun.mockResolvedValueOnce('output');
|
||||
|
||||
const secrets = [{ ParameterKey: 'key1', EnvironmentVariable: 'SECRET_KEY', ParameterValue: 'secret-val-123' }];
|
||||
|
||||
await provider.runTaskInWorkflow('guid-sec', 'img', 'build-cmd', '/m', '/w', [], secrets as any);
|
||||
|
||||
const command = mockRun.mock.calls[0][0];
|
||||
expect(command).toContain('$env:SECRET_KEY');
|
||||
});
|
||||
|
||||
it('does not include credential in plaintext log output when using WinRM', async () => {
|
||||
mockRun.mockResolvedValueOnce('output');
|
||||
|
||||
await provider.runTaskInWorkflow('guid-cred', 'img', 'cmd', '/m', '/w', [], []);
|
||||
|
||||
// The credential is used via ConvertTo-SecureString, not logged directly
|
||||
const command = mockRun.mock.calls[0][0];
|
||||
expect(command).toContain('ConvertTo-SecureString');
|
||||
expect(command).toContain('-AsPlainText -Force');
|
||||
});
|
||||
|
||||
it('omits credential part when no credential is configured (WinRM)', async () => {
|
||||
const params = createBuildParameters({ remotePowershellCredential: '' });
|
||||
provider = new RemotePowershellProvider(params);
|
||||
mockRun.mockResolvedValueOnce('output');
|
||||
|
||||
await provider.runTaskInWorkflow('guid-nocred', 'img', 'cmd', '/m', '/w', [], []);
|
||||
|
||||
const command = mockRun.mock.calls[0][0];
|
||||
expect(command).toContain("Invoke-Command -ComputerName 'build-server-01.internal'");
|
||||
expect(command).not.toContain('-Credential');
|
||||
expect(command).not.toContain('PSCredential');
|
||||
});
|
||||
|
||||
it('throws and logs warning when remote execution fails', async () => {
|
||||
const execError = new Error('Remote execution failed: access denied');
|
||||
mockRun.mockRejectedValueOnce(execError);
|
||||
|
||||
await expect(provider.runTaskInWorkflow('guid-fail', 'img', 'cmd', '/m', '/w', [], [])).rejects.toThrow(
|
||||
'Remote execution failed',
|
||||
);
|
||||
|
||||
expect(mockLogWarning).toHaveBeenCalledWith(expect.stringContaining('Task failed'));
|
||||
});
|
||||
|
||||
it('preserves passwords containing colons when splitting credentials', async () => {
|
||||
const params = createBuildParameters({
|
||||
remotePowershellCredential: 'admin:P@ss:w0rd:with:colons!',
|
||||
});
|
||||
provider = new RemotePowershellProvider(params);
|
||||
mockRun.mockResolvedValueOnce('output');
|
||||
|
||||
await provider.runTaskInWorkflow('guid-colon', 'img', 'cmd', '/m', '/w', [], []);
|
||||
|
||||
const command = mockRun.mock.calls[0][0];
|
||||
expect(command).toContain("PSCredential('admin'");
|
||||
expect(command).toContain("ConvertTo-SecureString 'P@ss:w0rd:with:colons!'");
|
||||
});
|
||||
|
||||
it('throws when credential has no colon separator', async () => {
|
||||
const params = createBuildParameters({
|
||||
remotePowershellCredential: 'nocolonhere',
|
||||
});
|
||||
provider = new RemotePowershellProvider(params);
|
||||
|
||||
await expect(provider.runTaskInWorkflow('guid-badcred', 'img', 'cmd', '/m', '/w', [], [])).rejects.toThrow(
|
||||
'username:password',
|
||||
);
|
||||
});
|
||||
|
||||
it('sets working directory in the remote script', async () => {
|
||||
mockRun.mockResolvedValueOnce('output');
|
||||
|
||||
await provider.runTaskInWorkflow('guid-wd', 'img', 'cmd', '/m', 'D:\\Builds\\Project', [], []);
|
||||
|
||||
const command = mockRun.mock.calls[0][0];
|
||||
expect(command).toContain('Set-Location');
|
||||
expect(command).toContain('D:\\Builds\\Project');
|
||||
});
|
||||
});
|
||||
|
||||
describe('cleanupWorkflow', () => {
|
||||
it('completes without error and logs session cleanup', async () => {
|
||||
// Setup first to set sessionId
|
||||
mockRun.mockResolvedValueOnce('');
|
||||
await provider.setupWorkflow('guid-cleanup', createBuildParameters(), 'main', []);
|
||||
|
||||
await provider.cleanupWorkflow(createBuildParameters(), 'main', []);
|
||||
|
||||
expect(mockLog).toHaveBeenCalledWith(expect.stringContaining('Cleaning up session'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('garbageCollect', () => {
|
||||
it('returns empty string and logs not-supported message', async () => {
|
||||
const result = await provider.garbageCollect('', false, 0, false, false);
|
||||
expect(result).toBe('');
|
||||
expect(mockLog).toHaveBeenCalledWith(expect.stringContaining('not supported'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('listResources', () => {
|
||||
it('returns the configured host as a resource', async () => {
|
||||
const resources = await provider.listResources();
|
||||
|
||||
expect(resources).toHaveLength(1);
|
||||
expect(resources[0].Name).toBe('build-server-01.internal');
|
||||
});
|
||||
});
|
||||
|
||||
describe('listWorkflow', () => {
|
||||
it('returns empty array (not implemented)', async () => {
|
||||
const workflows = await provider.listWorkflow();
|
||||
expect(workflows).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('watchWorkflow', () => {
|
||||
it('returns empty string (not implemented)', async () => {
|
||||
const result = await provider.watchWorkflow();
|
||||
expect(result).toBe('');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,446 @@
|
||||
import fs from 'node:fs';
|
||||
import * as core from '@actions/core';
|
||||
import { SecretSourceService, validateSecretKey } from './secret-source-service';
|
||||
|
||||
jest.mock('node:fs');
|
||||
jest.mock('@actions/core', () => ({
|
||||
setSecret: jest.fn(),
|
||||
info: jest.fn(),
|
||||
warning: jest.fn(),
|
||||
error: jest.fn(),
|
||||
}));
|
||||
jest.mock('../core/orchestrator-system', () => ({
|
||||
OrchestratorSystem: {
|
||||
Run: jest.fn().mockResolvedValue(''),
|
||||
},
|
||||
}));
|
||||
jest.mock('../core/orchestrator-logger', () => ({
|
||||
__esModule: true,
|
||||
default: {
|
||||
log: jest.fn(),
|
||||
logWarning: jest.fn(),
|
||||
error: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockFs = fs as jest.Mocked<typeof fs>;
|
||||
|
||||
describe('SecretSourceService', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('validateSecretKey', () => {
|
||||
it('should accept alphanumeric keys', () => {
|
||||
expect(validateSecretKey('MY_SECRET_KEY')).toBe('MY_SECRET_KEY');
|
||||
});
|
||||
|
||||
it('should accept keys with hyphens', () => {
|
||||
expect(validateSecretKey('my-secret-key')).toBe('my-secret-key');
|
||||
});
|
||||
|
||||
it('should accept keys with dots', () => {
|
||||
expect(validateSecretKey('my.secret.key')).toBe('my.secret.key');
|
||||
});
|
||||
|
||||
it('should accept keys with forward slashes', () => {
|
||||
expect(validateSecretKey('path/to/secret')).toBe('path/to/secret');
|
||||
});
|
||||
|
||||
it('should accept keys with mixed valid characters', () => {
|
||||
expect(validateSecretKey('my-app/prod_db.password')).toBe('my-app/prod_db.password');
|
||||
});
|
||||
|
||||
it('should reject keys with semicolons (shell injection)', () => {
|
||||
expect(() => validateSecretKey('; rm -rf /')).toThrow('Invalid secret key name');
|
||||
});
|
||||
|
||||
it('should reject keys with backticks (command substitution)', () => {
|
||||
expect(() => validateSecretKey('`whoami`')).toThrow('Invalid secret key name');
|
||||
});
|
||||
|
||||
it('should reject keys with dollar signs (variable expansion)', () => {
|
||||
expect(() => validateSecretKey('$HOME')).toThrow('Invalid secret key name');
|
||||
});
|
||||
|
||||
it('should reject keys with pipe characters', () => {
|
||||
expect(() => validateSecretKey('key | cat /etc/passwd')).toThrow('Invalid secret key name');
|
||||
});
|
||||
|
||||
it('should reject keys with ampersands', () => {
|
||||
expect(() => validateSecretKey('key && echo pwned')).toThrow('Invalid secret key name');
|
||||
});
|
||||
|
||||
it('should reject keys with newlines', () => {
|
||||
expect(() => validateSecretKey('key\nmalicious')).toThrow('Invalid secret key name');
|
||||
});
|
||||
|
||||
it('should reject keys with quotes', () => {
|
||||
expect(() => validateSecretKey('"key"')).toThrow('Invalid secret key name');
|
||||
expect(() => validateSecretKey("'key'")).toThrow('Invalid secret key name');
|
||||
});
|
||||
|
||||
it('should reject keys with parentheses (subshell)', () => {
|
||||
expect(() => validateSecretKey('$(whoami)')).toThrow('Invalid secret key name');
|
||||
});
|
||||
|
||||
it('should reject empty keys', () => {
|
||||
expect(() => validateSecretKey('')).toThrow('Invalid secret key name');
|
||||
});
|
||||
|
||||
it('should reject keys with spaces', () => {
|
||||
expect(() => validateSecretKey('key with spaces')).toThrow('Invalid secret key name');
|
||||
});
|
||||
});
|
||||
|
||||
describe('isPremadeSource', () => {
|
||||
it('should return true for aws-secrets-manager', () => {
|
||||
expect(SecretSourceService.isPremadeSource('aws-secrets-manager')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for aws-secret-manager (legacy alias)', () => {
|
||||
expect(SecretSourceService.isPremadeSource('aws-secret-manager')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for aws-parameter-store', () => {
|
||||
expect(SecretSourceService.isPremadeSource('aws-parameter-store')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for gcp-secret-manager', () => {
|
||||
expect(SecretSourceService.isPremadeSource('gcp-secret-manager')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for azure-key-vault', () => {
|
||||
expect(SecretSourceService.isPremadeSource('azure-key-vault')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for hashicorp-vault', () => {
|
||||
expect(SecretSourceService.isPremadeSource('hashicorp-vault')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for hashicorp-vault-kv1', () => {
|
||||
expect(SecretSourceService.isPremadeSource('hashicorp-vault-kv1')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for vault (short alias)', () => {
|
||||
expect(SecretSourceService.isPremadeSource('vault')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for unknown source', () => {
|
||||
expect(SecretSourceService.isPremadeSource('unknown-source')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAvailableSources', () => {
|
||||
it('should return all premade source names', () => {
|
||||
const sources = SecretSourceService.getAvailableSources();
|
||||
expect(sources).toContain('aws-secrets-manager');
|
||||
expect(sources).toContain('aws-parameter-store');
|
||||
expect(sources).toContain('gcp-secret-manager');
|
||||
expect(sources).toContain('azure-key-vault');
|
||||
expect(sources).toContain('hashicorp-vault');
|
||||
expect(sources).toContain('hashicorp-vault-kv1');
|
||||
expect(sources).toContain('vault');
|
||||
expect(sources.length).toBeGreaterThanOrEqual(8);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveSource', () => {
|
||||
it('should resolve premade source by name', () => {
|
||||
const source = SecretSourceService.resolveSource('aws-secrets-manager');
|
||||
expect(source).toBeDefined();
|
||||
expect(source!.name).toBe('aws-secrets-manager');
|
||||
expect(source!.command).toContain('secretsmanager');
|
||||
});
|
||||
|
||||
it('should resolve custom command with {0} placeholder', () => {
|
||||
const source = SecretSourceService.resolveSource('vault kv get -field=value secret/{0}');
|
||||
expect(source).toBeDefined();
|
||||
expect(source!.name).toBe('custom-command');
|
||||
expect(source!.command).toContain('{0}');
|
||||
});
|
||||
|
||||
it('should resolve command with spaces as custom command', () => {
|
||||
const source = SecretSourceService.resolveSource('my-tool get-secret');
|
||||
expect(source).toBeDefined();
|
||||
expect(source!.name).toBe('custom-command');
|
||||
});
|
||||
|
||||
it('should return undefined for unknown single-word source', () => {
|
||||
const source = SecretSourceService.resolveSource('unknown');
|
||||
expect(source).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetchSecret', () => {
|
||||
it('should run the command with {0} replaced by key', async () => {
|
||||
const { OrchestratorSystem } = require('../core/orchestrator-system');
|
||||
OrchestratorSystem.Run.mockResolvedValue('my-secret-value');
|
||||
|
||||
const source = SecretSourceService.resolveSource('aws-secrets-manager')!;
|
||||
const result = await SecretSourceService.fetchSecret(source, 'MY_SECRET');
|
||||
|
||||
expect(result).toBe('my-secret-value');
|
||||
expect(OrchestratorSystem.Run).toHaveBeenCalledWith(expect.stringContaining('MY_SECRET'), false, true);
|
||||
});
|
||||
|
||||
it('should parse JSON output when parseOutput is json-field', async () => {
|
||||
const { OrchestratorSystem } = require('../core/orchestrator-system');
|
||||
OrchestratorSystem.Run.mockResolvedValue(JSON.stringify({ value: 'extracted-secret' }));
|
||||
|
||||
const source = {
|
||||
name: 'test-source',
|
||||
command: 'fetch {0}',
|
||||
parseOutput: 'json-field' as const,
|
||||
jsonField: 'value',
|
||||
};
|
||||
const result = await SecretSourceService.fetchSecret(source, 'KEY');
|
||||
|
||||
expect(result).toBe('extracted-secret');
|
||||
});
|
||||
|
||||
it('should fall back to raw output on invalid JSON with json-field mode', async () => {
|
||||
const { OrchestratorSystem } = require('../core/orchestrator-system');
|
||||
OrchestratorSystem.Run.mockResolvedValue('not-json');
|
||||
|
||||
const source = {
|
||||
name: 'test-source',
|
||||
command: 'fetch {0}',
|
||||
parseOutput: 'json-field' as const,
|
||||
jsonField: 'value',
|
||||
};
|
||||
const result = await SecretSourceService.fetchSecret(source, 'KEY');
|
||||
|
||||
expect(result).toBe('not-json');
|
||||
});
|
||||
|
||||
it('should return empty string on command failure', async () => {
|
||||
const { OrchestratorSystem } = require('../core/orchestrator-system');
|
||||
OrchestratorSystem.Run.mockRejectedValue(new Error('command not found'));
|
||||
|
||||
const source = SecretSourceService.resolveSource('aws-secrets-manager')!;
|
||||
const result = await SecretSourceService.fetchSecret(source, 'KEY');
|
||||
|
||||
expect(result).toBe('');
|
||||
});
|
||||
|
||||
it('should reject keys with shell injection characters', async () => {
|
||||
const source = SecretSourceService.resolveSource('aws-secrets-manager')!;
|
||||
|
||||
await expect(SecretSourceService.fetchSecret(source, '; rm -rf /')).rejects.toThrow('Invalid secret key name');
|
||||
});
|
||||
|
||||
it('should reject keys with command substitution', async () => {
|
||||
const source = SecretSourceService.resolveSource('aws-secrets-manager')!;
|
||||
|
||||
await expect(SecretSourceService.fetchSecret(source, '$(whoami)')).rejects.toThrow('Invalid secret key name');
|
||||
});
|
||||
|
||||
it('should reject keys with backtick command substitution', async () => {
|
||||
const source = SecretSourceService.resolveSource('aws-secrets-manager')!;
|
||||
|
||||
await expect(SecretSourceService.fetchSecret(source, '`cat /etc/passwd`')).rejects.toThrow(
|
||||
'Invalid secret key name',
|
||||
);
|
||||
});
|
||||
|
||||
it('should accept keys with valid path-like patterns', async () => {
|
||||
const { OrchestratorSystem } = require('../core/orchestrator-system');
|
||||
OrchestratorSystem.Run.mockResolvedValue('secret-value');
|
||||
|
||||
const source = SecretSourceService.resolveSource('aws-secrets-manager')!;
|
||||
const result = await SecretSourceService.fetchSecret(source, 'prod/database/password');
|
||||
|
||||
expect(result).toBe('secret-value');
|
||||
});
|
||||
|
||||
it('should mask fetched secret values with core.setSecret', async () => {
|
||||
const { OrchestratorSystem } = require('../core/orchestrator-system');
|
||||
OrchestratorSystem.Run.mockResolvedValue('super-secret-value');
|
||||
|
||||
const source = SecretSourceService.resolveSource('aws-secrets-manager')!;
|
||||
await SecretSourceService.fetchSecret(source, 'MY_SECRET');
|
||||
|
||||
expect(core.setSecret).toHaveBeenCalledWith('super-secret-value');
|
||||
});
|
||||
|
||||
it('should not mask empty secret values', async () => {
|
||||
const { OrchestratorSystem } = require('../core/orchestrator-system');
|
||||
OrchestratorSystem.Run.mockResolvedValue('');
|
||||
|
||||
const source = SecretSourceService.resolveSource('aws-secrets-manager')!;
|
||||
await SecretSourceService.fetchSecret(source, 'MY_SECRET');
|
||||
|
||||
expect(core.setSecret).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should mask JSON-extracted secret values', async () => {
|
||||
const { OrchestratorSystem } = require('../core/orchestrator-system');
|
||||
OrchestratorSystem.Run.mockResolvedValue(JSON.stringify({ value: 'json-secret' }));
|
||||
|
||||
const source = {
|
||||
name: 'test-source',
|
||||
command: 'fetch {0}',
|
||||
parseOutput: 'json-field' as const,
|
||||
jsonField: 'value',
|
||||
};
|
||||
await SecretSourceService.fetchSecret(source, 'KEY');
|
||||
|
||||
expect(core.setSecret).toHaveBeenCalledWith('json-secret');
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetchFromEnv', () => {
|
||||
it('should return env var value when set', () => {
|
||||
process.env.TEST_SECRET_KEY = 'env-value';
|
||||
const result = SecretSourceService.fetchFromEnv('TEST_SECRET_KEY');
|
||||
expect(result).toBe('env-value');
|
||||
delete process.env.TEST_SECRET_KEY;
|
||||
});
|
||||
|
||||
it('should return empty string when env var is not set', () => {
|
||||
const result = SecretSourceService.fetchFromEnv('NONEXISTENT_KEY_12345');
|
||||
expect(result).toBe('');
|
||||
});
|
||||
|
||||
it('should mask env var values with core.setSecret', () => {
|
||||
process.env.TEST_MASK_KEY = 'masked-env-value';
|
||||
SecretSourceService.fetchFromEnv('TEST_MASK_KEY');
|
||||
expect(core.setSecret).toHaveBeenCalledWith('masked-env-value');
|
||||
delete process.env.TEST_MASK_KEY;
|
||||
});
|
||||
|
||||
it('should not mask empty env var values', () => {
|
||||
const result = SecretSourceService.fetchFromEnv('NONEXISTENT_KEY_99999');
|
||||
expect(result).toBe('');
|
||||
expect(core.setSecret).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetchAll', () => {
|
||||
it('should fetch all keys from env source', async () => {
|
||||
process.env.KEY_A = 'val-a';
|
||||
process.env.KEY_B = 'val-b';
|
||||
|
||||
const results = await SecretSourceService.fetchAll('env', ['KEY_A', 'KEY_B']);
|
||||
|
||||
expect(results.KEY_A).toBe('val-a');
|
||||
expect(results.KEY_B).toBe('val-b');
|
||||
|
||||
delete process.env.KEY_A;
|
||||
delete process.env.KEY_B;
|
||||
});
|
||||
|
||||
it('should fetch all keys from premade source', async () => {
|
||||
const { OrchestratorSystem } = require('../core/orchestrator-system');
|
||||
OrchestratorSystem.Run.mockResolvedValueOnce('secret-1').mockResolvedValueOnce('secret-2');
|
||||
|
||||
const results = await SecretSourceService.fetchAll('aws-parameter-store', ['param1', 'param2']);
|
||||
|
||||
expect(results.param1).toBe('secret-1');
|
||||
expect(results.param2).toBe('secret-2');
|
||||
expect(OrchestratorSystem.Run).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('should return empty results for unknown source', async () => {
|
||||
const results = await SecretSourceService.fetchAll('unknown', ['key1']);
|
||||
expect(results).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadFromYaml', () => {
|
||||
it('should return empty array when file does not exist', () => {
|
||||
(mockFs.existsSync as jest.Mock).mockReturnValue(false);
|
||||
const result = SecretSourceService.loadFromYaml('/nonexistent.yml');
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it('should parse valid YAML source definitions', () => {
|
||||
(mockFs.existsSync as jest.Mock).mockReturnValue(true);
|
||||
(mockFs.readFileSync as jest.Mock).mockReturnValue(`
|
||||
sources:
|
||||
- name: my-vault
|
||||
command: 'vault kv get -field=value secret/{0}'
|
||||
- name: my-api
|
||||
command: 'curl -s https://api.example.com/{0}'
|
||||
parseOutput: json-field
|
||||
jsonField: secret_value
|
||||
`);
|
||||
|
||||
const result = SecretSourceService.loadFromYaml('/sources.yml');
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result[0].name).toBe('my-vault');
|
||||
expect(result[0].command).toBe('vault kv get -field=value secret/{0}');
|
||||
expect(result[1].name).toBe('my-api');
|
||||
expect(result[1].parseOutput).toBe('json-field');
|
||||
expect(result[1].jsonField).toBe('secret_value');
|
||||
});
|
||||
|
||||
it('should handle YAML with single source', () => {
|
||||
(mockFs.existsSync as jest.Mock).mockReturnValue(true);
|
||||
(mockFs.readFileSync as jest.Mock).mockReturnValue(`
|
||||
sources:
|
||||
- name: simple
|
||||
command: echo {0}
|
||||
`);
|
||||
|
||||
const result = SecretSourceService.loadFromYaml('/simple.yml');
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].name).toBe('simple');
|
||||
});
|
||||
|
||||
it('should return empty array on parse error', () => {
|
||||
(mockFs.existsSync as jest.Mock).mockReturnValue(true);
|
||||
(mockFs.readFileSync as jest.Mock).mockImplementation(() => {
|
||||
throw new Error('Permission denied');
|
||||
});
|
||||
|
||||
const result = SecretSourceService.loadFromYaml('/error.yml');
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('premade source commands', () => {
|
||||
it('aws-secrets-manager uses --query SecretString', () => {
|
||||
const source = SecretSourceService.resolveSource('aws-secrets-manager')!;
|
||||
expect(source.command).toContain('--query SecretString');
|
||||
expect(source.command).toContain('--output text');
|
||||
});
|
||||
|
||||
it('aws-parameter-store uses --with-decryption', () => {
|
||||
const source = SecretSourceService.resolveSource('aws-parameter-store')!;
|
||||
expect(source.command).toContain('--with-decryption');
|
||||
expect(source.command).toContain('--query Parameter.Value');
|
||||
});
|
||||
|
||||
it('gcp-secret-manager uses latest version', () => {
|
||||
const source = SecretSourceService.resolveSource('gcp-secret-manager')!;
|
||||
expect(source.command).toContain('latest');
|
||||
});
|
||||
|
||||
it('azure-key-vault uses AZURE_VAULT_NAME env var', () => {
|
||||
const source = SecretSourceService.resolveSource('azure-key-vault')!;
|
||||
expect(source.command).toContain('$AZURE_VAULT_NAME');
|
||||
});
|
||||
|
||||
it('hashicorp-vault uses vault kv get with VAULT_MOUNT', () => {
|
||||
const source = SecretSourceService.resolveSource('hashicorp-vault')!;
|
||||
expect(source.command).toContain('vault kv get');
|
||||
expect(source.command).toContain('VAULT_MOUNT');
|
||||
expect(source.command).toContain('-field=value');
|
||||
});
|
||||
|
||||
it('hashicorp-vault-kv1 uses vault read for KV v1', () => {
|
||||
const source = SecretSourceService.resolveSource('hashicorp-vault-kv1')!;
|
||||
expect(source.command).toContain('vault read');
|
||||
expect(source.command).toContain('-field=value');
|
||||
});
|
||||
|
||||
it('vault alias resolves to same command as hashicorp-vault', () => {
|
||||
const vault = SecretSourceService.resolveSource('vault')!;
|
||||
const hashicorpVault = SecretSourceService.resolveSource('hashicorp-vault')!;
|
||||
expect(vault.command).toBe(hashicorpVault.command);
|
||||
});
|
||||
});
|
||||
});
|
||||
337
src/model/orchestrator/services/secrets/secret-source-service.ts
Normal file
337
src/model/orchestrator/services/secrets/secret-source-service.ts
Normal file
@@ -0,0 +1,337 @@
|
||||
import fs from 'node:fs';
|
||||
import * as core from '@actions/core';
|
||||
import OrchestratorLogger from '../core/orchestrator-logger';
|
||||
import { OrchestratorSystem } from '../core/orchestrator-system';
|
||||
|
||||
/**
|
||||
* A secret source definition: how to fetch a secret value by key.
|
||||
*/
|
||||
export interface SecretSourceDefinition {
|
||||
name: string;
|
||||
command: string;
|
||||
parseOutput?: 'raw' | 'json-field';
|
||||
jsonField?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that a secret key name contains only safe characters.
|
||||
* Prevents shell injection when keys are interpolated into commands.
|
||||
*
|
||||
* Allowed characters: alphanumeric, hyphens, underscores, dots, forward slashes.
|
||||
*
|
||||
* @param key - The secret key name to validate
|
||||
* @returns The validated key (unchanged)
|
||||
* @throws Error if the key contains disallowed characters
|
||||
*/
|
||||
export function validateSecretKey(key: string): string {
|
||||
if (!/^[a-zA-Z0-9\-_./]+$/.test(key)) {
|
||||
throw new Error(
|
||||
`Invalid secret key name: "${key}". Keys may only contain alphanumeric characters, hyphens, underscores, dots, and forward slashes.`,
|
||||
);
|
||||
}
|
||||
|
||||
return key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mask a secret value so it does not appear in GitHub Actions logs.
|
||||
* Empty or whitespace-only values are skipped (core.setSecret would be a no-op).
|
||||
*/
|
||||
function maskSecretValue(value: string): void {
|
||||
if (value.trim().length > 0) {
|
||||
core.setSecret(value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Premade secret sources and custom YAML-based secret source definitions.
|
||||
*
|
||||
* Premade sources are string shortcuts that expand to shell commands:
|
||||
* - `aws-secrets-manager` -- AWS Secrets Manager
|
||||
* - `aws-parameter-store` -- AWS Systems Manager Parameter Store
|
||||
* - `gcp-secret-manager` -- Google Cloud Secret Manager
|
||||
* - `azure-key-vault` -- Azure Key Vault (requires AZURE_VAULT_NAME env var)
|
||||
* - `hashicorp-vault` -- HashiCorp Vault KV v2 (requires VAULT_ADDR, optionally VAULT_MOUNT)
|
||||
* - `hashicorp-vault-kv1` -- HashiCorp Vault KV v1 (requires VAULT_ADDR, optionally VAULT_MOUNT)
|
||||
* - `env` -- Read from environment variables (no shell command needed)
|
||||
*
|
||||
* Custom YAML format:
|
||||
* sources:
|
||||
* - name: my-vault
|
||||
* command: 'vault kv get -field=value secret/{0}'
|
||||
* - name: my-api
|
||||
* command: 'curl -s https://secrets.example.com/api/{0}'
|
||||
* parseOutput: json-field
|
||||
* jsonField: value
|
||||
*/
|
||||
export class SecretSourceService {
|
||||
private static readonly premadeSources: Record<string, SecretSourceDefinition> = {
|
||||
'aws-secrets-manager': {
|
||||
name: 'aws-secrets-manager',
|
||||
command: 'aws secretsmanager get-secret-value --secret-id {0} --query SecretString --output text',
|
||||
parseOutput: 'raw',
|
||||
},
|
||||
'aws-secret-manager': {
|
||||
// Alias for backward compatibility (original name in inputPullCommand)
|
||||
name: 'aws-secret-manager',
|
||||
command: 'aws secretsmanager get-secret-value --secret-id {0} --query SecretString --output text',
|
||||
parseOutput: 'raw',
|
||||
},
|
||||
'aws-parameter-store': {
|
||||
name: 'aws-parameter-store',
|
||||
command: 'aws ssm get-parameter --name {0} --with-decryption --query Parameter.Value --output text',
|
||||
parseOutput: 'raw',
|
||||
},
|
||||
'gcp-secret-manager': {
|
||||
name: 'gcp-secret-manager',
|
||||
command: 'gcloud secrets versions access latest --secret="{0}"',
|
||||
parseOutput: 'raw',
|
||||
},
|
||||
'azure-key-vault': {
|
||||
name: 'azure-key-vault',
|
||||
command: 'az keyvault secret show --vault-name "$AZURE_VAULT_NAME" --name {0} --query value --output tsv',
|
||||
parseOutput: 'raw',
|
||||
},
|
||||
'hashicorp-vault': {
|
||||
// HashiCorp Vault KV v2 (default). Requires VAULT_ADDR env var.
|
||||
// Optionally set VAULT_MOUNT to override the mount path (default: 'secret').
|
||||
// Authentication is handled by VAULT_TOKEN or other Vault auth env vars.
|
||||
name: 'hashicorp-vault',
|
||||
command: 'vault kv get -mount="${VAULT_MOUNT:-secret}" -field=value {0}',
|
||||
parseOutput: 'raw',
|
||||
},
|
||||
'hashicorp-vault-kv1': {
|
||||
// HashiCorp Vault KV v1. Requires VAULT_ADDR env var.
|
||||
// Optionally set VAULT_MOUNT to override the mount path (default: 'secret').
|
||||
name: 'hashicorp-vault-kv1',
|
||||
command: 'vault read -mount="${VAULT_MOUNT:-secret}" -field=value {0}',
|
||||
parseOutput: 'raw',
|
||||
},
|
||||
vault: {
|
||||
// Short alias for hashicorp-vault (KV v2)
|
||||
name: 'vault',
|
||||
command: 'vault kv get -mount="${VAULT_MOUNT:-secret}" -field=value {0}',
|
||||
parseOutput: 'raw',
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if a source name is a known premade source.
|
||||
*/
|
||||
static isPremadeSource(sourceName: string): boolean {
|
||||
return sourceName in SecretSourceService.premadeSources;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of available premade source names.
|
||||
*/
|
||||
static getAvailableSources(): string[] {
|
||||
return Object.keys(SecretSourceService.premadeSources);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a source name to a SecretSourceDefinition.
|
||||
*
|
||||
* - If the name matches a premade source, returns that definition.
|
||||
* - If it looks like a shell command (contains spaces or {0}), wraps it as a custom command.
|
||||
* - Otherwise, returns undefined.
|
||||
*/
|
||||
static resolveSource(sourceName: string): SecretSourceDefinition | undefined {
|
||||
// Check premade sources
|
||||
if (SecretSourceService.isPremadeSource(sourceName)) {
|
||||
return SecretSourceService.premadeSources[sourceName];
|
||||
}
|
||||
|
||||
// If it contains a placeholder or spaces, treat it as a raw command
|
||||
if (sourceName.includes('{0}') || sourceName.includes(' ')) {
|
||||
return {
|
||||
name: 'custom-command',
|
||||
command: sourceName,
|
||||
parseOutput: 'raw',
|
||||
};
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load custom secret source definitions from a YAML file.
|
||||
*
|
||||
* Expected format:
|
||||
* sources:
|
||||
* - name: my-source
|
||||
* command: 'my-tool get-secret {0}'
|
||||
* - name: my-api
|
||||
* command: 'curl -s https://api.example.com/secrets/{0}'
|
||||
* parseOutput: json-field
|
||||
* jsonField: value
|
||||
*/
|
||||
static loadFromYaml(filePath: string): SecretSourceDefinition[] {
|
||||
if (!fs.existsSync(filePath)) {
|
||||
OrchestratorLogger.logWarning(`Secret source YAML not found: ${filePath}`);
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const content = fs.readFileSync(filePath, 'utf8');
|
||||
const parsed = SecretSourceService.parseSimpleYaml(content);
|
||||
|
||||
return parsed;
|
||||
} catch (error: any) {
|
||||
OrchestratorLogger.logWarning(`Failed to parse secret source YAML: ${error.message}`);
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a secret value using the given source definition.
|
||||
*
|
||||
* Validates the key against an allowlist pattern before interpolating it
|
||||
* into the command string to prevent shell injection. The fetched secret
|
||||
* value is masked via core.setSecret() so it does not leak in logs.
|
||||
*
|
||||
* @param source - The secret source definition to use
|
||||
* @param key - The secret key to fetch
|
||||
* @returns The secret value, or empty string on failure
|
||||
*/
|
||||
static async fetchSecret(source: SecretSourceDefinition, key: string): Promise<string> {
|
||||
// Validate the key to prevent shell injection
|
||||
validateSecretKey(key);
|
||||
|
||||
const command = source.command.replace(/\{0\}/g, key);
|
||||
|
||||
try {
|
||||
const output = await OrchestratorSystem.Run(command, false, true);
|
||||
|
||||
let value: string;
|
||||
|
||||
if (source.parseOutput === 'json-field' && source.jsonField) {
|
||||
try {
|
||||
const parsed = JSON.parse(output);
|
||||
value = parsed[source.jsonField] || '';
|
||||
} catch {
|
||||
OrchestratorLogger.logWarning(`Failed to parse JSON output from ${source.name} for key ${key}`);
|
||||
value = output.trim();
|
||||
}
|
||||
} else {
|
||||
value = output.trim();
|
||||
}
|
||||
|
||||
// Mask the secret value so it does not appear in GitHub Actions logs
|
||||
maskSecretValue(value);
|
||||
|
||||
return value;
|
||||
} catch (error: any) {
|
||||
OrchestratorLogger.logWarning(`Failed to fetch secret '${key}' from ${source.name}: ${error.message}`);
|
||||
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a secret from an environment variable. No shell command needed.
|
||||
* The value is masked via core.setSecret() so it does not leak in logs.
|
||||
*/
|
||||
static fetchFromEnv(key: string): string {
|
||||
const value = process.env[key] || '';
|
||||
maskSecretValue(value);
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a source name and fetch all secrets from it.
|
||||
*
|
||||
* @param sourceName - Premade source name, shell command, or 'env'
|
||||
* @param keys - List of secret keys to fetch
|
||||
* @returns Map of key -> value
|
||||
*/
|
||||
static async fetchAll(sourceName: string, keys: string[]): Promise<Record<string, string>> {
|
||||
const results: Record<string, string> = {};
|
||||
|
||||
if (sourceName === 'env') {
|
||||
for (const key of keys) {
|
||||
results[key] = SecretSourceService.fetchFromEnv(key);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
const source = SecretSourceService.resolveSource(sourceName);
|
||||
if (!source) {
|
||||
OrchestratorLogger.logWarning(
|
||||
`Unknown secret source '${sourceName}'. Available sources: ${SecretSourceService.getAvailableSources().join(
|
||||
', ',
|
||||
)}`,
|
||||
);
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
OrchestratorLogger.log(`Fetching ${keys.length} secret(s) from ${source.name}`);
|
||||
|
||||
for (const key of keys) {
|
||||
results[key] = await SecretSourceService.fetchSecret(source, key);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple YAML parser for secret source definitions.
|
||||
* Handles the specific structure we expect without requiring a YAML library.
|
||||
*/
|
||||
private static parseSimpleYaml(content: string): SecretSourceDefinition[] {
|
||||
const definitions: SecretSourceDefinition[] = [];
|
||||
const lines = content.split('\n');
|
||||
let current: Partial<SecretSourceDefinition> | null = null;
|
||||
|
||||
for (const rawLine of lines) {
|
||||
const line = rawLine.replace(/\r$/, '');
|
||||
const trimmed = line.trim();
|
||||
|
||||
if (trimmed === '' || trimmed.startsWith('#')) continue;
|
||||
|
||||
if (trimmed === '- name:' || trimmed.startsWith('- name:')) {
|
||||
if (current?.name && current?.command) {
|
||||
definitions.push(current as SecretSourceDefinition);
|
||||
}
|
||||
|
||||
current = {
|
||||
name: trimmed
|
||||
.replace('- name:', '')
|
||||
.trim()
|
||||
.replace(/^['"]|['"]$/g, ''),
|
||||
parseOutput: 'raw',
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
if (current && trimmed.startsWith('command:')) {
|
||||
current.command = trimmed
|
||||
.replace('command:', '')
|
||||
.trim()
|
||||
.replace(/^['"]|['"]$/g, '');
|
||||
} else if (current && trimmed.startsWith('parseOutput:')) {
|
||||
const value = trimmed
|
||||
.replace('parseOutput:', '')
|
||||
.trim()
|
||||
.replace(/^['"]|['"]$/g, '');
|
||||
current.parseOutput = value as 'raw' | 'json-field';
|
||||
} else if (current && trimmed.startsWith('jsonField:')) {
|
||||
current.jsonField = trimmed
|
||||
.replace('jsonField:', '')
|
||||
.trim()
|
||||
.replace(/^['"]|['"]$/g, '');
|
||||
}
|
||||
}
|
||||
|
||||
if (current?.name && current?.command) {
|
||||
definitions.push(current as SecretSourceDefinition);
|
||||
}
|
||||
|
||||
return definitions;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user