Files
privacy.sexy/tests/integration/infrastructure/CodeRunner/ScriptFileCodeRunner.spec.ts
undergroundwires 8c17396285 Fix script cancellation with new dialog on Linux
This commit improves the management of script execution process by
enhancing the way terminal commands are handled, paving the way for
easier future modifications and providing clearer feedback to users when
scripts are cancelled.

Previously, the UI displayed a generic error message which could lead to
confusion if the user intentionally cancelled the script execution. Now,
a specific error dialog will appear, improving the user experience by
accurately reflecting the action taken by the user.

This change affects code execution on Linux where closing GNOME terminal
returns exit code `137` which is then treated by script cancellation by
privacy.sexy to show the accurate error dialog. It does not affect macOS
and Windows as curret commands result in success (`0`) exit code on
cancellation.

Additionally, this update encapsulates OS-specific logic into dedicated
classes, promoting better separation of concerns and increasing the
modularity of the codebase. This makes it simpler to maintain and extend
the application.

Key changes:

- Display a specific error message for script cancellations.
- Refactor command execution into dedicated classes.
- Improve file permission setting flexibility and avoid setting file
  permissions on Windows as it's not required to execute files.
- Introduce more granular error types for script execution.
- Increase logging for shell commands to aid in debugging.
- Expand test coverage to ensure reliability.
- Fix error dialogs not showing the error messages due to incorrect
  propagation of errors.

Other supported changes:

- Update `SECURITY.md` with details on script readback and verification.
- Fix a typo in `IpcRegistration.spec.ts`.
- Document antivirus scans in `desktop-vs-web-features.md`.
2024-04-30 15:04:59 +02:00

101 lines
3.4 KiB
TypeScript

import { mkdtemp } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { exec } from 'node:child_process';
import { describe, it } from 'vitest';
import type { ScriptDirectoryProvider } from '@/infrastructure/CodeRunner/Creation/Directory/ScriptDirectoryProvider';
import { ScriptFileCreationOrchestrator } from '@/infrastructure/CodeRunner/Creation/ScriptFileCreationOrchestrator';
import { ScriptFileCodeRunner } from '@/infrastructure/CodeRunner/ScriptFileCodeRunner';
import { CurrentEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory';
import { OperatingSystem } from '@/domain/OperatingSystem';
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
import { LinuxTerminalEmulator } from '@/infrastructure/CodeRunner/Execution/CommandDefinition/Commands/LinuxVisibleTerminalCommand';
describe('ScriptFileCodeRunner', () => {
it('executes simple script correctly', async ({ skip }) => {
// arrange
const currentOperatingSystem = CurrentEnvironment.os;
if (await shouldSkipTest(currentOperatingSystem)) {
skip();
return;
}
const temporaryDirectoryProvider = createTemporaryDirectoryProvider();
const codeRunner = createCodeRunner(temporaryDirectoryProvider);
const args = getPlatformSpecificArguments(currentOperatingSystem);
// act
const { success, error } = await codeRunner.runCode(...args);
// assert
expect(success).to.equal(true, formatAssertionMessage([
'Failed to successfully execute the script.',
'Details:', JSON.stringify(error),
]));
});
});
function getPlatformSpecificArguments(
os: OperatingSystem | undefined,
): Parameters<ScriptFileCodeRunner['runCode']> {
switch (os) {
case undefined:
throw new Error('Operating system detection failed: Unable to identify the current platform.');
case OperatingSystem.Windows:
return [
[
'@echo off',
'echo Hello, World!',
'exit /b 0',
].join('\n'),
'bat',
];
case OperatingSystem.macOS:
case OperatingSystem.Linux:
return [
[
'#!/bin/bash',
'echo "Hello, World!"',
'exit 0',
].join('\n'),
'sh',
];
default:
throw new Error(`Platform not supported: The current operating system (${os}) is not compatible with this script execution.`);
}
}
function shouldSkipTest(
os: OperatingSystem | undefined,
): Promise<boolean> {
if (os !== OperatingSystem.Linux) {
return Promise.resolve(false);
}
return isLinuxTerminalEmulatorSupported();
}
function isLinuxTerminalEmulatorSupported(): Promise<boolean> {
return new Promise((resolve) => {
exec(`which ${LinuxTerminalEmulator}`).on('close', (exitCode) => {
resolve(exitCode !== 0);
});
});
}
function createCodeRunner(directoryProvider: ScriptDirectoryProvider): ScriptFileCodeRunner {
return new ScriptFileCodeRunner(
undefined,
new ScriptFileCreationOrchestrator(undefined, undefined, directoryProvider),
);
}
function createTemporaryDirectoryProvider(): ScriptDirectoryProvider {
return {
provideScriptDirectory: async () => {
const temporaryDirectoryPathPrefix = join(tmpdir(), 'privacy-sexy-tests-');
const temporaryDirectoryFullPath = await mkdtemp(temporaryDirectoryPathPrefix);
return {
success: true,
directoryAbsolutePath: temporaryDirectoryFullPath,
};
},
};
}