From f868821851d11ff5cf8d1fa216c8fa1c58a32565 Mon Sep 17 00:00:00 2001 From: Michael Vogt Date: Thu, 19 Nov 2026 17:32:22 +0100 Subject: [PATCH 1/5] sysupdate: skip disabled components when updating "systemd-sysupdate update" fails with an error if a component is disabled, so we cannot just indiscriminately call it for every component. We need to parse out (from "systemd-sysupdate components") which components are actually enabled. We didn't notice this issue earlier because .component files were also not being linked into the runtime /etc at all, which will be fixed in a later patch in this series. This should no longer be needed after we switch to the built-in --all-components flag for systemd-sysupdate. Signed-off-by: Michael Vogt Signed-off-by: Aleksa Sarai --- cmd/quarry-sysupdate/utils_sysupdate.go | 32 +++- cmd/quarry-sysupdate/utils_sysupdate_test.go | 155 +++++++++++++++++++ 2 files changed, 185 insertions(+), 2 deletions(-) create mode 100644 cmd/quarry-sysupdate/utils_sysupdate_test.go diff --git a/cmd/quarry-sysupdate/utils_sysupdate.go b/cmd/quarry-sysupdate/utils_sysupdate.go index 6522cd1..12a66a9 100644 --- a/cmd/quarry-sysupdate/utils_sysupdate.go +++ b/cmd/quarry-sysupdate/utils_sysupdate.go @@ -9,6 +9,7 @@ import ( "fmt" "log/slog" "os/exec" + "slices" "go.amutable.dev/quarry/internal/jsonutils" "go.amutable.dev/quarry/internal/systemdcmd" @@ -28,15 +29,42 @@ func listComponents(ctx context.Context) ([]string, error) { return nil, fmt.Errorf("get list of sysupdate components (%s): %w", cmd, err) } + components, err := parseComponents(data) + if err != nil { + return nil, fmt.Errorf("(%s) produced invalid json: %w", cmd, err) + } + return components, nil +} + +// parseComponents returns the components to update from the output of +// "systemd-sysupdate --json=short components". +func parseComponents(data []byte) ([]string, error) { type outputType struct { Default bool `json:"default"` Components []string `json:"components"` + Details []struct { + Name string `json:"name"` + Enabled *bool `json:"enabled,omitzero"` + } `json:"details"` } out, err := jsonutils.Parse[outputType](data) if err != nil { - return nil, fmt.Errorf("(%s) produced invalid json: %w", cmd, err) + return nil, err } - components := out.Components + // "systemd-sysupdate update" fails for disabled components so we need to + // strip those out. + disabled := make(map[string]bool, len(out.Components)) + for _, detail := range out.Details { + if detail.Enabled != nil && !*detail.Enabled { + disabled[detail.Name] = true + } + } + components := slices.DeleteFunc(out.Components, func(component string) bool { + if disabled[component] { + slog.Info("Skipping disabled sysupdate component.", "component", component) + } + return disabled[component] + }) if out.Default { components = append(components, defaultComponent) } diff --git a/cmd/quarry-sysupdate/utils_sysupdate_test.go b/cmd/quarry-sysupdate/utils_sysupdate_test.go new file mode 100644 index 0000000..7b1f0e1 --- /dev/null +++ b/cmd/quarry-sysupdate/utils_sysupdate_test.go @@ -0,0 +1,155 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (C) 2026 Amutable GmbH + +package sysupdate + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestParseComponents(t *testing.T) { + for _, test := range []struct { + name string + data string + want []string + wantErr bool + }{ + { + name: "SkipsDisabled", + // As printed by "systemd-sysupdate --json=short components". + data: `{ + "default": true, + "components": ["cilium", "k8s-cp", "k8s-worker"], + "details": [ + {"description": "Cilium", "enabled": true, "suggested": true, "name": "cilium"}, + {"description": "Kubernetes control plane", "enabled": false, "suggested": false, "name": "k8s-cp"}, + {"enabled": true, "suggested": false, "name": "k8s-worker"} + ] + }`, + want: []string{"cilium", "k8s-worker", defaultComponent}, + }, + { + name: "SkipsDisabled_NoDefault", + data: `{ + "default": false, + "components": ["a", "b", "c"], + "details": [ + {"name": "a", "enabled": true}, + {"name": "b", "enabled": false}, + {"name": "c", "enabled": true} + ] + }`, + want: []string{"a", "c"}, + }, + { + name: "AllDisabled_Default", + data: `{ + "default": true, + "components": ["a", "b"], + "details": [ + {"name": "a", "enabled": false}, + {"name": "b", "enabled": false} + ] + }`, + want: []string{defaultComponent}, + }, + { + name: "AllDisabled_NoDefault", + data: `{ + "default": false, + "components": ["a", "b"], + "details": [ + {"name": "a", "enabled": false}, + {"name": "b", "enabled": false} + ] + }`, + want: []string{}, + }, + // Only an explicit "enabled": false disables a component. + { + name: "EnabledMissing", + data: `{ + "default": false, + "components": ["a"], + "details": [{"name": "a"}] + }`, + want: []string{"a"}, + }, + { + name: "EnabledNull", + data: `{ + "default": false, + "components": ["a"], + "details": [{"name": "a", "enabled": null}] + }`, + want: []string{"a"}, + }, + { + name: "DetailsPartial", + data: `{ + "default": false, + "components": ["a", "b"], + "details": [{"name": "b", "enabled": false}] + }`, + want: []string{"a"}, + }, + { + name: "DetailsUnknownComponent", + data: `{ + "default": false, + "components": ["a"], + "details": [{"name": "b", "enabled": false}] + }`, + want: []string{"a"}, + }, + // A systemd-sysupdate without "details" reports the names only. + { + name: "WithoutDetails_Default", + data: `{"default": true, "components": ["a", "b"]}`, + want: []string{"a", "b", defaultComponent}, + }, + { + name: "WithoutDetails_NoDefault", + data: `{"default": false, "components": ["a", "b"]}`, + want: []string{"a", "b"}, + }, + { + name: "WithoutDetails_DefaultOnly", + data: `{"default": true, "components": []}`, + want: []string{defaultComponent}, + }, + { + name: "WithoutDetails_Empty", + data: `{"default": false, "components": []}`, + want: []string{}, + }, + { + name: "WithoutDetails_NullComponents", + data: `{"default": true, "components": null}`, + want: []string{defaultComponent}, + }, + {name: "EmptyObject", data: `{}`, want: []string{}}, + {name: "InvalidJSON", data: `not json`, wantErr: true}, + {name: "InvalidComponentsType", data: `{"components": "a"}`, wantErr: true}, + {name: "InvalidDefaultType", data: `{"default": "true"}`, wantErr: true}, + { + name: "InvalidEnabledType", + data: `{"components": ["a"], "details": [{"name": "a", "enabled": "false"}]}`, + wantErr: true, + }, + } { + t.Run(test.name, func(t *testing.T) { + components, err := parseComponents([]byte(test.data)) + if test.wantErr { + require.Error(t, err) + assert.Empty(t, components) + } else { + require.NoError(t, err) + assert.Equal(t, test.want, components) + } + }) + } +} From 4f622244385ad56833cd2a34c5e2399d9cad3285 Mon Sep 17 00:00:00 2001 From: Aleksa Sarai Date: Tue, 24 Nov 2026 00:26:32 +1100 Subject: [PATCH 2/5] xsysupdate: install sysupdate..component definition files to /etc Previously we would skip these files if distributed which meant that disabled-by-default and runtime-enabled components would not be installed correctly. This only fixes clients consuming these files, a later patch in this series fixes hardhat to properly generate these component files. Signed-off-by: Aleksa Sarai --- internal/xsysupdate/transfer.go | 7 ++++--- internal/xsysupdate/transfer_test.go | 29 ++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/internal/xsysupdate/transfer.go b/internal/xsysupdate/transfer.go index 12f7725..030a4f9 100644 --- a/internal/xsysupdate/transfer.go +++ b/internal/xsysupdate/transfer.go @@ -48,7 +48,7 @@ var ( // directories, be writable, and be persistent across reboot. // // On AmutableOS, only /etc fits the bill. - transferInstallDir = "/etc" // .../sysupdate{.*,}.d/ + transferInstallDir = "/etc" // .../sysupdate{.*,.d} // extensionInstallDir is where sysext and confexts are linked by default // using CurrentSymlink. // FIXME: This is only needed for the systemd bug workaround in Init. @@ -58,8 +58,9 @@ var ( // transferInstallPatterns are a set of globs that will match the symlink names // in /etc and in /var/lib/quarry-sysupdate/xsysupdate/transfers/. var transferInstallPatterns = [...]string{ - "sysupdate.*.d", // component sysupdate directories - "sysupdate.d/*", // base system sysupdate files + "sysupdate.d/*", // base system sysupdate files + "sysupdate.*.d", // component sysupdate directories + "sysupdate.*.component", // component definition files } // TransferFileExtension is an [Extension] that implements auto-installation of diff --git a/internal/xsysupdate/transfer_test.go b/internal/xsysupdate/transfer_test.go index ff18a5b..f920bae 100644 --- a/internal/xsysupdate/transfer_test.go +++ b/internal/xsysupdate/transfer_test.go @@ -263,6 +263,24 @@ func TestUnlinkTransfers_RemovesQuarryComponentDir(t *testing.T) { assert.ErrorIs(t, err, fs.ErrNotExist) } +// Covers the `sysupdate.*.component` glob (component definition files, which +// live directly in /etc rather than in a sysupdate directory). +func TestUnlinkTransfers_RemovesQuarryComponentFile(t *testing.T) { + env, ctx := setupTestEnv(t) + ext := initExt(ctx, t) + + target := filepath.Join(env.storeDir, fixedNewDirSubpath, "sysupdate.comp.component") //nolint:forbidigo // test code + require.NoError(t, os.MkdirAll(filepath.Dir(target), 0o755)) //nolint:forbidigo // test code + require.NoError(t, os.WriteFile(target, []byte("dummy"), 0o644)) //nolint:forbidigo // test code + link := filepath.Join(env.etcPath, "sysupdate.comp.component") //nolint:forbidigo // test code + require.NoError(t, os.Symlink(target, link)) //nolint:forbidigo // test code + + require.NoError(t, ext.unlinkTransfers()) + + _, err := os.Lstat(link) + assert.ErrorIs(t, err, fs.ErrNotExist) +} + func TestUnlinkTransfers_SkipsNonSymlinks(t *testing.T) { env, ctx := setupTestEnv(t) ext := initExt(ctx, t) @@ -299,6 +317,7 @@ func TestLinkTransfers_BaseAndComponent(t *testing.T) { env.populateUpdateDir(t, fixedNewDirSubpath, map[string][]byte{ "sysupdate.d/base.transfer": []byte("base"), "sysupdate.comp.d/component.conf": []byte("component"), + "sysupdate.comp.component": []byte("[Component]"), }) require.NoError(t, ext.linkTransfers(fixedNewDirSubpath)) @@ -317,6 +336,16 @@ func TestLinkTransfers_BaseAndComponent(t *testing.T) { target, err = os.Readlink(compLink) require.NoError(t, err) assert.Equal(t, filepath.Join(env.storeDir, fixedNewDirSubpath, "sysupdate.comp.d"), target) //nolint:forbidigo // test code + + // Component definition files are linked directly into /etc, not inside + // the component directory. + defLink := filepath.Join(env.etcPath, "sysupdate.comp.component") //nolint:forbidigo // test code + target, err = os.Readlink(defLink) + require.NoError(t, err) + assert.Equal(t, filepath.Join(env.storeDir, fixedNewDirSubpath, "sysupdate.comp.component"), target) //nolint:forbidigo // test code + info, err := os.Stat(defLink) + require.NoError(t, err) + assert.True(t, info.Mode().IsRegular()) } func TestLinkTransfers_CreatesSysupdateDirIfMissing(t *testing.T) { From d816887e5d97773a0c9c525b3103c9cc6d3130ff Mon Sep 17 00:00:00 2001 From: Aleksa Sarai Date: Tue, 24 Nov 2026 01:11:51 +1100 Subject: [PATCH 3/5] hardhat: targets: improve TargetsBuilder usage for --quarry-transfer-dir There is no need to pass around file contents as maps of paths and bytes or having the kinda complicated collation code with restrictions about duplicates. Really we should be merging all of the provided directory contents as much as possible. Fixes: 57c679a2595e ("hardhat: publish sysupdate definitions inline with --quarry-transfer-dir") Signed-off-by: Aleksa Sarai --- cmd/hardhat/targets.go | 4 +- cmd/hardhat/targets_quarry.go | 169 +++++++++++++++-------------- cmd/hardhat/targets_quarry_test.go | 90 ++++++++++----- 3 files changed, 153 insertions(+), 110 deletions(-) diff --git a/cmd/hardhat/targets.go b/cmd/hardhat/targets.go index 1f8f8dc..bb67f68 100644 --- a/cmd/hardhat/targets.go +++ b/cmd/hardhat/targets.go @@ -460,7 +460,7 @@ var targetsCommand = withKeystoreFlagUnless(&cli.Command{ // This happens before creating --output so that bad options leave it // alone. - quarry, err := quarrySpecFromFlags(cmd) + quarryTargets, err := quarrySpecFromFlags(cmd) if err != nil { return err } @@ -566,7 +566,7 @@ var targetsCommand = withKeystoreFlagUnless(&cli.Command{ } } - if err := addQuarryTargets(builder, quarry); err != nil { + if err := addQuarryTargets(builder, quarryTargets); err != nil { return err } diff --git a/cmd/hardhat/targets_quarry.go b/cmd/hardhat/targets_quarry.go index e9475d0..b1d62df 100644 --- a/cmd/hardhat/targets_quarry.go +++ b/cmd/hardhat/targets_quarry.go @@ -7,10 +7,8 @@ import ( "encoding/json" "fmt" "io/fs" - "maps" "os" "path/filepath" - "slices" "strings" "unicode" @@ -41,37 +39,30 @@ func quarryTargetsFlags() []cli.Flag { } } -// quarryTransferDir is one of --quarry-transfer-dir with its -// sources. -type quarryTransferDir struct { - dir string - sources []string +// quarryTransferSource is one = of +// --quarry-transfer-dir. +type quarryTransferSource struct { + componentDir string + source string } // quarrySpecFromFlags parses and checks the --quarry-* options. -func quarrySpecFromFlags(cmd *cli.Command) ([]*quarryTransferDir, error) { - var dirs []*quarryTransferDir - byDir := map[string]*quarryTransferDir{} +// +// TODO: We should probably return a wrapping struct or something a bit more +// generic so the caller's usage of [addQuarryTargets] makes more sense. +func quarrySpecFromFlags(cmd *cli.Command) ([]quarryTransferSource, error) { + var sources []quarryTransferSource for _, arg := range cmd.StringSlice("quarry-transfer-dir") { - dir, source, ok := strings.Cut(arg, "=") + componentDir, source, ok := strings.Cut(arg, "=") if !ok || source == "" { return nil, fmt.Errorf("--quarry-transfer-dir=%q must be =", arg) } - if _, err := transferlayout.ParseComponentDir(dir); err != nil { + if _, err := transferlayout.ParseComponentDir(componentDir); err != nil { return nil, fmt.Errorf("--quarry-transfer-dir=%q: %w", arg, err) } - entry, ok := byDir[dir] - if !ok { - entry = &quarryTransferDir{dir: dir} - byDir[dir] = entry - dirs = append(dirs, entry) - } - if slices.Contains(entry.sources, source) { - return nil, fmt.Errorf("--quarry-transfer-dir=%q given twice", arg) - } - entry.sources = append(entry.sources, source) + sources = append(sources, quarryTransferSource{componentDir: componentDir, source: source}) } - return dirs, nil + return sources, nil } // confextSourcePrefix marks a --quarry-transfer-dir source that names a @@ -83,6 +74,15 @@ func hasSpaceOrControl(s string) bool { return strings.ContainsFunc(s, func(r rune) bool { return unicode.IsSpace(r) || unicode.IsControl(r) }) } +// rejectConflict returns an error if the contents of the existing target at +// targetPath differ from data. +func rejectConflict(existing *tufmetadata.TargetFiles, targetPath string, data []byte) error { + if err := tufext.VerifyData(data, existing.Length, existing.Hashes); err != nil { + return fmt.Errorf("target %s is given twice with different contents: %w", targetPath, err) + } + return nil +} + // confextTransfer returns the transfer definition installing the confext DDI // "_.confext.raw" into the /var/lib/confexts/.raw.v/ // directory, from which systemd picks the newest instance. The source pattern @@ -109,23 +109,43 @@ InstancesMax=2 `) } -// readDefinitionSource adds the definition files of one source directory to -// files, keyed by their path relative to it, or generates them for a confext -// source. A file name that another source already added is an error. -func readDefinitionSource(files map[string][]byte, source string) error { - add := func(rel string, data []byte) error { - if _, dup := files[rel]; dup { - return fmt.Errorf("%s: definition file %s is also in another source", source, rel) - } - files[rel] = data - return nil +// addInlineTarget adds an inline target with the given target path. If there +// is an existing entry with identical contents this is a no-op, but if the +// contents are different then an error is returned. +func addInlineTarget(builder *tufext.TargetsBuilder, targetPath string, data []byte) error { + existing, ok := builder.TargetsType().Targets[targetPath] + if !ok { + _, err := addInlineBytes(builder, targetPath, data) + return err + } + if err := rejectConflict(existing, targetPath, data); err != nil { + return err + } + // If there is already an existing entry, make sure we include inline data. + ext := tufext.TargetFilesExt(existing) + if inline, err := ext.InlineData(); err != nil { + return fmt.Errorf("target %s has invalid inline data: %w", targetPath, err) + } else if inline == nil { + ext.WithInlineData(data) } + return nil +} + +// addDefinitionSource adds the definition files of one source directory to the +// targets under componentDir, keeping their path relative to the source, or +// generates them for a confext source. +func addDefinitionSource(builder *tufext.TargetsBuilder, componentDir, source string) error { if name, ok := strings.CutPrefix(source, confextSourcePrefix); ok { // systemd reads the confext name up to the first "_" of the file name. if !transferlayout.ValidPathComponent(name) || strings.Contains(name, "_") || hasSpaceOrControl(name) { return fmt.Errorf("invalid confext name %q in %s", name, source) } - return add("50-"+name+".transfer", confextTransfer(name)) + file := "50-" + name + ".transfer" + targetPath, err := transferlayout.TargetPath(componentDir, file) + if err != nil { + return fmt.Errorf("%s: %s: %w", componentDir, file, err) + } + return addInlineTarget(builder, targetPath, confextTransfer(name)) } found := false err := filepath.WalkDir(source, func(path string, entry fs.DirEntry, err error) error { //nolint:forbidigo // user-controlled host path @@ -144,6 +164,9 @@ func readDefinitionSource(files map[string][]byte, source string) error { if err != nil { return err } + // TODO: Ideally tufext.TargetsBuilder would auto-detect what sizes + // this inlining should happen at and we could then provide a reader + // instead? if info.Size() > maxInlineSize { return fmt.Errorf("definition file %s is too large (%d bytes) to be inlined (limit %d bytes)", path, info.Size(), maxInlineSize) } @@ -152,7 +175,14 @@ func readDefinitionSource(files map[string][]byte, source string) error { return err } found = true - return add(rel, data) + targetPath, err := transferlayout.TargetPath(componentDir, rel) + if err != nil { + return fmt.Errorf("%s: %s: %w", componentDir, rel, err) + } + if err := addInlineTarget(builder, targetPath, data); err != nil { + return fmt.Errorf("%s: %w", source, err) + } + return nil }) if err != nil { return err @@ -163,57 +193,34 @@ func readDefinitionSource(files map[string][]byte, source string) error { return nil } -// layoutTransferDir turns the sources of one transfer directory into its -// files. For a named component, these include the generated component file -// if no source ships one. -func layoutTransferDir(entry *quarryTransferDir) (map[string][]byte, error) { - files := map[string][]byte{} - for _, source := range entry.sources { - if err := readDefinitionSource(files, source); err != nil { - return nil, err - } - } - // quarrySpecFromFlags already checked the directory name. - component, _ := transferlayout.ParseComponentDir(entry.dir) - if component == "" { - return files, nil - } - componentFile := component + ".component" - if _, shipped := files[componentFile]; !shipped { - files[componentFile] = transferlayout.ComponentFile(component) - } - return files, nil -} - // addQuarryTargets adds what the --quarry-* options ask for to the targets. -func addQuarryTargets(builder *tufext.TargetsBuilder, dirs []*quarryTransferDir) error { - for _, entry := range dirs { - files, err := layoutTransferDir(entry) - if err != nil { +// Every named component gets a generated .component file if no +// source ships one. +func addQuarryTargets(builder *tufext.TargetsBuilder, sources []quarryTransferSource) error { + components := map[string]struct{}{} + for _, src := range sources { + if err := addDefinitionSource(builder, src.componentDir, src.source); err != nil { return err } - for _, rel := range slices.Sorted(maps.Keys(files)) { - path, err := transferlayout.TargetPath(entry.dir, rel) - if err != nil { - return fmt.Errorf("%s: %s: %w", entry.dir, rel, err) - } - if err := rejectExisting(builder, path); err != nil { - return err - } - if _, err := addInlineBytes(builder, path, files[rel]); err != nil { - return err - } + // quarrySpecFromFlags already checked the directory name. + component, _ := transferlayout.ParseComponentDir(src.componentDir) + if component != "" { + components[component] = struct{}{} } } - return nil -} - -// rejectExisting returns an error if the targets already hold path. The -// builder would otherwise silently replace the entry (a generated entry -// colliding with a hashed or merged one). -func rejectExisting(builder *tufext.TargetsBuilder, path string) error { - if _, dup := builder.TargetsType().Targets[path]; dup { - return fmt.Errorf("target %s is given twice", path) + for component := range components { + componentDir := transferlayout.ComponentDir(component) + componentFile := component + ".component" + componentPath, err := transferlayout.TargetPath(componentDir, componentFile) + if err != nil { + return fmt.Errorf("%s: %s: %w", componentDir, componentFile, err) + } + if _, ok := builder.TargetsType().Targets[componentPath]; ok { + continue + } + if err := addInlineTarget(builder, componentPath, transferlayout.ComponentFile(component)); err != nil { + return err + } } return nil } diff --git a/cmd/hardhat/targets_quarry_test.go b/cmd/hardhat/targets_quarry_test.go index 56d767c..dba21ce 100644 --- a/cmd/hardhat/targets_quarry_test.go +++ b/cmd/hardhat/targets_quarry_test.go @@ -50,10 +50,10 @@ func TestAddQuarryTargets(t *testing.T) { "own.transfer": "[Transfer]\n", "own.component": "[Component]\nDescription=Own\n", }) - spec := []*quarryTransferDir{ - {dir: "sysupdate.d", sources: []string{base}}, - {dir: "sysupdate.k8s.d", sources: []string{k8s}}, - {dir: "sysupdate.own.d", sources: []string{shipped}}, + spec := []quarryTransferSource{ + {componentDir: "sysupdate.d", source: base}, + {componentDir: "sysupdate.k8s.d", source: k8s}, + {componentDir: "sysupdate.own.d", source: shipped}, } builder := tufext.NewTargetsBuilder() require.NoError(t, addQuarryTargets(builder, spec)) @@ -78,25 +78,49 @@ func TestAddQuarryTargets(t *testing.T) { func TestAddQuarryTargetsRejects(t *testing.T) { dir := writeDefinitions(t, t.TempDir(), map[string]string{}) - spec := []*quarryTransferDir{{dir: "sysupdate.d", sources: []string{dir}}} + spec := []quarryTransferSource{{componentDir: "sysupdate.d", source: dir}} require.ErrorContains(t, addQuarryTargets(tufext.NewTargetsBuilder(), spec), "holds no definition files") - // A path already in the targets is an error rather than a silent - // replacement. + // A path already in the targets with different contents is an error + // rather than a silent replacement. dir = writeDefinitions(t, t.TempDir(), map[string]string{"x.transfer": "[Transfer]\n"}) builder := tufext.NewTargetsBuilder() _, err := addInlineBytes(builder, ".quarry/sysupdate.d/x.transfer", nil) require.NoError(t, err) - spec = []*quarryTransferDir{{dir: "sysupdate.d", sources: []string{dir}}} - require.ErrorContains(t, addQuarryTargets(builder, spec), "given twice") + spec = []quarryTransferSource{{componentDir: "sysupdate.d", source: dir}} + require.ErrorContains(t, addQuarryTargets(builder, spec), "given twice with different contents") +} + +// A path already in the targets with the same contents keeps the existing +// entry, adding the inline data if it has none. +func TestAddQuarryTargets_ExistingIdentical(t *testing.T) { + const data = "[Transfer]\n" + dir := writeDefinitions(t, t.TempDir(), map[string]string{"x.transfer": data}) + + builder := tufext.NewTargetsBuilder() + existing, err := builder.AddTargetFile(".quarry/sysupdate.d/x.transfer", int64(len(data)), hashAlgorithm.FromString(data)) + require.NoError(t, err) + custom := json.RawMessage(`{"keep": true}`) + existing.Custom = &custom + + spec := []quarryTransferSource{{componentDir: "sysupdate.d", source: dir}} + require.NoError(t, addQuarryTargets(builder, spec)) + target := builder.TargetsType().Targets[".quarry/sysupdate.d/x.transfer"] + assert.Same(t, existing, target, "the existing entry is kept") + assert.JSONEq(t, `{"keep": true}`, string(*target.Custom)) + assert.Equal(t, data, inlineString(t, builder, ".quarry/sysupdate.d/x.transfer"), "inline data is added") + + // An existing entry that already has the inline data is left alone. + require.NoError(t, addQuarryTargets(builder, spec)) + assert.Same(t, existing, builder.TargetsType().Targets[".quarry/sysupdate.d/x.transfer"]) } // A confext source generates the definitions. The transfer comes from // hardhat's template, and the component file is generated as for any component // directory without one. func TestAddQuarryTargets_Confext(t *testing.T) { - spec := []*quarryTransferDir{ - {dir: "sysupdate.edge-gw.d", sources: []string{"confext:edge-gw"}}, + spec := []quarryTransferSource{ + {componentDir: "sysupdate.edge-gw.d", source: "confext:edge-gw"}, } builder := tufext.NewTargetsBuilder() require.NoError(t, addQuarryTargets(builder, spec)) @@ -113,24 +137,37 @@ func TestAddQuarryTargets_Confext(t *testing.T) { } assert.Equal(t, "[Component]\nDescription=edge-gw\n", inlineString(t, builder, dir+"edge-gw.component")) - // Several sources merge into one directory. A file in two of them is an error. + // Several sources merge into one directory. extra := writeDefinitions(t, t.TempDir(), map[string]string{"60-extra.transfer": "[Transfer]\n"}) - spec = []*quarryTransferDir{ - {dir: "sysupdate.gw.d", sources: []string{"confext:gw", "confext:gw-certs", extra}}, + spec = []quarryTransferSource{ + {componentDir: "sysupdate.gw.d", source: "confext:gw"}, + {componentDir: "sysupdate.gw.d", source: "confext:gw-certs"}, + {componentDir: "sysupdate.gw.d", source: extra}, } builder = tufext.NewTargetsBuilder() require.NoError(t, addQuarryTargets(builder, spec)) assert.Contains(t, inlineString(t, builder, ".quarry/sysupdate.gw.d/50-gw.transfer"), "MatchPattern=**/gw_@v.confext.raw\n") assert.Contains(t, inlineString(t, builder, ".quarry/sysupdate.gw.d/50-gw-certs.transfer"), "MatchPattern=**/gw-certs_@v.confext.raw\n") assert.Equal(t, "[Transfer]\n", inlineString(t, builder, ".quarry/sysupdate.gw.d/60-extra.transfer")) - spec = []*quarryTransferDir{ - {dir: "sysupdate.gw.d", sources: []string{"confext:gw", extra, extra}}, + assert.Len(t, builder.TargetsType().Targets, 4, "the component file is generated once") + + // The same file in two sources is fine, but different contents are an + // error. + spec = []quarryTransferSource{ + {componentDir: "sysupdate.gw.d", source: extra}, + {componentDir: "sysupdate.gw.d", source: extra}, + } + require.NoError(t, addQuarryTargets(tufext.NewTargetsBuilder(), spec)) + other := writeDefinitions(t, t.TempDir(), map[string]string{"60-extra.transfer": "[Transfer]\nVerify=no\n"}) + spec = []quarryTransferSource{ + {componentDir: "sysupdate.gw.d", source: extra}, + {componentDir: "sysupdate.gw.d", source: other}, } - require.ErrorContains(t, addQuarryTargets(tufext.NewTargetsBuilder(), spec), "also in another source") + require.ErrorContains(t, addQuarryTargets(tufext.NewTargetsBuilder(), spec), "given twice with different contents") for _, name := range []string{"", "a_b", "a/b", "..", "a b", "a\nb"} { - spec := []*quarryTransferDir{ - {dir: "sysupdate.x.d", sources: []string{"confext:" + name}}, + spec := []quarryTransferSource{ + {componentDir: "sysupdate.x.d", source: "confext:" + name}, } require.Error(t, addQuarryTargets(tufext.NewTargetsBuilder(), spec), "confext name %q", name) } @@ -153,10 +190,10 @@ func TestSetQuarryCustomVersion(t *testing.T) { } // quarrySpecFor runs quarrySpecFromFlags on a dummy command with the args. -func quarrySpecFor(t *testing.T, args ...string) ([]*quarryTransferDir, error) { +func quarrySpecFor(t *testing.T, args ...string) ([]quarryTransferSource, error) { t.Helper() var ( - spec []*quarryTransferDir + spec []quarryTransferSource specErr error ) cmd := &cli.Command{ @@ -179,17 +216,16 @@ func TestQuarrySpecFromFlags(t *testing.T) { "--quarry-transfer-dir=sysupdate.k8s.d=/k8s", ) require.NoError(t, err) - assert.Equal(t, []*quarryTransferDir{ - {dir: "sysupdate.gw.d", sources: []string{"confext:gw", "confext:gw-certs"}}, - {dir: "sysupdate.d", sources: []string{"/defs"}}, - {dir: "sysupdate.k8s.d", sources: []string{"/k8s"}}, + assert.Equal(t, []quarryTransferSource{ + {componentDir: "sysupdate.gw.d", source: "confext:gw"}, + {componentDir: "sysupdate.d", source: "/defs"}, + {componentDir: "sysupdate.gw.d", source: "confext:gw-certs"}, + {componentDir: "sysupdate.k8s.d", source: "/k8s"}, }, spec) - const dir = "--quarry-transfer-dir=sysupdate.x.d=/defs" for name, args := range map[string][]string{ "invalid component dir": {"--quarry-transfer-dir=other.d=/defs"}, "no source": {"--quarry-transfer-dir=sysupdate.d="}, - "repeated source": {dir, dir}, } { _, err := quarrySpecFor(t, args...) require.Error(t, err, name) From 3264f187aba37095248a389a50bc35d5ecd2c76b Mon Sep 17 00:00:00 2001 From: Aleksa Sarai Date: Tue, 24 Nov 2026 01:35:39 +1100 Subject: [PATCH 4/5] xsysupdate: do not patch non-transfer files Injecting a pointless [Source] Path=... value doesn't make sense for any non-transfer / non-transfer-drop-in files. Signed-off-by: Aleksa Sarai --- internal/xsysupdate/transfer.go | 16 ++++++++- internal/xsysupdate/transfer_test.go | 53 ++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/internal/xsysupdate/transfer.go b/internal/xsysupdate/transfer.go index 030a4f9..c5dd042 100644 --- a/internal/xsysupdate/transfer.go +++ b/internal/xsysupdate/transfer.go @@ -229,6 +229,15 @@ func (ext *TransferFileExtension) patchTransferFile(wtr io.Writer, rdr io.Reader return nil } +// isPatchableDefinition returns whether transferPath is a file which should be +// patched with a custom [Source] Path= value (in particular, .transfer files +// or any .transfer.d/*.conf drop-ins). +func isPatchableDefinition(transferPath string) bool { + dir, file := filepath.Split(transferPath) //nolint:forbidigo // lexical check only + return strings.HasSuffix(file, ".transfer") || // transfer file + (strings.HasSuffix(file, ".conf") && strings.HasSuffix(dir, ".transfer.d/")) // drop-in +} + // ApplyTarget saves the transfer file from the repository to the per-update // transfer directory. func (ext *TransferFileExtension) ApplyTarget(ctx context.Context, info *tufclient.TargetInfo) (_ bool, Err error) { @@ -254,7 +263,12 @@ func (ext *TransferFileExtension) ApplyTarget(ctx context.Context, info *tufclie srcRdr := progressbar.NewReader(srcTransferFile, progressbar.DefaultBytes(info.Length, info.Path)) - if err := ext.patchTransferFile(dstTransferTmpFile, &srcRdr); err != nil { + if isPatchableDefinition(transferPath) { + err = ext.patchTransferFile(dstTransferTmpFile, &srcRdr) + } else { + _, err = io.Copy(dstTransferTmpFile, &srcRdr) + } + if err != nil { return false, fmt.Errorf("write transfer file %s to tmpfile: %w", info.Path, err) } if err := srcTransferFile.Close(); err != nil { diff --git a/internal/xsysupdate/transfer_test.go b/internal/xsysupdate/transfer_test.go index f920bae..d165f44 100644 --- a/internal/xsysupdate/transfer_test.go +++ b/internal/xsysupdate/transfer_test.go @@ -677,6 +677,59 @@ func TestApplyTarget_NestedPath(t *testing.T) { assert.True(t, info2.Mode().IsRegular()) } +func TestIsPatchableDefinition(t *testing.T) { + for transferPath, want := range map[string]bool{ + "sysupdate.d/foo.transfer": true, + "sysupdate.k8s.d/foo.transfer": true, + "sysupdate.d/foo.transfer.d/x.conf": true, + "sysupdate.k8s.d/foo.transfer.d/x.conf": true, + "sysupdate.k8s.component": false, + "sysupdate.d/docker.feature": false, + "sysupdate.d/docker.feature.d/x.conf": false, + "sysupdate.d/foo.transfer.d/x.txt": false, + "sysupdate.d/foo.conf": false, + } { + assert.Equal(t, want, isPatchableDefinition(transferPath), transferPath) + } +} + +// Only transfer files and their drop-ins get the source path override. Other +// definitions are installed byte-for-byte. +func TestApplyTarget_PatchesOnlyTransfers(t *testing.T) { + env, ctx := setupTestEnv(t) + + const ( + componentBody = "[Component]\nDescription=k8s\n" + dropinBody = "[Source]\nPath=https://upstream.example.com/\n" + ) + srv := testrepo.New(t) + componentTarget := srv.WriteTarget(t, ".quarry/sysupdate.k8s.component", strings.NewReader(componentBody)) + dropinTarget := srv.WriteTarget(t, ".quarry/sysupdate.k8s.d/foo.transfer.d/x.conf", strings.NewReader(dropinBody)) + repo := makeRepo(t, srv, "testrepo") + + proxyURL := "http://localhost:9999/" + ext := &TransferFileExtension{OverrideSourcePathURL: &proxyURL} + _, err := ext.Init(ctx) + require.NoError(t, err) + t.Cleanup(func() { _ = ext.Close() }) + + for _, target := range []*tufmetadata.TargetFiles{componentTarget, dropinTarget} { + applied, err := ext.ApplyTarget(ctx, &tufclient.TargetInfo{TargetFiles: target, Repo: repo}) + require.NoError(t, err) + assert.True(t, applied, target.Path) + } + + out, err := os.ReadFile(filepath.Join(env.storeDir, fixedNewDirSubpath, "sysupdate.k8s.component")) //nolint:forbidigo // test code + require.NoError(t, err) + assert.Equal(t, componentBody, string(out), "component file is not patched") + + out, err = os.ReadFile(filepath.Join(env.storeDir, fixedNewDirSubpath, "sysupdate.k8s.d", "foo.transfer.d", "x.conf")) //nolint:forbidigo // test code + require.NoError(t, err) + cfg, err := ini.Load(out) + require.NoError(t, err) + assert.Equal(t, proxyURL, cfg.Section("Source").Key("Path").String(), "transfer drop-in is patched") +} + func TestClose_Idempotent(t *testing.T) { _, ctx := setupTestEnv(t) ext := initExt(ctx, t) From af1733149fb386ead609a354d7679d64b6fd7b45 Mon Sep 17 00:00:00 2001 From: Aleksa Sarai Date: Tue, 24 Nov 2026 01:41:17 +1100 Subject: [PATCH 5/5] hardhat targets: publish component files as .quarry/sysupdate..component To make using the CLI easier the foo.component file is still provided inside the component directory but we now hoist it into the top-level directory so that it can be installed by clients properly. This also means we now reject component directories that have a different .component file inside them, since they will be ignored (and are kind of weird to have in the first place). Signed-off-by: Aleksa Sarai --- cmd/hardhat/targets_quarry.go | 36 +++++++++++++++++++------- cmd/hardhat/targets_quarry_test.go | 24 ++++++++++++++--- internal/transferlayout/layout.go | 18 +++++++++++-- internal/transferlayout/layout_test.go | 11 ++++++++ 4 files changed, 74 insertions(+), 15 deletions(-) diff --git a/cmd/hardhat/targets_quarry.go b/cmd/hardhat/targets_quarry.go index b1d62df..a93ba07 100644 --- a/cmd/hardhat/targets_quarry.go +++ b/cmd/hardhat/targets_quarry.go @@ -5,6 +5,7 @@ package main import ( "encoding/json" + "errors" "fmt" "io/fs" "os" @@ -28,7 +29,7 @@ func quarryTargetsFlags() []cli.Flag { return []cli.Flag{ &cli.StringSliceFlag{ Name: "quarry-transfer-dir", - Usage: "ship sysupdate definitions for one component, given as =. is the component's sysupdate definitions directory. It is \"sysupdate.d\" for the default component or \"sysupdate..d\". is a directory of definitions (*.transfer, *.feature, .component and drop-in directories) or \"" + confextSourcePrefix + "\" for a generated transfer installing the confext DDI _.confext.raw. Repeat the option for the same to merge sources. The files are published under " + transferlayout.Prefix + "/. For a named component, .component is generated (without Enabled=, so it is an enabled-by-default component) if no source ships it", + Usage: "ship sysupdate definitions for one component, given as =. is the component's sysupdate definitions directory. It is \"sysupdate.d\" for the default component or \"sysupdate..d\". is a directory of definitions (*.transfer, *.feature, drop-in directories and, for a named component, .component at its top) or \"" + confextSourcePrefix + "\" for a generated transfer installing the confext DDI _.confext.raw. Repeat the option for the same to merge sources. The files are published under " + transferlayout.Prefix + "/, except .component, which is published as " + transferlayout.Prefix + "sysupdate..component. For a named component, .component is generated (without Enabled=, so it is an enabled-by-default component) if no source ships it", }, // TODO: This should probably allow you to specify a subset of targets // to apply this to, as applying it to everything is kinda aggressive. @@ -160,6 +161,10 @@ func addDefinitionSource(builder *tufext.TargetsBuilder, componentDir, source st return err } rel = filepath.ToSlash(rel) + targetPath, err := definitionTargetPath(componentDir, rel) + if err != nil { + return fmt.Errorf("%s: %s: %w", componentDir, rel, err) + } info, err := entry.Info() if err != nil { return err @@ -175,10 +180,6 @@ func addDefinitionSource(builder *tufext.TargetsBuilder, componentDir, source st return err } found = true - targetPath, err := transferlayout.TargetPath(componentDir, rel) - if err != nil { - return fmt.Errorf("%s: %s: %w", componentDir, rel, err) - } if err := addInlineTarget(builder, targetPath, data); err != nil { return fmt.Errorf("%s: %w", source, err) } @@ -193,6 +194,25 @@ func addDefinitionSource(builder *tufext.TargetsBuilder, componentDir, source st return nil } +// definitionTargetPath returns the target path of the definition file rel of a +// source for componentDir. The component's own .component at the +// top of the source is published as the component file. Any other +// *.component file is an error. +func definitionTargetPath(componentDir, rel string) (string, error) { + if !strings.HasSuffix(rel, ".component") { + return transferlayout.TargetPath(componentDir, rel) + } + // quarrySpecFromFlags already checked the directory name. + component, _ := transferlayout.ParseComponentDir(componentDir) + if component == "" { + return "", errors.New("the default component has no component file") + } + if rel != component+".component" { + return "", fmt.Errorf("unexpected component file (only %s.component is allowed)", component) + } + return transferlayout.ComponentFilePath(component) +} + // addQuarryTargets adds what the --quarry-* options ask for to the targets. // Every named component gets a generated .component file if no // source ships one. @@ -209,11 +229,9 @@ func addQuarryTargets(builder *tufext.TargetsBuilder, sources []quarryTransferSo } } for component := range components { - componentDir := transferlayout.ComponentDir(component) - componentFile := component + ".component" - componentPath, err := transferlayout.TargetPath(componentDir, componentFile) + componentPath, err := transferlayout.ComponentFilePath(component) if err != nil { - return fmt.Errorf("%s: %s: %w", componentDir, componentFile, err) + return fmt.Errorf("component %s: %w", component, err) } if _, ok := builder.TargetsType().Targets[componentPath]; ok { continue diff --git a/cmd/hardhat/targets_quarry_test.go b/cmd/hardhat/targets_quarry_test.go index dba21ce..de85e4d 100644 --- a/cmd/hardhat/targets_quarry_test.go +++ b/cmd/hardhat/targets_quarry_test.go @@ -64,10 +64,11 @@ func TestAddQuarryTargets(t *testing.T) { assert.Equal(t, "[Transfer]\nVerify=no\n", inlineString(t, builder, baseDir+"10-usr.transfer.d/x.conf")) assert.Equal(t, "[Feature]\nSuggestOnMachineTag=amutable.ext.docker\n", inlineString(t, builder, baseDir+"docker.feature")) - const k8sDir = ".quarry/sysupdate.k8s.d/" + // Component files are published next to, not inside, their directory. assert.Equal(t, "[Component]\nDescription=k8s\n", - inlineString(t, builder, k8sDir+"k8s.component"), "a missing component file is generated") - assert.Equal(t, "[Component]\nDescription=Own\n", inlineString(t, builder, ".quarry/sysupdate.own.d/own.component")) + inlineString(t, builder, ".quarry/sysupdate.k8s.component"), "a missing component file is generated") + assert.Equal(t, "[Component]\nDescription=Own\n", inlineString(t, builder, ".quarry/sysupdate.own.component")) + assert.NotContains(t, builder.TargetsType().Targets, ".quarry/sysupdate.own.d/own.component") targets := builder.TargetsType().Targets assert.Len(t, targets, 7) @@ -89,6 +90,21 @@ func TestAddQuarryTargetsRejects(t *testing.T) { require.NoError(t, err) spec = []quarryTransferSource{{componentDir: "sysupdate.d", source: dir}} require.ErrorContains(t, addQuarryTargets(builder, spec), "given twice with different contents") + + // Only a named component's own component file, at the top of the + // source, is allowed. + for name, test := range map[string]struct { + componentDir string + files map[string]string + }{ + "default component": {"sysupdate.d", map[string]string{"x.component": "[Component]\n"}}, + "other component": {"sysupdate.k8s.d", map[string]string{"other.component": "[Component]\n"}}, + "nested": {"sysupdate.k8s.d", map[string]string{"sub/k8s.component": "[Component]\n"}}, + } { + dir := writeDefinitions(t, t.TempDir(), test.files) + spec := []quarryTransferSource{{componentDir: test.componentDir, source: dir}} + require.Error(t, addQuarryTargets(tufext.NewTargetsBuilder(), spec), name) + } } // A path already in the targets with the same contents keeps the existing @@ -135,7 +151,7 @@ func TestAddQuarryTargets_Confext(t *testing.T) { } { assert.Contains(t, transfer, want) } - assert.Equal(t, "[Component]\nDescription=edge-gw\n", inlineString(t, builder, dir+"edge-gw.component")) + assert.Equal(t, "[Component]\nDescription=edge-gw\n", inlineString(t, builder, ".quarry/sysupdate.edge-gw.component")) // Several sources merge into one directory. extra := writeDefinitions(t, t.TempDir(), map[string]string{"60-extra.transfer": "[Transfer]\n"}) diff --git a/internal/transferlayout/layout.go b/internal/transferlayout/layout.go index d449a4e..ac8ad31 100644 --- a/internal/transferlayout/layout.go +++ b/internal/transferlayout/layout.go @@ -3,7 +3,7 @@ // Package transferlayout describes the repository layout of what quarry // ships as special TUF targets for systemd-sysupdate. This covers the -// transfer definition directories under ".quarry/". +// transfer definition directories and component files under ".quarry/". // // hardhat writes this layout ("hardhat targets --quarry-*") and // quarry-sysupdate (internal/xsysupdate) reads it, so both sides share the @@ -11,6 +11,7 @@ package transferlayout import ( + "errors" "fmt" "strings" ) @@ -71,8 +72,21 @@ func TargetPath(dir, file string) (string, error) { return Prefix + dir + "/" + file, nil } +// ComponentFilePath returns the target path of a named component's definition +// file, which is "sysupdate..component". The default +// component has no component file. +func ComponentFilePath(component string) (string, error) { + if component == "" { + return "", errors.New("the default component has no component file") + } + if _, err := ParseComponentDir(ComponentDir(component)); err != nil { + return "", err + } + return Prefix + "sysupdate." + component + ".component", nil +} + // ComponentFile returns the generated ".component" definition for -// a component directory that ships none. It sets no Enabled=, so it is an +// a component that ships none. It sets no Enabled=, so it is an // enabled-by-default component as in sysupdate. func ComponentFile(component string) []byte { return []byte("[Component]\nDescription=" + component + "\n") diff --git a/internal/transferlayout/layout_test.go b/internal/transferlayout/layout_test.go index d81b6e2..5458195 100644 --- a/internal/transferlayout/layout_test.go +++ b/internal/transferlayout/layout_test.go @@ -44,6 +44,17 @@ func TestComponentDir(t *testing.T) { } } +func TestComponentFilePath(t *testing.T) { + path, err := ComponentFilePath("k8s") + require.NoError(t, err) + assert.Equal(t, ".quarry/sysupdate.k8s.component", path) + + for _, component := range []string{"", "a.b", "a/b", ".."} { + _, err := ComponentFilePath(component) + require.Error(t, err, "component %q", component) + } +} + func TestComponentFile(t *testing.T) { assert.Equal(t, "[Component]\nDescription=k8s\n", string(ComponentFile("k8s"))) }