From 4661dc846e0b518f127930ba639153f483e3c24a Mon Sep 17 00:00:00 2001 From: Dan Tsekhanskiy Date: Sun, 12 Apr 2026 14:52:46 +0000 Subject: [PATCH 1/2] docs: Add navigation links to top of examples.md --- docs/examples.md | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/docs/examples.md b/docs/examples.md index 5810ae8..52d26cd 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -4,6 +4,46 @@ How to write, register, compose, and test Converge blueprints, plus a complete r For real-world blueprints, see the [blueprints/](../blueprints/) directory, including [CIS L1 benchmarks](../blueprints/cis/) for Windows, Ubuntu, and macOS. +**Getting started:** +[What Is a Blueprint](#what-is-a-blueprint) · +[Writing a Blueprint](#writing-a-blueprint) · +[Registering in main.go](#registering-in-maingo) · +[Platform-Conditional Logic](#platform-conditional-logic) · +[Dependencies](#explicit-dependencies-with-dependson) · +[Daemon Mode](#daemon-mode-converge-serve) · +[Composition](#blueprint-composition) · +[Testing](#testing-blueprints) + +**Resources:** +[File](#file) · +[Package](#package) · +[Service](#service) · +[Exec](#exec) · +[User](#user) · +[Template](#template) · +[Hostname](#hostname) · +[Cron](#cron) · +[Repository](#repository) · +[Firewall](#firewall) · +[Reboot](#reboot) · +[InShard](#inshard) · +[Secret](#secret--encrypted-config) + +**Platform-specific:** +[Registry](#registry-windows-only) · +[SecurityPolicy](#securitypolicy-windows-only) · +[AuditPolicy](#auditpolicy-windows-only) · +[Sysctl](#sysctl-linux-only) · +[KernelModule](#kernelmodule-linux-only) · +[Plist](#plist-macos-only) + +**[Conditions](#conditions):** +[NetworkInterface](#networkinterface-vpn-gated-firewall-rules) · +[MountPoint](#mountpoint-nfs-backed-service) · +[FileExists](#fileexists-cert-enrollment-after-bootstrap) · +[NetworkReachable](#networkreachable-proxy-config-before-package-installs) · +[RegistryKey/Value](#registrykeyexists--registryvalueexists--registryvalueequals-windows-only) + --- ## What Is a Blueprint From 058e2d33d836cf9c5fb8014931ba8caa77fa5e5f Mon Sep 17 00:00:00 2001 From: Dan Tsekhanskiy Date: Sun, 12 Apr 2026 16:09:20 +0000 Subject: [PATCH 2/2] fix: Address all review findings from issues 17, 19, 21 File extension: mode() mutual exclusion for Content+URL, case-insensitive checksum, applyBlock respects Mode, httpClient redirect restriction, exact block marker matching, remote + block mode test coverage. Exec: ShellParams empty-slice guard, resolveShell dedup (3 return vals). Kernelmodule: module name validation, errors.Is(fs.ErrNotExist), isModuleLoaded/isModuleBlacklisted error propagation. Cron: newline injection validation in Schedule/Command/User/Name. Windows COM: errors.As for OleError type safety. Hostname: shared alreadySet() guard across all platforms. Repository: gpgcheck=1 default for dnf/yum. Docs: design.md hardcoded list replaced with directory link, examples.md nested navigation added. --- docs/design.md | 2 +- docs/examples.md | 60 +-- extensions/cron/cron.go | 21 + extensions/cron/cron_crontab.go | 8 + extensions/cron/cron_windows.go | 14 +- extensions/exec/exec.go | 34 +- extensions/exec/exec_test.go | 36 +- extensions/file/file.go | 42 +- extensions/file/file_test.go | 420 ++++++++++++++++++ extensions/hostname/hostname.go | 13 + extensions/hostname/hostname_darwin.go | 8 + extensions/hostname/hostname_linux.go | 8 + extensions/hostname/hostname_windows.go | 10 +- extensions/kernelmodule/kernelmodule.go | 11 + extensions/kernelmodule/kernelmodule_linux.go | 38 +- .../kernelmodule/kernelmodule_linux_test.go | 6 +- extensions/kernelmodule/kernelmodule_test.go | 27 ++ extensions/pkg/repository.go | 7 +- extensions/pkg/repository_test.go | 7 +- 19 files changed, 672 insertions(+), 100 deletions(-) diff --git a/docs/design.md b/docs/design.md index b9f7035..eb4d8c1 100644 --- a/docs/design.md +++ b/docs/design.md @@ -139,7 +139,7 @@ type Extension interface { | Package | Description | |---------|-------------| | `dsl/` | Public SDK: blueprint types, opts structs, resource methods, shard/config helpers | -| `extensions/` | Resource implementations: file, exec, firewall, pkg, reboot, service, user, registry, secpol, auditpol, sysctl, plist | +| `extensions/` | Resource implementations: one subdirectory per resource type, see directory for full list | | `internal/` | Engine, DAG graph, daemon, auto-edges, exit codes, platform detection, output, logging | | `cmd/converge/` | Cobra CLI entry point, blueprint registration | | `blueprints/` | Built-in blueprints: baseline, linux, darwin, windows, CIS L1 | diff --git a/docs/examples.md b/docs/examples.md index 52d26cd..f5626a1 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -4,45 +4,27 @@ How to write, register, compose, and test Converge blueprints, plus a complete r For real-world blueprints, see the [blueprints/](../blueprints/) directory, including [CIS L1 benchmarks](../blueprints/cis/) for Windows, Ubuntu, and macOS. -**Getting started:** -[What Is a Blueprint](#what-is-a-blueprint) · -[Writing a Blueprint](#writing-a-blueprint) · -[Registering in main.go](#registering-in-maingo) · -[Platform-Conditional Logic](#platform-conditional-logic) · -[Dependencies](#explicit-dependencies-with-dependson) · -[Daemon Mode](#daemon-mode-converge-serve) · -[Composition](#blueprint-composition) · -[Testing](#testing-blueprints) - -**Resources:** -[File](#file) · -[Package](#package) · -[Service](#service) · -[Exec](#exec) · -[User](#user) · -[Template](#template) · -[Hostname](#hostname) · -[Cron](#cron) · -[Repository](#repository) · -[Firewall](#firewall) · -[Reboot](#reboot) · -[InShard](#inshard) · -[Secret](#secret--encrypted-config) - -**Platform-specific:** -[Registry](#registry-windows-only) · -[SecurityPolicy](#securitypolicy-windows-only) · -[AuditPolicy](#auditpolicy-windows-only) · -[Sysctl](#sysctl-linux-only) · -[KernelModule](#kernelmodule-linux-only) · -[Plist](#plist-macos-only) - -**[Conditions](#conditions):** -[NetworkInterface](#networkinterface-vpn-gated-firewall-rules) · -[MountPoint](#mountpoint-nfs-backed-service) · -[FileExists](#fileexists-cert-enrollment-after-bootstrap) · -[NetworkReachable](#networkreachable-proxy-config-before-package-installs) · -[RegistryKey/Value](#registrykeyexists--registryvalueexists--registryvalueequals-windows-only) +- [What Is a Blueprint](#what-is-a-blueprint) +- [Writing a Blueprint](#writing-a-blueprint) +- [Registering in main.go](#registering-in-maingo) +- [Platform-Conditional Logic](#platform-conditional-logic) +- [Explicit Dependencies with DependsOn](#explicit-dependencies-with-dependson) +- [Daemon Mode (`converge serve`)](#daemon-mode-converge-serve) +- [Blueprint Composition](#blueprint-composition) +- [Testing Blueprints](#testing-blueprints) +- [Resource Reference](#resource-reference) + - [File](#file) (content, remote download, block management) + - [Package](#package), [Service](#service), [Exec](#exec) (shell, PowerShell, bash) + - [User](#user), [Firewall](#firewall), [Reboot](#reboot) + - [Template](#template), [Hostname](#hostname), [Cron](#cron), [Repository](#repository) + - [KernelModule](#kernelmodule-linux-only), [Sysctl](#sysctl-linux-only) + - [Registry](#registry-windows-only), [SecurityPolicy](#securitypolicy-windows-only), [AuditPolicy](#auditpolicy-windows-only) + - [Plist](#plist-macos-only) + - [InShard](#inshard), [Secret / Encrypted Config](#secret--encrypted-config) +- [Conditions](#conditions) + - [NetworkInterface](#networkinterface-vpn-gated-firewall-rules), [MountPoint](#mountpoint-nfs-backed-service) + - [FileExists](#fileexists-cert-enrollment-after-bootstrap), [NetworkReachable](#networkreachable-proxy-config-before-package-installs) + - [RegistryKey / RegistryValue](#registrykeyexists--registryvalueexists--registryvalueequals-windows-only) --- diff --git a/extensions/cron/cron.go b/extensions/cron/cron.go index f2c775f..f9cf957 100644 --- a/extensions/cron/cron.go +++ b/extensions/cron/cron.go @@ -4,6 +4,7 @@ package cron import ( "fmt" + "strings" "github.com/TsekNet/converge/extensions" ) @@ -53,3 +54,23 @@ func (c *Cron) fsys() extensions.FS { return extensions.RealFS(c.FS) } func (c *Cron) ID() string { return fmt.Sprintf("cron:%s", c.Name) } func (c *Cron) String() string { return fmt.Sprintf("Cron %s", c.Name) } func (c *Cron) IsCritical() bool { return c.Critical } + +// validate rejects fields containing newline, carriage return, or null bytes. +// These characters could inject additional cron lines or corrupt Task Scheduler +// XML on Windows. +func (c *Cron) validate() error { + const bad = "\n\r\x00" + for _, pair := range []struct { + name, value string + }{ + {"Schedule", c.Schedule}, + {"Command", c.Command}, + {"User", c.User}, + {"Name", c.Name}, + } { + if strings.ContainsAny(pair.value, bad) { + return fmt.Errorf("cron %s: %s contains invalid character (newline, carriage return, or null)", c.Name, pair.name) + } + } + return nil +} diff --git a/extensions/cron/cron_crontab.go b/extensions/cron/cron_crontab.go index 1662648..b5ecf7b 100644 --- a/extensions/cron/cron_crontab.go +++ b/extensions/cron/cron_crontab.go @@ -32,6 +32,10 @@ func (c *Cron) cronFilePath() string { // Check reads the cron.d file to determine if the task exists with correct content. func (c *Cron) Check(_ context.Context) (*extensions.State, error) { + if err := c.validate(); err != nil { + return nil, err + } + path := c.cronFilePath() wantLine := c.cronLine() @@ -79,6 +83,10 @@ func (c *Cron) Check(_ context.Context) (*extensions.State, error) { // Apply creates, updates, or removes the cron.d file. func (c *Cron) Apply(_ context.Context) (*extensions.Result, error) { + if err := c.validate(); err != nil { + return nil, err + } + path := c.cronFilePath() if c.State == "absent" { diff --git a/extensions/cron/cron_windows.go b/extensions/cron/cron_windows.go index fdfed99..84f1319 100644 --- a/extensions/cron/cron_windows.go +++ b/extensions/cron/cron_windows.go @@ -4,6 +4,7 @@ package cron import ( "context" + "errors" "fmt" "github.com/go-ole/go-ole" @@ -14,6 +15,10 @@ import ( // Check queries the Windows Task Scheduler COM API for the named task. func (c *Cron) Check(_ context.Context) (*extensions.State, error) { + if err := c.validate(); err != nil { + return nil, err + } + exists, err := taskExists(c.Name) if err != nil { return nil, fmt.Errorf("query task %s: %w", c.Name, err) @@ -45,6 +50,10 @@ func (c *Cron) Check(_ context.Context) (*extensions.State, error) { // Apply creates or removes a Windows scheduled task via the Task Scheduler COM API. func (c *Cron) Apply(_ context.Context) (*extensions.Result, error) { + if err := c.validate(); err != nil { + return nil, err + } + if c.State == "absent" { if err := deleteTask(c.Name); err != nil { return nil, err @@ -63,7 +72,10 @@ func (c *Cron) Apply(_ context.Context) (*extensions.Result, error) { func withTaskService(fn func(service *ole.IDispatch) error) error { if err := ole.CoInitializeEx(0, ole.COINIT_MULTITHREADED); err != nil { // S_FALSE (0x00000001) means COM was already initialized on this thread. - if err.(*ole.OleError).Code() != 0x00000001 { + var oleErr *ole.OleError + if errors.As(err, &oleErr) && oleErr.Code() == 0x00000001 { + // Safe to continue: COM already initialized. + } else { return fmt.Errorf("CoInitializeEx: %w", err) } } diff --git a/extensions/exec/exec.go b/extensions/exec/exec.go index 32d4ca4..dfb92f8 100644 --- a/extensions/exec/exec.go +++ b/extensions/exec/exec.go @@ -99,17 +99,6 @@ func (e *Exec) ID() string { return fmt.Sprintf("exec:%s", e.Name) } func (e *Exec) String() string { return fmt.Sprintf("Exec %s", e.Name) } func (e *Exec) IsCritical() bool { return e.Critical } -// resolvedShell returns the concrete shell name after resolving "auto". -func (e *Exec) resolvedShell() string { - if e.Shell == ShellAuto { - if runtime.GOOS == "windows" { - return ShellPowerShell - } - return ShellBash - } - return e.Shell -} - // shellCmd builds an exec.Cmd for the given command string, respecting the // Shell setting. When Shell is empty, the command is split on whitespace // (for guards) or used directly with Args (for Apply). @@ -122,11 +111,10 @@ func (e *Exec) shellCmd(ctx context.Context, command string) *exec.Cmd { return exec.CommandContext(ctx, parts[0], parts[1:]...) } - binary, params := e.resolveShell() + binary, params, shell := e.resolveShell() args := make([]string, 0, len(params)+2) args = append(args, params...) - shell := e.resolvedShell() switch shell { case ShellBash, ShellSh: args = append(args, "-c", command) @@ -140,13 +128,23 @@ func (e *Exec) shellCmd(ctx context.Context, command string) *exec.Cmd { return exec.CommandContext(ctx, binary, args...) } -// resolveShell returns the binary path and parameter flags for the configured shell. -func (e *Exec) resolveShell() (binary string, params []string) { - if e.ShellParams != nil { +// resolveShell returns the binary path, parameter flags, and resolved shell +// name for the configured shell. The resolved name accounts for "auto" +// expanding to the platform default. +func (e *Exec) resolveShell() (binary string, params []string, shell string) { + if len(e.ShellParams) > 0 { params = e.ShellParams } - shell := e.resolvedShell() + shell = e.Shell + if shell == ShellAuto { + if runtime.GOOS == "windows" { + shell = ShellPowerShell + } else { + shell = ShellBash + } + } + switch shell { case ShellPowerShell: binary = defaultPowerShellPath @@ -167,7 +165,7 @@ func (e *Exec) resolveShell() (binary string, params []string) { default: binary = shell // allow arbitrary shell path } - return binary, params + return binary, params, shell } // applyCmd builds an exec.Cmd for the Apply command. diff --git a/extensions/exec/exec_test.go b/extensions/exec/exec_test.go index 9400b55..e358204 100644 --- a/extensions/exec/exec_test.go +++ b/extensions/exec/exec_test.go @@ -263,21 +263,25 @@ func TestResolveShell(t *testing.T) { tests := []struct { shell string wantBinary string + wantShell string }{ - {ShellPowerShell, defaultPowerShellPath}, - {ShellPwsh, "pwsh"}, - {ShellCmd, `C:\Windows\System32\cmd.exe`}, - {ShellBash, "/bin/bash"}, - {ShellSh, "/bin/sh"}, - {"/usr/local/bin/zsh", "/usr/local/bin/zsh"}, + {ShellPowerShell, defaultPowerShellPath, ShellPowerShell}, + {ShellPwsh, "pwsh", ShellPwsh}, + {ShellCmd, `C:\Windows\System32\cmd.exe`, ShellCmd}, + {ShellBash, "/bin/bash", ShellBash}, + {ShellSh, "/bin/sh", ShellSh}, + {"/usr/local/bin/zsh", "/usr/local/bin/zsh", "/usr/local/bin/zsh"}, } for _, tt := range tests { t.Run(tt.shell, func(t *testing.T) { e := &Exec{Shell: tt.shell} - binary, _ := e.resolveShell() + binary, _, shell := e.resolveShell() if binary != tt.wantBinary { t.Errorf("binary = %q, want %q", binary, tt.wantBinary) } + if shell != tt.wantShell { + t.Errorf("shell = %q, want %q", shell, tt.wantShell) + } }) } } @@ -287,29 +291,37 @@ func TestResolveShell_CustomParams(t *testing.T) { Shell: ShellPowerShell, ShellParams: []string{"-ExecutionPolicy", "RemoteSigned"}, } - _, params := e.resolveShell() + _, params, _ := e.resolveShell() if len(params) != 2 || params[0] != "-ExecutionPolicy" { t.Errorf("params = %v, want custom params", params) } } -func TestResolvedShell_Auto(t *testing.T) { +func TestResolveShell_Auto(t *testing.T) { e := &Exec{Shell: ShellAuto} - got := e.resolvedShell() + _, _, got := e.resolveShell() // On Linux (CI), auto resolves to bash if got != ShellBash && got != ShellPowerShell { - t.Errorf("resolvedShell() = %q, want bash or powershell", got) + t.Errorf("resolveShell() shell = %q, want bash or powershell", got) } } func TestResolveShell_DefaultPSParams(t *testing.T) { e := &Exec{Shell: ShellPowerShell} - _, params := e.resolveShell() + _, params, _ := e.resolveShell() if len(params) != len(defaultPSParams) { t.Errorf("params = %v, want default PS params %v", params, defaultPSParams) } } +func TestResolveShell_EmptySliceGetsDefaults(t *testing.T) { + e := &Exec{Shell: ShellPowerShell, ShellParams: []string{}} + _, params, _ := e.resolveShell() + if len(params) != len(defaultPSParams) { + t.Errorf("empty ShellParams should get defaults, got %v", params) + } +} + func TestTruncate(t *testing.T) { tests := []struct { input string diff --git a/extensions/file/file.go b/extensions/file/file.go index c815fd4..86126eb 100644 --- a/extensions/file/file.go +++ b/extensions/file/file.go @@ -21,7 +21,18 @@ import ( const maxDownloadSize = 512 << 20 // 512 MiB // httpClient is a shared client with a sane timeout for remote downloads. -var httpClient = &http.Client{Timeout: 30 * time.Second} +var httpClient = &http.Client{ + Timeout: 30 * time.Second, + CheckRedirect: func(req *http.Request, via []*http.Request) error { + if len(via) >= 3 { + return fmt.Errorf("too many redirects") + } + if req.URL.Host != via[0].URL.Host { + return fmt.Errorf("redirect to different host: %s", req.URL.Host) + } + return nil + }, +} // File manages content, permissions, and ownership of a file on disk. // @@ -127,6 +138,9 @@ func (f *File) mode() (string, error) { if count > 1 { return "", fmt.Errorf("file %s: URL and BlockName are mutually exclusive", f.Path) } + if f.URL != "" && f.Content != "" { + return "", fmt.Errorf("file %s: Content and URL are mutually exclusive", f.Path) + } return active, nil } @@ -277,7 +291,7 @@ func (f *File) checkRemote() (*extensions.State, error) { if err != nil { return nil, fmt.Errorf("checksum %s: %w", absPath, err) } - if actual != f.Checksum { + if !strings.EqualFold(actual, f.Checksum) { changes = append(changes, extensions.Change{ Property: "sha256", From: actual[:min(12, len(actual))] + "...", @@ -311,7 +325,7 @@ func (f *File) applyRemote(ctx context.Context) (*extensions.Result, error) { } actual := sha256Hex(data) - if actual != f.Checksum { + if !strings.EqualFold(actual, f.Checksum) { return nil, fmt.Errorf("checksum mismatch for %s: got %s, want %s", f.Path, actual, f.Checksum) } @@ -457,7 +471,11 @@ func (f *File) applyBlock() (*extensions.Result, error) { if err := f.fsys().MkdirAll(dir, 0755); err != nil { return nil, fmt.Errorf("mkdir %s: %w", dir, err) } - if err := f.fsys().WriteFile(absPath, []byte(result), 0644); err != nil { + perm := f.Mode + if perm == 0 { + perm = 0644 + } + if err := f.fsys().WriteFile(absPath, []byte(result), perm); err != nil { return nil, fmt.Errorf("write %s: %w", absPath, err) } @@ -476,12 +494,11 @@ func extractBlock(data, beginMarker, endMarker string) (string, error) { var block []string for _, line := range lines { - trimmed := strings.TrimSpace(line) - if trimmed == beginMarker { + if line == beginMarker { inside = true continue } - if trimmed == endMarker { + if line == endMarker { if !inside { continue } @@ -510,14 +527,13 @@ func upsertBlock(data, beginMarker, endMarker, block string) string { var replaced bool for _, line := range lines { - trimmed := strings.TrimSpace(line) - if trimmed == beginMarker { + if line == beginMarker { inside = true replaced = true result = append(result, strings.Split(block, "\n")...) continue } - if trimmed == endMarker { + if line == endMarker { inside = false continue } @@ -542,12 +558,11 @@ func removeBlock(data, beginMarker, endMarker string) string { var inside bool for _, line := range lines { - trimmed := strings.TrimSpace(line) - if trimmed == beginMarker { + if line == beginMarker { inside = true continue } - if trimmed == endMarker { + if line == endMarker { inside = false continue } @@ -624,6 +639,7 @@ func summarizeContent(s string) string { return fmt.Sprintf("%d lines, %d bytes", lines, len(s)) } +// TODO: extract to shared helper (duplicated in exec, template, repository) func truncate(s string, maxLen int) string { s = strings.TrimRight(s, "\n\r") if len(s) <= maxLen { diff --git a/extensions/file/file_test.go b/extensions/file/file_test.go index 59f4909..9f6c78b 100644 --- a/extensions/file/file_test.go +++ b/extensions/file/file_test.go @@ -2,6 +2,11 @@ package file import ( "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "net/http" + "net/http/httptest" "os" "path/filepath" "testing" @@ -351,3 +356,418 @@ func TestFile_MapFS_ContentDrift(t *testing.T) { t.Error("should report changes") } } + +// --- Remote mode tests (URL + Checksum) --- + +func sha256sum(data []byte) string { + h := sha256.Sum256(data) + return hex.EncodeToString(h[:]) +} + +func TestFile_Remote_CheckMissing(t *testing.T) { + mfs := testutil.NewMapFS() + f := New("/opt/tool", Opts{ + URL: "https://example.com/tool", + Checksum: "abc123", + FS: mfs, + }) + testutil.AssertDrifted(t, f) +} + +func TestFile_Remote_CheckChecksumMatch(t *testing.T) { + mfs := testutil.NewMapFS() + content := []byte("binary-content-here") + mfs.Set("/opt/tool", content, 0755) + + f := New("/opt/tool", Opts{ + URL: "https://example.com/tool", + Checksum: sha256sum(content), + FS: mfs, + }) + testutil.AssertInSync(t, f) +} + +func TestFile_Remote_CheckChecksumMismatch(t *testing.T) { + mfs := testutil.NewMapFS() + mfs.Set("/opt/tool", []byte("old-version"), 0755) + + f := New("/opt/tool", Opts{ + URL: "https://example.com/tool", + Checksum: sha256sum([]byte("new-version")), + FS: mfs, + }) + testutil.AssertDrifted(t, f) +} + +func TestFile_Remote_ApplyAndVerify(t *testing.T) { + body := []byte("downloaded-payload-v2") + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Write(body) + })) + defer ts.Close() + + mfs := testutil.NewMapFS() + f := New("/opt/tool", Opts{ + URL: ts.URL + "/tool", + Checksum: sha256sum(body), + Mode: 0755, + FS: mfs, + }) + + ctx := context.Background() + result, err := f.Apply(ctx) + if err != nil { + t.Fatalf("Apply() error = %v", err) + } + if !result.Changed { + t.Error("Apply() should report Changed=true") + } + + got, ok := mfs.Get("/opt/tool") + if !ok { + t.Fatal("file should exist after Apply") + } + if string(got) != string(body) { + t.Errorf("content = %q, want %q", got, body) + } + + // Verify Check reports in-sync after Apply. + f2 := New("/opt/tool", Opts{ + URL: ts.URL + "/tool", + Checksum: sha256sum(body), + Mode: 0755, + FS: mfs, + }) + testutil.AssertInSync(t, f2) +} + +func TestFile_Remote_ChecksumMismatchRejectsDownload(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte("wrong-content")) + })) + defer ts.Close() + + mfs := testutil.NewMapFS() + f := New("/opt/tool", Opts{ + URL: ts.URL + "/tool", + Checksum: sha256sum([]byte("expected-content")), + FS: mfs, + }) + + ctx := context.Background() + _, err := f.Apply(ctx) + if err == nil { + t.Fatal("Apply() should error on checksum mismatch") + } +} + +func TestFile_Remote_RequiresChecksum(t *testing.T) { + mfs := testutil.NewMapFS() + f := New("/opt/tool", Opts{ + URL: "https://example.com/tool", + FS: mfs, + }) + + ctx := context.Background() + _, err := f.Check(ctx) + if err == nil { + t.Fatal("Check() should error when Checksum is empty with URL") + } +} + +func TestFile_Remote_MutualExclusion(t *testing.T) { + mfs := testutil.NewMapFS() + f := New("/opt/tool", Opts{ + Content: "literal", + URL: "https://example.com/tool", + Checksum: "abc", + FS: mfs, + }) + + ctx := context.Background() + _, err := f.Check(ctx) + if err == nil { + t.Fatal("Check() should error when both Content and URL are set") + } +} + +// --- Block mode tests (BlockName) --- + +func TestFile_Block_CheckMissing(t *testing.T) { + mfs := testutil.NewMapFS() + f := New("/etc/config", Opts{ + BlockName: "myapp", + Content: "key=value", + FS: mfs, + }) + testutil.AssertDrifted(t, f) +} + +func TestFile_Block_CheckInSync(t *testing.T) { + mfs := testutil.NewMapFS() + existing := "# BEGIN converge:myapp\nkey=value\n# END converge:myapp\n" + mfs.Set("/etc/config", []byte(existing), 0644) + + f := New("/etc/config", Opts{ + BlockName: "myapp", + Content: "key=value", + FS: mfs, + }) + testutil.AssertInSync(t, f) +} + +func TestFile_Block_CheckDrift(t *testing.T) { + mfs := testutil.NewMapFS() + existing := "# BEGIN converge:myapp\nold=value\n# END converge:myapp\n" + mfs.Set("/etc/config", []byte(existing), 0644) + + f := New("/etc/config", Opts{ + BlockName: "myapp", + Content: "new=value", + FS: mfs, + }) + testutil.AssertDrifted(t, f) +} + +func TestFile_Block_Converges(t *testing.T) { + mfs := testutil.NewMapFS() + f := New("/etc/config", Opts{ + BlockName: "myapp", + Content: "key=value", + FS: mfs, + }) + testutil.AssertConverges(t, f) +} + +func TestFile_Block_InsertIntoExisting(t *testing.T) { + mfs := testutil.NewMapFS() + mfs.Set("/etc/config", []byte("header=true\n"), 0644) + + f := New("/etc/config", Opts{ + BlockName: "myapp", + Content: "key=value", + FS: mfs, + }) + + ctx := context.Background() + _, err := f.Apply(ctx) + if err != nil { + t.Fatalf("Apply() error = %v", err) + } + + data, _ := mfs.Get("/etc/config") + got := string(data) + want := "header=true\n\n# BEGIN converge:myapp\nkey=value\n# END converge:myapp" + if got != want { + t.Errorf("content =\n%q\nwant\n%q", got, want) + } +} + +func TestFile_Block_UpdateExisting(t *testing.T) { + mfs := testutil.NewMapFS() + existing := "before\n# BEGIN converge:myapp\nold=val\n# END converge:myapp\nafter" + mfs.Set("/etc/config", []byte(existing), 0644) + + f := New("/etc/config", Opts{ + BlockName: "myapp", + Content: "new=val", + FS: mfs, + }) + + ctx := context.Background() + _, err := f.Apply(ctx) + if err != nil { + t.Fatalf("Apply() error = %v", err) + } + + data, _ := mfs.Get("/etc/config") + got := string(data) + want := "before\n# BEGIN converge:myapp\nnew=val\n# END converge:myapp\nafter" + if got != want { + t.Errorf("content =\n%q\nwant\n%q", got, want) + } +} + +func TestFile_Block_Remove(t *testing.T) { + mfs := testutil.NewMapFS() + existing := "before\n# BEGIN converge:myapp\nkey=value\n# END converge:myapp\nafter" + mfs.Set("/etc/config", []byte(existing), 0644) + + f := New("/etc/config", Opts{ + BlockName: "myapp", + State: "absent", + FS: mfs, + }) + + ctx := context.Background() + _, err := f.Apply(ctx) + if err != nil { + t.Fatalf("Apply() error = %v", err) + } + + data, _ := mfs.Get("/etc/config") + got := string(data) + want := "before\nafter" + if got != want { + t.Errorf("content =\n%q\nwant\n%q", got, want) + } +} + +func TestFile_Block_MissingEndMarker(t *testing.T) { + mfs := testutil.NewMapFS() + // Begin marker without matching end marker. + existing := "# BEGIN converge:myapp\nkey=value\n" + mfs.Set("/etc/config", []byte(existing), 0644) + + f := New("/etc/config", Opts{ + BlockName: "myapp", + Content: "key=value", + FS: mfs, + }) + + ctx := context.Background() + _, err := f.Check(ctx) + if err == nil { + t.Fatal("Check() should error when end marker is missing") + } +} + +func TestFile_Block_RespectsMode(t *testing.T) { + mfs := testutil.NewMapFS() + f := New("/etc/config", Opts{ + BlockName: "myapp", + Content: "key=value", + Mode: 0600, + FS: mfs, + }) + + ctx := context.Background() + _, err := f.Apply(ctx) + if err != nil { + t.Fatalf("Apply() error = %v", err) + } + + info, err := mfs.Stat("/etc/config") + if err != nil { + t.Fatalf("Stat() error = %v", err) + } + if info.Mode().Perm() != 0600 { + t.Errorf("mode = %04o, want 0600", info.Mode().Perm()) + } +} + +// --- Helper unit tests --- + +func TestExtractBlock(t *testing.T) { + begin := "# BEGIN converge:test" + end := "# END converge:test" + + tests := []struct { + name string + data string + want string + wantErr bool + }{ + { + name: "block present", + data: fmt.Sprintf("before\n%s\ncontent-line\n%s\nafter", begin, end), + want: "content-line", + }, + { + name: "block absent", + data: "no markers here", + want: "", + }, + { + name: "empty block", + data: fmt.Sprintf("%s\n%s", begin, end), + want: "", + }, + { + name: "missing end marker", + data: fmt.Sprintf("%s\ncontent-line\n", begin), + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := extractBlock(tt.data, begin, end) + if tt.wantErr { + if err == nil { + t.Fatal("expected error, got nil") + } + return + } + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if got != tt.want { + t.Errorf("extractBlock() = %q, want %q", got, tt.want) + } + }) + } +} + +func TestUpsertBlock(t *testing.T) { + begin := "# BEGIN converge:test" + end := "# END converge:test" + block := begin + "\nnew-content\n" + end + + tests := []struct { + name string + data string + want string + }{ + { + name: "insert into empty", + data: "", + want: fmt.Sprintf("\n%s\nnew-content\n%s", begin, end), + }, + { + name: "replace existing", + data: fmt.Sprintf("before\n%s\nold-content\n%s\nafter", begin, end), + want: fmt.Sprintf("before\n%s\nnew-content\n%s\nafter", begin, end), + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := upsertBlock(tt.data, begin, end, block) + if got != tt.want { + t.Errorf("upsertBlock() =\n%q\nwant\n%q", got, tt.want) + } + }) + } +} + +func TestRemoveBlock(t *testing.T) { + begin := "# BEGIN converge:test" + end := "# END converge:test" + + tests := []struct { + name string + data string + want string + }{ + { + name: "block present", + data: fmt.Sprintf("before\n%s\ncontent\n%s\nafter", begin, end), + want: "before\nafter", + }, + { + name: "block absent", + data: "no markers here", + want: "no markers here", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := removeBlock(tt.data, begin, end) + if got != tt.want { + t.Errorf("removeBlock() = %q, want %q", got, tt.want) + } + }) + } +} diff --git a/extensions/hostname/hostname.go b/extensions/hostname/hostname.go index ede5df5..83408b1 100644 --- a/extensions/hostname/hostname.go +++ b/extensions/hostname/hostname.go @@ -34,6 +34,19 @@ func (h *Hostname) ID() string { return "hostname:" + h.Name } func (h *Hostname) String() string { return "Hostname " + h.Name } func (h *Hostname) IsCritical() bool { return h.Critical } +// alreadySet returns true if the current hostname already matches. +// Also returns an error if the name is empty. +func (h *Hostname) alreadySet() (bool, error) { + if h.Name == "" { + return false, fmt.Errorf("hostname: name must not be empty") + } + current, err := os.Hostname() + if err != nil { + return false, fmt.Errorf("read hostname: %w", err) + } + return current == h.Name, nil +} + // Check compares the current hostname to the desired value. func (h *Hostname) Check(_ context.Context) (*extensions.State, error) { current, err := os.Hostname() diff --git a/extensions/hostname/hostname_darwin.go b/extensions/hostname/hostname_darwin.go index 689dedc..9ebe44b 100644 --- a/extensions/hostname/hostname_darwin.go +++ b/extensions/hostname/hostname_darwin.go @@ -18,6 +18,14 @@ const sysSetHostname = 88 // Apply sets the hostname via the sethostname(2) syscall on macOS. func (h *Hostname) Apply(_ context.Context) (*extensions.Result, error) { + match, err := h.alreadySet() + if err != nil { + return nil, err + } + if match { + return &extensions.Result{Changed: false, Status: extensions.StatusOK, Message: "already set"}, nil + } + name := []byte(h.Name) _, _, errno := unix.Syscall( sysSetHostname, diff --git a/extensions/hostname/hostname_linux.go b/extensions/hostname/hostname_linux.go index 29546bf..0946273 100644 --- a/extensions/hostname/hostname_linux.go +++ b/extensions/hostname/hostname_linux.go @@ -14,6 +14,14 @@ import ( // Apply sets the hostname via the sethostname syscall and persists it // to /etc/hostname for survival across reboots. func (h *Hostname) Apply(_ context.Context) (*extensions.Result, error) { + match, err := h.alreadySet() + if err != nil { + return nil, err + } + if match { + return &extensions.Result{Changed: false, Status: extensions.StatusOK, Message: "already set"}, nil + } + if err := unix.Sethostname([]byte(h.Name)); err != nil { return nil, fmt.Errorf("sethostname(%s): %w", h.Name, err) } diff --git a/extensions/hostname/hostname_windows.go b/extensions/hostname/hostname_windows.go index 21ebbe6..c69043d 100644 --- a/extensions/hostname/hostname_windows.go +++ b/extensions/hostname/hostname_windows.go @@ -20,13 +20,19 @@ var ( // Apply sets the Windows hostname via SetComputerNameExW. // A reboot is required for the change to take effect. func (h *Hostname) Apply(_ context.Context) (*extensions.Result, error) { + match, err := h.alreadySet() + if err != nil { + return nil, err + } + if match { + return &extensions.Result{Changed: false, Status: extensions.StatusOK, Message: "already set"}, nil + } + namePtr, err := windows.UTF16PtrFromString(h.Name) if err != nil { return nil, fmt.Errorf("encode hostname %q: %w", h.Name, err) } - // SetComputerNameExW(ComputerNamePhysicalDnsHostname, lpBuffer) - // ComputerNamePhysicalDnsHostname = 5 ret, _, callErr := procSetComputerNameExW.Call( windows.ComputerNamePhysicalDnsHostname, uintptr(unsafe.Pointer(namePtr)), diff --git a/extensions/kernelmodule/kernelmodule.go b/extensions/kernelmodule/kernelmodule.go index f563b5f..a529c37 100644 --- a/extensions/kernelmodule/kernelmodule.go +++ b/extensions/kernelmodule/kernelmodule.go @@ -6,6 +6,7 @@ package kernelmodule import ( "fmt" + "regexp" ) // StateType represents whether the module should be loaded or blacklisted. @@ -38,6 +39,16 @@ func New(module string, opts Opts) *KernelModule { } } +var validModuleName = regexp.MustCompile(`^[a-zA-Z0-9_-]+$`) + +// validate returns an error if the module name contains invalid characters. +func (k *KernelModule) validate() error { + if !validModuleName.MatchString(k.Module) { + return fmt.Errorf("invalid module name %q: must match [a-zA-Z0-9_-]+", k.Module) + } + return nil +} + func (k *KernelModule) ID() string { return fmt.Sprintf("kernelmodule:%s", k.Module) } func (k *KernelModule) String() string { return fmt.Sprintf("KernelModule %s (%s)", k.Module, k.State) } func (k *KernelModule) IsCritical() bool { return k.Critical } diff --git a/extensions/kernelmodule/kernelmodule_linux.go b/extensions/kernelmodule/kernelmodule_linux.go index 790b7be..43daa49 100644 --- a/extensions/kernelmodule/kernelmodule_linux.go +++ b/extensions/kernelmodule/kernelmodule_linux.go @@ -5,7 +5,9 @@ package kernelmodule import ( "bufio" "context" + "errors" "fmt" + "io/fs" "os" "path/filepath" "strings" @@ -21,12 +23,19 @@ const ( // Check reads /proc/modules for loaded state and /etc/modprobe.d/ for blacklist state. func (k *KernelModule) Check(_ context.Context) (*extensions.State, error) { + if err := k.validate(); err != nil { + return nil, err + } + loaded, err := isModuleLoaded(k.Module) if err != nil { return nil, fmt.Errorf("check module %s: %w", k.Module, err) } - blacklisted := isModuleBlacklisted(k.Module) + blacklisted, err := isModuleBlacklisted(k.Module) + if err != nil { + return nil, fmt.Errorf("check blacklist %s: %w", k.Module, err) + } switch k.State { case Loaded: @@ -70,12 +79,19 @@ func (k *KernelModule) Check(_ context.Context) (*extensions.State, error) { // Apply loads or blacklists the module. func (k *KernelModule) Apply(_ context.Context) (*extensions.Result, error) { + if err := k.validate(); err != nil { + return nil, err + } + switch k.State { case Loaded: if err := removeFromBlacklist(k.Module); err != nil { return nil, fmt.Errorf("remove blacklist %s: %w", k.Module, err) } - loaded, _ := isModuleLoaded(k.Module) + loaded, err := isModuleLoaded(k.Module) + if err != nil { + return nil, fmt.Errorf("check module %s: %w", k.Module, err) + } if !loaded { if err := loadModule(k.Module); err != nil { return nil, fmt.Errorf("load module %s: %w", k.Module, err) @@ -84,7 +100,10 @@ func (k *KernelModule) Apply(_ context.Context) (*extensions.Result, error) { return &extensions.Result{Changed: true, Status: extensions.StatusChanged, Message: "loaded"}, nil case Blacklisted: - loaded, _ := isModuleLoaded(k.Module) + loaded, err := isModuleLoaded(k.Module) + if err != nil { + return nil, fmt.Errorf("check module %s: %w", k.Module, err) + } if loaded { if err := unloadModule(k.Module); err != nil { return nil, fmt.Errorf("unload module %s: %w", k.Module, err) @@ -119,19 +138,22 @@ func isModuleLoaded(module string) (bool, error) { } // isModuleBlacklisted checks for a blacklist entry in /etc/modprobe.d/converge-blacklist.conf. -func isModuleBlacklisted(module string) bool { +func isModuleBlacklisted(module string) (bool, error) { path := filepath.Join(modprobeDir, blacklistFile) data, err := os.ReadFile(path) + if errors.Is(err, fs.ErrNotExist) { + return false, nil + } if err != nil { - return false + return false, fmt.Errorf("read %s: %w", path, err) } line := fmt.Sprintf("blacklist %s", module) for _, l := range strings.Split(string(data), "\n") { if strings.TrimSpace(l) == line { - return true + return true, nil } } - return false + return false, nil } // loadModule loads a kernel module using /sbin/modprobe via finit_module. @@ -195,7 +217,7 @@ func addToBlacklist(module string) error { func removeFromBlacklist(module string) error { path := filepath.Join(modprobeDir, blacklistFile) data, err := os.ReadFile(path) - if os.IsNotExist(err) { + if errors.Is(err, fs.ErrNotExist) { return nil } if err != nil { diff --git a/extensions/kernelmodule/kernelmodule_linux_test.go b/extensions/kernelmodule/kernelmodule_linux_test.go index f444bd3..1793aac 100644 --- a/extensions/kernelmodule/kernelmodule_linux_test.go +++ b/extensions/kernelmodule/kernelmodule_linux_test.go @@ -23,7 +23,11 @@ func TestIsModuleLoaded(t *testing.T) { func TestIsModuleBlacklisted(t *testing.T) { // Should be false for a nonexistent module with no blacklist file - if isModuleBlacklisted("nonexistent_fake_module_xyz") { + blacklisted, err := isModuleBlacklisted("nonexistent_fake_module_xyz") + if err != nil { + t.Fatalf("isModuleBlacklisted() error: %v", err) + } + if blacklisted { t.Error("should not be blacklisted without a blacklist file") } } diff --git a/extensions/kernelmodule/kernelmodule_test.go b/extensions/kernelmodule/kernelmodule_test.go index 3f7a20f..c5539a0 100644 --- a/extensions/kernelmodule/kernelmodule_test.go +++ b/extensions/kernelmodule/kernelmodule_test.go @@ -50,3 +50,30 @@ func TestNew(t *testing.T) { t.Errorf("State = %q, want %q", k.State, Loaded) } } + +func TestKernelModule_Validate(t *testing.T) { + tests := []struct { + name string + module string + wantErr bool + }{ + {"valid simple", "cramfs", false}, + {"valid underscore", "snd_hda_intel", false}, + {"valid hyphen", "nf-conntrack", false}, + {"valid mixed", "vfat_v2-test", false}, + {"invalid space", "my module", true}, + {"invalid slash", "../etc/passwd", true}, + {"invalid semicolon", "mod;rm -rf /", true}, + {"invalid empty", "", true}, + {"invalid dot", "mod.ko", true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + k := New(tt.module, Opts{State: Loaded}) + err := k.validate() + if (err != nil) != tt.wantErr { + t.Errorf("validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} diff --git a/extensions/pkg/repository.go b/extensions/pkg/repository.go index e68355c..27ee0c4 100644 --- a/extensions/pkg/repository.go +++ b/extensions/pkg/repository.go @@ -93,11 +93,12 @@ func (r *Repository) repoContent() string { } else { fmt.Fprintln(&b, "enabled=0") } + // Always enable GPG checking. When GPGKey is provided, include + // the gpgkey= line. Otherwise, the repo-level or system-level + // GPG keys must already be configured (e.g. rpm --import). + fmt.Fprintln(&b, "gpgcheck=1") if r.GPGKey != "" { - fmt.Fprintln(&b, "gpgcheck=1") fmt.Fprintf(&b, "gpgkey=%s\n", r.GPGKey) - } else { - fmt.Fprintln(&b, "gpgcheck=0") } return b.String() default: diff --git a/extensions/pkg/repository_test.go b/extensions/pkg/repository_test.go index 3b5ece9..11c5e6c 100644 --- a/extensions/pkg/repository_test.go +++ b/extensions/pkg/repository_test.go @@ -78,8 +78,11 @@ func TestRepository_RepoContent_Dnf(t *testing.T) { func TestRepository_RepoContent_Dnf_NoGPG(t *testing.T) { r := NewRepository("local", RepositoryOpts{URI: "file:///opt/repo/", ManagerName: "dnf", Enabled: true}) got := r.repoContent() - if !strings.Contains(got, "gpgcheck=0") { - t.Errorf("should have gpgcheck=0 when no GPGKey, got: %s", got) + if !strings.Contains(got, "gpgcheck=1") { + t.Errorf("should have gpgcheck=1 even when no GPGKey, got: %s", got) + } + if strings.Contains(got, "gpgkey=") { + t.Errorf("should not have gpgkey= line when GPGKey is empty, got: %s", got) } }