Skip to content

Commit

Permalink
fix: Restore encoded version of api keys (#450)
Browse files Browse the repository at this point in the history
  • Loading branch information
ggarri authored Dec 17, 2021
1 parent 2a45397 commit 4eaaf99
Show file tree
Hide file tree
Showing 6 changed files with 26 additions and 36 deletions.
3 changes: 2 additions & 1 deletion .env.dev.sample
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ AUTH_API_KEY_FILE=/apikey/sample.csv
AUTH_TLS_CA=/ca/ca.crt

# OpenID Connect
#AUTH_OIDC_ISSUER_URL={ENTER your Identity provider URL here, example: https://consensys.eu.auth0.com}
#AUTH_OIDC_ISSUER_URL={ENTER your Identity Provider(IDP) URL here, example: https://consensys.eu.auth0.com}
#AUTH_OIDC_AUDIENCE={ENTER your IDP used audience, example: https://quorum-key-manager.consensys.net}

## Start HTTPS server
HTTPS_ENABLED=true
Expand Down
6 changes: 4 additions & 2 deletions deps/config/apikey/sample.csv
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
## Notes: Request headers should be "Authorization: Basic base64({user-key})"
## Column separator is ","

admin-user,tenant1|user1,"*:*","admin"
guest-user,tenant2|user2,"*:secrets *:keys read:ethereum","anonymous"
# sha256("admin-user")
f470213d9ae659187a19b9cb2169b4b400544f4d3f59250eda657154700da616,tenant1|user1,"*:*","admin"
# sha256("guest-user")
8605f70ff5f55e2a9323d97de3dbf8e61f38314d93298ca00e19f8918fe8971b,tenant2|user2,"*:secrets *:keys read:ethereum","anonymous"
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ require (
github.com/spf13/pflag v1.0.5
github.com/spf13/viper v1.7.1
github.com/stretchr/testify v1.7.0
github.com/swaggo/swag v1.7.6
github.com/swaggo/swag v1.7.6 // indirect
go.elastic.co/ecszap v1.0.0
go.uber.org/atomic v1.8.0 // indirect
go.uber.org/multierr v1.7.0 // indirect
Expand Down
8 changes: 4 additions & 4 deletions src/auth/service/authenticator/authenticator.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"crypto/sha256"
tls2 "crypto/tls"
"crypto/x509"
"encoding/base64"
"fmt"
"hash"
"strings"
Expand Down Expand Up @@ -78,10 +77,11 @@ func (authen *Authenticator) AuthenticateAPIKey(_ context.Context, apiKey []byte
return nil, fmt.Errorf("failed to hash api key")
}

claims, ok := authen.apiKeyClaims[base64.StdEncoding.EncodeToString(authen.hasher.Sum(nil))]
apiKeySha256 := fmt.Sprintf("%x", authen.hasher.Sum(nil))
claims, ok := authen.apiKeyClaims[apiKeySha256]
if !ok {
errMessage := "api key not found"
authen.logger.Warn(errMessage, "api_key_hash", apiKey)
errMessage := "invalid api key"
authen.logger.Warn(errMessage)
return nil, errors.UnauthorizedError(errMessage)
}

Expand Down
24 changes: 11 additions & 13 deletions src/auth/service/authenticator/authenticator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ package authenticator

import (
"context"
"crypto/sha256"
tls2 "crypto/tls"
"crypto/x509"
"encoding/base64"
"fmt"
"testing"

Expand Down Expand Up @@ -51,9 +51,13 @@ func (s *authenticatorTestSuite) SetupTest() {
aliceClaims := testdata.FakeUserClaims()
bobClaims := testdata.FakeUserClaims()
bobClaims.Scope = "*:*"

aliceSha256 := fmt.Sprintf("%x", sha256.Sum256([]byte(aliceAPIKey)))
bobSha256 := fmt.Sprintf("%x", sha256.Sum256([]byte(bobAPIKey)))

s.userClaims = map[string]*entities.UserClaims{
"BRqrbYycs44wSi40uij02ZlPd5zBxuWIMessUGcdxtI=": aliceClaims, // base64 of alice key
"XWubgVAkP8ug1MD+9JqFuMYvKE6phwFYRC/9ALdvFss=": bobClaims, // base64 of bob key
aliceSha256: aliceClaims, // base64 of alice key
bobSha256: bobClaims, // base64 of bob key
}

// TLS certs
Expand Down Expand Up @@ -126,9 +130,7 @@ func (s *authenticatorTestSuite) TestAuthenticateAPIKey() {
ctx := context.Background()

s.Run("should authenticate with api key successfully", func() {
aliceKey, _ := base64.StdEncoding.DecodeString(aliceAPIKey)

userInfo, err := s.auth.AuthenticateAPIKey(ctx, aliceKey)
userInfo, err := s.auth.AuthenticateAPIKey(ctx, []byte(aliceAPIKey))

require.NoError(s.T(), err)
assert.Equal(s.T(), "Alice", userInfo.Username)
Expand All @@ -139,27 +141,23 @@ func (s *authenticatorTestSuite) TestAuthenticateAPIKey() {
})

s.Run("should authenticate an api key successfully with wildcard permissions", func() {
bobKey, _ := base64.StdEncoding.DecodeString(bobAPIKey)

userInfo, err := s.auth.AuthenticateAPIKey(ctx, bobKey)
userInfo, err := s.auth.AuthenticateAPIKey(ctx, []byte(bobAPIKey))

require.NoError(s.T(), err)
assert.Equal(s.T(), entities.NewWildcardUser().Permissions, userInfo.Permissions)
})

s.Run("should return UnauthorizedError if api key is not found", func() {
invalidKey, _ := base64.StdEncoding.DecodeString("invalid-key")
userInfo, err := s.auth.AuthenticateAPIKey(ctx, invalidKey)
userInfo, err := s.auth.AuthenticateAPIKey(ctx, []byte("invalid-key"))

require.Nil(s.T(), userInfo)
assert.True(s.T(), errors.IsUnauthorizedError(err))
})

s.Run("should return UnauthorizedError if the authentication method is not enabled", func() {
aliceKey, _ := base64.StdEncoding.DecodeString(aliceAPIKey)
auth := New(nil, nil, nil, s.logger)

userInfo, err := auth.AuthenticateAPIKey(ctx, aliceKey)
userInfo, err := auth.AuthenticateAPIKey(ctx, []byte(aliceAPIKey))

require.Nil(s.T(), userInfo)
assert.True(s.T(), errors.IsUnauthorizedError(err))
Expand Down
19 changes: 4 additions & 15 deletions src/infra/api-key/csv/reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,8 @@ package csv

import (
"context"
"crypto/sha256"
"encoding/base64"
csv2 "encoding/csv"
"fmt"
"hash"
"io"
"os"

Expand All @@ -18,15 +15,14 @@ const (
csvSeparator = ','
csvCommentsMarker = '#'
csvRowLen = 4
csvHashOffset = 0
csvAPIKeyHash = 0
csvUserOffset = 1
csvPermissionsOffset = 2
csvRolesOffset = 3
)

type Reader struct {
path string
hasher hash.Hash
path string
}

var _ apikey.Reader = &Reader{}
Expand All @@ -37,7 +33,7 @@ func New(cfg *Config) (*Reader, error) {
return nil, err
}

return &Reader{path: cfg.Path, hasher: sha256.New()}, nil
return &Reader{path: cfg.Path}, nil
}

func (r *Reader) Load(_ context.Context) (map[string]*entities.UserClaims, error) {
Expand Down Expand Up @@ -65,14 +61,7 @@ func (r *Reader) Load(_ context.Context) (map[string]*entities.UserClaims, error
return nil, fmt.Errorf("invalid number of cells, should be %d", csvRowLen)
}

r.hasher.Reset()
_, err = r.hasher.Write([]byte(cells[csvHashOffset]))
if err != nil {
return nil, fmt.Errorf("failed to hash api key")
}

apiKeyHash := base64.StdEncoding.EncodeToString(r.hasher.Sum(nil))
claims[apiKeyHash] = &entities.UserClaims{
claims[cells[csvAPIKeyHash]] = &entities.UserClaims{
Subject: cells[csvUserOffset],
Scope: cells[csvPermissionsOffset],
Roles: cells[csvRolesOffset],
Expand Down

0 comments on commit 4eaaf99

Please sign in to comment.