Adds project summaries and share counts on top of #32025. The sidebar's pinned projects read the summaries; the Projects page reads the summaries and the counts. - **`GET /api/experimental/chats/projects/summaries`** returns one `ChatProjectSummary` for every project in the existing project list (the same set): `project_id`, `pinned`, `pin_order`, `own_chat_count`, `own_unread_count`, `own_running`, `own_needs_attention` (`requires_action`, `error` or `paused`) and `last_activity_at` (newest `updated_at` among the caller's counted chats). Counts use only the caller's own top-level, non-archived chats; unread uses the same rule as `has_unread`. `pin_order` is the stored order from #32025: it sorts the pinned projects, lowest first, and can have gaps. A summary does not repeat the project: clients pair it with `GET /chats/projects` by ID. - **Share counts on `ChatProject`:** every project response now carries `member_count` (the owner plus the users the project is shared with directly), `group_count` (shared groups, including Everyone) and `shared_with_everyone`. They count exactly the users and groups `GET .../projects/{project}/acl` lists: users outside the project's organization and deleted groups are left out, through the same helper the ACL endpoint uses. Group members are not expanded, so a list costs two extra queries (memberships and groups) for any number of projects. While chat sharing is disabled or the `chat-project-sharing` experiment is off, every project reports 1 member, 0 groups. - **Same numbers on both pages:** the project page heading already showed "N members, M groups" from the ACL. It now uses a shared formatter, `formatProjectMembers`, which the Projects page card (#32083) also uses, and names the Everyone group first instead of counting it: "Everyone, 2 members, 1 group". - **Why summaries are separate:** the pin and the caller's chat counts change with every chat event, and clients refetch them often, so they do not come with the project, its templates and permissions. - **Authorization:** summaries return only projects the caller can read. They also carry the caller's pins, so they ask RBAC for `read_personal` on the caller: an API key scoped without `user:read_personal` gets a 403. The summaries authorize each project with a full evaluation while the caller has fewer than 200, because the partial evaluation `rbac.Filter` prepares by default costs an organization member about 6 ms per request and a full evaluation about 0.03 ms per project. <details> <summary>Verification</summary> `make gen/db` and the API docs and TypeScript types regenerate cleanly; Go lint on the changed packages, the summaries, share counts, pin, chat list, ACL and dbauthz tests pass; `pnpm lint` and the project page tests pass. `TestChatProjectShareCounts` fails if either ACL filter (organization membership, existing groups) is removed. The summaries timings (1.6 ms at 10 projects, 4.6 ms at 50) are medians of 40 runs against a local Postgres 13, measured before the share counts change. Dogfood UAT with a premium license ran on an earlier response shape, which carried the project and a people count inside each summary. It was not repeated for this shape; the Go and Vitest tests cover it. </details> > [!NOTE] > Most of this PR was written by AI agents (Xum, with UAT run through Coder Agents). The verification above is from those runs.
448 lines
16 KiB
Go
448 lines
16 KiB
Go
package coderd
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"slices"
|
|
|
|
"github.com/google/uuid"
|
|
"golang.org/x/xerrors"
|
|
|
|
"github.com/coder/coder/v2/buildinfo"
|
|
"github.com/coder/coder/v2/coderd/audit"
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
"github.com/coder/coder/v2/coderd/database/db2sdk"
|
|
"github.com/coder/coder/v2/coderd/database/dbauthz"
|
|
"github.com/coder/coder/v2/coderd/httpapi"
|
|
"github.com/coder/coder/v2/coderd/httpmw"
|
|
"github.com/coder/coder/v2/coderd/rbac/acl"
|
|
"github.com/coder/coder/v2/coderd/rbac/policy"
|
|
"github.com/coder/coder/v2/coderd/util/slice"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
)
|
|
|
|
// @Summary Get chat project ACL
|
|
// @ID get-chat-project-acl
|
|
// @Security CoderSessionToken
|
|
// @Tags Chats
|
|
// @Produce json
|
|
// @Param organization path string true "Organization ID" format(uuid)
|
|
// @Param project path string true "Chat project ID" format(uuid)
|
|
// @Success 200 {object} codersdk.ChatProjectACL
|
|
// @Router /api/experimental/organizations/{organization}/chats/projects/{project}/acl [get]
|
|
// @x-apidocgen {"skip": true}
|
|
//
|
|
//nolint:revive // HTTP handler writes to ResponseWriter.
|
|
func (api *API) getChatProjectACL(rw http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
project := httpmw.ChatProjectParam(r)
|
|
|
|
// Read check first so the disabled response does not reveal the project.
|
|
if !api.Authorize(r, policy.ActionRead, project.RBACObject()) {
|
|
httpapi.ResourceNotFound(rw)
|
|
return
|
|
}
|
|
if !api.allowChatSharing(ctx, rw) {
|
|
return
|
|
}
|
|
|
|
//nolint:gocritic // Project readers see the owner without user read permission.
|
|
owner, err := api.Database.GetUserByID(dbauthz.AsSystemRestricted(ctx), project.OwnerID)
|
|
if err != nil {
|
|
httpapi.InternalServerError(rw, xerrors.Errorf("get project owner: %w", err))
|
|
return
|
|
}
|
|
users, err := api.chatProjectACLUsers(ctx, project)
|
|
if err != nil {
|
|
httpapi.InternalServerError(rw, err)
|
|
return
|
|
}
|
|
// Groups from other organizations stay listed because their members in
|
|
// this organization still get access.
|
|
groups, err := resolveACLGroups(ctx, api.Database, uuid.Nil, project.GroupACL, func(group codersdk.Group, entry database.ChatACLEntry) codersdk.ChatProjectGroup {
|
|
return codersdk.ChatProjectGroup{Group: group, Role: convertToChatProjectRole(entry.Permissions)}
|
|
})
|
|
if err != nil {
|
|
httpapi.InternalServerError(rw, err)
|
|
return
|
|
}
|
|
httpapi.Write(ctx, rw, http.StatusOK, codersdk.ChatProjectACL{
|
|
Owner: db2sdk.MinimalUser(owner),
|
|
Users: users,
|
|
Groups: groups,
|
|
})
|
|
}
|
|
|
|
// @Summary Update chat project ACL
|
|
// @ID update-chat-project-acl
|
|
// @Security CoderSessionToken
|
|
// @Tags Chats
|
|
// @Accept json
|
|
// @Param organization path string true "Organization ID" format(uuid)
|
|
// @Param project path string true "Chat project ID" format(uuid)
|
|
// @Param request body codersdk.UpdateChatProjectACL true "Update chat project ACL request"
|
|
// @Success 204
|
|
// @Router /api/experimental/organizations/{organization}/chats/projects/{project}/acl [patch]
|
|
// @x-apidocgen {"skip": true}
|
|
func (api *API) patchChatProjectACL(rw http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
project := httpmw.ChatProjectParam(r)
|
|
apiKey := httpmw.APIKey(r)
|
|
|
|
aReq, commitAudit := audit.InitRequest[database.ChatProject](rw, &audit.RequestParams{
|
|
Audit: *api.Auditor.Load(),
|
|
Log: api.Logger,
|
|
Request: r,
|
|
Action: database.AuditActionWrite,
|
|
OrganizationID: project.OrganizationID,
|
|
})
|
|
defer commitAudit()
|
|
aReq.Old = project
|
|
|
|
if !api.Authorize(r, policy.ActionRead, project.RBACObject()) {
|
|
httpapi.ResourceNotFound(rw)
|
|
return
|
|
}
|
|
if !api.allowChatSharing(ctx, rw) {
|
|
return
|
|
}
|
|
if !api.Authorize(r, policy.ActionShare, project.RBACObject()) {
|
|
httpapi.Forbidden(rw)
|
|
return
|
|
}
|
|
|
|
var req codersdk.UpdateChatProjectACL
|
|
if !httpapi.Read(ctx, rw, r, &req) {
|
|
return
|
|
}
|
|
|
|
validErrs := acl.Validate(ctx, api.Database, ChatProjectACLUpdateValidator(req))
|
|
if len(validErrs) > 0 {
|
|
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
|
|
Message: "Invalid request to update chat project ACL.",
|
|
Validations: validErrs,
|
|
})
|
|
return
|
|
}
|
|
// RBAC matches ACL keys as strings, so only canonical UUIDs work.
|
|
userRoles, userKeyErrs := canonicalChatProjectRoles(req.UserRoles, "user_roles")
|
|
groupRoles, groupKeyErrs := canonicalChatProjectRoles(req.GroupRoles, "group_roles")
|
|
if len(userKeyErrs)+len(groupKeyErrs) > 0 {
|
|
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
|
|
Message: "Invalid request to update chat project ACL.",
|
|
Validations: slices.Concat(userKeyErrs, groupKeyErrs),
|
|
})
|
|
return
|
|
}
|
|
|
|
if _, ok := userRoles[project.OwnerID]; ok {
|
|
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
|
|
Message: "The project owner cannot be added to the project's sharing list.",
|
|
})
|
|
return
|
|
}
|
|
if _, ok := userRoles[apiKey.UserID]; ok {
|
|
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
|
|
Message: "Cannot change your own project sharing role.",
|
|
})
|
|
return
|
|
}
|
|
|
|
err := api.Database.InTx(func(tx database.Store) error {
|
|
// Lock granted users' memberships before the project row. A membership
|
|
// delete locks its row and then, through the 000629 trigger, the project
|
|
// row, so the reverse order could deadlock. Holding the membership lock
|
|
// also keeps a delete from missing the grant written below.
|
|
if userIDs := grantedChatProjectIDs(userRoles); len(userIDs) > 0 {
|
|
//nolint:gocritic // Validation below reports users that are not members.
|
|
_, err := tx.LockOrganizationMembersByUserIDsForShare(dbauthz.AsSystemRestricted(ctx), database.LockOrganizationMembersByUserIDsForShareParams{
|
|
OrganizationID: project.OrganizationID,
|
|
UserIds: userIDs,
|
|
})
|
|
if err != nil {
|
|
return xerrors.Errorf("lock organization members: %w", err)
|
|
}
|
|
}
|
|
current, err := tx.GetChatProjectByIDForUpdate(ctx, project.ID)
|
|
if err != nil {
|
|
return xerrors.Errorf("get chat project for update: %w", err)
|
|
}
|
|
aReq.Old = current
|
|
validErrs, err := validateChatProjectACLOrganization(ctx, tx, project, userRoles, groupRoles)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(validErrs) > 0 {
|
|
return &chatProjectACLValidationError{validations: validErrs}
|
|
}
|
|
userACL := applyChatProjectRoles(current.UserACL, userRoles)
|
|
groupACL := applyChatProjectRoles(current.GroupACL, groupRoles)
|
|
if err := tx.UpdateChatProjectACLByID(ctx, database.UpdateChatProjectACLByIDParams{
|
|
ID: project.ID,
|
|
UserACL: userACL,
|
|
GroupACL: groupACL,
|
|
}); err != nil {
|
|
return xerrors.Errorf("update chat project ACL: %w", err)
|
|
}
|
|
updated, err := tx.GetChatProjectByID(ctx, project.ID)
|
|
if err != nil {
|
|
return xerrors.Errorf("get updated chat project: %w", err)
|
|
}
|
|
aReq.New = updated
|
|
return nil
|
|
}, nil)
|
|
if err != nil {
|
|
if validationErr, ok := errors.AsType[*chatProjectACLValidationError](err); ok {
|
|
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
|
|
Message: "Invalid request to update chat project ACL.",
|
|
Validations: validationErr.validations,
|
|
})
|
|
return
|
|
}
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
httpapi.ResourceNotFound(rw)
|
|
return
|
|
}
|
|
if dbauthz.IsNotAuthorizedError(err) {
|
|
httpapi.Forbidden(rw)
|
|
return
|
|
}
|
|
httpapi.InternalServerError(rw, err)
|
|
return
|
|
}
|
|
|
|
rw.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
func canonicalChatProjectRoles(roles map[string]codersdk.ChatProjectRole, field string) (map[uuid.UUID]codersdk.ChatProjectRole, []codersdk.ValidationError) {
|
|
canonical := make(map[uuid.UUID]codersdk.ChatProjectRole, len(roles))
|
|
var validErrs []codersdk.ValidationError
|
|
for rawID, role := range roles {
|
|
id, err := uuid.Parse(rawID)
|
|
if err != nil {
|
|
validErrs = append(validErrs, codersdk.ValidationError{
|
|
Field: field,
|
|
Detail: fmt.Sprintf("%q is not a valid UUID", rawID),
|
|
})
|
|
continue
|
|
}
|
|
if _, ok := canonical[id]; ok {
|
|
validErrs = append(validErrs, codersdk.ValidationError{
|
|
Field: field,
|
|
Detail: fmt.Sprintf("ID %v is listed more than once under different spellings", id),
|
|
})
|
|
continue
|
|
}
|
|
canonical[id] = role
|
|
}
|
|
return canonical, validErrs
|
|
}
|
|
|
|
func applyChatProjectRoles(current database.ChatACL, roles map[uuid.UUID]codersdk.ChatProjectRole) database.ChatACL {
|
|
next := make(database.ChatACL, len(current)+len(roles))
|
|
for id, entry := range current {
|
|
next[id] = entry
|
|
}
|
|
for id, role := range roles {
|
|
if role == codersdk.ChatProjectRoleDeleted {
|
|
delete(next, id.String())
|
|
continue
|
|
}
|
|
next[id.String()] = database.ChatACLEntry{Permissions: db2sdk.ChatProjectRoleActions(role)}
|
|
}
|
|
return next
|
|
}
|
|
|
|
type chatProjectACLValidationError struct {
|
|
validations []codersdk.ValidationError
|
|
}
|
|
|
|
func (*chatProjectACLValidationError) Error() string {
|
|
return "invalid chat project ACL"
|
|
}
|
|
|
|
func validateChatProjectACLOrganization(
|
|
ctx context.Context,
|
|
db database.Store,
|
|
project database.ChatProject,
|
|
userRoles, groupRoles map[uuid.UUID]codersdk.ChatProjectRole,
|
|
) ([]codersdk.ValidationError, error) {
|
|
//nolint:gocritic // Validation needs every requested user and group, even ones the caller cannot read.
|
|
sysCtx := dbauthz.AsSystemRestricted(ctx)
|
|
var validErrs []codersdk.ValidationError
|
|
|
|
userIDs := grantedChatProjectIDs(userRoles)
|
|
if len(userIDs) > 0 {
|
|
memberships, err := db.GetOrganizationIDsByMemberIDs(sysCtx, userIDs)
|
|
if err != nil && !xerrors.Is(err, sql.ErrNoRows) {
|
|
return nil, xerrors.Errorf("get organization memberships: %w", err)
|
|
}
|
|
inOrg := make(map[uuid.UUID]bool, len(memberships))
|
|
for _, membership := range memberships {
|
|
inOrg[membership.UserID] = slices.Contains(membership.OrganizationIDs, project.OrganizationID)
|
|
}
|
|
for _, id := range userIDs {
|
|
if !inOrg[id] {
|
|
validErrs = append(validErrs, codersdk.ValidationError{
|
|
Field: "user_roles",
|
|
Detail: fmt.Sprintf("user with ID %v is not a member of the project's organization", id),
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
groupIDs := grantedChatProjectIDs(groupRoles)
|
|
if len(groupIDs) > 0 {
|
|
groups, err := db.GetGroups(sysCtx, database.GetGroupsParams{GroupIds: groupIDs})
|
|
if err != nil && !xerrors.Is(err, sql.ErrNoRows) {
|
|
return nil, xerrors.Errorf("get groups: %w", err)
|
|
}
|
|
for _, group := range groups {
|
|
if group.Group.OrganizationID != project.OrganizationID {
|
|
validErrs = append(validErrs, codersdk.ValidationError{
|
|
Field: "group_roles",
|
|
Detail: fmt.Sprintf("group with ID %v is not in the project's organization", group.Group.ID),
|
|
})
|
|
}
|
|
}
|
|
}
|
|
return validErrs, nil
|
|
}
|
|
|
|
func grantedChatProjectIDs(roles map[uuid.UUID]codersdk.ChatProjectRole) []uuid.UUID {
|
|
ids := make([]uuid.UUID, 0, len(roles))
|
|
for id, role := range roles {
|
|
if role != codersdk.ChatProjectRoleDeleted {
|
|
ids = append(ids, id)
|
|
}
|
|
}
|
|
return ids
|
|
}
|
|
|
|
func (api *API) chatProjectACLUsers(ctx context.Context, project database.ChatProject) ([]codersdk.ChatProjectUser, error) {
|
|
//nolint:gocritic // Project readers see who it is shared with without user read permission.
|
|
memberships, err := api.Database.GetOrganizationIDsByMemberIDs(dbauthz.AsSystemRestricted(ctx), parseACLIDs(project.UserACL))
|
|
if err != nil && !xerrors.Is(err, sql.ErrNoRows) {
|
|
return nil, xerrors.Errorf("get organization memberships: %w", err)
|
|
}
|
|
return resolveACLUsers(ctx, api.Database, chatProjectACLMembers(project, memberships), func(user codersdk.MinimalUser, entry database.ChatACLEntry) codersdk.ChatProjectUser {
|
|
return codersdk.ChatProjectUser{MinimalUser: user, Role: convertToChatProjectRole(entry.Permissions)}
|
|
})
|
|
}
|
|
|
|
// chatProjectACLMembers keeps the project's user entries for members of its
|
|
// organization. Entries for other users grant nothing, because access
|
|
// requires membership, so the ACL hides them. The 000629 trigger and the
|
|
// membership lock in patchChatProjectACL keep such entries from being
|
|
// written. memberships may cover users of other projects.
|
|
func chatProjectACLMembers(project database.ChatProject, memberships []database.GetOrganizationIDsByMemberIDsRow) database.ChatACL {
|
|
members := make(database.ChatACL, len(project.UserACL))
|
|
for _, membership := range memberships {
|
|
key := membership.UserID.String()
|
|
entry, ok := project.UserACL[key]
|
|
if ok && slices.Contains(membership.OrganizationIDs, project.OrganizationID) {
|
|
members[key] = entry
|
|
}
|
|
}
|
|
return members
|
|
}
|
|
|
|
// chatProjectSharingAvailable reports whether projects report the users and
|
|
// groups they are shared with. It matches the gate on the project ACL
|
|
// routes. Which projects are listed does not depend on it: grant keys
|
|
// select candidates and RBAC decides.
|
|
func (api *API) chatProjectSharingAvailable() bool {
|
|
return !api.chatSharingDisabled() && (buildinfo.IsDev() || api.Experiments.Enabled(codersdk.ExperimentChatProjectSharing))
|
|
}
|
|
|
|
// chatProjectShareCounts holds how many users and groups a project's ACL
|
|
// lists.
|
|
type chatProjectShareCounts struct {
|
|
users, groups int
|
|
everyone bool
|
|
}
|
|
|
|
// chatProjectsShareCounts counts the users and groups getChatProjectACL
|
|
// lists for each project, without the owner. Group members are not
|
|
// expanded, so this takes two queries for any number of projects. While
|
|
// chat sharing is unavailable, every project counts nothing.
|
|
func (api *API) chatProjectsShareCounts(ctx context.Context, projects []database.ChatProject) (map[uuid.UUID]chatProjectShareCounts, error) {
|
|
counts := make(map[uuid.UUID]chatProjectShareCounts, len(projects))
|
|
if !api.chatProjectSharingAvailable() {
|
|
return counts, nil
|
|
}
|
|
var userIDs, groupIDs []uuid.UUID
|
|
for _, project := range projects {
|
|
userIDs = append(userIDs, parseACLIDs(project.UserACL)...)
|
|
groupIDs = append(groupIDs, parseACLIDs(project.GroupACL)...)
|
|
}
|
|
//nolint:gocritic // Project readers see who it is shared with without user read permission.
|
|
sysCtx := dbauthz.AsSystemRestricted(ctx)
|
|
var memberships []database.GetOrganizationIDsByMemberIDsRow
|
|
if len(userIDs) > 0 {
|
|
var err error
|
|
memberships, err = api.Database.GetOrganizationIDsByMemberIDs(sysCtx, slice.Unique(userIDs))
|
|
if err != nil && !xerrors.Is(err, sql.ErrNoRows) {
|
|
return nil, xerrors.Errorf("get organization memberships: %w", err)
|
|
}
|
|
}
|
|
// As in resolveACLGroups, entries for groups that no longer exist are
|
|
// not listed.
|
|
groupExists := make(map[string]bool, len(groupIDs))
|
|
if len(groupIDs) > 0 {
|
|
groups, err := api.Database.GetGroups(sysCtx, database.GetGroupsParams{GroupIds: slice.Unique(groupIDs)})
|
|
if err != nil {
|
|
return nil, xerrors.Errorf("get ACL groups: %w", err)
|
|
}
|
|
for _, group := range groups {
|
|
groupExists[group.Group.ID.String()] = true
|
|
}
|
|
}
|
|
for _, project := range projects {
|
|
count := chatProjectShareCounts{users: len(chatProjectACLMembers(project, memberships))}
|
|
for key := range project.GroupACL {
|
|
if groupExists[key] {
|
|
count.groups++
|
|
}
|
|
}
|
|
// The Everyone group's ID is the organization ID.
|
|
everyone := project.OrganizationID.String()
|
|
_, shared := project.GroupACL[everyone]
|
|
count.everyone = shared && groupExists[everyone]
|
|
counts[project.ID] = count
|
|
}
|
|
return counts, nil
|
|
}
|
|
|
|
type ChatProjectACLUpdateValidator codersdk.UpdateChatProjectACL
|
|
|
|
var _ acl.UpdateValidator[codersdk.ChatProjectRole] = ChatProjectACLUpdateValidator{}
|
|
|
|
func (v ChatProjectACLUpdateValidator) Users() (map[string]codersdk.ChatProjectRole, string) {
|
|
return v.UserRoles, "user_roles"
|
|
}
|
|
|
|
func (v ChatProjectACLUpdateValidator) Groups() (map[string]codersdk.ChatProjectRole, string) {
|
|
return v.GroupRoles, "group_roles"
|
|
}
|
|
|
|
func (ChatProjectACLUpdateValidator) ValidateRole(role codersdk.ChatProjectRole) error {
|
|
switch role {
|
|
case codersdk.ChatProjectRoleDeleted, codersdk.ChatProjectRoleUse, codersdk.ChatProjectRoleAdmin:
|
|
return nil
|
|
}
|
|
return xerrors.Errorf("role %q is not a valid chat project role", role)
|
|
}
|
|
|
|
func convertToChatProjectRole(actions []policy.Action) codersdk.ChatProjectRole {
|
|
for _, role := range []codersdk.ChatProjectRole{codersdk.ChatProjectRoleAdmin, codersdk.ChatProjectRoleUse} {
|
|
if slice.SameElements(actions, db2sdk.ChatProjectRoleActions(role)) {
|
|
return role
|
|
}
|
|
}
|
|
return codersdk.ChatProjectRoleDeleted
|
|
}
|