diff --git a/aws_lambda_builders/workflows/nodejs_npm/actions.py b/aws_lambda_builders/workflows/nodejs_npm/actions.py index bf2f1bc17..e5673ee20 100644 --- a/aws_lambda_builders/workflows/nodejs_npm/actions.py +++ b/aws_lambda_builders/workflows/nodejs_npm/actions.py @@ -2,9 +2,11 @@ Action to resolve NodeJS dependencies using NPM """ +import json import logging import os import re +import shutil from typing import Optional from aws_lambda_builders import utils @@ -104,6 +106,129 @@ def __init__(self, install_dir: str, subprocess_npm: SubprocessNpm, omit_dev: bo self.subprocess_npm = subprocess_npm self.omit_dev = omit_dev + def _read_local_dependencies(self): + """Read the manifest once for active and protected dependencies.""" + manifest_path = os.path.join(self.install_dir, "package.json") + + try: + with open(manifest_path, encoding="utf-8-sig") as manifest_file: + manifest = json.load(manifest_file) + except (FileNotFoundError, json.JSONDecodeError, UnicodeDecodeError): + # Let npm handle missing or invalid manifests. + return {}, [] + + if not isinstance(manifest, dict): + return {}, [] + + dependencies = {} + protected_specs = [] + + for section in ("devDependencies", "dependencies", "optionalDependencies"): + entries = manifest.get(section, {}) + if not isinstance(entries, dict): + continue + + # Protect every declared source, including omitted dev dependencies + # and declarations overridden by another dependency section. + protected_specs.extend(entries.values()) + + if section != "devDependencies" or not self.omit_dev: + dependencies.update(entries) + + return dependencies, protected_specs + + @staticmethod + def _local_dependency_source(install_dir, spec): + """Normalize file: and bare local dependency paths.""" + if not isinstance(spec, str) or "\x00" in spec: + return None + + if spec.startswith("file:"): + path = spec[5:] + elif spec.startswith(("./", "../", "/", "~/")) or os.path.isabs(spec): + path = spec + elif os.name == "nt" and spec.startswith((".\\", "..\\", "~\\")): + path = spec + else: + return None + + if not path: + return None + + if path.startswith("~/") or (os.name == "nt" and path.startswith("~\\")): + expanded = os.path.expanduser(path) + if expanded == path: + return None + path = expanded + + return os.path.realpath(os.path.join(install_dir, path)) + + @staticmethod + def _paths_overlap(first, second): + """Compare conservatively using case folding on every OS. + + Even on case-sensitive filesystems, treating case variants as + overlapping errs on the side of preserving source directories. + """ + first = os.path.normcase(first).casefold() + second = os.path.normcase(second).casefold() + + try: + common = os.path.commonpath([first, second]) + except ValueError: + return False + + return common in (first, second) + + def _refresh_local_dependencies(self): + """Refresh installed copies of direct local directory dependencies.""" + dependencies, protected_specs = self._read_local_dependencies() + install_dir = os.path.realpath(self.install_dir) + modules_dir = os.path.join(install_dir, "node_modules") + + protected_sources = [ + path for spec in protected_specs if (path := self._local_dependency_source(install_dir, spec)) is not None + ] + + if os.path.normcase(os.path.realpath(modules_dir)) != os.path.normcase(modules_dir): + return + + for name, spec in dependencies.items(): + local_source = self._local_dependency_source(install_dir, spec) + + if local_source is None: + continue + + if not re.fullmatch( + r"(?:@[A-Za-z0-9_~-][A-Za-z0-9._~-]*/)?[A-Za-z0-9_~-][A-Za-z0-9._~-]*", + name, + ): + continue + + if not os.path.isdir(local_source): + continue + + if not os.path.isfile(os.path.join(local_source, "package.json")): + continue + + installed = os.path.join(modules_dir, *name.split("/")) + + if not os.path.isdir(installed) or os.path.islink(installed): + continue + + if os.path.normcase(os.path.realpath(installed)) != os.path.normcase(installed): + continue + + if any(self._paths_overlap(installed, path) for path in protected_sources): + continue + + LOG.debug("Refreshing local npm dependency: %s", name) + + try: + shutil.rmtree(installed) + except OSError as ex: + raise ActionFailedError(str(ex)) from ex + class NodejsNpmInstallAction(NodejsNpmInstallOrUpdateBaseAction): """ @@ -146,6 +271,7 @@ def execute(self): if self.omit_dev: command.append("--omit=dev") if self.install_links: + self._refresh_local_dependencies() command.append("--install-links") self.subprocess_npm.run(command, cwd=self.install_dir) @@ -176,6 +302,8 @@ def execute(self): try: LOG.debug("NODEJS updating dependencies in: %s", self.install_dir) + self._refresh_local_dependencies() + command = ["update", "--no-audit", "--no-save"] if self.omit_dev: command.append("--omit=dev") diff --git a/tests/integration/workflows/nodejs_npm/test_local_dependency_refresh.py b/tests/integration/workflows/nodejs_npm/test_local_dependency_refresh.py new file mode 100644 index 000000000..f0be99b7f --- /dev/null +++ b/tests/integration/workflows/nodejs_npm/test_local_dependency_refresh.py @@ -0,0 +1,135 @@ +import json +import tempfile +from pathlib import Path +from unittest import TestCase + +from parameterized import parameterized + +from aws_lambda_builders.builder import LambdaBuilder +from aws_lambda_builders.supported_runtimes import NODEJS_RUNTIMES +from aws_lambda_builders.workflows.nodejs_npm.npm import SubprocessNpm +from aws_lambda_builders.workflows.nodejs_npm.utils import ( + EXPERIMENTAL_FLAG_NODEJS_MONOREPO, + OSUtils, +) + + +class TestLocalDependencyRefresh(TestCase): + + @parameterized.expand( + [ + ( + f"{runtime}_{path_type}_{workflow}", + runtime, + spec, + workflow == "install", + ) + for runtime in NODEJS_RUNTIMES + for path_type, spec in [ + ("file", "file:../local-dependency"), + ("bare", "../local-dependency"), + ] + for workflow in ["update", "install"] + ] + ) + def test_build_in_source_refreshes_local_dependency(self, _name, runtime, spec, use_lockfile): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + source_dir = root / "function" + local_dep = root / "local-dependency" + artifacts_dir = root / "artifacts" + scratch_dir = root / "scratch" + + for directory in ( + source_dir, + local_dep, + artifacts_dir, + scratch_dir, + ): + directory.mkdir() + + (local_dep / "package.json").write_text( + json.dumps( + { + "name": "local-dependency", + "version": "1.0.0", + "main": "index.js", + } + ), + encoding="utf-8", + ) + + dependency_source = local_dep / "index.js" + + original = "module.exports = 'original';\\n" + updated = "module.exports = 'updated';\\n" + + dependency_source.write_text(original, encoding="utf-8") + + manifest = source_dir / "package.json" + manifest.write_text( + json.dumps( + { + "name": "test-function", + "version": "1.0.0", + "dependencies": {"local-dependency": spec}, + } + ), + encoding="utf-8", + ) + + flags = [] + lockfile = source_dir / "package-lock.json" + original_lockfile = None + + if use_lockfile: + SubprocessNpm(OSUtils()).run( + [ + "install", + "--package-lock-only", + "--install-links", + "--no-audit", + "--no-fund", + ], + cwd=str(source_dir), + ) + + original_lockfile = lockfile.read_bytes() + flags = [EXPERIMENTAL_FLAG_NODEJS_MONOREPO] + + builder = LambdaBuilder( + language="nodejs", + dependency_manager="npm", + application_framework=None, + ) + + def build(): + builder.build( + str(source_dir), + str(artifacts_dir), + str(scratch_dir), + str(manifest), + runtime=runtime, + build_in_source=True, + experimental_flags=flags, + ) + + build() + + installed = source_dir / "node_modules" / "local-dependency" / "index.js" + + artifact = artifacts_dir / "node_modules" / "local-dependency" / "index.js" + + self.assertEqual(installed.read_text(encoding="utf-8"), original) + self.assertEqual(artifact.read_text(encoding="utf-8"), original) + + dependency_source.write_text(updated, encoding="utf-8") + + build() + + self.assertEqual(dependency_source.read_text(encoding="utf-8"), updated) + self.assertEqual(installed.read_text(encoding="utf-8"), updated) + self.assertEqual(artifact.read_text(encoding="utf-8"), updated) + + if use_lockfile: + self.assertEqual(lockfile.read_bytes(), original_lockfile) diff --git a/tests/unit/workflows/nodejs_npm/test_local_dependency_refresh.py b/tests/unit/workflows/nodejs_npm/test_local_dependency_refresh.py new file mode 100644 index 000000000..11b93f697 --- /dev/null +++ b/tests/unit/workflows/nodejs_npm/test_local_dependency_refresh.py @@ -0,0 +1,333 @@ +import json +from unittest.mock import Mock + +import pytest + +from aws_lambda_builders.workflows.nodejs_npm.actions import ( + NodejsNpmInstallAction, + NodejsNpmUpdateAction, +) + + +def make_package(path): + path.mkdir(parents=True, exist_ok=True) + (path / "package.json").write_text( + '{"name": "example", "version": "1.0.0"}', + encoding="utf-8", + ) + (path / "index.js").write_text( + "module.exports = 'example';", + encoding="utf-8", + ) + return path + + +def make_action(project, manifest, omit_dev=True): + (project / "package.json").write_text( + json.dumps(manifest), + encoding="utf-8", + ) + npm = Mock() + action = NodejsNpmUpdateAction( + str(project), + subprocess_npm=npm, + omit_dev=omit_dev, + ) + return action, npm + + +@pytest.mark.parametrize( + "section,name,omit_dev,removed", + [ + ("dependencies", "local-dependency", True, True), + ("dependencies", "@example/local", True, True), + ("optionalDependencies", "local-dependency", True, True), + ("devDependencies", "local-dependency", True, False), + ("devDependencies", "local-dependency", False, True), + ], +) +@pytest.mark.parametrize("spec", ["file:../local", "../local"]) +def test_refresh_dependency_types(tmp_path, section, name, omit_dev, removed, spec): + project = tmp_path / "project" + project.mkdir() + + local = make_package(tmp_path / "local") + installed = make_package(project / "node_modules" / name) + unrelated = make_package(project / "node_modules" / "unrelated") + + action, npm = make_action( + project, + {section: {name: spec}}, + omit_dev=omit_dev, + ) + + def verify_before_update(*args, **kwargs): + assert installed.exists() != removed + assert local.exists() + assert unrelated.exists() + + npm.run.side_effect = verify_before_update + + action.execute() + + npm.run.assert_called_once() + + +def test_preserves_registry_and_tarball_dependencies(tmp_path): + project = tmp_path / "project" + project.mkdir() + + registry = make_package(project / "node_modules" / "registry") + archive = make_package(project / "node_modules" / "archive") + + (tmp_path / "archive.tgz").write_bytes(b"archive") + + action, npm = make_action( + project, + { + "dependencies": { + "registry": "^1.0.0", + "archive": "file:../archive.tgz", + } + }, + ) + + action.execute() + + assert registry.exists() + assert archive.exists() + npm.run.assert_called_once() + + +def test_preserves_symlinked_dependency(tmp_path): + project = tmp_path / "project" + modules = project / "node_modules" + modules.mkdir(parents=True) + + local = make_package(tmp_path / "local") + installed = modules / "local-dependency" + + try: + installed.symlink_to(local, target_is_directory=True) + except OSError: + pytest.skip("Directory symlinks unavailable") + + action, npm = make_action( + project, + {"dependencies": {"local-dependency": "file:../local"}}, + ) + + action.execute() + + assert installed.is_symlink() + assert (local / "index.js").exists() + npm.run.assert_called_once() + + +def test_preserves_symlinked_node_modules(tmp_path): + project = tmp_path / "project" + project.mkdir() + + external = tmp_path / "external" + external.mkdir() + + installed = make_package(external / "local-dependency") + make_package(tmp_path / "local") + + try: + (project / "node_modules").symlink_to(external, target_is_directory=True) + except OSError: + pytest.skip("Directory symlinks unavailable") + + action, npm = make_action( + project, + {"dependencies": {"local-dependency": "file:../local"}}, + ) + + action.execute() + + assert installed.exists() + npm.run.assert_called_once() + + +def test_rejects_path_traversal(tmp_path): + project = tmp_path / "project" + (project / "node_modules").mkdir(parents=True) + + protected = make_package(project / "protected") + make_package(tmp_path / "local") + + action, npm = make_action( + project, + {"dependencies": {"../protected": "file:../local"}}, + ) + + action.execute() + + assert (protected / "index.js").exists() + npm.run.assert_called_once() + + +def test_preserves_original_source(tmp_path): + project = tmp_path / "project" + + installed = make_package(project / "node_modules" / "local-dependency") + + action, npm = make_action( + project, + {"dependencies": {"local-dependency": "file:node_modules/local-dependency"}}, + ) + + action.execute() + + assert (installed / "index.js").exists() + npm.run.assert_called_once() + + +@pytest.mark.parametrize("manifest", [None, "{invalid json"]) +def test_invalid_or_missing_manifest(tmp_path, manifest): + if manifest is not None: + (tmp_path / "package.json").write_text(manifest, encoding="utf-8") + + npm = Mock() + + action = NodejsNpmUpdateAction( + str(tmp_path), + subprocess_npm=npm, + ) + + action.execute() + + npm.run.assert_called_once() + + +@pytest.mark.parametrize("section", ["dependencies", "devDependencies"]) +@pytest.mark.parametrize("prefix", ["file:", "./"]) +def test_preserves_other_dependency_source(tmp_path, section, prefix): + project = tmp_path / "project" + installed = make_package(project / "node_modules" / "local-dependency") + nested_source = make_package(installed / "nested-source") + make_package(tmp_path / "local") + + manifest = { + "dependencies": { + "local-dependency": "file:../local", + } + } + + manifest.setdefault(section, {})["other"] = prefix + "node_modules/local-dependency/nested-source" + + action, npm = make_action(project, manifest) + + action.execute() + + assert installed.exists() + assert nested_source.exists() + npm.run.assert_called_once() + + +@pytest.mark.parametrize( + "path_type", + ["relative", "absolute", "home", "file-home"], +) +def test_refresh_additional_local_paths(tmp_path, monkeypatch, path_type): + project = tmp_path / "project" + project.mkdir() + + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.setenv("USERPROFILE", str(tmp_path)) + + if path_type == "relative": + local = make_package(project / "local") + spec = "./local" + else: + local = make_package(tmp_path / "local") + if path_type == "absolute": + spec = str(local) + elif path_type == "home": + spec = "~/local" + else: + spec = "file:~/local" + + installed = make_package(project / "node_modules" / "local-dependency") + + action, npm = make_action( + project, + {"dependencies": {"local-dependency": spec}}, + ) + + action.execute() + + assert not installed.exists() + assert (local / "index.js").exists() + npm.run.assert_called_once() + + +@pytest.mark.parametrize("spec", ["file:../local\x00", "../local\x00"]) +def test_rejects_null_characters(tmp_path, spec): + project = tmp_path / "project" + installed = make_package(project / "node_modules" / "local-dependency") + make_package(tmp_path / "local") + + action, npm = make_action( + project, + {"dependencies": {"local-dependency": spec}}, + ) + + action.execute() + + assert installed.exists() + npm.run.assert_called_once() + + +@pytest.mark.parametrize("install_links", [True, False]) +def test_install_refreshes_only_when_install_links_enabled(tmp_path, install_links): + project = tmp_path / "project" + local = make_package(tmp_path / "local") + installed = make_package(project / "node_modules" / "local-dependency") + + (project / "package.json").write_text( + json.dumps({"dependencies": {"local-dependency": "../local"}}), + encoding="utf-8", + ) + + npm = Mock() + action = NodejsNpmInstallAction( + str(project), + subprocess_npm=npm, + install_links=install_links, + ) + + def verify_before_install(*args, **kwargs): + assert installed.exists() != install_links + assert local.exists() + + npm.run.side_effect = verify_before_install + action.execute() + npm.run.assert_called_once() + + +def test_preserves_sources_from_overridden_declarations(tmp_path): + project = tmp_path / "project" + installed = make_package(project / "node_modules" / "local-dependency") + nested_source = make_package(installed / "nested-source") + make_package(tmp_path / "local") + + action, npm = make_action( + project, + { + "dependencies": { + "local-dependency": "../local", + "other": "1.0.0", + }, + "devDependencies": { + "other": "./node_modules/local-dependency/nested-source", + }, + }, + ) + + action.execute() + + assert installed.exists() + assert nested_source.exists() + npm.run.assert_called_once()