Files
archie/internal/webui/api_config_test.go
T
sam f544dd0978 feat(config): SIGHUP-triggered reload with requires-restart warnings
The daemon can now re-read its configuration on SIGHUP (or on a
future in-process trigger) and republish it through the Holder,
closing the first half of issue #348: 'config can change at runtime,
safely, and can't brick the daemon.'

Reload path:
- cmd/archied/reload.go: ReloadController re-runs loader.Resolve on
  the same paths main.go passed at startup (Resolve is pure -- no
  reload state added to the loader). apply is called only with a
  Document that passed validation; a failed reload records the error
  and its timestamp and leaves the running config untouched. That
  Set-not-called-on-error property is the safety core and is pinned
  by TestReloadValidationFailureDoesNotApply.
- SIGHUP listener in main.go runs reloadLoop(ctx, ch, controller, log);
  the loop is extracted as a testable seam (syscall.SIGHUP is Unix-only,
  fine given the Linux target).

PollInterval is genuinely reloadable now, not just re-read:
the three ticker sites (Run, per-identity goroutine, shared
maintenance loop) re-read the interval each tick and Reset the ticker
on change. A reloaded poll_interval takes effect on the next cycle.

Diff-and-warn so an operator never has to read the source to know
whether an edit took effect: changedNonReloadableFields compares the
old and new snapshots against an allowlist of re-read fields
(PollInterval, Repos, DiffCapLines, Budgets, Dispatch, and the
Containers sub-fields VolumeTTL + MaxConcurrency). Anything else that
changed logs Warn 'requires a restart'; a fully-applied reload logs
Info. The allowlist is deliberate: a field added to Config later
defaults to requires-restart, the safe direction.

NATS split-brain closed: containerEnv now hands containers the
endpoint the daemon's own client connected with at startup
(Daemon.ConnectedNATS, captured at construction) instead of the live
config, so a reloaded nats.url cannot point new containers at a
server the daemon is not publishing on. A nats change is therefore
classified requires-restart, and CLAUDE.md's 'hands its own nats.url
verbatim' note is updated to the meaning it now has (same today,
deliberately different after a reload).

Validation guard: poll_interval <= 0 is rejected in validate.go
beside the VolumeTTL guard. applyDefaults fills zero with 60s, so
this fires on an explicit negative -- which would panic
time.NewTicker/Reset at boot and, after the per-iteration reset,
on a SIGHUP mid-run.

Observability: config.ReloadStatus (last_error, last_error_at,
last_reload_at) is recorded by the controller and surfaced in
/api/config via Server.LastReload, so a stale running config is
visible in the dashboard, not just the logs. Rendering waits for the
UI step.

Recovery hatch: --no-config-overlay flag plus ARCHIE_SKIP_CONFIG_OVERLAY=1
(configuration.SkipOverlay), logged at startup. No overlay source
exists yet; the flag is the documented escape hatch the DB overlay
(step 3 of #348) will consult.

webui.Server.ConfigProvenance becomes atomic.Pointer so a reload can
swap it via SetProvenance independently of Cfg; the accepted skew
(new config alongside old provenance) is documented on the field.

Verified: task check clean; -race on daemon, webui, cmd/archied,
config, infrastructure/configuration.
2026-08-10 00:19:46 +10:00

310 lines
9.7 KiB
Go

package webui
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/channels"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/secret"
)
// fakeSecrets are recognisable strings that must never appear anywhere in
// handleConfig's response body. If any of these leak, the allowlist in
// api_config.go has a hole -- see handleConfig's doc comment for why it is
// built field by field rather than by marshalling config.Config directly.
const (
fakeForgeToken = "ghp_FAKESECRETTOKENVALUE123"
fakeProviderKey = "sk-FAKEPROVIDERKEYVALUE456"
fakeBWSKeyName = "FAKE-BWS-SECRET-KEY-789"
fakeNATSToken = "nats-FAKESECRETTOKEN000"
)
func configWithFakeSecrets() *config.Holder {
return config.NewHolder(config.Config{
WorkDir: "/work/archie",
SkillsDir: "/work/archie/.agents/skills",
DBPath: "/work/archie/archie.db",
BotUser: "archie-bot",
BotEmail: "archie@example.com",
Label: "archie",
Forge: config.Forge{
Type: "gitea",
Host: "gitea.example.com",
TokenEnv: "GITEA_TOKEN",
Token: secret.SecretRef{Engine: "env", Key: fakeForgeToken},
},
Models: map[string]string{"builder": "openai/gpt-4"},
Providers: map[string]config.Provider{
"openai": {
Class: "openai",
APIKeyEnv: "OPENAI_API_KEY",
APIKey: secret.SecretRef{Engine: "bws", Key: fakeBWSKeyName},
BaseURL: "https://api.openai.com/v1",
},
"custom": {
Class: "custom",
APIKey: secret.SecretRef{Engine: "literal", Key: fakeProviderKey},
},
},
Repos: []config.Repo{
{Owner: "acme", Name: "widget", Base: "main", Gate: [][]string{{"task", "check"}}},
},
Agent: config.Agent{Mode: "subprocess", Command: "/usr/local/bin/archie-agent", Env: []string{"HOME"}},
NATS: config.NATSConfig{URL: "nats://127.0.0.1:4222", TokenEnv: "NATS_TOKEN"},
Chat: config.ChatConfig{
Telegram: config.TelegramConfig{TokenEnv: "TELEGRAM_TOKEN"},
},
})
}
// leakCandidates returns the set of fake secret strings a test should
// confirm are absent from a response body. NATS token is included even
// though handleConfig doesn't expose NATS today, guarding against a future
// regression that starts serializing it wholesale.
func leakCandidates() []string {
return []string{fakeForgeToken, fakeProviderKey, fakeBWSKeyName, fakeNATSToken}
}
func TestHandleConfigNeverLeaksSecrets(t *testing.T) {
cases := []struct {
name string
cfg *config.Holder
}{
{name: "populated config with secrets", cfg: configWithFakeSecrets()},
{name: "nil config", cfg: nil},
{name: "zero-value config", cfg: config.NewHolder(config.Config{})},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
srv := newTestServer(t)
srv.Cfg = tc.cfg
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
}
body := w.Body.String()
for _, leak := range leakCandidates() {
if strings.Contains(body, leak) {
t.Errorf("response body leaked secret value %q:\n%s", leak, body)
}
}
var got map[string]any
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("response is not valid JSON: %v", err)
}
})
}
}
// TestHandleConfigSafeFieldsPresent proves the allowlisted, non-secret
// fields still make it through -- a test that only checked for absence of
// secrets could pass trivially by returning {}.
func TestHandleConfigSafeFieldsPresent(t *testing.T) {
srv := newTestServer(t)
srv.Cfg = configWithFakeSecrets()
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
var got ConfigView
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("decode: %v", err)
}
if got.Identity.BotUser != "archie-bot" {
t.Errorf("Identity.BotUser = %q, want archie-bot", got.Identity.BotUser)
}
if got.Identity.ForgeHost != "gitea.example.com" {
t.Errorf("Identity.ForgeHost = %q, want gitea.example.com", got.Identity.ForgeHost)
}
if len(got.Repositories) != 1 || got.Repositories[0].Owner != "acme" {
t.Errorf("Repositories = %+v", got.Repositories)
}
if !got.Providers["openai"].Configured {
t.Errorf("Providers[openai].Configured = false, want true (APIKeyEnv is set)")
}
if got.Providers["openai"].APIKeyEnv != "OPENAI_API_KEY" {
t.Errorf("Providers[openai].APIKeyEnv = %q, want OPENAI_API_KEY", got.Providers["openai"].APIKeyEnv)
}
if got.Agent.Mode != "subprocess" {
t.Errorf("Agent.Mode = %q, want subprocess", got.Agent.Mode)
}
if got.Storage.WorkDir != "/work/archie" {
t.Errorf("Storage.WorkDir = %q", got.Storage.WorkDir)
}
}
// TestHandleConfigIncludesReloadStatus proves a failed reload is surfaced
// in /api/config so the operator can see the running config is stale
// without reading logs.
func TestHandleConfigIncludesReloadStatus(t *testing.T) {
srv := newTestServer(t)
srv.Cfg = configWithFakeSecrets()
srv.LastReload = func() config.ReloadStatus {
return config.ReloadStatus{
LastError: "poll_interval must be positive",
LastErrorAt: "2026-08-09T12:00:00Z",
}
}
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
var got ConfigView
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("decode: %v", err)
}
if got.Reload == nil {
t.Fatal("Reload = nil, want the failed-reload status")
}
if got.Reload.LastError != "poll_interval must be positive" {
t.Errorf("Reload.LastError = %q", got.Reload.LastError)
}
if got.Reload.LastErrorAt != "2026-08-09T12:00:00Z" {
t.Errorf("Reload.LastErrorAt = %q", got.Reload.LastErrorAt)
}
}
// TestHandleConfigOmitsReloadStatusWhenUnavailable pins that the reload
// field is absent (not empty) when the server has no reload seam wired.
func TestHandleConfigOmitsReloadStatusWhenUnavailable(t *testing.T) {
srv := newTestServer(t)
srv.Cfg = configWithFakeSecrets()
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
var got ConfigView
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("decode: %v", err)
}
if got.Reload != nil {
t.Errorf("Reload = %+v, want nil (no reload seam)", got.Reload)
}
}
// TestSetProvenancePublishesForConfigView proves a reloaded provenance
// list reaches /api/config.
func TestSetProvenancePublishesForConfigView(t *testing.T) {
srv := newTestServer(t)
srv.Cfg = configWithFakeSecrets()
srv.SetProvenance([]ConfigOrigin{
{Path: "/etc/archie/config.toml", Role: "main", Layer: "base"},
{Path: "/etc/archie/conf.d/docker.yaml", Role: "extra", Layer: "overlay", Feature: "docker"},
})
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
var got ConfigView
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("decode: %v", err)
}
if len(got.Provenance) != 2 {
t.Fatalf("Provenance = %+v, want 2 origins", got.Provenance)
}
if got.Provenance[0].Path != "/etc/archie/config.toml" {
t.Errorf("Provenance[0].Path = %q", got.Provenance[0].Path)
}
}
func TestHandleChannelsReportsConfiguredState(t *testing.T) {
srv := newTestServer(t)
srv.Cfg = configWithFakeSecrets()
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/channels", nil)
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
}
body := w.Body.String()
for _, leak := range leakCandidates() {
if strings.Contains(body, leak) {
t.Errorf("channels response leaked secret value %q:\n%s", leak, body)
}
}
var got struct {
Channels []ChannelView `json:"channels"`
}
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("decode: %v", err)
}
var telegram *ChannelView
for i := range got.Channels {
if got.Channels[i].Name == "Telegram" {
telegram = &got.Channels[i]
}
}
if telegram == nil {
t.Fatal("no Telegram channel in response")
}
if !telegram.Configured {
t.Errorf("Telegram.Configured = false, want true (TokenEnv is set)")
}
}
func TestHandleChannelsNilConfig(t *testing.T) {
srv := newTestServer(t)
srv.Cfg = nil
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/channels", nil)
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
}
var got struct {
Channels []ChannelView `json:"channels"`
}
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("decode: %v", err)
}
if len(got.Channels) != 0 {
t.Errorf("Channels = %+v, want empty when Cfg is nil", got.Channels)
}
}
func TestHandleChannelsUsesRuntimeManager(t *testing.T) {
srv := newTestServer(t)
srv.Cfg = configWithFakeSecrets()
srv.Channels = channels.NewManager([]channels.Descriptor{{
ID: "telegram", Name: "Telegram", Configured: true, ReloadSupported: true,
}})
srv.Channels.MarkFailed("telegram", "token rejected")
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/channels", nil)
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
var got struct {
Channels []ChannelView `json:"channels"`
}
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
if len(got.Channels) != 1 || got.Channels[0].State != "failed" || !got.Channels[0].ReloadSupported {
t.Fatalf("channels = %#v", got.Channels)
}
}