diff --git a/storage/storage.go b/storage/storage.go index bcde986f6de..4da4d8dec66 100644 --- a/storage/storage.go +++ b/storage/storage.go @@ -24,6 +24,8 @@ var ErrKeyNotFound = errors.New("key not found") var ErrMDCBConnectionLost = errors.New("mdcb connection is lost") +const MongoBsonIdLength = 24 + // Handler is a standard interface to a storage backend, used by // AuthorisationManager to read and write key values to the backend type Handler interface { @@ -127,8 +129,12 @@ func TokenOrg(token string) string { } // 24 is mongo bson id length - if len(token) > 24 { - return token[:24] + if len(token) > MongoBsonIdLength { + newToken := token[:MongoBsonIdLength] + _, err := hex.DecodeString(newToken) + if err == nil { + return newToken + } } return "" diff --git a/storage/storage_test.go b/storage/storage_test.go new file mode 100644 index 00000000000..ea105b74164 --- /dev/null +++ b/storage/storage_test.go @@ -0,0 +1,41 @@ +package storage + +import "testing" + +func Test_TokenOrg(t *testing.T) { + tcs := []struct { + name string + givenKey string + expectedResult string + }{ + { + name: "long non-b64 key - without orgId ", + givenKey: "testdata-JJNIsqyZViCvcnbX8ouvG7yctsH1irHa2aklAFYC", + expectedResult: "", + }, + { + name: "b64 key", + givenKey: "eyJvcmciOiI2NDkyZjY2ZTZlYmJjNTZjNmE2YmYwMjIiLCJpZCI6IjEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU5IiwiaCI6Im11cm11cjY0In0=", + expectedResult: "6492f66e6ebbc56c6a6bf022", + }, + { + name: "long non-b64 key - with orgId", + givenKey: "6492f66e6ebbc56c6a6bf022657c162274933214b91ea570", + expectedResult: "6492f66e6ebbc56c6a6bf022", + }, + { + name: "short non-b64 key", + givenKey: "6492f66e6e", + expectedResult: "", + }, + } + + for _, tc := range tcs { + t.Run(tc.name, func(t *testing.T) { + result := TokenOrg(tc.givenKey) + if result != tc.expectedResult { + t.Errorf("Expected %s, got %s", tc.expectedResult, result) + } + }) + } +}