Skip to content

Custom roles: return every ungrantable permission as validations, and render them in the role editor #32279

Open

Description

@coder-superblink

Follow-up to #32263. That issue is about the role editor offering permissions nobody can grant. This one covers what happens when the API rejects permissions: the API should report every invalid permission at once, and the role editor needs to render that response properly. Today it can't.

Background

When a custom role contains permissions the caller can't grant, customRoleCheck returns on the first failure, and postOrgRoles/putOrgRoles send the raw wrapped Go error back as detail:

{"message":"Failed to update role permissions","detail":"org=\"<org-uuid>\": org: invalid permission for action=\"application_connect\" type=\"workspace_dormant\", not allowed to grant this permission"}

So the user fixes one permission per save. The UI also shows the same message twice: once in the form's ErrorAlert and once in a toast (see the screenshots on #32263).

Proposal: accumulate and return validations

customRoleCheck isn't on a hot path. It only runs on custom role inserts and updates (admin API calls, plus system-role reconciliation, which returns before the escalation loop). There's also prior art for collecting errors and returning them as codersdk.Response.Validations:

Suggested backend shape:

  • customRoleCheck collects every escalation failure, across the site, org, member and user loops, into a typed error such as *dbauthz.InvalidRolePermissionsError{Permissions []rbac.Permission}. dbauthz doesn't import codersdk, so the HTTP mapping belongs in the handler.
  • postOrgRoles/putOrgRoles use errors.As and respond 400 with a human-readable message and one ValidationError per permission. Give each permission a unique field, e.g. organization_permissions.workspace_dormant:ssh.
  • Keep filling detail with a joined summary for clients that only read detail. Keep the raw wrapped error in server logs only. No org UUIDs in user-facing text.

I tried a rough version of this locally (diff below). The response then looks like this:

{
  "message": "This role includes permissions you can't grant.",
  "validations": [
    {"field": "organization_permissions.workspace_dormant:application_connect", "detail": "You can't grant workspace_dormant:application_connect because you don't have that permission."},
    {"field": "organization_permissions.workspace_dormant:share", "detail": "You can't grant workspace_dormant:share because you don't have that permission."},
    {"field": "organization_permissions.workspace_dormant:ssh", "detail": "You can't grant workspace_dormant:ssh because you don't have that permission."},
    {"field": "organization_permissions.workspace_dormant:start", "detail": "You can't grant workspace_dormant:start because you don't have that permission."}
  ]
}

Frontend problem: the role editor can't render this response

With the backend change above, I reproduced the frontend behavior on main @ b4f8b6756c6a7ddddeab1664b51dea1237740a6e:

  1. The in-form error disappears. CreateEditRolePageView.tsx#L115 only renders ErrorAlert when !isApiValidationError(error). It expects field helpers to show validation errors instead, but getFormHelpers is only wired to name and display_name. Nothing in the permissions table reads validations, so the form shows no error at all, and the selected checkboxes look valid.
  2. The only signal is a toast with a run-on paragraph. The toast description comes from getErrorDetail → getValidationErrorMessage, which joins the details with \n. The toast doesn't preserve the newlines, so the four errors run together.
  3. Shared field names would collapse. mapApiErrorToFieldErrors does result[error.field] = detail, so when several entries share a field, only the last one survives. That's why the backend needs one unique field per permission. acl.Validate already returns several entries under a single field (one for users, one for groups), so it's worth checking whether any ACL UI relies on this mapping.

Suggested frontend changes

  • Render permission-level validations in the permissions table: mark each offending checkbox and show its detail inline. Also show a short summary alert at the top of the form (e.g. "4 permissions can't be granted") so the error is visible without scrolling.
  • Drop the error case from the toast.promise in CreateEditRolePage.tsx#L82 so errors appear once, in the form. Keep its loading and success messages.
  • If a toast or alert still lists several validations, render them as a list instead of joining them with \n.

Compatibility

This is an additive change, not a breaking one:

  • Same endpoints, same 400 status, same codersdk.Response type. validations is already an optional field in the response schema.
  • The Go SDK's codersdk.Error.Error() already prints every validation, so coder organization roles create/edit users get the full list without changes.
  • message and detail are human-readable strings, not a contract. Keeping a detail summary helps clients that do string matching. In-repo tests that match "not allowed to grant this permission" (dbauthz/customroles_test.go) need updating if that text changes.
  • The site ships inside the same binary, so there's no frontend/backend version skew. The frontend changes above must land in the same PR, or the role editor gets worse (problem 1).

Rough backend diff used for the repro

Repro only, not production-ready: it only covers the org loop, and the error type and messages are placeholders.

diff
diff --git a/coderd/database/dbauthz/dbauthz.go b/coderd/database/dbauthz/dbauthz.go
index 0812156967..68ebefb3aa 100644
--- a/coderd/database/dbauthz/dbauthz.go
+++ b/coderd/database/dbauthz/dbauthz.go
@@ -1717,12 +1717,17 @@ func (q *querier) customRoleCheck(ctx context.Context, role database.CustomRole,
 	}
 
 	for orgID, perms := range rbacRole.ByOrgID {
+		// REPRO-ONLY: accumulate escalation failures instead of returning the first.
+		var invalid []rbac.Permission
 		for _, orgPerm := range perms.Org {
 			err := q.customRoleEscalationCheck(ctx, act, orgPerm, rbac.Object{OrgID: orgID, Type: orgPerm.ResourceType})
 			if err != nil {
-				return xerrors.Errorf("org=%q: org: %w", orgID, err)
+				invalid = append(invalid, orgPerm)
 			}
 		}
+		if len(invalid) > 0 {
+			return &InvalidRolePermissionsError{Permissions: invalid}
+		}
 		for _, memberPerm := range perms.Member {
 			// The person giving the permission should still be required to have
 			// the permissions throughout the org in order to give individuals the
@@ -10098,3 +10103,12 @@ func (q *querier) GetAuthorizedMCPServerConfigs(ctx context.Context, organizatio
 func (q *querier) GetAuthorizedOrganizationSkillMetadata(ctx context.Context, organizationID uuid.UUID, prepared rbac.PreparedAuthorized) ([]database.ListOrganizationSkillMetadataByOrganizationIDRow, error) {
 	return q.db.GetAuthorizedOrganizationSkillMetadata(ctx, organizationID, prepared)
 }
+
+// InvalidRolePermissionsError is REPRO-ONLY: lists every permission the caller cannot grant.
+type InvalidRolePermissionsError struct {
+	Permissions []rbac.Permission
+}
+
+func (e *InvalidRolePermissionsError) Error() string {
+	return xerrors.Errorf("%d permission(s) cannot be granted", len(e.Permissions)).Error()
+}
diff --git a/enterprise/coderd/roles.go b/enterprise/coderd/roles.go
index d33b4dd489..7fa44ec336 100644
--- a/enterprise/coderd/roles.go
+++ b/enterprise/coderd/roles.go
@@ -2,6 +2,7 @@ package coderd
 
 import (
 	"context"
+	"errors"
 	"fmt"
 	"net/http"
 	"strings"
@@ -12,6 +13,7 @@ import (
 	"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"
@@ -76,6 +78,21 @@ func (api *API) postOrgRoles(rw http.ResponseWriter, r *http.Request) {
 		return
 	}
 	if err != nil {
+		var invalidPerms *dbauthz.InvalidRolePermissionsError
+		if errors.As(err, &invalidPerms) {
+			validations := make([]codersdk.ValidationError, 0, len(invalidPerms.Permissions))
+			for _, p := range invalidPerms.Permissions {
+				validations = append(validations, codersdk.ValidationError{
+					Field:  fmt.Sprintf("organization_permissions.%s:%s", p.ResourceType, p.Action),
+					Detail: fmt.Sprintf("You can't grant %s:%s because you don't have that permission.", p.ResourceType, p.Action),
+				})
+			}
+			httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
+				Message:     "This role includes permissions you can't grant.",
+				Validations: validations,
+			})
+			return
+		}
 		httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
 			Message: "Failed to update role permissions",
 			Detail:  err.Error(),
@@ -167,6 +184,21 @@ func (api *API) putOrgRoles(rw http.ResponseWriter, r *http.Request) {
 		return
 	}
 	if err != nil {
+		var invalidPerms *dbauthz.InvalidRolePermissionsError
+		if errors.As(err, &invalidPerms) {
+			validations := make([]codersdk.ValidationError, 0, len(invalidPerms.Permissions))
+			for _, p := range invalidPerms.Permissions {
+				validations = append(validations, codersdk.ValidationError{
+					Field:  fmt.Sprintf("organization_permissions.%s:%s", p.ResourceType, p.Action),
+					Detail: fmt.Sprintf("You can't grant %s:%s because you don't have that permission.", p.ResourceType, p.Action),
+				})
+			}
+			httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
+				Message:     "This role includes permissions you can't grant.",
+				Validations: validations,
+			})
+			return
+		}
 		httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
 			Message: "Failed to update role permissions",
 			Detail:  err.Error(),

Created on behalf of @angrycub

Activity

  1. linear-code commented on Nov 16, 2026

    @linear-code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions