diff --git a/.github/workflows/bump-version.yaml b/.github/workflows/bump-version.yaml index fed8580..fe4d9aa 100644 --- a/.github/workflows/bump-version.yaml +++ b/.github/workflows/bump-version.yaml @@ -54,6 +54,8 @@ jobs: run: | make tools make -s tools-path >> "${GITHUB_PATH}" + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Bump version # also fetches the wit dependencies for the new version, and builds and tests the components run: build/scripts/bump-version.sh "${VERSION}" diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 0387d90..1e23969 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -10,6 +10,11 @@ on: - 'v[0-9]+\.[0-9]+\.[0-9]+-?**' pull_request: {} +# read only unless a job asks for more, e.g. publish, the GITHUB_TOKEN is otherwise the repository's +# default, which may be able to write +permissions: + contents: read + jobs: # the settings of the repository's Makefile the other jobs need, e.g. whether it builds a cli settings: @@ -31,13 +36,24 @@ jobs: steps: - uses: actions/checkout@v7 - uses: actions-rust-lang/setup-rust-toolchain@v2 + - name: Cache tools + # the tools installed here, with a read only GITHUB_TOKEN, are restored by the publish job, + # which doesn't install them with its token that can write. Saved once the job succeeds. + uses: actions/cache@v6 + with: + path: target/tools + key: tools-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('build/tools/Cargo.toml', 'tools/Cargo.toml', 'rust-toolchain.toml', 'build/tools.mk') }} - name: Install cargo binstall uses: cargo-bins/cargo-binstall@main - name: Install tools - # the versions pinned in build/tools/Cargo.toml and tools/Cargo.toml, on the path for later steps + # the versions pinned in build/tools/Cargo.toml and tools/Cargo.toml, on the path for later + # steps. Nothing to install when the cache is restored. The token raises cargo binstall's + # GitHub API rate limit. run: | make tools make -s tools-path >> "${GITHUB_PATH}" + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Generate # the wit dependencies, and anything else the repository generates, see `make generate` run: make generate @@ -132,6 +148,16 @@ jobs: - uses: actions-rust-lang/setup-rust-toolchain@v2 with: target: ${{ matrix.target }} + - name: Install musl + # the static linux builds compile the C of a crate the cli depends on, e.g. aws-lc-sys of rustls, + # with musl-gcc, cc looks for a cross compiler, e.g. x86_64-linux-musl-gcc, the runners have none + if: endsWith(matrix.target, '-linux-musl') + env: + TARGET: ${{ matrix.target }} + run: | + sudo apt-get update + sudo apt-get install -y musl-tools + echo "CC_${TARGET//-/_}=musl-gcc" >> "${GITHUB_ENV}" - name: Build cli run: cargo build --release --locked --bin "${CLI_BIN}" --target ${{ matrix.target }} - name: Package cli @@ -226,14 +252,18 @@ jobs: run: echo "::notice::a dry run, the repository variable DRY_RUN is true, nothing is published" - uses: actions/checkout@v7 - uses: actions-rust-lang/setup-rust-toolchain@v2 - - name: Install cargo binstall - uses: cargo-bins/cargo-binstall@main - - name: Install tools - run: | - make tools - make -s tools-path >> "${GITHUB_PATH}" - - name: Install cosign - uses: sigstore/cosign-installer@v4.1.3 + - name: Restore tools + # installed by the build job, so the tools aren't downloaded, or built, where the GITHUB_TOKEN + # can write and OIDC tokens can be requested. The key must match the build job's. + uses: actions/cache/restore@v6 + with: + path: target/tools + key: tools-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('build/tools/Cargo.toml', 'tools/Cargo.toml', 'rust-toolchain.toml', 'build/tools.mk') }} + fail-on-cache-miss: true + - name: Add tools to the path + # the restored tools, nothing is installed. Publishing only needs the pinned tools, wkg and + # cosign, a local tool isn't built here. + run: make -s tools-path >> "${GITHUB_PATH}" - name: Download components.tar uses: actions/download-artifact@v8 with: @@ -284,7 +314,8 @@ jobs: id: publish run: | make publish - if [ "${DRY_RUN}" != "true" ] ; then + # nothing may be published, e.g. a repository of tests, see PUBLISH_INTERFACE + if [ "${DRY_RUN}" != "true" ] && [ -s "${PUBLISH_LOG}" ] ; then echo "published=true" >> "${GITHUB_OUTPUT}" fi env: @@ -293,25 +324,83 @@ jobs: VERSION: "${{ steps.version.outputs.VERSION }}" - name: Draft release notes if: startsWith(github.ref, 'refs/tags/') || (github.ref == 'refs/heads/main' && contains(steps.interface_version.outputs.VERSION, '-')) + # with COMPONENTIZED_DIRECTORY_SCAN=true, each file leads with its id and icon linking to the + # page componentized.dev serves its version at once the directory-scan job's scan has indexed + # it, the debug build to the page of its version. The directory's id of a package is its repository + # path, e.g. ghcr.io/componentized/logging is componentized:logging, the interface, and + # ghcr.io/componentized/logging/levels is componentized:logging-levels, a component. The icon + # is the directory's for the kind of package, https://componentized.dev/_icons/, in the colors + # of GitHub's light or dark theme, neutral where the theme isn't known. + env: + DIRECTORY: ${{ vars.COMPONENTIZED_DIRECTORY_SCAN == 'true' }} + VERSION: ${{ steps.version.outputs.VERSION }} run: | + icons="https://componentized.dev/_icons" + published="${RUNNER_TEMP}/published.txt" + if [ ! -s "${published}" ] ; then + # nothing published, e.g. a repository of tests, see PUBLISH_INTERFACE, or a dry run + echo "No components are published with this release." > "${RUNNER_TEMP}/release-notes.md" + cat "${RUNNER_TEMP}/release-notes.md" + exit 0 + fi { echo "## Published components" echo - echo "| File | Size | Image |" - echo "| --- | --: | --- |" + if [ "${DIRECTORY}" = "true" ] ; then + echo "| Directory | File | Size | Image |" + echo "| --- | --- | --: | --- |" + else + echo "| File | Size | Image |" + echo "| --- | --: | --- |" + fi while read -r file bytes image ; do size=$( numfmt --to=iec-i --suffix=B --format=%.1f "${bytes}" ) - echo "| \`${file}\` | ${size} | \`${image}\` |" - done < "${RUNNER_TEMP}/published.txt" + row="| \`${file}\` | ${size} | \`${image}\` |" + if [ "${DIRECTORY}" = "true" ] ; then + # e.g. ghcr.io/componentized/logging/levels:0.3.1@sha256:... -> componentized/logging/levels + path="${image#*/}" + path="${path%%[:@]*}" + namespace="${path%%/*}" + name="${path#*/}" + name="${name//\//-}" + # the directory's kind: the interface is a package, a component composed with wac + # is a composition, e.g. levels.debug.wasm from components/levels/levels.wac + component="${file%.wasm}" + component="${component%.debug}" + if [ "${file}" = "interface.wasm" ] ; then + kind=package + elif [ -f "components/${component}/${component}.wac" ] || [ -f "components/${component}/${component}.plug" ] ; then + kind=composition + else + kind=component + fi + id="${namespace}:${name}@${VERSION}" + # each icon is 26 by 26, a 16 by 16 icon with a margin for its badges, centered on the + # text. GitHub drops the styles that would keep the id on one line, so a word joiner + # holds the id to its icon and its hyphens are non-breaking hyphens, the link and its + # title have the id as it is. The link has GitHub's color, GitHub drops the styles + # that would give it the directory's. + picture="\"${kind}\"" + label="${id//-/$'\xe2\x80\x91'}" + row="| ${picture}"$'\xe2\x81\xa0'"${label} ${row}" + fi + echo "${row}" + done < "${published}" } > "${RUNNER_TEMP}/release-notes.md" cat "${RUNNER_TEMP}/release-notes.md" + - name: Pack components.tar with the published SBOMs + # each component released with an SBOM, the one it's published with, see PUBLISHED_SBOM_DIR in + # build/sbom.mk, in place of the build's, which doesn't name its version or image. A file that + # isn't published, e.g. a dep- component, keeps the build's, see build/scripts/pack-components.sh + if: startsWith(github.ref, 'refs/tags/') && env.DRY_RUN != 'true' + run: build/scripts/pack-components.sh target/components target/sbom/published components.tar - name: Draft GitHub Release - if: startsWith(github.ref, 'refs/tags/') && ( env.DRY_RUN != 'true' || github.repository == 'componentized/build' ) + if: startsWith(github.ref, 'refs/tags/') && env.DRY_RUN != 'true' uses: softprops/action-gh-release@v3 with: draft: true body_path: ${{ runner.temp }}/release-notes.md - # the cli archives of a repository with a cli + # the components with their SBOMs, and the cli archives of a repository with a cli files: | components.tar ${{ needs.settings.outputs.cli != '' && 'dist/*' || '' }} diff --git a/build/MANIFEST b/build/MANIFEST index 09b2bef..ebd564c 100644 --- a/build/MANIFEST +++ b/build/MANIFEST @@ -1,22 +1,28 @@ -0edf07b7ec073ce666d847f9c9976ad68822d80d7c1651739459ff27f8b3fa0f .github/workflows/bump-version.yaml -5b2adefd1b6278712f2054c62a9845fee41a717b6977a1202740ac176d0a3d54 .github/workflows/ci.yaml +24d18f2ff9c51cc013d00f1e03b4ed410f1b37972fc74dc442317db568c8443b .github/workflows/bump-version.yaml +fa6939b1b80ed5ea8f365b2a638faac374353bee685a3e272e1925b136e7fc83 .github/workflows/ci.yaml b09c55d4207eb188036d3a7ba118c68b2547e958362d898714408af3a1c4afa6 .github/workflows/release.yaml 0a5da65531ed134a43f0aba94aacccd84707d548c348eb31868365c8c400978a .github/workflows/update-build.yaml f9b6ad1d205adf8198aecdf9130fe149a362cbe805c077f19c17dc5562b60405 build/README.md -10fbbe21746d38d841dbc2ddf94b7daffbecd51715a516c694940b4d79f51067 build/build.mk -4d3b9ec8b5b4f8b58df9997a064d353f8792f1001f58d984ba80998748216a18 build/components.mk +82702fae07fabf9464dc7a684a10a4b0c15010aaf426df71dae9700544746143 build/build.mk +8a6a11425bbf2abd95dda20aad3e5d39a2c7df787ab44423c8807f73c60f0db4 build/completions.jq +26746c18425ae9562be94fbe2d9e86e7bd4799d79fba6d08090ae1717b0798a6 build/components.mk acb1b32ba485536dc0b834cb351f41a6804339e4beab0b0391d149d069724a89 build/local.jq 5560aa0d6be4878992a77441c0631da5ae4d52cc65f52185b2af333f70a58b59 build/pinned.jq -df556e7ce9919c72815db01ac06ef541ecb1b9f920facb51ccbb635d17ee656a build/publish.mk +3677afc3852cbe9748227d3c30992ef4f2768e485f8362387e2420d904a710d2 build/publish.mk +bc5c1a7230a950cac4afd0f7ba62dc4e8e8651b125265f1a9d22e3c93dcb6682 build/sbom.mk 2e98011760ad48ff0d706df309f95a067e0edc82c9ec55292cd2522d4e347c47 build/scripts/bump-version.sh c651f8d58218a8ad6475857a70364e2df9e5607aa066800f19d0b65ec97a02da build/scripts/check-build.sh +a55a79b043ec3c0ae7e8a70b232a24327a5ce45cc79635d77347bd6d638c7fe1 build/scripts/completions.sh 45c5f4b5e7a4525c6da2780687b705536f2a57f40c18eda0ec84015c5c38df3e build/scripts/create-commit.sh -c125f2fdad69e6ad5caa660659b51a420be867fea36cd274aeceac0c10eb1594 build/scripts/publish.sh +28d9caf08b47329f685482ebe570fc1dceb88d4b724e8b22b51e029ff8eaef33 build/scripts/pack-components.sh +b9673e111ec7cd329901a940002b495b8bc4beee81b4a78704a9668651beaebb build/scripts/publish.sh +e6662bcf5b8f5a1adc657edf711d5721d0fc46f4373c48ada1e420db0b6d75d0 build/scripts/sbom-cargo.sh +c7274f7ec1ee029f08e063fa409d9a95bac2267942c328a3f8e2796200db3738 build/scripts/sbom.sh d91382922ff27332373518e782a6f003081db04809b5a87d00d77531d9f95c6b build/scripts/update-build.sh 0477a5e4ee8fdb61e6cf67205c43aafe52be25501b8e9d41e72ce805b5b3c0df build/scripts/wac-deps.sh 58fb46d7754b0a8316350e2733cc27baf2e85502cd26ca36e1091207b10af5e4 build/scripts/wit-canonical.sh 44f65271d65b043e9affcbaddd9e958ecb33a60e945d7ce869e6408925620626 build/sync.mk -c08767afa3a60b96ab908ab8cf2169eb03eeb5947b9d1b9c3dc8444eae52cabc build/tools.mk -d3a8914a14ca9ffae55c2352b72bd86f9b482beef1918c401743a27581bb52f5 build/tools/Cargo.toml +4f7b72906ee6331cec0c227980a8f5d9e2476ccf24fa5dfaccf98e56f64599e3 build/tools.mk +95e67bce1c62e6c403e25e96a59e3fb381d5cc9096de655a97cba19d1f1159c5 build/tools/Cargo.toml dab14a274377b620391d4979812ef34997e07b01ffd6b90e6df3b37131e3a3eb build/tools/lib.rs -7010449b71c86de391f25e32a8bf06419f1a277479108aa31250b8aead56e45d build/wit.mk +991097deae7cbc0072ac84fb4fa0f8c743ee0fafeeee9fc2f38190dac50bda65 build/wit.mk diff --git a/build/VERSION b/build/VERSION index 8c43fb4..82942c3 100644 --- a/build/VERSION +++ b/build/VERSION @@ -1 +1 @@ -v0.1.4 +v0.1.6 diff --git a/build/build.mk b/build/build.mk index 1f57898..adb8983 100644 --- a/build/build.mk +++ b/build/build.mk @@ -46,6 +46,7 @@ PUBLISH_CRATES ?= include build/tools.mk include build/wit.mk include build/components.mk +include build/sbom.mk include build/publish.mk include build/sync.mk diff --git a/build/completions.jq b/build/completions.jq new file mode 100644 index 0000000..aaed8ac --- /dev/null +++ b/build/completions.jq @@ -0,0 +1,15 @@ +# generates target/tools/completions from `cargo metadata --no-deps` of build/tools/Cargo.toml, +# followed by that of the repository's tools/Cargo.toml when it has one, slurped, see build/tools.mk. +# Each line is a binary and the arguments that print its completions, quoted for the shell, e.g. +# `'wasm-tools' 'completion'`, read by build/scripts/completions.sh. A binary the repository lists +# overrides the build's, one listed with no arguments has none. +def completions($manifest): + (.packages[0].metadata.completions // {}) + | to_entries[] + | if (.value | type) == "array" and all(.value[]; type == "string") then . + else error("\(.key) in [package.metadata.completions] in \($manifest) is not a list of arguments") end; +([.[0] | completions("build/tools/Cargo.toml")] + [.[1] // empty | completions("tools/Cargo.toml")]) +| reduce .[] as $binary ({}; .[$binary.key] = $binary.value) +| to_entries | sort_by(.key)[] +| select(.value != []) +| [.key] + .value | @sh diff --git a/build/components.mk b/build/components.mk index e94505b..2c22f6e 100644 --- a/build/components.mk +++ b/build/components.mk @@ -63,8 +63,14 @@ clean-components: clean-wit .PHONY: components ## Build the interface and each component into target/components, `make components/` builds one components: ${COMPONENTS_DIR}/interface.wasm $(foreach component,$(COMPONENTS),${COMPONENTS_DIR}/$(component)/$(component).wasm ${COMPONENTS_DIR}/$(component)/$(component).debug.wasm) +# the components whose release and debug builds may have different WIT, not checked by `make +# check-components`, e.g. a wasm32-wasip3 component whose release build wasm-opt optimizes, see +# COMPONENT_OPTIMIZE, dropping imports of the standard library the debug build keeps: +# `CHECK_COMPONENTS_SKIP := gate`. `make check-components/` still checks one. +CHECK_COMPONENTS_SKIP ?= + .PHONY: check-components ## Check the release and debug build of each component have the same WIT, `make check-components/` checks one -check-components: $(foreach component,$(COMPONENTS),check-components/$(component)) +check-components: $(foreach component,$(filter-out $(CHECK_COMPONENTS_SKIP),$(COMPONENTS)),check-components/$(component)) .PHONY: validate-components ## Validate the release and debug build of each component, `make validate-components/` checks one validate-components: $(foreach component,$(COMPONENTS),validate-components/$(component)) diff --git a/build/publish.mk b/build/publish.mk index a675543..5f42df8 100644 --- a/build/publish.mk +++ b/build/publish.mk @@ -5,15 +5,19 @@ DRY_RUN ?= false # append each published file, its size in bytes and its image to this file, e.g. `gate.wasm 1234567 ghcr.io/componentized/http/gate:0.1.0@sha256:...` PUBLISH_LOG ?= +# publish the interface, interface.wasm, `false` for a repository whose interface isn't one to depend +# on, e.g. componentized/build, whose interface is there to test the build +PUBLISH_INTERFACE ?= true + # the files that can be published, e.g. gate.wasm, published from target/components/gate/gate.wasm. # Components are not published when they are pulled from elsewhere, `dep-`, built here for use by # other components, `internal-`, or tests, `test-`. -PUBLISH_FILES := interface.wasm $(foreach component,$(filter-out dep-% internal-% test-%,$(COMPONENTS)),$(component).wasm $(component).debug.wasm) +PUBLISH_FILES := $(if $(filter true,$(PUBLISH_INTERFACE)),interface.wasm) $(foreach component,$(filter-out dep-% internal-% test-%,$(COMPONENTS)),$(component).wasm $(component).debug.wasm) .PHONY: publish ## Publish each component in the target/components directory, `make publish-` publishes one, e.g. publish-gate.wasm publish: $(addprefix publish-,$(PUBLISH_FILES)) .PHONY: $(addprefix publish-,$(PUBLISH_FILES)) -$(addprefix publish-,$(PUBLISH_FILES)): publish-%: | $(call tool,wkg) - @VERSION="$(VERSION)" REPOSITORY="$(REPOSITORY)" COMPONENTS_DIR="$(COMPONENTS_DIR)" SIGN="$(SIGN)" PUBLISH_LOG="$(PUBLISH_LOG)" DRY_RUN="$(DRY_RUN)" \ +$(addprefix publish-,$(PUBLISH_FILES)): publish-%: | $(call tool,wkg) $(COSIGN_INSTALLED) + @COSIGN="$(COSIGN)" VERSION="$(VERSION)" REPOSITORY="$(REPOSITORY)" COMPONENTS_DIR="$(COMPONENTS_DIR)" SIGN="$(SIGN)" PUBLISH_LOG="$(PUBLISH_LOG)" SBOM_DIR="$(PUBLISHED_SBOM_DIR)" DRY_RUN="$(DRY_RUN)" \ build/scripts/publish.sh $* diff --git a/build/sbom.mk b/build/sbom.mk new file mode 100644 index 0000000..2a87f16 --- /dev/null +++ b/build/sbom.mk @@ -0,0 +1,93 @@ +# the SBOM of each component and of the interface, CycloneDX JSON beside the wasm file it describes, +# e.g. target/components/greeter/greeter.cdx.json for greeter.wasm and greeter.debug.cdx.json for +# greeter.debug.wasm, built with the components and published with them, see build/scripts/sbom.sh + +# the SBOMs cargo-cyclonedx generates for the packages of the workspace, a directory for each target +CARGO_SBOM_DIR := target/sbom/cargo + +# the SBOM of each file published, with its version and image, see build/scripts/publish.sh, laid out +# like the components directory, e.g. greeter/greeter.debug.cdx.json for greeter.debug.wasm. The CI +# workflow packs them with the components into the components.tar of the release it drafts, in place +# of the SBOMs of the build. +PUBLISHED_SBOM_DIR := target/sbom/published + +# the time the SBOMs are generated at, the time of the commit, so the SBOMs of a commit are the same +# each time they are generated +SBOM_EPOCH := $(or $(shell git log -1 --format=%ct 2> /dev/null),0) + +# the version of the cli a component is generated with, a local tool's is its package's version, e.g. +# `$(call tool_crate_version,componentized-constants-cli)` +tool_crate_version = $(if $(filter $(1),$(LOCAL_TOOLS)),$(shell cargo pkgid -p $(1) | sed 's/.*[\#@]//'),$(call tool_version,$(1))) + +.PHONY: sboms ## Generate the SBOM of the interface and of each component, built with them by `make components` +sboms: ${COMPONENTS_DIR}/interface.cdx.json $(foreach component,$(COMPONENTS),${COMPONENTS_DIR}/$(component)/$(component).cdx.json ${COMPONENTS_DIR}/$(component)/$(component).debug.cdx.json) + +components: sboms + +.PHONY: clean-sboms ## Remove the SBOMs cargo-cyclonedx generated and those published, `make clean-components` removes the others +clean-sboms: + rm -rf $(CARGO_SBOM_DIR) $(PUBLISHED_SBOM_DIR) + +clean-components: clean-sboms + +# the SBOM of each package of the workspace built for the target, e.g. target/sbom/cargo/wasm32-wasip2. +# A stamp, the directory isn't made newer when an SBOM in it is replaced. +$(CARGO_SBOM_DIR)/%.stamp: Cargo.toml Cargo.lock $(shell find . -name Cargo.toml -not -path './target/*' -not -path './build/tools/*' -not -path './tools/*') build/scripts/sbom-cargo.sh | $(call tool,cargo-cyclonedx) + CARGO_CYCLONEDX=$(CARGO_CYCLONEDX) SOURCE_DATE_EPOCH=$(SBOM_EPOCH) build/scripts/sbom-cargo.sh $* $(CARGO_SBOM_DIR)/$* + @touch $@ + +# `$(call sbom,,,,)` +sbom = SOURCE_DATE_EPOCH=$(SBOM_EPOCH) build/scripts/sbom.sh $(1) $(2) $(3) $(4) + +define BUILD_SBOM + +ifneq ($(or $(wildcard components/$1/wit/$1.constants.wit),$(wildcard components/$1/$1.properties)),) + +# a component generated with a cli embeds the cli's code, e.g. the constants cli's +SBOM_CLI_$1 := $(if $(wildcard components/$1/wit/$1.constants.wit),componentized-constants-cli,componentized-static-config-cli) + +${COMPONENTS_DIR}/$1/$1.cdx.json ${COMPONENTS_DIR}/$1/$1.debug.cdx.json: ${COMPONENTS_DIR}/$1/%.cdx.json: ${COMPONENTS_DIR}/$1/%.wasm build/scripts/sbom.sh + $$(call sbom,generated,$$<,$$@,$$(SBOM_CLI_$1) $$(call tool_crate_version,$$(SBOM_CLI_$1))) + +else ifneq ($(wildcard components/$1/$1.wac),) + +${COMPONENTS_DIR}/$1/$1.cdx.json: ${COMPONENTS_DIR}/$1/$1.wasm $$(foreach component,$$(WAC_DEPS_$1),$${COMPONENTS_DIR}/$$(component)/$$(component).cdx.json) build/scripts/sbom.sh + $$(call sbom,composition,$$<,$$@,$$(foreach component,$$(WAC_DEPS_$1),$${COMPONENTS_DIR}/$$(component)/$$(component).cdx.json)) + +${COMPONENTS_DIR}/$1/$1.debug.cdx.json: ${COMPONENTS_DIR}/$1/$1.debug.wasm $$(foreach component,$$(WAC_DEPS_$1),$${COMPONENTS_DIR}/$$(component)/$$(component).debug.cdx.json) build/scripts/sbom.sh + $$(call sbom,composition,$$<,$$@,$$(foreach component,$$(WAC_DEPS_$1),$${COMPONENTS_DIR}/$$(component)/$$(component).debug.cdx.json)) + +else ifneq ($(wildcard components/$1/$1.plug),) + +${COMPONENTS_DIR}/$1/$1.cdx.json: ${COMPONENTS_DIR}/$1/$1.wasm $$(foreach component,$$(PLUG_COMPONENTS_$1),$${COMPONENTS_DIR}/$$(component)/$$(component).cdx.json) build/scripts/sbom.sh + $$(call sbom,composition,$$<,$$@,$$(foreach component,$$(PLUG_COMPONENTS_$1),$${COMPONENTS_DIR}/$$(component)/$$(component).cdx.json)) + +${COMPONENTS_DIR}/$1/$1.debug.cdx.json: ${COMPONENTS_DIR}/$1/$1.debug.wasm $$(foreach component,$$(PLUG_COMPONENTS_$1),$${COMPONENTS_DIR}/$$(component)/$$(component).debug.cdx.json) build/scripts/sbom.sh + $$(call sbom,composition,$$<,$$@,$$(foreach component,$$(PLUG_COMPONENTS_$1),$${COMPONENTS_DIR}/$$(component)/$$(component).debug.cdx.json)) + +else ifneq ($(wildcard components/$1/$1.wkg),) + +# the image the release build is pulled from is the first line of the .wkg file, the debug build's +# the last. cosign verifies the SBOM attested to it, the base of its SBOM. +${COMPONENTS_DIR}/$1/$1.cdx.json: ${COMPONENTS_DIR}/$1/$1.wasm components/$1/$1.wkg build/scripts/sbom.sh | $(COSIGN_INSTALLED) + COSIGN=$(COSIGN) $$(call sbom,oci,$$<,$$@,$$(shell head -1 components/$1/$1.wkg)) + +${COMPONENTS_DIR}/$1/$1.debug.cdx.json: ${COMPONENTS_DIR}/$1/$1.debug.wasm components/$1/$1.wkg build/scripts/sbom.sh | $(COSIGN_INSTALLED) + COSIGN=$(COSIGN) $$(call sbom,oci,$$<,$$@,$$(shell tail -1 components/$1/$1.wkg)) + +else ifneq ($(wildcard components/$1/Cargo.toml),) + +# the release and debug builds depend on the same crates. A wasm32-wasip3 component links the +# wasi-libc of the wasi-sdk sysroot or the one built from WASI_LIBC_VERSION, see build/tools.mk. +${COMPONENTS_DIR}/$1/$1.cdx.json ${COMPONENTS_DIR}/$1/$1.debug.cdx.json: ${COMPONENTS_DIR}/$1/%.cdx.json: ${COMPONENTS_DIR}/$1/%.wasm $(CARGO_SBOM_DIR)/$(call component_target,$1).stamp build/scripts/sbom.sh | $(call tool,wasm-tools) $(if $(filter wasm32-wasip3,$(call component_target,$1)),$(WASI_SDK) $(WASI_LIBC)) + WASM_TOOLS=$(WASM_TOOLS) WASI_SDK_PATH=$(WASI_SDK_PATH) WASI_LIBC_VERSION=$(WASI_LIBC_VERSION) WASI_LIBC_WASI_VERSION=$(WASI_LIBC_WASI_VERSION) \ + $$(call sbom,cargo,$$<,$$@,$(CARGO_SBOM_DIR)/$(call component_target,$1)/$1.cdx.json $(call component_target,$1)) + +endif + +endef + +$(foreach component,$(COMPONENTS),$(eval $(call BUILD_SBOM,$(component)))) + +${COMPONENTS_DIR}/interface.cdx.json: ${COMPONENTS_DIR}/interface.wasm wkg.lock build/scripts/sbom.sh + $(call sbom,interface,$<,$@,wkg.lock) diff --git a/build/scripts/completions.sh b/build/scripts/completions.sh new file mode 100644 index 0000000..ae31716 --- /dev/null +++ b/build/scripts/completions.sh @@ -0,0 +1,40 @@ +# shellcheck shell=bash +# Registers the shell completions of the installed tools, sourced by bash or zsh at startup once the +# tools are on the PATH, e.g. in ~/.bashrc: +# +# PATH="$(make -s tools-path):${PATH}" +# source /path/to/repository/build/scripts/completions.sh +# +# The tools that have completions, and how each prints them, are listed in +# [package.metadata.completions] of build/tools/Cargo.toml and the repository's tools/Cargo.toml, +# generated into target/tools/completions by `make tools`. Generated as each shell starts, so a tool +# installed or bumped since completes in new shells. A tool that isn't installed is skipped, as is +# one that fails to print its completions. + +# the arguments are the ones each line of completions sets +# shellcheck disable=SC2120 +__componentized_completions() { + local script completions shell line + if [ -n "${ZSH_VERSION:-}" ]; then + # zsh's path of the sourced script, BASH_SOURCE in bash + # shellcheck disable=SC2296 + script="${(%):-%x}" + shell=zsh + else + script="${BASH_SOURCE[0]}" + shell=bash + fi + completions="$(cd "$(dirname "$script")/../.." && pwd)/target/tools/completions" + [ -f "$completions" ] || return 0 + while IFS= read -r line; do + # the binary and its arguments, quoted by build/completions.jq + eval "set -- $line" + command -v "$1" > /dev/null 2>&1 || continue + # only a script the tool printed, one that fails may print its usage to stdout, which isn't + # run, and none reads the terminal, which would hang the shell + line=$("$@" "$shell" < /dev/null 2> /dev/null) || continue + [ -n "$line" ] && eval "$line" + done < "$completions" +} +__componentized_completions +unset -f __componentized_completions diff --git a/build/scripts/pack-components.sh b/build/scripts/pack-components.sh new file mode 100755 index 0000000..84d527b --- /dev/null +++ b/build/scripts/pack-components.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash + +# Pack the components with an SBOM for each, the SBOM it's published with when it is, into a tar, e.g. +# the components.tar of a release. +# +# build/scripts/pack-components.sh +# +# e.g. `build/scripts/pack-components.sh target/components target/sbom/published components.tar`. The +# published SBOMs are laid out like the components directory, see build/scripts/publish.sh. Each wasm +# file is packed with, beside it as .cdx.json: +# +# - the SBOM it's published with, naming its version and image, e.g. greeter.wasm's +# - for a debug build not published as it's identical to the release build, the release build's +# published SBOM, it's the same file, e.g. defaults.debug.wasm's is defaults.wasm's +# - otherwise the SBOM of the build, for a file that isn't published, e.g. a component pulled with +# wkg, whose SBOM is the one it's published with where cosign verifies it, see +# build/scripts/sbom.sh, or an internal- or test- component +# +# The components directory isn't changed, the tar is packed from a copy of it. + +set -euo pipefail + +components="${1:-}" +published="${2:-}" +tar="${3:-}" +if [[ -z "$components" || -z "$published" || -z "$tar" ]]; then + echo "usage: $0 , e.g. target/components target/sbom/published components.tar" >&2 + exit 1 +fi + +staging=$(mktemp -d) +trap 'rm -rf "$staging"' EXIT +cp -R "${components}/." "$staging" + +while IFS= read -r wasm; do + file="${wasm#./}" + sbom="${file%.wasm}.cdx.json" + release="${file%.debug.wasm}.wasm" + if [[ -f "${published}/${sbom}" ]]; then + cp "${published}/${sbom}" "${staging}/${sbom}" + echo "${file}: the SBOM it's published with" + elif [[ "$file" == *.debug.wasm && -f "${published}/${release%.wasm}.cdx.json" ]] \ + && cmp -s "${staging}/${file}" "${staging}/${release}"; then + cp "${published}/${release%.wasm}.cdx.json" "${staging}/${sbom}" + echo "${file}: the SBOM ${release} is published with, it's the same file" + elif [[ -f "${staging}/${sbom}" ]]; then + echo "${file}: the SBOM of the build, it isn't published" + else + echo "${file}: no SBOM" >&2 + exit 1 + fi +done < <(cd "$staging" && find . -name '*.wasm' | sort) + +tar -cf "$tar" -C "$staging" . diff --git a/build/scripts/publish.sh b/build/scripts/publish.sh index 407b173..2f7f365 100755 --- a/build/scripts/publish.sh +++ b/build/scripts/publish.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash -# Publish a built component to an OCI registry, and sign it with cosign. +# Publish a built component to an OCI registry, sign it with cosign, and attest its SBOM. # # VERSION= REPOSITORY= build/scripts/publish.sh # @@ -11,6 +11,11 @@ # `_debug` suffix. A debug build identical to the release build adds nothing, e.g. components # without debug info, and is not published. # +# The SBOM built beside the file, e.g. gate.cdx.json for gate.wasm, see build/scripts/sbom.sh, names +# the component it describes, by the directory's id of the package, its version and its image, and is +# attested to the image with cosign, a signed CycloneDX attestation, `cosign verify-attestation --type +# cyclonedx` verifies it. +# # interface.wasm -> ${REPOSITORY}:0.1.0 # gate.wasm -> ${REPOSITORY}/gate:0.1.0 # gate.debug.wasm -> ${REPOSITORY}/gate:0.1.0_debug @@ -25,6 +30,10 @@ # e.g. to a local registry # PUBLISH_LOG append the published file, its size in bytes and its image to this file, e.g. # `gate.wasm 1234567 ghcr.io/componentized/http/gate:0.1.0@sha256:...` +# COSIGN the cosign binary, defaults to cosign on the PATH +# SBOM_DIR the directory the SBOM published with the file is written to, laid out like the +# components directory, e.g. gate/gate.debug.cdx.json for gate.debug.wasm and +# interface.cdx.json for interface.wasm, defaults to target/sbom/published # DRY_RUN `true` to show what would be published without pushing or signing anything, # the image is logged with a `dry-run` digest @@ -43,6 +52,8 @@ GITHUB_REPOSITORY="${GITHUB_REPOSITORY:-componentized/$(basename "$(git rev-pars COMPONENTS_DIR="${COMPONENTS_DIR:-target/components}" SIGN="${SIGN:-true}" PUBLISH_LOG="${PUBLISH_LOG:-}" +SBOM_DIR="${SBOM_DIR:-target/sbom/published}" +COSIGN="${COSIGN:-cosign}" DRY_RUN="${DRY_RUN:-false}" component="${file%.wasm}" @@ -50,14 +61,18 @@ component="${component%.debug}" debug="" [[ "$file" == *.debug.wasm ]] && debug=true +# the directory's id of the package, e.g. componentized:http for the interface of componentized/http +# and componentized:http-gate for its gate component if [[ "$file" == interface.wasm ]]; then component_file="$file" - title="${GITHUB_REPOSITORY/\//:}" + id="${GITHUB_REPOSITORY/\//:}" else component_file="${component}/${file}" - title="${GITHUB_REPOSITORY/\//:}-${component}" + id="${GITHUB_REPOSITORY/\//:}-${component}" fi +title="$id" [[ -n "$debug" ]] && title="${title} (debug)" +sbom="${COMPONENTS_DIR}/${component_file%.wasm}.cdx.json" if [[ -n "$debug" ]] && cmp -s "${COMPONENTS_DIR}/${component_file}" "${COMPONENTS_DIR}/${component}/${component}.wasm"; then echo "Not publishing ${file} as it is identical to ${component}.wasm" @@ -121,10 +136,34 @@ if [[ -n "$PUBLISH_LOG" ]]; then echo "${file} ${size} ${image}@${digest}" >> "$PUBLISH_LOG" fi +# the SBOM of the component published, the component already named by its id, with its version and +# image, e.g. pkg:oci/gate@sha256%3A...?repository_url=ghcr.io/componentized/http/gate&tag=0.1.0 +published_sbom="${SBOM_DIR}/${component_file%.wasm}.cdx.json" +mkdir -p "$(dirname "$published_sbom")" +repository="${image%:*}" +purl="pkg:oci/${repository##*/}" +[[ "$digest" == sha256:* ]] && purl="${purl}@${digest/:/%3A}" +purl="${purl}?repository_url=${repository}&tag=${tag}" +jq \ + --arg version "${component_version#v}" \ + --arg purl "$purl" \ + --arg description "$description" \ + --arg source "https://github.com/${GITHUB_REPOSITORY}.git" \ + --arg url "$url" \ + --arg revision "$revision" \ + '.metadata.component += { + version: $version, + description: $description, + purl: $purl, + licenses: [{expression: "Apache-2.0"}], + externalReferences: [{type: "vcs", url: $source, comment: "revision \($revision)"}, {type: "website", url: $url}] + }' "$sbom" > "$published_sbom" + if [[ "$DRY_RUN" == true ]]; then - echo "Not signing ${image}@${digest}, DRY_RUN=${DRY_RUN}" + echo "Not signing ${image}@${digest}, nor attesting its SBOM ${published_sbom}, DRY_RUN=${DRY_RUN}" elif [[ "$SIGN" == true ]]; then - cosign sign --yes "${image}@${digest}" + "$COSIGN" sign --yes "${image}@${digest}" + "$COSIGN" attest --yes --type cyclonedx --predicate "$published_sbom" "${image}@${digest}" else - echo "Not signing ${image}@${digest}, SIGN=${SIGN}" + echo "Not signing ${image}@${digest}, nor attesting its SBOM ${published_sbom}, SIGN=${SIGN}" fi diff --git a/build/scripts/sbom-cargo.sh b/build/scripts/sbom-cargo.sh new file mode 100755 index 0000000..986f13b --- /dev/null +++ b/build/scripts/sbom-cargo.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash + +# Generate the CycloneDX SBOM of each package of the cargo workspace, built for a target, with +# cargo-cyclonedx. +# +# CARGO_CYCLONEDX= build/scripts/sbom-cargo.sh +# +# Writes /.cdx.json for each package of the workspace, e.g. +# target/sbom/cargo/wasm32-wasip2/greeter.cdx.json, the dependencies the package has built for the +# target, without the build dependencies. build/scripts/sbom.sh makes the SBOM of a component from +# its package's. cargo-cyclonedx writes the SBOM of each package beside its Cargo.toml, under a name of +# its own for each target so that two targets can be generated at once, and they're moved to . +# +# CARGO_CYCLONEDX the cargo-cyclonedx binary, run as `$CARGO_CYCLONEDX cyclonedx` +# SOURCE_DATE_EPOCH the time the SBOMs are generated at, e.g. the time of the commit, for SBOMs that +# are the same each time they are generated + +set -euo pipefail + +cd "$(dirname "$0")/../.." + +target="${1:-}" +dir="${2:-}" +if [[ -z "$target" || -z "$dir" ]]; then + echo "usage: $0 , e.g. wasm32-wasip2 target/sbom/cargo/wasm32-wasip2" >&2 + exit 1 +fi +: "${CARGO_CYCLONEDX:?CARGO_CYCLONEDX is undefined}" + +# the name of each package's SBOM beside its Cargo.toml, cargo-cyclonedx adds `.json` +name=".sbom-${target}" + +# the name and directory of each package of the workspace +packages=$( + cargo metadata --no-deps --format-version 1 \ + | jq -r '.workspace_members as $members | .packages[] | select(.id | IN($members[])) | "\(.name)\t\(.manifest_path | rtrimstr("/Cargo.toml"))"' +) + +# remove what's left beside the packages' Cargo.toml when generating fails +trap 'while IFS=$'"'"'\t'"'"' read -r _ path; do rm -f "${path}/${name}.json"; done <<< "$packages"' EXIT + +"$CARGO_CYCLONEDX" cyclonedx \ + --manifest-path Cargo.toml \ + --format json \ + --spec-version 1.6 \ + --target "$target" \ + --no-build-deps \ + --override-filename "$name" \ + --quiet + +mkdir -p "$dir" +while IFS=$'\t' read -r package path; do + mv "${path}/${name}.json" "${dir}/${package}.cdx.json" +done <<< "$packages" diff --git a/build/scripts/sbom.sh b/build/scripts/sbom.sh new file mode 100755 index 0000000..cb70afd --- /dev/null +++ b/build/scripts/sbom.sh @@ -0,0 +1,351 @@ +#!/usr/bin/env bash + +# Generate the CycloneDX SBOM of a component the build makes, or of the interface, from how it's made. +# +# build/scripts/sbom.sh cargo a component built with cargo +# build/scripts/sbom.sh composition ... composed or plugged with wac +# build/scripts/sbom.sh generated generated by a cli, e.g. constants +# build/scripts/sbom.sh oci pulled with wkg, e.g. a dep- component +# build/scripts/sbom.sh interface the interface, built with wkg +# +# The SBOM describes the wasm file as its component, `metadata.component`, by its SHA-256, the digest +# of the layer it's published as, and lists what it's made from: +# +# cargo the package and the crates it depends on built for its target, from the SBOM +# build/scripts/sbom-cargo.sh generated for the package, the Rust standard library of +# the toolchain, by the commit of rustc, and the wasi-libc it links for a wasm32-wasi* +# target: for wasm32-wasip3 the wasi-libc of the wasi-sdk sysroot, or the one built from +# WASI_LIBC_VERSION, otherwise the wasi-libc bundled with the standard library. Each +# adapter the component embeds, e.g. wasi_snapshot_preview1 embedded by +# wasm-component-ld or `wasm-tools component new --adapt`, by its SHA-256 +# composition the components it's composed from, each with what it's made from, from their SBOMs +# generated the crate of the cli it's generated with, e.g. componentized-constants-cli, whose +# code it embeds +# oci what the SBOM attested to the image it's pulled from says, verified with cosign, or +# else nothing, it is the image, named by its purl and OCI coordinates +# interface the WIT packages it depends on, from wkg.lock +# +# The component is named by the directory's id of the package it's published as, e.g. +# componentized:build-greeter for greeter.wasm and greeter.debug.wasm of componentized/build, +# componentized:build for the interface, as build/scripts/publish.sh names it, and referenced as +# `component:`, e.g. component:componentized:build-greeter. A component pulled +# with wkg is named after the image it's pulled from, e.g. componentized:logging-to-stderr for +# ghcr.io/componentized/logging/to-stderr. Its version and image are known when it's published, +# build/scripts/publish.sh adds them. +# +# GITHUB_REPOSITORY the GitHub repository the components are built from, e.g. componentized/http, +# defaults to the componentized repository named after the checkout +# COSIGN the cosign binary, to verify the SBOM attested to an image a component is +# pulled from, defaults to cosign on the PATH, without it the SBOM is made from +# the image alone +# SOURCE_DATE_EPOCH the time the SBOM is generated at, e.g. the time of the commit, for an SBOM +# that is the same each time it is generated, defaults to now +# WASM_TOOLS the wasm-tools binary, to find the adapters a component embeds, defaults to +# wasm-tools on the PATH +# WASI_SDK_PATH the wasi-sdk a wasm32-wasip3 component is linked with, see build/tools.mk +# WASI_LIBC_VERSION the wasi-libc a wasm32-wasip3 component links when built from source, a +# commit or tag, empty for the wasi-sdk sysroot's +# WASI_LIBC_WASI_VERSION the WASI 0.3 version the wasi-libc built from WASI_LIBC_VERSION was rewritten +# to import + +set -euo pipefail + +cd "$(dirname "$0")/../.." + +kind="${1:-}" +wasm="${2:-}" +out="${3:-}" +if [[ -z "$kind" || -z "$wasm" || -z "$out" ]]; then + echo "usage: $0 ..., e.g. cargo target/components/greeter/greeter.wasm target/components/greeter/greeter.cdx.json target/sbom/cargo/wasm32-wasip2/greeter.cdx.json" >&2 + exit 1 +fi +shift 3 + +component=$(basename "$wasm" .wasm) +component="${component%.debug}" +# the directory's id of the package, as build/scripts/publish.sh names it +GITHUB_REPOSITORY="${GITHUB_REPOSITORY:-componentized/$(basename "$(git rev-parse --show-toplevel)")}" +if [[ "$kind" == interface ]]; then + name="${GITHUB_REPOSITORY/\//:}" +else + name="${GITHUB_REPOSITORY/\//:}-${component}" +fi +sha256=$( (sha256sum "$wasm" 2> /dev/null || shasum -a 256 "$wasm") | cut -d' ' -f1) +epoch="${SOURCE_DATE_EPOCH:-$(date +%s)}" + +# the SBOM of the component, made of what's given as $components, $dependencies, what the component +# depends on directly as $depends_on, and the tools it's generated with as $tools +bom=' + {type: "library", "bom-ref": "component:\($name)", name: $name, hashes: [{alg: "SHA-256", content: $sha256}]} as $component + | { + bomFormat: "CycloneDX", + specVersion: "1.6", + version: 1, + metadata: { + timestamp: ($epoch | tonumber | todate), + tools: {components: $tools}, + component: ($component + $root) + }, + components: $components, + dependencies: ([{ref: $component["bom-ref"], dependsOn: $depends_on}] + $dependencies) + } +' + +case "$kind" in + cargo) + package_sbom="${1:?the SBOM of the package is undefined}" + target="${2:?the target the component is built for is undefined}" + + # the Rust standard library, of the toolchain the repository pins, by the commit of rustc + rustc=$(rustc -vV) + rust_release=$(sed -n 's/^release: //p' <<< "$rustc") + rust_commit=$(sed -n 's/^commit-hash: //p' <<< "$rustc") + + # the wasi-libc a wasm32-wasip3 component links, and the wasi-sdk it's linked with, as JSON + wasi_libc=null + wasi_sdk=null + if [[ "$target" == wasm32-wasip3 ]]; then + : "${WASI_SDK_PATH:?WASI_SDK_PATH is undefined, the wasi-sdk a wasm32-wasip3 component is linked with}" + # e.g. `34.0` followed by `wasi-libc: 2e6fb9d8ee0c` + sdk_version=$(head -1 "${WASI_SDK_PATH}/VERSION") + wasi_sdk=$(jq -n --arg version "$sdk_version" '{type: "application", name: "wasi-sdk", version: $version}') + if [[ -n "${WASI_LIBC_VERSION:-}" ]]; then + wasi_libc=$(jq -n --arg version "$WASI_LIBC_VERSION" --arg wasi "${WASI_LIBC_WASI_VERSION:-}" --arg sdk "$sdk_version" '{ + version: $version, + description: "built from source with wasi-sdk \($sdk)", + pedigree: (if $wasi != "" then {notes: "its WASI 0.3 bindings rewritten to import WASI \($wasi)"} else null end) + } | del(..|nulls)') + else + wasi_libc=$(jq -n --arg version "$(sed -n 's/^wasi-libc: //p' "${WASI_SDK_PATH}/VERSION")" --arg sdk "$sdk_version" '{ + version: $version, + description: "the experimental-coop-threads sysroot of wasi-sdk \($sdk)" + }') + fi + elif [[ "$target" == wasm32-wasi* ]]; then + wasi_libc=$(jq -n --arg target "$target" --arg release "$rust_release" '{ + description: "bundled with the Rust standard library for \($target) of rustc \($release)" + }') + fi + + # each adapter the component embeds, a module wit-component names `wit-component:adapter:`, + # by the SHA-256 of its bytes + adapters=$( + "${WASM_TOOLS:-wasm-tools}" metadata show --json "$wasm" \ + | jq -c '.. | objects | select(has("module")) | .module | select((.name // "") | startswith("wit-component:adapter:"))' \ + | while read -r module; do + start=$(jq -r '.range.start' <<< "$module") + end=$(jq -r '.range.end' <<< "$module") + adapter_sha256=$(tail -c +$((start + 1)) "$wasm" | head -c $((end - start)) | (sha256sum 2> /dev/null || shasum -a 256) | cut -d' ' -f1) + jq -c --arg sha256 "$adapter_sha256" '{name: (.name | ltrimstr("wit-component:adapter:")), sha256: $sha256, producers: (.producers // [])}' <<< "$module" + done \ + | jq -s '.' + ) + + # the crates whose code the component can contain, e.g. ["greeter@0.1.0", "wit-bindgen@0.63.0"]: + # the package and its normal dependencies for the target, without the proc-macros and the + # crates only they depend on, e.g. syn and wit-parser, which run as it's compiled + runtime=$( + cargo tree --quiet --locked -p "$component" --target "$target" -e normal,no-proc-macro --prefix none --format '{p}' \ + | sed -E 's/ \(.*//; s/ v/@/' \ + | sort -u \ + | jq -R . | jq -s . + ) + + # cargo-cyclonedx names the package by its path, absolute, it's made relative to the + # repository, e.g. path+file://./components/greeter#0.1.0. The package's targets are dropped, + # the component is built from one of them. A crate the component's code can't contain is + # scoped `excluded`, it's listed, with its version, hashes and licenses, as a crate the + # component is built with rather than one it's made of. + jq --arg name "$name" --arg sha256 "$sha256" --arg epoch "$epoch" --arg root "$PWD" \ + --arg target "$target" --arg rust_release "$rust_release" --arg rust_commit "$rust_commit" \ + --argjson wasi_libc "$wasi_libc" --argjson wasi_sdk "$wasi_sdk" --argjson adapters "$adapters" \ + --argjson runtime "$runtime" ' + walk(if type == "string" then gsub($root; ".") else . end) + | .components |= map(if "\(.name)@\(.version)" | IN($runtime[]) then . else . + {scope: "excluded"} end) + | (.metadata.component | del(.components)) as $package + | "pkg:github/rust-lang/rust@\($rust_commit)" as $rust_purl + | { + type: "library", + "bom-ref": "rust-std:\($rust_commit):\($target)", + name: "rust-std", + version: $rust_release, + description: "the Rust standard library for \($target)", + purl: $rust_purl + } as $rust_std + | (if $wasi_libc == null then null + elif $wasi_libc.version then + {type: "library", "bom-ref": "pkg:github/webassembly/wasi-libc@\($wasi_libc.version)", name: "wasi-libc", purl: "pkg:github/webassembly/wasi-libc@\($wasi_libc.version)"} + $wasi_libc + else + {type: "library", "bom-ref": "wasi-libc:\($rust_commit):\($target)", name: "wasi-libc"} + $wasi_libc + end) as $libc + | [$adapters[] | { + type: "library", + "bom-ref": "adapter:\(.name)@\(.sha256)", + name: .name, + description: "a WASI adapter embedded in the component", + hashes: [{alg: "SHA-256", content: .sha256}], + properties: [.producers[] | .[0] as $field | .[1] | to_entries[] | {name: "producers:\($field):\(.key)", value: .value}] + }] as $adapter_components + | ([.metadata.tools[]? | {type: "application", name, version}] + [$wasi_sdk | values]) as $tools + | {} as $root + | ([$package, $rust_std, ($libc | values)] + $adapter_components + (.components // [])) as $components + | ((.dependencies // []) + + [{ref: $rust_std["bom-ref"], dependsOn: [$libc | values | .["bom-ref"]]}] + + [$libc | values | {ref: .["bom-ref"], dependsOn: []}] + + [$adapter_components[] | {ref: .["bom-ref"], dependsOn: []}]) as $dependencies + | ([$package["bom-ref"], $rust_std["bom-ref"], ($libc | values | .["bom-ref"])] + [$adapter_components[]["bom-ref"]]) as $depends_on + | '"$bom" "$package_sbom" > "$out" + ;; + composition) + if [[ $# -eq 0 ]]; then + echo "the SBOMs of the components composed are undefined" >&2 + exit 1 + fi + # each component composed, with what it's made from, a crate two components depend on is + # listed once + jq -n --arg name "$name" --arg sha256 "$sha256" --arg epoch "$epoch" ' + [inputs] as $sboms + | ([$sboms[].metadata.tools.components[]?] | unique_by([.name, .version])) as $tools + | {} as $root + # a crate one component is made of and another only built with, scoped `excluded`, is + # one the composition is made of + | ([$sboms[] | [.metadata.component] + .components] | add | group_by(.["bom-ref"]) + | map(if any(.[]; .scope != "excluded") then (map(select(.scope != "excluded")) | .[0]) else .[0] end)) as $components + | ([$sboms[].dependencies[]] | unique_by(.ref)) as $dependencies + | [$sboms[].metadata.component["bom-ref"]] as $depends_on + | '"$bom" "$@" > "$out" + ;; + generated) + crate="${1:?the crate of the cli is undefined}" + version="${2:?the version of the cli is undefined}" + jq -n --arg name "$name" --arg sha256 "$sha256" --arg epoch "$epoch" --arg crate "$crate" --arg version "$version" ' + "pkg:cargo/\($crate)@\($version)" as $purl + | [{type: "application", name: $crate, version: $version}] as $tools + | {} as $root + | [{type: "library", "bom-ref": $purl, name: $crate, version: $version, purl: $purl}] as $components + | [{ref: $purl, dependsOn: []}] as $dependencies + | [$purl] as $depends_on + | '"$bom" > "$out" + ;; + oci) + image="${1:?the image is undefined}" + # e.g. ghcr.io/componentized/logging/to-stderr:0.3.1@sha256:... is + # pkg:oci/to-stderr@sha256%3A...?repository_url=ghcr.io/componentized/logging/to-stderr&tag=0.3.1 + repository="${image%%@*}" + digest="" + [[ "$image" == *@* ]] && digest="${image#*@}" + tag="" + if [[ "${repository##*/}" == *:* ]]; then + tag="${repository##*:}" + repository="${repository%:*}" + fi + # the directory's id of the image's package, e.g. componentized:logging-to-stderr for + # ghcr.io/componentized/logging/to-stderr, the registry dropped, then the namespace and the + # rest of the path joined with `-` + path="${repository#*/}" + rest="${path#*/}" + name="${path%%/*}:${rest//\//-}" + # the SBOM published with the image, attested with cosign as build/scripts/publish.sh attests + # it, verified to be signed by a GitHub Actions workflow of the image's org, e.g. + # https://github.com/componentized/... for ghcr.io/componentized/logging/to-stderr. Without + # cosign, a digest, or a verified attestation, e.g. an image published before its SBOM was, + # the SBOM is made from the image alone. + published=null + cosign="${COSIGN:-cosign}" + org="${path%%/*}" + if [[ -z "$digest" ]]; then + echo "not fetching the SBOM of ${image}, it has no digest" >&2 + elif ! command -v "$cosign" > /dev/null; then + echo "not fetching the SBOM attested to ${repository}@${digest}, cosign is not installed" >&2 + elif envelopes=$("$cosign" verify-attestation --type cyclonedx \ + --certificate-identity-regexp "^https://github\.com/${org}/" \ + --certificate-oidc-issuer https://token.actions.githubusercontent.com \ + "${repository}@${digest}" 2> /dev/null) && [[ -n "$envelopes" ]]; then + # each attestation verified is a DSSE envelope of an in-toto statement whose predicate is + # the SBOM, the last is used + published=$(tail -1 <<< "$envelopes" | jq '.payload | @base64d | fromjson | .predicate') + published_sha256=$(jq -r '.metadata.component.hashes[]? | select(.alg == "SHA-256") | .content' <<< "$published") + if [[ -n "$published_sha256" && "$published_sha256" != "$sha256" ]]; then + echo "the SBOM attested to ${repository}@${digest} describes a component with the SHA-256 ${published_sha256}, not ${wasm}'s ${sha256}" >&2 + exit 1 + fi + echo "using the SBOM attested to ${repository}@${digest}" >&2 + else + echo "no SBOM attested to ${repository}@${digest} by a workflow of github.com/${org} verified, the SBOM is made from the image alone" >&2 + fi + + # the image's OCI coordinates: the registry, the repository in it, the tag and the digest, e.g. + # ghcr.io, componentized/logging/to-stderr, 0.3.1 and sha256:..., and the reference it's + # pulled by. The version is the tag's, a debug build's `_debug` tag is version `+debug`, as + # build/scripts/publish.sh tags it, e.g. 0.3.1_debug is 0.3.1+debug. A published SBOM is the + # base: what it says of the component, its version, licenses and what it's made from, is kept, + # and the component's SHA-256, OCI coordinates and the reference to the SBOM are added. + jq -n --arg name "$name" --arg sha256 "$sha256" --arg epoch "$epoch" --arg image "$image" --arg repository "$repository" --arg digest "$digest" --arg tag "$tag" --argjson published "$published" ' + ($repository | split("/") | last) as $last + | "pkg:oci/\($last)\(if $digest != "" then "@\($digest | sub(":"; "%3A"))" else "" end)?repository_url=\($repository)\(if $tag != "" then "&tag=\($tag)" else "" end)" as $purl + | [{type: "application", name: "wkg"}] as $tools + | { + version: (if $tag != "" then $tag | sub("_"; "+") else null end), + purl: $purl, + externalReferences: [{type: "distribution", url: "oci://\($image)", comment: "the OCI image the component is pulled from with wkg"}], + properties: [ + {name: "oci:registry", value: ($repository | split("/") | first)}, + {name: "oci:repository", value: ($repository | split("/") | .[1:] | join("/"))}, + (if $tag != "" then {name: "oci:tag", value: $tag} else empty end), + (if $digest != "" then {name: "oci:digest", value: $digest} else empty end) + ] + } | del(..|nulls) as $root + | [] as $components + | [] as $dependencies + | [] as $depends_on + | '"$bom"' + | if $published == null then . else + . as $local + | $published + | .metadata.timestamp = $local.metadata.timestamp + | .metadata.tools = {components: ([(.metadata.tools | if type == "array" then .[] else .components[]? end)] + $local.metadata.tools.components + [{type: "application", name: "cosign"}] | unique_by(.name))} + | .metadata.component |= ( + .hashes = $local.metadata.component.hashes + | .purl = $local.metadata.component.purl + | .version //= $local.metadata.component.version + | .externalReferences = ((.externalReferences // []) + $local.metadata.component.externalReferences + [{ + type: "bom", + url: "oci://\($repository)@\($digest)", + comment: "the SBOM attested to the image with cosign, the base of this SBOM" + }]) + | .properties = ((.properties // []) + $local.metadata.component.properties) + ) + end + ' > "$out" + ;; + interface) + lock="${1:?the wkg.lock is undefined}" + # each version of each package in wkg.lock, a line of its name, registry, version and digest + packages=$(awk ' + /^\[\[packages\]\]/ { name = ""; registry = "" } + /^name = / { gsub(/"/, "", $3); name = $3 } + /^registry = / { gsub(/"/, "", $3); registry = $3 } + /^version = / && name != "" { gsub(/"/, "", $3); version = $3 } + /^digest = / && name != "" { gsub(/"/, "", $3); print name "\t" registry "\t" version "\t" $3 } + ' "$lock") + jq -n -R --arg name "$name" --arg sha256 "$sha256" --arg epoch "$epoch" ' + [inputs | select(. != "") | split("\t") | {name: .[0], registry: .[1], version: .[2], digest: .[3]}] as $packages + | [{type: "application", name: "wkg"}] as $tools + | {} as $root + | [$packages[] | { + type: "library", + "bom-ref": "wit:\(.name)@\(.version)", + name, + version, + hashes: [{alg: "SHA-256", content: (.digest | ltrimstr("sha256:"))}], + properties: [{name: "wkg:registry", value: .registry}] + }] as $components + | [$components[] | {ref: .["bom-ref"], dependsOn: []}] as $dependencies + | [$components[]["bom-ref"]] as $depends_on + | '"$bom" <<< "$packages" > "$out" + ;; + *) + echo "unknown kind ${kind}, one of cargo, composition, generated, oci or interface" >&2 + exit 1 + ;; +esac diff --git a/build/tools.mk b/build/tools.mk index 97ac85c..91818f5 100644 --- a/build/tools.mk +++ b/build/tools.mk @@ -55,6 +55,18 @@ $(TOOLS_MK): $(TOOLS_MANIFESTS) build/pinned.jq @echo "TOOLS_MANIFESTS_PINNED := $(TOOLS_MANIFESTS)" >> $@.tmp @mv $@.tmp $@ +# the binaries that print shell completions and their arguments, read by build/scripts/completions.sh +# as a shell starts, see [package.metadata.completions] in build/tools/Cargo.toml. Generated with the +# tools, the repository's tools/Cargo.toml is read last, overriding the build's. +TOOLS_COMPLETIONS := target/tools/completions + +tools: $(TOOLS_COMPLETIONS) + +$(TOOLS_COMPLETIONS): $(TOOLS_MANIFESTS) build/completions.jq + @mkdir -p $(@D) + @set -o pipefail; for manifest in $(TOOLS_MANIFESTS); do cargo metadata --manifest-path $$manifest --no-deps --format-version 1; done | jq -rs -f build/completions.jq > $@.tmp + @mv $@.tmp $@ + # the packages of the workspace, generated again when LOCAL_TOOLS changes. The workspace's members may # change without changing Cargo.toml or Cargo.lock, `make clean-tools` generates it again. $(LOCAL_TOOLS_MK): Cargo.toml Cargo.lock $(filter-out $(TOOLS_MK) $(LOCAL_TOOLS_MK),$(MAKEFILE_LIST)) build/local.jq @@ -107,6 +119,31 @@ endef $(foreach name,$(LOCAL_TOOLS),$(eval $(call INSTALL_LOCAL_TOOL,$(name)))) +# cosign, which signs the published components and attests their SBOMs, see build/scripts/publish.sh, +# and verifies the SBOM attested to a component pulled with wkg, see build/scripts/sbom.sh. A binary +# of the release for the host, checked against the release's checksums, run as `$(COSIGN)`. +COSIGN_VERSION := 3.1.4 +COSIGN_HOST := $(or $(word 2,$(subst :, ,$(filter $(shell rustc --print host-tuple):%,aarch64-apple-darwin:darwin-arm64 x86_64-apple-darwin:darwin-amd64 aarch64-unknown-linux-gnu:linux-arm64 x86_64-unknown-linux-gnu:linux-amd64))),unsupported-host) +COSIGN := $(TOOLS_BIN)/cosign +COSIGN_INSTALLED := $(TOOLS_DIR)/.installed/cosign@$(COSIGN_VERSION) + +tools: $(COSIGN_INSTALLED) + +$(COSIGN_INSTALLED): + @mkdir -p $(TOOLS_BIN) $(@D) + @curl -fsSL -o $(COSIGN).download https://github.com/sigstore/cosign/releases/download/v$(COSIGN_VERSION)/cosign-$(COSIGN_HOST) + @expected=$$(curl -fsSL https://github.com/sigstore/cosign/releases/download/v$(COSIGN_VERSION)/cosign_checksums.txt | awk '$$2 == "cosign-$(COSIGN_HOST)" { print $$1 }'); \ + actual=$$( (sha256sum $(COSIGN).download 2> /dev/null || shasum -a 256 $(COSIGN).download) | cut -d' ' -f1); \ + if [ -z "$$expected" ] || [ "$$expected" != "$$actual" ]; then \ + rm -f $(COSIGN).download; \ + echo "cosign-$(COSIGN_HOST) $(COSIGN_VERSION) has the SHA-256 $$actual, not the $${expected:-unknown} of the release's checksums" >&2; \ + exit 1; \ + fi + @chmod +x $(COSIGN).download + @mv $(COSIGN).download $(COSIGN) + @rm -f $(@D)/cosign@* + @touch $@ + ifneq ($(filter wasm32-wasip3,$(COMPONENT_TARGETS)),) # wasi-sdk, for its experimental sysroot with a wasi-libc built for component model cooperative diff --git a/build/tools/Cargo.toml b/build/tools/Cargo.toml index 22a6396..5040e5c 100644 --- a/build/tools/Cargo.toml +++ b/build/tools/Cargo.toml @@ -17,6 +17,8 @@ path = "lib.rs" # the binaries each tool installs, the Makefile runs each by path from a variable named after it, # e.g. `$(WASM_TOOLS)` for `wasm-tools` [package.metadata.bins] +cargo-cyclonedx = ["cargo-cyclonedx"] +componentized-build-cli = ["componentized-build"] componentized-constants-cli = ["constants"] componentized-static-config-cli = ["static-config"] wac-cli = ["wac"] @@ -24,13 +26,24 @@ wasm-opt = ["wasm-opt"] wasm-tools = ["wasm-tools"] wkg = ["wkg"] +# the arguments of the binaries that print their shell completions, the shell's name is appended, +# e.g. `wasm-tools completion bash`, registered by build/scripts/completions.sh. A binary installed +# other than with cargo is listed too, e.g. cosign, see build/tools.mk. A repository adds its own +# in its tools/Cargo.toml, or overrides one with `[]`, e.g. for a tool it builds without them. +[package.metadata.completions] +componentized-build = ["completions"] +cosign = ["completion"] +wasm-tools = ["completion"] + [dependencies] +cargo-cyclonedx = "=0.5.10" +componentized-build-cli = "=0.1.6" componentized-constants-cli = "=0.2.0" componentized-static-config-cli = "=0.3.0" wac-cli = "=0.12.0" wasm-opt = "=0.116.1" wasm-tools = "=1.263.0" -wkg = "=0.16.1" +wkg = "=0.16.2" # not a member of the repository's workspace [workspace] diff --git a/build/wit.mk b/build/wit.mk index 756adc9..419941c 100644 --- a/build/wit.mk +++ b/build/wit.mk @@ -10,6 +10,12 @@ wit_deps = $(patsubst ./%,%,$(1)/wit/deps) WIT_DEPS := $(foreach dir,$(WKG_DIRS),$(call wit_deps,$(dir))) +# the cache wkg fetches packages into, in place of the system cache. wkg caches a package by its +# version, so a dev version fetched again would come from the cache, stale, rather than the registry. +# Exported for every wkg the build runs, absolute as wkg also runs in other directories, e.g. +# `cd components && wkg fetch`. `make clean-wit` removes it. +export WKG_CACHE_DIR := $(abspath target/wkg-cache) + # runs wkg with the arguments in the directory with a wkg.toml, e.g. `$(call wkg,components,fetch)`. # wkg rewrites wkg.lock even when nothing changed, which would leave everything made from the lock # looking out of date, so the lock is put back as it was, with its time, when its content is unchanged @@ -18,9 +24,9 @@ wkg = cp -p $(1)/wkg.lock $(1)/wkg.lock.orig && \ if cmp -s $(1)/wkg.lock.orig $(1)/wkg.lock; then mv $(1)/wkg.lock.orig $(1)/wkg.lock; else rm $(1)/wkg.lock.orig; fi; \ exit $$status -.PHONY: clean-wit ## Remove the fetched wit dependencies, fetched again by `make wit` +.PHONY: clean-wit ## Remove the fetched wit dependencies and the wkg cache, fetched again by `make wit` clean-wit: - rm -rf $(WIT_DEPS) + rm -rf $(WIT_DEPS) $(WKG_CACHE_DIR) .PHONY: wit ## Fetch the wit dependencies of each wkg.toml into its wit/deps wit: $(WIT_DEPS)