Skip to contentSkip to conversation

fetch2: Add support for upstream source tracing

PATCH Superseded [email protected] 2 participants 5 messages Apr 23, 2023 – Apr 24, 2023

v3 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

PATCH v3 1/3 fetch2: Add support for upstream source tracing

From: Alberto Pianon <[email protected]>

License compliance, SBoM generation and CVE checking require to be able to trace each source file back to its corresponding upstream source. The current implementation of bb.fetch2 makes it difficult, especially when multiple upstream sources are combined together.

This patch provides an interface to solve the issue by implementing a process that unpacks each SRC_URI element into a temporary directory, creates an entrypoint to collect relevant provenance metadata on each source file, moves everything to the recipe rootdir, and saves metadata in a JSON file.

This patch contains required modifications to fetchers' code plus a TraceUnpackBase class that implements the above described process. Data collection logic should be separately implemented by subclassing TraceUnpackBase, implementing _collect_data() and _process_data() methods.

Splitting the above described solution in multiple patches and in multiple modules/classes aims at easing review and merge process, and also at decoupling the development of the data collection logic from the process that enables it.

---
 bin/bitbake-selftest        |   1 +
 lib/bb/fetch2/__init__.py   |  55 +++++++-
 lib/bb/fetch2/crate.py      |   2 +
 lib/bb/fetch2/gitsm.py      |  24 +++-
 lib/bb/fetch2/hg.py         |   1 +
 lib/bb/fetch2/npm.py        |   1 +
 lib/bb/fetch2/npmsw.py      |  26 +++-
 lib/bb/fetch2/trace_base.py | 256 ++++++++++++++++++++++++++++++++++++
 lib/bb/tests/trace_base.py  | 227 ++++++++++++++++++++++++++++++++
 9 files changed, 584 insertions(+), 9 deletions(-)
 create mode 100644 lib/bb/fetch2/trace_base.py
 create mode 100644 lib/bb/tests/trace_base.py
bin/bitbake-selftest +1 -0
index f25f23b1..6d60a5d2 100755
@@ -31,6 +31,7 @@ tests = ["bb.tests.codeparser",
          "bb.tests.runqueue",
          "bb.tests.siggen",
          "bb.tests.utils",
+         "bb.tests.trace_base",
          "bb.tests.compression",
          "hashserv.tests",
          "layerindexlib.tests.layerindexobj",
lib/bb/fetch2/__init__.py +52 -3

102 lines not on this page · raw message

lib/bb/fetch2/crate.py +2 -0
index a7021e5b..93666de0 100644
@@ -101,8 +101,10 @@ class Crate(Wget):
         pn = d.getVar('BPN')
         if pn == ud.parm.get('name'):
             cmd = "tar -xz --no-same-owner -f %s" % thefile
+            ud.destdir = rootdir
         else:
             cargo_bitbake = self._cargo_bitbake_path(rootdir)
+            ud.destdir = cargo_bitbake
 
             cmd = "tar -xz --no-same-owner -f %s -C %s" % (thefile, cargo_bitbake)
 
lib/bb/fetch2/gitsm.py +23 -1
index f8e239bc..c161d1f3 100644
@@ -34,6 +34,11 @@ class GitSM(Git):
         """
         return ud.type in ['gitsm']
 
+    def urldata_init(self, ud, d):
+        super(GitSM, self).urldata_init(ud, d)
+        ud.module_data = []
+        ud.checkout_destdir = None
+
     def process_submodules(self, ud, workdir, function, d):
         """
         Iterate over all of the submodules in this repository and execute
@@ -138,6 +143,15 @@ class GitSM(Git):
 
             function(ud, url, module, paths[module], workdir, ld)
 
+            if function.__name__ == "unpack_submodules":
+                destdir = os.path.join(ud.checkout_destdir, paths[module])
+                ud.module_data.append({
+                    "url": url,
+                    "destdir": destdir.rstrip("/"),
+                    "parent_destdir": ud.checkout_destdir.rstrip("/"),
+                    "revision": subrevision[module]
+                })
+
         return submodules != []
 
     def need_update(self, ud, d):
@@ -209,9 +223,13 @@ class GitSM(Git):
             else:
                 repo_conf = os.path.join(ud.destdir, '.git')
 
+            checkout_destdir = os.path.join(ud.checkout_destdir, modpath)
+
             try:
                 newfetch = Fetch([url], d, cache=False)
-                newfetch.unpack(root=os.path.dirname(os.path.join(repo_conf, 'modules', module)))
+                newfetch.unpack(root=os.path.dirname(os.path.join(repo_conf, 'modules', module)), is_module=True, checkout_destdir=checkout_destdir)
+                # add nested submodules' data
+                ud.module_data += newfetch.ud[url].module_data
             except Exception as e:
                 logger.error('gitsm: submodule unpack failed: %s %s' % (type(e).__name__, str(e)))
                 raise
@@ -233,6 +251,10 @@ class GitSM(Git):
 
         Git.unpack(self, ud, destdir, d)
 
+        if not ud.checkout_destdir:
+            # for main git repo, checkout destdir corresponds with unpack destdir
+            ud.checkout_destdir = ud.destdir
+
         ret = self.process_submodules(ud, ud.destdir, unpack_submodules, d)
 
         if not ud.bareclone and ret:
lib/bb/fetch2/hg.py +1 -0
index 063e1300..0fd69db7 100644
@@ -242,6 +242,7 @@ class Hg(FetchMethod):
         revflag = "-r %s" % ud.revision
         subdir = ud.parm.get("destsuffix", ud.module)
         codir = "%s/%s" % (destdir, subdir)
+        ud.destdir = codir
 
         scmdata = ud.parm.get("scmdata", "")
         if scmdata != "nokeep":
lib/bb/fetch2/npm.py +1 -0
index 8a179a33..34e1f276 100644
@@ -294,6 +294,7 @@ class Npm(FetchMethod):
         destsuffix = ud.parm.get("destsuffix", "npm")
         destdir = os.path.join(rootdir, destsuffix)
         npm_unpack(ud.localpath, destdir, d)
+        ud.destdir = destdir
 
     def clean(self, ud, d):
         """Clean any existing full or partial download"""
lib/bb/fetch2/npmsw.py +21 -5
index 36fcbfba..79c369dc 100644
@@ -66,6 +66,9 @@ class NpmShrinkWrap(FetchMethod):
     def urldata_init(self, ud, d):
         """Init npmsw specific variables within url data"""
 
+        # initialize module_data (for module source tracing)
+        ud.module_data = []
+
         # Get the 'shrinkwrap' parameter
         ud.shrinkwrap_file = re.sub(r"^npmsw://", "", ud.url.split(";")[0])
 
@@ -250,20 +253,33 @@ class NpmShrinkWrap(FetchMethod):
 
     def unpack(self, ud, rootdir, d):
         """Unpack the downloaded dependencies"""
-        destdir = d.getVar("S")
-        destsuffix = ud.parm.get("destsuffix")
-        if destsuffix:
-            destdir = os.path.join(rootdir, destsuffix)
+        # rootdir param is a temporary dir. The real rootdir, where sources are
+        # moved after being traced, is stored in ud.rootdir.
+        destsuffix = ud.parm.get("destsuffix") or os.path.relpath(d.getVar("S"), ud.rootdir)
+        destdir = os.path.join(rootdir, destsuffix)
+        ud.destdir = destdir
 
         bb.utils.mkdirhier(destdir)
         bb.utils.copyfile(ud.shrinkwrap_file,
                           os.path.join(destdir, "npm-shrinkwrap.json"))
 
+        for dep in ud.deps:
+            dep_destdir = os.path.join(destdir, dep["destsuffix"])
+            # to get parent destdir, we get rid of the last 2 path elements
+            # (node_modules/<module_name>)
+            dep_parent_destdir = "/".join(dep_destdir.split("/")[:-2])
+            ud.module_data.append({
+                "url": dep["url"] or dep["localpath"],
+                "destdir": dep_destdir.rstrip("/"),
+                "parent_destdir": dep_parent_destdir.rstrip("/"),
+                "revision": None
+            })
+
         auto = [dep["url"] for dep in ud.deps if not dep["localpath"]]
         manual = [dep for dep in ud.deps if dep["localpath"]]
 
         if auto:
-            ud.proxy.unpack(destdir, auto)
+            ud.proxy.unpack(destdir, auto, is_module=True)
 
         for dep in manual:
             depdestdir = os.path.join(destdir, dep["destsuffix"])
lib/bb/fetch2/trace_base.py new file +256 -0

257 lines not on this page · raw message

lib/bb/tests/trace_base.py new file +227 -0

227 lines not on this page · raw message

Signature · 1 line
2.34.1
#1 lore raw

PATCH v3 2/3 fetch2: Add metadata collection for upstream source tracing

From: Alberto Pianon <[email protected]>

This patch subclasses TraceUnpackBase by implementing _collect_data() and _process_data() methods, in order to implement upstream metadata collection logic for bb.fetch2.

The final output is a compressed json file, stored in rootdir/temp. Data format is described in the help text of the trace module.

---
 lib/bb/fetch2/__init__.py |   2 +-
 lib/bb/fetch2/trace.py    | 534 ++++++++++++++++++++++++++++++++++++++
 2 files changed, 535 insertions(+), 1 deletion(-)
 create mode 100644 lib/bb/fetch2/trace.py
lib/bb/fetch2/__init__.py +1 -1
index c4915208..d241ae0f 100644
@@ -28,7 +28,7 @@ import bb.checksum
 import bb.process
 import bb.event
 
-from .trace_base import TraceUnpackBase as TraceUnpack
+from .trace import TraceUnpack
 
 __version__ = "2"
 _checksum_cache = bb.checksum.FileChecksumCache()
lib/bb/fetch2/trace.py new file +534 -0

534 lines not on this page · raw message

Signature · 1 line
2.34.1
#2 lore raw
In reply to [email protected]

Hi,

Quoted 6 lines · Alberto Pianon

From: Alberto Pianon <[email protected]>

License compliance, SBoM generation and CVE checking require to be able to trace each source file back to its corresponding upstream source. The current implementation of bb.fetch2 makes it difficult, especially when multiple upstream sources are combined together.

No comment to the patch itself, which seems to create a way to capture checksums of recipe source files which can be mapped to SRC_URI entries. Would be nice to have this as an optional feature though, unless the performance impact on builds is close to zero. Measurements?

But I see no connection toe CVE checking? The problem I have is that I've seen SPDX and SBOM things sold as solutions to CVE checking while in reality they have done nothing. Yocto has cve-check.bbclass which uses PN/CVE_PRODUCT and PV/CVE_VERSION to query data from CVE database and to generate reports about affected, patched and unpatched CVEs, which then also include info from patch files (CVE number, if any) and list of ignored CVEs from recipe metadata.

Even if SRC_URI can be split to individual entries, and each file in soure tree can be mapped to exact SRC_URI entry, then what's the link to CVEs?

CVEs don't map to SRC_URI entries even if they in theory could. CVEs don't map the exact source file checksums. Multiple versions of a source file can be mapped to be affected by a CVE they contain the same bug, which is usually encoded in CVEs as SW component name and upstream release version range. The SRC_URI entry SW component name and version are not added in this patch, and the CVE metadata about ignored and patched CVEs are not exported, so I don't see any links to CVEs.

Cheers,

-Mikko

#3 lore raw

Hi Mikko,

thanks for your feedback.

Quoted 5 lines · On 2023-04-24 11:15 Mikko Rapeli wrote:

Hi,

Quoted 2 lines · Alberto Pianon

From: Alberto Pianon <[email protected]>

Quoted 7 lines
Quoted 4 lines

License compliance, SBoM generation and CVE checking require to be able to trace each source file back to its corresponding upstream source. The current implementation of bb.fetch2 makes it difficult, especially when multiple upstream sources are combined together.

No comment to the patch itself, which seems to create a way to capture checksums of recipe source files which can be mapped to SRC_URI entries.

Not only to SRC_URI entries but to actual upstream download locations, especially for file:// SRC_URIs (which are local, but they usually have an upstream source such as a git repo) and for npmsw:// and gitsm:// SRC_URIs (a single SRC_URI may map to multiple download locations).

To grasp a better idea of the final result, you may have a look at (compressed) test data in the last patch, and at the corresponding test cases in TraceUnpackIntegrationTest:

http://cgit.openembedded.org/bitbake-contrib/commit/?h=alpianon/srctrace2

Quoted 3 lines

Would be nice to have this as an optional feature though, unless the performance impact on builds is close to zero. Measurements?

bitbake core-image-full-cmdline on a 16-core 32GB-ram VM, using an existing download cache (to avoid differences due to network performance) took 41m57.043s without the patches, and 42m26.727s with the patches. That's roughly 30s more; IMHO it seems acceptable.
Keep also in mind that source tracing is done only once and then data should be stored somehow in sstate-cache (WIP).
BTW the thing would require some more performance testing in an adequate testing infrastructure, could you (or others) help in this respect?

Quoted 12 lines

But I see no connection toe CVE checking? The problem I have is that I've seen SPDX and SBOM things sold as solutions to CVE checking while in reality they have done nothing. Yocto has cve-check.bbclass which uses PN/CVE_PRODUCT and PV/CVE_VERSION to query data from CVE database and to generate reports about affected, patched and unpatched CVEs, which then also include info from patch files (CVE number, if any) and list of ignored CVEs from recipe metadata.

Even if SRC_URI can be split to individual entries, and each file in soure tree can be mapped to exact SRC_URI entry, then what's the link to CVEs?

Quoted 7 lines

CVEs don't map to SRC_URI entries even if they in theory could. CVEs don't map the exact source file checksums. Multiple versions of a source file can be mapped to be affected by a CVE they contain the same bug, which is usually encoded in CVEs as SW component name and upstream release version range. The SRC_URI entry SW component name and version are not added in this patch, and the CVE metadata about ignored and patched CVEs are not exported, so I don't see any links to CVEs.

Actually the commit message could be improved in this respect. Being able to get upstream download locations (especially with recipes mixing multiple upstream sources, and with gitsm and npmsw fetchers) is a pre-condition to identify the relevant components and therefore do CVE checks, but CVE checks as such are not covered by the patch. I may clarify that.

For example, a possible improvement in this respect could be to calculate not only download locations (SPDX), but also purls (https://github.com/package-url/purl-spec),
which may be used to do CVE checks against commercial or, even better, open databases (such as VulnerableCode https://www.nexb.com/vulnerablecode/).

Cheers,

Alberto

#4 lore raw

Hi,

Quoted 26 lines · Alberto Pianon

Hi Mikko,

thanks for your feedback.

Quoted 13 lines · On 2023-04-24 11:15 Mikko Rapeli wrote:

Hi,

Quoted 9 lines · Alberto Pianon

From: Alberto Pianon <[email protected]>

License compliance, SBoM generation and CVE checking require to be able
to trace each source file back to its corresponding upstream source. The
current implementation of bb.fetch2 makes it difficult, especially when
multiple upstream sources are combined together.

Quoted 2 lines

No comment to the patch itself, which seems to create a way to capture checksums of recipe source files which can be mapped to SRC_URI entries.

Not only to SRC_URI entries but to actual upstream download locations, especially for file:// SRC_URIs (which are local, but they usually have an upstream source such as a git repo) and for npmsw:// and gitsm:// SRC_URIs (a single SRC_URI may map to multiple download locations).

Quoted 5 lines

To grasp a better idea of the final result, you may have a look at (compressed) test data in the last patch, and at the corresponding test cases in TraceUnpackIntegrationTest:

http://cgit.openembedded.org/bitbake-contrib/commit/?h=alpianon/srctrace2

I checked this. In the past I had exported similar information into buildhistory, though did not expand the SRC_URI entries. But post processing the data in buildhistory was handy for a few extra checks, like making sure all SW components/recipes have a valid CVE_PRODUCT. Richard rejected this approach though.

Quoted 4 lines
Quoted 3 lines

Would be nice to have this as an optional feature though, unless the performance impact on builds is close to zero. Measurements?

Quoted 8 lines

bitbake core-image-full-cmdline on a 16-core 32GB-ram VM, using an existing download cache (to avoid differences due to network performance) took 41m57.043s without the patches, and 42m26.727s with the patches. That's roughly 30s more; IMHO it seems acceptable.
Keep also in mind that source tracing is done only once and then data should be stored somehow in sstate-cache (WIP).
BTW the thing would require some more performance testing in an adequate testing infrastructure, could you (or others) help in this respect?

Ok, sounds like the performance impact is small enough. File system buffering in RAM hides most of the work, I think.

Quoted 27 lines
Quoted 12 lines

But I see no connection toe CVE checking? The problem I have is that I've seen SPDX and SBOM things sold as solutions to CVE checking while in reality they have done nothing. Yocto has cve-check.bbclass which uses PN/CVE_PRODUCT and PV/CVE_VERSION to query data from CVE database and to generate reports about affected, patched and unpatched CVEs, which then also include info from patch files (CVE number, if any) and list of ignored CVEs from recipe metadata.

Even if SRC_URI can be split to individual entries, and each file in soure tree can be mapped to exact SRC_URI entry, then what's the link to CVEs?

Quoted 8 lines

CVEs don't map to SRC_URI entries even if they in theory could. CVEs don't map the exact source file checksums. Multiple versions of a source file can be mapped to be affected by a CVE they contain the same bug, which is usually encoded in CVEs as SW component name and upstream release version range. The SRC_URI entry SW component name and version are not
added in this patch, and the CVE metadata about ignored and patched CVEs are not exported, so I don't see any links to CVEs.

Actually the commit message could be improved in this respect. Being able to get upstream download locations (especially with recipes mixing multiple upstream sources, and with gitsm and npmsw fetchers) is a pre-condition to identify the relevant components and therefore do CVE checks, but CVE checks as such are not covered by the patch. I may clarify that.

Quoted 6 lines

For example, a possible improvement in this respect could be to calculate not
only download locations (SPDX), but also purls
(https://github.com/package-url/purl-spec),
which may be used to do CVE checks against commercial or, even better, open databases (such as VulnerableCode https://www.nexb.com/vulnerablecode/).

Actually, I think it would serve yocto better to improve the yocto side cve-checker.bbclass or language/module specific bbclasses to generate additional CVE_PRODUCT and CVE_VERSION variables for SRC_URI entries of embedded SW like npm modules or rust crates. Then for the embedded gitsm and other modules, additional CVE_PRODUCT and matching CVE_VERSION variables should be set, somehow, possibly with some automation.

Exporting the data to be used by other, possibly commercial tools, doesn't help the community, in my opinion. I've also seen how commercial solutions failed to fill the gaps, and (a backported) yocto cve-checker.bbclass helped to identify how grave they were.

Cheers,

-Mikko