Skip to content

Commit

Permalink
[NET-687] On license validation fail, parse and store the message of …
Browse files Browse the repository at this point in the history
…the response (#2669)

* On license validation fail, parse and store the message of the response

* Return cached response body when necessary

* Have license validation return proper val,err
  • Loading branch information
gabrielseibel1 authored Nov 17, 2023
1 parent 27378b9 commit 0a88fde
Showing 1 changed file with 31 additions and 20 deletions.
51 changes: 31 additions & 20 deletions pro/license.go
Original file line number Diff line number Diff line change
Expand Up @@ -213,35 +213,46 @@ func validateLicenseKey(encryptedData []byte, publicKey *[32]byte) ([]byte, erro
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
client := &http.Client{}
var body []byte
validateResponse, err := client.Do(req)
if err != nil { // check cache
body, err = getCachedResponse()
if err != nil {
return nil, err
}
slog.Warn("proceeding with cached response, Netmaker API may be down")
} else {
defer validateResponse.Body.Close()
if validateResponse.StatusCode != http.StatusOK {
err := fmt.Errorf("could not validate license, got status code %d", validateResponse.StatusCode)
// if it's a temp error, just log it, don't consider license invalid
if validateResponse.StatusCode == http.StatusServiceUnavailable ||
validateResponse.StatusCode == http.StatusGatewayTimeout {
slog.Warn(err.Error())
return nil, nil
}
return nil, err
} // if you received a 200 cache the response locally
return getCachedResponse()
}
defer validateResponse.Body.Close()
code := validateResponse.StatusCode

body, err = io.ReadAll(validateResponse.Body)
// if we received a 200, cache the response locally
if code == http.StatusOK {
body, err := io.ReadAll(validateResponse.Body)
if err != nil {
slog.Warn("failed to parse response", "error", err)
return nil, err
}
cacheResponse(body)
if err := cacheResponse(body); err != nil {
slog.Warn("failed to cache response", "error", err)
}
return body, nil
}

// at this point the backend returned some undesired state

// inform failure via logs
err = fmt.Errorf("could not validate license with validation backend, got status code %d", validateResponse.StatusCode)
slog.Warn(err.Error())
body, err := io.ReadAll(validateResponse.Body)
if err != nil {
slog.Warn(err.Error())
}
slog.Warn("license-validation backend response: %s", string(body))

// try to use cache if we had a temporary error
if code == http.StatusServiceUnavailable || code == http.StatusGatewayTimeout {
slog.Warn("proceeding with cached response, Netmaker API may be down")
return getCachedResponse()
}

return body, err
// at this point the error is irreversible, return it
return nil, err
}

func getAccountsHost() string {
Expand Down

0 comments on commit 0a88fde

Please sign in to comment.