Skip to content

cmd: fix signature algorithm detection error shadowing and login fallback - #230

Open
Paramveersingh-S wants to merge 1 commit into
apache:mainfrom
Paramveersingh-S:fix/auto-signature-algorithm-login-fallback
Open

Paramveersingh-S wants to merge 1 commit into
apache:mainfrom
Paramveersingh-S:fix/auto-signature-algorithm-login-fallback

Conversation

@Paramveersingh-S

Copy link
Copy Markdown

Fixes #226

Problem

Commit c3c3377 (Support API signing with HmacSHA512 (#213)) introduced two regressions in cmd/network.go when a profile has signaturealgorithm = auto (the default for new and migrated profiles) alongside invalid/stale apikey/secretkey and valid username/password:

  1. Error variable shadowing in detectSignatureAlgorithm (cmd/network.go:385-396):

    if _, err := parseAPIResponse(body); err == nil {
        ...
        return algorithm, nil
    }
    lastErr = err
    if isAuthenticationFailure(response.StatusCode, err) {
        ...
    } else {
        return "", err
    }

    Because if _, err := parseAPIResponse(body); err == nil shadows the outer err (returned by executeSignedAPIRequest, which is nil once an HTTP response is received), err after the if block is always nil:

    • lastErr = err overwrites lastErr with nil on every failed HTTP probe, causing detectSignatureAlgorithm to discard the parsed CloudStack API error and fall through to the generic errors.New("failed to detect signature algorithm").
    • When a probe fails with a non-authentication HTTP status (e.g., HTTP 500), return "", err returns "", nil, causing signRequest to fail downstream with signature algorithm must be concrete.
  2. Missing fallback to username/password login when profile apikey/secretkey fail (cmd/network.go:481-495):

    • Prior to #213 (and preserved by #174 when !r.CredentialsSupplied), if a profile in .cmk/config contained both apikey/secretkey and username/password and the API key was stale or invalid (returning HTTP 401), NewAPIRequest fell back to Login(r) with username/password when credentials were not supplied on the command line (!r.CredentialsSupplied).
    • After #213, NewAPIRequest returned immediately inside the if len(r.Config.ActiveProfile.APIKey) > 0 && len(r.Config.ActiveProfile.SecretKey) > 0 branch on both signature detection failure (signaturealgorithm = auto) and HTTP 401 response (signaturealgorithm = HmacSHA1 / HmacSHA512), never falling back to Login(r).

Solution

  1. In detectSignatureAlgorithm:
    • Assign the result of parseAPIResponse(body) to parseErr (avoiding shadowing the outer err) and close response.Body immediately after reading inside the probe loop.
    • Record lastErr = parseErr, pass parseErr to isAuthenticationFailure(response.StatusCode, parseErr), and return "", parseErr on non-authentication probe errors.
  2. In NewAPIRequest:
    • Clone params before attaching apiKey so the base request parameters stay clean if API-key auth falls back to session login.
    • When !r.CredentialsSupplied and username/password are configured in the active profile:
      • If activeSignatureAlgorithm(r) fails with an authentication error (isAuthenticationFailure(0, err)), fall through to Login(r) session authentication.
      • If executeSignedAPIRequest returns http.StatusUnauthorized (401), close the response body and fall through to Login(r) session authentication.
    • When r.CredentialsSupplied is true (CLI -k/-s or environment variables) or username/password are not configured, preserve #174 behavior and return the error directly without falling back to Login(r).

Verification / Solution Proof

Added four unit tests in cmd/network_test.go:

  • TestAutoFallsBackToLoginWhenProfileAPIKeysAreInvalid: verifies that when a profile has signaturealgorithm = auto, invalid apikey/secretkey, and valid username/password (CredentialsSupplied = false), NewAPIRequest probes HmacSHA512 and HmacSHA1, falls back to Login (command=login), completes the command with sessionkey (without sending apiKey), and keeps signaturealgorithm = auto.
  • TestExplicitSignatureAlgorithmFallsBackToLoginWhenProfileAPIKeysAreInvalid: verifies that an explicit HmacSHA1 profile with invalid apikey/secretkey and valid username/password (CredentialsSupplied = false) falls back to Login on HTTP 401.
  • TestAutoDoesNotFallBackToLoginWhenCredentialsSuppliedOnCLI: verifies that when CredentialsSupplied = true, NewAPIRequest does not fall back to Login and surfaces the server's parsed authentication error ((HTTP 401, error code 9999) unable to verify user credentials and/or request signature) instead of "failed to detect signature algorithm".
  • TestAutoReturnsNonAuthProbeErrorImmediately: verifies that a non-authentication error during probing (HTTP 500) is returned immediately on the first probe instead of returning "", nil.
$ go test -mod=vendor -v ./cli ./cmd ./config
=== RUN   TestFindAutocompleteAPIRelatedNounMatch
--- PASS: TestFindAutocompleteAPIRelatedNounMatch (0.00s)
...
=== RUN   TestAutoFallsBackToLoginWhenProfileAPIKeysAreInvalid
--- PASS: TestAutoFallsBackToLoginWhenProfileAPIKeysAreInvalid (0.01s)
=== RUN   TestExplicitSignatureAlgorithmFallsBackToLoginWhenProfileAPIKeysAreInvalid
--- PASS: TestExplicitSignatureAlgorithmFallsBackToLoginWhenProfileAPIKeysAreInvalid (0.01s)
=== RUN   TestAutoDoesNotFallBackToLoginWhenCredentialsSuppliedOnCLI
--- PASS: TestAutoDoesNotFallBackToLoginWhenCredentialsSuppliedOnCLI (0.01s)
=== RUN   TestAutoReturnsNonAuthProbeErrorImmediately
--- PASS: TestAutoReturnsNonAuthProbeErrorImmediately (0.01s)
PASS
ok  	github.com/apache/cloudstack-cloudmonkey/cmd	2.732s

Copilot AI balanced review requested due to automatic review settings November 23, 2026 06:42

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@Paramveersingh-S

Copy link
Copy Markdown
Author

cc @sureshanaparti @weizhouapache @borisstoyanov for review whenever you get a chance — fixes #226 (err := shadowing in detectSignatureAlgorithm and fallback when listCapabilities fails prior to login).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

"Error: failed to detect signature algorithm" during first sync with signaturealgorithm = auto in the profile

2 participants