Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
25 changes: 24 additions & 1 deletion v2/api/sql/v1/user_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,11 @@ type UserSpec struct {
// db_ddladmin, db_datawriter, db_datareader, db_denydatawriter, and db_denydatareader.
Roles []string `json:"roles,omitempty"`

// +kubebuilder:validation:Required
// LocalUser contains details for creating a standard (non-aad) Azure SQL User
LocalUser *LocalUserSpec `json:"localUser,omitempty"`

// AADUser contains details for creating an AAD user.
AADUser *AADUserSpec `json:"aadUser,omitempty"`
}

// OriginalVersion returns the original API version used to create the resource.
Expand Down Expand Up @@ -144,6 +146,27 @@ type LocalUserSpec struct {
Password *genruntime.SecretReference `json:"password,omitempty"`
}

// AADUserSpec defines the specification for an Azure AD user.
// When creating an AAD user, the AzureName must match the identity name in Azure AD:
// - For managed identity: "my-managed-identity-name"
// - For service principal: "my-app-name"
// - For standard AAD user: "user@domain.onmicrosoft.com"
// - For AAD group: "my-group-name"
type AADUserSpec struct {
// Alias overrides AzureName for the database user name.
// Use when AzureName exceeds 128 characters (Azure SQL Server limit).
// +kubebuilder:validation:MaxLength=128
Alias string `json:"alias,omitempty"`

// ServerAdminUsername is the username of the Server administrator. If your server admin was configured with
// Azure Service Operator, this should match the value of the Administrator's $.spec.login field. If the
// administrator is a group, the ServerAdminUsername should be the group name, not the actual username of the
// identity to log in with. For example if the administrator group is "admin-group" and identity "my-identity" is
// a member of that group, the ServerAdminUsername should be "admin-group".
// +kubebuilder:validation:Required
ServerAdminUsername string `json:"serverAdminUsername,omitempty"`
}

type UserStatus struct {
// Conditions: The observed state of the resource
Conditions []conditions.Condition `json:"conditions,omitempty"`
Expand Down
193 changes: 193 additions & 0 deletions v2/api/sql/v1/webhook/user_webhook_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
package webhook

import (
"context"
"testing"

. "github.com/onsi/gomega"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

v1 "github.com/Azure/azure-service-operator/v2/api/sql/v1"
"github.com/Azure/azure-service-operator/v2/pkg/genruntime"
)

func Test_UserWebhook_ValidateIsLocalOrAAD(t *testing.T) {
t.Parallel()
g := NewGomegaWithT(t)
webhook := &User_Webhook{}
ctx := context.Background()

tests := []struct {
name string
user *v1.User
wantErr string
}{
{
name: "valid local user",
user: &v1.User{
Spec: v1.UserSpec{
LocalUser: &v1.LocalUserSpec{
ServerAdminUsername: "admin",
ServerAdminPassword: &genruntime.SecretReference{Name: "secret", Key: "password"},
Password: &genruntime.SecretReference{Name: "secret", Key: "userpass"},
},
},
},
wantErr: "",
},
{
name: "valid AAD user",
user: &v1.User{
Spec: v1.UserSpec{
AADUser: &v1.AADUserSpec{
ServerAdminUsername: "admin",
},
},
},
wantErr: "",
},
{
name: "neither specified",
user: &v1.User{Spec: v1.UserSpec{}},
wantErr: "exactly one of spec.localUser or spec.aadUser must be set",
},
{
name: "both specified",
user: &v1.User{
Spec: v1.UserSpec{
LocalUser: &v1.LocalUserSpec{ServerAdminUsername: "admin"},
AADUser: &v1.AADUserSpec{ServerAdminUsername: "admin"},
},
},
wantErr: "exactly one of spec.localUser or spec.aadUser must be set",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := webhook.validateIsLocalOrAAD(ctx, tt.user)
if tt.wantErr == "" {
g.Expect(err).To(BeNil())
} else {
g.Expect(err).ToNot(BeNil())
g.Expect(err.Error()).To(ContainSubstring(tt.wantErr))
}
})
}
}

func Test_UserWebhook_ValidateUserTypeNotChanged(t *testing.T) {
t.Parallel()
g := NewGomegaWithT(t)
webhook := &User_Webhook{}
ctx := context.Background()

tests := []struct {
name string
oldUser *v1.User
newUser *v1.User
wantErr string
}{
{
name: "local to local - allowed",
oldUser: &v1.User{Spec: v1.UserSpec{LocalUser: &v1.LocalUserSpec{ServerAdminUsername: "admin"}}},
newUser: &v1.User{Spec: v1.UserSpec{LocalUser: &v1.LocalUserSpec{ServerAdminUsername: "admin2"}}},
wantErr: "",
},
{
name: "aad to aad - allowed",
oldUser: &v1.User{Spec: v1.UserSpec{AADUser: &v1.AADUserSpec{ServerAdminUsername: "admin"}}},
newUser: &v1.User{Spec: v1.UserSpec{AADUser: &v1.AADUserSpec{ServerAdminUsername: "admin2"}}},
wantErr: "",
},
{
name: "local to aad - not allowed",
oldUser: &v1.User{Spec: v1.UserSpec{LocalUser: &v1.LocalUserSpec{ServerAdminUsername: "admin"}}},
newUser: &v1.User{Spec: v1.UserSpec{AADUser: &v1.AADUserSpec{ServerAdminUsername: "admin"}}},
wantErr: "cannot change from local user to AAD user",
},
{
name: "aad to local - not allowed",
oldUser: &v1.User{Spec: v1.UserSpec{AADUser: &v1.AADUserSpec{ServerAdminUsername: "admin"}}},
newUser: &v1.User{Spec: v1.UserSpec{LocalUser: &v1.LocalUserSpec{ServerAdminUsername: "admin"}}},
wantErr: "cannot change from AAD user to local user",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := webhook.validateUserTypeNotChanged(ctx, tt.oldUser, tt.newUser)
if tt.wantErr == "" {
g.Expect(err).To(BeNil())
} else {
g.Expect(err).ToNot(BeNil())
g.Expect(err.Error()).To(ContainSubstring(tt.wantErr))
}
})
}
}

func Test_UserWebhook_ValidateUserAADAliasNotChanged(t *testing.T) {
t.Parallel()
g := NewGomegaWithT(t)
webhook := &User_Webhook{}
ctx := context.Background()

tests := []struct {
name string
oldUser *v1.User
newUser *v1.User
wantErr string
}{
{
name: "alias unchanged - allowed",
oldUser: &v1.User{Spec: v1.UserSpec{AADUser: &v1.AADUserSpec{Alias: "myalias"}}},
newUser: &v1.User{Spec: v1.UserSpec{AADUser: &v1.AADUserSpec{Alias: "myalias"}}},
wantErr: "",
},
{
name: "alias changed - not allowed",
oldUser: &v1.User{Spec: v1.UserSpec{AADUser: &v1.AADUserSpec{Alias: "oldalias"}}},
newUser: &v1.User{Spec: v1.UserSpec{AADUser: &v1.AADUserSpec{Alias: "newalias"}}},
wantErr: "cannot change AAD user 'alias'",
},
{
name: "local user - skipped",
oldUser: &v1.User{Spec: v1.UserSpec{LocalUser: &v1.LocalUserSpec{ServerAdminUsername: "admin"}}},
newUser: &v1.User{Spec: v1.UserSpec{LocalUser: &v1.LocalUserSpec{ServerAdminUsername: "admin"}}},
wantErr: "",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := webhook.validateUserAADAliasNotChanged(ctx, tt.oldUser, tt.newUser)
if tt.wantErr == "" {
g.Expect(err).To(BeNil())
} else {
g.Expect(err).ToNot(BeNil())
g.Expect(err.Error()).To(ContainSubstring(tt.wantErr))
}
})
}
}

func Test_UserWebhook_ValidateCreate(t *testing.T) {
t.Parallel()
g := NewGomegaWithT(t)
webhook := &User_Webhook{}
ctx := context.Background()

user := &v1.User{
ObjectMeta: metav1.ObjectMeta{Name: "test-user", Namespace: "default"},
Spec: v1.UserSpec{
AzureName: "my-managed-identity",
AADUser: &v1.AADUserSpec{ServerAdminUsername: "admin"},
},
}

_, err := webhook.ValidateCreate(ctx, user)
g.Expect(err).To(BeNil())
}
63 changes: 57 additions & 6 deletions v2/api/sql/v1/webhook/user_webhook_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ var _ webhook.CustomDefaulter = &User_Webhook{}
func (webhook *User_Webhook) Default(ctx context.Context, obj runtime.Object) error {
resource, ok := obj.(*v1.User)
if !ok {
return fmt.Errorf("expected github.com/Azure/azure-service-operator/v2/api/dbforpostgresql/v1/User, but got %T", obj)
return fmt.Errorf("expected github.com/Azure/azure-service-operator/v2/api/sql/v1/User, but got %T", obj)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hah, great catch

}
err := webhook.defaultImpl(ctx, resource)
if err != nil {
Expand Down Expand Up @@ -68,7 +68,7 @@ var _ webhook.CustomValidator = &User_Webhook{}
func (webhook *User_Webhook) ValidateCreate(ctx context.Context, obj runtime.Object) (admission.Warnings, error) {
resource, ok := obj.(*v1.User)
if !ok {
return nil, fmt.Errorf("expected github.com/Azure/azure-service-operator/v2/api/dbforpostgresql/v1/User, but got %T", obj)
return nil, fmt.Errorf("expected github.com/Azure/azure-service-operator/v2/api/sql/v1/User, but got %T", obj)
}
validations := webhook.createValidations()
var temp any = webhook
Expand All @@ -82,7 +82,7 @@ func (webhook *User_Webhook) ValidateCreate(ctx context.Context, obj runtime.Obj
func (webhook *User_Webhook) ValidateDelete(ctx context.Context, obj runtime.Object) (admission.Warnings, error) {
resource, ok := obj.(*v1.User)
if !ok {
return nil, fmt.Errorf("expected github.com/Azure/azure-service-operator/v2/api/dbforpostgresql/v1/User, but got %T", obj)
return nil, fmt.Errorf("expected github.com/Azure/azure-service-operator/v2/api/sql/v1/User, but got %T", obj)
}
validations := webhook.deleteValidations()
var temp any = webhook
Expand All @@ -96,11 +96,11 @@ func (webhook *User_Webhook) ValidateDelete(ctx context.Context, obj runtime.Obj
func (webhook *User_Webhook) ValidateUpdate(ctx context.Context, oldObj runtime.Object, newObj runtime.Object) (admission.Warnings, error) {
newResource, ok := newObj.(*v1.User)
if !ok {
return nil, fmt.Errorf("expected github.com/Azure/azure-service-operator/v2/api/dbforpostgresql/v1/User, but got %T", newObj)
return nil, fmt.Errorf("expected github.com/Azure/azure-service-operator/v2/api/sql/v1/User, but got %T", newObj)
}
oldResource, ok := oldObj.(*v1.User)
if !ok {
return nil, fmt.Errorf("expected github.com/Azure/azure-service-operator/v2/api/dbforpostgresql/v1/User, but got %T", oldObj)
return nil, fmt.Errorf("expected github.com/Azure/azure-service-operator/v2/api/sql/v1/User, but got %T", oldObj)
}
validations := webhook.updateValidations()
var temp any = webhook
Expand All @@ -116,7 +116,9 @@ func (webhook *User_Webhook) ValidateUpdate(ctx context.Context, oldObj runtime.

// createValidations validates the creation of the resource
func (webhook *User_Webhook) createValidations() []func(ctx context.Context, obj *v1.User) (admission.Warnings, error) {
return nil
return []func(ctx context.Context, obj *v1.User) (admission.Warnings, error){
webhook.validateIsLocalOrAAD,
}
}

// deleteValidations validates the deletion of the resource
Expand All @@ -127,7 +129,12 @@ func (webhook *User_Webhook) deleteValidations() []func(ctx context.Context, obj
// updateValidations validates the update of the resource
func (webhook *User_Webhook) updateValidations() []func(ctx context.Context, oldObj *v1.User, newObj *v1.User) (admission.Warnings, error) {
return []func(ctx context.Context, oldObj *v1.User, newObj *v1.User) (admission.Warnings, error){
func(ctx context.Context, oldObj *v1.User, newObj *v1.User) (admission.Warnings, error) {
return webhook.validateIsLocalOrAAD(ctx, newObj)
},
webhook.validateUserTypeNotChanged,
webhook.validateWriteOncePropertiesNotChanged,
webhook.validateUserAADAliasNotChanged,
}
}

Expand Down Expand Up @@ -177,3 +184,47 @@ func (webhook *User_Webhook) validateWriteOncePropertiesNotChanged(_ context.Con

return nil, kerrors.NewAggregate(errs)
}

// validateIsLocalOrAAD validates that exactly one of LocalUser or AADUser is specified
func (webhook *User_Webhook) validateIsLocalOrAAD(_ context.Context, obj *v1.User) (admission.Warnings, error) {
if obj.Spec.LocalUser == nil && obj.Spec.AADUser == nil {
return nil, eris.Errorf("exactly one of spec.localUser or spec.aadUser must be set")
}

if obj.Spec.LocalUser != nil && obj.Spec.AADUser != nil {
return nil, eris.Errorf("exactly one of spec.localUser or spec.aadUser must be set, not both")
}

return nil, nil
}

// validateUserTypeNotChanged prevents changing user type after creation
func (webhook *User_Webhook) validateUserTypeNotChanged(_ context.Context, oldObj *v1.User, newObj *v1.User) (admission.Warnings, error) {
// Prevent change from AAD -> Local
if oldObj.Spec.AADUser != nil && newObj.Spec.AADUser == nil {
return nil, eris.Errorf("cannot change from AAD user to local user")
}

// Prevent change from Local -> AAD
if oldObj.Spec.LocalUser != nil && newObj.Spec.LocalUser == nil {
return nil, eris.Errorf("cannot change from local user to AAD user")
}

return nil, nil
}

// validateUserAADAliasNotChanged prevents changing AAD alias after creation
func (webhook *User_Webhook) validateUserAADAliasNotChanged(_ context.Context, oldObj *v1.User, newObj *v1.User) (admission.Warnings, error) {
if oldObj.Spec.AADUser == nil || newObj.Spec.AADUser == nil {
return nil, nil
}

oldAlias := oldObj.Spec.AADUser.Alias
newAlias := newObj.Spec.AADUser.Alias

if oldAlias != newAlias {
return nil, eris.Errorf("cannot change AAD user 'alias' from %q to %q", oldAlias, newAlias)
}

return nil, nil
}
20 changes: 20 additions & 0 deletions v2/api/sql/v1/zz_generated.deepcopy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading