Skip to content

feat: allow creating manual oidc/github based users #9000

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 15 commits into from
Aug 11, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
feat: allow creating manual oidc/github based users
  • Loading branch information
Emyrk committed Aug 8, 2023
commit bdec01fa39dd89efb224bf2a255daef666dfb5c0
42 changes: 36 additions & 6 deletions cli/usercreate.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cli

import (
"fmt"
"strings"

"github.com/go-playground/validator/v10"
"golang.org/x/xerrors"
Expand All @@ -18,6 +19,7 @@ func (r *RootCmd) userCreate() *clibase.Cmd {
username string
password string
disableLogin bool
loginType string
)
client := new(codersdk.Client)
cmd := &clibase.Cmd{
Expand Down Expand Up @@ -54,7 +56,18 @@ func (r *RootCmd) userCreate() *clibase.Cmd {
return err
}
}
if password == "" && !disableLogin {
userLoginType := codersdk.LoginTypePassword
if disableLogin {
userLoginType = codersdk.LoginTypeNone
} else if loginType != "" {
if disableLogin {
return xerrors.New("You cannot specify both --disable-login and --login-type")
}
userLoginType = codersdk.LoginType(loginType)
}

if password == "" && userLoginType == codersdk.LoginTypePassword {
// Generate a random password
password, err = cryptorand.StringCharset(cryptorand.Human, 20)
if err != nil {
return err
Expand All @@ -66,14 +79,22 @@ func (r *RootCmd) userCreate() *clibase.Cmd {
Username: username,
Password: password,
OrganizationID: organization.ID,
DisableLogin: disableLogin,
UserLoginType: userLoginType,
})
if err != nil {
return err
}
authenticationMethod := `Your password is: ` + cliui.DefaultStyles.Field.Render(password)
if disableLogin {

authenticationMethod := ""
switch codersdk.LoginType(strings.ToLower(string(userLoginType))) {
case codersdk.LoginTypePassword:
authenticationMethod = `Your password is: ` + cliui.DefaultStyles.Field.Render(password)
case codersdk.LoginTypeNone:
authenticationMethod = "Login has been disabled for this user. Contact your administrator to authenticate."
case codersdk.LoginTypeGithub:
authenticationMethod = `Login is authenticated through GitHub.`
case codersdk.LoginTypeOIDC:
authenticationMethod = `Login is authenticated through the configured OIDC provider.`
}

_, _ = fmt.Fprintln(inv.Stderr, `A new user has been created!
Expand Down Expand Up @@ -111,11 +132,20 @@ Create a workspace `+cliui.DefaultStyles.Code.Render("coder create")+`!`)
Value: clibase.StringOf(&password),
},
{
Flag: "disable-login",
Description: "Disabling login for a user prevents the user from authenticating via password or IdP login. Authentication requires an API key/token generated by an admin. " +
Flag: "disable-login",
Hidden: true,
Description: "Deprecated: Use '--login-type=none'. \nDisabling login for a user prevents the user from authenticating via password or IdP login. Authentication requires an API key/token generated by an admin. " +
"Be careful when using this flag as it can lock the user out of their account.",
Value: clibase.BoolOf(&disableLogin),
},
{
Flag: "login-type",
Description: fmt.Sprintf("Optionally specify the login type for the user. Valid values are: %s.",
strings.Join([]string{
string(codersdk.LoginTypePassword), string(codersdk.LoginTypeNone), string(codersdk.LoginTypeGithub), string(codersdk.LoginTypeOIDC)}, ", ",
)),
Value: clibase.StringOf(&loginType),
},
}
return cmd
}
10 changes: 9 additions & 1 deletion coderd/apidoc/docs.go

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

10 changes: 9 additions & 1 deletion coderd/apidoc/swagger.json

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

16 changes: 8 additions & 8 deletions coderd/coderdtest/coderdtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -588,14 +588,7 @@ func createAnotherUserRetry(t *testing.T, client *codersdk.Client, organizationI
require.NoError(t, err)

var sessionToken string
if !req.DisableLogin {
login, err := client.LoginWithPassword(context.Background(), codersdk.LoginWithPasswordRequest{
Email: req.Email,
Password: req.Password,
})
require.NoError(t, err)
sessionToken = login.SessionToken
} else {
if req.DisableLogin || req.UserLoginType == codersdk.LoginTypeNone {
// Cannot log in with a disabled login user. So make it an api key from
// the client making this user.
token, err := client.CreateToken(context.Background(), user.ID.String(), codersdk.CreateTokenRequest{
Expand All @@ -605,6 +598,13 @@ func createAnotherUserRetry(t *testing.T, client *codersdk.Client, organizationI
})
require.NoError(t, err)
sessionToken = token.Key
} else {
login, err := client.LoginWithPassword(context.Background(), codersdk.LoginWithPasswordRequest{
Email: req.Email,
Password: req.Password,
})
require.NoError(t, err)
sessionToken = login.SessionToken
}

if user.Status == codersdk.UserStatusDormant {
Expand Down
18 changes: 17 additions & 1 deletion coderd/userauth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ func TestUserLogin(t *testing.T) {
require.Equal(t, http.StatusUnauthorized, apiErr.StatusCode())
})
// Password auth should fail if the user is made without password login.
t.Run("LoginTypeNone", func(t *testing.T) {
t.Run("DisableLoginDeprecatedField", func(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
user := coderdtest.CreateFirstUser(t, client)
Expand All @@ -160,6 +160,22 @@ func TestUserLogin(t *testing.T) {
})
require.Error(t, err)
})

t.Run("LoginTypeNone", func(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
user := coderdtest.CreateFirstUser(t, client)
anotherClient, anotherUser := coderdtest.CreateAnotherUserMutators(t, client, user.OrganizationID, nil, func(r *codersdk.CreateUserRequest) {
r.Password = ""
r.UserLoginType = codersdk.LoginTypeNone
})

_, err := anotherClient.LoginWithPassword(context.Background(), codersdk.LoginWithPasswordRequest{
Email: anotherUser.Email,
Password: "SomeSecurePassword!",
})
require.Error(t, err)
})
}

func TestUserAuthMethods(t *testing.T) {
Expand Down
40 changes: 29 additions & 11 deletions coderd/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,11 +287,27 @@ func (api *API) postUser(rw http.ResponseWriter, r *http.Request) {
return
}

if req.UserLoginType == "" && req.DisableLogin {
// Handle the deprecated field
req.UserLoginType = codersdk.LoginTypeNone
}
if req.UserLoginType == "" {
// Default to password auth
req.UserLoginType = codersdk.LoginTypePassword
}

if req.UserLoginType != codersdk.LoginTypePassword && req.Password != "" {
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
Message: fmt.Sprintf("Password cannot be set for non-password (%q) authentication.", req.UserLoginType),
})
return
}

// If password auth is disabled, don't allow new users to be
// created with a password!
if api.DeploymentValues.DisablePasswordAuth {
if api.DeploymentValues.DisablePasswordAuth && req.UserLoginType == codersdk.LoginTypePassword {
httpapi.Write(ctx, rw, http.StatusForbidden, codersdk.Response{
Message: "You cannot manually provision new users with password authentication disabled!",
Message: "Password based authentication is disabled! Unable to provision new users with password authentication.",
})
return
}
Expand Down Expand Up @@ -353,17 +369,11 @@ func (api *API) postUser(rw http.ResponseWriter, r *http.Request) {
}
}

if req.DisableLogin && req.Password != "" {
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
Message: "Cannot set password when disabling login.",
})
return
}

var loginType database.LoginType
if req.DisableLogin {
switch req.UserLoginType {
case codersdk.LoginTypeNone:
loginType = database.LoginTypeNone
} else {
case codersdk.LoginTypePassword:
err = userpassword.Validate(req.Password)
if err != nil {
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
Expand All @@ -376,6 +386,14 @@ func (api *API) postUser(rw http.ResponseWriter, r *http.Request) {
return
}
loginType = database.LoginTypePassword
case codersdk.LoginTypeOIDC:
loginType = database.LoginTypeOIDC
case codersdk.LoginTypeGithub:
loginType = database.LoginTypeGithub
default:
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
Message: fmt.Sprintf("Unsupported login type %q for manually creating new users.", req.UserLoginType),
})
}

user, _, err := api.CreateUser(ctx, api.Database, CreateUserRequest{
Expand Down
5 changes: 4 additions & 1 deletion codersdk/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,12 @@ type CreateFirstUserResponse struct {
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_if=DisableLogin false"`
Password string `json:"password"`
// UserLoginType defaults to LoginTypePassword.
UserLoginType LoginType `json:"login_type"`
// DisableLogin sets the user's login type to 'none'. This prevents the user
// from being able to use a password or any other authentication method to login.
// Deprecated: Set UserLoginType=LoginTypeDisabled instead.
DisableLogin bool `json:"disable_login"`
OrganizationID uuid.UUID `json:"organization_id" validate:"" format:"uuid"`
}
Expand Down
16 changes: 9 additions & 7 deletions docs/api/schemas.md

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

1 change: 1 addition & 0 deletions docs/api/users.md

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

2 changes: 1 addition & 1 deletion scripts/develop.sh
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ fatal() {
trap 'fatal "Script encountered an error"' ERR

cdroot
start_cmd API "" "${CODER_DEV_SHIM}" server --http-address 0.0.0.0:3000 --swagger-enable --access-url "http://127.0.0.1:3000" --dangerous-allow-cors-requests=true --experiments "*,moons" "$@"
start_cmd API "" "${CODER_DEV_SHIM}" server --http-address 0.0.0.0:3000 --swagger-enable --access-url "http://127.0.0.1:3000" --dangerous-allow-cors-requests=true "$@"

echo '== Waiting for Coder to become ready'
# Start the timeout in the background so interrupting this script
Expand Down
1 change: 1 addition & 0 deletions site/src/api/typesGenerated.ts

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