Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SANDBOX-674: add NewBannedUser and IsAlreadyBanned funcs #413

Merged
merged 11 commits into from
Jul 18, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions pkg/banneduser/banneduser.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package banneduser

import (
"context"
"fmt"

toolchainv1alpha1 "github.com/codeready-toolchain/api/api/v1alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
)

const bannedByLabel = toolchainv1alpha1.LabelKeyPrefix + "banned-by"
rsoaresd marked this conversation as resolved.
Show resolved Hide resolved
rsoaresd marked this conversation as resolved.
Show resolved Hide resolved

// NewBannedUser creates a BannedUser resource
rsoaresd marked this conversation as resolved.
Show resolved Hide resolved
func NewBannedUser(userSignup *toolchainv1alpha1.UserSignup, bannedBy string) (*toolchainv1alpha1.BannedUser, error) {
var emailHashLbl, phoneHashLbl string
var exists bool

if emailHashLbl, exists = userSignup.Labels[toolchainv1alpha1.UserSignupUserEmailHashLabelKey]; !exists {
return nil, fmt.Errorf("the UserSignup %s doesn't have the label '%s' set", userSignup.Name, toolchainv1alpha1.UserSignupUserEmailHashLabelKey) // nolint:loggercheck
}

bannedUser := &toolchainv1alpha1.BannedUser{
ObjectMeta: metav1.ObjectMeta{
Namespace: userSignup.Namespace,
Name: fmt.Sprintf("banneduser-%s", emailHashLbl),
Labels: map[string]string{
toolchainv1alpha1.BannedUserEmailHashLabelKey: emailHashLbl,
bannedByLabel: bannedBy,
},
},
Spec: toolchainv1alpha1.BannedUserSpec{
Email: userSignup.Spec.IdentityClaims.Email,
},
}

if phoneHashLbl, exists = userSignup.Labels[toolchainv1alpha1.UserSignupUserPhoneHashLabelKey]; exists {
bannedUser.Labels[toolchainv1alpha1.BannedUserPhoneNumberHashLabelKey] = phoneHashLbl
}
return bannedUser, nil
}

// IsAlreadyBanned checks if the user was already banned
func IsAlreadyBanned(ctx context.Context, userEmailHash string, hostClient client.Client, hostNamespace string) (bool, error) {
emailHashLabelMatch := client.MatchingLabels(map[string]string{
toolchainv1alpha1.BannedUserEmailHashLabelKey: userEmailHash,
})
bannedUsers := &toolchainv1alpha1.BannedUserList{}

if err := hostClient.List(ctx, bannedUsers, emailHashLabelMatch, client.InNamespace(hostNamespace)); err != nil {
return false, err
}

return len(bannedUsers.Items) > 0, nil
}
188 changes: 188 additions & 0 deletions pkg/banneduser/banneduser_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
package banneduser

import (
"context"
"fmt"
"testing"

toolchainv1alpha1 "github.com/codeready-toolchain/api/api/v1alpha1"
"github.com/codeready-toolchain/toolchain-common/pkg/test"
commonsignup "github.com/codeready-toolchain/toolchain-common/pkg/test/usersignup"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/kubectl/pkg/scheme"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
)

func TestNewBannedUser(t *testing.T) {
userSignup1 := commonsignup.NewUserSignup(commonsignup.WithName("johny"), commonsignup.WithEmail("[email protected]"))
userSignup1UserEmailHash := userSignup1.Labels[toolchainv1alpha1.UserSignupUserEmailHashLabelKey]

userSignup2 := commonsignup.NewUserSignup(commonsignup.WithName("bob"), commonsignup.WithEmail("[email protected]"))
userSignup2.Labels = nil

userSignup3 := commonsignup.NewUserSignup(commonsignup.WithName("oliver"), commonsignup.WithEmail("[email protected]"))
userSignup3PhoneHash := "fd276563a8232d16620da8ec85d0575f"
userSignup3.Labels[toolchainv1alpha1.UserSignupUserPhoneHashLabelKey] = userSignup3PhoneHash
userSignup3EmailHash := userSignup3.Labels[toolchainv1alpha1.UserSignupUserEmailHashLabelKey]

tests := []struct {
name string
userSignup *toolchainv1alpha1.UserSignup
bannedBy string
wantError bool
wantErrorMsg string
expectedBannedUser *toolchainv1alpha1.BannedUser
}{
{
name: "userSignup with email hash label",
userSignup: userSignup1,
bannedBy: "admin",
wantError: false,
wantErrorMsg: "",
expectedBannedUser: &toolchainv1alpha1.BannedUser{
ObjectMeta: metav1.ObjectMeta{
Namespace: userSignup1.Namespace,
Name: fmt.Sprintf("banneduser-%s", userSignup1UserEmailHash),
Labels: map[string]string{
toolchainv1alpha1.BannedUserEmailHashLabelKey: userSignup1UserEmailHash,
bannedByLabel: "admin",
},
},
Spec: toolchainv1alpha1.BannedUserSpec{
Email: userSignup1.Spec.IdentityClaims.Email,
},
},
},
{
name: "userSignup without email hash label and phone hash label",
userSignup: userSignup2,
bannedBy: "admin",
wantError: true,
wantErrorMsg: fmt.Sprintf("the UserSignup %s doesn't have the label '%s' set", userSignup2.Name, toolchainv1alpha1.UserSignupUserEmailHashLabelKey),
expectedBannedUser: nil,
},
{
name: "userSignup with email hash label and phone hash label",
userSignup: userSignup3,
bannedBy: "admin",
wantError: false,
wantErrorMsg: "",
expectedBannedUser: &toolchainv1alpha1.BannedUser{
ObjectMeta: metav1.ObjectMeta{
Namespace: userSignup3.Namespace,
Name: fmt.Sprintf("banneduser-%s", userSignup3EmailHash),
Labels: map[string]string{
toolchainv1alpha1.BannedUserEmailHashLabelKey: userSignup3EmailHash,
bannedByLabel: "admin",
toolchainv1alpha1.UserSignupUserPhoneHashLabelKey: userSignup3PhoneHash,
},
},
Spec: toolchainv1alpha1.BannedUserSpec{
Email: userSignup3.Spec.IdentityClaims.Email,
},
},
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := NewBannedUser(tt.userSignup, tt.bannedBy)

if tt.wantError {
require.Error(t, err)
assert.Equal(t, tt.wantErrorMsg, err.Error())
require.Nil(t, got)
} else {
require.NoError(t, err)
require.NotNil(t, got)

assert.Equal(t, tt.expectedBannedUser.ObjectMeta.Namespace, got.ObjectMeta.Namespace)
assert.Equal(t, tt.expectedBannedUser.ObjectMeta.Name, got.ObjectMeta.Name)
assert.Equal(t, tt.expectedBannedUser.Spec.Email, got.Spec.Email)

if tt.expectedBannedUser != nil && !compareMaps(tt.expectedBannedUser.Labels, got.Labels) {
t.Errorf("compareMaps(%v, %v) = false, expected = true", tt.expectedBannedUser.Labels, got.Labels)
}
}
})
}
}

func TestIsAlreadyBanned(t *testing.T) {
userSignup1 := commonsignup.NewUserSignup(commonsignup.WithName("johny"), commonsignup.WithEmail("[email protected]"))
userSignup2 := commonsignup.NewUserSignup(commonsignup.WithName("bob"), commonsignup.WithEmail("[email protected]"))
userSignup3 := commonsignup.NewUserSignup(commonsignup.WithName("oliver"), commonsignup.WithEmail("[email protected]"))
bannedUser1, err := NewBannedUser(userSignup1, "admin")
require.NoError(t, err)
bannedUser2, err := NewBannedUser(userSignup2, "admin")
require.NoError(t, err)
bannedUser3, err := NewBannedUser(userSignup3, "admin")
require.NoError(t, err)

mockT := test.NewMockT()
fakeClient := test.NewFakeClient(mockT, bannedUser1)
ctx := context.TODO()

tests := []struct {
name string
toBan *toolchainv1alpha1.BannedUser
wantResult bool
wantError bool
fakeClient *test.FakeClient
}{
{
name: "user is already banned",
toBan: bannedUser1,
wantResult: true,
wantError: false,
fakeClient: fakeClient,
},
{
name: "user is not banned",
toBan: bannedUser2,
wantResult: false,
wantError: false,
fakeClient: fakeClient,
},
{
name: "cannot list banned users because the client does have type v1alpha1.BannedUserList registered in the scheme",
toBan: bannedUser3,
wantResult: false,
wantError: true,
fakeClient: &test.FakeClient{Client: fake.NewClientBuilder().WithScheme(scheme.Scheme).Build(), T: t},
rsoaresd marked this conversation as resolved.
Show resolved Hide resolved
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotResult, err := IsAlreadyBanned(ctx, tt.toBan.Labels[toolchainv1alpha1.BannedUserEmailHashLabelKey], tt.fakeClient, test.HostOperatorNs)

if tt.wantError {
require.Error(t, err)
} else {
require.NoError(t, err)
assert.Equal(t, tt.wantResult, gotResult)
}
})
}
}

func compareMaps(map1, map2 map[string]string) bool {
rsoaresd marked this conversation as resolved.
Show resolved Hide resolved
if len(map1) != len(map2) {
return false
}

for key, value1 := range map1 {
value2, ok := map2[key]
if !ok {
return false
}
if value1 != value2 {
return false
}
}

return true
}
Loading