Files
NarratorandClaude Opus 5.5 5e8be12ca8 Keep the answers and secrets safe on disk, and vars.yml parseable
Saving:
- config.json, presets.json, the imported copies and the inventory's
  vars.yml and hosts are written by config.WriteSecret: to a temp file
  that's synced and renamed into place, so a crash or full disk leaves
  the old file instead of half of the new one, and always 0600. Writing
  in place kept the mode of a file that was already 0644, as a hand-made
  inventory or a restored backup often is. Links are followed, so a
  linked inventory stays linked.
- A config.json that isn't valid JSON is moved aside to
  config.json.broken-<time> before the wizard starts afresh. Before,
  the fresh answers' new secrets overwrote it on the next save, and a
  redeploy locked Synapse out of Postgres.
- Importing over a server whose answers can't be read now stops instead
  of replacing them without a .before-import copy.
- The imported vars file is kept as imported/<name>/vars.yml, which is
  where ImportedVars reads it, whatever it was called.

The base domain:
- It has to be a hostname. It becomes directory names in the
  inventory, so 'https://example.org' made nested directories, and an
  imported matrix_domain of '../../tmp/x' wrote outside the playbook.
  The Server step drops a pasted https:// and trailing slash; Missing()
  and the importer refuse anything else.

vars.yml:
- A one-line Fine-tune value that is a block list or mapping ("- a",
  "a: b") is written under the key rather than after it, which wasn't
  YAML.
- A pasted "|" block in a YAML field is indented like an override's.

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

446 lines
14 KiB
Go

package config
import (
"encoding/json"
"fmt"
"maps"
"os"
"regexp"
"slices"
"sort"
"strconv"
"strings"
"time"
"gopkg.in/yaml.v3"
"interzone/internal/catalog"
)
// HostName is the inventory name MDAD uses for the server.
func (c *Config) HostName() string { return "matrix." + c.Domain }
type yamlWriter struct {
b strings.Builder
seen map[string]bool
// over replaces the value of any key written, so a variable changed on
// the Tuning screen wins over what interzone would set.
over map[string]string
}
func (w *yamlWriter) section(title string) {
fmt.Fprintf(&w.b, "\n# ── %s %s\n", title, strings.Repeat("─", max(3, 60-len(title))))
}
func (w *yamlWriter) comment(s string) { fmt.Fprintf(&w.b, "# %s\n", s) }
// raw writes an already-formatted scalar. Later writes of the same key are
// dropped so components that share a variable never produce duplicates.
func (w *yamlWriter) raw(key, value string) {
if !w.claim(key) {
return
}
fmt.Fprintf(&w.b, "%s: %s\n", key, value)
}
// claim reports whether key is still to be written, writing the Fine-tune
// value instead when there is one.
func (w *yamlWriter) claim(key string) bool {
if v, ok := w.over[key]; ok {
w.override(key, v)
return false
}
if w.seen[key] {
return false
}
w.seen[key] = true
return true
}
// override writes a raw YAML value from the Tuning screen.
func (w *yamlWriter) override(key, value string) {
if w.seen[key] {
return
}
w.seen[key] = true
value = strings.TrimRight(value, "\n ")
if !strings.Contains(value, "\n") && !blockCollection(value) {
fmt.Fprintf(&w.b, "%s: %s # changed in interzone's Fine-tune screen\n", key, value)
return
}
if strings.HasPrefix(value, "|") || strings.HasPrefix(value, ">") {
head, rest, _ := strings.Cut(value, "\n")
fmt.Fprintf(&w.b, "%s: %s\n%s\n", key, head, indentKeep(rest))
return
}
fmt.Fprintf(&w.b, "%s:\n%s\n", key, indent(value, " "))
}
// blockCollection reports whether a one-line value is a block list or
// mapping, like "- a" or "a: b", which can't follow the key on its line.
func blockCollection(value string) bool {
var n yaml.Node
if yaml.Unmarshal([]byte(value), &n) != nil || len(n.Content) == 0 {
return false
}
v := n.Content[0]
return (v.Kind == yaml.SequenceNode || v.Kind == yaml.MappingNode) && v.Style&yaml.FlowStyle == 0
}
// indentKeep indents a block scalar's body unless it already is.
func indentKeep(s string) string {
for _, l := range strings.Split(s, "\n") {
if l != "" && !strings.HasPrefix(l, " ") {
return indent(s, " ")
}
}
return s
}
func (w *yamlWriter) str(key, value string) { w.raw(key, Quote(value)) }
func (w *yamlWriter) block(key, body string) {
if !w.claim(key) {
return
}
body = strings.TrimRight(body, "\n ")
if strings.HasPrefix(body, "|") || strings.HasPrefix(body, ">") {
head, rest, _ := strings.Cut(body, "\n")
fmt.Fprintf(&w.b, "%s: %s\n%s\n", key, head, indentKeep(rest))
return
}
fmt.Fprintf(&w.b, "%s:\n%s\n", key, indent(body, " "))
}
func indent(s, pad string) string {
lines := strings.Split(s, "\n")
for i, l := range lines {
if l != "" {
lines[i] = pad + l
}
}
return strings.Join(lines, "\n")
}
// iniQuote quotes a value for an INI inventory line, which Ansible splits
// like a shell does. shortcut: a value that reads as a number, list or
// {{ template }} is still converted by Ansible; a YAML host_vars file would
// keep it as typed, if a password like that ever matters.
func iniQuote(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" }
// Quote renders s as a single-quoted YAML scalar.
func Quote(s string) string { return "'" + strings.ReplaceAll(s, "'", "''") + "'" }
var numeric = regexp.MustCompile(`^-?[0-9]+(\.[0-9]+)?$`)
func (w *yamlWriter) field(f catalog.Field, v string) {
if v == "" && !f.Required {
return
}
switch f.Kind {
case catalog.Bool:
if v != "true" {
v = "false"
}
w.raw(f.Var, v)
case catalog.Number:
if numeric.MatchString(v) {
w.raw(f.Var, v)
} else {
w.str(f.Var, v)
}
case catalog.List:
var items []string
for _, it := range strings.Split(v, ",") {
if it = strings.TrimSpace(it); it != "" {
items = append(items, "- "+Quote(it))
}
}
if len(items) == 0 {
w.raw(f.Var, "[]")
} else {
w.block(f.Var, strings.Join(items, "\n"))
}
case catalog.YAML:
w.block(f.Var, v)
default:
w.str(f.Var, v)
}
}
// MigrationVersion reads the value MDAD expects from the playbook's own example config.
func MigrationVersion(playbookDir string) string {
b, err := os.ReadFile(playbookDir + "/examples/vars.yml")
if err != nil {
return ""
}
m := regexp.MustCompile(`(?m)^matrix_playbook_migration_validated_version:\s*(\S+)`).FindSubmatch(b)
if m == nil {
return ""
}
return string(m[1])
}
// VarsYAML renders inventory/host_vars/matrix.<domain>/vars.yml.
// certPath/keyPath are only used for the self-signed and custom SSL modes.
func (c *Config) VarsYAML(migrationVersion, certPath, keyPath string) string {
w := &yamlWriter{seen: map[string]bool{}, over: c.Overrides}
// Hand-written extra vars win: a key there is left out above it, so
// vars.yml never holds it twice.
for _, line := range strings.Split(c.ExtraYAML, "\n") {
if k, _, ok := strings.Cut(line, ":"); ok && k != "" && !strings.ContainsAny(k[:1], " \t#-") {
w.seen[strings.TrimSpace(k)] = true
}
}
fmt.Fprintf(&w.b, "# Generated by interzone on %s.\n", time.Now().Format("2006-01-02 15:04"))
w.comment("Re-running interzone rewrites this file. Put hand-written settings in the")
w.comment("\"Extra vars\" box inside interzone so they survive.")
w.b.WriteString("---\n")
w.section("Basics")
if migrationVersion == "" {
migrationVersion = "'' # filled in from the playbook during deploy"
}
w.raw("matrix_playbook_migration_validated_version", migrationVersion)
w.str("matrix_domain", c.Domain)
w.raw("matrix_homeserver_implementation", c.Homeserver)
w.str("matrix_homeserver_generic_secret_key", c.GenericSecret)
w.raw("matrix_playbook_reverse_proxy_type", "playbook-managed-traefik")
w.raw("devture_systemd_docker_base_ipv6_enabled", fmt.Sprint(c.IPv6))
w.str("postgres_connection_password", c.PostgresPassword)
w.raw("matrix_homeserver_federation_enabled", fmt.Sprint(c.Federation))
if c.Federation {
c.renderFederationLists(w)
}
if c.FederationPort() == "443" {
w.comment("Federation goes through 443 with the client API, so 8448 stays closed.")
w.raw("matrix_federation_public_port", "443")
w.raw("matrix_"+c.Homeserver+"_container_labels_public_federation_api_enabled", "false")
}
w.section("Mirrors")
if c.Sources.UseRegistry && c.Sources.RegistryPrefix != "" {
w.comment("Every container image is pulled from this registry instead of docker.io, ghcr.io, etc.")
w.str("matrix_container_global_registry_prefix_override", normalizePrefix(c.Sources.RegistryPrefix))
// The RustPush role is not wired to the global override upstream.
w.raw("matrix_bridge_rustpush_container_image_registry_prefix_upstream", `"{{ matrix_container_global_registry_prefix_override }}"`)
} else {
w.comment("Images are pulled from their upstream registries.")
}
if c.Sources.DockerPackageURL != "" {
w.comment("Docker Engine packages come from this mirror of download.docker.com/linux.")
w.str("docker_repo_url", strings.TrimRight(c.Sources.DockerPackageURL, "/"))
}
w.section("SSL certificates")
switch c.SSL.Mode {
case "letsencrypt":
if c.SSL.ACMEEmail != "" {
w.str("traefik_config_certificatesResolvers_acme_email", c.SSL.ACMEEmail)
} else {
w.comment("Let's Encrypt without a contact email.")
}
case "none":
w.comment("No HTTPS: put your own TLS-terminating proxy in front of this server.")
w.raw("traefik_config_entrypoint_web_secure_enabled", "false")
case "selfsigned", "custom":
w.raw("traefik_config_certificatesResolvers_acme_enabled", "false")
w.raw("traefik_ssl_dir_enabled", "true")
w.block("traefik_provider_configuration_extension_yaml", strings.TrimSpace(`
tls:
certificates:
- certFile: /ssl/cert.pem
keyFile: /ssl/privkey.pem
stores:
default:
defaultCertificate:
certFile: /ssl/cert.pem
keyFile: /ssl/privkey.pem`))
w.block("aux_file_definitions", fmt.Sprintf(`- dest: "{{ traefik_ssl_dir_path }}/privkey.pem"
src: %s
mode: '0600'
- dest: "{{ traefik_ssl_dir_path }}/cert.pem"
src: %s`, Quote(keyPath), Quote(certPath)))
}
w.section("First admin user")
switch c.Homeserver {
case "synapse", "dendrite":
w.block("matrix_user_creator_users_additional", fmt.Sprintf("- username: %s\n initial_password: %s\n initial_type: admin",
Quote(c.AdminUser), Quote(c.AdminPassword)))
w.comment("Bridges and bots take it as their administrator; Meowlnir's management room needs one.")
w.raw("matrix_admin", Quote("@"+c.AdminUser+":{{ matrix_domain }}"))
if c.UsesMAS() {
if c.Signup {
w.comment("Anyone with the sign-up token can create an account; no email is asked")
w.comment("for, as the server sends none. interzone makes the token on each install.")
}
w.raw("matrix_authentication_service_config_account_password_registration_enabled", strconv.FormatBool(c.Signup))
if c.Signup {
w.raw("matrix_authentication_service_config_account_password_registration_email_required", "false")
w.raw("matrix_authentication_service_config_account_password_registration_token_required", "true")
}
}
case "continuwuity", "tuwunel":
if c.CloseRegistration {
w.comment("Registration was closed from interzone's Manage menu.")
w.raw("matrix_"+c.Homeserver+"_config_allow_registration", "false")
break
}
w.comment("These servers can't create users from Ansible. Register the first account")
w.comment("from any client using this token, then close registration from interzone.")
w.raw("matrix_"+c.Homeserver+"_config_allow_registration", "true")
w.str("matrix_"+c.Homeserver+"_config_registration_token", c.AdminPassword)
case "conduit":
if c.CloseRegistration {
w.comment("Registration was closed from interzone's Manage menu.")
w.raw("matrix_conduit_allow_registration", "false")
break
}
w.comment("Conduit can't create users from Ansible. Registration is open until you")
w.comment("create your account; close it afterwards from interzone's Manage menu.")
w.raw("matrix_conduit_allow_registration", "true")
}
// Continuwuity's own OAuth login is on by default; Tuwunel's needs this,
// and the client well-known it's only given with HTTPS.
if c.Homeserver == "tuwunel" && c.SSL.Mode != "none" {
w.comment("Tuwunel's own login and sign-up page, for apps with OAuth login like Element X.")
w.str("matrix_tuwunel_environment_variables_extension", "TUWUNEL_OIDC_NATIVE_AUTH=true")
}
w.section("Components")
for _, cat := range catalog.Categories {
var comps []catalog.Component
for _, comp := range catalog.Components {
if comp.Category != cat {
continue
}
if c.Enabled(comp) || (comp.DefaultOn && comp.EnableVar != "") {
comps = append(comps, comp)
}
}
if len(comps) == 0 {
continue
}
fmt.Fprintf(&w.b, "\n# %s\n", cat)
for _, comp := range comps {
on := c.Enabled(comp)
if comp.EnableVar != "" {
w.raw(comp.EnableVar, fmt.Sprint(on))
}
if !on {
continue
}
keys := make([]string, 0, len(comp.Extra))
for k := range comp.Extra {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
w.raw(k, comp.Extra[k])
}
for _, f := range comp.Fields {
if f.ShowIf != "" && c.Values[f.ShowIf] != "true" {
continue
}
w.field(f, c.Values[f.Var])
}
if hv := comp.HostVar(); c.Values[hv] != "" {
w.str(hv, c.Values[hv])
}
}
}
var rest []string
for _, k := range slices.Sorted(maps.Keys(c.Overrides)) {
if !w.seen[k] {
rest = append(rest, k)
}
}
if len(rest) > 0 {
w.section("Tuning")
w.comment("Role defaults changed in interzone's Fine-tune screen (Manage).")
for _, k := range rest {
w.override(k, c.Overrides[k])
}
}
if extra := strings.TrimSpace(c.ExtraYAML); extra != "" {
w.section("Extra vars (hand-written)")
w.b.WriteString(extra + "\n")
}
return w.b.String()
}
func normalizePrefix(p string) string {
p = strings.TrimPrefix(strings.TrimPrefix(strings.TrimSpace(p), "https://"), "http://")
return strings.TrimRight(p, "/") + "/"
}
// systemPython is the Python the playbook installs packages for.
var systemPython = "/usr/bin/python3"
// HostsINI renders inventory/hosts.
func (c *Config) HostsINI() string {
var b strings.Builder
b.WriteString("# Generated by interzone.\n[matrix_servers]\n")
parts := []string{c.HostName()}
t := c.Target
if t.Mode == "local" {
parts = append(parts, "ansible_connection=local")
// Ansible would otherwise run modules with its own venv's Python,
// which lacks the Docker SDK the playbook installs for the system's.
if _, err := os.Stat(systemPython); err == nil {
parts = append(parts, "ansible_python_interpreter="+systemPython)
}
if os.Geteuid() != 0 {
parts = append(parts, "ansible_become=true", "ansible_become_user=root")
}
} else {
parts = append(parts, "ansible_host="+iniQuote(t.Host), "ansible_ssh_user="+iniQuote(t.User))
if t.Port != "" && t.Port != "22" {
parts = append(parts, "ansible_port="+iniQuote(t.Port))
}
if t.SSHKey != "" {
parts = append(parts, "ansible_ssh_private_key_file="+iniQuote(t.SSHKey))
}
if t.User != "root" {
parts = append(parts, "ansible_become=true", "ansible_become_user=root")
}
}
if t.BecomePass != "" {
parts = append(parts, "ansible_become_password="+iniQuote(t.BecomePass))
}
b.WriteString(strings.Join(parts, " ") + "\n")
return b.String()
}
// renderFederationLists writes which servers to federate with: Synapse
// takes an allow list of names, Continuwuity and Tuwunel regexes for both.
func (c *Config) renderFederationLists(w *yamlWriter) {
list := func(names []string, pattern bool) string {
out := []string{}
for _, n := range names {
if pattern {
n = "^" + regexp.QuoteMeta(n) + "$"
}
out = append(out, n)
}
b, _ := json.Marshal(out)
return string(b)
}
switch c.Homeserver {
case "synapse":
if len(c.FederateOnly) > 0 {
w.raw("matrix_synapse_federation_domain_whitelist", list(c.FederateOnly, false))
}
case "continuwuity", "tuwunel":
if len(c.FederateOnly) > 0 {
w.raw("matrix_"+c.Homeserver+"_config_allowed_remote_server_names", list(c.FederateOnly, true))
}
if len(c.FederateNever) > 0 {
w.raw("matrix_"+c.Homeserver+"_config_forbidden_remote_server_names", list(c.FederateNever, true))
}
}
}