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
62 changes: 62 additions & 0 deletions internal/cmd/token/create_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ package token
import (
"bytes"
"context"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"

Expand Down Expand Up @@ -156,3 +159,62 @@ func TestServiceToken_CreateCmdWithTTL(t *testing.T) {
res := &ServiceTokenWithSecret{orig: orig}
c.Assert(buf.String(), qt.JSONEquals, res)
}

func TestServiceToken_DuplicateCmd(t *testing.T) {
c := qt.New(t)

var buf bytes.Buffer
format := printer.JSON
p := printer.NewPrinter(&format)
p.SetResourceOutput(&buf)

org := "planetscale"
sourceID := "123456"
name := "copy-token"
secret := "d2980bbd91a4ab878601ef0573a7af7b1b15e705"
newID := "654321"
createdAt := time.Date(2025, 1, 15, 10, 30, 0, 0, time.UTC)

var requests int
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests++
c.Assert(r.Method, qt.Equals, http.MethodPost)
c.Assert(r.URL.Path, qt.Equals, "/v1/organizations/planetscale/service-tokens/123456/duplicate")
c.Assert(r.Header.Get("Authorization"), qt.Equals, "Bearer test-token")
body, err := io.ReadAll(r.Body)
c.Assert(err, qt.IsNil)
c.Assert(string(body), qt.Equals, "{\"name\":\"copy-token\"}\n")

_, err = io.WriteString(w, `{"id":"654321","type":"ServiceToken","token":"d2980bbd91a4ab878601ef0573a7af7b1b15e705","name":"copy-token","created_at":"2025-01-15T10:30:00.000Z"}`)
c.Assert(err, qt.IsNil)
}))
t.Cleanup(ts.Close)

ch := &cmdutil.Helper{
Printer: p,
Config: &config.Config{
Organization: org,
AccessToken: "test-token",
},
Client: func() (*ps.Client, error) {
return ps.NewClient(ps.WithBaseURL(ts.URL), ps.WithAccessToken("test-token"))
},
}

cmd := TokenCmd(ch)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs([]string{"duplicate", sourceID, "--name", name, "--org", org})
c.Assert(cmd.Execute(), qt.IsNil)
c.Assert(requests, qt.Equals, 1)

tokenName := name
orig := &ps.ServiceToken{
ID: newID,
Type: "ServiceToken",
Token: secret,
Name: &tokenName,
CreatedAt: createdAt,
}
c.Assert(buf.String(), qt.JSONEquals, &ServiceTokenWithSecret{orig: orig})
}
58 changes: 58 additions & 0 deletions internal/cmd/token/duplicate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package token

import (
"fmt"

"github.com/planetscale/cli/internal/cmdutil"
"github.com/planetscale/cli/internal/planetscale"
"github.com/planetscale/cli/internal/printer"
"github.com/spf13/cobra"
)

func DuplicateCmd(ch *cmdutil.Helper) *cobra.Command {
var name string

cmd := &cobra.Command{
Use: "duplicate <id>",
Short: "duplicate a service token in the organization",
Args: cmdutil.RequiredArgs("id"),
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
client, err := ch.Client()
if err != nil {
return err
}

id := args[0]
req := &planetscale.DuplicateServiceTokenRequest{
Organization: ch.Config.Organization,
ID: id,
Name: name,
}

end := ch.Printer.PrintProgress(fmt.Sprintf("Duplicating service token %s in org %s",
printer.BoldBlue(id), printer.BoldBlue(ch.Config.Organization)))
defer end()

token, err := client.ServiceTokens.Duplicate(ctx, req)
if err != nil {
switch cmdutil.ErrCode(err) {
case planetscale.ErrNotFound:
return fmt.Errorf("service token %s does not exist in organization %s",
printer.BoldBlue(id), printer.BoldBlue(ch.Config.Organization))
default:
return cmdutil.HandleError(err)
}
}

end()

return ch.Printer.PrintResource(toServiceTokenWithSecret(token))
},
}

cmd.Flags().StringVar(&name, "name", "", "name for the duplicated service token")
cmd.MarkFlagRequired("name") // nolint:errcheck

return cmd
}
1 change: 1 addition & 0 deletions internal/cmd/token/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ func TokenCmd(ch *cmdutil.Helper) *cobra.Command {
cmd.MarkPersistentFlagRequired("org") // nolint:errcheck

cmd.AddCommand(CreateCmd(ch))
cmd.AddCommand(DuplicateCmd(ch))
cmd.AddCommand(ListCmd(ch))
cmd.AddCommand(ShowCmd(ch))
cmd.AddCommand(ShowAccessCmd(ch))
Expand Down
8 changes: 8 additions & 0 deletions internal/mock/servicetoken.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ type ServiceTokenService struct {
CreateFn func(context.Context, *ps.CreateServiceTokenRequest) (*ps.ServiceToken, error)
CreateFnInvoked bool

DuplicateFn func(context.Context, *ps.DuplicateServiceTokenRequest) (*ps.ServiceToken, error)
DuplicateFnInvoked bool

GetFn func(context.Context, *ps.GetServiceTokenRequest) (*ps.ServiceToken, error)
GetFnInvoked bool

Expand Down Expand Up @@ -37,6 +40,11 @@ func (s *ServiceTokenService) Create(ctx context.Context, req *ps.CreateServiceT
return s.CreateFn(ctx, req)
}

func (s *ServiceTokenService) Duplicate(ctx context.Context, req *ps.DuplicateServiceTokenRequest) (*ps.ServiceToken, error) {
s.DuplicateFnInvoked = true
return s.DuplicateFn(ctx, req)
}

func (s *ServiceTokenService) Get(ctx context.Context, req *ps.GetServiceTokenRequest) (*ps.ServiceToken, error) {
s.GetFnInvoked = true
return s.GetFn(ctx, req)
Expand Down
21 changes: 21 additions & 0 deletions internal/planetscale/service_tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ var _ ServiceTokenService = &serviceTokenService{}
// Service Token API.
type ServiceTokenService interface {
Create(context.Context, *CreateServiceTokenRequest) (*ServiceToken, error)
Duplicate(context.Context, *DuplicateServiceTokenRequest) (*ServiceToken, error)
Get(context.Context, *GetServiceTokenRequest) (*ServiceToken, error)
List(context.Context, *ListServiceTokensRequest) ([]*ServiceToken, error)
ListGrants(context.Context, *ListServiceTokenGrantsRequest) ([]*ServiceTokenGrant, error)
Expand Down Expand Up @@ -40,6 +41,20 @@ func (s *serviceTokenService) Create(ctx context.Context, createReq *CreateServi
return st, nil
}

func (s *serviceTokenService) Duplicate(ctx context.Context, dupReq *DuplicateServiceTokenRequest) (*ServiceToken, error) {
req, err := s.client.newRequest(http.MethodPost, path.Join(serviceTokenAPIPath(dupReq.Organization, dupReq.ID), "duplicate"), dupReq)
if err != nil {
return nil, err
}

st := &ServiceToken{}
if err := s.client.do(ctx, req, &st); err != nil {
return nil, err
}

return st, nil
}

func (s *serviceTokenService) Get(ctx context.Context, getReq *GetServiceTokenRequest) (*ServiceToken, error) {
req, err := s.client.newRequest(http.MethodGet, serviceTokenAPIPath(getReq.Organization, getReq.ID), nil)
if err != nil {
Expand Down Expand Up @@ -133,6 +148,12 @@ type CreateServiceTokenRequest struct {
TTL *int `json:"ttl,omitempty"`
}

type DuplicateServiceTokenRequest struct {
Organization string `json:"-"`
ID string `json:"-"`
Name string `json:"name"`
}

type GetServiceTokenRequest struct {
Organization string `json:"-"`
ID string `json:"-"`
Expand Down
Loading