Skip to content

Commit

Permalink
feat: Env var license key
Browse files Browse the repository at this point in the history
  • Loading branch information
noahmmcgivern committed Aug 6, 2024
1 parent c6f4f83 commit 1e1e678
Show file tree
Hide file tree
Showing 4 changed files with 134 additions and 26 deletions.
86 changes: 66 additions & 20 deletions internal/install/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,12 @@ var Command = &cobra.Command{
logLevel := configAPI.GetLogLevel()
config.InitFileLogger(logLevel)

detailErr := validateProfile(config.DefaultMaxTimeoutSeconds)
detailErr := validateProfile()
if detailErr != nil {
log.Fatal(detailErr)

Check failure

Code scanning / CodeQL

Clear-text logging of sensitive information High

Sensitive data returned by an access to APIKeyMissing
flows to a logging call.
Sensitive data returned by an access to InvalidUserAPIKeyFormat
flows to a logging call.
}

detailErr = fetchLicenseKey()
if detailErr != nil {
log.Fatal(detailErr)
}
Expand Down Expand Up @@ -104,21 +109,20 @@ func init() {
Command.Flags().StringSliceVarP(&tags, "tag", "", []string{}, "the tags to add during install, can be multiple. Example: --tag tag1:test,tag2:test")
}

func validateProfile(maxTimeoutSeconds int) *types.DetailError {
func validateProfile() *types.DetailError {
accountID := configAPI.GetActiveProfileAccountID()
APIKey := configAPI.GetActiveProfileString(config.APIKey)
apiKey := configAPI.GetActiveProfileString(config.APIKey)
region := configAPI.GetActiveProfileString(config.Region)
licenseKey := configAPI.GetActiveProfileString(config.LicenseKey)

if accountID == 0 {
return types.NewDetailError(types.EventTypes.AccountIDMissing, "Account ID is required.")
}

if APIKey == "" {
if apiKey == "" {
return types.NewDetailError(types.EventTypes.APIKeyMissing, "User API key is required.")
}

if !utils.IsValidUserAPIKeyFormat(APIKey) {
if !utils.IsValidUserAPIKeyFormat(apiKey) {
return types.NewDetailError(types.EventTypes.InvalidUserAPIKeyFormat, `Invalid user API key format detected. Please provide a valid user API key. User API keys usually have a prefix of "NRAK-" or "NRAA-".`)
}

Expand All @@ -134,19 +138,6 @@ func validateProfile(maxTimeoutSeconds int) *types.DetailError {
return types.NewDetailError(types.EventTypes.UnableToConnect, err.Error())
}

if licenseKey == "" {
_licenseKey, err := client.FetchLicenseKey(accountID, config.FlagProfileName, &maxTimeoutSeconds)
if err != nil {
message := fmt.Sprintf("could not fetch license key for account %d:, license key: %v %s", accountID, utils.Obfuscate(licenseKey), err)
log.Debug(message)
return types.NewDetailError(types.EventTypes.UnableToFetchLicenseKey, fmt.Sprintf("%s", err))
}
licenseKey = _licenseKey
}

os.Setenv("NEW_RELIC_LICENSE_KEY", licenseKey)
log.Debugf("using license key %s", utils.Obfuscate(licenseKey))

return nil
}

Expand All @@ -158,20 +149,75 @@ func checkNetwork() error {
err := client.NRClient.TestEndpoints()
if err != nil {
if IsProxyConfigured() {
proxyConfig := httpproxy.FromEnvironment()

log.Warn("Proxy settings have been configured, but we are still unable to connect to the New Relic platform.")
log.Warn("You may need to adjust your proxy environment variables or configure your proxy to allow the specified domain.")
log.Warn("Current proxy config:")
proxyConfig := httpproxy.FromEnvironment()
log.Warnf(" HTTPS_PROXY=%s", proxyConfig.HTTPSProxy)
log.Warnf(" HTTP_PROXY=%s", proxyConfig.HTTPProxy)
log.Warnf(" NO_PROXY=%s", proxyConfig.NoProxy)
} else {
log.Warn("Failed to connect to the New Relic platform.")
log.Warn("If you need to use a proxy, consider setting the HTTPS_PROXY environment variable, then try again.")
}

log.Warn("More information about proxy configuration: https://github.com/newrelic/newrelic-cli/blob/main/docs/GETTING_STARTED.md#using-an-http-proxy")
log.Warn("More information about network requirements: https://docs.newrelic.com/docs/new-relic-solutions/get-started/networks/")
}

return err
}

// Attempt to fetch and set a license key through 3 methods:
// 1. NEW_RELIC_LICENSE_KEY environment variable,
// 2. Active profile config.LicenseKey,
// 3. API call,
// returns an error if all methods fail.
func fetchLicenseKey() *types.DetailError {
accountID := configAPI.GetActiveProfileAccountID()

var licenseKey string

defer func() {
os.Setenv("NEW_RELIC_LICENSE_KEY", licenseKey)
log.Debug("using license key: ", utils.Obfuscate(licenseKey))
}()

// fetch licenseKey from environment
licenseKey = os.Getenv("NEW_RELIC_LICENSE_KEY")

if utils.IsValidLicenseKeyFormat(licenseKey) {
return nil
}

if licenseKey != "" {
log.Debug("license key provided via NEW_RELIC_LICENSE_KEY is invalid")
}

// fetch licenseKey from active profile
licenseKey = configAPI.GetActiveProfileString(config.LicenseKey)

if utils.IsValidLicenseKeyFormat(licenseKey) {
return nil
}

if licenseKey != "" {
log.Debug("license key provided by config is invalid")
}

// fetch licenseKey via API
maxTimeoutSeconds := config.DefaultMaxTimeoutSeconds

licenseKey, err := client.FetchLicenseKey(accountID, config.FlagProfileName, &maxTimeoutSeconds)

if err != nil {
err = fmt.Errorf("could not fetch license key for accountID (%d): %s",
accountID,
err.Error())

return types.NewDetailError(types.EventTypes.UnableToFetchLicenseKey, err.Error())
}

return nil
}
36 changes: 30 additions & 6 deletions internal/install/command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func TestInstallCommand(t *testing.T) {
testcobra.CheckCobraMetadata(t, Command)
testcobra.CheckCobraRequiredFlags(t, Command, []string{})
}
func TestCommandValidProfile(t *testing.T) {
func TestValidateProfile(t *testing.T) {
accountID := os.Getenv("NEW_RELIC_ACCOUNT_ID")
apiKey := os.Getenv("NEW_RELIC_API_KEY")
region := os.Getenv("NEW_RELIC_REGION")
Expand All @@ -31,7 +31,7 @@ func TestCommandValidProfile(t *testing.T) {
defer server.Close()

os.Setenv("NEW_RELIC_ACCOUNT_ID", "")
err := validateProfile(5)
err := validateProfile()
assert.Error(t, err)
assert.Equal(t, types.EventTypes.AccountIDMissing, err.EventName)

Expand All @@ -42,11 +42,11 @@ func TestCommandValidProfile(t *testing.T) {
}

os.Setenv("NEW_RELIC_API_KEY", "")
err = validateProfile(5)
err = validateProfile()
assert.Equal(t, types.EventTypes.APIKeyMissing, err.EventName)

os.Setenv("NEW_RELIC_API_KEY", "67890")
err = validateProfile(5)
err = validateProfile()
assert.Equal(t, types.EventTypes.InvalidUserAPIKeyFormat, err.EventName)

if apiKey == "" {
Expand All @@ -56,18 +56,42 @@ func TestCommandValidProfile(t *testing.T) {
}

os.Setenv("NEW_RELIC_REGION", "au")
err = validateProfile(5)
err = validateProfile()
assert.Equal(t, types.EventTypes.InvalidRegion, err.EventName)

os.Setenv("NEW_RELIC_REGION", "")
err = validateProfile(5)
err = validateProfile()
assert.Equal(t, types.EventTypes.RegionMissing, err.EventName)

os.Setenv("NEW_RELIC_ACCOUNT_ID", accountID)
os.Setenv("NEW_RELIC_REGION", region)
os.Setenv("NEW_RELIC_API_KEY", apiKey)
}

func TestFetchLicenseKey(t *testing.T) {
okCase := func() *types.DetailError { return nil }()
// Error case
// err := fetchLicenseKey()
// assert.Equal(t, types.EventTypes.UnableToFetchLicenseKey, err.EventName)

// licenseKey := os.Getenv("NEW_RELIC_LICENSE_KEY")
// assert.Equal(t, "", licenseKey)

// TODO: From API (mock?)

// TODO: From profile

// From environment variable
expect := "0123456789abcdefABCDEF0123456789abcdNRAL"
os.Setenv("NEW_RELIC_LICENSE_KEY", expect)

err := fetchLicenseKey()
assert.Equal(t, okCase, err)

actual := os.Getenv("NEW_RELIC_LICENSE_KEY")
assert.Equal(t, expect, actual)
}

func initSegmentMockServer() *httptest.Server {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
Expand Down
19 changes: 19 additions & 0 deletions internal/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,3 +204,22 @@ func IsValidUserAPIKeyFormat(key string) bool {

return isAlphanumeric
}

// Returns true if the given license key is valid.
// A valid license key is 40 characters in length,
// ends with "NRAL", and has a hexidecimal prefix.

Check failure on line 210 in internal/utils/utils.go

View workflow job for this annotation

GitHub Actions / lint

"hexidecimal" is a misspelling of "hexadecimal"

Check failure on line 210 in internal/utils/utils.go

View workflow job for this annotation

GitHub Actions / lint

`hexidecimal` is a misspelling of `hexadecimal` (misspell)
func IsValidLicenseKeyFormat(licenseKey string) bool {
if len(licenseKey) != 40 {
return false
}

suffix := "NRAL"

if !strings.HasSuffix(licenseKey, suffix) {
return false
}

prefix := strings.TrimSuffix(licenseKey, suffix)

return regexp.MustCompile("^[a-fA-F0-9]*$").MatchString(prefix)
}
19 changes: 19 additions & 0 deletions internal/utils/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,3 +123,22 @@ func TestIsValidUserAPIKeyFormat_Invalid(t *testing.T) {
result = IsValidUserAPIKeyFormat("NRAK-@$%^!")
assert.False(t, result)
}

func TestIsValidLicenseKeyFormat_Valid(t *testing.T) {
result := IsValidLicenseKeyFormat("0123456789abcdefABCDEF0123456789abcdNRAL")
assert.True(t, result)
}

func TestIsValidLicenseKeyFormat_Invalid(t *testing.T) {
// Invalid length
result := IsValidLicenseKeyFormat("0123456789abcefNRAL")
assert.False(t, result)

// Invalid suffix
result = IsValidLicenseKeyFormat("0123456789abcdefABCDEF0123456789abcdNRAK")
assert.False(t, result)

// Invalid characters
result = IsValidLicenseKeyFormat("0123456789ghijklGHIJKL0123456789ghijNRAL")
assert.False(t, result)
}

0 comments on commit 1e1e678

Please sign in to comment.