diff --git a/.eslintrc b/.eslintrc index 13a7f3f1d0..7538a64436 100644 --- a/.eslintrc +++ b/.eslintrc @@ -33,6 +33,10 @@ { "name": "global", "message": "Use `globalThis` instead" + }, + { + "name": "window", + "message": "Use `globalThis` instead" } ], "require-yield": 0, diff --git a/src/bin/agent/CommandStart.ts b/src/bin/agent/CommandStart.ts index bd207817bf..3efa70a057 100644 --- a/src/bin/agent/CommandStart.ts +++ b/src/bin/agent/CommandStart.ts @@ -8,7 +8,7 @@ import type PolykeyAgent from '../../PolykeyAgent'; import type { RecoveryCode } from '../../keys/types'; import type { PolykeyWorkerManagerInterface } from '../../workers/types'; import path from 'path'; -import child_process from 'child_process'; +import childProcess from 'child_process'; import process from 'process'; import CommandPolykey from '../CommandPolykey'; import * as binUtils from '../utils'; @@ -130,7 +130,7 @@ class CommandStart extends CommandPolykey { ); stdio[2] = agentErrFile.fd; } - const agentProcess = child_process.fork( + const agentProcess = childProcess.fork( path.join(__dirname, '../polykey-agent'), [], { diff --git a/tests/agent/service/notificationsSend.test.ts b/tests/agent/service/notificationsSend.test.ts index df1d23d352..cda10f3356 100644 --- a/tests/agent/service/notificationsSend.test.ts +++ b/tests/agent/service/notificationsSend.test.ts @@ -26,7 +26,7 @@ import * as utilsPB from '@/proto/js/polykey/v1/utils/utils_pb'; import * as notificationsPB from '@/proto/js/polykey/v1/notifications/notifications_pb'; import * as nodesUtils from '@/nodes/utils'; import * as notificationsUtils from '@/notifications/utils'; -import { expectRemoteError } from '../../utils'; +import { expectRemoteError } from '../../utils/utils'; import { globalRootKeyPems } from '../../fixtures/globalRootKeyPems'; describe('notificationsSend', () => { diff --git a/tests/bin/agent/lock.test.ts b/tests/bin/agent/lock.test.ts index 5f39a55500..86b41665c3 100644 --- a/tests/bin/agent/lock.test.ts +++ b/tests/bin/agent/lock.test.ts @@ -29,21 +29,19 @@ describe('lock', () => { testUtils.testIf( testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, )('lock deletes the session token', async () => { - await execUtils.pkStdio( - ['agent', 'unlock'], - { + await execUtils.pkExec(['agent', 'unlock'], { + env: { PK_NODE_PATH: agentDir, PK_PASSWORD: agentPassword, }, - agentDir, - ); - const { exitCode } = await execUtils.pkStdio( - ['agent', 'lock'], - { + cwd: agentDir, + }); + const { exitCode } = await execUtils.pkExec(['agent', 'lock'], { + env: { PK_NODE_PATH: agentDir, }, - agentDir, - ); + cwd: agentDir, + }); expect(exitCode).toBe(0); const session = await Session.createSession({ sessionTokenPath: path.join(agentDir, config.defaults.tokenBase), @@ -61,30 +59,23 @@ describe('lock', () => { mockedPrompts.mockImplementation(async (_opts: any) => { return { password }; }); - await execUtils.pkStdio( - ['agent', 'unlock'], - { + await execUtils.pkStdio(['agent', 'unlock'], { + env: { PK_NODE_PATH: agentDir, PK_PASSWORD: agentPassword, }, - agentDir, - ); + cwd: agentDir, + }); // Session token is deleted - await execUtils.pkStdio( - ['agent', 'lock'], - { - PK_NODE_PATH: agentDir, - }, - agentDir, - ); + await execUtils.pkStdio(['agent', 'lock'], { + env: { PK_NODE_PATH: agentDir }, + cwd: agentDir, + }); // Will prompt to reauthenticate - await execUtils.pkStdio( - ['agent', 'status'], - { - PK_NODE_PATH: agentDir, - }, - agentDir, - ); + await execUtils.pkStdio(['agent', 'status'], { + env: { PK_NODE_PATH: agentDir }, + cwd: agentDir, + }); // Prompted for password 1 time expect(mockedPrompts.mock.calls.length).toBe(1); mockedPrompts.mockClear(); diff --git a/tests/bin/agent/lockall.test.ts b/tests/bin/agent/lockall.test.ts index a23d7ba802..20e5c7f289 100644 --- a/tests/bin/agent/lockall.test.ts +++ b/tests/bin/agent/lockall.test.ts @@ -35,21 +35,17 @@ describe('lockall', () => { testUtils.testIf( testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, )('lockall deletes the session token', async () => { - await execUtils.pkStdio( - ['agent', 'unlock'], - { + await execUtils.pkExec(['agent', 'unlock'], { + env: { PK_NODE_PATH: agentDir, PK_PASSWORD: agentPassword, }, - agentDir, - ); - const { exitCode } = await execUtils.pkStdio( - ['agent', 'lockall'], - { - PK_NODE_PATH: agentDir, - }, - agentDir, - ); + cwd: agentDir, + }); + const { exitCode } = await execUtils.pkExec(['agent', 'lockall'], { + env: { PK_NODE_PATH: agentDir }, + cwd: agentDir, + }); expect(exitCode).toBe(0); const session = await Session.createSession({ sessionTokenPath: path.join(agentDir, config.defaults.tokenBase), @@ -63,33 +59,26 @@ describe('lockall', () => { 'lockall ensures reauthentication is required', async () => { const password = agentPassword; - await execUtils.pkStdio( - ['agent', 'unlock'], - { + await execUtils.pkStdio(['agent', 'unlock'], { + env: { PK_NODE_PATH: agentDir, PK_PASSWORD: agentPassword, }, - agentDir, - ); - await execUtils.pkStdio( - ['agent', 'lockall'], - { - PK_NODE_PATH: agentDir, - }, - agentDir, - ); + cwd: agentDir, + }); + await execUtils.pkStdio(['agent', 'lockall'], { + env: { PK_NODE_PATH: agentDir }, + cwd: agentDir, + }); // Token is deleted, reauthentication is required mockedPrompts.mockClear(); mockedPrompts.mockImplementation(async (_opts: any) => { return { password }; }); - await execUtils.pkStdio( - ['agent', 'status'], - { - PK_NODE_PATH: agentDir, - }, - agentDir, - ); + await execUtils.pkStdio(['agent', 'status'], { + env: { PK_NODE_PATH: agentDir }, + cwd: agentDir, + }); // Prompted for password 1 time expect(mockedPrompts.mock.calls.length).toBe(1); mockedPrompts.mockClear(); @@ -98,14 +87,13 @@ describe('lockall', () => { testUtils.testIf( testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, )('lockall causes old session tokens to fail', async () => { - await execUtils.pkStdio( - ['agent', 'unlock'], - { + await execUtils.pkExec(['agent', 'unlock'], { + env: { PK_NODE_PATH: agentDir, PK_PASSWORD: agentPassword, }, - agentDir, - ); + cwd: agentDir, + }); const session = await Session.createSession({ sessionTokenPath: path.join(agentDir, config.defaults.tokenBase), fs, @@ -113,22 +101,23 @@ describe('lockall', () => { }); const token = await session.readToken(); await session.stop(); - await execUtils.pkStdio( - ['agent', 'lockall'], - { + await execUtils.pkExec(['agent', 'lockall'], { + env: { PK_NODE_PATH: agentDir, PK_PASSWORD: agentPassword, }, - agentDir, - ); + cwd: agentDir, + }); // Old token is invalid - const { exitCode, stderr } = await execUtils.pkStdio( + const { exitCode, stderr } = await execUtils.pkExec( ['agent', 'status', '--format', 'json'], { - PK_NODE_PATH: agentDir, - PK_TOKEN: token, + env: { + PK_NODE_PATH: agentDir, + PK_TOKEN: token, + }, + cwd: agentDir, }, - agentDir, ); execUtils.expectProcessError(exitCode, stderr, [ new errors.ErrorClientAuthDenied(), diff --git a/tests/bin/agent/start.test.ts b/tests/bin/agent/start.test.ts index 55ec099437..bd2454e088 100644 --- a/tests/bin/agent/start.test.ts +++ b/tests/bin/agent/start.test.ts @@ -57,9 +57,11 @@ describe('start', () => { 'json', ], { - PK_PASSWORD: password, + env: { + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, logger, ); const rlOut = readline.createInterface(agentProcess.stdout!); @@ -131,9 +133,11 @@ describe('start', () => { 'json', ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + }, + cwd: dataDir, }, - dataDir, logger, ); const agentProcessExit = new Promise((resolve, reject) => { @@ -227,10 +231,12 @@ describe('start', () => { 'json', ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, logger.getChild('agentProcess1'), ), execUtils.pkSpawn( @@ -250,10 +256,12 @@ describe('start', () => { 'json', ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, logger.getChild('agentProcess2'), ), ]); @@ -321,10 +329,12 @@ describe('start', () => { 'json', ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, logger.getChild('agentProcess'), ), execUtils.pkSpawn( @@ -338,10 +348,12 @@ describe('start', () => { 'json', ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, logger.getChild('bootstrapProcess'), ), ]); @@ -405,10 +417,12 @@ describe('start', () => { '--verbose', ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, logger, ); const rlOut = readline.createInterface(agentProcess1.stdout!); @@ -432,10 +446,12 @@ describe('start', () => { '--verbose', ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, logger, ); const status = new Status({ @@ -477,10 +493,12 @@ describe('start', () => { '--verbose', ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, logger.getChild('agentProcess1'), ); const rlErr = readline.createInterface(agentProcess1.stderr!); @@ -518,10 +536,12 @@ describe('start', () => { 'json', ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, logger.getChild('agentProcess2'), ); const rlOut = readline.createInterface(agentProcess2.stdout!); @@ -601,9 +621,11 @@ describe('start', () => { 'json', ], { - PK_PASSWORD: password1, + env: { + PK_PASSWORD: password1, + }, + cwd: dataDir, }, - dataDir, logger.getChild('agentProcess1'), ); const rlOut = readline.createInterface(agentProcess1.stdout!); @@ -636,10 +658,12 @@ describe('start', () => { '--verbose', ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password2, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password2, + }, + cwd: dataDir, }, - dataDir, logger.getChild('agentProcess2'), ); const statusInfo2 = await status.waitFor('LIVE'); @@ -652,10 +676,12 @@ describe('start', () => { const agentProcess3 = await execUtils.pkSpawn( ['agent', 'start', '--workers', '0', '--verbose'], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password2, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password2, + }, + cwd: dataDir, }, - dataDir, logger.getChild('agentProcess3'), ); const statusInfo3 = await status.waitFor('LIVE'); @@ -685,11 +711,13 @@ describe('start', () => { '--verbose', ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password2, - PK_RECOVERY_CODE: recoveryCode, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password2, + PK_RECOVERY_CODE: recoveryCode, + }, + cwd: dataDir, }, - dataDir, logger.getChild('agentProcess4'), ); const statusInfo4 = await status.waitFor('LIVE'); @@ -741,10 +769,12 @@ describe('start', () => { '--verbose', ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, logger.getChild('agentProcess'), ); const statusInfo = await status.waitFor('LIVE'); @@ -781,11 +811,13 @@ describe('start', () => { const agentProcess = await execUtils.pkSpawn( ['agent', 'start', '--workers', '0', '--verbose'], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, - PK_ROOT_KEY: privateKeyPem, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + PK_ROOT_KEY: privateKeyPem, + }, + cwd: dataDir, }, - dataDir, logger, ); const statusInfo = await status.waitFor('LIVE'); @@ -833,10 +865,12 @@ describe('start', () => { privateKeyPath, ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, logger, ); const statusInfo = await status.waitFor('LIVE'); @@ -931,19 +965,20 @@ describe('start', () => { '--verbose', ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); - await execUtils.pkStdio( - ['agent', 'stop'], - { + await execUtils.pkStdio(['agent', 'stop'], { + env: { PK_NODE_PATH: nodePath, PK_PASSWORD: password, }, - dataDir, - ); + cwd: dataDir, + }); mockedConfigDefaultsNetwork.mockRestore(); await status.waitFor('DEAD'); }, @@ -991,21 +1026,22 @@ describe('start', () => { '--verbose', ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, - PK_SEED_NODES: `;${seedNodeId1}@${seedNodeHost1}:${seedNodePort1}`, - PK_NETWORK: 'testnet', + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + PK_SEED_NODES: `;${seedNodeId1}@${seedNodeHost1}:${seedNodePort1}`, + PK_NETWORK: 'testnet', + }, + cwd: dataDir, }, - dataDir, ); - await execUtils.pkStdio( - ['agent', 'stop'], - { + await execUtils.pkStdio(['agent', 'stop'], { + env: { PK_NODE_PATH: nodePath, PK_PASSWORD: password, }, - dataDir, - ); + cwd: dataDir, + }); mockedConfigDefaultsNetwork.mockRestore(); await status.waitFor('DEAD'); }, diff --git a/tests/bin/agent/status.test.ts b/tests/bin/agent/status.test.ts index 5401fd935c..470fcf3255 100644 --- a/tests/bin/agent/status.test.ts +++ b/tests/bin/agent/status.test.ts @@ -54,22 +54,26 @@ describe('status', () => { '--verbose', ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, - PK_ROOT_KEY: globalRootKeyPems[0], + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + PK_ROOT_KEY: globalRootKeyPems[0], + }, + cwd: dataDir, }, - dataDir, logger, ); await status.waitFor('STARTING'); let exitCode, stdout; - ({ exitCode, stdout } = await execUtils.pkStdio( + ({ exitCode, stdout } = await execUtils.pkExec( ['agent', 'status', '--format', 'json'], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); // If the command was slow, it may have become LIVE already @@ -82,13 +86,15 @@ describe('status', () => { agentProcess.kill('SIGTERM'); // Cannot wait for STOPPING because waitFor polling may miss the transition await status.waitFor('DEAD'); - ({ exitCode, stdout } = await execUtils.pkStdio( + ({ exitCode, stdout } = await execUtils.pkExec( ['agent', 'status', '--format', 'json'], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); // If the command was slow, it may have become DEAD already @@ -97,13 +103,15 @@ describe('status', () => { status: expect.stringMatching(/STOPPING|DEAD/), }); await agentProcessExit; - ({ exitCode, stdout } = await execUtils.pkStdio( + ({ exitCode, stdout } = await execUtils.pkExec( ['agent', 'status', '--format', 'json'], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toMatchObject({ @@ -115,10 +123,10 @@ describe('status', () => { testUtils.testIf( testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, )('status on missing agent', async () => { - const { exitCode, stdout } = await execUtils.pkStdio( + const { exitCode, stdout } = await execUtils.pkExec( ['agent', 'status', '--format', 'json'], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), + env: { PK_NODE_PATH: path.join(dataDir, 'polykey') }, }, ); expect(exitCode).toBe(0); @@ -149,13 +157,15 @@ describe('status', () => { logger, }); const statusInfo = (await status.readStatus())!; - const { exitCode, stdout } = await execUtils.pkStdio( + const { exitCode, stdout } = await execUtils.pkExec( ['agent', 'status', '--format', 'json', '--verbose'], { - PK_NODE_PATH: agentDir, - PK_PASSWORD: agentPassword, + env: { + PK_NODE_PATH: agentDir, + PK_PASSWORD: agentPassword, + }, + cwd: agentDir, }, - agentDir, ); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toMatchObject({ @@ -187,7 +197,7 @@ describe('status', () => { }); const statusInfo = (await status.readStatus())!; // This still needs a `nodePath` because of session token path - const { exitCode, stdout } = await execUtils.pkStdio( + const { exitCode, stdout } = await execUtils.pkExec( [ 'agent', 'status', @@ -205,8 +215,10 @@ describe('status', () => { 'json', '--verbose', ], - {}, - dataDir, + { + env: {}, + cwd: dataDir, + }, ); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toMatchObject({ diff --git a/tests/bin/agent/stop.test.ts b/tests/bin/agent/stop.test.ts index f8af1b17b0..14565ada7b 100644 --- a/tests/bin/agent/stop.test.ts +++ b/tests/bin/agent/stop.test.ts @@ -42,11 +42,13 @@ describe('stop', () => { '0', ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, - PK_ROOT_KEY: globalRootKeyPems[0], + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + PK_ROOT_KEY: globalRootKeyPems[0], + }, + cwd: dataDir, }, - dataDir, logger, ); const status = new Status({ @@ -60,14 +62,13 @@ describe('stop', () => { logger, }); await status.waitFor('LIVE'); - await execUtils.pkStdio( - ['agent', 'stop'], - { + await execUtils.pkExec(['agent', 'stop'], { + env: { PK_NODE_PATH: path.join(dataDir, 'polykey'), PK_PASSWORD: password, }, - dataDir, - ); + cwd: dataDir, + }); await status.waitFor('DEAD'); await sleep(5000); agentProcess.kill(); @@ -104,49 +105,53 @@ describe('stop', () => { '0', ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, - PK_ROOT_KEY: globalRootKeyPems[0], + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + PK_ROOT_KEY: globalRootKeyPems[0], + }, + cwd: dataDir, }, - dataDir, logger, ); await status.waitFor('LIVE'); // Simultaneous calls to stop must use pkExec const [agentStop1, agentStop2] = await Promise.all([ - execUtils.pkExec( - ['agent', 'stop', '--password-file', passwordPath], - { + execUtils.pkExec(['agent', 'stop', '--password-file', passwordPath], { + env: { PK_NODE_PATH: path.join(dataDir, 'polykey'), }, - dataDir, - ), - execUtils.pkExec( - ['agent', 'stop', '--password-file', passwordPath], - { + cwd: dataDir, + }), + execUtils.pkExec(['agent', 'stop', '--password-file', passwordPath], { + env: { PK_NODE_PATH: path.join(dataDir, 'polykey'), }, - dataDir, - ), + cwd: dataDir, + }), ]); // Cannot await for STOPPING // It's not reliable until file watching is implemented // So just 1 ms delay until sending another stop command await sleep(1); - const agentStop3 = await execUtils.pkStdio( + const agentStop3 = await execUtils.pkExec( ['agent', 'stop', '--node-path', path.join(dataDir, 'polykey')], { - PK_PASSWORD: password, + env: { + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); await status.waitFor('DEAD'); - const agentStop4 = await execUtils.pkStdio( + const agentStop4 = await execUtils.pkExec( ['agent', 'stop', '--password-file', passwordPath], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + }, + cwd: dataDir, }, - dataDir, ); // If the GRPC server gets closed after the GRPC connection is established // then it's possible that one of these exit codes is 1 @@ -193,33 +198,36 @@ describe('stop', () => { '--verbose', ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, - PK_ROOT_KEY: globalRootKeyPems[0], + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + PK_ROOT_KEY: globalRootKeyPems[0], + }, + cwd: dataDir, }, - dataDir, logger, ); await status.waitFor('STARTING'); const { exitCode, stderr } = await execUtils.pkStdio( ['agent', 'stop', '--format', 'json'], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + }, + cwd: dataDir, }, - dataDir, ); execUtils.expectProcessError(exitCode, stderr, [ new binErrors.ErrorCLIPolykeyAgentStatus('agent is starting'), ]); await status.waitFor('LIVE'); - await execUtils.pkStdio( - ['agent', 'stop'], - { + await execUtils.pkStdio(['agent', 'stop'], { + env: { PK_NODE_PATH: path.join(dataDir, 'polykey'), PK_PASSWORD: password, }, - dataDir, - ); + cwd: dataDir, + }); await status.waitFor('DEAD'); agentProcess.kill(); }, @@ -243,11 +251,13 @@ describe('stop', () => { '0', ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, - PK_ROOT_KEY: globalRootKeyPems[0], + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + PK_ROOT_KEY: globalRootKeyPems[0], + }, + cwd: dataDir, }, - dataDir, logger, ); const status = new Status({ @@ -261,27 +271,28 @@ describe('stop', () => { logger, }); await status.waitFor('LIVE'); - const { exitCode, stderr } = await execUtils.pkStdio( + const { exitCode, stderr } = await execUtils.pkExec( ['agent', 'stop', '--format', 'json'], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: 'wrong password', + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: 'wrong password', + }, + cwd: dataDir, }, - dataDir, ); execUtils.expectProcessError(exitCode, stderr, [ new clientErrors.ErrorClientAuthDenied(), ]); // Should still be LIVE expect((await status.readStatus())?.status).toBe('LIVE'); - await execUtils.pkStdio( - ['agent', 'stop'], - { + await execUtils.pkExec(['agent', 'stop'], { + env: { PK_NODE_PATH: path.join(dataDir, 'polykey'), PK_PASSWORD: password, }, - dataDir, - ); + cwd: dataDir, + }); await status.waitFor('DEAD'); agentProcess.kill(); }, diff --git a/tests/bin/agent/unlock.test.ts b/tests/bin/agent/unlock.test.ts index 93bfc953c0..62b8d0ca78 100644 --- a/tests/bin/agent/unlock.test.ts +++ b/tests/bin/agent/unlock.test.ts @@ -34,33 +34,36 @@ describe('unlock', () => { fresh: true, }); let exitCode, stdout; - ({ exitCode } = await execUtils.pkStdio( - ['agent', 'unlock'], - { + ({ exitCode } = await execUtils.pkExec(['agent', 'unlock'], { + env: { PK_NODE_PATH: agentDir, PK_PASSWORD: agentPassword, }, - agentDir, - )); + cwd: agentDir, + })); expect(exitCode).toBe(0); // Run command without password - ({ exitCode, stdout } = await execUtils.pkStdio( + ({ exitCode, stdout } = await execUtils.pkExec( ['agent', 'status', '--format', 'json'], { - PK_NODE_PATH: agentDir, + env: { + PK_NODE_PATH: agentDir, + }, + cwd: agentDir, }, - agentDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toMatchObject({ status: 'LIVE' }); // Run command with PK_TOKEN - ({ exitCode, stdout } = await execUtils.pkStdio( + ({ exitCode, stdout } = await execUtils.pkExec( ['agent', 'status', '--format', 'json'], { - PK_NODE_PATH: agentDir, - PK_TOKEN: await session.readToken(), + env: { + PK_NODE_PATH: agentDir, + PK_TOKEN: await session.readToken(), + }, + cwd: agentDir, }, - agentDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toMatchObject({ status: 'LIVE' }); diff --git a/tests/bin/bootstrap.test.ts b/tests/bin/bootstrap.test.ts index cfc1f37f24..c7aefffca5 100644 --- a/tests/bin/bootstrap.test.ts +++ b/tests/bin/bootstrap.test.ts @@ -32,7 +32,7 @@ describe('bootstrap', () => { const password = 'password'; const passwordPath = path.join(dataDir, 'password'); await fs.promises.writeFile(passwordPath, password); - const { exitCode, stdout } = await execUtils.pkStdio( + const { exitCode, stdout } = await execUtils.pkExec( [ 'bootstrap', '--password-file', @@ -42,9 +42,11 @@ describe('bootstrap', () => { '--verbose', ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + }, + cwd: dataDir, }, - dataDir, ); expect(exitCode).toBe(0); const recoveryCode = stdout.trim(); @@ -69,7 +71,7 @@ describe('bootstrap', () => { await fs.promises.writeFile(privateKeyPath, privateKeyPem, { encoding: 'utf-8', }); - const { exitCode: exitCode1 } = await execUtils.pkStdio( + const { exitCode: exitCode1 } = await execUtils.pkExec( [ 'bootstrap', '--password-file', @@ -79,18 +81,22 @@ describe('bootstrap', () => { privateKeyPath, ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + }, + cwd: dataDir, }, - dataDir, ); expect(exitCode1).toBe(0); - const { exitCode: exitCode2 } = await execUtils.pkStdio( + const { exitCode: exitCode2 } = await execUtils.pkExec( ['bootstrap', '--password-file', passwordPath, '--verbose'], { - PK_NODE_PATH: path.join(dataDir, 'polykey2'), - PK_ROOT_KEY: privateKeyPem, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey2'), + PK_ROOT_KEY: privateKeyPem, + }, + cwd: dataDir, }, - dataDir, ); expect(exitCode2).toBe(0); }, @@ -105,7 +111,7 @@ describe('bootstrap', () => { await fs.promises.mkdir(path.join(dataDir, 'polykey')); await fs.promises.writeFile(path.join(dataDir, 'polykey', 'test'), ''); let exitCode, stdout, stderr; - ({ exitCode, stdout, stderr } = await execUtils.pkStdio( + ({ exitCode, stdout, stderr } = await execUtils.pkExec( [ 'bootstrap', '--node-path', @@ -117,16 +123,18 @@ describe('bootstrap', () => { 'json', ], { - PK_PASSWORD: password, + env: { + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); const errorBootstrapExistingState = new bootstrapErrors.ErrorBootstrapExistingState(); execUtils.expectProcessError(exitCode, stderr, [ errorBootstrapExistingState, ]); - ({ exitCode, stdout, stderr } = await execUtils.pkStdio( + ({ exitCode, stdout, stderr } = await execUtils.pkExec( [ 'bootstrap', '--node-path', @@ -137,9 +145,11 @@ describe('bootstrap', () => { '--verbose', ], { - PK_PASSWORD: password, + env: { + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); const recoveryCode = stdout.trim(); @@ -167,10 +177,12 @@ describe('bootstrap', () => { 'json', ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, logger.getChild('bootstrapProcess1'), ), execUtils.pkSpawn( @@ -183,10 +195,12 @@ describe('bootstrap', () => { 'json', ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, logger.getChild('bootstrapProcess2'), ), ]); @@ -242,10 +256,12 @@ describe('bootstrap', () => { const bootstrapProcess1 = await execUtils.pkSpawn( ['bootstrap', '--root-key-pair-bits', '1024', '--verbose'], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, logger.getChild('bootstrapProcess1'), ); const rlErr = readline.createInterface(bootstrapProcess1.stderr!); @@ -266,7 +282,7 @@ describe('bootstrap', () => { bootstrapProcess1.once('exit', () => res(null)); }); // Attempting to bootstrap should fail with existing state - const bootstrapProcess2 = await execUtils.pkStdio( + const bootstrapProcess2 = await execUtils.pkExec( [ 'bootstrap', '--root-key-pair-bits', @@ -276,10 +292,12 @@ describe('bootstrap', () => { 'json', ], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); const errorBootstrapExistingState = new bootstrapErrors.ErrorBootstrapExistingState(); @@ -289,13 +307,15 @@ describe('bootstrap', () => { [errorBootstrapExistingState], ); // Attempting to bootstrap with --fresh should succeed - const bootstrapProcess3 = await execUtils.pkStdio( + const bootstrapProcess3 = await execUtils.pkExec( ['bootstrap', '--root-key-pair-bits', '1024', '--fresh', '--verbose'], { - PK_NODE_PATH: path.join(dataDir, 'polykey'), - PK_PASSWORD: password, + env: { + PK_NODE_PATH: path.join(dataDir, 'polykey'), + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(bootstrapProcess3.exitCode).toBe(0); const recoveryCode = bootstrapProcess3.stdout.trim(); diff --git a/tests/bin/identities/allowDisallowPermissions.test.ts b/tests/bin/identities/allowDisallowPermissions.test.ts index f6f33b553c..95b7d76540 100644 --- a/tests/bin/identities/allowDisallowPermissions.test.ts +++ b/tests/bin/identities/allowDisallowPermissions.test.ts @@ -111,10 +111,12 @@ describe('allow/disallow/permissions', () => { `${nodePort}`, ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); // Must first trust node before we can set permissions // This is because trusting the node sets it in our gestalt graph, which @@ -122,20 +124,24 @@ describe('allow/disallow/permissions', () => { await execUtils.pkStdio( ['identities', 'trust', nodesUtils.encodeNodeId(nodeId)], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); // We should now have the 'notify' permission, so we'll set the 'scan' // permission as well ({ exitCode } = await execUtils.pkStdio( ['identities', 'allow', nodesUtils.encodeNodeId(nodeId), 'scan'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); // Check that both permissions are set @@ -148,10 +154,12 @@ describe('allow/disallow/permissions', () => { 'json', ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ @@ -161,19 +169,23 @@ describe('allow/disallow/permissions', () => { ({ exitCode } = await execUtils.pkStdio( ['identities', 'disallow', nodesUtils.encodeNodeId(nodeId), 'notify'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); ({ exitCode } = await execUtils.pkStdio( ['identities', 'disallow', nodesUtils.encodeNodeId(nodeId), 'scan'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); // Check that both permissions were unset @@ -186,10 +198,12 @@ describe('allow/disallow/permissions', () => { 'json', ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ @@ -212,10 +226,12 @@ describe('allow/disallow/permissions', () => { `${nodePort}`, ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); // Authenticate our own identity in order to query the provider const mockedBrowser = jest @@ -229,10 +245,12 @@ describe('allow/disallow/permissions', () => { testToken.identityId, ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); mockedBrowser.mockRestore(); // Must first trust identity before we can set permissions @@ -241,14 +259,13 @@ describe('allow/disallow/permissions', () => { // This command should fail first time since the identity won't be linked // to any nodes. It will trigger this process via discovery and we must // wait and then retry - await execUtils.pkStdio( - ['identities', 'trust', providerString], - { + await execUtils.pkStdio(['identities', 'trust', providerString], { + env: { PK_NODE_PATH: nodePath, PK_PASSWORD: password, }, - dataDir, - ); + cwd: dataDir, + }); await poll( async () => { const gestalts = await poll>( @@ -273,10 +290,12 @@ describe('allow/disallow/permissions', () => { ({ exitCode } = await execUtils.pkStdio( ['identities', 'trust', providerString], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); // We should now have the 'notify' permission, so we'll set the 'scan' @@ -284,20 +303,24 @@ describe('allow/disallow/permissions', () => { ({ exitCode } = await execUtils.pkStdio( ['identities', 'allow', providerString, 'scan'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); // Check that both permissions are set ({ exitCode, stdout } = await execUtils.pkStdio( ['identities', 'permissions', providerString, '--format', 'json'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ @@ -307,29 +330,35 @@ describe('allow/disallow/permissions', () => { ({ exitCode } = await execUtils.pkStdio( ['identities', 'disallow', providerString, 'notify'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); ({ exitCode } = await execUtils.pkStdio( ['identities', 'disallow', providerString, 'scan'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); // Check that both permissions were unset ({ exitCode, stdout } = await execUtils.pkStdio( ['identities', 'permissions', providerString, '--format', 'json'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ @@ -343,55 +372,65 @@ describe('allow/disallow/permissions', () => { let exitCode; // Allow // Invalid gestalt id - ({ exitCode } = await execUtils.pkStdio( + ({ exitCode } = await execUtils.pkExec( ['identities', 'allow', 'invalid', 'notify'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(sysexits.USAGE); // Invalid permission - ({ exitCode } = await execUtils.pkStdio( + ({ exitCode } = await execUtils.pkExec( ['identities', 'allow', nodesUtils.encodeNodeId(nodeId), 'invalid'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(sysexits.USAGE); // Permissions // Invalid gestalt id - ({ exitCode } = await execUtils.pkStdio( + ({ exitCode } = await execUtils.pkExec( ['identities', 'permissions', 'invalid'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(sysexits.USAGE); // Disallow // Invalid gestalt id - ({ exitCode } = await execUtils.pkStdio( + ({ exitCode } = await execUtils.pkExec( ['identities', 'disallow', 'invalid', 'notify'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(sysexits.USAGE); // Invalid permission - ({ exitCode } = await execUtils.pkStdio( + ({ exitCode } = await execUtils.pkExec( ['identities', 'disallow', nodesUtils.encodeNodeId(nodeId), 'invalid'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(sysexits.USAGE); }); diff --git a/tests/bin/identities/authenticateAuthenticated.test.ts b/tests/bin/identities/authenticateAuthenticated.test.ts index 5fc3997104..b0508aa18e 100644 --- a/tests/bin/identities/authenticateAuthenticated.test.ts +++ b/tests/bin/identities/authenticateAuthenticated.test.ts @@ -71,10 +71,12 @@ describe('authenticate/authenticated', () => { testToken.identityId, ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(stdout).toContain('randomtestcode'); @@ -82,10 +84,12 @@ describe('authenticate/authenticated', () => { ({ exitCode, stdout } = await execUtils.pkStdio( ['identities', 'authenticated', '--format', 'json'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ @@ -103,10 +107,12 @@ describe('authenticate/authenticated', () => { 'json', ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ @@ -125,20 +131,24 @@ describe('authenticate/authenticated', () => { ({ exitCode } = await execUtils.pkStdio( ['identities', 'authenticate', '', testToken.identityId], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(sysexits.USAGE); // Invalid identity ({ exitCode } = await execUtils.pkStdio( ['identities', 'authenticate', testToken.providerId, ''], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(sysexits.USAGE); // Authenticated @@ -146,10 +156,12 @@ describe('authenticate/authenticated', () => { ({ exitCode } = await execUtils.pkStdio( ['identities', 'authenticate', '--provider-id', ''], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(sysexits.USAGE); }, diff --git a/tests/bin/identities/claim.test.ts b/tests/bin/identities/claim.test.ts index 1da42fc8f3..66efb8c42f 100644 --- a/tests/bin/identities/claim.test.ts +++ b/tests/bin/identities/claim.test.ts @@ -71,10 +71,12 @@ describe('claim', () => { testToken.identityId, ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); // Claim identity const { exitCode, stdout } = await execUtils.pkStdio( @@ -87,10 +89,12 @@ describe('claim', () => { 'json', ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual(['Claim Id: 0', 'Url: test.com']); @@ -111,10 +115,12 @@ describe('claim', () => { const { exitCode } = await execUtils.pkStdio( ['identities', 'claim', testToken.providerId, testToken.identityId], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(exitCode).toBe(sysexits.NOPERM); }, @@ -127,20 +133,24 @@ describe('claim', () => { ({ exitCode } = await execUtils.pkStdio( ['identities', 'claim', '', testToken.identityId], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(sysexits.USAGE); // Invalid identity ({ exitCode } = await execUtils.pkStdio( ['identities', 'claim', testToken.providerId, ''], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(sysexits.USAGE); }, diff --git a/tests/bin/identities/discoverGet.test.ts b/tests/bin/identities/discoverGet.test.ts index 004f570467..1baf38ad1d 100644 --- a/tests/bin/identities/discoverGet.test.ts +++ b/tests/bin/identities/discoverGet.test.ts @@ -136,10 +136,12 @@ describe('discover/get', () => { testToken.identityId, ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); // Add one of the nodes to our gestalt graph so that we'll be able to // contact the gestalt during discovery @@ -152,19 +154,23 @@ describe('discover/get', () => { `${nodeAPort}`, ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); // Discover gestalt by node const discoverResponse = await execUtils.pkStdio( ['identities', 'discover', nodesUtils.encodeNodeId(nodeAId)], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(discoverResponse.exitCode).toBe(0); // Since discovery is a background process we need to wait for the @@ -194,10 +200,12 @@ describe('discover/get', () => { const getResponse = await execUtils.pkStdio( ['identities', 'get', nodesUtils.encodeNodeId(nodeAId)], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(getResponse.exitCode).toBe(0); expect(getResponse.stdout).toContain(nodesUtils.encodeNodeId(nodeAId)); @@ -232,10 +240,12 @@ describe('discover/get', () => { testToken.identityId, ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); // Add one of the nodes to our gestalt graph so that we'll be able to // contact the gestalt during discovery @@ -248,19 +258,23 @@ describe('discover/get', () => { `${nodeAPort}`, ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); // Discover gestalt by node const discoverResponse = await execUtils.pkStdio( ['identities', 'discover', providerString], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(discoverResponse.exitCode).toBe(0); // Since discovery is a background process we need to wait for the @@ -290,10 +304,12 @@ describe('discover/get', () => { const getResponse = await execUtils.pkStdio( ['identities', 'get', providerString], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(getResponse.exitCode).toBe(0); expect(getResponse.stdout).toContain(nodesUtils.encodeNodeId(nodeAId)); @@ -321,20 +337,24 @@ describe('discover/get', () => { ({ exitCode } = await execUtils.pkStdio( ['identities', 'discover', 'invalid'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(sysexits.USAGE); // Get ({ exitCode } = await execUtils.pkStdio( ['identities', 'get', 'invalid'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); }, ); diff --git a/tests/bin/identities/search.test.ts b/tests/bin/identities/search.test.ts index aa1219923d..c1d7dcff7c 100644 --- a/tests/bin/identities/search.test.ts +++ b/tests/bin/identities/search.test.ts @@ -153,10 +153,12 @@ describe('search', () => { ({ exitCode, stdout } = await execUtils.pkStdio( ['identities', 'search', '--format', 'json'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(stdout).toBe(''); @@ -164,19 +166,23 @@ describe('search', () => { await execUtils.pkStdio( ['identities', 'authenticate', provider1.id, identityId], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); // Now our search should include the identities from provider1 ({ exitCode, stdout } = await execUtils.pkStdio( ['identities', 'search', '--format', 'json'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); searchResults = stdout.split('\n').slice(undefined, -1).map(JSON.parse); @@ -188,20 +194,24 @@ describe('search', () => { await execUtils.pkStdio( ['identities', 'authenticate', provider2.id, identityId], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); // Now our search should include the identities from provider1 and // provider2 ({ exitCode, stdout } = await execUtils.pkStdio( ['identities', 'search', '--format', 'json'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); searchResults = stdout.split('\n').slice(undefined, -1).map(JSON.parse); @@ -216,10 +226,12 @@ describe('search', () => { ({ exitCode, stdout } = await execUtils.pkStdio( ['identities', 'search', '4', '5', '--format', 'json'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); searchResults = stdout.split('\n').slice(undefined, -1).map(JSON.parse); @@ -230,10 +242,12 @@ describe('search', () => { await execUtils.pkStdio( ['identities', 'authenticate', provider3.id, identityId], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); // We can get results from only some providers using the --provider-id // option @@ -248,10 +262,12 @@ describe('search', () => { 'json', ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); searchResults = stdout.split('\n').slice(undefined, -1).map(JSON.parse); @@ -273,10 +289,12 @@ describe('search', () => { 'json', ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); searchResults = stdout.split('\n').slice(undefined, -1).map(JSON.parse); @@ -291,10 +309,12 @@ describe('search', () => { ({ exitCode, stdout } = await execUtils.pkStdio( ['identities', 'search', '--identity-id', 'user3', '--format', 'json'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); searchResults = stdout.split('\n').slice(undefined, -1).map(JSON.parse); @@ -306,10 +326,12 @@ describe('search', () => { ({ exitCode, stdout } = await execUtils.pkStdio( ['identities', 'search', '--limit', '2', '--format', 'json'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); searchResults = stdout.split('\n').slice(undefined, -1).map(JSON.parse); @@ -325,30 +347,36 @@ describe('search', () => { ({ exitCode } = await execUtils.pkStdio( ['identities', 'search', '--identity-id', ''], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(sysexits.USAGE); // Invalid auth identity id ({ exitCode } = await execUtils.pkStdio( ['identities', 'search', '--auth-identity-id', ''], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(sysexits.USAGE); // Invalid value for limit ({ exitCode } = await execUtils.pkStdio( ['identities', 'search', '--limit', 'NaN'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(sysexits.USAGE); }, diff --git a/tests/bin/identities/trustUntrustList.test.ts b/tests/bin/identities/trustUntrustList.test.ts index 3311011041..f486b7b085 100644 --- a/tests/bin/identities/trustUntrustList.test.ts +++ b/tests/bin/identities/trustUntrustList.test.ts @@ -112,10 +112,12 @@ describe('trust/untrust/list', () => { `${nodePort}`, ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); const mockedBrowser = jest .spyOn(identitiesUtils, 'browser') @@ -128,10 +130,12 @@ describe('trust/untrust/list', () => { testToken.identityId, ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); mockedBrowser.mockRestore(); // Trust node - this should trigger discovery on the gestalt the node @@ -139,10 +143,12 @@ describe('trust/untrust/list', () => { ({ exitCode } = await execUtils.pkStdio( ['identities', 'trust', nodesUtils.encodeNodeId(nodeId)], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); // Since discovery is a background process we need to wait for the @@ -152,10 +158,12 @@ describe('trust/untrust/list', () => { ({ exitCode, stdout } = await execUtils.pkStdio( ['identities', 'list', '--format', 'json'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toHaveLength(1); @@ -175,20 +183,24 @@ describe('trust/untrust/list', () => { ({ exitCode } = await execUtils.pkStdio( ['identities', 'untrust', nodesUtils.encodeNodeId(nodeId)], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); // Check that gestalt still exists but has no permissions ({ exitCode, stdout } = await execUtils.pkStdio( ['identities', 'list', '--format', 'json'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toHaveLength(1); @@ -231,10 +243,12 @@ describe('trust/untrust/list', () => { `${nodePort}`, ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); const mockedBrowser = jest .spyOn(identitiesUtils, 'browser') @@ -247,10 +261,12 @@ describe('trust/untrust/list', () => { testToken.identityId, ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); mockedBrowser.mockRestore(); // Trust identity - this should trigger discovery on the gestalt the node @@ -260,10 +276,12 @@ describe('trust/untrust/list', () => { ({ exitCode } = await execUtils.pkStdio( ['identities', 'trust', providerString], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(sysexits.NOUSER); // Since discovery is a background process we need to wait for the @@ -273,20 +291,24 @@ describe('trust/untrust/list', () => { ({ exitCode } = await execUtils.pkStdio( ['identities', 'trust', providerString], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); // Check that gestalt was discovered and permission was set ({ exitCode, stdout } = await execUtils.pkStdio( ['identities', 'list', '--format', 'json'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toHaveLength(1); @@ -306,20 +328,24 @@ describe('trust/untrust/list', () => { ({ exitCode } = await execUtils.pkStdio( ['identities', 'untrust', providerString], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); // Check that gestalt still exists but has no permissions ({ exitCode, stdout } = await execUtils.pkStdio( ['identities', 'list', '--format', 'json'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toHaveLength(1); @@ -354,20 +380,24 @@ describe('trust/untrust/list', () => { ({ exitCode } = await execUtils.pkStdio( ['identities', 'trust', 'invalid'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(sysexits.USAGE); // Untrust ({ exitCode } = await execUtils.pkStdio( ['identities', 'untrust', 'invalid'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(sysexits.USAGE); }, diff --git a/tests/bin/keys/cert.test.ts b/tests/bin/keys/cert.test.ts index d963c586ba..0e7757d5c6 100644 --- a/tests/bin/keys/cert.test.ts +++ b/tests/bin/keys/cert.test.ts @@ -20,26 +20,30 @@ describe('cert', () => { testUtils.testIf( testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, )('cert gets the certificate', async () => { - let { exitCode, stdout } = await execUtils.pkStdio( + let { exitCode, stdout } = await execUtils.pkExec( ['keys', 'cert', '--format', 'json'], { - PK_NODE_PATH: agentDir, - PK_PASSWORD: agentPassword, + env: { + PK_NODE_PATH: agentDir, + PK_PASSWORD: agentPassword, + }, + cwd: agentDir, }, - agentDir, ); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ cert: expect.any(String), }); const certCommand = JSON.parse(stdout).cert; - ({ exitCode, stdout } = await execUtils.pkStdio( + ({ exitCode, stdout } = await execUtils.pkExec( ['agent', 'status', '--format', 'json'], { - PK_NODE_PATH: agentDir, - PK_PASSWORD: agentPassword, + env: { + PK_NODE_PATH: agentDir, + PK_PASSWORD: agentPassword, + }, + cwd: agentDir, }, - agentDir, )); expect(exitCode).toBe(0); const certStatus = JSON.parse(stdout).rootCertPem; diff --git a/tests/bin/keys/certchain.test.ts b/tests/bin/keys/certchain.test.ts index eae9f78e78..8bf08af338 100644 --- a/tests/bin/keys/certchain.test.ts +++ b/tests/bin/keys/certchain.test.ts @@ -22,26 +22,30 @@ describe('certchain', () => { testUtils.testIf( testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, )('certchain gets the certificate chain', async () => { - let { exitCode, stdout } = await execUtils.pkStdio( + let { exitCode, stdout } = await execUtils.pkExec( ['keys', 'certchain', '--format', 'json'], { - PK_NODE_PATH: agentDir, - PK_PASSWORD: agentPassword, + env: { + PK_NODE_PATH: agentDir, + PK_PASSWORD: agentPassword, + }, + cwd: agentDir, }, - agentDir, ); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ certchain: expect.any(Array), }); const certChainCommand = JSON.parse(stdout).certchain.join('\n'); - ({ exitCode, stdout } = await execUtils.pkStdio( + ({ exitCode, stdout } = await execUtils.pkExec( ['agent', 'status', '--format', 'json'], { - PK_NODE_PATH: agentDir, - PK_PASSWORD: agentPassword, + env: { + PK_NODE_PATH: agentDir, + PK_PASSWORD: agentPassword, + }, + cwd: agentDir, }, - agentDir, )); expect(exitCode).toBe(0); const certChainStatus = JSON.parse(stdout).rootCertChainPem; diff --git a/tests/bin/keys/encryptDecrypt.test.ts b/tests/bin/keys/encryptDecrypt.test.ts index 1dfd6fa4f3..e2dded150f 100644 --- a/tests/bin/keys/encryptDecrypt.test.ts +++ b/tests/bin/keys/encryptDecrypt.test.ts @@ -21,42 +21,45 @@ describe('encrypt-decrypt', () => { afterEach(async () => { await agentClose(); }); - testUtils.testIf(testUtils.isTestPlatformDocker)( - 'encrypts and decrypts data', - async () => { - let exitCode, stdout; - const dataPath = path.join(agentDir, 'data'); - await fs.promises.writeFile(dataPath, 'abc', { - encoding: 'binary', - }); - ({ exitCode, stdout } = await execUtils.pkStdio( - ['keys', 'encrypt', dataPath, '--format', 'json'], - { + testUtils.testIf( + testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, + )('encrypts and decrypts data', async () => { + let exitCode, stdout; + const dataPath = path.join(agentDir, 'data'); + await fs.promises.writeFile(dataPath, 'abc', { + encoding: 'binary', + }); + ({ exitCode, stdout } = await execUtils.pkExec( + ['keys', 'encrypt', dataPath, '--format', 'json'], + { + env: { PK_NODE_PATH: agentDir, PK_PASSWORD: agentPassword, }, - agentDir, - )); - expect(exitCode).toBe(0); - expect(JSON.parse(stdout)).toEqual({ - encryptedData: expect.any(String), - }); - const encrypted = JSON.parse(stdout).encryptedData; - await fs.promises.writeFile(dataPath, encrypted, { - encoding: 'binary', - }); - ({ exitCode, stdout } = await execUtils.pkStdio( - ['keys', 'decrypt', dataPath, '--format', 'json'], - { + cwd: agentDir, + }, + )); + expect(exitCode).toBe(0); + expect(JSON.parse(stdout)).toEqual({ + encryptedData: expect.any(String), + }); + const encrypted = JSON.parse(stdout).encryptedData; + await fs.promises.writeFile(dataPath, encrypted, { + encoding: 'binary', + }); + ({ exitCode, stdout } = await execUtils.pkExec( + ['keys', 'decrypt', dataPath, '--format', 'json'], + { + env: { PK_NODE_PATH: agentDir, PK_PASSWORD: agentPassword, }, - agentDir, - )); - expect(exitCode).toBe(0); - expect(JSON.parse(stdout)).toEqual({ - decryptedData: 'abc', - }); - }, - ); + cwd: agentDir, + }, + )); + expect(exitCode).toBe(0); + expect(JSON.parse(stdout)).toEqual({ + decryptedData: 'abc', + }); + }); }); diff --git a/tests/bin/keys/password.test.ts b/tests/bin/keys/password.test.ts index cea0e50c2a..a97e06a194 100644 --- a/tests/bin/keys/password.test.ts +++ b/tests/bin/keys/password.test.ts @@ -26,34 +26,37 @@ describe('password', () => { )('password changes the root password', async () => { const passPath = path.join(agentDir, 'passwordChange'); await fs.promises.writeFile(passPath, 'password-change'); - let { exitCode } = await execUtils.pkStdio( + let { exitCode } = await execUtils.pkExec( ['keys', 'password', '--password-new-file', passPath], { - PK_NODE_PATH: agentDir, - PK_PASSWORD: agentPassword, + env: { + PK_NODE_PATH: agentDir, + PK_PASSWORD: agentPassword, + }, + cwd: agentDir, }, - agentDir, ); expect(exitCode).toBe(0); // Old password should no longer work - ({ exitCode } = await execUtils.pkStdio( - ['keys', 'root'], - { + ({ exitCode } = await execUtils.pkExec(['keys', 'root'], { + env: { PK_NODE_PATH: agentDir, PK_PASSWORD: agentPassword, }, - agentDir, - )); + cwd: agentDir, + })); expect(exitCode).not.toBe(0); // Revert side effects using new password await fs.promises.writeFile(passPath, agentPassword); - ({ exitCode } = await execUtils.pkStdio( + ({ exitCode } = await execUtils.pkExec( ['keys', 'password', '--password-new-file', passPath], { - PK_NODE_PATH: agentDir, - PK_PASSWORD: 'password-change', + env: { + PK_NODE_PATH: agentDir, + PK_PASSWORD: 'password-change', + }, + cwd: agentDir, }, - agentDir, )); }); }); diff --git a/tests/bin/keys/renew.test.ts b/tests/bin/keys/renew.test.ts index b94ca39e29..9b10ae3d20 100644 --- a/tests/bin/keys/renew.test.ts +++ b/tests/bin/keys/renew.test.ts @@ -59,10 +59,12 @@ describe('renew', () => { let { exitCode, stdout } = await execUtils.pkStdio( ['keys', 'root', '--private-key', '--format', 'json'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(exitCode).toBe(0); const prevPublicKey = JSON.parse(stdout).publicKey; @@ -70,10 +72,12 @@ describe('renew', () => { ({ exitCode, stdout } = await execUtils.pkStdio( ['agent', 'status', '--format', 'json'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); const prevNodeId = JSON.parse(stdout).nodeId; @@ -83,20 +87,24 @@ describe('renew', () => { ({ exitCode } = await execUtils.pkStdio( ['keys', 'renew', '--password-new-file', passPath], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); // Get new keypair and nodeId and compare against old ({ exitCode, stdout } = await execUtils.pkStdio( ['keys', 'root', '--private-key', '--format', 'json'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: 'password-new', + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: 'password-new', + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); const newPublicKey = JSON.parse(stdout).publicKey; @@ -104,10 +112,12 @@ describe('renew', () => { ({ exitCode, stdout } = await execUtils.pkStdio( ['agent', 'status', '--format', 'json'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: 'password-new', + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: 'password-new', + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); const newNodeId = JSON.parse(stdout).nodeId; @@ -119,10 +129,12 @@ describe('renew', () => { ({ exitCode } = await execUtils.pkStdio( ['keys', 'password', '--password-new-file', passPath], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: 'password-new', + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: 'password-new', + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); }, diff --git a/tests/bin/keys/reset.test.ts b/tests/bin/keys/reset.test.ts index 5aca6650af..62fce56f18 100644 --- a/tests/bin/keys/reset.test.ts +++ b/tests/bin/keys/reset.test.ts @@ -59,10 +59,12 @@ describe('reset', () => { let { exitCode, stdout } = await execUtils.pkStdio( ['keys', 'root', '--private-key', '--format', 'json'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(exitCode).toBe(0); const prevPublicKey = JSON.parse(stdout).publicKey; @@ -70,10 +72,12 @@ describe('reset', () => { ({ exitCode, stdout } = await execUtils.pkStdio( ['agent', 'status', '--format', 'json'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); const prevNodeId = JSON.parse(stdout).nodeId; @@ -83,20 +87,24 @@ describe('reset', () => { ({ exitCode } = await execUtils.pkStdio( ['keys', 'reset', '--password-new-file', passPath], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); // Get new keypair and nodeId and compare against old ({ exitCode, stdout } = await execUtils.pkStdio( ['keys', 'root', '--private-key', '--format', 'json'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: 'password-new', + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: 'password-new', + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); const newPublicKey = JSON.parse(stdout).publicKey; @@ -104,10 +112,12 @@ describe('reset', () => { ({ exitCode, stdout } = await execUtils.pkStdio( ['agent', 'status', '--format', 'json'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: 'password-new', + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: 'password-new', + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); const newNodeId = JSON.parse(stdout).nodeId; @@ -119,10 +129,12 @@ describe('reset', () => { ({ exitCode } = await execUtils.pkStdio( ['keys', 'password', '--password-new-file', passPath], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: 'password-new', + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: 'password-new', + }, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); }, diff --git a/tests/bin/keys/root.test.ts b/tests/bin/keys/root.test.ts index 7121412400..b9d1cbeacd 100644 --- a/tests/bin/keys/root.test.ts +++ b/tests/bin/keys/root.test.ts @@ -20,13 +20,15 @@ describe('root', () => { testUtils.testIf( testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, )('root gets the public key', async () => { - const { exitCode, stdout } = await execUtils.pkStdio( + const { exitCode, stdout } = await execUtils.pkExec( ['keys', 'root', '--format', 'json'], { - PK_NODE_PATH: agentDir, - PK_PASSWORD: agentPassword, + env: { + PK_NODE_PATH: agentDir, + PK_PASSWORD: agentPassword, + }, + cwd: agentDir, }, - agentDir, ); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ @@ -36,13 +38,15 @@ describe('root', () => { testUtils.testIf( testUtils.isTestPlatformEmpty || testUtils.isTestPlatformDocker, )('root gets public and private keys', async () => { - const { exitCode, stdout } = await execUtils.pkStdio( + const { exitCode, stdout } = await execUtils.pkExec( ['keys', 'root', '--private-key', '--format', 'json'], { - PK_NODE_PATH: agentDir, - PK_PASSWORD: agentPassword, + env: { + PK_NODE_PATH: agentDir, + PK_PASSWORD: agentPassword, + }, + cwd: agentDir, }, - agentDir, ); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ diff --git a/tests/bin/keys/signVerify.test.ts b/tests/bin/keys/signVerify.test.ts index d98037875c..3fd577bf9f 100644 --- a/tests/bin/keys/signVerify.test.ts +++ b/tests/bin/keys/signVerify.test.ts @@ -29,13 +29,15 @@ describe('sign-verify', () => { await fs.promises.writeFile(dataPath, 'sign-me', { encoding: 'binary', }); - ({ exitCode, stdout } = await execUtils.pkStdio( + ({ exitCode, stdout } = await execUtils.pkExec( ['keys', 'sign', dataPath, '--format', 'json'], { - PK_NODE_PATH: agentDir, - PK_PASSWORD: agentPassword, + env: { + PK_NODE_PATH: agentDir, + PK_PASSWORD: agentPassword, + }, + cwd: agentDir, }, - agentDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ @@ -46,13 +48,15 @@ describe('sign-verify', () => { await fs.promises.writeFile(signaturePath, signed, { encoding: 'binary', }); - ({ exitCode, stdout } = await execUtils.pkStdio( + ({ exitCode, stdout } = await execUtils.pkExec( ['keys', 'verify', dataPath, signaturePath, '--format', 'json'], { - PK_NODE_PATH: agentDir, - PK_PASSWORD: agentPassword, + env: { + PK_NODE_PATH: agentDir, + PK_PASSWORD: agentPassword, + }, + cwd: agentDir, }, - agentDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ diff --git a/tests/bin/nodes/add.test.ts b/tests/bin/nodes/add.test.ts index 37cfc25488..69b3f67df3 100644 --- a/tests/bin/nodes/add.test.ts +++ b/tests/bin/nodes/add.test.ts @@ -69,20 +69,24 @@ describe('add', () => { `${port}`, ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(exitCode).toBe(0); // Checking if node was added. const { stdout } = await execUtils.pkStdio( ['nodes', 'find', nodesUtils.encodeNodeId(validNodeId)], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(stdout).toContain(validHost); expect(stdout).toContain(`${port}`); @@ -99,10 +103,12 @@ describe('add', () => { `${port}`, ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(exitCode).toBe(sysexits.USAGE); }, @@ -119,10 +125,12 @@ describe('add', () => { `${port}`, ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(exitCode).toBe(sysexits.USAGE); }, @@ -140,10 +148,12 @@ describe('add', () => { `${port}`, ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(exitCode).toBe(0); // Checking if node was added. @@ -164,10 +174,12 @@ describe('add', () => { `${port}`, ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(exitCode).toBe(sysexits.NOHOST); }, @@ -186,10 +198,12 @@ describe('add', () => { `${port}`, ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(exitCode).toBe(0); // Checking if node was added. diff --git a/tests/bin/nodes/claim.test.ts b/tests/bin/nodes/claim.test.ts index 53d65ac2a4..6b0147d6d1 100644 --- a/tests/bin/nodes/claim.test.ts +++ b/tests/bin/nodes/claim.test.ts @@ -89,10 +89,12 @@ describe('claim', () => { const { exitCode, stdout } = await execUtils.pkStdio( ['nodes', 'claim', remoteIdEncoded], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(exitCode).toBe(0); expect(stdout).toContain('Gestalt Invite'); @@ -108,10 +110,12 @@ describe('claim', () => { const { exitCode, stdout } = await execUtils.pkStdio( ['nodes', 'claim', remoteIdEncoded, '--force-invite'], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(exitCode).toBe(0); expect(stdout).toContain('Gestalt Invite'); @@ -125,10 +129,12 @@ describe('claim', () => { const { exitCode, stdout } = await execUtils.pkStdio( ['nodes', 'claim', remoteIdEncoded], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(exitCode).toBe(0); expect(stdout).toContain('cryptolink claim'); diff --git a/tests/bin/nodes/find.test.ts b/tests/bin/nodes/find.test.ts index 890409f8d1..90d1416da0 100644 --- a/tests/bin/nodes/find.test.ts +++ b/tests/bin/nodes/find.test.ts @@ -113,10 +113,12 @@ describe('find', () => { 'json', ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ @@ -140,10 +142,12 @@ describe('find', () => { 'json', ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ @@ -170,10 +174,12 @@ describe('find', () => { 'json', ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(exitCode).toBe(sysexits.GENERAL); expect(JSON.parse(stdout)).toEqual({ diff --git a/tests/bin/nodes/ping.test.ts b/tests/bin/nodes/ping.test.ts index cba66dbb1b..06ec3bad26 100644 --- a/tests/bin/nodes/ping.test.ts +++ b/tests/bin/nodes/ping.test.ts @@ -108,10 +108,12 @@ describe('ping', () => { 'json', ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(exitCode).toBe(sysexits.GENERAL); // Should fail with no response. for automation purposes. expect(stderr).toContain('No response received'); @@ -136,10 +138,12 @@ describe('ping', () => { 'json', ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(exitCode).not.toBe(0); // Should fail if node doesn't exist. expect(JSON.parse(stdout)).toEqual({ @@ -162,10 +166,12 @@ describe('ping', () => { 'json', ], { - PK_NODE_PATH: nodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: nodePath, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, ); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ diff --git a/tests/bin/notifications/sendReadClear.test.ts b/tests/bin/notifications/sendReadClear.test.ts index f7b52d04c3..c6101fc3db 100644 --- a/tests/bin/notifications/sendReadClear.test.ts +++ b/tests/bin/notifications/sendReadClear.test.ts @@ -70,7 +70,7 @@ describe('send/read/claim', () => { let exitCode, stdout; let readNotifications: Array; // Add receiver to sender's node graph so it can be contacted - ({ exitCode } = await execUtils.pkStdio( + ({ exitCode } = await execUtils.pkExec( [ 'nodes', 'add', @@ -79,14 +79,16 @@ describe('send/read/claim', () => { receiverPort.toString(), ], { - PK_NODE_PATH: senderAgentDir, - PK_PASSWORD: senderAgentPassword, + env: { + PK_NODE_PATH: senderAgentDir, + PK_PASSWORD: senderAgentPassword, + }, + cwd: senderAgentDir, }, - senderAgentDir, )); expect(exitCode).toBe(0); // Add sender to receiver's node graph so it can be trusted - ({ exitCode } = await execUtils.pkStdio( + ({ exitCode } = await execUtils.pkExec( [ 'nodes', 'add', @@ -95,24 +97,28 @@ describe('send/read/claim', () => { senderPort.toString(), ], { - PK_NODE_PATH: receiverAgentDir, - PK_PASSWORD: receiverAgentPassword, + env: { + PK_NODE_PATH: receiverAgentDir, + PK_PASSWORD: receiverAgentPassword, + }, + cwd: receiverAgentDir, }, - receiverAgentDir, )); expect(exitCode).toBe(0); // Trust sender so notification can be received - ({ exitCode } = await execUtils.pkStdio( + ({ exitCode } = await execUtils.pkExec( ['identities', 'trust', nodesUtils.encodeNodeId(senderId)], { - PK_NODE_PATH: receiverAgentDir, - PK_PASSWORD: receiverAgentPassword, + env: { + PK_NODE_PATH: receiverAgentDir, + PK_PASSWORD: receiverAgentPassword, + }, + cwd: receiverAgentDir, }, - receiverAgentDir, )); expect(exitCode).toBe(0); // Send some notifications - ({ exitCode } = await execUtils.pkStdio( + ({ exitCode } = await execUtils.pkExec( [ 'notifications', 'send', @@ -120,13 +126,15 @@ describe('send/read/claim', () => { 'test message 1', ], { - PK_NODE_PATH: senderAgentDir, - PK_PASSWORD: senderAgentPassword, + env: { + PK_NODE_PATH: senderAgentDir, + PK_PASSWORD: senderAgentPassword, + }, + cwd: senderAgentDir, }, - senderAgentDir, )); expect(exitCode).toBe(0); - ({ exitCode } = await execUtils.pkStdio( + ({ exitCode } = await execUtils.pkExec( [ 'notifications', 'send', @@ -134,13 +142,15 @@ describe('send/read/claim', () => { 'test message 2', ], { - PK_NODE_PATH: senderAgentDir, - PK_PASSWORD: senderAgentPassword, + env: { + PK_NODE_PATH: senderAgentDir, + PK_PASSWORD: senderAgentPassword, + }, + cwd: senderAgentDir, }, - senderAgentDir, )); expect(exitCode).toBe(0); - ({ exitCode } = await execUtils.pkStdio( + ({ exitCode } = await execUtils.pkExec( [ 'notifications', 'send', @@ -148,20 +158,24 @@ describe('send/read/claim', () => { 'test message 3', ], { - PK_NODE_PATH: senderAgentDir, - PK_PASSWORD: senderAgentPassword, + env: { + PK_NODE_PATH: senderAgentDir, + PK_PASSWORD: senderAgentPassword, + }, + cwd: senderAgentDir, }, - senderAgentDir, )); expect(exitCode).toBe(0); // Read notifications - ({ exitCode, stdout } = await execUtils.pkStdio( + ({ exitCode, stdout } = await execUtils.pkExec( ['notifications', 'read', '--format', 'json'], { - PK_NODE_PATH: receiverAgentDir, - PK_PASSWORD: receiverAgentPassword, + env: { + PK_NODE_PATH: receiverAgentDir, + PK_PASSWORD: receiverAgentPassword, + }, + cwd: receiverAgentDir, }, - receiverAgentDir, )); expect(exitCode).toBe(0); readNotifications = stdout @@ -194,13 +208,15 @@ describe('send/read/claim', () => { isRead: true, }); // Read only unread (none) - ({ exitCode, stdout } = await execUtils.pkStdio( + ({ exitCode, stdout } = await execUtils.pkExec( ['notifications', 'read', '--unread', '--format', 'json'], { - PK_NODE_PATH: receiverAgentDir, - PK_PASSWORD: receiverAgentPassword, + env: { + PK_NODE_PATH: receiverAgentDir, + PK_PASSWORD: receiverAgentPassword, + }, + cwd: receiverAgentDir, }, - receiverAgentDir, )); expect(exitCode).toBe(0); readNotifications = stdout @@ -209,13 +225,15 @@ describe('send/read/claim', () => { .map(JSON.parse); expect(readNotifications).toHaveLength(0); // Read notifications on reverse order - ({ exitCode, stdout } = await execUtils.pkStdio( + ({ exitCode, stdout } = await execUtils.pkExec( ['notifications', 'read', '--order=oldest', '--format', 'json'], { - PK_NODE_PATH: receiverAgentDir, - PK_PASSWORD: receiverAgentPassword, + env: { + PK_NODE_PATH: receiverAgentDir, + PK_PASSWORD: receiverAgentPassword, + }, + cwd: receiverAgentDir, }, - receiverAgentDir, )); expect(exitCode).toBe(0); readNotifications = stdout @@ -248,13 +266,15 @@ describe('send/read/claim', () => { isRead: true, }); // Read only one notification - ({ exitCode, stdout } = await execUtils.pkStdio( + ({ exitCode, stdout } = await execUtils.pkExec( ['notifications', 'read', '--number=1', '--format', 'json'], { - PK_NODE_PATH: receiverAgentDir, - PK_PASSWORD: receiverAgentPassword, + env: { + PK_NODE_PATH: receiverAgentDir, + PK_PASSWORD: receiverAgentPassword, + }, + cwd: receiverAgentDir, }, - receiverAgentDir, )); expect(exitCode).toBe(0); readNotifications = stdout @@ -271,22 +291,23 @@ describe('send/read/claim', () => { isRead: true, }); // Clear notifications - ({ exitCode } = await execUtils.pkStdio( - ['notifications', 'clear'], - { + ({ exitCode } = await execUtils.pkExec(['notifications', 'clear'], { + env: { PK_NODE_PATH: receiverAgentDir, PK_PASSWORD: receiverAgentPassword, }, - receiverAgentDir, - )); + cwd: receiverAgentDir, + })); // Check there are no more notifications - ({ exitCode, stdout } = await execUtils.pkStdio( + ({ exitCode, stdout } = await execUtils.pkExec( ['notifications', 'read', '--format', 'json'], { - PK_NODE_PATH: receiverAgentDir, - PK_PASSWORD: receiverAgentPassword, + env: { + PK_NODE_PATH: receiverAgentDir, + PK_PASSWORD: receiverAgentPassword, + }, + cwd: receiverAgentDir, }, - receiverAgentDir, )); expect(exitCode).toBe(0); readNotifications = stdout diff --git a/tests/bin/polykey.test.ts b/tests/bin/polykey.test.ts index d3feeff4ee..72cfc6b663 100644 --- a/tests/bin/polykey.test.ts +++ b/tests/bin/polykey.test.ts @@ -12,7 +12,7 @@ describe('polykey', () => { testUtils.isTestPlatformLinux || testUtils.isTestPlatformDocker, )('default help display', async () => { - const result = await execUtils.pkStdio([]); + const result = await execUtils.pkExec([]); expect(result.exitCode).toBe(0); expect(result.stdout).toBe(''); expect(result.stderr.length > 0).toBe(true); @@ -48,10 +48,12 @@ describe('polykey', () => { 'json', ], { - PK_TEST_DATA_PATH: dataDir, - PK_PASSWORD: password, + env: { + PK_TEST_DATA_PATH: dataDir, + PK_PASSWORD: password, + }, + cwd: dataDir, }, - dataDir, logger, ); const rlErr = readline.createInterface(agentProcess.stderr!); diff --git a/tests/bin/secrets/secrets.test.ts b/tests/bin/secrets/secrets.test.ts index afa4ab3686..a07e6cb57f 100644 --- a/tests/bin/secrets/secrets.test.ts +++ b/tests/bin/secrets/secrets.test.ts @@ -33,8 +33,10 @@ describe('CLI secrets', () => { // Authorize session await execUtils.pkStdio( ['agent', 'unlock', '-np', dataDir, '--password-file', passwordFile], - {}, - dataDir, + { + env: {}, + cwd: dataDir, + }, ); }); afterEach(async () => { @@ -64,7 +66,10 @@ describe('CLI secrets', () => { `${vaultName}:MySecret`, ]; - const result = await execUtils.pkStdio([...command], {}, dataDir); + const result = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result.exitCode).toBe(0); await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { @@ -99,7 +104,10 @@ describe('CLI secrets', () => { `${vaultName}:MySecret`, ]; - const result = await execUtils.pkStdio([...command], {}, dataDir); + const result = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result.exitCode).toBe(0); await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { @@ -122,7 +130,10 @@ describe('CLI secrets', () => { command = ['secrets', 'get', '-np', dataDir, `${vaultName}:MySecret`]; - const result = await execUtils.pkStdio([...command], {}, dataDir); + const result = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result.exitCode).toBe(0); }, ); @@ -142,7 +153,10 @@ describe('CLI secrets', () => { command = ['secrets', 'list', '-np', dataDir, vaultName]; - const result = await execUtils.pkStdio([...command], {}, dataDir); + const result = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result.exitCode).toBe(0); }, globalThis.defaultTimeout * 2, @@ -164,7 +178,10 @@ describe('CLI secrets', () => { '-r', ]; - const result = await execUtils.pkStdio([...command], {}, dataDir); + const result = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result.exitCode).toBe(0); await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { @@ -207,7 +224,10 @@ describe('CLI secrets', () => { 'MyRenamedSecret', ]; - const result = await execUtils.pkStdio([...command], {}, dataDir); + const result = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result.exitCode).toBe(0); await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { @@ -243,7 +263,10 @@ describe('CLI secrets', () => { `${vaultName}:MySecret`, ]; - const result2 = await execUtils.pkStdio([...command], {}, dataDir); + const result2 = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result2.exitCode).toBe(0); await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { @@ -285,7 +308,10 @@ describe('CLI secrets', () => { command = ['secrets', 'dir', '-np', dataDir, secretDir, vaultName]; - const result2 = await execUtils.pkStdio([...command], {}, dataDir); + const result2 = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result2.exitCode).toBe(0); await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { @@ -312,7 +338,10 @@ describe('CLI secrets', () => { command = ['secrets', 'stat', '-np', dataDir, `${vaultName}:MySecret`]; - const result = await execUtils.pkStdio([...command], {}, dataDir); + const result = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('nlink: 1'); expect(result.stdout).toContain('blocks: 1'); diff --git a/tests/bin/sessions.test.ts b/tests/bin/sessions.test.ts index a00e8f8676..910c171eab 100644 --- a/tests/bin/sessions.test.ts +++ b/tests/bin/sessions.test.ts @@ -53,28 +53,26 @@ describe('sessions', () => { logger, }); let exitCode; - ({ exitCode } = await execUtils.pkStdio( - ['agent', 'status'], - { + ({ exitCode } = await execUtils.pkStdio(['agent', 'status'], { + env: { PK_NODE_PATH: agentDir, PK_PASSWORD: agentPassword, }, - agentDir, - )); + cwd: agentDir, + })); expect(exitCode).toBe(0); const token1 = await session.readToken(); // Tokens are not nonces // Wait at least 1 second // To ensure that the next token has a new expiry await sleep(1100); - ({ exitCode } = await execUtils.pkStdio( - ['agent', 'status'], - { + ({ exitCode } = await execUtils.pkStdio(['agent', 'status'], { + env: { PK_NODE_PATH: agentDir, PK_PASSWORD: agentPassword, }, - agentDir, - )); + cwd: agentDir, + })); expect(exitCode).toBe(0); const token2 = await session.readToken(); expect(token1).not.toBe(token2); @@ -89,11 +87,13 @@ describe('sessions', () => { ({ exitCode, stderr } = await execUtils.pkStdio( ['agent', 'status', '--format', 'json'], { - PK_NODE_PATH: agentDir, - PK_PASSWORD: 'invalid', - PK_TOKEN: 'token', + env: { + PK_NODE_PATH: agentDir, + PK_PASSWORD: 'invalid', + PK_TOKEN: 'token', + }, + cwd: agentDir, }, - agentDir, )); execUtils.expectProcessError(exitCode, stderr, [ new clientErrors.ErrorClientAuthDenied(), @@ -102,11 +102,13 @@ describe('sessions', () => { ({ exitCode, stderr } = await execUtils.pkStdio( ['agent', 'status', '--format', 'json'], { - PK_NODE_PATH: agentDir, - PK_PASSWORD: 'invalid', - PK_TOKEN: undefined, + env: { + PK_NODE_PATH: agentDir, + PK_PASSWORD: 'invalid', + PK_TOKEN: undefined, + }, + cwd: agentDir, }, - agentDir, )); execUtils.expectProcessError(exitCode, stderr, [ new clientErrors.ErrorClientAuthDenied(), @@ -115,11 +117,13 @@ describe('sessions', () => { ({ exitCode, stderr } = await execUtils.pkStdio( ['agent', 'status', '--format', 'json'], { - PK_NODE_PATH: agentDir, - PK_PASSWORD: undefined, - PK_TOKEN: 'token', + env: { + PK_NODE_PATH: agentDir, + PK_PASSWORD: undefined, + PK_TOKEN: 'token', + }, + cwd: agentDir, }, - agentDir, )); execUtils.expectProcessError(exitCode, stderr, [ new clientErrors.ErrorClientAuthDenied(), @@ -130,24 +134,18 @@ describe('sessions', () => { 'prompt for password to authenticate attended commands', async () => { const password = agentPassword; - await execUtils.pkStdio( - ['agent', 'lock'], - { - PK_NODE_PATH: agentDir, - }, - agentDir, - ); + await execUtils.pkStdio(['agent', 'lock'], { + env: { PK_NODE_PATH: agentDir }, + cwd: agentDir, + }); mockedPrompts.mockClear(); mockedPrompts.mockImplementation(async (_opts: any) => { return { password }; }); - const { exitCode } = await execUtils.pkStdio( - ['agent', 'status'], - { - PK_NODE_PATH: agentDir, - }, - agentDir, - ); + const { exitCode } = await execUtils.pkStdio(['agent', 'status'], { + env: { PK_NODE_PATH: agentDir }, + cwd: agentDir, + }); expect(exitCode).toBe(0); // Prompted for password 1 time expect(mockedPrompts.mock.calls.length).toBe(1); @@ -157,26 +155,20 @@ describe('sessions', () => { testUtils.testIf(testUtils.isTestPlatformEmpty)( 're-prompts for password if unable to authenticate command', async () => { - await execUtils.pkStdio( - ['agent', 'lock'], - { - PK_NODE_PATH: agentDir, - }, - agentDir, - ); + await execUtils.pkStdio(['agent', 'lock'], { + env: { PK_NODE_PATH: agentDir }, + cwd: agentDir, + }); const validPassword = agentPassword; const invalidPassword = 'invalid'; mockedPrompts.mockClear(); mockedPrompts .mockResolvedValueOnce({ password: invalidPassword }) .mockResolvedValue({ password: validPassword }); - const { exitCode } = await execUtils.pkStdio( - ['agent', 'status'], - { - PK_NODE_PATH: agentDir, - }, - agentDir, - ); + const { exitCode } = await execUtils.pkStdio(['agent', 'status'], { + env: { PK_NODE_PATH: agentDir }, + cwd: agentDir, + }); expect(exitCode).toBe(0); // Prompted for password 2 times expect(mockedPrompts.mock.calls.length).toBe(2); diff --git a/tests/bin/vaults/vaults.test.ts b/tests/bin/vaults/vaults.test.ts index aacea58202..9f161e912c 100644 --- a/tests/bin/vaults/vaults.test.ts +++ b/tests/bin/vaults/vaults.test.ts @@ -73,8 +73,10 @@ describe('CLI vaults', () => { // Authorize session await execUtils.pkStdio( ['agent', 'unlock', '-np', dataDir, '--password-file', passwordFile], - {}, - dataDir, + { + env: {}, + cwd: dataDir, + }, ); vaultName = genVaultName(); command = []; @@ -96,7 +98,10 @@ describe('CLI vaults', () => { await polykeyAgent.vaultManager.createVault('Vault1' as VaultName); await polykeyAgent.vaultManager.createVault('Vault2' as VaultName); - const result = await execUtils.pkStdio([...command], {}, dataDir); + const result = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result.exitCode).toBe(0); }, ); @@ -106,12 +111,17 @@ describe('CLI vaults', () => { 'should create vaults', async () => { command = ['vaults', 'create', '-np', dataDir, 'MyTestVault']; - const result = await execUtils.pkStdio([...command], {}, dataDir); + const result = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result.exitCode).toBe(0); const result2 = await execUtils.pkStdio( ['vaults', 'touch', '-np', dataDir, 'MyTestVault2'], - {}, - dataDir, + { + env: {}, + cwd: dataDir, + }, ); expect(result2.exitCode).toBe(0); @@ -141,7 +151,10 @@ describe('CLI vaults', () => { const id = polykeyAgent.vaultManager.getVaultId(vaultName); expect(id).toBeTruthy(); - const result = await execUtils.pkStdio([...command], {}, dataDir); + const result = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result.exitCode).toBe(0); const list = (await polykeyAgent.vaultManager.listVaults()).keys(); @@ -167,7 +180,10 @@ describe('CLI vaults', () => { const id = polykeyAgent.vaultManager.getVaultId(vaultName); expect(id).toBeTruthy(); - const result = await execUtils.pkStdio([...command], {}, dataDir); + const result = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); // Exit code of the exception expect(result.exitCode).toBe(sysexits.USAGE); @@ -192,7 +208,10 @@ describe('CLI vaults', () => { id = polykeyAgent.vaultManager.getVaultId(vaultName); expect(id).toBeTruthy(); - const result2 = await execUtils.pkStdio([...command], {}, dataDir); + const result2 = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result2.exitCode).toBe(0); const list = (await polykeyAgent.vaultManager.listVaults()).keys(); @@ -274,7 +293,10 @@ describe('CLI vaults', () => { targetNodeIdEncoded, ]; - let result = await execUtils.pkStdio([...command], {}, dataDir); + let result = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result.exitCode).toBe(0); const clonedVaultId = await polykeyAgent.vaultManager.getVaultId( @@ -300,7 +322,7 @@ describe('CLI vaults', () => { vaultName, nodesUtils.encodeNodeId(targetNodeId), ]; - result = await execUtils.pkStdio([...command], {}, dataDir); + result = await execUtils.pkStdio([...command], { env: {}, cwd: dataDir }); expect(result.exitCode).toBe(0); const secondClonedVaultId = (await polykeyAgent.vaultManager.getVaultId( @@ -326,7 +348,7 @@ describe('CLI vaults', () => { ); command = ['vaults', 'pull', '-np', dataDir, vaultName]; - result = await execUtils.pkStdio([...command], {}, dataDir); + result = await execUtils.pkStdio([...command], { env: {}, cwd: dataDir }); expect(result.exitCode).toBe(0); await polykeyAgent.vaultManager.withVaults( @@ -349,7 +371,7 @@ describe('CLI vaults', () => { vaultsUtils.encodeVaultId(secondClonedVaultId), targetNodeIdEncoded, ]; - result = await execUtils.pkStdio([...command], {}, dataDir); + result = await execUtils.pkStdio([...command], { env: {}, cwd: dataDir }); expect(result.exitCode).toBe(sysexits.USAGE); expect(result.stderr).toContain('ErrorVaultsVaultUndefined'); @@ -363,7 +385,7 @@ describe('CLI vaults', () => { vaultsUtils.encodeVaultId(secondClonedVaultId), 'InvalidNodeId', ]; - result = await execUtils.pkStdio([...command], {}, dataDir); + result = await execUtils.pkStdio([...command], { env: {}, cwd: dataDir }); expect(result.exitCode).toBe(sysexits.USAGE); await targetPolykeyAgent.stop(); @@ -408,7 +430,10 @@ describe('CLI vaults', () => { vaultIdEncoded, targetNodeIdEncoded, ]; - const result = await execUtils.pkStdio([...command], {}, dataDir); + const result = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result.exitCode).toBe(0); // Check permission @@ -459,7 +484,10 @@ describe('CLI vaults', () => { vaultIdEncoded1, targetNodeIdEncoded, ]; - const result = await execUtils.pkStdio([...command], {}, dataDir); + const result = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result.exitCode).toBe(0); // Check permission @@ -481,7 +509,10 @@ describe('CLI vaults', () => { vaultIdEncoded2, targetNodeIdEncoded, ]; - const result2 = await execUtils.pkStdio([...command], {}, dataDir); + const result2 = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result2.exitCode).toBe(0); // Check permission @@ -525,14 +556,20 @@ describe('CLI vaults', () => { await polykeyAgent.acl.setVaultAction(vaultId2, targetNodeId, 'pull'); command = ['vaults', 'permissions', '-np', dataDir, vaultIdEncoded1]; - const result = await execUtils.pkStdio([...command], {}, dataDir); + const result = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result.exitCode).toBe(0); expect(result.stdout).toContain(targetNodeIdEncoded); expect(result.stdout).toContain('clone'); expect(result.stdout).toContain('pull'); command = ['vaults', 'permissions', '-np', dataDir, vaultIdEncoded2]; - const result2 = await execUtils.pkStdio([...command], {}, dataDir); + const result2 = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result2.exitCode).toBe(0); expect(result2.stdout).toContain(targetNodeIdEncoded); expect(result2.stdout).not.toContain('clone'); @@ -575,7 +612,10 @@ describe('CLI vaults', () => { ver1Oid, ]; - const result = await execUtils.pkStdio([...command], {}, dataDir); + const result = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result.exitCode).toBe(0); await polykeyAgent.vaultManager.withVaults([vaultId], async (vault) => { @@ -620,7 +660,10 @@ describe('CLI vaults', () => { ver1Oid, ]; - const result = await execUtils.pkStdio([...command], {}, dataDir); + const result = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result.exitCode).toBe(0); const command2 = [ @@ -632,7 +675,10 @@ describe('CLI vaults', () => { 'last', ]; - const result2 = await execUtils.pkStdio([...command2], {}, dataDir); + const result2 = await execUtils.pkStdio([...command2], { + env: {}, + cwd: dataDir, + }); expect(result2.exitCode).toBe(0); }, ); @@ -652,7 +698,10 @@ describe('CLI vaults', () => { 'NOT_A_VALID_CHECKOUT_ID', ]; - const result = await execUtils.pkStdio([...command], {}, dataDir); + const result = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result.exitCode).toBe(sysexits.USAGE); expect(result.stderr).toContain('ErrorVaultReferenceInvalid'); @@ -670,7 +719,10 @@ describe('CLI vaults', () => { 'NOT_A_VALID_CHECKOUT_ID', ]; - const result = await execUtils.pkStdio([...command], {}, dataDir); + const result = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result.exitCode).toBe(sysexits.USAGE); expect(result.stderr).toContain('ErrorVaultsVaultUndefined'); }, @@ -714,7 +766,10 @@ describe('CLI vaults', () => { async () => { const command = ['vaults', 'log', '-np', dataDir, vaultName]; - const result = await execUtils.pkStdio([...command], {}, dataDir); + const result = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result.exitCode).toEqual(0); expect(result.stdout).toContain(writeF1Oid); expect(result.stdout).toContain(writeF2Oid); @@ -726,7 +781,10 @@ describe('CLI vaults', () => { async () => { const command = ['vaults', 'log', '-np', dataDir, '-d', '2', vaultName]; - const result = await execUtils.pkStdio([...command], {}, dataDir); + const result = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result.exitCode).toEqual(0); expect(result.stdout).not.toContain(writeF1Oid); expect(result.stdout).toContain(writeF2Oid); @@ -748,7 +806,10 @@ describe('CLI vaults', () => { writeF2Oid, ]; - const result = await execUtils.pkStdio([...command], {}, dataDir); + const result = await execUtils.pkStdio([...command], { + env: {}, + cwd: dataDir, + }); expect(result.exitCode).toEqual(0); expect(result.stdout).not.toContain(writeF1Oid); expect(result.stdout).toContain(writeF2Oid); @@ -794,11 +855,10 @@ describe('CLI vaults', () => { '-np', dataDir, ]; - const result1 = await execUtils.pkStdio( - commands1, - { PK_PASSWORD: 'password' }, - dataDir, - ); + const result1 = await execUtils.pkStdio(commands1, { + env: { PK_PASSWORD: 'password' }, + cwd: dataDir, + }); expect(result1.exitCode).toEqual(sysexits.NOPERM); expect(result1.stderr).toContain( 'ErrorVaultsPermissionDenied: Permission was denied - Scanning is not allowed for', @@ -816,11 +876,10 @@ describe('CLI vaults', () => { '-np', dataDir, ]; - const result2 = await execUtils.pkStdio( - commands2, - { PK_PASSWORD: 'password' }, - dataDir, - ); + const result2 = await execUtils.pkStdio(commands2, { + env: { PK_PASSWORD: 'password' }, + cwd: dataDir, + }); expect(result2.exitCode).toEqual(sysexits.NOPERM); expect(result2.stderr).toContain( 'ErrorVaultsPermissionDenied: Permission was denied - Scanning is not allowed for', @@ -851,11 +910,10 @@ describe('CLI vaults', () => { '-np', dataDir, ]; - const result3 = await execUtils.pkStdio( - commands3, - { PK_PASSWORD: 'password' }, - dataDir, - ); + const result3 = await execUtils.pkStdio(commands3, { + env: { PK_PASSWORD: 'password' }, + cwd: dataDir, + }); expect(result3.exitCode).toBe(0); expect(result3.stdout).toContain( `Vault1\t\t${vaultsUtils.encodeVaultId(vault1Id)}\t\tclone`, diff --git a/tests/bootstrap/utils.test.ts b/tests/bootstrap/utils.test.ts index ce972f48bb..48783735ca 100644 --- a/tests/bootstrap/utils.test.ts +++ b/tests/bootstrap/utils.test.ts @@ -7,7 +7,7 @@ import * as bootstrapErrors from '@/bootstrap/errors'; import { utils as keysUtils } from '@/keys'; import { errors as statusErrors } from '@/status'; import config from '@/config'; -import * as testUtils from '../utils'; +import * as testUtils from '../utils/utils'; describe('bootstrap/utils', () => { const logger = new Logger('bootstrap/utils test', LogLevel.WARN, [ diff --git a/tests/client/service/gestaltsGestaltTrustByIdentity.test.ts b/tests/client/service/gestaltsGestaltTrustByIdentity.test.ts index d979b968cd..0790c2b6cb 100644 --- a/tests/client/service/gestaltsGestaltTrustByIdentity.test.ts +++ b/tests/client/service/gestaltsGestaltTrustByIdentity.test.ts @@ -33,7 +33,7 @@ import * as keysUtils from '@/keys/utils'; import * as clientUtils from '@/client/utils/utils'; import * as nodesUtils from '@/nodes/utils'; import TestProvider from '../../identities/TestProvider'; -import { expectRemoteError } from '../../utils'; +import { expectRemoteError } from '../../utils/utils'; import { globalRootKeyPems } from '../../fixtures/globalRootKeyPems'; describe('gestaltsGestaltTrustByIdentity', () => { diff --git a/tests/client/service/identitiesAuthenticate.test.ts b/tests/client/service/identitiesAuthenticate.test.ts index 6756d1162b..238038ccdf 100644 --- a/tests/client/service/identitiesAuthenticate.test.ts +++ b/tests/client/service/identitiesAuthenticate.test.ts @@ -16,7 +16,7 @@ import * as validationErrors from '@/validation/errors'; import * as clientUtils from '@/client/utils/utils'; import * as nodesUtils from '@/nodes/utils'; import TestProvider from '../../identities/TestProvider'; -import { expectRemoteError } from '../../utils'; +import { expectRemoteError } from '../../utils/utils'; describe('identitiesAuthenticate', () => { const logger = new Logger('identitiesAuthenticate test', LogLevel.WARN, [ diff --git a/tests/client/service/identitiesClaim.test.ts b/tests/client/service/identitiesClaim.test.ts index 928a6e211c..af4597836f 100644 --- a/tests/client/service/identitiesClaim.test.ts +++ b/tests/client/service/identitiesClaim.test.ts @@ -26,7 +26,7 @@ import * as claimsUtils from '@/claims/utils'; import * as nodesUtils from '@/nodes/utils'; import * as validationErrors from '@/validation/errors'; import TestProvider from '../../identities/TestProvider'; -import { expectRemoteError } from '../../utils'; +import { expectRemoteError } from '../../utils/utils'; import { globalRootKeyPems } from '../../fixtures/globalRootKeyPems'; describe('identitiesClaim', () => { diff --git a/tests/client/service/identitiesInfoConnectedGet.test.ts b/tests/client/service/identitiesInfoConnectedGet.test.ts index e0f57e5c4c..a735122205 100644 --- a/tests/client/service/identitiesInfoConnectedGet.test.ts +++ b/tests/client/service/identitiesInfoConnectedGet.test.ts @@ -16,7 +16,7 @@ import * as clientUtils from '@/client/utils/utils'; import * as nodesUtils from '@/nodes/utils'; import * as identitiesErrors from '@/identities/errors'; import TestProvider from '../../identities/TestProvider'; -import { expectRemoteError } from '../../utils'; +import { expectRemoteError } from '../../utils/utils'; describe('identitiesInfoConnectedGet', () => { const logger = new Logger('identitiesInfoConnectedGet test', LogLevel.WARN, [ diff --git a/tests/client/service/keysKeyPairRenew.test.ts b/tests/client/service/keysKeyPairRenew.test.ts index 47445ead05..aa6893ebb2 100644 --- a/tests/client/service/keysKeyPairRenew.test.ts +++ b/tests/client/service/keysKeyPairRenew.test.ts @@ -17,7 +17,7 @@ import * as utilsPB from '@/proto/js/polykey/v1/utils/utils_pb'; import * as clientUtils from '@/client/utils/utils'; import * as keysUtils from '@/keys/utils'; import { NodeManager } from '@/nodes'; -import * as testUtils from '../../utils'; +import * as testUtils from '../../utils/utils'; describe('keysKeyPairRenew', () => { const logger = new Logger('keysKeyPairRenew test', LogLevel.WARN, [ diff --git a/tests/client/service/keysKeyPairReset.test.ts b/tests/client/service/keysKeyPairReset.test.ts index 55af8f35c7..2ca5ea7c26 100644 --- a/tests/client/service/keysKeyPairReset.test.ts +++ b/tests/client/service/keysKeyPairReset.test.ts @@ -17,7 +17,7 @@ import * as utilsPB from '@/proto/js/polykey/v1/utils/utils_pb'; import * as clientUtils from '@/client/utils/utils'; import * as keysUtils from '@/keys/utils'; import { NodeManager } from '@/nodes'; -import * as testUtils from '../../utils'; +import * as testUtils from '../../utils/utils'; describe('keysKeyPairReset', () => { const logger = new Logger('keysKeyPairReset test', LogLevel.WARN, [ diff --git a/tests/client/service/nodesAdd.test.ts b/tests/client/service/nodesAdd.test.ts index 4144f7fd98..ae30111181 100644 --- a/tests/client/service/nodesAdd.test.ts +++ b/tests/client/service/nodesAdd.test.ts @@ -21,7 +21,7 @@ import * as utilsPB from '@/proto/js/polykey/v1/utils/utils_pb'; import * as nodesUtils from '@/nodes/utils'; import * as clientUtils from '@/client/utils/utils'; import * as validationErrors from '@/validation/errors'; -import { expectRemoteError } from '../../utils'; +import { expectRemoteError } from '../../utils/utils'; import { globalRootKeyPems } from '../../fixtures/globalRootKeyPems'; describe('nodesAdd', () => { diff --git a/tests/client/service/nodesClaim.test.ts b/tests/client/service/nodesClaim.test.ts index fc1b4e81e3..e5999eef9f 100644 --- a/tests/client/service/nodesClaim.test.ts +++ b/tests/client/service/nodesClaim.test.ts @@ -24,7 +24,7 @@ import * as nodesPB from '@/proto/js/polykey/v1/nodes/nodes_pb'; import * as utilsPB from '@/proto/js/polykey/v1/utils/utils_pb'; import * as clientUtils from '@/client/utils/utils'; import * as validationErrors from '@/validation/errors'; -import * as testUtils from '../../utils'; +import * as testUtils from '../../utils/utils'; import { globalRootKeyPems } from '../../fixtures/globalRootKeyPems'; describe('nodesClaim', () => { diff --git a/tests/client/service/nodesFind.test.ts b/tests/client/service/nodesFind.test.ts index 6f73fc1e11..16cd290481 100644 --- a/tests/client/service/nodesFind.test.ts +++ b/tests/client/service/nodesFind.test.ts @@ -19,7 +19,7 @@ import { ClientServiceService } from '@/proto/js/polykey/v1/client_service_grpc_ import * as nodesPB from '@/proto/js/polykey/v1/nodes/nodes_pb'; import * as clientUtils from '@/client/utils/utils'; import * as validationErrors from '@/validation/errors'; -import { expectRemoteError } from '../../utils'; +import { expectRemoteError } from '../../utils/utils'; import { globalRootKeyPems } from '../../fixtures/globalRootKeyPems'; describe('nodesFind', () => { diff --git a/tests/client/service/nodesPing.test.ts b/tests/client/service/nodesPing.test.ts index 7461f84fbf..4729550835 100644 --- a/tests/client/service/nodesPing.test.ts +++ b/tests/client/service/nodesPing.test.ts @@ -20,7 +20,7 @@ import * as utilsPB from '@/proto/js/polykey/v1/utils/utils_pb'; import * as nodesPB from '@/proto/js/polykey/v1/nodes/nodes_pb'; import * as clientUtils from '@/client/utils/utils'; import * as validationErrors from '@/validation/errors'; -import { expectRemoteError } from '../../utils'; +import { expectRemoteError } from '../../utils/utils'; import { globalRootKeyPems } from '../../fixtures/globalRootKeyPems'; describe('nodesPing', () => { diff --git a/tests/client/service/vaultsClone.test.ts b/tests/client/service/vaultsClone.test.ts index e9f906b87b..4419e39c7b 100644 --- a/tests/client/service/vaultsClone.test.ts +++ b/tests/client/service/vaultsClone.test.ts @@ -15,7 +15,7 @@ import GRPCServer from '@/grpc/GRPCServer'; import GRPCClientClient from '@/client/GRPCClientClient'; import vaultsClone from '@/client/service/vaultsClone'; import { ClientServiceService } from '@/proto/js/polykey/v1/client_service_grpc_pb'; -import * as testUtils from '../../utils'; +import * as testUtils from '../../utils/utils'; describe('vaultsClone', () => { const logger = new Logger('vaultsClone test', LogLevel.WARN, [ diff --git a/tests/client/service/vaultsCreateDeleteList.test.ts b/tests/client/service/vaultsCreateDeleteList.test.ts index f7159d630b..814e4f0c46 100644 --- a/tests/client/service/vaultsCreateDeleteList.test.ts +++ b/tests/client/service/vaultsCreateDeleteList.test.ts @@ -20,7 +20,7 @@ import { ClientServiceService } from '@/proto/js/polykey/v1/client_service_grpc_ import * as utilsPB from '@/proto/js/polykey/v1/utils/utils_pb'; import * as vaultsPB from '@/proto/js/polykey/v1/vaults/vaults_pb'; import * as clientUtils from '@/client/utils/utils'; -import * as testUtils from '../../utils'; +import * as testUtils from '../../utils/utils'; import { globalRootKeyPems } from '../../fixtures/globalRootKeyPems'; describe('vaultsCreateDeleteList', () => { diff --git a/tests/client/service/vaultsLog.test.ts b/tests/client/service/vaultsLog.test.ts index 96c1c1ae96..4c1ac5789f 100644 --- a/tests/client/service/vaultsLog.test.ts +++ b/tests/client/service/vaultsLog.test.ts @@ -18,7 +18,7 @@ import vaultsLog from '@/client/service/vaultsLog'; import { ClientServiceService } from '@/proto/js/polykey/v1/client_service_grpc_pb'; import * as vaultsPB from '@/proto/js/polykey/v1/vaults/vaults_pb'; import * as clientUtils from '@/client/utils/utils'; -import * as testUtils from '../../utils'; +import * as testUtils from '../../utils/utils'; import { globalRootKeyPems } from '../../fixtures/globalRootKeyPems'; describe('vaultsLog', () => { diff --git a/tests/client/service/vaultsPermissionSetUnsetGet.test.ts b/tests/client/service/vaultsPermissionSetUnsetGet.test.ts index e025591f2e..d35a60a21f 100644 --- a/tests/client/service/vaultsPermissionSetUnsetGet.test.ts +++ b/tests/client/service/vaultsPermissionSetUnsetGet.test.ts @@ -23,7 +23,7 @@ import * as nodesPB from '@/proto/js/polykey/v1/nodes/nodes_pb'; import * as vaultsPB from '@/proto/js/polykey/v1/vaults/vaults_pb'; import * as clientUtils from '@/client/utils/utils'; import * as nodesUtils from '@/nodes/utils'; -import * as testUtils from '../../utils'; +import * as testUtils from '../../utils/utils'; import { globalRootKeyPems } from '../../fixtures/globalRootKeyPems'; describe('vaultsPermissionSetUnsetGet', () => { diff --git a/tests/client/service/vaultsPull.test.ts b/tests/client/service/vaultsPull.test.ts index f438fa71ff..89f220199c 100644 --- a/tests/client/service/vaultsPull.test.ts +++ b/tests/client/service/vaultsPull.test.ts @@ -15,7 +15,7 @@ import GRPCServer from '@/grpc/GRPCServer'; import GRPCClientClient from '@/client/GRPCClientClient'; import vaultsPull from '@/client/service/vaultsPull'; import { ClientServiceService } from '@/proto/js/polykey/v1/client_service_grpc_pb'; -import * as testUtils from '../../utils'; +import * as testUtils from '../../utils/utils'; describe('vaultsPull', () => { const logger = new Logger('vaultsPull test', LogLevel.WARN, [ diff --git a/tests/client/service/vaultsRename.test.ts b/tests/client/service/vaultsRename.test.ts index d144630911..8428d5be19 100644 --- a/tests/client/service/vaultsRename.test.ts +++ b/tests/client/service/vaultsRename.test.ts @@ -18,7 +18,7 @@ import { ClientServiceService } from '@/proto/js/polykey/v1/client_service_grpc_ import * as vaultsPB from '@/proto/js/polykey/v1/vaults/vaults_pb'; import * as clientUtils from '@/client/utils/utils'; import * as vaultsUtils from '@/vaults/utils'; -import * as testUtils from '../../utils'; +import * as testUtils from '../../utils/utils'; import { globalRootKeyPems } from '../../fixtures/globalRootKeyPems'; describe('vaultsRename', () => { diff --git a/tests/client/service/vaultsScan.test.ts b/tests/client/service/vaultsScan.test.ts index 8e0409c80f..3bbfaed9ac 100644 --- a/tests/client/service/vaultsScan.test.ts +++ b/tests/client/service/vaultsScan.test.ts @@ -15,7 +15,7 @@ import GRPCServer from '@/grpc/GRPCServer'; import GRPCClientClient from '@/client/GRPCClientClient'; import vaultsScan from '@/client/service/vaultsScan'; import { ClientServiceService } from '@/proto/js/polykey/v1/client_service_grpc_pb'; -import * as testUtils from '../../utils'; +import * as testUtils from '../../utils/utils'; describe('vaultsScan', () => { const logger = new Logger('vaultsScan test', LogLevel.WARN, [ diff --git a/tests/client/service/vaultsSecretsEdit.test.ts b/tests/client/service/vaultsSecretsEdit.test.ts index 817cda3960..e39e2c6ce1 100644 --- a/tests/client/service/vaultsSecretsEdit.test.ts +++ b/tests/client/service/vaultsSecretsEdit.test.ts @@ -20,7 +20,7 @@ import * as vaultsPB from '@/proto/js/polykey/v1/vaults/vaults_pb'; import * as secretsPB from '@/proto/js/polykey/v1/secrets/secrets_pb'; import * as clientUtils from '@/client/utils/utils'; import * as vaultsUtils from '@/vaults/utils'; -import * as testUtils from '../../utils'; +import * as testUtils from '../../utils/utils'; import { globalRootKeyPems } from '../../fixtures/globalRootKeyPems'; describe('vaultsSecretsEdit', () => { diff --git a/tests/client/service/vaultsSecretsMkdir.test.ts b/tests/client/service/vaultsSecretsMkdir.test.ts index 7b78c6e549..6b13cb2340 100644 --- a/tests/client/service/vaultsSecretsMkdir.test.ts +++ b/tests/client/service/vaultsSecretsMkdir.test.ts @@ -19,7 +19,7 @@ import * as vaultsPB from '@/proto/js/polykey/v1/vaults/vaults_pb'; import * as utilsPB from '@/proto/js/polykey/v1/utils/utils_pb'; import * as clientUtils from '@/client/utils/utils'; import * as vaultsUtils from '@/vaults/utils'; -import * as testUtils from '../../utils'; +import * as testUtils from '../../utils/utils'; import { globalRootKeyPems } from '../../fixtures/globalRootKeyPems'; describe('vaultsSecretsMkdir', () => { diff --git a/tests/client/service/vaultsSecretsNewDeleteGet.test.ts b/tests/client/service/vaultsSecretsNewDeleteGet.test.ts index 32ed9030fc..8c42be37e8 100644 --- a/tests/client/service/vaultsSecretsNewDeleteGet.test.ts +++ b/tests/client/service/vaultsSecretsNewDeleteGet.test.ts @@ -23,7 +23,7 @@ import * as secretsPB from '@/proto/js/polykey/v1/secrets/secrets_pb'; import * as clientUtils from '@/client/utils/utils'; import * as vaultsUtils from '@/vaults/utils'; import * as vaultsErrors from '@/vaults/errors'; -import * as testUtils from '../../utils'; +import * as testUtils from '../../utils/utils'; import { globalRootKeyPems } from '../../fixtures/globalRootKeyPems'; describe('vaultsSecretsNewDeleteGet', () => { diff --git a/tests/client/service/vaultsSecretsNewDirList.test.ts b/tests/client/service/vaultsSecretsNewDirList.test.ts index e0ed0fda7e..afa8d5b19e 100644 --- a/tests/client/service/vaultsSecretsNewDirList.test.ts +++ b/tests/client/service/vaultsSecretsNewDirList.test.ts @@ -21,7 +21,7 @@ import * as utilsPB from '@/proto/js/polykey/v1/utils/utils_pb'; import * as secretsPB from '@/proto/js/polykey/v1/secrets/secrets_pb'; import * as clientUtils from '@/client/utils/utils'; import * as vaultsUtils from '@/vaults/utils'; -import * as testUtils from '../../utils'; +import * as testUtils from '../../utils/utils'; import { globalRootKeyPems } from '../../fixtures/globalRootKeyPems'; describe('vaultsSecretsNewDirList', () => { diff --git a/tests/client/service/vaultsSecretsRename.test.ts b/tests/client/service/vaultsSecretsRename.test.ts index 51c4585230..32c8a4e555 100644 --- a/tests/client/service/vaultsSecretsRename.test.ts +++ b/tests/client/service/vaultsSecretsRename.test.ts @@ -20,7 +20,7 @@ import * as secretsPB from '@/proto/js/polykey/v1/secrets/secrets_pb'; import * as utilsPB from '@/proto/js/polykey/v1/utils/utils_pb'; import * as clientUtils from '@/client/utils/utils'; import * as vaultsUtils from '@/vaults/utils'; -import * as testUtils from '../../utils'; +import * as testUtils from '../../utils/utils'; import { globalRootKeyPems } from '../../fixtures/globalRootKeyPems'; describe('vaultsSecretsRename', () => { diff --git a/tests/client/service/vaultsSecretsStat.test.ts b/tests/client/service/vaultsSecretsStat.test.ts index 80ec8eaed9..46d65fc935 100644 --- a/tests/client/service/vaultsSecretsStat.test.ts +++ b/tests/client/service/vaultsSecretsStat.test.ts @@ -20,7 +20,7 @@ import * as vaultsPB from '@/proto/js/polykey/v1/vaults/vaults_pb'; import * as secretsPB from '@/proto/js/polykey/v1/secrets/secrets_pb'; import * as clientUtils from '@/client/utils/utils'; import * as vaultsUtils from '@/vaults/utils'; -import * as testUtils from '../../utils'; +import * as testUtils from '../../utils/utils'; import { globalRootKeyPems } from '../../fixtures/globalRootKeyPems'; describe('vaultsSecretsStat', () => { diff --git a/tests/client/service/vaultsVersion.test.ts b/tests/client/service/vaultsVersion.test.ts index 7e0e3f13a3..3c2178a491 100644 --- a/tests/client/service/vaultsVersion.test.ts +++ b/tests/client/service/vaultsVersion.test.ts @@ -20,7 +20,7 @@ import * as vaultsPB from '@/proto/js/polykey/v1/vaults/vaults_pb'; import * as clientUtils from '@/client/utils/utils'; import * as vaultsUtils from '@/vaults/utils'; import * as vaultsErrors from '@/vaults/errors'; -import * as testUtils from '../../utils'; +import * as testUtils from '../../utils/utils'; import { globalRootKeyPems } from '../../fixtures/globalRootKeyPems'; describe('vaultsVersion', () => { diff --git a/tests/grpc/GRPCClient.test.ts b/tests/grpc/GRPCClient.test.ts index 2062803bc8..f09bb79d43 100644 --- a/tests/grpc/GRPCClient.test.ts +++ b/tests/grpc/GRPCClient.test.ts @@ -19,7 +19,7 @@ import * as utilsPB from '@/proto/js/polykey/v1/utils/utils_pb'; import { timerStart } from '@/utils'; import * as utils from './utils'; import * as testNodesUtils from '../nodes/utils'; -import { expectRemoteError } from '../utils'; +import { expectRemoteError } from '../utils/utils'; describe('GRPCClient', () => { const logger = new Logger('GRPCClient Test', LogLevel.WARN, [ diff --git a/tests/grpc/utils.test.ts b/tests/grpc/utils.test.ts index f89819693e..ee0c8c6d27 100644 --- a/tests/grpc/utils.test.ts +++ b/tests/grpc/utils.test.ts @@ -8,7 +8,7 @@ import * as grpcErrors from '@/grpc/errors'; import * as errors from '@/errors'; import * as utilsPB from '@/proto/js/polykey/v1/utils/utils_pb'; import * as utils from './utils'; -import * as testUtils from '../utils'; +import * as testUtils from '../utils/utils'; describe('GRPC utils', () => { const logger = new Logger('GRPC utils Test', LogLevel.WARN, [ diff --git a/tests/grpc/utils/testService.ts b/tests/grpc/utils/testService.ts index bec280ffca..8f860a08f9 100644 --- a/tests/grpc/utils/testService.ts +++ b/tests/grpc/utils/testService.ts @@ -15,7 +15,7 @@ import * as grpcErrors from '@/grpc/errors'; import * as clientUtils from '@/client/utils'; import * as utilsPB from '@/proto/js/polykey/v1/utils/utils_pb'; import { sleep } from '@/utils'; -import * as testUtils from '../../utils'; +import * as testUtils from '../../utils/utils'; function createTestService({ authenticate, diff --git a/tests/nat/DMZ.test.ts b/tests/nat/DMZ.test.ts index cce591e355..4166c7518f 100644 --- a/tests/nat/DMZ.test.ts +++ b/tests/nat/DMZ.test.ts @@ -40,9 +40,7 @@ describe('DMZ', () => { const password = 'abc123'; const usrns = testNatUtils.createUserNamespace(logger); const netns = testNatUtils.createNetworkNamespace(usrns.pid!, logger); - const agentProcess = await testNatUtils.pkSpawnNs( - usrns.pid!, - netns.pid!, + const agentProcess = await execUtils.pkSpawn( [ 'agent', 'start', @@ -59,10 +57,17 @@ describe('DMZ', () => { 'json', ], { - PK_PASSWORD: password, - PK_ROOT_KEY: globalRootKeyPems[0], + env: { + PK_PASSWORD: password, + PK_ROOT_KEY: globalRootKeyPems[0], + }, + command: `nsenter ${testNatUtils + .nsenter(usrns.pid!, netns.pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, logger.getChild('agentProcess'), ); const rlOut = readline.createInterface(agentProcess.stdout!); @@ -142,9 +147,7 @@ describe('DMZ', () => { // └────────────────────────────────────┘ └────────────────────────────────────┘ // Since neither node is behind a NAT can directly add eachother's // details using pk nodes add - await testNatUtils.pkExecNs( - userPid!, - agent1Pid!, + await execUtils.pkExec( [ 'nodes', 'add', @@ -154,14 +157,19 @@ describe('DMZ', () => { '--no-ping', ], { - PK_NODE_PATH: agent1NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent1NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent1Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, ); - await testNatUtils.pkExecNs( - userPid!, - agent2Pid!, + await execUtils.pkExec( [ 'nodes', 'add', @@ -171,36 +179,53 @@ describe('DMZ', () => { '--no-ping', ], { - PK_NODE_PATH: agent2NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent2NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent2Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, ); let exitCode, stdout; - ({ exitCode, stdout } = await testNatUtils.pkExecNs( - userPid!, - agent1Pid!, + ({ exitCode, stdout } = await execUtils.pkExec( ['nodes', 'ping', agent2NodeId, '--format', 'json'], { - PK_NODE_PATH: agent1NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent1NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent1Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ success: true, message: 'Node is Active.', }); - ({ exitCode, stdout } = await testNatUtils.pkExecNs( - userPid!, - agent2Pid!, + ({ exitCode, stdout } = await execUtils.pkExec( ['nodes', 'ping', agent1NodeId, '--format', 'json'], { - PK_NODE_PATH: agent2NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent2NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent2Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ @@ -238,30 +263,40 @@ describe('DMZ', () => { // Should be able to ping straight away using the details from the // seed node let exitCode, stdout; - ({ exitCode, stdout } = await testNatUtils.pkExecNs( - userPid!, - agent1Pid!, + ({ exitCode, stdout } = await execUtils.pkExec( ['nodes', 'ping', agent2NodeId, '--format', 'json'], { - PK_NODE_PATH: agent1NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent1NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent1Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ success: true, message: 'Node is Active.', }); - ({ exitCode, stdout } = await testNatUtils.pkExecNs( - userPid!, - agent2Pid!, + ({ exitCode, stdout } = await execUtils.pkExec( ['nodes', 'ping', agent1NodeId, '--format', 'json'], { - PK_NODE_PATH: agent2NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent2NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent2Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ diff --git a/tests/nat/endpointDependentNAT.test.ts b/tests/nat/endpointDependentNAT.test.ts index f8a771912a..3d2271d1f1 100644 --- a/tests/nat/endpointDependentNAT.test.ts +++ b/tests/nat/endpointDependentNAT.test.ts @@ -4,6 +4,7 @@ import fs from 'fs'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import * as testNatUtils from './utils'; import * as testUtils from '../utils'; +import * as execUtils from '../utils/exec'; const supportsNatTesting = testUtils.isPlatformLinux && @@ -43,9 +44,7 @@ describe('endpoint dependent NAT traversal', () => { tearDownNAT, } = await testNatUtils.setupNAT('edm', 'dmz', logger); // Since node2 is not behind a NAT can directly add its details - await testNatUtils.pkExecNs( - userPid!, - agent1Pid!, + await execUtils.pkExec( [ 'nodes', 'add', @@ -55,20 +54,32 @@ describe('endpoint dependent NAT traversal', () => { '--no-ping', ], { - PK_NODE_PATH: agent1NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent1NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent1Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, ); - const { exitCode, stdout } = await testNatUtils.pkExecNs( - userPid!, - agent1Pid!, + const { exitCode, stdout } = await execUtils.pkExec( ['nodes', 'ping', agent2NodeId, '--format', 'json'], { - PK_NODE_PATH: agent1NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent1NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent1Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, ); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ @@ -97,9 +108,7 @@ describe('endpoint dependent NAT traversal', () => { tearDownNAT, } = await testNatUtils.setupNAT('dmz', 'edm', logger); // Agent 2 must ping Agent 1 first, since Agent 2 is behind a NAT - await testNatUtils.pkExecNs( - userPid!, - agent2Pid!, + await execUtils.pkExec( [ 'nodes', 'add', @@ -109,21 +118,33 @@ describe('endpoint dependent NAT traversal', () => { '--no-ping', ], { - PK_NODE_PATH: agent2NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent2NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent2Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, ); let exitCode, stdout; - ({ exitCode, stdout } = await testNatUtils.pkExecNs( - userPid!, - agent2Pid!, + ({ exitCode, stdout } = await execUtils.pkExec( ['nodes', 'ping', agent1NodeId, '--format', 'json'], { - PK_NODE_PATH: agent2NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent2NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent2Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ @@ -131,15 +152,20 @@ describe('endpoint dependent NAT traversal', () => { message: 'Node is Active.', }); // Can now ping Agent 2 (it will be expecting a response) - ({ exitCode, stdout } = await testNatUtils.pkExecNs( - userPid!, - agent1Pid!, + ({ exitCode, stdout } = await execUtils.pkExec( ['nodes', 'ping', agent2NodeId, '--format', 'json'], { - PK_NODE_PATH: agent1NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent1NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent1Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ @@ -169,15 +195,20 @@ describe('endpoint dependent NAT traversal', () => { // since port mapping changes between targets in EDM mapping // Node 2 -> Node 1 ping should fail (Node 1 behind NAT) let exitCode, stdout; - ({ exitCode, stdout } = await testNatUtils.pkExecNs( - userPid!, - agent2Pid!, + ({ exitCode, stdout } = await execUtils.pkExec( ['nodes', 'ping', agent1NodeId, '--format', 'json'], { - PK_NODE_PATH: agent2NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent2NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent2Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(1); expect(JSON.parse(stdout)).toEqual({ @@ -185,15 +216,20 @@ describe('endpoint dependent NAT traversal', () => { message: `Failed to resolve node ID ${agent1NodeId} to an address.`, }); // Node 1 -> Node 2 ping should also fail for the same reason - ({ exitCode, stdout } = await testNatUtils.pkExecNs( - userPid!, - agent1Pid!, + ({ exitCode, stdout } = await execUtils.pkExec( ['nodes', 'ping', agent2NodeId, '--format', 'json'], { - PK_NODE_PATH: agent1NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent1NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent1Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(1); expect(JSON.parse(stdout)).toEqual({ @@ -221,30 +257,40 @@ describe('endpoint dependent NAT traversal', () => { } = await testNatUtils.setupNATWithSeedNode('edm', 'eim', logger); // Since one of the nodes uses EDM NAT we cannot punch through let exitCode, stdout; - ({ exitCode, stdout } = await testNatUtils.pkExecNs( - userPid!, - agent2Pid!, + ({ exitCode, stdout } = await execUtils.pkExec( ['nodes', 'ping', agent1NodeId, '--format', 'json'], { - PK_NODE_PATH: agent2NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent2NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent2Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(1); expect(JSON.parse(stdout)).toEqual({ success: false, message: `Failed to resolve node ID ${agent1NodeId} to an address.`, }); - ({ exitCode, stdout } = await testNatUtils.pkExecNs( - userPid!, - agent1Pid!, + ({ exitCode, stdout } = await execUtils.pkExec( ['nodes', 'ping', agent2NodeId, '--format', 'json'], { - PK_NODE_PATH: agent1NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent1NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent1Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(1); expect(JSON.parse(stdout)).toEqual({ diff --git a/tests/nat/endpointIndependentNAT.test.ts b/tests/nat/endpointIndependentNAT.test.ts index 1c3df4309b..d713300fc4 100644 --- a/tests/nat/endpointIndependentNAT.test.ts +++ b/tests/nat/endpointIndependentNAT.test.ts @@ -4,6 +4,7 @@ import fs from 'fs'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import * as testNatUtils from './utils'; import * as testUtils from '../utils'; +import * as execUtils from '../utils/exec'; const supportsNatTesting = testUtils.isPlatformLinux && @@ -43,9 +44,7 @@ describe('endpoint independent NAT traversal', () => { tearDownNAT, } = await testNatUtils.setupNAT('eim', 'dmz', logger); // Since node2 is not behind a NAT can directly add its details - await testNatUtils.pkExecNs( - userPid!, - agent1Pid!, + await execUtils.pkExec( [ 'nodes', 'add', @@ -55,20 +54,32 @@ describe('endpoint independent NAT traversal', () => { '--no-ping', ], { - PK_NODE_PATH: agent1NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent1NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent1Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, ); - const { exitCode, stdout } = await testNatUtils.pkExecNs( - userPid!, - agent1Pid!, + const { exitCode, stdout } = await execUtils.pkExec( ['nodes', 'ping', agent2NodeId, '--format', 'json'], { - PK_NODE_PATH: agent1NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent1NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent1Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, ); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ @@ -98,9 +109,7 @@ describe('endpoint independent NAT traversal', () => { agent2ProxyPort, tearDownNAT, } = await testNatUtils.setupNAT('dmz', 'eim', logger); - await testNatUtils.pkExecNs( - userPid!, - agent2Pid!, + await execUtils.pkExec( [ 'nodes', 'add', @@ -110,14 +119,19 @@ describe('endpoint independent NAT traversal', () => { '--no-ping', ], { - PK_NODE_PATH: agent2NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent2NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent2Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, ); - await testNatUtils.pkExecNs( - userPid!, - agent1Pid!, + await execUtils.pkExec( [ 'nodes', 'add', @@ -127,22 +141,34 @@ describe('endpoint independent NAT traversal', () => { '--no-ping', ], { - PK_NODE_PATH: agent1NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent1NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent1Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, ); // If we try to ping Agent 2 it will fail let exitCode, stdout; - ({ exitCode, stdout } = await testNatUtils.pkExecNs( - userPid!, - agent1Pid!, + ({ exitCode, stdout } = await execUtils.pkExec( ['nodes', 'ping', agent2NodeId, '--format', 'json'], { - PK_NODE_PATH: agent1NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent1NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent1Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(1); expect(JSON.parse(stdout)).toEqual({ @@ -150,15 +176,20 @@ describe('endpoint independent NAT traversal', () => { message: 'No response received', }); // But Agent 2 can ping Agent 1 because Agent 1 is not behind a NAT - ({ exitCode, stdout } = await testNatUtils.pkExecNs( - userPid!, - agent2Pid!, + ({ exitCode, stdout } = await execUtils.pkExec( ['nodes', 'ping', agent1NodeId, '--format', 'json'], { - PK_NODE_PATH: agent2NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent2NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent2Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ @@ -166,15 +197,20 @@ describe('endpoint independent NAT traversal', () => { message: 'Node is Active.', }); // Can now ping Agent 2 (it will be expecting a response) - ({ exitCode, stdout } = await testNatUtils.pkExecNs( - userPid!, - agent1Pid!, + ({ exitCode, stdout } = await execUtils.pkExec( ['nodes', 'ping', agent2NodeId, '--format', 'json'], { - PK_NODE_PATH: agent1NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent1NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent1Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ @@ -204,9 +240,7 @@ describe('endpoint independent NAT traversal', () => { agent2ProxyPort, tearDownNAT, } = await testNatUtils.setupNAT('dmz', 'eim', logger); - await testNatUtils.pkExecNs( - userPid!, - agent2Pid!, + await execUtils.pkExec( [ 'nodes', 'add', @@ -216,14 +250,19 @@ describe('endpoint independent NAT traversal', () => { '--no-ping', ], { - PK_NODE_PATH: agent2NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent2NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent2Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, ); - await testNatUtils.pkExecNs( - userPid!, - agent1Pid!, + await execUtils.pkExec( [ 'nodes', 'add', @@ -233,22 +272,34 @@ describe('endpoint independent NAT traversal', () => { '--no-ping', ], { - PK_NODE_PATH: agent1NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent1NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent1Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, ); // If we try to ping Agent 2 it will fail let exitCode, stdout; - ({ exitCode, stdout } = await testNatUtils.pkExecNs( - userPid!, - agent1Pid!, + ({ exitCode, stdout } = await execUtils.pkExec( ['nodes', 'ping', agent2NodeId, '--format', 'json'], { - PK_NODE_PATH: agent1NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent1NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent1Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(1); expect(JSON.parse(stdout)).toEqual({ @@ -256,15 +307,20 @@ describe('endpoint independent NAT traversal', () => { message: 'No response received', }); // But Agent 2 can ping Agent 1 because it's expecting a response now - ({ exitCode, stdout } = await testNatUtils.pkExecNs( - userPid!, - agent2Pid!, + ({ exitCode, stdout } = await execUtils.pkExec( ['nodes', 'ping', agent1NodeId, '--format', 'json'], { - PK_NODE_PATH: agent2NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent2NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent2Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ @@ -272,15 +328,20 @@ describe('endpoint independent NAT traversal', () => { message: 'Node is Active.', }); // Can now ping Agent 2 (it will be expecting a response too) - ({ exitCode, stdout } = await testNatUtils.pkExecNs( - userPid!, - agent1Pid!, + ({ exitCode, stdout } = await execUtils.pkExec( ['nodes', 'ping', agent2NodeId, '--format', 'json'], { - PK_NODE_PATH: agent1NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent1NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent1Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ @@ -309,30 +370,40 @@ describe('endpoint independent NAT traversal', () => { // Should be able to ping straight away using the seed node as a // signaller let exitCode, stdout; - ({ exitCode, stdout } = await testNatUtils.pkExecNs( - userPid!, - agent1Pid!, + ({ exitCode, stdout } = await execUtils.pkExec( ['nodes', 'ping', agent2NodeId, '--format', 'json'], { - PK_NODE_PATH: agent1NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent1NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent1Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ success: true, message: 'Node is Active.', }); - ({ exitCode, stdout } = await testNatUtils.pkExecNs( - userPid!, - agent2Pid!, + ({ exitCode, stdout } = await execUtils.pkExec( ['nodes', 'ping', agent1NodeId, '--format', 'json'], { - PK_NODE_PATH: agent2NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent2NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent2Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(0); expect(JSON.parse(stdout)).toEqual({ @@ -360,30 +431,40 @@ describe('endpoint independent NAT traversal', () => { } = await testNatUtils.setupNATWithSeedNode('eim', 'edm', logger); // Since one of the nodes uses EDM NAT we cannot punch through let exitCode, stdout; - ({ exitCode, stdout } = await testNatUtils.pkExecNs( - userPid!, - agent2Pid!, + ({ exitCode, stdout } = await execUtils.pkExec( ['nodes', 'ping', agent1NodeId, '--format', 'json'], { - PK_NODE_PATH: agent2NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent2NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent2Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(1); expect(JSON.parse(stdout)).toEqual({ success: false, message: `Failed to resolve node ID ${agent1NodeId} to an address.`, }); - ({ exitCode, stdout } = await testNatUtils.pkExecNs( - userPid!, - agent1Pid!, + ({ exitCode, stdout } = await execUtils.pkExec( ['nodes', 'ping', agent2NodeId, '--format', 'json'], { - PK_NODE_PATH: agent1NodePath, - PK_PASSWORD: password, + env: { + PK_NODE_PATH: agent1NodePath, + PK_PASSWORD: password, + }, + command: `nsenter ${testNatUtils + .nsenter(userPid!, agent1Pid!) + .join(' ')} ts-node --project ${execUtils.tsConfigPath} ${ + execUtils.polykeyPath + }`, + cwd: dataDir, }, - dataDir, )); expect(exitCode).toBe(1); expect(JSON.parse(stdout)).toEqual({ diff --git a/tests/nat/utils.ts b/tests/nat/utils.ts index a5695f988f..8d0c09568b 100644 --- a/tests/nat/utils.ts +++ b/tests/nat/utils.ts @@ -2,12 +2,12 @@ import type { ChildProcess } from 'child_process'; import os from 'os'; import fs from 'fs'; import path from 'path'; -import child_process from 'child_process'; +import childProcess from 'child_process'; import readline from 'readline'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import * as execUtils from '../utils/exec'; import { globalRootKeyPems } from '../fixtures/globalRootKeyPems'; -import { nsenter, pkExecNs, pkSpawnNs } from '../utils/exec'; +import { tsConfigPath, polykeyPath, pkSpawn } from '../utils/exec'; type NATType = 'eim' | 'edm' | 'dmz'; @@ -123,6 +123,22 @@ const AGENT2_PORT = '55552'; */ const DMZ_PORT = '55555'; +/** + * Formats the command to enter a namespace to run a process inside it + */ +const nsenter = (usrnsPid: number, netnsPid: number) => { + return [ + '--target', + usrnsPid.toString(), + '--user', + '--preserve-credentials', + 'nsenter', + '--target', + netnsPid.toString(), + '--net', + ]; +}; + /** * Create a user namespace from which network namespaces can be created without * requiring sudo @@ -131,7 +147,7 @@ function createUserNamespace( logger: Logger = new Logger(createUserNamespace.name), ): ChildProcess { logger.info('unshare --user --map-root-user'); - const subprocess = child_process.spawn( + const subprocess = childProcess.spawn( 'unshare', ['--user', '--map-root-user'], { @@ -156,7 +172,7 @@ function createNetworkNamespace( logger.info( `nsenter --target ${usrnsPid.toString()} --user --preserve-credentials unshare --net`, ); - const subprocess = child_process.spawn( + const subprocess = childProcess.spawn( 'nsenter', [ '--target', @@ -1025,9 +1041,7 @@ async function setupNATWithSeedNode( router2Netns.pid!, logger, ); - const seedNode = await pkSpawnNs( - usrns.pid!, - seedNetns.pid!, + const seedNode = await pkSpawn( [ 'agent', 'start', @@ -1046,10 +1060,15 @@ async function setupNATWithSeedNode( 'json', ], { - PK_PASSWORD: password, - PK_ROOT_KEY: globalRootKeyPems[0], + env: { + PK_PASSWORD: password, + PK_ROOT_KEY: globalRootKeyPems[0], + }, + command: `nsenter ${nsenter(usrns.pid!, seedNetns.pid!).join( + ' ', + )} ts-node --project ${tsConfigPath} ${polykeyPath}`, + cwd: dataDir, }, - dataDir, logger.getChild('seed'), ); const rlOutSeed = readline.createInterface(seedNode.stdout!); @@ -1059,9 +1078,7 @@ async function setupNATWithSeedNode( }); const nodeIdSeed = JSON.parse(stdoutSeed).nodeId; const proxyPortSeed = JSON.parse(stdoutSeed).proxyPort; - const agent1 = await pkSpawnNs( - usrns.pid!, - agent1Netns.pid!, + const agent1 = await pkSpawn( [ 'agent', 'start', @@ -1084,10 +1101,15 @@ async function setupNATWithSeedNode( 'json', ], { - PK_PASSWORD: password, - PK_ROOT_KEY: globalRootKeyPems[1], + env: { + PK_PASSWORD: password, + PK_ROOT_KEY: globalRootKeyPems[1], + }, + command: `nsenter ${nsenter(usrns.pid!, agent1Netns.pid!).join( + ' ', + )} ts-node --project ${tsConfigPath} ${polykeyPath}`, + cwd: dataDir, }, - dataDir, logger.getChild('agent1'), ); const rlOutNode1 = readline.createInterface(agent1.stdout!); @@ -1096,9 +1118,7 @@ async function setupNATWithSeedNode( rlOutNode1.once('close', reject); }); const nodeId1 = JSON.parse(stdoutNode1).nodeId; - const agent2 = await pkSpawnNs( - usrns.pid!, - agent2Netns.pid!, + const agent2 = await pkSpawn( [ 'agent', 'start', @@ -1121,10 +1141,15 @@ async function setupNATWithSeedNode( 'json', ], { - PK_PASSWORD: password, - PK_ROOT_KEY: globalRootKeyPems[2], + env: { + PK_PASSWORD: password, + PK_ROOT_KEY: globalRootKeyPems[2], + }, + command: `nsenter ${nsenter(usrns.pid!, agent2Netns.pid!).join( + ' ', + )} ts-node --project ${tsConfigPath} ${polykeyPath}`, + cwd: dataDir, }, - dataDir, logger.getChild('agent2'), ); const rlOutNode2 = readline.createInterface(agent2.stdout!); @@ -1265,9 +1290,7 @@ async function setupNAT( agent2Netns.pid!, logger, ); - const agent1 = await pkSpawnNs( - usrns.pid!, - agent1Netns.pid!, + const agent1 = await pkSpawn( [ 'agent', 'start', @@ -1288,10 +1311,15 @@ async function setupNAT( 'json', ], { - PK_PASSWORD: password, - PK_ROOT_KEY: globalRootKeyPems[3], + env: { + PK_PASSWORD: password, + PK_ROOT_KEY: globalRootKeyPems[3], + }, + command: `nsenter ${nsenter(usrns.pid!, agent1Netns.pid!).join( + ' ', + )} ts-node --project ${tsConfigPath} ${polykeyPath}`, + cwd: dataDir, }, - dataDir, logger.getChild('agent1'), ); const rlOutNode1 = readline.createInterface(agent1.stdout!); @@ -1300,9 +1328,7 @@ async function setupNAT( rlOutNode1.once('close', reject); }); const nodeId1 = JSON.parse(stdoutNode1).nodeId; - const agent2 = await pkSpawnNs( - usrns.pid!, - agent2Netns.pid!, + const agent2 = await pkSpawn( [ 'agent', 'start', @@ -1323,10 +1349,15 @@ async function setupNAT( 'json', ], { - PK_PASSWORD: password, - PK_ROOT_KEY: globalRootKeyPems[4], + env: { + PK_PASSWORD: password, + PK_ROOT_KEY: globalRootKeyPems[4], + }, + command: `nsenter ${nsenter(usrns.pid!, agent2Netns.pid!).join( + ' ', + )} ts-node --project ${tsConfigPath} ${polykeyPath}`, + cwd: dataDir, }, - dataDir, logger.getChild('agent2'), ); const rlOutNode2 = readline.createInterface(agent2.stdout!); @@ -1373,11 +1404,10 @@ async function setupNAT( } export { + nsenter, + setupNAT, + setupNATWithSeedNode, createUserNamespace, createNetworkNamespace, setupNetworkNamespaceInterfaces, - pkExecNs, - pkSpawnNs, - setupNAT, - setupNATWithSeedNode, }; diff --git a/tests/network/Proxy.test.ts b/tests/network/Proxy.test.ts index 5bab753c4a..b67e2760b4 100644 --- a/tests/network/Proxy.test.ts +++ b/tests/network/Proxy.test.ts @@ -12,7 +12,7 @@ import * as networkErrors from '@/network/errors'; import * as keysUtils from '@/keys/utils'; import * as nodesUtils from '@/nodes/utils'; import { poll, promise, promisify, timerStart, timerStop } from '@/utils'; -import * as testUtils from '../utils'; +import * as testUtils from '../utils/utils'; import * as testNodesUtils from '../nodes/utils'; /** diff --git a/tests/nodes/NodeConnection.test.ts b/tests/nodes/NodeConnection.test.ts index 5befbdc149..e0ea1b792c 100644 --- a/tests/nodes/NodeConnection.test.ts +++ b/tests/nodes/NodeConnection.test.ts @@ -2,7 +2,7 @@ import type { AddressInfo } from 'net'; import type { ConnectionInfo, Host, Port, TLSConfig } from '@/network/types'; import type { NodeId, NodeInfo } from '@/nodes/types'; import type { Server } from '@grpc/grpc-js'; -import type * as child_process from 'child_process'; +import type * as childProcess from 'child_process'; import net from 'net'; import os from 'os'; import path from 'path'; @@ -733,7 +733,7 @@ describe(`${NodeConnection.name} test`, () => { | NodeConnection | undefined; let testProxy: Proxy | undefined; - let testProcess: child_process.ChildProcessWithoutNullStreams | undefined; + let testProcess: childProcess.ChildProcessWithoutNullStreams | undefined; try { const testProcess = spawnFile('tests/grpc/utils/testServer.ts'); const waitP = promise(); @@ -799,7 +799,7 @@ describe(`${NodeConnection.name} test`, () => { | NodeConnection | undefined; let testProxy: Proxy | undefined; - let testProcess: child_process.ChildProcessWithoutNullStreams | undefined; + let testProcess: childProcess.ChildProcessWithoutNullStreams | undefined; try { const testProcess = spawnFile('tests/grpc/utils/testServer.ts'); const waitP = promise(); diff --git a/tests/nodes/NodeConnectionManager.termination.test.ts b/tests/nodes/NodeConnectionManager.termination.test.ts index bdf7c4a6b2..e36c996c78 100644 --- a/tests/nodes/NodeConnectionManager.termination.test.ts +++ b/tests/nodes/NodeConnectionManager.termination.test.ts @@ -24,7 +24,7 @@ import * as grpcUtils from '@/grpc/utils'; import * as agentErrors from '@/agent/errors'; import * as utilsPB from '@/proto/js/polykey/v1/utils/utils_pb'; import { promise, promisify } from '@/utils'; -import * as testUtils from '../utils'; +import * as testUtils from '../utils/utils'; import { globalRootKeyPems } from '../fixtures/globalRootKeyPems'; describe(`${NodeConnectionManager.name} termination test`, () => { diff --git a/tests/notifications/NotificationsManager.test.ts b/tests/notifications/NotificationsManager.test.ts index d9bd3accc6..c6d80ab3ac 100644 --- a/tests/notifications/NotificationsManager.test.ts +++ b/tests/notifications/NotificationsManager.test.ts @@ -22,7 +22,7 @@ import * as notificationsErrors from '@/notifications/errors'; import * as vaultsUtils from '@/vaults/utils'; import * as nodesUtils from '@/nodes/utils'; import * as keysUtils from '@/keys/utils'; -import * as testUtils from '../utils'; +import * as testUtils from '../utils/utils'; import { globalRootKeyPems } from '../fixtures/globalRootKeyPems'; describe('NotificationsManager', () => { diff --git a/tests/utils/exec.ts b/tests/utils/exec.ts index 1706fc62a7..b6c5c21b99 100644 --- a/tests/utils/exec.ts +++ b/tests/utils/exec.ts @@ -2,12 +2,11 @@ import type { ChildProcess } from 'child_process'; import type ErrorPolykey from '@/ErrorPolykey'; import type { PrivateKeyPem } from '@/keys/types'; import type { StatusLive } from '@/status/types'; -import child_process from 'child_process'; +import childProcess from 'child_process'; import fs from 'fs'; import path from 'path'; import process from 'process'; import readline from 'readline'; -import os from 'os'; import * as mockProcess from 'jest-mock-process'; import mockedEnv from 'mocked-env'; import nexpect from 'nexpect'; @@ -16,6 +15,21 @@ import main from '@/bin/polykey'; import { promise } from '@/utils'; import * as validationUtils from '@/validation/utils'; +type ExecOpts = { + env: Record; + command?: string | undefined; + cwd?: string; + shell?: boolean; +}; + +const tsConfigPath = path.resolve( + path.join(globalThis.projectDir, 'tsconfig.json'), +); + +const polykeyPath = path.resolve( + path.join(globalThis.projectDir, 'src/bin/polykey.ts'), +); + const generateDockerArgs = (mountPath: string) => [ '--interactive', '--rm', @@ -48,31 +62,40 @@ const generateDockerArgs = (mountPath: string) => [ ]; /** - * Wrapper for execFile to make it asynchronous and non-blocking + * Execute general (non-Polykey) commands */ async function exec( command: string, args: Array = [], + opts: ExecOpts = { env: {} }, ): Promise<{ stdout: string; stderr: string; }> { + const env = { + ...process.env, + ...opts.env, + }; return new Promise((resolve, reject) => { - child_process.execFile( - command, - args, - { windowsHide: true }, - (error, stdout, stderr) => { - if (error) { - reject(error); - } else { - return resolve({ - stdout, - stderr, - }); - } - }, - ); + let stdout = '', + stderr = ''; + const subprocess = childProcess.spawn(command, args, { + env, + windowsHide: true, + shell: opts.shell ? opts.shell : false, + }); + subprocess.stdout.on('data', (data) => { + stdout += data.toString(); + }); + subprocess.stderr.on('data', (data) => { + stderr += data.toString(); + }); + subprocess.on('exit', () => { + resolve({ stdout, stderr }); + }); + subprocess.on('error', (e) => { + reject(e); + }); }); } @@ -88,28 +111,23 @@ async function pk(args: Array): Promise { * Both stdout and stderr are the entire output including newlines * This can only be used serially, because the mocks it relies on are global singletons * If it is used concurrently, the mocking side-effects can conflict - * @param env Augments env for command execution - * @param cwd Defaults to temporary directory */ async function pkStdio( args: Array = [], - env: Record = {}, - cwd?: string, + opts: ExecOpts = { env: {} }, ): Promise<{ exitCode: number; stdout: string; stderr: string; }> { - if (globalThis.testCmd != null) return pkStdioTarget(args, env, cwd); - - cwd = - cwd ?? + const cwd = + opts.cwd ?? (await fs.promises.mkdtemp(path.join(globalThis.tmpDir, 'polykey-test-'))); // Recall that we attempt to connect to all specified seed nodes on agent start. // Therefore, for testing purposes only, we default the seed nodes as empty // (if not defined in the env) to ensure no attempted connections. A regular // PolykeyAgent is expected to initially connect to the mainnet seed nodes - env['PK_SEED_NODES'] = env['PK_SEED_NODES'] ?? ''; + opts.env['PK_SEED_NODES'] = opts.env['PK_SEED_NODES'] ?? ''; // Parse the arguments of process.stdout.write and process.stderr.write const parseArgs = (args) => { const data = args[0]; @@ -151,7 +169,7 @@ async function pkStdio( () => process, ); const mockCwd = mockProcess.spyOnImplementing(process, 'cwd', () => cwd!); - const envRestore = mockedEnv(env); + const envRestore = mockedEnv(opts.env); const mockedStdout = mockProcess.mockProcessStdout(); const mockedStderr = mockProcess.mockProcessStderr(); const exitCode = await pk(args); @@ -180,219 +198,134 @@ async function pkStdio( * This is used when a subprocess functionality needs to be used * This is intended for terminating subprocesses * Both stdout and stderr are the entire output including newlines - * @param env Augments env for command execution - * @param cwd Defaults to temporary directory + * By default `globalThis.testCommand` should be `undefined` because `PK_TEST_COMMAND` will not be set + * This is strictly checking for existence, `PK_TEST_COMMAND=''` is legitimate but undefined behaviour */ async function pkExec( args: Array = [], - env: Record = {}, - cwd?: string, + opts: ExecOpts = { env: {}, command: globalThis.testCmd }, ): Promise<{ exitCode: number; stdout: string; stderr: string; }> { - if (globalThis.testCmd != null) return pkExecTarget(args, env, cwd); - - cwd = - cwd ?? - (await fs.promises.mkdtemp(path.join(globalThis.tmpDir, 'polykey-test-'))); - env = { - ...process.env, - ...env, - }; - // Recall that we attempt to connect to all specified seed nodes on agent start. - // Therefore, for testing purposes only, we default the seed nodes as empty - // (if not defined in the env) to ensure no attempted connections. A regular - // PolykeyAgent is expected to initially connect to the mainnet seed nodes - env['PK_SEED_NODES'] = env['PK_SEED_NODES'] ?? ''; - const tsConfigPath = path.resolve( - path.join(globalThis.projectDir, 'tsconfig.json'), - ); - const polykeyPath = path.resolve( - path.join(globalThis.projectDir, 'src/bin/polykey.ts'), - ); - return new Promise((resolve, reject) => { - child_process.execFile( - 'ts-node', - ['--project', tsConfigPath, polykeyPath, ...args], - { - env, - cwd, - windowsHide: true, - }, - (error, stdout, stderr) => { - if (error != null && error.code === undefined) { - // This can only happen when the command is killed - return reject(error); - } else { - // Success and Unsuccessful exits are valid here - return resolve({ - exitCode: error && error.code != null ? error.code : 0, - stdout, - stderr, - }); - } - }, - ); - }); + if (opts.command == null) { + return await pkExecWithoutShell(args, opts); + } else { + return await pkExecWithShell(args, opts); + } } /** * Launch pk command through subprocess * This is used when a subprocess functionality needs to be used * This is intended for non-terminating subprocesses - * @param env Augments env for command execution - * @param cwd Defaults to temporary directory + * By default `globalThis.testCommand` should be `undefined` because `PK_TEST_COMMAND` will not be set + * This is strictly checking for existence, `PK_TEST_COMMAND=''` is legitimate but undefined behaviour */ async function pkSpawn( args: Array = [], - env: Record = {}, - cwd?: string, + opts: ExecOpts = { env: {}, command: globalThis.testCmd }, logger: Logger = new Logger(pkSpawn.name), ): Promise { - if (globalThis.testCmd != null) return pkSpawnTarget(args, env, cwd, logger); - - cwd = - cwd ?? - (await fs.promises.mkdtemp(path.join(globalThis.tmpDir, 'polykey-test-'))); - env = { - ...process.env, - ...env, - }; - // Recall that we attempt to connect to all specified seed nodes on agent start. - // Therefore, for testing purposes only, we default the seed nodes as empty - // (if not defined in the env) to ensure no attempted connections. A regular - // PolykeyAgent is expected to initially connect to the mainnet seed nodes - env['PK_SEED_NODES'] = env['PK_SEED_NODES'] ?? ''; - const tsConfigPath = path.resolve( - path.join(globalThis.projectDir, 'tsconfig.json'), - ); - const polykeyPath = path.resolve( - path.join(globalThis.projectDir, 'src/bin/polykey.ts'), - ); - const command = - globalThis.testCmd != null - ? path.resolve(path.join(globalThis.projectDir, globalThis.testCmd)) - : 'ts-node'; - const tsNodeArgs = - globalThis.testCmd != null ? [] : ['--project', tsConfigPath, polykeyPath]; - const subprocess = child_process.spawn(command, [...tsNodeArgs, ...args], { - env, - cwd, - stdio: ['pipe', 'pipe', 'pipe'], - windowsHide: true, - }); - // The readline library will trim newlines - const rlOut = readline.createInterface(subprocess.stdout!); - rlOut.on('line', (l) => logger.info(l)); - const rlErr = readline.createInterface(subprocess.stderr!); - rlErr.on('line', (l) => logger.info(l)); - return subprocess; + if (opts.command == null) { + return await pkSpawnWithoutShell(args, opts, logger); + } else { + return await pkSpawnWithShell(args, opts, logger); + } } /** - * Mimics the behaviour of `pkStdio` while running the command as a separate process. - * Note that this is incompatible with jest mocking. - * @param args - args to be passed to the command. - * @param env - environment variables to be passed to the command. - * @param cwd - the working directory the command will be executed in. + * Runs pk command through subprocess + * This is the default */ -async function pkStdioTarget( +async function pkExecWithoutShell( args: Array = [], - env: Record = {}, - cwd?: string, + opts: ExecOpts = { env: {} }, ): Promise<{ exitCode: number; stdout: string; stderr: string; }> { - cwd = path.resolve( - cwd ?? - (await fs.promises.mkdtemp( - path.join(globalThis.tmpDir, 'polykey-test-'), - )), - ); + const cwd = + opts.cwd ?? + (await fs.promises.mkdtemp(path.join(globalThis.tmpDir, 'polykey-test-'))); + const env = { + ...process.env, + ...opts.env, + }; // Recall that we attempt to connect to all specified seed nodes on agent start. // Therefore, for testing purposes only, we default the seed nodes as empty // (if not defined in the env) to ensure no attempted connections. A regular // PolykeyAgent is expected to initially connect to the mainnet seed nodes env['PK_SEED_NODES'] = env['PK_SEED_NODES'] ?? ''; - - // If using the command override we need to spawn a process - env = { - ...process.env, - ...env, - DOCKER_OPTIONS: generateDockerArgs(cwd).join(' '), - }; - const command = globalThis.testCmd!; - const escapedArgs = args.map((x) => x.replace(/(["\s'$`\\])/g, '\\$1')); - const subprocess = child_process.spawn(command, escapedArgs, { - env, - cwd, - stdio: ['pipe', 'pipe', 'pipe'], - windowsHide: true, - shell: true, - }); - const exitCodeProm = promise(); - subprocess.on('exit', (code) => { - exitCodeProm.resolveP(code); - }); - subprocess.on('error', (e) => { - exitCodeProm.rejectP(e); - }); - let stdout = '', - stderr = ''; - subprocess.stdout.on('data', (data) => { - stdout += data.toString(); - }); - subprocess.stderr.on('data', (data) => { - stderr += data.toString(); + return new Promise((resolve, reject) => { + let stdout = '', + stderr = ''; + const subprocess = childProcess.spawn( + 'ts-node', + ['--project', tsConfigPath, polykeyPath, ...args], + { + env, + cwd, + windowsHide: true, + shell: opts.shell ? opts.shell : false, + }, + ); + subprocess.stdout.on('data', (data) => { + stdout += data.toString(); + }); + subprocess.stderr.on('data', (data) => { + stderr += data.toString(); + }); + subprocess.on('exit', (code) => { + resolve({ exitCode: code ?? -255, stdout, stderr }); + }); + subprocess.on('error', (e) => { + reject(e); + }); }); - return { exitCode: (await exitCodeProm.p) ?? -255, stdout, stderr }; } /** - * Execs the target command spawning it as a seperate process - * @param args - args to be passed to the command. - * @param env Augments env for command execution - * @param cwd Defaults to temporary directory + * Runs pk command through subprocess + * This is the parameter > environment override */ -async function pkExecTarget( +async function pkExecWithShell( args: Array = [], - env: Record = {}, - cwd?: string, + opts: ExecOpts = { env: {}, command: globalThis.testCmd }, ): Promise<{ exitCode: number; stdout: string; stderr: string; }> { - cwd = path.resolve( - cwd ?? + const cwd = path.resolve( + opts.cwd ?? (await fs.promises.mkdtemp( path.join(globalThis.tmpDir, 'polykey-test-'), )), ); - env = { + const env = { ...process.env, - ...env, - DOCKER_OPTIONS: generateDockerArgs(cwd).join(' '), + ...opts.env, }; + if (globalThis.testPlatform === 'docker') { + env.DOCKER_OPTIONS = generateDockerArgs(cwd).join(' '); + } // Recall that we attempt to connect to all specified seed nodes on agent start. // Therefore, for testing purposes only, we default the seed nodes as empty // (if not defined in the env) to ensure no attempted connections. A regular // PolykeyAgent is expected to initially connect to the mainnet seed nodes env['PK_SEED_NODES'] = env['PK_SEED_NODES'] ?? ''; - const command = globalThis.testCmd!; - const escapedArgs = args.map((x) => x.replace(/(["\s'$`\\])/g, '\\$1')); + args = args.map(escapeShellArgs); return new Promise((resolve, reject) => { let stdout = '', stderr = ''; - const subprocess = child_process.spawn(command, escapedArgs, { + const subprocess = childProcess.spawn(opts.command!, args, { env, cwd, windowsHide: true, - shell: true, + shell: opts.shell ? opts.shell : true, }); subprocess.stdout.on('data', (data) => { stdout += data.toString(); @@ -410,42 +343,79 @@ async function pkExecTarget( } /** - * This will spawn a process that executes the target `cmd` provided. - * @param args - args to be passed to the command. - * @param env - environment variables to be passed to the command. - * @param cwd - the working directory the command will be executed in. - * @param logger + * Launch pk command through subprocess + * This is the default */ -async function pkSpawnTarget( +async function pkSpawnWithoutShell( args: Array = [], - env: Record = {}, - cwd?: string, - logger: Logger = new Logger(pkSpawn.name), + opts: ExecOpts = { env: {} }, + logger: Logger = new Logger(pkSpawnWithoutShell.name), ): Promise { - cwd = path.resolve( - cwd ?? + const cwd = + opts.cwd ?? + (await fs.promises.mkdtemp(path.join(globalThis.tmpDir, 'polykey-test-'))); + const env = { + ...process.env, + ...opts.env, + }; + // Recall that we attempt to connect to all specified seed nodes on agent start. + // Therefore, for testing purposes only, we default the seed nodes as empty + // (if not defined in the env) to ensure no attempted connections. A regular + // PolykeyAgent is expected to initially connect to the mainnet seed nodes + env['PK_SEED_NODES'] = env['PK_SEED_NODES'] ?? ''; + const subprocess = childProcess.spawn( + 'ts-node', + ['--project', tsConfigPath, polykeyPath, ...args], + { + env, + cwd, + stdio: ['pipe', 'pipe', 'pipe'], + windowsHide: true, + shell: opts.shell ? opts.shell : false, + }, + ); + // The readline library will trim newlines + const rlOut = readline.createInterface(subprocess.stdout!); + rlOut.on('line', (l) => logger.info(l)); + const rlErr = readline.createInterface(subprocess.stderr!); + rlErr.on('line', (l) => logger.info(l)); + return subprocess; +} + +/** + * Launch pk command through subprocess + * This is the parameter > environment override + */ +async function pkSpawnWithShell( + args: Array = [], + opts: ExecOpts = { env: {}, command: globalThis.testCmd }, + logger: Logger = new Logger(pkSpawnWithShell.name), +): Promise { + const cwd = path.resolve( + opts.cwd ?? (await fs.promises.mkdtemp( path.join(globalThis.tmpDir, 'polykey-test-'), )), ); - env = { + const env = { ...process.env, - ...env, - DOCKER_OPTIONS: generateDockerArgs(cwd).join(' '), + ...opts.env, }; + if (globalThis.testPlatform === 'docker') { + env.DOCKER_OPTIONS = generateDockerArgs(cwd).join(' '); + } // Recall that we attempt to connect to all specified seed nodes on agent start. // Therefore, for testing purposes only, we default the seed nodes as empty // (if not defined in the env) to ensure no attempted connections. A regular // PolykeyAgent is expected to initially connect to the mainnet seed nodes env['PK_SEED_NODES'] = env['PK_SEED_NODES'] ?? ''; - const command = globalThis.testCmd!; - const escapedArgs = args.map((x) => x.replace(/(["\s'$`\\])/g, '\\$1')); - const subprocess = child_process.spawn(command, escapedArgs, { + args = args.map(escapeShellArgs); + const subprocess = childProcess.spawn(opts.command!, args, { env, cwd, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, - shell: true, + shell: opts.shell ? opts.shell : true, }); // The readline library will trim newlines const rlOut = readline.createInterface(subprocess.stdout!); @@ -588,10 +558,12 @@ async function setupTestAgent(privateKeyPem: PrivateKeyPem, logger: Logger) { '--verbose', ], { - PK_PASSWORD: agentPassword, - PK_ROOT_KEY: privateKeyPem, + env: { + PK_PASSWORD: agentPassword, + PK_ROOT_KEY: privateKeyPem, + }, + cwd: agentDir, }, - agentDir, logger, ); const startedProm = promise(); @@ -629,171 +601,33 @@ async function setupTestAgent(privateKeyPem: PrivateKeyPem, logger: Logger) { } function spawnFile(path: string) { - return child_process.spawn('ts-node', [ + return childProcess.spawn('ts-node', [ '--require', 'tsconfig-paths/register', path, ]); } -/** - * Formats the command to enter a namespace to run a process inside it - */ -const nsenter = (usrnsPid: number, netnsPid: number) => { - return [ - '--target', - usrnsPid.toString(), - '--user', - '--preserve-credentials', - 'nsenter', - '--target', - netnsPid.toString(), - '--net', - ]; -}; - -/** - * Runs pk command through subprocess inside a network namespace - * This is used when a subprocess functionality needs to be used - * This is intended for terminating subprocesses - * Both stdout and stderr are the entire output including newlines - * @param env Augments env for command execution - * @param cwd Defaults to temporary directory - */ -async function pkExecNs( - usrnsPid: number, - netnsPid: number, - args: Array = [], - env: Record = {}, - cwd?: string, -): Promise<{ - exitCode: number; - stdout: string; - stderr: string; -}> { - cwd = - cwd ?? (await fs.promises.mkdtemp(path.join(os.tmpdir(), 'polykey-test-'))); - env = { - ...process.env, - ...env, - }; - // Recall that we attempt to connect to all specified seed nodes on agent start. - // Therefore, for testing purposes only, we default the seed nodes as empty - // (if not defined in the env) to ensure no attempted connections. A regular - // PolykeyAgent is expected to initially connect to the mainnet seed nodes - env['PK_SEED_NODES'] = env['PK_SEED_NODES'] ?? ''; - const tsConfigPath = path.resolve( - path.join(globalThis.projectDir, 'tsconfig.json'), - ); - const polykeyPath = path.resolve( - path.join(globalThis.projectDir, 'src/bin/polykey.ts'), - ); - return new Promise((resolve, reject) => { - child_process.execFile( - 'nsenter', - [ - ...nsenter(usrnsPid, netnsPid), - 'ts-node', - '--project', - tsConfigPath, - polykeyPath, - ...args, - ], - { - env, - cwd, - windowsHide: true, - }, - (error, stdout, stderr) => { - if (error != null && error.code === undefined) { - // This can only happen when the command is killed - return reject(error); - } else { - // Success and Unsuccessful exits are valid here - return resolve({ - exitCode: error && error.code != null ? error.code : 0, - stdout, - stderr, - }); - } - }, - ); - }); -} - -/** - * Launch pk command through subprocess inside a network namespace - * This is used when a subprocess functionality needs to be used - * This is intended for non-terminating subprocesses - * @param env Augments env for command execution - * @param cwd Defaults to temporary directory - */ -async function pkSpawnNs( - usrnsPid: number, - netnsPid: number, - args: Array = [], - env: Record = {}, - cwd?: string, - logger: Logger = new Logger(pkSpawnNs.name), -): Promise { - cwd = - cwd ?? (await fs.promises.mkdtemp(path.join(os.tmpdir(), 'polykey-test-'))); - env = { - ...process.env, - ...env, - }; - // Recall that we attempt to connect to all specified seed nodes on agent start. - // Therefore, for testing purposes only, we default the seed nodes as empty - // (if not defined in the env) to ensure no attempted connections. A regular - // PolykeyAgent is expected to initially connect to the mainnet seed nodes - env['PK_SEED_NODES'] = env['PK_SEED_NODES'] ?? ''; - const tsConfigPath = path.resolve( - path.join(globalThis.projectDir, 'tsconfig.json'), - ); - const polykeyPath = path.resolve( - path.join(globalThis.projectDir, 'src/bin/polykey.ts'), - ); - const subprocess = child_process.spawn( - 'nsenter', - [ - ...nsenter(usrnsPid, netnsPid), - 'ts-node', - '--project', - tsConfigPath, - polykeyPath, - ...args, - ], - { - env, - cwd, - stdio: ['pipe', 'pipe', 'pipe'], - windowsHide: true, - shell: true, - }, - ); - const rlErr = readline.createInterface(subprocess.stderr!); - rlErr.on('line', (l) => { - // The readline library will trim newlines - logger.info(l); - }); - return subprocess; +function escapeShellArgs(arg: string): string { + return arg.replace(/(["\s'$`\\])/g, '\\$1'); } export { - exec, - pk, - pkStdio, + tsConfigPath, + polykeyPath, pkExec, pkSpawn, - pkStdioTarget, - pkExecTarget, - pkSpawnTarget, pkExpect, + pkStdio, + exec, + pk, + setupTestAgent, processExit, expectProcessError, - setupTestAgent, + pkExecWithShell, + pkExecWithoutShell, + pkSpawnWithShell, + pkSpawnWithoutShell, spawnFile, - nsenter, - pkExecNs, - pkSpawnNs, + escapeShellArgs, }; diff --git a/tests/vaults/VaultManager.test.ts b/tests/vaults/VaultManager.test.ts index 6b5c556cdd..3d7ac47782 100644 --- a/tests/vaults/VaultManager.test.ts +++ b/tests/vaults/VaultManager.test.ts @@ -32,7 +32,7 @@ import * as vaultsUtils from '@/vaults/utils'; import { sleep } from '@/utils'; import VaultInternal from '@/vaults/VaultInternal'; import * as nodeTestUtils from '../nodes/utils'; -import { expectRemoteError } from '../utils'; +import { expectRemoteError } from '../utils/utils'; import { globalRootKeyPems } from '../fixtures/globalRootKeyPems'; describe('VaultManager', () => {