refactor: testing from the beginning. a journey in 150k lines of tests to none
This commit is contained in:
651 files changed
-146443
No files matched your search
@@ -1,250 +0,0 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
)
|
||||
|
||||
const acme = "acme"
|
||||
|
||||
func principal(role org.Role) access.Principal {
|
||||
return access.Principal{
|
||||
IdentityID: identity.IdentityID("11111111-1111-5111-8111-111111111111"),
|
||||
Kind: identity.KindUser,
|
||||
Org: acme,
|
||||
Memberships: []org.Membership{
|
||||
{IdentityID: identity.IdentityID("11111111-1111-5111-8111-111111111111"), OrgID: acme, Role: role},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func resource(kind access.ResourceKind, id string) access.Resource {
|
||||
return access.Resource{Kind: kind, ID: id, Org: acme, Workspace: "net"}
|
||||
}
|
||||
|
||||
func newEngine(t *testing.T, policies ...access.Policy) *Engine {
|
||||
t.Helper()
|
||||
e, err := New(policies)
|
||||
if err != nil {
|
||||
t.Fatalf("New() = %v, want nil", err)
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
func TestShippedRoleMatrix(t *testing.T) {
|
||||
shipped := access.ShippedOrgPolicies(acme)
|
||||
e := newEngine(t, shipped...)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
role org.Role
|
||||
action access.Action
|
||||
kind access.ResourceKind
|
||||
id string
|
||||
wantAllow bool
|
||||
}{
|
||||
// Viewer: read everything except secret values.
|
||||
{name: "viewer reads a binding", role: org.RoleViewer, action: access.ActionRead, kind: access.KindBinding, id: "b1", wantAllow: true},
|
||||
{name: "viewer reads logs", role: org.RoleViewer, action: access.ActionReadLogs, kind: access.KindTask, id: "1", wantAllow: true},
|
||||
{name: "viewer cannot read a secret", role: org.RoleViewer, action: access.ActionReadSecret, kind: access.KindSecret, id: "firewall-api"},
|
||||
{name: "viewer cannot create", role: org.RoleViewer, action: access.ActionCreate, kind: access.KindBinding, id: "b1"},
|
||||
{name: "viewer cannot run", role: org.RoleViewer, action: access.ActionRun, kind: access.KindWorkflow, id: "implement"},
|
||||
// Developer: create and edit, run, read logs -- no approve, no delete,
|
||||
// no secret values.
|
||||
{name: "developer creates a binding", role: org.RoleDeveloper, action: access.ActionCreate, kind: access.KindBinding, id: "b1", wantAllow: true},
|
||||
{name: "developer edits a mapping", role: org.RoleDeveloper, action: access.ActionUpdate, kind: access.KindMapping, id: "m1", wantAllow: true},
|
||||
{name: "developer runs a workflow", role: org.RoleDeveloper, action: access.ActionRun, kind: access.KindWorkflow, id: "implement", wantAllow: true},
|
||||
{name: "developer cannot approve", role: org.RoleDeveloper, action: access.ActionApprove, kind: access.KindBinding, id: "b1"},
|
||||
{name: "developer cannot delete", role: org.RoleDeveloper, action: access.ActionDelete, kind: access.KindBinding, id: "b1"},
|
||||
{name: "developer cannot read a secret", role: org.RoleDeveloper, action: access.ActionReadSecret, kind: access.KindSecret, id: "firewall-api"},
|
||||
{name: "developer cannot manage members", role: org.RoleDeveloper, action: access.ActionManageMembers, kind: access.KindMember, id: "u2"},
|
||||
// Admin: everything except deleting the org.
|
||||
{name: "admin approves a binding", role: org.RoleAdmin, action: access.ActionApprove, kind: access.KindBinding, id: "b1", wantAllow: true},
|
||||
{name: "admin deletes a binding", role: org.RoleAdmin, action: access.ActionDelete, kind: access.KindBinding, id: "b1", wantAllow: true},
|
||||
{name: "admin deletes the org is denied", role: org.RoleAdmin, action: access.ActionDelete, kind: access.KindOrg, id: acme},
|
||||
{name: "admin reads a secret", role: org.RoleAdmin, action: access.ActionReadSecret, kind: access.KindSecret, id: "firewall-api", wantAllow: true},
|
||||
{name: "admin manages policies", role: org.RoleAdmin, action: access.ActionManagePolicies, kind: access.KindPolicy, id: "p1", wantAllow: true},
|
||||
// Owner: everything in the org, including deleting it.
|
||||
{name: "owner deletes the org", role: org.RoleOwner, action: access.ActionDelete, kind: access.KindOrg, id: acme, wantAllow: true},
|
||||
{name: "owner manages identities", role: org.RoleOwner, action: access.ActionManageIdentities, kind: access.KindIdentity, id: "u2", wantAllow: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := e.Authorize(principal(tt.role), tt.action, resource(tt.kind, tt.id), access.Context{})
|
||||
if got.Allowed != tt.wantAllow {
|
||||
t.Fatalf("Authorize(%s, %s, %s/%s) allowed=%v level=%v policies=%v, want allow=%v",
|
||||
tt.role, tt.action, tt.kind, tt.id, got.Allowed, got.Level, got.Policies, tt.wantAllow)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrossOrgForbid(t *testing.T) {
|
||||
e := newEngine(t, access.ShippedOrgPolicies(acme)...)
|
||||
p := access.Principal{
|
||||
IdentityID: identity.IdentityID("11111111-1111-5111-8111-111111111111"),
|
||||
Org: acme,
|
||||
Memberships: []org.Membership{
|
||||
{IdentityID: identity.IdentityID("11111111-1111-5111-8111-111111111111"), OrgID: acme, Role: org.RoleOwner},
|
||||
},
|
||||
}
|
||||
got := e.Authorize(p, access.ActionRead, access.Resource{Kind: access.KindBinding, ID: "b1", Org: "other", Workspace: "net"}, access.Context{})
|
||||
if got.Allowed {
|
||||
t.Fatal("owner read of another org's binding was allowed; the cross-org forbid must win")
|
||||
}
|
||||
if got.Level != access.LevelInstance || len(got.Policies) != 1 || got.Policies[0] != access.CrossOrgForbidID {
|
||||
t.Fatalf("denial = level %v policies %v, want instance level with %q", got.Level, got.Policies, access.CrossOrgForbidID)
|
||||
}
|
||||
|
||||
// An org-less principal is denied everything.
|
||||
agentless := p
|
||||
agentless.Org = ""
|
||||
if got := e.Authorize(agentless, access.ActionRead, resource(access.KindBinding, "b1"), access.Context{}); got.Allowed {
|
||||
t.Fatal("org-less principal was allowed")
|
||||
}
|
||||
|
||||
// A create request with no resource org is the principal's own org.
|
||||
create := resource(access.KindBinding, "b1")
|
||||
create.Org = ""
|
||||
if got := e.Authorize(principal(org.RoleDeveloper), access.ActionCreate, create, access.Context{}); !got.Allowed {
|
||||
t.Fatalf("create in own org denied: level=%v policies=%v", got.Level, got.Policies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkspacePolicyCannotWidenOrg(t *testing.T) {
|
||||
// The org forbids run where the workspace is production; a workspace
|
||||
// policy permitting run has no effect.
|
||||
orgPolicies := access.ShippedOrgPolicies(acme)
|
||||
orgPolicies = append(orgPolicies, access.Policy{
|
||||
ID: "org-no-run-production", Level: access.LevelOrg, OrgID: acme,
|
||||
Text: `forbid(principal, action == Archie::Action::"run", resource) when { resource.workspace == "production" };`,
|
||||
})
|
||||
workspace := access.Policy{
|
||||
ID: "ws-allow-run", Level: access.LevelWorkspace, OrgID: acme, WorkspaceID: "production",
|
||||
Text: `permit(principal, action, resource) when { action == Archie::Action::"run" };`,
|
||||
}
|
||||
e := newEngine(t, append(orgPolicies, workspace)...)
|
||||
r := resource(access.KindWorkflow, "implement")
|
||||
r.Workspace = "production"
|
||||
got := e.Authorize(principal(org.RoleDeveloper), access.ActionRun, r, access.Context{})
|
||||
if got.Allowed {
|
||||
t.Fatal("workspace policy widened an org forbid")
|
||||
}
|
||||
if got.Level != access.LevelOrg || got.Policies[0] != "org-no-run-production" {
|
||||
t.Fatalf("denial decided at %v by %v, want the org policy", got.Level, got.Policies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestObjectPolicyNarrows(t *testing.T) {
|
||||
// Only one identity may read the firewall-api secret.
|
||||
socID := identity.IdentityID("33333333-3333-5333-8333-333333333333")
|
||||
object := access.Policy{
|
||||
ID: "secret-soc-only", Level: access.LevelObject, OrgID: acme, WorkspaceID: "net",
|
||||
ObjectKind: access.KindSecret, ObjectID: "firewall-api",
|
||||
Text: `permit(principal, action == Archie::Action::"read_secret", resource) when {
|
||||
principal == Archie::Identity::"` + string(socID) + `"
|
||||
};`,
|
||||
}
|
||||
e := newEngine(t, append(access.ShippedOrgPolicies(acme), object)...)
|
||||
|
||||
// An admin would otherwise read it, but the object level narrows: the
|
||||
// object policy has no permit for this principal, so the level denies.
|
||||
admin := principal(org.RoleAdmin)
|
||||
admin.IdentityID = identity.IdentityID("22222222-2222-5222-8222-222222222222")
|
||||
got := e.Authorize(admin, access.ActionReadSecret, resource(access.KindSecret, "firewall-api"), access.Context{})
|
||||
if got.Allowed {
|
||||
t.Fatal("admin read a secret the object policy narrows away")
|
||||
}
|
||||
if got.Level != access.LevelObject {
|
||||
t.Fatalf("denial decided at %v, want object level", got.Level)
|
||||
}
|
||||
|
||||
soc := admin
|
||||
soc.IdentityID = socID
|
||||
if got := e.Authorize(soc, access.ActionReadSecret, resource(access.KindSecret, "firewall-api"), access.Context{}); !got.Allowed {
|
||||
t.Fatalf("permitted identity denied: level=%v policies=%v", got.Level, got.Policies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidPolicyDeniesItsLevel(t *testing.T) {
|
||||
invalid := access.Policy{
|
||||
ID: "broken-workspace", Level: access.LevelWorkspace, OrgID: acme, WorkspaceID: "net",
|
||||
Text: `permit(principal, action, resource) when { principal.bogus == "x" };`,
|
||||
}
|
||||
e := newEngine(t, append(access.ShippedOrgPolicies(acme), invalid)...)
|
||||
problems := e.Problems()
|
||||
if len(problems) != 1 || problems[0].Policy.ID != "broken-workspace" {
|
||||
t.Fatalf("Problems() = %+v, want one entry for broken-workspace", problems)
|
||||
}
|
||||
if !errors.Is(problems[0].Err, access.ErrPolicyInvalidText) {
|
||||
t.Fatalf("problem err = %v, want ErrPolicyInvalidText", problems[0].Err)
|
||||
}
|
||||
// The workspace level denies everything, even what the org permits.
|
||||
got := e.Authorize(principal(org.RoleOwner), access.ActionRead, resource(access.KindBinding, "b1"), access.Context{})
|
||||
if got.Allowed || got.Level != access.LevelWorkspace {
|
||||
t.Fatalf("level with an invalid policy did not refuse: %+v", got)
|
||||
}
|
||||
if !errors.Is(got.Err, access.ErrPolicyInvalidText) {
|
||||
t.Fatalf("decision err = %v, want ErrPolicyInvalidText", got.Err)
|
||||
}
|
||||
// The denial record names the level's policies.
|
||||
if len(got.Policies) == 0 || got.Policies[0] != "broken-workspace" {
|
||||
t.Fatalf("refusal named %v, want the level's policy", got.Policies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidInstancePolicyStopsServing(t *testing.T) {
|
||||
if _, err := New([]access.Policy{
|
||||
{ID: "broken-instance", Level: access.LevelInstance, Text: `permit(principal, action, resource) when { resource.nope == 1 };`},
|
||||
}); err == nil {
|
||||
t.Fatal("New() accepted an invalid instance policy; archie must stop serving")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRefusesUnknownVocabulary(t *testing.T) {
|
||||
e := newEngine(t)
|
||||
bad := access.Policy{ID: "p1", Level: access.LevelOrg, OrgID: acme, Text: `permit(principal, action, resource) when { resource.wat == "x" };`}
|
||||
if err := e.Validate(bad); !errors.Is(err, access.ErrPolicyInvalidText) {
|
||||
t.Fatalf("Validate(unknown attribute) = %v, want ErrPolicyInvalidText", err)
|
||||
}
|
||||
badText := access.Policy{ID: "p2", Level: access.LevelOrg, OrgID: acme, Text: `permit(principal, action, resource) when { principal.org == 42 };`}
|
||||
if err := e.Validate(badText); !errors.Is(err, access.ErrPolicyInvalidText) {
|
||||
t.Fatalf("Validate(type error) = %v, want ErrPolicyInvalidText", err)
|
||||
}
|
||||
multi := access.Policy{ID: "p3", Level: access.LevelOrg, OrgID: acme, Text: `permit(principal, action, resource); permit(principal, action, resource);`}
|
||||
if err := e.Validate(multi); !errors.Is(err, access.ErrPolicyInvalidText) {
|
||||
t.Fatalf("Validate(multiple policies) = %v, want ErrPolicyInvalidText", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkspaceRoleNarrowsTheOrgRole(t *testing.T) {
|
||||
// A developer org-wide, viewer in the net workspace: read-only there.
|
||||
p := principal(org.RoleDeveloper)
|
||||
p.Memberships = append(p.Memberships, org.Membership{IdentityID: p.IdentityID, OrgID: acme, WorkspaceID: "net", Role: org.RoleViewer})
|
||||
e := newEngine(t, access.ShippedOrgPolicies(acme)...)
|
||||
if got := e.Authorize(p, access.ActionRead, resource(access.KindBinding, "b1"), access.Context{}); !got.Allowed {
|
||||
t.Fatalf("viewer-in-workspace denied a read: %+v", got)
|
||||
}
|
||||
if got := e.Authorize(p, access.ActionCreate, resource(access.KindBinding, "b1"), access.Context{}); got.Allowed {
|
||||
t.Fatal("workspace viewer role did not narrow the org-wide developer role")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDenialNamesDecidingPolicies(t *testing.T) {
|
||||
e := newEngine(t, access.ShippedOrgPolicies(acme)...)
|
||||
// A viewer denied create is decided by the org level, whose only
|
||||
// policies are the shipped role set.
|
||||
got := e.Authorize(principal(org.RoleViewer), access.ActionCreate, resource(access.KindBinding, "b1"), access.Context{})
|
||||
if got.Level != access.LevelOrg {
|
||||
t.Fatalf("level = %v, want org", got.Level)
|
||||
}
|
||||
for _, id := range got.Policies {
|
||||
if id != access.PolicyOrgRead && id != access.PolicyOrgEdit && id != access.PolicyOrgAdmin && id != access.PolicyOrgOwner {
|
||||
t.Fatalf("denial names an unknown policy %q", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
package agentboot
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/container"
|
||||
)
|
||||
|
||||
func bootGitDir(t *testing.T) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(dir, ".git"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
func TestTaskIDRequiresValidDedicatedTaskMetadata(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
payload []byte
|
||||
write bool
|
||||
wantID int64
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "absent fails closed", wantErr: true},
|
||||
{name: "valid selects task", payload: mustTaskPayload(t, container.TaskPayload{ID: 42}), write: true, wantID: 42},
|
||||
{name: "malformed fails closed", payload: []byte("not json"), write: true, wantErr: true},
|
||||
{name: "zero ID fails closed", payload: mustTaskPayload(t, container.TaskPayload{}), write: true, wantErr: true},
|
||||
{name: "negative ID fails closed", payload: mustTaskPayload(t, container.TaskPayload{ID: -1}), write: true, wantErr: true},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
dir := bootGitDir(t)
|
||||
if test.write {
|
||||
if err := os.WriteFile(filepath.Join(dir, ".git", "task.json"), test.payload, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
id, err := TaskID(dir)
|
||||
if (err != nil) != test.wantErr {
|
||||
t.Fatalf("TaskID() error = %v, wantErr %v", err, test.wantErr)
|
||||
}
|
||||
if id != test.wantID {
|
||||
t.Fatalf("TaskID() ID = %d, want %d", id, test.wantID)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskIDFailsClosedOnNonMissingReadError(t *testing.T) {
|
||||
dir := bootGitDir(t)
|
||||
path := filepath.Join(dir, ".git", "task.json")
|
||||
if err := os.Mkdir(path, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
id, err := TaskID(dir)
|
||||
if err == nil {
|
||||
t.Fatal("TaskID() error = nil for unreadable task.json path")
|
||||
}
|
||||
if id != 0 {
|
||||
t.Fatalf("TaskID() ID = %d, want 0", id)
|
||||
}
|
||||
}
|
||||
|
||||
func mustTaskPayload(t *testing.T, payload container.TaskPayload) []byte {
|
||||
t.Helper()
|
||||
data, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return data
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
package agentgit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMarkWorktreeSafe(t *testing.T) {
|
||||
log := slog.New(slog.DiscardHandler)
|
||||
|
||||
present := func(t *testing.T) string { t.Helper(); return t.TempDir() }
|
||||
absent := func(t *testing.T) string { t.Helper(); return t.TempDir() + "/never-mounted" }
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
mountDir func(t *testing.T) string
|
||||
runErr error
|
||||
want bool
|
||||
wantRuns int
|
||||
}{
|
||||
{
|
||||
name: "configures git when the worktree is mounted",
|
||||
mountDir: present,
|
||||
want: true,
|
||||
wantRuns: 1,
|
||||
},
|
||||
{
|
||||
name: "git failure is best-effort",
|
||||
mountDir: present,
|
||||
runErr: errors.New("exit status 1"),
|
||||
want: false,
|
||||
wantRuns: 1,
|
||||
},
|
||||
{
|
||||
name: "git missing is best-effort",
|
||||
mountDir: present,
|
||||
runErr: errors.New(`exec: "git": executable file not found in $PATH`),
|
||||
want: false,
|
||||
wantRuns: 1,
|
||||
},
|
||||
{
|
||||
name: "no mounted worktree leaves git config untouched",
|
||||
mountDir: absent,
|
||||
want: false,
|
||||
wantRuns: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := tc.mountDir(t)
|
||||
var runs [][]string
|
||||
run := func(_ context.Context, args ...string) ([]byte, error) {
|
||||
runs = append(runs, args)
|
||||
return []byte("output"), tc.runErr
|
||||
}
|
||||
|
||||
got := markSafe(context.Background(), dir, run, log)
|
||||
|
||||
if got != tc.want {
|
||||
t.Fatalf("markSafe() = %v, want %v", got, tc.want)
|
||||
}
|
||||
if len(runs) != tc.wantRuns {
|
||||
t.Fatalf("git invoked %d times, want %d (%v)", len(runs), tc.wantRuns, runs)
|
||||
}
|
||||
if tc.wantRuns == 0 {
|
||||
return
|
||||
}
|
||||
wantArgs := []string{"config", "--global", "--add", "safe.directory", dir}
|
||||
if !reflect.DeepEqual(runs[0], wantArgs) {
|
||||
t.Fatalf("git args = %v, want %v", runs[0], wantArgs)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The guard markSafe applies is existence, not mount-ness: a directory that
|
||||
// merely exists at mountDir -- a stale leftover from a prior run, never
|
||||
// actually bind-mounted this time -- still satisfies os.Stat and gets
|
||||
// configured. This is the documented, accepted behavior (see markSafe's
|
||||
// doc comment): a real mount check would need platform-specific mountinfo
|
||||
// parsing, and the resulting stale safe.directory entry is inert unless a
|
||||
// git repository later exists at that exact path. This test pins the
|
||||
// current contract so a future change to it is a deliberate decision, not
|
||||
// a silent regression either way.
|
||||
func TestMarkWorktreeSafeAcceptsAnExistingButUnmountedDirectory(t *testing.T) {
|
||||
dir := t.TempDir() // exists on disk; nothing bind-mounted it here
|
||||
|
||||
var runs [][]string
|
||||
run := func(_ context.Context, args ...string) ([]byte, error) {
|
||||
runs = append(runs, args)
|
||||
return []byte("output"), nil
|
||||
}
|
||||
|
||||
if got := markSafe(context.Background(), dir, run, slog.New(slog.DiscardHandler)); !got {
|
||||
t.Fatal("markSafe() = false for an existing (if unmounted) directory, want true per the documented existence-based guard")
|
||||
}
|
||||
if len(runs) != 1 {
|
||||
t.Fatalf("git invoked %d times, want 1", len(runs))
|
||||
}
|
||||
}
|
||||
|
||||
// A mount path that is a file, not a directory, is not a worktree: git must
|
||||
// not be reconfigured for it.
|
||||
func TestMarkWorktreeSafeIgnoresNonDirectory(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
file := filepath.Join(dir, "worktree")
|
||||
if err := os.WriteFile(file, []byte("not a worktree"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
invoked := false
|
||||
run := func(_ context.Context, _ ...string) ([]byte, error) {
|
||||
invoked = true
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if got := markSafe(context.Background(), file, run, slog.New(slog.DiscardHandler)); got {
|
||||
t.Fatal("markSafe() = true for a non-directory mount path, want false")
|
||||
}
|
||||
if invoked {
|
||||
t.Fatal("git was invoked for a non-directory mount path")
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package nats
|
||||
|
||||
import (
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestInfrastructureDoesNotImportApplication(t *testing.T) {
|
||||
files, err := filepath.Glob("*.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, path := range files {
|
||||
if strings.HasSuffix(path, "_test.go") {
|
||||
continue
|
||||
}
|
||||
file, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, imported := range file.Imports {
|
||||
name, err := strconv.Unquote(imported.Path.Value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(name, "/internal/app/") {
|
||||
t.Errorf("%s imports application package %q", path, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,314 +0,0 @@
|
||||
package nats
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
natstest "github.com/nats-io/nats-server/v2/test"
|
||||
natsio "github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/forgerpc"
|
||||
"github.com/samcharles93/archie-core/internal/taskrun"
|
||||
"github.com/samcharles93/archie-core/internal/worktreerpc"
|
||||
)
|
||||
|
||||
const testDefinition = "id: implement\nsteps: []\n"
|
||||
|
||||
func TestTransportContainsNoSharedTaskWorkerTopology(t *testing.T) {
|
||||
source, err := os.ReadFile("transport.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, forbidden := range []string{"QueueSubscribe", "taskRunSubjectWildcard", "taskRunQueueGroup"} {
|
||||
if strings.Contains(string(source), forbidden) {
|
||||
t.Errorf("transport.go contains forbidden shared-worker mechanism %q", forbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testTransport(t *testing.T) (*Transport, *natsio.Conn) {
|
||||
t.Helper()
|
||||
srv := natstest.RunRandClientPortServer()
|
||||
t.Cleanup(srv.Shutdown)
|
||||
conn, err := natsio.Connect(srv.ClientURL())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(conn.Close)
|
||||
return &Transport{conn: conn}, conn
|
||||
}
|
||||
|
||||
func TestTaskRunSubjectOwnsCanonicalNATSTopology(t *testing.T) {
|
||||
if got := SubjectForTask(42); got != "archie.taskrun.42" {
|
||||
t.Fatalf("SubjectForTask(42) = %q", got)
|
||||
}
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
subject string
|
||||
wantID int64
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "canonical", subject: "archie.taskrun.42", wantID: 42},
|
||||
{name: "missing prefix", subject: "taskrun.42", wantErr: true},
|
||||
{name: "missing ID", subject: "archie.taskrun.", wantErr: true},
|
||||
{name: "nondecimal", subject: "archie.taskrun.any", wantErr: true},
|
||||
{name: "zero", subject: "archie.taskrun.0", wantErr: true},
|
||||
{name: "negative", subject: "archie.taskrun.-1", wantErr: true},
|
||||
{name: "noncanonical leading zero", subject: "archie.taskrun.042", wantErr: true},
|
||||
{name: "extra token", subject: "archie.taskrun.42.extra", wantErr: true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got, err := taskIDFromSubject(test.subject)
|
||||
if test.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("taskIDFromSubject(%q) = %d, want error", test.subject, got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || got != test.wantID {
|
||||
t.Fatalf("taskIDFromSubject(%q) = (%d, %v), want (%d, nil)", test.subject, got, err, test.wantID)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Full-task handoff and all worker RPC use core NATS. The worker must connect
|
||||
// to a broker with JetStream disabled; requiring a durable consumer would mean
|
||||
// the deleted per-stage transport still owns startup. The State Store target
|
||||
// is a separate gRPC connection, not a NATS feature, so it is supplied here
|
||||
// too (it does not need to be reachable -- grpc.NewClient is lazy).
|
||||
func TestConnectRequiresOnlyCoreNATS(t *testing.T) {
|
||||
srv := natstest.RunServer(&server.Options{Port: -1, Authorization: "worker-secret"})
|
||||
t.Cleanup(srv.Shutdown)
|
||||
|
||||
transport, err := Connect(t.Context(), Config{URL: srv.ClientURL(), Token: "worker-secret", StateStoreURL: "127.0.0.1:9999"}, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatalf("Connect to core-only NATS: %v", err)
|
||||
}
|
||||
transport.Close()
|
||||
}
|
||||
|
||||
func TestSubscribeTasksServesOnlyBootTaskSubject(t *testing.T) {
|
||||
transport, conn := testTransport(t)
|
||||
calls := 0
|
||||
subscription, err := transport.SubscribeTasks(t.Context(), 42, func(_ context.Context, request taskrun.Request) (*taskrun.Response, error) {
|
||||
calls++
|
||||
if request.Task.ID != 42 {
|
||||
t.Fatalf("task ID = %d, want 42", request.Task.ID)
|
||||
}
|
||||
return &taskrun.Response{Status: "done"}, nil
|
||||
}, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = subscription.Close() })
|
||||
|
||||
payload, err := json.Marshal(taskrun.Request{Task: &workflow.Task{ID: 42}, WorktreeGrant: "grant", WorkflowDefinition: testDefinition})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
message, err := conn.Request(SubjectForTask(42), payload, time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var response taskrun.Response
|
||||
if err := json.Unmarshal(message.Data, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 1 || response.Status != "done" {
|
||||
t.Fatalf("handler/response = (%d, %q), want (1, done)", calls, response.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubscribeTasksOwnsWireErrors(t *testing.T) {
|
||||
transport, conn := testTransport(t)
|
||||
handlerCalls := 0
|
||||
subscription, err := transport.SubscribeTasks(t.Context(), 9, func(context.Context, taskrun.Request) (*taskrun.Response, error) {
|
||||
handlerCalls++
|
||||
return nil, errors.New("run failed")
|
||||
}, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = subscription.Close() })
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
payload []byte
|
||||
want string
|
||||
wantHandlerCalls int
|
||||
}{
|
||||
{name: "decode", payload: []byte("not json"), want: "decode taskrun request:"},
|
||||
{name: "missing task", payload: []byte(`{}`), want: "validate taskrun request: task is required"},
|
||||
{name: "null task", payload: []byte(`{"task":null}`), want: "validate taskrun request: task is required"},
|
||||
{name: "nonpositive task ID", payload: []byte(`{"task":{"id":0}}`), want: "validate taskrun request: task ID must be positive, got 0"},
|
||||
{name: "missing worktree grant", payload: []byte(`{"task":{"id":9,"owner":"acme","repo":"api"}}`), want: "validate taskrun request: worktree grant is required"},
|
||||
{name: "missing workflow definition", payload: []byte(`{"task":{"id":9},"worktree_grant":"grant"}`), want: "validate taskrun request: workflow definition is required"},
|
||||
{name: "payload subject mismatch", payload: []byte(`{"task":{"id":8},"worktree_grant":"grant","workflow_definition":"id: implement\nsteps: []\n"}`), want: "validate taskrun request: task ID 8 does not match subject task ID 9"},
|
||||
{name: "handler", payload: []byte(`{"task":{"id":9},"worktree_grant":"grant","workflow_definition":"id: implement\nsteps: []\n"}`), want: "run failed", wantHandlerCalls: 1},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
before := handlerCalls
|
||||
message, err := conn.Request(SubjectForTask(9), test.payload, time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var response taskrun.Response
|
||||
if err := json.Unmarshal(message.Data, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Error == "" || !strings.Contains(response.Error, test.want) {
|
||||
t.Fatalf("response error = %q, want containing %q", response.Error, test.want)
|
||||
}
|
||||
if got := handlerCalls - before; got != test.wantHandlerCalls {
|
||||
t.Fatalf("handler calls = %d, want %d", got, test.wantHandlerCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleTaskRejectsSubjectCorrelationErrors(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
subject string
|
||||
bootTaskID int64
|
||||
requestID int64
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "malformed subject",
|
||||
subject: "archie.taskrun.invalid",
|
||||
requestID: 7,
|
||||
want: `validate taskrun request: invalid taskrun subject "archie.taskrun.invalid"`,
|
||||
},
|
||||
{
|
||||
name: "boot mismatch",
|
||||
subject: SubjectForTask(9),
|
||||
bootTaskID: 42,
|
||||
requestID: 9,
|
||||
want: "validate taskrun request: task ID 9 does not match boot task ID 42",
|
||||
},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
transport, conn := testTransport(t)
|
||||
handlerCalls := 0
|
||||
subscription, err := conn.Subscribe(test.subject, func(message *natsio.Msg) {
|
||||
transport.handleTask(t.Context(), message, test.bootTaskID, func(context.Context, taskrun.Request) (*taskrun.Response, error) {
|
||||
handlerCalls++
|
||||
return &taskrun.Response{Status: "unexpected"}, nil
|
||||
}, slog.New(slog.DiscardHandler))
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = subscription.Unsubscribe() })
|
||||
if err := conn.Flush(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
payload, err := json.Marshal(taskrun.Request{Task: &workflow.Task{ID: test.requestID}, WorktreeGrant: "grant", WorkflowDefinition: testDefinition})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
message, err := conn.Request(test.subject, payload, time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var response taskrun.Response
|
||||
if err := json.Unmarshal(message.Data, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Error != test.want {
|
||||
t.Fatalf("response error = %q, want %q", response.Error, test.want)
|
||||
}
|
||||
if handlerCalls != 0 {
|
||||
t.Fatalf("handler calls = %d, want 0", handlerCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type recordingSDKSubscription struct {
|
||||
unsubscribeCalls int
|
||||
unsubscribeErr error
|
||||
}
|
||||
|
||||
func (s *recordingSDKSubscription) Unsubscribe() error {
|
||||
s.unsubscribeCalls++
|
||||
return s.unsubscribeErr
|
||||
}
|
||||
|
||||
func TestSubscribeTasksReportsSetupFailuresAndCleansUpFlushFailure(t *testing.T) {
|
||||
subscribeErr := errors.New("subscribe failed")
|
||||
flushErr := errors.New("flush failed")
|
||||
cleanupErr := errors.New("unsubscribe failed")
|
||||
tests := []struct {
|
||||
name string
|
||||
subscribeErr error
|
||||
flushErr error
|
||||
cleanupErr error
|
||||
wantErr error
|
||||
wantUnsubscribes int
|
||||
wantCleanupLog bool
|
||||
}{
|
||||
{name: "direct subscribe", subscribeErr: subscribeErr, wantErr: subscribeErr},
|
||||
{name: "flush cleanup succeeds", flushErr: flushErr, wantErr: flushErr, wantUnsubscribes: 1},
|
||||
{name: "flush cleanup fails", flushErr: flushErr, cleanupErr: cleanupErr, wantErr: flushErr, wantUnsubscribes: 1, wantCleanupLog: true},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
sub := &recordingSDKSubscription{unsubscribeErr: test.cleanupErr}
|
||||
transport := &Transport{
|
||||
subscribe: func(string, natsio.MsgHandler) (sdkSubscription, error) {
|
||||
return sub, test.subscribeErr
|
||||
},
|
||||
flush: func(timeout time.Duration) error {
|
||||
if timeout != taskSubscriptionFlushTimeout {
|
||||
t.Fatalf("flush timeout = %s, want %s", timeout, taskSubscriptionFlushTimeout)
|
||||
}
|
||||
return test.flushErr
|
||||
},
|
||||
}
|
||||
var output bytes.Buffer
|
||||
_, err := transport.SubscribeTasks(t.Context(), 42, func(context.Context, taskrun.Request) (*taskrun.Response, error) {
|
||||
t.Fatal("handler called")
|
||||
return nil, nil
|
||||
}, slog.New(slog.NewTextHandler(&output, nil)))
|
||||
if !errors.Is(err, test.wantErr) {
|
||||
t.Fatalf("error = %v, want %v", err, test.wantErr)
|
||||
}
|
||||
if sub.unsubscribeCalls != test.wantUnsubscribes {
|
||||
t.Fatalf("unsubscribe calls = %d, want %d", sub.unsubscribeCalls, test.wantUnsubscribes)
|
||||
}
|
||||
if got := strings.Contains(output.String(), "task subscription cleanup failed after flush failure"); got != test.wantCleanupLog {
|
||||
t.Fatalf("cleanup warning logged = %v, want %v; output %q", got, test.wantCleanupLog, output.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRPCFactoriesPreserveIdentityAndTimeout(t *testing.T) {
|
||||
transport, _ := testTransport(t)
|
||||
timeout := 60 * time.Second
|
||||
forgeClient, ok := transport.Forger("identity-a", timeout).(*forgerpc.Client)
|
||||
if !ok || forgeClient.Identity != "identity-a" || forgeClient.Timeout != timeout {
|
||||
t.Fatalf("forge client = %#v", forgeClient)
|
||||
}
|
||||
if store := transport.Store(timeout); store == nil {
|
||||
t.Fatal("store client = nil, want a non-nil workflow.Store")
|
||||
}
|
||||
treeClient, ok := transport.Trees("identity-a", "grant-a", timeout).(*worktreerpc.Client)
|
||||
if !ok || treeClient.Identity != "identity-a" || treeClient.Grant != "grant-a" || treeClient.Timeout != timeout {
|
||||
t.Fatalf("tree client = %#v", treeClient)
|
||||
}
|
||||
}
|
||||
@@ -1,159 +0,0 @@
|
||||
package artifactsync
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func sampleArtifact() Artifact {
|
||||
return Artifact{
|
||||
Title: "Review of PR #7",
|
||||
Source: "# Review\n\none finding, one check",
|
||||
Meta: Meta{
|
||||
Format: "markdown",
|
||||
Category: "pr-review",
|
||||
Visibility: "account-only",
|
||||
Egress: "none",
|
||||
Actor: "system:pr-reviewer",
|
||||
Origin: "pr-review",
|
||||
RequestID: "artifact:pr-review:acme/widget#7",
|
||||
Version: "r1",
|
||||
SentAt: time.Date(2026, 9, 22, 16, 45, 0, 0, time.UTC),
|
||||
Task: &Task{Owner: "acme", Repo: "widget", Number: 7},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishPostsTheContractBody(t *testing.T) {
|
||||
var gotPath, gotAuth string
|
||||
var gotBody map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotPath, gotAuth = r.URL.Path, r.Header.Get("Authorization")
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
_ = json.Unmarshal(body, &gotBody)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_, _ = w.Write([]byte(`{"ok":true,"id":"a_1","url":"https://offloaded.dev/collab?document=a_1"}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := NewClient(srv.URL, "secret-token")
|
||||
url, err := c.Publish(context.Background(), sampleArtifact())
|
||||
if err != nil {
|
||||
t.Fatalf("Publish: %v", err)
|
||||
}
|
||||
if url != "https://offloaded.dev/collab?document=a_1" {
|
||||
t.Fatalf("url = %q, want the editor deep link", url)
|
||||
}
|
||||
if gotPath != "/api/artifacts" {
|
||||
t.Fatalf("path = %q, want /api/artifacts", gotPath)
|
||||
}
|
||||
if gotAuth != "Bearer secret-token" {
|
||||
t.Fatalf("Authorization = %q, want the bearer token", gotAuth)
|
||||
}
|
||||
if gotBody["format"] != "offloaded-collab-artifact" {
|
||||
t.Fatalf("top-level format = %v, want the contract envelope", gotBody["format"])
|
||||
}
|
||||
if gotBody["title"] != "Review of PR #7" || gotBody["source"] != sampleArtifact().Source {
|
||||
t.Fatalf("title/source did not round-trip: %v", gotBody)
|
||||
}
|
||||
artifact, ok := gotBody["artifact"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("artifact block missing: %v", gotBody)
|
||||
}
|
||||
if artifact["format"] != "markdown" || artifact["category"] != "pr-review" {
|
||||
t.Fatalf("artifact format/category = %v", artifact)
|
||||
}
|
||||
if artifact["actor"] != "system:pr-reviewer" || artifact["source"] != "pr-review" {
|
||||
t.Fatalf("attribution = %v", artifact)
|
||||
}
|
||||
if artifact["requestId"] != "artifact:pr-review:acme/widget#7" || artifact["version"] != "r1" {
|
||||
t.Fatalf("idempotency fields = %v", artifact)
|
||||
}
|
||||
if artifact["visibility"] != "account-only" || artifact["egress"] != "none" {
|
||||
t.Fatalf("visibility/egress = %v", artifact)
|
||||
}
|
||||
task, ok := artifact["task"].(map[string]any)
|
||||
if !ok || task["owner"] != "acme" || task["repo"] != "widget" {
|
||||
t.Fatalf("task coordinates = %v", artifact["task"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishDoesNotRetryAClientError(t *testing.T) {
|
||||
for _, status := range []int{http.StatusUnauthorized, http.StatusBadRequest} {
|
||||
var attempts atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
attempts.Add(1)
|
||||
w.WriteHeader(status)
|
||||
_, _ = w.Write([]byte(`{"error":"source is required"}`))
|
||||
}))
|
||||
_, err := NewClient(srv.URL, "tok").Publish(context.Background(), sampleArtifact())
|
||||
srv.Close()
|
||||
if err == nil {
|
||||
t.Fatalf("status %d: Publish error = nil, want failure", status)
|
||||
}
|
||||
if attempts.Load() != 1 {
|
||||
t.Fatalf("status %d attempts = %d, want exactly one attempt", status, attempts.Load())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishSurfacesTheFieldReasonOn400(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"error":"source is required"}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
_, err := NewClient(srv.URL, "tok").Publish(context.Background(), sampleArtifact())
|
||||
if err == nil || !strings.Contains(err.Error(), "source is required") {
|
||||
t.Fatalf("error = %v, want it to carry the field reason", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishRetries503UntilSuccess(t *testing.T) {
|
||||
var attempts atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if attempts.Add(1) < 3 {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_, _ = w.Write([]byte(`{"ok":true,"id":"a_2","url":"u"}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := NewClient(srv.URL, "tok")
|
||||
c.wait = time.Millisecond
|
||||
url, err := c.Publish(context.Background(), sampleArtifact())
|
||||
if err != nil || url != "u" {
|
||||
t.Fatalf("Publish = (%q, %v), want success after two 503s", url, err)
|
||||
}
|
||||
if attempts.Load() != 3 {
|
||||
t.Fatalf("attempts = %d, want 3", attempts.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishFailsWhen503Persists(t *testing.T) {
|
||||
var attempts atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
attempts.Add(1)
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := NewClient(srv.URL, "tok")
|
||||
c.wait = time.Millisecond
|
||||
if _, err := c.Publish(context.Background(), sampleArtifact()); err == nil {
|
||||
t.Fatal("Publish error = nil, want failure after exhausting retries")
|
||||
}
|
||||
if attempts.Load() != 4 {
|
||||
t.Fatalf("attempts = %d, want the initial attempt plus three retries", attempts.Load())
|
||||
}
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
package bindingcipher
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// testBindingKey is high-entropy 32-byte-style material for cipher tests. It
|
||||
// must be split across the fingerprint and key derivation consistently.
|
||||
const testBindingKey = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
|
||||
|
||||
func TestBindingCipherRoundTrip(t *testing.T) {
|
||||
c, err := NewBindingCipher(testBindingKey, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher: %v", err)
|
||||
}
|
||||
plain := "sentry-hmac-secret-0123456789abcdef"
|
||||
env, err := c.Encrypt(plain)
|
||||
if err != nil {
|
||||
t.Fatalf("Encrypt: %v", err)
|
||||
}
|
||||
if env == plain {
|
||||
t.Fatal("Encrypt returned the plaintext")
|
||||
}
|
||||
if !strings.HasPrefix(env, "arcie-binding:v1:") {
|
||||
t.Fatalf("envelope prefix = %q, want arcie-binding:v1:", env)
|
||||
}
|
||||
got, err := c.Decrypt(env)
|
||||
if err != nil {
|
||||
t.Fatalf("Decrypt: %v", err)
|
||||
}
|
||||
if got != plain {
|
||||
t.Fatalf("round-trip = %q, want %q", got, plain)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBindingCipherWrongKeyFails(t *testing.T) {
|
||||
c, _ := NewBindingCipher(testBindingKey, nil)
|
||||
env, err := c.Encrypt("secret-0123456789abcdef")
|
||||
if err != nil {
|
||||
t.Fatalf("Encrypt: %v", err)
|
||||
}
|
||||
c2, _ := NewBindingCipher("a-completely-different-key-0000000000000000", nil)
|
||||
if _, err := c2.Decrypt(env); err == nil {
|
||||
t.Fatal("Decrypt with the wrong key succeeded, want error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBindingCipherTamperedCiphertextFails(t *testing.T) {
|
||||
c, _ := NewBindingCipher(testBindingKey, nil)
|
||||
env, err := c.Encrypt("secret-0123456789abcdef")
|
||||
if err != nil {
|
||||
t.Fatalf("Encrypt: %v", err)
|
||||
}
|
||||
tampered := tamperEnvelope(t, env)
|
||||
if _, err := c.Decrypt(tampered); err == nil {
|
||||
t.Fatal("Decrypt of tampered envelope succeeded, want authentication error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBindingCipherUnrecognisedEnvelopeFails(t *testing.T) {
|
||||
c, _ := NewBindingCipher(testBindingKey, nil)
|
||||
for _, bad := range []string{"", "not-an-envelope", "arcie-binding:v2:deadbeef:AAAA"} {
|
||||
if _, err := c.Decrypt(bad); err == nil {
|
||||
t.Errorf("Decrypt(%q) succeeded, want error", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBindingCipherKeyNotInKeyringFails(t *testing.T) {
|
||||
c, _ := NewBindingCipher("key-0-material-0000000000000000", nil)
|
||||
env, err := c.Encrypt("secret-0123456789abcdef")
|
||||
if err != nil {
|
||||
t.Fatalf("Encrypt: %v", err)
|
||||
}
|
||||
// A keyring without the sealing key cannot decrypt the row.
|
||||
c2, _ := NewBindingCipher(testBindingKey, nil)
|
||||
if _, err := c2.Decrypt(env); err == nil {
|
||||
t.Fatal("Decrypt via a keyring missing the sealing key succeeded, want error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBindingCipherRotationKeepsOldRowsReadable(t *testing.T) {
|
||||
oldKey := "old-key-material-000000000000000000000000"
|
||||
cOld, _ := NewBindingCipher(oldKey, nil)
|
||||
env, err := cOld.Encrypt("secret-0123456789abcdef")
|
||||
if err != nil {
|
||||
t.Fatalf("Encrypt (old): %v", err)
|
||||
}
|
||||
|
||||
// Rotate: active becomes a new key, old is retained for reads.
|
||||
cNew, err := NewBindingCipher(testBindingKey, []string{oldKey})
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher (rotated): %v", err)
|
||||
}
|
||||
got, err := cNew.Decrypt(env)
|
||||
if err != nil {
|
||||
t.Fatalf("Decrypt old row under rotated keyring: %v", err)
|
||||
}
|
||||
if got != "secret-0123456789abcdef" {
|
||||
t.Fatalf("rotated decrypt = %q", got)
|
||||
}
|
||||
|
||||
// Once the old key is dropped, the old row is unreadable.
|
||||
cDropped, _ := NewBindingCipher(testBindingKey, nil)
|
||||
if _, err := cDropped.Decrypt(env); err == nil {
|
||||
t.Fatal("Decrypt with rotated-out keyring succeeded, want error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBindingCipherDerivesDistinctKeys(t *testing.T) {
|
||||
a, _ := NewBindingCipher("material-A", nil)
|
||||
b, _ := NewBindingCipher("material-B", nil)
|
||||
if a.activeFingerprint == b.activeFingerprint {
|
||||
t.Fatal("distinct materials produced the same fingerprint")
|
||||
}
|
||||
if string(a.activeKey) == string(b.activeKey) {
|
||||
t.Fatal("distinct materials produced the same derived key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDomainSeparationRejectsRelocation(t *testing.T) {
|
||||
c, _ := NewBindingCipher(testBindingKey, nil)
|
||||
plain := "refresh-token-0123456789abcdef"
|
||||
env, err := c.EncryptDomain(HarnessSecretDomain, plain)
|
||||
if err != nil {
|
||||
t.Fatalf("EncryptDomain: %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(env, "arcie-harness:v1:") {
|
||||
t.Fatalf("envelope prefix = %q, want arcie-harness:v1:", env)
|
||||
}
|
||||
// The envelope sealed for HarnessSecretDomain must not authenticate
|
||||
// under BindingDomain's AAD, even with the same keyring: a row moved
|
||||
// from oauth_secrets into a bindings-secret column must not decrypt.
|
||||
if _, err := c.Decrypt(env); err == nil {
|
||||
t.Fatal("Decrypt (BindingDomain) of a HarnessSecretDomain envelope succeeded, want error")
|
||||
}
|
||||
got, err := c.DecryptDomain(HarnessSecretDomain, env)
|
||||
if err != nil {
|
||||
t.Fatalf("DecryptDomain: %v", err)
|
||||
}
|
||||
if got != plain {
|
||||
t.Fatalf("round-trip = %q, want %q", got, plain)
|
||||
}
|
||||
}
|
||||
|
||||
// tamperEnvelope flips one byte inside the ciphertext region so Decrypt must
|
||||
// fail authentication rather than return altered plaintext.
|
||||
func tamperEnvelope(t *testing.T, envelope string) string {
|
||||
t.Helper()
|
||||
parts := strings.SplitN(envelope, ":", 4)
|
||||
if len(parts) != 4 {
|
||||
t.Fatalf("unexpected envelope: %q", envelope)
|
||||
}
|
||||
raw, err := base64.RawURLEncoding.DecodeString(parts[3])
|
||||
if err != nil {
|
||||
t.Fatalf("decode payload: %v", err)
|
||||
}
|
||||
// Flip a byte in the ciphertext region (not the nonce).
|
||||
idx := 12
|
||||
if len(raw) <= idx {
|
||||
t.Fatalf("payload too short to tamper: %d bytes", len(raw))
|
||||
}
|
||||
raw[idx] ^= 0x01
|
||||
parts[3] = base64.RawURLEncoding.EncodeToString(raw)
|
||||
return strings.Join(parts, ":")
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package captureintake
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
@@ -1,453 +0,0 @@
|
||||
package captureintake
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/webhookguard"
|
||||
)
|
||||
|
||||
// recordingPublisher captures every event.Publish call so a test can assert
|
||||
// a capture reached the live SSE pipeline without standing up a real
|
||||
// streaming HTTP connection.
|
||||
type recordingPublisher struct {
|
||||
published []events.Event
|
||||
}
|
||||
|
||||
func (r *recordingPublisher) Publish(_ context.Context, e events.Event) {
|
||||
r.published = append(r.published, e)
|
||||
}
|
||||
|
||||
// testReceiver builds a Receiver over a real store, so tests assert on the
|
||||
// rows a capture actually persisted rather than on a mock's recollection.
|
||||
// srv keeps the same handle, since ListCaptures reads back what the receiver
|
||||
// wrote.
|
||||
type testReceiver struct {
|
||||
*Receiver
|
||||
// store is the event-capture store the receiver writes through, kept so a
|
||||
// test asserts on persisted rows rather than on a mock's recollection.
|
||||
store *postgres.EDA
|
||||
}
|
||||
|
||||
// Handler serves the receiver's route the way its host process mounts it,
|
||||
// so path parsing and method routing are exercised, not bypassed.
|
||||
func (r testReceiver) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
r.Register(mux)
|
||||
return mux
|
||||
}
|
||||
|
||||
// captureTestServerWithoutStore builds a Receiver with no capture storage,
|
||||
// for the "capture not configured" degradation: the route still answers, but
|
||||
// with 503 rather than persisting a row.
|
||||
func captureTestServerWithoutStore(t *testing.T) testReceiver {
|
||||
t.Helper()
|
||||
return testReceiver{Receiver: &Receiver{Log: slog.New(slog.DiscardHandler)}}
|
||||
}
|
||||
|
||||
func captureTestServer(t *testing.T) testReceiver {
|
||||
t.Helper()
|
||||
s := pgstore.EDA(t, nil)
|
||||
return testReceiver{
|
||||
Receiver: &Receiver{
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Captures: s,
|
||||
MaxBodyBytes: 1024,
|
||||
Retention: 7 * 24 * time.Hour,
|
||||
MaxEvents: 100,
|
||||
Limiter: webhookguard.NewRateLimiter(1000, 1000, time.Now),
|
||||
},
|
||||
store: s,
|
||||
}
|
||||
}
|
||||
|
||||
// hmacSHA256 returns the GitHub-style "sha256=<hex>" signature for body
|
||||
// under secret, the same form webhookguard.VerifyHMAC accepts.
|
||||
func hmacSHA256(secret, body string) string {
|
||||
mac := hmac.New(sha256.New, []byte(secret))
|
||||
mac.Write([]byte(body))
|
||||
return "sha256=" + hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
func TestHandleCaptureStoresRedactedBody(t *testing.T) {
|
||||
srv := captureTestServer(t)
|
||||
body := `{"action":"opened","sender":{"token":"shh-secret"}}`
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusAccepted, w.Body.String())
|
||||
}
|
||||
got, err := srv.store.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures: %v", err)
|
||||
}
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("captured rows = %d, want 1", len(got))
|
||||
}
|
||||
c := got[0]
|
||||
if c.Source != "github" {
|
||||
t.Errorf("Source = %q, want %q", c.Source, "github")
|
||||
}
|
||||
if c.ContentType != "application/json" {
|
||||
t.Errorf("ContentType = %q, want application/json", c.ContentType)
|
||||
}
|
||||
if strings.Contains(c.Body, "shh-secret") {
|
||||
t.Errorf("Body = %q, want the token value redacted", c.Body)
|
||||
}
|
||||
if !strings.Contains(c.Body, `"action":"opened"`) {
|
||||
t.Errorf("Body = %q, want the non-sensitive field preserved", c.Body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleCapturePublishesLiveEventOnSuccess pins the "no manual refresh"
|
||||
// acceptance criterion's actual mechanism: a successful capture must reach
|
||||
// the host process's event pipeline with Kind "capture" so the dashboard's
|
||||
// event inspector knows to refetch. This does not open a real SSE
|
||||
// connection -- it asserts what the receiver hands to its Publish hook,
|
||||
// which is the part this package adds; persistence and fan-out are the
|
||||
// host process's pipeline (the daemon's bus drain), already tested there.
|
||||
//
|
||||
// The published event is deliberately LIGHTWEIGHT (id + source only, no
|
||||
// body/headers): the events table this feeds (the State Store events table) has
|
||||
// no retention or row-count prune, unlike captured_events, so embedding the
|
||||
// full (up to CaptureMaxBodyBytes) payload here would duplicate it into an
|
||||
// unbounded table and defeat the disk-bound guarantee InsertCapture's own
|
||||
// prune-on-write exists to provide. See docs/prds/event-capture-storage.md.
|
||||
func TestHandleCapturePublishesLiveEventOnSuccess(t *testing.T) {
|
||||
srv := captureTestServer(t)
|
||||
pub := &recordingPublisher{}
|
||||
srv.Publish = pub.Publish
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{"action":"opened"}`))
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want %d", w.Code, http.StatusAccepted)
|
||||
}
|
||||
if len(pub.published) != 1 {
|
||||
t.Fatalf("published events = %d, want 1", len(pub.published))
|
||||
}
|
||||
e := pub.published[0]
|
||||
if e.Kind != "capture" {
|
||||
t.Fatalf("Kind = %q, want \"capture\"", e.Kind)
|
||||
}
|
||||
// e.ID is deliberately not pinned here: assigning the persisted
|
||||
// events-table row id is the host pipeline's persistence step, not the
|
||||
// receiver's, and the receiver publishes before that runs.
|
||||
captured, err := srv.store.ListCaptures(t.Context(), 1)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures: %v", err)
|
||||
}
|
||||
if len(captured) != 1 {
|
||||
t.Fatalf("captured rows = %d, want 1", len(captured))
|
||||
}
|
||||
if got, want := e.Data["id"], captured[0].ID; got != want {
|
||||
t.Fatalf("Data[\"id\"] = %v, want %v (the persisted captured_events row id, for frontend dedup)", got, want)
|
||||
}
|
||||
if got, _ := e.Data["source"].(string); got != "github" {
|
||||
t.Fatalf("Data[\"source\"] = %v, want \"github\"", e.Data["source"])
|
||||
}
|
||||
if _, hasBody := e.Data["body"]; hasBody {
|
||||
t.Fatalf("Data[\"body\"] present, want it omitted -- embedding the full payload here duplicates it into the unbounded events table")
|
||||
}
|
||||
if _, hasHeaders := e.Data["headers"]; hasHeaders {
|
||||
t.Fatalf("Data[\"headers\"] present, want it omitted -- same unbounded-duplication risk as body")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCaptureAcceptsUnauthenticatedByDesign(t *testing.T) {
|
||||
// Capture must accept requests with no HMAC secret configured -- that is
|
||||
// the entire point of an unbound capture endpoint. This test documents
|
||||
// that the handler does not gate on any signature header.
|
||||
srv := captureTestServer(t)
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/unknown-source", strings.NewReader(`{}`))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want %d", w.Code, http.StatusAccepted)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCaptureNonJSONBodyStoredUnredacted(t *testing.T) {
|
||||
srv := captureTestServer(t)
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/plain", strings.NewReader("not json"))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want %d", w.Code, http.StatusAccepted)
|
||||
}
|
||||
got, err := srv.store.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures: %v", err)
|
||||
}
|
||||
if len(got) != 1 || got[0].Body != "not json" {
|
||||
t.Fatalf("captured = %+v, want raw body preserved when it is not JSON", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCaptureRejectsOversizedBody(t *testing.T) {
|
||||
srv := captureTestServer(t)
|
||||
srv.MaxBodyBytes = 8
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{"far":"too big for the cap"}`))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusRequestEntityTooLarge {
|
||||
t.Fatalf("status = %d, want %d", w.Code, http.StatusRequestEntityTooLarge)
|
||||
}
|
||||
got, err := srv.store.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures: %v", err)
|
||||
}
|
||||
if len(got) != 0 {
|
||||
t.Fatalf("captured rows = %d, want 0 (oversized body must never be persisted)", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleCaptureEnforcesBodyCapEvenWhenUnconfigured pins that a caller
|
||||
// that forgets to set CaptureMaxBodyBytes (zero value) still gets a bound --
|
||||
// this is the one disk-bound mechanic that limits a single payload's size
|
||||
// rather than row count or write rate, so it must never silently no-op.
|
||||
func TestHandleCaptureEnforcesBodyCapEvenWhenUnconfigured(t *testing.T) {
|
||||
srv := captureTestServer(t)
|
||||
srv.MaxBodyBytes = 0
|
||||
|
||||
oversized := strings.Repeat("x", fallbackMaxBodyBytes+1)
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(oversized))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusRequestEntityTooLarge {
|
||||
t.Fatalf("status = %d, want %d (CaptureMaxBodyBytes=0 must still enforce the fallback cap)", w.Code, http.StatusRequestEntityTooLarge)
|
||||
}
|
||||
got, err := srv.store.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures: %v", err)
|
||||
}
|
||||
if len(got) != 0 {
|
||||
t.Fatalf("captured rows = %d, want 0", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCaptureRateLimitsPerRemoteAddr(t *testing.T) {
|
||||
// Deliberately NOT keyed by the source path segment: source is an
|
||||
// unregistered, attacker-chosen string for this endpoint (see
|
||||
// handleCapture and docs/prds/event-capture-storage.md), so both
|
||||
// requests below use the SAME source and DIFFERENT RemoteAddr to prove
|
||||
// the limiter is keyed on the sender's address, not the segment.
|
||||
srv := captureTestServer(t)
|
||||
srv.Limiter = webhookguard.NewRateLimiter(0, 1, time.Now) // burst 1, no refill
|
||||
|
||||
req := func(remoteAddr string) *http.Request {
|
||||
r := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{}`))
|
||||
r.RemoteAddr = remoteAddr
|
||||
return r
|
||||
}
|
||||
|
||||
w1 := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w1, req("203.0.113.5:11111"))
|
||||
if w1.Code != http.StatusAccepted {
|
||||
t.Fatalf("first request status = %d, want %d", w1.Code, http.StatusAccepted)
|
||||
}
|
||||
|
||||
w2 := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w2, req("203.0.113.5:22222"))
|
||||
if w2.Code != http.StatusTooManyRequests {
|
||||
t.Fatalf("second request (same host, different port) status = %d, want %d", w2.Code, http.StatusTooManyRequests)
|
||||
}
|
||||
|
||||
// A different remote address, same source segment, must not be affected
|
||||
// by the exhausted budget above.
|
||||
w3 := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w3, req("198.51.100.9:33333"))
|
||||
if w3.Code != http.StatusAccepted {
|
||||
t.Fatalf("other-remote-addr request status = %d, want %d", w3.Code, http.StatusAccepted)
|
||||
}
|
||||
|
||||
got, err := srv.store.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures: %v", err)
|
||||
}
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("captured rows = %d, want 2 (the rate-limited request must not be persisted)", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCaptureIgnoresGetMethod(t *testing.T) {
|
||||
// The route is registered "POST /webhooks/capture/{source}"; a GET does
|
||||
// not match it and falls through to the host mux's own routing (405 in
|
||||
// this isolated registration) -- it must not be treated as a capture.
|
||||
srv := captureTestServer(t)
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/webhooks/capture/github", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code == http.StatusAccepted {
|
||||
t.Fatalf("status = %d, a GET must never be accepted as a capture", w.Code)
|
||||
}
|
||||
got, err := srv.store.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures: %v", err)
|
||||
}
|
||||
if len(got) != 0 {
|
||||
t.Fatalf("captured rows = %d, want 0 (GET must not persist a capture)", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCaptureWithoutCapturesConfiguredIs503(t *testing.T) {
|
||||
srv := captureTestServerWithoutStore(t)
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{}`))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want %d when Captures is nil", w.Code, http.StatusServiceUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
// captureInsertErrorStore forces InsertCapture to fail so the handler's
|
||||
// error path is exercised without relying on a real storage failure.
|
||||
type captureInsertErrorStore struct {
|
||||
storecontract.CaptureStore
|
||||
}
|
||||
|
||||
func (captureInsertErrorStore) InsertCapture(context.Context, storecontract.CapturedEvent, time.Duration, int) (string, error) {
|
||||
return "", errors.New("boom")
|
||||
}
|
||||
|
||||
func TestHandleCaptureStorageFailureIs500(t *testing.T) {
|
||||
srv := captureTestServer(t)
|
||||
srv.Captures = captureInsertErrorStore{}
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{}`))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status = %d, want %d", w.Code, http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// stubSources resolves a fixed set of sources, or fails every lookup.
|
||||
type stubSources struct {
|
||||
byPath map[string]source.Source
|
||||
err error
|
||||
}
|
||||
|
||||
func (s stubSources) GetSource(_ context.Context, path string) (*source.Source, error) {
|
||||
if s.err != nil {
|
||||
return nil, s.err
|
||||
}
|
||||
src, ok := s.byPath[path]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return &src, nil
|
||||
}
|
||||
|
||||
// memCaptures records inserted captures, including the Unsigned flag the
|
||||
// legacy store does not persist.
|
||||
type memCaptures struct{ rows []storecontract.CapturedEvent }
|
||||
|
||||
func (m *memCaptures) InsertCapture(_ context.Context, c storecontract.CapturedEvent, _ time.Duration, _ int) (string, error) {
|
||||
m.rows = append(m.rows, c)
|
||||
return "c", nil
|
||||
}
|
||||
|
||||
func (m *memCaptures) ListCaptures(context.Context, int) ([]storecontract.CapturedEvent, error) {
|
||||
return m.rows, nil
|
||||
}
|
||||
|
||||
// TestHandleCaptureSigning pins the source signing rule: a signed source
|
||||
// authenticates only a valid X-Hub-Signature-256 or X-Signature-256 HMAC
|
||||
// under its secret; an approved unsigned source marks every event unsigned;
|
||||
// anything else is captured and neither authenticated nor unsigned, so it
|
||||
// never dispatches.
|
||||
func TestHandleCaptureSigning(t *testing.T) {
|
||||
const secret = "abcdefghijklmnop"
|
||||
const body = `{"action":"opened"}`
|
||||
signed := source.Source{Path: "github", Signing: source.SigningSigned, Secret: secret}
|
||||
pending := source.Source{Path: "github", Signing: source.SigningUnsignedPending, Secret: secret}
|
||||
unsigned := source.Source{Path: "github", Signing: source.SigningUnsigned, Secret: secret}
|
||||
noSecret := source.Source{Path: "github", Signing: source.SigningSigned}
|
||||
tests := []struct {
|
||||
name string
|
||||
sources SourceResolver
|
||||
header, sig string
|
||||
authenticated bool
|
||||
unsigned bool
|
||||
}{
|
||||
{"signed, valid hub signature", sources(signed), "X-Hub-Signature-256", hmacSHA256(secret, body), true, false},
|
||||
{"signed, valid fallback signature", sources(signed), "X-Signature-256", hmacSHA256(secret, body), true, false},
|
||||
{"signed, wrong signature", sources(signed), "X-Hub-Signature-256", hmacSHA256("not-the-real-secret", body), false, false},
|
||||
{"signed, no signature", sources(signed), "", "", false, false},
|
||||
{"signed, no secret yet", sources(noSecret), "X-Hub-Signature-256", hmacSHA256("", body), false, false},
|
||||
{"unsigned request not yet approved", sources(pending), "", "", false, false},
|
||||
{"unsigned request not yet approved, signed event", sources(pending), "X-Hub-Signature-256", hmacSHA256(secret, body), true, false},
|
||||
{"approved unsigned", sources(unsigned), "", "", false, true},
|
||||
{"unknown source", sources(), "X-Hub-Signature-256", hmacSHA256(secret, body), false, false},
|
||||
{"lookup error fails open at capture", stubSources{err: errors.New("db locked")}, "", "", false, false},
|
||||
{"no source store", nil, "X-Hub-Signature-256", hmacSHA256(secret, body), false, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
captures := &memCaptures{}
|
||||
rc := &Receiver{Log: slog.New(slog.DiscardHandler), Captures: captures, Sources: tt.sources}
|
||||
mux := http.NewServeMux()
|
||||
rc.Register(mux)
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(body))
|
||||
if tt.header != "" {
|
||||
req.Header.Set(tt.header, tt.sig)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want %d", w.Code, http.StatusAccepted)
|
||||
}
|
||||
if len(captures.rows) != 1 {
|
||||
t.Fatalf("captured rows = %d, want 1", len(captures.rows))
|
||||
}
|
||||
got := captures.rows[0]
|
||||
if got.Authenticated != tt.authenticated || got.Unsigned != tt.unsigned {
|
||||
t.Fatalf("authenticated, unsigned = %v, %v; want %v, %v", got.Authenticated, got.Unsigned, tt.authenticated, tt.unsigned)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func sources(list ...source.Source) stubSources {
|
||||
byPath := map[string]source.Source{}
|
||||
for _, s := range list {
|
||||
byPath[s.Path] = s
|
||||
}
|
||||
return stubSources{byPath: byPath}
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
func TestApplyOverlayValuesFieldLevelMerge(t *testing.T) {
|
||||
cfg := config.Config{
|
||||
BotUser: "a",
|
||||
Budgets: config.Budgets{MaxSteps: 10},
|
||||
}
|
||||
overrides := map[string]any{
|
||||
"budgets": map[string]any{"max_steps": float64(20)},
|
||||
}
|
||||
if err := ApplyOverlayValues(&cfg, overrides); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Budgets.MaxSteps != 20 {
|
||||
t.Errorf("MaxSteps = %d, want 20", cfg.Budgets.MaxSteps)
|
||||
}
|
||||
// Fields the overlay omits keep their value.
|
||||
if cfg.BotUser != "a" {
|
||||
t.Errorf("BotUser = %q, want a (unchanged)", cfg.BotUser)
|
||||
}
|
||||
}
|
||||
|
||||
// TestApplyOverlayValuesPreservesOmittedNestedFields pins ApplyOverlayValues'
|
||||
// documented promise -- "only the keys present are replaced, every field the
|
||||
// overlay omits keeps its existing value" -- at the depth where it matters.
|
||||
//
|
||||
// The concrete risk is services.state: an overlay that changes only the target
|
||||
// must not clear target_token, because dropping the token silently removes
|
||||
// authentication for a non-loopback State Store. The existing field-level test
|
||||
// only covers one level (budgets.max_steps); these cases go two levels deep into
|
||||
// a map of structs, which is the shape Services has.
|
||||
func TestApplyOverlayValuesPreservesOmittedNestedFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
start config.Services
|
||||
overlay map[string]any
|
||||
want config.Services
|
||||
}{
|
||||
{
|
||||
name: "target-only overlay keeps the token",
|
||||
start: config.Services{config.ServiceNameState: {Target: "127.0.0.1:50051", TargetToken: "secret"}},
|
||||
overlay: map[string]any{"services": map[string]any{config.ServiceNameState: map[string]any{"target": "10.0.0.5:50051"}}},
|
||||
want: config.Services{config.ServiceNameState: {Target: "10.0.0.5:50051", TargetToken: "secret"}},
|
||||
},
|
||||
{
|
||||
name: "token-only overlay keeps the target",
|
||||
start: config.Services{config.ServiceNameState: {Target: "10.0.0.5:50051", TargetToken: "old"}},
|
||||
overlay: map[string]any{"services": map[string]any{config.ServiceNameState: map[string]any{"target_token": "rotated"}}},
|
||||
want: config.Services{config.ServiceNameState: {Target: "10.0.0.5:50051", TargetToken: "rotated"}},
|
||||
},
|
||||
{
|
||||
name: "sibling service is untouched",
|
||||
start: config.Services{config.ServiceNameGateway: {Target: "127.0.0.1:50052"}, config.ServiceNameState: {Target: "a", TargetToken: "t"}},
|
||||
overlay: map[string]any{"services": map[string]any{config.ServiceNameState: map[string]any{"target": "b"}}},
|
||||
want: config.Services{config.ServiceNameGateway: {Target: "127.0.0.1:50052"}, config.ServiceNameState: {Target: "b", TargetToken: "t"}},
|
||||
},
|
||||
{
|
||||
name: "an entry the overlay introduces decodes in full",
|
||||
start: config.Services{},
|
||||
overlay: map[string]any{"services": map[string]any{config.ServiceNameState: map[string]any{"target": "127.0.0.1:50051", "target_token": "fresh"}}},
|
||||
want: config.Services{config.ServiceNameState: {Target: "127.0.0.1:50051", TargetToken: "fresh"}},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cfg := config.Config{Services: tt.start}
|
||||
if err := ApplyOverlayValues(&cfg, tt.overlay); err != nil {
|
||||
t.Fatalf("ApplyOverlayValues: %v", err)
|
||||
}
|
||||
if !maps.Equal(cfg.Services, tt.want) {
|
||||
t.Errorf("Services = %+v, want %+v", cfg.Services, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestApplyOverlayValuesMergesEveryMapEntry pins that the preservation above is
|
||||
// a property of ApplyOverlayValues rather than of Services. yaml.v3 decodes a
|
||||
// map value into a fresh zero value, so every map[string]struct field loses the
|
||||
// fields an override omits; Services, image.hosted and providers are the three
|
||||
// the configuration has, so a fix that named one of them would leave the other
|
||||
// two silently zeroing operator settings.
|
||||
func TestApplyOverlayValuesMergesEveryMapEntry(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
start config.Config
|
||||
overlay map[string]any
|
||||
check func(t *testing.T, cfg config.Config)
|
||||
}{
|
||||
{
|
||||
name: "providers entry keeps the fields the overlay omits",
|
||||
start: config.Config{Providers: map[string]config.Provider{
|
||||
"anthropic": {Class: "anthropic", APIKeyEnv: "ANTHROPIC_API_KEY"},
|
||||
}},
|
||||
overlay: map[string]any{"providers": map[string]any{
|
||||
"anthropic": map[string]any{"base_url": "https://proxy.example"},
|
||||
}},
|
||||
check: func(t *testing.T, cfg config.Config) {
|
||||
t.Helper()
|
||||
want := map[string]config.Provider{
|
||||
"anthropic": {Class: "anthropic", APIKeyEnv: "ANTHROPIC_API_KEY", BaseURL: "https://proxy.example"},
|
||||
}
|
||||
if !maps.Equal(cfg.Providers, want) {
|
||||
t.Errorf("Providers = %+v, want %+v", cfg.Providers, want)
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cfg := tt.start
|
||||
if err := ApplyOverlayValues(&cfg, tt.overlay); err != nil {
|
||||
t.Fatalf("ApplyOverlayValues: %v", err)
|
||||
}
|
||||
tt.check(t, cfg)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoaderApplyOverlayLayersDefaultsValidatesAndRecordsProvenance(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
if err := os.WriteFile(path, []byte("bot_user = \"widget\"\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
l := New(slog.New(slog.DiscardHandler))
|
||||
doc, err := l.Resolve(path, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
applied, err := l.ApplyOverlay(doc, map[string]any{"poll_interval": "90s"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if applied.Config.PollInterval != config.Duration(90*time.Second) {
|
||||
t.Errorf("PollInterval = %v, want 90s", applied.Config.PollInterval)
|
||||
}
|
||||
if len(applied.Provenance.Origins) != 2 {
|
||||
t.Errorf("Origins = %+v, want 2 (file + runtime overlay)", applied.Provenance.Origins)
|
||||
}
|
||||
|
||||
// An overlay that fails validation aborts; ApplyOverlay never mutates
|
||||
// its input, so the base document is untouched even without a copy.
|
||||
if _, err := l.ApplyOverlay(doc, map[string]any{"dispatch": map[string]any{"trigger": "bogus"}}); err == nil {
|
||||
t.Fatal("invalid overlay accepted")
|
||||
}
|
||||
if doc.Config.Dispatch.Trigger != "assignee" {
|
||||
t.Errorf("base Dispatch.Trigger = %q, want assignee (defaulted, untouched)", doc.Config.Dispatch.Trigger)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoaderApplyOverlayEmptyIsNoOp(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
if err := os.WriteFile(path, []byte("bot_user = \"widget\"\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l := New(slog.New(slog.DiscardHandler))
|
||||
doc, err := l.Resolve(path, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
applied, err := l.ApplyOverlay(doc, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(applied.Provenance.Origins) != 1 {
|
||||
t.Errorf("Origins = %+v, want 1 (no overlay origin for an empty overlay)", applied.Provenance.Origins)
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
func TestArtifactsConfigDefaults(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" +
|
||||
"[forge]\ntype = \"gitea\"\nhost = \"https://git.example.test\"\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Artifacts.BaseURL != "" {
|
||||
t.Errorf("BaseURL = %q, want empty so the sender stays disabled", cfg.Artifacts.BaseURL)
|
||||
}
|
||||
if want := (config.SecretRef{Engine: "env", Key: "WORKSPACE_INGEST_TOKEN"}); cfg.Artifacts.Token != want {
|
||||
t.Errorf("Token = %+v, want the documented fallback %+v", cfg.Artifacts.Token, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestArtifactsConfigPreservesExplicitValues(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" +
|
||||
"[artifacts]\nbase_url = \"https://offloaded.dev\"\n" +
|
||||
"token = { engine = \"env\", key = \"ARCHIE_GITHUB_TOKEN\" }\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Artifacts.BaseURL != "https://offloaded.dev" {
|
||||
t.Errorf("BaseURL = %q, want the explicit value", cfg.Artifacts.BaseURL)
|
||||
}
|
||||
if want := (config.SecretRef{Engine: "env", Key: "ARCHIE_GITHUB_TOKEN"}); cfg.Artifacts.Token != want {
|
||||
t.Errorf("Token = %+v, want %+v", cfg.Artifacts.Token, want)
|
||||
}
|
||||
}
|
||||
@@ -1,269 +0,0 @@
|
||||
// This file fences the claim that every archie binary reads the same
|
||||
// configuration file when the operator names none. The value is only
|
||||
// observable by starting a process and reading which file it opened, but the
|
||||
// failure being guarded against is a second derivation of that value, which is
|
||||
// a shape in the source before it is a wrong path at runtime -- so the fence
|
||||
// reads the source.
|
||||
//
|
||||
// Four binaries derived their default with os.UserConfigDir while the daemon
|
||||
// resolved it from its own config home (archie-core-8i6l). The two agree on
|
||||
// Linux with an absolute XDG_CONFIG_HOME and diverge everywhere else: darwin
|
||||
// resolves os.UserConfigDir to ~/Library/Application Support, and a relative
|
||||
// XDG_CONFIG_HOME is rejected outright rather than honoured. One deployment
|
||||
// then boots from a different config file depending on which binary started it.
|
||||
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/printer"
|
||||
"go/token"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const moduleImportPrefix = "github.com/samcharles93/archie-core/"
|
||||
|
||||
// configPackageImportPath is this package as its importers name it, spelled
|
||||
// out so a moved or renamed package fails this fence instead of matching
|
||||
// nothing and passing.
|
||||
const configPackageImportPath = moduleImportPrefix + "internal/infrastructure/configuration"
|
||||
|
||||
// helperName is the single helper that resolves the default configuration path.
|
||||
const helperName = "DefaultConfigPath"
|
||||
|
||||
// configFlagDefault is one -config registration found by the fence: where it
|
||||
// is, what it defaults to, and whether that default comes from the helper.
|
||||
type configFlagDefault struct {
|
||||
at token.Position
|
||||
expr string
|
||||
resolved bool
|
||||
}
|
||||
|
||||
// TestDefaultConfigPathFollowsTheConfigHome pins the precedence every archie
|
||||
// binary shares: $XDG_CONFIG_HOME when it is set, ~/.config when it is not.
|
||||
//
|
||||
// The relative and unknowable-home cases are the ones a second derivation gets
|
||||
// wrong, so they are the reason this table exists rather than a single
|
||||
// assertion: os.UserConfigDir rejects a relative $XDG_CONFIG_HOME with an error
|
||||
// rather than resolving it, and answers with ~/Library/Application Support on
|
||||
// darwin, where this rule says ~/.config.
|
||||
func TestDefaultConfigPathFollowsTheConfigHome(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
tests := []struct {
|
||||
name string
|
||||
xdg string
|
||||
home string // an empty home is an unknowable one: os.UserHomeDir fails
|
||||
wantDir string
|
||||
}{
|
||||
{
|
||||
name: "an absolute XDG_CONFIG_HOME is used as given",
|
||||
xdg: filepath.Join(home, "xdg"),
|
||||
home: filepath.Join(home, "ignored"),
|
||||
wantDir: filepath.Join(home, "xdg", "archie"),
|
||||
},
|
||||
{
|
||||
name: "a relative XDG_CONFIG_HOME is honoured rather than rejected",
|
||||
xdg: filepath.Join("relative", "config"),
|
||||
home: home,
|
||||
wantDir: filepath.Join("relative", "config", "archie"),
|
||||
},
|
||||
{
|
||||
// $XDG_CONFIG_HOME "either not set or empty" is one case to the code
|
||||
// under test, which reads it with os.Getenv: nothing downstream can
|
||||
// tell an absent variable from an empty one, so neither can this.
|
||||
name: "an unset or empty XDG_CONFIG_HOME falls back to the home directory",
|
||||
home: home,
|
||||
wantDir: filepath.Join(home, ".config", "archie"),
|
||||
},
|
||||
{
|
||||
name: "an unknowable home leaves the path relative instead of empty",
|
||||
wantDir: filepath.Join(".config", "archie"),
|
||||
},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Setenv("HOME", tc.home)
|
||||
t.Setenv("XDG_CONFIG_HOME", tc.xdg)
|
||||
if got := DefaultConfigDir(); got != tc.wantDir {
|
||||
t.Errorf("DefaultConfigDir() = %q, want %q", got, tc.wantDir)
|
||||
}
|
||||
if got, want := DefaultConfigPath(), filepath.Join(tc.wantDir, "config.toml"); got != want {
|
||||
t.Errorf("DefaultConfigPath() = %q, want %q", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBinariesTakeTheDefaultConfigPathFromHere(t *testing.T) {
|
||||
fset := token.NewFileSet()
|
||||
var defaults []configFlagDefault
|
||||
|
||||
root := moduleRoot(t)
|
||||
|
||||
for _, pattern := range []string{
|
||||
filepath.Join(root, "cmd", "*", "*.go"),
|
||||
filepath.Join(root, "internal", "app", "archied", "*.go"),
|
||||
} {
|
||||
paths, err := filepath.Glob(pattern)
|
||||
if err != nil {
|
||||
t.Fatalf("glob %s: %v", pattern, err)
|
||||
}
|
||||
if len(paths) == 0 {
|
||||
t.Fatalf("glob %s matched no file, so this fence checked nothing", pattern)
|
||||
}
|
||||
for _, path := range paths {
|
||||
if strings.HasSuffix(path, "_test.go") {
|
||||
continue
|
||||
}
|
||||
file, err := parser.ParseFile(fset, path, nil, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("parse %s: %v", path, err)
|
||||
}
|
||||
helper := importedName(file, configPackageImportPath)
|
||||
ast.Inspect(file, func(node ast.Node) bool {
|
||||
call, ok := node.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
if isSelectorCall(call, "os", "UserConfigDir") {
|
||||
t.Errorf("%s: resolves the config directory itself with os.UserConfigDir; it rejects a relative XDG_CONFIG_HOME and resolves to ~/Library/Application Support on darwin, so this process would boot from a different file than the daemon (%s.%s resolves it once)",
|
||||
fset.Position(call.Pos()), lastElement(configPackageImportPath), helperName)
|
||||
}
|
||||
defaultExpr, ok := configFlagDefaultExpr(call)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
defaults = append(defaults, configFlagDefault{
|
||||
at: fset.Position(call.Pos()),
|
||||
expr: renderExpr(fset, defaultExpr),
|
||||
resolved: callsHelper(defaultExpr, helper),
|
||||
})
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if len(defaults) == 0 {
|
||||
t.Fatalf("no -config registration found under %s; this fence matched nothing and would pass vacuously", root)
|
||||
}
|
||||
for _, d := range defaults {
|
||||
if !d.resolved {
|
||||
t.Errorf("%s: -config defaults to %s instead of %s.%s(); every binary reads the same file only while they all take the path from that one helper (archie-core-8i6l)",
|
||||
d.at, d.expr, lastElement(configPackageImportPath), helperName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// configFlagDefaultExpr returns the default expression of a call registering a
|
||||
// flag named "config", and whether the call registers one at all. Both
|
||||
// flag.StringVar(target, name, value, usage) and flag.String(name, value,
|
||||
// usage) are recognised, whatever name the FlagSet is bound to -- the callers
|
||||
// use flag.CommandLine, fs and flags interchangeably.
|
||||
func configFlagDefaultExpr(call *ast.CallExpr) (ast.Expr, bool) {
|
||||
sel, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
switch sel.Sel.Name {
|
||||
case "StringVar":
|
||||
if len(call.Args) >= 3 && isStringLiteral(call.Args[1], "config") {
|
||||
return call.Args[2], true
|
||||
}
|
||||
case "String":
|
||||
if len(call.Args) >= 2 && isStringLiteral(call.Args[0], "config") {
|
||||
return call.Args[1], true
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// isSelectorCall reports whether call is qualifier.name(...).
|
||||
func isSelectorCall(call *ast.CallExpr, qualifier, name string) bool {
|
||||
sel, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
ident, ok := sel.X.(*ast.Ident)
|
||||
return ok && ident.Name == qualifier && sel.Sel.Name == name
|
||||
}
|
||||
|
||||
// callsHelper reports whether expr is helper.name(), where helper is the local
|
||||
// name this file's imports give the configuration package ("" when the file
|
||||
// does not import it).
|
||||
func callsHelper(expr ast.Expr, helper string) bool {
|
||||
if helper == "" {
|
||||
return false
|
||||
}
|
||||
call, ok := expr.(*ast.CallExpr)
|
||||
return ok && isSelectorCall(call, helper, helperName)
|
||||
}
|
||||
|
||||
// isStringLiteral reports whether expr is the string literal want.
|
||||
func isStringLiteral(expr ast.Expr, want string) bool {
|
||||
literal, ok := expr.(*ast.BasicLit)
|
||||
if !ok || literal.Kind != token.STRING {
|
||||
return false
|
||||
}
|
||||
value, err := strconv.Unquote(literal.Value)
|
||||
return err == nil && value == want
|
||||
}
|
||||
|
||||
// importedName returns the name file's imports bind path to, or "" when the
|
||||
// file does not import it.
|
||||
func importedName(file *ast.File, path string) string {
|
||||
for _, imported := range file.Imports {
|
||||
if imported.Path == nil {
|
||||
continue
|
||||
}
|
||||
importedPath, err := strconv.Unquote(imported.Path.Value)
|
||||
if err != nil || importedPath != path {
|
||||
continue
|
||||
}
|
||||
if name := imported.Name; name != nil && name.Name != "" && name.Name != "_" && name.Name != "." {
|
||||
return name.Name
|
||||
}
|
||||
return lastElement(path)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// renderExpr renders expr as source text, for a failure message that names the
|
||||
// derivation instead of only its position.
|
||||
func renderExpr(fset *token.FileSet, expr ast.Expr) string {
|
||||
var buf bytes.Buffer
|
||||
if err := printer.Fprint(&buf, fset, expr); err != nil {
|
||||
return "<unrenderable expression>"
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func lastElement(path string) string {
|
||||
return path[strings.LastIndex(path, "/")+1:]
|
||||
}
|
||||
|
||||
// moduleRoot walks up from this test's source to the directory holding go.mod.
|
||||
func moduleRoot(t *testing.T) string {
|
||||
t.Helper()
|
||||
_, file, _, ok := runtime.Caller(0)
|
||||
if !ok {
|
||||
t.Fatal("cannot locate this test's source file")
|
||||
}
|
||||
dir := filepath.Dir(file)
|
||||
for {
|
||||
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
|
||||
return dir
|
||||
}
|
||||
parent := filepath.Dir(dir)
|
||||
if parent == dir {
|
||||
t.Fatal("no go.mod above this test's source file")
|
||||
}
|
||||
dir = parent
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
func TestValidateCurators(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(cfg *config.Config)
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "no curators",
|
||||
mutate: func(cfg *config.Config) {},
|
||||
},
|
||||
{
|
||||
name: "valid curator",
|
||||
mutate: func(cfg *config.Config) {
|
||||
cfg.Curators = []config.CuratorDefinition{{Name: "project", Enabled: true, Interval: config.Duration(time.Hour)}}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "missing interval",
|
||||
mutate: func(cfg *config.Config) {
|
||||
cfg.Curators = []config.CuratorDefinition{{Name: "project", Enabled: true}}
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "zero interval",
|
||||
mutate: func(cfg *config.Config) {
|
||||
cfg.Curators = []config.CuratorDefinition{{Name: "project", Enabled: true, Interval: config.Duration(0)}}
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "negative interval",
|
||||
mutate: func(cfg *config.Config) {
|
||||
cfg.Curators = []config.CuratorDefinition{{Name: "project", Enabled: true, Interval: config.Duration(-time.Minute)}}
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
// A definition must be valid seed data whether or not it is
|
||||
// currently enabled: flipping Enabled on later must not silently
|
||||
// default the interval.
|
||||
name: "disabled curator still requires interval",
|
||||
mutate: func(cfg *config.Config) {
|
||||
cfg.Curators = []config.CuratorDefinition{{Name: "project"}}
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cfg := minimalValidConfig()
|
||||
tt.mutate(&cfg)
|
||||
err := Validate(&cfg)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("Validate() error = %v, wantErr %v", err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,257 +0,0 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
func TestApplyNATSDefaultsResolvesMode(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mode string
|
||||
url string
|
||||
want string
|
||||
}{
|
||||
{name: "url set implies external", url: "nats://localhost:4222", want: config.NATSModeExternal},
|
||||
{name: "empty implies embedded", want: config.NATSModeEmbedded},
|
||||
{name: "explicit embedded is preserved", mode: config.NATSModeEmbedded, want: config.NATSModeEmbedded},
|
||||
{name: "explicit external is preserved", mode: config.NATSModeExternal, url: "nats://localhost:4222", want: config.NATSModeExternal},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cfg := &config.Config{NATS: config.NATSConfig{Mode: tc.mode, URL: tc.url}}
|
||||
applyNATSDefaults(cfg)
|
||||
if cfg.NATS.Mode != tc.want {
|
||||
t.Errorf("applyNATSDefaults() mode = %q, want %q", cfg.NATS.Mode, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyContainerDefaultsMakesManagedWorkersReadyByDefault(t *testing.T) {
|
||||
cfg := &config.Config{}
|
||||
applyContainerDefaults(cfg)
|
||||
|
||||
if cfg.Containers.Image != defaultContainerImage {
|
||||
t.Errorf("Containers.Image = %q, want %q", cfg.Containers.Image, defaultContainerImage)
|
||||
}
|
||||
if cfg.Containers.MaxUptime.Std() != defaultContainerUptime {
|
||||
t.Errorf("Containers.MaxUptime = %s, want %s", cfg.Containers.MaxUptime.Std(), defaultContainerUptime)
|
||||
}
|
||||
if cfg.Containers.VolumeTTL.Std() != defaultVolumeTTL {
|
||||
t.Errorf("Containers.VolumeTTL = %s, want %s", cfg.Containers.VolumeTTL.Std(), defaultVolumeTTL)
|
||||
}
|
||||
if cfg.Containers.PullPolicy != defaultPullPolicy {
|
||||
t.Errorf("Containers.PullPolicy = %q, want %q", cfg.Containers.PullPolicy, defaultPullPolicy)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyForgeDefaultsIntake(t *testing.T) {
|
||||
cfg := &config.Config{}
|
||||
applyForgeDefaults(cfg)
|
||||
if cfg.Forge.Intake != config.ForgeIntakePoll {
|
||||
t.Errorf("applyForgeDefaults() intake = %q, want %q", cfg.Forge.Intake, config.ForgeIntakePoll)
|
||||
}
|
||||
|
||||
explicit := &config.Config{Forge: config.Forge{Intake: config.ForgeIntakeWebhook}}
|
||||
applyForgeDefaults(explicit)
|
||||
if explicit.Forge.Intake != config.ForgeIntakeWebhook {
|
||||
t.Errorf("applyForgeDefaults() intake = %q, want unchanged %q", explicit.Forge.Intake, config.ForgeIntakeWebhook)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyIdentityDefaultsDerivesEmailPerIdentity(t *testing.T) {
|
||||
cfg := &config.Config{Identities: []config.IdentityConfig{
|
||||
{BotUser: "github-bot", Forge: config.Forge{Type: forgeTypeGitHub}},
|
||||
{BotUser: "gitea-bot", Forge: config.Forge{Type: forgeTypeGitea}},
|
||||
{BotUser: "explicit", BotEmail: "bot@example.test", Forge: config.Forge{Type: forgeTypeGitHub}},
|
||||
}}
|
||||
|
||||
applyIdentityDefaults(cfg)
|
||||
|
||||
want := []string{"github-bot@users.noreply.github.com", "gitea-bot@gitea.local", "bot@example.test"}
|
||||
for i := range want {
|
||||
if cfg.Identities[i].BotEmail != want[i] {
|
||||
t.Errorf("identity %d BotEmail = %q, want %q", i, cfg.Identities[i].BotEmail, want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestApplyIdentityDefaultsAdoptsASoleIdentityForTheRoot pins the single-identity
|
||||
// case. When one [[identities]] entry defines the deployment, the root
|
||||
// single-identity fields must not be left empty: consumers that are inherently
|
||||
// single-agent read the root BotUser (the session curator is built with
|
||||
// cfg.BotUser), so an empty root there is not "unused", it is "no agent" and
|
||||
// every session is skipped.
|
||||
func TestApplyIdentityDefaultsAdoptsASoleIdentityForTheRoot(t *testing.T) {
|
||||
cfg := &config.Config{Identities: []config.IdentityConfig{
|
||||
{BotUser: "solo-bot", Forge: config.Forge{Type: forgeTypeGitHub}},
|
||||
}}
|
||||
|
||||
applyIdentityDefaults(cfg)
|
||||
|
||||
if want := "solo-bot"; cfg.BotUser != want {
|
||||
t.Errorf("root BotUser = %q, want %q adopted from the sole identity", cfg.BotUser, want)
|
||||
}
|
||||
if want := "solo-bot@users.noreply.github.com"; cfg.BotEmail != want {
|
||||
t.Errorf("root BotEmail = %q, want %q", cfg.BotEmail, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestApplyIdentityDefaultsLeavesAnExplicitRootAlone is the other direction: a
|
||||
// default must never overwrite what the operator wrote.
|
||||
func TestApplyIdentityDefaultsLeavesAnExplicitRootAlone(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
BotUser: "explicit-root",
|
||||
Identities: []config.IdentityConfig{
|
||||
{BotUser: "solo-bot", Forge: config.Forge{Type: forgeTypeGitHub}},
|
||||
},
|
||||
}
|
||||
|
||||
applyIdentityDefaults(cfg)
|
||||
|
||||
if want := "explicit-root"; cfg.BotUser != want {
|
||||
t.Errorf("root BotUser = %q, want the explicit value %q preserved", cfg.BotUser, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestApplyIdentityDefaultsDoesNotGuessBetweenIdentities records the boundary:
|
||||
// with more than one identity there is no single answer for the root, so it is
|
||||
// left empty for the operator to set deliberately rather than guessed at.
|
||||
func TestApplyIdentityDefaultsDoesNotGuessBetweenIdentities(t *testing.T) {
|
||||
cfg := &config.Config{Identities: []config.IdentityConfig{
|
||||
{BotUser: "one", Forge: config.Forge{Type: forgeTypeGitHub}},
|
||||
{BotUser: "two", Forge: config.Forge{Type: forgeTypeGitHub}},
|
||||
}}
|
||||
|
||||
applyIdentityDefaults(cfg)
|
||||
|
||||
if cfg.BotUser != "" {
|
||||
t.Errorf("root BotUser = %q, want empty: two identities leave no single answer", cfg.BotUser)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyCaptureDefaultsFillsZeroValues(t *testing.T) {
|
||||
cfg := &config.Config{}
|
||||
applyCaptureDefaults(cfg)
|
||||
|
||||
if got, want := cfg.Capture.Retention.Std(), defaultCaptureRetention; got != want {
|
||||
t.Errorf("Capture.Retention = %v, want %v", got, want)
|
||||
}
|
||||
if cfg.Capture.MaxEvents != defaultCaptureMaxEvents {
|
||||
t.Errorf("Capture.MaxEvents = %d, want %d", cfg.Capture.MaxEvents, defaultCaptureMaxEvents)
|
||||
}
|
||||
if cfg.Capture.MaxBodyBytes != defaultCaptureMaxBodyBytes {
|
||||
t.Errorf("Capture.MaxBodyBytes = %d, want %d", cfg.Capture.MaxBodyBytes, defaultCaptureMaxBodyBytes)
|
||||
}
|
||||
if cfg.Capture.RatePerSecond != defaultCaptureRatePerSecond {
|
||||
t.Errorf("Capture.RatePerSecond = %v, want %v", cfg.Capture.RatePerSecond, defaultCaptureRatePerSecond)
|
||||
}
|
||||
if cfg.Capture.RateBurst != defaultCaptureRateBurst {
|
||||
t.Errorf("Capture.RateBurst = %d, want %d", cfg.Capture.RateBurst, defaultCaptureRateBurst)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyCaptureDefaultsLeavesExplicitValuesAlone(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
Capture: config.CaptureConfig{
|
||||
Retention: config.Duration(24 * time.Hour),
|
||||
MaxEvents: 42,
|
||||
MaxBodyBytes: 1024,
|
||||
RatePerSecond: 2.5,
|
||||
RateBurst: 9,
|
||||
},
|
||||
}
|
||||
applyCaptureDefaults(cfg)
|
||||
|
||||
if cfg.Capture.Retention.Std() != 24*time.Hour {
|
||||
t.Errorf("Capture.Retention = %v, want unchanged 24h", cfg.Capture.Retention.Std())
|
||||
}
|
||||
if cfg.Capture.MaxEvents != 42 {
|
||||
t.Errorf("Capture.MaxEvents = %d, want unchanged 42", cfg.Capture.MaxEvents)
|
||||
}
|
||||
if cfg.Capture.MaxBodyBytes != 1024 {
|
||||
t.Errorf("Capture.MaxBodyBytes = %d, want unchanged 1024", cfg.Capture.MaxBodyBytes)
|
||||
}
|
||||
if cfg.Capture.RatePerSecond != 2.5 {
|
||||
t.Errorf("Capture.RatePerSecond = %v, want unchanged 2.5", cfg.Capture.RatePerSecond)
|
||||
}
|
||||
if cfg.Capture.RateBurst != 9 {
|
||||
t.Errorf("Capture.RateBurst = %d, want unchanged 9", cfg.Capture.RateBurst)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyMemoryDefaultsFillsAbsentEngineWithBuiltin(t *testing.T) {
|
||||
cfg := &config.Config{}
|
||||
applyMemoryDefaults(cfg)
|
||||
|
||||
if cfg.Memory.Engine != memoryEngineBuiltin {
|
||||
t.Errorf("Memory.Engine = %q, want %q", cfg.Memory.Engine, memoryEngineBuiltin)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyMemoryDefaultsLeavesExplicitEngineAlone(t *testing.T) {
|
||||
cfg := &config.Config{Memory: config.MemoryConfig{Engine: "honcho"}}
|
||||
applyMemoryDefaults(cfg)
|
||||
|
||||
if cfg.Memory.Engine != "honcho" {
|
||||
t.Errorf("Memory.Engine = %q, want unchanged %q", cfg.Memory.Engine, "honcho")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDefaultsKeepAnExplicitUnlimitedDiffCap is the regression case for
|
||||
// diff_cap_lines = 0 silently becoming 400. The dashboard schema, and
|
||||
// StageDiffCap itself, both document 0 as "no cap", but the defaults pass could
|
||||
// not tell an explicit 0 from an absent key and rewrote both to 400 -- so the
|
||||
// documented way to switch the cap off was unreachable through config.
|
||||
func TestDefaultsKeepAnExplicitUnlimitedDiffCap(t *testing.T) {
|
||||
unlimited := 0
|
||||
cfg := config.Config{DiffCapLines: &unlimited}
|
||||
(&Loader{}).applyDefaults(&cfg)
|
||||
|
||||
if cfg.DiffCapLines == nil {
|
||||
t.Fatal("DiffCapLines = nil, want the explicit 0 preserved")
|
||||
}
|
||||
if *cfg.DiffCapLines != 0 {
|
||||
t.Fatalf("DiffCapLines = %d, want 0: an explicit 0 means no cap", *cfg.DiffCapLines)
|
||||
}
|
||||
if cfg.DiffCap() != 0 {
|
||||
t.Fatalf("DiffCap() = %d, want 0 (unlimited)", cfg.DiffCap())
|
||||
}
|
||||
}
|
||||
|
||||
// TestDefaultsApplyTheDiffCapWhenUnset pins the other half: an absent key still
|
||||
// gets the safety cap, so omitting it never silently auto-opens huge PRs.
|
||||
func TestDefaultsApplyTheDiffCapWhenUnset(t *testing.T) {
|
||||
cfg := config.Config{}
|
||||
(&Loader{}).applyDefaults(&cfg)
|
||||
|
||||
if cfg.DiffCapLines == nil || *cfg.DiffCapLines != defaultDiffCapLines {
|
||||
t.Fatalf("DiffCapLines = %v, want %d when the key is absent", cfg.DiffCapLines, defaultDiffCapLines)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDefaultsFillTheHealthDependencyTimeout pins that the probe timeout has a
|
||||
// default, so a config that never mentions it still bounds the Gateway call
|
||||
// rather than letting a hung dependency stall the whole health report.
|
||||
func TestDefaultsFillTheHealthDependencyTimeout(t *testing.T) {
|
||||
cfg := config.Config{}
|
||||
(&Loader{}).applyDefaults(&cfg)
|
||||
|
||||
if got := time.Duration(cfg.Health.DependencyTimeout); got != defaultHealthDependencyTimeout {
|
||||
t.Fatalf("Health.DependencyTimeout = %v, want %v", got, defaultHealthDependencyTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDefaultsKeepAConfiguredHealthDependencyTimeout pins that an operator's
|
||||
// value is not overwritten, which is the whole point of making it configurable.
|
||||
func TestDefaultsKeepAConfiguredHealthDependencyTimeout(t *testing.T) {
|
||||
cfg := config.Config{Health: config.Health{DependencyTimeout: config.Duration(30 * time.Second)}}
|
||||
(&Loader{}).applyDefaults(&cfg)
|
||||
|
||||
if got := time.Duration(cfg.Health.DependencyTimeout); got != 30*time.Second {
|
||||
t.Fatalf("Health.DependencyTimeout = %v, want the configured 30s", got)
|
||||
}
|
||||
}
|
||||
@@ -1,754 +0,0 @@
|
||||
// Feature-based config contract tests.
|
||||
//
|
||||
// These tests define the REQUIREMENTS for archie-core-abg.19. An
|
||||
// implementing agent must make every test in this file pass WITHOUT
|
||||
// modifying the tests themselves. The tests are the spec.
|
||||
//
|
||||
// Design:
|
||||
// - ~/.config/archie/config.yaml -- daemon-level fields
|
||||
// - ~/.config/archie/config.gateway.yaml -- chat channels, platforms
|
||||
// - ~/.config/archie/config.tools.yaml -- MCP servers, tool policy
|
||||
// - ~/.config/archie/config.memory.yaml -- memory provider config
|
||||
// - ~/.config/archie/config.models.yaml -- LLM providers and models
|
||||
// - ~/.config/archie/config.identities.yaml -- identity configs
|
||||
// - ~/.config/archie/conf.d/*.yaml -- additional feature files (Linux convention)
|
||||
//
|
||||
// Missing files mean "feature disabled" -- no error, just zero values.
|
||||
// Legacy config.toml is still supported as a fallback.
|
||||
// Overlay support: --config-overlay <dir> applies files from <dir>
|
||||
// on top of the base config directory.
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
// helpers
|
||||
|
||||
// writeFile creates a file under dir with the given content.
|
||||
func writeFile(t *testing.T, dir, name, content string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil {
|
||||
t.Fatalf("write %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
// tmpConfigDir creates a temp directory for config files.
|
||||
func tmpConfigDir(t *testing.T) string {
|
||||
t.Helper()
|
||||
d := t.TempDir()
|
||||
// Also create conf.d/ subdirectory for additional feature files.
|
||||
if err := os.MkdirAll(filepath.Join(d, "conf.d"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// ── 1. Daemon-level config ────────────────────────────────────────
|
||||
|
||||
// func TestLoadDirLoadsDaemonConfig(t *testing.T) {
|
||||
// dir := tmpConfigDir(t)
|
||||
// writeFile(t, dir, "config.yaml", `
|
||||
// work_dir: /var/archie/work
|
||||
// db_path: /var/archie/data.db
|
||||
// poll_interval: 30s
|
||||
// max_retries: 5
|
||||
// bot_user: archie
|
||||
// `)
|
||||
|
||||
// cfg, err := loadDir(dir, "")
|
||||
// if err != nil {
|
||||
// t.Fatalf("LoadDir: %v", err)
|
||||
// }
|
||||
// if cfg.WorkDir != "/var/archie/work" {
|
||||
// t.Errorf("WorkDir = %q", cfg.WorkDir)
|
||||
// }
|
||||
// if cfg.DBPath != "/var/archie/data.db" {
|
||||
// t.Errorf("DBPath = %q", cfg.DBPath)
|
||||
// }
|
||||
// if cfg.PollInterval.Std() != 30*time.Second {
|
||||
// t.Errorf("PollInterval = %v", cfg.PollInterval.Std())
|
||||
// }
|
||||
// if cfg.MaxRetries != 5 {
|
||||
// t.Errorf("MaxRetries = %d", cfg.MaxRetries)
|
||||
// }
|
||||
// if cfg.BotUser != "archie" {
|
||||
// t.Errorf("BotUser = %q", cfg.BotUser)
|
||||
// }
|
||||
// }
|
||||
|
||||
// func TestLoadDirAppliesDefaultsForMissingDaemonFields(t *testing.T) {
|
||||
// dir := tmpConfigDir(t)
|
||||
// writeFile(t, dir, "config.yaml", `bot_user: solo`)
|
||||
|
||||
// cfg, err := loadDir(dir, "")
|
||||
// if err != nil {
|
||||
// t.Fatalf("LoadDir: %v", err)
|
||||
// }
|
||||
// // Defaults from finalize() must still apply.
|
||||
// if cfg.PollInterval.Std() != 60*time.Second {
|
||||
// t.Errorf("PollInterval default = %v, want 60s", cfg.PollInterval.Std())
|
||||
// }
|
||||
// if cfg.WorkDir == "" {
|
||||
// t.Error("WorkDir should have a default")
|
||||
// }
|
||||
// }
|
||||
|
||||
// func TestLoadDirRequiresBotUser(t *testing.T) {
|
||||
// dir := tmpConfigDir(t)
|
||||
// writeFile(t, dir, "config.yaml", `db_path: /tmp/db`)
|
||||
// _, err := loadDir(dir, "")
|
||||
// if err == nil || !strings.Contains(err.Error(), "bot_user") {
|
||||
// t.Errorf("expected bot_user error, got: %v", err)
|
||||
// }
|
||||
// }
|
||||
|
||||
// // ── 2. Feature files are optional ─────────────────────────────────
|
||||
|
||||
// func TestLoadDirMissingFeatureFilesSucceeds(t *testing.T) {
|
||||
// dir := tmpConfigDir(t)
|
||||
// // Only config.yaml exists -- no gateway, tools, memory, models, identities files.
|
||||
// writeFile(t, dir, "config.yaml", `bot_user: minimal`)
|
||||
|
||||
// cfg, err := loadDir(dir, "")
|
||||
// if err != nil {
|
||||
// t.Fatalf("LoadDir: %v", err)
|
||||
// }
|
||||
// // Gateway config should be zero-valued (feature disabled).
|
||||
// if cfg.Chat.Telegram.TokenEnv != "" {
|
||||
// t.Error("Telegram should be disabled when config.gateway.yaml is absent")
|
||||
// }
|
||||
// // Tools should be zero-valued.
|
||||
// if len(cfg.Providers) != 0 {
|
||||
// t.Errorf("Providers should be empty when config.models.yaml is absent, got %d", len(cfg.Providers))
|
||||
// }
|
||||
// }
|
||||
|
||||
// ── 3. Gateway feature file ───────────────────────────────────────
|
||||
|
||||
// func TestLoadDirGatewayConfig(t *testing.T) {
|
||||
// dir := tmpConfigDir(t)
|
||||
// writeFile(t, dir, "config.yaml", `bot_user: gwtest`)
|
||||
// writeFile(t, dir, "config.gateway.yaml", `
|
||||
// chat:
|
||||
// telegram:
|
||||
// token_env: TELEGRAM_TOKEN
|
||||
// web:
|
||||
// listen: "0.0.0.0:9090"
|
||||
// `)
|
||||
|
||||
// cfg, err := loadDir(dir, "")
|
||||
// if err != nil {
|
||||
// t.Fatalf("LoadDir: %v", err)
|
||||
// }
|
||||
// if cfg.Chat.Telegram.TokenEnv != "TELEGRAM_TOKEN" {
|
||||
// t.Errorf("Telegram token_env = %q", cfg.Chat.Telegram.TokenEnv)
|
||||
// }
|
||||
// if cfg.Web.Listen != "0.0.0.0:9090" {
|
||||
// t.Errorf("Web listen = %q", cfg.Web.Listen)
|
||||
// }
|
||||
// }
|
||||
|
||||
// ── 4. Models feature file ────────────────────────────────────────
|
||||
|
||||
// func TestLoadDirModelsConfig(t *testing.T) {
|
||||
// dir := tmpConfigDir(t)
|
||||
// writeFile(t, dir, "config.yaml", `bot_user: modeltest`)
|
||||
// writeFile(t, dir, "config.models.yaml", `
|
||||
// models:
|
||||
// triage: deepseek/deepseek-v4
|
||||
// planner: anthropic/claude-sonnet
|
||||
// builder: anthropic/claude-sonnet
|
||||
// providers:
|
||||
// deepseek:
|
||||
// class: deepseek
|
||||
// api_key_env: DEEPSEEK_KEY
|
||||
// anthropic:
|
||||
// class: anthropic
|
||||
// api_key_env: ANTHROPIC_KEY
|
||||
// `)
|
||||
|
||||
// cfg, err := loadDir(dir, "")
|
||||
// if err != nil {
|
||||
// t.Fatalf("LoadDir: %v", err)
|
||||
// }
|
||||
// if cfg.Models["triage"] != "deepseek/deepseek-v4" {
|
||||
// t.Errorf("triage model = %q", cfg.Models["triage"])
|
||||
// }
|
||||
// if cfg.Models["planner"] != "anthropic/claude-sonnet" {
|
||||
// t.Errorf("planner model = %q", cfg.Models["planner"])
|
||||
// }
|
||||
// if len(cfg.Providers) != 2 {
|
||||
// t.Fatalf("expected 2 providers, got %d", len(cfg.Providers))
|
||||
// }
|
||||
// ds, ok := cfg.Providers["deepseek"]
|
||||
// if !ok || ds.Class != "deepseek" || ds.APIKeyEnv != "DEEPSEEK_KEY" {
|
||||
// t.Errorf("deepseek provider = %+v", ds)
|
||||
// }
|
||||
// }
|
||||
|
||||
// ── 6. Tools feature file ─────────────────────────────────────────
|
||||
|
||||
// func TestLoadDirToolsConfig(t *testing.T) {
|
||||
// dir := tmpConfigDir(t)
|
||||
// writeFile(t, dir, "config.yaml", `bot_user: tooltest`)
|
||||
// writeFile(t, dir, "config.tools.yaml", `
|
||||
// mcp_servers:
|
||||
// - name: filesystem
|
||||
// transport: stdio
|
||||
// command: npx
|
||||
// args: ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
|
||||
// - name: web-search
|
||||
// transport: http
|
||||
// url: https://search-mcp.example.test
|
||||
// tool_policy:
|
||||
// max_result_chars: 100000
|
||||
// `)
|
||||
|
||||
// cfg, err := loadDir(dir, "")
|
||||
// if err != nil {
|
||||
// t.Fatalf("LoadDir: %v", err)
|
||||
// }
|
||||
// if len(cfg.Tools.MCPServers) != 2 {
|
||||
// t.Fatalf("expected 2 MCP servers, got %d", len(cfg.Tools.MCPServers))
|
||||
// }
|
||||
// if cfg.Tools.MCPServers[0].Name != "filesystem" {
|
||||
// t.Errorf("server[0].name = %q", cfg.Tools.MCPServers[0].Name)
|
||||
// }
|
||||
// if cfg.Tools.MCPServers[0].Transport != "stdio" {
|
||||
// t.Errorf("server[0].transport = %q", cfg.Tools.MCPServers[0].Transport)
|
||||
// }
|
||||
// if cfg.Tools.MCPServers[1].Transport != "http" {
|
||||
// t.Errorf("server[1].transport = %q", cfg.Tools.MCPServers[1].Transport)
|
||||
// }
|
||||
// if cfg.Tools.Policy.MaxResultChars != 100000 {
|
||||
// t.Errorf("max_result_chars = %d", cfg.Tools.Policy.MaxResultChars)
|
||||
// }
|
||||
// }
|
||||
|
||||
// ── 7. Identities feature file ────────────────────────────────────
|
||||
|
||||
// func TestLoadDirIdentitiesConfig(t *testing.T) {
|
||||
// dir := tmpConfigDir(t)
|
||||
// writeFile(t, dir, "config.yaml", `bot_user: idtest`)
|
||||
// writeFile(t, dir, "config.identities.yaml", `
|
||||
// identities:
|
||||
// - name: primary
|
||||
// bot_user: archie
|
||||
// forge:
|
||||
// type: gitea
|
||||
// host: https://git.example.test
|
||||
// token:
|
||||
// engine: env
|
||||
// key: ARCHIE_TOKEN
|
||||
// repos:
|
||||
// - owner: sam
|
||||
// name: archie-core
|
||||
// ecosystem: go
|
||||
// - name: secondary
|
||||
// bot_user: winter
|
||||
// forge:
|
||||
// type: gitea
|
||||
// host: https://git.example.test
|
||||
// token:
|
||||
// engine: env
|
||||
// key: WINTER_TOKEN
|
||||
// repos:
|
||||
// - owner: sam
|
||||
// name: example-service
|
||||
// ecosystem: go
|
||||
// `)
|
||||
|
||||
// cfg, err := loadDir(dir, "")
|
||||
// if err != nil {
|
||||
// t.Fatalf("LoadDir: %v", err)
|
||||
// }
|
||||
// if len(cfg.Identities) != 2 {
|
||||
// t.Fatalf("expected 2 identities, got %d", len(cfg.Identities))
|
||||
// }
|
||||
// if cfg.Identities[0].Name != "primary" {
|
||||
// t.Errorf("identities[0].name = %q", cfg.Identities[0].Name)
|
||||
// }
|
||||
// if cfg.Identities[1].Name != "secondary" {
|
||||
// t.Errorf("identities[1].name = %q", cfg.Identities[1].Name)
|
||||
// }
|
||||
// if cfg.Identities[0].Forge.Token != (secret.SecretRef{Engine: "env", Key: "ARCHIE_TOKEN"}) {
|
||||
// t.Errorf("identities[0].forge.token = %#v", cfg.Identities[0].Forge.Token)
|
||||
// }
|
||||
// }
|
||||
|
||||
// ── 8. conf.d/ additional feature files ─────────────────────────
|
||||
|
||||
// func TestLoadDirConfigDExtraFeatures(t *testing.T) {
|
||||
// dir := tmpConfigDir(t)
|
||||
// writeFile(t, dir, "config.yaml", `bot_user: extratest`)
|
||||
// // A third-party plugin could drop its config here.
|
||||
// writeFile(t, dir, "conf.d/custom-tool.yaml", `
|
||||
// custom_tools:
|
||||
// - name: my-analyzer
|
||||
// command: /usr/local/bin/analyzer
|
||||
// `)
|
||||
|
||||
// cfg, err := loadDir(dir, "")
|
||||
// if err != nil {
|
||||
// t.Fatalf("LoadDir: %v", err)
|
||||
// }
|
||||
// // Extra features are accessible via a generic key-value map.
|
||||
// if cfg.Extra == nil {
|
||||
// t.Fatal("Extra should not be nil when conf.d/ files are present")
|
||||
// }
|
||||
// custom, ok := cfg.Extra["custom-tool"]
|
||||
// if !ok {
|
||||
// t.Fatal("Extra should contain 'custom-tool' key from conf.d/custom-tool.yaml")
|
||||
// }
|
||||
// if customMap, ok := custom.(map[string]any); ok {
|
||||
// tools, ok := customMap["custom_tools"].([]any)
|
||||
// if !ok || len(tools) != 1 {
|
||||
// t.Errorf("custom_tools = %v", customMap["custom_tools"])
|
||||
// }
|
||||
// } else {
|
||||
// t.Errorf("extra value should be map[string]any, got %T", custom)
|
||||
// }
|
||||
// }
|
||||
|
||||
// func TestLoadDirYamlTakesPrecedenceOverToml(t *testing.T) {
|
||||
// dir := tmpConfigDir(t)
|
||||
// // Both exist -- YAML wins.
|
||||
// writeFile(t, dir, "config.yaml", `bot_user: yaml-wins`)
|
||||
// writeFile(t, dir, "config.toml", `bot_user = "toml-loses"`)
|
||||
|
||||
// cfg, err := loadDir(dir, "")
|
||||
// if err != nil {
|
||||
// t.Fatalf("LoadDir: %v", err)
|
||||
// }
|
||||
// if cfg.BotUser != "yaml-wins" {
|
||||
// t.Errorf("BotUser = %q, want yaml-wins (YAML must take precedence)", cfg.BotUser)
|
||||
// }
|
||||
// }
|
||||
|
||||
// ── 10. Overlay support ────────────────────────────────────────────
|
||||
|
||||
// func TestLoadDirOverlay(t *testing.T) {
|
||||
// baseDir := tmpConfigDir(t)
|
||||
// writeFile(t, baseDir, "config.yaml", `
|
||||
// bot_user: base-bot
|
||||
// work_dir: /base/work
|
||||
// max_retries: 3
|
||||
// `)
|
||||
// writeFile(t, baseDir, "config.models.yaml", `
|
||||
// models:
|
||||
// triage: base/model
|
||||
// `)
|
||||
|
||||
// overlayDir := tmpConfigDir(t)
|
||||
// // Overlay only needs to specify what differs.
|
||||
// writeFile(t, overlayDir, "config.yaml", `
|
||||
// bot_user: overlay-bot
|
||||
// `)
|
||||
// writeFile(t, overlayDir, "config.models.yaml", `
|
||||
// models:
|
||||
// triage: overlay/model
|
||||
// planner: overlay/planner
|
||||
// `)
|
||||
|
||||
// cfg, err := loadDir(baseDir, overlayDir)
|
||||
// if err != nil {
|
||||
// t.Fatalf("LoadDir: %v", err)
|
||||
// }
|
||||
// // Overridden by overlay.
|
||||
// if cfg.BotUser != "overlay-bot" {
|
||||
// t.Errorf("BotUser = %q, want overlay-bot", cfg.BotUser)
|
||||
// }
|
||||
// // Inherited from base (not mentioned in overlay).
|
||||
// if cfg.WorkDir != "/base/work" {
|
||||
// t.Errorf("WorkDir = %q, want /base/work (inherited from base)", cfg.WorkDir)
|
||||
// }
|
||||
// if cfg.MaxRetries != 3 {
|
||||
// t.Errorf("MaxRetries = %d, want 3 (inherited from base)", cfg.MaxRetries)
|
||||
// }
|
||||
// // Model from overlay takes precedence; model only in overlay is merged.
|
||||
// if cfg.Models["triage"] != "overlay/model" {
|
||||
// t.Errorf("triage = %q, want overlay/model", cfg.Models["triage"])
|
||||
// }
|
||||
// if cfg.Models["planner"] != "overlay/planner" {
|
||||
// t.Errorf("planner = %q, want overlay/planner (new key from overlay)", cfg.Models["planner"])
|
||||
// }
|
||||
// }
|
||||
|
||||
// func TestLoadDirOverlayFeatureFileOnlyInOverlay(t *testing.T) {
|
||||
// baseDir := tmpConfigDir(t)
|
||||
// writeFile(t, baseDir, "config.yaml", `bot_user: base-only`)
|
||||
|
||||
// overlayDir := tmpConfigDir(t)
|
||||
// // Overlay adds a feature file not present in base.
|
||||
// writeFile(t, overlayDir, "config.yaml", `bot_user: override-bot`)
|
||||
// writeFile(t, overlayDir, "config.gateway.yaml", `
|
||||
// chat:
|
||||
// telegram:
|
||||
// token_env: OVERLAY_TG_TOKEN
|
||||
// `)
|
||||
|
||||
// cfg, err := loadDir(baseDir, overlayDir)
|
||||
// if err != nil {
|
||||
// t.Fatalf("LoadDir: %v", err)
|
||||
// }
|
||||
// if cfg.Chat.Telegram.TokenEnv != "OVERLAY_TG_TOKEN" {
|
||||
// t.Errorf("Telegram token_env = %q, want OVERLAY_TG_TOKEN (feature file from overlay)", cfg.Chat.Telegram.TokenEnv)
|
||||
// }
|
||||
// }
|
||||
|
||||
// func TestLoadDirOverlayEmptyDirIsNoop(t *testing.T) {
|
||||
// baseDir := tmpConfigDir(t)
|
||||
// writeFile(t, baseDir, "config.yaml", `bot_user: base-only`)
|
||||
|
||||
// overlayDir := tmpConfigDir(t)
|
||||
// // Empty overlay directory -- same as calling loadDir(baseDir, "").
|
||||
|
||||
// cfg, err := loadDir(baseDir, overlayDir)
|
||||
// if err != nil {
|
||||
// t.Fatalf("LoadDir: %v", err)
|
||||
// }
|
||||
// if cfg.BotUser != "base-only" {
|
||||
// t.Errorf("BotUser = %q, want base-only", cfg.BotUser)
|
||||
// }
|
||||
// }
|
||||
|
||||
// ── 11. Validation ─────────────────────────────────────────────────
|
||||
|
||||
// func TestLoadDirRejectsInvalidFeatureFile(t *testing.T) {
|
||||
// dir := tmpConfigDir(t)
|
||||
// writeFile(t, dir, "config.yaml", `bot_user: valid`)
|
||||
// writeFile(t, dir, "config.models.yaml", `this: [is: not: valid: yaml: }}`)
|
||||
|
||||
// _, err := loadDir(dir, "")
|
||||
// if err == nil {
|
||||
// t.Fatal("expected error for malformed feature file")
|
||||
// }
|
||||
// }
|
||||
|
||||
// func TestLoadDirRejectsUnknownFeatureFile(t *testing.T) {
|
||||
// dir := tmpConfigDir(t)
|
||||
// writeFile(t, dir, "config.yaml", `bot_user: valid`)
|
||||
// // config.unknown.yaml is not a known feature -- should error, not silently ignore.
|
||||
// writeFile(t, dir, "config.unknown.yaml", `foo: bar`)
|
||||
|
||||
// _, err := loadDir(dir, "")
|
||||
// if err == nil {
|
||||
// t.Fatal("expected error for unknown feature file (silent ignore would hide typos)")
|
||||
// }
|
||||
// if !strings.Contains(err.Error(), "unknown") && !strings.Contains(err.Error(), "unrecognized") {
|
||||
// t.Errorf("error should mention unknown/unrecognized file, got: %v", err)
|
||||
// }
|
||||
// }
|
||||
|
||||
// func TestLoadDirRejectsDuplicateFeatureFiles(t *testing.T) {
|
||||
// dir := tmpConfigDir(t)
|
||||
// writeFile(t, dir, "config.yaml", `bot_user: dupetest`)
|
||||
// // Two files claiming the same feature.
|
||||
// writeFile(t, dir, "config.gateway.yaml", `chat: {telegram: {token_env: FIRST}}`)
|
||||
// writeFile(t, dir, "conf.d/gateway.yaml", `chat: {telegram: {token_env: SECOND}}`)
|
||||
|
||||
// _, err := loadDir(dir, "")
|
||||
// if err == nil {
|
||||
// t.Fatal("expected error for duplicate feature files")
|
||||
// }
|
||||
// if !strings.Contains(err.Error(), "duplicate") && !strings.Contains(err.Error(), "gateway") {
|
||||
// t.Errorf("error should mention duplicate and the feature name, got: %v", err)
|
||||
// }
|
||||
// }
|
||||
|
||||
// func TestLoadDirRequiresConfigYamlOrConfigToml(t *testing.T) {
|
||||
// dir := tmpConfigDir(t)
|
||||
// // Neither config.yaml nor config.toml exists.
|
||||
// _, err := loadDir(dir, "")
|
||||
// if err == nil || !strings.Contains(err.Error(), "config.yaml") && !strings.Contains(err.Error(), "config.toml") {
|
||||
// t.Errorf("expected error about missing config.yaml or config.toml, got: %v", err)
|
||||
// }
|
||||
// }
|
||||
|
||||
// ── 12. Agent config (still supported) ────────────────────────────
|
||||
|
||||
// func TestLoadDirAgentConfig(t *testing.T) {
|
||||
// dir := tmpConfigDir(t)
|
||||
// writeFile(t, dir, "config.yaml", `
|
||||
// bot_user: agenttest
|
||||
// agent:
|
||||
// mode: subprocess
|
||||
// command: /usr/local/bin/archie-agent
|
||||
// env:
|
||||
// - DEBUG
|
||||
// - NO_COLOR
|
||||
// budgets:
|
||||
// max_steps: 60
|
||||
|
||||
// wall_clock: 30m
|
||||
// `)
|
||||
|
||||
// cfg, err := loadDir(dir, "")
|
||||
// if err != nil {
|
||||
// t.Fatalf("LoadDir: %v", err)
|
||||
// }
|
||||
// if cfg.Agent.Mode != "subprocess" {
|
||||
// t.Errorf("Agent.Mode = %q", cfg.Agent.Mode)
|
||||
// }
|
||||
// if cfg.Agent.Command != "/usr/local/bin/archie-agent" {
|
||||
// t.Errorf("Agent.Command = %q", cfg.Agent.Command)
|
||||
// }
|
||||
// if cfg.Budgets.MaxSteps != 60 {
|
||||
// t.Errorf("Budgets.MaxSteps = %d", cfg.Budgets.MaxSteps)
|
||||
// }
|
||||
// }
|
||||
|
||||
// ── 13. NATS and Containers (still in daemon config) ──────────────
|
||||
|
||||
// func TestLoadDirNATSAndContainersConfig(t *testing.T) {
|
||||
// dir := tmpConfigDir(t)
|
||||
// writeFile(t, dir, "config.yaml", `
|
||||
// bot_user: infra
|
||||
// nats:
|
||||
// url: nats://nats.example:4222
|
||||
// token_env: NATS_TOKEN
|
||||
// containers:
|
||||
// image: ghcr.io/sam/archie-agent:latest
|
||||
// max_concurrency: 4
|
||||
// pull_policy: always
|
||||
// `)
|
||||
|
||||
// cfg, err := loadDir(dir, "")
|
||||
// if err != nil {
|
||||
// t.Fatalf("LoadDir: %v", err)
|
||||
// }
|
||||
// if cfg.NATS.URL != "nats://nats.example:4222" {
|
||||
// t.Errorf("NATS.URL = %q", cfg.NATS.URL)
|
||||
// }
|
||||
// if cfg.Containers.Image != "ghcr.io/sam/archie-agent:latest" {
|
||||
// t.Errorf("Containers.Image = %q", cfg.Containers.Image)
|
||||
// }
|
||||
// }
|
||||
|
||||
// ── 14. Dispatch config ─────────────────────────────────────────────
|
||||
|
||||
// func TestLoadDirDispatchConfig(t *testing.T) {
|
||||
// dir := tmpConfigDir(t)
|
||||
// writeFile(t, dir, "config.yaml", `
|
||||
// bot_user: dispatchtest
|
||||
// dispatch:
|
||||
// trigger: label
|
||||
// ack_reaction: rock
|
||||
// labels:
|
||||
// queued: bot:queued
|
||||
// working: bot:working
|
||||
// pr: bot:pr
|
||||
// `)
|
||||
|
||||
// cfg, err := loadDir(dir, "")
|
||||
// if err != nil {
|
||||
// t.Fatalf("LoadDir: %v", err)
|
||||
// }
|
||||
// if cfg.Dispatch.Trigger != "label" {
|
||||
// t.Errorf("Dispatch.Trigger = %q", cfg.Dispatch.Trigger)
|
||||
// }
|
||||
// if cfg.Dispatch.AckReaction != "rock" {
|
||||
// t.Errorf("Dispatch.AckReaction = %q", cfg.Dispatch.AckReaction)
|
||||
// }
|
||||
// if cfg.Dispatch.Labels["queued"] != "bot:queued" {
|
||||
// t.Errorf("Dispatch.Labels[queued] = %q", cfg.Dispatch.Labels["queued"])
|
||||
// }
|
||||
// }
|
||||
|
||||
// ── 15. Notify config ───────────────────────────────────────────────
|
||||
|
||||
// func TestLoadDirNotifyConfig(t *testing.T) {
|
||||
// dir := tmpConfigDir(t)
|
||||
// writeFile(t, dir, "config.yaml", `
|
||||
// bot_user: notifytest
|
||||
// notify:
|
||||
// webhook: https://hooks.example.test/archie
|
||||
// `)
|
||||
|
||||
// cfg, err := loadDir(dir, "")
|
||||
// if err != nil {
|
||||
// t.Fatalf("LoadDir: %v", err)
|
||||
// }
|
||||
// if cfg.Notify.Webhook != "https://hooks.example.test/archie" {
|
||||
// t.Errorf("Notify.Webhook = %q", cfg.Notify.Webhook)
|
||||
// }
|
||||
// }
|
||||
|
||||
// ── 16. DiffCapLines config ─────────────────────────────────────────
|
||||
|
||||
// func TestLoadDirDiffCapLinesConfig(t *testing.T) {
|
||||
// dir := tmpConfigDir(t)
|
||||
// writeFile(t, dir, "config.yaml", `
|
||||
// bot_user: difftest
|
||||
// diff_cap_lines: 200
|
||||
// `)
|
||||
|
||||
// cfg, err := loadDir(dir, "")
|
||||
// if err != nil {
|
||||
// t.Fatalf("LoadDir: %v", err)
|
||||
// }
|
||||
// if cfg.DiffCapLines != 200 {
|
||||
// t.Errorf("DiffCapLines = %d, want 200", cfg.DiffCapLines)
|
||||
// }
|
||||
// }
|
||||
|
||||
// ── 17. Skills and Plugin dirs ──────────────────────────────────────
|
||||
|
||||
// func TestLoadDirSkillsAndPluginDirs(t *testing.T) {
|
||||
// dir := tmpConfigDir(t)
|
||||
// writeFile(t, dir, "config.yaml", `
|
||||
// bot_user: skillstest
|
||||
// skills_dir: /opt/archie/skills
|
||||
// plugin_dir: /opt/archie/plugins
|
||||
// `)
|
||||
|
||||
// cfg, err := loadDir(dir, "")
|
||||
// if err != nil {
|
||||
// t.Fatalf("LoadDir: %v", err)
|
||||
// }
|
||||
// if cfg.SkillsDir != "/opt/archie/skills" {
|
||||
// t.Errorf("SkillsDir = %q", cfg.SkillsDir)
|
||||
// }
|
||||
// if cfg.PluginDir != "/opt/archie/plugins" {
|
||||
// t.Errorf("PluginDir = %q", cfg.PluginDir)
|
||||
// }
|
||||
// }
|
||||
|
||||
// func TestLoadDirSecretEngineDir(t *testing.T) {
|
||||
// dir := tmpConfigDir(t)
|
||||
// writeFile(t, dir, "config.yaml", `
|
||||
// bot_user: secrettest
|
||||
// secret_engine_dir: /opt/archie/secret-engines
|
||||
// `)
|
||||
|
||||
// cfg, err := loadDir(dir, "")
|
||||
// if err != nil {
|
||||
// t.Fatal(err)
|
||||
// }
|
||||
// if got := cfg.SecretEngineDir; got != "/opt/archie/secret-engines" {
|
||||
// t.Fatalf("SecretEngineDir = %q", got)
|
||||
// }
|
||||
// }
|
||||
|
||||
// func TestLoadDirExpandsSecretEngineHome(t *testing.T) {
|
||||
// home := t.TempDir()
|
||||
// t.Setenv("HOME", home)
|
||||
// dir := tmpConfigDir(t)
|
||||
// writeFile(t, dir, "config.yaml", `
|
||||
// bot_user: secrettest
|
||||
// secret_engine_dir: ~/.config/archie/secret-engines
|
||||
// `)
|
||||
// cfg, err := loadDir(dir, "")
|
||||
// if err != nil {
|
||||
// t.Fatal(err)
|
||||
// }
|
||||
// want := filepath.Join(home, ".config", "archie", "secret-engines")
|
||||
// if cfg.SecretEngineDir != want {
|
||||
// t.Fatalf("SecretEngineDir = %q, want %q", cfg.SecretEngineDir, want)
|
||||
// }
|
||||
// }
|
||||
|
||||
// ── 18. API stability: ForTask must still work ─────────────────────
|
||||
|
||||
// func TestLoadDirForTaskRoundTrip(t *testing.T) {
|
||||
// dir := tmpConfigDir(t)
|
||||
// writeFile(t, dir, "config.yaml", `
|
||||
// bot_user: tasktest
|
||||
// diff_cap_lines: 321
|
||||
// `)
|
||||
// writeFile(t, dir, "config.models.yaml", `
|
||||
// models:
|
||||
// builder: anthropic/claude
|
||||
// planner: openai/gpt
|
||||
// `)
|
||||
|
||||
// cfg, err := loadDir(dir, "")
|
||||
// if err != nil {
|
||||
// t.Fatalf("LoadDir: %v", err)
|
||||
// }
|
||||
|
||||
// taskCfg := cfg.ForTask()
|
||||
// // ForTask must still carry the merged models.
|
||||
// if taskCfg.Models["builder"] != "anthropic/claude" {
|
||||
// t.Errorf("ForTask models[builder] = %q", taskCfg.Models["builder"])
|
||||
// }
|
||||
// if taskCfg.Models["planner"] != "openai/gpt" {
|
||||
// t.Errorf("ForTask models[planner] = %q", taskCfg.Models["planner"])
|
||||
// }
|
||||
// if taskCfg.DiffCapLines != 321 {
|
||||
// t.Errorf("ForTask DiffCapLines = %d", taskCfg.DiffCapLines)
|
||||
// }
|
||||
// // ForTask must NOT carry secret references.
|
||||
// roundTripped := taskCfg.ToConfig()
|
||||
// if roundTripped.Forge.Token != (secret.SecretRef{}) {
|
||||
// t.Error("ForTask must not leak Forge.Token")
|
||||
// }
|
||||
// }
|
||||
|
||||
// ── 19. Existing Load function must be preserved ────────────────────
|
||||
|
||||
func TestLoadFunctionStillWorks(t *testing.T) {
|
||||
dir := tmpConfigDir(t)
|
||||
writeFile(t, dir, "config.toml", `
|
||||
bot_user = "oldstyle"
|
||||
poll_interval = "120s"
|
||||
|
||||
[forge]
|
||||
type = "github"
|
||||
token = { engine = "env", key = "GH_TOKEN" }
|
||||
|
||||
[[repos]]
|
||||
owner = "acme"
|
||||
name = "old-repo"
|
||||
`)
|
||||
|
||||
cfg, err := loadFile(filepath.Join(dir, "config.toml"))
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if cfg.BotUser != "oldstyle" {
|
||||
t.Errorf("BotUser = %q", cfg.BotUser)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadOverlayFunctionStillWorks(t *testing.T) {
|
||||
baseDir := tmpConfigDir(t)
|
||||
overlayDir := tmpConfigDir(t)
|
||||
writeFile(t, baseDir, "config.toml", `
|
||||
bot_user = "base"
|
||||
max_retries = 2
|
||||
[forge]
|
||||
type = "github"
|
||||
token = { engine = "env", key = "BASE_TOKEN" }
|
||||
[[repos]]
|
||||
owner = "acme"
|
||||
name = "base-repo"
|
||||
`)
|
||||
writeFile(t, overlayDir, "config.toml", `
|
||||
bot_user = "overlaid"
|
||||
max_retries = 5
|
||||
`)
|
||||
|
||||
cfg, err := loadOverlay(
|
||||
filepath.Join(baseDir, "config.toml"),
|
||||
filepath.Join(overlayDir, "config.toml"),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadOverlay: %v", err)
|
||||
}
|
||||
if cfg.BotUser != "overlaid" {
|
||||
t.Errorf("BotUser = %q, want overlaid", cfg.BotUser)
|
||||
}
|
||||
if cfg.MaxRetries != 5 {
|
||||
t.Errorf("MaxRetries = %d, want 5 (overridden by overlay)", cfg.MaxRetries)
|
||||
}
|
||||
// Inherited from base.
|
||||
if cfg.Forge.Token != (secret.SecretRef{Engine: "env", Key: "BASE_TOKEN"}) {
|
||||
t.Errorf("Forge.Token = %#v, want {env BASE_TOKEN} (inherited)", cfg.Forge.Token)
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package configuration
|
||||
|
||||
import "github.com/samcharles93/archie-core/internal/config"
|
||||
|
||||
// These helpers unwrap Document for tests that only assert on the resulting
|
||||
// settings. Tests covering provenance use the Loader methods directly.
|
||||
|
||||
func loadFile(path string) (config.Config, error) {
|
||||
return unwrap(New(nil).File(path))
|
||||
}
|
||||
|
||||
func loadOverlay(basePath, overlayPath string) (config.Config, error) {
|
||||
return unwrap(New(nil).Overlay(basePath, overlayPath))
|
||||
}
|
||||
|
||||
func unwrap(doc *Document, err error) (config.Config, error) {
|
||||
if err != nil {
|
||||
return config.Config{}, err
|
||||
}
|
||||
return doc.Config, nil
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
)
|
||||
|
||||
// TestIdentityNameRuleAgreesAcrossFileAndStore pins the one field both paths
|
||||
// judge: a configured identity name becomes the store identity's display name
|
||||
// (internal/app/archied.configuredIdentityNames ->
|
||||
// postgres.Store.BootstrapIdentities -> identity.New), so a name the file
|
||||
// loader accepts must be a name the store accepts, and a name it refuses must
|
||||
// be refused on both sides. Two rule sets on the same string is how a name of
|
||||
// spaces passed the file's `name == ""` check and then failed the store's
|
||||
// trimmed check -- the file accepted a config the State Store could not boot
|
||||
// with.
|
||||
func TestIdentityNameRuleAgreesAcrossFileAndStore(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
configured string
|
||||
wantReject bool
|
||||
}{
|
||||
{name: "ordinary name", configured: "personal"},
|
||||
{name: "name padded with whitespace", configured: " personal "},
|
||||
{name: "whitespace-only name", configured: " ", wantReject: true},
|
||||
{name: "empty name", configured: "", wantReject: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cfg := minimalValidConfig()
|
||||
cfg.BotUser = ""
|
||||
cfg.Identities = []config.IdentityConfig{{
|
||||
Name: tt.configured,
|
||||
BotUser: "archie-personal",
|
||||
Repos: []config.Repo{{Owner: "acme", Name: "app"}},
|
||||
Forge: config.Forge{Type: "none"},
|
||||
}}
|
||||
fileErr := Validate(&cfg)
|
||||
_, storeErr := identity.New(identity.StableID(tt.configured), identity.KindBot, tt.configured)
|
||||
if (fileErr != nil) != tt.wantReject {
|
||||
t.Fatalf("Validate(identities[0].name=%q) = %v, wantReject=%v", tt.configured, fileErr, tt.wantReject)
|
||||
}
|
||||
if (storeErr != nil) != tt.wantReject {
|
||||
t.Fatalf("identity.New(%q) = %v, wantReject=%v", tt.configured, storeErr, tt.wantReject)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestBotUserNameRuleAgreesAcrossFileAndStore is the single-identity half of
|
||||
// the same rule: configuredIdentityNames turns bot_user into the same display
|
||||
// name, and BootstrapIdentities trims it the way identity.New does, so the
|
||||
// file loader's `bot_user == ""` test must reject a name of spaces exactly as
|
||||
// the store does.
|
||||
func TestBotUserNameRuleAgreesAcrossFileAndStore(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
botUser string
|
||||
wantReject bool
|
||||
}{
|
||||
{name: "ordinary bot user", botUser: "archie-bot"},
|
||||
{name: "bot user padded with whitespace", botUser: " archie-bot "},
|
||||
{name: "whitespace-only bot user", botUser: " ", wantReject: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cfg := minimalValidConfig()
|
||||
cfg.BotUser = tt.botUser
|
||||
fileErr := Validate(&cfg)
|
||||
trimmed := strings.TrimSpace(tt.botUser)
|
||||
_, storeErr := identity.New(identity.StableID(trimmed), identity.KindBot, trimmed)
|
||||
if (fileErr != nil) != tt.wantReject {
|
||||
t.Fatalf("Validate(bot_user=%q) = %v, wantReject=%v", tt.botUser, fileErr, tt.wantReject)
|
||||
}
|
||||
if (storeErr != nil) != tt.wantReject {
|
||||
t.Fatalf("identity.New(bot_user=%q) = %v, wantReject=%v", tt.botUser, storeErr, tt.wantReject)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,936 +0,0 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
func TestLoadDispatchAckReaction(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
dispatch string
|
||||
wantAck string
|
||||
}{
|
||||
{name: "default", wantAck: "eyes"},
|
||||
{name: "disabled", dispatch: "\n[dispatch]\nack_reaction = \"off\"\n", wantAck: ""},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" + tt.dispatch + "\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Dispatch.AckReaction != tt.wantAck {
|
||||
t.Errorf("AckReaction: got %q, want %q", cfg.Dispatch.AckReaction, tt.wantAck)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadExpandsConfiguredHomePaths(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := `
|
||||
bot_user = "widget"
|
||||
work_dir = "~/archie/work"
|
||||
state_dir = "~/archie/state"
|
||||
plugin_dir = "~/archie/plugins"
|
||||
module_dir = "~/archie/modules"
|
||||
skills_dir = "~/archie/skills"
|
||||
|
||||
[chat]
|
||||
workspace = "~/archie/workspace"
|
||||
|
||||
[[repos]]
|
||||
owner = "acme"
|
||||
name = "app"
|
||||
`
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wants := map[string]struct {
|
||||
got string
|
||||
want string
|
||||
}{
|
||||
"work_dir": {got: cfg.WorkDir, want: filepath.Join(home, "archie", "work")},
|
||||
"state_dir": {got: cfg.StateDir, want: filepath.Join(home, "archie", "state")},
|
||||
"chat.workspace": {got: cfg.Chat.Workspace, want: filepath.Join(home, "archie", "workspace")},
|
||||
// The operator-facing plugin, module and skills directories take the
|
||||
// same ~ as every other path in the file: config.example.toml tells
|
||||
// operators to write them that way, and a value that stays literal is
|
||||
// a directory that silently does not exist (no plugins load, no
|
||||
// modules load, no skills beyond the built-ins).
|
||||
"plugin_dir": {got: cfg.PluginDir, want: filepath.Join(home, "archie", "plugins")},
|
||||
"module_dir": {got: cfg.ModuleDir, want: filepath.Join(home, "archie", "modules")},
|
||||
"skills_dir": {got: cfg.SkillsDir, want: filepath.Join(home, "archie", "skills")},
|
||||
}
|
||||
for name, tt := range wants {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
if tt.got != tt.want {
|
||||
t.Errorf("got %q, want %q", tt.got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// state_dir defaults to archie's directory under the data home.
|
||||
func TestStateDirDefaultsToTheDataHome(t *testing.T) {
|
||||
dataHome := t.TempDir()
|
||||
t.Setenv("XDG_DATA_HOME", dataHome)
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := `
|
||||
bot_user = "widget"
|
||||
|
||||
[[repos]]
|
||||
owner = "acme"
|
||||
name = "app"
|
||||
`
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := filepath.Join(dataHome, "archie"); cfg.StateDir != want {
|
||||
t.Fatalf("StateDir = %q, want %q", cfg.StateDir, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveSelectsFileFormatsAndDirectories(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
prepare func(t *testing.T, dir string) string
|
||||
wantUser string
|
||||
wantPath string
|
||||
}{
|
||||
{
|
||||
name: "toml file",
|
||||
prepare: func(t *testing.T, dir string) string {
|
||||
path := filepath.Join(dir, "config.toml")
|
||||
if err := os.WriteFile(path, []byte("bot_user = \"toml-bot\"\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
},
|
||||
wantUser: "toml-bot", wantPath: "config.toml",
|
||||
},
|
||||
{
|
||||
name: "yaml file",
|
||||
prepare: func(t *testing.T, dir string) string {
|
||||
path := filepath.Join(dir, "config.yaml")
|
||||
if err := os.WriteFile(path, []byte("bot_user: yaml-bot\nrepos:\n - owner: acme\n name: app\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
},
|
||||
wantUser: "yaml-bot", wantPath: "config.yaml",
|
||||
},
|
||||
{
|
||||
name: "directory",
|
||||
prepare: func(t *testing.T, dir string) string {
|
||||
if err := os.WriteFile(filepath.Join(dir, "config.yaml"), []byte("bot_user: directory-bot\nrepos:\n - owner: acme\n name: app\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return dir
|
||||
},
|
||||
wantUser: "directory-bot", wantPath: "config.yaml",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
doc, err := New(nil).Resolve(tt.prepare(t, dir), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if doc.Config.BotUser != tt.wantUser {
|
||||
t.Errorf("BotUser = %q, want %q", doc.Config.BotUser, tt.wantUser)
|
||||
}
|
||||
if got := filepath.Base(doc.Provenance.Paths()[0]); got != tt.wantPath {
|
||||
t.Errorf("provenance path = %q, want %q", got, tt.wantPath)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadTelegramTokenSecretRef(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" +
|
||||
"[chat.telegram]\ntoken = { engine = \"bws\", key = \"TELEGRAM_BOT_TOKEN\" }\n" +
|
||||
"[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := secret.SecretRef{Engine: "bws", Key: "TELEGRAM_BOT_TOKEN"}
|
||||
if cfg.Chat.Telegram.Token != want {
|
||||
t.Errorf("Telegram.Token = %#v, want %#v", cfg.Chat.Telegram.Token, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadRejectsInvalidConfigEnumsAndGlobs pins which layer rejects each kind
|
||||
// of invalid value. Every file source produces a BOOTSTRAP document, and the
|
||||
// settings the control plane owns are layered over it later; a stale TOML value
|
||||
// in one of those must not fail the load (docs/prds/runtime-control-plane.md,
|
||||
// "Bootstrap, migration, and recovery"). So a check over a database-owned
|
||||
// setting is asserted with Validate instead -- what boot.runtimeConfig runs over
|
||||
// the document a process will use, and the checks the loader no longer applies.
|
||||
// Each case asserts both halves it applies to, so a check that quietly
|
||||
// disappeared fails the case rather than passing it.
|
||||
func TestLoadRejectsInvalidConfigEnumsAndGlobs(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
wantLoadErr bool
|
||||
}{
|
||||
{
|
||||
name: "dispatch trigger",
|
||||
body: fileConfigPrefix + "[dispatch]\ntrigger = \"labels\"\n",
|
||||
},
|
||||
{
|
||||
name: "provider userinfo",
|
||||
body: fileConfigPrefix + "[providers.openai]\nclass = \"openai\"\nbase_url = \"https://token@example.com/v1\"\n",
|
||||
},
|
||||
{
|
||||
name: "provider query secret",
|
||||
body: fileConfigPrefix + "[providers.openai]\nclass = \"openai\"\nbase_url = \"https://example.com/v1?api_key=secret\"\n",
|
||||
},
|
||||
{
|
||||
name: "test glob",
|
||||
body: fileConfigPrefix + "[[repos]]\nowner = \"acme\"\nname = \"app\"\ntest_glob = \"[\"\n",
|
||||
},
|
||||
{
|
||||
// File-owned settings: no control-plane resource carries them, so
|
||||
// the load path is the layer that has to reject them.
|
||||
name: "forge intake",
|
||||
body: fileConfigPrefix + "[forge]\nintake = \"not-a-real-intake\"\n",
|
||||
wantLoadErr: true,
|
||||
},
|
||||
{
|
||||
name: "memory engine",
|
||||
body: fileConfigPrefix + "[memory]\nengine = \"not-a-real-engine\"\n",
|
||||
wantLoadErr: true,
|
||||
},
|
||||
{
|
||||
name: "negative capture retention",
|
||||
body: fileConfigPrefix + "[capture]\nretention = \"-1h\"\n",
|
||||
wantLoadErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
if err := os.WriteFile(path, []byte(tt.body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
doc, err := New(nil).File(path)
|
||||
if tt.wantLoadErr {
|
||||
if err == nil {
|
||||
t.Fatal("File() = nil error, want the bootstrap document rejected")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("File: %v (a database-owned value must not fail the load)", err)
|
||||
}
|
||||
if err := Validate(&doc.Config); err == nil {
|
||||
t.Fatal("Validate = nil, want the value rejected there")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadToolPolicyDefaultsAndOverrides covers the result-size and turn-budget
|
||||
// limits end to end from TOML. Before these fields carried toml tags they could
|
||||
// not be set from the daemon's config at all, so a test that only exercised
|
||||
// defaulting would have passed against a setting no operator could reach.
|
||||
//
|
||||
// A negative value means "disabled" rather than zero: defaulting cannot tell an
|
||||
// explicit 0 from an absent key, so zero has to stay available as "unset".
|
||||
func TestLoadToolPolicyDefaultsAndOverrides(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
policy string
|
||||
wantMaxResult int
|
||||
wantSpillDir string
|
||||
}{
|
||||
{
|
||||
// SpillDir has no default on purpose: a path outside
|
||||
// chat.workspace is one the read tool refuses, so the model would
|
||||
// be handed a reference it cannot open. Absent means truncate
|
||||
// inline.
|
||||
name: "defaults",
|
||||
wantMaxResult: 50_000,
|
||||
|
||||
wantSpillDir: "",
|
||||
},
|
||||
{
|
||||
name: "explicit values",
|
||||
policy: "[tools.tool_policy]\nmax_result_chars = 1234\nspill_dir = \"/var/spool/archie\"\n",
|
||||
wantMaxResult: 1234,
|
||||
wantSpillDir: "/var/spool/archie",
|
||||
},
|
||||
{
|
||||
name: "negative disables the per-result cap",
|
||||
policy: "[tools.tool_policy]\nmax_result_chars = -1\n",
|
||||
wantMaxResult: -1,
|
||||
wantSpillDir: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" + tt.policy +
|
||||
"\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
policy := cfg.Tools.Policy
|
||||
if policy.MaxResultChars != tt.wantMaxResult {
|
||||
t.Errorf("MaxResultChars = %d, want %d", policy.MaxResultChars, tt.wantMaxResult)
|
||||
}
|
||||
|
||||
if policy.SpillDir != tt.wantSpillDir {
|
||||
t.Errorf("SpillDir = %q, want %q", policy.SpillDir, tt.wantSpillDir)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemovedTurnCapsAreIgnoredByLegacyConfig(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n[budgets]\nmax_tokens = 1\n" +
|
||||
"[tools.tool_policy]\nmax_result_chars = 1234\nturn_budget_chars = 1\n" +
|
||||
"[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
encoded, err := json.Marshal(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, removed := range []string{"max_tokens", "turn_budget_chars"} {
|
||||
if strings.Contains(string(encoded), removed) {
|
||||
t.Fatalf("removed turn cap %q survived config decode: %s", removed, encoded)
|
||||
}
|
||||
}
|
||||
if cfg.Tools.Policy.MaxResultChars != 1234 {
|
||||
t.Fatalf("per-tool result cap = %d, want 1234", cfg.Tools.Policy.MaxResultChars)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadWebFetchDefaultsAndOverrides covers the fetch tool's settings.
|
||||
//
|
||||
// The enabled case matters most: it is a pointer precisely so an operator can
|
||||
// turn the tool off, which a plain bool could not express because defaulting
|
||||
// cannot tell `enabled = false` from an absent key.
|
||||
func TestLoadWebFetchDefaultsAndOverrides(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
webFetch string
|
||||
wantEnabled bool
|
||||
wantTimeout time.Duration
|
||||
wantMaxBytes int64
|
||||
wantPrivate bool
|
||||
}{
|
||||
{
|
||||
name: "defaults",
|
||||
wantEnabled: true,
|
||||
wantTimeout: 30 * time.Second,
|
||||
wantMaxBytes: 2_000_000,
|
||||
},
|
||||
{
|
||||
name: "explicitly disabled",
|
||||
webFetch: "[tools.web_fetch]\nenabled = false\n",
|
||||
wantEnabled: false,
|
||||
wantTimeout: 30 * time.Second,
|
||||
wantMaxBytes: 2_000_000,
|
||||
},
|
||||
{
|
||||
name: "overrides",
|
||||
webFetch: "[tools.web_fetch]\ntimeout = \"5s\"\nmax_bytes = 4096\nallow_private_networks = true\n",
|
||||
wantEnabled: true,
|
||||
wantTimeout: 5 * time.Second,
|
||||
wantMaxBytes: 4096,
|
||||
wantPrivate: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" + tt.webFetch +
|
||||
"\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
wf := cfg.Tools.WebFetch
|
||||
if got := wf.IsEnabled(); got != tt.wantEnabled {
|
||||
t.Errorf("IsEnabled() = %v, want %v", got, tt.wantEnabled)
|
||||
}
|
||||
if got := wf.Timeout.Std(); got != tt.wantTimeout {
|
||||
t.Errorf("Timeout = %s, want %s", got, tt.wantTimeout)
|
||||
}
|
||||
if wf.MaxBytes != tt.wantMaxBytes {
|
||||
t.Errorf("MaxBytes = %d, want %d", wf.MaxBytes, tt.wantMaxBytes)
|
||||
}
|
||||
if wf.AllowPrivateNetworks != tt.wantPrivate {
|
||||
t.Errorf("AllowPrivateNetworks = %v, want %v", wf.AllowPrivateNetworks, tt.wantPrivate)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadContainerVolumeTTL(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ttl string
|
||||
wantTTL time.Duration
|
||||
}{
|
||||
{name: "default", wantTTL: 72 * time.Hour},
|
||||
{name: "explicit", ttl: "volume_ttl = \"6h\"\n", wantTTL: 6 * time.Hour},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" +
|
||||
"[nats]\nurl = \"nats://localhost:4222\"\n" +
|
||||
"[containers]\nimage = \"archie-agent:test\"\n" + tt.ttl +
|
||||
"[[repos]]\nowner = \"acme\"\nname = \"app\"\npersistent_storage = true\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := cfg.Containers.VolumeTTL.Std(); got != tt.wantTTL {
|
||||
t.Fatalf("Containers.VolumeTTL = %s, want %s", got, tt.wantTTL)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadRejectsNegativeContainerVolumeTTL: containers are a control-plane
|
||||
// resource (container-runtime-policies), so a negative volume_ttl is judged by
|
||||
// Validate rather than by the load path -- a stale TOML value in a database-owned
|
||||
// setting must not fail a process's startup. The second half of the assertion is
|
||||
// what keeps dropping the check from passing this test.
|
||||
func TestLoadRejectsNegativeContainerVolumeTTL(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" +
|
||||
"[nats]\nurl = \"nats://localhost:4222\"\n" +
|
||||
"[containers]\nimage = \"archie-agent:test\"\nvolume_ttl = \"-1h\"\n" +
|
||||
"[[repos]]\nowner = \"acme\"\nname = \"app\"\npersistent_storage = true\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
doc, err := New(nil).File(path)
|
||||
if err != nil {
|
||||
t.Fatalf("File: %v (a database-owned value must not fail the load)", err)
|
||||
}
|
||||
if err := Validate(&doc.Config); err == nil {
|
||||
t.Fatal("Validate accepted a negative containers.volume_ttl")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExampleConfigLoads(t *testing.T) {
|
||||
cfg, err := loadFile(filepath.Join("..", "..", "..", "config.example.toml"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Forge.Host != "https://github.com" {
|
||||
t.Errorf("Forge.Host: got %q", cfg.Forge.Host)
|
||||
}
|
||||
if cfg.Dispatch.AckReaction != "eyes" {
|
||||
t.Errorf("Dispatch.AckReaction: got %q", cfg.Dispatch.AckReaction)
|
||||
}
|
||||
// [[repos]] is commented out in the template on purpose: an active
|
||||
// example here would validate as a normal repo (owner/name are only
|
||||
// checked for non-empty) and archied would silently poll one that
|
||||
// doesn't exist. At least one entry is required before archied will
|
||||
// poll anything, but the template cannot supply it -- see the comment
|
||||
// above [[repos]] in config.example.toml.
|
||||
if len(cfg.Repos) != 0 {
|
||||
t.Errorf("Repos: got %+v, want none: config.example.toml's [[repos]] entry is documentation, not a live default", cfg.Repos)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOverlay(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
basePath := filepath.Join(dir, "config.toml")
|
||||
base := "bot_user = \"widget\"\nwork_dir = \"/base/work\"\n" +
|
||||
"[log]\nlevel = \"warn\"\n" +
|
||||
"[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(basePath, []byte(base), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
overlayPath := filepath.Join(dir, "config.docker.toml")
|
||||
overlay := "work_dir = \"/var/lib/archie/work\"\n[log]\nlevel = \"debug\"\n" +
|
||||
"[nats]\nurl = \"nats://nats:4222\"\n" +
|
||||
"[containers]\nimage = \"archie-agent:latest\"\n"
|
||||
if err := os.WriteFile(overlayPath, []byte(overlay), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := loadOverlay(basePath, overlayPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Overlay-set fields win.
|
||||
if cfg.WorkDir != "/var/lib/archie/work" {
|
||||
t.Errorf("WorkDir: got %q, want overlay value", cfg.WorkDir)
|
||||
}
|
||||
if cfg.Log.Level != "debug" {
|
||||
t.Errorf("Log.Level: got %q, want %q", cfg.Log.Level, "debug")
|
||||
}
|
||||
// Fields the overlay omits keep the base value.
|
||||
if cfg.BotUser != "widget" {
|
||||
t.Errorf("BotUser: got %q, want base value", cfg.BotUser)
|
||||
}
|
||||
if len(cfg.Repos) != 1 || cfg.Repos[0].Owner != "acme" {
|
||||
t.Errorf("Repos: got %+v, want base repos", cfg.Repos)
|
||||
}
|
||||
|
||||
// No overlay path behaves like loadFile(basePath).
|
||||
baseOnly, err := loadOverlay(basePath, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if baseOnly.Log.Level != "warn" {
|
||||
t.Errorf("Log.Level with empty overlay: got %q, want %q", baseOnly.Log.Level, "warn")
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolveFileOverlayPreservesOmittedMapEntryFields characterizes the
|
||||
// -config-overlay path at the depth the runtime overlay is already guarded at
|
||||
// (TestApplyOverlayValuesPreservesOmittedNestedFields).
|
||||
//
|
||||
// It goes through Loader.Resolve, the production entry point, because the
|
||||
// hazard was a property of how the overlay file is applied, not of any one
|
||||
// decode helper: Loader.overlayFile decoded the overlay into the very config
|
||||
// the base file produced, and a map-valued entry is replaced wholesale, so every
|
||||
// field of that entry the overlay does not name was cleared.
|
||||
//
|
||||
// That is archie-core-e2e2 on a user-visible path. deployments/dev.toml is the
|
||||
// documented -config-overlay argument and sets [services.state] target/listen,
|
||||
// while the installed config.toml is where [services.state].target_token lives:
|
||||
// the overlay silently dropped the token. The directory form of the same flag is
|
||||
// covered by TestDirOverlayPreservesOmittedMapEntryFields.
|
||||
func TestResolveFileOverlayPreservesOmittedMapEntryFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
base string
|
||||
overlayName string
|
||||
overlay string
|
||||
check func(t *testing.T, cfg config.Config)
|
||||
}{
|
||||
{
|
||||
// The deployment shape quoted above, with the value that is read
|
||||
// only when a client dials a non-loopback State Store.
|
||||
name: "services.state entry keeps the token it does not name",
|
||||
base: "[services.state]\ntarget = \"127.0.0.1:9090\"\ntarget_token = \"secret\"\n",
|
||||
overlay: "[services.state]\ntarget = \"10.0.0.5:9090\"\n",
|
||||
check: func(t *testing.T, cfg config.Config) {
|
||||
t.Helper()
|
||||
got := cfg.Services[config.ServiceNameState]
|
||||
if got.Target != "10.0.0.5:9090" {
|
||||
t.Errorf("services.state.target = %q, want the overlay's 10.0.0.5:9090", got.Target)
|
||||
}
|
||||
if got.TargetToken != "secret" {
|
||||
t.Errorf("services.state.target_token = %q, want the base's secret: a file overlay must not clear a field it does not name", got.TargetToken)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "providers entry keeps the fields it does not name",
|
||||
base: "[providers.anthropic]\nclass = \"anthropic\"\n" +
|
||||
"api_key_env = \"ANTHROPIC_API_KEY\"\n",
|
||||
overlay: "[providers.anthropic]\nbase_url = \"https://proxy.example\"\n",
|
||||
check: func(t *testing.T, cfg config.Config) {
|
||||
t.Helper()
|
||||
got := cfg.Providers["anthropic"]
|
||||
want := config.Provider{
|
||||
Class: "anthropic",
|
||||
APIKeyEnv: "ANTHROPIC_API_KEY",
|
||||
BaseURL: "https://proxy.example",
|
||||
}
|
||||
if got != want {
|
||||
t.Errorf("providers.anthropic = %+v, want %+v", got, want)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
// The overlay file may be YAML (-config-overlay accepts either
|
||||
// format), and it is folded by the same code.
|
||||
name: "yaml overlay keeps the token it does not name",
|
||||
base: "[services.state]\ntarget = \"127.0.0.1:9090\"\ntarget_token = \"secret\"\n",
|
||||
overlayName: "dev.yaml",
|
||||
overlay: "services:\n state:\n target: 10.0.0.5:9090\n",
|
||||
check: func(t *testing.T, cfg config.Config) {
|
||||
t.Helper()
|
||||
got := cfg.Services[config.ServiceNameState]
|
||||
if got.Target != "10.0.0.5:9090" {
|
||||
t.Errorf("services.state.target = %q, want the overlay's 10.0.0.5:9090", got.Target)
|
||||
}
|
||||
if got.TargetToken != "secret" {
|
||||
t.Errorf("services.state.target_token = %q, want the base's secret", got.TargetToken)
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
basePath := filepath.Join(dir, "config.toml")
|
||||
overlayName := tt.overlayName
|
||||
if overlayName == "" {
|
||||
overlayName = "dev.toml"
|
||||
}
|
||||
overlayPath := filepath.Join(dir, overlayName)
|
||||
if err := os.WriteFile(basePath, []byte(minimalValidConfigTOML+tt.base), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(overlayPath, []byte(tt.overlay), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
doc, err := New(nil).Resolve(basePath, overlayPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
tt.check(t, doc.Config)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadAcceptsStaleDatabaseOwnedValues is the bootstrap half of the layer
|
||||
// split (archie-core-i3qm). docs/prds/runtime-control-plane.md,
|
||||
// "Bootstrap, migration, and recovery": after migration, settings in TOML are
|
||||
// ignored and cannot block State Store startup. The other half is the boot
|
||||
// itself -- archie-state-store seeds these same settings into the control plane
|
||||
// on a fresh database, and a seed it cannot validate is skipped rather than fatal
|
||||
// (TestStateStoreBootsWithStaleDatabaseOwnedValues boots the process for that).
|
||||
//
|
||||
// Each case is a setting with a control-plane resource behind it, seeded from
|
||||
// that field by controlplane.Server.ImportConfig: providers
|
||||
// (provider-settings), poll_interval and dispatch (scheduling-policy),
|
||||
// containers (container-runtime-policies), repositories
|
||||
// (repository-policies). The second assertion is what keeps this from being a
|
||||
// weaker gate: the value is still rejected by Validate, which is what the daemon
|
||||
// and the Gateway run over the document a process will actually use. Nothing in
|
||||
// this package layers that document, so the check here is the file document on
|
||||
// its own -- the test is that the loader judges no database-owned field, not
|
||||
// that the value is harmless.
|
||||
func TestLoadAcceptsStaleDatabaseOwnedValues(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
}{
|
||||
{
|
||||
name: "providers base_url carries userinfo",
|
||||
body: fileConfigPrefix + "[providers.openai]\nclass = \"openai\"\nbase_url = \"https://token@example.com/v1\"\n",
|
||||
},
|
||||
{
|
||||
name: "negative poll_interval",
|
||||
body: fileConfigPrefix + "poll_interval = \"-5s\"\n",
|
||||
},
|
||||
{
|
||||
name: "unrecognised dispatch.trigger",
|
||||
body: fileConfigPrefix + "[dispatch]\ntrigger = \"labels\"\n",
|
||||
},
|
||||
{
|
||||
name: "negative containers.volume_ttl",
|
||||
body: fileConfigPrefix + "[containers]\nvolume_ttl = \"-1m\"\n",
|
||||
},
|
||||
{
|
||||
name: "malformed repos test_glob",
|
||||
body: fileConfigPrefix + "[[repos]]\nowner = \"acme\"\nname = \"app\"\ntest_glob = \"[\"\n",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
if err := os.WriteFile(path, []byte(tt.body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
doc, err := New(nil).File(path)
|
||||
if err != nil {
|
||||
t.Fatalf("File: %v (a stale database-owned value must not fail the load)", err)
|
||||
}
|
||||
if err := Validate(&doc.Config); err == nil {
|
||||
t.Fatal("Validate = nil, want the control plane's own layer to reject it")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// fileConfigPrefix is the smallest document the load path accepts on its own,
|
||||
// so each case above adds one stale setting and nothing else.
|
||||
const fileConfigPrefix = "bot_user = \"widget\"\nwork_dir = \"/base/work\"\n"
|
||||
|
||||
// TestDirOverlayPreservesOmittedMapEntryFields is the directory form of the
|
||||
// same guarantee TestResolveFileOverlayPreservesOmittedMapEntryFields pins.
|
||||
// -config-overlay accepts a directory as well as a file, Loader.Dir documents
|
||||
// "the same field-level precedence as [Loader.Overlay]", and Loader.Resolve
|
||||
// routes a directory source to Dir -- so a map-valued entry the overlay only
|
||||
// partly addresses must keep the fields it does not name on both forms of the
|
||||
// flag, including when the entry arrives through a feature file.
|
||||
func TestDirOverlayPreservesOmittedMapEntryFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
baseFiles map[string]string
|
||||
overlayFiles map[string]string
|
||||
check func(t *testing.T, cfg config.Config)
|
||||
}{
|
||||
{
|
||||
name: "main config keeps the token it does not name",
|
||||
baseFiles: map[string]string{
|
||||
"config.yaml": "bot_user: widget\nservices:\n state:\n target: 127.0.0.1:9090\n target_token: secret\n",
|
||||
},
|
||||
overlayFiles: map[string]string{
|
||||
"config.yaml": "services:\n state:\n target: 10.0.0.5:9090\n",
|
||||
},
|
||||
check: func(t *testing.T, cfg config.Config) {
|
||||
t.Helper()
|
||||
got := cfg.Services[config.ServiceNameState]
|
||||
if got.Target != "10.0.0.5:9090" {
|
||||
t.Errorf("services.state.target = %q, want the overlay's 10.0.0.5:9090", got.Target)
|
||||
}
|
||||
if got.TargetToken != "secret" {
|
||||
t.Errorf("services.state.target_token = %q, want the base's secret: a directory overlay must not clear a field it does not name", got.TargetToken)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "feature file keeps the fields it does not name",
|
||||
baseFiles: map[string]string{
|
||||
"config.yaml": "bot_user: widget\n",
|
||||
"config.models.yaml": "providers:\n anthropic:\n class: anthropic\n api_key_env: ANTHROPIC_API_KEY\n",
|
||||
},
|
||||
overlayFiles: map[string]string{
|
||||
"config.models.yaml": "providers:\n anthropic:\n base_url: https://proxy.example\n",
|
||||
},
|
||||
check: func(t *testing.T, cfg config.Config) {
|
||||
t.Helper()
|
||||
got := cfg.Providers["anthropic"]
|
||||
want := config.Provider{
|
||||
Class: "anthropic",
|
||||
APIKeyEnv: "ANTHROPIC_API_KEY",
|
||||
BaseURL: "https://proxy.example",
|
||||
}
|
||||
if got != want {
|
||||
t.Errorf("providers.anthropic = %+v, want %+v", got, want)
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
baseDir, overlayDir := tmpConfigDir(t), tmpConfigDir(t)
|
||||
for name, content := range tt.baseFiles {
|
||||
writeFile(t, baseDir, name, content)
|
||||
}
|
||||
for name, content := range tt.overlayFiles {
|
||||
writeFile(t, overlayDir, name, content)
|
||||
}
|
||||
|
||||
doc, err := New(nil).Resolve(baseDir, overlayDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
tt.check(t, doc.Config)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadBytesDoesNotExist(t *testing.T) {
|
||||
_, err := loadBytes(nil)
|
||||
if err == nil {
|
||||
t.Error("expected error from nil LoadBytes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdentitiesConfigParsesTwoIdentities(t *testing.T) {
|
||||
cfg, err := loadBytes([]byte(`
|
||||
bot_user = "default-legacy"
|
||||
|
||||
[[identities]]
|
||||
name = "archie"
|
||||
bot_user = "archie"
|
||||
forge = { type = "gitea", host = "https://git.example.test", token = { engine = "env", key = "ARCHIE_TOKEN" } }
|
||||
|
||||
[[identities.repos]]
|
||||
owner = "acme"
|
||||
name = "archie-core"
|
||||
base = "main"
|
||||
ecosystem = "go"
|
||||
|
||||
[[identities]]
|
||||
name = "winter"
|
||||
bot_user = "winter"
|
||||
forge = { type = "gitea", host = "https://git.example.test", token = { engine = "env", key = "WINTER_TOKEN" } }
|
||||
|
||||
[[identities.repos]]
|
||||
owner = "acme"
|
||||
name = "example-service"
|
||||
base = "main"
|
||||
ecosystem = "go"
|
||||
`))
|
||||
if err != nil {
|
||||
t.Fatalf("LoadBytes: %v", err)
|
||||
}
|
||||
if len(cfg.Identities) != 2 {
|
||||
t.Fatalf("len(Identities) = %d, want 2", len(cfg.Identities))
|
||||
}
|
||||
if cfg.Identities[0].Name != "archie" {
|
||||
t.Errorf("Identities[0].Name = %q", cfg.Identities[0].Name)
|
||||
}
|
||||
if cfg.Identities[0].BotUser != "archie" {
|
||||
t.Errorf("Identities[0].BotUser = %q", cfg.Identities[0].BotUser)
|
||||
}
|
||||
if cfg.Identities[0].Forge.Token != (secret.SecretRef{Engine: "env", Key: "ARCHIE_TOKEN"}) {
|
||||
t.Errorf("Identities[0].Forge.Token = %#v", cfg.Identities[0].Forge.Token)
|
||||
}
|
||||
if len(cfg.Identities[0].Repos) != 1 || cfg.Identities[0].Repos[0].Name != "archie-core" {
|
||||
t.Errorf("Identities[0].Repos = %+v", cfg.Identities[0].Repos)
|
||||
}
|
||||
if cfg.Identities[1].Name != "winter" {
|
||||
t.Errorf("Identities[1].Name = %q", cfg.Identities[1].Name)
|
||||
}
|
||||
if cfg.Identities[1].BotUser != "winter" {
|
||||
t.Errorf("Identities[1].BotUser = %q", cfg.Identities[1].BotUser)
|
||||
}
|
||||
if cfg.Identities[1].Forge.Token != (secret.SecretRef{Engine: "env", Key: "WINTER_TOKEN"}) {
|
||||
t.Errorf("Identities[1].Forge.Token = %#v", cfg.Identities[1].Forge.Token)
|
||||
}
|
||||
if len(cfg.Identities[1].Repos) != 1 || cfg.Identities[1].Repos[0].Name != "example-service" {
|
||||
t.Errorf("Identities[1].Repos = %+v", cfg.Identities[1].Repos)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdentitiesConfigFallsBackToLegacyWhenEmpty(t *testing.T) {
|
||||
cfg, err := loadBytes([]byte(`
|
||||
bot_user = "solo"
|
||||
forge = { type = "github", host = "https://github.test", token = { engine = "env", key = "GH_TOKEN" } }
|
||||
|
||||
[[repos]]
|
||||
owner = "acme"
|
||||
name = "my-repo"
|
||||
`))
|
||||
if err != nil {
|
||||
t.Fatalf("LoadBytes: %v", err)
|
||||
}
|
||||
if len(cfg.Identities) != 0 {
|
||||
t.Errorf("len(Identities) = %d, want 0 (empty = legacy mode)", len(cfg.Identities))
|
||||
}
|
||||
if cfg.BotUser != "solo" {
|
||||
t.Errorf("BotUser = %q, want solo (legacy field active)", cfg.BotUser)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdentitiesConfigRejectsEmptyName(t *testing.T) {
|
||||
_, err := loadBytes([]byte(`
|
||||
[[identities]]
|
||||
bot_user = "no-name"
|
||||
forge = { type = "github", token = { engine = "env", key = "X" } }
|
||||
`))
|
||||
if err == nil {
|
||||
t.Error("expected error for identity with empty name")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdentitiesConfigRejectsMissingForgeToken(t *testing.T) {
|
||||
// Unlike the top-level [forge], a per-identity forge has no default
|
||||
// token -- each identity needs its own secret reference (e.g.
|
||||
// distinct bot accounts each with their own token). Omitting it must
|
||||
// be a startup error, not a silent empty-string token.
|
||||
_, err := loadBytes([]byte(`
|
||||
[[identities]]
|
||||
name = "archie"
|
||||
bot_user = "archie"
|
||||
forge = { type = "github" }
|
||||
|
||||
[[identities.repos]]
|
||||
owner = "acme"
|
||||
name = "archie-core"
|
||||
`))
|
||||
if err == nil {
|
||||
t.Fatal("expected error for identity with no forge.token")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "forge.token") {
|
||||
t.Errorf("error = %q, want mention of forge.token", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// loadBytes writes data to a temporary file and loads it, so tests can
|
||||
// exercise decoding without managing files themselves.
|
||||
func loadBytes(data []byte) (config.Config, error) {
|
||||
if data == nil {
|
||||
return config.Config{}, os.ErrNotExist
|
||||
}
|
||||
tmp, err := os.CreateTemp("", "archie-config-*.toml")
|
||||
if err != nil {
|
||||
return config.Config{}, err
|
||||
}
|
||||
defer func() { _ = os.Remove(tmp.Name()) }()
|
||||
if _, err := tmp.Write(data); err != nil {
|
||||
_ = tmp.Close()
|
||||
return config.Config{}, err
|
||||
}
|
||||
_ = tmp.Close()
|
||||
return loadFile(tmp.Name())
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func writeSchedulingConfig(t *testing.T, section string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
if err := os.WriteFile(path, []byte("bot_user = \"widget\"\n"+section), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func TestLoaderDecodesSchedulingInputSeparatelyFromRuntimeConfig(t *testing.T) {
|
||||
doc, err := New(nil).File(writeSchedulingConfig(t, `
|
||||
[scheduling]
|
||||
interval = "30s"
|
||||
max_parallel = 2
|
||||
job_timeout = "5m"
|
||||
events_sink = "bus"
|
||||
`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := doc.Scheduling.Interval.Std(); got != 30*time.Second {
|
||||
t.Errorf("Interval = %v, want 30s", got)
|
||||
}
|
||||
if got := doc.Scheduling.MaxParallel; got != 2 {
|
||||
t.Errorf("MaxParallel = %d, want 2", got)
|
||||
}
|
||||
if got := doc.Scheduling.JobTimeout.Std(); got != 5*time.Minute {
|
||||
t.Errorf("JobTimeout = %v, want 5m", got)
|
||||
}
|
||||
if got := doc.Scheduling.EventsSink; got != EventsSinkBus {
|
||||
t.Errorf("EventsSink = %q, want %q", got, EventsSinkBus)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoaderLeavesAbsentSchedulingInputUnset(t *testing.T) {
|
||||
doc, err := New(nil).File(writeSchedulingConfig(t, ""))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if doc.Scheduling != (SchedulingInput{}) {
|
||||
t.Errorf("Scheduling = %+v, want zero external input", doc.Scheduling)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSchedulingFileOverlayKeepsUnspecifiedBaseFields(t *testing.T) {
|
||||
base := writeSchedulingConfig(t, "[scheduling]\ninterval = \"30s\"\nmax_parallel = 2\n")
|
||||
overlay := filepath.Join(t.TempDir(), "overlay.toml")
|
||||
if err := os.WriteFile(overlay, []byte("[scheduling]\njob_timeout = \"5m\"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
doc, err := New(nil).Overlay(base, overlay)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if doc.Scheduling.Interval.Std() != 30*time.Second || doc.Scheduling.MaxParallel != 2 || doc.Scheduling.JobTimeout.Std() != 5*time.Minute {
|
||||
t.Errorf("Scheduling = %+v, want merged input", doc.Scheduling)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExampleConfigLeavesSchedulingAtDefaults(t *testing.T) {
|
||||
doc, err := New(nil).File(filepath.Join("..", "..", "..", "config.example.toml"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if doc.Scheduling != (SchedulingInput{}) {
|
||||
t.Errorf("Scheduling = %+v, want commented example to remain unset", doc.Scheduling)
|
||||
}
|
||||
}
|
||||
@@ -1,186 +0,0 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
func TestLoadGatewayServiceTarget(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name, section, wantTarget string
|
||||
}{
|
||||
{name: "default", wantTarget: "127.0.0.1:8585"},
|
||||
{name: "explicit target", section: "[services.gateway]\ntarget = 'dns:///gateway:8443'", wantTarget: "dns:///gateway:8443"},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
if err := os.WriteFile(path, []byte("bot_user = 'widget'\n"+tt.section), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Services.Get(config.ServiceNameGateway).Target != tt.wantTarget {
|
||||
t.Fatalf("target = %q, want %q", cfg.Services.Get(config.ServiceNameGateway).Target, tt.wantTarget)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadServiceListens: both gRPC services this repository runs bind an
|
||||
// address the configuration names. They used to be flag-only, so a host whose
|
||||
// default port was already taken could only be retargeted
|
||||
// by passing -listen and hand-writing an overlay whose target matched -- two
|
||||
// files to keep in step, and nothing to keep them there.
|
||||
func TestLoadServiceListens(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name, section, wantState, wantGateway string
|
||||
}{
|
||||
{name: "defaults", wantState: "127.0.0.1:9090", wantGateway: "127.0.0.1:8585"},
|
||||
{
|
||||
name: "explicit listens",
|
||||
section: "[services.state]\nlisten = '127.0.0.1:9191'\n[services.gateway]\nlisten = '127.0.0.1:8686'",
|
||||
wantState: "127.0.0.1:9191",
|
||||
wantGateway: "127.0.0.1:8686",
|
||||
},
|
||||
{
|
||||
name: "state listen alone leaves the gateway default",
|
||||
section: "[services.state]\nlisten = '127.0.0.1:9191'",
|
||||
wantState: "127.0.0.1:9191",
|
||||
wantGateway: "127.0.0.1:8585",
|
||||
},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
if err := os.WriteFile(path, []byte("bot_user = 'widget'\n"+tt.section), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Services.Get(config.ServiceNameState).Listen != tt.wantState {
|
||||
t.Fatalf("state listen = %q, want %q", cfg.Services.Get(config.ServiceNameState).Listen, tt.wantState)
|
||||
}
|
||||
if cfg.Services.Get(config.ServiceNameGateway).Listen != tt.wantGateway {
|
||||
t.Fatalf("gateway listen = %q, want %q", cfg.Services.Get(config.ServiceNameGateway).Listen, tt.wantGateway)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadHealthListen: the daemon's liveness surface is not optional. The
|
||||
// update watchdog restarts archied and asks whether it came back, and only
|
||||
// archied can answer that -- the dashboard's /healthz belongs to the
|
||||
// dashboard, which can be switched off and moves to its own process
|
||||
// (archie-core-1r4g, archie-core-exbz).
|
||||
func TestLoadHealthListen(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name, section, wantListen string
|
||||
}{
|
||||
{name: "default", wantListen: "127.0.0.1:8485"},
|
||||
{name: "explicit listen", section: "[health]\nlisten = '127.0.0.1:9500'", wantListen: "127.0.0.1:9500"},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
if err := os.WriteFile(path, []byte("bot_user = 'widget'\n"+tt.section), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Health.Listen != tt.wantListen {
|
||||
t.Fatalf("health listen = %q, want %q", cfg.Health.Listen, tt.wantListen)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegisteredServiceDefaultsNeedNoLoaderEdit pins criterion 4 of
|
||||
// docs/prds/service-registry.md. A service registered anywhere gets its
|
||||
// defaults applied here without this package naming it, which is the whole
|
||||
// point of iterating the registry instead of writing one branch per service.
|
||||
func TestRegisteredServiceDefaultsNeedNoLoaderEdit(t *testing.T) {
|
||||
config.RegisterService(config.ServiceBoth, "loadertest", "127.0.0.1:7101", "127.0.0.1:7102", "LOADERTEST_TOKEN")
|
||||
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
if err := os.WriteFile(path, []byte("bot_user = 'widget'\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := cfg.Services.Get("loadertest")
|
||||
if got.Target != "127.0.0.1:7101" {
|
||||
t.Errorf("target = %q, want the registered default", got.Target)
|
||||
}
|
||||
if got.Listen != "127.0.0.1:7102" {
|
||||
t.Errorf("listen = %q, want the registered default", got.Listen)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStateTargetIsNotDefaulted keeps the asymmetry the registry now carries as
|
||||
// data: the gateway's target is defaulted, the State Store's is operator
|
||||
// input, and defaulting it to something dialable would turn a missing
|
||||
// required value into a connection attempt against the wrong host.
|
||||
func TestStateTargetIsNotDefaulted(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
if err := os.WriteFile(path, []byte("bot_user = 'widget'\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := cfg.Services.Get(config.ServiceNameState).Target; got != "" {
|
||||
t.Errorf("state target = %q, want empty", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUnregisteredServiceSectionIsReported is the regression this change had to
|
||||
// avoid introducing. Services was a struct, so [services.gatway] landed in
|
||||
// Undecoded() and was reported. As a map it decodes cleanly, so without the
|
||||
// registry check a typo'd service section would load silently and the daemon
|
||||
// would dial the default instead.
|
||||
func TestUnregisteredServiceSectionIsReported(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
src := minimalValidConfigTOML + "[services.gatway]\ntarget = '127.0.0.1:1'\n"
|
||||
if err := os.WriteFile(path, []byte(src), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
doc, err := New(nil).File(path)
|
||||
if err != nil {
|
||||
t.Fatalf("File: %v (an unknown key must not fail the load)", err)
|
||||
}
|
||||
if !slices.Contains(doc.UnknownKeys, "services.gatway") {
|
||||
t.Errorf("UnknownKeys = %v, want it to contain %q", doc.UnknownKeys, "services.gatway")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegisteredServiceSectionIsNotReported is the other half: a real service
|
||||
// section must not be flagged just because the map would accept anything.
|
||||
func TestRegisteredServiceSectionIsNotReported(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
src := minimalValidConfigTOML + "[services.state]\ntarget = '127.0.0.1:9090'\n"
|
||||
if err := os.WriteFile(path, []byte(src), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
doc, err := New(nil).File(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, k := range doc.UnknownKeys {
|
||||
if strings.HasPrefix(k, "services.") {
|
||||
t.Errorf("UnknownKeys = %v, want no services.* entry for a registered service", doc.UnknownKeys)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package setup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDefaultPrompter(t *testing.T) {
|
||||
var p DefaultPrompter
|
||||
|
||||
if idx, err := p.Select(context.Background(), "q", []string{"a", "b"}); err != nil || idx != 0 {
|
||||
t.Errorf("Select = (%d, %v), want (0, nil)", idx, err)
|
||||
}
|
||||
if got, err := p.ReadLine(context.Background(), "q", "default"); err != nil || got != "default" {
|
||||
t.Errorf("ReadLine = (%q, %v), want (\"default\", nil)", got, err)
|
||||
}
|
||||
if got, err := p.ReadSecret(context.Background(), "q"); err != nil || got != "" {
|
||||
t.Errorf("ReadSecret = (%q, %v), want (\"\", nil)", got, err)
|
||||
}
|
||||
if got, err := p.Confirm(context.Background(), "q", true); err != nil || !got {
|
||||
t.Errorf("Confirm(defaultYes=true) = (%v, %v), want (true, nil)", got, err)
|
||||
}
|
||||
if got, err := p.Confirm(context.Background(), "q", false); err != nil || got {
|
||||
t.Errorf("Confirm(defaultYes=false) = (%v, %v), want (false, nil)", got, err)
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
package setup
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEnvFileSink_MatchSetEnvKeyFormat(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "env")
|
||||
s := NewEnvFileSink(path)
|
||||
if err := s.Put("env", "ARCHIE_GITHUB_TOKEN", "abc"); err != nil {
|
||||
t.Fatalf("Put: %v", err)
|
||||
}
|
||||
if err := s.Commit(); err != nil {
|
||||
t.Fatalf("Commit: %v", err)
|
||||
}
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("read env file: %v", err)
|
||||
}
|
||||
if got, want := string(b), "ARCHIE_GITHUB_TOKEN='abc'\n"; got != want {
|
||||
t.Errorf("env file = %q, want %q", got, want)
|
||||
}
|
||||
if info, err := os.Stat(path); err != nil || info.Mode().Perm() != 0o600 {
|
||||
t.Errorf("env file mode = %v (%v), want 0600", info.Mode().Perm(), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvFileSink_ReplacesExistingAndPreservesUnrelated(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "env")
|
||||
if err := os.WriteFile(path, []byte("KEEP='keep'\nARCHIE_GITHUB_TOKEN='old'\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s := NewEnvFileSink(path)
|
||||
if err := s.Put("env", "ARCHIE_GITHUB_TOKEN", "new"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Put("env", "ARCHIE_GITEA_TOKEN", "gitea"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Commit(); err != nil {
|
||||
t.Fatalf("Commit: %v", err)
|
||||
}
|
||||
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Unrelated line keeps its position; replaced keys move to the end (the
|
||||
// same behaviour as set_env_key's grep -v + append), new keys sorted.
|
||||
want := "KEEP='keep'\nARCHIE_GITEA_TOKEN='gitea'\nARCHIE_GITHUB_TOKEN='new'\n"
|
||||
if got := string(b); got != want {
|
||||
t.Errorf("env file = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvFileSink_EscapesSingleQuotes(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "env")
|
||||
s := NewEnvFileSink(path)
|
||||
if err := s.Put("env", "K", "a'b"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Commit(); err != nil {
|
||||
t.Fatalf("Commit: %v", err)
|
||||
}
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, want := string(b), "K='a'\\''b'\n"; got != want {
|
||||
t.Errorf("env file = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvFileSink_RejectsNonEnvEngine(t *testing.T) {
|
||||
s := NewEnvFileSink(filepath.Join(t.TempDir(), "env"))
|
||||
if err := s.Put("bws", "K", "v"); err == nil {
|
||||
t.Error("Put(bws) = nil error, want a failure: the env file has no representation for non-env engines")
|
||||
}
|
||||
}
|
||||
@@ -1,250 +0,0 @@
|
||||
package setup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
// rejectingPrompter fails the test if any question is asked, proving that a
|
||||
// fully-populated Params never touches the prompt surface.
|
||||
// scriptedSecretPrompter answers only the secret reads. Any other prompt means
|
||||
// Params failed to supply a non-secret answer; an exhausted script means a
|
||||
// secret was read that the test did not expect.
|
||||
type scriptedSecretPrompter struct {
|
||||
t *testing.T
|
||||
secrets []string
|
||||
next int
|
||||
}
|
||||
|
||||
func (s *scriptedSecretPrompter) take(prompt string) string {
|
||||
if s.next >= len(s.secrets) {
|
||||
s.t.Fatalf("unexpected secret read %q: Params supplied every non-secret answer and no more were scripted", prompt)
|
||||
}
|
||||
v := s.secrets[s.next]
|
||||
s.next++
|
||||
return v
|
||||
}
|
||||
|
||||
func (s *scriptedSecretPrompter) Select(context.Context, string, []string) (int, error) {
|
||||
s.t.Fatal("unexpected Select: Params should have supplied this answer")
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (s *scriptedSecretPrompter) ReadLine(context.Context, string, string) (string, error) {
|
||||
s.t.Fatal("unexpected ReadLine: Params should have supplied this answer")
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (s *scriptedSecretPrompter) ReadSecret(_ context.Context, prompt string) (string, error) {
|
||||
return s.take(prompt), nil
|
||||
}
|
||||
|
||||
func (s *scriptedSecretPrompter) Confirm(context.Context, string, bool) (bool, error) {
|
||||
s.t.Fatal("unexpected Confirm: Params should have supplied this answer")
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// TestRunParams_SecretsComeOnlyFromThePrompter pins the rule that a secret is
|
||||
// never a parameter. Params supplies every non-secret answer, so the only
|
||||
// prompts reached are the secret reads, and the values they return are the only
|
||||
// values that reach the secret sink. TOML gets a reference, never the value.
|
||||
func TestRunParams_SecretsComeOnlyFromThePrompter(t *testing.T) {
|
||||
params := Params{
|
||||
BotUser: "archie-bot",
|
||||
Operator: "Ada",
|
||||
ForgeType: "github",
|
||||
ForgeHost: "https://github.acme.internal",
|
||||
Provider: "ollama", // keyless, so no provider secret is read
|
||||
Model: "llama3",
|
||||
TelegramUserIDs: []int64{111, 222},
|
||||
}
|
||||
p := &scriptedSecretPrompter{t: t, secrets: []string{"ghp-token", "tg-token"}}
|
||||
secrets := newFakeSecrets()
|
||||
edits, err := RunParams(context.Background(), p, nil, secrets, ExistingValues{}, params)
|
||||
if err != nil {
|
||||
t.Fatalf("RunParams: %v", err)
|
||||
}
|
||||
if err := secrets.Commit(); err != nil {
|
||||
t.Fatalf("Commit: %v", err)
|
||||
}
|
||||
if p.next != len(p.secrets) {
|
||||
t.Errorf("read %d secrets, want %d: every secret must come from a prompt", p.next, len(p.secrets))
|
||||
}
|
||||
if got := secrets.committed["env:ARCHIE_GITHUB_TOKEN"]; got != "ghp-token" {
|
||||
t.Errorf("committed env:ARCHIE_GITHUB_TOKEN = %q, want ghp-token", got)
|
||||
}
|
||||
if got := secrets.committed["env:ARCHIE_TELEGRAM_TOKEN"]; got != "tg-token" {
|
||||
t.Errorf("committed env:ARCHIE_TELEGRAM_TOKEN = %q, want tg-token", got)
|
||||
}
|
||||
|
||||
cfg := generateAndLoad(t, edits)
|
||||
if cfg.BotUser != "archie-bot" {
|
||||
t.Errorf("bot_user = %q, want archie-bot", cfg.BotUser)
|
||||
}
|
||||
if cfg.Forge.Token.Engine != "env" || cfg.Forge.Token.Key != "ARCHIE_GITHUB_TOKEN" {
|
||||
t.Errorf("forge.token = %+v, want a reference to env/ARCHIE_GITHUB_TOKEN", cfg.Forge.Token)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunParams_NonSecretParamsNeverPrompt is the non-secret half: every
|
||||
// answer Params can carry is supplied, so nothing is asked for except the
|
||||
// secrets, which Params deliberately cannot supply.
|
||||
func TestRunParams_NonSecretParamsNeverPrompt(t *testing.T) {
|
||||
params := Params{
|
||||
BotUser: "archie-bot",
|
||||
Operator: "Ada",
|
||||
ForgeType: "none",
|
||||
Provider: "ollama",
|
||||
Model: "llama3",
|
||||
TelegramUserIDs: []int64{111, 222},
|
||||
}
|
||||
// Ollama is keyless and forge "none" stores no token, so this run asks for
|
||||
// exactly one secret: the Telegram bot token.
|
||||
p := &scriptedSecretPrompter{t: t, secrets: []string{"tg-token"}}
|
||||
secrets := newFakeSecrets()
|
||||
edits, err := RunParams(context.Background(), p, nil, secrets, ExistingValues{}, params)
|
||||
if err != nil {
|
||||
t.Fatalf("RunParams: %v", err)
|
||||
}
|
||||
cfg := generateAndLoad(t, edits)
|
||||
if cfg.BotUser != "archie-bot" {
|
||||
t.Errorf("bot_user = %q, want archie-bot", cfg.BotUser)
|
||||
}
|
||||
if cfg.Forge.Type != "none" {
|
||||
t.Errorf("forge.type = %q, want none", cfg.Forge.Type)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunParams_PartialParamsAskOnlyTheRest(t *testing.T) {
|
||||
// Bot user, provider and model are supplied; operator, forge and
|
||||
// telegram are left for the prompter. The provider API key is never in
|
||||
// Params (there is no typed field for it), so it is always prompted.
|
||||
p := &fakePrompter{
|
||||
lines: []string{""}, // operator left blank
|
||||
selects: []int{2}, // forge: none
|
||||
secrets: []string{"sk-openai-key"},
|
||||
confirms: []bool{false},
|
||||
}
|
||||
secrets := newFakeSecrets()
|
||||
edits, err := RunParams(context.Background(), p, nil, secrets, ExistingValues{}, Params{
|
||||
BotUser: "archie-bot",
|
||||
Provider: "openai",
|
||||
Model: "gpt-5.4",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RunParams: %v", err)
|
||||
}
|
||||
if err := secrets.Commit(); err != nil {
|
||||
t.Fatalf("Commit: %v", err)
|
||||
}
|
||||
|
||||
cfg := generateAndLoad(t, edits)
|
||||
if cfg.BotUser != "archie-bot" {
|
||||
t.Errorf("bot_user = %q, want archie-bot", cfg.BotUser)
|
||||
}
|
||||
if cfg.Chat.Operator != "" {
|
||||
t.Errorf("chat.operator = %q, want empty (prompt left blank)", cfg.Chat.Operator)
|
||||
}
|
||||
if cfg.Forge.Type != "none" {
|
||||
t.Errorf("forge.type = %q, want none", cfg.Forge.Type)
|
||||
}
|
||||
if cfg.Providers["openai"].APIKey.Key != "OPENAI_API_KEY" {
|
||||
t.Errorf("providers.openai.api_key.key = %q, want OPENAI_API_KEY", cfg.Providers["openai"].APIKey.Key)
|
||||
}
|
||||
for _, role := range []string{"triage", "planner", "builder"} {
|
||||
if cfg.Models[role] != "openai/gpt-5.4" {
|
||||
t.Errorf("models[%s] = %q, want openai/gpt-5.4", role, cfg.Models[role])
|
||||
}
|
||||
}
|
||||
if got := secrets.committed["env:OPENAI_API_KEY"]; got != "sk-openai-key" {
|
||||
t.Errorf("committed openai key = %q, want sk-openai-key", got)
|
||||
}
|
||||
if len(secrets.committed) != 1 {
|
||||
t.Errorf("committed secrets = %v, want only the openai key", secrets.committed)
|
||||
}
|
||||
}
|
||||
|
||||
// The --defaults baseline from the plan's Decision 2: bot user archie-bot,
|
||||
// github, https://github.com, ollama, llama3, operator/telegram skipped. It
|
||||
// must produce a loadable config with no secrets written, because ollama is
|
||||
// the one keyless path.
|
||||
func TestRun_DefaultsBaselineLoads(t *testing.T) {
|
||||
params := Params{
|
||||
BotUser: "archie-bot",
|
||||
ForgeType: "github",
|
||||
ForgeHost: "https://github.com",
|
||||
Provider: "ollama",
|
||||
Model: "llama3",
|
||||
}
|
||||
secrets := newFakeSecrets()
|
||||
edits, err := RunParams(context.Background(), DefaultPrompter{}, nil, secrets, ExistingValues{}, params)
|
||||
if err != nil {
|
||||
t.Fatalf("RunParams: %v", err)
|
||||
}
|
||||
if err := secrets.Commit(); err != nil {
|
||||
t.Fatalf("Commit: %v", err)
|
||||
}
|
||||
|
||||
cfg := generateAndLoad(t, edits)
|
||||
if cfg.BotUser != "archie-bot" {
|
||||
t.Errorf("bot_user = %q, want archie-bot", cfg.BotUser)
|
||||
}
|
||||
if cfg.Forge.Type != "github" || cfg.Forge.Host != "https://github.com" {
|
||||
t.Errorf("forge = %q/%q, want github/https://github.com", cfg.Forge.Type, cfg.Forge.Host)
|
||||
}
|
||||
for _, role := range []string{"triage", "planner", "builder"} {
|
||||
if cfg.Models[role] != "ollama/llama3" {
|
||||
t.Errorf("models[%s] = %q, want ollama/llama3", role, cfg.Models[role])
|
||||
}
|
||||
}
|
||||
if cfg.Providers["ollama"].Class != "ollama" {
|
||||
t.Errorf("providers.ollama.class = %q, want ollama", cfg.Providers["ollama"].Class)
|
||||
}
|
||||
if len(secrets.committed) != 0 {
|
||||
t.Errorf("committed secrets = %v, want none: the defaults baseline is keyless", secrets.committed)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunParams_SecretRefsWriteReferencesWithoutStoring pins what a reference
|
||||
// means: the value already lives in a secret engine, so setup writes the
|
||||
// reference, reads nothing from the prompt surface, and stores nothing of its
|
||||
// own. `vault/openbao` is deliberate -- an arbitrary engine name must survive
|
||||
// to TOML, which the legacy token_env form could not express.
|
||||
func TestRunParams_SecretRefsWriteReferencesWithoutStoring(t *testing.T) {
|
||||
params := Params{
|
||||
BotUser: "archie-bot",
|
||||
Operator: "Ada",
|
||||
ForgeType: "github",
|
||||
ForgeHost: "https://github.com",
|
||||
ForgeTokenRef: config.SecretRef{Engine: "bws", Key: "ARCHIE_GITHUB_TOKEN"},
|
||||
Provider: "openai",
|
||||
Model: "gpt-5.4",
|
||||
ProviderAPIKeyRef: config.SecretRef{Engine: "vault", Key: "OPENAI_API_KEY"},
|
||||
TelegramTokenRef: config.SecretRef{Engine: "bws", Key: "TELEGRAM_BOT_TOKEN"},
|
||||
TelegramUserIDs: []int64{111},
|
||||
}
|
||||
// No secrets are scripted: any ReadSecret call fails the test, because a
|
||||
// reference means nothing may be prompted for.
|
||||
p := &scriptedSecretPrompter{t: t}
|
||||
secrets := newFakeSecrets()
|
||||
edits, err := RunParams(context.Background(), p, nil, secrets, ExistingValues{}, params)
|
||||
if err != nil {
|
||||
t.Fatalf("RunParams: %v", err)
|
||||
}
|
||||
if len(secrets.pending) != 0 {
|
||||
t.Errorf("pending secrets = %v, want none: setup does not own a referenced value", secrets.pending)
|
||||
}
|
||||
|
||||
cfg := generateAndLoad(t, edits)
|
||||
if got := cfg.Forge.Token; got != params.ForgeTokenRef {
|
||||
t.Errorf("forge.token = %+v, want %+v", got, params.ForgeTokenRef)
|
||||
}
|
||||
if got := cfg.Providers["openai"].APIKey; got != params.ProviderAPIKeyRef {
|
||||
t.Errorf("providers.openai.api_key = %+v, want %+v", got, params.ProviderAPIKeyRef)
|
||||
}
|
||||
if got := cfg.Chat.Telegram.Token; got != params.TelegramTokenRef {
|
||||
t.Errorf("chat.telegram.token = %+v, want %+v", got, params.TelegramTokenRef)
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package setup
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
func TestParseSecretRef(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in string
|
||||
want config.SecretRef
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "env engine", in: "env:ARCHIE_GITHUB_TOKEN", want: config.SecretRef{Engine: "env", Key: "ARCHIE_GITHUB_TOKEN"}},
|
||||
{name: "bws engine", in: "bws:OPENAI_API_KEY", want: config.SecretRef{Engine: "bws", Key: "OPENAI_API_KEY"}},
|
||||
{name: "operator-supplied engine", in: "vault:TELEGRAM_BOT_TOKEN", want: config.SecretRef{Engine: "vault", Key: "TELEGRAM_BOT_TOKEN"}},
|
||||
{name: "hyphenated engine", in: "my-engine:KEY", want: config.SecretRef{Engine: "my-engine", Key: "KEY"}},
|
||||
{name: "surrounding space is trimmed", in: " env : ARCHIE_TOKEN ", want: config.SecretRef{Engine: "env", Key: "ARCHIE_TOKEN"}},
|
||||
{name: "no colon", in: "ARCHIE_GITHUB_TOKEN", wantErr: true},
|
||||
{name: "empty engine", in: ":ARCHIE_TOKEN", wantErr: true},
|
||||
{name: "empty key", in: "env:", wantErr: true},
|
||||
{name: "engine with a space", in: "my engine:KEY", wantErr: true},
|
||||
// Engine names are Yaegi plugin filenames and the shipped ones are bare
|
||||
// identifiers (age, sops, vault), so a path separator is never valid.
|
||||
{name: "engine with a slash", in: "vault/openbao:KEY", wantErr: true},
|
||||
{name: "key with a colon", in: "env:A:B", wantErr: true},
|
||||
{name: "empty", in: "", wantErr: true},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got, err := ParseSecretRef(tc.in)
|
||||
if tc.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("ParseSecretRef(%q) = %+v, want an error", tc.in, got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("ParseSecretRef(%q): %v", tc.in, err)
|
||||
}
|
||||
if got != tc.want {
|
||||
t.Errorf("ParseSecretRef(%q) = %+v, want %+v", tc.in, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,492 +0,0 @@
|
||||
package setup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
configtemplate "github.com/samcharles93/archie-core"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration/tomlwrite"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
// fakePrompter drives Run from typed scripted answers rather than raw
|
||||
// terminal bytes. It mirrors Prompter's real contract (an empty ReadLine
|
||||
// answer resolves to the caller's default; Select/Confirm/ReadSecret return
|
||||
// their scripted value directly) so a test reads as "what would the
|
||||
// operator have typed", not as a simulation of terminal parsing --
|
||||
// terminalprompt's own tests already cover that parsing.
|
||||
type fakePrompter struct {
|
||||
selects []int
|
||||
lines []string
|
||||
secrets []string
|
||||
confirms []bool
|
||||
}
|
||||
|
||||
func (f *fakePrompter) pop(name string, q *[]string) (string, error) {
|
||||
if len(*q) == 0 {
|
||||
return "", fmt.Errorf("fakePrompter: no more scripted %s answers", name)
|
||||
}
|
||||
v := (*q)[0]
|
||||
*q = (*q)[1:]
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func (f *fakePrompter) Select(_ context.Context, _ string, options []string) (int, error) {
|
||||
if len(f.selects) == 0 {
|
||||
return -1, fmt.Errorf("fakePrompter: no more scripted selects")
|
||||
}
|
||||
n := f.selects[0]
|
||||
f.selects = f.selects[1:]
|
||||
if n < 0 || n >= len(options) {
|
||||
return -1, fmt.Errorf("fakePrompter: scripted select %d out of range for %d options", n, len(options))
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (f *fakePrompter) ReadLine(_ context.Context, _, defaultValue string) (string, error) {
|
||||
v, err := f.pop("line", &f.lines)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if v == "" {
|
||||
return defaultValue, nil
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func (f *fakePrompter) ReadSecret(_ context.Context, _ string) (string, error) {
|
||||
return f.pop("secret", &f.secrets)
|
||||
}
|
||||
|
||||
func (f *fakePrompter) Confirm(_ context.Context, _ string, defaultYes bool) (bool, error) {
|
||||
if len(f.confirms) == 0 {
|
||||
return false, fmt.Errorf("fakePrompter: no more scripted confirms")
|
||||
}
|
||||
v := f.confirms[0]
|
||||
f.confirms = f.confirms[1:]
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// fakeSecrets records Put calls without committing until Commit is called,
|
||||
// mirroring the real buffer-then-commit contract Run relies on.
|
||||
type fakeSecrets struct {
|
||||
pending map[string]string // "engine:key" -> value
|
||||
committed map[string]string
|
||||
}
|
||||
|
||||
func newFakeSecrets() *fakeSecrets {
|
||||
return &fakeSecrets{pending: map[string]string{}, committed: map[string]string{}}
|
||||
}
|
||||
|
||||
func (f *fakeSecrets) Put(engine, key, value string) error {
|
||||
f.pending[engine+":"+key] = value
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeSecrets) Commit() error {
|
||||
maps.Copy(f.committed, f.pending)
|
||||
return nil
|
||||
}
|
||||
|
||||
// generateAndLoad renders edits against the real embedded template and
|
||||
// loads the result through a real configuration.Loader -- the same check
|
||||
// Run's own doc comment says the caller must perform. This is what "every
|
||||
// config setup writes passes configuration.Validate, verified by a test
|
||||
// that runs setup non-interactively and validates the output" means in
|
||||
// practice: proving the real load path (defaults, decode, validate, in
|
||||
// their real order) accepts it, not asserting against a second,
|
||||
// hand-rolled representation.
|
||||
func generateAndLoad(t *testing.T, edits []tomlwrite.Edit) config.Config {
|
||||
t.Helper()
|
||||
out, err := tomlwrite.Generate(configtemplate.Example, edits)
|
||||
if err != nil {
|
||||
t.Fatalf("tomlwrite.Generate: %v", err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "config.toml")
|
||||
if err := os.WriteFile(path, out, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
doc, err := configuration.New(nil).File(path)
|
||||
if err != nil {
|
||||
t.Fatalf("generated config does not load: %v\n%s", err, out)
|
||||
}
|
||||
return doc.Config
|
||||
}
|
||||
|
||||
func TestRun_GitHubCloudProvider(t *testing.T) {
|
||||
p := &fakePrompter{
|
||||
lines: []string{"acme-archie", "Ada Lovelace", "gpt-5.4"},
|
||||
selects: []int{0, 0}, // OpenAI, GitHub
|
||||
secrets: []string{"sk-openai-token", "ghp-github-token"},
|
||||
confirms: []bool{false}, // no telegram
|
||||
}
|
||||
secrets := newFakeSecrets()
|
||||
edits, err := Run(context.Background(), p, nil, secrets, ExistingValues{})
|
||||
if err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if err := secrets.Commit(); err != nil {
|
||||
t.Fatalf("Commit: %v", err)
|
||||
}
|
||||
|
||||
cfg := generateAndLoad(t, edits)
|
||||
if cfg.BotUser != "acme-archie" {
|
||||
t.Errorf("bot_user = %q, want acme-archie", cfg.BotUser)
|
||||
}
|
||||
if cfg.Chat.Operator != "Ada Lovelace" {
|
||||
t.Errorf("chat.operator = %q, want Ada Lovelace", cfg.Chat.Operator)
|
||||
}
|
||||
if cfg.Forge.Type != "github" {
|
||||
t.Errorf("forge.type = %q, want github", cfg.Forge.Type)
|
||||
}
|
||||
if cfg.Forge.Token.Key != "ARCHIE_GITHUB_TOKEN" {
|
||||
t.Errorf("forge.token.key = %q, want ARCHIE_GITHUB_TOKEN", cfg.Forge.Token.Key)
|
||||
}
|
||||
if got, want := secrets.committed["env:ARCHIE_GITHUB_TOKEN"], "ghp-github-token"; got != want {
|
||||
t.Errorf("committed github token = %q, want %q", got, want)
|
||||
}
|
||||
if cfg.Providers["openai"].Class != "openai" {
|
||||
t.Errorf("providers.openai.class = %q, want openai", cfg.Providers["openai"].Class)
|
||||
}
|
||||
if cfg.Providers["openai"].APIKey.Key != "OPENAI_API_KEY" {
|
||||
t.Errorf("providers.openai.api_key.key = %q, want OPENAI_API_KEY", cfg.Providers["openai"].APIKey.Key)
|
||||
}
|
||||
if got, want := secrets.committed["env:OPENAI_API_KEY"], "sk-openai-token"; got != want {
|
||||
t.Errorf("committed openai key = %q, want %q", got, want)
|
||||
}
|
||||
for _, role := range []string{"triage", "planner", "builder"} {
|
||||
if cfg.Models[role] != "openai/gpt-5.4" {
|
||||
t.Errorf("models[%s] = %q, want openai/gpt-5.4", role, cfg.Models[role])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_GiteaForge(t *testing.T) {
|
||||
p := &fakePrompter{
|
||||
lines: []string{"acme-archie", "", "gpt-5.4", "https://git.acme.internal"},
|
||||
selects: []int{0, 1}, // OpenAI, Gitea
|
||||
secrets: []string{"sk-openai-token", "gitea-token"},
|
||||
confirms: []bool{false},
|
||||
}
|
||||
secrets := newFakeSecrets()
|
||||
edits, err := Run(context.Background(), p, nil, secrets, ExistingValues{})
|
||||
if err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if err := secrets.Commit(); err != nil {
|
||||
t.Fatalf("Commit: %v", err)
|
||||
}
|
||||
|
||||
cfg := generateAndLoad(t, edits)
|
||||
if cfg.Forge.Type != "gitea" {
|
||||
t.Errorf("forge.type = %q, want gitea", cfg.Forge.Type)
|
||||
}
|
||||
if cfg.Forge.Host != "https://git.acme.internal" {
|
||||
t.Errorf("forge.host = %q, want https://git.acme.internal", cfg.Forge.Host)
|
||||
}
|
||||
if cfg.Forge.Token.Key != "ARCHIE_GITEA_TOKEN" {
|
||||
t.Errorf("forge.token.key = %q, want ARCHIE_GITEA_TOKEN", cfg.Forge.Token.Key)
|
||||
}
|
||||
if got, want := secrets.committed["env:ARCHIE_GITEA_TOKEN"], "gitea-token"; got != want {
|
||||
t.Errorf("committed gitea token = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_ForgeNone(t *testing.T) {
|
||||
p := &fakePrompter{
|
||||
lines: []string{"acme-archie", "", "gpt-5.4"},
|
||||
selects: []int{0, 2}, // OpenAI, None
|
||||
secrets: []string{"sk-openai-token"},
|
||||
confirms: []bool{false},
|
||||
}
|
||||
secrets := newFakeSecrets()
|
||||
edits, err := Run(context.Background(), p, nil, secrets, ExistingValues{})
|
||||
if err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if err := secrets.Commit(); err != nil {
|
||||
t.Fatalf("Commit: %v", err)
|
||||
}
|
||||
|
||||
cfg := generateAndLoad(t, edits)
|
||||
if cfg.Forge.Type != "none" {
|
||||
t.Errorf("forge.type = %q, want none", cfg.Forge.Type)
|
||||
}
|
||||
if cfg.Forge.Token.Key != "" {
|
||||
t.Errorf("forge.token.key = %q, want empty: no token was ever collected for forge type none", cfg.Forge.Token.Key)
|
||||
}
|
||||
if len(secrets.committed) != 1 { // just the openai key
|
||||
t.Errorf("committed secrets = %v, want only the openai key", secrets.committed)
|
||||
}
|
||||
}
|
||||
|
||||
type fakeDiscovery struct {
|
||||
models []string
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeDiscovery) ListOllamaModels(context.Context) ([]string, error) {
|
||||
return f.models, f.err
|
||||
}
|
||||
|
||||
func TestRun_SelfHostedWithDiscoveredModels(t *testing.T) {
|
||||
p := &fakePrompter{
|
||||
lines: []string{"acme-archie", ""},
|
||||
selects: []int{len(cloudProviders), 0, 2}, // provider: self-hosted; ollama model list: index 0; forge: none
|
||||
confirms: []bool{false},
|
||||
}
|
||||
discovery := &fakeDiscovery{models: []string{"llama3", "qwen2.5:7b"}}
|
||||
secrets := newFakeSecrets()
|
||||
edits, err := Run(context.Background(), p, discovery, secrets, ExistingValues{})
|
||||
if err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
|
||||
cfg := generateAndLoad(t, edits)
|
||||
for _, role := range []string{"triage", "planner", "builder"} {
|
||||
if cfg.Models[role] != "ollama/llama3" {
|
||||
t.Errorf("models[%s] = %q, want ollama/llama3", role, cfg.Models[role])
|
||||
}
|
||||
}
|
||||
if cfg.Providers["ollama"].Class != "ollama" {
|
||||
t.Errorf("providers.ollama.class = %q, want ollama", cfg.Providers["ollama"].Class)
|
||||
}
|
||||
if len(secrets.committed) != 0 {
|
||||
t.Errorf("committed secrets = %v, want none: self-hosted needs no API key", secrets.committed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_SelfHostedDiscoveryUnavailableFallsBackToFreeText(t *testing.T) {
|
||||
p := &fakePrompter{
|
||||
lines: []string{"acme-archie", "", "custom-model:latest"},
|
||||
selects: []int{len(cloudProviders), 2}, // self-hosted, forge none
|
||||
confirms: []bool{false},
|
||||
}
|
||||
discovery := &fakeDiscovery{err: fmt.Errorf("ollama not found")}
|
||||
secrets := newFakeSecrets()
|
||||
edits, err := Run(context.Background(), p, discovery, secrets, ExistingValues{})
|
||||
if err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
cfg := generateAndLoad(t, edits)
|
||||
if cfg.Models["triage"] != "ollama/custom-model:latest" {
|
||||
t.Errorf("models[triage] = %q, want ollama/custom-model:latest", cfg.Models["triage"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_TelegramRequiresAllowedUserIDs(t *testing.T) {
|
||||
p := &fakePrompter{
|
||||
lines: []string{"acme-archie", "", "gpt-5.4", ""}, // last "" is the empty allowed-ids answer
|
||||
selects: []int{0, 2}, // openai, forge none
|
||||
secrets: []string{"sk-openai-token", "tg-token"},
|
||||
confirms: []bool{true}, // yes, configure telegram
|
||||
}
|
||||
secrets := newFakeSecrets()
|
||||
_, err := Run(context.Background(), p, nil, secrets, ExistingValues{})
|
||||
if err == nil {
|
||||
t.Fatal("Run() = nil error, want a failure: telegram configured with no allowed user IDs answers nobody")
|
||||
}
|
||||
if secrets.committed["env:ARCHIE_TELEGRAM_TOKEN"] != "" {
|
||||
t.Error("telegram token must not be committed when the flow aborts on missing allowed user IDs")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_TelegramWithAllowedUserIDs(t *testing.T) {
|
||||
p := &fakePrompter{
|
||||
lines: []string{"acme-archie", "", "gpt-5.4", "111, 222"},
|
||||
selects: []int{0, 2},
|
||||
secrets: []string{"sk-openai-token", "tg-token"},
|
||||
confirms: []bool{true},
|
||||
}
|
||||
secrets := newFakeSecrets()
|
||||
edits, err := Run(context.Background(), p, nil, secrets, ExistingValues{})
|
||||
if err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if err := secrets.Commit(); err != nil {
|
||||
t.Fatalf("Commit: %v", err)
|
||||
}
|
||||
cfg := generateAndLoad(t, edits)
|
||||
if want := (config.SecretRef{Engine: "env", Key: "ARCHIE_TELEGRAM_TOKEN"}); cfg.Chat.Telegram.Token != want {
|
||||
t.Errorf("chat.telegram.token = %+v, want %+v", cfg.Chat.Telegram.Token, want)
|
||||
}
|
||||
if len(cfg.Chat.Telegram.AllowedUserIDs) != 2 || cfg.Chat.Telegram.AllowedUserIDs[0] != 111 || cfg.Chat.Telegram.AllowedUserIDs[1] != 222 {
|
||||
t.Errorf("chat.telegram.allowed_user_ids = %v, want [111 222]", cfg.Chat.Telegram.AllowedUserIDs)
|
||||
}
|
||||
if got, want := secrets.committed["env:ARCHIE_TELEGRAM_TOKEN"], "tg-token"; got != want {
|
||||
t.Errorf("committed telegram token = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// config.example.toml ships [providers.openai] active by default with an
|
||||
// api_key pointing at the bws engine, which errors when the bws CLI isn't
|
||||
// installed. cmd/archied/provider_secrets.go resolves every entry in
|
||||
// cfg.Providers at startup, not just the ones [models] references, so an
|
||||
// operator who picks any other provider must not be left with that entry
|
||||
// still pointing at bws -- the daemon would refuse to boot on a config
|
||||
// setup itself produced.
|
||||
func TestRun_NonOpenAIProviderNeutralisesTemplateDefaultOpenAIKey(t *testing.T) {
|
||||
p := &fakePrompter{
|
||||
lines: []string{"acme-archie", "", "claude-opus"},
|
||||
selects: []int{1, 2}, // Anthropic, forge none
|
||||
secrets: []string{"sk-anthropic-token"},
|
||||
confirms: []bool{false},
|
||||
}
|
||||
secrets := newFakeSecrets()
|
||||
edits, err := Run(context.Background(), p, nil, secrets, ExistingValues{})
|
||||
if err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
cfg := generateAndLoad(t, edits)
|
||||
if cfg.Providers["openai"].APIKey != (secret.SecretRef{}) {
|
||||
t.Fatalf("providers.openai.api_key = %+v, want the zero value: it must not still point at the "+
|
||||
"template's default bws reference once a different provider is chosen, or the daemon refuses to boot",
|
||||
cfg.Providers["openai"].APIKey)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_OpenAISkippedKeyNeutralisesTemplateDefault(t *testing.T) {
|
||||
p := &fakePrompter{
|
||||
lines: []string{"acme-archie", "", "gpt-5.4"},
|
||||
selects: []int{0, 2}, // OpenAI, forge none
|
||||
secrets: []string{""},
|
||||
confirms: []bool{false},
|
||||
}
|
||||
secrets := newFakeSecrets()
|
||||
edits, err := Run(context.Background(), p, nil, secrets, ExistingValues{})
|
||||
if err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
cfg := generateAndLoad(t, edits)
|
||||
if cfg.Providers["openai"].APIKey != (secret.SecretRef{}) {
|
||||
t.Fatalf("providers.openai.api_key = %+v, want the zero value when the key prompt was left blank, "+
|
||||
"not the template's default bws reference", cfg.Providers["openai"].APIKey)
|
||||
}
|
||||
}
|
||||
|
||||
// The drift-bug regression test: for every forge type that writes a token,
|
||||
// the key decoded from the generated TOML must equal the key the secret was
|
||||
// actually stored under -- not merely equal some hardcoded literal on the
|
||||
// assertion side, which would pass even if both sides had independently
|
||||
// drifted to the same wrong value.
|
||||
func TestRun_ForgeTokenKeyMatchesStoredSecretKey(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
forgeIndex int
|
||||
lines []string
|
||||
secret string
|
||||
}{
|
||||
{name: "github", forgeIndex: 0, lines: []string{"acme-archie", "", "gpt-5.4"}, secret: "ghp-token"},
|
||||
{name: "gitea", forgeIndex: 1, lines: []string{"acme-archie", "", "gpt-5.4", "https://gitea.acme.internal"}, secret: "gitea-token"},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
p := &fakePrompter{
|
||||
lines: tc.lines,
|
||||
selects: []int{0, tc.forgeIndex},
|
||||
secrets: []string{"sk-openai-token", tc.secret},
|
||||
confirms: []bool{false},
|
||||
}
|
||||
secrets := newFakeSecrets()
|
||||
edits, err := Run(context.Background(), p, nil, secrets, ExistingValues{})
|
||||
if err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if err := secrets.Commit(); err != nil {
|
||||
t.Fatalf("Commit: %v", err)
|
||||
}
|
||||
cfg := generateAndLoad(t, edits)
|
||||
|
||||
storedUnderKey := ""
|
||||
for k, v := range secrets.committed {
|
||||
if v == tc.secret {
|
||||
storedUnderKey = k
|
||||
}
|
||||
}
|
||||
if storedUnderKey == "" {
|
||||
t.Fatalf("secret %q was never committed: %v", tc.secret, secrets.committed)
|
||||
}
|
||||
wantKey := "env:" + cfg.Forge.Token.Key
|
||||
if storedUnderKey != wantKey {
|
||||
t.Errorf("forge.token.key decodes to %q, but the secret was stored under %q -- these must match", cfg.Forge.Token.Key, storedUnderKey)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A second run against an already-generated config, changing one answer,
|
||||
// must not disturb the rest of the file -- tomlwrite's own guarantee
|
||||
// (archie-core-rs9), exercised here through setup's edits specifically.
|
||||
func TestRun_SecondRunAgainstOwnOutputChangesOnlyOneField(t *testing.T) {
|
||||
p1 := &fakePrompter{
|
||||
lines: []string{"acme-archie", "", "gpt-5.4"},
|
||||
selects: []int{0, 2},
|
||||
secrets: []string{"sk-openai-token"},
|
||||
confirms: []bool{false},
|
||||
}
|
||||
secrets := newFakeSecrets()
|
||||
edits1, err := Run(context.Background(), p1, nil, secrets, ExistingValues{})
|
||||
if err != nil {
|
||||
t.Fatalf("first Run: %v", err)
|
||||
}
|
||||
first, err := tomlwrite.Generate(configtemplate.Example, edits1)
|
||||
if err != nil {
|
||||
t.Fatalf("Generate: %v", err)
|
||||
}
|
||||
|
||||
p2 := &fakePrompter{
|
||||
lines: []string{"acme-archie-renamed", "", "gpt-5.4"},
|
||||
selects: []int{0, 2},
|
||||
secrets: []string{"sk-openai-token"},
|
||||
confirms: []bool{false},
|
||||
}
|
||||
edits2, err := Run(context.Background(), p2, nil, secrets, ExistingValues{BotUser: "acme-archie"})
|
||||
if err != nil {
|
||||
t.Fatalf("second Run: %v", err)
|
||||
}
|
||||
second, err := tomlwrite.Apply(first, edits2)
|
||||
if err != nil {
|
||||
t.Fatalf("Apply: %v", err)
|
||||
}
|
||||
|
||||
firstLines := splitLines(t, first)
|
||||
secondLines := splitLines(t, second)
|
||||
if len(firstLines) != len(secondLines) {
|
||||
t.Fatalf("line count changed: %d -> %d", len(firstLines), len(secondLines))
|
||||
}
|
||||
changed := 0
|
||||
for i := range firstLines {
|
||||
if firstLines[i] != secondLines[i] {
|
||||
changed++
|
||||
if firstLines[i] != `bot_user = "acme-archie"` {
|
||||
t.Errorf("unexpected line changed on re-run: %q -> %q", firstLines[i], secondLines[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
if changed != 1 {
|
||||
t.Errorf("expected exactly one changed line (bot_user), got %d", changed)
|
||||
}
|
||||
}
|
||||
|
||||
func splitLines(t *testing.T, b []byte) []string {
|
||||
t.Helper()
|
||||
var lines []string
|
||||
start := 0
|
||||
for i, c := range b {
|
||||
if c == '\n' {
|
||||
lines = append(lines, string(b[start:i]))
|
||||
start = i + 1
|
||||
}
|
||||
}
|
||||
if start < len(b) {
|
||||
lines = append(lines, string(b[start:]))
|
||||
}
|
||||
return lines
|
||||
}
|
||||
@@ -1,255 +0,0 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/agent"
|
||||
)
|
||||
|
||||
func TestConfigDirResolvesFilesAndDirectories(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := t.TempDir()
|
||||
configFile := filepath.Join(dir, "config.toml")
|
||||
if err := os.WriteFile(configFile, []byte(""), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
path string
|
||||
want string
|
||||
}{
|
||||
{name: "a directory is used as given", path: dir, want: dir},
|
||||
{name: "a file uses its directory", path: configFile, want: dir},
|
||||
{name: "a missing path falls back to its directory", path: filepath.Join(dir, "missing", "config.toml"), want: filepath.Join(dir, "missing")},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
if got := ConfigDir(test.path); got != test.want {
|
||||
t.Fatalf("ConfigDir(%q) = %q, want %q", test.path, got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSoulPath(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := t.TempDir()
|
||||
if got, want := SoulPath(dir), filepath.Join(dir, SoulFilename); got != want {
|
||||
t.Fatalf("SoulPath(dir) = %q, want %q", got, want)
|
||||
}
|
||||
configFile := filepath.Join(dir, "config.toml")
|
||||
if got, want := SoulPath(configFile), filepath.Join(dir, SoulFilename); got != want {
|
||||
t.Fatalf("SoulPath(file) = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeedSoulCreatesStarterWhenAbsent(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := t.TempDir()
|
||||
result, err := SeedSoul(dir, agent.ShippedSoul())
|
||||
if err != nil {
|
||||
t.Fatalf("SeedSoul() error = %v", err)
|
||||
}
|
||||
if result.Action != SoulCreated {
|
||||
t.Fatalf("SeedSoul() action = %q, want %q", result.Action, SoulCreated)
|
||||
}
|
||||
if want := filepath.Join(dir, SoulFilename); result.Path != want {
|
||||
t.Fatalf("SeedSoul() path = %q, want %q", result.Path, want)
|
||||
}
|
||||
got, err := os.ReadFile(result.Path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(got) != agent.ShippedSoul() {
|
||||
t.Fatalf("seeded SOUL = %q, want the shipped default", got)
|
||||
}
|
||||
info, err := os.Stat(result.Path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("seeded SOUL mode = %v, want 0600", info.Mode().Perm())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeedSoulNeverClobbersAUserEdit(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := t.TempDir()
|
||||
existing := "# My agent\n\nCall me Ada.\n"
|
||||
writeSoulTestFile(t, dir, existing)
|
||||
|
||||
result, err := SeedSoul(dir, agent.ShippedSoul())
|
||||
if err != nil {
|
||||
t.Fatalf("SeedSoul() error = %v", err)
|
||||
}
|
||||
if result.Action != SoulPreserved {
|
||||
t.Fatalf("SeedSoul() action = %q, want %q", result.Action, SoulPreserved)
|
||||
}
|
||||
if got := readSoulTestFile(t, dir); got != existing {
|
||||
t.Fatalf("user edit was changed:\n got %q\nwant %q", got, existing)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeedSoulPreservesAnEmptyFile(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := t.TempDir()
|
||||
writeSoulTestFile(t, dir, "")
|
||||
|
||||
result, err := SeedSoul(dir, agent.ShippedSoul())
|
||||
if err != nil {
|
||||
t.Fatalf("SeedSoul() error = %v", err)
|
||||
}
|
||||
if result.Action != SoulPreserved {
|
||||
t.Fatalf("SeedSoul() action = %q, want %q (an empty file is an existing file)", result.Action, SoulPreserved)
|
||||
}
|
||||
if got := readSoulTestFile(t, dir); got != "" {
|
||||
t.Fatalf("empty SOUL was changed to %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeedSoulLeavesACurrentDocumentUntouched(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := t.TempDir()
|
||||
// A CRLF checkout of the current document is still current: normalising
|
||||
// line endings must not make it look like a user edit, and it must not
|
||||
// provoke a rewrite on every boot.
|
||||
existing := strings.ReplaceAll(agent.ShippedSoul(), "\n", "\r\n")
|
||||
writeSoulTestFile(t, dir, existing)
|
||||
|
||||
result, err := SeedSoul(dir, agent.ShippedSoul())
|
||||
if err != nil {
|
||||
t.Fatalf("SeedSoul() error = %v", err)
|
||||
}
|
||||
if result.Action != SoulCurrent {
|
||||
t.Fatalf("SeedSoul() action = %q, want %q", result.Action, SoulCurrent)
|
||||
}
|
||||
if got := readSoulTestFile(t, dir); got != existing {
|
||||
t.Fatalf("current SOUL was rewritten:\n got %q\nwant %q", got, existing)
|
||||
}
|
||||
}
|
||||
|
||||
// A body that merely looks like a starter template is the user's until a build
|
||||
// ships it: the seeder must not rewrite content no upgrade produced. This fails
|
||||
// if an unshipped body is ever added to the recognised templates.
|
||||
func TestSeedSoulPreservesATemplateShapedUserEdit(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := t.TempDir()
|
||||
existing := "# Archie\n\nOld starter identity.\n"
|
||||
writeSoulTestFile(t, dir, existing)
|
||||
|
||||
result, err := SeedSoul(dir, agent.ShippedSoul())
|
||||
if err != nil {
|
||||
t.Fatalf("SeedSoul() error = %v", err)
|
||||
}
|
||||
if result.Action != SoulPreserved {
|
||||
t.Fatalf("SeedSoul() action = %q, want %q", result.Action, SoulPreserved)
|
||||
}
|
||||
if got := readSoulTestFile(t, dir); got != existing {
|
||||
t.Fatalf("template-shaped edit was changed:\n got %q\nwant %q", got, existing)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeedSoulPreservesASymlink(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := t.TempDir()
|
||||
target := filepath.Join(dir, "some-other-file.md")
|
||||
userContent := "# User-managed\n"
|
||||
if err := os.WriteFile(target, []byte(userContent), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
link := filepath.Join(dir, SoulFilename)
|
||||
if err := os.Symlink(target, link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
result, err := SeedSoul(dir, agent.ShippedSoul())
|
||||
if err != nil {
|
||||
t.Fatalf("SeedSoul() error = %v", err)
|
||||
}
|
||||
if result.Action != SoulPreserved {
|
||||
t.Fatalf("SeedSoul() action = %q, want %q", result.Action, SoulPreserved)
|
||||
}
|
||||
info, err := os.Lstat(link)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Mode()&os.ModeSymlink == 0 {
|
||||
t.Fatal("SeedSoul replaced a symlink with a regular file")
|
||||
}
|
||||
got, err := os.ReadFile(target)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(got) != userContent {
|
||||
t.Fatalf("symlink target was changed to %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeedSoulTreatsAnOversizedFileAsAUserEdit(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := t.TempDir()
|
||||
oversized := agent.ShippedSoul() + strings.Repeat("padding line\n", maxSoulReadBytes/8)
|
||||
writeSoulTestFile(t, dir, oversized)
|
||||
|
||||
result, err := SeedSoul(dir, agent.ShippedSoul())
|
||||
if err != nil {
|
||||
t.Fatalf("SeedSoul() error = %v", err)
|
||||
}
|
||||
if result.Action != SoulPreserved {
|
||||
t.Fatalf("SeedSoul() action = %q, want %q", result.Action, SoulPreserved)
|
||||
}
|
||||
if got := readSoulTestFile(t, dir); got != oversized {
|
||||
t.Fatal("oversized SOUL was rewritten")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeedSoulSeedsBesideASelectedConfigFile(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := t.TempDir()
|
||||
configFile := filepath.Join(dir, "config.toml")
|
||||
if err := os.WriteFile(configFile, []byte(""), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
result, err := SeedSoul(configFile, agent.ShippedSoul())
|
||||
if err != nil {
|
||||
t.Fatalf("SeedSoul() error = %v", err)
|
||||
}
|
||||
if result.Action != SoulCreated {
|
||||
t.Fatalf("SeedSoul() action = %q, want %q", result.Action, SoulCreated)
|
||||
}
|
||||
if want := filepath.Join(dir, SoulFilename); result.Path != want {
|
||||
t.Fatalf("SeedSoul() path = %q, want %q", result.Path, want)
|
||||
}
|
||||
}
|
||||
|
||||
func writeSoulTestFile(t *testing.T, dir, content string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(filepath.Join(dir, SoulFilename), []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func readSoulTestFile(t *testing.T, dir string) string {
|
||||
t.Helper()
|
||||
data, err := os.ReadFile(filepath.Join(dir, SoulFilename))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
package tomlwrite_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration/tomlwrite"
|
||||
)
|
||||
|
||||
const sample = `# archied configuration.
|
||||
poll_interval = "60s"
|
||||
label = "archie" # display label
|
||||
|
||||
[forge]
|
||||
type = "github"
|
||||
host = "https://github.com"
|
||||
token = { engine = "env", key = "ARCHIE_GITHUB_TOKEN" }
|
||||
|
||||
# [chat]
|
||||
# operator = "Ada Lovelace"
|
||||
# workspace = "~/.local/share/archie/workspace"
|
||||
# max_steps = 100
|
||||
|
||||
[budgets]
|
||||
max_steps = 60
|
||||
`
|
||||
|
||||
func TestApply_ActiveKey_ReplacesValuePreservesComment(t *testing.T) {
|
||||
out, err := tomlwrite.Apply([]byte(sample), []tomlwrite.Edit{
|
||||
{Table: "", Key: "label", Value: tomlwrite.String("acme")},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := strings.Replace(sample, `label = "archie" # display label`, `label = "acme" # display label`, 1)
|
||||
if string(out) != want {
|
||||
t.Fatalf("unexpected output:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApply_ActiveInlineTable_Replaces(t *testing.T) {
|
||||
out, err := tomlwrite.Apply([]byte(sample), []tomlwrite.Edit{
|
||||
{Table: "forge", Key: "token", Value: tomlwrite.Ref("env", "GITEA_TOKEN")},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := strings.Replace(sample,
|
||||
`token = { engine = "env", key = "ARCHIE_GITHUB_TOKEN" }`,
|
||||
`token = { engine = "env", key = "GITEA_TOKEN" }`, 1)
|
||||
if string(out) != want {
|
||||
t.Fatalf("unexpected output:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApply_CommentedTable_UncommentsOnlyRequestedKey(t *testing.T) {
|
||||
out, err := tomlwrite.Apply([]byte(sample), []tomlwrite.Edit{
|
||||
{Table: "chat", Key: "operator", Value: tomlwrite.String("Ada Lovelace")},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := string(out)
|
||||
if !strings.Contains(got, "\n[chat]\noperator = \"Ada Lovelace\"\n# workspace = \"~/.local/share/archie/workspace\"\n# max_steps = 100\n") {
|
||||
t.Fatalf("expected header and operator uncommented, siblings left commented, got:\n%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApply_MissingKeyInExistingActiveTable_Appends(t *testing.T) {
|
||||
out, err := tomlwrite.Apply([]byte(sample), []tomlwrite.Edit{
|
||||
{Table: "budgets", Key: "wall_clock", Value: "\"45m\""},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := string(out)
|
||||
if !strings.Contains(got, "[budgets]\nmax_steps = 60\nwall_clock = \"45m\"\n") {
|
||||
t.Fatalf("expected wall_clock appended after max_steps, got:\n%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApply_NewTable_AppendedAtEnd(t *testing.T) {
|
||||
out, err := tomlwrite.Apply([]byte(sample), []tomlwrite.Edit{
|
||||
{Table: "providers.anthropic", Key: "class", Value: tomlwrite.String("anthropic")},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := string(out)
|
||||
if !strings.HasSuffix(got, "\n\n[providers.anthropic]\nclass = \"anthropic\"\n") {
|
||||
t.Fatalf("expected new table appended at end, got:\n%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestApply_UnrelatedLinesByteIdentical is the archie-core-rs9 acceptance
|
||||
// criterion: changing one value must not touch any other line, comments
|
||||
// included.
|
||||
func TestApply_UnrelatedLinesByteIdentical(t *testing.T) {
|
||||
out, err := tomlwrite.Apply([]byte(sample), []tomlwrite.Edit{
|
||||
{Table: "", Key: "label", Value: tomlwrite.String("acme")},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
beforeLines := strings.Split(sample, "\n")
|
||||
afterLines := strings.Split(string(out), "\n")
|
||||
if len(beforeLines) != len(afterLines) {
|
||||
t.Fatalf("line count changed: %d -> %d", len(beforeLines), len(afterLines))
|
||||
}
|
||||
for i := range beforeLines {
|
||||
if strings.HasPrefix(beforeLines[i], "label") {
|
||||
continue
|
||||
}
|
||||
if beforeLines[i] != afterLines[i] {
|
||||
t.Fatalf("line %d changed unexpectedly:\n- %q\n+ %q", i, beforeLines[i], afterLines[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestApply_Idempotent_SecondRunLeavesOtherEditByteIdentical mirrors a
|
||||
// real setup re-run: apply one edit, then apply a second, different edit
|
||||
// to the result, and check the first edit's line -- and everything else
|
||||
// unrelated to either edit -- is untouched.
|
||||
func TestApply_Idempotent_SecondRunLeavesOtherEditByteIdentical(t *testing.T) {
|
||||
first, err := tomlwrite.Apply([]byte(sample), []tomlwrite.Edit{
|
||||
{Table: "", Key: "label", Value: tomlwrite.String("acme")},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := tomlwrite.Apply(first, []tomlwrite.Edit{
|
||||
{Table: "forge", Key: "host", Value: tomlwrite.String("https://gitea.example.com")},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
firstLines := strings.Split(string(first), "\n")
|
||||
secondLines := strings.Split(string(second), "\n")
|
||||
if len(firstLines) != len(secondLines) {
|
||||
t.Fatalf("line count changed: %d -> %d", len(firstLines), len(secondLines))
|
||||
}
|
||||
for i := range firstLines {
|
||||
if strings.HasPrefix(secondLines[i], "host") {
|
||||
continue
|
||||
}
|
||||
if firstLines[i] != secondLines[i] {
|
||||
t.Fatalf("line %d changed unexpectedly on second run:\n- %q\n+ %q", i, firstLines[i], secondLines[i])
|
||||
}
|
||||
}
|
||||
if !strings.Contains(string(second), `label = "acme"`) {
|
||||
t.Fatalf("first run's edit was lost on second run:\n%s", second)
|
||||
}
|
||||
}
|
||||
|
||||
// [models], [web], and [notify] in the real template all carry
|
||||
// a trailing "# ..." comment on the header line itself
|
||||
// ("[models] # role -> ..."). The header regexes were anchored with no
|
||||
// allowance for that, so Apply's table-tracking never recognised these as
|
||||
// table headers at all -- an edit targeting "models" fell through every
|
||||
// matching stage and got appended as a brand-new duplicate [models] table
|
||||
// at EOF, which BurntSushi/toml then refuses to decode ("Key 'models' has
|
||||
// already been defined"). archied setup's models step targets exactly this
|
||||
// table.
|
||||
func TestApply_ActiveHeaderWithTrailingComment_IsRecognised(t *testing.T) {
|
||||
src := `[models] # role -> ai-sdk runtime ref
|
||||
triage = "openai/gpt-5.4"
|
||||
|
||||
[budgets]
|
||||
max_steps = 60
|
||||
`
|
||||
out, err := tomlwrite.Apply([]byte(src), []tomlwrite.Edit{
|
||||
{Table: "models", Key: "planner", Value: tomlwrite.String("openai/gpt-5.4")},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := string(out)
|
||||
if strings.Count(got, "planner") != 1 {
|
||||
t.Fatalf("expected exactly one planner line, got:\n%s", got)
|
||||
}
|
||||
if strings.Contains(got, "\n[models]\n") {
|
||||
t.Fatalf("a second, commentless [models] table was appended instead of reusing the commented-header one:\n%s", got)
|
||||
}
|
||||
var decoded config.Config
|
||||
if _, err := toml.Decode(got, &decoded); err != nil {
|
||||
t.Fatalf("output does not parse as TOML: %v\n%s", err, got)
|
||||
}
|
||||
if decoded.Models["triage"] != "openai/gpt-5.4" || decoded.Models["planner"] != "openai/gpt-5.4" {
|
||||
t.Fatalf("models did not round-trip: got %+v", decoded.Models)
|
||||
}
|
||||
}
|
||||
@@ -1,221 +0,0 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// minimalValidConfigTOML is enough to pass Validate on its own, so these tests
|
||||
// isolate the unknown-key behaviour from unrelated validation failures.
|
||||
const minimalValidConfigTOML = "bot_user = \"widget\"\nwork_dir = \"/base/work\"\n"
|
||||
|
||||
// TestUnknownKeysAreReported pins plan-config-drift.md step 1: a
|
||||
// misspelled key must not parse, validate and silently do nothing. Today
|
||||
// (before the fix) it loads with zero indication anything was ignored.
|
||||
func TestUnknownKeysAreReported(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
src := minimalValidConfigTOML + "[containers]\nmax_concurrancy = 4\n" // typo: concurrancy
|
||||
if err := os.WriteFile(path, []byte(src), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
doc, err := New(nil).File(path)
|
||||
if err != nil {
|
||||
t.Fatalf("File: %v (an unknown key must not fail the load)", err)
|
||||
}
|
||||
if len(doc.UnknownKeys) == 0 {
|
||||
t.Fatal("UnknownKeys is empty, want the typo'd key reported")
|
||||
}
|
||||
found := false
|
||||
for _, k := range doc.UnknownKeys {
|
||||
if k == "containers.max_concurrancy" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("UnknownKeys = %v, want it to contain %q", doc.UnknownKeys, "containers.max_concurrancy")
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidSchedulingBlockIsNotReportedAsUnknown pins Hazard 1 from
|
||||
// plan-config-drift.md: one file feeds both &doc.Config and
|
||||
// &doc.Scheduling. Reporting either target's Undecoded() verbatim would
|
||||
// flag every config carrying a real [scheduling] block, since Config has
|
||||
// no "scheduling" field and SchedulingInput has nothing else.
|
||||
func TestValidSchedulingBlockIsNotReportedAsUnknown(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
src := minimalValidConfigTOML + "[scheduling]\ninterval = \"60s\"\nmax_parallel = 4\n"
|
||||
if err := os.WriteFile(path, []byte(src), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
doc, err := New(nil).File(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(doc.UnknownKeys) != 0 {
|
||||
t.Errorf("UnknownKeys = %v, want none: a valid [scheduling] block is not an unknown key", doc.UnknownKeys)
|
||||
}
|
||||
if doc.Scheduling.MaxParallel != 4 {
|
||||
t.Errorf("Scheduling.MaxParallel = %d, want 4 (scheduling must still decode correctly)", doc.Scheduling.MaxParallel)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUnknownSchedulingKeyIsStillReported is the mirror of the Hazard 1
|
||||
// test: a typo inside [scheduling] must not be masked by the intersection
|
||||
// logic that protects legitimate cross-target keys.
|
||||
func TestUnknownSchedulingKeyIsStillReported(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
src := minimalValidConfigTOML + "[scheduling]\nmax_parallell = 4\n" // typo: extra "l"
|
||||
if err := os.WriteFile(path, []byte(src), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
doc, err := New(nil).File(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := false
|
||||
for _, k := range doc.UnknownKeys {
|
||||
if k == "scheduling.max_parallell" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("UnknownKeys = %v, want it to contain %q", doc.UnknownKeys, "scheduling.max_parallell")
|
||||
}
|
||||
}
|
||||
|
||||
// TestOverlayUnknownKeysAreStillReported pins that the overlay path kept its
|
||||
// drift detection when the overlay file started being applied through the
|
||||
// config fold instead of being decoded into the document's config. That matters
|
||||
// twice over there: the report comes from a separate decode, and a file is
|
||||
// parsed by TOML while the fold applies it with a yaml decode, which do not
|
||||
// match keys the same way. A key the APPLY cannot consume has to be reported,
|
||||
// or a spelling that works in the base config would silently do nothing in the
|
||||
// overlay.
|
||||
func TestOverlayUnknownKeysAreStillReported(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
overlay string
|
||||
wantUnknown string
|
||||
}{
|
||||
{
|
||||
name: "a key no decode target consumes",
|
||||
overlay: "[containers]\nmax_concurrancy = 4\n", // typo: concurrancy
|
||||
wantUnknown: "containers.max_concurrancy",
|
||||
},
|
||||
{
|
||||
// TOML matches keys case-insensitively, so the file's own decode
|
||||
// consumes BOT_USER and reports nothing; the apply folds the file's
|
||||
// mapping with a yaml decode, which does not match it. Without the
|
||||
// second source for this report the value would be dropped in
|
||||
// silence, so the spelling is reported instead.
|
||||
name: "a key only the file decode can match",
|
||||
overlay: "BOT_USER = \"upper\"\n",
|
||||
wantUnknown: "BOT_USER",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
basePath := filepath.Join(dir, "config.toml")
|
||||
overlayPath := filepath.Join(dir, "dev.toml")
|
||||
if err := os.WriteFile(basePath, []byte(minimalValidConfigTOML), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(overlayPath, []byte(tt.overlay), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
doc, err := New(nil).Resolve(basePath, overlayPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v (an unknown key must not fail the load)", err)
|
||||
}
|
||||
if !slices.Contains(doc.UnknownKeys, tt.wantUnknown) {
|
||||
t.Errorf("UnknownKeys = %v, want it to contain %q", doc.UnknownKeys, tt.wantUnknown)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestExampleConfigHasNoUnknownKeys is the contract test the design
|
||||
// promised: the checked-in template must never itself trip the detector.
|
||||
func TestExampleConfigHasNoUnknownKeys(t *testing.T) {
|
||||
doc, err := New(nil).File(filepath.Join("..", "..", "..", "config.example.toml"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(doc.UnknownKeys) != 0 {
|
||||
t.Errorf("config.example.toml has unknown keys: %v", doc.UnknownKeys)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeploymentOverlaysHaveNoUnknownKeys covers every shipped overlay
|
||||
// profile the same way, loaded as they are in production: layered over
|
||||
// config.example.toml via -config-overlay.
|
||||
func TestDeploymentOverlaysHaveNoUnknownKeys(t *testing.T) {
|
||||
base := filepath.Join("..", "..", "..", "config.example.toml")
|
||||
dir := filepath.Join("..", "..", "..", "deployments")
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, e := range entries {
|
||||
if filepath.Ext(e.Name()) != ".toml" {
|
||||
continue
|
||||
}
|
||||
t.Run(e.Name(), func(t *testing.T) {
|
||||
doc, err := New(nil).Overlay(base, filepath.Join(dir, e.Name()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(doc.UnknownKeys) != 0 {
|
||||
t.Errorf("%s has unknown keys: %v", e.Name(), doc.UnknownKeys)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestRemovedFieldsSurfaceAsUnknownKeys pins the removal of two fields that
|
||||
// were decoded but read nowhere. Once they are gone the compiler guards
|
||||
// nothing, so the unknown-key detector is the only thing left that can tell an
|
||||
// operator their setting does nothing -- which is the whole reason to remove
|
||||
// them rather than leave a live-looking knob wired to nothing.
|
||||
func TestRemovedFieldsSurfaceAsUnknownKeys(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
block string
|
||||
key string
|
||||
}{
|
||||
{
|
||||
name: "memory session_ttl",
|
||||
block: "[memory]\nsession_ttl = \"72h\"\n",
|
||||
key: "memory.session_ttl",
|
||||
},
|
||||
{
|
||||
name: "tool policy parallel_execution",
|
||||
block: "[tools.tool_policy]\nparallel_execution = true\n",
|
||||
key: "tools.tool_policy.parallel_execution",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
if err := os.WriteFile(path, []byte(minimalValidConfigTOML+tt.block), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
doc, err := New(nil).File(path)
|
||||
if err != nil {
|
||||
t.Fatalf("File: %v (a removed key must not fail the load)", err)
|
||||
}
|
||||
if slices.Contains(doc.UnknownKeys, tt.key) {
|
||||
return
|
||||
}
|
||||
t.Errorf("UnknownKeys = %v, want it to contain %q", doc.UnknownKeys, tt.key)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,681 +0,0 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"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),
|
||||
Dispatch: config.Dispatch{
|
||||
Trigger: "assignee",
|
||||
},
|
||||
Forge: config.Forge{Type: "none"},
|
||||
Containers: config.ContainerConfig{
|
||||
Image: "ghcr.io/samcharles93/archie-agent:latest",
|
||||
},
|
||||
Services: config.Services{
|
||||
config.ServiceNameGateway: {Target: "127.0.0.1:8585"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidate_RejectsTheSameProblemsAsLoaderLoad pins the direction that still
|
||||
// holds after archie-core-i3qm split the bootstrap checks from the effective
|
||||
// ones: every problem the load path rejects, Validate rejects too. Validate
|
||||
// additionally rejects the settings the control plane owns, which the load path
|
||||
// must let through (validateBootstrap) so a stale TOML value cannot fail a
|
||||
// process's startup. The name is kept from when the two check sets were equal.
|
||||
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 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: "unrecognised memory.engine",
|
||||
mutate: func(cfg *config.Config) { cfg.Memory.Engine = "not-a-real-engine" },
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "recognised memory.engine",
|
||||
mutate: func(cfg *config.Config) { cfg.Memory.Engine = "builtin" },
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "empty memory.engine is not unrecognised",
|
||||
mutate: func(cfg *config.Config) { cfg.Memory.Engine = "" },
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
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 full-task workers work with either embedded
|
||||
// or external broker deployment.
|
||||
func TestValidateNATS(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mode string
|
||||
url 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: "removed off mode", mode: "off", wantErr: true},
|
||||
{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: "removed off mode with url", mode: "off", url: "nats://localhost:4222", wantErr: true},
|
||||
{name: "unknown mode", mode: "not-a-mode", wantErr: true},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cfg := minimalValidConfig()
|
||||
cfg.NATS = config.NATSConfig{Mode: tc.mode, URL: tc.url}
|
||||
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 TestValidateContainersSupportsBothBrokerDeployments(t *testing.T) {
|
||||
base := func() config.Config {
|
||||
cfg := minimalValidConfig()
|
||||
cfg.Containers = config.ContainerConfig{Image: "archie-agent:latest"}
|
||||
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 supports containers", func(t *testing.T) {
|
||||
cfg := base()
|
||||
cfg.NATS.Mode = config.NATSModeEmbedded
|
||||
if err := Validate(&cfg); err != nil {
|
||||
t.Fatalf("Validate() = %v, want nil for managed containers with embedded nats", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestValidateContainersRegistryAuth pins that a registry credential naming
|
||||
// only half a secret reference is refused while the zero reference (anonymous
|
||||
// pulls) is accepted: a half-named ref can only be a typo, and the pool cannot
|
||||
// resolve it into the header a private registry needs.
|
||||
func TestValidateContainersRegistryAuth(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ref secret.SecretRef
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "unset pulls anonymously"},
|
||||
{name: "both halves named", ref: secret.SecretRef{Engine: "env", Key: "REGISTRY_AUTH"}},
|
||||
{name: "engine only", ref: secret.SecretRef{Engine: "env"}, wantErr: true},
|
||||
{name: "key only", ref: secret.SecretRef{Key: "REGISTRY_AUTH"}, wantErr: true},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cfg := minimalValidConfig()
|
||||
cfg.Containers.RegistryAuth = tc.ref
|
||||
err := Validate(&cfg)
|
||||
if tc.wantErr {
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("Validate() = %v, want ErrInvalidInput", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("Validate() = %v, want nil", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 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: "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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateForgeIntakeRejectsIdentityIntake pins that an intake setting on
|
||||
// a [[identities]] entry is refused instead of accepted-and-ignored.
|
||||
// IdentityConfig.Forge is the same type as the root [forge] block, so
|
||||
// identities[N].forge.intake, .webhook_secret and .webhook_addr all decode --
|
||||
// but every intake read is of the root block, so before this check they
|
||||
// parsed, reached no code path, and were never even validated. A setting an
|
||||
// operator can spell that nothing reads is a lie in the config file.
|
||||
func TestValidateForgeIntakeRejectsIdentityIntake(t *testing.T) {
|
||||
// identity builds one entry whose forge is otherwise valid, so a
|
||||
// rejection can only come from the field the case sets.
|
||||
identity := func(mutate func(*config.Forge)) config.IdentityConfig {
|
||||
forge := config.Forge{
|
||||
Type: "github",
|
||||
Token: config.SecretRef{Engine: "env", Key: "ARCHIE_GITHUB_TOKEN"},
|
||||
}
|
||||
if mutate != nil {
|
||||
mutate(&forge)
|
||||
}
|
||||
return config.IdentityConfig{Name: "personal", BotUser: "archie-personal", Forge: forge}
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
identities []config.IdentityConfig
|
||||
// want lists fragments the error must carry; empty means no error.
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "unset intake on an identity is valid",
|
||||
identities: []config.IdentityConfig{identity(nil)},
|
||||
},
|
||||
{
|
||||
name: "poll intake on an identity is valid",
|
||||
identities: []config.IdentityConfig{identity(func(f *config.Forge) {
|
||||
f.Intake = config.ForgeIntakePoll
|
||||
})},
|
||||
},
|
||||
{
|
||||
name: "webhook intake on an identity is rejected with the identity, setting, and reason",
|
||||
identities: []config.IdentityConfig{identity(func(f *config.Forge) {
|
||||
f.Intake = config.ForgeIntakeWebhook
|
||||
})},
|
||||
want: []string{`identities[0] ("personal").forge.intake "webhook"`, "per-identity webhook intake is not implemented"},
|
||||
},
|
||||
{
|
||||
name: "both intake on an identity is rejected with the identity, setting, and reason",
|
||||
identities: []config.IdentityConfig{identity(func(f *config.Forge) {
|
||||
f.Intake = config.ForgeIntakeBoth
|
||||
})},
|
||||
want: []string{`identities[0] ("personal").forge.intake "both"`, "per-identity webhook intake is not implemented"},
|
||||
},
|
||||
{
|
||||
name: "an unknown intake on an identity names the accepted value",
|
||||
identities: []config.IdentityConfig{identity(func(f *config.Forge) {
|
||||
f.Intake = "sometimes"
|
||||
})},
|
||||
want: []string{`identities[0] ("personal").forge.intake "sometimes"`, "want poll"},
|
||||
},
|
||||
{
|
||||
name: "webhook_secret on an identity is rejected",
|
||||
identities: []config.IdentityConfig{identity(func(f *config.Forge) {
|
||||
f.WebhookSecret = config.SecretRef{Engine: "env", Key: "ARCHIE_WEBHOOK_SECRET"}
|
||||
})},
|
||||
want: []string{`identities[0] ("personal").forge.webhook_secret`, "per-identity webhook intake is not implemented"},
|
||||
},
|
||||
{
|
||||
name: "webhook_addr on an identity is rejected",
|
||||
identities: []config.IdentityConfig{identity(func(f *config.Forge) {
|
||||
f.WebhookAddr = "0.0.0.0:8645"
|
||||
})},
|
||||
want: []string{`identities[0] ("personal").forge.webhook_addr`, "per-identity webhook intake is not implemented"},
|
||||
},
|
||||
{
|
||||
// The offender is the second entry: the message must locate it, not
|
||||
// report "an identity" for a file whose first identity is fine.
|
||||
name: "the rejected identity is the one named, not the first",
|
||||
identities: []config.IdentityConfig{
|
||||
identity(nil),
|
||||
{
|
||||
Name: "work",
|
||||
BotUser: "archie-work",
|
||||
Forge: config.Forge{
|
||||
Type: "gitea",
|
||||
Intake: config.ForgeIntakeWebhook,
|
||||
Token: config.SecretRef{Engine: "env", Key: "ARCHIE_GITEA_TOKEN"},
|
||||
},
|
||||
},
|
||||
},
|
||||
want: []string{`identities[1] ("work").forge.intake "webhook"`},
|
||||
},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cfg := minimalValidConfig()
|
||||
cfg.Identities = tc.identities
|
||||
requireValidateError(t, validateForgeIntake(&cfg), tc.want)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateForgeIntakeRejectsRootWebhookIntakeWithIdentities pins the other
|
||||
// half of the same lie: [forge].intake = "webhook"/"both" alongside
|
||||
// [[identities]] used to start the daemon, which logged "forge webhook
|
||||
// disabled: multi-identity deployments are not supported yet" and polled
|
||||
// instead. Failing closed at validation replaces that silent downgrade.
|
||||
func TestValidateForgeIntakeRejectsRootWebhookIntakeWithIdentities(t *testing.T) {
|
||||
identity := config.IdentityConfig{
|
||||
Name: "personal",
|
||||
BotUser: "archie-personal",
|
||||
Forge: config.Forge{
|
||||
Type: "github",
|
||||
Token: config.SecretRef{Engine: "env", Key: "ARCHIE_GITHUB_TOKEN"},
|
||||
},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
intake string
|
||||
identities []config.IdentityConfig
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "webhook intake plus identities is rejected",
|
||||
intake: config.ForgeIntakeWebhook,
|
||||
identities: []config.IdentityConfig{identity},
|
||||
want: []string{`forge.intake "webhook"`, "alongside [[identities]]", `forge.intake = "poll"`},
|
||||
},
|
||||
{
|
||||
name: "both intake plus identities is rejected",
|
||||
intake: config.ForgeIntakeBoth,
|
||||
identities: []config.IdentityConfig{identity},
|
||||
want: []string{`forge.intake "both"`, "alongside [[identities]]", `forge.intake = "poll"`},
|
||||
},
|
||||
{
|
||||
name: "poll intake plus identities stays valid",
|
||||
intake: config.ForgeIntakePoll,
|
||||
identities: []config.IdentityConfig{identity},
|
||||
},
|
||||
{
|
||||
name: "webhook intake with no identities stays valid",
|
||||
intake: config.ForgeIntakeWebhook,
|
||||
identities: nil,
|
||||
},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cfg := minimalValidConfig()
|
||||
cfg.Forge.Intake = tc.intake
|
||||
cfg.Forge.WebhookAddr = "0.0.0.0:8645"
|
||||
if tc.intake == config.ForgeIntakeWebhook || tc.intake == config.ForgeIntakeBoth {
|
||||
// Supply the secret and address the receiver would need, so a
|
||||
// rejection can only come from the combination itself and not
|
||||
// from a missing webhook setting.
|
||||
cfg.Forge.WebhookSecret = config.SecretRef{Engine: "env", Key: "ARCHIE_WEBHOOK_SECRET"}
|
||||
}
|
||||
cfg.Identities = tc.identities
|
||||
requireValidateError(t, validateForgeIntake(&cfg), tc.want)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoaderRejectsIdentityIntakeFromFile drives the rejection through the
|
||||
// real file path, because the defect was that the key DECODES. Asserting on
|
||||
// validateForgeIntake alone would not prove an operator's
|
||||
// [identities.forge] intake = "webhook" is refused where they would hit it.
|
||||
func TestLoaderRejectsIdentityIntakeFromFile(t *testing.T) {
|
||||
const doc = `
|
||||
bot_user = "archie-bot"
|
||||
|
||||
[services.gateway]
|
||||
target = "127.0.0.1:8585"
|
||||
|
||||
[forge]
|
||||
type = "none"
|
||||
|
||||
[containers]
|
||||
image = "ghcr.io/samcharles93/archie-agent:latest"
|
||||
|
||||
[[identities]]
|
||||
name = "personal"
|
||||
bot_user = "archie-personal"
|
||||
|
||||
[identities.forge]
|
||||
type = "github"
|
||||
intake = "webhook"
|
||||
token = { engine = "env", key = "ARCHIE_GITHUB_TOKEN" }
|
||||
|
||||
[[identities.repos]]
|
||||
owner = "my-org"
|
||||
name = "my-repo"
|
||||
`
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
if err := os.WriteFile(path, []byte(doc), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, err := New(nil).File(path)
|
||||
requireValidateError(t, err, []string{`identities[0] ("personal").forge.intake "webhook"`, "not implemented"})
|
||||
}
|
||||
|
||||
// deploymentOverlays are the files in deployments/ that are not standalone
|
||||
// profiles. dev.toml layers over an installed config (`task dev` passes it as
|
||||
// -config-overlay) so it legitimately carries no bot_user; every other file
|
||||
// here is a template an operator copies to config.toml and expects to start.
|
||||
var deploymentOverlays = map[string]bool{"dev.toml": true}
|
||||
|
||||
// TestShippedProfilesValidate guards every standalone profile the repository
|
||||
// ships against a validation rule that would reject it. AGENTS.md lists
|
||||
// deployments/ as the supported profiles, so a profile that cannot load is a
|
||||
// documented deployment path that cannot start at all. The directory is
|
||||
// enumerated rather than a list of filenames repeated here, so a profile added
|
||||
// later is covered the moment it is committed instead of the moment someone
|
||||
// remembers this test.
|
||||
func TestShippedProfilesValidate(t *testing.T) {
|
||||
paths, err := filepath.Glob(filepath.Join("..", "..", "..", "deployments", "*.toml"))
|
||||
if err != nil {
|
||||
t.Fatalf("glob deployment profiles: %v", err)
|
||||
}
|
||||
if len(paths) == 0 {
|
||||
t.Fatal("no deployment profiles matched; the glob is wrong, not the profiles")
|
||||
}
|
||||
|
||||
seen := make(map[string]bool, len(paths))
|
||||
for _, path := range paths {
|
||||
seen[filepath.Base(path)] = true
|
||||
}
|
||||
// An exclusion that no longer names a real file would silently widen the
|
||||
// rule, so it is checked as well.
|
||||
for name := range deploymentOverlays {
|
||||
if !seen[name] {
|
||||
t.Errorf("deploymentOverlays names %q, which deployments/ does not contain", name)
|
||||
}
|
||||
}
|
||||
|
||||
var checked int
|
||||
for _, path := range paths {
|
||||
if deploymentOverlays[filepath.Base(path)] {
|
||||
continue
|
||||
}
|
||||
checked++
|
||||
t.Run(filepath.Base(path), func(t *testing.T) {
|
||||
doc, err := New(nil).File(path)
|
||||
if err != nil {
|
||||
t.Fatalf("load %s: %v", path, err)
|
||||
}
|
||||
if err := Validate(&doc.Config); err != nil {
|
||||
t.Fatalf("validate %s: %v", path, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
if checked == 0 {
|
||||
t.Fatal("every discovered profile was excluded, so this test asserts nothing")
|
||||
}
|
||||
}
|
||||
|
||||
// requireValidateError asserts err wraps ErrInvalidInput and carries every
|
||||
// fragment in want. An error that only said "invalid input" would leave the
|
||||
// operator guessing which of the file's settings to fix, so every rejection
|
||||
// above is asserted on the words that name the setting.
|
||||
func requireValidateError(t *testing.T, err error, want []string) {
|
||||
t.Helper()
|
||||
if len(want) == 0 {
|
||||
if err != nil {
|
||||
t.Fatalf("got error %v, want the configuration accepted", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatal("got nil error, want a rejection")
|
||||
}
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("error %v does not wrap ErrInvalidInput", err)
|
||||
}
|
||||
for _, fragment := range want {
|
||||
if !strings.Contains(err.Error(), fragment) {
|
||||
t.Errorf("error %q does not name %q", err, fragment)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateMemoryNamesTheValidSet pins the AC this satisfies: an
|
||||
// unknown memory.engine is rejected with a clear error naming the valid
|
||||
// set, in the same style forge.type already uses.
|
||||
func TestValidateMemoryNamesTheValidSet(t *testing.T) {
|
||||
cfg := minimalValidConfig()
|
||||
cfg.Memory.Engine = "not-a-real-engine"
|
||||
|
||||
err := validateMemory(&cfg)
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("validateMemory(unknown engine) = %v, want wrapping ErrInvalidInput", err)
|
||||
}
|
||||
if got, want := err.Error(), `memory.engine "not-a-real-engine" (want builtin)`; !strings.Contains(got, want) {
|
||||
t.Errorf("error text = %q, want it to contain %q", got, want)
|
||||
}
|
||||
}
|
||||
@@ -1,356 +0,0 @@
|
||||
// Shared fixtures for the crondelivery tests. The fakes here come in two
|
||||
// flavours, and the distinction is load-bearing: the "naive" ones ignore ctx
|
||||
// entirely, so a cancellation test built on them proves the RUNNER's own guard
|
||||
// is what suppresses the side effect, rather than the fake's good manners.
|
||||
package crondelivery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/scheduling"
|
||||
)
|
||||
|
||||
// --- fakes --------------------------------------------------------------------
|
||||
|
||||
// naiveCourier records every call unconditionally and ignores ctx entirely. It
|
||||
// models the worst realistic transport — one that would send after shutdown —
|
||||
// so a test using it proves the RUNNER's own cancellation guard is what
|
||||
// prevents the side effect, not the fake's good manners.
|
||||
type naiveCourier struct {
|
||||
mu sync.Mutex
|
||||
calls int
|
||||
chats []string
|
||||
texts []string
|
||||
}
|
||||
|
||||
func (n *naiveCourier) send(_ context.Context, chatID, text string) error {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
n.calls++
|
||||
n.chats = append(n.chats, chatID)
|
||||
n.texts = append(n.texts, text)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *naiveCourier) snapshot() (chats, texts []string, calls int) {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
return append([]string(nil), n.chats...), append([]string(nil), n.texts...), n.calls
|
||||
}
|
||||
|
||||
// naiveSubmitter mirrors naiveCourier for the workflow path.
|
||||
type naiveSubmitter struct {
|
||||
mu sync.Mutex
|
||||
calls int
|
||||
ids []string
|
||||
}
|
||||
|
||||
func (n *naiveSubmitter) Submit(_ context.Context, identity, _, _ string) error {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
n.calls++
|
||||
n.ids = append(n.ids, identity)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *naiveSubmitter) count() int {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
return n.calls
|
||||
}
|
||||
|
||||
// naiveRunner counts calls and ignores ctx, like naiveCourier. It is what the
|
||||
// router's cancellation case forwards to, so the router's own guard is the only
|
||||
// thing that can stop the dispatch.
|
||||
type naiveRunner struct {
|
||||
mu sync.Mutex
|
||||
calls int
|
||||
}
|
||||
|
||||
func (n *naiveRunner) Run(_ context.Context, _ scheduling.Job) error {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
n.calls++
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *naiveRunner) count() int {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
return n.calls
|
||||
}
|
||||
|
||||
// fakeLookup serves specs from a map and ignores ctx entirely, like
|
||||
// naiveCourier.
|
||||
//
|
||||
// The cancellation tests need it because a production store is expected to be
|
||||
// cancellation-aware: a source whose Get returns ctx.Err() before it reads
|
||||
// masks the runner's own guard — hydrate fails and the run returns the context
|
||||
// error whether or not the runner checked. A lookup that ignores ctx removes
|
||||
// that mask, leaving the runner's guard as the only thing that can prevent the
|
||||
// side effect.
|
||||
type fakeLookup struct {
|
||||
specs map[string]scheduling.JobSpec
|
||||
}
|
||||
|
||||
func (f *fakeLookup) Get(_ context.Context, id string) (scheduling.JobSpec, bool, error) {
|
||||
spec, ok := f.specs[id]
|
||||
return spec, ok, nil
|
||||
}
|
||||
|
||||
// MarkRun satisfies RouterStore. It deliberately does nothing: these tests
|
||||
// exercise the runner's and the router's own dispatch guards, and the record
|
||||
// step is covered against a store that really advances in
|
||||
// TestRouterAdvancesTheScheduleAfterASuccessfulRun.
|
||||
func (f *fakeLookup) MarkRun(_ context.Context, _ string, _ time.Time) error { return nil }
|
||||
|
||||
// fakeCourier records what was sent and can be made to fail or to block until
|
||||
// cancelled.
|
||||
type fakeCourier struct {
|
||||
mu sync.Mutex
|
||||
chats []string
|
||||
texts []string
|
||||
calls int
|
||||
err error
|
||||
entered chan struct{} // closed when send is entered; nil means no signal
|
||||
blockOn chan struct{} // when non-nil, send waits on it (or ctx) before returning
|
||||
}
|
||||
|
||||
func (f *fakeCourier) send(ctx context.Context, chatID, text string) error {
|
||||
f.mu.Lock()
|
||||
f.calls++
|
||||
f.chats = append(f.chats, chatID)
|
||||
f.texts = append(f.texts, text)
|
||||
entered, block := f.entered, f.blockOn
|
||||
err := f.err
|
||||
f.mu.Unlock()
|
||||
if entered != nil {
|
||||
select {
|
||||
case <-entered:
|
||||
default:
|
||||
close(entered)
|
||||
}
|
||||
}
|
||||
if block != nil {
|
||||
select {
|
||||
case <-block:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (f *fakeCourier) snapshot() (chats, texts []string, calls int) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return append([]string(nil), f.chats...), append([]string(nil), f.texts...), f.calls
|
||||
}
|
||||
|
||||
// fakeSubmitter records submitted work.
|
||||
type fakeSubmitter struct {
|
||||
mu sync.Mutex
|
||||
identities []string
|
||||
titles []string
|
||||
bodies []string
|
||||
calls int
|
||||
err error
|
||||
entered chan struct{}
|
||||
block chan struct{}
|
||||
}
|
||||
|
||||
func (f *fakeSubmitter) Submit(ctx context.Context, identity, title, body string) error {
|
||||
f.mu.Lock()
|
||||
f.calls++
|
||||
f.identities = append(f.identities, identity)
|
||||
f.titles = append(f.titles, title)
|
||||
f.bodies = append(f.bodies, body)
|
||||
entered, block := f.entered, f.block
|
||||
err := f.err
|
||||
f.mu.Unlock()
|
||||
if entered != nil {
|
||||
select {
|
||||
case <-entered:
|
||||
default:
|
||||
close(entered)
|
||||
}
|
||||
}
|
||||
if block != nil {
|
||||
select {
|
||||
case <-block:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (f *fakeSubmitter) snapshot() (ids, titles, bodies []string, calls int) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return append([]string(nil), f.identities...),
|
||||
append([]string(nil), f.titles...),
|
||||
append([]string(nil), f.bodies...),
|
||||
f.calls
|
||||
}
|
||||
|
||||
// recordingSink captures emitted events.
|
||||
type recordingSink struct {
|
||||
mu sync.Mutex
|
||||
events []recordedEvent
|
||||
}
|
||||
|
||||
type recordedEvent struct {
|
||||
kind string
|
||||
detail string
|
||||
data map[string]any
|
||||
}
|
||||
|
||||
func (s *recordingSink) Emit(kind, detail string, data map[string]any) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.events = append(s.events, recordedEvent{kind: kind, detail: detail, data: data})
|
||||
}
|
||||
|
||||
func (s *recordingSink) all() []recordedEvent {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return append([]recordedEvent(nil), s.events...)
|
||||
}
|
||||
|
||||
// countingRunner is a stand-in runner used to prove the router did or did not
|
||||
// reach a kind's runner.
|
||||
type countingRunner struct {
|
||||
mu sync.Mutex
|
||||
calls int
|
||||
ids []string
|
||||
}
|
||||
|
||||
func (c *countingRunner) Run(_ context.Context, job scheduling.Job) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.calls++
|
||||
c.ids = append(c.ids, job.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *countingRunner) count() int {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.calls
|
||||
}
|
||||
|
||||
// --- helpers ------------------------------------------------------------------
|
||||
|
||||
// memStore is the test's schedules document: a map with the three faces the
|
||||
// production store shows the package — SpecLookup (Get), RunRecorder (MarkRun
|
||||
// with real schedule arithmetic), and JobSource (Due). It replaces the file-
|
||||
// backed store this package's fixtures used to open, which died with the
|
||||
// legacy jobs.json store; the document now lives behind the control plane in
|
||||
// production, and what these tests need from persistence is semantics, not a
|
||||
// file.
|
||||
type memStore struct {
|
||||
mu sync.Mutex
|
||||
jobs map[string]scheduling.JobSpec
|
||||
}
|
||||
|
||||
func newStore(t *testing.T) *memStore {
|
||||
t.Helper()
|
||||
return &memStore{jobs: make(map[string]scheduling.JobSpec)}
|
||||
}
|
||||
|
||||
// Create persists a spec verbatim. Fixtures that want a due job set NextRun
|
||||
// themselves (createJob does it when unset).
|
||||
func (m *memStore) Create(_ context.Context, spec scheduling.JobSpec) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if _, exists := m.jobs[spec.ID]; exists {
|
||||
return fmt.Errorf("memStore: id %q already exists", spec.ID)
|
||||
}
|
||||
m.jobs[spec.ID] = spec
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memStore) Get(_ context.Context, id string) (scheduling.JobSpec, bool, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
spec, ok := m.jobs[id]
|
||||
return spec, ok, nil
|
||||
}
|
||||
|
||||
// Due returns the jobs whose NextRun is at or before now, the same contract
|
||||
// the production source keeps.
|
||||
func (m *memStore) Due(_ context.Context, now time.Time) ([]scheduling.Job, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
due := make([]scheduling.Job, 0, len(m.jobs))
|
||||
for _, spec := range m.jobs {
|
||||
if !spec.NextRun.After(now) {
|
||||
due = append(due, scheduling.Job{ID: spec.ID, Pool: scheduling.Pool(spec.Pool), Detail: spec.Detail})
|
||||
}
|
||||
}
|
||||
return due, nil
|
||||
}
|
||||
|
||||
// MarkRun advances an interval job's NextRun the way the production
|
||||
// recording step does, and reports a once schedule as unsupported — the
|
||||
// sentinel the router swallows.
|
||||
func (m *memStore) MarkRun(_ context.Context, id string, runAt time.Time) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
spec, ok := m.jobs[id]
|
||||
if !ok {
|
||||
return fmt.Errorf("%w: id %q", scheduling.ErrJobNotFound, id)
|
||||
}
|
||||
next, err := spec.Schedule.NextRun(runAt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
at := runAt.UTC()
|
||||
spec.LastRun = &at
|
||||
spec.NextRun = next
|
||||
m.jobs[id] = spec
|
||||
return nil
|
||||
}
|
||||
|
||||
// createJob persists a spec and returns the scheduling job the engine would
|
||||
// hand a runner for it.
|
||||
func createJob(t *testing.T, s *memStore, spec scheduling.JobSpec) scheduling.Job {
|
||||
t.Helper()
|
||||
if spec.NextRun.IsZero() {
|
||||
// Due now: the engine only ever hands a runner a job its source
|
||||
// reported due, so the fixture must be in that state.
|
||||
spec.NextRun = time.Now().UTC().Add(-time.Minute)
|
||||
}
|
||||
if err := s.Create(t.Context(), spec); err != nil {
|
||||
t.Fatalf("Create(%q): %v", spec.ID, err)
|
||||
}
|
||||
return scheduling.Job{ID: spec.ID, Pool: scheduling.Pool(spec.Pool), Detail: spec.Detail}
|
||||
}
|
||||
|
||||
// chatSpec is a minimal chat job.
|
||||
func chatSpec(id, chatID, text string) scheduling.JobSpec {
|
||||
return scheduling.JobSpec{
|
||||
ID: id,
|
||||
Detail: "test job " + id,
|
||||
Kind: scheduling.KindChat,
|
||||
Schedule: scheduling.Schedule{Kind: scheduling.ScheduleInterval, Interval: scheduling.Duration(time.Hour)},
|
||||
Target: scheduling.Target{ChatID: chatID},
|
||||
Payload: scheduling.Payload{Text: text},
|
||||
}
|
||||
}
|
||||
|
||||
// workflowSpec is a minimal workflow job.
|
||||
func workflowSpec(id, detail, body string) scheduling.JobSpec {
|
||||
return scheduling.JobSpec{
|
||||
ID: id,
|
||||
Detail: detail,
|
||||
Kind: scheduling.KindWorkflow,
|
||||
Schedule: scheduling.Schedule{Kind: scheduling.ScheduleInterval, Interval: scheduling.Duration(time.Hour)},
|
||||
Payload: scheduling.Payload{Text: body},
|
||||
}
|
||||
}
|
||||
@@ -1,430 +0,0 @@
|
||||
package crondelivery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/scheduling"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
// --- Router -------------------------------------------------------------------
|
||||
|
||||
// routerFixture builds a router over a real store with counting stand-ins for
|
||||
// the per-kind runners, so a test can assert the router reached one and not
|
||||
// the other.
|
||||
func routerFixture(t *testing.T, kind string) (*Router, *countingRunner, *countingRunner, *recordingSink) {
|
||||
t.Helper()
|
||||
s := newStore(t)
|
||||
createJob(t, s, scheduling.JobSpec{
|
||||
ID: "routed",
|
||||
Detail: "routed job",
|
||||
Kind: kind,
|
||||
Schedule: scheduling.Schedule{Kind: scheduling.ScheduleInterval, Interval: scheduling.Duration(time.Hour)},
|
||||
})
|
||||
chat, workflow := &countingRunner{}, &countingRunner{}
|
||||
sink := &recordingSink{}
|
||||
r, err := NewRouter(s, map[string]scheduling.Runner{
|
||||
scheduling.KindChat: chat,
|
||||
scheduling.KindWorkflow: workflow,
|
||||
}, sink)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter: %v", err)
|
||||
}
|
||||
return r, chat, workflow, sink
|
||||
}
|
||||
|
||||
func TestRouterDispatchesByKind(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
kind string
|
||||
wantChat int
|
||||
wantWorkflow int
|
||||
}{
|
||||
{"chat kind reaches the chat runner", scheduling.KindChat, 1, 0},
|
||||
{"workflow kind reaches the workflow runner", scheduling.KindWorkflow, 0, 1},
|
||||
{"empty kind defaults to the chat runner", "", 1, 0},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
r, chat, workflow, _ := routerFixture(t, tc.kind)
|
||||
job := scheduling.Job{ID: "routed"}
|
||||
|
||||
if err := r.Run(t.Context(), job); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if got := chat.count(); got != tc.wantChat {
|
||||
t.Errorf("chat runner ran %d times, want %d", got, tc.wantChat)
|
||||
}
|
||||
if got := workflow.count(); got != tc.wantWorkflow {
|
||||
t.Errorf("workflow runner ran %d times, want %d", got, tc.wantWorkflow)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestRouterUnknownKindIsRefusedAtTheGate is the acceptance criterion: an
|
||||
// unrecognised kind is reported as KindJobError with phase "dispatch", reaches
|
||||
// no runner, and returns nil — a no-op refused at the gate, not a failed run
|
||||
// (which would suppress every later tick of the job).
|
||||
func TestRouterUnknownKindIsRefusedAtTheGate(t *testing.T) {
|
||||
r, chat, workflow, sink := routerFixture(t, "teleport")
|
||||
job := scheduling.Job{ID: "routed", Pool: scheduling.PoolParallel, Detail: "routed job"}
|
||||
|
||||
if err := r.Run(t.Context(), job); err != nil {
|
||||
t.Fatalf("Run on an unknown kind = %v, want nil (a refusal is not a failure)", err)
|
||||
}
|
||||
if got := chat.count(); got != 0 {
|
||||
t.Errorf("chat runner ran %d times for an unknown kind, want 0", got)
|
||||
}
|
||||
if got := workflow.count(); got != 0 {
|
||||
t.Errorf("workflow runner ran %d times for an unknown kind, want 0", got)
|
||||
}
|
||||
|
||||
emitted := sink.all()
|
||||
if len(emitted) != 1 {
|
||||
t.Fatalf("emitted %d events, want 1: %+v", len(emitted), emitted)
|
||||
}
|
||||
got := emitted[0]
|
||||
if got.kind != events.KindJobError {
|
||||
t.Errorf("event kind = %q, want %q", got.kind, events.KindJobError)
|
||||
}
|
||||
// The data map matches the engine's own error shape, so one consumer
|
||||
// can render both without a special case for the router.
|
||||
for _, key := range []string{"job", "pool", "phase", "err"} {
|
||||
if _, ok := got.data[key]; !ok {
|
||||
t.Errorf("event data is missing key %q: %+v", key, got.data)
|
||||
}
|
||||
}
|
||||
if got.data["phase"] != "dispatch" {
|
||||
t.Errorf("phase = %v, want %q", got.data["phase"], "dispatch")
|
||||
}
|
||||
if got.data["job"] != "routed" {
|
||||
t.Errorf("job = %v, want %q", got.data["job"], "routed")
|
||||
}
|
||||
if got.data["pool"] != "parallel" {
|
||||
t.Errorf("pool = %v, want %q", got.data["pool"], "parallel")
|
||||
}
|
||||
if got.data["err"] == "" || got.data["err"] == nil {
|
||||
t.Errorf("err = %v, want a message naming the unknown kind", got.data["err"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestRouterNilSinkDoesNotPanicOnUnknownKind mirrors the engine's own
|
||||
// tolerance: a nil sink disables emission without disabling the refusal.
|
||||
func TestRouterNilSinkDoesNotPanicOnUnknownKind(t *testing.T) {
|
||||
s := newStore(t)
|
||||
createJob(t, s, scheduling.JobSpec{
|
||||
ID: "routed",
|
||||
Kind: "teleport",
|
||||
Schedule: scheduling.Schedule{Kind: scheduling.ScheduleInterval, Interval: scheduling.Duration(time.Hour)},
|
||||
})
|
||||
chat, workflow := &countingRunner{}, &countingRunner{}
|
||||
r, err := NewRouter(s, map[string]scheduling.Runner{
|
||||
scheduling.KindChat: chat,
|
||||
scheduling.KindWorkflow: workflow,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter: %v", err)
|
||||
}
|
||||
|
||||
if err := r.Run(t.Context(), scheduling.Job{ID: "routed"}); err != nil {
|
||||
t.Fatalf("Run with a nil sink = %v, want nil", err)
|
||||
}
|
||||
if chat.count() != 0 || workflow.count() != 0 {
|
||||
t.Errorf("a runner was reached for an unknown kind: chat=%d workflow=%d",
|
||||
chat.count(), workflow.count())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouterMissingSpecReturnsError(t *testing.T) {
|
||||
s := newStore(t)
|
||||
r, err := NewRouter(s, map[string]scheduling.Runner{
|
||||
scheduling.KindChat: &countingRunner{},
|
||||
}, &recordingSink{})
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter: %v", err)
|
||||
}
|
||||
err = r.Run(t.Context(), scheduling.Job{ID: "never-created"})
|
||||
if err == nil {
|
||||
t.Fatal("Run with a missing spec returned nil, want an error")
|
||||
}
|
||||
if !errors.Is(err, errSpecMissing) {
|
||||
t.Errorf("Run = %v, want it to wrap %v", err, errSpecMissing)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRouterPassesTheEngineJobThrough pins that the router hands the runner
|
||||
// the job the engine built, not a re-derived one: identity and pool are the
|
||||
// engine's, and the runner's event attribution depends on them surviving.
|
||||
func TestRouterPassesTheEngineJobThrough(t *testing.T) {
|
||||
r, chat, _, _ := routerFixture(t, scheduling.KindChat)
|
||||
job := scheduling.Job{ID: "routed", Pool: scheduling.PoolSequential, Detail: "detail from engine"}
|
||||
|
||||
if err := r.Run(t.Context(), job); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
chat.mu.Lock()
|
||||
defer chat.mu.Unlock()
|
||||
if len(chat.ids) != 1 || chat.ids[0] != "routed" {
|
||||
t.Errorf("runner saw job ids %v, want [routed]", chat.ids)
|
||||
}
|
||||
}
|
||||
|
||||
// --- AC3: every runner honours cancellation ----------------------------------
|
||||
|
||||
// TestEveryRunnerHonoursCancellation covers the acceptance criterion as one
|
||||
// property over all three runners rather than three separate tests: the engine
|
||||
// hands every run a bounded context and cancels it on shutdown, so a runner
|
||||
// that ignores cancellation holds the engine past its own deadline.
|
||||
//
|
||||
// The downstream effects used here deliberately IGNORE ctx. A fake that
|
||||
// honours cancellation would make this pass whether or not the runner checks,
|
||||
// which is the failure mode the criterion exists to prevent.
|
||||
func TestEveryRunnerHonoursCancellation(t *testing.T) {
|
||||
lookup := &fakeLookup{specs: map[string]scheduling.JobSpec{
|
||||
"chat-job": chatSpec("chat-job", "ops-room", "hello"),
|
||||
"wf-job": workflowSpec("wf-job", "workflow job", "body"),
|
||||
}}
|
||||
|
||||
courier := &naiveCourier{}
|
||||
submitter := &naiveSubmitter{}
|
||||
chat, err := NewChatCourier(lookup, courier.send)
|
||||
if err != nil {
|
||||
t.Fatalf("NewChatCourier: %v", err)
|
||||
}
|
||||
workflow, err := NewWorkflowTask(lookup, submitter)
|
||||
if err != nil {
|
||||
t.Fatalf("NewWorkflowTask: %v", err)
|
||||
}
|
||||
// The router forwards to a ctx-ignoring runner, so this case pins the
|
||||
// router's own guard: a cancelled run must not reach the dispatch.
|
||||
forwarded := &naiveRunner{}
|
||||
router, err := NewRouter(lookup, map[string]scheduling.Runner{
|
||||
scheduling.KindChat: forwarded,
|
||||
scheduling.KindWorkflow: workflow,
|
||||
}, &recordingSink{})
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter: %v", err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
runner scheduling.Runner
|
||||
job scheduling.Job
|
||||
sideEffects func() int
|
||||
}{
|
||||
{"ChatCourier", chat, scheduling.Job{ID: "chat-job"}, func() int {
|
||||
_, _, calls := courier.snapshot()
|
||||
return calls
|
||||
}},
|
||||
{"WorkflowTask", workflow, scheduling.Job{ID: "wf-job"}, submitter.count},
|
||||
{"Router", router, scheduling.Job{ID: "chat-job"}, forwarded.count},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cancelled, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
if err := tc.runner.Run(cancelled, tc.job); !errors.Is(err, context.Canceled) {
|
||||
t.Errorf("Run on a cancelled ctx = %v, want context.Canceled", err)
|
||||
}
|
||||
if got := tc.sideEffects(); got != 0 {
|
||||
t.Errorf("a cancelled run produced %d side effect(s), want 0", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// --- AC4: the headline scenario, end to end -----------------------------------
|
||||
|
||||
// dailyStatusSummary is the hard-coded template AC4 calls for. The blueprints
|
||||
// slice replaces it with parameterisation; until then the composed message is
|
||||
// this constant, and the test asserts the delivered text against it.
|
||||
const dailyStatusSummary = "Daily status summary: all workers healthy, no tasks parked."
|
||||
|
||||
// TestDailyStatusSummaryEndToEnd is the epic's headline scenario exercised
|
||||
// through the whole chain a deployment uses: a scheduled job in the schedules
|
||||
// document is reported due by its own JobSource, handed to the router
|
||||
// the engine is given, dispatched to the chat runner, and delivered as the
|
||||
// composed message.
|
||||
func TestDailyStatusSummaryEndToEnd(t *testing.T) {
|
||||
s := newStore(t)
|
||||
const chatID = "ops-room"
|
||||
|
||||
spec := scheduling.JobSpec{
|
||||
ID: "daily-status",
|
||||
Detail: "daily status summary",
|
||||
Kind: scheduling.KindChat,
|
||||
Schedule: scheduling.Schedule{Kind: scheduling.ScheduleInterval, Interval: scheduling.Duration(24 * time.Hour)},
|
||||
Target: scheduling.Target{ChatID: chatID},
|
||||
Payload: scheduling.Payload{Text: dailyStatusSummary},
|
||||
// Due now: create it with a next_run in the past, the state a
|
||||
// long-idle daemon wakes up to.
|
||||
NextRun: time.Now().UTC().Add(-time.Minute),
|
||||
}
|
||||
if err := s.Create(t.Context(), spec); err != nil {
|
||||
t.Fatalf("Create: %v", err)
|
||||
}
|
||||
|
||||
// The engine's source: the store itself, answering what is due.
|
||||
due, err := s.Due(t.Context(), time.Now().UTC())
|
||||
if err != nil {
|
||||
t.Fatalf("Due: %v", err)
|
||||
}
|
||||
if len(due) != 1 {
|
||||
t.Fatalf("Due returned %d jobs, want 1: %+v", len(due), due)
|
||||
}
|
||||
|
||||
courier := &fakeCourier{}
|
||||
courierRunner, err := NewChatCourier(s, courier.send)
|
||||
if err != nil {
|
||||
t.Fatalf("NewChatCourier: %v", err)
|
||||
}
|
||||
router, err := NewRouter(s, map[string]scheduling.Runner{
|
||||
scheduling.KindChat: courierRunner,
|
||||
}, &recordingSink{})
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter: %v", err)
|
||||
}
|
||||
|
||||
// The engine hands the router the job its source reported.
|
||||
if err := router.Run(t.Context(), due[0]); err != nil {
|
||||
t.Fatalf("router.Run: %v", err)
|
||||
}
|
||||
|
||||
chats, texts, calls := courier.snapshot()
|
||||
if calls != 1 {
|
||||
t.Fatalf("courier called %d times, want 1", calls)
|
||||
}
|
||||
if chats[0] != chatID {
|
||||
t.Errorf("delivered to %q, want %q", chats[0], chatID)
|
||||
}
|
||||
if texts[0] != dailyStatusSummary {
|
||||
t.Errorf("delivered %q, want the composed summary %q", texts[0], dailyStatusSummary)
|
||||
}
|
||||
}
|
||||
|
||||
// --- constructors -------------------------------------------------------------
|
||||
|
||||
func TestConstructorsRejectNilDependencies(t *testing.T) {
|
||||
s := newStore(t)
|
||||
courier := &fakeCourier{}
|
||||
tests := []struct {
|
||||
name string
|
||||
run func() error
|
||||
}{
|
||||
{"ChatCourier without a spec lookup", func() error {
|
||||
_, err := NewChatCourier(nil, courier.send)
|
||||
return err
|
||||
}},
|
||||
{"ChatCourier without a courier", func() error {
|
||||
_, err := NewChatCourier(s, nil)
|
||||
return err
|
||||
}},
|
||||
{"WorkflowTask without a spec lookup", func() error {
|
||||
_, err := NewWorkflowTask(nil, &fakeSubmitter{})
|
||||
return err
|
||||
}},
|
||||
{"WorkflowTask without a submitter", func() error {
|
||||
_, err := NewWorkflowTask(s, nil)
|
||||
return err
|
||||
}},
|
||||
{"Router without a spec lookup", func() error {
|
||||
_, err := NewRouter(nil, map[string]scheduling.Runner{
|
||||
scheduling.KindChat: &countingRunner{},
|
||||
}, nil)
|
||||
return err
|
||||
}},
|
||||
{"Router without any runner", func() error {
|
||||
_, err := NewRouter(s, nil, nil)
|
||||
return err
|
||||
}},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if err := tc.run(); err == nil {
|
||||
t.Error("constructor returned nil error, want a refusal")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestImplementsSchedulingRunner is the compile-time contract check the engine
|
||||
// depends on.
|
||||
func TestImplementsSchedulingRunner(t *testing.T) {
|
||||
var (
|
||||
_ scheduling.Runner = (*ChatCourier)(nil)
|
||||
_ scheduling.Runner = (*WorkflowTask)(nil)
|
||||
_ scheduling.Runner = (*Router)(nil)
|
||||
)
|
||||
}
|
||||
|
||||
// TestRouterAdvancesTheScheduleAfterASuccessfulRun is the acceptance criterion
|
||||
// for a recurring job's timing: the recording step is the only thing that
|
||||
// moves a job's NextRun, and the Router is the single Runner the engine hands
|
||||
// every job. With no caller the store keeps reporting the job due on every
|
||||
// tick, so a job scheduled every hour fires once per tick instead.
|
||||
func TestRouterAdvancesTheScheduleAfterASuccessfulRun(t *testing.T) {
|
||||
s := newStore(t)
|
||||
job := createJob(t, s, chatSpec("advance", "chat-1", "hello"))
|
||||
|
||||
before, ok, err := s.Get(t.Context(), job.ID)
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("Get before = (%+v, %v, %v)", before, ok, err)
|
||||
}
|
||||
if !before.NextRun.Before(time.Now()) {
|
||||
t.Fatalf("fixture is not due: NextRun = %v", before.NextRun)
|
||||
}
|
||||
|
||||
r, err := NewRouter(s, map[string]scheduling.Runner{
|
||||
scheduling.KindChat: &countingRunner{},
|
||||
}, &recordingSink{})
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter: %v", err)
|
||||
}
|
||||
if err := r.Run(t.Context(), job); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
|
||||
after, ok, err := s.Get(t.Context(), job.ID)
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("Get after = (%+v, %v, %v)", after, ok, err)
|
||||
}
|
||||
if after.LastRun == nil {
|
||||
t.Error("LastRun is nil after a successful run: the run was never recorded")
|
||||
}
|
||||
if !after.NextRun.After(time.Now()) {
|
||||
t.Fatalf("NextRun = %v (was %v): a completed interval job is still due, so it re-fires on every tick",
|
||||
after.NextRun, before.NextRun)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRouterToleratesAOnceScheduleWithoutANextRun pins the other half: a
|
||||
// one-shot job has no recurring next run by definition, so MarkRun reports
|
||||
// scheduling.ErrScheduleUnsupported. That is not a run failure -- the job ran --
|
||||
// and returning it would make the engine emit KindJobError for a job that
|
||||
// succeeded.
|
||||
func TestRouterToleratesAOnceScheduleWithoutANextRun(t *testing.T) {
|
||||
s := newStore(t)
|
||||
at := time.Now().Add(-time.Hour)
|
||||
job := createJob(t, s, scheduling.JobSpec{
|
||||
ID: "one-shot",
|
||||
Detail: "one-shot job",
|
||||
Kind: scheduling.KindChat,
|
||||
Schedule: scheduling.Schedule{Kind: scheduling.ScheduleOnce, At: &at},
|
||||
Target: scheduling.Target{ChatID: "chat-1"},
|
||||
Payload: scheduling.Payload{Text: "once"},
|
||||
})
|
||||
|
||||
r, err := NewRouter(s, map[string]scheduling.Runner{
|
||||
scheduling.KindChat: &countingRunner{},
|
||||
}, &recordingSink{})
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter: %v", err)
|
||||
}
|
||||
if err := r.Run(t.Context(), job); err != nil {
|
||||
t.Fatalf("Run on a once schedule = %v, want nil (no recurring next run is not a failure)", err)
|
||||
}
|
||||
}
|
||||
@@ -1,279 +0,0 @@
|
||||
package crondelivery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/scheduling"
|
||||
)
|
||||
|
||||
// --- ChatCourier --------------------------------------------------------------
|
||||
|
||||
func TestChatCourierSendsPayloadToTargetChat(t *testing.T) {
|
||||
s := newStore(t)
|
||||
courier := &fakeCourier{}
|
||||
runner, err := NewChatCourier(s, courier.send)
|
||||
if err != nil {
|
||||
t.Fatalf("NewChatCourier: %v", err)
|
||||
}
|
||||
job := createJob(t, s, chatSpec("standup", "ops-room", "morning"))
|
||||
|
||||
if err := runner.Run(t.Context(), job); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
chats, texts, calls := courier.snapshot()
|
||||
if calls != 1 {
|
||||
t.Fatalf("courier called %d times, want 1", calls)
|
||||
}
|
||||
if chats[0] != "ops-room" {
|
||||
t.Errorf("chat id = %q, want %q", chats[0], "ops-room")
|
||||
}
|
||||
if texts[0] != "morning" {
|
||||
t.Errorf("text = %q, want %q", texts[0], "morning")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatCourierPropagatesCourierError(t *testing.T) {
|
||||
s := newStore(t)
|
||||
wantErr := errors.New("channel refused")
|
||||
courier := &fakeCourier{err: wantErr}
|
||||
runner, err := NewChatCourier(s, courier.send)
|
||||
if err != nil {
|
||||
t.Fatalf("NewChatCourier: %v", err)
|
||||
}
|
||||
job := createJob(t, s, chatSpec("boom", "ops-room", "morning"))
|
||||
|
||||
err = runner.Run(t.Context(), job)
|
||||
if !errors.Is(err, wantErr) {
|
||||
t.Errorf("Run = %v, want it to wrap %v", err, wantErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatCourierMissingSpecReturnsError(t *testing.T) {
|
||||
s := newStore(t)
|
||||
courier := &fakeCourier{}
|
||||
runner, err := NewChatCourier(s, courier.send)
|
||||
if err != nil {
|
||||
t.Fatalf("NewChatCourier: %v", err)
|
||||
}
|
||||
|
||||
// The engine reported this id due; the store does not have it. That is
|
||||
// a real inconsistency, so it must surface rather than be swallowed.
|
||||
err = runner.Run(t.Context(), scheduling.Job{ID: "never-created"})
|
||||
if err == nil {
|
||||
t.Fatal("Run with a missing spec returned nil, want an error")
|
||||
}
|
||||
if _, _, calls := courier.snapshot(); calls != 0 {
|
||||
t.Errorf("courier was called %d times for a missing spec, want 0", calls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatCourierHonoursCancellation is the bounded-shutdown property the
|
||||
// engine relies on: it cancels a run on Stop, and a runner that blocks through
|
||||
// cancellation keeps the run in flight past the engine's own deadline.
|
||||
//
|
||||
// Two cases, because they exercise different code paths: a run started with an
|
||||
// already-cancelled context must produce no side effect at all, and a run
|
||||
// cancelled while the courier is mid-send must return the context error so the
|
||||
// engine's shutdown completes rather than waiting for a full timeout.
|
||||
func TestChatCourierHonoursCancellation(t *testing.T) {
|
||||
t.Run("cancelled before the run sends nothing", func(t *testing.T) {
|
||||
// Both the lookup and the courier ignore ctx, so only the
|
||||
// runner's own guard can stop the send.
|
||||
lookup := &fakeLookup{specs: map[string]scheduling.JobSpec{
|
||||
"cancel-me": chatSpec("cancel-me", "ops-room", "morning"),
|
||||
}}
|
||||
courier := &naiveCourier{}
|
||||
runner, err := NewChatCourier(lookup, courier.send)
|
||||
if err != nil {
|
||||
t.Fatalf("NewChatCourier: %v", err)
|
||||
}
|
||||
|
||||
cancelled, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
err = runner.Run(cancelled, scheduling.Job{ID: "cancel-me"})
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Errorf("Run on a cancelled ctx = %v, want context.Canceled", err)
|
||||
}
|
||||
if _, _, calls := courier.snapshot(); calls != 0 {
|
||||
t.Errorf("courier was called %d times on a cancelled ctx, want 0", calls)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("cancelled mid-send returns the context error", func(t *testing.T) {
|
||||
s := newStore(t)
|
||||
entered := make(chan struct{})
|
||||
never := make(chan struct{})
|
||||
defer close(never) // never released; only cancellation can unblock
|
||||
courier := &fakeCourier{entered: entered, blockOn: never}
|
||||
runner, err := NewChatCourier(s, courier.send)
|
||||
if err != nil {
|
||||
t.Fatalf("NewChatCourier: %v", err)
|
||||
}
|
||||
job := createJob(t, s, chatSpec("cancel-mid", "ops-room", "morning"))
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- runner.Run(ctx, job) }()
|
||||
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(5 * time.Second):
|
||||
cancel()
|
||||
t.Fatal("courier was never entered; Run did not reach the send")
|
||||
}
|
||||
cancel()
|
||||
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Errorf("Run cancelled mid-send = %v, want context.Canceled", err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Run did not return after cancellation; it ignored ctx.Done()")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// --- WorkflowTask -------------------------------------------------------------
|
||||
|
||||
func TestWorkflowTaskSubmitsIdentityTitleAndBody(t *testing.T) {
|
||||
s := newStore(t)
|
||||
sub := &fakeSubmitter{}
|
||||
runner, err := NewWorkflowTask(s, sub)
|
||||
if err != nil {
|
||||
t.Fatalf("NewWorkflowTask: %v", err)
|
||||
}
|
||||
job := createJob(t, s, workflowSpec("nightly", "nightly maintenance", "run the sweep"))
|
||||
|
||||
if err := runner.Run(t.Context(), job); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
ids, titles, bodies, calls := sub.snapshot()
|
||||
if calls != 1 {
|
||||
t.Fatalf("submitter called %d times, want 1", calls)
|
||||
}
|
||||
if ids[0] != "nightly" {
|
||||
t.Errorf("identity = %q, want the job id %q", ids[0], "nightly")
|
||||
}
|
||||
if titles[0] != "nightly maintenance" {
|
||||
t.Errorf("title = %q, want %q", titles[0], "nightly maintenance")
|
||||
}
|
||||
if bodies[0] != "run the sweep" {
|
||||
t.Errorf("body = %q, want %q", bodies[0], "run the sweep")
|
||||
}
|
||||
}
|
||||
|
||||
// TestWorkflowTaskFallsBackToJobIDForTitle pins the documented fallback: a job
|
||||
// with no Detail still submits under a nameable title rather than an empty one.
|
||||
func TestWorkflowTaskFallsBackToJobIDForTitle(t *testing.T) {
|
||||
s := newStore(t)
|
||||
sub := &fakeSubmitter{}
|
||||
runner, err := NewWorkflowTask(s, sub)
|
||||
if err != nil {
|
||||
t.Fatalf("NewWorkflowTask: %v", err)
|
||||
}
|
||||
spec := workflowSpec("untitled", "", "body")
|
||||
job := createJob(t, s, spec)
|
||||
|
||||
if err := runner.Run(t.Context(), job); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
_, titles, _, _ := sub.snapshot()
|
||||
if titles[0] != "untitled" {
|
||||
t.Errorf("title = %q, want the job id %q when Detail is empty", titles[0], "untitled")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkflowTaskMissingSpecReturnsError(t *testing.T) {
|
||||
s := newStore(t)
|
||||
sub := &fakeSubmitter{}
|
||||
runner, err := NewWorkflowTask(s, sub)
|
||||
if err != nil {
|
||||
t.Fatalf("NewWorkflowTask: %v", err)
|
||||
}
|
||||
err = runner.Run(t.Context(), scheduling.Job{ID: "never-created"})
|
||||
if err == nil {
|
||||
t.Fatal("Run with a missing spec returned nil, want an error")
|
||||
}
|
||||
if _, _, _, calls := sub.snapshot(); calls != 0 {
|
||||
t.Errorf("submitter was called %d times for a missing spec, want 0", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkflowTaskPropagatesSubmitError(t *testing.T) {
|
||||
s := newStore(t)
|
||||
wantErr := errors.New("intake unavailable")
|
||||
sub := &fakeSubmitter{err: wantErr}
|
||||
runner, err := NewWorkflowTask(s, sub)
|
||||
if err != nil {
|
||||
t.Fatalf("NewWorkflowTask: %v", err)
|
||||
}
|
||||
job := createJob(t, s, workflowSpec("nightly", "nightly maintenance", "run"))
|
||||
|
||||
err = runner.Run(t.Context(), job)
|
||||
if !errors.Is(err, wantErr) {
|
||||
t.Errorf("Run = %v, want it to wrap %v", err, wantErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkflowTaskHonoursCancellation(t *testing.T) {
|
||||
t.Run("cancelled before the run submits nothing", func(t *testing.T) {
|
||||
// Both the lookup and the submitter ignore ctx, so only the
|
||||
// runner's own guard can stop the submit.
|
||||
lookup := &fakeLookup{specs: map[string]scheduling.JobSpec{
|
||||
"cancel-me": workflowSpec("cancel-me", "cancel me", "body"),
|
||||
}}
|
||||
sub := &naiveSubmitter{}
|
||||
runner, err := NewWorkflowTask(lookup, sub)
|
||||
if err != nil {
|
||||
t.Fatalf("NewWorkflowTask: %v", err)
|
||||
}
|
||||
|
||||
cancelled, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
err = runner.Run(cancelled, scheduling.Job{ID: "cancel-me"})
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Errorf("Run on a cancelled ctx = %v, want context.Canceled", err)
|
||||
}
|
||||
if calls := sub.count(); calls != 0 {
|
||||
t.Errorf("submitter was called %d times on a cancelled ctx, want 0", calls)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("cancelled mid-submit returns the context error", func(t *testing.T) {
|
||||
s := newStore(t)
|
||||
entered := make(chan struct{})
|
||||
never := make(chan struct{})
|
||||
defer close(never)
|
||||
sub := &fakeSubmitter{entered: entered, block: never}
|
||||
runner, err := NewWorkflowTask(s, sub)
|
||||
if err != nil {
|
||||
t.Fatalf("NewWorkflowTask: %v", err)
|
||||
}
|
||||
job := createJob(t, s, workflowSpec("cancel-mid", "cancel me", "body"))
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- runner.Run(ctx, job) }()
|
||||
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(5 * time.Second):
|
||||
cancel()
|
||||
t.Fatal("submitter was never entered; Run did not reach the submit")
|
||||
}
|
||||
cancel()
|
||||
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Errorf("Run cancelled mid-submit = %v, want context.Canceled", err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Run did not return after cancellation; it ignored ctx.Done()")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
package cronevents
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/scheduling"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
// chanClock is a deterministic scheduling.Clock: one tick per value sent on
|
||||
// ch, so the test drives the engine instead of waiting on wall-clock time.
|
||||
// After returns the same channel every time, and the engine re-arms only when
|
||||
// it is called again -- so nothing fires unless the test says so.
|
||||
type chanClock struct{ ch chan time.Time }
|
||||
|
||||
func (c chanClock) Now() time.Time { return time.Time{} }
|
||||
|
||||
func (c chanClock) After(time.Duration) <-chan time.Time { return c.ch }
|
||||
|
||||
// staticSource reports the same due jobs on every tick.
|
||||
type staticSource []scheduling.Job
|
||||
|
||||
func (s staticSource) Due(context.Context, time.Time) ([]scheduling.Job, error) { return s, nil }
|
||||
|
||||
type okRunner struct{}
|
||||
|
||||
func (okRunner) Run(context.Context, scheduling.Job) error { return nil }
|
||||
|
||||
// TestEngineSinkPublishesRealRunOnTheBus is the end-to-end proof of the
|
||||
// adapter: the engine's own emission, over the bus, as an event the
|
||||
// dashboard's timeline can read. It runs a real engine on a driven clock --
|
||||
// no sleeps, no wall-clock deadlines -- so the only thing under test is the
|
||||
// wiring between Emit and Publish.
|
||||
func TestEngineSinkPublishesRealRunOnTheBus(t *testing.T) {
|
||||
bus := events.NewBus()
|
||||
t.Cleanup(bus.Close)
|
||||
sub := bus.Subscribe(4)
|
||||
|
||||
sink := New(bus)
|
||||
clock := chanClock{ch: make(chan time.Time, 1)}
|
||||
engine, err := scheduling.NewEngine(
|
||||
staticSource{{ID: "daily", Pool: scheduling.PoolParallel, Detail: "daily status summary"}},
|
||||
okRunner{},
|
||||
scheduling.EngineConfig{Interval: time.Minute, Clock: clock, Events: sink},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("NewEngine: %v", err)
|
||||
}
|
||||
if err := engine.Start(t.Context()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
// WithoutCancel: t.Context() is cancelled before this cleanup runs,
|
||||
// and a cancelled ctx would only make Stop give up at once.
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(t.Context()), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := engine.Stop(ctx); err != nil {
|
||||
t.Errorf("Stop: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
clock.ch <- time.Time{} // one tick
|
||||
|
||||
select {
|
||||
case got := <-sub.C:
|
||||
if got.Kind != scheduling.KindJobRun {
|
||||
t.Errorf("Kind = %q, want %q", got.Kind, scheduling.KindJobRun)
|
||||
}
|
||||
if got.Detail != "daily status summary" {
|
||||
t.Errorf("Detail = %q, want the engine's job detail", got.Detail)
|
||||
}
|
||||
if got.Data["job"] != "daily" {
|
||||
t.Errorf("Data[job] = %v, want %q", got.Data["job"], "daily")
|
||||
}
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("no job_run event reached the bus: the engine's run is unobservable")
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package cronevents
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/scheduling"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
// TestSinkPublishesEmitAsJobEvent: the engine's emitted event is the only
|
||||
// trace a scheduled run leaves (a job has no task, no chat turn and no
|
||||
// workflow behind it), so the adapter has to carry Kind, Detail and Data
|
||||
// across unchanged and must not borrow a task-scoped identity it does not
|
||||
// have.
|
||||
func TestSinkPublishesEmitAsJobEvent(t *testing.T) {
|
||||
bus := events.NewBus()
|
||||
t.Cleanup(bus.Close)
|
||||
sub := bus.Subscribe(4)
|
||||
|
||||
sink := New(bus)
|
||||
if sink == nil {
|
||||
t.Fatal("New(bus) = nil, want a sink over the bus")
|
||||
}
|
||||
|
||||
// The shape the engine builds for a completed run
|
||||
// (internal/domain/scheduling/ticker.go runJob).
|
||||
sink.Emit(scheduling.KindJobRun, "nightly status", map[string]any{
|
||||
"job": "nightly-status",
|
||||
"pool": string(scheduling.PoolSequential),
|
||||
"duration_ms": int64(12),
|
||||
})
|
||||
|
||||
select {
|
||||
case got := <-sub.C:
|
||||
if got.Kind != scheduling.KindJobRun {
|
||||
t.Errorf("Kind = %q, want %q", got.Kind, scheduling.KindJobRun)
|
||||
}
|
||||
if got.Detail != "nightly status" {
|
||||
t.Errorf("Detail = %q, want unchanged \"nightly status\"", got.Detail)
|
||||
}
|
||||
if got.Data["job"] != "nightly-status" {
|
||||
t.Errorf("Data[job] = %v, want unchanged \"nightly-status\"", got.Data["job"])
|
||||
}
|
||||
if got.Data["duration_ms"] != int64(12) {
|
||||
t.Errorf("Data[duration_ms] = %v, want unchanged 12", got.Data["duration_ms"])
|
||||
}
|
||||
// The bus stamps publish time when the event carries none.
|
||||
if got.At.IsZero() {
|
||||
t.Error("At is zero: a timeline cannot place an event with no timestamp")
|
||||
}
|
||||
if got.TaskID != 0 || got.Repo != "" || got.Issue != 0 || got.Workflow != "" || got.Stage != "" {
|
||||
t.Errorf("event carries task-scoped identity it has none of: %+v", got)
|
||||
}
|
||||
default:
|
||||
t.Fatal("Emit published no event: the dashboard timeline would see nothing")
|
||||
}
|
||||
}
|
||||
|
||||
// A missing bus cannot produce an adapter; composition decides whether that
|
||||
// is acceptable for the selected event mode.
|
||||
func TestSinkIsNilWithoutABus(t *testing.T) {
|
||||
sink := New(nil)
|
||||
if sink != nil {
|
||||
t.Errorf("New(nil) = %#v, want a nil sink", sink)
|
||||
}
|
||||
}
|
||||
@@ -1,209 +0,0 @@
|
||||
package drain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/drain"
|
||||
)
|
||||
|
||||
func TestParseProcStatField22(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
stat string
|
||||
want int64
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "systemd pid 1 with real start time",
|
||||
stat: "1 (systemd) S 0 1 1 0 -1 4194560 214130 42927786 23 588 817 557 98753 15714 20 0 1 0 5 0 0 0 0 ...",
|
||||
want: 5,
|
||||
},
|
||||
{
|
||||
name: "comm containing spaces is handled",
|
||||
stat: "1 (init daemon) S 0 1 1 0 -1 4194560 0 0 0 0 0 0 0 0 20 0 1 0 42 0 0 0 0 ...",
|
||||
want: 42,
|
||||
},
|
||||
{
|
||||
name: "many trailing fields (real proc stat has 50+) are tolerated",
|
||||
stat: "1 (systemd) S 0 1 1 0 -1 4194560 214130 42927786 23 588 817 557 98753 15714 20 0 1 0 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0",
|
||||
want: 9,
|
||||
},
|
||||
{
|
||||
name: "too few post-paren fields fails",
|
||||
stat: "1 (systemd) S 0 1 1",
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "missing closing paren fails",
|
||||
stat: "1 systemd S 0 1 1",
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "non-numeric start time fails",
|
||||
stat: "1 (systemd) S 0 1 1 0 -1 4194560 214130 42927786 23 588 817 557 98753 15714 20 0 1 0 notanumber 0 0 0 0",
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "zero start time fails",
|
||||
stat: "1 (systemd) S 0 1 1 0 -1 4194560 214130 42927786 23 588 817 557 98753 15714 20 0 1 0 0 0 0 0 0",
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got, err := parseProcStat(test.stat)
|
||||
if (err != nil) != test.wantErr {
|
||||
t.Fatalf("parseProcStat() error = %v, wantErr %v", err, test.wantErr)
|
||||
}
|
||||
if got != test.want {
|
||||
t.Fatalf("parseProcStat() = %d, want %d", got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// writeMarker writes a drain marker JSON file with the given epoch.
|
||||
func writeMarker(t *testing.T, dir string, epoch drain.Epoch) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(dir, DefaultMarkerFilename)
|
||||
payload, err := json.Marshal(drain.Marker{InstantiationEpoch: epoch, Reason: "test"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, payload, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func TestReaderCheckTable(t *testing.T) {
|
||||
current := drain.Epoch{BootID: "boot-now", PID1Start: 100}
|
||||
prior := drain.Epoch{BootID: "boot-old", PID1Start: 100}
|
||||
|
||||
match := func() (drain.Epoch, error) { return current, nil }
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
write func(dir string) string
|
||||
epoch func() (drain.Epoch, error)
|
||||
want drain.Decision
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "absent marker reports none",
|
||||
write: func(dir string) string {
|
||||
return filepath.Join(dir, DefaultMarkerFilename)
|
||||
},
|
||||
epoch: match,
|
||||
want: drain.DecisionNone,
|
||||
},
|
||||
{
|
||||
name: "marker with current epoch is valid",
|
||||
write: func(dir string) string { return writeMarker(t, dir, current) },
|
||||
epoch: match,
|
||||
want: drain.DecisionValid,
|
||||
},
|
||||
{
|
||||
name: "marker written against a prior epoch is stale",
|
||||
write: func(dir string) string { return writeMarker(t, dir, prior) },
|
||||
epoch: match,
|
||||
want: drain.DecisionStale,
|
||||
},
|
||||
{
|
||||
name: "current epoch unreadable fails closed to stale",
|
||||
write: func(dir string) string { return writeMarker(t, dir, current) },
|
||||
epoch: func() (drain.Epoch, error) {
|
||||
return drain.Epoch{}, errors.New("proc unavailable")
|
||||
},
|
||||
want: drain.DecisionStale,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "malformed marker fails closed to stale",
|
||||
write: func(dir string) string {
|
||||
path := filepath.Join(dir, DefaultMarkerFilename)
|
||||
if err := os.WriteFile(path, []byte("{ not json"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
},
|
||||
epoch: match,
|
||||
want: drain.DecisionStale,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "marker file is a directory fails closed to stale",
|
||||
write: func(dir string) string {
|
||||
path := filepath.Join(dir, DefaultMarkerFilename)
|
||||
if err := os.Mkdir(path, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
},
|
||||
epoch: match,
|
||||
want: drain.DecisionStale,
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := test.write(dir)
|
||||
reader := New(path, test.epoch)
|
||||
got, err := reader.Check()
|
||||
if (err != nil) != test.wantErr {
|
||||
t.Fatalf("Check() error = %v, wantErr %v", err, test.wantErr)
|
||||
}
|
||||
if got != test.want {
|
||||
t.Fatalf("Check() = %v, want %v", got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReaderParsesOperatorWrittenJSON(t *testing.T) {
|
||||
// The marker is written by an external operator script, so the on-disk
|
||||
// shape (underscore keys) is part of the contract. Unmarshal it as-is and
|
||||
// confirm the epoch round-trips to a valid decision -- this is what guards
|
||||
// the JSON tag wiring rather than go fixture marshaling.
|
||||
current := drain.Epoch{BootID: "boot-now", PID1Start: 100}
|
||||
const raw = `{"instantiation_epoch":{"boot_id":"boot-now","pid1_start":100},"reason":"maintenance window","requested_at":"2026-09-05T00:00:00Z"}`
|
||||
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, DefaultMarkerFilename)
|
||||
if err := os.WriteFile(path, []byte(raw), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got, err := New(path, func() (drain.Epoch, error) { return current, nil }).Check()
|
||||
if err != nil {
|
||||
t.Fatalf("Check() error = %v", err)
|
||||
}
|
||||
if got != drain.DecisionValid {
|
||||
t.Fatalf("Check() = %v, want valid", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDefaultsToCurrentEpoch(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
// No epoch function passed: New must fall back to the package's real
|
||||
// CurrentEpoch. The marker records the real current epoch read from /proc,
|
||||
// so Check must report it valid -- proving the default wiring works end to
|
||||
// end without a host restart.
|
||||
current, err := CurrentEpoch()
|
||||
if err != nil {
|
||||
t.Skipf("cannot read current epoch on this host: %v", err)
|
||||
}
|
||||
path := writeMarker(t, dir, current)
|
||||
got, err := New(path, nil).Check()
|
||||
if err != nil {
|
||||
t.Fatalf("Check() error = %v", err)
|
||||
}
|
||||
if got != drain.DecisionValid {
|
||||
t.Fatalf("Check() = %v, want valid", got)
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func verifyLeaf(t *testing.T, ca *CA, leaf *tls.Certificate, name string) error {
|
||||
t.Helper()
|
||||
pool := x509.NewCertPool()
|
||||
if !pool.AppendCertsFromPEM(ca.CertPEM()) {
|
||||
t.Fatal("CertPEM is not a PEM certificate")
|
||||
}
|
||||
cert, err := x509.ParseCertificate(leaf.Certificate[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = cert.Verify(x509.VerifyOptions{DNSName: name, Roots: pool})
|
||||
return err
|
||||
}
|
||||
|
||||
func TestCAPersistsAcrossLoads(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
first, err := LoadOrCreateCA(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := LoadOrCreateCA(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(first.CertPEM()) != string(second.CertPEM()) {
|
||||
t.Fatal("reloading the CA produced a different certificate; every container would stop trusting the proxy")
|
||||
}
|
||||
info, err := os.Stat(filepath.Join(dir, caKeyFile))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if perm := info.Mode().Perm(); perm != 0o600 {
|
||||
t.Fatalf("CA key is mode %o, want 600", perm)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCAIssuesVerifiableLeaves(t *testing.T) {
|
||||
ca, err := LoadOrCreateCA(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, host := range []string{"api.example.com", "10.0.0.5"} {
|
||||
leaf, err := ca.leaf(host)
|
||||
if err != nil {
|
||||
t.Fatalf("leaf(%q): %v", host, err)
|
||||
}
|
||||
if err := verifyLeaf(t, ca, leaf, host); err != nil {
|
||||
t.Fatalf("leaf for %q does not verify: %v", host, err)
|
||||
}
|
||||
if err := verifyLeaf(t, ca, leaf, "other.example.com"); err == nil {
|
||||
t.Fatalf("leaf for %q also verifies for another host", host)
|
||||
}
|
||||
again, err := ca.leaf(host)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if again != leaf {
|
||||
t.Fatalf("leaf for %q is re-signed on every connection", host)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCARejectsATamperedKey(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if _, err := LoadOrCreateCA(dir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, caKeyFile), []byte("not a key"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := LoadOrCreateCA(dir); err == nil {
|
||||
t.Fatal("a corrupt CA key loaded; the proxy must fail closed rather than mint a new CA silently")
|
||||
}
|
||||
}
|
||||
@@ -1,222 +0,0 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"net/http"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/docker/sandbox-kit-spec/v3/spec"
|
||||
)
|
||||
|
||||
func apiKey(service, phase string, required bool, name string, inject ...spec.Inject) spec.CredentialCapability {
|
||||
return spec.CredentialCapability{
|
||||
Service: service, Phase: phase, APIKey: &spec.APIKey{Name: name, ProxyManaged: true, Inject: inject},
|
||||
Required: required,
|
||||
}
|
||||
}
|
||||
|
||||
// registerWith registers run-7 with every declared service carried as an API
|
||||
// key, mirroring what the launcher passes for a run whose bindings all name
|
||||
// secrets. registerBoundWith is for the tests that need a different kind.
|
||||
func (h *harness) registerWith(t *testing.T, creds ...spec.CredentialCapability) *Session {
|
||||
t.Helper()
|
||||
kinds := map[string]CredentialKind{}
|
||||
for _, c := range creds {
|
||||
kinds[c.Service] = CredentialAPIKey
|
||||
}
|
||||
return h.registerBoundWith(t, kinds, creds...)
|
||||
}
|
||||
|
||||
func (h *harness) registerBoundWith(t *testing.T, bound map[string]CredentialKind, creds ...spec.CredentialCapability) *Session {
|
||||
t.Helper()
|
||||
s, err := h.proxy.Register(SessionOptions{
|
||||
Run: "run-7",
|
||||
Network: &spec.PhasedNetwork{
|
||||
Install: &spec.NetworkRules{Allow: []string{"install.example.com"}},
|
||||
Runtime: &spec.NetworkRules{Allow: []string{"api.example.com:443", "plain.example.com:80"}},
|
||||
},
|
||||
Credentials: creds,
|
||||
Bound: bound,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func TestInjectsAnAPIKeyHeader(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.bind("run-7/example", "real-secret")
|
||||
s := h.registerWith(t, apiKey("example", "runtime", true, "EXAMPLE_KEY",
|
||||
spec.Inject{Domain: "api.example.com", Header: "Authorization", Format: "Bearer %s"}))
|
||||
s.EnterRuntime()
|
||||
req, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, "https://api.example.com/", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+Sentinel)
|
||||
resp, err := h.client(s.Token()).Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
if got := h.lastAuth.Load(); got != "Bearer real-secret" {
|
||||
t.Fatalf("upstream Authorization %v, want the real key in place of the sentinel", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectsBasicAuth(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.bind("run-7/example", "real-secret")
|
||||
s := h.registerWith(t, apiKey("example", "runtime", true, "",
|
||||
spec.Inject{Domain: "api.example.com", Scheme: "basic", Username: "x-access-token"}))
|
||||
s.EnterRuntime()
|
||||
if _, _, err := get(t, h.client(s.Token()), "https://api.example.com/"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "Basic " + base64.StdEncoding.EncodeToString([]byte("x-access-token:real-secret"))
|
||||
if got := h.lastAuth.Load(); got != want {
|
||||
t.Fatalf("upstream Authorization %v, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectionIsScopedToItsDomainAndPhase(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.bind("run-7/example", "real-secret")
|
||||
h.bind("run-7/installer", "install-secret")
|
||||
s := h.registerWith(t,
|
||||
apiKey("example", "runtime", true, "EXAMPLE_KEY", spec.Inject{Domain: "api.example.com", Header: "Authorization", Format: "Bearer %s"}),
|
||||
apiKey("installer", "install", true, "", spec.Inject{Domain: "plain.example.com", Header: "X-Install", Format: "%s"}),
|
||||
)
|
||||
s.EnterRuntime()
|
||||
if _, _, err := get(t, h.client(s.Token()), "http://plain.example.com/"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := h.lastAuth.Load(); got != "" {
|
||||
t.Fatalf("a key for api.example.com was sent to plain.example.com: %v", got)
|
||||
}
|
||||
if h.lastInstall.Load() != "" {
|
||||
t.Fatal("an install-phase credential was injected at runtime")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnUnboundCredential(t *testing.T) {
|
||||
t.Run("required stops the request before it reaches upstream", func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
s := h.registerWith(t, apiKey("example", "runtime", true, "EXAMPLE_KEY",
|
||||
spec.Inject{Domain: "api.example.com", Header: "Authorization", Format: "Bearer %s"}))
|
||||
s.EnterRuntime()
|
||||
status, _, err := get(t, h.client(s.Token()), "https://api.example.com/")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status != http.StatusBadGateway || h.hits.Load() != 0 {
|
||||
t.Fatalf("status %d with %d upstream hits; want 502 and none", status, h.hits.Load())
|
||||
}
|
||||
})
|
||||
t.Run("optional passes without one", func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
s := h.registerWith(t, apiKey("example", "runtime", false, "EXAMPLE_KEY",
|
||||
spec.Inject{Domain: "api.example.com", Header: "Authorization", Format: "Bearer %s"}))
|
||||
s.EnterRuntime()
|
||||
status, _, err := get(t, h.client(s.Token()), "https://api.example.com/")
|
||||
if err != nil || status != http.StatusOK {
|
||||
t.Fatalf("got %d %v", status, err)
|
||||
}
|
||||
if got := h.lastAuth.Load(); got != "" {
|
||||
t.Fatalf("upstream saw Authorization %v with no binding", got)
|
||||
}
|
||||
})
|
||||
t.Run("a resolver failure is never treated as unbound", func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.failResolves(errors.New("state store unreachable"))
|
||||
s := h.registerWith(t, apiKey("example", "runtime", false, "EXAMPLE_KEY",
|
||||
spec.Inject{Domain: "api.example.com", Header: "Authorization", Format: "Bearer %s"}))
|
||||
s.EnterRuntime()
|
||||
status, _, err := get(t, h.client(s.Token()), "https://api.example.com/")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status != http.StatusBadGateway || h.hits.Load() != 0 {
|
||||
t.Fatalf("status %d with %d upstream hits; want 502 and none", status, h.hits.Load())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestTheResolverSeesTheRunAndService(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.bind("run-7/example", "real-secret")
|
||||
s := h.registerWith(t, apiKey("example", "runtime", true, "EXAMPLE_KEY",
|
||||
spec.Inject{Domain: "api.example.com", Header: "Authorization", Format: "Bearer %s"}))
|
||||
s.EnterRuntime()
|
||||
if _, _, err := get(t, h.client(s.Token()), "https://api.example.com/"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if !slices.Contains(h.resolved, "run-7/example") {
|
||||
t.Fatalf("resolver calls %v, want run-7/example", h.resolved)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAnOAuthBoundServiceInjectsNoAPIKey is the "whichever the host has
|
||||
// bound" side of the credential kind: docker/claude-code-kit declares apiKey
|
||||
// and oauth on one service, and an org that bound the OAuth token set must
|
||||
// not have the API-key rule fire with the empty value the resolver answers
|
||||
// for an OAuth-bound service -- every request to a domain the Kit named
|
||||
// would then carry an empty credential.
|
||||
func TestAnOAuthBoundServiceInjectsNoAPIKey(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
// The run carries the service as the org's OAuth token set: the resolver
|
||||
// answers it (with no API-key value, as kitrun grants an OAuth-bound
|
||||
// service).
|
||||
h.bind("run-7/example", "")
|
||||
s := h.registerBoundWith(t, map[string]CredentialKind{"example": CredentialOAuth},
|
||||
apiKey("example", "runtime", true, "EXAMPLE_KEY",
|
||||
spec.Inject{Domain: "api.example.com", Header: "Authorization", Format: "Bearer %s"}))
|
||||
s.EnterRuntime()
|
||||
if _, _, err := get(t, h.client(s.Token()), "https://api.example.com/"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := h.lastAuth.Load(); got != "" {
|
||||
t.Fatalf("upstream Authorization %v, want no header: an OAuth-bound service carries no API key", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSentinelEnv(t *testing.T) {
|
||||
env := SentinelEnv([]spec.CredentialCapability{
|
||||
apiKey("named", "runtime", true, "NAMED_KEY", spec.Inject{Domain: "a.example.com", Header: "X", Format: "%s"}),
|
||||
apiKey("injectonly", "runtime", true, "", spec.Inject{Domain: "b.example.com", Header: "X", Format: "%s"}),
|
||||
})
|
||||
if !slices.Equal(env, []string{"NAMED_KEY=" + Sentinel}) {
|
||||
t.Fatalf("SentinelEnv = %v; a named key gets the sentinel, an inject-only key gets nothing", env)
|
||||
}
|
||||
}
|
||||
|
||||
// fakeResolver lets the harness stand in for the run credential's secrets.
|
||||
func (h *harness) resolve(_ context.Context, run, service string) (string, error) {
|
||||
key := run + "/" + service
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.resolved = append(h.resolved, key)
|
||||
if h.resolveErr != nil {
|
||||
return "", h.resolveErr
|
||||
}
|
||||
v, ok := h.secrets[key]
|
||||
if !ok {
|
||||
return "", ErrUnbound
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func (h *harness) bind(key, value string) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.secrets[key] = value
|
||||
}
|
||||
|
||||
func (h *harness) failResolves(err error) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.resolveErr = err
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
package egress
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestGrantResolverOnlyResolvesWhatWasGranted is the mutation-checked
|
||||
// isolation proof: a service never granted for a run, a service granted only
|
||||
// to a different run, and a service already revoked must all answer
|
||||
// ErrUnbound -- there is no path from "asked" to "returned" that does not go
|
||||
// through an explicit Grant.
|
||||
func TestGrantResolverOnlyResolvesWhatWasGranted(t *testing.T) {
|
||||
g := NewGrantResolver()
|
||||
g.Grant("run-a", map[string]string{"openai": "sk-a"})
|
||||
g.Grant("run-b", map[string]string{"anthropic": "sk-b"})
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
run string
|
||||
service string
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "a granted service resolves", run: "run-a", service: "openai", want: "sk-a"},
|
||||
{name: "a service granted to a different run never resolves here", run: "run-a", service: "anthropic", wantErr: true},
|
||||
{name: "a service never granted to any run", run: "run-a", service: "unknown", wantErr: true},
|
||||
{name: "an unknown run resolves nothing", run: "run-c", service: "openai", wantErr: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := g.Resolve(t.Context(), tt.run, tt.service)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("Resolve(%q, %q) = (%q, nil), want ErrUnbound", tt.run, tt.service, got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || got != tt.want {
|
||||
t.Fatalf("Resolve(%q, %q) = (%q, %v), want (%q, nil)", tt.run, tt.service, got, err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGrantResolverRevokeRemovesEveryGrantForTheRun(t *testing.T) {
|
||||
g := NewGrantResolver()
|
||||
g.Grant("run-a", map[string]string{"openai": "sk-a", "anthropic": "sk-b"})
|
||||
g.RevokeGrant("run-a")
|
||||
|
||||
if _, err := g.Resolve(t.Context(), "run-a", "openai"); err == nil {
|
||||
t.Fatal("Resolve after RevokeGrant returned a value, want ErrUnbound")
|
||||
}
|
||||
if _, err := g.Resolve(t.Context(), "run-a", "anthropic"); err == nil {
|
||||
t.Fatal("Resolve after RevokeGrant returned a value, want ErrUnbound")
|
||||
}
|
||||
}
|
||||
|
||||
// TestGrantResolverGrantReplacesNotMerges: a run re-granted with a narrower
|
||||
// set (a Kit that stopped declaring a service it once did, or a retry
|
||||
// dispatched after a grant changed) must lose the dropped service, not keep
|
||||
// it from the previous Grant call.
|
||||
func TestGrantResolverGrantReplacesNotMerges(t *testing.T) {
|
||||
g := NewGrantResolver()
|
||||
g.Grant("run-a", map[string]string{"openai": "sk-a", "anthropic": "sk-b"})
|
||||
g.Grant("run-a", map[string]string{"openai": "sk-a2"})
|
||||
|
||||
got, err := g.Resolve(t.Context(), "run-a", "openai")
|
||||
if err != nil || got != "sk-a2" {
|
||||
t.Fatalf("Resolve(openai) = (%q, %v), want (sk-a2, nil)", got, err)
|
||||
}
|
||||
if _, err := g.Resolve(t.Context(), "run-a", "anthropic"); err == nil {
|
||||
t.Fatal("anthropic still resolves after a narrower Grant replaced it, want ErrUnbound")
|
||||
}
|
||||
}
|
||||
@@ -1,238 +0,0 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/x509"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/docker/sandbox-kit-spec/v3/spec"
|
||||
"github.com/moby/moby/api/types/container"
|
||||
"github.com/moby/moby/client"
|
||||
)
|
||||
|
||||
const probeImage = "alpine:3"
|
||||
|
||||
func buildStatic(t *testing.T, dir, pkg, name string) {
|
||||
t.Helper()
|
||||
cmd := exec.CommandContext(t.Context(), "go", "build", "-o", filepath.Join(dir, name), pkg)
|
||||
cmd.Env = append(os.Environ(), "CGO_ENABLED=0")
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("build %s: %v\n%s", pkg, err, out)
|
||||
}
|
||||
}
|
||||
|
||||
func ensureImage(t *testing.T, cli *client.Client, ref string) {
|
||||
t.Helper()
|
||||
if _, err := cli.ImageInspect(t.Context(), ref); err == nil {
|
||||
return
|
||||
}
|
||||
rc, err := cli.ImagePull(t.Context(), ref, client.ImagePullOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("pull %s: %v", ref, err)
|
||||
}
|
||||
defer rc.Close()
|
||||
_, _ = io.Copy(io.Discard, rc)
|
||||
}
|
||||
|
||||
func bridgeGateway(t *testing.T, cli *client.Client) string {
|
||||
t.Helper()
|
||||
res, err := cli.NetworkInspect(t.Context(), "bridge", client.NetworkInspectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, c := range res.Network.IPAM.Config {
|
||||
if c.Gateway.IsValid() && c.Gateway.Is4() {
|
||||
return c.Gateway.String()
|
||||
}
|
||||
}
|
||||
t.Fatal("default bridge has no IPv4 gateway")
|
||||
return ""
|
||||
}
|
||||
|
||||
// runProbe runs egressclient in a container on the sandbox network and
|
||||
// returns one result line per probe.
|
||||
func runProbe(t *testing.T, cli *client.Client, networkName, bin, caPath, token string, probes ...string) []string {
|
||||
t.Helper()
|
||||
outDir := t.TempDir()
|
||||
if err := os.Chmod(outDir, 0o777); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
created, err := cli.ContainerCreate(t.Context(), client.ContainerCreateOptions{
|
||||
Config: &container.Config{
|
||||
Image: probeImage,
|
||||
Entrypoint: []string{"/probe/egressclient"},
|
||||
Cmd: append([]string{"/out/result"}, probes...),
|
||||
Env: ProxyEnv(token, "/ca/ca.pem"),
|
||||
},
|
||||
HostConfig: &container.HostConfig{
|
||||
NetworkMode: container.NetworkMode(networkName),
|
||||
// z relabels for SELinux hosts, which otherwise refuse the
|
||||
// container access to freshly created host files.
|
||||
Binds: []string{bin + ":/probe:ro,z", caPath + ":/ca:ro,z", outDir + ":/out:z"},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
_, _ = cli.ContainerRemove(context.WithoutCancel(t.Context()), created.ID, client.ContainerRemoveOptions{Force: true})
|
||||
}()
|
||||
if _, err := cli.ContainerStart(t.Context(), created.ID, client.ContainerStartOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wait := cli.ContainerWait(t.Context(), created.ID, client.ContainerWaitOptions{Condition: container.WaitConditionNotRunning})
|
||||
select {
|
||||
case <-wait.Result:
|
||||
case err := <-wait.Error:
|
||||
t.Fatal(err)
|
||||
case <-time.After(90 * time.Second):
|
||||
t.Fatal("probe container did not finish")
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(outDir, "result"))
|
||||
if err != nil {
|
||||
t.Fatalf("probe wrote no result: %v", err)
|
||||
}
|
||||
return strings.Split(strings.TrimSpace(string(raw)), "\n")
|
||||
}
|
||||
|
||||
// TestSandboxNetworkReachesOnlyTheProxy runs real containers: a sandbox on
|
||||
// an isolated network, the relay, and the proxy on the host. It proves the
|
||||
// PRD's egress properties end to end rather than by construction.
|
||||
func TestSandboxNetworkReachesOnlyTheProxy(t *testing.T) {
|
||||
cli, err := client.New(client.FromEnv)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = cli.Close() })
|
||||
ensureImage(t, cli, probeImage)
|
||||
|
||||
bin := t.TempDir()
|
||||
buildStatic(t, bin, "github.com/samcharles93/archie-core/cmd/archie-agent", "archie-agent")
|
||||
buildStatic(t, bin, "./testdata/egressclient", "egressclient")
|
||||
|
||||
upstream := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = io.WriteString(w, "upstream:"+r.Host+r.URL.Path)
|
||||
}))
|
||||
t.Cleanup(upstream.Close)
|
||||
roots := x509.NewCertPool()
|
||||
roots.AddCert(upstream.Certificate())
|
||||
|
||||
caDir := t.TempDir()
|
||||
ca, err := LoadOrCreateCA(caDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
proxy := NewProxy(ca, ProxyOptions{
|
||||
UpstreamRoots: roots,
|
||||
Dial: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
if addr != "api.example.com:443" {
|
||||
return nil, fmt.Errorf("unrouted upstream %s", addr)
|
||||
}
|
||||
return (&net.Dialer{}).DialContext(ctx, network, upstream.Listener.Addr().String())
|
||||
},
|
||||
})
|
||||
gateway := bridgeGateway(t, cli)
|
||||
ln, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", net.JoinHostPort(gateway, "0"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := &http.Server{Handler: proxy, ReadHeaderTimeout: 10 * time.Second}
|
||||
go func() { _ = server.Serve(ln) }()
|
||||
t.Cleanup(func() { _ = server.Close() })
|
||||
proxyAddr := ln.Addr().String()
|
||||
|
||||
name := fmt.Sprintf("archie-egress-test-%d", time.Now().UnixNano())
|
||||
networks := NewNetworks(cli, RelaySpec{
|
||||
Name: name + "-relay",
|
||||
Image: probeImage,
|
||||
Entrypoint: []string{"/bin/archie-agent"},
|
||||
Cmd: RelayArgs(proxyAddr, "", ""),
|
||||
Network: "bridge",
|
||||
Binds: []string{filepath.Join(bin, "archie-agent") + ":/bin/archie-agent:ro,z"},
|
||||
})
|
||||
if err := networks.Start(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = networks.Close(context.WithoutCancel(t.Context())) })
|
||||
if err := networks.Create(t.Context(), name); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = networks.Remove(context.WithoutCancel(t.Context()), name) })
|
||||
|
||||
// A host service listening on every interface, the way NATS and
|
||||
// Postgres do. The sandbox must not reach it by any address.
|
||||
hostService, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", ":0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = hostService.Close() })
|
||||
go func() {
|
||||
for {
|
||||
c, err := hostService.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_ = c.Close()
|
||||
}
|
||||
}()
|
||||
_, hostPort, err := net.SplitHostPort(hostService.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sandboxNet, err := cli.NetworkInspect(t.Context(), name, client.NetworkInspectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(sandboxNet.Network.IPAM.Config) == 0 || !sandboxNet.Network.IPAM.Config[0].Subnet.IsValid() {
|
||||
t.Fatal("sandbox network has no subnet")
|
||||
}
|
||||
// The address a bridge gateway would hold: the subnet's first host. An
|
||||
// isolated sandbox network leaves it unassigned.
|
||||
sandboxGateway := sandboxNet.Network.IPAM.Config[0].Subnet.Masked().Addr().Next().String()
|
||||
|
||||
session, err := proxy.Register(SessionOptions{Run: "integration", Network: &spec.PhasedNetwork{Runtime: &spec.NetworkRules{Allow: []string{"api.example.com:443"}}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
session.EnterRuntime()
|
||||
|
||||
results := runProbe(t, cli, name, bin, caDir, session.Token(),
|
||||
"get", "https://api.example.com/ok",
|
||||
"get", "https://denied.example.com/",
|
||||
"dial", proxyAddr,
|
||||
"dial", net.JoinHostPort(sandboxGateway, hostPort),
|
||||
"dial", net.JoinHostPort(gateway, hostPort),
|
||||
"dial", "1.1.1.1:443",
|
||||
)
|
||||
want := []struct{ prefix, why string }{
|
||||
{"OK 200 upstream:api.example.com/ok", "an allowed host is reachable through the relay and proxy"},
|
||||
{"ERR", "a host outside the policy is refused"},
|
||||
{"BLOCKED", "the proxy's own listener is unreachable except through the relay"},
|
||||
{"BLOCKED", "a host service on all interfaces is unreachable through the sandbox's own gateway address"},
|
||||
{"BLOCKED", "a host service on all interfaces is unreachable through the docker bridge"},
|
||||
{"BLOCKED", "the internet is unreachable directly"},
|
||||
}
|
||||
if len(results) != len(want) {
|
||||
t.Fatalf("probe returned %d results, want %d: %q", len(results), len(want), results)
|
||||
}
|
||||
for i, w := range want {
|
||||
if !strings.HasPrefix(results[i], w.prefix) {
|
||||
t.Errorf("%s: got %q, want prefix %q", w.why, results[i], w.prefix)
|
||||
}
|
||||
}
|
||||
|
||||
wrong := runProbe(t, cli, name, bin, caDir, "not-a-token", "get", "https://api.example.com/ok")
|
||||
if len(wrong) != 1 || !strings.HasPrefix(wrong[0], "ERR") {
|
||||
t.Errorf("a sandbox with the wrong token reached upstream: %q", wrong)
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/harnesssecret"
|
||||
)
|
||||
|
||||
// The provider's granted scopes are captured with the token set (RFC 6749
|
||||
// section 5.1 spells them as one space-delimited string), so a Kit's
|
||||
// credential file can render them.
|
||||
func TestOAuthCaptureRecordsScopes(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.token.response = `{"access_token":"new-access","refresh_token":"new-refresh","expires_in":3600,"scope":"user:inference user:profile"}`
|
||||
_ = h.oauth.PutHarnessSecret(t.Context(), harnesssecret.Secret{
|
||||
Org: "org-1", Service: "claude-code",
|
||||
AccessToken: "old-access", RefreshToken: "real-refresh",
|
||||
Scopes: []string{"user:inference"},
|
||||
})
|
||||
s := h.oauthSession(t, true, true)
|
||||
|
||||
status, _ := postToken(t, h, s, "grant_type=refresh_token&refresh_token="+sentinelRefresh)
|
||||
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", status)
|
||||
}
|
||||
stored, err := h.oauth.GetHarnessSecret(t.Context(), "org-1", "claude-code")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := []string{"user:inference", "user:profile"}; !slices.Equal(stored.Scopes, want) {
|
||||
t.Fatalf("stored scopes = %v, want the granted set %v", stored.Scopes, want)
|
||||
}
|
||||
}
|
||||
|
||||
// A refresh that does not repeat the scope keeps the set the login captured:
|
||||
// a provider may return scopes only on the initial exchange.
|
||||
func TestOAuthCaptureKeepsScopesWhenTheResponseOmitsThem(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.token.response = `{"access_token":"new-access","refresh_token":"new-refresh","expires_in":3600}`
|
||||
want := []string{"user:inference", "user:profile"}
|
||||
_ = h.oauth.PutHarnessSecret(t.Context(), harnesssecret.Secret{
|
||||
Org: "org-1", Service: "claude-code",
|
||||
AccessToken: "old-access", RefreshToken: "real-refresh",
|
||||
Scopes: want,
|
||||
})
|
||||
s := h.oauthSession(t, true, true)
|
||||
|
||||
status, _ := postToken(t, h, s, "grant_type=refresh_token&refresh_token="+sentinelRefresh)
|
||||
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", status)
|
||||
}
|
||||
stored, err := h.oauth.GetHarnessSecret(t.Context(), "org-1", "claude-code")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !slices.Equal(stored.Scopes, want) {
|
||||
t.Fatalf("stored scopes = %v, want the set the login captured %v", stored.Scopes, want)
|
||||
}
|
||||
}
|
||||
@@ -1,331 +0,0 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/docker/sandbox-kit-spec/v3/spec"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/harnesssecret"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
type fakeOAuthStore struct {
|
||||
mu sync.Mutex
|
||||
secrets map[string]harnesssecret.Secret
|
||||
}
|
||||
|
||||
func newFakeOAuthStore() *fakeOAuthStore {
|
||||
return &fakeOAuthStore{secrets: map[string]harnesssecret.Secret{}}
|
||||
}
|
||||
|
||||
func (f *fakeOAuthStore) GetHarnessSecret(_ context.Context, org, service string) (harnesssecret.Secret, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
s, ok := f.secrets[org+"/"+service]
|
||||
if !ok {
|
||||
return harnesssecret.Secret{}, storecontract.ErrHarnessSecretNotFound
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (f *fakeOAuthStore) PutHarnessSecret(_ context.Context, s harnesssecret.Secret) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.secrets[s.Org+"/"+s.Service] = s
|
||||
return nil
|
||||
}
|
||||
|
||||
// tokenEndpoint is the fake provider token endpoint: it records the body the
|
||||
// proxy sent upstream and answers with a configured response.
|
||||
type tokenEndpoint struct {
|
||||
mu sync.Mutex
|
||||
lastBody []byte
|
||||
hits int
|
||||
response string
|
||||
}
|
||||
|
||||
func (e *tokenEndpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
e.lastBody, e.hits = body, e.hits+1
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = io.WriteString(w, e.response)
|
||||
}
|
||||
|
||||
func (e *tokenEndpoint) seen() (string, int) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
return string(e.lastBody), e.hits
|
||||
}
|
||||
|
||||
const (
|
||||
sentinelAccess = "sentinel-access"
|
||||
sentinelRefresh = "sentinel-refresh"
|
||||
)
|
||||
|
||||
func oauthCred(required bool) spec.CredentialCapability {
|
||||
return spec.CredentialCapability{
|
||||
Required: required,
|
||||
Service: "claude-code", Phase: "runtime",
|
||||
OAuth: &spec.OAuth{
|
||||
TokenEndpoint: &spec.TokenEndpoint{Host: "oauth.example.com", Path: "/token"},
|
||||
ResourceHosts: []string{"api.example.com"},
|
||||
Sentinels: &spec.Sentinels{AccessToken: sentinelAccess, RefreshToken: sentinelRefresh},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// oauthSession registers run-7 in org-1 with one OAuth credential, granted
|
||||
// to the run when grant is set.
|
||||
func (h *harness) oauthSession(t *testing.T, required, grant bool) *Session {
|
||||
t.Helper()
|
||||
if grant {
|
||||
h.bind("run-7/claude-code", "")
|
||||
}
|
||||
s, err := h.proxy.Register(SessionOptions{
|
||||
Run: "run-7", Org: "org-1",
|
||||
Network: &spec.PhasedNetwork{Runtime: &spec.NetworkRules{Allow: []string{"oauth.example.com:443", "api.example.com:443"}}},
|
||||
Credentials: []spec.CredentialCapability{oauthCred(required)},
|
||||
Bound: map[string]CredentialKind{"claude-code": CredentialOAuth},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.EnterRuntime()
|
||||
return s
|
||||
}
|
||||
|
||||
func postToken(t *testing.T, h *harness, s *Session, form string) (int, map[string]any) {
|
||||
t.Helper()
|
||||
req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, "https://oauth.example.com/token", strings.NewReader(form))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
resp, err := h.client(s.Token()).Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
var out map[string]any
|
||||
_ = json.Unmarshal(body, &out)
|
||||
return resp.StatusCode, out
|
||||
}
|
||||
|
||||
func TestOAuthRefreshUsesTheStoredTokenAndReturnsOnlySentinels(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
response string
|
||||
wantRefresh string
|
||||
}{
|
||||
{
|
||||
name: "rotating provider",
|
||||
response: `{"access_token":"new-access","refresh_token":"new-refresh","expires_in":3600,"token_type":"Bearer"}`,
|
||||
wantRefresh: "new-refresh",
|
||||
},
|
||||
{
|
||||
name: "provider keeps the refresh token",
|
||||
response: `{"access_token":"new-access","expires_in":3600}`,
|
||||
wantRefresh: "real-refresh",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.token.response = tt.response
|
||||
_ = h.oauth.PutHarnessSecret(t.Context(), harnesssecret.Secret{Org: "org-1", Service: "claude-code", AccessToken: "old-access", RefreshToken: "real-refresh"})
|
||||
s := h.oauthSession(t, true, true)
|
||||
|
||||
status, out := postToken(t, h, s, "grant_type=refresh_token&refresh_token="+sentinelRefresh)
|
||||
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", status)
|
||||
}
|
||||
if sent, _ := h.token.seen(); sent != "grant_type=refresh_token&refresh_token=real-refresh" {
|
||||
t.Fatalf("upstream body = %q, want the stored refresh token in place of the sentinel", sent)
|
||||
}
|
||||
if out["access_token"] != sentinelAccess {
|
||||
t.Fatalf("container got access_token %v, want the sentinel", out["access_token"])
|
||||
}
|
||||
if _, rotated := out["refresh_token"]; rotated && out["refresh_token"] != sentinelRefresh {
|
||||
t.Fatalf("container got refresh_token %v, want the sentinel", out["refresh_token"])
|
||||
}
|
||||
stored, _ := h.oauth.GetHarnessSecret(t.Context(), "org-1", "claude-code")
|
||||
if stored.AccessToken != "new-access" || stored.RefreshToken != tt.wantRefresh || stored.ExpiresAt.IsZero() {
|
||||
t.Fatalf("stored = %+v, want access new-access, refresh %s and an expiry", stored, tt.wantRefresh)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOAuthLoginExchangeCapturesWithNoStoredToken(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.token.response = `{"access_token":"first-access","refresh_token":"first-refresh"}`
|
||||
s := h.oauthSession(t, true, true)
|
||||
|
||||
status, out := postToken(t, h, s, "grant_type=authorization_code&code=abc")
|
||||
|
||||
if status != http.StatusOK || out["refresh_token"] != sentinelRefresh {
|
||||
t.Fatalf("status %d, body %v; want 200 with sentinels", status, out)
|
||||
}
|
||||
stored, err := h.oauth.GetHarnessSecret(t.Context(), "org-1", "claude-code")
|
||||
if err != nil || stored.RefreshToken != "first-refresh" {
|
||||
t.Fatalf("stored = %+v, %v; want the captured login", stored, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOAuthRefreshWithNoStoredTokenNeverReachesUpstream(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
s := h.oauthSession(t, true, true)
|
||||
|
||||
status, _ := postToken(t, h, s, "grant_type=refresh_token&refresh_token="+sentinelRefresh)
|
||||
|
||||
if status != http.StatusBadGateway {
|
||||
t.Fatalf("status = %d, want 502", status)
|
||||
}
|
||||
if _, hits := h.token.seen(); hits != 0 {
|
||||
t.Fatalf("upstream hit %d times, want 0", hits)
|
||||
}
|
||||
}
|
||||
|
||||
// An org's stored token is read and written only for a run whose credential
|
||||
// carries the service; declaring it in the Kit is not enough.
|
||||
func TestOAuthUngrantedRunNeitherReadsNorWritesTheOrgToken(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
required bool
|
||||
wantStatus int
|
||||
wantHits int
|
||||
}{
|
||||
{name: "required", required: true, wantStatus: http.StatusBadGateway, wantHits: 0},
|
||||
{name: "optional passes through untouched", required: false, wantStatus: http.StatusOK, wantHits: 1},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.token.response = `{"access_token":"attacker-access","refresh_token":"attacker-refresh"}`
|
||||
seed := harnesssecret.Secret{Org: "org-1", Service: "claude-code", AccessToken: "real-access", RefreshToken: "real-refresh"}
|
||||
_ = h.oauth.PutHarnessSecret(t.Context(), seed)
|
||||
s := h.oauthSession(t, tt.required, false)
|
||||
|
||||
status, _ := postToken(t, h, s, "grant_type=refresh_token&refresh_token="+sentinelRefresh)
|
||||
|
||||
sent, hits := h.token.seen()
|
||||
if status != tt.wantStatus || hits != tt.wantHits {
|
||||
t.Fatalf("status %d with %d upstream hits, want %d with %d", status, hits, tt.wantStatus, tt.wantHits)
|
||||
}
|
||||
if strings.Contains(sent, "real-refresh") {
|
||||
t.Fatalf("upstream saw the org's refresh token: %q", sent)
|
||||
}
|
||||
stored, _ := h.oauth.GetHarnessSecret(t.Context(), "org-1", "claude-code")
|
||||
if stored.Org != seed.Org || stored.Service != seed.Service ||
|
||||
stored.AccessToken != seed.AccessToken || stored.RefreshToken != seed.RefreshToken ||
|
||||
stored.TokenType != seed.TokenType || !stored.ExpiresAt.Equal(seed.ExpiresAt) ||
|
||||
!slices.Equal(stored.Scopes, seed.Scopes) {
|
||||
t.Fatalf("stored = %+v, want it unchanged", stored)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOAuthResourceRequestCarriesTheStoredAccessToken(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
_ = h.oauth.PutHarnessSecret(t.Context(), harnesssecret.Secret{Org: "org-1", Service: "claude-code", AccessToken: "real-access"})
|
||||
s := h.oauthSession(t, true, true)
|
||||
|
||||
req, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, "https://api.example.com/v1/messages", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+sentinelAccess)
|
||||
resp, err := h.client(s.Token()).Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
|
||||
if got := h.lastAuth.Load(); got != "Bearer real-access" {
|
||||
t.Fatalf("upstream Authorization = %v, want the stored access token", got)
|
||||
}
|
||||
}
|
||||
|
||||
// dualCred declares apiKey and oauth on one service, the spec's shape for
|
||||
// "whichever the host has bound" (docker/claude-code-kit does, for
|
||||
// anthropic).
|
||||
func dualCred(required bool) spec.CredentialCapability {
|
||||
c := oauthCred(required)
|
||||
c.APIKey = &spec.APIKey{Name: "EXAMPLE_KEY", ProxyManaged: true, Inject: []spec.Inject{
|
||||
{Domain: "api.example.com", Header: "Authorization", Format: "Bearer %s"},
|
||||
}}
|
||||
return c
|
||||
}
|
||||
|
||||
// TestAnAPIKeyBoundServiceDoesNotInterceptTheTokenEndpoint is the mirror of
|
||||
// TestAnOAuthBoundServiceInjectsNoAPIKey: when the org's binding names a
|
||||
// secret for a service whose Kit also declares OAuth, this run has no token
|
||||
// set to exchange, so its token endpoint is an ordinary allowed host.
|
||||
// Intercepting it could only fail on the missing token set, or capture a
|
||||
// login the org never bound.
|
||||
func TestAnAPIKeyBoundServiceDoesNotInterceptTheTokenEndpoint(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
h.bind("run-7/claude-code", "sk-real-key")
|
||||
s, err := h.proxy.Register(SessionOptions{
|
||||
Run: "run-7", Org: "org-1",
|
||||
Network: &spec.PhasedNetwork{Runtime: &spec.NetworkRules{Allow: []string{"oauth.example.com:443"}}},
|
||||
Credentials: []spec.CredentialCapability{dualCred(false)},
|
||||
Bound: map[string]CredentialKind{"claude-code": CredentialAPIKey},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.EnterRuntime()
|
||||
status, _ := postToken(t, h, s, "grant_type=refresh_token&refresh_token="+sentinelRefresh)
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("token endpoint status %d, want 200: an API-key-bound run has no token set to intercept", status)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegisterAllowsARequiredAPIKeyBoundCredentialWithNoStore: a Kit may
|
||||
// declare apiKey and oauth on one service as required (the spec's
|
||||
// "whichever the host has bound"). An org that bound the API key has no use
|
||||
// for a token store, so the launch must not be refused for the missing one.
|
||||
func TestRegisterAllowsARequiredAPIKeyBoundCredentialWithNoStore(t *testing.T) {
|
||||
ca, err := LoadOrCreateCA(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := NewProxy(ca, ProxyOptions{})
|
||||
if _, err := p.Register(SessionOptions{
|
||||
Run: "run-7", Org: "org-1",
|
||||
Credentials: []spec.CredentialCapability{dualCred(true)},
|
||||
Bound: map[string]CredentialKind{"claude-code": CredentialAPIKey},
|
||||
}); err != nil {
|
||||
t.Fatalf("Register() = %v, want an API-key-bound run to need no token store", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterRefusesARequiredOAuthCredentialWithNoStore(t *testing.T) {
|
||||
ca, err := LoadOrCreateCA(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := NewProxy(ca, ProxyOptions{})
|
||||
if _, err := p.Register(SessionOptions{Run: "run-7", Org: "org-1", Credentials: []spec.CredentialCapability{oauthCred(true)}, Bound: map[string]CredentialKind{"claude-code": CredentialOAuth}}); err == nil {
|
||||
t.Fatal("Register() succeeded with a required OAuth credential and no store")
|
||||
}
|
||||
}
|
||||
|
||||
func newTokenEndpoint(t *testing.T) (*tokenEndpoint, *httptest.Server) {
|
||||
t.Helper()
|
||||
e := &tokenEndpoint{}
|
||||
srv := httptest.NewTLSServer(e)
|
||||
t.Cleanup(srv.Close)
|
||||
return e, srv
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/docker/sandbox-kit-spec/v3/spec"
|
||||
)
|
||||
|
||||
func TestRulesAllows(t *testing.T) {
|
||||
rules := compileRules(&spec.NetworkRules{
|
||||
Allow: []string{"api.example.com:443", "downloads.example.com", "*.cdn.example.net", "10.0.0.5:8080"},
|
||||
Deny: []string{"blocked.cdn.example.net"},
|
||||
})
|
||||
tests := []struct {
|
||||
host string
|
||||
port int
|
||||
want bool
|
||||
}{
|
||||
{"api.example.com", 443, true},
|
||||
{"api.example.com", 80, false},
|
||||
{"API.Example.COM.", 443, true},
|
||||
{"downloads.example.com", 443, true},
|
||||
{"downloads.example.com", 8443, true},
|
||||
{"a.cdn.example.net", 443, true},
|
||||
{"cdn.example.net", 443, false},
|
||||
{"a.b.cdn.example.net", 443, false},
|
||||
{"blocked.cdn.example.net", 443, false},
|
||||
{"10.0.0.5", 8080, true},
|
||||
{"10.0.0.5", 80, false},
|
||||
{"example.com", 443, false},
|
||||
{"evil-api.example.com", 443, false},
|
||||
{"api.example.com.evil.test", 443, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := rules.allows(tt.host, tt.port); got != tt.want {
|
||||
t.Errorf("allows(%q, %d) = %v, want %v", tt.host, tt.port, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRulesEverything(t *testing.T) {
|
||||
for _, all := range []string{"*", "**"} {
|
||||
rules := compileRules(&spec.NetworkRules{Allow: []string{all}, Deny: []string{"telemetry.example.com"}})
|
||||
if !rules.allows("anything.example.org", 443) {
|
||||
t.Errorf("%q does not allow an arbitrary host", all)
|
||||
}
|
||||
if rules.allows("telemetry.example.com", 443) {
|
||||
t.Errorf("deny does not win over %q", all)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNilRulesAllowNothing(t *testing.T) {
|
||||
if compileRules(nil).allows("api.example.com", 443) {
|
||||
t.Fatal("a phase with no rules allowed egress")
|
||||
}
|
||||
}
|
||||
@@ -1,260 +0,0 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// harness wires a proxy to local upstreams: the proxy's dialer maps the
|
||||
// public names a policy uses onto httptest listeners, so the tests exercise
|
||||
// the real CONNECT, TLS termination and forwarding paths hermetically.
|
||||
type harness struct {
|
||||
proxy *Proxy
|
||||
server *httptest.Server
|
||||
upstream *httptest.Server
|
||||
plain *httptest.Server
|
||||
hits atomic.Int32
|
||||
lastAuth atomic.Value
|
||||
lastInstall atomic.Value
|
||||
caPool *x509.CertPool
|
||||
|
||||
mu sync.Mutex
|
||||
secrets map[string]string
|
||||
resolved []string
|
||||
resolveErr error
|
||||
oauth *fakeOAuthStore
|
||||
token *tokenEndpoint
|
||||
}
|
||||
|
||||
func newHarness(t *testing.T) *harness {
|
||||
t.Helper()
|
||||
h := &harness{secrets: map[string]string{}, oauth: newFakeOAuthStore()}
|
||||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
h.hits.Add(1)
|
||||
h.lastAuth.Store(r.Header.Get("Authorization"))
|
||||
h.lastInstall.Store(r.Header.Get("X-Install"))
|
||||
_, _ = io.WriteString(w, "upstream:"+r.Host+r.URL.Path)
|
||||
})
|
||||
h.upstream = httptest.NewTLSServer(handler)
|
||||
h.plain = httptest.NewServer(handler)
|
||||
t.Cleanup(h.upstream.Close)
|
||||
t.Cleanup(h.plain.Close)
|
||||
|
||||
ca, err := LoadOrCreateCA(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
upstreamRoots := x509.NewCertPool()
|
||||
upstreamRoots.AddCert(h.upstream.Certificate())
|
||||
token, tokenSrv := newTokenEndpoint(t)
|
||||
h.token = token
|
||||
routes := map[string]string{
|
||||
"api.example.com:443": h.upstream.Listener.Addr().String(),
|
||||
"install.example.com:443": h.upstream.Listener.Addr().String(),
|
||||
"denied.example.com:443": h.upstream.Listener.Addr().String(),
|
||||
"plain.example.com:80": h.plain.Listener.Addr().String(),
|
||||
"oauth.example.com:443": tokenSrv.Listener.Addr().String(),
|
||||
}
|
||||
h.proxy = NewProxy(ca, ProxyOptions{
|
||||
UpstreamRoots: upstreamRoots,
|
||||
Resolver: ResolverFunc(h.resolve),
|
||||
OAuthStore: h.oauth,
|
||||
Dial: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
target, ok := routes[addr]
|
||||
if !ok {
|
||||
t.Errorf("proxy dialled unexpected upstream %s", addr)
|
||||
return nil, &net.OpError{Op: "dial", Net: network, Err: net.UnknownNetworkError("unrouted")}
|
||||
}
|
||||
return (&net.Dialer{}).DialContext(ctx, network, target)
|
||||
},
|
||||
})
|
||||
h.server = httptest.NewServer(h.proxy)
|
||||
t.Cleanup(h.server.Close)
|
||||
h.caPool = x509.NewCertPool()
|
||||
h.caPool.AppendCertsFromPEM(ca.CertPEM())
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *harness) register(t *testing.T) *Session {
|
||||
t.Helper()
|
||||
return h.registerWith(t)
|
||||
}
|
||||
|
||||
func (h *harness) client(token string) *http.Client {
|
||||
proxyURL, _ := url.Parse(h.server.URL)
|
||||
if token != "" {
|
||||
proxyURL.User = url.UserPassword(proxyUser, token)
|
||||
}
|
||||
return &http.Client{Transport: &http.Transport{
|
||||
Proxy: http.ProxyURL(proxyURL),
|
||||
TLSClientConfig: &tls.Config{RootCAs: h.caPool},
|
||||
}}
|
||||
}
|
||||
|
||||
func get(t *testing.T, c *http.Client, target string) (int, string, error) {
|
||||
t.Helper()
|
||||
req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, target, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp, err := c.Do(req)
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, string(body), nil
|
||||
}
|
||||
|
||||
func TestProxyForwardsAllowedHTTPS(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
s := h.register(t)
|
||||
s.EnterRuntime()
|
||||
status, body, err := get(t, h.client(s.Token()), "https://api.example.com/v1/messages")
|
||||
if err != nil {
|
||||
t.Fatalf("request through proxy: %v", err)
|
||||
}
|
||||
if status != http.StatusOK || body != "upstream:api.example.com/v1/messages" {
|
||||
t.Fatalf("got %d %q", status, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyRefusesWithoutAValidToken(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
s := h.register(t)
|
||||
s.EnterRuntime()
|
||||
revoked := h.register(t)
|
||||
revoked.EnterRuntime()
|
||||
h.proxy.Revoke(revoked.Token())
|
||||
for name, token := range map[string]string{"no token": "", "unknown token": "not-a-token", "revoked token": revoked.Token()} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
if _, _, err := get(t, h.client(token), "https://api.example.com/"); err == nil {
|
||||
t.Fatal("request succeeded without a valid session")
|
||||
}
|
||||
status, _, err := get(t, h.client(token), "http://plain.example.com/")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status != http.StatusProxyAuthRequired {
|
||||
t.Fatalf("plain request got %d, want 407", status)
|
||||
}
|
||||
})
|
||||
}
|
||||
if h.hits.Load() != 0 {
|
||||
t.Fatalf("upstream saw %d requests from unauthenticated clients", h.hits.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyEnforcesThePhasePolicy(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
s := h.register(t)
|
||||
c := h.client(s.Token())
|
||||
|
||||
if status, _, err := get(t, c, "https://install.example.com/"); err != nil || status != http.StatusOK {
|
||||
t.Fatalf("install-phase host during install: %d %v", status, err)
|
||||
}
|
||||
if _, _, err := get(t, c, "https://api.example.com/"); err == nil {
|
||||
t.Fatal("runtime-only host reachable during install")
|
||||
}
|
||||
s.EnterRuntime()
|
||||
if _, _, err := get(t, h.client(s.Token()), "https://install.example.com/"); err == nil {
|
||||
t.Fatal("install-phase host still reachable at runtime")
|
||||
}
|
||||
if _, _, err := get(t, h.client(s.Token()), "https://denied.example.com/"); err == nil {
|
||||
t.Fatal("host outside every allow list reachable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyForwardsAllowedPlainHTTP(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
s := h.register(t)
|
||||
s.EnterRuntime()
|
||||
status, body, err := get(t, h.client(s.Token()), "http://plain.example.com/x")
|
||||
if err != nil || status != http.StatusOK || body != "upstream:plain.example.com/x" {
|
||||
t.Fatalf("got %d %q %v", status, body, err)
|
||||
}
|
||||
status, _, err = get(t, h.client(s.Token()), "http://denied.example.com/")
|
||||
if err != nil || status != http.StatusForbidden {
|
||||
t.Fatalf("denied plain request got %d %v, want 403", status, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyRefusesAHostHeaderThatLeavesTheTunnel(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
s := h.register(t)
|
||||
s.EnterRuntime()
|
||||
c := h.client(s.Token())
|
||||
req, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, "https://api.example.com/", nil)
|
||||
req.Host = "denied.example.com"
|
||||
resp, err := c.Do(req)
|
||||
if err == nil {
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusMisdirectedRequest {
|
||||
t.Fatalf("smuggled Host got %d, want 421", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
if h.hits.Load() != 0 {
|
||||
t.Fatal("a request whose Host differs from its tunnel reached upstream")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyRefusesMismatchedSNI(t *testing.T) {
|
||||
h := newHarness(t)
|
||||
s := h.register(t)
|
||||
s.EnterRuntime()
|
||||
proxyURL, _ := url.Parse(h.server.URL)
|
||||
proxyURL.User = url.UserPassword(proxyUser, s.Token())
|
||||
tr := &http.Transport{
|
||||
Proxy: http.ProxyURL(proxyURL),
|
||||
TLSClientConfig: &tls.Config{RootCAs: h.caPool, ServerName: "denied.example.com"},
|
||||
}
|
||||
req, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, "https://api.example.com/", nil)
|
||||
resp, err := (&http.Client{Transport: tr}).Do(req)
|
||||
if err == nil {
|
||||
_ = resp.Body.Close()
|
||||
t.Fatal("a TLS handshake naming another host completed inside the tunnel")
|
||||
}
|
||||
if h.hits.Load() != 0 {
|
||||
t.Fatal("mismatched SNI reached upstream")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpstreamGuard(t *testing.T) {
|
||||
tests := []struct {
|
||||
ip string
|
||||
literal bool
|
||||
want bool
|
||||
}{
|
||||
{"93.184.216.34", false, true},
|
||||
{"127.0.0.1", false, false},
|
||||
{"127.0.0.1", true, false},
|
||||
{"::1", false, false},
|
||||
{"0.0.0.0", true, false},
|
||||
{"10.1.2.3", false, false},
|
||||
{"10.1.2.3", true, true},
|
||||
{"172.17.0.1", false, false},
|
||||
{"192.168.1.10", false, false},
|
||||
{"169.254.169.254", false, false},
|
||||
{"fd00::1", false, false},
|
||||
{"fe80::1", false, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
err := guardUpstream(net.ParseIP(tt.ip), tt.literal)
|
||||
if got := err == nil; got != tt.want {
|
||||
t.Errorf("guardUpstream(%s, literal=%v) allowed=%v, want %v (%v)", tt.ip, tt.literal, got, tt.want, err)
|
||||
}
|
||||
}
|
||||
if err := guardUpstream(net.ParseIP("127.0.0.1"), false); err == nil || !strings.Contains(err.Error(), "127.0.0.1") {
|
||||
t.Fatalf("guard error %v does not name the refused address", err)
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
package relay
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func listen(t *testing.T) net.Listener {
|
||||
t.Helper()
|
||||
ln, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = ln.Close() })
|
||||
return ln
|
||||
}
|
||||
|
||||
func echoServer(t *testing.T) string {
|
||||
t.Helper()
|
||||
ln := listen(t)
|
||||
go func() {
|
||||
for {
|
||||
c, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
defer c.Close()
|
||||
_, _ = io.Copy(c, c)
|
||||
}()
|
||||
}
|
||||
}()
|
||||
return ln.Addr().String()
|
||||
}
|
||||
|
||||
func startRelay(t *testing.T, target string) (string, context.CancelFunc, <-chan error) {
|
||||
t.Helper()
|
||||
ln := listen(t)
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- Serve(ctx, ln, target) }()
|
||||
return ln.Addr().String(), cancel, done
|
||||
}
|
||||
|
||||
func TestRelayForwardsBothWays(t *testing.T) {
|
||||
addr, cancel, _ := startRelay(t, echoServer(t))
|
||||
defer cancel()
|
||||
c, err := (&net.Dialer{}).DialContext(t.Context(), "tcp", addr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
_ = c.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
for _, line := range []string{"first\n", "second\n"} {
|
||||
if _, err := io.WriteString(c, line); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := bufio.NewReader(c).ReadString('\n')
|
||||
if err != nil || got != line {
|
||||
t.Fatalf("echo %q, want %q (%v)", got, line, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRelayClosesTheClientWhenTheTargetIsDown(t *testing.T) {
|
||||
dead := listen(t)
|
||||
target := dead.Addr().String()
|
||||
_ = dead.Close()
|
||||
addr, cancel, _ := startRelay(t, target)
|
||||
defer cancel()
|
||||
c, err := (&net.Dialer{}).DialContext(t.Context(), "tcp", addr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
_ = c.SetReadDeadline(time.Now().Add(5 * time.Second))
|
||||
if _, err := c.Read(make([]byte, 1)); !errors.Is(err, io.EOF) {
|
||||
t.Fatalf("read from a relay with no target: %v, want EOF", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRelayStopsOnCancel(t *testing.T) {
|
||||
_, cancel, done := startRelay(t, echoServer(t))
|
||||
cancel()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatalf("Serve returned %v after cancel, want nil", err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Serve did not return after its context was cancelled")
|
||||
}
|
||||
}
|
||||
@@ -1,211 +0,0 @@
|
||||
package embedding
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
domainembedding "github.com/samcharles93/archie-core/internal/domain/embedding"
|
||||
)
|
||||
|
||||
func TestNewDegradesWhenNoRoleConfigured(t *testing.T) {
|
||||
t.Parallel()
|
||||
cfg := config.Config{}
|
||||
if _, ok := New(cfg, Options{}); ok {
|
||||
t.Fatal("New() ok = true, want false when models[embedding] is unset")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDegradesWhenProviderUnknown(t *testing.T) {
|
||||
t.Parallel()
|
||||
cfg := config.Config{
|
||||
Models: map[string]string{Role: "openai/text-embedding-3-small"},
|
||||
}
|
||||
if _, ok := New(cfg, Options{}); ok {
|
||||
t.Fatal("New() ok = true, want false when the provider is not configured")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDegradesWhenRefHasNoProviderPrefix(t *testing.T) {
|
||||
t.Parallel()
|
||||
cfg := config.Config{
|
||||
Models: map[string]string{Role: "text-embedding-3-small"},
|
||||
Providers: map[string]config.Provider{"openai": {Class: "openai", APIKeyEnv: "TEST_KEY"}},
|
||||
}
|
||||
if _, ok := New(cfg, Options{Getenv: constEnv("secret")}); ok {
|
||||
t.Fatal("New() ok = true, want false for a model ref with no provider/ prefix")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDegradesWhenCredentialMissing(t *testing.T) {
|
||||
t.Parallel()
|
||||
cfg := config.Config{
|
||||
Models: map[string]string{Role: "openai/text-embedding-3-small"},
|
||||
Providers: map[string]config.Provider{"openai": {Class: "openai", APIKeyEnv: "TEST_MISSING_KEY"}},
|
||||
}
|
||||
if _, ok := New(cfg, Options{Getenv: constEnv("")}); ok {
|
||||
t.Fatal("New() ok = true, want false when the configured credential env var is empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDegradesForUnsupportedProviderClass(t *testing.T) {
|
||||
t.Parallel()
|
||||
cfg := config.Config{
|
||||
Models: map[string]string{Role: "custom/some-model"},
|
||||
Providers: map[string]config.Provider{"custom": {Class: "azure", APIKeyEnv: "TEST_KEY"}},
|
||||
}
|
||||
if _, ok := New(cfg, Options{Getenv: constEnv("secret")}); ok {
|
||||
t.Fatal("New() ok = true, want false for a provider class embeddings doesn't support")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewSucceedsWhenNoCredentialRequired(t *testing.T) {
|
||||
t.Parallel()
|
||||
cfg := config.Config{
|
||||
Models: map[string]string{Role: "local/nomic-embed-text"},
|
||||
Providers: map[string]config.Provider{"local": {Class: "ollama"}},
|
||||
}
|
||||
if _, ok := New(cfg, Options{}); !ok {
|
||||
t.Fatal("New() ok = false, want true for a credential-free provider class (ollama)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientEmbedReturnsVectorsInInputOrder(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/embeddings" {
|
||||
t.Fatalf("unexpected path %q", r.URL.Path)
|
||||
}
|
||||
var body struct {
|
||||
Model string `json:"model"`
|
||||
Input []string `json:"input"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Fatalf("decode request: %v", err)
|
||||
}
|
||||
if body.Model != "text-embedding-3-small" {
|
||||
t.Fatalf("model = %q, want %q", body.Model, "text-embedding-3-small")
|
||||
}
|
||||
resp := map[string]any{
|
||||
"object": "list",
|
||||
"model": body.Model,
|
||||
"data": []map[string]any{
|
||||
{"object": "embedding", "index": 1, "embedding": []float32{0.4, 0.5}},
|
||||
{"object": "embedding", "index": 0, "embedding": []float32{0.1, 0.2}},
|
||||
},
|
||||
"usage": map[string]any{"prompt_tokens": 3, "total_tokens": 3},
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(resp)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
cfg := config.Config{
|
||||
Models: map[string]string{Role: "openai/text-embedding-3-small"},
|
||||
Providers: map[string]config.Provider{
|
||||
"openai": {Class: "openai", APIKeyEnv: "TEST_OPENAI_KEY", BaseURL: srv.URL},
|
||||
},
|
||||
}
|
||||
c, ok := New(cfg, Options{Getenv: constEnv("secret")})
|
||||
if !ok {
|
||||
t.Fatal("New() ok = false, want true")
|
||||
}
|
||||
|
||||
vectors, err := c.Embed(context.Background(), []string{"hello", "world"})
|
||||
if err != nil {
|
||||
t.Fatalf("Embed() error = %v", err)
|
||||
}
|
||||
if len(vectors) != 2 {
|
||||
t.Fatalf("len(vectors) = %d, want 2", len(vectors))
|
||||
}
|
||||
if got := vectors[0]; len(got) != 2 || got[0] != 0.1 || got[1] != 0.2 {
|
||||
t.Fatalf("vectors[0] = %v, want [0.1 0.2]", got)
|
||||
}
|
||||
if got := vectors[1]; len(got) != 2 || got[0] != 0.4 || got[1] != 0.5 {
|
||||
t.Fatalf("vectors[1] = %v, want [0.4 0.5]", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientEmbedSurfacesProviderFailureAsError(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = w.Write([]byte(`{"error":"invalid api key"}`))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
cfg := config.Config{
|
||||
Models: map[string]string{Role: "openai/text-embedding-3-small"},
|
||||
Providers: map[string]config.Provider{
|
||||
"openai": {Class: "openai", APIKeyEnv: "TEST_OPENAI_KEY", BaseURL: srv.URL},
|
||||
},
|
||||
}
|
||||
c, ok := New(cfg, Options{Getenv: constEnv("bad-key")})
|
||||
if !ok {
|
||||
t.Fatal("New() ok = false, want true")
|
||||
}
|
||||
|
||||
if _, err := c.Embed(context.Background(), []string{"hello"}); err == nil {
|
||||
t.Fatal("Embed() error = nil, want a reported error for the 401 response")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientEmbedRespectsTimeout(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
release := make(chan struct{})
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
<-release
|
||||
}))
|
||||
// Cleanups run LIFO: srv.Close (registered first) waits for the
|
||||
// in-flight handler to return, so release must close before it does --
|
||||
// hence registering it second, not for statement-order readability.
|
||||
t.Cleanup(srv.Close)
|
||||
t.Cleanup(func() { close(release) })
|
||||
|
||||
cfg := config.Config{
|
||||
Models: map[string]string{Role: "openai/text-embedding-3-small"},
|
||||
Providers: map[string]config.Provider{
|
||||
"openai": {Class: "openai", APIKeyEnv: "TEST_OPENAI_KEY", BaseURL: srv.URL},
|
||||
},
|
||||
}
|
||||
c, ok := New(cfg, Options{Getenv: constEnv("secret"), Timeout: 50 * time.Millisecond})
|
||||
if !ok {
|
||||
t.Fatal("New() ok = false, want true")
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
_, err := c.Embed(context.Background(), []string{"hello"})
|
||||
if err == nil {
|
||||
t.Fatal("Embed() error = nil, want a timeout error")
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > 2*time.Second {
|
||||
t.Fatalf("Embed() took %v, want it bounded by the configured timeout", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientEmbedRejectsEmptyInput(t *testing.T) {
|
||||
t.Parallel()
|
||||
cfg := config.Config{
|
||||
Models: map[string]string{Role: "local/nomic-embed-text"},
|
||||
Providers: map[string]config.Provider{"local": {Class: "ollama"}},
|
||||
}
|
||||
c, ok := New(cfg, Options{})
|
||||
if !ok {
|
||||
t.Fatal("New() ok = false, want true")
|
||||
}
|
||||
if _, err := c.Embed(context.Background(), nil); !errors.Is(err, domainembedding.ErrEmptyInput) {
|
||||
t.Fatalf("Embed() error = %v, want %v", err, domainembedding.ErrEmptyInput)
|
||||
}
|
||||
}
|
||||
|
||||
func constEnv(value string) func(string) string {
|
||||
return func(string) string { return value }
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package nats
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
natstest "github.com/nats-io/nats-server/v2/test"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/eventbus"
|
||||
)
|
||||
|
||||
// TestPublishUniqueSuppressesDuplicateKeyOnWorkQueueStream is the regression
|
||||
// proof behind archie-core-7d5u.5 (idempotency and poll/webhook parity): a
|
||||
// forge issue discovered independently by the poller and the webhook
|
||||
// receiver produces two TaskEnvelopes with the identical
|
||||
// workintake.TaskEnvelope.IdempotencyKey(), published to the SAME
|
||||
// WorkQueuePolicy stream ARCHIE_TASKS uses in production (Config.Retention
|
||||
// left unset, per TestWithDefaultsRetention). A second PublishUnique call
|
||||
// with the same key inside the dedup window must be silently suppressed by
|
||||
// the server, so a single consumer only ever observes one message -- never
|
||||
// two tasks for one issue.
|
||||
func TestPublishUniqueSuppressesDuplicateKeyOnWorkQueueStream(t *testing.T) {
|
||||
srv := natstest.RunServer(&server.Options{Port: -1, JetStream: true, StoreDir: t.TempDir()})
|
||||
t.Cleanup(srv.Shutdown)
|
||||
|
||||
c, err := Connect(t.Context(), Config{
|
||||
URL: srv.ClientURL(),
|
||||
StreamName: "TASKS_DEDUP_TEST",
|
||||
Subjects: []string{"tasks.dedup.test.>"},
|
||||
FilterSubject: "tasks.dedup.test.>",
|
||||
// Retention left unset: defaults to WorkQueuePolicy, the same policy
|
||||
// ARCHIE_TASKS uses in production for task distribution.
|
||||
}, discardLogger())
|
||||
if err != nil {
|
||||
t.Fatalf("Connect = %v", err)
|
||||
}
|
||||
t.Cleanup(c.Close)
|
||||
|
||||
const key = "archie:owner/repo/42"
|
||||
|
||||
// Poll-discovered publish, then webhook-discovered publish of the same
|
||||
// issue moments later -- both carry the identical idempotency key.
|
||||
if err := c.PublishUnique(t.Context(), "tasks.dedup.test.issue", key, []byte("poll")); err != nil {
|
||||
t.Fatalf("PublishUnique (poll) = %v", err)
|
||||
}
|
||||
if err := c.PublishUnique(t.Context(), "tasks.dedup.test.issue", key, []byte("webhook")); err != nil {
|
||||
t.Fatalf("PublishUnique (webhook) = %v", err)
|
||||
}
|
||||
|
||||
msg, err := c.Fetch(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("Fetch (first) = %v", err)
|
||||
}
|
||||
if err := msg.Ack(); err != nil {
|
||||
t.Fatalf("Ack = %v", err)
|
||||
}
|
||||
|
||||
// A second delivery for the same issue would be a double-dispatched
|
||||
// task. There must be none queued.
|
||||
if _, err := c.Fetch(t.Context()); err == nil {
|
||||
t.Fatal("Fetch (second) succeeded, want eventbus.ErrNoMessage -- duplicate was not suppressed")
|
||||
} else if !errors.Is(err, eventbus.ErrNoMessage) {
|
||||
t.Fatalf("Fetch (second) = %v, want eventbus.ErrNoMessage", err)
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
package nats
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
)
|
||||
|
||||
// TestStartEmbeddedLifecycle proves the in-process server starts with
|
||||
// JetStream enabled, accepts a client that provisions a stream, and stops on
|
||||
// Shutdown. It is the production path behind docs/prds/embedded-nats.md,
|
||||
// distinct from the test-only natstest helper used elsewhere.
|
||||
func TestStartEmbeddedLifecycle(t *testing.T) {
|
||||
srv, err := StartEmbedded(t.Context(), EmbeddedOptions{StoreDir: t.TempDir()}, discardLogger())
|
||||
if err != nil {
|
||||
t.Fatalf("StartEmbedded = %v", err)
|
||||
}
|
||||
|
||||
url := srv.ClientURL()
|
||||
if url == "" {
|
||||
t.Fatal("ClientURL() = empty, want the bound address")
|
||||
}
|
||||
if unauthenticated, connectErr := nats.Connect(url); connectErr == nil {
|
||||
unauthenticated.Close()
|
||||
t.Fatal("unauthenticated connection succeeded, want embedded NATS to require its per-start token")
|
||||
}
|
||||
token := srv.Token()
|
||||
if token == "" {
|
||||
t.Fatal("Token() = empty, want a generated runtime token")
|
||||
}
|
||||
|
||||
// Connecting and provisioning a stream proves JetStream is live, not just
|
||||
// the core NATS socket.
|
||||
c, err := Connect(t.Context(), Config{
|
||||
URL: url,
|
||||
Token: token,
|
||||
Subjects: []string{"embedded.test.>"},
|
||||
FilterSubject: "embedded.test.>",
|
||||
}, discardLogger())
|
||||
if err != nil {
|
||||
t.Fatalf("Connect to embedded server = %v", err)
|
||||
}
|
||||
c.Close()
|
||||
|
||||
srv.Shutdown()
|
||||
|
||||
// After Shutdown the port must refuse new connections, proving the server
|
||||
// owns its own stop rather than leaking the goroutine.
|
||||
if _, err := nats.Connect(url); err == nil {
|
||||
t.Fatalf("nats.Connect(%q) after Shutdown = nil, want connection refused", url)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStartEmbeddedShutdownOnCancelledContext pins that a cancelled ctx aborts
|
||||
// startup rather than blocking the full readiness window during shutdown
|
||||
// racing boot.
|
||||
func TestStartEmbeddedShutdownOnCancelledContext(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
if _, err := StartEmbedded(ctx, EmbeddedOptions{StoreDir: t.TempDir()}, discardLogger()); err == nil {
|
||||
t.Fatal("StartEmbedded(cancelled ctx) = nil, want an error")
|
||||
}
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
package nats
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
natstest "github.com/nats-io/nats-server/v2/test"
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/eventbus"
|
||||
)
|
||||
|
||||
func discardLogger() *slog.Logger { return slog.New(slog.DiscardHandler) }
|
||||
|
||||
// TestWithDefaultsRetention pins the retention default: unset defaults to
|
||||
// WorkQueuePolicy (task distribution), and an explicit LimitsPolicy is left
|
||||
// alone. The pointer form is what lets "unset" default to WorkQueuePolicy
|
||||
// when the policy's zero value (LimitsPolicy) is a valid explicit choice.
|
||||
func TestWithDefaultsRetention(t *testing.T) {
|
||||
t.Run("unset defaults to work-queue", func(t *testing.T) {
|
||||
cfg := (Config{}).withDefaults()
|
||||
if cfg.Retention == nil {
|
||||
t.Fatal("withDefaults().Retention = nil, want non-nil")
|
||||
}
|
||||
if *cfg.Retention != jetstream.WorkQueuePolicy {
|
||||
t.Fatalf("withDefaults().Retention = %v, want %v", *cfg.Retention, jetstream.WorkQueuePolicy)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("explicit limits is preserved", func(t *testing.T) {
|
||||
limits := jetstream.LimitsPolicy
|
||||
cfg := (Config{Retention: &limits}).withDefaults()
|
||||
if cfg.Retention == nil || *cfg.Retention != jetstream.LimitsPolicy {
|
||||
t.Fatalf("withDefaults().Retention = %v, want %v", cfg.Retention, jetstream.LimitsPolicy)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestConnectRetentionFanout proves the reason retention must be a Config
|
||||
// field: under LimitsPolicy two independent consumers each receive every
|
||||
// matching message (fan-out), the behaviour reactions need and WorkQueuePolicy
|
||||
// cannot provide. This is the exact trap CLAUDE.md documents -- a second
|
||||
// consumer on an overlapping filter subject under WorkQueuePolicy silently
|
||||
// gets nothing.
|
||||
func TestConnectRetentionFanout(t *testing.T) {
|
||||
srv := natstest.RunServer(&server.Options{Port: -1, JetStream: true, StoreDir: t.TempDir()})
|
||||
t.Cleanup(srv.Shutdown)
|
||||
|
||||
limits := jetstream.LimitsPolicy
|
||||
c, err := Connect(t.Context(), Config{
|
||||
URL: srv.ClientURL(),
|
||||
StreamName: "REACTIONS_FANOUT_TEST",
|
||||
Subjects: []string{"reaction.fanout.test.>"},
|
||||
FilterSubject: "reaction.fanout.test.>",
|
||||
Retention: &limits,
|
||||
}, discardLogger())
|
||||
if err != nil {
|
||||
t.Fatalf("Connect = %v", err)
|
||||
}
|
||||
t.Cleanup(c.Close)
|
||||
|
||||
var mu sync.Mutex
|
||||
gotA := map[string]int{}
|
||||
gotB := map[string]int{}
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
done := make(chan struct{}, 2)
|
||||
subscriber := func(recv map[string]int) {
|
||||
defer func() { done <- struct{}{} }()
|
||||
_ = c.Subscribe(ctx, "reaction.fanout.test.>", func(m eventbus.Message) error {
|
||||
mu.Lock()
|
||||
recv[string(m.Data())]++
|
||||
mu.Unlock()
|
||||
return nil
|
||||
})
|
||||
}
|
||||
go subscriber(gotA)
|
||||
go subscriber(gotB)
|
||||
|
||||
// Publish after the consumers have had a chance to be created, but the
|
||||
// Limits stream retains messages regardless of subscriber timing.
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
if err := c.Publish(t.Context(), "reaction.fanout.test.1", []byte("x")); err != nil {
|
||||
t.Fatalf("Publish x = %v", err)
|
||||
}
|
||||
if err := c.Publish(t.Context(), "reaction.fanout.test.2", []byte("y")); err != nil {
|
||||
t.Fatalf("Publish y = %v", err)
|
||||
}
|
||||
|
||||
// Both consumers must observe both messages; poll rather than sleep a
|
||||
// fixed duration so a slow CI runner does not flake.
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
mu.Lock()
|
||||
aFull := gotA["x"] >= 1 && gotA["y"] >= 1
|
||||
bFull := gotB["x"] >= 1 && gotB["y"] >= 1
|
||||
mu.Unlock()
|
||||
if aFull && bFull {
|
||||
break
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
cancel()
|
||||
<-done
|
||||
<-done
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
for name, got := range map[string]map[string]int{"A": gotA, "B": gotB} {
|
||||
if got["x"] != 1 || got["y"] != 1 {
|
||||
t.Errorf("consumer %s received %v, want x and y once each (fan-out failed)", name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package nats
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestClientConnectedReflectsTheLiveConnection pins the broker fact /status
|
||||
// reports. It must answer from the connection the daemon already holds -- a
|
||||
// client that dialled the broker itself would report whether a fresh dial
|
||||
// works, not whether this process's own task bus is up, and would put a
|
||||
// network round trip (and its timeout) inside a chat command's handler.
|
||||
func TestClientConnectedReflectsTheLiveConnection(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
srv, err := StartEmbedded(ctx, EmbeddedOptions{StoreDir: t.TempDir()}, discardLogger())
|
||||
if err != nil {
|
||||
t.Fatalf("StartEmbedded = %v", err)
|
||||
}
|
||||
t.Cleanup(srv.Shutdown)
|
||||
|
||||
live, err := Connect(ctx, Config{
|
||||
URL: srv.ClientURL(),
|
||||
Token: srv.Token(),
|
||||
Subjects: []string{"status.test.>"},
|
||||
FilterSubject: "status.test.>",
|
||||
}, discardLogger())
|
||||
if err != nil {
|
||||
t.Fatalf("Connect = %v", err)
|
||||
}
|
||||
t.Cleanup(live.Close)
|
||||
|
||||
closed, err := Connect(ctx, Config{
|
||||
URL: srv.ClientURL(),
|
||||
Token: srv.Token(),
|
||||
Subjects: []string{"status.closed.>"},
|
||||
FilterSubject: "status.closed.>",
|
||||
}, discardLogger())
|
||||
if err != nil {
|
||||
t.Fatalf("Connect = %v", err)
|
||||
}
|
||||
closed.Close()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
client *Client
|
||||
want bool
|
||||
}{
|
||||
{name: "connected client", client: live, want: true},
|
||||
{name: "closed client", client: closed, want: false},
|
||||
{name: "no client at all", client: nil, want: false},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := tc.client.Connected(); got != tc.want {
|
||||
t.Errorf("Connected() = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
package gatewayrpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
)
|
||||
|
||||
// authChat is a minimal ChatContract for the auth boundary: only Snapshot
|
||||
// and Stream are exercised, the rest fall through to the nil embedded
|
||||
// contract and are never called.
|
||||
type authChat struct {
|
||||
gateway.ChatContract
|
||||
snapshot gateway.ChatSnapshot
|
||||
}
|
||||
|
||||
func (f *authChat) Snapshot(context.Context) (gateway.ChatSnapshot, error) {
|
||||
return f.snapshot, nil
|
||||
}
|
||||
|
||||
func (f *authChat) Stream(context.Context, gateway.Inbound) (<-chan gateway.ChatEvent, error) {
|
||||
ch := make(chan gateway.ChatEvent)
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
// serveAuth serves the chat contract on a loopback listener with the token
|
||||
// interceptors installed when token is non-empty, mirroring the standalone
|
||||
// gateway composition. It returns the dial target.
|
||||
func serveAuth(t *testing.T, token string) string {
|
||||
t.Helper()
|
||||
listener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
var opts []grpc.ServerOption
|
||||
if token != "" {
|
||||
opts = []grpc.ServerOption{
|
||||
grpc.ChainUnaryInterceptor(UnaryServerInterceptor(token)),
|
||||
grpc.ChainStreamInterceptor(StreamServerInterceptor(token)),
|
||||
}
|
||||
}
|
||||
server := grpc.NewServer(opts...)
|
||||
RegisterServer(server, &authChat{})
|
||||
go func() { _ = server.Serve(listener) }()
|
||||
t.Cleanup(server.Stop)
|
||||
return listener.Addr().String()
|
||||
}
|
||||
|
||||
func TestGatewayTokenRoundTrip(t *testing.T) {
|
||||
target := serveAuth(t, "correct-token")
|
||||
client, cleanup, err := Dial(target, "correct-token")
|
||||
if err != nil {
|
||||
t.Fatalf("Dial with the correct token: %v", err)
|
||||
}
|
||||
defer cleanup()
|
||||
if _, err := client.Snapshot(t.Context()); err != nil {
|
||||
t.Fatalf("Snapshot with the correct token: %v", err)
|
||||
}
|
||||
events, err := client.Stream(t.Context(), gateway.Inbound{})
|
||||
if err != nil {
|
||||
t.Fatalf("Stream with the correct token: %v", err)
|
||||
}
|
||||
for range events {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayTokenMissingIsRejected(t *testing.T) {
|
||||
target := serveAuth(t, "correct-token")
|
||||
// A loopback target dials without a credential, so the dial itself
|
||||
// succeeds; the server rejects the unauthenticated call.
|
||||
client, cleanup, err := Dial(target, "")
|
||||
if err != nil {
|
||||
t.Fatalf("Dial to a loopback target without a token: %v", err)
|
||||
}
|
||||
defer cleanup()
|
||||
if _, err := client.Snapshot(t.Context()); status.Code(err) != codes.Unauthenticated {
|
||||
t.Fatalf("Snapshot without a token: code = %v, want Unauthenticated (err = %v)", status.Code(err), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayTokenWrongIsRejected(t *testing.T) {
|
||||
target := serveAuth(t, "correct-token")
|
||||
client, cleanup, err := Dial(target, "wrong-token")
|
||||
if err != nil {
|
||||
t.Fatalf("Dial with a token: %v", err)
|
||||
}
|
||||
defer cleanup()
|
||||
if _, err := client.Snapshot(t.Context()); status.Code(err) != codes.Unauthenticated {
|
||||
t.Fatalf("Snapshot with the wrong token: code = %v, want Unauthenticated (err = %v)", status.Code(err), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayStreamWithoutTokenIsRejected(t *testing.T) {
|
||||
target := serveAuth(t, "correct-token")
|
||||
client, cleanup, err := Dial(target, "")
|
||||
if err != nil {
|
||||
t.Fatalf("Dial to a loopback target without a token: %v", err)
|
||||
}
|
||||
defer cleanup()
|
||||
events, err := client.Stream(t.Context(), gateway.Inbound{})
|
||||
if err != nil {
|
||||
t.Fatalf("Stream without a token: %v", err)
|
||||
}
|
||||
event, ok := <-events
|
||||
if !ok {
|
||||
t.Fatal("Stream without a token closed with no error event")
|
||||
}
|
||||
if event.Kind != "error" {
|
||||
t.Fatalf("Stream without a token: event kind = %q, want error", event.Kind)
|
||||
}
|
||||
}
|
||||
@@ -1,240 +0,0 @@
|
||||
package gatewayrpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
func remoteChat(t *testing.T, local gateway.ChatContract) gateway.ChatContract {
|
||||
t.Helper()
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
server := grpc.NewServer()
|
||||
RegisterServer(server, local)
|
||||
go func() { _ = server.Serve(listener) }()
|
||||
t.Cleanup(func() { server.Stop(); _ = listener.Close() })
|
||||
conn, err := grpc.NewClient("passthrough:///gateway", grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) }))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
return NewClient(conn)
|
||||
}
|
||||
|
||||
func TestChatContractConformance(t *testing.T) {
|
||||
for _, mode := range []string{"local", "grpc"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
sessions := gateway.NewSessionStoreMemory()
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
router := gateway.NewRouter(nil, nil, "web")
|
||||
router.Version = "Archie\nGateway: 1.2.3\nRuntime: 4.5.6"
|
||||
router.InitSessions(sessions)
|
||||
local := &gateway.LocalChatAdapter{Router: router, Sessions: sessions}
|
||||
var chat gateway.ChatContract = local
|
||||
if mode == "grpc" {
|
||||
chat = remoteChat(t, local)
|
||||
}
|
||||
if _, found, err := chat.GetSession(ctx, "missing"); err != nil || found {
|
||||
t.Fatalf("missing session: %v %v", found, err)
|
||||
}
|
||||
msg := gateway.Inbound{
|
||||
Message: messaging.Message{ConversationID: messaging.ConversationID{ChannelID: "browser"}, Sender: "web", Role: messaging.RoleUser, Text: "/help"},
|
||||
Page: "/tasks",
|
||||
}
|
||||
reply, err := chat.Route(ctx, msg)
|
||||
if err != nil || reply.Text == "" || reply.SessionID == "" {
|
||||
t.Fatalf("route: %+v %v", reply, err)
|
||||
}
|
||||
session, found, err := chat.GetSession(ctx, reply.SessionID)
|
||||
if err != nil || !found || session.Source.Platform != "web" {
|
||||
t.Fatalf("session: %+v %v %v", session, found, err)
|
||||
}
|
||||
snap, err := chat.Snapshot(ctx)
|
||||
if err != nil || len(snap.Sessions) != 1 || snap.CancellationAvailable || snap.PersonasAvailable {
|
||||
t.Fatalf("snapshot: %+v %v", snap, err)
|
||||
}
|
||||
// The Messaging Service renders /version from this field rather
|
||||
// than stamping its own build, so it has to survive the wire.
|
||||
if snap.Version != router.Version {
|
||||
t.Fatalf("snapshot version = %q, want %q", snap.Version, router.Version)
|
||||
}
|
||||
if _, err := chat.RecentMessages(ctx, reply.SessionID, 200); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if turns, err := chat.RecentTurns(ctx, reply.SessionID, 200); err != nil || len(turns) != 0 {
|
||||
t.Fatalf("turns: %+v %v", turns, err)
|
||||
}
|
||||
if _, err := chat.Cancel(ctx, reply.SessionID); err == nil {
|
||||
t.Fatal("missing cancellation capability accepted")
|
||||
}
|
||||
if _, err := chat.SetPersona(ctx, reply.SessionID, "missing"); err == nil {
|
||||
t.Fatal("missing persona capability accepted")
|
||||
}
|
||||
events, err := chat.Stream(ctx, msg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var got []gateway.ChatEvent
|
||||
for event := range events {
|
||||
got = append(got, event)
|
||||
}
|
||||
if len(got) < 2 || got[0].Kind != "started" || got[len(got)-1].Kind != "done" || got[len(got)-1].Text != reply.Text {
|
||||
t.Fatalf("stream: %+v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWireValuesPreserveHistoryAndMedia(t *testing.T) {
|
||||
now := time.Date(2026, 9, 5, 1, 2, 3, 456, time.UTC)
|
||||
tool := gateway.ToolCallEvent{ID: "tool-1", Name: "read", Parameters: "{}", Output: "result", Err: "failed"}
|
||||
turn := gateway.TurnRecord{TurnID: "turn", SessionID: "session", SourceID: "source", Status: gateway.TurnStatusPartial, Attempt: 3, OwnerID: "owner", InputMessageID: "input", AssistantMessageID: "assistant", PartialText: "partial", ResponseText: "reply", ToolCalls: []gateway.ToolCallEvent{tool}, Error: "failure", CreatedAt: now, UpdatedAt: now}
|
||||
if got := turnValue(turnProto(turn)); !reflect.DeepEqual(got, turn) {
|
||||
t.Fatalf("turn round trip: %+v", got)
|
||||
}
|
||||
size := int64(0)
|
||||
width := 640
|
||||
height := 480
|
||||
duration := 3
|
||||
event := gateway.ChatEvent{Kind: "media", Text: "caption", SessionID: "session", Tool: tool, Media: gateway.MediaEvent{ToolName: "send_file", Attachment: gateway.MediaAttachment{Type: "video", FileID: "file", URL: "https://example.test/video", Path: "/tmp/video", MIMEType: "video/mp4", FileName: "video.mp4", FileSize: &size, Width: &width, Height: &height, Duration: &duration}}}
|
||||
if got := eventValue(eventProto(event)); !reflect.DeepEqual(got, event) {
|
||||
t.Fatalf("event round trip: %+v", got)
|
||||
}
|
||||
// Transport-only inbound context rides alongside the record and must
|
||||
// survive the hop: Page reaches the system prompt, BudgetKey is what the
|
||||
// Gateway charges the message against when the channel has no per-person
|
||||
// SenderID to charge (a webhook route), and Platform is how the Gateway
|
||||
// learns which channel it is serving -- one Router serves all of them
|
||||
// (archie-core-c1qx).
|
||||
in := gateway.Inbound{
|
||||
Message: messaging.Message{ConversationID: messaging.ConversationID{ChannelID: "/hook"}, Role: messaging.RoleUser, Text: "hi"},
|
||||
Page: "/tasks",
|
||||
BudgetKey: "/hook",
|
||||
Platform: "webhook",
|
||||
}
|
||||
if got := inboundValue(inboundProto(in)); !reflect.DeepEqual(got, in) {
|
||||
t.Fatalf("inbound round trip = %+v, want %+v", got, in)
|
||||
}
|
||||
if got := inboundValue(inboundProto(gateway.Inbound{})); !got.Message.At.IsZero() {
|
||||
t.Fatalf("zero time became %v", got.Message.At)
|
||||
}
|
||||
}
|
||||
|
||||
// recordingTaskActor captures the identity scope an action reached the daemon
|
||||
// with. A pointer, because nil is a distinct authorization, not a blank name.
|
||||
type recordingTaskActor struct {
|
||||
identity *string
|
||||
taskID int64
|
||||
action taskstate.Action
|
||||
payload taskactions.ActionPayload
|
||||
}
|
||||
|
||||
func (a *recordingTaskActor) ApplyChatTaskAction(
|
||||
_ context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action, payload taskactions.ActionPayload,
|
||||
) (gateway.TaskActionResult, error) {
|
||||
a.identity, a.taskID, a.action, a.payload = identity, taskID, action, payload
|
||||
return gateway.TaskActionResult{TaskID: taskID, Action: string(action), Message: "applied"}, nil
|
||||
}
|
||||
|
||||
// TestTaskActionScopeSurvivesTheWire pins the distinction the daemon's action
|
||||
// service draws (internal/domain/taskactions.Service.Apply): a nil identity is
|
||||
// an authenticated dashboard operator acting across identities, a non-nil one
|
||||
// is a chat user acting on their own task. ApplyTaskAction cannot express the
|
||||
// operator case -- "" is a real identity in a single-identity deployment (see
|
||||
// chatTaskProfiles) -- so it has its own contract method, and the difference
|
||||
// has to survive both the local adapter and the gRPC hop.
|
||||
func TestTaskActionScopeSurvivesTheWire(t *testing.T) {
|
||||
for _, mode := range []string{"local", "grpc"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
actor := &recordingTaskActor{}
|
||||
local := &gateway.LocalChatAdapter{TaskActor: actor}
|
||||
var chat gateway.ChatContract = local
|
||||
if mode == "grpc" {
|
||||
chat = remoteChat(t, local)
|
||||
}
|
||||
|
||||
result, err := chat.ApplyOperatorTaskAction(ctx, taskactions.Actor{}, 42, taskstate.ActionApprove, taskactions.ActionPayload{RetryMode: taskstate.RetryContinuePushedWork})
|
||||
if err != nil {
|
||||
t.Fatalf("operator action: %v", err)
|
||||
}
|
||||
if actor.identity != nil {
|
||||
t.Fatalf("operator action arrived scoped to %q, want an unscoped nil identity", *actor.identity)
|
||||
}
|
||||
if actor.taskID != 42 || actor.action != taskstate.ActionApprove {
|
||||
t.Fatalf("operator action = (%d, %q), want (42, %q)", actor.taskID, actor.action, taskstate.ActionApprove)
|
||||
}
|
||||
if actor.payload.RetryMode != taskstate.RetryContinuePushedWork {
|
||||
t.Fatalf("operator action retry mode = %q, want %q: the choice must survive the hop", actor.payload.RetryMode, taskstate.RetryContinuePushedWork)
|
||||
}
|
||||
if result.TaskID != 42 || result.Action != string(taskstate.ActionApprove) || result.Message != "applied" {
|
||||
t.Fatalf("operator result = %+v, want the daemon's result", result)
|
||||
}
|
||||
|
||||
if _, err := chat.ApplyTaskAction(ctx, "scout", 7, taskstate.ActionRetry, taskactions.ActionPayload{}); err != nil {
|
||||
t.Fatalf("chat action: %v", err)
|
||||
}
|
||||
if actor.identity == nil || *actor.identity != "scout" {
|
||||
t.Fatalf("chat action lost its identity scope: %v", actor.identity)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// failingTaskActor reports one error, whatever the action.
|
||||
type failingTaskActor struct{ err error }
|
||||
|
||||
func (a failingTaskActor) ApplyChatTaskAction(
|
||||
context.Context, *string, taskactions.Actor, int64, taskstate.Action, taskactions.ActionPayload,
|
||||
) (gateway.TaskActionResult, error) {
|
||||
return gateway.TaskActionResult{}, a.err
|
||||
}
|
||||
|
||||
// TestTaskActionErrorsKeepTheirSentinelOverGRPC: the dashboard answers 404,
|
||||
// 409 or 503 by matching these sentinels, and gRPC carries a code and a
|
||||
// string, not a Go error. Losing the class here turns "that task already
|
||||
// moved on" into "the daemon is broken".
|
||||
func TestTaskActionErrorsKeepTheirSentinelOverGRPC(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
err error
|
||||
}{
|
||||
{name: "not found", err: fmt.Errorf("task 7: %w", taskactions.ErrNotFound)},
|
||||
{name: "conflict", err: fmt.Errorf("%w: action \"approve\" is not available while task is parked", taskactions.ErrConflict)},
|
||||
{name: "stale transition", err: fmt.Errorf("stop task 7: %w", storecontract.ErrStaleTransition)},
|
||||
{name: "unavailable", err: taskactions.ErrUnavailable},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
local := &gateway.LocalChatAdapter{TaskActor: failingTaskActor{err: tc.err}}
|
||||
chat := remoteChat(t, local)
|
||||
|
||||
_, err := chat.ApplyOperatorTaskAction(ctx, taskactions.Actor{}, 7, taskstate.ActionApprove, taskactions.ActionPayload{})
|
||||
if err == nil {
|
||||
t.Fatalf("ApplyOperatorTaskAction error = nil, want %v", tc.err)
|
||||
}
|
||||
if !errors.Is(err, errors.Unwrap(tc.err)) && !errors.Is(err, tc.err) {
|
||||
t.Fatalf("error %v is not the daemon's sentinel %v", err, tc.err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tc.err.Error()) {
|
||||
t.Fatalf("error message = %q, want it to carry the daemon's %q", err.Error(), tc.err.Error())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
package gatewayrpc
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestTargetIsLoopback(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
addr string
|
||||
want bool
|
||||
}{
|
||||
{"loopback ipv4", "127.0.0.1:8585", true},
|
||||
{"loopback ipv6", "[::1]:8585", true},
|
||||
{"localhost hostname", "localhost:8585", true},
|
||||
{"localhost uppercase", "LOCALHOST:8585", true},
|
||||
{"wildcard", "0.0.0.0:8585", false},
|
||||
{"private ip", "192.168.1.10:8585", false},
|
||||
{"dns name", "gateway.example.com:8585", false},
|
||||
{"empty host", ":8585", false},
|
||||
{"malformed", "127.0.0.1", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := TargetIsLoopback(tt.addr)
|
||||
if tt.name == "malformed" {
|
||||
if err == nil {
|
||||
t.Fatalf("TargetIsLoopback(%q) = (%v, nil), want error", tt.addr, got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("TargetIsLoopback(%q): %v", tt.addr, err)
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Fatalf("TargetIsLoopback(%q) = %v, want %v", tt.addr, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDialFailsClosedOffLoopbackWithoutToken is the transport half of the
|
||||
// Gateway security rule: a target reachable from the network must present a
|
||||
// Bearer [REDACTED], so a missing credential stops the dial rather than opening
|
||||
// an unauthenticated connection. It mirrors staterpc's §9 dial rule.
|
||||
func TestDialFailsClosedOffLoopbackWithoutToken(t *testing.T) {
|
||||
if _, _, err := Dial("", ""); err == nil {
|
||||
t.Fatal("Dial with an empty target should fail")
|
||||
}
|
||||
if _, _, err := Dial("0.0.0.0:8585", ""); err == nil {
|
||||
t.Fatal("Dial to a non-loopback target without a token should fail closed")
|
||||
}
|
||||
client, cleanup, err := Dial("0.0.0.0:8585", "secret")
|
||||
if err != nil {
|
||||
t.Fatalf("Dial to a non-loopback target with a token: %v", err)
|
||||
}
|
||||
defer cleanup()
|
||||
if client == nil {
|
||||
t.Fatal("Dial returned no client")
|
||||
}
|
||||
loopback, cleanupLoopback, err := Dial("127.0.0.1:8585", "")
|
||||
if err != nil {
|
||||
t.Fatalf("Dial to a loopback target without a token: %v", err)
|
||||
}
|
||||
defer cleanupLoopback()
|
||||
if loopback == nil {
|
||||
t.Fatal("Dial returned no client for a loopback target")
|
||||
}
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
package gatewayrpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
)
|
||||
|
||||
// remoteStore wires a StoreClient to a real SQLite session store through the
|
||||
// gRPC server, mirroring production (standalone gateway owns the store,
|
||||
// archied dials in).
|
||||
func remoteStore(t *testing.T, sessions gateway.SessionStore, chat gateway.ChatContract) gateway.SessionStore {
|
||||
t.Helper()
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
server := grpc.NewServer()
|
||||
RegisterServer(server, chat, sessions)
|
||||
go func() { _ = server.Serve(listener) }()
|
||||
t.Cleanup(func() { server.Stop(); _ = listener.Close() })
|
||||
conn, err := grpc.NewClient("passthrough:///gateway", grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) }))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
return NewStoreClient(conn)
|
||||
}
|
||||
|
||||
// TestStoreClientPreservesCanonicalRecords pins the remote store contract:
|
||||
// messages cross the wire in their gateway shape (the proto is unchanged)
|
||||
// and come back as the same canonical records -- sender, derived role, and
|
||||
// conversation address intact. Roles are passed empty to prove the server
|
||||
// derives them from the owning session, exactly like the in-process
|
||||
// boundary.
|
||||
func TestStoreClientPreservesCanonicalRecords(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
sessions := gateway.NewSessionStoreMemory()
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
router := gateway.NewRouter(nil, nil, "web")
|
||||
router.InitSessions(sessions)
|
||||
local := &gateway.LocalChatAdapter{Router: router, Sessions: sessions}
|
||||
store := remoteStore(t, sessions, local)
|
||||
|
||||
sc := gateway.SessionContext{
|
||||
SessionID: "sess-1",
|
||||
Source: gateway.SessionSource{Platform: "web", BotUser: "archie", ChannelID: "chat-1"},
|
||||
CreatedAt: time.Now().UTC(),
|
||||
LastActiveAt: time.Now().UTC(),
|
||||
}
|
||||
if err := store.Save(ctx, sc); err != nil {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
|
||||
msgs := []messaging.Message{
|
||||
{SourceID: "w-1", Sender: "web", Text: "hello", At: time.Now().UTC()},
|
||||
{SourceID: "w-2", Sender: "archie", Text: "hi", At: time.Now().UTC()},
|
||||
}
|
||||
for _, m := range msgs {
|
||||
if err := store.SaveMessage(ctx, "sess-1", m); err != nil {
|
||||
t.Fatalf("SaveMessage: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
got, err := store.RecentMessages(ctx, "sess-1", 10)
|
||||
if err != nil {
|
||||
t.Fatalf("RecentMessages: %v", err)
|
||||
}
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("RecentMessages returned %d messages, want 2", len(got))
|
||||
}
|
||||
want := []messaging.Message{
|
||||
{
|
||||
SourceID: "w-1", Sender: "web", Role: messaging.RoleUser, Text: "hello",
|
||||
ConversationID: messaging.ConversationID{ChannelID: "chat-1"},
|
||||
},
|
||||
{
|
||||
SourceID: "w-2", Sender: "archie", Role: messaging.RoleAssistant, Text: "hi",
|
||||
ConversationID: messaging.ConversationID{ChannelID: "chat-1"},
|
||||
},
|
||||
}
|
||||
for i, w := range want {
|
||||
if got[i].SourceID != w.SourceID || got[i].Sender != w.Sender ||
|
||||
got[i].Role != w.Role || got[i].Text != w.Text ||
|
||||
got[i].ConversationID != w.ConversationID {
|
||||
t.Fatalf("message %d = %+v, want %+v", i, got[i], w)
|
||||
}
|
||||
if got[i].ID == "" {
|
||||
t.Fatalf("message %d has no canonical ID", i)
|
||||
}
|
||||
}
|
||||
|
||||
page, err := store.SearchMessages(ctx, "sess-1", gateway.MessageQuery{Query: "hello", Limit: 10})
|
||||
if err != nil {
|
||||
t.Fatalf("SearchMessages: %v", err)
|
||||
}
|
||||
if len(page.Messages) != 1 || page.Messages[0].Role != messaging.RoleUser ||
|
||||
page.Messages[0].ConversationID.ChannelID != "chat-1" {
|
||||
t.Fatalf("SearchMessages = %+v, want the user message with its conversation", page.Messages)
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
package gatewayrpc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// TestStoredMediaRoundTrip: a message's attachment metadata must survive
|
||||
// the wire both ways, while the in-process bytes -- turn-scoped by
|
||||
// contract -- must never be marshalled onto it.
|
||||
func TestStoredMediaRoundTrip(t *testing.T) {
|
||||
size, width := int64(2048), 640
|
||||
in := messaging.Message{
|
||||
ID: messaging.MessageID("m1"),
|
||||
Role: messaging.RoleUser, Text: "[document: notes.txt]",
|
||||
Media: []messaging.MediaAttachment{{
|
||||
Type: "document", FileID: "tg-f1", URL: "https://example.invalid/notes",
|
||||
Path: "/tmp/never-here", MIMEType: "text/plain", FileName: "notes.txt",
|
||||
FileSize: &size, Width: &width, Data: []byte("file bytes"),
|
||||
}},
|
||||
}
|
||||
out := storedValue(storedProto(in))
|
||||
if len(out.Media) != 1 {
|
||||
t.Fatalf("round-tripped media = %#v, want one attachment", out.Media)
|
||||
}
|
||||
att := out.Media[0]
|
||||
if att.Type != "document" || att.FileName != "notes.txt" || att.MIMEType != "text/plain" {
|
||||
t.Errorf("attachment = %#v, want its metadata preserved", att)
|
||||
}
|
||||
if att.FileID != "tg-f1" {
|
||||
t.Errorf("FileID = %q, want tg-f1", att.FileID)
|
||||
}
|
||||
if att.FileSize == nil || *att.FileSize != size || att.Width == nil || *att.Width != width {
|
||||
t.Errorf("numeric metadata = %#v, want size and width preserved", att)
|
||||
}
|
||||
if att.URL != "https://example.invalid/notes" {
|
||||
t.Errorf("URL = %q, want preserved", att.URL)
|
||||
}
|
||||
if len(att.Data) != 0 {
|
||||
t.Errorf("attachment bytes crossed the wire, want them stripped")
|
||||
}
|
||||
}
|
||||
|
||||
// TestInboundMediaRoundTrip mirrors the stored direction for the inbound
|
||||
// transport context, except that the bytes ride along. The channel frontend
|
||||
// (archie-messaging) downloads an inbound attachment, but the process that
|
||||
// runs the turn is archie-gateway/archied, which never holds the Telegram
|
||||
// token -- so the bytes have to cross this request or the model never sees
|
||||
// the photo or document it was sent.
|
||||
func TestInboundMediaRoundTrip(t *testing.T) {
|
||||
raw := []byte("jpeg bytes")
|
||||
in := messaging.Inbound{
|
||||
Message: messaging.Message{Text: "hi", Sender: "sam"},
|
||||
Media: []messaging.MediaAttachment{
|
||||
{Type: "image", FileID: "f1", MIMEType: "image/jpeg", Data: raw},
|
||||
},
|
||||
}
|
||||
out := inboundValue(inboundProto(in))
|
||||
if len(out.Media) != 1 || out.Media[0].FileID != "f1" || out.Media[0].Type != "image" {
|
||||
t.Fatalf("round-tripped inbound media = %#v, want the sender attachment", out.Media)
|
||||
}
|
||||
if !bytes.Equal(out.Media[0].Data, raw) {
|
||||
t.Errorf("inbound attachment bytes = %q, want %q carried to the turn", out.Media[0].Data, raw)
|
||||
}
|
||||
}
|
||||
@@ -1,219 +0,0 @@
|
||||
package kit
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
"github.com/docker/sandbox-kit-spec/v3/spec"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/egress"
|
||||
)
|
||||
|
||||
// oauthCredentialFileKit is a Kit declaring a proxy-managed OAuth credential
|
||||
// whose harness reads its tokens from a credential file, as the published
|
||||
// Claude Code Kit does (the spec's own example).
|
||||
const oauthCredentialFileKit = sessions + `
|
||||
- type: com.docker.sandbox/credential@1
|
||||
config:
|
||||
service: claude-code
|
||||
phase: runtime
|
||||
oauth:
|
||||
tokenEndpoint: {host: platform.claude.com, path: /v1/oauth/token}
|
||||
sentinels:
|
||||
accessToken: sk-ant-oat01-proxy-managed
|
||||
refreshToken: sk-ant-ort01-proxy-managed
|
||||
credentialFile:
|
||||
path: /home/agent/.claude/.credentials.json
|
||||
structure:
|
||||
claudeAiOauth:
|
||||
accessToken: "{{.AccessToken}}"
|
||||
refreshToken: "{{.RefreshToken}}"
|
||||
expiresAt: "{{.ExpiresAt}}"`
|
||||
|
||||
func credentialFilePlan(t *testing.T) *Plan {
|
||||
t.Helper()
|
||||
p, err := Admit(descriptor(t, spec.KindWorkload, oauthCredentialFileKit))
|
||||
if err != nil {
|
||||
t.Fatalf("admit: %v", err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func findFile(files []spec.File, path string) (spec.File, bool) {
|
||||
for _, f := range files {
|
||||
if f.Path == path {
|
||||
return f, true
|
||||
}
|
||||
}
|
||||
return spec.File{}, false
|
||||
}
|
||||
|
||||
// TestAssembleRendersTheOAuthCredentialFile is the sentinel rule: a bound
|
||||
// OAuth credential whose Kit declares a credentialFile gets that file written
|
||||
// at the declared path, holding the Kit's sentinels and never a real token.
|
||||
func TestAssembleRendersTheOAuthCredentialFile(t *testing.T) {
|
||||
l, err := Assemble(credentialFilePlan(t), image, LaunchParams{
|
||||
Execution: "exec-42", ProxyToken: "tok", CAPath: "/etc/archie/ca.pem",
|
||||
Bound: map[string]egress.CredentialKind{"claude-code": egress.CredentialOAuth},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, ok := findFile(l.Files, "/home/agent/.claude/.credentials.json")
|
||||
if !ok {
|
||||
t.Fatalf("no credential file at the declared path; files = %v", l.Files)
|
||||
}
|
||||
if f.Mode != "0600" {
|
||||
t.Errorf("credential file mode = %q, want 0600", f.Mode)
|
||||
}
|
||||
if strings.Contains(f.Content, "{{") {
|
||||
t.Errorf("credential file still holds a placeholder: %s", f.Content)
|
||||
}
|
||||
var doc struct {
|
||||
ClaudeAiOauth struct {
|
||||
AccessToken string `json:"accessToken"`
|
||||
RefreshToken string `json:"refreshToken"`
|
||||
ExpiresAt float64 `json:"expiresAt"`
|
||||
} `json:"claudeAiOauth"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(f.Content), &doc); err != nil {
|
||||
t.Fatalf("credential file is not JSON: %v\n%s", err, f.Content)
|
||||
}
|
||||
if doc.ClaudeAiOauth.AccessToken != "sk-ant-oat01-proxy-managed" {
|
||||
t.Errorf("accessToken = %q, want the Kit's access-token sentinel", doc.ClaudeAiOauth.AccessToken)
|
||||
}
|
||||
if doc.ClaudeAiOauth.RefreshToken != "sk-ant-ort01-proxy-managed" {
|
||||
t.Errorf("refreshToken = %q, want the Kit's refresh-token sentinel", doc.ClaudeAiOauth.RefreshToken)
|
||||
}
|
||||
if doc.ClaudeAiOauth.ExpiresAt != 0 {
|
||||
t.Errorf("expiresAt = %v, want 0 with no stored token set", doc.ClaudeAiOauth.ExpiresAt)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAssembleRendersTheStoredExpiry proves the credential file carries the
|
||||
// stored token set's expiry -- the value the CLI checks before it decides to
|
||||
// refresh -- and that it is a number, not a quoted placeholder.
|
||||
func TestAssembleRendersTheStoredExpiry(t *testing.T) {
|
||||
expires := time.UnixMilli(1700000000123)
|
||||
l, err := Assemble(credentialFilePlan(t), image, LaunchParams{
|
||||
Execution: "exec-42", ProxyToken: "tok", CAPath: "/etc/archie/ca.pem",
|
||||
Bound: map[string]egress.CredentialKind{"claude-code": egress.CredentialOAuth}, OAuth: map[string]OAuthFacts{"claude-code": {ExpiresAt: expires}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, ok := findFile(l.Files, "/home/agent/.claude/.credentials.json")
|
||||
if !ok {
|
||||
t.Fatalf("no credential file at the declared path; files = %v", l.Files)
|
||||
}
|
||||
var doc struct {
|
||||
ClaudeAiOauth struct {
|
||||
ExpiresAt int64 `json:"expiresAt"`
|
||||
} `json:"claudeAiOauth"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(f.Content), &doc); err != nil {
|
||||
t.Fatalf("credential file is not JSON: %v\n%s", err, f.Content)
|
||||
}
|
||||
if doc.ClaudeAiOauth.ExpiresAt != expires.UnixMilli() {
|
||||
t.Errorf("expiresAt = %d, want the stored expiry %d", doc.ClaudeAiOauth.ExpiresAt, expires.UnixMilli())
|
||||
}
|
||||
}
|
||||
|
||||
// TestAssembleRendersATOMLCredentialFile covers the non-default encoding the
|
||||
// spec provides for agents that read TOML credentials files.
|
||||
func TestAssembleRendersATOMLCredentialFile(t *testing.T) {
|
||||
const tomlKit = sessions + `
|
||||
- type: com.docker.sandbox/credential@1
|
||||
config:
|
||||
service: example
|
||||
phase: runtime
|
||||
oauth:
|
||||
tokenEndpoint: {host: auth.example.com}
|
||||
sentinels: {accessToken: sentinel-access, refreshToken: sentinel-refresh}
|
||||
credentialFile:
|
||||
path: /home/agent/credentials.toml
|
||||
format: toml
|
||||
structure:
|
||||
api_url: "https://api.example.com"
|
||||
tokens:
|
||||
access_token: "{{.AccessToken}}"
|
||||
refresh_token: "{{.RefreshToken}}"`
|
||||
p, err := Admit(descriptor(t, spec.KindWorkload, tomlKit))
|
||||
if err != nil {
|
||||
t.Fatalf("admit: %v", err)
|
||||
}
|
||||
l, err := Assemble(p, image, LaunchParams{Execution: "exec-42", Bound: map[string]egress.CredentialKind{"example": egress.CredentialOAuth}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, ok := findFile(l.Files, "/home/agent/credentials.toml")
|
||||
if !ok {
|
||||
t.Fatalf("no credential file at the declared path; files = %v", l.Files)
|
||||
}
|
||||
var doc struct {
|
||||
APIURL string `toml:"api_url"`
|
||||
Tokens struct {
|
||||
AccessToken string `toml:"access_token"`
|
||||
RefreshToken string `toml:"refresh_token"`
|
||||
} `toml:"tokens"`
|
||||
}
|
||||
if _, err := toml.Decode(f.Content, &doc); err != nil {
|
||||
t.Fatalf("credential file is not TOML: %v\n%s", err, f.Content)
|
||||
}
|
||||
if doc.Tokens.AccessToken != "sentinel-access" || doc.Tokens.RefreshToken != "sentinel-refresh" {
|
||||
t.Errorf("tokens = %+v, want the sentinels", doc.Tokens)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAssembleRefusesAPlaceholderItCannotRender: a placeholder archie does
|
||||
// not supply must refuse the launch rather than leave the literal standing in
|
||||
// the file, which the CLI would read as a credential.
|
||||
func TestAssembleRefusesAPlaceholderItCannotRender(t *testing.T) {
|
||||
const unknownKit = sessions + `
|
||||
- type: com.docker.sandbox/credential@1
|
||||
config:
|
||||
service: example
|
||||
phase: runtime
|
||||
oauth:
|
||||
tokenEndpoint: {host: auth.example.com}
|
||||
sentinels: {accessToken: sentinel-access}
|
||||
credentialFile:
|
||||
path: /home/agent/credentials.json
|
||||
structure:
|
||||
mystery: "{{.NotAPlaceholder}}"`
|
||||
p, err := Admit(descriptor(t, spec.KindWorkload, unknownKit))
|
||||
if err != nil {
|
||||
t.Fatalf("admit: %v", err)
|
||||
}
|
||||
_, err = Assemble(p, image, LaunchParams{Execution: "exec-42", Bound: map[string]egress.CredentialKind{"example": egress.CredentialOAuth}})
|
||||
if err == nil || !strings.Contains(err.Error(), "{{.NotAPlaceholder}}") {
|
||||
t.Fatalf("Assemble = %v, want a refusal naming {{.NotAPlaceholder}}", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAssembleRefusesAMissingSentinel: a token placeholder with no declared
|
||||
// sentinel cannot be hidden, so the file must not be written at all.
|
||||
func TestAssembleRefusesAMissingSentinel(t *testing.T) {
|
||||
const noSentinelKit = sessions + `
|
||||
- type: com.docker.sandbox/credential@1
|
||||
config:
|
||||
service: example
|
||||
phase: runtime
|
||||
oauth:
|
||||
tokenEndpoint: {host: auth.example.com}
|
||||
credentialFile:
|
||||
path: /home/agent/credentials.json
|
||||
structure:
|
||||
access_token: "{{.AccessToken}}"`
|
||||
p, err := Admit(descriptor(t, spec.KindWorkload, noSentinelKit))
|
||||
if err != nil {
|
||||
t.Fatalf("admit: %v", err)
|
||||
}
|
||||
_, err = Assemble(p, image, LaunchParams{Execution: "exec-42", Bound: map[string]egress.CredentialKind{"example": egress.CredentialOAuth}})
|
||||
if err == nil || !strings.Contains(err.Error(), "access-token sentinel") {
|
||||
t.Fatalf("Assemble = %v, want a refusal naming the missing access-token sentinel", err)
|
||||
}
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
package kit
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/docker/sandbox-kit-spec/v3/spec"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/egress"
|
||||
)
|
||||
|
||||
// claudeCodeCredentialFileKit mirrors the published Claude Code Kit's
|
||||
// credentialFile: the OAuth fields nested, the granted scopes among them, and
|
||||
// a top-level primaryApiKey.
|
||||
const claudeCodeCredentialFileKit = sessions + `
|
||||
- type: com.docker.sandbox/credential@1
|
||||
config:
|
||||
service: claude-code
|
||||
phase: runtime
|
||||
oauth:
|
||||
tokenEndpoint: {host: platform.claude.com, path: /v1/oauth/token}
|
||||
sentinels:
|
||||
accessToken: sk-ant-oat01-proxy-managed
|
||||
refreshToken: sk-ant-ort01-proxy-managed
|
||||
credentialFile:
|
||||
path: /home/agent/.claude/.credentials.json
|
||||
structure:
|
||||
claudeAiOauth:
|
||||
accessToken: "{{.AccessToken}}"
|
||||
refreshToken: "{{.RefreshToken}}"
|
||||
expiresAt: "{{.ExpiresAt}}"
|
||||
scopes: "{{.Scopes}}"
|
||||
primaryApiKey: "{{.PrimaryApiKey}}"`
|
||||
|
||||
// renderClaudeCredentialFile assembles the Claude-shaped Kit with facts and
|
||||
// returns the credential file's decoded top level.
|
||||
func renderClaudeCredentialFile(t *testing.T, facts OAuthFacts) map[string]any {
|
||||
t.Helper()
|
||||
p, err := Admit(descriptor(t, spec.KindWorkload, claudeCodeCredentialFileKit))
|
||||
if err != nil {
|
||||
t.Fatalf("admit: %v", err)
|
||||
}
|
||||
l, err := Assemble(p, image, LaunchParams{
|
||||
Execution: "exec-42", Bound: map[string]egress.CredentialKind{"claude-code": egress.CredentialOAuth},
|
||||
OAuth: map[string]OAuthFacts{"claude-code": facts},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Assemble: %v", err)
|
||||
}
|
||||
f, ok := findFile(l.Files, "/home/agent/.claude/.credentials.json")
|
||||
if !ok {
|
||||
t.Fatalf("no credential file at the declared path; files = %v", l.Files)
|
||||
}
|
||||
var doc map[string]any
|
||||
if err := json.Unmarshal([]byte(f.Content), &doc); err != nil {
|
||||
t.Fatalf("credential file is not JSON: %v\n%s", err, f.Content)
|
||||
}
|
||||
return doc
|
||||
}
|
||||
|
||||
// TestAssembleRendersTheGrantedScopes: {{.Scopes}} is an array in the target
|
||||
// encoding, so a one-element set must still be a one-element ARRAY and never
|
||||
// collapse to a bare string -- the single and multi cases differ exactly
|
||||
// there, and nowhere else.
|
||||
func TestAssembleRendersTheGrantedScopes(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
scopes []string
|
||||
}{
|
||||
{name: "a single granted scope is a one-element array", scopes: []string{"user:inference"}},
|
||||
{name: "several granted scopes are a multi-element array", scopes: []string{"user:inference", "user:profile"}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
doc := renderClaudeCredentialFile(t, OAuthFacts{Scopes: tt.scopes})
|
||||
oauth, _ := doc["claudeAiOauth"].(map[string]any)
|
||||
if oauth == nil {
|
||||
t.Fatalf("claudeAiOauth = %v, want an object", doc["claudeAiOauth"])
|
||||
}
|
||||
raw, ok := oauth["scopes"].([]any)
|
||||
if !ok {
|
||||
t.Fatalf("scopes = %#v (%T), want a JSON array", oauth["scopes"], oauth["scopes"])
|
||||
}
|
||||
if len(raw) != len(tt.scopes) {
|
||||
t.Fatalf("scopes = %v, want %v", raw, tt.scopes)
|
||||
}
|
||||
for i, want := range tt.scopes {
|
||||
if raw[i] != want {
|
||||
t.Fatalf("scopes[%d] = %v, want %q", i, raw[i], want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAssembleRefusesWhenNoScopesWereCaptured: the spec declares no omission
|
||||
// case for {{.Scopes}}, so a token set with no scopes refuses the launch with
|
||||
// something the operator can act on rather than writing an empty array, which
|
||||
// would silently change the CLI's capability decisions.
|
||||
func TestAssembleRefusesWhenNoScopesWereCaptured(t *testing.T) {
|
||||
p, err := Admit(descriptor(t, spec.KindWorkload, claudeCodeCredentialFileKit))
|
||||
if err != nil {
|
||||
t.Fatalf("admit: %v", err)
|
||||
}
|
||||
_, err = Assemble(p, image, LaunchParams{
|
||||
Execution: "exec-42", Bound: map[string]egress.CredentialKind{"claude-code": egress.CredentialOAuth},
|
||||
OAuth: map[string]OAuthFacts{"claude-code": {}},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("Assemble with no captured scopes = nil error, want a refusal")
|
||||
}
|
||||
for _, want := range []string{"{{.Scopes}}", "setup terminal"} {
|
||||
if !strings.Contains(err.Error(), want) {
|
||||
t.Fatalf("Assemble error = %q, want it to name %q", err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestAssembleOmitsAnUncapturedPrimaryApiKey: the spec's case for
|
||||
// {{.PrimaryApiKey}} is that its enclosing key is omitted when no key is
|
||||
// captured. archie never hands the container a key -- it resolves one only to
|
||||
// fill the egress grant -- so the key must be ABSENT; absent and empty are
|
||||
// different bugs.
|
||||
func TestAssembleOmitsAnUncapturedPrimaryApiKey(t *testing.T) {
|
||||
doc := renderClaudeCredentialFile(t, OAuthFacts{Scopes: []string{"user:inference"}})
|
||||
if v, present := doc["primaryApiKey"]; present {
|
||||
t.Fatalf("primaryApiKey = %#v, want the key omitted entirely", v)
|
||||
}
|
||||
if _, ok := doc["claudeAiOauth"]; !ok {
|
||||
t.Fatalf("claudeAiOauth missing alongside primaryApiKey: %v", doc)
|
||||
}
|
||||
}
|
||||
@@ -1,278 +0,0 @@
|
||||
package kit
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/docker/sandbox-kit-spec/v3/spec"
|
||||
)
|
||||
|
||||
const sessions = `
|
||||
- type: com.docker.sandbox/agent-sessions@1
|
||||
config:
|
||||
prompt: [-p, "{{.Prompt}}"]
|
||||
resume: [--resume, "{{.SessionID}}"]`
|
||||
|
||||
func descriptor(t *testing.T, kind, capabilities string) *spec.Descriptor {
|
||||
t.Helper()
|
||||
d, err := spec.Decode([]byte("schemaVersion: \"3\"\nkind: " + kind + "\ncapabilities:" + capabilities + "\n"))
|
||||
if err != nil {
|
||||
t.Fatalf("fixture does not decode: %v", err)
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
func refusedTypes(t *testing.T, err error) []string {
|
||||
t.Helper()
|
||||
var refused *RefusedError
|
||||
if !errors.As(err, &refused) {
|
||||
t.Fatalf("want *RefusedError, got %v", err)
|
||||
}
|
||||
var types []string
|
||||
for _, r := range refused.Refusals {
|
||||
types = append(types, r.Type)
|
||||
}
|
||||
return types
|
||||
}
|
||||
|
||||
func TestAdmit(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
capabilities string
|
||||
wantRefused []string
|
||||
wantSkipped []string
|
||||
wantAdmitted int
|
||||
}{
|
||||
{
|
||||
name: "every supported type is admitted",
|
||||
capabilities: sessions + `
|
||||
- type: com.docker.sandbox/network-policy@1
|
||||
config: {runtime: {allow: [api.example.com:443]}}
|
||||
- type: com.docker.sandbox/credential@1
|
||||
config:
|
||||
service: example
|
||||
phase: runtime
|
||||
apiKey: {name: EXAMPLE_KEY, proxyManaged: true, inject: [{domain: api.example.com, header: Authorization, format: "Bearer %s"}]}
|
||||
- type: com.docker.sandbox/volume@1
|
||||
config: {path: /home/agent/.state, size: 1g}
|
||||
- type: com.docker.sandbox/lifecycle@1
|
||||
config: {startup: [{command: [true]}]}
|
||||
- type: com.docker.sandbox/agent-skills@1
|
||||
config: {path: /home/agent/.skills}
|
||||
- type: com.docker.sandbox/agent-context@1
|
||||
config: {content: be terse}
|
||||
- type: com.docker.sandbox/resources@1
|
||||
config: {memory: 2g}`,
|
||||
wantAdmitted: 8,
|
||||
},
|
||||
{
|
||||
name: "a required unsupported type refuses the launch",
|
||||
capabilities: sessions + "\n - type: com.docker.sandbox/privileged@1",
|
||||
wantRefused: []string{"com.docker.sandbox/privileged@1"},
|
||||
},
|
||||
{
|
||||
name: "an optional unsupported type is skipped and recorded",
|
||||
capabilities: sessions + `
|
||||
- type: com.docker.sandbox/port@1
|
||||
optional: true
|
||||
config: {port: 8080}`,
|
||||
wantSkipped: []string{"com.docker.sandbox/port@1"},
|
||||
wantAdmitted: 1,
|
||||
},
|
||||
{
|
||||
name: "network-policy@2 is refused",
|
||||
capabilities: sessions + `
|
||||
- type: com.docker.sandbox/network-policy@2
|
||||
config: {runtime: {allow: [api.example.com]}}`,
|
||||
wantRefused: []string{"com.docker.sandbox/network-policy@2"},
|
||||
},
|
||||
{
|
||||
name: "a host-specific type archie does not know is refused",
|
||||
capabilities: sessions + `
|
||||
- type: example.com/gpu-broker@1
|
||||
config: {pool: a}`,
|
||||
wantRefused: []string{"example.com/gpu-broker@1"},
|
||||
},
|
||||
{
|
||||
name: "a credential with passthrough is refused",
|
||||
capabilities: sessions + `
|
||||
- type: com.docker.sandbox/network-policy@1
|
||||
config: {runtime: {allow: [api.example.com]}}
|
||||
- type: com.docker.sandbox/credential@1
|
||||
config:
|
||||
service: example
|
||||
phase: runtime
|
||||
oauth: {tokenEndpoint: {host: api.example.com}, passthrough: true}`,
|
||||
wantRefused: []string{"com.docker.sandbox/credential@1"},
|
||||
},
|
||||
{
|
||||
name: "an optional forge credential is skipped, never bound",
|
||||
capabilities: sessions + `
|
||||
- type: com.docker.sandbox/network-policy@1
|
||||
config: {runtime: {allow: [api.github.com]}}
|
||||
- type: com.docker.sandbox/credential@1
|
||||
optional: true
|
||||
config:
|
||||
service: github
|
||||
phase: runtime
|
||||
apiKey: {name: GH_TOKEN, proxyManaged: true, inject: [{domain: api.github.com, header: Authorization, format: "Bearer %s"}]}`,
|
||||
wantSkipped: []string{"com.docker.sandbox/credential@1"},
|
||||
wantAdmitted: 2,
|
||||
},
|
||||
{
|
||||
name: "every refusal is reported, not only the first",
|
||||
capabilities: sessions + `
|
||||
- type: com.docker.sandbox/privileged@1
|
||||
- type: com.docker.sandbox/long-running@1`,
|
||||
wantRefused: []string{"com.docker.sandbox/privileged@1", "com.docker.sandbox/long-running@1"},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
plan, err := Admit(descriptor(t, spec.KindWorkload, tt.capabilities))
|
||||
if tt.wantRefused != nil {
|
||||
if got := refusedTypes(t, err); !slices.Equal(got, tt.wantRefused) {
|
||||
t.Fatalf("refused %v, want %v", got, tt.wantRefused)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("Admit: %v", err)
|
||||
}
|
||||
var skipped []string
|
||||
for _, s := range plan.Skipped {
|
||||
skipped = append(skipped, s.Type)
|
||||
}
|
||||
if !slices.Equal(skipped, tt.wantSkipped) {
|
||||
t.Fatalf("skipped %v, want %v", skipped, tt.wantSkipped)
|
||||
}
|
||||
if len(plan.Capabilities) != tt.wantAdmitted {
|
||||
t.Fatalf("admitted %d capabilities, want %d", len(plan.Capabilities), tt.wantAdmitted)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefusalNamesTheCapability(t *testing.T) {
|
||||
_, err := Admit(descriptor(t, spec.KindWorkload, sessions+"\n - type: com.docker.sandbox/usb-device@1\n config: {class: hid}"))
|
||||
if err == nil || !strings.Contains(err.Error(), "com.docker.sandbox/usb-device@1") {
|
||||
t.Fatalf("error %v does not name the refused capability", err)
|
||||
}
|
||||
}
|
||||
|
||||
// admit reads one Kit the way the launcher does: merged alone, then admitted.
|
||||
func admit(t *testing.T, c spec.Contribution) (*Plan, error) {
|
||||
t.Helper()
|
||||
merged, err := spec.Merge([]spec.Contribution{c}, MergeOptions)
|
||||
if err != nil {
|
||||
t.Fatalf("Merge: %v", err)
|
||||
}
|
||||
return FromMerge(merged)
|
||||
}
|
||||
|
||||
func TestFromMerge(t *testing.T) {
|
||||
workload := spec.Contribution{Reference: "workload", Descriptor: descriptor(t, spec.KindWorkload, sessions)}
|
||||
mixin := spec.Contribution{Reference: "mixin", Descriptor: descriptor(t, spec.KindMixin, `
|
||||
- type: com.docker.sandbox/network-policy@1
|
||||
config: {runtime: {allow: [api.example.com]}}`)}
|
||||
bareWorkload := spec.Contribution{Reference: "bare", Descriptor: descriptor(t, spec.KindWorkload, `
|
||||
- type: com.docker.sandbox/resources@1
|
||||
config: {memory: 1g}`)}
|
||||
|
||||
plan, err := admit(t, workload)
|
||||
if err != nil || plan.Sessions == nil || len(plan.Sessions.Prompt) == 0 {
|
||||
t.Fatalf("admit(workload) = %+v, %v; want a plan with a headless prompt verb", plan, err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
kit spec.Contribution
|
||||
want string
|
||||
}{
|
||||
{"a bare mixin", mixin, "publish a Kit set"},
|
||||
{"no headless prompt verb", bareWorkload, "agent-sessions"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name+" is refused", func(t *testing.T) {
|
||||
_, err := admit(t, tt.kit)
|
||||
if err == nil || !strings.Contains(err.Error(), tt.want) {
|
||||
t.Fatalf("error %v, want one mentioning %q", err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateNeeds pins the harness PRD's "a gate retry without a resume
|
||||
// verb" refusal (Contract): archie resumes the harness's own session with the
|
||||
// gate's output rather than starting a fresh one, so a gated stage's retry
|
||||
// budget is unmeetable by a Kit whose agent-sessions capability names no
|
||||
// resume verb.
|
||||
func TestValidateNeeds(t *testing.T) {
|
||||
promptOnly := descriptor(t, spec.KindWorkload, `
|
||||
- type: com.docker.sandbox/agent-sessions@1
|
||||
config:
|
||||
prompt: [-p, "{{.Prompt}}"]`)
|
||||
withResume := descriptor(t, spec.KindWorkload, sessions)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
descriptor *spec.Descriptor
|
||||
gateRetries int
|
||||
wantErr bool
|
||||
}{
|
||||
{"no gated stage, no resume verb", promptOnly, 0, false},
|
||||
{"gated stage, no resume verb", promptOnly, 2, true},
|
||||
{"gated stage, a resume verb", withResume, 2, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
plan, err := Admit(tt.descriptor)
|
||||
if err != nil {
|
||||
t.Fatalf("Admit: %v", err)
|
||||
}
|
||||
sessions, err := spec.AgentSessionsOf(plan.Capabilities)
|
||||
if err != nil {
|
||||
t.Fatalf("AgentSessionsOf: %v", err)
|
||||
}
|
||||
plan.Sessions = sessions
|
||||
|
||||
err = ValidateNeeds(plan, tt.gateRetries)
|
||||
if tt.wantErr && err == nil {
|
||||
t.Fatal("ValidateNeeds accepted a gate retry budget the kit cannot resume")
|
||||
}
|
||||
if !tt.wantErr && err != nil {
|
||||
t.Fatalf("ValidateNeeds: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodePublished(t *testing.T) {
|
||||
published := "schemaVersion: \"3\"\nkind: workload\ncapabilities:" + sessions + "\n"
|
||||
tests := []struct {
|
||||
name string
|
||||
annotations map[string]string
|
||||
wantErr string
|
||||
}{
|
||||
{"a published descriptor decodes", map[string]string{spec.AnnotationDescriptor: published}, ""},
|
||||
{"an image without the annotation is not a kit", map[string]string{"org.opencontainers.image.title": "x"}, "not a kit"},
|
||||
{"an unknown field is an error", map[string]string{spec.AnnotationDescriptor: published + "surprise: true\n"}, "surprise"},
|
||||
{"an unexpanded build arg is not a published form", map[string]string{spec.AnnotationDescriptor: "schemaVersion: \"3\"\nkind: workload\nversion: \"${{ kit.args.version }}\"\n"}, "version"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
d, err := DecodePublished(tt.annotations)
|
||||
if tt.wantErr == "" {
|
||||
if err != nil || d == nil {
|
||||
t.Fatalf("DecodePublished: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Fatalf("error %v, want one mentioning %q", err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,222 +0,0 @@
|
||||
package kit
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/docker/sandbox-kit-spec/v3/spec"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/egress"
|
||||
)
|
||||
|
||||
const launchKit = `
|
||||
- type: com.docker.sandbox/agent-sessions@1
|
||||
config:
|
||||
prompt: [-p, "{{.Prompt}}"]
|
||||
resume: [--resume, "{{.SessionID}}"]
|
||||
- type: com.docker.sandbox/network-policy@1
|
||||
config: {install: {allow: [registry.example.com]}, runtime: {allow: [api.example.com]}}
|
||||
- type: com.docker.sandbox/credential@1
|
||||
config:
|
||||
service: example
|
||||
phase: runtime
|
||||
apiKey: {name: EXAMPLE_KEY, proxyManaged: true, inject: [{domain: api.example.com, header: x-api-key, format: "%s"}]}
|
||||
- type: com.docker.sandbox/volume@1
|
||||
config: {path: /home/agent/.cli/sessions, size: 1g}
|
||||
- type: com.docker.sandbox/volume@1
|
||||
config: {path: /home/agent/.cli/history}
|
||||
- type: com.docker.sandbox/lifecycle@1
|
||||
config:
|
||||
install:
|
||||
- command: echo "$WORKSPACE_DIR" > /etc/seeded
|
||||
env: [WORKSPACE_DIR]
|
||||
startup:
|
||||
- command: [cli, warm-up]
|
||||
env: [SBX_CRED_EXAMPLE_MODE, NOT_A_RUNTIME_VARIABLE]
|
||||
- command: [cli, daemon]
|
||||
user: "0"
|
||||
background: true`
|
||||
|
||||
func plan(t *testing.T) *Plan {
|
||||
t.Helper()
|
||||
p, err := admit(t, spec.Contribution{Reference: "kit", Descriptor: descriptor(t, spec.KindWorkload, launchKit)})
|
||||
if err != nil {
|
||||
t.Fatalf("admit: %v", err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
var image = ImageConfig{
|
||||
Entrypoint: []string{"/usr/local/bin/cli"},
|
||||
Cmd: []string{"--no-color"},
|
||||
Env: []string{"PATH=/usr/local/bin:/usr/bin:/bin", "HOME=/home/agent", "IMAGE_ONLY=kept"},
|
||||
User: "agent",
|
||||
}
|
||||
|
||||
var params = LaunchParams{Execution: "exec-42", ProxyToken: "tok", CAPath: "/etc/archie/ca.pem", Bound: map[string]egress.CredentialKind{"example": egress.CredentialAPIKey}}
|
||||
|
||||
func TestAssembleHarness(t *testing.T) {
|
||||
l, err := Assemble(plan(t), image, params)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := l.Harness
|
||||
if !slices.Equal(h.Launch, []string{"/usr/local/bin/cli", "--no-color"}) {
|
||||
t.Errorf("launch %v, want the image entrypoint then cmd", h.Launch)
|
||||
}
|
||||
if !slices.Equal(h.Prompt, []string{"-p", "{{.Prompt}}"}) || !slices.Equal(h.Resume, []string{"--resume", "{{.SessionID}}"}) {
|
||||
t.Errorf("verbs prompt=%v resume=%v, want the Kit's agent-sessions verbs", h.Prompt, h.Resume)
|
||||
}
|
||||
if h.User != "agent" {
|
||||
t.Errorf("user %q, want the image's user", h.User)
|
||||
}
|
||||
for _, want := range []string{
|
||||
"PATH=/usr/local/bin:/usr/bin:/bin", "IMAGE_ONLY=kept",
|
||||
"WORKSPACE_DIR=" + WorkspaceDir,
|
||||
"HTTPS_PROXY=http://archie:tok@archie-egress:3128",
|
||||
"SSL_CERT_FILE=/etc/archie/ca.pem",
|
||||
"EXAMPLE_KEY=archie-proxy-managed",
|
||||
} {
|
||||
if !slices.Contains(h.Env, want) {
|
||||
t.Errorf("harness env lacks %q:\n%s", want, strings.Join(h.Env, "\n"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssembleNeverRunsTheHarnessAsRoot(t *testing.T) {
|
||||
for _, user := range []string{"", "root", "0", "0:0"} {
|
||||
img := image
|
||||
img.User = user
|
||||
l, err := Assemble(plan(t), img, params)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if l.Harness.User != DefaultHarnessUser {
|
||||
t.Errorf("image user %q gave harness user %q, want %q", user, l.Harness.User, DefaultHarnessUser)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssembleHooks(t *testing.T) {
|
||||
l, err := Assemble(plan(t), image, params)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(l.Install) != 1 || len(l.Startup) != 2 {
|
||||
t.Fatalf("install %d startup %d, want 1 and 2", len(l.Install), len(l.Startup))
|
||||
}
|
||||
install := l.Install[0]
|
||||
if !slices.Equal(install.Argv, []string{"sh", "-c", `echo "$WORKSPACE_DIR" > /etc/seeded`}) {
|
||||
t.Errorf("a string command runs through the shell, as the Kit spec decodes it; got %v", install.Argv)
|
||||
}
|
||||
if install.User != "0" {
|
||||
t.Errorf("install hook user %q, want root by default", install.User)
|
||||
}
|
||||
if !slices.Contains(install.Env, "WORKSPACE_DIR="+WorkspaceDir) || !slices.Contains(install.Env, "HTTPS_PROXY=http://archie:tok@archie-egress:3128") {
|
||||
t.Errorf("install env %v, want its declared variable and the egress baseline", install.Env)
|
||||
}
|
||||
warm := l.Startup[0]
|
||||
if warm.User != DefaultHarnessUser {
|
||||
t.Errorf("startup hook user %q, want the agent user by default", warm.User)
|
||||
}
|
||||
if !slices.Contains(warm.Env, "SBX_CRED_EXAMPLE_MODE=apikey") {
|
||||
t.Errorf("startup env %v, want the bound credential's mode", warm.Env)
|
||||
}
|
||||
for _, e := range warm.Env {
|
||||
if strings.HasPrefix(e, "NOT_A_RUNTIME_VARIABLE=") || strings.HasPrefix(e, "IMAGE_ONLY=") || strings.HasPrefix(e, "EXAMPLE_KEY=") {
|
||||
t.Errorf("startup env carries %q, which it neither declared nor is baseline", e)
|
||||
}
|
||||
}
|
||||
if daemon := l.Startup[1]; daemon.User != "0" || !daemon.Background {
|
||||
t.Errorf("startup hook %+v, want its declared root user and background flag", daemon)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssembleVolumesArePerExecution(t *testing.T) {
|
||||
a, err := Assemble(plan(t), image, params)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
again, _ := Assemble(plan(t), image, params)
|
||||
other := params
|
||||
other.Execution = "exec-43"
|
||||
b, _ := Assemble(plan(t), image, other)
|
||||
if len(a.Volumes) != 2 {
|
||||
t.Fatalf("volumes %v, want 2", a.Volumes)
|
||||
}
|
||||
if !slices.Equal(a.Volumes, again.Volumes) {
|
||||
t.Error("volume names are not stable for one execution; a retry would lose its sessions")
|
||||
}
|
||||
if a.Volumes[0].Name == a.Volumes[1].Name {
|
||||
t.Error("two paths share a volume")
|
||||
}
|
||||
for i := range a.Volumes {
|
||||
if a.Volumes[i].Name == b.Volumes[i].Name {
|
||||
t.Errorf("executions share volume %q", a.Volumes[i].Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssembleAgentContextProfile(t *testing.T) {
|
||||
assemble := func(t *testing.T, contextYAML string) Launch {
|
||||
t.Helper()
|
||||
p, err := admit(t, spec.Contribution{Reference: "registry/team-set@sha256:ab", Descriptor: descriptor(t, spec.KindWorkload, sessions+contextYAML)})
|
||||
if err != nil {
|
||||
t.Fatalf("admit: %v", err)
|
||||
}
|
||||
l, err := Assemble(p, image, LaunchParams{Execution: "exec-1"})
|
||||
if err != nil {
|
||||
t.Fatalf("Assemble: %v", err)
|
||||
}
|
||||
return l
|
||||
}
|
||||
byPath := func(files []spec.File) map[string]string {
|
||||
out := map[string]string{}
|
||||
for _, f := range files {
|
||||
out[f.Path] = f.Content
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
t.Run("a staged body is indexed where the image holds it", func(t *testing.T) {
|
||||
files := byPath(assemble(t, `
|
||||
- type: com.docker.sandbox/agent-context@1
|
||||
config: {filename: CLAUDE.md, contentFile: /usr/share/sandbox/kit/team/context.md}`).Context)
|
||||
profile, ok := files["/archie/CLAUDE.md"]
|
||||
if !ok || len(files) != 1 {
|
||||
t.Fatalf("context files = %v, want only the profile beside the workspace", files)
|
||||
}
|
||||
if !strings.Contains(profile, "registry/team-set@sha256:ab") || !strings.Contains(profile, "/usr/share/sandbox/kit/team/context.md") {
|
||||
t.Fatalf("profile does not index the Kit's staged body:\n%s", profile)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an inline body gets its own file the profile points at", func(t *testing.T) {
|
||||
files := byPath(assemble(t, `
|
||||
- type: com.docker.sandbox/agent-context@1
|
||||
config: {filename: AGENTS.md, content: "Use motd."}`).Context)
|
||||
profile := files["/archie/AGENTS.md"]
|
||||
var body string
|
||||
for path, content := range files {
|
||||
if path != "/archie/AGENTS.md" {
|
||||
body = path
|
||||
if content != "Use motd." {
|
||||
t.Fatalf("%s = %q, want the inline body", path, content)
|
||||
}
|
||||
}
|
||||
}
|
||||
if body == "" || strings.HasPrefix(body, WorkspaceDir+"/") || !strings.Contains(profile, body) {
|
||||
t.Fatalf("files %v: want the inline body outside the workspace and indexed by the profile", files)
|
||||
}
|
||||
if strings.Contains(profile, "Use motd.") {
|
||||
t.Fatal("the profile inlines a Kit's body; it must only point at it")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("no profile filename materializes nothing", func(t *testing.T) {
|
||||
if files := assemble(t, "").Context; len(files) != 0 {
|
||||
t.Fatalf("context files = %v, want none", files)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
package kitrun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/docker/sandbox-kit-spec/v3/spec"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/harnesssecret"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/egress"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/kit"
|
||||
)
|
||||
|
||||
type fakeOAuthSecrets struct {
|
||||
secret harnesssecret.Secret
|
||||
err error
|
||||
}
|
||||
|
||||
func (f fakeOAuthSecrets) GetHarnessSecret(context.Context, string, string) (harnesssecret.Secret, error) {
|
||||
if f.err != nil {
|
||||
return harnesssecret.Secret{}, f.err
|
||||
}
|
||||
return f.secret, nil
|
||||
}
|
||||
|
||||
const credentialFileKit = `
|
||||
schemaVersion: "3"
|
||||
kind: workload
|
||||
capabilities:
|
||||
- type: com.docker.sandbox/agent-sessions@1
|
||||
config: {prompt: [-p, "{{.Prompt}}"]}
|
||||
- type: com.docker.sandbox/credential@1
|
||||
config:
|
||||
service: claude-code
|
||||
phase: runtime
|
||||
oauth:
|
||||
tokenEndpoint: {host: platform.claude.com, path: /v1/oauth/token}
|
||||
sentinels:
|
||||
accessToken: sk-ant-oat01-proxy-managed
|
||||
refreshToken: sk-ant-ort01-proxy-managed
|
||||
credentialFile:
|
||||
path: /home/agent/.claude/.credentials.json
|
||||
structure:
|
||||
claudeAiOauth:
|
||||
accessToken: "{{.AccessToken}}"
|
||||
refreshToken: "{{.RefreshToken}}"
|
||||
expiresAt: "{{.ExpiresAt}}"
|
||||
`
|
||||
|
||||
func credentialFilePlan(t *testing.T) *kit.Plan {
|
||||
t.Helper()
|
||||
d, err := spec.Decode([]byte(credentialFileKit))
|
||||
if err != nil {
|
||||
t.Fatalf("fixture does not decode: %v", err)
|
||||
}
|
||||
p, err := kit.Admit(d)
|
||||
if err != nil {
|
||||
t.Fatalf("admit: %v", err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func planCredentials(t *testing.T, p *kit.Plan) []spec.CredentialCapability {
|
||||
t.Helper()
|
||||
creds, err := spec.CredentialsOf(p.Capabilities)
|
||||
if err != nil {
|
||||
t.Fatalf("credentials of plan: %v", err)
|
||||
}
|
||||
return creds
|
||||
}
|
||||
|
||||
// TestCredentialFileNeverCarriesARealToken is the sentinel rule end to end:
|
||||
// the store holds real tokens, kitrun reads the set only for its expiry, and
|
||||
// the assembled credential file holds the Kit's sentinels instead. The store's
|
||||
// real values must not appear anywhere in the rendered file.
|
||||
func TestCredentialFileNeverCarriesARealToken(t *testing.T) {
|
||||
expires := time.UnixMilli(1700000000123)
|
||||
ancestors := []string{"user:inference", "user:profile"}
|
||||
l := &Launcher{OAuth: fakeOAuthSecrets{secret: harnesssecret.Secret{
|
||||
Org: "acme", Service: "claude-code",
|
||||
AccessToken: "real-access-token", RefreshToken: "real-refresh-token",
|
||||
ExpiresAt: expires, Scopes: ancestors,
|
||||
}}}
|
||||
p := credentialFilePlan(t)
|
||||
bound := map[string]egress.CredentialKind{"claude-code": egress.CredentialOAuth}
|
||||
|
||||
facts, err := l.oauthFacts(context.Background(), "acme", planCredentials(t, p), bound)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := facts["claude-code"].ExpiresAt; got != expires {
|
||||
t.Fatalf("oauthFacts[claude-code].ExpiresAt = %v, want the stored expiry %v", got, expires)
|
||||
}
|
||||
if got := facts["claude-code"].Scopes; !slices.Equal(got, ancestors) {
|
||||
t.Fatalf("oauthFacts[claude-code].Scopes = %v, want the stored scopes %v", got, ancestors)
|
||||
}
|
||||
|
||||
launch, err := kit.Assemble(p, kit.ImageConfig{User: "agent"}, kit.LaunchParams{
|
||||
Execution: "exec-1", Bound: bound, OAuth: facts,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var content string
|
||||
for _, f := range launch.Files {
|
||||
if f.Path == "/home/agent/.claude/.credentials.json" {
|
||||
content = f.Content
|
||||
}
|
||||
}
|
||||
if content == "" {
|
||||
t.Fatalf("no credential file rendered; files = %v", launch.Files)
|
||||
}
|
||||
if strings.Contains(content, "real-access-token") || strings.Contains(content, "real-refresh-token") {
|
||||
t.Fatalf("credential file carries a real token: %s", content)
|
||||
}
|
||||
if !strings.Contains(content, "sk-ant-oat01-proxy-managed") || !strings.Contains(content, "sk-ant-ort01-proxy-managed") {
|
||||
t.Fatalf("credential file does not hold the sentinels: %s", content)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOAuthExpiriesFailsClosed: a Kit that renders a credential file cannot be
|
||||
// launched without the stored token set its expiry comes from.
|
||||
func TestOAuthExpiriesFailsClosed(t *testing.T) {
|
||||
p := credentialFilePlan(t)
|
||||
creds := planCredentials(t, p)
|
||||
bound := map[string]egress.CredentialKind{"claude-code": egress.CredentialOAuth}
|
||||
ctx := context.Background()
|
||||
|
||||
if _, err := (&Launcher{}).oauthFacts(ctx, "acme", creds, bound); err == nil {
|
||||
t.Fatal("oauthFacts with no store = nil error, want a refusal")
|
||||
}
|
||||
l := &Launcher{OAuth: fakeOAuthSecrets{err: errors.New("no captured token")}}
|
||||
if _, err := l.oauthFacts(ctx, "acme", creds, bound); err == nil {
|
||||
t.Fatal("oauthFacts with no stored token = nil error, want a refusal")
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package kitrun
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWorkerEnvReachesNATSAndTheStateStoreThroughTheRelay(t *testing.T) {
|
||||
got, err := WorkerEnv(Endpoints{
|
||||
NATS: "nats://172.17.0.1:4222", NATSToken: "nt",
|
||||
StateStore: "10.0.0.5:7443", StateStoreToken: "st",
|
||||
}, 1001, 1002)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []string{
|
||||
"NATS_URL=nats://archie-egress:4222", "NATS_TOKEN=nt",
|
||||
"STATE_STORE_URL=archie-egress:50051", "STATE_STORE_TOKEN=st",
|
||||
"WORKTREE_UID=1001", "WORKTREE_GID=1002",
|
||||
}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("WorkerEnv = %q\nwant %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerEnvWithoutAStateStoreOmitsIt(t *testing.T) {
|
||||
got, err := WorkerEnv(Endpoints{NATS: "tls://nats.internal:4222"}, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !slices.Equal(got, []string{"NATS_URL=tls://archie-egress:4222", "WORKTREE_UID=0", "WORKTREE_GID=0"}) {
|
||||
t.Fatalf("WorkerEnv = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRelayTargets(t *testing.T) {
|
||||
nats, store, err := relayTargets(Endpoints{NATS: "nats://172.17.0.1:4222", StateStore: "dns:///store.lan:7443"})
|
||||
if err != nil || nats != "172.17.0.1:4222" || store != "store.lan:7443" {
|
||||
t.Fatalf("relayTargets = %q, %q, %v", nats, store, err)
|
||||
}
|
||||
if _, _, err := relayTargets(Endpoints{NATS: "nats://a:1,nats://b:2"}); err == nil {
|
||||
t.Fatal("a NATS cluster URL list was accepted; the relay forwards one address")
|
||||
}
|
||||
}
|
||||
@@ -1,243 +0,0 @@
|
||||
package kitrun
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/docker/sandbox-kit-spec/v3/spec"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/egress"
|
||||
)
|
||||
|
||||
var errSecretNotConfigured = errors.New("secret not configured")
|
||||
|
||||
type fakeSecretResolver map[config.SecretRef]string
|
||||
|
||||
func (f fakeSecretResolver) Resolve(ref config.SecretRef) (string, error) {
|
||||
v, ok := f[ref]
|
||||
if !ok {
|
||||
return "", errSecretNotConfigured
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func declaredCred(service string) spec.CredentialCapability {
|
||||
return spec.CredentialCapability{Service: service}
|
||||
}
|
||||
|
||||
func declaredOAuth(service string) spec.CredentialCapability {
|
||||
c := declaredCred(service)
|
||||
c.OAuth = &spec.OAuth{TokenEndpoint: &spec.TokenEndpoint{Host: "auth.example.com"}}
|
||||
return c
|
||||
}
|
||||
|
||||
// TestResolveCredentialsReadsTheLiveConfig is the "reads current, not a boot
|
||||
// snapshot" requirement: two calls against the same Launcher, differing only
|
||||
// in what l.Config now holds, must produce different results. A Launcher
|
||||
// that captured Bindings once at construction (the reverted design) cannot
|
||||
// pass this.
|
||||
func TestResolveCredentialsReadsTheLiveConfig(t *testing.T) {
|
||||
ref := config.SecretRef{Engine: "env", Key: "OPENAI_KEY"}
|
||||
l := &Launcher{
|
||||
Config: config.NewHolder(config.Config{}),
|
||||
Secrets: fakeSecretResolver{ref: "sk-live"},
|
||||
}
|
||||
req := Request{Org: "acme", GrantedServices: []string{"openai"}}
|
||||
creds := []spec.CredentialCapability{declaredCred("openai")}
|
||||
|
||||
granted, kinds := l.resolveCredentials(req, creds)
|
||||
if len(granted) != 0 || len(kinds) != 0 {
|
||||
t.Fatalf("resolveCredentials with no configured binding = (%v, %v), want both empty", granted, kinds)
|
||||
}
|
||||
|
||||
l.Config.Set(config.Config{Containers: config.ContainerConfig{
|
||||
Credentials: []config.CredentialBinding{{Service: "openai", Org: "acme", Secret: ref}},
|
||||
}})
|
||||
|
||||
granted, kinds = l.resolveCredentials(req, creds)
|
||||
if granted["openai"] != "sk-live" || kinds["openai"] != egress.CredentialAPIKey {
|
||||
t.Fatalf("resolveCredentials after the binding was added = (%v, %v), want openai granted as an API key", granted, kinds)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolveCredentialsIsAnIntersection is the isolation proof at the
|
||||
// Launcher boundary: a secret the identity is not granted, or a binding from
|
||||
// another org, is never in the resolved set, however the Kit declares it.
|
||||
func TestResolveCredentialsIsAnIntersection(t *testing.T) {
|
||||
openaiRef := config.SecretRef{Engine: "env", Key: "OPENAI_KEY"}
|
||||
otherRef := config.SecretRef{Engine: "env", Key: "OTHER_KEY"}
|
||||
l := &Launcher{
|
||||
Config: config.NewHolder(config.Config{Containers: config.ContainerConfig{
|
||||
Credentials: []config.CredentialBinding{
|
||||
{Service: "openai", Org: "acme", Secret: openaiRef},
|
||||
{Service: "other-org-svc", Org: "other-org", Secret: otherRef},
|
||||
{Service: "claude-code", Org: "acme"},
|
||||
},
|
||||
}}),
|
||||
Secrets: fakeSecretResolver{openaiRef: "sk-acme", otherRef: "sk-other"},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
req Request
|
||||
creds []spec.CredentialCapability
|
||||
want map[string]string
|
||||
mutated bool
|
||||
}{
|
||||
{
|
||||
name: "declared, granted, matching org resolves",
|
||||
req: Request{Org: "acme", GrantedServices: []string{"openai"}},
|
||||
creds: []spec.CredentialCapability{declaredCred("openai")},
|
||||
want: map[string]string{"openai": "sk-acme"},
|
||||
},
|
||||
{
|
||||
name: "not granted never resolves even though declared and the org matches",
|
||||
req: Request{Org: "acme", GrantedServices: nil},
|
||||
creds: []spec.CredentialCapability{declaredCred("openai")},
|
||||
want: map[string]string{},
|
||||
},
|
||||
{
|
||||
name: "a binding from another org never resolves even when granted",
|
||||
req: Request{Org: "acme", GrantedServices: []string{"other-org-svc"}},
|
||||
creds: []spec.CredentialCapability{declaredCred("other-org-svc")},
|
||||
want: map[string]string{},
|
||||
},
|
||||
{
|
||||
name: "an OAuth service is granted without a config secret",
|
||||
req: Request{Org: "acme", GrantedServices: []string{"claude-code"}},
|
||||
creds: []spec.CredentialCapability{declaredOAuth("claude-code")},
|
||||
want: map[string]string{"claude-code": ""},
|
||||
},
|
||||
{
|
||||
name: "an ungranted OAuth service never resolves",
|
||||
req: Request{Org: "acme", GrantedServices: nil},
|
||||
creds: []spec.CredentialCapability{declaredOAuth("claude-code")},
|
||||
want: map[string]string{},
|
||||
},
|
||||
{
|
||||
name: "not declared by the Kit never resolves even though granted",
|
||||
req: Request{Org: "acme", GrantedServices: []string{"openai"}},
|
||||
creds: nil,
|
||||
want: map[string]string{},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
granted, _ := l.resolveCredentials(tt.req, tt.creds)
|
||||
if len(granted) != len(tt.want) {
|
||||
t.Fatalf("resolveCredentials() = %v, want %v", granted, tt.want)
|
||||
}
|
||||
for service, value := range tt.want {
|
||||
if got, ok := granted[service]; !ok || got != value {
|
||||
t.Fatalf("resolveCredentials()[%q] = %q, want %q", service, granted[service], value)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolveCredentialsTakesTheBoundKindFromTheBinding: the sandbox kit
|
||||
// spec lets one credential@1 declare apiKey and oauth together, meaning
|
||||
// "whichever the host has bound" (the reference docker/claude-code-kit and
|
||||
// codex workloads both do, for anthropic and openai respectively). The org's
|
||||
// binding -- not the Kit's declaration -- therefore decides which one a run
|
||||
// carries, so a binding that names a secret must resolve that secret even
|
||||
// when the Kit also declares OAuth, and a binding that names none must never
|
||||
// resolve to an empty value the proxy would then inject.
|
||||
func TestResolveCredentialsTakesTheBoundKindFromTheBinding(t *testing.T) {
|
||||
keyRef := config.SecretRef{Engine: "env", Key: "ANTHROPIC_API_KEY"}
|
||||
// The registry's documented zero-ref behaviour: resolves to "" with no
|
||||
// error, which is why "no value" cannot be told apart from "no secret"
|
||||
// by the resolved string alone.
|
||||
secrets := fakeSecretResolver{keyRef: "sk-ant-real", config.SecretRef{}: ""}
|
||||
// dual declares apiKey and oauth on one service, the spec's "whichever
|
||||
// the host has bound" shape.
|
||||
dual := func() spec.CredentialCapability {
|
||||
c := declaredOAuth("anthropic")
|
||||
c.APIKey = &spec.APIKey{Name: "ANTHROPIC_API_KEY", ProxyManaged: true}
|
||||
return c
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
bindings []config.CredentialBinding
|
||||
creds []spec.CredentialCapability
|
||||
service string
|
||||
wantValue string
|
||||
wantKind egress.CredentialKind
|
||||
}{
|
||||
{
|
||||
name: "an API-key binding resolves its value for a Kit that also declares OAuth",
|
||||
bindings: []config.CredentialBinding{{Service: "anthropic", Org: "acme", Secret: keyRef}},
|
||||
creds: []spec.CredentialCapability{dual()},
|
||||
service: "anthropic",
|
||||
wantValue: "sk-ant-real",
|
||||
wantKind: egress.CredentialAPIKey,
|
||||
},
|
||||
{
|
||||
name: "a binding with no secret of its own is the OAuth token set",
|
||||
bindings: []config.CredentialBinding{{Service: "anthropic", Org: "acme"}},
|
||||
creds: []spec.CredentialCapability{dual()},
|
||||
service: "anthropic",
|
||||
wantValue: "",
|
||||
wantKind: egress.CredentialOAuth,
|
||||
},
|
||||
{
|
||||
name: "an OAuth-only Kit service with no binding secret is the OAuth token set",
|
||||
bindings: []config.CredentialBinding{{Service: "oauth-only", Org: "acme"}},
|
||||
creds: []spec.CredentialCapability{declaredOAuth("oauth-only")},
|
||||
service: "oauth-only",
|
||||
wantValue: "",
|
||||
wantKind: egress.CredentialOAuth,
|
||||
},
|
||||
{
|
||||
name: "an API-key Kit service with no binding secret stays unbound, never empty",
|
||||
bindings: []config.CredentialBinding{{Service: "api-key-only", Org: "acme"}},
|
||||
creds: []spec.CredentialCapability{declaredCred("api-key-only")},
|
||||
service: "api-key-only",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
l := &Launcher{
|
||||
Config: config.NewHolder(config.Config{Containers: config.ContainerConfig{
|
||||
Credentials: tt.bindings,
|
||||
}}),
|
||||
Secrets: secrets,
|
||||
}
|
||||
granted, kinds := l.resolveCredentials(Request{Org: "acme", GrantedServices: []string{tt.service}}, tt.creds)
|
||||
got, ok := granted[tt.service]
|
||||
if tt.wantKind == "" {
|
||||
if ok {
|
||||
t.Fatalf("resolveCredentials()[%q] = %q, want no credential at all", tt.service, got)
|
||||
}
|
||||
if kind := kinds[tt.service]; kind != "" {
|
||||
t.Fatalf("resolveCredentials() kind[%q] = %q, want unbound", tt.service, kind)
|
||||
}
|
||||
return
|
||||
}
|
||||
if !ok || got != tt.wantValue {
|
||||
t.Fatalf("resolveCredentials()[%q] = %q (present %v), want %q", tt.service, got, ok, tt.wantValue)
|
||||
}
|
||||
if kind := kinds[tt.service]; kind != tt.wantKind {
|
||||
t.Fatalf("resolveCredentials() kind[%q] = %q, want %q", tt.service, kind, tt.wantKind)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The skills store is mounted read-only whatever mode a Kit asks for, and
|
||||
// not at all when the operator configured none.
|
||||
func TestSkillsBinds(t *testing.T) {
|
||||
asks := []spec.AgentSkillsCapability{
|
||||
{Path: "/home/agent/.claude/skills", Mode: "readwrite"},
|
||||
}
|
||||
got := skillsBinds(asks, "/srv/shared")
|
||||
if len(got) != 1 || got[0] != "/srv/shared/.agents/skills:/home/agent/.claude/skills:ro" {
|
||||
t.Fatalf("skillsBinds = %v, want the store mounted read-only at the Kit's path", got)
|
||||
}
|
||||
if got := skillsBinds(asks, ""); len(got) != 0 {
|
||||
t.Fatalf("skillsBinds with no skills_dir = %v, want none", got)
|
||||
}
|
||||
}
|
||||
@@ -1,444 +0,0 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidateSectionName(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
wantErr bool
|
||||
}{
|
||||
{"valid simple", "Facts", false},
|
||||
{"valid with spaces", "User Preferences", false},
|
||||
{"valid alphanumeric", "Section 123", false},
|
||||
{"empty", "", true},
|
||||
{"too long", strings.Repeat("a", 65), true},
|
||||
{"exactly max length", strings.Repeat("a", 64), false},
|
||||
{"invalid punctuation", "Facts!", true},
|
||||
{"invalid hyphen", "my-section", true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := ValidateSectionName(tt.input)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("ValidateSectionName(%q) error = %v, wantErr %v", tt.input, err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func newTestStore(t *testing.T, maxBytes int) *Store {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
s, err := NewStore(filepath.Join(dir, "MEMORY.md"), maxBytes)
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore: %v", err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func TestStore_NewStore_MissingFile(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "MEMORY.md")
|
||||
s, err := NewStore(path, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore: %v", err)
|
||||
}
|
||||
if s.Render() != "" {
|
||||
t.Fatalf("expected empty render for missing file, got %q", s.Render())
|
||||
}
|
||||
if s.MaxBytes() != defaultMaxFileBytes {
|
||||
t.Fatalf("expected default max bytes, got %d", s.MaxBytes())
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Add_CreatesSection(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
|
||||
res, err := s.Add("Facts", "the sky is blue")
|
||||
if err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
if !res.Created {
|
||||
t.Fatalf("expected Created=true for new section")
|
||||
}
|
||||
if res.Section != "Facts" {
|
||||
t.Fatalf("expected section Facts, got %q", res.Section)
|
||||
}
|
||||
|
||||
rendered := s.Render()
|
||||
if !strings.Contains(rendered, "## Facts") {
|
||||
t.Fatalf("expected rendered content to contain header, got %q", rendered)
|
||||
}
|
||||
if !strings.Contains(rendered, "the sky is blue") {
|
||||
t.Fatalf("expected rendered content to contain the entry, got %q", rendered)
|
||||
}
|
||||
|
||||
// Verify the write actually landed on disk.
|
||||
data, err := os.ReadFile(s.Path())
|
||||
if err != nil {
|
||||
t.Fatalf("reading file: %v", err)
|
||||
}
|
||||
if string(data) != rendered {
|
||||
t.Fatalf("disk content does not match in-memory render:\ndisk: %q\nmem: %q", data, rendered)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Add_AppendsToExistingSection(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
|
||||
if _, err := s.Add("Facts", "first entry"); err != nil {
|
||||
t.Fatalf("first Add: %v", err)
|
||||
}
|
||||
res, err := s.Add("Facts", "second entry")
|
||||
if err != nil {
|
||||
t.Fatalf("second Add: %v", err)
|
||||
}
|
||||
if res.Created {
|
||||
t.Fatalf("expected Created=false when appending to existing section")
|
||||
}
|
||||
|
||||
rendered := s.Render()
|
||||
if strings.Count(rendered, "## Facts") != 1 {
|
||||
t.Fatalf("expected exactly one Facts header, got: %q", rendered)
|
||||
}
|
||||
if !strings.Contains(rendered, "first entry") || !strings.Contains(rendered, "second entry") {
|
||||
t.Fatalf("expected both entries present, got %q", rendered)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Add_InvalidSectionName(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
if _, err := s.Add("bad-name!", "content"); err == nil {
|
||||
t.Fatalf("expected error for invalid section name")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Add_EmptyContent(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
if _, err := s.Add("Facts", " "); err == nil {
|
||||
t.Fatalf("expected error for empty content")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Add_RejectsOversizedWrite(t *testing.T) {
|
||||
s := newTestStore(t, 32) // tiny bound
|
||||
|
||||
_, err := s.Add("Facts", strings.Repeat("x", 100))
|
||||
if err == nil {
|
||||
t.Fatalf("expected error when write would exceed max bytes")
|
||||
}
|
||||
if s.Render() != "" {
|
||||
t.Fatalf("expected no mutation on rejected write, got %q", s.Render())
|
||||
}
|
||||
if _, statErr := os.Stat(s.Path()); statErr == nil {
|
||||
t.Fatalf("expected no file to be written on rejected write")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Replace_FindsAndReplaces(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
if _, err := s.Add("Facts", "the sky is blue"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
|
||||
res, err := s.Replace("Facts", "blue", "green", true)
|
||||
if err != nil {
|
||||
t.Fatalf("Replace: %v", err)
|
||||
}
|
||||
if res.CharsRemoved != len("blue") || res.CharsAdded != len("green") {
|
||||
t.Fatalf("unexpected char counts: %+v", res)
|
||||
}
|
||||
|
||||
rendered := s.Render()
|
||||
if !strings.Contains(rendered, "the sky is green") {
|
||||
t.Fatalf("expected replacement applied, got %q", rendered)
|
||||
}
|
||||
if strings.Contains(rendered, "blue") {
|
||||
t.Fatalf("expected original substring gone, got %q", rendered)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Replace_CaseInsensitive(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
if _, err := s.Add("Facts", "The Sky Is Blue"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
|
||||
if _, err := s.Replace("Facts", "sky", "ocean", false); err != nil {
|
||||
t.Fatalf("Replace: %v", err)
|
||||
}
|
||||
rendered := s.Render()
|
||||
if !strings.Contains(rendered, "The ocean Is Blue") {
|
||||
t.Fatalf("expected case-insensitive replacement, got %q", rendered)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Replace_CaseSensitiveMismatchFails(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
if _, err := s.Add("Facts", "The Sky Is Blue"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
if _, err := s.Replace("Facts", "sky", "ocean", true); err == nil {
|
||||
t.Fatalf("expected case-sensitive mismatch to fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Replace_MissingSection(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
if _, err := s.Replace("Nope", "a", "b", true); err == nil {
|
||||
t.Fatalf("expected error for missing section")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Replace_SubstringNotFound(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
if _, err := s.Add("Facts", "the sky is blue"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
if _, err := s.Replace("Facts", "purple", "green", true); err == nil {
|
||||
t.Fatalf("expected error when substring not found")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Replace_FirstOccurrenceOnly(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
if _, err := s.Add("Facts", "cat cat cat"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
if _, err := s.Replace("Facts", "cat", "dog", true); err != nil {
|
||||
t.Fatalf("Replace: %v", err)
|
||||
}
|
||||
rendered := s.Render()
|
||||
if !strings.Contains(rendered, "dog cat cat") {
|
||||
t.Fatalf("expected only first occurrence replaced, got %q", rendered)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Remove_RemovesMatchingBlock(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
if _, err := s.Add("Facts", "entry one"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
if _, err := s.Add("Facts", "entry two"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
|
||||
res, err := s.Remove("Facts", "entry one", true)
|
||||
if err != nil {
|
||||
t.Fatalf("Remove: %v", err)
|
||||
}
|
||||
if res.CharsRemoved != len("entry one") {
|
||||
t.Fatalf("unexpected chars removed: %d", res.CharsRemoved)
|
||||
}
|
||||
|
||||
rendered := s.Render()
|
||||
if strings.Contains(rendered, "entry one") {
|
||||
t.Fatalf("expected entry one removed, got %q", rendered)
|
||||
}
|
||||
if !strings.Contains(rendered, "entry two") {
|
||||
t.Fatalf("expected entry two to remain, got %q", rendered)
|
||||
}
|
||||
// The section header should remain even though a block was removed.
|
||||
if !strings.Contains(rendered, "## Facts") {
|
||||
t.Fatalf("expected section header to remain, got %q", rendered)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Remove_MissingSection(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
if _, err := s.Remove("Nope", "a", true); err == nil {
|
||||
t.Fatalf("expected error for missing section")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Remove_SubstringNotFound(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
if _, err := s.Add("Facts", "entry one"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
if _, err := s.Remove("Facts", "nonexistent", true); err == nil {
|
||||
t.Fatalf("expected error when substring not found")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_PersistsAcrossReload(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "MEMORY.md")
|
||||
|
||||
s1, err := NewStore(path, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore: %v", err)
|
||||
}
|
||||
if _, err := s1.Add("Facts", "persisted entry"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
|
||||
s2, err := NewStore(path, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore reload: %v", err)
|
||||
}
|
||||
if !strings.Contains(s2.Render(), "persisted entry") {
|
||||
t.Fatalf("expected reloaded store to contain persisted entry, got %q", s2.Render())
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Reload_PicksUpExternalChanges(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "MEMORY.md")
|
||||
|
||||
s, err := NewStore(path, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore: %v", err)
|
||||
}
|
||||
if s.Render() != "" {
|
||||
t.Fatalf("expected empty store initially")
|
||||
}
|
||||
|
||||
// Simulate an external write (e.g. a prior process, or manual edit)
|
||||
// happening after construction but before Reload.
|
||||
if err := os.WriteFile(path, []byte("## Facts\n\nexternal entry\n"), 0o644); err != nil {
|
||||
t.Fatalf("writing external content: %v", err)
|
||||
}
|
||||
|
||||
if err := s.Reload(); err != nil {
|
||||
t.Fatalf("Reload: %v", err)
|
||||
}
|
||||
if !strings.Contains(s.Render(), "external entry") {
|
||||
t.Fatalf("expected reload to pick up external entry, got %q", s.Render())
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Reload_MissingFileResetsToEmpty(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "MEMORY.md")
|
||||
|
||||
s, err := NewStore(path, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore: %v", err)
|
||||
}
|
||||
if _, err := s.Add("Facts", "entry"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
if err := os.Remove(path); err != nil {
|
||||
t.Fatalf("removing file: %v", err)
|
||||
}
|
||||
if err := s.Reload(); err != nil {
|
||||
t.Fatalf("Reload: %v", err)
|
||||
}
|
||||
if s.Render() != "" {
|
||||
t.Fatalf("expected empty store after reload of missing file, got %q", s.Render())
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_EmptySectionRoundTrip(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "MEMORY.md")
|
||||
|
||||
const original = "## Empty\n\n## Next\n\nContent\n"
|
||||
if err := os.WriteFile(path, []byte(original), 0o644); err != nil {
|
||||
t.Fatalf("writing seed file: %v", err)
|
||||
}
|
||||
|
||||
s, err := NewStore(path, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore: %v", err)
|
||||
}
|
||||
got := s.Render()
|
||||
if got != original {
|
||||
t.Fatalf("expected stable round-trip for empty section:\nwant %q\ngot %q", original, got)
|
||||
}
|
||||
|
||||
// Re-rendering after a fresh reload must be idempotent (no growth from
|
||||
// repeated parse/render cycles).
|
||||
if err := s.Reload(); err != nil {
|
||||
t.Fatalf("Reload: %v", err)
|
||||
}
|
||||
if got := s.Render(); got != original {
|
||||
t.Fatalf("expected reload to preserve round-trip:\nwant %q\ngot %q", original, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_ConsecutiveEmptySectionsRoundTrip(t *testing.T) {
|
||||
// Extends TestStore_EmptySectionRoundTrip to two consecutive empty
|
||||
// sections followed by a populated one, since the fix must generalize
|
||||
// past a single degenerate case.
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "MEMORY.md")
|
||||
multi := "## E1\n\n## E2\n\n## Facts\n\nfact one\n"
|
||||
if err := os.WriteFile(path, []byte(multi), 0o644); err != nil {
|
||||
t.Fatalf("writing fixture: %v", err)
|
||||
}
|
||||
s2, err := NewStore(path, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore: %v", err)
|
||||
}
|
||||
if got := s2.Render(); got != multi {
|
||||
t.Fatalf("round-trip mismatch for consecutive empty sections:\norig: %q\nrender: %q", multi, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_PreambleOnlyRoundTrip(t *testing.T) {
|
||||
// Regression test: a file with no section headers at all (just
|
||||
// preamble content) must not gain a spurious trailing blank line.
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "MEMORY.md")
|
||||
content := "Hello\nWorld\n"
|
||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
||||
t.Fatalf("writing fixture: %v", err)
|
||||
}
|
||||
s, err := NewStore(path, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore: %v", err)
|
||||
}
|
||||
if got := s.Render(); got != content {
|
||||
t.Fatalf("round-trip mismatch for preamble-only file:\norig: %q\nrender: %q", content, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_MultipleSectionsRoundTrip(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "MEMORY.md")
|
||||
|
||||
s1, err := NewStore(path, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore: %v", err)
|
||||
}
|
||||
if _, err := s1.Add("Facts", "fact one"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
if _, err := s1.Add("Preferences", "pref one"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
if _, err := s1.Add("Facts", "fact two"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
|
||||
s2, err := NewStore(path, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore reload: %v", err)
|
||||
}
|
||||
rendered := s2.Render()
|
||||
for _, want := range []string{"## Facts", "## Preferences", "fact one", "fact two", "pref one"} {
|
||||
if !strings.Contains(rendered, want) {
|
||||
t.Fatalf("expected rendered content to contain %q, got %q", want, rendered)
|
||||
}
|
||||
}
|
||||
|
||||
// Now mutate the reloaded store and ensure both sections survive.
|
||||
if _, err := s2.Remove("Facts", "fact one", true); err != nil {
|
||||
t.Fatalf("Remove: %v", err)
|
||||
}
|
||||
rendered = s2.Render()
|
||||
if strings.Contains(rendered, "fact one") {
|
||||
t.Fatalf("expected fact one removed, got %q", rendered)
|
||||
}
|
||||
if !strings.Contains(rendered, "fact two") || !strings.Contains(rendered, "pref one") {
|
||||
t.Fatalf("expected other entries to survive, got %q", rendered)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,231 +0,0 @@
|
||||
package modelcatalog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
return f(req)
|
||||
}
|
||||
|
||||
func catalogClient(body string) *http.Client {
|
||||
return &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
Header: make(http.Header),
|
||||
}, nil
|
||||
})}
|
||||
}
|
||||
|
||||
func TestLoadDownloadsFiltersAndDiscoversUsableProviders(t *testing.T) {
|
||||
const body = `{
|
||||
"openai": {
|
||||
"id": "openai",
|
||||
"name": "OpenAI",
|
||||
"npm": "@ai-sdk/openai",
|
||||
"api": "https://api.openai.test/v1",
|
||||
"env": ["OPENAI_API_KEY"],
|
||||
"models": {
|
||||
"tool-model": {"id":"tool-model","name":"Tool Model","tool_call":true,"limit":{"context":1000,"output":100}},
|
||||
"text-model": {"id":"text-model","name":"Text Model","tool_call":false}
|
||||
}
|
||||
},
|
||||
"anthropic": {
|
||||
"id": "anthropic",
|
||||
"npm": "@ai-sdk/anthropic",
|
||||
"env": ["ANTHROPIC_API_KEY"],
|
||||
"models": {"claude": {"id":"claude","tool_call":true}}
|
||||
}
|
||||
}`
|
||||
cachePath := filepath.Join(t.TempDir(), "models.json")
|
||||
got, err := Load(context.Background(), Options{
|
||||
URL: "https://models.test/catalog.json",
|
||||
CachePath: cachePath,
|
||||
HTTPClient: catalogClient(body),
|
||||
Getenv: func(name string) string {
|
||||
if name == "OPENAI_API_KEY" {
|
||||
return "present"
|
||||
}
|
||||
return ""
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got.Providers) != 1 {
|
||||
t.Fatalf("providers = %#v, want one usable provider", got.Providers)
|
||||
}
|
||||
provider := got.Providers[0]
|
||||
if provider.ID != "openai" || provider.Class != "openai" || provider.APIKeyEnv != "OPENAI_API_KEY" {
|
||||
t.Fatalf("provider = %#v", provider)
|
||||
}
|
||||
if len(provider.Models) != 1 || provider.Models[0].ID != "tool-model" {
|
||||
t.Fatalf("models = %#v, want only tool-capable model", provider.Models)
|
||||
}
|
||||
if provider.Models[0].ContextWindow != 1000 || provider.Models[0].MaxOutputTokens != 100 {
|
||||
t.Fatalf("model limits = %#v", provider.Models[0])
|
||||
}
|
||||
if _, err := os.Stat(cachePath); err != nil {
|
||||
t.Fatalf("cache was not written: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadFallsBackToCache(t *testing.T) {
|
||||
cachePath := filepath.Join(t.TempDir(), "models.json")
|
||||
if err := os.WriteFile(cachePath, []byte(`{
|
||||
"openai": {
|
||||
"id":"openai",
|
||||
"npm":"@ai-sdk/openai",
|
||||
"env":["OPENAI_API_KEY"],
|
||||
"models":{"cached":{"id":"cached","tool_call":true}}
|
||||
}
|
||||
}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got, err := Load(context.Background(), Options{
|
||||
URL: "http://127.0.0.1:1",
|
||||
CachePath: cachePath,
|
||||
Getenv: func(string) string { return "present" },
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got.Providers) != 1 || got.Providers[0].Models[0].ID != "cached" {
|
||||
t.Fatalf("snapshot = %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadPreservesAndUsesCacheWhenDownloadIsInvalid(t *testing.T) {
|
||||
cachePath := filepath.Join(t.TempDir(), "models.json")
|
||||
cached := []byte(`{
|
||||
"openai": {
|
||||
"id":"openai",
|
||||
"npm":"@ai-sdk/openai",
|
||||
"env":["OPENAI_API_KEY"],
|
||||
"models":{"cached":{"id":"cached","tool_call":true}}
|
||||
}
|
||||
}`)
|
||||
if err := os.WriteFile(cachePath, cached, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got, err := Load(context.Background(), Options{
|
||||
URL: "https://models.test/catalog.json",
|
||||
CachePath: cachePath,
|
||||
HTTPClient: catalogClient(`{"broken":`),
|
||||
Getenv: func(string) string { return "present" },
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got.Providers) != 1 || got.Providers[0].Models[0].ID != "cached" {
|
||||
t.Fatalf("snapshot = %#v, want preserved cached catalog", got)
|
||||
}
|
||||
after, err := os.ReadFile(cachePath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(after) != string(cached) {
|
||||
t.Fatalf("invalid download replaced cache:\n%s", after)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadExplicitProviderOverridesCatalogDefaults(t *testing.T) {
|
||||
const body = `{
|
||||
"openai": {
|
||||
"id":"openai",
|
||||
"npm":"@ai-sdk/openai",
|
||||
"api":"https://catalog.invalid/v1",
|
||||
"env":["OPENAI_API_KEY"],
|
||||
"models":{"tool":{"id":"tool","tool_call":true}}
|
||||
}
|
||||
}`
|
||||
got, err := Load(context.Background(), Options{
|
||||
URL: "https://models.test/catalog.json",
|
||||
CachePath: filepath.Join(t.TempDir(), "models.json"),
|
||||
HTTPClient: catalogClient(body),
|
||||
Getenv: func(string) string { return "present" },
|
||||
Configured: map[string]config.Provider{
|
||||
"openai": {
|
||||
Class: "openai-compatible",
|
||||
APIKeyEnv: "CUSTOM_KEY",
|
||||
BaseURL: "https://custom.test/v1",
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
provider := got.Providers[0]
|
||||
if provider.Class != "openai-compatible" || provider.APIKeyEnv != "CUSTOM_KEY" ||
|
||||
provider.BaseURL != "https://custom.test/v1" {
|
||||
t.Fatalf("configured override lost: %#v", provider)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadMapsGoogleCatalogProviderToSDKGeminiClass(t *testing.T) {
|
||||
const body = `{
|
||||
"google": {
|
||||
"id":"google",
|
||||
"npm":"@ai-sdk/google",
|
||||
"env":["GOOGLE_API_KEY","GEMINI_API_KEY"],
|
||||
"models":{"gemini":{"id":"gemini","tool_call":true}}
|
||||
}
|
||||
}`
|
||||
got, err := Load(context.Background(), Options{
|
||||
URL: "https://models.test/catalog.json",
|
||||
CachePath: filepath.Join(t.TempDir(), "models.json"),
|
||||
HTTPClient: catalogClient(body),
|
||||
Getenv: func(name string) string {
|
||||
if name == "GEMINI_API_KEY" {
|
||||
return "present"
|
||||
}
|
||||
return ""
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got.Providers) != 1 {
|
||||
t.Fatalf("providers = %#v, want Google provider", got.Providers)
|
||||
}
|
||||
if got.Providers[0].Class != "gemini" {
|
||||
t.Fatalf("Google class = %q, want ai-sdk native gemini class", got.Providers[0].Class)
|
||||
}
|
||||
if got.Providers[0].APIKeyEnv != "GEMINI_API_KEY" {
|
||||
t.Fatalf("Google key env = %q, want present catalog env", got.Providers[0].APIKeyEnv)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadUsesSDKOpenAICompatibleFallbackForUnknownPackage(t *testing.T) {
|
||||
const body = `{
|
||||
"native-only": {
|
||||
"id":"native-only",
|
||||
"npm":"@ai-sdk/native-only",
|
||||
"env":["NATIVE_KEY"],
|
||||
"models":{"tool":{"id":"tool","tool_call":true}}
|
||||
}
|
||||
}`
|
||||
got, err := Load(context.Background(), Options{
|
||||
URL: "https://models.test/catalog.json", CachePath: filepath.Join(t.TempDir(), "models.json"),
|
||||
HTTPClient: catalogClient(body), Getenv: func(string) string { return "present" },
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got.Providers) != 1 || got.Providers[0].Class != "openai-compatible" {
|
||||
t.Fatalf("providers = %#v, want SDK openai-compatible fallback", got.Providers)
|
||||
}
|
||||
}
|
||||
@@ -1,197 +0,0 @@
|
||||
package oidc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// TestAuthCodeURLRequestsTheAudienceAtTheAuthorizationEndpoint pins the trap infra
|
||||
// measured: a provider that is asked for the audience only at the token endpoint
|
||||
// returns a token with an empty audience, and the audience check then refuses a
|
||||
// perfectly valid token. The fix is this query parameter, so a test fails if it
|
||||
// ever goes missing.
|
||||
func TestAuthCodeURLRequestsTheAudienceAtTheAuthorizationEndpoint(t *testing.T) {
|
||||
p := newProvider(t)
|
||||
flow, err := NewFlow(context.Background(), Config{Issuer: p.server.URL, Audience: testAudience},
|
||||
"archie-web", "secret", p.server.URL+"/oauth2/callback")
|
||||
if err != nil {
|
||||
t.Fatalf("NewFlow() error = %v", err)
|
||||
}
|
||||
|
||||
raw, verifier := flow.AuthCodeURL("state-1")
|
||||
parsed, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
t.Fatalf("AuthCodeURL() returned an unparseable URL: %v", err)
|
||||
}
|
||||
query := parsed.Query()
|
||||
if got := query.Get("audience"); got != testAudience {
|
||||
t.Fatalf("audience = %q, want %q", got, testAudience)
|
||||
}
|
||||
if query.Get("code_challenge") == "" || query.Get("code_challenge_method") != "S256" {
|
||||
t.Fatalf("PKCE is not on the authorization request: %v", query)
|
||||
}
|
||||
if verifier == "" {
|
||||
t.Fatal("AuthCodeURL() returned no PKCE verifier for the callback")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewFlowRefusesAnIncompleteConfiguration(t *testing.T) {
|
||||
p := newProvider(t)
|
||||
complete := Config{Issuer: p.server.URL, Audience: testAudience}
|
||||
tests := []struct {
|
||||
name string
|
||||
cfg Config
|
||||
clientID string
|
||||
redirectURL string
|
||||
}{
|
||||
{"no client id", complete, "", p.server.URL + "/oauth2/callback"},
|
||||
{"no redirect URL", complete, "archie-web", ""},
|
||||
{"no audience", Config{Issuer: p.server.URL}, "archie-web", p.server.URL + "/oauth2/callback"},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if _, err := NewFlow(context.Background(), tc.cfg, tc.clientID, "secret", tc.redirectURL); err == nil {
|
||||
t.Fatal("NewFlow() accepted a configuration it must refuse")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestExchangeCompletesARealAuthorizationCodeFlow drives the flow against the test
|
||||
// provider's own authorize and token endpoints, so the code exchange and PKCE are
|
||||
// exercised rather than stubbed.
|
||||
func TestExchangeCompletesARealAuthorizationCodeFlow(t *testing.T) {
|
||||
p := newProvider(t)
|
||||
redirect := "http://dashboard.example/oauth2/callback"
|
||||
flow, err := NewFlow(context.Background(), Config{Issuer: p.server.URL, Audience: testAudience},
|
||||
"archie-web", "secret", redirect)
|
||||
if err != nil {
|
||||
t.Fatalf("NewFlow() error = %v", err)
|
||||
}
|
||||
|
||||
authURL, verifier := flow.AuthCodeURL("state-2")
|
||||
code := p.authorize(t, authURL, "state-2")
|
||||
|
||||
session, err := flow.Exchange(context.Background(), code, verifier)
|
||||
if err != nil {
|
||||
t.Fatalf("Exchange() error = %v", err)
|
||||
}
|
||||
if session.Credential.Subject.Subject != "a150ab4b-0000-0000-0000-000000000001" {
|
||||
t.Fatalf("subject = %q, want the person's provider subject", session.Credential.Subject.Subject)
|
||||
}
|
||||
if session.Credential.Subject.Issuer != p.server.URL {
|
||||
t.Fatalf("issuer = %q, want %q", session.Credential.Subject.Issuer, p.server.URL)
|
||||
}
|
||||
if session.Token == "" {
|
||||
t.Fatal("Exchange() returned no token to present on later requests")
|
||||
}
|
||||
}
|
||||
|
||||
// TestExchangeRefusesAWrongPKCEVerifier: the provider rejects the exchange, and
|
||||
// archie must surface that as a refusal rather than a session.
|
||||
func TestExchangeRefusesAWrongPKCEVerifier(t *testing.T) {
|
||||
p := newProvider(t)
|
||||
flow, err := NewFlow(context.Background(), Config{Issuer: p.server.URL, Audience: testAudience},
|
||||
"archie-web", "secret", "http://dashboard.example/oauth2/callback")
|
||||
if err != nil {
|
||||
t.Fatalf("NewFlow() error = %v", err)
|
||||
}
|
||||
authURL, _ := flow.AuthCodeURL("state-3")
|
||||
code := p.authorize(t, authURL, "state-3")
|
||||
|
||||
if _, err := flow.Exchange(context.Background(), code, "not-the-verifier"); err == nil {
|
||||
t.Fatal("Exchange() accepted a wrong PKCE verifier")
|
||||
}
|
||||
}
|
||||
|
||||
// authorize walks a browser's side of the flow: it asks the provider's
|
||||
// authorization endpoint and returns the code the provider sends back.
|
||||
func (p *provider) authorize(t *testing.T, authURL, wantState string) string {
|
||||
t.Helper()
|
||||
request, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authURL, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("build authorize request: %v", err)
|
||||
}
|
||||
client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
t.Fatalf("authorize: %v", err)
|
||||
}
|
||||
defer func() { _ = response.Body.Close() }()
|
||||
location := response.Header.Get("Location")
|
||||
if location == "" {
|
||||
t.Fatalf("authorize returned %d with no redirect", response.StatusCode)
|
||||
}
|
||||
parsed, err := url.Parse(location)
|
||||
if err != nil {
|
||||
t.Fatalf("authorize redirect is unparseable: %v", err)
|
||||
}
|
||||
if got := parsed.Query().Get("state"); got != wantState {
|
||||
t.Fatalf("state = %q, want %q", got, wantState)
|
||||
}
|
||||
return parsed.Query().Get("code")
|
||||
}
|
||||
|
||||
// authorizeEndpoint is a faithful authorization endpoint: it requires the
|
||||
// audience and the PKCE challenge, and it only issues a code for a verifier it
|
||||
// later receives.
|
||||
func (p *provider) authorizeEndpoint(t *testing.T) http.HandlerFunc {
|
||||
t.Helper()
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
query := r.URL.Query()
|
||||
if query.Get("audience") == "" {
|
||||
http.Error(w, "audience is required at the authorization endpoint", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
challenge := query.Get("code_challenge")
|
||||
if challenge == "" || query.Get("code_challenge_method") != "S256" {
|
||||
http.Error(w, "PKCE is required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
code := "code-" + query.Get("state")
|
||||
p.pending.Store(code, challenge)
|
||||
location := query.Get("redirect_uri") + "?code=" + url.QueryEscape(code) + "&state=" + url.QueryEscape(query.Get("state"))
|
||||
http.Redirect(w, r, location, http.StatusSeeOther)
|
||||
}
|
||||
}
|
||||
|
||||
// tokenEndpoint trades a code for a signed access token, checking the PKCE
|
||||
// verifier against the challenge the authorization endpoint recorded.
|
||||
func (p *provider) tokenEndpoint(t *testing.T) http.HandlerFunc {
|
||||
t.Helper()
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, "bad form", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
code := r.PostForm.Get("code")
|
||||
challenge, ok := p.pending.LoadAndDelete(code)
|
||||
if !ok {
|
||||
http.Error(w, "unknown code", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
want, ok := challenge.(string)
|
||||
if !ok || pkceChallenge(r.PostForm.Get("code_verifier")) != want {
|
||||
http.Error(w, "PKCE verification failed", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"access_token": p.personToken(t),
|
||||
"token_type": "Bearer",
|
||||
"expires_in": 3600,
|
||||
"scope": "openid profile email",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// pkceChallenge computes the challenge the way the client library does, so the
|
||||
// provider's check is the library's own transformation rather than archie's.
|
||||
func pkceChallenge(verifier string) string {
|
||||
return oauth2.S256ChallengeFromVerifier(verifier)
|
||||
}
|
||||
@@ -1,289 +0,0 @@
|
||||
package oidc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-jose/go-jose/v4"
|
||||
"github.com/go-jose/go-jose/v4/jwt"
|
||||
)
|
||||
|
||||
const testAudience = "archie-dashboard"
|
||||
|
||||
// provider is a minimal identity provider: a discovery document and a JWKS.
|
||||
// It signs with a real RSA key so every refusal below is the library's own
|
||||
// signature and claim checking, not a stub's behaviour.
|
||||
type provider struct {
|
||||
server *httptest.Server
|
||||
key *rsa.PrivateKey
|
||||
keyID string
|
||||
// other is a second, unrelated key used to sign a token the provider
|
||||
// never published, which is what a forged or foreign token looks like.
|
||||
other *rsa.PrivateKey
|
||||
// pending holds the PKCE challenge each issued code must be redeemed with.
|
||||
pending sync.Map
|
||||
}
|
||||
|
||||
func newProvider(t *testing.T) *provider {
|
||||
t.Helper()
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatalf("generate key: %v", err)
|
||||
}
|
||||
other, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatalf("generate second key: %v", err)
|
||||
}
|
||||
p := &provider{key: key, other: other, keyID: "test-key"}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"issuer": p.server.URL,
|
||||
"jwks_uri": p.server.URL + "/keys",
|
||||
"authorization_endpoint": p.server.URL + "/authorize",
|
||||
"token_endpoint": p.server.URL + "/token",
|
||||
"response_types_supported": []string{"code"},
|
||||
"subject_types_supported": []string{"public"},
|
||||
"id_token_signing_alg_values_supported": []string{"RS256"},
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("/authorize", p.authorizeEndpoint(t))
|
||||
mux.HandleFunc("/token", p.tokenEndpoint(t))
|
||||
mux.HandleFunc("/keys", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{
|
||||
Key: key.Public(), KeyID: p.keyID, Algorithm: "RS256", Use: "sig",
|
||||
}}})
|
||||
})
|
||||
p.server = httptest.NewServer(mux)
|
||||
t.Cleanup(p.server.Close)
|
||||
return p
|
||||
}
|
||||
|
||||
// testClaims is the claim set this provider emits. A machine token carries
|
||||
// client_id and no sub; a person's token carries sub.
|
||||
type testClaims struct {
|
||||
jwt.Claims
|
||||
ClientID string `json:"client_id,omitempty"`
|
||||
Scopes []string `json:"scp,omitempty"`
|
||||
}
|
||||
|
||||
// token signs a token with the given key for the given claims.
|
||||
func (p *provider) token(t *testing.T, signer *rsa.PrivateKey, mutate func(*testClaims)) string {
|
||||
t.Helper()
|
||||
claims := testClaims{
|
||||
Issuer: p.server.URL,
|
||||
Subject: "sam",
|
||||
Audience: jwt.Audience{testAudience},
|
||||
Expiry: jwt.NewNumericDate(time.Now().Add(time.Hour)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now().Add(-time.Minute)),
|
||||
}
|
||||
if mutate != nil {
|
||||
mutate(&claims)
|
||||
}
|
||||
sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: signer},
|
||||
(&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", p.keyID))
|
||||
if err != nil {
|
||||
t.Fatalf("new signer: %v", err)
|
||||
}
|
||||
raw, err := jwt.Signed(sig).Claims(claims).Serialize()
|
||||
if err != nil {
|
||||
t.Fatalf("serialize token: %v", err)
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
// personToken is what the token endpoint issues for a signed-in person: a
|
||||
// subject, and the audience this dashboard checks.
|
||||
func (p *provider) personToken(t *testing.T) string {
|
||||
t.Helper()
|
||||
return p.token(t, p.key, func(c *testClaims) {
|
||||
c.Subject = "a150ab4b-0000-0000-0000-000000000001"
|
||||
c.ClientID = ""
|
||||
c.Scopes = []string{"openid", "profile", "email"}
|
||||
})
|
||||
}
|
||||
|
||||
func (p *provider) verifier(t *testing.T) *Verifier {
|
||||
t.Helper()
|
||||
v, err := New(context.Background(), Config{Issuer: p.server.URL, Audience: testAudience})
|
||||
if err != nil {
|
||||
t.Fatalf("New() error = %v", err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func TestVerifyAcceptsAProviderIssuedToken(t *testing.T) {
|
||||
p := newProvider(t)
|
||||
credential, err := p.verifier(t).Verify(context.Background(), p.token(t, p.key, nil))
|
||||
if err != nil {
|
||||
t.Fatalf("Verify() error = %v", err)
|
||||
}
|
||||
if credential.Subject.Subject != "sam" {
|
||||
t.Fatalf("subject = %q, want %q", credential.Subject.Subject, "sam")
|
||||
}
|
||||
if credential.Subject.Issuer != p.server.URL {
|
||||
t.Fatalf("issuer = %q, want %q", credential.Subject.Issuer, p.server.URL)
|
||||
}
|
||||
}
|
||||
|
||||
// TestVerifyDerivesTheSubjectTheWayTheProviderIssuesIt: a person is named by sub
|
||||
// and a machine by client_id, because a machine token carries no sub at all.
|
||||
// Getting this wrong does not fail loudly -- it binds every machine caller to one
|
||||
// identity, or to none.
|
||||
func TestVerifyDerivesTheSubjectTheWayTheProviderIssuesIt(t *testing.T) {
|
||||
p := newProvider(t)
|
||||
verifier := p.verifier(t)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*testClaims)
|
||||
wantSubject string
|
||||
wantScopes []string
|
||||
}{
|
||||
{
|
||||
name: "a person's token carries sub",
|
||||
mutate: func(c *testClaims) {
|
||||
c.Subject = "a150ab4b-0000-0000-0000-000000000001"
|
||||
c.Scopes = []string{"openid", "profile", "email", "groups"}
|
||||
},
|
||||
wantSubject: "a150ab4b-0000-0000-0000-000000000001",
|
||||
wantScopes: []string{"openid", "profile", "email", "groups"},
|
||||
},
|
||||
{
|
||||
name: "a machine token carries client_id and no sub",
|
||||
mutate: func(c *testClaims) {
|
||||
c.Subject = ""
|
||||
c.ClientID = "archie"
|
||||
c.Scopes = []string{"authelia.bearer.authz"}
|
||||
},
|
||||
wantSubject: "archie",
|
||||
wantScopes: []string{"authelia.bearer.authz"},
|
||||
},
|
||||
{
|
||||
name: "sub wins when a token carries both",
|
||||
mutate: func(c *testClaims) {
|
||||
c.Subject = "a150ab4b-0000-0000-0000-000000000002"
|
||||
c.ClientID = "archie-web"
|
||||
},
|
||||
wantSubject: "a150ab4b-0000-0000-0000-000000000002",
|
||||
},
|
||||
{
|
||||
name: "a space-delimited scope claim is read too",
|
||||
mutate: func(c *testClaims) {
|
||||
c.Subject = "a150ab4b-0000-0000-0000-000000000003"
|
||||
c.ClientID = ""
|
||||
c.Scopes = nil
|
||||
},
|
||||
wantSubject: "a150ab4b-0000-0000-0000-000000000003",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
credential, err := verifier.Verify(context.Background(), p.token(t, p.key, tc.mutate))
|
||||
if err != nil {
|
||||
t.Fatalf("Verify() error = %v", err)
|
||||
}
|
||||
if credential.Subject.Subject != tc.wantSubject {
|
||||
t.Fatalf("subject = %q, want %q", credential.Subject.Subject, tc.wantSubject)
|
||||
}
|
||||
if tc.wantScopes != nil && !slices.Equal(credential.Scopes, tc.wantScopes) {
|
||||
t.Fatalf("scopes = %v, want %v", credential.Scopes, tc.wantScopes)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestVerifyRefusesATokenThatNamesNobody: a verified token asserting neither sub
|
||||
// nor client_id is an anonymous caller, and accepting it would let any token the
|
||||
// provider ever signed act as whoever the binding happened to hold.
|
||||
func TestVerifyRefusesATokenThatNamesNobody(t *testing.T) {
|
||||
p := newProvider(t)
|
||||
token := p.token(t, p.key, func(c *testClaims) {
|
||||
c.Subject = ""
|
||||
c.ClientID = ""
|
||||
})
|
||||
if _, err := p.verifier(t).Verify(context.Background(), token); err == nil {
|
||||
t.Fatal("Verify() accepted a token that asserts no caller")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyRefusesEveryUnacceptableToken(t *testing.T) {
|
||||
p := newProvider(t)
|
||||
verifier := p.verifier(t)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
token string
|
||||
}{
|
||||
{
|
||||
name: "no token",
|
||||
token: "",
|
||||
},
|
||||
{
|
||||
name: "expired",
|
||||
token: p.token(t, p.key, func(c *testClaims) { c.Expiry = jwt.NewNumericDate(time.Now().Add(-time.Hour)) }),
|
||||
},
|
||||
{
|
||||
name: "signed by a key the provider never published",
|
||||
token: p.token(t, p.other, nil),
|
||||
},
|
||||
{
|
||||
name: "issued for another audience",
|
||||
token: p.token(t, p.key, func(c *testClaims) { c.Audience = jwt.Audience{"another-service"} }),
|
||||
},
|
||||
{
|
||||
name: "issued by another provider",
|
||||
token: p.token(t, p.key, func(c *testClaims) { c.Issuer = "https://someone-else.example" }),
|
||||
},
|
||||
{
|
||||
// The human path's failure mode: a token minted without the requested
|
||||
// audience arrives with an empty audience, and the check here refuses
|
||||
// it. The fix is requesting the audience at the authorisation
|
||||
// endpoint, not weakening this check.
|
||||
name: "issued with no audience at all",
|
||||
token: p.token(t, p.key, func(c *testClaims) { c.Audience = nil }),
|
||||
},
|
||||
{
|
||||
name: "not a token at all",
|
||||
token: "not-a-jwt",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if _, err := verifier.Verify(context.Background(), tc.token); err == nil {
|
||||
t.Fatal("Verify() accepted a token it must refuse")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewRefusesAnIncompleteConfiguration(t *testing.T) {
|
||||
p := newProvider(t)
|
||||
tests := []struct {
|
||||
name string
|
||||
cfg Config
|
||||
}{
|
||||
{"no issuer", Config{Audience: testAudience}},
|
||||
{"no audience", Config{Issuer: p.server.URL}},
|
||||
{"unreachable issuer", Config{Issuer: "http://127.0.0.1:1", Audience: testAudience}},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if _, err := New(context.Background(), tc.cfg); err == nil {
|
||||
t.Fatal("New() accepted a configuration it must refuse")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,225 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
)
|
||||
|
||||
func newStoreForAccess(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
pool, _ := migrated(t)
|
||||
return New(pool)
|
||||
}
|
||||
|
||||
func TestAccessPolicyStore(t *testing.T) {
|
||||
s := newStoreForAccess(t)
|
||||
ctx := t.Context()
|
||||
|
||||
// PutPolicy stores one policy and reports a versioned level.
|
||||
p := access.Policy{
|
||||
ID: "test-policy", Level: access.LevelOrg, OrgID: "soc",
|
||||
Text: `permit(principal, action, resource) when { resource.kind == "binding" };`,
|
||||
}
|
||||
v1, err := s.PutPolicy(ctx, p)
|
||||
if err != nil {
|
||||
t.Fatalf("PutPolicy: %v", err)
|
||||
}
|
||||
if v1 != 2 { // the counter starts at 1; the first write bumps it
|
||||
t.Fatalf("PutPolicy version = %d, want 2", v1)
|
||||
}
|
||||
v2, err := s.PutPolicy(ctx, p)
|
||||
if err != nil {
|
||||
t.Fatalf("second PutPolicy: %v", err)
|
||||
}
|
||||
if v2 <= v1 {
|
||||
t.Fatalf("second PutPolicy version = %d, want > %d", v2, v1)
|
||||
}
|
||||
|
||||
// A malformed policy is refused by the store's own structural check.
|
||||
bad := access.Policy{ID: "bad", Level: access.LevelOrg, OrgID: "soc"}
|
||||
if _, err := s.PutPolicy(ctx, bad); !errors.Is(err, access.ErrInvalidPolicy) {
|
||||
t.Fatalf("PutPolicy(structurally invalid) = %v, want ErrInvalidPolicy", err)
|
||||
}
|
||||
|
||||
// ListPolicies round-trips the scope tuple.
|
||||
list, err := s.ListPolicies(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ListPolicies: %v", err)
|
||||
}
|
||||
if len(list) != 1 {
|
||||
t.Fatalf("ListPolicies = %d policies, want 1", len(list))
|
||||
}
|
||||
if list[0].ID != "test-policy" || list[0].OrgID != "soc" {
|
||||
t.Fatalf("ListPolicies[0] = %+v, want the stored policy", list[0])
|
||||
}
|
||||
|
||||
// DeletePolicy removes it and reports an unknown key as a sentinel.
|
||||
if err := s.DeletePolicy(ctx, p); err != nil {
|
||||
t.Fatalf("DeletePolicy: %v", err)
|
||||
}
|
||||
if err := s.DeletePolicy(ctx, p); !errors.Is(err, access.ErrPolicyNotFound) {
|
||||
t.Fatalf("second DeletePolicy = %v, want ErrPolicyNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureShippedOrgPolicies(t *testing.T) {
|
||||
s := newStoreForAccess(t)
|
||||
ctx := t.Context()
|
||||
|
||||
if err := s.EnsureShippedOrgPolicies(ctx, "soc"); err != nil {
|
||||
t.Fatalf("EnsureShippedOrgPolicies: %v", err)
|
||||
}
|
||||
list, err := s.ListPolicies(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ListPolicies: %v", err)
|
||||
}
|
||||
if len(list) != 4 {
|
||||
t.Fatalf("seeding produced %d policies, want the 4 shipped roles", len(list))
|
||||
}
|
||||
|
||||
// An edited role policy survives a re-seed: an org that already carries
|
||||
// the shipped IDs is left untouched.
|
||||
edited := list[0]
|
||||
edited.Text = `permit(principal, action, resource) when { resource.kind == "edited" };`
|
||||
if _, err := s.PutPolicy(ctx, edited); err != nil {
|
||||
t.Fatalf("PutPolicy(edit): %v", err)
|
||||
}
|
||||
if err := s.EnsureShippedOrgPolicies(ctx, "soc"); err != nil {
|
||||
t.Fatalf("re-seed: %v", err)
|
||||
}
|
||||
after, err := s.ListPolicies(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ListPolicies after re-seed: %v", err)
|
||||
}
|
||||
for _, p := range after {
|
||||
if p.ID == edited.ID && p.Text != edited.Text {
|
||||
t.Fatalf("re-seed overwrote an edited role policy %s", p.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetPolicies(t *testing.T) {
|
||||
s := newStoreForAccess(t)
|
||||
ctx := t.Context()
|
||||
|
||||
if err := s.ResetOrgPolicies(ctx, "soc"); err != nil {
|
||||
t.Fatalf("ResetOrgPolicies: %v", err)
|
||||
}
|
||||
// An operator's custom org policy on top of the shipped set.
|
||||
custom := access.Policy{
|
||||
ID: "org-lockdown", Level: access.LevelOrg, OrgID: "soc",
|
||||
Text: `forbid(principal, action, resource) when { resource.kind == "source" };`,
|
||||
}
|
||||
if _, err := s.PutPolicy(ctx, custom); err != nil {
|
||||
t.Fatalf("PutPolicy(custom): %v", err)
|
||||
}
|
||||
// A workspace policy must survive an org reset.
|
||||
ws := access.Policy{
|
||||
ID: "ws-rule", Level: access.LevelWorkspace, OrgID: "soc", WorkspaceID: "net",
|
||||
Text: `permit(principal, action, resource) when { resource.kind == "binding" };`,
|
||||
}
|
||||
if _, err := s.PutPolicy(ctx, ws); err != nil {
|
||||
t.Fatalf("PutPolicy(ws): %v", err)
|
||||
}
|
||||
// And an instance policy must survive an org reset but not an instance
|
||||
// reset.
|
||||
instance := access.Policy{
|
||||
ID: "instance-rule", Level: access.LevelInstance,
|
||||
Text: `forbid(principal, action, resource) when { resource.kind == "secret" };`,
|
||||
}
|
||||
if _, err := s.PutPolicy(ctx, instance); err != nil {
|
||||
t.Fatalf("PutPolicy(instance): %v", err)
|
||||
}
|
||||
|
||||
if err := s.ResetOrgPolicies(ctx, "soc"); err != nil {
|
||||
t.Fatalf("org reset: %v", err)
|
||||
}
|
||||
after, err := s.ListPolicies(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ListPolicies: %v", err)
|
||||
}
|
||||
orgPolicies := 0
|
||||
for _, p := range after {
|
||||
switch {
|
||||
case p.Level == access.LevelOrg && p.OrgID == "soc":
|
||||
orgPolicies++
|
||||
case p.Level == access.LevelOrg:
|
||||
t.Fatalf("org reset touched policy %s of another org", p.ID)
|
||||
}
|
||||
}
|
||||
if orgPolicies != 4 {
|
||||
t.Fatalf("org-level policies after reset = %d, want the 4 shipped roles", orgPolicies)
|
||||
}
|
||||
|
||||
if err := s.ResetInstancePolicies(ctx); err != nil {
|
||||
t.Fatalf("ResetInstancePolicies: %v", err)
|
||||
}
|
||||
after, err = s.ListPolicies(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ListPolicies after instance reset: %v", err)
|
||||
}
|
||||
for _, p := range after {
|
||||
if p.Level == access.LevelInstance {
|
||||
t.Fatalf("instance reset left policy %s", p.ID)
|
||||
}
|
||||
}
|
||||
if len(after) == 0 {
|
||||
t.Fatal("instance reset removed non-instance policies")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDenialStore(t *testing.T) {
|
||||
s := newStoreForAccess(t)
|
||||
ctx := t.Context()
|
||||
|
||||
denial := access.Denial{
|
||||
Principal: identity.IdentityID("11111111-1111-5111-8111-111111111111"),
|
||||
Org: "soc", Action: access.ActionRead, Kind: access.KindBinding,
|
||||
ResourceID: "b1", Level: access.LevelOrg,
|
||||
Policies: []string{access.PolicyOrgRead, access.PolicyOrgEdit},
|
||||
}
|
||||
if err := s.RecordDenial(ctx, denial); err != nil {
|
||||
t.Fatalf("RecordDenial: %v", err)
|
||||
}
|
||||
if err := s.RecordDenial(ctx, denial); err != nil {
|
||||
t.Fatalf("repeat RecordDenial: %v", err)
|
||||
}
|
||||
// A different action is a separate row.
|
||||
other := denial
|
||||
other.Action = access.ActionDelete
|
||||
if err := s.RecordDenial(ctx, other); err != nil {
|
||||
t.Fatalf("RecordDenial(other action): %v", err)
|
||||
}
|
||||
|
||||
rows, err := s.ListDenials(ctx, "soc", 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListDenials: %v", err)
|
||||
}
|
||||
if len(rows) != 2 {
|
||||
t.Fatalf("ListDenials = %d rows, want 2", len(rows))
|
||||
}
|
||||
if rows[0].Action != access.ActionDelete {
|
||||
t.Fatalf("newest denial = %v, want the delete denial", rows[0].Action)
|
||||
}
|
||||
for _, r := range rows {
|
||||
if r.Action == access.ActionRead {
|
||||
if r.Count != 2 {
|
||||
t.Fatalf("repeated denial count = %d, want 2 (coalesced within the minute)", r.Count)
|
||||
}
|
||||
if len(r.Policies) != 2 {
|
||||
t.Fatalf("denial policies = %v, want the deciding policies", r.Policies)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Another org sees none of these.
|
||||
if rows, err := s.ListDenials(ctx, "other", 10); err != nil || len(rows) != 0 {
|
||||
t.Fatalf("ListDenials(other org) = %d rows %v, want none", len(rows), err)
|
||||
}
|
||||
// An org-less denial is refused at the producer.
|
||||
if err := s.RecordDenial(ctx, access.Denial{Action: access.ActionRead}); err == nil {
|
||||
t.Fatal("RecordDenial accepted a denial with no org or principal")
|
||||
}
|
||||
}
|
||||
@@ -1,366 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
task "github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
// CancelExecution is the one cancel path (docs/prds/execution-tree-state-machine.md,
|
||||
// "Cancellation"): one transaction cancels every non-terminal StepExecution of
|
||||
// the execution's current attempt and moves the execution to the status the
|
||||
// operator action names, with one event row per step transition and the
|
||||
// execution's own audit row in the same write.
|
||||
|
||||
func TestCancelExecutionCancelsTheAttemptsStepsAndTheExecution(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
stageID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "review",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep stage: %v", err)
|
||||
}
|
||||
childID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt,
|
||||
ParentID: stageID, Kind: task.StepKindAgent, Name: "review:1",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep child: %v", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stageID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded, Detail: "done",
|
||||
}); err != nil {
|
||||
t.Fatalf("FinishStep: %v", err)
|
||||
}
|
||||
|
||||
steps, err := s.CancelExecution(t.Context(), execution.ID, "stopped by operator", taskstate.Parked)
|
||||
if err != nil {
|
||||
t.Fatalf("CancelExecution: %v", err)
|
||||
}
|
||||
if len(steps) != 1 || steps[0] != childID {
|
||||
t.Fatalf("cancelled steps = %v, want only the non-terminal %d", steps, childID)
|
||||
}
|
||||
|
||||
// Every non-terminal step of the current attempt is cancelled; the one
|
||||
// that already finished is never rewritten.
|
||||
var statuses map[int64]string
|
||||
if err := s.pool.QueryRow(t.Context(),
|
||||
`SELECT jsonb_object_agg(id, status) FROM step_executions WHERE execution_id = $1`,
|
||||
execution.ID).Scan(&statuses); err != nil {
|
||||
t.Fatalf("read steps: %v", err)
|
||||
}
|
||||
if statuses[stageID] != string(taskstate.StepSucceeded) || statuses[childID] != string(taskstate.StepCancelled) {
|
||||
t.Fatalf("statuses = %v, want the finished step kept and the child cancelled", statuses)
|
||||
}
|
||||
|
||||
got, err := s.TaskByID(t.Context(), execution.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID: %+v %v", got, err)
|
||||
}
|
||||
if got.Status != taskstate.Parked || got.ParkReason != "stopped by operator" {
|
||||
t.Fatalf("execution after cancel = %s (%q), want parked with the reason", got.Status, got.ParkReason)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancelExecutionWritesOneEventPerCancelledStep(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
stageID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep: %v", err)
|
||||
}
|
||||
if _, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt,
|
||||
ParentID: stageID, Kind: task.StepKindAgent, Name: "implement",
|
||||
}); err != nil {
|
||||
t.Fatalf("StartStep child: %v", err)
|
||||
}
|
||||
|
||||
if _, err := s.CancelExecution(t.Context(), execution.ID, "stopped by operator", taskstate.Parked); err != nil {
|
||||
t.Fatalf("CancelExecution: %v", err)
|
||||
}
|
||||
evs, err := s.TaskEvents(t.Context(), execution.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskEvents: %v", err)
|
||||
}
|
||||
var cancelled []events.Event
|
||||
for _, e := range evs {
|
||||
if e.Data["cancelled"] == true {
|
||||
cancelled = append(cancelled, e)
|
||||
}
|
||||
}
|
||||
if len(cancelled) != 2 {
|
||||
t.Fatalf("cancel events = %d, want one per step the transaction cancelled", len(cancelled))
|
||||
}
|
||||
for _, e := range cancelled {
|
||||
if e.Kind != events.KindStageFinish || e.Attempt != execution.Attempt {
|
||||
t.Errorf("cancel event = %+v, want a stage_finish row attributed to the attempt", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancelExecutionLeavesEarlierAttemptsAlone(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
firstAttempt := execution.Attempt
|
||||
stepID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: firstAttempt, Kind: task.StepKindStage, Name: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep: %v", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stepID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded,
|
||||
}); err != nil {
|
||||
t.Fatalf("FinishStep: %v", err)
|
||||
}
|
||||
// A retry requeues and reclaims: attempt 2.
|
||||
if err := s.Requeue(t.Context(), execution.ID, taskstate.Running, "implement"); err != nil {
|
||||
t.Fatalf("Requeue: %v", err)
|
||||
}
|
||||
retried, err := s.ClaimNext(t.Context())
|
||||
if err != nil || retried == nil {
|
||||
t.Fatalf("ClaimNext: %+v %v", retried, err)
|
||||
}
|
||||
|
||||
if _, err := s.CancelExecution(t.Context(), execution.ID, "stopped by operator", taskstate.Parked); err != nil {
|
||||
t.Fatalf("CancelExecution: %v", err)
|
||||
}
|
||||
var firstAttemptStatuses []string
|
||||
if err := s.pool.QueryRow(t.Context(),
|
||||
`SELECT jsonb_agg(status) FROM step_executions WHERE execution_id = $1 AND attempt = $2`,
|
||||
execution.ID, firstAttempt).Scan(&firstAttemptStatuses); err != nil {
|
||||
t.Fatalf("read first attempt's steps: %v", err)
|
||||
}
|
||||
for _, status := range firstAttemptStatuses {
|
||||
if status != string(taskstate.StepSucceeded) {
|
||||
t.Errorf("an earlier attempt's step was rewritten to %q; history is never rewritten", status)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancelExecutionRefusesWhatTheTableForbids(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
target string
|
||||
want error
|
||||
}{
|
||||
{name: "a terminal execution", target: taskstate.Queued, want: storecontract.ErrIllegalTransition},
|
||||
{name: "an unroutable destination", target: "quantum", want: storecontract.ErrIllegalTransition},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
if tt.name == "a terminal execution" {
|
||||
// completed is terminal: the table routes nothing out of it.
|
||||
if err := s.Transition(t.Context(), execution.ID, taskstate.Running, taskstate.Completed, "done"); err != nil {
|
||||
t.Fatalf("seed completed: %v", err)
|
||||
}
|
||||
}
|
||||
if _, err := s.CancelExecution(t.Context(), execution.ID, "why", tt.target); !errors.Is(err, tt.want) {
|
||||
t.Fatalf("CancelExecution(to=%q) = %v, want %v", tt.target, err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
// A queued execution cancels fine: the table routes queued -> closed_wont_do.
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
if err := s.Transition(t.Context(), execution.ID, taskstate.Running, taskstate.Queued, "requeue"); err != nil {
|
||||
t.Fatalf("seed queued: %v", err)
|
||||
}
|
||||
if _, err := s.CancelExecution(t.Context(), execution.ID, "cancelled by operator", taskstate.Declined); err != nil {
|
||||
t.Fatalf("CancelExecution(queued -> closed_wont_do) = %v, want nil", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancelExecutionOnAMissingExecutionIsStale(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
if _, err := s.CancelExecution(t.Context(), 999999, "why", taskstate.Parked); !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("CancelExecution on a missing execution = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
}
|
||||
|
||||
// RecoverStale is the crash-recovery half of
|
||||
// docs/prds/execution-tree-state-machine.md: requeueing a running execution
|
||||
// moves the steps its interrupted attempt left running to the table's
|
||||
// interrupted outcome, through the step transition table (the pair pinned in
|
||||
// SQL, like the execution's own edge), with one event row per step transition
|
||||
// and the execution's audit row in the same transaction. Killing the daemon
|
||||
// mid-stage and restarting leaves that stage interrupted and the execution
|
||||
// queued with a fresh attempt for the next run.
|
||||
func TestRecoverStaleInterruptsRunningSteps(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
stageID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep stage: %v", err)
|
||||
}
|
||||
childID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt,
|
||||
ParentID: stageID, Kind: task.StepKindAgent, Name: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep child: %v", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stageID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded, Detail: "done",
|
||||
}); err != nil {
|
||||
t.Fatalf("FinishStep: %v", err)
|
||||
}
|
||||
|
||||
requeued, err := s.RecoverStale(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("RecoverStale: %v", err)
|
||||
}
|
||||
if requeued != 1 {
|
||||
t.Fatalf("RecoverStale requeued %d, want the one running execution", requeued)
|
||||
}
|
||||
|
||||
got, err := s.TaskByID(t.Context(), execution.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID: %+v %v", got, err)
|
||||
}
|
||||
if got.Status != taskstate.Queued {
|
||||
t.Fatalf("execution after recovery = %q, want queued for the next attempt", got.Status)
|
||||
}
|
||||
|
||||
var statuses map[int64]string
|
||||
if err := s.pool.QueryRow(t.Context(),
|
||||
`SELECT jsonb_object_agg(id, status) FROM step_executions WHERE execution_id = $1`,
|
||||
execution.ID).Scan(&statuses); err != nil {
|
||||
t.Fatalf("read steps: %v", err)
|
||||
}
|
||||
if statuses[stageID] != string(taskstate.StepSucceeded) {
|
||||
t.Errorf("the finished step was rewritten to %q; recovery only interrupts", statuses[stageID])
|
||||
}
|
||||
if statuses[childID] != string(taskstate.StepInterrupted) {
|
||||
t.Errorf("the step the crash left running = %q, want interrupted", statuses[childID])
|
||||
}
|
||||
|
||||
evs, err := s.TaskEvents(t.Context(), execution.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskEvents: %v", err)
|
||||
}
|
||||
var interrupted []events.Event
|
||||
for _, e := range evs {
|
||||
if e.Data["interrupted"] == true {
|
||||
interrupted = append(interrupted, e)
|
||||
}
|
||||
}
|
||||
if len(interrupted) != 1 {
|
||||
t.Fatalf("interrupted step events = %d, want exactly one for the step transition", len(interrupted))
|
||||
}
|
||||
if interrupted[0].Kind != events.KindStageFinish || interrupted[0].Stage != "implement" ||
|
||||
interrupted[0].Attempt != got.Attempt {
|
||||
t.Errorf("interrupted event = %+v, want a stage_finish row attributed to the interrupted attempt", interrupted[0])
|
||||
}
|
||||
}
|
||||
|
||||
// A wait:true call step is how the store knows the caller is still waiting on
|
||||
// its callee: it closes only when the callee ends, so a non-terminal call
|
||||
// step is a callee the caller waits on. Cancelling the caller sweeps each
|
||||
// such callee through its own CancelExecution -- the callee's own lifecycle
|
||||
// -- while a finished call step's callee (wait:false, or already ended) runs
|
||||
// on. Trees never cross runs: a call step naming a task that is not the
|
||||
// caller's callee cannot even be recorded (StartStep verifies the callee's
|
||||
// call_parent_task_id).
|
||||
func TestCancelExecutionCancelsTheCalleesTheCallerWaitsOn(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
caller := runningExecution(t, s)
|
||||
|
||||
// The callee: started through the call linkage the way a wait:true step
|
||||
// does (the store derives the callee from the caller's own row), running
|
||||
// under its own lifecycle, with a running step of its own.
|
||||
callee, err := s.StartCall(t.Context(), caller.ID, "implement", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("EnqueueCallTask: %v", err)
|
||||
}
|
||||
if _, err := s.ClaimNext(t.Context()); err != nil {
|
||||
t.Fatalf("ClaimNext callee: %v", err)
|
||||
}
|
||||
// The claim increments the attempt; read the row back the way the
|
||||
// container's own request carries it.
|
||||
callee, err = s.TaskByID(t.Context(), callee.ID)
|
||||
if err != nil || callee == nil {
|
||||
t.Fatalf("TaskByID(callee): %+v %v", callee, err)
|
||||
}
|
||||
if _, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: callee.ID, Attempt: callee.Attempt, Kind: task.StepKindStage, Name: "implement",
|
||||
}); err != nil {
|
||||
t.Fatalf("callee StartStep: %v", err)
|
||||
}
|
||||
|
||||
// The caller's wait:true call step names the callee and is still running.
|
||||
if _, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: caller.ID, Attempt: caller.Attempt, Kind: task.StepKindCall,
|
||||
Name: "workflow.call", CalledExecutionID: callee.ID,
|
||||
}); err != nil {
|
||||
t.Fatalf("call step: %v", err)
|
||||
}
|
||||
|
||||
// A wait:false call step's callee runs on: its call step already ended.
|
||||
unwaited, err := s.StartCall(t.Context(), caller.ID, "implement", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.ClaimNext(t.Context()); err != nil {
|
||||
t.Fatalf("ClaimNext no-wait callee: %v", err)
|
||||
}
|
||||
noWaitStep, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: caller.ID, Attempt: caller.Attempt, Kind: task.StepKindCall,
|
||||
Name: "workflow.call", CalledExecutionID: unwaited.ID,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("no-wait call step: %v", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: noWaitStep, ExecutionID: caller.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded, Detail: "started; no wait",
|
||||
}); err != nil {
|
||||
t.Fatalf("close the no-wait call step: %v", err)
|
||||
}
|
||||
|
||||
if _, err := s.CancelExecution(t.Context(), caller.ID, "stopped by operator", taskstate.Parked); err != nil {
|
||||
t.Fatalf("CancelExecution: %v", err)
|
||||
}
|
||||
|
||||
waited, err := s.TaskByID(t.Context(), callee.ID)
|
||||
if err != nil || waited == nil {
|
||||
t.Fatalf("TaskByID(callee): %+v %v", waited, err)
|
||||
}
|
||||
if waited.Status != taskstate.Parked {
|
||||
t.Fatalf("the waited-on callee = %q, want parked under its own lifecycle", waited.Status)
|
||||
}
|
||||
waitedSteps, err := s.TaskEvents(t.Context(), callee.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("callee TaskEvents: %v", err)
|
||||
}
|
||||
if len(waitedSteps) == 0 {
|
||||
t.Error("the callee's steps were not cancelled with their events")
|
||||
}
|
||||
|
||||
unwaitedAfter, err := s.TaskByID(t.Context(), unwaited.ID)
|
||||
if err != nil || unwaitedAfter == nil {
|
||||
t.Fatalf("TaskByID no-wait callee: %+v %v", unwaitedAfter, err)
|
||||
}
|
||||
if unwaitedAfter.Status != taskstate.Running {
|
||||
t.Errorf("the wait:false callee = %q, want it running on", unwaitedAfter.Status)
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
// ClearTerminalTasks deletes exactly the statuses taskstate.Terminal names, so
|
||||
// the SQL list cannot fall behind a new terminal status.
|
||||
func TestClearTerminalTasksMatchesTaskstate(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
statuses := taskstate.Statuses()
|
||||
for i, meta := range statuses {
|
||||
if _, err := s.EnqueueIssue(t.Context(), "acme", "widgets", i+1, "t", "b", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.pool.Exec(t.Context(), "UPDATE tasks SET status = $1 WHERE issue_number = $2", meta.ID, i+1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.ClearTerminalTasks(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i, meta := range statuses {
|
||||
task, err := s.TaskByIssue(t.Context(), "acme", "widgets", i+1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if kept := task != nil; kept == taskstate.Terminal(meta.ID) {
|
||||
t.Errorf("status %q: kept = %v, want kept only when not terminal", meta.ID, kept)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,166 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// eventTypeFixture saves a type on source matching events whose "kind" equals kind.
|
||||
func eventTypeFixture(t *testing.T, s *EDA, source, kind string) string {
|
||||
t.Helper()
|
||||
id, err := s.InsertEventType(t.Context(), eventtype.EventType{
|
||||
Source: source, Name: kind,
|
||||
Rule: eventtype.Rule{Payload: []eventtype.PayloadCondition{{Path: "kind", Op: eventtype.OpEquals, Value: kind}}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEventType() error = %v", err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func armedBinding(t *testing.T, s *EDA, source, mappingID string) string {
|
||||
t.Helper()
|
||||
id, err := s.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "n", Matcher: binding.Matcher{Source: source}, MappingID: mappingID, Workflow: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding() error = %v", err)
|
||||
}
|
||||
if err := s.ApproveBinding(t.Context(), id); err != nil {
|
||||
t.Fatalf("ApproveBinding() error = %v", err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func captureOf(t *testing.T, s *EDA, source, body string) string {
|
||||
t.Helper()
|
||||
id, err := s.InsertCapture(t.Context(), storecontract.CapturedEvent{Source: source, Body: body}, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("InsertCapture() error = %v", err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func undispatchedIDs(t *testing.T, s *EDA, source string) map[string]bool {
|
||||
t.Helper()
|
||||
list, err := s.ListUndispatchedCaptures(t.Context(), []string{source}, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListUndispatchedCaptures() error = %v", err)
|
||||
}
|
||||
out := map[string]bool{}
|
||||
for _, c := range list {
|
||||
out[c.ID] = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestSeveralArmedBindingsShareASource(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
a := armedBinding(t, s, "github", "")
|
||||
b := armedBinding(t, s, "github", "")
|
||||
armed, err := s.ArmedBindingsForSource(t.Context(), "github")
|
||||
if err != nil {
|
||||
t.Fatalf("ArmedBindingsForSource() error = %v", err)
|
||||
}
|
||||
got := map[string]bool{}
|
||||
for _, x := range armed {
|
||||
got[x.ID] = true
|
||||
}
|
||||
if !got[a] || !got[b] || len(armed) != 2 {
|
||||
t.Fatalf("armed = %v, want both %s and %s", got, a, b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMappingAndBindingRoundTripEventTypeAndFilter(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
typeID := eventTypeFixture(t, s, "github", "push")
|
||||
mid, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m", EventTypeID: typeID})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
}
|
||||
m, err := s.GetMapping(t.Context(), mid)
|
||||
if err != nil || m.EventTypeID != typeID {
|
||||
t.Fatalf("GetMapping() event type = %q (err %v), want %q", m.EventTypeID, err, typeID)
|
||||
}
|
||||
bid, err := s.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "n", Matcher: binding.Matcher{Source: "github"}, MappingID: mid, Workflow: "implement",
|
||||
Filter: `kind == "push"`,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding() error = %v", err)
|
||||
}
|
||||
b, err := s.GetBinding(t.Context(), bid)
|
||||
if err != nil || b.Filter != `kind == "push"` {
|
||||
t.Fatalf("GetBinding() filter = %q (err %v)", b.Filter, err)
|
||||
}
|
||||
b.Filter = ""
|
||||
if err := s.UpdateBinding(t.Context(), *b); err != nil {
|
||||
t.Fatalf("UpdateBinding() error = %v", err)
|
||||
}
|
||||
if b, _ = s.GetBinding(t.Context(), bid); b.Filter != "" {
|
||||
t.Fatalf("filter after clearing = %q, want empty", b.Filter)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMappingMatchCountRisesOncePerEvent(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
mid, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m"})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
}
|
||||
before := time.Now().Add(-time.Minute)
|
||||
for _, capture := range []string{"c1", "c2", "c1"} {
|
||||
if err := s.RecordMappingMatch(t.Context(), mid, capture); err != nil {
|
||||
t.Fatalf("RecordMappingMatch(%s) error = %v", capture, err)
|
||||
}
|
||||
}
|
||||
list, err := s.ListMappings(t.Context())
|
||||
if err != nil || len(list) != 1 {
|
||||
t.Fatalf("ListMappings() = %d (err %v)", len(list), err)
|
||||
}
|
||||
if list[0].MatchCount != 2 {
|
||||
t.Errorf("MatchCount = %d, want 2 (one per distinct event)", list[0].MatchCount)
|
||||
}
|
||||
if !list[0].LastMatchedAt.After(before) {
|
||||
t.Errorf("LastMatchedAt = %v, want a recent time", list[0].LastMatchedAt)
|
||||
}
|
||||
got, _ := s.GetMapping(t.Context(), mid)
|
||||
if got.MatchCount != 2 {
|
||||
t.Errorf("GetMapping MatchCount = %d, want 2", got.MatchCount)
|
||||
}
|
||||
}
|
||||
|
||||
// A capture stays undispatched until every armed binding for its event type
|
||||
// has dispatched it; a binding for another event type does not hold it.
|
||||
func TestUndispatchedIsPerBinding(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
push := eventTypeFixture(t, s, "github", "push")
|
||||
issue := eventTypeFixture(t, s, "github", "issue")
|
||||
pushMap, _ := s.InsertMapping(t.Context(), mapping.Mapping{Name: "p", EventTypeID: push})
|
||||
issueMap, _ := s.InsertMapping(t.Context(), mapping.Mapping{Name: "i", EventTypeID: issue})
|
||||
a := armedBinding(t, s, "github", pushMap)
|
||||
b := armedBinding(t, s, "github", pushMap)
|
||||
c := armedBinding(t, s, "github", issueMap)
|
||||
|
||||
capture := captureOf(t, s, "github", `{"kind":"push"}`)
|
||||
if !undispatchedIDs(t, s, "github")[capture] {
|
||||
t.Fatal("new push capture not listed")
|
||||
}
|
||||
if err := s.RecordDispatch(t.Context(), a, 1, capture, 1); err != nil {
|
||||
t.Fatalf("RecordDispatch(a) error = %v", err)
|
||||
}
|
||||
if !undispatchedIDs(t, s, "github")[capture] {
|
||||
t.Fatal("capture dropped after one of two push bindings dispatched it")
|
||||
}
|
||||
if err := s.RecordDispatch(t.Context(), b, 1, capture, 2); err != nil {
|
||||
t.Fatalf("RecordDispatch(b) error = %v", err)
|
||||
}
|
||||
if undispatchedIDs(t, s, "github")[capture] {
|
||||
t.Fatalf("capture still listed after both push bindings dispatched it (issue binding %s must not hold it)", c)
|
||||
}
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
func githubType(name, event string) eventtype.EventType {
|
||||
return eventtype.EventType{
|
||||
Source: "gh", Name: name,
|
||||
Rule: eventtype.Rule{Headers: []eventtype.HeaderCondition{{Name: "X-GitHub-Event", Value: event}}},
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventTypeSaveRefusals(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
pushID, err := s.InsertEventType(t.Context(), githubType("push", "push"))
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEventType(push) error = %v", err)
|
||||
}
|
||||
prID, err := s.InsertEventType(t.Context(), githubType("pr", "pull_request"))
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEventType(pr) error = %v", err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
save func() error
|
||||
wantErr error
|
||||
}{
|
||||
{"insert overlapping rule", func() error {
|
||||
_, err := s.InsertEventType(t.Context(), githubType("push-again", "push"))
|
||||
return err
|
||||
}, eventtype.ErrOverlap},
|
||||
{"insert catch-all beside typed", func() error {
|
||||
_, err := s.InsertEventType(t.Context(), eventtype.EventType{Source: "gh", Name: "all"})
|
||||
return err
|
||||
}, eventtype.ErrOverlap},
|
||||
{"insert duplicate name", func() error {
|
||||
_, err := s.InsertEventType(t.Context(), githubType("push", "issues"))
|
||||
return err
|
||||
}, eventtype.ErrInvalid},
|
||||
{"insert without name", func() error {
|
||||
_, err := s.InsertEventType(t.Context(), githubType("", "issues"))
|
||||
return err
|
||||
}, eventtype.ErrInvalid},
|
||||
{"update into overlap", func() error {
|
||||
pr := githubType("pr", "push")
|
||||
pr.ID = prID
|
||||
return s.UpdateEventType(t.Context(), pr)
|
||||
}, eventtype.ErrOverlap},
|
||||
{"update missing", func() error {
|
||||
missing := githubType("x", "x")
|
||||
missing.ID = "missing"
|
||||
return s.UpdateEventType(t.Context(), missing)
|
||||
}, storecontract.ErrEventTypeNotFound},
|
||||
{"delete missing", func() error { return s.DeleteEventType(t.Context(), "missing") }, storecontract.ErrEventTypeNotFound},
|
||||
{"other source is independent", func() error {
|
||||
_, err := s.InsertEventType(t.Context(), eventtype.EventType{Source: "fw", Name: "all"})
|
||||
return err
|
||||
}, nil},
|
||||
{"update keeps itself out of the overlap check", func() error {
|
||||
push := githubType("push-renamed", "push")
|
||||
push.ID = pushID
|
||||
return s.UpdateEventType(t.Context(), push)
|
||||
}, nil},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := tt.save()
|
||||
if tt.wantErr == nil && err != nil {
|
||||
t.Fatalf("error = %v, want nil", err)
|
||||
}
|
||||
if tt.wantErr != nil && !errors.Is(err, tt.wantErr) {
|
||||
t.Fatalf("error = %v, want %v", err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
types, err := s.ListEventTypes(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("ListEventTypes() error = %v", err)
|
||||
}
|
||||
names := map[string]bool{}
|
||||
for _, et := range types {
|
||||
names[et.Source+"/"+et.Name] = true
|
||||
}
|
||||
for _, want := range []string{"gh/push-renamed", "gh/pr", "fw/all"} {
|
||||
if !names[want] {
|
||||
t.Errorf("ListEventTypes() lacks %s: %v", want, names)
|
||||
}
|
||||
}
|
||||
if len(types) != 3 {
|
||||
t.Errorf("ListEventTypes() = %d types, want 3", len(types))
|
||||
}
|
||||
}
|
||||
|
||||
// A type made from a pasted payload has that payload's schema, and a later
|
||||
// matching capture is identified as it and becomes dispatchable; a capture
|
||||
// matching no type stays unidentified and is never listed for dispatch.
|
||||
func TestPastedTypeIdentifiesLaterCaptures(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
pasted := eventtype.Sample{
|
||||
Headers: map[string]string{"X-GitHub-Event": "pull_request"},
|
||||
Body: []byte(`{"action":"opened","number":1}`),
|
||||
}
|
||||
id, err := s.InsertEventType(t.Context(), eventtype.FromExample("gh", "pull_request", pasted))
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEventType() error = %v", err)
|
||||
}
|
||||
types, err := s.ListEventTypes(t.Context())
|
||||
if err != nil || len(types) != 1 {
|
||||
t.Fatalf("ListEventTypes() = %v (err %v)", types, err)
|
||||
}
|
||||
if got := types[0].Schema; got["action"] != eventtype.TypeString || got["number"] != eventtype.TypeNumber {
|
||||
t.Fatalf("schema = %v, want the pasted payload's", got)
|
||||
}
|
||||
|
||||
for _, c := range []storecontract.CapturedEvent{
|
||||
{Source: "gh", Headers: `{"X-Github-Event":["pull_request"]}`, Body: `{"action":"closed","number":9}`},
|
||||
{Source: "gh", Headers: `{"X-Github-Event":["push"]}`, Body: `{"ref":"main"}`},
|
||||
} {
|
||||
if _, err := s.InsertCapture(t.Context(), c, 0, 0); err != nil {
|
||||
t.Fatalf("InsertCapture() error = %v", err)
|
||||
}
|
||||
}
|
||||
all, err := s.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures() error = %v", err)
|
||||
}
|
||||
byBody := map[string]string{}
|
||||
for _, c := range all {
|
||||
byBody[c.Body] = c.EventType
|
||||
}
|
||||
if byBody[`{"action":"closed","number":9}`] != id {
|
||||
t.Errorf("matching capture event type = %q, want %q", byBody[`{"action":"closed","number":9}`], id)
|
||||
}
|
||||
if byBody[`{"ref":"main"}`] != "" {
|
||||
t.Errorf("unmatched capture event type = %q, want unidentified", byBody[`{"ref":"main"}`])
|
||||
}
|
||||
|
||||
mid, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m", EventTypeID: id})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
}
|
||||
armedBinding(t, s, "gh", mid)
|
||||
undispatched, err := s.ListUndispatchedCaptures(t.Context(), []string{"gh"}, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListUndispatchedCaptures() error = %v", err)
|
||||
}
|
||||
if len(undispatched) != 1 || undispatched[0].EventType != id {
|
||||
t.Fatalf("ListUndispatchedCaptures() = %+v, want only the identified capture", undispatched)
|
||||
}
|
||||
}
|
||||
@@ -1,213 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/bindingcipher"
|
||||
)
|
||||
|
||||
const edaTestKey = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
|
||||
|
||||
// edaFor builds an EDA store over a migrated database, with no cipher.
|
||||
func edaFor(t *testing.T) *EDA {
|
||||
t.Helper()
|
||||
pool, _ := migrated(t)
|
||||
return NewEDA(pool, nil)
|
||||
}
|
||||
|
||||
func edaWithCipher(t *testing.T, cipher bindingcipher.BindingCipher) (*pgxpool.Pool, *EDA) {
|
||||
t.Helper()
|
||||
pool, _ := migrated(t)
|
||||
return pool, NewEDA(pool, cipher)
|
||||
}
|
||||
|
||||
func insertBinding(t *testing.T, s *EDA, source string) string {
|
||||
t.Helper()
|
||||
id, err := s.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "n", Matcher: binding.Matcher{Source: source}, Workflow: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding() error = %v", err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Hazard 2: unique-violation detection must be by SQLSTATE, not by grepping
|
||||
// the driver's error text. A Postgres error whose message happens to contain
|
||||
// "unique" but whose SQLSTATE is not 23505 must not be treated as one, and a
|
||||
// 23505 with a message lacking those words must be detected.
|
||||
func TestIsUniqueViolationDetectsBySQLState(t *testing.T) {
|
||||
if !isUniqueViolation(&pgconn.PgError{Code: "23505", Message: "duplicate key value"}) {
|
||||
t.Error("SQLSTATE 23505 was not detected as a unique violation")
|
||||
}
|
||||
if isUniqueViolation(&pgconn.PgError{Code: "23502", Message: "null value in column of a unique constraint"}) {
|
||||
t.Error("a non-23505 error whose text says unique was treated as a unique violation; SQLSTATE is authoritative")
|
||||
}
|
||||
if isUniqueViolation(errors.New("not a database error")) {
|
||||
t.Error("a non-Postgres error was treated as a unique violation")
|
||||
}
|
||||
}
|
||||
|
||||
// Hazard 2 (integration): the dispatch ledger is at-most-once, refused by the
|
||||
// schema and surfaced as ErrAlreadyDispatched.
|
||||
func TestRecordDispatchIsIdempotent(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
if err := s.RecordDispatch(t.Context(), "b1", 1, "c1", 42); err != nil {
|
||||
t.Fatalf("first RecordDispatch() error = %v", err)
|
||||
}
|
||||
if err := s.RecordDispatch(t.Context(), "b1", 1, "c1", 99); !errors.Is(err, storecontract.ErrAlreadyDispatched) {
|
||||
t.Errorf("second RecordDispatch() error = %v, want ErrAlreadyDispatched", err)
|
||||
}
|
||||
}
|
||||
|
||||
// binding_version is stored but deliberately not part of the unique key: a
|
||||
// version bump does not permit re-dispatching the same (binding, capture).
|
||||
func TestBindingDispatchVersionBumpDoesNotPermitRedispatch(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
if err := s.RecordDispatch(t.Context(), "b1", 1, "c1", 42); err != nil {
|
||||
t.Fatalf("first RecordDispatch() error = %v", err)
|
||||
}
|
||||
if err := s.RecordDispatch(t.Context(), "b1", 2, "c1", 99); !errors.Is(err, storecontract.ErrAlreadyDispatched) {
|
||||
t.Errorf("redispatch with a version bump = %v, want ErrAlreadyDispatched: binding_version is not part of the key", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlaybookDispatchIsIdempotent(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
if err := s.RecordPlaybookDispatch(t.Context(), "p1", "v1", "e1", "a1"); err != nil {
|
||||
t.Fatalf("first RecordPlaybookDispatch() error = %v", err)
|
||||
}
|
||||
if err := s.RecordPlaybookDispatch(t.Context(), "p1", "v1", "e1", "a1"); !errors.Is(err, storecontract.ErrAlreadyDispatched) {
|
||||
t.Errorf("second RecordPlaybookDispatch() error = %v, want ErrAlreadyDispatched", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The lifecycle gate survives the port: pending_approval -> armed, and only
|
||||
// from pending_approval.
|
||||
func TestBindingLifecycle(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
id := insertBinding(t, s, "src-lifecycle")
|
||||
|
||||
if err := s.ApproveBinding(t.Context(), id); err != nil {
|
||||
t.Fatalf("ApproveBinding(pending_approval) error = %v", err)
|
||||
}
|
||||
if err := s.ApproveBinding(t.Context(), id); !errors.Is(err, storecontract.ErrBindingTransition) {
|
||||
t.Errorf("re-approving an armed binding = %v, want ErrBindingTransition", err)
|
||||
}
|
||||
armed, err := s.ArmedBindingsForSource(t.Context(), "src-lifecycle")
|
||||
if err != nil || len(armed) != 1 {
|
||||
t.Fatalf("ArmedBindingsForSource() = %d bindings (err %v), want 1", len(armed), err)
|
||||
}
|
||||
}
|
||||
|
||||
// A capture round-trips its payload verbatim.
|
||||
func TestCaptureRoundTrip(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
body := `{"action":"created"}`
|
||||
if _, err := s.InsertCapture(t.Context(), storecontract.CapturedEvent{
|
||||
Source: "sentry", Body: body, Headers: `{"X-Hook":"1"}`, ContentType: "application/json",
|
||||
}, 0, 0); err != nil {
|
||||
t.Fatalf("InsertCapture() error = %v", err)
|
||||
}
|
||||
list, err := s.ListCaptures(t.Context(), 10)
|
||||
if err != nil || len(list) != 1 {
|
||||
t.Fatalf("ListCaptures() = %d (err %v), want 1", len(list), err)
|
||||
}
|
||||
if list[0].Body != body {
|
||||
t.Errorf("Body round-trip = %q, want %q", list[0].Body, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMappingCRUD(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
id, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "payload-map"})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
}
|
||||
got, err := s.GetMapping(t.Context(), id)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("GetMapping() = %v (err %v), want the mapping", got, err)
|
||||
}
|
||||
if got.Name != "payload-map" {
|
||||
t.Errorf("Name = %q, want payload-map", got.Name)
|
||||
}
|
||||
got.Name = "renamed"
|
||||
if err := s.UpdateMapping(t.Context(), *got); err != nil {
|
||||
t.Fatalf("UpdateMapping() error = %v", err)
|
||||
}
|
||||
if err := s.DeleteMapping(t.Context(), id); err != nil {
|
||||
t.Fatalf("DeleteMapping() error = %v", err)
|
||||
}
|
||||
if err := s.DeleteMapping(t.Context(), id); !errors.Is(err, storecontract.ErrMappingNotFound) {
|
||||
t.Errorf("DeleteMapping(absent) = %v, want ErrMappingNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The Notify callback is an injected seam, not a LISTEN/NOTIFY path: a store
|
||||
// wired with one fires a change event per successful bindings/mappings write,
|
||||
// and one wired with none is a silent no-op.
|
||||
func TestNotifyCallbackIsAnInjectedSeam(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
var got []events.Event
|
||||
s.SetNotify(func(e events.Event) { got = append(got, e) })
|
||||
|
||||
id, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "wired"})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
}
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("notified %d times, want 1", len(got))
|
||||
}
|
||||
if got[0].Data["id"] != id || got[0].Data["action"] != "create" {
|
||||
t.Errorf("event data = %+v, want id=%q action=create", got[0].Data, id)
|
||||
}
|
||||
|
||||
// A store composed without a notifier is a silent no-op.
|
||||
s.SetNotify(nil)
|
||||
if _, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "silent"}); err != nil {
|
||||
t.Fatalf("InsertMapping(nil notifier) error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// tool_calls is an append-only transcript with no unique index: repeated rows
|
||||
// are distinct entries, and one task's calls never surface in another's.
|
||||
func TestToolCallRoundTrip(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
at := time.Date(2026, 9, 23, 1, 2, 3, 0, time.UTC)
|
||||
|
||||
for range 2 {
|
||||
if err := s.InsertToolCall(t.Context(), ToolCall{
|
||||
TaskID: 42, Attempt: 2, Tool: "shell", Result: "all checks passed", CalledAt: at,
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertToolCall() error = %v", err)
|
||||
}
|
||||
}
|
||||
if err := s.InsertToolCall(t.Context(), ToolCall{
|
||||
TaskID: 7, Attempt: 1, Tool: "read_file", Error: "no such file", CalledAt: at.Add(time.Second),
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertToolCall(other task) error = %v", err)
|
||||
}
|
||||
|
||||
got, err := s.TaskToolCalls(t.Context(), 42)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskToolCalls() error = %v", err)
|
||||
}
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("TaskToolCalls() returned %d rows, want 2 (the transcript is append-only)", len(got))
|
||||
}
|
||||
if got[0].Result != "all checks passed" || got[0].Error != "" {
|
||||
t.Errorf("first row result/error = %q/%q, want the summary with no error", got[0].Result, got[0].Error)
|
||||
}
|
||||
if got[0].CalledAt.IsZero() {
|
||||
t.Error("called_at did not round-trip")
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
||||
)
|
||||
|
||||
// TestEventInsertsCommitInIDOrder pins the event-append lock: an insert
|
||||
// waits while another transaction holds an uncommitted event, so a reader
|
||||
// paging by (at, id) never sees a later id commit before an earlier one.
|
||||
func TestEventInsertsCommitInIDOrder(t *testing.T) {
|
||||
pool, _ := migrated(t)
|
||||
st := New(pool)
|
||||
|
||||
tx, err := pool.Begin(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("Begin: %v", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(t.Context()) }()
|
||||
firstID, err := insertEventQ(t.Context(), postgresdb.New(tx), events.Event{Kind: "first"})
|
||||
if err != nil {
|
||||
t.Fatalf("insert in tx: %v", err)
|
||||
}
|
||||
|
||||
type result struct {
|
||||
id int64
|
||||
err error
|
||||
}
|
||||
done := make(chan result, 1)
|
||||
go func() {
|
||||
id, err := st.InsertEvent(t.Context(), events.Event{Kind: "second"})
|
||||
done <- result{id, err}
|
||||
}()
|
||||
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for {
|
||||
var waiting int
|
||||
if err := pool.QueryRow(t.Context(),
|
||||
"SELECT count(*) FROM pg_locks WHERE locktype = 'advisory' AND NOT granted").Scan(&waiting); err != nil {
|
||||
t.Fatalf("pg_locks: %v", err)
|
||||
}
|
||||
if waiting > 0 {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case r := <-done:
|
||||
t.Fatalf("second insert returned (id %d, err %v) while the first was uncommitted; want it to wait", r.id, r.err)
|
||||
default:
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("second insert never waited on the event-append lock")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
|
||||
if visible, err := st.EventsSince(t.Context(), "", 10); err != nil || len(visible) != 0 {
|
||||
t.Fatalf("EventsSince while the first insert is uncommitted = %d events, %v; want none", len(visible), err)
|
||||
}
|
||||
if err := tx.Commit(t.Context()); err != nil {
|
||||
t.Fatalf("Commit: %v", err)
|
||||
}
|
||||
r := <-done
|
||||
if r.err != nil {
|
||||
t.Fatalf("second insert: %v", r.err)
|
||||
}
|
||||
if r.id <= firstID {
|
||||
t.Fatalf("second id %d, want greater than first id %d", r.id, firstID)
|
||||
}
|
||||
all, err := st.EventsSince(t.Context(), "", 10)
|
||||
if err != nil {
|
||||
t.Fatalf("EventsSince: %v", err)
|
||||
}
|
||||
if len(all) != 2 || all[0].Kind != "first" || all[1].Kind != "second" {
|
||||
t.Fatalf("EventsSince after both commit = %+v, want first then second", all)
|
||||
}
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/harnesssecret"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/bindingcipher"
|
||||
)
|
||||
|
||||
func readRawHarnessSecret(t *testing.T, pool *pgxpool.Pool, org, service string) string {
|
||||
t.Helper()
|
||||
var stored string
|
||||
err := pool.QueryRow(t.Context(), "SELECT secret_enc FROM harness_secrets WHERE org = $1 AND service = $2", org, service).Scan(&stored)
|
||||
if err != nil {
|
||||
t.Fatalf("read raw harness secret: %v", err)
|
||||
}
|
||||
return stored
|
||||
}
|
||||
|
||||
// A stored OAuth token set is a cipher envelope on disk and reads back as
|
||||
// plaintext, and the column never holds the raw access or refresh token.
|
||||
func TestHarnessSecretRoundTripEncrypts(t *testing.T) {
|
||||
cipher, err := bindingcipher.NewBindingCipher(edaTestKey, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher() error = %v", err)
|
||||
}
|
||||
pool, s := edaWithCipher(t, cipher)
|
||||
in := harnesssecret.Secret{
|
||||
Org: "org-1", Service: "claude-code",
|
||||
AccessToken: "at-0123456789abcdef", RefreshToken: "rt-0123456789abcdef",
|
||||
TokenType: "Bearer", ExpiresAt: time.Now().Add(time.Hour).UTC().Truncate(time.Second),
|
||||
Scopes: []string{"user:inference", "user:profile"},
|
||||
}
|
||||
if err := s.PutHarnessSecret(t.Context(), in); err != nil {
|
||||
t.Fatalf("PutHarnessSecret() error = %v", err)
|
||||
}
|
||||
raw := readRawHarnessSecret(t, pool, in.Org, in.Service)
|
||||
if raw == "" {
|
||||
t.Fatal("stored secret is empty")
|
||||
}
|
||||
for _, want := range []string{in.AccessToken, in.RefreshToken} {
|
||||
if strings.Contains(raw, want) {
|
||||
t.Fatalf("stored column contains a real token: %q", raw)
|
||||
}
|
||||
}
|
||||
got, err := s.GetHarnessSecret(t.Context(), in.Org, in.Service)
|
||||
if err != nil {
|
||||
t.Fatalf("GetHarnessSecret() error = %v", err)
|
||||
}
|
||||
if got.AccessToken != in.AccessToken || got.RefreshToken != in.RefreshToken ||
|
||||
got.TokenType != in.TokenType || !got.ExpiresAt.Equal(in.ExpiresAt) ||
|
||||
!slices.Equal(got.Scopes, in.Scopes) {
|
||||
t.Fatalf("GetHarnessSecret() = %+v, want %+v", got, in)
|
||||
}
|
||||
}
|
||||
|
||||
// A refresh (a second Put for the same org/service) overwrites the row
|
||||
// rather than accumulating one per token: exactly the upsert semantics the
|
||||
// egress proxy's every refresh depends on.
|
||||
func TestHarnessSecretPutOverwritesOnRefresh(t *testing.T) {
|
||||
cipher, err := bindingcipher.NewBindingCipher(edaTestKey, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, s := edaWithCipher(t, cipher)
|
||||
org, service := "org-1", "claude-code"
|
||||
first := harnesssecret.Secret{Org: org, Service: service, AccessToken: "at-first", RefreshToken: "rt-first"}
|
||||
if err := s.PutHarnessSecret(t.Context(), first); err != nil {
|
||||
t.Fatalf("PutHarnessSecret(first) error = %v", err)
|
||||
}
|
||||
second := harnesssecret.Secret{Org: org, Service: service, AccessToken: "at-second", RefreshToken: "rt-second"}
|
||||
if err := s.PutHarnessSecret(t.Context(), second); err != nil {
|
||||
t.Fatalf("PutHarnessSecret(second) error = %v", err)
|
||||
}
|
||||
got, err := s.GetHarnessSecret(t.Context(), org, service)
|
||||
if err != nil {
|
||||
t.Fatalf("GetHarnessSecret() error = %v", err)
|
||||
}
|
||||
if got.AccessToken != second.AccessToken {
|
||||
t.Fatalf("AccessToken = %q, want the refreshed value %q", got.AccessToken, second.AccessToken)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHarnessSecretNotFound(t *testing.T) {
|
||||
_, s := edaWithCipher(t, nil)
|
||||
_, err := s.GetHarnessSecret(t.Context(), "org-1", "no-such-service")
|
||||
if !errors.Is(err, storecontract.ErrHarnessSecretNotFound) {
|
||||
t.Fatalf("GetHarnessSecret() error = %v, want ErrHarnessSecretNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHarnessSecretPutRejectsIncomplete(t *testing.T) {
|
||||
_, s := edaWithCipher(t, nil)
|
||||
if err := s.PutHarnessSecret(t.Context(), harnesssecret.Secret{Org: "org-1"}); err == nil {
|
||||
t.Fatal("PutHarnessSecret() with no service or access token succeeded, want error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHarnessSecretRequiresEncryption(t *testing.T) {
|
||||
pool, store := edaWithCipher(t, nil)
|
||||
err := store.PutHarnessSecret(t.Context(), harnesssecret.Secret{Org: "org", Service: "service", AccessToken: "access"})
|
||||
if err == nil {
|
||||
t.Fatal("OAuth token stored without an encryption key")
|
||||
}
|
||||
var count int
|
||||
if err := pool.QueryRow(t.Context(), "SELECT count(*) FROM harness_secrets").Scan(&count); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Fatalf("stored %d rows without encryption", count)
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storepkg"
|
||||
)
|
||||
|
||||
func TestInstalledPackagesOrgPinsAndDependencies(t *testing.T) {
|
||||
pool, _ := migrated(t)
|
||||
s := NewInstalledPackages(pool)
|
||||
ctx := t.Context()
|
||||
const digest = "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
||||
base := storepkg.Descriptor{
|
||||
APIVersion: storepkg.APIVersion, DisplayName: "Kit", Version: "1",
|
||||
Contributes: storepkg.Contributions{Skills: []string{"skill"}},
|
||||
}
|
||||
kit := storepkg.Installed{OrgID: "org-a", Name: "kit", Reference: "localhost:5000/kit", Digest: digest, Descriptor: base, Layer: []byte("kit"), UpdatePolicy: "manual"}
|
||||
review := storepkg.Installed{OrgID: "org-a", Name: "review", Reference: "localhost:5000/review", Digest: digest, Descriptor: base, Layer: []byte("review"), UpdatePolicy: "manual"}
|
||||
review.Descriptor.Requires = []storepkg.PackageRef{{Name: "kit", Digest: digest}}
|
||||
|
||||
if err := s.Install(ctx, review); !errors.Is(err, storepkg.ErrNotFound) {
|
||||
t.Fatalf("missing dependency: %v", err)
|
||||
}
|
||||
if err := s.Install(ctx, kit); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Install(ctx, review); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Install(ctx, review); !errors.Is(err, storepkg.ErrInstalled) {
|
||||
t.Fatalf("duplicate install: %v", err)
|
||||
}
|
||||
if _, err := s.Get(ctx, "org-b", "kit"); !errors.Is(err, storepkg.ErrNotFound) {
|
||||
t.Fatalf("cross-org get: %v", err)
|
||||
}
|
||||
if list, err := s.List(ctx, "org-b"); err != nil || len(list) != 0 {
|
||||
t.Fatalf("cross-org list: %v, %v", list, err)
|
||||
}
|
||||
if err := s.Remove(ctx, "org-a", "kit"); !errors.Is(err, storepkg.ErrRequired) {
|
||||
t.Fatalf("remove required package: %v", err)
|
||||
}
|
||||
if err := s.Remove(ctx, "org-a", "review"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Remove(ctx, "org-a", "kit"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Remove(ctx, "org-a", "kit"); !errors.Is(err, storepkg.ErrNotFound) {
|
||||
t.Fatalf("remove missing: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -1,302 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestLibpqTargetKeepsThePasswordOffTheCommandLine(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
url string
|
||||
wantDB string
|
||||
wantEnv []string
|
||||
leakFree string
|
||||
}{
|
||||
{
|
||||
name: "url with password",
|
||||
url: "postgres://archie:s3cret@db.example:5432/archie?sslmode=require",
|
||||
wantDB: "postgres://archie@db.example:5432/archie?sslmode=require",
|
||||
wantEnv: []string{"PGPASSWORD=s3cret"},
|
||||
leakFree: "s3cret",
|
||||
},
|
||||
{
|
||||
name: "url without password",
|
||||
url: "postgresql://archie@db.example/archie",
|
||||
wantDB: "postgresql://archie@db.example/archie",
|
||||
},
|
||||
{
|
||||
name: "key value connection string passes through",
|
||||
url: "host=db.example dbname=archie",
|
||||
wantDB: "host=db.example dbname=archie",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
db, env := libpqTarget(tt.url)
|
||||
if db != tt.wantDB {
|
||||
t.Errorf("dbname = %q, want %q", db, tt.wantDB)
|
||||
}
|
||||
if !slices.Equal(env, tt.wantEnv) {
|
||||
t.Errorf("env = %q, want %q", env, tt.wantEnv)
|
||||
}
|
||||
if tt.leakFree != "" && strings.Contains(db, tt.leakFree) {
|
||||
t.Errorf("dbname %q carries the password", db)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolArguments(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
got []string
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "dump is a whole-database custom-format archive",
|
||||
got: dumpArgs("postgres://h/db", "/tmp/out.dump"),
|
||||
want: []string{"--format=custom", "--no-password", "--file=/tmp/out.dump", "--dbname=postgres://h/db"},
|
||||
},
|
||||
{
|
||||
name: "restore cleans, stops on the first error and is atomic",
|
||||
got: restoreArgs("postgres://h/db", "/tmp/in.dump"),
|
||||
want: []string{"--clean", "--if-exists", "--single-transaction", "--exit-on-error", "--no-owner", "--no-password", "--dbname=postgres://h/db", "/tmp/in.dump"},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if !slices.Equal(tt.got, tt.want) {
|
||||
t.Errorf("args = %q, want %q", tt.got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotTablesReadsTheArchiveList(t *testing.T) {
|
||||
list := `;
|
||||
; Archive created at 2026-09-24 10:00:00 UTC
|
||||
;
|
||||
215; 1259 16390 TABLE public tasks archie
|
||||
216; 1259 16391 SEQUENCE public tasks_id_seq archie
|
||||
3401; 0 16390 TABLE DATA public tasks archie
|
||||
217; 1259 16400 TABLE public goose_db_version archie
|
||||
`
|
||||
got := snapshotTables(list)
|
||||
want := []string{"public.goose_db_version", "public.tasks"}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("snapshotTables = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func requireTools(t *testing.T) {
|
||||
t.Helper()
|
||||
for _, tool := range []string{"pg_dump", "pg_restore"} {
|
||||
if _, err := exec.LookPath(tool); err != nil {
|
||||
t.Skipf("%s is not on PATH; the integration test needs the PostgreSQL 18 client tools", tool)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// migratedURL is a migrated database and a pool on it.
|
||||
func migratedURL(t *testing.T) (string, *pgxpool.Pool) {
|
||||
t.Helper()
|
||||
url := pgtest.URL(t)
|
||||
pool := openPool(t, url)
|
||||
if err := Migrate(t.Context(), pool, Migrations()); err != nil {
|
||||
t.Fatalf("Migrate: %v", err)
|
||||
}
|
||||
return url, pool
|
||||
}
|
||||
|
||||
func titles(t *testing.T, pool *pgxpool.Pool) []string {
|
||||
t.Helper()
|
||||
rows, err := pool.Query(t.Context(), "SELECT title FROM tasks ORDER BY id")
|
||||
if err != nil {
|
||||
t.Fatalf("list tasks: %v", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []string
|
||||
for rows.Next() {
|
||||
var title string
|
||||
if err := rows.Scan(&title); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out = append(out, title)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func enqueue(t *testing.T, pool *pgxpool.Pool, title string) {
|
||||
t.Helper()
|
||||
if _, err := New(pool).EnqueueChatTask(t.Context(), "acme", "widget", title, "body", "implement", "", nil); err != nil {
|
||||
t.Fatalf("enqueue %q: %v", title, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A restore after a forward migration is the case restore exists for: the
|
||||
// tables the later migration added are not in the snapshot, so --clean alone
|
||||
// would leave them behind for the next upgrade to trip over.
|
||||
func TestBackupThenRestoreReturnsTheDatabaseToTheSnapshot(t *testing.T) {
|
||||
requireTools(t)
|
||||
url, pool := migratedURL(t)
|
||||
enqueue(t, pool, "before")
|
||||
before, err := SchemaVersion(t.Context(), pool)
|
||||
if err != nil {
|
||||
t.Fatalf("SchemaVersion: %v", err)
|
||||
}
|
||||
snapshot := filepath.Join(t.TempDir(), "snapshot.dump")
|
||||
if err := Backup(t.Context(), url, snapshot); err != nil {
|
||||
t.Fatalf("Backup: %v", err)
|
||||
}
|
||||
if leftovers, _ := filepath.Glob(snapshot + ".tmp*"); len(leftovers) != 0 {
|
||||
t.Errorf("backup left scratch files: %v", leftovers)
|
||||
}
|
||||
|
||||
enqueue(t, pool, "after")
|
||||
if _, err := pool.Exec(t.Context(), "CREATE TABLE later_migration (id bigint)"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(t.Context(), "INSERT INTO goose_db_version (version_id, is_applied) VALUES ($1, true)", before+1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := Restore(t.Context(), url, snapshot); err != nil {
|
||||
t.Fatalf("Restore: %v", err)
|
||||
}
|
||||
if got := titles(t, pool); !slices.Equal(got, []string{"before"}) {
|
||||
t.Errorf("tasks after restore = %q, want only the snapshot's", got)
|
||||
}
|
||||
var extra bool
|
||||
if err := pool.QueryRow(t.Context(), "SELECT to_regclass('public.later_migration') IS NOT NULL").Scan(&extra); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if extra {
|
||||
t.Error("restore left a table the snapshot does not contain")
|
||||
}
|
||||
if after, err := SchemaVersion(t.Context(), pool); err != nil || after != before {
|
||||
t.Errorf("schema version after restore = %d, %v; want %d", after, err, before)
|
||||
}
|
||||
enqueue(t, pool, "writable")
|
||||
}
|
||||
|
||||
func TestRestoreRefusesWhileAnyServiceIsServing(t *testing.T) {
|
||||
requireTools(t)
|
||||
for _, owner := range ServiceOwners {
|
||||
t.Run(owner, func(t *testing.T) {
|
||||
url, pool := migratedURL(t)
|
||||
enqueue(t, pool, "snapshot")
|
||||
snapshot := filepath.Join(t.TempDir(), "snapshot.dump")
|
||||
if err := Backup(t.Context(), url, snapshot); err != nil {
|
||||
t.Fatalf("Backup: %v", err)
|
||||
}
|
||||
enqueue(t, pool, "live")
|
||||
claimOther(t, url, owner, false, false)
|
||||
|
||||
err := Restore(t.Context(), url, snapshot)
|
||||
if !errors.Is(err, ErrOwned) {
|
||||
t.Fatalf("Restore with %s serving = %v, want ErrOwned", owner, err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), owner) {
|
||||
t.Errorf("refusal must name the serving role %q: %v", owner, err)
|
||||
}
|
||||
if got := titles(t, pool); !slices.Equal(got, []string{"snapshot", "live"}) {
|
||||
t.Errorf("refused restore changed the database: %q", got)
|
||||
}
|
||||
// Every claim the refused restore took is dropped again.
|
||||
for _, other := range ServiceOwners {
|
||||
if other == owner {
|
||||
continue
|
||||
}
|
||||
claim, err := AcquireOwnership(t.Context(), pool, other)
|
||||
if err != nil {
|
||||
t.Fatalf("%s still held after a refused restore: %v", other, err)
|
||||
}
|
||||
_ = claim.Release(t.Context())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreRefusesWhatItCannotCheck(t *testing.T) {
|
||||
requireTools(t)
|
||||
url, pool := migratedURL(t)
|
||||
snapshot := filepath.Join(t.TempDir(), "snapshot.dump")
|
||||
if err := Backup(t.Context(), url, snapshot); err != nil {
|
||||
t.Fatalf("Backup: %v", err)
|
||||
}
|
||||
notASnapshot := filepath.Join(t.TempDir(), "garbage.dump")
|
||||
if err := os.WriteFile(notASnapshot, []byte("not an archive"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
enqueue(t, pool, "live")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
url string
|
||||
from string
|
||||
}{
|
||||
{name: "unreachable server", url: "postgres://archie:archie@127.0.0.1:1/none?connect_timeout=2", from: snapshot},
|
||||
{name: "not a snapshot", url: url, from: notASnapshot},
|
||||
{name: "missing snapshot", url: url, from: filepath.Join(t.TempDir(), "absent.dump")},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if err := Restore(t.Context(), tt.url, tt.from); err == nil {
|
||||
t.Fatal("Restore succeeded, want refusal")
|
||||
}
|
||||
if got := titles(t, pool); !slices.Equal(got, []string{"live"}) {
|
||||
t.Errorf("refused restore changed the database: %q", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBackupFailureKeepsThePreviousSnapshot(t *testing.T) {
|
||||
requireTools(t)
|
||||
out := filepath.Join(t.TempDir(), "snapshot.dump")
|
||||
if err := os.WriteFile(out, []byte("good snapshot"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := Backup(t.Context(), "postgres://archie:archie@127.0.0.1:1/none?connect_timeout=2", out); err == nil {
|
||||
t.Fatal("Backup of an unreachable database succeeded")
|
||||
}
|
||||
if data, _ := os.ReadFile(out); string(data) != "good snapshot" {
|
||||
t.Errorf("failed backup replaced the previous snapshot: %q", data)
|
||||
}
|
||||
if leftovers, _ := filepath.Glob(out + ".tmp*"); len(leftovers) != 0 {
|
||||
t.Errorf("failed backup left scratch files: %v", leftovers)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckSchemaVersion(t *testing.T) {
|
||||
supported := SupportedSchemaVersion()
|
||||
if supported < 4 {
|
||||
t.Fatalf("SupportedSchemaVersion = %d, want the highest embedded migration", supported)
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
version int64
|
||||
wantErr error
|
||||
}{
|
||||
{name: "current", version: supported},
|
||||
{name: "older is upgradable", version: 1},
|
||||
{name: "newer than this binary", version: supported + 1, wantErr: ErrSchemaTooNew},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if err := CheckSchemaVersion(tt.version); !errors.Is(err, tt.wantErr) {
|
||||
t.Fatalf("CheckSchemaVersion(%d) = %v, want %v", tt.version, err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,216 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func storeFor(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
pool := openPool(t, pgtest.URL(t))
|
||||
if err := Migrate(t.Context(), pool, Migrations()); err != nil {
|
||||
t.Fatalf("Migrate: %v", err)
|
||||
}
|
||||
return New(pool)
|
||||
}
|
||||
|
||||
// runningTask enqueues one issue and claims it, the state every park starts in.
|
||||
func runningTask(t *testing.T, s *Store) *workflow.Task {
|
||||
t.Helper()
|
||||
if _, err := s.EnqueueIssue(t.Context(), "acme", "widgets", 1, "t", "b", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := s.ClaimNext(t.Context())
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("ClaimNext = %v, %v", task, err)
|
||||
}
|
||||
return task
|
||||
}
|
||||
|
||||
type transitionRow struct{ from, to, detail string }
|
||||
|
||||
func transitions(t *testing.T, s *Store, taskID int64) []transitionRow {
|
||||
t.Helper()
|
||||
rows, err := s.pool.Query(t.Context(), "SELECT from_status, to_status, detail FROM transitions WHERE task_id = $1 ORDER BY id", taskID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []transitionRow
|
||||
for rows.Next() {
|
||||
var r transitionRow
|
||||
if err := rows.Scan(&r.from, &r.to, &r.detail); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Every free-text column the SQLite store clipped to 4000 bytes on a rune
|
||||
// boundary is clipped the same way here. The oversized value ends in a
|
||||
// multi-byte rune straddling the limit, so a byte cut would store invalid
|
||||
// UTF-8 and a missing clip would store all of it.
|
||||
func TestWritesClipFreeTextTo4000Bytes(t *testing.T) {
|
||||
oversized := strings.Repeat("x", 3999) + "é" + strings.Repeat("y", 1000)
|
||||
want := strings.Repeat("x", 3999)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
write func(t *testing.T, s *Store) string
|
||||
}{
|
||||
{name: "transition to parked: park reason and transition detail", write: func(t *testing.T, s *Store) string {
|
||||
task := runningTask(t, s)
|
||||
if err := s.Transition(t.Context(), task.ID, workflow.StatusRunning, workflow.StatusParked, oversized); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows := transitions(t, s, task.ID)
|
||||
if len(rows) == 0 || rows[len(rows)-1].detail != want {
|
||||
t.Errorf("transition detail not clipped: %d rows", len(rows))
|
||||
}
|
||||
got, _ := s.TaskByID(t.Context(), task.ID)
|
||||
return got.ParkReason
|
||||
}},
|
||||
{name: "park task: park reason and transition detail", write: func(t *testing.T, s *Store) string {
|
||||
task := runningTask(t, s)
|
||||
if err := s.ParkTask(t.Context(), task.ID, workflow.StatusRunning, oversized, "transient"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows := transitions(t, s, task.ID)
|
||||
if len(rows) == 0 || rows[len(rows)-1].detail != want {
|
||||
t.Errorf("transition detail not clipped: %d rows", len(rows))
|
||||
}
|
||||
got, _ := s.TaskByID(t.Context(), task.ID)
|
||||
return got.ParkReason
|
||||
}},
|
||||
{name: "update: park reason", write: func(t *testing.T, s *Store) string {
|
||||
task := runningTask(t, s)
|
||||
task.ParkReason = oversized
|
||||
if err := s.Update(t.Context(), task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ := s.TaskByID(t.Context(), task.ID)
|
||||
return got.ParkReason
|
||||
}},
|
||||
{name: "begin remediation: review payload", write: func(t *testing.T, s *Store) string {
|
||||
task := runningTask(t, s)
|
||||
if err := s.Transition(t.Context(), task.ID, workflow.StatusRunning, workflow.StatusPROpen, "pr"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.BeginRemediation(t.Context(), task.ID, oversized); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ := s.TaskByID(t.Context(), task.ID)
|
||||
return got.ReviewPayload
|
||||
}},
|
||||
{name: "update review payload", write: func(t *testing.T, s *Store) string {
|
||||
task := runningTask(t, s)
|
||||
if err := s.Transition(t.Context(), task.ID, workflow.StatusRunning, workflow.StatusPROpen, "pr"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.BeginRemediation(t.Context(), task.ID, "first"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.UpdateReviewPayload(t.Context(), task.ID, oversized); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ := s.TaskByID(t.Context(), task.ID)
|
||||
return got.ReviewPayload
|
||||
}},
|
||||
{name: "event detail", write: func(t *testing.T, s *Store) string {
|
||||
if _, err := s.InsertEvent(t.Context(), events.Event{Kind: events.KindLog, Detail: oversized}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := s.EventsSince(t.Context(), "", 1)
|
||||
if err != nil || len(got) != 1 {
|
||||
t.Fatalf("EventsSince = %d, %v", len(got), err)
|
||||
}
|
||||
return got[0].Detail
|
||||
}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := tt.write(t, storeFor(t))
|
||||
if got != want || !utf8.ValidString(got) {
|
||||
t.Errorf("stored %d bytes (valid UTF-8 %v), want the %d-byte rune-boundary clip", len(got), utf8.ValidString(got), len(want))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParkClassNormalisation(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
park func(ctx context.Context, s *Store, id int64) error
|
||||
want string
|
||||
}{
|
||||
{name: "generic transition to parked is needs_human", want: "needs_human", park: func(ctx context.Context, s *Store, id int64) error {
|
||||
return s.Transition(ctx, id, workflow.StatusRunning, workflow.StatusParked, "gate failed")
|
||||
}},
|
||||
{name: "known class is kept", want: "transient", park: func(ctx context.Context, s *Store, id int64) error {
|
||||
return s.ParkTask(ctx, id, workflow.StatusRunning, "container acquire failed", "transient")
|
||||
}},
|
||||
{name: "unknown class falls back to needs_human", want: "needs_human", park: func(ctx context.Context, s *Store, id int64) error {
|
||||
return s.ParkTask(ctx, id, workflow.StatusRunning, "x", "urgent")
|
||||
}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
task := runningTask(t, s)
|
||||
if err := tt.park(t.Context(), s, task.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ := s.TaskByID(t.Context(), task.ID)
|
||||
if got.Status != workflow.StatusParked || got.ParkClass != tt.want {
|
||||
t.Fatalf("status %q class %q, want parked %q", got.Status, got.ParkClass, tt.want)
|
||||
}
|
||||
// Requeue clears class and reason together: a stale class on a
|
||||
// queued task would group a live task with parked ones.
|
||||
if err := s.Requeue(t.Context(), task.ID, workflow.StatusParked, "implement"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ = s.TaskByID(t.Context(), task.ID)
|
||||
if got.ParkClass != "needs_human" || got.ParkReason != "" {
|
||||
t.Errorf("after requeue: class %q reason %q, want cleared", got.ParkClass, got.ParkReason)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A transition that leaves parked alone keeps the previous park fields, and
|
||||
// every guarded write leaves exactly one audit row in order.
|
||||
func TestTransitionsRecordEachMoveInOrder(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
task := runningTask(t, s)
|
||||
ctx := t.Context()
|
||||
if err := s.ParkTask(ctx, task.ID, workflow.StatusRunning, "why", "transient"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Requeue(ctx, task.ID, workflow.StatusParked, "implement"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A stale transition writes no audit row.
|
||||
if err := s.Transition(ctx, task.ID, workflow.StatusRunning, workflow.StatusPROpen, "stale"); err == nil {
|
||||
t.Fatal("stale Transition succeeded")
|
||||
}
|
||||
got := transitions(t, s, task.ID)
|
||||
want := []transitionRow{
|
||||
{workflow.StatusRunning, workflow.StatusParked, "why"},
|
||||
{workflow.StatusParked, workflow.StatusQueued, "requeued implement"},
|
||||
}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("transitions = %+v, want %+v", got, want)
|
||||
}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Errorf("transition %d = %+v, want %+v", i, got[i], want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
)
|
||||
|
||||
// newStoreForOrg is a migrated pool with the Store built over it.
|
||||
func newStoreForOrg(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
pool, _ := migrated(t)
|
||||
return New(pool)
|
||||
}
|
||||
|
||||
// seedAgent inserts one bot identity to assign.
|
||||
func seedAgent(t *testing.T, s *Store, name string) identity.Identity {
|
||||
t.Helper()
|
||||
value, err := identity.New(identity.StableID(name), identity.KindBot, name)
|
||||
if err != nil {
|
||||
t.Fatalf("identity.New(%s): %v", name, err)
|
||||
}
|
||||
created, err := s.Create(t.Context(), value, identity.Audit{
|
||||
ActorID: identity.SystemID, Source: "test", RequestID: "seed:" + name,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Create identity %s: %v", name, err)
|
||||
}
|
||||
return created
|
||||
}
|
||||
|
||||
func TestOrgRepository(t *testing.T) {
|
||||
s := newStoreForOrg(t)
|
||||
ctx := t.Context()
|
||||
|
||||
if _, err := s.CreateOrg(ctx, org.Org{ID: "soc", Name: "SOC"}); err != nil {
|
||||
t.Fatalf("CreateOrg: %v", err)
|
||||
}
|
||||
if _, err := s.CreateOrg(ctx, org.Org{ID: "soc", Name: "dup"}); !errors.Is(err, org.ErrOrgExists) {
|
||||
t.Fatalf("duplicate CreateOrg = %v, want ErrOrgExists", err)
|
||||
}
|
||||
if _, err := s.CreateOrg(ctx, org.Org{ID: "bad", Name: " "}); !errors.Is(err, org.ErrInvalidOrg) {
|
||||
t.Fatalf("blank-name CreateOrg = %v, want ErrInvalidOrg", err)
|
||||
}
|
||||
got, err := s.GetOrg(ctx, "soc")
|
||||
if err != nil {
|
||||
t.Fatalf("GetOrg: %v", err)
|
||||
}
|
||||
if got.Name != "SOC" {
|
||||
t.Fatalf("GetOrg = %+v, want name SOC", got)
|
||||
}
|
||||
if _, err := s.GetOrg(ctx, "missing"); !errors.Is(err, org.ErrOrgNotFound) {
|
||||
t.Fatalf("GetOrg(missing) = %v, want ErrOrgNotFound", err)
|
||||
}
|
||||
|
||||
ws, err := s.CreateWorkspace(ctx, org.Workspace{ID: "net", OrgID: "soc", Name: "networking-prd", Environment: "production"})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateWorkspace: %v", err)
|
||||
}
|
||||
if _, err := s.CreateWorkspace(ctx, ws); !errors.Is(err, org.ErrWorkspaceExists) {
|
||||
t.Fatalf("duplicate CreateWorkspace = %v, want ErrWorkspaceExists", err)
|
||||
}
|
||||
if _, err := s.CreateWorkspace(ctx, org.Workspace{ID: "x", OrgID: "missing", Name: "x"}); !errors.Is(err, org.ErrOrgNotFound) {
|
||||
t.Fatalf("CreateWorkspace(unknown org) = %v, want ErrOrgNotFound", err)
|
||||
}
|
||||
workspaces, err := s.ListWorkspaces(ctx, "soc")
|
||||
if err != nil || len(workspaces) != 1 || workspaces[0].ID != "net" {
|
||||
t.Fatalf("ListWorkspaces = %+v, %v; want one net", workspaces, err)
|
||||
}
|
||||
|
||||
member := seedAgent(t, s, "responder")
|
||||
if err := s.EnsureMembership(ctx, org.Membership{IdentityID: member.ID, OrgID: "soc", Role: org.RoleOwner}); err != nil {
|
||||
t.Fatalf("EnsureMembership: %v", err)
|
||||
}
|
||||
if err := s.EnsureMembership(ctx, org.Membership{IdentityID: member.ID, OrgID: "soc", Role: org.RoleOwner}); err != nil {
|
||||
t.Fatalf("repeated EnsureMembership: %v", err)
|
||||
}
|
||||
if err := s.EnsureMembership(ctx, org.Membership{OrgID: "soc", Role: org.RoleOwner}); !errors.Is(err, org.ErrInvalidMembership) {
|
||||
t.Fatalf("EnsureMembership(no identity) = %v, want ErrInvalidMembership", err)
|
||||
}
|
||||
missing := seedAgent(t, s, "ghost")
|
||||
if err := s.EnsureMembership(ctx, org.Membership{IdentityID: missing.ID, OrgID: "missing", Role: org.RoleOwner}); !errors.Is(err, org.ErrOrgNotFound) {
|
||||
t.Fatalf("EnsureMembership(unknown org) = %v, want ErrOrgNotFound", err)
|
||||
}
|
||||
|
||||
agent := seedAgent(t, s, "archie")
|
||||
if err := s.AssignAgent(ctx, org.AgentAssignment{IdentityID: agent.ID, OrgID: "soc"}); err != nil {
|
||||
t.Fatalf("AssignAgent: %v", err)
|
||||
}
|
||||
if err := s.AssignAgent(ctx, org.AgentAssignment{IdentityID: agent.ID, OrgID: "missing"}); !errors.Is(err, org.ErrOrgNotFound) {
|
||||
t.Fatalf("AssignAgent(unknown org) = %v, want ErrOrgNotFound", err)
|
||||
}
|
||||
resolved, err := s.OrgForIdentity(ctx, agent.ID)
|
||||
if err != nil || resolved != "soc" {
|
||||
t.Fatalf("OrgForIdentity(agent) = %s, %v; want soc", resolved, err)
|
||||
}
|
||||
|
||||
// An identity with only an org-wide membership resolves through it.
|
||||
// A person with only an org-wide membership resolves through it.
|
||||
person := seedAgent(t, s, "operator")
|
||||
if err := s.EnsureMembership(ctx, org.Membership{IdentityID: person.ID, OrgID: "soc", Role: org.RoleOwner}); err != nil {
|
||||
t.Fatalf("EnsureMembership: %v", err)
|
||||
}
|
||||
resolved, err = s.OrgForIdentity(ctx, person.ID)
|
||||
if err != nil || resolved != "soc" {
|
||||
t.Fatalf("OrgForIdentity(member) = %s, %v; want soc", resolved, err)
|
||||
}
|
||||
|
||||
// An identity in no org resolves to the default org.
|
||||
resolved, err = s.OrgForIdentity(ctx, "nobody")
|
||||
if err != nil || resolved != org.DefaultOrgID {
|
||||
t.Fatalf("OrgForIdentity(no org) = %s, %v; want default", resolved, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpgradeDefaultOrg(t *testing.T) {
|
||||
s := newStoreForOrg(t)
|
||||
ctx := t.Context()
|
||||
|
||||
// Records written before the upgrade: one with an empty org (the shape a
|
||||
// pre-column row lands in), one stamped by the default backfill.
|
||||
agent := seedAgent(t, s, "archie")
|
||||
if err := s.queries().InsertOrgUpgradePhase(ctx, "state_store"); err != nil {
|
||||
t.Fatalf("pre-insert ledger row: %v", err)
|
||||
}
|
||||
|
||||
// First run: completes both phases and is recorded.
|
||||
if err := s.UpgradeDefaultOrg(ctx); err != nil {
|
||||
t.Fatalf("UpgradeDefaultOrg: %v", err)
|
||||
}
|
||||
for _, phase := range []string{"state_store", "edastore"} {
|
||||
if _, err := s.queries().GetOrgUpgradePhase(ctx, phase); err != nil {
|
||||
t.Fatalf("phase %s not recorded: %v", phase, err)
|
||||
}
|
||||
}
|
||||
if _, err := s.GetOrg(ctx, org.DefaultOrgID); err != nil {
|
||||
t.Fatalf("default org missing after upgrade: %v", err)
|
||||
}
|
||||
workspaces, err := s.ListWorkspaces(ctx, org.DefaultOrgID)
|
||||
if err != nil || len(workspaces) != 1 || workspaces[0].ID != org.DefaultWorkspaceID {
|
||||
t.Fatalf("default workspace missing after upgrade: %+v, %v", workspaces, err)
|
||||
}
|
||||
resolved, err := s.OrgForIdentity(ctx, agent.ID)
|
||||
if err != nil || resolved != org.DefaultOrgID {
|
||||
t.Fatalf("agent org after upgrade = %s, %v; want default", resolved, err)
|
||||
}
|
||||
|
||||
// A second run is a no-op: recorded phases are never re-run.
|
||||
if err := s.UpgradeDefaultOrg(ctx); err != nil {
|
||||
t.Fatalf("second UpgradeDefaultOrg: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpgradeStampsEmptyOrg(t *testing.T) {
|
||||
pool, _ := migrated(t)
|
||||
s := New(pool)
|
||||
ctx := t.Context()
|
||||
|
||||
// Rows with an empty org, as a write between migration and upgrade would
|
||||
// leave them: one on each phase's side of the ledger.
|
||||
for _, stmt := range []string{
|
||||
"INSERT INTO resources (kind, value, version, updated_at, org_id) VALUES ('workflow:legacy', 'v', 1, now(), '')",
|
||||
"INSERT INTO bindings (id, name, source, secret) VALUES ('b1', 'b', 'src', '')",
|
||||
"UPDATE bindings SET org_id = '' WHERE id = 'b1'",
|
||||
} {
|
||||
if _, err := pool.Exec(ctx, stmt); err != nil {
|
||||
t.Fatalf("seed %q: %v", stmt, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.UpgradeDefaultOrg(ctx); err != nil {
|
||||
t.Fatalf("UpgradeDefaultOrg: %v", err)
|
||||
}
|
||||
var stamped string
|
||||
if err := pool.QueryRow(ctx, "SELECT org_id FROM resources WHERE kind = 'workflow:legacy'").Scan(&stamped); err != nil || stamped != "default" {
|
||||
t.Fatalf("resource org after upgrade = %q, %v; want default", stamped, err)
|
||||
}
|
||||
if err := pool.QueryRow(ctx, "SELECT org_id, workspace_id FROM bindings WHERE id = 'b1'").Scan(&stamped, &stamped); err != nil || stamped != "default" {
|
||||
t.Fatalf("binding org/workspace after upgrade = %q, %v; want default", stamped, err)
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func openPool(t *testing.T, url string) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
pool, err := Open(t.Context(), url)
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
return pool
|
||||
}
|
||||
|
||||
// claimOther takes name as another process would, then optionally releases it
|
||||
// or kills its backend.
|
||||
func claimOther(t *testing.T, url, name string, release, terminate bool) {
|
||||
t.Helper()
|
||||
other, err := AcquireOwnership(t.Context(), openPool(t, url), name)
|
||||
if err != nil {
|
||||
t.Fatalf("first claim: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = other.Release(t.Context()) })
|
||||
if release {
|
||||
if err := other.Release(t.Context()); err != nil {
|
||||
t.Fatalf("Release: %v", err)
|
||||
}
|
||||
}
|
||||
if terminate {
|
||||
if _, err := openPool(t, url).Exec(t.Context(), "SELECT pg_terminate_backend($1)", other.pid); err != nil {
|
||||
t.Fatalf("terminate: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAcquireOwnership(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
// held is taken by another process before the claim under test.
|
||||
held string
|
||||
// release drops the other claim before the claim under test.
|
||||
release bool
|
||||
// terminate kills the other claim's backend, as a crash would.
|
||||
terminate bool
|
||||
want error
|
||||
}{
|
||||
{name: "state-store", want: nil},
|
||||
{name: "state-store", held: "state-store", want: ErrOwned},
|
||||
{name: "state-store", held: "state-store", release: true, want: nil},
|
||||
{name: "state-store", held: "state-store", terminate: true, want: nil},
|
||||
{name: "gateway", held: "state-store", want: nil},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name+"/held="+tt.held, func(t *testing.T) {
|
||||
url := pgtest.URL(t)
|
||||
if tt.held != "" {
|
||||
claimOther(t, url, tt.held, tt.release, tt.terminate)
|
||||
}
|
||||
got, err := AcquireOwnership(t.Context(), openPool(t, url), tt.name)
|
||||
if got != nil {
|
||||
t.Cleanup(func() { _ = got.Release(t.Context()) })
|
||||
}
|
||||
if !errors.Is(err, tt.want) {
|
||||
t.Fatalf("AcquireOwnership(%q) = %v, want %v", tt.name, err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"sync"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
|
||||
func TestCheckServerVersion(t *testing.T) {
|
||||
tests := []struct {
|
||||
num int
|
||||
want error
|
||||
}{
|
||||
{num: 180000},
|
||||
{num: 180006},
|
||||
{num: 190000},
|
||||
{num: 179999, want: ErrServerTooOld},
|
||||
{num: 170011, want: ErrServerTooOld},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if err := checkServerVersion(tt.num); !errors.Is(err, tt.want) {
|
||||
t.Errorf("checkServerVersion(%d) = %v, want %v", tt.num, err, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenConnectsToPostgres18(t *testing.T) {
|
||||
pool, err := Open(t.Context(), pgtest.URL(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
defer pool.Close()
|
||||
var one int
|
||||
if err := pool.QueryRow(t.Context(), "SELECT 1").Scan(&one); err != nil || one != 1 {
|
||||
t.Fatalf("SELECT 1 = %d, %v", one, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Each migration inserts one row, so the row count is the number of times
|
||||
// it was applied.
|
||||
var countingMigrations = fstest.MapFS{
|
||||
"00001_create.sql": {Data: []byte("-- +goose Up\nCREATE TABLE applied (n int);\nINSERT INTO applied VALUES (1);\n")},
|
||||
"00002_again.sql": {Data: []byte("-- +goose Up\nINSERT INTO applied VALUES (2);\n")},
|
||||
}
|
||||
|
||||
func TestMigrateAppliesEachMigrationOnce(t *testing.T) {
|
||||
pool, err := Open(t.Context(), pgtest.URL(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
// Two processes starting together, then a later restart.
|
||||
var wg sync.WaitGroup
|
||||
errs := make([]error, 2)
|
||||
for i := range errs {
|
||||
wg.Go(func() { errs[i] = Migrate(t.Context(), pool, countingMigrations) })
|
||||
}
|
||||
wg.Wait()
|
||||
for i, err := range errs {
|
||||
if err != nil {
|
||||
t.Fatalf("concurrent Migrate %d: %v", i, err)
|
||||
}
|
||||
}
|
||||
if err := Migrate(t.Context(), pool, countingMigrations); err != nil {
|
||||
t.Fatalf("Migrate on restart: %v", err)
|
||||
}
|
||||
|
||||
var rows int
|
||||
if err := pool.QueryRow(t.Context(), "SELECT count(*) FROM applied").Scan(&rows); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rows != 2 {
|
||||
t.Fatalf("applied rows = %d, want 2 (each migration exactly once)", rows)
|
||||
}
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
)
|
||||
|
||||
// Tests for the review gate response write
|
||||
// (docs/prds/pr-review-operator-response.md, Decision 2): one guarded
|
||||
// requeue beside RetryTask/BeginRemediation. The rereview cap is enforced in
|
||||
// the row, so a race cannot spend a round the cap forbids.
|
||||
|
||||
// waitingTaskWithGate claims a task, runs it to waiting_human and writes a
|
||||
// gate document on it -- the state an operator's response acts on.
|
||||
func waitingTaskWithGate(t *testing.T, s *Store) *workflow.Task {
|
||||
t.Helper()
|
||||
execution := runningTask(t, s)
|
||||
if err := s.Transition(t.Context(), execution.ID, workflow.StatusRunning, workflow.StatusWaitingHuman, "awaiting operator review"); err != nil {
|
||||
t.Fatalf("Transition to waiting_human: %v", err)
|
||||
}
|
||||
if err := s.Update(t.Context(), &workflow.Task{
|
||||
ID: execution.ID, Workflow: execution.Workflow, ReviewGate: `{"findings":[{"title":"f0"}]}`,
|
||||
}); err != nil {
|
||||
t.Fatalf("write gate offer: %v", err)
|
||||
}
|
||||
refreshed, err := s.TaskByID(t.Context(), execution.ID)
|
||||
if err != nil || refreshed == nil {
|
||||
t.Fatalf("TaskByID = (%v, %v)", refreshed, err)
|
||||
}
|
||||
return refreshed
|
||||
}
|
||||
|
||||
func TestRespondReviewGateIncrementsOnlyForARereview(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
task := waitingTaskWithGate(t, s)
|
||||
|
||||
if err := s.RespondReviewGate(t.Context(), task.ID, workflow.StatusWaitingHuman, `{"outcome":"approve"}`, false, 2); err != nil {
|
||||
t.Fatalf("RespondReviewGate(approve): %v", err)
|
||||
}
|
||||
got, err := s.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%v, %v)", got, err)
|
||||
}
|
||||
if got.Status != workflow.StatusQueued {
|
||||
t.Fatalf("status after approve = %q, want %q: the response requeues", got.Status, workflow.StatusQueued)
|
||||
}
|
||||
if got.RereviewRounds != 0 {
|
||||
t.Fatalf("rereview_rounds after approve = %d, want 0: an approve counts no round", got.RereviewRounds)
|
||||
}
|
||||
if got.ReviewGate != `{"outcome":"approve"}` {
|
||||
t.Fatalf("review_gate after approve = %q, want the caller's document", got.ReviewGate)
|
||||
}
|
||||
if got.Workflow != task.Workflow {
|
||||
t.Fatalf("workflow after approve = %q, want %q (the wait resumes the workflow the wait names)", got.Workflow, task.Workflow)
|
||||
}
|
||||
|
||||
// Requeue again to waiting, then answer with a re-review: the counter moves.
|
||||
if err := s.Transition(t.Context(), task.ID, workflow.StatusQueued, workflow.StatusRunning, ""); err != nil {
|
||||
t.Fatalf("claim again: %v", err)
|
||||
}
|
||||
if err := s.Transition(t.Context(), task.ID, workflow.StatusRunning, workflow.StatusWaitingHuman, ""); err != nil {
|
||||
t.Fatalf("wait again: %v", err)
|
||||
}
|
||||
if err := s.RespondReviewGate(t.Context(), task.ID, workflow.StatusWaitingHuman, `{"outcome":"rereview","instructions":"look again"}`, true, 2); err != nil {
|
||||
t.Fatalf("RespondReviewGate(rereview): %v", err)
|
||||
}
|
||||
got, err = s.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%v, %v)", got, err)
|
||||
}
|
||||
if got.RereviewRounds != 1 {
|
||||
t.Fatalf("rereview_rounds after one re-review = %d, want 1 (and it must survive the store round trip)", got.RereviewRounds)
|
||||
}
|
||||
if got.Status != workflow.StatusQueued {
|
||||
t.Fatalf("status after re-review = %q, want %q", got.Status, workflow.StatusQueued)
|
||||
}
|
||||
if got.ReviewGate != `{"outcome":"rereview","instructions":"look again"}` {
|
||||
t.Fatalf("review_gate after re-review = %q, want the caller's document", got.ReviewGate)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRespondReviewGateAtCapRefusedAndStaysWaiting(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
task := waitingTaskWithGate(t, s)
|
||||
|
||||
// Spend both rounds: two waiting_human gates answered with re-reviews.
|
||||
for range 2 {
|
||||
if err := s.RespondReviewGate(t.Context(), task.ID, workflow.StatusWaitingHuman, `{"outcome":"rereview"}`, true, 2); err != nil {
|
||||
t.Fatalf("RespondReviewGate(reviewer round %d): %v", task.RereviewRounds, err)
|
||||
}
|
||||
if err := s.Transition(t.Context(), task.ID, workflow.StatusQueued, workflow.StatusRunning, ""); err != nil {
|
||||
t.Fatalf("claim again: %v", err)
|
||||
}
|
||||
if err := s.Transition(t.Context(), task.ID, workflow.StatusRunning, workflow.StatusWaitingHuman, ""); err != nil {
|
||||
t.Fatalf("wait again: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
before, err := s.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || before == nil {
|
||||
t.Fatalf("TaskByID = (%v, %v)", before, err)
|
||||
}
|
||||
err = s.RespondReviewGate(t.Context(), task.ID, workflow.StatusWaitingHuman, `{"outcome":"rereview"}`, true, 2)
|
||||
if !errors.Is(err, storecontract.ErrRereviewCapReached) {
|
||||
t.Fatalf("RespondReviewGate at cap = %v, want ErrRereviewCapReached", err)
|
||||
}
|
||||
after, err := s.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || after == nil {
|
||||
t.Fatalf("TaskByID = (%v, %v)", after, err)
|
||||
}
|
||||
if after.Status != workflow.StatusWaitingHuman {
|
||||
t.Fatalf("status after refused re-review = %q, want %q: the task stays waiting", after.Status, workflow.StatusWaitingHuman)
|
||||
}
|
||||
if after.RereviewRounds != before.RereviewRounds || after.ReviewGate != before.ReviewGate {
|
||||
t.Fatalf("refused re-review changed the row: rounds %d->%d, gate %q->%q",
|
||||
before.RereviewRounds, after.RereviewRounds, before.ReviewGate, after.ReviewGate)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRespondReviewGateStaleFromStatusWritesNothing(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
task := waitingTaskWithGate(t, s)
|
||||
|
||||
err := s.RespondReviewGate(t.Context(), task.ID, workflow.StatusParked, `{"outcome":"approve"}`, false, 2)
|
||||
if !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("RespondReviewGate from parked = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
got, err := s.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%v, %v)", got, err)
|
||||
}
|
||||
if got.Status != workflow.StatusWaitingHuman || got.ReviewGate != `{"findings":[{"title":"f0"}]}` {
|
||||
t.Fatalf("refused write changed the row: status=%q gate=%q", got.Status, got.ReviewGate)
|
||||
}
|
||||
}
|
||||
@@ -1,213 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/bindingcipher"
|
||||
)
|
||||
|
||||
func readRawSourceSecret(t *testing.T, pool *pgxpool.Pool, path string) string {
|
||||
t.Helper()
|
||||
var stored string
|
||||
if err := pool.QueryRow(t.Context(), "SELECT secret FROM sources WHERE path = $1", path).Scan(&stored); err != nil {
|
||||
t.Fatalf("read raw secret: %v", err)
|
||||
}
|
||||
return stored
|
||||
}
|
||||
|
||||
// A new source keeps its generated path, is signed, stores its secret as a
|
||||
// cipher envelope and reads it back as plaintext.
|
||||
func TestSourceRoundTripEncryptsSecret(t *testing.T) {
|
||||
cipher, err := bindingcipher.NewBindingCipher(edaTestKey, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher() error = %v", err)
|
||||
}
|
||||
pool, s := edaWithCipher(t, cipher)
|
||||
in, err := source.New("")
|
||||
if err != nil {
|
||||
t.Fatalf("source.New() error = %v", err)
|
||||
}
|
||||
if err := s.InsertSource(t.Context(), in); err != nil {
|
||||
t.Fatalf("InsertSource() error = %v", err)
|
||||
}
|
||||
if raw := readRawSourceSecret(t, pool, in.Path); raw == in.Secret || raw == "" {
|
||||
t.Fatalf("stored secret = %q, want a cipher envelope", raw)
|
||||
}
|
||||
got, err := s.GetSource(t.Context(), in.Path)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("GetSource() = %v, %v", got, err)
|
||||
}
|
||||
if got.Path != in.Path || got.Signing != source.SigningSigned || got.Secret != in.Secret {
|
||||
t.Fatalf("GetSource() = %+v, want path %q signed with the plaintext secret", got, in.Path)
|
||||
}
|
||||
list, err := s.ListSources(t.Context())
|
||||
if err != nil || len(list) != 1 || list[0].Secret != in.Secret {
|
||||
t.Fatalf("ListSources() = %+v, %v", list, err)
|
||||
}
|
||||
}
|
||||
|
||||
// sourceUnder inserts a new source through a store sealing with cipher.
|
||||
func sourceUnder(t *testing.T, cipher bindingcipher.BindingCipher) (*pgxpool.Pool, source.Source) {
|
||||
t.Helper()
|
||||
pool, s := edaWithCipher(t, cipher)
|
||||
in, err := source.New("")
|
||||
if err != nil {
|
||||
t.Fatalf("source.New() error = %v", err)
|
||||
}
|
||||
if err := s.InsertSource(t.Context(), in); err != nil {
|
||||
t.Fatalf("InsertSource() error = %v", err)
|
||||
}
|
||||
return pool, in
|
||||
}
|
||||
|
||||
// A deployment with no configured key stores plaintext.
|
||||
func TestSourceNoCipherKeepsPlaintext(t *testing.T) {
|
||||
pool, in := sourceUnder(t, nil)
|
||||
if raw := readRawSourceSecret(t, pool, in.Path); raw != in.Secret {
|
||||
t.Errorf("stored secret = %q, want the plaintext with no cipher configured", raw)
|
||||
}
|
||||
}
|
||||
|
||||
// A secret written under the previous key stays readable once a new active
|
||||
// key is installed; otherwise rotation bricks every signed source.
|
||||
func TestSourceRotatedKeyStillReadsOldRows(t *testing.T) {
|
||||
const oldKey = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"
|
||||
oldCipher, err := bindingcipher.NewBindingCipher(oldKey, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher(old) error = %v", err)
|
||||
}
|
||||
pool, in := sourceUnder(t, oldCipher)
|
||||
rotated, err := bindingcipher.NewBindingCipher(edaTestKey, []string{oldKey})
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher(rotated) error = %v", err)
|
||||
}
|
||||
got, err := NewEDA(pool, rotated).GetSource(t.Context(), in.Path)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("GetSource() after rotation = %v, %v", got, err)
|
||||
}
|
||||
if got.Secret != in.Secret {
|
||||
t.Errorf("Secret after rotation = %q: the previous key must still decrypt", got.Secret)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceWritesRefuseBadState(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
taken := source.Source{Path: "sentry", Signing: source.SigningSigned, Secret: "k"}
|
||||
if err := s.InsertSource(t.Context(), taken); err != nil {
|
||||
t.Fatalf("InsertSource() error = %v", err)
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
write func() error
|
||||
want error
|
||||
}{
|
||||
{"taken custom path", func() error { return s.InsertSource(t.Context(), taken) }, storecontract.ErrSourcePathTaken},
|
||||
{"stale signing", func() error {
|
||||
return s.SetSourceSigning(t.Context(), "sentry", source.SigningUnsignedPending, source.SigningUnsigned)
|
||||
}, storecontract.ErrSourceSigningStale},
|
||||
{"signing on unknown path", func() error {
|
||||
return s.SetSourceSigning(t.Context(), "nope", source.SigningSigned, source.SigningUnsignedPending)
|
||||
}, storecontract.ErrSourceNotFound},
|
||||
{"secret on unknown path", func() error { return s.SetSourceSecret(t.Context(), "nope", "k") }, storecontract.ErrSourceNotFound},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if err := tt.write(); !errors.Is(err, tt.want) {
|
||||
t.Fatalf("error = %v, want %v", err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
got, err := s.GetSource(t.Context(), "nope")
|
||||
if err != nil || got != nil {
|
||||
t.Fatalf("GetSource(unknown) = %v, %v; want nil, nil", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceSigningAndSecretWrites(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
if err := s.InsertSource(t.Context(), source.Source{Path: "fw", Signing: source.SigningSigned}); err != nil {
|
||||
t.Fatalf("InsertSource() error = %v", err)
|
||||
}
|
||||
if err := s.SetSourceSigning(t.Context(), "fw", source.SigningSigned, source.SigningUnsignedPending); err != nil {
|
||||
t.Fatalf("SetSourceSigning() error = %v", err)
|
||||
}
|
||||
if err := s.SetSourceSecret(t.Context(), "fw", "newsecret"); err != nil {
|
||||
t.Fatalf("SetSourceSecret() error = %v", err)
|
||||
}
|
||||
got, err := s.GetSource(t.Context(), "fw")
|
||||
if err != nil || got.Signing != source.SigningUnsignedPending || got.Secret != "newsecret" {
|
||||
t.Fatalf("GetSource() = %+v, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureUnsignedRoundTrip(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
// Only an identified capture with an armed binding for its type is listed
|
||||
// for dispatch; a catch-all type identifies every event on the source.
|
||||
etID, err := s.InsertEventType(t.Context(), eventtype.EventType{Source: "fw", Name: "any"})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEventType() error = %v", err)
|
||||
}
|
||||
mid, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m", EventTypeID: etID})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
}
|
||||
armedBinding(t, s, "fw", mid)
|
||||
if _, err := s.InsertCapture(t.Context(), storecontract.CapturedEvent{Source: "fw", Unsigned: true}, 0, 0); err != nil {
|
||||
t.Fatalf("InsertCapture() error = %v", err)
|
||||
}
|
||||
for name, list := range map[string]func() ([]storecontract.CapturedEvent, error){
|
||||
"ListCaptures": func() ([]storecontract.CapturedEvent, error) { return s.ListCaptures(t.Context(), 10) },
|
||||
"ListUndispatchedCaptures": func() ([]storecontract.CapturedEvent, error) {
|
||||
return s.ListUndispatchedCaptures(t.Context(), []string{"fw"}, 10)
|
||||
},
|
||||
} {
|
||||
got, err := list()
|
||||
if err != nil || len(got) != 1 || !got[0].Unsigned {
|
||||
t.Errorf("%s() = %+v, %v; want one unsigned capture", name, got, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Existing source strings become sources: a bound source takes its binding's
|
||||
// secret, a capture-only source gets none, and an existing source is kept.
|
||||
func TestDeriveSourcesFromExistingRows(t *testing.T) {
|
||||
pool, q := migrated(t)
|
||||
ctx := t.Context()
|
||||
for _, stmt := range []string{
|
||||
`INSERT INTO bindings (id, name, source, secret) VALUES ('b1', 'n', 'sentry', 'envelope')`,
|
||||
`INSERT INTO captures (id, source, received_at) VALUES ('c1', 'sentry', now()), ('c2', 'firewall', now()), ('c3', 'kept', now())`,
|
||||
`INSERT INTO sources (path, signing, secret) VALUES ('kept', 'unsigned', 'x')`,
|
||||
} {
|
||||
if _, err := pool.Exec(ctx, stmt); err != nil {
|
||||
t.Fatalf("%s: %v", stmt, err)
|
||||
}
|
||||
}
|
||||
if err := q.DeriveSources(ctx); err != nil {
|
||||
t.Fatalf("DeriveSources() error = %v", err)
|
||||
}
|
||||
want := map[string][2]string{
|
||||
"sentry": {"signed", "envelope"},
|
||||
"firewall": {"signed", ""},
|
||||
"kept": {"unsigned", "x"},
|
||||
}
|
||||
rows, err := q.ListSources(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ListSources() error = %v", err)
|
||||
}
|
||||
if len(rows) != len(want) {
|
||||
t.Fatalf("derived %d sources, want %d: %+v", len(rows), len(want), rows)
|
||||
}
|
||||
for _, r := range rows {
|
||||
if w := want[r.Path]; w != [2]string{r.Signing, r.Secret} {
|
||||
t.Errorf("source %q = (%s, %q), want %v", r.Path, r.Signing, r.Secret, w)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,540 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
||||
)
|
||||
|
||||
// syntheticIssueBase mirrors the store's chat issue-number seed. It is the
|
||||
// fallback for a repo's first chat task, not the number that lands: the
|
||||
// allocator adds one to it.
|
||||
const syntheticIssueBase = 1_000_000_000_000_000
|
||||
|
||||
// migrated is a pool with the State Store schema applied, and its queries.
|
||||
func migrated(t *testing.T) (*pgxpool.Pool, *postgresdb.Queries) {
|
||||
t.Helper()
|
||||
pool, err := Open(t.Context(), pgtest.URL(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
if err := Migrate(t.Context(), pool, Migrations()); err != nil {
|
||||
t.Fatalf("Migrate: %v", err)
|
||||
}
|
||||
return pool, postgresdb.New(pool)
|
||||
}
|
||||
|
||||
// queriesFor is migrated's queries without the pool, for tests that only read
|
||||
// and write through sqlc.
|
||||
func queriesFor(t *testing.T) *postgresdb.Queries {
|
||||
t.Helper()
|
||||
_, q := migrated(t)
|
||||
return q
|
||||
}
|
||||
|
||||
func resourcesFor(t *testing.T) *Resources {
|
||||
t.Helper()
|
||||
pool, _ := migrated(t)
|
||||
return NewResources(pool)
|
||||
}
|
||||
|
||||
// insertChatTask queues one chat-sourced task.
|
||||
func insertChatTask(t *testing.T, q *postgresdb.Queries) postgresdb.Task {
|
||||
t.Helper()
|
||||
task, err := q.InsertChatTask(t.Context(), postgresdb.InsertChatTaskParams{
|
||||
Owner: "acme", Repo: "widget", Title: "t", Body: "b",
|
||||
Workflow: "tdd", Identity: "bot",
|
||||
FallbackIssueNumber: syntheticIssueBase,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertChatTask: %v", err)
|
||||
}
|
||||
return task
|
||||
}
|
||||
|
||||
func TestSchemaAppliesAndTasksRoundTrip(t *testing.T) {
|
||||
q := queriesFor(t)
|
||||
|
||||
task := insertChatTask(t, q)
|
||||
if task.Status != "queued" {
|
||||
t.Fatalf("new task status = %q, want queued", task.Status)
|
||||
}
|
||||
if task.CreatedAt.IsZero() || task.UpdatedAt.IsZero() {
|
||||
t.Error("created_at/updated_at were not populated")
|
||||
}
|
||||
if task.IssueNumber != syntheticIssueBase+1 {
|
||||
t.Fatalf("first chat task issue number = %d, want %d", task.IssueNumber, syntheticIssueBase+1)
|
||||
}
|
||||
|
||||
got, err := q.TaskByIssue(t.Context(), postgresdb.TaskByIssueParams{
|
||||
Owner: task.Owner, Repo: task.Repo, IssueNumber: task.IssueNumber,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("TaskByIssue: %v", err)
|
||||
}
|
||||
if got.ID != task.ID {
|
||||
t.Fatalf("TaskByIssue = %d, want %d", got.ID, task.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// The chat allocator hands out the next number per repo, so two chat tasks in
|
||||
// one repo never share an issue number.
|
||||
func TestChatIssueNumberAllocatorIsPerRepo(t *testing.T) {
|
||||
q := queriesFor(t)
|
||||
|
||||
first := insertChatTask(t, q)
|
||||
second := insertChatTask(t, q)
|
||||
if second.IssueNumber != first.IssueNumber+1 {
|
||||
t.Fatalf("second chat issue number = %d, want %d", second.IssueNumber, first.IssueNumber+1)
|
||||
}
|
||||
}
|
||||
|
||||
// Task uniqueness follows the record's identity: the same owner/repo/issue
|
||||
// under the same org and identity is refused, and the constraint that carries
|
||||
// that rule survives the move.
|
||||
func TestTaskIssueNumberIsUnique(t *testing.T) {
|
||||
pool, q := migrated(t)
|
||||
task := insertChatTask(t, q)
|
||||
|
||||
_, err := pool.Exec(t.Context(), `
|
||||
INSERT INTO tasks (owner, repo, issue_number, identity, org_id)
|
||||
VALUES ($1, $2, $3, $4, 'default')`,
|
||||
task.Owner, task.Repo, task.IssueNumber, task.Identity)
|
||||
if err == nil {
|
||||
t.Fatal("a second task for the same org/identity/owner/repo/issue was accepted, want the unique constraint refused it")
|
||||
}
|
||||
|
||||
// A different identity may work the same issue: that is its own record.
|
||||
if task.Identity != "other" {
|
||||
_, err = pool.Exec(t.Context(), `
|
||||
INSERT INTO tasks (owner, repo, issue_number, identity, org_id)
|
||||
VALUES ($1, $2, $3, 'other', 'default')`,
|
||||
task.Owner, task.Repo, task.IssueNumber)
|
||||
if err != nil {
|
||||
t.Fatalf("a second task under another identity was refused: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Claiming takes the oldest queued task, in id order, and counts the attempt.
|
||||
func TestClaimNextTakesTheOldestAndCountsTheAttempt(t *testing.T) {
|
||||
q := queriesFor(t)
|
||||
first := insertChatTask(t, q)
|
||||
second := insertChatTask(t, q)
|
||||
|
||||
claimed, err := q.ClaimNextTask(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("ClaimNextTask: %v", err)
|
||||
}
|
||||
if claimed.ID != first.ID || claimed.Status != "running" || claimed.Attempt != 1 {
|
||||
t.Fatalf("first claim = {id:%d status:%q attempt:%d}, want {id:%d running 1}", claimed.ID, claimed.Status, claimed.Attempt, first.ID)
|
||||
}
|
||||
|
||||
claimed, err = q.ClaimNextTask(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("second ClaimNextTask: %v", err)
|
||||
}
|
||||
if claimed.ID != second.ID {
|
||||
t.Fatalf("second claim = %d, want %d", claimed.ID, second.ID)
|
||||
}
|
||||
|
||||
if _, err := q.ClaimNextTask(t.Context()); !errors.Is(err, pgx.ErrNoRows) {
|
||||
t.Fatalf("claim on an empty queue = %v, want pgx.ErrNoRows", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A claimer must not wait behind a row another transaction holds: it takes the
|
||||
// next one. This is what FOR UPDATE SKIP LOCKED buys over the SQLite version,
|
||||
// where a second claimer could only ever have blocked on the writer lock.
|
||||
func TestClaimSkipsARowAnotherTransactionHolds(t *testing.T) {
|
||||
pool, q := migrated(t)
|
||||
held := insertChatTask(t, q)
|
||||
free := insertChatTask(t, q)
|
||||
|
||||
tx, err := pool.Begin(t.Context())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(t.Context()) }()
|
||||
var lockedID int64
|
||||
if err := tx.QueryRow(t.Context(),
|
||||
`SELECT id FROM tasks WHERE status = 'queued' ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1`,
|
||||
).Scan(&lockedID); err != nil {
|
||||
t.Fatalf("lock the oldest queued row: %v", err)
|
||||
}
|
||||
if lockedID != held.ID {
|
||||
t.Fatalf("locked row %d, want the oldest queued row %d", lockedID, held.ID)
|
||||
}
|
||||
|
||||
claimed, err := q.ClaimNextTask(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("ClaimNextTask while a row is held: %v", err)
|
||||
}
|
||||
if claimed.ID != free.ID {
|
||||
t.Fatalf("claimed %d while %d was held, want the skipped-to row %d", claimed.ID, free.ID, held.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// A control-plane resource write is optimistic and idempotent: a retry returns
|
||||
// the audited original, while a different request based on a stale revision is
|
||||
// refused. The history remains the audit trail, newest first.
|
||||
func TestResourceWritesPreserveOptimisticAndIdempotentSemantics(t *testing.T) {
|
||||
resources := resourcesFor(t)
|
||||
firstAt := time.Date(2026, 9, 24, 1, 0, 0, 0, time.UTC)
|
||||
first, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: "settings", Value: []byte(`{"v":1}`), Actor: "operator", Source: "archie-ui",
|
||||
RequestID: "r1", ExpectedVersion: 0, At: firstAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("first PutResource: %v", err)
|
||||
}
|
||||
if first.Version != 1 || first.CurrentVersion != 0 {
|
||||
t.Fatalf("first write = %+v, want version 1 from version 0", first)
|
||||
}
|
||||
|
||||
replay, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: "settings", Value: []byte(`{"v":999}`), Actor: "other", Source: "retry",
|
||||
RequestID: "r1", ExpectedVersion: 0, At: firstAt.Add(time.Minute),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("replay PutResource: %v", err)
|
||||
}
|
||||
if replay.Version != first.Version || string(replay.Value) != string(first.Value) || replay.Actor != first.Actor {
|
||||
t.Fatalf("replay = %+v, want original %+v", replay, first)
|
||||
}
|
||||
|
||||
if _, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: "settings", Value: []byte(`{"v":2}`), Actor: "operator", Source: "archie-ui",
|
||||
RequestID: "r2", ExpectedVersion: 0, At: firstAt.Add(2 * time.Minute),
|
||||
}); !errors.Is(err, storecontract.ErrResourceVersionConflict) {
|
||||
t.Fatalf("stale PutResource = %v, want ErrResourceVersionConflict", err)
|
||||
}
|
||||
|
||||
second, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: "settings", Value: []byte(`{"v":2}`), Actor: "operator", Source: "messaging",
|
||||
RequestID: "r2", ExpectedVersion: 1, At: firstAt.Add(3 * time.Minute),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("second PutResource: %v", err)
|
||||
}
|
||||
if second.Version != 2 || second.CurrentVersion != 1 {
|
||||
t.Fatalf("second write = %+v, want version 2 from version 1", second)
|
||||
}
|
||||
lateReplay, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: "settings", Value: []byte(`{"v":999}`), Actor: "other", Source: "retry",
|
||||
RequestID: "r1", ExpectedVersion: 0, At: firstAt.Add(4 * time.Minute),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("late replay PutResource: %v", err)
|
||||
}
|
||||
if lateReplay.Version != first.Version || string(lateReplay.Value) != string(first.Value) {
|
||||
t.Fatalf("late replay = %+v, want original %+v", lateReplay, first)
|
||||
}
|
||||
live, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, "settings")
|
||||
if err != nil {
|
||||
t.Fatalf("Resource: %v", err)
|
||||
}
|
||||
if live.Version != second.Version || string(live.Value) != string(second.Value) {
|
||||
t.Fatalf("live resource after replay = %+v, want second write %+v", live, second)
|
||||
}
|
||||
|
||||
history, err := resources.ResourceHistory(t.Context(), storecontract.DefaultOrgID, "settings", 1)
|
||||
if err != nil {
|
||||
t.Fatalf("ResourceHistory: %v", err)
|
||||
}
|
||||
if len(history) != 1 || history[0].Version != 2 || history[0].Source != "messaging" {
|
||||
t.Fatalf("limited history = %+v, want newest revision only", history)
|
||||
}
|
||||
history, err = resources.ResourceHistory(t.Context(), storecontract.DefaultOrgID, "settings", 0)
|
||||
if err != nil {
|
||||
t.Fatalf("unlimited ResourceHistory: %v", err)
|
||||
}
|
||||
if len(history) != 2 {
|
||||
t.Fatalf("history after late replay = %+v, want two revisions", history)
|
||||
}
|
||||
if _, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, "missing"); !errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
t.Fatalf("missing Resource = %v, want ErrResourceNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A write is idempotent per request ID, and the ledger holding those IDs
|
||||
// outlives the row it describes. So a replay whose resource is gone must
|
||||
// re-create it: answering with the ledger's revision alone reports a version for
|
||||
// a kind the store does not hold, and a caller cannot tell that apart from a
|
||||
// resource that is there. An operator removing a resource and restarting the
|
||||
// process that seeds it is the shape this repairs.
|
||||
func TestResourceReplayRecreatesARemovedResource(t *testing.T) {
|
||||
pool, _ := migrated(t)
|
||||
resources := NewResources(pool)
|
||||
at := time.Date(2026, 9, 27, 9, 0, 0, 0, time.UTC)
|
||||
write := storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: "workflow-definitions", Value: []byte(`{"definitions":[]}`), Actor: "system:migration",
|
||||
Source: "legacy-config", RequestID: "import:workflow-definitions", ExpectedVersion: 0, At: at,
|
||||
}
|
||||
seeded, err := resources.PutResource(t.Context(), write)
|
||||
if err != nil {
|
||||
t.Fatalf("seed PutResource: %v", err)
|
||||
}
|
||||
|
||||
if _, err := pool.Exec(t.Context(), `DELETE FROM resources WHERE kind = $1`, write.Kind); err != nil {
|
||||
t.Fatalf("remove the resource: %v", err)
|
||||
}
|
||||
if _, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, write.Kind); !errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
t.Fatalf("resource after the removal = %v, want ErrResourceNotFound", err)
|
||||
}
|
||||
|
||||
replayed, err := resources.PutResource(t.Context(), write)
|
||||
if err != nil {
|
||||
t.Fatalf("replay PutResource: %v", err)
|
||||
}
|
||||
if replayed.Version != seeded.Version || string(replayed.Value) != string(seeded.Value) {
|
||||
t.Fatalf("replay = %+v, want the revision the ledger records, %+v", replayed, seeded)
|
||||
}
|
||||
live, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, write.Kind)
|
||||
if err != nil {
|
||||
t.Fatalf("the replay did not re-create the resource: %v", err)
|
||||
}
|
||||
if live.Version != seeded.Version || string(live.Value) != string(seeded.Value) {
|
||||
t.Fatalf("live resource after the replay = %+v, want the restored %+v", live, seeded)
|
||||
}
|
||||
// The repair re-creates the row the write produced; it does not append a
|
||||
// second ledger entry, which idx_resource_history_kind_request would refuse.
|
||||
history, err := resources.ResourceHistory(t.Context(), storecontract.DefaultOrgID, write.Kind, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("ResourceHistory: %v", err)
|
||||
}
|
||||
if len(history) != 1 {
|
||||
t.Fatalf("history after the replay = %d revisions, want the one the write made", len(history))
|
||||
}
|
||||
|
||||
// A resource the store still holds is answered from the ledger, unchanged:
|
||||
// the idempotent replay the index exists for.
|
||||
again, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: write.Kind, Value: []byte(`{"definitions":[{"id":"different"}]}`), Actor: "other",
|
||||
Source: "retry", RequestID: write.RequestID, ExpectedVersion: 0, At: at.Add(time.Minute),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("second replay: %v", err)
|
||||
}
|
||||
if again.Version != seeded.Version || string(again.Value) != string(seeded.Value) {
|
||||
t.Fatalf("second replay = %+v, want the original %+v", again, seeded)
|
||||
}
|
||||
}
|
||||
|
||||
// A request ID is idempotent per kind: the store API, the resource_history
|
||||
// UNIQUE(kind, request_id) index and every production caller treat it as one,
|
||||
// so a caller that mints one request ID for two different kinds must get two
|
||||
// writes -- the second kind's own revision -- and not the first kind's history
|
||||
// row replayed under the second kind's name.
|
||||
func TestResourceRequestIDIsIdempotentPerKind(t *testing.T) {
|
||||
resources := resourcesFor(t)
|
||||
at := time.Date(2026, 9, 26, 12, 0, 0, 0, time.UTC)
|
||||
first, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: "provider-settings", Value: []byte(`{"v":1}`), Actor: "operator", Source: "import",
|
||||
RequestID: "shared", ExpectedVersion: 0, At: at,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("first PutResource: %v", err)
|
||||
}
|
||||
second, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: "scheduling-policy", Value: []byte(`{"v":2}`), Actor: "operator", Source: "import",
|
||||
RequestID: "shared", ExpectedVersion: 0, At: at,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("second PutResource with the same request ID: %v", err)
|
||||
}
|
||||
if second.Kind != "scheduling-policy" || string(second.Value) != `{"v":2}` || second.Version != 1 {
|
||||
t.Fatalf("second write = %+v, want scheduling-policy's own revision, not a replay of %+v", second, first)
|
||||
}
|
||||
|
||||
replay, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: "scheduling-policy", Value: []byte(`{"v":999}`), Actor: "other", Source: "retry",
|
||||
RequestID: "shared", ExpectedVersion: 0, At: at.Add(time.Minute),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("replay PutResource: %v", err)
|
||||
}
|
||||
if replay.Version != second.Version || string(replay.Value) != string(second.Value) || replay.Actor != second.Actor {
|
||||
t.Fatalf("replay = %+v, want scheduling-policy's original %+v", replay, second)
|
||||
}
|
||||
|
||||
live, err := resources.Resource(t.Context(), storecontract.DefaultOrgID, "scheduling-policy")
|
||||
if err != nil {
|
||||
t.Fatalf("Resource: %v", err)
|
||||
}
|
||||
if live.Version != second.Version || string(live.Value) != string(second.Value) {
|
||||
t.Fatalf("live scheduling-policy = %+v, want second write %+v", live, second)
|
||||
}
|
||||
}
|
||||
|
||||
// PostgreSQL admits concurrent writers, unlike SQLite's single writer. The
|
||||
// resource lock keeps the expected-version comparison and audit append one
|
||||
// serialized operation.
|
||||
func TestConcurrentResourceWritesAcceptOnlyOneExpectedVersion(t *testing.T) {
|
||||
resources := resourcesFor(t)
|
||||
type result struct{ err error }
|
||||
start := make(chan struct{})
|
||||
results := make(chan result, 2)
|
||||
for _, requestID := range []string{"first", "second"} {
|
||||
go func() {
|
||||
<-start
|
||||
_, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: "settings", Value: []byte(`{"v":1}`), Actor: "operator", Source: "test",
|
||||
RequestID: requestID, ExpectedVersion: 0,
|
||||
})
|
||||
results <- result{err: err}
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
|
||||
var succeeded, conflicted int
|
||||
for range 2 {
|
||||
outcome := <-results
|
||||
switch {
|
||||
case outcome.err == nil:
|
||||
succeeded++
|
||||
case errors.Is(outcome.err, storecontract.ErrResourceVersionConflict):
|
||||
conflicted++
|
||||
default:
|
||||
t.Fatalf("concurrent PutResource: %v", outcome.err)
|
||||
}
|
||||
}
|
||||
if succeeded != 1 || conflicted != 1 {
|
||||
t.Fatalf("concurrent writes = %d succeeded, %d conflicted; want 1 each", succeeded, conflicted)
|
||||
}
|
||||
|
||||
history, err := resources.ResourceHistory(t.Context(), storecontract.DefaultOrgID, "settings", 0)
|
||||
if err != nil {
|
||||
t.Fatalf("ResourceHistory: %v", err)
|
||||
}
|
||||
if len(history) != 1 || history[0].Version != 1 {
|
||||
t.Fatalf("history after race = %+v, want exactly one version 1", history)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResourceWritesRecordFieldLevelAudit: each write records one sys_audit row
|
||||
// per field it changed, newest first, and a replayed write records nothing.
|
||||
func TestResourceWritesRecordFieldLevelAudit(t *testing.T) {
|
||||
resources := resourcesFor(t)
|
||||
put := func(value string, expected int64, request string) {
|
||||
t.Helper()
|
||||
if _, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: storecontract.DefaultOrgID,
|
||||
Kind: "settings", Value: []byte(value), Actor: "sam", Source: "archie-ui",
|
||||
RequestID: request, ExpectedVersion: expected,
|
||||
}); err != nil {
|
||||
t.Fatalf("PutResource(%s): %v", value, err)
|
||||
}
|
||||
}
|
||||
put(`{"a":1,"b":2}`, 0, "r1")
|
||||
put(`{"a":1,"b":3,"c":4}`, 1, "r2")
|
||||
put(`{"a":1,"b":3,"c":4}`, 1, "r2")
|
||||
|
||||
audit, err := resources.Audit(t.Context(), storecontract.AuditTableResources, []string{"settings"}, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("ResourceAudit: %v", err)
|
||||
}
|
||||
got := make([]string, 0, len(audit))
|
||||
for _, entry := range audit {
|
||||
got = append(got, fmt.Sprintf("v%d %s %s->%s by %s", entry.Version, entry.Field, entry.OldValue, entry.NewValue, entry.Actor))
|
||||
}
|
||||
want := []string{
|
||||
"v2 c ->4 by sam", "v2 b 2->3 by sam",
|
||||
"v1 b ->2 by sam", "v1 a ->1 by sam",
|
||||
}
|
||||
if strings.Join(got, "; ") != strings.Join(want, "; ") {
|
||||
t.Fatalf("audit =\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))
|
||||
}
|
||||
}
|
||||
|
||||
// A kind is one document per org: two orgs write the same kind under the same
|
||||
// request ID and each keeps its own value, revision, history and audit trail.
|
||||
func TestResourcesAreIndependentPerOrg(t *testing.T) {
|
||||
resources := resourcesFor(t)
|
||||
at := time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC)
|
||||
put := func(orgID, value string, expected int64) storecontract.Resource {
|
||||
t.Helper()
|
||||
got, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: orgID, Kind: "workflow-definitions", Value: []byte(value), Actor: "operator",
|
||||
Source: "test", RequestID: "shared-" + value, ExpectedVersion: expected, At: at,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("PutResource(%s): %v", orgID, err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
put("acme", `{"v":"a1"}`, 0)
|
||||
acme := put("acme", `{"v":"a2"}`, 1)
|
||||
globex := put("globex", `{"v":"g1"}`, 0)
|
||||
if acme.Version != 2 || globex.Version != 1 {
|
||||
t.Fatalf("versions acme=%d globex=%d, want 2 and 1: orgs must not share a revision counter", acme.Version, globex.Version)
|
||||
}
|
||||
if _, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: "globex", Kind: "workflow-definitions", Value: []byte(`{}`), Actor: "operator",
|
||||
Source: "test", RequestID: "stale", ExpectedVersion: 2, At: at,
|
||||
}); !errors.Is(err, storecontract.ErrResourceVersionConflict) {
|
||||
t.Fatalf("globex write expecting acme's version = %v, want ErrResourceVersionConflict", err)
|
||||
}
|
||||
|
||||
live, err := resources.Resource(t.Context(), "globex", "workflow-definitions")
|
||||
if err != nil || string(live.Value) != `{"v":"g1"}` || live.OrgID != "globex" {
|
||||
t.Fatalf("globex Resource = %+v, %v", live, err)
|
||||
}
|
||||
if _, err := resources.Resource(t.Context(), "initech", "workflow-definitions"); !errors.Is(err, storecontract.ErrResourceNotFound) {
|
||||
t.Fatalf("an org that never wrote the kind reads %v, want ErrResourceNotFound", err)
|
||||
}
|
||||
history, err := resources.ResourceHistory(t.Context(), "acme", "workflow-definitions", 0)
|
||||
if err != nil || len(history) != 2 {
|
||||
t.Fatalf("acme history = %d entries, %v; want its own 2", len(history), err)
|
||||
}
|
||||
audit, err := resources.Audit(t.Context(), storecontract.AuditTableResources,
|
||||
[]string{storecontract.ResourceAuditKey("globex", "workflow-definitions")}, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("Audit: %v", err)
|
||||
}
|
||||
for _, entry := range audit {
|
||||
if entry.Version != 1 {
|
||||
t.Fatalf("globex audit entry at version %d: acme's revisions leaked into its trail", entry.Version)
|
||||
}
|
||||
}
|
||||
if len(audit) == 0 {
|
||||
t.Fatal("globex audit is empty, want its first write")
|
||||
}
|
||||
}
|
||||
|
||||
// A key the audit record key could not tell apart from another, or one naming
|
||||
// no org, is refused on both paths rather than reading as an absent resource.
|
||||
func TestResourceKeysAreValidated(t *testing.T) {
|
||||
resources := resourcesFor(t)
|
||||
for _, key := range [][2]string{{"", "settings"}, {"acme", ""}, {"a/b", "settings"}, {"a", "b/settings"}} {
|
||||
if _, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
OrgID: key[0], Kind: key[1], Value: []byte(`{}`), Actor: "operator", Source: "test", RequestID: "r",
|
||||
}); err == nil {
|
||||
t.Errorf("write %q/%q accepted", key[0], key[1])
|
||||
}
|
||||
if _, err := resources.Resource(t.Context(), key[0], key[1]); errors.Is(err, storecontract.ErrResourceNotFound) || err == nil {
|
||||
t.Errorf("read %q/%q = %v, want a key error, not not-found", key[0], key[1], err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,314 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
task "github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
// The step-execution writes (docs/prds/execution-tree-state-machine.md): each
|
||||
// of StartStep and FinishStep is one transaction -- guarded row write plus the
|
||||
// domain event row -- under the step transition table, with the execution's
|
||||
// own status gating whether a step may run at all.
|
||||
|
||||
// runningExecution enqueues and claims one task, the state a step runs in.
|
||||
func runningExecution(t *testing.T, s *Store) *workflow.Task {
|
||||
t.Helper()
|
||||
seed, err := s.EnqueueChatTask(t.Context(), "acme", "widgets", "t", "b", "implement", "", nil)
|
||||
if err != nil || seed == nil {
|
||||
t.Fatalf("EnqueueChatTask: %+v %v", seed, err)
|
||||
}
|
||||
claimed, err := s.ClaimNext(t.Context())
|
||||
if err != nil || claimed == nil {
|
||||
t.Fatalf("ClaimNext: %+v %v", claimed, err)
|
||||
}
|
||||
return claimed
|
||||
}
|
||||
|
||||
func TestStartStepRecordsAStageEnteringRunning(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
stepID, startEvent, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep: %v", err)
|
||||
}
|
||||
if startEvent.Kind != events.KindStageStart || startEvent.Stage != "implement" ||
|
||||
startEvent.TaskID != execution.ID || startEvent.Attempt != execution.Attempt ||
|
||||
startEvent.Repo != "acme/widgets" || startEvent.ID == 0 {
|
||||
t.Fatalf("stage_start event = %+v, want the transition's row", startEvent)
|
||||
}
|
||||
|
||||
eventsForTask, err := s.TaskEvents(t.Context(), execution.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskEvents: %v", err)
|
||||
}
|
||||
if n := len(eventsForTask); n != 1 {
|
||||
t.Fatalf("events after StartStep = %d, want exactly the one the transition wrote", n)
|
||||
}
|
||||
|
||||
step, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stepID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded, Detail: "implemented",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("FinishStep: %v", err)
|
||||
}
|
||||
if step.Kind != events.KindStageFinish || step.Stage != "implement" || step.ID == 0 {
|
||||
t.Fatalf("stage_finish event = %+v, want the transition's row", step)
|
||||
}
|
||||
if _, ok := step.Data["duration_ms"]; !ok {
|
||||
t.Errorf("stage_finish data = %v, want duration_ms: the stage statistics read it", step.Data)
|
||||
}
|
||||
if _, has := step.Data["error"]; has {
|
||||
t.Errorf("stage_finish data = %v, want no error key for a succeeded step", step.Data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinishStepFailedCarriesTheErrorTheDashboardRenders(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
stepID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "review",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep: %v", err)
|
||||
}
|
||||
step, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stepID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepFailed, Detail: "review found 3 findings",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("FinishStep: %v", err)
|
||||
}
|
||||
if step.Data["error"] != "review found 3 findings" {
|
||||
t.Errorf("stage_finish data = %v, want the error text stageOutcome renders", step.Data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartStepRefusesWhatTheStateMachineForbids(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
seed func(s *Store, taskID int64) error
|
||||
start task.StepStart
|
||||
want error
|
||||
}{
|
||||
{
|
||||
name: "an execution that is not running",
|
||||
start: task.StepStart{Kind: task.StepKindStage, Name: "plan", Attempt: 1},
|
||||
want: storecontract.ErrIllegalTransition,
|
||||
},
|
||||
{
|
||||
name: "an execution that does not exist",
|
||||
start: task.StepStart{Kind: task.StepKindStage, Name: "plan", Attempt: 1},
|
||||
want: storecontract.ErrStaleTransition,
|
||||
},
|
||||
{
|
||||
name: "an attempt the execution no longer runs",
|
||||
start: task.StepStart{Kind: task.StepKindStage, Name: "plan", Attempt: 99},
|
||||
want: storecontract.ErrStaleTransition,
|
||||
},
|
||||
{
|
||||
name: "an unknown step kind",
|
||||
start: task.StepStart{Kind: "quantum", Name: "plan", Attempt: 1},
|
||||
want: storecontract.ErrInvalidStep,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
if tt.name == "an execution that is not running" {
|
||||
// Back on the queue: nothing may run under it. The seed rides
|
||||
// the legal running->queued edge, not a hand-written pair.
|
||||
if err := s.Transition(t.Context(), execution.ID, taskstate.Running, taskstate.Queued, "requeue"); err != nil {
|
||||
t.Fatalf("seed queued: %v", err)
|
||||
}
|
||||
}
|
||||
start := tt.start
|
||||
start.ExecutionID = execution.ID
|
||||
if tt.name == "an execution that does not exist" {
|
||||
start.ExecutionID = execution.ID + 999999
|
||||
}
|
||||
if _, _, err := s.StartStep(t.Context(), start); !errors.Is(err, tt.want) {
|
||||
t.Fatalf("StartStep = %v, want %v", err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartStepUnderATerminalParentIsIllegal(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
parentID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "review",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep parent: %v", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: parentID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded, Detail: "done",
|
||||
}); err != nil {
|
||||
t.Fatalf("FinishStep parent: %v", err)
|
||||
}
|
||||
|
||||
_, _, err = s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt,
|
||||
ParentID: parentID, Kind: task.StepKindAgent, Name: "review:2",
|
||||
})
|
||||
if !errors.Is(err, storecontract.ErrIllegalTransition) {
|
||||
t.Fatalf("StartStep under a terminal parent = %v, want ErrIllegalTransition", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStepDepthIsDerivedFromTheParent(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
parentID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep stage: %v", err)
|
||||
}
|
||||
childID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt,
|
||||
ParentID: parentID, Kind: task.StepKindAgent, Name: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep agent child: %v", err)
|
||||
}
|
||||
var depths map[int64]int
|
||||
if err := s.pool.QueryRow(t.Context(),
|
||||
`SELECT jsonb_object_agg(id, depth) FROM step_executions WHERE execution_id = $1`,
|
||||
execution.ID).Scan(&depths); err != nil {
|
||||
t.Fatalf("read depths: %v", err)
|
||||
}
|
||||
if depths[parentID] != 0 || depths[childID] != 1 {
|
||||
t.Fatalf("depths = %v, want the stage at 0 and its child at 1", depths)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinishStepRefusesStaleAndForeign(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
other := runningExecution(t, s)
|
||||
|
||||
stepID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "plan",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep: %v", err)
|
||||
}
|
||||
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stepID, ExecutionID: other.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded,
|
||||
}); !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("FinishStep naming another execution = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stepID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepSucceeded, To: taskstate.StepFailed,
|
||||
}); !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("FinishStep with an untruthful from = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stepID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepPending,
|
||||
}); !errors.Is(err, storecontract.ErrIllegalTransition) {
|
||||
t.Fatalf("FinishStep off-table pair = %v, want ErrIllegalTransition", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stepID + 999999, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded,
|
||||
}); !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("FinishStep on a missing step = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestListStepsOrdersByAttemptThenID is the dashboard run detail's
|
||||
// authoritative read (docs/prds/execution-tree-state-machine.md): every
|
||||
// attempt in one call when attempt is 0, one attempt's steps when it names
|
||||
// one, both ordered oldest first.
|
||||
func TestListStepsOrdersByAttemptThenID(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
firstStepID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "plan",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep: %v", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: firstStepID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded, Detail: "planned", TokensUsed: 42,
|
||||
}); err != nil {
|
||||
t.Fatalf("FinishStep: %v", err)
|
||||
}
|
||||
secondStepID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep: %v", err)
|
||||
}
|
||||
|
||||
steps, err := s.ListSteps(t.Context(), execution.ID, execution.Attempt)
|
||||
if err != nil {
|
||||
t.Fatalf("ListSteps: %v", err)
|
||||
}
|
||||
if len(steps) != 2 {
|
||||
t.Fatalf("ListSteps len = %d, want 2", len(steps))
|
||||
}
|
||||
if steps[0].ID != firstStepID || steps[0].Name != "plan" || steps[0].Status != taskstate.StepSucceeded ||
|
||||
steps[0].Detail != "planned" || steps[0].TokensUsed != 42 || steps[0].StartedAt.IsZero() || steps[0].FinishedAt.IsZero() {
|
||||
t.Fatalf("steps[0] = %+v, want the finished plan step", steps[0])
|
||||
}
|
||||
if steps[1].ID != secondStepID || steps[1].Name != "implement" || steps[1].Status != taskstate.StepRunning ||
|
||||
steps[1].StartedAt.IsZero() || !steps[1].FinishedAt.IsZero() {
|
||||
t.Fatalf("steps[1] = %+v, want the still-running implement step", steps[1])
|
||||
}
|
||||
|
||||
// attempt 0 lists every attempt; there is only one here, so the result is
|
||||
// the same, proving the "list everything" branch is reachable and correct
|
||||
// rather than coincidentally equal to a hardcoded attempt.
|
||||
all, err := s.ListSteps(t.Context(), execution.ID, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("ListSteps(attempt=0): %v", err)
|
||||
}
|
||||
if len(all) != 2 {
|
||||
t.Fatalf("ListSteps(attempt=0) len = %d, want 2", len(all))
|
||||
}
|
||||
|
||||
// A different execution's steps never appear, however queried.
|
||||
other := runningExecution(t, s)
|
||||
otherSteps, err := s.ListSteps(t.Context(), other.ID, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("ListSteps other execution: %v", err)
|
||||
}
|
||||
if len(otherSteps) != 0 {
|
||||
t.Fatalf("ListSteps other execution = %+v, want none", otherSteps)
|
||||
}
|
||||
}
|
||||
|
||||
// A late FinishStep for a step another path already finished is stale, the
|
||||
// PRD's named wire behaviour: errors.Is matches on the client too.
|
||||
func TestFinishStepOffTablePairIsIllegalOverTheTable(t *testing.T) {
|
||||
if !taskstate.CanStepTransition(taskstate.StepPending, taskstate.StepRunning) {
|
||||
t.Fatal("pending -> running must be in the step transition table")
|
||||
}
|
||||
if taskstate.CanStepTransition(taskstate.StepSucceeded, taskstate.StepRunning) {
|
||||
t.Fatal("succeeded -> running must not be in the step transition table: terminal is terminal")
|
||||
}
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
// Declared workflow outputs on the task row: the attempt-scoped structured
|
||||
// results a run writes (docs/prds/workflow-call-outputs.md, "Storage and
|
||||
// wire").
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
)
|
||||
|
||||
// newStoreForOutputs is a migrated pool with the Store built over it.
|
||||
func newStoreForOutputs(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
pool, _ := migrated(t)
|
||||
return New(pool)
|
||||
}
|
||||
|
||||
// TestTaskOutputs pins the task row half of the outputs model:
|
||||
//
|
||||
// - Update persists the run's written set, decoded exactly on the way out;
|
||||
// - an encoded set past the structured-payload bound is refused, not
|
||||
// clipped (clipped JSON does not parse);
|
||||
// - a claim starts the next attempt with an empty set, so nothing a
|
||||
// retried attempt does not rewrite survives.
|
||||
func TestTaskOutputs(t *testing.T) {
|
||||
t.Run("Update persists the run's outputs and TaskByID reads them back", func(t *testing.T) {
|
||||
st := newStoreForOutputs(t)
|
||||
ctx := t.Context()
|
||||
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "callee", "body", "w", "", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := st.ClaimNext(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
row, err := st.TaskByID(ctx, task.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
row.Outputs = map[string]any{"contained": true, "n": "3"}
|
||||
if err := st.Update(ctx, row); err != nil {
|
||||
t.Fatalf("Update: %v", err)
|
||||
}
|
||||
back, err := st.TaskByID(ctx, task.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if back.Outputs["contained"] != true || back.Outputs["n"] != "3" {
|
||||
t.Fatalf("row outputs = %+v, want the written set read back", back.Outputs)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an encoded set past the structured-payload bound is refused", func(t *testing.T) {
|
||||
st := newStoreForOutputs(t)
|
||||
ctx := t.Context()
|
||||
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "callee", "body", "w", "", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := st.ClaimNext(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
row, err := st.TaskByID(ctx, task.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
row.Outputs = map[string]any{"summary": strings.Repeat("x", 5000)}
|
||||
err = st.Update(ctx, row)
|
||||
if err == nil {
|
||||
t.Fatal("Update accepted a set past the structured-payload bound; it must be refused, not clipped")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "outputs") {
|
||||
t.Fatalf("refusal = %v, want it to name the outputs", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a retried attempt starts with an empty set", func(t *testing.T) {
|
||||
st := newStoreForOutputs(t)
|
||||
ctx := t.Context()
|
||||
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "callee", "body", "w", "", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := st.ClaimNext(ctx)
|
||||
if err != nil || first == nil {
|
||||
t.Fatalf("first claim: (%+v, %v)", first, err)
|
||||
}
|
||||
if first.Outputs != nil {
|
||||
t.Fatalf("first claim outputs = %+v, want the empty set the fresh attempt starts with", first.Outputs)
|
||||
}
|
||||
row, err := st.TaskByID(ctx, task.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
row.Outputs = map[string]any{"contained": true}
|
||||
if err := st.Update(ctx, row); err != nil {
|
||||
t.Fatalf("Update: %v", err)
|
||||
}
|
||||
back, err := st.TaskByID(ctx, task.ID)
|
||||
if err != nil || back.Outputs["contained"] != true {
|
||||
t.Fatalf("setup: the attempt's outputs did not reach the row: (%+v, %v)", back.Outputs, err)
|
||||
}
|
||||
if err := st.Transition(ctx, task.ID, workflow.StatusRunning, workflow.StatusParked, "needs a look"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := st.RetryTask(ctx, task.ID, workflow.StatusParked, "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := st.ClaimNext(ctx)
|
||||
if err != nil || second == nil {
|
||||
t.Fatalf("retried claim: (%+v, %v)", second, err)
|
||||
}
|
||||
if task.ID != second.ID {
|
||||
t.Skipf("another queued task claimed first; the idempotent queue handed out %d", second.ID)
|
||||
}
|
||||
if second.Outputs != nil {
|
||||
t.Fatalf("retried attempt outputs = %+v, want the empty set", second.Outputs)
|
||||
}
|
||||
final, err := st.TaskByID(ctx, task.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, still := final.Outputs["contained"]; still {
|
||||
t.Fatalf("row outputs = %+v, want the emptiness the new attempt starts with", final.Outputs)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate/taskstatetest"
|
||||
)
|
||||
|
||||
// Enforcement of the shared transition table (docs/prds/execution-tree-state-machine.md):
|
||||
// a status write whose from->to pair the table does not route is refused with
|
||||
// ErrIllegalTransition, leaves the row untouched and writes no audit row --
|
||||
// the same three guarantees a stale from already had under ErrStaleTransition.
|
||||
|
||||
// TestIllegalTransitionsAreRejected drives every caller-supplied status write
|
||||
// through an illegal pair and asserts the refusal is total: sentinel, status,
|
||||
// audit trail.
|
||||
func TestIllegalTransitionsAreRejected(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
seed string // status the task is parked in before the write
|
||||
write func(s *Store, taskID int64) error
|
||||
}{
|
||||
{name: "transition queued->parked", seed: taskstate.Queued, write: func(s *Store, taskID int64) error {
|
||||
return s.Transition(t.Context(), taskID, taskstate.Queued, taskstate.Parked, "why")
|
||||
}},
|
||||
{name: "transition running->merged", seed: taskstate.Running, write: func(s *Store, taskID int64) error {
|
||||
return s.Transition(t.Context(), taskID, taskstate.Running, taskstate.Merged, "why")
|
||||
}},
|
||||
{name: "transition running->rejected", seed: taskstate.Running, write: func(s *Store, taskID int64) error {
|
||||
return s.Transition(t.Context(), taskID, taskstate.Running, taskstate.Rejected, "why")
|
||||
}},
|
||||
{name: "transition parked->running", seed: taskstate.Parked, write: func(s *Store, taskID int64) error {
|
||||
return s.Transition(t.Context(), taskID, taskstate.Parked, taskstate.Running, "why")
|
||||
}},
|
||||
{name: "transition waiting_human->pr_open", seed: taskstate.WaitingHuman, write: func(s *Store, taskID int64) error {
|
||||
return s.Transition(t.Context(), taskID, taskstate.WaitingHuman, taskstate.PROpen, "why")
|
||||
}},
|
||||
{name: "transition out of terminal merged", seed: taskstate.Merged, write: func(s *Store, taskID int64) error {
|
||||
return s.Transition(t.Context(), taskID, taskstate.Merged, taskstate.Queued, "why")
|
||||
}},
|
||||
{name: "park from queued", seed: taskstate.Queued, write: func(s *Store, taskID int64) error {
|
||||
return s.ParkTask(t.Context(), taskID, taskstate.Queued, "why", taskstate.ParkTransient)
|
||||
}},
|
||||
{name: "park from pr_open", seed: taskstate.PROpen, write: func(s *Store, taskID int64) error {
|
||||
return s.ParkTask(t.Context(), taskID, taskstate.PROpen, "why", taskstate.ParkTransient)
|
||||
}},
|
||||
{name: "requeue from terminal merged", seed: taskstate.Merged, write: func(s *Store, taskID int64) error {
|
||||
return s.Requeue(t.Context(), taskID, taskstate.Merged, "implement")
|
||||
}},
|
||||
{name: "retry from terminal merged", seed: taskstate.Merged, write: func(s *Store, taskID int64) error {
|
||||
return s.RetryTask(t.Context(), taskID, taskstate.Merged, "implement", "")
|
||||
}},
|
||||
{name: "retry from queued self-pair", seed: taskstate.Queued, write: func(s *Store, taskID int64) error {
|
||||
return s.RetryTask(t.Context(), taskID, taskstate.Queued, "implement", "")
|
||||
}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
task, err := s.EnqueueChatTask(t.Context(), "acme", "widgets", "t", "b", "implement", "", nil)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("EnqueueChatTask: %+v %v", task, err)
|
||||
}
|
||||
taskstatetest.Seed(t.Context(), t, s, task.ID, taskstate.Queued, tt.seed, "seed")
|
||||
before := len(transitions(t, s, task.ID))
|
||||
|
||||
err = tt.write(s, task.ID)
|
||||
if !errors.Is(err, storecontract.ErrIllegalTransition) {
|
||||
t.Fatalf("illegal write = %v, want ErrIllegalTransition", err)
|
||||
}
|
||||
got, err := s.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID: %+v %v", got, err)
|
||||
}
|
||||
if got.Status != tt.seed {
|
||||
t.Fatalf("status after refused write = %q, want %q", got.Status, tt.seed)
|
||||
}
|
||||
if n := len(transitions(t, s, task.ID)); n != before {
|
||||
t.Fatalf("refused write added %d audit row(s), want none", n-before)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Staleness still wins when the from is both untruthful and illegal: the
|
||||
// row's own status is the ground truth a caller first has to be right about
|
||||
// (a queued->merged write against a running task is stale, as the wire
|
||||
// conformance battery has always asserted).
|
||||
func TestStaleFromBeatsIllegalPair(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
task, err := s.EnqueueChatTask(t.Context(), "acme", "widgets", "t", "b", "implement", "", nil)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("EnqueueChatTask: %+v %v", task, err)
|
||||
}
|
||||
taskstatetest.Seed(t.Context(), t, s, task.ID, taskstate.Queued, taskstate.Running, "claim")
|
||||
err = s.Transition(t.Context(), task.ID, taskstate.Queued, taskstate.Merged, "why")
|
||||
if !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("untruthful from = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A legal pair still lands: the guard must not reject what the table routes,
|
||||
// and the audit row is written as before.
|
||||
func TestLegalTransitionStillWrites(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
task, err := s.EnqueueChatTask(t.Context(), "acme", "widgets", "t", "b", "implement", "", nil)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("EnqueueChatTask: %+v %v", task, err)
|
||||
}
|
||||
taskstatetest.Seed(t.Context(), t, s, task.ID, taskstate.Queued, taskstate.Running, "claim")
|
||||
if err := s.Transition(t.Context(), task.ID, taskstate.Running, taskstate.Completed, "done"); err != nil {
|
||||
t.Fatalf("legal transition running->completed = %v, want nil", err)
|
||||
}
|
||||
got, err := s.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID: %+v %v", got, err)
|
||||
}
|
||||
if got.Status != taskstate.Completed {
|
||||
t.Fatalf("status = %q, want %q", got.Status, taskstate.Completed)
|
||||
}
|
||||
rows := transitions(t, s, task.ID)
|
||||
if n := len(rows); n == 0 || rows[n-1] != (transitionRow{taskstate.Running, taskstate.Completed, "done"}) {
|
||||
t.Fatalf("last audit row = %+v, want the running->completed edge", rows)
|
||||
}
|
||||
}
|
||||
|
||||
// The status-changing methods whose from/to is pinned in SQL rather than
|
||||
// supplied by a caller (claim, BeginRemediation, RecoverStale) can only write
|
||||
// the pairs asserted here. Pinning them to the shared table keeps a query
|
||||
// edit from moving a write off the table without this file failing.
|
||||
// The step edge RecoverStale writes is table-routed too: the sweep's WHERE
|
||||
// clause pins status = 'running' and writes 'interrupted', so the pair must
|
||||
// stay legal on the STEP table for a query edit to stay on it. The step table
|
||||
// is a different table from the execution's, so it is pinned beside it rather
|
||||
// than mixed into the execution pairs above.
|
||||
func TestSQLPinnedStepTransitionsAreTableLegal(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
from, to taskstate.StepStatus
|
||||
}{{name: "crash recovery pins step running->interrupted", from: taskstate.StepRunning, to: taskstate.StepInterrupted}} {
|
||||
if !taskstate.CanStepTransition(tc.from, tc.to) {
|
||||
t.Errorf("%s: %s -> %s is not in the shared step transition table", tc.name, tc.from, tc.to)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSQLPinnedTransitionsAreTableLegal(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
from, to string
|
||||
}{
|
||||
{name: "claim pins queued->running", from: taskstate.Queued, to: taskstate.Running},
|
||||
{name: "begin remediation pins pr_open->queued", from: taskstate.PROpen, to: taskstate.Queued},
|
||||
{name: "crash recovery pins running->queued", from: taskstate.Running, to: taskstate.Queued},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if !taskstate.CanTransition(tt.from, tt.to) {
|
||||
t.Errorf("%s: %s -> %s is not in the shared transition table", tt.name, tt.from, tt.to)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate/taskstatetest"
|
||||
)
|
||||
|
||||
// TestWorkflowStatsCountsCompletedRuns pins the per-workflow count the
|
||||
// transition table made reachable: a run that finishes with no pull request
|
||||
// (a no-change build, a triage that needed no code) ends in taskstate.Completed,
|
||||
// so the workflows page has to be able to see those runs at all. The count is a
|
||||
// status filter in SQL, which fails silently when it is wrong -- a typo'd or
|
||||
// missing filter reads as zero, not as an error -- so it is asserted against the
|
||||
// store rather than left to the dashboard to notice.
|
||||
func TestWorkflowStatsCountsCompletedRuns(t *testing.T) {
|
||||
pool, q := migrated(t)
|
||||
store := New(pool)
|
||||
|
||||
finished := insertChatTask(t, q)
|
||||
merged := insertChatTask(t, q)
|
||||
finish := func(id int64, to string) {
|
||||
t.Helper()
|
||||
// Seeded along the table's edges: a merged task is merged on an open
|
||||
// pull request, and the fixture used to write running -> merged.
|
||||
taskstatetest.Seed(t.Context(), t, store, id, taskstate.Queued, to, "")
|
||||
}
|
||||
finish(finished.ID, taskstate.Completed)
|
||||
finish(merged.ID, taskstate.Merged)
|
||||
|
||||
stats, err := store.WorkflowStats(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("WorkflowStats: %v", err)
|
||||
}
|
||||
if len(stats) != 1 {
|
||||
t.Fatalf("WorkflowStats = %+v, want one row for %q", stats, finished.Workflow)
|
||||
}
|
||||
got := stats[0]
|
||||
if got.Workflow != merged.Workflow {
|
||||
t.Fatalf("WorkflowStats row is %q, want %q", got.Workflow, merged.Workflow)
|
||||
}
|
||||
if got.Runs != 2 || got.Completed != 1 || got.Merged != 1 {
|
||||
t.Errorf("WorkflowStats = %+v, want runs 2, completed 1, merged 1: the completed count has to be its own status, not a share of merged", got)
|
||||
}
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
package prsource
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// buildTarGz writes files (path -> content) into a gzipped tar stream,
|
||||
// optionally wrapped in a single leading directory the way GitHub's and
|
||||
// Gitea's repository archives are (e.g. "acme-widget-deadbeef/").
|
||||
func buildTarGz(t *testing.T, wrapper string, files map[string]string) []byte {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
gz := gzip.NewWriter(&buf)
|
||||
tw := tar.NewWriter(gz)
|
||||
for path, content := range files {
|
||||
full := path
|
||||
if wrapper != "" {
|
||||
full = wrapper + "/" + path
|
||||
}
|
||||
if err := tw.WriteHeader(&tar.Header{Name: full, Mode: 0o644, Size: int64(len(content))}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := tw.Write([]byte(content)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := tw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := gz.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func TestExtractTarGzStripsTheWrapperDirectory(t *testing.T) {
|
||||
data := buildTarGz(t, "acme-widget-deadbeef", map[string]string{
|
||||
"README.md": "hello\n",
|
||||
"src/main.go": "package main\n",
|
||||
"src/nested/a.go": "package nested\n",
|
||||
})
|
||||
dest := t.TempDir()
|
||||
|
||||
if err := extractTarGz(bytes.NewReader(data), dest); err != nil {
|
||||
t.Fatalf("extractTarGz: %v", err)
|
||||
}
|
||||
|
||||
for _, rel := range []string{"README.md", "src/main.go", "src/nested/a.go"} {
|
||||
if _, err := os.Stat(filepath.Join(dest, rel)); err != nil {
|
||||
t.Errorf("expected %s to exist: %v", rel, err)
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dest, "acme-widget-deadbeef")); err == nil {
|
||||
t.Error("the wrapper directory itself should not survive extraction")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractTarGzWithNoWrapperDirectory(t *testing.T) {
|
||||
data := buildTarGz(t, "", map[string]string{"a.go": "package a\n"})
|
||||
dest := t.TempDir()
|
||||
|
||||
if err := extractTarGz(bytes.NewReader(data), dest); err != nil {
|
||||
t.Fatalf("extractTarGz: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dest, "a.go")); err != nil {
|
||||
t.Errorf("expected a.go to exist: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractTarGzRefusesPathTraversal(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
gz := gzip.NewWriter(&buf)
|
||||
tw := tar.NewWriter(gz)
|
||||
evil := "wrapper/../../../etc/passwd-clone"
|
||||
if err := tw.WriteHeader(&tar.Header{Name: evil, Mode: 0o644, Size: 4}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := tw.Write([]byte("evil")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := gz.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dest := t.TempDir()
|
||||
|
||||
if err := extractTarGz(bytes.NewReader(buf.Bytes()), dest); err == nil {
|
||||
t.Fatal("want an error for a path-traversal archive entry, not a silent write outside destDir")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractTarGzRefusesAnAbsoluteEntryPath(t *testing.T) {
|
||||
data := buildTarGz(t, "", map[string]string{"/etc/passwd-clone": "evil"})
|
||||
dest := t.TempDir()
|
||||
|
||||
if err := extractTarGz(bytes.NewReader(data), dest); err == nil {
|
||||
t.Fatal("want an error for an absolute archive entry, not a silent write")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractTarGzWritesNothingOutsideDestWhenAnEntryEscapes(t *testing.T) {
|
||||
base := t.TempDir()
|
||||
dest := filepath.Join(base, "snapshot")
|
||||
if err := os.MkdirAll(dest, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Two entries with different top-level components keep the wrapper
|
||||
// prefix empty, so the leading ".." is preserved rather than stripped.
|
||||
data := buildTarGz(t, "", map[string]string{
|
||||
"../escaped.txt": "evil",
|
||||
"keep.txt": "ok",
|
||||
})
|
||||
|
||||
if err := extractTarGz(bytes.NewReader(data), dest); err == nil {
|
||||
t.Fatal("want an error for an entry that escapes destDir")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(base, "escaped.txt")); err == nil {
|
||||
t.Fatal("an escaping entry must not be written outside destDir")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractTarGzLeavesNoDotGit(t *testing.T) {
|
||||
data := buildTarGz(t, "wrapper", map[string]string{
|
||||
"a.go": "package a\n",
|
||||
".git/HEAD": "ref: refs/heads/main\n",
|
||||
".git/config": "[core]\n",
|
||||
".github/x.yaml": "ok\n",
|
||||
})
|
||||
dest := t.TempDir()
|
||||
|
||||
if err := extractTarGz(bytes.NewReader(data), dest); err != nil {
|
||||
t.Fatalf("extractTarGz: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dest, ".git")); err == nil {
|
||||
t.Error("a .git directory must never survive extraction (Isolation: the pipeline reads a .git-free snapshot)")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dest, ".github", "x.yaml")); err != nil {
|
||||
t.Errorf("a non-.git dotfile should still extract: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractTarGzStripsWrapperWithExplicitDirectoryEntries(t *testing.T) {
|
||||
// Real GitHub/Gitea archives include explicit tar directory headers for
|
||||
// the wrapper and every subdirectory, not just file entries with long
|
||||
// names -- a wrapper-only directory header has no "/" in its own
|
||||
// (cleaned) name, which must not be mistaken for "no wrapper exists".
|
||||
var buf bytes.Buffer
|
||||
gz := gzip.NewWriter(&buf)
|
||||
tw := tar.NewWriter(gz)
|
||||
dirs := []string{"acme-widget-deadbeef/", "acme-widget-deadbeef/src/"}
|
||||
for _, d := range dirs {
|
||||
if err := tw.WriteHeader(&tar.Header{Name: d, Typeflag: tar.TypeDir, Mode: 0o755}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
files := map[string]string{
|
||||
"acme-widget-deadbeef/README.md": "hello\n",
|
||||
"acme-widget-deadbeef/src/main.go": "package main\n",
|
||||
}
|
||||
for name, content := range files {
|
||||
if err := tw.WriteHeader(&tar.Header{Name: name, Mode: 0o644, Size: int64(len(content))}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := tw.Write([]byte(content)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := tw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := gz.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dest := t.TempDir()
|
||||
|
||||
if err := extractTarGz(bytes.NewReader(buf.Bytes()), dest); err != nil {
|
||||
t.Fatalf("extractTarGz: %v", err)
|
||||
}
|
||||
for _, rel := range []string{"README.md", "src/main.go"} {
|
||||
if _, err := os.Stat(filepath.Join(dest, rel)); err != nil {
|
||||
t.Errorf("expected %s to exist: %v", rel, err)
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dest, "acme-widget-deadbeef")); err == nil {
|
||||
t.Error("the wrapper directory itself should not survive extraction")
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package prsource
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func writePrefetched(t *testing.T, dir string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Join(dir, "snapshot", "sub"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "metadata.json"), []byte(`{"title":"t","body":"b","head_sha":"abc123"}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "diff.patch"), []byte("diff --git a/x b/x\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "snapshot", "file.go"), []byte("package a\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "snapshot", "sub", "nested.go"), []byte("package sub\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMountSourceMetadataReadsSidecarFile(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writePrefetched(t, dir)
|
||||
src := NewFromMount(dir)
|
||||
|
||||
meta, err := src.Metadata(context.Background(), "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatalf("Metadata: %v", err)
|
||||
}
|
||||
if meta.Title != "t" || meta.Body != "b" {
|
||||
t.Fatalf("meta = %+v, want title/body from the sidecar file", meta)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMountSourceDiffReadsPatchFile(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writePrefetched(t, dir)
|
||||
src := NewFromMount(dir)
|
||||
|
||||
diff, err := src.Diff(context.Background(), "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatalf("Diff: %v", err)
|
||||
}
|
||||
if diff != "diff --git a/x b/x\n" {
|
||||
t.Fatalf("diff = %q, want the patch file's content", diff)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMountSourceSnapshotCopiesFilesAndReturnsHeadSHA(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writePrefetched(t, dir)
|
||||
src := NewFromMount(dir)
|
||||
destDir := t.TempDir()
|
||||
|
||||
headSHA, err := src.Snapshot(context.Background(), "acme", "widget", 1, destDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Snapshot: %v", err)
|
||||
}
|
||||
if headSHA != "abc123" {
|
||||
t.Fatalf("headSHA = %q, want abc123", headSHA)
|
||||
}
|
||||
got, err := os.ReadFile(filepath.Join(destDir, "file.go"))
|
||||
if err != nil {
|
||||
t.Fatalf("read copied file: %v", err)
|
||||
}
|
||||
if string(got) != "package a\n" {
|
||||
t.Fatalf("copied file content = %q", got)
|
||||
}
|
||||
nested, err := os.ReadFile(filepath.Join(destDir, "sub", "nested.go"))
|
||||
if err != nil {
|
||||
t.Fatalf("read copied nested file: %v", err)
|
||||
}
|
||||
if string(nested) != "package sub\n" {
|
||||
t.Fatalf("copied nested file content = %q", nested)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMountSourceMetadataFailsWithoutPrefetchedData(t *testing.T) {
|
||||
src := NewFromMount(t.TempDir())
|
||||
if _, err := src.Metadata(context.Background(), "acme", "widget", 1); err == nil {
|
||||
t.Fatal("want an error when no metadata.json was prefetched")
|
||||
}
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
package prsource
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type fakeForge struct {
|
||||
pr PullRequest
|
||||
diff string
|
||||
archive []byte
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeForge) GetPullRequest(context.Context, string, string, int) (PullRequest, error) {
|
||||
return f.pr, f.err
|
||||
}
|
||||
|
||||
func (f *fakeForge) GetPullRequestDiff(context.Context, string, string, int) (string, error) {
|
||||
return f.diff, f.err
|
||||
}
|
||||
|
||||
func (f *fakeForge) GetRepoArchive(context.Context, string, string, string) (io.ReadCloser, error) {
|
||||
if f.err != nil {
|
||||
return nil, f.err
|
||||
}
|
||||
return io.NopCloser(bytes.NewReader(f.archive)), nil
|
||||
}
|
||||
|
||||
func TestMetadataMapsForgePullRequest(t *testing.T) {
|
||||
forge := &fakeForge{pr: PullRequest{Title: "t", Body: "b", HeadSHA: "abc"}}
|
||||
s := New(forge)
|
||||
|
||||
meta, err := s.Metadata(context.Background(), "acme", "widgets", 7)
|
||||
if err != nil {
|
||||
t.Fatalf("Metadata: %v", err)
|
||||
}
|
||||
if meta.Title != "t" || meta.Body != "b" {
|
||||
t.Errorf("meta = %+v, want title/body from the forge PR", meta)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetadataPropagatesForgeError(t *testing.T) {
|
||||
wantErr := errors.New("forge unreachable")
|
||||
s := New(&fakeForge{err: wantErr})
|
||||
|
||||
if _, err := s.Metadata(context.Background(), "acme", "widgets", 7); !errors.Is(err, wantErr) {
|
||||
t.Fatalf("err = %v, want %v", err, wantErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiffFetchesOverHTTPWithNoCheckout(t *testing.T) {
|
||||
forge := &fakeForge{diff: "diff --git a b"}
|
||||
s := New(forge)
|
||||
|
||||
diff, err := s.Diff(context.Background(), "acme", "widgets", 7)
|
||||
if err != nil {
|
||||
t.Fatalf("Diff: %v", err)
|
||||
}
|
||||
if diff != "diff --git a b" {
|
||||
t.Errorf("diff = %q, want the forge's raw diff response", diff)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiffPropagatesForgeError(t *testing.T) {
|
||||
wantErr := errors.New("diff fetch failed")
|
||||
s := New(&fakeForge{err: wantErr})
|
||||
|
||||
if _, err := s.Diff(context.Background(), "acme", "widgets", 7); !errors.Is(err, wantErr) {
|
||||
t.Fatalf("err = %v, want %v", err, wantErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotExtractsTheArchiveAndReturnsTheHeadSHA(t *testing.T) {
|
||||
archive := buildTarGz(t, "acme-widgets-deadbeef", map[string]string{"main.go": "package main\n"})
|
||||
forge := &fakeForge{pr: PullRequest{HeadSHA: "deadbeef"}, archive: archive}
|
||||
s := New(forge)
|
||||
dest := t.TempDir()
|
||||
|
||||
headSHA, err := s.Snapshot(context.Background(), "acme", "widgets", 7, dest)
|
||||
if err != nil {
|
||||
t.Fatalf("Snapshot: %v", err)
|
||||
}
|
||||
if headSHA != "deadbeef" {
|
||||
t.Errorf("headSHA = %q, want the forge-reported head SHA", headSHA)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dest, "main.go")); err != nil {
|
||||
t.Errorf("expected the extracted file to exist: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dest, "acme-widgets-deadbeef")); err == nil {
|
||||
t.Error("the wrapper directory itself should not survive extraction")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotPropagatesForgeError(t *testing.T) {
|
||||
wantErr := errors.New("archive fetch failed")
|
||||
s := New(&fakeForge{err: wantErr})
|
||||
|
||||
if _, err := s.Snapshot(context.Background(), "acme", "widgets", 7, t.TempDir()); !errors.Is(err, wantErr) {
|
||||
t.Fatalf("err = %v, want %v", err, wantErr)
|
||||
}
|
||||
}
|
||||
@@ -1,269 +0,0 @@
|
||||
package readiness
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/health"
|
||||
)
|
||||
|
||||
type fakeCounter struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func (f fakeCounter) StatusCounts(context.Context) (map[string]int, error) {
|
||||
return map[string]int{}, f.err
|
||||
}
|
||||
|
||||
func TestStoreProbe_ReadyOnCleanQuery(t *testing.T) {
|
||||
p := NewStoreProbe(fakeCounter{})
|
||||
if got := p.Check(context.Background()); got.Status != health.StatusOK {
|
||||
t.Fatalf("status = %q, want ok", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreProbe_DegradedOnError(t *testing.T) {
|
||||
p := NewStoreProbe(fakeCounter{err: errors.New("database is locked")})
|
||||
got := p.Check(context.Background())
|
||||
if got.Status != health.StatusDegraded {
|
||||
t.Fatalf("status = %q, want degraded", got.Status)
|
||||
}
|
||||
if got.Detail == "" {
|
||||
t.Fatalf("detail should explain the failure")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreProbe_DegradedWhenUnwired(t *testing.T) {
|
||||
p := &StoreProbe{}
|
||||
if got := p.Check(context.Background()); got.Status != health.StatusDegraded {
|
||||
t.Fatalf("status = %q, want degraded", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreProbe_Name(t *testing.T) {
|
||||
if got := NewStoreProbe(fakeCounter{}).Name(); got != "state_db" {
|
||||
t.Fatalf("name = %q, want state_db", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigProbe_ReadyOnValidConfig(t *testing.T) {
|
||||
p := NewConfigProbe(func() config.Config { return config.Config{BotUser: "b"} }, func(*config.Config) error { return nil })
|
||||
if got := p.Check(context.Background()); got.Status != health.StatusOK {
|
||||
t.Fatalf("status = %q, want ok", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigProbe_DegradedOnInvalidConfig(t *testing.T) {
|
||||
p := NewConfigProbe(func() config.Config { return config.Config{} }, func(*config.Config) error { return errors.New("bot_user required") })
|
||||
got := p.Check(context.Background())
|
||||
if got.Status != health.StatusDegraded {
|
||||
t.Fatalf("status = %q, want degraded", got.Status)
|
||||
}
|
||||
if got.Detail == "" {
|
||||
t.Fatalf("detail should explain the validation failure")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigProbe_DegradedWhenGetIsNil(t *testing.T) {
|
||||
p := NewConfigProbe(nil, func(*config.Config) error { return nil })
|
||||
if got := p.Check(context.Background()); got.Status != health.StatusDegraded {
|
||||
t.Fatalf("status = %q, want degraded", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigProbe_DegradedWhenValidatorIsNil(t *testing.T) {
|
||||
p := NewConfigProbe(func() config.Config { return config.Config{} }, nil)
|
||||
if got := p.Check(context.Background()); got.Status != health.StatusDegraded {
|
||||
t.Fatalf("status = %q, want degraded", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiskProbe_Name(t *testing.T) {
|
||||
if got := NewDiskProbe(".").Name(); got != "disk" {
|
||||
t.Fatalf("name = %q, want disk", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiskProbe_DegradedOnEmptyPath(t *testing.T) {
|
||||
p := NewDiskProbe("")
|
||||
if got := p.Check(context.Background()); got.Status != health.StatusDegraded {
|
||||
t.Fatalf("status = %q, want degraded", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiskProbe_DegradedOnBogusPath(t *testing.T) {
|
||||
p := NewDiskProbe("/this/path/does/not/exist/zzz")
|
||||
if got := p.Check(context.Background()); got.Status != health.StatusDegraded {
|
||||
t.Fatalf("status = %q, want degraded", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiskProbe_ReadyOnRealFilesystem(t *testing.T) {
|
||||
p := NewDiskProbe(t.TempDir())
|
||||
if got := p.Check(context.Background()); got.Status != health.StatusOK {
|
||||
t.Fatalf("status = %q, want ok (temp dir should be nearly empty): %s", got.Status, got.Detail)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiskProbe_ThresholdLogic(t *testing.T) {
|
||||
// A path that exists is a real filesystem; the threshold is the only
|
||||
// thing we can meaningfully vary here without mocking statfs. Assert that
|
||||
// a generous threshold (well above 100%) always passes, which it does
|
||||
// for any real used fraction.
|
||||
p := &DiskProbe{Path: t.TempDir(), Threshold: 2.0}
|
||||
if got := p.Check(context.Background()); got.Status != health.StatusOK {
|
||||
t.Fatalf("status = %q, want ok with threshold > 100%%", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelProbe_DegradedWhenNoModel(t *testing.T) {
|
||||
p := NewModelProbe(func() string { return "" }, func() []string { return nil }, nil)
|
||||
if got := p.Check(context.Background()); got.Status != health.StatusDegraded {
|
||||
t.Fatalf("status = %q, want degraded", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelProbe_ReadyOnConfiguredNoReachCheck(t *testing.T) {
|
||||
p := NewModelProbe(func() string { return "openai/gpt-4o" }, func() []string { return []string{"openai/gpt-4o"} }, nil)
|
||||
got := p.Check(context.Background())
|
||||
if got.Status != health.StatusOK {
|
||||
t.Fatalf("status = %q, want ok", got.Status)
|
||||
}
|
||||
if got.Detail == "" {
|
||||
t.Fatalf("detail should name the active model")
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelProbe_ReachSuccess(t *testing.T) {
|
||||
p := NewModelProbe(func() string { return "openai/gpt-4o" }, func() []string { return []string{"openai/gpt-4o"} }, func(context.Context) error { return nil })
|
||||
if got := p.Check(context.Background()); got.Status != health.StatusOK {
|
||||
t.Fatalf("status = %q, want ok", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelProbe_ReachFailure(t *testing.T) {
|
||||
p := NewModelProbe(func() string { return "openai/gpt-4o" }, func() []string { return []string{"openai/gpt-4o"} }, func(context.Context) error { return errors.New("connection refused") })
|
||||
got := p.Check(context.Background())
|
||||
if got.Status != health.StatusDegraded {
|
||||
t.Fatalf("status = %q, want degraded", got.Status)
|
||||
}
|
||||
if got.Detail == "" {
|
||||
t.Fatalf("detail should explain the reachability failure")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayProbe_ReadyWithRunningChannels(t *testing.T) {
|
||||
p := NewGatewayProbe(func() []ChannelState {
|
||||
return []ChannelState{{ID: "telegram", Configured: true, State: "running"}}
|
||||
}, func(context.Context) int { return 3 })
|
||||
got := p.Check(context.Background())
|
||||
if got.Status != health.StatusOK {
|
||||
t.Fatalf("status = %q, want ok", got.Status)
|
||||
}
|
||||
if got.Detail == "" {
|
||||
t.Fatalf("detail should report channel and session counts")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayProbe_DegradedWhenNoChannelsConfigured(t *testing.T) {
|
||||
p := NewGatewayProbe(func() []ChannelState {
|
||||
return []ChannelState{{ID: "telegram", Configured: false, State: "stopped"}}
|
||||
}, func(context.Context) int { return 0 })
|
||||
if got := p.Check(context.Background()); got.Status != health.StatusDegraded {
|
||||
t.Fatalf("status = %q, want degraded", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayProbe_DegradedWhenChannelFailed(t *testing.T) {
|
||||
p := NewGatewayProbe(func() []ChannelState {
|
||||
return []ChannelState{
|
||||
{ID: "telegram", Configured: true, State: "failed"},
|
||||
{ID: "email", Configured: true, State: "running"},
|
||||
}
|
||||
}, func(context.Context) int { return 5 })
|
||||
if got := p.Check(context.Background()); got.Status != health.StatusDegraded {
|
||||
t.Fatalf("status = %q, want degraded", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayProbe_DegradedWhenNoChannelRunning(t *testing.T) {
|
||||
p := NewGatewayProbe(func() []ChannelState {
|
||||
return []ChannelState{{ID: "telegram", Configured: true, State: "stopped"}}
|
||||
}, func(context.Context) int { return 0 })
|
||||
if got := p.Check(context.Background()); got.Status != health.StatusDegraded {
|
||||
t.Fatalf("status = %q, want degraded", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
// A required path must not inherit the rules of an earlier optional target on
|
||||
// the same path. Dedup keeps one target per path, and when the optional target
|
||||
// is the one kept, a required path that has gone missing is swallowed as
|
||||
// "optional absent" -- reporting OK while a path the daemon needs is
|
||||
// unavailable. Retaining required status for a path that any target requires
|
||||
// is the fix.
|
||||
func TestDiskProbe_DedupKeepsRequiredWhenOptionalSharesThePath(t *testing.T) {
|
||||
fs := fakeStatfs(map[string]syscall.Statfs_t{
|
||||
"/": {Blocks: 100, Bavail: 100}, // a healthy target keeps the detail list non-empty
|
||||
})
|
||||
// Production orders root first, then the optional /var, then the
|
||||
// config-supplied data path -- which can resolve to /var and collide.
|
||||
p := NewDiskProbeTargets([]DiskTarget{
|
||||
{Name: "root", Path: "/"},
|
||||
{Name: "var", Path: "/var", Optional: true},
|
||||
{Name: "data", Path: "/var"},
|
||||
})
|
||||
p.Statfs = fs.statfs
|
||||
|
||||
got := p.Check(context.Background())
|
||||
if got.Status != health.StatusDegraded {
|
||||
t.Fatalf("status = %q, want degraded: a required path that has vanished must not be reported OK via an optional target's rules (detail: %s)",
|
||||
got.Status, got.Detail)
|
||||
}
|
||||
if !strings.Contains(got.Detail, "data") {
|
||||
t.Fatalf("detail = %q, want the required target named", got.Detail)
|
||||
}
|
||||
}
|
||||
|
||||
// The inverse: when the kept target is genuinely optional and only optional
|
||||
// targets share the path, an absent path still degrades nothing.
|
||||
func TestDiskProbe_DedupKeepsOptionalWhenNoTargetRequiresThePath(t *testing.T) {
|
||||
fs := fakeStatfs(map[string]syscall.Statfs_t{
|
||||
"/": {Blocks: 100, Bavail: 100},
|
||||
})
|
||||
p := NewDiskProbeTargets([]DiskTarget{
|
||||
{Name: "root", Path: "/"},
|
||||
{Name: "var", Path: "/var", Optional: true},
|
||||
{Name: "var-dup", Path: "/var", Optional: true},
|
||||
})
|
||||
p.Statfs = fs.statfs
|
||||
|
||||
got := p.Check(context.Background())
|
||||
if got.Status != health.StatusOK {
|
||||
t.Fatalf("status = %q, want ok: an optional path absent entirely is not a failure (detail: %s)", got.Status, got.Detail)
|
||||
}
|
||||
}
|
||||
|
||||
// fakeStatfs returns a statfs replacement serving sizes for known paths and
|
||||
// ENOENT for anything else, so a test can drive the disk probe without
|
||||
// filling a real filesystem.
|
||||
func fakeStatfs(sizes map[string]syscall.Statfs_t) struct {
|
||||
statfs func(string, *syscall.Statfs_t) error
|
||||
} {
|
||||
return struct {
|
||||
statfs func(string, *syscall.Statfs_t) error
|
||||
}{
|
||||
statfs: func(path string, out *syscall.Statfs_t) error {
|
||||
stat, ok := sizes[path]
|
||||
if !ok {
|
||||
return os.ErrNotExist
|
||||
}
|
||||
*out = stat
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package nats
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestWithDefaults(t *testing.T) {
|
||||
cfg := (Config{}).withDefaults()
|
||||
if cfg.Bucket != DefaultBucket {
|
||||
t.Errorf("withDefaults().Bucket = %q, want %q", cfg.Bucket, DefaultBucket)
|
||||
}
|
||||
if cfg.InstalledBucket != DefaultInstalledBucket {
|
||||
t.Errorf("withDefaults().InstalledBucket = %q, want %q", cfg.InstalledBucket, DefaultInstalledBucket)
|
||||
}
|
||||
if cfg.TTL != DefaultTTL {
|
||||
t.Errorf("withDefaults().TTL = %v, want %v", cfg.TTL, DefaultTTL)
|
||||
}
|
||||
if cfg.Heartbeat != DefaultHeartbeat {
|
||||
t.Errorf("withDefaults().Heartbeat = %v, want %v", cfg.Heartbeat, DefaultHeartbeat)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
cfg Config
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "valid", cfg: Config{URL: "nats://x", TTL: 15 * time.Second, Heartbeat: 5 * time.Second}, wantErr: false},
|
||||
{name: "missing url", cfg: Config{TTL: time.Second, Heartbeat: 200 * time.Millisecond}, wantErr: true},
|
||||
{name: "heartbeat equals ttl", cfg: Config{URL: "nats://x", TTL: time.Second, Heartbeat: time.Second}, wantErr: true},
|
||||
{name: "heartbeat exceeds ttl", cfg: Config{URL: "nats://x", TTL: time.Second, Heartbeat: 2 * time.Second}, wantErr: true},
|
||||
{name: "negative durations", cfg: Config{URL: "nats://x", TTL: -time.Second, Heartbeat: time.Second}, wantErr: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := tt.cfg.Validate()
|
||||
if tt.wantErr {
|
||||
if !errors.Is(err, ErrInvalidConfig) {
|
||||
t.Fatalf("Validate() = %v, want ErrInvalidConfig", err)
|
||||
}
|
||||
} else if err != nil {
|
||||
t.Fatalf("Validate() = %v, want nil", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package nats
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestEndpointKey(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
service string
|
||||
id string
|
||||
want string
|
||||
}{
|
||||
{name: "simple", service: "curator", id: "inst-1", want: "curator.inst-1"},
|
||||
{name: "single-char id", service: "scheduler", id: "a", want: "scheduler.a"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := endpointKey(tt.service, tt.id); got != tt.want {
|
||||
t.Errorf("endpointKey(%q, %q) = %q, want %q", tt.service, tt.id, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEndpointKeyPrefix(t *testing.T) {
|
||||
if got := endpointKeyPrefix("curator"); got != "curator.*" {
|
||||
t.Errorf("endpointKeyPrefix(curator) = %q, want %q", got, "curator.*")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIDFromEndpointKey(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
service string
|
||||
key string
|
||||
want string
|
||||
}{
|
||||
{name: "own key returns id", service: "curator", key: "curator.inst-1", want: "inst-1"},
|
||||
{name: "other service", service: "curator", key: "scheduler.inst", want: ""},
|
||||
{name: "empty id", service: "curator", key: "curator.", want: ""},
|
||||
{name: "key equals prefix", service: "curator", key: "curator", want: ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := idFromEndpointKey(tt.service, tt.key); got != tt.want {
|
||||
t.Errorf("idFromEndpointKey(%q, %q) = %q, want %q", tt.service, tt.key, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,310 +0,0 @@
|
||||
package nats
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
natstest "github.com/nats-io/nats-server/v2/test"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/servicediscovery"
|
||||
)
|
||||
|
||||
// discardLogger silences the registry logger in tests, matching the sibling
|
||||
// eventbus/nats test convention.
|
||||
func discardLogger() *slog.Logger { return slog.New(slog.DiscardHandler) }
|
||||
|
||||
// testConfig returns a discovery Config with a short TTL/heartbeat so tests
|
||||
// exercise expiry quickly without relying on a fixture elsewhere.
|
||||
func testConfig() Config {
|
||||
return Config{TTL: time.Second, Heartbeat: 200 * time.Millisecond}
|
||||
}
|
||||
|
||||
// TestConnectRejectsTTLBelowDefaultHeartbeat pins the Connect ordering: a
|
||||
// caller that sets TTL below DefaultHeartbeat and leaves Heartbeat unset must
|
||||
// be refused as ErrInvalidConfig, not silently given a registry whose live
|
||||
// entries expire between refreshes (DefaultHeartbeat >= TTL).
|
||||
func TestConnectRejectsTTLBelowDefaultHeartbeat(t *testing.T) {
|
||||
_, err := Connect(context.Background(), Config{URL: "nats://127.0.0.1:1", TTL: 2 * time.Second}, discardLogger())
|
||||
if !errors.Is(err, ErrInvalidConfig) {
|
||||
t.Fatalf("Connect() = %v, want ErrInvalidConfig", err)
|
||||
}
|
||||
}
|
||||
|
||||
// newServer starts a real in-process NATS server with JetStream enabled. This
|
||||
// is the established test technique for the NATS infrastructure (see the
|
||||
// sibling eventbus/nats retention test): a real server, not a mocked client.
|
||||
func newServer(t *testing.T) *server.Server {
|
||||
t.Helper()
|
||||
srv := natstest.RunServer(&server.Options{
|
||||
Port: -1,
|
||||
JetStream: true,
|
||||
StoreDir: t.TempDir(),
|
||||
})
|
||||
t.Cleanup(srv.Shutdown)
|
||||
return srv
|
||||
}
|
||||
|
||||
// newClient connects a registry client to a fresh server with the given config.
|
||||
// Cleanup closes the connection after the caller's own cleanups (registered
|
||||
// later) have run, so a caller can cancel registration contexts first.
|
||||
func newClient(t *testing.T, cfg Config) *Client {
|
||||
t.Helper()
|
||||
cfg.URL = newServer(t).ClientURL()
|
||||
c, err := Connect(context.Background(), cfg, discardLogger())
|
||||
if err != nil {
|
||||
t.Fatalf("Connect = %v", err)
|
||||
}
|
||||
t.Cleanup(c.Close)
|
||||
return c
|
||||
}
|
||||
|
||||
// expectEvent reads from a Watch channel until it observes the wanted event,
|
||||
// discarding unrelated early events (e.g. the rest of an initial snapshot).
|
||||
func expectEvent(t *testing.T, ch <-chan servicediscovery.Event, want servicediscovery.Event) {
|
||||
t.Helper()
|
||||
deadline := time.NewTimer(10 * time.Second)
|
||||
defer deadline.Stop()
|
||||
for {
|
||||
select {
|
||||
case ev, ok := <-ch:
|
||||
if !ok {
|
||||
t.Fatalf("watch channel closed before %s for %s", want.Kind, want.Endpoint.ID)
|
||||
}
|
||||
if ev == want {
|
||||
return
|
||||
}
|
||||
case <-deadline.C:
|
||||
t.Fatalf("timed out waiting for %s for %s", want.Kind, want.Endpoint.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegistryResolveNotInstalled pins that a service that was never registered
|
||||
// resolves to ErrNotInstalled, not an empty roster.
|
||||
func TestRegistryResolveNotInstalled(t *testing.T) {
|
||||
client := newClient(t, testConfig())
|
||||
_, err := client.Resolve(context.Background(), "curator")
|
||||
if !errors.Is(err, servicediscovery.ErrNotInstalled) {
|
||||
t.Fatalf("Resolve(unregistered) = %v, want ErrNotInstalled", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegistryWatchNotInstalled pins that watching a never-registered service
|
||||
// returns ErrNotInstalled at call time.
|
||||
func TestRegistryWatchNotInstalled(t *testing.T) {
|
||||
client := newClient(t, testConfig())
|
||||
_, err := client.Watch(context.Background(), "curator")
|
||||
if !errors.Is(err, servicediscovery.ErrNotInstalled) {
|
||||
t.Fatalf("Watch(unregistered) = %v, want ErrNotInstalled", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegistryRegisterResolve covers registration and a single-instance resolve.
|
||||
func TestRegistryRegisterResolve(t *testing.T) {
|
||||
client := newClient(t, testConfig())
|
||||
regCtx, regCancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(regCancel)
|
||||
|
||||
reg, err := client.Register(regCtx, "curator", servicediscovery.Endpoint{
|
||||
ID: "inst-1",
|
||||
Address: "127.0.0.1:5001",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Register = %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = reg.Unregister(context.Background()) })
|
||||
|
||||
eps, err := client.Resolve(context.Background(), "curator")
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve after Register = %v", err)
|
||||
}
|
||||
if len(eps) != 1 {
|
||||
t.Fatalf("Resolve length = %d, want 1: %+v", len(eps), eps)
|
||||
}
|
||||
got := eps[0]
|
||||
want := servicediscovery.Endpoint{Service: "curator", ID: "inst-1", Address: "127.0.0.1:5001"}
|
||||
if got != want {
|
||||
t.Errorf("Resolve endpoint = %+v, want %+v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegistryRegisterResolveMultiple proves multiple instances of one service
|
||||
// resolve together, ordered deterministically by ID.
|
||||
func TestRegistryRegisterResolveMultiple(t *testing.T) {
|
||||
client := newClient(t, testConfig())
|
||||
regCtx, regCancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(regCancel)
|
||||
|
||||
instances := []servicediscovery.Endpoint{
|
||||
{ID: "b", Address: "127.0.0.1:5002"},
|
||||
{ID: "a", Address: "127.0.0.1:5001"},
|
||||
}
|
||||
var regs []*Registration
|
||||
for _, ep := range instances {
|
||||
reg, err := client.Register(regCtx, "curator", ep)
|
||||
if err != nil {
|
||||
t.Fatalf("Register %s = %v", ep.ID, err)
|
||||
}
|
||||
regs = append(regs, reg)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
for _, r := range regs {
|
||||
_ = r.Unregister(context.Background())
|
||||
}
|
||||
})
|
||||
|
||||
eps, err := client.Resolve(context.Background(), "curator")
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve = %v", err)
|
||||
}
|
||||
if len(eps) != 2 {
|
||||
t.Fatalf("Resolve length = %d, want 2: %+v", len(eps), eps)
|
||||
}
|
||||
if eps[0].ID != "a" || eps[1].ID != "b" {
|
||||
t.Errorf("Resolve order = %s, %s; want a, b", eps[0].ID, eps[1].ID)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegistryResolveInstalledButDown is the contract's governing semantic: a
|
||||
// service that registered but has no live endpoint resolves to an empty,
|
||||
// non-error roster, distinct from ErrNotInstalled.
|
||||
func TestRegistryResolveInstalledButDown(t *testing.T) {
|
||||
client := newClient(t, testConfig())
|
||||
regCtx, regCancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(regCancel)
|
||||
|
||||
reg, err := client.Register(regCtx, "curator", servicediscovery.Endpoint{
|
||||
ID: "inst-1",
|
||||
Address: "127.0.0.1:5001",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Register = %v", err)
|
||||
}
|
||||
if err := reg.Unregister(context.Background()); err != nil {
|
||||
t.Fatalf("Unregister = %v", err)
|
||||
}
|
||||
|
||||
// The installed marker persists, so the service is still installed; it just
|
||||
// has no live endpoints.
|
||||
eps, err := client.Resolve(context.Background(), "curator")
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve after Unregister = %v, want nil (installed but down)", err)
|
||||
}
|
||||
if len(eps) != 0 {
|
||||
t.Fatalf("Resolve length = %d, want 0 for installed-but-down service", len(eps))
|
||||
}
|
||||
if eps == nil {
|
||||
t.Fatal("Resolve returned nil slice, want a non-nil empty slice")
|
||||
}
|
||||
|
||||
_, err = client.Resolve(context.Background(), "never-installed")
|
||||
if !errors.Is(err, servicediscovery.ErrNotInstalled) {
|
||||
t.Fatalf("Resolve(never-installed) = %v, want ErrNotInstalled", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegistryWatchJoinLeave covers Join and Leave emission, including the
|
||||
// initial snapshot and a heartbeat refresh not being re-emitted as a Join.
|
||||
func TestRegistryWatchJoinLeave(t *testing.T) {
|
||||
client := newClient(t, testConfig())
|
||||
|
||||
// Register A first so its entry is part of the initial watch snapshot and
|
||||
// the installed marker is present before Watch.
|
||||
regCtx, regCancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(regCancel)
|
||||
regA, err := client.Register(regCtx, "curator", servicediscovery.Endpoint{ID: "a", Address: "127.0.0.1:5001"})
|
||||
if err != nil {
|
||||
t.Fatalf("Register a = %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = regA.Unregister(context.Background()) })
|
||||
|
||||
watchCtx, watchCancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(watchCancel)
|
||||
events, err := client.Watch(watchCtx, "curator")
|
||||
if err != nil {
|
||||
t.Fatalf("Watch = %v", err)
|
||||
}
|
||||
|
||||
// Initial snapshot delivers the pre-existing instance as a Join.
|
||||
expectEvent(t, events, servicediscovery.Event{
|
||||
Kind: servicediscovery.Join,
|
||||
Endpoint: servicediscovery.Endpoint{Service: "curator", ID: "a", Address: "127.0.0.1:5001"},
|
||||
})
|
||||
|
||||
// A new instance joining is a Join.
|
||||
regB, err := client.Register(regCtx, "curator", servicediscovery.Endpoint{ID: "b", Address: "127.0.0.1:5002"})
|
||||
if err != nil {
|
||||
t.Fatalf("Register b = %v", err)
|
||||
}
|
||||
expectEvent(t, events, servicediscovery.Event{
|
||||
Kind: servicediscovery.Join,
|
||||
Endpoint: servicediscovery.Endpoint{Service: "curator", ID: "b", Address: "127.0.0.1:5002"},
|
||||
})
|
||||
|
||||
// An explicit unregister is a Leave.
|
||||
if err := regB.Unregister(context.Background()); err != nil {
|
||||
t.Fatalf("Unregister b = %v", err)
|
||||
}
|
||||
expectEvent(t, events, servicediscovery.Event{
|
||||
Kind: servicediscovery.Leave,
|
||||
Endpoint: servicediscovery.Endpoint{Service: "curator", ID: "b"},
|
||||
})
|
||||
}
|
||||
|
||||
// TestRegistryWatchHeartbeatExpiry proves that a stopped heartbeat leads to a
|
||||
// Leave via the bucket TTL (installed-but-down), not to a flapping re-Join of
|
||||
// the same ID.
|
||||
func TestRegistryWatchHeartbeatExpiry(t *testing.T) {
|
||||
cfg := testConfig()
|
||||
cfg.TTL = 600 * time.Millisecond
|
||||
cfg.Heartbeat = 100 * time.Millisecond
|
||||
client := newClient(t, cfg)
|
||||
|
||||
regCtx, regCancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(regCancel)
|
||||
reg, err := client.Register(regCtx, "curator", servicediscovery.Endpoint{ID: "exp", Address: "127.0.0.1:5001"})
|
||||
if err != nil {
|
||||
t.Fatalf("Register = %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = reg.Unregister(context.Background()) })
|
||||
|
||||
watchCtx, watchCancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(watchCancel)
|
||||
events, err := client.Watch(watchCtx, "curator")
|
||||
if err != nil {
|
||||
t.Fatalf("Watch = %v", err)
|
||||
}
|
||||
expectEvent(t, events, servicediscovery.Event{
|
||||
Kind: servicediscovery.Join,
|
||||
Endpoint: servicediscovery.Endpoint{Service: "curator", ID: "exp", Address: "127.0.0.1:5001"},
|
||||
})
|
||||
|
||||
// Stop the heartbeat; the entry is no longer refreshed and expires via TTL.
|
||||
regCancel()
|
||||
|
||||
expectEvent(t, events, servicediscovery.Event{
|
||||
Kind: servicediscovery.Leave,
|
||||
Endpoint: servicediscovery.Endpoint{Service: "curator", ID: "exp"},
|
||||
})
|
||||
|
||||
// The service is still installed (its marker persists), so Resolve is an
|
||||
// empty, non-error roster -- not ErrNotInstalled.
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for {
|
||||
eps, err := client.Resolve(context.Background(), "curator")
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve after expiry = %v, want nil (installed but down)", err)
|
||||
}
|
||||
if len(eps) == 0 {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("Resolve still reports %d live endpoints after heartbeat expiry", len(eps))
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
package sessioncurator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
)
|
||||
|
||||
func newTestStore(t *testing.T) gateway.SessionStore {
|
||||
t.Helper()
|
||||
s := gateway.NewSessionStoreMemory()
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
return s
|
||||
}
|
||||
|
||||
func TestAdapterRecentSessionsFiltersByActivity(t *testing.T) {
|
||||
t.Parallel()
|
||||
store := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
|
||||
old := gateway.SessionContext{SessionID: "old", LastActiveAt: time.Unix(100, 0)}
|
||||
recent := gateway.SessionContext{SessionID: "recent", LastActiveAt: time.Unix(2000, 0)}
|
||||
if err := store.Save(ctx, old); err != nil {
|
||||
t.Fatalf("Save(old) = %v", err)
|
||||
}
|
||||
if err := store.Save(ctx, recent); err != nil {
|
||||
t.Fatalf("Save(recent) = %v", err)
|
||||
}
|
||||
|
||||
a := NewAdapter(store, "archie-bot")
|
||||
got, err := a.RecentSessions(ctx, time.Unix(1000, 0))
|
||||
if err != nil {
|
||||
t.Fatalf("RecentSessions() = %v, want nil", err)
|
||||
}
|
||||
if len(got) != 1 || got[0].ID != "recent" {
|
||||
t.Fatalf("RecentSessions() = %v, want only 'recent'", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdapterMessagesReadsRoleFromRecords(t *testing.T) {
|
||||
t.Parallel()
|
||||
store := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
|
||||
sess := gateway.SessionContext{SessionID: "s1", LastActiveAt: time.Unix(1000, 0)}
|
||||
if err := store.Save(ctx, sess); err != nil {
|
||||
t.Fatalf("Save() = %v", err)
|
||||
}
|
||||
// Roles are set by whoever produced the message; the adapter reads them
|
||||
// from the records, needing no bot identity of its own.
|
||||
for _, m := range []messaging.Message{
|
||||
{Sender: "user123", Role: messaging.RoleUser, Text: "hello", At: time.Unix(1, 0)},
|
||||
{Sender: "archie", Role: messaging.RoleAssistant, Text: "hi there", At: time.Unix(2, 0)},
|
||||
} {
|
||||
if err := store.SaveMessage(ctx, "s1", m); err != nil {
|
||||
t.Fatalf("SaveMessage(%v) = %v", m, err)
|
||||
}
|
||||
}
|
||||
// A hand-built record without a role reads as a user message.
|
||||
if err := store.SaveMessage(ctx, "s1", messaging.Message{Text: "bare", At: time.Unix(3, 0)}); err != nil {
|
||||
t.Fatalf("SaveMessage(bare) = %v", err)
|
||||
}
|
||||
|
||||
a := NewAdapter(store, "archie-bot")
|
||||
got, err := a.Messages(ctx, "s1", 10)
|
||||
if err != nil {
|
||||
t.Fatalf("Messages() = %v, want nil", err)
|
||||
}
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("Messages() = %v, want 3", got)
|
||||
}
|
||||
if got[0].Role != "user" || got[0].Content != "hello" {
|
||||
t.Errorf("Messages()[0] = %+v, want user/hello", got[0])
|
||||
}
|
||||
if got[1].Role != "assistant" || got[1].Content != "hi there" {
|
||||
t.Errorf("Messages()[1] = %+v, want assistant/hi there", got[1])
|
||||
}
|
||||
if got[2].Role != "user" || got[2].Content != "bare" {
|
||||
t.Errorf("Messages()[2] = %+v, want user/bare", got[2])
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdapterRecentSessionsCarriesAgentID pins that the agent a session's
|
||||
// memory is addressed to comes from the composition, not from the record's
|
||||
// own BotUser: BotUser is the router's session-resolution key
|
||||
// (gateway/session_commands.go), which is empty in a single-identity
|
||||
// deployment -- an addressing component, never a match key.
|
||||
func TestAdapterRecentSessionsCarriesAgentID(t *testing.T) {
|
||||
t.Parallel()
|
||||
store := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
|
||||
sess := gateway.SessionContext{
|
||||
SessionID: "s1",
|
||||
Source: messaging.SessionSource{Platform: "telegram", BotUser: "primary", ChannelID: "chat-1"},
|
||||
LastActiveAt: time.Unix(2000, 0),
|
||||
}
|
||||
if err := store.Save(ctx, sess); err != nil {
|
||||
t.Fatalf("Save() = %v", err)
|
||||
}
|
||||
|
||||
got, err := NewAdapter(store, "archie-bot").RecentSessions(ctx, time.Unix(1000, 0))
|
||||
if err != nil {
|
||||
t.Fatalf("RecentSessions() = %v, want nil", err)
|
||||
}
|
||||
if len(got) != 1 || got[0].AgentID != "archie-bot" {
|
||||
t.Fatalf("RecentSessions() = %+v, want one session whose AgentID is the composition's %q", got, "archie-bot")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdapterMessagesCarriesSenderID pins that the channel-native participant
|
||||
// identifier survives the store-to-curator hop, and stays empty for a message
|
||||
// whose channel offers none.
|
||||
func TestAdapterMessagesCarriesSenderID(t *testing.T) {
|
||||
t.Parallel()
|
||||
store := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
|
||||
if err := store.Save(ctx, gateway.SessionContext{SessionID: "s1", LastActiveAt: time.Unix(1000, 0)}); err != nil {
|
||||
t.Fatalf("Save() = %v", err)
|
||||
}
|
||||
for _, m := range []messaging.Message{
|
||||
{Sender: "alice", SenderID: "u-42", Role: messaging.RoleUser, Text: "hello", At: time.Unix(1, 0)},
|
||||
{Sender: "archie", Role: messaging.RoleAssistant, Text: "hi", At: time.Unix(2, 0)},
|
||||
} {
|
||||
if err := store.SaveMessage(ctx, "s1", m); err != nil {
|
||||
t.Fatalf("SaveMessage(%v) = %v", m, err)
|
||||
}
|
||||
}
|
||||
|
||||
got, err := NewAdapter(store, "archie-bot").Messages(ctx, "s1", 10)
|
||||
if err != nil {
|
||||
t.Fatalf("Messages() = %v, want nil", err)
|
||||
}
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("Messages() = %+v, want 2", got)
|
||||
}
|
||||
if got[0].SenderID != "u-42" {
|
||||
t.Errorf("Messages()[0].SenderID = %q, want %q", got[0].SenderID, "u-42")
|
||||
}
|
||||
if got[1].SenderID != "" {
|
||||
t.Errorf("Messages()[1].SenderID = %q, want empty", got[1].SenderID)
|
||||
}
|
||||
}
|
||||
@@ -1,780 +0,0 @@
|
||||
package sessioncurator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/curator"
|
||||
domainmemory "github.com/samcharles93/archie-core/internal/domain/memory"
|
||||
infraMemory "github.com/samcharles93/archie-core/internal/infrastructure/memory"
|
||||
)
|
||||
|
||||
// --- fakes -------------------------------------------------------------
|
||||
|
||||
type fakeConversations struct {
|
||||
sessions map[string]time.Time // id -> last active
|
||||
agents map[string]string // id -> the agent that served it
|
||||
messages map[string][]curator.ConversationMessage
|
||||
}
|
||||
|
||||
func (f *fakeConversations) RecentSessions(_ context.Context, since time.Time) ([]curator.SessionSummary, error) {
|
||||
var out []curator.SessionSummary
|
||||
for id, at := range f.sessions {
|
||||
if at.Before(since) {
|
||||
continue
|
||||
}
|
||||
out = append(out, curator.SessionSummary{ID: id, AgentID: f.agents[id], LastActive: at})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *fakeConversations) Messages(_ context.Context, sessionID string, n int) ([]curator.ConversationMessage, error) {
|
||||
msgs := f.messages[sessionID]
|
||||
if len(msgs) > n {
|
||||
msgs = msgs[len(msgs)-n:]
|
||||
}
|
||||
return msgs, nil
|
||||
}
|
||||
|
||||
// newFakeConversations builds the single-session fixture every write-path
|
||||
// case starts from: session "s1", served by agent "winter", with the given
|
||||
// message tail.
|
||||
func newFakeConversations(msgs ...curator.ConversationMessage) *fakeConversations {
|
||||
return &fakeConversations{
|
||||
sessions: map[string]time.Time{"s1": time.Unix(1000, 0)},
|
||||
agents: map[string]string{"s1": "winter"},
|
||||
messages: map[string][]curator.ConversationMessage{"s1": msgs},
|
||||
}
|
||||
}
|
||||
|
||||
// fakeLLM returns a canned response per call, or the same response every
|
||||
// time if only one is configured.
|
||||
type fakeLLM struct {
|
||||
responses []string
|
||||
err error
|
||||
calls int
|
||||
}
|
||||
|
||||
func (f *fakeLLM) Chat(context.Context, curator.ChatRequest) (curator.ChatResult, error) {
|
||||
if f.err != nil {
|
||||
return curator.ChatResult{}, f.err
|
||||
}
|
||||
i := f.calls
|
||||
f.calls++
|
||||
if i >= len(f.responses) {
|
||||
i = len(f.responses) - 1
|
||||
}
|
||||
return curator.ChatResult{Text: f.responses[i]}, nil
|
||||
}
|
||||
|
||||
// fakeEngine records what the curator asked it to create. domain/memory's
|
||||
// own fake engine is unexported in its package's test files, so this one is
|
||||
// minimal on purpose: the read half exists only to satisfy MemoryEngine.
|
||||
type fakeEngine struct {
|
||||
created []domainmemory.NewRecord
|
||||
createErr error
|
||||
}
|
||||
|
||||
func (f *fakeEngine) Name() string { return "builtin" }
|
||||
func (f *fakeEngine) Version() string { return "test" }
|
||||
func (f *fakeEngine) Manifest() domainmemory.Manifest { return domainmemory.Manifest{} }
|
||||
func (f *fakeEngine) Bind(domainmemory.Registrar) {}
|
||||
func (f *fakeEngine) Start(context.Context) error { return nil }
|
||||
func (f *fakeEngine) Health(context.Context) domainmemory.Health {
|
||||
return domainmemory.Health{Status: domainmemory.HealthHealthy}
|
||||
}
|
||||
func (f *fakeEngine) Stop(context.Context) error { return nil }
|
||||
|
||||
func (f *fakeEngine) Create(_ context.Context, in domainmemory.NewRecord) (domainmemory.Record, error) {
|
||||
if f.createErr != nil {
|
||||
return domainmemory.Record{}, f.createErr
|
||||
}
|
||||
f.created = append(f.created, in)
|
||||
return domainmemory.Record{
|
||||
ID: domainmemory.RecordID(fmt.Sprintf("r%d", len(f.created))),
|
||||
Scope: in.Scope,
|
||||
Kind: in.Kind,
|
||||
Content: in.Content,
|
||||
Author: in.Author,
|
||||
OriginUser: in.OriginUser,
|
||||
Source: in.Source,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (f *fakeEngine) Get(context.Context, domainmemory.Scope, domainmemory.RecordID) (domainmemory.Record, error) {
|
||||
return domainmemory.Record{}, domainmemory.ErrNotFound
|
||||
}
|
||||
|
||||
func (f *fakeEngine) Query(context.Context, domainmemory.Query) ([]domainmemory.Record, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (f *fakeEngine) List(context.Context, domainmemory.Scope) ([]domainmemory.Record, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (f *fakeEngine) Update(context.Context, domainmemory.RecordUpdate) (domainmemory.Record, error) {
|
||||
return domainmemory.Record{}, domainmemory.ErrNotFound
|
||||
}
|
||||
|
||||
func (f *fakeEngine) Forget(context.Context, domainmemory.Scope, domainmemory.RecordID) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeEngine) Revisions(context.Context, domainmemory.Scope, domainmemory.RecordID) ([]domainmemory.Revision, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type fakeEngineSource struct{ engine *fakeEngine }
|
||||
|
||||
func (f fakeEngineSource) Get(name string) (domainmemory.MemoryEngine, bool) {
|
||||
if name != "builtin" {
|
||||
return nil, false
|
||||
}
|
||||
return f.engine, true
|
||||
}
|
||||
|
||||
// engineSource adapts one memory engine under the name the curator is built
|
||||
// with, so a case can bind the real builtin engine where the fake's refusal
|
||||
// behaviour would hide what the engine actually validates.
|
||||
type engineSource struct{ engine domainmemory.MemoryEngine }
|
||||
|
||||
func (s engineSource) Get(name string) (domainmemory.MemoryEngine, bool) {
|
||||
if name != "builtin" {
|
||||
return nil, false
|
||||
}
|
||||
return s.engine, true
|
||||
}
|
||||
|
||||
func newTestCuratorWithEngine(t *testing.T, conv curator.ConversationSource, llm curator.LLMRunner, engine domainmemory.MemoryEngine) *Curator {
|
||||
t.Helper()
|
||||
c := New(time.Hour, "builtin")
|
||||
c.Bind(curator.Registrar{
|
||||
Conversations: conv,
|
||||
LLM: llm,
|
||||
MemoryEngines: engineSource{engine: engine},
|
||||
Clock: testClock{now: time.Unix(1000, 0)},
|
||||
})
|
||||
return c
|
||||
}
|
||||
|
||||
// engineScopeDirs names the per-scope directories a real engine has written
|
||||
// to. It persists one directory per scope it has ever written, so an empty
|
||||
// root is an engine holding no records at all -- the only root-wide view the
|
||||
// engine's scope-addressed read surface can't give a test.
|
||||
func engineScopeDirs(t *testing.T, root string) []string {
|
||||
t.Helper()
|
||||
entries, err := os.ReadDir(root)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadDir(%s) = %v", root, err)
|
||||
}
|
||||
names := make([]string, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
names = append(names, e.Name())
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
type testClock struct{ now time.Time }
|
||||
|
||||
func (c testClock) Now() time.Time { return c.now }
|
||||
func (c testClock) After(d time.Duration) <-chan time.Time { return time.After(d) }
|
||||
|
||||
func newTestCurator(t *testing.T, conv *fakeConversations, llm *fakeLLM, engine *fakeEngine) *Curator {
|
||||
t.Helper()
|
||||
c := New(time.Hour, "builtin")
|
||||
c.Bind(curator.Registrar{
|
||||
Conversations: conv,
|
||||
LLM: llm,
|
||||
MemoryEngines: fakeEngineSource{engine: engine},
|
||||
Clock: testClock{now: time.Unix(1000, 0)},
|
||||
})
|
||||
return c
|
||||
}
|
||||
|
||||
// --- tests ---------------------------------------------------------------
|
||||
|
||||
func TestCheckReportsFalseWithNoRecentSessions(t *testing.T) {
|
||||
t.Parallel()
|
||||
conv := &fakeConversations{sessions: map[string]time.Time{}}
|
||||
c := newTestCurator(t, conv, &fakeLLM{}, &fakeEngine{})
|
||||
|
||||
ok, err := c.Check(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Check() = %v, want nil", err)
|
||||
}
|
||||
if ok {
|
||||
t.Error("Check() = true, want false: no recent sessions")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckReportsTrueWithARecentSession(t *testing.T) {
|
||||
t.Parallel()
|
||||
conv := &fakeConversations{sessions: map[string]time.Time{"s1": time.Unix(1000, 0)}}
|
||||
c := newTestCurator(t, conv, &fakeLLM{}, &fakeEngine{})
|
||||
|
||||
ok, err := c.Check(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Check() = %v, want nil", err)
|
||||
}
|
||||
if !ok {
|
||||
t.Error("Check() = false, want true: a session is recently active")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPassExtractsAndWritesObservations(t *testing.T) {
|
||||
t.Parallel()
|
||||
conv := newFakeConversations(curator.ConversationMessage{Role: "user", SenderID: "u-42", Content: "I prefer tabs over spaces"})
|
||||
llm := &fakeLLM{responses: []string{`["prefers tabs over spaces"]`}}
|
||||
engine := &fakeEngine{}
|
||||
c := newTestCurator(t, conv, llm, engine)
|
||||
|
||||
res, err := c.Pass(context.Background(), curator.PassInput{})
|
||||
if err != nil {
|
||||
t.Fatalf("Pass() = %v, want nil", err)
|
||||
}
|
||||
if len(res.Actions) != 1 || res.Actions[0].Type != ActionExtracted {
|
||||
t.Fatalf("Actions = %#v, want one %s", res.Actions, ActionExtracted)
|
||||
}
|
||||
if want := time.Unix(1000, 0); !res.Actions[0].At.Equal(want) {
|
||||
t.Errorf("Actions[0].At = %v, want %v (from the curator's clock, not zero)", res.Actions[0].At, want)
|
||||
}
|
||||
if len(engine.created) != 1 {
|
||||
t.Fatalf("created = %#v, want exactly 1", engine.created)
|
||||
}
|
||||
got := engine.created[0]
|
||||
// The session id is not a scope: what the curator extracted is a fact
|
||||
// about one person as seen by one agent, and agent-user is the only
|
||||
// scope that says so.
|
||||
if want := (domainmemory.Scope{Kind: domainmemory.ScopeAgentUser, Agent: "winter", User: "u-42"}); got.Scope != want {
|
||||
t.Errorf("Scope = %v, want %v", got.Scope, want)
|
||||
}
|
||||
if got.Content != "prefers tabs over spaces" {
|
||||
t.Errorf("Content = %q, want the extracted fact verbatim", got.Content)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPassWritesExtractedFactsToAgentUserScope pins the address and
|
||||
// provenance of every curator write: a later chat turn reads back
|
||||
// agent-user memory for its own agent and user, and only a record written
|
||||
// there is visible to it.
|
||||
func TestPassWritesExtractedFactsToAgentUserScope(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
messages []curator.ConversationMessage
|
||||
response string
|
||||
wantContents []string
|
||||
}{
|
||||
{
|
||||
name: "one user sender",
|
||||
messages: []curator.ConversationMessage{{Role: "user", SenderID: "u-42", Content: "I prefer tabs"}},
|
||||
response: `["prefers tabs over spaces"]`,
|
||||
wantContents: []string{"prefers tabs over spaces"},
|
||||
},
|
||||
{
|
||||
name: "the same sender across several messages is still one participant",
|
||||
messages: []curator.ConversationMessage{
|
||||
{Role: "user", SenderID: "u-42", Content: "I prefer tabs"},
|
||||
{Role: "assistant", Content: "noted"},
|
||||
{Role: "user", SenderID: "u-42", Content: "and vim bindings"},
|
||||
},
|
||||
response: `["prefers tabs over spaces"]`,
|
||||
wantContents: []string{"prefers tabs over spaces"},
|
||||
},
|
||||
{
|
||||
name: "an assistant sender beside one identified user sender is still one participant",
|
||||
messages: []curator.ConversationMessage{
|
||||
{Role: "user", SenderID: "u-42", Content: "I prefer tabs"},
|
||||
{Role: "assistant", SenderID: "winter", Content: "noted"},
|
||||
},
|
||||
response: `["prefers tabs over spaces"]`,
|
||||
wantContents: []string{"prefers tabs over spaces"},
|
||||
},
|
||||
{
|
||||
name: "one write per extracted fact",
|
||||
messages: []curator.ConversationMessage{{Role: "user", SenderID: "u-42", Content: "lots of facts"}},
|
||||
response: `["fact a","fact b","fact c"]`,
|
||||
wantContents: []string{"fact a", "fact b", "fact c"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
engine := &fakeEngine{}
|
||||
c := newTestCurator(t, newFakeConversations(tt.messages...), &fakeLLM{responses: []string{tt.response}}, engine)
|
||||
|
||||
res, err := c.Pass(context.Background(), curator.PassInput{})
|
||||
if err != nil {
|
||||
t.Fatalf("Pass() = %v, want nil", err)
|
||||
}
|
||||
wantScope := domainmemory.Scope{Kind: domainmemory.ScopeAgentUser, Agent: "winter", User: "u-42"}
|
||||
if len(engine.created) != len(tt.wantContents) {
|
||||
t.Fatalf("created = %#v, want %d record(s)", engine.created, len(tt.wantContents))
|
||||
}
|
||||
for i, want := range tt.wantContents {
|
||||
got := engine.created[i]
|
||||
if got.Scope != wantScope {
|
||||
t.Errorf("created[%d].Scope = %v, want %v", i, got.Scope, wantScope)
|
||||
}
|
||||
if got.Kind != "note" {
|
||||
t.Errorf("created[%d].Kind = %q, want %q", i, got.Kind, "note")
|
||||
}
|
||||
if got.Author != Name {
|
||||
t.Errorf("created[%d].Author = %q, want the producer's own name %q", i, got.Author, Name)
|
||||
}
|
||||
if got.OriginUser != domainmemory.IdentityID("u-42") {
|
||||
t.Errorf("created[%d].OriginUser = %q, want the participant %q", i, got.OriginUser, "u-42")
|
||||
}
|
||||
if got.Source != "s1" {
|
||||
t.Errorf("created[%d].Source = %q, want the session id %q", i, got.Source, "s1")
|
||||
}
|
||||
if got.Content != want {
|
||||
t.Errorf("created[%d].Content = %q, want %q", i, got.Content, want)
|
||||
}
|
||||
}
|
||||
if len(res.Actions) != 1 || res.Actions[0].Type != ActionExtracted {
|
||||
t.Errorf("Actions = %#v, want one %s", res.Actions, ActionExtracted)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestPassSkipsSessionsWithoutASingleParticipant pins the fail-closed rule.
|
||||
// Every case's model response offers a fact, so a write here could only come
|
||||
// from a guessed participant.
|
||||
func TestPassSkipsSessionsWithoutASingleParticipant(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
messages []curator.ConversationMessage
|
||||
wantReason string
|
||||
}{
|
||||
{
|
||||
// Both producers are pinned by their own packages: the webhook
|
||||
// clears SenderID and carries the route in Inbound.BudgetKey
|
||||
// (internal/channels/webhook), the dashboard never sets one.
|
||||
// Either way the session arrives here with nothing that names a
|
||||
// person, which is the input this case pins.
|
||||
name: "zero senders: a dashboard or webhook session carries no per-person identity",
|
||||
messages: []curator.ConversationMessage{{Role: "user", Content: "hello"}},
|
||||
wantReason: "no single participant: 0 distinct sender(s), 1 unidentified user message(s)",
|
||||
},
|
||||
{
|
||||
name: "an identified sender beside an unidentified user message: the excerpt's provenance is unknown",
|
||||
messages: []curator.ConversationMessage{
|
||||
{Role: "user", SenderID: "u-42", Content: "I prefer tabs"},
|
||||
{Role: "user", Content: "a message whose channel carries no sender id"},
|
||||
},
|
||||
wantReason: "no single participant: 1 distinct sender(s), 1 unidentified user message(s)",
|
||||
},
|
||||
{
|
||||
name: "several distinct senders: a group chat",
|
||||
messages: []curator.ConversationMessage{
|
||||
{Role: "user", SenderID: "u-1", Content: "hi"},
|
||||
{Role: "user", SenderID: "u-2", Content: "hello"},
|
||||
},
|
||||
wantReason: "no single participant: 2 distinct sender(s)",
|
||||
},
|
||||
{
|
||||
name: "a sender present only on assistant messages does not count",
|
||||
messages: []curator.ConversationMessage{{Role: "assistant", SenderID: "winter", Content: "hi"}},
|
||||
wantReason: "no single participant: 0 distinct sender(s)",
|
||||
},
|
||||
{
|
||||
name: "empty senders among the user messages do not create a participant",
|
||||
messages: []curator.ConversationMessage{
|
||||
{Role: "user", Content: "hello"},
|
||||
{Role: "user", Content: "still nobody"},
|
||||
},
|
||||
wantReason: "no single participant: 0 distinct sender(s), 2 unidentified user message(s)",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
engine := &fakeEngine{}
|
||||
c := newTestCurator(t, newFakeConversations(tt.messages...), &fakeLLM{responses: []string{`["a fact worth keeping"]`}}, engine)
|
||||
|
||||
res, err := c.Pass(context.Background(), curator.PassInput{})
|
||||
if err != nil {
|
||||
t.Fatalf("Pass() = %v, want nil: an unattributable session is skipped, not a pass failure", err)
|
||||
}
|
||||
if len(engine.created) != 0 {
|
||||
t.Fatalf("created = %#v, want none: the session has no single participant to write for", engine.created)
|
||||
}
|
||||
if len(res.Actions) != 1 {
|
||||
t.Fatalf("Actions = %#v, want exactly one skip", res.Actions)
|
||||
}
|
||||
got := res.Actions[0]
|
||||
if got.Type != ActionSkipped {
|
||||
t.Errorf("Actions[0].Type = %q, want %q", got.Type, ActionSkipped)
|
||||
}
|
||||
if got.Detail != "s1" {
|
||||
t.Errorf("Actions[0].Detail = %q, want the session id %q", got.Detail, "s1")
|
||||
}
|
||||
if got.Reason != tt.wantReason {
|
||||
t.Errorf("Actions[0].Reason = %q, want %q", got.Reason, tt.wantReason)
|
||||
}
|
||||
if want := time.Unix(1000, 0); !got.At.Equal(want) {
|
||||
t.Errorf("Actions[0].At = %v, want %v (from the curator's clock)", got.At, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPassTreatsUnparseableResponseAsNothingExtracted(t *testing.T) {
|
||||
t.Parallel()
|
||||
conv := newFakeConversations(curator.ConversationMessage{Role: "user", SenderID: "u-42", Content: "hello"})
|
||||
llm := &fakeLLM{responses: []string{"not json at all"}}
|
||||
engine := &fakeEngine{}
|
||||
c := newTestCurator(t, conv, llm, engine)
|
||||
|
||||
res, err := c.Pass(context.Background(), curator.PassInput{})
|
||||
if err != nil {
|
||||
t.Fatalf("Pass() = %v, want nil: an unparseable response is not a pass failure", err)
|
||||
}
|
||||
if len(res.Actions) != 0 {
|
||||
t.Fatalf("Actions = %#v, want none", res.Actions)
|
||||
}
|
||||
if len(engine.created) != 0 {
|
||||
t.Fatalf("created = %#v, want none", engine.created)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPassEmptyArrayExtractsNothing(t *testing.T) {
|
||||
t.Parallel()
|
||||
conv := newFakeConversations(curator.ConversationMessage{Role: "user", SenderID: "u-42", Content: "hi"})
|
||||
llm := &fakeLLM{responses: []string{`[]`}}
|
||||
engine := &fakeEngine{}
|
||||
c := newTestCurator(t, conv, llm, engine)
|
||||
|
||||
res, err := c.Pass(context.Background(), curator.PassInput{})
|
||||
if err != nil {
|
||||
t.Fatalf("Pass() = %v, want nil", err)
|
||||
}
|
||||
if len(res.Actions) != 0 {
|
||||
t.Fatalf("Actions = %#v, want none: nothing in the excerpt was worth keeping", res.Actions)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPassTreatsASessionWithNoMessagesAsNothingExtracted(t *testing.T) {
|
||||
t.Parallel()
|
||||
conv := newFakeConversations()
|
||||
engine := &fakeEngine{}
|
||||
c := newTestCurator(t, conv, &fakeLLM{responses: []string{`["a fact worth keeping"]`}}, engine)
|
||||
|
||||
res, err := c.Pass(context.Background(), curator.PassInput{})
|
||||
if err != nil {
|
||||
t.Fatalf("Pass() = %v, want nil", err)
|
||||
}
|
||||
if len(res.Actions) != 0 {
|
||||
t.Fatalf("Actions = %#v, want none: a session with no messages yields nothing to extract", res.Actions)
|
||||
}
|
||||
if len(engine.created) != 0 {
|
||||
t.Fatalf("created = %#v, want none", engine.created)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPassCapsObservationsPerSession(t *testing.T) {
|
||||
t.Parallel()
|
||||
conv := newFakeConversations(curator.ConversationMessage{Role: "user", SenderID: "u-42", Content: "lots of facts"})
|
||||
llm := &fakeLLM{responses: []string{`["a","b","c","d","e","f","g"]`}}
|
||||
engine := &fakeEngine{}
|
||||
c := newTestCurator(t, conv, llm, engine)
|
||||
|
||||
if _, err := c.Pass(context.Background(), curator.PassInput{}); err != nil {
|
||||
t.Fatalf("Pass() = %v, want nil", err)
|
||||
}
|
||||
if len(engine.created) != maxObservationsPerSession {
|
||||
t.Fatalf("created = %d, want capped at %d", len(engine.created), maxObservationsPerSession)
|
||||
}
|
||||
// The cap truncates the tail, and keeps the order the model returned.
|
||||
want := []string{"a", "b", "c", "d", "e"}
|
||||
for i, content := range want {
|
||||
if engine.created[i].Content != content {
|
||||
t.Errorf("created[%d].Content = %q, want %q", i, engine.created[i].Content, content)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPassReviewsMultipleSessionsIndependently(t *testing.T) {
|
||||
t.Parallel()
|
||||
conv := &fakeConversations{
|
||||
sessions: map[string]time.Time{"s1": time.Unix(1000, 0), "s2": time.Unix(1000, 0)},
|
||||
agents: map[string]string{"s1": "winter", "s2": "spring"},
|
||||
messages: map[string][]curator.ConversationMessage{
|
||||
"s1": {{Role: "user", SenderID: "u-1", Content: "fact for s1"}},
|
||||
"s2": {{Role: "user", SenderID: "u-2", Content: "fact for s2"}},
|
||||
},
|
||||
}
|
||||
// One response for both sessions: the map iteration order above is not
|
||||
// deterministic, so nothing here may depend on which session is asked
|
||||
// first -- attribution is asserted through Source.
|
||||
llm := &fakeLLM{responses: []string{`["a fact"]`}}
|
||||
engine := &fakeEngine{}
|
||||
c := newTestCurator(t, conv, llm, engine)
|
||||
|
||||
res, err := c.Pass(context.Background(), curator.PassInput{})
|
||||
if err != nil {
|
||||
t.Fatalf("Pass() = %v, want nil", err)
|
||||
}
|
||||
if len(res.Actions) != 2 {
|
||||
t.Fatalf("Actions = %#v, want 2 (one per session)", res.Actions)
|
||||
}
|
||||
if len(engine.created) != 2 {
|
||||
t.Fatalf("created = %#v, want 2", engine.created)
|
||||
}
|
||||
scopes := map[string]domainmemory.Scope{}
|
||||
for _, rec := range engine.created {
|
||||
scopes[rec.Source] = rec.Scope
|
||||
}
|
||||
// Each session's own agent addresses its scope, so a session summary
|
||||
// whose agent id is dropped or swapped writes into another agent's
|
||||
// memory.
|
||||
for session, want := range map[string]domainmemory.Scope{
|
||||
"s1": {Kind: domainmemory.ScopeAgentUser, Agent: "winter", User: "u-1"},
|
||||
"s2": {Kind: domainmemory.ScopeAgentUser, Agent: "spring", User: "u-2"},
|
||||
} {
|
||||
if got := scopes[session]; got != want {
|
||||
t.Errorf("scope of the write sourced from %s = %v, want %v", session, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPassSkipsASessionWithNoAgentID drives the real builtin engine, whose
|
||||
// Create validates the scope it is handed. A session with no agent id is the
|
||||
// address the tree has for an agent-user record without an agent: it has no
|
||||
// scope, so it must be skipped and its reason recorded, never turned into a
|
||||
// Pass error that takes every other session's actions down with it.
|
||||
func TestPassSkipsASessionWithNoAgentID(t *testing.T) {
|
||||
t.Parallel()
|
||||
root := t.TempDir()
|
||||
engine := infraMemory.NewBuiltinEngine(root, 0)
|
||||
conv := &fakeConversations{
|
||||
sessions: map[string]time.Time{"s1": time.Unix(1000, 0)},
|
||||
agents: map[string]string{"s1": ""},
|
||||
messages: map[string][]curator.ConversationMessage{
|
||||
"s1": {{Role: "user", SenderID: "u-42", Content: "I prefer tabs"}},
|
||||
},
|
||||
}
|
||||
c := newTestCuratorWithEngine(t, conv, &fakeLLM{responses: []string{`["prefers tabs over spaces"]`}}, engine)
|
||||
|
||||
res, err := c.Pass(context.Background(), curator.PassInput{})
|
||||
if err != nil {
|
||||
t.Fatalf("Pass() = %v, want nil: a session with no agent id is skipped, not a pass failure", err)
|
||||
}
|
||||
if len(res.Actions) != 1 {
|
||||
t.Fatalf("Actions = %#v, want exactly one skip", res.Actions)
|
||||
}
|
||||
got := res.Actions[0]
|
||||
if got.Type != ActionSkipped {
|
||||
t.Errorf("Actions[0].Type = %q, want %q", got.Type, ActionSkipped)
|
||||
}
|
||||
if got.Detail != "s1" {
|
||||
t.Errorf("Actions[0].Detail = %q, want the session id %q", got.Detail, "s1")
|
||||
}
|
||||
if want := "no agent id: bot_user is unset (agent-user memory needs an agent and a user)"; got.Reason != want {
|
||||
t.Errorf("Actions[0].Reason = %q, want %q", got.Reason, want)
|
||||
}
|
||||
if dirs := engineScopeDirs(t, root); len(dirs) != 0 {
|
||||
t.Errorf("engine scope directories = %v, want none: the pass wrote for a session it could not address", dirs)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPassWritesThroughTheRealEngineForAnAddressableSession is the companion
|
||||
// to the skip above: it holds the same real engine, the same extractable
|
||||
// message, and an agent id, so the skip cannot pass for a reason unrelated to
|
||||
// the agent id -- such as an engine that refuses every write.
|
||||
func TestPassWritesThroughTheRealEngineForAnAddressableSession(t *testing.T) {
|
||||
t.Parallel()
|
||||
root := t.TempDir()
|
||||
engine := infraMemory.NewBuiltinEngine(root, 0)
|
||||
conv := &fakeConversations{
|
||||
sessions: map[string]time.Time{"s1": time.Unix(1000, 0)},
|
||||
agents: map[string]string{"s1": "archie-bot"},
|
||||
messages: map[string][]curator.ConversationMessage{
|
||||
"s1": {{Role: "user", SenderID: "u-42", Content: "I prefer tabs"}},
|
||||
},
|
||||
}
|
||||
c := newTestCuratorWithEngine(t, conv, &fakeLLM{responses: []string{`["prefers tabs over spaces"]`}}, engine)
|
||||
|
||||
res, err := c.Pass(context.Background(), curator.PassInput{})
|
||||
if err != nil {
|
||||
t.Fatalf("Pass() = %v, want nil", err)
|
||||
}
|
||||
if len(res.Actions) != 1 || res.Actions[0].Type != ActionExtracted {
|
||||
t.Fatalf("Actions = %#v, want one %s", res.Actions, ActionExtracted)
|
||||
}
|
||||
scope := domainmemory.Scope{Kind: domainmemory.ScopeAgentUser, Agent: "archie-bot", User: "u-42"}
|
||||
records, err := engine.List(context.Background(), scope)
|
||||
if err != nil {
|
||||
t.Fatalf("List(%v) = %v, want nil", scope, err)
|
||||
}
|
||||
if len(records) != 1 {
|
||||
t.Fatalf("List(%v) = %#v, want the one extracted record", scope, records)
|
||||
}
|
||||
if records[0].Content != "prefers tabs over spaces" {
|
||||
t.Errorf("Content = %q, want the extracted fact verbatim", records[0].Content)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPassContinuesPastAnUnattributableSession pins that a session the pass
|
||||
// cannot address costs the pass that session and nothing else. Both sessions
|
||||
// here are unattributable, so an abort on the first would drop the second's
|
||||
// action as well.
|
||||
func TestPassContinuesPastAnUnattributableSession(t *testing.T) {
|
||||
t.Parallel()
|
||||
root := t.TempDir()
|
||||
engine := infraMemory.NewBuiltinEngine(root, 0)
|
||||
conv := &fakeConversations{
|
||||
sessions: map[string]time.Time{"s1": time.Unix(1000, 0), "s2": time.Unix(1000, 0)},
|
||||
agents: map[string]string{"s1": "", "s2": ""},
|
||||
messages: map[string][]curator.ConversationMessage{
|
||||
"s1": {{Role: "user", SenderID: "u-1", Content: "fact for s1"}},
|
||||
"s2": {{Role: "user", SenderID: "u-2", Content: "fact for s2"}},
|
||||
},
|
||||
}
|
||||
c := newTestCuratorWithEngine(t, conv, &fakeLLM{responses: []string{`["a fact worth keeping"]`}}, engine)
|
||||
|
||||
res, err := c.Pass(context.Background(), curator.PassInput{})
|
||||
if err != nil {
|
||||
t.Fatalf("Pass() = %v, want nil: one unattributable session must not abort the pass", err)
|
||||
}
|
||||
if len(res.Actions) != 2 {
|
||||
t.Fatalf("Actions = %#v, want one action per session", res.Actions)
|
||||
}
|
||||
seen := make(map[string]string, len(res.Actions))
|
||||
for _, a := range res.Actions {
|
||||
if a.Type != ActionSkipped {
|
||||
t.Errorf("Actions = %#v, want every action to be %s", res.Actions, ActionSkipped)
|
||||
}
|
||||
seen[a.Detail] = a.Type
|
||||
}
|
||||
for _, session := range []string{"s1", "s2"} {
|
||||
if _, ok := seen[session]; !ok {
|
||||
t.Errorf("no action recorded for %s: a session the pass could not address took the whole pass down with it", session)
|
||||
}
|
||||
}
|
||||
if dirs := engineScopeDirs(t, root); len(dirs) != 0 {
|
||||
t.Errorf("engine scope directories = %v, want none", dirs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPassUnknownEngineIsAnError(t *testing.T) {
|
||||
t.Parallel()
|
||||
c := New(time.Hour, "does-not-exist")
|
||||
c.Bind(curator.Registrar{
|
||||
Conversations: &fakeConversations{},
|
||||
MemoryEngines: fakeEngineSource{engine: &fakeEngine{}},
|
||||
Clock: testClock{now: time.Unix(1000, 0)},
|
||||
})
|
||||
|
||||
if _, err := c.Pass(context.Background(), curator.PassInput{}); err == nil {
|
||||
t.Fatal("Pass() with an unregistered engine name = nil, want error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEffectiveSinceDefaultsToLookbackWindow(t *testing.T) {
|
||||
t.Parallel()
|
||||
now := time.Unix(1_000_000, 0)
|
||||
got := effectiveSince(time.Time{}, now)
|
||||
want := now.Add(-defaultLookback)
|
||||
if !got.Equal(want) {
|
||||
t.Errorf("effectiveSince(zero, now) = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEffectiveSincePassesThroughAnExplicitValue(t *testing.T) {
|
||||
t.Parallel()
|
||||
explicit := time.Unix(500, 0)
|
||||
got := effectiveSince(explicit, time.Unix(1_000_000, 0))
|
||||
if !got.Equal(explicit) {
|
||||
t.Errorf("effectiveSince(explicit, now) = %v, want %v unchanged", got, explicit)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManifestShape(t *testing.T) {
|
||||
t.Parallel()
|
||||
c := New(15*time.Minute, "builtin")
|
||||
m := c.Manifest()
|
||||
if !m.OnInput {
|
||||
t.Error("Manifest().OnInput = false, want true: wakes on completed chat turns")
|
||||
}
|
||||
if !m.Conversations {
|
||||
t.Error("Manifest().Conversations = false, want true")
|
||||
}
|
||||
if m.MemoryEngine != "builtin" {
|
||||
t.Errorf("Manifest().MemoryEngine = %q, want %q", m.MemoryEngine, "builtin")
|
||||
}
|
||||
if len(m.Tools) != 0 {
|
||||
t.Errorf("Manifest().Tools = %v, want none: extraction is a plain completion, not tool-calling", m.Tools)
|
||||
}
|
||||
// deliberately NOT checking true -- documents the negative
|
||||
if m.Skills {
|
||||
t.Error("Manifest().Skills = true, want false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistersAndRunsThroughTheRegistry(t *testing.T) {
|
||||
t.Parallel()
|
||||
r := curator.NewRegistry(curator.Registrar{
|
||||
Conversations: &fakeConversations{},
|
||||
LLM: &fakeLLM{},
|
||||
MemoryEngines: fakeEngineSource{engine: &fakeEngine{}},
|
||||
})
|
||||
c := New(time.Hour, "builtin")
|
||||
if err := r.Register(c); err != nil {
|
||||
t.Fatalf("Register() = %v, want nil", err)
|
||||
}
|
||||
if err := r.Start(context.Background()); err != nil {
|
||||
t.Fatalf("registry Start() = %v, want nil", err)
|
||||
}
|
||||
if health := r.Health(context.Background()); health[Name].Status != curator.HealthHealthy {
|
||||
t.Errorf("Health() = %v, want healthy", health)
|
||||
}
|
||||
if err := r.Stop(context.Background()); err != nil {
|
||||
t.Fatalf("registry Stop() = %v, want nil", err)
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
errLLM = errors.New("model unavailable")
|
||||
errCreate = errors.New("engine refused the write")
|
||||
)
|
||||
|
||||
func TestPassPropagatesALLMFailure(t *testing.T) {
|
||||
// Unlike an unparseable response, the model call itself failing (the
|
||||
// provider is down) is a real Pass error, not a "nothing to extract"
|
||||
// outcome.
|
||||
t.Parallel()
|
||||
conv := newFakeConversations(curator.ConversationMessage{Role: "user", SenderID: "u-42", Content: "hi"})
|
||||
llm := &fakeLLM{err: errLLM}
|
||||
c := newTestCurator(t, conv, llm, &fakeEngine{})
|
||||
|
||||
if _, err := c.Pass(context.Background(), curator.PassInput{}); !errors.Is(err, errLLM) {
|
||||
t.Fatalf("Pass() error = %v, want it to wrap the LLM failure", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPassPropagatesACreateFailure(t *testing.T) {
|
||||
// The engine refusing a write is a real failure, not "nothing to
|
||||
// extract": the pass must not report success for a fact it did not
|
||||
// persist.
|
||||
t.Parallel()
|
||||
conv := newFakeConversations(curator.ConversationMessage{Role: "user", SenderID: "u-42", Content: "hi"})
|
||||
engine := &fakeEngine{createErr: errCreate}
|
||||
c := newTestCurator(t, conv, &fakeLLM{responses: []string{`["a fact"]`}}, engine)
|
||||
|
||||
if _, err := c.Pass(context.Background(), curator.PassInput{}); !errors.Is(err, errCreate) {
|
||||
t.Fatalf("Pass() error = %v, want it to wrap the engine's create failure", err)
|
||||
}
|
||||
}
|
||||
@@ -1,215 +0,0 @@
|
||||
package skillcurator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/curator"
|
||||
)
|
||||
|
||||
func newTestCurator(t *testing.T, root string) *Curator {
|
||||
t.Helper()
|
||||
c := New(time.Hour)
|
||||
c.Bind(curator.Registrar{Skills: NewStore(root)})
|
||||
return c
|
||||
}
|
||||
|
||||
func TestCheckReportsFalseWithNoSkills(t *testing.T) {
|
||||
t.Parallel()
|
||||
c := newTestCurator(t, t.TempDir())
|
||||
ok, err := c.Check(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Check() = %v, want nil", err)
|
||||
}
|
||||
if ok {
|
||||
t.Error("Check() = true, want false: no skills to review")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckReportsTrueWithASkill(t *testing.T) {
|
||||
t.Parallel()
|
||||
root := t.TempDir()
|
||||
writeSkill(t, root, "tdd-bugfix", validSkill)
|
||||
c := newTestCurator(t, root)
|
||||
|
||||
ok, err := c.Check(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Check() = %v, want nil", err)
|
||||
}
|
||||
if !ok {
|
||||
t.Error("Check() = false, want true: a skill exists to review")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPassFlagsAParseFailureWithoutWriting(t *testing.T) {
|
||||
t.Parallel()
|
||||
root := t.TempDir()
|
||||
const broken = "---\nname: [unterminated\n---\n"
|
||||
writeSkill(t, root, "broken", broken)
|
||||
c := newTestCurator(t, root)
|
||||
|
||||
res, err := c.Pass(context.Background(), curator.PassInput{})
|
||||
if err != nil {
|
||||
t.Fatalf("Pass() = %v, want nil", err)
|
||||
}
|
||||
if len(res.Actions) != 1 || res.Actions[0].Type != ActionInvalid {
|
||||
t.Fatalf("Actions = %#v, want one %s", res.Actions, ActionInvalid)
|
||||
}
|
||||
if res.Actions[0].Detail != "broken" {
|
||||
t.Errorf("Detail = %q, want the skill name", res.Actions[0].Detail)
|
||||
}
|
||||
if res.Actions[0].Reason == "" {
|
||||
t.Error("Reason is empty, want the parse failure")
|
||||
}
|
||||
|
||||
// The broken skill must be untouched: this curator never rewrites
|
||||
// content it could not parse.
|
||||
got, err := NewStore(root).Read(context.Background(), "broken")
|
||||
if err != nil {
|
||||
t.Fatalf("Read(broken) after Pass = %v", err)
|
||||
}
|
||||
if got.Content != broken {
|
||||
t.Errorf("Content after Pass = %q, want unchanged %q", got.Content, broken)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPassFlagsAMissingRequiredField(t *testing.T) {
|
||||
t.Parallel()
|
||||
tests := []struct {
|
||||
name string
|
||||
content string
|
||||
}{
|
||||
{"missing name", "---\ndescription: does a thing\n---\nBody.\n"},
|
||||
{"missing description", "---\nname: my-skill\n---\nBody.\n"},
|
||||
{"missing both", "---\nversion: \"1\"\n---\nBody.\n"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
root := t.TempDir()
|
||||
writeSkill(t, root, "incomplete", tt.content)
|
||||
c := newTestCurator(t, root)
|
||||
|
||||
res, err := c.Pass(context.Background(), curator.PassInput{})
|
||||
if err != nil {
|
||||
t.Fatalf("Pass() = %v, want nil", err)
|
||||
}
|
||||
if len(res.Actions) != 1 || res.Actions[0].Type != ActionIncomplete {
|
||||
t.Fatalf("Actions = %#v, want one %s", res.Actions, ActionIncomplete)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPassNormalizesTrailingWhitespaceAndWritesBack(t *testing.T) {
|
||||
t.Parallel()
|
||||
root := t.TempDir()
|
||||
const messy = "---\nname: tdd-bugfix \ndescription: Fix a bug\n---\nBody text. \nMore.\t\n\n\n"
|
||||
writeSkill(t, root, "tdd-bugfix", messy)
|
||||
c := newTestCurator(t, root)
|
||||
|
||||
res, err := c.Pass(context.Background(), curator.PassInput{})
|
||||
if err != nil {
|
||||
t.Fatalf("Pass() = %v, want nil", err)
|
||||
}
|
||||
if len(res.Actions) != 1 || res.Actions[0].Type != ActionNormalized {
|
||||
t.Fatalf("Actions = %#v, want one %s", res.Actions, ActionNormalized)
|
||||
}
|
||||
|
||||
got, err := NewStore(root).Read(context.Background(), "tdd-bugfix")
|
||||
if err != nil {
|
||||
t.Fatalf("Read() after Pass = %v", err)
|
||||
}
|
||||
if strings.Contains(got.Content, " \n") || strings.Contains(got.Content, "\t\n") {
|
||||
t.Errorf("Content still has trailing whitespace: %q", got.Content)
|
||||
}
|
||||
if strings.HasSuffix(got.Content, "\n\n") {
|
||||
t.Errorf("Content still has multiple trailing newlines: %q", got.Content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPassLeavesACleanSkillUntouchedWithNoAction(t *testing.T) {
|
||||
t.Parallel()
|
||||
root := t.TempDir()
|
||||
writeSkill(t, root, "tdd-bugfix", validSkill)
|
||||
c := newTestCurator(t, root)
|
||||
|
||||
res, err := c.Pass(context.Background(), curator.PassInput{})
|
||||
if err != nil {
|
||||
t.Fatalf("Pass() = %v, want nil", err)
|
||||
}
|
||||
if len(res.Actions) != 0 {
|
||||
t.Fatalf("Actions = %#v, want none for an already-clean skill", res.Actions)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPassReviewsEverySkillIndependently(t *testing.T) {
|
||||
// A parse failure in one skill must not abort review of the others --
|
||||
// the whole reason this curator has its own store instead of
|
||||
// delegating List/Read to a single bulk discovery call.
|
||||
t.Parallel()
|
||||
root := t.TempDir()
|
||||
writeSkill(t, root, "broken", "---\nname: [unterminated\n---\n")
|
||||
writeSkill(t, root, "clean", validSkill)
|
||||
writeSkill(t, root, "incomplete", "---\nname: x\n---\nBody.\n")
|
||||
c := newTestCurator(t, root)
|
||||
|
||||
res, err := c.Pass(context.Background(), curator.PassInput{})
|
||||
if err != nil {
|
||||
t.Fatalf("Pass() = %v, want nil", err)
|
||||
}
|
||||
if len(res.Actions) != 2 {
|
||||
t.Fatalf("Actions = %#v, want exactly 2 (broken + incomplete; clean reports nothing)", res.Actions)
|
||||
}
|
||||
byType := map[string]bool{}
|
||||
for _, a := range res.Actions {
|
||||
byType[a.Type+":"+a.Detail] = true
|
||||
}
|
||||
if !byType[ActionInvalid+":broken"] {
|
||||
t.Errorf("missing invalid action for 'broken': %#v", res.Actions)
|
||||
}
|
||||
if !byType[ActionIncomplete+":incomplete"] {
|
||||
t.Errorf("missing incomplete action for 'incomplete': %#v", res.Actions)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManifestDeclaresOnlySkills(t *testing.T) {
|
||||
t.Parallel()
|
||||
c := New(30 * time.Minute)
|
||||
m := c.Manifest()
|
||||
if !m.Skills {
|
||||
t.Error("Manifest().Skills = false, want true")
|
||||
}
|
||||
if len(m.Tools) != 0 {
|
||||
t.Errorf("Manifest().Tools = %v, want none: this curator never reaches tools", m.Tools)
|
||||
}
|
||||
if m.MemoryEngine != "" {
|
||||
t.Errorf("Manifest().MemoryEngine = %q, want empty: this curator does not use memory", m.MemoryEngine)
|
||||
}
|
||||
if m.Interval != 30*time.Minute {
|
||||
t.Errorf("Manifest().Interval = %v, want the configured 30m", m.Interval)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistersAndRunsThroughTheRegistry(t *testing.T) {
|
||||
t.Parallel()
|
||||
root := t.TempDir()
|
||||
writeSkill(t, root, "tdd-bugfix", validSkill)
|
||||
|
||||
r := curator.NewRegistry(curator.Registrar{Skills: NewStore(root)})
|
||||
c := New(time.Hour)
|
||||
if err := r.Register(c); err != nil {
|
||||
t.Fatalf("Register() = %v, want nil", err)
|
||||
}
|
||||
if err := r.Start(context.Background()); err != nil {
|
||||
t.Fatalf("registry Start() = %v, want nil", err)
|
||||
}
|
||||
if health := r.Health(context.Background()); health[Name].Status != curator.HealthHealthy {
|
||||
t.Errorf("Health() = %v, want healthy", health)
|
||||
}
|
||||
if err := r.Stop(context.Background()); err != nil {
|
||||
t.Fatalf("registry Stop() = %v, want nil", err)
|
||||
}
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
package skillcurator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/curator"
|
||||
)
|
||||
|
||||
func writeSkill(t *testing.T, root, name, content string) {
|
||||
t.Helper()
|
||||
dir := filepath.Join(root, skillsDir, name)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatalf("MkdirAll(%s) = %v", dir, err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, skillFile), []byte(content), 0o644); err != nil {
|
||||
t.Fatalf("WriteFile = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
const validSkill = "---\nname: tdd-bugfix\ndescription: Fix a bug with a red-then-green test\n---\nBody text.\n"
|
||||
|
||||
func TestStoreListMissingDirIsEmptyNotError(t *testing.T) {
|
||||
t.Parallel()
|
||||
s := NewStore(t.TempDir())
|
||||
refs, err := s.List(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("List() = %v, want nil", err)
|
||||
}
|
||||
if len(refs) != 0 {
|
||||
t.Fatalf("List() = %v, want empty", refs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreListSkipsADirectoryWithNoSkillFile(t *testing.T) {
|
||||
t.Parallel()
|
||||
root := t.TempDir()
|
||||
writeSkill(t, root, "good", validSkill)
|
||||
if err := os.MkdirAll(filepath.Join(root, skillsDir, "empty-dir"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s := NewStore(root)
|
||||
refs, err := s.List(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("List() = %v, want nil", err)
|
||||
}
|
||||
if len(refs) != 1 || refs[0].Name != "good" {
|
||||
t.Fatalf("List() = %v, want only 'good'", refs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreReadReturnsContentAndDescription(t *testing.T) {
|
||||
t.Parallel()
|
||||
root := t.TempDir()
|
||||
writeSkill(t, root, "tdd-bugfix", validSkill)
|
||||
|
||||
s := NewStore(root)
|
||||
sk, err := s.Read(context.Background(), "tdd-bugfix")
|
||||
if err != nil {
|
||||
t.Fatalf("Read() = %v, want nil", err)
|
||||
}
|
||||
if sk.Content != validSkill {
|
||||
t.Errorf("Content = %q, want the raw file content", sk.Content)
|
||||
}
|
||||
if sk.Description != "Fix a bug with a red-then-green test" {
|
||||
t.Errorf("Description = %q, want the frontmatter description", sk.Description)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreReadUnparseableSkillStillReturnsRawContent(t *testing.T) {
|
||||
// Read never treats a parse failure as an error -- Pass decides that,
|
||||
// via its own skill.Parse call. Description is simply empty.
|
||||
t.Parallel()
|
||||
root := t.TempDir()
|
||||
const broken = "---\nname: [unterminated\n---\n"
|
||||
writeSkill(t, root, "broken", broken)
|
||||
|
||||
s := NewStore(root)
|
||||
sk, err := s.Read(context.Background(), "broken")
|
||||
if err != nil {
|
||||
t.Fatalf("Read() = %v, want nil even for unparseable frontmatter", err)
|
||||
}
|
||||
if sk.Content != broken {
|
||||
t.Errorf("Content = %q, want the raw content regardless of parse failure", sk.Content)
|
||||
}
|
||||
if sk.Description != "" {
|
||||
t.Errorf("Description = %q, want empty for a skill that failed to parse", sk.Description)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreReadMissingSkillIsAnError(t *testing.T) {
|
||||
t.Parallel()
|
||||
s := NewStore(t.TempDir())
|
||||
if _, err := s.Read(context.Background(), "nonexistent"); err == nil {
|
||||
t.Fatal("Read(nonexistent) = nil, want error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreWriteRequiresAnExistingSkillDirectory(t *testing.T) {
|
||||
t.Parallel()
|
||||
s := NewStore(t.TempDir())
|
||||
err := s.Write(context.Background(), curator.Skill{Name: "new-skill", Content: "content"})
|
||||
if err == nil {
|
||||
t.Fatal("Write(new skill) = nil, want error: Write curates, it does not create")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreWritePersistsContent(t *testing.T) {
|
||||
t.Parallel()
|
||||
root := t.TempDir()
|
||||
writeSkill(t, root, "tdd-bugfix", validSkill)
|
||||
|
||||
s := NewStore(root)
|
||||
updated := validSkill + "\nMore body.\n"
|
||||
if err := s.Write(context.Background(), curator.Skill{Name: "tdd-bugfix", Content: updated}); err != nil {
|
||||
t.Fatalf("Write() = %v, want nil", err)
|
||||
}
|
||||
|
||||
got, err := s.Read(context.Background(), "tdd-bugfix")
|
||||
if err != nil {
|
||||
t.Fatalf("Read() after Write = %v", err)
|
||||
}
|
||||
if got.Content != updated {
|
||||
t.Errorf("Content after Write = %q, want %q", got.Content, updated)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreDeleteRemovesTheWholeSkillDirectory(t *testing.T) {
|
||||
t.Parallel()
|
||||
root := t.TempDir()
|
||||
writeSkill(t, root, "tdd-bugfix", validSkill)
|
||||
if err := os.WriteFile(filepath.Join(root, skillsDir, "tdd-bugfix", "extra.txt"), []byte("x"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s := NewStore(root)
|
||||
if err := s.Delete(context.Background(), "tdd-bugfix"); err != nil {
|
||||
t.Fatalf("Delete() = %v, want nil", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(root, skillsDir, "tdd-bugfix")); !os.IsNotExist(err) {
|
||||
t.Fatalf("skill directory still exists after Delete, or unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreDeleteMissingSkillIsNotAnError(t *testing.T) {
|
||||
t.Parallel()
|
||||
s := NewStore(t.TempDir())
|
||||
if err := s.Delete(context.Background(), "never-existed"); err != nil {
|
||||
t.Fatalf("Delete(missing) = %v, want nil: the end state (absent) already holds", err)
|
||||
}
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// TestEventAttributionSurvivesTheStateStoreBoundary runs the same insert through
|
||||
// the local adapter and through a bufconn-backed gRPC client, because that hop is
|
||||
// where the attribution was being lost: the daemon records the event and the State
|
||||
// Store holds it, so a field the contract does not carry is a field the record
|
||||
// never has.
|
||||
//
|
||||
// The failure this pins is specific and was live: the actor was named inside the
|
||||
// event's detail text while actor_id, actor_kind and principal_id were all empty,
|
||||
// so an audit query reading the columns found nothing and "who approved this"
|
||||
// meant parsing a human-readable string. An in-process test passed throughout,
|
||||
// because it never crossed this boundary.
|
||||
func TestEventAttributionSurvivesTheStateStoreBoundary(t *testing.T) {
|
||||
const (
|
||||
actorID = "70000000-0000-5000-8000-000000000001"
|
||||
principalID = "70000000-0000-5000-8000-000000000002"
|
||||
actorKind = "bot"
|
||||
)
|
||||
|
||||
for _, mode := range []string{"local", "grpc"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
local := pgstore.Open(t)
|
||||
var c contract = local
|
||||
if mode == "grpc" {
|
||||
c = remoteTaskStore(t, local, nil, nil)
|
||||
}
|
||||
|
||||
task, err := c.EnqueueChatTask(ctx, "acme", "widget", "title", "body", "implement", "", nil)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("EnqueueChatTask = (%+v, %v)", task, err)
|
||||
}
|
||||
|
||||
recorded := events.Event{
|
||||
Kind: events.KindAgentApproved,
|
||||
TaskID: task.ID,
|
||||
ActorID: actorID,
|
||||
ActorKind: actorKind,
|
||||
PrincipalID: principalID,
|
||||
Detail: "approved by an agent, authorised by a person",
|
||||
}
|
||||
if _, err := c.InsertEvent(ctx, recorded); err != nil {
|
||||
t.Fatalf("InsertEvent: %v", err)
|
||||
}
|
||||
|
||||
got, err := c.TaskEvents(ctx, task.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskEvents: %v", err)
|
||||
}
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("TaskEvents returned %d events, want 1", len(got))
|
||||
}
|
||||
event := got[0]
|
||||
if event.ActorID != actorID || event.ActorKind != actorKind || event.PrincipalID != principalID {
|
||||
t.Fatalf("attribution did not cross the boundary: actor=%q kind=%q principal=%q",
|
||||
event.ActorID, event.ActorKind, event.PrincipalID)
|
||||
}
|
||||
if event.Kind != events.KindAgentApproved {
|
||||
t.Fatalf("kind = %q, want %q", event.Kind, events.KindAgentApproved)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
func TestCaptureListsExceedUnaryMessageLimit(t *testing.T) {
|
||||
local := pgstore.Open(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
// Only an identified capture is listed for dispatch; a catch-all type
|
||||
// identifies every event on the source as it arrives.
|
||||
eventTypeID, etErr := eda.InsertEventType(t.Context(), eventtype.EventType{Source: "large", Name: "any"})
|
||||
if etErr != nil {
|
||||
t.Fatal(etErr)
|
||||
}
|
||||
body := strings.Repeat("x", 256<<10)
|
||||
for range 20 {
|
||||
if _, err := eda.InsertCapture(t.Context(), storecontract.CapturedEvent{Source: "large", Body: body, Authenticated: true}, 0, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// A binding's mapping is a real relation now, so it must point at a
|
||||
// mapping that exists; the store refuses a dangling id.
|
||||
mappingID, mapErr := eda.InsertMapping(t.Context(), mapping.Mapping{
|
||||
Name: "m",
|
||||
EventTypeID: eventTypeID,
|
||||
Fields: []mapping.Field{{Name: "title", Path: "title", Type: mapping.TypeString}},
|
||||
})
|
||||
if mapErr != nil {
|
||||
t.Fatal(mapErr)
|
||||
}
|
||||
// ListUndispatchedCaptures only returns sources with an armed binding
|
||||
// (ArmedBindingsForSource), so "large" needs one taken through the
|
||||
// public draft -> pending_approval -> armed lifecycle.
|
||||
id, err := eda.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "large binding", Matcher: binding.Matcher{Source: "large"},
|
||||
MappingID: mappingID, Workflow: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := eda.UpdateBinding(t.Context(), binding.Binding{
|
||||
ID: id, Name: "large binding", Matcher: binding.Matcher{Source: "large"},
|
||||
MappingID: mappingID, Workflow: "implement",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := eda.ApproveBinding(t.Context(), id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remote := remoteEDA(t, local, eda)
|
||||
for _, undispatched := range []bool{false, true} {
|
||||
var captures []storecontract.CapturedEvent
|
||||
var err error
|
||||
if undispatched {
|
||||
captures, err = remote.ListUndispatchedCaptures(t.Context(), []string{"large"}, 20)
|
||||
} else {
|
||||
captures, err = remote.ListCaptures(t.Context(), 20)
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("undispatched=%v: %v", undispatched, err)
|
||||
continue
|
||||
}
|
||||
if len(captures) != 20 {
|
||||
t.Fatalf("undispatched=%v: got %d captures, want 20", undispatched, len(captures))
|
||||
}
|
||||
for _, capture := range captures {
|
||||
if capture.Body != body {
|
||||
t.Fatal("capture body truncated")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 651 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user