Skip to content

Commit

Permalink
fix: move key generation logic into SeedAPIKey
Browse files Browse the repository at this point in the history
  • Loading branch information
danvixent committed Jun 11, 2022
1 parent 2def17b commit 628ce19
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 36 deletions.
49 changes: 29 additions & 20 deletions server/security_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,33 +105,26 @@ func (s *SecurityIntegrationTestSuite) Test_CreateAppPortalAPIKey() {

initRealmChain(s.T(), s.DB.APIRepo(), s.DB.UserRepo(), s.ConvoyApp.cache)

member, err := testdb.SeedOrganisationMember(s.DB, s.DefaultOrg, s.DefaultUser, &auth.Role{
// Just Before.
app, _ := testdb.SeedApplication(s.DB, s.DefaultGroup, uuid.NewString(), "test-app", true)

role := auth.Role{
Type: auth.RoleAdmin,
Groups: []string{s.DefaultGroup.UID},
})

newAPIKey := &models.APIKey{
Name: s.DefaultOrg.Name + "'s default key",
Role: models.Role{
Type: auth.RoleAdmin,
Group: s.DefaultGroup.UID,
},
}

_, keyString, err := s.ConvoyApp.securityService.CreateAPIKey(context.Background(), member, newAPIKey)
// Generate api key for this group, use the key to authenticate for this request later on
_, keyString, err := testdb.SeedAPIKey(s.DB, role, uuid.NewString(), "test", "api")
require.NoError(s.T(), err)

// Just Before.
app, _ := testdb.SeedApplication(s.DB, s.DefaultGroup, uuid.NewString(), "test-app", true)

// Arrange Request.
bodyStr := `{"name":"default_api_key","role":{"type":"ui_admin","group":"%s"},"key_type":"api_key","expires_at":"%s"}"`
body := serialize(bodyStr, s.DefaultGroup.UID, time.Now().Add(time.Hour))

url := fmt.Sprintf("/api/v1/security/applications/%s/keys", app.UID)

req := createRequest(http.MethodPost, url, body)
req.Header.Set("Authorization", fmt.Sprintf("BEARER %s", keyString))
req.Header.Set("Authorization", fmt.Sprintf("BEARER %s", keyString)) // authenticate with previously generated key
w := httptest.NewRecorder()

// Act.
Expand All @@ -153,8 +146,12 @@ func (s *SecurityIntegrationTestSuite) Test_CreateAppPortalAPIKey() {
func (s *SecurityIntegrationTestSuite) Test_RevokeAPIKey() {
expectedStatusCode := http.StatusOK

role := auth.Role{
Type: auth.RoleAdmin,
Groups: []string{s.DefaultGroup.UID},
}
// Just Before.
apiKey, _ := testdb.SeedAPIKey(s.DB, s.DefaultGroup, uuid.NewString(), "test", "api")
apiKey, _, _ := testdb.SeedAPIKey(s.DB, role, uuid.NewString(), "test", "api")

url := fmt.Sprintf("/ui/organisations/%s/security/keys/%s/revoke", s.DefaultOrg.UID, apiKey.UID)

Expand All @@ -180,8 +177,12 @@ func (s *SecurityIntegrationTestSuite) Test_RevokeAPIKey() {
func (s *SecurityIntegrationTestSuite) Test_GetAPIKeyByID() {
expectedStatusCode := http.StatusOK

role := auth.Role{
Type: auth.RoleAdmin,
Groups: []string{s.DefaultGroup.UID},
}
// Just Before.
apiKey, _ := testdb.SeedAPIKey(s.DB, s.DefaultGroup, uuid.NewString(), "test", "api")
apiKey, _, _ := testdb.SeedAPIKey(s.DB, role, uuid.NewString(), "test", "api")

url := fmt.Sprintf("/ui/organisations/%s/security/keys/%s", s.DefaultOrg.UID, apiKey.UID)

Expand Down Expand Up @@ -224,8 +225,12 @@ func (s *SecurityIntegrationTestSuite) Test_GetAPIKeyByID_APIKeyNotFound() {
func (s *SecurityIntegrationTestSuite) Test_UpdateAPIKey() {
expectedStatusCode := http.StatusOK

role := auth.Role{
Type: auth.RoleAdmin,
Groups: []string{s.DefaultGroup.UID},
}
// Just Before.
apiKey, _ := testdb.SeedAPIKey(s.DB, s.DefaultGroup, uuid.NewString(), "test", "api")
apiKey, _, _ := testdb.SeedAPIKey(s.DB, role, uuid.NewString(), "test", "api")

bodyStr := `{"role":{"type":"api","groups":["%s"]}}`
body := serialize(bodyStr, s.DefaultGroup.UID)
Expand Down Expand Up @@ -277,10 +282,14 @@ func (s *SecurityIntegrationTestSuite) Test_UpdateAPIKey_APIKeyNotFound() {
func (s *SecurityIntegrationTestSuite) Test_GetAPIKeys() {
expectedStatusCode := http.StatusOK

role := auth.Role{
Type: auth.RoleAdmin,
Groups: []string{s.DefaultGroup.UID},
}
// Just Before.
_, _ = testdb.SeedAPIKey(s.DB, s.DefaultGroup, uuid.NewString(), "test", "api")
_, _ = testdb.SeedAPIKey(s.DB, s.DefaultGroup, uuid.NewString(), "test", "api")
_, _ = testdb.SeedAPIKey(s.DB, s.DefaultGroup, uuid.NewString(), "test", "api")
_, _, _ = testdb.SeedAPIKey(s.DB, role, uuid.NewString(), "test", "api")
_, _, _ = testdb.SeedAPIKey(s.DB, role, uuid.NewString(), "test", "api")
_, _, _ = testdb.SeedAPIKey(s.DB, role, uuid.NewString(), "test", "api")

bodyStr := `{"role":{"type":"api","groups":["%s"]}}`
body := serialize(bodyStr, uuid.NewString())
Expand Down
40 changes: 24 additions & 16 deletions server/testdb/seed.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,21 @@ package testdb

import (
"context"
"crypto/sha256"
"encoding/base64"
"errors"
"fmt"
"time"

"github.com/dchest/uniuri"

"github.com/frain-dev/convoy"
"github.com/frain-dev/convoy/auth"
"github.com/frain-dev/convoy/config"
"github.com/frain-dev/convoy/datastore"
"github.com/frain-dev/convoy/util"
"github.com/google/uuid"
log "github.com/sirupsen/logrus"
"github.com/xdg-go/pbkdf2"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
)
Expand Down Expand Up @@ -265,34 +268,39 @@ func SeedOrganisationInvite(db datastore.DatabaseClient, org *datastore.Organisa
}

// SeedAPIKey creates random api key for integration tests.
func SeedAPIKey(db datastore.DatabaseClient, g *datastore.Group, uid, name, keyType string) (*datastore.APIKey, error) {
func SeedAPIKey(db datastore.DatabaseClient, role auth.Role, uid, name, keyType string) (*datastore.APIKey, string, error) {
if util.IsStringEmpty(uid) {
uid = uuid.New().String()
}

maskID, key := util.GenerateAPIKey()
salt, err := util.GenerateSecret()
if err != nil {
return nil, "", errors.New("failed to generate salt")
}

dk := pbkdf2.Key([]byte(key), []byte(salt), 4096, 32, sha256.New)
encodedKey := base64.URLEncoding.EncodeToString(dk)

apiKey := &datastore.APIKey{
UID: uid,
MaskID: fmt.Sprintf("mask-%s", uuid.NewString()),
Name: name,
Type: datastore.KeyType(keyType),
Role: auth.Role{
Type: auth.RoleUIAdmin,
Groups: []string{g.UID},
Apps: nil,
},
Hash: fmt.Sprintf("hash-%s", uuid.NewString()),
Salt: fmt.Sprintf("salt-%s", uuid.NewString()),
UID: uid,
MaskID: maskID,
Name: name,
Type: datastore.KeyType(keyType),
Role: role,
Hash: encodedKey,
Salt: salt,
CreatedAt: primitive.NewDateTimeFromTime(time.Now()),
UpdatedAt: primitive.NewDateTimeFromTime(time.Now()),
DocumentStatus: datastore.ActiveDocumentStatus,
}

err := db.APIRepo().CreateAPIKey(context.Background(), apiKey)
err = db.APIRepo().CreateAPIKey(context.Background(), apiKey)
if err != nil {
return nil, err
return nil, "", err
}

return apiKey, nil
return apiKey, key, nil
}

// seed default group
Expand Down

0 comments on commit 628ce19

Please sign in to comment.