Files
sam 125457a391
publish / publish (push) Successful in 1m21s
feat(connector): declare privileged effects on every lookup and action (#2071)
Regenerate the connector SDK from the host contract, which adds the
effects_declared, privilege_change and secret_access fields. Every lookup and
action in this repository now states them, and a Semaphore template states
them in its effect settings or is unavailable in chat.
2026-11-21 21:29:49 +11:00

366 lines
15 KiB
Go

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{EffectsDeclared: true, 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{EffectsDeclared: true, 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{EffectsDeclared: true, 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{EffectsDeclared: true, 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)