Skip to content

Commit

Permalink
fix: return error during failed userinfo lookup
Browse files Browse the repository at this point in the history
Closes snyk#48.
  • Loading branch information
mcombuechen committed Oct 31, 2023
1 parent 8ce0d37 commit e9fe694
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
13 changes: 11 additions & 2 deletions lib/snyk/self.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ package snyk
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"

"github.com/deepmap/oapi-codegen/pkg/securityprovider"
"github.com/google/uuid"
Expand Down Expand Up @@ -46,12 +49,18 @@ func getSnykOrg(auth *securityprovider.SecurityProviderApiKey) (*uuid.UUID, erro
return nil, err
}

if self.HTTPResponse.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Failed to get user info (%s).", self.HTTPResponse.Status)
}

var userInfo selfDocument
if err = json.Unmarshal(self.Body, &userInfo); err != nil {
return nil, err
}

org := userInfo.Data.Attributes.DefaultOrgContext
if org := userInfo.Data.Attributes.DefaultOrgContext; org != nil {
return org, nil
}

return org, nil
return nil, errors.New("Failed to get org ID.")
}
20 changes: 18 additions & 2 deletions lib/snyk/self_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package snyk

import (
"net/http"
"testing"

"github.com/deepmap/oapi-codegen/pkg/securityprovider"
Expand All @@ -26,18 +27,33 @@ import (
"github.com/stretchr/testify/require"
)

func TestGetSnykOrg(t *testing.T) {
func TestGetSnykOrg_Success(t *testing.T) {
expectedOrg := uuid.MustParse("00000000-0000-0000-0000-000000000000")
auth, err := securityprovider.NewSecurityProviderApiKey("header", "name", "value")
require.NoError(t, err)

httpmock.Activate()
defer httpmock.DeactivateAndReset()
httpmock.RegisterResponder("GET", "https://api.snyk.io/rest/self",
httpmock.NewJsonResponderOrPanic(200, httpmock.File("testdata/self.json")),
httpmock.NewJsonResponderOrPanic(http.StatusOK, httpmock.File("testdata/self.json")),
)

actualOrg, err := getSnykOrg(auth)
assert.NoError(t, err)
assert.Equal(t, expectedOrg, *actualOrg)
}

func TestGetSnykOrg_Unauthorized(t *testing.T) {
auth, err := securityprovider.NewSecurityProviderApiKey("header", "name", "value")
require.NoError(t, err)

httpmock.Activate()
defer httpmock.DeactivateAndReset()
httpmock.RegisterResponder("GET", "https://api.snyk.io/rest/self",
httpmock.NewJsonResponderOrPanic(http.StatusUnauthorized, []byte(`{"msg":"unauthorized"}`)),
)

actualOrg, err := getSnykOrg(auth)
assert.ErrorContains(t, err, "Failed to get user info (401)")
assert.Nil(t, actualOrg)
}

0 comments on commit e9fe694

Please sign in to comment.