diff mbox series

fetch/gitsm: Fix submodule premirror fetch with BB_FETCH_PREMIRRORONLY

Message ID 20261204132502.306778-1-tiago.mlb.vasconcelos@gmail.com
State New
Headers show
Series fetch/gitsm: Fix submodule premirror fetch with BB_FETCH_PREMIRRORONLY | expand

Commit Message

Tiago Vasconcelos Dec. 4, 2026, 1:25 p.m. UTC
With BB_FETCH_PREMIRRORONLY enabled, try_mirror_url() sets BB_NO_NETWORK to
"1" in a copy of the datastore before calling the original fetcher for a
downloaded mirror tarball, so that no git commands can reach upstream.

For gitsm that datastore is also used to fetch the submodules. The nested
Fetch object inherits BB_NO_NETWORK="1" and therefore blocks its own
PREMIRRORS download, even though the parent repository was downloaded from
the same premirror. The fetch fails with:

```text
gitsm: submodule download failed: NetworkAccess Network access disabled
  through BB_NO_NETWORK (or set indirectly due to use of
  BB_FETCH_PREMIRRORONLY) but access requested with command wget ...
```

Save the original BB_NO_NETWORK value in a datastore flag and restore it
before downloading a mirror candidate. This allows nested submodule
mirror downloads while retaining the network block when processing the
downloaded tarball with the original fetcher.

Add a dedicated submodule premirror test suite with shared repository
and mirror setup. Use a local HTTP server to verify that full and shallow
submodule fetches succeed with BB_FETCH_PREMIRRORONLY enabled. Also verify
that a submodule missing from the premirror fails with NetworkAccess
rather than falling back to upstream.

Signed-off-by: Tiago Vasconcelos <tiago.mlb.vasconcelos@gmail.com>
---
 lib/bb/fetch/__init__.py |  12 ++++
 lib/bb/tests/fetch.py    | 128 +++++++++++++++++++++++++++++++++++++++
 2 files changed, 140 insertions(+)
diff mbox series

Patch

diff --git a/lib/bb/fetch/__init__.py b/lib/bb/fetch/__init__.py
index 76e0778d1..5c57e29e0 100644
--- a/lib/bb/fetch/__init__.py
+++ b/lib/bb/fetch/__init__.py
@@ -1078,6 +1078,14 @@  def try_mirror_url(fetch, origud, ud, ld, check = False):
     # Return of None or a value means we're finished
     # False means try another url
 
+    # Save the original network setting before premirror-only processing
+    # forces BB_NO_NETWORK to 1. Datastore copies pass this flag to nested
+    # submodule fetches, which restore the setting for mirror downloads.
+    network = ld.getVarFlag("BB_NO_NETWORK", "original_bb_no_network")
+    if network is None:
+        network = ld.getVar("BB_NO_NETWORK") or "0"
+        ld.setVarFlag("BB_NO_NETWORK", "original_bb_no_network", network)
+
     try:
         lf = None
         if ud.lockfile != origud.lockfile:
@@ -1090,6 +1098,10 @@  def try_mirror_url(fetch, origud, ud, ld, check = False):
             return False
 
         if not verify_donestamp(ud, ld, origud) or ud.method.need_update(ud, ld):
+            if bb.utils.to_boolean(ld.getVar("BB_FETCH_PREMIRRORONLY")):
+                # Restore the original setting so PREMIRRORONLY blocks upstream access
+                # without also blocking downloads from configured mirrors.
+                ld.setVar("BB_NO_NETWORK", network)
             ud.method.download(ud, ld)
             if hasattr(ud.method,"build_mirror_data"):
                 ud.method.build_mirror_data(ud, ld)
diff --git a/lib/bb/tests/fetch.py b/lib/bb/tests/fetch.py
index 6f30ade5b..98e2843a7 100644
--- a/lib/bb/tests/fetch.py
+++ b/lib/bb/tests/fetch.py
@@ -2608,6 +2608,134 @@  class GitShallowTest(FetcherTest):
         self.fetch_shallow(uri)
         self.assertRevCount(1)
 
+class GitSubmodulePremirrorTest(FetcherTest):
+    def setUp(self):
+        FetcherTest.setUp(self)
+        self.gitdir = os.path.join(self.tempdir, 'git')
+        self.srcdir = os.path.join(self.tempdir, 'gitsource')
+        bb.utils.mkdirhier(self.srcdir)
+        self.git_init(cwd=self.srcdir)
+        self.d.setVar('WORKDIR', self.tempdir)
+        self.d.setVar('S', self.gitdir)
+        self.d.delVar('PREMIRRORS')
+        self.d.delVar('MIRRORS')
+        self.d.setVar('SRCREV', '${AUTOREV}')
+        self.d.setVar('AUTOREV', '${@bb.fetch.get_autorev(d)}')
+        self.d.setVar("__BBSRCREV_SEEN", "1")
+
+    def add_empty_file(self, path, cwd=None):
+        if cwd is None:
+            cwd = self.srcdir
+        open(os.path.join(cwd, path), 'w').close()
+        self.git(['add', path], cwd=cwd)
+        self.git(['commit', '-m', path, path], cwd=cwd)
+
+    def fetch(self, uri):
+        d = self.d.createCopy()
+        d.setVar('SRC_URI', uri)
+        uri = d.expand(uri)
+        fetcher = bb.fetch.Fetch([uri], d)
+        fetcher.download()
+        return fetcher
+
+    def assertRevCount(self, expected_count, cwd=None):
+        if cwd is None:
+            cwd = self.gitdir
+        actual_count = len(self.git(['rev-list', 'HEAD'], cwd=cwd).splitlines())
+        self.assertEqual(expected_count, actual_count, msg='Object count `%d` is not the expected `%d`' % (actual_count, expected_count))
+
+    def use_http_premirror(self, mirrordir):
+        # Serve the prepared downloads locally and allow this host in mirror-only mode.
+        server = HTTPService(mirrordir, host='127.0.0.1')
+        server.start()
+        self.addCleanup(server.stop)
+        self.d.setVar('PREMIRRORS', 'gitsm://.*/.* http://127.0.0.1:%s/' % server.port)
+        self.d.setVar('BB_FETCH_PREMIRRORONLY', '1')
+        self.d.setVar('BB_NO_NETWORK', '0')
+        self.d.setVar('BB_ALLOWED_NETWORKS', '127.0.0.1')
+
+    def create_submodule_repo(self, submodule_url=None):
+        self.add_empty_file('a')
+        self.add_empty_file('b')
+
+        submodule_dir = os.path.join(self.tempdir, 'gitsubmodule')
+        bb.utils.mkdirhier(submodule_dir)
+        self.git_init(cwd=submodule_dir)
+        # Make this look like it was cloned from a remote...
+        self.git(['config', '--add', 'remote.origin.url', submodule_dir], cwd=submodule_dir)
+        self.git(['config', '--add', 'remote.origin.fetch', '+refs/heads/*:refs/remotes/origin/*'], cwd=submodule_dir)
+        self.add_empty_file('asub', cwd=submodule_dir)
+        self.add_empty_file('bsub', cwd=submodule_dir)
+
+        self.git(['submodule', 'init'], cwd=self.srcdir)
+        self.git(['-c', 'protocol.file.allow=always', 'submodule', 'add', 'file://%s' % submodule_dir], cwd=self.srcdir)
+        self.git(['submodule', 'update'], cwd=self.srcdir)
+        if submodule_url is not None:
+            self.git(['config', '-f', '.gitmodules', 'submodule.gitsubmodule.url', submodule_url], cwd=self.srcdir)
+        self.git(['commit', '-m', 'submodule', '-a'], cwd=self.srcdir)
+
+        uri = 'gitsm://%s;protocol=file;subdir=${S};branch=master' % self.srcdir
+        return uri, submodule_dir
+
+    def prepare_submodule_premirror(self, uri, shallow=False):
+        self.d.setVar('BB_GIT_SHALLOW', '1' if shallow else '0')
+        self.d.setVar('BB_GENERATE_MIRROR_TARBALLS', '0' if shallow else '1')
+        self.d.setVar('BB_GENERATE_SHALLOW_TARBALLS', '1' if shallow else '0')
+
+        # Fetch once to generate the mirror tarballs
+        self.fetch(uri)
+
+        # Stop generating tarballs during the mirror-only fetch.
+        self.d.setVar('BB_GENERATE_MIRROR_TARBALLS', '0')
+        self.d.setVar('BB_GENERATE_SHALLOW_TARBALLS', '0')
+        mirrordir = os.path.join(self.tempdir, 'mirror')
+        bb.utils.rename(self.dldir, mirrordir)
+        bb.utils.mkdirhier(self.dldir)
+        return mirrordir
+
+    def check_submodule_premirroronly(self, shallow):
+        uri, submodule_dir = self.create_submodule_repo()
+        mirrordir = self.prepare_submodule_premirror(uri, shallow=shallow)
+
+        # Remove the original repositories so the fetch must use the premirror.
+        bb.utils.remove(self.gitdir, recurse=True)
+        bb.utils.remove(self.srcdir, recurse=True)
+        bb.utils.remove(submodule_dir, recurse=True)
+
+        self.use_http_premirror(mirrordir)
+        self.fetch(uri).unpack(self.d.getVar('WORKDIR'))
+
+        # Shallow fetches retain only the tip commit; full fetches retain all commits.
+        expected_revisions = 1 if shallow else 3
+        self.assertRevCount(expected_revisions)
+        self.assertTrue(os.listdir(os.path.join(self.gitdir, 'gitsubmodule')))
+        expected_submodule_revisions = 1 if shallow else 2
+        self.assertRevCount(expected_submodule_revisions, cwd=os.path.join(self.gitdir, 'gitsubmodule'))
+
+    def test_submodule_premirroronly(self):
+        """Submodules must be fetched from a network PREMIRRORS with BB_FETCH_PREMIRRORONLY"""
+        self.check_submodule_premirroronly(shallow=False)
+
+    def test_shallow_submodule_premirroronly(self):
+        """Shallow submodules must be fetched from a network PREMIRRORS with BB_FETCH_PREMIRRORONLY"""
+        self.check_submodule_premirroronly(shallow=True)
+
+    def test_submodule_premirroronly_no_upstream(self):
+        """A submodule missing from PREMIRRORS must not be fetched from upstream"""
+        uri, submodule_dir = self.create_submodule_repo(submodule_url='https://git.invalid/sub.git')
+
+        # Generate only the parent tarball, leaving the submodule missing from the mirror.
+        mirrordir = self.prepare_submodule_premirror('git://%s;protocol=file;branch=master' % self.srcdir)
+        bb.utils.remove(self.srcdir, recurse=True)
+        bb.utils.remove(submodule_dir, recurse=True)
+
+        self.use_http_premirror(mirrordir)
+        # The missing submodule premirror must fail instead of falling back to upstream.
+        with self.assertRaises(bb.fetch.NetworkAccess) as cm:
+            self.fetch(uri)
+        self.assertIn('git.invalid', cm.exception.url)
+
+
 class GitLfsTest(FetcherTest):
     def skipIfNoGitLFS():
         if not shutil.which('git-lfs'):