Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
package handler
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"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/testutil"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
// privateProjectFixture: a private project whose members are the workspace
// owner (testUserID) and one regular member (insider), a regular workspace
// member outside it (outsider), a workspace admin outside it (outsideAdmin),
// an issue and a comment inside it, and a public issue outside any project.
type privateProjectFixture struct {
projectID string
insider string
outsider string
outsideAdmin string
secretIssue string
secretComment string
publicIssue string
marker string
}
func newPrivateProjectFixture(t *testing.T) privateProjectFixture {
t.Helper()
marker := fmt.Sprintf("pp%d", time.Now().UnixNano())
f := privateProjectFixture{marker: marker}
f.insider = createPlainMember(t, marker+"[email protected]")
f.outsider = createPlainMember(t, marker+"[email protected]")
f.outsideAdmin = createWorkspaceAdmin(t, marker+"[email protected]")
f.projectID = dbfx.Project(t, marker+" secret project", testutil.Cols{"visibility": projectaccess.VisibilityPrivate})
addProjectMemberRow(t, f.projectID, testUserID)
addProjectMemberRow(t, f.projectID, f.insider)
// Explicit numbers far above the workspace counter keep these rows clear
// of the numbers CreateIssue allocates in the same test.
base := 800000 + int(time.Now().UnixNano()%100000)*2
f.secretIssue = dbfx.Issue(t, marker+" secret issue", testutil.Cols{"project_id": f.projectID, "number": base})
f.secretComment = dbfx.Comment(t, f.secretIssue, marker+" secret comment")
f.publicIssue = dbfx.Issue(t, marker+" public issue", testutil.Cols{"number": base + 1})
return f
}
// createWorkspaceAdmin adds a workspace admin who is a member of no private
// project: the role must not let them see one.
func createWorkspaceAdmin(t *testing.T, email string) string {
t.Helper()
userID := createPlainMember(t, email)
if _, err := testPool.Exec(context.Background(),
`UPDATE member SET role = 'admin' WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, userID); err != nil {
t.Fatalf("promote admin: %v", err)
}
return userID
}
func removeProjectMemberRow(t *testing.T, projectID, userID string) {
t.Helper()
if _, err := testPool.Exec(context.Background(),
`DELETE FROM project_member WHERE project_id = $1 AND user_id = $2`, projectID, userID); err != nil {
t.Fatalf("remove project member: %v", err)
}
}
func addProjectMemberRow(t *testing.T, projectID, userID string) {
t.Helper()
dbfx.InsertNoID(t, "project_member", testutil.Cols{
"workspace_id": testWorkspaceID,
"project_id": projectID,
"user_id": userID,
}, "project_id = $1 AND user_id = $2", projectID, userID)
}
func asUser(req *http.Request, userID string) *http.Request {
req.Header.Set("X-User-ID", userID)
return req
}
func TestPrivateProjectIssueDetailMatrix(t *testing.T) {
f := newPrivateProjectFixture(t)
get := func(userID, issueID string) int {
req := withURLParam(asUser(newRequest(http.MethodGet, "/api/issues/"+issueID, nil), userID), "id", issueID)
rec := httptest.NewRecorder()
testHandler.GetIssue(rec, req)
return rec.Code
}
for _, tc := range []struct {
name string
userID string
want int
}{
{"project member", f.insider, http.StatusOK},
{"workspace owner in the member list", testUserID, http.StatusOK},
{"workspace member outside the project", f.outsider, http.StatusNotFound},
{"workspace admin outside the project", f.outsideAdmin, http.StatusNotFound},
} {
if got := get(tc.userID, f.secretIssue); got != tc.want {
t.Errorf("%s: GET secret issue = %d, want %d", tc.name, got, tc.want)
}
}
if got := get(f.outsider, f.publicIssue); got != http.StatusOK {
t.Errorf("outsider GET public issue = %d, want 200", got)
}
// Sub-resources go through the same loader.
req := withURLParam(asUser(newRequest(http.MethodGet, "/api/issues/"+f.secretIssue+"/comments", nil), f.outsider), "id", f.secretIssue)
testutil.Call(t, testHandler.ListComments, req).Want(http.StatusNotFound)
}
func TestPrivateProjectHiddenFromLists(t *testing.T) {
f := newPrivateProjectFixture(t)
listIssueIDs := func(userID, query string) map[string]bool {
req := asUser(newRequest(http.MethodGet, "/api/issues?"+query, nil), userID)
var resp struct {
Issues []IssueResponse `json:"issues"`
}
testutil.Call(t, testHandler.ListIssues, req).Want(http.StatusOK).JSON(&resp)
ids := map[string]bool{}
for _, is := range resp.Issues {
ids[is.ID] = true
}
return ids
}
for _, query := range []string{"limit=100", "open_only=true"} {
outsider := listIssueIDs(f.outsider, query)
if outsider[f.secretIssue] || !outsider[f.publicIssue] {
t.Errorf("%s: outsider sees secret=%v public=%v", query, outsider[f.secretIssue], outsider[f.publicIssue])
}
if insider := listIssueIDs(f.insider, query); !insider[f.secretIssue] {
t.Errorf("%s: insider does not see the secret issue", query)
}
}
listProjectIDs := func(userID string) map[string]bool {
var resp struct {
Projects []ProjectResponse `json:"projects"`
}
testutil.Call(t, testHandler.ListProjects, asUser(newRequest(http.MethodGet, "/api/projects", nil), userID)).
Want(http.StatusOK).JSON(&resp)
ids := map[string]bool{}
for _, p := range resp.Projects {
ids[p.ID] = true
if p.ID == f.projectID && p.Visibility != projectaccess.VisibilityPrivate {
t.Errorf("project visibility = %q, want private", p.Visibility)
}
}
return ids
}
if listProjectIDs(f.outsider)[f.projectID] {
t.Error("outsider sees the private project in the project list")
}
if listProjectIDs(f.outsideAdmin)[f.projectID] {
t.Error("workspace admin outside the project sees it in the project list")
}
if !listProjectIDs(f.insider)[f.projectID] {
t.Error("project member does not see the private project in the project list")
}
search := func(userID string) map[string]bool {
req := asUser(newRequest(http.MethodGet, "/api/issues/search?q="+f.marker, nil), userID)
var resp struct {
Issues []struct {
ID string `json:"id"`
} `json:"issues"`
}
testutil.Call(t, testHandler.SearchIssues, req).Want(http.StatusOK).JSON(&resp)
ids := map[string]bool{}
for _, is := range resp.Issues {
ids[is.ID] = true
}
return ids
}
if got := search(f.outsider); got[f.secretIssue] || !got[f.publicIssue] {
t.Errorf("outsider search: secret=%v public=%v", got[f.secretIssue], got[f.publicIssue])
}
if !search(f.insider)[f.secretIssue] {
t.Error("insider search misses the secret issue")
}
projectReq := withURLParam(asUser(newRequest(http.MethodGet, "/api/projects/"+f.projectID, nil), f.outsider), "id", f.projectID)
testutil.Call(t, testHandler.GetProject, projectReq).Want(http.StatusNotFound)
}
func TestPrivateProjectSearchProjectFilter(t *testing.T) {
f := newPrivateProjectFixture(t)
commentIssue := dbfx.Issue(t, "comment-only search hit", testutil.Cols{"project_id": f.projectID})
dbfx.Comment(t, commentIssue, f.marker+" matching comment")
for _, includeClosed := range []string{"false", "true"} {
for _, userID := range []string{f.insider, f.outsider, testUserID} {
req := asUser(newRequest(http.MethodGet, "/api/issues/search?q="+f.marker+"&project_id="+f.projectID+"&include_closed="+includeClosed, nil), userID)
var resp struct {
Issues []SearchIssueResponse `json:"issues"`
}
testutil.Call(t, testHandler.SearchIssues, req).Want(http.StatusOK).JSON(&resp)
if userID == f.outsider {
if len(resp.Issues) != 0 {
t.Fatalf("outsider project search (include_closed=%s) exposed %+v", includeClosed, resp.Issues)
}
continue
}
if len(resp.Issues) != 2 {
t.Fatalf("authorized project search (include_closed=%s) = %+v, want title and comment hits", includeClosed, resp.Issues)
}
for _, issue := range resp.Issues {
if issue.ID != f.secretIssue && issue.ID != commentIssue {
t.Fatalf("project search returned an issue outside the selected project: %+v", issue)
}
}
}
}
}
func TestPrivateProjectSubtreeRunsAreRedacted(t *testing.T) {
f := newPrivateProjectFixture(t)
dbfx.Exec(t, "UPDATE issue SET parent_issue_id=$1 WHERE id=$2", f.publicIssue, f.secretIssue)
agentID := dbfx.Agent(t, f.marker+" subtree agent", testRuntimeID, testutil.Cols{"owner_id": f.insider})
taskID := dbfx.Task(t, agentID, testutil.Cols{
"issue_id": f.secretIssue, "runtime_id": testRuntimeID, "status": "completed",
"result": testutil.Raw(`'{"output":"private subtree result","comment":"private inline result"}'::jsonb`),
"handoff_note": "private handoff",
})
for _, view := range []string{"", "&view=timeline"} {
for _, userID := range []string{f.outsider, f.insider, testUserID} {
req := withURLParam(asUser(newRequest(http.MethodGet, "/api/issues/"+f.publicIssue+"/task-runs?scope=subtree"+view, nil), userID), "id", f.publicIssue)
var runs []AgentTaskResponse
testutil.Call(t, testHandler.ListTasksByIssue, req).Want(http.StatusOK).JSON(&runs)
if len(runs) != 1 || runs[0].ID != taskID {
t.Fatalf("subtree runs = %+v, want descendant run %s", runs, taskID)
}
run := runs[0]
if userID == f.outsider {
if !run.Restricted || run.IssueID != "" || run.IssueTitle != "" || run.IssueIdentifier != "" || run.Result != nil || run.HandoffNote != "" {
t.Fatalf("private descendant run exposed to outsider: %+v", run)
}
} else if run.Restricted || run.IssueID != f.secretIssue || run.IssueTitle == "" || run.Result == nil {
t.Fatalf("authorized viewer lost descendant run content: %+v", run)
}
}
}
}
func TestPrivateProjectCommentAndAttachmentByID(t *testing.T) {
f := newPrivateProjectFixture(t)
react := func(userID string) int {
req := withURLParam(asUser(newRequest(http.MethodPost, "/api/comments/"+f.secretComment+"/reactions", map[string]any{"emoji": "👍"}), userID), "commentId", f.secretComment)
rec := httptest.NewRecorder()
testHandler.AddReaction(rec, req)
return rec.Code
}
if got := react(f.outsider); got != http.StatusNotFound {
t.Errorf("outsider reaction on secret comment = %d, want 404", got)
}
if got := react(f.insider); got >= 400 {
t.Errorf("insider reaction on secret comment = %d, want success", got)
}
testPool.Exec(context.Background(), `DELETE FROM comment_reaction WHERE comment_id = $1`, f.secretComment)
attachmentID := dbfx.Insert(t, "attachment", testutil.Cols{
"workspace_id": testWorkspaceID,
"issue_id": f.secretIssue,
"uploader_type": "member",
"uploader_id": testUserID,
"filename": "secret.txt",
"url": "https://example.invalid/secret.txt",
"content_type": "text/plain",
"size_bytes": 1,
})
req := withURLParam(asUser(newRequest(http.MethodGet, "/api/attachments/"+attachmentID, nil), f.outsider), "id", attachmentID)
testutil.Call(t, testHandler.GetAttachmentByID, req).Want(http.StatusNotFound)
}
func TestPrivateProjectWritesNeedVisibility(t *testing.T) {
f := newPrivateProjectFixture(t)
create := func(userID string, body map[string]any) *testutil.Response {
return testutil.Call(t, testHandler.CreateIssue, asUser(newRequest(http.MethodPost, "/api/issues", body), userID))
}
create(f.outsider, map[string]any{"title": f.marker + " smuggled", "project_id": f.projectID}).Want(http.StatusBadRequest)
create(f.outsider, map[string]any{"title": f.marker + " child", "parent_issue_id": f.secretIssue}).Want(http.StatusBadRequest)
var created IssueResponse
create(f.insider, map[string]any{"title": f.marker + " insider issue", "project_id": f.projectID}).Want(http.StatusCreated).JSON(&created)
t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, created.ID) })
// Moving a public issue into the private project needs the same access.
move := withURLParam(asUser(newRequest(http.MethodPut, "/api/issues/"+f.publicIssue, map[string]any{"project_id": f.projectID}), f.outsider), "id", f.publicIssue)
testutil.Call(t, testHandler.UpdateIssue, move).Want(http.StatusBadRequest)
}
func TestPrivateProjectVisibilityAndMembersAPI(t *testing.T) {
f := newPrivateProjectFixture(t)
createPrivate := func() *testutil.Response {
return testutil.Call(t, testHandler.CreateProject, asUser(newRequest(http.MethodPost, "/api/projects", map[string]any{
"title": f.marker + " new private",
"visibility": "private",
"member_ids": []string{f.insider},
}), f.insider))
}
var project ProjectResponse
createPrivate().Want(http.StatusCreated).JSON(&project)
t.Cleanup(func() {
testPool.Exec(context.Background(), `DELETE FROM project_member WHERE project_id = $1`, project.ID)
testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, project.ID)
})
if project.Visibility != projectaccess.VisibilityPrivate {
t.Fatalf("visibility = %q", project.Visibility)
}
// No lead was named and none is invented. The creator manages access to
// the project they made, which is what lets a regular member run one.
if project.LeadType != nil || project.LeadID != nil {
t.Fatalf("lead = %v %v, want none", project.LeadType, project.LeadID)
}
members := func(userID string) *testutil.Response {
req := withURLParam(asUser(newRequest(http.MethodGet, "/api/projects/"+project.ID+"/members", nil), userID), "id", project.ID)
return testutil.Call(t, testHandler.ListProjectMembers, req)
}
members(f.outsider).Want(http.StatusNotFound)
var list struct {
Members []ProjectMemberResponse `json:"members"`
ManagerID *string `json:"manager_id"`
}
members(f.insider).Want(http.StatusOK).JSON(&list)
if len(list.Members) != 1 || list.Members[0].UserID != f.insider {
t.Fatalf("members = %+v, want only the creator", list.Members)
}
if list.ManagerID == nil || *list.ManagerID != f.insider {
t.Fatalf("manager_id = %v, want the creator", list.ManagerID)
}
add := func(userID string, ids ...string) *testutil.Response {
req := withURLParam(asUser(newRequest(http.MethodPost, "/api/projects/"+project.ID+"/members", map[string]any{"user_ids": ids}), userID), "id", project.ID)
return testutil.Call(t, testHandler.AddProjectMembers, req)
}
remove := func(actor, target string) *testutil.Response {
req := testutil.WithURLParams(asUser(newRequest(http.MethodDelete, "/api/projects/"+project.ID+"/members/"+target, nil), actor), "id", project.ID, "userId", target)
return testutil.Call(t, testHandler.RemoveProjectMember, req)
}
update := func(userID string, body map[string]any) *testutil.Response {
req := withURLParam(asUser(newRequest(http.MethodPut, "/api/projects/"+project.ID, body), userID), "id", project.ID)
return testutil.Call(t, testHandler.UpdateProject, req)
}
// A workspace role is not a way in: the owner and an admin outside the
// member list cannot read the project, let alone manage it.
for _, manager := range []string{testUserID, f.outsideAdmin} {
members(manager).Want(http.StatusNotFound)
add(manager, manager).Want(http.StatusNotFound)
remove(manager, f.insider).Want(http.StatusNotFound)
update(manager, map[string]any{"visibility": "workspace"}).Want(http.StatusNotFound)
}
members(f.insider).Want(http.StatusOK).JSON(&list)
if len(list.Members) != 1 || list.Members[0].UserID != f.insider {
t.Fatal("refused requests changed project membership")
}
// The creator adds; unknown workspace users are rejected.
add(f.insider, "00000000-0000-0000-0000-00000000beef").Want(http.StatusBadRequest)
add(f.insider, f.outsider, testUserID).Want(http.StatusOK)
// An ordinary project member manages nothing, self-removal included.
add(f.outsider, f.outsideAdmin).Want(http.StatusForbidden)
remove(f.outsider, f.insider).Want(http.StatusForbidden)
remove(f.outsider, f.outsider).Want(http.StatusForbidden)
update(f.outsider, map[string]any{"visibility": "workspace"}).Want(http.StatusForbidden)
members(f.outsider).Want(http.StatusOK)
// Once in the member list, a workspace owner manages access too.
remove(testUserID, f.outsider).Want(http.StatusNoContent)
members(f.outsider).Want(http.StatusNotFound)
// And a member can be removed whatever their workspace role.
remove(f.insider, testUserID).Want(http.StatusNoContent)
members(testUserID).Want(http.StatusNotFound)
var updated ProjectResponse
update(f.insider, map[string]any{"visibility": "workspace"}).Want(http.StatusOK).JSON(&updated)
if updated.Visibility != projectaccess.VisibilityWorkspace {
t.Fatalf("visibility after switch = %q", updated.Visibility)
}
members(f.outsider).Want(http.StatusOK)
}
func TestPrivateProjectTaskTranscriptAndRunHistory(t *testing.T) {
f := newPrivateProjectFixture(t)
var agentID string
if err := testPool.QueryRow(context.Background(),
`SELECT id FROM agent WHERE workspace_id = $1 AND name = 'Handler Test Agent'`, testWorkspaceID,
).Scan(&agentID); err != nil {
t.Fatalf("load seeded agent: %v", err)
}
taskID := dbfx.Task(t, agentID, testutil.Cols{
"issue_id": f.secretIssue,
"runtime_id": testRuntimeID,
"status": "completed",
"result": testutil.Raw(`'{"output":"secret result"}'::jsonb`),
})
transcript := func(userID string) int {
req := withURLParam(asUser(newRequest(http.MethodGet, "/api/tasks/"+taskID+"/messages", nil), userID), "taskId", taskID)
req = req.WithContext(middleware.SetMemberContext(req.Context(), testWorkspaceID, db.Member{}))
rec := httptest.NewRecorder()
testHandler.ListTaskMessagesByUser(rec, req)
return rec.Code
}
if got := transcript(f.outsider); got != http.StatusNotFound {
t.Errorf("outsider transcript = %d, want 404", got)
}
if got := transcript(f.insider); got != http.StatusOK {
t.Errorf("insider transcript = %d, want 200", got)
}
history := func(userID string) AgentTaskResponse {
req := withURLParam(asUser(newRequest(http.MethodGet, "/api/agents/"+agentID+"/tasks", nil), userID), "id", agentID)
var tasks []AgentTaskResponse
testutil.Call(t, testHandler.ListAgentTasks, req).Want(http.StatusOK).JSON(&tasks)
for _, task := range tasks {
if task.ID == taskID {
return task
}
}
t.Fatalf("run %s missing from %s's history", taskID, userID)
return AgentTaskResponse{}
}
hidden := history(f.outsider)
if !hidden.Restricted || hidden.IssueID != "" || hidden.Result != nil || hidden.Status != "completed" {
t.Errorf("outsider run = restricted %v issue %q result %v status %q; want a redacted completed run",
hidden.Restricted, hidden.IssueID, hidden.Result, hidden.Status)
}
visible := history(f.insider)
if visible.Restricted || visible.IssueID != f.secretIssue {
t.Errorf("insider run = restricted %v issue %q", visible.Restricted, visible.IssueID)
}
}
func TestPrivateProjectEnqueueNeedsAgentOwnerAccess(t *testing.T) {
f := newPrivateProjectFixture(t)
ctx := context.Background()
outsiderAgent := dbfx.Agent(t, f.marker+" outsider agent", testRuntimeID, testutil.Cols{"owner_id": f.outsider})
insiderAgent := dbfx.Agent(t, f.marker+" insider agent", testRuntimeID, testutil.Cols{"owner_id": f.insider})
t.Cleanup(func() {
testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, f.secretIssue)
})
issue := func(agentID string) db.Issue {
testPool.Exec(ctx, `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, f.secretIssue, agentID)
row, err := testHandler.Queries.GetIssue(ctx, parseUUID(f.secretIssue))
if err != nil {
t.Fatalf("load issue: %v", err)
}
return row
}
_, err := testHandler.TaskService.EnqueueTaskForIssueByActor(ctx, issue(outsiderAgent), parseUUID(f.insider))
if !errors.Is(err, service.ErrProjectAccessDenied) {
t.Fatalf("outsider-owned agent: err = %v, want ErrProjectAccessDenied", err)
}
_, err = testHandler.TaskService.EnqueueTaskForIssueByActor(ctx, issue(insiderAgent), parseUUID(f.insider))
if errors.Is(err, service.ErrProjectAccessDenied) {
t.Fatalf("insider-owned agent refused for project access")
}
// Assignment surfaces the same rule as an explicit 403.
rec := httptest.NewRecorder()
req := asUser(newRequest(http.MethodPut, "/api/issues/"+f.secretIssue, nil), f.insider)
ok := testHandler.requireAssigneeCanAccessProject(rec, req, parseUUID(testWorkspaceID),
pgtype.Text{String: "agent", Valid: true}, parseUUID(outsiderAgent), parseUUID(f.projectID))
if ok || rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), string(ReasonProjectAccessBlocked)) {
t.Fatalf("assignment pre-check = %v %d %s", ok, rec.Code, rec.Body.String())
}
}
func TestPrivateProjectInboxSkipsOutsiders(t *testing.T) {
f := newPrivateProjectFixture(t)
ctx := context.Background()
write := func(recipient string) error {
_, err := testHandler.Queries.CreateInboxItem(ctx, db.CreateInboxItemParams{
WorkspaceID: parseUUID(testWorkspaceID),
RecipientType: "member",
RecipientID: parseUUID(recipient),
Type: "mentioned",
Severity: "info",
IssueID: parseUUID(f.secretIssue),
Title: f.marker + " secret notification",
})
return err
}
t.Cleanup(func() {
testPool.Exec(context.Background(), `DELETE FROM inbox_item WHERE issue_id = $1`, f.secretIssue)
})
if err := write(f.outsider); !errors.Is(err, pgx.ErrNoRows) {
t.Fatalf("outsider notification: err = %v, want skipped", err)
}
if err := write(f.outsideAdmin); !errors.Is(err, pgx.ErrNoRows) {
t.Fatalf("notification to a workspace admin outside the project: err = %v, want skipped", err)
}
if err := write(f.insider); err != nil {
t.Fatalf("insider notification: %v", err)
}
if err := write(testUserID); err != nil {
t.Fatalf("owner notification: %v", err)
}
}
func removeProjectMemberAsOwner(t *testing.T, f privateProjectFixture, userID string) {
t.Helper()
req := testutil.WithURLParams(newRequest(http.MethodDelete, "/api/projects/"+f.projectID+"/members/"+userID, nil), "id", f.projectID, "userId", userID)
testutil.Call(t, testHandler.RemoveProjectMember, req).Want(http.StatusNoContent)
}
func TestPrivateProjectIssueUnreadRunReferencesAfterRevocation(t *testing.T) {
f := newPrivateProjectFixture(t)
agentID := dbfx.Agent(t, f.marker+" unread agent", testRuntimeID, testutil.Cols{"owner_id": f.insider})
secretTask := dbfx.Task(t, agentID, testutil.Cols{"issue_id": f.secretIssue, "runtime_id": testRuntimeID, "status": "completed"})
publicTask := dbfx.Task(t, agentID, testutil.Cols{"issue_id": f.publicIssue, "runtime_id": testRuntimeID, "status": "completed"})
secretResult := dbfx.Comment(t, f.secretIssue, "private run result", testutil.Cols{"source_task_id": secretTask})
publicResult := dbfx.Comment(t, f.publicIssue, "public run result", testutil.Cols{"source_task_id": publicTask})
dbfx.Cleanup(t, `DELETE FROM issue_unread WHERE user_id = $1`, f.insider)
dbfx.Exec(t, `
INSERT INTO issue_unread (workspace_id, user_id, issue_id, outcome, agent_id, task_id)
VALUES ($1, $2, $3, 'completed', $4, $5), ($1, $2, $6, 'completed', $4, $7)`,
testWorkspaceID, f.insider, f.secretIssue, agentID, secretTask, f.publicIssue, publicTask)
before := listIssueUnreadAs(t, f.insider)
if len(before) != 2 {
t.Fatalf("member should see both unread issues, got %+v", before)
}
for _, item := range before {
wantTask, wantComment := publicTask, publicResult
if item.IssueID == f.secretIssue {
wantTask, wantComment = secretTask, secretResult
} else if item.IssueID != f.publicIssue {
t.Fatalf("unexpected unread issue: %+v", item)
}
if item.TaskID == nil || *item.TaskID != wantTask || item.CommentID == nil || *item.CommentID != wantComment {
t.Fatalf("unread issue should link to task %s and comment %s, got %+v", wantTask, wantComment, item)
}
}
removeProjectMemberAsOwner(t, f, f.insider)
after := listIssueUnreadAs(t, f.insider)
if len(after) != 1 || after[0].IssueID != f.publicIssue {
t.Fatalf("revoked member should only see the public unread issue, got %+v", after)
}
if after[0].TaskID == nil || *after[0].TaskID != publicTask || after[0].CommentID == nil || *after[0].CommentID != publicResult {
t.Fatalf("public unread issue should retain its run references after revocation, got %+v", after[0])
}
}
func TestPrivateProjectArchivedInboxAndUnreadAfterRevocation(t *testing.T) {
f := newPrivateProjectFixture(t)
dbfx.Insert(t, "inbox_item", testutil.Cols{
"workspace_id": testWorkspaceID, "recipient_type": "member", "recipient_id": f.insider,
"type": "mentioned", "severity": "info", "title": f.marker + " archived secret", "issue_id": f.secretIssue,
"archived": true,
})
unreadID := dbfx.Insert(t, "inbox_item", testutil.Cols{
"workspace_id": testWorkspaceID, "recipient_type": "member", "recipient_id": f.insider,
"type": "mentioned", "severity": "info", "title": f.marker + " unread secret", "issue_id": f.secretIssue,
})
countUnread := func() int64 {
req := asUser(newRequest(http.MethodGet, "/api/inbox/unread-count", nil), f.insider)
var resp struct {
Count int64 `json:"count"`
}
testutil.Call(t, inboxWorkspaceHandler(testHandler.CountUnreadInbox), req).Want(http.StatusOK).JSON(&resp)
return resp.Count
}
if got := countUnread(); got < 1 {
t.Fatalf("member unread count before removal = %d, want the private notification counted", got)
}
before := countUnread()
removeProjectMemberAsOwner(t, f, f.insider)
for _, tc := range []struct {
name string
handler http.HandlerFunc
}{
{"archived list", testHandler.ListArchivedInbox},
{"archived page", testHandler.ListArchivedInboxPage},
{"archived facets", testHandler.GetArchivedInboxFacets},
} {
req := asUser(newRequest(http.MethodGet, "/api/inbox/archived", nil), f.insider)
body := testutil.Call(t, inboxWorkspaceHandler(tc.handler), req).Want(http.StatusOK).Text()
if strings.Contains(body, f.secretIssue) || strings.Contains(body, f.marker) {
t.Errorf("%s still returns the private notification after removal: %s", tc.name, body)
}
}
if got := countUnread(); got != before-1 {
t.Errorf("unread count after removal = %d, want %d (notification %s no longer counted)", got, before-1, unreadID)
}
}
func TestPrivateProjectLeadChangeCannotGrantAccess(t *testing.T) {
f := newPrivateProjectFixture(t)
isMember := func(userID string) bool {
var ok bool
if err := testPool.QueryRow(context.Background(),
`SELECT EXISTS(SELECT 1 FROM project_member WHERE project_id = $1 AND user_id = $2)`, f.projectID, userID,
).Scan(&ok); err != nil {
t.Fatal(err)
}
return ok
}
t.Cleanup(func() {
testPool.Exec(context.Background(), `DELETE FROM project_member WHERE project_id = $1 AND user_id = $2`, f.projectID, f.outsider)
})
setLead := func(req *http.Request) *testutil.Response {
return testutil.Call(t, testHandler.UpdateProject, withURLParam(req, "id", f.projectID))
}
body := map[string]any{"lead_type": "member", "lead_id": f.outsider}
// An agent run of a project member cannot hand the project to an outsider.
agent := dbfx.Agent(t, f.marker+" insider agent", testRuntimeID, testutil.Cols{"owner_id": f.insider})
task := dbfx.Task(t, agent, testutil.Cols{"runtime_id": testRuntimeID, "issue_id": f.secretIssue, "status": "running",
"originator_user_id": f.insider, "accountable_user_id": f.insider})
req := asUser(newRequest(http.MethodPut, "/api/projects/"+f.projectID, body), f.insider)
req.Header.Set("X-Actor-Source", "task_token")
req.Header.Set("X-Agent-ID", agent)
req.Header.Set("X-Task-ID", task)
setLead(req).Want(http.StatusForbidden)
if isMember(f.outsider) {
t.Fatal("agent lead change granted the outsider project membership")
}
var lead *string
testPool.QueryRow(context.Background(), `SELECT lead_id::text FROM project WHERE id = $1`, f.projectID).Scan(&lead)
if lead != nil {
t.Fatalf("refused update still wrote lead_id = %s", *lead)
}
// A human workspace owner may, and the new lead becomes a member.
setLead(asUser(newRequest(http.MethodPut, "/api/projects/"+f.projectID, body), testUserID)).Want(http.StatusOK)
if !isMember(f.outsider) {
t.Fatal("a member lead of a private project must be a project member")
}
}
func TestPrivateProjectLeadChangeRequiresAccessManager(t *testing.T) {
for _, change := range []string{"self", "outsider", "clear", "id_only", "type_only"} {
t.Run(change, func(t *testing.T) {
f := newPrivateProjectFixture(t)
lead := createPlainMember(t, f.marker+"[email protected]")
addProjectMemberRow(t, f.projectID, lead)
dbfx.Exec(t, `UPDATE project SET lead_type = 'member', lead_id = $1 WHERE id = $2`, lead, f.projectID)
body := map[string]any{"lead_type": "member", "lead_id": f.insider, "title": "must not change"}
switch change {
case "outsider":
body["lead_id"] = f.outsider
case "clear":
body["lead_type"], body["lead_id"] = nil, nil
case "id_only":
delete(body, "lead_type")
case "type_only":
body["lead_type"] = nil
delete(body, "lead_id")
}
req := withURLParam(asUser(newRequest(http.MethodPut, "/api/projects/"+f.projectID, body), f.insider), "id", f.projectID)
testutil.Call(t, testHandler.UpdateProject, req).Want(http.StatusForbidden)
var title, storedLead string
if err := testPool.QueryRow(context.Background(), `SELECT title, lead_id::text FROM project WHERE id = $1`, f.projectID).Scan(&title, &storedLead); err != nil {
t.Fatal(err)
}
if storedLead != lead || title == "must not change" {
t.Fatal("refused lead change still changed the project")
}
})
}
}
// On a workspace-visible project the lead stays an ordinary field: any member
// (or agent) may set it, as before private projects. Leading one therefore
// grants nothing; in particular it does not let a member make it private.
func TestWorkspaceProjectLeadStaysOpenButGrantsNoAccess(t *testing.T) {
f := newPrivateProjectFixture(t)
dbfx.Exec(t, `UPDATE project SET visibility = 'workspace' WHERE id = $1`, f.projectID)
update := func(body map[string]any) *testutil.Response {
req := withURLParam(asUser(newRequest(http.MethodPut, "/api/projects/"+f.projectID, body), f.outsider), "id", f.projectID)
return testutil.Call(t, testHandler.UpdateProject, req)
}
update(map[string]any{"lead_type": "member", "lead_id": f.outsider}).Want(http.StatusOK)
update(map[string]any{"visibility": "private"}).Want(http.StatusForbidden)
addReq := withURLParam(asUser(newRequest(http.MethodPost, "/api/projects/"+f.projectID+"/members", map[string]any{"user_ids": []string{f.outsider}}), f.outsider), "id", f.projectID)
testutil.Call(t, testHandler.AddProjectMembers, addReq).Want(http.StatusForbidden)
var visibility string
if err := testPool.QueryRow(context.Background(), `SELECT visibility FROM project WHERE id = $1`, f.projectID).Scan(&visibility); err != nil {
t.Fatal(err)
}
if visibility != projectaccess.VisibilityWorkspace {
t.Fatalf("visibility = %q after a self-appointed lead tried to make it private", visibility)
}
}
// The owner and the admin here are project members; the role alone would not
// let them reach the project.
func TestPrivateProjectAccessManagersCanAddAndTransferLead(t *testing.T) {
for _, actor := range []string{"owner", "admin", "lead"} {
t.Run(actor, func(t *testing.T) {
f := newPrivateProjectFixture(t)
dbfx.Exec(t, `UPDATE project SET lead_type = 'member', lead_id = $1 WHERE id = $2`, f.insider, f.projectID)
userID := testUserID
if actor == "lead" {
userID = f.insider
} else if actor == "admin" {
userID = createWorkspaceAdmin(t, f.marker+"[email protected]")
addProjectMemberRow(t, f.projectID, userID)
}
added := createPlainMember(t, f.marker+"[email protected]")
req := withURLParam(asUser(newRequest(http.MethodPost, "/api/projects/"+f.projectID+"/members", map[string]any{"user_ids": []string{added}}), userID), "id", f.projectID)
testutil.Call(t, testHandler.AddProjectMembers, req).Want(http.StatusOK)
req = withURLParam(asUser(newRequest(http.MethodPut, "/api/projects/"+f.projectID, map[string]any{"lead_type": "member", "lead_id": f.outsider}), userID), "id", f.projectID)
testutil.Call(t, testHandler.UpdateProject, req).Want(http.StatusOK)
var newLeadIsMember, oldLeadIsMember bool
if err := testPool.QueryRow(context.Background(), `SELECT
EXISTS(SELECT 1 FROM project_member WHERE project_id = $1 AND user_id = $2),
EXISTS(SELECT 1 FROM project_member WHERE project_id = $1 AND user_id = $3)`, f.projectID, f.outsider, f.insider).Scan(&newLeadIsMember, &oldLeadIsMember); err != nil {
t.Fatal(err)
}
if !newLeadIsMember || !oldLeadIsMember {
t.Fatal("lead transfer must add the new lead and retain the old lead's membership")
}
})
}
}
func TestPrivateProjectCurrentLeadCannotBeRemoved(t *testing.T) {
f := newPrivateProjectFixture(t)
dbfx.Exec(t, `UPDATE project SET lead_type = 'member', lead_id = $1 WHERE id = $2`, f.insider, f.projectID)
for _, actor := range []string{testUserID, f.insider} {
req := testutil.WithURLParams(asUser(newRequest(http.MethodDelete, "/api/projects/"+f.projectID+"/members/"+f.insider, nil), actor), "id", f.projectID, "userId", f.insider)
testutil.Call(t, testHandler.RemoveProjectMember, req).Want(http.StatusConflict)
}
var exists bool
if err := testPool.QueryRow(context.Background(), `SELECT EXISTS(SELECT 1 FROM project_member WHERE project_id = $1 AND user_id = $2)`, f.projectID, f.insider).Scan(&exists); err != nil {
t.Fatal(err)
}
if !exists {
t.Fatal("current lead lost project membership")
}
}
func TestPrivateProjectRevocationDeletesProjectFromSearchIndex(t *testing.T) {
f := newPrivateProjectFixture(t)
cursor := searchIndexManifest(t, testWorkspaceID).Cursor
removeProjectMemberAsOwner(t, f, f.insider)
req := asUser(searchIndexRequest(http.MethodPost, "/api/search-index/changes", testWorkspaceID, map[string]any{"cursor": cursor, "limit": 1000}), f.insider)
var changes SearchIndexChangesResponse
testutil.Call(t, testHandler.ListSearchIndexChanges, req).Want(http.StatusOK).JSON(&changes)
for _, id := range changes.Deleted.Projects {
if id == f.projectID {
return
}
}
t.Errorf("revoked project missing from search deletions; projects=%v issues=%v comments=%v",
changes.Deleted.Projects, changes.Deleted.Issues, changes.Deleted.Comments)
}
func TestPrivateProjectQuickCreateNeedsAgentOwnerAccess(t *testing.T) {
f := newPrivateProjectFixture(t)
runtime := dbfx.Runtime(t, f.marker+" runtime", testutil.Cols{"owner_id": f.outsider, "metadata": testutil.Raw(`'{"cli_version":"99.0.0"}'::jsonb`)})
agent := dbfx.Agent(t, f.marker+" outsider agent", runtime, testutil.Cols{"owner_id": f.outsider, "permission_mode": "public_to", "visibility": "workspace"})
dbfx.Insert(t, "agent_invocation_target", testutil.Cols{"agent_id": agent, "target_type": "workspace", "target_id": testWorkspaceID})
t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE agent_id = $1`, agent) })
for _, body := range []map[string]any{
{"prompt": "Create a task in this project", "agent_id": agent, "project_id": f.projectID},
{"prompt": "Create a sub-issue", "agent_id": agent, "parent_issue_id": f.secretIssue},
} {
rec := httptest.NewRecorder()
testHandler.QuickCreateIssue(rec, newRequest(http.MethodPost, "/api/issues/quick-create", body))
if rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), string(ReasonProjectAccessBlocked)) {
t.Errorf("quick-create %v = %d %s, want 403 %s", body, rec.Code, rec.Body.String(), ReasonProjectAccessBlocked)
}
}
var queued int
testPool.QueryRow(context.Background(), `SELECT count(*) FROM agent_task_queue WHERE agent_id = $1`, agent).Scan(&queued)
if queued != 0 {
t.Fatalf("refused quick-create queued %d task(s)", queued)
}
}
func TestPrivateProjectCommentSubIssuePreviewHidden(t *testing.T) {
f := newPrivateProjectFixture(t)
preview := func(userID string) *testutil.Response {
req := withURLParam(asUser(newRequest(http.MethodGet, "/api/comments/"+f.secretComment+"/sub-issue/preview", nil), userID), "commentId", f.secretComment)
return testutil.Call(t, testHandler.PreviewCommentSubIssue, req)
}
if body := preview(f.outsider).Text(); strings.Contains(body, f.marker) {
t.Fatalf("outsider preview leaks the private thread: %s", body)
}
preview(f.insider).Want(http.StatusOK)
}
// The workspace-wide wakeup lists (the Wakeups page, the board's paused cue
// and the per-issue summaries) are not read through an issue, so each one has
// to leave out rules on issues in a project the caller cannot see.
func TestPrivateProjectWakeupListsSkipOutsiders(t *testing.T) {
f := newPrivateProjectFixture(t)
agent := dbfx.Agent(t, f.marker+" wake target", testRuntimeID)
dbfx.Cleanup(t, "DELETE FROM activity_log WHERE issue_id=$1", f.secretIssue)
dbfx.Cleanup(t, "DELETE FROM issue_wakeup WHERE issue_id=$1", f.secretIssue)
dbfx.Cleanup(t, "DELETE FROM issue_wakeup_receipt WHERE wakeup_id IN (SELECT id FROM issue_wakeup WHERE issue_id=$1)", f.secretIssue)
svc := service.IssueWakeupService{Tasks: testHandler.TaskService}
create := func() string {
t.Helper()
w, err := svc.Create(context.Background(), parseUUID(f.secretIssue), parseUUID(testUserID), pgtype.UUID{}, service.WakeupInput{
AgentID: agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created"}, Instruction: "check",
})
if err != nil {
t.Fatal(err)
}
return uuidToString(w.ID)
}
create()
paused := create()
dbfx.Exec(t, "UPDATE issue_wakeup SET enabled=false,paused_reason='rate',disabled_at=now() WHERE id=$1", paused)
// An open sub-issue makes the secret issue's child-done system rule listable.
dbfx.Issue(t, f.marker+" secret child", testutil.Cols{"project_id": f.projectID, "parent_issue_id": f.secretIssue})
if w := putChildDoneRule(t, f.secretIssue, map[string]any{"instruction": "Advance."}); w.Code != http.StatusOK {
t.Fatalf("create system rule: %d %s", w.Code, w.Body.String())
}
onSecretIssue := func(userID string, list http.HandlerFunc, path string) int {
t.Helper()
var rows []struct {
IssueID string `json:"issue_id"`
}
testutil.Call(t, list, asUser(newRequest(http.MethodGet, path, nil), userID)).Want(http.StatusOK).JSON(&rows)
n := 0
for _, row := range rows {
if row.IssueID == f.secretIssue {
n++
}
}
return n
}
for _, tc := range []struct {
name string
userID string
visible bool
}{
{"project member", f.insider, true},
{"workspace owner in the member list", testUserID, true},
{"workspace member outside the project", f.outsider, false},
{"workspace admin outside the project", f.outsideAdmin, false},
} {
// The marker is in the secret issue's title and nowhere else, so the
// search narrows the page and its total to this fixture's rules.
var page struct {
Items []struct {
IssueID string `json:"issue_id"`
} `json:"items"`
Total int `json:"total"`
}
req := asUser(newRequest(http.MethodGet, "/api/issue-wakeups?scope=all&limit=100&search="+f.marker, nil), tc.userID)
testutil.Call(t, testHandler.ListWorkspaceWakeups, req).Want(http.StatusOK).JSON(&page)
want := 0
if tc.visible {
want = 3 // the active rule, the paused rule and the system rule
}
if len(page.Items) != want || page.Total != want {
t.Errorf("%s: wakeup list has %d rules (total %d) on the secret issue, want %d", tc.name, len(page.Items), page.Total, want)
}
if got := onSecretIssue(tc.userID, testHandler.ListWorkspaceWakeupSummaries, "/api/issue-wakeup-summaries") > 0; got != tc.visible {
t.Errorf("%s: wakeup summaries include the secret issue = %v, want %v", tc.name, got, tc.visible)
}
if got := onSecretIssue(tc.userID, testHandler.ListPausedWakeups, "/api/issue-wakeup-paused") > 0; got != tc.visible {
t.Errorf("%s: paused wakeups include the secret issue = %v, want %v", tc.name, got, tc.visible)
}
}
}
// A run on a private project's issue is listed as restricted to members
// outside the project, id included. Stopping it by that id must need the same
// access as reading it.
func TestPrivateProjectRunCancelNeedsVisibility(t *testing.T) {
f := newPrivateProjectFixture(t)
var agentID string
if err := testPool.QueryRow(context.Background(),
`SELECT id FROM agent WHERE workspace_id = $1 AND name = 'Handler Test Agent'`, testWorkspaceID,
).Scan(&agentID); err != nil {
t.Fatalf("load seeded agent: %v", err)
}
queuedRun := func() string {
return dbfx.Task(t, agentID, testutil.Cols{"issue_id": f.secretIssue, "runtime_id": testRuntimeID})
}
taskID := queuedRun()
rec := httptest.NewRecorder()
testHandler.CancelTaskByUser(rec, cancelTaskByUserRequest(t, f.outsider, taskID))
if rec.Code != http.StatusNotFound {
t.Errorf("outsider cancel = %d, want 404", rec.Code)
}
if strings.Contains(rec.Body.String(), f.secretIssue) {
t.Errorf("outsider cancel response names the private issue: %s", rec.Body.String())
}
if got := taskStatus(t, taskID); got != "queued" {
t.Errorf("run after outsider cancel = %q, want queued", got)
}
rec = httptest.NewRecorder()
testHandler.CancelTaskByUser(rec, cancelTaskByUserRequest(t, f.outsideAdmin, taskID))
if rec.Code != http.StatusNotFound || taskStatus(t, taskID) != "queued" {
t.Errorf("workspace admin outside the project: cancel = %d, run = %q; want 404 and queued", rec.Code, taskStatus(t, taskID))
}
for i, tc := range []struct {
name string
userID string
}{
{"project member", f.insider},
{"workspace owner in the member list", testUserID},
} {
// An issue holds one pending run per agent, so the first case stops
// the run the outsider could not.
if i > 0 {
taskID = queuedRun()
}
rec := httptest.NewRecorder()
testHandler.CancelTaskByUser(rec, cancelTaskByUserRequest(t, tc.userID, taskID))
if rec.Code != http.StatusOK {
t.Errorf("%s: cancel = %d, want 200: %s", tc.name, rec.Code, rec.Body.String())
}
if got := taskStatus(t, taskID); got != "cancelled" {
t.Errorf("%s: run after cancel = %q, want cancelled", tc.name, got)
}
}
}
// Sub-issue progress is read for every parent in one call, not through an
// issue, so its counts have to leave out sub-issues in a project the caller
// cannot see.
func TestPrivateProjectChildProgressSkipsHiddenSubIssues(t *testing.T) {
f := newPrivateProjectFixture(t)
dbfx.Issue(t, f.marker+" public child", testutil.Cols{"parent_issue_id": f.publicIssue})
dbfx.Issue(t, f.marker+" secret child", testutil.Cols{"project_id": f.projectID, "parent_issue_id": f.publicIssue, "status": "done"})
secretOnlyParent := dbfx.Issue(t, f.marker+" parent of one secret child")
dbfx.Issue(t, f.marker+" lone secret child", testutil.Cols{"project_id": f.projectID, "parent_issue_id": secretOnlyParent})
type counts struct{ Total, Done int64 }
progress := func(userID string) map[string]counts {
t.Helper()
var body struct {
Progress []struct {
ParentIssueID string `json:"parent_issue_id"`
Total int64 `json:"total"`
Done int64 `json:"done"`
} `json:"progress"`
}
req := asUser(newRequest(http.MethodGet, "/api/issues/child-progress", nil), userID)
testutil.Call(t, testHandler.ChildIssueProgress, req).Want(http.StatusOK).JSON(&body)
out := map[string]counts{}
for _, p := range body.Progress {
out[p.ParentIssueID] = counts{p.Total, p.Done}
}
return out
}
for _, tc := range []struct {
name string
userID string
mixed counts
secretOnly counts
}{
{"project member", f.insider, counts{2, 1}, counts{1, 0}},
{"workspace owner in the member list", testUserID, counts{2, 1}, counts{1, 0}},
{"workspace member outside the project", f.outsider, counts{1, 0}, counts{}},
{"workspace admin outside the project", f.outsideAdmin, counts{1, 0}, counts{}},
} {
got := progress(tc.userID)
if got[f.publicIssue] != tc.mixed {
t.Errorf("%s: parent with a public and a secret sub-issue = %+v, want %+v", tc.name, got[f.publicIssue], tc.mixed)
}
if got[secretOnlyParent] != tc.secretOnly {
t.Errorf("%s: parent with only a secret sub-issue = %+v, want %+v", tc.name, got[secretOnlyParent], tc.secretOnly)
}
}
}
// A public parent can hold sub-issues from a private project. Its child-done
// system rule counts and names only the sub-issues the viewer can see.
func TestPrivateProjectSystemWakeupSkipsHiddenChildren(t *testing.T) {
f := newPrivateProjectFixture(t)
dbfx.Exec(t, "UPDATE issue SET parent_issue_id=$1 WHERE id=$2", f.publicIssue, f.secretIssue)
publicChild := dbfx.Issue(t, f.marker+" public child", testutil.Cols{"parent_issue_id": f.publicIssue})
var secretNumber int
dbfx.QueryRow(t, "SELECT number FROM issue WHERE id=$1", f.secretIssue).Scan(&secretNumber)
secretSuffix := fmt.Sprintf("-%d", secretNumber)
childDone := func(userID string) []systemWakeupResponse {
t.Helper()
var rules []systemWakeupResponse
req := withURLParam(asUser(newRequest(http.MethodGet, "/api/issues/"+f.publicIssue+"/system-wakeups", nil), userID), "id", f.publicIssue)
testutil.Call(t, testHandler.ListIssueSystemWakeups, req).Want(http.StatusOK).JSON(&rules)
return rules
}
namesSecretChild := func(rule systemWakeupResponse) bool {
for _, identifier := range rule.Waiting {
if strings.HasSuffix(identifier, secretSuffix) {
return true
}
}
return false
}
viewers := []struct {
name string
userID string
visible bool
}{
{"project member", f.insider, true},
{"workspace owner in the member list", testUserID, true},
{"workspace member outside the project", f.outsider, false},
{"workspace admin outside the project", f.outsideAdmin, false},
}
for _, tc := range viewers {
rules := childDone(tc.userID)
if len(rules) != 1 {
t.Fatalf("%s: got %d system rules, want the child-done rule", tc.name, len(rules))
}
want := 1
if tc.visible {
want = 2
}
if rule := rules[0]; rule.Total != want || rule.Remaining != want || len(rule.Waiting) != want || namesSecretChild(rule) != tc.visible {
t.Errorf("%s: child-done rule waits for %d of %d (%v), want %d sub-issues and the private one named = %v", tc.name, rule.Remaining, rule.Total, rule.Waiting, want, tc.visible)
}
}
// Only the private sub-issue is still open.
dbfx.Exec(t, "UPDATE issue SET status='done' WHERE id=$1", publicChild)
for _, tc := range viewers {
rules := childDone(tc.userID)
if !tc.visible {
if len(rules) != 0 {
t.Errorf("%s: child-done rule still reported for a private sub-issue: %+v", tc.name, rules)
}
continue
}
if len(rules) != 1 || rules[0].Total != 2 || rules[0].Remaining != 1 || !namesSecretChild(rules[0]) {
t.Errorf("%s: child-done rule = %+v, want 1 of 2 left and the private one named", tc.name, rules)
}
}
}
func TestPrivateProjectPullRequestSummariesSkipHiddenIssues(t *testing.T) {
f := newPrivateProjectFixture(t)
now := time.Now()
linkGitHub := func(issueID string, number int) string {
prID := dbfx.Insert(t, "github_pull_request", testutil.Cols{
"workspace_id": testWorkspaceID, "installation_id": 0,
"repo_owner": "acme", "repo_name": f.marker, "pr_number": number,
"title": "pr", "state": "open", "html_url": "https://github.test/pr",
"pr_created_at": now, "pr_updated_at": now,
})
dbfx.InsertNoID(t, "issue_pull_request", testutil.Cols{"issue_id": issueID, "pull_request_id": prID},
"pull_request_id = $1", prID)
return prID
}
publicPR := linkGitHub(f.publicIssue, 1)
secretGitHubPR := linkGitHub(f.secretIssue, 2)
secretGitLabPR := dbfx.Insert(t, "vcs_pull_request", testutil.Cols{
"workspace_id": testWorkspaceID, "connection_id": testWorkspaceID, "provider": "gitlab",
"repo_owner": "acme", "repo_name": f.marker, "pr_number": 3,
"title": "mr", "state": "open", "html_url": "https://gitlab.test/mr",
"pr_created_at": now, "pr_updated_at": now,
})
dbfx.InsertNoID(t, "issue_vcs_pull_request", testutil.Cols{"issue_id": f.secretIssue, "pull_request_id": secretGitLabPR},
"pull_request_id = $1", secretGitLabPR)
visible := func(userID string) map[string]bool {
t.Helper()
var body struct {
PullRequests []IssuePullRequestSummaryResponse `json:"pull_requests"`
}
req := asUser(newRequest(http.MethodGet, "/api/issues/pull-requests", nil), userID)
testutil.Call(t, testHandler.ListIssuePullRequestSummaries, req).Want(http.StatusOK).JSON(&body)
out := map[string]bool{}
for _, pr := range body.PullRequests {
out[pr.ID] = true
}
return out
}
for _, tc := range []struct {
name string
userID string
seesSecret bool
}{
{"project member", f.insider, true},
{"workspace owner in the member list", testUserID, true},
{"workspace member outside the project", f.outsider, false},
{"workspace admin outside the project", f.outsideAdmin, false},
} {
got := visible(tc.userID)
if !got[publicPR] {
t.Errorf("%s: missing the PR linked to a public issue", tc.name)
}
for _, prID := range []string{secretGitHubPR, secretGitLabPR} {
if got[prID] != tc.seesSecret {
t.Errorf("%s: sees PR %s on a private-project issue = %v, want %v", tc.name, prID, got[prID], tc.seesSecret)
}
}
}
}
func TestPrivateProjectWorkingAgentsHiddenFromOutsiders(t *testing.T) {
f := newPrivateProjectFixture(t)
agentID := createHandlerTestAgent(t, f.marker+" working agent", []byte(`{}`))
dbfx.Task(t, agentID, testutil.Cols{"issue_id": f.secretIssue, "runtime_id": testRuntimeID, "status": "running", "started_at": time.Now()})
for _, userID := range []string{f.outsider, f.outsideAdmin, f.insider} {
req := asUser(newRequest(http.MethodGet, "/api/working-agents?type=issue&project="+f.projectID, nil), userID)
var agents []WorkspaceWorkingAgent
testutil.Call(t, testHandler.ListWorkspaceWorkingAgents, req).Want(http.StatusOK).JSON(&agents)
found := false
for _, a := range agents {
if a.ID == agentID {
found = a.RunningTaskCount == 1
}
}
if userID == f.insider && !found {
t.Fatalf("project member lost the agent working in the project: %+v", agents)
}
if userID != f.insider && len(agents) != 0 {
t.Fatalf("private project's working agents exposed to %s: %+v", userID, agents)
}
}
}
func TestPrivateProjectWorkingAgentsUnderHiddenParent(t *testing.T) {
f := newPrivateProjectFixture(t)
agentID := createHandlerTestAgent(t, f.marker+" sub-issue agent", []byte(`{}`))
child := dbfx.Issue(t, f.marker+" secret sub-issue", testutil.Cols{"project_id": f.projectID, "parent_issue_id": f.secretIssue})
dbfx.Task(t, agentID, testutil.Cols{"issue_id": child, "runtime_id": testRuntimeID, "status": "running", "started_at": time.Now()})
for _, userID := range []string{f.outsider, f.outsideAdmin, f.insider} {
req := asUser(newRequest(http.MethodGet, "/api/working-agents?type=issue&parent="+f.secretIssue, nil), userID)
var agents []WorkspaceWorkingAgent
testutil.Call(t, testHandler.ListWorkspaceWorkingAgents, req).Want(http.StatusOK).JSON(&agents)
found := false
for _, a := range agents {
if a.ID == agentID {
found = a.RunningTaskCount == 1
}
}
if userID == f.insider && !found {
t.Fatalf("project member lost the agent working under the issue: %+v", agents)
}
if userID != f.insider && len(agents) != 0 {
t.Fatalf("working agents under a private issue exposed to %s: %+v", userID, agents)
}
}
}