Files
archie/internal/infrastructure/configuration/setup/envsink.go
T
sam ee608d81fb feat(configuration): add archied setup, the caller the first-run flow was built for
docs/architecture/configuration.md decides that "install.sh must stop generating
config.toml; archied setup owns it", and gives the reason: the installer
hand-rolling TOML already drifted from the schema once, and "the durable fix is
that the code writing the config is the code that reads it". setup.Run,
tomlwrite, configtemplate.Example and terminalprompt were all built for that and
had no production caller between them. This adds the caller.

setup.Run's own doc comment states the obligations, and they are the shape of
installValidatedConfig: render the edits, prove the result loads through a real
configuration.Loader, and only then install the file and commit the secrets. A
validation failure returns before either write, so a bad config leaves neither a
config nor a secret on disk. The rendered bytes are proven from a temp file, so
a load failure cannot have already installed anything. The config is written
0600 via same-directory temp and rename.

Parameterisation is typed, not matched against prompt text. A flag-to-prompt
mapping would have to match strings, which is the brittleness removed in
9a4f11c, so setup.Params is consulted before each question instead and the
prompts are only reached for answers nothing supplied. Run stays a wrapper
passing the zero value, so the package's existing tests keep passing untouched.
No environment variable is consulted anywhere: flags and prompts are the only
two ways an answer arrives.

--defaults is a known-valid unattended baseline, not "each prompt's own default".
That cannot work, and the test proves it: the provider step's first option is
OpenAI, whose model prompt hard-errors on an empty answer. The baseline therefore
covers every required answer and leaves optional ones to answer themselves as
"skip" -- ollama is the only keyless provider, so an unattended install boots
without needing a secret.

Two gaps closed after review rather than left as accepted work:

- A cloud provider was not configurable without a terminal, because the provider
  API key had no typed parameter: unattended setup could only ever pick the
  keyless self-hosted provider. Params.ProviderAPIKey and -provider-api-key fix
  that. The key goes to the env file and TOML carries only the secret reference.
- The write order was unpinned. Inverting installValidatedConfig's two writes --
  committing secrets before the config -- left every test green, so nothing held
  the invariant the SecretSink contract states. The new
  TestInstallValidatedConfig_ConfigWriteFailureLeavesNoSecret fails on that
  inversion; the existing validation-failure test does not cover it.

Also fixed three lint failures in the first pass (gocyclo on RunSetup, and two
ineffectual `choice` initialisers): RunSetup's flag surface, the flag-to-Params
mapping, the prompter choice and the existing-config read are now separate
functions, which is the real fix for the complexity rather than a suppression.

The setup flow no longer hand-rolls its own answer format: -telegram-user-ids
reuses setup.ParseTelegramUserIDs, the same parser the prompt path uses, so the
allowlist cannot be parsed two ways.

Found by an adversarial package sweep (temp tracker: config-1,
repo-root-deployment-2, .local/issue-tracker/). Plan of record:
.local/issue-tracker/design-archied-setup.md. install.sh still generates its own
config; that is phase 2 and is not claimed here.
2026-09-15 02:52:24 +10:00

143 lines
4.1 KiB
Go

package setup
import (
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
)
// EnvFileSink is a SecretSink that stores secrets in the env file beside
// config.toml (${XDG_CONFIG_HOME:-~/.config}/archie/env by default). The
// daemon reads that file through systemd's EnvironmentFile, so the line
// format must match what install.sh's set_env_key has always written -- a
// single-quoted KEY='value' line, with an embedded single quote escaped as a
// backslash between two single quotes -- rather than any other
// plausible-looking format.
//
// Put buffers; nothing is written until Commit, and Commit rewrites the file
// atomically with mode 0600. The caller must only Commit once the config
// text referencing these secrets has been proven loadable, so a validation
// failure leaves neither a config nor a secret on disk.
type EnvFileSink struct {
path string
entries map[string]string
}
// NewEnvFileSink returns a sink that writes the env file at path.
func NewEnvFileSink(path string) *EnvFileSink {
return &EnvFileSink{path: path, entries: map[string]string{}}
}
// Put records an env-file entry. Only the "env" engine has a representation
// in the env file; every key setup writes uses engine "env".
func (s *EnvFileSink) Put(engine, key, value string) error {
if engine != "env" {
return fmt.Errorf("setup: env file sink cannot store engine %q secrets", engine)
}
if strings.TrimSpace(key) == "" {
return fmt.Errorf("setup: env file sink: empty key")
}
s.entries[key] = value
return nil
}
// Commit writes every Put entry, replacing any existing line for the same
// key, leaving unrelated lines byte-identical, and persists the result
// atomically.
func (s *EnvFileSink) Commit() error {
if len(s.entries) == 0 {
return nil
}
keys := make([]string, 0, len(s.entries))
for k := range s.entries {
keys = append(keys, k)
}
sort.Strings(keys)
var out []string
existing, err := readEnvLines(s.path)
if err != nil {
return fmt.Errorf("setup: read env file: %w", err)
}
for _, line := range existing {
keep := true
for _, key := range keys {
if strings.HasPrefix(line, key+"=") {
keep = false
break
}
}
if keep {
out = append(out, line)
}
}
for _, key := range keys {
out = append(out, key+"='"+escapeEnvValue(s.entries[key])+"'")
}
if err := os.MkdirAll(filepath.Dir(s.path), 0o700); err != nil {
return fmt.Errorf("setup: create env directory: %w", err)
}
if err := writeEnvFileAtomic(s.path, []byte(strings.Join(out, "\n")+"\n")); err != nil {
return fmt.Errorf("setup: write env file: %w", err)
}
return nil
}
// readEnvLines reads the env file's lines, without their trailing newline.
// A missing or empty file yields no lines.
func readEnvLines(path string) ([]string, error) {
b, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
text := strings.TrimSuffix(string(b), "\n")
if text == "" {
return nil, nil
}
return strings.Split(text, "\n"), nil
}
// escapeEnvValue renders value as the contents of a single-quoted
// systemd EnvironmentFile value: a literal single quote becomes a backslash
// between two single quotes. This is byte-for-byte what install.sh's
// set_env_key produces, so the Go sink and the shell helper cannot disagree
// about the on-disk format.
func escapeEnvValue(v string) string {
return strings.ReplaceAll(v, "'", `'\''`)
}
// writeEnvFileAtomic writes data to path via a same-directory temp file and
// rename, mirroring set_env_key's mktemp-then-mv so a reader never observes
// a half-written env file.
func writeEnvFileAtomic(path string, data []byte) error {
tmp, err := os.CreateTemp(filepath.Dir(path), ".env.XXXXXX")
if err != nil {
return err
}
name := tmp.Name()
defer os.Remove(name) // no-op after a successful rename
if err := tmp.Chmod(0o600); err != nil {
tmp.Close()
return err
}
if _, err := tmp.Write(data); err != nil {
tmp.Close()
return err
}
if err := tmp.Sync(); err != nil {
tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
return os.Rename(name, path)
}