Thanks to visit codestin.com
Credit goes to github.com

Skip to content

chore: include custom roles in list org roles #13336

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
May 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cli/organization.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ func (r *RootCmd) organizations() *serpent.Command {
r.currentOrganization(),
r.switchOrganization(),
r.createOrganization(),
r.organizationRoles(),
},
}

Expand Down
18 changes: 10 additions & 8 deletions enterprise/cli/rolescmd.go → cli/organizationroles.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,23 @@ import (
"github.com/coder/serpent"
)

// **NOTE** Only covers site wide roles at present. Org scoped roles maybe
// should be nested under some command that scopes to an org??

func (r *RootCmd) roles() *serpent.Command {
func (r *RootCmd) organizationRoles() *serpent.Command {
cmd := &serpent.Command{
Use: "roles",
Short: "Manage site-wide roles.",
Short: "Manage organization roles.",
Aliases: []string{"role"},
Handler: func(inv *serpent.Invocation) error {
return inv.Command.HelpHandler(inv)
},
Hidden: true,
Children: []*serpent.Command{
r.showRole(),
r.showOrganizationRoles(),
},
}
return cmd
}

func (r *RootCmd) showRole() *serpent.Command {
func (r *RootCmd) showOrganizationRoles() *serpent.Command {
formatter := cliui.NewOutputFormatter(
cliui.ChangeFormatterData(
cliui.TableFormat([]assignableRolesTableRow{}, []string{"name", "display_name", "built_in", "site_permissions", "org_permissions", "user_permissions"}),
Expand Down Expand Up @@ -67,7 +64,12 @@ func (r *RootCmd) showRole() *serpent.Command {
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
roles, err := client.ListSiteRoles(ctx)
org, err := CurrentOrganization(r, inv, client)
if err != nil {
return err
}

roles, err := client.ListOrganizationRoles(ctx, org.ID)
if err != nil {
return xerrors.Errorf("listing roles: %w", err)
}
Expand Down
51 changes: 51 additions & 0 deletions cli/organizationroles_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package cli_test

import (
"bytes"
"testing"

"github.com/google/uuid"
"github.com/stretchr/testify/require"

"github.com/coder/coder/v2/cli/clitest"
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbgen"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/testutil"
)

func TestShowOrganizationRoles(t *testing.T) {
t.Parallel()

t.Run("OK", func(t *testing.T) {
t.Parallel()

ownerClient, db := coderdtest.NewWithDatabase(t, &coderdtest.Options{})
owner := coderdtest.CreateFirstUser(t, ownerClient)
client, _ := coderdtest.CreateAnotherUser(t, ownerClient, owner.OrganizationID, rbac.RoleUserAdmin())

const expectedRole = "test-role"
dbgen.CustomRole(t, db, database.CustomRole{
Name: expectedRole,
DisplayName: "Expected",
SitePermissions: nil,
OrgPermissions: nil,
UserPermissions: nil,
OrganizationID: uuid.NullUUID{
UUID: owner.OrganizationID,
Valid: true,
},
})
Comment on lines +28 to +39
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

API to make custom org roles does not exist yet. I'll circle back to this when I get org role editing in.

It's a chicken and the egg problem


ctx := testutil.Context(t, testutil.WaitMedium)
inv, root := clitest.New(t, "organization", "roles", "show")
clitest.SetupConfig(t, client, root)

buf := new(bytes.Buffer)
inv.Stdout = buf
err := inv.WithContext(ctx).Run()
require.NoError(t, err)
require.Contains(t, buf.String(), expectedRole)
})
}
8 changes: 8 additions & 0 deletions coderd/apidoc/docs.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions coderd/apidoc/swagger.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 8 additions & 3 deletions coderd/database/db2sdk/db2sdk.go
Original file line number Diff line number Diff line change
Expand Up @@ -527,12 +527,17 @@ func ProvisionerDaemon(dbDaemon database.ProvisionerDaemon) codersdk.Provisioner
}

func Role(role rbac.Role) codersdk.Role {
roleName, orgIDStr, err := rbac.RoleSplit(role.Name)
if err != nil {
roleName = role.Name
}
return codersdk.Role{
Name: role.Name,
Name: roleName,
OrganizationID: orgIDStr,
DisplayName: role.DisplayName,
SitePermissions: List(role.Site, Permission),
OrganizationPermissions: Map(role.Org, ListLazy(Permission)),
UserPermissions: List(role.Site, Permission),
UserPermissions: List(role.User, Permission),
}
}

Expand All @@ -546,7 +551,7 @@ func Permission(permission rbac.Permission) codersdk.Permission {

func RoleToRBAC(role codersdk.Role) rbac.Role {
return rbac.Role{
Name: role.Name,
Name: rbac.RoleName(role.Name, role.OrganizationID),
DisplayName: role.DisplayName,
Site: List(role.SitePermissions, PermissionToRBAC),
Org: Map(role.OrganizationPermissions, ListLazy(PermissionToRBAC)),
Expand Down
14 changes: 14 additions & 0 deletions coderd/database/dbgen/dbgen.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"encoding/json"
"fmt"
"net"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -817,6 +818,19 @@ func OAuth2ProviderAppToken(t testing.TB, db database.Store, seed database.OAuth
return token
}

func CustomRole(t testing.TB, db database.Store, seed database.CustomRole) database.CustomRole {
role, err := db.UpsertCustomRole(genCtx, database.UpsertCustomRoleParams{
Name: takeFirst(seed.Name, strings.ToLower(namesgenerator.GetRandomName(1))),
DisplayName: namesgenerator.GetRandomName(1),
OrganizationID: seed.OrganizationID,
SitePermissions: takeFirstSlice(seed.SitePermissions, []byte("[]")),
OrgPermissions: takeFirstSlice(seed.SitePermissions, []byte("{}")),
UserPermissions: takeFirstSlice(seed.SitePermissions, []byte("[]")),
})
require.NoError(t, err, "insert custom role")
return role
}

func must[V any](v V, err error) V {
if err != nil {
panic(err)
Expand Down
12 changes: 11 additions & 1 deletion coderd/database/dbmem/dbmem.go
Original file line number Diff line number Diff line change
Expand Up @@ -1187,7 +1187,11 @@ func (q *FakeQuerier) CustomRoles(_ context.Context, arg database.CustomRolesPar
role := role
if len(arg.LookupRoles) > 0 {
if !slices.ContainsFunc(arg.LookupRoles, func(s string) bool {
return strings.EqualFold(s, role.Name)
roleName := rbac.RoleName(role.Name, "")
if role.OrganizationID.UUID != uuid.Nil {
roleName = rbac.RoleName(role.Name, role.OrganizationID.UUID.String())
}
return strings.EqualFold(s, roleName)
}) {
continue
}
Expand All @@ -1197,6 +1201,10 @@ func (q *FakeQuerier) CustomRoles(_ context.Context, arg database.CustomRolesPar
continue
}

if arg.OrganizationID != uuid.Nil && role.OrganizationID.UUID != arg.OrganizationID {
continue
}

found = append(found, role)
}

Expand Down Expand Up @@ -8377,6 +8385,7 @@ func (q *FakeQuerier) UpsertCustomRole(_ context.Context, arg database.UpsertCus
for i := range q.customRoles {
if strings.EqualFold(q.customRoles[i].Name, arg.Name) {
q.customRoles[i].DisplayName = arg.DisplayName
q.customRoles[i].OrganizationID = arg.OrganizationID
q.customRoles[i].SitePermissions = arg.SitePermissions
q.customRoles[i].OrgPermissions = arg.OrgPermissions
q.customRoles[i].UserPermissions = arg.UserPermissions
Expand All @@ -8388,6 +8397,7 @@ func (q *FakeQuerier) UpsertCustomRole(_ context.Context, arg database.UpsertCus
role := database.CustomRole{
Name: arg.Name,
DisplayName: arg.DisplayName,
OrganizationID: arg.OrganizationID,
SitePermissions: arg.SitePermissions,
OrgPermissions: arg.OrgPermissions,
UserPermissions: arg.UserPermissions,
Expand Down
30 changes: 21 additions & 9 deletions coderd/database/queries.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 12 additions & 3 deletions coderd/database/queries/roles.sql
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,32 @@ FROM
custom_roles
WHERE
true
-- Lookup roles filter
-- Lookup roles filter expects the role names to be in the rbac package
-- format. Eg: name[:<organization_id>]
AND CASE WHEN array_length(@lookup_roles :: text[], 1) > 0 THEN
-- Case insensitive
name ILIKE ANY(@lookup_roles :: text [])
-- Case insensitive lookup with org_id appended (if non-null).
-- This will return just the name if org_id is null. It'll append
-- the org_id if not null
concat(name, NULLIF(concat(':', organization_id), ':')) ILIKE ANY(@lookup_roles :: text [])
Comment on lines +11 to +14
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This logic is not ideal, but it removes a good chunk of logic in the APIKey middlewhere, which is where this argument is exclusively used atm.

I would prefer to do some tuple lookup, where the parameter is something like:

type RoleLookup struct {
  Name string
  OrganizationID string
}

type LookUp []RoleLookup

I am unsure if sqlc can support this. So this is what it will look like for now.

ELSE true
END
-- Org scoping filter, to only fetch site wide roles
AND CASE WHEN @exclude_org_roles :: boolean THEN
organization_id IS null
ELSE true
END
AND CASE WHEN @organization_id :: uuid != '00000000-0000-0000-0000-000000000000'::uuid THEN
organization_id = @organization_id
ELSE true
END
;

-- name: UpsertCustomRole :one
INSERT INTO
custom_roles (
name,
display_name,
organization_id,
site_permissions,
org_permissions,
user_permissions,
Expand All @@ -33,6 +41,7 @@ VALUES (
-- Always force lowercase names
lower(@name),
@display_name,
@organization_id,
@site_permissions,
@org_permissions,
@user_permissions,
Expand Down
Loading
Loading