Fix invisible script execution on Windows #264

This commit addresses an issue in the privacy.sexy desktop application
where scripts executed as administrator on Windows were running in the
background. This was observed in environments like Windows Pro VMs on
Azure, where operations typically run with administrative privileges.

Previously, the application used the `"$path"` shell command to execute
scripts. This mechanism failed to activate the logic for requesting
admin privileges if the app itself was running as an administrator.
To resolve this, the script execution process has been modified to
explicitly ask for administrator privileges using the `VerbAs` method.
This ensures that the script always runs in a new `cmd.exe` window,
enhancing visibility and user interaction.

Other supporting changes:

- Rename the generated script file from `run-{timestamp}-{extension}` er
  to `{timestamp}-privacy-script-{extension}` for clearer identification
  and better file sorting.
- Refactor `ScriptFileCreator` to parameterize file extension and
  script name.
- Rename `OsTimestampedFilenameGenerator` to
  `TimestampedFilenameGenerator` to better reflect its new and more
  scoped functionality after refactoring mentioned abvoe.
- Remove `setAppName()` due to ineffective behavior in Windows.
- Update `SECURITY.md` to highlight that the app doesn't require admin
  rights for standard operations.
- Add `.editorconfig` settings for PowerShell scripts.
- Add a integration test for script execution logic. Improve environment
  detection for more reliable test execution.
- Disable application logging during unit/integration tests to keep test
  outputs clean and focused.
This commit is contained in:
undergroundwires
2024-01-09 20:44:06 +01:00
parent 728584240c
commit b404a91ada
32 changed files with 716 additions and 290 deletions

View File

@@ -1,103 +0,0 @@
import { describe, it, expect } from 'vitest';
import { AllSupportedOperatingSystems, SupportedOperatingSystem } from '@tests/shared/TestCases/SupportedOperatingSystems';
import { OperatingSystem } from '@/domain/OperatingSystem';
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
import { RuntimeEnvironmentStub } from '@tests/unit/shared/Stubs/RuntimeEnvironmentStub';
import { OsTimestampedFilenameGenerator } from '@/infrastructure/CodeRunner/Creation/Filename/OsTimestampedFilenameGenerator';
describe('OsTimestampedFilenameGenerator', () => {
describe('generateFilename', () => {
it('generates correct prefix', () => {
// arrange
const expectedPrefix = 'run';
// act
const filename = generateFilenamePartsForTesting();
// assert
expect(filename.prefix).to.equal(expectedPrefix);
});
it('generates correct timestamp', () => {
// arrange
const currentDate = '2023-01-01T12:00:00.000Z';
const expectedTimestamp = '2023-01-01_12-00-00';
const date = new Date(currentDate);
// act
const filename = generateFilenamePartsForTesting({ date });
// assert
expect(filename.timestamp).to.equal(expectedTimestamp, formatAssertionMessage[
`Generated file name: ${filename.generatedFileName}`
]);
});
describe('generates correct extension', () => {
const testScenarios: Record<SupportedOperatingSystem, string> = {
[OperatingSystem.Windows]: 'bat',
[OperatingSystem.Linux]: 'sh',
[OperatingSystem.macOS]: 'sh',
};
AllSupportedOperatingSystems.forEach((operatingSystem) => {
it(`on ${OperatingSystem[operatingSystem]}`, () => {
// arrange
const expectedExtension = testScenarios[operatingSystem];
// act
const filename = generateFilenamePartsForTesting({ operatingSystem });
// assert
expect(filename.extension).to.equal(expectedExtension, formatAssertionMessage[
`Generated file name: ${filename.generatedFileName}`
]);
});
});
});
describe('generates filename without extension for unknown OS', () => {
// arrange
const testScenarios: ReadonlyArray<{
readonly description: string;
readonly unknownOs?: OperatingSystem;
}> = [
{
description: 'unsupported OS',
unknownOs: 'Unsupported' as unknown as OperatingSystem,
},
{
description: 'undefined OS',
unknownOs: undefined,
},
];
testScenarios.forEach(({ description, unknownOs }) => {
it(description, () => {
// act
const filename = generateFilenamePartsForTesting({ operatingSystem: unknownOs });
// assert
expect(filename.extension).toBeUndefined();
});
});
});
});
});
interface TestFileNameComponents {
readonly prefix: string;
readonly timestamp: string;
readonly extension?: string;
readonly generatedFileName: string;
}
function generateFilenamePartsForTesting(testScenario?: {
operatingSystem?: OperatingSystem,
date?: Date,
}): TestFileNameComponents {
const date = testScenario?.date ?? new Date();
const sut = new OsTimestampedFilenameGenerator(
new RuntimeEnvironmentStub().withOs(testScenario?.operatingSystem),
);
const filename = sut.generateFilename(date);
const pattern = /^(?<prefix>[^-]+)-(?<timestamp>[^.]+)(?:\.(?<extension>[^.]+))?$/; // prefix-timestamp.extension
const match = filename.match(pattern);
if (!match?.groups?.prefix || !match?.groups?.timestamp) {
throw new Error(`Failed to parse prefix or timestamp: ${filename}`);
}
return {
generatedFileName: filename,
prefix: match.groups.prefix,
timestamp: match.groups.timestamp,
extension: match.groups.extension,
};
}

View File

@@ -0,0 +1,124 @@
import { describe, it, expect } from 'vitest';
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
import { TimestampedFilenameGenerator } from '@/infrastructure/CodeRunner/Creation/Filename/TimestampedFilenameGenerator';
import { itEachAbsentStringValue } from '@tests/unit/shared/TestCases/AbsentTests';
describe('TimestampedFilenameGenerator', () => {
describe('generateFilename', () => {
describe('script name', () => {
it('uses correct script name', () => {
// arrange
const expectedScriptName = 'test-script';
// act
const filename = generateFilenamePartsForTesting({
scriptName: expectedScriptName,
});
// assert
expect(filename.scriptName).to.equal(expectedScriptName);
});
describe('error for missing script name', () => {
itEachAbsentStringValue((absentValue) => {
// arrange
const expectedError = 'Script name is required but not provided.';
// act
const act = () => generateFilenamePartsForTesting({
scriptName: absentValue,
});
// assert
expect(act).to.throw(expectedError);
}, { excludeNull: true, excludeUndefined: true });
});
});
it('generates expected timestamp', () => {
// arrange
const currentDate = '2023-01-01T12:00:00.000Z';
const expectedTimestamp = '2023-01-01_12-00-00';
const date = new Date(currentDate);
// act
const filename = generateFilenamePartsForTesting({ date });
// assert
expect(filename.timestamp).to.equal(expectedTimestamp, formatAssertionMessage[
`Generated file name: ${filename.generatedFilename}`
]);
});
describe('extension', () => {
it('uses correct extension', () => {
// arrange
const expectedExtension = 'sexy';
// act
const filename = generateFilenamePartsForTesting({ extension: expectedExtension });
// assert
expect(filename.extension).to.equal(expectedExtension, formatAssertionMessage[
`Generated file name: ${filename.generatedFilename}`
]);
});
describe('handles absent extension', () => {
itEachAbsentStringValue((absentExtension) => {
// arrange
const expectedExtension = undefined;
// act
const filename = generateFilenamePartsForTesting({ extension: absentExtension });
// assert
expect(filename.extension).to.equal(expectedExtension, formatAssertionMessage[
`Generated file name: ${filename.generatedFilename}`
]);
}, { excludeNull: true });
});
it('errors on dot-starting extension', () => {
// arrange
const invalidExtension = '.sexy';
const expectedError = 'File extension should not start with a dot.';
// act
const act = () => generateFilenamePartsForTesting({ extension: invalidExtension });
// assert
expect(act).to.throw(expectedError);
});
});
});
});
interface TestFileNameComponents {
readonly scriptName: string;
readonly timestamp: string;
readonly extension?: string;
readonly generatedFilename: string;
}
function generateFilenamePartsForTesting(testScenario?: {
readonly date?: Date,
readonly extension?: string,
readonly scriptName?: string,
}): TestFileNameComponents {
const date = testScenario?.date ?? new Date();
const sut = new TimestampedFilenameGenerator();
const filename = sut.generateFilename(
{
scriptName: testScenario?.scriptName ?? 'privacy-script',
scriptFileExtension: testScenario?.extension,
},
date,
);
return parseFilename(filename);
}
function parseFilename(generatedFilename: string): TestFileNameComponents {
const pattern = /^(?<timestamp>\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})-(?<scriptName>[^.]+?)(?:\.(?<extension>[^.]+))?$/;// timestamp-scriptName.extension
const match = generatedFilename.match(pattern);
function assertMatch(name: string, value: string | undefined): asserts value is string {
if (!value) {
throw new Error([
`Missing "${name}" match in generated filename.`,
`Generated filename: ${generatedFilename}`,
`Match object: ${JSON.stringify(match)}`,
].join('\n'));
}
}
assertMatch('script name', match?.groups?.scriptName);
assertMatch('timestamp', match?.groups?.timestamp);
return {
generatedFilename,
scriptName: match.groups.scriptName,
timestamp: match.groups.timestamp,
extension: match.groups.extension,
};
}

View File

@@ -11,6 +11,8 @@ import { FilenameGeneratorStub } from '@tests/unit/shared/Stubs/FilenameGenerato
import { SystemOperationsStub } from '@tests/unit/shared/Stubs/SystemOperationsStub';
import { SystemOperations } from '@/infrastructure/CodeRunner/System/SystemOperations';
import { LocationOpsStub } from '@tests/unit/shared/Stubs/LocationOpsStub';
import { ScriptFileNameParts } from '@/infrastructure/CodeRunner/Creation/ScriptFileCreator';
import { expectExists } from '@tests/shared/Assertions/ExpectExists';
describe('ScriptFileCreationOrchestrator', () => {
describe('createScriptFile', () => {
@@ -62,6 +64,28 @@ describe('ScriptFileCreationOrchestrator', () => {
.pop();
expect(actualFileName).to.equal(expectedFilename);
});
it('generates file name using specified parts', async () => {
// arrange
const expectedParts: ScriptFileNameParts = {
scriptName: 'expected-script-name',
scriptFileExtension: 'expected-script-file-extension',
};
const filenameGeneratorStub = new FilenameGeneratorStub();
const context = new ScriptFileCreationOrchestratorTestSetup()
.withFileNameParts(expectedParts)
.withFilenameGenerator(filenameGeneratorStub);
// act
await context.createScriptFile();
// assert
const fileNameGenerationCalls = filenameGeneratorStub.callHistory.filter((c) => c.methodName === 'generateFilename');
expect(fileNameGenerationCalls).to.have.lengthOf(1);
const callArguments = fileNameGenerationCalls[0].args;
const [scriptNameFileParts] = callArguments;
expectExists(scriptNameFileParts, `Call arguments: ${JSON.stringify(callArguments)}`);
expect(scriptNameFileParts).to.equal(expectedParts);
});
it('generates complete file path', async () => {
// arrange
const expectedPath = 'expected-script-path';
@@ -84,7 +108,7 @@ describe('ScriptFileCreationOrchestrator', () => {
expect(actualFilePath).to.equal(expectedPath);
});
});
describe('writing file to system', () => {
describe('file writing', () => {
it('writes file to the generated path', async () => {
// arrange
const filesystem = new FileSystemOpsStub();
@@ -133,6 +157,11 @@ class ScriptFileCreationOrchestratorTestSetup {
private fileContents = `[${ScriptFileCreationOrchestratorTestSetup.name}] script file contents`;
private fileNameParts: ScriptFileNameParts = {
scriptName: `[${ScriptFileCreationOrchestratorTestSetup.name}] script name`,
scriptFileExtension: `[${ScriptFileCreationOrchestratorTestSetup.name}] file extension`,
};
public withFileContents(fileContents: string): this {
this.fileContents = fileContents;
return this;
@@ -153,6 +182,11 @@ class ScriptFileCreationOrchestratorTestSetup {
return this;
}
public withFileNameParts(fileNameParts: ScriptFileNameParts): this {
this.fileNameParts = fileNameParts;
return this;
}
public createScriptFile(): ReturnType<ScriptFileCreationOrchestrator['createScriptFile']> {
const creator = new ScriptFileCreationOrchestrator(
this.system,
@@ -160,6 +194,6 @@ class ScriptFileCreationOrchestratorTestSetup {
this.directoryProvider,
this.logger,
);
return creator.createScriptFile(this.fileContents);
return creator.createScriptFile(this.fileContents, this.fileNameParts);
}
}

View File

@@ -55,7 +55,7 @@ describe('VisibleTerminalScriptFileExecutor', () => {
{
description: 'encloses path in quotes',
filePath: 'file',
expectedCommand: '"file"',
expectedCommand: 'PowerShell Start-Process -Verb RunAs -FilePath "file"',
},
],
[OperatingSystem.macOS]: [

View File

@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest';
import { ScriptFileCodeRunner } from '@/infrastructure/CodeRunner/ScriptFileCodeRunner';
import { LoggerStub } from '@tests/unit/shared/Stubs/LoggerStub';
import { Logger } from '@/application/Common/Log/Logger';
import { ScriptFileName } from '@/application/CodeRunner/ScriptFileName';
import { ScriptFileExecutor } from '@/infrastructure/CodeRunner/Execution/ScriptFileExecutor';
import { ScriptFileExecutorStub } from '@tests/unit/shared/Stubs/ScriptFileExecutorStub';
import { ScriptFileCreator } from '@/infrastructure/CodeRunner/Creation/ScriptFileCreator';
@@ -11,7 +12,7 @@ import { expectThrowsAsync } from '@tests/shared/Assertions/ExpectThrowsAsync';
describe('ScriptFileCodeRunner', () => {
describe('runCode', () => {
it('executes the script file as expected', async () => {
it('executes script file correctly', async () => {
// arrange
const expectedFilePath = 'expected script path';
const fileExecutor = new ScriptFileExecutorStub();
@@ -45,6 +46,41 @@ describe('ScriptFileCodeRunner', () => {
const [actualCode] = createCalls[0].args;
expect(actualCode).to.equal(expectedCode);
});
it('creates script file with provided extension', async () => {
// arrange
const expectedFileExtension = 'expected-file-extension';
const fileCreator = new ScriptFileCreatorStub();
const context = new CodeRunnerTestSetup()
.withFileCreator(fileCreator)
.withFileExtension(expectedFileExtension);
// act
await context.runCode();
// assert
const createCalls = fileCreator.callHistory.filter((call) => call.methodName === 'createScriptFile');
expect(createCalls.length).to.equal(1);
const [,scriptFileNameParts] = createCalls[0].args;
expectExists(scriptFileNameParts, JSON.stringify(`Call args: ${JSON.stringify(createCalls[0].args)}`));
expect(scriptFileNameParts.scriptFileExtension).to.equal(expectedFileExtension);
});
it('creates script file with provided name', async () => {
// arrange
const expectedScriptName = ScriptFileName;
const fileCreator = new ScriptFileCreatorStub();
const context = new CodeRunnerTestSetup()
.withFileCreator(fileCreator);
// act
await context.runCode();
// assert
const createCalls = fileCreator.callHistory.filter((call) => call.methodName === 'createScriptFile');
expect(createCalls.length).to.equal(1);
const [,scriptFileNameParts] = createCalls[0].args;
expectExists(scriptFileNameParts, JSON.stringify(`Call args: ${JSON.stringify(createCalls[0].args)}`));
expect(scriptFileNameParts.scriptName).to.equal(expectedScriptName);
});
describe('error handling', () => {
const testScenarios: ReadonlyArray<{
readonly description: string;
@@ -52,7 +88,7 @@ describe('ScriptFileCodeRunner', () => {
readonly faultyContext: CodeRunnerTestSetup;
}> = [
(() => {
const error = new Error('script file execution failed');
const error = new Error('Test Error: Script file execution intentionally failed for testing purposes.');
const executor = new ScriptFileExecutorStub();
executor.executeScriptFile = () => {
throw error;
@@ -64,7 +100,7 @@ describe('ScriptFileCodeRunner', () => {
};
})(),
(() => {
const error = new Error('script file creation failed');
const error = new Error('Test Error: Script file creation intentionally failed for testing purposes.');
const creator = new ScriptFileCreatorStub();
creator.createScriptFile = () => {
throw error;
@@ -76,7 +112,7 @@ describe('ScriptFileCodeRunner', () => {
};
})(),
];
describe('logs errors correctly', () => {
describe('logs errors', () => {
testScenarios.forEach(({ description, faultyContext }) => {
it(`logs error when ${description}`, async () => {
// arrange
@@ -94,7 +130,7 @@ describe('ScriptFileCodeRunner', () => {
});
});
});
describe('correctly rethrows errors', () => {
describe('rethrows errors', () => {
testScenarios.forEach(({ description, injectedException, faultyContext }) => {
it(`rethrows error when ${description}`, async () => {
// act
@@ -111,6 +147,8 @@ describe('ScriptFileCodeRunner', () => {
class CodeRunnerTestSetup {
private code = `[${CodeRunnerTestSetup.name}]code`;
private fileExtension = `[${CodeRunnerTestSetup.name}]file-extension`;
private fileCreator: ScriptFileCreator = new ScriptFileCreatorStub();
private fileExecutor: ScriptFileExecutor = new ScriptFileExecutorStub();
@@ -123,7 +161,7 @@ class CodeRunnerTestSetup {
this.fileCreator,
this.logger,
);
await runner.runCode(this.code);
await runner.runCode(this.code, this.fileExtension);
}
public withFileExecutor(fileExecutor: ScriptFileExecutor): this {
@@ -145,4 +183,9 @@ class CodeRunnerTestSetup {
this.fileCreator = fileCreator;
return this;
}
public withFileExtension(fileExtension: string): this {
this.fileExtension = fileExtension;
return this;
}
}