hosts was written with YAML quoting ('' for a quote), but Ansible splits
inventory lines like a shell, so it read it'' as its and becoming root
failed. Values are now shell-quoted, the SSH host, user, port and key
too, and the importer reads lines back the same way Ansible does.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
431 lines
14 KiB
Go
431 lines
14 KiB
Go
package config
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"maps"
|
|
"os"
|
|
"regexp"
|
|
"slices"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"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") {
|
|
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, " "))
|
|
}
|
|
|
|
// 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, 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)))
|
|
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))
|
|
}
|
|
}
|
|
}
|