diff --git a/stackit/internal/services/mongodbflex/mongodbflex_test.go b/stackit/internal/services/mongodbflex/mongodbflex_test.go index 0321a442b..ffab2b682 100644 --- a/stackit/internal/services/mongodbflex/mongodbflex_test.go +++ b/stackit/internal/services/mongodbflex/mongodbflex_test.go @@ -167,3 +167,32 @@ resource "stackit_mongodbflex_user" "user" { }, }) } + +func TestMongoDBUserInvalidUsernameValidationError(t *testing.T) { + projectId := uuid.NewString() + instanceId := uuid.NewString() + tfConfig := fmt.Sprintf(` +provider "stackit" { + mongodbflex_custom_endpoint = "http://localhost:12345" + service_account_token = "mock-server-needs-no-auth" +} + +resource "stackit_mongodbflex_user" "user" { + project_id = "%s" + instance_id = "%s" + username = "-invalid-username" + roles = ["read"] + database = "db-name" +} +`, projectId, instanceId) + + resource.UnitTest(t, resource.TestCase{ + ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories, + Steps: []resource.TestStep{ + { + Config: tfConfig, + ExpectError: regexp.MustCompile("Attribute username must start with a letter.*"), + }, + }, + }) +} diff --git a/stackit/internal/services/mongodbflex/user/resource.go b/stackit/internal/services/mongodbflex/user/resource.go index b3ef51f69..e70253ecd 100644 --- a/stackit/internal/services/mongodbflex/user/resource.go +++ b/stackit/internal/services/mongodbflex/user/resource.go @@ -5,8 +5,10 @@ import ( "errors" "fmt" "net/http" + "regexp" "strings" + "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" "github.com/hashicorp/terraform-plugin-framework/resource/schema/mapplanmodifier" "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils" @@ -183,6 +185,12 @@ func (r *userResource) Schema(_ context.Context, _ resource.SchemaRequest, resp stringplanmodifier.RequiresReplace(), stringplanmodifier.UseStateForUnknown(), }, + Validators: []validator.String{ + stringvalidator.RegexMatches( + regexp.MustCompile("^[A-Za-z][A-Za-z0-9-]{1,61}[A-Za-z0-9]$"), + "must start with a letter, must have between 3 and 63 letters, numbers or hyphens, and no hyphen at the end", + ), + }, }, "roles": schema.SetAttribute{ Description: descriptions["roles"],