Skip to content
Merged
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
3 changes: 3 additions & 0 deletions apps/csm-portal/backend/cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ func main() {
productVulnerabilityHandler := handler.NewProductVulnerabilityHandler(entityClient)
conversationHandler := handler.NewConversationHandler(entityClient)
taskSlaHandler := handler.NewTaskSlaHandler(entityClient)
taskHandler := handler.NewTaskHandler(entityClient)
incidentHandler := handler.NewIncidentHandler(entityClient)
problemHandler := handler.NewProblemHandler(entityClient)

Expand Down Expand Up @@ -153,6 +154,8 @@ func main() {
mux.HandleFunc("POST /conversations/search", conversationHandler.SearchConversations)
mux.HandleFunc("POST /slas/search", taskSlaHandler.SearchTaskSlas)
mux.HandleFunc("GET /slas/{id}", taskSlaHandler.GetTaskSla)
mux.HandleFunc("POST /cases/{caseId}/tasks/search", taskHandler.SearchCaseTasks)
mux.HandleFunc("GET /tasks/{id}", taskHandler.GetTask)
mux.HandleFunc("POST /incidents/search", incidentHandler.SearchIncidents)
mux.HandleFunc("POST /incidents", incidentHandler.CreateIncident)
mux.HandleFunc("GET /incidents/{id}", incidentHandler.GetIncident)
Expand Down
12 changes: 12 additions & 0 deletions apps/csm-portal/backend/internal/entity/entity.go
Original file line number Diff line number Diff line change
Expand Up @@ -372,3 +372,15 @@ func (c *Client) SearchTaskSlas(ctx context.Context, body []byte) ([]byte, error
func (c *Client) GetTaskSla(ctx context.Context, id string) ([]byte, error) {
return c.do(ctx, http.MethodGet, fmt.Sprintf("/slas/%s", url.PathEscape(id)), nil)
}

// SearchCaseTasks calls POST /cases/{caseId}/tasks/search on the entity service.
// Response is returned as raw JSON; typed response structs are deferred.
func (c *Client) SearchCaseTasks(ctx context.Context, caseID string, body []byte) ([]byte, error) {
return c.do(ctx, http.MethodPost, fmt.Sprintf("/cases/%s/tasks/search", url.PathEscape(caseID)), body)
}

// GetTask calls GET /tasks/{id} on the entity service.
// Response is returned as raw JSON; typed response structs are deferred.
func (c *Client) GetTask(ctx context.Context, id string) ([]byte, error) {
return c.do(ctx, http.MethodGet, fmt.Sprintf("/tasks/%s", url.PathEscape(id)), nil)
}
21 changes: 21 additions & 0 deletions apps/csm-portal/backend/internal/handler/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -635,3 +635,24 @@ func (m *mockEntityTaskSlaClient) GetTaskSla(ctx context.Context, id string) ([]
}
return []byte(`{"id":"11111111-1111-1111-1111-111111111111"}`), nil
}

// ----- mock entity task client -----

type mockEntityTaskClient struct {
searchCaseTasksFn func(ctx context.Context, caseID string, body []byte) ([]byte, error)
getTaskFn func(ctx context.Context, id string) ([]byte, error)
}

func (m *mockEntityTaskClient) SearchCaseTasks(ctx context.Context, caseID string, body []byte) ([]byte, error) {
if m.searchCaseTasksFn != nil {
return m.searchCaseTasksFn(ctx, caseID, body)
}
return []byte(`{"tasks":[],"total":0,"limit":20,"offset":0}`), nil
}

func (m *mockEntityTaskClient) GetTask(ctx context.Context, id string) ([]byte, error) {
if m.getTaskFn != nil {
return m.getTaskFn(ctx, id)
}
return []byte(`{"id":"11111111-1111-1111-1111-111111111111"}`), nil
}
109 changes: 109 additions & 0 deletions apps/csm-portal/backend/internal/handler/tasks.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// Copyright (c) 2026 WSO2 LLC. (https://www.wso2.com).
//
// WSO2 LLC. licenses this file to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file except
// in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

package handler

import (
"context"
"encoding/json"
"io"
"log/slog"
"net/http"

"github.com/wso2-open-operations/cs-tools/apps/csm-portal/backend/internal/middleware"
)

// entityTaskClient abstracts the entity service task operations.
type entityTaskClient interface {
SearchCaseTasks(ctx context.Context, caseID string, body []byte) ([]byte, error)
GetTask(ctx context.Context, id string) ([]byte, error)
}

// TaskHandler handles HTTP requests for task operations.
type TaskHandler struct {
entity entityTaskClient
}

// NewTaskHandler creates a TaskHandler backed by the given entity client.
func NewTaskHandler(entity entityTaskClient) *TaskHandler {
return &TaskHandler{entity: entity}
}

// SearchCaseTasks handles POST /cases/{caseId}/tasks/search.
// The endpoint is path-scoped, so the request body (e.g. {"pagination":{"limit":...,"offset":...}})
// is capped and forwarded to the entity service as-is, and the response is returned verbatim.
func (h *TaskHandler) SearchCaseTasks(w http.ResponseWriter, r *http.Request) {
user := middleware.UserInfoFromContext(r.Context())
if user == nil {
writeError(w, http.StatusUnauthorized, ErrMsgUnauthorized)
return
}

caseID := r.PathValue("caseId")
if caseID == "" || !uuidRe.MatchString(caseID) {
writeError(w, http.StatusBadRequest, ErrMsgInvalidUUID)
return
}

r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes)
body, err := io.ReadAll(r.Body)
if err != nil {
if _, ok := err.(*http.MaxBytesError); ok {
writeError(w, http.StatusRequestEntityTooLarge, ErrMsgTooLarge)
return
}
writeError(w, http.StatusBadRequest, errMsgReadBody)
return
}

if len(body) > 0 && !json.Valid(body) {
writeError(w, http.StatusBadRequest, ErrMsgBadRequest)
return
}

result, err := h.entity.SearchCaseTasks(r.Context(), caseID, body)
if err != nil {
slog.ErrorContext(r.Context(), "entity SearchCaseTasks failed", "userID", user.UserID, "caseID", caseID, "err", err)
mapUpstreamError(w, err, "Failed to retrieve case tasks.")
return
}

writeJSON(w, http.StatusOK, result)
}

// GetTask handles GET /tasks/{id}.
func (h *TaskHandler) GetTask(w http.ResponseWriter, r *http.Request) {
user := middleware.UserInfoFromContext(r.Context())
if user == nil {
writeError(w, http.StatusUnauthorized, ErrMsgUnauthorized)
return
}

id := r.PathValue("id")
if id == "" || !uuidRe.MatchString(id) {
writeError(w, http.StatusBadRequest, ErrMsgInvalidUUID)
return
}

result, err := h.entity.GetTask(r.Context(), id)
if err != nil {
slog.ErrorContext(r.Context(), "entity GetTask failed", "userID", user.UserID, "id", id, "err", err)
mapUpstreamError(w, err, "Failed to retrieve task.")
return
}

writeJSON(w, http.StatusOK, result)
}
218 changes: 218 additions & 0 deletions apps/csm-portal/backend/internal/handler/tasks_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
// Copyright (c) 2026 WSO2 LLC. (https://www.wso2.com).
//
// WSO2 LLC. licenses this file to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file except
// in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

package handler

import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
)

const testTaskCaseID = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
const testTaskID = "11111111-1111-1111-1111-111111111111"

func TestSearchCaseTasks(t *testing.T) {
t.Run("requires authenticated user", func(t *testing.T) {
h := NewTaskHandler(&mockEntityTaskClient{})
r := httptest.NewRequest(http.MethodPost, "/cases/"+testTaskCaseID+"/tasks/search", strings.NewReader(`{}`))
r.SetPathValue("caseId", testTaskCaseID)
w := httptest.NewRecorder()
h.SearchCaseTasks(w, r)
assertStatus(t, w, http.StatusUnauthorized)
assertErrorMessage(t, w, ErrMsgUnauthorized)
assertContentType(t, w, "application/json")
})

t.Run("rejects malformed case UUID", func(t *testing.T) {
h := NewTaskHandler(&mockEntityTaskClient{})
r := withUser(httptest.NewRequest(http.MethodPost, "/cases/not-a-uuid/tasks/search", strings.NewReader(`{}`)))
r.SetPathValue("caseId", "not-a-uuid")
w := httptest.NewRecorder()
h.SearchCaseTasks(w, r)
assertStatus(t, w, http.StatusBadRequest)
assertErrorMessage(t, w, ErrMsgInvalidUUID)
assertContentType(t, w, "application/json")
})

t.Run("rejects empty case id", func(t *testing.T) {
h := NewTaskHandler(&mockEntityTaskClient{})
r := withUser(httptest.NewRequest(http.MethodPost, "/cases//tasks/search", strings.NewReader(`{}`)))
w := httptest.NewRecorder()
h.SearchCaseTasks(w, r)
assertStatus(t, w, http.StatusBadRequest)
assertErrorMessage(t, w, ErrMsgInvalidUUID)
assertContentType(t, w, "application/json")
})

t.Run("rejects body exceeding 1 MiB", func(t *testing.T) {
h := NewTaskHandler(&mockEntityTaskClient{})
r := withUser(httptest.NewRequest(http.MethodPost, "/cases/"+testTaskCaseID+"/tasks/search", strings.NewReader(strings.Repeat("x", maxRequestBodyBytes+1))))
r.SetPathValue("caseId", testTaskCaseID)
w := httptest.NewRecorder()
h.SearchCaseTasks(w, r)
assertStatus(t, w, http.StatusRequestEntityTooLarge)
assertErrorMessage(t, w, ErrMsgTooLarge)
assertContentType(t, w, "application/json")
})

t.Run("rejects invalid JSON body", func(t *testing.T) {
h := NewTaskHandler(&mockEntityTaskClient{})
r := withUser(httptest.NewRequest(http.MethodPost, "/cases/"+testTaskCaseID+"/tasks/search", strings.NewReader(`not-json`)))
r.SetPathValue("caseId", testTaskCaseID)
w := httptest.NewRecorder()
h.SearchCaseTasks(w, r)
assertStatus(t, w, http.StatusBadRequest)
assertErrorMessage(t, w, ErrMsgBadRequest)
assertContentType(t, w, "application/json")
})

t.Run("forwards case id and body verbatim to upstream", func(t *testing.T) {
var capturedCaseID string
var capturedBody []byte
reqBody := `{"pagination":{"limit":20,"offset":0}}`
client := &mockEntityTaskClient{
searchCaseTasksFn: func(_ context.Context, caseID string, body []byte) ([]byte, error) {
capturedCaseID = caseID
capturedBody = body
return []byte(`{"tasks":[{"id":"` + testTaskID + `"}],"total":1,"limit":20,"offset":0}`), nil
},
}
h := NewTaskHandler(client)
r := withUser(httptest.NewRequest(http.MethodPost, "/cases/"+testTaskCaseID+"/tasks/search", strings.NewReader(reqBody)))
r.SetPathValue("caseId", testTaskCaseID)
w := httptest.NewRecorder()
h.SearchCaseTasks(w, r)

assertStatus(t, w, http.StatusOK)
assertContentType(t, w, "application/json")

if capturedCaseID != testTaskCaseID {
t.Errorf("upstream received caseID %q, want %q", capturedCaseID, testTaskCaseID)
}
if string(capturedBody) != reqBody {
t.Errorf("upstream body = %q, want verbatim %q", string(capturedBody), reqBody)
}
resp := decodeJSON[map[string]any](t, w)
if resp["total"] != float64(1) {
t.Errorf("total = %v, want 1", resp["total"])
}
})

t.Run("upstream errors are mapped correctly", func(t *testing.T) {
for _, tc := range upstreamErrors("Failed to retrieve case tasks.") {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
client := &mockEntityTaskClient{
searchCaseTasksFn: func(_ context.Context, _ string, _ []byte) ([]byte, error) {
return nil, tc.err
},
}
h := NewTaskHandler(client)
r := withUser(httptest.NewRequest(http.MethodPost, "/cases/"+testTaskCaseID+"/tasks/search", strings.NewReader(`{}`)))
r.SetPathValue("caseId", testTaskCaseID)
w := httptest.NewRecorder()
h.SearchCaseTasks(w, r)
assertStatus(t, w, tc.wantCode)
assertErrorMessage(t, w, tc.wantMsg)
assertContentType(t, w, "application/json")
})
}
})
}

func TestGetTask(t *testing.T) {
t.Run("requires authenticated user", func(t *testing.T) {
h := NewTaskHandler(&mockEntityTaskClient{})
r := httptest.NewRequest(http.MethodGet, "/tasks/"+testTaskID, nil)
r.SetPathValue("id", testTaskID)
w := httptest.NewRecorder()
h.GetTask(w, r)
assertStatus(t, w, http.StatusUnauthorized)
assertErrorMessage(t, w, ErrMsgUnauthorized)
assertContentType(t, w, "application/json")
})

t.Run("rejects malformed UUID", func(t *testing.T) {
h := NewTaskHandler(&mockEntityTaskClient{})
r := withUser(httptest.NewRequest(http.MethodGet, "/tasks/not-a-uuid", nil))
r.SetPathValue("id", "not-a-uuid")
w := httptest.NewRecorder()
h.GetTask(w, r)
assertStatus(t, w, http.StatusBadRequest)
assertErrorMessage(t, w, ErrMsgInvalidUUID)
assertContentType(t, w, "application/json")
})

t.Run("rejects empty id", func(t *testing.T) {
h := NewTaskHandler(&mockEntityTaskClient{})
r := withUser(httptest.NewRequest(http.MethodGet, "/tasks/", nil))
w := httptest.NewRecorder()
h.GetTask(w, r)
assertStatus(t, w, http.StatusBadRequest)
assertErrorMessage(t, w, ErrMsgInvalidUUID)
assertContentType(t, w, "application/json")
})

t.Run("forwards id to upstream and returns 200", func(t *testing.T) {
var capturedID string
client := &mockEntityTaskClient{
getTaskFn: func(_ context.Context, id string) ([]byte, error) {
capturedID = id
return []byte(`{"id":"` + testTaskID + `","subject":"Investigate outage","state":"in_progress"}`), nil
},
}
h := NewTaskHandler(client)
r := withUser(httptest.NewRequest(http.MethodGet, "/tasks/"+testTaskID, nil))
r.SetPathValue("id", testTaskID)
w := httptest.NewRecorder()
h.GetTask(w, r)

assertStatus(t, w, http.StatusOK)
assertContentType(t, w, "application/json")

if capturedID != testTaskID {
t.Errorf("upstream received id %q, want %q", capturedID, testTaskID)
}
resp := decodeJSON[map[string]any](t, w)
if resp["subject"] != "Investigate outage" {
t.Errorf("response subject = %v, want %q", resp["subject"], "Investigate outage")
}
})

t.Run("upstream errors are mapped correctly", func(t *testing.T) {
for _, tc := range upstreamErrors("Failed to retrieve task.") {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
client := &mockEntityTaskClient{
getTaskFn: func(_ context.Context, _ string) ([]byte, error) {
return nil, tc.err
},
}
h := NewTaskHandler(client)
r := withUser(httptest.NewRequest(http.MethodGet, "/tasks/"+testTaskID, nil))
r.SetPathValue("id", testTaskID)
w := httptest.NewRecorder()
h.GetTask(w, r)
assertStatus(t, w, tc.wantCode)
assertErrorMessage(t, w, tc.wantMsg)
assertContentType(t, w, "application/json")
})
}
})
}
Loading