Skip to content

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

Go

fix(guests): close guest access gaps and make 0.12 a safe rollback point (MUL-9714) (#11055)

Multica Eve5face7d30b70
diff --git a/SELF_HOSTING.md b/SELF_HOSTING.md
index 72027ba595..785f341a1e 100644
--- a/SELF_HOSTING.md
+++ b/SELF_HOSTING.md
@@ -372,6 +372,8 @@ To roll back if an upgrade goes sideways:
helm -n multica rollback multica
```
+> **Rolling back after guests exist.** Releases before guests treat a guest as a full member, so once a workspace has a guest or a pending guest invitation, roll back only to a release that includes guest-safe rollback (MUL-9714, the first release containing [#11055](https://github.com/multica-ai/multica/pull/11055)) or later. That release also refuses any member role it does not know, so you can roll back to it from later releases that add roles. Roll back the application only: keep the database schema, and do not run down migrations. The down migration for guests (`699`) deletes the projects recorded on pending guest invitations.
+
> **Upgrading from `v0.3.4` to `v0.3.5+` fails with `refusing to drop legacy daily rollups: ...`?** As of MUL-2957 the `migrate up` command runs an idempotent monthly-slice backfill automatically before applying migration `103`, so a clean upgrade is a single `helm upgrade` + backend rollout. If you are still on a pre-MUL-2957 binary or the auto-hook fails, run the standalone backfill against the same database the chart is using (`kubectl -n multica exec deploy/multica-backend -- ./backfill_task_usage_hourly --sleep-between-slices=2s`), then restart the backend deployment to re-apply migrations. See [Advanced Configuration → Usage Dashboard Rollup](SELF_HOSTING_ADVANCED.md#usage-dashboard-rollup) for the full recovery flow.
### Tearing down
diff --git a/apps/docs/content/docs/members-roles.mdx b/apps/docs/content/docs/members-roles.mdx
index bd8b3a272b..36043d3375 100644
--- a/apps/docs/content/docs/members-roles.mdx
+++ b/apps/docs/content/docs/members-roles.mdx
@@ -51,7 +51,7 @@ On Multica Cloud, a workspace on the Free plan can have up to 5 members. Members
A guest sees only the projects shared with it. In those projects it can read issues, comment, react, and follow them; it cannot create or edit issues, run or mention agents, or open workspace settings, and it sees no other projects, agents, autopilots, or runtimes. Guests are free: they take no paid seat and no member slot.
-`owner` and `admin` invite a guest by choosing **Guest** in the invite dialog and picking the projects it can see. From a member's actions menu they can make a member a guest, which frees its seat and takes back its agents, autopilots, and runtime access; make a guest a member, which takes a seat; or change a guest's projects with **Manage accessible projects**.
+`owner` and `admin` invite a guest by choosing **Guest** in the invite dialog and picking the projects it can see. From a member's actions menu they can make a member a guest, which frees its seat and takes back its agents, autopilots, and runtime access; make a guest a member, which takes a seat; or change a guest's projects with **Manage accessible projects**. Like everything else about a private project, a guest's access to one is shown and changed only by people on that project's member list; changing a guest's projects leaves its access to private projects you are not on as it is.
On Multica Cloud, guests are included in Pro and Business. When a trial ends or a workspace moves to Free, existing guests keep their access and can still be removed, narrowed, or made members, but no new guests can be added. Self-hosted workspaces have guests.
diff --git a/apps/docs/content/docs/members-roles.zh.mdx b/apps/docs/content/docs/members-roles.zh.mdx
index 57ae2289d6..eef6754dc7 100644
--- a/apps/docs/content/docs/members-roles.zh.mdx
+++ b/apps/docs/content/docs/members-roles.zh.mdx
@@ -51,7 +51,7 @@ import { RolesDemo } from "@/components/demos/roles-demo";
访客只能看到分享给自己的项目。在这些项目里,访客可以查看任务、评论、添加表情回应和关注任务;不能创建或修改任务,不能运行或 @ agent,也不能打开工作区设置,看不到其他项目、agent、autopilot 和 runtime。访客免费,不占付费席位,也不占成员名额。
-`owner` 和 `admin` 在邀请弹窗里选择**访客**并勾选可访问的项目,即可邀请访客。在成员的操作菜单里,可以把成员设为访客(释放其席位,并收回其 agent、autopilot 和 runtime 权限),把访客设为成员(占用一个席位),或通过**管理可访问的项目**调整访客能看到的项目。
+`owner` 和 `admin` 在邀请弹窗里选择**访客**并勾选可访问的项目,即可邀请访客。在成员的操作菜单里,可以把成员设为访客(释放其席位,并收回其 agent、autopilot 和 runtime 权限),把访客设为成员(占用一个席位),或通过**管理可访问的项目**调整访客能看到的项目。和私有项目的其他信息一样,访客在某个私有项目上的权限,只有该项目成员列表里的人能看到和修改;调整访客的项目时,你不在其中的私有项目上的权限保持不变。
在 Multica Cloud 上,Pro 和 Business 包含访客。试用结束或工作区降到 Free 后,已有访客保留访问权限,仍然可以移除、缩小范围或设为成员,但不能再添加新访客。自部署的工作区可以使用访客。
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 507f8ed3ce..58464e4e8e 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -89,9 +89,9 @@ func (h *Handler) requireDaemonWorkspaceAccess(w http.ResponseWriter, r *http.Re
}
}
- _, ok := h.requireWorkspaceMember(w, r, workspaceID, "not found")
+ member, ok := h.requireWorkspaceMember(w, r, workspaceID, "not found")
if ok && userID != "" {
- h.MembershipCache.Set(r.Context(), userID, workspaceID)
+ h.cacheMembership(r.Context(), member)
}
return ok
}
@@ -317,11 +317,13 @@ func (h *Handler) verifyDaemonWorkspaceAccess(r *http.Request, workspaceID strin
if h.MembershipCache.Get(r.Context(), userID, workspaceID) {
return true
}
- _, err := h.getWorkspaceMember(r.Context(), userID, workspaceID)
- if err != nil {
+ // The same rule as requireWorkspaceMember: a guest reaches only the
+ // routes on its allowlist, which no daemon route is.
+ member, err := h.getWorkspaceMember(r.Context(), userID, workspaceID)
+ if err != nil || (projectaccess.IsGuestRole(member.Role) && !middleware.GuestMayRequest(r)) {
return false
}
- h.MembershipCache.Set(r.Context(), userID, workspaceID)
+ h.cacheMembership(r.Context(), member)
return true
}
@@ -1121,6 +1123,9 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
})
repoResp := workspaceReposResponse(req.WorkspaceID, ws.Repos, ws.Settings, h.cfg.GitExtraCACerts)
+ if !h.daemonCredentialSeesWorkspaceConfig(r, req.WorkspaceID) {
+ repoResp = workspaceReposResponse(req.WorkspaceID, nil, nil, h.cfg.GitExtraCACerts)
+ }
body := map[string]any{
"runtimes": resp,
@@ -1332,6 +1337,10 @@ func (h *Handler) GetDaemonWorkspaceRepos(w http.ResponseWriter, r *http.Request
if !h.requireDaemonWorkspaceAccess(w, r, workspaceID) {
return
}
+ if !h.daemonCredentialSeesWorkspaceConfig(r, workspaceID) {
+ writeError(w, http.StatusNotFound, "not found")
+ return
+ }
ws, err := h.Queries.GetWorkspace(r.Context(), parseUUID(workspaceID))
if err != nil {
@@ -1342,6 +1351,25 @@ func (h *Handler) GetDaemonWorkspaceRepos(w http.ResponseWriter, r *http.Request
writeJSON(w, http.StatusOK, workspaceReposResponse(workspaceID, ws.Repos, ws.Settings, h.cfg.GitExtraCACerts))
}
+// daemonCredentialSeesWorkspaceConfig reports whether a daemon request may
+// read the workspace's repositories and settings. They configure the
+// workspace, which a guest is not shown (MUL-9420), so the person the
+// credential acts for (a PAT or JWT user, or the owner a daemon token is bound
+// to) must hold a non-guest role now. The membership cache cannot answer this:
+// it holds no role. Qoder-managed and pre-owner daemon tokens act for no
+// person and keep their access.
+func (h *Handler) daemonCredentialSeesWorkspaceConfig(r *http.Request, workspaceID string) bool {
+ userID := requestUserID(r)
+ if middleware.DaemonWorkspaceIDFromContext(r.Context()) != "" {
+ userID = middleware.DaemonTokenOwnerIDFromContext(r.Context())
+ if userID == "" {
+ return true
+ }
+ }
+ member, err := h.getWorkspaceMember(r.Context(), userID, workspaceID)
+ return err == nil && !projectaccess.IsGuestRole(member.Role)
+}
+
// setRuntimeOffline flips a runtime offline, recording the daemon's reason when
// it sent one. An absent or unusable reason falls back to the plain offline
// write: a malformed payload must never cost the caller the state change it
diff --git a/server/internal/handler/file.go b/server/internal/handler/file.go
index cfc168f44d..5a2e9c44df 100644
--- a/server/internal/handler/file.go
+++ b/server/internal/handler/file.go
@@ -953,11 +953,12 @@ func (h *Handler) loadAttachmentForDownload(w http.ResponseWriter, r *http.Reque
}
return att, true
}
- if _, err := h.getWorkspaceMember(r.Context(), userID, workspaceID); err != nil {
+ member, err := h.getWorkspaceMember(r.Context(), userID, workspaceID)
+ if err != nil {
writeError(w, http.StatusNotFound, "attachment not found")
return db.Attachment{}, false
}
- h.MembershipCache.Set(r.Context(), userID, workspaceID)
+ h.cacheMembership(r.Context(), member)
if !h.requireAttachmentVisible(w, r, workspaceID, att) {
return db.Attachment{}, false
}
diff --git a/server/internal/handler/guest.go b/server/internal/handler/guest.go
index bb97f52511..5158f2cf91 100644
--- a/server/internal/handler/guest.go
+++ b/server/internal/handler/guest.go
@@ -6,6 +6,7 @@ import (
"errors"
"log/slog"
"net/http"
+ "slices"
"strings"
"time"
@@ -195,6 +196,8 @@ func writeMemberUpdateError(w http.ResponseWriter, err error) {
writeMemberRoleChanged(w)
case errors.Is(err, pgx.ErrNoRows):
writeError(w, http.StatusNotFound, "member not found")
+ case errors.Is(err, errGuestProjectNotVisible):
+ writeError(w, http.StatusBadRequest, "project not found")
default:
writeError(w, http.StatusInternalServerError, "failed to update member")
}
@@ -268,13 +271,33 @@ func (h *Handler) parseGuestProjectIDs(w http.ResponseWriter, r *http.Request, w
return ids, true
}
-// setGuestProjects makes ids exactly the projects userID is a member of. When
-// that adds or takes away a project, the guest's local search copy is made to
-// rebuild: nothing in those projects changed, so sync alone would neither
-// drop what it lost nor deliver what it gained.
+// visibleProjectIDs is the part of a guest's projects a viewer with hidden
+// may be shown.
+func visibleProjectIDs(hidden projectaccess.Hidden, ids []string) []string {
+ if hidden.Empty() {
+ return ids
+ }
+ visible := make([]string, 0, len(ids))
+ for _, id := range ids {
+ if parsed, err := util.ParseUUID(id); err == nil && hidden.CanSeeProject(parsed) {
+ visible = append(visible, id)
+ }
+ }
+ return visible
+}
+
+// setGuestProjects makes ids the projects userID is a member of among those
+// addedBy can see (guestProjectsToKeep). When that adds or takes away a
+// project, the guest's local search copy is made to rebuild: nothing in those
+// projects changed, so sync alone would neither drop what it lost nor deliver
+// what it gained.
func setGuestProjects(r *http.Request, q *db.Queries, workspaceID, userID, addedBy pgtype.UUID, ids []pgtype.UUID) error {
+ keep, err := guestProjectsToKeep(r.Context(), q, workspaceID, addedBy, ids)
+ if err != nil {
+ return err
+ }
removed, err := q.RemoveUserFromProjectsExcept(r.Context(), db.RemoveUserFromProjectsExceptParams{
- WorkspaceID: workspaceID, UserID: userID, KeepProjectIds: ids,
+ WorkspaceID: workspaceID, UserID: userID, KeepProjectIds: keep,
})
if err != nil {
return err
@@ -291,6 +314,28 @@ func setGuestProjects(r *http.Request, q *db.Queries, workspaceID, userID, added
return markSearchAccessChanged(r.Context(), q, workspaceID, userID)
}
+// errGuestProjectNotVisible reports a guest project the operator cannot see.
+var errGuestProjectNotVisible = errors.New("guest project not visible to the operator")
+
+// guestProjectsToKeep is what an operator setting a guest's projects to ids
+// leaves the guest a member of. An operator manages a guest's grants only on
+// the projects it can see itself, owners and admins included (MUL-9284): a
+// project in ids it cannot see is refused, and the guest keeps its grants on
+// every private project hidden from the operator. Run it in the transaction
+// that writes the grants, so both read the same project memberships.
+func guestProjectsToKeep(ctx context.Context, q *db.Queries, workspaceID, operator pgtype.UUID, ids []pgtype.UUID) ([]pgtype.UUID, error) {
+ hidden, err := projectaccess.ForPrincipals(ctx, q, workspaceID, operator)
+ if err != nil {
+ return nil, err
+ }
+ for _, id := range ids {
+ if !hidden.CanSeeProject(id) {
+ return nil, errGuestProjectNotVisible
+ }
+ }
+ return append(slices.Clone(ids), hidden.IDs()...), nil
+}
+
// markSearchAccessChanged records, in the caller's transaction, that what
// userID can see changed without the content changing (MUL-9420). Local
// search copies built before the transaction then rebuild under the new
@@ -494,7 +539,10 @@ func (h *Handler) SetMemberProjects(w http.ResponseWriter, r *http.Request) {
writeMemberUpdateError(w, err)
return
}
- if err := setGuestProjects(r, qtx, target.WorkspaceID, target.UserID, requester.UserID, ids); err != nil {
+ if err := setGuestProjects(r, qtx, target.WorkspaceID, target.UserID, requester.UserID, ids); errors.Is(err, errGuestProjectNotVisible) {
+ writeError(w, http.StatusBadRequest, "project not found")
+ return
+ } else if err != nil {
slog.Warn("set guest projects failed", append(logger.RequestAttrs(r), "error", err, "member_id", uuidToString(target.ID))...)
writeError(w, http.StatusInternalServerError, "failed to update projects")
return
@@ -511,9 +559,10 @@ func (h *Handler) SetMemberProjects(w http.ResponseWriter, r *http.Request) {
return
}
resp := h.memberWithUserResponse(target, user)
- resp.ProjectIDs = uuidsToStrings(ids)
+ // The event reaches every member, so it carries no projects; see UpdateMember.
h.publish(protocol.EventMemberUpdated, uuidToString(target.WorkspaceID), "member", requestUserID(r), map[string]any{
"member": resp,
})
+ resp.ProjectIDs = uuidsToStrings(ids)
writeJSON(w, http.StatusOK, resp)
}
diff --git a/server/internal/handler/guest_access_test.go b/server/internal/handler/guest_access_test.go
new file mode 100644
index 0000000000..b1fd0c4fd3
--- /dev/null
+++ b/server/internal/handler/guest_access_test.go
@@ -0,0 +1,432 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/entitlement"
+ "github.com/multica-ai/multica/server/internal/middleware"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// A guest reads the workspace it is in through GET /api/workspaces/{id} and
+// GET /api/workspaces. Both show it the workspace's name and look, and none of
+// the agent instructions, repositories or settings that configure it.
+func TestGuestWorkspaceResponseOmitsConfiguration(t *testing.T) {
+ suffix := uuid.NewString()[:8]
+ workspaceID := dbfx.Workspace(t, "Guest shell "+suffix, "guest-shell-"+suffix, testutil.Cols{
+ "context": "internal agent instructions",
+ "settings": `{"github_enabled": true, "github_pr_sidebar_enabled": false, "internal_flag": "x"}`,
+ "repos": `[{"url": "https://github.com/acme/private"}]`,
+ })
+ dbfx.Cleanup(t, `DELETE FROM member WHERE workspace_id = $1`, workspaceID)
+ dbfx.Member(t, workspaceID, testUserID, "owner")
+ guest := dbfx.User(t, "Shell guest", "shell-guest-"+suffix+"@multica.test")
+ dbfx.Member(t, workspaceID, guest, "guest")
+ member := dbfx.User(t, "Shell member", "shell-member-"+suffix+"@multica.test")
+ dbfx.Member(t, workspaceID, member, "member")
+
+ get := func(userID string) WorkspaceResponse {
+ t.Helper()
+ var ws WorkspaceResponse
+ req := withURLParam(asUser(newRequest(http.MethodGet, "/api/workspaces/"+workspaceID, nil), userID), "id", workspaceID)
+ handler := middleware.RequireWorkspaceMemberFromURL(testHandler.Queries, "id")(http.HandlerFunc(testHandler.GetWorkspace))
+ testutil.Call(t, handler.ServeHTTP, req).Want(http.StatusOK).JSON(&ws)
+ return ws
+ }
+ list := func(userID string) WorkspaceResponse {
+ t.Helper()
+ var all []WorkspaceResponse
+ testutil.Call(t, testHandler.ListWorkspaces, asUser(newRequest(http.MethodGet, "/api/workspaces", nil), userID)).
+ Want(http.StatusOK).JSON(&all)
+ for _, ws := range all {
+ if ws.ID == workspaceID {
+ return ws
+ }
+ }
+ t.Fatalf("workspace %s missing from the list", workspaceID)
+ return WorkspaceResponse{}
+ }
+
+ for name, ws := range map[string]WorkspaceResponse{"get": get(guest), "list": list(guest)} {
+ if ws.Name != "Guest shell "+suffix || ws.Slug != "guest-shell-"+suffix {
+ t.Errorf("guest %s: identity = %q %q", name, ws.Name, ws.Slug)
+ }
+ if ws.Context != nil {
+ t.Errorf("guest %s: context = %q, want null", name, *ws.Context)
+ }
+ if repos, _ := ws.Repos.([]any); len(repos) != 0 {
+ t.Errorf("guest %s: repos = %v, want empty", name, ws.Repos)
+ }
+ settings, _ := ws.Settings.(map[string]any)
+ if fmt.Sprint(settings) != "map[github_enabled:true github_pr_sidebar_enabled:false]" {
+ t.Errorf("guest %s: settings = %v, want only the GitHub display flags", name, ws.Settings)
+ }
+ }
+
+ for _, viewer := range []struct{ name, userID string }{{"owner", testUserID}, {"member", member}} {
+ for name, ws := range map[string]WorkspaceResponse{"get": get(viewer.userID), "list": list(viewer.userID)} {
+ settings, _ := ws.Settings.(map[string]any)
+ if repos, _ := ws.Repos.([]any); ws.Context == nil || len(repos) != 1 || settings["internal_flag"] != "x" {
+ t.Errorf("%s %s: want the full workspace, got context=%v repos=%v settings=%v", viewer.name, name, ws.Context, ws.Repos, ws.Settings)
+ }
+ }
+ }
+}
+
+// A guest's grants on a private project are listed and changed only by those
+// who can see that project, owners and admins included (MUL-9284). Changing a
+// guest's projects without seeing one of them leaves the guest in it.
+func TestGuestProjectGrantsFollowTheViewersProjects(t *testing.T) {
+ clearInvitationsForTestWorkspace(t)
+ f := newGuestFixture(t)
+ addProjectMemberRow(t, f.secret, f.guest) // the owner (testUserID) is in secret
+ admin := createWorkspaceAdmin(t, f.marker+"[email protected]")
+ member := createPlainMember(t, f.marker+"[email protected]")
+ dbfx.Insert(t, "workspace_invitation", testutil.Cols{
+ "workspace_id": testWorkspaceID,
+ "inviter_id": testUserID,
+ "invitee_email": f.marker + "[email protected]",
+ "role": "guest",
+ "status": "pending",
+ "expires_at": testutil.Raw("now() + interval '1 day'"),
+ "project_ids": testutil.Raw(fmt.Sprintf("ARRAY['%s', '%s']::uuid[]", f.shared, f.secret)),
+ })
+
+ listedGrants := func(viewer string) (member, invitation []string) {
+ t.Helper()
+ var members []MemberWithUserResponse
+ guestRequest(t, testHandler.ListMembersWithUser, viewer, http.MethodGet,
+ "/api/workspaces/"+testWorkspaceID+"/members", nil, "id", testWorkspaceID).
+ Want(http.StatusOK).JSON(&members)
+ for _, m := range members {
+ if m.UserID == f.guest {
+ member = sorted(m.ProjectIDs...)
+ }
+ }
+ var invitations []InvitationResponse
+ guestRequest(t, testHandler.ListWorkspaceInvitations, viewer, http.MethodGet,
+ "/api/workspaces/"+testWorkspaceID+"/invitations", nil, "id", testWorkspaceID).
+ Want(http.StatusOK).JSON(&invitations)
+ for _, inv := range invitations {
+ if inv.Role == "guest" {
+ invitation = sorted(inv.ProjectIDs...)
+ }
+ }
+ return member, invitation
+ }
+ both := fmt.Sprint(sorted(f.shared, f.secret))
+ for _, tc := range []struct {
+ name, viewer, want string
+ }{
+ {"owner in the private project", testUserID, both},
+ {"admin outside it", admin, fmt.Sprint([]string{f.shared})},
+ {"member outside it", member, fmt.Sprint([]string{f.shared})},
+ } {
+ gotMember, gotInvitation := listedGrants(tc.viewer)
+ if fmt.Sprint(gotMember) != tc.want {
+ t.Errorf("%s: members list guest project_ids = %v, want %s", tc.name, gotMember, tc.want)
+ }
+ if fmt.Sprint(gotInvitation) != tc.want {
+ t.Errorf("%s: invitation project_ids = %v, want %s", tc.name, gotInvitation, tc.want)
+ }
+ }
+
+ setProjects := func(operator string, ids ...string) *testutil.Response {
+ t.Helper()
+ path := "/api/workspaces/" + testWorkspaceID + "/members/" + f.guestMember + "/projects"
+ req := withURLParams(asUser(newRequest(http.MethodPut, path, SetMemberProjectsRequest{ProjectIDs: ids}), operator),
+ "id", testWorkspaceID, "memberId", f.guestMember)
+ return testutil.Call(t, testHandler.SetMemberProjects, req)
+ }
+
+ // The admin moves the guest to another project; its grant on the private
+ // project the admin cannot see stays.
+ var resp MemberWithUserResponse
+ setProjects(admin, f.other).Want(http.StatusOK).JSON(&resp)
+ if got := guestProjectIDs(t, f.guest); fmt.Sprint(got) != fmt.Sprint(sorted(f.other, f.secret)) {
+ t.Errorf("after the admin's change guest projects = %v, want other and secret", got)
+ }
+ if fmt.Sprint(resp.ProjectIDs) != fmt.Sprint([]string{f.other}) {
+ t.Errorf("admin's response project_ids = %v, want only other", resp.ProjectIDs)
+ }
+ setProjects(admin, f.secret).Want(http.StatusBadRequest)
+
+ // The owner, a member of the private project, can take the guest out of it.
+ setProjects(testUserID, f.shared).Want(http.StatusOK)
+ if got := guestProjectIDs(t, f.guest); fmt.Sprint(got) != fmt.Sprint([]string{f.shared}) {
+ t.Errorf("after the owner's change guest projects = %v, want only shared", got)
+ }
+
+ // Demoting a member keeps it in the private projects the admin cannot see.
+ demoted := createPlainMember(t, f.marker+"[email protected]")
+ addProjectMemberRow(t, f.secret, demoted)
+ var demotedMember string
+ dbfx.QueryRow(t, `SELECT id FROM member WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, demoted).Scan(&demotedMember)
+ req := withURLParams(asUser(newRequest(http.MethodPatch, "/api/workspaces/"+testWorkspaceID+"/members/"+demotedMember,
+ UpdateMemberRequest{Role: "guest", ProjectIDs: []string{f.shared}}), admin), "id", testWorkspaceID, "memberId", demotedMember)
+ testutil.Call(t, testHandler.UpdateMember, req).Want(http.StatusOK)
+ if got := guestProjectIDs(t, demoted); fmt.Sprint(got) != fmt.Sprint(sorted(f.shared, f.secret)) {
+ t.Errorf("demoted guest projects = %v, want shared and secret", got)
+ }
+}
+
+// A member who received doc notifications and is then made a guest cannot
+// read them any more: not in the archive, its page and facets, the unread
+// counts, or by acting on the item directly. Notifications on issues in its
+// projects stay.
+func TestDemotedGuestCannotReadProjectlessNotifications(t *testing.T) {
+ f := newGuestFixture(t)
+ user := createPlainMember(t, f.marker+"[email protected]")
+ notify := func(issueID, title string, archived, read bool) string {
+ cols := testutil.Cols{
+ "workspace_id": testWorkspaceID, "recipient_type": "member", "recipient_id": user,
+ "type": inboxTypeDocComment, "severity": "info", "title": title, "body": "quoted doc text",
+ "archived": archived, "read": read,
+ }
+ if issueID != "" {
+ cols["issue_id"] = issueID
+ cols["type"] = "mentioned"
+ }
+ return dbfx.Insert(t, "inbox_item", cols)
+ }
+ archivedDoc := notify("", f.marker+" doc title", true, false)
+ notify("", f.marker+" unread doc", false, false)
+ // An archived issue with an active row lists in the inbox, not the archive.
+ archivedShared := dbfx.Issue(t, f.marker+" archived shared issue", testutil.Cols{
+ "project_id": f.shared, "number": 800000 + int(time.Now().UnixNano()%100000),
+ })
+ notify(archivedShared, f.marker+" shared", true, false)
+ notify(f.sharedIssue, f.marker+" shared unread", false, false)
+ notify(f.otherIssue, f.marker+" other unread", false, false)
+
+ archivedTitles := func() map[string]bool {
+ t.Helper()
+ titles := map[string]bool{}
+ var items []InboxItemResponse
+ guestRequest(t, testHandler.ListArchivedInbox, user, http.MethodGet, "/api/inbox/archived", nil).Want(http.StatusOK).JSON(&items)
+ for _, item := range items {
+ titles["list:"+item.Title] = true
+ }
+ var page archivedInboxPageResponse
+ guestRequest(t, testHandler.ListArchivedInboxPage, user, http.MethodGet, "/api/inbox/archived/page", nil).Want(http.StatusOK).JSON(&page)
+ for _, item := range page.Items {
+ titles["page:"+item.Title] = true
+ }
+ return titles
+ }
+ if titles := archivedTitles(); !titles["list:"+f.marker+" doc title"] || !titles["page:"+f.marker+" doc title"] {
+ t.Fatalf("as a member the archive misses the doc notification: %v", titles)
+ }
+
+ dbfx.Exec(t, `UPDATE member SET role = 'guest' WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, user)
+ addProjectMemberRow(t, f.shared, user)
+
+ titles := archivedTitles()
+ for _, key := range []string{"list:", "page:"} {
+ if titles[key+f.marker+" doc title"] {
+ t.Errorf("guest archive (%s) still shows the doc notification", key)
+ }
+ if !titles[key+f.marker+" shared"] {
+ t.Errorf("guest archive (%s) lost the notification on its project", key)
+ }
+ }
+
+ var facets archivedInboxFacetsResponse
+ guestRequest(t, testHandler.GetArchivedInboxFacets, user, http.MethodGet, "/api/inbox/archived/facets", nil).Want(http.StatusOK).JSON(&facets)
+ if facets.Types["system"] != 0 || facets.UnreadCount != 1 {
+ t.Errorf("guest facets count the doc notification: types=%v unread=%d", facets.Types, facets.UnreadCount)
+ }
+
+ var count map[string]int64
+ guestRequest(t, testHandler.CountUnreadInbox, user, http.MethodGet, "/api/inbox/unread-count", nil).Want(http.StatusOK).JSON(&count)
+ if count["count"] != 1 {
+ t.Errorf("guest unread count = %d, want 1 (its project's issue only)", count["count"])
+ }
+ var summary []InboxWorkspaceUnreadResponse
+ testutil.Call(t, testHandler.UnreadInboxSummary, asUser(newRequest(http.MethodGet, "/api/inbox/unread-summary", nil), user)).
+ Want(http.StatusOK).JSON(&summary)
+ if len(summary) != 1 || summary[0].Count != 1 {
+ t.Errorf("guest unread summary = %+v, want 1 in the workspace", summary)
+ }
+
+ for _, action := range []struct {
+ name string
+ handler http.HandlerFunc
+ }{
+ {"unarchive", testHandler.UnarchiveInboxItem},
+ {"read", testHandler.MarkInboxRead},
+ } {
+ rec := guestRequest(t, action.handler, user, http.MethodPost, "/api/inbox/"+archivedDoc+"/"+action.name, nil, "id", archivedDoc)
+ if rec.Code != http.StatusNotFound {
+ t.Errorf("guest %s of the doc notification = %d, want 404: %s", action.name, rec.Code, rec.Body.String())
+ }
+ }
+}
+
+// A member row whose role this build does not know grants nothing: a later
+// release may add a role, and rolling back to this build must not read it as
+// a member, the way builds before guests read 'guest'.
+func TestUnknownMemberRoleGrantsNothing(t *testing.T) {
+ ctx := context.Background()
+ if _, err := testPool.Exec(ctx, `ALTER TABLE member DROP CONSTRAINT IF EXISTS member_role_check,
+ ADD CONSTRAINT member_role_check CHECK (role IN ('owner', 'admin', 'member', 'guest', 'future_role')) NOT VALID`); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM member WHERE role = 'future_role'`)
+ testPool.Exec(context.Background(), `ALTER TABLE member DROP CONSTRAINT IF EXISTS member_role_check,
+ ADD CONSTRAINT member_role_check CHECK (role IN ('owner', 'admin', 'member', 'guest')) NOT VALID`)
+ })
+ user := createPlainMember(t, fmt.Sprintf("future-role-%[email protected]", uuid.NewString()[:8]))
+ ok := func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) }
+ guestRequest(t, ok, user, http.MethodGet, "/api/projects", nil).Want(http.StatusNoContent)
+
+ dbfx.Exec(t, `UPDATE member SET role = 'future_role' WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, user)
+
+ for _, path := range []string{"/api/projects", "/api/issues", "/api/agents"} {
+ if rec := guestRequest(t, ok, user, http.MethodGet, path, nil); rec.Code != http.StatusNotFound {
+ t.Errorf("GET %s with an unknown role = %d, want 404", path, rec.Code)
+ }
+ }
+ var all []WorkspaceResponse
+ testutil.Call(t, testHandler.ListWorkspaces, asUser(newRequest(http.MethodGet, "/api/workspaces", nil), user)).
+ Want(http.StatusOK).JSON(&all)
+ for _, ws := range all {
+ if ws.ID == testWorkspaceID {
+ t.Error("workspace list includes a workspace where the role is unknown")
+ }
+ }
+ rows, err := testHandler.Queries.GetRealtimeMemberships(ctx, db.GetRealtimeMembershipsParams{
+ UserIds: []pgtype.UUID{parseUUID(user)}, WorkspaceIds: []pgtype.UUID{parseUUID(testWorkspaceID)},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(rows) != 0 {
+ t.Error("realtime admits a member with an unknown role")
+ }
+
+ // Nor does it get workspace data through the account-level reads: the
+ // daemon's workspace list, notifications, and the unread summary, which
+ // still lists the workspace where the person is a member.
+ other := dbfx.Workspace(t, "Future role other "+uuid.NewString()[:8], "future-role-"+uuid.NewString()[:8])
+ dbfx.Cleanup(t, `DELETE FROM member WHERE workspace_id = $1`, other)
+ dbfx.Member(t, other, user, "member")
+ daemonWorkspaces, err := testHandler.Queries.ListDaemonWorkspaces(ctx, parseUUID(user))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(daemonWorkspaces) != 1 || uuidToString(daemonWorkspaces[0].ID) != other {
+ t.Errorf("daemon workspaces = %v, want only the workspace where the role is known", daemonWorkspaces)
+ }
+ if _, err := testHandler.Queries.CreateInboxItem(ctx, db.CreateInboxItemParams{
+ ID: parseUUID(uuid.NewString()), WorkspaceID: parseUUID(testWorkspaceID), RecipientType: "member",
+ RecipientID: parseUUID(user), Type: "mentioned", Severity: "info", Title: "future role",
+ }); !errors.Is(err, pgx.ErrNoRows) {
+ t.Errorf("deliver to a member with an unknown role: err = %v, want no row written", err)
+ }
+ for _, ws := range []string{testWorkspaceID, other} {
+ dbfx.Insert(t, "inbox_item", testutil.Cols{
+ "workspace_id": ws, "recipient_type": "member", "recipient_id": user,
+ "type": "mentioned", "severity": "info", "title": "unread",
+ })
+ }
+ var summary []InboxWorkspaceUnreadResponse
+ testutil.Call(t, testHandler.UnreadInboxSummary, asUser(newRequest(http.MethodGet, "/api/inbox/unread-summary", nil), user)).
+ Want(http.StatusOK).JSON(&summary)
+ if len(summary) != 1 || summary[0].WorkspaceID != other {
+ t.Errorf("unread summary = %+v, want only the workspace where the role is known", summary)
+ }
+}
+
+// A pending guest invitation reserves no member slot, so a joiner holding one
+// who comes in through a member share link takes a new slot, and cannot take
+// one another invitation reserved.
+func TestJoinShareLinkWithGuestInvitationTakesANewSlot(t *testing.T) {
+ workspaceID := memberLimitWorkspace(t, 3) // owner + 3 members
+ link := createTestShareLink(t, workspaceID, "member", 5, 0)
+ email := "guest-invited-joiner-" + uuid.NewString() + "@multica.ai"
+ userID := dbfx.User(t, "Guest-invited joiner", email)
+ guestInvitation := pendingInvitation(t, workspaceID, email, userID)
+ dbfx.Exec(t, `UPDATE workspace_invitation SET role = 'guest' WHERE id = $1`, guestInvitation)
+ pendingInvitation(t, workspaceID, "other-"+uuid.NewString()+"@multica.ai", "") // the fifth slot
+ useMemberLimit(t, workspaceID, entitlement.ActionEnforce, 5)
+
+ wantMemberLimitReached(t, joinWorkspaceByLink(t, link.Code, userID))
+ if n := dbfx.Count(t, `SELECT count(*) FROM member WHERE workspace_id = $1 AND user_id = $2`, workspaceID, userID); n != 0 {
+ t.Fatalf("refused join created %d members", n)
+ }
+}
+
+// The daemon routes hand out the same repositories and settings. A guest's
+// PAT/JWT is refused by the guest allowlist, and the membership cache, which
+// holds no role, never lists a guest; the reads that return the
+// configuration also check the current role of the person behind the
+// credential, which covers a daemon token whose owner has become a guest.
+func TestGuestCannotReadWorkspaceConfigThroughDaemonRoutes(t *testing.T) {
+ setHandlerTestWorkspaceRepos(t, []map[string]string{{"url": "[email protected]:acme/private.git"}})
+ marker := fmt.Sprintf("daemon-guest-%d", time.Now().UnixNano())
+ guest := createPlainMember(t, marker+"@multica.test")
+ dbfx.Exec(t, `UPDATE member SET role = 'guest' WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, guest)
+ member := createPlainMember(t, marker+"[email protected]")
+ path := "/api/daemon/workspaces/" + testWorkspaceID + "/repos"
+
+ readRepos := func(req *http.Request) *testutil.Response {
+ t.Helper()
+ return testutil.Call(t, testHandler.GetDaemonWorkspaceRepos, withURLParam(req, "workspaceId", testWorkspaceID))
+ }
+ guestToken := func(method, path string, body any) *http.Request {
+ req := newDaemonTokenRequest(method, path, body, testWorkspaceID, marker)
+ return req.WithContext(middleware.WithDaemonTokenOwnerID(req.Context(), guest))
+ }
+ guestPAT := func() *http.Request { return asUser(newRequest(http.MethodGet, path, nil), guest) }
+
+ readRepos(guestPAT()).Want(http.StatusForbidden)
+ readRepos(guestToken(http.MethodGet, path, nil)).Want(http.StatusNotFound)
+ readRepos(asUser(newRequest(http.MethodGet, path, nil), member)).Want(http.StatusOK)
+ readRepos(newDaemonTokenRequest(http.MethodGet, path, nil, testWorkspaceID, "owner-daemon")).Want(http.StatusOK)
+ if testHandler.verifyDaemonWorkspaceAccess(guestPAT(), testWorkspaceID) {
+ t.Error("the batch daemon check admits a guest")
+ }
+
+ // A daemon token whose owner is now a guest still registers its runtimes
+ // but gets none of the workspace's repositories or settings.
+ dbfx.Cleanup(t, `DELETE FROM agent_runtime WHERE daemon_id = $1`, marker)
+ var registered map[string]any
+ rec := testutil.Call(t, testHandler.DaemonRegister, guestToken(http.MethodPost, "/api/daemon/register", map[string]any{
+ "workspace_id": testWorkspaceID,
+ "daemon_id": marker,
+ "device_name": "guest-device",
+ "runtimes": []map[string]any{{"name": "guest-runtime", "type": "claude", "version": "1.0.0", "status": "online"}},
+ })).Want(http.StatusOK)
+ if err := json.NewDecoder(rec.Body).Decode(&registered); err != nil {
+ t.Fatal(err)
+ }
+ if repos, _ := registered["repos"].([]any); len(repos) != 0 || registered["settings"] != nil {
+ t.Errorf("guest-owned registration returned repos=%v settings=%v, want none", registered["repos"], registered["settings"])
+ }
+
+ t.Run("membership cache", func(t *testing.T) {
+ installFreshMembershipCache(t)
+ ctx := context.Background()
+ testHandler.verifyDaemonWorkspaceAccess(guestPAT(), testWorkspaceID)
+ if testHandler.MembershipCache.Get(ctx, guest, testWorkspaceID) {
+ t.Error("a guest was cached as a member")
+ }
+ // An entry written before this rule, or by a missed path, still
+ // does not open the configuration.
+ testHandler.MembershipCache.Set(ctx, guest, testWorkspaceID)
+ readRepos(guestPAT()).Want(http.StatusNotFound)
+ })
+}
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index e7cbaae90e..0efa616fe3 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -991,6 +991,17 @@ func (h *Handler) workspaceMember(w http.ResponseWriter, r *http.Request, worksp
return h.requireWorkspaceMember(w, r, workspaceID, "workspace not found")
}
+// cacheMembership records member in the membership cache, which callers
+// read as "a member who is not a guest": the cache holds no role, and a hit
+// skips the guest allowlist (MUL-9420). A guest is therefore never cached and
+// is looked up on every request.
+func (h *Handler) cacheMembership(ctx context.Context, member db.Member) {
+ if projectaccess.IsGuestRole(member.Role) {
+ return
+ }
+ h.MembershipCache.Set(ctx, uuidToString(member.UserID), uuidToString(member.WorkspaceID))
+}
+
func roleAllowed(role string, roles ...string) bool {
for _, candidate := range roles {
if role == candidate {
@@ -1329,5 +1340,10 @@ func (h *Handler) loadInboxItemForUser(w http.ResponseWriter, r *http.Request, i
if !h.requireIssueIDVisible(w, r, workspaceID, item.IssueID, http.StatusNotFound, "inbox item not found") {
return db.InboxItem{}, false
}
+ // An item without an issue (a doc comment) is outside any project, which
+ // a guest cannot see even when it was delivered before the demotion.
+ if !item.IssueID.Valid && !h.requireProjectVisible(w, r, workspaceID, pgtype.UUID{}, http.StatusNotFound, "inbox item not found") {
+ return db.InboxItem{}, false
+ }
return item, true
}
diff --git a/server/internal/handler/invitation.go b/server/internal/handler/invitation.go
index a8f7505f91..b8c253582d 100644
--- a/server/internal/handler/invitation.go
+++ b/server/internal/handler/invitation.go
@@ -266,7 +266,12 @@ func (h *Handler) CreateInvitation(w http.ResponseWriter, r *http.Request) {
// Notify the invitee in real time if they are a registered user.
userID := requestUserID(r)
- eventPayload := map[string]any{"invitation": resp}
+ // The event reaches every member, so it leaves out the projects, which
+ // may include private ones (ListWorkspaceInvitations filters them per
+ // viewer). Clients refetch on it rather than reading the payload.
+ eventInvitation := resp
+ eventInvitation.ProjectIDs = nil
+ eventPayload := map[string]any{"invitation": eventInvitation}
var workspaceName string
if ws, err := h.Queries.GetWorkspace(r.Context(), requester.WorkspaceID); err == nil {
workspaceName = ws.Name
@@ -313,6 +318,12 @@ func (h *Handler) ListWorkspaceInvitations(w http.ResponseWriter, r *http.Reques
writeError(w, http.StatusInternalServerError, "failed to list invitations")
return
}
+ // A guest invitation's projects are listed only where the viewer can see
+ // them, as on the members list.
+ hidden, ok := h.requestHiddenProjects(w, r, workspaceID)
+ if !ok {
+ return
+ }
includeGuests := clientRendersGuestRole(r)
resp := make([]InvitationResponse, 0, len(rows))
@@ -327,7 +338,7 @@ func (h *Handler) ListWorkspaceInvitations(w http.ResponseWriter, r *http.Reques
InviteeEmail: row.InviteeEmail,
InviteeUserID: uuidToPtr(row.InviteeUserID),
Role: row.Role,
- ProjectIDs: uuidsToStrings(row.ProjectIds),
+ ProjectIDs: visibleProjectIDs(hidden, uuidsToStrings(row.ProjectIds)),
Status: row.Status,
CreatedAt: timestampToString(row.CreatedAt),
UpdatedAt: timestampToString(row.UpdatedAt),
diff --git a/server/internal/handler/share_link.go b/server/internal/handler/share_link.go
index 660c57ac09..cfd9e09354 100644
--- a/server/internal/handler/share_link.go
+++ b/server/internal/handler/share_link.go
@@ -301,17 +301,18 @@ func (h *Handler) JoinByShareLink(w http.ResponseWriter, r *http.Request) {
}
// A joiner who also holds a pending email invitation takes the slot that
- // invitation reserved, exactly as accepting it would.
+ // invitation reserved, exactly as accepting it would. A guest invitation
+ // reserves no slot (CountWorkspaceMemberSlots), so it holds none to take.
holdsInvitation := false
if h.Entitlements != nil {
- _, pendingErr := h.Queries.GetPendingInvitationByEmail(r.Context(), db.GetPendingInvitationByEmailParams{
+ pending, pendingErr := h.Queries.GetPendingInvitationByEmail(r.Context(), db.GetPendingInvitationByEmailParams{
WorkspaceID: linkPreview.WorkspaceID, InviteeEmail: strings.ToLower(user.Email),
})
if pendingErr != nil && !errors.Is(pendingErr, pgx.ErrNoRows) {
writeError(w, http.StatusInternalServerError, "failed to join workspace")
return
}
- holdsInvitation = pendingErr == nil
+ holdsInvitation = pendingErr == nil && roleTakesMemberSlot(pending.Role)
}
memberLimit, err := h.memberLimitFor(r.Context(), linkPreview.WorkspaceID, linkPreview.Role, holdsInvitation)
if err != nil {
@@ -402,9 +403,10 @@ func (h *Handler) JoinByShareLink(w http.ResponseWriter, r *http.Request) {
return
}
- // A joiner whose pending invitation was settled above takes the slot that
- // invitation held, as accepting it would; otherwise the join is a new slot.
- memberLimit.reserved = settledInvitationID.Valid
+ // A joiner whose pending member invitation was settled above takes the
+ // slot that invitation held, as accepting it would; otherwise the join is
+ // a new slot.
+ memberLimit.reserved = settledInvitationID.Valid && roleTakesMemberSlot(pendingInv.Role)
limitAdmission, err := memberLimit.admit(r.Context(), qtx)
if err != nil {
_ = tx.Rollback(r.Context())
diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.go
index 77fed39f05..4443fa0892 100644
--- a/server/internal/handler/workspace.go
+++ b/server/internal/handler/workspace.go
@@ -141,6 +141,37 @@ func (h *Handler) workspaceToResponse(w db.Workspace) WorkspaceResponse {
}
}
+// guestWorkspaceSettings are the settings a guest's issue page reads to decide
+// what to show; everything else in settings configures the workspace.
+var guestWorkspaceSettings = []string{
+ "github_enabled",
+ "github_pr_sidebar_enabled",
+ "github_auto_link_prs_enabled",
+}
+
+// workspaceResponseFor is workspaceToResponse narrowed to the viewer's role.
+// A guest (MUL-9420) gets what identifies and displays the workspace, not the
+// agent instructions (context), repositories, or settings that configure it.
+// The fields stay present, empty, so every client parses the same shape.
+func (h *Handler) workspaceResponseFor(w db.Workspace, role string) WorkspaceResponse {
+ resp := h.workspaceToResponse(w)
+ if !projectaccess.IsGuestRole(role) {
+ return resp
+ }
+ settings := map[string]any{}
+ if all, ok := resp.Settings.(map[string]any); ok {
+ for _, key := range guestWorkspaceSettings {
+ if v, ok := all[key]; ok {
+ settings[key] = v
+ }
+ }
+ }
+ resp.Context = nil
+ resp.Settings = settings
+ resp.Repos = []any{}
+ return resp
+}
+
type MemberResponse struct {
ID string `json:"id"`
WorkspaceID string `json:"workspace_id"`
@@ -184,13 +215,13 @@ func (h *Handler) ListWorkspaces(w http.ResponseWriter, r *http.Request) {
if boundWorkspaceID != "" && uuidToString(ws.ID) != boundWorkspaceID {
continue
}
- item := h.workspaceToResponse(db.Workspace{
+ item := h.workspaceResponseFor(db.Workspace{
ID: ws.ID, Name: ws.Name, Slug: ws.Slug, Description: ws.Description,
Settings: ws.Settings, CreatedAt: ws.CreatedAt, UpdatedAt: ws.UpdatedAt,
Context: ws.Context, Repos: ws.Repos, IssuePrefix: ws.IssuePrefix,
IssueCounter: ws.IssueCounter, AvatarUrl: ws.AvatarUrl,
AttributionFailClosed: ws.AttributionFailClosed,
- })
+ }, ws.Role)
if ws.PinnedAt.Valid {
pinnedAt := timestampToString(ws.PinnedAt)
item.PinnedAt = &pinnedAt
@@ -243,12 +274,17 @@ func (h *Handler) GetWorkspace(w http.ResponseWriter, r *http.Request) {
return
}
+ member, ok := h.workspaceMember(w, r, id)
+ if !ok {
+ return
+ }
+
ws, err := h.Queries.GetWorkspace(r.Context(), idUUID)
if err != nil {
writeError(w, http.StatusNotFound, "workspace not found")
return
}
- writeJSON(w, http.StatusOK, h.workspaceToResponse(ws))
+ writeJSON(w, http.StatusOK, h.workspaceResponseFor(ws, member.Role))
}
type CreateWorkspaceRequest struct {
@@ -620,6 +656,15 @@ func (h *Handler) ListMembersWithUser(w http.ResponseWriter, r *http.Request) {
requester, _ := ctxMember(r.Context())
requesterIsGuest := projectaccess.IsGuestRole(requester.Role)
includeGuests := clientRendersGuestRole(r)
+ // Everyone else sees a guest's grants only on projects they can see
+ // themselves: a private project's id is not shown outside its members,
+ // owners and admins included (MUL-9284).
+ var requesterHidden projectaccess.Hidden
+ if !requesterIsGuest {
+ if requesterHidden, ok = h.requestHiddenProjects(w, r, uuidToString(wsUUID)); !ok {
+ return
+ }
+ }
visibleGuests := map[[16]byte]bool{requester.UserID.Bytes: true}
if requesterIsGuest {
mine := map[string]bool{}
@@ -655,7 +700,7 @@ func (h *Handler) ListMembersWithUser(w http.ResponseWriter, r *http.Request) {
AvatarURL: h.resolveAvatarURLPtr(textToPtr(m.UserAvatarUrl)),
}
if guest && !requesterIsGuest {
- item.ProjectIDs = guestProjects[m.UserID.Bytes]
+ item.ProjectIDs = visibleProjectIDs(requesterHidden, guestProjects[m.UserID.Bytes])
}
resp = append(resp, item)
}
@@ -800,13 +845,15 @@ func (h *Handler) UpdateMember(w http.ResponseWriter, r *http.Request) {
}
resp := h.memberWithUserResponse(updatedMember, user)
- if toGuest {
- resp.ProjectIDs = uuidsToStrings(guestProjects)
- }
userID := requestUserID(r)
+ // The event reaches every member, so it carries no projects: a guest's
+ // projects are shown per viewer (ListMembersWithUser).
h.publish(protocol.EventMemberUpdated, uuidToString(requester.WorkspaceID), "member", userID, map[string]any{
"member": resp,
})
+ if toGuest {
+ resp.ProjectIDs = uuidsToStrings(guestProjects)
+ }
writeJSON(w, http.StatusOK, resp)
}
diff --git a/server/internal/handler/workspace_revoke.go b/server/internal/handler/workspace_revoke.go
index f5af1db9c9..eebe2e646a 100644
--- a/server/internal/handler/workspace_revoke.go
+++ b/server/internal/handler/workspace_revoke.go
@@ -299,10 +299,15 @@ func (h *Handler) revokeMember(ctx context.Context, workspaceID, userID, memberI
// No FK cascade (repo rule): a departing member leaves every private
// project in the workspace and stops watching every project. A new guest
- // keeps exactly its guest projects.
+ // keeps its guest projects and the private projects hidden from the
+ // operator (guestProjectsToKeep).
if demote {
+ keep, err := guestProjectsToKeep(ctx, qtx, workspaceID, archivedBy, guestProjects)
+ if err != nil {
+ return empty, err
+ }
if _, err := qtx.RemoveUserFromProjectsExcept(ctx, db.RemoveUserFromProjectsExceptParams{
- WorkspaceID: workspaceID, UserID: userID, KeepProjectIds: guestProjects,
+ WorkspaceID: workspaceID, UserID: userID, KeepProjectIds: keep,
}); err != nil {
return empty, err
}
diff --git a/server/pkg/db/generated/inbox.sql.go b/server/pkg/db/generated/inbox.sql.go
index bc66649cbf..fc81b2a95f 100644
--- a/server/pkg/db/generated/inbox.sql.go
+++ b/server/pkg/db/generated/inbox.sql.go
@@ -328,11 +328,10 @@ WHERE i.workspace_id = $1
AND i.archived = false
AND (i.snoozed_until IS NULL OR i.snoozed_until <= now())
-- MUL-8472: private projects the caller cannot see.
- AND ($4::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (
- SELECT 1 FROM issue hidden_issue
- WHERE hidden_issue.id = i.issue_id
- AND COALESCE(hidden_issue.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($4::uuid[])
- ))
+ -- A row without an issue counts as outside any project (see ListInboxItems).
+ AND ($4::uuid[] IS NULL OR NOT (COALESCE(
+ (SELECT hidden_issue.project_id FROM issue hidden_issue WHERE hidden_issue.id = i.issue_id),
+ '00000000-0000-0000-0000-000000000000'::uuid) = ANY($4::uuid[])))
`
type CountUnreadInboxParams struct {
@@ -361,6 +360,7 @@ FROM (
i.workspace_id, i.read
FROM inbox_item i
JOIN member m ON m.workspace_id = i.workspace_id AND m.user_id = i.recipient_id
+ AND m.role IN ('owner', 'admin', 'member', 'guest')
WHERE i.recipient_type = 'member'
AND i.recipient_id = $1
AND i.archived = false
@@ -378,6 +378,13 @@ FROM (
WHERE pm.project_id = private_project.id AND pm.user_id = i.recipient_id
)
)
+ -- MUL-9420: a guest counts only issues in its own projects, so nothing
+ -- outside a project and nothing in a project it is not a member of.
+ AND (m.role <> 'guest' OR EXISTS (
+ SELECT 1 FROM issue guest_issue
+ JOIN project_member gpm ON gpm.project_id = guest_issue.project_id AND gpm.user_id = i.recipient_id
+ WHERE guest_issue.id = i.issue_id
+ ))
ORDER BY i.workspace_id, COALESCE(i.issue_id, i.id), i.created_at DESC
) newest
WHERE newest.read = false
@@ -398,8 +405,8 @@ type CountUnreadInboxByWorkspaceRow struct {
// the switcher dot for a workspace whose inbox the user sees as empty
// (MUL-3695). Items without an issue group on their own id. The
// member join keeps counts scoped to workspaces the user still belongs to,
-// so a stale item left behind in a workspace the user has since left cannot
-// light the dot.
+// so a stale item left behind in a workspace the user has since left, or holds
+// a role this build does not know in, cannot light the dot.
func (q *Queries) CountUnreadInboxByWorkspace(ctx context.Context, recipientID pgtype.UUID) ([]CountUnreadInboxByWorkspaceRow, error) {
rows, err := q.db.Query(ctx, countUnreadInboxByWorkspace, recipientID)
if err != nil {
@@ -440,6 +447,7 @@ LEFT JOIN LATERAL (
) AS snoozed ON true
WHERE (($2::text = 'member' AND EXISTS (
SELECT 1 FROM member WHERE workspace_id = $1 AND user_id = $3
+ AND role IN ('owner', 'admin', 'member', 'guest')
)) OR ($2::text = 'agent' AND EXISTS (
SELECT 1 FROM agent WHERE workspace_id = $1 AND id = $3
)))
@@ -480,6 +488,8 @@ type CreateInboxItemParams struct {
// wakes it. A joining row is the issue's newest, so it carries the issue's
// return rank (returned_at, the snooze end); inbox.Deliver clears it from the
// row that held it (HandInboxReturnToRow).
+// A role this build does not know is no membership (see
+// GetMemberByUserAndWorkspace), so it is sent nothing.
// MUL-8472: a member outside a private project gets no notification about its
// issues, whatever their workspace role. Only project members do.
func (q *Queries) CreateInboxItem(ctx context.Context, arg CreateInboxItemParams) (InboxItem, error) {
@@ -716,11 +726,11 @@ WITH eligible_archived AS MATERIALIZED (
AND i.recipient_id = $3
AND i.archived = true
-- MUL-8472: private projects the caller cannot see.
- AND ($4::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (
- SELECT 1 FROM issue hidden_issue
- WHERE hidden_issue.id = i.issue_id
- AND COALESCE(hidden_issue.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($4::uuid[])
- ))
+ -- A row without an issue counts as outside any project, which a guest's
+ -- hidden set holds (projectaccess.NoProject), as ListInboxItems does.
+ AND ($4::uuid[] IS NULL OR NOT (COALESCE(
+ (SELECT hidden_issue.project_id FROM issue hidden_issue WHERE hidden_issue.id = i.issue_id),
+ '00000000-0000-0000-0000-000000000000'::uuid) = ANY($4::uuid[])))
AND (i.issue_id IS NULL OR NOT EXISTS (
SELECT 1
FROM inbox_item active
diff --git a/server/pkg/db/generated/inbox_archive.sql.go b/server/pkg/db/generated/inbox_archive.sql.go
index 1faa9499ca..0e9c6bca0f 100644
--- a/server/pkg/db/generated/inbox_archive.sql.go
+++ b/server/pkg/db/generated/inbox_archive.sql.go
@@ -31,11 +31,11 @@ WITH base AS MATERIALIZED (
AND i.recipient_id = $2::uuid
AND i.archived = true
-- MUL-8472: private projects the caller cannot see.
- AND ($3::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (
- SELECT 1 FROM issue hidden_issue
- WHERE hidden_issue.id = i.issue_id
- AND COALESCE(hidden_issue.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($3::uuid[])
- ))
+ -- A row without an issue counts as outside any project, which a guest's
+ -- hidden set holds (projectaccess.NoProject), as ListInboxItems does.
+ AND ($3::uuid[] IS NULL OR NOT (COALESCE(
+ (SELECT hidden_issue.project_id FROM issue hidden_issue WHERE hidden_issue.id = i.issue_id),
+ '00000000-0000-0000-0000-000000000000'::uuid) = ANY($3::uuid[])))
AND (i.issue_id IS NULL OR NOT EXISTS (
SELECT 1 FROM inbox_item active
WHERE active.workspace_id = i.workspace_id
@@ -226,11 +226,11 @@ WITH base AS MATERIALIZED (
AND i.recipient_id = $2::uuid
AND i.archived = true
-- MUL-8472: private projects the caller cannot see.
- AND ($3::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (
- SELECT 1 FROM issue hidden_issue
- WHERE hidden_issue.id = i.issue_id
- AND COALESCE(hidden_issue.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($3::uuid[])
- ))
+ -- A row without an issue counts as outside any project, which a guest's
+ -- hidden set holds (projectaccess.NoProject), as ListInboxItems does.
+ AND ($3::uuid[] IS NULL OR NOT (COALESCE(
+ (SELECT hidden_issue.project_id FROM issue hidden_issue WHERE hidden_issue.id = i.issue_id),
+ '00000000-0000-0000-0000-000000000000'::uuid) = ANY($3::uuid[])))
AND ($4::uuid IS NULL OR i.issue_id = $4::uuid
OR (i.issue_id IS NULL AND i.id = $4::uuid))
AND (i.issue_id IS NULL OR NOT EXISTS (
diff --git a/server/pkg/db/generated/member.sql.go b/server/pkg/db/generated/member.sql.go
index 97624636e2..d0c43e6f4c 100644
--- a/server/pkg/db/generated/member.sql.go
+++ b/server/pkg/db/generated/member.sql.go
@@ -68,6 +68,7 @@ func (q *Queries) GetMember(ctx context.Context, id pgtype.UUID) (Member, error)
const getMemberByUserAndWorkspace = `-- name: GetMemberByUserAndWorkspace :one
SELECT id, workspace_id, user_id, role, created_at, pinned_at FROM member
WHERE user_id = $1 AND workspace_id = $2
+ AND role IN ('owner', 'admin', 'member', 'guest')
`
type GetMemberByUserAndWorkspaceParams struct {
@@ -75,6 +76,10 @@ type GetMemberByUserAndWorkspaceParams struct {
WorkspaceID pgtype.UUID `json:"workspace_id"`
}
+// A role this build does not know is no membership: every access check that
+// starts from this lookup refuses it. A later release can then add a role
+// and still be rolled back to this one without the old build reading the new
+// role as a full member, the way builds before guests read 'guest'.
func (q *Queries) GetMemberByUserAndWorkspace(ctx context.Context, arg GetMemberByUserAndWorkspaceParams) (Member, error) {
row := q.db.QueryRow(ctx, getMemberByUserAndWorkspace, arg.UserID, arg.WorkspaceID)
var i Member
@@ -117,7 +122,7 @@ JOIN (
unnest($2::uuid[]) AS workspace_id
) AS requested
ON m.user_id = requested.user_id AND m.workspace_id = requested.workspace_id
-WHERE m.role <> 'guest'
+WHERE m.role IN ('owner', 'admin', 'member')
`
type GetRealtimeMembershipsParams struct {
@@ -131,7 +136,8 @@ type GetRealtimeMembershipsRow struct {
}
// Guests (MUL-9420) get no realtime stream: workspace fanout is not narrowed
-// to their projects, so a socket that becomes a guest's is closed.
+// to their projects, so a socket that becomes a guest's is closed. Neither
+// does a role this build does not know (see GetMemberByUserAndWorkspace).
func (q *Queries) GetRealtimeMemberships(ctx context.Context, arg GetRealtimeMembershipsParams) ([]GetRealtimeMembershipsRow, error) {
rows, err := q.db.Query(ctx, getRealtimeMemberships, arg.UserIds, arg.WorkspaceIds)
if err != nil {
diff --git a/server/pkg/db/generated/workspace.sql.go b/server/pkg/db/generated/workspace.sql.go
index b8d3771e1b..cb13d9afc0 100644
--- a/server/pkg/db/generated/workspace.sql.go
+++ b/server/pkg/db/generated/workspace.sql.go
@@ -356,6 +356,7 @@ SELECT w.id, w.name
FROM member m
JOIN workspace w ON w.id = m.workspace_id
WHERE m.user_id = $1
+ AND m.role IN ('owner', 'admin', 'member', 'guest')
ORDER BY w.id ASC
`
@@ -367,7 +368,8 @@ type ListDaemonWorkspacesRow struct {
// Daemons only need the membership set and display name to discover which
// workspaces should have local runtimes. Keep this projection intentionally
// narrow so the periodic consistency check never reads UI-only JSON/text
-// columns such as settings, repos, or context.
+// columns such as settings, repos, or context. A role this build does not
+// know is no membership (see GetMemberByUserAndWorkspace).
func (q *Queries) ListDaemonWorkspaces(ctx context.Context, userID pgtype.UUID) ([]ListDaemonWorkspacesRow, error) {
rows, err := q.db.Query(ctx, listDaemonWorkspaces, userID)
if err != nil {
@@ -391,10 +393,12 @@ func (q *Queries) ListDaemonWorkspaces(ctx context.Context, userID pgtype.UUID)
const listWorkspaces = `-- name: ListWorkspaces :many
SELECT w.id, w.name, w.slug, w.description, w.settings,
w.created_at, w.updated_at, w.context, w.repos,
- w.issue_prefix, w.issue_counter, w.avatar_url, w.attribution_fail_closed, m.pinned_at
+ w.issue_prefix, w.issue_counter, w.avatar_url, w.attribution_fail_closed, m.pinned_at,
+ m.role
FROM member m
JOIN workspace w ON w.id = m.workspace_id
WHERE m.user_id = $1
+ AND m.role IN ('owner', 'admin', 'member', 'guest')
ORDER BY m.pinned_at DESC NULLS LAST, w.created_at ASC
`
@@ -413,8 +417,11 @@ type ListWorkspacesRow struct {
AvatarUrl pgtype.Text `json:"avatar_url"`
AttributionFailClosed bool `json:"attribution_fail_closed"`
PinnedAt pgtype.Timestamptz `json:"pinned_at"`
+ Role string `json:"role"`
}
+// The role narrows what a guest is shown (workspaceResponseFor). A role this
+// build does not know is no membership (see GetMemberByUserAndWorkspace).
func (q *Queries) ListWorkspaces(ctx context.Context, userID pgtype.UUID) ([]ListWorkspacesRow, error) {
rows, err := q.db.Query(ctx, listWorkspaces, userID)
if err != nil {
@@ -439,6 +446,7 @@ func (q *Queries) ListWorkspaces(ctx context.Context, userID pgtype.UUID) ([]Lis
&i.AvatarUrl,
&i.AttributionFailClosed,
&i.PinnedAt,
+ &i.Role,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/queries/inbox.sql b/server/pkg/db/queries/inbox.sql
index df1e75803a..1fd5ece010 100644
--- a/server/pkg/db/queries/inbox.sql
+++ b/server/pkg/db/queries/inbox.sql
@@ -61,11 +61,11 @@ WITH eligible_archived AS MATERIALIZED (
AND i.recipient_id = $3
AND i.archived = true
-- MUL-8472: private projects the caller cannot see.
- AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (
- SELECT 1 FROM issue hidden_issue
- WHERE hidden_issue.id = i.issue_id
- AND COALESCE(hidden_issue.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])
- ))
+ -- A row without an issue counts as outside any project, which a guest's
+ -- hidden set holds (projectaccess.NoProject), as ListInboxItems does.
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR NOT (COALESCE(
+ (SELECT hidden_issue.project_id FROM issue hidden_issue WHERE hidden_issue.id = i.issue_id),
+ '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
AND (i.issue_id IS NULL OR NOT EXISTS (
SELECT 1
FROM inbox_item active
@@ -147,8 +147,11 @@ LEFT JOIN LATERAL (
ORDER BY s.snoozed_until DESC
LIMIT 1
) AS snoozed ON true
+-- A role this build does not know is no membership (see
+-- GetMemberByUserAndWorkspace), so it is sent nothing.
WHERE (($2::text = 'member' AND EXISTS (
SELECT 1 FROM member WHERE workspace_id = $1 AND user_id = $3
+ AND role IN ('owner', 'admin', 'member', 'guest')
)) OR ($2::text = 'agent' AND EXISTS (
SELECT 1 FROM agent WHERE workspace_id = $1 AND id = $3
)))
@@ -266,11 +269,10 @@ WHERE i.workspace_id = sqlc.arg('workspace_id')
AND i.archived = false
AND (i.snoozed_until IS NULL OR i.snoozed_until <= now())
-- MUL-8472: private projects the caller cannot see.
- AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (
- SELECT 1 FROM issue hidden_issue
- WHERE hidden_issue.id = i.issue_id
- AND COALESCE(hidden_issue.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])
- ));
+ -- A row without an issue counts as outside any project (see ListInboxItems).
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR NOT (COALESCE(
+ (SELECT hidden_issue.project_id FROM issue hidden_issue WHERE hidden_issue.id = i.issue_id),
+ '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])));
-- name: CountUnreadInboxByWorkspace :many
-- Per-workspace unread inbox counts for a recipient member, matching the
@@ -282,14 +284,15 @@ WHERE i.workspace_id = sqlc.arg('workspace_id')
-- the switcher dot for a workspace whose inbox the user sees as empty
-- (MUL-3695). Items without an issue group on their own id. The
-- member join keeps counts scoped to workspaces the user still belongs to,
--- so a stale item left behind in a workspace the user has since left cannot
--- light the dot.
+-- so a stale item left behind in a workspace the user has since left, or holds
+-- a role this build does not know in, cannot light the dot.
SELECT newest.workspace_id, count(*) AS count
FROM (
SELECT DISTINCT ON (i.workspace_id, COALESCE(i.issue_id, i.id))
i.workspace_id, i.read
FROM inbox_item i
JOIN member m ON m.workspace_id = i.workspace_id AND m.user_id = i.recipient_id
+ AND m.role IN ('owner', 'admin', 'member', 'guest')
WHERE i.recipient_type = 'member'
AND i.recipient_id = $1
AND i.archived = false
@@ -307,6 +310,13 @@ FROM (
WHERE pm.project_id = private_project.id AND pm.user_id = i.recipient_id
)
)
+ -- MUL-9420: a guest counts only issues in its own projects, so nothing
+ -- outside a project and nothing in a project it is not a member of.
+ AND (m.role <> 'guest' OR EXISTS (
+ SELECT 1 FROM issue guest_issue
+ JOIN project_member gpm ON gpm.project_id = guest_issue.project_id AND gpm.user_id = i.recipient_id
+ WHERE guest_issue.id = i.issue_id
+ ))
ORDER BY i.workspace_id, COALESCE(i.issue_id, i.id), i.created_at DESC
) newest
WHERE newest.read = false
diff --git a/server/pkg/db/queries/inbox_archive.sql b/server/pkg/db/queries/inbox_archive.sql
index dc7c019d56..65313ba88c 100644
--- a/server/pkg/db/queries/inbox_archive.sql
+++ b/server/pkg/db/queries/inbox_archive.sql
@@ -29,11 +29,11 @@ WITH base AS MATERIALIZED (
AND i.recipient_id = sqlc.arg(recipient_id)::uuid
AND i.archived = true
-- MUL-8472: private projects the caller cannot see.
- AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (
- SELECT 1 FROM issue hidden_issue
- WHERE hidden_issue.id = i.issue_id
- AND COALESCE(hidden_issue.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])
- ))
+ -- A row without an issue counts as outside any project, which a guest's
+ -- hidden set holds (projectaccess.NoProject), as ListInboxItems does.
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR NOT (COALESCE(
+ (SELECT hidden_issue.project_id FROM issue hidden_issue WHERE hidden_issue.id = i.issue_id),
+ '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
AND (sqlc.narg(group_id)::uuid IS NULL OR i.issue_id = sqlc.narg(group_id)::uuid
OR (i.issue_id IS NULL AND i.id = sqlc.narg(group_id)::uuid))
AND (i.issue_id IS NULL OR NOT EXISTS (
@@ -144,11 +144,11 @@ WITH base AS MATERIALIZED (
AND i.recipient_id = sqlc.arg(recipient_id)::uuid
AND i.archived = true
-- MUL-8472: private projects the caller cannot see.
- AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (
- SELECT 1 FROM issue hidden_issue
- WHERE hidden_issue.id = i.issue_id
- AND COALESCE(hidden_issue.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])
- ))
+ -- A row without an issue counts as outside any project, which a guest's
+ -- hidden set holds (projectaccess.NoProject), as ListInboxItems does.
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR NOT (COALESCE(
+ (SELECT hidden_issue.project_id FROM issue hidden_issue WHERE hidden_issue.id = i.issue_id),
+ '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
AND (i.issue_id IS NULL OR NOT EXISTS (
SELECT 1 FROM inbox_item active
WHERE active.workspace_id = i.workspace_id
diff --git a/server/pkg/db/queries/member.sql b/server/pkg/db/queries/member.sql
index e102b783d4..ce42036030 100644
--- a/server/pkg/db/queries/member.sql
+++ b/server/pkg/db/queries/member.sql
@@ -13,8 +13,13 @@ SELECT * FROM member
WHERE id = $1;
-- name: GetMemberByUserAndWorkspace :one
+-- A role this build does not know is no membership: every access check that
+-- starts from this lookup refuses it. A later release can then add a role
+-- and still be rolled back to this one without the old build reading the new
+-- role as a full member, the way builds before guests read 'guest'.
SELECT * FROM member
-WHERE user_id = $1 AND workspace_id = $2;
+WHERE user_id = $1 AND workspace_id = $2
+ AND role IN ('owner', 'admin', 'member', 'guest');
-- name: GetRealtimeMemberships :many
SELECT m.user_id, m.workspace_id
@@ -25,8 +30,9 @@ JOIN (
) AS requested
ON m.user_id = requested.user_id AND m.workspace_id = requested.workspace_id
-- Guests (MUL-9420) get no realtime stream: workspace fanout is not narrowed
--- to their projects, so a socket that becomes a guest's is closed.
-WHERE m.role <> 'guest';
+-- to their projects, so a socket that becomes a guest's is closed. Neither
+-- does a role this build does not know (see GetMemberByUserAndWorkspace).
+WHERE m.role IN ('owner', 'admin', 'member');
-- name: CreateMember :one
INSERT INTO member (workspace_id, user_id, role)
diff --git a/server/pkg/db/queries/workspace.sql b/server/pkg/db/queries/workspace.sql
index f0ebab18c9..3ec2d8f814 100644
--- a/server/pkg/db/queries/workspace.sql
+++ b/server/pkg/db/queries/workspace.sql
@@ -1,21 +1,27 @@
-- name: ListWorkspaces :many
+-- The role narrows what a guest is shown (workspaceResponseFor). A role this
+-- build does not know is no membership (see GetMemberByUserAndWorkspace).
SELECT w.id, w.name, w.slug, w.description, w.settings,
w.created_at, w.updated_at, w.context, w.repos,
- w.issue_prefix, w.issue_counter, w.avatar_url, w.attribution_fail_closed, m.pinned_at
+ w.issue_prefix, w.issue_counter, w.avatar_url, w.attribution_fail_closed, m.pinned_at,
+ m.role
FROM member m
JOIN workspace w ON w.id = m.workspace_id
WHERE m.user_id = $1
+ AND m.role IN ('owner', 'admin', 'member', 'guest')
ORDER BY m.pinned_at DESC NULLS LAST, w.created_at ASC;
-- name: ListDaemonWorkspaces :many
-- Daemons only need the membership set and display name to discover which
-- workspaces should have local runtimes. Keep this projection intentionally
-- narrow so the periodic consistency check never reads UI-only JSON/text
--- columns such as settings, repos, or context.
+-- columns such as settings, repos, or context. A role this build does not
+-- know is no membership (see GetMemberByUserAndWorkspace).
SELECT w.id, w.name
FROM member m
JOIN workspace w ON w.id = m.workspace_id
WHERE m.user_id = $1
+ AND m.role IN ('owner', 'admin', 'member', 'guest')
ORDER BY w.id ASC;
-- name: GetDaemonWorkspace :one