Skip to content

Commit

Permalink
Tests fix (#2978)
Browse files Browse the repository at this point in the history
Fix some test in order to stabilize master tests.

(cherry picked from commit 2f32536)
  • Loading branch information
tbuchaillot authored and Tyk Bot committed Apr 1, 2020
1 parent 4ad1005 commit 835b58c
Show file tree
Hide file tree
Showing 8 changed files with 62 additions and 21 deletions.
11 changes: 6 additions & 5 deletions certs/manager.go
Expand Up @@ -374,16 +374,17 @@ func (c *CertificateManager) ListRawPublicKey(keyID string) (out interface{}) {
func (c *CertificateManager) ListAllIds(prefix string) (out []string) {
indexKey := prefix + "-index"
exists, _ := c.storage.Exists(indexKey)
if !exists {
keys := c.storage.GetKeys("raw-" + prefix + "*")
if exists && prefix != "" {
keys, _ := c.storage.GetListRange(indexKey, 0, -1)
for _, key := range keys {
c.storage.AppendToSet(indexKey, key)
out = append(out, strings.TrimPrefix(key, "raw-"))
}

} else {
keys, _ := c.storage.GetListRange(indexKey, 0, -1)
keys := c.storage.GetKeys("raw-" + prefix + "*")
for _, key := range keys {
if prefix != "" {
c.storage.AppendToSet(indexKey, key)
}
out = append(out, strings.TrimPrefix(key, "raw-"))
}
}
Expand Down
29 changes: 17 additions & 12 deletions gateway/gateway_test.go
Expand Up @@ -1908,27 +1908,31 @@ func TestCache_singleErrorResponse(t *testing.T) {
}

func TestOverrideErrors(t *testing.T) {
defer ResetTestConfig()
defer defaultTykErrors()

assert := func(expectedError string, expectedCode int, actualError error, actualCode int) {
if !(expectedError == actualError.Error() && expectedCode == actualCode) {
t.Fatal("Override failed")
}
}

const message1 = "Message1"
const code1 = 1
const code1 = 901
const message2 = "Message2"
const code2 = 2
const code2 = 902
const message3 = "Message3"
const code3 = 3
const code3 = 903
const message4 = "Message4"
const code4 = 4
const code4 = 904
const message5 = "Message5"
const code5 = 5
const code5 = 905
const message6 = "Message6"
const code6 = 6
const code6 = 906

globalConf := config.Global()
globalConf.OverrideMessages = map[string]config.TykError{
testConf := config.Global()

testConf.OverrideMessages = map[string]config.TykError{
ErrOAuthAuthorizationFieldMissing: {
Message: message1,
Code: code1,
Expand All @@ -1954,7 +1958,7 @@ func TestOverrideErrors(t *testing.T) {
Code: code6,
},
}
config.SetGlobal(globalConf)
config.SetGlobal(testConf)

overrideTykErrors()

Expand All @@ -1977,15 +1981,16 @@ func TestOverrideErrors(t *testing.T) {
assert(message6, code6, e, i)

t.Run("Partial override", func(t *testing.T) {
globalConf.OverrideMessages = map[string]config.TykError{
testConf.OverrideMessages = map[string]config.TykError{
ErrOAuthAuthorizationFieldMissing: {
Code: code4,
},
ErrOAuthAuthorizationFieldMalformed: {
Message: message4,
},
}
config.SetGlobal(globalConf)

config.SetGlobal(testConf)

overrideTykErrors()

Expand All @@ -1994,6 +1999,6 @@ func TestOverrideErrors(t *testing.T) {

e, i = errorAndStatusCode(ErrOAuthAuthorizationFieldMalformed)
assert(message4, code2, e, i)

})

}
33 changes: 33 additions & 0 deletions gateway/handler_error.go
Expand Up @@ -30,6 +30,39 @@ func errorAndStatusCode(errType string) (error, int) {
return errors.New(err.Message), err.Code
}

func defaultTykErrors() {
TykErrors = make(map[string]config.TykError)
TykErrors[ErrAuthAuthorizationFieldMissing] = config.TykError{
Message: "Authorization field missing",
Code: http.StatusUnauthorized,
}

TykErrors[ErrAuthKeyNotFound] = config.TykError{
Message: "Access to this API has been disallowed",
Code: http.StatusForbidden,
}

TykErrors[ErrOAuthAuthorizationFieldMissing] = config.TykError{
Message: "Authorization field missing",
Code: http.StatusBadRequest,
}

TykErrors[ErrOAuthAuthorizationFieldMalformed] = config.TykError{
Message: "Bearer token malformed",
Code: http.StatusBadRequest,
}

TykErrors[ErrOAuthKeyNotFound] = config.TykError{
Message: "Key not authorised",
Code: http.StatusForbidden,
}

TykErrors[ErrOAuthClientDeleted] = config.TykError{
Message: "Key not authorised. OAuth client access was revoked",
Code: http.StatusForbidden,
}
}

func overrideTykErrors() {
for id, err := range config.Global().OverrideMessages {

Expand Down
1 change: 1 addition & 0 deletions gateway/middleware.go
Expand Up @@ -341,6 +341,7 @@ func (t BaseMiddleware) ApplyPolicies(session *user.SessionState) error {
// check if we already have limit on API level specified when policy was created
if accessRights.Limit == nil || *accessRights.Limit == (user.APILimit{}) {
// limit was not specified on API level so we will populate it from policy
idForScope = policy.ID
accessRights.Limit = &user.APILimit{
QuotaMax: policy.QuotaMax,
QuotaRenewalRate: policy.QuotaRenewalRate,
Expand Down
2 changes: 1 addition & 1 deletion gateway/mw_jwt.go
Expand Up @@ -582,7 +582,7 @@ func (k *JWTMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _
key, err := ParseRSAPublicKey(val)
if err != nil {
logger.WithError(err).Error("Failed to decode JWT key")
return nil, err
return nil, errors.New("Failed to decode JWT key")
}
return key, nil
default:
Expand Down
2 changes: 1 addition & 1 deletion gateway/mw_jwt_test.go
Expand Up @@ -1893,7 +1893,7 @@ func TestJWTRSAInvalidPublickKey(t *testing.T) {
ts.Run(t, test.TestCase{
Headers: authHeaders,
Code: http.StatusForbidden,
BodyMatch: "Key not authorized:Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key",
BodyMatch: "Failed to decode JWT key",
})
})
}
Expand Down
2 changes: 1 addition & 1 deletion gateway/policy_test.go
Expand Up @@ -509,7 +509,7 @@ func testPrepareApplyPolicies() (*BaseMiddleware, []testApplyPoliciesData) {
Rate: 300,
Per: 1,
},
AllowanceScope: "e",
AllowanceScope: "per_api_with_limit_set_from_policy",
},
"d": {
Limit: &user.APILimit{
Expand Down
3 changes: 2 additions & 1 deletion gateway/res_handler_header_injector_test.go
Expand Up @@ -113,6 +113,7 @@ func TestGlobalResponseHeaders(t *testing.T) {
spec.Proxy.ListenPath = "/"

spec.ResponseProcessors = []apidef.ResponseProcessor{{Name: "header_injector"}}

})[0]
LoadAPI(spec)

Expand All @@ -122,7 +123,7 @@ func TestGlobalResponseHeaders(t *testing.T) {
_, _ = ts.Run(t, test.TestCase{HeadersMatch: addedHeaders, HeadersNotMatch: removedHeaders})

// Add and remove global response headers
UpdateAPIVersion(spec, "Default", func(v *apidef.VersionInfo) {
UpdateAPIVersion(spec, "v1", func(v *apidef.VersionInfo) {
v.UseExtendedPaths = true
v.GlobalResponseHeaders = map[string]string{
"global-header": "global-value",
Expand Down

0 comments on commit 835b58c

Please sign in to comment.