diff --git a/cmd/network.go b/cmd/network.go index 4ef6ce3..810739e 100644 --- a/cmd/network.go +++ b/cmd/network.go @@ -374,25 +374,26 @@ func detectSignatureAlgorithm(r *Request) (string, error) { continue } - defer response.Body.Close() body, readErr := ioutil.ReadAll(response.Body) + response.Body.Close() if readErr != nil { config.Debug("API signature algorithm probe failed reading response body for ", algorithm, ": ", readErr) lastErr = readErr continue } config.Debug("Signature algorithm probe response body:", string(body)) - if _, err := parseAPIResponse(body); err == nil { + _, parseErr := parseAPIResponse(body) + if parseErr == nil { config.Debug("Selected API signature algorithm:", algorithm) persistDetectedSignatureAlgorithm(r, algorithm) return algorithm, nil } - lastErr = err - if isAuthenticationFailure(response.StatusCode, err) { - config.Debug("API signature algorithm probe failed authentication for ", algorithm, ": ", err) + lastErr = parseErr + if isAuthenticationFailure(response.StatusCode, parseErr) { + config.Debug("API signature algorithm probe failed authentication for ", algorithm, ": ", parseErr) } else { - config.Debug("API signature algorithm probe failed with non-authentication error for ", algorithm, ": ", err) - return "", err + config.Debug("API signature algorithm probe failed with non-authentication error for ", algorithm, ": ", parseErr) + return "", parseErr } } @@ -478,21 +479,34 @@ func NewAPIRequest(r *Request, api string, args []string, isAsync bool) (map[str var err error usingSessionAuth := false - if len(r.Config.ActiveProfile.APIKey) > 0 && len(r.Config.ActiveProfile.SecretKey) > 0 { - apiKey := r.Config.ActiveProfile.APIKey - if len(apiKey) > 0 { - params.Add("apiKey", apiKey) - } + hasAPIKeyAuth := len(r.Config.ActiveProfile.APIKey) > 0 && len(r.Config.ActiveProfile.SecretKey) > 0 + hasPasswordAuth := len(r.Config.ActiveProfile.Username) > 0 && len(r.Config.ActiveProfile.Password) > 0 + + if hasAPIKeyAuth { + signedParams := cloneRequestParams(params) + signedParams.Add("apiKey", r.Config.ActiveProfile.APIKey) signatureAlgorithm, err := activeSignatureAlgorithm(r) if err != nil { - return nil, err - } - response, err := executeSignedAPIRequest(r, params, signatureAlgorithm) - if err != nil { - return nil, err + if !r.CredentialsSupplied && hasPasswordAuth && isAuthenticationFailure(0, err) { + config.Debug("API key signature algorithm detection failed authentication, falling back to login: ", err) + } else { + return nil, err + } + } else { + response, err := executeSignedAPIRequest(r, signedParams, signatureAlgorithm) + if err != nil { + return nil, err + } + if response.StatusCode == http.StatusUnauthorized && !r.CredentialsSupplied && hasPasswordAuth { + response.Body.Close() + config.Debug("API key request returned HTTP 401, falling back to login") + } else { + return processAPIResponse(r, response, isAsync) + } } - return processAPIResponse(r, response, isAsync) - } else if len(r.Config.ActiveProfile.Username) > 0 && len(r.Config.ActiveProfile.Password) > 0 { + } + + if hasPasswordAuth { usingSessionAuth = true sessionKey, err := Login(r) if err != nil { diff --git a/cmd/network_test.go b/cmd/network_test.go index 6333dab..33d8e9b 100644 --- a/cmd/network_test.go +++ b/cmd/network_test.go @@ -20,6 +20,7 @@ package cmd import ( "fmt" "net/http" + "net/http/cookiejar" "net/http/httptest" "net/url" "path/filepath" @@ -107,6 +108,7 @@ func successResponse(command string) string { func newTestRequest(t *testing.T, serverURL string, signatureAlgorithm string) *Request { t.Helper() dir := t.TempDir() + jar, _ := cookiejar.New(nil) cfg := &config.Config{ Dir: dir, ConfigFile: filepath.Join(dir, "config"), @@ -127,7 +129,7 @@ func newTestRequest(t *testing.T, serverURL string, signatureAlgorithm string) * APIKey: testAPIKey, SecretKey: testSecretKey, SignatureAlgorithm: signatureAlgorithm, - Client: http.DefaultClient, + Client: &http.Client{Jar: jar}, }, } return NewRequest(GetAPIHandler(), cfg, nil, false) @@ -253,3 +255,165 @@ func TestAutoDoesNotRetryUserCommandDirectly(t *testing.T) { t.Fatalf("deployVirtualMachine attempt count = %d, want 1", userCommandAttempts) } } + +func newLoginFallbackTestServer(t *testing.T, loginResponseStatus int) *signatureTestServer { + t.Helper() + testServer := &signatureTestServer{} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + if err := req.ParseForm(); err != nil { + http.Error(w, "failed to parse request form", http.StatusBadRequest) + return + } + + command := req.Form.Get("command") + algorithm := "session" + if req.Form.Get("signature") != "" { + algorithm = identifySignatureAlgorithm(req.Form) + } + testServer.mu.Lock() + testServer.attempts = append(testServer.attempts, signatureAttempt{ + Command: command, + Algorithm: algorithm, + }) + testServer.mu.Unlock() + + w.Header().Set("Content-Type", "application/json") + if strings.EqualFold(command, "login") { + if loginResponseStatus != http.StatusOK { + w.WriteHeader(loginResponseStatus) + fmt.Fprint(w, `{"loginresponse":{"errorcode":531,"errortext":"Failed to authenticate user"}}`) + return + } + http.SetCookie(w, &http.Cookie{ + Name: "JSESSIONID", + Value: "test-jsession-id", + Path: "/", + }) + http.SetCookie(w, &http.Cookie{ + Name: "sessionkey", + Value: "test-session-key", + Path: "/", + }) + fmt.Fprint(w, `{"loginresponse":{"sessionkey":"test-session-key","username":"admin"}}`) + return + } + + if req.Form.Get("sessionkey") == "test-session-key" && req.Form.Get("apiKey") == "" { + fmt.Fprint(w, successResponse(command)) + return + } + + w.WriteHeader(http.StatusUnauthorized) + fmt.Fprint(w, `{"errorresponse":{"errorcode":401,"cserrorcode":9999,"errortext":"unable to verify user credentials and/or request signature"}}`) + })) + testServer.server = server + t.Cleanup(server.Close) + return testServer +} + +func TestAutoFallsBackToLoginWhenProfileAPIKeysAreInvalid(t *testing.T) { + server := newLoginFallbackTestServer(t, http.StatusOK) + request := newTestRequest(t, server.server.URL, config.SignatureAlgorithmAuto) + request.Config.ActiveProfile.APIKey = "invalid-api-key" + request.Config.ActiveProfile.SecretKey = "invalid-secret-key" + request.Config.ActiveProfile.Username = "admin" + request.Config.ActiveProfile.Password = "password" + request.CredentialsSupplied = false + + if _, err := NewAPIRequest(request, "listZones", nil, false); err != nil { + t.Fatalf("expected fallback to username/password login to succeed, got error: %v", err) + } + + if got := request.Config.ActiveProfile.SignatureAlgorithm; got != config.SignatureAlgorithmAuto { + t.Fatalf("signature algorithm = %q, want %q", got, config.SignatureAlgorithmAuto) + } + + attempts := server.snapshotAttempts() + if len(attempts) != 4 { + t.Fatalf("attempt count = %d, want 4: %+v", len(attempts), attempts) + } + if attempts[0].Command != "listApis" || attempts[1].Command != "listApis" { + t.Fatalf("expected two listApis signature probes first, got %+v", attempts[:2]) + } + if attempts[2] != (signatureAttempt{Command: "login", Algorithm: "session"}) { + t.Fatalf("third attempt = %+v, want login with session", attempts[2]) + } + if attempts[3] != (signatureAttempt{Command: "listZones", Algorithm: "session"}) { + t.Fatalf("fourth attempt = %+v, want listZones with session", attempts[3]) + } +} + +func TestExplicitSignatureAlgorithmFallsBackToLoginWhenProfileAPIKeysAreInvalid(t *testing.T) { + server := newLoginFallbackTestServer(t, http.StatusOK) + request := newTestRequest(t, server.server.URL, config.SignatureAlgorithmHmacSHA1) + request.Config.ActiveProfile.APIKey = "invalid-api-key" + request.Config.ActiveProfile.SecretKey = "invalid-secret-key" + request.Config.ActiveProfile.Username = "admin" + request.Config.ActiveProfile.Password = "password" + request.CredentialsSupplied = false + + if _, err := NewAPIRequest(request, "listZones", nil, false); err != nil { + t.Fatalf("expected fallback to username/password login to succeed, got error: %v", err) + } + + attempts := server.snapshotAttempts() + if len(attempts) != 3 { + t.Fatalf("attempt count = %d, want 3: %+v", len(attempts), attempts) + } + if attempts[0].Command != "listZones" { + t.Fatalf("first attempt = %+v, want listZones signed attempt", attempts[0]) + } + if attempts[1] != (signatureAttempt{Command: "login", Algorithm: "session"}) { + t.Fatalf("second attempt = %+v, want login with session", attempts[1]) + } + if attempts[2] != (signatureAttempt{Command: "listZones", Algorithm: "session"}) { + t.Fatalf("third attempt = %+v, want listZones with session", attempts[2]) + } +} + +func TestAutoDoesNotFallBackToLoginWhenCredentialsSuppliedOnCLI(t *testing.T) { + server := newLoginFallbackTestServer(t, http.StatusOK) + request := newTestRequest(t, server.server.URL, config.SignatureAlgorithmAuto) + request.Config.ActiveProfile.APIKey = "invalid-api-key" + request.Config.ActiveProfile.SecretKey = "invalid-secret-key" + request.Config.ActiveProfile.Username = "admin" + request.Config.ActiveProfile.Password = "password" + request.CredentialsSupplied = true + + _, err := NewAPIRequest(request, "listZones", nil, false) + if err == nil { + t.Fatal("expected request with invalid CLI credentials to fail without falling back to login") + } + if !strings.Contains(err.Error(), "unable to verify user credentials") { + t.Fatalf("expected server authentication error, got: %v", err) + } + + for _, attempt := range server.snapshotAttempts() { + if attempt.Command == "login" { + t.Fatalf("unexpected fallback to login when CredentialsSupplied is true: %+v", server.snapshotAttempts()) + } + } +} + +func TestAutoReturnsNonAuthProbeErrorImmediately(t *testing.T) { + probeCount := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + probeCount++ + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, `{"errorresponse":{"errorcode":530,"cserrorcode":9999,"errortext":"internal server error"}}`) + })) + t.Cleanup(server.Close) + + request := newTestRequest(t, server.URL, config.SignatureAlgorithmAuto) + _, err := NewAPIRequest(request, "listZones", nil, false) + if err == nil { + t.Fatal("expected non-auth probe failure to return an error") + } + if !strings.Contains(err.Error(), "internal server error") { + t.Fatalf("expected internal server error message, got: %v", err) + } + if probeCount != 1 { + t.Fatalf("probe count = %d, want 1", probeCount) + } +}