Files
NarratorandClaude Opus 5.5 87e848dede Ansible checks the server's host key, and secrets stay off command lines
- Every playbook ran with ANSIBLE_HOST_KEY_CHECKING=False, so anyone in
  the middle could pose as the server and be handed the sudo password
  and every secret in vars.yml. Ansible's ssh now uses
  StrictHostKeyChecking=accept-new, like interzone's own ssh calls: a
  new server is trusted on first sight, a changed key stops the run.
- The ssh connection-sharing folder in /tmp is only used when it's this
  user's own and closed to others; someone else could have made it
  first and planted a socket.
- Registering a user passed the password in --extra-vars, readable with
  ps. It goes through a 0600 vars file, like the other admin actions.
- The restore source and backup destination are passed as JSON, so a
  path with a space no longer breaks them.
- The update preview's git fetch puts "--" before the URL, as every
  other git call does.
- A domain's backup list no longer includes dumps of another domain
  that starts with the same name and a dash (a.org vs a.org-b.net).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 19:28:07 +01:00

169 lines
4.4 KiB
Go

package deploy
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"interzone/internal/config"
)
// TaskResult is one host's result for one task, as Ansible's json callback
// reports it.
type TaskResult map[string]json.RawMessage
func (t TaskResult) String(key string) string {
var s string
_ = json.Unmarshal(t[key], &s)
return s
}
// runPlayJSON runs a play against the server with Ansible's json output
// and returns each named task's result. vars are passed through a
// temporary owner-only file so secrets never show up in ps.
// writeVarsFile writes extra vars that hold secrets to a 0600 file in the
// inventory, for "-e @file"; the caller removes it.
func writeVarsFile(dir string, vars any) (string, error) {
f, err := os.CreateTemp(filepath.Join(dir, "inventory"), ".interzone-vars-*.json")
if err != nil {
return "", err
}
err = json.NewEncoder(f).Encode(vars)
if cerr := f.Close(); err == nil {
err = cerr
}
if err != nil {
os.Remove(f.Name())
return "", err
}
return f.Name(), nil
}
// jsonVars is extra vars as JSON, which Ansible doesn't split on spaces
// the way it does key=value.
func jsonVars(vars map[string]string) string {
b, _ := json.Marshal(vars)
return string(b)
}
func runPlayJSON(ctx context.Context, c *config.Config, name, play string, vars map[string]any, args ...string) (map[string]TaskResult, error) {
bin, err := lookPath("ansible-playbook")
if err != nil {
return nil, fmt.Errorf("run a full install first: Ansible isn't installed yet")
}
if _, err := os.Stat(filepath.Join(c.PlaybookDir, "inventory", "hosts")); err != nil {
return nil, fmt.Errorf("run a full install first: there's no inventory in %s yet", c.PlaybookDir)
}
dir := c.PlaybookDir
playDir := filepath.Join(dir, "inventory")
if strings.HasPrefix(play, "#root\n") {
// Plays that load the playbook's roles must sit next to setup.yml.
playDir = dir
}
// A name of its own, as two plays of the same kind can run at once.
f, err := os.CreateTemp(playDir, "interzone-"+name+"-*.yml")
if err != nil {
return nil, err
}
playFile := f.Name()
defer os.Remove(playFile)
_, err = f.WriteString(play)
if cerr := f.Close(); err == nil {
err = cerr
}
if err != nil {
return nil, err
}
cmdArgs := []string{"-i", "inventory/hosts", playFile}
if len(vars) > 0 {
f, err := writeVarsFile(dir, vars)
if err != nil {
return nil, err
}
defer os.Remove(f)
cmdArgs = append(cmdArgs, "-e", "@"+f)
}
cmd := exec.CommandContext(ctx, bin, append(cmdArgs, args...)...)
cmd.Dir = dir
cmd.Env = append(Env(c), "ANSIBLE_STDOUT_CALLBACK=json", "ANSIBLE_CALLBACK_RESULT_FORMAT=json")
var stderr bytes.Buffer
cmd.Stderr = &stderr
out, runErr := cmd.Output()
var doc struct {
Plays []struct {
Tasks []struct {
Task struct {
Name string `json:"name"`
} `json:"task"`
Hosts map[string]TaskResult `json:"hosts"`
} `json:"tasks"`
} `json:"plays"`
}
if i := bytes.IndexByte(out, '{'); i >= 0 {
out = out[i:]
}
if err := json.Unmarshal(out, &doc); err != nil {
if runErr != nil {
return nil, fmt.Errorf("%s", lastLine(stderr.String(), runErr))
}
return nil, fmt.Errorf("couldn't read Ansible's output: %w", err)
}
res := map[string]TaskResult{}
for _, p := range doc.Plays {
for _, t := range p.Tasks {
for _, h := range t.Hosts {
if t.Task.Name != "" {
res[t.Task.Name] = h
}
if failed(h) {
return res, fmt.Errorf("%s: %s", t.Task.Name, taskMessage(h))
}
}
}
}
if runErr != nil {
return res, fmt.Errorf("%s", lastLine(stderr.String(), runErr))
}
return res, nil
}
func failed(h TaskResult) bool {
var b bool
if json.Unmarshal(h["failed"], &b) == nil && b {
return true
}
return json.Unmarshal(h["unreachable"], &b) == nil && b
}
// taskMessage is the most useful text of a failed task.
func taskMessage(h TaskResult) string {
for _, k := range []string{"msg", "stderr", "stdout"} {
if s := strings.TrimSpace(h.String(k)); s != "" {
return lastLine(s, nil)
}
}
return "failed"
}
func lastLine(s string, fallback error) string {
s = strings.TrimSpace(s)
// Ansible's own errors end with where in the file, e.g. "^ column 7".
if _, e, ok := strings.Cut(s, "[ERROR]: "); ok {
s, _, _ = strings.Cut(e, "\n")
return s
}
if i := strings.LastIndex(s, "\n"); i >= 0 {
s = s[i+1:]
}
if s == "" && fallback != nil {
return fallback.Error()
}
return s
}