Files
archie/internal/infrastructure/configuration/validate_test.go
T
sam 508a0ad48c feat(forge): GitHub webhook receiver for immediate issue dispatch
Add [forge] intake = "poll" (default) | "webhook" | "both", and a forge
webhook receiver (internal/forge/webhook) that verifies a GitHub webhook's
HMAC signature, decodes the "issues" event, and publishes a matched issue
through the same path the poller uses -- so a labelled or assigned issue
starts a task the moment it happens instead of waiting up to poll_interval
(bead archie-core-7d5u.4).

The dispatch predicate (workintake.MatchesDispatch/RequiresLabel) is now a
single shared definition consumed by both the poller and the webhook
receiver, so the two cannot drift -- including the empty-label guard from
63d0446 (an empty label must never match every open issue). Assignee
matching is case-insensitive to agree with AssignedIssues' server-side
GitHub filter; label matching stays case-sensitive, since GitHub labels
are case-distinct.

daemon.publishTask is exported as PublishTask, the single enqueue path
now shared by the poller and the webhook intake.

Two failure modes fixed during adversarial self-review before this landed:
a webhook secret that fails to resolve at runtime now degrades (logs and
skips the receiver) instead of aborting the whole daemon -- under
intake="both" the poll exists specifically as a backstop for this exact
misconfiguration, so crashing boot over it defeated its own purpose;
multi-identity deployments ([[identities]]) are explicitly unsupported for
now (webhook intake refuses to start, logs why, and leaves each identity's
own poll loop unaffected) rather than silently matching issues against the
wrong identity's dispatch rules.
2026-08-22 19:21:09 +10:00

337 lines
11 KiB
Go

package configuration
import (
"errors"
"os"
"testing"
"time"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/secret"
)
// A minimal config that satisfies every check validate applies without
// relying on applyDefaults -- Validate documents that it does not apply
// defaults, so this fixture fills in every field a default would otherwise
// have supplied.
func minimalValidConfig() config.Config {
return config.Config{
BotUser: "archie-bot",
PollInterval: config.Duration(60 * time.Second),
Agent: config.Agent{Mode: "inprocess"},
Dispatch: config.Dispatch{
Trigger: "assignee",
},
Forge: config.Forge{Type: "none"},
}
}
// TestForgeDisabled pins the single definition of the disabled-forge
// predicate: cmd/archied's resolveForge calls ForgeDisabled instead of
// maintaining its own copy, so any alias added or removed here must hold
// for both config validation and daemon startup. The table deliberately
// includes a case-variant alias and the empty string to catch a future
// implementation that lowercases or matches prefixes instead of comparing
// the exact aliases.
func TestForgeDisabled(t *testing.T) {
tests := []struct {
name string
typ string
want bool
}{
{name: "none", typ: "none", want: true},
{name: "off", typ: "off", want: true},
{name: "disabled", typ: "disabled", want: true},
{name: "github", typ: "github", want: false},
{name: "gitea", typ: "gitea", want: false},
{name: "empty string", typ: "", want: false},
{name: "case variant is not an alias", typ: "None", want: false},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if got := ForgeDisabled(tc.typ); got != tc.want {
t.Errorf("ForgeDisabled(%q) = %v, want %v", tc.typ, got, tc.want)
}
})
}
}
func TestValidate_IsCallableOutsideThePackage(t *testing.T) {
cfg := minimalValidConfig()
if err := Validate(&cfg); err != nil {
t.Fatalf("Validate(minimal valid config) = %v, want nil", err)
}
}
func TestValidate_RejectsTheSameProblemsAsLoaderLoad(t *testing.T) {
tests := []struct {
name string
mutate func(cfg *config.Config)
wantErr bool
}{
{
name: "valid config",
mutate: func(cfg *config.Config) {},
wantErr: false,
},
{
name: "missing bot_user with no identities",
mutate: func(cfg *config.Config) { cfg.BotUser = "" },
wantErr: true,
},
{
name: "unrecognised agent.mode",
mutate: func(cfg *config.Config) { cfg.Agent.Mode = "not-a-real-mode" },
wantErr: true,
},
{
name: "unrecognised dispatch.trigger",
mutate: func(cfg *config.Config) { cfg.Dispatch.Trigger = "not-a-real-trigger" },
wantErr: true,
},
{
// GH#445: an empty label matches every open issue via the forge
// API's issues-list filter, so a "label" trigger with no label
// set must fail validation rather than queue the whole repo.
name: "label trigger with empty label",
mutate: func(cfg *config.Config) {
cfg.Dispatch.Trigger = "label"
cfg.Label = ""
},
wantErr: true,
},
{
name: "either trigger with empty label",
mutate: func(cfg *config.Config) {
cfg.Dispatch.Trigger = "either"
cfg.Label = ""
},
wantErr: true,
},
{
name: "label trigger with a label set",
mutate: func(cfg *config.Config) {
cfg.Dispatch.Trigger = "label"
cfg.Label = "archie"
},
wantErr: false,
},
{
name: "unrecognised forge.type",
mutate: func(cfg *config.Config) { cfg.Forge.Type = "not-a-real-forge" },
wantErr: true,
},
{
name: "negative poll_interval",
mutate: func(cfg *config.Config) { cfg.PollInterval = config.Duration(-5 * time.Second) },
wantErr: true,
},
{
name: "zero poll_interval",
mutate: func(cfg *config.Config) { cfg.PollInterval = 0 },
wantErr: true,
},
{
name: "provider base_url carries userinfo",
mutate: func(cfg *config.Config) {
cfg.Providers = map[string]config.Provider{
"acme": {BaseURL: "https://user:pass@example.com"},
}
},
wantErr: true,
},
{
name: "negative capture.retention",
mutate: func(cfg *config.Config) { cfg.Capture.Retention = config.Duration(-time.Hour) },
wantErr: true,
},
{
name: "negative capture.max_events",
mutate: func(cfg *config.Config) { cfg.Capture.MaxEvents = -1 },
wantErr: true,
},
{
name: "negative capture.max_body_bytes",
mutate: func(cfg *config.Config) { cfg.Capture.MaxBodyBytes = -1 },
wantErr: true,
},
{
name: "negative capture.rate_per_second",
mutate: func(cfg *config.Config) { cfg.Capture.RatePerSecond = -1 },
wantErr: true,
},
{
name: "negative capture.rate_burst",
mutate: func(cfg *config.Config) { cfg.Capture.RateBurst = -1 },
wantErr: true,
},
{
name: "zero capture fields are valid (defaults fill them)",
mutate: func(cfg *config.Config) {},
wantErr: false,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
cfg := minimalValidConfig()
tc.mutate(&cfg)
err := Validate(&cfg)
if tc.wantErr && err == nil {
t.Fatal("Validate() = nil, want an error")
}
if tc.wantErr && !errors.Is(err, ErrInvalidInput) {
t.Errorf("Validate() = %v, want it to wrap ErrInvalidInput", err)
}
if !tc.wantErr && err != nil {
t.Fatalf("Validate() = %v, want nil", err)
}
})
}
}
// TestValidateNATS pins the nats mode contract from docs/prds/embedded-nats.md:
// an unset mode resolves from url without mutating cfg, external requires url,
// embedded/off forbid a url, and agent.mode="nats" requires external.
func TestValidateNATS(t *testing.T) {
tests := []struct {
name string
mode string
url string
agent string
wantErr bool
}{
{name: "unset mode with url resolves external", url: "nats://localhost:4222"},
{name: "unset mode without url resolves embedded"},
{name: "embedded with no url", mode: config.NATSModeEmbedded},
{name: "off with no url", mode: config.NATSModeOff},
{name: "external with url", mode: config.NATSModeExternal, url: "nats://localhost:4222"},
{name: "external without url", mode: config.NATSModeExternal, wantErr: true},
{name: "embedded with url", mode: config.NATSModeEmbedded, url: "nats://localhost:4222", wantErr: true},
{name: "off with url", mode: config.NATSModeOff, url: "nats://localhost:4222", wantErr: true},
{name: "unknown mode", mode: "not-a-mode", wantErr: true},
{name: "agent nats with embedded", mode: config.NATSModeEmbedded, agent: "nats", wantErr: true},
{name: "agent nats with external", mode: config.NATSModeExternal, url: "nats://localhost:4222", agent: "nats"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
cfg := minimalValidConfig()
cfg.NATS = config.NATSConfig{Mode: tc.mode, URL: tc.url}
if tc.agent != "" {
cfg.Agent.Mode = tc.agent
}
err := validateNATS(&cfg)
if tc.wantErr && err == nil {
t.Fatal("validateNATS() = nil, want an error")
}
if !tc.wantErr && err != nil {
t.Fatalf("validateNATS() = %v, want nil", err)
}
})
}
}
// TestValidateContainersResolvesNATSMode pins that validateContainers reads
// the *resolved* nats mode, not the raw field: a hand-built config with
// containers enabled and a url but no explicit mode must validate the same way
// the loader's on-disk form does (url implies external), rather than diverge
// because validateContainers saw an empty mode.
func TestValidateContainersResolvesNATSMode(t *testing.T) {
base := func() config.Config {
cfg := minimalValidConfig()
cfg.Containers = config.ContainerConfig{Enabled: true, Image: "archie-agent:latest"}
cfg.Agent.Mode = "nats"
return cfg
}
t.Run("unset mode with url resolves external", func(t *testing.T) {
cfg := base()
cfg.NATS.URL = "nats://localhost:4222"
if err := Validate(&cfg); err != nil {
t.Fatalf("Validate() = %v, want nil (unset mode + url resolves external)", err)
}
})
t.Run("embedded mode rejects containers", func(t *testing.T) {
cfg := base()
cfg.NATS.Mode = config.NATSModeEmbedded
if err := Validate(&cfg); err == nil {
t.Fatal("Validate() = nil, want an error for containers with embedded nats")
}
})
}
// TestValidateForgeIntake pins the forge.intake contract: an unset intake
// resolves to poll without mutating cfg, and webhook/both require a webhook
// secret and listen address.
func TestValidateForgeIntake(t *testing.T) {
tests := []struct {
name string
intake string
secret secret.SecretRef
addr string
natsMode string
wantErr bool
}{
{name: "unset resolves poll"},
{name: "poll is valid", intake: config.ForgeIntakePoll},
{name: "webhook requires secret", intake: config.ForgeIntakeWebhook, addr: "0.0.0.0:8645", wantErr: true},
{name: "webhook requires addr", intake: config.ForgeIntakeWebhook, secret: secret.SecretRef{Engine: "env", Key: "SECRET"}, wantErr: true},
{name: "webhook with secret and addr is valid", intake: config.ForgeIntakeWebhook, secret: secret.SecretRef{Engine: "env", Key: "SECRET"}, addr: "0.0.0.0:8645"},
{name: "both with secret and addr is valid", intake: config.ForgeIntakeBoth, secret: secret.SecretRef{Engine: "env", Key: "SECRET"}, addr: "0.0.0.0:8645"},
{name: "webhook with nats off is rejected", intake: config.ForgeIntakeWebhook, secret: secret.SecretRef{Engine: "env", Key: "SECRET"}, addr: "0.0.0.0:8645", natsMode: config.NATSModeOff, wantErr: true},
{name: "unknown intake", intake: "not-a-mode", wantErr: true},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
cfg := minimalValidConfig()
cfg.Forge.Intake = tc.intake
cfg.Forge.WebhookSecret = tc.secret
cfg.Forge.WebhookAddr = tc.addr
if tc.natsMode != "" {
cfg.NATS.Mode = tc.natsMode
}
err := validateForgeIntake(&cfg)
if tc.wantErr && err == nil {
t.Fatal("validateForgeIntake() = nil, want an error")
}
if !tc.wantErr && err != nil {
t.Fatalf("validateForgeIntake() = %v, want nil", err)
}
})
}
}
// Validate must run the exact same checks Loader.File applies internally --
// this pins that a config Validate accepts on its own, once the same
// defaults Loader.File would apply are filled in by hand, is also accepted
// when it goes through the real file-loading path.
func TestValidate_AgreesWithLoaderLoad(t *testing.T) {
dir := t.TempDir()
path := dir + "/config.toml"
const doc = `
bot_user = "archie-bot"
[agent]
mode = "inprocess"
[dispatch]
trigger = "assignee"
[forge]
type = "none"
`
if err := os.WriteFile(path, []byte(doc), 0o600); err != nil {
t.Fatal(err)
}
cfg := minimalValidConfig()
if err := Validate(&cfg); err != nil {
t.Fatalf("Validate(in-memory) = %v, want nil", err)
}
if _, err := New(nil).File(path); err != nil {
t.Fatalf("Loader.File(equivalent config on disk) = %v, want nil", err)
}
}