feat(host): typed host actions: delete old files, enable and disable an allowed timer, set one config key (archie #1982)
publish / publish (push) Successful in 1m10s
publish / publish (push) Successful in 1m10s
This commit is contained in:
11 files changed
+825
-20
No files matched your search
@@ -0,0 +1,365 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json/jsontext"
|
||||
json "encoding/json/v2"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/samcharles93/archipelago/sdk/connector"
|
||||
connectorv1 "github.com/samcharles93/archipelago/sdk/connector/v1"
|
||||
)
|
||||
|
||||
const (
|
||||
actionDeleteFiles = "delete_files"
|
||||
actionEnableTimer = "enable_timer"
|
||||
actionDisableTimer = "disable_timer"
|
||||
actionSetConfig = "set_config_key"
|
||||
|
||||
maxAgeHours = 24 * 365 * 10
|
||||
maxValueLen = 1024
|
||||
)
|
||||
|
||||
var (
|
||||
timerName = regexp.MustCompile(`^[A-Za-z0-9:_.@-]{1,200}\.timer$`)
|
||||
configKey = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_.-]{0,127}$`)
|
||||
hostNameRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,252}$`)
|
||||
errNoHelper = errors.New("timers need the sudo helpers: set helpers on the host")
|
||||
)
|
||||
|
||||
// checkActionSettings validates what the actions rely on, so a bad setting
|
||||
// fails the connector at start rather than an action at run time.
|
||||
func (t *Target) checkActionSettings() error {
|
||||
if !hostNameRe.MatchString(t.Name) {
|
||||
return fmt.Errorf("name %q isn't a plain host name", t.Name)
|
||||
}
|
||||
for i, dir := range t.Disposable {
|
||||
if !path.IsAbs(dir) {
|
||||
return fmt.Errorf("disposable directory %q must be absolute", dir)
|
||||
}
|
||||
clean := path.Clean(dir)
|
||||
if clean == "/" {
|
||||
return errors.New("the root directory can't be disposable")
|
||||
}
|
||||
if _, err := checkPath(clean, t.Paths); err != nil {
|
||||
return fmt.Errorf("disposable directory: %w", err)
|
||||
}
|
||||
t.Disposable[i] = clean
|
||||
}
|
||||
for _, timer := range t.Timers {
|
||||
if !timerName.MatchString(timer) {
|
||||
return fmt.Errorf("timer %q must be a unit name ending in .timer", timer)
|
||||
}
|
||||
}
|
||||
if len(t.Timers) > 0 && !t.Helpers {
|
||||
return errNoHelper
|
||||
}
|
||||
for i, file := range t.ConfigFiles {
|
||||
if err := plainPath(file); err != nil {
|
||||
return fmt.Errorf("config file %q: %w", file, err)
|
||||
}
|
||||
t.ConfigFiles[i] = path.Clean(file)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func plainPath(p string) error {
|
||||
if !path.IsAbs(p) {
|
||||
return errors.New("must be absolute")
|
||||
}
|
||||
if strings.ContainsFunc(p, func(r rune) bool { return r < 0x20 || r == 0x7f }) {
|
||||
return errors.New("contains control characters")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *host) actionTypes() []*connectorv1.ActionType {
|
||||
var timers, configs bool
|
||||
for _, t := range h.targets {
|
||||
timers = timers || len(t.Timers) > 0
|
||||
configs = configs || len(t.ConfigFiles) > 0
|
||||
}
|
||||
hostProp := `"host":{"type":"string"}`
|
||||
types := []*connectorv1.ActionType{{
|
||||
Name: actionDeleteFiles,
|
||||
Description: "Delete the regular files directly or deeply under a directory on a host whose name matches a glob and that were not modified for at least a number of hours. The directory must be under the host's configured roots.",
|
||||
InputSchema: []byte(`{"type":"object","required":["host","directory","pattern","older_than_hours"],"additionalProperties":false,"properties":{` + hostProp +
|
||||
`,"directory":{"type":"string","description":"An absolute directory."},"pattern":{"type":"string","description":"A file name glob such as *.log; no path separators."},"older_than_hours":{"type":"integer","minimum":1}}}`),
|
||||
Effect: &connectorv1.Effect{Reversibility: connectorv1.Reversibility_REVERSIBILITY_IRREVERSIBLE, Summary: "Deletes files; irreversible unless the directory is one the host declares disposable."},
|
||||
Idempotent: true,
|
||||
}}
|
||||
if timers {
|
||||
schema := []byte(`{"type":"object","required":["host","timer"],"additionalProperties":false,"properties":{` + hostProp + `,"timer":{"type":"string","description":"A systemd timer unit name from the host's allow-list."}}}`)
|
||||
types = append(types,
|
||||
&connectorv1.ActionType{Name: actionDisableTimer, Description: "Disable and stop a systemd timer on a host.", InputSchema: schema, Idempotent: true,
|
||||
Effect: &connectorv1.Effect{Reversibility: connectorv1.Reversibility_REVERSIBILITY_UNDONE_AUTOMATICALLY, Summary: "Disables and stops a timer; enabling it again undoes this."}},
|
||||
&connectorv1.ActionType{Name: actionEnableTimer, Description: "Enable and start a systemd timer on a host.", InputSchema: schema, Idempotent: true,
|
||||
Effect: &connectorv1.Effect{Reversibility: connectorv1.Reversibility_REVERSIBILITY_UNDONE_AUTOMATICALLY, Summary: "Enables and starts a timer; disabling it again undoes this."}},
|
||||
)
|
||||
}
|
||||
if configs {
|
||||
types = append(types, &connectorv1.ActionType{
|
||||
Name: actionSetConfig,
|
||||
Description: "Set one KEY=VALUE line in a config file the host allows, keeping a backup of the file as it was.",
|
||||
InputSchema: []byte(`{"type":"object","required":["host","file","key","value"],"additionalProperties":false,"properties":{` + hostProp +
|
||||
`,"file":{"type":"string","description":"An absolute path from the host's allow-list."},"key":{"type":"string"},"value":{"type":"string","description":"A single line."}}}`),
|
||||
Effect: &connectorv1.Effect{Reversibility: connectorv1.Reversibility_REVERSIBILITY_RECOVERABLE, Summary: "Changes one setting in a config file; the previous file is kept beside it."},
|
||||
Idempotent: true,
|
||||
})
|
||||
}
|
||||
return types
|
||||
}
|
||||
|
||||
type actionInput struct {
|
||||
Host string `json:"host"`
|
||||
Directory string `json:"directory"`
|
||||
Pattern string `json:"pattern"`
|
||||
OlderThanHours int `json:"older_than_hours"`
|
||||
Timer string `json:"timer"`
|
||||
File string `json:"file"`
|
||||
Key string `json:"key"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
// plan is an action checked against its host and ready to run.
|
||||
type plan struct {
|
||||
target Target
|
||||
command func(key string) string
|
||||
effect *connectorv1.Effect
|
||||
disposable bool
|
||||
// report builds the output from the command's stdout.
|
||||
report func(out []byte) (any, error)
|
||||
}
|
||||
|
||||
func (h *host) plan(action string, raw jsontext.Value) (plan, error) {
|
||||
var in actionInput
|
||||
if err := json.Unmarshal(raw, &in, json.RejectUnknownMembers(true)); err != nil {
|
||||
return plan{}, fmt.Errorf("input: %w", err)
|
||||
}
|
||||
target, ok := h.targets[in.Host]
|
||||
if !ok {
|
||||
return plan{}, fmt.Errorf("host %q isn't configured", in.Host)
|
||||
}
|
||||
switch action {
|
||||
case actionDeleteFiles:
|
||||
return planDelete(target, in)
|
||||
case actionEnableTimer, actionDisableTimer:
|
||||
return planTimer(target, action, in)
|
||||
case actionSetConfig:
|
||||
return planConfig(target, in)
|
||||
}
|
||||
return plan{}, fmt.Errorf("no action named %q", action)
|
||||
}
|
||||
|
||||
func under(p string, dirs []string) bool {
|
||||
return slices.ContainsFunc(dirs, func(d string) bool { return p == d || strings.HasPrefix(p, d+"/") })
|
||||
}
|
||||
|
||||
func planDelete(t Target, in actionInput) (plan, error) {
|
||||
dir, err := checkPath(in.Directory, t.Paths)
|
||||
if err != nil {
|
||||
return plan{}, err
|
||||
}
|
||||
if dir == "/" {
|
||||
return plan{}, errors.New("refusing to delete from the root directory")
|
||||
}
|
||||
if err := checkPattern(in.Pattern); err != nil {
|
||||
return plan{}, err
|
||||
}
|
||||
if in.OlderThanHours < 1 || in.OlderThanHours > maxAgeHours {
|
||||
return plan{}, fmt.Errorf("older_than_hours %d must be between 1 and %d", in.OlderThanHours, maxAgeHours)
|
||||
}
|
||||
disposable := under(dir, t.Disposable)
|
||||
// A directory claimed disposable must resolve into a disposable directory
|
||||
// on the host, so a symlink can't carry the claim to somewhere that isn't.
|
||||
roots := t.Paths
|
||||
reversibility := connectorv1.Reversibility_REVERSIBILITY_IRREVERSIBLE
|
||||
summary := fmt.Sprintf("Deletes files matching %s under %s not modified for %d hours; irreversible.", in.Pattern, dir, in.OlderThanHours)
|
||||
if disposable {
|
||||
roots = t.Disposable
|
||||
reversibility = connectorv1.Reversibility_REVERSIBILITY_RECOVERABLE
|
||||
summary = fmt.Sprintf("Deletes files matching %s under disposable directory %s not modified for %d hours; they are regenerated.", in.Pattern, dir, in.OlderThanHours)
|
||||
}
|
||||
minutes := strconv.Itoa(in.OlderThanHours * 60)
|
||||
return plan{
|
||||
target: t,
|
||||
disposable: disposable,
|
||||
effect: &connectorv1.Effect{Reversibility: reversibility, Summary: summary},
|
||||
command: func(string) string {
|
||||
if t.Helpers {
|
||||
return helperDir + "delete-old-files " + quote(dir) + " " + minutes + " " + quote(in.Pattern)
|
||||
}
|
||||
return deleteCommand(dir, in.Pattern, minutes, roots)
|
||||
},
|
||||
report: func(out []byte) (any, error) {
|
||||
files, bytes := sumSizes(out)
|
||||
return map[string]any{"host": t.Name, "directory": dir, "pattern": in.Pattern, "files_deleted": files, "bytes_deleted": bytes}, nil
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// checkPattern accepts a file name glob: one path component, printable.
|
||||
func checkPattern(p string) error {
|
||||
switch {
|
||||
case p == "":
|
||||
return errors.New("pattern is empty")
|
||||
case len(p) > 255 || !utf8.ValidString(p):
|
||||
return errors.New("pattern isn't a file name")
|
||||
case strings.ContainsAny(p, "/\\") || strings.ContainsFunc(p, func(r rune) bool { return r < 0x20 || r == 0x7f }):
|
||||
return errors.New("pattern must be a file name glob with no path separators, backslashes or control characters")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// confine is a shell snippet that resolves dir and exits 3 unless it lies in
|
||||
// one of roots once symlinks are followed. It leaves the resolved directory
|
||||
// in $d.
|
||||
func confine(dir string, roots []string) string {
|
||||
var b strings.Builder
|
||||
b.WriteString("d=$(realpath -e -- " + quote(dir) + ") || exit 3; ok=; for r in")
|
||||
for _, r := range roots {
|
||||
b.WriteString(" " + quote(r))
|
||||
}
|
||||
b.WriteString(`; do rr=$(realpath -e -- "$r") || continue; case "$d" in "$rr"|"$rr"/*) ok=1;; esac; done; [ -n "$ok" ] || exit 3; `)
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// deleteCommand removes regular files on dir's filesystem, printing each
|
||||
// one's size before deleting it so the report counts what was removed.
|
||||
func deleteCommand(dir, pattern, minutes string, roots []string) string {
|
||||
return confine(dir, roots) + `LC_ALL=C find -P "$d" -xdev -type f -name ` + quote(pattern) + " -mmin +" + minutes + ` -printf '%s\n' -delete`
|
||||
}
|
||||
|
||||
func sumSizes(out []byte) (files int, bytes int64) {
|
||||
for line := range strings.Lines(string(out)) {
|
||||
n, err := strconv.ParseInt(strings.TrimSpace(line), 10, 64)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
files++
|
||||
bytes += n
|
||||
}
|
||||
return files, bytes
|
||||
}
|
||||
|
||||
func planTimer(t Target, action string, in actionInput) (plan, error) {
|
||||
if !slices.Contains(t.Timers, in.Timer) {
|
||||
return plan{}, fmt.Errorf("timer %q isn't one this host allows", in.Timer)
|
||||
}
|
||||
verb, state := "enable", "enabled"
|
||||
if action == actionDisableTimer {
|
||||
verb, state = "disable", "disabled"
|
||||
}
|
||||
return plan{
|
||||
target: t,
|
||||
effect: &connectorv1.Effect{Reversibility: connectorv1.Reversibility_REVERSIBILITY_UNDONE_AUTOMATICALLY, Summary: fmt.Sprintf("%ss %s.", strings.ToUpper(verb[:1])+verb[1:], in.Timer)},
|
||||
command: func(string) string {
|
||||
return helperDir + "timer-control " + verb + " " + quote(in.Timer)
|
||||
},
|
||||
report: func([]byte) (any, error) {
|
||||
return map[string]any{"host": t.Name, "timer": in.Timer, "state": state}, nil
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func planConfig(t Target, in actionInput) (plan, error) {
|
||||
file := path.Clean(in.File)
|
||||
if !slices.Contains(t.ConfigFiles, file) {
|
||||
return plan{}, fmt.Errorf("file %q isn't one this host allows", in.File)
|
||||
}
|
||||
if !configKey.MatchString(in.Key) {
|
||||
return plan{}, fmt.Errorf("key %q isn't a plain name", in.Key)
|
||||
}
|
||||
if len(in.Value) > maxValueLen || !utf8.ValidString(in.Value) || strings.ContainsFunc(in.Value, func(r rune) bool { return r < 0x20 || r == 0x7f }) {
|
||||
return plan{}, errors.New("value must be a single printable line")
|
||||
}
|
||||
return plan{
|
||||
target: t,
|
||||
effect: &connectorv1.Effect{Reversibility: connectorv1.Reversibility_REVERSIBILITY_RECOVERABLE, Summary: fmt.Sprintf("Sets %s in %s; the previous file is kept beside it.", in.Key, file)},
|
||||
command: func(key string) string {
|
||||
sum := sha256.Sum256([]byte(key))
|
||||
return setKeyCommand(file, file+".archie-bak-"+hex.EncodeToString(sum[:6]), in.Key, in.Value)
|
||||
},
|
||||
report: func(out []byte) (any, error) {
|
||||
state, backup, _ := strings.Cut(strings.TrimSpace(string(out)), " ")
|
||||
if state != "changed" && state != "unchanged" {
|
||||
return nil, fmt.Errorf("unexpected output %q", out)
|
||||
}
|
||||
res := map[string]any{"host": t.Name, "file": file, "key": in.Key, "changed": state == "changed"}
|
||||
if backup != "" {
|
||||
res["backup"] = backup
|
||||
}
|
||||
return res, nil
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// setKeyCommand rewrites every KEY=VALUE line for key (or appends one) in a
|
||||
// copy of file, keeps the original as backup unless this action already did,
|
||||
// then renames the copy over it. Key and value reach awk through the
|
||||
// environment, so awk never interprets them. Exit 4 means the file isn't a
|
||||
// plain file owned by the account.
|
||||
func setKeyCommand(file, backup, key, value string) string {
|
||||
const awk = `BEGIN{k=ENVIRON["K"];v=ENVIRON["V"]} {s=$0;sub(/^[ \t]+/,"",s);i=index(s,"=");if(i>1){n=substr(s,1,i-1);sub(/[ \t]+$/,"",n);if(n==k){print k "=" v;done=1;next}}print $0} END{if(!done)print k "=" v}`
|
||||
f, b := quote(file), quote(backup)
|
||||
return "f=" + f + "; b=" + b + `; { [ -f "$f" ] && [ ! -L "$f" ] && [ -O "$f" ]; } || exit 4; ` +
|
||||
`t=$(mktemp -- "$f.archie.XXXXXX") || exit 5; trap 'rm -f -- "$t"' EXIT; ` +
|
||||
"K=" + quote(key) + " V=" + quote(value) + " awk " + quote(awk) + ` "$f" > "$t" || exit 5; ` +
|
||||
`if cmp -s -- "$f" "$t"; then echo unchanged; exit 0; fi; ` +
|
||||
`[ -e "$b" ] || cp -p -- "$f" "$b" || exit 5; chmod --reference="$f" -- "$t" && mv -f -- "$t" "$f" && echo changed "$b"`
|
||||
}
|
||||
|
||||
func (h *host) Resolve(_ context.Context, action string, raw jsontext.Value) (*connectorv1.ResolveResponse, error) {
|
||||
p, err := h.plan(action, raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &connectorv1.ResolveResponse{
|
||||
Target: &connectorv1.Target{Kind: "host", Id: p.target.Name, Environment: p.target.Environment, Disposable: p.disposable},
|
||||
Effect: p.effect,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Invoke runs the checked action. The operations are idempotent, so the key
|
||||
// is required but needs no ledger: running one again finds the work done. A
|
||||
// command that started and ended without an exit status (the session dropped)
|
||||
// may have done any part of its work, so it is an unknown outcome; one that
|
||||
// never started, or exited non-zero, is a plain failure.
|
||||
func (h *host) Invoke(ctx context.Context, action string, raw jsontext.Value, key string) (jsontext.Value, bool, error) {
|
||||
p, err := h.plan(action, raw)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if key == "" {
|
||||
return nil, false, errors.New("an idempotency key is required")
|
||||
}
|
||||
r := h.runner(ctx, p.target, p.command(key))
|
||||
if r.started && !r.exited {
|
||||
return nil, true, fmt.Errorf("%s on %s: connection lost mid-operation: %w", action, p.target.Name, r.err)
|
||||
} else if r.exited && r.status != 0 {
|
||||
msg := fmt.Sprintf("%s on %s failed with exit status %d", action, p.target.Name, r.status)
|
||||
if files, bytes := sumSizes(r.out); files > 0 {
|
||||
msg += fmt.Sprintf(" after removing %d files (%d bytes)", files, bytes)
|
||||
}
|
||||
return nil, false, errors.New(msg)
|
||||
} else if !r.started {
|
||||
return nil, false, r.err
|
||||
}
|
||||
result, err := p.report(r.out)
|
||||
if err != nil {
|
||||
return nil, true, fmt.Errorf("%s on %s: %w", action, p.target.Name, err)
|
||||
}
|
||||
encoded, err := json.Marshal(result, json.Deterministic(true))
|
||||
return encoded, false, err
|
||||
}
|
||||
|
||||
var _ connector.Actor = (*host)(nil)
|
||||
@@ -0,0 +1,353 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json/jsontext"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
connectorv1 "github.com/samcharles93/archipelago/sdk/connector/v1"
|
||||
)
|
||||
|
||||
// fakeHost is a host whose runner records commands and never touches a
|
||||
// network.
|
||||
func fakeHost(t *testing.T, res execResult) (*host, *[]string) {
|
||||
t.Helper()
|
||||
target := Target{
|
||||
Name: "web-1", Environment: "production", Helpers: true,
|
||||
Paths: []string{"/srv/app", "/var/tmp"},
|
||||
Disposable: []string{"/var/tmp/cache"},
|
||||
Timers: []string{"backup.timer"},
|
||||
ConfigFiles: []string{"/srv/app/app.conf"},
|
||||
}
|
||||
if err := target.checkActionSettings(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var ran []string
|
||||
h := &host{targets: map[string]Target{"web-1": target}, runner: func(_ context.Context, _ Target, command string) execResult {
|
||||
ran = append(ran, command)
|
||||
return res
|
||||
}}
|
||||
return h, &ran
|
||||
}
|
||||
|
||||
// TestActionInputIsConfined guards the host connector's write boundary: an
|
||||
// action that names a directory outside the host's roots, a pattern that
|
||||
// leaves its directory, a timer or file off the allow-lists, or text that
|
||||
// could break out of its shell argument is refused before any command is
|
||||
// built, so nothing reaches the host.
|
||||
func TestActionInputIsConfined(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
action string
|
||||
input string
|
||||
}{
|
||||
{"directory outside the roots", actionDeleteFiles, `{"host":"web-1","directory":"/etc","pattern":"*.log","older_than_hours":24}`},
|
||||
{"directory climbing out of a root", actionDeleteFiles, `{"host":"web-1","directory":"/srv/app/../../etc","pattern":"*.log","older_than_hours":24}`},
|
||||
{"a root's name as a prefix", actionDeleteFiles, `{"host":"web-1","directory":"/srv/application","pattern":"*.log","older_than_hours":24}`},
|
||||
{"relative directory", actionDeleteFiles, `{"host":"web-1","directory":"srv/app","pattern":"*.log","older_than_hours":24}`},
|
||||
{"newline in directory", actionDeleteFiles, "{\"host\":\"web-1\",\"directory\":\"/srv/app\\n/etc\",\"pattern\":\"*.log\",\"older_than_hours\":24}"},
|
||||
{"pattern with a path separator", actionDeleteFiles, `{"host":"web-1","directory":"/srv/app","pattern":"../*","older_than_hours":24}`},
|
||||
{"pattern with a backslash", actionDeleteFiles, `{"host":"web-1","directory":"/srv/app","pattern":"a\\b","older_than_hours":24}`},
|
||||
{"empty pattern", actionDeleteFiles, `{"host":"web-1","directory":"/srv/app","pattern":"","older_than_hours":24}`},
|
||||
{"newline in pattern", actionDeleteFiles, "{\"host\":\"web-1\",\"directory\":\"/srv/app\",\"pattern\":\"a\\nb\",\"older_than_hours\":24}"},
|
||||
{"no age", actionDeleteFiles, `{"host":"web-1","directory":"/srv/app","pattern":"*.log"}`},
|
||||
{"age under an hour", actionDeleteFiles, `{"host":"web-1","directory":"/srv/app","pattern":"*.log","older_than_hours":0}`},
|
||||
{"unknown host", actionDeleteFiles, `{"host":"web-9","directory":"/srv/app","pattern":"*.log","older_than_hours":24}`},
|
||||
{"unknown member", actionDeleteFiles, `{"host":"web-1","directory":"/srv/app","pattern":"*.log","older_than_hours":24,"extra":"x"}`},
|
||||
{"timer off the allow-list", actionDisableTimer, `{"host":"web-1","timer":"apt-daily.timer"}`},
|
||||
{"timer name with an injection", actionDisableTimer, `{"host":"web-1","timer":"backup.timer; id"}`},
|
||||
{"timer enable off the allow-list", actionEnableTimer, `{"host":"web-1","timer":"other.timer"}`},
|
||||
{"config file off the allow-list", actionSetConfig, `{"host":"web-1","file":"/etc/shadow","key":"A","value":"b"}`},
|
||||
{"config file climbing to another", actionSetConfig, `{"host":"web-1","file":"/srv/app/../../etc/shadow","key":"A","value":"b"}`},
|
||||
{"config key with an equals sign", actionSetConfig, `{"host":"web-1","file":"/srv/app/app.conf","key":"A=b","value":"b"}`},
|
||||
{"config key with a space", actionSetConfig, `{"host":"web-1","file":"/srv/app/app.conf","key":"A b","value":"b"}`},
|
||||
{"config value with a newline", actionSetConfig, "{\"host\":\"web-1\",\"file\":\"/srv/app/app.conf\",\"key\":\"A\",\"value\":\"b\\nC=d\"}"},
|
||||
{"config value too long", actionSetConfig, `{"host":"web-1","file":"/srv/app/app.conf","key":"A","value":"` + strings.Repeat("v", maxValueLen+1) + `"}`},
|
||||
{"unknown action", "run_command", `{"host":"web-1","command":"id"}`},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
h, ran := fakeHost(t, execResult{started: true})
|
||||
if _, err := h.Resolve(t.Context(), tt.action, jsontext.Value(tt.input)); err == nil {
|
||||
t.Fatal("Resolve accepted it")
|
||||
}
|
||||
if _, unknown, err := h.Invoke(t.Context(), tt.action, jsontext.Value(tt.input), "k1"); err == nil || unknown {
|
||||
t.Fatalf("Invoke err=%v unknown=%v, want a plain refusal", err, unknown)
|
||||
}
|
||||
if len(*ran) != 0 {
|
||||
t.Fatalf("a command was built for a refused action: %v", *ran)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestSettingsAreChecked guards the per-host settings the actions trust: a
|
||||
// disposable directory outside the host's roots would let a claim of
|
||||
// recoverability cover anything, and a timer without the sudo helpers has no
|
||||
// way to run.
|
||||
func TestSettingsAreChecked(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
t Target
|
||||
}{
|
||||
{"disposable outside the roots", Target{Name: "web-1", Paths: []string{"/srv/app"}, Disposable: []string{"/etc"}}},
|
||||
{"disposable is the filesystem root", Target{Name: "web-1", Paths: []string{"/"}, Disposable: []string{"/"}}},
|
||||
{"timer that isn't a timer", Target{Name: "web-1", Helpers: true, Timers: []string{"sshd.service"}}},
|
||||
{"timers without helpers", Target{Name: "web-1", Timers: []string{"backup.timer"}}},
|
||||
{"relative config file", Target{Name: "web-1", ConfigFiles: []string{"app.conf"}}},
|
||||
{"host name with a space", Target{Name: "web 1"}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if err := tt.t.checkActionSettings(); err == nil {
|
||||
t.Fatal("accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDisposableDirectoryIsRecoverable guards the reversibility claim: a
|
||||
// directory under a disposable one resolves as disposable and recoverable,
|
||||
// any other under the roots as irreversible, and the shell guard of a
|
||||
// disposable delete only admits the disposable directories, so a symlink
|
||||
// can't carry the claim elsewhere.
|
||||
func TestDisposableDirectoryIsRecoverable(t *testing.T) {
|
||||
h := &host{targets: map[string]Target{"web-1": {Name: "web-1", Environment: "staging", Paths: []string{"/srv/app", "/var/tmp"}, Disposable: []string{"/var/tmp/cache"}}}}
|
||||
tests := []struct {
|
||||
dir string
|
||||
disposable bool
|
||||
reversible connectorv1.Reversibility
|
||||
}{
|
||||
{"/var/tmp/cache", true, connectorv1.Reversibility_REVERSIBILITY_RECOVERABLE},
|
||||
{"/var/tmp/cache/pip", true, connectorv1.Reversibility_REVERSIBILITY_RECOVERABLE},
|
||||
{"/var/tmp/cache2", false, connectorv1.Reversibility_REVERSIBILITY_IRREVERSIBLE},
|
||||
{"/var/tmp", false, connectorv1.Reversibility_REVERSIBILITY_IRREVERSIBLE},
|
||||
{"/srv/app/logs", false, connectorv1.Reversibility_REVERSIBILITY_IRREVERSIBLE},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.dir, func(t *testing.T) {
|
||||
in := jsontext.Value(`{"host":"web-1","directory":"` + tt.dir + `","pattern":"*","older_than_hours":2}`)
|
||||
res, err := h.Resolve(t.Context(), actionDeleteFiles, in)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := res.GetTarget()
|
||||
if got.GetKind() != "host" || got.GetId() != "web-1" || got.GetEnvironment() != "staging" || got.GetDisposable() != tt.disposable {
|
||||
t.Fatalf("target = %v", got)
|
||||
}
|
||||
if res.GetEffect().GetReversibility() != tt.reversible || res.GetEffect().GetReadOnly() {
|
||||
t.Fatalf("effect = %v", res.GetEffect())
|
||||
}
|
||||
p, err := h.plan(actionDeleteFiles, in)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cmd := p.command("k")
|
||||
if strings.Contains(cmd, "/srv/app") && tt.disposable || tt.disposable && !strings.Contains(cmd, "'/var/tmp/cache'") || tt.disposable && strings.Contains(cmd, "'/var/tmp'") {
|
||||
t.Fatalf("disposable delete guarded by the wrong roots: %s", cmd)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestGeneratedCommandsKeepArguments guards command injection: whatever an
|
||||
// accepted pattern, key or value contains, the command stays one well-formed
|
||||
// shell command (syntax-checked, never run) with the text inside quotes.
|
||||
func TestGeneratedCommandsKeepArguments(t *testing.T) {
|
||||
h, _ := fakeHost(t, execResult{started: true})
|
||||
h.targets["web-1"] = func() Target { x := h.targets["web-1"]; x.Helpers = false; x.Timers = nil; return x }()
|
||||
evil := `x'; touch pwned; echo '$(id)` + "`id`"
|
||||
inputs := []struct{ action, in string }{
|
||||
{actionDeleteFiles, `{"host":"web-1","directory":"/srv/app/it's","pattern":` + string(mustJSON(t, evil)) + `,"older_than_hours":3}`},
|
||||
{actionSetConfig, `{"host":"web-1","file":"/srv/app/app.conf","key":"A_b","value":` + string(mustJSON(t, evil)) + `}`},
|
||||
}
|
||||
for _, tt := range inputs {
|
||||
t.Run(tt.action, func(t *testing.T) {
|
||||
p, err := h.plan(tt.action, jsontext.Value(tt.in))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cmd := p.command("k")
|
||||
if out, err := exec.CommandContext(t.Context(), "sh", "-n", "-c", cmd).CombinedOutput(); err != nil {
|
||||
t.Fatalf("not a well-formed command: %v: %s", err, out)
|
||||
}
|
||||
// The payload must appear only as one quoted word.
|
||||
if !strings.Contains(cmd, quote(evil)) || strings.Count(cmd, "touch pwned") != 1 {
|
||||
t.Fatalf("payload isn't one quoted word: %s", cmd)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func mustJSON(t *testing.T, s string) []byte {
|
||||
t.Helper()
|
||||
b, err := jsontext.AppendQuote(nil, s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// TestConfineResolvesSymlinks guards the shell-side half of confinement: a
|
||||
// directory that is lexically inside a root but a symlink out of it is
|
||||
// refused once resolved. Only the read-only guard runs.
|
||||
func TestConfineResolvesSymlinks(t *testing.T) {
|
||||
base := t.TempDir()
|
||||
root, outside := filepath.Join(base, "root"), filepath.Join(base, "outside")
|
||||
for _, d := range []string{filepath.Join(root, "inner"), outside} {
|
||||
if err := os.MkdirAll(d, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := os.Symlink(outside, filepath.Join(root, "escape")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
dir string
|
||||
ok bool
|
||||
}{
|
||||
{"inside", filepath.Join(root, "inner"), true},
|
||||
{"the root itself", root, true},
|
||||
{"symlink out of the root", filepath.Join(root, "escape"), false},
|
||||
{"outside entirely", outside, false},
|
||||
{"missing", filepath.Join(root, "nope"), false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
script := confine(tt.dir, []string{root}) + `printf '%s' "$d"`
|
||||
out, err := exec.CommandContext(t.Context(), "sh", "-c", script).Output()
|
||||
if tt.ok && err != nil {
|
||||
t.Fatalf("refused: %v", err)
|
||||
}
|
||||
if !tt.ok && err == nil {
|
||||
t.Fatalf("admitted %s as %s", tt.dir, out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestInvokeOutcomes guards what an operator is told about a run: a dropped
|
||||
// session is an unknown outcome (the work may be half done), a run that never
|
||||
// started or exited non-zero is a plain failure, and a success reports what
|
||||
// was done.
|
||||
func TestInvokeOutcomes(t *testing.T) {
|
||||
del := jsontext.Value(`{"host":"web-1","directory":"/srv/app/logs","pattern":"*.log","older_than_hours":24}`)
|
||||
tests := []struct {
|
||||
name string
|
||||
res execResult
|
||||
wantUnknown bool
|
||||
wantErr bool
|
||||
wantOut string
|
||||
}{
|
||||
{"deleted two files", execResult{started: true, exited: true, out: []byte("100\n250\n")}, false, false, `"bytes_deleted":350,"directory":"/srv/app/logs","files_deleted":2`},
|
||||
{"nothing to delete", execResult{started: true, exited: true}, false, false, `"files_deleted":0`},
|
||||
{"session dropped", execResult{started: true, out: []byte("100\n"), err: errors.New("wait: remote command exited without exit status or exit signal")}, true, true, ""},
|
||||
{"exit status", execResult{started: true, exited: true, status: 1, out: []byte("100\n"), err: errors.New("exit")}, false, true, ""},
|
||||
{"never started", execResult{err: errors.New("reach web-1: refused")}, false, true, ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
h, _ := fakeHost(t, tt.res)
|
||||
out, unknown, err := h.Invoke(t.Context(), actionDeleteFiles, del, "k1")
|
||||
if (err != nil) != tt.wantErr || unknown != tt.wantUnknown {
|
||||
t.Fatalf("err=%v unknown=%v", err, unknown)
|
||||
}
|
||||
if tt.wantOut != "" && !strings.Contains(string(out), tt.wantOut) {
|
||||
t.Fatalf("output %s lacks %s", out, tt.wantOut)
|
||||
}
|
||||
})
|
||||
}
|
||||
h, _ := fakeHost(t, execResult{started: true, exited: true})
|
||||
if _, _, err := h.Invoke(t.Context(), actionDeleteFiles, del, ""); err == nil {
|
||||
t.Fatal("ran without an idempotency key")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeleteRefusesFilesystemRoot guards a host whose roots include "/": a
|
||||
// delete there may reach any directory under it but never "/" itself.
|
||||
func TestDeleteRefusesFilesystemRoot(t *testing.T) {
|
||||
h := &host{targets: map[string]Target{"web-1": {Name: "web-1", Paths: []string{"/"}}}}
|
||||
for _, dir := range []string{"/", "//", "/srv/.."} {
|
||||
in := jsontext.Value(`{"host":"web-1","directory":"` + dir + `","pattern":"*","older_than_hours":2}`)
|
||||
if _, err := h.Resolve(t.Context(), actionDeleteFiles, in); err == nil {
|
||||
t.Fatalf("accepted %q", dir)
|
||||
}
|
||||
}
|
||||
in := jsontext.Value(`{"host":"web-1","directory":"/srv","pattern":"*","older_than_hours":2}`)
|
||||
if _, err := h.Resolve(t.Context(), actionDeleteFiles, in); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCommandsDoWhatTheyReport runs the generated shell on files in a
|
||||
// temporary directory: delete_files removes only old regular files matching
|
||||
// the glob and reports their sizes, and set_config_key rewrites one key
|
||||
// literally (backslashes and ampersands included), keeps a backup, and is a
|
||||
// no-op the second time.
|
||||
func TestCommandsDoWhatTheyReport(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
write := func(name, body string, age time.Duration) string {
|
||||
t.Helper()
|
||||
p := filepath.Join(dir, name)
|
||||
if err := os.WriteFile(p, []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
when := time.Now().Add(-age)
|
||||
if err := os.Chtimes(p, when, when); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
exists := func(p string) bool { _, err := os.Lstat(p); return err == nil }
|
||||
run := func(command string) string {
|
||||
t.Helper()
|
||||
out, err := exec.CommandContext(t.Context(), "sh", "-c", command).Output()
|
||||
if err != nil {
|
||||
t.Fatalf("%v: %s", err, command)
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
|
||||
oldLog := write("a.log", "12345", 48*time.Hour)
|
||||
newLog := write("b.log", "x", time.Minute)
|
||||
oldTxt := write("c.txt", "x", 48*time.Hour)
|
||||
link := filepath.Join(dir, "d.log")
|
||||
if err := os.Symlink(oldTxt, link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
files, bytes := sumSizes([]byte(run(deleteCommand(dir, "*.log", "120", []string{dir}))))
|
||||
if files != 1 || bytes != 5 || exists(oldLog) || !exists(newLog) || !exists(oldTxt) || !exists(link) {
|
||||
t.Fatalf("deleted %d files, %d bytes; old log gone=%v, new log kept=%v, txt kept=%v, link kept=%v",
|
||||
files, bytes, !exists(oldLog), exists(newLog), exists(oldTxt), exists(link))
|
||||
}
|
||||
|
||||
conf := write("app.conf", "# keep\nA = 1\nB=2\n", time.Minute)
|
||||
set := func(key, value string) string {
|
||||
return strings.TrimSpace(run(setKeyCommand(conf, conf+".bak-"+key, key, value)))
|
||||
}
|
||||
value := `a\n&b $x`
|
||||
if got := set("A", value); got != "changed "+conf+".bak-A" {
|
||||
t.Fatalf("first set printed %q", got)
|
||||
}
|
||||
body, _ := os.ReadFile(conf)
|
||||
if want := "# keep\nA=" + value + "\nB=2\n"; string(body) != want {
|
||||
t.Fatalf("config = %q, want %q", body, want)
|
||||
}
|
||||
if backup, _ := os.ReadFile(conf + ".bak-A"); string(backup) != "# keep\nA = 1\nB=2\n" {
|
||||
t.Fatalf("backup = %q", backup)
|
||||
}
|
||||
if got := set("A", value); got != "unchanged" {
|
||||
t.Fatalf("second set printed %q", got)
|
||||
}
|
||||
set("C", "3")
|
||||
if body, _ = os.ReadFile(conf); !strings.HasSuffix(string(body), "B=2\nC=3\n") {
|
||||
t.Fatalf("appended config = %q", body)
|
||||
}
|
||||
}
|
||||
+19
-1
@@ -30,6 +30,18 @@ type Target struct {
|
||||
// may read as root, so a path outside them is refused: an instruction
|
||||
// injected into an event can't steer the agent into the rest of the host.
|
||||
Paths []string `json:"paths"`
|
||||
// Environment is what the host is for (production, staging), declared on
|
||||
// every action's target so policy can tell them apart.
|
||||
Environment string `json:"environment"`
|
||||
// Disposable are the host's temp and cache directories, inside Paths.
|
||||
// Deleting from one is recoverable by regeneration; deleting from anywhere
|
||||
// else under Paths is irreversible.
|
||||
Disposable []string `json:"disposable"`
|
||||
// Timers are the systemd timers the connector may enable and disable.
|
||||
Timers []string `json:"timers"`
|
||||
// ConfigFiles are the files whose keys the connector may set, each owned
|
||||
// by the connector's account.
|
||||
ConfigFiles []string `json:"config_files"`
|
||||
|
||||
key ssh.PublicKey
|
||||
}
|
||||
@@ -38,6 +50,8 @@ type host struct {
|
||||
targets map[string]Target
|
||||
username string
|
||||
signer ssh.Signer
|
||||
// runner executes a command on a host; tests replace it.
|
||||
runner func(ctx context.Context, target Target, command string) execResult
|
||||
}
|
||||
|
||||
func newHost(cfg connector.Config) (*host, error) {
|
||||
@@ -58,12 +72,16 @@ func newHost(cfg connector.Config) (*host, error) {
|
||||
}
|
||||
t.Paths[i] = path.Clean(root)
|
||||
}
|
||||
if err := t.checkActionSettings(); err != nil {
|
||||
return nil, fmt.Errorf("host %q: %w", t.Name, err)
|
||||
}
|
||||
h.targets[t.Name] = t
|
||||
}
|
||||
pem, pass := cfg.Secrets["ssh.private_key"], cfg.Secrets["ssh.private_key_passphrase"]
|
||||
if h.username == "" || pem == "" {
|
||||
return nil, errNoCredential
|
||||
}
|
||||
h.runner = h.execute
|
||||
var err error
|
||||
if pass != "" {
|
||||
h.signer, err = ssh.ParsePrivateKeyWithPassphrase([]byte(pem), []byte(pass))
|
||||
@@ -77,7 +95,7 @@ func newHost(cfg connector.Config) (*host, error) {
|
||||
}
|
||||
|
||||
func (h *host) Describe() connector.Description {
|
||||
return connector.Description{Lookups: []*connectorv1.LookupType{
|
||||
return connector.Description{Actions: h.actionTypes(), Lookups: []*connectorv1.LookupType{
|
||||
{
|
||||
Name: "filesystem_usage",
|
||||
Description: "Size, used and available bytes and inode use of the filesystem holding a path on a host.",
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
// Command host is the host connector: read-only lookups on the hosts it is
|
||||
// configured with, run over SSH with a pinned host key and the credential
|
||||
// Archie hands it. It runs no free-form command; a judged command action
|
||||
// comes with judgement.
|
||||
// Command host is the host connector: read-only lookups and a few typed
|
||||
// actions on the hosts it is configured with, run over SSH with a pinned host
|
||||
// key and the credential Archie hands it. It runs no free-form command.
|
||||
package main
|
||||
|
||||
import "github.com/samcharles93/archipelago/sdk/connector"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: dev.archie.package.v1
|
||||
displayName: Host
|
||||
description: Read-only lookups on configured hosts over SSH, with pinned host keys and a machine credential in the ssh slot.
|
||||
description: Read-only lookups on configured hosts over SSH, plus typed actions (delete old files, enable or disable an allowed timer, set one config key), each judged on its declared effect. Pinned host keys and a machine credential in the ssh slot.
|
||||
version: 0.1.0
|
||||
contributes:
|
||||
extensions:
|
||||
|
||||
+32
-10
@@ -26,36 +26,58 @@ const (
|
||||
// prints something and then exits non-zero (du meeting a directory it can't
|
||||
// read) still returns what it printed.
|
||||
func (h *host) run(ctx context.Context, target Target, command string) ([]byte, error) {
|
||||
r := h.execute(ctx, target, command)
|
||||
if len(r.out) > 0 {
|
||||
return r.out, nil
|
||||
}
|
||||
return nil, r.err
|
||||
}
|
||||
|
||||
// execResult is what a command did. started is false when it never reached
|
||||
// the remote shell (no connection, handshake or session), so nothing ran. A
|
||||
// started command that did not exit (the session dropped, the deadline
|
||||
// passed) may have done part or all of its work.
|
||||
type execResult struct {
|
||||
out []byte
|
||||
started bool
|
||||
exited bool
|
||||
status int
|
||||
err error
|
||||
}
|
||||
|
||||
func (h *host) execute(ctx context.Context, target Target, command string) execResult {
|
||||
ctx, cancel := context.WithTimeout(ctx, commandTimeout)
|
||||
defer cancel()
|
||||
conn, err := dial(ctx, target.Address)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reach %s: %w", target.Name, err)
|
||||
return execResult{err: fmt.Errorf("reach %s: %w", target.Name, err)}
|
||||
}
|
||||
stop := context.AfterFunc(ctx, func() { _ = conn.Close() })
|
||||
defer stop()
|
||||
cc, chans, reqs, err := ssh.NewClientConn(conn, target.Address, h.clientConfig(target))
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, fmt.Errorf("ssh to %s: %w", target.Name, err)
|
||||
return execResult{err: fmt.Errorf("ssh to %s: %w", target.Name, err)}
|
||||
}
|
||||
client := ssh.NewClient(cc, chans, reqs)
|
||||
defer func() { _ = client.Close() }()
|
||||
session, err := client.NewSession()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ssh session on %s: %w", target.Name, err)
|
||||
return execResult{err: fmt.Errorf("ssh session on %s: %w", target.Name, err)}
|
||||
}
|
||||
defer func() { _ = session.Close() }()
|
||||
var out limited
|
||||
session.Stdout = &out
|
||||
runErr := session.Run(command)
|
||||
if out.Len() > 0 {
|
||||
return out.Bytes(), nil
|
||||
err = session.Run(command)
|
||||
res := execResult{out: out.Bytes(), started: true, exited: err == nil}
|
||||
if err != nil {
|
||||
res.err = fmt.Errorf("on %s: %w", target.Name, err)
|
||||
var exit *ssh.ExitError
|
||||
if errors.As(err, &exit) {
|
||||
res.exited, res.status = true, exit.ExitStatus()
|
||||
}
|
||||
}
|
||||
if runErr != nil {
|
||||
return nil, fmt.Errorf("on %s: %w", target.Name, runErr)
|
||||
}
|
||||
return nil, nil
|
||||
return res
|
||||
}
|
||||
|
||||
// clientConfig pins the target's host key. It asks only for that key's
|
||||
|
||||
@@ -13,3 +13,16 @@
|
||||
- The roots lookups may look under, as `paths` in the `hosts` setting (for
|
||||
example `["/tmp", "/var/tmp"]`). Lookups run no guards and may read as root,
|
||||
so any path outside them is refused.
|
||||
- For actions, the helpers read two root-owned allow-lists, created empty by
|
||||
`install.sh`: `/etc/archie/delete-roots` (one directory per line; `delete_files`
|
||||
as root only reaches directories that resolve into one) and `/etc/archie/timers`
|
||||
(one unit name per line; the only timers `enable_timer` and `disable_timer`
|
||||
can touch). They repeat the connector's own settings, so a compromised
|
||||
connector can't widen them. Timers need `"helpers": true`.
|
||||
- Without helpers, `delete_files` runs as the account, which can delete only
|
||||
what it owns or has group access to. `set_config_key` always runs as the
|
||||
account: the file must be a plain file it owns, and the directory writable.
|
||||
- Per-host settings in `hosts`: `environment` (declared on every action's
|
||||
target), `disposable` (temp and cache directories inside `paths`; deleting
|
||||
there is recoverable), `timers` (unit names) and `config_files` (absolute
|
||||
paths).
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#!/bin/sh
|
||||
# delete-old-files DIR MINUTES PATTERN: deletes regular files under DIR on its
|
||||
# filesystem whose name matches PATTERN and that were not modified for MINUTES,
|
||||
# printing each one's size first. DIR must resolve, symlinks followed, into a
|
||||
# directory listed in /etc/archie/delete-roots. Run by the host connector
|
||||
# through sudo, so it trusts none of its arguments.
|
||||
set -eu
|
||||
[ "$#" -eq 3 ] || { echo "usage: delete-old-files DIR MINUTES PATTERN" >&2; exit 2; }
|
||||
case "$1" in /*) ;; *) echo "dir must be absolute" >&2; exit 2 ;; esac
|
||||
case "$2" in '' | *[!0-9]*) echo "minutes must be a number" >&2; exit 2 ;; esac
|
||||
[ "$2" -ge 60 ] || { echo "minutes must be at least 60" >&2; exit 2; }
|
||||
case "$3" in '' | */* | *\\*) echo "pattern must be a file name glob" >&2; exit 2 ;; esac
|
||||
dir=$(realpath -e -- "$1") || exit 3
|
||||
[ "$dir" != / ] || exit 3
|
||||
ok=
|
||||
while IFS= read -r root; do
|
||||
case "$root" in /*) ;; *) continue ;; esac
|
||||
root=$(realpath -e -- "$root") || continue
|
||||
[ "$root" != / ] || continue
|
||||
case "$dir" in "$root" | "$root"/*) ok=1 ;; esac
|
||||
done < /etc/archie/delete-roots
|
||||
[ -n "$ok" ] || { echo "dir is outside /etc/archie/delete-roots" >&2; exit 3; }
|
||||
LC_ALL=C exec find -P "$dir" -xdev -type f -name "$3" -mmin +"$2" -printf '%s\n' -delete
|
||||
@@ -1,9 +1,11 @@
|
||||
#!/bin/sh
|
||||
# Installs the host connector's read-only helpers and their sudo rule. Run as
|
||||
# Installs the host connector's helpers and their sudo rule. Run as
|
||||
# root on each host the connector reaches.
|
||||
set -eu
|
||||
here=$(dirname "$0")
|
||||
install -d -m 755 /usr/local/libexec/archie
|
||||
install -m 755 -o root -g root "$here/directory-sizes" "$here/old-files" /usr/local/libexec/archie/
|
||||
install -m 755 -o root -g root "$here/directory-sizes" "$here/old-files" "$here/delete-old-files" "$here/timer-control" /usr/local/libexec/archie/
|
||||
install -d -m 755 /etc/archie
|
||||
for f in delete-roots timers; do [ -e "/etc/archie/$f" ] || install -m 644 -o root -g root /dev/null "/etc/archie/$f"; done
|
||||
install -m 440 -o root -g root "$here/sudoers" /etc/sudoers.d/archie-host
|
||||
visudo -cf /etc/sudoers.d/archie-host
|
||||
@@ -1,2 +1,2 @@
|
||||
# The host connector's read-only helpers, and nothing else, as root.
|
||||
archie ALL=(root) NOPASSWD: /usr/local/libexec/archie/directory-sizes, /usr/local/libexec/archie/old-files
|
||||
# The host connector's helpers, and nothing else, as root.
|
||||
archie ALL=(root) NOPASSWD: /usr/local/libexec/archie/directory-sizes, /usr/local/libexec/archie/old-files, /usr/local/libexec/archie/delete-old-files, /usr/local/libexec/archie/timer-control
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
# timer-control enable|disable NAME: enables and starts, or disables and stops,
|
||||
# one systemd timer, if /etc/archie/timers lists it. Run by the host connector
|
||||
# through sudo, so it trusts none of its arguments.
|
||||
set -eu
|
||||
[ "$#" -eq 2 ] || { echo "usage: timer-control enable|disable NAME" >&2; exit 2; }
|
||||
case "$1" in enable | disable) ;; *) echo "verb must be enable or disable" >&2; exit 2 ;; esac
|
||||
case "$2" in *.timer) ;; *) echo "name must end in .timer" >&2; exit 2 ;; esac
|
||||
grep -qxF -- "$2" /etc/archie/timers || { echo "$2 is not listed in /etc/archie/timers" >&2; exit 3; }
|
||||
exec systemctl "$1" --now -- "$2"
|
||||
Reference in new issue
Block a user