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

Feature/custom user regex #71

Merged
merged 25 commits into from
Feb 5, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
fix PR comments
  • Loading branch information
MotwaniM committed Feb 1, 2024
commit b4bde6496c137478cd1479b75d76a8919337ea15
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ RESOURCE_PREFIX=rapid
DOMAIN_NAME=example.com
COGNITO_USER_POOL_ID=11111111
LAYERS=raw,layer
CUSTOM_USERNAME_REGEX="regex_expression"
CUSTOM_USER_NAME_REGEX="regex_expression"
# SDK Specific
RAPID_CLIENT_ID=
RAPID_CLIENT_SECRET=
Expand Down
2 changes: 0 additions & 2 deletions api/api/common/config/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@
COGNITO_RESOURCE_SERVER_ID = f"https://{DOMAIN_NAME}"
COGNITO_USER_POOL_ID = os.environ["COGNITO_USER_POOL_ID"]

CUSTOM_USERNAME_REGEX = os.environ.get("CUSTOM_USERNAME_REGEX")

ALLOWED_EMAIL_DOMAINS = os.environ["ALLOWED_EMAIL_DOMAINS"]

IDENTITY_PROVIDER_BASE_URL = (
Expand Down
4 changes: 4 additions & 0 deletions api/api/common/config/constants.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import os

BASE_API_PATH = "/api"
BASE_REGEX = "^[a-zA-Z0-9_-]"
FILENAME_WITH_TIMESTAMP_REGEX = r"[a-zA-Z0-9:_\-]+.csv$"
Expand Down Expand Up @@ -38,3 +40,5 @@

FIRST_SCHEMA_VERSION_NUMBER = 1
SCHEMA_VERSION_INCREMENT = 1

CUSTOM_USER_NAME_REGEX = os.environ.get("CUSTOM_USER_NAME_REGEX")
13 changes: 8 additions & 5 deletions api/api/domain/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from api.common.config.constants import (
EMAIL_REGEX,
USERNAME_REGEX,
CUSTOM_USER_NAME_REGEX,
)
from api.common.custom_exceptions import UserError

Expand All @@ -27,12 +28,14 @@ def get_validated_username(self):
https://docs.aws.amazon.com/cognito/latest/developerguide/limits.html
"""
if self.username is not None and re.fullmatch(USERNAME_REGEX, self.username):
custom_username_regex = os.environ.get("CUSTOM_USERNAME_REGEX")
if re.fullmatch(custom_username_regex, self.username):
if CUSTOM_USER_NAME_REGEX is None:
return self.username
raise UserError(
"Your username does not match the requirements specified by your organisation"
)
else:
if re.fullmatch(CUSTOM_USER_NAME_REGEX, self.username):
return self.username
raise UserError(
"Your username does not match the requirements specified by your organisation."
)
raise UserError(
"This username is invalid. Please check the username and try again"
)
Expand Down
2 changes: 1 addition & 1 deletion api/batect.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ containers:
ALLOWED_EMAIL_DOMAINS: ${ALLOWED_EMAIL_DOMAINS:-}
RESOURCE_PREFIX: ${RESOURCE_PREFIX:-prefix}
LAYERS: ${LAYERS:-}
CUSTOM_USERNAME_REGEX: ${CUSTOM_USERNAME_REGEX:-}
CUSTOM_USER_NAME_REGEX: ${CUSTOM_USER_NAME_REGEX:-}
tasks:
runtime-environment:
description: Build runtime environment
Expand Down
67 changes: 51 additions & 16 deletions api/test/api/adapter/test_cognito_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from api.common.config.aws import DOMAIN_NAME
from api.common.custom_exceptions import AWSServiceError, UserError
from api.domain.client import ClientRequest, ClientResponse
from api.domain.user import UserResponse, UserRequest
from api.domain.user import UserResponse, UserRequest, CUSTOM_USER_NAME_REGEX


class BaseCognitoAdapter(ABC):
Expand Down Expand Up @@ -248,10 +248,51 @@ def test_throws_error_when_client_app_name_has_not_been_changed_from_placeholder


class TestCognitoAdapterUsers(BaseCognitoAdapter):
@mock.patch.dict(
os.environ, {"CUSTOM_USERNAME_REGEX": "[a-zA-Z][a-zA-Z0-9@._-]{2,127}"}
)
def test_create_user(self):
cognito_response = {
"User": {
"Username": "TtestUser1",
"Attributes": [
{"Name": "sub", "Value": "some-uu-id-b226-e5fd18c59b85"},
{"Name": "email_verified", "Value": "True"},
{"Name": "email", "Value": "user-name@example1.com"},
],
},
"ResponseMetadata": {
"RequestId": "the-request-id-b368-fae5cebb746f",
"HTTPStatusCode": 200,
},
}
expected_response = UserResponse(
username="TtestUser1",
email="user-name@example1.com",
permissions=["WRITE_PUBLIC", "READ_PRIVATE"],
user_id="some-uu-id-b226-e5fd18c59b85",
)
request = UserRequest(
username="TtestUser1",
email="TtestUser1@example1.com",
permissions=["WRITE_PUBLIC", "READ_PRIVATE"],
)
self.cognito_boto_client.admin_create_user.return_value = cognito_response

actual_response = self.cognito_adapter.create_user(request)
self.cognito_boto_client.admin_create_user.assert_called_once_with(
UserPoolId=COGNITO_USER_POOL_ID,
Username="TtestUser1",
UserAttributes=[
{"Name": "email", "Value": "TtestUser1@example1.com"},
{"Name": "email_verified", "Value": "True"},
],
DesiredDeliveryMediums=[
"EMAIL",
],
)

assert actual_response == expected_response

@mock.patch("api.domain.user.CUSTOM_USER_NAME_REGEX", None)
def test_create_user_no_custom_regex(self):
cognito_response = {
"User": {
"Username": "user-name",
Expand Down Expand Up @@ -324,13 +365,10 @@ def test_delete_user_fails_when_user_does_not_exist(self):
):
self.cognito_adapter.delete_user("my_user")

@mock.patch.dict(
os.environ, {"CUSTOM_USERNAME_REGEX": "[a-zA-Z][a-zA-Z0-9@._-]{2,127}"}
)
def test_create_user_fails_in_aws(self):
request = UserRequest(
username="user-name",
email="user-name@example1.com",
username="TtestUser1",
email="TtestUser1@example1.com",
permissions=["WRITE_PUBLIC", "READ_PRIVATE"],
)

Expand All @@ -340,17 +378,14 @@ def test_create_user_fails_in_aws(self):
)

with pytest.raises(
AWSServiceError, match="The user 'user-name' could not be created"
AWSServiceError, match="The user 'TtestUser1' could not be created"
):
self.cognito_adapter.create_user(request)

@mock.patch.dict(
os.environ, {"CUSTOM_USERNAME_REGEX": "[a-zA-Z][a-zA-Z0-9@._-]{2,127}"}
)
def test_create_user_fails_when_the_user_already_exist(self):
request = UserRequest(
username="user-name",
email="user-name@example1.com",
username="TtestUser1",
email="TtestUser1@example1.com",
permissions=["WRITE_PUBLIC", "READ_PRIVATE"],
)

Expand All @@ -361,7 +396,7 @@ def test_create_user_fails_when_the_user_already_exist(self):

with pytest.raises(
UserError,
match="The user 'user-name' or email 'user-name@example1.com' already exist",
match="The user 'TtestUser1' or email 'TtestUser1@example1.com' already exist",
):
self.cognito_adapter.create_user(request)

Expand Down
14 changes: 7 additions & 7 deletions api/test/api/domain/test_user_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@ class TestUserRequest:
"S1234",
],
)
@mock.patch.dict(
os.environ, {"CUSTOM_USERNAME_REGEX": "[a-zA-Z][a-zA-Z0-9@._-]{2,127}"}
@mock.patch(
"api.domain.user.CUSTOM_USER_NAME_REGEX", "[a-zA-Z][a-zA-Z0-9@._-]{2,127}"
)
def test_get_validated_username(self, provided_username):
request = UserRequest(username=provided_username, email="user@email.com")

# Overrwrite env variable on fn import
# Overwrite env variable on fn import
try:
validated_name = request.get_validated_username()
assert validated_name == provided_username
Expand All @@ -46,8 +46,8 @@ def test_get_validated_username(self, provided_username):
"A" * 129,
],
)
@mock.patch.dict(
os.environ, {"CUSTOM_USERNAME_REGEX": "[a-zA-Z][a-zA-Z0-9@._-]{2,127}"}
@mock.patch(
"api.domain.user.CUSTOM_USER_NAME_REGEX", "[a-zA-Z][a-zA-Z0-9@._-]{2,127}"
)
def test_raises_error_when_invalid_username(self, provided_username):
request = UserRequest(username=provided_username, email="user@email.com")
Expand All @@ -68,7 +68,7 @@ def test_raises_error_when_invalid_username(self, provided_username):
"S1234",
],
)
@mock.patch.dict(os.environ, {"CUSTOM_USERNAME_REGEX": "^[A-Z][A-Za-z0-9]{3,50}$"})
@mock.patch("api.domain.user.CUSTOM_USER_NAME_REGEX", "^[A-Z][A-Za-z0-9]{3,50}$")
def test_get_validated_username_custom_regex(self, provided_username):
request = UserRequest(username=provided_username, email="user@email.com")
try:
Expand All @@ -87,7 +87,7 @@ def test_get_validated_username_custom_regex(self, provided_username):
"A....",
],
)
@mock.patch.dict(os.environ, {"CUSTOM_USERNAME_REGEX": "^[A-Z][A-Za-z0-9]{3,50}$"})
@mock.patch("api.domain.user.CUSTOM_USER_NAME_REGEX", "^[A-Z][A-Za-z0-9]{3,50}$")
def test_raises_error_when_invalid_username_custom_regex(self, provided_username):
request = UserRequest(username=provided_username, email="user@email.com")

Expand Down
2 changes: 1 addition & 1 deletion infrastructure/modules/app-cluster/main.tf
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ locals {
"COGNITO_USER_POOL_ID" : var.cognito_user_pool_id,
"RESOURCE_PREFIX" : var.resource-name-prefix,
"COGNITO_USER_LOGIN_APP_CREDENTIALS_SECRETS_NAME" : var.cognito_user_login_app_credentials_secrets_name
"CUSTOM_USERNAME_REGEX" : var.custom_username_regex
"CUSTOM_USER_NAME_REGEX" : var.custom_user_name_regex
}, var.project_information)
}

Expand Down
17 changes: 5 additions & 12 deletions infrastructure/modules/app-cluster/variables.tf
Original file line number Diff line number Diff line change
Expand Up @@ -203,16 +203,9 @@ variable "layers" {
default = ["default"]
}

variable "custom_username_regex" {
type = list(string)
description = "A list containing the regex expression for conditional user validation and a string to test against. The input must be a terraform list variable composed of two strings. The first string is the regex expression and the second string is the test string for said regular expression."
# Set default to a regex expression for basic api username validation
default = ["[a-zA-Z][a-zA-Z0-9@._-]{2,127}", "AUser1"]

validation {
condition = can(regex(var.custom_username_regex[0], var.custom_username_regex[1]))
error_message = "Your regex expression cannot be evaluated against your test string. Please check the expression and the test string."
}
variable "custom_user_name_regex" {
type = string
description = "A regex expression for conditional user validation."
default = null
nullable = true
}


Loading