Skip to content

Commit

Permalink
Merge 8ca2b82 into 6e8bd83
Browse files Browse the repository at this point in the history
  • Loading branch information
dencoded committed Aug 27, 2019
2 parents 6e8bd83 + 8ca2b82 commit dd27e79
Show file tree
Hide file tree
Showing 13 changed files with 97 additions and 30 deletions.
5 changes: 3 additions & 2 deletions gateway/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@ func handleAddOrUpdate(keyName string, r *http.Request, isHashed bool) (interfac

// get original session in case of update and preserve fields that SHOULD NOT be updated
originalKey := user.SessionState{}
originalKeyName := keyName
if r.Method == http.MethodPut {
found := false
for apiID := range newSession.AccessRights {
Expand Down Expand Up @@ -367,6 +368,7 @@ func handleAddOrUpdate(keyName string, r *http.Request, isHashed bool) (interfac
}
} else {
newSession.DateCreated = time.Now()
keyName = generateToken(newSession.OrgID, keyName)
}

// Update our session object (create it)
Expand All @@ -375,7 +377,6 @@ func handleAddOrUpdate(keyName string, r *http.Request, isHashed bool) (interfac
// Only if it's NEW
switch r.Method {
case http.MethodPost:
keyName = generateToken(newSession.OrgID, keyName)
// It's a create, so lets hash the password
setSessionPassword(&newSession)
case http.MethodPut:
Expand Down Expand Up @@ -406,7 +407,7 @@ func handleAddOrUpdate(keyName string, r *http.Request, isHashed bool) (interfac
})

response := apiModifyKeySuccess{
Key: keyName,
Key: originalKeyName,
Status: "ok",
Action: action,
}
Expand Down
11 changes: 8 additions & 3 deletions gateway/api_definition.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,10 @@ import (

sprig "gopkg.in/Masterminds/sprig.v2"

"github.com/gorilla/mux"

"github.com/TykTechnologies/tyk/headers"
"github.com/TykTechnologies/tyk/rpc"
"github.com/gorilla/mux"

circuit "github.com/rubyist/circuitbreaker"
"github.com/sirupsen/logrus"
Expand Down Expand Up @@ -248,8 +249,12 @@ func (a APIDefinitionLoader) MakeSpec(def *apidef.APIDefinition, logger *logrus.
// Add any new session managers or auth handlers here
spec.AuthManager = &DefaultAuthorisationManager{}

spec.SessionManager = &DefaultSessionManager{}
spec.OrgSessionManager = &DefaultSessionManager{}
spec.SessionManager = &DefaultSessionManager{
orgID: spec.OrgID,
}
spec.OrgSessionManager = &DefaultSessionManager{
orgID: spec.OrgID,
}

spec.GlobalConfig = config.Global()

Expand Down
18 changes: 10 additions & 8 deletions gateway/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ func TestKeyHandler(t *testing.T) {
AccessRights: map[string]user.AccessDefinition{"test": {
APIID: "test", Versions: []string{"v1"},
}},
OrgID: "default",
}
policiesMu.Unlock()
withPolicy := CreateStandardSession()
Expand Down Expand Up @@ -280,6 +281,7 @@ func TestKeyHandler_UpdateKey(t *testing.T) {
spec.APIID = testAPIID
spec.UseKeylessAccess = false
spec.Auth.UseParam = true
spec.OrgID = "default"
})

pID := CreatePolicy(func(p *user.Policy) {
Expand Down Expand Up @@ -428,8 +430,8 @@ func testHashKeyHandlerHelper(t *testing.T, expectedHashSize int) {
}}
withAccessJSON, _ := json.Marshal(withAccess)

myKey := generateToken("", "")
myKeyHash := storage.HashKey(myKey)
myKey := "my_key_id"
myKeyHash := storage.HashKey(generateToken("default", myKey))

if len(myKeyHash) != expectedHashSize {
t.Errorf("Expected hash size: %d, got %d. Hash: %s. Key: %s", expectedHashSize, len(myKeyHash), myKeyHash, myKey)
Expand Down Expand Up @@ -472,10 +474,10 @@ func testHashKeyHandlerHelper(t *testing.T, expectedHashSize int) {
Code: 200,
BodyMatch: fmt.Sprintf(`"key":"%s"`, myKeyHash),
},
// get one key by key name
// get one key by key name (API specified)
{
Method: "GET",
Path: "/tyk/keys/" + myKey,
Path: "/tyk/keys/" + myKey + "?api_id=test",
Data: string(withAccessJSON),
AdminAuth: true,
Code: 200,
Expand Down Expand Up @@ -594,7 +596,7 @@ func TestHashKeyListingDisabled(t *testing.T) {
withAccessJSON, _ := json.Marshal(withAccess)

myKey := "my_key_id"
myKeyHash := storage.HashKey(myKey)
myKeyHash := storage.HashKey(generateToken("default", myKey))

t.Run("Create, get and delete key with key hashing", func(t *testing.T) {
ts.Run(t, []test.TestCase{
Expand Down Expand Up @@ -624,10 +626,10 @@ func TestHashKeyListingDisabled(t *testing.T) {
Code: 200,
BodyMatch: fmt.Sprintf(`"key_hash":"%s"`, myKeyHash),
},
// get one key by key name
// get one key by key name (API specified)
{
Method: "GET",
Path: "/tyk/keys/" + myKey,
Path: "/tyk/keys/" + myKey + "?api_id=test",
Data: string(withAccessJSON),
AdminAuth: true,
Code: 200,
Expand Down Expand Up @@ -712,7 +714,7 @@ func TestHashKeyHandlerHashingDisabled(t *testing.T) {
withAccessJSON, _ := json.Marshal(withAccess)

myKey := "my_key_id"
myKeyHash := storage.HashKey(myKey)
myKeyHash := storage.HashKey(generateToken("default", myKey))

t.Run("Create, get and delete key with key hashing", func(t *testing.T) {
ts.Run(t, []test.TestCase{
Expand Down
25 changes: 22 additions & 3 deletions gateway/auth_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ import (
"sync"
"time"

uuid "github.com/satori/go.uuid"

"github.com/TykTechnologies/tyk/config"
"github.com/TykTechnologies/tyk/storage"
"github.com/TykTechnologies/tyk/user"
uuid "github.com/satori/go.uuid"

"github.com/sirupsen/logrus"
)
Expand Down Expand Up @@ -117,6 +118,7 @@ type DefaultSessionManager struct {
store storage.Handler
asyncWrites bool
disableCacheSessionState bool
orgID string
}

type SessionUpdate struct {
Expand Down Expand Up @@ -267,7 +269,10 @@ func (b *DefaultSessionManager) RemoveSession(keyName string, hashed bool) bool
if hashed {
return b.store.DeleteRawKey(b.store.GetKeyPrefix() + keyName)
} else {
return b.store.DeleteKey(keyName)
// support both old and new key hashing
res1 := b.store.DeleteKey(keyName)
res2 := b.store.DeleteKey(generateToken(b.orgID, keyName))
return res1 || res2
}
}

Expand All @@ -281,7 +286,21 @@ func (b *DefaultSessionManager) SessionDetail(keyName string, hashed bool) (user
if hashed {
jsonKeyVal, err = b.store.GetRawKey(b.store.GetKeyPrefix() + keyName)
} else {
jsonKeyVal, err = b.store.GetKey(keyName)
// try to get legacy and new format key at once
var jsonKeyValList []string
jsonKeyValList, err = b.store.GetMultiKey(
[]string{
keyName,
generateToken(b.orgID, keyName),
},
)
// pick the 1st non empty from the returned list
for _, val := range jsonKeyValList {
if val != "" {
jsonKeyVal = val
break
}
}
}

if err != nil {
Expand Down
1 change: 1 addition & 0 deletions gateway/cert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,7 @@ func TestKeyWithCertificateTLS(t *testing.T) {
spec.BaseIdentityProvidedBy = apidef.AuthToken
spec.Auth.UseCertificate = true
spec.Proxy.ListenPath = "/"
spec.OrgID = "default"
})

client := getTLSClient(&clientCert, nil)
Expand Down
6 changes: 6 additions & 0 deletions gateway/ldap_auth_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,12 @@ func (l *LDAPStorageHandler) GetKey(filter string) (string, error) {
return "", nil
}

func (r *LDAPStorageHandler) GetMultiKey(keyNames []string) ([]string, error) {
log.Warning("Not implementated")

return nil, nil
}

func (l *LDAPStorageHandler) GetRawKey(filter string) (string, error) {
log.Warning("Not implementated")

Expand Down
3 changes: 1 addition & 2 deletions gateway/mw_auth_key_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,7 @@ func TestMurmur3CharBug(t *testing.T) {

ts.Run(t, []test.TestCase{
genTestCase("wrong", 403),
// Should reject instead, just to show bug
genTestCase(key+"abc", 200),
genTestCase(key+"abc", 403),
genTestCase(key, 200),
}...)
})
Expand Down
9 changes: 7 additions & 2 deletions gateway/mw_jwt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -902,6 +902,7 @@ func TestJWTScopeToPolicyMapping(t *testing.T) {
spec.JWTIdentityBaseField = "user_id"
spec.JWTPolicyFieldName = "policy_id"
spec.Proxy.ListenPath = "/api1"
spec.OrgID = "default"
})[0]

p1ID := CreatePolicy(func(p *user.Policy) {
Expand All @@ -928,6 +929,7 @@ func TestJWTScopeToPolicyMapping(t *testing.T) {
spec.JWTIdentityBaseField = "user_id"
spec.JWTPolicyFieldName = "policy_id"
spec.Proxy.ListenPath = "/api2"
spec.OrgID = "default"
})[0]

p2ID := CreatePolicy(func(p *user.Policy) {
Expand All @@ -954,6 +956,7 @@ func TestJWTScopeToPolicyMapping(t *testing.T) {
spec.JWTIdentityBaseField = "user_id"
spec.JWTPolicyFieldName = "policy_id"
spec.Proxy.ListenPath = "/api3"
spec.OrgID = "default"
})[0]

spec := BuildAPI(func(spec *APISpec) {
Expand All @@ -969,6 +972,7 @@ func TestJWTScopeToPolicyMapping(t *testing.T) {
"user:read": p1ID,
"user:write": p2ID,
}
spec.OrgID = "default"
})[0]

LoadAPI(spec, spec1, spec2, spec3)
Expand All @@ -995,7 +999,7 @@ func TestJWTScopeToPolicyMapping(t *testing.T) {
})

// check that key has right set of policies assigned - there should be all three - base one and two from scope
sessionID := generateToken("", fmt.Sprintf("%x", md5.Sum([]byte(userID))))
sessionID := generateToken("default", fmt.Sprintf("%x", md5.Sum([]byte(userID))))
t.Run("Request to check that session has got correct apply_policies value", func(t *testing.T) {
ts.Run(
t,
Expand Down Expand Up @@ -1076,6 +1080,7 @@ func TestJWTExistingSessionRSAWithRawSourcePolicyIDChanged(t *testing.T) {
spec.JWTIdentityBaseField = "user_id"
spec.JWTPolicyFieldName = "policy_id"
spec.Proxy.ListenPath = "/"
spec.OrgID = "default"
})[0]

LoadAPI(spec)
Expand All @@ -1095,7 +1100,7 @@ func TestJWTExistingSessionRSAWithRawSourcePolicyIDChanged(t *testing.T) {
t.Claims.(jwt.MapClaims)["exp"] = time.Now().Add(time.Hour * 72).Unix()
})

sessionID := generateToken("", fmt.Sprintf("%x", md5.Sum([]byte("user"))))
sessionID := generateToken("default", fmt.Sprintf("%x", md5.Sum([]byte("user"))))

authHeaders := map[string]string{"authorization": jwtToken}
t.Run("Initial request with 1st policy", func(t *testing.T) {
Expand Down
4 changes: 2 additions & 2 deletions gateway/policy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -748,7 +748,7 @@ func TestPerAPIPolicyUpdate(t *testing.T) {
ts.Run(t, []test.TestCase{
{
Method: http.MethodGet,
Path: "/tyk/keys/" + key,
Path: "/tyk/keys/" + key + "?api_id=api1",
AdminAuth: true,
Code: http.StatusOK,
BodyMatchFunc: func(data []byte) bool {
Expand Down Expand Up @@ -799,7 +799,7 @@ func TestPerAPIPolicyUpdate(t *testing.T) {
ts.Run(t, []test.TestCase{
{
Method: http.MethodGet,
Path: "/tyk/keys/" + key,
Path: "/tyk/keys/" + key + "?api_id=api1",
AdminAuth: true,
Code: http.StatusOK,
BodyMatchFunc: func(data []byte) bool {
Expand Down
6 changes: 6 additions & 0 deletions gateway/rpc_storage_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,12 @@ func (r *RPCStorageHandler) GetRawKey(keyName string) (string, error) {
return value.(string), nil
}

func (r *RPCStorageHandler) GetMultiKey(keyNames []string) ([]string, error) {
log.Warning("RPCStorageHandler.GetMultiKey - Not implemented")

return nil, nil
}

func (r *RPCStorageHandler) GetExp(keyName string) (int64, error) {
log.Debug("GetExp called")
value, err := rpc.FuncClientSingleton("GetExp", r.fixKey(keyName))
Expand Down
7 changes: 5 additions & 2 deletions gateway/testutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -362,13 +362,13 @@ func withAuth(r *http.Request) *http.Request {

// Deprecated: Use Test.CreateSession instead.
func CreateSession(sGen ...func(s *user.SessionState)) string {
key := generateToken("", "")
key := generateToken("default", "")
session := CreateStandardSession()
if len(sGen) > 0 {
sGen[0](session)
}
if session.Certificate != "" {
key = generateToken("", session.Certificate)
key = generateToken("default", session.Certificate)
}

FallbackKeySesionManager.UpdateSession(storage.HashKey(key), session, 60, config.Global().HashKeys)
Expand All @@ -388,6 +388,7 @@ func CreateStandardSession() *user.SessionState {
session.QuotaMax = -1
session.Tags = []string{}
session.MetaData = make(map[string]interface{})
session.OrgID = "default"
return session
}

Expand All @@ -407,6 +408,7 @@ func CreatePolicy(pGen ...func(p *user.Policy)) string {
pID := keyGen.GenerateAuthKey("")
pol := CreateStandardPolicy()
pol.ID = pID
pol.OrgID = "default"

if len(pGen) > 0 {
pGen[0](pol)
Expand Down Expand Up @@ -680,6 +682,7 @@ func StartTest(config ...TestConfig) *Test {

const sampleAPI = `{
"api_id": "test",
"org_id": "default",
"use_keyless": true,
"definition": {
"location": "header",
Expand Down
Loading

0 comments on commit dd27e79

Please sign in to comment.