Skip to content

CLOUDP-330561: Moves unauth error check to common errors #4043

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

Merged
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 cmd/atlas/atlas.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"strings"

"github.com/AlecAivazis/survey/v2/core"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli/commonerrors"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli/root"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/config"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/telemetry"
Expand All @@ -36,6 +37,8 @@ func execute(rootCmd *cobra.Command) {

To learn more, see our documentation: https://www.mongodb.com/docs/atlas/cli/stable/connect-atlas-cli/`
if cmd, err := rootCmd.ExecuteContextC(ctx); err != nil {
err := commonerrors.Check(err)
rootCmd.PrintErrln(rootCmd.ErrPrefix(), err)
if !telemetry.StartedTrackingCommand() {
telemetry.StartTrackingCommand(cmd, os.Args[1:])
}
Expand Down
3 changes: 2 additions & 1 deletion internal/cli/auth/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (

"github.com/AlecAivazis/survey/v2"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli/commonerrors"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli/require"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/config"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/flag"
Expand Down Expand Up @@ -397,7 +398,7 @@ func (opts *LoginOpts) LoginPreRun(ctx context.Context) func() error {
// clean up any expired or invalid tokens
opts.config.Set(config.AccessTokenField, "")

if !errors.Is(err, cli.ErrInvalidRefreshToken) {
if !commonerrors.IsInvalidRefreshToken(err) {
return err
}
}
Expand Down
4 changes: 2 additions & 2 deletions internal/cli/backup/restores/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,15 +73,15 @@ func (opts *StartOpts) Run() error {
if opts.isFlexCluster {
r, err := opts.store.CreateRestoreFlexClusterJobs(opts.ConfigProjectID(), opts.clusterName, opts.newFlexBackupRestoreJobCreate())
if err != nil {
return commonerrors.Check(err)
return err
}
return opts.Print(r)
}

request := opts.newCloudProviderSnapshotRestoreJob()
restoreJob, err := opts.store.CreateRestoreJobs(opts.ConfigProjectID(), opts.clusterName, request)
if err != nil {
return commonerrors.Check(err)
return err
}

return opts.Print(restoreJob)
Expand Down
3 changes: 1 addition & 2 deletions internal/cli/backup/snapshots/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import (
"fmt"

"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli/commonerrors"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli/require"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/config"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/flag"
Expand Down Expand Up @@ -59,7 +58,7 @@ func (opts *CreateOpts) Run() error {

r, err := opts.store.CreateSnapshot(opts.ConfigProjectID(), opts.clusterName, createRequest)
if err != nil {
return commonerrors.Check(err)
return err
}
return opts.Print(r)
}
Expand Down
3 changes: 1 addition & 2 deletions internal/cli/clusters/advancedsettings/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import (
"context"

"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli/commonerrors"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli/require"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/config"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/flag"
Expand Down Expand Up @@ -67,7 +66,7 @@ func (opts *UpdateOpts) initStore(ctx context.Context) func() error {
func (opts *UpdateOpts) Run() error {
r, err := opts.store.UpdateAtlasClusterConfigurationOptions(opts.ConfigProjectID(), opts.name, opts.newProcessArgs())
if err != nil {
return commonerrors.Check(err)
return err
}

return opts.Print(r)
Expand Down
5 changes: 2 additions & 3 deletions internal/cli/clusters/describe.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import (
"fmt"

"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli/commonerrors"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli/require"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/config"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/flag"
Expand Down Expand Up @@ -83,12 +82,12 @@ func (opts *DescribeOpts) RunFlexCluster(err error) error {
}

if *apiError.ErrorCode != cannotUseFlexWithClusterApisErrorCode {
return commonerrors.Check(err)
return err
}

r, err := opts.store.FlexCluster(opts.ConfigProjectID(), opts.name)
if err != nil {
return commonerrors.Check(err)
return err
}

return opts.Print(r)
Expand Down
5 changes: 2 additions & 3 deletions internal/cli/clusters/pause.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import (
"fmt"

"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli/commonerrors"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli/require"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/config"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/flag"
Expand Down Expand Up @@ -60,14 +59,14 @@ func (opts *PauseOpts) Run() error {
if isIndependentShardScaling(opts.autoScalingMode) {
r, err := opts.store.PauseClusterLatest(opts.ConfigProjectID(), opts.name)
if err != nil {
return commonerrors.Check(err)
return err
}
return opts.Print(r)
}

r, err := opts.store.PauseCluster(opts.ConfigProjectID(), opts.name)
if err != nil {
return commonerrors.Check(err)
return err
}
return opts.Print(r)
}
Expand Down
5 changes: 2 additions & 3 deletions internal/cli/clusters/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import (
"fmt"

"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli/commonerrors"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli/require"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/config"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/flag"
Expand Down Expand Up @@ -60,14 +59,14 @@ func (opts *StartOpts) Run() error {
if isIndependentShardScaling(opts.autoScalingMode) {
r, err := opts.store.StartClusterLatest(opts.ConfigProjectID(), opts.name)
if err != nil {
return commonerrors.Check(err)
return err
}
return opts.Print(r)
}

r, err := opts.store.StartCluster(opts.ConfigProjectID(), opts.name)
if err != nil {
return commonerrors.Check(err)
return err
}
return opts.Print(r)
}
Expand Down
2 changes: 1 addition & 1 deletion internal/cli/clusters/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ func (opts *UpdateOpts) RunDedicatedClusterWideScaling() error {

r, err := opts.store.UpdateCluster(opts.ConfigProjectID(), opts.name, cluster)
if err != nil {
return commonerrors.Check(err)
return err
}

return opts.Print(r)
Expand Down
105 changes: 91 additions & 14 deletions internal/cli/commonerrors/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,51 +16,128 @@ package commonerrors

import (
"errors"
"net/http"

"go.mongodb.org/atlas-sdk/v20250312005/admin"
atlasClustersPinned "go.mongodb.org/atlas-sdk/v20240530005/admin"
atlasv2 "go.mongodb.org/atlas-sdk/v20250312005/admin"
atlas "go.mongodb.org/atlas/mongodbatlas"
)

var (
errClusterUnsupported = errors.New("atlas supports this command only for M10+ clusters. You can upgrade your cluster by running the 'atlas cluster upgrade' command")
errOutsideVPN = errors.New("forbidden action outside access allow list, if you are a MongoDB employee double check your VPN connection")
errAsymmetricShardUnsupported = errors.New("trying to run a cluster wide scaling command on an independent shard scaling cluster. Use --autoScalingMode 'independentShardScaling' instead")
ErrUnauthorized = errors.New(`this action requires authentication

To log in using your Atlas username and password, run: atlas auth login
To set credentials using API keys, run: atlas config init`)
ErrInvalidRefreshToken = errors.New(`session expired

Please note that your session expires periodically.
If you use Atlas CLI for automation, see https://www.mongodb.com/docs/atlas/cli/stable/atlas-cli-automate/ for best practices.
To login, run: atlas auth login`)
)

const (
asymmetricShardUnsupportedErrorCode = "ASYMMETRIC_SHARD_UNSUPPORTED"
unknownErrorCode = "UNKNOWN_ERROR"
asymmetricShardUnsupportedErrorCode = "ASYMMETRIC_SHARD_UNSUPPORTED"
tenantClusterUpdateUnsupportedErrorCode = "TENANT_CLUSTER_UPDATE_UNSUPPORTED"
globalUserOutsideSubnetErrorCode = "GLOBAL_USER_OUTSIDE_SUBNET"
unauthorizedErrorCode = "UNAUTHORIZED"
invalidRefreshTokenErrorCode = "INVALID_REFRESH_TOKEN"
)

// Check checks the error and returns a more user-friendly error message if applicable.
func Check(err error) error {
if err == nil {
return nil
}

apiError, ok := admin.AsError(err)
if ok {
switch apiError.GetErrorCode() {
case "TENANT_CLUSTER_UPDATE_UNSUPPORTED":
return errClusterUnsupported
case "GLOBAL_USER_OUTSIDE_SUBNET":
return errOutsideVPN
case asymmetricShardUnsupportedErrorCode:
return errAsymmetricShardUnsupported
}
apiErrorCode := getErrorCode(err)

switch apiErrorCode {
case unauthorizedErrorCode:
return ErrUnauthorized
case invalidRefreshTokenErrorCode:
return ErrInvalidRefreshToken
case tenantClusterUpdateUnsupportedErrorCode:
return errClusterUnsupported
case globalUserOutsideSubnetErrorCode:
return errOutsideVPN
case asymmetricShardUnsupportedErrorCode:
return errAsymmetricShardUnsupported
}

apiError := getError(err) // some `Unauthorized` errors do not have an error code, so we check the HTTP status code

if apiError == http.StatusUnauthorized {
return ErrUnauthorized
}

return err
}

// getErrorCode extracts the error code from the error if it is an Atlas error.
// This function checks for v2 SDK, the pinned clusters SDK and the old SDK errors.
// If the error is not any of these Atlas errors, it returns "UNKNOWN_ERROR".
func getErrorCode(err error) string {
if err == nil {
return unknownErrorCode
}

var atlasErr *atlas.ErrorResponse
if errors.As(err, &atlasErr) {
return atlasErr.ErrorCode
}
if sdkError, ok := atlasv2.AsError(err); ok {
return sdkError.ErrorCode
}
if sdkPinnedError, ok := atlasClustersPinned.AsError(err); ok {
return sdkPinnedError.GetErrorCode()
}

return unknownErrorCode
}

// getError extracts the HTTP error code from the error if it is an Atlas error.
// This function checks for v2 SDK, the pinned clusters SDK and the old SDK errors.
// If the error is not any of these Atlas errors, it returns 0.
func getError(err error) int {
if err == nil {
return 0
}

var atlasErr *atlas.ErrorResponse
if errors.As(err, &atlasErr) {
return atlasErr.HTTPCode
}
if apiError, ok := atlasv2.AsError(err); ok {
return apiError.GetError()
}
if apiPinnedError, ok := atlasClustersPinned.AsError(err); ok {
return apiPinnedError.GetError()
}

return 0
}

func IsAsymmetricShardUnsupported(err error) bool {
apiError, ok := admin.AsError(err)
apiError, ok := atlasv2.AsError(err)
if !ok {
return false
}
return apiError.GetErrorCode() == asymmetricShardUnsupportedErrorCode
}

func IsCannotUseFlexWithClusterApis(err error) bool {
apiError, ok := admin.AsError(err)
apiError, ok := atlasv2.AsError(err)
if !ok {
return false
}
return apiError.GetErrorCode() == "CANNOT_USE_FLEX_CLUSTER_IN_CLUSTER_API"
}

func IsInvalidRefreshToken(err error) bool {
errCode := getErrorCode(err)
return errCode == invalidRefreshTokenErrorCode
}
Loading
Loading