Skip to content

Commit

Permalink
APP-2592: Goutils: implement auth handler that supports (id, key) pai…
Browse files Browse the repository at this point in the history
…rs (#203)
  • Loading branch information
Ojima Abraham authored Oct 5, 2023
1 parent 45e9b67 commit 59ae872
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
20 changes: 20 additions & 0 deletions rpc/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,26 @@ func MakeSimpleMultiAuthHandler(forEntities, expectedPayloads []string) AuthHand
})
}

// MakeSimpleMultiAuthPairHandler works similarly to MakeSimpleMultiAuthHandler with the addition of
// supporting a key, id pair used to ensure that a key that maps to the id matches the key passed
// during the function call.
func MakeSimpleMultiAuthPairHandler(expectedPayloads map[string]string) AuthHandler {
if len(expectedPayloads) == 0 {
panic("expected at least one payload")
}

return AuthHandlerFunc(func(ctx context.Context, entity, payload string) (map[string]string, error) {
if _, ok := expectedPayloads[entity]; !ok {
return nil, errInvalidCredentials
}

if subtle.ConstantTimeCompare([]byte(expectedPayloads[entity]), []byte(payload)) == 1 {
return map[string]string{}, nil
}
return nil, errInvalidCredentials
})
}

// MakeEntitiesChecker checks a list of entities against a given one for use in an auth handler.
func MakeEntitiesChecker(forEntities []string) func(ctx context.Context, entities ...string) error {
return func(ctx context.Context, entities ...string) error {
Expand Down
23 changes: 23 additions & 0 deletions rpc/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,29 @@ func TestMakeSimpleMultiAuthHandler(t *testing.T) {
})
}

func TestMakeSimpleMultiAuthPairHandler(t *testing.T) {
test.That(t, func() {
MakeSimpleMultiAuthPairHandler(map[string]string{})
}, test.ShouldPanicWith, "expected at least one payload")

t.Run("should validate (keyID, key) mappings", func(t *testing.T) {
expectedKeysMap := map[string]string{"myKeyID": "someKey", "somethingElseKeyID": "someOtherKeyID"}
handler := MakeSimpleMultiAuthPairHandler(expectedKeysMap)

for key, value := range expectedKeysMap {
t.Run(key, func(t *testing.T) {
_, err := handler.Authenticate(context.Background(), key, value)
test.That(t, err, test.ShouldBeNil)
_, err = handler.Authenticate(context.Background(), key, value+"1")
test.That(t, err, test.ShouldEqual, errInvalidCredentials)

_, err = handler.Authenticate(context.Background(), "notent", key)
test.That(t, err, test.ShouldBeError, errInvalidCredentials)
})
}
})
}

func TestTokenVerificationKeyProviderFunc(t *testing.T) {
err1 := errors.New("whoops")
capCtx := make(chan struct{})
Expand Down

0 comments on commit 59ae872

Please sign in to comment.