Skip to content
Open
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
58 changes: 58 additions & 0 deletions internal/cmd/token/create_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,3 +218,61 @@ func TestServiceToken_DuplicateCmd(t *testing.T) {
}
c.Assert(buf.String(), qt.JSONEquals, &ServiceTokenWithSecret{orig: orig})
}

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

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

org := "planetscale"
id := "123456"
name := "renamed"
secret := "d2980bbd91a4ab878601ef0573a7af7b1b15e705"

var requests int
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests++
c.Assert(r.Method, qt.Equals, http.MethodPatch)
c.Assert(r.URL.Path, qt.Equals, "/v1/organizations/planetscale/service-tokens/123456")
body, err := io.ReadAll(r.Body)
c.Assert(err, qt.IsNil)
c.Assert(string(body), qt.Equals, "{\"name\":\"renamed\",\"ttl\":3600}\n")
c.Assert(string(body), qt.Not(qt.Contains), secret)
c.Assert(string(body), qt.Not(qt.Contains), "token")

_, err = io.WriteString(w, `{"id":"123456","type":"ServiceToken","token":"d2980bbd91a4ab878601ef0573a7af7b1b15e705","name":"renamed","created_at":"2025-01-15T10:30:00.000Z","expires_at":"2025-01-15T11: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{"update", id, "--name", name, "--ttl", "3600", "--org", org})
c.Assert(cmd.Execute(), qt.IsNil)
c.Assert(requests, qt.Equals, 1)
c.Assert(buf.String(), qt.JSONEquals, map[string]any{
"id": id,
"name": name,
"created_at": "2025-01-15T10:30:00Z",
"last_used_at": nil,
"last_used_ip": nil,
"last_used_asn_organization": nil,
"expires_at": "2025-01-15T11:30:00Z",
})
c.Assert(buf.String(), qt.Not(qt.Contains), secret)
}
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(UpdateCmd(ch))
cmd.AddCommand(DuplicateCmd(ch))
cmd.AddCommand(ListCmd(ch))
cmd.AddCommand(ShowCmd(ch))
Expand Down
90 changes: 90 additions & 0 deletions internal/cmd/token/update.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package token

import (
"fmt"
"strconv"

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

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

cmd := &cobra.Command{
Use: "update <id>",
Short: "update a service token's name or expiry",
Long: "Update a service token's name or expiry. This does not rotate the token secret or change its id or grants.",
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]
nameSet := cmd.Flags().Changed("name")
ttlSet := cmd.Flags().Changed("ttl")
if !nameSet && !ttlSet {
return fmt.Errorf("at least one of --name or --ttl must be provided")
}

req := &planetscale.UpdateServiceTokenRequest{
Organization: ch.Config.Organization,
ID: id,
}
if nameSet {
req.Name = &name
}
if ttlSet {
parsed, err := serviceTokenTTL(ttl)
if err != nil {
return err
}
req.TTL = parsed
}

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

token, err := client.ServiceTokens.Update(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(toServiceTokenDetails(token))
},
}

cmd.Flags().StringVar(&name, "name", "", "new name for the service token. Omit to leave the name unchanged")
cmd.Flags().StringVar(&ttl, "ttl", "", `time to live in seconds, or "never" to remove the expiry. Omit to leave the expiry unchanged`)

return cmd
}

// serviceTokenTTL parses the same seconds unit as service-token create.
// "never" clears the expiry. Create uses 0 for that and omits the field;
// update cannot, because an omitted --ttl leaves the expiry alone.
func serviceTokenTTL(v string) (*planetscale.UpdateServiceTokenTTL, error) {
if v == "never" {
return &planetscale.UpdateServiceTokenTTL{Never: true}, nil
}
seconds, err := strconv.Atoi(v)
if err != nil {
return nil, fmt.Errorf(`--ttl must be a number of seconds or "never"`)
}
return &planetscale.UpdateServiceTokenTTL{Seconds: seconds}, nil
}
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

UpdateFn func(context.Context, *ps.UpdateServiceTokenRequest) (*ps.ServiceToken, error)
UpdateFnInvoked bool

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

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

func (s *ServiceTokenService) Update(ctx context.Context, req *ps.UpdateServiceTokenRequest) (*ps.ServiceToken, error) {
s.UpdateFnInvoked = true
return s.UpdateFn(ctx, req)
}

func (s *ServiceTokenService) Duplicate(ctx context.Context, req *ps.DuplicateServiceTokenRequest) (*ps.ServiceToken, error) {
s.DuplicateFnInvoked = true
return s.DuplicateFn(ctx, req)
Expand Down
37 changes: 37 additions & 0 deletions internal/planetscale/service_tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package planetscale

import (
"context"
"encoding/json"
"net/http"
"path"
"time"
Expand All @@ -13,6 +14,7 @@ var _ ServiceTokenService = &serviceTokenService{}
// Service Token API.
type ServiceTokenService interface {
Create(context.Context, *CreateServiceTokenRequest) (*ServiceToken, error)
Update(context.Context, *UpdateServiceTokenRequest) (*ServiceToken, error)
Duplicate(context.Context, *DuplicateServiceTokenRequest) (*ServiceToken, error)
Get(context.Context, *GetServiceTokenRequest) (*ServiceToken, error)
List(context.Context, *ListServiceTokensRequest) ([]*ServiceToken, error)
Expand Down Expand Up @@ -41,6 +43,20 @@ func (s *serviceTokenService) Create(ctx context.Context, createReq *CreateServi
return st, nil
}

func (s *serviceTokenService) Update(ctx context.Context, updateReq *UpdateServiceTokenRequest) (*ServiceToken, error) {
req, err := s.client.newRequest(http.MethodPatch, serviceTokenAPIPath(updateReq.Organization, updateReq.ID), updateReq)
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) 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 {
Expand Down Expand Up @@ -148,6 +164,27 @@ type CreateServiceTokenRequest struct {
TTL *int `json:"ttl,omitempty"`
}

type UpdateServiceTokenRequest struct {
Organization string `json:"-"`
ID string `json:"-"`
Name *string `json:"name,omitempty"`
TTL *UpdateServiceTokenTTL `json:"ttl,omitempty"`
}

// UpdateServiceTokenTTL is a service-token lifetime in seconds.
// Never clears the expiry; it is encoded as JSON null.
type UpdateServiceTokenTTL struct {
Never bool
Seconds int
}

func (t UpdateServiceTokenTTL) MarshalJSON() ([]byte, error) {
if t.Never {
return []byte("null"), nil
}
return json.Marshal(t.Seconds)
}

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