Skip to content

Commit

Permalink
Add unit tests for listCNSI (#4876)
Browse files Browse the repository at this point in the history
Signed-off-by: Thomas Quandt <[email protected]>
  • Loading branch information
thquad committed Feb 25, 2021
1 parent 8fb2fc6 commit 166190a
Show file tree
Hide file tree
Showing 2 changed files with 206 additions and 14 deletions.
178 changes: 177 additions & 1 deletion src/jetstream/cnsi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ func TestGetCFv2InfoWithInvalidEndpoint(t *testing.T) {
}
}

func TestRegisterCFClusterWithUserEndpointsEnabled(t *testing.T) {
func TestRegisterWithUserEndpointsEnabled(t *testing.T) {
// execute this in parallel
t.Parallel()

Expand Down Expand Up @@ -578,3 +578,179 @@ func TestRegisterCFClusterWithUserEndpointsEnabled(t *testing.T) {
})
})
}

func TestListCNSIsWithUserEndpointsEnabled(t *testing.T) {
t.Parallel()

Convey("Request to list endpoints", t, func() {

// mock StratosAuthService
ctrl := gomock.NewController(t)
mockStratosAuth := mock_interfaces.NewMockStratosAuth(ctrl)
defer ctrl.Finish()

// setup mock DB, PortalProxy and mock StratosAuthService
pp, db, mock := setupPortalProxyWithAuthService(mockStratosAuth)
defer db.Close()

// setup request

res := httptest.NewRecorder()
req := setupMockReq("GET", "", nil)
_, ctx := setupEchoContext(res, req)

mockAdmin := setupMockUser(mockAdminGUID, true, []string{})
mockUser1 := setupMockUser(mockUserGUID+"1", false, []string{"stratos.endpointadmin"})
mockUser2 := setupMockUser(mockUserGUID+"2", false, []string{"stratos.endpointadmin"})

adminEndpointArgs := createEndpointRowArgs("CF Endpoint 1", "https://127.0.0.1:50001", mockAdmin.ConnectedUser.GUID, mockAdmin.ConnectedUser.Admin)
userEndpoint1Args := createEndpointRowArgs("CF Endpoint 2", "https://127.0.0.1:50002", mockUser1.ConnectedUser.GUID, mockUser1.ConnectedUser.Admin)
userEndpoint2Args := createEndpointRowArgs("CF Endpoint 3", "https://127.0.0.1:50003", mockUser2.ConnectedUser.GUID, mockUser2.ConnectedUser.Admin)

adminRows := sqlmock.NewRows(rowFieldsForCNSI).
AddRow(adminEndpointArgs...)
user1Rows := sqlmock.NewRows(rowFieldsForCNSI).
AddRow(userEndpoint1Args...)
allRows := sqlmock.NewRows(rowFieldsForCNSI).
AddRow(adminEndpointArgs...).
AddRow(userEndpoint1Args...).
AddRow(userEndpoint2Args...)

Convey("as admin", func() {

if errSession := pp.setSessionValues(ctx, mockAdmin.SessionValues); errSession != nil {
t.Error(errors.New("unable to mock/stub user in session object"))
}

Convey("with UserEndpointsEnabled = enabled", func() {
//expect list all
pp.GetConfig().UserEndpointsEnabled = config.UserEndpointsConfigEnum.Enabled

mockStratosAuth.
EXPECT().
GetUser(gomock.Eq(mockAdmin.ConnectedUser.GUID)).
Return(mockAdmin.ConnectedUser, nil)

mock.ExpectQuery(selectFromCNSIs).WillReturnRows(allRows)
err := pp.listCNSIs(ctx)
dberr := mock.ExpectationsWereMet()

Convey("there should be no error", func() {
So(err, ShouldBeNil)
})

Convey("there should be no db error", func() {
So(dberr, ShouldBeNil)
})
})
Convey("with UserEndpointsEnabled = admin_only", func() {
//expect list all
pp.GetConfig().UserEndpointsEnabled = config.UserEndpointsConfigEnum.AdminOnly

mockStratosAuth.
EXPECT().
GetUser(gomock.Eq(mockAdmin.ConnectedUser.GUID)).
Return(mockAdmin.ConnectedUser, nil)

mock.ExpectQuery(selectFromCNSIs).WillReturnRows(allRows)
err := pp.listCNSIs(ctx)
dberr := mock.ExpectationsWereMet()

Convey("there should be no error", func() {
So(err, ShouldBeNil)
})

Convey("there should be no db error", func() {
So(dberr, ShouldBeNil)
})

})
Convey("with UserEndpointsEnabled = disabled", func() {
// expect list creator with ""
pp.GetConfig().UserEndpointsEnabled = config.UserEndpointsConfigEnum.Disabled

mock.ExpectQuery(selectCreatorFromCNSIs).WithArgs("").WillReturnRows(adminRows)
err := pp.listCNSIs(ctx)
dberr := mock.ExpectationsWereMet()

Convey("there should be no error", func() {
So(err, ShouldBeNil)
})

Convey("there should be no db error", func() {
So(dberr, ShouldBeNil)
})
})

})
Convey("as user", func() {
//expect list creator with "" and user-guid as args
if errSession := pp.setSessionValues(ctx, mockUser1.SessionValues); errSession != nil {
t.Error(errors.New("unable to mock/stub user in session object"))
}

Convey("with UserEndpointsEnabled = enabled", func() {
// expect list creator with "" and own endpoints
pp.GetConfig().UserEndpointsEnabled = config.UserEndpointsConfigEnum.Enabled

mockStratosAuth.
EXPECT().
GetUser(gomock.Eq(mockUser1.ConnectedUser.GUID)).
Return(mockUser1.ConnectedUser, nil)

mock.ExpectQuery(selectCreatorFromCNSIs).WithArgs(mockUser1.ConnectedUser.GUID).WillReturnRows(user1Rows)
mock.ExpectQuery(selectCreatorFromCNSIs).WithArgs("").WillReturnRows(adminRows)
err := pp.listCNSIs(ctx)
dberr := mock.ExpectationsWereMet()

Convey("there should be no error", func() {
So(err, ShouldBeNil)
})

Convey("there should be no db error", func() {
So(dberr, ShouldBeNil)
})

})
Convey("with UserEndpointsEnabled = admin_only", func() {
// expect list creator with ""
pp.GetConfig().UserEndpointsEnabled = config.UserEndpointsConfigEnum.AdminOnly

mockStratosAuth.
EXPECT().
GetUser(gomock.Eq(mockUser1.ConnectedUser.GUID)).
Return(mockUser1.ConnectedUser, nil)

mock.ExpectQuery(selectCreatorFromCNSIs).WithArgs("").WillReturnRows(adminRows)
err := pp.listCNSIs(ctx)
dberr := mock.ExpectationsWereMet()

Convey("there should be no error", func() {
So(err, ShouldBeNil)
})

Convey("there should be no db error", func() {
So(dberr, ShouldBeNil)
})

})
Convey("with UserEndpointsEnabled = disabled", func() {
// expect list creator with ""
pp.GetConfig().UserEndpointsEnabled = config.UserEndpointsConfigEnum.Disabled

mock.ExpectQuery(selectCreatorFromCNSIs).WithArgs("").WillReturnRows(adminRows)
err := pp.listCNSIs(ctx)
dberr := mock.ExpectationsWereMet()

Convey("there should be no error", func() {
So(err, ShouldBeNil)
})

Convey("there should be no db error", func() {
So(dberr, ShouldBeNil)
})
})

})
})
}
42 changes: 29 additions & 13 deletions src/jetstream/mock_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,20 @@ func expectEncryptedTokenRow(mockEncryptionKey []byte) sqlmock.Rows {
AddRow(mockTokenGUID, encryptedUaaToken, encryptedUaaToken, mockTokenExpiry, false, "OAuth2", "", mockUserGUID, nil)
}

func createEndpointRowArgs(endpointName string, APIEndpoint string, uaaUserGUID string, userAdmin bool) []driver.Value {
creatorGUID := ""

h := sha1.New()
if userAdmin {
h.Write([]byte(APIEndpoint))
} else {
h.Write([]byte(APIEndpoint + uaaUserGUID))
creatorGUID = uaaUserGUID
}

return []driver.Value{base64.RawURLEncoding.EncodeToString(h.Sum(nil)), endpointName, "cf", APIEndpoint, mockAuthEndpoint, mockTokenEndpoint, mockDopplerEndpoint, true, mockClientId, cipherClientSecret, false, "", "", creatorGUID}
}

func setupHTTPTest(req *http.Request) (*httptest.ResponseRecorder, *echo.Echo, echo.Context, *portalProxy, *sql.DB, sqlmock.Sqlmock) {
res := httptest.NewRecorder()
e, ctx := setupEchoContext(res, req)
Expand Down Expand Up @@ -360,19 +374,21 @@ const (

stringCFType = "cf"

selectAnyFromTokens = `SELECT (.+) FROM tokens WHERE (.+)`
insertIntoTokens = `INSERT INTO tokens`
updateTokens = `UPDATE tokens`
selectAnyFromCNSIs = `SELECT (.+) FROM cnsis WHERE (.+)`
deleteFromCNSIs = `DELETE FROM cnsis WHERE (.+)`
insertIntoCNSIs = `INSERT INTO cnsis`
findUserGUID = `SELECT user_guid FROM local_users WHERE (.+)`
addLocalUser = `INSERT INTO local_users (.+)`
findPasswordHash = `SELECT password_hash FROM local_users WHERE (.+)`
findUserScope = `SELECT user_scope FROM local_users WHERE (.+)`
updateLastLoginTime = `UPDATE local_users (.+)`
findLastLoginTime = `SELECT last_login FROM local_users WHERE (.+)`
getDbVersion = `SELECT version_id FROM goose_db_version WHERE is_applied = '1' ORDER BY id DESC LIMIT 1`
selectAnyFromTokens = `SELECT (.+) FROM tokens WHERE (.+)`
insertIntoTokens = `INSERT INTO tokens`
updateTokens = `UPDATE tokens`
selectFromCNSIs = `SELECT (.+) FROM cnsis`
selectAnyFromCNSIs = `SELECT (.+) FROM cnsis WHERE (.+)`
selectCreatorFromCNSIs = `SELECT (.+) FROM cnsis WHERE creator=(.+)`
deleteFromCNSIs = `DELETE FROM cnsis WHERE (.+)`
insertIntoCNSIs = `INSERT INTO cnsis`
findUserGUID = `SELECT user_guid FROM local_users WHERE (.+)`
addLocalUser = `INSERT INTO local_users (.+)`
findPasswordHash = `SELECT password_hash FROM local_users WHERE (.+)`
findUserScope = `SELECT user_scope FROM local_users WHERE (.+)`
updateLastLoginTime = `UPDATE local_users (.+)`
findLastLoginTime = `SELECT last_login FROM local_users WHERE (.+)`
getDbVersion = `SELECT version_id FROM goose_db_version WHERE is_applied = '1' ORDER BY id DESC LIMIT 1`
)

var rowFieldsForCNSI = []string{"guid", "name", "cnsi_type", "api_endpoint", "auth_endpoint", "token_endpoint", "doppler_logging_endpoint", "skip_ssl_validation", "client_id", "client_secret", "allow_sso", "sub_type", "meta_data", "creator"}
Expand Down

0 comments on commit 166190a

Please sign in to comment.