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..a93ba07 100644 --- a/cmd/hardhat/targets_quarry.go +++ b/cmd/hardhat/targets_quarry.go @@ -5,12 +5,11 @@ package main import ( "encoding/json" + "errors" "fmt" "io/fs" - "maps" "os" "path/filepath" - "slices" "strings" "unicode" @@ -30,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. @@ -41,37 +40,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 +75,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 +110,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 @@ -140,10 +161,17 @@ func readDefinitionSource(files map[string][]byte, source string) error { 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 } + // 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 +180,10 @@ func readDefinitionSource(files map[string][]byte, source string) error { return err } found = true - return add(rel, data) + if err := addInlineTarget(builder, targetPath, data); err != nil { + return fmt.Errorf("%s: %w", source, err) + } + return nil }) if err != nil { return err @@ -163,57 +194,51 @@ 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 - } +// 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(entry.dir) + component, _ := transferlayout.ParseComponentDir(componentDir) if component == "" { - return files, nil + return "", errors.New("the default component has no component file") } - componentFile := component + ".component" - if _, shipped := files[componentFile]; !shipped { - files[componentFile] = transferlayout.ComponentFile(component) + if rel != component+".component" { + return "", fmt.Errorf("unexpected component file (only %s.component is allowed)", component) } - return files, nil + return transferlayout.ComponentFilePath(component) } // 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 { + componentPath, err := transferlayout.ComponentFilePath(component) + if err != nil { + return fmt.Errorf("component %s: %w", component, 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..de85e4d 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)) @@ -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) @@ -78,25 +79,64 @@ 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") + + // 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 +// 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)) @@ -111,26 +151,39 @@ 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. 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 +206,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 +232,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) 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) + } + }) + } +} 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"))) } diff --git a/internal/xsysupdate/transfer.go b/internal/xsysupdate/transfer.go index 12f7725..c5dd042 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 @@ -228,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) { @@ -253,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 ff18a5b..d165f44 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) { @@ -648,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)