Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
22 changes: 22 additions & 0 deletions docs/examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,28 @@ 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.

- [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)

---

## What Is a Blueprint
Expand Down
21 changes: 21 additions & 0 deletions extensions/cron/cron.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package cron

import (
"fmt"
"strings"

"github.com/TsekNet/converge/extensions"
)
Expand Down Expand Up @@ -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
}
8 changes: 8 additions & 0 deletions extensions/cron/cron_crontab.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -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" {
Expand Down
14 changes: 13 additions & 1 deletion extensions/cron/cron_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package cron

import (
"context"
"errors"
"fmt"

"github.com/go-ole/go-ole"
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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)
}
}
Expand Down
34 changes: 16 additions & 18 deletions extensions/exec/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand All @@ -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)
Expand All @@ -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
Expand All @@ -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.
Expand Down
36 changes: 24 additions & 12 deletions extensions/exec/exec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
})
}
}
Expand All @@ -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
Expand Down
42 changes: 29 additions & 13 deletions extensions/file/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
//
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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))] + "...",
Expand Down Expand Up @@ -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)
}

Expand Down Expand Up @@ -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)
}

Expand All @@ -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
}
Expand Down Expand Up @@ -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
}
Expand All @@ -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
}
Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading