Skip to content

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

Go

MUL-9955 fix(activity): redact duplicate references per realtime reader and for deleted originals (#11287)

Multica Evef537414ab797
diff --git a/server/cmd/server/activity_listeners.go b/server/cmd/server/activity_listeners.go
index cfe7887af8..b970d0da6e 100644
--- a/server/cmd/server/activity_listeners.go
+++ b/server/cmd/server/activity_listeners.go
@@ -388,10 +388,7 @@ func publishActivityEvent(bus *events.Bus, original events.Event, activity db.Ac
"actor_type": actorType,
"actor_id": util.UUIDToString(activity.ActorID),
"action": action,
- // Realtime fans out by this issue's audience, which need not
- // see an issue the details name; clients refetch the timeline,
- // where the reference is redacted per reader.
- "details": json.RawMessage(handler.StripActivityIssueRef(action, activity.Details)),
+ "details": json.RawMessage(activity.Details),
"created_at": util.TimestampToString(activity.CreatedAt),
},
},
diff --git a/server/cmd/server/issue_ref_realtime.go b/server/cmd/server/issue_ref_realtime.go
new file mode 100644
index 0000000000..53c63c0df4
--- /dev/null
+++ b/server/cmd/server/issue_ref_realtime.go
@@ -0,0 +1,223 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "log/slog"
+ "sort"
+ "strings"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/handler"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
+ "github.com/multica-ai/multica/server/internal/realtime"
+ "github.com/multica-ai/multica/server/internal/util"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// An event reaches the audience of the issue it is about, but a duplicate mark
+// (MUL-7349) also names a second issue, which can sit in a private project
+// part of that audience may not read (MUL-9932). An event that moves the mark
+// reaches each recipient with only the references it may read. Any other
+// event names the original only because the issue still points at it, which
+// every client already has from its own reads, so one frame with those
+// references stripped serves everyone.
+
+// issueRefEvents may name issues other than the one they are about.
+var issueRefEvents = map[string]bool{
+ protocol.EventIssueCreated: true,
+ protocol.EventIssueUpdated: true,
+ protocol.EventActivityCreated: true,
+}
+
+// duplicateMarkKeys are an issue event's top-level ids of both ends of a
+// duplicate mark change.
+var duplicateMarkKeys = []string{"duplicate_of_issue_id", "prev_duplicate_of_issue_id"}
+
+// visitIssueRefs calls strip with each reference top, an event payload, makes
+// to an issue other than its own: a duplicate mark's ends and resolved
+// original on an issue event, a duplicate activity's other issue. "" stands
+// for an activity reference whose issue cannot be told from its details. A
+// reference strip returns true for is removed from top: an issue event's id
+// becomes null, its original null (or, with omitOriginal, absent, which
+// clients merging the issue into their cache read as unchanged), and an
+// activity's details lose the id and identifier.
+func visitIssueRefs(eventType string, top map[string]json.RawMessage, omitOriginal bool, strip func(id string) bool) {
+ if eventType == protocol.EventActivityCreated {
+ entry := jsonObject(top["entry"])
+ action := jsonString(entry["action"])
+ if id, named := handler.ActivityIssueRef(action, entry["details"]); named && strip(util.UUIDToString(id)) {
+ entry["details"] = handler.StripActivityIssueRef(action, entry["details"])
+ top["entry"], _ = json.Marshal(entry)
+ }
+ return
+ }
+ null := json.RawMessage("null")
+ for _, key := range duplicateMarkKeys {
+ if id := jsonString(top[key]); id != "" && strip(id) {
+ top[key] = null
+ }
+ }
+ issue := jsonObject(top["issue"])
+ if id := jsonString(jsonObject(issue["duplicate_of"])["id"]); id != "" && strip(id) {
+ if omitOriginal {
+ delete(issue, "duplicate_of")
+ } else {
+ issue["duplicate_of"] = null
+ }
+ top["issue"], _ = json.Marshal(issue)
+ }
+}
+
+// duplicateMarkMoved reports whether e changes what an issue is a duplicate
+// of: a duplicate activity, or an issue event whose two ends differ.
+func duplicateMarkMoved(e events.Event) bool {
+ if e.Type == protocol.EventActivityCreated {
+ return true
+ }
+ top := jsonObject(e.Payload)
+ return jsonString(top[duplicateMarkKeys[0]]) != jsonString(top[duplicateMarkKeys[1]])
+}
+
+// strippedFrame marshals e for the wire with the references strip selects
+// removed (see visitIssueRefs).
+func strippedFrame(e events.Event, omitOriginal bool, strip func(id string) bool) ([]byte, error) {
+ payload := jsonObject(projectOutbound(e.Type, e.Payload))
+ visitIssueRefs(e.Type, payload, omitOriginal, strip)
+ return json.Marshal(map[string]any{"type": e.Type, "payload": payload, "actor_id": e.ActorID, "actor_type": e.ActorType})
+}
+
+// jsonObject reads v, a payload value or its raw JSON, as a JSON object; nil
+// when it is not one.
+func jsonObject(v any) map[string]json.RawMessage {
+ raw, ok := v.(json.RawMessage)
+ if !ok {
+ var err error
+ if raw, err = json.Marshal(v); err != nil {
+ return nil
+ }
+ }
+ var m map[string]json.RawMessage
+ if json.Unmarshal(raw, &m) != nil {
+ return nil
+ }
+ return m
+}
+
+func jsonString(raw json.RawMessage) string {
+ var s string
+ _ = json.Unmarshal(raw, &s)
+ return s
+}
+
+// IssueRefReaders maps each issue e names besides its own (visitIssueRefs)
+// that not every member may read to the user ids who may: the members of its
+// private project. A reference whose issue is gone, or cannot be told, maps to
+// nobody, as in the HTTP reads. nil means every recipient may read every
+// reference.
+func (a *dbPrivateProjectAudience) IssueRefReaders(ctx context.Context, e events.Event) (map[string]map[string]bool, error) {
+ if !issueRefEvents[e.Type] || e.WorkspaceID == "" {
+ return nil, nil
+ }
+ ws, err := a.workspace(ctx, e.WorkspaceID)
+ if err != nil || len(ws.projects) == 0 {
+ return nil, err
+ }
+ var refs []string
+ visitIssueRefs(e.Type, jsonObject(e.Payload), false, func(id string) bool {
+ refs = append(refs, id)
+ return false
+ })
+ if len(refs) == 0 {
+ return nil, nil
+ }
+ var ids []pgtype.UUID
+ for _, ref := range refs {
+ if id, err := util.ParseUUID(ref); err == nil {
+ ids = append(ids, id)
+ }
+ }
+ projects := map[string]string{}
+ if len(ids) > 0 {
+ rows, err := a.q.ListIssueProjectIDs(ctx, ids)
+ if err != nil {
+ return nil, err
+ }
+ for _, row := range rows {
+ projects[util.UUIDToString(row.ID)] = util.UUIDToString(row.ProjectID)
+ }
+ }
+ var out map[string]map[string]bool
+ for _, ref := range refs {
+ projectID, found := projects[ref]
+ members, private := ws.projects[projectID]
+ if found && !private {
+ continue
+ }
+ set := make(map[string]bool, len(members))
+ for _, userID := range members {
+ set[userID] = true
+ }
+ if out == nil {
+ out = map[string]map[string]bool{}
+ }
+ out[ref] = set
+ }
+ return out, nil
+}
+
+// Members lists the members of a workspace who receive realtime events: all
+// but guests (MUL-9420).
+func (a *dbPrivateProjectAudience) Members(ctx context.Context, workspaceID string) ([]string, error) {
+ wsUUID, err := util.ParseUUID(workspaceID)
+ if err != nil {
+ return nil, nil
+ }
+ rows, err := a.q.ListMembers(ctx, wsUUID)
+ if err != nil {
+ return nil, err
+ }
+ out := make([]string, 0, len(rows))
+ for _, m := range rows {
+ if !projectaccess.IsGuestRole(m.Role) {
+ out = append(out, util.UUIDToString(m.UserID))
+ }
+ }
+ return out, nil
+}
+
+// sendPerReader delivers e to each recipient, stripped of the references
+// refReaders says it may not read. full is the frame for a reader of all of
+// them.
+func sendPerReader(b realtime.Broadcaster, e events.Event, full []byte, recipients []string, refReaders map[string]map[string]bool) {
+ frames := map[string][]byte{}
+ for _, userID := range recipients {
+ var hide []string
+ for ref, readers := range refReaders {
+ if !readers[userID] {
+ hide = append(hide, ref)
+ }
+ }
+ frame := full
+ if len(hide) > 0 {
+ sort.Strings(hide)
+ key := strings.Join(hide, ",")
+ var ok bool
+ if frame, ok = frames[key]; !ok {
+ hidden := make(map[string]bool, len(hide))
+ for _, ref := range hide {
+ hidden[ref] = true
+ }
+ var err error
+ if frame, err = strippedFrame(e, false, func(id string) bool { return hidden[id] }); err != nil {
+ slog.Error("failed to marshal event", "event_type", e.Type, "error", err)
+ return
+ }
+ frames[key] = frame
+ }
+ }
+ b.BroadcastToScope(realtime.ScopeWorkspaceMember, realtime.WorkspaceMemberScopeID(e.WorkspaceID, userID), frame)
+ }
+}
diff --git a/server/cmd/server/issue_ref_realtime_test.go b/server/cmd/server/issue_ref_realtime_test.go
new file mode 100644
index 0000000000..9d2761b36b
--- /dev/null
+++ b/server/cmd/server/issue_ref_realtime_test.go
@@ -0,0 +1,191 @@
+package main
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/realtime"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+const ppDeletedIssue = "00000000-0000-0000-0000-00000000dead"
+
+// framesByMember returns each member's frame payload, failing on a workspace
+// broadcast or a member reached twice.
+func framesByMember(t *testing.T, fb *fakeBroadcaster) map[string]map[string]json.RawMessage {
+ t.Helper()
+ fb.mu.Lock()
+ defer fb.mu.Unlock()
+ if len(fb.workspaceCalls) != 0 {
+ t.Fatalf("broadcast to the whole workspace: %s", fb.workspaceCalls[0].msg)
+ }
+ out := map[string]map[string]json.RawMessage{}
+ for _, c := range fb.scopeCalls {
+ if c.scopeType != realtime.ScopeWorkspaceMember {
+ continue
+ }
+ userID := strings.TrimPrefix(c.scopeID, ppWorkspace+":")
+ if _, dup := out[userID]; dup {
+ t.Fatalf("%s reached twice", userID)
+ }
+ var frame struct {
+ Payload map[string]json.RawMessage `json:"payload"`
+ }
+ if err := json.Unmarshal(c.msg, &frame); err != nil {
+ t.Fatalf("decode frame: %v", err)
+ }
+ out[userID] = frame.Payload
+ }
+ return out
+}
+
+func TestRegisterListeners_DuplicateMarkReachesEachMemberAsTheyMayReadIt(t *testing.T) {
+ // A public issue moves its duplicate mark from an issue in the second
+ // private project to one in the first.
+ fb := publishPrivateAudience(events.Event{Type: protocol.EventIssueUpdated, Payload: map[string]any{
+ "issue": map[string]any{"id": ppPublicIssue, "project_id": ppPublic, "title": "public",
+ "duplicate_of": map[string]any{"id": ppSecretIssue, "identifier": "SECRET-1", "title": "secret title"}},
+ "duplicate_of_issue_id": ppSecretIssue,
+ "prev_duplicate_of_issue_id": ppSecretIssue2,
+ "prev_duplicate_of_identifier": "SECRET2-1",
+ }})
+ frames := framesByMember(t, fb)
+ if len(frames) != 4 {
+ t.Fatalf("delivered to %d members, want the 4 non-guest members", len(frames))
+ }
+ for userID, want := range map[string]struct{ next, prev bool }{
+ ppMember: {next: true},
+ ppOther: {prev: true},
+ ppShared: {next: true, prev: true},
+ ppPlain: {},
+ } {
+ p := frames[userID]
+ if _, leaked := p["prev_duplicate_of_identifier"]; leaked {
+ t.Errorf("%s: prev_duplicate_of_identifier reached the wire", userID)
+ }
+ if got := jsonString(p["duplicate_of_issue_id"]) == ppSecretIssue; got != want.next {
+ t.Errorf("%s: duplicate_of_issue_id = %s, want visible=%v", userID, p["duplicate_of_issue_id"], want.next)
+ }
+ if got := jsonString(p["prev_duplicate_of_issue_id"]) == ppSecretIssue2; got != want.prev {
+ t.Errorf("%s: prev_duplicate_of_issue_id = %s, want visible=%v", userID, p["prev_duplicate_of_issue_id"], want.prev)
+ }
+ issue := jsonObject(p["issue"])
+ if got := jsonString(jsonObject(issue["duplicate_of"])["identifier"]) == "SECRET-1"; got != want.next {
+ t.Errorf("%s: issue.duplicate_of = %s, want visible=%v", userID, issue["duplicate_of"], want.next)
+ }
+ if jsonString(issue["title"]) != "public" {
+ t.Errorf("%s: issue = %s, want the rest kept", userID, p["issue"])
+ }
+ }
+}
+
+func TestRegisterListeners_DuplicateActivityReachesEachMemberAsTheyMayReadIt(t *testing.T) {
+ // Through the producer the activity log uses, which leaves the details
+ // whole for the fanout to project.
+ activity := func(issueID, action string, details map[string]string) *fakeBroadcaster {
+ body, _ := json.Marshal(details)
+ bus := events.New()
+ fb := &fakeBroadcaster{}
+ registerListeners(bus, fb, newPrivateProjectAudience(fakeAudienceQuerier{}))
+ publishActivityEvent(bus, events.Event{WorkspaceID: ppWorkspace}, db.ActivityLog{IssueID: ppUUID(issueID), Action: action, Details: body})
+ return fb
+ }
+ details := func(p map[string]json.RawMessage) map[string]string {
+ var d map[string]string
+ _ = json.Unmarshal(jsonObject(p["entry"])["details"], &d)
+ return d
+ }
+
+ t.Run("original in a private project", func(t *testing.T) {
+ frames := framesByMember(t, activity(ppPublicIssue, "duplicate_marked",
+ map[string]string{"original_id": ppSecretIssue, "original_identifier": "SECRET-1", "to": "cancelled"}))
+ for userID, visible := range map[string]bool{ppMember: true, ppShared: true, ppOther: false, ppPlain: false} {
+ d := details(frames[userID])
+ if (d["original_identifier"] == "SECRET-1" && d["original_id"] == ppSecretIssue) != visible {
+ t.Errorf("%s: details = %v, want visible=%v", userID, d, visible)
+ }
+ if d["to"] != "cancelled" {
+ t.Errorf("%s: details = %v, want the rest kept", userID, d)
+ }
+ }
+ })
+
+ // Both issues in one private project: its whole audience keeps the
+ // reference, so a client appending the entry shows it.
+ t.Run("same private project", func(t *testing.T) {
+ frames := framesByMember(t, activity(ppSecretIssue, "duplicate_added",
+ map[string]string{"duplicate_id": ppSecretSibling, "duplicate_identifier": "SECRET-2"}))
+ if len(frames) != 2 {
+ t.Fatalf("delivered to %v, want the project's two members", frames)
+ }
+ for userID, p := range frames {
+ if d := details(p); d["duplicate_identifier"] != "SECRET-2" {
+ t.Errorf("%s: details = %v, want the reference kept", userID, d)
+ }
+ }
+ })
+
+ // Who could see a deleted original went with its project: nobody keeps
+ // it, not even a member of every private project there is now.
+ t.Run("deleted original", func(t *testing.T) {
+ frames := framesByMember(t, activity(ppPublicIssue, "duplicate_unmarked",
+ map[string]string{"original_id": ppDeletedIssue, "original_identifier": "GONE-1", "reason": "original_deleted"}))
+ if len(frames) != 4 {
+ t.Fatalf("delivered to %d members, want the 4 non-guest members", len(frames))
+ }
+ for userID, p := range frames {
+ if d := details(p); d["original_id"] != "" || d["original_identifier"] != "" || d["reason"] != "original_deleted" {
+ t.Errorf("%s: details = %v, want the reference stripped and the reason kept", userID, d)
+ }
+ }
+ })
+}
+
+// An edit that leaves the mark alone still names the original. Every client
+// already has it, or not, from its own reads, so one frame without it goes to
+// the whole workspace: the original is left out of the issue, which clients
+// merge as unchanged, and the unchanged ends are nulled.
+func TestRegisterListeners_UnmovedDuplicateMarkKeepsOneFrame(t *testing.T) {
+ fb := publishPrivateAudience(events.Event{Type: protocol.EventIssueUpdated, Payload: map[string]any{
+ "issue": map[string]any{"id": ppPublicIssue, "project_id": ppPublic, "title": "renamed",
+ "duplicate_of": map[string]any{"id": ppSecretIssue, "identifier": "SECRET-1", "title": "secret title"}},
+ "title_changed": true,
+ "duplicate_of_issue_id": ppSecretIssue,
+ "prev_duplicate_of_issue_id": ppSecretIssue,
+ }})
+ if len(fb.workspaceCalls) != 1 || len(privateAudienceScopes(fb)) != 0 {
+ t.Fatalf("workspace=%d scoped=%v, want one workspace broadcast", len(fb.workspaceCalls), privateAudienceScopes(fb))
+ }
+ msg := fb.workspaceCalls[0].msg
+ if strings.Contains(string(msg), ppSecretIssue) || strings.Contains(string(msg), "SECRET-1") {
+ t.Fatalf("frame names the private original: %s", msg)
+ }
+ var frame struct {
+ Payload map[string]json.RawMessage `json:"payload"`
+ }
+ if err := json.Unmarshal(msg, &frame); err != nil {
+ t.Fatal(err)
+ }
+ issue := jsonObject(frame.Payload["issue"])
+ if _, present := issue["duplicate_of"]; present || jsonString(issue["title"]) != "renamed" {
+ t.Errorf("issue = %s, want duplicate_of left out and the rest kept", frame.Payload["issue"])
+ }
+ for _, key := range duplicateMarkKeys {
+ if string(frame.Payload[key]) != "null" {
+ t.Errorf("%s = %s, want null", key, frame.Payload[key])
+ }
+ }
+}
+
+func TestRegisterListeners_ReadableDuplicateMarkKeepsWorkspaceFanout(t *testing.T) {
+ fb := publishPrivateAudience(events.Event{Type: protocol.EventIssueUpdated, Payload: map[string]any{
+ "issue": map[string]any{"id": ppPublicIssue, "project_id": nil, "duplicate_of": map[string]any{"id": ppPublicIssue}},
+ "duplicate_of_issue_id": ppPublicIssue,
+ }})
+ if len(fb.workspaceCalls) != 1 || len(privateAudienceScopes(fb)) != 0 {
+ t.Fatalf("workspace=%d scoped=%v, want one workspace broadcast", len(fb.workspaceCalls), privateAudienceScopes(fb))
+ }
+}
diff --git a/server/cmd/server/listeners.go b/server/cmd/server/listeners.go
index d2eaab66d0..076ca997c3 100644
--- a/server/cmd/server/listeners.go
+++ b/server/cmd/server/listeners.go
@@ -37,7 +37,9 @@ import (
// internal/external payload boundary in one reviewable place.
var internalOnlyPayloadKeys = map[string][]string{
// The live-session keys feed activity folding and mention dedup.
- protocol.EventIssueUpdated: {"prev_description", "prev_title", "description_live_editors", "description_seen_mentions"},
+ // prev_duplicate_of_identifier names a deleted original for the activity
+ // log, which can no longer look it up or tell who could see it.
+ protocol.EventIssueUpdated: {"prev_description", "prev_title", "description_live_editors", "description_seen_mentions", "prev_duplicate_of_identifier"},
// task:failed error text is consumed synchronously by channel outbounds.
// It may contain provider/runtime detail that belongs in the originating
// chat transcript, not in the workspace-wide realtime fanout.
@@ -340,11 +342,30 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster, audience ...priv
if projectAudience != nil && e.WorkspaceID != "" {
ctx, cancel := context.WithTimeout(context.Background(), audienceResolveTimeout)
recipients, private, err := projectAudience.Audience(ctx, e)
+ var refReaders map[string]map[string]bool
+ if err == nil {
+ refReaders, err = projectAudience.IssueRefReaders(ctx, e)
+ }
+ perReader := len(refReaders) > 0 && duplicateMarkMoved(e)
+ if err == nil && perReader && !private {
+ recipients, err = projectAudience.Members(ctx, e.WorkspaceID)
+ }
cancel()
if err != nil {
logAudienceFailure(e, err)
return
}
+ if perReader {
+ realtime.M.RecordEvent(e.Type)
+ sendPerReader(b, e, data, recipients, refReaders)
+ return
+ }
+ if len(refReaders) > 0 {
+ if data, err = strippedFrame(e, true, func(id string) bool { return refReaders[id] != nil }); err != nil {
+ slog.Error("failed to marshal event", "event_type", e.Type, "error", err)
+ return
+ }
+ }
if private {
realtime.M.RecordEvent(e.Type)
for _, userID := range recipients {
diff --git a/server/cmd/server/private_project_realtime.go b/server/cmd/server/private_project_realtime.go
index ab5d73ce4f..ea0ec2f94a 100644
--- a/server/cmd/server/private_project_realtime.go
+++ b/server/cmd/server/private_project_realtime.go
@@ -32,6 +32,10 @@ type privateProjectAudience interface {
// user ids that may receive it. err means the decision could not be made;
// the caller drops the event rather than widen it.
Audience(ctx context.Context, e events.Event) (userIDs []string, private bool, err error)
+ // IssueRefReaders and Members narrow what an event says about issues other
+ // than its own; see issue_ref_realtime.go.
+ IssueRefReaders(ctx context.Context, e events.Event) (map[string]map[string]bool, error)
+ Members(ctx context.Context, workspaceID string) ([]string, error)
}
type audienceQuerier interface {
@@ -40,6 +44,7 @@ type audienceQuerier interface {
GetCommentIssueProjectID(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error)
GetAgentTask(ctx context.Context, id pgtype.UUID) (db.AgentTaskQueue, error)
GetAutopilot(ctx context.Context, id pgtype.UUID) (db.Autopilot, error)
+ ListMembers(ctx context.Context, workspaceID pgtype.UUID) ([]db.Member, error)
projectaccess.TaskQuerier
}
diff --git a/server/cmd/server/private_project_realtime_test.go b/server/cmd/server/private_project_realtime_test.go
index b1ba823949..6d54fc80d6 100644
--- a/server/cmd/server/private_project_realtime_test.go
+++ b/server/cmd/server/private_project_realtime_test.go
@@ -38,6 +38,12 @@ const (
ppAutopilotTask = "00000000-0000-0000-0000-0000000000e2"
ppQuickCreateTask = "00000000-0000-0000-0000-0000000000e3"
ppCrossProjectTask = "00000000-0000-0000-0000-0000000000e4"
+
+ // Workspace members in no private project, and another issue in the
+ // first private project.
+ ppPlain = "00000000-0000-0000-0000-0000000000c4"
+ ppGuest = "00000000-0000-0000-0000-0000000000c5"
+ ppSecretSibling = "00000000-0000-0000-0000-0000000000d4"
)
type fakeAudienceQuerier struct {
@@ -68,7 +74,7 @@ func (f fakeAudienceQuerier) ListPrivateProjectAudience(context.Context, pgtype.
func (fakeAudienceQuerier) GetIssueProjectID(_ context.Context, id pgtype.UUID) (pgtype.UUID, error) {
switch util.UUIDToString(id) {
- case ppSecretIssue:
+ case ppSecretIssue, ppSecretSibling:
return ppUUID(ppPrivate), nil
case ppPublicIssue:
return ppUUID(ppPublic), nil
@@ -78,6 +84,14 @@ func (fakeAudienceQuerier) GetIssueProjectID(_ context.Context, id pgtype.UUID)
return pgtype.UUID{}, pgx.ErrNoRows
}
+func (fakeAudienceQuerier) ListMembers(_ context.Context, ws pgtype.UUID) ([]db.Member, error) {
+ var out []db.Member
+ for _, id := range []string{ppMember, ppShared, ppOther, ppPlain} {
+ out = append(out, db.Member{WorkspaceID: ws, UserID: ppUUID(id), Role: "member"})
+ }
+ return append(out, db.Member{WorkspaceID: ws, UserID: ppUUID(ppGuest), Role: "guest"}), nil
+}
+
func (fakeAudienceQuerier) GetCommentIssueProjectID(_ context.Context, id pgtype.UUID) (pgtype.UUID, error) {
if util.UUIDToString(id) == ppSecretComment {
return ppUUID(ppPrivate), nil
diff --git a/server/internal/handler/activity_refs.go b/server/internal/handler/activity_refs.go
index dfdd1c3e04..92c7eef87c 100644
--- a/server/internal/handler/activity_refs.go
+++ b/server/internal/handler/activity_refs.go
@@ -27,23 +27,30 @@ var activityIssueRefs = map[string]activityIssueRef{
"duplicate_removed": {id: "duplicate_id", identifier: "duplicate_identifier"},
}
-// referencedIssueID returns the other issue an activity names, if any.
-func referencedIssueID(action string, details []byte) (pgtype.UUID, bool) {
+// ActivityIssueRef returns the other issue an activity names. named reports
+// whether the details carry a reference at all; id is invalid when they do
+// but its issue cannot be told from them, which leaves its visibility
+// unknown.
+func ActivityIssueRef(action string, details []byte) (id pgtype.UUID, named bool) {
ref, ok := activityIssueRefs[action]
if !ok || len(details) == 0 {
return pgtype.UUID{}, false
}
var fields map[string]json.RawMessage
if err := json.Unmarshal(details, &fields); err != nil {
- return pgtype.UUID{}, false
+ return pgtype.UUID{}, true
}
- var id string
- if err := json.Unmarshal(fields[ref.id], &id); err != nil || id == "" {
+ rawID, hasID := fields[ref.id]
+ if _, hasIdentifier := fields[ref.identifier]; !hasID && !hasIdentifier {
return pgtype.UUID{}, false
}
- parsed, err := util.ParseUUID(id)
+ var s string
+ if err := json.Unmarshal(rawID, &s); err != nil {
+ return pgtype.UUID{}, true
+ }
+ parsed, err := util.ParseUUID(s)
if err != nil {
- return pgtype.UUID{}, false
+ return pgtype.UUID{}, true
}
return parsed, true
}
@@ -77,34 +84,33 @@ func StripActivityIssueRef(action string, details []byte) []byte {
}
// redactHiddenActivityRefs strips, in place, the reference to another issue
-// from every activity whose referenced issue sits in a project hidden from
-// the reader. actions[i] and details[i] describe the same activity. A
-// referenced issue that no longer exists keeps its reference: activities
-// carry a deleted issue's identifier on purpose so the row still reads.
+// from every activity unless the reader can be shown to see that issue. A
+// referenced issue that no longer exists is stripped for every reader: who
+// could see it went with its project, and seeing every project today says
+// nothing about a project deleted since. actions[i] and details[i] describe
+// the same activity.
func (h *Handler) redactHiddenActivityRefs(r *http.Request, hidden projectaccess.Hidden, actions []string, details [][]byte) error {
- if hidden.Empty() {
- return nil
- }
refs := make([]pgtype.UUID, len(actions))
+ named := make([]bool, len(actions))
var ids []pgtype.UUID
for i, action := range actions {
- if id, ok := referencedIssueID(action, details[i]); ok {
- refs[i] = id
- ids = append(ids, id)
+ refs[i], named[i] = ActivityIssueRef(action, details[i])
+ if refs[i].Valid {
+ ids = append(ids, refs[i])
}
}
- if len(ids) == 0 {
- return nil
- }
- hiddenIssues, err := h.hiddenIssueIDs(r, hidden, ids)
- if err != nil {
- return err
- }
- for i, id := range refs {
- if !id.Valid {
- continue
+ visible := map[pgtype.UUID]bool{}
+ if len(ids) > 0 {
+ rows, err := h.Queries.ListIssueProjectIDs(r.Context(), ids)
+ if err != nil {
+ return err
}
- if _, isHidden := hiddenIssues[id]; isHidden {
+ for _, row := range rows {
+ visible[row.ID] = hidden.CanSeeProject(row.ProjectID)
+ }
+ }
+ for i := range actions {
+ if named[i] && !visible[refs[i]] {
details[i] = StripActivityIssueRef(actions[i], details[i])
}
}
diff --git a/server/internal/handler/activity_refs_test.go b/server/internal/handler/activity_refs_test.go
index df63189757..2112b1e01a 100644
--- a/server/internal/handler/activity_refs_test.go
+++ b/server/internal/handler/activity_refs_test.go
@@ -2,10 +2,13 @@ package handler
import (
"encoding/json"
+ "fmt"
"net/http"
"net/http/httptest"
"testing"
+ "time"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
"github.com/multica-ai/multica/server/internal/testutil"
)
@@ -28,6 +31,29 @@ func TestStripActivityIssueRef(t *testing.T) {
}
}
+func TestActivityIssueRef(t *testing.T) {
+ const id = "00000000-0000-0000-0000-000000000001"
+ cases := []struct {
+ name, action, details string
+ named, valid bool
+ }{
+ {"id and identifier", "duplicate_marked", `{"original_id":"` + id + `","original_identifier":"MUL-1"}`, true, true},
+ {"identifier without id", "duplicate_added", `{"duplicate_identifier":"MUL-1"}`, true, false},
+ {"unreadable id", "duplicate_unmarked", `{"original_id":"x","original_identifier":"MUL-1"}`, true, false},
+ {"unreadable details", "duplicate_marked", `not json`, true, false},
+ {"no reference left", "duplicate_removed", `{"reason":"x"}`, false, false},
+ {"unrelated action", "status_changed", `{"original_id":"` + id + `"}`, false, false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got, named := ActivityIssueRef(tc.action, []byte(tc.details))
+ if named != tc.named || got.Valid != tc.valid {
+ t.Errorf("ActivityIssueRef(%s, %s) = valid %v, named %v; want valid %v, named %v", tc.action, tc.details, got.Valid, named, tc.valid, tc.named)
+ }
+ })
+ }
+}
+
// A duplicate mark names an issue in another project. Readers who can see the
// project feed or the issue's timeline but not that other project must not
// learn the other issue's id or identifier; readers who can see both still do.
@@ -124,3 +150,86 @@ func TestActivityRefsToHiddenIssuesAreRedacted(t *testing.T) {
}
})
}
+
+// Once the private original is deleted, the reference names an issue whose
+// project is gone with it, and its delete adds a row that names it again.
+// Neither may come back for a reader who could not see it before.
+func TestActivityRefsToDeletedIssuesAreRedacted(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ f := newPrivateProjectFixture(t)
+ openIssue := dbfx.Issue(t, f.marker+" open issue")
+ original := dbfx.Issue(t, f.marker+" doomed original", testutil.Cols{"project_id": f.projectID})
+ insertActivity := func(action string, details map[string]string) {
+ t.Helper()
+ body, _ := json.Marshal(details)
+ dbfx.Exec(t, `
+ INSERT INTO activity_log (workspace_id, issue_id, actor_type, actor_id, action, details)
+ VALUES ($1, $2, 'member', $3, $4, $5::jsonb)
+ `, testWorkspaceID, openIssue, testUserID, action, string(body))
+ }
+ timeline := func(userID string) map[string]map[string]string {
+ t.Helper()
+ var entries []TimelineEntry
+ req := withURLParam(asUser(newRequest(http.MethodGet, "/api/issues/"+openIssue+"/timeline", nil), userID), "id", openIssue)
+ rec := httptest.NewRecorder()
+ testHandler.ListTimeline(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("timeline as %s: %d %s", userID, rec.Code, rec.Body.String())
+ }
+ if err := json.NewDecoder(rec.Body).Decode(&entries); err != nil {
+ t.Fatalf("decode timeline: %v", err)
+ }
+ out := map[string]map[string]string{}
+ for _, e := range entries {
+ if e.Action != nil {
+ var d map[string]string
+ _ = json.Unmarshal(e.Details, &d)
+ out[*e.Action] = d
+ }
+ }
+ return out
+ }
+
+ insertActivity("duplicate_marked", map[string]string{"original_id": original, "original_identifier": "SECRET-9", "to": "cancelled"})
+ dbfx.Exec(t, `DELETE FROM issue WHERE id = $1`, original)
+ insertActivity("duplicate_unmarked", map[string]string{"original_id": original, "original_identifier": "SECRET-9", "reason": "original_deleted"})
+
+ for _, reader := range []struct{ name, id string }{{"outsider", f.outsider}, {"outside admin", f.outsideAdmin}} {
+ t.Run(reader.name, func(t *testing.T) {
+ got := timeline(reader.id)
+ if d := got["duplicate_marked"]; d == nil || d["original_id"] != "" || d["original_identifier"] != "" || d["to"] != "cancelled" {
+ t.Errorf("duplicate_marked = %v, want the deleted original redacted and the rest kept", d)
+ }
+ if d := got["duplicate_unmarked"]; d == nil || d["original_id"] != "" || d["original_identifier"] != "" || d["reason"] != "original_deleted" {
+ t.Errorf("duplicate_unmarked = %v, want the deleted original redacted and the reason kept", d)
+ }
+ })
+ }
+}
+
+// A reader who sees every private project today learns nothing about one
+// deleted since, so a reference to an issue that is gone is stripped even
+// when nothing is hidden from them.
+func TestActivityRefsToDeletedIssuesAreRedactedWhenNothingIsHidden(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ visible := dbfx.Issue(t, fmt.Sprintf("visible original %d", time.Now().UnixNano()))
+ actions := []string{"duplicate_marked", "duplicate_unmarked"}
+ details := [][]byte{
+ []byte(`{"original_id":"` + visible + `","original_identifier":"OPEN-1"}`),
+ []byte(`{"original_id":"00000000-0000-0000-0000-00000000dead","original_identifier":"GONE-1","reason":"original_deleted"}`),
+ }
+ req := newRequest(http.MethodGet, "/api/issues/x/timeline", nil)
+ if err := testHandler.redactHiddenActivityRefs(req, projectaccess.Hidden{}, actions, details); err != nil {
+ t.Fatal(err)
+ }
+ if got := string(details[0]); got != `{"original_id":"`+visible+`","original_identifier":"OPEN-1"}` {
+ t.Errorf("existing issue = %s, want it kept", got)
+ }
+ if got := string(details[1]); got != `{"reason":"original_deleted"}` {
+ t.Errorf("deleted issue = %s, want only the reason kept", got)
+ }
+}