Files
coder/cli/usercreate.go
T
Jake HowellandSushant P 0e104f38e0 fix!: deprecate login_type=none, convert existing users to password login (#26851)
> 🤖 This PR was modified by Coder Agents on behalf of Jake Howell.

Deprecates `login_type=none` (legacy passwordless machine users) in
favour of premium **service accounts**, and migrates existing accounts
off the deprecated path while preserving their identity. Resolves
[DEVEX-226].

## What this does

- **Creation is gated** — `POST /users` and `coder users create` reject
`login_type=none` (and the deprecated `--disable-login`) unless a
service account is requested.
- **Existing users are converted** — migration
`000554_legacy_none_login_to_password` rewrites legacy non-system,
non–service-account `login_type='none'` accounts to
`login_type='password'`. Email addresses are **preserved** and existing
API tokens remain valid. Admins can set a password if interactive login
is desired.

## Why convert to `password` and not `is_service_account`?

Migration `000433_add_is_service_account_to_users` adds two CHECK
constraints:

- `users_email_not_empty`: `(is_service_account = true) = (email = '')`
- `users_service_account_login_type`: `is_service_account = false OR
login_type = 'none'`

Turning a real, email-bearing `login_type=none` user into a service
account would require **blanking their email**. Converting to `password`
instead preserves the account and its email.

> ⚠️ **Breaking / one-way.** The `down` migration cannot restore which
users originally had `login_type='none'`.


Decision log

- **Goal:** move existing `login_type=none` users off the deprecated
path while preserving their identity/email.
- **Constraint discovered:** the `is_service_account` CHECK constraints
(migration `000433`) make a literal `none → service account` conversion
require blanking emails, so this PR converts to `password` instead to
keep emails intact.
- **Implementation:** creation-gating in `cli/usercreate.go` and
`coderd/users.go`, matching test updates, plus the
`000554_legacy_none_login_to_password.{up,down}.sql` migration.
- **CI fix:** the branch was behind `main` and its migration originally
numbered `000534`, which collided with main's
`000534_drop_chat_model_configs_provider`. Merged `main` and renumbered
to `000554` (next free after main's `000553`). `make gen` produces no
drift (the migration is data-only).



> The service-account conversion alternative (#27182, which blanked
emails) was closed in favour of this password-preserving approach.
>
> Docs follow-up: #27333.

[DEVEX-226]: https://linear.app/issue/DEVEX-226

---------

Co-authored-by: Sushant P <zenithwolf1000@users.noreply.github.com>
2026-07-28 21:05:50 +10:00

234 lines
7.6 KiB
Go

package cli
import (
"fmt"
"strings"
"github.com/go-playground/validator/v10"
"github.com/google/uuid"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/cryptorand"
"github.com/coder/pretty"
"github.com/coder/serpent"
)
func (r *RootCmd) userCreate() *serpent.Command {
var (
email string
username string
name string
password string
disableLogin bool
loginType string
serviceAccount bool
orgContext = NewOrganizationContext()
)
cmd := &serpent.Command{
Use: "create",
Short: "Create a new user.",
Middleware: serpent.Chain(
serpent.RequireNArgs(0),
),
Handler: func(inv *serpent.Invocation) error {
if serviceAccount {
switch {
case loginType != "":
return xerrors.New("You cannot use --login-type with --service-account")
case password != "":
return xerrors.New("You cannot use --password with --service-account")
case email != "":
return xerrors.New("You cannot use --email with --service-account")
case disableLogin:
return xerrors.New("You cannot use --disable-login with --service-account")
}
} else {
switch {
case disableLogin && loginType != "":
return xerrors.New("You cannot specify both --disable-login and --login-type")
case disableLogin:
return xerrors.New("--disable-login is deprecated. Use --service-account for machine-to-machine access.")
case loginType == string(codersdk.LoginTypeNone):
return xerrors.New("Login type 'none' is deprecated. Use --service-account for machine-to-machine access.")
}
}
client, err := r.InitClient(inv)
if err != nil {
return err
}
organization, err := orgContext.Selected(inv, client)
if err != nil {
return err
}
// We only prompt for the full name if both username and email have not
// been set. This is to avoid breaking existing non-interactive usage.
shouldPromptName := username == "" && email == ""
if username == "" {
username, err = cliui.Prompt(inv, cliui.PromptOptions{
Text: "Username:",
Validate: func(username string) error {
err = codersdk.NameValid(username)
if err != nil {
return xerrors.Errorf("username %q is invalid: %w", username, err)
}
return nil
},
})
if err != nil {
return err
}
}
if email == "" && !serviceAccount {
email, err = cliui.Prompt(inv, cliui.PromptOptions{
Text: "Email:",
Validate: func(s string) error {
err := validator.New().Var(s, "email")
if err != nil {
return xerrors.New("That's not a valid email address!")
}
return err
},
})
if err != nil {
return err
}
}
if name == "" && shouldPromptName {
rawName, err := cliui.Prompt(inv, cliui.PromptOptions{
Text: "Full name (optional):",
})
if err != nil {
return err
}
name = codersdk.NormalizeRealUsername(rawName)
if !strings.EqualFold(rawName, name) {
cliui.Warnf(inv.Stderr, "Normalized name to %q", name)
}
}
userLoginType := codersdk.LoginTypePassword
if disableLogin || serviceAccount {
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
}
}
_, err = client.CreateUserWithOrgs(inv.Context(), codersdk.CreateUserRequestWithOrgs{
Email: email,
Username: username,
Name: name,
Password: password,
OrganizationIDs: []uuid.UUID{organization.ID},
UserLoginType: userLoginType,
ServiceAccount: serviceAccount,
})
if err != nil {
return err
}
authenticationMethod := ""
switch codersdk.LoginType(strings.ToLower(string(userLoginType))) {
case codersdk.LoginTypePassword:
authenticationMethod = `Your password is: ` + pretty.Sprint(cliui.DefaultStyles.Field, 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.`
}
if serviceAccount {
email = "n/a"
authenticationMethod = "Service accounts must authenticate with a token and cannot log in."
}
_, _ = fmt.Fprintln(inv.Stderr, `A new user has been created!
Share the instructions below to get them started.
`+pretty.Sprint(cliui.DefaultStyles.Placeholder, "—————————————————————————————————————————————————")+`
Download the Coder command line for your operating system:
https://github.com/coder/coder/releases
Run `+pretty.Sprint(cliui.DefaultStyles.Code, "coder login "+client.URL.String())+` to authenticate.
Your email is: `+pretty.Sprint(cliui.DefaultStyles.Field, email)+`
`+authenticationMethod+`
Create a workspace `+pretty.Sprint(cliui.DefaultStyles.Code, "coder create")+`!`)
return nil
},
}
cmd.Options = serpent.OptionSet{
{
Flag: "email",
FlagShorthand: "e",
Description: "Specifies an email address for the new user.",
Value: serpent.StringOf(&email),
},
{
Flag: "username",
FlagShorthand: "u",
Description: "Specifies a username for the new user.",
Value: serpent.Validate(serpent.StringOf(&username), func(_username *serpent.String) error {
username := _username.String()
if username != "" {
err := codersdk.NameValid(username)
if err != nil {
return xerrors.Errorf("username %q is invalid: %w", username, err)
}
}
return nil
}),
},
{
Flag: "full-name",
FlagShorthand: "n",
Description: "Specifies an optional human-readable name for the new user.",
Value: serpent.StringOf(&name),
},
{
Flag: "password",
FlagShorthand: "p",
Description: "Specifies a password for the new user.",
Value: serpent.StringOf(&password),
},
{
Flag: "disable-login",
Hidden: true,
Description: "Deprecated: Use --service-account (requires Premium) for machine-to-machine access. \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: serpent.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. "+
"Deprecated: 'none' is deprecated. Use service accounts (requires Premium) for machine-to-machine access, "+
"or password/github/oidc login types for regular user accounts.",
strings.Join([]string{
string(codersdk.LoginTypePassword), string(codersdk.LoginTypeNone), string(codersdk.LoginTypeGithub), string(codersdk.LoginTypeOIDC),
}, ", ",
)),
Value: serpent.StringOf(&loginType),
},
{
Flag: "service-account",
Description: "Create a user account intended to be used by a service or as an intermediary rather than by a human.",
Value: serpent.BoolOf(&serviceAccount),
},
}
orgContext.AttachOptions(cmd)
return cmd
}