mirror of
https://github.com/coder/coder.git
synced 2026-11-01 04:47:17 +08:00
`default_org_member_roles` was only settable through Terraform or a raw
`PATCH /api/v2/organizations/{organization}`. This adds a CLI
equivalent.
```console
coder organizations edit --org acme --default-org-member-roles organization-workspace-access,organization-template-admin
coder organizations edit --org acme --default-org-member-roles "" # grant no roles
```
- The flag replaces the organization's current list rather than adding
to it. It accepts a comma-separated list, may be repeated, and
de-duplicates. An empty value removes every role.
- Removing a role prompts for confirmation, listing the roles being
removed, unless `-y` is passed. Adding roles applies without a prompt.
- The resulting set is printed, so no follow-up command is needed to
confirm what was applied.
- The organization is chosen with `-O/--org` or `$CODER_ORGANIZATION`,
and is implicit when the caller belongs to exactly one organization.
The org update endpoint is behind `FeatureMultipleOrganizations`, so the
command is enterprise/premium only. Non-built-in roles are rejected by
the server, and `dbauthz` already prevents a caller from setting a
default they could not assign to a member individually.
<details>
<summary>Implementation notes</summary>
## Shape
`codersdk.UpdateOrganizationRequest.DefaultOrgMemberRoles *[]string` and
the enterprise `patchOrganization` handler already existed; only the CLI
was missing, and nothing in `cli/` called `UpdateOrganization` at all.
No server or SDK changes are needed.
`organizations edit` follows the partial-update pattern of `coder groups
edit`: check `ParsedFlags().Changed(...)`, populate only the fields the
user set, and leave the rest nil so the handler preserves them. Passing
no flags is an error.
Two earlier shapes were tried and dropped:
- **A `default-org-member-roles` entry in the `organizations settings`
registry.** Every sibling entry unmarshals an SDK type that maps 1:1 to
a dedicated endpoint; this field has no such endpoint. Reusing
`UpdateOrganizationRequest` for the piped JSON meant a stray `name`
field could rename the org, and the documented `show > file`, edit, `set
< file` workflow failed on the default organization, whose name is
reserved.
- **A `--default-org-member-roles` flag on `organizations create`.**
`create` cannot set display name, description, or icon either, so a
roles-only flag there is asymmetric. It would also require
`CreateOrganizationRequest` to grow the field plus server-side
validation.
## Known sharp edge
`serpent.StringArray` resets its slice when any flag value is empty, so
`--default-org-member-roles a --default-org-member-roles ""` clears the
list rather than keeping `a`. This is pinned by a test and called out in
a code comment. The confirmation prompt catches it interactively; a
script passing `-y` would not. A custom flag value that ignores empty
occurrences was prototyped and reverted as more machinery than the
behavior warranted.
## Validation
Manually verified against a local dev deployment with a premium license:
setting, adding, clearing, prompt accepted and declined, duplicate and
whitespace handling, invalid role rejection, and a plain member being
denied. Confirmed with `/authcheck` that a member loses workspace-create
access when the roles are cleared and regains it when restored, and that
the change is recorded in the audit log.
## Follow-ups worth considering
- `--name`, `--display-name`, `--description`, and `--icon` on
`organizations edit`; all already exist on `UpdateOrganizationRequest`.
Rename deserves its own discussion.
- Setting the defaults to `organization-admin` makes every member an org
admin, including the ability to edit the org further, and those users
still render as plain members in member listings. Reachable today via
the API, UI, and Terraform; a warning on privileged roles would help.
- `dbauthz.InsertOrganization` has no `canAssignRoles` check, unlike
`UpdateOrganization`. Harmless while the only caller passes the
deployment default constant.
- `docs/admin/users/organizations.md` still points users at the
dashboard or a raw `PATCH`.
</details>
---
Created by Coder Agents on behalf of @jscottmiller.
177 lines
5.1 KiB
Go
177 lines
5.1 KiB
Go
package cli
|
|
|
|
import (
|
|
"fmt"
|
|
"slices"
|
|
"strings"
|
|
|
|
"github.com/google/uuid"
|
|
"golang.org/x/xerrors"
|
|
|
|
"github.com/coder/coder/v2/cli/cliui"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
"github.com/coder/pretty"
|
|
"github.com/coder/serpent"
|
|
)
|
|
|
|
func (r *RootCmd) createOrganization() *serpent.Command {
|
|
cmd := &serpent.Command{
|
|
Use: "create <organization name>",
|
|
Short: "Create a new organization.",
|
|
Middleware: serpent.Chain(
|
|
serpent.RequireNArgs(1),
|
|
),
|
|
Options: serpent.OptionSet{
|
|
cliui.SkipPromptOption(),
|
|
},
|
|
Handler: func(inv *serpent.Invocation) error {
|
|
client, err := r.InitClient(inv)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
orgName := inv.Args[0]
|
|
|
|
err = codersdk.NameValid(orgName)
|
|
if err != nil {
|
|
return xerrors.Errorf("organization name %q is invalid: %w", orgName, err)
|
|
}
|
|
|
|
// This check is not perfect since not all users can read all organizations.
|
|
// So ignore the error and if the org already exists, prevent the user
|
|
// from creating it.
|
|
existing, _ := client.OrganizationByName(inv.Context(), orgName)
|
|
if existing.ID != uuid.Nil {
|
|
return xerrors.Errorf("organization %q already exists", orgName)
|
|
}
|
|
|
|
organization, err := client.CreateOrganization(inv.Context(), codersdk.CreateOrganizationRequest{
|
|
Name: orgName,
|
|
})
|
|
if err != nil {
|
|
return xerrors.Errorf("failed to create organization: %w", err)
|
|
}
|
|
|
|
_, _ = fmt.Fprintf(inv.Stdout, "Organization %s (%s) created.\n", organization.Name, organization.ID)
|
|
return nil
|
|
},
|
|
}
|
|
|
|
return cmd
|
|
}
|
|
|
|
const defaultOrgMemberRolesFlag = "default-org-member-roles"
|
|
|
|
func (r *RootCmd) editOrganization(orgContext *OrganizationContext) *serpent.Command {
|
|
var defaultOrgMemberRoles []string
|
|
cmd := &serpent.Command{
|
|
Use: "edit",
|
|
Short: "Edit organization settings.",
|
|
Long: FormatExamples(
|
|
Example{
|
|
Description: "Replace the roles every member of the organization holds",
|
|
Command: "coder organizations edit --default-org-member-roles organization-workspace-access,organization-template-admin",
|
|
},
|
|
Example{
|
|
Description: "Grant members no roles at all",
|
|
Command: `coder organizations edit --default-org-member-roles ""`,
|
|
},
|
|
),
|
|
Middleware: serpent.Chain(
|
|
serpent.RequireNArgs(0),
|
|
),
|
|
Options: serpent.OptionSet{
|
|
{
|
|
Name: defaultOrgMemberRolesFlag,
|
|
Flag: defaultOrgMemberRolesFlag,
|
|
Description: "Replaces the roles every member of the organization holds. " +
|
|
"Accepts a comma-separated list and may be repeated. " +
|
|
"An empty value removes every role. " +
|
|
"New organizations start with organization-workspace-access, which grants members access to their own workspaces.",
|
|
Value: serpent.StringArrayOf(&defaultOrgMemberRoles),
|
|
},
|
|
cliui.SkipPromptOption(),
|
|
},
|
|
Handler: func(inv *serpent.Invocation) error {
|
|
if !inv.ParsedFlags().Changed(defaultOrgMemberRolesFlag) {
|
|
return xerrors.Errorf("no changes requested; pass --%s", defaultOrgMemberRolesFlag)
|
|
}
|
|
|
|
roles, err := parseDefaultOrgMemberRoles(defaultOrgMemberRoles)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
client, err := r.InitClient(inv)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
org, err := orgContext.Selected(inv, client)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
removed := make([]string, 0, len(org.DefaultOrgMemberRoles))
|
|
for _, role := range org.DefaultOrgMemberRoles {
|
|
if !slices.Contains(roles, role) {
|
|
removed = append(removed, role)
|
|
}
|
|
}
|
|
if len(removed) > 0 {
|
|
_, err = cliui.Prompt(inv, cliui.PromptOptions{
|
|
Text: fmt.Sprintf("Remove %s from every member of %s?",
|
|
pretty.Sprint(cliui.DefaultStyles.Code, strings.Join(removed, ", ")),
|
|
pretty.Sprint(cliui.DefaultStyles.Code, org.Name)),
|
|
IsConfirm: true,
|
|
Default: cliui.ConfirmNo,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
organization, err := client.UpdateOrganization(inv.Context(), org.ID.String(), codersdk.UpdateOrganizationRequest{
|
|
DefaultOrgMemberRoles: &roles,
|
|
})
|
|
if err != nil {
|
|
return xerrors.Errorf("failed to update organization: %w", err)
|
|
}
|
|
|
|
_, _ = fmt.Fprintf(inv.Stdout, "Organization %s (%s) updated.\nDefault member roles: %s\n",
|
|
organization.Name, organization.ID, formatOrgMemberRoles(organization.DefaultOrgMemberRoles))
|
|
return nil
|
|
},
|
|
}
|
|
orgContext.AttachOptions(cmd)
|
|
|
|
return cmd
|
|
}
|
|
|
|
// parseDefaultOrgMemberRoles trims and de-duplicates the flag values,
|
|
// preserving the order they were given in. An empty set of values means
|
|
// "no roles": serpent resets the slice to nil when any flag value is
|
|
// empty, so `--flag a --flag ""` also lands here. The returned slice is
|
|
// always allocated so the request carries [] rather than null, which the
|
|
// server reads as "unspecified".
|
|
func parseDefaultOrgMemberRoles(values []string) ([]string, error) {
|
|
roles := make([]string, 0, len(values))
|
|
for _, role := range values {
|
|
role = strings.TrimSpace(role)
|
|
if role == "" {
|
|
return nil, xerrors.Errorf("--%s contains an empty role name", defaultOrgMemberRolesFlag)
|
|
}
|
|
if !slices.Contains(roles, role) {
|
|
roles = append(roles, role)
|
|
}
|
|
}
|
|
return roles, nil
|
|
}
|
|
|
|
func formatOrgMemberRoles(roles []string) string {
|
|
if len(roles) == 0 {
|
|
return "(none)"
|
|
}
|
|
return strings.Join(roles, ", ")
|
|
}
|