From b2624497d99cdc7ffec6cb62d696cdd6e2e2fd91 Mon Sep 17 00:00:00 2001 From: William Wang Date: Tue, 29 Apr 2025 19:10:24 +0000 Subject: [PATCH] Merged PR 1633683: Add Support for Username/Password Constraint Validation for DataPlane User CRUD with Extensibility Hooks ### Does this PR have any customer impact? Yes ### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc) Feature ### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes) No ### Are you introducing any new config? If yes, do you have tests with and without them being set? No ### ChangeLog (Refer [Template](../oss/CHANGELOG.md)) ### Description We are adding the following constraints for username and password: **Username** - The username length must be greater than 0 and less than or equal to 63 characters. **Password** - The password length must be between 8 and 256 characters (inclusive). - The password must satisfy at least 3 of the following 4 conditions: - Contains at least one lowercase letter. - Contains at least one uppercase letter. - Contains at least one digit. - Contains at least one special (non-alphanumeric) character. - The password must not contain any 3-character substring of the username (case-insensitive). Related work items: #3916282 --- pg_documentdb/include/api_hooks.h | 12 ++++ pg_documentdb/include/api_hooks_def.h | 11 +++ pg_documentdb/src/api_hooks.c | 34 +++++++++ pg_documentdb/src/commands/users.c | 72 +++++++++++++++---- .../src/configs/feature_flag_configs.c | 11 +++ .../regress/expected/user_crud_commands.out | 29 ++++++++ .../test/regress/sql/user_crud_commands.sql | 11 +++ 7 files changed, 168 insertions(+), 12 deletions(-) diff --git a/pg_documentdb/include/api_hooks.h b/pg_documentdb/include/api_hooks.h index ff6b64a3..2fb4219a 100644 --- a/pg_documentdb/include/api_hooks.h +++ b/pg_documentdb/include/api_hooks.h @@ -115,6 +115,18 @@ bool IsUserExternal(const char *userName); */ const pgbson * GetUserInfoFromExternalIdentityProvider(const char *userName); +/* + * Default password validation implementation + * Returns true if password is valid, false otherwise + */ +bool IsPasswordValid(const char *username, const char *password); + +/* + * Default username validation implementation + * Returns true if username is valid, false otherwise + */ +bool IsUsernameValid(const char *username); + /* * Hook for handling colocation of tables */ diff --git a/pg_documentdb/include/api_hooks_def.h b/pg_documentdb/include/api_hooks_def.h index 4e45a83d..d8c17950 100644 --- a/pg_documentdb/include/api_hooks_def.h +++ b/pg_documentdb/include/api_hooks_def.h @@ -118,6 +118,17 @@ typedef const pgbson *(*GetUserInfoFromExternalIdentityProvider_HookType)(); extern GetUserInfoFromExternalIdentityProvider_HookType get_user_info_from_external_identity_provider_hook; + +/* Method for username validation */ +typedef bool (*UserNameValidation_HookType)(const char *username); +extern UserNameValidation_HookType username_validation_hook; + + +/* Method for password validation */ +typedef bool (*PasswordValidation_HookType)(const char *username, const char *password); +extern PasswordValidation_HookType password_validation_hook; + + /* * Hook for enabling running a query with nested distribution enabled. */ diff --git a/pg_documentdb/src/api_hooks.c b/pg_documentdb/src/api_hooks.c index 038127cb..8cb944e3 100644 --- a/pg_documentdb/src/api_hooks.c +++ b/pg_documentdb/src/api_hooks.c @@ -62,6 +62,10 @@ GetUserInfoFromExternalIdentityProvider_HookType get_user_info_from_external_identity_provider_hook = NULL; IsUserExternal_HookType is_user_external_hook = NULL; +UserNameValidation_HookType + username_validation_hook = NULL; +PasswordValidation_HookType + password_validation_hook = NULL; /* * Single node scenario is always a metadata coordinator @@ -295,6 +299,36 @@ IsUserExternal(const char *userName) } +/* + * Default password validation implementation, just returns true + */ +bool +IsPasswordValid(const char *username, const char *password) +{ + if (password_validation_hook != NULL) + { + return password_validation_hook(username, password); + } + return true; +} + + +/* + * Default username validation implementation + * Returns true if username is valid, false otherwise + */ +bool +IsUsernameValid(const char *username) +{ + if (username_validation_hook != NULL) + { + return username_validation_hook(username); + } + + return true; +} + + void HandleColocation(MongoCollection *collection, const bson_value_t *colocationOptions) { diff --git a/pg_documentdb/src/commands/users.c b/pg_documentdb/src/commands/users.c index 3cd93be2..cd9d2eaa 100644 --- a/pg_documentdb/src/commands/users.c +++ b/pg_documentdb/src/commands/users.c @@ -38,6 +38,9 @@ extern int MaxUserLimit; /* GUC that controls the blocked role prefix list*/ extern char *BlockedRolePrefixList; +/* GUC that controls whether we use username/password validation*/ +extern bool EnableUsernamePasswordConstraints; + PG_FUNCTION_INFO_V1(documentdb_extension_create_user); PG_FUNCTION_INFO_V1(documentdb_extension_drop_user); PG_FUNCTION_INFO_V1(documentdb_extension_update_user); @@ -50,6 +53,7 @@ static Datum UpdateNativeUser(UpdateUserSpec *spec); static char * ParseGetUserSpec(pgbson *getSpec); static char * PrehashPassword(const char *password); static bool IsCallingUserExternal(void); +static bool IsPasswordInvalid(const char *username, const char *password); /* * documentdb_extension_create_user implements the @@ -280,7 +284,7 @@ ParseCreateUserSpec(pgbson *createSpec) { ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_BADVALUE), - errmsg("'customData' must be a bson document."))); + errmsg("'customData' must be a BSON document."))); } if (!IsBsonValueEmptyDocument(customDataDocument)) @@ -328,10 +332,19 @@ ParseCreateUserSpec(pgbson *createSpec) "Password is not allowed when using an external identity provider."))); } } - else if (!has_user || !has_roles || !has_pwd) + else { - ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_BADVALUE), errmsg( - "'createUser', 'roles' and 'pwd' are required fields."))); + if (!has_user || !has_roles || !has_pwd) + { + ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_BADVALUE), errmsg( + "'createUser', 'roles' and 'pwd' are required fields."))); + } + + if (IsPasswordInvalid(spec->createUser, spec->pwd)) + { + ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_BADVALUE), + errmsg("Invalid password, use a different password."))); + } } return spec; @@ -649,7 +662,7 @@ documentdb_extension_update_user(PG_FUNCTION_ARGS) { ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_COMMANDNOTSUPPORTED), errmsg( - "UpdateUser command is not supported for a non native user."))); + "UpdateUser command is not supported for a non-native user."))); } else { @@ -742,6 +755,13 @@ UpdateNativeUser(UpdateUserSpec *spec) errmsg("Password cannot be empty."))); } + /* Verify password meets complexity requirements */ + if (IsPasswordInvalid(spec->updateUser, spec->pwd)) + { + ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_BADVALUE), + errmsg("Invalid password, use a different password."))); + } + StringInfo updateUserInfo = makeStringInfo(); appendStringInfo(updateUserInfo, "ALTER USER %s WITH PASSWORD %s;", quote_identifier( spec->updateUser), quote_literal_cstr(PrehashPassword( @@ -1083,7 +1103,7 @@ PrehashPassword(const char *password) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), - errmsg("could not generate random salt."))); + errmsg("Could not generate random salt."))); } #if PG_VERSION_NUM >= 160000 /* PostgreSQL 16.0 or higher */ @@ -1106,23 +1126,51 @@ PrehashPassword(const char *password) } +/* + * Method calls the IsUsernameValid hook to validate the username. + * This validation logic must be in sync with control plane username validation. + */ bool IsUserNameInvalid(const char *userName) { /* Split the blocked role prefix list */ - char *copyBlockList = pstrdup(BlockedRolePrefixList); - char *token = strtok(copyBlockList, ","); + char *blockedRolePrefixList = pstrdup(BlockedRolePrefixList); + bool containsBlockedPrefix = false; + char *token = strtok(blockedRolePrefixList, ","); while (token != NULL) { if (strncmp(userName, token, strlen(token)) == 0) { - pfree(copyBlockList); - return true; + containsBlockedPrefix = true; + break; } token = strtok(NULL, ","); } - pfree(copyBlockList); - return false; + pfree(blockedRolePrefixList); + + + bool is_valid = !containsBlockedPrefix; + if (EnableUsernamePasswordConstraints) + { + is_valid = IsUsernameValid(userName) && is_valid; + } + return !is_valid; +} + + +/* + * Method calls the IsPasswordValid hook to validate the password. + * This validation logic must be in sync with control plane password validation. + */ +static bool +IsPasswordInvalid(const char *username, const char *password) +{ + bool is_valid = true; + if (EnableUsernamePasswordConstraints) + { + is_valid = IsPasswordValid(username, password); + } + return !is_valid; } diff --git a/pg_documentdb/src/configs/feature_flag_configs.c b/pg_documentdb/src/configs/feature_flag_configs.c index 527ca633..9266648d 100644 --- a/pg_documentdb/src/configs/feature_flag_configs.c +++ b/pg_documentdb/src/configs/feature_flag_configs.c @@ -150,6 +150,9 @@ bool EnableBackendStatementTimeout = DEFAULT_ENABLE_STATEMENT_TIMEOUT; #define ALTER_CREATION_TIME_IN_COMPLETE_UPGRADE false bool AlterCreationTimeInCompleteUpgrade = ALTER_CREATION_TIME_IN_COMPLETE_UPGRADE; +#define DEFAULT_ENABLE_USERNAME_PASSWORD_CONSTRAINTS true +bool EnableUsernamePasswordConstraints = DEFAULT_ENABLE_USERNAME_PASSWORD_CONSTRAINTS; + /* FEATURE FLAGS END */ void @@ -421,4 +424,12 @@ InitializeFeatureFlagConfigurations(const char *prefix, const char *newGucPrefix NULL, &IndexTermUseUnsafeTransform, DEFAULT_USE_UNSAFE_INDEX_TERM_TRANSFORM, PGC_USERSET, 0, NULL, NULL, NULL); + + DefineCustomBoolVariable( + psprintf("%s.enableUsernamePasswordConstraints", newGucPrefix), + gettext_noop( + "Determines whether username and password constraints are enabled."), + NULL, &EnableUsernamePasswordConstraints, + DEFAULT_ENABLE_USERNAME_PASSWORD_CONSTRAINTS, + PGC_USERSET, 0, NULL, NULL, NULL); } diff --git a/pg_documentdb/src/test/regress/expected/user_crud_commands.out b/pg_documentdb/src/test/regress/expected/user_crud_commands.out index 71a415d0..c0641f4b 100644 --- a/pg_documentdb/src/test/regress/expected/user_crud_commands.out +++ b/pg_documentdb/src/test/regress/expected/user_crud_commands.out @@ -87,6 +87,35 @@ SELECT documentdb_api.create_user('{"createUser":"test_user4", "pwd":"test_passw { "ok" : { "$numberInt" : "1" } } (1 row) +-- Create a user with an empty password should fail +SELECT documentdb_api.create_user('{"createUser":"test_user_empty_pwd", "pwd":"", "roles":[{"role":"readAnyDatabase","db":"admin"}]}'); +ERROR: Password cannot be empty. +-- Create a user with password less than 8 characters and drop it +SELECT documentdb_api.create_user('{"createUser":"test_user_short_pwd", "pwd":"Short1!", "roles":[{"role":"readAnyDatabase","db":"admin"}]}'); + create_user +----------------------------------- + { "ok" : { "$numberInt" : "1" } } +(1 row) + +SELECT documentdb_api.drop_user('{"dropUser":"test_user_short_pwd"}'); + drop_user +----------------------------------- + { "ok" : { "$numberInt" : "1" } } +(1 row) + +-- Create a user with password more than 256 characters and drop it +SELECT documentdb_api.create_user('{"createUser":"test_user_long_pwd", "pwd":"ThisIsAVeryLongPasswordThatExceedsTheTwoHundredFiftySixCharacterLimitAndThereforeShouldFailValidation1!abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", "roles":[{"role":"readAnyDatabase","db":"admin"}]}'); + create_user +----------------------------------- + { "ok" : { "$numberInt" : "1" } } +(1 row) + +SELECT documentdb_api.drop_user('{"dropUser":"test_user_long_pwd"}'); + drop_user +----------------------------------- + { "ok" : { "$numberInt" : "1" } } +(1 row) + --Verify that the user is created SELECT documentdb_api.users_info('{"usersInfo":"test_user4"}'); users_info diff --git a/pg_documentdb/src/test/regress/sql/user_crud_commands.sql b/pg_documentdb/src/test/regress/sql/user_crud_commands.sql index a6b66bc5..391cd709 100644 --- a/pg_documentdb/src/test/regress/sql/user_crud_commands.sql +++ b/pg_documentdb/src/test/regress/sql/user_crud_commands.sql @@ -55,6 +55,17 @@ SELECT documentdb_api.create_user('{"createUser":"test_user4", "pwd":"test_passw --Create a user with no DB SELECT documentdb_api.create_user('{"createUser":"test_user4", "pwd":"test_password", "roles":[{"role":"readWriteAnyDatabase"}, {"role":"clusterAdmin"}]}'); +-- Create a user with an empty password should fail +SELECT documentdb_api.create_user('{"createUser":"test_user_empty_pwd", "pwd":"", "roles":[{"role":"readAnyDatabase","db":"admin"}]}'); + +-- Create a user with password less than 8 characters and drop it +SELECT documentdb_api.create_user('{"createUser":"test_user_short_pwd", "pwd":"Short1!", "roles":[{"role":"readAnyDatabase","db":"admin"}]}'); +SELECT documentdb_api.drop_user('{"dropUser":"test_user_short_pwd"}'); + +-- Create a user with password more than 256 characters and drop it +SELECT documentdb_api.create_user('{"createUser":"test_user_long_pwd", "pwd":"ThisIsAVeryLongPasswordThatExceedsTheTwoHundredFiftySixCharacterLimitAndThereforeShouldFailValidation1!abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", "roles":[{"role":"readAnyDatabase","db":"admin"}]}'); +SELECT documentdb_api.drop_user('{"dropUser":"test_user_long_pwd"}'); + --Verify that the user is created SELECT documentdb_api.users_info('{"usersInfo":"test_user4"}');