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
12 changes: 6 additions & 6 deletions cli/testdata/coder_users_create_--help.golden
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
Usage: coder users create [flags]

Options
--disable-login bool
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. Be careful when using this flag as it can lock
the user out of their account.

-e, --email string
Specifies an email address for the new user.

--login-type string
Optionally specify the login type for the user. Valid values are:
password, none, github, oidc. Using 'none' prevents the user from
authenticating and requires an API key/token to be generated by an
admin.

-p, --password string
Specifies a password for the new user.

Expand Down
44 changes: 38 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 && loginType != "" {
return xerrors.New("You cannot specify both --disable-login and --login-type")
}
if disableLogin {
userLoginType = codersdk.LoginTypeNone
} else if loginType != "" {
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,22 @@ 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. "+
"Using 'none' prevents the user from authenticating and requires an API key/token to be generated by an admin.",
strings.Join([]string{
string(codersdk.LoginTypePassword), string(codersdk.LoginTypeNone), string(codersdk.LoginTypeGithub), string(codersdk.LoginTypeOIDC),
}, ", ",
)),
Value: clibase.StringOf(&loginType),
},
}
return cmd
}
12 changes: 11 additions & 1 deletion coderd/apidoc/docs.go

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

13 changes: 11 additions & 2 deletions 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
66 changes: 66 additions & 0 deletions coderd/users_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"testing"
"time"

"github.com/golang-jwt/jwt"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -565,6 +566,71 @@ func TestPostUsers(t *testing.T) {
}
}
})

t.Run("CreateNoneLoginType", func(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
first := coderdtest.CreateFirstUser(t, client)

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

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

found, err := client.User(ctx, user.ID.String())
require.NoError(t, err)
require.Equal(t, found.LoginType, codersdk.LoginTypeNone)
})

t.Run("CreateOIDCLoginType", func(t *testing.T) {
t.Parallel()
email := "another@user.org"
conf := coderdtest.NewOIDCConfig(t, "")
config := conf.OIDCConfig(t, jwt.MapClaims{
"email": email,
})
config.AllowSignups = false
config.IgnoreUserInfo = true

client := coderdtest.New(t, &coderdtest.Options{
OIDCConfig: config,
})
first := coderdtest.CreateFirstUser(t, client)

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

_, err := client.CreateUser(ctx, codersdk.CreateUserRequest{
OrganizationID: first.OrganizationID,
Email: email,
Username: "someone-else",
Password: "",
UserLoginType: codersdk.LoginTypeOIDC,
})
require.NoError(t, err)

// Try to log in with OIDC.
userClient := codersdk.New(client.URL)
resp := oidcCallback(t, userClient, conf.EncodeClaims(t, jwt.MapClaims{
"email": email,
}))
require.Equal(t, resp.StatusCode, http.StatusTemporaryRedirect)
// Set the client to use this OIDC context
authCookie := authCookieValue(resp.Cookies())
userClient.SetSessionToken(authCookie)
_ = resp.Body.Close()

found, err := userClient.User(ctx, "me")
require.NoError(t, err)
require.Equal(t, found.LoginType, codersdk.LoginTypeOIDC)
})
}

func TestUpdateUserProfile(t *testing.T) {
Expand Down
1 change: 1 addition & 0 deletions codersdk/apikey.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ type APIKey struct {
type LoginType string

const (
LoginTypeUnknown LoginType = ""
LoginTypePassword LoginType = "password"
LoginTypeGithub LoginType = "github"
LoginTypeOIDC LoginType = "oidc"
Expand Down
Loading