|
| 1 | +import Ajv2020 from 'ajv/dist/2020.js'; |
| 2 | +import { |
| 3 | + ApplyRequestData, InitializeResponseData, IpcMessageSchema, |
| 4 | + MessageCmd, |
| 5 | + PlanRequestData, |
| 6 | + PlanResponseData, ResourceConfig, ResourceOperation, |
| 7 | + SpawnStatus, |
| 8 | + SudoRequestData, SudoRequestDataSchema, ValidateRequestData, ValidateResponseData |
| 9 | +} from 'codify-schemas'; |
| 10 | +import { ChildProcess, SpawnOptions, fork, spawn } from 'node:child_process'; |
| 11 | + |
| 12 | +import { CodifyTestUtils } from './test-utils.js'; |
| 13 | +import path from 'node:path'; |
| 14 | + |
| 15 | +const ajv = new Ajv2020.default({ |
| 16 | + strict: true |
| 17 | +}); |
| 18 | +const ipcMessageValidator = ajv.compile(IpcMessageSchema); |
| 19 | +const sudoRequestValidator = ajv.compile(SudoRequestDataSchema); |
| 20 | + |
| 21 | +export class PluginTester { |
| 22 | + childProcess: ChildProcess |
| 23 | + |
| 24 | + /** |
| 25 | + * PluginTester is a helper class to integration test plugins. It launches plugins via fork() just like CodifyCLI does. |
| 26 | + * |
| 27 | + * @param pluginPath A fully qualified path |
| 28 | + */ |
| 29 | + constructor(pluginPath: string) { |
| 30 | + if (!path.isAbsolute(pluginPath)) { |
| 31 | + throw new Error('A fully qualified path must be supplied to PluginTester'); |
| 32 | + } |
| 33 | + |
| 34 | + this.childProcess = fork( |
| 35 | + pluginPath, |
| 36 | + [], |
| 37 | + { |
| 38 | + // Use default true to test plugins in secure mode (un-able to request sudo directly) |
| 39 | + detached: true, |
| 40 | + env: { ...process.env }, |
| 41 | + execArgv: ['--import', 'tsx/esm'], |
| 42 | + }, |
| 43 | + ) |
| 44 | + |
| 45 | + this.handleSudoRequests(this.childProcess); |
| 46 | + } |
| 47 | + |
| 48 | + async test(configs: ResourceConfig[]): Promise<void> { |
| 49 | + const initializeResult = await this.initialize(); |
| 50 | + |
| 51 | + const unsupportedConfigs = configs.filter((c) => |
| 52 | + !initializeResult.resourceDefinitions.some((rd) => rd.type === c.type) |
| 53 | + ) |
| 54 | + if (unsupportedConfigs.length > 0) { |
| 55 | + throw new Error(`The plugin does not support the following configs supplied:\n ${JSON.stringify(unsupportedConfigs, null, 2)}\n Initialize result: ${JSON.stringify(initializeResult)}`) |
| 56 | + } |
| 57 | + |
| 58 | + const validate = await this.validate({ configs }); |
| 59 | + |
| 60 | + const invalidConfigs = validate.validationResults.filter((v) => !v.isValid) |
| 61 | + if (invalidConfigs.length > 0) { |
| 62 | + throw new Error(`The following configs did not validate:\n ${JSON.stringify(invalidConfigs, null, 2)}`) |
| 63 | + } |
| 64 | + |
| 65 | + const plans = []; |
| 66 | + for (const config of configs) { |
| 67 | + plans.push(await this.plan(config)); |
| 68 | + } |
| 69 | + |
| 70 | + for (const plan of plans) { |
| 71 | + await this.apply({ |
| 72 | + planId: plan.planId |
| 73 | + }); |
| 74 | + } |
| 75 | + |
| 76 | + // Check that all applys were successful by re-planning |
| 77 | + const validationPlans = []; |
| 78 | + for (const config of configs) { |
| 79 | + validationPlans.push(await this.plan(config)); |
| 80 | + } |
| 81 | + |
| 82 | + const unsuccessfulPlans = validationPlans.filter((p) => p.operation !== ResourceOperation.NOOP); |
| 83 | + if (unsuccessfulPlans.length > 0) { |
| 84 | + throw new Error(`The following applies were not successful.\n ${JSON.stringify(unsuccessfulPlans, null, 2)}`) |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + async initialize(): Promise<InitializeResponseData> { |
| 89 | + return CodifyTestUtils.sendMessageAndAwaitResponse(this.childProcess, { |
| 90 | + cmd: 'initialize', |
| 91 | + data: {}, |
| 92 | + }); |
| 93 | + } |
| 94 | + |
| 95 | + async validate(data: ValidateRequestData): Promise<ValidateResponseData> { |
| 96 | + return CodifyTestUtils.sendMessageAndAwaitResponse(this.childProcess, { |
| 97 | + cmd: 'validate', |
| 98 | + data, |
| 99 | + }); |
| 100 | + } |
| 101 | + |
| 102 | + async plan(data: PlanRequestData): Promise<PlanResponseData> { |
| 103 | + return CodifyTestUtils.sendMessageAndAwaitResponse(this.childProcess, { |
| 104 | + cmd: 'plan', |
| 105 | + data, |
| 106 | + }); |
| 107 | + } |
| 108 | + |
| 109 | + async apply(data: ApplyRequestData): Promise<void> { |
| 110 | + return CodifyTestUtils.sendMessageAndAwaitResponse(this.childProcess, { |
| 111 | + cmd: 'apply', |
| 112 | + data, |
| 113 | + }); |
| 114 | + } |
| 115 | + |
| 116 | + private handleSudoRequests(process: ChildProcess) { |
| 117 | + // Listen for incoming sudo incoming sudo requests |
| 118 | + process.on('message', async (message) => { |
| 119 | + if (!ipcMessageValidator(message)) { |
| 120 | + throw new Error(`Invalid message from plugin. ${JSON.stringify(message, null, 2)}`); |
| 121 | + } |
| 122 | + |
| 123 | + if (message.cmd === MessageCmd.SUDO_REQUEST) { |
| 124 | + const { data } = message; |
| 125 | + if (!sudoRequestValidator(data)) { |
| 126 | + throw new Error(`Invalid sudo request from plugin. ${JSON.stringify(sudoRequestValidator.errors, null, 2)}`); |
| 127 | + } |
| 128 | + |
| 129 | + const { command, options } = data as unknown as SudoRequestData; |
| 130 | + |
| 131 | + console.log(`Running command with sudo: 'sudo ${command}'`) |
| 132 | + const result = await sudoSpawn(command, options); |
| 133 | + |
| 134 | + process.send({ |
| 135 | + cmd: MessageCmd.SUDO_REQUEST + '_Response', |
| 136 | + data: result, |
| 137 | + }) |
| 138 | + } |
| 139 | + }) |
| 140 | + } |
| 141 | +} |
| 142 | + |
| 143 | + |
| 144 | +type CodifySpawnOptions = { |
| 145 | + cwd?: string; |
| 146 | + throws?: boolean, |
| 147 | +} & Omit<SpawnOptions, 'detached' | 'shell' | 'stdio'> |
| 148 | + |
| 149 | +/** |
| 150 | + * |
| 151 | + * @param cmd Command to run. Ex: `rm -rf` |
| 152 | + * @param opts Options for spawn |
| 153 | + * @param secureMode Secure mode for sudo |
| 154 | + * @param pluginName Optional plugin name so that stdout and stderr can be piped |
| 155 | + * |
| 156 | + * @see promiseSpawn |
| 157 | + * @see spawn |
| 158 | + * |
| 159 | + * @returns SpawnResult { status: SUCCESS | ERROR; data: string } |
| 160 | + */ |
| 161 | +async function sudoSpawn( |
| 162 | + cmd: string, |
| 163 | + opts: CodifySpawnOptions, |
| 164 | +): Promise<{ data: string, status: SpawnStatus }> { |
| 165 | + return new Promise((resolve) => { |
| 166 | + const output: string[] = []; |
| 167 | + |
| 168 | + const _cmd = `sudo ${cmd}`; |
| 169 | + |
| 170 | + // Source start up shells to emulate a users environment vs. a non-interactive non-login shell script |
| 171 | + // Ignore all stdin |
| 172 | + const _process = spawn(`source ~/.zshrc; ${_cmd}`, [], { |
| 173 | + ...opts, |
| 174 | + shell: 'zsh', |
| 175 | + stdio: ['ignore', 'pipe', 'pipe'], |
| 176 | + }); |
| 177 | + |
| 178 | + const { stderr, stdout } = _process |
| 179 | + stdout.setEncoding('utf8'); |
| 180 | + stderr.setEncoding('utf8'); |
| 181 | + |
| 182 | + stdout.on('data', (data) => { |
| 183 | + output.push(data.toString()); |
| 184 | + }) |
| 185 | + |
| 186 | + stderr.on('data', (data) => { |
| 187 | + output.push(data.toString()); |
| 188 | + }) |
| 189 | + |
| 190 | + stdout.pipe(process.stdout); |
| 191 | + stderr.pipe(process.stderr); |
| 192 | + |
| 193 | + _process.on('close', (code) => { |
| 194 | + resolve({ |
| 195 | + data: output.join(''), |
| 196 | + status: code === 0 ? SpawnStatus.SUCCESS : SpawnStatus.ERROR, |
| 197 | + }) |
| 198 | + }) |
| 199 | + }) |
| 200 | +} |
0 commit comments