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
3 changes: 3 additions & 0 deletions internal/cmd/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,9 @@ func ApiCmd(ch *cmdutil.Helper, userAgent string, defaultHeaders map[string]stri
originalHost := req.URL.Hostname()
redirectCheck := makeRedirectCheck(originalHost)

if err := ch.Config.LoadAccessToken(); err != nil {
return err
}
var cl *http.Client
if ch.Config.AccessToken != "" {
// Create a transport chain that uses OAuth2 token but honors our redirect policy
Expand Down
3 changes: 3 additions & 0 deletions internal/cmd/auth/check.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ func CheckCmd(ch *cmdutil.Helper) *cobra.Command {
Args: cobra.NoArgs,
Short: "Check if you are authenticated",
RunE: func(cmd *cobra.Command, args []string) error {
if err := ch.Config.LoadAccessToken(); err != nil {
return err
}
ctx := cmd.Context()
resp := buildAuthCheckResponse(ctx, ch)

Expand Down
19 changes: 14 additions & 5 deletions internal/cmd/auth/logout.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package auth

import (
"bufio"
"errors"
"fmt"
"io"

"github.com/planetscale/cli/internal/auth"
Expand All @@ -23,7 +25,9 @@ func LogoutCmd(ch *cmdutil.Helper) *cobra.Command {
Args: cobra.NoArgs,
Short: "Log out of the PlanetScale API",
RunE: func(cmd *cobra.Command, args []string) error {
if ch.Config.AccessToken == "" {
// An unreadable token can't be revoked, but deleting it still logs out.
readErr := ch.Config.LoadStoredAccessToken()
if readErr == nil && ch.Config.AccessToken == "" {
ch.Printer.Println("Already logged out. Exiting...")
return nil
}
Expand All @@ -42,15 +46,20 @@ func LogoutCmd(ch *cmdutil.Helper) *cobra.Command {

end := ch.Printer.PrintProgress("Logging out...")
defer end()
err = authenticator.RevokeToken(ctx, ch.Config.AccessToken)
if err != nil {
return err
if readErr == nil {
err = authenticator.RevokeToken(ctx, ch.Config.AccessToken)
if err != nil {
return err
}
}
err = config.DeleteAccessToken()
if err != nil {
return err
return errors.Join(readErr, err)
}
end()
if readErr != nil {
fmt.Fprintf(cmd.ErrOrStderr(), "Warning: deleted the stored access token without revoking it: %v\n", readErr)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}
ch.Printer.Println("Successfully logged out.")

return nil
Expand Down
3 changes: 3 additions & 0 deletions internal/cmd/branch/connections/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,9 @@ func branchIsProduction(ctx context.Context, ch *cmdutil.Helper, database, branc
}

func newConnectionsClient(ch *cmdutil.Helper, database, branch string, target ConnectionTarget) (*live.Client, error) {
if err := ch.Config.LoadAccessToken(); err != nil {
return nil, err
}
return live.NewClient(live.ClientConfig{
BaseURL: ch.Config.BaseURL,
Organization: ch.Config.Organization,
Expand Down
10 changes: 2 additions & 8 deletions internal/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,15 +188,12 @@ func runCmd(ctx context.Context, ver, commit, buildDate string, format *printer.

rootCmd.Flags().BoolVar(&skillFlag, "skill", false, "Print the agent skill file and exit")

cfg, err := config.New()
if err != nil {
return err
}
cfg := config.New()

rootCmd.PersistentFlags().StringVar(&cfg.BaseURL,
"api-url", ps.DefaultBaseURL, "The base URL for the PlanetScale API.")
rootCmd.PersistentFlags().StringVar(&cfg.AccessToken,
"api-token", cfg.AccessToken, "The API token to use for authenticating against the PlanetScale API.")
"api-token", "", "The API token to use for authenticating against the PlanetScale API.")

rootCmd.PersistentFlags().VarP(printer.NewFormatValue(printer.Human, format), "format", "f",
"Show output in a specific format. Possible values: [human, json, csv]")
Expand Down Expand Up @@ -242,9 +239,6 @@ func runCmd(ctx context.Context, ver, commit, buildDate string, format *printer.
rootCmd.PersistentFlags().MarkDeprecated("service-token-name", "use --service-token-id instead")
rootCmd.PersistentFlags().MarkHidden("service-token-name")

// We don't want to show the default value
rootCmd.PersistentFlags().Lookup("api-token").DefValue = ""

// Add command groups for better organization
// Every command's help/usage output ends with a pointer to the embedded
// agent guide, so agents that discover pscale via --help (rather than a
Expand Down
54 changes: 54 additions & 0 deletions internal/cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ package cmd
import (
"bytes"
"context"
"encoding/json"
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"

"github.com/99designs/keyring"
"github.com/planetscale/cli/internal/cmd/agentguide"
"github.com/planetscale/cli/internal/cmdutil"
"github.com/spf13/cobra"
Expand All @@ -28,6 +30,58 @@ func TestAddCommandGroupsOmitsNeki(t *testing.T) {

const rootCLIHelperEnv = "PSCALE_ROOT_CLI_HELPER"

func TestStoredTokenLoadingIsLazyAndReportsJSONErrors(t *testing.T) {
for _, backend := range keyring.AvailableBackends() {
switch backend {
case keyring.KeychainBackend, keyring.SecretServiceBackend, keyring.KWalletBackend, keyring.WinCredBackend:
t.Skip("requires file fallback; run with CGO_ENABLED=0 on macOS")
}
}
home := writeHomeConfig(t, "")
// Reading a directory as a token reliably fails without touching a keychain.
if err := os.Mkdir(filepath.Join(home, ".config", "planetscale", "access-token"), 0o700); err != nil {
t.Fatal(err)
}
for _, args := range [][]string{
{"--help", "--format", "json"},
{"--version", "--format", "json"},
{"--skill", "--format", "json"},
} {
result := runRootCLIWithHome(t, home, args...)
if result.exitCode != 0 {
t.Fatalf("%v loaded stored credentials: stdout=%q stderr=%q", args, result.stdout, result.stderr)
}
}
for _, args := range [][]string{
{"org", "list", "--format", "json"},
{"auth", "check", "--format", "json"},
} {
result := runRootCLIWithHome(t, home, args...)
if result.exitCode != cmdutil.FatalErrExitCode {
t.Fatalf("%v exit code = %d, stdout=%q stderr=%q", args, result.exitCode, result.stdout, result.stderr)
}
var resp struct {
Status string `json:"status"`
Error string `json:"error"`
Issues []any `json:"issues"`
NextSteps []string `json:"next_steps"`
}
if err := json.Unmarshal([]byte(result.stdout), &resp); err != nil {
t.Fatalf("%v did not return one JSON envelope: %v, stdout=%q", args, err, result.stdout)
}
if resp.Status != "error" || !strings.Contains(resp.Error, "access-token") || len(resp.Issues) == 0 || len(resp.NextSteps) == 0 {
t.Fatalf("%v invalid JSON error envelope: %s", args, result.stdout)
}
}
result := runRootCLIWithHome(t, home, "auth", "logout", "--format", "json")
if result.exitCode != 0 {
t.Fatalf("auth logout exit code = %d, stdout=%q stderr=%q", result.exitCode, result.stdout, result.stderr)
}
if _, err := os.Stat(filepath.Join(home, ".config", "planetscale", "access-token")); !os.IsNotExist(err) {
t.Fatalf("auth logout left unreadable token in place: %v", err)
}
}

func TestRootSkillFlag(t *testing.T) {
for _, args := range [][]string{
{"--skill", "--format", "json"},
Expand Down
3 changes: 3 additions & 0 deletions internal/cmdutil/cmdutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,9 @@ func WarnDeprecated(name, message string, next func(cmd *cobra.Command, args []s
// actionable error message.
func CheckAuthentication(cfg *config.Config) func(cmd *cobra.Command, args []string) error {
return func(cmd *cobra.Command, args []string) error {
if err := cfg.LoadAccessToken(); err != nil {
return err
}
if err := cfg.IsAuthenticated(); err != nil {
if commandFormat(cmd) == printer.JSON.String() {
resp := struct {
Expand Down
81 changes: 61 additions & 20 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"os"
"path/filepath"
"strings"
"sync"

"github.com/99designs/keyring"
ps "github.com/planetscale/cli/internal/planetscale"
Expand Down Expand Up @@ -34,21 +35,41 @@ type Config struct {
ServiceTokenID string
ServiceToken string

loadAccessToken func() (string, error)

// Project Configuration
Database string
Branch string
}

func New() (*Config, error) {
accessToken, err := readAccessToken()
if err != nil {
return nil, err
func New() *Config {
return &Config{
BaseURL: ps.DefaultBaseURL,
loadAccessToken: sync.OnceValues(readAccessToken),
}
}

return &Config{
AccessToken: accessToken,
BaseURL: ps.DefaultBaseURL,
}, nil
// LoadAccessToken fills AccessToken from credential storage unless explicit
// credentials were provided.
func (c *Config) LoadAccessToken() error {
if c.ServiceTokenID != "" || c.ServiceToken != "" {
return nil
}
return c.LoadStoredAccessToken()
}

// LoadStoredAccessToken fills AccessToken from credential storage unless an
// access token was provided, even when service token credentials are set.
func (c *Config) LoadStoredAccessToken() error {
if c.AccessToken != "" || c.loadAccessToken == nil {
return nil
}
token, err := c.loadAccessToken()
if err != nil {
return err
}
c.AccessToken = token
return nil
}

func (c *Config) IsAuthenticated() error {
Expand All @@ -63,6 +84,9 @@ func (c *Config) IsAuthenticated() error {
if c.ServiceTokenIsSet() {
return nil
}
if err := c.LoadAccessToken(); err != nil {
return err
}

if c.AccessToken == "" {
return errors.New("you must run 'pscale auth login' to authenticate before using this command")
Expand Down Expand Up @@ -92,6 +116,9 @@ func (c *Config) NewClientFromConfig(clientOpts ...ps.ClientOption) (*ps.Client,
if c.ServiceTokenIsSet() {
opts = append(opts, ps.WithServiceToken(c.ServiceTokenID, c.ServiceToken))
} else {
if err := c.LoadAccessToken(); err != nil {
return nil, err
}
opts = append(opts, ps.WithAccessToken(c.AccessToken))
}
opts = append(opts, clientOpts...)
Expand Down Expand Up @@ -175,7 +202,10 @@ func readAccessToken() (string, error) {
if errors.Is(err, keyring.ErrKeyNotFound) {
// Migrate to keychain
accessToken, tokenErr := readAccessTokenPath()
if len(accessToken) > 0 && tokenErr == nil {
if tokenErr != nil && !os.IsNotExist(tokenErr) {
return "", tokenErr
}
if len(accessToken) > 0 {
return migrateAccessToken(ring, accessToken)
}
// Might need to improve this, but today the empty
Expand Down Expand Up @@ -229,10 +259,19 @@ func DeleteAccessToken() error {
return deleteAccessTokenPath()
}

return ring.Remove(keyringKey)
// Remove the token file left by keyring migration so a later read
// doesn't migrate it back or fail on it.
if err := deleteAccessTokenFile(); err != nil {
return err
}
err = ring.Remove(keyringKey)
if err != nil && !errors.Is(err, keyring.ErrKeyNotFound) {
return err
}
return nil
}

func openKeyring() (keyring.Keyring, error) {
var openKeyring = func() (keyring.Keyring, error) {
return keyring.Open(keyring.Config{
AllowedBackends: []keyring.BackendType{
keyring.SecretServiceBackend,
Expand Down Expand Up @@ -264,9 +303,6 @@ func readAccessTokenPath() ([]byte, error) {

stat, err := os.Stat(tokenPath)
if err != nil {
if !os.IsNotExist(err) {
log.Fatal(err)
}
return nil, err
} else {
if stat.Mode()&^tokenFileMode != 0 {
Expand All @@ -277,24 +313,29 @@ func readAccessTokenPath() ([]byte, error) {
}
accessToken, err = os.ReadFile(tokenPath)
if err != nil {
log.Fatal(err)
return nil, err
}
}

return accessToken, nil
}

func deleteAccessTokenPath() error {
func deleteAccessTokenFile() error {
tokenPath, err := accessTokenPath()
if err != nil {
return err
}

err = os.Remove(tokenPath)
if err != nil {
if !os.IsNotExist(err) {
return fmt.Errorf("error removing access token file: %w", err)
}
if err != nil && !os.IsNotExist(err) {
return fmt.Errorf("error removing access token file: %w", err)
}
return nil
}

func deleteAccessTokenPath() error {
if err := deleteAccessTokenFile(); err != nil {
return err
}

configFile, err := DefaultConfigPath()
Expand Down
Loading
Loading