diff --git a/.changes/v2.20.0/536-bug-fixes.md b/.changes/v2.20.0/536-bug-fixes.md new file mode 100644 index 000000000..e8558e523 --- /dev/null +++ b/.changes/v2.20.0/536-bug-fixes.md @@ -0,0 +1,2 @@ +* Fix a bug that prevented returning a specific error while authenticating client with invalid + password [GH-536] diff --git a/govcd/api_vcd.go b/govcd/api_vcd.go index e4ffc885b..fc3619ed9 100644 --- a/govcd/api_vcd.go +++ b/govcd/api_vcd.go @@ -92,6 +92,14 @@ func (vcdClient *VCDClient) vcdCloudApiAuthorize(user, pass, org string) (*http. } defer resp.Body.Close() + + // Catch HTTP 401 (Status Unauthorized) to return an error as otherwise this library would return + // odd errors while doing lookup of resources and confuse user. + if resp.StatusCode == http.StatusUnauthorized { + return nil, fmt.Errorf("received response HTTP %d (Unauthorized). Please check if your credentials are valid", + resp.StatusCode) + } + // Store the authorization header vcdClient.Client.VCDToken = resp.Header.Get(BearerTokenHeader) vcdClient.Client.VCDAuthHeader = BearerTokenHeader diff --git a/govcd/api_vcd_test.go b/govcd/api_vcd_test.go index 4da761617..63afb4bf6 100644 --- a/govcd/api_vcd_test.go +++ b/govcd/api_vcd_test.go @@ -1666,6 +1666,38 @@ func TestVCDClient_Authenticate(t *testing.T) { } } +func TestVCDClient_AuthenticateInvalidPassword(t *testing.T) { + config, err := GetConfigStruct() + if err != nil { + t.Fatalf("err: %s", err) + } + client, err := GetTestVCDFromYaml(config) + if err != nil { + t.Fatalf("error getting client structure: %s", err) + } + + err = client.Authenticate(config.Provider.User, "INVALID-PASSWORD", config.Provider.SysOrg) + if err == nil || !strings.Contains(err.Error(), "401") { + t.Fatalf("expected error for invalid credentials") + } +} + +func TestVCDClient_AuthenticateInvalidToken(t *testing.T) { + config, err := GetConfigStruct() + if err != nil { + t.Fatalf("err: %s", err) + } + client, err := GetTestVCDFromYaml(config) + if err != nil { + t.Fatalf("error getting client structure: %s", err) + } + + err = client.SetToken(config.Provider.SysOrg, AuthorizationHeader, "invalid-token") + if err == nil || !strings.Contains(err.Error(), "401") { + t.Fatalf("expected error for invalid credentials") + } +} + func Test_splitParent(t *testing.T) { type args struct { parent string