Files
coder/coderd/rbac/acl/updatevalidator.go
Garrett Delfosse 6ebefb8325 feat: add chat project sharing API (#30439)
API for chat project sharing (experiment `chat-projects`). Builds on
#30479 (merged).

Owners share a project with users, groups, or the whole organization
(the Everyone group, ID = organization ID). Chats in a shared project
stay private.

| Role    | Project and instructions | Memories   | ACL  | Delete |
|---------|--------------------------|------------|------|--------|
| `use`   | read                     | read/write | read | no     |
| `admin` | read/write               | read/write | edit | no     |

Only the owner, and administrators whose role grants delete, can delete
a project.

- **API:** `GET`/`PATCH .../chats/projects/{project}/acl`, same shapes
as `/chats/{chat}/acl`, plus SDK methods. Project responses include the
caller's `permissions` (`update`, `delete`, `share`); the UI hides edit
and delete accordingly.
- **Listing:** `GET /chats/projects` returns owned and shared projects.
Removes `GetChatProjectsByOwnerID`.
- **Chat access:** creating a chat in a project, and loading its memory
and instructions on each turn, requires the chat owner to own the
project or have an ACL grant (`chatd.ChatProjectUsableBy`). Role grants
don't count. If the grant is removed, existing chats lose memory and
instructions on their next turn.
- **Validation:** users and groups must be in the project's
organization; keys must be canonical UUIDs; callers can't change their
own role; the owner can't be added. Migration `000624` drops a user's
grants when they leave the organization, so rejoining doesn't restore
access.
- **Instructions:** readers who can't edit get 403 instead of 404, and
the UI hides editing.
- **Agent prompt:** memories are visible to and editable by sharees, so
the agent is told not to save secrets or personal details.

Known gap: project deletion still detaches chats, and a sharee's open
sidebar keeps showing them until reload. #30683 replaces this.

Not included: share notifications, `/acl/available`, sharing UI.

<details>
<summary>Decision log</summary>

- `use` grants memory read/write over HTTP, because agents in a sharee's
chats can already write memories. Making the agent read-only for sharees
was the alternative (@f0ssel chose sharees changing memories through
use).
- An administrator with `share` can grant themselves access and then use
the project. Accepted to keep access control simple (@f0ssel).
</details>

> Generated by Coder Agents.
2026-10-19 11:32:26 +00:00

136 lines
4.2 KiB
Go

package acl
import (
"context"
"fmt"
"github.com/google/uuid"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
"github.com/coder/coder/v2/codersdk"
)
// Role is the set of ACL role types Validate accepts.
type Role interface {
codersdk.WorkspaceRole | codersdk.TemplateRole | codersdk.ChatRole | codersdk.ChatProjectRole | codersdk.MCPServerConfigRole | codersdk.OrganizationSkillRole
}
type UpdateValidator[R Role] interface {
// Users should return a map from user UUIDs (as strings) to the role they
// are being assigned. Additionally, it should return a string that will be
// used as the field name for the ValidationErrors returned from Validate.
Users() (map[string]R, string)
// Groups should return a map from group UUIDs (as strings) to the role they
// are being assigned. Additionally, it should return a string that will be
// used as the field name for the ValidationErrors returned from Validate.
Groups() (map[string]R, string)
// ValidateRole should return an error that will be used in the
// ValidationError if the role is invalid for the corresponding resource type.
ValidateRole(role R) error
}
func Validate[R Role](
ctx context.Context,
db database.Store,
v UpdateValidator[R],
) []codersdk.ValidationError {
// nolint:gocritic // Validate requires full read access to users and groups
ctx = dbauthz.AsSystemRestricted(ctx)
var validErrs []codersdk.ValidationError
groupRoles, groupsField := v.Groups()
groupIDs := make([]uuid.UUID, 0, len(groupRoles))
for idStr, role := range groupRoles {
// Validate the provided role names
if err := v.ValidateRole(role); err != nil {
validErrs = append(validErrs, codersdk.ValidationError{
Field: groupsField,
Detail: err.Error(),
})
}
// Validate that the IDs are UUIDs
id, err := uuid.Parse(idStr)
if err != nil {
validErrs = append(validErrs, codersdk.ValidationError{
Field: groupsField,
Detail: fmt.Sprintf("%v is not a valid UUID.", idStr),
})
continue
}
// Don't check if the ID exists when setting the role to
// WorkspaceRoleDeleted or TemplateRoleDeleted. They might've existing at
// some point and got deleted. If we report that as an error here then they
// can't be removed.
if string(role) == "" {
continue
}
groupIDs = append(groupIDs, id)
}
// Validate that the groups exist
groupValidation, err := db.ValidateGroupIDs(ctx, groupIDs)
if err != nil {
validErrs = append(validErrs, codersdk.ValidationError{
Field: groupsField,
Detail: fmt.Sprintf("failed to validate group IDs: %v", err.Error()),
})
}
if !groupValidation.Ok {
for _, id := range groupValidation.InvalidGroupIds {
validErrs = append(validErrs, codersdk.ValidationError{
Field: groupsField,
Detail: fmt.Sprintf("group with ID %v does not exist", id),
})
}
}
userRoles, usersField := v.Users()
userIDs := make([]uuid.UUID, 0, len(userRoles))
for idStr, role := range userRoles {
// Validate the provided role names
if err := v.ValidateRole(role); err != nil {
validErrs = append(validErrs, codersdk.ValidationError{
Field: usersField,
Detail: err.Error(),
})
}
// Validate that the IDs are UUIDs
id, err := uuid.Parse(idStr)
if err != nil {
validErrs = append(validErrs, codersdk.ValidationError{
Field: usersField,
Detail: fmt.Sprintf("%v is not a valid UUID.", idStr),
})
continue
}
// Don't check if the ID exists when setting the role to
// WorkspaceRoleDeleted or TemplateRoleDeleted. They might've existing at
// some point and got deleted. If we report that as an error here then they
// can't be removed.
if string(role) == "" {
continue
}
userIDs = append(userIDs, id)
}
// Validate that the groups exist
userValidation, err := db.ValidateUserIDs(ctx, userIDs)
if err != nil {
validErrs = append(validErrs, codersdk.ValidationError{
Field: usersField,
Detail: fmt.Sprintf("failed to validate user IDs: %v", err.Error()),
})
}
if !userValidation.Ok {
for _, id := range userValidation.InvalidUserIds {
validErrs = append(validErrs, codersdk.ValidationError{
Field: usersField,
Detail: fmt.Sprintf("user with ID %v does not exist", id),
})
}
}
return validErrs
}