From 76beec398340f1d85427ab1e4765905936c2e6f7 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 15 Nov 2026 00:08:42 +0000 Subject: [PATCH] Add IP restrictions to service-token create and update Co-authored-by: Mike Coutermarsh --- internal/cmd/token/create.go | 9 ++ internal/cmd/token/create_test.go | 41 ++++++++ internal/cmd/token/show_test.go | 5 + internal/cmd/token/token.go | 14 +++ internal/cmd/token/update.go | 92 +++++++++++++++++ internal/cmd/token/update_test.go | 106 ++++++++++++++++++++ internal/mock/servicetoken.go | 8 ++ internal/planetscale/service_tokens.go | 27 +++++ internal/planetscale/service_tokens_test.go | 85 ++++++++++++++++ 9 files changed, 387 insertions(+) create mode 100644 internal/cmd/token/update.go create mode 100644 internal/cmd/token/update_test.go diff --git a/internal/cmd/token/create.go b/internal/cmd/token/create.go index ba9482e0..076cbc8f 100644 --- a/internal/cmd/token/create.go +++ b/internal/cmd/token/create.go @@ -12,10 +12,13 @@ import ( func CreateCmd(ch *cmdutil.Helper) *cobra.Command { var name string var ttl int + var cidrs []string cmd := &cobra.Command{ Use: "create", Short: "create a service token for the organization", + Example: ` pscale service-token create --name ci --cidrs 10.0.0.0/8,192.168.1.1/32 + pscale service-token create --name ci`, RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() client, err := ch.Client() @@ -28,6 +31,10 @@ func CreateCmd(ch *cmdutil.Helper) *cobra.Command { Name: stringPtrOrNil(name), TTL: intPtrOrNil(ttl), } + if cmd.Flags().Changed("cidrs") { + normalized := normalizeCIDRs(cidrs) + req.CIDRs = &normalized + } end := ch.Printer.PrintProgress(fmt.Sprintf("Creating service token in org %s", printer.BoldBlue(ch.Config.Organization))) defer end() @@ -50,6 +57,8 @@ func CreateCmd(ch *cmdutil.Helper) *cobra.Command { cmd.Flags().StringVar(&name, "name", "", "optional name for the service token") cmd.Flags().IntVar(&ttl, "ttl", 0, "Time to live (in seconds) for the service token. The token will be invalid when TTL has passed") + cmd.Flags().StringSliceVar(&cidrs, "cidrs", nil, + "IP addresses and CIDR ranges allowed to use this service token. Omit to leave the token unrestricted") return cmd } diff --git a/internal/cmd/token/create_test.go b/internal/cmd/token/create_test.go index 9fdb2c1a..eb99e501 100644 --- a/internal/cmd/token/create_test.go +++ b/internal/cmd/token/create_test.go @@ -36,6 +36,7 @@ func TestServiceToken_CreateCmd(t *testing.T) { CreateFn: func(ctx context.Context, req *ps.CreateServiceTokenRequest) (*ps.ServiceToken, error) { c.Assert(req.Organization, qt.Equals, org) c.Assert(req.Name, qt.IsNil) + c.Assert(req.CIDRs, qt.IsNil) return orig, nil }, } @@ -109,6 +110,46 @@ func TestServiceToken_CreateCmdWithName(t *testing.T) { c.Assert(buf.String(), qt.JSONEquals, res) } +func TestServiceToken_CreateCmdWithCIDRs(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" + createdAt := time.Date(2025, 1, 15, 10, 30, 0, 0, time.UTC) + cidrs := []string{"10.0.0.0/8", "192.168.1.1/32"} + + orig := &ps.ServiceToken{ID: id, CreatedAt: createdAt, CIDRs: cidrs} + + svc := &mock.ServiceTokenService{ + CreateFn: func(ctx context.Context, req *ps.CreateServiceTokenRequest) (*ps.ServiceToken, error) { + c.Assert(req.CIDRs, qt.IsNotNil) + c.Assert(*req.CIDRs, qt.DeepEquals, cidrs) + return orig, nil + }, + } + + ch := &cmdutil.Helper{ + Printer: p, + Config: &config.Config{Organization: org}, + Client: func() (*ps.Client, error) { + return &ps.Client{ServiceTokens: svc}, nil + }, + } + + cmd := CreateCmd(ch) + cmd.SetArgs([]string{"--cidrs", "10.0.0.0/8,192.168.1.1/32"}) + err := cmd.Execute() + + c.Assert(err, qt.IsNil) + c.Assert(svc.CreateFnInvoked, qt.IsTrue) + c.Assert(buf.String(), qt.JSONEquals, &ServiceTokenWithSecret{orig: orig}) +} + func TestServiceToken_CreateCmdWithTTL(t *testing.T) { c := qt.New(t) diff --git a/internal/cmd/token/show_test.go b/internal/cmd/token/show_test.go index 838b1d5d..f37a7887 100644 --- a/internal/cmd/token/show_test.go +++ b/internal/cmd/token/show_test.go @@ -29,6 +29,7 @@ func TestServiceToken_ShowCmd(t *testing.T) { lastUsedAt := time.Date(2025, 1, 20, 14, 45, 0, 0, time.UTC) lastUsedIP := "203.0.113.5" lastUsedOrganization := "Example Networks" + cidrs := []string{"10.0.0.0/8", "192.168.1.1/32"} token := &ps.ServiceToken{ ID: id, Name: &name, @@ -37,6 +38,7 @@ func TestServiceToken_ShowCmd(t *testing.T) { LastUsedAt: &lastUsedAt, LastUsedIP: &lastUsedIP, LastUsedAsnOrganization: &lastUsedOrganization, + CIDRs: cidrs, } svc := &mock.ServiceTokenService{ @@ -63,6 +65,7 @@ func TestServiceToken_ShowCmd(t *testing.T) { "last_used_ip": "203.0.113.5", "last_used_asn_organization": "Example Networks", "expires_at": nil, + "cidrs": cidrs, }) c.Assert(buf.String(), qt.Not(qt.Contains), token.Token) } @@ -88,6 +91,7 @@ func TestServiceToken_ShowCmdHuman(t *testing.T) { CreatedAt: time.Date(2025, 1, 15, 10, 30, 0, 0, time.UTC), LastUsedIP: &lastUsedIP, LastUsedAsnOrganization: &lastUsedOrganization, + CIDRs: []string{"10.0.0.0/8", "192.168.1.1/32"}, }, nil }, } @@ -102,6 +106,7 @@ func TestServiceToken_ShowCmdHuman(t *testing.T) { c.Assert(buf.String(), qt.Contains, "deploy-token") c.Assert(buf.String(), qt.Contains, "203.0.113.5") c.Assert(buf.String(), qt.Contains, "Example Networks") + c.Assert(buf.String(), qt.Contains, "10.0.0.0/8, 192.168.1.1/32") c.Assert(buf.String(), qt.Not(qt.Contains), "must-not-be-printed") } diff --git a/internal/cmd/token/token.go b/internal/cmd/token/token.go index b49e883d..09d9a86b 100644 --- a/internal/cmd/token/token.go +++ b/internal/cmd/token/token.go @@ -3,6 +3,7 @@ package token import ( "encoding/json" "fmt" + "strings" "time" "github.com/planetscale/cli/internal/cmdutil" @@ -38,6 +39,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)) @@ -52,6 +54,7 @@ func TokenCmd(ch *cmdutil.Helper) *cobra.Command { type ServiceToken struct { ID string `header:"id" json:"id"` Name string `header:"name" json:"name"` + CIDRs string `header:"cidrs"` LastUsedAt int64 `header:"last_used_at,timestamp(ms|utc|human)" json:"last_used_at"` LastUsedIP string `header:"last_used_ip" json:"last_used_ip"` LastUsedOrganization string `header:"last_used_organization" json:"last_used_organization"` @@ -88,6 +91,7 @@ func toServiceToken(st *ps.ServiceToken) *ServiceToken { return &ServiceToken{ ID: st.ID, Name: name, + CIDRs: formatCIDRs(st.CIDRs), LastUsedAt: lastUsedAt, LastUsedIP: derefString(st.LastUsedIP), LastUsedOrganization: derefString(st.LastUsedAsnOrganization), @@ -97,6 +101,10 @@ func toServiceToken(st *ps.ServiceToken) *ServiceToken { } } +func formatCIDRs(cidrs []string) string { + return strings.Join(cidrs, ", ") +} + func derefString(value *string) string { if value == nil { return "" @@ -107,6 +115,7 @@ func derefString(value *string) string { type ServiceTokenDetails struct { ID string `header:"id"` Name string `header:"name"` + CIDRs string `header:"cidrs"` LastUsedAt int64 `header:"last_used_at,timestamp(ms|utc|human)"` LastUsedIP string `header:"last_used_ip"` LastUsedOrganization string `header:"last_used_organization"` @@ -125,6 +134,7 @@ func (s *ServiceTokenDetails) MarshalJSON() ([]byte, error) { LastUsedIP *string `json:"last_used_ip"` LastUsedAsnOrganization *string `json:"last_used_asn_organization"` ExpiresAt *time.Time `json:"expires_at"` + CIDRs []string `json:"cidrs"` }{ ID: s.orig.ID, Name: s.orig.Name, @@ -133,6 +143,7 @@ func (s *ServiceTokenDetails) MarshalJSON() ([]byte, error) { LastUsedIP: s.orig.LastUsedIP, LastUsedAsnOrganization: s.orig.LastUsedAsnOrganization, ExpiresAt: s.orig.ExpiresAt, + CIDRs: s.orig.CIDRs, }, "", " ") } @@ -142,6 +153,7 @@ func toServiceTokenDetails(st *ps.ServiceToken) *ServiceTokenDetails { return &ServiceTokenDetails{ ID: token.ID, Name: token.Name, + CIDRs: token.CIDRs, LastUsedAt: token.LastUsedAt, LastUsedIP: token.LastUsedIP, LastUsedOrganization: token.LastUsedOrganization, @@ -155,6 +167,7 @@ func toServiceTokenDetails(st *ps.ServiceToken) *ServiceTokenDetails { type ServiceTokenWithSecret struct { ID string `header:"id" json:"id"` Name string `header:"name" json:"name"` + CIDRs string `header:"cidrs"` Token string `header:"token" json:"token"` ExpiresAt int64 `header:"expires_at,timestamp(ms|utc|human)" json:"expires_at"` CreatedAt int64 `header:"created_at,timestamp(ms|utc|human)" json:"created_at"` @@ -181,6 +194,7 @@ func toServiceTokenWithSecret(st *ps.ServiceToken) *ServiceTokenWithSecret { return &ServiceTokenWithSecret{ ID: st.ID, Name: name, + CIDRs: formatCIDRs(st.CIDRs), Token: st.Token, ExpiresAt: expiresAt, CreatedAt: printer.GetMilliseconds(st.CreatedAt), diff --git a/internal/cmd/token/update.go b/internal/cmd/token/update.go new file mode 100644 index 00000000..7bbfecd3 --- /dev/null +++ b/internal/cmd/token/update.go @@ -0,0 +1,92 @@ +package token + +import ( + "errors" + "fmt" + "strings" + + "github.com/planetscale/cli/internal/cmdutil" + "github.com/planetscale/cli/internal/planetscale" + "github.com/planetscale/cli/internal/printer" + "github.com/spf13/cobra" +) + +// UpdateCmd replaces the IP restrictions on a service token. +func UpdateCmd(ch *cmdutil.Helper) *cobra.Command { + var cidrs []string + + cmd := &cobra.Command{ + Use: "update ", + Short: "Update a service token's IP restrictions", + Long: `Update the IP addresses and CIDR ranges allowed to use a service token. + +This does not rotate the token. Pass an empty --cidrs value to remove all restrictions.`, + Example: ` pscale service-token update --cidrs 10.0.0.0/8,192.168.1.1/32 + pscale service-token update --cidrs ""`, + Args: cmdutil.RequiredArgs("id"), + RunE: func(cmd *cobra.Command, args []string) error { + ctx := cmd.Context() + id := args[0] + + if !cmd.Flags().Changed("cidrs") { + return errors.New("--cidrs must be provided") + } + + client, err := ch.Client() + if err != nil { + return err + } + + end := ch.Printer.PrintProgress(fmt.Sprintf("Updating service token %s in org %s", + printer.BoldBlue(id), printer.BoldBlue(ch.Config.Organization))) + defer end() + + normalized := normalizeCIDRs(cidrs) + token, err := client.ServiceTokens.Update(ctx, &planetscale.UpdateServiceTokenRequest{ + Organization: ch.Config.Organization, + ID: id, + CIDRs: &normalized, + }) + 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() + + if ch.Printer.Format() == printer.Human { + ch.Printer.Printf("Service token %s was successfully updated.\n", printer.BoldBlue(token.ID)) + if len(token.CIDRs) == 0 { + ch.Printer.Println("IP restrictions: none") + } else { + ch.Printer.Printf("IP restrictions: %s\n", strings.Join(token.CIDRs, ", ")) + } + return nil + } + + return ch.Printer.PrintResource(toServiceTokenDetails(token)) + }, + } + + cmd.Flags().StringSliceVar(&cidrs, "cidrs", nil, + "Replace the IP addresses and CIDR ranges allowed to use this service token. Pass an empty value to remove all restrictions") + + return cmd +} + +// normalizeCIDRs drops the empty entries produced by flags like --cidrs "" so +// that clearing restrictions sends an empty list instead of a blank CIDR. +func normalizeCIDRs(cidrs []string) []string { + out := make([]string, 0, len(cidrs)) + for _, cidr := range cidrs { + if trimmed := strings.TrimSpace(cidr); trimmed != "" { + out = append(out, trimmed) + } + } + return out +} diff --git a/internal/cmd/token/update_test.go b/internal/cmd/token/update_test.go new file mode 100644 index 00000000..5643de84 --- /dev/null +++ b/internal/cmd/token/update_test.go @@ -0,0 +1,106 @@ +package token + +import ( + "bytes" + "context" + "testing" + + "github.com/planetscale/cli/internal/cmdutil" + "github.com/planetscale/cli/internal/config" + "github.com/planetscale/cli/internal/mock" + ps "github.com/planetscale/cli/internal/planetscale" + "github.com/planetscale/cli/internal/printer" + + qt "github.com/frankban/quicktest" +) + +func TestServiceToken_UpdateCmdSetsCIDRs(t *testing.T) { + c := qt.New(t) + + var buf bytes.Buffer + format := printer.JSON + p := printer.NewPrinter(&format) + p.SetResourceOutput(&buf) + + org := "planetscale" + id := "token-id" + cidrs := []string{"10.0.0.0/8", "192.168.1.1/32"} + secret := "must-not-be-printed" + + svc := &mock.ServiceTokenService{ + UpdateFn: func(ctx context.Context, req *ps.UpdateServiceTokenRequest) (*ps.ServiceToken, error) { + c.Assert(req.Organization, qt.Equals, org) + c.Assert(req.ID, qt.Equals, id) + c.Assert(req.CIDRs, qt.IsNotNil) + c.Assert(*req.CIDRs, qt.DeepEquals, cidrs) + return &ps.ServiceToken{ID: id, Token: secret, CIDRs: cidrs}, nil + }, + } + + cmd := UpdateCmd(serviceTokenUpdateHelper(p, org, svc)) + cmd.SetArgs([]string{id, "--cidrs", "10.0.0.0/8,192.168.1.1/32"}) + err := cmd.Execute() + + c.Assert(err, qt.IsNil) + c.Assert(svc.UpdateFnInvoked, qt.IsTrue) + c.Assert(buf.String(), qt.JSONEquals, map[string]any{ + "id": id, + "name": nil, + "created_at": "0001-01-01T00:00:00Z", + "last_used_at": nil, + "last_used_ip": nil, + "last_used_asn_organization": nil, + "expires_at": nil, + "cidrs": cidrs, + }) + c.Assert(buf.String(), qt.Not(qt.Contains), secret) +} + +func TestServiceToken_UpdateCmdClearsCIDRs(t *testing.T) { + c := qt.New(t) + + format := printer.JSON + p := printer.NewPrinter(&format) + + svc := &mock.ServiceTokenService{ + UpdateFn: func(ctx context.Context, req *ps.UpdateServiceTokenRequest) (*ps.ServiceToken, error) { + c.Assert(req.CIDRs, qt.IsNotNil) + c.Assert(*req.CIDRs, qt.HasLen, 0) + return &ps.ServiceToken{ID: "token-id"}, nil + }, + } + + cmd := UpdateCmd(serviceTokenUpdateHelper(p, "planetscale", svc)) + cmd.SetArgs([]string{"token-id", "--cidrs", ""}) + err := cmd.Execute() + + c.Assert(err, qt.IsNil) + c.Assert(svc.UpdateFnInvoked, qt.IsTrue) +} + +func TestServiceToken_UpdateCmdRequiresCIDRs(t *testing.T) { + c := qt.New(t) + + format := printer.JSON + p := printer.NewPrinter(&format) + + svc := &mock.ServiceTokenService{} + + cmd := UpdateCmd(serviceTokenUpdateHelper(p, "planetscale", svc)) + cmd.SetArgs([]string{"token-id"}) + err := cmd.Execute() + + c.Assert(err, qt.IsNotNil) + c.Assert(err.Error(), qt.Contains, "--cidrs must be provided") + c.Assert(svc.UpdateFnInvoked, qt.IsFalse) +} + +func serviceTokenUpdateHelper(p *printer.Printer, org string, svc *mock.ServiceTokenService) *cmdutil.Helper { + return &cmdutil.Helper{ + Printer: p, + Config: &config.Config{Organization: org}, + Client: func() (*ps.Client, error) { + return &ps.Client{ServiceTokens: svc}, nil + }, + } +} diff --git a/internal/mock/servicetoken.go b/internal/mock/servicetoken.go index 97638a3a..dd7d0daf 100644 --- a/internal/mock/servicetoken.go +++ b/internal/mock/servicetoken.go @@ -19,6 +19,9 @@ type ServiceTokenService struct { ListFn func(context.Context, *ps.ListServiceTokensRequest) ([]*ps.ServiceToken, error) ListFnInvoked bool + UpdateFn func(context.Context, *ps.UpdateServiceTokenRequest) (*ps.ServiceToken, error) + UpdateFnInvoked bool + DeleteFn func(context.Context, *ps.DeleteServiceTokenRequest) error DeleteFnInvoked bool @@ -55,6 +58,11 @@ func (s *ServiceTokenService) List(ctx context.Context, req *ps.ListServiceToken return s.ListFn(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) Delete(ctx context.Context, req *ps.DeleteServiceTokenRequest) error { s.DeleteFnInvoked = true return s.DeleteFn(ctx, req) diff --git a/internal/planetscale/service_tokens.go b/internal/planetscale/service_tokens.go index 13d68c65..5cd96aa3 100644 --- a/internal/planetscale/service_tokens.go +++ b/internal/planetscale/service_tokens.go @@ -17,6 +17,7 @@ type ServiceTokenService interface { Get(context.Context, *GetServiceTokenRequest) (*ServiceToken, error) List(context.Context, *ListServiceTokensRequest) ([]*ServiceToken, error) ListGrants(context.Context, *ListServiceTokenGrantsRequest) ([]*ServiceTokenGrant, error) + Update(context.Context, *UpdateServiceTokenRequest) (*ServiceToken, error) Delete(context.Context, *DeleteServiceTokenRequest) error GetAccess(context.Context, *GetServiceTokenAccessRequest) ([]*ServiceTokenAccess, error) AddAccess(context.Context, *AddServiceTokenAccessRequest) ([]*ServiceTokenAccess, error) @@ -83,6 +84,20 @@ func (s *serviceTokenService) List(ctx context.Context, listReq *ListServiceToke return tokenListResponse.ServiceTokens, 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) Delete(ctx context.Context, delReq *DeleteServiceTokenRequest) error { req, err := s.client.newRequest(http.MethodDelete, serviceTokenAPIPath(delReq.Organization, delReq.ID), nil) if err != nil { @@ -146,6 +161,17 @@ type CreateServiceTokenRequest struct { Organization string `json:"-"` Name *string `json:"name,omitempty"` TTL *int `json:"ttl,omitempty"` + // CIDRs sets IP restrictions when non-nil. Nil omits the field. + CIDRs *[]string `json:"cidrs,omitempty"` +} + +// UpdateServiceTokenRequest replaces a service token's IP restrictions. +// Only CIDRs is sent. A pointer to an empty slice clears the restriction; +// nil omits the field. +type UpdateServiceTokenRequest struct { + Organization string `json:"-"` + ID string `json:"-"` + CIDRs *[]string `json:"cidrs,omitempty"` } type DuplicateServiceTokenRequest struct { @@ -202,6 +228,7 @@ type ServiceToken struct { LastUsedIP *string `json:"last_used_ip"` LastUsedAsnOrganization *string `json:"last_used_asn_organization"` ExpiresAt *time.Time `json:"expires_at"` + CIDRs []string `json:"cidrs"` } type ServiceTokenGrant struct { diff --git a/internal/planetscale/service_tokens_test.go b/internal/planetscale/service_tokens_test.go index cb750b34..c6263c34 100644 --- a/internal/planetscale/service_tokens_test.go +++ b/internal/planetscale/service_tokens_test.go @@ -95,6 +95,91 @@ func TestServiceTokens_CreateWithTTL(t *testing.T) { c.Assert(snapshot, qt.DeepEquals, want) } +func TestServiceTokens_CreateWithCIDRs(t *testing.T) { + c := qt.New(t) + + wantBody := []byte("{\"cidrs\":[\"203.0.113.0/24\",\"198.51.100.10\"]}\n") + + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + c.Assert(r.Method, qt.Equals, http.MethodPost) + data, err := io.ReadAll(r.Body) + c.Assert(err, qt.IsNil) + c.Assert(data, qt.DeepEquals, wantBody) + + out := `{"id":"test-id","type":"ServiceToken","token":"secret","created_at":"2021-01-14T10:19:23.000Z","cidrs":["203.0.113.0/24","198.51.100.10"]}` + _, err = w.Write([]byte(out)) + c.Assert(err, qt.IsNil) + })) + + client, err := NewClient(WithBaseURL(ts.URL)) + c.Assert(err, qt.IsNil) + + cidrs := []string{"203.0.113.0/24", "198.51.100.10"} + snapshot, err := client.ServiceTokens.Create(context.Background(), &CreateServiceTokenRequest{ + Organization: testOrg, + CIDRs: &cidrs, + }) + + c.Assert(err, qt.IsNil) + c.Assert(snapshot.CIDRs, qt.DeepEquals, cidrs) +} + +func TestServiceTokens_UpdateCIDRs(t *testing.T) { + c := qt.New(t) + + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + c.Assert(r.Method, qt.Equals, http.MethodPatch) + c.Assert(r.URL.Path, qt.Equals, "/v1/organizations/my-org/service-tokens/1234") + + data, err := io.ReadAll(r.Body) + c.Assert(err, qt.IsNil) + c.Assert(data, qt.DeepEquals, []byte("{\"cidrs\":[\"203.0.113.10/32\"]}\n")) + + _, err = w.Write([]byte(`{"id":"1234","cidrs":["203.0.113.10/32"],"created_at":"2021-01-14T10:19:23.000Z"}`)) + c.Assert(err, qt.IsNil) + })) + + client, err := NewClient(WithBaseURL(ts.URL)) + c.Assert(err, qt.IsNil) + + cidrs := []string{"203.0.113.10/32"} + token, err := client.ServiceTokens.Update(context.Background(), &UpdateServiceTokenRequest{ + Organization: testOrg, + ID: "1234", + CIDRs: &cidrs, + }) + + c.Assert(err, qt.IsNil) + c.Assert(token.ID, qt.Equals, "1234") + c.Assert(token.CIDRs, qt.DeepEquals, []string{"203.0.113.10/32"}) +} + +func TestServiceTokens_UpdateClearsCIDRs(t *testing.T) { + c := qt.New(t) + + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + data, err := io.ReadAll(r.Body) + c.Assert(err, qt.IsNil) + c.Assert(data, qt.DeepEquals, []byte("{\"cidrs\":[]}\n")) + + _, err = w.Write([]byte(`{"id":"1234","cidrs":[],"created_at":"2021-01-14T10:19:23.000Z"}`)) + c.Assert(err, qt.IsNil) + })) + + client, err := NewClient(WithBaseURL(ts.URL)) + c.Assert(err, qt.IsNil) + + cidrs := []string{} + token, err := client.ServiceTokens.Update(context.Background(), &UpdateServiceTokenRequest{ + Organization: testOrg, + ID: "1234", + CIDRs: &cidrs, + }) + + c.Assert(err, qt.IsNil) + c.Assert(token.CIDRs, qt.HasLen, 0) +} + func TestServiceTokens_Get(t *testing.T) { c := qt.New(t)