Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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: 1 addition & 1 deletion apps/csm-portal/backend/cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ func main() {
mux.HandleFunc("PATCH /cases/{id}", caseHandler.PatchCase)
mux.HandleFunc("POST /cases/{id}/comments", caseHandler.CreateCaseComment)
mux.HandleFunc("POST /cases/{id}/comments/search", caseHandler.SearchCaseComments)
mux.HandleFunc("POST /projects/{id}/cases/search", caseHandler.SearchProjectCases)
mux.HandleFunc("POST /cases/search", caseHandler.SearchCases)
mux.HandleFunc("GET /updates/product-update-levels", updatesHandler.GetProductUpdateLevels)
mux.HandleFunc("POST /updates/levels/search", updatesHandler.SearchUpdatesBetweenUpdateLevels)
mux.HandleFunc("GET /users/me", usersHandler.GetMe)
Expand Down
39 changes: 5 additions & 34 deletions apps/csm-portal/backend/internal/handler/cases.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,23 +79,6 @@ func injectCreatedBy(body []byte, userID string) ([]byte, error) {
return json.Marshal(m)
}

// injectProjectID merges a project ID into a JSON request body as projectIds: [id].
func injectProjectID(body []byte, projectID string) ([]byte, error) {
var m map[string]json.RawMessage
if err := json.Unmarshal(body, &m); err != nil {
return nil, err
}
if m == nil {
m = make(map[string]json.RawMessage)
}
ids, err := json.Marshal([]string{projectID})
if err != nil {
return nil, err
}
m["projectIds"] = ids
return json.Marshal(m)
}

// entityCaseClient abstracts the entity service operations used by CaseHandler,
// allowing the handler to be tested independently of the real HTTP client.
type entityCaseClient interface {
Expand Down Expand Up @@ -282,21 +265,15 @@ func (h *CaseHandler) SearchCaseComments(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusOK, result)
}

// SearchProjectCases handles POST /projects/{id}/cases/search.
// It enforces the project scope by injecting projectIds: [id] into the entity request.
func (h *CaseHandler) SearchProjectCases(w http.ResponseWriter, r *http.Request) {
// SearchCases handles POST /cases/search.
// Project IDs and other filters are accepted directly in the request body.
func (h *CaseHandler) SearchCases(w http.ResponseWriter, r *http.Request) {
user := middleware.UserInfoFromContext(r.Context())
if user == nil {
writeError(w, http.StatusUnauthorized, ErrMsgUnauthorized)
return
}

projectID := r.PathValue("id")
if projectID == "" {
writeError(w, http.StatusBadRequest, ErrMsgBadRequest)
return
}

r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes)
body, err := io.ReadAll(r.Body)
if err != nil {
Expand All @@ -313,15 +290,9 @@ func (h *CaseHandler) SearchProjectCases(w http.ResponseWriter, r *http.Request)
return
}

entityBody, err := injectProjectID(body, projectID)
if err != nil {
writeError(w, http.StatusBadRequest, ErrMsgBadRequest)
return
}

result, err := h.entity.SearchCases(r.Context(), entityBody)
result, err := h.entity.SearchCases(r.Context(), body)
if err != nil {
slog.ErrorContext(r.Context(), "entity SearchCases failed", "userID", user.UserID, "projectID", projectID, "err", err)
slog.ErrorContext(r.Context(), "entity SearchCases failed", "userID", user.UserID, "err", err)
mapUpstreamError(w, err, "Failed to search cases.")
return
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
Expand Down
76 changes: 23 additions & 53 deletions apps/csm-portal/backend/internal/handler/cases_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -439,77 +439,52 @@ func TestSearchCaseComments(t *testing.T) {
})
}

// ----- SearchProjectCases -----
// ----- SearchCases -----

func TestSearchProjectCases(t *testing.T) {
func TestSearchCases(t *testing.T) {
t.Run("requires authenticated user", func(t *testing.T) {
h := NewCaseHandler(&mockEntityCaseClient{})
r := httptest.NewRequest(http.MethodPost, "/projects/proj-1/cases/search", strings.NewReader(`{}`))
r.SetPathValue("id", "proj-1")
r := httptest.NewRequest(http.MethodPost, "/cases/search", strings.NewReader(`{}`))
w := httptest.NewRecorder()
h.SearchProjectCases(w, r)
h.SearchCases(w, r)
assertStatus(t, w, http.StatusUnauthorized)
assertErrorMessage(t, w, ErrMsgUnauthorized)
assertContentType(t, w, "application/json")
})

t.Run("rejects missing project id", func(t *testing.T) {
h := NewCaseHandler(&mockEntityCaseClient{})
r := withUser(httptest.NewRequest(http.MethodPost, "/projects//cases/search", strings.NewReader(`{}`)))
w := httptest.NewRecorder()
h.SearchProjectCases(w, r)
assertStatus(t, w, http.StatusBadRequest)
assertErrorMessage(t, w, ErrMsgBadRequest)
assertContentType(t, w, "application/json")
})

t.Run("rejects body exceeding 1 MiB", func(t *testing.T) {
h := NewCaseHandler(&mockEntityCaseClient{})
r := withUser(httptest.NewRequest(http.MethodPost, "/projects/proj-1/cases/search", strings.NewReader(strings.Repeat("x", maxRequestBodyBytes+1))))
r.SetPathValue("id", "proj-1")
r := withUser(httptest.NewRequest(http.MethodPost, "/cases/search", strings.NewReader(strings.Repeat("x", maxRequestBodyBytes+1))))
w := httptest.NewRecorder()
h.SearchProjectCases(w, r)
h.SearchCases(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 := NewCaseHandler(&mockEntityCaseClient{})
r := withUser(httptest.NewRequest(http.MethodPost, "/projects/proj-1/cases/search", strings.NewReader(`not-json`)))
r.SetPathValue("id", "proj-1")
r := withUser(httptest.NewRequest(http.MethodPost, "/cases/search", strings.NewReader(`not-json`)))
w := httptest.NewRecorder()
h.SearchProjectCases(w, r)
h.SearchCases(w, r)
assertStatus(t, w, http.StatusBadRequest)
assertErrorMessage(t, w, ErrMsgBadRequest)
assertContentType(t, w, "application/json")
})

t.Run("handles JSON null body as empty object without panic", func(t *testing.T) {
h := NewCaseHandler(&mockEntityCaseClient{})
r := withUser(httptest.NewRequest(http.MethodPost, "/projects/proj-1/cases/search", strings.NewReader(`null`)))
r.SetPathValue("id", "proj-1")
w := httptest.NewRecorder()
h.SearchProjectCases(w, r)
assertStatus(t, w, http.StatusOK)
assertContentType(t, w, "application/json")
})

t.Run("injects projectId from path and forwards to upstream", func(t *testing.T) {
const projectID = "proj-42"
t.Run("forwards body to upstream and returns 200", func(t *testing.T) {
var capturedBody []byte
client := &mockEntityCaseClient{
searchCasesFn: func(_ context.Context, body []byte) ([]byte, error) {
capturedBody = body
return []byte(`{"cases":[{"id":"case-1","projectId":"proj-42"}],"total":1}`), nil
return []byte(`{"cases":[{"id":"case-1"}],"total":1}`), nil
},
}
h := NewCaseHandler(client)
r := withUser(httptest.NewRequest(http.MethodPost, "/projects/proj-42/cases/search",
strings.NewReader(`{"pagination":{"limit":10,"offset":0},"stateKeys":["open"]}`)))
r.SetPathValue("id", projectID)
r := withUser(httptest.NewRequest(http.MethodPost, "/cases/search",
strings.NewReader(`{"projectIds":["proj-1"],"stateKeys":["open"],"pagination":{"limit":10,"offset":0}}`)))
w := httptest.NewRecorder()
h.SearchProjectCases(w, r)
h.SearchCases(w, r)

assertStatus(t, w, http.StatusOK)
assertContentType(t, w, "application/json")
Expand All @@ -519,8 +494,8 @@ func TestSearchProjectCases(t *testing.T) {
t.Fatalf("upstream received invalid JSON: %v", err)
}
var ids []string
if err := json.Unmarshal(sent["projectIds"], &ids); err != nil || len(ids) != 1 || ids[0] != projectID {
t.Errorf("upstream projectIds = %v, want [%q]", ids, projectID)
if err := json.Unmarshal(sent["projectIds"], &ids); err != nil || len(ids) != 1 || ids[0] != "proj-1" {
t.Errorf("upstream projectIds = %v, want [\"proj-1\"]", ids)
}

resp := decodeJSON[map[string]any](t, w)
Expand All @@ -529,8 +504,7 @@ func TestSearchProjectCases(t *testing.T) {
}
})

t.Run("path project id overrides any projectIds in request body", func(t *testing.T) {
const projectID = "proj-authoritative"
t.Run("forwards body without projectIds unchanged", func(t *testing.T) {
var capturedBody []byte
client := &mockEntityCaseClient{
searchCasesFn: func(_ context.Context, body []byte) ([]byte, error) {
Expand All @@ -539,21 +513,18 @@ func TestSearchProjectCases(t *testing.T) {
},
}
h := NewCaseHandler(client)
r := withUser(httptest.NewRequest(http.MethodPost, "/projects/proj-authoritative/cases/search",
strings.NewReader(`{"projectIds":["proj-attacker","proj-other"]}`)))
r.SetPathValue("id", projectID)
r := withUser(httptest.NewRequest(http.MethodPost, "/cases/search",
strings.NewReader(`{"stateKeys":["open"],"pagination":{"limit":10,"offset":0}}`)))
w := httptest.NewRecorder()
h.SearchProjectCases(w, r)
h.SearchCases(w, r)

assertStatus(t, w, http.StatusOK)

var sent map[string]json.RawMessage
if err := json.Unmarshal(capturedBody, &sent); err != nil {
t.Fatalf("upstream received invalid JSON: %v", err)
}
var ids []string
if err := json.Unmarshal(sent["projectIds"], &ids); err != nil || len(ids) != 1 || ids[0] != projectID {
t.Errorf("upstream projectIds = %v, want [%q] (path ID must win)", ids, projectID)
if _, exists := sent["projectIds"]; exists {
t.Errorf("upstream body unexpectedly contains projectIds: %s", sent["projectIds"])
}
})

Expand All @@ -567,10 +538,9 @@ func TestSearchProjectCases(t *testing.T) {
},
}
h := NewCaseHandler(client)
r := withUser(httptest.NewRequest(http.MethodPost, "/projects/proj-1/cases/search", strings.NewReader(`{}`)))
r.SetPathValue("id", "proj-1")
r := withUser(httptest.NewRequest(http.MethodPost, "/cases/search", strings.NewReader(`{}`)))
w := httptest.NewRecorder()
h.SearchProjectCases(w, r)
h.SearchCases(w, r)
assertStatus(t, w, tc.wantCode)
assertErrorMessage(t, w, tc.wantMsg)
assertContentType(t, w, "application/json")
Expand Down
25 changes: 11 additions & 14 deletions apps/csm-portal/backend/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -598,23 +598,16 @@ paths:
schema:
$ref: '#/components/schemas/ErrorPayload'

/projects/{id}/cases/search:
/cases/search:
post:
summary: Search cases for a specific project.
operationId: postProjectsIdCasesSearch
parameters:
- name: id
in: path
description: ID of the project
required: true
schema:
type: string
summary: Search cases.
operationId: postCasesSearch
requestBody:
description: Project case search payload
description: Case search payload
content:
application/json:
schema:
$ref: '#/components/schemas/ProjectCaseSearchPayload'
$ref: '#/components/schemas/CaseSearchPayload'
required: true
responses:
"200":
Expand Down Expand Up @@ -948,11 +941,15 @@ components:
enum: [error, partial_outage, performance_degradation, question, security_or_compliance, total_outage]
description: Nature of the issue

ProjectCaseSearchPayload:
CaseSearchPayload:
type: object
nullable: true
description: Case search payload for a project-scoped search. The project ID is taken from the URL path; any projectIds in the body are ignored.
properties:
projectIds:
type: array
items:
type: string
description: Filter by project IDs (optional)
pagination:
allOf:
- $ref: '#/components/schemas/Pagination'
Expand Down