Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions platform/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
35 changes: 35 additions & 0 deletions platform/agency/artifacts_test.go
Original file line number Diff line number Diff line change
@@ -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
}
221 changes: 221 additions & 0 deletions platform/agency/cases.go
Original file line number Diff line number Diff line change
@@ -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{},
}
}
Loading
Loading