2023-02-07 01:58:21 +11:00
//go:build !slim
package cli
import (
2026-06-02 08:36:01 -06:00
"database/sql"
2023-02-07 01:58:21 +11:00
"fmt"
"sort"
"github.com/google/uuid"
"golang.org/x/xerrors"
2026-01-08 10:29:41 +04:00
"cdr.dev/slog/v3"
"cdr.dev/slog/v3/sloggers/sloghuman"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/coderd/database"
2024-03-20 13:14:43 -04:00
"github.com/coder/coder/v2/coderd/database/awsiamrds"
2023-09-01 19:50:12 +03:00
"github.com/coder/coder/v2/coderd/database/dbtime"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/gitsshkey"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/coderd/userpassword"
"github.com/coder/coder/v2/codersdk"
2024-03-15 11:24:38 -05:00
"github.com/coder/serpent"
2023-02-07 01:58:21 +11:00
)
2026-09-30 12:36:05 -04:00
type organizationMembership struct {
OrganizationID uuid . UUID `json:"organization_id"`
OrganizationName string `json:"organization_name"`
Roles [] string `json:"roles"`
}
// createAdminUserResponse never includes the password. This command talks to
// the database directly, so there is no codersdk type to reuse.
type createAdminUserResponse struct {
ID uuid . UUID `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Roles [] string `json:"roles"`
Organizations [] organizationMembership `json:"organizations"`
}
2024-03-17 09:45:26 -05:00
func ( r * RootCmd ) newCreateAdminUserCommand () * serpent . Command {
2023-02-07 01:58:21 +11:00
var (
newUserDBURL string
2024-03-20 13:14:43 -04:00
newUserPgAuth string
2023-02-07 01:58:21 +11:00
newUserSSHKeygenAlgorithm string
newUserUsername string
newUserEmail string
newUserPassword string
2026-09-30 12:36:05 -04:00
formatter = cliui . NewOutputFormatter (
cliui . ChangeFormatterData ( cliui . TextFormat (), func ( data any ) ( any , error ) {
typed , ok := data .( createAdminUserResponse )
if ! ok {
return "" , xerrors . Errorf ( "expected createAdminUserResponse, got %T" , data )
}
return fmt . Sprintf (
"\nUser created successfully.\nID: %s\nUsername: %s\nEmail: %s\nPassword: ********\n" ,
typed . ID , typed . Username , typed . Email ,
), nil
}),
cliui . JSONFormat (),
)
2023-02-07 01:58:21 +11:00
)
2024-03-17 09:45:26 -05:00
createAdminUserCommand := & serpent . Command {
2023-02-07 01:58:21 +11:00
Use : "create-admin-user" ,
Short : "Create a new admin user with the given username, email and password and adds it to every organization." ,
2024-03-15 11:24:38 -05:00
Handler : func ( inv * serpent . Invocation ) error {
2023-03-23 17:42:20 -05:00
ctx := inv . Context ()
2023-02-07 01:58:21 +11:00
sshKeygenAlgorithm , err := gitsshkey . ParseAlgorithm ( newUserSSHKeygenAlgorithm )
if err != nil {
return xerrors . Errorf ( "parse ssh keygen algorithm %q: %w" , newUserSSHKeygenAlgorithm , err )
}
2023-03-23 17:42:20 -05:00
cfg := r . createConfig ()
2023-11-14 22:56:27 +04:00
logger := inv . Logger . AppendSinks ( sloghuman . Sink ( inv . Stderr ))
2023-03-23 17:42:20 -05:00
if r . verbose {
2023-02-07 01:58:21 +11:00
logger = logger . Leveled ( slog . LevelDebug )
}
2024-03-15 14:16:36 +01:00
ctx , cancel := inv . SignalNotifyContext ( ctx , StopSignals ... )
2023-02-07 01:58:21 +11:00
defer cancel ()
if newUserDBURL == "" {
2023-08-13 11:48:11 -05:00
cliui . Infof ( inv . Stdout , "Using built-in PostgreSQL (%s)" , cfg . PostgresPath ())
2025-01-20 14:31:16 +01:00
url , closePg , err := startBuiltinPostgres ( ctx , cfg , logger , "" )
2023-02-07 01:58:21 +11:00
if err != nil {
return err
}
defer func () {
_ = closePg ()
}()
newUserDBURL = url
}
2024-03-20 13:14:43 -04:00
sqlDriver := "postgres"
if codersdk . PostgresAuth ( newUserPgAuth ) == codersdk . PostgresAuthAWSIAMRDS {
sqlDriver , err = awsiamrds . Register ( inv . Context (), sqlDriver )
if err != nil {
return xerrors . Errorf ( "register aws rds iam auth: %w" , err )
}
}
2025-01-03 12:15:35 -05:00
sqlDB , err := ConnectToPostgres ( ctx , logger , sqlDriver , newUserDBURL , nil )
2023-02-07 01:58:21 +11:00
if err != nil {
return xerrors . Errorf ( "connect to postgres: %w" , err )
}
defer func () {
_ = sqlDB . Close ()
}()
db := database . New ( sqlDB )
validateInputs := func ( username , email , password string ) error {
// Use the validator tags so we match the API's validation.
2024-08-23 16:23:51 -05:00
req := codersdk . CreateUserRequestWithOrgs {
Username : "username" ,
Name : "Admin User" ,
Email : "email@coder.com" ,
Password : "ValidPa$$word123!" ,
OrganizationIDs : [] uuid . UUID { uuid . New ()},
2023-02-07 01:58:21 +11:00
}
if username != "" {
req . Username = username
}
if email != "" {
req . Email = email
}
if password != "" {
req . Password = password
}
return httpapi . Validate . Struct ( req )
}
if newUserUsername == "" {
2023-03-23 17:42:20 -05:00
newUserUsername , err = cliui . Prompt ( inv , cliui . PromptOptions {
2023-02-07 01:58:21 +11:00
Text : "Username" ,
Validate : func ( val string ) error {
if val == "" {
return xerrors . New ( "username cannot be empty" )
}
return validateInputs ( val , "" , "" )
},
})
if err != nil {
return err
}
}
2024-06-26 09:00:42 +01:00
2023-02-07 01:58:21 +11:00
if newUserEmail == "" {
2023-03-23 17:42:20 -05:00
newUserEmail , err = cliui . Prompt ( inv , cliui . PromptOptions {
2023-02-07 01:58:21 +11:00
Text : "Email" ,
Validate : func ( val string ) error {
if val == "" {
return xerrors . New ( "email cannot be empty" )
}
return validateInputs ( "" , val , "" )
},
})
if err != nil {
return err
}
}
if newUserPassword == "" {
2023-03-23 17:42:20 -05:00
newUserPassword , err = cliui . Prompt ( inv , cliui . PromptOptions {
2023-02-07 01:58:21 +11:00
Text : "Password" ,
Secret : true ,
Validate : func ( val string ) error {
if val == "" {
return xerrors . New ( "password cannot be empty" )
}
return validateInputs ( "" , "" , val )
},
})
if err != nil {
return err
}
// Prompt again.
2023-03-23 17:42:20 -05:00
_ , err = cliui . Prompt ( inv , cliui . PromptOptions {
2023-02-07 01:58:21 +11:00
Text : "Confirm password" ,
Secret : true ,
Validate : func ( val string ) error {
if val != newUserPassword {
return xerrors . New ( "passwords do not match" )
}
return nil
},
})
if err != nil {
return err
}
}
err = validateInputs ( newUserUsername , newUserEmail , newUserPassword )
if err != nil {
return xerrors . Errorf ( "validate inputs: %w" , err )
}
hashedPassword , err := userpassword . Hash ( newUserPassword )
if err != nil {
return xerrors . Errorf ( "hash password: %w" , err )
}
// Create the user.
var newUser database . User
2026-09-30 12:36:05 -04:00
var memberships [] organizationMembership
2023-02-07 01:58:21 +11:00
err = db . InTx ( func ( tx database . Store ) error {
2024-08-28 13:24:28 -05:00
orgs , err := tx . GetOrganizations ( ctx , database . GetOrganizationsParams {})
2023-02-07 01:58:21 +11:00
if err != nil {
return xerrors . Errorf ( "get organizations: %w" , err )
}
// Sort organizations by name so that test output is consistent.
sort . Slice ( orgs , func ( i , j int ) bool {
return orgs [ i ]. Name < orgs [ j ]. Name
})
2023-03-23 17:42:20 -05:00
_ , _ = fmt . Fprintln ( inv . Stderr , "Creating user..." )
2023-02-07 01:58:21 +11:00
newUser , err = tx . InsertUser ( ctx , database . InsertUserParams {
2026-03-11 10:19:08 -07:00
ID : uuid . New (),
Email : newUserEmail ,
Username : newUserUsername ,
Name : "Admin User" ,
HashedPassword : [] byte ( hashedPassword ),
CreatedAt : dbtime . Now (),
UpdatedAt : dbtime . Now (),
RBACRoles : [] string { rbac . RoleOwner (). String ()},
LoginType : database . LoginTypePassword ,
Status : "" ,
IsServiceAccount : false ,
2023-02-07 01:58:21 +11:00
})
if err != nil {
return xerrors . Errorf ( "insert user: %w" , err )
}
2023-03-23 17:42:20 -05:00
_ , _ = fmt . Fprintln ( inv . Stderr , "Generating user SSH key..." )
2023-02-07 01:58:21 +11:00
privateKey , publicKey , err := gitsshkey . Generate ( sshKeygenAlgorithm )
if err != nil {
return xerrors . Errorf ( "generate user gitsshkey: %w" , err )
}
_ , err = tx . InsertGitSSHKey ( ctx , database . InsertGitSSHKeyParams {
2026-06-02 08:36:01 -06:00
UserID : newUser . ID ,
CreatedAt : dbtime . Now (),
UpdatedAt : dbtime . Now (),
PrivateKey : privateKey ,
PrivateKeyKeyID : sql . NullString {}, // Plaintext; this CLI bypasses dbcrypt. Encrypted on next rotate.
PublicKey : publicKey ,
2023-02-07 01:58:21 +11:00
})
if err != nil {
return xerrors . Errorf ( "insert user gitsshkey: %w" , err )
}
for _ , org := range orgs {
2023-03-23 17:42:20 -05:00
_ , _ = fmt . Fprintf ( inv . Stderr , "Adding user to organization %q (%s) as admin...\n" , org . Name , org . ID . String ())
2026-09-30 12:36:05 -04:00
roles := [] string { rbac . RoleOrgAdmin ()}
2023-02-07 01:58:21 +11:00
_ , err := tx . InsertOrganizationMember ( ctx , database . InsertOrganizationMemberParams {
OrganizationID : org . ID ,
UserID : newUser . ID ,
2023-09-01 19:50:12 +03:00
CreatedAt : dbtime . Now (),
UpdatedAt : dbtime . Now (),
2026-09-30 12:36:05 -04:00
Roles : roles ,
2023-02-07 01:58:21 +11:00
})
if err != nil {
return xerrors . Errorf ( "insert organization member: %w" , err )
}
2026-09-30 12:36:05 -04:00
memberships = append ( memberships , organizationMembership {
OrganizationID : org . ID ,
OrganizationName : org . Name ,
Roles : roles ,
})
2023-02-07 01:58:21 +11:00
}
return nil
}, nil )
if err != nil {
return err
}
2026-09-30 12:36:05 -04:00
out , err := formatter . Format ( ctx , createAdminUserResponse {
ID : newUser . ID ,
Username : newUser . Username ,
Email : newUser . Email ,
Roles : newUser . RBACRoles ,
Organizations : memberships ,
})
if err != nil {
return err
}
if formatter . FormatID () == "json" {
_ , err = fmt . Fprintln ( inv . Stdout , out )
} else {
_ , err = fmt . Fprint ( inv . Stderr , out )
}
return err
2023-02-07 01:58:21 +11:00
},
}
2023-03-23 17:42:20 -05:00
createAdminUserCommand . Options . Add (
2024-03-15 11:24:38 -05:00
serpent . Option {
2023-06-01 15:02:29 -08:00
Env : "CODER_PG_CONNECTION_URL" ,
2023-03-23 17:42:20 -05:00
Flag : "postgres-url" ,
Description : "URL of a PostgreSQL database. If empty, the built-in PostgreSQL deployment will be used (Coder must not be already running in this case)." ,
2024-03-15 11:24:38 -05:00
Value : serpent . StringOf ( & newUserDBURL ),
2023-03-23 17:42:20 -05:00
},
2024-03-20 13:14:43 -04:00
serpent . Option {
Name : "Postgres Connection Auth" ,
Description : "Type of auth to use when connecting to postgres." ,
Flag : "postgres-connection-auth" ,
Env : "CODER_PG_CONNECTION_AUTH" ,
Default : "password" ,
Value : serpent . EnumOf ( & newUserPgAuth , codersdk . PostgresAuthDrivers ... ),
},
2024-03-15 11:24:38 -05:00
serpent . Option {
2023-03-23 17:42:20 -05:00
Env : "CODER_SSH_KEYGEN_ALGORITHM" ,
Flag : "ssh-keygen-algorithm" ,
Description : "The algorithm to use for generating ssh keys. Accepted values are \"ed25519\", \"ecdsa\", or \"rsa4096\"." ,
Default : "ed25519" ,
2024-03-15 11:24:38 -05:00
Value : serpent . StringOf ( & newUserSSHKeygenAlgorithm ),
2023-03-23 17:42:20 -05:00
},
2024-03-15 11:24:38 -05:00
serpent . Option {
2023-03-23 17:42:20 -05:00
Env : "CODER_USERNAME" ,
Flag : "username" ,
Description : "The username of the new user. If not specified, you will be prompted via stdin." ,
2024-03-15 11:24:38 -05:00
Value : serpent . StringOf ( & newUserUsername ),
2023-03-23 17:42:20 -05:00
},
2024-03-15 11:24:38 -05:00
serpent . Option {
2023-03-23 17:42:20 -05:00
Env : "CODER_EMAIL" ,
Flag : "email" ,
Description : "The email of the new user. If not specified, you will be prompted via stdin." ,
2024-03-15 11:24:38 -05:00
Value : serpent . StringOf ( & newUserEmail ),
2023-03-23 17:42:20 -05:00
},
2024-03-15 11:24:38 -05:00
serpent . Option {
2023-03-23 17:42:20 -05:00
Env : "CODER_PASSWORD" ,
Flag : "password" ,
Description : "The password of the new user. If not specified, you will be prompted via stdin." ,
2024-03-15 11:24:38 -05:00
Value : serpent . StringOf ( & newUserPassword ),
2023-03-23 17:42:20 -05:00
},
)
2026-09-30 12:36:05 -04:00
formatter . AttachOptions ( & createAdminUserCommand . Options )
2023-02-07 01:58:21 +11:00
return createAdminUserCommand
}