Unverified Commit 134912a5 authored by otaconix's avatar otaconix Committed by GitHub
Browse files

Fix import-safe checks when scripts are run from a path with symlinks (#1265)

* Fix import-safe checks when scripts are run from a path with symlinks

In v6, setup-java was made "import-safe" to facilitate testing. This
prevents setup-java & cleanup-java from doing anything when their
sources get imported.

This works fine in the general case, but actually invoking the script
(`node setup-java/index.js`) when the path to the script contains
symlinks led to the script incorrectly believing it was imported, and
refuse to actually run.

To fix this, we pass `process.argv[1]` through `fs.realpathSync`, which
resolves symlinks in the path.

Fixes #1264

* Preserve import safety when resolving symlink entrypoints

Share entrypoint detection between setup and cleanup, handle non-file entrypoints safely, and normalize both paths for preserved symlinks. Add real-process regression coverage and rebuild action bundles.

Co-authored-by: default avatarCopilot App <[email protected]>
Copilot-Session: 831c32f2-a275-45bd-a92b-c387372a1554

* Update js-yaml to fix merge-source denial of service

Bump the transitive development dependency from 3.15.1 to 3.15.2 to address GHSA-2883-xcg3-v3hh without changing dependency ranges or CI checks.

Co-authored-by: default avatarCopilot App <[email protected]>
Copilot-Session: 831c32f2-a275-45bd-a92b-c387372a1554

---------

Co-authored-by: default avatarBruno Borges <[email protected]>
Co-authored-by: default avatarCopilot App <[email protected]>
Copilot-Session: 831c32f2-a275-45bd-a92b-c387372a1554
parent 0781fc6a
Loading
Loading
Loading
Loading
+87
Changes for __tests__/entrypoints.test.ts: 87 added lines, 0 removed lines.
Original line number Diff line number Diff line
import {afterAll, beforeAll, describe, expect, it} from '@jest/globals';
import {spawnSync} from 'child_process';
import fs from 'fs';
import os from 'os';
import path from 'path';
import {fileURLToPath, pathToFileURL} from 'url';

const dist = fileURLToPath(new URL('../dist/', import.meta.url));
let tempDir: string;
let linkedDist: string;

beforeAll(() => {
  tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'setup-java-entrypoints-'));
  linkedDist = path.join(tempDir, 'linked # dist');
  fs.symlinkSync(dist, linkedDist, 'junction');
});

afterAll(() => {
  fs.rmSync(tempDir, {recursive: true, force: true});
});

function execute(args: string[], input?: string) {
  return spawnSync(process.execPath, args, {
    encoding: 'utf8',
    input,
    timeout: 10000,
    env: {
      PATH: process.env.PATH,
      SystemRoot: process.env.SystemRoot
    }
  });
}

describe.each([
  ['setup', 1, 'java-version or java-version-file input expected'],
  ['cleanup', 0, '']
] as const)('%s entrypoint', (name, exitCode, output) => {
  it.each(['direct', 'symlink', 'preserved symlink'])(
    'executes through a %s path',
    mode => {
      const entry = path.join(
        mode === 'direct' ? dist : linkedDist,
        name,
        'index.js'
      );
      const args =
        mode === 'preserved symlink'
          ? ['--preserve-symlinks-main', entry]
          : [entry];
      const result = execute(args);

      expect(result.error).toBeUndefined();
      expect(result.status).toBe(exitCode);
      expect(result.stderr).toBe('');
      expect(result.stdout).not.toContain('skipping the execution');
      if (output) {
        expect(result.stdout).toContain(output);
      } else {
        expect(result.stdout).toBe('');
      }
    }
  );

  it.each(['eval', 'stdin', 'file'])(
    'does not execute when imported from %s',
    mode => {
      const moduleUrl = pathToFileURL(path.join(dist, name, 'index.js')).href;
      const source = `const {run} = await import(${JSON.stringify(moduleUrl)}); console.log(typeof run);`;
      const importer = path.join(tempDir, `${name}-importer.mjs`);
      fs.writeFileSync(importer, source);
      const args =
        mode === 'file'
          ? [importer]
          : mode === 'eval'
            ? ['--input-type=module', '-e', source]
            : ['--input-type=module', '-'];
      const result = execute(args, mode === 'stdin' ? source : undefined);

      expect(result.error).toBeUndefined();
      expect(result.status).toBe(0);
      expect(result.stderr).toBe('');
      expect(result.stdout).toContain('skipping the execution');
      expect(result.stdout).toContain('function');
      expect(result.stdout).not.toContain('::error::');
    }
  );
});
+52
Changes for __tests__/is-main-module.test.ts: 52 added lines, 0 removed lines.
Original line number Diff line number Diff line
import {afterEach, beforeEach, describe, expect, it, jest} from '@jest/globals';
import fs from 'fs';
import {isMainModule} from '../src/is-main-module.js';

describe('main module detection', () => {
  const originalArgv = process.argv;

  beforeEach(() => {
    process.argv = [process.execPath, 'entrypoint.js'];
  });

  afterEach(() => {
    process.argv = originalArgv;
    jest.restoreAllMocks();
  });

  it.each([undefined, '-'])(
    'skips filesystem access when argv[1] is %s',
    entrypoint => {
      process.argv =
        entrypoint === undefined
          ? [process.execPath]
          : [process.execPath, entrypoint];
      const realpath = jest.spyOn(fs, 'realpathSync');

      expect(isMainModule(import.meta.url)).toBe(false);
      expect(realpath).not.toHaveBeenCalled();
    }
  );

  it.each(['ENOENT', 'ENOTDIR'])(
    'treats a non-file entrypoint returning %s as an import',
    code => {
      jest.spyOn(fs, 'realpathSync').mockImplementation(() => {
        throw Object.assign(new Error('No file-based entrypoint'), {code});
      });

      expect(isMainModule(import.meta.url)).toBe(false);
    }
  );

  it('propagates unexpected filesystem errors', () => {
    const error = Object.assign(new Error('Permission denied'), {
      code: 'EACCES'
    });
    jest.spyOn(fs, 'realpathSync').mockImplementation(() => {
      throw error;
    });

    expect(() => isMainModule(import.meta.url)).toThrow(error);
  });
});
+1
Changes for __tests__/setup-java.module-loading.test.ts: 1 added line, 0 removed lines.
Original line number Diff line number Diff line
@@ -27,6 +27,7 @@ jest.unstable_mockModule('@actions/core', () => ({

jest.unstable_mockModule('fs', () => ({
  default: {
    ...jest.requireActual<typeof import('fs')>('fs'),
    readFileSync: jest.fn()
  }
}));
+1
Changes for __tests__/setup-java.test.ts: 1 added line, 0 removed lines.
Original line number Diff line number Diff line
@@ -27,6 +27,7 @@ jest.unstable_mockModule('@actions/core', () => ({

jest.unstable_mockModule('fs', () => ({
  default: {
    ...jest.requireActual<typeof import('fs')>('fs'),
    readFileSync: jest.fn()
  }
}));
+26 −1
Changes for dist/cleanup/index.js: 26 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -35747,6 +35747,7 @@ __nccwpck_require__.d(__webpack_exports__, {
var cleanup_java_core = __nccwpck_require__(3838);
// EXTERNAL MODULE: external "fs"
var external_fs_ = __nccwpck_require__(9896);
var external_fs_default = /*#__PURE__*/__nccwpck_require__.n(external_fs_);
// EXTERNAL MODULE: external "path"
var external_path_ = __nccwpck_require__(6928);
// EXTERNAL MODULE: external "crypto"
@@ -35890,6 +35891,30 @@ async function verifyPackageSignature(archivePath, signatureUrl, publicKeyConten
var constants = __nccwpck_require__(7242);
// EXTERNAL MODULE: external "url"
var external_url_ = __nccwpck_require__(7016);
;// CONCATENATED MODULE: ./src/is-main-module.ts
function isMainModule(moduleUrl) {
    const entrypoint = process.argv[1];
    if (!entrypoint || entrypoint === '-') {
        return false;
    }
    let entrypointPath;
    try {
        entrypointPath = external_fs_default().realpathSync(entrypoint);
    }
    catch (error) {
        if (error instanceof Error &&
            'code' in error &&
            (error.code === 'ENOENT' || error.code === 'ENOTDIR')) {
            return false;
        }
        throw error;
    }
    // Resolve both paths for runtimes using --preserve-symlinks-main.
    return entrypointPath === external_fs_default().realpathSync((0,external_url_.fileURLToPath)(moduleUrl));
}
;// CONCATENATED MODULE: ./src/cleanup-java.ts
@@ -35957,7 +35982,7 @@ async function run() {
    await cleanup_java_removeGpgHome();
    await ignoreError(saveCaches());
}
if (process.argv[1] === (0,external_url_.fileURLToPath)(import.meta.url)) {
if (isMainModule(import.meta.url)) {
    run();
}
else {
Loading