Skip to content

fix(scim): ensure scim users aren't created with their own org #7595

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 3 commits into from
May 19, 2023
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: 0 additions & 1 deletion coderd/apidoc/docs.go

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

2 changes: 1 addition & 1 deletion coderd/apidoc/swagger.json

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

6 changes: 5 additions & 1 deletion coderd/userauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -921,7 +921,11 @@ func (api *API) oauthLogin(r *http.Request, params oauthLoginParams) (*http.Cook
Username: params.Username,
OrganizationID: organizationID,
},
LoginType: params.LoginType,
// All of the userauth tests depend on this being able to create
// the first organization. It shouldn't be possible in normal
// operation.
CreateOrganization: len(organizations) == 0,
LoginType: params.LoginType,
})
if err != nil {
return xerrors.Errorf("create user: %w", err)
Expand Down
58 changes: 43 additions & 15 deletions coderd/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,8 @@ func (api *API) postFirstUser(rw http.ResponseWriter, r *http.Request) {
// Create an org for the first user.
OrganizationID: uuid.Nil,
},
LoginType: database.LoginTypePassword,
CreateOrganization: true,
LoginType: database.LoginTypePassword,
})
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Expand Down Expand Up @@ -313,19 +314,41 @@ func (api *API) postUser(rw http.ResponseWriter, r *http.Request) {
return
}

_, err = api.Database.GetOrganizationByID(ctx, req.OrganizationID)
if httpapi.Is404Error(err) {
httpapi.Write(ctx, rw, http.StatusNotFound, codersdk.Response{
Message: fmt.Sprintf("Organization does not exist with the provided id %q.", req.OrganizationID),
})
return
}
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Internal error fetching organization.",
Detail: err.Error(),
})
return
if req.OrganizationID != uuid.Nil {
// If an organization was provided, make sure it exists.
_, err := api.Database.GetOrganizationByID(ctx, req.OrganizationID)
if err != nil {
if httpapi.Is404Error(err) {
httpapi.Write(ctx, rw, http.StatusNotFound, codersdk.Response{
Message: fmt.Sprintf("Organization does not exist with the provided id %q.", req.OrganizationID),
})
return
}

httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Internal error fetching organization.",
Detail: err.Error(),
})
return
}
} else {
// If no organization is provided, add the user to the first
// organization.
organizations, err := api.Database.GetOrganizations(ctx)
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Internal error fetching orgs.",
Detail: err.Error(),
})
return
}

if len(organizations) > 0 {
// Add the user to the first organization. Once multi-organization
// support is added, we should enable a configuration map of user
// email to organization.
req.OrganizationID = organizations[0].ID
}
}

err = userpassword.Validate(req.Password)
Expand Down Expand Up @@ -955,7 +978,8 @@ func (api *API) organizationByUserAndName(rw http.ResponseWriter, r *http.Reques

type CreateUserRequest struct {
codersdk.CreateUserRequest
LoginType database.LoginType
CreateOrganization bool
LoginType database.LoginType
}

func (api *API) CreateUser(ctx context.Context, store database.Store, req CreateUserRequest) (database.User, uuid.UUID, error) {
Expand All @@ -964,6 +988,10 @@ func (api *API) CreateUser(ctx context.Context, store database.Store, req Create
orgRoles := make([]string, 0)
// If no organization is provided, create a new one for the user.
if req.OrganizationID == uuid.Nil {
if !req.CreateOrganization {
return xerrors.Errorf("organization ID must be provided")
}

organization, err := tx.InsertOrganization(ctx, database.InsertOrganizationParams{
ID: uuid.New(),
Name: req.Username,
Expand Down
38 changes: 35 additions & 3 deletions coderd/users_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"time"

"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup"

Expand Down Expand Up @@ -478,21 +479,49 @@ func TestPostUsers(t *testing.T) {
require.Equal(t, http.StatusNotFound, apiErr.StatusCode())
})

t.Run("CreateWithoutOrg", func(t *testing.T) {
t.Parallel()
auditor := audit.NewMock()
client := coderdtest.New(t, &coderdtest.Options{Auditor: auditor})
numLogs := len(auditor.AuditLogs())

firstUser := coderdtest.CreateFirstUser(t, client)
numLogs++ // add an audit log for user create
numLogs++ // add an audit log for login

ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()

user, err := client.CreateUser(ctx, codersdk.CreateUserRequest{
Email: "another@user.org",
Username: "someone-else",
Password: "SomeSecurePassword!",
})
require.NoError(t, err)

require.Len(t, auditor.AuditLogs(), numLogs)
require.Equal(t, database.AuditActionCreate, auditor.AuditLogs()[numLogs-1].Action)
require.Equal(t, database.AuditActionLogin, auditor.AuditLogs()[numLogs-2].Action)

require.Len(t, user.OrganizationIDs, 1)
assert.Equal(t, firstUser.OrganizationID, user.OrganizationIDs[0])
})

t.Run("Create", func(t *testing.T) {
t.Parallel()
auditor := audit.NewMock()
client := coderdtest.New(t, &coderdtest.Options{Auditor: auditor})
numLogs := len(auditor.AuditLogs())

user := coderdtest.CreateFirstUser(t, client)
firstUser := coderdtest.CreateFirstUser(t, client)
numLogs++ // add an audit log for user create
numLogs++ // add an audit log for login

ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()

_, err := client.CreateUser(ctx, codersdk.CreateUserRequest{
OrganizationID: user.OrganizationID,
user, err := client.CreateUser(ctx, codersdk.CreateUserRequest{
OrganizationID: firstUser.OrganizationID,
Email: "another@user.org",
Username: "someone-else",
Password: "SomeSecurePassword!",
Expand All @@ -502,6 +531,9 @@ func TestPostUsers(t *testing.T) {
require.Len(t, auditor.AuditLogs(), numLogs)
require.Equal(t, database.AuditActionCreate, auditor.AuditLogs()[numLogs-1].Action)
require.Equal(t, database.AuditActionLogin, auditor.AuditLogs()[numLogs-2].Action)

require.Len(t, user.OrganizationIDs, 1)
assert.Equal(t, firstUser.OrganizationID, user.OrganizationIDs[0])
})

t.Run("LastSeenAt", func(t *testing.T) {
Expand Down
2 changes: 1 addition & 1 deletion codersdk/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ type CreateUserRequest struct {
Email string `json:"email" validate:"required,email" format:"email"`
Username string `json:"username" validate:"required,username"`
Password string `json:"password" validate:"required"`
OrganizationID uuid.UUID `json:"organization_id" validate:"required" format:"uuid"`
OrganizationID uuid.UUID `json:"organization_id" validate:"" format:"uuid"`
}

type UpdateUserProfileRequest struct {
Expand Down
2 changes: 1 addition & 1 deletion docs/api/schemas.md
Original file line number Diff line number Diff line change
Expand Up @@ -1564,7 +1564,7 @@ CreateParameterRequest is a structure used to create a new parameter value for a
| Name | Type | Required | Restrictions | Description |
| ----------------- | ------ | -------- | ------------ | ----------- |
| `email` | string | true | | |
| `organization_id` | string | true | | |
| `organization_id` | string | false | | |
| `password` | string | true | | |
| `username` | string | true | | |

Expand Down
20 changes: 18 additions & 2 deletions enterprise/coderd/scim.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,11 +156,27 @@ func (api *API) scimPostUser(rw http.ResponseWriter, r *http.Request) {
return
}

var organizationID uuid.UUID
//nolint:gocritic
organizations, err := api.Database.GetOrganizations(dbauthz.AsSystemRestricted(ctx))
if err != nil {
_ = handlerutil.WriteError(rw, err)
return
}

if len(organizations) > 0 {
// Add the user to the first organization. Once multi-organization
// support is added, we should enable a configuration map of user
// email to organization.
organizationID = organizations[0].ID
}

//nolint:gocritic // needed for SCIM
user, _, err := api.AGPL.CreateUser(dbauthz.AsSystemRestricted(ctx), api.Database, agpl.CreateUserRequest{
CreateUserRequest: codersdk.CreateUserRequest{
Username: sUser.UserName,
Email: email,
Username: sUser.UserName,
Email: email,
OrganizationID: organizationID,
},
LoginType: database.LoginTypeOIDC,
})
Expand Down