Skip to content

feat: create a token for another user via cli #13424

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

Closed
wants to merge 4 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 30 additions & 9 deletions cli/tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ func (r *RootCmd) createToken() *serpent.Command {
var (
tokenLifetime time.Duration
name string
user string
)
client := new(codersdk.Client)
cmd := &serpent.Command{
Expand All @@ -58,16 +59,29 @@ func (r *RootCmd) createToken() *serpent.Command {
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
res, err := client.CreateToken(inv.Context(), codersdk.Me, codersdk.CreateTokenRequest{
Lifetime: tokenLifetime,
TokenName: name,
})
if err != nil {
return xerrors.Errorf("create tokens: %w", err)
userID := codersdk.Me
if user != "" {
userID = user
adminID := codersdk.Me
res, err := client.CreateTokenForUser(inv.Context(), adminID, userID, codersdk.CreateTokenRequest{
Lifetime: tokenLifetime,
TokenName: name,
})
if err != nil {
return xerrors.Errorf("create tokens for user %s: %w", user, err)
}
_, _ = fmt.Fprintln(inv.Stdout, res.Key) // Print the token to stdout
} else {
// Otherwise, create a token for the current user
res, err := client.CreateToken(inv.Context(), userID, codersdk.CreateTokenRequest{
Lifetime: tokenLifetime,
TokenName: name,
})
if err != nil {
return xerrors.Errorf("create tokens: %w", err)
}
_, _ = fmt.Fprintln(inv.Stdout, res.Key) // Print the token to stdout
}

_, _ = fmt.Fprintln(inv.Stdout, res.Key)

return nil
},
}
Expand All @@ -87,6 +101,13 @@ func (r *RootCmd) createToken() *serpent.Command {
Description: "Specify a human-readable name.",
Value: serpent.StringOf(&name),
},
{
Flag: "user",
FlagShorthand: "u",
Env: "CODER_TOKEN_USER",
Description: "create a token on behalf of another user",
Value: serpent.StringOf(&name),
},
}

return cmd
Expand Down
10 changes: 10 additions & 0 deletions cli/tokens_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,16 @@ func TestTokens(t *testing.T) {
require.NotEmpty(t, res)
id := res[:10]

inv, root = clitest.New(t, "tokens", "create", "-u", "user-one")
clitest.SetupConfig(t, client, root)
buf = new(bytes.Buffer)
inv.Stdout = buf
err = inv.WithContext(ctx).Run()
require.NoError(t, err)
res = buf.String()
require.NotEmpty(t, res)


inv, root = clitest.New(t, "tokens", "ls")
clitest.SetupConfig(t, client, root)
buf = new(bytes.Buffer)
Expand Down
39 changes: 39 additions & 0 deletions codersdk/apikey.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,45 @@ func (c *Client) CreateToken(ctx context.Context, userID string, req CreateToken
return apiKey, json.NewDecoder(res.Body).Decode(&apiKey)
}


// CreateTokenForUser allows an admin to create a token on behalf of another user.
func (c *Client) CreateTokenForUser(ctx context.Context, adminID, targetUserID string, req CreateTokenRequest) (GenerateAPIKeyResponse, error) {
isAdmin, err := c.isAdmin(ctx, adminID)
if err != nil {
return GenerateAPIKeyResponse{}, fmt.Errorf("admin check failed: %w", err)
}
if !isAdmin {
return GenerateAPIKeyResponse{}, fmt.Errorf("user %s is not an admin", adminID)
}
if adminID == targetUserID {
return GenerateAPIKeyResponse{}, fmt.Errorf("admin cannot create a token for themselves")
}
return c.CreateToken(ctx, targetUserID, req)
}

// isAdmin is a placeholder function to check if a user is an admin.
func (c *Client) isAdmin(ctx context.Context, userID string) (bool, error) {
res, err := c.Request(ctx, http.MethodGet, fmt.Sprintf("/api/v2/users/%s/keys", userID), nil)
if err != nil {
return false, fmt.Errorf("unable to get user : %s", userID)
}
defer res.Body.Close()
if res.StatusCode > http.StatusCreated {
return false, ReadBodyAsError(res)
}
//extract roles, when the API returns roles from the response, ensuring system admin privileges
var roles []string
if err := json.NewDecoder(res.Body).Decode(&roles); err != nil {
return false, fmt.Errorf("failed to decode roles: %w", err)
}
for _, role := range roles {
if role == "admin" {
return true, nil
}
}
return false, nil
}
Comment on lines +97 to +118
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We shouldn't perform intermediary checks in our API package.

Ideally, our API returns a friendly error indicating that the user isn't an admin, which reduces the number of requests required as well.


// CreateAPIKey generates an API key for the user ID provided.
// CreateToken should be used over CreateAPIKey. CreateToken allows better
// tracking of the token's usage and allows for custom expiration.
Expand Down
32 changes: 19 additions & 13 deletions pnpm-lock.yaml

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

Loading