Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

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

import (
"encoding/csv"
"strings"

"github.com/spf13/pflag"
"golang.org/x/xerrors"

"github.com/coder/coder/v2/codersdk"
)

var (
_ pflag.SliceValue = &AllowListFlag{}
_ pflag.Value = &AllowListFlag{}
)

// AllowListFlag implements pflag.SliceValue for codersdk.APIAllowListTarget entries.
type AllowListFlag []codersdk.APIAllowListTarget

func AllowListFlagOf(al *[]codersdk.APIAllowListTarget) *AllowListFlag {
return (*AllowListFlag)(al)
}

func (a AllowListFlag) String() string {
return strings.Join(a.GetSlice(), ",")
}

func (a AllowListFlag) Value() []codersdk.APIAllowListTarget {
return []codersdk.APIAllowListTarget(a)
}

func (AllowListFlag) Type() string { return "allow-list" }

func (a *AllowListFlag) Set(set string) error {
values, err := csv.NewReader(strings.NewReader(set)).Read()
if err != nil {
return xerrors.Errorf("parse allow list entries as csv: %w", err)
}
for _, v := range values {
if err := a.Append(v); err != nil {
return err
}
}
return nil
}

func (a *AllowListFlag) Append(value string) error {
value = strings.TrimSpace(value)
if value == "" {
return xerrors.New("allow list entry cannot be empty")
}
var target codersdk.APIAllowListTarget
if err := target.UnmarshalText([]byte(value)); err != nil {
return err
}

*a = append(*a, target)
return nil
}

func (a *AllowListFlag) Replace(items []string) error {
*a = []codersdk.APIAllowListTarget{}
for _, item := range items {
if err := a.Append(item); err != nil {
return err
}
}
return nil
}

func (a *AllowListFlag) GetSlice() []string {
out := make([]string, len(*a))
for i, entry := range *a {
out[i] = entry.String()
}
return out
}
5 changes: 5 additions & 0 deletions cli/testdata/coder_tokens_--help.golden
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ USAGE:

$ coder tokens ls

- Create a scoped token:

$ coder tokens create --scope workspace:read --allow workspace:<uuid>

- Remove a token by ID:

$ coder tokens rm WuoWs4ZsMX
Expand All @@ -24,6 +28,7 @@ SUBCOMMANDS:
create Create a token
list List tokens
remove Delete a token
view Display detailed information about a token

———
Run `coder --help` for a list of global options.
6 changes: 6 additions & 0 deletions cli/testdata/coder_tokens_create_--help.golden
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,18 @@ USAGE:
Create a token

OPTIONS:
--allow allow-list
Repeatable allow-list entry (<type>:<uuid>, e.g. workspace:1234-...).

--lifetime string, $CODER_TOKEN_LIFETIME
Specify a duration for the lifetime of the token.

-n, --name string, $CODER_TOKEN_NAME
Specify a human-readable name.

--scope string-array
Repeatable scope to attach to the token (e.g. workspace:read).

-u, --user string, $CODER_TOKEN_USER
Specify the user to create the token for (Only works if logged in user
is admin).
Expand Down
2 changes: 1 addition & 1 deletion cli/testdata/coder_tokens_list_--help.golden
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ OPTIONS:
Specifies whether all users' tokens will be listed or not (must have
Owner role to see all tokens).

-c, --column [id|name|last used|expires at|created at|owner] (default: id,name,last used,expires at,created at)
-c, --column [id|name|scopes|allow list|last used|expires at|created at|owner] (default: id,name,scopes,allow list,last used,expires at,created at)
Columns to display in table output.

-o, --output table|json (default: table)
Expand Down
16 changes: 16 additions & 0 deletions cli/testdata/coder_tokens_view_--help.golden
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
coder v0.0.0-devel

USAGE:
coder tokens view [flags] <name|id>

Display detailed information about a token

OPTIONS:
-c, --column [id|name|scopes|allow list|last used|expires at|created at|owner] (default: id,name,scopes,allow list,last used,expires at,created at,owner)
Columns to display in table output.

-o, --output table|json (default: table)
Output format.

———
Run `coder --help` for a list of global options.
108 changes: 103 additions & 5 deletions cli/tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@ import (
"fmt"
"os"
"slices"
"sort"
"strings"
"time"

"golang.org/x/xerrors"

"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/coderd/util/slice"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/serpent"
)
Expand All @@ -27,6 +29,10 @@ func (r *RootCmd) tokens() *serpent.Command {
Description: "List your tokens",
Command: "coder tokens ls",
},
Example{
Description: "Create a scoped token",
Command: "coder tokens create --scope workspace:read --allow workspace:<uuid>",
},
Example{
Description: "Remove a token by ID",
Command: "coder tokens rm WuoWs4ZsMX",
Expand All @@ -39,6 +45,7 @@ func (r *RootCmd) tokens() *serpent.Command {
Children: []*serpent.Command{
r.createToken(),
r.listTokens(),
r.viewToken(),
r.removeToken(),
},
}
Expand All @@ -50,6 +57,8 @@ func (r *RootCmd) createToken() *serpent.Command {
tokenLifetime string
name string
user string
scopes []string
allowList []codersdk.APIAllowListTarget
)
cmd := &serpent.Command{
Use: "create",
Expand Down Expand Up @@ -88,10 +97,18 @@ func (r *RootCmd) createToken() *serpent.Command {
}
}

res, err := client.CreateToken(inv.Context(), userID, codersdk.CreateTokenRequest{
req := codersdk.CreateTokenRequest{
Lifetime: parsedLifetime,
TokenName: name,
})
}
if len(req.Scopes) == 0 {
req.Scopes = slice.StringEnums[codersdk.APIKeyScope](scopes)
}
if len(allowList) > 0 {
req.AllowList = append([]codersdk.APIAllowListTarget(nil), allowList...)
}

res, err := client.CreateToken(inv.Context(), userID, req)
if err != nil {
return xerrors.Errorf("create tokens: %w", err)
}
Expand Down Expand Up @@ -123,6 +140,16 @@ func (r *RootCmd) createToken() *serpent.Command {
Description: "Specify the user to create the token for (Only works if logged in user is admin).",
Value: serpent.StringOf(&user),
},
{
Flag: "scope",
Description: "Repeatable scope to attach to the token (e.g. workspace:read).",
Value: serpent.StringArrayOf(&scopes),
},
{
Flag: "allow",
Description: "Repeatable allow-list entry (<type>:<uuid>, e.g. workspace:1234-...).",
Value: AllowListFlagOf(&allowList),
},
}

return cmd
Expand All @@ -136,27 +163,56 @@ type tokenListRow struct {
// For table format:
ID string `json:"-" table:"id,default_sort"`
TokenName string `json:"token_name" table:"name"`
Scopes string `json:"-" table:"scopes"`
Allow string `json:"-" table:"allow list"`
LastUsed time.Time `json:"-" table:"last used"`
ExpiresAt time.Time `json:"-" table:"expires at"`
CreatedAt time.Time `json:"-" table:"created at"`
Owner string `json:"-" table:"owner"`
}

func tokenListRowFromToken(token codersdk.APIKeyWithOwner) tokenListRow {
return tokenListRowFromKey(token.APIKey, token.Username)
}

func tokenListRowFromKey(token codersdk.APIKey, owner string) tokenListRow {
return tokenListRow{
APIKey: token.APIKey,
APIKey: token,
ID: token.ID,
TokenName: token.TokenName,
Scopes: joinScopes(token.Scopes),
Allow: joinAllowList(token.AllowList),
LastUsed: token.LastUsed,
ExpiresAt: token.ExpiresAt,
CreatedAt: token.CreatedAt,
Owner: token.Username,
Owner: owner,
}
}

func joinScopes(scopes []codersdk.APIKeyScope) string {
if len(scopes) == 0 {
return ""
}
vals := slice.ToStrings(scopes)
sort.Strings(vals)
return strings.Join(vals, ", ")
}

func joinAllowList(entries []codersdk.APIAllowListTarget) string {
if len(entries) == 0 {
return ""
}
vals := make([]string, len(entries))
for i, entry := range entries {
vals[i] = entry.String()
}
sort.Strings(vals)
return strings.Join(vals, ", ")
}

func (r *RootCmd) listTokens() *serpent.Command {
// we only display the 'owner' column if the --all argument is passed in
defaultCols := []string{"id", "name", "last used", "expires at", "created at"}
defaultCols := []string{"id", "name", "scopes", "allow list", "last used", "expires at", "created at"}
if slices.Contains(os.Args, "-a") || slices.Contains(os.Args, "--all") {
defaultCols = append(defaultCols, "owner")
}
Expand Down Expand Up @@ -226,6 +282,48 @@ func (r *RootCmd) listTokens() *serpent.Command {
return cmd
}

func (r *RootCmd) viewToken() *serpent.Command {
formatter := cliui.NewOutputFormatter(
cliui.TableFormat([]tokenListRow{}, []string{"id", "name", "scopes", "allow list", "last used", "expires at", "created at", "owner"}),
cliui.JSONFormat(),
)

cmd := &serpent.Command{
Use: "view <name|id>",
Short: "Display detailed information about a token",
Middleware: serpent.Chain(
serpent.RequireNArgs(1),
),
Handler: func(inv *serpent.Invocation) error {
client, err := r.InitClient(inv)
if err != nil {
return err
}

tokenName := inv.Args[0]
token, err := client.APIKeyByName(inv.Context(), codersdk.Me, tokenName)
if err != nil {
maybeID := strings.Split(tokenName, "-")[0]
token, err = client.APIKeyByID(inv.Context(), codersdk.Me, maybeID)
if err != nil {
return xerrors.Errorf("fetch api key by name or id: %w", err)
}
}

row := tokenListRowFromKey(*token, "")
out, err := formatter.Format(inv.Context(), []tokenListRow{row})
if err != nil {
return err
}
_, err = fmt.Fprintln(inv.Stdout, out)
return err
},
}

formatter.AttachOptions(&cmd.Options)
return cmd
}

func (r *RootCmd) removeToken() *serpent.Command {
cmd := &serpent.Command{
Use: "remove <name|id|token>",
Expand Down
Loading