Skip to content

Commit

Permalink
feat: add IsForbiddenErr error checking for 403s
Browse files Browse the repository at this point in the history
  • Loading branch information
GGabriele committed Jan 13, 2023
1 parent e0fcd03 commit b1e27cf
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
10 changes: 10 additions & 0 deletions kong/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,13 @@ func IsNotFoundErr(e error) bool {
}
return false
}

// IsForbiddenErr returns true if the error or its cause is
// a 403 response from Kong.
func IsForbiddenErr(e error) bool {
var apiErr *APIError
if errors.As(e, &apiErr) {
return apiErr.httpCode == http.StatusForbidden
}
return false
}
29 changes: 29 additions & 0 deletions kong/error_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package kong
import (
"errors"
"fmt"
"net/http"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -49,3 +50,31 @@ func TestAPIError_Code(T *testing.T) {
require.True(ok)
assert.True(kongErr.Code() == 404)
}

func TestIsForbiddenErrE2E(T *testing.T) {
assert := assert.New(T)

// Create the http client with a custom transport
// always returning a 403
forbiddenTransport := &forbiddenTransport{}
httpClient := &http.Client{
Transport: forbiddenTransport,
}
// if KONG_ADMIN_TOKEN is set, a different custom transport would be used
T.Setenv("KONG_ADMIN_TOKEN", "")

client, err := NewTestClient(nil, httpClient)
assert.NoError(err)
assert.NotNil(client)

_, err = client.Consumers.ListAll(defaultCtx)
assert.NotNil(err)
assert.True(IsForbiddenErr(err))
}

type forbiddenTransport struct{}

func (ft *forbiddenTransport) RoundTrip(req *http.Request) (*http.Response, error) {
// Create a new response with 403 status code
return nil, NewAPIError(http.StatusForbidden, "Enterprise license missing or expired")
}

0 comments on commit b1e27cf

Please sign in to comment.