Compare commits

...

6 Commits

Author SHA1 Message Date
elasticspoon a6f044c3f0
Merge b152653332 into 13dd526f11 2024-05-03 22:12:10 +00:00
Colin Adler 13dd526f11
fix: prevent stdlib logging from messing up ssh (#13161)
Fixes https://github.com/coder/coder/issues/13144
2024-05-03 22:12:06 +00:00
recanman b20c63c185
fix: install openrc service on alpine (#12294) (#12870)
* fix: install openrc service on alpine (#12294)

* fmt

---------

Co-authored-by: Kyle Carberry <kyle@coder.com>
2024-05-03 21:09:23 +00:00
Michael Brewer 060f023174
feat: mask coder login token to enhance security (#12948)
* feat(login): treat coder token as a secret

* Update login.go
2024-05-03 17:03:13 -04:00
elasticspoon b152653332 fixup!: review changes
Change language in commands
Humanize session token remaining time
Inline auth middleware
2024-04-24 19:59:00 -04:00
elasticspoon f554cd2463 feat(cli): add auth command (#11004)
Adds `coder auth` command with 3 sub-commands: `coder auth token`,
`coder auth status` and `coder auth login`.

`coder auth login`: This is the same command as `coder login`.

`coder auth status`: Informs the user about their authentication
status. It may make sense for this to not show an error
if called when user is not logged in.

`coder auth token`: Informs the user of their token string
and the expiration time of the token.

All the commands use a middleware to check that the user is
authenticated and will return an error if the user is not. They also
make at most 2 API calls.

The commands have additional values that could be shown but are not with
this implementation.
2024-04-06 20:14:23 -04:00
22 changed files with 483 additions and 4 deletions

84
cli/auth.go Normal file
View File

@ -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
cli/auth_test.go Normal file
View File

@ -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)
})
}

View File

@ -287,7 +287,8 @@ func (r *RootCmd) login() *serpent.Command {
}
sessionToken, err = cliui.Prompt(inv, cliui.PromptOptions{
Text: "Paste your token here:",
Text: "Paste your token here:",
Secret: true,
Validate: func(token string) error {
client.SetSessionToken(token)
_, err := client.User(ctx, codersdk.Me)

View File

@ -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(),

View File

@ -1441,7 +1441,7 @@ func newProvisionerDaemon(
connector[string(database.ProvisionerTypeTerraform)] = sdkproto.NewDRPCProvisionerClient(terraformClient)
default:
return nil, fmt.Errorf("unknown provisioner type %q", provisionerType)
return nil, xerrors.Errorf("unknown provisioner type %q", provisionerType)
}
}

View File

@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
@ -79,6 +80,10 @@ func (r *RootCmd) ssh() *serpent.Command {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// Prevent unnecessary logs from the stdlib from messing up the TTY.
// See: https://github.com/coder/coder/issues/13144
log.SetOutput(io.Discard)
logger := inv.Logger
defer func() {
if retErr != nil {

View File

@ -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"

14
cli/testdata/coder_auth_--help.golden vendored Normal file
View File

@ -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.

View File

@ -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.

View File

@ -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.

View File

@ -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.

View File

@ -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()

View File

@ -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 |

19
docs/cli/auth.md generated Normal file
View File

@ -0,0 +1,19 @@
<!-- DO NOT EDIT | GENERATED CONTENT -->
# auth
Manage authentication for Coder deployment.
## Usage
```console
coder auth <subcommand>
```
## Subcommands
| Name | Purpose |
| --------------------------------------- | --------------------------------------------------- |
| [<code>status</code>](./auth_status.md) | Show user authentication status. |
| [<code>token</code>](./auth_token.md) | Show the current session token and expiration time. |
| [<code>login</code>](./auth_login.md) | Authenticate with Coder deployment |

57
docs/cli/auth_login.md generated Normal file
View File

@ -0,0 +1,57 @@
<!-- DO NOT EDIT | GENERATED CONTENT -->
# auth login
Authenticate with Coder deployment
## Usage
```console
coder auth login [flags] [<url>]
```
## Options
### --first-user-email
| | |
| ----------- | ------------------------------------ |
| Type | <code>string</code> |
| Environment | <code>$CODER_FIRST_USER_EMAIL</code> |
Specifies an email address to use if creating the first user for the deployment.
### --first-user-username
| | |
| ----------- | --------------------------------------- |
| Type | <code>string</code> |
| Environment | <code>$CODER_FIRST_USER_USERNAME</code> |
Specifies a username to use if creating the first user for the deployment.
### --first-user-password
| | |
| ----------- | --------------------------------------- |
| Type | <code>string</code> |
| Environment | <code>$CODER_FIRST_USER_PASSWORD</code> |
Specifies a password to use if creating the first user for the deployment.
### --first-user-trial
| | |
| ----------- | ------------------------------------ |
| Type | <code>bool</code> |
| Environment | <code>$CODER_FIRST_USER_TRIAL</code> |
Specifies whether a trial license should be provisioned for the Coder deployment or not.
### --use-token-as-session
| | |
| ---- | ----------------- |
| Type | <code>bool</code> |
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.

11
docs/cli/auth_status.md generated Normal file
View File

@ -0,0 +1,11 @@
<!-- DO NOT EDIT | GENERATED CONTENT -->
# auth status
Show user authentication status.
## Usage
```console
coder auth status
```

11
docs/cli/auth_token.md generated Normal file
View File

@ -0,0 +1,11 @@
<!-- DO NOT EDIT | GENERATED CONTENT -->
# auth token
Show the current session token and expiration time.
## Usage
```console
coder auth token
```

View File

@ -612,6 +612,26 @@
"path": "./cli.md",
"icon_path": "./images/icons/terminal.svg",
"children": [
{
"title": "auth",
"description": "Manage authentication for Coder deployment.",
"path": "cli/auth.md"
},
{
"title": "auth login",
"description": "Authenticate with Coder deployment",
"path": "cli/auth_login.md"
},
{
"title": "auth status",
"description": "Show user authentication status.",
"path": "cli/auth_status.md"
},
{
"title": "auth token",
"description": "Show the current session token and expiration time.",
"path": "cli/auth_token.md"
},
{
"title": "autoupdate",
"description": "Toggle auto-update policy for a workspace",

38
scripts/linux-pkg/coder-openrc Executable file
View File

@ -0,0 +1,38 @@
#!/sbin/openrc-run
name=coder
description="Coder - Self-hosted developer workspaces on your infra"
document="https://coder.com/docs/coder-oss"
depend() {
need net
after net-online
use dns logger
}
checkpath --directory --owner coder:coder --mode 0700 /var/cache/coder
start_pre() {
if [ ! -f /etc/coder.d/coder.env ]; then
eerror "/etc/coder.d/coder.env file does not exist"
return 1
fi
# Read and export environment variables ignoring comment lines and blank lines
while IFS= read -r line; do
# Skip blank or comment lines
if [ -z "$line" ] || [[ "$line" =~ ^# ]]; then
continue
fi
export "$line"
done < /etc/coder.d/coder.env
}
command="/usr/bin/coder"
command_args="server"
command_user="coder:coder"
command_background="yes"
pidfile="/run/coder.pid"
restart="always"
restart_delay="5"
stop_timeout="90"

View File

@ -0,0 +1,39 @@
#!/sbin/openrc-run
name=coder-workspace-proxy
description="Coder - external workspace proxy server"
document="https://coder.com/docs/coder-oss"
depend() {
need net
after net-online
use dns logger
}
checkpath --directory --owner coder:coder --mode 0700 /var/cache/coder
start_pre() {
if [ ! -f /etc/coder.d/coder-workspace-proxy.env ]; then
eerror "/etc/coder.d/coder-workspace-proxy.env file does not exist"
return 1
fi
# Read and export environment variables ignoring comment lines and blank lines
while IFS= read -r line; do
# Skip blank or comment lines
if [ -z "$line" ] || [[ "$line" =~ ^# ]]; then
continue
fi
export "$line"
done < /etc/coder.d/coder-workspace-proxy.env
}
command="/usr/bin/coder"
command_args="workspace-proxy server"
command_user="coder:coder"
command_background="yes"
pidfile="/run/coder-workspace-proxy.pid"
restart="always"
restart_delay="5"
stop_timeout="90"

View File

@ -0,0 +1,29 @@
name: coder
platform: linux
arch: "${GOARCH}"
version: "${CODER_VERSION}"
version_schema: semver
release: 1
vendor: Coder
homepage: https://coder.com
maintainer: Coder <support@coder.com>
description: |
Provision development environments with infrastructure with code
license: AGPL-3.0
suggests:
- postgresql
scripts:
preinstall: preinstall.sh
contents:
- src: coder
dst: /usr/bin/coder
- src: coder.env
dst: /etc/coder.d/coder.env
type: "config|noreplace"
- src: coder-workspace-proxy-openrc
dst: /etc/init.d/coder-workspace-proxy
- src: coder-openrc
dst: /etc/init.d/coder

View File

@ -89,9 +89,16 @@ ln "$(realpath scripts/linux-pkg/coder.service)" "$temp_dir/"
ln "$(realpath scripts/linux-pkg/nfpm.yaml)" "$temp_dir/"
ln "$(realpath scripts/linux-pkg/preinstall.sh)" "$temp_dir/"
nfpm_config_file="nfpm.yaml"
# Use nfpm-alpine.yaml when building for Alpine (OpenRC).
if [[ "$format" == "apk" ]]; then
nfpm_config_file="nfpm-alpine.yaml"
fi
pushd "$temp_dir"
GOARCH="$arch" CODER_VERSION="$version" nfpm package \
-f nfpm.yaml \
-f "$nfpm_config_file" \
-p "$format" \
-t "$output_path" \
1>&2