Skip to contentSkip to conversation

fetch/npm: fix security issue and re-enable fetcher

PATCH Superseded Thomas Perrot 3 participants 6 messages Jun 10 – Jun 16

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

cover fetch/npm: fix security issue and re-enable fetcher

The npm fetcher was disabled in 355cd226 (Jan 2026) because it retrieved checksums from the remote registry rather than from the recipe. A compromised registry controls both the tarball and its advertised hash, making checksum verification meaningless.

Fix the root cause by separating URL resolution from checksum handling:
- _resolve_proxy_url now stores only the bare tarball URL in the .resolved file; the registry-supplied dist.integrity / dist.shasum values are ignored entirely.
- _setup_proxy builds the proxy URL from that bare tarball URL and injects the checksum from the recipe's own SRC_URI parameters (sha512sum=, sha256sum=, etc.). When no checksum is provided the proxy URL carries none, and BitBake's standard BB_STRICT_CHECKSUM machinery handles the missing-checksum case the same way the wget fetcher does. A bb.warn() is emitted so recipe authors get a clear signal instead of a silent unsigned download.
- version=latest is now a hard ParameterError instead of a warning; it is inherently non-reproducible.
- Narrow the broad 'except Exception' in _npm_view to json.JSONDecodeError so that FetchError and ParameterError propagate typed to callers. Also fall back to str(error) when 'summary' is absent in the registry error dict so the message is never silently None.
- Clear uri.params before rebuilding the proxy URL to prevent a .resolved file written by the npmsw fetcher (which stores the full URI with checksum params) from contaminating the npm proxy URL with a registry-sourced checksum, bypassing the security invariant that only recipe-provided checksums are trusted.
- Remove dead 'if ud.version == "latest": return True' branch from need_update(); version=latest is rejected at urldata_init time.

Migration note: recipes using npm:// must now supply a checksum in SRC_URI, e.g.:

SRC_URI = "npm://registry.npmjs.org;package=lodash;version=4.17.21;sha512sum=<hex>"

On the first build without a checksum BitBake will download the tarball, compute the hash, and instruct the author to add it. Any stale .resolved files under DL_DIR/npm2/ written by the old fetcher (which embedded registry-sourced checksums) must be deleted before rebuilding.

[YOCTO #16105]

Fixes 355cd226e072 ("fetch2/npm: Disable npm/npmsw fetchers due to security issues")

---
Thomas Perrot (2):
fetch/npmsw: fix security issue and re-enable fetcher tests/fetch: restore and extend npm/npmsw test coverage

 lib/bb/fetch2/npmsw.py | 12 +++++-----
 lib/bb/tests/fetch.py  | 64 +++++++++++++++++++++++++++++++++++---------------
 2 files changed, 51 insertions(+), 25 deletions(-)

---
base-commit: d6bc0e5ec549a4f984cb3d470dd3c04d0ea46fde
change-id: 20260605-dev-tprrt-fix-npm-348c627ed2f2

Best regards,

Signature · 1 line
Thomas Perrot <[email protected]>
#1 lore raw

PATCH 1/2 fetch/npmsw: fix security issue and re-enable fetcher

The npmsw fetcher was disabled in 355cd226 (Jan 2026) along with the npm fetcher, but its security model is already correct: checksums come from the locally-committed npm-shrinkwrap.json file, not from the network.

Re-enable it with the following fixes:
- Add the missing FetchError import that would cause a NameError on malformed shrinkwrap files.
- Change 'if not packages' to 'if packages is None' in foreach_dependencies so a valid zero-dependency shrinkwrap (packages={}) no longer raises FetchError.
- Add 'elif resolved is None' guard before the startswith chain in _resolve_dependency so missing 'resolved' fields raise ParameterError instead of AttributeError.

[YOCTO #16105]

Fixes 355cd226e072 ("fetch2/npm: Disable npm/npmsw fetchers due to security issues")
---
 lib/bb/fetch2/npmsw.py | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
lib/bb/fetch2/npmsw.py +6 -6
index 5255e8b465e1..f09ea5794856 100644
@@ -21,6 +21,7 @@ import json
 import os
 import re
 import bb
+from bb.fetch2 import FetchError
 from bb.fetch2 import Fetch
 from bb.fetch2 import FetchMethod
 from bb.fetch2 import ParameterError
@@ -44,7 +45,7 @@ def foreach_dependencies(shrinkwrap, callback=None, dev=False):
             location = the location of the package (string)
     """
     packages = shrinkwrap.get("packages")
-    if not packages:
+    if packages is None:
         raise FetchError("Invalid shrinkwrap file format")
 
     for location, data in packages.items():
@@ -63,11 +64,7 @@ class NpmShrinkWrap(FetchMethod):
 
     def supports(self, ud, d):
         """Check if a given url can be fetched with npmsw"""
-        #return ud.type in ["npmsw"]
-        if ud.type in ["npmsw"]:
-            from bb.parse import SkipRecipe
-            raise SkipRecipe("The npmsw fetcher has been disabled due to security issues and there is no maintainer to address them")
-        return False
+        return ud.type in ["npmsw"]
 
     def urldata_init(self, ud, d):
         """Init npmsw specific variables within url data"""
@@ -126,6 +123,9 @@ class NpmShrinkWrap(FetchMethod):
                 extrapaths.append(resolvefile)
 
             # Handle http tarball sources
+            elif resolved is None:
+                raise ParameterError("Missing 'resolved' field for dependency '%s'" % name, ud.url)
+
             elif resolved.startswith("http") and integrity:
                 localfile = npm_localfile(os.path.basename(resolved))
 
Signature · 1 line
2.54.0
#2 lore raw

PATCH 2/2 tests/fetch: restore and extend npm/npmsw test coverage

In reply to Thomas Perrot

Re-enable all NPMTest cases that were disabled by returning an unconditional unittest.skip():
- Fix skipIfNoNpm() dead code: the shutil.which check was unreachable after the early return.
- Remove the return-skip guard from all test_npmsw_* tests; the npmsw fetcher is now re-enabled.
- Restore test_npm_no_network_no_tarball with a proper @skipIfNoNpm() decorator.

Adapt tests for the new npm fetcher behaviour:
- Replace test_npm_version_latest (which asserted success) with test_npm_version_latest_rejected, which asserts ParameterError since version=latest is no longer accepted.

Add two new tests:
- test_npm_recipe_checksum: verifies that a sha512sum/sha256sum param in SRC_URI is forwarded to the proxy fetcher and the download succeeds when it matches.
- test_npm_bad_recipe_checksum_rejected: verifies that a wrong checksum in the recipe causes the fetch to fail.

[YOCTO #16105]

---
 lib/bb/tests/fetch.py | 64 ++++++++++++++++++++++++++++++++++++---------------
 1 file changed, 45 insertions(+), 19 deletions(-)
lib/bb/tests/fetch.py +45 -19
index 95cf6c414bbe..a7629b975101 100644
@@ -17,6 +17,7 @@ import collections
 import os
 import signal
 import subprocess
+import json
 import tarfile
 from bb.fetch2 import URI
 import bb
@@ -2875,7 +2876,6 @@ class CrateTest(FetcherTest):
 
 class NPMTest(FetcherTest):
     def skipIfNoNpm():
-        return unittest.skip('npm disabled due to security issues')
         if not shutil.which('npm'):
             return unittest.skip('npm not installed')
         return lambda f: f
@@ -2897,7 +2897,9 @@ class NPMTest(FetcherTest):
     @skipIfNoNpm()
     @skipIfNoNetwork()
     def test_npm_bad_checksum(self):
-        urls = ['npm://registry.npmjs.org;package=@savoirfairelinux/node-server-example;version=1.0.0']
+        urls = ['npm://registry.npmjs.org;package=@savoirfairelinux/node-server-example;version=1.0.0'
+                ';sha512sum=f2dd7d88cb9a129fbb97eb87a8b5103bab24f783420fd7587f8000a355a12bf7'
+                '83f1263230afc588123958b73e36bb241f63eaf08119aac5aa2a870bc4de9223']
         # Fetch once to get a tarball
         fetcher = bb.fetch.Fetch(urls, self.d)
         ud = fetcher.ud[fetcher.urls[0]]
@@ -3001,8 +3003,8 @@ class NPMTest(FetcherTest):
         unpackdir = os.path.join(self.unpackdir, 'foo', 'bar')
         self.assertTrue(os.path.exists(os.path.join(unpackdir, 'package.json')))
 
+    @skipIfNoNpm()
     def test_npm_no_network_no_tarball(self):
-        return unittest.skip('npm disabled due to security issues')
         urls = ['npm://registry.npmjs.org;package=@savoirfairelinux/node-server-example;version=1.0.0']
         self.d.setVar('BB_NO_NETWORK', '1')
         fetcher = bb.fetch.Fetch(urls, self.d)
@@ -3027,7 +3029,7 @@ class NPMTest(FetcherTest):
     @skipIfNoNpm()
     @skipIfNoNetwork()
     def test_npm_registry_alternate(self):
-        urls = ['npm://skimdb.npmjs.com;package=@savoirfairelinux/node-server-example;version=1.0.0']
+        urls = ['npm://registry.npmjs.org;package=@savoirfairelinux/node-server-example;version=1.0.0']
         fetcher = bb.fetch.Fetch(urls, self.d)
         fetcher.download()
         fetcher.unpack(self.unpackdir)
@@ -3035,14 +3037,10 @@ class NPMTest(FetcherTest):
         self.assertTrue(os.path.exists(os.path.join(unpackdir, 'package.json')))
 
     @skipIfNoNpm()
-    @skipIfNoNetwork()
-    def test_npm_version_latest(self):
+    def test_npm_version_latest_rejected(self):
         url = ['npm://registry.npmjs.org;package=@savoirfairelinux/node-server-example;version=latest']
-        fetcher = bb.fetch.Fetch(url, self.d)
-        fetcher.download()
-        fetcher.unpack(self.unpackdir)
-        unpackdir = os.path.join(self.unpackdir, 'npm')
-        self.assertTrue(os.path.exists(os.path.join(unpackdir, 'package.json')))
+        with self.assertRaises(bb.fetch2.ParameterError):
+            bb.fetch.Fetch(url, self.d)
 
     @skipIfNoNpm()
     @skipIfNoNetwork()
@@ -3067,6 +3065,42 @@ class NPMTest(FetcherTest):
         with self.assertRaises(bb.fetch2.ParameterError):
             fetcher = bb.fetch.Fetch(urls, self.d)
 
+    @skipIfNoNpm()
+    @skipIfNoNetwork()
+    def test_npm_recipe_checksum(self):
+        """A sha512sum param in SRC_URI is forwarded to the proxy and verified."""
+        import subprocess
+        from bb.fetch2.npm import npm_integrity
+        result = subprocess.run(
+            ['npm', 'view', '--json', '@savoirfairelinux/[email protected]'],
+            capture_output=True, text=True)
+        if result.returncode != 0:
+            self.skipTest('npm view failed: %s' % result.stderr.strip())
+        try:
+            view = json.loads(result.stdout)
+        except json.JSONDecodeError:
+            self.skipTest('npm view returned invalid JSON')
+        integrity = view.get('dist', {}).get('integrity')
+        if not integrity:
+            self.skipTest('npm view response missing dist.integrity')
+        checksum_name, hexsum = npm_integrity(integrity)
+        urls = ['npm://registry.npmjs.org;package=@savoirfairelinux/node-server-example'
+                ';version=1.0.0;%s=%s' % (checksum_name, hexsum)]
+        fetcher = bb.fetch.Fetch(urls, self.d)
+        ud = fetcher.ud[fetcher.urls[0]]
+        fetcher.download()
+        self.assertTrue(os.path.exists(ud.localpath))
+
+    @skipIfNoNpm()
+    @skipIfNoNetwork()
+    def test_npm_bad_recipe_checksum_rejected(self):
+        """A wrong sha512sum param in SRC_URI causes the fetch to fail."""
+        urls = ['npm://registry.npmjs.org;package=@savoirfairelinux/node-server-example'
+                ';version=1.0.0;sha512sum=deadbeef00']
+        fetcher = bb.fetch.Fetch(urls, self.d)
+        with self.assertRaises(bb.fetch2.FetchError):
+            fetcher.download()
+
     @skipIfNoNpm()
     @skipIfNoNetwork()
     def test_npm_registry_none(self):
@@ -3099,7 +3133,6 @@ class NPMTest(FetcherTest):
 
     @skipIfNoNetwork()
     def test_npmsw(self):
-        return unittest.skip('npm disabled due to security issues')
         swfile = self.create_shrinkwrap_file({
             'packages': {
                 'node_modules/array-flatten': {
@@ -3136,7 +3169,6 @@ class NPMTest(FetcherTest):
 
     @skipIfNoNetwork()
     def test_npmsw_git(self):
-        return unittest.skip('npm disabled due to security issues')
         swfile = self.create_shrinkwrap_file({
             'packages': {
                 'node_modules/cookie': {
@@ -3150,7 +3182,6 @@ class NPMTest(FetcherTest):
 
     @skipIfNoNetwork()
     def test_npmsw_dev(self):
-        return unittest.skip('npm disabled due to security issues')
         swfile = self.create_shrinkwrap_file({
             'packages': {
                 'node_modules/array-flatten': {
@@ -3179,7 +3210,6 @@ class NPMTest(FetcherTest):
 
     @skipIfNoNetwork()
     def test_npmsw_destsuffix(self):
-        return unittest.skip('npm disabled due to security issues')
         swfile = self.create_shrinkwrap_file({
             'packages': {
                 'node_modules/array-flatten': {
@@ -3195,7 +3225,6 @@ class NPMTest(FetcherTest):
         self.assertTrue(os.path.exists(os.path.join(self.unpackdir, 'foo', 'bar', 'node_modules', 'array-flatten', 'package.json')))
 
     def test_npmsw_no_network_no_tarball(self):
-        return unittest.skip('npm disabled due to security issues')
         swfile = self.create_shrinkwrap_file({
             'packages': {
                 'node_modules/array-flatten': {
@@ -3235,7 +3264,6 @@ class NPMTest(FetcherTest):
 
     @skipIfNoNetwork()
     def test_npmsw_npm_reusability(self):
-        return unittest.skip('npm disabled due to security issues')
         # Fetch once with npmsw
         swfile = self.create_shrinkwrap_file({
             'packages': {
@@ -3258,7 +3286,6 @@ class NPMTest(FetcherTest):
 
     @skipIfNoNetwork()
     def test_npmsw_bad_checksum(self):
-        return unittest.skip('npm disabled due to security issues')
         # Try to fetch with bad checksum
         swfile = self.create_shrinkwrap_file({
             'packages': {
@@ -3355,7 +3382,6 @@ class NPMTest(FetcherTest):
 
     @skipIfNoNetwork()
     def test_npmsw_bundled(self):
-        return unittest.skip('npm disabled due to security issues')
         swfile = self.create_shrinkwrap_file({
             'packages': {
                 'node_modules/array-flatten': {
Signature · 1 line
2.54.0
#3 lore raw
In reply to Thomas Perrot
Quoted 44 lines · Thomas Perrot via lists.openembedded.org

The npm fetcher was disabled in 355cd226 (Jan 2026) because it retrieved checksums from the remote registry rather than from the recipe.  A compromised registry controls both the tarball and its advertised hash, making checksum verification meaningless.

Fix the root cause by separating URL resolution from checksum handling:
- _resolve_proxy_url now stores only the bare tarball URL in the .resolved file; the registry-supplied dist.integrity / dist.shasum values are ignored entirely.
- _setup_proxy builds the proxy URL from that bare tarball URL and injects the checksum from the recipe's own SRC_URI parameters (sha512sum=, sha256sum=, etc.).  When no checksum is provided the proxy URL carries none, and BitBake's standard BB_STRICT_CHECKSUM machinery handles the missing-checksum case the same way the wget fetcher does.  A bb.warn() is emitted so recipe authors get a clear signal instead of a silent unsigned download.
- version=latest is now a hard ParameterError instead of a warning; it is inherently non-reproducible.
- Narrow the broad 'except Exception' in _npm_view to json.JSONDecodeError so that FetchError and ParameterError propagate typed to callers.  Also fall back to str(error) when 'summary' is absent in the registry error dict so the message is never silently None.
- Clear uri.params before rebuilding the proxy URL to prevent a .resolved file written by the npmsw fetcher (which stores the full URI with checksum params) from contaminating the npm proxy URL with a registry-sourced checksum, bypassing the security invariant that only recipe-provided checksums are trusted.
- Remove dead 'if ud.version == "latest": return True' branch from need_update(); version=latest is rejected at urldata_init time.

Migration note: recipes using npm:// must now supply a checksum in SRC_URI, e.g.:

  SRC_URI = "npm://registry.npmjs.org;package=lodash;version=4.17.21;sha512sum=<hex>"

On the first build without a checksum BitBake will download the tarball, compute the hash, and instruct the author to add it.  Any stale .resolved files under DL_DIR/npm2/ written by the old fetcher (which embedded registry-sourced checksums) must be deleted before rebuilding.

[YOCTO #16105]

Fixes 355cd226e072 ("fetch2/npm: Disable npm/npmsw fetchers due to security issues")
Quoted 8 lines

---
Thomas Perrot (2):
      fetch/npmsw: fix security issue and re-enable fetcher tests/fetch: restore and extend npm/npmsw test coverage

 lib/bb/fetch2/npmsw.py | 12 +++++-----
 lib/bb/tests/fetch.py  | 64 +++++++++++++++++++++++++++++++++++---------------

 2 files changed, 51 insertions(+), 25 deletions(-)

I suspect there is a patch missing or something here as it doesn't touch npm.py and half the changes above appear missing...

Cheers,

Richard

#4 lore raw

Hello Richard,

Quoted 73 lines · Richard Purdie via lists.openembedded.org
Quoted 71 lines · Thomas Perrot via lists.openembedded.org

The npm fetcher was disabled in 355cd226 (Jan 2026) because it retrieved
checksums from the remote registry rather than from the recipe.  A compromised registry controls both the tarball and its advertised hash,
making checksum verification meaningless.

Fix the root cause by separating URL resolution from checksum handling:
- _resolve_proxy_url now stores only the bare tarball URL in the .resolved
  file; the registry-supplied dist.integrity / dist.shasum values are
  ignored entirely.
- _setup_proxy builds the proxy URL from that bare tarball URL and injects
  the checksum from the recipe's own SRC_URI parameters (sha512sum=,
  sha256sum=, etc.).  When no checksum is provided the proxy URL carries
  none, and BitBake's standard BB_STRICT_CHECKSUM machinery handles the
  missing-checksum case the same way the wget fetcher does.  A bb.warn()
  is emitted so recipe authors get a clear signal instead of a silent
  unsigned download.
- version=latest is now a hard ParameterError instead of a warning; it is
  inherently non-reproducible.
- Narrow the broad 'except Exception' in _npm_view to json.JSONDecodeError
  so that FetchError and ParameterError propagate typed to callers.  Also
  fall back to str(error) when 'summary' is absent in the registry error
  dict so the message is never silently None.
- Clear uri.params before rebuilding the proxy URL to prevent a .resolved file written by the npmsw fetcher (which stores the full URI
  with checksum params) from contaminating the npm proxy URL with a registry-sourced checksum, bypassing the security invariant that only
  recipe-provided checksums are trusted.
- Remove dead 'if ud.version == "latest": return True' branch from need_update(); version=latest is rejected at urldata_init time.

Migration note: recipes using npm:// must now supply a checksum in SRC_URI, e.g.:

  SRC_URI = "npm://registry.npmjs.org;package=lodash;version=4.17.21;sha512sum= <hex>"

On the first build without a checksum BitBake will download the tarball,
compute the hash, and instruct the author to add it.  Any stale .resolved
files under DL_DIR/npm2/ written by the old fetcher (which embedded registry-sourced checksums) must be deleted before rebuilding.

[YOCTO #16105]

Fixes 355cd226e072 ("fetch2/npm: Disable npm/npmsw fetchers due to

security issues")

---
Thomas Perrot (2):
      fetch/npmsw: fix security issue and re-enable fetcher tests/fetch: restore and extend npm/npmsw test coverage

Quoted 7 lines
Quoted 4 lines

 lib/bb/fetch2/npmsw.py | 12 +++++----- lib/bb/tests/fetch.py  | 64 +++++++++++++++++++++++++++++++++++---
------------

 2 files changed, 51 insertions(+), 25 deletions(-)

I suspect there is a patch missing or something here as it doesn't touch npm.py and half the changes above appear missing...

Sorry, that’s strange, it seems I made a mistake with b4. I’ll resend them.

Kind regards,
Thomas

Quoted 15 lines

Cheers,

Richard

-=-=-=-=-=-=-=-=-=-=-=-
Links: You receive all messages sent to this group. View/Reply Online (#19646):
https://lists.openembedded.org/g/bitbake-devel/message/19646
Mute This Topic: https://lists.openembedded.org/mt/119741992/5443093
Group Owner: [email protected] Unsubscribe:
https://lists.openembedded.org/g/bitbake-devel/unsub [[email protected]
]
-=-=-=-=-=-=-=-=-=-=-=-

Signature · 3 lines
Thomas Perrot, Bootlin
Embedded Linux and kernel engineering
https://bootlin.com
#5 lore raw
Quoted 5 lines · Thomas Perrot via lists.openembedded.org
Quoted 2 lines

I suspect there is a patch missing or something here as it doesn't touch npm.py and half the changes above appear missing...

Sorry, that’s strange, it seems I made a mistake with b4. I’ll resend them.

What happened to that? :)

There are users of the fetcher that resort to horrible hacks, and there's just been another request for it, so if you have patches, that would be most welcome.

Alex