From e4cbdfa3f3587085673c94ce0b8c348c99637e2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Salavisa?= Date: Sun, 6 Sep 2026 09:44:09 +0100 Subject: [PATCH] refactor(gitlab): remove legacy websocket request API (#3431) Co-authored-by: Kandev Agent --- apps/backend/internal/backendapp/helpers.go | 4 +- apps/backend/internal/events/types.go | 2 +- .../gitlab/controller_watches_http_test.go | 2 + apps/backend/internal/gitlab/handlers.go | 735 ------------------ .../gitlab/handlers_registration_test.go | 157 +--- .../gitlab/handlers_ws_actions_test.go | 701 ----------------- .../internal/gitlab/handlers_ws_test.go | 484 ------------ .../gitlab/handlers_ws_watches_test.go | 563 -------------- .../internal/gitlab/mock_controller.go | 10 + .../gitlab/security_regression_test.go | 127 +-- apps/backend/pkg/websocket/actions.go | 55 +- docs/public/websocket-api.md | 44 +- 12 files changed, 106 insertions(+), 2778 deletions(-) delete mode 100644 apps/backend/internal/gitlab/handlers.go delete mode 100644 apps/backend/internal/gitlab/handlers_ws_actions_test.go delete mode 100644 apps/backend/internal/gitlab/handlers_ws_test.go delete mode 100644 apps/backend/internal/gitlab/handlers_ws_watches_test.go diff --git a/apps/backend/internal/backendapp/helpers.go b/apps/backend/internal/backendapp/helpers.go index ec94ec978c..2c9e438699 100644 --- a/apps/backend/internal/backendapp/helpers.go +++ b/apps/backend/internal/backendapp/helpers.go @@ -1429,9 +1429,9 @@ func registerSecondaryRoutes( } if p.services.GitLab != nil { - gitlab.RegisterRoutesWithDispatcher(p.router, p.gateway.Dispatcher, p.services.GitLab, p.log) + gitlab.RegisterRoutes(p.router, p.services.GitLab, p.log) gitlab.RegisterMockRoutes(p.router, p.services.GitLab, p.log) - p.log.Debug("Registered GitLab handlers (HTTP + WebSocket)") + p.log.Debug("Registered GitLab handlers (HTTP)") } if p.services.AzureDevOps != nil { diff --git a/apps/backend/internal/events/types.go b/apps/backend/internal/events/types.go index a95930513d..9d6f9b64ba 100644 --- a/apps/backend/internal/events/types.go +++ b/apps/backend/internal/events/types.go @@ -340,7 +340,7 @@ const ( // Event types for GitLab integration const ( - GitLabMRFeedback = "gitlab.mr_feedback" // MR has new feedback (UI notification only) + GitLabMRFeedback = "gitlab.mr_feedback" // MR has new feedback GitLabMRStateChanged = "gitlab.mr_state_changed" // MR state changed (merged, closed, etc.) GitLabNewReviewMR = "gitlab.new_mr_to_review" // New MR found needing review GitLabNewIssue = "gitlab.new_issue" // New issue found matching issue watch diff --git a/apps/backend/internal/gitlab/controller_watches_http_test.go b/apps/backend/internal/gitlab/controller_watches_http_test.go index e35678d081..0eea456586 100644 --- a/apps/backend/internal/gitlab/controller_watches_http_test.go +++ b/apps/backend/internal/gitlab/controller_watches_http_test.go @@ -10,6 +10,8 @@ import ( "github.com/gin-gonic/gin" ) +const respKeyDeleted = "deleted" + // newWatchHTTPFixture builds the full v1 HTTP surface over a store seeded with // two workspaces, the dependency validators that accept the "ws-1" fixture // identifiers, and a per-workspace mock client. Watch CRUD over HTTP is diff --git a/apps/backend/internal/gitlab/handlers.go b/apps/backend/internal/gitlab/handlers.go deleted file mode 100644 index 8f27592933..0000000000 --- a/apps/backend/internal/gitlab/handlers.go +++ /dev/null @@ -1,735 +0,0 @@ -package gitlab - -import ( - "context" - "strings" - - "github.com/gin-gonic/gin" - - "github.com/kandev/kandev/internal/common/logger" - ws "github.com/kandev/kandev/pkg/websocket" -) - -const ( - errMsgInvalidPayload = "invalid payload" - errMsgIDRequired = "id required" - respKeyDeleted = "deleted" -) - -// RegisterRoutesWithDispatcher registers HTTP + WS routes for GitLab. -// Preserves the existing RegisterRoutes(router, svc, log) signature by -// adding a sibling function so callers can pass a dispatcher. -func RegisterRoutesWithDispatcher(router *gin.Engine, dispatcher *ws.Dispatcher, svc *Service, log *logger.Logger) { - NewController(svc, log).RegisterHTTPRoutes(router) - // GitLab requests are workspace-scoped on the HTTP surface. The legacy - // WebSocket handlers predate workspace-owned connections and cannot carry - // the same authorization boundary, so they intentionally remain unmounted. - _ = dispatcher -} - -// RegisterMockRoutes registers mock control endpoints if the underlying -// client is a MockClient. No-op otherwise. -func RegisterMockRoutes(router *gin.Engine, svc *Service, log *logger.Logger) { - mock, ok := svc.Client().(*MockClient) - if !ok { - return - } - NewMockController(mock, svc, log).RegisterRoutes(router) - log.Info("registered GitLab mock control endpoints") -} - -// registerWSHandlers wires the GitLab WS action surface onto the dispatcher. -func registerWSHandlers(dispatcher *ws.Dispatcher, svc *Service, log *logger.Logger) { - dispatcher.RegisterFunc(ws.ActionGitLabStatus, wsStatus(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabTaskMRsList, wsListTaskMRs(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabTaskMRGet, wsGetTaskMR(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabMRFeedbackGet, wsGetMRFeedback(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabReviewWatchesList, wsListReviewWatches(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabReviewWatchCreate, wsCreateReviewWatch(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabReviewWatchUpdate, wsUpdateReviewWatch(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabReviewWatchDelete, wsDeleteReviewWatch(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabReviewTrigger, wsTriggerReviewWatch(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabReviewTriggerAll, wsTriggerAllReviewChecks(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabMRWatchesList, wsListMRWatches(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabMRWatchDelete, wsDeleteMRWatch(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabMRFilesGet, wsGetMRFiles(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabMRCommitsGet, wsGetMRCommits(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabTaskMRSync, wsSyncTaskMR(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabStats, wsGetStats(svc, log)) - - dispatcher.RegisterFunc(ws.ActionGitLabMRMerge, wsMergeMR(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabMRApprove, wsApproveMR(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabMRUnapprove, wsUnapproveMR(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabMRSetLabels, wsSetMRLabels(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabMRSetAssignees, wsSetMRAssignees(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabMRDiscussionNew, wsNewDiscussionNote(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabMRDiscussionResolve, wsResolveDiscussion(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabProjectMergeMethodsGet, wsGetProjectMergeMethods(svc, log)) - - dispatcher.RegisterFunc(ws.ActionGitLabIssueWatchesList, wsListIssueWatches(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabIssueWatchCreate, wsCreateIssueWatch(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabIssueWatchUpdate, wsUpdateIssueWatch(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabIssueWatchDelete, wsDeleteIssueWatch(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabIssueTrigger, wsTriggerIssueWatch(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabIssueTriggerAll, wsTriggerAllIssueChecks(svc, log)) - - dispatcher.RegisterFunc(ws.ActionGitLabActionPresetsList, wsListActionPresets(svc)) - dispatcher.RegisterFunc(ws.ActionGitLabActionPresetsUpdate, wsUpdateActionPresets(svc)) - dispatcher.RegisterFunc(ws.ActionGitLabActionPresetsReset, wsResetActionPresets(svc)) - - dispatcher.RegisterFunc(ws.ActionGitLabListUserProjects, wsListUserProjects(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabSearchProjects, wsSearchProjects(svc, log)) - dispatcher.RegisterFunc(ws.ActionGitLabProjectBranches, wsListProjectBranches(svc, log)) - - dispatcher.RegisterFunc(ws.ActionGitLabCleanupReviewTasks, wsCleanupReviewTasks(svc)) - dispatcher.RegisterFunc(ws.ActionGitLabCleanupIssueTasks, wsCleanupIssueTasks(svc)) -} - -// --- Generic helpers --- - -func parseInto[T any](msg *ws.Message, out *T) error { return msg.ParsePayload(out) } - -func badRequest(msg *ws.Message, reason string) (*ws.Message, error) { - return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, reason, nil) -} - -func internalError(msg *ws.Message, err error) (*ws.Message, error) { - return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil) -} - -func okResponse(msg *ws.Message, payload interface{}) (*ws.Message, error) { - return ws.NewResponse(msg.ID, msg.Action, payload) -} - -// --- Status / list / get / sync --- - -func wsStatus(svc *Service, log *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - status, err := svc.GetStatus(ctx) - if err != nil { - log.Warn("gitlab status: " + err.Error()) - return internalError(msg, err) - } - return okResponse(msg, status) - } -} - -func wsListTaskMRs(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - WorkspaceID string `json:"workspace_id"` - TaskID string `json:"task_id"` - } - // Malformed payloads must not silently fall through to the "list - // everything in workspace" branch — that exposes more data than the - // caller intended. Empty payload (both fields absent) is rejected - // further down by the workspace_id check. - if err := parseInto(msg, &req); err != nil { - return badRequest(msg, errMsgInvalidPayload) - } - if req.TaskID != "" { - mrs, err := svc.ListTaskMRsByTask(ctx, req.TaskID) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"task_mrs": mrs}) - } - if req.WorkspaceID == "" { - return badRequest(msg, "workspace_id or task_id required") - } - grouped, err := svc.ListTaskMRsByWorkspace(ctx, req.WorkspaceID) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, TaskMRsResponse{TaskMRs: grouped}) - } -} - -func wsGetTaskMR(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - TaskID string `json:"task_id"` - } - if err := parseInto(msg, &req); err != nil || req.TaskID == "" { - return badRequest(msg, "task_id required") - } - mrs, err := svc.ListTaskMRsByTask(ctx, req.TaskID) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"task_mrs": mrs}) - } -} - -func wsGetMRFeedback(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - Project string `json:"project"` - IID int `json:"iid"` - } - if err := parseInto(msg, &req); err != nil || req.Project == "" || req.IID <= 0 { - return badRequest(msg, "project and iid required") - } - feedback, err := svc.GetMRFeedback(ctx, req.Project, req.IID) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, feedback) - } -} - -func wsGetMRFiles(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - Project string `json:"project"` - IID int `json:"iid"` - } - if err := parseInto(msg, &req); err != nil || req.Project == "" || req.IID <= 0 { - return badRequest(msg, "project and iid required") - } - files, err := svc.GetMRFiles(ctx, req.Project, req.IID) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"files": files}) - } -} - -func wsGetMRCommits(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - Project string `json:"project"` - IID int `json:"iid"` - } - if err := parseInto(msg, &req); err != nil || req.Project == "" || req.IID <= 0 { - return badRequest(msg, "project and iid required") - } - commits, err := svc.GetMRCommits(ctx, req.Project, req.IID) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"commits": commits}) - } -} - -func wsSyncTaskMR(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - TaskID string `json:"task_id"` - } - if err := parseInto(msg, &req); err != nil || req.TaskID == "" { - return badRequest(msg, "task_id required") - } - rows, err := svc.TriggerMRSync(ctx, req.TaskID) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"task_mrs": rows}) - } -} - -func wsGetStats(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - stats, err := svc.GetStats(ctx) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, stats) - } -} - -// --- Review watch handlers --- - -func wsListReviewWatches(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - WorkspaceID string `json:"workspace_id"` - } - if err := parseInto(msg, &req); err != nil { - return badRequest(msg, errMsgInvalidPayload) - } - var watches []*ReviewWatch - var err error - if req.WorkspaceID == "" { - watches, err = svc.ListAllReviewWatches(ctx) - } else { - watches, err = svc.ListReviewWatches(ctx, req.WorkspaceID) - } - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"watches": watches}) - } -} - -func wsCreateReviewWatch(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req CreateReviewWatchRequest - if err := parseInto(msg, &req); err != nil { - return badRequest(msg, errMsgInvalidPayload) - } - w, err := svc.CreateReviewWatch(ctx, &req) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, w) - } -} - -func wsUpdateReviewWatch(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - ID string `json:"id"` - UpdateReviewWatchRequest - } - if err := parseInto(msg, &req); err != nil || req.ID == "" { - return badRequest(msg, errMsgIDRequired) - } - if err := svc.UpdateReviewWatch(ctx, req.ID, &req.UpdateReviewWatchRequest); err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"updated": true}) - } -} - -func wsDeleteReviewWatch(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - ID string `json:"id"` - } - if err := parseInto(msg, &req); err != nil || req.ID == "" { - return badRequest(msg, errMsgIDRequired) - } - if err := svc.DeleteReviewWatch(ctx, req.ID); err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{respKeyDeleted: true}) - } -} - -func wsTriggerReviewWatch(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - ID string `json:"id"` - } - if err := parseInto(msg, &req); err != nil || req.ID == "" { - return badRequest(msg, errMsgIDRequired) - } - mrs, err := svc.TriggerReviewWatch(ctx, req.ID) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"mrs": mrs}) - } -} - -func wsTriggerAllReviewChecks(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - n, err := svc.TriggerReviewWatchAll(ctx) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"count": n}) - } -} - -// --- MR watch handlers --- - -func wsListMRWatches(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - SessionID string `json:"session_id"` - TaskID string `json:"task_id"` - } - if err := parseInto(msg, &req); err != nil { - return badRequest(msg, errMsgInvalidPayload) - } - switch { - case req.SessionID != "": - ws, err := svc.ListMRWatchesBySession(ctx, req.SessionID) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"watches": ws}) - case req.TaskID != "": - ws, err := svc.ListMRWatchesByTask(ctx, req.TaskID) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"watches": ws}) - default: - ws, err := svc.ListActiveMRWatches(ctx) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"watches": ws}) - } - } -} - -func wsDeleteMRWatch(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - ID string `json:"id"` - } - if err := parseInto(msg, &req); err != nil || req.ID == "" { - return badRequest(msg, errMsgIDRequired) - } - if err := svc.DeleteMRWatch(ctx, req.ID); err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{respKeyDeleted: true}) - } -} - -// --- Issue watch handlers --- - -func wsListIssueWatches(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - WorkspaceID string `json:"workspace_id"` - } - if err := parseInto(msg, &req); err != nil { - return badRequest(msg, errMsgInvalidPayload) - } - var watches []*IssueWatch - var err error - if req.WorkspaceID == "" { - watches, err = svc.ListAllIssueWatches(ctx) - } else { - watches, err = svc.ListIssueWatches(ctx, req.WorkspaceID) - } - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"watches": watches}) - } -} - -func wsCreateIssueWatch(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req CreateIssueWatchRequest - if err := parseInto(msg, &req); err != nil { - return badRequest(msg, errMsgInvalidPayload) - } - w, err := svc.CreateIssueWatch(ctx, &req) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, w) - } -} - -func wsUpdateIssueWatch(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - ID string `json:"id"` - UpdateIssueWatchRequest - } - if err := parseInto(msg, &req); err != nil || req.ID == "" { - return badRequest(msg, errMsgIDRequired) - } - if err := svc.UpdateIssueWatch(ctx, req.ID, &req.UpdateIssueWatchRequest); err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"updated": true}) - } -} - -func wsDeleteIssueWatch(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - ID string `json:"id"` - } - if err := parseInto(msg, &req); err != nil || req.ID == "" { - return badRequest(msg, errMsgIDRequired) - } - if err := svc.DeleteIssueWatch(ctx, req.ID); err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{respKeyDeleted: true}) - } -} - -func wsTriggerIssueWatch(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - ID string `json:"id"` - } - if err := parseInto(msg, &req); err != nil || req.ID == "" { - return badRequest(msg, errMsgIDRequired) - } - issues, err := svc.TriggerIssueWatch(ctx, req.ID) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"issues": issues}) - } -} - -func wsTriggerAllIssueChecks(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - n, err := svc.TriggerIssueWatchAll(ctx) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"count": n}) - } -} - -// --- Write actions --- - -func wsMergeMR(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - Project string `json:"project"` - IID int `json:"iid"` - Method string `json:"method"` - SquashCommitMessage string `json:"squash_commit_message"` - } - if err := parseInto(msg, &req); err != nil || req.Project == "" || req.IID <= 0 { - return badRequest(msg, "project and iid required") - } - mr, err := svc.MergeMR(ctx, req.Project, req.IID, req.Method, req.SquashCommitMessage) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, mr) - } -} - -func wsApproveMR(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - Project string `json:"project"` - IID int `json:"iid"` - } - if err := parseInto(msg, &req); err != nil || req.Project == "" || req.IID <= 0 { - return badRequest(msg, "project and iid required") - } - if err := svc.SubmitMRApproval(ctx, req.Project, req.IID); err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"approved": true}) - } -} - -func wsUnapproveMR(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - Project string `json:"project"` - IID int `json:"iid"` - } - if err := parseInto(msg, &req); err != nil || req.Project == "" || req.IID <= 0 { - return badRequest(msg, "project and iid required") - } - if err := svc.SubmitMRUnapproval(ctx, req.Project, req.IID); err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"unapproved": true}) - } -} - -func wsSetMRLabels(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - Project string `json:"project"` - IID int `json:"iid"` - Labels []string `json:"labels"` - } - if err := parseInto(msg, &req); err != nil || req.Project == "" || req.IID <= 0 { - return badRequest(msg, "project and iid required") - } - if err := svc.SetMRLabels(ctx, req.Project, req.IID, req.Labels); err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"updated": true}) - } -} - -func wsSetMRAssignees(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - Project string `json:"project"` - IID int `json:"iid"` - AssigneeIDs []int `json:"assignee_ids"` - } - if err := parseInto(msg, &req); err != nil || req.Project == "" || req.IID <= 0 { - return badRequest(msg, "project and iid required") - } - if err := svc.SetMRAssignees(ctx, req.Project, req.IID, req.AssigneeIDs); err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"updated": true}) - } -} - -func wsNewDiscussionNote(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - Project string `json:"project"` - IID int `json:"iid"` - DiscussionID string `json:"discussion_id"` - Body string `json:"body"` - } - if err := parseInto(msg, &req); err != nil || req.Project == "" || req.IID <= 0 || req.DiscussionID == "" { - return badRequest(msg, "project, iid, discussion_id required") - } - if strings.TrimSpace(req.Body) == "" { - return badRequest(msg, "body required") - } - note, err := svc.CreateMRDiscussionNote(ctx, req.Project, req.IID, req.DiscussionID, req.Body) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, note) - } -} - -func wsResolveDiscussion(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - Project string `json:"project"` - IID int `json:"iid"` - DiscussionID string `json:"discussion_id"` - } - if err := parseInto(msg, &req); err != nil || req.Project == "" || req.IID <= 0 || req.DiscussionID == "" { - return badRequest(msg, "project, iid, discussion_id required") - } - if err := svc.ResolveMRDiscussion(ctx, req.Project, req.IID, req.DiscussionID); err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"resolved": true}) - } -} - -func wsGetProjectMergeMethods(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - Project string `json:"project"` - } - if err := parseInto(msg, &req); err != nil || req.Project == "" { - return badRequest(msg, "project required") - } - methods, err := svc.GetProjectMergeMethods(ctx, req.Project) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, methods) - } -} - -// --- Projects --- - -func wsListUserProjects(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - projects, err := svc.ListUserProjects(ctx) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"projects": projects}) - } -} - -func wsSearchProjects(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - Query string `json:"query"` - Limit int `json:"limit"` - } - if err := parseInto(msg, &req); err != nil { - return badRequest(msg, errMsgInvalidPayload) - } - projects, err := svc.SearchProjects(ctx, req.Query, req.Limit) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"projects": projects}) - } -} - -func wsListProjectBranches(svc *Service, _ *logger.Logger) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - Project string `json:"project"` - } - if err := parseInto(msg, &req); err != nil || req.Project == "" { - return badRequest(msg, "project required") - } - branches, err := svc.ListProjectBranches(ctx, req.Project) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]interface{}{"branches": branches}) - } -} - -// --- Action presets --- - -func wsListActionPresets(svc *Service) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - WorkspaceID string `json:"workspace_id"` - } - if err := parseInto(msg, &req); err != nil || req.WorkspaceID == "" { - return badRequest(msg, "workspace_id required") - } - presets, err := svc.GetActionPresetsOrDefault(ctx, req.WorkspaceID) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, presets) - } -} - -func wsUpdateActionPresets(svc *Service) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req UpdateActionPresetsRequest - if err := parseInto(msg, &req); err != nil || req.WorkspaceID == "" { - return badRequest(msg, "workspace_id required") - } - presets, err := svc.UpdateActionPresets(ctx, &req) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, presets) - } -} - -func wsResetActionPresets(svc *Service) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req struct { - WorkspaceID string `json:"workspace_id"` - } - if err := parseInto(msg, &req); err != nil || req.WorkspaceID == "" { - return badRequest(msg, "workspace_id required") - } - presets, err := svc.ResetActionPresets(ctx, req.WorkspaceID) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, presets) - } -} - -// --- Cleanup --- - -func wsCleanupReviewTasks(svc *Service) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - n, err := svc.CleanupAllReviewTasks(ctx) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]int{respKeyDeleted: n}) - } -} - -func wsCleanupIssueTasks(svc *Service) ws.HandlerFunc { - return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - n, err := svc.CleanupAllIssueTasks(ctx) - if err != nil { - return internalError(msg, err) - } - return okResponse(msg, map[string]int{respKeyDeleted: n}) - } -} diff --git a/apps/backend/internal/gitlab/handlers_registration_test.go b/apps/backend/internal/gitlab/handlers_registration_test.go index c4da8b5466..24116fffab 100644 --- a/apps/backend/internal/gitlab/handlers_registration_test.go +++ b/apps/backend/internal/gitlab/handlers_registration_test.go @@ -1,107 +1,25 @@ package gitlab import ( - "context" "testing" "github.com/gin-gonic/gin" - ws "github.com/kandev/kandev/pkg/websocket" + "github.com/kandev/kandev/internal/common/logger" ) -// gitLabWSActions is every action registerWSHandlers wires. Kept explicit so a -// handler added to handlers.go without a corresponding entry here fails -// TestRegisterWSHandlersCoversEveryGitLabAction rather than going untested. -var gitLabWSActions = []string{ - ws.ActionGitLabStatus, - ws.ActionGitLabTaskMRsList, - ws.ActionGitLabTaskMRGet, - ws.ActionGitLabMRFeedbackGet, - ws.ActionGitLabReviewWatchesList, - ws.ActionGitLabReviewWatchCreate, - ws.ActionGitLabReviewWatchUpdate, - ws.ActionGitLabReviewWatchDelete, - ws.ActionGitLabReviewTrigger, - ws.ActionGitLabReviewTriggerAll, - ws.ActionGitLabMRWatchesList, - ws.ActionGitLabMRWatchDelete, - ws.ActionGitLabMRFilesGet, - ws.ActionGitLabMRCommitsGet, - ws.ActionGitLabTaskMRSync, - ws.ActionGitLabStats, - ws.ActionGitLabMRMerge, - ws.ActionGitLabMRApprove, - ws.ActionGitLabMRUnapprove, - ws.ActionGitLabMRSetLabels, - ws.ActionGitLabMRSetAssignees, - ws.ActionGitLabMRDiscussionNew, - ws.ActionGitLabMRDiscussionResolve, - ws.ActionGitLabProjectMergeMethodsGet, - ws.ActionGitLabIssueWatchesList, - ws.ActionGitLabIssueWatchCreate, - ws.ActionGitLabIssueWatchUpdate, - ws.ActionGitLabIssueWatchDelete, - ws.ActionGitLabIssueTrigger, - ws.ActionGitLabIssueTriggerAll, - ws.ActionGitLabActionPresetsList, - ws.ActionGitLabActionPresetsUpdate, - ws.ActionGitLabActionPresetsReset, - ws.ActionGitLabListUserProjects, - ws.ActionGitLabSearchProjects, - ws.ActionGitLabProjectBranches, - ws.ActionGitLabCleanupReviewTasks, - ws.ActionGitLabCleanupIssueTasks, +func newRouteRegistrationFixture(t *testing.T, client Client) (*Service, *logger.Logger) { + t.Helper() + log := newTestLogger(t) + return NewService(DefaultHost, client, AuthMethodNone, nil, log), log } -func TestRegisterWSHandlersCoversEveryGitLabAction(t *testing.T) { - svc, _, log := newWSFixture(t, NewMockClient(DefaultHost)) - dispatcher := ws.NewDispatcher() - - registerWSHandlers(dispatcher, svc, log) - - for _, action := range gitLabWSActions { - if !dispatcher.HasHandler(action) { - t.Errorf("action %q has no handler registered", action) - } - } - if got := dispatcher.HandlerCount(); got != len(gitLabWSActions) { - t.Errorf("handler count = %d, want %d; a handler was added or removed "+ - "without updating gitLabWSActions", got, len(gitLabWSActions)) - } -} - -// TestRegisterRoutesWithDispatcherLeavesWSSurfaceUnmounted pins the -// authorization boundary documented in handlers.go: the legacy GitLab WS -// handlers are workspace-unscoped, so RegisterRoutesWithDispatcher must mount -// the HTTP surface only and leave the dispatcher untouched. Wiring -// registerWSHandlers back in here would silently expose every workspace's -// watches over a connection that carries no workspace scope. -func TestRegisterRoutesWithDispatcherLeavesWSSurfaceUnmounted(t *testing.T) { +func TestRegisterRoutesMountsHTTPRoutes(t *testing.T) { gin.SetMode(gin.TestMode) - svc, _, log := newWSFixture(t, NewMockClient(DefaultHost)) - dispatcher := ws.NewDispatcher() + svc, log := newRouteRegistrationFixture(t, NewMockClient(DefaultHost)) router := gin.New() - RegisterRoutesWithDispatcher(router, dispatcher, svc, log) - - if got := dispatcher.HandlerCount(); got != 0 { - t.Fatalf("dispatcher has %d handlers, want 0 — the GitLab WS surface is "+ - "deliberately unmounted because it cannot carry the workspace "+ - "authorization boundary the HTTP routes enforce", got) - } - for _, action := range gitLabWSActions { - if dispatcher.HasHandler(action) { - t.Errorf("action %q was mounted on the dispatcher", action) - } - } -} - -func TestRegisterRoutesWithDispatcherMountsHTTPRoutes(t *testing.T) { - gin.SetMode(gin.TestMode) - svc, _, log := newWSFixture(t, NewMockClient(DefaultHost)) - router := gin.New() - - RegisterRoutesWithDispatcher(router, ws.NewDispatcher(), svc, log) + RegisterRoutes(router, svc, log) want := map[string]string{ "GET": "/api/v1/gitlab/status", @@ -120,44 +38,9 @@ func TestRegisterRoutesWithDispatcherMountsHTTPRoutes(t *testing.T) { } } -// TestRegisterRoutesMatchesDispatcherVariant guards the package-level -// RegisterRoutes entrypoint against drifting from the dispatcher-aware sibling: -// both must mount exactly the same HTTP surface. -func TestRegisterRoutesMatchesDispatcherVariant(t *testing.T) { - gin.SetMode(gin.TestMode) - svc, _, log := newWSFixture(t, NewMockClient(DefaultHost)) - - plain := gin.New() - RegisterRoutes(plain, svc, log) - withDispatcher := gin.New() - RegisterRoutesWithDispatcher(withDispatcher, ws.NewDispatcher(), svc, log) - - collect := func(router *gin.Engine) map[string]bool { - out := map[string]bool{} - for _, route := range router.Routes() { - out[route.Method+" "+route.Path] = true - } - return out - } - plainRoutes, dispatcherRoutes := collect(plain), collect(withDispatcher) - if len(plainRoutes) == 0 { - t.Fatal("RegisterRoutes mounted no routes at all") - } - for route := range plainRoutes { - if !dispatcherRoutes[route] { - t.Errorf("route %q is missing from RegisterRoutesWithDispatcher", route) - } - } - for route := range dispatcherRoutes { - if !plainRoutes[route] { - t.Errorf("route %q is missing from RegisterRoutes", route) - } - } -} - func TestRegisterMockRoutesIsNoOpForNonMockClient(t *testing.T) { gin.SetMode(gin.TestMode) - svc, _, log := newWSFixture(t, NewNoopClient(DefaultHost)) + svc, log := newRouteRegistrationFixture(t, NewNoopClient(DefaultHost)) router := gin.New() RegisterMockRoutes(router, svc, log) @@ -169,7 +52,7 @@ func TestRegisterMockRoutesIsNoOpForNonMockClient(t *testing.T) { func TestRegisterMockRoutesMountsControlEndpointsForMockClient(t *testing.T) { gin.SetMode(gin.TestMode) - svc, _, log := newWSFixture(t, NewMockClient(DefaultHost)) + svc, log := newRouteRegistrationFixture(t, NewMockClient(DefaultHost)) router := gin.New() RegisterMockRoutes(router, svc, log) @@ -178,23 +61,3 @@ func TestRegisterMockRoutesMountsControlEndpointsForMockClient(t *testing.T) { t.Fatal("no mock control endpoints were registered for a MockClient") } } - -// TestWSHandlersDispatchThroughDispatcher proves the registered closures are -// reachable by action name and return their own action in the reply, which is -// what lets the frontend correlate a response with the request that caused it. -func TestWSHandlersDispatchThroughDispatcher(t *testing.T) { - client := NewMockClient(DefaultHost) - client.SetUser("alice") - svc, _, log := newWSFixture(t, client) - dispatcher := ws.NewDispatcher() - registerWSHandlers(dispatcher, svc, log) - - resp, err := dispatcher.Dispatch(context.Background(), - wsRequest(t, ws.ActionGitLabStatus, nil)) - - var status Status - wsOK(t, resp, err, ws.ActionGitLabStatus, &status) - if status.Username != "alice" { - t.Errorf("username = %q, want alice", status.Username) - } -} diff --git a/apps/backend/internal/gitlab/handlers_ws_actions_test.go b/apps/backend/internal/gitlab/handlers_ws_actions_test.go deleted file mode 100644 index 063524ac97..0000000000 --- a/apps/backend/internal/gitlab/handlers_ws_actions_test.go +++ /dev/null @@ -1,701 +0,0 @@ -package gitlab - -import ( - "context" - "errors" - "testing" - - "github.com/kandev/kandev/internal/common/logger" - ws "github.com/kandev/kandev/pkg/websocket" -) - -// actionRecordingClient captures the arguments each write handler forwards to -// the GitLab client, so the tests can assert the exact upstream call rather -// than only the response envelope. Any method left unset delegates to the -// embedded MockClient. -type actionRecordingClient struct { - *MockClient - - labelCalls []labelCall - assigneeCalls []assigneeCall - noteCalls []noteCall - resolveCalls []resolveCall - mergeMethods *ProjectMergeMethods - mergeErr error -} - -type labelCall struct { - Project string - IID int - Labels []string -} - -type assigneeCall struct { - Project string - IID int - IDs []int -} - -type noteCall struct { - Project string - IID int - DiscussionID string - Body string -} - -type resolveCall struct { - Project string - IID int - DiscussionID string -} - -func (c *actionRecordingClient) SetMRLabels(_ context.Context, project string, iid int, labels []string) error { - c.labelCalls = append(c.labelCalls, labelCall{Project: project, IID: iid, Labels: labels}) - return nil -} - -func (c *actionRecordingClient) SetMRAssignees(_ context.Context, project string, iid int, ids []int) error { - c.assigneeCalls = append(c.assigneeCalls, assigneeCall{Project: project, IID: iid, IDs: ids}) - return nil -} - -func (c *actionRecordingClient) CreateMRDiscussionNote(_ context.Context, project string, iid int, discussionID, body string) (*MRNote, error) { - c.noteCalls = append(c.noteCalls, noteCall{Project: project, IID: iid, DiscussionID: discussionID, Body: body}) - return &MRNote{ID: 99, Body: body}, nil -} - -func (c *actionRecordingClient) ResolveMRDiscussion(_ context.Context, project string, iid int, discussionID string) error { - c.resolveCalls = append(c.resolveCalls, resolveCall{Project: project, IID: iid, DiscussionID: discussionID}) - return nil -} - -func (c *actionRecordingClient) GetProjectMergeMethods(ctx context.Context, project string) (*ProjectMergeMethods, error) { - if c.mergeErr != nil { - return nil, c.mergeErr - } - if c.mergeMethods != nil { - return c.mergeMethods, nil - } - return c.MockClient.GetProjectMergeMethods(ctx, project) -} - -func newActionFixture(t *testing.T) (*Service, *actionRecordingClient, *logger.Logger) { - t.Helper() - client := &actionRecordingClient{MockClient: NewMockClient(DefaultHost)} - client.SetUser("alice") - svc, _, log := newWSFixture(t, client) - return svc, client, log -} - -// projectAndIIDValidationCases is shared by every handler whose guard is the -// same "project and iid required" triple. -func projectAndIIDValidationCases(t *testing.T, action string, handler ws.HandlerFunc) { - t.Helper() - cases := map[string]*ws.Message{ - "missing project": wsRequest(t, action, map[string]interface{}{"iid": 1}), - "missing iid": wsRequest(t, action, map[string]interface{}{"project": "g/p"}), - "malformed": wsRawRequest(action, `{"iid":"one"}`), - } - for name, msg := range cases { - t.Run(name, func(t *testing.T) { - resp, err := handler(context.Background(), msg) - wsErr(t, resp, err, action, ws.ErrorCodeBadRequest, "project and iid required") - }) - } -} - -// --- Merge --- - -func TestWSMergeMRMergesAndReturnsMR(t *testing.T) { - svc, client, log := newActionFixture(t) - iid := client.SeedMR("group/p", &MR{Title: "feat: x", State: "opened"}) - - resp, err := wsMergeMR(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabMRMerge, map[string]interface{}{ - "project": "group/p", "iid": iid, "method": "merge", - })) - - var mr MR - wsOK(t, resp, err, ws.ActionGitLabMRMerge, &mr) - if mr.State != "merged" { - t.Errorf("state = %q, want merged", mr.State) - } -} - -// TestWSMergeMRSurfacesDisallowedMethod pins that method validation happens -// before the merge call: the project below allows only merge commits, so a -// fast-forward request must fail rather than silently merging some other way. -func TestWSMergeMRSurfacesDisallowedMethod(t *testing.T) { - svc, client, log := newActionFixture(t) - client.mergeMethods = &ProjectMergeMethods{Merge: true} - iid := client.SeedMR("group/p", &MR{Title: "feat: x", State: "opened"}) - - resp, err := wsMergeMR(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabMRMerge, map[string]interface{}{ - "project": "group/p", "iid": iid, "method": "ff", - })) - - payload := wsErr(t, resp, err, ws.ActionGitLabMRMerge, ws.ErrorCodeInternalError, "") - if payload.Message != "project does not allow fast-forward merge" { - t.Errorf("message = %q, want the fast-forward rejection", payload.Message) - } - mr, getErr := client.GetMR(context.Background(), "group/p", iid) - if getErr != nil { - t.Fatalf("reload MR: %v", getErr) - } - if mr.State == "merged" { - t.Error("MR was merged despite the disallowed method") - } -} - -func TestWSMergeMRValidatesProjectAndIID(t *testing.T) { - svc, _, log := newActionFixture(t) - projectAndIIDValidationCases(t, ws.ActionGitLabMRMerge, wsMergeMR(svc, log)) -} - -// --- Approve / unapprove --- - -func TestWSApproveMRRecordsApproval(t *testing.T) { - svc, client, log := newActionFixture(t) - iid := client.SeedMR("group/p", &MR{Title: "feat: x", State: "opened"}) - - resp, err := wsApproveMR(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabMRApprove, map[string]interface{}{"project": "group/p", "iid": iid})) - - var body map[string]bool - wsOK(t, resp, err, ws.ActionGitLabMRApprove, &body) - if !body["approved"] { - t.Errorf("payload = %v, want {\"approved\":true}", body) - } - approvals, err := client.ListMRApprovals(context.Background(), "group/p", iid) - if err != nil { - t.Fatalf("list approvals: %v", err) - } - if len(approvals) != 1 || approvals[0].Username != "alice" { - t.Errorf("approvals = %+v, want alice's single approval", approvals) - } -} - -func TestWSApproveMRSurfacesUpstreamFailure(t *testing.T) { - svc, _, log := newActionFixture(t) - - resp, err := wsApproveMR(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabMRApprove, map[string]interface{}{"project": "group/p", "iid": 404})) - - wsErr(t, resp, err, ws.ActionGitLabMRApprove, ws.ErrorCodeInternalError, "") -} - -func TestWSApproveMRValidatesProjectAndIID(t *testing.T) { - svc, _, log := newActionFixture(t) - projectAndIIDValidationCases(t, ws.ActionGitLabMRApprove, wsApproveMR(svc, log)) -} - -func TestWSUnapproveMRRemovesApproval(t *testing.T) { - svc, client, log := newActionFixture(t) - iid := client.SeedMR("group/p", &MR{Title: "feat: x", State: "opened"}) - client.SeedApprovals("group/p", iid, []MRApproval{{Username: "alice"}}, 1) - - resp, err := wsUnapproveMR(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabMRUnapprove, map[string]interface{}{"project": "group/p", "iid": iid})) - - var body map[string]bool - wsOK(t, resp, err, ws.ActionGitLabMRUnapprove, &body) - if !body["unapproved"] { - t.Errorf("payload = %v, want {\"unapproved\":true}", body) - } - approvals, err := client.ListMRApprovals(context.Background(), "group/p", iid) - if err != nil { - t.Fatalf("list approvals: %v", err) - } - if len(approvals) != 0 { - t.Errorf("approvals = %+v, want alice's approval revoked", approvals) - } -} - -func TestWSUnapproveMRValidatesProjectAndIID(t *testing.T) { - svc, _, log := newActionFixture(t) - projectAndIIDValidationCases(t, ws.ActionGitLabMRUnapprove, wsUnapproveMR(svc, log)) -} - -// --- Labels / assignees --- - -func TestWSSetMRLabelsForwardsExactLabels(t *testing.T) { - svc, client, log := newActionFixture(t) - - resp, err := wsSetMRLabels(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabMRSetLabels, map[string]interface{}{ - "project": "group/p", "iid": 5, "labels": []string{"bug", "p1"}, - })) - - var body map[string]bool - wsOK(t, resp, err, ws.ActionGitLabMRSetLabels, &body) - if !body["updated"] { - t.Errorf("payload = %v, want {\"updated\":true}", body) - } - if len(client.labelCalls) != 1 { - t.Fatalf("label calls = %d, want exactly 1", len(client.labelCalls)) - } - call := client.labelCalls[0] - if call.Project != "group/p" || call.IID != 5 { - t.Errorf("call target = %s!%d, want group/p!5", call.Project, call.IID) - } - if len(call.Labels) != 2 || call.Labels[0] != "bug" || call.Labels[1] != "p1" { - t.Errorf("labels = %v, want [bug p1] in order", call.Labels) - } -} - -// TestWSSetMRLabelsForwardsEmptyListToClearLabels guards the "remove every -// label" case: an empty list must still reach the client, because dropping the -// call would silently leave the old labels in place. -func TestWSSetMRLabelsForwardsEmptyListToClearLabels(t *testing.T) { - svc, client, log := newActionFixture(t) - - resp, err := wsSetMRLabels(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabMRSetLabels, map[string]interface{}{ - "project": "group/p", "iid": 5, "labels": []string{}, - })) - - wsOK(t, resp, err, ws.ActionGitLabMRSetLabels, nil) - if len(client.labelCalls) != 1 { - t.Fatalf("label calls = %d, want 1 even for an empty list", len(client.labelCalls)) - } - if len(client.labelCalls[0].Labels) != 0 { - t.Errorf("labels = %v, want an empty list", client.labelCalls[0].Labels) - } -} - -func TestWSSetMRLabelsValidatesProjectAndIID(t *testing.T) { - svc, _, log := newActionFixture(t) - projectAndIIDValidationCases(t, ws.ActionGitLabMRSetLabels, wsSetMRLabels(svc, log)) -} - -func TestWSSetMRAssigneesForwardsExactIDs(t *testing.T) { - svc, client, log := newActionFixture(t) - - resp, err := wsSetMRAssignees(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabMRSetAssignees, map[string]interface{}{ - "project": "group/p", "iid": 6, "assignee_ids": []int{7, 8}, - })) - - var body map[string]bool - wsOK(t, resp, err, ws.ActionGitLabMRSetAssignees, &body) - if !body["updated"] { - t.Errorf("payload = %v, want {\"updated\":true}", body) - } - if len(client.assigneeCalls) != 1 { - t.Fatalf("assignee calls = %d, want exactly 1", len(client.assigneeCalls)) - } - call := client.assigneeCalls[0] - if call.Project != "group/p" || call.IID != 6 { - t.Errorf("call target = %s!%d, want group/p!6", call.Project, call.IID) - } - if len(call.IDs) != 2 || call.IDs[0] != 7 || call.IDs[1] != 8 { - t.Errorf("assignee ids = %v, want [7 8]", call.IDs) - } -} - -func TestWSSetMRAssigneesValidatesProjectAndIID(t *testing.T) { - svc, _, log := newActionFixture(t) - projectAndIIDValidationCases(t, ws.ActionGitLabMRSetAssignees, wsSetMRAssignees(svc, log)) -} - -// --- Discussions --- - -func TestWSNewDiscussionNoteForwardsBody(t *testing.T) { - svc, client, log := newActionFixture(t) - - resp, err := wsNewDiscussionNote(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabMRDiscussionNew, map[string]interface{}{ - "project": "group/p", "iid": 9, "discussion_id": "disc-1", "body": "looks good", - })) - - var note MRNote - wsOK(t, resp, err, ws.ActionGitLabMRDiscussionNew, ¬e) - if note.Body != "looks good" { - t.Errorf("note body = %q, want the posted body echoed back", note.Body) - } - if len(client.noteCalls) != 1 { - t.Fatalf("note calls = %d, want exactly 1", len(client.noteCalls)) - } - if client.noteCalls[0] != (noteCall{Project: "group/p", IID: 9, DiscussionID: "disc-1", Body: "looks good"}) { - t.Errorf("note call = %+v, want the exact request arguments", client.noteCalls[0]) - } -} - -func TestWSNewDiscussionNoteRequiresProjectIIDAndDiscussion(t *testing.T) { - svc, _, log := newActionFixture(t) - handler := wsNewDiscussionNote(svc, log) - - cases := map[string]interface{}{ - "missing project": map[string]interface{}{"iid": 1, "discussion_id": "d", "body": "b"}, - "missing iid": map[string]interface{}{"project": "g/p", "discussion_id": "d", "body": "b"}, - "missing discussion": map[string]interface{}{"project": "g/p", "iid": 1, "body": "b"}, - } - for name, payload := range cases { - t.Run(name, func(t *testing.T) { - resp, err := handler(context.Background(), wsRequest(t, ws.ActionGitLabMRDiscussionNew, payload)) - wsErr(t, resp, err, ws.ActionGitLabMRDiscussionNew, ws.ErrorCodeBadRequest, - "project, iid, discussion_id required") - }) - } -} - -// TestWSNewDiscussionNoteRejectsBlankBody covers the separate whitespace guard: -// a body of only spaces is rejected with its own reason and never reaches the -// client, so no empty comment is posted upstream. -func TestWSNewDiscussionNoteRejectsBlankBody(t *testing.T) { - svc, client, log := newActionFixture(t) - - resp, err := wsNewDiscussionNote(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabMRDiscussionNew, map[string]interface{}{ - "project": "group/p", "iid": 9, "discussion_id": "disc-1", "body": " \t\n ", - })) - - wsErr(t, resp, err, ws.ActionGitLabMRDiscussionNew, ws.ErrorCodeBadRequest, "body required") - if len(client.noteCalls) != 0 { - t.Errorf("note calls = %+v, want none for a blank body", client.noteCalls) - } -} - -func TestWSResolveDiscussionForwardsDiscussionID(t *testing.T) { - svc, client, log := newActionFixture(t) - - resp, err := wsResolveDiscussion(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabMRDiscussionResolve, map[string]interface{}{ - "project": "group/p", "iid": 9, "discussion_id": "disc-1", - })) - - var body map[string]bool - wsOK(t, resp, err, ws.ActionGitLabMRDiscussionResolve, &body) - if !body["resolved"] { - t.Errorf("payload = %v, want {\"resolved\":true}", body) - } - if len(client.resolveCalls) != 1 || - client.resolveCalls[0] != (resolveCall{Project: "group/p", IID: 9, DiscussionID: "disc-1"}) { - t.Errorf("resolve calls = %+v, want the exact request arguments", client.resolveCalls) - } -} - -func TestWSResolveDiscussionRequiresDiscussionID(t *testing.T) { - svc, _, log := newActionFixture(t) - - resp, err := wsResolveDiscussion(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabMRDiscussionResolve, map[string]interface{}{ - "project": "group/p", "iid": 9, - })) - - wsErr(t, resp, err, ws.ActionGitLabMRDiscussionResolve, ws.ErrorCodeBadRequest, - "project, iid, discussion_id required") -} - -// --- Merge methods --- - -func TestWSGetProjectMergeMethodsReturnsAllowedMethods(t *testing.T) { - svc, client, log := newActionFixture(t) - client.mergeMethods = &ProjectMergeMethods{Merge: true, AllowSquash: true} - - resp, err := wsGetProjectMergeMethods(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabProjectMergeMethodsGet, map[string]string{"project": "group/p"})) - - var methods ProjectMergeMethods - wsOK(t, resp, err, ws.ActionGitLabProjectMergeMethodsGet, &methods) - if !methods.Merge || !methods.AllowSquash || methods.FastForward { - t.Errorf("methods = %+v, want merge+squash only", methods) - } -} - -func TestWSGetProjectMergeMethodsRequiresProject(t *testing.T) { - svc, _, log := newActionFixture(t) - - resp, err := wsGetProjectMergeMethods(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabProjectMergeMethodsGet, map[string]string{})) - - wsErr(t, resp, err, ws.ActionGitLabProjectMergeMethodsGet, ws.ErrorCodeBadRequest, "project required") -} - -func TestWSGetProjectMergeMethodsSurfacesUpstreamFailure(t *testing.T) { - svc, client, log := newActionFixture(t) - client.mergeErr = errors.New("gitlab unreachable") - - resp, err := wsGetProjectMergeMethods(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabProjectMergeMethodsGet, map[string]string{"project": "group/p"})) - - wsErr(t, resp, err, ws.ActionGitLabProjectMergeMethodsGet, ws.ErrorCodeInternalError, "gitlab unreachable") -} - -// --- Projects --- - -func TestWSListUserProjectsReturnsProjects(t *testing.T) { - svc, _, log := newActionFixture(t) - - resp, err := wsListUserProjects(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabListUserProjects, nil)) - - var body struct { - Projects []Project `json:"projects"` - } - wsOK(t, resp, err, ws.ActionGitLabListUserProjects, &body) - if len(body.Projects) != 1 || body.Projects[0].PathWithNamespace != "kandev/sample" { - t.Fatalf("projects = %+v, want the single kandev/sample project", body.Projects) - } -} - -func TestWSSearchProjectsFiltersByQuery(t *testing.T) { - svc, _, log := newActionFixture(t) - handler := wsSearchProjects(svc, log) - - tests := []struct { - name string - query string - want int - }{ - {"matching query", "sample", 1}, - {"non-matching query", "nothing-like-this", 0}, - {"empty query returns all", "", 1}, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - resp, err := handler(context.Background(), - wsRequest(t, ws.ActionGitLabSearchProjects, map[string]interface{}{ - "query": test.query, "limit": 10, - })) - - var body struct { - Projects []Project `json:"projects"` - } - wsOK(t, resp, err, ws.ActionGitLabSearchProjects, &body) - if len(body.Projects) != test.want { - t.Errorf("projects = %d, want %d (%+v)", len(body.Projects), test.want, body.Projects) - } - }) - } -} - -func TestWSSearchProjectsRejectsMalformedPayload(t *testing.T) { - svc, _, log := newActionFixture(t) - - resp, err := wsSearchProjects(svc, log)(context.Background(), - wsRawRequest(ws.ActionGitLabSearchProjects, `{"limit":"ten"}`)) - - wsErr(t, resp, err, ws.ActionGitLabSearchProjects, ws.ErrorCodeBadRequest, errMsgInvalidPayload) -} - -func TestWSListProjectBranchesReturnsBranches(t *testing.T) { - svc, client, log := newActionFixture(t) - client.SeedBranches("group/p", []RepoBranch{{Name: "main"}, {Name: "dev"}}) - - resp, err := wsListProjectBranches(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabProjectBranches, map[string]string{"project": "group/p"})) - - var body struct { - Branches []RepoBranch `json:"branches"` - } - wsOK(t, resp, err, ws.ActionGitLabProjectBranches, &body) - if len(body.Branches) != 2 || body.Branches[0].Name != "main" { - t.Fatalf("branches = %+v, want [main dev]", body.Branches) - } -} - -func TestWSListProjectBranchesRequiresProject(t *testing.T) { - svc, _, log := newActionFixture(t) - - resp, err := wsListProjectBranches(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabProjectBranches, map[string]string{})) - - wsErr(t, resp, err, ws.ActionGitLabProjectBranches, ws.ErrorCodeBadRequest, "project required") -} - -// --- Action presets --- - -func TestWSListActionPresetsReturnsDefaultsForNewWorkspace(t *testing.T) { - svc, _, _ := newWSFixture(t, NewMockClient(DefaultHost)) - - resp, err := wsListActionPresets(svc)(context.Background(), - wsRequest(t, ws.ActionGitLabActionPresetsList, map[string]string{"workspace_id": "ws-1"})) - - var presets ActionPresets - wsOK(t, resp, err, ws.ActionGitLabActionPresetsList, &presets) - if len(presets.MR) == 0 || len(presets.Issue) == 0 { - t.Fatalf("presets = %+v, want the built-in defaults substituted", presets) - } -} - -func TestWSListActionPresetsRequiresWorkspaceID(t *testing.T) { - svc, _, _ := newWSFixture(t, NewMockClient(DefaultHost)) - - resp, err := wsListActionPresets(svc)(context.Background(), - wsRequest(t, ws.ActionGitLabActionPresetsList, map[string]string{})) - - wsErr(t, resp, err, ws.ActionGitLabActionPresetsList, ws.ErrorCodeBadRequest, "workspace_id required") -} - -func TestWSUpdateActionPresetsPersistsMRList(t *testing.T) { - svc, store, _ := newWSFixture(t, NewMockClient(DefaultHost)) - ctx := context.Background() - seedWorkspace(t, store, "ws-1") - - resp, err := wsUpdateActionPresets(svc)(ctx, - wsRequest(t, ws.ActionGitLabActionPresetsUpdate, UpdateActionPresetsRequest{ - WorkspaceID: "ws-1", - MR: &[]ActionPreset{{ID: "ship", Label: "Ship it", PromptTemplate: "ship {{mr}}"}}, - })) - - var presets ActionPresets - wsOK(t, resp, err, ws.ActionGitLabActionPresetsUpdate, &presets) - if len(presets.MR) != 1 || presets.MR[0].ID != "ship" { - t.Fatalf("mr presets = %+v, want only the custom ship preset", presets.MR) - } - stored, err := store.GetActionPresets(ctx, "ws-1") - if err != nil { - t.Fatalf("reload presets: %v", err) - } - if len(stored.MR) != 1 || stored.MR[0].Label != "Ship it" { - t.Errorf("stored mr presets = %+v, want the custom preset persisted", stored.MR) - } -} - -func TestWSUpdateActionPresetsRequiresWorkspaceID(t *testing.T) { - svc, _, _ := newWSFixture(t, NewMockClient(DefaultHost)) - - resp, err := wsUpdateActionPresets(svc)(context.Background(), - wsRequest(t, ws.ActionGitLabActionPresetsUpdate, UpdateActionPresetsRequest{})) - - wsErr(t, resp, err, ws.ActionGitLabActionPresetsUpdate, ws.ErrorCodeBadRequest, "workspace_id required") -} - -func TestWSResetActionPresetsClearsStoredOverrides(t *testing.T) { - svc, store, _ := newWSFixture(t, NewMockClient(DefaultHost)) - ctx := context.Background() - seedWorkspace(t, store, "ws-1") - if err := store.UpsertActionPresets(ctx, &ActionPresets{ - WorkspaceID: "ws-1", - MR: []ActionPreset{{ID: "ship", Label: "Ship it", PromptTemplate: "ship"}}, - }); err != nil { - t.Fatalf("seed presets: %v", err) - } - - resp, err := wsResetActionPresets(svc)(ctx, - wsRequest(t, ws.ActionGitLabActionPresetsReset, map[string]string{"workspace_id": "ws-1"})) - - var presets ActionPresets - wsOK(t, resp, err, ws.ActionGitLabActionPresetsReset, &presets) - for _, preset := range presets.MR { - if preset.ID == "ship" { - t.Fatalf("mr presets = %+v, want the custom preset gone after reset", presets.MR) - } - } - stored, err := store.GetActionPresets(ctx, "ws-1") - if err != nil { - t.Fatalf("reload presets: %v", err) - } - if len(stored.MR) != 0 { - t.Errorf("stored mr presets = %+v, want the row deleted", stored.MR) - } -} - -func TestWSResetActionPresetsRequiresWorkspaceID(t *testing.T) { - svc, _, _ := newWSFixture(t, NewMockClient(DefaultHost)) - - resp, err := wsResetActionPresets(svc)(context.Background(), - wsRequest(t, ws.ActionGitLabActionPresetsReset, map[string]string{})) - - wsErr(t, resp, err, ws.ActionGitLabActionPresetsReset, ws.ErrorCodeBadRequest, "workspace_id required") -} - -// --- Cleanup --- - -// cleanupTaskDeleter records the task IDs a cleanup sweep deletes. -type cleanupTaskDeleter struct{ ids []string } - -func (d *cleanupTaskDeleter) DeleteTask(_ context.Context, taskID string) error { - d.ids = append(d.ids, taskID) - return nil -} - -func TestWSCleanupReviewTasksDeletesTasksForMergedMRs(t *testing.T) { - client := NewMockClient(DefaultHost) - svc, store, _ := newWSFixture(t, client) - ctx := context.Background() - seedWorkspace(t, store, "ws-1") - deleter := &cleanupTaskDeleter{} - svc.SetTaskDeleter(deleter) - - const project, iid = "team/repo", 7 - watch := &ReviewWatch{WorkspaceID: "ws-1", Enabled: true, CleanupPolicy: CleanupPolicyAlways} - if err := store.CreateReviewWatch(ctx, watch); err != nil { - t.Fatalf("create review watch: %v", err) - } - if _, err := store.ReserveReviewMRTask(ctx, watch.ID, project, iid, "url"); err != nil { - t.Fatalf("reserve review MR task: %v", err) - } - if err := store.AssignReviewMRTaskID(ctx, watch.ID, project, iid, "task-merged"); err != nil { - t.Fatalf("assign review MR task: %v", err) - } - client.SeedMR(project, &MR{IID: iid, State: gitlabStateMerged}) - - resp, err := wsCleanupReviewTasks(svc)(ctx, - wsRequest(t, ws.ActionGitLabCleanupReviewTasks, nil)) - - var body map[string]int - wsOK(t, resp, err, ws.ActionGitLabCleanupReviewTasks, &body) - if body[respKeyDeleted] != 1 { - t.Errorf("payload = %v, want {%q:1}", body, respKeyDeleted) - } - if len(deleter.ids) != 1 || deleter.ids[0] != "task-merged" { - t.Errorf("deleted task ids = %v, want [task-merged]", deleter.ids) - } -} - -func TestWSCleanupReviewTasksReportsMissingDeleterAsInternalError(t *testing.T) { - svc, _, _ := newWSFixture(t, NewMockClient(DefaultHost)) - - resp, err := wsCleanupReviewTasks(svc)(context.Background(), - wsRequest(t, ws.ActionGitLabCleanupReviewTasks, nil)) - - wsErr(t, resp, err, ws.ActionGitLabCleanupReviewTasks, ws.ErrorCodeInternalError, - "task deleter not configured") -} - -func TestWSCleanupIssueTasksDeletesTasksForClosedIssues(t *testing.T) { - client := NewMockClient(DefaultHost) - svc, store, _ := newWSFixture(t, client) - ctx := context.Background() - seedWorkspace(t, store, "ws-1") - deleter := &cleanupTaskDeleter{} - svc.SetTaskDeleter(deleter) - - const project, iid = "team/repo", 5 - watch := &IssueWatch{WorkspaceID: "ws-1", Enabled: true, CleanupPolicy: CleanupPolicyAlways} - if err := store.CreateIssueWatch(ctx, watch); err != nil { - t.Fatalf("create issue watch: %v", err) - } - if _, err := store.ReserveIssueWatchTask(ctx, watch.ID, project, iid, "url"); err != nil { - t.Fatalf("reserve issue task: %v", err) - } - if err := store.AssignIssueWatchTaskID(ctx, watch.ID, project, iid, "task-closed"); err != nil { - t.Fatalf("assign issue task: %v", err) - } - client.SeedIssue(project, &Issue{IID: iid, State: gitlabStateClosed}) - - resp, err := wsCleanupIssueTasks(svc)(ctx, - wsRequest(t, ws.ActionGitLabCleanupIssueTasks, nil)) - - var body map[string]int - wsOK(t, resp, err, ws.ActionGitLabCleanupIssueTasks, &body) - if body[respKeyDeleted] != 1 { - t.Errorf("payload = %v, want {%q:1}", body, respKeyDeleted) - } - if len(deleter.ids) != 1 || deleter.ids[0] != "task-closed" { - t.Errorf("deleted task ids = %v, want [task-closed]", deleter.ids) - } -} - -func TestWSCleanupIssueTasksReportsMissingDeleterAsInternalError(t *testing.T) { - svc, _, _ := newWSFixture(t, NewMockClient(DefaultHost)) - - resp, err := wsCleanupIssueTasks(svc)(context.Background(), - wsRequest(t, ws.ActionGitLabCleanupIssueTasks, nil)) - - wsErr(t, resp, err, ws.ActionGitLabCleanupIssueTasks, ws.ErrorCodeInternalError, - "task deleter not configured") -} diff --git a/apps/backend/internal/gitlab/handlers_ws_test.go b/apps/backend/internal/gitlab/handlers_ws_test.go deleted file mode 100644 index c51ab4e620..0000000000 --- a/apps/backend/internal/gitlab/handlers_ws_test.go +++ /dev/null @@ -1,484 +0,0 @@ -package gitlab - -import ( - "context" - "encoding/json" - "errors" - "testing" - - "github.com/kandev/kandev/internal/common/logger" - ws "github.com/kandev/kandev/pkg/websocket" -) - -// --- Shared WS handler fixture --- -// -// The WS surface in handlers.go is the legacy, workspace-unscoped GitLab -// action set: every handler closes over the package Service and translates a -// ws.Message into one service call. These helpers drive a handler directly -// and decode the envelope it returns, so the tests can assert the wire -// contract (error code, reason string, payload keys) rather than merely -// executing the closure. - -func newWSFixture(t *testing.T, client Client) (*Service, *Store, *logger.Logger) { - t.Helper() - log := newTestLogger(t) - store := newTestStore(t) - svc := NewService(DefaultHost, client, AuthMethodPAT, nil, log) - svc.SetStore(store) - return svc, store, log -} - -// wsRequest builds a request envelope with payload marshalled as JSON. -func wsRequest(t *testing.T, action string, payload interface{}) *ws.Message { - t.Helper() - msg, err := ws.NewRequest("req-42", action, payload) - if err != nil { - t.Fatalf("build %s request: %v", action, err) - } - return msg -} - -// wsRawRequest builds a request envelope carrying a verbatim payload, used to -// exercise the malformed-payload branches that a marshalled Go value cannot -// produce. -func wsRawRequest(action, rawPayload string) *ws.Message { - return &ws.Message{ - ID: "req-42", - Type: ws.MessageTypeRequest, - Action: action, - Payload: json.RawMessage(rawPayload), - } -} - -// wsOK asserts a success envelope that echoes the request's correlation ID and -// action, then decodes the payload into out. -func wsOK(t *testing.T, resp *ws.Message, err error, action string, out interface{}) { - t.Helper() - if err != nil { - t.Fatalf("handler returned a transport error: %v", err) - } - if resp == nil { - t.Fatal("handler returned a nil message") - } - if resp.Type != ws.MessageTypeResponse { - t.Fatalf("type = %q, want %q (payload: %s)", resp.Type, ws.MessageTypeResponse, resp.Payload) - } - if resp.ID != "req-42" { - t.Errorf("id = %q, want the request id echoed back", resp.ID) - } - if resp.Action != action { - t.Errorf("action = %q, want %q", resp.Action, action) - } - if out == nil { - return - } - if decodeErr := json.Unmarshal(resp.Payload, out); decodeErr != nil { - t.Fatalf("decode payload %s: %v", resp.Payload, decodeErr) - } -} - -// wsErr asserts an error envelope with the expected code and reason and -// returns the decoded error payload. -func wsErr(t *testing.T, resp *ws.Message, err error, action, code, reason string) ws.ErrorPayload { - t.Helper() - if err != nil { - t.Fatalf("handler returned a transport error: %v", err) - } - if resp == nil { - t.Fatal("handler returned a nil message") - } - if resp.Type != ws.MessageTypeError { - t.Fatalf("type = %q, want %q (payload: %s)", resp.Type, ws.MessageTypeError, resp.Payload) - } - if resp.ID != "req-42" { - t.Errorf("id = %q, want the request id echoed back", resp.ID) - } - if resp.Action != action { - t.Errorf("action = %q, want %q", resp.Action, action) - } - var payload ws.ErrorPayload - if decodeErr := json.Unmarshal(resp.Payload, &payload); decodeErr != nil { - t.Fatalf("decode error payload %s: %v", resp.Payload, decodeErr) - } - if payload.Code != code { - t.Errorf("error code = %q, want %q", payload.Code, code) - } - if reason != "" && payload.Message != reason { - t.Errorf("error message = %q, want %q", payload.Message, reason) - } - return payload -} - -// failingSecretProvider makes Service.GetStatus fail at its findTokenSecret -// step, which is the only internal-error path wsStatus has. -type failingSecretProvider struct{ err error } - -func (f *failingSecretProvider) List(context.Context) ([]*SecretListItem, error) { - return nil, f.err -} - -func (f *failingSecretProvider) Reveal(context.Context, string) (string, error) { - return "", f.err -} - -// --- Status --- - -func TestWSStatusReturnsServiceStatus(t *testing.T) { - client := NewMockClient(DefaultHost) - client.SetUser("alice") - svc, _, log := newWSFixture(t, client) - - resp, err := wsStatus(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabStatus, nil)) - - var status Status - wsOK(t, resp, err, ws.ActionGitLabStatus, &status) - if !status.Authenticated { - t.Error("authenticated = false, want true for the mock client") - } - if status.Username != "alice" { - t.Errorf("username = %q, want alice", status.Username) - } - if status.AuthMethod != AuthMethodPAT { - t.Errorf("auth_method = %q, want %q", status.AuthMethod, AuthMethodPAT) - } - if status.Host != DefaultHost { - t.Errorf("host = %q, want %q", status.Host, DefaultHost) - } -} - -func TestWSStatusMapsSecretLookupFailureToInternalError(t *testing.T) { - log := newTestLogger(t) - svc := NewService(DefaultHost, NewMockClient(DefaultHost), AuthMethodPAT, - &failingSecretProvider{err: errors.New("vault offline")}, log) - - resp, err := wsStatus(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabStatus, nil)) - - payload := wsErr(t, resp, err, ws.ActionGitLabStatus, ws.ErrorCodeInternalError, "") - if payload.Message == "" { - t.Error("internal error message is empty; the cause must reach the client") - } -} - -// --- Task MR listing --- - -func TestWSListTaskMRsByTaskReturnsOnlyThatTasksRows(t *testing.T) { - svc, store, log := newWSFixture(t, NewMockClient(DefaultHost)) - ctx := context.Background() - seedWorkspace(t, store, "ws-1") - seedTask(t, store, "task-a", "ws-1") - seedTask(t, store, "task-b", "ws-1") - if err := store.UpsertTaskMR(ctx, newTestMR("task-a", "repo-1", "group/a", 11)); err != nil { - t.Fatalf("seed task-a MR: %v", err) - } - if err := store.UpsertTaskMR(ctx, newTestMR("task-b", "repo-1", "group/b", 22)); err != nil { - t.Fatalf("seed task-b MR: %v", err) - } - - resp, err := wsListTaskMRs(svc, log)(ctx, - wsRequest(t, ws.ActionGitLabTaskMRsList, map[string]string{"task_id": "task-a"})) - - var body struct { - TaskMRs []*TaskMR `json:"task_mrs"` - } - wsOK(t, resp, err, ws.ActionGitLabTaskMRsList, &body) - if len(body.TaskMRs) != 1 { - t.Fatalf("task_mrs = %d rows, want exactly task-a's single row", len(body.TaskMRs)) - } - if body.TaskMRs[0].ProjectPath != "group/a" || body.TaskMRs[0].MRIID != 11 { - t.Errorf("row = %s!%d, want group/a!11", body.TaskMRs[0].ProjectPath, body.TaskMRs[0].MRIID) - } -} - -func TestWSListTaskMRsByWorkspaceGroupsRowsByTask(t *testing.T) { - svc, store, log := newWSFixture(t, NewMockClient(DefaultHost)) - ctx := context.Background() - seedWorkspace(t, store, "ws-1") - seedTask(t, store, "task-a", "ws-1") - seedTask(t, store, "task-b", "ws-1") - for _, mr := range []*TaskMR{ - newTestMR("task-a", "repo-1", "group/a", 11), - newTestMR("task-b", "repo-1", "group/b", 22), - } { - if err := store.UpsertTaskMR(ctx, mr); err != nil { - t.Fatalf("seed %s MR: %v", mr.TaskID, err) - } - } - - resp, err := wsListTaskMRs(svc, log)(ctx, - wsRequest(t, ws.ActionGitLabTaskMRsList, map[string]string{"workspace_id": "ws-1"})) - - var body TaskMRsResponse - wsOK(t, resp, err, ws.ActionGitLabTaskMRsList, &body) - if len(body.TaskMRs) != 2 { - t.Fatalf("grouped tasks = %d, want 2 (%v)", len(body.TaskMRs), body.TaskMRs) - } - if got := body.TaskMRs["task-a"]; len(got) != 1 || got[0].MRIID != 11 { - t.Errorf("task-a group = %+v, want the single !11 row", got) - } -} - -// TestWSListTaskMRsRejectsMalformedPayload pins the comment in handlers.go: a -// payload that fails to parse must not fall through to the "list everything in -// the workspace" branch, which would return more rows than the caller asked -// for. -func TestWSListTaskMRsRejectsMalformedPayload(t *testing.T) { - svc, store, log := newWSFixture(t, NewMockClient(DefaultHost)) - seedWorkspace(t, store, "ws-1") - - resp, err := wsListTaskMRs(svc, log)(context.Background(), - wsRawRequest(ws.ActionGitLabTaskMRsList, `{"task_id":12345}`)) - - wsErr(t, resp, err, ws.ActionGitLabTaskMRsList, ws.ErrorCodeBadRequest, errMsgInvalidPayload) -} - -func TestWSListTaskMRsRequiresWorkspaceOrTask(t *testing.T) { - svc, _, log := newWSFixture(t, NewMockClient(DefaultHost)) - - resp, err := wsListTaskMRs(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabTaskMRsList, map[string]string{})) - - wsErr(t, resp, err, ws.ActionGitLabTaskMRsList, ws.ErrorCodeBadRequest, - "workspace_id or task_id required") -} - -func TestWSGetTaskMRRequiresTaskID(t *testing.T) { - svc, _, log := newWSFixture(t, NewMockClient(DefaultHost)) - - for name, msg := range map[string]*ws.Message{ - "absent": wsRequest(t, ws.ActionGitLabTaskMRGet, map[string]string{}), - "malformed": wsRawRequest(ws.ActionGitLabTaskMRGet, `{"task_id":[]}`), - } { - t.Run(name, func(t *testing.T) { - resp, err := wsGetTaskMR(svc, log)(context.Background(), msg) - wsErr(t, resp, err, ws.ActionGitLabTaskMRGet, ws.ErrorCodeBadRequest, "task_id required") - }) - } -} - -func TestWSGetTaskMRReturnsRowsForTask(t *testing.T) { - svc, store, log := newWSFixture(t, NewMockClient(DefaultHost)) - ctx := context.Background() - seedWorkspace(t, store, "ws-1") - seedTask(t, store, "task-a", "ws-1") - if err := store.UpsertTaskMR(ctx, newTestMR("task-a", "repo-1", "group/a", 7)); err != nil { - t.Fatalf("seed MR: %v", err) - } - - resp, err := wsGetTaskMR(svc, log)(ctx, - wsRequest(t, ws.ActionGitLabTaskMRGet, map[string]string{"task_id": "task-a"})) - - var body struct { - TaskMRs []*TaskMR `json:"task_mrs"` - } - wsOK(t, resp, err, ws.ActionGitLabTaskMRGet, &body) - if len(body.TaskMRs) != 1 || body.TaskMRs[0].MRIID != 7 { - t.Fatalf("task_mrs = %+v, want the single !7 row", body.TaskMRs) - } -} - -// --- MR feedback / files / commits --- - -func TestWSGetMRFeedbackValidatesProjectAndIID(t *testing.T) { - svc, _, log := newWSFixture(t, NewMockClient(DefaultHost)) - handler := wsGetMRFeedback(svc, log) - - cases := map[string]*ws.Message{ - "missing project": wsRequest(t, ws.ActionGitLabMRFeedbackGet, map[string]interface{}{"iid": 3}), - "zero iid": wsRequest(t, ws.ActionGitLabMRFeedbackGet, map[string]interface{}{"project": "g/p", "iid": 0}), - "negative iid": wsRequest(t, ws.ActionGitLabMRFeedbackGet, map[string]interface{}{"project": "g/p", "iid": -1}), - "malformed": wsRawRequest(ws.ActionGitLabMRFeedbackGet, `{"project":true}`), - } - for name, msg := range cases { - t.Run(name, func(t *testing.T) { - resp, err := handler(context.Background(), msg) - wsErr(t, resp, err, ws.ActionGitLabMRFeedbackGet, ws.ErrorCodeBadRequest, "project and iid required") - }) - } -} - -func TestWSGetMRFeedbackReturnsClientFeedback(t *testing.T) { - client := NewMockClient(DefaultHost) - client.SetUser("alice") - iid := client.SeedMR("group/p", &MR{Title: "feat: x", State: "opened"}) - client.SeedApprovals("group/p", iid, []MRApproval{{Username: "bob"}}, 1) - svc, _, log := newWSFixture(t, client) - - resp, err := wsGetMRFeedback(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabMRFeedbackGet, map[string]interface{}{"project": "group/p", "iid": iid})) - - var feedback MRFeedback - wsOK(t, resp, err, ws.ActionGitLabMRFeedbackGet, &feedback) - if len(feedback.Approvals) != 1 || feedback.Approvals[0].Username != "bob" { - t.Errorf("approvals = %+v, want bob's single approval", feedback.Approvals) - } -} - -func TestWSGetMRFilesReturnsSeededFiles(t *testing.T) { - client := NewMockClient(DefaultHost) - iid := client.SeedMR("group/p", &MR{Title: "feat: x"}) - client.SeedFiles("group/p", iid, []MRFile{{Filename: "a.go", Additions: 3}}) - svc, _, log := newWSFixture(t, client) - - resp, err := wsGetMRFiles(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabMRFilesGet, map[string]interface{}{"project": "group/p", "iid": iid})) - - var body struct { - Files []MRFile `json:"files"` - } - wsOK(t, resp, err, ws.ActionGitLabMRFilesGet, &body) - if len(body.Files) != 1 || body.Files[0].Filename != "a.go" { - t.Fatalf("files = %+v, want the single a.go entry", body.Files) - } -} - -func TestWSGetMRFilesValidatesProjectAndIID(t *testing.T) { - svc, _, log := newWSFixture(t, NewMockClient(DefaultHost)) - - resp, err := wsGetMRFiles(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabMRFilesGet, map[string]interface{}{"project": "", "iid": 1})) - - wsErr(t, resp, err, ws.ActionGitLabMRFilesGet, ws.ErrorCodeBadRequest, "project and iid required") -} - -func TestWSGetMRCommitsReturnsSeededCommits(t *testing.T) { - client := NewMockClient(DefaultHost) - iid := client.SeedMR("group/p", &MR{Title: "feat: x"}) - client.SeedCommits("group/p", iid, []MRCommitInfo{{SHA: "abc123", Message: "feat: x"}}) - svc, _, log := newWSFixture(t, client) - - resp, err := wsGetMRCommits(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabMRCommitsGet, map[string]interface{}{"project": "group/p", "iid": iid})) - - var body struct { - Commits []MRCommitInfo `json:"commits"` - } - wsOK(t, resp, err, ws.ActionGitLabMRCommitsGet, &body) - if len(body.Commits) != 1 || body.Commits[0].SHA != "abc123" { - t.Fatalf("commits = %+v, want the single abc123 entry", body.Commits) - } -} - -func TestWSGetMRCommitsValidatesProjectAndIID(t *testing.T) { - svc, _, log := newWSFixture(t, NewMockClient(DefaultHost)) - - resp, err := wsGetMRCommits(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabMRCommitsGet, map[string]interface{}{"project": "g/p"})) - - wsErr(t, resp, err, ws.ActionGitLabMRCommitsGet, ws.ErrorCodeBadRequest, "project and iid required") -} - -// --- Sync --- - -func TestWSSyncTaskMRRequiresTaskID(t *testing.T) { - svc, _, log := newWSFixture(t, NewMockClient(DefaultHost)) - - resp, err := wsSyncTaskMR(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabTaskMRSync, map[string]string{})) - - wsErr(t, resp, err, ws.ActionGitLabTaskMRSync, ws.ErrorCodeBadRequest, "task_id required") -} - -func TestWSSyncTaskMRReportsMissingStoreAsInternalError(t *testing.T) { - log := newTestLogger(t) - svc := NewService(DefaultHost, NewMockClient(DefaultHost), AuthMethodPAT, nil, log) - - resp, err := wsSyncTaskMR(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabTaskMRSync, map[string]string{"task_id": "task-a"})) - - wsErr(t, resp, err, ws.ActionGitLabTaskMRSync, ws.ErrorCodeInternalError, - "gitlab store not configured") -} - -func TestWSSyncTaskMRReturnsRefreshedRows(t *testing.T) { - client := NewMockClient(DefaultHost) - iid := client.SeedMR("group/p", &MR{Title: "feat: refreshed", State: "opened"}) - svc, store, log := newWSFixture(t, client) - ctx := context.Background() - seedWorkspace(t, store, "ws-1") - seedTask(t, store, "task-a", "ws-1") - row := newTestMR("task-a", "repo-1", "group/p", iid) - row.MRTitle = "stale title" - if err := store.UpsertTaskMR(ctx, row); err != nil { - t.Fatalf("seed MR row: %v", err) - } - - resp, err := wsSyncTaskMR(svc, log)(ctx, - wsRequest(t, ws.ActionGitLabTaskMRSync, map[string]string{"task_id": "task-a"})) - - var body struct { - TaskMRs []*TaskMR `json:"task_mrs"` - } - wsOK(t, resp, err, ws.ActionGitLabTaskMRSync, &body) - if len(body.TaskMRs) != 1 { - t.Fatalf("task_mrs = %d rows, want 1", len(body.TaskMRs)) - } - if body.TaskMRs[0].MRTitle != "feat: refreshed" { - t.Errorf("title = %q, want the upstream title to have replaced the stale one", - body.TaskMRs[0].MRTitle) - } -} - -// --- Stats --- - -// statsRecordingClient records the filters GetStats sends upstream so the test -// can assert the three distinct queries, not just the aggregate numbers. -type statsRecordingClient struct { - *MockClient - mrFilters []string -} - -func (c *statsRecordingClient) SearchMRsPaged(ctx context.Context, filter, customQuery string, page, perPage int) (*MRSearchPage, error) { - c.mrFilters = append(c.mrFilters, filter) - return c.MockClient.SearchMRsPaged(ctx, filter, customQuery, page, perPage) -} - -func TestWSGetStatsReturnsCountsAndQueriesEachScope(t *testing.T) { - client := &statsRecordingClient{MockClient: NewMockClient(DefaultHost)} - client.SetUser("alice") - client.SeedMR("group/p", &MR{Title: "one", State: "opened"}) - client.SeedMR("group/q", &MR{Title: "two", State: "opened"}) - client.SeedIssue("group/p", &Issue{IID: 1, Title: "bug", State: "opened"}) - svc, _, log := newWSFixture(t, client) - - resp, err := wsGetStats(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabStats, nil)) - - var stats Stats - wsOK(t, resp, err, ws.ActionGitLabStats, &stats) - if stats.OpenMRs != 2 { - t.Errorf("open_mrs = %d, want 2", stats.OpenMRs) - } - if stats.MRsAwaitingMyReview != 2 { - t.Errorf("mrs_awaiting_my_review = %d, want 2", stats.MRsAwaitingMyReview) - } - if stats.OpenIssuesAssignedMe != 1 { - t.Errorf("open_issues_assigned_me = %d, want 1", stats.OpenIssuesAssignedMe) - } - want := []string{"scope=created_by_me&state=opened", "reviewer_username=alice&state=opened"} - if len(client.mrFilters) != len(want) { - t.Fatalf("MR search filters = %q, want %q", client.mrFilters, want) - } - for i, filter := range want { - if client.mrFilters[i] != filter { - t.Errorf("MR search filter[%d] = %q, want %q", i, client.mrFilters[i], filter) - } - } -} - -// TestWSGetStatsDegradesToZeroWithoutAuthenticatedUser pins the documented -// behavior of Service.GetStats: an unresolvable user yields empty counts -// rather than an error envelope, so the dashboard still renders. -func TestWSGetStatsDegradesToZeroWithoutAuthenticatedUser(t *testing.T) { - svc, _, log := newWSFixture(t, NewMockClient(DefaultHost)) - - resp, err := wsGetStats(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabStats, nil)) - - var stats Stats - wsOK(t, resp, err, ws.ActionGitLabStats, &stats) - if stats.OpenMRs != 0 || stats.OpenIssuesAssignedMe != 0 { - t.Errorf("stats = %+v, want zeroed counts when no user resolves", stats) - } -} diff --git a/apps/backend/internal/gitlab/handlers_ws_watches_test.go b/apps/backend/internal/gitlab/handlers_ws_watches_test.go deleted file mode 100644 index 0507c361d0..0000000000 --- a/apps/backend/internal/gitlab/handlers_ws_watches_test.go +++ /dev/null @@ -1,563 +0,0 @@ -package gitlab - -import ( - "context" - "testing" - - "github.com/kandev/kandev/internal/common/logger" - ws "github.com/kandev/kandev/pkg/websocket" -) - -// newWatchWSFixture builds a service whose watch-dependency validators accept -// the "ws-1" fixture identifiers, so the WS create/update handlers exercise the -// real validation path rather than a stub that waves everything through. -func newWatchWSFixture(t *testing.T) (*Service, *Store, *logger.Logger) { - t.Helper() - svc, store := newDependencyTestService(t) - seedWorkspace(t, store, "ws-1") - seedWorkspace(t, store, "ws-2") - return svc, store, newTestLogger(t) -} - -// --- Review watches --- - -func TestWSListReviewWatchesScopesToWorkspaceWhenGiven(t *testing.T) { - svc, store, log := newWatchWSFixture(t) - ctx := context.Background() - mine := validReviewWatchRow() - other := validReviewWatchRow() - other.WorkspaceID = "ws-2" - for _, w := range []*ReviewWatch{mine, other} { - if err := store.CreateReviewWatch(ctx, w); err != nil { - t.Fatalf("seed review watch: %v", err) - } - } - - resp, err := wsListReviewWatches(svc, log)(ctx, - wsRequest(t, ws.ActionGitLabReviewWatchesList, map[string]string{"workspace_id": "ws-1"})) - - var body struct { - Watches []*ReviewWatch `json:"watches"` - } - wsOK(t, resp, err, ws.ActionGitLabReviewWatchesList, &body) - if len(body.Watches) != 1 { - t.Fatalf("watches = %d, want only the ws-1 watch", len(body.Watches)) - } - if body.Watches[0].WorkspaceID != "ws-1" { - t.Errorf("watch workspace = %q, want ws-1", body.Watches[0].WorkspaceID) - } -} - -// TestWSListReviewWatchesWithoutWorkspaceListsAll pins the deliberate fallback -// in wsListReviewWatches: an absent workspace_id lists every workspace's -// watches. If that ever needs to become a rejection, this test is the one to -// change. -func TestWSListReviewWatchesWithoutWorkspaceListsAll(t *testing.T) { - svc, store, log := newWatchWSFixture(t) - ctx := context.Background() - other := validReviewWatchRow() - other.WorkspaceID = "ws-2" - for _, w := range []*ReviewWatch{validReviewWatchRow(), other} { - if err := store.CreateReviewWatch(ctx, w); err != nil { - t.Fatalf("seed review watch: %v", err) - } - } - - resp, err := wsListReviewWatches(svc, log)(ctx, - wsRequest(t, ws.ActionGitLabReviewWatchesList, map[string]string{})) - - var body struct { - Watches []*ReviewWatch `json:"watches"` - } - wsOK(t, resp, err, ws.ActionGitLabReviewWatchesList, &body) - if len(body.Watches) != 2 { - t.Fatalf("watches = %d, want both workspaces' watches", len(body.Watches)) - } -} - -func TestWSListReviewWatchesRejectsMalformedPayload(t *testing.T) { - svc, _, log := newWatchWSFixture(t) - - resp, err := wsListReviewWatches(svc, log)(context.Background(), - wsRawRequest(ws.ActionGitLabReviewWatchesList, `{"workspace_id":7}`)) - - wsErr(t, resp, err, ws.ActionGitLabReviewWatchesList, ws.ErrorCodeBadRequest, errMsgInvalidPayload) -} - -func TestWSCreateReviewWatchPersistsAndReturnsRow(t *testing.T) { - svc, store, log := newWatchWSFixture(t) - ctx := context.Background() - - resp, err := wsCreateReviewWatch(svc, log)(ctx, - wsRequest(t, ws.ActionGitLabReviewWatchCreate, validReviewWatchRequest())) - - var created ReviewWatch - wsOK(t, resp, err, ws.ActionGitLabReviewWatchCreate, &created) - if created.ID == "" { - t.Fatal("created watch has no id") - } - if created.WorkspaceID != "ws-1" || created.RepositoryID != "repo-valid" { - t.Errorf("created watch = %+v, want the requested workspace/repository", created) - } - stored, err := store.GetReviewWatch(ctx, created.ID) - if err != nil || stored == nil { - t.Fatalf("watch was not persisted: row=%v err=%v", stored, err) - } -} - -func TestWSCreateReviewWatchRejectsInvalidDependencies(t *testing.T) { - svc, _, log := newWatchWSFixture(t) - req := validReviewWatchRequest() - req.RepositoryID = "repo-other" // belongs to ws-2 - - resp, err := wsCreateReviewWatch(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabReviewWatchCreate, req)) - - wsErr(t, resp, err, ws.ActionGitLabReviewWatchCreate, ws.ErrorCodeInternalError, "") -} - -func TestWSCreateReviewWatchRejectsMalformedPayload(t *testing.T) { - svc, _, log := newWatchWSFixture(t) - - resp, err := wsCreateReviewWatch(svc, log)(context.Background(), - wsRawRequest(ws.ActionGitLabReviewWatchCreate, `{"workspace_id":[]}`)) - - wsErr(t, resp, err, ws.ActionGitLabReviewWatchCreate, ws.ErrorCodeBadRequest, errMsgInvalidPayload) -} - -func TestWSUpdateReviewWatchAppliesPatch(t *testing.T) { - svc, store, log := newWatchWSFixture(t) - ctx := context.Background() - watch := validReviewWatchRow() - if err := store.CreateReviewWatch(ctx, watch); err != nil { - t.Fatalf("seed review watch: %v", err) - } - - resp, err := wsUpdateReviewWatch(svc, log)(ctx, - wsRequest(t, ws.ActionGitLabReviewWatchUpdate, map[string]interface{}{ - "id": watch.ID, - "enabled": false, - })) - - var body map[string]bool - wsOK(t, resp, err, ws.ActionGitLabReviewWatchUpdate, &body) - if !body["updated"] { - t.Errorf("payload = %v, want {\"updated\":true}", body) - } - stored, err := store.GetReviewWatch(ctx, watch.ID) - if err != nil { - t.Fatalf("reload watch: %v", err) - } - if stored.Enabled { - t.Error("watch is still enabled; the patch did not reach the store") - } -} - -func TestWSUpdateReviewWatchRequiresID(t *testing.T) { - svc, _, log := newWatchWSFixture(t) - - resp, err := wsUpdateReviewWatch(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabReviewWatchUpdate, map[string]interface{}{"enabled": false})) - - wsErr(t, resp, err, ws.ActionGitLabReviewWatchUpdate, ws.ErrorCodeBadRequest, errMsgIDRequired) -} - -func TestWSUpdateReviewWatchReportsUnknownIDAsInternalError(t *testing.T) { - svc, _, log := newWatchWSFixture(t) - - resp, err := wsUpdateReviewWatch(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabReviewWatchUpdate, map[string]interface{}{ - "id": "does-not-exist", "enabled": false, - })) - - wsErr(t, resp, err, ws.ActionGitLabReviewWatchUpdate, ws.ErrorCodeInternalError, "") -} - -func TestWSDeleteReviewWatchRemovesRow(t *testing.T) { - svc, store, log := newWatchWSFixture(t) - ctx := context.Background() - watch := validReviewWatchRow() - if err := store.CreateReviewWatch(ctx, watch); err != nil { - t.Fatalf("seed review watch: %v", err) - } - - resp, err := wsDeleteReviewWatch(svc, log)(ctx, - wsRequest(t, ws.ActionGitLabReviewWatchDelete, map[string]string{"id": watch.ID})) - - var body map[string]bool - wsOK(t, resp, err, ws.ActionGitLabReviewWatchDelete, &body) - if !body[respKeyDeleted] { - t.Errorf("payload = %v, want {\"deleted\":true}", body) - } - remaining, err := store.ListReviewWatches(ctx, "ws-1") - if err != nil { - t.Fatalf("list review watches: %v", err) - } - if len(remaining) != 0 { - t.Errorf("watches remaining = %d, want 0", len(remaining)) - } -} - -func TestWSDeleteReviewWatchRequiresID(t *testing.T) { - svc, _, log := newWatchWSFixture(t) - - resp, err := wsDeleteReviewWatch(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabReviewWatchDelete, map[string]string{})) - - wsErr(t, resp, err, ws.ActionGitLabReviewWatchDelete, ws.ErrorCodeBadRequest, errMsgIDRequired) -} - -func TestWSTriggerReviewWatchRequiresID(t *testing.T) { - svc, _, log := newWatchWSFixture(t) - - resp, err := wsTriggerReviewWatch(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabReviewTrigger, map[string]string{})) - - wsErr(t, resp, err, ws.ActionGitLabReviewTrigger, ws.ErrorCodeBadRequest, errMsgIDRequired) -} - -func TestWSTriggerReviewWatchReportsUnknownWatch(t *testing.T) { - svc, _, log := newWatchWSFixture(t) - - resp, err := wsTriggerReviewWatch(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabReviewTrigger, map[string]string{"id": "nope"})) - - wsErr(t, resp, err, ws.ActionGitLabReviewTrigger, ws.ErrorCodeInternalError, "") -} - -// TestWSTriggerAllReviewChecksCountsOnlyEnabledWatches seeds one enabled and -// one disabled watch over the same MR. The count is the number of MRs found -// across enabled watches, so a handler that ignored the enabled flag would -// report 2 and one that always returned 0 would report 0 — only the correct -// filter yields 1. -func TestWSTriggerAllReviewChecksCountsOnlyEnabledWatches(t *testing.T) { - svc, store, log := newWatchWSFixture(t) - ctx := context.Background() - client := NewMockClient(DefaultHost) - client.SetUser("kandev-tester") - client.SeedMR("group/p", &MR{IID: 1, Title: "needs review", WebURL: "https://x/1", - Reviewers: []MRReviewer{{Username: "kandev-tester"}}}) - svc.workspaceClients["ws-1"] = client - - disabled := validReviewWatchRow() - disabled.Enabled = false - for _, watch := range []*ReviewWatch{validReviewWatchRow(), disabled} { - if err := store.CreateReviewWatch(ctx, watch); err != nil { - t.Fatalf("seed review watch: %v", err) - } - } - - resp, err := wsTriggerAllReviewChecks(svc, log)(ctx, - wsRequest(t, ws.ActionGitLabReviewTriggerAll, nil)) - - var body map[string]int - wsOK(t, resp, err, ws.ActionGitLabReviewTriggerAll, &body) - if body["count"] != 1 { - t.Errorf("count = %d, want 1 — the enabled watch contributes its MR and "+ - "the disabled one contributes nothing", body["count"]) - } -} - -// --- MR watches --- - -func TestWSListMRWatchesSelectsBranchBySessionThenTaskThenAll(t *testing.T) { - svc, store, log := newWatchWSFixture(t) - ctx := context.Background() - seedTask(t, store, "task-a", "ws-1") - seedTask(t, store, "task-b", "ws-1") - if _, err := svc.CreateMRWatch(ctx, "sess-a", "task-a", "repo-1", "group/a", 1, "feat/a"); err != nil { - t.Fatalf("seed watch a: %v", err) - } - if _, err := svc.CreateMRWatch(ctx, "sess-b", "task-b", "repo-1", "group/b", 2, "feat/b"); err != nil { - t.Fatalf("seed watch b: %v", err) - } - - tests := []struct { - name string - payload map[string]string - want []string - }{ - {"by session", map[string]string{"session_id": "sess-a"}, []string{"group/a"}}, - {"by task", map[string]string{"task_id": "task-b"}, []string{"group/b"}}, - {"all active", map[string]string{}, []string{"group/a", "group/b"}}, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - resp, err := wsListMRWatches(svc, log)(ctx, - wsRequest(t, ws.ActionGitLabMRWatchesList, test.payload)) - - var body struct { - Watches []*MRWatch `json:"watches"` - } - wsOK(t, resp, err, ws.ActionGitLabMRWatchesList, &body) - if len(body.Watches) != len(test.want) { - t.Fatalf("watches = %d, want %d (%v)", len(body.Watches), len(test.want), body.Watches) - } - got := map[string]bool{} - for _, w := range body.Watches { - got[w.ProjectPath] = true - } - for _, project := range test.want { - if !got[project] { - t.Errorf("watch for %q missing from %v", project, got) - } - } - }) - } -} - -func TestWSListMRWatchesRejectsMalformedPayload(t *testing.T) { - svc, _, log := newWatchWSFixture(t) - - resp, err := wsListMRWatches(svc, log)(context.Background(), - wsRawRequest(ws.ActionGitLabMRWatchesList, `{"session_id":{}}`)) - - wsErr(t, resp, err, ws.ActionGitLabMRWatchesList, ws.ErrorCodeBadRequest, errMsgInvalidPayload) -} - -func TestWSDeleteMRWatchRemovesRow(t *testing.T) { - svc, store, log := newWatchWSFixture(t) - ctx := context.Background() - seedTask(t, store, "task-a", "ws-1") - watch, err := svc.CreateMRWatch(ctx, "sess-a", "task-a", "repo-1", "group/a", 1, "feat/a") - if err != nil { - t.Fatalf("seed watch: %v", err) - } - - resp, err := wsDeleteMRWatch(svc, log)(ctx, - wsRequest(t, ws.ActionGitLabMRWatchDelete, map[string]string{"id": watch.ID})) - - var body map[string]bool - wsOK(t, resp, err, ws.ActionGitLabMRWatchDelete, &body) - if !body[respKeyDeleted] { - t.Errorf("payload = %v, want {\"deleted\":true}", body) - } - remaining, err := svc.ListActiveMRWatches(ctx) - if err != nil { - t.Fatalf("list active watches: %v", err) - } - if len(remaining) != 0 { - t.Errorf("watches remaining = %d, want 0", len(remaining)) - } -} - -func TestWSDeleteMRWatchRequiresID(t *testing.T) { - svc, _, log := newWatchWSFixture(t) - - resp, err := wsDeleteMRWatch(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabMRWatchDelete, map[string]string{})) - - wsErr(t, resp, err, ws.ActionGitLabMRWatchDelete, ws.ErrorCodeBadRequest, errMsgIDRequired) -} - -// --- Issue watches --- - -func TestWSListIssueWatchesScopesToWorkspaceWhenGiven(t *testing.T) { - svc, store, log := newWatchWSFixture(t) - ctx := context.Background() - other := validIssueWatchRow() - other.WorkspaceID = "ws-2" - for _, w := range []*IssueWatch{validIssueWatchRow(), other} { - if err := store.CreateIssueWatch(ctx, w); err != nil { - t.Fatalf("seed issue watch: %v", err) - } - } - - resp, err := wsListIssueWatches(svc, log)(ctx, - wsRequest(t, ws.ActionGitLabIssueWatchesList, map[string]string{"workspace_id": "ws-2"})) - - var body struct { - Watches []*IssueWatch `json:"watches"` - } - wsOK(t, resp, err, ws.ActionGitLabIssueWatchesList, &body) - if len(body.Watches) != 1 || body.Watches[0].WorkspaceID != "ws-2" { - t.Fatalf("watches = %+v, want only the ws-2 watch", body.Watches) - } -} - -func TestWSListIssueWatchesWithoutWorkspaceListsAll(t *testing.T) { - svc, store, log := newWatchWSFixture(t) - ctx := context.Background() - other := validIssueWatchRow() - other.WorkspaceID = "ws-2" - for _, w := range []*IssueWatch{validIssueWatchRow(), other} { - if err := store.CreateIssueWatch(ctx, w); err != nil { - t.Fatalf("seed issue watch: %v", err) - } - } - - resp, err := wsListIssueWatches(svc, log)(ctx, - wsRequest(t, ws.ActionGitLabIssueWatchesList, map[string]string{})) - - var body struct { - Watches []*IssueWatch `json:"watches"` - } - wsOK(t, resp, err, ws.ActionGitLabIssueWatchesList, &body) - if len(body.Watches) != 2 { - t.Fatalf("watches = %d, want both workspaces' watches", len(body.Watches)) - } -} - -func TestWSListIssueWatchesRejectsMalformedPayload(t *testing.T) { - svc, _, log := newWatchWSFixture(t) - - resp, err := wsListIssueWatches(svc, log)(context.Background(), - wsRawRequest(ws.ActionGitLabIssueWatchesList, `{"workspace_id":false}`)) - - wsErr(t, resp, err, ws.ActionGitLabIssueWatchesList, ws.ErrorCodeBadRequest, errMsgInvalidPayload) -} - -func TestWSCreateIssueWatchPersistsAndReturnsRow(t *testing.T) { - svc, store, log := newWatchWSFixture(t) - ctx := context.Background() - - resp, err := wsCreateIssueWatch(svc, log)(ctx, - wsRequest(t, ws.ActionGitLabIssueWatchCreate, validIssueWatchRequest())) - - var created IssueWatch - wsOK(t, resp, err, ws.ActionGitLabIssueWatchCreate, &created) - if created.ID == "" { - t.Fatal("created watch has no id") - } - stored, err := store.GetIssueWatch(ctx, created.ID) - if err != nil || stored == nil { - t.Fatalf("watch was not persisted: row=%v err=%v", stored, err) - } -} - -func TestWSCreateIssueWatchRejectsInvalidDependencies(t *testing.T) { - svc, _, log := newWatchWSFixture(t) - req := validIssueWatchRequest() - req.AgentProfileID = "agent-missing" - - resp, err := wsCreateIssueWatch(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabIssueWatchCreate, req)) - - wsErr(t, resp, err, ws.ActionGitLabIssueWatchCreate, ws.ErrorCodeInternalError, "") -} - -func TestWSCreateIssueWatchRejectsMalformedPayload(t *testing.T) { - svc, _, log := newWatchWSFixture(t) - - resp, err := wsCreateIssueWatch(svc, log)(context.Background(), - wsRawRequest(ws.ActionGitLabIssueWatchCreate, `"a string, not an object"`)) - - wsErr(t, resp, err, ws.ActionGitLabIssueWatchCreate, ws.ErrorCodeBadRequest, errMsgInvalidPayload) -} - -func TestWSUpdateIssueWatchAppliesPatch(t *testing.T) { - svc, store, log := newWatchWSFixture(t) - ctx := context.Background() - watch := validIssueWatchRow() - if err := store.CreateIssueWatch(ctx, watch); err != nil { - t.Fatalf("seed issue watch: %v", err) - } - - resp, err := wsUpdateIssueWatch(svc, log)(ctx, - wsRequest(t, ws.ActionGitLabIssueWatchUpdate, map[string]interface{}{ - "id": watch.ID, "enabled": false, - })) - - var body map[string]bool - wsOK(t, resp, err, ws.ActionGitLabIssueWatchUpdate, &body) - if !body["updated"] { - t.Errorf("payload = %v, want {\"updated\":true}", body) - } - stored, err := store.GetIssueWatch(ctx, watch.ID) - if err != nil { - t.Fatalf("reload watch: %v", err) - } - if stored.Enabled { - t.Error("watch is still enabled; the patch did not reach the store") - } -} - -func TestWSUpdateIssueWatchRequiresID(t *testing.T) { - svc, _, log := newWatchWSFixture(t) - - resp, err := wsUpdateIssueWatch(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabIssueWatchUpdate, map[string]interface{}{"enabled": true})) - - wsErr(t, resp, err, ws.ActionGitLabIssueWatchUpdate, ws.ErrorCodeBadRequest, errMsgIDRequired) -} - -func TestWSDeleteIssueWatchRemovesRow(t *testing.T) { - svc, store, log := newWatchWSFixture(t) - ctx := context.Background() - watch := validIssueWatchRow() - if err := store.CreateIssueWatch(ctx, watch); err != nil { - t.Fatalf("seed issue watch: %v", err) - } - - resp, err := wsDeleteIssueWatch(svc, log)(ctx, - wsRequest(t, ws.ActionGitLabIssueWatchDelete, map[string]string{"id": watch.ID})) - - var body map[string]bool - wsOK(t, resp, err, ws.ActionGitLabIssueWatchDelete, &body) - if !body[respKeyDeleted] { - t.Errorf("payload = %v, want {\"deleted\":true}", body) - } - remaining, err := store.ListIssueWatches(ctx, "ws-1") - if err != nil { - t.Fatalf("list issue watches: %v", err) - } - if len(remaining) != 0 { - t.Errorf("watches remaining = %d, want 0", len(remaining)) - } -} - -func TestWSDeleteIssueWatchRequiresID(t *testing.T) { - svc, _, log := newWatchWSFixture(t) - - resp, err := wsDeleteIssueWatch(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabIssueWatchDelete, map[string]string{})) - - wsErr(t, resp, err, ws.ActionGitLabIssueWatchDelete, ws.ErrorCodeBadRequest, errMsgIDRequired) -} - -func TestWSTriggerIssueWatchRequiresID(t *testing.T) { - svc, _, log := newWatchWSFixture(t) - - resp, err := wsTriggerIssueWatch(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabIssueTrigger, map[string]string{})) - - wsErr(t, resp, err, ws.ActionGitLabIssueTrigger, ws.ErrorCodeBadRequest, errMsgIDRequired) -} - -func TestWSTriggerIssueWatchReportsUnknownWatch(t *testing.T) { - svc, _, log := newWatchWSFixture(t) - - resp, err := wsTriggerIssueWatch(svc, log)(context.Background(), - wsRequest(t, ws.ActionGitLabIssueTrigger, map[string]string{"id": "nope"})) - - wsErr(t, resp, err, ws.ActionGitLabIssueTrigger, ws.ErrorCodeInternalError, "") -} - -// TestWSTriggerAllIssueChecksCountsOnlyEnabledWatches is the issue mirror of -// the review test above, and discriminates the same three outcomes. -func TestWSTriggerAllIssueChecksCountsOnlyEnabledWatches(t *testing.T) { - svc, store, log := newWatchWSFixture(t) - ctx := context.Background() - client := NewMockClient(DefaultHost) - client.SetUser("kandev-tester") - client.SeedIssue("group/p", &Issue{IID: 3, Title: "bug", WebURL: "https://x/3"}) - svc.workspaceClients["ws-1"] = client - - disabled := validIssueWatchRow() - disabled.Enabled = false - for _, watch := range []*IssueWatch{validIssueWatchRow(), disabled} { - if err := store.CreateIssueWatch(ctx, watch); err != nil { - t.Fatalf("seed issue watch: %v", err) - } - } - - resp, err := wsTriggerAllIssueChecks(svc, log)(ctx, - wsRequest(t, ws.ActionGitLabIssueTriggerAll, nil)) - - var body map[string]int - wsOK(t, resp, err, ws.ActionGitLabIssueTriggerAll, &body) - if body["count"] != 1 { - t.Errorf("count = %d, want 1 — the enabled watch contributes its issue and "+ - "the disabled one contributes nothing", body["count"]) - } -} diff --git a/apps/backend/internal/gitlab/mock_controller.go b/apps/backend/internal/gitlab/mock_controller.go index 0ceb7e4317..1e8cfe5274 100644 --- a/apps/backend/internal/gitlab/mock_controller.go +++ b/apps/backend/internal/gitlab/mock_controller.go @@ -26,6 +26,16 @@ func NewMockController(mock *MockClient, svc *Service, log *logger.Logger) *Mock return &MockController{mock: mock, service: svc, logger: log} } +// RegisterMockRoutes registers mock control endpoints when the service uses a MockClient. +func RegisterMockRoutes(router *gin.Engine, svc *Service, log *logger.Logger) { + mock, ok := svc.Client().(*MockClient) + if !ok { + return + } + NewMockController(mock, svc, log).RegisterRoutes(router) + log.Info("registered GitLab mock control endpoints") +} + // RegisterRoutes wires the mock control endpoints under /api/v1/gitlab/mock. func (c *MockController) RegisterRoutes(router *gin.Engine) { api := router.Group("/api/v1/gitlab/mock") diff --git a/apps/backend/internal/gitlab/security_regression_test.go b/apps/backend/internal/gitlab/security_regression_test.go index cbb3905c2c..a319cc1540 100644 --- a/apps/backend/internal/gitlab/security_regression_test.go +++ b/apps/backend/internal/gitlab/security_regression_test.go @@ -4,8 +4,15 @@ import ( "context" "errors" "fmt" + "go/ast" + "go/parser" + "go/token" "net/http" "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strconv" "strings" "sync/atomic" "testing" @@ -17,62 +24,76 @@ import ( "go.uber.org/zap/zaptest/observer" "github.com/kandev/kandev/internal/common/logger" - ws "github.com/kandev/kandev/pkg/websocket" ) -func TestRegisterRoutesWithDispatcherDoesNotExposeLegacyGitLabActions(t *testing.T) { - dispatcher := ws.NewDispatcher() - router := gin.New() - RegisterRoutesWithDispatcher( - router, - dispatcher, - NewService(DefaultHost, NewNoopClient(DefaultHost), AuthMethodNone, nil, newTestLogger(t)), - newTestLogger(t), - ) - - legacyActions := []string{ - ws.ActionGitLabStatus, - ws.ActionGitLabTaskMRsList, - ws.ActionGitLabTaskMRGet, - ws.ActionGitLabMRFeedbackGet, - ws.ActionGitLabReviewWatchesList, - ws.ActionGitLabReviewWatchCreate, - ws.ActionGitLabReviewWatchUpdate, - ws.ActionGitLabReviewWatchDelete, - ws.ActionGitLabReviewTrigger, - ws.ActionGitLabReviewTriggerAll, - ws.ActionGitLabMRWatchesList, - ws.ActionGitLabMRWatchDelete, - ws.ActionGitLabMRFilesGet, - ws.ActionGitLabMRCommitsGet, - ws.ActionGitLabTaskMRSync, - ws.ActionGitLabStats, - ws.ActionGitLabMRMerge, - ws.ActionGitLabMRApprove, - ws.ActionGitLabMRUnapprove, - ws.ActionGitLabMRSetLabels, - ws.ActionGitLabMRSetAssignees, - ws.ActionGitLabMRDiscussionNew, - ws.ActionGitLabMRDiscussionResolve, - ws.ActionGitLabProjectMergeMethodsGet, - ws.ActionGitLabIssueWatchesList, - ws.ActionGitLabIssueWatchCreate, - ws.ActionGitLabIssueWatchUpdate, - ws.ActionGitLabIssueWatchDelete, - ws.ActionGitLabIssueTrigger, - ws.ActionGitLabIssueTriggerAll, - ws.ActionGitLabActionPresetsList, - ws.ActionGitLabActionPresetsUpdate, - ws.ActionGitLabActionPresetsReset, - ws.ActionGitLabListUserProjects, - ws.ActionGitLabSearchProjects, - ws.ActionGitLabProjectBranches, - ws.ActionGitLabCleanupReviewTasks, - ws.ActionGitLabCleanupIssueTasks, +func TestGitLabRequestSurfaceCannotImportWebSocketTransport(t *testing.T) { + _, sourceFile, _, ok := runtime.Caller(0) + if !ok { + t.Fatal("locate GitLab package") } - for _, action := range legacyActions { - if dispatcher.HasHandler(action) { - t.Errorf("legacy GitLab WebSocket action %q is registered", action) + packageDir := filepath.Dir(sourceFile) + entries, err := os.ReadDir(packageDir) + if err != nil { + t.Fatalf("read GitLab package: %v", err) + } + + for _, entry := range entries { + if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".go") || strings.HasSuffix(entry.Name(), "_test.go") { + continue + } + path := filepath.Join(packageDir, entry.Name()) + file, parseErr := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly) + if parseErr != nil { + t.Fatalf("parse %s: %v", entry.Name(), parseErr) + } + for _, importSpec := range file.Imports { + importPath, unquoteErr := strconv.Unquote(importSpec.Path.Value) + if unquoteErr != nil { + t.Fatalf("read import in %s: %v", entry.Name(), unquoteErr) + } + if importPath == "github.com/kandev/kandev/pkg/websocket" { + t.Errorf("%s imports the WebSocket request transport; GitLab requests must remain HTTP-only", entry.Name()) + } + } + } +} + +func TestWebSocketCatalogContainsOnlyAuthorizedGitLabActions(t *testing.T) { + authorized := map[string]bool{ + "ActionGitLabCheckSessionMR": true, + "ActionGitLabTaskMRUpdated": true, + "ActionGitLabTaskMRAutomationUpdated": true, + } + _, sourceFile, _, ok := runtime.Caller(0) + if !ok { + t.Fatal("locate GitLab package") + } + actionsPath := filepath.Join(filepath.Dir(sourceFile), "..", "..", "pkg", "websocket", "actions.go") + file, err := parser.ParseFile(token.NewFileSet(), actionsPath, nil, 0) + if err != nil { + t.Fatalf("parse WebSocket action catalog: %v", err) + } + + found := map[string]bool{} + ast.Inspect(file, func(node ast.Node) bool { + spec, isValueSpec := node.(*ast.ValueSpec) + if !isValueSpec { + return true + } + for _, name := range spec.Names { + if !strings.HasPrefix(name.Name, "ActionGitLab") { + continue + } + found[name.Name] = true + if !authorized[name.Name] { + t.Errorf("legacy GitLab WebSocket action constant %s is present", name.Name) + } + } + return true + }) + for action := range authorized { + if !found[action] { + t.Errorf("authorized GitLab WebSocket action constant %s is missing", action) } } } diff --git a/apps/backend/pkg/websocket/actions.go b/apps/backend/pkg/websocket/actions.go index 51d2810a99..48883c8c7c 100644 --- a/apps/backend/pkg/websocket/actions.go +++ b/apps/backend/pkg/websocket/actions.go @@ -569,61 +569,10 @@ const ( ActionGitHubCleanupIssueTasks = "github.cleanup.issue_tasks" ) -// GitLab integration actions +// GitLab integration notifications const ( - ActionGitLabStatus = "gitlab.status" - ActionGitLabTaskMRsList = "gitlab.task_mrs.list" - ActionGitLabTaskMRGet = "gitlab.task_mr.get" - ActionGitLabMRFeedbackGet = "gitlab.mr_feedback.get" - ActionGitLabReviewWatchesList = "gitlab.review_watches.list" - ActionGitLabReviewWatchCreate = "gitlab.review_watches.create" - ActionGitLabReviewWatchUpdate = "gitlab.review_watches.update" - ActionGitLabReviewWatchDelete = "gitlab.review_watches.delete" - ActionGitLabReviewTrigger = "gitlab.review_watches.trigger" - ActionGitLabReviewTriggerAll = "gitlab.review_watches.trigger_all" - ActionGitLabMRWatchesList = "gitlab.mr_watches.list" - ActionGitLabMRWatchDelete = "gitlab.mr_watches.delete" - ActionGitLabMRFilesGet = "gitlab.mr_files.get" - ActionGitLabMRCommitsGet = "gitlab.mr_commits.get" - ActionGitLabTaskMRUpdated = "gitlab.task_mr.updated" // Notification - ActionGitLabMRFeedbackNotify = "gitlab.mr_feedback.notify" // Notification - ActionGitLabNewReviewMRNotify = "gitlab.new_review_mr.notify" // Notification - ActionGitLabTaskMRSync = "gitlab.task_mr.sync" - ActionGitLabStats = "gitlab.stats" - + ActionGitLabTaskMRUpdated = "gitlab.task_mr.updated" // Notification ActionGitLabTaskMRAutomationUpdated = "gitlab.task_mr_options.updated" // Notification - - ActionGitLabMRMerge = "gitlab.mr.merge" - ActionGitLabMRApprove = "gitlab.mr.approve" - ActionGitLabMRUnapprove = "gitlab.mr.unapprove" - ActionGitLabMRSetLabels = "gitlab.mr.set_labels" - ActionGitLabMRSetAssignees = "gitlab.mr.set_assignees" - ActionGitLabMRDiscussionNew = "gitlab.mr.discussion.new" - ActionGitLabMRDiscussionResolve = "gitlab.mr.discussion.resolve" - ActionGitLabProjectMergeMethodsGet = "gitlab.project.merge_methods.get" - - // Issue watch actions - ActionGitLabIssueWatchesList = "gitlab.issue_watches.list" - ActionGitLabIssueWatchCreate = "gitlab.issue_watches.create" - ActionGitLabIssueWatchUpdate = "gitlab.issue_watches.update" - ActionGitLabIssueWatchDelete = "gitlab.issue_watches.delete" - ActionGitLabIssueTrigger = "gitlab.issue_watches.trigger" - ActionGitLabIssueTriggerAll = "gitlab.issue_watches.trigger_all" - ActionGitLabNewIssueNotify = "gitlab.new_issue.notify" // Notification - - // Action preset actions for the /gitlab page quick-launch prompts. - ActionGitLabActionPresetsList = "gitlab.action_presets.list" - ActionGitLabActionPresetsUpdate = "gitlab.action_presets.update" - ActionGitLabActionPresetsReset = "gitlab.action_presets.reset" - - // Project discovery / autocomplete. - ActionGitLabListUserProjects = "gitlab.projects.list" - ActionGitLabSearchProjects = "gitlab.projects.search" - ActionGitLabProjectBranches = "gitlab.project.branches" - - // Manual cleanup sweeps. - ActionGitLabCleanupReviewTasks = "gitlab.cleanup.review_tasks" - ActionGitLabCleanupIssueTasks = "gitlab.cleanup.issue_tasks" ) // Jira integration actions diff --git a/docs/public/websocket-api.md b/docs/public/websocket-api.md index 84ac068b3b..fab6b6c474 100644 --- a/docs/public/websocket-api.md +++ b/docs/public/websocket-api.md @@ -276,7 +276,7 @@ websocat ws://127.0.0.1:38429/ws ## Registered request action catalog -The following 310 unique action names have concrete dispatcher registrations in the current backend. The 12 subscription/focus actions in the previous table are additional gateway-handled requests. Availability can still depend on a configured integration, handler mode, or service; registration does not supply credentials, provider installation, a running executor, or permission to external systems. +The following 279 unique action names have concrete dispatcher registrations in the current backend. The 12 subscription/focus actions in the previous table are additional gateway-handled requests. Availability can still depend on a configured integration, handler mode, or service; registration does not supply credentials, provider installation, a running executor, or permission to external systems. Payloads are not uniform. Read the corresponding handler request struct before building a non-first-party client. Names below are exact, including `vscode.openFile` and underscore-separated `user_shell.*` actions. @@ -550,49 +550,13 @@ github.task_pr.get github.task_pr.sync github.task_prs.list -gitlab.action_presets.list -gitlab.action_presets.reset -gitlab.action_presets.update gitlab.check_session_mr -gitlab.cleanup.issue_tasks -gitlab.cleanup.review_tasks -gitlab.issue_watches.create -gitlab.issue_watches.delete -gitlab.issue_watches.list -gitlab.issue_watches.trigger -gitlab.issue_watches.trigger_all -gitlab.issue_watches.update -gitlab.mr.approve -gitlab.mr.discussion.new -gitlab.mr.discussion.resolve -gitlab.mr.merge -gitlab.mr.set_assignees -gitlab.mr.set_labels -gitlab.mr.unapprove -gitlab.mr_commits.get -gitlab.mr_feedback.get -gitlab.mr_files.get -gitlab.mr_watches.delete -gitlab.mr_watches.list -gitlab.project.branches -gitlab.project.merge_methods.get -gitlab.projects.list -gitlab.projects.search -gitlab.review_watches.create -gitlab.review_watches.delete -gitlab.review_watches.list -gitlab.review_watches.trigger -gitlab.review_watches.trigger_all -gitlab.review_watches.update -gitlab.stats -gitlab.status -gitlab.task_mr.get -gitlab.task_mr.sync -gitlab.task_mrs.list ``` Provider actions make outbound calls with the backend's configured GitHub or GitLab identity. Status and registration do not imply a provider is authenticated, reachable, or authorized for a repository. +GitLab UI queries and mutations use the authenticated `/api/v1/gitlab/...` HTTP routes. The only remaining GitLab WebSocket request action is `gitlab.check_session_mr`, which refreshes a session's linked merge request. + ### Jira, Linear, and Sprites ```text @@ -746,6 +710,8 @@ agent.install.finished github.task_pr.updated github.task_ci_options.updated github.rate_limit.updated +gitlab.task_mr.updated +gitlab.task_mr_options.updated system.job.update ```