👽️(mailboxes) fix mailbox creation after dimail api improvement

Latest dimail modification lead to a bug in our app, preventing mailbox creation
from working properly. I swapped old dimail url to new one, mirrored dimail
modification and fixed tests and tada!
This commit is contained in:
Marie PUPO JEAMMET
2024-08-26 19:10:43 +02:00
committed by Marie
parent ba46d7de54
commit e04a994d37
9 changed files with 34 additions and 23 deletions

View File

@@ -10,7 +10,11 @@ and this project adheres to
### Added ### Added
🔧Runtime config for the frontend #345 - 🔧Runtime config for the frontend (#345)
### Fixed
- 👽️(mailboxes) fix mailbox creation after dimail api improvement (#360)
## [1.0.1] - 2024-08-19 ## [1.0.1] - 2024-08-19

View File

@@ -96,7 +96,9 @@ class MailboxFactory(factory.django.DjangoModelFactory):
) )
rsps.add( rsps.add(
rsps.POST, rsps.POST,
re.compile(rf".*/domains/{domain.name}/mailboxes/"), re.compile(
rf".*/domains/{domain.name}/mailboxes/{kwargs['local_part']}"
),
body=str( body=str(
{ {
"email": f"{kwargs['local_part']}@{domain.name}", "email": f"{kwargs['local_part']}@{domain.name}",

View File

@@ -79,10 +79,7 @@ def test_api_mailboxes__create_viewer_failure():
@pytest.mark.parametrize( @pytest.mark.parametrize(
"role", "role",
[ [enums.MailDomainRoleChoices.OWNER, enums.MailDomainRoleChoices.ADMIN],
enums.MailDomainRoleChoices.OWNER,
enums.MailDomainRoleChoices.ADMIN,
],
) )
def test_api_mailboxes__create_roles_success(role): def test_api_mailboxes__create_roles_success(role):
"""Users with owner or admin role should be able to create mailbox on the mail domain.""" """Users with owner or admin role should be able to create mailbox on the mail domain."""
@@ -139,10 +136,7 @@ def test_api_mailboxes__create_roles_success(role):
@pytest.mark.parametrize( @pytest.mark.parametrize(
"role", "role",
[ [enums.MailDomainRoleChoices.OWNER, enums.MailDomainRoleChoices.ADMIN],
enums.MailDomainRoleChoices.OWNER,
enums.MailDomainRoleChoices.ADMIN,
],
) )
def test_api_mailboxes__create_with_accent_success(role): def test_api_mailboxes__create_with_accent_success(role):
"""Users with proper abilities should be able to create mailbox on the mail domain with a """Users with proper abilities should be able to create mailbox on the mail domain with a
@@ -345,7 +339,6 @@ def test_api_mailboxes__domain_owner_or_admin_successful_creation_and_provisioni
payload = json.loads(rsps.calls[1].request.body) payload = json.loads(rsps.calls[1].request.body)
assert payload == { assert payload == {
"displayName": f"{mailbox_data['first_name']} {mailbox_data['last_name']}", "displayName": f"{mailbox_data['first_name']} {mailbox_data['last_name']}",
"email": f"{mailbox_data['local_part']}@{access.domain.name}",
"givenName": mailbox_data["first_name"], "givenName": mailbox_data["first_name"],
"surName": mailbox_data["last_name"], "surName": mailbox_data["last_name"],
} }

View File

@@ -246,12 +246,15 @@ def test_models_mailboxes__create_mailbox_success(mock_info, mock_error):
# Logger # Logger
assert not mock_error.called assert not mock_error.called
assert mock_info.call_count == 1 assert mock_info.call_count == 2
assert mock_info.call_args_list[0][0] == ( assert mock_info.call_args_list[0][0] == (
"Token succesfully granted by mail-provisioning API.",
)
assert mock_info.call_args_list[1][0] == (
"Mailbox successfully created on domain %s", "Mailbox successfully created on domain %s",
domain.name, domain.name,
) )
assert mock_info.call_args_list[0][1] == ( assert mock_info.call_args_list[1][1] == (
{ {
"extra": { "extra": {
"response": str( "response": str(

View File

@@ -28,13 +28,15 @@ session.mount("https://", adapter)
class DimailAPIClient: class DimailAPIClient:
"""A dimail-API client.""" """A dimail-API client."""
API_URL = settings.MAIL_PROVISIONING_API_URL
def get_headers(self, domain): def get_headers(self, domain):
"""Build header dict from domain object.""" """Build header dict from domain object."""
# self.secret is the encoded basic auth, to request a new token from dimail-api # self.secret is the encoded basic auth, to request a new token from dimail-api
headers = {"Content-Type": "application/json"} headers = {"Content-Type": "application/json"}
response = requests.get( response = requests.get(
f"{settings.MAIL_PROVISIONING_API_URL}/token/", f"{self.API_URL}/token/",
headers={"Authorization": f"Basic {domain.secret}"}, headers={"Authorization": f"Basic {domain.secret}"},
timeout=status.HTTP_200_OK, timeout=status.HTTP_200_OK,
) )
@@ -46,6 +48,7 @@ class DimailAPIClient:
if "access_token" in response.json(): if "access_token" in response.json():
headers["Authorization"] = f"Bearer {response.json()['access_token']}" headers["Authorization"] = f"Bearer {response.json()['access_token']}"
logger.info("Token succesfully granted by mail-provisioning API.")
return headers return headers
@@ -53,7 +56,6 @@ class DimailAPIClient:
"""Send a CREATE mailbox request to mail provisioning API.""" """Send a CREATE mailbox request to mail provisioning API."""
payload = { payload = {
"email": f"{mailbox.local_part}@{mailbox.domain}",
"givenName": mailbox.first_name, "givenName": mailbox.first_name,
"surName": mailbox.last_name, "surName": mailbox.last_name,
"displayName": f"{mailbox.first_name} {mailbox.last_name}", "displayName": f"{mailbox.first_name} {mailbox.last_name}",
@@ -61,18 +63,19 @@ class DimailAPIClient:
try: try:
response = session.post( response = session.post(
f"{settings.MAIL_PROVISIONING_API_URL}/domains/{mailbox.domain}/mailboxes/", f"{self.API_URL}/domains/{mailbox.domain}/mailboxes/{mailbox.local_part}/",
json=payload, json=payload,
headers=self.get_headers(mailbox.domain), headers=self.get_headers(mailbox.domain),
verify=True, verify=True,
timeout=10, timeout=10,
) )
except requests.exceptions.ConnectionError as e: except requests.exceptions.ConnectionError as error:
logger.error( logger.error(
"Connection error while trying to reach %s.", "Connection error while trying to reach %s.",
settings.MAIL_PROVISIONING_API_URL, self.API_URL,
exc_info=e, exc_info=error,
) )
raise error
if response.status_code == status.HTTP_201_CREATED: if response.status_code == status.HTTP_201_CREATED:
extra = {"response": response.content.decode("utf-8")} extra = {"response": response.content.decode("utf-8")}
@@ -92,4 +95,10 @@ class DimailAPIClient:
raise exceptions.PermissionDenied( raise exceptions.PermissionDenied(
f"Please check secret of the mail domain {mailbox.domain.name}" f"Please check secret of the mail domain {mailbox.domain.name}"
) )
else:
logger.error(
"Unexpected response: %s",
response.content.decode("utf-8"),
)
return response return response

View File

@@ -366,7 +366,7 @@ class Base(Configuration):
# mailboxes provisioning API # mailboxes provisioning API
MAIL_PROVISIONING_API_URL = values.Value( MAIL_PROVISIONING_API_URL = values.Value(
default="https://main.dev.ox.numerique.gouv.fr", default="https://api.dev.ox.numerique.gouv.fr",
environ_name="MAIL_PROVISIONING_API_URL", environ_name="MAIL_PROVISIONING_API_URL",
environ_prefix=None, environ_prefix=None,
) )

View File

@@ -84,7 +84,7 @@ backend:
secretKeyRef: secretKeyRef:
name: redis.redis.libre.sh name: redis.redis.libre.sh
key: url key: url
MAIL_PROVISIONING_API_URL: "https://main.dev.ox.numerique.gouv.fr" MAIL_PROVISIONING_API_URL: "https://api.dev.ox.numerique.gouv.fr"
FEATURE_TEAMS: False FEATURE_TEAMS: False
createsuperuser: createsuperuser:

View File

@@ -84,7 +84,7 @@ backend:
secretKeyRef: secretKeyRef:
name: redis.redis.libre.sh name: redis.redis.libre.sh
key: url key: url
MAIL_PROVISIONING_API_URL: "https://main.dev.ox.numerique.gouv.fr" MAIL_PROVISIONING_API_URL: "https://api.dev.ox.numerique.gouv.fr"
FEATURE_TEAMS: False FEATURE_TEAMS: False
createsuperuser: createsuperuser:

View File

@@ -84,7 +84,7 @@ backend:
secretKeyRef: secretKeyRef:
name: redis.redis.libre.sh name: redis.redis.libre.sh
key: url key: url
MAIL_PROVISIONING_API_URL: "https://main.dev.ox.numerique.gouv.fr" MAIL_PROVISIONING_API_URL: "https://api.dev.ox.numerique.gouv.fr"
createsuperuser: createsuperuser: