Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8992: fix(server): apply private-project access to indirect issue references (#10327)

pseudoyu984c2145a0ed
diff --git a/server/internal/handler/file.go b/server/internal/handler/file.go
index ab753a4833..4541c2c4a1 100644
--- a/server/internal/handler/file.go
+++ b/server/internal/handler/file.go
@@ -506,6 +506,9 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusForbidden, "invalid comment_id")
return
}
+ if !h.requireIssueIDVisible(w, r, workspaceID, comment.IssueID, http.StatusForbidden, "invalid comment_id") {
+ return
+ }
params.CommentID = comment.ID
}
if chatSessionID := r.FormValue("chat_session_id"); chatSessionID != "" {
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index aa585f025d..7741b07078 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -1299,5 +1299,10 @@ func (h *Handler) loadInboxItemForUser(w http.ResponseWriter, r *http.Request, i
writeError(w, http.StatusNotFound, "inbox item not found")
return db.InboxItem{}, false
}
+ // An item on an issue in a private project the caller cannot see (never
+ // granted, or revoked since it was delivered) answers like a missing one.
+ if !h.requireIssueIDVisible(w, r, workspaceID, item.IssueID, http.StatusNotFound, "inbox item not found") {
+ return db.InboxItem{}, false
+ }
return item, true
}
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 54c245a842..c88434ae5a 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -28,6 +28,7 @@ import (
"github.com/multica-ai/multica/server/internal/logger"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/middleware"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
"github.com/multica-ai/multica/server/internal/qoderruntime"
"github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
@@ -347,12 +348,12 @@ func validateIssueEnum(w http.ResponseWriter, field, value string, allowed []str
// page full of custom ones costs one catalog read rather than one per row. The
// Resolver includes ARCHIVED statuses, because an issue left on an archived
// status still belongs in its category's column. (MUL-6243)
-func (h *Handler) fillStatusCategories(ctx context.Context, wsID pgtype.UUID, resps []IssueResponse) {
+func (h *Handler) fillStatusCategories(ctx context.Context, wsID pgtype.UUID, hidden projectaccess.Hidden, resps []IssueResponse) {
var originals []pgtype.UUID
for i := range resps {
originals = appendDuplicateOriginal(originals, resps[i].Status, resps[i].duplicateOfIssueID)
}
- fill := h.newStatusCategoryFiller(ctx, wsID, originals...)
+ fill := h.newStatusCategoryFiller(ctx, wsID, hidden, originals...)
for i := range resps {
fill(&resps[i])
}
@@ -368,7 +369,11 @@ func (h *Handler) fillStatusCategories(ctx context.Context, wsID pgtype.UUID, re
// with appendDuplicateOriginal. A page passes them so they resolve in one read
// up front, the way labelsByIssue loads a page's labels; an original that was
// not passed still resolves, one read per distinct original. (MUL-7349)
-func (h *Handler) newStatusCategoryFiller(ctx context.Context, wsID pgtype.UUID, originals ...pgtype.UUID) func(*IssueResponse) {
+//
+// hidden is the reader's hidden projects: an original in one of them is left
+// off like a missing one (MUL-8472). Broadcasts, which reach every member,
+// pass the zero value; per-reader filtering of those is the fanout's job.
+func (h *Handler) newStatusCategoryFiller(ctx context.Context, wsID pgtype.UUID, hidden projectaccess.Hidden, originals ...pgtype.UUID) func(*IssueResponse) {
resolver := issuestatus.NewResolver(wsID)
refs := duplicateOriginals{}
h.loadDuplicateOriginals(ctx, wsID, refs, originals)
@@ -378,7 +383,7 @@ func (h *Handler) newStatusCategoryFiller(ctx context.Context, wsID pgtype.UUID,
}
// Every response that resolves its status also resolves its duplicate
// mark, so the two never disagree about which endpoints carry them.
- h.fillDuplicateOf(ctx, wsID, resp, refs)
+ h.fillDuplicateOf(ctx, wsID, resp, refs, hidden)
if resp.StatusCategory != "" {
return
}
@@ -391,8 +396,8 @@ func (h *Handler) newStatusCategoryFiller(ctx context.Context, wsID pgtype.UUID,
// fillStatusCategory is the single-response form. Only for endpoints that build
// exactly ONE response; anything looping must use newStatusCategoryFiller.
-func (h *Handler) fillStatusCategory(ctx context.Context, wsID pgtype.UUID, resp *IssueResponse) {
- h.newStatusCategoryFiller(ctx, wsID)(resp)
+func (h *Handler) fillStatusCategory(ctx context.Context, wsID pgtype.UUID, hidden projectaccess.Hidden, resp *IssueResponse) {
+ h.newStatusCategoryFiller(ctx, wsID, hidden)(resp)
}
// duplicateOfPointer keeps a duplicate mark only while the issue is
@@ -448,14 +453,14 @@ func (h *Handler) loadDuplicateOriginals(ctx context.Context, wsID pgtype.UUID,
// fillDuplicateOf resolves a duplicate mark to its original (MUL-7349),
// through refs so a page's originals cost one read (see
// newStatusCategoryFiller). A missing original leaves DuplicateOf unset.
-func (h *Handler) fillDuplicateOf(ctx context.Context, wsID pgtype.UUID, resp *IssueResponse, refs duplicateOriginals) {
+func (h *Handler) fillDuplicateOf(ctx context.Context, wsID pgtype.UUID, resp *IssueResponse, refs duplicateOriginals, hidden projectaccess.Hidden) {
id := resp.duplicateOfIssueID
if !id.Valid {
return
}
h.loadDuplicateOriginals(ctx, wsID, refs, []pgtype.UUID{id})
row := refs[id]
- if row == nil {
+ if row == nil || !hidden.CanSeeProject(row.ProjectID) {
return
}
// The response already rendered its own identifier with the workspace
@@ -1284,7 +1289,7 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {
for _, sr := range results {
originals = appendDuplicateOriginal(originals, sr.issue.Status, sr.issue.DuplicateOfIssueID)
}
- fillSearch := h.newStatusCategoryFiller(ctx, wsUUID, originals...)
+ fillSearch := h.newStatusCategoryFiller(ctx, wsUUID, hidden, originals...)
resp := make([]SearchIssueResponse, len(results))
for i, sr := range results {
sir := SearchIssueResponse{
@@ -1475,7 +1480,7 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {
originals = appendDuplicateOriginal(originals, issue.Status, issue.DuplicateOfIssueID)
}
labelsMap := h.labelsByIssue(ctx, wsUUID, ids)
- fillOpen := h.newStatusCategoryFiller(ctx, wsUUID, originals...)
+ fillOpen := h.newStatusCategoryFiller(ctx, wsUUID, openHidden, originals...)
resp := make([]IssueResponse, len(issues))
for i, issue := range issues {
resp[i] = openIssueRowToResponse(issue, prefix)
@@ -1914,7 +1919,7 @@ LIMIT %s OFFSET %s`, whereSql, orderBy, limitRef, offsetRef)
}
resp[i].Labels = &labels
}
- h.fillStatusCategories(ctx, wsUUID, resp)
+ h.fillStatusCategories(ctx, wsUUID, hidden, resp)
writeJSON(w, http.StatusOK, map[string]any{
"created_by_user_id": r.URL.Query().Get("created_by_user_id"),
@@ -2536,7 +2541,7 @@ ORDER BY
prefix := h.getIssuePrefix(ctx, wsUUID)
// One Resolver for the whole page — a per-row filler would query the
// catalog once per custom-status row. (MUL-6243)
- fillGrouped := h.newStatusCategoryFiller(ctx, wsUUID, originals...)
+ fillGrouped := h.newStatusCategoryFiller(ctx, wsUUID, hidden, originals...)
groups := []IssueAssigneeGroupResponse{}
groupIndex := map[string]int{}
@@ -2574,9 +2579,13 @@ func (h *Handler) GetIssue(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ hidden, ok := h.requestHiddenProjects(w, r, uuidToString(issue.WorkspaceID))
+ if !ok {
+ return
+ }
prefix := h.getIssuePrefix(r.Context(), issue.WorkspaceID)
resp := issueToResponse(issue, prefix)
- h.fillStatusCategory(r.Context(), issue.WorkspaceID, &resp)
+ h.fillStatusCategory(r.Context(), issue.WorkspaceID, hidden, &resp)
detailLabels := h.labelsByIssue(r.Context(), issue.WorkspaceID, []pgtype.UUID{issue.ID})[uuidToString(issue.ID)]
if detailLabels == nil {
detailLabels = []LabelResponse{}
@@ -2605,7 +2614,7 @@ func (h *Handler) GetIssue(w http.ResponseWriter, r *http.Request) {
}
}
- if sourceContext, err := h.issueSourceContextDetail(r.Context(), issue); err == nil {
+ if sourceContext, err := h.issueSourceContextDetail(r.Context(), issue, hidden); err == nil {
resp.SourceContext = sourceContext
} else if !errors.Is(err, pgx.ErrNoRows) {
slog.Warn("load issue source context failed", append(logger.RequestAttrs(r), "issue_id", uuidToString(issue.ID), "error", err)...)
@@ -2989,6 +2998,10 @@ func (h *Handler) QuickCreateIssue(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ attachmentIDs, ok = h.visibleAttachmentIDs(w, r, wsUUID, attachmentIDs)
+ if !ok {
+ return
+ }
// Optional project_id — validate it belongs to the same workspace before
// pinning the task to it. The handler is the trust boundary; the frontend
@@ -3413,6 +3426,9 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "parent issue not found in this workspace")
return
}
+ if !h.requireProjectVisible(w, r, workspaceID, parent.ProjectID, http.StatusBadRequest, "parent issue not found in this workspace") {
+ return
+ }
}
}
@@ -3500,6 +3516,10 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ attachmentIDs, ok = h.visibleAttachmentIDs(w, r, wsUUID, attachmentIDs)
+ if !ok {
+ return
+ }
labelIDs, ok := parseUUIDSliceOrBadRequest(w, req.LabelIDs, "label_ids")
if !ok {
@@ -3591,7 +3611,7 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {
// One filler for this create, shared by the broadcast payload and the HTTP
// response below, so a custom-status create reads the catalog once per
// request rather than once per payload. (MUL-6243)
- fillCreated := h.newStatusCategoryFiller(r.Context(), wsUUID)
+ fillCreated := h.newStatusCategoryFiller(r.Context(), wsUUID, projectaccess.Hidden{})
// Analytics agent ID: assignee agent when the issue is being assigned
// to an agent, otherwise the creator agent for agent-authored issues.
@@ -3664,7 +3684,7 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {
if errors.Is(err, service.ErrActiveDuplicate) {
dup := *res.DuplicateIssue
existing := issueToResponse(dup, h.getIssuePrefix(r.Context(), dup.WorkspaceID))
- h.fillStatusCategory(r.Context(), dup.WorkspaceID, &existing)
+ h.fillStatusCategory(r.Context(), dup.WorkspaceID, projectaccess.Hidden{}, &existing)
writeJSON(w, http.StatusConflict, map[string]any{
"code": "active_duplicate_issue",
"error": duplicateIssueMessage(existing),
@@ -4002,6 +4022,12 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ // MUL-8472: a target the caller cannot see answers like a missing one,
+ // before any other field is validated and before the mark writes anything
+ // (including the activity on the target).
+ if !h.requireDuplicateTarget(w, r, prevIssue.WorkspaceID, duplicateOfID) {
+ return
+ }
// Pre-fill nullable fields (bare sqlc.narg) with current values
params := db.UpdateIssueParams{
@@ -4229,6 +4255,10 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ attachmentIDs, ok = h.visibleAttachmentIDs(w, r, prevIssue.WorkspaceID, attachmentIDs)
+ if !ok {
+ return
+ }
// The agent this write hands the issue to gets the change as its own run,
// not also through its event wakeups.
@@ -4277,7 +4307,7 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
resp := issueToResponse(issue, prefix)
slog.Info("issue updated", append(logger.RequestAttrs(r), "issue_id", id, "workspace_id", workspaceID)...)
- h.fillStatusCategory(r.Context(), issue.WorkspaceID, &resp)
+ h.fillStatusCategory(r.Context(), issue.WorkspaceID, projectaccess.Hidden{}, &resp)
assigneeChanged := (req.AssigneeType != nil || req.AssigneeID != nil || handoff != nil) &&
(prevIssue.AssigneeType.String != issue.AssigneeType.String || uuidToString(prevIssue.AssigneeID) != uuidToString(issue.AssigneeID))
statusChanged := (req.Status != nil || params.Status.Valid) && prevIssue.Status != issue.Status
@@ -4390,6 +4420,14 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
h.processChildEvents(r.Context(), issue.ParentIssueID, prevIssue.ParentIssueID)
}
+ // The broadcast reaches every member; the caller's own copy names the
+ // original only when the caller can see it.
+ if resp.DuplicateOf != nil {
+ resp.DuplicateOf = nil
+ if hidden, err := h.hiddenProjects(r, workspaceID); err == nil {
+ h.fillStatusCategory(r.Context(), issue.WorkspaceID, hidden, &resp)
+ }
+ }
writeJSON(w, http.StatusOK, resp)
}
@@ -4748,7 +4786,7 @@ func (h *Handler) deleteIssuesAndCollectAttachmentURLs(ctx context.Context, issu
func (h *Handler) publishIssueSnapshots(ctx context.Context, issues []db.Issue, actorType, actorID string) {
for _, issue := range issues {
response := issueToResponse(issue, h.getIssuePrefix(ctx, issue.WorkspaceID))
- h.fillStatusCategory(ctx, issue.WorkspaceID, &response)
+ h.fillStatusCategory(ctx, issue.WorkspaceID, projectaccess.Hidden{}, &response)
h.publish(protocol.EventIssueUpdated, uuidToString(issue.WorkspaceID), actorType, actorID, map[string]any{"issue": response})
}
}
@@ -4761,7 +4799,7 @@ func (h *Handler) publishClearedDuplicates(ctx context.Context, cleared []cleare
for _, c := range cleared {
prefix := h.getIssuePrefix(ctx, c.Issue.WorkspaceID)
response := issueToResponse(c.Issue, prefix)
- h.fillStatusCategory(ctx, c.Issue.WorkspaceID, &response)
+ h.fillStatusCategory(ctx, c.Issue.WorkspaceID, projectaccess.Hidden{}, &response)
h.publish(protocol.EventIssueUpdated, uuidToString(c.Issue.WorkspaceID), actorType, actorID, map[string]any{
"issue": response,
"duplicate_of_issue_id": liveDuplicateMark(c.Issue.Status, c.Issue.DuplicateOfIssueID),
@@ -4895,7 +4933,7 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
updated := 0
// One Resolver for the whole batch — a per-issue filler would query the
// catalog once per custom-status row. (MUL-6243)
- fillBatch := h.newStatusCategoryFiller(r.Context(), wsUUID)
+ fillBatch := h.newStatusCategoryFiller(r.Context(), wsUUID, projectaccess.Hidden{})
// Parents whose sub-issues changed this batch. Their rules are evaluated
// once after the loop against the final state (MUL-4155), not per child
// against a mid-batch snapshot.
diff --git a/server/internal/handler/issue_duplicate.go b/server/internal/handler/issue_duplicate.go
index 1b1561a97d..e22d497a56 100644
--- a/server/internal/handler/issue_duplicate.go
+++ b/server/internal/handler/issue_duplicate.go
@@ -9,6 +9,7 @@ import (
"net/http"
"github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/issuestatus"
"github.com/multica-ai/multica/server/internal/logger"
@@ -73,6 +74,32 @@ func parseDuplicateMark(w http.ResponseWriter, req *UpdateIssueRequest, rawField
return targetID, true
}
+// requireDuplicateTarget answers a target that is missing, in another
+// workspace, or in a private project the caller cannot see (MUL-8472) with
+// the same 400, before any other field of the request is validated. Checking
+// visibility alone is not enough: a missing target would pass it and fail on
+// a later field (an invalid assignee, say), while a hidden one stops here, so
+// the two answers would tell the caller the hidden issue exists.
+// lockAndCheckDuplicateMark still re-checks the target under lock.
+func (h *Handler) requireDuplicateTarget(w http.ResponseWriter, r *http.Request, workspaceID pgtype.UUID, targetID pgtype.UUID) bool {
+ if !targetID.Valid {
+ return true
+ }
+ _, err := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{
+ ID: targetID,
+ WorkspaceID: workspaceID,
+ })
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusBadRequest, errDuplicateTargetNotFound.Error())
+ return false
+ }
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load duplicate target")
+ return false
+ }
+ return h.requireIssueIDVisible(w, r, uuidToString(workspaceID), targetID, http.StatusBadRequest, errDuplicateTargetNotFound.Error())
+}
+
// lockAndCheckDuplicateMark validates a mark inside the update transaction.
// Both issues are locked first, so marks that share an issue run one after
// the other and each validates what the previous one wrote. Deleting the
@@ -147,7 +174,7 @@ func (h *Handler) ListIssueDuplicates(w http.ResponseWriter, r *http.Request) {
return
}
prefix := h.getIssuePrefix(r.Context(), issue.WorkspaceID)
- fill := h.newStatusCategoryFiller(r.Context(), issue.WorkspaceID)
+ fill := h.newStatusCategoryFiller(r.Context(), issue.WorkspaceID, hidden)
var duplicateOf *IssueResponse
if issue.Status == issuestatus.Cancelled && issue.DuplicateOfIssueID.Valid {
diff --git a/server/internal/handler/issue_duplicate_originals_test.go b/server/internal/handler/issue_duplicate_originals_test.go
index 1af8373328..4343bec02c 100644
--- a/server/internal/handler/issue_duplicate_originals_test.go
+++ b/server/internal/handler/issue_duplicate_originals_test.go
@@ -11,6 +11,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/multica-ai/multica/server/internal/analytics"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
"github.com/multica-ai/multica/server/internal/testutil"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -179,7 +180,7 @@ func TestDuplicateOriginalResolvesWithoutPriming(t *testing.T) {
t.Fatalf("GetIssue: %v", err)
}
resp := issueToResponse(row, "MUL")
- testHandler.newStatusCategoryFiller(context.Background(), row.WorkspaceID)(&resp)
+ testHandler.newStatusCategoryFiller(context.Background(), row.WorkspaceID, projectaccess.Hidden{})(&resp)
if resp.DuplicateOf == nil || resp.DuplicateOf.ID != original {
t.Fatalf("duplicate_of = %+v, want %s", resp.DuplicateOf, original)
}
diff --git a/server/internal/handler/issue_move.go b/server/internal/handler/issue_move.go
index 89e8a56635..76c51df936 100644
--- a/server/internal/handler/issue_move.go
+++ b/server/internal/handler/issue_move.go
@@ -86,6 +86,9 @@ func (h *Handler) MoveIssue(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "project not found in this workspace")
return
}
+ if !h.requireProjectVisible(w, r, uuidToString(current.WorkspaceID), *projectID, http.StatusBadRequest, "project not found in this workspace") {
+ return
+ }
}
beforeID, ok := decodeIssueMoveAnchor(w, fields["before_id"], "before_id")
@@ -175,11 +178,12 @@ func (h *Handler) issueMoveAnchorPosition(
return nil, true
}
var position float64
+ var projectID pgtype.UUID
err := h.DB.QueryRow(r.Context(), `
- SELECT position
+ SELECT position, project_id
FROM issue
WHERE workspace_id = $1 AND id = $2
- `, workspaceID, *id).Scan(&position)
+ `, workspaceID, *id).Scan(&position, &projectID)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
writeError(w, http.StatusBadRequest, "move anchor not found in this workspace")
@@ -188,6 +192,9 @@ func (h *Handler) issueMoveAnchorPosition(
}
return nil, false
}
+ if !h.requireProjectVisible(w, r, uuidToString(workspaceID), projectID, http.StatusBadRequest, "move anchor not found in this workspace") {
+ return nil, false
+ }
return &position, true
}
diff --git a/server/internal/handler/issue_payload_shape_test.go b/server/internal/handler/issue_payload_shape_test.go
index 3809599de5..08002bfa9f 100644
--- a/server/internal/handler/issue_payload_shape_test.go
+++ b/server/internal/handler/issue_payload_shape_test.go
@@ -9,6 +9,7 @@ import (
"time"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
"github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/testutil"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -202,7 +203,7 @@ func TestResolvedBroadcastDuplicateOfMatchesResponse(t *testing.T) {
prefix := testHandler.getIssuePrefix(ctx, row.WorkspaceID)
resp := issueToResponse(row, prefix)
- testHandler.fillStatusCategory(ctx, row.WorkspaceID, &resp)
+ testHandler.fillStatusCategory(ctx, row.WorkspaceID, projectaccess.Hidden{}, &resp)
if resp.DuplicateOf == nil {
t.Fatal("HTTP rendering lost the mark")
}
diff --git a/server/internal/handler/issue_table_group.go b/server/internal/handler/issue_table_group.go
index 4a244060c6..c615dbb238 100644
--- a/server/internal/handler/issue_table_group.go
+++ b/server/internal/handler/issue_table_group.go
@@ -273,13 +273,11 @@ END, ''))`,
)) END`,
}, true
case "parent":
+ // The sort key reads the parent's title, so it is built per request in
+ // sortExpression, where the viewer's hidden projects are known.
return resolvedIssueTableGroup{
kind: "parent",
groupExpr: "COALESCE(i.parent_issue_id::text, '__no_parent__')",
- groupSortExpr: `CASE WHEN group_value = '__no_parent__' THEN '' ELSE LOWER(COALESCE(
- (SELECT p.title FROM issue p WHERE p.workspace_id = $1 AND p.id = group_value::uuid),
- ''
-)) END`,
}, true
case "compound":
if group.Secondary != "status" && group.Secondary != "status_category" {
@@ -440,9 +438,18 @@ func (group resolvedIssueTableGroup) expression(addArg func(any) string) string
return group.groupExpr
}
-func (group resolvedIssueTableGroup) sortExpression() string {
+// sortExpression orders groups. parentVisible is a predicate on the parent
+// row aliased p: a parent in a project the viewer cannot see sorts and renders
+// like a missing one.
+func (group resolvedIssueTableGroup) sortExpression(parentVisible string) string {
if group.kind == "compound" && group.primary != nil {
- return group.primary.sortExpression()
+ return group.primary.sortExpression(parentVisible)
+ }
+ if group.kind == "parent" {
+ return fmt.Sprintf(`CASE WHEN group_value = '__no_parent__' THEN '' ELSE LOWER(COALESCE(
+ (SELECT p.title FROM issue p WHERE p.workspace_id = $1 AND p.id = group_value::uuid AND %s),
+ ''
+)) END`, parentVisible)
}
if group.groupSortExpr != "" {
return group.groupSortExpr
@@ -522,9 +529,9 @@ func (group resolvedIssueTableGroup) orderExpression(addArg func(any) string) st
}
}
-func (group resolvedIssueTableGroup) contextExpression(addArg func(any) string, issuePrefix string) string {
+func (group resolvedIssueTableGroup) contextExpression(addArg func(any) string, issuePrefix, parentVisible string) string {
if group.kind == "compound" && group.primary != nil {
- return group.primary.contextExpression(addArg, issuePrefix)
+ return group.primary.contextExpression(addArg, issuePrefix, parentVisible)
}
if group.kind != "parent" {
return "'{}'::jsonb"
@@ -539,8 +546,8 @@ func (group resolvedIssueTableGroup) contextExpression(addArg func(any) string,
'status', p.status
))
FROM issue p
- WHERE p.workspace_id = $1 AND p.id = group_value::uuid
-), '{}'::jsonb) END`, prefixRef)
+ WHERE p.workspace_id = $1 AND p.id = group_value::uuid AND %s
+), '{}'::jsonb) END`, prefixRef, parentVisible)
}
const statusCategoryGroupKeyPrefix = "status_category:"
@@ -936,9 +943,9 @@ func (h *Handler) ListIssueTableGroups(w http.ResponseWriter, r *http.Request) {
return "$" + strconv.Itoa(len(args))
}
groupExpr := group.expression(addArg)
- groupSortExpr := group.sortExpression()
+ groupSortExpr := group.sortExpression(compiled.parentVisible())
orderExpr := group.orderExpression(addArg)
- contextExpr := group.contextExpression(addArg, h.getIssuePrefix(r.Context(), compiled.workspaceID))
+ contextExpr := group.contextExpression(addArg, h.getIssuePrefix(r.Context(), compiled.workspaceID), compiled.parentVisible())
cursorPredicate := "TRUE"
if cursor != nil {
if cursor.GroupOrder == nil || cursor.GroupSortKey == nil || cursor.GroupCursorKey == nil {
diff --git a/server/internal/handler/issue_table_query.go b/server/internal/handler/issue_table_query.go
index abcd4ff619..9a66f32cba 100644
--- a/server/internal/handler/issue_table_query.go
+++ b/server/internal/handler/issue_table_query.go
@@ -17,6 +17,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -183,6 +184,19 @@ type issueTableSQL struct {
args []any
fingerprint string
workspaceID pgtype.UUID
+ hidden projectaccess.Hidden
+ // hiddenProjectsRef is the placeholder holding the viewer's hidden project
+ // ids, empty when the viewer sees every project.
+ hiddenProjectsRef string
+}
+
+// parentVisible is a predicate on a parent issue aliased p: true unless the
+// parent sits in a project the viewer cannot see.
+func (s issueTableSQL) parentVisible() string {
+ if s.hiddenProjectsRef == "" {
+ return "TRUE"
+ }
+ return hiddenProjectPredicate("p.project_id", s.hiddenProjectsRef)
}
type issueTableCursor struct {
@@ -517,8 +531,10 @@ func (h *Handler) compileIssueTableQuery(w http.ResponseWriter, r *http.Request,
if !ok {
return issueTableSQL{}, false
}
+ hiddenProjectsRef := ""
if ids := hidden.Param(); ids != nil {
- where = append(where, hiddenProjectPredicate("i.project_id", addArg(ids)))
+ hiddenProjectsRef = addArg(ids)
+ where = append(where, hiddenProjectPredicate("i.project_id", hiddenProjectsRef))
}
negated := make(map[string]bool, len(spec.Filters.Negate))
@@ -882,9 +898,11 @@ func (h *Handler) compileIssueTableQuery(w http.ResponseWriter, r *http.Request,
where = appendIssueTableSearchFilter(where, addArg, spec.Search)
return issueTableSQL{
- where: strings.Join(where, " AND "),
- args: args,
- fingerprint: fingerprint,
- workspaceID: workspaceUUID,
+ where: strings.Join(where, " AND "),
+ args: args,
+ fingerprint: fingerprint,
+ workspaceID: workspaceUUID,
+ hidden: hidden,
+ hiddenProjectsRef: hiddenProjectsRef,
}, true
}
diff --git a/server/internal/handler/issue_table_rows.go b/server/internal/handler/issue_table_rows.go
index 529b5dd5a6..e910e79429 100644
--- a/server/internal/handler/issue_table_rows.go
+++ b/server/internal/handler/issue_table_rows.go
@@ -520,7 +520,7 @@ SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
labelsByIssue := baseHandler.labelsByIssue(r.Context(), compiled.workspaceID, issueIDs)
// One Resolver and one originals read for the page — see
// newStatusCategoryFiller. (MUL-6243, MUL-7349)
- fillTableRow := baseHandler.newStatusCategoryFiller(r.Context(), compiled.workspaceID, originals...)
+ fillTableRow := baseHandler.newStatusCategoryFiller(r.Context(), compiled.workspaceID, compiled.hidden, originals...)
responseRows := make([]issueTableRowResponse, len(scanned))
for index, row := range scanned {
issue := issueListRowToResponse(row.issue, prefix)
diff --git a/server/internal/handler/issue_trigger.go b/server/internal/handler/issue_trigger.go
index e3cb44885f..840a44c15b 100644
--- a/server/internal/handler/issue_trigger.go
+++ b/server/internal/handler/issue_trigger.go
@@ -167,6 +167,12 @@ func (h *Handler) PreviewIssueTrigger(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "too many issue_ids")
return
}
+ // MUL-8472: an issue or project the caller cannot see previews like an
+ // unknown one.
+ hidden, ok := h.requestHiddenProjects(w, r, workspaceID)
+ if !ok {
+ return
+ }
// Resolve the prospective assignee once — a malformed id is a deterministic
// 400, never a silent miscount.
@@ -218,7 +224,7 @@ func (h *Handler) PreviewIssueTrigger(w http.ResponseWriter, r *http.Request) {
// Mirror CreateIssue's workflow handling: the starting column's
// handoff when no assignee was picked. (MUL-7420)
if req.ProjectID != nil && *req.ProjectID != "" {
- if projectUUID, err := util.ParseUUID(*req.ProjectID); err == nil {
+ if projectUUID, err := util.ParseUUID(*req.ProjectID); err == nil && hidden.CanSeeProject(projectUUID) {
if def, project, err := issueworkflow.ForProject(r.Context(), h.Queries, wsUUID, projectUUID); err == nil && def != nil {
if step, ok := def.Step(candidate.Status); ok && step.HandsOff() && !hasNewAssignee {
if t, id, ok := issueworkflow.ResolveHandler(step, project, actorType, parseUUID(actorID)); ok {
@@ -244,8 +250,8 @@ func (h *Handler) PreviewIssueTrigger(w http.ResponseWriter, r *http.Request) {
ID: issueUUID,
WorkspaceID: parseUUID(workspaceID),
})
- if err != nil {
- continue // cross-workspace / unknown id contributes no trigger
+ if err != nil || !hidden.CanSeeProject(loaded.ProjectID) {
+ continue // cross-workspace / unknown / hidden id contributes no trigger
}
post := loaded
diff --git a/server/internal/handler/issue_view_preference.go b/server/internal/handler/issue_view_preference.go
index c6934d4814..65a6feec77 100644
--- a/server/internal/handler/issue_view_preference.go
+++ b/server/internal/handler/issue_view_preference.go
@@ -44,6 +44,9 @@ func (h *Handler) resolvePreferenceScope(
writeError(w, http.StatusNotFound, "project not found")
return pgtype.UUID{}, false
}
+ if !h.requireProjectVisible(w, r, uuidToString(wsUUID), projUUID, http.StatusNotFound, "project not found") {
+ return pgtype.UUID{}, false
+ }
return projUUID, true
default:
writeError(w, http.StatusBadRequest, "invalid scope_type")
diff --git a/server/internal/handler/label.go b/server/internal/handler/label.go
index e99bfad077..b94d64e73e 100644
--- a/server/internal/handler/label.go
+++ b/server/internal/handler/label.go
@@ -144,8 +144,12 @@ func (h *Handler) ListLabels(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, err.Error())
return
}
+ hidden, ok := h.requestHiddenProjects(w, r, workspaceID)
+ if !ok {
+ return
+ }
labels, err := h.Queries.ListLabels(r.Context(), db.ListLabelsParams{
- WorkspaceID: parseUUID(workspaceID), ResourceType: resourceType,
+ WorkspaceID: parseUUID(workspaceID), ResourceType: resourceType, HiddenProjectIds: hidden.Param(),
})
if err != nil {
slog.Warn("ListLabels failed", append(logger.RequestAttrs(r), "error", err)...)
diff --git a/server/internal/handler/pr_auto_complete.go b/server/internal/handler/pr_auto_complete.go
index ee9b0190b7..6f4749562f 100644
--- a/server/internal/handler/pr_auto_complete.go
+++ b/server/internal/handler/pr_auto_complete.go
@@ -16,6 +16,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/issuestatus"
"github.com/multica-ai/multica/server/internal/issueworkflow"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
"github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -307,7 +308,7 @@ func (h *Handler) maybeAutoCompleteIssue(ctx context.Context, workspaceID, issue
prefix := h.getIssuePrefix(ctx, issue.WorkspaceID)
resp := issueToResponse(updated, prefix)
- h.fillStatusCategory(ctx, updated.WorkspaceID, &resp)
+ h.fillStatusCategory(ctx, updated.WorkspaceID, projectaccess.Hidden{}, &resp)
h.publish(protocol.EventIssueUpdated, uuidToString(workspaceID), "system", "", map[string]any{
"issue": resp,
"status_changed": true,
diff --git a/server/internal/handler/private_project_inbox_relations_test.go b/server/internal/handler/private_project_inbox_relations_test.go
new file mode 100644
index 0000000000..488e5f651b
--- /dev/null
+++ b/server/internal/handler/private_project_inbox_relations_test.go
@@ -0,0 +1,236 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+type inboxItemState struct{ read, archived bool }
+
+func loadInboxItemState(t *testing.T, itemID string) inboxItemState {
+ t.Helper()
+ var s inboxItemState
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT read, archived FROM inbox_item WHERE id = $1`, itemID,
+ ).Scan(&s.read, &s.archived); err != nil {
+ t.Fatalf("load inbox item %s: %v", itemID, err)
+ }
+ return s
+}
+
+func insertSecretInboxItem(t *testing.T, f privateProjectFixture, recipient string) string {
+ t.Helper()
+ return dbfx.Insert(t, "inbox_item", testutil.Cols{
+ "workspace_id": testWorkspaceID, "recipient_type": "member", "recipient_id": recipient,
+ "type": "mentioned", "severity": "info", "title": f.marker + " secret notification", "issue_id": f.secretIssue,
+ })
+}
+
+// Read, unread, archive and unarchive all load the item through
+// loadInboxItemForUser, so an item on an issue the caller can no longer see
+// must 404 there and stay untouched.
+func TestPrivateProjectInboxItemMutationsNeedVisibility(t *testing.T) {
+ f := newPrivateProjectFixture(t)
+ type mutation struct {
+ name string
+ path string
+ handler http.HandlerFunc
+ before inboxItemState
+ after inboxItemState
+ }
+ mutations := []mutation{
+ {"read", "/read", testHandler.MarkInboxRead, inboxItemState{false, false}, inboxItemState{true, false}},
+ {"unread", "/unread", testHandler.MarkInboxUnread, inboxItemState{true, false}, inboxItemState{false, false}},
+ {"archive", "/archive", testHandler.ArchiveInboxItem, inboxItemState{false, false}, inboxItemState{false, true}},
+ {"unarchive", "/unarchive", testHandler.UnarchiveInboxItem, inboxItemState{false, true}, inboxItemState{false, false}},
+ }
+ call := func(m mutation, userID, itemID string) *testutil.Response {
+ dbfx.Exec(t, `UPDATE inbox_item SET read = $2, archived = $3 WHERE id = $1`, itemID, m.before.read, m.before.archived)
+ req := withURLParam(asUser(newRequest(http.MethodPost, "/api/inbox/"+itemID+m.path, nil), userID), "id", itemID)
+ return testutil.Call(t, inboxWorkspaceHandler(m.handler), req)
+ }
+ allowed := func(who, userID, itemID string) {
+ t.Helper()
+ for _, m := range mutations {
+ call(m, userID, itemID).Want(http.StatusOK)
+ if got := loadInboxItemState(t, itemID); got != m.after {
+ t.Errorf("%s %s: state = %+v, want %+v", who, m.name, got, m.after)
+ }
+ }
+ }
+ blocked := func(who, userID, itemID string) {
+ t.Helper()
+ for _, m := range mutations {
+ call(m, userID, itemID).Want(http.StatusNotFound)
+ if got := loadInboxItemState(t, itemID); got != m.before {
+ t.Errorf("%s %s: refused mutation changed state to %+v, want %+v", who, m.name, got, m.before)
+ }
+ }
+ }
+
+ ownerItem := insertSecretInboxItem(t, f, testUserID)
+ insiderItem := insertSecretInboxItem(t, f, f.insider)
+ // Delivered before the outsider lost access (or written by a path that
+ // never checked): the row exists, but the outsider may not act on it.
+ outsiderItem := insertSecretInboxItem(t, f, f.outsider)
+
+ allowed("workspace owner outside the member list", testUserID, ownerItem)
+ allowed("project member", f.insider, insiderItem)
+ blocked("workspace member outside the project", f.outsider, outsiderItem)
+
+ removeProjectMemberAsOwner(t, f, f.insider)
+ blocked("revoked project member", f.insider, insiderItem)
+
+ // Notifications outside the private project stay actionable after revocation.
+ publicItem := dbfx.Insert(t, "inbox_item", testutil.Cols{
+ "workspace_id": testWorkspaceID, "recipient_type": "member", "recipient_id": f.insider,
+ "type": "mentioned", "severity": "info", "title": f.marker + " public notification", "issue_id": f.publicIssue,
+ })
+ allowed("revoked project member on a public issue", f.insider, publicItem)
+}
+
+func TestPrivateProjectSubscribedIssueIDsHidden(t *testing.T) {
+ f := newPrivateProjectFixture(t)
+ subscribe := func(issueID, userID string) {
+ dbfx.InsertNoID(t, "issue_subscriber", testutil.Cols{
+ "issue_id": issueID, "user_type": "member", "user_id": userID, "reason": "manual",
+ }, "issue_id = $1 AND user_id = $2", issueID, userID)
+ }
+ for _, userID := range []string{testUserID, f.insider, f.outsider} {
+ subscribe(f.secretIssue, userID)
+ subscribe(f.publicIssue, userID)
+ }
+ subscribed := func(userID string) map[string]bool {
+ t.Helper()
+ var out struct {
+ IssueIDs []string `json:"issue_ids"`
+ }
+ req := asUser(newRequest(http.MethodGet, "/api/issues/subscribed", nil), userID)
+ testutil.Call(t, inboxWorkspaceHandler(testHandler.ListSubscribedIssueIDs), req).Want(http.StatusOK).JSON(&out)
+ ids := map[string]bool{}
+ for _, id := range out.IssueIDs {
+ ids[id] = true
+ }
+ return ids
+ }
+ check := func(who, userID string, wantSecret bool) {
+ t.Helper()
+ got := subscribed(userID)
+ if got[f.secretIssue] != wantSecret || !got[f.publicIssue] {
+ t.Errorf("%s: subscribed secret=%v public=%v, want secret=%v public=true", who, got[f.secretIssue], got[f.publicIssue], wantSecret)
+ }
+ }
+ check("workspace owner outside the member list", testUserID, true)
+ check("project member", f.insider, true)
+ check("workspace member outside the project", f.outsider, false)
+
+ removeProjectMemberAsOwner(t, f, f.insider)
+ check("revoked project member", f.insider, false)
+}
+
+func TestPrivateProjectLabelUsageCountHidden(t *testing.T) {
+ f := newPrivateProjectFixture(t)
+ labelID := dbfx.Insert(t, "issue_label", testutil.Cols{
+ "workspace_id": testWorkspaceID, "name": f.marker + " label", "color": "#f00", "resource_type": "issue",
+ })
+ dbfx.Cleanup(t, `DELETE FROM issue_to_label WHERE label_id = $1`, labelID)
+ dbfx.Exec(t, `INSERT INTO issue_to_label (issue_id, label_id) VALUES ($1, $3), ($2, $3)`, f.secretIssue, f.publicIssue, labelID)
+
+ usage := func(userID string) int64 {
+ t.Helper()
+ var out struct {
+ Labels []LabelResponse `json:"labels"`
+ }
+ req := asUser(newRequest(http.MethodGet, "/api/labels?resource_type=issue", nil), userID)
+ testutil.Call(t, testHandler.ListLabels, req).Want(http.StatusOK).JSON(&out)
+ for _, l := range out.Labels {
+ if l.ID == labelID {
+ return l.UsageCount
+ }
+ }
+ t.Fatalf("label %s missing from %s's list", labelID, userID)
+ return 0
+ }
+ for _, tc := range []struct {
+ name string
+ userID string
+ want int64
+ }{
+ {"workspace owner outside the member list", testUserID, 2},
+ {"project member", f.insider, 2},
+ {"workspace member outside the project", f.outsider, 1},
+ } {
+ if got := usage(tc.userID); got != tc.want {
+ t.Errorf("%s: usage_count = %d, want %d", tc.name, got, tc.want)
+ }
+ }
+
+ removeProjectMemberAsOwner(t, f, f.insider)
+ if got := usage(f.insider); got != 1 {
+ t.Errorf("revoked project member: usage_count = %d, want 1", got)
+ }
+}
+
+// A project-scoped view preference on a project the caller cannot see answers
+// exactly like one on a project that does not exist, for reads and writes.
+func TestPrivateProjectViewPreferenceScopeHidden(t *testing.T) {
+ f := newPrivateProjectFixture(t)
+ const missingProject = "00000000-0000-0000-0000-00000000beef"
+ for _, userID := range []string{testUserID, f.insider, f.outsider} {
+ dbfx.Cleanup(t, `DELETE FROM issue_view_preference WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, userID)
+ }
+ get := func(userID, projectID string) *testutil.Response {
+ req := asUser(newRequest(http.MethodGet, "/api/issue-view-preferences?scope_type=project&scope_id="+projectID, nil), userID)
+ return testutil.Call(t, testHandler.GetIssueViewPreference, req)
+ }
+ put := func(userID, projectID string) *testutil.Response {
+ req := asUser(newRequest(http.MethodPut, "/api/issue-view-preferences", map[string]any{
+ "scope_type": "project", "scope_id": projectID, "prefs": map[string]any{"hidden": []string{"builtin:all"}},
+ }), userID)
+ return testutil.Call(t, testHandler.PutIssueViewPreference, req)
+ }
+ stored := func(userID string) int {
+ t.Helper()
+ var n int
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT count(*) FROM issue_view_preference WHERE workspace_id = $1 AND user_id = $2 AND scope_type = 'project' AND scope_id = $3`,
+ testWorkspaceID, userID, f.projectID,
+ ).Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ return n
+ }
+ blocked := func(who, userID string) {
+ t.Helper()
+ before := stored(userID)
+ missingGet := get(userID, missingProject).Want(http.StatusNotFound).Text()
+ missingPut := put(userID, missingProject).Want(http.StatusNotFound).Text()
+ if body := get(userID, f.projectID).Want(http.StatusNotFound).Text(); body != missingGet {
+ t.Errorf("%s: hidden GET body %q differs from missing %q", who, body, missingGet)
+ }
+ if body := put(userID, f.projectID).Want(http.StatusNotFound).Text(); body != missingPut {
+ t.Errorf("%s: hidden PUT body %q differs from missing %q", who, body, missingPut)
+ }
+ if after := stored(userID); after != before {
+ t.Errorf("%s: refused PUT changed stored preferences from %d to %d", who, before, after)
+ }
+ }
+
+ for _, tc := range []struct{ name, userID string }{
+ {"workspace owner outside the member list", testUserID},
+ {"project member", f.insider},
+ } {
+ put(tc.userID, f.projectID).Want(http.StatusOK)
+ get(tc.userID, f.projectID).Want(http.StatusOK)
+ if stored(tc.userID) != 1 {
+ t.Errorf("%s: project preference was not stored", tc.name)
+ }
+ }
+ blocked("workspace member outside the project", f.outsider)
+
+ removeProjectMemberAsOwner(t, f, f.insider)
+ blocked("revoked project member", f.insider)
+}
diff --git a/server/internal/handler/private_project_relations_test.go b/server/internal/handler/private_project_relations_test.go
new file mode 100644
index 0000000000..5c38a07ef1
--- /dev/null
+++ b/server/internal/handler/private_project_relations_test.go
@@ -0,0 +1,378 @@
+package handler
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+// Relations and indirect ids (MUL-8472): an object a request reaches through
+// another issue, a comment or an attachment id must answer for a private
+// project exactly as the direct issue route does.
+
+func relationIssueNumber() int {
+ return 700000 + int(time.Now().UnixNano()%50000)*2
+}
+
+func putIssueAs(t *testing.T, userID, issueID string, body map[string]any) *testutil.Response {
+ t.Helper()
+ req := withURLParam(asUser(newRequest(http.MethodPut, "/api/issues/"+issueID, body), userID), "id", issueID)
+ return testutil.Call(t, testHandler.UpdateIssue, req)
+}
+
+func getIssueAs(t *testing.T, userID, issueID string) *testutil.Response {
+ t.Helper()
+ req := withURLParam(asUser(newRequest(http.MethodGet, "/api/issues/"+issueID, nil), userID), "id", issueID)
+ return testutil.Call(t, testHandler.GetIssue, req)
+}
+
+func TestPrivateProjectDuplicateMarkNeedsVisibleTarget(t *testing.T) {
+ f := newPrivateProjectFixture(t)
+ secretTitle := f.marker + " secret issue"
+
+ hidden := putIssueAs(t, f.outsider, f.publicIssue, map[string]any{"duplicate_of_issue_id": f.secretIssue})
+ missing := putIssueAs(t, f.outsider, f.publicIssue, map[string]any{"duplicate_of_issue_id": uuid.NewString()})
+ hidden.Want(http.StatusBadRequest)
+ if hidden.Code != missing.Code || hidden.Text() != missing.Text() {
+ t.Errorf("hidden target answers %d %s, missing target %d %s", hidden.Code, hidden.Text(), missing.Code, missing.Text())
+ }
+ if strings.Contains(hidden.Text(), secretTitle) {
+ t.Errorf("refused mark leaks the hidden original: %s", hidden.Text())
+ }
+ // A second invalid field must not let the two answers drift apart: the
+ // target is checked before the assignee, for a hidden and a missing one
+ // alike.
+ badAssignee := func(target string) *testutil.Response {
+ return putIssueAs(t, f.outsider, f.publicIssue, map[string]any{
+ "duplicate_of_issue_id": target, "assignee_type": "agent", "assignee_id": uuid.NewString(),
+ })
+ }
+ hiddenWithAssignee, missingWithAssignee := badAssignee(f.secretIssue), badAssignee(uuid.NewString())
+ hiddenWithAssignee.Want(http.StatusBadRequest)
+ if hiddenWithAssignee.Code != missingWithAssignee.Code || hiddenWithAssignee.Text() != missingWithAssignee.Text() {
+ t.Errorf("with an invalid assignee, hidden target answers %d %s, missing target %d %s",
+ hiddenWithAssignee.Code, hiddenWithAssignee.Text(), missingWithAssignee.Code, missingWithAssignee.Text())
+ }
+ var status string
+ var duplicateOf *string
+ dbfx.QueryRow(t, `SELECT status, duplicate_of_issue_id::text FROM issue WHERE id = $1`, f.publicIssue).Scan(&status, &duplicateOf)
+ if status != "todo" || duplicateOf != nil {
+ t.Errorf("refused mark wrote the issue: status=%s duplicate_of=%v", status, duplicateOf)
+ }
+
+ // The insider can mark, and sees the original.
+ own := dbfx.Issue(t, f.marker+" insider duplicate", testutil.Cols{"number": relationIssueNumber()})
+ var marked IssueResponse
+ putIssueAs(t, f.insider, own, map[string]any{"duplicate_of_issue_id": f.secretIssue}).Want(http.StatusOK).JSON(&marked)
+ if marked.DuplicateOf == nil || marked.DuplicateOf.ID != f.secretIssue {
+ t.Fatalf("insider mark response duplicate_of = %+v, want the secret issue", marked.DuplicateOf)
+ }
+
+ // After losing access the same mark no longer names the original.
+ removeProjectMemberAsOwner(t, f, f.insider)
+ var detail IssueResponse
+ body := getIssueAs(t, f.insider, own).Want(http.StatusOK).JSON(&detail).Text()
+ if detail.DuplicateOf != nil || strings.Contains(body, secretTitle) {
+ t.Errorf("revoked member's issue detail still names the hidden original: %s", body)
+ }
+ var edited IssueResponse
+ body = putIssueAs(t, f.outsider, own, map[string]any{"title": f.marker + " retitled duplicate"}).Want(http.StatusOK).JSON(&edited).Text()
+ if edited.DuplicateOf != nil || strings.Contains(body, secretTitle) {
+ t.Errorf("outsider update response names the hidden original: %s", body)
+ }
+ getIssueAs(t, testUserID, own).Want(http.StatusOK).JSON(&detail)
+ if detail.DuplicateOf == nil || detail.DuplicateOf.ID != f.secretIssue {
+ t.Errorf("workspace owner lost the duplicate_of on %s: %+v", own, detail.DuplicateOf)
+ }
+}
+
+func uploadAs(t *testing.T, userID string, fields map[string]string) *testutil.Response {
+ t.Helper()
+ var body bytes.Buffer
+ writer := multipart.NewWriter(&body)
+ part, err := writer.CreateFormFile("file", "relation.txt")
+ if err != nil {
+ t.Fatal(err)
+ }
+ part.Write([]byte("relation upload"))
+ for k, v := range fields {
+ writer.WriteField(k, v)
+ }
+ writer.Close()
+ req := httptest.NewRequest(http.MethodPost, "/api/upload-file", &body)
+ req.Header.Set("Content-Type", writer.FormDataContentType())
+ req.Header.Set("X-User-ID", userID)
+ req.Header.Set("X-Workspace-ID", testWorkspaceID)
+ return testutil.Call(t, testHandler.UploadFile, req)
+}
+
+func TestPrivateProjectUploadToHiddenComment(t *testing.T) {
+ f := newPrivateProjectFixture(t)
+ origStorage := testHandler.Storage
+ testHandler.Storage = &mockStorage{}
+ t.Cleanup(func() { testHandler.Storage = origStorage })
+ dbfx.Cleanup(t, `DELETE FROM attachment WHERE comment_id = $1`, f.secretComment)
+ count := func() int {
+ return dbfx.Count(t, `SELECT count(*) FROM attachment WHERE comment_id = $1`, f.secretComment)
+ }
+
+ uploadAs(t, f.outsider, map[string]string{"comment_id": f.secretComment}).Want(http.StatusForbidden)
+ uploadAs(t, f.outsider, map[string]string{"issue_id": f.publicIssue, "comment_id": f.secretComment}).Want(http.StatusForbidden)
+ if n := count(); n != 0 {
+ t.Fatalf("outsider uploads attached %d files to the hidden comment", n)
+ }
+ uploadAs(t, f.insider, map[string]string{"comment_id": f.secretComment}).Want(http.StatusOK)
+ if n := count(); n != 1 {
+ t.Fatalf("insider upload attached %d files, want 1", n)
+ }
+}
+
+func insertCommentOnlyAttachment(t *testing.T, commentID, filename string) string {
+ t.Helper()
+ return dbfx.Insert(t, "attachment", testutil.Cols{
+ "workspace_id": testWorkspaceID,
+ "comment_id": commentID,
+ "uploader_type": "member",
+ "uploader_id": testUserID,
+ "filename": filename,
+ "url": "https://example.invalid/" + filename,
+ "content_type": "text/plain",
+ "size_bytes": 1,
+ })
+}
+
+func attachmentIssueID(t *testing.T, attachmentID string) *string {
+ t.Helper()
+ var issueID *string
+ dbfx.QueryRow(t, `SELECT issue_id::text FROM attachment WHERE id = $1`, attachmentID).Scan(&issueID)
+ return issueID
+}
+
+// An attachment that carries only a comment id belongs to that comment's
+// issue; an issue write must not adopt it past the comment's project.
+func TestPrivateProjectAttachmentAdoptionSkipsHidden(t *testing.T) {
+ f := newPrivateProjectFixture(t)
+ secretFile := f.marker + "-secret-file.txt"
+ hiddenAtt := insertCommentOnlyAttachment(t, f.secretComment, secretFile)
+
+ putIssueAs(t, f.outsider, f.publicIssue, map[string]any{"attachment_ids": []string{hiddenAtt}}).Want(http.StatusOK)
+ if got := attachmentIssueID(t, hiddenAtt); got != nil {
+ t.Fatalf("outsider update adopted the hidden attachment into %s", *got)
+ }
+ if body := getIssueAs(t, f.outsider, f.publicIssue).Want(http.StatusOK).Text(); strings.Contains(body, secretFile) {
+ t.Fatalf("public issue exposes the hidden attachment: %s", body)
+ }
+
+ var created IssueResponse
+ testutil.Call(t, testHandler.CreateIssue, asUser(newRequest(http.MethodPost, "/api/issues", map[string]any{
+ "title": f.marker + " adopting create", "attachment_ids": []string{hiddenAtt},
+ }), f.outsider)).Want(http.StatusCreated).JSON(&created)
+ dbfx.Cleanup(t, `DELETE FROM issue WHERE id = $1`, created.ID)
+ if got := attachmentIssueID(t, hiddenAtt); got != nil {
+ t.Fatalf("outsider create adopted the hidden attachment into %s", *got)
+ }
+
+ // A caller who can see the comment keeps the existing adoption behavior.
+ visibleAtt := insertCommentOnlyAttachment(t, f.secretComment, f.marker+"-insider-file.txt")
+ own := dbfx.Issue(t, f.marker+" insider adopter", testutil.Cols{"number": relationIssueNumber()})
+ putIssueAs(t, f.insider, own, map[string]any{"attachment_ids": []string{visibleAtt}}).Want(http.StatusOK)
+ if got := attachmentIssueID(t, visibleAtt); got == nil || *got != own {
+ t.Fatalf("insider update did not adopt the visible attachment: %v", got)
+ }
+}
+
+// A sub-issue in a workspace project under a private parent: the parent group
+// must not name the parent to a reader outside its project.
+func TestPrivateProjectTableParentGroupHidden(t *testing.T) {
+ f := newPrivateProjectFixture(t)
+ publicProject := dbfx.Project(t, f.marker+" public project")
+ dbfx.Issue(t, f.marker+" public child", testutil.Cols{
+ "project_id": publicProject, "parent_issue_id": f.secretIssue, "number": relationIssueNumber(),
+ })
+ secretTitle := f.marker + " secret issue"
+ groups := func(userID string) string {
+ t.Helper()
+ req := asUser(newRequest(http.MethodPost, "/api/issues/table/groups", issueTableGroupsRequest{
+ Query: issueTableQuerySpec{
+ Scope: issueTableScope{Kind: "project", ProjectID: publicProject},
+ Sort: issueTableSortRequest{Field: "title", Direction: "asc"},
+ },
+ Group: issueTableGroupSpec{Kind: "parent"},
+ Page: issueTablePageRequest{Limit: 100},
+ }), userID)
+ return testutil.Call(t, testHandler.ListIssueTableGroups, req).Want(http.StatusOK).Text()
+ }
+ outsiderBody := groups(f.outsider)
+ if strings.Contains(outsiderBody, secretTitle) {
+ t.Errorf("outsider parent group names the hidden parent: %s", outsiderBody)
+ }
+ var outsider issueTableGroupsResponse
+ if err := json.Unmarshal([]byte(outsiderBody), &outsider); err != nil {
+ t.Fatal(err)
+ }
+ for _, g := range outsider.Groups {
+ if g.Value.ParentID != nil && *g.Value.ParentID == f.secretIssue && (g.Value.Parent != nil || g.Value.ValueState != "unavailable") {
+ t.Errorf("outsider hidden parent group = %+v, want unavailable with no parent ref", g.Value)
+ }
+ }
+ for _, userID := range []string{f.insider, testUserID} {
+ if body := groups(userID); !strings.Contains(body, secretTitle) {
+ t.Errorf("authorized reader %s lost the parent group title: %s", userID, body)
+ }
+ }
+}
+
+// A sub-issue created from a private thread into a workspace project keeps its
+// frozen snapshot, but the live source is not compared against for a reader
+// who cannot see it: nothing posted there after capture reaches them.
+func TestPrivateProjectSourceContextLiveThreadHidden(t *testing.T) {
+ f := newPrivateProjectFixture(t)
+ ctx := context.Background()
+ // Same lock as TestCommentSourceContextLifecycle: another package's intent
+ // sweeper must not claim this test's capture.
+ lockConn, err := testPool.Acquire(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := lockConn.Exec(ctx, `SELECT pg_advisory_lock($1)`, int64(0x53434f4e54455854)); err != nil {
+ lockConn.Release()
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ _, _ = lockConn.Exec(context.Background(), `SELECT pg_advisory_unlock($1)`, int64(0x53434f4e54455854))
+ lockConn.Release()
+ })
+ origStorage := testHandler.Storage
+ testHandler.Storage = &mockStorage{}
+ t.Cleanup(func() { testHandler.Storage = origStorage })
+
+ publicProject := dbfx.Project(t, f.marker+" source target project")
+ anchor := dbfx.Comment(t, f.secretIssue, f.marker+" anchor reply", testutil.Cols{"parent_id": f.secretComment})
+
+ var preview sourceContextPreviewResponse
+ previewReq := withURLParam(asUser(newRequest(http.MethodGet, "/api/comments/"+anchor+"/sub-issue-preview", nil), f.insider), "commentId", anchor)
+ testutil.Call(t, testHandler.PreviewCommentSubIssue, previewReq).Want(http.StatusOK).JSON(&preview)
+
+ var target IssueResponse
+ createReq := withURLParam(asUser(newRequest(http.MethodPost, "/api/comments/"+anchor+"/sub-issues", map[string]any{
+ "mode": "manual", "capture_token": preview.CaptureToken,
+ "issue": map[string]any{"title": f.marker + " public target", "status": "todo", "priority": "none", "project_id": publicProject},
+ }), f.insider), "commentId", anchor)
+ testutil.Call(t, testHandler.CreateCommentSubIssue, createReq).Want(http.StatusCreated).JSON(&target)
+ dbfx.Cleanup(t, `DELETE FROM issue WHERE id = $1`, target.ID)
+ dbfx.Cleanup(t, `DELETE FROM issue_source_context WHERE issue_id = $1`, target.ID)
+
+ // After capture, a file lands in the private description, and a comment
+ // with an earlier timestamp (as a backfill or import writes it) joins the
+ // captured part of the thread.
+ liveFile := f.marker + "-live-plan.pdf"
+ liveAtt := dbfx.Insert(t, "attachment", testutil.Cols{
+ "workspace_id": testWorkspaceID, "issue_id": f.secretIssue, "uploader_type": "member", "uploader_id": testUserID,
+ "filename": liveFile, "url": "https://example.invalid/" + liveFile, "content_type": "application/pdf", "size_bytes": 1,
+ })
+ dbfx.Exec(t, `UPDATE issue SET description = $1 WHERE id = $2`, "!file["+liveFile+"](/api/attachments/"+liveAtt+"/download)", f.secretIssue)
+ live := f.marker + " live reply after capture"
+ dbfx.Comment(t, f.secretIssue, live, testutil.Cols{
+ "parent_id": f.secretComment,
+ "created_at": testutil.Raw("(SELECT created_at + interval '1 microsecond' FROM comment WHERE id = '" + f.secretComment + "')"),
+ })
+
+ type detail struct {
+ SourceContext *struct {
+ DisplayState string `json:"display_state"`
+ CanOpenCurrentSource bool `json:"can_open_current_source"`
+ CurrentSource any `json:"current_source"`
+ Snapshot struct {
+ AnchorCommentID string `json:"anchor_comment_id"`
+ } `json:"snapshot"`
+ } `json:"source_context"`
+ }
+ var out detail
+ body := getIssueAs(t, f.outsider, target.ID).Want(http.StatusOK).JSON(&out).Text()
+ if strings.Contains(body, live) || strings.Contains(body, liveFile) {
+ t.Errorf("outsider sees content added to the hidden source after capture: %s", body)
+ }
+ if out.SourceContext == nil || out.SourceContext.Snapshot.AnchorCommentID != anchor {
+ t.Fatalf("outsider lost the frozen snapshot: %s", body)
+ }
+ if out.SourceContext.DisplayState != "unavailable" || out.SourceContext.CanOpenCurrentSource || out.SourceContext.CurrentSource != nil {
+ t.Errorf("outsider source state = %+v, want unavailable with no current source", out.SourceContext)
+ }
+ for _, userID := range []string{f.insider, testUserID} {
+ if body := getIssueAs(t, userID, target.ID).Want(http.StatusOK).Text(); !strings.Contains(body, live) || !strings.Contains(body, liveFile) {
+ t.Errorf("authorized reader %s no longer sees the live source change: %s", userID, body)
+ }
+ }
+}
+
+// Validations that run before the visibility check would tell a hidden id
+// from a missing one; each pair below must answer identically.
+func TestPrivateProjectRelationExistenceOracles(t *testing.T) {
+ f := newPrivateProjectFixture(t)
+ same := func(name string, hidden, missing *testutil.Response) {
+ t.Helper()
+ if hidden.Code != missing.Code || hidden.Text() != missing.Text() {
+ t.Errorf("%s: hidden answers %d %s, missing answers %d %s", name, hidden.Code, hidden.Text(), missing.Code, missing.Text())
+ }
+ }
+
+ move := func(userID string, body map[string]any) *testutil.Response {
+ req := withURLParam(asUser(newRequest(http.MethodPost, "/api/issues/"+f.publicIssue+"/move", body), userID), "id", f.publicIssue)
+ return testutil.Call(t, testHandler.MoveIssue, req)
+ }
+ same("move anchor",
+ move(f.outsider, map[string]any{"before_id": f.secretIssue, "after_id": nil}),
+ move(f.outsider, map[string]any{"before_id": uuid.NewString(), "after_id": nil}))
+ same("move project",
+ move(f.outsider, map[string]any{"project_id": f.projectID, "before_id": uuid.NewString(), "after_id": nil}),
+ move(f.outsider, map[string]any{"project_id": uuid.NewString(), "before_id": uuid.NewString(), "after_id": nil}))
+ if body := move(testUserID, map[string]any{"before_id": f.secretIssue, "after_id": nil}).Text(); strings.Contains(body, "move anchor not found") {
+ t.Errorf("workspace owner cannot anchor on the private issue: %s", body)
+ }
+
+ title := f.marker + " oracle create"
+ create := func(parentID string) *testutil.Response {
+ return testutil.Call(t, testHandler.CreateIssue, asUser(newRequest(http.MethodPost, "/api/issues", map[string]any{
+ "title": title, "parent_issue_id": parentID, "assignee_type": "agent", "assignee_id": uuid.NewString(),
+ }), f.outsider))
+ }
+ same("create parent with invalid assignee", create(f.secretIssue), create(uuid.NewString()))
+ if n := dbfx.Count(t, `SELECT count(*) FROM issue WHERE title = $1`, title); n != 0 {
+ t.Errorf("refused creates wrote %d issues", n)
+ }
+
+ subIssue := func(tokenIssueID string) *testutil.Response {
+ anchor := uuid.NewString()
+ token := "sha256:" + strings.Repeat("0", 64) + ":" + tokenIssueID
+ req := withURLParam(asUser(newRequest(http.MethodPost, "/api/comments/"+anchor+"/sub-issues", map[string]any{
+ "mode": "manual", "capture_token": token, "issue": map[string]any{"title": title, "status": "todo", "priority": "none"},
+ }), f.outsider), "commentId", anchor)
+ return testutil.Call(t, testHandler.CreateCommentSubIssue, req)
+ }
+ same("comment sub-issue token issue", subIssue(f.secretIssue), subIssue(uuid.NewString()))
+
+ agentID := seededReadyAgentID(t)
+ preview := func(userID string) IssueTriggerPreviewResponse {
+ var resp IssueTriggerPreviewResponse
+ testutil.Call(t, testHandler.PreviewIssueTrigger, asUser(newRequest(http.MethodPost, "/api/issues/preview-trigger", map[string]any{
+ "issue_ids": []string{f.secretIssue}, "assignee_type": "agent", "assignee_id": agentID,
+ }), userID)).Want(http.StatusOK).JSON(&resp)
+ return resp
+ }
+ if got := preview(f.outsider); got.TotalCount != 0 {
+ t.Errorf("outsider preview evaluates the hidden issue: %+v", got)
+ }
+ if got := preview(testUserID); got.TotalCount != 1 || got.Triggers[0].IssueID != f.secretIssue {
+ t.Errorf("workspace owner preview = %+v, want one run on the private issue", got)
+ }
+}
diff --git a/server/internal/handler/project_access.go b/server/internal/handler/project_access.go
index b29fe12b5f..f60026843f 100644
--- a/server/internal/handler/project_access.go
+++ b/server/internal/handler/project_access.go
@@ -226,37 +226,92 @@ func (h *Handler) requireAssigneeCanAccessProject(w http.ResponseWriter, r *http
return true
}
+// attachmentInHiddenProject reports whether an attachment belongs to an issue,
+// or to a comment on an issue, in one of the hidden projects. A comment
+// attachment need not carry its issue id, so the comment answers for it.
+func (h *Handler) attachmentInHiddenProject(ctx context.Context, hidden projectaccess.Hidden, att db.Attachment) (bool, error) {
+ if hidden.Empty() {
+ return false, nil
+ }
+ var projectID pgtype.UUID
+ var err error
+ switch {
+ case att.IssueID.Valid:
+ projectID, err = h.Queries.GetIssueProjectID(ctx, att.IssueID)
+ case att.CommentID.Valid:
+ projectID, err = h.Queries.GetCommentIssueProjectID(ctx, att.CommentID)
+ default:
+ return false, nil
+ }
+ if errors.Is(err, pgx.ErrNoRows) {
+ return false, nil
+ }
+ if err != nil {
+ return false, err
+ }
+ return !hidden.CanSeeProject(projectID), nil
+}
+
// requireAttachmentVisible 404s an attachment on an issue (or a comment on an
// issue) in a project the caller cannot see.
func (h *Handler) requireAttachmentVisible(w http.ResponseWriter, r *http.Request, workspaceID string, att db.Attachment) bool {
- if att.IssueID.Valid {
- return h.requireIssueIDVisible(w, r, workspaceID, att.IssueID, http.StatusNotFound, "attachment not found")
- }
- if !att.CommentID.Valid {
+ if !att.IssueID.Valid && !att.CommentID.Valid {
return true
}
hidden, ok := h.requestHiddenProjects(w, r, workspaceID)
if !ok {
return false
}
- if hidden.Empty() {
- return true
- }
- projectID, err := h.Queries.GetCommentIssueProjectID(r.Context(), att.CommentID)
- if errors.Is(err, pgx.ErrNoRows) {
- return true
- }
+ inHidden, err := h.attachmentInHiddenProject(r.Context(), hidden, att)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to resolve project access")
return false
}
- if !hidden.CanSeeProject(projectID) {
+ if inHidden {
writeError(w, http.StatusNotFound, "attachment not found")
return false
}
return true
}
+// visibleAttachmentIDs drops, from ids a write is about to adopt, every
+// attachment the request cannot see, so a hidden one is skipped exactly like
+// a missing one. It writes a 500 and returns ok=false when access cannot be
+// resolved.
+func (h *Handler) visibleAttachmentIDs(w http.ResponseWriter, r *http.Request, workspaceID pgtype.UUID, ids []pgtype.UUID) ([]pgtype.UUID, bool) {
+ if len(ids) == 0 {
+ return ids, true
+ }
+ hidden, ok := h.requestHiddenProjects(w, r, uuidToString(workspaceID))
+ if !ok {
+ return nil, false
+ }
+ if hidden.Empty() {
+ return ids, true
+ }
+ atts, err := h.Queries.ListAttachmentsByIDs(r.Context(), db.ListAttachmentsByIDsParams{AttachmentIds: ids, WorkspaceID: workspaceID})
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to resolve project access")
+ return nil, false
+ }
+ drop := map[pgtype.UUID]bool{}
+ for _, att := range atts {
+ inHidden, err := h.attachmentInHiddenProject(r.Context(), hidden, att)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to resolve project access")
+ return nil, false
+ }
+ drop[att.ID] = inHidden
+ }
+ out := ids[:0:0]
+ for _, id := range ids {
+ if !drop[id] {
+ out = append(out, id)
+ }
+ }
+ return out, true
+}
+
// requireChatProjectVisible gates a chat session's project context
// (MUL-8472). The context is injected into the chat agent's runs, so both the
// caller and the agent's owner must see the project; otherwise it 404s like a
diff --git a/server/internal/handler/search_index.go b/server/internal/handler/search_index.go
index 3380a236e4..62a687de9a 100644
--- a/server/internal/handler/search_index.go
+++ b/server/internal/handler/search_index.go
@@ -397,7 +397,7 @@ func (h *Handler) GetSearchIndexSnapshot(w http.ResponseWriter, r *http.Request)
}
resp := SearchIndexSnapshotResponse{
- Issues: h.searchIndexIssues(ctx, wsUUID, visibleIssues),
+ Issues: h.searchIndexIssues(ctx, wsUUID, hidden, visibleIssues),
Comments: make([]SearchIndexComment, 0, len(comments)),
Projects: searchIndexProjects(visibleProjects(hidden, projects)),
NextAfterNumber: nextAfterNumber,
@@ -550,7 +550,7 @@ func (h *Handler) ListSearchIndexChanges(w http.ResponseWriter, r *http.Request)
}
resp := SearchIndexChangesResponse{
- Issues: h.searchIndexIssues(ctx, wsUUID, issues),
+ Issues: h.searchIndexIssues(ctx, wsUUID, hidden, issues),
Comments: []SearchIndexComment{},
Projects: searchIndexProjects(projects),
Deleted: SearchIndexDeleted{
@@ -610,7 +610,7 @@ func (h *Handler) ListSearchIndexChanges(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusOK, resp)
}
-func (h *Handler) searchIndexIssues(ctx context.Context, wsUUID pgtype.UUID, issues []db.Issue) []SearchIndexIssue {
+func (h *Handler) searchIndexIssues(ctx context.Context, wsUUID pgtype.UUID, hidden projectaccess.Hidden, issues []db.Issue) []SearchIndexIssue {
out := make([]SearchIndexIssue, 0, len(issues))
if len(issues) == 0 {
return out
@@ -620,7 +620,7 @@ func (h *Handler) searchIndexIssues(ctx context.Context, wsUUID pgtype.UUID, iss
for _, is := range issues {
originals = appendDuplicateOriginal(originals, is.Status, is.DuplicateOfIssueID)
}
- fill := h.newStatusCategoryFiller(ctx, wsUUID, originals...)
+ fill := h.newStatusCategoryFiller(ctx, wsUUID, hidden, originals...)
for _, is := range issues {
resp := issueToResponse(is, prefix)
fill(&resp)
diff --git a/server/internal/handler/source_context.go b/server/internal/handler/source_context.go
index f0a940a02b..1b58cfb361 100644
--- a/server/internal/handler/source_context.go
+++ b/server/internal/handler/source_context.go
@@ -17,6 +17,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/logger"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
"github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
agentpkg "github.com/multica-ai/multica/server/pkg/agent"
@@ -244,7 +245,11 @@ func sourceContextThreadChangeReasons(captured, current service.SourceContextSna
return sourceContextThreadChangeDetails(captured, current).Reasons
}
-func (h *Handler) issueSourceContextDetail(ctx context.Context, issue db.Issue) (*sourceContextDetailResponse, error) {
+// issueSourceContextDetail renders an issue's frozen source context for one
+// reader. hidden is the reader's hidden projects: when the live source issue
+// is in one, only the frozen snapshot is returned and the live source reads as
+// unavailable, so nothing posted there after capture reaches this reader.
+func (h *Handler) issueSourceContextDetail(ctx context.Context, issue db.Issue, hidden projectaccess.Hidden) (*sourceContextDetailResponse, error) {
row, err := h.Queries.GetIssueSourceContextByIssue(ctx, db.GetIssueSourceContextByIssueParams{WorkspaceID: issue.WorkspaceID, IssueID: issue.ID})
if err != nil {
return nil, err
@@ -274,6 +279,25 @@ func (h *Handler) issueSourceContextDetail(ctx context.Context, issue db.Issue)
} else if errors.Is(anchorErr, pgx.ErrNoRows) || anchorErr == nil {
response.AnchorCommentState = "deleted"
}
+ liveSourceID := row.SourceIssueID
+ if anchorExists {
+ liveSourceID = anchor.IssueID
+ }
+ if !hidden.Empty() {
+ projectID, err := h.Queries.GetIssueProjectID(ctx, liveSourceID)
+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ return nil, fmt.Errorf("resolve source issue project: %w", err)
+ }
+ if err == nil && !hidden.CanSeeProject(projectID) {
+ response.DisplayState = "unavailable"
+ response.SourceIssueState = "unavailable"
+ response.CommentThreadState = "unavailable"
+ response.AnchorCommentState = "unavailable"
+ response.CanOpenCurrentSource = false
+ response.CurrentSource = nil
+ return response, nil
+ }
+ }
var currentIssue service.SourceContextIssueSnapshot
var currentIssueErr error
@@ -485,8 +509,18 @@ func (h *Handler) CreateCommentSubIssue(w http.ResponseWriter, r *http.Request)
}
build, err := service.BuildSourceContext(r.Context(), h.Queries, wsUUID, anchorCommentID)
if errors.Is(err, service.ErrAnchorCommentDeleted) {
- if _, issueErr := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{ID: tokenIssueID, WorkspaceID: wsUUID}); errors.Is(issueErr, pgx.ErrNoRows) {
+ // The token's issue id comes from the client; one in a project the
+ // caller cannot see answers like a deleted one.
+ tokenIssue, issueErr := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{ID: tokenIssueID, WorkspaceID: wsUUID})
+ if errors.Is(issueErr, pgx.ErrNoRows) {
err = service.ErrSourceIssueDeleted
+ } else if issueErr == nil {
+ hidden, hiddenErr := h.hiddenProjects(r, workspaceID)
+ if hiddenErr != nil {
+ err = hiddenErr
+ } else if !hidden.CanSeeProject(tokenIssue.ProjectID) {
+ err = service.ErrSourceIssueDeleted
+ }
}
}
if err != nil {
@@ -707,6 +741,10 @@ func (h *Handler) createManualCommentSubIssue(w http.ResponseWriter, r *http.Req
if !ok {
return errSourceContextResponseWritten
}
+ attachmentIDs, ok = h.visibleAttachmentIDs(w, r, workspaceID, attachmentIDs)
+ if !ok {
+ return errSourceContextResponseWritten
+ }
labelIDs, ok := parseUUIDSliceOrBadRequest(w, input.LabelIDs, "label_ids")
if !ok {
return errSourceContextResponseWritten
@@ -761,7 +799,7 @@ func (h *Handler) createManualCommentSubIssue(w http.ResponseWriter, r *http.Req
return err
}
response := issueToResponse(result.Issue, prefix)
- h.fillStatusCategory(r.Context(), workspaceID, &response)
+ h.fillStatusCategory(r.Context(), workspaceID, projectaccess.Hidden{}, &response)
labelResponses := labelsToResponse(result.Labels)
response.Labels = &labelResponses
slog.Info("sub-issue created from captured comment", append(sourceContextAuditAttrs(r, capture.ID, capture.Snapshot.SourceIssue.ID, capture.Snapshot.AnchorCommentID, userID, "manual", limits, "success"), "target_issue_id", uuidToString(result.Issue.ID))...)
@@ -855,6 +893,10 @@ func (h *Handler) prepareAgentCommentSubIssue(w http.ResponseWriter, r *http.Req
if !ok {
return nil, errSourceContextResponseWritten
}
+ attachmentIDs, ok = h.visibleAttachmentIDs(w, r, workspaceID, attachmentIDs)
+ if !ok {
+ return nil, errSourceContextResponseWritten
+ }
var projectID pgtype.UUID
if strings.TrimSpace(input.ProjectID) != "" {
parsed, err := util.ParseUUID(strings.TrimSpace(input.ProjectID))
diff --git a/server/internal/handler/source_context_integration_test.go b/server/internal/handler/source_context_integration_test.go
index 42b7ec4e16..f08bf08a1e 100644
--- a/server/internal/handler/source_context_integration_test.go
+++ b/server/internal/handler/source_context_integration_test.go
@@ -16,6 +16,7 @@ import (
"github.com/multica-ai/multica/server/internal/entitlement/entitlementtest"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/middleware"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
"github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -493,7 +494,7 @@ func TestCommentSourceContextLifecycle(t *testing.T) {
if err != nil {
t.Fatalf("load target issue: %v", err)
}
- detail, err := testHandler.issueSourceContextDetail(ctx, issue)
+ detail, err := testHandler.issueSourceContextDetail(ctx, issue, projectaccess.Hidden{})
if err != nil {
t.Fatalf("load changed source detail: %v", err)
}
@@ -526,7 +527,7 @@ func TestCommentSourceContextLifecycle(t *testing.T) {
if _, err := testPool.Exec(ctx, `UPDATE comment SET parent_id = NULL WHERE id = $1`, replyID); err != nil {
t.Fatalf("re-root source reply: %v", err)
}
- changedPathDetail, err := testHandler.issueSourceContextDetail(ctx, issue)
+ changedPathDetail, err := testHandler.issueSourceContextDetail(ctx, issue, projectaccess.Hidden{})
if err != nil {
t.Fatalf("load changed-path detail: %v", err)
}
@@ -554,7 +555,7 @@ func TestCommentSourceContextLifecycle(t *testing.T) {
if _, err := testPool.Exec(ctx, `UPDATE issue SET description = 'frozen issue body', revision = revision + 1, updated_at = now() WHERE id = $1`, sourceIssueID); err != nil {
t.Fatalf("remove live issue attachment reference: %v", err)
}
- attachmentDetail, err := testHandler.issueSourceContextDetail(ctx, issue)
+ attachmentDetail, err := testHandler.issueSourceContextDetail(ctx, issue, projectaccess.Hidden{})
if err != nil {
t.Fatalf("load attachment-changed detail: %v", err)
}
@@ -591,7 +592,7 @@ func TestCommentSourceContextLifecycle(t *testing.T) {
if _, err := testPool.Exec(ctx, `DELETE FROM comment WHERE id = $1`, selectedID); err != nil {
t.Fatalf("delete anchor comment: %v", err)
}
- deletedPathDetail, err := testHandler.issueSourceContextDetail(ctx, issue)
+ deletedPathDetail, err := testHandler.issueSourceContextDetail(ctx, issue, projectaccess.Hidden{})
if err != nil {
t.Fatalf("load deleted-path detail: %v", err)
}
@@ -632,7 +633,7 @@ func TestCommentSourceContextLifecycle(t *testing.T) {
if !ok || updatedIssue.ID != targetIssueID || updatedIssue.ParentIssueID != nil || updatedIssue.Stage != nil {
t.Fatalf("detached child update issue = %#v", updatePayload["issue"])
}
- deletedDetail, err := testHandler.issueSourceContextDetail(ctx, detached)
+ deletedDetail, err := testHandler.issueSourceContextDetail(ctx, detached, projectaccess.Hidden{})
if err != nil {
t.Fatalf("load deleted-source detail: %v", err)
}
diff --git a/server/internal/handler/subscriber.go b/server/internal/handler/subscriber.go
index 0cfcda6966..a36e92858d 100644
--- a/server/internal/handler/subscriber.go
+++ b/server/internal/handler/subscriber.go
@@ -93,13 +93,19 @@ func (h *Handler) ListSubscribedIssueIDs(w http.ResponseWriter, r *http.Request)
if !ok {
return
}
- wsUUID, ok := parseUUIDOrBadRequest(w, ctxWorkspaceID(r.Context()), "workspace id")
+ workspaceID := ctxWorkspaceID(r.Context())
+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
+ if !ok {
+ return
+ }
+ hidden, ok := h.requestHiddenProjects(w, r, workspaceID)
if !ok {
return
}
ids, err := h.Queries.ListSubscribedIssueIDs(r.Context(), db.ListSubscribedIssueIDsParams{
- WorkspaceID: wsUUID,
- UserID: parseUUID(userID),
+ WorkspaceID: wsUUID,
+ UserID: parseUUID(userID),
+ HiddenProjectIds: hidden.Param(),
})
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list subscribed issues")
diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.go
index 16002f8877..f858398ba7 100644
--- a/server/pkg/db/generated/issue.sql.go
+++ b/server/pkg/db/generated/issue.sql.go
@@ -1371,7 +1371,7 @@ func (q *Queries) ListIssueGCStatuses(ctx context.Context, arg ListIssueGCStatus
}
const listIssueRefsInWorkspace = `-- name: ListIssueRefsInWorkspace :many
-SELECT id, number, title, status FROM issue
+SELECT id, number, title, status, project_id FROM issue
WHERE workspace_id = $1
AND id = ANY($2::uuid[])
`
@@ -1382,10 +1382,11 @@ type ListIssueRefsInWorkspaceParams struct {
}
type ListIssueRefsInWorkspaceRow struct {
- ID pgtype.UUID `json:"id"`
- Number int32 `json:"number"`
- Title string `json:"title"`
- Status string `json:"status"`
+ ID pgtype.UUID `json:"id"`
+ Number int32 `json:"number"`
+ Title string `json:"title"`
+ Status string `json:"status"`
+ ProjectID pgtype.UUID `json:"project_id"`
}
// GetIssueRefInWorkspace for a page: every original the page's duplicates
@@ -1404,6 +1405,7 @@ func (q *Queries) ListIssueRefsInWorkspace(ctx context.Context, arg ListIssueRef
&i.Number,
&i.Title,
&i.Status,
+ &i.ProjectID,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/generated/issue_label.sql.go b/server/pkg/db/generated/issue_label.sql.go
index dd75801c82..41ae830dc1 100644
--- a/server/pkg/db/generated/issue_label.sql.go
+++ b/server/pkg/db/generated/issue_label.sql.go
@@ -392,20 +392,27 @@ func (q *Queries) GetLabel(ctx context.Context, arg GetLabelParams) (IssueLabel,
const listLabels = `-- name: ListLabels :many
SELECT l.id, l.workspace_id, l.name, l.color, l.created_at, l.updated_at, l.resource_type, l.description,
CASE l.resource_type
- WHEN 'issue' THEN (SELECT COUNT(*) FROM issue_to_label x WHERE x.label_id = l.id)
+ -- MUL-8472: issues in private projects the caller cannot see are not counted.
+ WHEN 'issue' THEN (SELECT COUNT(*) FROM issue_to_label x WHERE x.label_id = l.id
+ AND ($1::uuid[] IS NULL OR NOT EXISTS (
+ SELECT 1 FROM issue hidden_issue
+ WHERE hidden_issue.id = x.issue_id
+ AND hidden_issue.project_id = ANY($1::uuid[])
+ )))
WHEN 'agent' THEN (SELECT COUNT(*) FROM agent_to_label x WHERE x.label_id = l.id)
WHEN 'skill' THEN (SELECT COUNT(*) FROM skill_to_label x WHERE x.label_id = l.id)
ELSE 0
END::bigint AS usage_count
FROM issue_label l
-WHERE l.workspace_id = $1::uuid
- AND l.resource_type = $2::text
+WHERE l.workspace_id = $2::uuid
+ AND l.resource_type = $3::text
ORDER BY LOWER(name) ASC
`
type ListLabelsParams struct {
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- ResourceType string `json:"resource_type"`
+ HiddenProjectIds []pgtype.UUID `json:"hidden_project_ids"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ResourceType string `json:"resource_type"`
}
type ListLabelsRow struct {
@@ -421,7 +428,7 @@ type ListLabelsRow struct {
}
func (q *Queries) ListLabels(ctx context.Context, arg ListLabelsParams) ([]ListLabelsRow, error) {
- rows, err := q.db.Query(ctx, listLabels, arg.WorkspaceID, arg.ResourceType)
+ rows, err := q.db.Query(ctx, listLabels, arg.HiddenProjectIds, arg.WorkspaceID, arg.ResourceType)
if err != nil {
return nil, err
}
diff --git a/server/pkg/db/generated/subscriber.sql.go b/server/pkg/db/generated/subscriber.sql.go
index b38a785e4d..c49aa6aa36 100644
--- a/server/pkg/db/generated/subscriber.sql.go
+++ b/server/pkg/db/generated/subscriber.sql.go
@@ -346,17 +346,20 @@ WHERE i.workspace_id = $1
AND s.user_type = 'member'
AND s.user_id = $2
AND s.unsubscribed_at IS NULL
+ -- MUL-8472: private projects the caller cannot see.
+ AND ($3::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY($3::uuid[])))
`
type ListSubscribedIssueIDsParams struct {
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- UserID pgtype.UUID `json:"user_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UserID pgtype.UUID `json:"user_id"`
+ HiddenProjectIds []pgtype.UUID `json:"hidden_project_ids"`
}
// Every issue in the workspace the member actively subscribes to; opt-out
// tombstones do not count.
func (q *Queries) ListSubscribedIssueIDs(ctx context.Context, arg ListSubscribedIssueIDsParams) ([]pgtype.UUID, error) {
- rows, err := q.db.Query(ctx, listSubscribedIssueIDs, arg.WorkspaceID, arg.UserID)
+ rows, err := q.db.Query(ctx, listSubscribedIssueIDs, arg.WorkspaceID, arg.UserID, arg.HiddenProjectIds)
if err != nil {
return nil, err
}
diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sql
index 17e7258c8e..87f46279c0 100644
--- a/server/pkg/db/queries/issue.sql
+++ b/server/pkg/db/queries/issue.sql
@@ -390,7 +390,7 @@ WHERE id = $1 AND workspace_id = $2;
-- name: ListIssueRefsInWorkspace :many
-- GetIssueRefInWorkspace for a page: every original the page's duplicates
-- point at, in one read.
-SELECT id, number, title, status FROM issue
+SELECT id, number, title, status, project_id FROM issue
WHERE workspace_id = sqlc.arg('workspace_id')
AND id = ANY(sqlc.arg('ids')::uuid[]);
diff --git a/server/pkg/db/queries/issue_label.sql b/server/pkg/db/queries/issue_label.sql
index d315a6d22a..cbfff065fc 100644
--- a/server/pkg/db/queries/issue_label.sql
+++ b/server/pkg/db/queries/issue_label.sql
@@ -1,7 +1,13 @@
-- name: ListLabels :many
SELECT l.*,
CASE l.resource_type
- WHEN 'issue' THEN (SELECT COUNT(*) FROM issue_to_label x WHERE x.label_id = l.id)
+ -- MUL-8472: issues in private projects the caller cannot see are not counted.
+ WHEN 'issue' THEN (SELECT COUNT(*) FROM issue_to_label x WHERE x.label_id = l.id
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR NOT EXISTS (
+ SELECT 1 FROM issue hidden_issue
+ WHERE hidden_issue.id = x.issue_id
+ AND hidden_issue.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])
+ )))
WHEN 'agent' THEN (SELECT COUNT(*) FROM agent_to_label x WHERE x.label_id = l.id)
WHEN 'skill' THEN (SELECT COUNT(*) FROM skill_to_label x WHERE x.label_id = l.id)
ELSE 0
diff --git a/server/pkg/db/queries/subscriber.sql b/server/pkg/db/queries/subscriber.sql
index 7ad4c122ea..82300d2e9f 100644
--- a/server/pkg/db/queries/subscriber.sql
+++ b/server/pkg/db/queries/subscriber.sql
@@ -265,7 +265,9 @@ JOIN issue i ON i.id = s.issue_id
WHERE i.workspace_id = sqlc.arg(workspace_id)
AND s.user_type = 'member'
AND s.user_id = sqlc.arg(user_id)
- AND s.unsubscribed_at IS NULL;
+ AND s.unsubscribed_at IS NULL
+ -- MUL-8472: private projects the caller cannot see.
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])));
-- name: IsIssueSubscriber :one
SELECT EXISTS(