Skip to content

SBOM: add a OperatingSystem package to each apk SBOM #2016

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jun 26, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions pkg/build/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -822,6 +822,12 @@ func (b *Build) BuildPackage(ctx context.Context) error {
log.Infof("retrieving workspace from builder: %s", cfg.PodID)
b.WorkspaceDirFS = apkofs.DirFS(b.WorkspaceDir)

// Retreive the os-release information from the runner
releaseData, err := b.Runner.GetReleaseData(ctx, cfg)
if err != nil {
return fmt.Errorf("unable to retrieve release data: %w", err)
}

// Apply xattrs to files in the new in-memory filesystem
for path, attrs := range xattrs {
for attr, data := range attrs {
Expand Down Expand Up @@ -905,14 +911,14 @@ func (b *Build) BuildPackage(ctx context.Context) error {

for _, sp := range b.Configuration.Subpackages {
spSBOM := b.SBOMGroup.Document(sp.Name)
spdxDoc := spSBOM.ToSPDX(ctx)
spdxDoc := spSBOM.ToSPDX(ctx, releaseData)
log.Infof("writing SBOM for subpackage %s", sp.Name)
if err := b.writeSBOM(sp.Name, &spdxDoc); err != nil {
return fmt.Errorf("writing SBOM for %s: %w", sp.Name, err)
}
}

spdxDoc := pSBOM.ToSPDX(ctx)
spdxDoc := pSBOM.ToSPDX(ctx, releaseData)
log.Infof("writing SBOM for %s", pkg.Name)
if err := b.writeSBOM(pkg.Name, &spdxDoc); err != nil {
return fmt.Errorf("writing SBOM for %s: %w", pkg.Name, err)
Expand Down
65 changes: 65 additions & 0 deletions pkg/config/release_data.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Copyright 2025 Chainguard, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package config

import (
"bufio"
"fmt"
"io"
"strings"

apko_build "chainguard.dev/apko/pkg/build"
)

// This is a copy of the ReleaseData related code from apko's pkg/build/sbom.go

// ParseReleaseData parses the information from /etc/os-release
//
// If no os-release file is found, it returns a Data struct with ID set to "unknown".
// TODO: this should best be imported from apko, but right now this function is not
// exported and not ready to be used outside of apko.
func ParseReleaseData(osRelease io.Reader) (*apko_build.ReleaseData, error) {
scanner := bufio.NewScanner(osRelease)

kv := map[string]string{}
for scanner.Scan() {
line := scanner.Text()
if line == "" {
continue
}

if strings.HasPrefix(line, "#") {
continue
}

before, after, ok := strings.Cut(line, "=")
if !ok {
return nil, fmt.Errorf("invalid os-release line: %q", line)
}

kv[before] = strings.Trim(after, "\"")
}

if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("reading os-release: %w", err)
}

return &apko_build.ReleaseData{
ID: kv["ID"],
Name: kv["NAME"],
PrettyName: kv["PRETTY_NAME"],
VersionID: kv["VERSION_ID"],
}, nil
}
24 changes: 24 additions & 0 deletions pkg/container/bubblewrap_runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package container

import (
"archive/tar"
"bufio"
"bytes"
"context"
"fmt"
Expand All @@ -26,6 +27,7 @@ import (
"strings"

"chainguard.dev/melange/internal/logwriter"
"chainguard.dev/melange/pkg/config"
"golang.org/x/sys/unix"

apko_build "chainguard.dev/apko/pkg/build"
Expand Down Expand Up @@ -230,6 +232,28 @@ func (bw *bubblewrap) WorkspaceTar(ctx context.Context, cfg *Config, extraFiles
return nil, nil
}

// GetReleaseData returns the OS information (os-release contents) for the Bubblewrap runner.
func (bw *bubblewrap) GetReleaseData(ctx context.Context, cfg *Config) (*apko_build.ReleaseData, error) {
// Read the os-release through a bubblewrap command
execCmd := bw.cmd(ctx, cfg, false, nil, "cat", "/etc/os-release")

log := clog.FromContext(ctx)
stderr := logwriter.New(log.Warn)
defer stderr.Close()
var buf bytes.Buffer
bufWriter := bufio.NewWriter(&buf)
defer bufWriter.Flush()

execCmd.Stdout = bufWriter
execCmd.Stderr = stderr
err := execCmd.Run()
if err != nil {
return nil, fmt.Errorf("failed to read os-release: %w", err)
}

return config.ParseReleaseData(&buf)
}

type bubblewrapOCILoader struct {
remove bool
guestDir string
Expand Down
55 changes: 55 additions & 0 deletions pkg/container/docker/docker_runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
package docker

import (
"bufio"
"bytes"
"context"
"fmt"
"io"
Expand All @@ -28,6 +30,7 @@ import (
apko_types "chainguard.dev/apko/pkg/build/types"
"chainguard.dev/melange/internal/contextreader"
"chainguard.dev/melange/internal/logwriter"
"chainguard.dev/melange/pkg/config"
mcontainer "chainguard.dev/melange/pkg/container"
"github.com/chainguard-dev/clog"
"github.com/docker/cli/cli/streams"
Expand Down Expand Up @@ -362,6 +365,58 @@ func (dk *docker) WorkspaceTar(ctx context.Context, cfg *mcontainer.Config, extr
return nil, nil
}

// GetReleaseData returns the OS information (os-release contents) for the Docker runner.
func (dk *docker) GetReleaseData(ctx context.Context, cfg *mcontainer.Config) (*apko_build.ReleaseData, error) {
if cfg.PodID == "" {
return nil, fmt.Errorf("pod not running")
}

taskIDResp, err := dk.cli.ContainerExecCreate(ctx, cfg.PodID, container.ExecOptions{
User: cfg.RunAsUID,
Cmd: []string{"cat", "/etc/os-release"},
WorkingDir: runnerWorkdir,
Tty: false,
AttachStderr: true,
AttachStdout: true,
})
if err != nil {
return nil, fmt.Errorf("failed to create exec task to read os-release: %w", err)
}

attachResp, err := dk.cli.ContainerExecAttach(ctx, taskIDResp.ID, container.ExecStartOptions{
Tty: false,
})
if err != nil {
return nil, fmt.Errorf("failed to attach to exec task: %w", err)
}
defer attachResp.Close()

var buf bytes.Buffer
bufWriter := bufio.NewWriter(&buf)
defer bufWriter.Flush()

log := clog.FromContext(ctx)
stderr := logwriter.New(log.Warn)
defer stderr.Close()

_, err = stdcopy.StdCopy(bufWriter, stderr, attachResp.Reader)
if err != nil {
return nil, fmt.Errorf("failed to read os-release output: %w", err)
}

inspectResp, err := dk.cli.ContainerExecInspect(ctx, taskIDResp.ID)
if err != nil {
return nil, fmt.Errorf("failed to get exit code from os-release task: %w", err)
}

if inspectResp.ExitCode != 0 {
return nil, fmt.Errorf("os-release task exited with code %d", inspectResp.ExitCode)
}

// Parse the os-release contents
return config.ParseReleaseData(&buf)
}

type dockerLoader struct {
cli *client.Client
}
Expand Down
30 changes: 30 additions & 0 deletions pkg/container/qemu_runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import (
apko_types "chainguard.dev/apko/pkg/build/types"
apko_cpio "chainguard.dev/apko/pkg/cpio"
"chainguard.dev/melange/internal/logwriter"
"chainguard.dev/melange/pkg/config"
"chainguard.dev/melange/pkg/license"
"github.com/chainguard-dev/clog"
"github.com/charmbracelet/log"
Expand Down Expand Up @@ -458,6 +459,35 @@ func (bw *qemu) WorkspaceTar(ctx context.Context, cfg *Config, extraFiles []stri
return os.Open(outFile.Name())
}

// GetReleaseData returns the OS information (os-release contents) for the Qemu runner.
func (bw *qemu) GetReleaseData(ctx context.Context, cfg *Config) (*apko_build.ReleaseData, error) {
// in case of buildless pipelines we just nop
if cfg.SSHKey == nil {
return nil, nil
}

var buf bytes.Buffer
bufWriter := bufio.NewWriter(&buf)
defer bufWriter.Flush()
err := sendSSHCommand(ctx,
cfg.WorkspaceClient,
cfg,
nil,
nil,
bufWriter,
false,
[]string{"sh", "-c", "cat /etc/os-release"},
)

if err != nil {
clog.FromContext(ctx).Errorf("failed to get os-release: %v", err)
return nil, err
}

// Parse the os-release contents
return config.ParseReleaseData(&buf)
}

type qemuOCILoader struct{}

func (b qemuOCILoader) LoadImage(ctx context.Context, layer v1.Layer, arch apko_types.Architecture, bc *apko_build.Context) (ref string, err error) {
Expand Down
2 changes: 2 additions & 0 deletions pkg/container/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ type Runner interface {
// The io.ReadCloser itself is a tar stream, which can be written to an io.Writer as is,
// or passed to an fs.FS processor
WorkspaceTar(ctx context.Context, cfg *Config, extraFiles []string) (io.ReadCloser, error)
// GetReleaseData returns the release data for the container's OS (os-release)
GetReleaseData(ctx context.Context, cfg *Config) (*apko_build.ReleaseData, error)
}

type Loader interface {
Expand Down
27 changes: 26 additions & 1 deletion pkg/sbom/document.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import (
"hash/fnv"
"time"

apko_build "chainguard.dev/apko/pkg/build"
"chainguard.dev/apko/pkg/sbom/generator/spdx"
"github.com/chainguard-dev/clog"
"sigs.k8s.io/release-utils/version"
)

Expand Down Expand Up @@ -38,8 +40,17 @@ func NewDocument() *Document {
}

// ToSPDX returns the Document converted to its SPDX representation.
func (d Document) ToSPDX(ctx context.Context) spdx.Document {
func (d Document) ToSPDX(ctx context.Context, releaseData *apko_build.ReleaseData) spdx.Document {
spdxPkgs := make([]spdx.Package, 0, len(d.Packages))

// Start off by adding the OperatingSystem package to the list of packages.
if releaseData != nil {
spdxPkgs = append(spdxPkgs, d.createOperatingSystemPackage(releaseData))
} else {
log := clog.FromContext(ctx)
log.Warn("No release data provided, not adding OperatingSystem package to SPDX document")
}

for _, p := range d.Packages {
spdxPkgs = append(spdxPkgs, p.ToSPDX(ctx))
}
Expand Down Expand Up @@ -92,6 +103,20 @@ func (d Document) getSPDXNamespace() string {
return "https://spdx.org/spdxdocs/chainguard/melange/" + hexHash
}

func (d Document) createOperatingSystemPackage(os *apko_build.ReleaseData) spdx.Package {
return spdx.Package{
ID: "SPDXRef-OperatingSystem",
Name: os.ID,
Version: os.VersionID,
FilesAnalyzed: false,
Description: "Operating System",
LicenseConcluded: spdx.NOASSERTION,
LicenseDeclared: spdx.NOASSERTION,
DownloadLocation: spdx.NOASSERTION,
PrimaryPurpose: "OPERATING-SYSTEM",
}
}

// AddPackageAndSetDescribed adds a package to the document and sets it as the
// document's described package.
func (d *Document) AddPackageAndSetDescribed(p *Package) {
Expand Down
Loading