Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ export class RuntimeJavaVersionIdentifier implements JavaVersionIdentifier {
childProcess.stderr.on('data', (data: Buffer) => {
stderr += data.toString();
});
childProcess.on('exit', (code: number) => {
// We listen to 'close' (not 'exit') so that stderr is fully drained before we parse it.
childProcess.on('close', (code: number|null) => {
/* istanbul ignore else */
if (code === 0) {
// Oddly enough the -version command is documented to go to stderr and not stdout
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,19 @@ function stubJavaProcess(stderrLine: string, exitCode: number = 0): cp.ChildProc
process.nextTick(() => {
child.stderr.emit('data', Buffer.from(stderrLine));
child.emit('exit', exitCode);
child.emit('close', exitCode);
});
return child as unknown as cp.ChildProcessWithoutNullStreams;
}

// Simulates stdio still being open at 'exit': the remaining stderr only arrives before 'close'.
function stubJavaProcessWithLateStderr(firstChunk: string, lateChunk: string): cp.ChildProcessWithoutNullStreams {
const child = Object.assign(new EventEmitter(), {stderr: new EventEmitter()});
process.nextTick(() => {
child.stderr.emit('data', Buffer.from(firstChunk));
child.emit('exit', 0);
child.stderr.emit('data', Buffer.from(lateChunk));
child.emit('close', 0);
});
return child as unknown as cp.ChildProcessWithoutNullStreams;
}
Expand Down Expand Up @@ -70,4 +83,14 @@ describe('RuntimeJavaVersionIdentifier CWE-427 regression', () => {
expect(version?.toString()).toEqual('11.0.6');
expect(spawnSpy).toHaveBeenCalledWith('java', ['-version'], {cwd: TRUSTED_DIR});
});

it('waits for stderr to be fully drained (close) before parsing, even with JAVA_TOOL_OPTIONS notice first', async () => {
jest.spyOn(cp, 'spawn').mockImplementation(() => stubJavaProcessWithLateStderr(
'Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8\n',
'openjdk version "17.0.11" 2024-04-16 LTS\n'));

const version = await new RuntimeJavaVersionIdentifier().identifyJavaVersion('java');

expect(version?.toString()).toEqual('17.0.11');
});
});
Loading