Skip to content
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

feat(cli): add auth command (#11004) #12885

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
84 changes: 84 additions & 0 deletions cli/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package cli

import (
"fmt"
"strings"
"time"

"golang.org/x/xerrors"

"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/pretty"
"github.com/coder/serpent"
)

func (r *RootCmd) auth() *serpent.Command {
cmd := &serpent.Command{
Use: "auth <subcommand>",
Short: "Manage authentication for Coder deployment.",
Children: []*serpent.Command{
r.authStatus(),
r.authToken(),
r.login(),
},
Handler: func(inv *serpent.Invocation) error {
return inv.Command.HelpHandler(inv)
},
}
return cmd
}

func (r *RootCmd) authToken() *serpent.Command {
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "token",
Short: "Show the current session token and expiration time.",
Middleware: serpent.Chain(
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
_, err := client.User(inv.Context(), codersdk.Me)
if err != nil {
return xerrors.Errorf("get user: %w", err)
}

sessionID := strings.Split(client.SessionToken(), "-")[0]
key, err := client.APIKeyByID(inv.Context(), codersdk.Me, sessionID)
if err != nil {
return err
}

remainingHours := time.Until(key.ExpiresAt).Hours()
if remainingHours > 24 {
_, _ = fmt.Fprintf(inv.Stdout, "Your session token '%s' expires in %.1f days.\n", client.SessionToken(), remainingHours/24)
} else {
_, _ = fmt.Fprintf(inv.Stdout, "Your session token '%s' expires in %.1f hours.\n", client.SessionToken(), remainingHours)
}

return nil
},
}
return cmd
}

func (r *RootCmd) authStatus() *serpent.Command {
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "status",
Short: "Show user authentication status.",
Middleware: serpent.Chain(
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
res, err := client.User(inv.Context(), codersdk.Me)
if err != nil {
return err
}

_, _ = fmt.Fprintf(inv.Stdout, "Hello there, %s! You're authenticated at %s.\n", pretty.Sprint(cliui.DefaultStyles.Keyword, res.Username), r.clientURL)
return nil
},
}
return cmd
}
93 changes: 93 additions & 0 deletions cli/auth_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package cli_test

import (
"context"
"fmt"
"strings"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/coder/coder/v2/cli/clitest"
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/pty/ptytest"
"github.com/coder/coder/v2/testutil"
)

func TestAuthToken(t *testing.T) {
t.Parallel()
t.Run("ValidUser", func(t *testing.T) {
t.Parallel()

client := coderdtest.New(t, nil)
coderdtest.CreateFirstUser(t, client)

inv, root := clitest.New(t, "auth", "token")
clitest.SetupConfig(t, client, root)
pty := ptytest.New(t).Attach(inv)

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

split := strings.Split(client.SessionToken(), "-")
_, err := client.APIKeyByID(ctx, codersdk.Me, split[0])
require.NoError(t, err)

doneChan := make(chan struct{})
go func() {
defer close(doneChan)
err := inv.Run()
assert.NoError(t, err)
}()

// token is valid for 24 hours by default
pty.ExpectMatch(fmt.Sprintf("Your session token '%s' expires in 24.0 hours.", client.SessionToken()))
<-doneChan
})

t.Run("NoUser", func(t *testing.T) {
t.Parallel()
inv, _ := clitest.New(t, "auth", "token")

err := inv.Run()
errorMsg := "You are not logged in."
assert.ErrorContains(t, err, errorMsg)
})
}

func TestAuthStatus(t *testing.T) {
t.Parallel()
t.Run("ValidUser", func(t *testing.T) {
t.Parallel()

client := coderdtest.New(t, nil)
coderdtest.CreateFirstUser(t, client)

inv, root := clitest.New(t, "auth", "status")
clitest.SetupConfig(t, client, root)

defaultUsername := "testuser"

pty := ptytest.New(t).Attach(inv)
doneChan := make(chan struct{})
go func() {
defer close(doneChan)
err := inv.Run()
assert.NoError(t, err)
}()

pty.ExpectMatch(fmt.Sprintf("Hello there, %s! You're authenticated at %s.", defaultUsername, client.URL.String()))
<-doneChan
})

t.Run("NoUser", func(t *testing.T) {
t.Parallel()
inv, _ := clitest.New(t, "auth", "status")

err := inv.Run()
errorMsg := "You are not logged in."
assert.ErrorContains(t, err, errorMsg)
})
}
1 change: 1 addition & 0 deletions cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ const (
func (r *RootCmd) CoreSubcommands() []*serpent.Command {
// Please re-sort this list alphabetically if you change it!
return []*serpent.Command{
r.auth(),
r.dotfiles(),
r.externalAuth(),
r.login(),
Expand Down
1 change: 1 addition & 0 deletions cli/testdata/coder_--help.golden
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ USAGE:
$ coder templates init

SUBCOMMANDS:
auth Manage authentication for Coder deployment.
autoupdate Toggle auto-update policy for a workspace
config-ssh Add an SSH Host entry for your workspaces "ssh
coder.workspace"
Expand Down
14 changes: 14 additions & 0 deletions cli/testdata/coder_auth_--help.golden
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
coder v0.0.0-devel

USAGE:
coder auth <subcommand>

Manage authentication for Coder deployment.

SUBCOMMANDS:
login Authenticate with Coder deployment
status Show user authentication status.
token Show the current session token and expiration time.

———
Run `coder --help` for a list of global options.
30 changes: 30 additions & 0 deletions cli/testdata/coder_auth_login_--help.golden
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
coder v0.0.0-devel

USAGE:
coder auth login [flags] [<url>]

Authenticate with Coder deployment

OPTIONS:
--first-user-email string, $CODER_FIRST_USER_EMAIL
Specifies an email address to use if creating the first user for the
deployment.

--first-user-password string, $CODER_FIRST_USER_PASSWORD
Specifies a password to use if creating the first user for the
deployment.

--first-user-trial bool, $CODER_FIRST_USER_TRIAL
Specifies whether a trial license should be provisioned for the Coder
deployment or not.

--first-user-username string, $CODER_FIRST_USER_USERNAME
Specifies a username to use if creating the first user for the
deployment.

--use-token-as-session bool
By default, the CLI will generate a new session token when logging in.
This flag will instead use the provided token as the session token.

———
Run `coder --help` for a list of global options.
9 changes: 9 additions & 0 deletions cli/testdata/coder_auth_status_--help.golden
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
coder v0.0.0-devel

USAGE:
coder auth status

Show user authentication status.

———
Run `coder --help` for a list of global options.
9 changes: 9 additions & 0 deletions cli/testdata/coder_auth_token_--help.golden
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
coder v0.0.0-devel

USAGE:
coder auth token

Show the current session token and expiration time.

———
Run `coder --help` for a list of global options.
2 changes: 1 addition & 1 deletion codersdk/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ func (c *Client) SessionToken() string {
return c.sessionToken
}

// SetSessionToken returns the currently set token for the client.
// SetSessionToken sets sessionToken for the client.
func (c *Client) SetSessionToken(token string) {
c.mu.Lock()
defer c.mu.Unlock()
Expand Down
1 change: 1 addition & 0 deletions docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ Coder — A tool for provisioning self-hosted development environments with Terr

| Name | Purpose |
| ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------- |
| [<code>auth</code>](./cli/auth.md) | Manage authentication for Coder deployment. |
| [<code>dotfiles</code>](./cli/dotfiles.md) | Personalize your workspace by applying a canonical dotfiles repository |
| [<code>external-auth</code>](./cli/external-auth.md) | Manage external authentication |
| [<code>login</code>](./cli/login.md) | Authenticate with Coder deployment |
Expand Down
19 changes: 19 additions & 0 deletions docs/cli/auth.md

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

57 changes: 57 additions & 0 deletions docs/cli/auth_login.md

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

11 changes: 11 additions & 0 deletions docs/cli/auth_status.md

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

11 changes: 11 additions & 0 deletions docs/cli/auth_token.md

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