diff --git a/platform/README.md b/platform/README.md index acab307..ba2af97 100644 --- a/platform/README.md +++ b/platform/README.md @@ -43,3 +43,5 @@ service, serves files over HTTP, and issues file tokens whose holder is an `auth | [`tasks/extensions/authz`](tasks/extensions/authz/README.md) | A task extension that decides whether the caller may run a command on a task at its current state | | [`tasks/extensions/notify`](tasks/extensions/notify/README.md) | A task extension that sends an email or SMS when a workflow step completes | | `tasks/systemcaller` | Completes task steps as the system principal, for code in the service itself | +| `workflowadmin` | The admin view of a deployment's workflows: a workflow's engine state, and resolving or force-parking a step | +| `agency` | An officer's view of the cases their organizational unit owns, and of the tasks on them their roles can read | diff --git a/platform/agency/artifacts_test.go b/platform/agency/artifacts_test.go new file mode 100644 index 0000000..0c06c3f --- /dev/null +++ b/platform/agency/artifacts_test.go @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (c) 2026 Lanka Software Foundation + +package agency + +import ( + "context" + "encoding/json" + "testing" + + "github.com/OpenNSW/core/artifact" + "github.com/OpenNSW/core/artifact/testutil" +) + +// newSet builds an artifact set from files: manifests[i] lists the rows of manifest +// version i+1, and the last one is current. +func newSet(t *testing.T, files map[string]string, manifests ...[]artifact.ManifestRow) *artifact.Set { + t.Helper() + m := testutil.MemLoader{} + for path, body := range files { + m[path] = []byte(body) + } + for i, rows := range manifests { + raw, err := json.Marshal(artifact.ManifestConfig{Artifacts: rows}) + if err != nil { + t.Fatal(err) + } + m[artifact.ManifestPath(i+1)] = raw + } + set, err := artifact.LoadSet(context.Background(), m) + if err != nil { + t.Fatal(err) + } + return set +} diff --git a/platform/agency/cases.go b/platform/agency/cases.go new file mode 100644 index 0000000..6b18852 --- /dev/null +++ b/platform/agency/cases.go @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (c) 2026 Lanka Software Foundation + +package agency + +import ( + "context" + "errors" + "log/slog" + "net/http" + "slices" + "time" + + "github.com/OpenNSW/core/artifact" + "github.com/OpenNSW/core/httputil" + "github.com/OpenNSW/core/pagination" + "github.com/OpenNSW/core/taskflow/store" + + "github.com/OpenNSW/core/platform/authn" + "github.com/OpenNSW/core/platform/tasks" +) + +const ( + errUnauthorized = "unauthorized" + errForbiddenRole = "catalog role required" + errCaseNotFound = "case not found" + errInvalidPaging = "invalid pagination parameters" +) + +// TaskLister is the narrow surface CaseHandler needs from the task store: the tasks of a +// case whose task templates list, in read.roles, one of the catalog roles the officer +// holds. core's task store satisfies it. The roles must never be empty, or GetTasks would +// list every task of the case: requireCatalogRole admits no officer without one. +type TaskLister interface { + // A non-nil error means the tasks could not be read, not that there are none. + GetTasks(ctx context.Context, filter store.TaskFilter) ([]store.TaskRecord, error) +} + +// CaseHandler serves the officer-facing case list and detail. Responses use the JSON +// field names of the applicant-facing case list and detail, so a client that renders those +// renders an agency case without changes. +type CaseHandler struct { + repo CaseRepository + tasks TaskLister + artifacts *artifact.Set // resolves each task's render config for its title + tokenRoles map[string][]string // token role -> the catalog roles mapped to it +} + +// NewCaseHandler creates a CaseHandler. roles is the catalog's Roles map, from +// catalog role to token role: an officer holding the token role of any of its entries may +// use the case views, sees the cases their OU owns in those roles, and in each the tasks +// whose read.roles list one of them. +func NewCaseHandler(repo CaseRepository, tasks TaskLister, artifacts *artifact.Set, roles map[string]string) *CaseHandler { + tokenRoles := make(map[string][]string, len(roles)) + for role, tokenRole := range roles { + // An empty token role would match a caller whose roles hold an empty string. + if tokenRole != "" { + tokenRoles[tokenRole] = append(tokenRoles[tokenRole], role) + } + } + return &CaseHandler{repo: repo, tasks: tasks, artifacts: artifacts, tokenRoles: tokenRoles} +} + +// CaseSummary is one row of the page HandleListCases returns. +type CaseSummary struct { + ID string `json:"id"` + Name string `json:"name,omitempty"` + State string `json:"state"` + CreatedAt string `json:"createdAt"` + UpdatedAt string `json:"updatedAt"` +} + +// CaseDetail is the response of HandleGetCase. +type CaseDetail struct { + CaseSummary + WorkflowNodes []WorkflowNode `json:"workflowNodes"` +} + +// WorkflowNode is one task of any workflow in the case, in the applicant-facing case +// detail's workflowNodes shape. +type WorkflowNode struct { + // ID is the task's ID (one run of a TASK node), not the node's ID in the workflow definition. + ID string `json:"id"` + CreatedAt string `json:"createdAt"` + UpdatedAt string `json:"updatedAt"` + WorkflowNodeTemplate WorkflowNodeTemplate `json:"workflowNodeTemplate"` + State string `json:"state"` + DependsOn []string `json:"depends_on"` +} + +// WorkflowNodeTemplate carries a task's display name and type. +type WorkflowNodeTemplate struct { + Name string `json:"name"` + Description string `json:"description"` + Type string `json:"type"` +} + +// HandleListCases returns a page of the cases the officer's OU owns in a role +// their token holds (case_parties), as the task gate decides who may open their tasks. +func (h *CaseHandler) HandleListCases(w http.ResponseWriter, r *http.Request) { + owner, ok := h.requireCatalogRole(w, r) + if !ok { + return + } + offsetParam, limitParam, err := pagination.ParsePaginationParams(r) + if err != nil { + httputil.Error(w, r, http.StatusBadRequest, errInvalidPaging) + return + } + offset, limit := pagination.ResolvePaginationParams(offsetParam, limitParam) + + cases, total, err := h.repo.ListCases(r.Context(), owner, offset, limit) + if err != nil { + httputil.InternalServerError(w, r, "failed to list cases", err) + return + } + items := make([]CaseSummary, len(cases)) + for i, c := range cases { + items[i] = toSummary(c) + } + httputil.JSON(w, http.StatusOK, pagination.NewPageResult(items, total, offset, limit)) +} + +// HandleGetCase returns the case its {id} path value names, if the officer's OU owns it +// (otherwise 404, as for a case that does not exist), plus the tasks of every flow on it +// that the officer may read. A task is listed when its task template's read.roles name a +// catalog role the officer holds; one listing none is not. +func (h *CaseHandler) HandleGetCase(w http.ResponseWriter, r *http.Request) { + owner, ok := h.requireCatalogRole(w, r) + if !ok { + return + } + ctx := r.Context() + id := r.PathValue("id") + + c, err := h.repo.GetCase(ctx, owner, id) + if err != nil { + if errors.Is(err, ErrCaseNotFound) { + httputil.Error(w, r, http.StatusNotFound, errCaseNotFound) + return + } + httputil.InternalServerError(w, r, "failed to get case", err, "caseId", id) + return + } + // Every flow on the case files its tasks under the case ID. + records, err := h.tasks.GetTasks(ctx, store.TaskFilter{CaseID: id, Roles: owner.Roles}) + if err != nil { + httputil.InternalServerError(w, r, "failed to list case tasks", err, "caseId", id) + return + } + nodes := make([]WorkflowNode, 0) + for _, t := range records { + if t.TaskType == "SYSTEM" { + continue + } + nodes = append(nodes, toNode(t, tasks.Title(r.Context(), tasks.RenderConfigs(h.artifacts), t))) + } + httputil.JSON(w, http.StatusOK, CaseDetail{CaseSummary: toSummary(*c), WorkflowNodes: nodes}) +} + +// requireCatalogRole returns the caller as an Owner: their OU and the catalog roles their +// token holds, sorted. It writes the error response and returns false unless the caller +// is a user holding the token role of any catalog role. A machine client is authenticated +// but never an officer, so it gets 403 rather than 401. An officer's roles come from their +// token, so they hold them in every case. +func (h *CaseHandler) requireCatalogRole(w http.ResponseWriter, r *http.Request) (Owner, bool) { + p, ok := authn.FromContext(r.Context()) + if !ok { + httputil.Error(w, r, http.StatusUnauthorized, errUnauthorized) + return Owner{}, false + } + var roles []string + if p.Kind == authn.KindUser { + for _, tokenRole := range p.Roles { + roles = append(roles, h.tokenRoles[tokenRole]...) + } + } + if len(roles) == 0 { + slog.WarnContext(r.Context(), "agency: case access denied, no catalog role held") + httputil.Error(w, r, http.StatusForbidden, errForbiddenRole) + return Owner{}, false + } + slices.Sort(roles) + return Owner{OUHandle: p.OUHandle, Roles: slices.Compact(roles)}, true +} + +func toSummary(c Case) CaseSummary { + s := CaseSummary{ + ID: c.ID, + State: c.State, + CreatedAt: c.CreatedAt.Format(time.RFC3339), + UpdatedAt: c.UpdatedAt.Format(time.RFC3339), + } + if c.Name != nil { + s.Name = *c.Name + } + return s +} + +// toNode maps a task record to the node states a case's action list groups by: a +// task in none of the states listed below is IN_PROGRESS. The agency keeps its own +// mapping so it can label states for its officers. name is the node's title (see +// tasks.Title). +func toNode(t store.TaskRecord, name string) WorkflowNode { + state := "IN_PROGRESS" + switch t.State { + case "COMPLETED", "FAILED", "QUEUED_EXTERNALLY", store.StateCancelled, store.StateOnHold: + state = t.State + } + return WorkflowNode{ + ID: t.TaskID, + CreatedAt: t.CreatedAt.Format(time.RFC3339), + UpdatedAt: t.UpdatedAt.Format(time.RFC3339), + WorkflowNodeTemplate: WorkflowNodeTemplate{ + Name: name, + Type: t.TaskType, + }, + State: state, + DependsOn: []string{}, + } +} diff --git a/platform/agency/cases_test.go b/platform/agency/cases_test.go new file mode 100644 index 0000000..db60b6c --- /dev/null +++ b/platform/agency/cases_test.go @@ -0,0 +1,251 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (c) 2026 Lanka Software Foundation + +package agency + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "reflect" + "slices" + "testing" + "time" + + "github.com/OpenNSW/core/pagination" + "github.com/OpenNSW/core/taskflow/store" + + "github.com/OpenNSW/core/platform/authn" +) + +// fakeCaseRepo holds cases and, per case, the OU that owns it and in which roles. +type fakeCaseRepo struct { + cases map[string]Case + owners map[string]Owner // case id -> its owning OU and roles +} + +func (f fakeCaseRepo) owns(o Owner, id string) bool { + owner, ok := f.owners[id] + return ok && owner.OUHandle == o.OUHandle && slices.ContainsFunc(o.Roles, func(r string) bool { return slices.Contains(owner.Roles, r) }) +} + +func (f fakeCaseRepo) ListCases(_ context.Context, o Owner, _, _ int) ([]Case, int64, error) { + out := []Case{} + for id, c := range f.cases { + if f.owns(o, id) { + out = append(out, c) + } + } + return out, int64(len(out)), nil +} + +func (f fakeCaseRepo) GetCase(_ context.Context, o Owner, id string) (*Case, error) { + c, ok := f.cases[id] + if !ok || !f.owns(o, id) { + return nil, ErrCaseNotFound + } + return &c, nil +} + +// fakeTasks answers GetTasks the way core's store does, through TaskFilter.Matches, and +// records each filter it was asked with. +type fakeTasks struct { + tasks []store.TaskRecord + filters *[]store.TaskFilter + // err, when set, is a failed read. + err error +} + +func (f fakeTasks) GetTasks(_ context.Context, filter store.TaskFilter) ([]store.TaskRecord, error) { + if f.filters != nil { + *f.filters = append(*f.filters, filter) + } + if f.err != nil { + return nil, f.err + } + var out []store.TaskRecord + for _, t := range f.tasks { + if filter.Matches(t) { + out = append(out, t) + } + } + return out, nil +} + +// officer is a user of agency-a holding roles. +func officer(roles ...string) *authn.Principal { + return &authn.Principal{Kind: authn.KindUser, OUHandle: "agency-a", Roles: roles} +} + +// requestBy builds a request authenticated as p, or unauthenticated when p is nil. +func requestBy(p *authn.Principal, target string, id string) *http.Request { + r := httptest.NewRequest(http.MethodGet, target, nil) + if id != "" { + r.SetPathValue("id", id) + } + if p != nil { + r = r.WithContext(authn.ContextWithPrincipal(r.Context(), p)) + } + return r +} + +// newCaseFixture serves case C1, owned by agency-a's OU as officer, with tasks of several +// roles, and returns the filters its task store is asked with. +func newCaseFixture(t *testing.T) (*CaseHandler, *[]store.TaskFilter) { + t.Helper() + now := time.Now() + repo := fakeCaseRepo{ + cases: map[string]Case{"C1": {ID: "C1", State: "IN_PROGRESS", CreatedAt: now, UpdatedAt: now}}, + owners: map[string]Owner{"C1": {OUHandle: "agency-a", Roles: []string{"officer"}}}, + } + officerRole := []string{"officer"} + var filters []store.TaskFilter + // Every flow on a case files its tasks under the case ID. + tasks := fakeTasks{filters: &filters, tasks: []store.TaskRecord{ + {TaskID: "n1", CaseID: "C1", ReadRoles: officerRole, TaskType: "APPLICATION", State: "PENDING_USER", TaskTemplateID: "tpl-a"}, + {TaskID: "n2", CaseID: "C1", ReadRoles: officerRole, TaskType: "APPLICATION", State: "COMPLETED", TaskTemplateID: "tpl-b"}, + {TaskID: "n3", CaseID: "C1", ReadRoles: officerRole, TaskType: "SYSTEM", State: "COMPLETED"}, + {TaskID: "n4", CaseID: "C1", ReadRoles: []string{"reviewer"}, TaskType: "REVIEW", State: "PENDING_USER", TaskTemplateID: "tpl-r"}, + {TaskID: "n5", CaseID: "C1", TaskType: "APPLICATION", State: "PENDING_USER", TaskTemplateID: "tpl-none"}, + {TaskID: "other-case", CaseID: "C9", ReadRoles: officerRole, TaskType: "APPLICATION", State: "PENDING_USER"}, + }} + return NewCaseHandler(repo, tasks, newSet(t, nil, nil), map[string]string{"officer": "Officer", "reviewer": "Reviewer"}), &filters +} + +func TestCaseHandlerRequiresACatalogRole(t *testing.T) { + h, _ := newCaseFixture(t) + for name, tc := range map[string]struct { + p *authn.Principal + want int + }{ + "unauthenticated": {nil, http.StatusUnauthorized}, + "applicant": {officer("Applicant"), http.StatusForbidden}, + // Only a user can be an officer, whatever roles a client token carries. + "client": {&authn.Principal{Kind: authn.KindClient, ClientID: "service-client", Roles: []string{"Officer"}}, http.StatusForbidden}, + "officer": {officer("Officer"), http.StatusOK}, + "mixed roles": {officer("Applicant", "Officer"), http.StatusOK}, + } { + rec := httptest.NewRecorder() + h.HandleListCases(rec, requestBy(tc.p, "/api/v1/cases", "")) + if rec.Code != tc.want { + t.Errorf("list as %s: status = %d, want %d", name, rec.Code, tc.want) + } + rec = httptest.NewRecorder() + h.HandleGetCase(rec, requestBy(tc.p, "/api/v1/cases/C1", "C1")) + if rec.Code != tc.want { + t.Errorf("detail as %s: status = %d, want %d", name, rec.Code, tc.want) + } + } +} + +// A case is shown only to an OU that owns it, in a role the caller's token holds. +func TestCaseHandlerShowsOnlyTheCallersCases(t *testing.T) { + h, _ := newCaseFixture(t) + for name, p := range map[string]*authn.Principal{ + "another role": officer("Reviewer"), + "another OU": {Kind: authn.KindUser, OUHandle: "agency-b", Roles: []string{"Officer"}}, + } { + rec := httptest.NewRecorder() + h.HandleListCases(rec, requestBy(p, "/api/v1/cases", "")) + var page pagination.Page[CaseSummary] + if err := json.Unmarshal(rec.Body.Bytes(), &page); err != nil || rec.Code != http.StatusOK || len(page.Items) != 0 { + t.Errorf("list as %s: status = %d, body %s, want no cases", name, rec.Code, rec.Body) + } + rec = httptest.NewRecorder() + h.HandleGetCase(rec, requestBy(p, "/api/v1/cases/C1", "C1")) + if rec.Code != http.StatusNotFound { + t.Errorf("detail as %s: status = %d, want 404", name, rec.Code) + } + } +} + +// The detail lists the case's tasks the officer may read: those whose read.roles name a +// catalog role they hold, asking the store once for the case with those catalog roles. +func TestCaseHandlerDetailListsTheReadableTasks(t *testing.T) { + h, filters := newCaseFixture(t) + + rec := httptest.NewRecorder() + h.HandleGetCase(rec, requestBy(officer("Reviewer", "Applicant", "Officer"), "/api/v1/cases/C1", "C1")) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", rec.Code, rec.Body) + } + var got CaseDetail + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + // n3 is SYSTEM, n5 lists no read roles, and other-case is another case's. + var ids []string + for _, n := range got.WorkflowNodes { + ids = append(ids, n.ID) + } + if !slices.Equal(ids, []string{"n1", "n2", "n4"}) { + t.Errorf("nodes = %v, want n1, n2 and n4", ids) + } + // No render config resolves, so each falls back to its template id. + if n1 := got.WorkflowNodes[0]; n1.State != "IN_PROGRESS" || n1.WorkflowNodeTemplate.Name != "tpl-a" { + t.Errorf("n1 = %+v", n1) + } + // The catalog roles, not the token roles; a token role outside the catalog adds none. + want := []store.TaskFilter{{CaseID: "C1", Roles: []string{"officer", "reviewer"}}} + if !reflect.DeepEqual(*filters, want) { + t.Errorf("filters = %+v, want %+v", *filters, want) + } +} + +// Tasks that could not be read are a server error, not a case with no tasks. +func TestCaseHandlerDetailFailsWhenTheTasksCannotBeRead(t *testing.T) { + h, _ := newCaseFixture(t) + h.tasks = fakeTasks{err: errors.New("db down")} + + rec := httptest.NewRecorder() + h.HandleGetCase(rec, requestBy(officer("Officer"), "/api/v1/cases/C1", "C1")) + if rec.Code != http.StatusInternalServerError { + t.Fatalf("status = %d, want 500", rec.Code) + } +} + +func TestCaseHandlerUnknownCase(t *testing.T) { + h, _ := newCaseFixture(t) + rec := httptest.NewRecorder() + h.HandleGetCase(rec, requestBy(officer("Officer"), "/api/v1/cases/nope", "nope")) + if rec.Code != http.StatusNotFound { + t.Fatalf("status = %d, want 404", rec.Code) + } +} + +// Catalog roles sharing a token role are all held by an officer holding it, so a case +// owned in either is theirs. +func TestCaseHandlerSharedTokenRole(t *testing.T) { + var filters []store.TaskFilter + repo := fakeCaseRepo{ + cases: map[string]Case{"C1": {ID: "C1"}}, + owners: map[string]Owner{"C1": {OUHandle: "agency-a", Roles: []string{"accountant"}}}, + } + h := NewCaseHandler(repo, fakeTasks{filters: &filters}, newSet(t, nil, nil), + map[string]string{"accountant": "Agency Officer", "officer": "Agency Officer"}) + + rec := httptest.NewRecorder() + h.HandleGetCase(rec, requestBy(officer("Agency Officer", "Agency Officer"), "/api/v1/cases/C1", "C1")) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", rec.Code, rec.Body) + } + want := []store.TaskFilter{{CaseID: "C1", Roles: []string{"accountant", "officer"}}} + if !reflect.DeepEqual(filters, want) { + t.Errorf("filters = %+v, want %+v", filters, want) + } +} + +// A catalog entry mapped to "" must not match a caller whose roles hold an empty string. +func TestCaseHandlerEmptyTokenRole(t *testing.T) { + h := NewCaseHandler(fakeCaseRepo{}, fakeTasks{}, newSet(t, nil, nil), map[string]string{"reviewer": ""}) + for _, roles := range [][]string{{""}, {"Reviewer"}, nil} { + rec := httptest.NewRecorder() + h.HandleListCases(rec, requestBy(officer(roles...), "/api/v1/cases", "")) + if rec.Code != http.StatusForbidden { + t.Errorf("roles %q: status = %d, want 403", roles, rec.Code) + } + } +} diff --git a/platform/agency/repository.go b/platform/agency/repository.go new file mode 100644 index 0000000..6a2e728 --- /dev/null +++ b/platform/agency/repository.go @@ -0,0 +1,123 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (c) 2026 Lanka Software Foundation + +package agency + +import ( + "context" + "database/sql" + "errors" + "fmt" + "strings" + "time" +) + +// ErrCaseNotFound is returned when no cases row exists for an id, or the caller owns none. +var ErrCaseNotFound = errors.New("case not found") + +// Case is one row of the generic cases table. +type Case struct { + ID string + Name *string + State string + CreatedAt time.Time + UpdatedAt time.Time +} + +// Owner is who reads a case: an OU, by its handle, in any of a set of catalog roles. A +// case is theirs when case_parties records the OU in one of the roles on it. +type Owner struct { + OUHandle string + Roles []string +} + +// CaseRepository reads the cases an owner owns. +type CaseRepository interface { + // ListCases returns one page of the cases owner owns, newest first, and their total. + ListCases(ctx context.Context, owner Owner, offset, limit int) ([]Case, int64, error) + // GetCase returns case id if owner owns it, else ErrCaseNotFound. + GetCase(ctx context.Context, owner Owner, id string) (*Case, error) +} + +type repository struct { + db *sql.DB +} + +// NewCaseRepository creates a CaseRepository on the app's shared *sql.DB. +func NewCaseRepository(db *sql.DB) CaseRepository { + return &repository{db: db} +} + +// owned returns the condition that the case in cases is owner's, and its arguments: the +// OU handle, then each role, in placeholders numbered from first. Its text holds only +// placeholders, so a query may join it in; every value is bound. +func owned(first int, owner Owner) (string, []any) { + args := make([]any, 0, 1+len(owner.Roles)) + args = append(args, owner.OUHandle) + roles := make([]string, len(owner.Roles)) + for i, role := range owner.Roles { + roles[i] = fmt.Sprintf("$%d", first+1+i) + args = append(args, role) + } + return fmt.Sprintf(`EXISTS ( + SELECT 1 FROM case_parties + WHERE case_parties.case_id = cases.id AND case_parties.party_type = 'ou' + AND case_parties.party_id = $%d AND case_parties.role IN (%s) +)`, first, strings.Join(roles, ",")), args +} + +func (r *repository) ListCases(ctx context.Context, owner Owner, offset, limit int) ([]Case, int64, error) { + if owner.OUHandle == "" || len(owner.Roles) == 0 { + return []Case{}, 0, nil + } + cond, args := owned(1, owner) + var total int64 + countQuery := `SELECT count(*) FROM cases WHERE ` + cond // #nosec G202 -- owned's text holds only numbered placeholders; every value is bound. + if err := r.db.QueryRowContext(ctx, countQuery, args...).Scan(&total); err != nil { + return nil, 0, err + } + page := fmt.Sprintf("OFFSET $%d LIMIT $%d", len(args)+1, len(args)+2) + // #nosec G202 -- owned's and page's texts hold only numbered placeholders; every value is bound. + q := ` + SELECT id, name, state, created_at, updated_at + FROM cases + WHERE ` + cond + ` + ORDER BY created_at DESC + ` + page + ` + ` + rows, err := r.db.QueryContext(ctx, q, append(args, offset, limit)...) + if err != nil { + return nil, 0, err + } + defer func() { _ = rows.Close() }() + cases := []Case{} + for rows.Next() { + var c Case + if err := rows.Scan(&c.ID, &c.Name, &c.State, &c.CreatedAt, &c.UpdatedAt); err != nil { + return nil, 0, err + } + cases = append(cases, c) + } + if err := rows.Err(); err != nil { + return nil, 0, err + } + return cases, total, nil +} + +func (r *repository) GetCase(ctx context.Context, owner Owner, id string) (*Case, error) { + if owner.OUHandle == "" || len(owner.Roles) == 0 { + return nil, ErrCaseNotFound + } + cond, args := owned(2, owner) + q := `SELECT id, name, state, created_at, updated_at FROM cases WHERE id = $1 AND ` + cond // #nosec G202 -- owned's text holds only numbered placeholders; every value is bound. + var c Case + err := r.db.QueryRowContext(ctx, q, append([]any{id}, args...)...). + Scan(&c.ID, &c.Name, &c.State, &c.CreatedAt, &c.UpdatedAt) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrCaseNotFound + } + if err != nil { + return nil, err + } + return &c, nil +} diff --git a/platform/agency/repository_test.go b/platform/agency/repository_test.go new file mode 100644 index 0000000..7144664 --- /dev/null +++ b/platform/agency/repository_test.go @@ -0,0 +1,185 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (c) 2026 Lanka Software Foundation + +package agency + +import ( + "context" + "database/sql" + "errors" + "regexp" + "testing" + "time" + + "github.com/DATA-DOG/go-sqlmock" +) + +func newMockRepo(t *testing.T) (CaseRepository, sqlmock.Sqlmock) { + t.Helper() + db, mock, err := sqlmock.New() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Close() }) + return NewCaseRepository(db), mock +} + +var officers = Owner{OUHandle: "agency-a", Roles: []string{"officer"}} + +// ownedFrom2 is owned's text for one role, numbered from $2. +const ownedFrom2 = `EXISTS ( + SELECT 1 FROM case_parties + WHERE case_parties.case_id = cases.id AND case_parties.party_type = 'ou' + AND case_parties.party_id = $2 AND case_parties.role IN ($3) +)` + +var caseColumns = []string{"id", "name", "state", "created_at", "updated_at"} + +func TestListCasesIsTheOwners(t *testing.T) { + repo, mock := newMockRepo(t) + created := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + name := "Tea" + mock.ExpectQuery(regexp.QuoteMeta(`SELECT count(*) FROM cases WHERE EXISTS ( + SELECT 1 FROM case_parties + WHERE case_parties.case_id = cases.id AND case_parties.party_type = 'ou' + AND case_parties.party_id = $1 AND case_parties.role IN ($2) +)`)). + WithArgs("agency-a", "officer"). + WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(2)) + mock.ExpectQuery(`SELECT id, name, state, created_at, updated_at\s+FROM cases\s+WHERE EXISTS .*`+ + regexp.QuoteMeta(`party_id = $1 AND case_parties.role IN ($2)`)+ + `.*ORDER BY created_at DESC\s+`+regexp.QuoteMeta(`OFFSET $3 LIMIT $4`)). + WithArgs("agency-a", "officer", 0, 20). + WillReturnRows(sqlmock.NewRows(caseColumns). + AddRow("C2", name, "IN_PROGRESS", created, created). + AddRow("C1", nil, "FINISHED", created, created)) + + cases, total, err := repo.ListCases(context.Background(), officers, 0, 20) + if err != nil || total != 2 || len(cases) != 2 { + t.Fatalf("cases = %+v, total = %d, err = %v", cases, total, err) + } + if cases[0].ID != "C2" || cases[0].Name == nil || *cases[0].Name != name || !cases[0].CreatedAt.Equal(created) { + t.Errorf("cases[0] = %+v", cases[0]) + } + if cases[1].ID != "C1" || cases[1].Name != nil || cases[1].State != "FINISHED" { + t.Errorf("cases[1] = %+v", cases[1]) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatal(err) + } +} + +// Each of the owner's roles is its own placeholder, numbered after the OU handle. +func TestListCasesInAnyRole(t *testing.T) { + repo, mock := newMockRepo(t) + owner := Owner{OUHandle: "agency-a", Roles: []string{"officer", "reviewer"}} + mock.ExpectQuery(regexp.QuoteMeta(`party_id = $1 AND case_parties.role IN ($2,$3)`)). + WithArgs("agency-a", "officer", "reviewer"). + WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(0)) + mock.ExpectQuery(regexp.QuoteMeta(`party_id = $1 AND case_parties.role IN ($2,$3)`)+`.*`+regexp.QuoteMeta(`OFFSET $4 LIMIT $5`)). + WithArgs("agency-a", "officer", "reviewer", 40, 20). + WillReturnRows(sqlmock.NewRows(caseColumns)) + + cases, total, err := repo.ListCases(context.Background(), owner, 40, 20) + if err != nil || total != 0 { + t.Fatalf("total = %d, err = %v", total, err) + } + if cases == nil || len(cases) != 0 { + t.Errorf("cases = %#v, want an empty slice", cases) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatal(err) + } +} + +func TestListCasesPropagatesFailures(t *testing.T) { + boom := errors.New("connection refused") + + t.Run("count", func(t *testing.T) { + repo, mock := newMockRepo(t) + mock.ExpectQuery(`SELECT count\(\*\) FROM cases`).WillReturnError(boom) + if _, _, err := repo.ListCases(context.Background(), officers, 0, 20); !errors.Is(err, boom) { + t.Errorf("err = %v, want the underlying error", err) + } + }) + t.Run("page", func(t *testing.T) { + repo, mock := newMockRepo(t) + mock.ExpectQuery(`SELECT count\(\*\) FROM cases`).WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(1)) + mock.ExpectQuery(`SELECT id, name`).WillReturnError(boom) + if _, _, err := repo.ListCases(context.Background(), officers, 0, 20); !errors.Is(err, boom) { + t.Errorf("err = %v, want the underlying error", err) + } + }) + t.Run("row", func(t *testing.T) { + repo, mock := newMockRepo(t) + mock.ExpectQuery(`SELECT count\(\*\) FROM cases`).WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(1)) + mock.ExpectQuery(`SELECT id, name`).WillReturnRows(sqlmock.NewRows(caseColumns). + AddRow("C1", nil, "IN_PROGRESS", time.Now(), time.Now()).RowError(0, boom)) + if _, _, err := repo.ListCases(context.Background(), officers, 0, 20); !errors.Is(err, boom) { + t.Errorf("err = %v, want the underlying error", err) + } + }) +} + +// An owner with no OU or no role owns nothing, without a query. +func TestCasesOfNoOwner(t *testing.T) { + repo, mock := newMockRepo(t) + for _, o := range []Owner{{Roles: []string{"officer"}}, {OUHandle: "agency-a"}} { + if cases, total, err := repo.ListCases(context.Background(), o, 0, 20); err != nil || total != 0 || cases == nil || len(cases) != 0 { + t.Errorf("%+v: cases = %v, total = %d, err = %v", o, cases, total, err) + } + if _, err := repo.GetCase(context.Background(), o, "C1"); !errors.Is(err, ErrCaseNotFound) { + t.Errorf("%+v: err = %v, want ErrCaseNotFound", o, err) + } + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatal(err) + } +} + +func TestGetCase(t *testing.T) { + repo, mock := newMockRepo(t) + created := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + updated := created.Add(time.Hour) + mock.ExpectQuery(regexp.QuoteMeta(`SELECT id, name, state, created_at, updated_at FROM cases WHERE id = $1 AND `+ownedFrom2)). + WithArgs("C1", "agency-a", "officer"). + WillReturnRows(sqlmock.NewRows(caseColumns).AddRow("C1", "Tea", "IN_PROGRESS", created, updated)) + + c, err := repo.GetCase(context.Background(), officers, "C1") + if err != nil { + t.Fatal(err) + } + if c.ID != "C1" || c.Name == nil || *c.Name != "Tea" || c.State != "IN_PROGRESS" || + !c.CreatedAt.Equal(created) || !c.UpdatedAt.Equal(updated) { + t.Errorf("case = %+v", c) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatal(err) + } +} + +// A case that does not exist, or that the owner does not own, is not found. +func TestGetCaseNotOwned(t *testing.T) { + repo, mock := newMockRepo(t) + mock.ExpectQuery(regexp.QuoteMeta(`FROM cases WHERE id = $1 AND EXISTS`)). + WithArgs("C1", "agency-a", "officer"). + WillReturnRows(sqlmock.NewRows(caseColumns)) + + if _, err := repo.GetCase(context.Background(), officers, "C1"); !errors.Is(err, ErrCaseNotFound) { + t.Fatalf("err = %v, want ErrCaseNotFound", err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatal(err) + } +} + +// A database failure is a failure, not a missing case. +func TestGetCasePropagatesFailures(t *testing.T) { + repo, mock := newMockRepo(t) + mock.ExpectQuery(`FROM cases WHERE id`).WillReturnError(sql.ErrConnDone) + + _, err := repo.GetCase(context.Background(), officers, "C1") + if !errors.Is(err, sql.ErrConnDone) || errors.Is(err, ErrCaseNotFound) { + t.Fatalf("err = %v, want the underlying error", err) + } +} diff --git a/platform/go.mod b/platform/go.mod index fb136d2..c22063d 100644 --- a/platform/go.mod +++ b/platform/go.mod @@ -11,6 +11,7 @@ require ( github.com/OpenNSW/core/httputil v0.3.0 github.com/OpenNSW/core/json v0.0.0-20260917101529-36df0ddf30e0 github.com/OpenNSW/core/notification v0.3.0 + github.com/OpenNSW/core/pagination v0.1.0 github.com/OpenNSW/core/payment v0.5.0 github.com/OpenNSW/core/refid v0.5.0 github.com/OpenNSW/core/remote v0.9.0 diff --git a/platform/go.sum b/platform/go.sum index db26c26..48b2acf 100644 --- a/platform/go.sum +++ b/platform/go.sum @@ -14,6 +14,8 @@ github.com/OpenNSW/core/json v0.0.0-20260917101529-36df0ddf30e0 h1:XP4TYN7gX9Mth github.com/OpenNSW/core/json v0.0.0-20260917101529-36df0ddf30e0/go.mod h1:9jLuqV3Fq7+hGycs9CTiG4v65Ngi6k4mkMkscSFL1Og= github.com/OpenNSW/core/notification v0.3.0 h1:8Sl5ig9IFUfnewkzO+6bWI6iCgbJF28aGQJZEI425Fs= github.com/OpenNSW/core/notification v0.3.0/go.mod h1:EFAFS7uwe2BwW1n2G2sFjvZNAZG4T6B1NOQk2Mpi1xo= +github.com/OpenNSW/core/pagination v0.1.0 h1:xLpgHAdgYxzJkXXBtQoTMxMxsjZZ9RNYvJOoQC0oddA= +github.com/OpenNSW/core/pagination v0.1.0/go.mod h1:UdpPJO/wMu2mv1nCJ1G1X0WEvFso8hh9OpDz2meA/Ts= github.com/OpenNSW/core/payment v0.5.0 h1:Xt5qPsEMNXQuyzcL/lR+QVkKmLvyJyHy/x+nMpLYDaU= github.com/OpenNSW/core/payment v0.5.0/go.mod h1:pg2hsryKmPVkiN42MWHEpwaPIuVGG5M32QUegd1AE+g= github.com/OpenNSW/core/refid v0.5.0 h1:dEOimyV5tHrlmF+9RFMwH/MwPd9aKT0AkDm3JUc07mo= diff --git a/platform/workflowadmin/case_service.go b/platform/workflowadmin/case_service.go new file mode 100644 index 0000000..2f2d810 --- /dev/null +++ b/platform/workflowadmin/case_service.go @@ -0,0 +1,148 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (c) 2026 Lanka Software Foundation + +package workflowadmin + +import ( + "context" + "database/sql" + "errors" + "fmt" + "time" + + "github.com/OpenNSW/core/artifact" + "github.com/OpenNSW/core/taskflow/store" + + "github.com/OpenNSW/core/platform/caseflow" + "github.com/OpenNSW/core/platform/tasks" +) + +// ErrCaseNotFound is returned when no cases row exists for an id. +var ErrCaseNotFound = errors.New("case not found") + +// FlowLister lists a case's flows, oldest first. *caseflow.Service satisfies it. +type FlowLister interface { + Flows(ctx context.Context, caseID string) ([]caseflow.Flow, error) +} + +// CaseRow is the case itself, in the admin's view of it. +type CaseRow struct { + ID string `json:"id"` + Name string `json:"name,omitempty"` + State string `json:"state"` + CreatedAt string `json:"createdAt"` + UpdatedAt string `json:"updatedAt"` +} + +// CaseNodeTemplate carries a task's display name and type, in the shape the applicant- +// and officer-facing case views use. +type CaseNodeTemplate struct { + Name string `json:"name"` + Type string `json:"type"` +} + +// CaseNode is one task of any flow on a case, for the admin view: the task store's own +// state, not the label a service's own case view gives it (see agency.toNode), since this +// is a diagnostic view, not the applicant's or officer's own. +type CaseNode struct { + ID string `json:"id"` + CreatedAt string `json:"createdAt"` + UpdatedAt string `json:"updatedAt"` + WorkflowNodeTemplate CaseNodeTemplate `json:"workflowNodeTemplate"` + State string `json:"state"` +} + +// CaseDetail is the response of Handler.HandleGetCase: any case, whichever service +// opened it, since every case shares the one ID space — every task on it +// whatever its read roles, and its flows by workflow ID, which an admin opens with +// Handler.HandleGetWorkflowEngineStatus. +type CaseDetail struct { + CaseRow + WorkflowNodes []CaseNode `json:"workflowNodes"` + Flows []caseflow.View `json:"flows"` +} + +// CaseService builds the admin's view of a case: the `cases` row, task store, and +// caseflow that every case runs on, whichever service opened it. A service that keeps its +// own record of a case gives that record the case's ID, so one ID addresses both. What a +// service shows on its own case view, and the ownership check it makes there, stays with +// that service; this is the part every admin view of a case needs identically, so there is +// only one of it. +type CaseService struct { + db *sql.DB + taskStore TaskStore + flows FlowLister + artifacts *artifact.Set +} + +// NewCaseService creates a CaseService on the app's shared *sql.DB. +func NewCaseService(db *sql.DB, taskStore TaskStore, flows FlowLister, artifacts *artifact.Set) *CaseService { + return &CaseService{db: db, taskStore: taskStore, flows: flows, artifacts: artifacts} +} + +// GetCaseDetail returns id's case, with no ownership check: any caller holding the admin +// scope may fetch any case, whichever service opened it. +func (s *CaseService) GetCaseDetail(ctx context.Context, id string) (*CaseDetail, error) { + row, err := s.getCaseRow(ctx, id) + if err != nil { + return nil, err + } + + rawTasks, err := s.taskStore.GetTasks(ctx, store.TaskFilter{CaseID: id}) + if err != nil { + return nil, fmt.Errorf("list tasks of case %s: %w", id, err) + } + nodes := make([]CaseNode, 0, len(rawTasks)) + for _, t := range rawTasks { + if t.TaskType == "SYSTEM" { + continue + } + nodes = append(nodes, CaseNode{ + ID: t.TaskID, + CreatedAt: t.CreatedAt.Format(time.RFC3339), + UpdatedAt: t.UpdatedAt.Format(time.RFC3339), + WorkflowNodeTemplate: CaseNodeTemplate{ + Name: tasks.Title(ctx, tasks.RenderConfigs(s.artifacts), t), + Type: t.TaskType, + }, + State: t.State, + }) + } + + flows, err := s.flows.Flows(ctx, id) + if err != nil { + return nil, err + } + views := make([]caseflow.View, 0, len(flows)) + for _, f := range flows { + views = append(views, caseflow.ViewOf(ctx, s.artifacts, f)) + } + + return &CaseDetail{CaseRow: row, WorkflowNodes: nodes, Flows: views}, nil +} + +func (s *CaseService) getCaseRow(ctx context.Context, id string) (CaseRow, error) { + var r struct { + ID string + Name sql.NullString + State string + CreatedAt time.Time + UpdatedAt time.Time + } + err := s.db.QueryRowContext(ctx, + `SELECT id, name, state, created_at, updated_at FROM cases WHERE id = $1`, id, + ).Scan(&r.ID, &r.Name, &r.State, &r.CreatedAt, &r.UpdatedAt) + if errors.Is(err, sql.ErrNoRows) { + return CaseRow{}, ErrCaseNotFound + } + if err != nil { + return CaseRow{}, err + } + return CaseRow{ + ID: r.ID, + Name: r.Name.String, + State: r.State, + CreatedAt: r.CreatedAt.Format(time.RFC3339), + UpdatedAt: r.UpdatedAt.Format(time.RFC3339), + }, nil +} diff --git a/platform/workflowadmin/case_service_test.go b/platform/workflowadmin/case_service_test.go new file mode 100644 index 0000000..9b56e3f --- /dev/null +++ b/platform/workflowadmin/case_service_test.go @@ -0,0 +1,264 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (c) 2026 Lanka Software Foundation + +package workflowadmin + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "reflect" + "regexp" + "testing" + "time" + + "github.com/DATA-DOG/go-sqlmock" + "github.com/OpenNSW/core/artifact" + "github.com/OpenNSW/core/artifact/testutil" + "github.com/OpenNSW/core/taskflow/store" + "github.com/stretchr/testify/mock" + + "github.com/OpenNSW/core/platform/audit" + "github.com/OpenNSW/core/platform/authn" + "github.com/OpenNSW/core/platform/caseflow" +) + +func newMockDB(t *testing.T) (*sql.DB, sqlmock.Sqlmock) { + t.Helper() + db, mock, err := sqlmock.New() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Close() }) + return db, mock +} + +func emptyArtifactSet(t *testing.T) *artifact.Set { + t.Helper() + // An empty, but present, manifest: render config and workflow definition lookups fall + // back to the task template id / template id, which is all these tests need. + set, err := artifact.LoadSet(context.Background(), testutil.MemLoader{ + "manifest_v1.json": []byte(`{"artifacts":[]}`), + }) + if err != nil { + t.Fatal(err) + } + return set +} + +// fakeFlows lists each case's flows, or fails with err. +type fakeFlows struct { + flows map[string][]caseflow.Flow + err error +} + +func (f fakeFlows) Flows(_ context.Context, caseID string) ([]caseflow.Flow, error) { + return f.flows[caseID], f.err +} + +const caseRowColumns = "id, name, state, created_at, updated_at" + +func caseRowQuery() string { + return `^` + regexp.QuoteMeta(`SELECT `+caseRowColumns+` FROM cases WHERE id = $1`) + `$` +} + +// A case addresses whoever's id it is, whatever kind of case it is — +// every task on it whatever its read roles, and its flows. +func TestCaseService_GetCaseDetail(t *testing.T) { + db, sqlMock := newMockDB(t) + now := time.Date(2026, 11, 3, 9, 0, 0, 0, time.UTC) + sqlMock.ExpectQuery(caseRowQuery()). + WithArgs("C1"). + WillReturnRows(sqlmock.NewRows([]string{"id", "name", "state", "created_at", "updated_at"}). + AddRow("C1", "Shipment 1", "IN_PROGRESS", now, now)) + + taskStore := &MockTaskStore{} + tasks := []store.TaskRecord{ + {TaskID: "n1", CaseID: "C1", ReadRoles: []string{"officer"}, TaskType: "APPLICATION", State: "PENDING_USER", TaskTemplateID: "tpl-a", CreatedAt: now, UpdatedAt: now}, + {TaskID: "n2", CaseID: "C1", TaskType: "SYSTEM", State: "COMPLETED", CreatedAt: now, UpdatedAt: now}, + } + // GetTasks is asked with only a CaseID: every task of the case is listed whatever its + // read roles, since this is an admin view. + taskStore.On("GetTasks", context.Background(), store.TaskFilter{CaseID: "C1"}).Return(tasks) + + flows := fakeFlows{flows: map[string][]caseflow.Flow{"C1": { + {WorkflowID: "wf-1", CaseID: "C1", TemplateID: "trade-export", Status: caseflow.StatusStarted, CreatedAt: now, UpdatedAt: now}, + }}} + svc := NewCaseService(db, taskStore, flows, emptyArtifactSet(t)) + + detail, err := svc.GetCaseDetail(context.Background(), "C1") + if err != nil { + t.Fatalf("err = %v, want nil", err) + } + if detail.CaseRow != (CaseRow{ID: "C1", Name: "Shipment 1", State: "IN_PROGRESS", CreatedAt: now.Format(time.RFC3339), UpdatedAt: now.Format(time.RFC3339)}) { + t.Errorf("case = %+v", detail.CaseRow) + } + // SYSTEM filtered out; the remaining task is listed whatever its read roles. + if len(detail.WorkflowNodes) != 1 || detail.WorkflowNodes[0].ID != "n1" { + t.Errorf("nodes = %+v, want just n1", detail.WorkflowNodes) + } + if detail.WorkflowNodes[0].WorkflowNodeTemplate.Name != "tpl-a" { + t.Errorf("node name = %q, want the template id fallback", detail.WorkflowNodes[0].WorkflowNodeTemplate.Name) + } + want := []caseflow.View{{WorkflowID: "wf-1", TemplateID: "trade-export", TemplateName: "trade-export", + Status: "STARTED", CreatedAt: now.Format(time.RFC3339), UpdatedAt: now.Format(time.RFC3339)}} + if !reflect.DeepEqual(detail.Flows, want) { + t.Errorf("flows = %+v, want %+v", detail.Flows, want) + } +} + +func TestCaseService_GetCaseDetail_NotFound(t *testing.T) { + db, sqlMock := newMockDB(t) + sqlMock.ExpectQuery(caseRowQuery()). + WithArgs("nope"). + WillReturnRows(sqlmock.NewRows([]string{"id", "name", "state", "created_at", "updated_at"})) + + svc := NewCaseService(db, &MockTaskStore{}, fakeFlows{}, emptyArtifactSet(t)) + if _, err := svc.GetCaseDetail(context.Background(), "nope"); !errors.Is(err, ErrCaseNotFound) { + t.Errorf("err = %v, want ErrCaseNotFound", err) + } + if err := sqlMock.ExpectationsWereMet(); err != nil { + t.Fatal(err) + } +} + +// A database failure reading the case is a failure, not a missing case. +func TestCaseService_GetCaseDetail_DBError(t *testing.T) { + db, sqlMock := newMockDB(t) + sqlMock.ExpectQuery(caseRowQuery()).WithArgs("C1").WillReturnError(sql.ErrConnDone) + + svc := NewCaseService(db, &MockTaskStore{}, fakeFlows{}, emptyArtifactSet(t)) + _, err := svc.GetCaseDetail(context.Background(), "C1") + if !errors.Is(err, sql.ErrConnDone) || errors.Is(err, ErrCaseNotFound) { + t.Errorf("err = %v, want the underlying error", err) + } +} + +// A case with no name has an empty Name. +func TestCaseService_GetCaseDetail_NoName(t *testing.T) { + db, sqlMock := newMockDB(t) + created := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + sqlMock.ExpectQuery(caseRowQuery()).WithArgs("C1"). + WillReturnRows(sqlmock.NewRows([]string{"id", "name", "state", "created_at", "updated_at"}). + AddRow("C1", nil, "IN_PROGRESS", created, created.Add(time.Hour))) + taskStore := &MockTaskStore{} + taskStore.On("GetTasks", mock.Anything, store.TaskFilter{CaseID: "C1"}).Return([]store.TaskRecord{}, nil) + + svc := NewCaseService(db, taskStore, fakeFlows{}, emptyArtifactSet(t)) + got, err := svc.GetCaseDetail(context.Background(), "C1") + if err != nil { + t.Fatal(err) + } + want := CaseRow{ID: "C1", State: "IN_PROGRESS", CreatedAt: "2026-01-02T03:04:05Z", UpdatedAt: "2026-01-02T04:04:05Z"} + if got.CaseRow != want { + t.Errorf("row = %+v, want %+v", got.CaseRow, want) + } +} + +func TestCaseService_GetCaseDetail_FlowsError(t *testing.T) { + db, sqlMock := newMockDB(t) + now := time.Now() + sqlMock.ExpectQuery(caseRowQuery()). + WithArgs("C1"). + WillReturnRows(sqlmock.NewRows([]string{"id", "name", "state", "created_at", "updated_at"}). + AddRow("C1", nil, "IN_PROGRESS", now, now)) + + taskStore := &MockTaskStore{} + taskStore.On("GetTasks", context.Background(), store.TaskFilter{CaseID: "C1"}).Return([]store.TaskRecord(nil)) + svc := NewCaseService(db, taskStore, fakeFlows{err: errors.New("db down")}, emptyArtifactSet(t)) + + if _, err := svc.GetCaseDetail(context.Background(), "C1"); err == nil { + t.Error("err = nil, want the flows error") + } +} + +// Tasks that could not be read fail the detail rather than show a case with none. +func TestCaseService_GetCaseDetail_TasksError(t *testing.T) { + db, sqlMock := newMockDB(t) + now := time.Now() + sqlMock.ExpectQuery(caseRowQuery()). + WithArgs("C1"). + WillReturnRows(sqlmock.NewRows([]string{"id", "name", "state", "created_at", "updated_at"}). + AddRow("C1", nil, "IN_PROGRESS", now, now)) + + taskStore := &MockTaskStore{} + taskStore.On("GetTasks", context.Background(), store.TaskFilter{CaseID: "C1"}).Return(nil, errors.New("db down")) + svc := NewCaseService(db, taskStore, fakeFlows{}, emptyArtifactSet(t)) + + if _, err := svc.GetCaseDetail(context.Background(), "C1"); err == nil || err.Error() != "list tasks of case C1: db down" { + t.Errorf("err = %v, want the task store error", err) + } +} + +func adminCaseRequest(p *authn.Principal, id string) *http.Request { + r := httptest.NewRequest(http.MethodGet, "/api/v1/admin/cases/"+id, nil) + r.SetPathValue("id", id) + if p != nil { + r = r.WithContext(authn.ContextWithPrincipal(r.Context(), p)) + } + return r +} + +var adminUser = &authn.Principal{Kind: authn.KindUser, UserID: "admin-1", OUHandle: "ops", Roles: []string{"Admin"}} + +// The admin case route serves whatever CaseService returns, with no ownership check. +func TestHandler_HandleGetCase(t *testing.T) { + db, sqlMock := newMockDB(t) + now := time.Now() + sqlMock.ExpectQuery(caseRowQuery()). + WithArgs("C1"). + WillReturnRows(sqlmock.NewRows([]string{"id", "name", "state", "created_at", "updated_at"}). + AddRow("C1", nil, "IN_PROGRESS", now, now)) + taskStore := &MockTaskStore{} + // The request context carries the auth principal, unlike the CaseService-level tests above. + taskStore.On("GetTasks", mock.Anything, store.TaskFilter{CaseID: "C1"}).Return([]store.TaskRecord(nil)) + cases := NewCaseService(db, taskStore, fakeFlows{}, emptyArtifactSet(t)) + client, capture := audit.NewWithCapture() + h := NewHandler(&Service{}, cases, client, testMaxRequestBytes) + + rec := httptest.NewRecorder() + h.HandleGetCase(rec, adminCaseRequest(adminUser, "C1")) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", rec.Code, rec.Body) + } + var got CaseDetail + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + if got.ID != "C1" { + t.Errorf("id = %q, want C1", got.ID) + } + if recs := capture.Records(); len(recs) != 1 || recs[0].TargetID != "C1" || recs[0].Metadata["view"] != "admin-case" { + t.Errorf("audit = %+v, want one admin-case read of C1", recs) + } +} + +// Unauthenticated is rejected before any query; an unknown id is a 404. +func TestHandler_HandleGetCase_Unauthenticated(t *testing.T) { + db, _ := newMockDB(t) + cases := NewCaseService(db, &MockTaskStore{}, fakeFlows{}, emptyArtifactSet(t)) + h := NewHandler(&Service{}, cases, nil, testMaxRequestBytes) + + rec := httptest.NewRecorder() + h.HandleGetCase(rec, adminCaseRequest(nil, "C1")) + if rec.Code != http.StatusUnauthorized { + t.Errorf("status = %d, want %d", rec.Code, http.StatusUnauthorized) + } +} + +func TestHandler_HandleGetCase_UnknownCase(t *testing.T) { + db, sqlMock := newMockDB(t) + sqlMock.ExpectQuery(caseRowQuery()).WithArgs("nope"). + WillReturnRows(sqlmock.NewRows([]string{"id", "name", "state", "created_at", "updated_at"})) + cases := NewCaseService(db, &MockTaskStore{}, fakeFlows{}, emptyArtifactSet(t)) + h := NewHandler(&Service{}, cases, nil, testMaxRequestBytes) + + rec := httptest.NewRecorder() + h.HandleGetCase(rec, adminCaseRequest(adminUser, "nope")) + if rec.Code != http.StatusNotFound { + t.Errorf("status = %d, want %d", rec.Code, http.StatusNotFound) + } +} diff --git a/platform/workflowadmin/engine_status.go b/platform/workflowadmin/engine_status.go new file mode 100644 index 0000000..daca945 --- /dev/null +++ b/platform/workflowadmin/engine_status.go @@ -0,0 +1,323 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (c) 2026 Lanka Software Foundation + +package workflowadmin + +import ( + "context" + "errors" + "fmt" + "log/slog" + "sort" + "time" + + "github.com/OpenNSW/core/taskflow/store" + workflow "github.com/OpenNSW/core/workflow" +) + +// EngineNodeDTO is a presentational view of one DAG node's raw engine state, as +// tracked by the workflow engine itself (workflow.NodeInfo), not the view of +// its tasks that a host derives from the task store. +// +// TODO: ID, LastError, ParkCategory, InputMapping, OutputMapping, CreatedAt, UpdatedAt, +// ChildWorkflowIDs and CachedTaskResult are plain copies of workflow.NodeInfo fields; revisit +// whether they need their own struct. +type EngineNodeDTO struct { + // ID is the node's ID in the workflow definition. It names the node, not a run of it, so it + // stays the same across retries and loop revisits; StepID addresses the current run. + ID string `json:"id"` + // StepID identifies the node's latest run (core's NodeInfo.ActivationID); a retry or loop + // revisit gives it a new one. A parked node is resolved by it, so a resolve made against an + // earlier parking of the same node is rejected instead of acting on a later one. + StepID string `json:"step_id,omitempty"` + Type string `json:"type"` + GatewayType string `json:"gateway_type,omitempty"` + TaskTemplateID string `json:"task_template_id,omitempty"` + Status string `json:"status"` + LastError string `json:"last_error,omitempty"` + // ParkCategory says why a node in AWAITING_ADMIN parked (INPUT_MAPPING, OUTPUT_MAPPING, + // TASK_FAILURE, GATEWAY_CONDITION, SPLIT_DATA, CHILD_FAILURE, DEFINITION_ERROR, ADMIN_FORCED or + // UNKNOWN), so the UI can guide an admin without parsing LastError. + ParkCategory string `json:"park_category,omitempty"` + // InputMapping and OutputMapping are the node's mappings, set only while it is parked. In + // InputMapping the key is the workflow variable read (a trailing "?" or "?!" marks it + // optional) and the value is the task input it fills; in OutputMapping the key is the task + // result field and the value is the workflow variable it writes. There a trailing "?" marks + // the field optional, and the variable keeps its value when the field is absent; with "?!", + // the variable is removed instead. So a RETRY fixes InputMapping keys, and a COMPLETE patch + // supplies OutputMapping values. + InputMapping map[string]string `json:"input_mapping,omitempty"` + OutputMapping map[string]string `json:"output_mapping,omitempty"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + // ChildWorkflowIDs lists any child workflow executions spawned by this node (SPLIT_TASK / + // BATCH_SPLIT). Each ID can be fetched via the same engine-status endpoint (it treats the + // path parameter as a workflow ID, not a case record) to drill down, regardless of + // whether that child has since completed. + ChildWorkflowIDs []string `json:"child_workflow_ids,omitempty"` + // TaskWorkflowID is set only for a TASK node whose task has actually started (there's a + // matching store.TaskRecord) — the workflow ID of the independent per-task ("micro") workflow + // spawned to fulfill it, on a separate manager/task queue from this node's own workflow (see + // Service.taskWm). Fetch it via the task-workflow engine-status endpoint to drill down — a + // node parked inside it is otherwise invisible here, since from this node's own workflow's + // point of view the TASK node is just pending completion. + TaskWorkflowID string `json:"task_workflow_id,omitempty"` + // CachedTaskResult is the raw Activity result of a TASK node whose Activity already ran, until + // the node completes. It shows an admin what came back before choosing RETRY or COMPLETE. + CachedTaskResult map[string]any `json:"cached_task_result,omitempty"` +} + +// EngineStatusDTO is one workflow's raw engine state: a case's flow, or a child +// workflow of one. +type EngineStatusDTO struct { + WorkflowID string `json:"workflow_id"` + Status string `json:"status"` + Nodes []EngineNodeDTO `json:"nodes"` + AuditTrail []string `json:"audit_trail"` + // GlobalVariables is the workflow instance's shared, dynamic business data + // (workflow.WorkflowInstance.WorkflowVariables) — workflow-wide, not per node; every node in + // this workflow sees the same snapshot. May hold business/PII data, hence the admin read scope + // rather than the scope applicants read their own cases with. + GlobalVariables map[string]any `json:"global_variables,omitempty"` + // Edges are the workflow's graph connections (workflow.WorkflowInstance.Edges). Source and + // target are the node IDs in Nodes[i].ID; conditions are verbatim. Lets an admin see what + // a parked GATEWAY's outgoing edges check. + Edges []workflow.Edge `json:"edges,omitempty"` +} + +// ErrEngineWorkflowNotFound is returned by GetEngineStatus when no workflow +// execution exists for the given ID on the registered workflow manager. +var ErrEngineWorkflowNotFound = errors.New("workflow execution not found") + +// ErrNodeNotParked is returned by ResolveAdminIntervention when no node is parked in AWAITING_ADMIN +// under the requested step: the step is unknown, already resolved, or an earlier parking of a node +// that has since parked again under a new step. Core silently drops a signal for such a step, so +// we check first. +var ErrNodeNotParked = errors.New("node is not currently awaiting admin intervention") + +// ErrAdminActionUnsupportedForGateway is returned for COMPLETE on a GATEWAY, which core would only +// log and re-park: a gateway's routing can't be bypassed. +var ErrAdminActionUnsupportedForGateway = errors.New("complete is not supported for GATEWAY nodes; use retry or abort") + +// ErrAdminInterventionUnsupported is returned when the workflow manager doesn't implement +// workflow.AdminInterventionResolver. +var ErrAdminInterventionUnsupported = errors.New("workflow manager does not support resolving admin interventions") + +// GetEngineStatus returns the raw engine state for workflowID — one of a case's flows, +// or (queried the same way, via this same endpoint) a nested child spawned by a SPLIT_TASK/ +// BATCH_SPLIT/PARALLEL_SPLIT node — straight from the registered workflow.Manager, an interface +// so this stays agnostic to whatever engine actually backs it. It checks no ownership of +// the case: the admin routes are gated on the admin scopes instead. +// +// Each TASK node's DTO is additionally enriched with TaskWorkflowID, when its task has actually +// started. +func (s *Service) GetEngineStatus(ctx context.Context, workflowID string) (*EngineStatusDTO, error) { + if s.wm == nil { + return nil, fmt.Errorf("no workflow manager registered for workflowadmin.Service") + } + + instance, err := s.wm.GetStatus(ctx, workflowID) + if err != nil { + if errors.Is(err, workflow.ErrWorkflowNotFound) { + return nil, ErrEngineWorkflowNotFound + } + return nil, fmt.Errorf("failed to get engine status for workflow %s: %w", workflowID, err) + } + + dto := buildEngineStatusDTO(workflowID, instance) + // Fetches every task record for the whole case, not just the ones under workflowID's + // own branch — the task store only supports filtering by case ID (see + // attachTaskWorkflowIDs), so a nested child-branch call re-fetches the same case-wide + // list. Acceptable for an admin screen opened manually and rarely; would need a narrower + // query on the task store itself (TaskRecord.ParentWorkflowID already holds the more specific + // ID, but nothing queries by it) if this ever shows up as an actual cost. + s.attachTaskWorkflowIDs(ctx, instance, dto.Nodes) + return dto, nil +} + +// GetTaskWorkflowEngineStatus returns the raw engine state for taskWorkflowID — the independent +// per-task ("micro") workflow a TASK node spawned to fulfill it (see EngineNodeDTO.TaskWorkflowID) +// — from the registered task-workflow manager, a separate manager/task queue from the one +// GetEngineStatus queries. +func (s *Service) GetTaskWorkflowEngineStatus(ctx context.Context, taskWorkflowID string) (*EngineStatusDTO, error) { + if s.taskWm == nil { + return nil, fmt.Errorf("no task workflow manager registered for workflowadmin.Service") + } + + instance, err := s.taskWm.GetStatus(ctx, taskWorkflowID) + if err != nil { + if errors.Is(err, workflow.ErrWorkflowNotFound) { + return nil, ErrEngineWorkflowNotFound + } + return nil, fmt.Errorf("failed to get engine status for task workflow %s: %w", taskWorkflowID, err) + } + + return buildEngineStatusDTO(taskWorkflowID, instance), nil +} + +// buildEngineStatusDTO converts a *workflow.WorkflowInstance into the presentational DTO shared +// by GetEngineStatus and GetTaskWorkflowEngineStatus — the two differ only in which +// workflow.Manager they queried and whether TaskWorkflowID enrichment applies. +func buildEngineStatusDTO(workflowID string, instance *workflow.WorkflowInstance) *EngineStatusDTO { + nodes := make([]EngineNodeDTO, 0, len(instance.NodeInfo)) + for _, n := range instance.NodeInfo { + // A DAG can define far more nodes than are ever relevant to look at — omit ones the + // interpreter hasn't reached yet, since "not started" carries no ops-actionable signal. + if n.Status == workflow.NodeStatusNotStarted { + continue + } + nodes = append(nodes, EngineNodeDTO{ + ID: n.ID, + StepID: n.ActivationID, + Type: string(n.Type), + GatewayType: string(n.GatewayType), + TaskTemplateID: n.TaskTemplateID, + Status: string(n.Status), + LastError: n.LastError, + ParkCategory: string(n.ParkCategory), + InputMapping: n.InputMapping, + OutputMapping: n.OutputMapping, + CreatedAt: n.CreatedAt, + UpdatedAt: n.UpdatedAt, + ChildWorkflowIDs: n.ChildWorkflowIDs, + CachedTaskResult: n.CachedTaskResult, + }) + } + // NodeInfo is a map; sort for a stable, readable response instead of + // random iteration order. + sort.Slice(nodes, func(i, j int) bool { + if !nodes[i].CreatedAt.Equal(nodes[j].CreatedAt) { + return nodes[i].CreatedAt.Before(nodes[j].CreatedAt) + } + return nodes[i].ID < nodes[j].ID + }) + + return &EngineStatusDTO{ + WorkflowID: workflowID, + Status: string(instance.Status), + Nodes: nodes, + AuditTrail: instance.AuditTrail, + GlobalVariables: instance.WorkflowVariables, + Edges: instance.Edges, + } +} + +// attachTaskWorkflowIDs fills in TaskWorkflowID on each TASK-type node in nodes, when its task +// has started. Task records are stored keyed by the case ID +// (store.TaskRecord.CaseID) even for a node nested several levels deep in a +// BATCH_SPLIT/PARALLEL_SPLIT branch — so the case ID is read off instance.WorkflowVariables +// (workflow.VarCaseID, propagated by the engine to every level of nesting) rather than +// assumed to be the workflowID GetEngineStatus was actually called with. Best-effort: if +// taskStore is nil or the case ID can't be determined, nodes are left without TaskWorkflowID +// rather than failing the whole engine-status read. +func (s *Service) attachTaskWorkflowIDs(ctx context.Context, instance *workflow.WorkflowInstance, nodes []EngineNodeDTO) { + if s.taskStore == nil { + return + } + caseID, _ := instance.WorkflowVariables[workflow.VarCaseID].(string) + if caseID == "" { + return + } + + tasks, err := s.taskStore.GetTasks(ctx, store.TaskFilter{CaseID: caseID}) + if err != nil { + slog.WarnContext(ctx, "workflowadmin: task workflow ids unavailable for engine status", "caseId", caseID, "error", err) + return + } + byTaskID := make(map[string]string, len(nodes)) + for _, rec := range tasks { + if rec.TaskWorkflowID != "" { + byTaskID[rec.TaskID] = rec.TaskWorkflowID + } + } + for i := range nodes { + if nodes[i].Type == string(workflow.NodeTypeTask) { + nodes[i].TaskWorkflowID = byTaskID[nodes[i].StepID] + } + } +} + +// ResolveAdminIntervention sends an admin's decision (RETRY/COMPLETE/ABORT) to a node parked +// in AWAITING_ADMIN on workflowID, one of a case's flows or one of its child-branch +// workflows, through the same manager GetEngineStatus queries. A task workflow is a separate ID +// space on its own manager: see ResolveTaskWorkflowAdminIntervention. sig.ActivationID names the +// parked step. +// +// nodeID is the resolved node's ID in the workflow definition (e.g. "officer_review"), not a run +// of it. It is returned only so the caller can audit which node was resolved in readable terms; +// the step ID is what addresses the run. +func (s *Service) ResolveAdminIntervention(ctx context.Context, workflowID string, sig workflow.AdminResolutionSignal) (nodeID string, err error) { + if s.wm == nil { + return "", fmt.Errorf("no workflow manager registered for workflowadmin.Service") + } + return resolveAdminIntervention(ctx, s.wm, workflowID, sig) +} + +// ResolveTaskWorkflowAdminIntervention is ResolveAdminIntervention for a node parked inside a task +// workflow (see EngineNodeDTO.TaskWorkflowID), resolved through the task workflow manager, the same +// one GetTaskWorkflowEngineStatus queries. +func (s *Service) ResolveTaskWorkflowAdminIntervention(ctx context.Context, taskWorkflowID string, sig workflow.AdminResolutionSignal) (nodeID string, err error) { + if s.taskWm == nil { + return "", fmt.Errorf("no task workflow manager registered for workflowadmin.Service") + } + return resolveAdminIntervention(ctx, s.taskWm, taskWorkflowID, sig) +} + +// resolveAdminIntervention is the body both resolve methods share, run against whichever manager +// owns workflowID. It finds the node parked under sig.ActivationID (the requested step), confirms a +// GATEWAY isn't asked to COMPLETE, fills in sig.NodeID and sends the signal. It returns the node's +// ID in the workflow definition, only for the caller's audit record (see ResolveAdminIntervention). +// +// Core routes the signal by sig.ActivationID (EngineNodeDTO.StepID), which must name a node's +// current run: a resolve made against an earlier parking of a node is rejected here, and if it +// slips past this check core drops it. +// +// The parked check and the signal are not atomic: the manager's ResolveAdminIntervention is a +// fire-and-forget Temporal signal, and core drops a signal for a step that is no longer parked +// without reporting it. If two admins resolve the same step at once, both can pass the check and +// both get success, though only the first signal takes effect. We accept this because admin +// resolution is expected to be a single admin acting at a time, not concurrent. TODO: fix this +// properly in core with an acknowledged Temporal Update that rejects a step that is no longer +// parked, then map that rejection to ErrNodeNotParked so the stale request gets a 409. +func resolveAdminIntervention(ctx context.Context, mgr workflow.Manager, workflowID string, sig workflow.AdminResolutionSignal) (string, error) { + resolver, ok := mgr.(workflow.AdminInterventionResolver) + if !ok { + return "", ErrAdminInterventionUnsupported + } + + instance, err := mgr.GetStatus(ctx, workflowID) + if err != nil { + if errors.Is(err, workflow.ErrWorkflowNotFound) { + return "", ErrEngineWorkflowNotFound + } + return "", fmt.Errorf("failed to verify step %s is parked on workflow %s: %w", sig.ActivationID, workflowID, err) + } + nodeID, node, ok := findParkedNode(instance.NodeInfo, sig.ActivationID) + if !ok { + return "", ErrNodeNotParked + } + if node.Type == workflow.NodeTypeGateway && sig.Action == workflow.AdminActionComplete { + return "", ErrAdminActionUnsupportedForGateway + } + sig.NodeID = nodeID + + if err := resolver.ResolveAdminIntervention(ctx, workflowID, "", sig); err != nil { + return "", fmt.Errorf("failed to resolve admin intervention for workflow %s node %s: %w", workflowID, nodeID, err) + } + return nodeID, nil +} + +// findParkedNode finds the node whose current run is stepID and is parked in AWAITING_ADMIN. A +// node's earlier runs are not in nodeInfo, so an earlier step matches nothing. A scan is fine: +// nodeInfo is small. +func findParkedNode(nodeInfo map[string]*workflow.NodeInfo, stepID string) (nodeID string, node *workflow.NodeInfo, ok bool) { + if stepID == "" { + return "", nil, false + } + for id, n := range nodeInfo { + if n.ActivationID == stepID && n.Status == workflow.NodeStatusAwaitingAdmin { + return id, n, true + } + } + return "", nil, false +} diff --git a/platform/workflowadmin/engine_status_test.go b/platform/workflowadmin/engine_status_test.go new file mode 100644 index 0000000..3fb9afe --- /dev/null +++ b/platform/workflowadmin/engine_status_test.go @@ -0,0 +1,410 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (c) 2026 Lanka Software Foundation + +package workflowadmin + +import ( + "context" + "testing" + "time" + + "fmt" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + "github.com/OpenNSW/core/taskflow/store" + workflow "github.com/OpenNSW/core/workflow" +) + +func TestService_GetEngineStatus(t *testing.T) { + mockWM := new(MockWM) + svc := newTestService(nil) + require.NoError(t, svc.RegisterWorkflowManager(mockWM)) + + ctx := context.Background() + flowID := uuid.NewString() + now := time.Now() + + instance := &workflow.WorkflowInstance{ + ID: flowID, + Status: workflow.StatusRunning, + WorkflowVariables: map[string]any{"declared_value": float64(1000)}, + NodeInfo: map[string]*workflow.NodeInfo{ + "node-b": {ID: "node-b", Type: workflow.NodeTypeTask, Status: workflow.NodeStatusRunning, CreatedAt: now.Add(time.Second), UpdatedAt: now.Add(time.Second)}, + "node-a": { + ID: "node-a", Type: workflow.NodeTypeSplitTask, Status: workflow.NodeStatusCompleted, CreatedAt: now, UpdatedAt: now, + ChildWorkflowIDs: []string{flowID + "--node-a--branch-1", flowID + "--node-a--branch-2"}, + }, + "node-c": {ID: "node-c", Type: workflow.NodeTypeTask, Status: workflow.NodeStatusNotStarted, CreatedAt: now.Add(2 * time.Second), UpdatedAt: now.Add(2 * time.Second)}, + }, + AuditTrail: []string{"workflow started"}, + Edges: []workflow.Edge{ + {ID: "e1", SourceID: "node-a", TargetID: "node-b", Condition: "declared_value > 500"}, + }, + } + mockWM.On("GetStatus", ctx, flowID).Return(instance, nil) + + result, err := svc.GetEngineStatus(ctx, flowID) + require.NoError(t, err) + assert.Equal(t, flowID, result.WorkflowID) + assert.Equal(t, "RUNNING", result.Status) + assert.Equal(t, []string{"workflow started"}, result.AuditTrail) + assert.Equal(t, map[string]any{"declared_value": float64(1000)}, result.GlobalVariables) + // node-c (NOT_STARTED) is filtered out — only node-a and node-b remain. + require.Len(t, result.Nodes, 2) + // Sorted by CreatedAt: node-a (earlier) before node-b. + assert.Equal(t, "node-a", result.Nodes[0].ID) + assert.Equal(t, "COMPLETED", result.Nodes[0].Status) + assert.Equal(t, []string{flowID + "--node-a--branch-1", flowID + "--node-a--branch-2"}, result.Nodes[0].ChildWorkflowIDs) + assert.Equal(t, "node-b", result.Nodes[1].ID) + assert.Equal(t, "RUNNING", result.Nodes[1].Status) + assert.Empty(t, result.Nodes[1].ChildWorkflowIDs) + // Edges pass straight through, condition included — an admin resolving a GATEWAY parked on + // "no matching conditions" needs to see exactly what each outgoing edge actually checks. + require.Len(t, result.Edges, 1) + assert.Equal(t, workflow.Edge{ID: "e1", SourceID: "node-a", TargetID: "node-b", Condition: "declared_value > 500"}, result.Edges[0]) + mockWM.AssertExpectations(t) +} + +// A parked node's category and mappings pass straight through — the resolve UI reads them to tell +// an admin why the node parked and which workflow variables a RETRY reads or a COMPLETE writes. +func TestService_GetEngineStatus_ParkContext(t *testing.T) { + mockWM := new(MockWM) + svc := newTestService(nil) + require.NoError(t, svc.RegisterWorkflowManager(mockWM)) + + ctx := context.Background() + flowID := uuid.NewString() + now := time.Now() + + instance := &workflow.WorkflowInstance{ + ID: flowID, + Status: workflow.StatusRunning, + NodeInfo: map[string]*workflow.NodeInfo{ + "review": { + ID: "review:uuid-1", Type: workflow.NodeTypeTask, Status: workflow.NodeStatusAwaitingAdmin, CreatedAt: now, UpdatedAt: now, + LastError: "output mapping error: required task variable 'status' not found in task result", + ParkCategory: workflow.ParkCategoryOutputMapping, + InputMapping: map[string]string{"applicant?": "applicant_ref"}, + OutputMapping: map[string]string{"status": "review.outcome"}, + }, + "intake": {ID: "intake:uuid-2", Type: workflow.NodeTypeTask, Status: workflow.NodeStatusCompleted, CreatedAt: now.Add(time.Second), UpdatedAt: now.Add(time.Second)}, + }, + } + mockWM.On("GetStatus", ctx, flowID).Return(instance, nil) + + result, err := svc.GetEngineStatus(ctx, flowID) + require.NoError(t, err) + require.Len(t, result.Nodes, 2) + + parked := result.Nodes[0] + assert.Equal(t, "review:uuid-1", parked.ID) + assert.Equal(t, "OUTPUT_MAPPING", parked.ParkCategory) + assert.Equal(t, map[string]string{"applicant?": "applicant_ref"}, parked.InputMapping) + assert.Equal(t, map[string]string{"status": "review.outcome"}, parked.OutputMapping) + + // A node that isn't parked carries none of it. + assert.Empty(t, result.Nodes[1].ParkCategory) + assert.Nil(t, result.Nodes[1].InputMapping) + assert.Nil(t, result.Nodes[1].OutputMapping) + mockWM.AssertExpectations(t) +} + +func TestService_GetEngineStatus_NotFound(t *testing.T) { + mockWM := new(MockWM) + svc := newTestService(nil) + require.NoError(t, svc.RegisterWorkflowManager(mockWM)) + + ctx := context.Background() + flowID := uuid.NewString() + mockWM.On("GetStatus", ctx, flowID).Return((*workflow.WorkflowInstance)(nil), fmt.Errorf("%w: workflow not found", workflow.ErrWorkflowNotFound)) + + _, err := svc.GetEngineStatus(ctx, flowID) + assert.ErrorIs(t, err, ErrEngineWorkflowNotFound) + mockWM.AssertExpectations(t) +} + +func TestService_GetEngineStatus_NoWorkflowManager(t *testing.T) { + svc := newTestService(nil) + + _, err := svc.GetEngineStatus(context.Background(), uuid.NewString()) + assert.Error(t, err) +} + +// A TASK node's TaskWorkflowID is filled in from the task store, keyed off +// workflow.VarCaseID rather than the queried workflow ID itself — this matters when +// GetEngineStatus is called on a nested child branch, not just the flow itself. +func TestService_GetEngineStatus_AttachesTaskWorkflowID(t *testing.T) { + mockWM := new(MockWM) + mockTaskStore := new(MockTaskStore) + svc := newTestService(mockTaskStore) + require.NoError(t, svc.RegisterWorkflowManager(mockWM)) + + ctx := context.Background() + caseID := uuid.NewString() + childWorkflowID := uuid.NewString() + stepID := uuid.NewString() + + instance := &workflow.WorkflowInstance{ + ID: childWorkflowID, + Status: workflow.StatusRunning, + WorkflowVariables: map[string]any{ + workflow.VarCaseID: caseID, + }, + NodeInfo: map[string]*workflow.NodeInfo{ + "officer_review": {ID: "officer_review", ActivationID: stepID, Type: workflow.NodeTypeTask, Status: workflow.NodeStatusAwaitingAdmin}, + "gateway_node": {ID: "gateway_node", ActivationID: stepID, Type: workflow.NodeTypeGateway, Status: workflow.NodeStatusCompleted}, + }, + } + mockWM.On("GetStatus", ctx, childWorkflowID).Return(instance, nil) + mockTaskStore.On("GetTasks", ctx, store.TaskFilter{CaseID: caseID}).Return([]store.TaskRecord{ + {TaskID: stepID, TaskWorkflowID: "task-wf-" + stepID}, + }) + + result, err := svc.GetEngineStatus(ctx, childWorkflowID) + require.NoError(t, err) + require.Len(t, result.Nodes, 2) + byID := map[string]EngineNodeDTO{result.Nodes[0].ID: result.Nodes[0], result.Nodes[1].ID: result.Nodes[1]} + assert.Equal(t, "task-wf-"+stepID, byID["officer_review"].TaskWorkflowID) + // Not a TASK node — must not get a TaskWorkflowID even though nothing prevents the map + // lookup from matching by coincidence. + assert.Empty(t, byID["gateway_node"].TaskWorkflowID) + mockWM.AssertExpectations(t) + mockTaskStore.AssertExpectations(t) +} + +func TestService_GetTaskWorkflowEngineStatus(t *testing.T) { + mockTaskWM := new(MockWM) + svc := newTestService(nil) + require.NoError(t, svc.RegisterTaskWorkflowManager(mockTaskWM)) + + ctx := context.Background() + taskWorkflowID := "task-wf-officer_review" + instance := &workflow.WorkflowInstance{ + ID: taskWorkflowID, + Status: workflow.StatusRunning, + NodeInfo: map[string]*workflow.NodeInfo{ + "map_output": {ID: "map_output", Type: workflow.NodeTypeTask, Status: workflow.NodeStatusAwaitingAdmin, LastError: "output mapping error"}, + }, + } + mockTaskWM.On("GetStatus", ctx, taskWorkflowID).Return(instance, nil) + + result, err := svc.GetTaskWorkflowEngineStatus(ctx, taskWorkflowID) + require.NoError(t, err) + assert.Equal(t, taskWorkflowID, result.WorkflowID) + require.Len(t, result.Nodes, 1) + assert.Equal(t, "AWAITING_ADMIN", result.Nodes[0].Status) + assert.Equal(t, "output mapping error", result.Nodes[0].LastError) + mockTaskWM.AssertExpectations(t) +} + +func TestService_GetTaskWorkflowEngineStatus_NotFound(t *testing.T) { + mockTaskWM := new(MockWM) + svc := newTestService(nil) + require.NoError(t, svc.RegisterTaskWorkflowManager(mockTaskWM)) + + ctx := context.Background() + taskWorkflowID := "task-wf-missing" + mockTaskWM.On("GetStatus", ctx, taskWorkflowID).Return((*workflow.WorkflowInstance)(nil), fmt.Errorf("%w: workflow not found", workflow.ErrWorkflowNotFound)) + + _, err := svc.GetTaskWorkflowEngineStatus(ctx, taskWorkflowID) + assert.ErrorIs(t, err, ErrEngineWorkflowNotFound) + mockTaskWM.AssertExpectations(t) +} + +func TestService_GetTaskWorkflowEngineStatus_NoManager(t *testing.T) { + svc := newTestService(nil) + + _, err := svc.GetTaskWorkflowEngineStatus(context.Background(), "task-wf-officer_review") + assert.Error(t, err) +} + +// TestService_ResolveAdminIntervention_RoutesByStepID: a resolve names only the parked +// step (EngineNodeDTO.StepID). The service finds the node parked under it and sends core a signal +// carrying both, since core matches pending resolutions on the ActivationID and silently drops a +// signal that names no current parking. +func TestService_ResolveAdminIntervention_RoutesByStepID(t *testing.T) { + mockWM := new(MockWM) + svc := newTestService(nil) + require.NoError(t, svc.RegisterWorkflowManager(mockWM)) + + ctx := context.Background() + workflowID := "flow-1" + stepID := "6aad0417-9a6d-4407-9509-2e51d8fcae99" + + instance := &workflow.WorkflowInstance{ + ID: workflowID, + Status: workflow.StatusRunning, + NodeInfo: map[string]*workflow.NodeInfo{ + "officer_review": {ID: "officer_review", ActivationID: stepID, Type: workflow.NodeTypeTask, Status: workflow.NodeStatusAwaitingAdmin}, + }, + } + mockWM.On("GetStatus", ctx, workflowID).Return(instance, nil) + mockWM.On("ResolveAdminIntervention", ctx, workflowID, "", mock.MatchedBy(func(sig workflow.AdminResolutionSignal) bool { + return sig.NodeID == "officer_review" && sig.ActivationID == stepID + })).Return(nil) + + nodeID, err := svc.ResolveAdminIntervention(ctx, workflowID, workflow.AdminResolutionSignal{ + ActivationID: stepID, + Action: workflow.AdminActionComplete, + Reason: "activity already ran, supplying result manually", + }) + require.NoError(t, err) + assert.Equal(t, "officer_review", nodeID) + mockWM.AssertExpectations(t) +} + +// A resolve naming an earlier parking of the node — it was resolved and has parked again under a +// new step ID since the admin loaded the engine status — is rejected rather than applied to the +// newer parking, and no signal is sent. +func TestService_ResolveAdminIntervention_StaleStepID(t *testing.T) { + mockWM := new(MockWM) + svc := newTestService(nil) + require.NoError(t, svc.RegisterWorkflowManager(mockWM)) + + ctx := context.Background() + workflowID := "flow-1" + mockWM.On("GetStatus", ctx, workflowID).Return(&workflow.WorkflowInstance{ + ID: workflowID, + Status: workflow.StatusRunning, + NodeInfo: map[string]*workflow.NodeInfo{ + "officer_review": {ID: "officer_review", ActivationID: "current-step", Type: workflow.NodeTypeTask, Status: workflow.NodeStatusAwaitingAdmin}, + }, + }, nil) + + _, err := svc.ResolveAdminIntervention(ctx, workflowID, workflow.AdminResolutionSignal{ + ActivationID: "earlier-step", + Action: workflow.AdminActionRetry, + Reason: "retry", + }) + assert.ErrorIs(t, err, ErrNodeNotParked) + mockWM.AssertExpectations(t) +} + +// A node parked inside a task workflow is resolved through the task workflow manager, routed by +// its step ID the same way, and the root manager is never consulted. +func TestService_ResolveTaskWorkflowAdminIntervention_UsesTaskManager(t *testing.T) { + rootWM, taskWM := new(MockWM), new(MockWM) + rootWM.Test(t) // any call to it fails the test + svc := newTestService(nil) + require.NoError(t, svc.RegisterWorkflowManager(rootWM)) + require.NoError(t, svc.RegisterTaskWorkflowManager(taskWM)) + + ctx := context.Background() + taskWorkflowID := "task-wf-n1_apply:ca7ed707-1dba-43ca-94bf-10eddf00df3c" + stepID := "6aad0417-9a6d-4407-9509-2e51d8fcae99" + taskWM.On("GetStatus", ctx, taskWorkflowID).Return(&workflow.WorkflowInstance{ + ID: taskWorkflowID, + Status: workflow.StatusRunning, + NodeInfo: map[string]*workflow.NodeInfo{ + "review_step": {ID: "review_step", ActivationID: stepID, Type: workflow.NodeTypeTask, Status: workflow.NodeStatusAwaitingAdmin}, + }, + }, nil) + taskWM.On("ResolveAdminIntervention", ctx, taskWorkflowID, "", mock.MatchedBy(func(sig workflow.AdminResolutionSignal) bool { + return sig.NodeID == "review_step" && sig.ActivationID == stepID + })).Return(nil) + + _, err := svc.ResolveTaskWorkflowAdminIntervention(ctx, taskWorkflowID, workflow.AdminResolutionSignal{ + ActivationID: stepID, + Action: workflow.AdminActionRetry, + Reason: "retry", + }) + require.NoError(t, err) + taskWM.AssertExpectations(t) + rootWM.AssertNotCalled(t, "GetStatus", mock.Anything, mock.Anything) +} + +func TestService_ResolveTaskWorkflowAdminIntervention_NoTaskManager(t *testing.T) { + rootWM := new(MockWM) + rootWM.Test(t) + svc := newTestService(nil) + require.NoError(t, svc.RegisterWorkflowManager(rootWM)) + + _, err := svc.ResolveTaskWorkflowAdminIntervention(context.Background(), "task-wf-1", workflow.AdminResolutionSignal{ + Action: workflow.AdminActionRetry, + Reason: "retry", + }) + // Not resolved through the root manager instead: that would be a silent fallback. + assert.ErrorContains(t, err, "no task workflow manager registered") + rootWM.AssertNotCalled(t, "GetStatus", mock.Anything, mock.Anything) +} + +func TestService_ResolveAdminIntervention_UnknownStepID(t *testing.T) { + mockWM := new(MockWM) + svc := newTestService(nil) + require.NoError(t, svc.RegisterWorkflowManager(mockWM)) + + ctx := context.Background() + workflowID := "flow-1" + instance := &workflow.WorkflowInstance{ + ID: workflowID, + Status: workflow.StatusRunning, + NodeInfo: map[string]*workflow.NodeInfo{ + "officer_review": {ID: "officer_review", ActivationID: "step-1", Type: workflow.NodeTypeTask, Status: workflow.NodeStatusAwaitingAdmin}, + }, + } + mockWM.On("GetStatus", ctx, workflowID).Return(instance, nil) + + _, err := svc.ResolveAdminIntervention(ctx, workflowID, workflow.AdminResolutionSignal{ + ActivationID: "no-such-step", + Action: workflow.AdminActionRetry, + Reason: "retry", + }) + assert.ErrorIs(t, err, ErrNodeNotParked) + mockWM.AssertExpectations(t) +} + +func TestService_ResolveAdminIntervention_NodeNotAwaitingAdmin(t *testing.T) { + mockWM := new(MockWM) + svc := newTestService(nil) + require.NoError(t, svc.RegisterWorkflowManager(mockWM)) + + ctx := context.Background() + workflowID := "flow-1" + instance := &workflow.WorkflowInstance{ + ID: workflowID, + Status: workflow.StatusRunning, + NodeInfo: map[string]*workflow.NodeInfo{ + "officer_review": {ID: "officer_review", ActivationID: "step-1", Type: workflow.NodeTypeTask, Status: workflow.NodeStatusRunning}, + }, + } + mockWM.On("GetStatus", ctx, workflowID).Return(instance, nil) + + _, err := svc.ResolveAdminIntervention(ctx, workflowID, workflow.AdminResolutionSignal{ + ActivationID: "step-1", + Action: workflow.AdminActionRetry, + Reason: "retry", + }) + assert.ErrorIs(t, err, ErrNodeNotParked) + mockWM.AssertExpectations(t) +} + +func TestService_ResolveAdminIntervention_GatewayCompleteUnsupported(t *testing.T) { + mockWM := new(MockWM) + svc := newTestService(nil) + require.NoError(t, svc.RegisterWorkflowManager(mockWM)) + + ctx := context.Background() + workflowID := "flow-1" + instance := &workflow.WorkflowInstance{ + ID: workflowID, + Status: workflow.StatusRunning, + NodeInfo: map[string]*workflow.NodeInfo{ + "gw1": {ID: "gw1", ActivationID: "step-1", Type: workflow.NodeTypeGateway, Status: workflow.NodeStatusAwaitingAdmin}, + }, + } + mockWM.On("GetStatus", ctx, workflowID).Return(instance, nil) + + _, err := svc.ResolveAdminIntervention(ctx, workflowID, workflow.AdminResolutionSignal{ + ActivationID: "step-1", + Action: workflow.AdminActionComplete, + Reason: "complete", + }) + assert.ErrorIs(t, err, ErrAdminActionUnsupportedForGateway) + // ResolveAdminIntervention on the manager must never be called for a rejected action — no + // expectation was set for it above, so testify would panic on an unexpected call. + mockWM.AssertExpectations(t) +} diff --git a/platform/workflowadmin/force_park.go b/platform/workflowadmin/force_park.go new file mode 100644 index 0000000..052acf7 --- /dev/null +++ b/platform/workflowadmin/force_park.go @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (c) 2026 Lanka Software Foundation + +package workflowadmin + +import ( + "context" + "errors" + "fmt" + + "github.com/OpenNSW/core/taskflow/orchestrator" + workflow "github.com/OpenNSW/core/workflow" +) + +// ErrNodeNotWaiting is returned by the force-park methods when the step names no TASK node that is +// still waiting on it: the step is unknown or over, the node is already parked, or its task finished +// while the request was in flight. +var ErrNodeNotWaiting = errors.New("node is not waiting on its step") + +// ErrForceParkUnsupportedNodeType is returned by the force-park methods for a node that isn't a TASK. +var ErrForceParkUnsupportedNodeType = errors.New("force-park is supported only for TASK nodes") + +// ForceParkTaskNode moves a TASK node on a flow (or a child workflow of one) that is waiting on its task into +// AWAITING_ADMIN, and closes that task. An admin then resolves the node like any parked node: RETRY +// starts a new task under a new step, COMPLETE moves on with a variables patch as the node's output, +// ABORT fails the workflow. Use it when the whole task has to go, for example to rebuild it from +// amended data. To override a single step and let the task carry on, use ForceParkTaskWorkflowStep. +// +// workflowID is a case's flow or one of its child-branch workflows, and stepID is +// the node's step_id from that workflow's engine status. It returns the node's ID in the workflow +// definition, for the caller's audit record. +// +// The node's step is parked first, so the node enters AWAITING_ADMIN (with ParkCategoryAdminForced) +// and stops accepting the task's completion, and then the task is closed. If closing the task fails, +// the node is already visibly parked and repeating the request finishes closing the task. +func (s *Service) ForceParkTaskNode(ctx context.Context, workflowID, stepID, reason string) (nodeID string, err error) { + if s.tasks == nil { + return "", fmt.Errorf("no task canceller registered for workflowadmin.Service") + } + return forceParkStep(ctx, s.wm, workflowID, stepID, reason, func() error { + // The task is named after the step that started it (see core's TaskManager.StartTask). If + // the task completed in the gap after ForceParkActivation, its completion was rejected by + // the parent workflow (ErrActivationNotPending) and the task is already closed. + err := s.tasks.CancelTask(ctx, stepID, reason) + if errors.Is(err, orchestrator.ErrTaskNotOpen) { + return nil + } + return err + }) +} + +// ForceParkTaskWorkflowStep moves one step of a task workflow that is waiting, such as a wait for an +// external callback, into AWAITING_ADMIN. The task stays open. Resolving the step through the task +// workflow's resolve route lets the task carry on: COMPLETE with a patch of the variables the step +// would have produced stands in for a callback that will never come, and the task then ends +// normally and reports to its parent. +// +// taskWorkflowID is a TASK node's task_workflow_id and stepID is the step's step_id from that task +// workflow's engine status. It returns the step's node ID, for the caller's audit record. +// +// While the step is parked the task is placed ON_HOLD (via the task workflow's AdminParkHandler), +// hiding interactive controls and refusing submissions or drafts as stale. +func (s *Service) ForceParkTaskWorkflowStep(ctx context.Context, taskWorkflowID, stepID, reason string) (nodeID string, err error) { + return forceParkStep(ctx, s.taskWm, taskWorkflowID, stepID, reason, nil) +} + +// forceParkStep is the body both force-park methods share, run against whichever manager owns +// workflowID. It checks the step names a TASK node waiting on it, parks the step first, then runs +// afterPark if set. If an earlier call parked the node (ParkCategoryAdminForced) and failed in +// afterPark, a retry skips ForceParkActivation and finishes afterPark. +func forceParkStep(ctx context.Context, mgr workflow.Manager, workflowID, stepID, reason string, afterPark func() error) (string, error) { + if mgr == nil { + return "", fmt.Errorf("no workflow manager registered for workflow %s", workflowID) + } + parker, ok := mgr.(workflow.ActivationParker) + if !ok { + return "", fmt.Errorf("workflow manager does not support force-parking a step") + } + + instance, err := mgr.GetStatus(ctx, workflowID) + if err != nil { + if errors.Is(err, workflow.ErrWorkflowNotFound) { + return "", ErrEngineWorkflowNotFound + } + return "", fmt.Errorf("failed to verify step %s is waiting on workflow %s: %w", stepID, workflowID, err) + } + nodeID, alreadyForceParked, err := findForceParkNode(instance.NodeInfo, stepID, afterPark != nil) + if err != nil { + return "", err + } + + if !alreadyForceParked { + if err := parker.ForceParkActivation(ctx, workflowID, "", stepID, reason); err != nil { + if errors.Is(err, workflow.ErrActivationNotPending) { + return "", fmt.Errorf("%w: %w", ErrNodeNotWaiting, err) + } + return "", fmt.Errorf("failed to park node %s on workflow %s: %w", nodeID, workflowID, err) + } + } + if afterPark != nil { + if err := afterPark(); err != nil { + return "", err + } + } + return nodeID, nil +} + +// findForceParkNode locates the TASK node whose current run is stepID and checks whether it is +// waiting (or, when allowAlreadyForceParked is true, already force-parked so a retry can finish +// closing its task). +func findForceParkNode(nodeInfo map[string]*workflow.NodeInfo, stepID string, allowAlreadyForceParked bool) (nodeID string, alreadyForceParked bool, err error) { + nodeID, node, ok := findNodeByStep(nodeInfo, stepID) + if !ok { + return "", false, ErrNodeNotWaiting + } + if node.Type != workflow.NodeTypeTask { + return "", false, ErrForceParkUnsupportedNodeType + } + alreadyForceParked = allowAlreadyForceParked && + node.Status == workflow.NodeStatusAwaitingAdmin && + node.ParkCategory == workflow.ParkCategoryAdminForced + if node.Status != workflow.NodeStatusRunning && !alreadyForceParked { + return "", false, ErrNodeNotWaiting + } + return nodeID, alreadyForceParked, nil +} + +// findNodeByStep finds the node whose current run is stepID, whatever its status. +func findNodeByStep(nodeInfo map[string]*workflow.NodeInfo, stepID string) (nodeID string, node *workflow.NodeInfo, ok bool) { + if stepID == "" { + return "", nil, false + } + for id, n := range nodeInfo { + if n.ActivationID == stepID { + return id, n, true + } + } + return "", nil, false +} diff --git a/platform/workflowadmin/force_park_test.go b/platform/workflowadmin/force_park_test.go new file mode 100644 index 0000000..1d4398b --- /dev/null +++ b/platform/workflowadmin/force_park_test.go @@ -0,0 +1,338 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (c) 2026 Lanka Software Foundation + +package workflowadmin + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + "github.com/OpenNSW/core/httputil" + "github.com/OpenNSW/core/platform/audit" + "github.com/OpenNSW/core/taskflow/orchestrator" + workflow "github.com/OpenNSW/core/workflow" +) + +// fakeTaskCanceller records the tasks it is asked to cancel, in calls shared with the test's +// workflow manager so their order can be checked. +type fakeTaskCanceller struct { + calls *[]string + err error +} + +func (f *fakeTaskCanceller) CancelTask(_ context.Context, taskID, reason string) error { + *f.calls = append(*f.calls, "cancel "+taskID+" ("+reason+")") + return f.err +} + +// waitingInstance is a workflow with one node of nodeType running under resolveTestStepID, as a +// TASK node is while it waits on its step. +func waitingInstance(nodeType workflow.NodeType) *workflow.WorkflowInstance { + inst := parkedInstance(nodeType) + inst.NodeInfo[resolveTestNodeID].Status = workflow.NodeStatusRunning + return inst +} + +// forceParkRoute is one of the two force-park endpoints, with the service method behind it. +type forceParkRoute struct { + name string + own managerSlot + other managerSlot + park func(s *Service) func(ctx context.Context, workflowID, stepID, reason string) (string, error) + handler func(r *Handler) http.HandlerFunc + // cancels says whether the route closes the node's task before parking it. + cancels bool +} + +var forceParkRoutes = []forceParkRoute{ + { + name: "flow route", own: rootManager, other: taskManager, cancels: true, + park: func(s *Service) func(context.Context, string, string, string) (string, error) { + return s.ForceParkTaskNode + }, + handler: func(r *Handler) http.HandlerFunc { return r.HandleForceParkTaskNode }, + }, + { + name: "task workflow route", own: taskManager, other: rootManager, cancels: false, + park: func(s *Service) func(context.Context, string, string, string) (string, error) { + return s.ForceParkTaskWorkflowStep + }, + handler: func(r *Handler) http.HandlerFunc { return r.HandleForceParkTaskWorkflowStep }, + }, +} + +// forceParkFixture builds a Service with mockWM as the route's own manager, an unused manager in the +// other slot, and a canceller returning cancelErr. Both record into the returned calls. +func forceParkFixture(t *testing.T, route forceParkRoute, cancelErr error) (*Service, *MockWM, *[]string) { + t.Helper() + calls := &[]string{} + mockWM, otherWM := new(MockWM), new(MockWM) + otherWM.Test(t) // any call on the other manager fails the test + svc := newTestService(nil) + require.NoError(t, route.own(svc, mockWM)) + require.NoError(t, route.other(svc, otherWM)) + require.NoError(t, svc.RegisterTaskCanceller(&fakeTaskCanceller{calls: calls, err: cancelErr})) + return svc, mockWM, calls +} + +// expectPark sets up the step's park on mockWM, recording it into calls, and returning err. +func expectPark(mockWM *MockWM, calls *[]string, err error) { + mockWM.On("ForceParkActivation", mock.Anything, resolveTestWorkflowID, "", resolveTestStepID, "warranted offline"). + Run(func(mock.Arguments) { *calls = append(*calls, "park") }). + Return(err) +} + +// The flow route parks the node first (so it is visibly parked and stops accepting the +// task's completion), then closes the node's task. The task workflow route parks the step alone and +// leaves its task open. +func TestForcePark_ParksTheStep(t *testing.T) { + for _, route := range forceParkRoutes { + t.Run(route.name, func(t *testing.T) { + svc, mockWM, calls := forceParkFixture(t, route, nil) + mockWM.On("GetStatus", mock.Anything, resolveTestWorkflowID).Return(waitingInstance(workflow.NodeTypeTask), nil) + expectPark(mockWM, calls, nil) + + nodeID, err := route.park(svc)(context.Background(), resolveTestWorkflowID, resolveTestStepID, "warranted offline") + + require.NoError(t, err) + assert.Equal(t, resolveTestNodeID, nodeID) + want := []string{"park"} + if route.cancels { + want = []string{"park", "cancel " + resolveTestStepID + " (warranted offline)"} + } + assert.Equal(t, want, *calls) + mockWM.AssertExpectations(t) + }) + } +} + +func TestForcePark_RejectsNodesNotWaiting(t *testing.T) { + tests := []struct { + name string + instance *workflow.WorkflowInstance + wantErr error + }{ + {"an unknown step", func() *workflow.WorkflowInstance { + inst := waitingInstance(workflow.NodeTypeTask) + inst.NodeInfo[resolveTestNodeID].ActivationID = "step-2" + return inst + }(), ErrNodeNotWaiting}, + {"a node already parked", parkedInstance(workflow.NodeTypeTask), ErrNodeNotWaiting}, + {"a completed node", func() *workflow.WorkflowInstance { + inst := waitingInstance(workflow.NodeTypeTask) + inst.NodeInfo[resolveTestNodeID].Status = workflow.NodeStatusCompleted + return inst + }(), ErrNodeNotWaiting}, + {"a split node", waitingInstance(workflow.NodeTypeSplitTask), ErrForceParkUnsupportedNodeType}, + {"a gateway", waitingInstance(workflow.NodeTypeGateway), ErrForceParkUnsupportedNodeType}, + } + for _, route := range forceParkRoutes { + for _, tt := range tests { + t.Run(route.name+"/"+tt.name, func(t *testing.T) { + svc, mockWM, calls := forceParkFixture(t, route, nil) + mockWM.On("GetStatus", mock.Anything, resolveTestWorkflowID).Return(tt.instance, nil) + + _, err := route.park(svc)(context.Background(), resolveTestWorkflowID, resolveTestStepID, "warranted offline") + + assert.ErrorIs(t, err, tt.wantErr) + assert.Empty(t, *calls) + }) + } + } +} + +// If the task finished in the gap right after ForceParkActivation parked the parent node, its +// completion was rejected by the parent workflow and the task is already closed: ForceParkTaskNode +// still succeeds. +func TestForceParkTaskNode_TaskClosedInTheGapAfterParkSucceeds(t *testing.T) { + svc, mockWM, calls := forceParkFixture(t, forceParkRoutes[0], fmt.Errorf("%w: task has completed", orchestrator.ErrTaskNotOpen)) + mockWM.On("GetStatus", mock.Anything, resolveTestWorkflowID).Return(waitingInstance(workflow.NodeTypeTask), nil) + expectPark(mockWM, calls, nil) + + nodeID, err := svc.ForceParkTaskNode(context.Background(), resolveTestWorkflowID, resolveTestStepID, "warranted offline") + + require.NoError(t, err) + assert.Equal(t, resolveTestNodeID, nodeID) + assert.Equal(t, []string{"park", "cancel " + resolveTestStepID + " (warranted offline)"}, *calls) + mockWM.AssertExpectations(t) +} + +// If ForceParkActivation succeeds and CancelTask then fails, the node is visibly parked with +// ParkCategoryAdminForced, and repeating ForceParkTaskNode finishes cancelling the task without +// calling ForceParkActivation again. +func TestForceParkTaskNode_CancelFailureCanBeRetriedOnceParked(t *testing.T) { + svc, mockWM, calls := forceParkFixture(t, forceParkRoutes[0], errors.New("temporal unavailable")) + mockWM.On("GetStatus", mock.Anything, resolveTestWorkflowID).Return(waitingInstance(workflow.NodeTypeTask), nil).Once() + expectPark(mockWM, calls, nil) + + _, err := svc.ForceParkTaskNode(context.Background(), resolveTestWorkflowID, resolveTestStepID, "warranted offline") + require.Error(t, err) + assert.NotErrorIs(t, err, ErrNodeNotWaiting) + assert.Equal(t, []string{"park", "cancel " + resolveTestStepID + " (warranted offline)"}, *calls) + + // Retry: the node is now AWAITING_ADMIN with ParkCategoryAdminForced. + alreadyParked := parkedInstance(workflow.NodeTypeTask) + alreadyParked.NodeInfo[resolveTestNodeID].ParkCategory = workflow.ParkCategoryAdminForced + mockWM.On("GetStatus", mock.Anything, resolveTestWorkflowID).Return(alreadyParked, nil).Once() + svc.tasks.(*fakeTaskCanceller).err = nil + + nodeID, err := svc.ForceParkTaskNode(context.Background(), resolveTestWorkflowID, resolveTestStepID, "warranted offline") + require.NoError(t, err) + assert.Equal(t, resolveTestNodeID, nodeID) + assert.Equal(t, []string{ + "park", + "cancel " + resolveTestStepID + " (warranted offline)", + "cancel " + resolveTestStepID + " (warranted offline)", + }, *calls) + mockWM.AssertExpectations(t) +} + +// The step finished while the request was in flight. +func TestForcePark_StepNoLongerPending(t *testing.T) { + for _, route := range forceParkRoutes { + t.Run(route.name, func(t *testing.T) { + svc, mockWM, calls := forceParkFixture(t, route, nil) + mockWM.On("GetStatus", mock.Anything, resolveTestWorkflowID).Return(waitingInstance(workflow.NodeTypeTask), nil) + expectPark(mockWM, calls, fmt.Errorf("%w: gone", workflow.ErrActivationNotPending)) + + _, err := route.park(svc)(context.Background(), resolveTestWorkflowID, resolveTestStepID, "warranted offline") + + assert.ErrorIs(t, err, ErrNodeNotWaiting) + }) + } +} + +func TestForcePark_WorkflowNotFound(t *testing.T) { + for _, route := range forceParkRoutes { + t.Run(route.name, func(t *testing.T) { + svc, mockWM, _ := forceParkFixture(t, route, nil) + mockWM.On("GetStatus", mock.Anything, resolveTestWorkflowID). + Return((*workflow.WorkflowInstance)(nil), fmt.Errorf("%w: gone", workflow.ErrWorkflowNotFound)) + + _, err := route.park(svc)(context.Background(), resolveTestWorkflowID, resolveTestStepID, "warranted offline") + + assert.ErrorIs(t, err, ErrEngineWorkflowNotFound) + }) + } +} + +func TestForceParkTaskNode_NoTaskCanceller(t *testing.T) { + svc := newTestService(nil) + require.NoError(t, svc.RegisterWorkflowManager(new(MockWM))) + + _, err := svc.ForceParkTaskNode(context.Background(), resolveTestWorkflowID, resolveTestStepID, "reason") + + require.Error(t, err) + assert.Contains(t, err.Error(), "no task canceller") +} + +func newForceParkRequest(body string) *http.Request { + req := newResolveRequest(body) + req.URL.Path = strings.TrimSuffix(req.URL.Path, "/resolve") + "/force-park" + return req +} + +func TestRouter_HandleForcePark_MapsResults(t *testing.T) { + tests := []struct { + name string + instance *workflow.WorkflowInstance + statusErr error + parkErr error + wantStatus int + }{ + {"parked is 204", waitingInstance(workflow.NodeTypeTask), nil, nil, http.StatusNoContent}, + {"workflow not found is 404", nil, fmt.Errorf("%w: gone", workflow.ErrWorkflowNotFound), nil, http.StatusNotFound}, + {"node not waiting is 409", parkedInstance(workflow.NodeTypeTask), nil, nil, http.StatusConflict}, + {"step no longer pending is 409", waitingInstance(workflow.NodeTypeTask), nil, workflow.ErrActivationNotPending, http.StatusConflict}, + {"a non-TASK node is 400", waitingInstance(workflow.NodeTypeGateway), nil, nil, http.StatusBadRequest}, + {"a Temporal failure is 500", waitingInstance(workflow.NodeTypeTask), nil, errors.New("temporal unavailable"), http.StatusInternalServerError}, + } + for _, route := range forceParkRoutes { + for _, tt := range tests { + t.Run(route.name+"/"+tt.name, func(t *testing.T) { + svc, mockWM, calls := forceParkFixture(t, route, nil) + client, _ := audit.NewWithCapture() + r := NewHandler(svc, nil, client, testMaxRequestBytes) + mockWM.On("GetStatus", mock.Anything, resolveTestWorkflowID).Return(tt.instance, tt.statusErr) + expectPark(mockWM, calls, tt.parkErr) + + w := httptest.NewRecorder() + route.handler(r)(w, newForceParkRequest(`{"reason":"warranted offline"}`)) + + assert.Equal(t, tt.wantStatus, w.Code) + }) + } + } +} + +// Requests the handler itself rejects never reach the service, so nothing is registered. +// A body over the handler's limit is refused before it reaches the service, so nothing is +// registered; one at the limit is read. +func TestRouter_HandleForcePark_LimitsBody(t *testing.T) { + // A blank reason, which the handler refuses after reading the body, so reaching that + // refusal shows the body was read in full. + body := `{"reason":" "}` + for _, route := range forceParkRoutes { + t.Run(route.name+"/over the limit", func(t *testing.T) { + client, _ := audit.NewWithCapture() + r := NewHandler(newTestService(nil), nil, client, int64(len(body))-1) + + w := httptest.NewRecorder() + route.handler(r)(w, newForceParkRequest(body)) + + assert.Equal(t, http.StatusRequestEntityTooLarge, w.Code) + assert.Contains(t, w.Body.String(), httputil.MsgBodyTooLarge) + }) + t.Run(route.name+"/at the limit", func(t *testing.T) { + client, _ := audit.NewWithCapture() + r := NewHandler(newTestService(nil), nil, client, int64(len(body))) + + w := httptest.NewRecorder() + route.handler(r)(w, newForceParkRequest(body)) + + assert.Equal(t, http.StatusBadRequest, w.Code) + assert.Contains(t, w.Body.String(), errReasonRequired) + }) + } +} + +func TestRouter_HandleForcePark_RejectsInvalidRequest(t *testing.T) { + tests := []struct { + name string + body string + stepID string + wantErr string + }{ + {"a missing reason", `{}`, resolveTestStepID, errReasonRequired}, + {"a blank reason", `{"reason":" "}`, resolveTestStepID, errReasonRequired}, + {"a body that is not JSON", `not json`, resolveTestStepID, httputil.MsgInvalidBody}, + {"anything after the JSON value", `{"reason":"a"}{"reason":"b"}`, resolveTestStepID, httputil.MsgInvalidBody}, + {"an unknown field", `{"reason":"a","action":"COMPLETE"}`, resolveTestStepID, `unknown field \"action\"`}, + {"a missing step", `{"reason":"a"}`, "", errStepIDRequired}, + } + for _, route := range forceParkRoutes { + for _, tt := range tests { + t.Run(route.name+"/"+tt.name, func(t *testing.T) { + client, _ := audit.NewWithCapture() + r := NewHandler(newTestService(nil), nil, client, testMaxRequestBytes) + req := newForceParkRequest(tt.body) + req.SetPathValue("stepId", tt.stepID) + + w := httptest.NewRecorder() + route.handler(r)(w, req) + + assert.Equal(t, http.StatusBadRequest, w.Code) + assert.Contains(t, w.Body.String(), tt.wantErr) + }) + } + } +} diff --git a/platform/workflowadmin/handler.go b/platform/workflowadmin/handler.go new file mode 100644 index 0000000..8c74922 --- /dev/null +++ b/platform/workflowadmin/handler.go @@ -0,0 +1,426 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (c) 2026 Lanka Software Foundation + +package workflowadmin + +import ( + "context" + "errors" + "log/slog" + "net/http" + "strings" + + "github.com/OpenNSW/core/httputil" + "github.com/OpenNSW/core/taskflow/store" + workflow "github.com/OpenNSW/core/workflow" + + "github.com/OpenNSW/core/platform/audit" + "github.com/OpenNSW/core/platform/authn" +) + +const ( + errUnauthorized = "unauthorized" + errWorkflowIDRequired = "workflow ID is required" + errWorkflowNotFound = "workflow execution not found" + errStepIDRequired = "step ID is required" + errInvalidAdminAction = "action must be one of RETRY, COMPLETE, ABORT" + errReasonRequired = "reason is required" + errCaseIDRequired = "case ID is required" + errCaseNotFound = "case not found" +) + +// validAdminActions maps the wire-format action string onto the core/workflow constant, and +// doubles as the allowlist HandleResolveAdminIntervention validates against. +var validAdminActions = map[string]workflow.AdminResolutionAction{ + string(workflow.AdminActionRetry): workflow.AdminActionRetry, + string(workflow.AdminActionComplete): workflow.AdminActionComplete, + string(workflow.AdminActionAbort): workflow.AdminActionAbort, +} + +// Handler serves the admin routes on svc and cases, auditing every read and override. +type Handler struct { + svc *Service + cases *CaseService + audit audit.Auditor + // maxRequestBytes caps a resolve or force-park request body. + maxRequestBytes int64 +} + +// NewHandler creates a Handler. A nil auditor records nothing. maxRequestBytes caps a +// resolve or force-park request body. +func NewHandler(svc *Service, cases *CaseService, auditor audit.Auditor, maxRequestBytes int64) *Handler { + return &Handler{svc: svc, cases: cases, audit: auditor, maxRequestBytes: maxRequestBytes} +} + +// HandleGetCase returns the case its {id} path value names: any case, with no ownership +// check, whichever service opened it, since every case shares the one ID space. +// Every task on it is listed whatever its read roles, and its flows by workflow ID, which +// an admin opens with HandleGetWorkflowEngineStatus. +// +// Gated at the route on the admin read scope, the same scope as the engine-status routes. +func (h *Handler) HandleGetCase(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + if _, ok := authn.FromContext(ctx); !ok { + httputil.Error(w, r, http.StatusUnauthorized, errUnauthorized) + return + } + id := r.PathValue("id") + if id == "" { + httputil.Error(w, r, http.StatusBadRequest, errCaseIDRequired) + return + } + + detail, err := h.cases.GetCaseDetail(ctx, id) + if err != nil { + if errors.Is(err, ErrCaseNotFound) { + httputil.Error(w, r, http.StatusNotFound, errCaseNotFound) + return + } + httputil.InternalServerError(w, r, "failed to retrieve case", err) + return + } + h.auditEvent(ctx, audit.ConsignmentEvent(audit.ActionRead, id, false, map[string]any{"view": "admin-case"})) + httputil.JSON(w, http.StatusOK, detail) +} + +// HandleGetWorkflowEngineStatus serves the engine status of the workflow its {id} path +// value names. {id} is a workflow ID: one of a case's flows (see the flows of the +// admin case view) or a child workflow of one (a node's child_workflow_ids). +// Returns that workflow's raw engine state (per-node status straight from the workflow +// manager, e.g. RUNNING/COMPLETED/AWAITING_ADMIN) — an ops/admin view distinct from the +// applicant- and officer-facing case views, which reflect task-store/business state instead. +// +// Gated at the route on the admin read scope, not on the scope applicants read their own +// cases with — this performs no per-case ownership +// check, so any caller holding the admin scope can view any workflow's engine state +// by design. +func (h *Handler) HandleGetWorkflowEngineStatus(w http.ResponseWriter, r *http.Request) { + h.handleEngineStatus(w, r, "engine-status", true, h.svc.GetEngineStatus) +} + +// HandleGetTaskWorkflowEngineStatus serves the engine status of the task workflow its {id} path +// value names. {id} is a task workflow's own workflow ID (see EngineNodeDTO.TaskWorkflowID, +// surfaced by HandleGetWorkflowEngineStatus on the TASK node that spawned it) — a separate ID +// space and workflow.Manager from the flow/child-workflow IDs HandleGetWorkflowEngineStatus +// queries. Gated at the route on the admin read scope. +func (h *Handler) HandleGetTaskWorkflowEngineStatus(w http.ResponseWriter, r *http.Request) { + h.handleEngineStatus(w, r, "task-workflow-engine-status", false, h.svc.GetTaskWorkflowEngineStatus) +} + +// handleEngineStatus is the common request/response handling shared by +// HandleGetWorkflowEngineStatus and HandleGetTaskWorkflowEngineStatus — they differ only in +// which Service method resolves {id} into an *EngineStatusDTO, the audit "view" label, and +// whether the target comes from the flow variables. +func (h *Handler) handleEngineStatus( + w http.ResponseWriter, r *http.Request, + view string, + flowAudit bool, + fetch func(ctx context.Context, id string) (*EngineStatusDTO, error), +) { + ctx := r.Context() + if _, ok := authn.FromContext(ctx); !ok { + httputil.Error(w, r, http.StatusUnauthorized, errUnauthorized) + return + } + id := r.PathValue("id") + if id == "" { + httputil.Error(w, r, http.StatusBadRequest, errWorkflowIDRequired) + return + } + + status, err := fetch(ctx, id) + if err != nil { + if errors.Is(err, ErrEngineWorkflowNotFound) { + httputil.Error(w, r, http.StatusNotFound, errWorkflowNotFound) + return + } + httputil.InternalServerError(w, r, "failed to retrieve "+view, err) + return + } + + event := audit.ConsignmentEvent(audit.ActionRead, id, false, map[string]any{"view": view}) + if flowAudit { + caseID, _ := status.GlobalVariables[workflow.VarCaseID].(string) + h.auditFlowEventWithCaseID(ctx, event, caseID) + } else { + h.auditTaskWorkflowEvent(ctx, event) + } + httputil.JSON(w, http.StatusOK, status) +} + +// ResolveAdminInterventionRequest is the request body for HandleResolveAdminIntervention. +// +// GlobalVariablesPatch is a patch, not the full variable set: dotted paths (e.g. +// "review.outcome") mapped to the values to write, applied before RETRY re-runs the node or +// COMPLETE marks it done. A map value is merged into an existing map at that path and any other +// value replaces it. Variables it doesn't name are untouched, and what it writes is +// workflow-wide, so it affects later nodes too. +type ResolveAdminInterventionRequest struct { + Action string `json:"action"` + GlobalVariablesPatch map[string]any `json:"global_variables_patch,omitempty"` + Reason string `json:"reason"` +} + +// HandleResolveAdminIntervention resolves the parked step its {id} and {stepId} path values +// name. {id} is the ID of the workflow instance containing the node: one of a case's flows or a +// child-branch workflow (a node's child_workflow_ids). {stepId} +// is the parked node's step_id from that workflow's engine status: it names that one parking, so a +// resolve sent after the node was resolved and parked again is rejected (409). A node inside a +// task workflow is resolved through HandleResolveTaskWorkflowAdminIntervention instead. +// +// Requires the admin write scope at the route: resolving can change workflow data +// (GlobalVariablesPatch) or force a path the interpreter didn't choose (Complete/Abort). +func (h *Handler) HandleResolveAdminIntervention(w http.ResponseWriter, r *http.Request) { + h.handleResolveAdminIntervention(w, r, "admin-resolve", h.svc.ResolveAdminIntervention, h.auditFlowEvent) +} + +// HandleResolveTaskWorkflowAdminIntervention resolves the parked task workflow step its {id} +// and {stepId} path values name. {id} is a task workflow's own workflow ID +// (a TASK node's task_workflow_id) — a separate ID space and workflow.Manager from the +// flow/child-workflow IDs HandleResolveAdminIntervention takes, the same split as the two +// engine-status routes. Otherwise identical, and gated on the same scope. +func (h *Handler) HandleResolveTaskWorkflowAdminIntervention(w http.ResponseWriter, r *http.Request) { + h.handleResolveAdminIntervention(w, r, "task-workflow-admin-resolve", h.svc.ResolveTaskWorkflowAdminIntervention, h.auditTaskWorkflowEvent) +} + +// handleResolveAdminIntervention is the request handling the two resolve routes share; they differ +// in which Service method resolves {id}, the audit "view" label, and the audit target resolver. +func (h *Handler) handleResolveAdminIntervention( + w http.ResponseWriter, r *http.Request, + view string, + resolve func(ctx context.Context, workflowID string, sig workflow.AdminResolutionSignal) (nodeID string, err error), + recordAudit func(context.Context, audit.Event), +) { + ctx := r.Context() + if _, ok := authn.FromContext(ctx); !ok { + httputil.Error(w, r, http.StatusUnauthorized, errUnauthorized) + return + } + workflowID := r.PathValue("id") + stepID := r.PathValue("stepId") + if workflowID == "" { + httputil.Error(w, r, http.StatusBadRequest, errWorkflowIDRequired) + return + } + if stepID == "" { + httputil.Error(w, r, http.StatusBadRequest, errStepIDRequired) + return + } + + var req ResolveAdminInterventionRequest + // DecodeJSON refuses unknown fields: a patch sent under a wrong key would otherwise be + // dropped while the action still succeeded. + if err := httputil.DecodeJSON(w, r, h.maxRequestBytes, &req); err != nil { + httputil.WriteDecodeError(w, r, err) + return + } + action, ok := validAdminActions[req.Action] + if !ok { + httputil.Error(w, r, http.StatusBadRequest, errInvalidAdminAction) + return + } + if strings.TrimSpace(req.Reason) == "" { + httputil.Error(w, r, http.StatusBadRequest, errReasonRequired) + return + } + + auditFail := func(errMsg string) { + recordAudit(ctx, audit.ConsignmentEvent(audit.ActionUpdate, workflowID, true, map[string]any{ + "view": view, + "stepId": stepID, + "action": req.Action, + "error": errMsg, + })) + } + + sig := workflow.AdminResolutionSignal{ + ActivationID: stepID, + Action: action, + WorkflowVariablesPatch: req.GlobalVariablesPatch, + Reason: req.Reason, + } + nodeID, err := resolve(ctx, workflowID, sig) + if err != nil { + switch { + case errors.Is(err, ErrEngineWorkflowNotFound): + auditFail(errWorkflowNotFound) + httputil.Error(w, r, http.StatusNotFound, errWorkflowNotFound) + case errors.Is(err, ErrNodeNotParked): + auditFail(err.Error()) + httputil.Error(w, r, http.StatusConflict, err.Error()) + case errors.Is(err, ErrAdminActionUnsupportedForGateway): + auditFail(err.Error()) + httputil.Error(w, r, http.StatusBadRequest, err.Error()) + default: + auditFail(err.Error()) + httputil.InternalServerError(w, r, "failed to resolve admin intervention", err) + } + return + } + + recordAudit(ctx, audit.ConsignmentEvent(audit.ActionUpdate, workflowID, false, map[string]any{ + "view": view, + "stepId": stepID, + "nodeId": nodeID, + "action": req.Action, + "reason": req.Reason, + })) + w.WriteHeader(http.StatusNoContent) +} + +// ForceParkRequest is the request body for HandleForceParkTaskNode. +type ForceParkRequest struct { + Reason string `json:"reason"` +} + +// HandleForceParkTaskNode force-parks the TASK node its {id} and {stepId} path values name. +// {id} is the workflow instance containing the node, one of a case's flows or a +// child-branch workflow, and {stepId} is the node's step_id from that workflow's engine status. The +// node must be a TASK waiting on its task; the task is closed and the node moved to AWAITING_ADMIN +// (see Service.ForceParkTaskNode), after which the resolve route applies. +// +// Requires the admin write scope, as resolve does: it takes a task away from the applicant or +// officer working on it. +func (h *Handler) HandleForceParkTaskNode(w http.ResponseWriter, r *http.Request) { + h.handleForcePark(w, r, "admin-force-park", h.svc.ForceParkTaskNode, h.auditFlowEvent) +} + +// HandleForceParkTaskWorkflowStep force-parks the task workflow step its {id} and {stepId} path +// values name. {id} is a task workflow's own workflow ID (a TASK node's task_workflow_id) and +// {stepId} is one of its steps. The step is moved to AWAITING_ADMIN and the task stays open +// (see Service.ForceParkTaskWorkflowStep); the task workflow's resolve route applies after. +// Gated on the same scope as HandleForceParkTaskNode. +func (h *Handler) HandleForceParkTaskWorkflowStep(w http.ResponseWriter, r *http.Request) { + h.handleForcePark(w, r, "task-workflow-admin-force-park", h.svc.ForceParkTaskWorkflowStep, h.auditTaskWorkflowEvent) +} + +// handleForcePark is the request handling the two force-park routes share; they differ only in +// which Service method parks the step, the audit "view" label, and the audit target resolver. +func (h *Handler) handleForcePark( + w http.ResponseWriter, r *http.Request, + view string, + forcePark func(ctx context.Context, workflowID, stepID, reason string) (nodeID string, err error), + recordAudit func(context.Context, audit.Event), +) { + ctx := r.Context() + if _, ok := authn.FromContext(ctx); !ok { + httputil.Error(w, r, http.StatusUnauthorized, errUnauthorized) + return + } + workflowID := r.PathValue("id") + stepID := r.PathValue("stepId") + if workflowID == "" { + httputil.Error(w, r, http.StatusBadRequest, errWorkflowIDRequired) + return + } + if stepID == "" { + httputil.Error(w, r, http.StatusBadRequest, errStepIDRequired) + return + } + + var req ForceParkRequest + if err := httputil.DecodeJSON(w, r, h.maxRequestBytes, &req); err != nil { + httputil.WriteDecodeError(w, r, err) + return + } + if strings.TrimSpace(req.Reason) == "" { + httputil.Error(w, r, http.StatusBadRequest, errReasonRequired) + return + } + + auditFail := func(errMsg string) { + recordAudit(ctx, audit.ConsignmentEvent(audit.ActionUpdate, workflowID, true, map[string]any{ + "view": view, + "stepId": stepID, + "error": errMsg, + })) + } + + nodeID, err := forcePark(ctx, workflowID, stepID, req.Reason) + if err != nil { + switch { + case errors.Is(err, ErrEngineWorkflowNotFound): + auditFail(errWorkflowNotFound) + httputil.Error(w, r, http.StatusNotFound, errWorkflowNotFound) + case errors.Is(err, ErrNodeNotWaiting): + auditFail(err.Error()) + httputil.Error(w, r, http.StatusConflict, ErrNodeNotWaiting.Error()) + case errors.Is(err, ErrForceParkUnsupportedNodeType): + auditFail(err.Error()) + httputil.Error(w, r, http.StatusBadRequest, err.Error()) + default: + auditFail(err.Error()) + httputil.InternalServerError(w, r, "failed to force-park node; please retry", err) + } + return + } + + recordAudit(ctx, audit.ConsignmentEvent(audit.ActionUpdate, workflowID, false, map[string]any{ + "view": view, + "stepId": stepID, + "nodeId": nodeID, + "reason": req.Reason, + })) + w.WriteHeader(http.StatusNoContent) +} + +// auditTaskWorkflowEvent resolves a task workflow's case from its persisted task record. +// Task-workflow variables do not reliably carry the case ID. A missing record leaves +// the target empty while retaining the workflow ID and the operation's original result. +func (h *Handler) auditTaskWorkflowEvent(ctx context.Context, e audit.Event) { + if h.audit == nil { + return + } + caseID := "" + if h.svc.taskStore != nil { + record, err := h.svc.taskStore.GetTaskByWorkflowID(ctx, e.TargetID) + switch { + case err == nil: + caseID = record.CaseID + case !errors.Is(err, store.ErrTaskNotFound): + slog.WarnContext(ctx, "workflowadmin: case unavailable for task workflow audit", "workflowId", e.TargetID, "error", err) + } + } + h.auditFlowEventWithCaseID(ctx, e, caseID) +} + +// auditFlowEvent resolves the case for a flow/child-workflow mutation audit. The extra +// status read is best-effort: the mutation's result must survive a lookup failure or a +// workflow that has already closed. Engine-status reads reuse their existing snapshot instead. +func (h *Handler) auditFlowEvent(ctx context.Context, e audit.Event) { + if h.audit == nil { + return + } + caseID := "" + if h.svc.wm != nil { + if instance, err := h.svc.wm.GetStatus(ctx, e.TargetID); err == nil && instance != nil { + caseID, _ = instance.WorkflowVariables[workflow.VarCaseID].(string) + } + } + h.auditFlowEventWithCaseID(ctx, e, caseID) +} + +// auditFlowEventWithCaseID keeps a flow or task-workflow address in metadata and targets the case. +// An unknown case stays empty rather than being mislabeled with a flow/child-workflow ID. +func (h *Handler) auditFlowEventWithCaseID(ctx context.Context, e audit.Event, caseID string) { + if h.audit == nil { + return + } + workflowID := e.TargetID + e.TargetID = caseID + if e.Metadata == nil { + e.Metadata = make(map[string]any) + } + e.Metadata["workflowId"] = workflowID + if caseID == "" { + e.Metadata["targetResolutionError"] = "the workflow's case could not be resolved" + slog.WarnContext(ctx, "workflow audit target could not be resolved", "workflowId", workflowID) + } + h.auditEvent(ctx, e) +} + +func (h *Handler) auditEvent(ctx context.Context, e audit.Event) { + if h.audit != nil { + h.audit.Audit(ctx, e) + } +} diff --git a/platform/workflowadmin/resolve_test.go b/platform/workflowadmin/resolve_test.go new file mode 100644 index 0000000..2e37151 --- /dev/null +++ b/platform/workflowadmin/resolve_test.go @@ -0,0 +1,309 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (c) 2026 Lanka Software Foundation + +package workflowadmin + +import ( + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/OpenNSW/core/httputil" + workflow "github.com/OpenNSW/core/workflow" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +const ( + resolveTestWorkflowID = "wf-1" + resolveTestNodeID = "officer_review" + // resolveTestStepID is the parked node's current step ID, which every request addresses. + resolveTestStepID = "step-1" + // testMaxRequestBytes is the resolve body limit the tests' handlers are built with. + testMaxRequestBytes = 1 << 20 +) + +// managerSlot registers a mock as one of the service's two workflow managers: the root one, for a +// case's flows and their child-branch workflows, or the task one, for task workflows. +type managerSlot func(svc *Service, m *MockWM) error + +var ( + rootManager managerSlot = func(svc *Service, m *MockWM) error { return svc.RegisterWorkflowManager(m) } + taskManager managerSlot = func(svc *Service, m *MockWM) error { return svc.RegisterTaskWorkflowManager(m) } +) + +// resolveRoute is one of the two resolve endpoints. They share all their request handling and +// differ only in which of the service's managers they use, so most tests below run against both. +type resolveRoute struct { + name string + own managerSlot // the manager this route must use + other managerSlot // the manager it must never touch + handler func(r *Handler) http.HandlerFunc +} + +var resolveRoutes = []resolveRoute{ + {"flow route", rootManager, taskManager, func(r *Handler) http.HandlerFunc { return r.HandleResolveAdminIntervention }}, + {"task workflow route", taskManager, rootManager, func(r *Handler) http.HandlerFunc { return r.HandleResolveTaskWorkflowAdminIntervention }}, +} + +// newResolveRequest builds a POST to a resolve endpoint as an authenticated admin, addressing +// resolveTestStepID on resolveTestWorkflowID. The handlers read their path values, not the +// URL, so the same request serves both routes. +func newResolveRequest(body string) *http.Request { + req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/workflows/"+resolveTestWorkflowID+"/steps/"+resolveTestStepID+"/resolve", strings.NewReader(body)) + req.SetPathValue("id", resolveTestWorkflowID) + req.SetPathValue("stepId", resolveTestStepID) + return req.WithContext(withAuthContext(req.Context(), "admin-1")) +} + +// newResolveRouter builds a Router whose service has mockWM registered as the manager route uses. +func newResolveRouter(t *testing.T, route resolveRoute, mockWM *MockWM) *Handler { + t.Helper() + svc := newTestService(nil) + require.NoError(t, route.own(svc, mockWM)) + return NewHandler(svc, nil, nil, testMaxRequestBytes) +} + +// parkedInstance is a workflow with one node of nodeType parked in AWAITING_ADMIN under +// resolveTestStepID, like a real engine status. +func parkedInstance(nodeType workflow.NodeType) *workflow.WorkflowInstance { + return &workflow.WorkflowInstance{ + ID: resolveTestWorkflowID, + Status: workflow.StatusRunning, + NodeInfo: map[string]*workflow.NodeInfo{ + resolveTestNodeID: {ID: resolveTestNodeID, ActivationID: resolveTestStepID, Type: nodeType, Status: workflow.NodeStatusAwaitingAdmin}, + }, + } +} + +// The request's fields must reach core's signal under core's names: the wire field +// global_variables_patch becomes WorkflowVariablesPatch, the path's step becomes ActivationID +// (core's routing key), and NodeID is the node found parked under it. A slip in this mapping would drop the admin's variables while still +// returning 204, so assert the whole signal rather than just that one was sent. +func TestHandler_HandleResolveAdminIntervention_ForwardsRequestToSignal(t *testing.T) { + for _, route := range resolveRoutes { + t.Run(route.name, func(t *testing.T) { + mockWM := new(MockWM) + r := newResolveRouter(t, route, mockWM) + mockWM.On("GetStatus", mock.Anything, resolveTestWorkflowID).Return(parkedInstance(workflow.NodeTypeTask), nil) + var got workflow.AdminResolutionSignal + mockWM.On("ResolveAdminIntervention", mock.Anything, resolveTestWorkflowID, "", mock.Anything). + Run(func(args mock.Arguments) { got = args.Get(3).(workflow.AdminResolutionSignal) }). + Return(nil) + + body := `{"action":"COMPLETE","global_variables_patch":{"review.outcome":"APPROVED"},"reason":"result was recorded under the wrong key"}` + w := httptest.NewRecorder() + route.handler(r)(w, newResolveRequest(body)) + + assert.Equal(t, http.StatusNoContent, w.Code) + assert.Equal(t, workflow.AdminResolutionSignal{ + NodeID: resolveTestNodeID, + ActivationID: resolveTestStepID, + Action: workflow.AdminActionComplete, + WorkflowVariablesPatch: map[string]any{"review.outcome": "APPROVED"}, + Reason: "result was recorded under the wrong key", + }, got) + mockWM.AssertExpectations(t) + }) + } +} + +// Each route resolves through its own manager and never the other's. Both are registered here, and +// only the route's own one has expectations, so a call to the other one fails the test. +func TestHandler_HandleResolveAdminIntervention_UsesOnlyItsOwnManager(t *testing.T) { + for _, route := range resolveRoutes { + t.Run(route.name, func(t *testing.T) { + ownWM, otherWM := new(MockWM), new(MockWM) + otherWM.Test(t) // an unexpected call fails this test cleanly instead of panicking + svc := newTestService(nil) + require.NoError(t, route.own(svc, ownWM)) + require.NoError(t, route.other(svc, otherWM)) + r := NewHandler(svc, nil, nil, testMaxRequestBytes) + ownWM.On("GetStatus", mock.Anything, resolveTestWorkflowID).Return(parkedInstance(workflow.NodeTypeTask), nil) + ownWM.On("ResolveAdminIntervention", mock.Anything, resolveTestWorkflowID, "", mock.Anything).Return(nil) + + w := httptest.NewRecorder() + route.handler(r)(w, newResolveRequest(`{"action":"RETRY","reason":"retry"}`)) + + assert.Equal(t, http.StatusNoContent, w.Code) + ownWM.AssertExpectations(t) + otherWM.AssertNotCalled(t, "GetStatus", mock.Anything, mock.Anything) + otherWM.AssertNotCalled(t, "ResolveAdminIntervention", mock.Anything, mock.Anything, mock.Anything, mock.Anything) + }) + } +} + +// A route whose own manager isn't registered fails, rather than quietly resolving through the +// other one: the two ID spaces are not interchangeable as far as the service is concerned. +func TestHandler_HandleResolveAdminIntervention_DoesNotFallBackToTheOtherManager(t *testing.T) { + for _, route := range resolveRoutes { + t.Run(route.name, func(t *testing.T) { + otherWM := new(MockWM) + otherWM.Test(t) // an unexpected call fails this test cleanly instead of panicking + svc := newTestService(nil) + require.NoError(t, route.other(svc, otherWM)) + r := NewHandler(svc, nil, nil, testMaxRequestBytes) + + w := httptest.NewRecorder() + route.handler(r)(w, newResolveRequest(`{"action":"RETRY","reason":"retry"}`)) + + assert.Equal(t, http.StatusInternalServerError, w.Code) + otherWM.AssertNotCalled(t, "GetStatus", mock.Anything, mock.Anything) + }) + } +} + +func TestHandler_HandleResolveAdminIntervention_MapsServiceErrors(t *testing.T) { + tests := []struct { + name string + body string + setup func(m *MockWM) + wantStatus int + }{ + { + name: "workflow not found is 404", + body: `{"action":"RETRY","reason":"retry"}`, + setup: func(m *MockWM) { + m.On("GetStatus", mock.Anything, resolveTestWorkflowID). + Return((*workflow.WorkflowInstance)(nil), fmt.Errorf("%w: gone", workflow.ErrWorkflowNotFound)) + }, + wantStatus: http.StatusNotFound, + }, + { + name: "node no longer parked is 409", + body: `{"action":"RETRY","reason":"retry"}`, + setup: func(m *MockWM) { + inst := parkedInstance(workflow.NodeTypeTask) + inst.NodeInfo["officer_review"].Status = workflow.NodeStatusRunning + m.On("GetStatus", mock.Anything, resolveTestWorkflowID).Return(inst, nil) + }, + wantStatus: http.StatusConflict, + }, + { + name: "stale step ID is 409", + body: `{"action":"RETRY","reason":"retry"}`, + setup: func(m *MockWM) { + // Resolved and parked again since the admin loaded the engine status. + inst := parkedInstance(workflow.NodeTypeTask) + inst.NodeInfo[resolveTestNodeID].ActivationID = "step-2" + m.On("GetStatus", mock.Anything, resolveTestWorkflowID).Return(inst, nil) + }, + wantStatus: http.StatusConflict, + }, + { + name: "COMPLETE on a gateway is 400", + body: `{"action":"COMPLETE","reason":"complete"}`, + setup: func(m *MockWM) { + m.On("GetStatus", mock.Anything, resolveTestWorkflowID).Return(parkedInstance(workflow.NodeTypeGateway), nil) + }, + wantStatus: http.StatusBadRequest, + }, + { + name: "signal failure is 500", + body: `{"action":"RETRY","reason":"retry"}`, + setup: func(m *MockWM) { + m.On("GetStatus", mock.Anything, resolveTestWorkflowID).Return(parkedInstance(workflow.NodeTypeTask), nil) + m.On("ResolveAdminIntervention", mock.Anything, resolveTestWorkflowID, "", mock.Anything).Return(errors.New("temporal unavailable")) + }, + wantStatus: http.StatusInternalServerError, + }, + } + for _, route := range resolveRoutes { + for _, tt := range tests { + t.Run(route.name+"/"+tt.name, func(t *testing.T) { + mockWM := new(MockWM) + r := newResolveRouter(t, route, mockWM) + tt.setup(mockWM) + + w := httptest.NewRecorder() + route.handler(r)(w, newResolveRequest(tt.body)) + + assert.Equal(t, tt.wantStatus, w.Code) + mockWM.AssertExpectations(t) + }) + } + } +} + +// Requests the handler itself rejects never reach the workflow manager, so none is registered. +func TestHandler_HandleResolveAdminIntervention_RejectsInvalidRequest(t *testing.T) { + tests := []struct { + name string + body string + wantErr string + }{ + {"a removed action", `{"action":"OVERRIDE","reason":"old client"}`, errInvalidAdminAction}, + {"an unknown action", `{"action":"EXPLODE","reason":"nope"}`, errInvalidAdminAction}, + {"a lower-case action", `{"action":"retry","reason":"nope"}`, errInvalidAdminAction}, + {"a missing reason", `{"action":"RETRY"}`, errReasonRequired}, + {"a blank reason", `{"action":"RETRY","reason":" "}`, errReasonRequired}, + {"a body that is not JSON", `not json`, httputil.MsgInvalidBody}, + {"an empty body", ``, httputil.MsgInvalidBody}, + {"anything after the JSON value", `{"action":"RETRY","reason":"first"}{"action":"ABORT","reason":"second"}`, httputil.MsgInvalidBody}, + // A patch sent under a field the endpoint doesn't define (here the pre-rename + // "overrides") must be rejected, not dropped while the action goes ahead with an empty patch. + {"an unknown field", `{"action":"COMPLETE","overrides":{"review.outcome":"APPROVED"},"reason":"stale client"}`, `unknown field \"overrides\"`}, + } + for _, route := range resolveRoutes { + for _, tt := range tests { + t.Run(route.name+"/"+tt.name, func(t *testing.T) { + r := NewHandler(newTestService(nil), nil, nil, testMaxRequestBytes) + + w := httptest.NewRecorder() + route.handler(r)(w, newResolveRequest(tt.body)) + + assert.Equal(t, http.StatusBadRequest, w.Code) + assert.Contains(t, w.Body.String(), tt.wantErr) + }) + } + } +} + +// A body over the handler's limit is refused before it reaches the workflow manager, so none is +// registered; one at the limit is read. +func TestHandler_HandleResolveAdminIntervention_LimitsBody(t *testing.T) { + // An action the handler refuses after reading the body, so reaching that refusal shows the + // body was read in full. + body := `{"action":"EXPLODE","reason":"nope"}` + for _, route := range resolveRoutes { + t.Run(route.name+"/over the limit", func(t *testing.T) { + r := NewHandler(newTestService(nil), nil, nil, int64(len(body))-1) + + w := httptest.NewRecorder() + route.handler(r)(w, newResolveRequest(body)) + + assert.Equal(t, http.StatusRequestEntityTooLarge, w.Code) + assert.Contains(t, w.Body.String(), httputil.MsgBodyTooLarge) + }) + t.Run(route.name+"/at the limit", func(t *testing.T) { + r := NewHandler(newTestService(nil), nil, nil, int64(len(body))) + + w := httptest.NewRecorder() + route.handler(r)(w, newResolveRequest(body)) + + assert.Equal(t, http.StatusBadRequest, w.Code) + assert.Contains(t, w.Body.String(), errInvalidAdminAction) + }) + } +} + +// A request without a step never reaches the workflow manager, so none is registered. +func TestHandler_HandleResolveAdminIntervention_RequiresStepID(t *testing.T) { + for _, route := range resolveRoutes { + t.Run(route.name, func(t *testing.T) { + r := NewHandler(newTestService(nil), nil, nil, testMaxRequestBytes) + req := newResolveRequest(`{"action":"RETRY","reason":"retry"}`) + req.SetPathValue("stepId", "") + + w := httptest.NewRecorder() + route.handler(r)(w, req) + + assert.Equal(t, http.StatusBadRequest, w.Code) + assert.Contains(t, w.Body.String(), errStepIDRequired) + }) + } +} diff --git a/platform/workflowadmin/service.go b/platform/workflowadmin/service.go new file mode 100644 index 0000000..756253a --- /dev/null +++ b/platform/workflowadmin/service.go @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (c) 2026 Lanka Software Foundation + +// Package workflowadmin is the ops/admin view of the workflows a deployment runs, whichever +// service started them: a workflow's raw engine state, and the admin's overrides of a node +// parked for them or forced to park (resolve, force-park). It addresses workflows by +// ID and checks no ownership of their case: its routes are gated on the admin scopes. +package workflowadmin + +import ( + "context" + + "github.com/OpenNSW/core/taskflow/store" + workflow "github.com/OpenNSW/core/workflow" +) + +// TaskStore is the narrow interface needed from the task store. GetTasks is passed only a +// CaseID, so every task of the case is listed whatever its read roles: this is an admin view. +// A non-nil error from GetTasks means the tasks could not be read, not that there are none. +type TaskStore interface { + GetTasks(ctx context.Context, filter store.TaskFilter) ([]store.TaskRecord, error) + GetTaskByWorkflowID(ctx context.Context, workflowID string) (store.TaskRecord, error) +} + +// TaskCanceller closes a task from outside its workflow. core's orchestrator.TaskManager implements +// it. +type TaskCanceller interface { + // CancelTask marks the task cancelled and terminates its workflow. It returns an error wrapping + // orchestrator.ErrTaskNotOpen if the task has completed or does not exist. + CancelTask(ctx context.Context, taskID, reason string) error +} + +// Service reads and overrides workflows through the deployment's two workflow managers. +type Service struct { + // wm is the flow (parent) workflow manager: a case's flows and their child workflows. + wm workflow.Manager + // taskWm is the workflow.Manager for the per-task ("micro") workflow runner — a separate + // manager/task queue from wm. + taskWm workflow.Manager + // tasks closes the task of a force-parked TASK node. + tasks TaskCanceller + // taskStore links a TASK node to its task workflow, and a task workflow to its case. + taskStore TaskStore +} + +// NewService creates a Service. A nil dependency only fails the operations that need it. +func NewService(wm, taskWm workflow.Manager, tasks TaskCanceller, taskStore TaskStore) *Service { + return &Service{wm: wm, taskWm: taskWm, tasks: tasks, taskStore: taskStore} +} diff --git a/platform/workflowadmin/task_workflow_audit_test.go b/platform/workflowadmin/task_workflow_audit_test.go new file mode 100644 index 0000000..2ef58ac --- /dev/null +++ b/platform/workflowadmin/task_workflow_audit_test.go @@ -0,0 +1,167 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (c) 2026 Lanka Software Foundation + +package workflowadmin + +import ( + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/OpenNSW/core/platform/audit" + "github.com/OpenNSW/core/taskflow/store" + workflow "github.com/OpenNSW/core/workflow" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +func TestTaskWorkflowEngineStatus_AuditTarget(t *testing.T) { + for _, tc := range []struct { + name string + record store.TaskRecord + err error + noStore bool + wantID string + }{ + {"stored case", store.TaskRecord{CaseID: "case-1", ParentWorkflowID: "nested-flow"}, nil, false, "case-1"}, + {"missing record", store.TaskRecord{}, store.ErrTaskNotFound, false, ""}, + {"failed read", store.TaskRecord{}, errors.New("db down"), false, ""}, + {"missing case", store.TaskRecord{ParentWorkflowID: "nested-flow"}, nil, false, ""}, + {"no store", store.TaskRecord{}, nil, true, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + const workflowID = "task-wf-review" + tasks := new(MockTaskStore) + var taskStore TaskStore = tasks + if tc.noStore { + taskStore = nil + } else { + tasks.On("GetTaskByWorkflowID", mock.Anything, workflowID).Return(tc.record, tc.err).Once() + } + svc := newTestService(taskStore) + wm := new(MockWM) + require.NoError(t, svc.RegisterTaskWorkflowManager(wm)) + // Task workflow globals can echo its own ID; they are not the audit target. + wm.On("GetStatus", mock.Anything, workflowID).Return(&workflow.WorkflowInstance{ + ID: workflowID, WorkflowVariables: map[string]any{workflow.VarCaseID: workflowID}, + }, nil).Once() + client, capture := audit.NewWithCapture() + router := NewHandler(svc, nil, client, testMaxRequestBytes) + req := httptest.NewRequest(http.MethodGet, "/", nil) + req.SetPathValue("id", workflowID) + req = req.WithContext(withAuthContext(req.Context(), "admin-1")) + w := httptest.NewRecorder() + router.HandleGetTaskWorkflowEngineStatus(w, req) + require.Equal(t, http.StatusOK, w.Code) + assert.Contains(t, w.Body.String(), workflowID) + records := capture.Records() + require.Len(t, records, 1) + assert.Equal(t, audit.TargetConsignment, records[0].TargetType) + assert.Equal(t, tc.wantID, records[0].TargetID) + assert.Equal(t, workflowID, records[0].Metadata["workflowId"]) + assert.Equal(t, "task-workflow-engine-status", records[0].Metadata["view"]) + assert.Equal(t, audit.StatusSuccess, records[0].Status) + if tc.wantID == "" { + assert.NotEmpty(t, records[0].Metadata["targetResolutionError"]) + } + tasks.AssertExpectations(t) + wm.AssertExpectations(t) + }) + } +} + +func TestTaskWorkflowActions_AuditTarget(t *testing.T) { + for _, forcePark := range []bool{false, true} { + for _, fail := range []bool{false, true} { + name := "resolve" + if forcePark { + name = "force-park" + } + if fail { + name += "/failure" + } else { + name += "/success" + } + t.Run(name, func(t *testing.T) { + const workflowID = "task-wf-review" + tasks := new(MockTaskStore) + tasks.On("GetTaskByWorkflowID", mock.Anything, workflowID).Return(store.TaskRecord{CaseID: "case-1"}, nil).Once() + svc := newTestService(tasks) + wm := new(MockWM) + require.NoError(t, svc.RegisterTaskWorkflowManager(wm)) + instance := parkedInstance(workflow.NodeTypeTask) + if forcePark { + instance.NodeInfo[resolveTestNodeID].Status = workflow.NodeStatusRunning + } + if fail { + instance.NodeInfo = nil + } + wm.On("GetStatus", mock.Anything, workflowID).Return(instance, nil).Once() + if !fail { + if forcePark { + wm.On("ForceParkActivation", mock.Anything, workflowID, "", resolveTestStepID, "repair").Return(nil).Once() + } else { + wm.On("ResolveAdminIntervention", mock.Anything, workflowID, "", mock.Anything).Return(nil).Once() + } + } + client, capture := audit.NewWithCapture() + router := NewHandler(svc, nil, client, testMaxRequestBytes) + body := `{"action":"RETRY","reason":"repair"}` + if forcePark { + body = `{"reason":"repair"}` + } + req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body)) + req.SetPathValue("id", workflowID) + req.SetPathValue("stepId", resolveTestStepID) + req = req.WithContext(withAuthContext(req.Context(), "admin-1")) + w := httptest.NewRecorder() + if forcePark { + router.HandleForceParkTaskWorkflowStep(w, req) + } else { + router.HandleResolveTaskWorkflowAdminIntervention(w, req) + } + wantCode, wantStatus := http.StatusNoContent, audit.StatusSuccess + if fail { + wantCode, wantStatus = http.StatusConflict, audit.StatusFailure + } + require.Equal(t, wantCode, w.Code) + records := capture.Records() + require.Len(t, records, 1) + assert.Equal(t, "case-1", records[0].TargetID) + assert.Equal(t, workflowID, records[0].Metadata["workflowId"]) + assert.Equal(t, resolveTestStepID, records[0].Metadata["stepId"]) + assert.Equal(t, wantStatus, records[0].Status) + tasks.AssertExpectations(t) + wm.AssertExpectations(t) + }) + } + } +} + +func TestWorkflowEngineStatus_AuditTargetUnchanged(t *testing.T) { + tasks := new(MockTaskStore) // A flow audit must not use the task-workflow lookup. + tasks.On("GetTasks", mock.Anything, store.TaskFilter{CaseID: "flow-1"}).Return([]store.TaskRecord(nil)).Once() + svc := newTestService(tasks) + wm := new(MockWM) + require.NoError(t, svc.RegisterWorkflowManager(wm)) + wm.On("GetStatus", mock.Anything, "flow-1").Return(&workflow.WorkflowInstance{ID: "flow-1", WorkflowVariables: map[string]any{workflow.VarCaseID: "flow-1"}}, nil).Once() + client, capture := audit.NewWithCapture() + router := NewHandler(svc, nil, client, testMaxRequestBytes) + req := httptest.NewRequest(http.MethodGet, "/", nil) + req.SetPathValue("id", "flow-1") + req = req.WithContext(withAuthContext(req.Context(), "admin-1")) + w := httptest.NewRecorder() + router.HandleGetWorkflowEngineStatus(w, req) + require.Equal(t, http.StatusOK, w.Code) + records := capture.Records() + require.Len(t, records, 1) + assert.Equal(t, "flow-1", records[0].TargetID) + assert.Equal(t, "engine-status", records[0].Metadata["view"]) + assert.Equal(t, "flow-1", records[0].Metadata["workflowId"]) + wm.AssertExpectations(t) + tasks.AssertExpectations(t) + tasks.AssertNotCalled(t, "GetTaskByWorkflowID", mock.Anything, mock.Anything) +} diff --git a/platform/workflowadmin/testutil_test.go b/platform/workflowadmin/testutil_test.go new file mode 100644 index 0000000..7c01b52 --- /dev/null +++ b/platform/workflowadmin/testutil_test.go @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (c) 2026 Lanka Software Foundation + +package workflowadmin + +import ( + "context" + + "github.com/stretchr/testify/mock" + + "github.com/OpenNSW/core/taskflow/store" + workflow "github.com/OpenNSW/core/workflow" + + "github.com/OpenNSW/core/platform/authn" +) + +// MockTaskStore implements workflowadmin.TaskStore for testing. +type MockTaskStore struct { + mock.Mock +} + +func (m *MockTaskStore) GetTaskByWorkflowID(ctx context.Context, workflowID string) (store.TaskRecord, error) { + args := m.Called(ctx, workflowID) + return args.Get(0).(store.TaskRecord), args.Error(1) +} + +// GetTasks returns the tasks the expectation was set up with, and its error when it was given one. +func (m *MockTaskStore) GetTasks(ctx context.Context, filter store.TaskFilter) ([]store.TaskRecord, error) { + args := m.Called(ctx, filter) + tasks, _ := args.Get(0).([]store.TaskRecord) + if len(args) > 1 { + return tasks, args.Error(1) + } + return tasks, nil +} + +// MockWM implements workflow.Manager for testing. +type MockWM struct { + mock.Mock +} + +func (m *MockWM) StartWorkflow(ctx context.Context, id string, workflowDefinition workflow.WorkflowDefinition, initialWorkflowVariables map[string]any) error { + args := m.Called(ctx, id, workflowDefinition, initialWorkflowVariables) + return args.Error(0) +} + +func (m *MockWM) CompleteActivation(ctx context.Context, workflowID, runID, activationID string, output map[string]any) error { + args := m.Called(ctx, workflowID, runID, activationID, output) + return args.Error(0) +} + +func (m *MockWM) TaskUpdate(ctx context.Context, workflowID, runID string, update workflow.UpdateEvent) error { + args := m.Called(ctx, workflowID, runID, update) + return args.Error(0) +} + +func (m *MockWM) GetStatus(ctx context.Context, workflowID string) (*workflow.WorkflowInstance, error) { + args := m.Called(ctx, workflowID) + if args.Get(0) == nil { + return nil, args.Error(1) + } + return args.Get(0).(*workflow.WorkflowInstance), args.Error(1) +} + +// ResolveAdminIntervention makes MockWM also satisfy workflow.AdminInterventionResolver — +// needed only by the ResolveAdminIntervention tests, which type-assert s.wm against it the same +// way the real Service.ResolveAdminIntervention does. +func (m *MockWM) ResolveAdminIntervention(ctx context.Context, workflowID, runID string, resolution workflow.AdminResolutionSignal) error { + args := m.Called(ctx, workflowID, runID, resolution) + return args.Error(0) +} + +// ForceParkActivation makes MockWM also satisfy workflow.ActivationParker, for the force-park tests. +func (m *MockWM) ForceParkActivation(ctx context.Context, workflowID, runID, activationID, reason string) error { + args := m.Called(ctx, workflowID, runID, activationID, reason) + return args.Error(0) +} + +// newTestService is a Service with only taskStore; a test sets the managers and task +// canceller it uses through the register helpers below. +func newTestService(taskStore TaskStore) *Service { + return &Service{taskStore: taskStore} +} + +// RegisterWorkflowManager sets the flow workflow manager, for a test. +func (s *Service) RegisterWorkflowManager(wm workflow.Manager) error { + s.wm = wm + return nil +} + +// RegisterTaskWorkflowManager sets the task workflow manager, for a test. +func (s *Service) RegisterTaskWorkflowManager(wm workflow.Manager) error { + s.taskWm = wm + return nil +} + +// RegisterTaskCanceller sets what closes a force-parked node's task, for a test. +func (s *Service) RegisterTaskCanceller(c TaskCanceller) error { + s.tasks = c + return nil +} + +func withAuthContext(ctx context.Context, userID string) context.Context { + return authn.ContextWithPrincipal(ctx, &authn.Principal{ + Kind: authn.KindUser, + UserID: userID, + Email: userID + "@example.com", + }) +} diff --git a/platform/workflowadmin/workflow_audit_test.go b/platform/workflowadmin/workflow_audit_test.go new file mode 100644 index 0000000..539aff0 --- /dev/null +++ b/platform/workflowadmin/workflow_audit_test.go @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright (c) 2026 Lanka Software Foundation + +package workflowadmin + +import ( + "errors" + "net/http" + "net/http/httptest" + "testing" + + "github.com/OpenNSW/core/platform/audit" + workflow "github.com/OpenNSW/core/workflow" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +func TestWorkflowEngineStatus_AuditCaseID(t *testing.T) { + for _, tc := range []struct { + name string + variables map[string]any + wantID string + }{ + {"auxiliary flow", map[string]any{workflow.VarCaseID: "case-1"}, "case-1"}, + {"missing case", nil, ""}, + {"invalid case", map[string]any{workflow.VarCaseID: 42}, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + svc := newTestService(nil) + wm := new(MockWM) + require.NoError(t, svc.RegisterWorkflowManager(wm)) + wm.On("GetStatus", mock.Anything, "auxiliary--child").Return(&workflow.WorkflowInstance{ + ID: "auxiliary--child", WorkflowVariables: tc.variables, + }, nil).Once() + client, capture := audit.NewWithCapture() + router := NewHandler(svc, nil, client, testMaxRequestBytes) + req := httptest.NewRequest(http.MethodGet, "/", nil) + req.SetPathValue("id", "auxiliary--child") + req = req.WithContext(withAuthContext(req.Context(), "admin-1")) + w := httptest.NewRecorder() + router.HandleGetWorkflowEngineStatus(w, req) + require.Equal(t, http.StatusOK, w.Code) + assert.Contains(t, w.Body.String(), `"workflow_id":"auxiliary--child"`) + records := capture.Records() + require.Len(t, records, 1) + assert.Equal(t, tc.wantID, records[0].TargetID) + assert.Equal(t, audit.TargetConsignment, records[0].TargetType) + assert.Equal(t, "auxiliary--child", records[0].Metadata["workflowId"]) + assert.Equal(t, "engine-status", records[0].Metadata["view"]) + assert.Equal(t, audit.StatusSuccess, records[0].Status) + if tc.wantID == "" { + assert.NotEmpty(t, records[0].Metadata["targetResolutionError"]) + } + wm.AssertExpectations(t) + }) + } +} + +func TestWorkflowActions_AuditCaseID(t *testing.T) { + for _, route := range []struct { + name string + handler func(*Handler) http.HandlerFunc + forcePark bool + }{ + {"resolve", func(r *Handler) http.HandlerFunc { return r.HandleResolveAdminIntervention }, false}, + {"force-park", func(r *Handler) http.HandlerFunc { return r.HandleForceParkTaskNode }, true}, + } { + for _, tc := range []struct { + name string + fail bool + lookupFails bool + }{ + {"success", false, false}, {"conflict", true, false}, {"lookup failure", false, true}, + } { + t.Run(route.name+"/"+tc.name, func(t *testing.T) { + svc := newTestService(nil) + wm := new(MockWM) + require.NoError(t, svc.RegisterWorkflowManager(wm)) + instance := parkedInstance(workflow.NodeTypeTask) + instance.WorkflowVariables = map[string]any{workflow.VarCaseID: "case-1"} + if route.forcePark { + instance.NodeInfo[resolveTestNodeID].Status = workflow.NodeStatusRunning + calls := []string{} + canceller := &fakeTaskCanceller{calls: &calls} + require.NoError(t, svc.RegisterTaskCanceller(canceller)) + + } + if tc.fail { + instance.NodeInfo = nil + } + wm.On("GetStatus", mock.Anything, resolveTestWorkflowID).Return(instance, nil).Once() + if tc.lookupFails { + wm.On("GetStatus", mock.Anything, resolveTestWorkflowID).Return((*workflow.WorkflowInstance)(nil), errors.New("temporal unavailable")).Once() + } else { + wm.On("GetStatus", mock.Anything, resolveTestWorkflowID).Return(instance, nil).Once() + } + if !tc.fail { + if route.forcePark { + wm.On("ForceParkActivation", mock.Anything, resolveTestWorkflowID, "", resolveTestStepID, "repair").Return(nil).Once() + } else { + wm.On("ResolveAdminIntervention", mock.Anything, resolveTestWorkflowID, "", mock.Anything).Return(nil).Once() + } + } + client, capture := audit.NewWithCapture() + router := NewHandler(svc, nil, client, testMaxRequestBytes) + body := `{"action":"RETRY","reason":"repair"}` + if route.forcePark { + body = `{"reason":"repair"}` + } + req := newResolveRequest(body) + w := httptest.NewRecorder() + route.handler(router)(w, req) + wantCode, wantStatus := http.StatusNoContent, audit.StatusSuccess + if tc.fail { + wantCode, wantStatus = http.StatusConflict, audit.StatusFailure + } + require.Equal(t, wantCode, w.Code) + records := capture.Records() + require.Len(t, records, 1) + wantID := "case-1" + if tc.lookupFails { + wantID = "" + assert.NotEmpty(t, records[0].Metadata["targetResolutionError"]) + } + assert.Equal(t, wantID, records[0].TargetID) + assert.Equal(t, resolveTestWorkflowID, records[0].Metadata["workflowId"]) + assert.Equal(t, resolveTestStepID, records[0].Metadata["stepId"]) + assert.Equal(t, wantStatus, records[0].Status) + wm.AssertExpectations(t) + }) + } + } +} + +func TestTaskWorkflowEngineStatus_DoesNotUseFlowAuditLookup(t *testing.T) { + svc := newTestService(nil) + rootWM, taskWM := new(MockWM), new(MockWM) + require.NoError(t, svc.RegisterWorkflowManager(rootWM)) + require.NoError(t, svc.RegisterTaskWorkflowManager(taskWM)) + taskWM.On("GetStatus", mock.Anything, "task-wf-1").Return(&workflow.WorkflowInstance{ID: "task-wf-1"}, nil).Once() + client, capture := audit.NewWithCapture() + router := NewHandler(svc, nil, client, testMaxRequestBytes) + req := httptest.NewRequest(http.MethodGet, "/", nil) + req.SetPathValue("id", "task-wf-1") + req = req.WithContext(withAuthContext(req.Context(), "admin-1")) + w := httptest.NewRecorder() + router.HandleGetTaskWorkflowEngineStatus(w, req) + require.Equal(t, http.StatusOK, w.Code) + records := capture.Records() + require.Len(t, records, 1) + assert.Equal(t, audit.TargetConsignment, records[0].TargetType) + assert.Equal(t, "task-workflow-engine-status", records[0].Metadata["view"]) + rootWM.AssertNotCalled(t, "GetStatus", mock.Anything, mock.Anything) + taskWM.AssertExpectations(t) +}