From 8fcdf388e48192a198882021f225bfd1d2990da8 Mon Sep 17 00:00:00 2001 From: Eric Seidel Date: Tue, 1 Dec 2026 16:44:34 -0800 Subject: [PATCH 1/4] feat(shorebird): build-time CycloneDX SBOMs for engine artifacts built into apps Adds shorebird/sbom (collect in each shard, emit once after), SBOM specs on the 14 artifacts built into apps in shorebird/ci, and a --package_licenses_path flag to licenses_cpp so SBOM components get SPDX ids from Flutter's own license scan. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/shorebird_engine_tests.yml | 9 +- .github/workflows/shorebird_sbom.yml | 48 ++ .../tools/licenses_cpp/src/license_checker.cc | 64 +- .../tools/licenses_cpp/src/license_checker.h | 4 + .../src/license_checker_unittests.cc | 37 + .../flutter/tools/licenses_cpp/src/main.cc | 17 + shorebird/ci/compose.json | 4 +- shorebird/ci/shards/linux.json | 103 ++- shorebird/ci/shards/macos.json | 53 +- shorebird/ci/shards/windows.json | 52 +- shorebird/sbom/README.md | 30 + shorebird/sbom/sbom.py | 649 ++++++++++++++++++ shorebird/sbom/sbom_test.py | 358 ++++++++++ shorebird/sbom/spdx_ids.json | 48 ++ 14 files changed, 1455 insertions(+), 21 deletions(-) create mode 100644 .github/workflows/shorebird_sbom.yml create mode 100644 shorebird/sbom/README.md create mode 100644 shorebird/sbom/sbom.py create mode 100644 shorebird/sbom/sbom_test.py create mode 100644 shorebird/sbom/spdx_ids.json diff --git a/.github/workflows/shorebird_engine_tests.yml b/.github/workflows/shorebird_engine_tests.yml index fcd0c03805ca0..bdd56cb1762ff 100644 --- a/.github/workflows/shorebird_engine_tests.yml +++ b/.github/workflows/shorebird_engine_tests.yml @@ -207,9 +207,10 @@ jobs: # shorebird_unittests covers shell/common/shorebird, runtime/shorebird # and the Rust updater. flutter_linux_sources adds the Linux embedder's # Shorebird code (fl_shorebird.cc, fl_engine.cc), and shell_unittests - # holds the Shell's Shorebird boot-flow tests. + # holds the Shell's Shorebird boot-flow tests. licenses_cpp_testrunner + # covers Shorebird's --package_licenses_path (shorebird/sbom). - name: 🔨 Build - run: ninja -C out/host_profile_unopt shorebird_unittests shell_unittests flutter/shell/platform/linux:flutter_linux_sources + run: ninja -C out/host_profile_unopt shorebird_unittests shell_unittests flutter/shell/platform/linux:flutter_linux_sources flutter/tools/licenses_cpp:licenses_cpp_testrunner working-directory: engine/src # From exe.unstripped/, where run_tests.py (the release's engine tests) @@ -220,6 +221,10 @@ jobs: run: ./out/host_profile_unopt/exe.unstripped/shorebird_unittests working-directory: engine/src + - name: 🧪 Run licenses_cpp tests + run: ./out/host_profile_unopt/licenses_cpp_testrunner + working-directory: engine/src + - name: 🧪 Run Shorebird shell_unittests run: ./out/host_profile_unopt/shell_unittests '--gtest_filter=*Shorebird*' working-directory: engine/src diff --git a/.github/workflows/shorebird_sbom.yml b/.github/workflows/shorebird_sbom.yml new file mode 100644 index 0000000000000..8660c1a786b2e --- /dev/null +++ b/.github/workflows/shorebird_sbom.yml @@ -0,0 +1,48 @@ +# Tests shorebird/sbom, which _build_engine runs to write the CycloneDX SBOMs +# published beside the engine artifacts built into apps. Also checks that the +# SBOM specs in shorebird/ci name real artifacts and that the matcher-to-SPDX +# table names real licenses_cpp matchers. +name: shorebird_sbom + +on: + pull_request: + paths: + - shorebird/sbom/** + - shorebird/ci/** + - engine/src/flutter/tools/licenses_cpp/data/licenses/** + - DEPS + - .github/workflows/shorebird_sbom.yml + push: + branches: + - shorebird/dev + paths: + - shorebird/sbom/** + - shorebird/ci/** + - engine/src/flutter/tools/licenses_cpp/data/licenses/** + - DEPS + - .github/workflows/shorebird_sbom.yml + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: 📚 Git Checkout + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + sparse-checkout: | + DEPS + shorebird + engine/src/flutter/tools/licenses_cpp/data + engine/src/flutter/shell/platform/android + engine/src/flutter/shell/platform/common/client_wrapper + engine/src/flutter/shell/platform/windows/client_wrapper + engine/src/flutter/lib/ui + engine/src/flutter/sky/packages/sky_engine + persist-credentials: false + + - name: 🧪 Test shorebird/sbom + run: python3 shorebird/sbom/sbom_test.py diff --git a/engine/src/flutter/tools/licenses_cpp/src/license_checker.cc b/engine/src/flutter/tools/licenses_cpp/src/license_checker.cc index b4fd8266ea321..5e799ebaaaf7c 100644 --- a/engine/src/flutter/tools/licenses_cpp/src/license_checker.cc +++ b/engine/src/flutter/tools/licenses_cpp/src/license_checker.cc @@ -17,6 +17,7 @@ #include "flutter/tools/licenses_cpp/src/filter.h" #include "flutter/tools/licenses_cpp/src/mmap_file.h" #include "third_party/abseil-cpp/absl/container/btree_map.h" +#include "third_party/abseil-cpp/absl/container/btree_set.h" #include "third_party/abseil-cpp/absl/container/flat_hash_set.h" #include "third_party/abseil-cpp/absl/log/log.h" #include "third_party/abseil-cpp/absl/log/vlog_is_on.h" @@ -205,9 +206,35 @@ Package GetPackage(const Data& data, return result; } +// Shorebird: writes `value` as a JSON string. +void WriteJsonString(std::ostream& out, std::string_view value) { + out << '"'; + for (char c : value) { + switch (c) { + case '"': + out << "\\\""; + break; + case '\\': + out << "\\\\"; + break; + case '\n': + out << "\\n"; + break; + default: + out << c; + } + } + out << '"'; +} + class LicenseMap { public: - void Add(std::string_view package, std::string_view license) { + void Add(std::string_view package, + std::string_view license, + std::string_view matcher = "") { + if (!matcher.empty()) { + package_matchers_[std::string(package)].emplace(std::string(matcher)); + } auto package_emplace_result = map_.try_emplace(license, absl::flat_hash_set()); absl::flat_hash_set& comment_set = @@ -225,8 +252,29 @@ class LicenseMap { } } + // Shorebird: {"": ["", ...], ...}, sorted. + void WritePackageLicenses(std::ostream& out) { + out << "{"; + bool first_package = true; + for (const auto& [package, matchers] : package_matchers_) { + out << (first_package ? "\n " : ",\n "); + first_package = false; + WriteJsonString(out, package); + out << ": ["; + bool first_matcher = true; + for (const std::string& matcher : matchers) { + out << (first_matcher ? "" : ", "); + first_matcher = false; + WriteJsonString(out, matcher); + } + out << "]"; + } + out << "\n}\n"; + } + private: absl::btree_map> map_; + absl::btree_map> package_matchers_; absl::flat_hash_set license_files_; }; @@ -255,7 +303,8 @@ absl::Status MatchLicenseFile(const fs::path& path, if (matches.ok()) { for (const Catalog::Match& match : matches.value()) { - license_map->Add(package.name, match.GetMatchedText()); + license_map->Add(package.name, match.GetMatchedText(), + match.GetMatcher()); VLOG(1) << "OK: " << path << " : " << match.GetMatcher(); } } else { @@ -300,7 +349,8 @@ bool ProcessSourceCode(const fs::path& relative_path, if (matches.ok()) { did_find_copyright = true; for (const Catalog::Match& match : matches.value()) { - license_map->Add(package.name, match.GetMatchedText()); + license_map->Add(package.name, match.GetMatchedText(), + match.GetMatcher()); VLOG(1) << "OK: " << relative_path.lexically_normal() << " : " << match.GetMatcher(); } @@ -379,7 +429,7 @@ bool ProcessNotices(const fs::path& relative_path, if (matches.ok()) { for (const Catalog::Match& match : matches.value()) { for (std::string_view project : projects) { - license_map->Add(project, match.GetMatchedText()); + license_map->Add(project, match.GetMatchedText(), match.GetMatcher()); } VLOG(1) << "OK: " << relative_path.lexically_normal() << " : " << match.GetMatcher(); @@ -593,6 +643,9 @@ std::vector LicenseChecker::Run( } state.license_map.Write(licenses); + if (flags.package_licenses != nullptr) { + state.license_map.WritePackageLicenses(*flags.package_licenses); + } if (!VLOG_IS_ON(1) && IsStdoutTerminal()) { PrintProgress(count++, git_repos.size()); std::cout << std::endl; @@ -650,6 +703,9 @@ int LicenseChecker::FileRun(std::string_view working_dir, } state.license_map.Write(licenses); + if (flags.package_licenses != nullptr) { + state.license_map.WritePackageLicenses(*flags.package_licenses); + } for (const absl::Status& status : state.errors) { std::cerr << status << "\n"; } diff --git a/engine/src/flutter/tools/licenses_cpp/src/license_checker.h b/engine/src/flutter/tools/licenses_cpp/src/license_checker.h index ef7637bd465b7..b47b2774ffe52 100644 --- a/engine/src/flutter/tools/licenses_cpp/src/license_checker.h +++ b/engine/src/flutter/tools/licenses_cpp/src/license_checker.h @@ -16,6 +16,10 @@ class LicenseChecker { struct Flags { bool treat_unmatched_comments_as_errors = false; std::optional root_package_name; + // Shorebird: when set, also writes a JSON object mapping each package to + // the names of the catalog matchers that matched its licenses. Read by + // shorebird/sbom to give SBOM components SPDX ids. + std::ostream* package_licenses = nullptr; }; static const char* kHeaderLicenseRegex; diff --git a/engine/src/flutter/tools/licenses_cpp/src/license_checker_unittests.cc b/engine/src/flutter/tools/licenses_cpp/src/license_checker_unittests.cc index bf947c674a2ff..1a9a25332338f 100644 --- a/engine/src/flutter/tools/licenses_cpp/src/license_checker_unittests.cc +++ b/engine/src/flutter/tools/licenses_cpp/src/license_checker_unittests.cc @@ -1005,3 +1005,40 @@ TEST_F(LicenseCheckerTest, OverrideRootPackageName) { Copyright Test )output"); } + +// Shorebird: --package_licenses_path, read by shorebird/sbom. +TEST_F(LicenseCheckerTest, WritesPackageLicenses) { + absl::StatusOr temp_path = MakeTempDir(); + ASSERT_TRUE(temp_path.ok()); + + absl::StatusOr data = MakeTestData(); + ASSERT_TRUE(data.ok()); + + fs::current_path(*temp_path); + ASSERT_EQ(std::system("mkdir -p third_party/foobar"), 0); + ASSERT_TRUE(WriteFile(kHeader, *temp_path / "main.cc").ok()); + ASSERT_TRUE( + WriteFile(kHeader, *temp_path / "third_party" / "foobar" / "foo.cc") + .ok()); + ASSERT_TRUE( + WriteFile(kLicense, *temp_path / "third_party" / "foobar" / "LICENSE") + .ok()); + Repo repo; + repo.Add("main.cc"); + repo.Add("third_party/foobar/foo.cc"); + repo.Add("third_party/foobar/LICENSE"); + ASSERT_TRUE(repo.Commit().ok()); + + std::stringstream package_licenses; + LicenseChecker::Flags flags = {.package_licenses = &package_licenses}; + std::stringstream ss; + std::vector errors = + LicenseChecker::Run(temp_path->string(), ss, *data, flags); + EXPECT_EQ(errors.size(), 0u); + + EXPECT_EQ(package_licenses.str(), R"output({ + "engine": ["header"], + "foobar": ["header", "test"] +} +)output"); +} diff --git a/engine/src/flutter/tools/licenses_cpp/src/main.cc b/engine/src/flutter/tools/licenses_cpp/src/main.cc index 092dc770d3ba9..b8ce97ae89c1a 100644 --- a/engine/src/flutter/tools/licenses_cpp/src/main.cc +++ b/engine/src/flutter/tools/licenses_cpp/src/main.cc @@ -41,6 +41,11 @@ ABSL_FLAG(std::optional, root_package, std::nullopt, "Name of the root package."); +ABSL_FLAG(std::optional, + package_licenses_path, + std::nullopt, + "Shorebird: path to write each package's matched license names to, " + "as JSON."); namespace { int Run(std::string_view working_dir, @@ -103,6 +108,18 @@ int main(int argc, char** argv) { flags.treat_unmatched_comments_as_errors = absl::GetFlag(FLAGS_treat_unmatched_comments_as_errors); flags.root_package_name = absl::GetFlag(FLAGS_root_package); + std::ofstream package_licenses; + std::optional package_licenses_path = + absl::GetFlag(FLAGS_package_licenses_path); + if (package_licenses_path.has_value()) { + package_licenses.open(package_licenses_path.value()); + if (!package_licenses.good()) { + std::cerr << "Unable to write to '" << package_licenses_path.value() + << "'."; + return 1; + } + flags.package_licenses = &package_licenses; + } if (input.has_value()) { if (include_filter.has_value()) { std::cerr << "`--input_filter` not supported with `--input`" diff --git a/shorebird/ci/compose.json b/shorebird/ci/compose.json index b48735ce97435..9dda358bee2f5 100644 --- a/shorebird/ci/compose.json +++ b/shorebird/ci/compose.json @@ -9,7 +9,7 @@ "--simulator-arm64-out-dir": "ci/ios_debug_sim_arm64" }, "artifacts": [ - {"src": "artifacts.zip", "dst": "flutter_infra_release/flutter/$engine/ios-release/artifacts.zip"}, + {"src": "artifacts.zip", "dst": "flutter_infra_release/flutter/$engine/ios-release/artifacts.zip", "sbom": ["ios-release"]}, {"src": "Flutter.framework.dSYM.zip", "dst": "flutter_infra_release/flutter/$engine/ios-release/Flutter.framework.dSYM.zip"} ] }, @@ -22,7 +22,7 @@ "--x64-out-dir": "ci/host_release" }, "artifacts": [ - {"src": "framework.zip", "dst": "flutter_infra_release/flutter/$engine/darwin-x64-release/framework.zip"}, + {"src": "framework.zip", "dst": "flutter_infra_release/flutter/$engine/darwin-x64-release/framework.zip", "sbom": ["macos-arm64-release", "macos-x64-release"]}, {"src": "FlutterMacOS.framework.dSYM.zip", "dst": "flutter_infra_release/flutter/$engine/darwin-x64/FlutterMacOS.framework.dSYM.zip"} ] }, diff --git a/shorebird/ci/shards/linux.json b/shorebird/ci/shards/linux.json index ea549fd349f4b..d36c01473de20 100644 --- a/shorebird/ci/shards/linux.json +++ b/shorebird/ci/shards/linux.json @@ -32,12 +32,25 @@ }, {"type": "verify_exported"} ], + "sbom": [ + { + "id": "android-arm64-release", + "builds": [ + { + "out_dir": "ci/android_release_arm64", + "roots": [ + "//flutter/shell/platform/android:flutter_shell_native" + ] + } + ] + } + ], "artifacts": [ {"src": "ci/android_release_arm64/zip_archives/android-arm64-release/artifacts.zip", "dst": "flutter_infra_release/flutter/$engine/android-arm64-release/artifacts.zip"}, {"src": "ci/android_release_arm64/zip_archives/android-arm64-release/linux-x64.zip", "dst": "flutter_infra_release/flutter/$engine/android-arm64-release/linux-x64.zip"}, {"src": "ci/android_release_arm64/zip_archives/android-arm64-release/symbols.zip", "dst": "flutter_infra_release/flutter/$engine/android-arm64-release/symbols.zip"}, {"src": "ci/android_release_arm64/arm64_v8a_release.pom", "dst": "download.flutter.io/io/flutter/arm64_v8a_release/1.0.0-$engine/arm64_v8a_release-1.0.0-$engine.pom"}, - {"src": "ci/android_release_arm64/arm64_v8a_release.jar", "dst": "download.flutter.io/io/flutter/arm64_v8a_release/1.0.0-$engine/arm64_v8a_release-1.0.0-$engine.jar"}, + {"src": "ci/android_release_arm64/arm64_v8a_release.jar", "dst": "download.flutter.io/io/flutter/arm64_v8a_release/1.0.0-$engine/arm64_v8a_release-1.0.0-$engine.jar", "sbom": ["android-arm64-release"]}, {"src": "ci/android_release_arm64/arm64_v8a_release.maven-metadata.xml", "dst": "download.flutter.io/io/flutter/arm64_v8a_release/1.0.0-$engine/arm64_v8a_release-1.0.0-$engine.maven-metadata.xml"}, {"src": "ci/android_debug_arm64/zip_archives/android-arm64/artifacts.zip", "dst": "flutter_infra_release/flutter/$engine/android-arm64/artifacts.zip"}, {"src": "ci/android_debug_arm64/zip_archives/android-arm64/symbols.zip", "dst": "flutter_infra_release/flutter/$engine/android-arm64/symbols.zip"}, @@ -81,15 +94,41 @@ }, {"type": "verify_exported"} ], + "sbom": [ + { + "id": "android-arm-release", + "builds": [ + { + "out_dir": "ci/android_release", + "roots": [ + "//flutter/shell/platform/android:flutter_shell_native" + ] + } + ] + }, + { + "id": "android-embedding-release", + "paths": [ + "flutter/shell/platform/android" + ] + }, + { + "id": "sky-engine", + "paths": [ + "flutter/lib/ui", + "flutter/sky/packages/sky_engine" + ] + } + ], "artifacts": [ {"src": "ci/android_release/zip_archives/android-arm-release/artifacts.zip", "dst": "flutter_infra_release/flutter/$engine/android-arm-release/artifacts.zip"}, {"src": "ci/android_release/zip_archives/android-arm-release/linux-x64.zip", "dst": "flutter_infra_release/flutter/$engine/android-arm-release/linux-x64.zip"}, {"src": "ci/android_release/zip_archives/android-arm-release/symbols.zip", "dst": "flutter_infra_release/flutter/$engine/android-arm-release/symbols.zip"}, {"src": "ci/android_release/armeabi_v7a_release.pom", "dst": "download.flutter.io/io/flutter/armeabi_v7a_release/1.0.0-$engine/armeabi_v7a_release-1.0.0-$engine.pom"}, - {"src": "ci/android_release/armeabi_v7a_release.jar", "dst": "download.flutter.io/io/flutter/armeabi_v7a_release/1.0.0-$engine/armeabi_v7a_release-1.0.0-$engine.jar"}, + {"src": "ci/android_release/armeabi_v7a_release.jar", "dst": "download.flutter.io/io/flutter/armeabi_v7a_release/1.0.0-$engine/armeabi_v7a_release-1.0.0-$engine.jar", "sbom": ["android-arm-release"]}, {"src": "ci/android_release/armeabi_v7a_release.maven-metadata.xml", "dst": "download.flutter.io/io/flutter/armeabi_v7a_release/1.0.0-$engine/armeabi_v7a_release-1.0.0-$engine.maven-metadata.xml"}, {"src": "ci/android_release/flutter_embedding_release.pom", "dst": "download.flutter.io/io/flutter/flutter_embedding_release/1.0.0-$engine/flutter_embedding_release-1.0.0-$engine.pom"}, - {"src": "ci/android_release/flutter_embedding_release.jar", "dst": "download.flutter.io/io/flutter/flutter_embedding_release/1.0.0-$engine/flutter_embedding_release-1.0.0-$engine.jar"}, + {"src": "ci/android_release/flutter_embedding_release.jar", "dst": "download.flutter.io/io/flutter/flutter_embedding_release/1.0.0-$engine/flutter_embedding_release-1.0.0-$engine.jar", "sbom": ["android-embedding-release"]}, {"src": "ci/android_release/flutter_embedding_release.maven-metadata.xml", "dst": "download.flutter.io/io/flutter/flutter_embedding_release/1.0.0-$engine/flutter_embedding_release-1.0.0-$engine.maven-metadata.xml"}, {"src": "ci/android_debug/zip_archives/android-arm/artifacts.zip", "dst": "flutter_infra_release/flutter/$engine/android-arm/artifacts.zip"}, {"src": "ci/android_debug/zip_archives/android-arm/symbols.zip", "dst": "flutter_infra_release/flutter/$engine/android-arm/symbols.zip"}, @@ -108,7 +147,7 @@ {"src": "ci/android_profile/flutter_embedding_profile.pom", "dst": "download.flutter.io/io/flutter/flutter_embedding_profile/1.0.0-$engine/flutter_embedding_profile-1.0.0-$engine.pom"}, {"src": "ci/android_profile/flutter_embedding_profile.jar", "dst": "download.flutter.io/io/flutter/flutter_embedding_profile/1.0.0-$engine/flutter_embedding_profile-1.0.0-$engine.jar"}, {"src": "ci/android_profile/flutter_embedding_profile.maven-metadata.xml", "dst": "download.flutter.io/io/flutter/flutter_embedding_profile/1.0.0-$engine/flutter_embedding_profile-1.0.0-$engine.maven-metadata.xml"}, - {"src": "ci/android_debug/zip_archives/sky_engine.zip", "dst": "flutter_infra_release/flutter/$engine/sky_engine.zip"}, + {"src": "ci/android_debug/zip_archives/sky_engine.zip", "dst": "flutter_infra_release/flutter/$engine/sky_engine.zip", "sbom": ["sky-engine"]}, {"src": "ci/android_debug/zip_archives/flutter_gpu.zip", "dst": "flutter_infra_release/flutter/$engine/flutter_gpu.zip"} ] }, @@ -141,12 +180,25 @@ }, {"type": "verify_exported"} ], + "sbom": [ + { + "id": "android-x64-release", + "builds": [ + { + "out_dir": "ci/android_release_x64", + "roots": [ + "//flutter/shell/platform/android:flutter_shell_native" + ] + } + ] + } + ], "artifacts": [ {"src": "ci/android_release_x64/zip_archives/android-x64-release/artifacts.zip", "dst": "flutter_infra_release/flutter/$engine/android-x64-release/artifacts.zip"}, {"src": "ci/android_release_x64/zip_archives/android-x64-release/linux-x64.zip", "dst": "flutter_infra_release/flutter/$engine/android-x64-release/linux-x64.zip"}, {"src": "ci/android_release_x64/zip_archives/android-x64-release/symbols.zip", "dst": "flutter_infra_release/flutter/$engine/android-x64-release/symbols.zip"}, {"src": "ci/android_release_x64/x86_64_release.pom", "dst": "download.flutter.io/io/flutter/x86_64_release/1.0.0-$engine/x86_64_release-1.0.0-$engine.pom"}, - {"src": "ci/android_release_x64/x86_64_release.jar", "dst": "download.flutter.io/io/flutter/x86_64_release/1.0.0-$engine/x86_64_release-1.0.0-$engine.jar"}, + {"src": "ci/android_release_x64/x86_64_release.jar", "dst": "download.flutter.io/io/flutter/x86_64_release/1.0.0-$engine/x86_64_release-1.0.0-$engine.jar", "sbom": ["android-x64-release"]}, {"src": "ci/android_release_x64/x86_64_release.maven-metadata.xml", "dst": "download.flutter.io/io/flutter/x86_64_release/1.0.0-$engine/x86_64_release-1.0.0-$engine.maven-metadata.xml"}, {"src": "ci/android_debug_x64/zip_archives/android-x64/artifacts.zip", "dst": "flutter_infra_release/flutter/$engine/android-x64/artifacts.zip"}, {"src": "ci/android_debug_x64/zip_archives/android-x64/symbols.zip", "dst": "flutter_infra_release/flutter/$engine/android-x64/symbols.zip"}, @@ -188,10 +240,19 @@ "command": "mkdir -p out/ci/host_release/aot_tools && out/ci/host_release/dart-sdk/bin/dart pub get --offline --directory=flutter/third_party/dart/pkg/aot_tools && out/ci/host_release/dart-sdk/bin/dart compile kernel flutter/third_party/dart/pkg/aot_tools/bin/aot_tools.dart -o out/ci/host_release/aot_tools/aot-tools.dill" } ], + "sbom": [ + { + "id": "flutter-patched-sdk-product", + "paths": [ + "flutter/third_party/dart/sdk/lib", + "flutter/lib/ui" + ] + } + ], "artifacts": [ {"src": "ci/host_release/dart-sdk", "dst": "flutter_infra_release/flutter/$engine/dart-sdk-linux-x64.zip", "zip": true, "content_hash": true}, {"src": "ci/host_release/zip_archives/linux-x64/font-subset.zip", "dst": "flutter_infra_release/flutter/$engine/linux-x64/font-subset.zip"}, - {"src": "ci/host_release/zip_archives/flutter_patched_sdk_product.zip", "dst": "flutter_infra_release/flutter/$engine/flutter_patched_sdk_product.zip"}, + {"src": "ci/host_release/zip_archives/flutter_patched_sdk_product.zip", "dst": "flutter_infra_release/flutter/$engine/flutter_patched_sdk_product.zip", "sbom": ["flutter-patched-sdk-product"]}, {"src": "ci/host_debug/zip_archives/linux-x64/artifacts.zip", "dst": "flutter_infra_release/flutter/$engine/linux-x64/artifacts.zip"}, {"src": "ci/host_debug/zip_archives/flutter_patched_sdk.zip", "dst": "flutter_infra_release/flutter/$engine/flutter_patched_sdk.zip"}, {"src": "ci/host_release/aot_tools/aot-tools.dill", "dst": "shorebird/$engine/aot-tools.dill"} @@ -216,8 +277,21 @@ "builds": ["linux_host_desktop_engine/ci/host_profile_desktop"] } ], + "sbom": [ + { + "id": "linux-x64-release", + "builds": [ + { + "out_dir": "ci/host_release_desktop", + "roots": [ + "//flutter/shell/platform/linux:flutter_linux_gtk" + ] + } + ] + } + ], "artifacts": [ - {"src": "ci/host_release_desktop/zip_archives/linux-x64-release/linux-x64-flutter-gtk.zip", "dst": "flutter_infra_release/flutter/$engine/linux-x64-release/linux-x64-flutter-gtk.zip"}, + {"src": "ci/host_release_desktop/zip_archives/linux-x64-release/linux-x64-flutter-gtk.zip", "dst": "flutter_infra_release/flutter/$engine/linux-x64-release/linux-x64-flutter-gtk.zip", "sbom": ["linux-x64-release"]}, {"src": "ci/host_debug_desktop/zip_archives/linux-x64-debug/linux-x64-flutter-gtk.zip", "dst": "flutter_infra_release/flutter/$engine/linux-x64-debug/linux-x64-flutter-gtk.zip"}, {"src": "ci/host_profile_desktop/zip_archives/linux-x64-profile/linux-x64-flutter-gtk.zip", "dst": "flutter_infra_release/flutter/$engine/linux-x64-profile/linux-x64-flutter-gtk.zip"} ] @@ -279,8 +353,21 @@ "out_dir": "linux_release_arm64" } ], + "sbom": [ + { + "id": "linux-arm64-release", + "builds": [ + { + "out_dir": "linux_release_arm64", + "roots": [ + "//flutter/shell/platform/linux:flutter_linux_gtk" + ] + } + ] + } + ], "artifacts": [ - {"src": "linux_release_arm64/zip_archives/linux-arm64-release/linux-arm64-flutter-gtk.zip", "dst": "flutter_infra_release/flutter/$engine/linux-arm64-release/linux-arm64-flutter-gtk.zip"} + {"src": "linux_release_arm64/zip_archives/linux-arm64-release/linux-arm64-flutter-gtk.zip", "dst": "flutter_infra_release/flutter/$engine/linux-arm64-release/linux-arm64-flutter-gtk.zip", "sbom": ["linux-arm64-release"]} ] } } diff --git a/shorebird/ci/shards/macos.json b/shorebird/ci/shards/macos.json index f2ea277139ad7..5d40353b60b22 100644 --- a/shorebird/ci/shards/macos.json +++ b/shorebird/ci/shards/macos.json @@ -117,7 +117,32 @@ } } ], - "compose_input": "ios-framework" + "compose_input": "ios-framework", + "sbom": [ + { + "id": "ios-release", + "builds": [ + { + "out_dir": "ci/ios_release", + "roots": [ + "//flutter/shell/platform/darwin/ios:create_flutter_framework_dylib" + ] + }, + { + "out_dir": "ci/ios_debug_sim", + "roots": [ + "//flutter/shell/platform/darwin/ios:create_flutter_framework_dylib" + ] + }, + { + "out_dir": "ci/ios_debug_sim_arm64", + "roots": [ + "//flutter/shell/platform/darwin/ios:create_flutter_framework_dylib" + ] + } + ] + } + ] }, "ios-debug": { "steps": [ @@ -153,6 +178,19 @@ } ], "compose_input": "macos-framework", + "sbom": [ + { + "id": "macos-arm64-release", + "builds": [ + { + "out_dir": "ci/mac_release_arm64", + "roots": [ + "//flutter/shell/platform/darwin/macos:flutter_framework_dylib" + ] + } + ] + } + ], "artifacts": [ {"src": "host_release_arm64/dart-sdk", "dst": "flutter_infra_release/flutter/$engine/dart-sdk-darwin-arm64.zip", "zip": true, "content_hash": true}, {"src": "ci/mac_release_arm64/zip_archives/darwin-arm64-release/artifacts.zip", "dst": "flutter_infra_release/flutter/$engine/darwin-x64-release/artifacts.zip"}, @@ -182,6 +220,19 @@ } ], "compose_input": "macos-framework", + "sbom": [ + { + "id": "macos-x64-release", + "builds": [ + { + "out_dir": "ci/host_release", + "roots": [ + "//flutter/shell/platform/darwin/macos:flutter_framework_dylib" + ] + } + ] + } + ], "artifacts": [ {"src": "host_release/dart-sdk", "dst": "flutter_infra_release/flutter/$engine/dart-sdk-darwin-x64.zip", "zip": true, "content_hash": true}, {"src": "ci/host_release/zip_archives/darwin-x64/font-subset.zip", "dst": "flutter_infra_release/flutter/$engine/darwin-x64/font-subset.zip"}, diff --git a/shorebird/ci/shards/windows.json b/shorebird/ci/shards/windows.json index d2687362b6722..0412bef5fb901 100644 --- a/shorebird/ci/shards/windows.json +++ b/shorebird/ci/shards/windows.json @@ -58,10 +58,23 @@ } } ], + "sbom": [ + { + "id": "windows-x64-release", + "builds": [ + { + "out_dir": "ci/host_release", + "roots": [ + "//flutter/shell/platform/windows:flutter_windows" + ] + } + ] + } + ], "artifacts": [ {"src": "ci/host_release/dart-sdk", "dst": "flutter_infra_release/flutter/$engine/dart-sdk-windows-x64.zip", "zip": true, "content_hash": true}, {"src": "ci/host_release/zip_archives/windows-x64/font-subset.zip", "dst": "flutter_infra_release/flutter/$engine/windows-x64/font-subset.zip"}, - {"src": "ci/host_release/zip_archives/windows-x64-release/windows-x64-flutter.zip", "dst": "flutter_infra_release/flutter/$engine/windows-x64-release/windows-x64-flutter.zip"} + {"src": "ci/host_release/zip_archives/windows-x64-release/windows-x64-flutter.zip", "dst": "flutter_infra_release/flutter/$engine/windows-x64-release/windows-x64-flutter.zip", "sbom": ["windows-x64-release"]} ] }, "host-debug": { @@ -75,10 +88,19 @@ } } ], + "sbom": [ + { + "id": "windows-x64-cpp-client-wrapper", + "paths": [ + "flutter/shell/platform/windows/client_wrapper", + "flutter/shell/platform/common/client_wrapper" + ] + } + ], "artifacts": [ {"src": "ci/host_debug/zip_archives/windows-x64/artifacts.zip", "dst": "flutter_infra_release/flutter/$engine/windows-x64/artifacts.zip"}, {"src": "ci/host_debug/zip_archives/windows-x64-debug/windows-x64-flutter.zip", "dst": "flutter_infra_release/flutter/$engine/windows-x64-debug/windows-x64-flutter.zip"}, - {"src": "ci/host_debug/zip_archives/windows-x64/flutter-cpp-client-wrapper.zip", "dst": "flutter_infra_release/flutter/$engine/windows-x64/flutter-cpp-client-wrapper.zip"} + {"src": "ci/host_debug/zip_archives/windows-x64/flutter-cpp-client-wrapper.zip", "dst": "flutter_infra_release/flutter/$engine/windows-x64/flutter-cpp-client-wrapper.zip", "sbom": ["windows-x64-cpp-client-wrapper"]} ] }, "host-profile": { @@ -104,12 +126,21 @@ } } ], + "sbom": [ + { + "id": "windows-arm64-cpp-client-wrapper", + "paths": [ + "flutter/shell/platform/windows/client_wrapper", + "flutter/shell/platform/common/client_wrapper" + ] + } + ], "artifacts": [ {"src": "ci/host_debug_arm64/dart-sdk", "dst": "flutter_infra_release/flutter/$engine/dart-sdk-windows-arm64.zip", "zip": true}, {"src": "ci/host_debug_arm64/zip_archives/windows-arm64/artifacts.zip", "dst": "flutter_infra_release/flutter/$engine/windows-arm64/artifacts.zip"}, {"src": "ci/host_debug_arm64/zip_archives/windows-arm64/font-subset.zip", "dst": "flutter_infra_release/flutter/$engine/windows-arm64/font-subset.zip"}, {"src": "ci/host_debug_arm64/zip_archives/windows-arm64-debug/windows-arm64-flutter.zip", "dst": "flutter_infra_release/flutter/$engine/windows-arm64-debug/windows-arm64-flutter.zip"}, - {"src": "ci/host_debug_arm64/zip_archives/windows-arm64/flutter-cpp-client-wrapper.zip", "dst": "flutter_infra_release/flutter/$engine/windows-arm64/flutter-cpp-client-wrapper.zip"} + {"src": "ci/host_debug_arm64/zip_archives/windows-arm64/flutter-cpp-client-wrapper.zip", "dst": "flutter_infra_release/flutter/$engine/windows-arm64/flutter-cpp-client-wrapper.zip", "sbom": ["windows-arm64-cpp-client-wrapper"]} ] }, "host-arm64-profile": { @@ -130,8 +161,21 @@ "builds": ["windows_arm_host_engine/ci\\host_release_arm64"] } ], + "sbom": [ + { + "id": "windows-arm64-release", + "builds": [ + { + "out_dir": "ci/host_release_arm64", + "roots": [ + "//flutter/shell/platform/windows:flutter_windows" + ] + } + ] + } + ], "artifacts": [ - {"src": "ci/host_release_arm64/zip_archives/windows-arm64-release/windows-arm64-flutter.zip", "dst": "flutter_infra_release/flutter/$engine/windows-arm64-release/windows-arm64-flutter.zip"} + {"src": "ci/host_release_arm64/zip_archives/windows-arm64-release/windows-arm64-flutter.zip", "dst": "flutter_infra_release/flutter/$engine/windows-arm64-release/windows-arm64-flutter.zip", "sbom": ["windows-arm64-release"]} ] } } diff --git a/shorebird/sbom/README.md b/shorebird/sbom/README.md new file mode 100644 index 0000000000000..061969f5c6b02 --- /dev/null +++ b/shorebird/sbom/README.md @@ -0,0 +1,30 @@ +# shorebird/sbom + +Writes CycloneDX 1.6 SBOMs for the engine artifacts built into customers' +apps, published beside each artifact on download.shorebird.dev as +`.cdx.json`, plus one per engine at +`shorebird//sbom.cdx.json`. +Design: https://app.notion.com/p/429f369b53c981a78406cd9519986389 + +- **What gets an SBOM:** each artifact entry in `shorebird/ci/shards/*.json` + and `compose.json` with an `sbom` list. The list names the specs it's built + from (the macOS framework is two: arm64 and x64). +- **Specs:** a shard's `sbom` list. Each spec has `builds` (an out dir and the + GN targets linked into the artifact) or `paths` (source directories, for + artifacts that are source, such as `sky_engine.zip`). +- **`sbom.py collect --shard /`** runs in the shard after + ninja. It walks `gn gen --ide=json`'s graph from each root and follows only + linked targets in the target toolchain, so build tools stay out. It names + packages the way `licenses_cpp` does (the directory after `third_party/`), + maps each file to its DEPS checkout, and lists the Rust updater's crates + with `cargo tree`. +- **`sbom.py emit`** runs once after all shards. It joins the collected files + with DEPS (url@rev, and upstream ancestry through `ci/scan_deps.py`) and + with `licenses_cpp --package_licenses_path` output. It then writes the + CycloneDX files. +- **Licenses:** `spdx_ids.json` maps `licenses_cpp` matcher names + (`tools/licenses_cpp/data/licenses/*`, first line) to SPDX ids. A matcher + missing from it becomes `LicenseRef-flutter-`; that's left out on + purpose where the matcher's license has no clear SPDX id. + +Test: `python3 shorebird/sbom/sbom_test.py`. diff --git a/shorebird/sbom/sbom.py b/shorebird/sbom/sbom.py new file mode 100644 index 0000000000000..5c1a2423b4abc --- /dev/null +++ b/shorebird/sbom/sbom.py @@ -0,0 +1,649 @@ +#!/usr/bin/env python3 +# Copyright 2026 Shorebird. All rights reserved. +"""Build-time CycloneDX SBOMs for the engine artifacts built into apps. + +Design: https://app.notion.com/p/429f369b53c981a78406cd9519986389 + +Two steps, run by _build_engine: + + collect In a shard, after ninja. For each SBOM spec the shard declares + (`sbom` in shorebird/ci/shards/*.json), walks GN's target graph + (`gn gen --ide=json`) from the spec's roots through what gets + linked, maps every source file to its package (named the way + licenses_cpp names packages) and to the DEPS checkout it comes + from, and lists the Rust updater's crates (`cargo tree`). Writes + .json per spec. + + emit Once, after all shards. Joins the collected files with DEPS + (url@rev, upstream ancestry via ci/scan_deps.py) and licenses_cpp's + --package_licenses_path output, and writes .cdx.json beside + every artifact that names specs in its `sbom` field, plus one + release SBOM, shorebird//sbom.cdx.json. +""" + +import argparse +import glob +import json +import os +import re +import subprocess +import sys +import tempfile +import urllib.parse +import uuid + +SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) +REPO_ROOT = os.path.realpath(os.path.join(SCRIPT_DIR, '..', '..')) +CI_DIR = os.path.join(REPO_ROOT, 'shorebird', 'ci') +ENGINE_SRC_PREFIX = 'engine/src/' + +FORK_PURL = 'pkg:github/shorebirdtech/flutter' +DOWNLOAD_URL = 'https://download.shorebird.dev/' + +# Mirrors GetPackage in tools/licenses_cpp/src/license_checker.cc, run as +# ci/licenses_cpp.sh runs it: working dir engine/src, root package "flutter". +ROOT_PACKAGE = 'flutter' +THIRD_PARTY_IGNORE = ('pkg', 'vulkan-deps') + +# Only these are linked into (or bundled by) the target that depends on them. +# Actions and executables reached as deps are build tools: their outputs may +# be embedded (a snapshot, generated code), but their own deps aren't. +FOLLOWED_TYPES = { + 'group', + 'source_set', + 'static_library', + 'shared_library', + 'loadable_module', + 'rust_library', + 'bundle_data', + 'create_bundle', + 'copy', +} + +UPDATER_ACTION = '//flutter/shell/common/shorebird:build_rust_updater' +UPDATER_DEPS_PATH = 'engine/src/flutter/third_party/updater' + + +# --------------------------------------------------------------------------- +# DEPS + + +class _Var: + # gclient's built-in variables, as ci/scan_deps.py sets them. They name + # host-specific checkouts (prebuilts, toolchains), none of them git deps + # linked into an artifact. + _BUILTINS = {'host_os': 'linux', 'host_cpu': 'x64'} + + def __init__(self, scope): + self._scope = scope + + def __call__(self, name): + deps_vars = self._scope.get('vars', {}) + return deps_vars[name] if name in deps_vars else self._BUILTINS[name] + + +def read_deps(deps_file): + """Returns ({path: (url, rev)} for git deps under engine/src, vars).""" + scope = {} + with open(deps_file) as f: + content = f.read() + exec(content, {'Var': _Var(scope), 'deps_os': {}, 'Str': str}, scope) + git_deps = {} + for path, dep in scope.get('deps', {}).items(): + if isinstance(dep, dict): + if dep.get('dep_type', 'git') != 'git' or 'url' not in dep: + continue + dep = dep['url'] + if not isinstance(dep, str) or '@' not in dep or not path.startswith(ENGINE_SRC_PREFIX): + continue + url, rev = dep.rsplit('@', 1) + git_deps[path] = (url, rev) + return git_deps, scope.get('vars', {}) + + +def repo_for(path, deps_paths): + """The DEPS checkout holding `path` (relative to engine/src), or '' for the + fork itself.""" + full = ENGINE_SRC_PREFIX + path + best = '' + for dep_path in deps_paths: + if (full == dep_path or full.startswith(dep_path + '/')) and len(dep_path) > len(best): + best = dep_path + return best + + +# --------------------------------------------------------------------------- +# Packages + + +def package_of(path): + """(name, dir) of the package a file belongs to, relative to engine/src.""" + parts = path.split('/')[:-1] + name, pkg_dir = ROOT_PACKAGE, '' + after_third_party = False + after_ignored = False + for i, part in enumerate(parts): + if after_ignored: + after_ignored = False + name, pkg_dir = part, '/'.join(parts[:i + 1]) + elif after_third_party: + if part in THIRD_PARTY_IGNORE: + after_ignored = True + after_third_party = False + name, pkg_dir = part, '/'.join(parts[:i + 1]) + elif part == 'third_party': + after_third_party = True + return name, pkg_dir + + +def components_for_paths(paths, deps_paths): + """Distinct {package, repo, subpath} for source paths (relative to + engine/src).""" + seen = {} + for path in paths: + name, pkg_dir = package_of(path) + repo = repo_for(path, deps_paths) + repo_dir = repo[len(ENGINE_SRC_PREFIX):] if repo else '' + subpath = '' + if pkg_dir and pkg_dir != repo_dir: + if not repo_dir: + subpath = pkg_dir + elif pkg_dir.startswith(repo_dir + '/'): + subpath = pkg_dir[len(repo_dir) + 1:] + key = (name, repo, subpath) + seen[key] = {'package': name, 'repo': repo, 'subpath': subpath} + return [seen[k] for k in sorted(seen)] + + +# --------------------------------------------------------------------------- +# collect + + +def _toolchain(label): + m = re.search(r'\(([^)]*)\)$', label) + return m.group(1) if m else None + + +def _strip_toolchain(label): + return re.sub(r'\([^)]*\)$', '', label) + + +def walk_project(project, roots): + """Source paths (relative to the source root) of everything linked into + `roots`, and the updater action's args if it's reached.""" + settings = project.get('build_settings', {}) + default_toolchain = settings.get('default_toolchain') + build_dir = settings.get('build_dir', '//out/').rstrip('/') + '/' + targets = project['targets'] + + def find(label): + if label in targets: + return label + if _toolchain(label) == default_toolchain and _strip_toolchain(label) in targets: + return _strip_toolchain(label) + if _toolchain(label) is None and default_toolchain and ( + label + '(' + default_toolchain + ')') in targets: + return label + '(' + default_toolchain + ')' + return None + + def in_default_toolchain(label, target): + toolchain = target.get('toolchain') or _toolchain(label) + return toolchain is None or toolchain == default_toolchain + + paths = set() + updater_args = [] + stack = [] + for root in roots: + found = find(root) + if found is None: + raise SystemExit('sbom: root %s is not in project.json' % root) + stack.append(found) + root_labels = set(stack) + seen = set() + while stack: + label = stack.pop() + if label in seen: + continue + seen.add(label) + target = targets[label] + if _strip_toolchain(label) == UPDATER_ACTION: + updater_args.append(target.get('args', [])) + continue + if label not in root_labels and (target.get('type') not in FOLLOWED_TYPES or + not in_default_toolchain(label, target)): + continue + files = list(target.get('sources', [])) + public = target.get('public') + if isinstance(public, list): + files += public + for f in files: + if f.startswith('//') and not f.startswith(build_dir): + paths.add(f[2:]) + for dep in target.get('deps', []): + found = find(dep) + if found is not None: + stack.append(found) + return paths, updater_args + + +def parse_updater_args(args): + parsed = {} + for i in range(len(args) - 1): + if args[i] in ('--rust-target', '--manifest-dir'): + parsed[args[i]] = args[i + 1] + return parsed.get('--rust-target'), parsed.get('--manifest-dir') + + +def parse_cargo_tree(output): + """Crates from `cargo tree --prefix none --format '{p}|{l}'`.""" + crates = {} + for line in output.splitlines(): + line = line.replace(' (*)', '').strip() + if not line or '|' not in line: + continue + pkg, license_expr = line.split('|', 1) + pkg = pkg.strip() + fields = pkg.split(' ', 2) + if len(fields) < 2: + continue + name, version = fields[0], fields[1].lstrip('v') + source = fields[2].strip('()') if len(fields) > 2 else '' + if name == 'updater': + continue + crates[(name, version)] = { + 'name': name, + 'version': version, + 'license': license_expr.strip(), + 'registry': not source, + } + return [crates[k] for k in sorted(crates)] + + +def cargo_crates(manifest_dir, rust_target): + output = subprocess.check_output([ + 'cargo', + 'tree', + '--locked', + '--manifest-path', + os.path.join(manifest_dir, 'Cargo.toml'), + '-p', + 'updater', + '--target', + rust_target, + '-e', + 'normal,no-proc-macro', + '--prefix', + 'none', + '--format', + '{p}|{l}', + ], + text=True) + return parse_cargo_tree(output) + + +def shard_specs(shard): + platform, name = shard.split('/', 1) + with open(os.path.join(CI_DIR, 'shards', platform + '.json')) as f: + return json.load(f)[name].get('sbom', []) + + +def collect(args): + engine_src = os.path.abspath(args.engine_src) + deps_paths, _ = read_deps(os.path.join(engine_src, '..', '..', 'DEPS')) + gn = args.gn or os.path.join(engine_src, 'flutter', 'third_party', 'gn', 'gn') + os.makedirs(args.out, exist_ok=True) + for spec in shard_specs(args.shard): + paths = set(spec.get('paths', [])) + # Each path in `paths` names a directory: give it a file so package_of + # places the directory itself. + paths = {p.rstrip('/') + '/_' for p in paths} + rust_targets = set() + manifest_dirs = set() + for build in spec.get('builds', []): + out_dir = os.path.join(engine_src, 'out', build['out_dir']) + subprocess.check_call([gn, 'gen', out_dir, '--ide=json'], cwd=engine_src) + with open(os.path.join(out_dir, 'project.json')) as f: + project = json.load(f) + build_paths, updater_args = walk_project(project, build['roots']) + paths |= build_paths + for a in updater_args: + rust_target, manifest_dir = parse_updater_args(a) + if rust_target: + rust_targets.add(rust_target) + manifest_dirs.add(os.path.normpath(os.path.join(out_dir, manifest_dir))) + result = { + 'id': spec['id'], + 'components': components_for_paths(sorted(paths), deps_paths), + } + if rust_targets: + crates = {} + for manifest_dir in sorted(manifest_dirs): + for rust_target in sorted(rust_targets): + for crate in cargo_crates(manifest_dir, rust_target): + crates[(crate['name'], crate['version'])] = crate + result['updater'] = { + 'rust_targets': sorted(rust_targets), + 'crates': [crates[k] for k in sorted(crates)], + } + with open(os.path.join(args.out, spec['id'] + '.json'), 'w') as f: + json.dump(result, f, indent=2, sort_keys=True) + f.write('\n') + print('sbom: %s: %d components%s' % ( + spec['id'], len(result['components']), + ', %d crates' % len(result['updater']['crates']) if 'updater' in result else '')) + + +# --------------------------------------------------------------------------- +# emit + + +def purl_for(url, rev, subpath=''): + # GitHub repos, and googlesource mirrors of them (.../external/github.com/ + # /), which keep upstream's commits: scanners know GitHub purls. + m = re.match(r'^(?:https://|git@|ssh://git@)github\.com[:/]([^/]+)/([^/]+?)(?:\.git)?/?$', url) + if not m: + m = re.match(r'^https://[a-z]+\.googlesource\.com/external/github\.com/([^/]+)/([^/]+?)(?:\.git)?/?$', url) + if m: + purl = 'pkg:github/%s/%s@%s' % (m.group(1).lower(), m.group(2).lower(), rev) + else: + name = url.rstrip('/').split('/')[-1] + if name.endswith('.git'): + name = name[:-4] + vcs_url = urllib.parse.quote('git+%s@%s' % (url, rev), safe='/:') + purl = 'pkg:generic/%s@%s?vcs_url=%s' % (name.lower(), rev, vcs_url) + if subpath: + purl += '#' + subpath + return purl + + +def https_url(url): + m = re.match(r'^git@github\.com:(.+?)(?:\.git)?$', url) + if m: + return 'https://github.com/' + m.group(1) + return url + + +def load_spdx_ids(): + with open(os.path.join(SCRIPT_DIR, 'spdx_ids.json')) as f: + return json.load(f) + + +def license_expression(matchers, spdx_ids): + """SPDX expression for a package's licenses_cpp matchers, or None.""" + ids = [] + for matcher in matchers: + spdx = spdx_ids.get(matcher) + if spdx is None: + spdx = 'LicenseRef-flutter-' + re.sub(r'[^A-Za-z0-9.]+', '-', matcher).strip('-') + if ' ' in spdx: + spdx = '(' + spdx + ')' + if spdx not in ids: + ids.append(spdx) + return ' AND '.join(sorted(ids)) if ids else None + + +def resolve_upstreams(repos, git_deps, deps_vars): + """{repo: (upstream url, ancestor commit)} via ci/scan_deps.py.""" + sys.path.insert(0, os.path.join(REPO_ROOT, 'engine', 'src', 'flutter', 'ci')) + import scan_deps # pylint: disable=import-outside-toplevel + result = {} + with tempfile.TemporaryDirectory() as clone_dir: + scan_deps.DEP_CLONE_DIR = clone_dir + for repo in sorted(repos): + if repo not in git_deps: + continue + url, rev = git_deps[repo] + found = scan_deps.get_common_ancestor([url, rev], deps_vars) + if found: + commit, upstream = found + result[repo] = (upstream, commit) + return result + + +class Emitter: + + def __init__(self, engine, git_deps, package_licenses, spdx_ids, upstreams): + self.engine = engine + self.git_deps = git_deps + self.package_licenses = package_licenses + self.spdx_ids = spdx_ids + self.upstreams = upstreams + + def component(self, c): + repo = c['repo'] + if repo: + url, rev = self.git_deps[repo] + else: + url, rev = 'https://github.com/shorebirdtech/flutter', self.engine + purl = purl_for(url, rev, c['subpath']) + out = { + 'type': 'library', + 'bom-ref': purl, + 'name': c['package'], + 'version': rev, + 'purl': purl, + 'externalReferences': [{'type': 'vcs', 'url': https_url(url)}], + } + expression = license_expression(self.package_licenses.get(c['package'], []), self.spdx_ids) + if expression: + out['licenses'] = [{'expression': expression}] + if repo in self.upstreams: + upstream, commit = self.upstreams[repo] + ancestor = purl_for(upstream, commit, c['subpath']) + out['pedigree'] = { + 'ancestors': [{ + 'type': 'library', + 'bom-ref': 'ancestor:' + purl, + 'name': c['package'], + 'version': commit, + 'purl': ancestor, + }] + } + return out + + def crate(self, crate): + if crate['registry']: + purl = 'pkg:cargo/%s@%s' % (crate['name'], crate['version']) + else: + purl = 'pkg:generic/%s@%s' % (crate['name'], crate['version']) + out = { + 'type': 'library', + 'bom-ref': purl, + 'name': crate['name'], + 'version': crate['version'], + 'purl': purl, + } + if crate['license']: + out['licenses'] = [{'expression': crate['license']}] + return out + + def updater_component(self): + url, rev = self.git_deps.get(UPDATER_DEPS_PATH, + ('https://github.com/shorebirdtech/updater', 'unknown')) + purl = purl_for(url, rev) + return { + 'type': 'library', + 'bom-ref': purl, + 'name': 'updater', + 'version': rev, + 'purl': purl, + 'licenses': [{'expression': 'Apache-2.0 OR MIT'}], + 'externalReferences': [{'type': 'vcs', 'url': https_url(url)}], + } + + def contents(self, collected): + """(components by bom-ref, refs the artifact depends on, dependencies).""" + components = {} + direct = [] + dependencies = [] + for c in collected['components']: + comp = self.component(c) + components[comp['bom-ref']] = comp + direct.append(comp['bom-ref']) + if 'updater' in collected: + updater = self.updater_component() + components[updater['bom-ref']] = updater + direct.append(updater['bom-ref']) + crate_refs = [] + for crate in collected['updater']['crates']: + comp = self.crate(crate) + components[comp['bom-ref']] = comp + crate_refs.append(comp['bom-ref']) + dependencies.append({'ref': updater['bom-ref'], 'dependsOn': sorted(set(crate_refs))}) + return components, sorted(set(direct)), dependencies + + def bom(self, serial_key, subject, components, dependencies): + return { + 'bomFormat': 'CycloneDX', + 'specVersion': '1.6', + 'serialNumber': 'urn:uuid:' + str(uuid.uuid5(uuid.NAMESPACE_URL, serial_key)), + 'version': 1, + 'metadata': { + 'tools': { + 'components': [{ + 'type': 'application', + 'name': 'shorebird/sbom', + 'version': self.engine, + }] + }, + 'component': subject, + 'supplier': {'name': 'Shorebird', 'url': ['https://shorebird.dev']}, + }, + 'components': [components[k] for k in sorted(components)], + 'dependencies': _merge_dependencies(dependencies), + } + + def artifact_bom(self, dst, collected_list): + subject = self.artifact_subject(dst) + components, direct, dependencies = {}, [], [] + for collected in collected_list: + c, d, deps = self.contents(collected) + components.update(c) + direct += d + dependencies += deps + dependencies.append({'ref': subject['bom-ref'], 'dependsOn': sorted(set(direct))}) + return self.bom(DOWNLOAD_URL + dst, subject, components, dependencies) + + def artifact_subject(self, dst): + return { + 'type': 'library', + 'bom-ref': 'artifact:' + dst, + 'name': dst.split('/')[-1], + 'version': self.engine, + 'externalReferences': [{'type': 'distribution', 'url': DOWNLOAD_URL + dst}], + } + + def release_bom(self, artifact_boms): + subject = { + 'type': 'framework', + 'bom-ref': FORK_PURL + '@' + self.engine, + 'name': 'Shorebird Flutter engine', + 'version': self.engine, + 'purl': FORK_PURL + '@' + self.engine, + } + components, dependencies, artifacts = {}, [], [] + for bom in artifact_boms: + artifact = bom['metadata']['component'] + components[artifact['bom-ref']] = artifact + artifacts.append(artifact['bom-ref']) + for c in bom['components']: + components[c['bom-ref']] = c + dependencies += bom['dependencies'] + dependencies.append({'ref': subject['bom-ref'], 'dependsOn': sorted(artifacts)}) + return self.bom(DOWNLOAD_URL + 'shorebird/%s/sbom.cdx.json' % self.engine, subject, + components, dependencies) + + +def _merge_dependencies(dependencies): + merged = {} + for d in dependencies: + merged.setdefault(d['ref'], set()).update(d['dependsOn']) + return [{'ref': ref, 'dependsOn': sorted(merged[ref])} for ref in sorted(merged)] + + +def artifact_specs(): + """[(dst, [spec ids])] for every shard and compose artifact with `sbom`.""" + result = [] + for path in sorted(glob.glob(os.path.join(CI_DIR, 'shards', '*.json'))): + with open(path) as f: + for shard in json.load(f).values(): + for artifact in shard.get('artifacts', []): + if artifact.get('sbom'): + result.append((artifact['dst'], artifact['sbom'])) + with open(os.path.join(CI_DIR, 'compose.json')) as f: + for compose in json.load(f).values(): + for artifact in compose.get('artifacts', []): + if artifact.get('sbom'): + result.append((artifact['dst'], artifact['sbom'])) + return result + + +def write_json(path, data): + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, 'w') as f: + json.dump(data, f, indent=2, sort_keys=True) + f.write('\n') + + +def emit(args): + git_deps, deps_vars = read_deps(os.path.join(REPO_ROOT, 'DEPS')) + with open(args.package_licenses) as f: + package_licenses = json.load(f) + specs = artifact_specs() + collected = {} + for _, ids in specs: + for spec_id in ids: + if spec_id not in collected: + path = os.path.join(args.collected, spec_id + '.json') + if not os.path.exists(path): + raise SystemExit('sbom: no collected %s (expected %s)' % (spec_id, path)) + with open(path) as f: + collected[spec_id] = json.load(f) + repos = {c['repo'] for spec in collected.values() for c in spec['components'] if c['repo']} + upstreams = {} if args.no_upstream else resolve_upstreams(repos, git_deps, deps_vars) + emitter = Emitter(args.engine, git_deps, package_licenses, load_spdx_ids(), upstreams) + boms = [] + for dst, ids in specs: + dst = dst.replace('$engine', args.engine) + bom = emitter.artifact_bom(dst, [collected[i] for i in ids]) + write_json(os.path.join(args.out, dst + '.cdx.json'), bom) + boms.append(bom) + release_path = 'shorebird/%s/sbom.cdx.json' % args.engine + write_json(os.path.join(args.out, release_path), emitter.release_bom(boms)) + print('sbom: wrote %d artifact SBOMs and %s' % (len(boms), release_path)) + + +def main(argv): + parser = argparse.ArgumentParser(description=__doc__.split('\n')[0]) + sub = parser.add_subparsers(dest='command', required=True) + + p = sub.add_parser('collect', help='In a shard: what each of its SBOM specs links.') + p.add_argument('--shard', required=True, help='/, e.g. linux/android-arm64') + p.add_argument('--engine-src', required=True, help='The checkout\'s engine/src') + p.add_argument('--out', required=True, help='Directory to write .json to') + p.add_argument('--gn', help='gn binary (default: flutter/third_party/gn/gn)') + p.set_defaults(func=collect) + + p = sub.add_parser('emit', help='After all shards: write the CycloneDX files.') + p.add_argument('--engine', required=True, help='Engine revision') + p.add_argument('--collected', required=True, help='Directory of collected .json') + p.add_argument( + '--package-licenses', + required=True, + help='licenses_cpp --package_licenses_path output', + ) + p.add_argument('--out', required=True, help='Root to write .cdx.json under') + p.add_argument( + '--no-upstream', + action='store_true', + help='Skip upstream ancestry (it clones each upstream repo)', + ) + p.set_defaults(func=emit) + + args = parser.parse_args(argv) + args.func(args) + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/shorebird/sbom/sbom_test.py b/shorebird/sbom/sbom_test.py new file mode 100644 index 0000000000000..465a7f5681fa0 --- /dev/null +++ b/shorebird/sbom/sbom_test.py @@ -0,0 +1,358 @@ +#!/usr/bin/env python3 +# Copyright 2026 Shorebird. All rights reserved. +"""Tests for sbom.py. Run: python3 shorebird/sbom/sbom_test.py""" + +import json +import os +import sys +import tempfile +import unittest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import sbom # pylint: disable=wrong-import-position + +DEPS = ''' +vars = { + 'skia_git': 'https://skia.googlesource.com', + 'skia_revision': 'aaaa', + 'dart_sdk_git': 'git@github.com:shorebirdtech/dart-sdk.git', + 'dart_sdk_revision': 'dddd', +} +deps = { + 'engine/src/flutter/third_party/skia': Var('skia_git') + '/skia.git' + '@' + Var('skia_revision'), + 'engine/src/flutter/third_party/dart': Var('dart_sdk_git') + '@' + Var('dart_sdk_revision'), + 'engine/src/third_party/abseil-cpp': { + 'url': 'https://flutter.googlesource.com/mirrors/abseil-cpp@bbbb', + 'condition': 'True', + }, + 'engine/src/flutter/third_party/vulkan-deps/vulkan-headers/src': + 'https://flutter.googlesource.com/mirrors/Vulkan-Headers@cccc', + 'engine/src/flutter/third_party/updater': 'https://github.com/shorebirdtech/updater.git@eeee', + 'engine/src/flutter/prebuilts/linux-x64/dart-sdk': { + 'dep_type': 'gcs', 'bucket': 'b', 'objects': [], + }, + 'engine/src/flutter/buildtools/linux-x64/clang': { + 'dep_type': 'cipd', 'packages': [], + }, + 'flutter_tools_outside_engine': 'https://example.com/x.git@ffff', +} +''' + +TOOLCHAIN = '//build/toolchain/android:clang_arm64' +HOST = '//build/toolchain/linux:clang_x64' + +PROJECT = { + 'build_settings': { + 'build_dir': '//out/ci/android_release_arm64/', + 'default_toolchain': TOOLCHAIN, + }, + 'targets': { + '//flutter/shell/platform/android:flutter_shell_native': { + 'type': 'shared_library', + 'toolchain': TOOLCHAIN, + 'sources': [ + '//flutter/shell/platform/android/library_loader.cc', + '//out/ci/android_release_arm64/gen/generated.cc', + ], + 'deps': [ + '//flutter/third_party/skia:skia', + '//flutter/shell/common/shorebird:updater', + '//flutter/third_party/flatbuffers:flatc(%s)' % HOST, + '//flutter/lib/snapshot:generate_snapshot_bins', + '//flutter/third_party/dart/runtime:libdart', + ], + }, + '//flutter/third_party/skia:skia': { + 'type': 'static_library', + 'toolchain': TOOLCHAIN, + 'sources': ['//flutter/third_party/skia/src/core/SkCanvas.cpp'], + 'public': ['//flutter/third_party/vulkan-deps/vulkan-headers/src/include/vulkan.h'], + 'deps': ['//third_party/abseil-cpp/absl/base:base'], + }, + '//third_party/abseil-cpp/absl/base:base': { + 'type': 'source_set', + 'toolchain': TOOLCHAIN, + 'sources': ['//third_party/abseil-cpp/absl/base/log_severity.cc'], + 'public': '*', + }, + '//flutter/third_party/dart/runtime:libdart': { + 'type': 'source_set', + 'toolchain': TOOLCHAIN, + 'sources': [ + '//flutter/third_party/dart/runtime/vm/dart.cc', + '//flutter/third_party/dart/third_party/double-conversion/src/strtod.cc', + ], + }, + '//flutter/shell/common/shorebird:updater': { + 'type': 'source_set', + 'toolchain': TOOLCHAIN, + 'sources': ['//flutter/shell/common/shorebird/updater.cc'], + 'deps': ['//flutter/shell/common/shorebird:build_rust_updater'], + }, + '//flutter/shell/common/shorebird:build_rust_updater': { + 'type': 'action', + 'toolchain': TOOLCHAIN, + 'args': [ + '--rust-target', + 'aarch64-linux-android', + '--manifest-dir', + '../../../flutter/third_party/updater', + ], + }, + '//flutter/third_party/flatbuffers:flatc(%s)' % HOST: { + 'type': 'executable', + 'toolchain': HOST, + 'sources': ['//flutter/third_party/flatbuffers/src/flatc.cpp'], + }, + '//flutter/lib/snapshot:generate_snapshot_bins': { + 'type': 'action', + 'toolchain': TOOLCHAIN, + 'deps': ['//flutter/third_party/sqlite:sqlite'], + }, + '//flutter/third_party/sqlite:sqlite': { + 'type': 'source_set', + 'toolchain': TOOLCHAIN, + 'sources': ['//flutter/third_party/sqlite/sqlite3.c'], + }, + }, +} + + +class SbomTest(unittest.TestCase): + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.deps_file = os.path.join(self.tmp.name, 'DEPS') + with open(self.deps_file, 'w') as f: + f.write(DEPS) + self.git_deps, self.vars = sbom.read_deps(self.deps_file) + + def tearDown(self): + self.tmp.cleanup() + + def test_read_deps_keeps_git_deps_under_engine_src(self): + self.assertEqual( + self.git_deps, { + 'engine/src/flutter/third_party/skia': ('https://skia.googlesource.com/skia.git', 'aaaa'), + 'engine/src/flutter/third_party/dart': ('git@github.com:shorebirdtech/dart-sdk.git', 'dddd'), + 'engine/src/third_party/abseil-cpp': + ('https://flutter.googlesource.com/mirrors/abseil-cpp', 'bbbb'), + 'engine/src/flutter/third_party/vulkan-deps/vulkan-headers/src': + ('https://flutter.googlesource.com/mirrors/Vulkan-Headers', 'cccc'), + 'engine/src/flutter/third_party/updater': + ('https://github.com/shorebirdtech/updater.git', 'eeee'), + } + ) + + def test_package_of_matches_licenses_cpp(self): + self.assertEqual(sbom.package_of('flutter/lib/ui/painting.cc'), ('flutter', '')) + self.assertEqual( + sbom.package_of('flutter/third_party/skia/src/core/SkCanvas.cpp'), + ('skia', 'flutter/third_party/skia') + ) + self.assertEqual( + sbom.package_of('flutter/third_party/dart/third_party/double-conversion/src/strtod.cc'), + ('double-conversion', 'flutter/third_party/dart/third_party/double-conversion') + ) + # vulkan-deps and pkg are skipped as package names (kThirdPartyIgnore). + self.assertEqual( + sbom.package_of('flutter/third_party/vulkan-deps/vulkan-headers/src/include/vulkan.h'), + ('vulkan-headers', 'flutter/third_party/vulkan-deps/vulkan-headers') + ) + self.assertEqual( + sbom.package_of('flutter/third_party/dart/third_party/pkg/args/lib/args.dart'), + ('args', 'flutter/third_party/dart/third_party/pkg/args') + ) + + def test_walk_follows_links_not_tools(self): + paths, updater_args = sbom.walk_project( + PROJECT, ['//flutter/shell/platform/android:flutter_shell_native'] + ) + self.assertEqual( + paths, { + 'flutter/shell/platform/android/library_loader.cc', + 'flutter/third_party/skia/src/core/SkCanvas.cpp', + 'flutter/third_party/vulkan-deps/vulkan-headers/src/include/vulkan.h', + 'third_party/abseil-cpp/absl/base/log_severity.cc', + 'flutter/third_party/dart/runtime/vm/dart.cc', + 'flutter/third_party/dart/third_party/double-conversion/src/strtod.cc', + 'flutter/shell/common/shorebird/updater.cc', + } + ) + self.assertEqual( + [sbom.parse_updater_args(a) for a in updater_args], + [('aarch64-linux-android', '../../../flutter/third_party/updater')], + ) + + def test_walk_rejects_unknown_root(self): + with self.assertRaises(SystemExit): + sbom.walk_project(PROJECT, ['//nope:nope']) + + def test_components_map_files_to_deps_checkouts(self): + paths, _ = sbom.walk_project(PROJECT, ['//flutter/shell/platform/android:flutter_shell_native']) + self.assertEqual( + sbom.components_for_paths(sorted(paths), self.git_deps), [ + { + 'package': 'abseil-cpp', 'repo': 'engine/src/third_party/abseil-cpp', 'subpath': '' + }, + { + 'package': 'dart', 'repo': 'engine/src/flutter/third_party/dart', 'subpath': '' + }, + { + 'package': 'double-conversion', 'repo': 'engine/src/flutter/third_party/dart', + 'subpath': 'third_party/double-conversion' + }, + {'package': 'flutter', 'repo': '', 'subpath': ''}, + {'package': 'skia', 'repo': 'engine/src/flutter/third_party/skia', 'subpath': ''}, + { + 'package': 'vulkan-headers', + 'repo': 'engine/src/flutter/third_party/vulkan-deps/vulkan-headers/src', + 'subpath': '' + }, + ] + ) + + def test_parse_cargo_tree(self): + output = '\n'.join([ + 'updater v0.1.0 (/x/library)|Apache-2.0 OR MIT', + 'anyhow v1.0.104|MIT OR Apache-2.0', + 'aho-corasick v1.1.4|Unlicense OR MIT', + 'aho-corasick v1.1.4|Unlicense OR MIT (*)', + 'bipatch v1.0.0 (https://github.com/x/bipatch#abc)|Apache-2.0 OR MIT', + ]) + self.assertEqual( + sbom.parse_cargo_tree(output), [ + {'name': 'aho-corasick', 'version': '1.1.4', 'license': 'Unlicense OR MIT', + 'registry': True}, + {'name': 'anyhow', 'version': '1.0.104', 'license': 'MIT OR Apache-2.0', + 'registry': True}, + {'name': 'bipatch', 'version': '1.0.0', 'license': 'Apache-2.0 OR MIT', + 'registry': False}, + ] + ) + + def test_purls(self): + self.assertEqual( + sbom.purl_for('git@github.com:shorebirdtech/dart-sdk.git', 'dddd'), + 'pkg:github/shorebirdtech/dart-sdk@dddd' + ) + self.assertEqual( + sbom.purl_for('https://skia.googlesource.com/skia.git', 'aaaa'), + 'pkg:generic/skia@aaaa?vcs_url=git%2Bhttps://skia.googlesource.com/skia.git%40aaaa' + ) + self.assertEqual( + sbom.purl_for('https://chromium.googlesource.com/external/github.com/google/re2', 'rrrr'), + 'pkg:github/google/re2@rrrr' + ) + self.assertEqual( + sbom.purl_for('git@github.com:shorebirdtech/dart-sdk.git', 'dddd', 'third_party/x'), + 'pkg:github/shorebirdtech/dart-sdk@dddd#third_party/x' + ) + + def test_license_expression(self): + ids = sbom.load_spdx_ids() + self.assertEqual(sbom.license_expression(['bsd3_clause', 'chromium'], ids), 'BSD-3-Clause') + self.assertEqual( + sbom.license_expression(['apache2 or mit', 'MIT'], ids), '(Apache-2.0 OR MIT) AND MIT' + ) + self.assertEqual( + sbom.license_expression(['harfbuzz copying'], ids), 'LicenseRef-flutter-harfbuzz-copying' + ) + self.assertIsNone(sbom.license_expression([], ids)) + + def test_spdx_ids_name_real_matchers(self): + matchers_dir = os.path.join( + sbom.REPO_ROOT, 'engine', 'src', 'flutter', 'tools', 'licenses_cpp', 'data', 'licenses' + ) + names = set() + for name in os.listdir(matchers_dir): + with open(os.path.join(matchers_dir, name)) as f: + names.add(f.readline().rstrip('\n')) + self.assertEqual(set(sbom.load_spdx_ids()) - names, set()) + + def test_artifact_bom(self): + paths, _ = sbom.walk_project(PROJECT, ['//flutter/shell/platform/android:flutter_shell_native']) + collected = { + 'id': 'android-arm64-release', + 'components': sbom.components_for_paths(sorted(paths), self.git_deps), + 'updater': { + 'rust_targets': ['aarch64-linux-android'], + 'crates': [{'name': 'anyhow', 'version': '1.0.104', 'license': 'MIT OR Apache-2.0', + 'registry': True}], + }, + } + emitter = sbom.Emitter( + 'e1', self.git_deps, {'skia': ['bsd3_clause']}, sbom.load_spdx_ids(), { + 'engine/src/third_party/abseil-cpp': + ('https://github.com/abseil/abseil-cpp', 'upstream1') + } + ) + dst = 'flutter_infra_release/flutter/e1/android-arm64-release/artifacts.zip' + bom = emitter.artifact_bom(dst, [collected]) + self.assertEqual(bom['specVersion'], '1.6') + self.assertEqual(bom['metadata']['component']['bom-ref'], 'artifact:' + dst) + by_name = {c['name']: c for c in bom['components']} + self.assertEqual( + sorted(by_name), [ + 'abseil-cpp', 'anyhow', 'dart', 'double-conversion', 'flutter', 'skia', 'updater', + 'vulkan-headers' + ] + ) + self.assertEqual(by_name['flutter']['purl'], 'pkg:github/shorebirdtech/flutter@e1') + self.assertEqual(by_name['skia']['licenses'], [{'expression': 'BSD-3-Clause'}]) + self.assertEqual(by_name['anyhow']['purl'], 'pkg:cargo/anyhow@1.0.104') + self.assertEqual( + by_name['abseil-cpp']['pedigree']['ancestors'][0]['purl'], + 'pkg:github/abseil/abseil-cpp@upstream1' + ) + deps = {d['ref']: d['dependsOn'] for d in bom['dependencies']} + self.assertIn(by_name['updater']['bom-ref'], deps['artifact:' + dst]) + self.assertEqual(deps[by_name['updater']['bom-ref']], ['pkg:cargo/anyhow@1.0.104']) + refs = [c['bom-ref'] for c in bom['components']] + self.assertEqual(len(refs), len(set(refs))) + + release = emitter.release_bom([bom]) + release_deps = {d['ref']: d['dependsOn'] for d in release['dependencies']} + self.assertEqual(release_deps['pkg:github/shorebirdtech/flutter@e1'], ['artifact:' + dst]) + self.assertNotEqual(release['serialNumber'], bom['serialNumber']) + + +class ConfigTest(unittest.TestCase): + """The real shorebird/ci config.""" + + def test_every_artifact_sbom_names_a_spec(self): + spec_ids = set() + for path in os.listdir(os.path.join(sbom.CI_DIR, 'shards')): + with open(os.path.join(sbom.CI_DIR, 'shards', path)) as f: + for shard in json.load(f).values(): + for spec in shard.get('sbom', []): + self.assertNotIn(spec['id'], spec_ids) + spec_ids.add(spec['id']) + self.assertTrue(spec.get('builds') or spec.get('paths'), spec['id']) + for build in spec.get('builds', []): + self.assertTrue(build['out_dir'] and build['roots'], spec['id']) + artifacts = sbom.artifact_specs() + self.assertTrue(artifacts) + for dst, ids in artifacts: + for spec_id in ids: + self.assertIn(spec_id, spec_ids, dst) + + def test_sbom_paths_in_the_fork_exist(self): + # Paths in DEPS checkouts (Dart's sdk/lib) aren't in this checkout + # without a gclient sync. + git_deps, _ = sbom.read_deps(os.path.join(sbom.REPO_ROOT, 'DEPS')) + for path in os.listdir(os.path.join(sbom.CI_DIR, 'shards')): + with open(os.path.join(sbom.CI_DIR, 'shards', path)) as f: + for shard in json.load(f).values(): + for spec in shard.get('sbom', []): + for p in spec.get('paths', []): + if sbom.repo_for(p + '/_', git_deps): + continue + self.assertTrue( + os.path.isdir(os.path.join(sbom.REPO_ROOT, 'engine', 'src', p)), + '%s: %s' % (spec['id'], p), + ) + + +if __name__ == '__main__': + unittest.main() diff --git a/shorebird/sbom/spdx_ids.json b/shorebird/sbom/spdx_ids.json new file mode 100644 index 0000000000000..0246d621e55d9 --- /dev/null +++ b/shorebird/sbom/spdx_ids.json @@ -0,0 +1,48 @@ +{ + "FTL": "FTL", + "MIT": "MIT", + "MIT (dateless indented)": "MIT", + "MIT (materials)": "MIT-Khronos-old", + "MIT (no newlines)": "MIT", + "MIT LLVM": "NCSA", + "angle commented": "BSD-3-Clause", + "apache 2 vulkan validation layers": "Apache-2.0", + "apache llvm": "Apache-2.0 WITH LLVM-exception", + "apache2": "Apache-2.0", + "apache2 boringssl": "Apache-2.0", + "apache2 centered": "Apache-2.0", + "apache2 header": "Apache-2.0", + "apache2 or mit": "Apache-2.0 OR MIT", + "apache2 spdx": "Apache-2.0", + "as is": "Zlib", + "boost file": "BSL-1.0", + "bsd header": "BSD-3-Clause", + "bsd2 clause": "BSD-2-Clause", + "bsd2 clause 2": "BSD-2-Clause", + "bsd2 clause android": "BSD-2-Clause", + "bsd3_clause": "BSD-3-Clause", + "chromium": "BSD-3-Clause", + "dart": "BSD-3-Clause", + "expat": "MIT", + "flutter": "BSD-3-Clause", + "freetype license": "FTL", + "google": "BSD-3-Clause", + "google commented": "BSD-3-Clause", + "google_comma": "BSD-3-Clause", + "icu": "Unicode-3.0", + "icu unicode header": "Unicode-3.0", + "ijg": "IJG", + "inja": "MIT", + "jpeg header": "IJG", + "libjpeg-turbo": "IJG AND BSD-3-Clause AND Zlib", + "libpng": "libpng-2.0", + "mit libXNVCtrl": "MIT", + "mit starred ": "MIT", + "mozilla 2.0": "MPL-2.0", + "polymer": "BSD-3-Clause", + "rapidjson": "MIT", + "rapidjson_header": "MIT", + "sgi": "SGI-B-2.0", + "sqlite": "blessing", + "v8": "BSD-3-Clause" +} From 08fea568b62b7d7b722e981c67bdf78b83ecd587 Mon Sep 17 00:00:00 2001 From: Eric Seidel Date: Tue, 1 Dec 2026 16:47:33 -0800 Subject: [PATCH 2/4] feat(shorebird): run licenses_cpp in linux/host for SBOM license ids Co-Authored-By: Claude Opus 5.5 --- shorebird/ci/shards/linux.json | 3 ++- shorebird/sbom/sbom.py | 45 +++++++++++++++++++++++++++++++--- 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/shorebird/ci/shards/linux.json b/shorebird/ci/shards/linux.json index d36c01473de20..ae22b91984afd 100644 --- a/shorebird/ci/shards/linux.json +++ b/shorebird/ci/shards/linux.json @@ -219,7 +219,7 @@ "type": "builder", "builds": ["linux_host_engine/ci/host_release"], "ninja_targets": { - "add": ["dart_sdk", "flutter/tools/font_subset"], + "add": ["dart_sdk", "flutter/tools/font_subset", "flutter/tools/licenses_cpp"], "why": "What this shard's artifacts, composes or later steps need that upstream's build doesn't list." } }, @@ -240,6 +240,7 @@ "command": "mkdir -p out/ci/host_release/aot_tools && out/ci/host_release/dart-sdk/bin/dart pub get --offline --directory=flutter/third_party/dart/pkg/aot_tools && out/ci/host_release/dart-sdk/bin/dart compile kernel flutter/third_party/dart/pkg/aot_tools/bin/aot_tools.dart -o out/ci/host_release/aot_tools/aot-tools.dill" } ], + "sbom_licenses": {"out_dir": "ci/host_release"}, "sbom": [ { "id": "flutter-patched-sdk-product", diff --git a/shorebird/sbom/sbom.py b/shorebird/sbom/sbom.py index 5c1a2423b4abc..46ccacbeb18be 100644 --- a/shorebird/sbom/sbom.py +++ b/shorebird/sbom/sbom.py @@ -60,6 +60,10 @@ 'copy', } +# What collect names licenses_cpp's --package_licenses_path output (the +# shard with `sbom_licenses` writes it); _build_engine passes it to emit. +PACKAGE_LICENSES = 'package_licenses.json' + UPDATER_ACTION = '//flutter/shell/common/shorebird:build_rust_updater' UPDATER_DEPS_PATH = 'engine/src/flutter/third_party/updater' @@ -281,18 +285,51 @@ def cargo_crates(manifest_dir, rust_target): return parse_cargo_tree(output) -def shard_specs(shard): +def shard_config(shard): platform, name = shard.split('/', 1) with open(os.path.join(CI_DIR, 'shards', platform + '.json')) as f: - return json.load(f)[name].get('sbom', []) + return json.load(f)[name] + + +def exe(path): + return path + '.exe' if sys.platform == 'win32' else path + + +def run_licenses_cpp(engine_src, out_dir, out): + """Runs licenses_cpp as ci/licenses_cpp.sh does, with Shorebird's + --package_licenses_path, and writes PACKAGE_LICENSES into `out`.""" + output = os.path.join(out, PACKAGE_LICENSES) + with tempfile.TemporaryDirectory() as tmp: + result = subprocess.run([ + exe(os.path.join(engine_src, 'out', out_dir, 'licenses_cpp')), + '--working_dir', + engine_src, + '--data_dir', + os.path.join(engine_src, 'flutter', 'tools', 'licenses_cpp', 'data'), + '--licenses_path', + os.path.join(tmp, 'LICENSE'), + '--root_package', + ROOT_PACKAGE, + '--package_licenses_path', + output, + ]) + # licenses_cpp exits 1 when a file has no license it recognizes (upstream's + # CI gate, which the fork doesn't run). It still writes what it matched. + if not os.path.exists(output) or os.path.getsize(output) == 0: + raise SystemExit('sbom: licenses_cpp (exit %d) wrote no %s' % (result.returncode, output)) + if result.returncode != 0: + print('sbom: licenses_cpp exited %d; using what it matched' % result.returncode) def collect(args): engine_src = os.path.abspath(args.engine_src) deps_paths, _ = read_deps(os.path.join(engine_src, '..', '..', 'DEPS')) - gn = args.gn or os.path.join(engine_src, 'flutter', 'third_party', 'gn', 'gn') + gn = args.gn or exe(os.path.join(engine_src, 'flutter', 'third_party', 'gn', 'gn')) os.makedirs(args.out, exist_ok=True) - for spec in shard_specs(args.shard): + config = shard_config(args.shard) + if 'sbom_licenses' in config: + run_licenses_cpp(engine_src, config['sbom_licenses']['out_dir'], args.out) + for spec in config.get('sbom', []): paths = set(spec.get('paths', [])) # Each path in `paths` names a directory: give it a file so package_of # places the directory itself. From 849b53c3efcbe4b87748aa86c2bed90cd2ca1509 Mon Sep 17 00:00:00 2001 From: Eric Seidel Date: Tue, 1 Dec 2026 17:01:19 -0800 Subject: [PATCH 3/4] fix(shorebird): SBOM review fixes Unique release bom-ref; fork subpaths include engine/src; Dart and Flutter fork ancestors; cargo '/' licenses as OR; rust-std component; JSON control characters; git identity for licenses_cpp tests; harfbuzz, ISC and BSD mappings. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/shorebird_engine_tests.yml | 6 ++ .../tools/licenses_cpp/src/license_checker.cc | 12 ++- shorebird/sbom/sbom.py | 87 +++++++++++++++++-- shorebird/sbom/sbom_test.py | 38 ++++++-- shorebird/sbom/spdx_ids.json | 5 ++ 5 files changed, 132 insertions(+), 16 deletions(-) diff --git a/.github/workflows/shorebird_engine_tests.yml b/.github/workflows/shorebird_engine_tests.yml index bdd56cb1762ff..e157cdb7c0e9c 100644 --- a/.github/workflows/shorebird_engine_tests.yml +++ b/.github/workflows/shorebird_engine_tests.yml @@ -221,9 +221,15 @@ jobs: run: ./out/host_profile_unopt/exe.unstripped/shorebird_unittests working-directory: engine/src + # Its tests commit to temporary git repos, which needs an identity. - name: 🧪 Run licenses_cpp tests run: ./out/host_profile_unopt/licenses_cpp_testrunner working-directory: engine/src + env: + GIT_AUTHOR_NAME: licenses_cpp test + GIT_AUTHOR_EMAIL: test@example.com + GIT_COMMITTER_NAME: licenses_cpp test + GIT_COMMITTER_EMAIL: test@example.com - name: 🧪 Run Shorebird shell_unittests run: ./out/host_profile_unopt/shell_unittests '--gtest_filter=*Shorebird*' diff --git a/engine/src/flutter/tools/licenses_cpp/src/license_checker.cc b/engine/src/flutter/tools/licenses_cpp/src/license_checker.cc index 5e799ebaaaf7c..8821a868da035 100644 --- a/engine/src/flutter/tools/licenses_cpp/src/license_checker.cc +++ b/engine/src/flutter/tools/licenses_cpp/src/license_checker.cc @@ -5,6 +5,7 @@ #include "flutter/tools/licenses_cpp/src/license_checker.h" #include +#include #include #include #include @@ -217,11 +218,14 @@ void WriteJsonString(std::ostream& out, std::string_view value) { case '\\': out << "\\\\"; break; - case '\n': - out << "\\n"; - break; default: - out << c; + if (static_cast(c) < 0x20) { + char escaped[7]; + std::snprintf(escaped, sizeof(escaped), "\\u%04x", c); + out << escaped; + } else { + out << c; + } } } out << '"'; diff --git a/shorebird/sbom/sbom.py b/shorebird/sbom/sbom.py index 46ccacbeb18be..425dcc1e06c70 100644 --- a/shorebird/sbom/sbom.py +++ b/shorebird/sbom/sbom.py @@ -66,6 +66,7 @@ UPDATER_ACTION = '//flutter/shell/common/shorebird:build_rust_updater' UPDATER_DEPS_PATH = 'engine/src/flutter/third_party/updater' +DART_DEPS_PATH = 'engine/src/flutter/third_party/dart' # --------------------------------------------------------------------------- @@ -151,7 +152,8 @@ def components_for_paths(paths, deps_paths): subpath = '' if pkg_dir and pkg_dir != repo_dir: if not repo_dir: - subpath = pkg_dir + # The fork's own repo root is two levels above engine/src. + subpath = ENGINE_SRC_PREFIX + pkg_dir elif pkg_dir.startswith(repo_dir + '/'): subpath = pkg_dir[len(repo_dir) + 1:] key = (name, repo, subpath) @@ -238,6 +240,12 @@ def parse_updater_args(args): return parsed.get('--rust-target'), parsed.get('--manifest-dir') +def cargo_license(expr): + """Cargo's license field as an SPDX expression: crates still using the + deprecated `MIT/Apache-2.0` form mean OR.""" + return ' OR '.join(part.strip() for part in expr.strip().split('/')) + + def parse_cargo_tree(output): """Crates from `cargo tree --prefix none --format '{p}|{l}'`.""" crates = {} @@ -257,7 +265,7 @@ def parse_cargo_tree(output): crates[(name, version)] = { 'name': name, 'version': version, - 'license': license_expr.strip(), + 'license': cargo_license(license_expr), 'registry': not source, } return [crates[k] for k in sorted(crates)] @@ -285,6 +293,29 @@ def cargo_crates(manifest_dir, rust_target): return parse_cargo_tree(output) +def rustc_version(): + """`rustc --version`'s version, e.g. 1.99.1.""" + return subprocess.check_output(['rustc', '--version'], text=True).split()[1] + + +def read_dart_version(engine_src): + """The Dart version the fork is based on, from its tools/VERSION (the + form dart-lang/sdk tags releases with: 3.14.1, 3.15.0-12.0.dev).""" + path = os.path.join(engine_src, 'flutter', 'third_party', 'dart', 'tools', 'VERSION') + if not os.path.exists(path): + return None + fields = {} + with open(path) as f: + for line in f: + parts = line.split() + if len(parts) == 2: + fields[parts[0]] = parts[1] + version = '%s.%s.%s' % (fields['MAJOR'], fields['MINOR'], fields['PATCH']) + if fields.get('CHANNEL') not in (None, 'stable'): + version += '-%s.%s.%s' % (fields['PRERELEASE'], fields['PRERELEASE_PATCH'], fields['CHANNEL']) + return version + + def shard_config(shard): platform, name = shard.split('/', 1) with open(os.path.join(CI_DIR, 'shards', platform + '.json')) as f: @@ -361,7 +392,13 @@ def collect(args): result['updater'] = { 'rust_targets': sorted(rust_targets), 'crates': [crates[k] for k in sorted(crates)], + # libupdater.a links Rust's standard library statically. + 'rustc': rustc_version(), } + if any(c['package'] == 'dart' for c in result['components']): + dart_version = read_dart_version(engine_src) + if dart_version: + result['dart_version'] = dart_version with open(os.path.join(args.out, spec['id'] + '.json'), 'w') as f: json.dump(result, f, indent=2, sort_keys=True) f.write('\n') @@ -439,8 +476,12 @@ def resolve_upstreams(repos, git_deps, deps_vars): class Emitter: - def __init__(self, engine, git_deps, package_licenses, spdx_ids, upstreams): + def __init__(self, engine, git_deps, package_licenses, spdx_ids, upstreams, + upstream_engine=None): self.engine = engine + # flutter/flutter's engine revision this fork's engine is based on, when + # the release recorded it (bin/internal/shorebird_upstream_engine.json). + self.upstream_engine = upstream_engine self.git_deps = git_deps self.package_licenses = package_licenses self.spdx_ids = spdx_ids @@ -464,9 +505,17 @@ def component(self, c): expression = license_expression(self.package_licenses.get(c['package'], []), self.spdx_ids) if expression: out['licenses'] = [{'expression': expression}] + ancestor = None if repo in self.upstreams: upstream, commit = self.upstreams[repo] ancestor = purl_for(upstream, commit, c['subpath']) + elif repo == DART_DEPS_PATH and c.get('dart_version') and not c['subpath']: + commit = c['dart_version'] + ancestor = 'pkg:github/dart-lang/sdk@' + commit + elif not repo and self.upstream_engine: + commit = self.upstream_engine + ancestor = purl_for('https://github.com/flutter/flutter', commit, c['subpath']) + if ancestor: out['pedigree'] = { 'ancestors': [{ 'type': 'library', @@ -514,7 +563,7 @@ def contents(self, collected): direct = [] dependencies = [] for c in collected['components']: - comp = self.component(c) + comp = self.component(dict(c, dart_version=collected.get('dart_version'))) components[comp['bom-ref']] = comp direct.append(comp['bom-ref']) if 'updater' in collected: @@ -522,6 +571,19 @@ def contents(self, collected): components[updater['bom-ref']] = updater direct.append(updater['bom-ref']) crate_refs = [] + rustc = collected['updater'].get('rustc') + if rustc: + std = { + 'type': 'library', + 'bom-ref': 'pkg:generic/rust-std@' + rustc, + 'name': 'rust-std', + 'version': rustc, + 'purl': 'pkg:generic/rust-std@' + rustc, + 'licenses': [{'expression': 'MIT OR Apache-2.0'}], + 'externalReferences': [{'type': 'vcs', 'url': 'https://github.com/rust-lang/rust'}], + } + components[std['bom-ref']] = std + crate_refs.append(std['bom-ref']) for crate in collected['updater']['crates']: comp = self.crate(crate) components[comp['bom-ref']] = comp @@ -573,7 +635,8 @@ def artifact_subject(self, dst): def release_bom(self, artifact_boms): subject = { 'type': 'framework', - 'bom-ref': FORK_PURL + '@' + self.engine, + # Not the purl: the fork's own `flutter` component has that ref. + 'bom-ref': 'release:' + self.engine, 'name': 'Shorebird Flutter engine', 'version': self.engine, 'purl': FORK_PURL + '@' + self.engine, @@ -615,6 +678,17 @@ def artifact_specs(): return result +def read_upstream_engine(engine): + """flutter/flutter's engine revision for `engine`, if the release pinned + it in bin/internal/shorebird_upstream_engine.json.""" + path = os.path.join(REPO_ROOT, 'bin', 'internal', 'shorebird_upstream_engine.json') + if not os.path.exists(path): + return None + with open(path) as f: + pinned = json.load(f) + return pinned.get('upstreamEngine') if pinned.get('engine') == engine else None + + def write_json(path, data): os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, 'w') as f: @@ -638,7 +712,8 @@ def emit(args): collected[spec_id] = json.load(f) repos = {c['repo'] for spec in collected.values() for c in spec['components'] if c['repo']} upstreams = {} if args.no_upstream else resolve_upstreams(repos, git_deps, deps_vars) - emitter = Emitter(args.engine, git_deps, package_licenses, load_spdx_ids(), upstreams) + emitter = Emitter(args.engine, git_deps, package_licenses, load_spdx_ids(), upstreams, + read_upstream_engine(args.engine)) boms = [] for dst, ids in specs: dst = dst.replace('$engine', args.engine) diff --git a/shorebird/sbom/sbom_test.py b/shorebird/sbom/sbom_test.py index 465a7f5681fa0..cc9e937fcc177 100644 --- a/shorebird/sbom/sbom_test.py +++ b/shorebird/sbom/sbom_test.py @@ -219,6 +219,7 @@ def test_parse_cargo_tree(self): 'aho-corasick v1.1.4|Unlicense OR MIT', 'aho-corasick v1.1.4|Unlicense OR MIT (*)', 'bipatch v1.0.0 (https://github.com/x/bipatch#abc)|Apache-2.0 OR MIT', + 'log-panics v2.1.0|MIT/Apache-2.0', ]) self.assertEqual( sbom.parse_cargo_tree(output), [ @@ -228,6 +229,8 @@ def test_parse_cargo_tree(self): 'registry': True}, {'name': 'bipatch', 'version': '1.0.0', 'license': 'Apache-2.0 OR MIT', 'registry': False}, + {'name': 'log-panics', 'version': '2.1.0', 'license': 'MIT OR Apache-2.0', + 'registry': True}, ] ) @@ -256,7 +259,7 @@ def test_license_expression(self): sbom.license_expression(['apache2 or mit', 'MIT'], ids), '(Apache-2.0 OR MIT) AND MIT' ) self.assertEqual( - sbom.license_expression(['harfbuzz copying'], ids), 'LicenseRef-flutter-harfbuzz-copying' + sbom.license_expression(['gifencode'], ids), 'LicenseRef-flutter-gifencode' ) self.assertIsNone(sbom.license_expression([], ids)) @@ -279,13 +282,19 @@ def test_artifact_bom(self): 'rust_targets': ['aarch64-linux-android'], 'crates': [{'name': 'anyhow', 'version': '1.0.104', 'license': 'MIT OR Apache-2.0', 'registry': True}], + 'rustc': '1.99.1', }, + 'dart_version': '3.14.1', } + collected['components'].append({ + 'package': 'txt', 'repo': '', 'subpath': 'engine/src/flutter/third_party/txt' + }) emitter = sbom.Emitter( 'e1', self.git_deps, {'skia': ['bsd3_clause']}, sbom.load_spdx_ids(), { 'engine/src/third_party/abseil-cpp': ('https://github.com/abseil/abseil-cpp', 'upstream1') - } + }, + upstream_engine='u2' ) dst = 'flutter_infra_release/flutter/e1/android-arm64-release/artifacts.zip' bom = emitter.artifact_bom(dst, [collected]) @@ -294,10 +303,21 @@ def test_artifact_bom(self): by_name = {c['name']: c for c in bom['components']} self.assertEqual( sorted(by_name), [ - 'abseil-cpp', 'anyhow', 'dart', 'double-conversion', 'flutter', 'skia', 'updater', - 'vulkan-headers' + 'abseil-cpp', 'anyhow', 'dart', 'double-conversion', 'flutter', 'rust-std', 'skia', + 'txt', 'updater', 'vulkan-headers' ] ) + self.assertEqual( + by_name['txt']['purl'], + 'pkg:github/shorebirdtech/flutter@e1#engine/src/flutter/third_party/txt' + ) + self.assertEqual( + by_name['dart']['pedigree']['ancestors'][0]['purl'], 'pkg:github/dart-lang/sdk@3.14.1' + ) + self.assertNotIn('pedigree', by_name['double-conversion']) + self.assertEqual( + by_name['flutter']['pedigree']['ancestors'][0]['purl'], 'pkg:github/flutter/flutter@u2' + ) self.assertEqual(by_name['flutter']['purl'], 'pkg:github/shorebirdtech/flutter@e1') self.assertEqual(by_name['skia']['licenses'], [{'expression': 'BSD-3-Clause'}]) self.assertEqual(by_name['anyhow']['purl'], 'pkg:cargo/anyhow@1.0.104') @@ -307,13 +327,19 @@ def test_artifact_bom(self): ) deps = {d['ref']: d['dependsOn'] for d in bom['dependencies']} self.assertIn(by_name['updater']['bom-ref'], deps['artifact:' + dst]) - self.assertEqual(deps[by_name['updater']['bom-ref']], ['pkg:cargo/anyhow@1.0.104']) + self.assertEqual( + deps[by_name['updater']['bom-ref']], + ['pkg:cargo/anyhow@1.0.104', 'pkg:generic/rust-std@1.99.1'] + ) refs = [c['bom-ref'] for c in bom['components']] self.assertEqual(len(refs), len(set(refs))) release = emitter.release_bom([bom]) release_deps = {d['ref']: d['dependsOn'] for d in release['dependencies']} - self.assertEqual(release_deps['pkg:github/shorebirdtech/flutter@e1'], ['artifact:' + dst]) + self.assertEqual(release_deps['release:e1'], ['artifact:' + dst]) + release_refs = [c['bom-ref'] for c in release['components']] + self.assertEqual(len(release_refs), len(set(release_refs))) + self.assertNotIn('release:e1', release_refs) self.assertNotEqual(release['serialNumber'], bom['serialNumber']) diff --git a/shorebird/sbom/spdx_ids.json b/shorebird/sbom/spdx_ids.json index 0246d621e55d9..418194610c92d 100644 --- a/shorebird/sbom/spdx_ids.json +++ b/shorebird/sbom/spdx_ids.json @@ -19,6 +19,7 @@ "bsd header": "BSD-3-Clause", "bsd2 clause": "BSD-2-Clause", "bsd2 clause 2": "BSD-2-Clause", + "bsd2 clause 3": "BSD-2-Clause", "bsd2 clause android": "BSD-2-Clause", "bsd3_clause": "BSD-3-Clause", "chromium": "BSD-3-Clause", @@ -28,7 +29,11 @@ "freetype license": "FTL", "google": "BSD-3-Clause", "google commented": "BSD-3-Clause", + "google header": "BSD-3-Clause", "google_comma": "BSD-3-Clause", + "harfbuzz": "MIT-Modern-Variant", + "harfbuzz copying": "MIT-Modern-Variant", + "harfbuzz2": "ISC", "icu": "Unicode-3.0", "icu unicode header": "Unicode-3.0", "ijg": "IJG", From 23cd0082ff40816d7ea5988707e94af57768c591 Mon Sep 17 00:00:00 2001 From: Eric Seidel Date: Tue, 1 Dec 2026 17:50:46 -0800 Subject: [PATCH 4/4] fix(shorebird): run cargo tree without color so licenses stay clean CI sets CARGO_TERM_COLOR=always, so the (*) dedupe marker came out wrapped in ANSI codes and leaked into crate license fields (seen in the _build_engine test build 46786597836). Co-Authored-By: Claude Opus 5.5 --- shorebird/sbom/sbom.py | 2 ++ shorebird/sbom/sbom_test.py | 12 ++++++++++++ 2 files changed, 14 insertions(+) diff --git a/shorebird/sbom/sbom.py b/shorebird/sbom/sbom.py index 425dcc1e06c70..565fe64010f9f 100644 --- a/shorebird/sbom/sbom.py +++ b/shorebird/sbom/sbom.py @@ -276,6 +276,8 @@ def cargo_crates(manifest_dir, rust_target): 'cargo', 'tree', '--locked', + '--color', + 'never', '--manifest-path', os.path.join(manifest_dir, 'Cargo.toml'), '-p', diff --git a/shorebird/sbom/sbom_test.py b/shorebird/sbom/sbom_test.py index cc9e937fcc177..bf05262948750 100644 --- a/shorebird/sbom/sbom_test.py +++ b/shorebird/sbom/sbom_test.py @@ -234,6 +234,18 @@ def test_parse_cargo_tree(self): ] ) + def test_cargo_crates_disables_color(self): + # CI sets CARGO_TERM_COLOR=always, which colors the `(*)` marker so it + # leaks into the license field. + calls = [] + original = sbom.subprocess.check_output + sbom.subprocess.check_output = lambda cmd, **_: calls.append(cmd) or '' + try: + sbom.cargo_crates('/x', 'aarch64-linux-android') + finally: + sbom.subprocess.check_output = original + self.assertIn(['--color', 'never'], [calls[0][i:i + 2] for i in range(len(calls[0]))]) + def test_purls(self): self.assertEqual( sbom.purl_for('git@github.com:shorebirdtech/dart-sdk.git', 'dddd'),