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,102 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/applystatus"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
type stubApplyStatus struct {
|
||||
records []storecontract.ApplyStatus
|
||||
err error
|
||||
}
|
||||
|
||||
func (s stubApplyStatus) PutApplyStatus(_ context.Context, _ storecontract.ApplyStatus) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s stubApplyStatus) ListApplyStatus(context.Context) ([]storecontract.ApplyStatus, error) {
|
||||
return s.records, s.err
|
||||
}
|
||||
|
||||
func applyStatusResponse(t *testing.T, server *Server) applyStatusView {
|
||||
t.Helper()
|
||||
recorder := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(recorder, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/control-plane/apply-status", nil))
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("GET apply-status = %d, want 200: %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
var view applyStatusView
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &view); err != nil {
|
||||
t.Fatalf("decode apply status: %v (body %s)", err, recorder.Body.String())
|
||||
}
|
||||
return view
|
||||
}
|
||||
|
||||
// TestApplyStatusDerivesState pins the three readings an operator acts on: a
|
||||
// process on the current version is live, one on an older version of a
|
||||
// restart-required kind is pending a restart, and one that has stopped
|
||||
// re-stamping is unknown rather than current (archie-core-pskb).
|
||||
func TestApplyStatusDerivesState(t *testing.T) {
|
||||
now := time.Date(2026, 9, 21, 12, 0, 0, 0, time.UTC)
|
||||
server := &Server{ApplyStatus: stubApplyStatus{records: []storecontract.ApplyStatus{
|
||||
{Process: applystatus.Daemon, Kind: "tool-settings", AppliedVersion: 4, ReportedAt: now.Add(-10 * time.Second)},
|
||||
{Process: applystatus.Gateway, Kind: "tool-settings", AppliedVersion: 3, ReportedAt: now.Add(-10 * time.Second)},
|
||||
{Process: applystatus.Messaging, Kind: "tool-settings", AppliedVersion: 4, ReportedAt: now.Add(-10 * time.Minute)},
|
||||
}}}
|
||||
server.now = func() time.Time { return now }
|
||||
|
||||
got := applyStatusResponse(t, server)
|
||||
states := map[string]string{}
|
||||
for _, record := range got.Records {
|
||||
states[record.Process] = record.State
|
||||
}
|
||||
for process, want := range map[string]string{
|
||||
applystatus.Daemon: applyStateCurrent,
|
||||
applystatus.Gateway: applyStateCurrent,
|
||||
applystatus.Messaging: applyStateUnknown,
|
||||
} {
|
||||
if states[process] != want {
|
||||
t.Errorf("%s state = %q, want %q", process, states[process], want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestApplyStatusReportsAnError pins that a process that rejected an edit
|
||||
// reads as failed with its error, and keeps showing the version still live
|
||||
// in it.
|
||||
func TestApplyStatusReportsAnError(t *testing.T) {
|
||||
now := time.Date(2026, 9, 21, 12, 0, 0, 0, time.UTC)
|
||||
server := &Server{ApplyStatus: stubApplyStatus{records: []storecontract.ApplyStatus{
|
||||
{
|
||||
Process: applystatus.Daemon, Kind: "tool-settings", AppliedVersion: 3,
|
||||
Error: "validate database settings: bad policy", ReportedAt: now,
|
||||
},
|
||||
}}}
|
||||
server.now = func() time.Time { return now }
|
||||
|
||||
got := applyStatusResponse(t, server)
|
||||
if len(got.Records) != 1 {
|
||||
t.Fatalf("got %d records, want 1", len(got.Records))
|
||||
}
|
||||
record := got.Records[0]
|
||||
if record.State != applyStateFailed || record.Error == "" || record.AppliedVersion != 3 {
|
||||
t.Fatalf("record = %+v, want failed with its error and version 3 still live", record)
|
||||
}
|
||||
}
|
||||
|
||||
// TestApplyStatusWithoutAStoreIsEmptyNotAnError: a process with no apply
|
||||
// status wiring must render an empty page, the same way the capture list
|
||||
// reports disabled rather than failing the dashboard.
|
||||
func TestApplyStatusWithoutAStoreIsEmptyNotAnError(t *testing.T) {
|
||||
got := applyStatusResponse(t, &Server{})
|
||||
if len(got.Records) != 0 {
|
||||
t.Fatalf("got %d records from a server with no store, want none", len(got.Records))
|
||||
}
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"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/domain/workflow"
|
||||
)
|
||||
|
||||
// memBindings keeps mappings and bindings in memory with no per-source limit,
|
||||
// as the Postgres store does.
|
||||
type memBindings struct {
|
||||
mappings map[string]mapping.Mapping
|
||||
bindings map[string]binding.Binding
|
||||
}
|
||||
|
||||
func newMemBindings() *memBindings {
|
||||
return &memBindings{mappings: map[string]mapping.Mapping{}, bindings: map[string]binding.Binding{}}
|
||||
}
|
||||
|
||||
func (m *memBindings) InsertMapping(_ context.Context, v mapping.Mapping) (string, error) {
|
||||
v.ID = fmt.Sprintf("m%d", len(m.mappings)+1)
|
||||
m.mappings[v.ID] = v
|
||||
return v.ID, nil
|
||||
}
|
||||
|
||||
func (m *memBindings) GetMapping(_ context.Context, id string) (*mapping.Mapping, error) {
|
||||
v, ok := m.mappings[id]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return &v, nil
|
||||
}
|
||||
func (m *memBindings) ListMappings(context.Context) ([]mapping.Mapping, error) { return nil, nil }
|
||||
func (m *memBindings) UpdateMapping(context.Context, mapping.Mapping) error { return nil }
|
||||
func (m *memBindings) DeleteMapping(context.Context, string) error { return nil }
|
||||
|
||||
func (m *memBindings) InsertBinding(_ context.Context, b binding.Binding) (string, error) {
|
||||
b.ID = fmt.Sprintf("b%d", len(m.bindings)+1)
|
||||
m.bindings[b.ID] = b
|
||||
return b.ID, nil
|
||||
}
|
||||
|
||||
func (m *memBindings) GetBinding(_ context.Context, id string) (*binding.Binding, error) {
|
||||
v, ok := m.bindings[id]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return &v, nil
|
||||
}
|
||||
func (m *memBindings) ListBindings(context.Context) ([]binding.Binding, error) { return nil, nil }
|
||||
func (m *memBindings) UpdateBinding(_ context.Context, b binding.Binding) error {
|
||||
if _, ok := m.bindings[b.ID]; !ok {
|
||||
return storecontract.ErrBindingNotFound
|
||||
}
|
||||
m.bindings[b.ID] = b
|
||||
return nil
|
||||
}
|
||||
func (m *memBindings) DeleteBinding(context.Context, string) error { return nil }
|
||||
func (m *memBindings) ApproveBinding(context.Context, string) error { return nil }
|
||||
|
||||
func memBindingServer(t *testing.T) (*Server, string) {
|
||||
t.Helper()
|
||||
store := newMemBindings()
|
||||
mappingID, _ := store.InsertMapping(t.Context(), mapping.Mapping{
|
||||
Name: "m", EventTypeID: "et-1",
|
||||
Fields: []mapping.Field{{Name: "title", Path: "issue.title", Type: mapping.TypeString}},
|
||||
})
|
||||
return &Server{
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Mappings: store,
|
||||
Bindings: store,
|
||||
ControlPlane: workflowControlPlane(t, workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "implement", YAML: "id: implement\nsteps:\n - type: implement.prepare\n"}}}),
|
||||
}, mappingID
|
||||
}
|
||||
|
||||
// Several bindings may share a source.
|
||||
func TestHandleBindingCreateAllowsSeveralPerSource(t *testing.T) {
|
||||
srv, mappingID := memBindingServer(t)
|
||||
for _, suffix := range []string{"first", "second"} {
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest(suffix, "sentry", mappingID))
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("%s create status = %d, want %d; body = %s", suffix, w.Code, http.StatusCreated, w.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A binding's filter is checked against its mapping's parameters on save.
|
||||
func TestHandleBindingFilterIsCheckedAgainstMapping(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
filter string
|
||||
want int
|
||||
}{
|
||||
{"no filter", "", http.StatusCreated},
|
||||
{"filter on a mapped parameter", `title.startsWith("P1")`, http.StatusCreated},
|
||||
{"unknown parameter", `severity == "high"`, http.StatusBadRequest},
|
||||
{"not boolean", `title`, http.StatusBadRequest},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
srv, mappingID := memBindingServer(t)
|
||||
req := validBindingRequest("f", "sentry", mappingID)
|
||||
req["filter"] = tt.filter
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", req)
|
||||
if w.Code != tt.want {
|
||||
t.Fatalf("create status = %d, want %d; body = %s", w.Code, tt.want, w.Body.String())
|
||||
}
|
||||
if w.Code == http.StatusCreated {
|
||||
var created binding.Binding
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &created)
|
||||
if created.Filter != tt.filter {
|
||||
t.Fatalf("created.Filter = %q, want %q", created.Filter, tt.filter)
|
||||
}
|
||||
w = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+created.ID, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("update status = %d; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBindingRejectsUnknownMapping(t *testing.T) {
|
||||
srv, _ := memBindingServer(t)
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("x", "sentry", "absent"))
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("create status = %d, want %d; body = %s", w.Code, http.StatusBadRequest, w.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -1,382 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// bindingTestServer wires a Server backed by a single *pgstore.TaskDB for all
|
||||
// three dashboards surfaces (Captures, Mappings, Bindings) and seeds the
|
||||
// one workflow binding tests need to pass server-side validation.
|
||||
func bindingTestServer(t *testing.T) *Server {
|
||||
t.Helper()
|
||||
s := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
eda := pgstore.EDA(t, nil)
|
||||
return &Server{
|
||||
Store: s,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Mappings: eda,
|
||||
Captures: eda,
|
||||
Bindings: eda,
|
||||
ControlPlane: workflowControlPlane(t, workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "implement", YAML: "id: implement\nsteps:\n - type: implement.prepare\n"}}}),
|
||||
}
|
||||
}
|
||||
|
||||
// seedMapping inserts one payload mapping and returns its row ID, so
|
||||
// binding tests have a valid non-zero mapping_id without hand-rolling SQL.
|
||||
func seedMapping(t *testing.T, srv *Server, name string) string {
|
||||
t.Helper()
|
||||
id, err := srv.Mappings.InsertMapping(t.Context(), mapping.Mapping{
|
||||
Name: name,
|
||||
SourceHint: "sentry",
|
||||
Fields: []mapping.Field{{Name: "title", Path: "issue.title", Type: mapping.TypeString, Required: true}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("seed mapping: %v", err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// validBindingRequest returns a populated bindingRequest that passes
|
||||
// binding.Validate and server-side workflow validation.
|
||||
func validBindingRequest(suffix, source, mappingID string) map[string]any {
|
||||
return map[string]any{
|
||||
"name": "binding " + suffix,
|
||||
"matcher": map[string]any{"source": source},
|
||||
"mapping_id": mappingID,
|
||||
"workflow": "implement",
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBindingCreateAndGet(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("a", "sentry", mappingID))
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("create status = %d, want %d; body = %s", w.Code, http.StatusCreated, w.Body.String())
|
||||
}
|
||||
var created binding.Binding
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil {
|
||||
t.Fatalf("unmarshal created: %v", err)
|
||||
}
|
||||
if created.ID == "" {
|
||||
t.Fatalf("created.ID = 0; body = %s", w.Body.String())
|
||||
}
|
||||
if created.Status != binding.StatusPendingApproval {
|
||||
t.Fatalf("created.Status = %q, want %q", created.Status, binding.StatusPendingApproval)
|
||||
}
|
||||
|
||||
w = doJSON(t, srv, http.MethodGet, "/api/bindings/"+created.ID, nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("get status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
var got binding.Binding
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("unmarshal got: %v", err)
|
||||
}
|
||||
if got.ID != created.ID {
|
||||
t.Fatalf("got.ID = %q, want %q", got.ID, created.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleBindingCreateAndUpdateRoundTripsOwnerRepo covers the
|
||||
// multi-repo fix at the API layer: a create/update request carrying
|
||||
// owner/repo persists them, and they're visible in the response
|
||||
// (they're not secret).
|
||||
func TestHandleBindingCreateAndUpdateRoundTripsOwnerRepo(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
|
||||
req := validBindingRequest("a", "sentry", mappingID)
|
||||
req["owner"] = "acme"
|
||||
req["repo"] = "widget"
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", req)
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("create status = %d, want %d; body = %s", w.Code, http.StatusCreated, w.Body.String())
|
||||
}
|
||||
var created binding.Binding
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil {
|
||||
t.Fatalf("unmarshal created: %v", err)
|
||||
}
|
||||
if created.Owner != "acme" || created.Repo != "widget" {
|
||||
t.Fatalf("created owner/repo = %q/%q, want acme/widget; body = %s", created.Owner, created.Repo, w.Body.String())
|
||||
}
|
||||
|
||||
updateReq := validBindingRequest("a", "sentry", mappingID)
|
||||
updateReq["owner"] = "other-org"
|
||||
updateReq["repo"] = "other-repo"
|
||||
w = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+created.ID, updateReq)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("update status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
var updated binding.Binding
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &updated); err != nil {
|
||||
t.Fatalf("unmarshal updated: %v", err)
|
||||
}
|
||||
if updated.Owner != "other-org" || updated.Repo != "other-repo" {
|
||||
t.Fatalf("updated owner/repo = %q/%q, want other-org/other-repo; body = %s", updated.Owner, updated.Repo, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleBindingCreateRejectsPartialOwnerRepo confirms the domain
|
||||
// validation (owner and repo must both be set or both empty) is
|
||||
// actually reached from the HTTP layer, not just unit-tested in
|
||||
// isolation.
|
||||
func TestHandleBindingCreateRejectsPartialOwnerRepo(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
|
||||
req := validBindingRequest("a", "sentry", mappingID)
|
||||
req["owner"] = "acme"
|
||||
// repo deliberately omitted
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", req)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("create status = %d, want %d (partial owner/repo pin); body = %s", w.Code, http.StatusBadRequest, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBindingCreateRejectsMissingWorkflow(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
|
||||
req := validBindingRequest("a", "sentry", mappingID)
|
||||
req["workflow"] = "no-such-workflow"
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", req)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusBadRequest, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBindingCreateRejectsValidationFailure(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
|
||||
req := validBindingRequest("a", "sentry", mappingID)
|
||||
req["name"] = " "
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", req)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusBadRequest, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBindingCreateRequiresToken(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
srv.Token = "secret"
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
|
||||
// httptest.NewRequest defaults to no Authorization header. With
|
||||
// Token set, requireToken must reject the request before any handler
|
||||
// body decode happens, so the response is 401, not 400.
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("a", "sentry", mappingID))
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusUnauthorized, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBindingUpdatePreservesOtherFields(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("a", "sentry", mappingID))
|
||||
var created binding.Binding
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &created)
|
||||
|
||||
// PATCH on a draft binding should update the editable fields and
|
||||
// leave status=draft in place. Phase B's UpdateBinding currently
|
||||
// only forces armed -> pending_approval; with no path from draft to
|
||||
// pending_approval yet, an edit on a draft row correctly stays
|
||||
// draft. This test pins the editable-fields half of the contract.
|
||||
update := validBindingRequest("renamed", "sentry", mappingID)
|
||||
w = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+created.ID, update)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("patch status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
var updated binding.Binding
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &updated); err != nil {
|
||||
t.Fatalf("unmarshal updated: %v", err)
|
||||
}
|
||||
if updated.Name != "binding renamed" {
|
||||
t.Fatalf("updated.Name = %q, want %q", updated.Name, "binding renamed")
|
||||
}
|
||||
if updated.MappingID != mappingID {
|
||||
t.Fatalf("updated.MappingID = %q, want %q", updated.MappingID, mappingID)
|
||||
}
|
||||
// Status MUST not regress from a state the caller never asked for.
|
||||
if updated.Status != binding.StatusPendingApproval {
|
||||
t.Fatalf("updated.Status = %q, want draft or pending_approval", updated.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBindingApproveArmedRejected(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("a", "sentry", mappingID))
|
||||
var created binding.Binding
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &created)
|
||||
if w = doJSON(t, srv, http.MethodPost, "/api/bindings/"+created.ID+"/approve", nil); w.Code != http.StatusOK {
|
||||
t.Fatalf("first approve status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
|
||||
// An armed binding is not a valid source state for approve:
|
||||
// ErrBindingTransition -> 409.
|
||||
w = doJSON(t, srv, http.MethodPost, "/api/bindings/"+created.ID+"/approve", nil)
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusConflict, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBindingApproveHappyPath(t *testing.T) {
|
||||
// A created binding awaits approval, and approving it arms it: the
|
||||
// operator who just created one can approve it without an edit.
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("a", "sentry", mappingID))
|
||||
var created binding.Binding
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &created)
|
||||
if created.Status != binding.StatusPendingApproval {
|
||||
t.Fatalf("created status = %q, want %q", created.Status, binding.StatusPendingApproval)
|
||||
}
|
||||
|
||||
w = doJSON(t, srv, http.MethodPost, "/api/bindings/"+created.ID+"/approve", nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("approve status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
var approved binding.Binding
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &approved)
|
||||
if approved.Status != binding.StatusArmed {
|
||||
t.Fatalf("approved status = %q, want %q", approved.Status, binding.StatusArmed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBindingEditOnArmedDropsToPendingApproval(t *testing.T) {
|
||||
// Pin the other half of the rule: an edit on an already-armed binding
|
||||
// drops it back to pending_approval (not silently re-armed). This is
|
||||
// the security property that makes the approval gate non-decorative.
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("a", "sentry", mappingID))
|
||||
var created binding.Binding
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &created)
|
||||
|
||||
// Drive it to armed via the happy path.
|
||||
_ = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+created.ID, validBindingRequest("a", "sentry", mappingID))
|
||||
_ = doJSON(t, srv, http.MethodPost, "/api/bindings/"+created.ID+"/approve", nil)
|
||||
|
||||
// Now edit. Status must drop back to pending_approval.
|
||||
w = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+created.ID, validBindingRequest("a-edited", "sentry", mappingID))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("patch status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
var patched binding.Binding
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &patched)
|
||||
if patched.Status != binding.StatusPendingApproval {
|
||||
t.Fatalf("after edit, status = %q, want %q", patched.Status, binding.StatusPendingApproval)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBindingApproveMissingReturns404(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings/999/approve", nil)
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusNotFound, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBindingDeleteRemovesRow(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("a", "sentry", mappingID))
|
||||
var created binding.Binding
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &created)
|
||||
|
||||
w = doJSON(t, srv, http.MethodDelete, "/api/bindings/"+created.ID, nil)
|
||||
if w.Code != http.StatusNoContent {
|
||||
t.Fatalf("delete status = %d, want %d; body = %s", w.Code, http.StatusNoContent, w.Body.String())
|
||||
}
|
||||
w = doJSON(t, srv, http.MethodGet, "/api/bindings/"+created.ID, nil)
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("get after delete status = %d, want %d", w.Code, http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBindingsUnavailableWhenNotConfigured(t *testing.T) {
|
||||
srv := &Server{Store: nil, Log: slog.New(slog.DiscardHandler)}
|
||||
w := doJSON(t, srv, http.MethodGet, "/api/bindings", nil)
|
||||
if w.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want %d", w.Code, http.StatusServiceUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleBindingMutationsRequireCSRFHeader pins the same browser
|
||||
// mutation contract handleTaskAction enforces (docs/prds/dynamic-curators.md:
|
||||
// "All mutations behind authorizeTaskMutation, same as bindings and
|
||||
// mappings") onto every binding write handler. A request with no
|
||||
// X-Archie-CSRF header must be refused, not silently mutate the store.
|
||||
func TestHandleBindingMutationsRequireCSRFHeader(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("a", "sentry", mappingID))
|
||||
var created binding.Binding
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil {
|
||||
t.Fatalf("unmarshal created binding: %v; body = %s", err, w.Body.String())
|
||||
}
|
||||
id := created.ID
|
||||
|
||||
tests := []struct {
|
||||
name, method, path string
|
||||
body any
|
||||
}{
|
||||
{"create", http.MethodPost, "/api/bindings", validBindingRequest("b", "other", mappingID)},
|
||||
{"update", http.MethodPatch, "/api/bindings/" + id, validBindingRequest("a", "sentry", mappingID)},
|
||||
{"approve", http.MethodPost, "/api/bindings/" + id + "/approve", nil},
|
||||
{"delete", http.MethodDelete, "/api/bindings/" + id, nil},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
w := doJSONNoCSRF(t, srv, tc.method, tc.path, tc.body)
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("status = %d, want %d without a CSRF header; body = %s", w.Code, http.StatusForbidden, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Saving a binding checks it against the workflow's declared inputs: an
|
||||
// unassigned required input is refused, and assigned inputs round-trip.
|
||||
func TestHandleBindingChecksWorkflowInputs(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
srv.ControlPlane = workflowControlPlane(t, workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{
|
||||
ID: "investigate",
|
||||
YAML: "id: investigate\nrepository: none\ninputs:\n subject: {type: string, required: true}\nsteps:\n - type: agent.run\n settings:\n mission: look\n",
|
||||
}}})
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
|
||||
req := validBindingRequest("a", "sentry", mappingID)
|
||||
req["workflow"] = "investigate"
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", req)
|
||||
if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), `requires input "subject"`) {
|
||||
t.Fatalf("create without the required input = %d %s, want 400 naming the input", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
req["inputs"] = map[string]any{"subject": map[string]any{"param": "title"}}
|
||||
w = doJSON(t, srv, http.MethodPost, "/api/bindings", req)
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("create = %d %s, want 201", w.Code, w.Body.String())
|
||||
}
|
||||
var created binding.Binding
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if created.Inputs["subject"].Param != "title" {
|
||||
t.Fatalf("created inputs = %+v, want subject from title", created.Inputs)
|
||||
}
|
||||
}
|
||||
@@ -1,203 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// captureTestServer builds a Server whose Captures field points at the same
|
||||
// concrete *pgstore.TaskDB as Store, so tests can assert on persisted rows
|
||||
// through the narrower CaptureStore interface -- Server.Store's static type
|
||||
// (storecontract.TaskStore) does not expose ListCaptures.
|
||||
func captureTestServer(t *testing.T) *Server {
|
||||
t.Helper()
|
||||
s := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
return &Server{
|
||||
Store: s,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
// Captures come from the event-capture store; the task store no
|
||||
// longer holds them.
|
||||
Captures: pgstore.EDA(t, nil),
|
||||
}
|
||||
}
|
||||
|
||||
// seedCapture inserts a captured row directly through the CaptureStore.
|
||||
// These tests cover the list read; the write path itself lives in
|
||||
// internal/infrastructure/captureintake and is tested there.
|
||||
func seedCapture(t *testing.T, srv *Server, source string) string {
|
||||
t.Helper()
|
||||
id, err := srv.Captures.InsertCapture(t.Context(), storecontract.CapturedEvent{
|
||||
ReceivedAt: time.Now().UTC(),
|
||||
Source: source,
|
||||
Body: `{"n":1}`,
|
||||
}, 7*24*time.Hour, 100)
|
||||
if err != nil {
|
||||
t.Fatalf("seed capture %q: %v", source, err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func captureListResponse(t *testing.T, w *httptest.ResponseRecorder) map[string]any {
|
||||
t.Helper()
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v; body = %s", err, w.Body.String())
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
func TestHandleCapturesListsRecentCapturesNewestFirst(t *testing.T) {
|
||||
srv := captureTestServer(t)
|
||||
for _, src := range []string{"first", "second", "third"} {
|
||||
seedCapture(t, srv, src)
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/captures", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
body := captureListResponse(t, w)
|
||||
if enabled, _ := body["enabled"].(bool); !enabled {
|
||||
t.Fatalf("enabled = %v, want true", body["enabled"])
|
||||
}
|
||||
captures, ok := body["captures"].([]any)
|
||||
if !ok || len(captures) != 3 {
|
||||
t.Fatalf("captures = %#v, want 3 entries", body["captures"])
|
||||
}
|
||||
first, ok := captures[0].(map[string]any)
|
||||
if !ok || first["source"] != "third" {
|
||||
t.Fatalf("captures[0] = %#v, want newest-first (source=\"third\")", captures[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCapturesRespectsLimitQueryParam(t *testing.T) {
|
||||
srv := captureTestServer(t)
|
||||
for range 3 {
|
||||
seedCapture(t, srv, "src")
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/captures?limit=1", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
body := captureListResponse(t, w)
|
||||
captures, _ := body["captures"].([]any)
|
||||
if len(captures) != 1 {
|
||||
t.Fatalf("captures = %#v, want 1 entry (limit=1)", body["captures"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCapturesDefaultsLimitWhenMissingOrInvalid(t *testing.T) {
|
||||
srv := captureTestServer(t)
|
||||
for range 3 {
|
||||
seedCapture(t, srv, "src")
|
||||
}
|
||||
|
||||
for _, limit := range []string{"", "not-a-number", "-5", "0", "4294967297"} {
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/captures?limit="+limit, nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
body := captureListResponse(t, w)
|
||||
captures, _ := body["captures"].([]any)
|
||||
if len(captures) != 3 {
|
||||
t.Fatalf("limit=%q: captures = %#v, want all 3 (an invalid/absent limit must not become a 0-row LIMIT)", limit, body["captures"])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCapturesWithoutCapturesConfiguredIsEnabledFalse(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/captures", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d (unconfigured is not an error, per the memory/skills precedent)", w.Code, http.StatusOK)
|
||||
}
|
||||
body := captureListResponse(t, w)
|
||||
if enabled, _ := body["enabled"].(bool); enabled {
|
||||
t.Fatalf("enabled = %v, want false when Captures is nil", body["enabled"])
|
||||
}
|
||||
captures, ok := body["captures"].([]any)
|
||||
if !ok || len(captures) != 0 {
|
||||
t.Fatalf("captures = %#v, want an empty list", body["captures"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCapturesRequiresToken(t *testing.T) {
|
||||
srv := captureTestServer(t)
|
||||
srv.Token = "dashboard-secret"
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/captures", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code == http.StatusOK {
|
||||
t.Fatalf("status = %d, want captures to require the dashboard token like every other /api/* route", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// recordingIntake stands in for the host process's capture receiver
|
||||
// (internal/infrastructure/captureintake.Receiver): the write path is owned
|
||||
// elsewhere, so the mount test only needs an http.Handler that answers.
|
||||
type recordingIntake struct {
|
||||
hit int
|
||||
}
|
||||
|
||||
func (r *recordingIntake) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
|
||||
r.hit++
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
}
|
||||
|
||||
// TestCaptureIntakeMountedOnBypassMux pins the mount contract that used to
|
||||
// live inside the write handler: the capture route must accept
|
||||
// unauthenticated senders even when the dashboard is token-gated, mirroring
|
||||
// /healthz's precedent. The receiver decides nothing about tokens; it is
|
||||
// this registration that keeps intake off requireToken.
|
||||
func TestCaptureIntakeMountedOnBypassMux(t *testing.T) {
|
||||
srv := captureTestServer(t)
|
||||
srv.Token = "dashboard-secret"
|
||||
intake := &recordingIntake{}
|
||||
srv.CaptureIntake = intake
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{}`))
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want %d (intake must bypass requireToken; body = %s)", w.Code, http.StatusAccepted, w.Body.String())
|
||||
}
|
||||
if intake.hit != 1 {
|
||||
t.Fatalf("intake handler calls = %d, want 1", intake.hit)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCaptureIntakeNilLeavesRouteAbsent pins the composition lever: a
|
||||
// process that does not own intake (the UI process, per compose) leaves
|
||||
// CaptureIntake nil and gets no capture route at all, rather than an
|
||||
// intake that 503s. Two listeners serving the same authority is what
|
||||
// docs/prds/ui-service-boundary.md:30-33 forbids.
|
||||
func TestCaptureIntakeNilLeavesRouteAbsent(t *testing.T) {
|
||||
srv := captureTestServer(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.StatusAccepted {
|
||||
t.Fatalf("status = %d, want any non-accept (the route must not exist without a mounted intake)", w.Code)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,686 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels/status"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
// fakeSecrets are recognisable strings that must never appear anywhere in
|
||||
// handleConfig's response body. If any of these leak, the allowlist in
|
||||
// api_config.go has a hole -- see handleConfig's doc comment for why it is
|
||||
// built field by field rather than by marshalling config.Config directly.
|
||||
const (
|
||||
fakeForgeToken = "ghp_FAKESECRETTOKENVALUE123"
|
||||
fakeProviderKey = "sk-FAKEPROVIDERKEYVALUE456"
|
||||
fakeBWSKeyName = "FAKE-BWS-SECRET-KEY-789"
|
||||
fakeNATSToken = "nats-FAKESECRETTOKEN000"
|
||||
)
|
||||
|
||||
func configWithFakeSecrets() *config.Holder {
|
||||
return config.NewHolder(config.Config{
|
||||
WorkDir: "/work/archie",
|
||||
SkillsDir: "/work/archie/.agents/skills",
|
||||
BotUser: "archie-bot",
|
||||
BotEmail: "archie@example.com",
|
||||
Label: "archie",
|
||||
Forge: config.Forge{
|
||||
Type: "gitea",
|
||||
Host: "gitea.example.com",
|
||||
Token: secret.SecretRef{Engine: "env", Key: fakeForgeToken},
|
||||
},
|
||||
Models: map[string]string{"builder": "openai/gpt-4"},
|
||||
Providers: map[string]config.Provider{
|
||||
"openai": {
|
||||
Class: "openai",
|
||||
APIKeyEnv: "OPENAI_API_KEY",
|
||||
APIKey: secret.SecretRef{Engine: "bws", Key: fakeBWSKeyName},
|
||||
BaseURL: "https://api.openai.com/v1",
|
||||
},
|
||||
"custom": {
|
||||
Class: "custom",
|
||||
APIKey: secret.SecretRef{Engine: "literal", Key: fakeProviderKey},
|
||||
},
|
||||
},
|
||||
Repos: []config.Repo{
|
||||
{Owner: "acme", Name: "widget", Base: "main", Gate: [][]string{{"task", "check"}}},
|
||||
},
|
||||
NATS: config.NATSConfig{URL: "nats://127.0.0.1:4222", TokenEnv: "NATS_TOKEN"},
|
||||
Chat: config.ChatConfig{
|
||||
Telegram: config.TelegramConfig{Token: secret.SecretRef{Engine: "env", Key: "TELEGRAM_TOKEN"}},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// leakCandidates returns the set of fake secret strings a test should
|
||||
// confirm are absent from a response body. NATS token is included even
|
||||
// though handleConfig doesn't expose NATS today, guarding against a future
|
||||
// regression that starts serializing it wholesale.
|
||||
func leakCandidates() []string {
|
||||
return []string{fakeForgeToken, fakeProviderKey, fakeBWSKeyName, fakeNATSToken}
|
||||
}
|
||||
|
||||
// localView installs the projection a configuration owner publishes, built by
|
||||
// the same function the daemon calls. Tests that used to hand the server a
|
||||
// live config.Holder now hand it that holder's projection, which is what every
|
||||
// process renders from since the server stopped holding configuration
|
||||
// (archie-core-ml30).
|
||||
func localView(srv *Server, in ConfigViewInput) {
|
||||
srv.ConfigSource = func(context.Context) (ConfigView, bool, error) {
|
||||
return BuildConfigView(in), true, nil
|
||||
}
|
||||
}
|
||||
|
||||
// localConfig is localView for the common case: a config snapshot and nothing
|
||||
// else.
|
||||
func localConfig(srv *Server, cfg *config.Holder) {
|
||||
if cfg == nil {
|
||||
return
|
||||
}
|
||||
localView(srv, ConfigViewInput{Config: cfg.Get()})
|
||||
}
|
||||
|
||||
// TestBuildConfigViewPublishesPerIdentityForges: in a multi-identity
|
||||
// deployment Identity and Repositories describe the default identity alone,
|
||||
// which is not enough to attribute a task to the forge that owns it. The
|
||||
// projection publishes each identity's forge coordinates and its repository
|
||||
// list so a process rendering task rows can resolve per task
|
||||
// (archie-core-pv6t) -- and, like every other field here, without a token.
|
||||
func TestBuildConfigViewPublishesPerIdentityForges(t *testing.T) {
|
||||
cfg := config.Config{
|
||||
Forge: config.Forge{Type: "github", Host: "https://github.example"},
|
||||
Repos: []config.Repo{{Owner: "acme", Name: "widget"}},
|
||||
Identities: []config.IdentityConfig{
|
||||
{
|
||||
Name: "gitea-bot",
|
||||
Forge: config.Forge{Type: "gitea", Host: "https://gitea.example", Token: secret.SecretRef{Engine: "env", Key: fakeForgeToken}},
|
||||
Repos: []config.Repo{{Owner: "acme", Name: "gadget"}, {Owner: "beta", Name: "svc"}},
|
||||
},
|
||||
{
|
||||
Name: "github-bot",
|
||||
Forge: config.Forge{Type: "github", Host: "https://github.example", Token: secret.SecretRef{Engine: "env", Key: fakeForgeToken}},
|
||||
Repos: []config.Repo{{Owner: "beta", Name: "app"}},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
view := BuildConfigView(ConfigViewInput{Config: cfg})
|
||||
|
||||
if !view.MultiIdentity {
|
||||
t.Error("MultiIdentity = false with two configured identities; a reader would attribute every task to the default forge")
|
||||
}
|
||||
if len(view.Identities) != 2 {
|
||||
t.Fatalf("Identities = %+v, want both configured identities", view.Identities)
|
||||
}
|
||||
gitea := view.Identities[0]
|
||||
if gitea.Name != "gitea-bot" || gitea.ForgeType != "gitea" || gitea.ForgeHost != "https://gitea.example" {
|
||||
t.Errorf("Identities[0] = %+v, want the gitea-bot forge coordinates", gitea)
|
||||
}
|
||||
if len(gitea.Repos) != 2 || gitea.Repos[0].Owner != "acme" || gitea.Repos[0].Name != "gadget" || gitea.Repos[1].Name != "svc" {
|
||||
t.Errorf("Identities[0].Repos = %+v, want the repositories it owns (owner and name are what attributing a task needs)", gitea.Repos)
|
||||
}
|
||||
if view.Identities[1].Name != "github-bot" || view.Identities[1].ForgeHost != "https://github.example" {
|
||||
t.Errorf("Identities[1] = %+v, want the github-bot forge coordinates", view.Identities[1])
|
||||
}
|
||||
|
||||
// The projection is the browser's copy, so the per-identity forges are a
|
||||
// new surface for a token to escape through.
|
||||
body, err := json.Marshal(view)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal view: %v", err)
|
||||
}
|
||||
for _, leak := range leakCandidates() {
|
||||
if strings.Contains(string(body), leak) {
|
||||
t.Errorf("published projection leaked %q; per-identity forges must publish coordinates only, never credentials", leak)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestConfigViewWithoutIdentitiesCarriesNone: a single-identity deployment
|
||||
// publishes no identity list, and the default identity's forge in Identity
|
||||
// stays the whole answer. This is the shape every deployment produces today.
|
||||
func TestConfigViewWithoutIdentitiesCarriesNone(t *testing.T) {
|
||||
view := BuildConfigView(ConfigViewInput{Config: configWithFakeSecrets().Get()})
|
||||
|
||||
if view.MultiIdentity {
|
||||
t.Error("MultiIdentity = true without [[identities]]; the projection would claim a per-identity layout it does not have")
|
||||
}
|
||||
if len(view.Identities) != 0 {
|
||||
t.Errorf("Identities = %+v, want none for a single-identity deployment", view.Identities)
|
||||
}
|
||||
if view.Identity.ForgeHost != "gitea.example.com" {
|
||||
t.Errorf("Identity.ForgeHost = %q, want the deployment's own forge", view.Identity.ForgeHost)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildConfigViewPublishesReviewDial: the effective pr-review policy is
|
||||
// published, so the dashboard (and any other reader of the snapshot) can show
|
||||
// which dials are in force after the review-settings resource is layered over
|
||||
// the file's [review] section (docs/prds/review-settings-resource.md,
|
||||
// "Projection and page").
|
||||
func TestBuildConfigViewPublishesReviewDial(t *testing.T) {
|
||||
view := BuildConfigView(ConfigViewInput{Config: config.Config{
|
||||
Review: config.Review{PrecisionGate: true, ApproveBeforePost: false},
|
||||
}})
|
||||
|
||||
if !view.Review.PrecisionGate {
|
||||
t.Error("Review.PrecisionGate = false, want the config's true")
|
||||
}
|
||||
if view.Review.ApproveBeforePost {
|
||||
t.Error("Review.ApproveBeforePost = true, want the config's false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleConfigNeverLeaksSecrets(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
cfg *config.Holder
|
||||
}{
|
||||
{name: "populated config with secrets", cfg: configWithFakeSecrets()},
|
||||
{name: "nil config", cfg: nil},
|
||||
{name: "zero-value config", cfg: config.NewHolder(config.Config{})},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
localConfig(srv, tc.cfg)
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
|
||||
body := w.Body.String()
|
||||
for _, leak := range leakCandidates() {
|
||||
if strings.Contains(body, leak) {
|
||||
t.Errorf("response body leaked secret value %q:\n%s", leak, body)
|
||||
}
|
||||
}
|
||||
|
||||
var got map[string]any
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("response is not valid JSON: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleConfigSafeFieldsPresent proves the allowlisted, non-secret
|
||||
// fields still make it through -- a test that only checked for absence of
|
||||
// secrets could pass trivially by returning {}.
|
||||
func TestHandleConfigSafeFieldsPresent(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
localConfig(srv, configWithFakeSecrets())
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
var got ConfigView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
|
||||
if got.Identity.BotUser != "archie-bot" {
|
||||
t.Errorf("Identity.BotUser = %q, want archie-bot", got.Identity.BotUser)
|
||||
}
|
||||
if got.Identity.ForgeHost != "gitea.example.com" {
|
||||
t.Errorf("Identity.ForgeHost = %q, want gitea.example.com", got.Identity.ForgeHost)
|
||||
}
|
||||
if len(got.Repositories) != 1 || got.Repositories[0].Owner != "acme" {
|
||||
t.Errorf("Repositories = %+v", got.Repositories)
|
||||
}
|
||||
if !got.Providers["openai"].Configured {
|
||||
t.Errorf("Providers[openai].Configured = false, want true (APIKeyEnv is set)")
|
||||
}
|
||||
if got.Providers["openai"].APIKeyEnv != "OPENAI_API_KEY" {
|
||||
t.Errorf("Providers[openai].APIKeyEnv = %q, want OPENAI_API_KEY", got.Providers["openai"].APIKeyEnv)
|
||||
}
|
||||
if got.Storage.WorkDir != "/work/archie" {
|
||||
t.Errorf("Storage.WorkDir = %q", got.Storage.WorkDir)
|
||||
}
|
||||
if strings.Contains(w.Body.String(), `"agent"`) {
|
||||
t.Errorf("removed agent execution selector leaked through config API: %s", w.Body)
|
||||
}
|
||||
var raw struct {
|
||||
Containers map[string]any `json:"containers"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &raw); err != nil {
|
||||
t.Fatalf("decode raw config view: %v", err)
|
||||
}
|
||||
if _, exists := raw.Containers["enabled"]; exists {
|
||||
t.Errorf("removed container execution switch leaked through config API: %s", w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleConfigIncludesReloadStatus proves a failed reload is surfaced
|
||||
// in /api/config so the operator can see the running config is stale
|
||||
// without reading logs.
|
||||
func TestHandleConfigIncludesReloadStatus(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
localView(srv, ConfigViewInput{
|
||||
Config: configWithFakeSecrets().Get(),
|
||||
Reload: &config.ReloadStatus{
|
||||
LastError: "poll_interval must be positive",
|
||||
LastErrorAt: "2026-08-09T12:00:00Z",
|
||||
},
|
||||
})
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
var got ConfigView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if got.Reload == nil {
|
||||
t.Fatal("Reload = nil, want the failed-reload status")
|
||||
}
|
||||
if got.Reload.LastError != "poll_interval must be positive" {
|
||||
t.Errorf("Reload.LastError = %q", got.Reload.LastError)
|
||||
}
|
||||
if got.Reload.LastErrorAt != "2026-08-09T12:00:00Z" {
|
||||
t.Errorf("Reload.LastErrorAt = %q", got.Reload.LastErrorAt)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleConfigOmitsReloadStatusWhenUnavailable pins that the reload
|
||||
// field is absent (not empty) when the server has no reload seam wired.
|
||||
func TestHandleConfigOmitsReloadStatusWhenUnavailable(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
localConfig(srv, configWithFakeSecrets())
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
var got ConfigView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if got.Reload != nil {
|
||||
t.Errorf("Reload = %+v, want nil (no reload seam)", got.Reload)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConfigViewCarriesProvenance proves the provenance list the
|
||||
// configuration owner supplies reaches /api/config.
|
||||
func TestConfigViewCarriesProvenance(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
localView(srv, ConfigViewInput{
|
||||
Config: configWithFakeSecrets().Get(),
|
||||
Provenance: []ConfigOrigin{
|
||||
{Path: "/etc/archie/config.toml", Role: "main", Layer: "base"},
|
||||
{Path: "/etc/archie/conf.d/docker.yaml", Role: "extra", Layer: "overlay", Feature: "docker"},
|
||||
},
|
||||
})
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
var got ConfigView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if len(got.Provenance) != 2 {
|
||||
t.Fatalf("Provenance = %+v, want 2 origins", got.Provenance)
|
||||
}
|
||||
if got.Provenance[0].Path != "/etc/archie/config.toml" {
|
||||
t.Errorf("Provenance[0].Path = %q", got.Provenance[0].Path)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleConfigReportsLockedKeys proves the dashboard is told which
|
||||
// config keys it cannot edit and why, so it can disable those rows
|
||||
// instead of silently omitting the edit affordance.
|
||||
func TestHandleConfigReportsLockedKeys(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
localConfig(srv, configWithFakeSecrets())
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
var got ConfigView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
for _, key := range []string{"database_url", "work_dir"} {
|
||||
if got.Locked[key] == "" {
|
||||
t.Errorf("Locked[%q] is empty, want a reason", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleConfigIncludesSchemaWithLiveValues proves the schema (archie-core-b6ew.2)
|
||||
// carries the same values as the flat ConfigView fields it is built from,
|
||||
// not a stale or empty catalog.
|
||||
func TestHandleConfigIncludesSchemaWithLiveValues(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
localConfig(srv, configWithFakeSecrets())
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
var got ConfigView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if len(got.Schema) == 0 {
|
||||
t.Fatal("Schema is empty, want the field descriptor catalog")
|
||||
}
|
||||
|
||||
fields := map[string]ConfigField{}
|
||||
for _, section := range got.Schema {
|
||||
for _, f := range section.Fields {
|
||||
fields[f.Key] = f
|
||||
}
|
||||
}
|
||||
|
||||
botUser, ok := fields["bot_user"]
|
||||
if !ok {
|
||||
t.Fatal(`Schema has no "bot_user" field`)
|
||||
}
|
||||
if botUser.Value != got.Identity.BotUser {
|
||||
t.Errorf("Schema[bot_user].Value = %v, want %v (ConfigView.Identity.BotUser)", botUser.Value, got.Identity.BotUser)
|
||||
}
|
||||
|
||||
// A locked field's schema entry carries the reason the flat Locked map
|
||||
// carries, so the generic renderer does not need to cross-reference it.
|
||||
workDir, ok := fields["work_dir"]
|
||||
if !ok {
|
||||
t.Fatal(`Schema has no "work_dir" field`)
|
||||
}
|
||||
if workDir.LockedReason == "" {
|
||||
t.Error("Schema[work_dir].LockedReason is empty, want the overlay-denied reason")
|
||||
}
|
||||
if workDir.LockedReason != got.Locked["work_dir"] {
|
||||
t.Errorf("Schema[work_dir].LockedReason = %q, want %q (ConfigView.Locked[work_dir])", workDir.LockedReason, got.Locked["work_dir"])
|
||||
}
|
||||
|
||||
// Structured fields still carry their value, for the dedicated editors
|
||||
// archie-core-b6ew.4 adds.
|
||||
repos, ok := fields["repos"]
|
||||
if !ok {
|
||||
t.Fatal(`Schema has no "repos" field`)
|
||||
}
|
||||
reposValue, ok := repos.Value.([]any)
|
||||
if !ok || len(reposValue) != 1 {
|
||||
t.Errorf("Schema[repos].Value = %#v, want the one configured repository", repos.Value)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleConfigSchemaCarriesNoEditabilityAdvert pins that the schema
|
||||
// response stops advertising a write capability no process has. Configuration
|
||||
// settings are written through the control plane, not the dashboard (see
|
||||
// docs/architecture/configuration.md, "Settings writes go through the
|
||||
// control plane"), and ui/src/settings/types.ts's ConfigField -- the
|
||||
// reader-side declaration of this wire shape -- carries every descriptor
|
||||
// property except an editability one. A descriptor that emits one offers the
|
||||
// dashboard an affordance nothing on the server can honour.
|
||||
func TestHandleConfigSchemaCarriesNoEditabilityAdvert(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
localConfig(srv, configWithFakeSecrets())
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
var wire struct {
|
||||
Schema []struct {
|
||||
Fields []map[string]any `json:"fields"`
|
||||
} `json:"schema"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &wire); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if len(wire.Schema) == 0 {
|
||||
t.Fatal("schema is empty, want the field descriptor catalog")
|
||||
}
|
||||
for _, section := range wire.Schema {
|
||||
for _, field := range section.Fields {
|
||||
if editable, ok := field["editable"]; ok {
|
||||
t.Errorf("schema field %v carries editable=%v; nothing writes configuration through the dashboard, so the descriptor must not offer the affordance", field["key"], editable)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleConfigSchemaNeverLeaksSecrets extends the secret-leak guard to
|
||||
// the schema block specifically, so a future field added to
|
||||
// configFieldDescriptors without going through ConfigView's allowlist would
|
||||
// be caught even if leakCandidates never appears in the flat fields.
|
||||
func TestHandleConfigSchemaNeverLeaksSecrets(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
localConfig(srv, configWithFakeSecrets())
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
var got ConfigView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
schemaJSON, err := json.Marshal(got.Schema)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal schema: %v", err)
|
||||
}
|
||||
for _, leak := range leakCandidates() {
|
||||
if strings.Contains(string(schemaJSON), leak) {
|
||||
t.Errorf("schema leaked secret value %q:\n%s", leak, schemaJSON)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleChannelsWithoutManagerIsEmpty: channel lifecycle is the status
|
||||
// manager's to report. A process without one answers an empty list rather
|
||||
// than deriving channels from configuration, which could only ever describe
|
||||
// what was configured, never what is running.
|
||||
func TestHandleChannelsWithoutManagerIsEmpty(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
localConfig(srv, configWithFakeSecrets())
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/channels", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
body := w.Body.String()
|
||||
for _, leak := range leakCandidates() {
|
||||
if strings.Contains(body, leak) {
|
||||
t.Errorf("channels response leaked secret value %q:\n%s", leak, body)
|
||||
}
|
||||
}
|
||||
var got struct {
|
||||
Channels []ChannelView `json:"channels"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if len(got.Channels) != 0 {
|
||||
t.Errorf("Channels = %+v, want empty without a status manager", got.Channels)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleChannelsUsesRuntimeManager(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
// Channels is a source rather than a concrete manager now: a process that
|
||||
// hosts channels supplies its own, and the dashboard process supplies a reader
|
||||
// over the State Store. This test drives the first.
|
||||
manager := status.NewManager([]status.Descriptor{{
|
||||
ID: "telegram", Name: "Telegram", Configured: true, ReloadSupported: true,
|
||||
}})
|
||||
manager.MarkFailed("telegram", "token rejected")
|
||||
srv.Channels = manager
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/channels", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
var got struct {
|
||||
Channels []ChannelView `json:"channels"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got.Channels) != 1 || got.Channels[0].State != "failed" || !got.Channels[0].ReloadSupported {
|
||||
t.Fatalf("channels = %#v", got.Channels)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRemoteConfigViewRendersThePublishedSnapshot: the UI process has no
|
||||
// configuration of its own, so the page it serves is whatever the owner
|
||||
// published.
|
||||
func TestRemoteConfigViewRendersThePublishedSnapshot(t *testing.T) {
|
||||
published := ConfigView{
|
||||
Identity: IdentityView{BotUser: "archie", ForgeType: "github"},
|
||||
Models: map[string]string{"chat": "anthropic/claude"},
|
||||
Providers: map[string]ProviderView{"anthropic": {APIKeyEnv: "ANTHROPIC_API_KEY", Configured: true}},
|
||||
Provenance: []ConfigOrigin{{Path: "/etc/archie/config.toml", Role: "main"}},
|
||||
}
|
||||
document, err := json.Marshal(published)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source := RemoteConfigView(stubSnapshots{snapshot: storecontract.ConfigSnapshot{
|
||||
Schema: ConfigViewSchema,
|
||||
Document: document,
|
||||
}, found: true})
|
||||
|
||||
view, found, err := source(t.Context())
|
||||
if err != nil || !found {
|
||||
t.Fatalf("RemoteConfigView = (found %v, %v), want the published snapshot", found, err)
|
||||
}
|
||||
if view.Identity.BotUser != "archie" || view.Providers["anthropic"].APIKeyEnv != "ANTHROPIC_API_KEY" {
|
||||
t.Fatalf("view = %+v, want the published values", view)
|
||||
}
|
||||
if len(view.Provenance) != 1 || view.Provenance[0].Path != "/etc/archie/config.toml" {
|
||||
t.Errorf("Provenance = %+v, want the published chain", view.Provenance)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRemoteConfigViewRefusesAnUnknownSchema: a document whose shape this
|
||||
// build does not know is not something to render half of.
|
||||
func TestRemoteConfigViewRefusesAnUnknownSchema(t *testing.T) {
|
||||
source := RemoteConfigView(stubSnapshots{snapshot: storecontract.ConfigSnapshot{
|
||||
Schema: "webui.ConfigView/99",
|
||||
Document: []byte(`{}`),
|
||||
}, found: true})
|
||||
|
||||
if _, found, err := source(t.Context()); err == nil || found {
|
||||
t.Fatalf("unknown schema = (found %v, %v), want an error", found, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConfigWithNoPublishedSnapshotIsEmpty: before the owner has published
|
||||
// anything the page has nothing to show, which is the documented degraded
|
||||
// response, not a failure.
|
||||
func TestConfigWithNoPublishedSnapshotIsEmpty(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.ConfigSource = RemoteConfigView(stubSnapshots{})
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/config", nil)
|
||||
res := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(res, req)
|
||||
|
||||
if res.Code != http.StatusOK || strings.TrimSpace(res.Body.String()) != "{}" {
|
||||
t.Fatalf("GET /api/config = %d %q, want 200 {}", res.Code, res.Body)
|
||||
}
|
||||
}
|
||||
|
||||
type stubSnapshots struct {
|
||||
snapshot storecontract.ConfigSnapshot
|
||||
found bool
|
||||
err error
|
||||
}
|
||||
|
||||
func (s stubSnapshots) PutConfigSnapshot(context.Context, storecontract.ConfigSnapshot) error {
|
||||
return s.err
|
||||
}
|
||||
|
||||
func (s stubSnapshots) ConfigSnapshot(context.Context) (storecontract.ConfigSnapshot, bool, error) {
|
||||
return s.snapshot, s.found, s.err
|
||||
}
|
||||
|
||||
// TestCapabilitiesReportWhatThisProcessCanServe: the same dashboard is served
|
||||
// by the daemon, which holds every runtime handle, and by the UI process,
|
||||
// which holds two remote contracts. A section with nothing behind it answers
|
||||
// empty rather than failing, which the browser cannot tell from a quiet
|
||||
// deployment -- so the server says which sections it can back.
|
||||
func TestCapabilitiesReportWhatThisProcessCanServe(t *testing.T) {
|
||||
get := func(srv *Server) map[string]bool {
|
||||
t.Helper()
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/capabilities", nil)
|
||||
res := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(res, req)
|
||||
if res.Code != http.StatusOK {
|
||||
t.Fatalf("GET /api/capabilities = %d, want 200", res.Code)
|
||||
}
|
||||
var body struct {
|
||||
Sections map[string]bool `json:"sections"`
|
||||
}
|
||||
if err := json.Unmarshal(res.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode capabilities: %v", err)
|
||||
}
|
||||
return body.Sections
|
||||
}
|
||||
|
||||
bare := get(newTestServer(t))
|
||||
for _, section := range []string{"logs", "curators", "channels", "mappings", "bindings", "skills"} {
|
||||
if bare[section] {
|
||||
t.Errorf("section %q reported available with nothing wired behind it", section)
|
||||
}
|
||||
}
|
||||
// The task board and configuration page work from the store and the
|
||||
// configured source, so they are never hidden.
|
||||
for _, section := range []string{"workflows", "settings"} {
|
||||
if !bare[section] {
|
||||
t.Errorf("section %q reported unavailable; it is served in every composition", section)
|
||||
}
|
||||
}
|
||||
|
||||
wired := newTestServer(t)
|
||||
wired.Channels = status.NewManager([]status.Descriptor{{ID: "telegram", Name: "Telegram"}})
|
||||
wired.LogFeed = logging.NewFeed(10)
|
||||
wired.Curators = stubCurators{}
|
||||
wired.Skills = stubSkillCatalog{}
|
||||
got := get(wired)
|
||||
for _, section := range []string{"logs", "curators", "skills", "channels"} {
|
||||
if !got[section] {
|
||||
t.Errorf("section %q reported unavailable despite being wired", section)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// stubCurators satisfies the webui-owned CuratorStatus view for tests.
|
||||
type stubCurators struct{}
|
||||
|
||||
func (stubCurators) Names() []string { return []string{"wired"} }
|
||||
func (stubCurators) Health(_ context.Context) map[string]CuratorHealthView {
|
||||
return map[string]CuratorHealthView{"wired": {Status: "healthy"}}
|
||||
}
|
||||
func (stubCurators) Activity(string) (CuratorActivity, bool) { return CuratorActivity{}, false }
|
||||
|
||||
// stubSkillCatalog satisfies the webui-owned SkillCatalog view for tests.
|
||||
type stubSkillCatalog struct{}
|
||||
|
||||
func (stubSkillCatalog) Skills() []SkillView { return []SkillView{{Name: "demo"}} }
|
||||
@@ -1,225 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
)
|
||||
|
||||
type controlPlaneClientStub struct {
|
||||
command *controlpb.CommandRequest
|
||||
// query is the resource a kind-less Query falls back to; queries is every
|
||||
// request Query was handed, so a test can read back the org each one
|
||||
// carried.
|
||||
query *controlpb.Resource
|
||||
queries []*controlpb.QueryRequest
|
||||
history *controlpb.HistoryRequest
|
||||
revisions []*controlpb.Revision
|
||||
audit *controlpb.AuditRequest
|
||||
entries []*controlpb.AuditEntry
|
||||
watch grpc.ServerStreamingClient[controlpb.WatchResponse]
|
||||
err error
|
||||
// resources, when set, answers Query per kind and keeps what Command
|
||||
// writes, falling back to query for a kind it does not hold.
|
||||
resources map[string]*controlpb.Resource
|
||||
}
|
||||
|
||||
func (f *controlPlaneClientStub) Catalog(context.Context, *controlpb.CatalogRequest, ...grpc.CallOption) (*controlpb.CatalogResponse, error) {
|
||||
return &controlpb.CatalogResponse{}, f.err
|
||||
}
|
||||
|
||||
func (f *controlPlaneClientStub) Query(_ context.Context, request *controlpb.QueryRequest, _ ...grpc.CallOption) (*controlpb.QueryResponse, error) {
|
||||
f.queries = append(f.queries, request)
|
||||
if resource, ok := f.resources[request.Kind]; ok {
|
||||
return &controlpb.QueryResponse{Resource: resource}, f.err
|
||||
}
|
||||
return &controlpb.QueryResponse{Resource: f.query}, f.err
|
||||
}
|
||||
|
||||
func (f *controlPlaneClientStub) History(_ context.Context, request *controlpb.HistoryRequest, _ ...grpc.CallOption) (*controlpb.HistoryResponse, error) {
|
||||
f.history = request
|
||||
return &controlpb.HistoryResponse{Revisions: f.revisions}, f.err
|
||||
}
|
||||
|
||||
func (f *controlPlaneClientStub) Audit(_ context.Context, request *controlpb.AuditRequest, _ ...grpc.CallOption) (*controlpb.AuditResponse, error) {
|
||||
f.audit = request
|
||||
return &controlpb.AuditResponse{Entries: f.entries}, f.err
|
||||
}
|
||||
|
||||
func (f *controlPlaneClientStub) Command(_ context.Context, request *controlpb.CommandRequest, _ ...grpc.CallOption) (*controlpb.CommandResponse, error) {
|
||||
f.command = request
|
||||
if f.err != nil {
|
||||
return nil, f.err
|
||||
}
|
||||
resource := &controlpb.Resource{Kind: request.Kind, Version: request.ExpectedVersion + 1, ValueJson: request.ValueJson}
|
||||
if f.resources != nil {
|
||||
f.resources[request.Kind] = resource
|
||||
}
|
||||
return &controlpb.CommandResponse{Resource: resource}, nil
|
||||
}
|
||||
|
||||
func (f *controlPlaneClientStub) Watch(context.Context, *controlpb.WatchRequest, ...grpc.CallOption) (grpc.ServerStreamingClient[controlpb.WatchResponse], error) {
|
||||
return f.watch, f.err
|
||||
}
|
||||
|
||||
// The multiplexed stream answers before any topic changes. An unchanged
|
||||
// resource must not leave the connection pill at Connecting indefinitely.
|
||||
func TestLiveStreamOpensBeforeTheFirstChange(t *testing.T) {
|
||||
server := httptest.NewServer((&Server{Store: &fakeEventStore{}, Log: slog.New(slog.DiscardHandler)}).Handler())
|
||||
t.Cleanup(server.Close)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
request, _ := http.NewRequestWithContext(ctx, http.MethodGet, server.URL+"/api/stream", nil)
|
||||
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatalf("stream did not answer before its first change: %v", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if got := response.Header.Get("Content-Type"); got != "text/event-stream" {
|
||||
t.Fatalf("Content-Type = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestControlPlaneCommandSuppliesTrustedAttribution(t *testing.T) {
|
||||
client := &controlPlaneClientStub{}
|
||||
server := &Server{ControlPlane: client}
|
||||
body := bytes.NewBufferString(`{"value":{"max_model_tool_steps":12},"expected_version":1,"actor":"browser"}`)
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/control-plane/resources/workflow-execution-settings/commands/replace", body)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("X-Archie-CSRF", "1")
|
||||
response := httptest.NewRecorder()
|
||||
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %q", response.Code, response.Body.String())
|
||||
}
|
||||
if client.command.Actor != string(identity.SystemID) || client.command.Source != "archie-ui" {
|
||||
t.Fatalf("attribution = %q/%q, want the System identity from archie-ui", client.command.Actor, client.command.Source)
|
||||
}
|
||||
if !strings.HasPrefix(client.command.RequestId, "ui-") || client.command.ExpectedVersion != 1 {
|
||||
t.Fatalf("request = %+v", client.command)
|
||||
}
|
||||
var got struct {
|
||||
Resource controlPlaneResource `json:"resource"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Resource.Version != 2 || string(got.Resource.Value) != `{"max_model_tool_steps":12}` {
|
||||
t.Fatalf("resource = %+v", got.Resource)
|
||||
}
|
||||
}
|
||||
|
||||
func TestControlPlaneConflictMapsToHTTPConflict(t *testing.T) {
|
||||
server := &Server{ControlPlane: &controlPlaneClientStub{err: status.Error(codes.Aborted, "version conflict")}}
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/control-plane/resources/settings/commands/replace", strings.NewReader(`{"value":{},"expected_version":1}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("X-Archie-CSRF", "1")
|
||||
response := httptest.NewRecorder()
|
||||
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
|
||||
if response.Code != http.StatusConflict {
|
||||
t.Fatalf("status = %d, want 409", response.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestControlPlaneHistoryRendersRevisionsForRestore(t *testing.T) {
|
||||
client := &controlPlaneClientStub{revisions: []*controlpb.Revision{
|
||||
{Version: 2, ValueJson: []byte(`{"max_model_tool_steps":40}`), Actor: string(identity.SystemID), Source: "archie-ui", RequestId: "ui-2"},
|
||||
{Version: 1, ValueJson: []byte(`{"max_model_tool_steps":25}`), Actor: "system:migration", Source: "legacy-config", RequestId: "import"},
|
||||
}}
|
||||
server := &Server{ControlPlane: client}
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/control-plane/resources/workflow-execution-settings/history", nil)
|
||||
response := httptest.NewRecorder()
|
||||
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %q", response.Code, response.Body.String())
|
||||
}
|
||||
if client.history.GetKind() != "workflow-execution-settings" {
|
||||
t.Fatalf("history requested for %q", client.history.GetKind())
|
||||
}
|
||||
var got struct {
|
||||
Revisions []struct {
|
||||
Version int64 `json:"version"`
|
||||
Value json.RawMessage `json:"value"`
|
||||
Actor string `json:"actor"`
|
||||
Source string `json:"source"`
|
||||
} `json:"revisions"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got.Revisions) != 2 || got.Revisions[0].Version != 2 || got.Revisions[0].Actor != string(identity.SystemID) {
|
||||
t.Fatalf("revisions = %+v", got.Revisions)
|
||||
}
|
||||
// The value is the restore payload: it has to survive as JSON, not base64.
|
||||
if string(got.Revisions[1].Value) != `{"max_model_tool_steps":25}` {
|
||||
t.Fatalf("older value = %s, want the JSON a replace can send back", got.Revisions[1].Value)
|
||||
}
|
||||
}
|
||||
|
||||
func TestControlPlaneHistoryWithoutAControlPlaneIsUnavailable(t *testing.T) {
|
||||
server := &Server{}
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/control-plane/resources/limits/history", nil)
|
||||
response := httptest.NewRecorder()
|
||||
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
|
||||
if response.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want 503", response.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestControlPlaneAuditFiltersByTableAndRecord: the page names its table and
|
||||
// records; the endpoint forwards exactly those and returns each changed field
|
||||
// with its JSON values intact.
|
||||
func TestControlPlaneAuditFiltersByTableAndRecord(t *testing.T) {
|
||||
client := &controlPlaneClientStub{entries: []*controlpb.AuditEntry{{
|
||||
Id: 9, Table: "resources", RecordKey: "workflow-execution-settings", Field: "max_model_tool_steps",
|
||||
OldValueJson: []byte("90"), NewValueJson: []byte("120"), Version: 2, Actor: "system", Source: "archie-ui",
|
||||
}}}
|
||||
server := &Server{ControlPlane: client}
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/control-plane/audit?table=resources&key=workflow-execution-settings&key=model-settings", nil)
|
||||
response := httptest.NewRecorder()
|
||||
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %q", response.Code, response.Body.String())
|
||||
}
|
||||
if client.audit.GetTable() != "resources" || strings.Join(client.audit.GetRecordKeys(), ",") != "workflow-execution-settings,model-settings" {
|
||||
t.Fatalf("forwarded %+v", client.audit)
|
||||
}
|
||||
var got struct {
|
||||
Entries []struct {
|
||||
Field string `json:"field"`
|
||||
OldValue json.RawMessage `json:"old_value"`
|
||||
NewValue json.RawMessage `json:"new_value"`
|
||||
Version int64 `json:"version"`
|
||||
} `json:"entries"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got.Entries) != 1 || got.Entries[0].Field != "max_model_tool_steps" || string(got.Entries[0].OldValue) != "90" || string(got.Entries[0].NewValue) != "120" || got.Entries[0].Version != 2 {
|
||||
t.Fatalf("entries = %+v", got.Entries)
|
||||
}
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/curator"
|
||||
)
|
||||
|
||||
type stubCuratorEngine struct {
|
||||
name string
|
||||
manifest curator.Manifest
|
||||
health curator.Health
|
||||
}
|
||||
|
||||
func (c *stubCuratorEngine) Name() string { return c.name }
|
||||
func (c *stubCuratorEngine) Version() string { return "v1" }
|
||||
func (c *stubCuratorEngine) Manifest() curator.Manifest { return c.manifest }
|
||||
func (c *stubCuratorEngine) Bind(curator.Registrar) {}
|
||||
func (c *stubCuratorEngine) Start(context.Context) error { return nil }
|
||||
func (c *stubCuratorEngine) Stop(context.Context) error { return nil }
|
||||
func (c *stubCuratorEngine) Health(context.Context) curator.Health { return c.health }
|
||||
func (c *stubCuratorEngine) Check(context.Context) (bool, error) { return false, nil }
|
||||
func (c *stubCuratorEngine) Pass(context.Context, curator.PassInput) (curator.PassResult, error) {
|
||||
return curator.PassResult{}, nil
|
||||
}
|
||||
|
||||
func TestHandleCuratorsNilRegistryReturnsEmpty(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/curators", nil))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
|
||||
var response struct {
|
||||
Curators []CuratorView `json:"curators"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(response.Curators) != 0 {
|
||||
t.Fatalf("curators = %#v, want empty", response.Curators)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCuratorsReportsNamesHealthAndActivity(t *testing.T) {
|
||||
registry := curator.NewRegistry(curator.Registrar{})
|
||||
c := &stubCuratorEngine{
|
||||
name: "skill-curator",
|
||||
manifest: curator.Manifest{Interval: time.Minute},
|
||||
health: curator.Health{Status: curator.HealthHealthy, Message: "ok"},
|
||||
}
|
||||
if err := registry.Register(c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
at := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
registry.RecordActivity("skill-curator", at, []curator.Action{
|
||||
{At: at, Type: "skill.updated", Detail: "rewrote foo", Reason: "stale content"},
|
||||
})
|
||||
|
||||
srv := newTestServer(t)
|
||||
srv.Curators = curatorStatusAdapter{registry}
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/curators", nil))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
|
||||
var response struct {
|
||||
Curators []CuratorView `json:"curators"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(response.Curators) != 1 {
|
||||
t.Fatalf("curators = %#v, want 1", response.Curators)
|
||||
}
|
||||
got := response.Curators[0]
|
||||
if got.Name != "skill-curator" {
|
||||
t.Fatalf("Name = %q, want skill-curator", got.Name)
|
||||
}
|
||||
if got.Health.Status != string(curator.HealthHealthy) || got.Health.Message != "ok" {
|
||||
t.Fatalf("Health = %#v", got.Health)
|
||||
}
|
||||
if got.LastRunAt == nil || !got.LastRunAt.Equal(at) {
|
||||
t.Fatalf("LastRunAt = %v, want %v", got.LastRunAt, at)
|
||||
}
|
||||
if got.LastRunActions != 1 {
|
||||
t.Fatalf("LastRunActions = %d, want 1", got.LastRunActions)
|
||||
}
|
||||
if len(got.RecentActions) != 1 || got.RecentActions[0].Type != "skill.updated" || got.RecentActions[0].Reason != "stale content" {
|
||||
t.Fatalf("RecentActions = %#v", got.RecentActions)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCuratorsReportsRegisteredCuratorWithNoActivityYet(t *testing.T) {
|
||||
registry := curator.NewRegistry(curator.Registrar{})
|
||||
c := &stubCuratorEngine{
|
||||
name: "never-run",
|
||||
manifest: curator.Manifest{Interval: time.Minute},
|
||||
health: curator.Health{Status: curator.HealthHealthy},
|
||||
}
|
||||
if err := registry.Register(c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
srv := newTestServer(t)
|
||||
srv.Curators = curatorStatusAdapter{registry}
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/curators", nil))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
|
||||
var response struct {
|
||||
Curators []CuratorView `json:"curators"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(response.Curators) != 1 {
|
||||
t.Fatalf("curators = %#v, want 1", response.Curators)
|
||||
}
|
||||
if got := response.Curators[0]; got.LastRunAt != nil || got.LastRunActions != 0 || len(got.RecentActions) != 0 {
|
||||
t.Fatalf("expected zero-value activity for a never-run curator, got %#v", got)
|
||||
}
|
||||
// Regression guard: time.Time's zero value is not "empty" to
|
||||
// encoding/json, so a naive time.Time field would serialize as
|
||||
// "0001-01-01T00:00:00Z" (a truthy string on the frontend) instead of
|
||||
// being omitted. Assert the raw JSON, not just the unmarshalled Go
|
||||
// value, so a future revert of the *time.Time fix is caught here.
|
||||
if body := w.Body.String(); strings.Contains(body, "0001-01-01") {
|
||||
t.Fatalf("response leaks zero-value time.Time: %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
// curatorStatusAdapter adapts the real registry to the webui-owned
|
||||
// CuratorStatus view, mirroring the daemon's bootstrap adapter.
|
||||
type curatorStatusAdapter struct{ r *curator.Registry }
|
||||
|
||||
func (a curatorStatusAdapter) Names() []string { return a.r.Names() }
|
||||
|
||||
func (a curatorStatusAdapter) Health(ctx context.Context) map[string]CuratorHealthView {
|
||||
health := a.r.Health(ctx)
|
||||
views := make(map[string]CuratorHealthView, len(health))
|
||||
for name, h := range health {
|
||||
views[name] = CuratorHealthView{Status: string(h.Status), Message: h.Message}
|
||||
}
|
||||
return views
|
||||
}
|
||||
|
||||
func (a curatorStatusAdapter) Activity(name string) (CuratorActivity, bool) {
|
||||
activity, ok := a.r.Activity(name)
|
||||
if !ok {
|
||||
return CuratorActivity{}, false
|
||||
}
|
||||
view := CuratorActivity{
|
||||
LastRunAt: activity.LastRunAt,
|
||||
LastRunActions: activity.LastRunActions,
|
||||
Recent: make([]CuratorActionView, 0, len(activity.Recent)),
|
||||
}
|
||||
for _, a2 := range activity.Recent {
|
||||
view.Recent = append(view.Recent, CuratorActionView{
|
||||
At: a2.At, Type: a2.Type, Detail: a2.Detail, Reason: a2.Reason,
|
||||
})
|
||||
}
|
||||
return view, true
|
||||
}
|
||||
@@ -1,189 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
type memCaptures struct{ list []storecontract.CapturedEvent }
|
||||
|
||||
func (m *memCaptures) InsertCapture(_ context.Context, c storecontract.CapturedEvent, _ time.Duration, _ int) (string, error) {
|
||||
m.list = append(m.list, c)
|
||||
return c.ID, nil
|
||||
}
|
||||
|
||||
func (m *memCaptures) ListCaptures(context.Context, int) ([]storecontract.CapturedEvent, error) {
|
||||
return m.list, nil
|
||||
}
|
||||
|
||||
// memEventTypes applies the domain's validation and overlap refusal, as the
|
||||
// real store does.
|
||||
type memEventTypes struct{ types []eventtype.EventType }
|
||||
|
||||
func (m *memEventTypes) InsertEventType(_ context.Context, t eventtype.EventType) (string, error) {
|
||||
if err := t.Validate(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := eventtype.CheckOverlap(m.types, t); err != nil {
|
||||
return "", err
|
||||
}
|
||||
t.ID = "et-" + t.Name
|
||||
m.types = append(m.types, t)
|
||||
return t.ID, nil
|
||||
}
|
||||
|
||||
func (m *memEventTypes) UpdateEventType(_ context.Context, t eventtype.EventType) error {
|
||||
for i, existing := range m.types {
|
||||
if existing.ID == t.ID {
|
||||
t.Source, t.Schema = existing.Source, existing.Schema
|
||||
if err := eventtype.CheckOverlap(m.types, t); err != nil {
|
||||
return err
|
||||
}
|
||||
m.types[i] = t
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return storecontract.ErrEventTypeNotFound
|
||||
}
|
||||
|
||||
func (m *memEventTypes) DeleteEventType(_ context.Context, id string) error {
|
||||
for i, existing := range m.types {
|
||||
if existing.ID == id {
|
||||
m.types = append(m.types[:i], m.types[i+1:]...)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return storecontract.ErrEventTypeNotFound
|
||||
}
|
||||
|
||||
func (m *memEventTypes) ListEventTypes(context.Context) ([]eventtype.EventType, error) {
|
||||
return m.types, nil
|
||||
}
|
||||
|
||||
func eventTypeServer(captures ...storecontract.CapturedEvent) (*Server, *memEventTypes) {
|
||||
types := &memEventTypes{}
|
||||
return &Server{
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Captures: &memCaptures{list: captures},
|
||||
EventTypes: types,
|
||||
}, types
|
||||
}
|
||||
|
||||
func serve(t *testing.T, srv *Server, method, path, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequestWithContext(t.Context(), method, path, strings.NewReader(body))
|
||||
req.Header.Set("X-Archie-CSRF", "1")
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
type eventTypesView struct {
|
||||
EventTypes []eventtype.EventType `json:"event_types"`
|
||||
Proposals []eventtype.Proposal `json:"proposals"`
|
||||
}
|
||||
|
||||
func listEventTypes(t *testing.T, srv *Server) eventTypesView {
|
||||
t.Helper()
|
||||
w := serve(t, srv, http.MethodGet, "/api/event-types", "")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("GET status = %d; body %s", w.Code, w.Body.String())
|
||||
}
|
||||
var v eventTypesView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func ghCapture(id, event, body string) storecontract.CapturedEvent {
|
||||
return storecontract.CapturedEvent{ID: id, Source: "gh", Headers: `{"X-Github-Event":["` + event + `"]}`, Body: body}
|
||||
}
|
||||
|
||||
// Two GitHub events with different X-GitHub-Event headers are two proposals,
|
||||
// and a firewall payload is a third.
|
||||
func TestEventTypesProposesGroupsFromUnidentifiedCaptures(t *testing.T) {
|
||||
srv, _ := eventTypeServer(
|
||||
ghCapture("c1", "push", `{"ref":"a"}`),
|
||||
ghCapture("c2", "pull_request", `{"action":"opened"}`),
|
||||
storecontract.CapturedEvent{ID: "f1", Source: "fw", Body: `{"src":"1.1.1.1"}`},
|
||||
// Already identified on arrival: not a proposal.
|
||||
func() storecontract.CapturedEvent {
|
||||
c := ghCapture("c3", "issues", `{}`)
|
||||
c.EventType = "et-x"
|
||||
return c
|
||||
}(),
|
||||
)
|
||||
v := listEventTypes(t, srv)
|
||||
var samples []string
|
||||
for _, p := range v.Proposals {
|
||||
samples = append(samples, p.SampleID)
|
||||
}
|
||||
if strings.Join(samples, ",") != "f1,c1,c2" {
|
||||
t.Fatalf("proposal samples = %v, want f1,c1,c2", samples)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventTypeCreateFromProposalRemovesIt(t *testing.T) {
|
||||
srv, types := eventTypeServer(ghCapture("c1", "push", `{"ref":"a"}`), ghCapture("c2", "pull_request", `{"action":"opened"}`))
|
||||
w := serve(t, srv, http.MethodPost, "/api/event-types", `{
|
||||
"source":"gh","name":"push",
|
||||
"rule":{"headers":[{"name":"x-github-event","value":"push"}]},
|
||||
"example":{"headers":{"x-github-event":"push"},"body":"{\"ref\":\"a\"}"}}`)
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("POST status = %d; body %s", w.Code, w.Body.String())
|
||||
}
|
||||
if got := types.types[0].Schema["ref"]; got != eventtype.TypeString {
|
||||
t.Fatalf("schema[ref] = %q, want string", got)
|
||||
}
|
||||
v := listEventTypes(t, srv)
|
||||
if len(v.EventTypes) != 1 || len(v.Proposals) != 1 || v.Proposals[0].SampleID != "c2" {
|
||||
t.Fatalf("after naming push: types %d, proposals %+v", len(v.EventTypes), v.Proposals)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventTypeWriteStatuses(t *testing.T) {
|
||||
srv, _ := eventTypeServer()
|
||||
pasted := `{"source":"gh","name":"%s","example":{"headers":{"X-GitHub-Event":"push"},"body":"{}"}}`
|
||||
tests := []struct {
|
||||
name, method, path, body string
|
||||
want int
|
||||
}{
|
||||
{"create from pasted payload", http.MethodPost, "/api/event-types", strings.Replace(pasted, "%s", "push", 1), http.StatusCreated},
|
||||
{"overlapping type is refused", http.MethodPost, "/api/event-types", strings.Replace(pasted, "%s", "push2", 1), http.StatusConflict},
|
||||
{"nameless type is refused", http.MethodPost, "/api/event-types", strings.Replace(pasted, "%s", "", 1), http.StatusBadRequest},
|
||||
{"bad json", http.MethodPost, "/api/event-types", `{`, http.StatusBadRequest},
|
||||
{"rename", http.MethodPut, "/api/event-types/et-push", `{"name":"pushed","rule":{"headers":[{"name":"X-GitHub-Event","value":"push"}]}}`, http.StatusOK},
|
||||
{"update missing", http.MethodPut, "/api/event-types/nope", `{"name":"x","rule":{}}`, http.StatusNotFound},
|
||||
{"delete", http.MethodDelete, "/api/event-types/et-push", ``, http.StatusNoContent},
|
||||
{"delete missing", http.MethodDelete, "/api/event-types/et-push", ``, http.StatusNotFound},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if w := serve(t, srv, tt.method, tt.path, tt.body); w.Code != tt.want {
|
||||
t.Fatalf("status = %d, want %d; body %s", w.Code, tt.want, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventTypesDisabledWithoutStore(t *testing.T) {
|
||||
srv := &Server{Log: slog.New(slog.DiscardHandler)}
|
||||
w := serve(t, srv, http.MethodGet, "/api/event-types", "")
|
||||
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"enabled":false`) {
|
||||
t.Fatalf("GET without store = %d %s, want 200 with enabled false", w.Code, w.Body.String())
|
||||
}
|
||||
if w := serve(t, srv, http.MethodPost, "/api/event-types", `{}`); w.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("POST without store = %d, want 503", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -1,291 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/websocket"
|
||||
|
||||
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/domain/harnesssecret"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// harnessSecretStub answers the harness store's two methods from a fixed
|
||||
// map keyed "org/service".
|
||||
type harnessSecretStub struct {
|
||||
secrets map[string]harnesssecret.Secret
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *harnessSecretStub) GetHarnessSecret(_ context.Context, orgID, service string) (harnesssecret.Secret, error) {
|
||||
if s.err != nil {
|
||||
return harnesssecret.Secret{}, s.err
|
||||
}
|
||||
if secret, ok := s.secrets[orgID+"/"+service]; ok {
|
||||
return secret, nil
|
||||
}
|
||||
return harnesssecret.Secret{}, storecontract.ErrHarnessSecretNotFound
|
||||
}
|
||||
|
||||
func (s *harnessSecretStub) PutHarnessSecret(context.Context, harnesssecret.Secret) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// pipeTerminal hands the test the far end of a net.Pipe for every session it
|
||||
// opens, so the bridge test can drive both directions without a container.
|
||||
type pipeTerminal struct {
|
||||
peers chan net.Conn
|
||||
}
|
||||
|
||||
func newPipeTerminal() *pipeTerminal { return &pipeTerminal{peers: make(chan net.Conn, 1)} }
|
||||
|
||||
func (p *pipeTerminal) Open(context.Context, string, string) (io.ReadWriteCloser, error) {
|
||||
client, peer := net.Pipe()
|
||||
p.peers <- peer
|
||||
return client, nil
|
||||
}
|
||||
|
||||
type failingTerminal struct{ err error }
|
||||
|
||||
func (f failingTerminal) Open(context.Context, string, string) (io.ReadWriteCloser, error) {
|
||||
return nil, f.err
|
||||
}
|
||||
|
||||
func harnessResources() map[string]*controlpb.Resource {
|
||||
return map[string]*controlpb.Resource{
|
||||
harnessBindingsKind: {Kind: harnessBindingsKind, ValueJson: []byte(
|
||||
`[{"service":"github","secret":{"engine":"env","key":"GH"}},{"service":"linear"}]`,
|
||||
)},
|
||||
harnessProfilesKind: {Kind: harnessProfilesKind, ValueJson: []byte(
|
||||
`{"claude-kit":{"kit":"ghcr.io/x/y@sha256:abc"},"plain":{"image":"x"}}`,
|
||||
)},
|
||||
}
|
||||
}
|
||||
|
||||
// TestHarnessBindingsJoinsCaptureState: the page lists every binding and the
|
||||
// capture state of the ones with a stored token set, and it never carries the
|
||||
// token itself.
|
||||
func TestHarnessBindingsJoinsCaptureState(t *testing.T) {
|
||||
expires := time.Date(2026, 10, 2, 12, 0, 0, 0, time.UTC)
|
||||
updated := expires.Add(-time.Hour)
|
||||
secrets := &harnessSecretStub{secrets: map[string]harnesssecret.Secret{
|
||||
string(org.DefaultOrgID) + "/github": {
|
||||
Org: string(org.DefaultOrgID), Service: "github", AccessToken: "secret-token",
|
||||
ExpiresAt: expires, UpdatedAt: updated, Scopes: []string{"repo", "read:org"},
|
||||
},
|
||||
}}
|
||||
srv := &Server{
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
ControlPlane: &controlPlaneClientStub{resources: harnessResources()},
|
||||
HarnessSecrets: secrets,
|
||||
}
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/harness/bindings", nil)
|
||||
response := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(response, request)
|
||||
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %q", response.Code, response.Body.String())
|
||||
}
|
||||
var got harnessView
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Terminal {
|
||||
t.Error("terminal reported available with no HarnessTerminal wired")
|
||||
}
|
||||
if len(got.Profiles) != 1 || got.Profiles[0] != "claude-kit" {
|
||||
t.Fatalf("profiles = %v, want the Kit profile only", got.Profiles)
|
||||
}
|
||||
if len(got.Bindings) != 2 {
|
||||
t.Fatalf("bindings = %+v", got.Bindings)
|
||||
}
|
||||
github := got.Bindings[0]
|
||||
if github.Service != "github" || !github.Captured || github.ExpiresAt == nil || !github.ExpiresAt.Equal(expires) {
|
||||
t.Fatalf("github binding = %+v", github)
|
||||
}
|
||||
if len(github.Scopes) != 2 || github.Scopes[0] != "repo" {
|
||||
t.Fatalf("scopes = %v", github.Scopes)
|
||||
}
|
||||
if linear := got.Bindings[1]; linear.Service != "linear" || linear.Captured {
|
||||
t.Fatalf("linear binding = %+v, want listed but uncaptured", linear)
|
||||
}
|
||||
// The token must not cross the wire in any form.
|
||||
if body := response.Body.String(); strings.Contains(body, "secret-token") {
|
||||
t.Fatalf("response leaked the access token: %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHarnessBindingsUnavailableWithoutItsContracts: the page needs both the
|
||||
// control-plane resource and the token store; either missing is a 503, never
|
||||
// an empty page that reads as "this org has no bindings".
|
||||
func TestHarnessBindingsUnavailableWithoutItsContracts(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
srv *Server
|
||||
}{
|
||||
{"no control plane", &Server{Log: slog.New(slog.DiscardHandler), HarnessSecrets: &harnessSecretStub{}}},
|
||||
{"no secret store", &Server{Log: slog.New(slog.DiscardHandler), ControlPlane: &controlPlaneClientStub{resources: harnessResources()}}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/harness/bindings", nil)
|
||||
response := httptest.NewRecorder()
|
||||
|
||||
tc.srv.Handler().ServeHTTP(response, request)
|
||||
|
||||
if response.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want 503", response.Code)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestHarnessTerminalUnwiredDegrades503 is the lane's required degrade path:
|
||||
// with no transport for the session, the route answers 503 and the page can
|
||||
// say the terminal is unavailable rather than failing a browser upgrade.
|
||||
func TestHarnessTerminalUnwiredDegrades503(t *testing.T) {
|
||||
srv := &Server{Log: slog.New(slog.DiscardHandler)}
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/harness/terminal?profile=claude-kit", nil)
|
||||
request.Header.Set("Upgrade", "websocket")
|
||||
response := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(response, request)
|
||||
|
||||
if response.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want 503", response.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHarnessTerminalRejectsNonUpgradeAndMissingProfile(t *testing.T) {
|
||||
srv := &Server{Log: slog.New(slog.DiscardHandler), HarnessTerminal: newPipeTerminal()}
|
||||
cases := []struct {
|
||||
name string
|
||||
path string
|
||||
upgrade bool
|
||||
want int
|
||||
}{
|
||||
{"no upgrade", "/api/harness/terminal?profile=claude-kit", false, http.StatusUpgradeRequired},
|
||||
{"no profile", "/api/harness/terminal", true, http.StatusBadRequest},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodGet, tc.path, nil)
|
||||
if tc.upgrade {
|
||||
request.Header.Set("Upgrade", "websocket")
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(response, request)
|
||||
|
||||
if response.Code != tc.want {
|
||||
t.Fatalf("status = %d, want %d", response.Code, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHarnessTerminalOpenFailureIsBadGateway(t *testing.T) {
|
||||
srv := &Server{Log: slog.New(slog.DiscardHandler), HarnessTerminal: failingTerminal{err: errors.New("no daemon")}}
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/harness/terminal?profile=claude-kit", nil)
|
||||
request.Header.Set("Upgrade", "websocket")
|
||||
response := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(response, request)
|
||||
|
||||
if response.Code != http.StatusBadGateway {
|
||||
t.Fatalf("status = %d, want 502", response.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHarnessTerminalBridgesWebSocketToSession proves the upgrade path moves
|
||||
// bytes both ways: the WebSocket is a PTY, so what the browser types reaches
|
||||
// the session and what the session prints reaches the browser.
|
||||
func TestHarnessTerminalBridgesWebSocketToSession(t *testing.T) {
|
||||
terminal := newPipeTerminal()
|
||||
srv := &Server{Log: slog.New(slog.DiscardHandler), HarnessTerminal: terminal}
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
t.Cleanup(ts.Close)
|
||||
|
||||
wsURL := "ws" + strings.TrimPrefix(ts.URL, "http") + "/api/harness/terminal?profile=claude-kit"
|
||||
ws, err := websocket.Dial(wsURL, "", ts.URL)
|
||||
if err != nil {
|
||||
t.Fatalf("dial: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = ws.Close() })
|
||||
|
||||
var peer net.Conn
|
||||
select {
|
||||
case peer = <-terminal.peers:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the handler never opened a session")
|
||||
}
|
||||
t.Cleanup(func() { _ = peer.Close() })
|
||||
|
||||
// Session to browser.
|
||||
go func() { _, _ = peer.Write([]byte("from-session")) }()
|
||||
got := make([]byte, len("from-session"))
|
||||
_ = ws.SetReadDeadline(time.Now().Add(5 * time.Second))
|
||||
if _, err := io.ReadFull(ws, got); err != nil {
|
||||
t.Fatalf("read from websocket: %v", err)
|
||||
}
|
||||
if string(got) != "from-session" {
|
||||
t.Fatalf("websocket read %q", got)
|
||||
}
|
||||
|
||||
// Browser to session.
|
||||
typed := make(chan string, 1)
|
||||
go func() {
|
||||
buf := make([]byte, len("from-browser"))
|
||||
if _, err := io.ReadFull(peer, buf); err != nil {
|
||||
typed <- "ERR:" + err.Error()
|
||||
return
|
||||
}
|
||||
typed <- string(buf)
|
||||
}()
|
||||
if _, err := ws.Write([]byte("from-browser")); err != nil {
|
||||
t.Fatalf("write to websocket: %v", err)
|
||||
}
|
||||
select {
|
||||
case got := <-typed:
|
||||
if got != "from-browser" {
|
||||
t.Fatalf("session read %q", got)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the session never received the browser's input")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHarnessRoutesAuthorizeAsSecretUpdate pins the route mapping the PRD
|
||||
// names: opening the terminal is the update action on the secret, and the
|
||||
// bindings read is a secret read.
|
||||
func TestHarnessRoutesAuthorizeAsSecretUpdate(t *testing.T) {
|
||||
cases := []struct {
|
||||
path string
|
||||
method string
|
||||
want access.Action
|
||||
kind access.ResourceKind
|
||||
}{
|
||||
{"/api/harness/terminal", http.MethodGet, access.ActionUpdate, access.KindSecret},
|
||||
{"/api/harness/bindings", http.MethodGet, access.ActionRead, access.KindSecret},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
request := httptest.NewRequestWithContext(t.Context(), tc.method, tc.path, nil)
|
||||
action, kind, _ := accessRequest(request)
|
||||
if action != tc.want || kind != tc.kind {
|
||||
t.Errorf("%s: got %s/%s, want %s/%s", tc.path, action, kind, tc.want, tc.kind)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/health"
|
||||
)
|
||||
|
||||
type healthProbe struct {
|
||||
name string
|
||||
check func(context.Context) health.Result
|
||||
}
|
||||
|
||||
func (p healthProbe) Name() string { return p.name }
|
||||
func (p healthProbe) Check(ctx context.Context) health.Result { return p.check(ctx) }
|
||||
|
||||
// TestHealthIsReachableWithoutAToken: a liveness probe must be answerable by
|
||||
// local orchestration tooling (systemd, a watchdog, a container healthcheck)
|
||||
// with no dashboard token, mirroring /healthz's precedent.
|
||||
func TestHealthIsReachableWithoutAToken(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.Token = "dashboard-secret"
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/health", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200; body = %q", w.Code, w.Body.String())
|
||||
}
|
||||
if w.Body.String() != "ok" {
|
||||
t.Fatalf("body = %q, want ok", w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestHealthDetailedRequiresToken: the detailed surface exposes real
|
||||
// subsystem state (disk layout, provider reachability) so it must be gated by
|
||||
// the dashboard token, unlike /health.
|
||||
func TestHealthDetailedRequiresToken(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.Token = "dashboard-secret"
|
||||
srv.Health = health.NewRegistry(healthProbe{name: "state_db", check: func(context.Context) health.Result {
|
||||
return health.Result{Status: health.StatusOK}
|
||||
}})
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/health/detailed", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status = %d, want 401", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHealthDetailedReportsRollupAndComponents(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.Token = "dashboard-secret"
|
||||
srv.Health = health.NewRegistry(
|
||||
healthProbe{name: "state_db", check: func(context.Context) health.Result {
|
||||
return health.Result{Status: health.StatusOK}
|
||||
}},
|
||||
healthProbe{name: "disk", check: func(context.Context) health.Result {
|
||||
return health.Result{Status: health.StatusDegraded, Detail: "93% used"}
|
||||
}},
|
||||
)
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/health/detailed", nil)
|
||||
req.Header.Set("Authorization", "Bearer dashboard-secret")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200; body = %q", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
var report health.Report
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &report); err != nil {
|
||||
t.Fatalf("decode report: %v (body %q)", err, w.Body.String())
|
||||
}
|
||||
if report.Status != health.StatusDegraded {
|
||||
t.Fatalf("status = %q, want degraded", report.Status)
|
||||
}
|
||||
if len(report.Components) != 2 {
|
||||
t.Fatalf("components = %d, want 2", len(report.Components))
|
||||
}
|
||||
if report.Components[0].Name != "state_db" || !report.Components[0].Ready {
|
||||
t.Fatalf("state_db component = %+v, want ready", report.Components[0])
|
||||
}
|
||||
if report.Components[1].Name != "disk" || report.Components[1].Ready || report.Components[1].Detail != "93% used" {
|
||||
t.Fatalf("disk component = %+v, want degraded with detail", report.Components[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestHealthDetailedAllOK(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.Token = "dashboard-secret"
|
||||
srv.Health = health.NewRegistry(
|
||||
healthProbe{name: "state_db", check: func(context.Context) health.Result {
|
||||
return health.Result{Status: health.StatusOK}
|
||||
}},
|
||||
healthProbe{name: "config", check: func(context.Context) health.Result {
|
||||
return health.Result{Status: health.StatusOK}
|
||||
}},
|
||||
)
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/health/detailed", nil)
|
||||
req.Header.Set("Authorization", "Bearer dashboard-secret")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
var report health.Report
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &report); err != nil {
|
||||
t.Fatalf("decode report: %v", err)
|
||||
}
|
||||
if report.Status != health.StatusOK {
|
||||
t.Fatalf("status = %q, want ok", report.Status)
|
||||
}
|
||||
for _, c := range report.Components {
|
||||
if !c.Ready {
|
||||
t.Fatalf("component %q not ready, got %+v", c.Name, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestHealthDetailedUnwiredAnswers503: a deployment that has not wired probes
|
||||
// must not report a fabricated healthy state.
|
||||
func TestHealthDetailedUnwiredAnswers503(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.Token = "dashboard-secret"
|
||||
srv.Health = nil
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/health/detailed", nil)
|
||||
req.Header.Set("Authorization", "Bearer dashboard-secret")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want 503", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
)
|
||||
|
||||
func TestLogEndpointsValidateAndBoundLimit(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
const entryCount = logging.MaxTailLines + 1
|
||||
|
||||
daemonLogPath := filepath.Join(t.TempDir(), "archied.log")
|
||||
daemonLog, closer, err := logging.New(logging.Options{File: daemonLogPath})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeLogEntries(daemonLog, entryCount)
|
||||
if err := closer.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv.LogFile = daemonLogPath
|
||||
|
||||
taskLogDir := t.TempDir()
|
||||
srv.TaskLogs = logging.NewTaskRegistry(taskLogDir, nil, logging.TaskSinkOptions{})
|
||||
if _, err := srv.Store.EnqueueIssue(t.Context(), "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(t.Context(), "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
taskSink, err := logging.NewTaskSink(taskLogDir, task.ID, task.Attempt, logging.TaskSinkOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeLogEntries(taskSink.Logger(), entryCount)
|
||||
if err := taskSink.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
endpoints := []struct {
|
||||
name string
|
||||
path string
|
||||
}{
|
||||
{name: "daemon logs", path: "/api/logs"},
|
||||
{name: "task logs", path: "/api/tasks/" + strconv.FormatInt(task.ID, 10) + "/logs"},
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
query string
|
||||
wantStatus int
|
||||
wantEntries int
|
||||
}{
|
||||
{name: "missing uses default", wantStatus: http.StatusOK, wantEntries: logging.DefaultTailLines},
|
||||
{name: "zero uses default", query: "?limit=0", wantStatus: http.StatusOK, wantEntries: logging.DefaultTailLines},
|
||||
{name: "negative uses default", query: "?limit=-1", wantStatus: http.StatusOK, wantEntries: logging.DefaultTailLines},
|
||||
{name: "valid is honored", query: "?limit=3", wantStatus: http.StatusOK, wantEntries: 3},
|
||||
{name: "whitespace is ignored", query: "?limit=%203%20", wantStatus: http.StatusOK, wantEntries: 3},
|
||||
{
|
||||
name: "oversized is clamped",
|
||||
query: "?limit=" + strconv.Itoa(logging.MaxTailLines+1),
|
||||
wantStatus: http.StatusOK,
|
||||
wantEntries: logging.MaxTailLines,
|
||||
},
|
||||
{name: "malformed is rejected", query: "?limit=not-a-number", wantStatus: http.StatusBadRequest},
|
||||
{name: "integer overflow is rejected", query: "?limit=999999999999999999999999", wantStatus: http.StatusBadRequest},
|
||||
}
|
||||
|
||||
for _, endpoint := range endpoints {
|
||||
t.Run(endpoint.name, func(t *testing.T) {
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, endpoint.path+tt.query, nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != tt.wantStatus {
|
||||
t.Fatalf("status = %d, want %d", w.Code, tt.wantStatus)
|
||||
}
|
||||
if tt.wantStatus != http.StatusOK {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Entries []logging.Entry `json:"entries"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if len(body.Entries) != tt.wantEntries {
|
||||
t.Errorf("entries = %d, want %d", len(body.Entries), tt.wantEntries)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func writeLogEntries(log *slog.Logger, count int) {
|
||||
for i := range count {
|
||||
log.Info("entry", "index", i)
|
||||
}
|
||||
}
|
||||
@@ -1,366 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"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"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// mappingTestServer builds a Server with both Mappings and Captures backed
|
||||
// by the same concrete *pgstore.TaskDB, so preview tests can insert a real
|
||||
// capture and resolve a mapping against it end to end.
|
||||
func mappingTestServer(t *testing.T) *Server {
|
||||
t.Helper()
|
||||
s := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
eda := pgstore.EDA(t, nil)
|
||||
return &Server{
|
||||
Store: s,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Mappings: eda,
|
||||
Captures: eda,
|
||||
EventTypes: testEventTypes(),
|
||||
}
|
||||
}
|
||||
|
||||
// testEventTypes holds one event type, et-1, whose schema has every path the
|
||||
// mapping tests write.
|
||||
func testEventTypes() *memEventTypes {
|
||||
return &memEventTypes{types: []eventtype.EventType{{
|
||||
ID: "et-1", Source: "sentry", Name: "issue",
|
||||
Schema: map[string]eventtype.ValueType{
|
||||
"a": eventtype.TypeString, "b": eventtype.TypeBool,
|
||||
"issue": eventtype.TypeObject, "issue.title": eventtype.TypeString,
|
||||
},
|
||||
}}}
|
||||
}
|
||||
|
||||
// A mapping belongs to an event type and is checked against its schema.
|
||||
func TestHandleMappingSaveChecksEventTypeSchema(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
eventType string
|
||||
path string
|
||||
fieldType mapping.FieldType
|
||||
want int
|
||||
}{
|
||||
{"fits the schema", "et-1", "issue.title", mapping.TypeString, http.StatusCreated},
|
||||
{"no event type", "", "issue.title", mapping.TypeString, http.StatusBadRequest},
|
||||
{"unknown event type", "et-9", "issue.title", mapping.TypeString, http.StatusBadRequest},
|
||||
{"path the type does not have", "et-1", "sender.login", mapping.TypeString, http.StatusBadRequest},
|
||||
{"type differs from the schema", "et-1", "issue.title", mapping.TypeNumber, http.StatusBadRequest},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
req := map[string]any{
|
||||
"name": "m",
|
||||
"event_type_id": tt.eventType,
|
||||
"fields": []mapping.Field{{Name: "f", Path: tt.path, Type: tt.fieldType}},
|
||||
}
|
||||
if w := doJSON(t, srv, http.MethodPost, "/api/mappings", req); w.Code != tt.want {
|
||||
t.Fatalf("create status = %d, want %d; body = %s", w.Code, tt.want, w.Body.String())
|
||||
}
|
||||
ok := doJSON(t, srv, http.MethodPost, "/api/mappings", map[string]any{
|
||||
"name": "base", "event_type_id": "et-1",
|
||||
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
|
||||
})
|
||||
var created mapping.Mapping
|
||||
_ = json.Unmarshal(ok.Body.Bytes(), &created)
|
||||
want := tt.want
|
||||
if want == http.StatusCreated {
|
||||
want = http.StatusOK
|
||||
}
|
||||
if w := doJSON(t, srv, http.MethodPatch, "/api/mappings/"+created.ID, req); w.Code != want {
|
||||
t.Fatalf("update status = %d, want %d; body = %s", w.Code, want, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// doJSON issues a request carrying the browser mutation headers
|
||||
// (Content-Type, X-Archie-CSRF) every write handler requires via
|
||||
// authorizeTaskMutation, so GET/POST/PATCH/DELETE calls in this package's
|
||||
// tests exercise the handler logic rather than the CSRF gate. Use
|
||||
// doJSONNoCSRF to test the gate itself.
|
||||
func doJSON(t *testing.T, srv *Server, method, path string, body any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
return doJSONWithHeaders(t, srv, method, path, body, true)
|
||||
}
|
||||
|
||||
// doJSONNoCSRF is doJSON without the X-Archie-CSRF header, for asserting
|
||||
// that a mutation handler refuses an unmarked cross-origin-shaped request.
|
||||
func doJSONNoCSRF(t *testing.T, srv *Server, method, path string, body any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
return doJSONWithHeaders(t, srv, method, path, body, false)
|
||||
}
|
||||
|
||||
func doJSONWithHeaders(t *testing.T, srv *Server, method, path string, body any, csrf bool) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
var r *http.Request
|
||||
if body != nil {
|
||||
b, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal request body: %v", err)
|
||||
}
|
||||
r = httptest.NewRequestWithContext(t.Context(), method, path, bytes.NewReader(b))
|
||||
} else {
|
||||
r = httptest.NewRequestWithContext(t.Context(), method, path, nil)
|
||||
}
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
if csrf {
|
||||
r.Header.Set("X-Archie-CSRF", "1")
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
|
||||
func TestHandleMappingCreateAndGet(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/mappings", map[string]any{
|
||||
"name": "sentry issue opened",
|
||||
"source_hint": "sentry",
|
||||
"event_type_id": "et-1",
|
||||
"fields": []mapping.Field{
|
||||
{Name: "title", Path: "issue.title", Type: mapping.TypeString, Required: true},
|
||||
},
|
||||
})
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("create status = %d, want %d; body = %s", w.Code, http.StatusCreated, w.Body.String())
|
||||
}
|
||||
var created mapping.Mapping
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil {
|
||||
t.Fatalf("unmarshal created mapping: %v", err)
|
||||
}
|
||||
if created.ID == "" || created.Name != "sentry issue opened" {
|
||||
t.Fatalf("created mapping = %+v", created)
|
||||
}
|
||||
|
||||
w = doJSON(t, srv, http.MethodGet, "/api/mappings/"+created.ID, nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("get status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
var got mapping.Mapping
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("unmarshal got mapping: %v", err)
|
||||
}
|
||||
if got.ID != created.ID || len(got.Fields) != 1 {
|
||||
t.Fatalf("got mapping = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMappingCreateRejectsInvalidMapping(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/mappings", map[string]any{"name": "", "fields": []mapping.Field{}})
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusBadRequest, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMappingGetMissingReturns404(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
w := doJSON(t, srv, http.MethodGet, "/api/mappings/999", nil)
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want %d", w.Code, http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMappingsList(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
for range 3 {
|
||||
doJSON(t, srv, http.MethodPost, "/api/mappings", map[string]any{
|
||||
"name": "m",
|
||||
"event_type_id": "et-1",
|
||||
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
|
||||
})
|
||||
}
|
||||
w := doJSON(t, srv, http.MethodGet, "/api/mappings", nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
var body struct {
|
||||
Mappings []mapping.Mapping `json:"mappings"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if len(body.Mappings) != 3 {
|
||||
t.Fatalf("mappings = %d, want 3", len(body.Mappings))
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMappingUpdate(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/mappings", map[string]any{
|
||||
"name": "orig",
|
||||
"event_type_id": "et-1",
|
||||
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
|
||||
})
|
||||
var created mapping.Mapping
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &created)
|
||||
|
||||
w = doJSON(t, srv, http.MethodPatch, "/api/mappings/"+created.ID, map[string]any{
|
||||
"name": "renamed",
|
||||
"event_type_id": "et-1",
|
||||
"fields": []mapping.Field{{Name: "b", Path: "b", Type: mapping.TypeBool}},
|
||||
})
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("update status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
|
||||
w = doJSON(t, srv, http.MethodGet, "/api/mappings/"+created.ID, nil)
|
||||
var got mapping.Mapping
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &got)
|
||||
if got.Name != "renamed" || len(got.Fields) != 1 || got.Fields[0].Name != "b" {
|
||||
t.Fatalf("updated mapping = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMappingUpdateMissingReturns404(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
w := doJSON(t, srv, http.MethodPatch, "/api/mappings/999", map[string]any{
|
||||
"name": "x",
|
||||
"event_type_id": "et-1",
|
||||
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
|
||||
})
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusNotFound, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMappingDelete(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/mappings", map[string]any{
|
||||
"name": "m",
|
||||
"event_type_id": "et-1",
|
||||
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
|
||||
})
|
||||
var created mapping.Mapping
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &created)
|
||||
|
||||
w = doJSON(t, srv, http.MethodDelete, "/api/mappings/"+created.ID, nil)
|
||||
if w.Code != http.StatusNoContent {
|
||||
t.Fatalf("delete status = %d, want %d; body = %s", w.Code, http.StatusNoContent, w.Body.String())
|
||||
}
|
||||
w = doJSON(t, srv, http.MethodGet, "/api/mappings/"+created.ID, nil)
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("get after delete status = %d, want %d", w.Code, http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMappingPreviewResolvesAgainstARealCapture(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
capID, err := srv.Captures.InsertCapture(t.Context(), storecontract.CapturedEvent{
|
||||
Source: "sentry",
|
||||
Body: `{"issue":{"title":"bug found"},"count":3}`,
|
||||
}, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("InsertCapture: %v", err)
|
||||
}
|
||||
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/mappings/preview", map[string]any{
|
||||
"capture_id": capID,
|
||||
"fields": []mapping.Field{
|
||||
{Name: "title", Path: "issue.title", Type: mapping.TypeString, Required: true},
|
||||
{Name: "missing", Path: "nope", Type: mapping.TypeString, Required: true},
|
||||
},
|
||||
})
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("preview status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
var body struct {
|
||||
Values map[string]any `json:"values"`
|
||||
Failures []mapping.Failure `json:"failures"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if body.Values["title"] != "bug found" {
|
||||
t.Fatalf("values = %+v", body.Values)
|
||||
}
|
||||
if len(body.Failures) != 1 || body.Failures[0].FieldName != "missing" || body.Failures[0].Reason != mapping.ReasonMissing {
|
||||
t.Fatalf("failures = %+v", body.Failures)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMappingPreviewUnknownCaptureReturns404(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/mappings/preview", map[string]any{
|
||||
"capture_id": "rabsent00000000",
|
||||
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
|
||||
})
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusNotFound, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestMappingCaptureScanWindowUsesConfiguredCaptureMaxEvents(t *testing.T) {
|
||||
if got := mappingCaptureScanWindow(20000); got != 20000 {
|
||||
t.Errorf("mappingCaptureScanWindow(20000) = %d, want 20000", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMappingCaptureScanWindowFallsBackWhenUnconfigured(t *testing.T) {
|
||||
if got := mappingCaptureScanWindow(0); got != captureScanWindowDefault {
|
||||
t.Errorf("mappingCaptureScanWindow(0) = %d, want default %d", got, captureScanWindowDefault)
|
||||
}
|
||||
if got := mappingCaptureScanWindow(-1); got != captureScanWindowDefault {
|
||||
t.Errorf("mappingCaptureScanWindow(-1) = %d, want default %d", got, captureScanWindowDefault)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMappingsUnavailableWhenNotConfigured(t *testing.T) {
|
||||
srv := &Server{Store: nil, Log: slog.New(slog.DiscardHandler)}
|
||||
w := doJSON(t, srv, http.MethodGet, "/api/mappings", nil)
|
||||
if w.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want %d", w.Code, http.StatusServiceUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleMappingMutationsRequireCSRFHeader mirrors
|
||||
// TestHandleBindingMutationsRequireCSRFHeader: every mapping write handler
|
||||
// must enforce the same browser mutation contract as handleTaskAction
|
||||
// (docs/prds/dynamic-curators.md), not just bindings.
|
||||
func TestHandleMappingMutationsRequireCSRFHeader(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
newMapping := map[string]any{
|
||||
"name": "sentry issue opened",
|
||||
"source_hint": "sentry",
|
||||
"event_type_id": "et-1",
|
||||
"fields": []mapping.Field{
|
||||
{Name: "title", Path: "issue.title", Type: mapping.TypeString, Required: true},
|
||||
},
|
||||
}
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/mappings", newMapping)
|
||||
var created mapping.Mapping
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil {
|
||||
t.Fatalf("unmarshal created mapping: %v; body = %s", err, w.Body.String())
|
||||
}
|
||||
id := created.ID
|
||||
|
||||
tests := []struct {
|
||||
name, method, path string
|
||||
body any
|
||||
}{
|
||||
{"create", http.MethodPost, "/api/mappings", newMapping},
|
||||
{"update", http.MethodPatch, "/api/mappings/" + id, newMapping},
|
||||
{"delete", http.MethodDelete, "/api/mappings/" + id, nil},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
w := doJSONNoCSRF(t, srv, tc.method, tc.path, tc.body)
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("status = %d, want %d without a CSRF header; body = %s", w.Code, http.StatusForbidden, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,220 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
// TestSetupChecklistRendersFromTheProjection: the checklist is derived from
|
||||
// the configuration projection, so it works in a process that holds no
|
||||
// configuration of its own. It reported nothing there while it read a live
|
||||
// holder, which the extracted dashboard never receives (archie-core-ml30).
|
||||
func TestSetupChecklistRendersFromTheProjection(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
cfg config.Config
|
||||
wantOperator string
|
||||
wantDone map[string]bool
|
||||
}{
|
||||
{
|
||||
name: "nothing configured yet",
|
||||
cfg: config.Config{},
|
||||
wantDone: map[string]bool{
|
||||
"Give Archie an identity": false,
|
||||
"Connect a repository": false,
|
||||
"Connect a chat channel": false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "identity, repository and a telegram token",
|
||||
cfg: config.Config{
|
||||
BotUser: "archie-bot",
|
||||
Repos: []config.Repo{{Owner: "acme", Name: "widget"}},
|
||||
Chat: config.ChatConfig{
|
||||
Operator: "Sam",
|
||||
Telegram: config.TelegramConfig{Token: config.SecretRef{Engine: "env", Key: "TELEGRAM_TOKEN"}},
|
||||
},
|
||||
},
|
||||
wantOperator: "Sam",
|
||||
wantDone: map[string]bool{
|
||||
"Give Archie an identity": true,
|
||||
"Connect a repository": true,
|
||||
"Connect a chat channel": true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "a webhook address counts as a channel",
|
||||
cfg: config.Config{
|
||||
Chat: config.ChatConfig{WebhookAddr: "127.0.0.1:9099"},
|
||||
},
|
||||
wantDone: map[string]bool{
|
||||
"Give Archie an identity": false,
|
||||
"Connect a repository": false,
|
||||
"Connect a chat channel": true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
// Round-tripped through the published document, which is how
|
||||
// the dashboard actually receives it.
|
||||
published := BuildConfigView(ConfigViewInput{Config: tc.cfg})
|
||||
document, err := json.Marshal(published)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv.ConfigSource = func(context.Context) (ConfigView, bool, error) {
|
||||
var view ConfigView
|
||||
if err := json.Unmarshal(document, &view); err != nil {
|
||||
return ConfigView{}, false, err
|
||||
}
|
||||
return view, true, nil
|
||||
}
|
||||
|
||||
got := getSetup(t, srv)
|
||||
if got.Operator != tc.wantOperator {
|
||||
t.Errorf("operator = %q, want %q", got.Operator, tc.wantOperator)
|
||||
}
|
||||
done := map[string]bool{}
|
||||
for _, step := range got.Steps {
|
||||
done[step.Title] = step.Done
|
||||
}
|
||||
for title, want := range tc.wantDone {
|
||||
if done[title] != want {
|
||||
t.Errorf("step %q done = %v, want %v", title, done[title], want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetupChecklistChatChannelStepCountsEveryFrontEnd: the checklist's
|
||||
// "Connect a chat channel" step asks whether ANY conversational front-end is
|
||||
// configured, so the projection it reads has to answer that question for every
|
||||
// front-end the daemon serves. The daemon's own channel inventory lists three
|
||||
// (telegram, the webhook gateway and the inbound mail gateway -- see
|
||||
// bootstrap.go's status.NewManager), and an email-only deployment is a
|
||||
// configured deployment: the mail gateway feeds the same gateway.Router as the
|
||||
// other two. Deriving the answer from two of the three told an email operator
|
||||
// to connect a channel they already had.
|
||||
func TestSetupChecklistChatChannelStepCountsEveryFrontEnd(t *testing.T) {
|
||||
const stepTitle = "Connect a chat channel"
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
cfg config.Config
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "nothing configured",
|
||||
cfg: config.Config{},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "telegram token env",
|
||||
cfg: config.Config{Chat: config.ChatConfig{
|
||||
Telegram: config.TelegramConfig{Token: config.SecretRef{Engine: "env", Key: "TELEGRAM_TOKEN"}},
|
||||
}},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "telegram token through the secret engine",
|
||||
cfg: config.Config{Chat: config.ChatConfig{
|
||||
Telegram: config.TelegramConfig{Token: config.SecretRef{Engine: "builtin", Key: "telegram"}},
|
||||
}},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "webhook gateway",
|
||||
cfg: config.Config{Chat: config.ChatConfig{
|
||||
WebhookAddr: "127.0.0.1:9099",
|
||||
}},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "inbound mail gateway",
|
||||
cfg: config.Config{Chat: config.ChatConfig{
|
||||
Email: config.EmailConfig{ListenAddr: "127.0.0.1:2525"},
|
||||
}},
|
||||
want: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.ConfigSource = publishedSource(t, tc.cfg)
|
||||
|
||||
got := getSetup(t, srv)
|
||||
found := false
|
||||
for _, step := range got.Steps {
|
||||
if step.Title != stepTitle {
|
||||
continue
|
||||
}
|
||||
found = true
|
||||
if step.Done != tc.want {
|
||||
t.Errorf("step %q done = %v, want %v (config: %+v)", stepTitle, step.Done, tc.want, tc.cfg.Chat)
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("no %q step in %+v", stepTitle, got.Steps)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// publishedSource renders cfg the way the daemon does -- through
|
||||
// webui.BuildConfigView -- and hands the server the marshalled document, which
|
||||
// is how the reading process actually receives it. Rendering here rather than
|
||||
// hand-writing a ConfigView keeps these tests honest about the producer: a
|
||||
// field BuildConfigView forgets is one the dashboard cannot see.
|
||||
func publishedSource(t *testing.T, cfg config.Config) ConfigViewSource {
|
||||
t.Helper()
|
||||
document, err := json.Marshal(BuildConfigView(ConfigViewInput{Config: cfg}))
|
||||
if err != nil {
|
||||
t.Fatalf("render the published projection: %v", err)
|
||||
}
|
||||
return func(context.Context) (ConfigView, bool, error) {
|
||||
var view ConfigView
|
||||
if err := json.Unmarshal(document, &view); err != nil {
|
||||
return ConfigView{}, false, err
|
||||
}
|
||||
return view, true, nil
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetupChecklistOmittedWithoutAProjection: no configuration to read means
|
||||
// the panel is omitted, not guessed at from zeroes.
|
||||
func TestSetupChecklistOmittedWithoutAProjection(t *testing.T) {
|
||||
got := getSetup(t, newTestServer(t))
|
||||
if len(got.Steps) != 0 {
|
||||
t.Errorf("steps = %+v, want none without a configuration projection", got.Steps)
|
||||
}
|
||||
}
|
||||
|
||||
type setupResponse struct {
|
||||
Steps []SetupStep `json:"steps"`
|
||||
Operator string `json:"operator"`
|
||||
}
|
||||
|
||||
func getSetup(t *testing.T, srv *Server) setupResponse {
|
||||
t.Helper()
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/setup", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("GET /api/setup = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
var got setupResponse
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
@@ -1,201 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// memSources is an in-memory SourceStore with the store's error contract.
|
||||
type memSources map[string]source.Source
|
||||
|
||||
func (m memSources) InsertSource(_ context.Context, s source.Source) error {
|
||||
if _, ok := m[s.Path]; ok {
|
||||
return storecontract.ErrSourcePathTaken
|
||||
}
|
||||
m[s.Path] = s
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m memSources) GetSource(_ context.Context, path string) (*source.Source, error) {
|
||||
s, ok := m[path]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return &s, nil
|
||||
}
|
||||
|
||||
func (m memSources) ListSources(context.Context) ([]source.Source, error) {
|
||||
out := make([]source.Source, 0, len(m))
|
||||
for _, s := range m {
|
||||
out = append(out, s)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (m memSources) SetSourceSigning(_ context.Context, path string, from, to source.Signing) error {
|
||||
s, ok := m[path]
|
||||
switch {
|
||||
case !ok:
|
||||
return storecontract.ErrSourceNotFound
|
||||
case s.Signing != from:
|
||||
return storecontract.ErrSourceSigningStale
|
||||
}
|
||||
s.Signing = to
|
||||
m[path] = s
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m memSources) SetSourceSecret(_ context.Context, path, secret string) error {
|
||||
s, ok := m[path]
|
||||
if !ok {
|
||||
return storecontract.ErrSourceNotFound
|
||||
}
|
||||
s.Secret = secret
|
||||
m[path] = s
|
||||
return nil
|
||||
}
|
||||
|
||||
func sourceTestServer(t *testing.T) (*Server, memSources) {
|
||||
t.Helper()
|
||||
srv := bindingTestServer(t)
|
||||
sources := memSources{}
|
||||
srv.Sources = sources
|
||||
return srv, sources
|
||||
}
|
||||
|
||||
func decodeSource(t *testing.T, body []byte) source.Source {
|
||||
t.Helper()
|
||||
var s source.Source
|
||||
if err := json.Unmarshal(body, &s); err != nil {
|
||||
t.Fatalf("unmarshal source: %v; body = %s", err, body)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func TestSourceCreateDefaultsToSignedUUIDv7AndShowsSecretOnce(t *testing.T) {
|
||||
srv, _ := sourceTestServer(t)
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/sources", map[string]any{})
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("create status = %d; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
created := decodeSource(t, w.Body.Bytes())
|
||||
if id, err := uuid.Parse(created.Path); err != nil || id.Version() != 7 {
|
||||
t.Fatalf("path %q is not a UUIDv7 (%v)", created.Path, err)
|
||||
}
|
||||
if created.Signing != source.SigningSigned || len(created.Secret) != source.MinSecretLen {
|
||||
t.Fatalf("created = %+v, want signed with a generated secret shown once", created)
|
||||
}
|
||||
|
||||
w = doJSON(t, srv, http.MethodGet, "/api/sources", nil)
|
||||
if w.Code != http.StatusOK || strings.Contains(w.Body.String(), created.Secret) || strings.Contains(w.Body.String(), `"secret"`) {
|
||||
t.Fatalf("list = %d %s; want the secret withheld", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceCreateRefusesTakenOrUnsafePath(t *testing.T) {
|
||||
srv, _ := sourceTestServer(t)
|
||||
if w := doJSON(t, srv, http.MethodPost, "/api/sources", map[string]any{"path": "sentry"}); w.Code != http.StatusCreated {
|
||||
t.Fatalf("first create = %d; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
tests := []struct {
|
||||
path string
|
||||
want int
|
||||
}{
|
||||
{"sentry", http.StatusConflict},
|
||||
{"a/b", http.StatusBadRequest},
|
||||
{"has space", http.StatusBadRequest},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if w := doJSON(t, srv, http.MethodPost, "/api/sources", map[string]any{"path": tt.path}); w.Code != tt.want {
|
||||
t.Errorf("create %q = %d, want %d; body = %s", tt.path, w.Code, tt.want, w.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceUnsignedNeedsApproval(t *testing.T) {
|
||||
srv, sources := sourceTestServer(t)
|
||||
sources["fw"] = source.Source{Path: "fw", Signing: source.SigningSigned, Secret: "k"}
|
||||
steps := []struct {
|
||||
name, path string
|
||||
body any
|
||||
code int
|
||||
want source.Signing
|
||||
}{
|
||||
{"approve with no request", "/api/sources/fw/approve-unsigned", nil, http.StatusConflict, source.SigningSigned},
|
||||
{"request unsigned", "/api/sources/fw/signing", map[string]any{"signed": false}, http.StatusOK, source.SigningUnsignedPending},
|
||||
{"approve", "/api/sources/fw/approve-unsigned", nil, http.StatusOK, source.SigningUnsigned},
|
||||
{"approve twice", "/api/sources/fw/approve-unsigned", nil, http.StatusConflict, source.SigningUnsigned},
|
||||
{"sign again", "/api/sources/fw/signing", map[string]any{"signed": true}, http.StatusOK, source.SigningSigned},
|
||||
{"unknown source", "/api/sources/nope/signing", map[string]any{"signed": false}, http.StatusNotFound, source.SigningSigned},
|
||||
}
|
||||
for _, st := range steps {
|
||||
w := doJSON(t, srv, http.MethodPost, st.path, st.body)
|
||||
if w.Code != st.code {
|
||||
t.Fatalf("%s: status = %d, want %d; body = %s", st.name, w.Code, st.code, w.Body.String())
|
||||
}
|
||||
if got := sources["fw"].Signing; got != st.want {
|
||||
t.Fatalf("%s: signing = %q, want %q", st.name, got, st.want)
|
||||
}
|
||||
if strings.Contains(w.Body.String(), `"secret"`) {
|
||||
t.Fatalf("%s: response leaked the secret: %s", st.name, w.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceRegenerateSecret(t *testing.T) {
|
||||
srv, sources := sourceTestServer(t)
|
||||
sources["fw"] = source.Source{Path: "fw", Signing: source.SigningSigned}
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/sources/fw/secret", nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
got := decodeSource(t, w.Body.Bytes())
|
||||
if len(got.Secret) != source.MinSecretLen || sources["fw"].Secret != got.Secret {
|
||||
t.Fatalf("secret = %q (stored %q), want a new stored secret shown once", got.Secret, sources["fw"].Secret)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceMutationsRequireCSRFHeader(t *testing.T) {
|
||||
srv, sources := sourceTestServer(t)
|
||||
sources["fw"] = source.Source{Path: "fw", Signing: source.SigningUnsignedPending}
|
||||
for _, path := range []string{"/api/sources", "/api/sources/fw/signing", "/api/sources/fw/approve-unsigned", "/api/sources/fw/secret"} {
|
||||
if w := doJSONNoCSRF(t, srv, http.MethodPost, path, map[string]any{}); w.Code != http.StatusForbidden {
|
||||
t.Errorf("%s without CSRF = %d, want %d", path, w.Code, http.StatusForbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBindingListMarksUnsignedSources(t *testing.T) {
|
||||
srv, sources := sourceTestServer(t)
|
||||
sources["fw"] = source.Source{Path: "fw", Signing: source.SigningUnsigned}
|
||||
sources["sentry"] = source.Source{Path: "sentry", Signing: source.SigningSigned}
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
for _, src := range []string{"fw", "sentry"} {
|
||||
if w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest(src, src, mappingID)); w.Code != http.StatusCreated {
|
||||
t.Fatalf("create binding = %d; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
w := doJSON(t, srv, http.MethodGet, "/api/bindings", nil)
|
||||
var body struct {
|
||||
Bindings []struct {
|
||||
Matcher struct{ Source string } `json:"matcher"`
|
||||
Unsigned bool `json:"unsigned"`
|
||||
} `json:"bindings"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || len(body.Bindings) != 2 {
|
||||
t.Fatalf("list = %s (%v)", w.Body.String(), err)
|
||||
}
|
||||
for _, b := range body.Bindings {
|
||||
if want := b.Matcher.Source == "fw"; b.Unsigned != want {
|
||||
t.Errorf("binding on %q unsigned = %v, want %v", b.Matcher.Source, b.Unsigned, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
)
|
||||
|
||||
// The dashboard derives everything it can present from /api/task-meta. If the
|
||||
// catalog is empty or malformed the frontend falls back to its own defaults and
|
||||
// the whole point of the endpoint -- one server-held vocabulary -- is lost.
|
||||
func TestTaskMetaCatalog(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/task-meta", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
|
||||
var got struct {
|
||||
Statuses []struct {
|
||||
ID string `json:"id"`
|
||||
Label string `json:"label"`
|
||||
Kind string `json:"kind"`
|
||||
NeedsYou bool `json:"needs_you"`
|
||||
} `json:"statuses"`
|
||||
Actions []struct {
|
||||
ID string `json:"id"`
|
||||
Label string `json:"label"`
|
||||
Kind string `json:"kind"`
|
||||
Confirm string `json:"confirm"`
|
||||
} `json:"actions"`
|
||||
RetryModes []struct {
|
||||
ID string `json:"id"`
|
||||
Label string `json:"label"`
|
||||
Description string `json:"description"`
|
||||
Default bool `json:"default"`
|
||||
RequiresBranch bool `json:"requires_branch"`
|
||||
} `json:"retry_modes"`
|
||||
ChangeStatuses []struct {
|
||||
ID string `json:"id"`
|
||||
Label string `json:"label"`
|
||||
} `json:"change_statuses"`
|
||||
ConfigSchema string `json:"config_schema"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
|
||||
if len(got.Statuses) == 0 {
|
||||
t.Error("statuses empty")
|
||||
}
|
||||
if len(got.Actions) == 0 {
|
||||
t.Error("actions empty")
|
||||
}
|
||||
if len(got.RetryModes) == 0 {
|
||||
t.Error("retry_modes empty; the retry dialog would offer no mode")
|
||||
}
|
||||
defaults := 0
|
||||
for _, m := range got.RetryModes {
|
||||
if m.ID == "" || m.Label == "" || m.Description == "" {
|
||||
t.Errorf("retry mode missing id/label/description: %+v", m)
|
||||
}
|
||||
if m.Default {
|
||||
defaults++
|
||||
}
|
||||
}
|
||||
if defaults != 1 {
|
||||
t.Errorf("retry_modes has %d defaults, want exactly 1", defaults)
|
||||
}
|
||||
if len(got.ChangeStatuses) == 0 {
|
||||
t.Error("change_statuses empty; the dashboard renders raw status codes without it")
|
||||
}
|
||||
if got.ConfigSchema == "" {
|
||||
t.Error("config_schema empty; the config panel would call every capture an unknown schema")
|
||||
}
|
||||
for _, s := range got.Statuses {
|
||||
if s.ID == "" || s.Label == "" {
|
||||
t.Errorf("status missing id/label: %+v", s)
|
||||
}
|
||||
}
|
||||
for _, a := range got.Actions {
|
||||
if a.ID == "" || a.Label == "" {
|
||||
t.Errorf("action missing id/label: %+v", a)
|
||||
}
|
||||
}
|
||||
for _, cs := range got.ChangeStatuses {
|
||||
if cs.ID == "" || cs.Label == "" {
|
||||
t.Errorf("change status missing id/label: %+v", cs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestTaskMetaChangeStatusesAreDeliberate pins the catalog's change-status IDs
|
||||
// to the producer's constants, in order, each with a distinct label. It is the
|
||||
// same guard config_schema_test.go applies to the config catalog: a sixth
|
||||
// Change* constant added without a label fails here rather than reaching the
|
||||
// dashboard as a raw status code.
|
||||
func TestTaskMetaChangeStatusesAreDeliberate(t *testing.T) {
|
||||
want := []string{
|
||||
task.ChangeAdded,
|
||||
task.ChangeModified,
|
||||
task.ChangeDeleted,
|
||||
task.ChangeRenamed,
|
||||
task.ChangeTypeChanged,
|
||||
}
|
||||
got := buildTaskMeta().ChangeStatuses
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("change_statuses has %d entries, want %d (one per Change* constant)", len(got), len(want))
|
||||
}
|
||||
labels := make(map[string]string, len(got))
|
||||
for i, cs := range got {
|
||||
if cs.ID != want[i] {
|
||||
t.Errorf("change_statuses[%d].id = %q, want %q", i, cs.ID, want[i])
|
||||
}
|
||||
if cs.Label == "" {
|
||||
t.Errorf("change status %q has no label", cs.ID)
|
||||
continue
|
||||
}
|
||||
if prev, dup := labels[cs.Label]; dup {
|
||||
t.Errorf("change statuses %q and %q share the label %q", prev, cs.ID, cs.Label)
|
||||
}
|
||||
labels[cs.Label] = cs.ID
|
||||
}
|
||||
}
|
||||
@@ -1,944 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
taskactionstore "github.com/samcharles93/archie-core/internal/infrastructure/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate/taskstatetest"
|
||||
)
|
||||
|
||||
// recordingCloser captures the forge issue-closure calls an action makes.
|
||||
type recordingCloser struct {
|
||||
calls []closeCall
|
||||
err error
|
||||
}
|
||||
|
||||
type closeCall struct {
|
||||
owner, repo string
|
||||
number int
|
||||
comment string
|
||||
}
|
||||
|
||||
func (r *recordingCloser) CloseIssue(_ context.Context, owner, repo string, number int, comment string) error {
|
||||
r.calls = append(r.calls, closeCall{owner, repo, number, comment})
|
||||
return r.err
|
||||
}
|
||||
|
||||
// daemonActions stands in for the daemon behind the Gateway contract. The
|
||||
// dashboard no longer composes a task-action service of its own: it asks
|
||||
// whoever owns task execution, reaching the same taskactions.Service over
|
||||
// gRPC and NATS in production (internal/infrastructure/taskactions). Running
|
||||
// that service directly here keeps these tests on real behaviour -- retry
|
||||
// limits, forge closure, timeline events, archiving -- rather than on a stub
|
||||
// that would agree with any handler.
|
||||
//
|
||||
// The service is rebuilt per call because tests attach collaborators after
|
||||
// the server exists, exactly as the daemon rebuilds it per request.
|
||||
type daemonActions struct {
|
||||
srv *Server
|
||||
// cfg is the daemon's configuration, held by the stand-in daemon
|
||||
// rather than by the dashboard: retry caps are the task owner's
|
||||
// policy and the dashboard does not hold configuration.
|
||||
cfg *config.Holder
|
||||
// logs is the daemon's own task-log registry. Archiving removes a
|
||||
// task's log files, and that is the daemon's cleanup over the state
|
||||
// directory it owns -- the dashboard reads logs through a contract and
|
||||
// has no directory to remove anything from.
|
||||
logs *logging.TaskRegistry
|
||||
issues *recordingCloser
|
||||
stopper *recordingTaskStopper
|
||||
// scopes records the identity each action arrived with, one per call.
|
||||
scopes []*string
|
||||
}
|
||||
|
||||
func (d *daemonActions) ApplyChatTaskAction(
|
||||
ctx context.Context, identity *string, actor taskactions.Actor, id int64, action taskstate.Action, res taskactions.ActionPayload,
|
||||
) (gateway.TaskActionResult, error) {
|
||||
d.scopes = append(d.scopes, identity)
|
||||
service := taskactionstore.NewService(
|
||||
taskactionstore.Store{TaskStore: d.srv.Store},
|
||||
taskactionstore.MaxRetries(d.cfg),
|
||||
d.cancelTask(),
|
||||
d.closeIssue(),
|
||||
d.removeLogs(),
|
||||
nil,
|
||||
d.publish(),
|
||||
d.srv.logf,
|
||||
)
|
||||
if err := service.Apply(ctx, identity, actor, id, action, res); err != nil {
|
||||
return gateway.TaskActionResult{}, err
|
||||
}
|
||||
return gateway.TaskActionResult{TaskID: id, Action: string(action)}, nil
|
||||
}
|
||||
|
||||
func (d *daemonActions) cancelTask() func(int64) bool {
|
||||
if d.stopper == nil {
|
||||
return nil
|
||||
}
|
||||
return d.stopper.CancelTask
|
||||
}
|
||||
|
||||
func (d *daemonActions) closeIssue() func(context.Context, string, string, int, string) error {
|
||||
if d.issues == nil {
|
||||
return nil
|
||||
}
|
||||
return d.issues.CloseIssue
|
||||
}
|
||||
|
||||
func (d *daemonActions) removeLogs() func(int64) error {
|
||||
if d.logs == nil {
|
||||
return nil
|
||||
}
|
||||
return d.logs.Remove
|
||||
}
|
||||
|
||||
func (d *daemonActions) publish() func(events.Event) {
|
||||
if d.srv.Events == nil {
|
||||
return nil
|
||||
}
|
||||
return d.srv.Events.Publish
|
||||
}
|
||||
|
||||
// wireOperatorActions gives srv a task-action owner, the way composition
|
||||
// gives the dashboard a Gateway contract.
|
||||
func wireOperatorActions(srv *Server) *daemonActions {
|
||||
actions := &daemonActions{srv: srv, cfg: config.NewHolder(config.Config{})}
|
||||
srv.Chat = &ChatService{Contract: &gateway.LocalChatAdapter{TaskActor: actions}}
|
||||
return actions
|
||||
}
|
||||
|
||||
// operatorActions returns the stand-in daemon behind srv's contract.
|
||||
func operatorActions(t *testing.T, srv *Server) *daemonActions {
|
||||
t.Helper()
|
||||
local, ok := srv.Chat.Contract.(*gateway.LocalChatAdapter)
|
||||
if !ok {
|
||||
t.Fatalf("chat contract is %T, want the local adapter these tests wire", srv.Chat.Contract)
|
||||
}
|
||||
actions, ok := local.TaskActor.(*daemonActions)
|
||||
if !ok {
|
||||
t.Fatalf("task actor is %T, want the stand-in daemon", local.TaskActor)
|
||||
}
|
||||
return actions
|
||||
}
|
||||
|
||||
// actionServer builds a dashboard server with a task in the given state, plus
|
||||
// the collaborators the action path needs.
|
||||
func actionServer(t *testing.T, status, parkReason string) (*Server, *workflow.Task, *recordingCloser, *events.Bus, *events.Sub) {
|
||||
t.Helper()
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 11, "a task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("ClaimNext = (%+v, %v)", task, err)
|
||||
}
|
||||
taskstatetest.Seed(ctx, t, srv.Store, task.ID, workflow.StatusRunning, status, parkReason)
|
||||
|
||||
closer := &recordingCloser{}
|
||||
bus := events.NewBus()
|
||||
t.Cleanup(bus.Close)
|
||||
sub := bus.Subscribe(16)
|
||||
|
||||
operatorActions(t, srv).issues = closer
|
||||
srv.Events = bus
|
||||
operatorActions(t, srv).cfg = config.NewHolder(config.Config{MaxRetries: 3})
|
||||
return srv, task, closer, bus, sub
|
||||
}
|
||||
|
||||
func postAction(t *testing.T, srv *Server, id int64, action string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost,
|
||||
"/api/tasks/"+strconv.FormatInt(id, 10)+"/action",
|
||||
bytes.NewBufferString(fmt.Sprintf(`{"action":%q}`, action)))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Archie-CSRF", "1")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
type recordingTaskStopper struct {
|
||||
calls []int64
|
||||
result bool
|
||||
}
|
||||
|
||||
type archiveFailingStore struct {
|
||||
storecontract.TaskStore
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *archiveFailingStore) ArchiveTask(
|
||||
context.Context,
|
||||
int64,
|
||||
string,
|
||||
events.Event,
|
||||
) (int64, error) {
|
||||
return 0, s.err
|
||||
}
|
||||
|
||||
func (s *recordingTaskStopper) CancelTask(id int64) bool {
|
||||
s.calls = append(s.calls, id)
|
||||
return s.result
|
||||
}
|
||||
|
||||
func setTaskStopper(t *testing.T, srv *Server, stopper *recordingTaskStopper) {
|
||||
t.Helper()
|
||||
operatorActions(t, srv).stopper = stopper
|
||||
}
|
||||
|
||||
// max_retries is configured, defaulted and shown in /api/config, but nothing
|
||||
// enforced it: the Web UI retry incremented retry_count with no cap, so a
|
||||
// task that fails every time could be retried forever. At the cap the task
|
||||
// belongs in dead, which is what the setting exists to express.
|
||||
func TestRetryEnforcesMaxRetries(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
priorCount int
|
||||
maxRetries int
|
||||
wantStatus int
|
||||
wantTask string
|
||||
}{
|
||||
{name: "under the cap", priorCount: 0, maxRetries: 3, wantStatus: http.StatusOK, wantTask: workflow.StatusQueued},
|
||||
{name: "one below the cap", priorCount: 2, maxRetries: 3, wantStatus: http.StatusOK, wantTask: workflow.StatusQueued},
|
||||
{name: "at the cap", priorCount: 3, maxRetries: 3, wantStatus: http.StatusConflict, wantTask: workflow.StatusDead},
|
||||
{name: "past the cap", priorCount: 5, maxRetries: 3, wantStatus: http.StatusConflict, wantTask: workflow.StatusDead},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv, task, _, _, _ := actionServer(t, workflow.StatusParked, "it broke")
|
||||
operatorActions(t, srv).cfg = config.NewHolder(config.Config{MaxRetries: tc.maxRetries})
|
||||
ctx := t.Context()
|
||||
// Drive retry_count up through the real atomic retry path
|
||||
// (RetryTask) rather than a raw counter bump, re-parking
|
||||
// between retries so each call sees the fromStatus it needs.
|
||||
for range tc.priorCount {
|
||||
if err := srv.Store.RetryTask(ctx, task.ID, workflow.StatusParked, "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
taskstatetest.Seed(ctx, t, srv.Store, task.ID, workflow.StatusQueued, workflow.StatusParked, "re-parked for test fixture")
|
||||
}
|
||||
|
||||
w := postAction(t, srv, task.ID, "retry")
|
||||
if w.Code != tc.wantStatus {
|
||||
t.Fatalf("status = %d, want %d (body %s)", w.Code, tc.wantStatus, w.Body)
|
||||
}
|
||||
|
||||
got, err := srv.Store.TaskByID(ctx, task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", got, err)
|
||||
}
|
||||
if got.Status != tc.wantTask {
|
||||
t.Errorf("status = %q, want %q", got.Status, tc.wantTask)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Rejecting a task must stop the forge issue coming back. It stays open,
|
||||
// labelled and assigned otherwise, so the next poll re-enqueues it -- and if
|
||||
// the operator has used the dashboard's Clear, which deletes the row, that is
|
||||
// a second implementation and a second PR for work already declined.
|
||||
func TestRejectClosesTheForgeIssue(t *testing.T) {
|
||||
srv, task, closer, _, _ := actionServer(t, workflow.StatusWaitingHuman, "review")
|
||||
|
||||
if w := postAction(t, srv, task.ID, "reject"); w.Code != http.StatusOK {
|
||||
t.Fatalf("reject status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
|
||||
if len(closer.calls) != 1 {
|
||||
t.Fatalf("CloseIssue calls = %d, want 1: the issue stays open and is "+
|
||||
"re-polled, so the work is done twice", len(closer.calls))
|
||||
}
|
||||
call := closer.calls[0]
|
||||
if call.owner != "acme" || call.repo != "widget" || call.number != 11 {
|
||||
t.Errorf("closed %s/%s#%d, want acme/widget#11", call.owner, call.repo, call.number)
|
||||
}
|
||||
if call.comment == "" {
|
||||
t.Error("closed with no comment: an issue that closes itself with no " +
|
||||
"explanation reads as archie losing the work")
|
||||
}
|
||||
}
|
||||
|
||||
// Approve and retry put the task back to work, so the issue must stay open.
|
||||
func TestApproveAndRetryDoNotCloseTheIssue(t *testing.T) {
|
||||
for _, tc := range []struct{ action, status, reason string }{
|
||||
{"approve", workflow.StatusWaitingHuman, "review"},
|
||||
{"retry", workflow.StatusParked, "it broke"},
|
||||
} {
|
||||
t.Run(tc.action, func(t *testing.T) {
|
||||
srv, task, closer, _, _ := actionServer(t, tc.status, tc.reason)
|
||||
if w := postAction(t, srv, task.ID, tc.action); w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
if len(closer.calls) != 0 {
|
||||
t.Errorf("CloseIssue called %d times for %s; the task is going "+
|
||||
"back to work", len(closer.calls), tc.action)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A chat-sourced task has a synthetic issue number that matches no forge
|
||||
// issue, so closing it would either error or close an unrelated issue.
|
||||
func TestRejectDoesNotCloseAChatTaskIssue(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
closer := &recordingCloser{}
|
||||
operatorActions(t, srv).issues = closer
|
||||
operatorActions(t, srv).cfg = config.NewHolder(config.Config{MaxRetries: 3})
|
||||
|
||||
task, err := srv.Store.EnqueueChatTask(ctx, "acme", "widget", "chat task", "", "", "", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := srv.Store.ClaimNext(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := srv.Store.Transition(ctx, task.ID, workflow.StatusRunning, workflow.StatusWaitingHuman, "review"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if w := postAction(t, srv, task.ID, "reject"); w.Code != http.StatusOK {
|
||||
t.Fatalf("reject status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
if len(closer.calls) != 0 {
|
||||
t.Errorf("CloseIssue called for a chat task: issue number %d is synthetic",
|
||||
task.IssueNumber)
|
||||
}
|
||||
}
|
||||
|
||||
// A forge that cannot close the issue must not fail the action: the operator's
|
||||
// decision is already recorded in the store, and reporting failure would
|
||||
// invite them to click again.
|
||||
func TestRejectSurvivesAForgeFailure(t *testing.T) {
|
||||
srv, task, closer, _, _ := actionServer(t, workflow.StatusWaitingHuman, "review")
|
||||
closer.err = errors.New("forge unreachable")
|
||||
|
||||
if w := postAction(t, srv, task.ID, "reject"); w.Code != http.StatusOK {
|
||||
t.Fatalf("reject status = %d, want 200: the store transition succeeded", w.Code)
|
||||
}
|
||||
got, err := srv.Store.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", got, err)
|
||||
}
|
||||
if got.Status != workflow.StatusClosedWontDo {
|
||||
t.Errorf("status = %q, want %q", got.Status, workflow.StatusClosedWontDo)
|
||||
}
|
||||
}
|
||||
|
||||
// Actions wrote store rows and nothing else, so the activity stream and the
|
||||
// task timeline never showed that a human had intervened -- the one kind of
|
||||
// event most worth seeing.
|
||||
func TestActionsEmitEvents(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
action string
|
||||
status string
|
||||
reason string
|
||||
wantMsg string
|
||||
}{
|
||||
{name: "approve", action: "approve", status: workflow.StatusWaitingHuman, reason: "review", wantMsg: "approve"},
|
||||
{name: "retry", action: "retry", status: workflow.StatusParked, reason: "it broke", wantMsg: "retry"},
|
||||
{name: "reject", action: "reject", status: workflow.StatusWaitingHuman, reason: "review", wantMsg: "reject"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv, task, _, _, sub := actionServer(t, tc.status, tc.reason)
|
||||
|
||||
if w := postAction(t, srv, task.ID, tc.action); w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
|
||||
select {
|
||||
case ev := <-sub.C:
|
||||
if ev.TaskID != task.ID {
|
||||
t.Errorf("event TaskID = %d, want %d", ev.TaskID, task.ID)
|
||||
}
|
||||
if ev.Kind == "" {
|
||||
t.Error("event Kind is empty")
|
||||
}
|
||||
if tc.action == "retry" {
|
||||
if ev.Data["retry_count"] != 1 || ev.Data["previous_reason"] != tc.reason {
|
||||
t.Errorf("retry event Data = %#v, want retry count and previous failure", ev.Data)
|
||||
}
|
||||
}
|
||||
default:
|
||||
t.Fatalf("%s emitted no event: the activity stream and timeline "+
|
||||
"never show that a human intervened", tc.action)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Error mapping. A store failure is not the client's fault, and returning 409
|
||||
// tells the UI to say "conflict" for what is actually a broken database.
|
||||
func TestTaskActionErrorMapping(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
setup func(t *testing.T, srv *Server, id int64)
|
||||
id func(id int64) string
|
||||
wantStatus int
|
||||
wantHidden string
|
||||
}{
|
||||
{
|
||||
name: "unknown action",
|
||||
body: `{"action":"detonate"}`,
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "malformed body",
|
||||
body: `not json`,
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "non-numeric id",
|
||||
body: `{"action":"approve"}`,
|
||||
id: func(int64) string { return "banana" },
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "unknown task",
|
||||
body: `{"action":"approve"}`,
|
||||
id: func(int64) string { return "424242" },
|
||||
wantStatus: http.StatusNotFound,
|
||||
},
|
||||
{
|
||||
name: "store lookup failure is redacted",
|
||||
body: `{"action":"approve"}`,
|
||||
setup: func(_ *testing.T, srv *Server, _ int64) {
|
||||
srv.Store = &stubStore{TaskStore: srv.Store, taskByIDErr: errors.New("database password leaked")}
|
||||
},
|
||||
wantStatus: http.StatusInternalServerError,
|
||||
wantHidden: "password",
|
||||
},
|
||||
{
|
||||
name: "wrong state",
|
||||
body: `{"action":"retry"}`,
|
||||
// The task is waiting_human, not parked.
|
||||
wantStatus: http.StatusConflict,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv, task, _, _, _ := actionServer(t, workflow.StatusWaitingHuman, "review")
|
||||
if tc.setup != nil {
|
||||
tc.setup(t, srv, task.ID)
|
||||
}
|
||||
path := strconv.FormatInt(task.ID, 10)
|
||||
if tc.id != nil {
|
||||
path = tc.id(task.ID)
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost,
|
||||
"/api/tasks/"+path+"/action", bytes.NewBufferString(tc.body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Archie-CSRF", "1")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != tc.wantStatus {
|
||||
t.Fatalf("status = %d, want %d (body %s)", w.Code, tc.wantStatus, w.Body)
|
||||
}
|
||||
if tc.wantHidden != "" && strings.Contains(w.Body.String(), tc.wantHidden) {
|
||||
t.Fatalf("response exposed internal error: %s", w.Body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// postActionBody posts one raw action body through the dashboard handler.
|
||||
func postActionBody(t *testing.T, srv *Server, id int64, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost,
|
||||
"/api/tasks/"+strconv.FormatInt(id, 10)+"/action", bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Archie-CSRF", "1")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
// TestTaskActionRecordsTheReviewGateAnswer is the dashboard half of Decision
|
||||
// 1: the action body carries instructions (required by rereview) and the
|
||||
// finding keys approve posts, and the answer lands on the task's review_gate
|
||||
// document through the same path chat uses.
|
||||
func TestTaskActionRecordsTheReviewGateAnswer(t *testing.T) {
|
||||
keep := workflowtask.ReviewGateFinding{Key: "main.go:1:keep", Finding: json.RawMessage(`{"file":"main.go","line_start":1,"title":"keep","body":"keep me"}`)}
|
||||
drop := workflowtask.ReviewGateFinding{Key: "main.go:9:drop", Finding: json.RawMessage(`{"file":"main.go","line_start":9,"title":"drop","body":"drop me"}`)}
|
||||
offer := workflowtask.EncodeReviewGate(workflowtask.ReviewGate{
|
||||
Findings: []workflowtask.ReviewGateFinding{keep, drop}, HeadSHA: "abc", Owner: "acme", Repo: "widget",
|
||||
PRNumber: 42, Workflow: "pr-review",
|
||||
})
|
||||
|
||||
t.Run("approve records the selection", func(t *testing.T) {
|
||||
srv, task, _, _, _ := actionServer(t, workflow.StatusWaitingHuman, "review")
|
||||
if err := srv.Store.Update(t.Context(), &workflow.Task{ID: task.ID, Workflow: "pr-review", ReviewGate: offer}); err != nil {
|
||||
t.Fatalf("seed the offer: %v", err)
|
||||
}
|
||||
w := postActionBody(t, srv, task.ID, fmt.Sprintf(`{"action":"approve","findings":[%q]}`, keep.Key))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
updated, err := srv.Store.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || updated == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", updated, err)
|
||||
}
|
||||
gate, ok := workflowtask.DecodeReviewGate(updated.ReviewGate)
|
||||
if !ok || !gate.Approved() {
|
||||
t.Fatalf("recorded gate = %q, want an approve", updated.ReviewGate)
|
||||
}
|
||||
if len(gate.Selection) != 1 || gate.Selection[0] != keep.Key {
|
||||
t.Fatalf("recorded selection = %v, want only the posted key", gate.Selection)
|
||||
}
|
||||
if updated.Status != workflow.StatusQueued {
|
||||
t.Fatalf("status = %q, want %q", updated.Status, workflow.StatusQueued)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("rereview records the instructions and clears the offer", func(t *testing.T) {
|
||||
srv, task, _, _, _ := actionServer(t, workflow.StatusWaitingHuman, "review")
|
||||
if err := srv.Store.Update(t.Context(), &workflow.Task{ID: task.ID, Workflow: "pr-review", ReviewGate: offer}); err != nil {
|
||||
t.Fatalf("seed the offer: %v", err)
|
||||
}
|
||||
w := postActionBody(t, srv, task.ID, `{"action":"rereview","instructions":"the migration ordering"}`)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
updated, err := srv.Store.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || updated == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", updated, err)
|
||||
}
|
||||
gate, _ := workflowtask.DecodeReviewGate(updated.ReviewGate)
|
||||
if gate.Outcome != workflowtask.GateRereview || gate.Instructions != "the migration ordering" {
|
||||
t.Fatalf("recorded gate = %+v, want the re-review outcome and instructions", gate)
|
||||
}
|
||||
if len(gate.Findings) != 0 {
|
||||
t.Fatalf("re-review kept the offer: %+v", gate.Findings)
|
||||
}
|
||||
if updated.RereviewRounds != 1 {
|
||||
t.Fatalf("rereview rounds = %d, want 1 (the guarded write counts it)", updated.RereviewRounds)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("rereview without instructions is refused before any write", func(t *testing.T) {
|
||||
srv, task, _, _, _ := actionServer(t, workflow.StatusWaitingHuman, "review")
|
||||
if err := srv.Store.Update(t.Context(), &workflow.Task{ID: task.ID, Workflow: "pr-review", ReviewGate: offer}); err != nil {
|
||||
t.Fatalf("seed the offer: %v", err)
|
||||
}
|
||||
w := postActionBody(t, srv, task.ID, `{"action":"rereview"}`)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400 (body %s)", w.Code, w.Body)
|
||||
}
|
||||
updated, err := srv.Store.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || updated == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", updated, err)
|
||||
}
|
||||
if updated.Status != workflow.StatusWaitingHuman || updated.RereviewRounds != 0 {
|
||||
t.Fatalf("refused re-review changed the row: %+v", updated)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestTaskActionIsUnscopedAndRemote covers what routing through the Gateway
|
||||
// contract has to preserve: the dashboard operator is authenticated and acts
|
||||
// across identities, so the action must arrive unscoped rather than claiming
|
||||
// some identity of the UI process's own invention.
|
||||
func TestTaskActionIsUnscopedAndRemote(t *testing.T) {
|
||||
srv, task, _, _, _ := actionServer(t, workflow.StatusWaitingHuman, "review")
|
||||
|
||||
if w := postAction(t, srv, task.ID, "approve"); w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
|
||||
actions := operatorActions(t, srv)
|
||||
if len(actions.scopes) != 1 {
|
||||
t.Fatalf("task-action owner saw %d calls, want the handler to have made exactly 1", len(actions.scopes))
|
||||
}
|
||||
if actions.scopes[0] != nil {
|
||||
t.Fatalf("dashboard action arrived scoped to %q, want an unscoped operator", *actions.scopes[0])
|
||||
}
|
||||
}
|
||||
|
||||
// TestTaskActionWithoutAContractIsUnavailable: the dashboard has no local
|
||||
// task-action implementation to fall back on, and must say so rather than
|
||||
// half-applying an action over the task store it can reach.
|
||||
func TestTaskActionWithoutAContractIsUnavailable(t *testing.T) {
|
||||
srv, task, _, _, _ := actionServer(t, workflow.StatusWaitingHuman, "review")
|
||||
srv.Chat = nil
|
||||
|
||||
w := postAction(t, srv, task.ID, "approve")
|
||||
if w.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want 503 with no gateway contract wired", w.Code)
|
||||
}
|
||||
got, err := srv.Store.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", got, err)
|
||||
}
|
||||
if got.Status != workflow.StatusWaitingHuman {
|
||||
t.Fatalf("task status = %q, want it untouched at %q", got.Status, workflow.StatusWaitingHuman)
|
||||
}
|
||||
}
|
||||
|
||||
// A store write failure is a 500, not a 409.
|
||||
func TestTaskActionStoreFailureIs500(t *testing.T) {
|
||||
base := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
if _, err := base.Store.EnqueueIssue(ctx, "acme", "widget", 11, "a task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := base.Store.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("ClaimNext = (%+v, %v)", task, err)
|
||||
}
|
||||
if err := base.Store.Transition(ctx, task.ID, workflow.StatusRunning, workflow.StatusWaitingHuman, "review"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
srv := &Server{
|
||||
Store: &stubStore{TaskStore: base.Store, requeueErr: errors.New("db locked")},
|
||||
Log: base.Log,
|
||||
}
|
||||
wireOperatorActions(srv).cfg = config.NewHolder(config.Config{MaxRetries: 3})
|
||||
w := postAction(t, srv, task.ID, "approve")
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status = %d, want 500: a store failure is not a conflict", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskListExposesLifecycleActions(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
want := map[string][]string{
|
||||
workflow.StatusQueued: {"cancel", "reject"},
|
||||
workflow.StatusRunning: {"stop", "reject"},
|
||||
workflow.StatusWaitingHuman: {"approve", "reject", "rereview"},
|
||||
workflow.StatusParked: {"retry", "abandon", "reject"},
|
||||
workflow.StatusPROpen: {"open_pr", "open_issue", "reject"},
|
||||
workflow.StatusMerged: {"archive"},
|
||||
workflow.StatusRejected: {"archive"},
|
||||
workflow.StatusDead: {"archive"},
|
||||
workflow.StatusClosedWontDo: {"archive"},
|
||||
workflow.StatusCompleted: {"archive"},
|
||||
}
|
||||
|
||||
number := 1
|
||||
for status := range want {
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", number, status, "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", number)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("TaskByIssue(%s) = (%+v, %v)", status, task, err)
|
||||
}
|
||||
taskstatetest.Seed(ctx, t, srv.Store, task.ID, workflow.StatusQueued, status, "test")
|
||||
number++
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/tasks", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
var got []struct {
|
||||
Status string `json:"status"`
|
||||
Actions []string `json:"actions"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, task := range got {
|
||||
if !slices.Equal(task.Actions, want[task.Status]) {
|
||||
t.Errorf("actions for %s = %v, want %v", task.Status, task.Actions, want[task.Status])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLifecycleSpecificTaskActions(t *testing.T) {
|
||||
tests := []struct {
|
||||
name, from, action, want string
|
||||
stopperResult bool
|
||||
closesIssue bool
|
||||
}{
|
||||
{name: "cancel queued", from: workflow.StatusQueued, action: "cancel", want: workflow.StatusClosedWontDo, closesIssue: true},
|
||||
{name: "stop running", from: workflow.StatusRunning, action: "stop", want: workflow.StatusParked, stopperResult: true},
|
||||
{name: "park stale running row", from: workflow.StatusRunning, action: "stop", want: workflow.StatusParked},
|
||||
{name: "abandon parked", from: workflow.StatusParked, action: "abandon", want: workflow.StatusClosedWontDo, closesIssue: false},
|
||||
// Reject is available from every non-terminal state and always lands in
|
||||
// the terminal Declined state, closing the forge issue.
|
||||
{name: "reject queued", from: workflow.StatusQueued, action: "reject", want: workflow.StatusClosedWontDo, closesIssue: true},
|
||||
{name: "reject running stops execution", from: workflow.StatusRunning, action: "reject", want: workflow.StatusClosedWontDo, closesIssue: true, stopperResult: true},
|
||||
{name: "reject waiting_human", from: workflow.StatusWaitingHuman, action: "reject", want: workflow.StatusClosedWontDo, closesIssue: true},
|
||||
{name: "reject parked", from: workflow.StatusParked, action: "reject", want: workflow.StatusClosedWontDo, closesIssue: true},
|
||||
{name: "reject pr_open", from: workflow.StatusPROpen, action: "reject", want: workflow.StatusClosedWontDo, closesIssue: true},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 11, "a task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 11)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("TaskByIssue = (%+v, %v)", task, err)
|
||||
}
|
||||
taskstatetest.Seed(ctx, t, srv.Store, task.ID, workflow.StatusQueued, tc.from, "test")
|
||||
closer := &recordingCloser{}
|
||||
operatorActions(t, srv).issues = closer
|
||||
bus := events.NewBus()
|
||||
t.Cleanup(bus.Close)
|
||||
srv.Events = bus
|
||||
sub := bus.Subscribe(1)
|
||||
if tc.action == "stop" || (tc.action == "reject" && tc.from == workflow.StatusRunning) {
|
||||
setTaskStopper(t, srv, &recordingTaskStopper{result: tc.stopperResult})
|
||||
}
|
||||
if w := postAction(t, srv, task.ID, tc.action); w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
got, err := srv.Store.TaskByID(ctx, task.ID)
|
||||
if err != nil || got == nil || got.Status != tc.want {
|
||||
t.Fatalf("task = (%+v, %v), want status %s", got, err, tc.want)
|
||||
}
|
||||
if got := len(closer.calls) > 0; got != tc.closesIssue {
|
||||
t.Errorf("forge issue closed = %v, want %v", got, tc.closesIssue)
|
||||
}
|
||||
select {
|
||||
case event := <-sub.C:
|
||||
if event.TaskID != task.ID || event.Kind == "" {
|
||||
t.Errorf("event = %+v", event)
|
||||
}
|
||||
default:
|
||||
t.Error("operator action emitted no activity event")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestArchiveRemovesOnlyOneTerminalTask(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
for number := 1; number <= 2; number++ {
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", number, "done", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", number)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("TaskByIssue = (%+v, %v)", task, err)
|
||||
}
|
||||
taskstatetest.Seed(ctx, t, srv.Store, task.ID, workflow.StatusQueued, workflow.StatusMerged, "done")
|
||||
}
|
||||
task, _ := srv.Store.TaskByIssue(ctx, "acme", "widget", 1)
|
||||
bus := events.NewBus()
|
||||
t.Cleanup(bus.Close)
|
||||
srv.Events = bus
|
||||
sub := bus.Subscribe(1)
|
||||
if w := postAction(t, srv, task.ID, "archive"); w.Code != http.StatusOK {
|
||||
t.Fatalf("archive status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
if got, err := srv.Store.TaskByID(ctx, task.ID); err != nil || got != nil {
|
||||
t.Fatalf("archived task = (%+v, %v), want nil", got, err)
|
||||
}
|
||||
if other, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 2); err != nil || other == nil {
|
||||
t.Fatalf("archive removed another task: (%+v, %v)", other, err)
|
||||
}
|
||||
history, err := srv.Store.EventsSince(ctx, "", 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(history) != 1 || history[0].Kind != events.KindTaskArchiveRequested || history[0].ID == 0 {
|
||||
t.Fatalf("durable archive audit = %+v", history)
|
||||
}
|
||||
select {
|
||||
case event := <-sub.C:
|
||||
if event.Kind != events.KindTaskArchiveRequested || event.TaskID != task.ID {
|
||||
t.Errorf("archive event = %+v", event)
|
||||
}
|
||||
default:
|
||||
t.Error("archive emitted no activity event")
|
||||
}
|
||||
}
|
||||
|
||||
// TestArchiveRemovesTheTaskLogDirectory guards the cleanup half of task
|
||||
// logging: without this, an archived task's log files (and every rotated
|
||||
// generation under it) would accumulate on disk forever, since nothing else
|
||||
// in the system ever visits a task again once it leaves the active board.
|
||||
//
|
||||
// The removal is the task owner's, not the dashboard's: the log files live in
|
||||
// the state directory, which the daemon owns, so the stand-in daemon holds the
|
||||
// registry the way the real one does. The dashboard reads logs through a
|
||||
// contract and has no directory to remove anything from.
|
||||
func TestArchiveRemovesTheTaskLogDirectory(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
baseDir := t.TempDir()
|
||||
logs := logging.NewTaskRegistry(baseDir, logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
operatorActions(t, srv).logs = logs
|
||||
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "done", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, _ := srv.Store.TaskByIssue(ctx, "acme", "widget", 1)
|
||||
taskstatetest.Seed(ctx, t, srv.Store, task.ID, workflow.StatusQueued, workflow.StatusMerged, "done")
|
||||
|
||||
if err := logs.Open(task.ID, task.Attempt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
logs.Write(ctx, task.ID, logging.Entry{Message: "line"})
|
||||
if err := logs.Close(task.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := logging.TaskLogDir(baseDir, task.ID)
|
||||
if _, err := os.Stat(dir); err != nil {
|
||||
t.Fatalf("task log dir missing before archive: %v", err)
|
||||
}
|
||||
|
||||
if w := postAction(t, srv, task.ID, "archive"); w.Code != http.StatusOK {
|
||||
t.Fatalf("archive status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
if _, err := os.Stat(dir); !os.IsNotExist(err) {
|
||||
t.Errorf("task log dir still present after archive: err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestArchiveAuditFailurePreservesTaskAndFailsRequest(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "done", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, _ := srv.Store.TaskByIssue(ctx, "acme", "widget", 1)
|
||||
taskstatetest.Seed(ctx, t, srv.Store, task.ID, workflow.StatusQueued, workflow.StatusMerged, "done")
|
||||
base := srv.Store
|
||||
srv.Store = &archiveFailingStore{TaskStore: base, err: errors.New("audit unavailable")}
|
||||
|
||||
if w := postAction(t, srv, task.ID, "archive"); w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("archive status = %d, want 500", w.Code)
|
||||
}
|
||||
if got, err := base.TaskByID(ctx, task.ID); err != nil || got == nil {
|
||||
t.Fatalf("failed archive removed task: (%+v, %v)", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskActionRejectsUnsafeRequests(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "queued", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, _ := srv.Store.TaskByIssue(ctx, "acme", "widget", 1)
|
||||
path := "/api/tasks/" + strconv.FormatInt(task.ID, 10) + "/action"
|
||||
tests := []struct {
|
||||
name, body, contentType, csrf, origin string
|
||||
want int
|
||||
}{
|
||||
{name: "cross origin", body: `{"action":"cancel"}`, contentType: "application/json", csrf: "1", origin: "https://evil.example", want: http.StatusForbidden},
|
||||
{name: "non JSON", body: `{"action":"cancel"}`, contentType: "text/plain", csrf: "1", want: http.StatusUnsupportedMediaType},
|
||||
{name: "oversized", body: strings.Repeat(" ", 5000) + `{"action":"cancel"}`, contentType: "application/json", csrf: "1", want: http.StatusRequestEntityTooLarge},
|
||||
{name: "unknown field", body: `{"action":"cancel","status":"queued"}`, contentType: "application/json", csrf: "1", want: http.StatusBadRequest},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodPost, path, strings.NewReader(tc.body))
|
||||
req.Header.Set("Content-Type", tc.contentType)
|
||||
req.Header.Set("X-Archie-CSRF", tc.csrf)
|
||||
if tc.origin != "" {
|
||||
req.Header.Set("Origin", tc.origin)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != tc.want {
|
||||
t.Fatalf("status = %d, want %d (body %s)", w.Code, tc.want, w.Body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskActionRequiresCSRFHeader(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "queued", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, _ := srv.Store.TaskByIssue(ctx, "acme", "widget", 1)
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodPost,
|
||||
"/api/tasks/"+strconv.FormatInt(task.ID, 10)+"/action",
|
||||
bytes.NewBufferString(`{"action":"cancel"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("status = %d, want 403 without CSRF header (body %s)", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRetryCarriesTheWorktreeModeToTheStore is the dashboard half of the
|
||||
// operator retry choice: the mode in the action body reaches the store write,
|
||||
// so the daemon reads the operator's choice rather than inferring one. The
|
||||
// refusal case pins that continuing with nothing pushed is a conflict, not a
|
||||
// queued resume.
|
||||
func TestRetryCarriesTheWorktreeModeToTheStore(t *testing.T) {
|
||||
t.Run("continue pushed work persists the choice", func(t *testing.T) {
|
||||
srv, task, _, _, _ := actionServer(t, workflow.StatusParked, "it broke")
|
||||
if err := srv.Store.Update(t.Context(), &workflow.Task{ID: task.ID, Branch: "fix/11-thing"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
w := postActionBody(t, srv, task.ID, `{"action":"retry","retry_mode":"continue_pushed_work"}`)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200 (body %s)", w.Code, w.Body)
|
||||
}
|
||||
|
||||
got, err := srv.Store.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", got, err)
|
||||
}
|
||||
if got.RetryMode != string(taskstate.RetryContinuePushedWork) {
|
||||
t.Errorf("retry_mode = %q, want %q", got.RetryMode, taskstate.RetryContinuePushedWork)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("continue with no branch is refused", func(t *testing.T) {
|
||||
srv, task, _, _, _ := actionServer(t, workflow.StatusParked, "it broke")
|
||||
|
||||
w := postActionBody(t, srv, task.ID, `{"action":"retry","retry_mode":"continue_pushed_work"}`)
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("status = %d, want 409 (body %s)", w.Code, w.Body)
|
||||
}
|
||||
|
||||
got, err := srv.Store.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", got, err)
|
||||
}
|
||||
if got.Status != workflow.StatusParked {
|
||||
t.Errorf("status = %q, want the task left parked", got.Status)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,276 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
// postActionWithCredential posts an operator action the way an authenticated
|
||||
// caller does: JSON, the CSRF header, and the bearer token the middleware
|
||||
// resolves.
|
||||
func postActionWithCredential(t *testing.T, srv *Server, id int64, action, credential string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost,
|
||||
"/api/tasks/"+strconv.FormatInt(id, 10)+"/action",
|
||||
bytes.NewBufferString(fmt.Sprintf(`{"action":%q}`, action)))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Archie-CSRF", "1")
|
||||
req.Header.Set("Authorization", "Bearer "+credential)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
// approvalEvent returns the recorded approval on a task's timeline.
|
||||
func approvalEvent(t *testing.T, srv *Server, taskID int64) events.Event {
|
||||
t.Helper()
|
||||
recorded, err := srv.Store.TaskEvents(t.Context(), taskID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskEvents: %v", err)
|
||||
}
|
||||
for _, event := range recorded {
|
||||
if event.Kind == events.KindHumanApproved || event.Kind == events.KindAgentApproved || event.Kind == events.KindTaskApproved {
|
||||
return event
|
||||
}
|
||||
}
|
||||
t.Fatalf("no approval was recorded on task %d (events: %+v)", taskID, recorded)
|
||||
return events.Event{}
|
||||
}
|
||||
|
||||
// TestApprovalRecordsTheVerifiedActor is the flip this whole boundary exists for:
|
||||
// a dashboard approval is recorded as the person whose credential verified, and an
|
||||
// agent's token is recorded as the agent's action -- not as task_approved for both,
|
||||
// and never as a human's.
|
||||
func TestApprovalRecordsTheVerifiedActor(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
identity identity.Identity
|
||||
wantKind string
|
||||
wantActor string
|
||||
}{
|
||||
{
|
||||
name: "a person's credential is recorded as that person",
|
||||
identity: identity.Identity{ID: "50000000-0000-5000-8000-000000000001", Kind: identity.KindUser, DisplayName: "sam", Lifecycle: identity.LifecycleActive},
|
||||
wantKind: events.KindHumanApproved,
|
||||
wantActor: "50000000-0000-5000-8000-000000000001",
|
||||
},
|
||||
{
|
||||
name: "an agent's credential is recorded as the agent",
|
||||
identity: identity.Identity{ID: "50000000-0000-5000-8000-000000000002", Kind: identity.KindBot, DisplayName: "archie-web", Lifecycle: identity.LifecycleActive},
|
||||
wantKind: events.KindAgentApproved,
|
||||
wantActor: "50000000-0000-5000-8000-000000000002",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv, task, _, _, _ := actionServer(t, workflow.StatusWaitingHuman, "needs a decision")
|
||||
// The middleware resolves a verified credential to this identity, which
|
||||
// is the only place the actor may come from.
|
||||
srv.Authenticate = func(context.Context, string) (identity.Identity, error) {
|
||||
return tc.identity, nil
|
||||
}
|
||||
|
||||
// The request also claims an identity of its own, which must be ignored.
|
||||
w := postActionWithCredential(t, srv, task.ID, "approve", "a-provider-token")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d (body %q)", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
|
||||
recorded := approvalEvent(t, srv, task.ID)
|
||||
if recorded.ActorID != tc.wantActor {
|
||||
t.Fatalf("actor = %q, want %q", recorded.ActorID, tc.wantActor)
|
||||
}
|
||||
if recorded.ActorKind != string(tc.identity.Kind) {
|
||||
t.Fatalf("actor kind = %q, want %q", recorded.ActorKind, tc.identity.Kind)
|
||||
}
|
||||
if recorded.Kind != tc.wantKind {
|
||||
t.Fatalf("event kind = %q, want %q", recorded.Kind, tc.wantKind)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestUnverifiedApprovalIsRecordedUnattributed: with no provider configured the
|
||||
// shared-token gate still admits a request, and that request carries no identity
|
||||
// -- so the action is recorded unattributed rather than credited to a human.
|
||||
func TestUnverifiedApprovalIsRecordedUnattributed(t *testing.T) {
|
||||
srv, task, _, _, _ := actionServer(t, workflow.StatusWaitingHuman, "needs a decision")
|
||||
|
||||
w := postAction(t, srv, task.ID, "approve")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d (body %q)", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
|
||||
recorded := approvalEvent(t, srv, task.ID)
|
||||
if recorded.ActorID != "" || recorded.ActorKind != "" || recorded.PrincipalID != "" {
|
||||
t.Fatalf("an unattributed approval recorded an actor: %+v", recorded)
|
||||
}
|
||||
if recorded.Kind != events.KindTaskApproved {
|
||||
t.Fatalf("event kind = %q, want %q", recorded.Kind, events.KindTaskApproved)
|
||||
}
|
||||
}
|
||||
|
||||
// TestActionRequestCannotChooseItsActor: the body is read for the action only.
|
||||
// Nothing a caller can put in the request may select the identity recorded.
|
||||
func TestActionRequestCannotChooseItsActor(t *testing.T) {
|
||||
srv, task, _, _, _ := actionServer(t, workflow.StatusWaitingHuman, "needs a decision")
|
||||
verified := identity.Identity{ID: "50000000-0000-5000-8000-000000000003", Kind: identity.KindUser, DisplayName: "sam", Lifecycle: identity.LifecycleActive}
|
||||
srv.Authenticate = func(context.Context, string) (identity.Identity, error) { return verified, nil }
|
||||
|
||||
body := map[string]any{"action": "approve", "actor": "forged", "actor_id": "forged", "identity": "forged"}
|
||||
encoded, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost,
|
||||
"/api/tasks/"+strconv.FormatInt(task.ID, 10)+"/action", bytes.NewReader(encoded))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Archie-CSRF", "1")
|
||||
req.Header.Set("Authorization", "Bearer a-provider-token")
|
||||
req.Header.Set("X-Archie-Actor", "forged")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
// The body carries fields the decoder rejects, which is the point: there is no
|
||||
// accepted way to name an actor, so the request is refused rather than
|
||||
// silently attributed.
|
||||
if w.Code == http.StatusOK {
|
||||
recorded := approvalEvent(t, srv, task.ID)
|
||||
if recorded.ActorID != string(verified.ID) {
|
||||
t.Fatalf("actor = %q, want the verified %q", recorded.ActorID, verified.ID)
|
||||
}
|
||||
return
|
||||
}
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400 or 200 with the verified actor", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// stubFlow stands in for the provider's authorization-code flow. The flow itself
|
||||
// is exercised against a real provider in internal/infrastructure/oidc; what is
|
||||
// proved here is that the dashboard's browser path reaches the recorded actor.
|
||||
type stubFlow struct {
|
||||
authURL string
|
||||
verifier string
|
||||
session identity.ProviderSession
|
||||
}
|
||||
|
||||
func (f stubFlow) AuthCodeURL(state string) (string, string) {
|
||||
return f.authURL + "?state=" + state, f.verifier
|
||||
}
|
||||
|
||||
func (f stubFlow) Exchange(context.Context, string, string) (identity.ProviderSession, error) {
|
||||
return f.session, nil
|
||||
}
|
||||
|
||||
func cookieNamed(t *testing.T, response *http.Response, name string) *http.Cookie {
|
||||
t.Helper()
|
||||
for _, c := range response.Cookies() {
|
||||
if c.Name == name && c.Value != "" {
|
||||
return c
|
||||
}
|
||||
}
|
||||
t.Fatalf("no %q cookie in the response", name)
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestBrowserSignInRecordsTheSignedInPerson drives the whole browser path: sign in
|
||||
// through the provider, come back with a code, and then act on a task holding only
|
||||
// the credential the flow stored -- the actor recorded must be that person.
|
||||
func TestBrowserSignInRecordsTheSignedInPerson(t *testing.T) {
|
||||
srv, task, _, _, _ := actionServer(t, workflow.StatusWaitingHuman, "needs a decision")
|
||||
person := identity.Identity{
|
||||
ID: "60000000-0000-5000-8000-000000000001", Kind: identity.KindUser,
|
||||
DisplayName: "sam", Lifecycle: identity.LifecycleActive,
|
||||
}
|
||||
const token = "provider-access-token"
|
||||
srv.Login = stubFlow{
|
||||
authURL: "http://provider.example/authorize",
|
||||
verifier: "pkce-verifier",
|
||||
session: identity.ProviderSession{
|
||||
Credential: identity.Credential{Subject: identity.Subject{Issuer: "https://idp.example", Subject: "sam"}},
|
||||
Token: token,
|
||||
},
|
||||
}
|
||||
srv.Authenticate = func(_ context.Context, raw string) (identity.Identity, error) {
|
||||
if raw != token {
|
||||
return identity.Identity{}, identity.ErrCredentialRejected
|
||||
}
|
||||
return person, nil
|
||||
}
|
||||
|
||||
// 1. A browser asks to sign in and is sent to the provider.
|
||||
loginRequest := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/oauth2/login", nil)
|
||||
loginResponse := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(loginResponse, loginRequest)
|
||||
if loginResponse.Code != http.StatusSeeOther {
|
||||
t.Fatalf("login status = %d, want %d", loginResponse.Code, http.StatusSeeOther)
|
||||
}
|
||||
state := cookieNamed(t, loginResponse.Result(), loginStateCookie)
|
||||
verifier := cookieNamed(t, loginResponse.Result(), loginVerifierCookie)
|
||||
|
||||
// 2. The provider sends the browser back with a code.
|
||||
callbackRequest := httptest.NewRequestWithContext(t.Context(), http.MethodGet,
|
||||
"/oauth2/callback?code=a-code&state="+state.Value, nil)
|
||||
callbackRequest.AddCookie(state)
|
||||
callbackRequest.AddCookie(verifier)
|
||||
callbackResponse := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(callbackResponse, callbackRequest)
|
||||
if callbackResponse.Code != http.StatusSeeOther {
|
||||
t.Fatalf("callback status = %d, want %d (body %q)", callbackResponse.Code, http.StatusSeeOther, callbackResponse.Body.String())
|
||||
}
|
||||
|
||||
// 3. The signed-in browser acts, presenting only what the flow stored.
|
||||
stored := cookieNamed(t, callbackResponse.Result(), providerTokenCookie)
|
||||
actionRequest := httptest.NewRequestWithContext(t.Context(), http.MethodPost,
|
||||
"/api/tasks/"+strconv.FormatInt(task.ID, 10)+"/action", bytes.NewBufferString(`{"action":"approve"}`))
|
||||
actionRequest.Header.Set("Content-Type", "application/json")
|
||||
actionRequest.Header.Set("X-Archie-CSRF", "1")
|
||||
actionRequest.AddCookie(stored)
|
||||
actionResponse := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(actionResponse, actionRequest)
|
||||
if actionResponse.Code != http.StatusOK {
|
||||
t.Fatalf("action status = %d, want %d (body %q)", actionResponse.Code, http.StatusOK, actionResponse.Body.String())
|
||||
}
|
||||
|
||||
recorded := approvalEvent(t, srv, task.ID)
|
||||
if recorded.ActorID != string(person.ID) {
|
||||
t.Fatalf("actor = %q, want the signed-in person %q", recorded.ActorID, person.ID)
|
||||
}
|
||||
if recorded.Kind != events.KindHumanApproved {
|
||||
t.Fatalf("event kind = %q, want %q", recorded.Kind, events.KindHumanApproved)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCallbackRefusesAMismatchedState: the callback must check the state it issued,
|
||||
// or a sign-in response could be replayed against another browser's flow.
|
||||
func TestCallbackRefusesAMismatchedState(t *testing.T) {
|
||||
srv, _, _, _, _ := actionServer(t, workflow.StatusWaitingHuman, "needs a decision")
|
||||
srv.Login = stubFlow{authURL: "http://provider.example/authorize", verifier: "pkce-verifier"}
|
||||
srv.Authenticate = func(context.Context, string) (identity.Identity, error) {
|
||||
t.Fatal("the callback verified a credential before checking its state")
|
||||
return identity.Identity{}, nil
|
||||
}
|
||||
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodGet,
|
||||
"/oauth2/callback?code=a-code&state=not-the-state-i-issued", nil)
|
||||
request.AddCookie(&http.Cookie{Name: loginStateCookie, Value: "the-state-i-issued"})
|
||||
request.AddCookie(&http.Cookie{Name: loginVerifierCookie, Value: "pkce-verifier"})
|
||||
response := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(response, request)
|
||||
|
||||
if response.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusUnauthorized)
|
||||
}
|
||||
}
|
||||
@@ -1,583 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
// stepWriter is StepRecorder, asserted against srv.Store here rather than
|
||||
// widened onto storecontract.TaskStore: the dashboard never writes a step
|
||||
// itself, only reads them (Server.Steps, storecontract.StepReader), and this
|
||||
// test needs real rows to exercise the read against.
|
||||
type stepWriter interface {
|
||||
StartStep(ctx context.Context, s task.StepStart) (int64, events.Event, error)
|
||||
FinishStep(ctx context.Context, s task.StepFinish) (events.Event, error)
|
||||
}
|
||||
|
||||
// railBase is the fixed clock the rail fixtures hang off, so every timestamp
|
||||
// and duration asserted below is a literal rather than a tolerance.
|
||||
var railBase = time.Date(2026, 9, 18, 7, 0, 0, 0, time.UTC)
|
||||
|
||||
// attemptEvent stands in for the events that still drive attempt bounds and
|
||||
// counts (attemptsFromEvents), independent of the stage rail those events
|
||||
// used to also back.
|
||||
func attemptEvent(taskID int64, attempt int, at time.Time) events.Event {
|
||||
return events.Event{Kind: events.KindAgentFinish, TaskID: taskID, Attempt: attempt, At: at}
|
||||
}
|
||||
|
||||
func insertTaskEvent(t *testing.T, srv *Server, ev events.Event) {
|
||||
t.Helper()
|
||||
if _, err := srv.Store.InsertEvent(t.Context(), ev); err != nil {
|
||||
t.Fatalf("insert %s event: %v", ev.Kind, err)
|
||||
}
|
||||
}
|
||||
|
||||
// stageStep is a fixture StepExecution the pure-function test builds by
|
||||
// hand -- no store round trip, since stageViewsFromSteps operates on
|
||||
// task.StepExecution values directly.
|
||||
func stageStep(name string, attempt int, status taskstate.StepStatus, startedAt, finishedAt time.Time, detail string) task.StepExecution {
|
||||
return task.StepExecution{
|
||||
Attempt: attempt, Kind: task.StepKindStage, Name: name, Status: status,
|
||||
StartedAt: startedAt, FinishedAt: finishedAt, Detail: detail,
|
||||
}
|
||||
}
|
||||
|
||||
// getTaskAPI issues one task-detail request through the real mux. A route that
|
||||
// is not registered falls through to the SPA asset handler and answers 200 with
|
||||
// an HTML page, so using the mux makes a missing registration fail the shape
|
||||
// assertions below rather than passing quietly.
|
||||
func getTaskAPI(t *testing.T, srv *Server, url string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, url, nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
func taskRoute(id int64, suffix string) string {
|
||||
return "/api/tasks/" + strconv.FormatInt(id, 10) + suffix
|
||||
}
|
||||
|
||||
// twoAttemptTask drives one task through the lifecycle the rail has to read:
|
||||
// claim (attempt 1), park, retry, claim (attempt 2), leaving the task running
|
||||
// on its second attempt. No test writes an attempt number directly, so the
|
||||
// attempt under test is the one the real lifecycle produced.
|
||||
func twoAttemptTask(t *testing.T, srv *Server) *workflow.Task {
|
||||
t.Helper()
|
||||
ctx := t.Context()
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := srv.Store.ClaimNext(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first == nil {
|
||||
t.Fatal("ClaimNext returned no task")
|
||||
}
|
||||
if first.Attempt != 1 {
|
||||
t.Fatalf("first claim attempt = %d, want 1", first.Attempt)
|
||||
}
|
||||
if err := srv.Store.Transition(ctx, first.ID, workflow.StatusRunning, workflow.StatusParked, "stage implement: builder exited 1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := srv.Store.RetryTask(ctx, first.ID, workflow.StatusParked, "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := srv.Store.ClaimNext(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if second == nil {
|
||||
t.Fatal("second claim returned no task")
|
||||
}
|
||||
if second.Attempt != 2 || second.Status != workflow.StatusRunning {
|
||||
t.Fatalf("second claim = attempt %d status %q, want attempt 2 running", second.Attempt, second.Status)
|
||||
}
|
||||
return second
|
||||
}
|
||||
|
||||
// summarizeAttemptRail renders a folded rail as one line per attempt so a table
|
||||
// case states the derivation it expects without a struct literal per stage:
|
||||
// "attempt:status[name:status:duration[#error][@nostart],...] duration".
|
||||
func durationToken(ms *int64) string {
|
||||
if ms == nil {
|
||||
return "?"
|
||||
}
|
||||
return strconv.FormatInt(*ms, 10)
|
||||
}
|
||||
|
||||
// summarizeStages renders a stage list the same way summarizeAttemptRail's
|
||||
// inner loop does, for a test that exercises stageViewsFromSteps alone.
|
||||
func summarizeStages(stages []taskStageView) string {
|
||||
tokens := make([]string, 0, len(stages))
|
||||
for _, s := range stages {
|
||||
token := s.Name + ":" + s.Status + ":" + durationToken(s.DurationMS)
|
||||
if s.StartedAt == nil {
|
||||
token += "@nostart"
|
||||
}
|
||||
if s.Error != "" {
|
||||
token += "#" + s.Error
|
||||
}
|
||||
tokens = append(tokens, token)
|
||||
}
|
||||
return strings.Join(tokens, ",")
|
||||
}
|
||||
|
||||
// TestStageViewsFromStepsDerivesEveryRailRule is the table behind R1: every
|
||||
// status rule the rail depends on, sourced from StepExecutions -- the
|
||||
// authoritative record (docs/prds/execution-tree-state-machine.md) -- rather
|
||||
// than a fold over stage_start/stage_finish events.
|
||||
func TestStageViewsFromStepsDerivesEveryRailRule(t *testing.T) {
|
||||
at := railBase.Add
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
steps []task.StepExecution
|
||||
inFlight bool
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "a succeeded step is ok and reports its measured span",
|
||||
steps: []task.StepExecution{stageStep("prepare", 1, taskstate.StepSucceeded, at(0), at(time.Second), "")},
|
||||
want: "prepare:ok:1000",
|
||||
},
|
||||
{
|
||||
name: "a failed step fails and carries its detail as the error",
|
||||
steps: []task.StepExecution{stageStep("implement", 1, taskstate.StepFailed, at(0), at(2*time.Second), "builder exited 1")},
|
||||
want: "implement:failed:2000#builder exited 1",
|
||||
},
|
||||
{
|
||||
name: "a cancelled step reads interrupted",
|
||||
steps: []task.StepExecution{stageStep("implement", 1, taskstate.StepCancelled, at(0), at(time.Second), "stopped by operator")},
|
||||
want: "implement:interrupted:1000",
|
||||
},
|
||||
{
|
||||
name: "an interrupted step reads interrupted",
|
||||
steps: []task.StepExecution{stageStep("implement", 1, taskstate.StepInterrupted, at(0), at(time.Second), "")},
|
||||
want: "implement:interrupted:1000",
|
||||
},
|
||||
{
|
||||
name: "a running step on the task's current in-flight attempt is running",
|
||||
steps: []task.StepExecution{stageStep("implement", 2, taskstate.StepRunning, at(0), time.Time{}, "")},
|
||||
inFlight: true,
|
||||
want: "implement:running:?",
|
||||
},
|
||||
{
|
||||
name: "a running step past the task's live attempt is stale, read as interrupted",
|
||||
steps: []task.StepExecution{stageStep("implement", 1, taskstate.StepRunning, at(0), time.Time{}, "")},
|
||||
inFlight: false,
|
||||
want: "implement:interrupted:?",
|
||||
},
|
||||
{
|
||||
name: "a pending step (never observed in practice) reads unknown rather than a false verdict",
|
||||
steps: []task.StepExecution{stageStep("implement", 1, taskstate.StepPending, time.Time{}, time.Time{}, "")},
|
||||
want: "implement:unknown:?@nostart",
|
||||
},
|
||||
{
|
||||
name: "a repeated stage name yields one rail entry per occurrence",
|
||||
steps: []task.StepExecution{
|
||||
stageStep("implement", 1, taskstate.StepSucceeded, at(0), at(time.Second), ""),
|
||||
{Attempt: 1, Kind: task.StepKindStage, Name: "implement", Status: taskstate.StepRunning, StartedAt: at(2 * time.Second)},
|
||||
},
|
||||
inFlight: true,
|
||||
want: "implement:ok:1000,implement:running:?",
|
||||
},
|
||||
{
|
||||
name: "an agent or call step is not part of the stage rail",
|
||||
steps: []task.StepExecution{
|
||||
stageStep("implement", 1, taskstate.StepSucceeded, at(0), at(time.Second), ""),
|
||||
{Attempt: 1, Kind: task.StepKindAgent, Name: "implement", Status: taskstate.StepSucceeded, StartedAt: at(0), FinishedAt: at(time.Second)},
|
||||
{Attempt: 1, Kind: task.StepKindCall, Name: "callee", Status: taskstate.StepSucceeded, StartedAt: at(0), FinishedAt: at(time.Second)},
|
||||
},
|
||||
want: "implement:ok:1000",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := summarizeStages(stageViewsFromSteps(tt.steps, tt.inFlight)); got != tt.want {
|
||||
t.Errorf("stages = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAttemptsFromEventsIndexesAttemptsFromEventsAndUnattributedCount pins
|
||||
// what attemptsFromEvents still owns now that stage derivation moved to
|
||||
// steps: which attempt numbers exist, and the unattributed-event count --
|
||||
// both read from the task's events, since an attempt can carry events (agent
|
||||
// calls, say) with no recorded step at all.
|
||||
func TestAttemptsFromEventsIndexesAttemptsFromEventsAndUnattributedCount(t *testing.T) {
|
||||
at := railBase.Add
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
taskStatus string
|
||||
currentAttempt int
|
||||
evs []events.Event
|
||||
steps []task.StepExecution
|
||||
wantAttempts []int
|
||||
wantUnattributed int
|
||||
}{
|
||||
{
|
||||
name: "a later attempt does not absorb the earlier attempt's steps",
|
||||
taskStatus: workflow.StatusRunning, currentAttempt: 2,
|
||||
evs: []events.Event{attemptEvent(1, 1, at(0)), attemptEvent(1, 2, at(time.Second))},
|
||||
steps: []task.StepExecution{stageStep("prepare", 1, taskstate.StepSucceeded, at(0), at(time.Second), "")},
|
||||
wantAttempts: []int{1, 2},
|
||||
},
|
||||
{
|
||||
name: "events carrying no attempt are counted, never grouped",
|
||||
taskStatus: workflow.StatusQueued, currentAttempt: 0,
|
||||
evs: []events.Event{{Kind: events.KindAgentFinish, TaskID: 1, At: at(0)}, {Kind: events.KindAgentFinish, TaskID: 1, At: at(time.Second)}},
|
||||
wantUnattributed: 2,
|
||||
},
|
||||
{
|
||||
name: "a task with no events has no attempts and nothing unattributed",
|
||||
taskStatus: workflow.StatusQueued, currentAttempt: 0,
|
||||
},
|
||||
{
|
||||
name: "an attempt with events but no recorded step still appears, with no stages",
|
||||
taskStatus: workflow.StatusParked, currentAttempt: 1,
|
||||
evs: []events.Event{attemptEvent(1, 1, at(0))},
|
||||
wantAttempts: []int{1},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
attempts, unattributed := attemptsFromEvents(tt.evs, tt.steps, tt.taskStatus, tt.currentAttempt)
|
||||
var got []int
|
||||
for _, a := range attempts {
|
||||
got = append(got, a.Attempt)
|
||||
}
|
||||
if len(got) != len(tt.wantAttempts) {
|
||||
t.Fatalf("attempts = %v, want %v", got, tt.wantAttempts)
|
||||
}
|
||||
for i, want := range tt.wantAttempts {
|
||||
if got[i] != want {
|
||||
t.Errorf("attempts = %v, want %v", got, tt.wantAttempts)
|
||||
}
|
||||
}
|
||||
if unattributed != tt.wantUnattributed {
|
||||
t.Errorf("unattributed = %d, want %d", unattributed, tt.wantUnattributed)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskAttemptsRendersBothAttemptsOfARetry pins the wire shape: an
|
||||
// attempt's ordered stages with name, start time, duration, terminal status and
|
||||
// error text, the task's current attempt, and attempt 1's rail excluding
|
||||
// attempt 2's stages.
|
||||
func TestHandleTaskAttemptsRendersBothAttemptsOfARetry(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
steps, ok := srv.Store.(stepWriter)
|
||||
if !ok {
|
||||
t.Fatal("test store does not implement stepWriter")
|
||||
}
|
||||
|
||||
// Not twoAttemptTask: StartStep guards on the execution's own current
|
||||
// attempt (a step named for a superseded attempt is a stale transition
|
||||
// by design -- steps.go, "a caller naming one the execution no longer
|
||||
// runs is describing a run that is over"), so attempt 1's steps have to
|
||||
// be recorded while the task is actually on attempt 1, before the retry
|
||||
// that moves it to attempt 2.
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
claimed1, err := srv.Store.ClaimNext(ctx)
|
||||
if err != nil || claimed1 == nil || claimed1.Attempt != 1 {
|
||||
t.Fatalf("ClaimNext = (%+v, %v), want attempt 1", claimed1, err)
|
||||
}
|
||||
|
||||
prepareID, _, err := steps.StartStep(ctx, task.StepStart{ExecutionID: claimed1.ID, Attempt: 1, Kind: task.StepKindStage, Name: "prepare"})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep prepare: %v", err)
|
||||
}
|
||||
if _, err := steps.FinishStep(ctx, task.StepFinish{
|
||||
StepID: prepareID, ExecutionID: claimed1.ID, From: taskstate.StepRunning, To: taskstate.StepSucceeded,
|
||||
}); err != nil {
|
||||
t.Fatalf("FinishStep prepare: %v", err)
|
||||
}
|
||||
implementID, _, err := steps.StartStep(ctx, task.StepStart{ExecutionID: claimed1.ID, Attempt: 1, Kind: task.StepKindStage, Name: "implement"})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep implement: %v", err)
|
||||
}
|
||||
if _, err := steps.FinishStep(ctx, task.StepFinish{
|
||||
StepID: implementID, ExecutionID: claimed1.ID, From: taskstate.StepRunning, To: taskstate.StepFailed,
|
||||
Detail: "stage implement: builder exited 1",
|
||||
}); err != nil {
|
||||
t.Fatalf("FinishStep implement: %v", err)
|
||||
}
|
||||
|
||||
if err := srv.Store.Transition(ctx, claimed1.ID, workflow.StatusRunning, workflow.StatusParked, "stage implement: builder exited 1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := srv.Store.RetryTask(ctx, claimed1.ID, workflow.StatusParked, "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
current, err := srv.Store.ClaimNext(ctx)
|
||||
if err != nil || current == nil || current.Attempt != 2 {
|
||||
t.Fatalf("second ClaimNext = (%+v, %v), want attempt 2", current, err)
|
||||
}
|
||||
if _, _, err := steps.StartStep(ctx, task.StepStart{ExecutionID: current.ID, Attempt: 2, Kind: task.StepKindStage, Name: "implement"}); err != nil {
|
||||
t.Fatalf("StartStep attempt 2 implement: %v", err)
|
||||
}
|
||||
|
||||
// No hand-inserted events: StartStep/FinishStep already write
|
||||
// stage_start/stage_finish events in the same transaction as the step
|
||||
// row (steps.go), which is what attemptBounds and event_count read --
|
||||
// attempt 1 gets exactly the 4 those two StartStep+FinishStep pairs
|
||||
// produce, attempt 2 the 1 its lone StartStep produces. Their
|
||||
// timestamps are the store's own clock, so bounds are checked for
|
||||
// presence and order below rather than against a literal railBase time.
|
||||
w := getTaskAPI(t, srv, taskRoute(current.ID, "/attempts"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
if raw := w.Body.String(); !strings.Contains(raw, `"error":""`) {
|
||||
t.Errorf("body = %s, want the ok stage's error field present and empty rather than omitted", raw)
|
||||
}
|
||||
|
||||
var body struct {
|
||||
TaskID int64 `json:"task_id"`
|
||||
CurrentAttempt int `json:"current_attempt"`
|
||||
UnattributedEvents int `json:"unattributed_events"`
|
||||
Attempts []struct {
|
||||
Attempt int `json:"attempt"`
|
||||
Status string `json:"status"`
|
||||
StartedAt *time.Time `json:"started_at"`
|
||||
FinishedAt *time.Time `json:"finished_at"`
|
||||
DurationMS *int64 `json:"duration_ms"`
|
||||
EventCount int `json:"event_count"`
|
||||
Stages []struct {
|
||||
Name string `json:"name"`
|
||||
Seq int `json:"seq"`
|
||||
Status string `json:"status"`
|
||||
StartedAt *time.Time `json:"started_at"`
|
||||
DurationMS *int64 `json:"duration_ms"`
|
||||
Error string `json:"error"`
|
||||
} `json:"stages"`
|
||||
} `json:"attempts"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v (%s)", err, w.Body)
|
||||
}
|
||||
if body.TaskID != current.ID || body.CurrentAttempt != 2 || body.UnattributedEvents != 0 {
|
||||
t.Fatalf("envelope = task %d, current attempt %d, unattributed %d; want %d, 2, 0",
|
||||
body.TaskID, body.CurrentAttempt, body.UnattributedEvents, current.ID)
|
||||
}
|
||||
if len(body.Attempts) != 2 {
|
||||
t.Fatalf("attempts = %d, want 2 (%s)", len(body.Attempts), w.Body)
|
||||
}
|
||||
|
||||
first := body.Attempts[0]
|
||||
if first.Attempt != 1 || first.Status != "failed" {
|
||||
t.Errorf("attempt 1 = %d/%q, want 1/failed", first.Attempt, first.Status)
|
||||
}
|
||||
if first.EventCount != 4 {
|
||||
t.Errorf("attempt 1 event_count = %d, want 4", first.EventCount)
|
||||
}
|
||||
// StartStep/FinishStep stamp their events with the store's own clock, so
|
||||
// only presence, order and non-negativity are checked here.
|
||||
if first.StartedAt == nil || first.FinishedAt == nil || first.FinishedAt.Before(*first.StartedAt) {
|
||||
t.Errorf("attempt 1 bounds = started %v finished %v, want finished not before started", first.StartedAt, first.FinishedAt)
|
||||
}
|
||||
if first.DurationMS == nil || *first.DurationMS < 0 {
|
||||
t.Errorf("attempt 1 duration_ms = %v, want a non-negative measured span", first.DurationMS)
|
||||
}
|
||||
if len(first.Stages) != 2 {
|
||||
t.Fatalf("attempt 1 stages = %d, want 2 (%s)", len(first.Stages), w.Body)
|
||||
}
|
||||
prepare := first.Stages[0]
|
||||
if prepare.Name != "prepare" || prepare.Seq != 0 || prepare.Status != "ok" || prepare.Error != "" {
|
||||
t.Errorf("stage 0 = %+v, want prepare/0/ok with no error", prepare)
|
||||
}
|
||||
// StartStep/FinishStep stamp started_at/finished_at with the store's own
|
||||
// clock (now()), not a caller-supplied time, so only their presence and
|
||||
// non-negativity are checked here -- railBase no longer applies to a step
|
||||
// row the way it did to a hand-inserted event.
|
||||
if prepare.StartedAt == nil || prepare.DurationMS == nil || *prepare.DurationMS < 0 {
|
||||
t.Errorf("stage 0 = %+v, want a recorded start and a non-negative duration", prepare)
|
||||
}
|
||||
implement := first.Stages[1]
|
||||
if implement.Name != "implement" || implement.Seq != 1 || implement.Status != "failed" {
|
||||
t.Errorf("stage 1 = %+v, want implement/1/failed", implement)
|
||||
}
|
||||
if implement.Error != "stage implement: builder exited 1" {
|
||||
t.Errorf("stage 1 error = %q, want the recorded error text", implement.Error)
|
||||
}
|
||||
if implement.DurationMS == nil || *implement.DurationMS < 0 {
|
||||
t.Errorf("stage 1 duration_ms = %v, want a non-negative measured duration", implement.DurationMS)
|
||||
}
|
||||
|
||||
second := body.Attempts[1]
|
||||
if second.Attempt != 2 || second.Status != "running" || second.EventCount != 1 {
|
||||
t.Errorf("attempt 2 = %d/%q with %d events, want 2/running with 1", second.Attempt, second.Status, second.EventCount)
|
||||
}
|
||||
if second.FinishedAt != nil || second.DurationMS != nil {
|
||||
t.Errorf("attempt 2 finished_at = %v, duration_ms = %v; both must be omitted for a running attempt",
|
||||
second.FinishedAt, second.DurationMS)
|
||||
}
|
||||
if len(second.Stages) != 1 || second.Stages[0].Name != "implement" || second.Stages[0].Status != "running" {
|
||||
t.Fatalf("attempt 2 stages = %+v, want one running implement", second.Stages)
|
||||
}
|
||||
if second.Stages[0].Error != "" {
|
||||
t.Errorf("attempt 2 stage error = %q, want empty", second.Stages[0].Error)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskAttemptsSeparatesUnattributedEventsFromAFirstRun pins the
|
||||
// honesty requirement: events that carry no attempt cannot be presented as
|
||||
// attempt 1, and a task with nothing recorded at all is a different answer from
|
||||
// a task whose events predate attribution.
|
||||
func TestHandleTaskAttemptsSeparatesUnattributedEventsFromAFirstRun(t *testing.T) {
|
||||
t.Run("a task with no events at all", func(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
if _, err := srv.Store.EnqueueIssue(t.Context(), "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(t.Context(), "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(task.ID, "/attempts"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
raw := w.Body.String()
|
||||
if !strings.Contains(raw, `"attempts":[]`) {
|
||||
t.Errorf("body = %s, want an empty attempts array rather than null", raw)
|
||||
}
|
||||
if !strings.Contains(raw, `"unattributed_events":0`) {
|
||||
t.Errorf("body = %s, want unattributed_events 0 for a task with nothing recorded", raw)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("events that carry no attempt", func(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
if _, err := srv.Store.EnqueueIssue(t.Context(), "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(t.Context(), "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
insertTaskEvent(t, srv, attemptEvent(task.ID, 0, railBase))
|
||||
insertTaskEvent(t, srv, attemptEvent(task.ID, 0, railBase.Add(time.Second)))
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(task.ID, "/attempts"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
var body struct {
|
||||
UnattributedEvents int `json:"unattributed_events"`
|
||||
Attempts []struct {
|
||||
Attempt int `json:"attempt"`
|
||||
} `json:"attempts"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v (%s)", err, w.Body)
|
||||
}
|
||||
if body.UnattributedEvents != 2 {
|
||||
t.Errorf("unattributed_events = %d, want 2", body.UnattributedEvents)
|
||||
}
|
||||
if len(body.Attempts) != 0 {
|
||||
t.Errorf("attempts = %+v, want none: events carrying no attempt must never be presented as a run", body.Attempts)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestTaskDetailRoutesRejectUnknownTasksAndStoreFailures keeps the three new
|
||||
// reads on the existing task-route conventions: an unknown task is 404 plain
|
||||
// text (never 200 with an empty body), a store failure is 500, and a
|
||||
// non-numeric id is 400.
|
||||
func TestTaskDetailRoutesRejectUnknownTasksAndStoreFailures(t *testing.T) {
|
||||
base := newTestServer(t)
|
||||
if _, err := base.Store.EnqueueIssue(t.Context(), "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
existing, err := base.Store.TaskByIssue(t.Context(), "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
eventsBroken := &Server{
|
||||
Store: &stubStore{TaskStore: base.Store, taskEventsErr: fmt.Errorf("db locked")},
|
||||
Log: base.Log,
|
||||
}
|
||||
lookupBroken := &Server{
|
||||
Store: &stubStore{TaskStore: base.Store, taskByIDErr: fmt.Errorf("db locked")},
|
||||
Log: base.Log,
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
srv *Server
|
||||
id int64
|
||||
suffix string
|
||||
wantStatus int
|
||||
}{
|
||||
{"attempts unknown task", base, 999, "/attempts", http.StatusNotFound},
|
||||
{"changes unknown task", base, 999, "/changes", http.StatusNotFound},
|
||||
{"debug unknown task", base, 999, "/debug", http.StatusNotFound},
|
||||
{"attempts events failure", eventsBroken, existing.ID, "/attempts", http.StatusInternalServerError},
|
||||
{"changes events failure", eventsBroken, existing.ID, "/changes", http.StatusInternalServerError},
|
||||
{"debug events failure", eventsBroken, existing.ID, "/debug", http.StatusInternalServerError},
|
||||
{"attempts lookup failure", lookupBroken, existing.ID, "/attempts", http.StatusInternalServerError},
|
||||
{"changes lookup failure", lookupBroken, existing.ID, "/changes", http.StatusInternalServerError},
|
||||
{"debug lookup failure", lookupBroken, existing.ID, "/debug", http.StatusInternalServerError},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
w := getTaskAPI(t, tt.srv, taskRoute(tt.id, tt.suffix))
|
||||
if w.Code != tt.wantStatus {
|
||||
t.Errorf("GET %s = %d (%s), want %d", tt.suffix, w.Code, w.Body, tt.wantStatus)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
for _, suffix := range []string{"/attempts", "/changes", "/debug"} {
|
||||
t.Run("non-numeric id "+suffix, func(t *testing.T) {
|
||||
w := getTaskAPI(t, base, "/api/tasks/not-a-number"+suffix)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("GET %s = %d (%s), want 400", suffix, w.Code, w.Body)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The attempt parameter belongs to the per-attempt reads: /attempts returns
|
||||
// every attempt of the task, so it does not consume the parameter at all,
|
||||
// while /changes and /debug resolve it and must refuse a value that is not
|
||||
// an attempt number rather than silently read the current one.
|
||||
t.Run("non-numeric attempt on /attempts is not a parameter of that read", func(t *testing.T) {
|
||||
w := getTaskAPI(t, base, taskRoute(existing.ID, "/attempts?attempt=later"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("GET /attempts?attempt=later = %d (%s), want 200", w.Code, w.Body)
|
||||
}
|
||||
})
|
||||
for _, suffix := range []string{"/changes", "/debug"} {
|
||||
t.Run("non-numeric attempt "+suffix, func(t *testing.T) {
|
||||
w := getTaskAPI(t, base, taskRoute(existing.ID, suffix+"?attempt=later"))
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("GET %s?attempt=later = %d (%s), want 400", suffix, w.Code, w.Body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,460 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
// captureData is the shape the producer persists for one capture: the diffstat
|
||||
// measured at the moment a run was committed or pushed. The reader's fixtures
|
||||
// are built here; nothing in this file re-derives a capture.
|
||||
func captureData(files []any, totals map[string]any) map[string]any {
|
||||
return map[string]any{
|
||||
"schema": events.ChangesCapturedSchema,
|
||||
"owner": "acme", "repo": "widget", "base": "main", "branch": "feat/2-x",
|
||||
"head_sha": "head-sha", "base_sha": "base-sha", "pr_number": 0,
|
||||
"captured_after": "commit-push",
|
||||
"files": files, "totals": totals, "truncated": false,
|
||||
}
|
||||
}
|
||||
|
||||
func modifiedFile(path string, additions, deletions int) map[string]any {
|
||||
return map[string]any{
|
||||
"path": path, "old_path": "", "status": "modified",
|
||||
"additions": additions, "deletions": deletions, "binary": false,
|
||||
}
|
||||
}
|
||||
|
||||
func insertCapture(t *testing.T, srv *Server, taskID int64, attempt int, stage string, data map[string]any) {
|
||||
t.Helper()
|
||||
insertTaskEvent(t, srv, events.Event{
|
||||
Kind: events.KindChangesCaptured, TaskID: taskID, Attempt: attempt, Stage: stage,
|
||||
At: railBase.Add(time.Duration(attempt) * time.Minute), Data: data,
|
||||
})
|
||||
}
|
||||
|
||||
// changesResponse is the endpoint's body as the page consumes it, decoded by
|
||||
// field name so the contract is asserted rather than substring-matched.
|
||||
type changesResponse struct {
|
||||
TaskID int64 `json:"task_id"`
|
||||
Attempt int `json:"attempt"`
|
||||
Found bool `json:"found"`
|
||||
Captures []captureViewJSON `json:"captures"`
|
||||
}
|
||||
|
||||
type captureViewJSON struct {
|
||||
CapturedAt time.Time `json:"captured_at"`
|
||||
CapturedAfter string `json:"captured_after"`
|
||||
Stage string `json:"stage"`
|
||||
Owner string `json:"owner"`
|
||||
Repo string `json:"repo"`
|
||||
Base string `json:"base"`
|
||||
Branch string `json:"branch"`
|
||||
HeadSHA string `json:"head_sha"`
|
||||
BaseSHA string `json:"base_sha"`
|
||||
PRNumber int `json:"pr_number"`
|
||||
RepoURL string `json:"repo_url"`
|
||||
PRURL string `json:"pr_url"`
|
||||
Totals changeTotalsJSON `json:"totals"`
|
||||
Truncated bool `json:"truncated"`
|
||||
Files []fileChangeJSON `json:"files"`
|
||||
}
|
||||
|
||||
type changeTotalsJSON struct {
|
||||
Files int `json:"files"`
|
||||
Additions int `json:"additions"`
|
||||
Deletions int `json:"deletions"`
|
||||
}
|
||||
|
||||
type fileChangeJSON struct {
|
||||
Path string `json:"path"`
|
||||
OldPath string `json:"old_path"`
|
||||
Status string `json:"status"`
|
||||
Additions int `json:"additions"`
|
||||
Deletions int `json:"deletions"`
|
||||
Binary bool `json:"binary"`
|
||||
}
|
||||
|
||||
func decodeChanges(t *testing.T, body []byte) changesResponse {
|
||||
t.Helper()
|
||||
var decoded changesResponse
|
||||
if err := json.Unmarshal(body, &decoded); err != nil {
|
||||
t.Fatalf("decode response: %v (%s)", err, body)
|
||||
}
|
||||
return decoded
|
||||
}
|
||||
|
||||
// TestHandleTaskChangesKeepsFoundFalseApartFromAnEmptyFileList pins the
|
||||
// distinction the changed-files view depends on: "no capture was recorded for
|
||||
// this attempt" is not "no files changed".
|
||||
func TestHandleTaskChangesKeepsFoundFalseApartFromAnEmptyFileList(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
current := twoAttemptTask(t, srv)
|
||||
insertCapture(t, srv, current.ID, 2, "commit",
|
||||
captureData([]any{}, map[string]any{"files": 0, "additions": 0, "deletions": 0}))
|
||||
|
||||
recorded := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2"))
|
||||
if recorded.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", recorded.Code, recorded.Body)
|
||||
}
|
||||
if raw := recorded.Body.String(); !strings.Contains(raw, `"files":[]`) {
|
||||
t.Errorf("body = %s, want an empty files array rather than null", raw)
|
||||
}
|
||||
body := decodeChanges(t, recorded.Body.Bytes())
|
||||
if !body.Found || body.Attempt != 2 {
|
||||
t.Fatalf("found = %v, attempt = %d; want true, 2", body.Found, body.Attempt)
|
||||
}
|
||||
if len(body.Captures) != 1 {
|
||||
t.Fatalf("captures = %d, want 1 (%s)", len(body.Captures), recorded.Body)
|
||||
}
|
||||
if len(body.Captures[0].Files) != 0 {
|
||||
t.Errorf("files = %+v, want none: a capture with an empty diff is still a capture", body.Captures[0].Files)
|
||||
}
|
||||
if body.Captures[0].Totals.Files != 0 {
|
||||
t.Errorf("totals.files = %d, want 0", body.Captures[0].Totals.Files)
|
||||
}
|
||||
|
||||
unrecorded := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=1"))
|
||||
if unrecorded.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", unrecorded.Code, unrecorded.Body)
|
||||
}
|
||||
if raw := unrecorded.Body.String(); !strings.Contains(raw, `"captures":[]`) {
|
||||
t.Errorf("body = %s, want an empty captures array rather than null", raw)
|
||||
}
|
||||
if got := decodeChanges(t, unrecorded.Body.Bytes()); got.Found || len(got.Captures) != 0 || got.Attempt != 1 {
|
||||
t.Errorf("attempt 1 = found %v with %d captures at attempt %d, want found false, none, attempt 1",
|
||||
got.Found, len(got.Captures), got.Attempt)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskChangesResolvesTheCurrentAttemptAndCarriesTheRecordedFields
|
||||
// pins the wire shape field by field, and that an absent attempt parameter
|
||||
// selects the task's current attempt.
|
||||
func TestHandleTaskChangesResolvesTheCurrentAttemptAndCarriesTheRecordedFields(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
current := twoAttemptTask(t, srv)
|
||||
data := captureData([]any{modifiedFile("internal/x.go", 12, 3)},
|
||||
map[string]any{"files": 1, "additions": 12, "deletions": 3})
|
||||
data["pr_number"] = 7
|
||||
insertCapture(t, srv, current.ID, 2, "commit-push", data)
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
body := decodeChanges(t, w.Body.Bytes())
|
||||
if body.TaskID != current.ID || body.Attempt != 2 || !body.Found {
|
||||
t.Fatalf("envelope = task %d attempt %d found %v; want %d, 2, true",
|
||||
body.TaskID, body.Attempt, body.Found, current.ID)
|
||||
}
|
||||
if len(body.Captures) != 1 {
|
||||
t.Fatalf("captures = %d, want 1 (%s)", len(body.Captures), w.Body)
|
||||
}
|
||||
capture := body.Captures[0]
|
||||
if !capture.CapturedAt.Equal(railBase.Add(2 * time.Minute)) {
|
||||
t.Errorf("captured_at = %v, want the capture event's own time", capture.CapturedAt)
|
||||
}
|
||||
if capture.CapturedAfter != "commit-push" || capture.Stage != "commit-push" {
|
||||
t.Errorf("captured_after = %q, stage = %q; want commit-push, commit-push", capture.CapturedAfter, capture.Stage)
|
||||
}
|
||||
if capture.Owner != "acme" || capture.Repo != "widget" || capture.Base != "main" || capture.Branch != "feat/2-x" {
|
||||
t.Errorf("repository fields = %q/%q base %q branch %q", capture.Owner, capture.Repo, capture.Base, capture.Branch)
|
||||
}
|
||||
if capture.HeadSHA != "head-sha" || capture.BaseSHA != "base-sha" || capture.PRNumber != 7 {
|
||||
t.Errorf("shas = %q/%q pr %d, want head-sha/base-sha/7", capture.HeadSHA, capture.BaseSHA, capture.PRNumber)
|
||||
}
|
||||
if capture.Totals.Files != 1 || capture.Totals.Additions != 12 || capture.Totals.Deletions != 3 {
|
||||
t.Errorf("totals = %+v, want 1/12/3", capture.Totals)
|
||||
}
|
||||
if capture.Truncated {
|
||||
t.Error("truncated = true for a capture that was not truncated")
|
||||
}
|
||||
if len(capture.Files) != 1 {
|
||||
t.Fatalf("files = %+v, want one", capture.Files)
|
||||
}
|
||||
file := capture.Files[0]
|
||||
if file.Path != "internal/x.go" || file.Status != "modified" || file.Additions != 12 || file.Deletions != 3 || file.Binary {
|
||||
t.Errorf("file = %+v, want internal/x.go modified +12 -3, not binary", file)
|
||||
}
|
||||
if file.OldPath != "" {
|
||||
t.Errorf("old_path = %q, want empty for a modify", file.OldPath)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskChangesKeepsTheFullTotalsOfATruncatedCapture pins that totals
|
||||
// are the producer's measurement of the whole change set, not a re-count of the
|
||||
// file entries this read happens to carry.
|
||||
func TestHandleTaskChangesKeepsTheFullTotalsOfATruncatedCapture(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
current := twoAttemptTask(t, srv)
|
||||
data := captureData([]any{modifiedFile("internal/x.go", 1, 1)},
|
||||
map[string]any{"files": 250, "additions": 900, "deletions": 10})
|
||||
data["truncated"] = true
|
||||
insertCapture(t, srv, current.ID, 2, "commit", data)
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
captures := decodeChanges(t, w.Body.Bytes()).Captures
|
||||
if len(captures) != 1 {
|
||||
t.Fatalf("captures = %d, want 1 (%s)", len(captures), w.Body)
|
||||
}
|
||||
capture := captures[0]
|
||||
if !capture.Truncated {
|
||||
t.Error("truncated = false for a capture that dropped file entries")
|
||||
}
|
||||
if len(capture.Files) != 1 {
|
||||
t.Fatalf("files = %d, want the single entry the producer capped the list to", len(capture.Files))
|
||||
}
|
||||
if capture.Totals.Files != 250 || capture.Totals.Additions != 900 || capture.Totals.Deletions != 10 {
|
||||
t.Errorf("totals = %+v, want the full 250/900/10 rather than a count of the 1 file carried", capture.Totals)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskChangesRefusesACaptureItCannotNameSchema pins the schema
|
||||
// marker's job: a payload whose shape this build does not know is not a
|
||||
// capture it may render. Rendering it would show a diffstat nobody read, so
|
||||
// the attempt reports that a capture was recorded and none was readable --
|
||||
// the panel's read-failure state -- rather than a capture of zeroes.
|
||||
func TestHandleTaskChangesRefusesACaptureItCannotNameSchema(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(map[string]any)
|
||||
}{
|
||||
{
|
||||
name: "no schema at all",
|
||||
mutate: func(data map[string]any) { delete(data, "schema") },
|
||||
},
|
||||
{
|
||||
name: "a schema this build does not know",
|
||||
mutate: func(data map[string]any) { data["schema"] = "archie/task-changes@2" },
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
current := twoAttemptTask(t, srv)
|
||||
data := captureData([]any{modifiedFile("internal/x.go", 12, 3)},
|
||||
map[string]any{"files": 1, "additions": 12, "deletions": 3})
|
||||
tt.mutate(data)
|
||||
insertCapture(t, srv, current.ID, 2, "commit", data)
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
body := decodeChanges(t, w.Body.Bytes())
|
||||
if !body.Found {
|
||||
t.Error("found = false although a capture event was recorded for the attempt")
|
||||
}
|
||||
if len(body.Captures) != 0 {
|
||||
t.Errorf("captures = %+v, want none: a payload this build cannot name must not be rendered as a capture",
|
||||
body.Captures)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskChangesRefusesAPayloadWhoseKeySetDrifted pins the other half
|
||||
// of the schema guard: the schema names the shape, the exact key set proves
|
||||
// the shape arrived. A key renamed, dropped or added means the payload is not
|
||||
// the one this reader knows, and reading it leniently is how a lost
|
||||
// truncation marker becomes "not truncated" and a moved cap becomes "every
|
||||
// file, none dropped".
|
||||
func TestHandleTaskChangesRefusesAPayloadWhoseKeySetDrifted(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(map[string]any)
|
||||
}{
|
||||
{
|
||||
name: "the truncation marker renamed",
|
||||
mutate: func(data map[string]any) {
|
||||
delete(data, "truncated")
|
||||
data["truncated_files"] = true
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "the file list dropped",
|
||||
mutate: func(data map[string]any) { delete(data, "files") },
|
||||
},
|
||||
{
|
||||
name: "a key this reader does not know",
|
||||
mutate: func(data map[string]any) { data["schema_version"] = 1 },
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
current := twoAttemptTask(t, srv)
|
||||
data := captureData([]any{modifiedFile("internal/x.go", 1, 0)},
|
||||
map[string]any{"files": task.MaxCapturedFiles + 1, "additions": 1, "deletions": 0})
|
||||
tt.mutate(data)
|
||||
insertCapture(t, srv, current.ID, 2, "commit", data)
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
body := decodeChanges(t, w.Body.Bytes())
|
||||
if !body.Found {
|
||||
t.Error("found = false although a capture event was recorded for the attempt")
|
||||
}
|
||||
if len(body.Captures) != 0 {
|
||||
t.Errorf("captures = %+v, want none: a payload whose keys drifted must not be read as zero values",
|
||||
body.Captures)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskChangesLinksThePullRequestOfTheFinalCapture is the reader half
|
||||
// of the requirement the commit-time captures cannot meet: their pr_number is
|
||||
// necessarily 0, and the capture OpenPR takes once the number exists is what
|
||||
// gives the panel a pull-request link.
|
||||
func TestHandleTaskChangesLinksThePullRequestOfTheFinalCapture(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.ConfigSource = func(_ context.Context) (ConfigView, bool, error) {
|
||||
return multiIdentityView(), true, nil
|
||||
}
|
||||
current := twoAttemptTask(t, srv)
|
||||
|
||||
beforePR := captureData([]any{modifiedFile("internal/x.go", 1, 0)},
|
||||
map[string]any{"files": 1, "additions": 1, "deletions": 0})
|
||||
beforePR["captured_after"] = "commit-push"
|
||||
insertCapture(t, srv, current.ID, 2, "commit-push", beforePR)
|
||||
|
||||
withPR := captureData([]any{modifiedFile("internal/x.go", 1, 0)},
|
||||
map[string]any{"files": 1, "additions": 1, "deletions": 0})
|
||||
withPR["captured_after"] = "open-pr"
|
||||
withPR["pr_number"] = 7
|
||||
insertCapture(t, srv, current.ID, 2, "open-pr", withPR)
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
captures := decodeChanges(t, w.Body.Bytes()).Captures
|
||||
if len(captures) != 2 {
|
||||
t.Fatalf("captures = %d, want both the push and the open-pr capture (%s)", len(captures), w.Body)
|
||||
}
|
||||
if captures[0].PRNumber != 0 || captures[0].PRURL != "" {
|
||||
t.Errorf("the push capture = pr %d url %q, want no PR: it was taken before one existed",
|
||||
captures[0].PRNumber, captures[0].PRURL)
|
||||
}
|
||||
if captures[1].CapturedAfter != "open-pr" || captures[1].PRNumber != 7 {
|
||||
t.Fatalf("the final capture = %q pr %d, want open-pr, 7", captures[1].CapturedAfter, captures[1].PRNumber)
|
||||
}
|
||||
if captures[1].PRURL != "https://gitea.example/acme/widget/pulls/7" {
|
||||
t.Errorf("pr_url = %q, want the pull request the capture names", captures[1].PRURL)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskChangesRefusesACaptureThatLostItsFileCap pins the cap from the
|
||||
// reading side: `files` is bounded at task.MaxCapturedFiles by the producer,
|
||||
// and a payload carrying more than that is one whose cap was lost. Rendering
|
||||
// it would advertise the loss as a complete capture of every file.
|
||||
func TestHandleTaskChangesRefusesACaptureThatLostItsFileCap(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
current := twoAttemptTask(t, srv)
|
||||
files := make([]any, 0, task.MaxCapturedFiles+1)
|
||||
for i := range task.MaxCapturedFiles + 1 {
|
||||
files = append(files, modifiedFile(fmt.Sprintf("file-%03d.go", i), 1, 0))
|
||||
}
|
||||
insertCapture(t, srv, current.ID, 2, "commit",
|
||||
captureData(files, map[string]any{"files": len(files), "additions": len(files), "deletions": 0}))
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
body := decodeChanges(t, w.Body.Bytes())
|
||||
if !body.Found {
|
||||
t.Error("found = false although a capture event was recorded for the attempt")
|
||||
}
|
||||
if len(body.Captures) != 0 {
|
||||
t.Errorf("captures = %d entries, want none: a payload over the cap is one whose cap was lost",
|
||||
len(body.Captures))
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskChangesSkipsCapturesWithNoReadablePayload pins the degrade
|
||||
// rule: a capture whose data is absent or malformed is skipped rather than
|
||||
// failing the read, and the attempt still reports that a capture was recorded.
|
||||
func TestHandleTaskChangesSkipsCapturesWithNoReadablePayload(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
current := twoAttemptTask(t, srv)
|
||||
|
||||
insertTaskEvent(t, srv, events.Event{
|
||||
Kind: events.KindChangesCaptured, TaskID: current.ID, Attempt: 2, Stage: "commit",
|
||||
At: railBase, Data: map[string]any{"files": "not-an-array"},
|
||||
})
|
||||
insertTaskEvent(t, srv, events.Event{
|
||||
Kind: events.KindChangesCaptured, TaskID: current.ID, Attempt: 2, Stage: "commit",
|
||||
At: railBase.Add(time.Second),
|
||||
})
|
||||
insertCapture(t, srv, current.ID, 2, "commit",
|
||||
captureData([]any{modifiedFile("internal/kept.go", 1, 0)},
|
||||
map[string]any{"files": 1, "additions": 1, "deletions": 0}))
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
body := decodeChanges(t, w.Body.Bytes())
|
||||
if !body.Found {
|
||||
t.Error("found = false although a capture event was recorded for the attempt")
|
||||
}
|
||||
if len(body.Captures) != 1 {
|
||||
t.Fatalf("captures = %+v, want only the readable one", body.Captures)
|
||||
}
|
||||
if got := body.Captures[0].Files[0].Path; got != "internal/kept.go" {
|
||||
t.Errorf("kept file = %q, want internal/kept.go", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskChangesLinksTheCaptureRepositoryAndPullRequest reuses the task
|
||||
// list's own forge projection: the page needs a repository link and, once a PR
|
||||
// exists, a pull-request link, and it must get them from the same source the
|
||||
// task list uses rather than a second one.
|
||||
func TestHandleTaskChangesLinksTheCaptureRepositoryAndPullRequest(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.ConfigSource = func(_ context.Context) (ConfigView, bool, error) {
|
||||
return multiIdentityView(), true, nil
|
||||
}
|
||||
current := twoAttemptTask(t, srv)
|
||||
|
||||
for _, prNumber := range []int{0, 7} {
|
||||
data := captureData([]any{modifiedFile("internal/x.go", 1, 0)},
|
||||
map[string]any{"files": 1, "additions": 1, "deletions": 0})
|
||||
data["pr_number"] = prNumber
|
||||
insertCapture(t, srv, current.ID, 2, "commit", data)
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("pr %d: status = %d, body %s", prNumber, w.Code, w.Body)
|
||||
}
|
||||
captures := decodeChanges(t, w.Body.Bytes()).Captures
|
||||
capture := captures[len(captures)-1]
|
||||
if capture.RepoURL != "https://gitea.example/acme/widget" {
|
||||
t.Errorf("pr %d: repo_url = %q, want the task's gitea repository", prNumber, capture.RepoURL)
|
||||
}
|
||||
wantPR := ""
|
||||
if prNumber > 0 {
|
||||
wantPR = "https://gitea.example/acme/widget/pulls/7"
|
||||
}
|
||||
if capture.PRURL != wantPR {
|
||||
t.Errorf("pr %d: pr_url = %q, want %q", prNumber, capture.PRURL, wantPR)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
// TestHandleTaskDebugReturnsTheWholeRecordAndEveryEvent pins R7's read: the
|
||||
// stored task record verbatim, and EVERY event of the task rather than only the
|
||||
// selected attempt's -- each event carries its own attempt, so a filtered list
|
||||
// would hide the very provenance the view exists to show.
|
||||
func TestHandleTaskDebugReturnsTheWholeRecordAndEveryEvent(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
current := twoAttemptTask(t, srv)
|
||||
|
||||
insertTaskEvent(t, srv, events.Event{
|
||||
Kind: events.KindStageStart, TaskID: current.ID, Attempt: 1, Stage: "prepare", At: railBase,
|
||||
})
|
||||
insertTaskEvent(t, srv, events.Event{
|
||||
Kind: events.KindAgentFinish, TaskID: current.ID, Attempt: 0, At: railBase.Add(time.Second),
|
||||
Data: map[string]any{"status": "ok"},
|
||||
})
|
||||
insertTaskEvent(t, srv, events.Event{
|
||||
Kind: events.KindStageStart, TaskID: current.ID, Attempt: 2, Stage: "implement",
|
||||
At: railBase.Add(2 * time.Second),
|
||||
})
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(current.ID, "/debug?attempt=1"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
raw := w.Body.String()
|
||||
if strings.Contains(raw, `"entries"`) {
|
||||
t.Errorf("body carries a log payload: %s", raw)
|
||||
}
|
||||
|
||||
var body struct {
|
||||
TaskID int64 `json:"task_id"`
|
||||
Attempt int `json:"attempt"`
|
||||
Task workflow.Task `json:"task"`
|
||||
Events []struct {
|
||||
Kind string `json:"kind"`
|
||||
Attempt int `json:"attempt"`
|
||||
} `json:"events"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v (%s)", err, w.Body)
|
||||
}
|
||||
if body.TaskID != current.ID || body.Attempt != 1 {
|
||||
t.Errorf("envelope = task %d attempt %d, want task %d attempt 1 (the selected attempt)",
|
||||
body.TaskID, body.Attempt, current.ID)
|
||||
}
|
||||
if body.Task.ID != current.ID || body.Task.Status != workflow.StatusRunning || body.Task.Attempt != 2 {
|
||||
t.Errorf("task record = id %d status %q attempt %d, want the stored record (%d, running, 2)",
|
||||
body.Task.ID, body.Task.Status, body.Task.Attempt, current.ID)
|
||||
}
|
||||
if len(body.Events) != 3 {
|
||||
t.Fatalf("events = %d, want all 3 including the one recorded against a different attempt (%s)",
|
||||
len(body.Events), w.Body)
|
||||
}
|
||||
wantAttempts := []int{1, 0, 2}
|
||||
for i, want := range wantAttempts {
|
||||
if body.Events[i].Attempt != want {
|
||||
t.Errorf("event %d attempt = %d, want %d (order and attribution preserved)", i, body.Events[i].Attempt, want)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(raw, `"attempt":0`) {
|
||||
t.Errorf("body = %s, want attempt carried on every event so an unattributed one stays distinguishable", raw)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskDebugResolvesTheCurrentAttemptWithoutAParameter pins that the
|
||||
// envelope reports the attempt the page selected, defaulting to the task's
|
||||
// current attempt exactly as the log read does.
|
||||
func TestHandleTaskDebugResolvesTheCurrentAttemptWithoutAParameter(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
current := twoAttemptTask(t, srv)
|
||||
|
||||
w := getTaskAPI(t, srv, taskRoute(current.ID, "/debug"))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
var body struct {
|
||||
Attempt int `json:"attempt"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v (%s)", err, w.Body)
|
||||
}
|
||||
if body.Attempt != current.Attempt {
|
||||
t.Errorf("attempt = %d, want the task's current attempt %d", body.Attempt, current.Attempt)
|
||||
}
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
)
|
||||
|
||||
// TestHandleTaskLogsDistinguishesNoLogForTheAttempt covers the dashboard's
|
||||
// misleading report. A process that HAS a task-log reader and an attempt that
|
||||
// genuinely has no file on disk is a different answer from a process that
|
||||
// cannot read logs at all, and only the second one is "logging is not enabled
|
||||
// here". The response has to carry that difference or the page cannot state it.
|
||||
func TestHandleTaskLogsDistinguishesNoLogForTheAttempt(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
srv.TaskLogs = logging.NewTaskRegistry(t.TempDir(), logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// No log is ever opened for this task: the reader works, the attempt has
|
||||
// no file.
|
||||
|
||||
w := getTaskLogs(t, srv, task.ID, nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
var body struct {
|
||||
Disabled bool `json:"disabled"`
|
||||
Found bool `json:"found"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v (%s)", err, w.Body)
|
||||
}
|
||||
if body.Disabled {
|
||||
t.Error("disabled = true for a process that has a task-log reader; that is the report the page turns into \"logging was not enabled for this run\"")
|
||||
}
|
||||
if body.Found {
|
||||
t.Error("found = true for an attempt with no log file on disk")
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), `"found"`) {
|
||||
t.Errorf("body = %s, want an explicit found marker so the page can say the attempt has no log rather than that logging is off", w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskLogsDownloadServesTheAttemptLog pins the deliverable: the
|
||||
// endpoint hands back the attempt's log as a file download. The route falling
|
||||
// through to the SPA asset handler would answer 200 with an HTML page, so this
|
||||
// asserts on the attachment headers and the body, not merely on the status.
|
||||
func TestHandleTaskLogsDownloadServesTheAttemptLog(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
logs := logging.NewTaskRegistry(t.TempDir(), logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
srv.TaskLogs = logs
|
||||
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := logs.Open(task.ID, task.Attempt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
logs.Write(ctx, task.ID, logging.Entry{Level: "ERROR", Message: "gate failed"})
|
||||
if err := logs.Close(task.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
url := "/api/tasks/" + strconv.FormatInt(task.ID, 10) + "/logs/download"
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("GET %s = %d, body %s", url, w.Code, w.Body)
|
||||
}
|
||||
wantName := "task-" + strconv.FormatInt(task.ID, 10) + "-attempt-" + strconv.Itoa(task.Attempt) + ".log"
|
||||
if got := w.Header().Get("Content-Disposition"); got != `attachment; filename="`+wantName+`"` {
|
||||
t.Errorf("Content-Disposition = %q, want an attachment named %q", got, wantName)
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), "gate failed") {
|
||||
t.Errorf("download body = %s, want the attempt's own log content", w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskLogsDownloadWithoutALogAnswersNotFound keeps the download
|
||||
// honest: there is nothing to attach, so it says so rather than handing back a
|
||||
// zero-byte file that looks like a successful download of nothing.
|
||||
func TestHandleTaskLogsDownloadWithoutALogAnswersNotFound(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
srv.TaskLogs = logging.NewTaskRegistry(t.TempDir(), logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
url := "/api/tasks/" + strconv.FormatInt(task.ID, 10) + "/logs/download"
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("GET %s with no log = %d, want 404", url, w.Code)
|
||||
}
|
||||
// The response is an error, not a file. Attachment headers are written
|
||||
// before the read (the body streams, so the size is unknown up front), and
|
||||
// leaving them on a 404 hands the caller a .log attachment containing only
|
||||
// the error text.
|
||||
if got := w.Header().Get("Content-Disposition"); got != "" {
|
||||
t.Errorf("Content-Disposition = %q on a 404, want it cleared so the error is not presented as a download", got)
|
||||
}
|
||||
if got := w.Header().Get("Content-Type"); strings.Contains(got, "ndjson") {
|
||||
t.Errorf("Content-Type = %q on a 404, want the error content type rather than the log's", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskLogsDownloadWithoutAReaderAnswersServiceUnavailable is the
|
||||
// degradation the boundary permits: a process with no task-log contract answers
|
||||
// 503 rather than 404, because "I cannot read logs" and "there is no log" are
|
||||
// not the same claim.
|
||||
func TestHandleTaskLogsDownloadWithoutAReaderAnswersServiceUnavailable(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
url := "/api/tasks/" + strconv.FormatInt(task.ID, 10) + "/logs/download"
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusServiceUnavailable {
|
||||
body, _ := io.ReadAll(w.Result().Body)
|
||||
t.Fatalf("GET %s without a reader = %d (%s), want 503", url, w.Code, body)
|
||||
}
|
||||
// Same rule as the 404: an unavailable reader is an error, not a file.
|
||||
if got := w.Header().Get("Content-Disposition"); got != "" {
|
||||
t.Errorf("Content-Disposition = %q on a 503, want it cleared so the error is not presented as a download", got)
|
||||
}
|
||||
}
|
||||
@@ -1,263 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
)
|
||||
|
||||
func TestHandleTaskLogsReturnsEntriesForLatestAttemptByDefault(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
baseDir := t.TempDir()
|
||||
logs := logging.NewTaskRegistry(baseDir, logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
srv.TaskLogs = logs
|
||||
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := logs.Open(task.ID, task.Attempt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
logs.Write(ctx, task.ID, logging.Entry{
|
||||
Level: "ERROR", Message: "gate failed", Fields: map[string]any{"component": "gate"},
|
||||
})
|
||||
if err := logs.Close(task.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
w := getTaskLogs(t, srv, task.ID, nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
var body struct {
|
||||
Entries []logging.Entry `json:"entries"`
|
||||
Attempt int `json:"attempt"`
|
||||
File string `json:"file"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if body.Attempt != task.Attempt {
|
||||
t.Errorf("attempt = %d, want %d (task's current attempt, resolved without a query param)", body.Attempt, task.Attempt)
|
||||
}
|
||||
if len(body.Entries) != 1 || body.Entries[0].Message != "gate failed" {
|
||||
t.Fatalf("entries = %+v, want one entry with message %q", body.Entries, "gate failed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleTaskLogsHonoursExplicitAttempt(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
baseDir := t.TempDir()
|
||||
logs := logging.NewTaskRegistry(baseDir, logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
srv.TaskLogs = logs
|
||||
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Write directly to attempt 1's file on disk -- a prior, already-closed
|
||||
// attempt that the task's current Attempt field no longer points at.
|
||||
sink, err := logging.NewTaskSink(baseDir, task.ID, 1, logging.TaskSinkOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sink.Logger().Warn("first attempt failed")
|
||||
if err := sink.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
w := getTaskLogs(t, srv, task.ID, map[string]string{"attempt": "1"})
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
var body struct {
|
||||
Entries []logging.Entry `json:"entries"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if len(body.Entries) != 1 || body.Entries[0].Message != "first attempt failed" {
|
||||
t.Fatalf("entries = %+v, want one entry with message %q", body.Entries, "first attempt failed")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskLogsFiltersByStageAndKeepsTheAttempt pins R5's read half: the
|
||||
// stage parameter reaches the reader's query, narrows the attempt's entries to
|
||||
// the lines that record that stage, and leaves both the attempt it resolved and
|
||||
// the file's existence (found) untouched -- a filter that matches nothing is
|
||||
// "nothing matching this filter", never "this deployment cannot read logs".
|
||||
func TestHandleTaskLogsFiltersByStageAndKeepsTheAttempt(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
baseDir := t.TempDir()
|
||||
srv.TaskLogs = logging.NewTaskRegistry(baseDir, logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Written to attempt 1's file: an earlier attempt the task's current
|
||||
// Attempt field does not point at, so the attempt must be requested.
|
||||
sink, err := logging.NewTaskSink(baseDir, task.ID, 1, logging.TaskSinkOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sink.Logger().Warn("committing the worktree", "stage", "commit")
|
||||
sink.Logger().Warn("agent produced a diff", "component", "agent")
|
||||
if err := sink.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
query map[string]string
|
||||
wantCount int
|
||||
wantFound bool
|
||||
}{
|
||||
{
|
||||
name: "no stage filter",
|
||||
query: map[string]string{"attempt": "1"},
|
||||
wantCount: 2,
|
||||
wantFound: true,
|
||||
},
|
||||
{
|
||||
name: "the stage this attempt recorded",
|
||||
query: map[string]string{"attempt": "1", "stage": "commit"},
|
||||
wantCount: 1,
|
||||
wantFound: true,
|
||||
},
|
||||
{
|
||||
name: "a stage no entry records",
|
||||
query: map[string]string{"attempt": "1", "stage": "implement"},
|
||||
wantCount: 0,
|
||||
wantFound: true,
|
||||
},
|
||||
{
|
||||
name: "a stage filter on an attempt with no log at all",
|
||||
query: map[string]string{"attempt": "2", "stage": "commit"},
|
||||
wantCount: 0,
|
||||
wantFound: false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
w := getTaskLogs(t, srv, task.ID, tt.query)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
var body struct {
|
||||
Entries []logging.Entry `json:"entries"`
|
||||
Attempt int `json:"attempt"`
|
||||
Found bool `json:"found"`
|
||||
Disabled bool `json:"disabled"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v (%s)", err, w.Body)
|
||||
}
|
||||
wantAttempt := 1
|
||||
if tt.query["attempt"] == "2" {
|
||||
wantAttempt = 2
|
||||
}
|
||||
if body.Attempt != wantAttempt {
|
||||
t.Errorf("attempt = %d, want the requested attempt %d", body.Attempt, wantAttempt)
|
||||
}
|
||||
if len(body.Entries) != tt.wantCount {
|
||||
t.Errorf("entries = %d, want %d (%s)", len(body.Entries), tt.wantCount, w.Body)
|
||||
}
|
||||
if body.Found != tt.wantFound {
|
||||
t.Errorf("found = %v, want %v: a filter that matches nothing is not a missing log", body.Found, tt.wantFound)
|
||||
}
|
||||
if body.Disabled {
|
||||
t.Error("disabled = true for a process that has a task-log reader")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleTaskLogsBadID(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/tasks/not-a-number/logs", nil)
|
||||
req.SetPathValue("id", "not-a-number")
|
||||
w := httptest.NewRecorder()
|
||||
srv.handleTaskLogs(w, req)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("status = %d, want %d", w.Code, http.StatusBadRequest)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleTaskLogsUnknownTask(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.TaskLogs = logging.NewTaskRegistry(t.TempDir(), logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
w := getTaskLogs(t, srv, 999, nil)
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("status = %d, want %d", w.Code, http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskLogsTaskLoggingDisabled guards the same "optional feature,
|
||||
// not an error" behaviour handleLogs already has for the daemon-wide log:
|
||||
// a deployment that never configured task logging must not turn "why did
|
||||
// this task park?" into a 500 for every task.
|
||||
func TestHandleTaskLogsTaskLoggingDisabled(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
w := getTaskLogs(t, srv, task.ID, nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
var body struct {
|
||||
Disabled bool `json:"disabled"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if !body.Disabled {
|
||||
t.Error("disabled = false, want true when TaskLogs is not configured")
|
||||
}
|
||||
}
|
||||
|
||||
func getTaskLogs(t *testing.T, srv *Server, taskID int64, query map[string]string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
url := "/api/tasks/" + strconv.FormatInt(taskID, 10) + "/logs"
|
||||
if len(query) > 0 {
|
||||
q := make([]byte, 0)
|
||||
sep := "?"
|
||||
for k, v := range query {
|
||||
q = append(q, []byte(sep+k+"="+v)...)
|
||||
sep = "&"
|
||||
}
|
||||
url += string(q)
|
||||
}
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, url, nil)
|
||||
req.SetPathValue("id", strconv.FormatInt(taskID, 10))
|
||||
w := httptest.NewRecorder()
|
||||
srv.handleTaskLogs(w, req)
|
||||
return w
|
||||
}
|
||||
@@ -1,238 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
)
|
||||
|
||||
func TestAuthorizeTaskMutationOrigin(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
trustForwardedDirect bool
|
||||
forwardedProto string
|
||||
forwardedHost string
|
||||
requestHost string
|
||||
tls bool
|
||||
origin string
|
||||
csrfHeader string
|
||||
contentType string
|
||||
wantStatus int
|
||||
}{
|
||||
{
|
||||
name: "1. proxied https: trust enabled directly, X-Forwarded-Proto https, plain HTTP, Origin https",
|
||||
trustForwardedDirect: true,
|
||||
forwardedProto: "https",
|
||||
requestHost: "archie.catlow.cloud",
|
||||
tls: false,
|
||||
origin: "https://archie.catlow.cloud",
|
||||
csrfHeader: "1",
|
||||
contentType: "application/json",
|
||||
wantStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "1c. proxied https: comma-separated X-Forwarded-Proto list",
|
||||
trustForwardedDirect: true,
|
||||
forwardedProto: "https, http",
|
||||
requestHost: "archie.catlow.cloud",
|
||||
tls: false,
|
||||
origin: "https://archie.catlow.cloud",
|
||||
csrfHeader: "1",
|
||||
contentType: "application/json",
|
||||
wantStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "1d. proxied https: X-Forwarded-Host trusted and matched",
|
||||
trustForwardedDirect: true,
|
||||
forwardedProto: "https",
|
||||
forwardedHost: "archie.catlow.cloud",
|
||||
requestHost: "10.36.25.188:8484",
|
||||
tls: false,
|
||||
origin: "https://archie.catlow.cloud",
|
||||
csrfHeader: "1",
|
||||
contentType: "application/json",
|
||||
wantStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "2. direct http: trust disabled, no forwarded header, Origin http",
|
||||
trustForwardedDirect: false,
|
||||
requestHost: "localhost:8484",
|
||||
tls: false,
|
||||
origin: "http://localhost:8484",
|
||||
csrfHeader: "1",
|
||||
contentType: "application/json",
|
||||
wantStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "3. direct https: trust disabled, r.TLS set, Origin https",
|
||||
trustForwardedDirect: false,
|
||||
requestHost: "localhost:8484",
|
||||
tls: true,
|
||||
origin: "https://localhost:8484",
|
||||
csrfHeader: "1",
|
||||
contentType: "application/json",
|
||||
wantStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "4. SPOOFED: trust disabled, attacker sends X-Forwarded-Proto https, plain HTTP, Origin https",
|
||||
trustForwardedDirect: false,
|
||||
forwardedProto: "https",
|
||||
requestHost: "localhost:8484",
|
||||
tls: false,
|
||||
origin: "https://localhost:8484",
|
||||
csrfHeader: "1",
|
||||
contentType: "application/json",
|
||||
wantStatus: http.StatusForbidden,
|
||||
},
|
||||
{
|
||||
name: "4b. SPOOFED HOST: trust disabled, attacker sends X-Forwarded-Host, plain HTTP",
|
||||
trustForwardedDirect: false,
|
||||
forwardedHost: "target.example.com",
|
||||
requestHost: "localhost:8484",
|
||||
tls: false,
|
||||
origin: "http://target.example.com",
|
||||
csrfHeader: "1",
|
||||
contentType: "application/json",
|
||||
wantStatus: http.StatusForbidden,
|
||||
},
|
||||
{
|
||||
name: "5. missing CSRF header: request rejected",
|
||||
trustForwardedDirect: true,
|
||||
forwardedProto: "https",
|
||||
requestHost: "archie.catlow.cloud",
|
||||
tls: false,
|
||||
origin: "https://archie.catlow.cloud",
|
||||
csrfHeader: "",
|
||||
contentType: "application/json",
|
||||
wantStatus: http.StatusForbidden,
|
||||
},
|
||||
{
|
||||
name: "6. genuinely cross-origin request: request rejected",
|
||||
trustForwardedDirect: true,
|
||||
forwardedProto: "https",
|
||||
requestHost: "archie.catlow.cloud",
|
||||
tls: false,
|
||||
origin: "https://evil.example.com",
|
||||
csrfHeader: "1",
|
||||
contentType: "application/json",
|
||||
wantStatus: http.StatusForbidden,
|
||||
},
|
||||
{
|
||||
name: "7. invalid Origin URI: containing userinfo",
|
||||
trustForwardedDirect: true,
|
||||
forwardedProto: "https",
|
||||
requestHost: "archie.catlow.cloud",
|
||||
tls: false,
|
||||
origin: "https://user:pass@archie.catlow.cloud",
|
||||
csrfHeader: "1",
|
||||
contentType: "application/json",
|
||||
wantStatus: http.StatusForbidden,
|
||||
},
|
||||
{
|
||||
name: "8. invalid Origin URI: containing path",
|
||||
trustForwardedDirect: true,
|
||||
forwardedProto: "https",
|
||||
requestHost: "archie.catlow.cloud",
|
||||
tls: false,
|
||||
origin: "https://archie.catlow.cloud/path",
|
||||
csrfHeader: "1",
|
||||
contentType: "application/json",
|
||||
wantStatus: http.StatusForbidden,
|
||||
},
|
||||
{
|
||||
name: "9. unsupported media type: non-JSON body",
|
||||
trustForwardedDirect: true,
|
||||
forwardedProto: "https",
|
||||
requestHost: "archie.catlow.cloud",
|
||||
tls: false,
|
||||
origin: "https://archie.catlow.cloud",
|
||||
csrfHeader: "1",
|
||||
contentType: "text/plain",
|
||||
wantStatus: http.StatusUnsupportedMediaType,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "queued", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 1)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("failed to fetch enqueued task: %v", err)
|
||||
}
|
||||
|
||||
srv.TrustForwardedHeaders = tc.trustForwardedDirect
|
||||
|
||||
path := "/api/tasks/" + strconv.FormatInt(task.ID, 10) + "/action"
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodPost, path, strings.NewReader(`{"action":"cancel"}`))
|
||||
|
||||
if tc.requestHost != "" {
|
||||
req.Host = tc.requestHost
|
||||
}
|
||||
if tc.tls {
|
||||
req.TLS = &tls.ConnectionState{}
|
||||
}
|
||||
if tc.forwardedProto != "" {
|
||||
req.Header.Set("X-Forwarded-Proto", tc.forwardedProto)
|
||||
}
|
||||
if tc.forwardedHost != "" {
|
||||
req.Header.Set("X-Forwarded-Host", tc.forwardedHost)
|
||||
}
|
||||
if tc.origin != "" {
|
||||
req.Header.Set("Origin", tc.origin)
|
||||
}
|
||||
if tc.csrfHeader != "" {
|
||||
req.Header.Set("X-Archie-CSRF", tc.csrfHeader)
|
||||
}
|
||||
if tc.contentType != "" {
|
||||
req.Header.Set("Content-Type", tc.contentType)
|
||||
}
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != tc.wantStatus {
|
||||
t.Fatalf("status = %d, want %d (body %q)", w.Code, tc.wantStatus, w.Body.String())
|
||||
}
|
||||
if tc.wantStatus >= http.StatusBadRequest {
|
||||
if got := w.Header().Get("Content-Type"); got != "text/plain; charset=utf-8" {
|
||||
t.Errorf("Content-Type = %q, want text/plain error response", got)
|
||||
}
|
||||
if got := w.Header().Get("X-Content-Type-Options"); got != "nosniff" {
|
||||
t.Errorf("X-Content-Type-Options = %q, want nosniff", got)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkRequestOriginProxy(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
creator := &recordingWorkRequestCreator{}
|
||||
srv.WorkRequests = creator
|
||||
srv.ControlPlane = workflowControlPlane(t, workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "implement", YAML: "id: implement\nsteps:\n - type: implement.prepare\n"}}})
|
||||
srv.TrustForwardedHeaders = true
|
||||
|
||||
body := `{"identity":"archie","repository":"acme/widget","workflow":"implement","title":"Fix login","instructions":"Reproduce and fix it."}`
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/work-requests", strings.NewReader(body))
|
||||
req.Host = "archie.catlow.cloud"
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Archie-CSRF", "1")
|
||||
req.Header.Set("X-Forwarded-Proto", "https")
|
||||
req.Header.Set("Origin", "https://archie.catlow.cloud")
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("status = %d, want 201 (body %q)", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -1,414 +0,0 @@
|
||||
package webui
|
||||
|
||||
// Tests for the task-timeline route. The dashboard's "Click a row for its
|
||||
// timeline" interaction depends on GET /api/tasks/{id} returning exactly that
|
||||
// task's events, ordered, and on the literal /api/tasks/clear route beating
|
||||
// the {id} wildcard.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
// A process with no configuration of its own still has to render the links,
|
||||
// or the extracted dashboard loses every click-through to the issue and the
|
||||
// pull request it opened. The daemon's published projection is where they
|
||||
// come from once the holder is gone.
|
||||
func TestTaskURLsFallBackToThePublishedProjection(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
view ConfigView
|
||||
ok bool
|
||||
err error
|
||||
wantPR string
|
||||
wantURL string
|
||||
}{
|
||||
{
|
||||
name: "published projection",
|
||||
view: ConfigView{Identity: IdentityView{ForgeType: "github", ForgeHost: "https://github.example"}},
|
||||
ok: true,
|
||||
wantURL: "https://github.example/acme/widget",
|
||||
wantPR: "https://github.example/acme/widget/pull/34",
|
||||
},
|
||||
{
|
||||
// A document published before the deployment carried per-identity
|
||||
// forges says so and carries none, so there is nothing to
|
||||
// attribute this task to. Withholding beats guessing.
|
||||
name: "a multi-identity document with no per-identity forges is withheld",
|
||||
view: ConfigView{
|
||||
Identity: IdentityView{ForgeType: "github", ForgeHost: "https://github.example"},
|
||||
MultiIdentity: true,
|
||||
},
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
name: "no snapshot published yet",
|
||||
},
|
||||
{
|
||||
name: "snapshot read failed",
|
||||
err: errors.New("state store down"),
|
||||
},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv := &Server{ConfigSource: func(context.Context) (ConfigView, bool, error) {
|
||||
return tc.view, tc.ok, tc.err
|
||||
}}
|
||||
task := workflow.Task{Owner: "acme", Repo: "widget", IssueNumber: 12, PRNumber: 34}
|
||||
forge := srv.resolveForge(t.Context())
|
||||
repoURL, _, prURL := taskURLs(task, forge(task))
|
||||
if repoURL != tc.wantURL || prURL != tc.wantPR {
|
||||
t.Fatalf("repo/PR URLs = %q, %q; want %q, %q", repoURL, prURL, tc.wantURL, tc.wantPR)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// multiIdentityView is a two-forge deployment as the daemon publishes it: the
|
||||
// default identity on GitHub, and a Gitea identity owning one repository.
|
||||
func multiIdentityView() ConfigView {
|
||||
return ConfigView{
|
||||
Identity: IdentityView{ForgeType: "github", ForgeHost: "https://github.example"},
|
||||
MultiIdentity: true,
|
||||
Identities: []ForgeIdentityView{
|
||||
{
|
||||
Name: "gitea-bot", ForgeType: "gitea", ForgeHost: "https://gitea.example",
|
||||
Repos: []ForgeRepoView{{Owner: "acme", Name: "widget"}, {Owner: "acme", Name: "shared"}},
|
||||
},
|
||||
{
|
||||
Name: "github-bot", ForgeType: "github", ForgeHost: "https://github.example",
|
||||
Repos: []ForgeRepoView{{Owner: "beta", Name: "svc"}, {Owner: "acme", Name: "shared"}},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolveForgeMatchesEachTaskToItsOwningIdentity ports the matching rules
|
||||
// recovered from 57d9be5's forgeConfigForTask onto the published projection:
|
||||
// exact identity name first, then repository ownership, with an ambiguous
|
||||
// match falling back to the default forge. Without them every row in a
|
||||
// multi-identity deployment renders no link at all.
|
||||
func TestResolveForgeMatchesEachTaskToItsOwningIdentity(t *testing.T) {
|
||||
srv := &Server{ConfigSource: func(context.Context) (ConfigView, bool, error) {
|
||||
return multiIdentityView(), true, nil
|
||||
}}
|
||||
forge := srv.resolveForge(t.Context())
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
task workflow.Task
|
||||
wantHost string
|
||||
wantPRPath string
|
||||
}{
|
||||
{
|
||||
// The name is authoritative even though the identity that owns
|
||||
// this repo would otherwise claim the task.
|
||||
name: "exact identity name wins over repo ownership",
|
||||
task: workflow.Task{Identity: "gitea-bot", Owner: "acme", Repo: "shared", PRNumber: 34},
|
||||
wantHost: "https://gitea.example",
|
||||
wantPRPath: "/pulls/34",
|
||||
},
|
||||
{
|
||||
name: "repo ownership resolves a task with no identity recorded",
|
||||
task: workflow.Task{Owner: "beta", Repo: "svc", PRNumber: 7},
|
||||
wantHost: "https://github.example",
|
||||
wantPRPath: "/pull/7",
|
||||
},
|
||||
{
|
||||
name: "an identity the projection does not carry falls back to repo ownership",
|
||||
task: workflow.Task{Identity: "retired", Owner: "acme", Repo: "widget", PRNumber: 12},
|
||||
wantHost: "https://gitea.example",
|
||||
wantPRPath: "/pulls/12",
|
||||
},
|
||||
{
|
||||
// Two identities list acme/shared, so ownership cannot decide.
|
||||
// Pointing at either would be a wrong link; the default forge is
|
||||
// the same answer the pre-cutover resolver gave.
|
||||
name: "an ambiguous repo belongs to the default forge",
|
||||
task: workflow.Task{Owner: "acme", Repo: "shared", PRNumber: 3},
|
||||
wantHost: "https://github.example",
|
||||
wantPRPath: "/pull/3",
|
||||
},
|
||||
{
|
||||
name: "no identity owns the repo",
|
||||
task: workflow.Task{Owner: "other", Repo: "repo", PRNumber: 9},
|
||||
wantHost: "https://github.example",
|
||||
wantPRPath: "/pull/9",
|
||||
},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
coords := forge(tc.task)
|
||||
if coords.host != tc.wantHost {
|
||||
t.Fatalf("host = %q, want %q", coords.host, tc.wantHost)
|
||||
}
|
||||
repoURL, issueURL, prURL := taskURLs(tc.task, coords)
|
||||
wantRepo := tc.wantHost + "/" + tc.task.Owner + "/" + tc.task.Repo
|
||||
if repoURL != wantRepo {
|
||||
t.Errorf("repo URL = %q, want %q", repoURL, wantRepo)
|
||||
}
|
||||
if tc.task.IssueNumber > 0 && issueURL == "" {
|
||||
t.Errorf("issue URL is empty for forge-backed task with issue number %d", tc.task.IssueNumber)
|
||||
}
|
||||
if prURL != wantRepo+tc.wantPRPath {
|
||||
t.Errorf("PR URL = %q, want %q", prURL, wantRepo+tc.wantPRPath)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolveForgeWithoutIdentitiesUsesTheDefault: a single-identity
|
||||
// deployment publishes no identity list, so every task belongs to the one
|
||||
// forge the projection carries -- exactly what this resolver did before
|
||||
// per-identity forges were published.
|
||||
func TestResolveForgeWithoutIdentitiesUsesTheDefault(t *testing.T) {
|
||||
srv := &Server{ConfigSource: func(context.Context) (ConfigView, bool, error) {
|
||||
return ConfigView{Identity: IdentityView{ForgeType: "github", ForgeHost: "https://github.example"}}, true, nil
|
||||
}}
|
||||
forge := srv.resolveForge(t.Context())
|
||||
|
||||
for _, task := range []workflow.Task{
|
||||
{Owner: "acme", Repo: "widget"},
|
||||
{Identity: "whatever", Owner: "acme", Repo: "widget"},
|
||||
} {
|
||||
if coords := forge(task); coords.host != "https://github.example" {
|
||||
t.Errorf("task %+v resolved to forge %q, want the deployment's only forge", task, coords.host)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTasksLinksEachRowToItsOwningForge proves the fix at the route the
|
||||
// dashboard actually reads: a multi-identity deployment's task list carries a
|
||||
// forge link on every row, built from the forge that owns that row.
|
||||
func TestHandleTasksLinksEachRowToItsOwningForge(t *testing.T) {
|
||||
base := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
if _, err := base.Store.EnqueueIssue(ctx, "acme", "widget", 12, "gitea work", "", "", "gitea-bot"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := base.Store.EnqueueIssue(ctx, "beta", "svc", 7, "github work", "", "", "github-bot"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tasks, err := base.Store.Tasks(ctx, 10)
|
||||
if err != nil || len(tasks) != 2 {
|
||||
t.Fatalf("seeded tasks = %d (%v), want 2", len(tasks), err)
|
||||
}
|
||||
for i := range tasks {
|
||||
tasks[i].PRNumber = tasks[i].IssueNumber
|
||||
if err := base.Store.Update(ctx, &tasks[i]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
srv := &Server{
|
||||
Store: base.Store,
|
||||
Log: base.Log,
|
||||
ConfigSource: func(context.Context) (ConfigView, bool, error) {
|
||||
return multiIdentityView(), true, nil
|
||||
},
|
||||
}
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/tasks", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("GET /api/tasks = %d (%s), want 200", w.Code, w.Body)
|
||||
}
|
||||
var rows []taskView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &rows); err != nil {
|
||||
t.Fatalf("decode rows: %v (%s)", err, w.Body)
|
||||
}
|
||||
if len(rows) != 2 {
|
||||
t.Fatalf("rows = %d, want 2 (%s)", len(rows), w.Body)
|
||||
}
|
||||
|
||||
want := map[string]struct{ repo, issue, pr string }{
|
||||
"acme/widget": {"https://gitea.example/acme/widget", "https://gitea.example/acme/widget/issues/12", "https://gitea.example/acme/widget/pulls/12"},
|
||||
"beta/svc": {"https://github.example/beta/svc", "https://github.example/beta/svc/issues/7", "https://github.example/beta/svc/pull/7"},
|
||||
}
|
||||
for _, row := range rows {
|
||||
key := row.Owner + "/" + row.Repo
|
||||
expected, ok := want[key]
|
||||
if !ok {
|
||||
t.Errorf("unexpected row %q", key)
|
||||
continue
|
||||
}
|
||||
if row.RepoURL != expected.repo || row.IssueURL != expected.issue || row.PRURL != expected.pr {
|
||||
t.Errorf("%s links = %q, %q, %q; want %q, %q, %q", key,
|
||||
row.RepoURL, row.IssueURL, row.PRURL, expected.repo, expected.issue, expected.pr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Approve requeues from the task's own recorded state rather than anything
|
||||
// the caller supplies, so a stale dashboard cannot approve a task twice.
|
||||
func TestHandleTaskActionApproveUsesRecordedState(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "approve me", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("claim = (%+v, %v)", task, err)
|
||||
}
|
||||
if err := srv.Store.Transition(ctx, task.ID, workflow.StatusRunning, workflow.StatusWaitingHuman, "review"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The wait names the workflow the approval resumes (feasibility's deliver
|
||||
// stage sets implement before it waits); the handler keeps it rather than
|
||||
// hardcoding one, so the approval runs the workflow the task carries
|
||||
// (docs/prds/pr-review-operator-response.md, Decision 1).
|
||||
waiting, err := srv.Store.TaskByID(ctx, task.ID)
|
||||
if err != nil || waiting == nil {
|
||||
t.Fatalf("TaskByID before approve = (%+v, %v)", waiting, err)
|
||||
}
|
||||
waiting.Workflow = "implement"
|
||||
if err := srv.Store.Update(ctx, waiting); err != nil {
|
||||
t.Fatalf("name the resuming workflow: %v", err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodPost, "/api/tasks/"+strconv.FormatInt(task.ID, 10)+"/action", bytes.NewBufferString(`{"action":"approve"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Archie-CSRF", "1")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("approve status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
got, err := srv.Store.TaskByID(ctx, task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", got, err)
|
||||
}
|
||||
if got.Status != workflow.StatusQueued || got.Workflow != "implement" {
|
||||
t.Fatalf("approved task = %+v, want queued/implement", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleTaskActionRetriesParkedTask(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "retry me", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("claim = (%+v, %v)", task, err)
|
||||
}
|
||||
if err := srv.Store.Transition(ctx, task.ID, workflow.StatusRunning, workflow.StatusParked, "failed"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodPost, "/api/tasks/"+strconv.FormatInt(task.ID, 10)+"/action", bytes.NewBufferString(`{"action":"retry"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Archie-CSRF", "1")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("retry status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
got, err := srv.Store.TaskByID(ctx, task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", got, err)
|
||||
}
|
||||
if got.Status != workflow.StatusQueued || got.RetryCount != 1 {
|
||||
t.Fatalf("retried task = %+v, want queued/retry_count=1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskIsolatesTasks returns the timeline for one task, and only
|
||||
// that task: another task's events must not leak into the response.
|
||||
func TestHandleTaskIsolatesTasks(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
for _, ev := range []events.Event{
|
||||
{TaskID: 7, Kind: "stage_start", Stage: "plan", Detail: "bootstrap"},
|
||||
{TaskID: 7, Kind: "stage_end", Stage: "plan"},
|
||||
{TaskID: 8, Kind: "stage_start", Stage: "implement"},
|
||||
} {
|
||||
if _, err := srv.Store.InsertEvent(ctx, ev); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/tasks/7", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
var got []events.Event
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("timeline has %d events, want 2 (task 8 must not leak in)", len(got))
|
||||
}
|
||||
if got[0].Kind != "stage_start" || got[0].Stage != "plan" {
|
||||
t.Errorf("first event = %+v, want stage_start/plan", got[0])
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskUnknownID returns an empty list, not an error, for a task id
|
||||
// that has no events yet -- the UI renders "No events yet" from that.
|
||||
func TestHandleTaskUnknownID(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/tasks/999", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", w.Code)
|
||||
}
|
||||
if body := strings.TrimSpace(w.Body.String()); body != "null" && body != "[]" {
|
||||
t.Fatalf("body = %s, want an empty timeline", body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskBadID is covered in webui_test.go (400 on a non-numeric id).
|
||||
|
||||
// TestHandleTaskStoreError proves a store failure surfaces as 500 -- the UI
|
||||
// shows its "Could not load timeline" state and offers a retry.
|
||||
func TestHandleTaskStoreError(t *testing.T) {
|
||||
base := newTestServer(t)
|
||||
srv := &Server{
|
||||
Store: &stubStore{TaskStore: base.Store, taskEventsErr: fmt.Errorf("db locked")},
|
||||
Log: base.Log,
|
||||
}
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/tasks/7", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status = %d, want 500", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBulkClearRouteCannotMutateTasks(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
if _, err := srv.Store.EnqueueIssue(t.Context(), "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/tasks/clear", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code == http.StatusOK {
|
||||
t.Fatal("GET /api/tasks/clear still exposes a destructive mutation")
|
||||
}
|
||||
tasks, err := srv.Store.Tasks(t.Context(), 10)
|
||||
if err != nil || len(tasks) != 1 {
|
||||
t.Fatalf("tasks after legacy clear request = (%d, %v), want one preserved", len(tasks), err)
|
||||
}
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/releaseupdate"
|
||||
)
|
||||
|
||||
func TestVersionStatusForCases(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
component releaseupdate.Component
|
||||
running string
|
||||
ok bool
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "matches, nothing newer",
|
||||
component: releaseupdate.Component{Installed: "1.0.0"},
|
||||
running: "1.0.0", ok: true,
|
||||
want: statusOK,
|
||||
},
|
||||
{
|
||||
name: "newer available, running matches installed claim",
|
||||
component: releaseupdate.Component{Installed: "1.0.0", Available: "1.1.0"},
|
||||
running: "1.0.0", ok: true,
|
||||
want: statusUpdateAvailable,
|
||||
},
|
||||
{
|
||||
name: "running contradicts the installed claim",
|
||||
component: releaseupdate.Component{Installed: "1.1.0"},
|
||||
running: "1.0.0", ok: true,
|
||||
want: statusDrift,
|
||||
},
|
||||
{
|
||||
name: "nothing observed running",
|
||||
component: releaseupdate.Component{Installed: "1.0.0"},
|
||||
running: "", ok: false,
|
||||
want: statusUnknown,
|
||||
},
|
||||
{
|
||||
name: "drift takes priority over update_available",
|
||||
component: releaseupdate.Component{Installed: "1.1.0", Available: "1.2.0"},
|
||||
running: "1.0.0", ok: true,
|
||||
want: statusDrift,
|
||||
},
|
||||
{
|
||||
name: "check command reported no installed claim -- nothing to compare against",
|
||||
component: releaseupdate.Component{},
|
||||
running: "1.0.0", ok: true,
|
||||
want: statusUnknown,
|
||||
},
|
||||
{
|
||||
name: "available with no installed claim must not read as an update, since nothing was compared",
|
||||
component: releaseupdate.Component{Available: "1.0.0"},
|
||||
running: "1.0.0", ok: true,
|
||||
want: statusUnknown,
|
||||
},
|
||||
{
|
||||
name: "installed equals available -- nothing new, matches Snapshot.Available's own semantics",
|
||||
component: releaseupdate.Component{Installed: "1.0.0", Available: "1.0.0"},
|
||||
running: "1.0.0", ok: true,
|
||||
want: statusOK,
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if got := versionStatusFor(test.component, test.running, test.ok); got != test.want {
|
||||
t.Errorf("versionStatusFor(%+v, %q, %v) = %q, want %q", test.component, test.running, test.ok, got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleVersionComposesCheckAndRunningVersions(t *testing.T) {
|
||||
sessions := gateway.NewSessionStoreMemory()
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
updates := &chatUpdateStub{snapshot: releaseupdate.Snapshot{Components: []releaseupdate.Component{
|
||||
{ID: "daemon", Label: "Gateway", Installed: "1.0.0", Available: "1.1.0", InstallType: "binary"},
|
||||
{ID: "agent", Label: "Runtime", Installed: "1.0.0", InstallType: "container", Reference: "img@sha256:abc"},
|
||||
}}}
|
||||
server := &Server{
|
||||
Chat: testChatService(gateway.NewRouter(chatStatusStub{}, nil, "web"), sessions, nil, nil, nil, updates, nil),
|
||||
RunningVersions: func() map[string]string { return map[string]string{"daemon": "1.0.0"} },
|
||||
}
|
||||
|
||||
res := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(res, httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/version", nil))
|
||||
if res.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", res.Code, res.Body)
|
||||
}
|
||||
var got struct {
|
||||
Components []componentVersionStatus `json:"components"`
|
||||
}
|
||||
if err := json.Unmarshal(res.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got.Components) != 2 {
|
||||
t.Fatalf("components = %#v, want 2", got.Components)
|
||||
}
|
||||
daemon := got.Components[0]
|
||||
if daemon.Status != statusUpdateAvailable || daemon.RunningVersion != "1.0.0" || daemon.InstallType != "binary" {
|
||||
t.Errorf("daemon = %+v, want status=%q running_version=1.0.0 install_type=binary", daemon, statusUpdateAvailable)
|
||||
}
|
||||
agent := got.Components[1]
|
||||
if agent.Status != statusUnknown || agent.RunningVersion != "" {
|
||||
t.Errorf("agent = %+v, want status=%q with no observed running version (not wired into RunningVersions in this test)", agent, statusUnknown)
|
||||
}
|
||||
if agent.Reference != "img@sha256:abc" {
|
||||
t.Errorf("agent.Reference = %q, want %q", agent.Reference, "img@sha256:abc")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleVersionTreatsPresentButEmptyRunningVersionAsUnobserved covers a
|
||||
// map entry that IS present but holds "" -- distinct from a missing key,
|
||||
// and reachable in production: a malformed or pre-this-change archie-agent
|
||||
// build could self-report an empty AgentVersion, which daemon.AgentStatus
|
||||
// would still record as observed=true, version="". An empty string is not
|
||||
// a version any component is actually running, so it must read as
|
||||
// unobserved rather than as a running value to compare against.
|
||||
func TestHandleVersionTreatsPresentButEmptyRunningVersionAsUnobserved(t *testing.T) {
|
||||
sessions := gateway.NewSessionStoreMemory()
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
updates := &chatUpdateStub{snapshot: releaseupdate.Snapshot{Components: []releaseupdate.Component{
|
||||
{ID: "agent", Label: "Runtime", Installed: "1.0.0"},
|
||||
}}}
|
||||
server := &Server{
|
||||
Chat: testChatService(gateway.NewRouter(chatStatusStub{}, nil, "web"), sessions, nil, nil, nil, updates, nil),
|
||||
RunningVersions: func() map[string]string { return map[string]string{"agent": ""} },
|
||||
}
|
||||
|
||||
res := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(res, httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/version", nil))
|
||||
var got struct {
|
||||
Components []componentVersionStatus `json:"components"`
|
||||
}
|
||||
if err := json.Unmarshal(res.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Components[0].Status != statusUnknown {
|
||||
t.Errorf("status = %q, want %q for a present-but-empty running version", got.Components[0].Status, statusUnknown)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleVersionUnconfigured(t *testing.T) {
|
||||
server := &Server{}
|
||||
|
||||
res := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(res, httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/version", nil))
|
||||
if res.Code != http.StatusNotImplemented {
|
||||
t.Fatalf("status = %d, want %d", res.Code, http.StatusNotImplemented)
|
||||
}
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
)
|
||||
|
||||
// TestWorkflowEnabledWritesTheCallersOrg: enabling a workflow writes the
|
||||
// caller's org's enablement document, and leaves the other org's exactly as it
|
||||
// found it -- otherwise a caller in one org toggles another org's workflows.
|
||||
func TestWorkflowEnabledWritesTheCallersOrg(t *testing.T) {
|
||||
// Both orgs have the workflow disabled, so the write has to name the org it
|
||||
// turns on rather than the state it happens to leave behind.
|
||||
const enablement = `{"orgs":{"default":{"disabled":["implement"]},"acme":{"disabled":["implement"]}}}`
|
||||
tests := []struct {
|
||||
name string
|
||||
orgID org.OrgID
|
||||
want org.OrgID
|
||||
other org.OrgID
|
||||
}{
|
||||
{name: "a caller resolved into acme", orgID: "acme", want: "acme", other: org.DefaultOrgID},
|
||||
{name: "no org on the context is the default org", want: org.DefaultOrgID, other: "acme"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
stub := workflowOrgControlPlane(t, workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "implement", YAML: "id: implement\nsteps:\n - type: implement.prepare\n"}}}, enablement)
|
||||
srv.ControlPlane = stub
|
||||
|
||||
w := doJSONInOrg(t, srv, tt.orgID, http.MethodPut, "/api/workflows/implement/enabled", map[string]any{"enabled": true})
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
if stub.command == nil {
|
||||
t.Fatal("the handler wrote no command")
|
||||
}
|
||||
if got := stub.command.GetOrgId(); got != string(tt.want) {
|
||||
t.Errorf("command carried org %q, want %q", got, tt.want)
|
||||
}
|
||||
var written task.WorkflowEnablement
|
||||
if err := json.Unmarshal(stub.command.GetValueJson(), &written); err != nil {
|
||||
t.Fatalf("decode written enablement: %v", err)
|
||||
}
|
||||
if !written.Enabled(tt.want, "implement") {
|
||||
t.Errorf("the write left implement disabled for %s", tt.want)
|
||||
}
|
||||
if written.Enabled(tt.other, "implement") {
|
||||
t.Errorf("the write enabled implement for %s, want only the caller's org", tt.other)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Disabling a workflow flags the bindings that target it and refuses new
|
||||
// ones; enabling it again lifts both.
|
||||
func TestWorkflowDisableFlagsAndRefusesBindings(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
stub, ok := srv.ControlPlane.(*controlPlaneClientStub)
|
||||
if !ok {
|
||||
t.Fatal("binding test server has no control-plane stub")
|
||||
}
|
||||
stub.resources = map[string]*controlpb.Resource{
|
||||
workflowEnablementKind: {Kind: workflowEnablementKind, Version: 1, ValueJson: []byte(`{"orgs":{}}`)},
|
||||
}
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
if w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("a", "sentry", mappingID)); w.Code != http.StatusCreated {
|
||||
t.Fatalf("create status = %d; body = %s", w.Code, w.Body)
|
||||
}
|
||||
|
||||
setEnabled := func(enabled bool) {
|
||||
t.Helper()
|
||||
if w := doJSON(t, srv, http.MethodPut, "/api/workflows/implement/enabled", map[string]any{"enabled": enabled}); w.Code != http.StatusOK {
|
||||
t.Fatalf("set enabled=%v status = %d; body = %s", enabled, w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
flagged := func() bool {
|
||||
t.Helper()
|
||||
w := doJSON(t, srv, http.MethodGet, "/api/bindings", nil)
|
||||
var body struct {
|
||||
Bindings []bindingView `json:"bindings"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || len(body.Bindings) != 1 {
|
||||
t.Fatalf("list bindings: %v; body = %s", err, w.Body)
|
||||
}
|
||||
return body.Bindings[0].WorkflowDisabled
|
||||
}
|
||||
|
||||
setEnabled(false)
|
||||
if !flagged() {
|
||||
t.Fatal("binding targeting a disabled workflow is not flagged")
|
||||
}
|
||||
if w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("b", "sentry", mappingID)); w.Code != http.StatusConflict {
|
||||
t.Fatalf("create against disabled workflow status = %d, want %d", w.Code, http.StatusConflict)
|
||||
}
|
||||
|
||||
setEnabled(true)
|
||||
if flagged() {
|
||||
t.Fatal("binding still flagged after the workflow was enabled")
|
||||
}
|
||||
if w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("b", "sentry", mappingID)); w.Code != http.StatusCreated {
|
||||
t.Fatalf("create after enabling status = %d; body = %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkflowEnabledRefusesUnknownWorkflow(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
if w := doJSON(t, srv, http.MethodPut, "/api/workflows/missing/enabled", map[string]any{"enabled": false}); w.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want %d", w.Code, http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
@@ -1,315 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
)
|
||||
|
||||
func workflowControlPlane(t *testing.T, definitions workflow.WorkflowDefinitionCollection) *controlPlaneClientStub {
|
||||
t.Helper()
|
||||
value, err := json.Marshal(definitions)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &controlPlaneClientStub{query: &controlpb.Resource{Kind: "workflow-definitions", Version: 1, ValueJson: value}}
|
||||
}
|
||||
|
||||
// workflowOrgControlPlane is the control-plane stub holding the two resources
|
||||
// the workflows handlers read together -- the definition collection and the
|
||||
// enablement document -- so a test can read back the org each was asked for.
|
||||
func workflowOrgControlPlane(t *testing.T, definitions workflow.WorkflowDefinitionCollection, enablement string) *controlPlaneClientStub {
|
||||
t.Helper()
|
||||
value, err := json.Marshal(definitions)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &controlPlaneClientStub{resources: map[string]*controlpb.Resource{
|
||||
workflowDefinitionsKind: {Kind: workflowDefinitionsKind, Version: 1, ValueJson: value},
|
||||
workflowEnablementKind: {Kind: workflowEnablementKind, Version: 1, ValueJson: []byte(enablement)},
|
||||
}}
|
||||
}
|
||||
|
||||
// doJSONInOrg issues a request acting in orgID, or in no org at all when orgID
|
||||
// is empty. The org travels on the request context (org.WithOrg) exactly as
|
||||
// authorize attaches the verified principal's, so a test reads back the org a
|
||||
// handler acts in the way production puts it there.
|
||||
func doJSONInOrg(t *testing.T, srv *Server, orgID org.OrgID, method, path string, body any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
var reader io.Reader
|
||||
if body != nil {
|
||||
encoded, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal request body: %v", err)
|
||||
}
|
||||
reader = bytes.NewReader(encoded)
|
||||
}
|
||||
ctx := t.Context()
|
||||
if orgID != "" {
|
||||
ctx = org.WithOrg(ctx, orgID)
|
||||
}
|
||||
r := httptest.NewRequestWithContext(ctx, method, path, reader)
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
r.Header.Set("X-Archie-CSRF", "1")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
|
||||
type recordingWorkRequestCreator struct{ request gateway.SpawnRequest }
|
||||
|
||||
func (c *recordingWorkRequestCreator) CreateTask(_ context.Context, request gateway.SpawnRequest) (int64, error) {
|
||||
c.request = request
|
||||
return 42, nil
|
||||
}
|
||||
|
||||
func TestWorkflowsIncludeInstalledZeroRunDefinitions(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.ControlPlane = workflowControlPlane(t, workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "custom", YAML: "id: custom\nsteps:\n - type: implement.prepare\n - type: implement.plan\n"}}})
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/workflows", nil))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
var response struct {
|
||||
Definitions []workflow.Definition `json:"definitions"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(response.Definitions) != 1 || response.Definitions[0].ID != "custom" || response.Definitions[0].Origin != "database" {
|
||||
t.Fatalf("definitions = %#v", response.Definitions)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWorkflowDefinitionsPathActsInTheCallersOrg: the definitions listing and
|
||||
// the enablement read beside it both act in the caller's org. A handler that
|
||||
// reads the definitions in the caller's org while reading the enablement in the
|
||||
// default org reports another org's enablement as the caller's own.
|
||||
func TestWorkflowDefinitionsPathActsInTheCallersOrg(t *testing.T) {
|
||||
// acme has disabled custom; the default org has not.
|
||||
const enablement = `{"orgs":{"acme":{"disabled":["custom"]}}}`
|
||||
tests := []struct {
|
||||
name string
|
||||
orgID org.OrgID
|
||||
want org.OrgID
|
||||
wantEnabled bool
|
||||
}{
|
||||
{name: "a caller resolved into acme", orgID: "acme", want: "acme"},
|
||||
{name: "no org on the context is the default org", want: org.DefaultOrgID, wantEnabled: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
stub := workflowOrgControlPlane(t, workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "custom", YAML: "id: custom\nsteps:\n - type: implement.prepare\n"}}}, enablement)
|
||||
srv.ControlPlane = stub
|
||||
|
||||
w := doJSONInOrg(t, srv, tt.orgID, http.MethodGet, "/api/workflows", nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
queried := map[string]bool{}
|
||||
for _, request := range stub.queries {
|
||||
queried[request.GetKind()] = true
|
||||
if got := request.GetOrgId(); got != string(tt.want) {
|
||||
t.Errorf("%s query carried org %q, want %q", request.GetKind(), got, tt.want)
|
||||
}
|
||||
}
|
||||
if !queried[workflowDefinitionsKind] || !queried[workflowEnablementKind] {
|
||||
t.Fatalf("definitions path queried %v, want both %s and %s", queried, workflowDefinitionsKind, workflowEnablementKind)
|
||||
}
|
||||
var response struct {
|
||||
Definitions []workflow.Definition `json:"definitions"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(response.Definitions) != 1 || response.Definitions[0].Enabled != tt.wantEnabled {
|
||||
t.Fatalf("definitions = %#v, want custom enabled=%v", response.Definitions, tt.wantEnabled)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestWorkRequestEnablementReadsTheCallersOrg: whether a workflow may run is
|
||||
// the caller's org's answer, so the org that disabled pr-review cannot run it
|
||||
// while an org that did not can.
|
||||
func TestWorkRequestEnablementReadsTheCallersOrg(t *testing.T) {
|
||||
const enablement = `{"orgs":{"acme":{"disabled":["pr-review"]}}}`
|
||||
request := map[string]any{
|
||||
"identity": "archie", "repository": "acme/widget", "workflow": "pr-review",
|
||||
"title": "Review 77", "instructions": "Review it.", "inputs": map[string]any{"pr_number": 77},
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
orgID org.OrgID
|
||||
want org.OrgID
|
||||
wantCode int
|
||||
}{
|
||||
{name: "a caller in the org that disabled it", orgID: "acme", want: "acme", wantCode: http.StatusConflict},
|
||||
{name: "a caller in the org that kept it enabled", want: org.DefaultOrgID, wantCode: http.StatusCreated},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
creator := &recordingWorkRequestCreator{}
|
||||
srv.WorkRequests = creator
|
||||
stub := workflowOrgControlPlane(t, workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "pr-review", YAML: declaredInputsDefinition}}}, enablement)
|
||||
srv.ControlPlane = stub
|
||||
|
||||
w := doJSONInOrg(t, srv, tt.orgID, http.MethodPost, "/api/work-requests", request)
|
||||
if w.Code != tt.wantCode {
|
||||
t.Fatalf("status = %d, body = %s, want %d", w.Code, w.Body, tt.wantCode)
|
||||
}
|
||||
for _, query := range stub.queries {
|
||||
if got := query.GetOrgId(); got != string(tt.want) {
|
||||
t.Errorf("%s query carried org %q, want %q", query.GetKind(), got, tt.want)
|
||||
}
|
||||
}
|
||||
if admitted := creator.request.Title != ""; admitted != (tt.wantCode == http.StatusCreated) {
|
||||
t.Errorf("task admitted = %v, want %v", admitted, tt.wantCode == http.StatusCreated)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// declaredInputsDefinition is a pr-review-shaped definition: it declares the
|
||||
// inputs the handler checks a work request against, one of them required, so a
|
||||
// request that does not name a pull request number cannot be admitted.
|
||||
const declaredInputsDefinition = `id: pr-review
|
||||
inputs:
|
||||
pr_number:
|
||||
type: number
|
||||
required: true
|
||||
depth:
|
||||
type: string
|
||||
steps:
|
||||
- type: implement.prepare
|
||||
`
|
||||
|
||||
func postWorkRequest(t *testing.T, srv *Server, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/work-requests", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Archie-CSRF", "1")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
// TestWorkRequestCarriesDeclaredInputs: a dashboard request names the workflow's
|
||||
// declared inputs and the admitted task carries them, so a pr-review request
|
||||
// reaches its workflow with the pull request number stagePRIntake reads
|
||||
// (archie-core-06nq).
|
||||
func TestWorkRequestCarriesDeclaredInputs(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
creator := &recordingWorkRequestCreator{}
|
||||
srv.WorkRequests = creator
|
||||
srv.ControlPlane = workflowControlPlane(t, workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "pr-review", YAML: declaredInputsDefinition}}})
|
||||
|
||||
w := postWorkRequest(t, srv, `{"identity":"archie","repository":"acme/widget","workflow":"pr-review","title":"Review 77","instructions":"Review it.","inputs":{"pr_number":77,"depth":"deep"}}`)
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
if got := creator.request.Inputs["pr_number"]; got != float64(77) {
|
||||
t.Errorf("pr_number input = %#v, want the number the request sent", got)
|
||||
}
|
||||
if got := creator.request.Inputs["depth"]; got != "deep" {
|
||||
t.Errorf("depth input = %#v, want \"deep\"", got)
|
||||
}
|
||||
// EffectivePRNumber is how the daemon and stagePRIntake read the input, so
|
||||
// the assignment is proven against the consumer rather than against the
|
||||
// map's shape alone.
|
||||
if got := (workflow.Task{Inputs: creator.request.Inputs}).EffectivePRNumber(); got != 77 {
|
||||
t.Errorf("EffectivePRNumber() = %d, want 77", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWorkRequestRejectsUnmetDeclaredInputs: the request is refused at the
|
||||
// producer, naming the input, instead of being admitted and then parked or
|
||||
// failed at the workflow's first stage.
|
||||
func TestWorkRequestRejectsUnmetDeclaredInputs(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "missing a required input",
|
||||
body: `{"identity":"archie","repository":"acme/widget","workflow":"pr-review","title":"Review","instructions":"Review it."}`,
|
||||
want: `input "pr_number" is required`,
|
||||
},
|
||||
{
|
||||
name: "naming an input the workflow does not declare",
|
||||
body: `{"identity":"archie","repository":"acme/widget","workflow":"pr-review","title":"Review","instructions":"Review it.","inputs":{"pr_number":77,"pull_request":77}}`,
|
||||
want: `input "pull_request" is not declared by the workflow`,
|
||||
},
|
||||
{
|
||||
name: "a value of the wrong type",
|
||||
body: `{"identity":"archie","repository":"acme/widget","workflow":"pr-review","title":"Review","instructions":"Review it.","inputs":{"pr_number":"seventy-seven"}}`,
|
||||
want: `input "pr_number" is string, want number`,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
creator := &recordingWorkRequestCreator{}
|
||||
srv.WorkRequests = creator
|
||||
srv.ControlPlane = workflowControlPlane(t, workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "pr-review", YAML: declaredInputsDefinition}}})
|
||||
|
||||
w := postWorkRequest(t, srv, tt.body)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), tt.want) {
|
||||
t.Errorf("body = %q, want it to name the failure %q", w.Body, tt.want)
|
||||
}
|
||||
if got := creator.request; got.Title != "" || got.Body != "" || len(got.Inputs) != 0 {
|
||||
t.Errorf("creator called with %#v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkRequestUsesNormalTaskAdmission(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
creator := &recordingWorkRequestCreator{}
|
||||
srv.WorkRequests = creator
|
||||
srv.ControlPlane = workflowControlPlane(t, workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "implement", YAML: "id: implement\nsteps:\n - type: implement.prepare\n"}}})
|
||||
|
||||
// An inputless workflow keeps taking an inputless request.
|
||||
body := `{"identity":"archie","repository":"acme/widget","workflow":"implement","title":"Fix login","instructions":"Reproduce and fix it."}`
|
||||
w := postWorkRequest(t, srv, body)
|
||||
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
if got := creator.request; got.Identity != "archie" || got.Repo != "acme/widget" || got.Workflow != "implement" || got.Title != "Fix login" || got.Body != "Reproduce and fix it." {
|
||||
t.Fatalf("request = %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkRequestRejectsDisabledWorkflow(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
creator := &recordingWorkRequestCreator{}
|
||||
srv.WorkRequests = creator
|
||||
srv.ControlPlane = workflowControlPlane(t, workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "custom", YAML: "id: custom\nsteps:\n - type: implement.prepare\n"}}})
|
||||
w := postWorkRequest(t, srv, `{"identity":"archie","repository":"acme/widget","workflow":"implement","title":"Fix","instructions":"Do it"}`)
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
if got := creator.request; got.Title != "" || got.Body != "" || got.Repo != "" || got.Workflow != "" || got.Identity != "" || len(got.Inputs) != 0 {
|
||||
t.Fatalf("creator called with %#v", got)
|
||||
}
|
||||
}
|
||||
@@ -1,228 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
)
|
||||
|
||||
var testActingIdentity = identity.Identity{
|
||||
ID: "40000000-0000-5000-8000-000000000001",
|
||||
Kind: identity.KindUser,
|
||||
DisplayName: "sam",
|
||||
Lifecycle: identity.LifecycleActive,
|
||||
Version: 1,
|
||||
}
|
||||
|
||||
// withIdentityCheck builds the middleware over a stub provider, which is the
|
||||
// seam the dashboard sees: verification and binding are proved in
|
||||
// internal/infrastructure/oidc and internal/domain/identity, and what is proved
|
||||
// here is that a request either resolves or is refused.
|
||||
func withIdentityCheck(t *testing.T, authenticate func(context.Context, string) (identity.Identity, error)) http.Handler {
|
||||
t.Helper()
|
||||
s := &Server{Authenticate: authenticate}
|
||||
return s.requireToken(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
value, ok := ActingIdentity(r.Context())
|
||||
if !ok {
|
||||
t.Error("handler ran without a resolved identity")
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(string(value.ID)))
|
||||
}))
|
||||
}
|
||||
|
||||
func TestIdentityRequestResolvesToTheCredentialSubject(t *testing.T) {
|
||||
seen := ""
|
||||
handler := withIdentityCheck(t, func(_ context.Context, raw string) (identity.Identity, error) {
|
||||
seen = raw
|
||||
return testActingIdentity, nil
|
||||
})
|
||||
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/tasks/7/action", strings.NewReader(`{"actor":"someone-else"}`))
|
||||
request.Header.Set("Authorization", "Bearer "+"a-provider-token")
|
||||
// A caller-supplied identity must not be consulted: the only source of the
|
||||
// acting identity is the credential the provider signed.
|
||||
request.Header.Set("X-Archie-Identity", "attacker-chosen")
|
||||
request.Header.Set("X-Archie-Actor", "attacker-chosen")
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusOK)
|
||||
}
|
||||
if seen != "a-provider-token" {
|
||||
t.Fatalf("verifier saw %q, want the presented credential", seen)
|
||||
}
|
||||
if got := recorder.Body.String(); got != string(testActingIdentity.ID) {
|
||||
t.Fatalf("resolved identity = %q, want %q", got, testActingIdentity.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdentityRequestRefusesEveryCallerItCannotAttribute(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
credential string
|
||||
authErr error
|
||||
wantStatus int
|
||||
}{
|
||||
{
|
||||
name: "no credential presented",
|
||||
credential: "",
|
||||
wantStatus: http.StatusUnauthorized,
|
||||
},
|
||||
{
|
||||
name: "credential rejected",
|
||||
credential: "Bearer expired-or-foreign",
|
||||
authErr: identity.ErrCredentialRejected,
|
||||
wantStatus: http.StatusUnauthorized,
|
||||
},
|
||||
{
|
||||
name: "subject not bound to an identity",
|
||||
credential: "Bearer valid-but-unknown",
|
||||
authErr: identity.ErrSubjectUnbound,
|
||||
wantStatus: http.StatusForbidden,
|
||||
},
|
||||
{
|
||||
name: "identity may not act",
|
||||
credential: "Bearer valid-but-suspended",
|
||||
authErr: identity.ErrIdentityInactive,
|
||||
wantStatus: http.StatusForbidden,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
handler := withIdentityCheck(t, func(_ context.Context, _ string) (identity.Identity, error) {
|
||||
if tc.authErr == nil {
|
||||
t.Fatal("the verifier was called with no credential to verify")
|
||||
}
|
||||
return identity.Identity{}, tc.authErr
|
||||
})
|
||||
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/tasks", nil)
|
||||
if tc.credential != "" {
|
||||
request.Header.Set("Authorization", tc.credential)
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
|
||||
if recorder.Code != tc.wantStatus {
|
||||
t.Fatalf("status = %d, want %d", recorder.Code, tc.wantStatus)
|
||||
}
|
||||
if tc.wantStatus == http.StatusUnauthorized &&
|
||||
recorder.Header().Get("WWW-Authenticate") == "" {
|
||||
t.Fatal("a 401 must name the scheme it accepts")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestIdentityCheckReplacesTheSharedToken: with a provider configured the shared
|
||||
// token is no longer a way in, because a credential that names nobody cannot
|
||||
// attribute what it does.
|
||||
func TestIdentityCheckReplacesTheSharedToken(t *testing.T) {
|
||||
handler := withIdentityCheck(t, func(_ context.Context, raw string) (identity.Identity, error) {
|
||||
if raw == "" {
|
||||
return identity.Identity{}, identity.ErrNoCredential
|
||||
}
|
||||
return testActingIdentity, nil
|
||||
})
|
||||
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil)
|
||||
request.AddCookie(&http.Cookie{Name: tokenCookie, Value: "the-shared-token"})
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
|
||||
if recorder.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusUnauthorized)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSharedTokenStillGatesAnInstanceWithNoProvider: with no provider configured
|
||||
// the shared token remains the gate, which is the loopback-friendly behaviour a
|
||||
// single-operator instance relies on.
|
||||
func TestSharedTokenStillGatesAnInstanceWithNoProvider(t *testing.T) {
|
||||
s := &Server{Token: ""}
|
||||
reached := false
|
||||
handler := s.requireToken(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { reached = true }))
|
||||
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil)
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
|
||||
if !reached {
|
||||
t.Fatal("a token-less loopback server refused a request")
|
||||
}
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusOK)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRefusedBrowserIsSentToSignIn: with a sign-in flow configured, a browser that
|
||||
// cannot authenticate belongs at the provider, not on a shared-token paste page
|
||||
// that cannot help it. A refusal signing in again cannot fix -- a suspended
|
||||
// identity -- is answered instead of redirected.
|
||||
func TestRefusedBrowserIsSentToSignIn(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
authErr error
|
||||
login identity.LoginFlow
|
||||
wantStatus int
|
||||
wantLogin bool
|
||||
}{
|
||||
{
|
||||
name: "no credential, sign-in available",
|
||||
authErr: identity.ErrCredentialRejected,
|
||||
login: stubFlow{},
|
||||
wantStatus: http.StatusSeeOther,
|
||||
wantLogin: true,
|
||||
},
|
||||
{
|
||||
name: "no credential, no sign-in flow",
|
||||
authErr: identity.ErrCredentialRejected,
|
||||
wantStatus: http.StatusUnauthorized,
|
||||
},
|
||||
{
|
||||
name: "suspended identity is told, not redirected",
|
||||
authErr: identity.ErrIdentityInactive,
|
||||
login: stubFlow{},
|
||||
wantStatus: http.StatusForbidden,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s := &Server{
|
||||
Login: tc.login,
|
||||
Authenticate: func(context.Context, string) (identity.Identity, error) {
|
||||
return identity.Identity{}, tc.authErr
|
||||
},
|
||||
}
|
||||
handler := s.requireToken(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
|
||||
t.Error("an unauthenticated request reached the handler")
|
||||
}))
|
||||
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil)
|
||||
request.Header.Set("Authorization", "Bearer a-token")
|
||||
request.Header.Set("Accept", "text/html")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
|
||||
if recorder.Code != tc.wantStatus {
|
||||
t.Fatalf("status = %d, want %d", recorder.Code, tc.wantStatus)
|
||||
}
|
||||
location := recorder.Header().Get("Location")
|
||||
if tc.wantLogin && location != loginPath {
|
||||
t.Fatalf("Location = %q, want %q", location, loginPath)
|
||||
}
|
||||
if !tc.wantLogin && location != "" {
|
||||
t.Fatalf("a refusal that signing in cannot fix redirected to %q", location)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,170 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRequireToken_RedirectRejectsProtocolRelativePath(t *testing.T) {
|
||||
s := &Server{Token: "secret-token"}
|
||||
h := s.requireToken(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "http://archie.local//evil.example//x?t=secret-token", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusSeeOther {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, http.StatusSeeOther)
|
||||
}
|
||||
loc := rec.Header().Get("Location")
|
||||
if strings.HasPrefix(loc, "//") || strings.HasPrefix(loc, "/\\") {
|
||||
t.Fatalf("Location %q is protocol-relative: open redirect to an attacker-controlled host", loc)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSameOriginPath(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
path string
|
||||
rawQuery string
|
||||
want string
|
||||
}{
|
||||
{name: "protocol relative", path: "//evil.example/x", want: "/evil.example/x"},
|
||||
{name: "backslash protocol relative", path: "/\\\\evil.example/x", want: "/evil.example/x"},
|
||||
{name: "double backslash protocol relative", path: "\\\\evil.example\\x", want: "/evil.example/x"},
|
||||
{name: "ordinary path and query", path: "/dashboard", rawQuery: "foo=bar", want: "/dashboard?foo=bar"},
|
||||
{name: "encoded percent", path: "/foo%bar", want: "/foo%25bar"},
|
||||
{name: "encoded question mark", path: "/foo?bar", want: "/foo%3Fbar"},
|
||||
{name: "encoded hash", path: "/foo#bar", want: "/foo%23bar"},
|
||||
{name: "encoded slash", path: "/foo/bar", want: "/foo/bar"},
|
||||
{name: "encoded backslash", path: "/foo\\bar", want: "/foo/bar"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := sameOriginPath(tt.path, tt.rawQuery); got != tt.want {
|
||||
t.Fatalf("sameOriginPath(%q, %q) = %q, want %q", tt.path, tt.rawQuery, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequireToken_RedirectStripsTokenFromCleanURL(t *testing.T) {
|
||||
s := &Server{Token: "secret-token"}
|
||||
h := s.requireToken(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "http://archie.local/dashboard?t=secret-token&foo=bar", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusSeeOther {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, http.StatusSeeOther)
|
||||
}
|
||||
loc := rec.Header().Get("Location")
|
||||
if strings.Contains(loc, "t=secret-token") {
|
||||
t.Fatalf("Location %q still carries the token", loc)
|
||||
}
|
||||
if loc != "/dashboard?foo=bar" {
|
||||
t.Fatalf("Location = %q, want /dashboard?foo=bar", loc)
|
||||
}
|
||||
}
|
||||
|
||||
// An unauthenticated browser navigation must land on something a human can act
|
||||
// on. Everything -- index.html, the assets, every API -- sits behind
|
||||
// requireToken, so a raw text 401 left a bookmarked URL with no way forward and
|
||||
// no way to reach the dashboard's own authentication banner.
|
||||
func TestRequireToken_ServesAnAuthPageToDocumentRequests(t *testing.T) {
|
||||
s := &Server{Token: "secret-token"}
|
||||
h := s.requireToken(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Error("an unauthenticated document request reached the protected handler")
|
||||
}))
|
||||
|
||||
req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "http://archie.local/", nil)
|
||||
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status = %d, want 401; an auth page served as 200 is cached and reads as success to a status-only check", rec.Code)
|
||||
}
|
||||
if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/html") {
|
||||
t.Fatalf("Content-Type = %q, want text/html", ct)
|
||||
}
|
||||
if cc := rec.Header().Get("Cache-Control"); !strings.Contains(cc, "no-store") {
|
||||
t.Fatalf("Cache-Control = %q, want no-store", cc)
|
||||
}
|
||||
body := rec.Body.String()
|
||||
for _, want := range []string{"<form", `action="/"`, `name="t"`, "token"} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Fatalf("auth page is missing %q:\n%s", want, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A rejected token posts back through the same exchange, so the page has to
|
||||
// say so and offer another try rather than answering a document with text.
|
||||
func TestRequireToken_AuthPageReportsARejectedToken(t *testing.T) {
|
||||
s := &Server{Token: "secret-token"}
|
||||
h := s.requireToken(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Error("a request with a bad token reached the protected handler")
|
||||
}))
|
||||
|
||||
req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "http://archie.local/?t=wrong", nil)
|
||||
req.Header.Set("Accept", "text/html")
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status = %d, want 401", rec.Code)
|
||||
}
|
||||
if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/html") {
|
||||
t.Fatalf("Content-Type = %q, want text/html", ct)
|
||||
}
|
||||
if body := rec.Body.String(); !strings.Contains(body, "not accepted") {
|
||||
t.Fatalf("auth page does not report the rejected token:\n%s", body)
|
||||
}
|
||||
}
|
||||
|
||||
// API and event-stream callers read a status, not a page: classifyActionError
|
||||
// maps 401 to "session-expired", and an HTML body on an EventSource error would
|
||||
// never be seen. The document/API split is the contract this guards.
|
||||
func TestRequireToken_KeepsTextUnauthorisedForAPIRequests(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
accept string
|
||||
}{
|
||||
{name: "json api", accept: "application/json"},
|
||||
{name: "fetch default", accept: "*/*"},
|
||||
{name: "event stream", accept: "text/event-stream"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := &Server{Token: "secret-token"}
|
||||
h := s.requireToken(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Error("an unauthenticated API request reached the protected handler")
|
||||
}))
|
||||
|
||||
req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "http://archie.local/api/tasks", nil)
|
||||
req.Header.Set("Accept", tt.accept)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status = %d, want 401", rec.Code)
|
||||
}
|
||||
if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/plain") {
|
||||
t.Fatalf("Content-Type = %q, want text/plain", ct)
|
||||
}
|
||||
if body := rec.Body.String(); !strings.Contains(body, "unauthorised") {
|
||||
t.Fatalf("body = %q, want the plain unauthorised text", body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"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"
|
||||
)
|
||||
|
||||
// fakeAuthorizer records the request it evaluated and answers with a fixed
|
||||
// decision. It is the chain stand-in the webui tests run against.
|
||||
type fakeAuthorizer struct {
|
||||
decision access.Decision
|
||||
last access.Resource
|
||||
lastAct access.Action
|
||||
}
|
||||
|
||||
func (f *fakeAuthorizer) Authorize(_ access.Principal, a access.Action, r access.Resource, _ access.Context) access.Decision {
|
||||
f.lastAct, f.last = a, r
|
||||
return f.decision
|
||||
}
|
||||
|
||||
type recordingDenials struct{ recorded []access.Denial }
|
||||
|
||||
func (r *recordingDenials) RecordDenial(_ context.Context, d access.Denial) error {
|
||||
r.recorded = append(r.recorded, d)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *recordingDenials) ListDenials(_ context.Context, _ org.OrgID, _ int) ([]access.Denial, error) {
|
||||
return nil, errors.New("not needed")
|
||||
}
|
||||
|
||||
func handlerEcho(w http.ResponseWriter, r *http.Request) {
|
||||
principal, ok := RequestPrincipal(r.Context())
|
||||
if ok {
|
||||
w.Header().Set("X-Principal-Org", string(principal.Org))
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func newAccessServer(t *testing.T, engine access.Authorizer, denials access.DenialStore) *Server {
|
||||
t.Helper()
|
||||
return &Server{Access: engine, Principals: nil, Denials: denials, Token: ""}
|
||||
}
|
||||
|
||||
// stubPrincipalSource answers with one fixed principal: the middleware test
|
||||
// only needs to see that principal's org reach the request context.
|
||||
type stubPrincipalSource struct{ principal access.Principal }
|
||||
|
||||
func (s stubPrincipalSource) PrincipalFor(context.Context, identity.IdentityID) (access.Principal, error) {
|
||||
return s.principal, nil
|
||||
}
|
||||
|
||||
func orgEcho(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte(org.OrgFromContext(r.Context())))
|
||||
}
|
||||
|
||||
// TestAuthorizeAttachesPrincipalOrgToRequestContext: the org a control-plane
|
||||
// call acts in is the principal's, and it travels on the context the handler
|
||||
// receives -- so every downstream request inherits it without naming it.
|
||||
func TestAuthorizeAttachesPrincipalOrgToRequestContext(t *testing.T) {
|
||||
namedOrg := access.Principal{
|
||||
IdentityID: testActingIdentity.ID,
|
||||
Kind: identity.KindUser,
|
||||
Org: "acme",
|
||||
Memberships: []org.Membership{{IdentityID: testActingIdentity.ID, OrgID: "acme", Role: org.RoleOwner}},
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
principal access.Principal
|
||||
acting bool
|
||||
want org.OrgID
|
||||
}{
|
||||
{name: "shared token acts in the default org", principal: TokenOwnerPrincipal(), want: org.DefaultOrgID},
|
||||
{name: "an identity acts in its own org", principal: namedOrg, acting: true, want: "acme"},
|
||||
{name: "an identity in the default org yields the default", principal: TokenOwnerPrincipal(), acting: true, want: org.DefaultOrgID},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := &Server{Access: &fakeAuthorizer{decision: access.Allowed()}, Principals: stubPrincipalSource{tt.principal}}
|
||||
h := s.authorize(http.HandlerFunc(orgEcho))
|
||||
ctx := t.Context()
|
||||
if tt.acting {
|
||||
ctx = WithActingIdentity(ctx, testActingIdentity)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/tasks", nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("authorized request served %d, want 200", rec.Code)
|
||||
}
|
||||
if got := rec.Body.String(); got != string(tt.want) {
|
||||
t.Fatalf("request org = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthorizeNilEngineServesEverything(t *testing.T) {
|
||||
s := &Server{}
|
||||
h := s.authorize(http.HandlerFunc(handlerEcho))
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/tasks", nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("nil chain served %d, want 200: the credential check stays the gate", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthorizeTokenOwnerAllowed(t *testing.T) {
|
||||
engine := &fakeAuthorizer{decision: access.Allowed()}
|
||||
s := newAccessServer(t, engine, nil)
|
||||
h := s.authorize(http.HandlerFunc(handlerEcho))
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/bindings", nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("allowed request served %d, want 200", rec.Code)
|
||||
}
|
||||
// The token owner is the owner of the default org, and the route
|
||||
// derived a read on the binding surface.
|
||||
if rec.Header().Get("X-Principal-Org") != string(org.DefaultOrgID) {
|
||||
t.Fatalf("principal org = %q, want the default org", rec.Header().Get("X-Principal-Org"))
|
||||
}
|
||||
if engine.lastAct != access.ActionRead || engine.last.Kind != access.KindBinding {
|
||||
t.Fatalf("derived action %q kind %q, want read on bindings", engine.lastAct, engine.last.Kind)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthorizeDenialIsForbiddenWithoutReason(t *testing.T) {
|
||||
engine := &fakeAuthorizer{decision: access.DeniedAt(access.LevelOrg, []string{access.PolicyOrgRead})}
|
||||
denials := &recordingDenials{}
|
||||
s := newAccessServer(t, engine, denials)
|
||||
h := s.authorize(http.HandlerFunc(handlerEcho))
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(), http.MethodDelete, "/api/bindings/b1", nil))
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("denied request served %d, want 403", rec.Code)
|
||||
}
|
||||
if rec.Body != nil && rec.Body.String() != "forbidden\n" {
|
||||
t.Fatalf("denial body = %q, want no reason", rec.Body.String())
|
||||
}
|
||||
if engine.lastAct != access.ActionDelete {
|
||||
t.Fatalf("derived action = %q, want delete", engine.lastAct)
|
||||
}
|
||||
if len(denials.recorded) != 1 {
|
||||
t.Fatalf("recorded %d denials, want 1", len(denials.recorded))
|
||||
}
|
||||
recorded := denials.recorded[0]
|
||||
if recorded.Principal != identity.SystemID || recorded.Action != access.ActionDelete ||
|
||||
recorded.Level != access.LevelOrg || len(recorded.Policies) != 1 {
|
||||
t.Fatalf("denial record = %+v, want principal, action, level and policies", recorded)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthorizeApproveRoute(t *testing.T) {
|
||||
engine := &fakeAuthorizer{decision: access.Allowed()}
|
||||
s := newAccessServer(t, engine, nil)
|
||||
h := s.authorize(http.HandlerFunc(handlerEcho))
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/bindings/b1/approve", nil))
|
||||
if engine.lastAct != access.ActionApprove {
|
||||
t.Fatalf("approve route derived action %q, want approve", engine.lastAct)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthorizeTaskLogRouteReadsLogs(t *testing.T) {
|
||||
engine := &fakeAuthorizer{decision: access.Allowed()}
|
||||
s := newAccessServer(t, engine, nil)
|
||||
h := s.authorize(http.HandlerFunc(handlerEcho))
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/tasks/7/logs", nil))
|
||||
if engine.lastAct != access.ActionReadLogs || engine.last.Kind != access.KindTask || engine.last.ID != "7" {
|
||||
t.Fatalf("log route derived %+v %q, want read_logs on task 7", engine.lastAct, engine.last.Kind)
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels/status"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
type fakeChannelStatusStore struct {
|
||||
rows []storecontract.ChannelStatus
|
||||
err error
|
||||
}
|
||||
|
||||
func (f fakeChannelStatusStore) PutChannelStatus(context.Context, []storecontract.ChannelStatus) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f fakeChannelStatusStore) ChannelStatus(context.Context) ([]storecontract.ChannelStatus, error) {
|
||||
return f.rows, f.err
|
||||
}
|
||||
|
||||
// TestRemoteChannelStatusMapsReportedState: the dashboard process reads channel
|
||||
// state another process published, so the mapping is the whole of its
|
||||
// responsibility -- including carrying an unknown state through rather than
|
||||
// dropping the channel, because a reader that hides a channel it does not
|
||||
// recognise shows a healthy page for a channel that is down.
|
||||
func TestRemoteChannelStatusMapsReportedState(t *testing.T) {
|
||||
source := RemoteChannelStatus(fakeChannelStatusStore{rows: []storecontract.ChannelStatus{
|
||||
{ID: "telegram", Name: "telegram", State: "running", Configured: true, ReloadSupported: true},
|
||||
{ID: "webhook", Name: "webhook", State: "failed", Detail: "listen: address in use", Configured: true},
|
||||
{ID: "email", Name: "email", State: "invented-later", Configured: true},
|
||||
}})
|
||||
|
||||
snapshot := source.Snapshot()
|
||||
if len(snapshot) != 3 {
|
||||
t.Fatalf("Snapshot() = %+v, want all three reported channels", snapshot)
|
||||
}
|
||||
if snapshot[0].State != status.StateRunning || !snapshot[0].ReloadSupported {
|
||||
t.Errorf("telegram = %+v, want running and reload-capable", snapshot[0])
|
||||
}
|
||||
if snapshot[1].State != status.StateFailed || snapshot[1].Detail == "" {
|
||||
t.Errorf("webhook = %+v, want the failure and its reason", snapshot[1])
|
||||
}
|
||||
if snapshot[2].State != status.State("invented-later") {
|
||||
t.Errorf("email state = %q, want the reported value carried through", snapshot[2].State)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRemoteChannelStatusReportsNothingWhenTheStoreFails: the handler has no
|
||||
// error to return, and the honest answer is an empty report. Showing a cached or
|
||||
// assumed state for a channel the dashboard cannot currently ask about is how a
|
||||
// dead channel keeps looking alive.
|
||||
func TestRemoteChannelStatusReportsNothingWhenTheStoreFails(t *testing.T) {
|
||||
source := RemoteChannelStatus(fakeChannelStatusStore{err: errors.New("state store unreachable")})
|
||||
if got := source.Snapshot(); len(got) != 0 {
|
||||
t.Fatalf("Snapshot() = %+v, want nothing when the store cannot answer", got)
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package webui
|
||||
|
||||
import "github.com/samcharles93/archie-core/internal/gateway"
|
||||
|
||||
func testChatService(router *gateway.Router, sessions gateway.SessionStore, turns *gateway.Turns, models gateway.ModelManager, personas *gateway.PersonaRegistry, updates ChatUpdateService, dangerous *DangerousService) *ChatService {
|
||||
return &ChatService{Contract: &gateway.LocalChatAdapter{
|
||||
Router: router, Sessions: sessions, Turns: turns, Models: models, Personas: personas,
|
||||
}, Updates: updates, Dangerous: dangerous}
|
||||
}
|
||||
|
||||
func testLocalChat(service *ChatService) *gateway.LocalChatAdapter {
|
||||
local, ok := service.Contract.(*gateway.LocalChatAdapter)
|
||||
if !ok {
|
||||
panic("test chat contract is not local")
|
||||
}
|
||||
return local
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
package webui
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestConfigFieldDescriptorsAreComplete guards the deliberateness the design
|
||||
// doc asks for (docs/prds/config-schema.md): every field must carry a key,
|
||||
// label, and type, and every field's RestartRequired must have been set by a
|
||||
// case in configFieldDescriptors rather than defaulted to Go's zero value.
|
||||
// Since Go cannot distinguish "explicitly false" from "unset," this test
|
||||
// instead pins the exact set of keys and their deliberate values, so a new
|
||||
// field added to the catalog without visiting this test fails loudly rather
|
||||
// than silently inheriting a zero value.
|
||||
func TestConfigFieldDescriptorsAreComplete(t *testing.T) {
|
||||
seen := map[string]bool{}
|
||||
for _, section := range configFieldDescriptors() {
|
||||
if section.ID == "" {
|
||||
t.Errorf("section with empty ID, label %q", section.Label)
|
||||
}
|
||||
if section.Label == "" {
|
||||
t.Errorf("section %q has no label", section.ID)
|
||||
}
|
||||
if section.Description == "" {
|
||||
t.Errorf("section %q has no description", section.ID)
|
||||
}
|
||||
if len(section.Fields) == 0 {
|
||||
t.Errorf("section %q has no fields", section.ID)
|
||||
}
|
||||
for _, f := range section.Fields {
|
||||
if f.Key == "" {
|
||||
t.Fatalf("section %q has a field with no key", section.ID)
|
||||
}
|
||||
if seen[f.Key] {
|
||||
t.Errorf("duplicate field key %q", f.Key)
|
||||
}
|
||||
seen[f.Key] = true
|
||||
if f.Label == "" {
|
||||
t.Errorf("field %q has no label", f.Key)
|
||||
}
|
||||
if f.Type == "" {
|
||||
t.Errorf("field %q has no type", f.Key)
|
||||
}
|
||||
if f.Type == FieldEnum && len(f.Options) == 0 {
|
||||
t.Errorf("field %q is type enum but has no options", f.Key)
|
||||
}
|
||||
if f.Type != FieldEnum && len(f.Options) != 0 {
|
||||
t.Errorf("field %q has options but is not type enum", f.Key)
|
||||
}
|
||||
// Value/LockedReason are attached per-instance
|
||||
// against a live ConfigView (archie-core-b6ew.2), not part of
|
||||
// the static catalog -- the catalog must not pre-populate them.
|
||||
if f.Value != nil {
|
||||
t.Errorf("field %q has a static Value; that is attached per-request", f.Key)
|
||||
}
|
||||
if f.LockedReason != "" {
|
||||
t.Errorf("field %q has a static LockedReason; that is attached per-request", f.Key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Keys the dashboard settings pages address by name must keep a descriptor.
|
||||
wantKeys := []string{
|
||||
"bot_user", "bot_email", "label", "forge.type", "forge.host", "diff_cap_lines",
|
||||
"repos", "models", "providers",
|
||||
"budgets.max_steps", "budgets.wall_clock", "budgets.gate_max_failures",
|
||||
"work_dir", "state_dir", "database_url",
|
||||
"web.listen",
|
||||
}
|
||||
for _, key := range wantKeys {
|
||||
if !seen[key] {
|
||||
t.Errorf("missing descriptor for %q", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestConfigFieldDescriptorsRestartRequiredIsDeliberate pins the exact
|
||||
// RestartRequired value per field against the evidence in
|
||||
// configFieldDescriptors' own doc comment (internal/app/archied/reload.go's
|
||||
// reloadableFields/reloadableSubFields allowlist), so a field added or
|
||||
// reclassified without checking reload.go fails loudly instead of quietly
|
||||
// defaulting to false ("this takes effect immediately") when it does not.
|
||||
func TestConfigFieldDescriptorsRestartRequiredIsDeliberate(t *testing.T) {
|
||||
want := map[string]bool{
|
||||
"bot_user": false,
|
||||
"bot_email": false,
|
||||
"label": false,
|
||||
"forge.type": true, // reloadableSubFields["Forge"] allows only Host
|
||||
"forge.host": false,
|
||||
"diff_cap_lines": false,
|
||||
"repos": false,
|
||||
"models": false,
|
||||
"providers": false,
|
||||
"budgets.max_steps": false,
|
||||
"budgets.wall_clock": false,
|
||||
"budgets.gate_max_failures": false,
|
||||
"work_dir": false, // locked, not merely restart-required
|
||||
"state_dir": false, // locked, not merely restart-required
|
||||
"database_url": false, // locked, not merely restart-required
|
||||
"web.listen": true, // Web is absent from both allowlists entirely
|
||||
}
|
||||
for _, section := range configFieldDescriptors() {
|
||||
for _, f := range section.Fields {
|
||||
wantRestart, ok := want[f.Key]
|
||||
if !ok {
|
||||
t.Errorf("field %q has no RestartRequired expectation in this test; add one against internal/app/archied/reload.go before adding the field", f.Key)
|
||||
continue
|
||||
}
|
||||
if f.RestartRequired != wantRestart {
|
||||
t.Errorf("field %q RestartRequired = %v, want %v", f.Key, f.RestartRequired, wantRestart)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package webui
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestDashboardURL(t *testing.T) {
|
||||
for _, tc := range []struct{ listen, token, want string }{
|
||||
{"0.0.0.0:8484", "abc", "http://localhost:8484/?t=abc"},
|
||||
{":8484", "abc", "http://localhost:8484/?t=abc"},
|
||||
{"[::]:8484", "abc", "http://localhost:8484/?t=abc"},
|
||||
{"127.0.0.1:8484", "", "http://127.0.0.1:8484/"},
|
||||
{"100.64.1.2:8484", "x", "http://100.64.1.2:8484/?t=x"},
|
||||
} {
|
||||
if got := DashboardURL(tc.listen, tc.token); got != tc.want {
|
||||
t.Errorf("DashboardURL(%q) = %q, want %q", tc.listen, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,273 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
// newTestPump builds a pump over the remote State Store contract, which is
|
||||
// the composition the UI process runs: the pump's only view of an event is
|
||||
// the one that came back over the wire.
|
||||
func newTestPump(t *testing.T, srv *Server) *eventPump {
|
||||
t.Helper()
|
||||
return srv.newEventPump()
|
||||
}
|
||||
|
||||
// Priming is what keeps the pump from replaying the whole events table into
|
||||
// every connected browser on startup. History is a client's own catch-up
|
||||
// (sseStream.catchUp), not the pump's job.
|
||||
func TestEventPumpPrimesPastHistoryThenDeliversNewEvents(t *testing.T) {
|
||||
srv := newRemoteTestServer(t)
|
||||
t0 := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
for _, detail := range []string{"first", "second"} {
|
||||
if _, err := srv.Store.InsertEvent(t.Context(), events.Event{Kind: "task_created", Detail: detail, At: t0}); err != nil {
|
||||
t.Fatalf("seed history: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
pump := newTestPump(t, srv)
|
||||
if err := pump.prime(t.Context()); err != nil {
|
||||
t.Fatalf("prime: %v", err)
|
||||
}
|
||||
|
||||
delivered, err := pump.deliver(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("deliver after prime: %v", err)
|
||||
}
|
||||
if delivered != 0 {
|
||||
t.Fatalf("pump delivered %d pre-existing events; priming must advance past history", delivered)
|
||||
}
|
||||
|
||||
t1 := time.Date(2026, 1, 1, 0, 0, 1, 0, time.UTC)
|
||||
id, err := srv.Store.InsertEvent(t.Context(), events.Event{Kind: "task_started", Detail: "after the pump", At: t1})
|
||||
if err != nil {
|
||||
t.Fatalf("insert live event: %v", err)
|
||||
}
|
||||
delivered, err = pump.deliver(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("deliver live event: %v", err)
|
||||
}
|
||||
if delivered != 1 {
|
||||
t.Fatalf("pump delivered %d events, want the 1 inserted after priming", delivered)
|
||||
}
|
||||
if want := storecontract.EventCursor(t1, id); pump.watermark != want {
|
||||
t.Fatalf("watermark = %q, want %q: the pump must not refetch a delivered event", pump.watermark, want)
|
||||
}
|
||||
}
|
||||
|
||||
// A store failure must not kill the pump: the next tick retries from the
|
||||
// same watermark, so a State Store restart costs latency, not the feed.
|
||||
func TestEventPumpKeepsItsWatermarkAcrossAStoreFailure(t *testing.T) {
|
||||
srv := newRemoteTestServer(t)
|
||||
pump := newTestPump(t, srv)
|
||||
if err := pump.prime(t.Context()); err != nil {
|
||||
t.Fatalf("prime: %v", err)
|
||||
}
|
||||
before := pump.watermark
|
||||
|
||||
cancelled, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
if _, err := pump.deliver(cancelled); err == nil {
|
||||
t.Fatal("deliver against a cancelled context returned no error")
|
||||
}
|
||||
if pump.watermark != before {
|
||||
t.Fatalf("watermark moved to %q on a failed fetch, want %q", pump.watermark, before)
|
||||
}
|
||||
}
|
||||
|
||||
// The bead's headline claim: an event written to the State Store by another
|
||||
// process reaches a browser hanging on /api/stream, with no in-process bus.
|
||||
func TestEventPumpReachesALiveSSEClient(t *testing.T) {
|
||||
srv := newRemoteTestServer(t)
|
||||
pump := newTestPump(t, srv)
|
||||
if err := pump.prime(t.Context()); err != nil {
|
||||
t.Fatalf("prime: %v", err)
|
||||
}
|
||||
|
||||
// handleSSE writes no response headers until its first send, so the
|
||||
// client blocks on Do() until something is on the wire. Seed one event
|
||||
// for catch-up to flush, then prove the pump delivers what comes after.
|
||||
if _, err := srv.Store.InsertEvent(t.Context(), events.Event{Kind: "task_created", Detail: "flushes the headers"}); err != nil {
|
||||
t.Fatalf("seed catch-up event: %v", err)
|
||||
}
|
||||
ts := newSSETestServer(t, srv)
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
lines := openSSEStream(t, ctx, ts)
|
||||
|
||||
go pump.run(ctx, 5*time.Millisecond)
|
||||
|
||||
if _, err := srv.Store.InsertEvent(t.Context(), events.Event{Kind: "task_started", Detail: "over the wire"}); err != nil {
|
||||
t.Fatalf("insert live event: %v", err)
|
||||
}
|
||||
|
||||
deadline := time.After(5 * time.Second)
|
||||
for {
|
||||
select {
|
||||
case line := <-lines:
|
||||
if strings.Contains(line, "over the wire") {
|
||||
return
|
||||
}
|
||||
case <-deadline:
|
||||
t.Fatal("live event never reached the SSE client; the pump is the only delivery path in the UI process")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// newSSETestServer serves the dashboard's real route set, so /api/stream goes
|
||||
// through requireToken and the mux exactly as a browser reaches it.
|
||||
func newSSETestServer(t *testing.T, srv *Server) *httptest.Server {
|
||||
t.Helper()
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
t.Cleanup(ts.Close)
|
||||
return ts
|
||||
}
|
||||
|
||||
// openSSEStream connects to /api/stream and relays each response line on a
|
||||
// channel. The request context ends the handler, which is what lets the
|
||||
// test server close.
|
||||
func openSSEStream(t *testing.T, ctx context.Context, ts *httptest.Server) <-chan string {
|
||||
t.Helper()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ts.URL+"/api/stream", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("sse request: %v", err)
|
||||
}
|
||||
resp, err := ts.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("GET /api/stream: %v", err)
|
||||
}
|
||||
// Closed at cleanup rather than by the reader goroutine: the body is the
|
||||
// live stream and must outlive this function, but it still has exactly
|
||||
// one owner and one close.
|
||||
t.Cleanup(func() { _ = resp.Body.Close() })
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("GET /api/stream = %d, want 200", resp.StatusCode)
|
||||
}
|
||||
lines := make(chan string, 64)
|
||||
go func() {
|
||||
defer close(lines)
|
||||
scanner := bufio.NewScanner(resp.Body)
|
||||
for scanner.Scan() {
|
||||
select {
|
||||
case lines <- scanner.Text():
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return
|
||||
}
|
||||
}()
|
||||
return lines
|
||||
}
|
||||
|
||||
// flakyEventReader fails its first failures calls, then answers an empty
|
||||
// table. It stands in for the State Store during the window where the UI
|
||||
// process is up and the store has not bound its listener yet.
|
||||
type flakyEventReader struct {
|
||||
failures int
|
||||
calls int
|
||||
}
|
||||
|
||||
func (f *flakyEventReader) EventsSince(context.Context, string, int) ([]events.Event, error) {
|
||||
f.calls++
|
||||
if f.calls <= f.failures {
|
||||
return nil, errors.New("connection refused")
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// archie-ui binds before archie-state-store is guaranteed to be listening, so
|
||||
// the first prime is routinely refused. Returning on that error left the
|
||||
// activity feed history-only until the process was restarted by hand.
|
||||
func TestPumpPriming(t *testing.T) {
|
||||
forever := 1 << 30
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
// failures is how many EventsSince calls are refused before the
|
||||
// store starts answering.
|
||||
failures int
|
||||
// deadline bounds the prime; zero means the test's own context, so
|
||||
// priming runs until it succeeds.
|
||||
deadline time.Duration
|
||||
wantErr bool
|
||||
wantCalls int // 0 means "unbounded, do not assert"
|
||||
}{
|
||||
{
|
||||
name: "retries until the store answers",
|
||||
failures: 3,
|
||||
wantCalls: 4,
|
||||
},
|
||||
{
|
||||
name: "gives up when the context ends",
|
||||
failures: forever,
|
||||
deadline: 20 * time.Millisecond,
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
reader := &flakyEventReader{failures: tc.failures}
|
||||
pump := &eventPump{
|
||||
store: reader,
|
||||
log: func(string, ...any) {},
|
||||
broadcast: func(events.Event) {},
|
||||
primeRetryMin: time.Millisecond,
|
||||
}
|
||||
|
||||
ctx := t.Context()
|
||||
if tc.deadline > 0 {
|
||||
timed, cancel := context.WithTimeout(ctx, tc.deadline)
|
||||
defer cancel()
|
||||
ctx = timed
|
||||
}
|
||||
|
||||
err := pump.primeWithRetry(ctx)
|
||||
if tc.wantErr && err == nil {
|
||||
t.Fatal("primeWithRetry returned no error")
|
||||
}
|
||||
if !tc.wantErr && err != nil {
|
||||
t.Fatalf("primeWithRetry: %v", err)
|
||||
}
|
||||
if tc.wantCalls > 0 && reader.calls != tc.wantCalls {
|
||||
t.Fatalf("EventsSince called %d times, want %d", reader.calls, tc.wantCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A dashboard route reloaded in the browser must get the app shell. The live
|
||||
// stream once sat at /events, the same path as the Events page, so a reload
|
||||
// there rendered the raw event stream instead of the page.
|
||||
func TestDashboardRoutesServeTheAppShell(t *testing.T) {
|
||||
ts := newSSETestServer(t, &Server{})
|
||||
for _, path := range []string{"/events", "/events?tab=inspector"} {
|
||||
t.Run(path, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ts.URL+path, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("GET %s: %v", path, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if ct := resp.Header.Get("Content-Type"); strings.HasPrefix(ct, "text/event-stream") {
|
||||
t.Fatalf("GET %s served the event stream, want the app shell", path)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,262 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
)
|
||||
|
||||
type liveResourceStore struct{ controlplane.ResourceStore }
|
||||
|
||||
func (*liveResourceStore) Resource(_ context.Context, _, kind string) (storecontract.Resource, error) {
|
||||
if kind == controlplane.PersonasKind {
|
||||
return storecontract.Resource{Kind: kind, Version: 1, Value: []byte(`{"default":"archie","personas":[]}`)}, nil
|
||||
}
|
||||
return storecontract.Resource{}, storecontract.ErrResourceNotFound
|
||||
}
|
||||
|
||||
// The real control-plane server (not a scripted Recv) must keep one upstream
|
||||
// Watch per generic kind independently of how many browser streams connect.
|
||||
// Its 250ms Resource poll runs once per kind, not once per browser.
|
||||
func TestLiveHubSharesRealControlPlaneWatches(t *testing.T) {
|
||||
steps, err := workflowsteps.NewManager()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
upstream, err := controlplane.NewServer(&liveResourceStore{}, steps)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var watches atomic.Int32
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
grpcServer := grpc.NewServer(grpc.StreamInterceptor(func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
|
||||
if info.FullMethod == controlpb.ControlPlaneService_Watch_FullMethodName {
|
||||
watches.Add(1)
|
||||
}
|
||||
return handler(srv, stream)
|
||||
}))
|
||||
controlpb.RegisterControlPlaneServiceServer(grpcServer, upstream)
|
||||
go func() { _ = grpcServer.Serve(listener) }()
|
||||
t.Cleanup(func() { grpcServer.Stop(); _ = listener.Close() })
|
||||
conn, err := grpc.NewClient("passthrough:///controlplane", 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() })
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
srv := &Server{ControlPlane: controlpb.NewControlPlaneServiceClient(conn), Store: &fakeEventStore{}, Log: slog.New(slog.DiscardHandler)}
|
||||
go srv.RunLive(ctx)
|
||||
catalog, err := upstream.Catalog(ctx, &controlpb.CatalogRequest{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
generic := 0
|
||||
for _, descriptor := range catalog.Resources {
|
||||
if descriptor.ApplyMode != "domain-managed" && descriptor.QueryService == "" {
|
||||
generic++
|
||||
}
|
||||
}
|
||||
waitUntil(t, func() bool { return int(watches.Load()) == generic })
|
||||
waitUntil(t, func() bool {
|
||||
srv.mu.Lock()
|
||||
defer srv.mu.Unlock()
|
||||
_, ok := srv.latest["control-plane/"+controlplane.PersonasKind]
|
||||
return ok
|
||||
})
|
||||
|
||||
httpServer := httptest.NewServer(srv.Handler())
|
||||
defer httpServer.Close()
|
||||
for range 3 {
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, httpServer.URL+"/api/stream", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
line, err := readTopic(bufio.NewScanner(response.Body), "control-plane")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var frame struct {
|
||||
Data controlPlaneResourceResponse `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(line), &frame); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if frame.Data.Resource.Kind != controlplane.PersonasKind || frame.Data.Resource.Version != 1 {
|
||||
t.Fatalf("late subscriber got %+v", frame.Data.Resource)
|
||||
}
|
||||
_ = response.Body.Close()
|
||||
}
|
||||
if got := int(watches.Load()); got != generic {
|
||||
t.Fatalf("%d upstream watches after three clients, want %d", got, generic)
|
||||
}
|
||||
}
|
||||
|
||||
func readTopic(scanner *bufio.Scanner, topic string) (string, error) {
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if !strings.HasPrefix(line, "data: ") {
|
||||
continue
|
||||
}
|
||||
data := strings.TrimPrefix(line, "data: ")
|
||||
var frame struct {
|
||||
Topic string `json:"topic"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(data), &frame); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if frame.Topic == topic {
|
||||
return data, nil
|
||||
}
|
||||
}
|
||||
return "", errors.New("stream ended before topic " + topic)
|
||||
}
|
||||
|
||||
func waitUntil(t *testing.T, ready func() bool) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if ready() {
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("live producer did not become ready")
|
||||
}
|
||||
|
||||
type countedIdentities struct {
|
||||
identity.Repository
|
||||
reads atomic.Int32
|
||||
}
|
||||
|
||||
func (f *countedIdentities) List(context.Context) ([]identity.Identity, error) {
|
||||
f.reads.Add(1)
|
||||
return []identity.Identity{identity.System()}, nil
|
||||
}
|
||||
|
||||
func TestIdentitiesPollOnceForSeveralClients(t *testing.T) {
|
||||
identities := &countedIdentities{}
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
srv := &Server{Store: &fakeEventStore{}, Log: slog.New(slog.DiscardHandler), Identities: identities}
|
||||
go srv.RunLive(ctx)
|
||||
waitUntil(t, func() bool { return identities.reads.Load() >= 1 })
|
||||
server := httptest.NewServer(srv.Handler())
|
||||
defer server.Close()
|
||||
for range 3 {
|
||||
request, _ := http.NewRequestWithContext(ctx, http.MethodGet, server.URL+"/api/stream", nil)
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if _, err := readTopic(bufio.NewScanner(response.Body), "identities"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
waitUntil(t, func() bool { return identities.reads.Load() >= 2 })
|
||||
if got := identities.reads.Load(); got != 2 {
|
||||
t.Fatalf("%d identity reads with three clients, want 2 (one per poll tick)", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlowLiveSubscriberIsDisconnectedForSnapshotReplay(t *testing.T) {
|
||||
srv := &Server{}
|
||||
_, _, stale, unregister := srv.registerSSEConn()
|
||||
defer unregister()
|
||||
for i := range 65 {
|
||||
srv.Broadcast(events.Event{ID: int64(i + 1), At: testAt})
|
||||
}
|
||||
select {
|
||||
case <-stale:
|
||||
default:
|
||||
t.Fatal("full subscriber was not disconnected: its dropped updates cannot be replayed until reconnect")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveStreamReplaysLogsOnlyWhenRequestedAndResumesBothCursors(t *testing.T) {
|
||||
feed := logging.NewFeed(20)
|
||||
// Feed's production writer stamps IDs; drive it through its public slog handler.
|
||||
log := slog.New(logging.NewFeedHandler(slog.NewTextHandler(new(bytes.Buffer), nil), feed))
|
||||
log.Info("before")
|
||||
srv := &Server{Store: &fakeEventStore{all: []events.Event{{ID: 1, At: testAt}, {ID: 2, At: testAt}}}, Log: slog.New(slog.DiscardHandler), LogFeed: feed}
|
||||
base := httptest.NewServer(srv.Handler())
|
||||
defer base.Close()
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
|
||||
defer cancel()
|
||||
get := func(path string) *http.Response {
|
||||
t.Helper()
|
||||
request, _ := http.NewRequestWithContext(ctx, http.MethodGet, base.URL+path, nil)
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return response
|
||||
}
|
||||
// A task-only connection must not subscribe to log traffic.
|
||||
plain := get("/api/stream")
|
||||
defer plain.Body.Close()
|
||||
withLogs := get("/api/stream?topics=logs")
|
||||
line, err := readTopic(bufio.NewScanner(withLogs.Body), "logs")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var frame struct {
|
||||
Data logging.Entry `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(line), &frame); err != nil || frame.Data.ID != 1 {
|
||||
t.Fatalf("log replay = %q, %v", line, err)
|
||||
}
|
||||
_ = withLogs.Body.Close()
|
||||
log.Info("after")
|
||||
cursor := streamCursors{Tasks: cursor(1), Logs: 1}.id()
|
||||
resumed := get("/api/stream?topics=logs&since=" + cursor)
|
||||
defer resumed.Body.Close()
|
||||
reader := bufio.NewScanner(resumed.Body)
|
||||
line, err = readTopic(reader, "tasks")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var taskFrame struct {
|
||||
Data events.Event `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(line), &taskFrame); err != nil || taskFrame.Data.ID != 2 {
|
||||
t.Fatalf("resumed task = %q, %v", line, err)
|
||||
}
|
||||
line, err = readTopic(reader, "logs")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := json.Unmarshal([]byte(line), &frame); err != nil || frame.Data.ID != 2 {
|
||||
t.Fatalf("resumed log = %q, %v", line, err)
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
@@ -1,165 +0,0 @@
|
||||
package webui
|
||||
|
||||
// Remote-contract coverage for the dashboard data paths. The production UI
|
||||
// process (archie-ui, and the daemon's webui) serves task, capture, mapping
|
||||
// and binding routes against a *staterpc.Client — the remote read contract —
|
||||
// not a concrete *pgstore.TaskDB. Every other webui test feeds a local store
|
||||
// directly, so none of them prove the handlers work once the data crosses the
|
||||
// gRPC wire. These do: they stand up a real SQLite store behind
|
||||
// staterpc.RegisterServer, dial it, and assert the handlers serve correctly.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
)
|
||||
|
||||
// newRemoteTestServer serves a real SQLite store behind a gRPC listener and
|
||||
// returns a webui.Server whose store fields are all the remote *staterpc.Client.
|
||||
// This is the composition the UI Service uses; it exercises the full
|
||||
// round-trip (handler -> narrow interface -> client -> wire -> server -> store)
|
||||
// rather than a fake.
|
||||
func newRemoteTestServer(t *testing.T) *Server {
|
||||
t.Helper()
|
||||
st := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
listener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
server := grpc.NewServer()
|
||||
// Two stores, as in the real composition: the task store serves the task
|
||||
// surfaces, the event-capture store serves captures/mappings/bindings.
|
||||
// Leaving one nil makes ListMappings/ListBindings fail closed with
|
||||
// err*Unavailable, which is also the real wiring.
|
||||
eda := pgstore.EDA(t, nil)
|
||||
staterpc.RegisterServer(server, staterpc.Deps{
|
||||
Tasks: st,
|
||||
Captures: eda,
|
||||
Mappings: eda,
|
||||
Bindings: eda,
|
||||
BindingDispatcher: eda,
|
||||
BindingTaskCreator: st,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
})
|
||||
go func() { _ = server.Serve(listener) }()
|
||||
t.Cleanup(server.Stop)
|
||||
|
||||
client, closeConn, err := staterpc.Dial(listener.Addr().String(), "")
|
||||
if err != nil {
|
||||
t.Fatalf("dial state store: %v", err)
|
||||
}
|
||||
t.Cleanup(closeConn)
|
||||
|
||||
return &Server{
|
||||
Store: client,
|
||||
Captures: client,
|
||||
Mappings: client,
|
||||
Bindings: client,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
CaptureMaxEvents: 10,
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteEndpointFamiliesServeOverReadContracts(t *testing.T) {
|
||||
srv := newRemoteTestServer(t)
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("summary", func(t *testing.T) {
|
||||
rr := httptest.NewRecorder()
|
||||
srv.handleSummary(rr, httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/summary", nil))
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Fatalf("GET /api/summary = %d, body %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("tasks_and_timeline", func(t *testing.T) {
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "remote task", "", "", ""); err != nil {
|
||||
t.Fatalf("enqueue: %v", err)
|
||||
}
|
||||
task, err := srv.Store.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("claim (%v, %v)", task, err)
|
||||
}
|
||||
if err := srv.Store.Transition(ctx, task.ID, workflow.StatusRunning, workflow.StatusWaitingHuman, "needs info"); err != nil {
|
||||
t.Fatalf("transition: %v", err)
|
||||
}
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
srv.handleTasks(rr, httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/tasks", nil))
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Fatalf("GET /api/tasks = %d, body %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
if !strings.Contains(rr.Body.String(), "remote task") {
|
||||
t.Fatalf("task not in response: %s", rr.Body.String())
|
||||
}
|
||||
|
||||
// The {id} route reads the task's events over the wire. handleTask
|
||||
// reads r.PathValue("id"), which only the mux populates, so this goes
|
||||
// through Server.Handler() rather than a direct handler call — the
|
||||
// realistic path and the one that exercises routing too.
|
||||
handler := srv.Handler()
|
||||
rr2 := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rr2, httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/tasks/"+strconv.FormatInt(task.ID, 10), nil))
|
||||
if rr2.Code != http.StatusOK {
|
||||
t.Fatalf("GET /api/tasks/{id} = %d, body %s", rr2.Code, rr2.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("mappings", func(t *testing.T) {
|
||||
rr := httptest.NewRecorder()
|
||||
srv.handleMappingsList(rr, httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/mappings", nil))
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Fatalf("GET /api/mappings = %d, body %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("bindings", func(t *testing.T) {
|
||||
rr := httptest.NewRecorder()
|
||||
srv.handleBindingsList(rr, httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/bindings", nil))
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Fatalf("GET /api/bindings = %d, body %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestRemoteLogAndHealthDegrade covers the two paths with no State Store
|
||||
// contract: logs (in-process feed, nil in a remote composition) report
|
||||
// disabled, and health consults the local registry (nil here) rather than a
|
||||
// concrete store. Both are deliberate degradation, not gaps to fill by
|
||||
// inventing a contract.
|
||||
func TestRemoteLogAndHealthDegrade(t *testing.T) {
|
||||
srv := newRemoteTestServer(t)
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("logs_disabled", func(t *testing.T) {
|
||||
rr := httptest.NewRecorder()
|
||||
srv.handleLogs(rr, httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/logs", nil))
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Fatalf("GET /api/logs = %d, body %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
if !strings.Contains(rr.Body.String(), "disabled") {
|
||||
t.Fatalf("expected logs to report disabled, got %s", rr.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("health_without_registry", func(t *testing.T) {
|
||||
rr := httptest.NewRecorder()
|
||||
srv.handleHealthDetailed(rr, httptest.NewRequestWithContext(ctx, http.MethodGet, "/health/detailed", nil))
|
||||
if rr.Code != http.StatusOK && rr.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("GET /health/detailed = %d, body %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,298 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
// testAt is a fixed instant every synthetic event in this file shares, so a
|
||||
// cursor can be built for an event from its id alone. Two events sharing a
|
||||
// timestamp exercise the id tie-break, which is the point of the cursor.
|
||||
var testAt = time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
|
||||
// cursor builds the opaque resume cursor for a synthetic event with id id.
|
||||
func cursor(id int64) string {
|
||||
return storecontract.EventCursor(testAt, id)
|
||||
}
|
||||
|
||||
func newTestSSEStream(since string) (*sseStream, *httptest.ResponseRecorder) {
|
||||
rec := httptest.NewRecorder()
|
||||
return &sseStream{
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
w: rec,
|
||||
fl: rec,
|
||||
since: since,
|
||||
}, rec
|
||||
}
|
||||
|
||||
// sendPage is the seam catchUp's page-boundary logic depends on: it must
|
||||
// stop the instant target is reached, even mid-page, rather than sending
|
||||
// events beyond what the caller asked for.
|
||||
func TestSSEStreamSendPageStopsAtTargetMidPage(t *testing.T) {
|
||||
s, _ := newTestSSEStream("")
|
||||
backlog := []events.Event{
|
||||
{ID: 1, At: testAt},
|
||||
{ID: 2, At: testAt},
|
||||
{ID: 3, At: testAt},
|
||||
{ID: 4, At: testAt},
|
||||
{ID: 5, At: testAt},
|
||||
}
|
||||
|
||||
reachedTarget, ok := s.sendPage(backlog, cursor(3))
|
||||
|
||||
if !ok {
|
||||
t.Fatal("sendPage() ok = false, want true")
|
||||
}
|
||||
if !reachedTarget {
|
||||
t.Fatal("reachedTarget = false, want true: target 3 was inside the page")
|
||||
}
|
||||
if s.since != cursor(3) {
|
||||
t.Fatalf("since = %q, want %q (stopped at the target, not the end of the page)", s.since, cursor(3))
|
||||
}
|
||||
}
|
||||
|
||||
// A target beyond the page must not be reported reached: the caller needs
|
||||
// another page.
|
||||
func TestSSEStreamSendPageDoesNotReportTargetReachedBeyondThePage(t *testing.T) {
|
||||
s, _ := newTestSSEStream("")
|
||||
backlog := []events.Event{{ID: 1, At: testAt}, {ID: 2, At: testAt}, {ID: 3, At: testAt}}
|
||||
|
||||
reachedTarget, ok := s.sendPage(backlog, cursor(10))
|
||||
|
||||
if !ok {
|
||||
t.Fatal("sendPage() ok = false, want true")
|
||||
}
|
||||
if reachedTarget {
|
||||
t.Fatal("reachedTarget = true, want false: target 10 was never reached in this page")
|
||||
}
|
||||
if s.since != cursor(3) {
|
||||
t.Fatalf("since = %q, want %q (the whole page was sent)", s.since, cursor(3))
|
||||
}
|
||||
}
|
||||
|
||||
// target == "" means "drain everything available"; sendPage must never
|
||||
// treat it as a target to stop at, or catchUp's initial call (which always
|
||||
// passes "") would stop after the very first event.
|
||||
func TestSSEStreamSendPageIgnoresZeroTarget(t *testing.T) {
|
||||
s, _ := newTestSSEStream("")
|
||||
backlog := []events.Event{{ID: 1, At: testAt}, {ID: 2, At: testAt}, {ID: 3, At: testAt}}
|
||||
|
||||
reachedTarget, ok := s.sendPage(backlog, "")
|
||||
|
||||
if !ok || reachedTarget {
|
||||
t.Fatalf("sendPage(target=\"\") = (%v, %v), want (false, true)", reachedTarget, ok)
|
||||
}
|
||||
if s.since != cursor(3) {
|
||||
t.Fatalf("since = %q, want %q (the whole page was sent)", s.since, cursor(3))
|
||||
}
|
||||
}
|
||||
|
||||
// A send failure must stop the page immediately and report failure, not
|
||||
// silently skip the failed event and keep going.
|
||||
func TestSSEStreamSendPageStopsOnWriteFailure(t *testing.T) {
|
||||
s, _ := newTestSSEStream("")
|
||||
s.w = failingWriter{}
|
||||
backlog := []events.Event{{ID: 1, At: testAt}, {ID: 2, At: testAt}}
|
||||
|
||||
reachedTarget, ok := s.sendPage(backlog, "")
|
||||
|
||||
if ok {
|
||||
t.Fatal("sendPage() ok = true, want false: the write failed")
|
||||
}
|
||||
if reachedTarget {
|
||||
t.Fatal("reachedTarget = true, want false on failure")
|
||||
}
|
||||
if s.since != "" {
|
||||
t.Fatalf("since = %q, want empty (unchanged: the first send already failed)", s.since)
|
||||
}
|
||||
}
|
||||
|
||||
// failingWriter fails every Write, so send() can be tested against a dead
|
||||
// connection without a real network failure.
|
||||
type failingWriter struct{}
|
||||
|
||||
func (failingWriter) Header() http.Header { return http.Header{} }
|
||||
func (failingWriter) Write([]byte) (int, error) { return 0, errWriteFailed }
|
||||
func (failingWriter) WriteHeader(statusCode int) {}
|
||||
|
||||
var errWriteFailed = errors.New("write failed")
|
||||
|
||||
// fakeEventStore serves EventsSince from a fixed, pre-seeded slice, paginating
|
||||
// the same way the real store does: up to limit events after cursor.
|
||||
type fakeEventStore struct {
|
||||
storecontract.TaskStore
|
||||
all []events.Event
|
||||
}
|
||||
|
||||
func (f *fakeEventStore) EventsSince(_ context.Context, since string, limit int) ([]events.Event, error) {
|
||||
page := make([]events.Event, 0, limit)
|
||||
for _, e := range f.all {
|
||||
if storecontract.EventCursor(e.At, e.ID) <= since {
|
||||
continue
|
||||
}
|
||||
page = append(page, e)
|
||||
if len(page) >= limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// catchUp must page across more than one EventsSince fetch when the backlog
|
||||
// exceeds sseBacklogPageSize in one page, rather than stopping after the
|
||||
// first page as though that were everything.
|
||||
func TestSSEStreamCatchUpPagesAcrossMultipleFetches(t *testing.T) {
|
||||
const total = sseBacklogPageSize + 50
|
||||
all := make([]events.Event, total)
|
||||
for i := range all {
|
||||
all[i] = events.Event{ID: int64(i + 1), At: testAt}
|
||||
}
|
||||
|
||||
s, rec := newTestSSEStream("")
|
||||
s.store = &fakeEventStore{all: all}
|
||||
|
||||
if !s.catchUp(context.Background(), "") {
|
||||
t.Fatal("catchUp() = false, want true")
|
||||
}
|
||||
if s.since != cursor(total) {
|
||||
t.Fatalf("since = %q, want %q (every event drained across pages)", s.since, cursor(total))
|
||||
}
|
||||
if n := countSSEFrames(rec.Body.String()); n != total {
|
||||
t.Fatalf("sent %d SSE frames, want %d", n, total)
|
||||
}
|
||||
}
|
||||
|
||||
// Every task frame identifies its topic so one EventSource can dispatch it
|
||||
// without interpreting the event's domain payload.
|
||||
func TestSSETaskFrameCarriesTopic(t *testing.T) {
|
||||
stream, rec := newTestSSEStream("")
|
||||
if !stream.send(events.Event{ID: 1, At: testAt, Kind: events.KindTaskQueued}) {
|
||||
t.Fatal("send failed")
|
||||
}
|
||||
line := strings.Split(rec.Body.String(), "\n")[1]
|
||||
var frame struct {
|
||||
Topic string `json:"topic"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &frame); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if frame.Topic != "tasks" {
|
||||
t.Fatalf("topic = %q, want tasks", frame.Topic)
|
||||
}
|
||||
}
|
||||
|
||||
// A target landing exactly on the last event of a full page must still be
|
||||
// recognised as reached, not mistaken for "page not yet exhausted, fetch
|
||||
// another".
|
||||
func TestSSEStreamCatchUpStopsAtTargetOnPageBoundary(t *testing.T) {
|
||||
all := make([]events.Event, sseBacklogPageSize+50)
|
||||
for i := range all {
|
||||
all[i] = events.Event{ID: int64(i + 1), At: testAt}
|
||||
}
|
||||
|
||||
s, _ := newTestSSEStream("")
|
||||
s.store = &fakeEventStore{all: all}
|
||||
|
||||
if !s.catchUp(context.Background(), cursor(sseBacklogPageSize)) {
|
||||
t.Fatal("catchUp() = false, want true")
|
||||
}
|
||||
if s.since != cursor(sseBacklogPageSize) {
|
||||
t.Fatalf("since = %q, want %q (stopped exactly at the target, not the whole backlog)", s.since, cursor(sseBacklogPageSize))
|
||||
}
|
||||
}
|
||||
|
||||
// countSSEFrames counts "data:" lines, which appear exactly once per event
|
||||
// frame (see sseStream.send's "id: ...\ndata: ...\n\n" format).
|
||||
func countSSEFrames(body string) int {
|
||||
return strings.Count(body, "\ndata: ")
|
||||
}
|
||||
|
||||
// TestSSEStreamSendPageSkipsNoiseKindsButAdvancesSince is the regression
|
||||
// test for archie-core-521: turn_completed fires on every chat turn with no
|
||||
// task correlation (Detail is a raw session ID, no TaskID), and dominated
|
||||
// the dashboard's Live Activity panel. It must never reach the SSE client,
|
||||
// but since must still advance past it -- otherwise the next catchUp
|
||||
// refetches the same filtered event forever, since EventsSince only ever
|
||||
// returns events after since.
|
||||
func TestSSEStreamSendPageSkipsNoiseKindsButAdvancesSince(t *testing.T) {
|
||||
s, rec := newTestSSEStream("")
|
||||
backlog := []events.Event{
|
||||
{ID: 1, At: testAt, Kind: events.KindTaskQueued},
|
||||
{ID: 2, At: testAt, Kind: events.KindTurnCompleted, Detail: "100000000"},
|
||||
{ID: 3, At: testAt, Kind: events.KindTurnCompleted, Detail: "100000000"},
|
||||
{ID: 4, At: testAt, Kind: events.KindParked},
|
||||
}
|
||||
|
||||
reachedTarget, ok := s.sendPage(backlog, "")
|
||||
|
||||
if !ok || reachedTarget {
|
||||
t.Fatalf("sendPage() = (%v, %v), want (false, true)", reachedTarget, ok)
|
||||
}
|
||||
if s.since != cursor(4) {
|
||||
t.Fatalf("since = %q, want %q (advanced past every event, including filtered ones)", s.since, cursor(4))
|
||||
}
|
||||
if n := countSSEFrames(rec.Body.String()); n != 2 {
|
||||
t.Fatalf("sent %d SSE frames, want 2 (turn_completed excluded)", n)
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), "turn_completed") {
|
||||
t.Error("SSE body contains a turn_completed frame, want it excluded entirely")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSEMultiTopicCursorHeaderWinsOverDeliberateReconnectURL(t *testing.T) {
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodGet,
|
||||
"/api/stream?topics=logs&since="+streamCursors{Tasks: cursor(1), Logs: 4}.id(), nil)
|
||||
request.Header.Set("Last-Event-ID", streamCursors{Tasks: cursor(2), Logs: 5}.id())
|
||||
got := sseCursors(request)
|
||||
if got.Tasks != cursor(2) || got.Logs != 5 {
|
||||
t.Fatalf("cursors = %+v, want tasks 2 and logs 5 from native reconnect", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSSESinceDegradesUnparseableCursorToBeginning is the legacy-cursor
|
||||
// tolerance guard: a browser holding the pre-cursor integer id: field, or a
|
||||
// ?since= carrying garbage, must resume from the beginning rather than error
|
||||
// or skip. This deliberately preserves the old failed-ParseInt-yields-0
|
||||
// degradation.
|
||||
func TestSSESinceDegradesUnparseableCursorToBeginning(t *testing.T) {
|
||||
valid := storecontract.EventCursor(testAt, 1)
|
||||
tests := []struct {
|
||||
name string
|
||||
since string
|
||||
header string
|
||||
want string
|
||||
}{
|
||||
{name: "absent", want: ""},
|
||||
{name: "legacy integer header", header: "42", want: ""},
|
||||
{name: "garbage query", since: "not-a-cursor", want: ""},
|
||||
{name: "garbage header", header: "garbage", want: ""},
|
||||
{name: "valid query cursor", since: valid, want: valid},
|
||||
{name: "valid header cursor beats garbage query", since: "garbage", header: valid, want: valid},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/stream", nil)
|
||||
if tt.since != "" {
|
||||
q := req.URL.Query()
|
||||
q.Set("since", tt.since)
|
||||
req.URL.RawQuery = q.Encode()
|
||||
}
|
||||
if tt.header != "" {
|
||||
req.Header.Set("Last-Event-ID", tt.header)
|
||||
}
|
||||
if got := sseSince(req); got != tt.want {
|
||||
t.Fatalf("sseSince = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/releaseupdate"
|
||||
)
|
||||
|
||||
// TestHandleChatUpdateInstallSetsReportPath is the regression proof: before
|
||||
// this fix, the webui install handler passed
|
||||
// releaseupdate.InstallMeta{Channel: "webui"} with no ReportPath, so the
|
||||
// watchdog's write_report() (scripts/archie-update-watchdog) silently
|
||||
// returned without ever writing a phase-2 report.
|
||||
func TestHandleChatUpdateInstallSetsReportPath(t *testing.T) {
|
||||
reportPath := filepath.Join(t.TempDir(), "update-report.json")
|
||||
updates := &chatUpdateStub{snapshot: releaseupdate.Snapshot{
|
||||
Components: []releaseupdate.Component{{ID: "gateway", Label: "Gateway", Installed: "1.0", Available: "1.1"}},
|
||||
}}
|
||||
sessions := gateway.NewSessionStoreMemory()
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
router := gateway.NewRouter(chatStatusStub{}, nil, "web")
|
||||
server := &Server{Chat: testChatService(router, sessions, nil, nil, nil, updates, nil), UpdateReportPath: reportPath}
|
||||
|
||||
body, err := json.Marshal(chatUpdateRequest{Snapshot: updates.snapshot})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(res, httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/chat/update/install", bytes.NewReader(body)))
|
||||
if res.Code != http.StatusOK || !updates.installed {
|
||||
t.Fatalf("update install = %d, body = %s", res.Code, res.Body.String())
|
||||
}
|
||||
if updates.installedMeta.ReportPath != reportPath {
|
||||
t.Errorf("ReportPath = %q, want %q", updates.installedMeta.ReportPath, reportPath)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleChatUpdateInstallRoutesRestartReportToTelegram(t *testing.T) {
|
||||
reportPath := filepath.Join(t.TempDir(), "telegram-update-report.json")
|
||||
updates := &chatUpdateStub{snapshot: releaseupdate.Snapshot{
|
||||
Components: []releaseupdate.Component{{ID: "gateway", Label: "Gateway", Installed: "1.0", Available: "1.1"}},
|
||||
}}
|
||||
sessions := gateway.NewSessionStoreMemory()
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
router := gateway.NewRouter(chatStatusStub{}, nil, "web")
|
||||
server := &Server{
|
||||
Chat: testChatService(router, sessions, nil, nil, nil, updates, nil),
|
||||
UpdateReportPath: filepath.Join(t.TempDir(), "webui-update-report.json"),
|
||||
TelegramUpdateReportPath: reportPath,
|
||||
TelegramUpdateChatID: 42,
|
||||
}
|
||||
|
||||
body, err := json.Marshal(chatUpdateRequest{Snapshot: updates.snapshot})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(res, httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/chat/update/install", bytes.NewReader(body)))
|
||||
if res.Code != http.StatusOK || !updates.installed {
|
||||
t.Fatalf("update install = %d, body = %s", res.Code, res.Body.String())
|
||||
}
|
||||
if updates.installedMeta.Channel != "telegram" {
|
||||
t.Errorf("Channel = %q, want telegram", updates.installedMeta.Channel)
|
||||
}
|
||||
if updates.installedMeta.ChatID != 42 {
|
||||
t.Errorf("ChatID = %d, want 42", updates.installedMeta.ChatID)
|
||||
}
|
||||
if updates.installedMeta.ReportPath != reportPath {
|
||||
t.Errorf("ReportPath = %q, want %q", updates.installedMeta.ReportPath, reportPath)
|
||||
}
|
||||
}
|
||||
@@ -1,522 +0,0 @@
|
||||
package webui
|
||||
|
||||
// The dashboard moved from a hand-written index.html embedded in this package
|
||||
// to the Vite build in ui/. Four tests were removed with it:
|
||||
//
|
||||
// - TestIndexContainsViewportMeta, TestIndexHasResponsiveFeatures asserted
|
||||
// markup and CSS that now live in ui/index.html and ui/src/css/.
|
||||
// - TestIndexEscapesSingleQuotesInOnclick, TestIndexEscDoesNotEscapeSingleQuotes
|
||||
// guarded against injection through string-interpolated onclick handlers.
|
||||
// That bug is no longer reachable: ui/src/base/dom.js builds nodes with
|
||||
// createTextNode and addEventListener, so no markup is assembled from
|
||||
// strings at all.
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
func newTestServer(t *testing.T) *Server {
|
||||
t.Helper()
|
||||
s := pgstore.Open(t)
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
srv := &Server{Store: s, Steps: s, Log: slog.New(slog.DiscardHandler)}
|
||||
// Composition always gives the dashboard a Gateway contract; task
|
||||
// actions travel through it now, so a test server without one could
|
||||
// only ever answer 503.
|
||||
wireOperatorActions(srv)
|
||||
return srv
|
||||
}
|
||||
|
||||
// stubStore wraps a real TaskStore and overrides selected methods to
|
||||
// inject errors. Methods that are not overridden delegate to the inner
|
||||
// store via the embedded interface.
|
||||
type stubStore struct {
|
||||
storecontract.TaskStore
|
||||
workflowStatsErr error
|
||||
stageStatsErr error
|
||||
tokensByDayErr error
|
||||
eventsSinceErr error
|
||||
taskEventsErr error
|
||||
taskByIDErr error
|
||||
requeueErr error
|
||||
}
|
||||
|
||||
func (s *stubStore) TaskByID(ctx context.Context, id int64) (*workflow.Task, error) {
|
||||
if s.taskByIDErr != nil {
|
||||
return nil, s.taskByIDErr
|
||||
}
|
||||
return s.TaskStore.TaskByID(ctx, id)
|
||||
}
|
||||
|
||||
func (s *stubStore) Requeue(ctx context.Context, id int64, from, workflow string) error {
|
||||
if s.requeueErr != nil {
|
||||
return s.requeueErr
|
||||
}
|
||||
return s.TaskStore.Requeue(ctx, id, from, workflow)
|
||||
}
|
||||
|
||||
func (s *stubStore) WorkflowStats(ctx context.Context) ([]storecontract.WorkflowStat, error) {
|
||||
if s.workflowStatsErr != nil {
|
||||
return nil, s.workflowStatsErr
|
||||
}
|
||||
return s.TaskStore.WorkflowStats(ctx)
|
||||
}
|
||||
|
||||
func (s *stubStore) StageStats(ctx context.Context) ([]storecontract.StageStat, error) {
|
||||
if s.stageStatsErr != nil {
|
||||
return nil, s.stageStatsErr
|
||||
}
|
||||
return s.TaskStore.StageStats(ctx)
|
||||
}
|
||||
|
||||
func (s *stubStore) TokensByDay(ctx context.Context, days int) ([]storecontract.DayTokens, error) {
|
||||
if s.tokensByDayErr != nil {
|
||||
return nil, s.tokensByDayErr
|
||||
}
|
||||
return s.TaskStore.TokensByDay(ctx, days)
|
||||
}
|
||||
|
||||
func (s *stubStore) EventsSince(ctx context.Context, cursor string, limit int) ([]events.Event, error) {
|
||||
if s.eventsSinceErr != nil {
|
||||
return nil, s.eventsSinceErr
|
||||
}
|
||||
return s.TaskStore.EventsSince(ctx, cursor, limit)
|
||||
}
|
||||
|
||||
func (s *stubStore) TaskEvents(ctx context.Context, taskID int64) ([]events.Event, error) {
|
||||
if s.taskEventsErr != nil {
|
||||
return nil, s.taskEventsErr
|
||||
}
|
||||
return s.TaskStore.TaskEvents(ctx, taskID)
|
||||
}
|
||||
|
||||
func TestHandleSummary(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "t", "b", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/summary", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
var got map[string]any
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, key := range []string{"statuses", "workflows", "stages", "tokens_by_day"} {
|
||||
if _, ok := got[key]; !ok {
|
||||
t.Errorf("summary missing key %q: %+v", key, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleSummaryWorkflowStatsError proves that handleSummary does not
|
||||
// silently discard an error from WorkflowStats. Today the handler uses
|
||||
// blank-identifier assignment (workflows, _ := ...), so this test FAILS
|
||||
// (wants 500, gets 200 with nil workflows).
|
||||
func TestHandleSummaryWorkflowStatsError(t *testing.T) {
|
||||
base := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
srv := &Server{
|
||||
Store: &stubStore{
|
||||
TaskStore: base.Store,
|
||||
workflowStatsErr: fmt.Errorf("db locked"),
|
||||
},
|
||||
Log: base.Log,
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/summary", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status = %d, want 500 — WorkflowStats error was silently discarded", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleSummaryStageStatsError proves that handleSummary does not
|
||||
// silently discard an error from StageStats.
|
||||
func TestHandleSummaryStageStatsError(t *testing.T) {
|
||||
base := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
srv := &Server{
|
||||
Store: &stubStore{
|
||||
TaskStore: base.Store,
|
||||
stageStatsErr: fmt.Errorf("db locked"),
|
||||
},
|
||||
Log: base.Log,
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/summary", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status = %d, want 500 — StageStats error was silently discarded", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleSummaryTokensByDayError proves that handleSummary does not
|
||||
// silently discard an error from TokensByDay.
|
||||
func TestHandleSummaryTokensByDayError(t *testing.T) {
|
||||
base := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
srv := &Server{
|
||||
Store: &stubStore{
|
||||
TaskStore: base.Store,
|
||||
tokensByDayErr: fmt.Errorf("db locked"),
|
||||
},
|
||||
Log: base.Log,
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/summary", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status = %d, want 500 — TokensByDay error was silently discarded", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleTasks(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "hello", "b", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/tasks", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
var got []workflow.Task
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 1 || got[0].Title != "hello" {
|
||||
t.Fatalf("tasks = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleTask(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "t", "b", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 1)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("TaskByIssue = (%+v, %v)", task, err)
|
||||
}
|
||||
if _, err := srv.Store.InsertEvent(ctx, events.Event{Kind: "stage_start", TaskID: task.ID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/tasks/"+strconv.FormatInt(task.ID, 10), nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
var got []events.Event
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 1 || got[0].Kind != "stage_start" {
|
||||
t.Fatalf("task events = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleTaskBadID(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/tasks/not-a-number", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleIndex(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d", w.Code)
|
||||
}
|
||||
if ct := w.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/html") {
|
||||
t.Fatalf("content-type = %q", ct)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHealthzIsReachableWithoutAToken: the update watchdog script polls
|
||||
// this endpoint from the local host after restarting archied, with no
|
||||
// dashboard session -- it must never require the dashboard token, unlike
|
||||
// every other route.
|
||||
func TestHealthzIsReachableWithoutAToken(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.Token = "dashboard-secret"
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/healthz", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %q", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleSSEEventsSinceError proves that handleSSE does not silently
|
||||
// discard an error from EventsSince. Today the handler has no else
|
||||
// branch for err != nil, so the error is swallowed and the client
|
||||
// receives no signal that catch-up was skipped: this test FAILS.
|
||||
func TestHandleSSEEventsSinceError(t *testing.T) {
|
||||
actual := newTestServer(t)
|
||||
srv := &Server{
|
||||
Store: &stubStore{
|
||||
TaskStore: actual.Store,
|
||||
eventsSinceErr: fmt.Errorf("db locked"),
|
||||
},
|
||||
Log: actual.Log,
|
||||
}
|
||||
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
t.Cleanup(ts.Close)
|
||||
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ts.URL+"/api/stream?since=0", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("EventsSince error silently swallowed — SSE handler never responded: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
reader := bufio.NewReader(resp.Body)
|
||||
// The SSE stream must surface the EventsSince error to the client.
|
||||
// Today the error is silently swallowed, so no error line is ever
|
||||
// sent and the test FAILS.
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
line, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if strings.Contains(line, "error") {
|
||||
return // PASS: error was surfaced to the client
|
||||
}
|
||||
}
|
||||
t.Fatal("EventsSince error was silently swallowed — no error sent to SSE client")
|
||||
}
|
||||
|
||||
func TestHandleSSEUsesLastEventIDForCatchUp(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
|
||||
defer cancel()
|
||||
at := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
first, err := srv.Store.InsertEvent(ctx, events.Event{Kind: "log", Detail: "first", At: at})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := srv.Store.InsertEvent(ctx, events.Event{Kind: "log", Detail: "second", At: at}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
t.Cleanup(ts.Close)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ts.URL+"/api/stream", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Last-Event-ID", storecontract.EventCursor(at, first))
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = resp.Body.Close() })
|
||||
|
||||
reader := bufio.NewReader(resp.Body)
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
line, readErr := reader.ReadString('\n')
|
||||
if readErr != nil {
|
||||
t.Fatalf("second event not received after Last-Event-ID: %v", readErr)
|
||||
}
|
||||
if strings.HasPrefix(line, "data:") {
|
||||
if strings.Contains(line, "first") {
|
||||
t.Fatalf("replayed event before Last-Event-ID: %q", line)
|
||||
}
|
||||
if strings.Contains(line, "second") {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
t.Fatal("second event not received after Last-Event-ID")
|
||||
}
|
||||
|
||||
func TestHandleSSEBacklogAndLive(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
|
||||
defer cancel()
|
||||
t0 := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
id, err := srv.Store.InsertEvent(ctx, events.Event{Kind: "log", Detail: "backlog", At: t0})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
t.Cleanup(ts.Close)
|
||||
|
||||
// The request carries t.Context() so the SSE stream is torn down when
|
||||
// the test ends rather than leaking the connection and its goroutine.
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ts.URL+"/api/stream", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = resp.Body.Close() })
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
reader := bufio.NewReader(resp.Body)
|
||||
line, err := readLineUntil(reader, "backlog")
|
||||
if err != nil {
|
||||
t.Fatalf("backlog event not received: %v (%q)", err, line)
|
||||
}
|
||||
|
||||
// Now broadcast a live event and confirm it's delivered too. Give
|
||||
// the SSE handler a moment to register its subscriber.
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
srv.Broadcast(events.Event{ID: id + 1, Kind: "log", Detail: "live", At: t0.Add(time.Second)})
|
||||
|
||||
if _, err := readLineUntil(reader, "live"); err != nil {
|
||||
t.Fatalf("live event not received: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleSSEFiltersTurnCompletedFromLiveBroadcast covers the live half of
|
||||
// the archie-core-521 fix: sendPage's filtering is exercised directly in
|
||||
// sse_test.go, but the live broadcast path (drain) has its own send call.
|
||||
// A turn_completed broadcast between two ordinary events must never reach
|
||||
// the client, while the ordinary events either side of it still do.
|
||||
func TestHandleSSEFiltersTurnCompletedFromLiveBroadcast(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
|
||||
defer cancel()
|
||||
t0 := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
id, err := srv.Store.InsertEvent(ctx, events.Event{Kind: "log", Detail: "backlog", At: t0})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
t.Cleanup(ts.Close)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ts.URL+"/api/stream", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = resp.Body.Close() })
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
reader := bufio.NewReader(resp.Body)
|
||||
if _, err := readLineUntil(reader, "backlog"); err != nil {
|
||||
t.Fatalf("backlog event not received: %v", err)
|
||||
}
|
||||
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
srv.Broadcast(events.Event{ID: id + 1, Kind: events.KindTurnCompleted, Detail: "100000000", At: t0.Add(time.Second)})
|
||||
srv.Broadcast(events.Event{ID: id + 2, Kind: "log", Detail: "after-noise", At: t0.Add(2 * time.Second)})
|
||||
|
||||
seen, err := readLinesUntil(reader, "after-noise")
|
||||
if err != nil {
|
||||
t.Fatalf("event after the filtered one was not received: %v", err)
|
||||
}
|
||||
for _, line := range seen {
|
||||
if strings.Contains(line, "turn_completed") {
|
||||
t.Fatalf("the filtered event's frame reached the client: %q", line)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// readLineUntil scans SSE "data:" lines until one contains want.
|
||||
func readLineUntil(r *bufio.Reader, want string) (string, error) {
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
line, err := r.ReadString('\n')
|
||||
if err != nil {
|
||||
return line, err
|
||||
}
|
||||
if strings.HasPrefix(line, "data:") && strings.Contains(line, want) {
|
||||
return line, nil
|
||||
}
|
||||
}
|
||||
return "", io.EOF
|
||||
}
|
||||
|
||||
// readLinesUntil scans SSE "data:" lines, collecting every one seen, until
|
||||
// one contains want -- unlike readLineUntil, callers get the full scan, not
|
||||
// just the matched line, so a frame that arrived before the match but was
|
||||
// never asserted on can't hide there.
|
||||
func readLinesUntil(r *bufio.Reader, want string) ([]string, error) {
|
||||
var seen []string
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
line, err := r.ReadString('\n')
|
||||
if err != nil {
|
||||
return seen, err
|
||||
}
|
||||
if !strings.HasPrefix(line, "data:") {
|
||||
continue
|
||||
}
|
||||
seen = append(seen, line)
|
||||
if strings.Contains(line, want) {
|
||||
return seen, nil
|
||||
}
|
||||
}
|
||||
return seen, io.EOF
|
||||
}
|
||||
Reference in new issue
Block a user