2022-04-29 09:04:19 -05:00
package coderd
import (
2024-06-12 10:07:12 -10:00
"context"
2024-08-30 11:19:36 -05:00
"fmt"
2022-04-29 09:04:19 -05:00
"net/http"
2024-06-12 09:52:18 -10:00
"github.com/google/uuid"
2024-06-12 10:07:12 -10:00
"golang.org/x/xerrors"
2022-04-29 09:04:19 -05:00
2024-06-24 09:19:32 -10:00
"github.com/coder/coder/v2/coderd/audit"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/database"
2024-06-12 10:07:12 -10:00
"github.com/coder/coder/v2/coderd/database/db2sdk"
2024-09-16 19:03:25 -05:00
"github.com/coder/coder/v2/coderd/database/dbauthz"
2024-06-20 04:19:24 -10:00
"github.com/coder/coder/v2/coderd/database/dbtime"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/httpmw"
2024-06-12 10:07:12 -10:00
"github.com/coder/coder/v2/coderd/rbac"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/codersdk"
2022-04-29 09:04:19 -05:00
)
2024-06-20 04:19:24 -10:00
// @Summary Add organization member
// @ID add-organization-member
// @Security CoderSessionToken
// @Produce json
// @Tags Members
// @Param organization path string true "Organization ID"
// @Param user path string true "User ID, name, or me"
// @Success 200 {object} codersdk.OrganizationMember
// @Router /organizations/{organization}/members/{user} [post]
func ( api * API ) postOrganizationMember ( rw http . ResponseWriter , r * http . Request ) {
var (
2024-06-24 09:19:32 -10:00
ctx = r . Context ()
organization = httpmw . OrganizationParam ( r )
user = httpmw . UserParam ( r )
auditor = api . Auditor . Load ()
aReq , commitAudit = audit . InitRequest [ database . AuditableOrganizationMember ]( rw , & audit . RequestParams {
2024-07-10 07:38:48 -10:00
OrganizationID : organization . ID ,
Audit : * auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionCreate ,
2024-06-24 09:19:32 -10:00
})
2024-06-20 04:19:24 -10:00
)
2024-06-24 09:19:32 -10:00
aReq . Old = database . AuditableOrganizationMember {}
defer commitAudit ()
2024-06-20 04:19:24 -10:00
2024-11-08 08:44:14 -06:00
if ! api . manualOrganizationMembership ( ctx , rw , user ) {
2024-08-30 11:19:36 -05:00
return
}
2024-06-20 04:19:24 -10:00
member , err := api . Database . InsertOrganizationMember ( ctx , database . InsertOrganizationMemberParams {
OrganizationID : organization . ID ,
UserID : user . ID ,
CreatedAt : dbtime . Now (),
UpdatedAt : dbtime . Now (),
Roles : [] string {},
})
if httpapi . Is404Error ( err ) {
httpapi . ResourceNotFound ( rw )
return
}
2024-06-20 13:05:11 -10:00
if database . IsUniqueViolation ( err , database . UniqueOrganizationMembersPkey ) {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2025-04-28 13:51:33 -07:00
Message : "User is already an organization member" ,
Detail : fmt . Sprintf ( "%s is already a member of %s" , user . Username , organization . DisplayName ),
2024-06-20 13:05:11 -10:00
})
return
}
2024-06-20 04:19:24 -10:00
if err != nil {
httpapi . InternalServerError ( rw , err )
return
}
2024-06-24 09:19:32 -10:00
aReq . New = member . Auditable ( user . Username )
2024-06-20 04:19:24 -10:00
resp , err := convertOrganizationMembers ( ctx , api . Database , [] database . OrganizationMember { member })
if err != nil {
httpapi . InternalServerError ( rw , err )
return
}
if len ( resp ) == 0 {
httpapi . InternalServerError ( rw , xerrors . Errorf ( "marshal member" ))
return
}
httpapi . Write ( ctx , rw , http . StatusOK , resp [ 0 ])
}
2024-06-20 05:06:37 -10:00
// @Summary Remove organization member
// @ID remove-organization-member
// @Security CoderSessionToken
// @Tags Members
// @Param organization path string true "Organization ID"
// @Param user path string true "User ID, name, or me"
2024-07-16 12:25:36 -06:00
// @Success 204
2024-06-20 05:06:37 -10:00
// @Router /organizations/{organization}/members/{user} [delete]
func ( api * API ) deleteOrganizationMember ( rw http . ResponseWriter , r * http . Request ) {
var (
2024-06-24 09:19:32 -10:00
ctx = r . Context ()
2024-07-16 12:25:36 -06:00
apiKey = httpmw . APIKey ( r )
2024-06-24 09:19:32 -10:00
organization = httpmw . OrganizationParam ( r )
member = httpmw . OrganizationMemberParam ( r )
auditor = api . Auditor . Load ()
aReq , commitAudit = audit . InitRequest [ database . AuditableOrganizationMember ]( rw , & audit . RequestParams {
2024-07-10 07:38:48 -10:00
OrganizationID : organization . ID ,
Audit : * auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionDelete ,
2024-06-24 09:19:32 -10:00
})
2024-06-20 05:06:37 -10:00
)
2024-06-24 09:19:32 -10:00
aReq . Old = member . OrganizationMember . Auditable ( member . Username )
defer commitAudit ()
2024-06-20 05:06:37 -10:00
2024-11-08 08:44:14 -06:00
// Note: we disallow adding OIDC users if organization sync is enabled.
// For removing members, do not have this same enforcement. As long as a user
// does not re-login, they will not be immediately removed from the organization.
// There might be an urgent need to revoke access.
// A user can re-login if they are removed in error.
// If we add a feature to force logout a user, then we can prevent manual
// member removal when organization sync is enabled, and use force logout instead.
2024-07-16 12:25:36 -06:00
if member . UserID == apiKey . UserID {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response { Message : "cannot remove self from an organization" })
return
}
2024-06-20 05:06:37 -10:00
err := api . Database . DeleteOrganizationMember ( ctx , database . DeleteOrganizationMemberParams {
OrganizationID : organization . ID ,
UserID : member . UserID ,
})
if httpapi . Is404Error ( err ) {
httpapi . ResourceNotFound ( rw )
return
}
if err != nil {
httpapi . InternalServerError ( rw , err )
return
}
2024-06-24 09:19:32 -10:00
aReq . New = database . AuditableOrganizationMember {}
2024-07-16 12:25:36 -06:00
rw . WriteHeader ( http . StatusNoContent )
2024-06-20 05:06:37 -10:00
}
2025-03-10 14:42:07 -04:00
// @Deprecated use /organizations/{organization}/paginated-members [get]
2024-06-12 09:52:18 -10:00
// @Summary List organization members
// @ID list-organization-members
// @Security CoderSessionToken
// @Produce json
// @Tags Members
// @Param organization path string true "Organization ID"
2024-07-16 12:25:36 -06:00
// @Success 200 {object} []codersdk.OrganizationMemberWithUserData
2024-06-12 09:52:18 -10:00
// @Router /organizations/{organization}/members [get]
func ( api * API ) listMembers ( rw http . ResponseWriter , r * http . Request ) {
var (
ctx = r . Context ()
organization = httpmw . OrganizationParam ( r )
)
members , err := api . Database . OrganizationMembers ( ctx , database . OrganizationMembersParams {
OrganizationID : organization . ID ,
UserID : uuid . Nil ,
2025-03-25 14:18:06 +02:00
IncludeSystem : false ,
2024-06-12 09:52:18 -10:00
})
if httpapi . Is404Error ( err ) {
httpapi . ResourceNotFound ( rw )
return
}
if err != nil {
httpapi . InternalServerError ( rw , err )
return
}
2024-07-16 12:25:36 -06:00
resp , err := convertOrganizationMembersWithUserData ( ctx , api . Database , members )
2024-06-12 10:07:12 -10:00
if err != nil {
httpapi . InternalServerError ( rw , err )
return
}
httpapi . Write ( ctx , rw , http . StatusOK , resp )
2024-06-12 09:52:18 -10:00
}
2025-03-10 14:42:07 -04:00
// @Summary Paginated organization members
// @ID paginated-organization-members
// @Security CoderSessionToken
// @Produce json
// @Tags Members
// @Param organization path string true "Organization ID"
// @Param limit query int false "Page limit, if 0 returns all members"
// @Param offset query int false "Page offset"
// @Success 200 {object} []codersdk.PaginatedMembersResponse
// @Router /organizations/{organization}/paginated-members [get]
func ( api * API ) paginatedMembers ( rw http . ResponseWriter , r * http . Request ) {
var (
ctx = r . Context ()
organization = httpmw . OrganizationParam ( r )
2025-07-15 14:55:34 +10:00
paginationParams , ok = ParsePagination ( rw , r )
2025-03-10 14:42:07 -04:00
)
if ! ok {
return
}
paginatedMemberRows , err := api . Database . PaginatedOrganizationMembers ( ctx , database . PaginatedOrganizationMembersParams {
OrganizationID : organization . ID ,
2025-03-26 01:56:39 -05:00
// #nosec G115 - Pagination limits are small and fit in int32
LimitOpt : int32 ( paginationParams . Limit ),
// #nosec G115 - Pagination offsets are small and fit in int32
OffsetOpt : int32 ( paginationParams . Offset ),
2025-03-10 14:42:07 -04:00
})
if httpapi . Is404Error ( err ) {
httpapi . ResourceNotFound ( rw )
return
}
if err != nil {
httpapi . InternalServerError ( rw , err )
return
}
memberRows := make ([] database . OrganizationMembersRow , 0 )
for _ , pRow := range paginatedMemberRows {
row := database . OrganizationMembersRow {
OrganizationMember : pRow . OrganizationMember ,
Username : pRow . Username ,
AvatarURL : pRow . AvatarURL ,
Name : pRow . Name ,
Email : pRow . Email ,
GlobalRoles : pRow . GlobalRoles ,
}
memberRows = append ( memberRows , row )
}
members , err := convertOrganizationMembersWithUserData ( ctx , api . Database , memberRows )
if err != nil {
httpapi . InternalServerError ( rw , err )
}
resp := codersdk . PaginatedMembersResponse {
Members : members ,
Count : int ( paginatedMemberRows [ 0 ]. Count ),
}
httpapi . Write ( ctx , rw , http . StatusOK , resp )
}
2023-01-11 12:16:09 +01:00
// @Summary Assign role to organization member
// @ID assign-role-to-organization-member
// @Security CoderSessionToken
// @Accept json
// @Produce json
// @Tags Members
// @Param organization path string true "Organization ID"
2023-01-11 14:08:04 +01:00
// @Param user path string true "User ID, name, or me"
// @Param request body codersdk.UpdateRoles true "Update roles request"
2023-01-11 12:16:09 +01:00
// @Success 200 {object} codersdk.OrganizationMember
// @Router /organizations/{organization}/members/{user}/roles [put]
2022-05-25 22:14:08 -05:00
func ( api * API ) putMemberRoles ( rw http . ResponseWriter , r * http . Request ) {
2022-09-21 17:07:00 -05:00
var (
2024-06-24 09:19:32 -10:00
ctx = r . Context ()
organization = httpmw . OrganizationParam ( r )
member = httpmw . OrganizationMemberParam ( r )
apiKey = httpmw . APIKey ( r )
auditor = api . Auditor . Load ()
aReq , commitAudit = audit . InitRequest [ database . AuditableOrganizationMember ]( rw , & audit . RequestParams {
2024-06-26 07:38:46 -10:00
OrganizationID : organization . ID ,
Audit : * auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionWrite ,
2024-06-24 09:19:32 -10:00
})
2022-09-21 17:07:00 -05:00
)
2024-06-24 09:19:32 -10:00
aReq . Old = member . OrganizationMember . Auditable ( member . Username )
defer commitAudit ()
2022-05-31 15:50:38 -05:00
2024-09-16 19:03:25 -05:00
// Check if changing roles is allowed
if ! api . allowChangingMemberRoles ( ctx , rw , member , organization ) {
return
}
2024-06-24 09:19:32 -10:00
if apiKey . UserID == member . OrganizationMember . UserID {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-05-31 15:50:38 -05:00
Message : "You cannot change your own organization roles." ,
2024-09-26 11:48:50 -05:00
Detail : "Another user with the appropriate permissions must change your roles." ,
2022-05-31 15:50:38 -05:00
})
return
}
2022-04-29 09:04:19 -05:00
var params codersdk . UpdateRoles
2022-09-21 17:07:00 -05:00
if ! httpapi . Read ( ctx , rw , r , & params ) {
2022-04-29 09:04:19 -05:00
return
}
2024-05-29 09:49:43 -05:00
updatedUser , err := api . Database . UpdateMemberRoles ( ctx , database . UpdateMemberRolesParams {
2022-04-29 09:04:19 -05:00
GrantedRoles : params . Roles ,
2023-10-11 09:41:14 +04:00
UserID : member . UserID ,
2022-04-29 09:04:19 -05:00
OrgID : organization . ID ,
})
2024-06-13 10:59:06 -10:00
if httpapi . Is404Error ( err ) {
httpapi . Forbidden ( rw )
return
}
2022-04-29 09:04:19 -05:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-04-29 09:04:19 -05:00
Message : err . Error (),
})
return
}
2024-06-24 09:19:32 -10:00
aReq . New = database . AuditableOrganizationMember {
OrganizationMember : updatedUser ,
Username : member . Username ,
}
2022-04-29 09:04:19 -05:00
2024-06-12 10:07:12 -10:00
resp , err := convertOrganizationMembers ( ctx , api . Database , [] database . OrganizationMember { updatedUser })
if err != nil {
httpapi . InternalServerError ( rw , err )
return
}
if len ( resp ) != 1 {
httpapi . InternalServerError ( rw , xerrors . Errorf ( "failed to serialize member to response, update still succeeded" ))
return
}
httpapi . Write ( ctx , rw , http . StatusOK , resp [ 0 ])
2022-04-29 09:04:19 -05:00
}
2024-09-16 19:03:25 -05:00
func ( api * API ) allowChangingMemberRoles ( ctx context . Context , rw http . ResponseWriter , member httpmw . OrganizationMember , organization database . Organization ) bool {
// nolint:gocritic // The caller could be an org admin without this perm.
// We need to disable manual role assignment if role sync is enabled for
// the given organization.
user , err := api . Database . GetUserByID ( dbauthz . AsSystemRestricted ( ctx ), member . UserID )
if err != nil {
httpapi . InternalServerError ( rw , err )
return false
}
if user . LoginType == database . LoginTypeOIDC {
// nolint:gocritic // fetching settings
orgSync , err := api . IDPSync . OrganizationRoleSyncEnabled ( dbauthz . AsSystemRestricted ( ctx ), api . Database , organization . ID )
if err != nil {
httpapi . InternalServerError ( rw , err )
return false
}
if orgSync {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2024-11-08 08:44:14 -06:00
Message : "Cannot modify roles for OIDC users when role sync is enabled. This organization member's roles are managed by the identity provider. Have the user re-login to refresh their roles." ,
2024-09-16 19:03:25 -05:00
Detail : "'User Role Field' is set in the organization settings. Ask an administrator to adjust or disable these settings." ,
})
return false
}
}
return true
}
2024-06-12 10:07:12 -10:00
// convertOrganizationMembers batches the role lookup to make only 1 sql call
// We
func convertOrganizationMembers ( ctx context . Context , db database . Store , mems [] database . OrganizationMember ) ([] codersdk . OrganizationMember , error ) {
converted := make ([] codersdk . OrganizationMember , 0 , len ( mems ))
roleLookup := make ([] database . NameOrganizationPair , 0 )
for _ , m := range mems {
converted = append ( converted , codersdk . OrganizationMember {
UserID : m . UserID ,
OrganizationID : m . OrganizationID ,
CreatedAt : m . CreatedAt ,
UpdatedAt : m . UpdatedAt ,
Roles : db2sdk . List ( m . Roles , func ( r string ) codersdk . SlimRole {
// If it is a built-in role, no lookups are needed.
rbacRole , err := rbac . RoleByName ( rbac . RoleIdentifier { Name : r , OrganizationID : m . OrganizationID })
if err == nil {
return db2sdk . SlimRole ( rbacRole )
}
// We know the role name and the organization ID. We are missing the
// display name. Append the lookup parameter, so we can get the display name
roleLookup = append ( roleLookup , database . NameOrganizationPair {
Name : r ,
OrganizationID : m . OrganizationID ,
})
return codersdk . SlimRole {
Name : r ,
DisplayName : "" ,
OrganizationID : m . OrganizationID . String (),
}
}),
})
2022-04-29 09:04:19 -05:00
}
2022-08-24 15:58:57 -04:00
2024-06-12 10:07:12 -10:00
customRoles , err := db . CustomRoles ( ctx , database . CustomRolesParams {
LookupRoles : roleLookup ,
ExcludeOrgRoles : false ,
2025-02-27 10:39:06 -07:00
OrganizationID : uuid . Nil ,
2024-06-12 10:07:12 -10:00
})
if err != nil {
// We are missing the display names, but that is not absolutely required. So just
// return the converted and the names will be used instead of the display names.
return converted , xerrors . Errorf ( "lookup custom roles: %w" , err )
2022-08-24 15:58:57 -04:00
}
2024-06-12 10:07:12 -10:00
// Now map the customRoles back to the slimRoles for their display name.
customRolesMap := make ( map [ string ] database . CustomRole )
for _ , role := range customRoles {
customRolesMap [ role . RoleIdentifier (). UniqueName ()] = role
}
for i := range converted {
for j , role := range converted [ i ]. Roles {
if cr , ok := customRolesMap [ role . UniqueName ()]; ok {
converted [ i ]. Roles [ j ]. DisplayName = cr . DisplayName
}
}
}
return converted , nil
2022-04-29 09:04:19 -05:00
}
2024-06-12 09:52:18 -10:00
2024-07-16 12:25:36 -06:00
func convertOrganizationMembersWithUserData ( ctx context . Context , db database . Store , rows [] database . OrganizationMembersRow ) ([] codersdk . OrganizationMemberWithUserData , error ) {
2024-06-12 10:07:12 -10:00
members := make ([] database . OrganizationMember , 0 )
for _ , row := range rows {
members = append ( members , row . OrganizationMember )
2024-06-12 09:52:18 -10:00
}
2024-06-12 10:07:12 -10:00
convertedMembers , err := convertOrganizationMembers ( ctx , db , members )
if err != nil {
return nil , err
}
if len ( convertedMembers ) != len ( rows ) {
return nil , xerrors . Errorf ( "conversion failed, mismatch slice lengths" )
}
2024-07-16 12:25:36 -06:00
converted := make ([] codersdk . OrganizationMemberWithUserData , 0 )
2024-06-12 10:07:12 -10:00
for i := range convertedMembers {
2024-07-16 12:25:36 -06:00
converted = append ( converted , codersdk . OrganizationMemberWithUserData {
2024-06-12 10:07:12 -10:00
Username : rows [ i ]. Username ,
2024-07-16 12:25:36 -06:00
AvatarURL : rows [ i ]. AvatarURL ,
Name : rows [ i ]. Name ,
2024-07-24 11:36:45 -06:00
Email : rows [ i ]. Email ,
2024-07-16 12:25:36 -06:00
GlobalRoles : db2sdk . SlimRolesFromNames ( rows [ i ]. GlobalRoles ),
2024-06-12 10:07:12 -10:00
OrganizationMember : convertedMembers [ i ],
})
}
return converted , nil
2024-06-12 09:52:18 -10:00
}
2024-11-08 08:44:14 -06:00
// manualOrganizationMembership checks if the user is an OIDC user and if organization sync is enabled.
// If organization sync is enabled, manual organization assignment is not allowed,
// since all organization membership is controlled by the external IDP.
func ( api * API ) manualOrganizationMembership ( ctx context . Context , rw http . ResponseWriter , user database . User ) bool {
if user . LoginType == database . LoginTypeOIDC && api . IDPSync . OrganizationSyncEnabled ( ctx , api . Database ) {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "Organization sync is enabled for OIDC users, meaning manual organization assignment is not allowed for this user. Have the user re-login to refresh their organizations." ,
Detail : fmt . Sprintf ( "User %s is an OIDC user and organization sync is enabled. Ask an administrator to resolve the membership in your external IDP." , user . Username ),
})
return false
}
return true
}