Skip to content
Open
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
128 changes: 128 additions & 0 deletions aws_lambda_builders/workflows/nodejs_npm/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Comment on lines +214 to +217

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[BUG] Local dependencies hoisted to an npm workspace root are never refreshed
_refresh_local_dependencies reads only install_dir/package.json and looks for installed copies only at install_dir/node_modules/<name>. If that directory is missing, the dependency is skipped.

This misses both workspace cases:

  • Building one workspace member in source. npm hoists the member's dependencies into the workspace root's node_modules. workflow.py says so in a comment and links them through resolve_project_root / NodejsNpmLinkDependencyClosureAction. Because nothing exists beside the function, the os.path.isdir(installed) check skips the dependency, and the stale copy at the root stays in place.
  • prepare_shared_project. Here install_dir is the project root, so only the root manifest is read. file: or bare-path dependencies that member packages declare, and that npm hoists into the root node_modules, are never considered.

Either way the original stale-dependency bug (aws/aws-sam-cli#7546) still happens in monorepos, even though the PR description says hoisted dependencies are supported. None of the new tests cover a workspace layout.

A fix would resolve the npm project root (as workflow.py already does with subprocess_npm.resolve_project_root) and look for installed copies there. The shared-preparation case also needs the member manifests to be read.


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):
"""
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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")
Expand Down
Original file line number Diff line number Diff line change
@@ -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)
Loading
Loading