Compare commits

..

190 Commits

Author SHA1 Message Date
Laurent Bossavit 38cfaff81f Fix typo 2024-10-25 13:00:37 +02:00
Laurent Bossavit 80ac55b6e2 (ci) add docker layer caching 2024-10-24 16:32:13 +02:00
Sabrina Demagny 230ed75d8d 🔖(patch) release version 1.4.1
Update all version files and changelog for patch release.
2024-10-23 22:55:56 +02:00
NathanPanchout 5ac3454c5a 🚑️(frontend) fix MailDomainsLayout
The content is not scrollable. We add an auto overflow to solve this problem
2024-10-23 21:44:28 +02:00
Sabrina Demagny bbac34b62a 🔖(minor) release version 1.4.0 (#483)
Update all version files and changelog for minor release.
2024-10-23 19:15:14 +02:00
Sabrina Demagny 38508c272e 📝(CHANGELOG) fix modification declaration
One of unreleased modification declaration was
declared in a wrong place
2024-10-23 18:46:04 +02:00
Sabrina Demagny 10a81f14e6 ✏️(mail) fix typo in mailbox creation email
Whitespace missing in french translation after ':'
2024-10-23 17:56:40 +02:00
Nathan Panchout a08689a64d (frontend) add tabs for mail domain page (#466)
Currently, it is complicated to understand the navigation between mailbox
management and role management for an email domain.
This is why we add tabs with explicit naming
2024-10-23 17:45:42 +02:00
Marie PUPO JEAMMET 30229e11f9 🐛(sentry) fix duplicated sentry errors
errors were sent to sentry twice
2024-10-22 18:03:01 +02:00
Sabrina Demagny d11d1f3bd0 🐛(script) improve and fix release script
Use regex to replace version and add missing
frontend update version.
2024-10-22 00:28:08 +02:00
renovate[bot] 6a22169dae ⬆️(dependencies) update python dependencies 2024-10-21 12:22:49 +02:00
Marie PUPO JEAMMET 6e7a6e9d51 🔖(patch) release version 1.3.1
Update all version files and changelog for patch release.
2024-10-18 14:49:56 +02:00
Marie PUPO JEAMMET 95fb476041 🔖(minor) release version 1.3.0
Update all version files and changelog for minor release.
2024-10-18 11:53:36 +02:00
Sabrina Demagny 6b4ea1a2e7 💄(mail) improve mailbox creation email
Remove useless icons, modify text
and improve displaying.
2024-10-15 13:34:03 +02:00
Sabrina Demagny be55d6ea09 📝(CHANGELOG) fix some modifications declaration
Some unreleased declarations was declared in a wrong place
2024-10-15 12:55:27 +02:00
Nathan Panchout 9c9216bb51 (frontend) show version number in footer (#461)
In order to see the version number pushed into production
2024-10-14 16:54:21 +02:00
Sabrina Demagny 017f52a0dc (api) add RELEASE version on config endpoint
Add release version deployed to config endpoint
in order to display release info in La Régie footer.
2024-10-14 14:57:28 +02:00
Quentin BEY d635c484ae 🛂(backend) do not duplicate user when disabled
When a user is disabled and tries to login, we
don't want the user to be duplicated,
the user should not be able to login.

Fixes https://github.com/numerique-gouv/people/issues/455
2024-10-11 16:19:18 +02:00
Marie PUPO JEAMMET 0e48bc0f90 🛂(backend) match email if no existing user matches the sub
Some OIDC identity providers may provide a random value in the "sub"
field instead of an identifying ID. In this case, it may be a good
idea to fallback to matching the user on its email field.
2024-10-11 15:24:53 +02:00
Sabrina Demagny f243a2423f (backend) manage roles on domain admin view
Allow to manage mail domain roles on mail domain admin interface
2024-10-10 16:09:37 +02:00
Marie PUPO JEAMMET 763eb254a8 📝(dimai) update docs on dimail
update README and docs describing interoperability between people and dimail

Co-authored-by: Laurent Bossavit <216452+Morendil@users.noreply.github.com>
2024-10-09 10:59:07 +02:00
Marie PUPO JEAMMET 9b613e63a9 🔧(sentry) reduce trace
we reduce trace to reduce spamming on sentry
2024-10-08 14:35:40 +02:00
Nathan Panchout 6b7f00651f 🐛(frontend) Bug manage access role (#449)
* 🐛(frontend) update access role

Currently, when you click on modify a role, the roles displayed are not the
correct ones. We always took the role of the connected user.
Additionally, there was a warning and a ban on changing roles if you were the
last owner, but it was decided that it was the backend that was throwing the
error and the action was allowed.

* (frontend) adapt tests

We adapt the tests. Remove the check if you are the last owner and use the new
props inside the relevant tests
2024-10-08 10:02:15 +02:00
renovate[bot] fe249c5b6f ⬆️(dependencies) update python dependencies 2024-10-07 17:56:01 +02:00
Marie PUPO JEAMMET 579657afa4 🐛(dimail) add status code in case of unexpected error
add status code in case of unexpected error
2024-10-04 11:32:49 +02:00
Marie PUPO JEAMMET ce21a7552b 🔖(patch) release version 1.2.1
Update all version files and changelog for patch release.
2024-10-03 16:02:00 +02:00
Jacques ROUSSEL 4a63a26135 🔐(secret) bump secret
Bump secret in order to use a new djangoSecretKey
2024-10-03 12:16:28 +02:00
Marie PUPO JEAMMET 8e4472befc 🐛(helm) fix dimail api url
wrong value in dimail api url was causing prod to not work
2024-10-03 12:16:28 +02:00
daproclaima 315a6ab931 (frontend) add mail domain access management
- access management view is ready to use
get, patch and delete requests once backend
is ready. How to create accesses with post
will come later in a future commit.
- update translations and component tests.
- reduce gap between mail domains feature
logo and mail domain name in top banner
2024-10-02 17:19:25 +02:00
daproclaima 2894b9a999 🚚(frontend) reorganize mail domains feature
- separate feature into domain, mailboxes
as a member management feature is arriving in
the mail domains feature
- pages/mail-domains/[slug].tsx becomes
pages/mail-domains/[slug]/index.tsx
2024-10-02 17:19:25 +02:00
Jacques ROUSSEL aea15292ee 🔧(mail) use new scaleway email gateway
We modify multiples things :
* settings.py in order to manage the new way to send email with the
scaleway gateway
* helm template to manage new mandatory secret
* helm configuration for staging/preprod/production
2024-10-02 17:05:17 +02:00
Marie PUPO JEAMMET de46a50e8d 🔖(minor) release version 1.2.0
Update all version files and changelog for minor release.
2024-09-30 17:38:44 +02:00
Sabrina Demagny e6ed3c3be2 (backend) domain accesses delete API
Allow to delete a access for a domain.
2024-09-30 17:09:27 +02:00
daproclaima f04c8bc6aa 🥅(frontend) catch new errors on mailbox creation
- catch errors related to MAIL_PROVISIONING_API_CREDENTIALS
introduced in commit #ba30b1d3eec73718add6585f30c6b7959cb21850.
Intentionally does not parse the error
"Permission denied. Please check your MAIL_PROVISIONING_API_CREDENTIALS."
as it means the user is neither admin or owner of the domain and
should not access the mailbox creation form
- update translations and component tests
2024-09-30 15:31:26 +01:00
Marie PUPO JEAMMET ae05b430db 🚨(pylint) fix linting error introduced by new pylint version
pylint version v3.3.1 added a new error and broke our CI
2024-09-30 13:06:39 +02:00
Marie PUPO JEAMMET c98d173c0a ✏️(makefile) fix typo in makefile, for dimail setup
make boostrap command failed because of wrong naming of
dimail setup command
2024-09-30 13:06:39 +02:00
renovate[bot] dddc281778 ⬆️(dependencies) update python dependencies 2024-09-30 13:06:39 +02:00
Jacques ROUSSEL bb2279b6d5 🐛(argocd) fix job synchronisation issue
Sometime argocd is locked because of immutable fiels on jobs. The
annotation tells argocd to do a replace to avoid this behaviour
2024-09-30 12:51:36 +02:00
Jacques ROUSSEL 5420b20f43 (ci) add helmfile linter
Add a linter to avoid to merge config that breaks argocd sync
2024-09-30 12:51:36 +02:00
Jacques ROUSSEL fbb2accefb 🔧(backend) fix configuration to avoid different ssl warning
Fix following warning messages :
- You have not set a value for the SECURE_HSTS_SECONDS setting.
- Your SECURE_SSL_REDIRECT setting is not set to True.
2024-09-30 11:27:33 +02:00
renovate[bot] 75008d3e9a ⬆️(dependencies) update js dependencies 2024-09-30 11:11:13 +02:00
Sabrina Demagny c4c3e9de96 (backend) domain accesses create API
Allow to create (POST) a new access for a domain.
Role can be change only to a role available and
depending to the authenticated user.
2024-09-27 17:55:15 +02:00
Sabrina Demagny 00816e097c (backend) domain accesses update API
Allow to update (PUT, PATCH) an access.
Role can be change only to a role available
depending to the authenticated user.
2024-09-27 16:09:15 +02:00
daproclaima 976c955126 ️(frontend) update left nav panel
- the HTML semantic needed improvement:
the menu items were button wrapped in a li
wrapped in link.
- update related tests
2024-09-27 15:29:18 +02:00
Marie PUPO JEAMMET 2967f1bff2 🐛(dimail) fix mail notification upon mailbox creation
Link to the webmail was missing from notification email.
This fixes html for link to correctly appear.
2024-09-27 12:20:56 +02:00
Marie PUPO JEAMMET a15d548ac4 🐛(dimail) remove trailing slash to lighten dimail's calls/logs
Remove trailing slash on mailbox creation request
to remove 307 redirects
2024-09-26 20:53:25 +02:00
Marie PUPO JEAMMET 7c6b3307fa (dimail) fix logger response in unauthorized response
a test was broken because of logger not logging errors
2024-09-26 20:53:25 +02:00
Marie PUPO JEAMMET 5ded297df6 (mailbox) send new mailbox confirmation email
send mailbox information upon creating a new mailbox
2024-09-26 20:53:25 +02:00
daproclaima b69ce001c8 (frontend) allow group members filtering
- add title above the list of members
- allow members filtering  with an input
- updates translations and related tests
- add global useDebounce hook to prevent
spamming API with useless requests on
inputs sending requests on value change
- add component and e2e tests
2024-09-26 18:09:31 +02:00
daproclaima c0cd136618 ♻️(frontend) improve CardCreateTeam component
- remove link wrapping cancel button and
tabIndex=-1 to button
2024-09-26 17:20:58 +02:00
daproclaima ee5a785d43 🥅(frontend) improve add member form error handling
- translate known errors, including already existing
group error, and directly display the other ones
- add component tests
- update translations
- add parseAPIError, a reusable function to
catch errors on the whole frontend app

Closes issue #293

♻️(frontend) improve general error catching

- change parseAPIError to make it reusable on all
requests
- update components depending on it
2024-09-26 17:20:58 +02:00
daproclaima 3d7dfa019c ⚗️(frontend) show username on AccountDropDown
- show username instead of "My account"
- udpate translations and tests
2024-09-26 16:32:18 +02:00
renovate[bot] cc9303bc9c ⬆️(dependencies) update js dependencies 2024-09-24 20:37:13 +02:00
Jacques ROUSSEL 34341e6f74 🔒️(helm) fix secret sync precedence
When new secret is added to backend secret, it's not sync at the
beginning of argocd synchronisation and jobs are blocked. Theses new
annotations fix this issue.
2024-09-23 12:52:04 +02:00
Marie PUPO JEAMMET 01abc66e59 (dimail) allow la regie to request a token for another user
allow la regie to request a token for another dimail user,
to better track who created/modified which ressource.
2024-09-20 17:21:31 +02:00
Marie PUPO JEAMMET 55d7e846d8 ♻️(serializers) move dimail calls to serializers
we move all business logic from model to serializer.
all API calls (direct and from front) will keep on triggering
expected 3rd party calls while admin actions will uniquely trigger
modifications in our database.
2024-09-20 14:20:22 +02:00
Marie PUPO JEAMMET 232ea97d87 (dimail) populate dimail local database for dev use
this commit adds a script and 'make' command to populate dimail database
with basic objects: an admin account, a regie account, a domain
and an owner for this domain.
2024-09-19 15:10:35 +02:00
renovate[bot] a7afa68afa ⬆️(dependencies) update next to v14.2.10 [SECURITY] 2024-09-19 10:06:09 +02:00
renovate[bot] 932ffb3bcb ⬆️(dependencies) update js dependencies 2024-09-19 09:54:40 +02:00
Jacques ROUSSEL d0254ce963 🔧(helm) bump secret
Bump secret to use the email provisionning secret
2024-09-18 19:02:34 +02:00
renovate[bot] cd1dcf11d5 ⬆️(dependencies) update python dependencies 2024-09-17 19:01:23 +02:00
Marie PUPO JEAMMET 59468aaa12 🍱(dimail) embark dimail-api as container
Embark a dimail-api container, automatically fetched from
their repository, to ensure our "bridge" to dimail-api
is up-to-date when developing.
2024-09-17 18:34:39 +02:00
Sabrina Demagny dd8bd2a89b (backend) domain accesses list API
Add an endpoint to list all accesses created for a domain
Return all roles available to set for each access depending to
the authenticated user.
2024-09-17 17:13:46 +02:00
rouja cc86a3bd61 🔧(helm) add marie key to dev sops secret (#394)
Marie's key was accidentally removed in last commit.
Add her key and restore .sops.yaml file, to easily add keys
for local dev secrets decryption/encryption.
2024-09-11 16:59:22 +02:00
Marie PUPO JEAMMET 7f31a2b820 🔖(minor) release version 1.1.0
Update all version files and changelog for minor release.
2024-09-10 17:20:05 +02:00
Jacques ROUSSEL aaca8819b3 🔧(helm) fix mail provisioning env
I forgot to use the new variable on the deployment.
2024-09-10 16:50:14 +02:00
Sabrina Demagny 77cc64a6c7 (release) add python script to prepare release
Change versions, update changelog and create branch and commit
to submit release informations.
Give following instructions to do after.
2024-09-10 15:30:30 +02:00
Marie PUPO JEAMMET aaad48480a (dimail) fix tests still waiting for domain.secret
For unknown reasons, these tests were forgotten and are still
refering to this 'secret' field, removed in last commit.
2024-09-10 15:29:19 +02:00
Marie PUPO JEAMMET 00dafd4b15 ♻️(dimail) separate headers request from mailbox request
I want to separate headers request form mailbox request,
as we were previously catching the same errors twice.
It should be clearer now.
2024-09-10 15:29:19 +02:00
Jacques ROUSSEL 864702d0ee 🔧(helm) add secret for email provisionning
Add email provisionning secret to be abble to provision email
2024-09-09 18:18:00 +02:00
Marie PUPO JEAMMET 29904ef7b6 (tests) update tests to look for dimail secret in settings
Update back-end tests to match 'secret' field being moved to settings.
2024-09-09 18:18:00 +02:00
Marie PUPO JEAMMET ba30b1d3ee 🗃️(models) remove 'secret' field from mailbox model
We remove 'secret' field, as it won't be of use in interactions
between la Régie and dimail. Régie credentials will be stored and used
as project variable.
2024-09-09 18:18:00 +02:00
renovate[bot] 9503b073b6 ⬆️(dependencies) update python dependencies 2024-09-09 15:01:53 +02:00
daproclaima e4aed82ff2 🥅(frontend) improve error catching in forms
- rename CreateMailboxForm into ModalCreateMailbox,
and useCreateMailDomain into useAddMailDomain
- use useAPIError hook in ModalCreateMailbox.tsx and ModalAddMailDomain
- update translations and tests (include removal of e2e test able
to be asserted by component tests)
2024-09-09 12:43:29 +02:00
daproclaima 25898bbb64 🥅(frontend) handle api errors
- add hook to handle api errors.
- add related component tests
2024-09-09 12:43:29 +02:00
daproclaima b5d8e92d1e 🐛(frontend) fix mail domain creation form
- allow to submit form by pressing "Enter" key
- force focus on form when form is submited
but is invalid
- add error 500 handling
- update related e2e tests
2024-09-09 12:43:29 +02:00
Marie PUPO JEAMMET 237d64b4c5 ♻️(dimail) refacto to better handle 500 errors from dimail
simple refacto to catch all 500 errors, including when
asking for new token.
2024-09-09 12:24:48 +02:00
daproclaima 0d157d3f2b ️(frontend) improve keyboard navigation on modals
- create a temporary Modal component to apply it
a function tracking document update and set
modal elements we want to ignore a tabindex=-1.
- add component tests
- temporary fix. Better to apply them on
cunningham directly
2024-09-09 11:58:37 +02:00
daproclaima d291e55a9e 🐛(frontend) fix mail domain addition form
- remove link wrapping cancel button
2024-09-09 11:58:37 +02:00
daproclaima e7aebfe59e 🐛(frontend) keyboard navigation language picker
- add temporary fix to language picker to
ignore select on keyboard navigation. Needs
to be fixed directly in Cunningham Select
- update related e2e test
2024-09-09 11:58:37 +02:00
daproclaima bd6cd59df6 💬(frontend) change add mail domain text
- update translations and tests
2024-09-09 11:41:34 +02:00
daproclaima 874ce18134 💬(frontend) fix group member removal text
- update FR translation
2024-09-09 11:41:34 +02:00
Marie PUPO JEAMMET 4fe74733a5 📈(monitoring) configure sentry dsn
configure sentry dsn to monitor errors in sentry
2024-09-05 16:16:05 +02:00
Marie PUPO JEAMMET 4b47f80cab 🚨(tests) fix obsolete code warnings
- in docker compose, remove obsolete 'version' field
- in django, replace obsolete CheckConstraints 'check' field by 'condition'
2024-09-05 14:57:32 +02:00
Marie PUPO JEAMMET ba631fafb9 🐛(dimail) improve handling of dimail errors on failed mailbox creation
dimail is called twice when creating a mailbox (once for the token,
and once for the post on mailbox endpoint). we want to clarify
the status_codes and messages of each error to inform user and ease debug
2024-09-05 14:57:32 +02:00
renovate[bot] ce15e8a3ed ⬆️(dependencies) update python dependencies 2024-09-05 12:00:53 +02:00
Marie PUPO JEAMMET 55dc342a8b 🔨(demo) add domains creation to demo
Add domains creation to "make demo" rule. Update related test.
2024-09-03 16:11:23 +02:00
renovate[bot] 05c8f636dd ⬆️(dependencies) update js dependencies 2024-09-02 09:41:24 +02:00
Sabrina Demagny 675ba4b557 🔖(patch) release version 1.0.2
Update all version files and changelog for release patch.
2024-08-30 18:03:26 +02:00
Marie PUPO JEAMMET f5c7abcd20 🗃️(mailboxes) migrate local part field modification
"+" character was removed from valid character for mailbox creation
this commit adds migration file for database to be up-to-date
2024-08-30 14:35:58 +02:00
lebaudantoine 8c54e701c1 🔧(helm) configure resource server in staging
Allow desk-staging app to interact with AgentConnect integration env
to introspect a received access token.

Other environment (pre-prod and production) will be configured when
at least one interconnection with a service provider has been
validated.
2024-08-30 13:12:25 +02:00
Anthony LC ff2cbe3aed 🔥(CI) remove crowdin from CI workflow
Pushing to crowdin from the workflow has some side
effects, if 2 branches are pushing to crowdin it
can cause conflicts and delete translations on
Crowdin side.
Better to push to crowdin manually to keep good
control over the translations.
2024-08-30 10:42:43 +02:00
Anthony LC 7f3f25c61d ⬆️(i18n) i18next-parser to 9.0.2
i18next-parser had a compatibility issue with
a dependency (cheerio). The last version
fixed this issue, plus fixed another issue
about a configuration problem.
We can now remove it from the renovate ignore list.
2024-08-30 10:42:43 +02:00
Anthony LC bd36983e3c (frontend) add @typescript-eslint/parser
In order to work correctly
@typescript-eslint/eslint-plugin requires
@typescript-eslint/parser to be installed as well.
We fixed the linting issues related to the
upgrade.
2024-08-30 10:42:43 +02:00
renovate[bot] e8cc6a6f23 ⬆️(dependencies) update js dependencies 2024-08-30 10:42:43 +02:00
lebaudantoine 9adb2d4cf4 📝(backend) draft a minimal documentation on resource server
I've committed few of my notes for my future myself, helping me to
run locally the stack. These notes are raw, I'll be more than happy
to refine them when I got sufficient time. Please feel free to ping
me if you have any question.
2024-08-29 11:39:08 +02:00
lebaudantoine bb5058c478 🔊(backend) enable debug logs in development
Enhance developer experience, unmuting some debug information,
that weren't taken into account.
2024-08-29 11:39:08 +02:00
lebaudantoine 78818ba541 🩹(backend) enable resource server authentication if properly configured
Tests are missing, let's ship it, I'll open an issue.

Without such protection, the whole app would crash if the resource server is
not configured. The fallback backend would return an appropriate error to
the client if the resource server is improperly configured.
2024-08-29 11:39:08 +02:00
lebaudantoine f1a2b7c603 (backend) authenticate requests using an access token issued by AC
Overload mozilla-django-oidc class to support an authentication method
with the resource server backend.

This enables any route of the API to be called with an access token
issued by Agent Connect.
2024-08-29 11:39:08 +02:00
lebaudantoine 5634a7f390 (backend) add resource server backend
Why:

Many services in La Suite rely on Agent Connect to authenticate their users.
Delegating  authentication to Agent Connect is highly beneficial. With a central
party (Agent Connect)  handling user authentication, our services can seamlessly
communicate with each other.  Our backend must be able to receive and verify
access tokens issued by Agent Connect.

Additionally, it should ensure that the resource owner has granted permission
for our  data to the service provider transmitting the access token.

How:

Our backend needs to verify access tokens by introspecting them. This involves
requesting the Authorization Server to validate the access token received in
the authentication header. The Authorization Server validates the token's
integrity, provides authentication and authorization information about
the user currently logged into the service provider requesting data from
the resource server.

The data returned by the Authorization Server to the resource server
is encrypted and signed. To encrypt the introspection token, the Authorization
Server retrieves the resource server's public key from
the new ‘/jwks’ endpoint.

Encryption parameters, such as algorithm and encoding, are configured on
the resource server. Ensure that these parameters match between
the Authorization Server and the resource server.

The resource server verifies the token signature using the Authorization
Server's public key, exposed through its `/jwks` endpoint. Make sure
the signature algorithms match between both servers. Finally, introspection
token claims are verified to adhere to good  practices for handling JWTs,
including checks on issuer, audience, and expiration time.

The introspection token contains a subject (`sub`). The resource server uses
this subject to retrieve the requested database user, compatible
with both pairwise and public subjects.

Important:

Agent Connect does not follow RFC 7662 but uses a draft RFC that adds security
(signing/encryption) to the initial specification. Refer to the "References"
section for more information.

References:

The initial RFC describing token introspection is RFC 7662 "OAuth 2.0 Token
Introspection". However, this RFC specifies that the introspection
response is a plain JSON object.

In eGovernment applications, our resource server requires stronger assurance
that the Authorization Server issued the token introspection response.

France Connect's team implemented a stronger version of the spec, returning
a signed and encrypted token  introspection response. This version is still
a draft, available under:

"draft-ietf-oauth-jwt-introspection-response".
2024-08-29 11:39:08 +02:00
lebaudantoine 9c05167d80 (backend) introduce an authorization server client
In OAuth 2.0, the Authorization Server is equivalent to the OIDC provider.

The Authorization Server exposes endpoints for token introspection and JWKS.
I’ve created a client to easily interact with the Authorization Server,
while doing the token introspection in our resource server.

Token introspection will be explained in upcoming commits.

The current OIDC library used in the project doesn’t offer token introspection,
leading to redundancy in the code handling some OIDC/OAuth2 flows.

This overlap makes the code bulky. My goal is to quickly deliver a working
PoC for the resource server, with plans to refactor in the longer run.

Please feel free to provide feedback on the class design.
2024-08-29 11:39:08 +02:00
lebaudantoine 21371dbd1b (backend) add a '/jwks' endpoint
Introduce a new endpoint, /jwks, which returns a JSON Web Key Set (JWKS).
This set of public crypto keys will be used by external parties to encrypt
data intended for our backend. In the context of the resource server, this key
will be used by the authorization server to encrypt the introspection response.

The current implementation exposes a single public key, with the private key
configurable in the app settings. The private key is represented as a string.
For enhanced security, we might prefer to store this data in a .pem file
excluded from version control.

A few parameters for this key, such as its type and encoding, are configurable
in the settings.

A critique of the current design is its lack of extensibility.
If we decide to offer more than one encryption method, this view will require
refactoring.

Additionally, the current implementation is tightly coupled with joserfc.

This lays the foundation for further improvements.

Please note, this endpoint only public components of the key, there is no
chance for any secret leaking.
2024-08-29 11:39:08 +02:00
lebaudantoine b40aefc505 ✏️(backend) fix minor typo
Found and fixed a minor typo. Nit-picking!
2024-08-29 11:39:08 +02:00
lebaudantoine 591b3eedff 🏗️(backend) create a new python package for the resource server
Encapsulate all Resource Server (RS) sources in a dedicated python package.

Resource server belongs to the Oauth2 ecosystem, please find informations
here https://www.oauth.com/oauth2-servers/the-resource-server/
2024-08-29 11:39:08 +02:00
lebaudantoine 09cb7ff6f1 (backend) add a JOSE dependency
We will add a JWKs endpoint to the application
and manipulate signed/encrypted Json Web Token (JWT).

Project lacks tooling for JSON Object Signing and Encryption (JOSE)
manipulations. After a quick benchmark, 'joserfc' has been chosen
as the dependency to add.

joserfc is a Python library that provides a comprehensive
implementation of several essential JOSE standards.

Please find the benchmark:

- Cryptography: Although using only cryptography is feasible, its
  interface/API is not as user-friendly.

- pyjwt: While pyjwt is popular, it lacks support for JWK and JWE objects,
  which are essential for the requirements.

- python-jose: The latest release of python-jose was in 2021, and the
  project seems less active compared to other alternatives.

- Authlib: Authlib is the second most popular library after pyjwt and seems
  modern with an active community. However, the parts relevant to the use case
  were extracted into a relatively new package named joserfc.

- joserfc: Although joserfc has fewer stars compared to Authlib, it was
  extracted from Authlib, which has more than 4k stars, indicating a solid
  foundation.

While the low star count of joserfc might raise concerns about its stability, it
is believed to be worth considering its addition. Adding Authlib and refactoring
later, once they finish migrating to joserfc, is also a possibility
2024-08-29 11:39:08 +02:00
Marie PUPO JEAMMET 87966fa062 🐛(backend) fix dependencies conflicts
Upgrading Django to 5.1 created a severe issue, breaking
mail template-associated features.

The issue originated from the third party 'easy_thumbnail'.
Please refer to the issue #641 on Django's repo. This is
the suggested workaround by @Miketsukami.
2024-08-28 12:21:02 +02:00
renovate[bot] e4dd3395bb ⬆️(dependencies) update python dependencies 2024-08-28 12:21:02 +02:00
Marie PUPO JEAMMET 93681b0030 (mailboxes) remove '+' from valid special caracters
We previously accepted '+' as a special caracter during mailbox creation.
We now remove it, as this caracter has a very special meaning and it wouldn't
make sense to create a mail using it.
2024-08-28 11:17:19 +02:00
Marie PUPO JEAMMET e04a994d37 👽️(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!
2024-08-28 11:17:19 +02:00
Sabrina Demagny ba46d7de54 (users) improve user display on admin users list
If user email exists, display it instead of sub to identify
users in admin view list.
2024-08-28 11:00:34 +02:00
Sabrina Demagny b79b4b1853 (domains) manage domain roles on user admin view
Allow to manage mail domain roles on user admin interface
2024-08-28 11:00:34 +02:00
Laurent Bossavit e3f8633931 (test) fix flaky search test
By making this email address invariant, we remove failures due to FactoryBoy's
random address being considered as a match to our test query
(and hence returning unexpected number of matches).
2024-08-28 10:47:19 +02:00
Anthony LC b84e8b89f7 🔧(helm) deactivate teams feature on productions env
Teams feature is not ready for production yet,
so we need to deactivate it on productions environment.
preprod should be a copy of production,
so we need to deactivate it on preprod too.
2024-08-21 15:13:12 +02:00
Anthony LC 32889b9e8c ♻️(frontend) replace env NEXT_PUBLIC_FEATURE_TEAM
NEXT_PUBLIC_FEATURE_TEAM is a buid-time env
variable, it is not easy to overload it per
environment.
We will use the config endpoint to get the
feature flag at runtime.
To do so, we are using the ConfigStore.
2024-08-21 15:13:12 +02:00
Anthony LC 75647fe289 (frontend) add config provider
Add a ConfigProvider to the frontend to provide
configuration to the app.
The configuration is loaded from the config
endpoint and stored in a zustand store.
2024-08-21 15:13:12 +02:00
Anthony LC 03bfef6061 (backend) add public endpoint /api/v1.0/config/
Add public endpoint /api/v1.0/config/ to
share some public configuration values
with the frontend.
2024-08-21 15:13:12 +02:00
daproclaima 85c789bb1a 🔖(patch) patch release to 1.0.1
- upgrade semver for all package.json, env.d files,
and pyproject.toml
- update CHANGELOG.md
2024-08-20 10:03:11 +02:00
daproclaima 049d8695be ️(frontend) updates links
- remove buttons inside links in panels and
teams index
- update component and e2e tests
2024-08-19 16:04:57 +02:00
daproclaima 49c238155c (frontend) user can add mail domain
- user can add an externally created mail domain
from UI and see the mail domain status on mail
domain page and left panel links.
- user can not create mailboxes to domain if mail
domain status is not equal to `enabled`
- update related tests and translations
2024-08-19 16:04:57 +02:00
daproclaima b79725acbe 💬(frontend) change text in mail domains list
- use more meaningful message
- update translations and e2e tests
2024-08-19 16:04:57 +02:00
Marie PUPO JEAMMET 439ddb9d4a 🔖(major) major release to 1.0.0
🎉! For changelog, see changelog.md
2024-08-09 15:21:42 +02:00
Sabrina Demagny a7a923e790 (mailboxes) manage bad secret sent to dimail API
- manage 403 returned by dimail API when mail domain secret is not valid
- improve some tests
- improve MailboxFactory to mock success for dimail API POST call
- override 403.html to return a nice failing error in django admin
- an error message is displayed on mailbox creation form of frontend
2024-08-09 13:37:20 +02:00
Marie PUPO JEAMMET 5ed63fc091 (test) add test list mailboxes non existing domain
Test that API raises a 404 when trying to list mailboxes
of a domain that does not exist.
2024-08-09 13:37:20 +02:00
Marie PUPO JEAMMET f55cb3a813 (mailboxes) add mail provisioning api integration
We want people to create new mailboxes in La Régie.
This commit adds integration with intermediary dimail-api,
which will in turn send our email creation request to Open-Xchange.
2024-08-09 13:37:20 +02:00
Marie PUPO JEAMMET 2c82f38c59 🗃️(domains) add "secret" field to domains
add a "secret" field to domain model. This secret will be used as
password in mail provisioning API.
2024-08-09 13:37:20 +02:00
Sabrina Demagny 8963f0bb3d (mail) add status on domain create or retrieve API
to display status on frontend
2024-08-08 23:47:49 +02:00
Anthony LC 733a1d8861 🔥(frontend) remove temporarily team feature
We want to make a first realease, but the
team feature is not ready yet.
So we will hide it for now by hiding the menu.
We will still let the feature in dev environment.
2024-08-08 16:29:06 +02:00
daproclaima 7916f7d7d0 (frontend) show names in mailbox table
- show a concatenation of first and last names
for each row in mailbox table
- update related e2e tests
2024-08-08 13:53:07 +02:00
daproclaima 45dbdd6c4c (frontend) restrict mailbox creation
- update mailbox creation feature by introducing the use of
new mail domain ability field to hide or show
mailbox creation button
- update related e2e tests
2024-08-08 13:53:07 +02:00
daproclaima 14deca13f4 🚸(frontend) improve screen reading navigation
- add aria-hidden and empty alt attributes for screen readers
to ignore decorative svg and images.
- remove icon from input field used to name a group
- update translations
- update related e2e and components tests
2024-08-08 12:16:20 +02:00
daproclaima 72340db74c 💬(frontend) update texts
- change message showed in mailbox list when none exist
- change CTA button text for group management modals
- fix 404 page title
- update translations
- update related e2e tests
2024-08-08 12:16:20 +02:00
renovate[bot] d812197381 ⬆️(dependencies) update django to v5.0.8 [SECURITY] 2024-08-08 11:41:14 +02:00
Sabrina Demagny c00c59b301 (mail) add first_name and last_name for Mailbox
Mail provisioning API needs a full name to create a new mailbox.
2024-08-07 15:03:09 +02:00
Marie PUPO JEAMMET 402e73582c (tests) improve tests for mailbox api
Regroup mailbox-related tests
+ add test 404 when trying to retrive a domain that doesn't exist
+ use enabled domains on tests
2024-08-07 10:23:49 +02:00
Sabrina Demagny b637774179 (mail) manage mailboxes permissions
Manage create and list permissions for all roles.
2024-08-06 16:00:00 +02:00
Marie PUPO JEAMMET 87e7d3e0b1 🚚(swagger) move swagger under /api/
Swagger was under /v1.0/swagger.
I just wanna move it under /api/ where the rest of the API is.
2024-08-05 16:49:27 +02:00
Sabrina Demagny eba9fb2d09 🚸(models) use a viewer role for MailDomainAccess
Rename member role to viewer role for MailDomainAccess.
A viewer is only allowed to see list of mailboxes
created for a domain. It makes more sense to name it viewer.
2024-08-05 15:05:15 +02:00
daproclaima e03ecb2d77 ️(frontend) change panel text color
- change text color displayed when panel of teams or mail domains is empty
to create more contrast between text and background colors
2024-08-05 12:42:13 +02:00
daproclaima 7e03d33be0 🚸(frontend) improve keyboard navigation
- add css rules to highlight focused-visible navigable elements
- update drop down components to make it keyboard navigable
- add e2e keyboard navigation tests asserting it navigates through
all focusable elements from top to bottom on groups index view
when one group exists
2024-08-05 12:42:13 +02:00
renovate[bot] 779c7d1e0e ⬆️(dependencies) update python dependencies 2024-08-05 11:05:18 +02:00
Sabrina Demagny b1e1de0269 🧑‍💻(backend) do not allow to delete a domain
At the moment a domain cannot be deleted.
We will be able to delete only pending domains and
simply turn to disabled an enabled domain.
2024-08-02 17:43:16 +02:00
Sabrina Demagny 63dee08be5 🧑‍💻(backend) add missing test on domain
Check the mail domain status after creation;
2024-08-02 17:43:16 +02:00
Anthony LC 582e3f5a05 (github) fix e2e workflow
An update to ubuntu made the command "docker-compose" not
working anymore. This commit fixes the issue.
2024-08-02 17:23:02 +02:00
Marie PUPO JEAMMET df59bfd1ee ⚰️(dead) remove obsolete file
remove obsolete file ... i think ?
It seems setup.cfg has been replaced by pyproject.toml
2024-08-02 12:34:02 +02:00
Marie PUPO JEAMMET c26786a107 🩺(coverage) add config and make rule to compute coverage
Configure pytest-cov settings in pyproject.toml and add make rule
to compute test coverage.
2024-08-02 12:34:02 +02:00
Anthony LC ca179b8811 ⬇️(frontend) downgrade @typescript-eslint/eslint-plugin to 7.13.1
@typescript-eslint/eslint-plugin released the
version 8, but it is causing some issues
(@typescript-eslint/no-duplicate-enum-values).
We downgrade it to 7.13.1 in waiting for a fix.
2024-08-01 10:22:10 +02:00
Anthony LC b413d8a915 ⬇️(frontend) downgrading fetch-mock to 9.11.0
fetch-mock released the version 10, but it is
causing some issues with jest because of
esm support.
2024-08-01 10:22:10 +02:00
renovate[bot] a07be7ecd7 ⬆️(dependencies) update js dependencies 2024-08-01 10:22:10 +02:00
Sabrina Demagny ab54d5af8f (backend) allow to filter member on team access endpoint
Filter member by name...
2024-07-31 16:01:32 +02:00
renovate[bot] 958f48f9e8 ⬆️(dependencies) update python dependencies 2024-07-31 12:22:42 +02:00
Marie PUPO JEAMMET 94b0c27775 📝(readme) update admin credentials in README
README was not correctly updated after last major modif to the admin auth,
resulting in confusion for users trying to log-in with email instead of sub.
2024-07-31 11:41:33 +02:00
renovate[bot] 953eefcb66 ⬆️(dependencies) update python dependencies 2024-07-22 14:34:47 +02:00
renovate[bot] 4f173c65d5 ⬆️(dependencies) update sentry-sdk to v2.8.0 [SECURITY] 2024-07-19 15:49:47 +02:00
renovate[bot] 99d3de6833 ⬆️(dependencies) update requests to v2.32.2 [SECURITY] 2024-07-19 15:15:58 +02:00
daproclaima e0000ca89c 💄(frontend) change elements positions in mailbox creation form
- remove icon on top of mailbox creation form
- change some text positions
- fix fields error style on hover
- update form field names translations
- update related e2e tests
2024-07-16 15:26:59 +02:00
daproclaima 32e6602dda 🚸(frontend) improve mailbox creation validations and error handling
- replace known error causes returned by the API on unsuccessful mailbox
creation requests by meaningful interpolated message shown above the
form
- strengthen form validation rules to be identical as those of
the api endpoint to prevent emitting invalid requests
- designate which form fields are mandatory for accessiblity
- update texts for better ux writting, and their translations
- fix css style input errors
- update related e2e tests.
2024-07-16 15:26:59 +02:00
renovate[bot] cda4373544 ⬆️(dependencies) update django to v5.0.7 [SECURITY] 2024-07-12 19:23:55 +02:00
Sabrina Demagny 8d7614c512 (models) add TeamAccess models on admin view
Declare TeamAccessAdmin
2024-07-10 16:40:48 +02:00
Sabrina Demagny 955a3dd226 (models) add MailDomain status
Add some status to allow to create mailboxes only for an active domain
2024-07-10 16:17:42 +02:00
daproclaima d69861c148 🔥(frontend) remove use of phone number data for mailbox creation
Remove phone number field from mailbox creation form and requests
to comply with GPDR as it is not an information we need to
collect for creating a mailbox. Deletes translations about phone
number field in mailbox creation form. Updates related e2e tests.
2024-07-04 11:31:52 +02:00
Marie PUPO JEAMMET 66300aca66 🧑‍💻(models) improve user str representation
Improve user model str representation to display name or email
if provided. Otherwise, returns sub as last resort.
2024-07-03 17:16:22 +02:00
daproclaima 2598f3649a (e2e) check default lang attribut of html tag
Asserts that default lang attribute of html tag
matches with the language used by default in
browser for supported languages.
2024-07-02 09:19:34 +02:00
daproclaima d3589dfca1 (e2e) check lang attribute on html tag updates
Asserts that lang attribute of html tag updates according to
language chosen by user.
2024-07-02 09:19:34 +02:00
daproclaima dfb5394310 ️(frontend) update html lang on language change
Performs lang attribute update on html tag on every language change.
By default the attribute value uses the i18n.language value.
2024-07-02 09:19:34 +02:00
Anthony LC bea23cc6e9 💬(frontend) change app name to Regie
The app was named Equipes, it is now Régie.
2024-07-01 17:16:47 +02:00
Anthony LC 7c36f1e775 💬(frontend) change text logo Marianne
Change the text of the logo Marianne.
It was "Devise" and now it's "République Francaise".
2024-07-01 17:16:47 +02:00
Anthony LC 8dcd6d5bb8 💄(frontend) fix flickering on datagrid sorting member
The datagrid was flickering when sorting the member list.
This was due to the fact that the list was getting
empty and then filled again with the sorted list
causing the flickering.
2024-07-01 16:56:34 +02:00
Anthony LC 5c87bd74cd 🏷️(frontend) adapt ordering name
Some ordering names changed with a prefix "user__".
We adapt the ordering name in the
frontend to match the backend.
2024-07-01 16:56:34 +02:00
Anthony LC a400c12037 🚚(frontend) change teams feature architecture
Changes the teams feature architecture, centralizing
all the teams-related features inside a teams folder.
2024-07-01 15:18:18 +02:00
Anthony LC 4d1aafe0d9 🐛(helm) fix createsuperuser command
The createsuperuser command changes recently.
We update the command to reflect the changes.
2024-06-28 11:37:56 +02:00
Anthony LC 0e5cbb1fc8 🐛(app-desk) force redirect on mail-domains/[slug]
When we use the static mode, Next.js want that we
build our mail-domains pages at build time.
But we can't do that because users can create a
mail at runtime.

So we redirect thanks to ngnix when we see that
a mail page is not found.
2024-06-28 10:06:26 +02:00
Anthony LC 56df81ef84 🐛(app-desk) force redirect on teams/[id]
When we use the static mode, Next.js want that we
build our team pages at build time. But we can't do that
because users can create a team at runtime.

So we redirect thanks to ngnix when we see that
a team page is not found.
2024-06-28 10:06:26 +02:00
Anthony LC 5c10ed32d5 🔧(app-desk) trailingSlash options when build
Add trailingSlash options to next.config.js
to be able to reach directly a page without adding
".html" at the end.
2024-06-28 10:06:26 +02:00
renovate[bot] ed24beb0f6 ⬆️(dependencies) update djangorestframework to v3.15.2 [SECURITY] 2024-06-27 18:17:46 +02:00
renovate[bot] 928fed9ac7 ⬆️(dependencies) update python dependencies 2024-06-27 18:08:39 +02:00
Samuel Paccoud - DINUM 2ec292bb91 ♻️(models) remove multiple identities
Multiple identities were complicating this project's code.
We moved the management of multiple identities to our
OIDC provider.
2024-06-27 17:45:23 +02:00
Anthony LC 79330015e0 ✏️(frontend) change "mention légale" to "mentions légales"
Change "mention légale" to "mentions légales".
2024-06-27 14:02:44 +02:00
Anthony LC d05bc60f5e 🧑‍💻(i18n) run prettier on format-deploy
The command format-deploy import a new json
from crowdin, but it is not formatted. This
commit run prettier on the file after the import
to format it.
2024-06-26 17:26:41 +02:00
Anthony LC c7861c6ad4 🐛(i18n) fix key that contain colon
Keys that contains colon where not being
translated correctly. This was due to the
colon being used as a separator for the
key and the value. This was fixed by
replacing the colon with a different
character that is not used in the key
or the value.
2024-06-26 17:26:41 +02:00
Anthony LC 952bea369e 🌐(frontend) add french translations
- Add french translations for the footer
- Add french translations for the mail part
2024-06-26 17:26:41 +02:00
Anthony LC 980c6ee1a4 🚸(app-desk) footer legales pages
- Add legales pages.
- Add links to the footer for the new pages.

Legales pages are based from
https://lasuite.numerique.gouv.fr/
2024-06-26 17:26:41 +02:00
Anthony LC 51c4a29751 ♻️(app-desk) change header html structure
Change a bit the html structure of the header
component to be more aligned.
Logo linked to homepage.
2024-06-26 17:26:41 +02:00
Anthony LC 01d72466a6 (app-desk) add footer
Add footer to the desk app.
2024-06-26 17:26:41 +02:00
Marie PUPO JEAMMET 19c36eafde (tests) fix tests after adding slugs to domains
- slug readonly on admin
- fix test to expect slug in payload, when retrieving a domain
2024-06-25 12:37:34 +02:00
daproclaima 93d4abee58 (e2e) update mail domains tests
Updates tests to use mail domain slug instead of id.
2024-06-25 12:37:34 +02:00
Sabrina Demagny bb3403f10f (mailbox_manager) add slug to MailDomain serializer
add missing field to MailDomain serializer after commit b4bafb6
2024-06-25 12:37:34 +02:00
daproclaima 0da30eb2e1 🚧(app-regie) use mail domain slug in mail domains feature
Stop using mailDomain.id in frontend navigation and mail-domains/
requests. Instead, uses mailDomain slug.
2024-06-25 12:37:34 +02:00
Anthony LC f70604df72 🚚(helm) move secret to desk/templates
With the recent changes to the helm chart,
the secrets.yaml file was not found by
Tilt anymore. This commit moves the file
to the correct location.
2024-06-25 11:36:09 +02:00
Anthony LC e75c8d49b3 👷(CI) add production tag to deploy workflow
Add `production` tag to deploy workflow.
Every tag production will trigger
the deploy workflow to production environment.
2024-06-25 11:36:09 +02:00
Anthony LC 4823c8d9dc 👷(helm) prod configuration
Add the prod configuration to the helm chart.
2024-06-25 11:36:09 +02:00
328 changed files with 17513 additions and 5654 deletions
+1
View File
@@ -4,6 +4,7 @@ on:
push:
tags:
- 'preprod'
- 'production'
jobs:
-1
View File
@@ -5,7 +5,6 @@ on:
push:
branches:
- 'main'
- 'fix/warning-backend'
tags:
- 'v*'
pull_request:
+22
View File
@@ -0,0 +1,22 @@
name: Helmfile lint
run-name: Helmfile lint
on:
pull_request:
branches:
- 'main'
jobs:
helmfile-lint:
runs-on: ubuntu-latest
container:
image: ghcr.io/helmfile/helmfile:latest
steps:
-
uses: numerique-gouv/action-helmfile-lint@main
with:
app-id: ${{ secrets.APP_ID }}
age-key: ${{ secrets.SOPS_PRIVATE }}
private-key: ${{ secrets.PRIVATE_KEY }}
helmfile-src: "src/helm"
repositories: "people,secrets"
+18 -80
View File
@@ -150,7 +150,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set services env variables
run: |
make create-env-files
@@ -175,15 +175,29 @@ jobs:
with:
path: src/frontend/apps/desk/out/
key: build-front-${{ github.run_id }}
# Pull the latest image to build, and avoid caching pull-only images.
# (docker pull is faster than caching in most cases.)
- run: docker compose pull
# In this step, this action saves a list of existing images,
# the cache is created without them in the post run.
# It also restores the cache if it exists.
- uses: satackey/action-docker-layer-caching@v0.0.11
# Ignore the failure of a step and avoid terminating the job.
continue-on-error: true
- name: Build and Start Docker Servers
env:
DOCKER_BUILDKIT: 1
COMPOSE_DOCKER_CLI_BUILD: 1
run: |
docker-compose build --pull --build-arg BUILDKIT_INLINE_CACHE=1
docker compose build --build-arg BUILDKIT_INLINE_CACHE=1
make run
# Finally, "Post Run satackey/action-docker-layer-caching@v0.0.11",
# which is the process of saving the cache, will be executed.
- name: Apply DRF migrations
run: |
make migrate
@@ -306,79 +320,3 @@ jobs:
run: python manage.py compilemessages
- name: Run tests
run: ~/.local/bin/pytest -n 2
i18n-crowdin:
runs-on: ubuntu-latest
steps:
-
uses: actions/create-github-app-token@v1
id: app-token
with:
app-id: ${{ secrets.APP_ID }}
private-key: ${{ secrets.PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
repositories: "people,secrets"
-
name: Checkout repository
uses: actions/checkout@v2
with:
submodules: recursive
token: ${{ steps.app-token.outputs.token }}
- name: Install gettext (required to make messages)
run: |
sudo apt-get update
sudo apt-get install -y gettext
- name: Install Python
uses: actions/setup-python@v5
with:
python-version: '3.10'
- name: Install development dependencies
working-directory: src/backend
run: pip install --user .[dev]
- name: Generate the translation base file
run: ~/.local/bin/django-admin makemessages --keep-pot --all
-
name: Load sops secrets
uses: rouja/actions-sops@main
with:
secret-file: secrets/numerique-gouv/people/secrets.enc.env
age-key: ${{ secrets.SOPS_PRIVATE }}
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18.x'
cache: 'yarn'
cache-dependency-path: src/frontend/yarn.lock
- name: Install dependencies
run: cd src/frontend/ && yarn install --frozen-lockfile
- name: Download sources from Crowdin to stay synchronized
run: |
docker run \
--rm \
-e CROWDIN_API_TOKEN=$CROWDIN_API_TOKEN \
-e CROWDIN_PROJECT_ID=$CROWDIN_PROJECT_ID \
-e CROWDIN_BASE_PATH=$CROWDIN_BASE_PATH \
-v "${{ github.workspace }}:/app" \
crowdin/cli:3.16.0 \
crowdin download sources -c /app/crowdin/config.yml
- name: Extract the frontend translation
run: make frontend-i18n-extract
- name: Upload files to Crowdin
run: |
docker run \
--rm \
-e CROWDIN_API_TOKEN=$CROWDIN_API_TOKEN \
-e CROWDIN_PROJECT_ID=$CROWDIN_PROJECT_ID \
-e CROWDIN_BASE_PATH=$CROWDIN_BASE_PATH \
-v "${{ github.workspace }}:/app" \
crowdin/cli:3.16.0 \
crowdin upload sources -c /app/crowdin/config.yml
+1
View File
@@ -66,6 +66,7 @@ src/frontend/tsclient
# Test & lint
.coverage
coverage.json
.pylint.d
.pytest_cache
db.sqlite3
+10
View File
@@ -0,0 +1,10 @@
creation_rules:
- path_regex: ./*
key_groups:
- age:
- age15fyxdwmg5mvldtqqus87xspuws2u0cpvwheehrtvkexj4tnsqqysw6re2x # jacques
- age16hnlml8yv4ynwy0seer57g8qww075crd0g7nsundz3pj4wk7m3vqftszg7 # github-repo
- age1plkp8td6zzfcavjusmsfrlk54t9vn8jjxm8zaz7cmnr7kzl2nfnsd54hwg # Anthony Le-Courric
- age12g6f5fse25tgrwweleh4jls3qs52hey2edh759smulwmk5lnzadslu2cp3 # Antoine Lebaud
- age1hnhuzj96ktkhpyygvmz0x9h8mfvssz7ss6emmukags644mdhf4msajk93r # Samuel Paccoud
- age1tl80n23wq6zxegupwn70ew0yp225ua5v4dk800x7g2w6pvlxz46qk592pa # Marie Pupo Jeammet
+128
View File
@@ -7,3 +7,131 @@ and this project adheres to
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [1.4.1] - 2024-10-23
### Fixed
- 🚑️(frontend) fix MailDomainsLayout
## [1.4.0] - 2024-10-23
### Added
- ✨(frontend) add tabs inside #466
### Fixed
- ✏️(mail) fix typo into mailbox creation email
- 🐛(sentry) fix duplicated sentry errors #479
- 🐛(script) improve and fix release script
## [1.3.1] - 2024-10-18
## [1.3.0] - 2024-10-18
### Added
- ✨(api) add RELEASE version on config endpoint #459
- ✨(backend) manage roles on domain admin view
- ✨(frontend) show version number in footer #369
### Changed
- 🛂(backend) match email if no existing user matches the sub
### Fixed
- 💄(mail) improve mailbox creation email #462
- 🐛(frontend) fix update accesses form #448
- 🛂(backend) do not duplicate user when disabled
## [1.2.1] - 2024-10-03
### Fixed
- 🔧(mail) use new scaleway email gateway #435
## [1.2.0] - 2024-09-30
### Added
- ✨(ci) add helmfile linter and fix argocd sync #424
- ✨(domains) add endpoint to list and retrieve domain accesses #404
- 🍱(dev) embark dimail-api as container #366
- ✨(dimail) allow la regie to request a token for another user #416
- ✨(frontend) show username on AccountDropDown #412
- 🥅(frontend) improve add & update group forms error handling #387
- ✨(frontend) allow group members filtering #363
- ✨(mailbox) send new mailbox confirmation email #397
- ✨(domains) domain accesses update API #423
- ✨(backend) domain accesses create API #428
- 🥅(frontend) catch new errors on mailbox creation #392
- ✨(api) domain accesses delete API #433
- ✨(frontend) add mail domain access management #413
### Fixed
- ♿️(frontend) fix left nav panel #396
- 🔧(backend) fix configuration to avoid different ssl warning #432
### Changed
- ♻️(serializers) move business logic to serializers #414
## [1.1.0] - 2024-09-10
### Added
- 📈(monitoring) configure sentry monitoring #378
- 🥅(frontend) improve api error handling #355
### Changed
- 🗃️(models) move dimail 'secret' to settings #372
### Fixed
- 🐛(dimail) improve handling of dimail errors on failed mailbox creation #377
- 💬(frontend) fix group member removal text #382
- 💬(frontend) fix add mail domain text #382
- 🐛(frontend) fix keyboard navigation #379
- 🐛(frontend) fix add mail domain form submission #355
## [1.0.2] - 2024-08-30
### Added
- 🔧Runtime config for the frontend (#345)
- 🔧(helm) configure resource server in staging
### Fixed
- 👽️(mailboxes) fix mailbox creation after dimail api improvement (#360)
## [1.0.1] - 2024-08-19
### Fixed
- ✨(frontend) user can add mail domains
## [1.0.0] - 2024-08-09
### Added
- ✨(domains) create and manage domains on admin + API
- ✨(domains) mailbox creation + link to email provisioning API
[unreleased]: https://github.com/numerique-gouv/people/compare/v1.4.1...main
[1.4.1]: https://github.com/numerique-gouv/people/releases/v1.4.1
[1.4.0]: https://github.com/numerique-gouv/people/releases/v1.4.0
[1.3.1]: https://github.com/numerique-gouv/people/releases/v1.3.1
[1.3.0]: https://github.com/numerique-gouv/people/releases/v1.3.0
[1.2.1]: https://github.com/numerique-gouv/people/releases/v1.2.1
[1.2.0]: https://github.com/numerique-gouv/people/releases/v1.2.0
[1.1.0]: https://github.com/numerique-gouv/people/releases/v1.1.0
[1.0.2]: https://github.com/numerique-gouv/people/releases/v1.0.2
[1.0.1]: https://github.com/numerique-gouv/people/releases/v1.0.1
[1.0.0]: https://github.com/numerique-gouv/people/releases/v1.0.0
+25 -1
View File
@@ -88,6 +88,7 @@ bootstrap: \
back-i18n-compile \
mails-install \
mails-build \
dimail-setup-db \
install-front-desk
.PHONY: bootstrap
@@ -109,6 +110,7 @@ run: ## start the wsgi (production) and development server
@$(COMPOSE) up --force-recreate -d app-dev
@$(COMPOSE) up --force-recreate -d celery-dev
@$(COMPOSE) up --force-recreate -d keycloak
@$(COMPOSE) up -d dimail
@echo "Wait for postgresql to be up..."
@$(WAIT_KC_DB)
@$(WAIT_DB)
@@ -129,6 +131,12 @@ demo: ## flush db then create a demo for load testing purpose
@$(MANAGE) create_demo
.PHONY: demo
reset-dimail-container:
@$(COMPOSE) up --force-recreate -d dimail
@$(MAKE) setup-dimail-db
.PHONY: reset-dimail-container
# Nota bene: Black should come after isort just in case they don't agree...
lint: ## lint back-end python sources
lint: \
@@ -166,6 +174,10 @@ test-back-parallel: ## run all back-end tests in parallel
bin/pytest -n auto $${args:-${1}}
.PHONY: test-back-parallel
test-coverage: ## compute, display and save test coverage
bin/pytest --cov=. --cov-report json .
.PHONY: test-coverage
makemigrations: ## run django makemigrations for the people project.
@echo "$(BOLD)Running makemigrations$(RESET)"
@$(COMPOSE) up -d postgresql
@@ -189,7 +201,8 @@ showmigrations: ## run django showmigrations for the people project.
superuser: ## Create an admin superuser with password "admin"
@echo "$(BOLD)Creating a Django superuser$(RESET)"
@$(MANAGE) createsuperuser --admin_email admin@example.com --password admin
$(MANAGE) createsuperuser --username admin --password admin
.PHONY: superuser
back-i18n-compile: ## compile the gettext files
@@ -267,6 +280,13 @@ i18n-generate-and-upload: \
crowdin-upload
.PHONY: i18n-generate-and-upload
# -- INTEROPERABILTY
# -- Dimail configuration
dimail-setup-db:
@echo "$(BOLD)Populating database of local dimail API container$(RESET)"
@$(MANAGE) setup_dimail_db
.PHONY: dimail-setup-db
# -- Mail generator
@@ -338,3 +358,7 @@ start-kind: ## Create the kubernetes cluster
tilt-up: ## start tilt - k8s local development
tilt up -f ./bin/Tiltfile
.PHONY: tilt-up
release: ## helper for release and deployment
python scripts/release.py
.PHONY: release
+26 -19
View File
@@ -1,12 +1,12 @@
# People
People is an application to handle users and teams.
People is an application to handle users and teams, and distribute permissions accross [La Suite](https://lasuite.numerique.gouv.fr/).
As of today, this project is **not yet ready for production**. Expect breaking changes.
People is built on top of [Django Rest
It is built on top of [Django Rest
Framework](https://www.django-rest-framework.org/).
All interoperabilities will be described in `docs/interoperability`.
## Getting started
### Prerequisite
@@ -25,7 +25,7 @@ $ docker compose -v
> ⚠️ You may need to run the following commands with `sudo` but this can be
> avoided by assigning your user to the `docker` group.
### Project bootstrap
### Bootstrap project
The easiest way to start working on the project is to use GNU Make:
@@ -38,7 +38,7 @@ database migrations and compile translations. It's a good idea to use this
command each time you are pulling code from the project repository to avoid
dependency-related or migration-related issues.
Your Docker services should now be up and running 🎉
Your Docker services should now be up and running! 🎉
Note that if you need to run them afterward, you can use the eponym Make rule:
@@ -46,13 +46,7 @@ Note that if you need to run them afterward, you can use the eponym Make rule:
$ make run
```
### Adding content
You can create a basic demo site by running:
$ make demo
Finally, you can check all available Make rules using:
You can check all available Make rules using:
```bash
$ make help
@@ -69,7 +63,24 @@ You first need to create a superuser account:
$ make superuser
```
You can then login with credentials `admin@example` / `admin`.
You can then login with sub `admin` and password `admin`.
### Adding demo content
You can create a basic demo site by running:
```bash
$ make demo
```
### Setting dimail database
To ease local development when working on interoperability between people and dimail, we embark dimail-api in a container running in "fake" mode.
To populate dimail local database with users/domains/permissions needed for basic development:
- log in with "people" user
- run `make dimail-setup-db`
### Run frontend
@@ -79,14 +90,10 @@ Run the front with:
$ make run-front-desk
```
Then access at
[http://localhost:3000](http://localhost:3000)
Then access [http://localhost:3000](http://localhost:3000) with :
user: people
password: people
## Contributing
This project is intended to be community-driven, so please, do not hesitate to
+8 -2
View File
@@ -1,5 +1,3 @@
version: '3.8'
services:
postgresql:
image: postgres:16
@@ -168,3 +166,11 @@ services:
- "8080:8080"
depends_on:
- kc_postgresql
dimail:
image: registry.mim-libre.fr/dimail/dimail-api:latest
environment:
DIMAIL_MODE: FAKE
DIMAIL_JWT_SECRET: fake_jwt_secret
ports:
- "8001:8000"
+35
View File
@@ -0,0 +1,35 @@
# dimail
## What is dimail ?
The mailing solution provided in La Suite is [Open-XChange](https://www.open-xchange.com/) (OX).
OX not having a provisioning API, 'dimail-api' or 'dimail' was created to allow mail-provisioning through People.
API and its documentation can be found [here](https://api.dev.ox.numerique.gouv.fr/docs#/).
## Architectural links of dimail
As dimail's primary goal is to act as an interface between People and OX, its architecture is similar to that of People. A series of requests are sent from People to dimail upon creating domains, users and accesses.
### Domains
Upon creating a domain on People, the same domain is created on dimail and will undergo a series of checks. When all checks have passed, the domain is considered valid and mailboxes can be created on it.
### Users
The ones issuing requests. Dimail users will reflect domains owners and administrators on People, for logging purposes and to allow direct use of dimail, if desired. User reconciliation is made on user uuid provided by ProConnect.
### Accesses
As for People, an access - a permissions (or "allows" in dimail) - grants an user permission to create objects on a domain.
Permissions requests are sent automatically upon :
- dimail database initialisation:
+ permission for dimail user People to create users and domains
- domain creation :
+ permission for dimail user People to manage domain
+ permission for new owner on new domain
- user creation:
+ permission for People to manage user
- access creation, if owner or admin:
+ permission for this user to manage domain
+164
View File
@@ -0,0 +1,164 @@
## Resource Server
For detailed information, please refer to the [OAuth 2.0 Resource Server documentation](https://www.oauth.com/oauth2-servers/the-resource-server/) and review the relevant commits that implement the resource server backend.
---
#### Overview
A resource server is a crucial component in an OAuth 2.0 ecosystem. It is responsible for accepting access tokens issued by the authorization server (in this case, Agent Connect), introspecting and validating those tokens, and then returning the requested protected resources to the client.
By implementing a resource server, we can securely share data between different services within La Suite. This ensures that only clients with the appropriate scopes and permissions can access specific resources, thereby enhancing security and maintaining proper access control across services.
---
#### Disclaimer
- Currently compatible only with Agent Connect.
- The development setup requires simplification, with dependencies on Agent Connect ideally mocked.
- Terminology aligns with the specification: what is referred to as a "resource server" is known as a "data provider" in Agent Connect.
- This documentation is WIP.
---
## Running Locally
#### Prerequisites
- **Agent Connect Stack**: Ensure the local Agent Connect stack is running. A solid understanding of its configuration and operation is recommended (advanced level).
- **People Stack**: Make sure the People stack is up and running.
- **Ngrok**: Install and set up Ngrok for secure tunneling.
---
### Update People's configurations
#### Environment variables
Agent Connect includes two pre-configured mocked data providers in its default stack (`bdd-fca-low`).
Use the client ID and client secret from one of these data providers. **Note:** Make sure to retrieve the decrypted secret, as it is stored encrypted in the database. You can find these values in the `dp.js` fixture file, where they are exposed in a comment.
Configure your environment with the following values from Agent Connect:
```
OIDC_RS_CLIENT_ID=<your-client-id-from-ac>
OIDC_RS_CLIENT_SECRET=<your-decrypted-client-secret-from-ac>
# In development, the resource server use insecure settings
OIDC_VERIFY_SSL=False
# Update the endpoints as follows
OIDC_OP_JWKS_ENDPOINT=https://core-fca-low.docker.dev-franceconnect.fr/api/v2/jwks
OIDC_OP_INTROSPECTION_ENDPOINT=https://core-fca-low.docker.dev-franceconnect.fr/api/v2/checktoken
OIDC_OP_URL=https://core-fca-low.docker.dev-franceconnect.fr/api/v2
```
#### Docker Network Configuration
To enable communication between the Docker networks for People and Agent Connect, update your docker-compose configuration. This setup is required because the Authorization Server and Resource Server will exchange requests over a back-channel, necessitating their accessibility to each other.
1. **Create a Network**: Define a new network to bridge the two Docker networks.
```yaml
networks:
authorization_server:
external: true
driver: bridge
name: "${DESK_NETWORK:-fc_public}"
```
2. **Update Network for `app-dev`**: Ensure your `app-dev` service is connected to both the default network and the new `authorization_server` network.
```yaml
app-dev:
...
networks:
- default
- authorization_server
```
#### Ngrok
To expose your local resource server through an HTTP tunnel, use Ngrok. This is necessary because, in the Agent Connect development stack, the resource server needs to be accessible to a user agent via a publicly accessible URL.
```
$ ngrok http 8071
```
---
### Update AgentConnect's configurations
Modify the AgentConnect configuration to include the local resource server settings.
**Update `fsa1-low` Environment File**:
Add your Ngrok URL and configure the `DATA_APIS` list with the appropriate values.
```env
App_DATA_APIS=[{"name":"Data Provider 1","url":"https://your-ngrok-url/api/v1.0/any-path","secret":"***"}, ...]
```
**Update Fixture in `dp.js`**:
Adjust the configuration for the data provider to match your local setup. Ensure that the `client_id`, `client_secret`, and other parameters are correctly set and aligned with your environment. This can be configured through environment variables.
```javascript
const dps = [
// Data Provider Configuration
{
uid: "6f21b751-ed06-48b6-a59c-36e1300a368a",
title: "Mock Data Provider - 1",
active: true,
slug: "DESK",
client_id: "***",
client_secret: "***",
// client_secret decrypted : ****
jwks_uri: "https://your-ngrok-url/api/v1.0/jwks", // Update this line
checktoken_signed_response_alg: "ES256",
checktoken_encrypted_response_alg: "RSA-OAEP",
checktoken_encrypted_response_enc: "A256GCM",
},
];
```
**Note**: Ensure that the `jwks_uri` and other cryptographic parameters (e.g., `checktoken_signed_response_alg`, `checktoken_encrypted_response_alg`, and `checktoken_encrypted_response_enc`) match your actual setup and are configured via environment variables where necessary.
---
### Usage
This section is a work in progress. Please note the following important points:
#### User `sub` Matching
Ensure that the `sub` (subject) field for users in AgentConnect matches the corresponding value in the People database. To synchronize this, you can run `make demo`, then edit the user's `sub` field to match the value returned by AgentConnect. For this, you'll need to update the editable field in Django Admin, specifically in `admin.py`. Adjust the `get_readonly_fields` method as follows:
```python
def get_readonly_fields(self, request, obj=None):
"""The 'sub' field should only be editable during creation, not for updates."""
if obj:
return self.readonly_fields
return self.readonly_fields + ["sub"] # update this line adding 'sub'
```
#### Scope for `groups`
Ensure that the `groups` scope is requested from the service provider during authentication with AgentConnect.
#### Resource Server Requests
By default, the `fsa1-low` environment calls the resource server using a POST request.
#### Testing
Most of the testing has been done using the `/users/me` endpoint. Update the `api/viewset.py` configuration to allow both GET and POST methods for this endpoint:
```python
@decorators.action(
detail=False,
methods=["get", "post"], # update this line adding 'post'
url_name="me",
url_path="me",
)
```
+32
View File
@@ -33,3 +33,35 @@ LOGOUT_REDIRECT_URL=http://localhost:3000
OIDC_REDIRECT_ALLOWED_HOSTS=["http://localhost:8083", "http://localhost:3000"]
OIDC_AUTH_REQUEST_EXTRA_PARAMS={"acr_values": "eidas1"}
OIDC_RS_CLIENT_ID=people
OIDC_RS_CLIENT_SECRET=ThisIsAnExampleKeyForDevPurposeOnly
OIDC_RS_PRIVATE_KEY_STR="-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC3boG1kwEGUYL+
U58RPrVToIsF9jHB64S6WJIIInPmAclBciXFb6BWG11mbRIgo8ha3WVnC/tGHbXb
ndiKdrH2vKHOsDhV9AmgHgNgWaUK9L0uuKEb/xMLePYWsYlgzcQJx8RZY7RQyWqE
20WfzFxeuCE7QMb6VXSOgwQMnJsKocguIh3VCI9RIBq3B1kdgW35AD63YKOygmGx
qjcWwbjhKLvkF7LpBdlyAEzOKqg4T5uCcHMfksMW2+foTJx70RrZM/KHU+Zysuw7
uhhVsgPBG+CsqBSjHQhs7jzymqxtQAfe1FkrCRxOq5Pv2Efr7kgtVSkJJiX3KutM
vnWuEypxAgMBAAECggEAGqKS9pbrN+vnmb7yMsqYgVVnQn0aggZNHlLkl4ZLLnuV
aemlhur7zO0JzajqUC+AFQOfaQxiFu8S/FoJ+qccFdATrcPEVmTKbgPVqSyzLKlX
fByGll5eOVT95NMwN8yBGgt2HSW/ZditXS/KxxahVgamGqjAC9MTSutGz/8Ae1U+
DNDBJCc6RAqu3T02tV9A2pSpVC1rSktDMpLUTscnsfxpaEQATd9DJUcHEvIwoX8q
GJpycPEhNhdPXqpln5SoMHcf/zS5ssF/Mce0lJJXYyE0LnEk9X12jMWyBqmLqXUY
cKLyynaFbis0DpQppwKx2y8GpL76k+Ci4dOHIvFknQKBgQDj/2WRMcWOvfBrggzj
FHpcme2gSo5A5c0CVyI+Xkf1Zab6UR6T7GiImEoj9tq0+o2WEix9rwoypgMBq8rz
/rrJAPSZjgv6z71k4EnO2FIB5R03vQmoBRCN8VlgvLM0xv52zyjV4Wx66Q4MDjyH
EgkpHyB0FzRZh0UzhnE/pYSetQKBgQDN9eLB1nA4CBSr1vMGNfQyfBQl3vpO9EP4
VSS3KnUqCIjJeLu682Ylu7SFxcJAfzUpy5S43hEvcuJsagsVKfmCAGcYZs9/xq3I
vzYyhaEOS5ezNxLSh4+yCNBPlmrmDyoazag0t8H8YQFBN6BVcxbATHqdWGUhIhYN
eEpEMOh2TQKBgGBr7kRNTENlyHtu8IxIaMcowfn8DdUcWmsW9oBx1vTNHKTYEZp1
bG/4F8LF7xCCtcY1wWMV17Y7xyG5yYcOv2eqY8dc72wO1wYGZLB5g5URlB2ycJcC
LVIaM7ZZl2BGl+8fBSIOx5XjYfFvQ+HLmtwtMchm19jVAEseHF7SXRfRAoGAK15j
aT2mU6Yf9C9G7T/fM+I8u9zACHAW/+ut14PxN/CkHQh3P16RW9CyqpiB1uLyZuKf
Zm4cYElotDuAKey0xVMgYlsDxnwni+X3m5vX1hLE1s/5/qrc7zg75QZfbCI1U3+K
s88d4e7rPLhh4pxhZgy0pP1ADkIHMr7ppIJH8OECgYEApNfbgsJVPAMzucUhJoJZ
OmZHbyCtJvs4b+zxnmhmSbopifNCgS4zjXH9qC7tsUph1WE6L2KXvtApHGD5H4GQ
IH5em4M/pHIcsqCi1qggBMbdvzHBUtC3R4sK0CpEFHlN+Y59aGazidcN2FPupNJv
MbyqKyC6DAzv4jEEhHaN7oY=
-----END PRIVATE KEY-----
"
+1 -1
View File
@@ -13,7 +13,7 @@
"enabled": false,
"groupName": "ignored js dependencies",
"matchManagers": ["npm"],
"matchPackageNames": ["node", "node-fetch", "i18next-parser", "eslint"]
"matchPackageNames": ["fetch-mock", "node", "node-fetch", "eslint"]
}
]
}
+115
View File
@@ -0,0 +1,115 @@
import datetime
import os
import re
import sys
from utils import run_command
RELEASE_KINDS = {'p': 'patch', 'm': 'minor', 'mj': 'major'}
def update_files(version):
"""Update all files needed with new release version"""
# pyproject.toml
sys.stdout.write("Update pyproject.toml...\n")
path = "src/backend/pyproject.toml"
with open(path, 'r') as file:
lines = file.readlines()
for index, line in enumerate(lines):
if line.startswith("version = "):
lines[index] = re.sub(r'\"(.*?)\"', f'"{version}"', line)
with open(path, 'w+') as file:
file.writelines(lines)
# helm files
sys.stdout.write("Update helm files...\n")
for env in ["preprod", "production"]:
path = f"src/helm/env.d/{env}/values.desk.yaml.gotmpl"
with open(path, 'r') as file:
lines = file.readlines()
for index, line in enumerate(lines):
if "tag:" in line:
lines[index] = re.sub(r'\"(.*?)\"', f'"v{version}"', line)
with open(path, 'w+') as file:
file.writelines(lines)
# frontend package.json
sys.stdout.write("Update package.json...\n")
files_to_modify = []
filename = "package.json"
for root, _dir, files in os.walk("src/frontend"):
if filename in files and "node_modules" not in root and ".next" not in root:
files_to_modify.append(os.path.join(root, filename))
for path in files_to_modify:
with open(path, 'r') as file:
lines = file.readlines()
for index, line in enumerate(lines):
if "version" in line:
lines[index] = re.sub(r'"version": \"(.*?)\"', f'"version": "{version}"', line)
with open(path, 'w+') as file:
file.writelines(lines)
return
def update_changelog(path, version):
"""Update changelog file with release info
"""
sys.stdout.write("Update CHANGELOG...\n")
with open(path, 'r') as file:
lines = file.readlines()
for index, line in enumerate(lines):
if "## [Unreleased]" in line:
today = datetime.date.today()
lines.insert(index + 1, f"\n## [{version}] - {today}\n")
if line.startswith("[unreleased]"):
last_version = lines[index + 1].split("]")[0][1:]
new_unreleased_line = line.replace(last_version, version)
new_release_line = lines[index + 1].replace(last_version, version)
lines[index] = new_unreleased_line
lines.insert(index + 1, new_release_line)
break
with open(path, 'w+') as file:
file.writelines(lines)
def prepare_release(version, kind):
sys.stdout.write('Let\'s go to create branch to release\n')
branch_to_release = f"release/{version}"
run_command(f"git checkout -b {branch_to_release}", shell=True)
run_command("git pull --rebase origin main", shell=True)
update_changelog("CHANGELOG.md", version)
update_files(version)
run_command("git add CHANGELOG.md", shell=True)
run_command("git add src/", shell=True)
message = f"""🔖({RELEASE_KINDS[kind]}) release version {version}
Update all version files and changelog for {RELEASE_KINDS[kind]} release."""
run_command(f"git commit -m '{message}'", shell=True)
confirm = input(f"\nNEXT COMMAND: \n>> git push origin {branch_to_release}\nContinue ? (y,n) ")
if confirm == 'y':
run_command(f"git push origin {branch_to_release}", shell=True)
sys.stdout.write(f"""
PLEASE DO THE FOLLOWING INSTRUCTIONS:
--> Please submit PR and merge code to main than tag version
>> git tag -a v{version}
>> git push origin v{version}
--> Please check docker image: https://hub.docker.com/r/lasuite/people-backend/tags
>> git tag -d preprod
>> git tag preprod
>> git push -f origin preprod
--> Now please generate release on github interface for the current tag v{version}
""")
if __name__ == "__main__":
version, kind = None, None
while not version:
version = input("Enter your release version:")
while kind not in RELEASE_KINDS:
kind = input("Enter kind of release (p:patch, m:minor, mj:major):")
prepare_release(version, kind)
+14
View File
@@ -0,0 +1,14 @@
import subprocess
import sys
def run_command(cmd, msg=None, shell=False, cwd='.', stdout=None):
if msg is None:
msg = f"# Running: {cmd}"
if stdout is not None:
stdout.write(msg + '\n')
if stdout != sys.stdout:
sys.stdout(msg)
subprocess.check_call(cmd, shell=shell, cwd=cwd, stdout=stdout, stderr=stdout)
if stdout is not None:
stdout.flush()
+1 -1
Submodule secrets updated: d7cfe7bcdc...b7ab5f1411
+36 -43
View File
@@ -1,49 +1,14 @@
"""Admin classes and registrations for People's core app."""
from django import forms
from django.contrib import admin
from django.contrib.auth import admin as auth_admin
from django.utils.translation import gettext_lazy as _
from mailbox_manager.admin import MailDomainAccessInline
from . import models
class IdentityFormSet(forms.BaseInlineFormSet):
"""
Make the "is_main" field readonly when it is True so that declaring another identity
works in the admin.
"""
def add_fields(self, form, index):
"""Disable the "is_main" field when it is set to True"""
super().add_fields(form, index)
is_main_value = form.instance.is_main if form.instance else False
form.fields["is_main"].disabled = is_main_value
class IdentityInline(admin.TabularInline):
"""Inline admin class for user identities."""
fields = (
"sub",
"email",
"is_main",
"created_at",
"updated_at",
)
formset = IdentityFormSet
model = models.Identity
extra = 0
readonly_fields = ("email", "created_at", "sub", "updated_at")
def has_add_permission(self, request, obj):
"""
Identities are automatically created on successful OIDC logins.
Disable creating identities via the admin.
"""
return False
class TeamAccessInline(admin.TabularInline):
"""Inline admin class for team accesses."""
@@ -72,11 +37,12 @@ class UserAdmin(auth_admin.UserAdmin):
{
"fields": (
"id",
"sub",
"password",
)
},
),
(_("Personal info"), {"fields": ("admin_email", "language", "timezone")}),
(_("Personal info"), {"fields": ("name", "email", "language", "timezone")}),
(
_("Permissions"),
{
@@ -97,13 +63,13 @@ class UserAdmin(auth_admin.UserAdmin):
None,
{
"classes": ("wide",),
"fields": ("admin_email", "password1", "password2"),
"fields": ("sub", "email", "password1", "password2"),
},
),
)
inlines = (IdentityInline, TeamAccessInline)
inlines = (TeamAccessInline, MailDomainAccessInline)
list_display = (
"admin_email",
"get_user",
"created_at",
"updated_at",
"is_active",
@@ -113,8 +79,22 @@ class UserAdmin(auth_admin.UserAdmin):
)
list_filter = ("is_staff", "is_superuser", "is_device", "is_active")
ordering = ("is_active", "-is_superuser", "-is_staff", "-is_device", "-updated_at")
readonly_fields = ("id", "created_at", "updated_at")
search_fields = ("id", "admin_email", "identities__sub", "identities__email")
readonly_fields = ["id", "created_at", "updated_at"]
search_fields = ("id", "email", "sub", "name")
def get_readonly_fields(self, request, obj=None):
"""The sub should only be editable for a create, not for updates."""
if obj:
return self.readonly_fields + ["sub"]
return self.readonly_fields
def get_user(self, obj):
"""Provide a nice display for user"""
return (
obj.name if obj.name else (obj.email if obj.email else f"[sub] {obj.sub}")
)
get_user.short_description = _("User")
@admin.register(models.Team)
@@ -131,6 +111,19 @@ class TeamAdmin(admin.ModelAdmin):
search_fields = ("name",)
@admin.register(models.TeamAccess)
class TeamAccessAdmin(admin.ModelAdmin):
"""Team access admin interface declaration."""
list_display = (
"user",
"team",
"role",
"created_at",
"updated_at",
)
@admin.register(models.Invitation)
class InvitationAdmin(admin.ModelAdmin):
"""Admin interface to handle invitations."""
+43 -27
View File
@@ -1,7 +1,8 @@
"""API endpoints"""
from django.conf import settings
from django.contrib.postgres.search import TrigramSimilarity
from django.db.models import Func, Max, OuterRef, Prefetch, Q, Subquery, Value
from django.db.models import Func, Max, OuterRef, Q, Subquery, Value
from django.db.models.functions import Coalesce
from rest_framework import (
@@ -12,8 +13,10 @@ from rest_framework import (
pagination,
response,
throttling,
views,
viewsets,
)
from rest_framework.permissions import AllowAny
from core import models
@@ -198,12 +201,6 @@ class UserViewSet(
# Exclude inactive contacts
queryset = queryset.filter(
is_active=True,
).prefetch_related(
Prefetch(
"identities",
queryset=models.Identity.objects.filter(is_main=True),
to_attr="_identities_main",
)
)
# Exclude all users already in the given team
@@ -214,15 +211,11 @@ class UserViewSet(
if query := self.request.GET.get("q", ""):
similarity = Max(
TrigramSimilarity(
Coalesce(
Func("identities__email", function="unaccent"), Value("")
),
Coalesce(Func("email", function="unaccent"), Value("")),
Func(Value(query), function="unaccent"),
)
+ TrigramSimilarity(
Coalesce(
Func("identities__name", function="unaccent"), Value("")
),
Coalesce(Func("name", function="unaccent"), Value("")),
Func(Value(query), function="unaccent"),
)
)
@@ -329,7 +322,7 @@ class TeamAccessViewSet(
filter_backends = [filters.OrderingFilter]
ordering = ["role"]
ordering_fields = ["role", "email", "name"]
ordering_fields = ["role", "user__email", "user__name"]
def get_permissions(self):
"""User only needs to be authenticated to list team accesses"""
@@ -357,34 +350,39 @@ class TeamAccessViewSet(
queryset = queryset.filter(team=self.kwargs["team_id"])
if self.action in {"list", "retrieve"}:
if query := self.request.GET.get("q", ""):
similarity = Max(
TrigramSimilarity(
Coalesce(Func("user__email", function="unaccent"), Value("")),
Func(Value(query), function="unaccent"),
)
+ TrigramSimilarity(
Coalesce(Func("user__name", function="unaccent"), Value("")),
Func(Value(query), function="unaccent"),
)
)
queryset = (
queryset.annotate(similarity=similarity)
.filter(similarity__gte=SIMILARITY_THRESHOLD)
.order_by("-similarity")
)
# Determine which role the logged-in user has in the team
user_role_query = models.TeamAccess.objects.filter(
user=self.request.user, team=self.kwargs["team_id"]
).values("role")[:1]
user_main_identity_query = models.Identity.objects.filter(
user=OuterRef("user_id"), is_main=True
)
queryset = (
# The logged-in user should be part of a team to see its accesses
queryset.filter(
team__accesses__user=self.request.user,
)
.prefetch_related(
Prefetch(
"user__identities",
queryset=models.Identity.objects.filter(is_main=True),
to_attr="_identities_main",
)
)
# Abilities are computed based on logged-in user's role and
# the user role on each team access
.annotate(
user_role=Subquery(user_role_query),
email=Subquery(user_main_identity_query.values("email")[:1]),
name=Subquery(user_main_identity_query.values("name")[:1]),
)
.select_related("user")
.distinct()
)
return queryset
@@ -496,3 +494,21 @@ class InvitationViewset(
.distinct()
)
return queryset
class ConfigView(views.APIView):
"""API ViewSet for sharing some public settings."""
permission_classes = [AllowAny]
def get(self, request):
"""
GET /api/v1.0/config/
Return a dictionary of public settings.
"""
array_settings = ["LANGUAGES", "FEATURES", "RELEASE"]
dict_settings = {}
for setting in array_settings:
dict_settings[setting] = getattr(settings, setting)
return response.Response(dict_settings)
+53 -36
View File
@@ -1,8 +1,8 @@
"""Authentication Backends for the People core app."""
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import SuspiciousOperation
from django.db import models
from django.utils.translation import gettext_lazy as _
import requests
@@ -10,14 +10,14 @@ from mozilla_django_oidc.auth import (
OIDCAuthenticationBackend as MozillaOIDCAuthenticationBackend,
)
from core.models import Identity
User = get_user_model()
class OIDCAuthenticationBackend(MozillaOIDCAuthenticationBackend):
"""Custom OpenID Connect (OIDC) Authentication Backend.
This class overrides the default OIDC Authentication Backend to accommodate differences
in the User and Identity models, and handles signed and/or encrypted UserInfo response.
in the User model, and handles signed and/or encrypted UserInfo response.
"""
def get_userinfo(self, access_token, id_token, payload):
@@ -51,7 +51,7 @@ class OIDCAuthenticationBackend(MozillaOIDCAuthenticationBackend):
return userinfo
def get_or_create_user(self, access_token, id_token, payload):
"""Return a User based on userinfo. Get or create a new user if no user matches the Sub.
"""Return a User based on userinfo. Create a new user if no match is found.
Parameters:
- access_token (str): The access token.
@@ -67,42 +67,30 @@ class OIDCAuthenticationBackend(MozillaOIDCAuthenticationBackend):
user_info = self.get_userinfo(access_token, id_token, payload)
# Compute user name from OIDC name fields as defined in settings
names_list = [
user_info[field]
for field in settings.USER_OIDC_FIELDS_TO_NAME
if user_info.get(field)
]
user_info["name"] = " ".join(names_list) or None
# Get user's full name from OIDC fields defined in settings
full_name = self.compute_full_name(user_info)
email = user_info.get("email")
claims = {
"email": email,
"name": full_name,
}
sub = user_info.get("sub")
if sub is None:
if not sub:
raise SuspiciousOperation(
_("User info contained no recognizable user identification")
)
user = (
self.UserModel.objects.filter(identities__sub=sub)
.annotate(
identity_email=models.F("identities__email"),
identity_name=models.F("identities__name"),
)
.distinct()
.first()
)
if user:
email = user_info.get("email")
name = user_info.get("name")
if (
email
and email != user.identity_email
or name
and name != user.identity_name
):
Identity.objects.filter(sub=sub).update(email=email, name=name)
# if sub is absent, try matching on email
user = self.get_existing_user(sub, email)
if user:
if not user.is_active:
raise SuspiciousOperation(_("User account is disabled"))
self.update_user_if_needed(user, claims)
elif self.get_settings("OIDC_CREATE_USER", True):
user = self.create_user(user_info)
user = User.objects.create(sub=sub, password="!", **claims) # noqa: S106
return user
@@ -114,9 +102,38 @@ class OIDCAuthenticationBackend(MozillaOIDCAuthenticationBackend):
_("Claims contained no recognizable user identification")
)
user = self.UserModel.objects.create(password="!") # noqa: S106
Identity.objects.create(
user=user, sub=sub, email=claims.get("email"), name=claims.get("name")
return self.UserModel.objects.create(
password="!", # noqa: S106
sub=sub,
email=claims.get("email"),
name=claims.get("name"),
)
return user
def compute_full_name(self, user_info):
"""Compute user's full name based on OIDC fields in settings."""
name_fields = settings.USER_OIDC_FIELDS_TO_NAME
full_name = " ".join(
user_info[field] for field in name_fields if user_info.get(field)
)
return full_name or None
def get_existing_user(self, sub, email):
"""Fetch existing user by sub or email."""
try:
return User.objects.get(sub=sub)
except User.DoesNotExist:
if email and settings.OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION:
try:
return User.objects.get(email=email)
except User.DoesNotExist:
pass
return None
def update_user_if_needed(self, user, claims):
"""Update user claims if they have changed."""
has_changed = any(
value and value != getattr(user, key) for key, value in claims.items()
)
if has_changed:
updated_claims = {key: value for key, value in claims.items() if value}
self.UserModel.objects.filter(sub=user.sub).update(**updated_claims)
+2 -13
View File
@@ -124,24 +124,13 @@ class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.User
django_get_or_create = ("admin_email",)
admin_email = factory.Faker("email")
language = factory.fuzzy.FuzzyChoice([lang[0] for lang in settings.LANGUAGES])
password = make_password("password")
class IdentityFactory(factory.django.DjangoModelFactory):
"""A factory to create identities for a user"""
class Meta:
model = models.Identity
django_get_or_create = ("sub",)
user = factory.SubFactory(UserFactory)
sub = factory.Sequence(lambda n: f"user{n!s}")
email = factory.Faker("email")
name = factory.Faker("name")
language = factory.fuzzy.FuzzyChoice([lang[0] for lang in settings.LANGUAGES])
password = make_password("password")
class TeamFactory(factory.django.DjangoModelFactory):
+6 -27
View File
@@ -1,4 +1,4 @@
# Generated by Django 5.0.3 on 2024-03-25 22:58
# Generated by Django 5.0.3 on 2024-06-08 09:25
import django.contrib.auth.models
import django.core.validators
@@ -45,7 +45,9 @@ class Migration(migrations.Migration):
('id', models.UUIDField(default=uuid.uuid4, editable=False, help_text='primary key for the record as UUID', primary_key=True, serialize=False, verbose_name='id')),
('created_at', models.DateTimeField(auto_now_add=True, help_text='date and time at which a record was created', verbose_name='created at')),
('updated_at', models.DateTimeField(auto_now=True, help_text='date and time at which a record was last updated', verbose_name='updated at')),
('admin_email', models.EmailField(blank=True, max_length=254, null=True, unique=True, verbose_name='admin email address')),
('sub', models.CharField(help_text='Required. 255 characters or fewer. Letters, numbers, and @/./+/-/_ characters only.', max_length=255, unique=True, validators=[django.core.validators.RegexValidator(message='Enter a valid sub. This value may contain only letters, numbers, and @/./+/-/_ characters.', regex='^[\\w.@+-]+\\Z')], verbose_name='sub')),
('email', models.EmailField(blank=True, max_length=254, null=True, verbose_name='email address')),
('name', models.CharField(blank=True, max_length=100, null=True, verbose_name='name')),
('language', models.CharField(choices="(('en-us', 'English'), ('fr-fr', 'French'))", default='en-us', help_text='The language in which the user wants to see the interface.', max_length=10, verbose_name='language')),
('timezone', timezone_field.fields.TimeZoneField(choices_display='WITH_GMT_OFFSET', default='UTC', help_text='The timezone in which the user wants to see times.', use_pytz=False)),
('is_device', models.BooleanField(default=False, help_text='Whether the user is a device or a real user.', verbose_name='device')),
@@ -87,25 +89,6 @@ class Migration(migrations.Migration):
name='profile_contact',
field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='user', to='core.contact'),
),
migrations.CreateModel(
name='Identity',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, help_text='primary key for the record as UUID', primary_key=True, serialize=False, verbose_name='id')),
('created_at', models.DateTimeField(auto_now_add=True, help_text='date and time at which a record was created', verbose_name='created at')),
('updated_at', models.DateTimeField(auto_now=True, help_text='date and time at which a record was last updated', verbose_name='updated at')),
('sub', models.CharField(help_text='Required. 255 characters or fewer. Letters, numbers, and @/./+/-/_ characters only.', max_length=255, unique=True, validators=[django.core.validators.RegexValidator(message='Enter a valid sub. This value may contain only letters, numbers, and @/./+/-/_ characters.', regex='^[\\w.@+-]+\\Z')], verbose_name='sub')),
('email', models.EmailField(blank=True, max_length=254, null=True, verbose_name='email address')),
('name', models.CharField(blank=True, max_length=100, null=True, verbose_name='name')),
('is_main', models.BooleanField(default=False, help_text='Designates whether the email is the main one.', verbose_name='main')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='identities', to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'identity',
'verbose_name_plural': 'identities',
'db_table': 'people_identity',
'ordering': ('-is_main', 'email'),
},
),
migrations.CreateModel(
name='Invitation',
fields=[
@@ -163,20 +146,16 @@ class Migration(migrations.Migration):
),
migrations.AddConstraint(
model_name='contact',
constraint=models.CheckConstraint(check=models.Q(('base__isnull', False), ('owner__isnull', True), _negated=True), name='base_owner_constraint', violation_error_message='A contact overriding a base contact must be owned.'),
constraint=models.CheckConstraint(condition=models.Q(('base__isnull', False), ('owner__isnull', True), _negated=True), name='base_owner_constraint', violation_error_message='A contact overriding a base contact must be owned.'),
),
migrations.AddConstraint(
model_name='contact',
constraint=models.CheckConstraint(check=models.Q(('base', models.F('id')), _negated=True), name='base_not_self', violation_error_message='A contact cannot be based on itself.'),
constraint=models.CheckConstraint(condition=models.Q(('base', models.F('id')), _negated=True), name='base_not_self', violation_error_message='A contact cannot be based on itself.'),
),
migrations.AlterUniqueTogether(
name='contact',
unique_together={('owner', 'base')},
),
migrations.AddConstraint(
model_name='identity',
constraint=models.UniqueConstraint(fields=('user', 'email'), name='unique_user_email', violation_error_message='This email address is already declared for this user.'),
),
migrations.AddConstraint(
model_name='invitation',
constraint=models.UniqueConstraint(fields=('email', 'team'), name='email_and_team_unique_together'),
+41 -130
View File
@@ -124,12 +124,12 @@ class Contact(BaseModel):
unique_together = ("owner", "base")
constraints = [
models.CheckConstraint(
check=~models.Q(base__isnull=False, owner__isnull=True),
condition=~models.Q(base__isnull=False, owner__isnull=True),
name="base_owner_constraint",
violation_error_message="A contact overriding a base contact must be owned.",
),
models.CheckConstraint(
check=~models.Q(base=models.F("id")),
condition=~models.Q(base=models.F("id")),
name="base_not_self",
violation_error_message="A contact cannot be based on itself.",
),
@@ -161,9 +161,25 @@ class Contact(BaseModel):
class User(AbstractBaseUser, BaseModel, auth_models.PermissionsMixin):
"""User model to work with OIDC only authentication."""
admin_email = models.EmailField(
_("admin email address"), unique=True, null=True, blank=True
sub_validator = validators.RegexValidator(
regex=r"^[\w.@+-]+\Z",
message=_(
"Enter a valid sub. This value may contain only letters, "
"numbers, and @/./+/-/_ characters."
),
)
sub = models.CharField(
_("sub"),
help_text=_(
"Required. 255 characters or fewer. Letters, numbers, and @/./+/-/_ characters only."
),
max_length=255,
unique=True,
validators=[sub_validator],
)
email = models.EmailField(_("email address"), null=True, blank=True)
name = models.CharField(_("name"), max_length=100, null=True, blank=True)
profile_contact = models.OneToOneField(
Contact,
on_delete=models.SET_NULL,
@@ -205,7 +221,7 @@ class User(AbstractBaseUser, BaseModel, auth_models.PermissionsMixin):
objects = auth_models.UserManager()
USERNAME_FIELD = "admin_email"
USERNAME_FIELD = "sub"
REQUIRED_FIELDS = []
class Meta:
@@ -214,116 +230,11 @@ class User(AbstractBaseUser, BaseModel, auth_models.PermissionsMixin):
verbose_name_plural = _("users")
def __str__(self):
return (
str(self.profile_contact)
if self.profile_contact
else self.admin_email or str(self.id)
)
def _get_identities_main(self):
"""Return a list with the main identity or an empty list."""
try:
return self._identities_main
except AttributeError:
return self.identities.filter(is_main=True)
@property
def name(self):
"""Return main identity's name."""
try:
return self._get_identities_main()[0].name
except IndexError:
return None
@property
def email(self):
"""Return main identity's email."""
try:
return self._get_identities_main()[0].email
except IndexError:
return None
def clean(self):
"""Validate fields."""
super().clean()
if self.profile_contact_id and not self.profile_contact.owner == self:
raise exceptions.ValidationError(
"Users can only declare as profile a contact they own."
)
def email_user(self, subject, message, from_email=None, **kwargs):
"""Email this user."""
email = self.email or self.admin_email
if not email:
raise ValueError("You must first set an email for the user.")
mail.send_mail(subject, message, from_email, [email], **kwargs)
@classmethod
def get_email_field_name(cls):
"""
Raise error when trying to get email field name from the user as we are using
a separate Email model to allow several emails per user.
"""
raise NotImplementedError(
"This feature is deactivated to allow several emails per user."
)
class Identity(BaseModel):
"""User identity"""
sub_validator = validators.RegexValidator(
regex=r"^[\w.@+-]+\Z",
message=_(
"Enter a valid sub. This value may contain only letters, "
"numbers, and @/./+/-/_ characters."
),
)
user = models.ForeignKey(User, related_name="identities", on_delete=models.CASCADE)
sub = models.CharField(
_("sub"),
help_text=_(
"Required. 255 characters or fewer. Letters, numbers, and @/./+/-/_ characters only."
),
max_length=255,
unique=True,
validators=[sub_validator],
)
email = models.EmailField(_("email address"), null=True, blank=True)
name = models.CharField(_("name"), max_length=100, null=True, blank=True)
is_main = models.BooleanField(
_("main"),
default=False,
help_text=_("Designates whether the email is the main one."),
)
class Meta:
db_table = "people_identity"
ordering = ("-is_main", "email")
verbose_name = _("identity")
verbose_name_plural = _("identities")
constraints = [
# Uniqueness
models.UniqueConstraint(
fields=["user", "email"],
name="unique_user_email",
violation_error_message=_(
"This email address is already declared for this user."
),
),
]
def __str__(self):
main_str = "[main]" if self.is_main else ""
id_str = self.email or self.sub
return f"{id_str:s}{main_str:s}"
return self.name if self.name else self.email or f"User {self.sub}"
def save(self, *args, **kwargs):
"""
Saves identity, ensuring users always have exactly one main identity.
If it's a new identity, give its user access to the relevant teams.
If it's a new user, give her access to the relevant teams.
"""
if self._state.adding:
@@ -331,9 +242,16 @@ class Identity(BaseModel):
super().save(*args, **kwargs)
# Ensure users always have one and only one main identity.
if self.is_main is True:
self.user.identities.exclude(id=self.id).update(is_main=False)
def clean(self):
"""Validate fields."""
super().clean()
if self.email:
self.email = User.objects.normalize_email(self.email)
if self.profile_contact_id and not self.profile_contact.owner == self:
raise exceptions.ValidationError(
"Users can only declare as profile a contact they own."
)
def _convert_valid_invitations(self):
"""
@@ -354,24 +272,17 @@ class Identity(BaseModel):
TeamAccess.objects.bulk_create(
[
TeamAccess(user=self.user, team=invitation.team, role=invitation.role)
TeamAccess(user=self, team=invitation.team, role=invitation.role)
for invitation in valid_invitations
]
)
valid_invitations.delete()
def clean(self):
"""Normalize the email field and clean the 'is_main' field."""
if self.email:
self.email = User.objects.normalize_email(self.email)
if not self.user.identities.exclude(pk=self.pk).filter(is_main=True).exists():
if not self.created_at:
self.is_main = True
elif not self.is_main:
raise exceptions.ValidationError(
{"is_main": "A user should have one and only one main identity."}
)
super().clean()
def email_user(self, subject, message, from_email=None, **kwargs):
"""Email this user."""
if not self.email:
raise ValueError("You must first set an email for the user.")
mail.send_mail(subject, message, from_email, [self.email], **kwargs)
class Team(BaseModel):
@@ -615,8 +526,8 @@ class Invitation(BaseModel):
"""Validate fields."""
super().clean()
# Check if an identity already exists for the provided email
if Identity.objects.filter(email=self.email).exists():
# Check if a user already exists for the provided email
if User.objects.filter(email=self.email).exists():
raise exceptions.ValidationError(
{"email": _("This email is already associated to a registered user.")}
)
@@ -0,0 +1,54 @@
"""Resource Server Authentication"""
import base64
import binascii
import logging
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from mozilla_django_oidc.contrib.drf import OIDCAuthentication
from .backend import ResourceServerBackend, ResourceServerImproperlyConfiguredBackend
from .clients import AuthorizationServerClient
logger = logging.getLogger(__name__)
class ResourceServerAuthentication(OIDCAuthentication):
"""Authenticate clients using the token received from the authorization server."""
def __init__(self):
super().__init__()
try:
authorization_server_client = AuthorizationServerClient(
url=settings.OIDC_OP_URL,
verify_ssl=settings.OIDC_VERIFY_SSL,
timeout=settings.OIDC_TIMEOUT,
proxy=settings.OIDC_PROXY,
url_jwks=settings.OIDC_OP_JWKS_ENDPOINT,
url_introspection=settings.OIDC_OP_INTROSPECTION_ENDPOINT,
)
self.backend = ResourceServerBackend(authorization_server_client)
except ImproperlyConfigured as err:
message = "Resource Server authentication is disabled"
logger.debug("%s. Exception: %s", message, err)
self.backend = ResourceServerImproperlyConfiguredBackend()
def get_access_token(self, request):
"""Retrieve and decode the access token from the request.
This method overcharges the 'get_access_token' method from the parent class,
to support service providers that would base64 encode the bearer token.
"""
access_token = super().get_access_token(request)
try:
access_token = base64.b64decode(access_token).decode("utf-8")
except (binascii.Error, TypeError):
pass
return access_token
+223
View File
@@ -0,0 +1,223 @@
"""Resource Server Backend"""
import logging
from django.conf import settings
from django.contrib import auth
from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation
from joserfc import jwe as jose_jwe
from joserfc import jwt as jose_jwt
from joserfc.errors import InvalidClaimError, InvalidTokenError
from requests.exceptions import HTTPError
from rest_framework.exceptions import AuthenticationFailed
from . import utils
logger = logging.getLogger(__name__)
class ResourceServerBackend:
"""Backend of an OAuth 2.0 resource server.
This backend is designed to authenticate resource owners to our API using the access token
they received from the authorization server.
In the context of OAuth 2.0, a resource server is a server that hosts protected resources and
is capable of accepting and responding to protected resource requests using access tokens.
The resource server verifies the validity of the access tokens issued by the authorization
server to ensure secure access to the resources.
For more information, visit: https://www.oauth.com/oauth2-servers/the-resource-server/
"""
# pylint: disable=too-many-instance-attributes
def __init__(self, authorization_server_client):
# pylint: disable=invalid-name
self.UserModel = auth.get_user_model()
self._client_id = settings.OIDC_RS_CLIENT_ID
self._client_secret = settings.OIDC_RS_CLIENT_SECRET
self._encryption_encoding = settings.OIDC_RS_ENCRYPTION_ENCODING
self._encryption_algorithm = settings.OIDC_RS_ENCRYPTION_ALGO
self._signing_algorithm = settings.OIDC_RS_SIGNING_ALGO
self._scopes = settings.OIDC_RS_SCOPES
if (
not self._client_id
or not self._client_secret
or not authorization_server_client
):
raise ImproperlyConfigured(
"Could not instantiate ResourceServerBackend, some parameters are missing."
)
self._authorization_server_client = authorization_server_client
self._claims_registry = jose_jwt.JWTClaimsRegistry(
iss={"essential": True, "value": self._authorization_server_client.url},
aud={"essential": True, "value": self._client_id},
token_introspection={"essential": True},
)
# pylint: disable=unused-argument
def get_or_create_user(self, access_token, id_token, payload):
"""Maintain API compatibility with OIDCAuthentication class from mozilla-django-oidc
Params 'id_token', 'payload' won't be used, and our implementation will only
support 'get_user', not 'get_or_create_user'.
"""
return self.get_user(access_token)
def get_user(self, access_token):
"""Get user from an access token emitted by the authorization server.
This method will submit the access token to the authorization server for
introspection, to ensure its validity and obtain the associated metadata.
It follows the specifications outlined in RFC7662 https://www.rfc-editor.org/info/rfc7662,
https://datatracker.ietf.org/doc/html/draft-ietf-oauth-jwt-introspection-response-12.
In our eGovernment applications, the standard RFC 7662 doesn't provide sufficient security.
Its introspection response is a plain JSON object. Therefore, we use the draft RFC
that extends RFC 7662 by returning a signed and encrypted JWT for stronger assurance that
the authorization server issued the token introspection response.
"""
jwt = self._introspect(access_token)
claims = self._verify_claims(jwt)
user_info = self._verify_user_info(claims["token_introspection"])
sub = user_info.get("sub")
if sub is None:
message = "User info contained no recognizable user identification"
logger.debug(message)
raise SuspiciousOperation(message)
try:
user = self.UserModel.objects.get(sub=sub)
except self.UserModel.DoesNotExist:
logger.debug("Login failed: No user with %s found", sub)
return None
return user
def _verify_user_info(self, introspection_response):
"""Verify the 'introspection_response' to get valid and relevant user info.
The 'introspection_response' should be still active, and while authenticating
the resource owner should have requested relevant scope to access her data in
our resource server.
Scope should be configured to match between the AS and the RS. The AS will filter
all the scopes the resource owner requested to expose only the relevant ones to
our resource server.
"""
active = introspection_response.get("active", None)
if not active:
message = "Introspection response is not active."
logger.debug(message)
raise SuspiciousOperation(message)
requested_scopes = introspection_response.get("scope", None).split(" ")
if set(self._scopes).isdisjoint(set(requested_scopes)):
message = "Introspection response contains any required scopes."
logger.debug(message)
raise SuspiciousOperation(message)
return introspection_response
def _introspect(self, token):
"""Introspect an access token to the authorization server."""
try:
jwe = self._authorization_server_client.get_introspection(
self._client_id,
self._client_secret,
token,
)
except HTTPError as err:
message = "Could not fetch introspection"
logger.debug("%s. Exception:", message, exc_info=True)
raise SuspiciousOperation(message) from err
private_key = utils.import_private_key_from_settings()
jws = self._decrypt(jwe, private_key=private_key)
try:
public_key_set = self._authorization_server_client.import_public_keys()
except (TypeError, ValueError, AttributeError, HTTPError) as err:
message = "Could get authorization server JWKS"
logger.debug("%s. Exception:", message, exc_info=True)
raise SuspiciousOperation(message) from err
jwt = self._decode(jws, public_key_set)
return jwt
def _decrypt(self, encrypted_token, private_key):
"""Decrypt the token encrypted by the Authorization Server (AS).
Resource Server (RS)'s public key is used for encryption, and its private
key is used for decryption. The RS's public key is exposed to the AS via a JWKS endpoint.
Encryption Algorithm and Encoding should be configured to match between the AS
and the RS.
"""
try:
decrypted_token = jose_jwe.decrypt_compact(
encrypted_token,
private_key,
algorithms=[self._encryption_algorithm, self._encryption_encoding],
)
except Exception as err:
message = "Token decryption failed"
logger.debug("%s. Exception:", message, exc_info=True)
raise SuspiciousOperation(message) from err
return decrypted_token
def _decode(self, encoded_token, public_key_set):
"""Decode the token signed by the Authorization Server (AS).
AS's private key is used for signing, and its public key is used for decoding.
The AS public key is exposed via a JWK endpoint.
Signing Algorithm should be configured to match between the AS and the RS.
"""
try:
token = jose_jwt.decode(
encoded_token.plaintext,
public_key_set,
algorithms=[self._signing_algorithm],
)
except ValueError as err:
message = "Token decoding failed"
logger.debug("%s. Exception:", message, exc_info=True)
raise SuspiciousOperation(message) from err
return token
def _verify_claims(self, token):
"""Verify the claims of the token to ensure authentication security.
By verifying these claims, we ensure that the token was issued by a
trusted authorization server and is intended for this specific
resource server. This prevents various types of attacks, such as
token substitution or misuse of tokens issued for different clients.
"""
try:
self._claims_registry.validate(token.claims)
except (InvalidClaimError, InvalidTokenError) as err:
message = "Failed to validate token's claims"
logger.debug("%s. Exception:", message, exc_info=True)
raise SuspiciousOperation(message) from err
return token.claims
class ResourceServerImproperlyConfiguredBackend:
"""Fallback backend for improperly configured Resource Servers."""
def get_or_create_user(self, access_token, id_token, payload):
"""Indicate that the Resource Server is improperly configured."""
raise AuthenticationFailed("Resource Server is improperly configured")
@@ -0,0 +1,95 @@
"""Resource Server Clients classes"""
from django.core.exceptions import ImproperlyConfigured
import requests
from joserfc.jwk import KeySet
class AuthorizationServerClient:
"""Client for interacting with an OAuth 2.0 authorization server.
An authorization server issues access tokens to client applications after authenticating
and obtaining authorization from the resource owner. It also provides endpoints for token
introspection and JSON Web Key Sets (JWKS) to validate and decode tokens.
This client facilitates communication with the authorization server, including:
- Fetching token introspection responses.
- Fetching JSON Web Key Sets (JWKS) for token validation.
- Setting appropriate headers for secure communication as recommended by RFC drafts.
"""
# ruff: noqa: PLR0913 PLR017
# pylint: disable=too-many-positional-arguments
# pylint: disable=too-many-arguments
def __init__(
self,
url,
url_jwks,
url_introspection,
verify_ssl,
timeout,
proxy,
):
if not url or not url_jwks or not url_introspection:
raise ImproperlyConfigured(
"Could not instantiate AuthorizationServerClient, some parameters are missing."
)
self.url = url
self._url_introspection = url_introspection
self._url_jwks = url_jwks
self._verify_ssl = verify_ssl
self._timeout = timeout
self._proxy = proxy
@property
def _introspection_headers(self):
"""Get HTTP header for the introspection request.
Notify the authorization server that we expect a signed and encrypted response
by setting the appropriate 'Accept' header.
This follows the recommendation from the draft RFC:
https://datatracker.ietf.org/doc/html/draft-ietf-oauth-jwt-introspection-response-12.
"""
return {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/token-introspection+jwt",
}
def get_introspection(self, client_id, client_secret, token):
"""Retrieve introspection response about a token."""
response = requests.post(
self._url_introspection,
data={
"client_id": client_id,
"client_secret": client_secret,
"token": token,
},
headers=self._introspection_headers,
verify=self._verify_ssl,
timeout=self._timeout,
proxies=self._proxy,
)
response.raise_for_status()
return response.text
def get_jwks(self):
"""Retrieve Authorization Server JWKS."""
response = requests.get(
self._url_jwks,
verify=self._verify_ssl,
timeout=self._timeout,
proxies=self._proxy,
)
response.raise_for_status()
return response.json()
def import_public_keys(self):
"""Retrieve and import Authorization Server JWKS."""
jwks = self.get_jwks()
public_keys = KeySet.import_key_set(jwks)
return public_keys
+9
View File
@@ -0,0 +1,9 @@
"""Resource Server URL Configuration"""
from django.urls import path
from .views import JWKSView
urlpatterns = [
path("jwks", JWKSView.as_view(), name="resource_server_jwks"),
]
+48
View File
@@ -0,0 +1,48 @@
"""Resource Server utils functions"""
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from joserfc.jwk import JWKRegistry
def import_private_key_from_settings():
"""Import the private key used by the resource server when interacting with the OIDC provider.
This private key is crucial; its public components are exposed in the JWK endpoints,
while its private component is used for decrypting the introspection token retrieved
from the OIDC provider.
By default, we recommend using RSAKey for asymmetric encryption,
known for its strong security features.
Note:
- The function requires the 'OIDC_RS_PRIVATE_KEY_STR' setting to be configured.
- The 'OIDC_RS_ENCRYPTION_KEY_TYPE' and 'OIDC_RS_ENCRYPTION_ALGO' settings can be customized
based on the chosen key type.
Raises:
ImproperlyConfigured: If the private key setting is missing, empty, or incorrect.
Returns:
joserfc.jwk.JWK: The imported private key as a JWK object.
"""
private_key_str = getattr(settings, "OIDC_RS_PRIVATE_KEY_STR", None)
if not private_key_str:
raise ImproperlyConfigured(
"OIDC_RS_PRIVATE_KEY_STR setting is missing or empty."
)
private_key_pem = private_key_str.encode()
try:
private_key = JWKRegistry.import_key(
private_key_pem,
key_type=settings.OIDC_RS_ENCRYPTION_KEY_TYPE,
parameters={"alg": settings.OIDC_RS_ENCRYPTION_ALGO, "use": "enc"},
)
except ValueError as err:
raise ImproperlyConfigured("OIDC_RS_PRIVATE_KEY_STR setting is wrong.") from err
return private_key
+40
View File
@@ -0,0 +1,40 @@
"""Resource Server views"""
from django.core.exceptions import ImproperlyConfigured
from joserfc.jwk import KeySet
from rest_framework.response import Response
from rest_framework.views import APIView
from . import utils
class JWKSView(APIView):
"""
API endpoint for retrieving a JSON Web Keys Set (JWKS).
Returns:
Response: JSON response containing the JWKS data.
"""
authentication_classes = [] # disable authentication
permission_classes = [] # disable permission
def get(self, request):
"""Handle GET requests to retrieve JSON Web Keys Set (JWKS).
Returns:
Response: JSON response containing the JWKS data.
"""
try:
private_key = utils.import_private_key_from_settings()
except (ImproperlyConfigured, ValueError) as err:
return Response({"error": str(err)}, status=500)
try:
jwk = KeySet([private_key]).as_dict(private=False)
except (TypeError, ValueError, AttributeError):
return Response({"error": "Could not load key"}, status=500)
return Response(jwk)
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

@@ -1,14 +1,15 @@
"""Unit tests for the Authentication Backends."""
from django.contrib.auth import get_user_model
from django.core.exceptions import SuspiciousOperation
import pytest
from core import models
from core import factories, models
from core.authentication.backends import OIDCAuthenticationBackend
from core.factories import IdentityFactory
pytestmark = pytest.mark.django_db
User = get_user_model()
def test_authentication_getter_existing_user_no_email(
@@ -19,26 +20,19 @@ def test_authentication_getter_existing_user_no_email(
"""
klass = OIDCAuthenticationBackend()
# Create a user and its identity
identity = IdentityFactory(name=None)
# Create multiple identities for a user
for _ in range(5):
IdentityFactory(user=identity.user)
user = factories.UserFactory()
def get_userinfo_mocked(*args):
return {"sub": identity.sub}
return {"sub": user.sub}
monkeypatch.setattr(OIDCAuthenticationBackend, "get_userinfo", get_userinfo_mocked)
with django_assert_num_queries(1):
user = klass.get_or_create_user(
authenticated_user = klass.get_or_create_user(
access_token="test-token", id_token=None, payload=None
)
identity.refresh_from_db()
assert user == identity.user
assert user == authenticated_user
def test_authentication_getter_existing_user_with_email(
@@ -48,19 +42,12 @@ def test_authentication_getter_existing_user_with_email(
When the user's info contains an email and targets an existing user,
"""
klass = OIDCAuthenticationBackend()
identity = IdentityFactory(name="John Doe")
# Create multiple identities for a user
for _ in range(5):
IdentityFactory(user=identity.user)
assert models.User.objects.count() == 1
user = factories.UserFactory(name="John Doe")
def get_userinfo_mocked(*args):
return {
"sub": identity.sub,
"email": identity.email,
"sub": user.sub,
"email": user.email,
"first_name": "John",
"last_name": "Doe",
}
@@ -69,11 +56,11 @@ def test_authentication_getter_existing_user_with_email(
# Only 1 query because email and names have not changed
with django_assert_num_queries(1):
user = klass.get_or_create_user(
authenticated_user = klass.get_or_create_user(
access_token="test-token", id_token=None, payload=None
)
assert models.User.objects.get() == user
assert user == authenticated_user
@pytest.mark.parametrize(
@@ -89,23 +76,14 @@ def test_authentication_getter_existing_user_change_fields(
first_name, last_name, email, django_assert_num_queries, monkeypatch
):
"""
It should update the email or name fields on the identity when they change.
The email on the user should not be changed.
It should update the email or name fields on the user when they change.
"""
klass = OIDCAuthenticationBackend()
identity = IdentityFactory(name="John Doe", email="john.doe@example.com")
user_email = identity.user.admin_email
# Create multiple identities for a user
for _ in range(5):
IdentityFactory(user=identity.user)
assert models.User.objects.count() == 1
user = factories.UserFactory(name="John Doe", email="john.doe@example.com")
def get_userinfo_mocked(*args):
return {
"sub": identity.sub,
"sub": user.sub,
"email": email,
"first_name": first_name,
"last_name": last_name,
@@ -114,24 +92,74 @@ def test_authentication_getter_existing_user_change_fields(
monkeypatch.setattr(OIDCAuthenticationBackend, "get_userinfo", get_userinfo_mocked)
# One and only one additional update query when a field has changed
with django_assert_num_queries(2):
authenticated_user = klass.get_or_create_user(
access_token="test-token", id_token=None, payload=None
)
assert user == authenticated_user
user.refresh_from_db()
assert user.email == email
assert user.name == f"{first_name:s} {last_name:s}"
def test_authentication_getter_existing_user_via_email(
django_assert_num_queries, monkeypatch
):
"""
If an existing user doesn't match the sub but matches the email,
the user should be returned.
"""
klass = OIDCAuthenticationBackend()
db_user = factories.UserFactory()
def get_userinfo_mocked(*args):
return {"sub": "123", "email": db_user.email}
monkeypatch.setattr(OIDCAuthenticationBackend, "get_userinfo", get_userinfo_mocked)
with django_assert_num_queries(2):
user = klass.get_or_create_user(
access_token="test-token", id_token=None, payload=None
)
identity.refresh_from_db()
assert identity.email == email
assert identity.name == f"{first_name:s} {last_name:s}"
assert user == db_user
assert models.User.objects.count() == 1
assert user == identity.user
assert user.admin_email == user_email
def test_authentication_getter_existing_user_no_fallback_to_email(
settings, monkeypatch
):
"""
When the "OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION" setting is set to False,
the system should not match users by email, even if the email matches.
"""
klass = OIDCAuthenticationBackend()
db_user = factories.UserFactory()
# Set the setting to False
settings.OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION = False
def get_userinfo_mocked(*args):
return {"sub": "123", "email": db_user.email}
monkeypatch.setattr(OIDCAuthenticationBackend, "get_userinfo", get_userinfo_mocked)
user = klass.get_or_create_user(
access_token="test-token", id_token=None, payload=None
)
# Since the sub doesn't match, it should create a new user
assert models.User.objects.count() == 2
assert user != db_user
assert user.sub == "123"
def test_authentication_getter_new_user_no_email(monkeypatch):
"""
If no user matches the user's info sub, a user should be created.
User's info doesn't contain an email, created user's email should be empty.
User's info doesn't contain an email/name, created user's email/name should be empty.
"""
klass = OIDCAuthenticationBackend()
@@ -144,11 +172,9 @@ def test_authentication_getter_new_user_no_email(monkeypatch):
access_token="test-token", id_token=None, payload=None
)
identity = user.identities.get()
assert identity.sub == "123"
assert identity.email is None
assert user.admin_email is None
assert user.sub == "123"
assert user.email is None
assert user.name is None
assert user.password == "!"
assert models.User.objects.count() == 1
@@ -156,11 +182,9 @@ def test_authentication_getter_new_user_no_email(monkeypatch):
def test_authentication_getter_new_user_with_email(monkeypatch):
"""
If no user matches the user's info sub, a user should be created.
User's email and name should be set on the identity.
The "email" field on the User model should not be set as it is reserved for staff users.
User's email and name should be set on the user.
"""
klass = OIDCAuthenticationBackend()
email = "people@example.com"
def get_userinfo_mocked(*args):
@@ -172,12 +196,10 @@ def test_authentication_getter_new_user_with_email(monkeypatch):
access_token="test-token", id_token=None, payload=None
)
identity = user.identities.get()
assert identity.sub == "123"
assert identity.email == email
assert identity.name == "John Doe"
assert user.admin_email is None
assert user.sub == "123"
assert user.email == email
assert user.name == "John Doe"
assert user.password == "!"
assert models.User.objects.count() == 1
@@ -202,3 +224,63 @@ def test_models_oidc_user_getter_invalid_token(django_assert_num_queries, monkey
klass.get_or_create_user(access_token="test-token", id_token=None, payload=None)
assert models.User.objects.exists() is False
def test_authentication_getter_existing_disabled_user_via_sub(
django_assert_num_queries, monkeypatch
):
"""
If an existing user matches the sub but is disabled,
an error should be raised and a user should not be created.
"""
klass = OIDCAuthenticationBackend()
db_user = factories.UserFactory(name="John Doe", is_active=False)
def get_userinfo_mocked(*args):
return {
"sub": db_user.sub,
"email": db_user.email,
"first_name": "John",
"last_name": "Doe",
}
monkeypatch.setattr(OIDCAuthenticationBackend, "get_userinfo", get_userinfo_mocked)
with (
django_assert_num_queries(1),
pytest.raises(SuspiciousOperation, match="User account is disabled"),
):
klass.get_or_create_user(access_token="test-token", id_token=None, payload=None)
assert models.User.objects.count() == 1
def test_authentication_getter_existing_disabled_user_via_email(
django_assert_num_queries, monkeypatch
):
"""
If an existing user does not matches the sub but match the email and is disabled,
an error should be raised and a user should not be created.
"""
klass = OIDCAuthenticationBackend()
db_user = factories.UserFactory(name="John Doe", is_active=False)
def get_userinfo_mocked(*args):
return {
"sub": "random",
"email": db_user.email,
"first_name": "John",
"last_name": "Doe",
}
monkeypatch.setattr(OIDCAuthenticationBackend, "get_userinfo", get_userinfo_mocked)
with (
django_assert_num_queries(2),
pytest.raises(SuspiciousOperation, match="User account is disabled"),
):
klass.get_or_create_user(access_token="test-token", id_token=None, payload=None)
assert models.User.objects.count() == 1
@@ -38,8 +38,7 @@ def test_view_logout_anonymous():
def test_view_logout(mocked_oidc_logout_url):
"""Authenticated users should be redirected to OIDC provider for logout."""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -60,8 +59,7 @@ def test_view_logout(mocked_oidc_logout_url):
def test_view_logout_no_oidc_provider(mocked_oidc_logout_url):
"""Authenticated users should be logged out when no OIDC provider is available."""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -96,8 +94,7 @@ def test_view_logout_callback_anonymous():
def test_view_logout_persist_state(initial_oidc_states):
"""State value should be persisted in session's data."""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
request = RequestFactory().request()
request.user = user
@@ -128,8 +125,7 @@ def test_view_logout_construct_oidc_logout_url(
):
"""Should construct the logout URL to initiate the logout flow with the OIDC provider."""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
request = RequestFactory().request()
request.user = user
@@ -159,8 +155,7 @@ def test_view_logout_construct_oidc_logout_url_none_id_token():
"""If no ID token is available in the session,
the user should be redirected to the final URL."""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
request = RequestFactory().request()
request.user = user
@@ -180,8 +175,7 @@ def test_view_logout_construct_oidc_logout_url_none_id_token():
def test_view_logout_callback_wrong_state(initial_state):
"""Should raise an error if OIDC state doesn't match session data."""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
request = RequestFactory().request()
request.user = user
@@ -207,8 +201,7 @@ def test_view_logout_callback_wrong_state(initial_state):
def test_view_logout_callback():
"""If state matches, callback should clear OIDC state and redirects."""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
request = RequestFactory().get("/logout-callback/", data={"state": "mocked_state"})
request.user = user
@@ -0,0 +1,447 @@
"""
Test for the Resource Server (RS) Backend.
"""
# pylint: disable=W0212
from logging import Logger
from unittest.mock import Mock, patch
from django.contrib import auth
from django.core.exceptions import SuspiciousOperation
from django.test.utils import override_settings
import pytest
from joserfc.errors import InvalidClaimError, InvalidTokenError
from joserfc.jwt import JWTClaimsRegistry
from requests.exceptions import HTTPError
from core.resource_server.backend import ResourceServerBackend
@pytest.fixture(name="mock_authorization_server")
def fixture_mock_authorization_server():
"""Mock an Authorization Server client."""
mock_server = Mock()
mock_server.url = "https://auth.server.com"
return mock_server
@pytest.fixture(name="mock_token")
def fixture_mock_token():
"""Mock a token"""
mock_token = Mock()
mock_token.claims = {"sub": "user123", "iss": "https://auth.server.com"}
return mock_token
@pytest.fixture(name="resource_server_backend")
def fixture_resource_server_backend(settings, mock_authorization_server):
"""Generate a Resource Server backend."""
settings.OIDC_RS_CLIENT_ID = "client_id"
settings.OIDC_RS_CLIENT_SECRET = "client_secret"
settings.OIDC_RS_ENCRYPTION_ENCODING = "A256GCM"
settings.OIDC_RS_ENCRYPTION_ALGO = "RSA-OAEP"
settings.OIDC_RS_SIGNING_ALGO = "ES256"
settings.OIDC_RS_SCOPES = ["groups"]
return ResourceServerBackend(mock_authorization_server)
@override_settings(OIDC_RS_CLIENT_ID="client_id")
@override_settings(OIDC_RS_CLIENT_SECRET="client_secret")
@override_settings(OIDC_RS_ENCRYPTION_ENCODING="A256GCM")
@override_settings(OIDC_RS_ENCRYPTION_ALGO="RSA-OAEP")
@override_settings(OIDC_RS_SIGNING_ALGO="RS256")
@override_settings(OIDC_RS_SCOPES=["scopes"])
@patch.object(auth, "get_user_model", return_value="foo")
def test_backend_initialization(mock_get_user_model, mock_authorization_server):
"""Test the ResourceServerBackend initialization."""
backend = ResourceServerBackend(mock_authorization_server)
mock_get_user_model.assert_called_once()
assert backend.UserModel == "foo"
assert backend._client_id == "client_id"
assert backend._client_secret == "client_secret"
assert backend._encryption_encoding == "A256GCM"
assert backend._encryption_algorithm == "RSA-OAEP"
assert backend._signing_algorithm == "RS256"
assert backend._scopes == ["scopes"]
assert backend._authorization_server_client == mock_authorization_server
assert isinstance(backend._claims_registry, JWTClaimsRegistry)
assert backend._claims_registry.options == {
"iss": {"essential": True, "value": "https://auth.server.com"},
"aud": {"essential": True, "value": "client_id"},
"token_introspection": {"essential": True},
}
@patch.object(ResourceServerBackend, "get_user", return_value="user")
def test_get_or_create_user(mock_get_user, resource_server_backend):
"""Test 'get_or_create_user' method."""
access_token = "access_token"
res = resource_server_backend.get_or_create_user(access_token, None, None)
mock_get_user.assert_called_once_with(access_token)
assert res == "user"
def test_verify_claims_success(resource_server_backend, mock_token):
"""Test '_verify_claims' method with a successful response."""
with patch.object(
resource_server_backend._claims_registry, "validate"
) as mock_validate:
resource_server_backend._verify_claims(mock_token)
mock_validate.assert_called_once_with(mock_token.claims)
def test_verify_claims_invalid_claim_error(resource_server_backend, mock_token):
"""Test '_verify_claims' method with an invalid claim error."""
with patch.object(
resource_server_backend._claims_registry, "validate"
) as mock_validate:
mock_validate.side_effect = InvalidClaimError("claim_name")
expected_message = "Failed to validate token's claims"
with patch.object(Logger, "debug") as mock_logger_debug:
with pytest.raises(SuspiciousOperation, match=expected_message):
resource_server_backend._verify_claims(mock_token)
mock_logger_debug.assert_called_once_with(
"%s. Exception:", expected_message, exc_info=True
)
def test_verify_claims_invalid_token_error(resource_server_backend, mock_token):
"""Test '_verify_claims' method with an invalid token error."""
with patch.object(
resource_server_backend._claims_registry, "validate"
) as mock_validate:
mock_validate.side_effect = InvalidTokenError
expected_message = "Failed to validate token's claims"
with patch.object(Logger, "debug") as mock_logger_debug:
with pytest.raises(SuspiciousOperation, match=expected_message):
resource_server_backend._verify_claims(mock_token)
mock_logger_debug.assert_called_once_with(
"%s. Exception:", expected_message, exc_info=True
)
def test_decode_success(resource_server_backend):
"""Test '_decode' method with a successful response."""
encoded_token = Mock()
encoded_token.plaintext = "valid_encoded_token"
public_key_set = Mock()
expected_decoded_token = {"sub": "user123"}
with patch(
"joserfc.jwt.decode", return_value=expected_decoded_token
) as mock_decode:
decoded_token = resource_server_backend._decode(encoded_token, public_key_set)
mock_decode.assert_called_once_with(
"valid_encoded_token", public_key_set, algorithms=["ES256"]
)
assert decoded_token == expected_decoded_token
def test_decode_failure(resource_server_backend):
"""Test '_decode' method with a ValueError"""
encoded_token = Mock()
encoded_token.plaintext = "invalid_encoded_token"
public_key_set = Mock()
with patch("joserfc.jwt.decode", side_effect=ValueError):
with patch.object(Logger, "debug") as mock_logger_debug:
with pytest.raises(SuspiciousOperation, match="Token decoding failed"):
resource_server_backend._decode(encoded_token, public_key_set)
mock_logger_debug.assert_called_once_with(
"%s. Exception:", "Token decoding failed", exc_info=True
)
def test_decrypt_success(resource_server_backend):
"""Test '_decrypt' method with a successful response."""
encrypted_token = "valid_encrypted_token"
private_key = "private_key"
expected_decrypted_token = {"sub": "user123"}
with patch(
"joserfc.jwe.decrypt_compact", return_value=expected_decrypted_token
) as mock_decrypt:
decrypted_token = resource_server_backend._decrypt(encrypted_token, private_key)
mock_decrypt.assert_called_once_with(
encrypted_token, private_key, algorithms=["RSA-OAEP", "A256GCM"]
)
assert decrypted_token == expected_decrypted_token
def test_decrypt_failure(resource_server_backend):
"""Test '_decrypt' method with an Exception."""
encrypted_token = "invalid_encrypted_token"
private_key = "private_key"
with patch(
"joserfc.jwe.decrypt_compact", side_effect=Exception("Decryption error")
):
expected_message = "Token decryption failed"
with patch.object(Logger, "debug") as mock_logger_debug:
with pytest.raises(SuspiciousOperation, match=expected_message):
resource_server_backend._decrypt(encrypted_token, private_key)
mock_logger_debug.assert_called_once_with(
"%s. Exception:", expected_message, exc_info=True
)
@patch(
"core.resource_server.utils.import_private_key_from_settings",
return_value="private_key",
)
# pylint: disable=unused-argument
def test_introspect_success(
mock_import_private_key_from_settings, resource_server_backend
):
"""Test '_introspect' method with a successful response."""
token = "valid_token"
jwe = "valid_jwe"
jws = "valid_jws"
jwt = {"sub": "user123"}
resource_server_backend._authorization_server_client.get_introspection = Mock(
return_value=jwe
)
resource_server_backend._decrypt = Mock(return_value=jws)
resource_server_backend._authorization_server_client.import_public_keys = Mock(
return_value="public_key_set"
)
resource_server_backend._decode = Mock(return_value=jwt)
result = resource_server_backend._introspect(token)
assert result == jwt
resource_server_backend._authorization_server_client.get_introspection.assert_called_once_with(
"client_id", "client_secret", token
)
resource_server_backend._decrypt.assert_called_once_with(
jwe, private_key="private_key"
)
resource_server_backend._authorization_server_client.import_public_keys.assert_called_once()
resource_server_backend._decode.assert_called_once_with(jws, "public_key_set")
def test_introspect_introspection_failure(resource_server_backend):
"""Test '_introspect' method when introspection to the AS fails."""
token = "invalid_token"
resource_server_backend._authorization_server_client.get_introspection.side_effect = HTTPError(
"Introspection error"
)
with patch.object(Logger, "debug") as mock_logger_debug:
expected_message = "Could not fetch introspection"
with pytest.raises(SuspiciousOperation, match=expected_message):
resource_server_backend._introspect(token)
mock_logger_debug.assert_called_once_with(
"%s. Exception:", expected_message, exc_info=True
)
@patch(
"core.resource_server.utils.import_private_key_from_settings",
return_value="private_key",
)
# pylint: disable=unused-argument
def test_introspect_public_key_import_failure(
mock_import_private_key_from_settings, resource_server_backend
):
"""Test '_introspect' method when fetching AS's jwks fails."""
token = "valid_token"
jwe = "valid_jwe"
jws = "valid_jws"
resource_server_backend._authorization_server_client.get_introspection = Mock(
return_value=jwe
)
resource_server_backend._decrypt = Mock(return_value=jws)
resource_server_backend._authorization_server_client.import_public_keys.side_effect = HTTPError(
"Public key error"
)
with patch.object(Logger, "debug") as mock_logger_debug:
expected_message = "Could get authorization server JWKS"
with pytest.raises(SuspiciousOperation, match=expected_message):
resource_server_backend._introspect(token)
mock_logger_debug.assert_called_once_with(
"%s. Exception:", expected_message, exc_info=True
)
def test_verify_user_info_success(resource_server_backend):
"""Test '_verify_user_info' with a successful response."""
introspection_response = {"active": True, "scope": "groups"}
result = resource_server_backend._verify_user_info(introspection_response)
assert result == introspection_response
def test_verify_user_info_inactive(resource_server_backend):
"""Test '_verify_user_info' with an inactive introspection response."""
introspection_response = {"active": False, "scope": "groups"}
expected_message = "Introspection response is not active."
with patch.object(Logger, "debug") as mock_logger_debug:
with pytest.raises(SuspiciousOperation, match=expected_message):
resource_server_backend._verify_user_info(introspection_response)
mock_logger_debug.assert_called_once_with(expected_message)
def test_verify_user_info_wrong_scopes(resource_server_backend):
"""Test '_verify_user_info' with wrong requested scopes."""
introspection_response = {"active": True, "scope": "wrong-scopes"}
expected_message = "Introspection response contains any required scopes."
with patch.object(Logger, "debug") as mock_logger_debug:
with pytest.raises(SuspiciousOperation, match=expected_message):
resource_server_backend._verify_user_info(introspection_response)
mock_logger_debug.assert_called_once_with(expected_message)
def test_get_user_success(resource_server_backend):
"""Test '_get_user' with a successful response."""
access_token = "valid_access_token"
mock_jwt = Mock()
mock_claims = {"token_introspection": {"sub": "user123"}}
mock_user = Mock()
resource_server_backend._introspect = Mock(return_value=mock_jwt)
resource_server_backend._verify_claims = Mock(return_value=mock_claims)
resource_server_backend._verify_user_info = Mock(
return_value=mock_claims["token_introspection"]
)
resource_server_backend.UserModel.objects.get = Mock(return_value=mock_user)
user = resource_server_backend.get_user(access_token)
assert user == mock_user
resource_server_backend._introspect.assert_called_once_with(access_token)
resource_server_backend._verify_claims.assert_called_once_with(mock_jwt)
resource_server_backend._verify_user_info.assert_called_once_with(
mock_claims["token_introspection"]
)
resource_server_backend.UserModel.objects.get.assert_called_once_with(sub="user123")
def test_get_user_could_not_introspect(resource_server_backend):
"""Test '_get_user' with introspection failing."""
access_token = "valid_access_token"
resource_server_backend._introspect = Mock(
side_effect=SuspiciousOperation("Invalid jwt")
)
resource_server_backend._verify_claims = Mock()
resource_server_backend._verify_user_info = Mock()
with pytest.raises(SuspiciousOperation, match="Invalid jwt"):
resource_server_backend.get_user(access_token)
resource_server_backend._introspect.assert_called_once_with(access_token)
resource_server_backend._verify_claims.assert_not_called()
resource_server_backend._verify_user_info.assert_not_called()
def test_get_user_invalid_introspection_response(resource_server_backend):
"""Test '_get_user' with an invalid introspection response."""
access_token = "valid_access_token"
mock_jwt = Mock()
resource_server_backend._introspect = Mock(return_value=mock_jwt)
resource_server_backend._verify_claims = Mock(
side_effect=SuspiciousOperation("Invalid claims")
)
resource_server_backend._verify_user_info = Mock()
with pytest.raises(SuspiciousOperation, match="Invalid claims"):
resource_server_backend.get_user(access_token)
resource_server_backend._introspect.assert_called_once_with(access_token)
resource_server_backend._verify_claims.assert_called_once_with(mock_jwt)
resource_server_backend._verify_user_info.assert_not_called()
def test_get_user_user_not_found(resource_server_backend):
"""Test '_get_user' if the user is not found."""
access_token = "valid_access_token"
mock_jwt = Mock()
mock_claims = {"token_introspection": {"sub": "user123"}}
resource_server_backend._introspect = Mock(return_value=mock_jwt)
resource_server_backend._verify_claims = Mock(return_value=mock_claims)
resource_server_backend._verify_user_info = Mock(
return_value=mock_claims["token_introspection"]
)
resource_server_backend.UserModel.objects.get = Mock(
side_effect=resource_server_backend.UserModel.DoesNotExist
)
with patch.object(Logger, "debug") as mock_logger_debug:
user = resource_server_backend.get_user(access_token)
assert user is None
resource_server_backend._introspect.assert_called_once_with(access_token)
resource_server_backend._verify_claims.assert_called_once_with(mock_jwt)
resource_server_backend._verify_user_info.assert_called_once_with(
mock_claims["token_introspection"]
)
resource_server_backend.UserModel.objects.get.assert_called_once_with(
sub="user123"
)
mock_logger_debug.assert_called_once_with(
"Login failed: No user with %s found", "user123"
)
def test_get_user_no_user_identification(resource_server_backend):
"""Test '_get_user' if the response miss a user identification."""
access_token = "valid_access_token"
mock_jwt = Mock()
mock_claims = {"token_introspection": {}}
resource_server_backend._introspect = Mock(return_value=mock_jwt)
resource_server_backend._verify_claims = Mock(return_value=mock_claims)
resource_server_backend._verify_user_info = Mock(
return_value=mock_claims["token_introspection"]
)
expected_message = "User info contained no recognizable user identification"
with patch.object(Logger, "debug") as mock_logger_debug:
with pytest.raises(SuspiciousOperation, match=expected_message):
resource_server_backend.get_user(access_token)
mock_logger_debug.assert_called_once_with(expected_message)
@@ -0,0 +1,187 @@
"""
Test for the Resource Server (RS) clients classes.
"""
# pylint: disable=W0212
from unittest.mock import MagicMock, patch
import pytest
from joserfc.jwk import KeySet, RSAKey
from requests.exceptions import HTTPError
from core.resource_server.clients import AuthorizationServerClient
@pytest.fixture(name="client")
def fixture_client():
"""Generate an Authorization Server client."""
return AuthorizationServerClient(
url="https://auth.example.com/api/v2",
url_jwks="https://auth.example.com/api/v2/jwks",
url_introspection="https://auth.example.com/api/v2/introspect",
verify_ssl=True,
timeout=5,
proxy=None,
)
def test_authorization_server_client_initialization():
"""Test the AuthorizationServerClient initialization."""
new_client = AuthorizationServerClient(
url="https://auth.example.com/api/v2",
url_jwks="https://auth.example.com/api/v2/jwks",
url_introspection="https://auth.example.com/api/v2/checktoken/foo",
verify_ssl=True,
timeout=5,
proxy=None,
)
assert new_client.url == "https://auth.example.com/api/v2"
assert (
new_client._url_introspection
== "https://auth.example.com/api/v2/checktoken/foo"
)
assert new_client._url_jwks == "https://auth.example.com/api/v2/jwks"
assert new_client._verify_ssl is True
assert new_client._timeout == 5
assert new_client._proxy is None
def test_introspection_headers(client):
"""Test the introspection headers to ensure they match the expected values."""
assert client._introspection_headers == {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/token-introspection+jwt",
}
@patch("requests.post")
def test_get_introspection_success(mock_post, client):
"""Test 'get_introspection' method with a successful response."""
mock_response = MagicMock()
mock_response.raise_for_status.return_value = None
mock_response.text = "introspection response"
mock_post.return_value = mock_response
result = client.get_introspection("client_id", "client_secret", "token")
assert result == "introspection response"
mock_post.assert_called_once_with(
"https://auth.example.com/api/v2/introspect",
data={
"client_id": "client_id",
"client_secret": "client_secret",
"token": "token",
},
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/token-introspection+jwt",
},
verify=True,
timeout=5,
proxies=None,
)
@patch("requests.post", side_effect=HTTPError())
# pylint: disable=(unused-argument
def test_get_introspection_error(mock_post, client):
"""Test 'get_introspection' method with an HTTPError."""
with pytest.raises(HTTPError):
client.get_introspection("client_id", "client_secret", "token")
@patch("requests.get")
def test_get_jwks_success(mock_get, client):
"""Test 'get_jwks' method with a successful response."""
mock_response = MagicMock()
mock_response.raise_for_status.return_value = None
mock_response.json.return_value = {"jwks": "foo"}
mock_get.return_value = mock_response
result = client.get_jwks()
assert result == {"jwks": "foo"}
mock_get.assert_called_once_with(
"https://auth.example.com/api/v2/jwks",
verify=client._verify_ssl,
timeout=client._timeout,
proxies=client._proxy,
)
@patch("requests.get")
def test_get_jwks_error(mock_get, client):
"""Test 'get_jwks' method with an HTTPError."""
mock_response = MagicMock()
mock_response.raise_for_status.side_effect = HTTPError(
response=MagicMock(status=500)
)
mock_get.return_value = mock_response
with pytest.raises(HTTPError):
client.get_jwks()
@patch("requests.get")
def test_import_public_keys_valid(mock_get, client):
"""Test 'import_public_keys' method with a successful response."""
mocked_key = RSAKey.generate_key(2048)
mock_response = MagicMock()
mock_response.raise_for_status.return_value = None
mock_response.json.return_value = {"keys": [mocked_key.as_dict()]}
mock_get.return_value = mock_response
response = client.import_public_keys()
assert isinstance(response, KeySet)
assert response.as_dict() == KeySet([mocked_key]).as_dict()
@patch("requests.get")
def test_import_public_keys_http_error(mock_get, client):
"""Test 'import_public_keys' method with an HTTPError."""
mock_response = MagicMock()
mock_response.raise_for_status.side_effect = HTTPError(
response=MagicMock(status=500)
)
mock_get.return_value = mock_response
with pytest.raises(HTTPError):
client.import_public_keys()
@patch("requests.get")
def test_import_public_keys_empty_jwks(mock_get, client):
"""Test 'import_public_keys' method with empty keys response."""
mock_response = MagicMock()
mock_response.raise_for_status.return_value = None
mock_response.json.return_value = {"keys": []}
mock_get.return_value = mock_response
response = client.import_public_keys()
assert isinstance(response, KeySet)
assert response.as_dict() == {"keys": []}
@patch("requests.get")
def test_import_public_keys_invalid_jwks(mock_get, client):
"""Test 'import_public_keys' method with invalid keys response."""
mock_response = MagicMock()
mock_response.raise_for_status.return_value = None
mock_response.json.return_value = {"keys": [{"foo": "foo"}]}
mock_get.return_value = mock_response
with pytest.raises(ValueError):
client.import_public_keys()
@@ -0,0 +1,88 @@
"""
Test for the Resource Server (RS) utils functions.
"""
from django.core.exceptions import ImproperlyConfigured
from django.test.utils import override_settings
import pytest
from joserfc.jwk import ECKey, RSAKey
from core.resource_server.utils import import_private_key_from_settings
PRIVATE_KEY_STR_MOCKED = """-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC3boG1kwEGUYL+
U58RPrVToIsF9jHB64S6WJIIInPmAclBciXFb6BWG11mbRIgo8ha3WVnC/tGHbXb
ndiKdrH2vKHOsDhV9AmgHgNgWaUK9L0uuKEb/xMLePYWsYlgzcQJx8RZY7RQyWqE
20WfzFxeuCE7QMb6VXSOgwQMnJsKocguIh3VCI9RIBq3B1kdgW35AD63YKOygmGx
qjcWwbjhKLvkF7LpBdlyAEzOKqg4T5uCcHMfksMW2+foTJx70RrZM/KHU+Zysuw7
uhhVsgPBG+CsqBSjHQhs7jzymqxtQAfe1FkrCRxOq5Pv2Efr7kgtVSkJJiX3KutM
vnWuEypxAgMBAAECggEAGqKS9pbrN+vnmb7yMsqYgVVnQn0aggZNHlLkl4ZLLnuV
aemlhur7zO0JzajqUC+AFQOfaQxiFu8S/FoJ+qccFdATrcPEVmTKbgPVqSyzLKlX
fByGll5eOVT95NMwN8yBGgt2HSW/ZditXS/KxxahVgamGqjAC9MTSutGz/8Ae1U+
DNDBJCc6RAqu3T02tV9A2pSpVC1rSktDMpLUTscnsfxpaEQATd9DJUcHEvIwoX8q
GJpycPEhNhdPXqpln5SoMHcf/zS5ssF/Mce0lJJXYyE0LnEk9X12jMWyBqmLqXUY
cKLyynaFbis0DpQppwKx2y8GpL76k+Ci4dOHIvFknQKBgQDj/2WRMcWOvfBrggzj
FHpcme2gSo5A5c0CVyI+Xkf1Zab6UR6T7GiImEoj9tq0+o2WEix9rwoypgMBq8rz
/rrJAPSZjgv6z71k4EnO2FIB5R03vQmoBRCN8VlgvLM0xv52zyjV4Wx66Q4MDjyH
EgkpHyB0FzRZh0UzhnE/pYSetQKBgQDN9eLB1nA4CBSr1vMGNfQyfBQl3vpO9EP4
VSS3KnUqCIjJeLu682Ylu7SFxcJAfzUpy5S43hEvcuJsagsVKfmCAGcYZs9/xq3I
vzYyhaEOS5ezNxLSh4+yCNBPlmrmDyoazag0t8H8YQFBN6BVcxbATHqdWGUhIhYN
eEpEMOh2TQKBgGBr7kRNTENlyHtu8IxIaMcowfn8DdUcWmsW9oBx1vTNHKTYEZp1
bG/4F8LF7xCCtcY1wWMV17Y7xyG5yYcOv2eqY8dc72wO1wYGZLB5g5URlB2ycJcC
LVIaM7ZZl2BGl+8fBSIOx5XjYfFvQ+HLmtwtMchm19jVAEseHF7SXRfRAoGAK15j
aT2mU6Yf9C9G7T/fM+I8u9zACHAW/+ut14PxN/CkHQh3P16RW9CyqpiB1uLyZuKf
Zm4cYElotDuAKey0xVMgYlsDxnwni+X3m5vX1hLE1s/5/qrc7zg75QZfbCI1U3+K
s88d4e7rPLhh4pxhZgy0pP1ADkIHMr7ppIJH8OECgYEApNfbgsJVPAMzucUhJoJZ
OmZHbyCtJvs4b+zxnmhmSbopifNCgS4zjXH9qC7tsUph1WE6L2KXvtApHGD5H4GQ
IH5em4M/pHIcsqCi1qggBMbdvzHBUtC3R4sK0CpEFHlN+Y59aGazidcN2FPupNJv
MbyqKyC6DAzv4jEEhHaN7oY=
-----END PRIVATE KEY-----
"""
@override_settings(OIDC_RS_PRIVATE_KEY_STR=PRIVATE_KEY_STR_MOCKED)
@pytest.mark.parametrize("mocked_private_key", [None, ""])
def test_import_private_key_from_settings_missing_or_empty_key(
settings, mocked_private_key
):
"""Should raise an exception if the settings 'OIDC_RS_PRIVATE_KEY_STR' is missing or empty."""
settings.OIDC_RS_PRIVATE_KEY_STR = mocked_private_key
with pytest.raises(
ImproperlyConfigured,
match="OIDC_RS_PRIVATE_KEY_STR setting is missing or empty.",
):
import_private_key_from_settings()
@pytest.mark.parametrize("mocked_private_key", ["123", "foo", "invalid_key"])
@override_settings(OIDC_RS_PRIVATE_KEY_STR=PRIVATE_KEY_STR_MOCKED)
@override_settings(OIDC_RS_ENCRYPTION_KEY_TYPE="RSA")
@override_settings(OIDC_RS_ENCRYPTION_ALGO="RS256")
def test_import_private_key_from_settings_incorrect_key(settings, mocked_private_key):
"""Should raise an exception if the setting 'OIDC_RS_PRIVATE_KEY_STR' has an incorrect value."""
settings.OIDC_RS_PRIVATE_KEY_STR = mocked_private_key
with pytest.raises(
ImproperlyConfigured, match="OIDC_RS_PRIVATE_KEY_STR setting is wrong."
):
import_private_key_from_settings()
@override_settings(OIDC_RS_PRIVATE_KEY_STR=PRIVATE_KEY_STR_MOCKED)
@override_settings(OIDC_RS_ENCRYPTION_KEY_TYPE="RSA")
@override_settings(OIDC_RS_ENCRYPTION_ALGO="RS256")
def test_import_private_key_from_settings_success_rsa_key():
"""Should import private key string as an RSA key."""
private_key = import_private_key_from_settings()
assert isinstance(private_key, RSAKey)
@override_settings(OIDC_RS_PRIVATE_KEY_STR=PRIVATE_KEY_STR_MOCKED)
@override_settings(OIDC_RS_ENCRYPTION_KEY_TYPE="EC")
@override_settings(OIDC_RS_ENCRYPTION_ALGO="ES256")
def test_import_private_key_from_settings_success_ec_key():
"""Should import private key string as an EC key."""
private_key = import_private_key_from_settings()
assert isinstance(private_key, ECKey)
@@ -0,0 +1,70 @@
"""
Tests for the Resource Server (RS) Views.
"""
from unittest import mock
from django.core.exceptions import ImproperlyConfigured
from django.urls import reverse
import pytest
from joserfc.jwk import RSAKey
from rest_framework.test import APIClient
pytestmark = pytest.mark.django_db
@mock.patch("core.resource_server.utils.import_private_key_from_settings")
def test_view_jwks_valid_public_key(mock_import_private_key_from_settings):
"""JWKs endpoint should return a set of valid Json Web Key"""
mocked_key = RSAKey.generate_key(2048)
mock_import_private_key_from_settings.return_value = mocked_key
url = reverse("resource_server_jwks")
response = APIClient().get(url)
mock_import_private_key_from_settings.assert_called_once()
assert response.status_code == 200
assert response["Content-Type"] == "application/json"
jwks = response.json()
assert jwks == {"keys": [mocked_key.as_dict(private=False)]}
# Security checks to make sure no details from the private key are exposed
private_details = ["d", "p", "q", "dp", "dq", "qi", "oth", "r", "t"]
assert all(
private_detail not in jwks["keys"][0].keys()
for private_detail in private_details
)
@mock.patch("core.resource_server.utils.import_private_key_from_settings")
def test_view_jwks_invalid_private_key(mock_import_private_key_from_settings):
"""JWKS endpoint should return a proper exception when loading keys fails."""
mock_import_private_key_from_settings.return_value = "wrong_key"
url = reverse("resource_server_jwks")
response = APIClient().get(url)
mock_import_private_key_from_settings.assert_called_once()
assert response.status_code == 500
assert response.json() == {"error": "Could not load key"}
@mock.patch("core.resource_server.utils.import_private_key_from_settings")
def test_view_jwks_missing_private_key(mock_import_private_key_from_settings):
"""JWKS endpoint should return a proper exception when private key is missing."""
mock_import_private_key_from_settings.side_effect = ImproperlyConfigured("foo.")
url = reverse("resource_server_jwks")
response = APIClient().get(url)
mock_import_private_key_from_settings.assert_called_once()
assert response.status_code == 500
assert response.json() == {"error": "foo."}
@@ -33,7 +33,7 @@ def test_openapi_client_schema():
)
assert output.getvalue() == ""
response = Client().get("/v1.0/swagger.json")
response = Client().get("/api/v1.0/swagger.json")
assert response.status_code == 200
with open(
@@ -41,9 +41,7 @@ def test_api_team_accesses_create_authenticated_unrelated():
Authenticated users should not be allowed to create team accesses for a team to
which they are not related.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
other_user = factories.UserFactory()
team = factories.TeamFactory()
@@ -66,9 +64,7 @@ def test_api_team_accesses_create_authenticated_unrelated():
def test_api_team_accesses_create_authenticated_member():
"""Members of a team should not be allowed to create team accesses."""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
team = factories.TeamFactory(users=[(user, "member")])
other_user = factories.UserFactory()
@@ -96,9 +92,7 @@ def test_api_team_accesses_create_authenticated_administrator():
"""
Administrators of a team should be able to create team accesses except for the "owner" role.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
team = factories.TeamFactory(users=[(user, "administrator")])
other_user = factories.UserFactory()
@@ -149,9 +143,7 @@ def test_api_team_accesses_create_authenticated_owner():
"""
Owners of a team should be able to create team accesses whatever the role.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
team = factories.TeamFactory(users=[(user, "owner")])
other_user = factories.UserFactory()
@@ -227,7 +219,7 @@ def test_api_team_accesses_create_webhook():
"value": [
{
"value": str(other_user.id),
"email": None,
"email": other_user.email,
"type": "User",
}
],
@@ -32,9 +32,7 @@ def test_api_team_accesses_delete_authenticated():
Authenticated users should not be allowed to delete a team access for a
team to which they are not related.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
access = factories.TeamAccessFactory()
client = APIClient()
@@ -52,9 +50,7 @@ def test_api_team_accesses_delete_member():
Authenticated users should not be allowed to delete a team access for a
team in which they are a simple member.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
team = factories.TeamFactory(users=[(user, "member")])
access = factories.TeamAccessFactory(team=team)
@@ -76,9 +72,7 @@ def test_api_team_accesses_delete_administrators():
Users who are administrators in a team should be allowed to delete an access
from the team provided it is not ownership.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
team = factories.TeamFactory(users=[(user, "administrator")])
access = factories.TeamAccessFactory(
team=team, role=random.choice(["member", "administrator"])
@@ -102,9 +96,7 @@ def test_api_team_accesses_delete_owners_except_owners():
Users should be able to delete the team access of another user
for a team of which they are owner provided it is not an owner access.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
team = factories.TeamFactory(users=[(user, "owner")])
access = factories.TeamAccessFactory(
team=team, role=random.choice(["member", "administrator"])
@@ -128,9 +120,7 @@ def test_api_team_accesses_delete_owners_for_owners():
Users should not be allowed to delete the team access of another owner
even for a team in which they are direct owner.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
team = factories.TeamFactory(users=[(user, "owner")])
access = factories.TeamAccessFactory(team=team, role="owner")
@@ -152,7 +142,6 @@ def test_api_team_accesses_delete_owners_last_owner():
It should not be possible to delete the last owner access from a team
"""
user = factories.UserFactory()
team = factories.TeamFactory()
access = factories.TeamAccessFactory(team=team, user=user, role="owner")
assert models.TeamAccess.objects.count() == 1
@@ -173,7 +162,6 @@ def test_api_team_accesses_delete_webhook():
When the team has a webhook, deleting a team access should fire a call.
"""
user = factories.UserFactory()
team = factories.TeamFactory(users=[(user, "administrator")])
webhook = factories.TeamWebhookFactory(team=team)
access = factories.TeamAccessFactory(
@@ -215,7 +203,7 @@ def test_api_team_accesses_delete_webhook():
"value": [
{
"value": str(access.user.id),
"email": None,
"email": access.user.email,
"type": "User",
}
],
@@ -28,9 +28,7 @@ def test_api_team_accesses_list_authenticated_unrelated():
Authenticated users should not be allowed to list team accesses for a team
to which they are not related.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
team = factories.TeamFactory()
factories.TeamAccessFactory.create_batch(3, team=team)
@@ -57,19 +55,12 @@ def test_api_team_accesses_list_authenticated_related():
Authenticated users should be able to list team accesses for a team
to which they are related, with a given role.
"""
identity = factories.IdentityFactory(is_main=True)
user = identity.user
user, administrator, owner = factories.UserFactory.create_batch(3)
team = factories.TeamFactory()
owner = factories.IdentityFactory(is_main=True)
access1 = factories.TeamAccessFactory.create(
team=team, user=owner.user, role="owner"
)
administrator = factories.IdentityFactory(is_main=True)
access1 = factories.TeamAccessFactory.create(team=team, user=owner, role="owner")
access2 = factories.TeamAccessFactory.create(
team=team, user=administrator.user, role="administrator"
team=team, user=administrator, role="administrator"
)
# Ensure this user's role is different from other team members to test abilities' computation
@@ -93,8 +84,8 @@ def test_api_team_accesses_list_authenticated_related():
"id": str(user_access.id),
"user": {
"id": str(user_access.user.id),
"email": str(identity.email),
"name": str(identity.name),
"email": str(user.email),
"name": str(user.name),
},
"role": str(user_access.role),
"abilities": user_access.get_abilities(user),
@@ -124,46 +115,152 @@ def test_api_team_accesses_list_authenticated_related():
)
def test_api_team_accesses_list_authenticated_main_identity():
def test_api_team_accesses_list_find_members(django_assert_num_queries):
"""
Name and email should be returned from main identity only
Authenticated users should be able to search users access with a case-insensitive and
partial query on the name.
"""
user = factories.UserFactory()
identity = factories.IdentityFactory(user=user, is_main=True)
factories.IdentityFactory(user=user) # additional non-main identity
dave = factories.UserFactory(name="dave bowman", email=None)
frank = factories.UserFactory(name="frank poole", email=None)
mary = factories.UserFactory(name="mary poole", email=None)
nicole = factories.UserFactory(name="nicole foole", email=None)
factories.UserFactory(email="tester@ministry.fr", name="john doe")
factories.UserFactory(name="heywood floyd", email=None)
factories.UserFactory(name="Andrei Smyslov", email=None)
factories.TeamFactory.create_batch(10)
team = factories.TeamFactory()
models.TeamAccess.objects.create(team=team, user=user) # random role
# Add Mary, Nicole and Dave in the same team
team = factories.TeamFactory(
name="Odyssey",
users=[
(mary, models.RoleChoices.OWNER),
(nicole, models.RoleChoices.ADMIN),
(dave, models.RoleChoices.MEMBER),
],
)
factories.TeamFactory(users=[(frank, models.RoleChoices.MEMBER)])
# other team members should appear, with correct identity
other_user = factories.UserFactory()
other_main_identity = factories.IdentityFactory(is_main=True, user=other_user)
factories.IdentityFactory(user=other_user)
factories.TeamAccessFactory.create(team=team, user=other_user)
# Search users in the team Odyssey
client = APIClient()
client.force_login(mary)
# Accesses for other teams to which the user is related should not be listed either
other_access = factories.TeamAccessFactory(user=user)
factories.TeamAccessFactory(team=other_access.team)
# 5 queries are needed here:
# - 1 query: select on user authenticated
# - 4 queries: get all users, owner included (2 more queries)
with django_assert_num_queries(5):
response = client.get(
f"/api/v1.0/teams/{team.id!s}/accesses/",
)
assert response.status_code == HTTP_200_OK
assert response.json()["count"] == 3
# We can find David Bowman
# 3 queries are needed here:
# - 1 query: user authenticated
# - 2 queries: search user query with match
with django_assert_num_queries(3):
response = client.get(
f"/api/v1.0/teams/{team.id!s}/accesses/?q=bowman",
)
assert response.status_code == HTTP_200_OK
assert response.json()["count"] == 1
dave_access = dave.accesses.get(team=team)
assert response.json()["results"][0]["id"] == str(dave_access.id)
# We can find Nicole
# 3 queries are needed here:
# - 1 query: user authenticated
# - 2 queries: search user query with match
with django_assert_num_queries(3):
response = client.get(
f"/api/v1.0/teams/{team.id!s}/accesses/?q=nicol",
)
assert response.status_code == HTTP_200_OK
assert response.json()["count"] == 1
nicole_access = nicole.accesses.get(team=team)
assert response.json()["results"][0]["id"] == str(nicole_access.id)
# We can find Nicole and Mary
# 5 queries are needed here:
# - 1 query: select on user authenticated
# - 4 queries: search user query with match and the owner found (2 more queries)
with django_assert_num_queries(5):
response = client.get(
f"/api/v1.0/teams/{team.id!s}/accesses/?q=ool",
)
assert response.status_code == HTTP_200_OK
assert response.json()["count"] == 2
user_access_ids = sorted([user["id"] for user in response.json()["results"]])
mary_access = mary.accesses.get(team=team)
assert sorted([str(mary_access.id), str(nicole_access.id)]) == user_access_ids
# We cannot find Andrei, because he isn't a member of the current team
# 2 queries are needed here:
# - 1 query: select on user authenticated
# - 1 query: search user query with no match
with django_assert_num_queries(2):
response = client.get(
f"/api/v1.0/teams/{team.id!s}/accesses/?q=andrei",
)
assert response.status_code == HTTP_200_OK
assert response.json()["count"] == 0
# We can find Mary
# 5 queries are needed here:
# - 1 query: select on user authenticated
# - 4 queries: search user query with match and an owner found (2 more queries)
with django_assert_num_queries(5):
response = client.get(
f"/api/v1.0/teams/{team.id!s}/accesses/?q=mary",
)
assert response.status_code == HTTP_200_OK
assert response.json()["count"] == 1
assert response.json()["results"][0]["id"] == str(mary_access.id)
def test_api_team_accesses__list_find_members_by_email():
"""
Authenticated users should be able to search users access with a case-insensitive and
partial query on the email.
"""
user = factories.UserFactory(name=None, email="alicia@example.com")
# set all names to None to match only on emails
colleague1 = factories.UserFactory(name=None, email="prudence_crandall@edu.us")
colleague2 = factories.UserFactory(name=None, email="reinebrunehaut@gouv.fr")
colleague3 = factories.UserFactory(name=None, email="artemisia.gentileschi@arte.it")
# Add all colleague in the same team
team = factories.TeamFactory(
users=[
(user, models.RoleChoices.ADMIN),
(colleague1, models.RoleChoices.OWNER),
(colleague2, models.RoleChoices.ADMIN),
(colleague3, models.RoleChoices.MEMBER),
],
)
factories.TeamAccessFactory.create_batch(4)
# Create another team with similar email
factories.TeamFactory(
users=[
(
factories.UserFactory(name=None, email="bruneau@gouv.fr"),
models.RoleChoices.ADMIN,
),
],
)
# Search users in the team Odyssey
client = APIClient()
client.force_login(user)
response = client.get(
f"/api/v1.0/teams/{team.id!s}/accesses/",
)
assert response.status_code == 200
assert response.json()["count"] == 2
users_info = [
(access["user"]["email"], access["user"]["name"])
for access in response.json()["results"]
]
# user information should be returned from main identity
assert sorted(users_info) == sorted(
[
(str(identity.email), str(identity.name)),
(str(other_main_identity.email), str(other_main_identity.name)),
]
response = client.get(
f"/api/v1.0/teams/{team.id!s}/accesses/?q=BRUNE",
)
assert response.status_code == HTTP_200_OK
assert response.json()["count"] == 1
assert response.json()["results"][0]["user"]["email"] == "reinebrunehaut@gouv.fr"
def test_api_team_accesses_list_authenticated_constant_numqueries(
@@ -173,31 +270,28 @@ def test_api_team_accesses_list_authenticated_constant_numqueries(
The number of queries should not depend on the amount of fetched accesses.
"""
user = factories.UserFactory()
factories.IdentityFactory(user=user, is_main=True)
team = factories.TeamFactory()
models.TeamAccess.objects.create(team=team, user=user) # random role
client = APIClient()
client.force_login(user)
# Only 4 queries are needed to efficiently fetch team accesses,
# Only 3 queries are needed to efficiently fetch team accesses,
# related users and identities :
# - query retrieving logged-in user for user_role annotation
# - count from pagination
# - query prefetching users' main identity
# - distinct from viewset
with django_assert_num_queries(4):
with django_assert_num_queries(3):
response = client.get(
f"/api/v1.0/teams/{team.id!s}/accesses/",
)
# create 20 new team members
for _ in range(20):
extra_user = factories.IdentityFactory(is_main=True).user
extra_user = factories.UserFactory()
factories.TeamAccessFactory(team=team, user=extra_user)
# num queries should still be 4
with django_assert_num_queries(4):
# num queries should still be the same
with django_assert_num_queries(3):
response = client.get(
f"/api/v1.0/teams/{team.id!s}/accesses/",
)
@@ -210,14 +304,12 @@ def test_api_team_accesses_list_authenticated_ordering():
"""Team accesses can be ordered by "role"."""
user = factories.UserFactory()
factories.IdentityFactory(user=user, is_main=True)
team = factories.TeamFactory()
models.TeamAccess.objects.create(team=team, user=user)
# create 20 new team members
for _ in range(20):
extra_user = factories.IdentityFactory(is_main=True).user
extra_user = factories.UserFactory()
factories.TeamAccessFactory(team=team, user=extra_user)
client = APIClient()
@@ -242,26 +334,24 @@ def test_api_team_accesses_list_authenticated_ordering():
assert sorted(results, reverse=True) == results
@pytest.mark.parametrize("ordering_fields", ["name", "email"])
def test_api_team_accesses_list_authenticated_ordering_user(ordering_fields):
"""Team accesses can be ordered by user's fields "email" or "name"."""
@pytest.mark.parametrize("ordering_field", ["email", "name"])
def test_api_team_accesses_list_authenticated_ordering_user(ordering_field):
"""Team accesses can be ordered by user's fields."""
user = factories.UserFactory()
factories.IdentityFactory(user=user, is_main=True)
team = factories.TeamFactory()
models.TeamAccess.objects.create(team=team, user=user)
# create 20 new team members
for _ in range(20):
extra_user = factories.IdentityFactory(is_main=True).user
extra_user = factories.UserFactory()
factories.TeamAccessFactory(team=team, user=extra_user)
client = APIClient()
client.force_login(user)
response = client.get(
f"/api/v1.0/teams/{team.id!s}/accesses/?ordering={ordering_fields}",
f"/api/v1.0/teams/{team.id!s}/accesses/?ordering=user__{ordering_field}",
)
assert response.status_code == HTTP_200_OK
assert response.json()["count"] == 21
@@ -271,19 +361,7 @@ def test_api_team_accesses_list_authenticated_ordering_user(ordering_fields):
return x.casefold().replace(" ", "")
results = [
team_access["user"][ordering_fields]
team_access["user"][ordering_field]
for team_access in response.json()["results"]
]
assert sorted(results, key=normalize) == results
response = client.get(
f"/api/v1.0/teams/{team.id!s}/accesses/?ordering=-{ordering_fields}",
)
assert response.status_code == HTTP_200_OK
assert response.json()["count"] == 21
results = [
team_access["user"][ordering_fields]
for team_access in response.json()["results"]
]
assert sorted(results, reverse=True, key=normalize) == results
@@ -31,9 +31,7 @@ def test_api_team_accesses_retrieve_authenticated_unrelated():
Authenticated users should not be allowed to retrieve a team access for
a team to which they are not related.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
access = factories.TeamAccessFactory(team=factories.TeamFactory())
client = APIClient()
@@ -62,9 +60,7 @@ def test_api_team_accesses_retrieve_authenticated_related():
A user who is related to a team should be allowed to retrieve the
associated team user accesses.
"""
identity = factories.IdentityFactory(is_main=True)
user = identity.user
user = factories.UserFactory()
team = factories.TeamFactory()
access = factories.TeamAccessFactory(team=team, user=user)
@@ -79,8 +75,8 @@ def test_api_team_accesses_retrieve_authenticated_related():
"id": str(access.id),
"user": {
"id": str(access.user.id),
"email": str(identity.email),
"name": str(identity.name),
"email": str(user.email),
"name": str(user.name),
},
"role": str(access.role),
"abilities": access.get_abilities(user),
@@ -43,9 +43,7 @@ def test_api_team_accesses_update_authenticated_unrelated():
Authenticated users should not be allowed to update a team access for a team to which
they are not related.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
access = factories.TeamAccessFactory()
old_values = serializers.TeamAccessSerializer(instance=access).data
@@ -72,9 +70,7 @@ def test_api_team_accesses_update_authenticated_unrelated():
def test_api_team_accesses_update_authenticated_member():
"""Members of a team should not be allowed to update its accesses."""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
team = factories.TeamFactory(users=[(user, "member")])
access = factories.TeamAccessFactory(team=team)
old_values = serializers.TeamAccessSerializer(instance=access).data
@@ -105,9 +101,7 @@ def test_api_team_accesses_update_administrator_except_owner():
A user who is an administrator in a team should be allowed to update a user
access for this team, as long as they don't try to set the role to owner.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
team = factories.TeamFactory(users=[(user, "administrator")])
access = factories.TeamAccessFactory(
team=team,
@@ -151,9 +145,7 @@ def test_api_team_accesses_update_administrator_from_owner():
A user who is an administrator in a team, should not be allowed to update
the user access of an "owner" for this team.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
team = factories.TeamFactory(users=[(user, "administrator")])
other_user = factories.UserFactory()
access = factories.TeamAccessFactory(team=team, user=other_user, role="owner")
@@ -184,9 +176,7 @@ def test_api_team_accesses_update_administrator_to_owner():
A user who is an administrator in a team, should not be allowed to update
the user access of another user to grant team ownership.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
team = factories.TeamFactory(users=[(user, "administrator")])
other_user = factories.UserFactory()
access = factories.TeamAccessFactory(
@@ -227,9 +217,7 @@ def test_api_team_accesses_update_owner_except_owner():
A user who is an owner in a team should be allowed to update
a user access for this team except for existing "owner" accesses.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
team = factories.TeamFactory(users=[(user, "owner")])
factories.UserFactory()
access = factories.TeamAccessFactory(
@@ -275,9 +263,7 @@ def test_api_team_accesses_update_owner_for_owners():
A user who is "owner" of a team should not be allowed to update
an existing owner access for this team.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
team = factories.TeamFactory(users=[(user, "owner")])
access = factories.TeamAccessFactory(team=team, role="owner")
old_values = serializers.TeamAccessSerializer(instance=access).data
@@ -307,9 +293,7 @@ def test_api_team_accesses_update_owner_self():
A user who is owner of a team should be allowed to update
their own user access provided there are other owners in the team.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
team = factories.TeamFactory()
access = factories.TeamAccessFactory(team=team, user=user, role="owner")
old_values = serializers.TeamAccessSerializer(instance=access).data
@@ -10,7 +10,7 @@ from rest_framework.status import (
)
from rest_framework.test import APIClient
from core.factories import IdentityFactory, TeamFactory
from core.factories import TeamFactory, UserFactory
from core.models import Team
pytestmark = pytest.mark.django_db
@@ -34,11 +34,10 @@ def test_api_teams_create_authenticated():
Authenticated users should be able to create teams and should automatically be declared
as the owner of the newly created team.
"""
identity = IdentityFactory()
user = identity.user
user = UserFactory()
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
response = client.post(
"/api/v1.0/teams/",
@@ -58,9 +57,9 @@ def test_api_teams_create_authenticated_slugify_name():
"""
Creating teams should automatically generate a slug.
"""
identity = IdentityFactory()
user = UserFactory()
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
response = client.post(
"/api/v1.0/teams/",
@@ -87,10 +86,10 @@ def test_api_teams_create_authenticated_expected_slug(param):
"""
Creating teams should automatically create unaccented, no unicode, lower-case slug.
"""
identity = IdentityFactory()
user = UserFactory()
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
response = client.post(
"/api/v1.0/teams/",
@@ -110,10 +109,10 @@ def test_api_teams_create_authenticated_unique_slugs():
Creating teams should raise an error if already existing slug.
"""
TeamFactory(name="existing team")
identity = IdentityFactory()
user = UserFactory()
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
response = client.post(
"/api/v1.0/teams/",
@@ -33,10 +33,10 @@ def test_api_teams_delete_authenticated_unrelated():
Authenticated users should not be allowed to delete a team to which they are not
related.
"""
identity = factories.IdentityFactory()
user = factories.UserFactory()
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
team = factories.TeamFactory()
@@ -54,8 +54,7 @@ def test_api_teams_delete_authenticated_member():
Authenticated users should not be allowed to delete a team for which they are
only a member.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -78,8 +77,7 @@ def test_api_teams_delete_authenticated_administrator():
Authenticated users should not be allowed to delete a team for which they are
administrator.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -102,8 +100,7 @@ def test_api_teams_delete_authenticated_owner():
Authenticated users should be able to delete a team for which they are directly
owner.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -31,8 +31,7 @@ def test_api_teams_list_authenticated():
Authenticated users should be able to list teams
they are an owner/administrator/member of.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -59,8 +58,7 @@ def test_api_teams_list_pagination(
_mock_page_size,
):
"""Pagination should work as expected."""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -105,8 +103,7 @@ def test_api_teams_list_pagination(
def test_api_teams_list_authenticated_distinct():
"""A team with several related users should only be listed once."""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -129,8 +126,7 @@ def test_api_teams_order():
"""
Test that the endpoint GET teams is sorted in 'created_at' descending order by default.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -159,8 +155,7 @@ def test_api_teams_order_param():
Test that the 'created_at' field is sorted in ascending order
when the 'ordering' query parameter is set.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -27,10 +27,10 @@ def test_api_teams_retrieve_authenticated_unrelated():
Authenticated users should not be allowed to retrieve a team to which they are
not related.
"""
identity = factories.IdentityFactory()
user = factories.UserFactory()
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
team = factories.TeamFactory()
@@ -46,8 +46,7 @@ def test_api_teams_retrieve_authenticated_related():
Authenticated users should be allowed to retrieve a team to which they
are related whatever the role.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -45,10 +45,10 @@ def test_api_teams_update_authenticated_unrelated():
"""
Authenticated users should not be allowed to update a team to which they are not related.
"""
identity = factories.IdentityFactory()
user = factories.UserFactory()
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
team = factories.TeamFactory()
old_team_values = serializers.TeamSerializer(instance=team).data
@@ -73,8 +73,7 @@ def test_api_teams_update_authenticated_members():
Users who are members of a team but not administrators should
not be allowed to update it.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -101,8 +100,7 @@ def test_api_teams_update_authenticated_members():
def test_api_teams_update_authenticated_administrators():
"""Administrators of a team should be allowed to update it."""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -134,8 +132,7 @@ def test_api_teams_update_authenticated_administrators():
def test_api_teams_update_authenticated_owners():
"""Administrators of a team should be allowed to update it,
apart from read-only fields."""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -170,8 +167,7 @@ def test_api_teams_update_administrator_or_owner_of_another():
Being administrator or owner of a team should not grant authorization to update
another team.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -200,8 +196,7 @@ def test_api_teams_update_existing_slug_should_return_error():
Updating a team's name to an existing slug should return a bad request,
instead of creating a duplicate.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
+41
View File
@@ -0,0 +1,41 @@
"""
Test users API endpoints in the People core app.
"""
import pytest
from rest_framework.status import (
HTTP_200_OK,
)
from rest_framework.test import APIClient
from core import factories
pytestmark = pytest.mark.django_db
def test_api_config_anonymous():
"""Anonymous users should be allowed to get the configuration."""
client = APIClient()
response = client.get("/api/v1.0/config/")
assert response.status_code == HTTP_200_OK
assert response.json() == {
"LANGUAGES": [["en-us", "English"], ["fr-fr", "French"]],
"FEATURES": {"TEAMS": True},
"RELEASE": "NA",
}
def test_api_config_authenticated():
"""Authenticated users should be allowed to get the configuration."""
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
response = client.get("/api/v1.0/config/")
assert response.status_code == HTTP_200_OK
assert response.json() == {
"LANGUAGES": [["en-us", "English"], ["fr-fr", "French"]],
"FEATURES": {"TEAMS": True},
"RELEASE": "NA",
}
+25 -44
View File
@@ -69,15 +69,14 @@ def test_api_contacts_list_authenticated_no_query():
Authenticated users should be able to list contacts without applying a query.
Profile and base contacts should be excluded.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
contact = factories.ContactFactory(owner=user)
user.profile_contact = contact
user.save()
# Let's have 5 contacts in database:
assert user.profile_contact is not None # Excluded because profile contact
base_contact = factories.BaseContactFactory() # Excluded because overriden
base_contact = factories.BaseContactFactory() # Excluded because overridden
factories.ContactFactory(
base=base_contact
) # Excluded because belongs to other user
@@ -108,8 +107,7 @@ def test_api_contacts_list_authenticated_by_full_name():
Authenticated users should be able to search users with a case insensitive and
partial query on the full name.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
dave = factories.BaseContactFactory(full_name="David Bowman")
nicole = factories.BaseContactFactory(full_name="Nicole Foole")
@@ -150,8 +148,7 @@ def test_api_contacts_list_authenticated_by_full_name():
def test_api_contacts_list_authenticated_uppercase_content():
"""Upper case content should be found by lower case query."""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
dave = factories.BaseContactFactory(full_name="EEE", short_name="AAA")
@@ -175,8 +172,7 @@ def test_api_contacts_list_authenticated_uppercase_content():
def test_api_contacts_list_authenticated_capital_query():
"""Upper case query should find lower case content."""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
dave = factories.BaseContactFactory(full_name="eee", short_name="aaa")
@@ -200,8 +196,7 @@ def test_api_contacts_list_authenticated_capital_query():
def test_api_contacts_list_authenticated_accented_content():
"""Accented content should be found by unaccented query."""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
dave = factories.BaseContactFactory(full_name="ééé", short_name="ààà")
@@ -225,8 +220,7 @@ def test_api_contacts_list_authenticated_accented_content():
def test_api_contacts_list_authenticated_accented_query():
"""Accented query should find unaccented content."""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
dave = factories.BaseContactFactory(full_name="eee", short_name="aaa")
@@ -264,9 +258,7 @@ def test_api_contacts_retrieve_authenticated_owned():
"""
Authenticated users should be allowed to retrieve a contact they own.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
contact = factories.ContactFactory(owner=user)
client = APIClient()
@@ -289,11 +281,11 @@ def test_api_contacts_retrieve_authenticated_public():
"""
Authenticated users should be able to retrieve public contacts.
"""
identity = factories.IdentityFactory()
user = factories.UserFactory()
contact = factories.BaseContactFactory()
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
response = client.get(f"/api/v1.0/contacts/{contact.id!s}/")
assert response.status_code == 200
@@ -311,11 +303,11 @@ def test_api_contacts_retrieve_authenticated_other():
"""
Authenticated users should not be allowed to retrieve another user's contacts.
"""
identity = factories.IdentityFactory()
user = factories.UserFactory()
contact = factories.ContactFactory()
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
response = client.get(f"/api/v1.0/contacts/{contact.id!s}/")
assert response.status_code == 403
@@ -339,10 +331,10 @@ def test_api_contacts_create_anonymous_forbidden():
def test_api_contacts_create_authenticated_missing_base():
"""Anonymous users should be able to create users."""
identity = factories.IdentityFactory(user__profile_contact=None)
user = factories.UserFactory(profile_contact=None)
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
response = client.post(
"/api/v1.0/contacts/",
@@ -360,8 +352,7 @@ def test_api_contacts_create_authenticated_missing_base():
def test_api_contacts_create_authenticated_successful():
"""Authenticated users should be able to create contacts."""
identity = factories.IdentityFactory(user__profile_contact=None)
user = identity.user
user = factories.UserFactory(profile_contact=None)
base_contact = factories.BaseContactFactory()
client = APIClient()
@@ -404,12 +395,10 @@ def test_api_contacts_create_authenticated_successful():
@override_settings(ALLOW_API_USER_CREATE=True)
def test_api_contacts_create_authenticated_existing_override():
"""
Trying to create a contact for base contact that is already overriden by the user
Trying to create a contact for base contact that is already overridden by the user
should receive a 400 error.
"""
identity = factories.IdentityFactory(user__profile_contact=None)
user = identity.user
user = factories.UserFactory(profile_contact=None)
base_contact = factories.BaseContactFactory()
factories.ContactFactory(base=base_contact, owner=user)
@@ -463,8 +452,7 @@ def test_api_contacts_update_authenticated_owned():
"""
Authenticated users should be allowed to update their own contacts.
"""
identity = factories.IdentityFactory(user__profile_contact=None)
user = identity.user
user = factories.UserFactory(profile_contact=None)
client = APIClient()
client.force_login(user)
@@ -498,8 +486,7 @@ def test_api_contacts_update_authenticated_profile():
"""
Authenticated users should be allowed to update their profile contact.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -534,8 +521,7 @@ def test_api_contacts_update_authenticated_other():
"""
Authenticated users should not be allowed to update contacts owned by other users.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -573,8 +559,7 @@ def test_api_contacts_delete_list_anonymous():
def test_api_contacts_delete_list_authenticated():
"""Authenticated users should not be allowed to delete a list of contacts."""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -602,8 +587,7 @@ def test_api_contacts_delete_authenticated_public():
"""
Authenticated users should not be allowed to delete a public contact.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -622,8 +606,7 @@ def test_api_contacts_delete_authenticated_owner():
"""
Authenticated users should be allowed to delete a contact they own.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
contact = factories.ContactFactory(owner=user)
client = APIClient()
@@ -642,8 +625,7 @@ def test_api_contacts_delete_authenticated_profile():
"""
Authenticated users should be allowed to delete their profile contact.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
contact = factories.ContactFactory(owner=user, base=None)
user.profile_contact = contact
user.save()
@@ -663,8 +645,7 @@ def test_api_contacts_delete_authenticated_other():
"""
Authenticated users should not be allowed to delete a contact they don't own.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
contact = factories.ContactFactory()
client = APIClient()
@@ -34,15 +34,15 @@ def test_api_team_invitations__create__anonymous():
def test_api_team_invitations__create__authenticated_outsider():
"""Users outside of team should not be permitted to invite to team."""
identity = factories.IdentityFactory()
user = factories.UserFactory()
team = factories.TeamFactory()
invitation_values = serializers.InvitationSerializer(
factories.InvitationFactory.build()
).data
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
response = client.post(
f"/api/v1.0/teams/{team.id}/invitations/",
invitation_values,
@@ -57,16 +57,16 @@ def test_api_team_invitations__create__authenticated_outsider():
)
def test_api_team_invitations__create__privileged_members(role):
"""Owners and administrators should be able to invite new members."""
identity = factories.IdentityFactory()
team = factories.TeamFactory(users=[(identity.user, role)])
user = factories.UserFactory()
team = factories.TeamFactory(users=[(user, role)])
invitation_values = serializers.InvitationSerializer(
factories.InvitationFactory.build()
).data
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
response = client.post(
f"/api/v1.0/teams/{team.id}/invitations/",
invitation_values,
@@ -79,16 +79,16 @@ def test_api_team_invitations__create__members():
"""
Members should not be able to invite new members.
"""
identity = factories.IdentityFactory()
team = factories.TeamFactory(users=[(identity.user, "member")])
user = factories.UserFactory()
team = factories.TeamFactory(users=[(user, "member")])
invitation_values = serializers.InvitationSerializer(
factories.InvitationFactory.build()
).data
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
response = client.post(
f"/api/v1.0/teams/{team.id}/invitations/",
invitation_values,
@@ -102,16 +102,16 @@ def test_api_team_invitations__create__members():
def test_api_team_invitations__create__issuer_and_team_automatically_added():
"""Team and issuer fields should auto-complete."""
identity = factories.IdentityFactory()
team = factories.TeamFactory(users=[(identity.user, "owner")])
user = factories.UserFactory()
team = factories.TeamFactory(users=[(user, "owner")])
# Generate a random invitation
invitation = factories.InvitationFactory.build()
invitation_data = {"email": invitation.email, "role": invitation.role}
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
response = client.post(
f"/api/v1.0/teams/{team.id}/invitations/",
invitation_data,
@@ -120,7 +120,7 @@ def test_api_team_invitations__create__issuer_and_team_automatically_added():
assert response.status_code == status.HTTP_201_CREATED
# team and issuer automatically set
assert response.json()["team"] == str(team.id)
assert response.json()["issuer"] == str(identity.user.id)
assert response.json()["issuer"] == str(user.id)
def test_api_team_invitations__create__cannot_duplicate_invitation():
@@ -129,8 +129,8 @@ def test_api_team_invitations__create__cannot_duplicate_invitation():
team = existing_invitation.team
# Grant privileged role on the Team to the user
identity = factories.IdentityFactory()
factories.TeamAccessFactory(team=team, user=identity.user, role="administrator")
user = factories.UserFactory()
factories.TeamAccessFactory(team=team, user=user, role="administrator")
# Create a new invitation to the same team with the exact same email address
duplicated_invitation = serializers.InvitationSerializer(
@@ -138,7 +138,7 @@ def test_api_team_invitations__create__cannot_duplicate_invitation():
).data
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
response = client.post(
f"/api/v1.0/teams/{team.id}/invitations/",
duplicated_invitation,
@@ -154,11 +154,9 @@ def test_api_team_invitations__create__cannot_invite_existing_users():
"""
Should not be able to invite already existing users.
"""
user = factories.UserFactory()
user, existing_user = factories.UserFactory.create_batch(2)
team = factories.TeamFactory(users=[(user, "administrator")])
existing_user = factories.IdentityFactory(is_main=True)
# Build an invitation to the email of an exising identity in the db
invitation_values = serializers.InvitationSerializer(
factories.InvitationFactory.build(email=existing_user.email, team=team)
@@ -166,6 +164,7 @@ def test_api_team_invitations__create__cannot_invite_existing_users():
client = APIClient()
client.force_login(user)
response = client.post(
f"/api/v1.0/teams/{team.id}/invitations/",
invitation_values,
@@ -190,14 +189,10 @@ def test_api_team_invitations__list__authenticated():
Authenticated user should be able to list invitations
in teams they belong to, including from other issuers.
"""
identity = factories.IdentityFactory()
other_user = factories.UserFactory()
team = factories.TeamFactory(
users=[(identity.user, "administrator"), (other_user, "owner")]
)
user, other_user = factories.UserFactory.create_batch(2)
team = factories.TeamFactory(users=[(user, "administrator"), (other_user, "owner")])
invitation = factories.InvitationFactory(
team=team, role="administrator", issuer=identity.user
team=team, role="administrator", issuer=user
)
other_invitations = factories.InvitationFactory.create_batch(
2, team=team, role="member", issuer=other_user
@@ -208,7 +203,7 @@ def test_api_team_invitations__list__authenticated():
factories.InvitationFactory.create_batch(2, team=other_team, role="member")
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
response = client.get(
f"/api/v1.0/teams/{team.id}/invitations/",
)
@@ -235,24 +230,22 @@ def test_api_team_invitations__list__expired_invitations_still_listed(settings):
"""
Expired invitations are still listed.
"""
identity = factories.IdentityFactory()
user = factories.UserFactory()
other_user = factories.UserFactory()
team = factories.TeamFactory(
users=[(identity.user, "administrator"), (other_user, "owner")]
)
team = factories.TeamFactory(users=[(user, "administrator"), (other_user, "owner")])
# override settings to accelerate validation expiration
settings.INVITATION_VALIDITY_DURATION = 1 # second
expired_invitation = factories.InvitationFactory(
team=team,
role="member",
issuer=identity.user,
issuer=user,
)
time.sleep(1)
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
response = client.get(
f"/api/v1.0/teams/{team.id}/invitations/",
)
@@ -293,12 +286,12 @@ def test_api_team_invitations__retrieve__unrelated_user():
"""
Authenticated unrelated users should not be able to retrieve invitations.
"""
user = factories.IdentityFactory(user=factories.UserFactory()).user
user = factories.UserFactory()
invitation = factories.InvitationFactory()
client = APIClient()
client.force_login(user)
response = client.get(
f"/api/v1.0/teams/{invitation.team.id}/invitations/{invitation.id}/",
)
@@ -311,8 +304,7 @@ def test_api_team_invitations__retrieve__team_member():
Authenticated team members should be able to retrieve invitations
whatever their role in the team.
"""
user = factories.IdentityFactory(user=factories.UserFactory()).user
user = factories.UserFactory()
invitation = factories.InvitationFactory()
factories.TeamAccessFactory(team=invitation.team, user=user, role="member")
@@ -342,8 +334,7 @@ def test_api_team_invitations__update__forbidden(method):
"""
Update of invitations is currently forbidden.
"""
user = factories.IdentityFactory(user=factories.UserFactory()).user
user = factories.UserFactory()
invitation = factories.InvitationFactory()
factories.TeamAccessFactory(team=invitation.team, user=user, role="owner")
@@ -376,13 +367,12 @@ def test_api_team_invitations__delete__anonymous():
def test_api_team_invitations__delete__authenticated_outsider():
"""Members outside of team should not cancel invitations."""
identity = factories.IdentityFactory()
user = factories.UserFactory()
team = factories.TeamFactory()
invitation = factories.InvitationFactory(team=team)
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
response = client.delete(
f"/api/v1.0/teams/{team.id}/invitations/{invitation.id}/",
)
@@ -392,13 +382,12 @@ def test_api_team_invitations__delete__authenticated_outsider():
@pytest.mark.parametrize("role", ["owner", "administrator"])
def test_api_team_invitations__delete__privileged_members(role):
"""Privileged member should be able to cancel invitation."""
identity = factories.IdentityFactory()
team = factories.TeamFactory(users=[(identity.user, role)])
user = factories.UserFactory()
team = factories.TeamFactory(users=[(user, role)])
invitation = factories.InvitationFactory(team=team)
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
response = client.delete(
f"/api/v1.0/teams/{team.id}/invitations/{invitation.id}/",
)
@@ -407,13 +396,12 @@ def test_api_team_invitations__delete__privileged_members(role):
def test_api_team_invitations__delete__members():
"""Member should not be able to cancel invitation."""
identity = factories.IdentityFactory()
team = factories.TeamFactory(users=[(identity.user, "member")])
user = factories.UserFactory()
team = factories.TeamFactory(users=[(user, "member")])
invitation = factories.InvitationFactory(team=team)
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
response = client.delete(
f"/api/v1.0/teams/{team.id}/invitations/{invitation.id}/",
)
+101 -228
View File
@@ -35,10 +35,10 @@ def test_api_users_list_authenticated():
"""
Authenticated users should be able to list all users.
"""
identity = factories.IdentityFactory()
user = factories.UserFactory()
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
factories.UserFactory.create_batch(2)
response = client.get(
@@ -53,23 +53,15 @@ def test_api_users_authenticated_list_by_email():
Authenticated users should be able to search users with a case-insensitive and
partial query on the email.
"""
user = factories.UserFactory(admin_email="tester@ministry.fr")
factories.IdentityFactory(user=user, email=user.admin_email, name="john doe")
user = factories.UserFactory(email="tester@ministry.fr", name="john doe")
dave = factories.UserFactory(email="david.bowman@work.com", name=None)
nicole = factories.UserFactory(email="nicole_foole@work.com", name=None)
frank = factories.UserFactory(email="frank_poole@work.com", name=None)
factories.UserFactory(email="heywood_floyd@work.com", name=None)
client = APIClient()
client.force_login(user)
dave = factories.IdentityFactory(
email="david.bowman@work.com", name=None, is_main=True
)
nicole = factories.IdentityFactory(
email="nicole_foole@work.com", name=None, is_main=True
)
frank = factories.IdentityFactory(
email="frank_poole@work.com", name=None, is_main=True
)
factories.IdentityFactory(email="heywood_floyd@work.com", name=None, is_main=True)
# Full query should work
response = client.get(
"/api/v1.0/users/?q=david.bowman@work.com",
@@ -77,14 +69,14 @@ def test_api_users_authenticated_list_by_email():
assert response.status_code == HTTP_200_OK
user_ids = [user["id"] for user in response.json()["results"]]
assert user_ids[0] == str(dave.user.id)
assert user_ids[0] == str(dave.id)
# Partial query should work
response = client.get("/api/v1.0/users/?q=fran")
assert response.status_code == HTTP_200_OK
user_ids = [user["id"] for user in response.json()["results"]]
assert user_ids[0] == str(frank.user.id)
assert user_ids[0] == str(frank.id)
# Result that matches a trigram twice ranks better than result that matches once
response = client.get("/api/v1.0/users/?q=ole")
@@ -92,7 +84,7 @@ def test_api_users_authenticated_list_by_email():
assert response.status_code == HTTP_200_OK
user_ids = [user["id"] for user in response.json()["results"]]
# "Nicole Foole" matches twice on "ole"
assert user_ids == [str(nicole.user.id), str(frank.user.id)]
assert user_ids == [str(nicole.id), str(frank.id)]
# Even with a low similarity threshold, query should match expected emails
response = client.get("/api/v1.0/users/?q=ool")
@@ -100,22 +92,22 @@ def test_api_users_authenticated_list_by_email():
assert response.status_code == HTTP_200_OK
assert response.json()["results"] == [
{
"id": str(nicole.user.id),
"id": str(nicole.id),
"email": nicole.email,
"name": nicole.name,
"is_device": nicole.user.is_device,
"is_staff": nicole.user.is_staff,
"language": nicole.user.language,
"timezone": str(nicole.user.timezone),
"is_device": nicole.is_device,
"is_staff": nicole.is_staff,
"language": nicole.language,
"timezone": str(nicole.timezone),
},
{
"id": str(frank.user.id),
"id": str(frank.id),
"email": frank.email,
"name": frank.name,
"is_device": frank.user.is_device,
"is_staff": frank.user.is_staff,
"language": frank.user.language,
"timezone": str(frank.user.timezone),
"is_device": frank.is_device,
"is_staff": frank.is_staff,
"language": frank.language,
"timezone": str(frank.timezone),
},
]
@@ -125,17 +117,15 @@ def test_api_users_authenticated_list_by_name():
Authenticated users should be able to search users with a case-insensitive and
partial query on the name.
"""
user = factories.UserFactory(admin_email="tester@ministry.fr")
factories.IdentityFactory(user=user, email=user.admin_email, name="john doe")
user = factories.UserFactory(email="tester@ministry.fr", name="john doe")
dave = factories.UserFactory(name="dave bowman", email=None)
nicole = factories.UserFactory(name="nicole foole", email=None)
frank = factories.UserFactory(name="frank poole", email=None)
factories.UserFactory(name="heywood floyd", email=None)
client = APIClient()
client.force_login(user)
dave = factories.IdentityFactory(name="dave bowman", email=None, is_main=True)
nicole = factories.IdentityFactory(name="nicole foole", email=None, is_main=True)
frank = factories.IdentityFactory(name="frank poole", email=None, is_main=True)
factories.IdentityFactory(name="heywood floyd", email=None, is_main=True)
# Full query should work
response = client.get(
"/api/v1.0/users/?q=david.bowman@work.com",
@@ -143,14 +133,14 @@ def test_api_users_authenticated_list_by_name():
assert response.status_code == HTTP_200_OK
user_ids = [user["id"] for user in response.json()["results"]]
assert user_ids[0] == str(dave.user.id)
assert user_ids[0] == str(dave.id)
# Partial query should work
response = client.get("/api/v1.0/users/?q=fran")
assert response.status_code == HTTP_200_OK
user_ids = [user["id"] for user in response.json()["results"]]
assert user_ids[0] == str(frank.user.id)
assert user_ids[0] == str(frank.id)
# Result that matches a trigram twice ranks better than result that matches once
response = client.get("/api/v1.0/users/?q=ole")
@@ -158,7 +148,7 @@ def test_api_users_authenticated_list_by_name():
assert response.status_code == HTTP_200_OK
user_ids = [user["id"] for user in response.json()["results"]]
# "Nicole Foole" matches twice on "ole"
assert user_ids == [str(nicole.user.id), str(frank.user.id)]
assert user_ids == [str(nicole.id), str(frank.id)]
# Even with a low similarity threshold, query should match expected user
response = client.get("/api/v1.0/users/?q=ool")
@@ -166,22 +156,22 @@ def test_api_users_authenticated_list_by_name():
assert response.status_code == HTTP_200_OK
assert response.json()["results"] == [
{
"id": str(nicole.user.id),
"id": str(nicole.id),
"email": nicole.email,
"name": nicole.name,
"is_device": nicole.user.is_device,
"is_staff": nicole.user.is_staff,
"language": nicole.user.language,
"timezone": str(nicole.user.timezone),
"is_device": nicole.is_device,
"is_staff": nicole.is_staff,
"language": nicole.language,
"timezone": str(nicole.timezone),
},
{
"id": str(frank.user.id),
"id": str(frank.id),
"email": frank.email,
"name": frank.name,
"is_device": frank.user.is_device,
"is_staff": frank.user.is_staff,
"language": frank.user.language,
"timezone": str(frank.user.timezone),
"is_device": frank.is_device,
"is_staff": frank.is_staff,
"language": frank.language,
"timezone": str(frank.timezone),
},
]
@@ -192,20 +182,14 @@ def test_api_users_authenticated_list_by_name_and_email():
partial query on the name and email.
"""
user = factories.UserFactory(admin_email="tester@ministry.fr")
factories.IdentityFactory(user=user, email=user.admin_email, name="john doe")
user = factories.UserFactory(email="tester@ministry.fr", name="john doe")
nicole = factories.UserFactory(email="nicole_foole@work.com", name="nicole foole")
frank = factories.UserFactory(email="oleg_poole@work.com", name=None)
david = factories.UserFactory(email=None, name="david role")
client = APIClient()
client.force_login(user)
nicole = factories.IdentityFactory(
email="nicole_foole@work.com", name="nicole foole", is_main=True
)
frank = factories.IdentityFactory(
email="oleg_poole@work.com", name=None, is_main=True
)
david = factories.IdentityFactory(email=None, name="david role", is_main=True)
# Result that matches a trigram in name and email ranks better than result that matches once
response = client.get("/api/v1.0/users/?q=ole")
@@ -215,7 +199,7 @@ def test_api_users_authenticated_list_by_name_and_email():
# "Nicole Foole" matches twice on "ole" in her name and twice on "ole" in her email
# "Oleg poole" matches twice on "ole" in her email
# "David role" matches once on "ole" in his name
assert user_ids == [str(nicole.user.id), str(frank.user.id), str(david.user.id)]
assert user_ids == [str(nicole.id), str(frank.id), str(david.id)]
def test_api_users_authenticated_list_exclude_users_already_in_team(
@@ -225,27 +209,26 @@ def test_api_users_authenticated_list_exclude_users_already_in_team(
Authenticated users should be able to search users
but the result should exclude all users already in the given team.
"""
user = factories.UserFactory(admin_email="tester@ministry.fr")
factories.IdentityFactory(user=user, email=user.email, name="john doe")
user = factories.UserFactory(email="tester@ministry.fr", name="john doe")
dave = factories.UserFactory(name="dave bowman", email=None)
nicole = factories.UserFactory(name="nicole foole", email=None)
frank = factories.UserFactory(name="frank poole", email=None)
mary = factories.UserFactory(name="mary poole", email=None)
factories.UserFactory(name="heywood floyd", email=None)
factories.UserFactory(name="Andrei Smyslov", email=None)
factories.TeamFactory.create_batch(10)
client = APIClient()
client.force_login(user)
dave = factories.IdentityFactory(name="dave bowman", email=None, is_main=True)
nicole = factories.IdentityFactory(name="nicole foole", email=None, is_main=True)
frank = factories.IdentityFactory(name="frank poole", email=None, is_main=True)
mary = factories.IdentityFactory(name="mary poole", email=None, is_main=True)
factories.IdentityFactory(name="heywood floyd", email=None, is_main=True)
factories.IdentityFactory(name="Andrei Smyslov", email=None, is_main=True)
factories.TeamFactory.create_batch(10)
# Add Dave and Frank in the same team
team = factories.TeamFactory(
users=[
(dave.user, models.RoleChoices.MEMBER),
(frank.user, models.RoleChoices.MEMBER),
(dave, models.RoleChoices.MEMBER),
(frank, models.RoleChoices.MEMBER),
]
)
factories.TeamFactory(users=[(nicole.user, models.RoleChoices.MEMBER)])
factories.TeamFactory(users=[(nicole, models.RoleChoices.MEMBER)])
# Search user to add him/her to a team, we give a team id to the request
# to exclude all users already in the team
@@ -266,118 +249,25 @@ def test_api_users_authenticated_list_exclude_users_already_in_team(
# - user authenticated
# - search user query
# - User
# - Identity
with django_assert_num_queries(4):
with django_assert_num_queries(3):
response = client.get(
f"/api/v1.0/users/?q=ool&team_id={team.id}",
)
assert response.status_code == HTTP_200_OK
user_ids = sorted([user["id"] for user in response.json()["results"]])
assert user_ids == sorted([str(mary.user.id), str(nicole.user.id)])
def test_api_users_authenticated_list_multiple_identities_single_user():
"""
User with multiple identities should appear only once in results.
"""
user = factories.UserFactory(admin_email="tester@ministry.fr")
factories.IdentityFactory(user=user, email=user.admin_email, name="eva karl")
client = APIClient()
client.force_login(user)
dave = factories.UserFactory()
factories.IdentityFactory(
user=dave, email="dave.bowman@work.com", name="dave bowman"
)
factories.IdentityFactory(user=dave, email="dave.bowman@fun.fr", name="dave bowman")
# Full query should work
response = client.get(
"/api/v1.0/users/?q=david.bowman@work.com",
)
assert response.status_code == HTTP_200_OK
# A single user is returned, despite similarity matching both emails
assert response.json()["count"] == 1
assert response.json()["results"][0]["id"] == str(dave.id)
def test_api_users_authenticated_list_multiple_identities_multiple_users():
"""
User with multiple identities should be ranked
on their best matching identity.
"""
user = factories.UserFactory(admin_email="tester@ministry.fr")
factories.IdentityFactory(user=user, email=user.admin_email, name="john doe")
client = APIClient()
client.force_login(user)
dave = factories.UserFactory()
dave_identity = factories.IdentityFactory(
user=dave, email="dave.bowman@work.com", is_main=True, name="dave bowman"
)
factories.IdentityFactory(user=dave, email="babibou@ehehe.com", name="babihou")
davina_identity = factories.IdentityFactory(
user=factories.UserFactory(), email="davina.bowan@work.com", name="davina"
)
prue_identity = factories.IdentityFactory(
user=factories.UserFactory(),
email="prudence.crandall@work.com",
name="prudence",
)
# Full query should work
response = client.get(
"/api/v1.0/users/?q=david.bowman@work.com",
)
assert response.status_code == HTTP_200_OK
assert response.json()["count"] == 3
assert response.json()["results"] == [
{
"id": str(dave.id),
"email": dave_identity.email,
"name": dave_identity.name,
"is_device": dave_identity.user.is_device,
"is_staff": dave_identity.user.is_staff,
"language": dave_identity.user.language,
"timezone": str(dave_identity.user.timezone),
},
{
"id": str(davina_identity.user.id),
"email": davina_identity.email,
"name": davina_identity.name,
"is_device": davina_identity.user.is_device,
"is_staff": davina_identity.user.is_staff,
"language": davina_identity.user.language,
"timezone": str(davina_identity.user.timezone),
},
{
"id": str(prue_identity.user.id),
"email": prue_identity.email,
"name": prue_identity.name,
"is_device": prue_identity.user.is_device,
"is_staff": prue_identity.user.is_staff,
"language": prue_identity.user.language,
"timezone": str(prue_identity.user.timezone),
},
]
assert user_ids == sorted([str(mary.id), str(nicole.id)])
def test_api_users_authenticated_list_uppercase_content():
"""Upper case content should be found by lower case query."""
user = factories.UserFactory(admin_email="tester@ministry.fr")
factories.IdentityFactory(user=user, email=user.admin_email, name="eva karl")
user = factories.UserFactory(email="tester@ministry.fr", name="eva karl")
dave = factories.UserFactory(
email="DAVID.BOWMAN@INTENSEWORK.COM", name="DAVID BOWMAN"
)
client = APIClient()
client.force_login(user)
dave = factories.IdentityFactory(
email="DAVID.BOWMAN@INTENSEWORK.COM", name="DAVID BOWMAN"
)
# Unaccented full address
response = client.get(
"/api/v1.0/users/?q=david.bowman@intensework.com",
@@ -385,7 +275,7 @@ def test_api_users_authenticated_list_uppercase_content():
assert response.status_code == HTTP_200_OK
user_ids = [user["id"] for user in response.json()["results"]]
assert user_ids == [str(dave.user.id)]
assert user_ids == [str(dave.id)]
# Partial query
response = client.get(
@@ -394,19 +284,17 @@ def test_api_users_authenticated_list_uppercase_content():
assert response.status_code == HTTP_200_OK
user_ids = [user["id"] for user in response.json()["results"]]
assert user_ids == [str(dave.user.id)]
assert user_ids == [str(dave.id)]
def test_api_users_list_authenticated_capital_query():
"""Upper case query should find lower case content."""
user = factories.UserFactory(admin_email="tester@ministry.fr")
factories.IdentityFactory(user=user, email=user.admin_email, name="eva karl")
user = factories.UserFactory(email="tester@ministry.fr", name="eva karl")
dave = factories.UserFactory(email="david.bowman@work.com", name="david bowman")
client = APIClient()
client.force_login(user)
dave = factories.IdentityFactory(email="david.bowman@work.com", name="david bowman")
# Full uppercase query
response = client.get(
"/api/v1.0/users/?q=DAVID.BOWMAN@WORK.COM",
@@ -414,7 +302,7 @@ def test_api_users_list_authenticated_capital_query():
assert response.status_code == HTTP_200_OK
user_ids = [user["id"] for user in response.json()["results"]]
assert user_ids == [str(dave.user.id)]
assert user_ids == [str(dave.id)]
# Partial uppercase email
response = client.get(
@@ -423,21 +311,17 @@ def test_api_users_list_authenticated_capital_query():
assert response.status_code == HTTP_200_OK
user_ids = [user["id"] for user in response.json()["results"]]
assert user_ids == [str(dave.user.id)]
assert user_ids == [str(dave.id)]
def test_api_contacts_list_authenticated_accented_query():
"""Accented content should be found by unaccented query."""
user = factories.UserFactory(admin_email="tester@ministry.fr")
factories.IdentityFactory(user=user, email=user.admin_email, name="john doe")
user = factories.UserFactory(email="tester@ministry.fr", name="john doe")
helene = factories.UserFactory(email="helene.bowman@work.com", name="helene bowman")
client = APIClient()
client.force_login(user)
helene = factories.IdentityFactory(
email="helene.bowman@work.com", name="helene bowman"
)
# Accented full query
response = client.get(
"/api/v1.0/users/?q=hélène.bowman@work.com",
@@ -445,7 +329,7 @@ def test_api_contacts_list_authenticated_accented_query():
assert response.status_code == HTTP_200_OK
user_ids = [user["id"] for user in response.json()["results"]]
assert user_ids == [str(helene.user.id)]
assert user_ids == [str(helene.id)]
# Unaccented partial email
response = client.get(
@@ -454,7 +338,7 @@ def test_api_contacts_list_authenticated_accented_query():
assert response.status_code == HTTP_200_OK
user_ids = [user["id"] for user in response.json()["results"]]
assert user_ids == [str(helene.user.id)]
assert user_ids == [str(helene.id)]
@mock.patch.object(Pagination, "get_page_size", return_value=3)
@@ -462,8 +346,7 @@ def test_api_users_list_pagination(
_mock_page_size,
):
"""Pagination should work as expected."""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -503,14 +386,13 @@ def test_api_users_list_pagination_page_size(
page_size,
):
"""Page's size on pagination should work as expected."""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
for i in range(page_size):
factories.UserFactory.create(admin_email=f"user-{i}@people.com")
factories.UserFactory.create(email=f"user-{i}@people.com")
response = client.get(
f"/api/v1.0/users/?page_size={page_size}",
@@ -528,14 +410,13 @@ def test_api_users_list_pagination_wrong_page_size(
page_size,
):
"""Page's size on pagination should be limited to "max_page_size"."""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
for i in range(page_size):
factories.UserFactory.create(admin_email=f"user-{i}@people.com")
factories.UserFactory.create(email=f"user-{i}@people.com")
response = client.get(
f"/api/v1.0/users/?page_size={page_size}",
@@ -563,8 +444,7 @@ def test_api_users_retrieve_me_anonymous():
def test_api_users_retrieve_me_authenticated():
"""Authenticated users should be able to retrieve their own user via the "/users/me" path."""
identity = factories.IdentityFactory(is_main=True)
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -582,8 +462,8 @@ def test_api_users_retrieve_me_authenticated():
assert response.status_code == HTTP_200_OK
assert response.json() == {
"id": str(user.id),
"name": str(identity.name),
"email": str(identity.email),
"name": str(user.name),
"email": str(user.email),
"language": user.language,
"timezone": str(user.timezone),
"is_device": False,
@@ -608,8 +488,7 @@ def test_api_users_retrieve_authenticated_self():
Authenticated users should be allowed to retrieve their own user.
The returned object should not contain the password.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -626,12 +505,10 @@ def test_api_users_retrieve_authenticated_other():
Authenticated users should be able to retrieve another user's detail view with
limited information.
"""
identity = factories.IdentityFactory()
user, other_user = factories.UserFactory.create_batch(2)
client = APIClient()
client.force_login(identity.user)
other_user = factories.UserFactory()
client.force_login(user)
response = client.get(
f"/api/v1.0/users/{other_user.id!s}/",
@@ -658,8 +535,7 @@ def test_api_users_create_anonymous():
def test_api_users_create_authenticated():
"""Authenticated users should not be able to create users via the API."""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -706,8 +582,7 @@ def test_api_users_update_authenticated_self():
Authenticated users should be able to update their own user but only "language"
and "timezone" fields.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -735,10 +610,10 @@ def test_api_users_update_authenticated_self():
def test_api_users_update_authenticated_other():
"""Authenticated users should not be allowed to update other users."""
identity = factories.IdentityFactory()
user = factories.UserFactory()
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
user = factories.UserFactory()
old_user_values = dict(serializers.UserSerializer(instance=user).data)
@@ -788,8 +663,7 @@ def test_api_users_patch_authenticated_self():
Authenticated users should be able to patch their own user but only "language"
and "timezone" fields.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -818,27 +692,27 @@ def test_api_users_patch_authenticated_self():
def test_api_users_patch_authenticated_other():
"""Authenticated users should not be allowed to patch other users."""
identity = factories.IdentityFactory()
user = factories.UserFactory()
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
user = factories.UserFactory()
old_user_values = dict(serializers.UserSerializer(instance=user).data)
other_user = factories.UserFactory()
old_user_values = dict(serializers.UserSerializer(instance=other_user).data)
new_user_values = dict(
serializers.UserSerializer(instance=factories.UserFactory()).data
)
for key, new_value in new_user_values.items():
response = client.put(
f"/api/v1.0/users/{user.id!s}/",
f"/api/v1.0/users/{other_user.id!s}/",
{key: new_value},
format="json",
)
assert response.status_code == HTTP_403_FORBIDDEN
user.refresh_from_db()
user_values = dict(serializers.UserSerializer(instance=user).data)
other_user.refresh_from_db()
user_values = dict(serializers.UserSerializer(instance=other_user).data)
for key, value in user_values.items():
assert value == old_user_values[key]
@@ -856,11 +730,11 @@ def test_api_users_delete_list_anonymous():
def test_api_users_delete_list_authenticated():
"""Authenticated users should not be allowed to delete a list of users."""
user = factories.UserFactory()
factories.UserFactory.create_batch(2)
identity = factories.IdentityFactory()
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
response = client.delete(
"/api/v1.0/users/",
@@ -884,11 +758,10 @@ def test_api_users_delete_authenticated():
"""
Authenticated users should not be allowed to delete a user other than themselves.
"""
identity = factories.IdentityFactory()
other_user = factories.UserFactory()
user, other_user = factories.UserFactory.create_batch(2)
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
response = client.delete(f"/api/v1.0/users/{other_user.id!s}/")
@@ -898,13 +771,13 @@ def test_api_users_delete_authenticated():
def test_api_users_delete_self():
"""Authenticated users should not be able to delete their own user."""
identity = factories.IdentityFactory()
user = factories.UserFactory()
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
response = client.delete(
f"/api/v1.0/users/{identity.user.id!s}/",
f"/api/v1.0/users/{user.id!s}/",
)
assert response.status_code == HTTP_405_METHOD_NOT_ALLOWED
@@ -1,183 +0,0 @@
"""
Unit tests for the Identity model
"""
from django.core.exceptions import ValidationError
import pytest
from core import factories, models
pytestmark = pytest.mark.django_db
def test_models_identities_str_main():
"""The str representation should be the email address with indication that it is main."""
identity = factories.IdentityFactory(email="david@example.com")
assert str(identity) == "david@example.com[main]"
def test_models_identities_str_secondary():
"""The str representation of a secondary email should be the email address."""
main_identity = factories.IdentityFactory()
secondary_identity = factories.IdentityFactory(
user=main_identity.user, email="david@example.com"
)
assert str(secondary_identity) == "david@example.com"
def test_models_identities_is_main_automatic():
"""The first identity created for a user should automatically be set as main."""
user = factories.UserFactory()
identity = models.Identity.objects.create(
user=user, sub="123", email="david@example.com"
)
assert identity.is_main is True
def test_models_identities_is_main_exists():
"""A user should always keep one and only one of its identities as main."""
user = factories.UserFactory()
main_identity, _secondary_identity = factories.IdentityFactory.create_batch(
2, user=user
)
assert main_identity.is_main is True
main_identity.is_main = False
with pytest.raises(
ValidationError, match="A user should have one and only one main identity."
):
main_identity.save()
def test_models_identities_is_main_switch():
"""Setting a secondary identity as main should reset the existing main identity."""
user = factories.UserFactory()
first_identity, second_identity = factories.IdentityFactory.create_batch(
2, user=user
)
assert first_identity.is_main is True
second_identity.is_main = True
second_identity.save()
second_identity.refresh_from_db()
assert second_identity.is_main is True
first_identity.refresh_from_db()
assert first_identity.is_main is False
def test_models_identities_email_not_required():
"""The 'email' field can be blank."""
user = factories.UserFactory()
models.Identity.objects.create(user=user, sub="123", email=None)
def test_models_identities_user_required():
"""The 'user' field is required."""
with pytest.raises(models.User.DoesNotExist, match="Identity has no user."):
models.Identity.objects.create(user=None, email="david@example.com")
def test_models_identities_email_unique_same_user():
"""The 'email' field should be unique for a given user."""
email = factories.IdentityFactory()
with pytest.raises(
ValidationError,
match="Identity with this User and Email address already exists.",
):
factories.IdentityFactory(user=email.user, email=email.email)
def test_models_identities_email_unique_different_users():
"""The 'email' field should not be unique among users."""
email = factories.IdentityFactory()
factories.IdentityFactory(email=email.email)
def test_models_identities_email_normalization():
"""The 'email' field should be automatically normalized upon saving."""
email = factories.IdentityFactory()
email.email = "Thomas.Jefferson@Example.com"
email.save()
assert email.email == "Thomas.Jefferson@example.com"
def test_models_identities_ordering():
"""Identities should be returned ordered by main status then by their email address."""
user = factories.UserFactory()
factories.IdentityFactory.create_batch(5, user=user)
emails = models.Identity.objects.all()
assert emails[0].is_main is True
for i in range(3):
assert emails[i + 1].is_main is False
assert emails[i + 2].email >= emails[i + 1].email
def test_models_identities_sub_null():
"""The 'sub' field should not be null."""
user = factories.UserFactory()
with pytest.raises(ValidationError, match="This field cannot be null."):
models.Identity.objects.create(user=user, sub=None)
def test_models_identities_sub_blank():
"""The 'sub' field should not be blank."""
user = factories.UserFactory()
with pytest.raises(ValidationError, match="This field cannot be blank."):
models.Identity.objects.create(user=user, email="david@example.com", sub="")
def test_models_identities_sub_unique():
"""The 'sub' field should be unique."""
user = factories.UserFactory()
identity = factories.IdentityFactory()
with pytest.raises(ValidationError, match="Identity with this Sub already exists."):
models.Identity.objects.create(user=user, sub=identity.sub)
def test_models_identities_sub_max_length():
"""The 'sub' field should be 255 characters maximum."""
factories.IdentityFactory(sub="a" * 255)
with pytest.raises(ValidationError) as excinfo:
factories.IdentityFactory(sub="a" * 256)
assert (
str(excinfo.value)
== "{'sub': ['Ensure this value has at most 255 characters (it has 256).']}"
)
def test_models_identities_sub_special_characters():
"""The 'sub' field should accept periods, dashes, +, @ and underscores."""
identity = factories.IdentityFactory(sub="dave.bowman-1+2@hal_9000")
assert identity.sub == "dave.bowman-1+2@hal_9000"
def test_models_identities_sub_spaces():
"""The 'sub' field should not accept spaces."""
with pytest.raises(ValidationError) as excinfo:
factories.IdentityFactory(sub="a b")
assert str(excinfo.value) == (
"{'sub': ['Enter a valid sub. This value may contain only letters, numbers, "
"and @/./+/-/_ characters.']}"
)
def test_models_identities_sub_upper_case():
"""The 'sub' field should accept upper case characters."""
identity = factories.IdentityFactory(sub="John")
assert identity.sub == "John"
def test_models_identities_sub_ascii():
"""The 'sub' field should accept non ASCII letters."""
identity = factories.IdentityFactory(sub="rené")
assert identity.sub == "rené"
@@ -84,7 +84,7 @@ def test_models_invitations__is_expired(settings):
def test_models_invitation__new_user__convert_invitations_to_accesses():
"""
Upon creating a new identity, invitations linked to that email
Upon creating a new user, invitations linked to that email
should be converted to accesses and then deleted.
"""
# Two invitations to the same mail but to different teams
@@ -95,16 +95,14 @@ def test_models_invitation__new_user__convert_invitations_to_accesses():
team=invitation_to_team2.team
) # another person invited to team2
new_identity = factories.IdentityFactory(
is_main=True, email=invitation_to_team1.email
)
new_user = factories.UserFactory(email=invitation_to_team1.email)
# The invitation regarding
assert models.TeamAccess.objects.filter(
team=invitation_to_team1.team, user=new_identity.user
team=invitation_to_team1.team, user=new_user
).exists()
assert models.TeamAccess.objects.filter(
team=invitation_to_team2.team, user=new_identity.user
team=invitation_to_team2.team, user=new_user
).exists()
assert not models.Invitation.objects.filter(
team=invitation_to_team1.team, email=invitation_to_team1.email
@@ -119,7 +117,7 @@ def test_models_invitation__new_user__convert_invitations_to_accesses():
def test_models_invitation__new_user__filter_expired_invitations():
"""
Upon creating a new identity, valid invitations should be converted into accesses
Upon creating a new user, valid invitations should be converted into accesses
and expired invitations should remain unchanged.
"""
with freeze_time("2020-01-01"):
@@ -127,11 +125,11 @@ def test_models_invitation__new_user__filter_expired_invitations():
user_email = expired_invitation.email
valid_invitation = factories.InvitationFactory(email=user_email)
new_identity = factories.IdentityFactory(is_main=True, email=user_email)
new_user = factories.UserFactory(email=user_email)
# valid invitation should have granted access to the related team
assert models.TeamAccess.objects.filter(
team=valid_invitation.team, user=new_identity.user
team=valid_invitation.team, user=new_user
).exists()
assert not models.Invitation.objects.filter(
team=valid_invitation.team, email=user_email
@@ -139,14 +137,14 @@ def test_models_invitation__new_user__filter_expired_invitations():
# expired invitation should not have been consumed
assert not models.TeamAccess.objects.filter(
team=expired_invitation.team, user=new_identity.user
team=expired_invitation.team, user=new_user
).exists()
assert models.Invitation.objects.filter(
team=expired_invitation.team, email=user_email
).exists()
@pytest.mark.parametrize("num_invitations, num_queries", [(0, 8), (1, 11), (20, 11)])
@pytest.mark.parametrize("num_invitations, num_queries", [(0, 4), (1, 7), (20, 7)])
def test_models_invitation__new_user__user_creation_constant_num_queries(
django_assert_num_queries, num_invitations, num_queries
):
@@ -160,15 +158,14 @@ def test_models_invitation__new_user__user_creation_constant_num_queries(
for _ in range(0, num_invitations):
factories.InvitationFactory(email=user_email, team=factories.TeamFactory())
user = factories.UserFactory()
factories.UserFactory()
# with no invitation, we skip an "if", resulting in 8 requests
# otherwise, we should have 11 queries with any number of invitations
with django_assert_num_queries(num_queries):
models.Identity.objects.create(
is_main=True,
models.User.objects.create(
email=user_email,
user=user,
password="!",
name="Prudence C.",
sub=uuid.uuid4(),
)
@@ -20,16 +20,13 @@ def test_models_team_accesses_str():
"""
The str representation should include user name, team full name and role.
"""
contact = factories.ContactFactory(full_name="David Bowman")
user = contact.owner
user.profile_contact = contact
user.save()
user = factories.UserFactory()
access = factories.TeamAccessFactory(
role="member",
user=user,
team__name="admins",
)
assert str(access) == "David Bowman is member in team admins"
assert str(access) == f"{user} is {access.role} in team {access.team}"
def test_models_team_accesses_unique():
@@ -77,7 +74,7 @@ def test_models_team_accesses_create_webhook():
"value": [
{
"value": str(user.id),
"email": None,
"email": user.email,
"type": "User",
}
],
@@ -120,7 +117,7 @@ def test_models_team_accesses_delete_webhook():
"value": [
{
"value": str(access.user.id),
"email": None,
"email": access.user.email,
"type": "User",
}
],
+103 -24
View File
@@ -14,13 +14,18 @@ pytestmark = pytest.mark.django_db
def test_models_users_str():
"""The str representation should be the full name."""
"""
user str representation should return name or email when avalaible.
Otherwise, it should return the sub.
"""
user = factories.UserFactory()
contact = factories.ContactFactory(full_name="david bowman", owner=user)
user.profile_contact = contact
user.save()
assert str(user) == user.name
assert str(user) == "david bowman"
no_name_user = factories.UserFactory(name=None)
assert str(no_name_user) == no_name_user.email
no_name_no_email_user = factories.UserFactory(name=None, email=None)
assert str(no_name_no_email_user) == f"User {no_name_no_email_user.sub}"
def test_models_users_id_unique():
@@ -30,21 +35,99 @@ def test_models_users_id_unique():
factories.UserFactory(id=user.id)
def test_models_users_email_unique():
"""The "admin_email" field should be unique except for the null value."""
def test_models_users_sub_null():
"""The 'sub' field should not be null."""
with pytest.raises(ValidationError, match="This field cannot be null.") as excinfo:
models.User.objects.create(sub=None, password="password")
assert str(excinfo.value) == "{'sub': ['This field cannot be null.']}"
def test_models_users_sub_blank():
"""The 'sub' field should not be blank."""
with pytest.raises(ValidationError, match="This field cannot be blank.") as excinfo:
models.User.objects.create(sub="", password="password")
assert str(excinfo.value) == "{'sub': ['This field cannot be blank.']}"
def test_models_users_sub_unique():
"""The 'sub' field should be unique."""
user = factories.UserFactory()
with pytest.raises(
ValidationError, match="User with this Admin email address already exists."
):
models.User.objects.create(admin_email=user.admin_email, password="password")
with pytest.raises(ValidationError, match="User with this Sub already exists."):
models.User.objects.create(sub=user.sub, password="password")
def test_models_users_sub_max_length():
"""The 'sub' field should be 255 characters maximum."""
factories.UserFactory(sub="a" * 255)
with pytest.raises(ValidationError) as excinfo:
factories.UserFactory(sub="a" * 256)
assert (
str(excinfo.value)
== "{'sub': ['Ensure this value has at most 255 characters (it has 256).']}"
)
def test_models_users_sub_special_characters():
"""The 'sub' field should accept periods, dashes, +, @ and underscores."""
user = factories.UserFactory(sub="dave.bowman-1+2@hal_9000")
assert user.sub == "dave.bowman-1+2@hal_9000"
def test_models_users_sub_spaces():
"""The 'sub' field should not accept spaces."""
with pytest.raises(ValidationError) as excinfo:
factories.UserFactory(sub="a b")
assert str(excinfo.value) == (
"{'sub': ['Enter a valid sub. This value may contain only letters, numbers, "
"and @/./+/-/_ characters.']}"
)
def test_models_users_sub_upper_case():
"""The 'sub' field should accept upper case characters."""
user = factories.UserFactory(sub="John")
assert user.sub == "John"
def test_models_users_sub_ascii():
"""The 'sub' field should accept non ASCII letters."""
user = factories.UserFactory(sub="rené")
assert user.sub == "rené"
def test_models_users_email_not_required():
"""The 'email' field can be blank."""
user = factories.UserFactory(email=None)
assert user.email is None
def test_models_users_email_normalization():
"""The 'email' field should be automatically normalized upon saving."""
user = factories.UserFactory()
user.email = "Thomas.Jefferson@Example.com"
user.save()
assert user.email == "Thomas.Jefferson@example.com"
def test_models_users_email_several_null():
"""Several users with a null value for the "email" field can co-exist."""
factories.UserFactory(admin_email=None)
models.User.objects.create(admin_email=None, password="foo.")
factories.UserFactory(email=None)
models.User.objects.create(email=None, sub="123", password="foo.")
assert models.User.objects.filter(admin_email__isnull=True).count() == 2
assert models.User.objects.filter(email__isnull=True).count() == 2
def test_models_users_email_not_unique():
"""The 'email' field should not necessarily be unique among users."""
user = factories.UserFactory()
other_user = factories.UserFactory(email=user.email)
assert user.email == other_user.email
def test_models_users_profile_not_owned():
@@ -78,10 +161,9 @@ def test_models_users_profile_owned_by_other():
def test_models_users_send_mail_main_existing():
"""The 'email_user' method should send mail to the user's main email address."""
main_email = factories.IdentityFactory(email="dave@example.com")
user = main_email.user
factories.IdentityFactory.create_batch(2, user=user)
"""The 'email_user' method should send mail to the user's email address."""
user = factories.UserFactory(email="dave@example.com")
factories.UserFactory.create_batch(2)
with mock.patch("django.core.mail.send_mail") as mock_send:
user.email_user("my subject", "my message")
@@ -93,22 +175,19 @@ def test_models_users_send_mail_main_existing():
def test_models_users_send_mail_main_admin():
"""
The 'email_user' method should send mail to the user's admin email address if the
user has no related identities.
The 'email_user' method should send mail to the user's email address.
"""
user = factories.UserFactory()
with mock.patch("django.core.mail.send_mail") as mock_send:
user.email_user("my subject", "my message")
mock_send.assert_called_once_with(
"my subject", "my message", None, [user.admin_email]
)
mock_send.assert_called_once_with("my subject", "my message", None, [user.email])
def test_models_users_send_mail_main_missing():
"""The 'email_user' method should fail if the user has no email address."""
user = factories.UserFactory(admin_email=None)
user = factories.UserFactory(email=None)
with pytest.raises(ValueError) as excinfo:
user.email_user("my subject", "my message")
+1 -2
View File
@@ -16,8 +16,7 @@ def test_throttle():
"""
Throttle protection should block requests if too many.
"""
identity = factories.IdentityFactory()
user = identity.user
user = factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -28,8 +28,8 @@ def test_utils_webhooks_add_user_to_group_no_webhooks():
@mock.patch.object(Logger, "info")
def test_utils_webhooks_add_user_to_group_success(mock_info):
"""The user passed to the function should get added."""
identity = factories.IdentityFactory()
access = factories.TeamAccessFactory(user=identity.user)
user = factories.UserFactory()
access = factories.TeamAccessFactory(user=user)
webhooks = factories.TeamWebhookFactory.create_batch(2, team=access.team)
with responses.RequestsMock() as rsps:
@@ -64,7 +64,7 @@ def test_utils_webhooks_add_user_to_group_success(mock_info):
"value": [
{
"value": str(access.user.id),
"email": identity.email,
"email": user.email,
"type": "User",
}
],
@@ -90,8 +90,8 @@ def test_utils_webhooks_add_user_to_group_success(mock_info):
@mock.patch.object(Logger, "info")
def test_utils_webhooks_remove_user_from_group_success(mock_info):
"""The user passed to the function should get removed."""
identity = factories.IdentityFactory()
access = factories.TeamAccessFactory(user=identity.user)
user = factories.UserFactory()
access = factories.TeamAccessFactory(user=user)
webhooks = factories.TeamWebhookFactory.create_batch(2, team=access.team)
with responses.RequestsMock() as rsps:
@@ -121,7 +121,7 @@ def test_utils_webhooks_remove_user_from_group_success(mock_info):
"value": [
{
"value": str(access.user.id),
"email": identity.email,
"email": user.email,
"type": "User",
}
],
@@ -148,8 +148,8 @@ def test_utils_webhooks_remove_user_from_group_success(mock_info):
@mock.patch.object(Logger, "info")
def test_utils_webhooks_add_user_to_group_failure(mock_info, mock_error):
"""The logger should be called on webhook call failure."""
identity = factories.IdentityFactory()
access = factories.TeamAccessFactory(user=identity.user)
user = factories.UserFactory()
access = factories.TeamAccessFactory(user=user)
webhooks = factories.TeamWebhookFactory.create_batch(2, team=access.team)
with responses.RequestsMock() as rsps:
@@ -179,7 +179,7 @@ def test_utils_webhooks_add_user_to_group_failure(mock_info, mock_error):
"value": [
{
"value": str(access.user.id),
"email": identity.email,
"email": user.email,
"type": "User",
}
],
@@ -207,8 +207,8 @@ def test_utils_webhooks_add_user_to_group_failure(mock_info, mock_error):
@mock.patch.object(Logger, "info")
def test_utils_webhooks_add_user_to_group_retries(mock_info, mock_error):
"""webhooks synchronization supports retries."""
identity = factories.IdentityFactory()
access = factories.TeamAccessFactory(user=identity.user)
user = factories.UserFactory()
access = factories.TeamAccessFactory(user=user)
webhook = factories.TeamWebhookFactory(team=access.team)
url = re.compile(r".*/Groups/.*")
@@ -236,7 +236,7 @@ def test_utils_webhooks_add_user_to_group_retries(mock_info, mock_error):
"value": [
{
"value": str(access.user.id),
"email": identity.email,
"email": user.email,
"type": "User",
}
],
@@ -262,8 +262,8 @@ def test_utils_webhooks_add_user_to_group_retries(mock_info, mock_error):
@mock.patch.object(Logger, "info")
def test_utils_synchronize_course_runs_max_retries_exceeded(mock_info, mock_error):
"""Webhooks synchronization has exceeded max retries and should get logged."""
identity = factories.IdentityFactory()
access = factories.TeamAccessFactory(user=identity.user)
user = factories.UserFactory()
access = factories.TeamAccessFactory(user=user)
webhook = factories.TeamWebhookFactory(team=access.team)
with responses.RequestsMock() as rsps:
@@ -290,7 +290,7 @@ def test_utils_synchronize_course_runs_max_retries_exceeded(mock_info, mock_erro
"value": [
{
"value": str(access.user.id),
"email": identity.email,
"email": user.email,
"type": "User",
}
],
@@ -314,8 +314,8 @@ def test_utils_synchronize_course_runs_max_retries_exceeded(mock_info, mock_erro
def test_utils_webhooks_add_user_to_group_authorization():
"""Secret token should be passed in authorization header when set."""
identity = factories.IdentityFactory()
access = factories.TeamAccessFactory(user=identity.user)
user = factories.UserFactory()
access = factories.TeamAccessFactory(user=user)
webhook = factories.TeamWebhookFactory(team=access.team, secret="123")
with responses.RequestsMock() as rsps:
+6
View File
@@ -4,6 +4,7 @@ from django.urls import path
from .views import (
DebugViewHtml,
DebugViewNewMailboxHtml,
DebugViewTxt,
)
@@ -18,4 +19,9 @@ urlpatterns = [
DebugViewTxt.as_view(),
name="debug.mail.invitation_txt",
),
path(
"__debug__/mail/new_mailbox_html",
DebugViewNewMailboxHtml.as_view(),
name="debug.mail.new_mailbox_html",
),
]
+14
View File
@@ -25,3 +25,17 @@ class DebugViewTxt(DebugBaseView):
"""Debug View for Text Email Layout"""
template_name = "mail/text/invitation.txt"
class DebugViewNewMailboxHtml(DebugBaseView):
"""Debug view for new mailbox email layout"""
template_name = "mail/html/new_mailbox.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["mailbox_data"] = {
"email": "john.doe@example.com",
"password": "6HGVAsjoog_v",
}
return context
+1
View File
@@ -4,4 +4,5 @@ NB_OBJECTS = {
"users": 1000,
"teams": 100,
"max_users_per_team": 100,
"domains": 20,
}
@@ -10,12 +10,15 @@ from uuid import uuid4
from django import db
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.utils.text import slugify
from faker import Faker
from core import models
from demo import defaults
from mailbox_manager import models as mailbox_models
from mailbox_manager.enums import MailDomainStatusChoices
fake = Faker()
@@ -115,7 +118,9 @@ def create_demo(stdout):
for i in range(defaults.NB_OBJECTS["users"]):
queue.push(
models.User(
admin_email=f"user{i:d}@example.com",
sub=uuid4(),
email=f"user{i:d}@example.com" if random.random() < 0.97 else None,
name=fake.name() if random.random() < 0.97 else None,
password="!",
is_superuser=False,
is_active=True,
@@ -125,27 +130,6 @@ def create_demo(stdout):
)
queue.flush()
with Timeit(stdout, "Creating identities"):
users_values = list(models.User.objects.values("id", "admin_email"))
for user_dict in users_values:
for i in range(
random.choices(range(5), weights=[5, 50, 30, 10, 5], k=1)[0]
):
user_email = user_dict["admin_email"]
queue.push(
models.Identity(
user_id=user_dict["id"],
sub=uuid4(),
is_main=(i == 0),
# Leave 3% of emails and names empty
email=f"identity{i:d}{user_email:s}"
if random.random() < 0.97
else None,
name=fake.name() if random.random() < 0.97 else None,
)
)
queue.flush()
with Timeit(stdout, "Creating teams"):
for i in range(defaults.NB_OBJECTS["teams"]):
queue.push(
@@ -171,6 +155,35 @@ def create_demo(stdout):
)
queue.flush()
with Timeit(stdout, "Creating domains"):
for _i in range(defaults.NB_OBJECTS["domains"]):
name = fake.domain_name()
slug = slugify(name)
queue.push(
mailbox_models.MailDomain(
name=name,
# slug should be automatic but bulk_create doesn't use save
slug=slug,
status=random.choice(MailDomainStatusChoices.choices)[0],
)
)
queue.flush()
with Timeit(stdout, "Creating accesses to domains"):
domains_ids = list(
mailbox_models.MailDomain.objects.values_list("id", flat=True)
)
for domain_id in domains_ids:
queue.push(
mailbox_models.MailDomainAccess(
domain_id=domain_id,
user_id=random.choice(users_ids),
role=models.RoleChoices.OWNER,
)
)
queue.flush()
class Command(BaseCommand):
"""A management command to create a demo database."""
@@ -10,15 +10,17 @@ User = get_user_model()
class Command(BaseCommand):
"""Management command to create superusers from an email and a password"""
"""
Management command to create superusers from a username and a password for demo purposes.
"""
help = "Create a superuser with an email and a password"
help = "Create a superuser with a username and a password for demo purposes"
def add_arguments(self, parser):
"""Define required arguments "email" and "password"."""
"""Define required arguments "username" and "password"."""
parser.add_argument(
"--admin_email",
help=("Email for the user."),
"--username",
help=("Username for the user."),
)
parser.add_argument(
"--password",
@@ -30,11 +32,11 @@ class Command(BaseCommand):
Given an email and a password, create a superuser or upgrade the existing
user to superuser status.
"""
email = options.get("admin_email")
username = options.get("username")
try:
user = User.objects.get(admin_email=email)
user = User.objects.get(sub=username)
except User.DoesNotExist:
user = User(admin_email=email)
user = User(sub=username)
message = "Superuser created successfully."
else:
if user.is_superuser and user.is_staff:
@@ -10,12 +10,13 @@ import pytest
from core import models
from demo import defaults
from mailbox_manager import models as mailbox_models
TEST_NB_OBJECTS = {
"users": 5,
"teams": 3,
"max_identities_per_user": 3,
"max_users_per_team": 5,
"domains": 2,
}
pytestmark = pytest.mark.django_db
@@ -27,10 +28,11 @@ def test_commands_create_demo():
"""The create_demo management command should create objects as expected."""
call_command("create_demo")
assert models.User.objects.count() == 5
assert models.Identity.objects.exists()
assert models.Team.objects.count() == 3
assert models.TeamAccess.objects.count() >= 3
assert models.User.objects.count() == TEST_NB_OBJECTS["users"]
assert models.Team.objects.count() == TEST_NB_OBJECTS["teams"]
assert models.TeamAccess.objects.count() >= TEST_NB_OBJECTS["teams"]
assert mailbox_models.MailDomain.objects.count() == TEST_NB_OBJECTS["domains"]
assert mailbox_models.MailDomainAccess.objects.count() == TEST_NB_OBJECTS["domains"]
def test_commands_createsuperuser():
@@ -39,6 +41,8 @@ def test_commands_createsuperuser():
with superuser permissions.
"""
call_command("createsuperuser")
call_command("createsuperuser", username="admin", password="admin")
assert models.User.objects.count() == 1
user = models.User.objects.get()
assert user.sub == "admin"
Binary file not shown.
+247 -101
View File
@@ -2,7 +2,7 @@ msgid ""
msgstr ""
"Project-Id-Version: lasuite-people\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2024-03-21 19:26+0000\n"
"POT-Creation-Date: 2024-10-15 10:52+0000\n"
"PO-Revision-Date: 2024-01-03 23:15\n"
"Last-Translator: \n"
"Language-Team: French\n"
@@ -17,212 +17,251 @@ msgstr ""
"X-Crowdin-File: backend.pot\n"
"X-Crowdin-File-ID: 2\n"
#: core/admin.py:70
#: core/admin.py:45
msgid "Personal info"
msgstr ""
#: core/admin.py:72
#: core/admin.py:47
msgid "Permissions"
msgstr ""
#: core/admin.py:84
#: core/admin.py:59
msgid "Important dates"
msgstr ""
#: core/authentication.py:81
#: core/admin.py:97
msgid "User"
msgstr ""
#: core/authentication/backends.py:82
msgid "User info contained no recognizable user identification"
msgstr ""
#: core/authentication.py:114
#: core/authentication/backends.py:90
msgid "User account is disabled"
msgstr ""
#: core/authentication/backends.py:102
msgid "Claims contained no recognizable user identification"
msgstr ""
#: core/models.py:38
#: core/enums.py:23
msgid "Failure"
msgstr ""
#: core/enums.py:24 mailbox_manager/enums.py:20
msgid "Pending"
msgstr ""
#: core/enums.py:25
msgid "Success"
msgstr ""
#: core/models.py:42
msgid "Member"
msgstr ""
#: core/models.py:39
#: core/models.py:43 mailbox_manager/enums.py:13
msgid "Administrator"
msgstr ""
#: core/models.py:40
#: core/models.py:44 mailbox_manager/enums.py:14
msgid "Owner"
msgstr ""
#: core/models.py:52
#: core/models.py:56
msgid "id"
msgstr ""
#: core/models.py:53
#: core/models.py:57
msgid "primary key for the record as UUID"
msgstr ""
#: core/models.py:59
#: core/models.py:63
msgid "created at"
msgstr ""
#: core/models.py:60
#: core/models.py:64
msgid "date and time at which a record was created"
msgstr ""
#: core/models.py:65
#: core/models.py:69
msgid "updated at"
msgstr ""
#: core/models.py:66
#: core/models.py:70
msgid "date and time at which a record was last updated"
msgstr ""
#: core/models.py:97
#: core/models.py:101
msgid "full name"
msgstr ""
#: core/models.py:98
#: core/models.py:102
msgid "short name"
msgstr ""
#: core/models.py:103
#: core/models.py:107
msgid "contact information"
msgstr ""
#: core/models.py:104
#: core/models.py:108
msgid "A JSON object containing the contact information"
msgstr ""
#: core/models.py:118
#: core/models.py:122
msgid "contact"
msgstr ""
#: core/models.py:119
#: core/models.py:123
msgid "contacts"
msgstr ""
#: core/models.py:160 core/models.py:263 core/models.py:483
msgid "email address"
msgstr ""
#: core/models.py:172
msgid "language"
msgstr ""
#: core/models.py:173
msgid "The language in which the user wants to see the interface."
msgstr ""
#: core/models.py:179
msgid "The timezone in which the user wants to see times."
msgstr ""
#: core/models.py:182
msgid "device"
msgstr ""
#: core/models.py:184
msgid "Whether the user is a device or a real user."
msgstr ""
#: core/models.py:187
msgid "staff status"
msgstr ""
#: core/models.py:189
msgid "Whether the user can log into this admin site."
msgstr ""
#: core/models.py:192
msgid "active"
msgstr ""
#: core/models.py:195
msgid ""
"Whether this user should be treated as active. Unselect this instead of "
"deleting accounts."
msgstr ""
#: core/models.py:207
msgid "user"
msgstr ""
#: core/models.py:208
msgid "users"
msgstr ""
#: core/models.py:248
#: core/models.py:167
msgid ""
"Enter a valid sub. This value may contain only letters, numbers, and @/./+/-/"
"_ characters."
msgstr ""
#: core/models.py:255
#: core/models.py:173
msgid "sub"
msgstr ""
#: core/models.py:257
#: core/models.py:175
msgid ""
"Required. 255 characters or fewer. Letters, numbers, and @/./+/-/_ "
"characters only."
msgstr ""
#: core/models.py:264
#: core/models.py:181 core/models.py:489
msgid "email address"
msgstr ""
#: core/models.py:182 mailbox_manager/models.py:20
msgid "name"
msgstr ""
#: core/models.py:266
msgid "main"
#: core/models.py:194
msgid "language"
msgstr ""
#: core/models.py:268
msgid "Designates whether the email is the main one."
#: core/models.py:195
msgid "The language in which the user wants to see the interface."
msgstr ""
#: core/models.py:274
msgid "identity"
#: core/models.py:201
msgid "The timezone in which the user wants to see times."
msgstr ""
#: core/models.py:275
msgid "identities"
#: core/models.py:204
msgid "device"
msgstr ""
#: core/models.py:282
msgid "This email address is already declared for this user."
#: core/models.py:206
msgid "Whether the user is a device or a real user."
msgstr ""
#: core/models.py:356
#: core/models.py:209
msgid "staff status"
msgstr ""
#: core/models.py:211
msgid "Whether the user can log into this admin site."
msgstr ""
#: core/models.py:214
msgid "active"
msgstr ""
#: core/models.py:217
msgid ""
"Whether this user should be treated as active. Unselect this instead of "
"deleting accounts."
msgstr ""
#: core/models.py:229
msgid "user"
msgstr ""
#: core/models.py:230
msgid "users"
msgstr ""
#: core/models.py:306
msgid "Team"
msgstr ""
#: core/models.py:357
#: core/models.py:307
msgid "Teams"
msgstr ""
#: core/models.py:417
#: core/models.py:367
msgid "Team/user relation"
msgstr ""
#: core/models.py:418
#: core/models.py:368
msgid "Team/user relations"
msgstr ""
#: core/models.py:423
#: core/models.py:373
msgid "This user is already in this team."
msgstr ""
#: core/models.py:500
#: core/models.py:462
msgid "url"
msgstr ""
#: core/models.py:463
msgid "secret"
msgstr ""
#: core/models.py:472
msgid "Team webhook"
msgstr ""
#: core/models.py:473
msgid "Team webhooks"
msgstr ""
#: core/models.py:506
msgid "Team invitation"
msgstr ""
#: core/models.py:501
#: core/models.py:507
msgid "Team invitations"
msgstr ""
#: core/models.py:526
#: core/models.py:532
msgid "This email is already associated to a registered user."
msgstr ""
#: core/models.py:568 core/models.py:573
#: core/models.py:574 core/models.py:580
msgid "Invitation to join Desk!"
msgstr ""
#: core/templates/mail/html/hello.html:159 core/templates/mail/text/hello.txt:3
msgid "Company logo"
msgstr ""
#: core/templates/mail/html/hello.html:188 core/templates/mail/text/hello.txt:5
#, python-format
msgid "Hello %(name)s"
msgstr ""
#: core/templates/mail/html/hello.html:188 core/templates/mail/text/hello.txt:5
msgid "Hello"
msgstr ""
#: core/templates/mail/html/hello.html:189 core/templates/mail/text/hello.txt:6
msgid "Thank you very much for your visit!"
msgstr ""
#: core/templates/mail/html/hello.html:221
#, python-format
msgid ""
"This mail has been sent to %(email)s by <a href=\"%(href)s\">%(name)s</a>"
msgstr ""
#: core/templates/mail/html/invitation.html:160
#: core/templates/mail/text/invitation.txt:3
msgid "La Suite Numérique"
@@ -246,7 +285,7 @@ msgstr ""
#: core/templates/mail/html/invitation.html:226
#: core/templates/mail/text/invitation.txt:14
msgid ""
"We are delighted to welcome you to our community on Equipes, your new "
"We are delighted to welcome you to our community on Régie, your new "
"companion to simplify the management of your groups efficiently, "
"intuitively, and securely."
msgstr ""
@@ -260,7 +299,7 @@ msgstr ""
#: core/templates/mail/html/invitation.html:236
#: core/templates/mail/text/invitation.txt:16
msgid "With Equipes, you will be able to:"
msgid "With Régie, you will be able to:"
msgstr ""
#: core/templates/mail/html/invitation.html:237
@@ -294,13 +333,13 @@ msgstr ""
#: core/templates/mail/html/invitation.html:252
#: core/templates/mail/text/invitation.txt:23
msgid "Visit Equipes"
msgid "Visit Régie"
msgstr ""
#: core/templates/mail/html/invitation.html:261
#: core/templates/mail/text/invitation.txt:25
msgid ""
"We are confident that Equipes will help you increase efficiency and "
"We are confident that Régie will help you increase efficiency and "
"productivity while strengthening the bond among members."
msgstr ""
@@ -320,19 +359,126 @@ msgid ""
msgstr ""
#: core/templates/mail/html/invitation.html:278
#: core/templates/mail/html/new_mailbox.html:272
#: core/templates/mail/text/invitation.txt:29
#: core/templates/mail/text/new_mailbox.txt:15
msgid "Sincerely,"
msgstr ""
msgstr "Cordialement,"
#: core/templates/mail/html/invitation.html:279
#: core/templates/mail/text/invitation.txt:31
msgid "The La Suite Numérique Team"
msgstr "L'équipe de La Suite Numérique"
#: core/templates/mail/html/new_mailbox.html:159
#: core/templates/mail/text/new_mailbox.txt:3
msgid "La Messagerie"
msgstr "La Messagerie"
#: core/templates/mail/html/new_mailbox.html:188
#: core/templates/mail/text/new_mailbox.txt:5
msgid "Welcome to La Messagerie"
msgstr "Bienvenue dans La Messagerie"
#: core/templates/mail/html/new_mailbox.html:193
#: core/templates/mail/text/new_mailbox.txt:6
msgid "La Messagerie is the email solution of La Suite."
msgstr "La Messagerie est la solution de mail de La Suite."
#: core/templates/mail/html/new_mailbox.html:199
#: core/templates/mail/text/new_mailbox.txt:7
msgid "Your mailbox has been created."
msgstr "Votre boîte mail a été créée."
#: core/templates/mail/html/new_mailbox.html:204
#: core/templates/mail/text/new_mailbox.txt:8
msgid "Please find below your login info: "
msgstr "Voici vos identifiants de connexion :"
#: core/templates/mail/html/new_mailbox.html:228
#: core/templates/mail/text/new_mailbox.txt:10
msgid "Email address: "
msgstr "Adresse email : "
#: core/templates/mail/html/new_mailbox.html:233
#: core/templates/mail/text/new_mailbox.txt:11
msgid "Temporary password (to be modify on first login): "
msgstr "Mot de passe temporaire (à modifier à la première connexion) : "
#: core/templates/mail/html/new_mailbox.html:261
#: core/templates/mail/text/new_mailbox.txt:13
msgid "Go to La Messagerie"
msgstr "Accéder à La Messagerie"
#: core/templates/mail/html/new_mailbox.html:273
#: core/templates/mail/text/new_mailbox.txt:17
msgid "La Suite Team"
msgstr "L'équipe de La Suite"
#: core/templates/mail/text/hello.txt:8
#, python-format
msgid "This mail has been sent to %(email)s by %(name)s [%(href)s]"
msgstr ""
#: people/settings.py:133
#: mailbox_manager/enums.py:12
msgid "Viewer"
msgstr ""
#: mailbox_manager/enums.py:21
msgid "Enabled"
msgstr ""
#: mailbox_manager/enums.py:22
msgid "Failed"
msgstr ""
#: mailbox_manager/enums.py:23
msgid "Disabled"
msgstr ""
#: mailbox_manager/models.py:31
msgid "Mail domain"
msgstr ""
#: mailbox_manager/models.py:32
msgid "Mail domains"
msgstr ""
#: mailbox_manager/models.py:98
msgid "User/mail domain relation"
msgstr ""
#: mailbox_manager/models.py:99
msgid "User/mail domain relations"
msgstr ""
#: mailbox_manager/models.py:171
msgid "local_part"
msgstr ""
#: mailbox_manager/models.py:185
msgid "secondary email address"
msgstr ""
#: mailbox_manager/models.py:190
msgid "Mailbox"
msgstr ""
#: mailbox_manager/models.py:191
msgid "Mailboxes"
msgstr ""
#: mailbox_manager/utils/dimail.py:137
msgid "Your new mailbox information"
msgstr "Informations concernant votre nouvelle boîte mail"
#: people/settings.py:134
msgid "English"
msgstr ""
#: people/settings.py:134
#: people/settings.py:135
msgid "French"
msgstr ""
#~ msgid "Regards,"
#~ msgstr "Cordialement,"
+29 -3
View File
@@ -6,6 +6,14 @@ from django.utils.translation import gettext_lazy as _
from mailbox_manager import models
class UserMailDomainAccessInline(admin.TabularInline):
"""Inline admin class for mail domain accesses."""
extra = 0
model = models.MailDomainAccess
readonly_fields = ("created_at", "updated_at", "domain", "user")
@admin.register(models.MailDomain)
class MailDomainAdmin(admin.ModelAdmin):
"""Mail domain admin interface declaration."""
@@ -14,20 +22,38 @@ class MailDomainAdmin(admin.ModelAdmin):
"name",
"created_at",
"updated_at",
"slug",
"status",
)
search_fields = ("name",)
readonly_fields = ["created_at"]
readonly_fields = ["created_at", "slug"]
inlines = (UserMailDomainAccessInline,)
@admin.register(models.MailDomainAccess)
class MailDomainAccessAdmin(admin.ModelAdmin):
"""Admin for mail domain accesses model."""
list_display = ("user", "domain")
list_display = (
"user",
"domain",
"role",
"created_at",
"updated_at",
)
class MailDomainAccessInline(admin.TabularInline):
"""Inline admin class for mail domain accesses."""
extra = 0
autocomplete_fields = ["user", "domain"]
model = models.MailDomainAccess
readonly_fields = ("created_at", "updated_at")
@admin.register(models.Mailbox)
class MailboxAdmin(admin.ModelAdmin):
"""Admin for mailbox model."""
list_display = ("__str__", "domain")
list_display = ("__str__", "first_name", "last_name")
@@ -2,6 +2,8 @@
from core.api import permissions as core_permissions
from mailbox_manager import models
class AccessPermission(core_permissions.IsAuthenticated):
"""Permission class for access objects."""
@@ -10,3 +12,21 @@ class AccessPermission(core_permissions.IsAuthenticated):
"""Check permission for a given object."""
abilities = obj.get_abilities(request.user)
return abilities.get(request.method.lower(), False)
class MailBoxPermission(core_permissions.IsAuthenticated):
"""Permission class to manage mailboxes for a mail domain"""
def has_permission(self, request, view):
domain = models.MailDomain.objects.get(slug=view.kwargs.get("domain_slug", ""))
abilities = domain.get_abilities(request.user)
return abilities.get(request.method.lower(), False)
class MailDomainAccessRolePermission(core_permissions.IsAuthenticated):
"""Permission class to manage mailboxes for a mail domain"""
def has_object_permission(self, request, view, obj):
"""Check permission for a given object."""
abilities = obj.get_abilities(request.user)
return abilities.get(request.method.lower(), False)
+144 -7
View File
@@ -1,8 +1,14 @@
"""Client serializers for People's mailbox manager app."""
from rest_framework import serializers
import json
from mailbox_manager import models
from rest_framework import exceptions, serializers
from core.api.serializers import UserSerializer
from core.models import User
from mailbox_manager import enums, models
from mailbox_manager.utils.dimail import DimailAPIClient
class MailboxSerializer(serializers.ModelSerializer):
@@ -10,25 +16,152 @@ class MailboxSerializer(serializers.ModelSerializer):
class Meta:
model = models.Mailbox
fields = ["id", "local_part", "secondary_email"]
fields = ["id", "first_name", "last_name", "local_part", "secondary_email"]
# everything is actually read-only as we do not allow update for now
read_only_fields = ["id"]
def create(self, validated_data):
"""
Override create function to fire a request on mailbox creation.
"""
# send new mailbox request to dimail
client = DimailAPIClient()
response = client.send_mailbox_request(
validated_data, self.context["request"].user.sub
)
# fix format to have actual json, and remove uuid
mailbox_data = json.loads(response.content.decode("utf-8").replace("'", '"'))
del mailbox_data["uuid"]
# actually save mailbox on our database
instance = models.Mailbox.objects.create(**validated_data)
# send confirmation email
client.send_new_mailbox_notification(
recipient=validated_data["secondary_email"], mailbox_data=mailbox_data
)
return instance
class MailDomainSerializer(serializers.ModelSerializer):
"""Serialize mail domain."""
abilities = serializers.SerializerMethodField(read_only=True)
class Meta:
model = models.MailDomain
lookup_field = "slug"
fields = [
"id",
"name",
"slug",
"status",
"abilities",
"created_at",
"updated_at",
]
read_only_fields = [
"id",
"slug",
"status",
"abilities",
"created_at",
"updated_at",
]
def get_abilities(self, domain) -> dict:
"""Return abilities of the logged-in user on the instance."""
request = self.context.get("request")
if request:
return domain.get_abilities(request.user)
return {}
class MailDomainAccessSerializer(serializers.ModelSerializer):
"""Serialize mail domain accesses."""
"""Serialize mail domain access."""
user = UserSerializer(read_only=True, fields=["id", "name", "email"])
can_set_role_to = serializers.SerializerMethodField(read_only=True)
class Meta:
model = models.MailDomainAccess
fields = ["id", "user", "role", "can_set_role_to"]
read_only_fields = ["id", "can_set_role_to"]
def update(self, instance, validated_data):
"""Make "user" field is readonly but only on update."""
validated_data.pop("user", None)
return super().update(instance, validated_data)
def get_can_set_role_to(self, access):
"""Return roles available to set for the authenticated user"""
return access.get_can_set_role_to(self.context.get("request").user)
def validate(self, attrs):
"""
Check access rights specific to writing (update/create)
"""
request = self.context.get("request")
authenticated_user = getattr(request, "user", None)
role = attrs.get("role")
# Update
if self.instance:
can_set_role_to = self.instance.get_can_set_role_to(authenticated_user)
if role and role not in can_set_role_to:
message = (
f"You are only allowed to set role to {', '.join(can_set_role_to)}"
if can_set_role_to
else "You are not allowed to modify role for this user."
)
raise exceptions.PermissionDenied(message)
# Create
else:
# A domain slug has to be set to create a new access
try:
domain_slug = self.context["domain_slug"]
except KeyError as exc:
raise exceptions.ValidationError(
"You must set a domain slug in kwargs to create a new domain access."
) from exc
try:
access = authenticated_user.mail_domain_accesses.get(
domain__slug=domain_slug
)
except models.MailDomainAccess.DoesNotExist as exc:
raise exceptions.PermissionDenied(
"You are not allowed to manage accesses for this domain."
) from exc
# Authenticated user must be owner or admin of current domain to set new roles
if access.role not in [
enums.MailDomainRoleChoices.OWNER,
enums.MailDomainRoleChoices.ADMIN,
]:
raise exceptions.PermissionDenied(
"You are not allowed to manage accesses for this domain."
)
# only an owner can set an owner role to another user
if (
role == enums.MailDomainRoleChoices.OWNER
and access.role != enums.MailDomainRoleChoices.OWNER
):
raise exceptions.PermissionDenied(
"Only owners of a domain can assign other users as owners."
)
attrs["user"] = User.objects.get(pk=self.initial_data["user"])
attrs["domain"] = models.MailDomain.objects.get(
slug=self.context["domain_slug"]
)
return attrs
class MailDomainAccessReadOnlySerializer(MailDomainAccessSerializer):
"""Serialize mail domain access for list and retrieve actions."""
class Meta:
model = models.MailDomainAccess
@@ -36,7 +169,11 @@ class MailDomainAccessSerializer(serializers.ModelSerializer):
"id",
"user",
"role",
"created_at",
"updated_at",
"can_set_role_to",
]
read_only_fields = [
"id",
"user",
"role",
"can_set_role_to",
]
read_only_fields = ["id"]
+130 -14
View File
@@ -1,11 +1,12 @@
"""API endpoints"""
from rest_framework import filters, mixins, viewsets
from rest_framework import permissions as drf_permissions
from django.db.models import Subquery
from rest_framework import exceptions, filters, mixins, viewsets
from core import models as core_models
from mailbox_manager import models
from mailbox_manager import enums, models
from mailbox_manager.api import permissions, serializers
@@ -14,7 +15,6 @@ class MailDomainViewSet(
mixins.CreateModelMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet,
):
"""
@@ -29,9 +29,6 @@ class MailDomainViewSet(
POST /api/<version>/mail-domains/ with expected data:
- name: str
Return newly created domain
DELETE /api/<version>/mail-domains/<domain-slug>/
Delete targeted team access
"""
permission_classes = [permissions.AccessPermission]
@@ -58,19 +55,125 @@ class MailDomainViewSet(
# pylint: disable=too-many-ancestors
class MailDomainAccessViewSet(
mixins.ListModelMixin,
viewsets.GenericViewSet,
mixins.ListModelMixin,
mixins.CreateModelMixin,
mixins.UpdateModelMixin,
mixins.RetrieveModelMixin,
mixins.DestroyModelMixin,
):
"""
MailDomainAccess viewset.
API ViewSet for all interactions with mail domain accesses.
GET /api/v1.0/mail-domains/<domain_slug>/accesses/:<domain_access_id>
Return list of all domain accesses related to the logged-in user and one
domain access if an id is provided.
POST /api/v1.0/mail-domains/<domain_slug>/accesses/ with expected data:
- user: str
- role: str [owner|admin|viewer]
Return newly created mail domain access
PUT /api/v1.0/mail-domains/<domain_slug>/accesses/<domain_access_id>/ with expected data:
- role: str [owner|admin|viewer]
Return updated domain access
PATCH /api/v1.0/mail-domains/<domain_slug>/accesses/<domain_access_id>/ with expected data:
- role: str [owner|admin|viewer]
Return partially updated domain access
DELETE /api/v1.0/mail-domains/<domain_slug>/accesses/<domain_access_id>/
Delete targeted domain access
"""
permission_classes = [drf_permissions.IsAuthenticated]
permission_classes = [permissions.MailDomainAccessRolePermission]
serializer_class = serializers.MailDomainAccessSerializer
filter_backends = [filters.OrderingFilter]
ordering_fields = ["created_at", "user", "domain", "role"]
ordering_fields = ["role", "user__email", "user__name"]
ordering = ["-created_at"]
queryset = models.MailDomainAccess.objects.all()
queryset = (
models.MailDomainAccess.objects.all()
.select_related("user")
.order_by("-created_at")
)
list_serializer_class = serializers.MailDomainAccessReadOnlySerializer
detail_serializer_class = serializers.MailDomainAccessSerializer
def get_serializer_class(self):
if self.action in {"list", "retrieve"}:
return self.list_serializer_class
return self.detail_serializer_class
def get_serializer_context(self):
"""Extra context provided to the serializer class."""
context = super().get_serializer_context()
context["domain_slug"] = self.kwargs["domain_slug"]
context["authenticated_user"] = self.request.user
return context
def get_queryset(self):
"""Return the queryset according to the action."""
queryset = super().get_queryset()
queryset = queryset.filter(domain__slug=self.kwargs["domain_slug"])
if self.action in {"list", "retrieve"}:
# Determine which role the logged-in user has in the domain
user_role_query = models.MailDomainAccess.objects.filter(
user=self.request.user, domain__slug=self.kwargs["domain_slug"]
).values("role")[:1]
queryset = (
# The logged-in user should be part of a domain to see its accesses
queryset.filter(
domain__accesses__user=self.request.user,
)
# Abilities are computed based on logged-in user's role and
# the user role on each domain access
.annotate(
user_role=Subquery(user_role_query),
)
.select_related("user")
.distinct()
)
return queryset
def perform_update(self, serializer):
"""Check that we don't change the role if it leads to losing the last owner."""
instance = serializer.instance
# Check if the role is being updated and the new role is not "owner"
if (
"role" in self.request.data
and self.request.data["role"] != enums.MailDomainRoleChoices.OWNER
):
domain = instance.domain
# Check if the access being updated is the last owner access for the domain
if (
instance.role == enums.MailDomainRoleChoices.OWNER
and domain.accesses.filter(
role=enums.MailDomainRoleChoices.OWNER
).count()
== 1
):
message = "Cannot change the role to a non-owner role for the last owner access."
raise exceptions.PermissionDenied({"role": message})
serializer.save()
def destroy(self, request, *args, **kwargs):
"""Forbid deleting the last owner access"""
instance = self.get_object()
domain = instance.domain
# Check if the access being deleted is the last owner access for the domain
if (
instance.role == enums.MailDomainRoleChoices.OWNER
and domain.accesses.filter(role=enums.MailDomainRoleChoices.OWNER).count()
== 1
):
message = "Cannot delete the last owner access for the domain."
raise exceptions.PermissionDenied({"detail": message})
return super().destroy(request, *args, **kwargs)
class MailBoxViewSet(
@@ -78,10 +181,23 @@ class MailBoxViewSet(
mixins.ListModelMixin,
viewsets.GenericViewSet,
):
"""MailBox ViewSet"""
"""MailBox ViewSet
permission_classes = [drf_permissions.IsAuthenticated]
GET /api/<version>/mail-domains/<domain-slug>/mailboxes/
Return a list of mailboxes on the domain
POST /api/<version>/mail-domains/<domain-slug>/mailboxes/ with expected data:
- first_name: str
- last_name: str
- local_part: str
- secondary_email: str
Sends request to email provisioning API and returns newly created mailbox
"""
permission_classes = [permissions.MailBoxPermission]
serializer_class = serializers.MailboxSerializer
filter_backends = [filters.OrderingFilter]
ordering = ["-created_at"]
queryset = models.Mailbox.objects.all()
def get_queryset(self):
+23
View File
@@ -0,0 +1,23 @@
"""
Application enums declaration
"""
from django.db import models
from django.utils.translation import gettext_lazy as _
class MailDomainRoleChoices(models.TextChoices):
"""Defines the possible roles a user can have to access to a mail domain."""
VIEWER = "viewer", _("Viewer")
ADMIN = "administrator", _("Administrator")
OWNER = "owner", _("Owner")
class MailDomainStatusChoices(models.TextChoices):
"""Defines the possible statuses in which a mail domain can be."""
PENDING = "pending", _("Pending")
ENABLED = "enabled", _("Enabled")
FAILED = "failed", _("Failed")
DISABLED = "disabled", _("Disabled")
+21 -11
View File
@@ -10,13 +10,15 @@ from faker import Faker
from core import factories as core_factories
from core import models as core_models
from mailbox_manager import models
from mailbox_manager import enums, models
fake = Faker()
class MailDomainFactory(factory.django.DjangoModelFactory):
"""A factory to create mail domain."""
"""A factory to create mail domain. Please not this is a factory to create mail domain with
default values. So the status is pending and no mailbox can be created from it,
until the mail domain is enabled."""
class Meta:
model = models.MailDomain
@@ -40,6 +42,12 @@ class MailDomainFactory(factory.django.DjangoModelFactory):
)
class MailDomainEnabledFactory(MailDomainFactory):
"""A factory to create mail domain enabled."""
status = enums.MailDomainStatusChoices.ENABLED
class MailDomainAccessFactory(factory.django.DjangoModelFactory):
"""A factory to create mail domain accesses."""
@@ -47,21 +55,23 @@ class MailDomainAccessFactory(factory.django.DjangoModelFactory):
model = models.MailDomainAccess
user = factory.SubFactory(core_factories.UserFactory)
domain = factory.SubFactory(MailDomainFactory)
role = factory.fuzzy.FuzzyChoice([r[0] for r in core_models.RoleChoices.choices])
domain = factory.SubFactory(MailDomainEnabledFactory)
role = factory.fuzzy.FuzzyChoice(
[r[0] for r in enums.MailDomainRoleChoices.choices]
)
class MailboxFactory(factory.django.DjangoModelFactory):
"""A factory to create mailboxes for mail domain members."""
"""A factory to create mailboxes for a mail domain."""
class Meta:
model = models.Mailbox
class Params:
"""Parameters for fields."""
first_name = factory.Faker("first_name", locale="fr_FR")
last_name = factory.Faker("last_name", locale="de_DE")
full_name = factory.Faker("name")
local_part = factory.LazyAttribute(lambda a: a.full_name.lower().replace(" ", "."))
domain = factory.SubFactory(MailDomainFactory)
local_part = factory.LazyAttribute(
lambda a: f"{slugify(a.first_name)}.{slugify(a.last_name)}"
)
domain = factory.SubFactory(MailDomainEnabledFactory)
secondary_email = factory.Faker("email")
@@ -0,0 +1,148 @@
"""Management command creating a dimail-api container, for test purposes."""
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
import requests
from rest_framework import status
User = get_user_model()
DIMAIL_URL = "http://host.docker.internal:8001"
admin = {"username": "admin", "password": "admin"}
regie = {"username": "la_regie", "password": "password"}
class Command(BaseCommand):
"""
Management command populate local dimail database, to ease dev
"""
help = "Populate local dimail database, for dev purposes."
def handle(self, *args, **options):
"""Handling of the management command."""
if not settings.DEBUG:
raise CommandError(
("This command is meant to run in local dev environment.")
)
# Create a first superuser for dimail-api container. User creation is usually
# protected behind admin rights but dimail allows to create a first user
# when database is empty
self.create_user(
auth=(None, None),
name=admin["username"],
password=admin["password"],
perms=[],
)
# Create Regie user, auth for all remaining requests
# and your own dev
self.create_user(
auth=(admin["username"], admin["password"]),
name=regie["username"],
password=regie["password"],
perms=["new_domain", "create_users", "manage_users"],
)
# we create a dimail user for keycloak+regie user John Doe
# This way, la Régie will be able to make request in the name of
# this user
people_base_user = User.objects.get(name="John Doe")
self.create_user(name=people_base_user.sub, password="whatever") # noqa S106
# we create a domain and add John Doe to it
domain_name = "test.domain.com"
self.create_domain(domain_name)
self.create_allows(people_base_user.sub, domain_name)
self.stdout.write("DONE", ending="\n")
def create_user(
self,
name,
password,
perms=None,
auth=(regie["username"], regie["password"]),
):
"""
Send a request to create a new user.
"""
response = requests.post(
url=f"{DIMAIL_URL}/users/",
json={
"name": name,
"password": password,
"is_admin": name == admin["username"],
"perms": perms or [],
},
auth=auth,
timeout=10,
)
if response.status_code == status.HTTP_201_CREATED:
self.stdout.write(self.style.SUCCESS(f"Creating user {name}......... OK"))
else:
self.stdout.write(
self.style.ERROR(
f"Creating user {name} ......... failed: {response.json()['detail']}"
)
)
def create_domain(self, name, auth=(regie["username"], regie["password"])):
"""
Send a request to create a new domain.
"""
response = requests.post(
url=f"{DIMAIL_URL}/domains/",
json={
"name": name,
"context_name": "context",
"features": ["webmail", "mailbox", "alias"],
},
auth=auth,
timeout=10,
)
if response.status_code == status.HTTP_201_CREATED:
self.stdout.write(
self.style.SUCCESS(f"Creating domain '{name}' ........ OK")
)
else:
self.stdout.write(
self.style.ERROR(
f"Creating domain '{name}' ........ failed: {response.json()['detail']}"
)
)
def create_allows(self, user, domain, auth=(regie["username"], regie["password"])):
"""
Send a request to create a new allows between user and domain.
"""
response = requests.post(
url=f"{DIMAIL_URL}/allows/",
json={
"domain": domain,
"user": user,
},
auth=auth,
timeout=10,
)
if response.status_code == status.HTTP_201_CREATED:
self.stdout.write(
self.style.SUCCESS(
f"Creating permissions for {user} on {domain} ........ OK"
)
)
else:
self.stdout.write(
self.style.ERROR(
f"Creating permissions for {user} on {domain}\
........ failed: {response.json()['detail']}"
)
)
@@ -0,0 +1,18 @@
# Generated by Django 5.0.6 on 2024-07-06 23:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mailbox_manager', '0005_alter_maildomain_slug'),
]
operations = [
migrations.AddField(
model_name='maildomain',
name='status',
field=models.CharField(choices=[('pending', 'Pending'), ('enabled', 'Enabled'), ('failed', 'Failed'), ('disabled', 'Disabled')], default='pending', max_length=10),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 5.0.6 on 2024-08-02 15:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mailbox_manager', '0006_maildomain_status'),
]
operations = [
migrations.AlterField(
model_name='maildomainaccess',
name='role',
field=models.CharField(choices=[('viewer', 'Viewer'), ('administrator', 'Administrator'), ('owner', 'Owner')], default='viewer', max_length=20),
),
]
@@ -0,0 +1,23 @@
# Generated by Django 5.0.6 on 2024-08-07 09:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mailbox_manager', '0007_alter_maildomainaccess_role'),
]
operations = [
migrations.AddField(
model_name='mailbox',
name='first_name',
field=models.CharField(blank=True, max_length=200),
),
migrations.AddField(
model_name='mailbox',
name='last_name',
field=models.CharField(blank=True, max_length=200),
),
]
@@ -0,0 +1,22 @@
# Generated by Django 5.0.6 on 2024-08-07 09:43
from django.db import migrations, models
from django.db.models import F
def populate_first_name_last_name(apps, schema_editor):
Mailbox = apps.get_model('mailbox_manager', 'Mailbox')
Mailbox.objects.filter(first_name='').update(first_name=F("local_part"))
Mailbox.objects.filter(last_name='').update(last_name=F("local_part"))
class Migration(migrations.Migration):
dependencies = [
('mailbox_manager', '0008_mailbox_first_name_mailbox_last_name'),
]
operations = [
migrations.RunPython(populate_first_name_last_name, reverse_code=migrations.RunPython.noop),
]
@@ -0,0 +1,23 @@
# Generated by Django 5.0.6 on 2024-08-07 10:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mailbox_manager', '0009_fill_mailbox_first_name_mailbox_last_name'),
]
operations = [
migrations.AlterField(
model_name='mailbox',
name='first_name',
field=models.CharField(max_length=200),
),
migrations.AlterField(
model_name='mailbox',
name='last_name',
field=models.CharField(max_length=200),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 5.0.6 on 2024-07-01 16:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mailbox_manager', '0010_alter_mailbox_first_name_alter_mailbox_last_name'),
]
operations = [
migrations.AddField(
model_name='maildomain',
name='secret',
field=models.CharField(blank=True, max_length=255, null=True, verbose_name='secret'),
),
]
@@ -0,0 +1,19 @@
# Generated by Django 5.1 on 2024-08-30 10:09
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mailbox_manager', '0011_maildomain_secret'),
]
operations = [
migrations.AlterField(
model_name='mailbox',
name='local_part',
field=models.CharField(max_length=150, validators=[django.core.validators.RegexValidator(regex='^[a-zA-Z0-9_.-]+$')], verbose_name='local_part'),
),
]
@@ -0,0 +1,17 @@
# Generated by Django 5.1 on 2024-08-30 12:46
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mailbox_manager', '0012_alter_mailbox_local_part'),
]
operations = [
migrations.RemoveField(
model_name='maildomain',
name='secret',
),
]
+114 -9
View File
@@ -3,12 +3,14 @@ Declare and configure the models for the People additional application : mailbox
"""
from django.conf import settings
from django.core import validators
from django.core import exceptions, validators
from django.db import models
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _
from core.models import BaseModel, RoleChoices
from core.models import BaseModel
from mailbox_manager.enums import MailDomainRoleChoices, MailDomainStatusChoices
class MailDomain(BaseModel):
@@ -18,6 +20,11 @@ class MailDomain(BaseModel):
_("name"), max_length=150, null=False, blank=False, unique=True
)
slug = models.SlugField(null=False, blank=False, unique=True, max_length=80)
status = models.CharField(
max_length=10,
default=MailDomainStatusChoices.PENDING,
choices=MailDomainStatusChoices.choices,
)
class Meta:
db_table = "people_mail_domain"
@@ -28,15 +35,18 @@ class MailDomain(BaseModel):
return self.name
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
"""Override save function to compute the slug."""
self.slug = self.get_slug()
return super().save(*args, **kwargs)
def get_slug(self):
"""Compute slug value from name."""
return slugify(self.name)
def get_abilities(self, user):
"""
Compute and return abilities for a given user on the domain.
"""
is_owner_or_admin = False
role = None
if user.is_authenticated:
@@ -45,13 +55,17 @@ class MailDomain(BaseModel):
except (MailDomainAccess.DoesNotExist, IndexError):
role = None
is_owner_or_admin = role in [RoleChoices.OWNER, RoleChoices.ADMIN]
is_owner_or_admin = role in [
MailDomainRoleChoices.OWNER,
MailDomainRoleChoices.ADMIN,
]
return {
"get": bool(role),
"patch": is_owner_or_admin,
"put": is_owner_or_admin,
"delete": role == RoleChoices.OWNER,
"post": is_owner_or_admin,
"delete": role == MailDomainRoleChoices.OWNER,
"manage_accesses": is_owner_or_admin,
}
@@ -74,7 +88,9 @@ class MailDomainAccess(BaseModel):
blank=False,
)
role = models.CharField(
max_length=20, choices=RoleChoices.choices, default=RoleChoices.MEMBER
max_length=20,
choices=MailDomainRoleChoices.choices,
default=MailDomainRoleChoices.VIEWER,
)
class Meta:
@@ -86,16 +102,77 @@ class MailDomainAccess(BaseModel):
def __str__(self):
return f"Access of user {self.user} on domain {self.domain}."
def get_can_set_role_to(self, user):
"""Return roles available to set"""
if not user.is_authenticated:
return []
roles = list(MailDomainRoleChoices)
authenticated_user_role = None
# get role of authenticated user
if hasattr(self, "user_role"):
authenticated_user_role = self.user_role
else:
try:
authenticated_user_role = user.mail_domain_accesses.get(
domain=self.domain
).role
except (MailDomainAccess.DoesNotExist, IndexError):
return []
# only an owner can set an owner role
if authenticated_user_role != MailDomainRoleChoices.OWNER:
roles.remove(MailDomainRoleChoices.OWNER)
# if the user authenticated is a viewer, they can't modify role
# and only an owner can change role of an owner
if authenticated_user_role == MailDomainRoleChoices.VIEWER or (
authenticated_user_role != MailDomainRoleChoices.OWNER
and self.role == MailDomainRoleChoices.OWNER
):
return []
# we only want to return other roles available to change,
# so we remove the current role of current access.
roles.remove(self.role)
return sorted(roles)
def get_abilities(self, user):
"""
Compute and return abilities for a given user on the domain access.
"""
role = None
if user.is_authenticated:
try:
role = user.mail_domain_accesses.filter(domain=self.domain).get().role
except (MailDomainAccess.DoesNotExist, IndexError):
role = None
is_owner_or_admin = role in [
MailDomainRoleChoices.OWNER,
MailDomainRoleChoices.ADMIN,
]
return {
"get": bool(role),
"patch": is_owner_or_admin,
"put": is_owner_or_admin,
"post": is_owner_or_admin,
"delete": is_owner_or_admin,
}
class Mailbox(BaseModel):
"""Mailboxes for users from mail domain."""
first_name = models.CharField(max_length=200, blank=False)
last_name = models.CharField(max_length=200, blank=False)
local_part = models.CharField(
_("local_part"),
max_length=150,
null=False,
blank=False,
validators=[validators.RegexValidator(regex="^[a-zA-Z0-9_.+-]+$")],
validators=[validators.RegexValidator(regex="^[a-zA-Z0-9_.-]+$")],
)
domain = models.ForeignKey(
MailDomain,
@@ -116,3 +193,31 @@ class Mailbox(BaseModel):
def __str__(self):
return f"{self.local_part!s}@{self.domain.name:s}"
def clean(self):
"""
Mailboxes can only be created on enabled domains.
Also, mail-provisioning API credentials must be set for dimail to allow auth.
"""
if self.domain.status != MailDomainStatusChoices.ENABLED:
raise exceptions.ValidationError(
"You can create mailbox only for a domain enabled"
)
# Won't be able to query user token if MAIL_PROVISIONING_API_CREDENTIALS are not set
if not settings.MAIL_PROVISIONING_API_CREDENTIALS:
raise exceptions.ValidationError(
"Please configure MAIL_PROVISIONING_API_CREDENTIALS before creating any mailbox."
)
def save(self, *args, **kwargs):
"""
Modification is forbidden for now.
"""
self.full_clean()
if self._state.adding:
return super().save(*args, **kwargs)
# Update is not implemented for now
raise NotImplementedError()
@@ -0,0 +1,2 @@
<h1>403 Forbidden</h1>
{{ exception }}
@@ -8,7 +8,7 @@ from rest_framework.test import APIClient
from core import factories as core_factories
from mailbox_manager import factories, models
from mailbox_manager import enums, factories, models
pytestmark = pytest.mark.django_db
@@ -31,10 +31,10 @@ def test_api_mail_domains__create_name_unique():
Creating domain should raise an error if already existing name.
"""
factories.MailDomainFactory(name="existing_domain.com")
identity = core_factories.IdentityFactory()
user = core_factories.UserFactory()
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
response = client.post(
"/api/v1.0/mail-domains/",
@@ -52,13 +52,10 @@ def test_api_mail_domains__create_authenticated():
Authenticated users should be able to create mail domains
and should automatically be added as owner of the newly created domain.
"""
identity = core_factories.IdentityFactory()
user = identity.user
user = core_factories.UserFactory()
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
response = client.post(
"/api/v1.0/mail-domains/",
{
@@ -66,8 +63,21 @@ def test_api_mail_domains__create_authenticated():
},
format="json",
)
assert response.status_code == status.HTTP_201_CREATED
domain = models.MailDomain.objects.get()
# response is as expected
assert response.json() == {
"id": str(domain.id),
"name": domain.name,
"slug": domain.slug,
"status": enums.MailDomainStatusChoices.PENDING,
"created_at": domain.created_at.isoformat().replace("+00:00", "Z"),
"updated_at": domain.updated_at.isoformat().replace("+00:00", "Z"),
"abilities": domain.get_abilities(user),
}
# a new domain with status "pending" is created and authenticated user is the owner
assert domain.status == enums.MailDomainStatusChoices.PENDING
assert domain.name == "mydomain.com"
assert domain.accesses.filter(role="owner", user=user).exists()
@@ -14,7 +14,7 @@ pytestmark = pytest.mark.django_db
def test_api_mail_domains__delete_anonymous():
"""Anonymous users should not be allowed to destroy a team."""
"""Anonymous users should not be allowed to destroy a domain."""
domain = factories.MailDomainFactory()
response = APIClient().delete(
@@ -25,83 +25,18 @@ def test_api_mail_domains__delete_anonymous():
assert models.MailDomain.objects.count() == 1
def test_api_mail_domains__delete_authenticated_unrelated():
def test_api_mail_domains__delete_authenticated():
"""
Authenticated users should not be allowed to delete a domain to which they are not
related.
Delete a domain is not allowed.
"""
identity = core_factories.IdentityFactory()
user = core_factories.UserFactory()
domain = factories.MailDomainFactory()
client = APIClient()
client.force_login(identity.user)
response = client.delete(
f"/api/v1.0/mail-domains/{domain.slug}/",
)
assert response.status_code == status.HTTP_404_NOT_FOUND
assert response.json() == {"detail": "No MailDomain matches the given query."}
assert models.MailDomain.objects.count() == 1
def test_api_mail_domains__delete_authenticated_member():
"""
Authenticated users should not be allowed to delete a domain
to which they are only a member.
"""
identity = core_factories.IdentityFactory()
user = identity.user
domain = factories.MailDomainFactory(users=[(user, "member")])
client = APIClient()
client.force_login(user)
response = client.delete(
f"/api/v1.0/mail-domains/{domain.slug}/",
)
assert response.status_code == status.HTTP_403_FORBIDDEN
assert response.json() == {
"detail": "You do not have permission to perform this action."
}
assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
assert models.MailDomain.objects.count() == 1
def test_api_mail_domains__delete_authenticated_administrator():
"""
Authenticated users should not be allowed to delete a domain
for which they are administrator.
"""
identity = core_factories.IdentityFactory()
user = identity.user
domain = factories.MailDomainFactory(users=[(user, "administrator")])
client = APIClient()
client.force_login(user)
response = client.delete(
f"/api/v1.0/mail-domains/{domain.slug}/",
)
assert response.status_code == status.HTTP_403_FORBIDDEN
assert response.json() == {
"detail": "You do not have permission to perform this action."
}
assert models.MailDomain.objects.count() == 1
def test_api_mail_domains__delete_authenticated_owner():
"""
Authenticated users should be able to delete a domain
for which they are directly owner.
"""
identity = core_factories.IdentityFactory()
user = identity.user
domain = factories.MailDomainFactory(users=[(user, "owner")])
client = APIClient()
client.force_login(user)
response = client.delete(
f"/api/v1.0/mail-domains/{domain.slug}/",
)
assert response.status_code == status.HTTP_204_NO_CONTENT
assert models.MailDomain.objects.exists() is False
@@ -32,8 +32,7 @@ def test_api_mail_domains__list_authenticated():
to which they have access.
"""
identity = core_factories.IdentityFactory()
user = identity.user
user = core_factories.UserFactory()
client = APIClient()
client.force_login(user)
@@ -42,8 +41,8 @@ def test_api_mail_domains__list_authenticated():
str(access.domain.id)
for access in factories.MailDomainAccessFactory.create_batch(5, user=user)
}
factories.MailDomainFactory.create_batch(2) # Other teams
factories.MailDomainAccessFactory.create_batch(2) # Other teams and accesses
factories.MailDomainFactory.create_batch(2) # Other domains
factories.MailDomainAccessFactory.create_batch(2) # Other domains and accesses
response = client.get(
"/api/v1.0/mail-domains/",
@@ -16,7 +16,7 @@ pytestmark = pytest.mark.django_db
def test_api_mail_domains__retrieve_anonymous():
"""Anonymous users should not be allowed to retrieve a domain."""
domain = factories.MailDomainFactory()
domain = factories.MailDomainEnabledFactory()
response = APIClient().get(f"/api/v1.0/mail-domains/{domain.slug}/")
assert response.status_code == status.HTTP_401_UNAUTHORIZED
@@ -25,17 +25,32 @@ def test_api_mail_domains__retrieve_anonymous():
}
def test_api_domains__retrieve_non_existing():
"""
Authenticated users should have an explicit error when trying to retrive
a domain that doesn't exist.
"""
client = APIClient()
client.force_login(core_factories.UserFactory())
response = client.get(
"/api/v1.0/mail-domains/nonexistent.domain/",
)
assert response.status_code == status.HTTP_404_NOT_FOUND
assert response.json() == {"detail": "Not found."}
def test_api_mail_domains__retrieve_authenticated_unrelated():
"""
Authenticated users should not be allowed to retrieve a domain
to which they have access.
"""
identity = core_factories.IdentityFactory()
user = core_factories.UserFactory()
client = APIClient()
client.force_login(identity.user)
client.force_login(user)
domain = factories.MailDomainFactory()
domain = factories.MailDomainEnabledFactory()
response = client.get(
f"/api/v1.0/mail-domains/{domain.slug}/",
@@ -49,13 +64,12 @@ def test_api_mail_domains__retrieve_authenticated_related():
Authenticated users should be allowed to retrieve a domain
to which they have access.
"""
identity = core_factories.IdentityFactory()
user = identity.user
user = core_factories.UserFactory()
client = APIClient()
client.force_login(user)
domain = factories.MailDomainFactory()
domain = factories.MailDomainEnabledFactory()
factories.MailDomainAccessFactory(domain=domain, user=user)
response = client.get(
@@ -66,6 +80,9 @@ def test_api_mail_domains__retrieve_authenticated_related():
assert response.json() == {
"id": str(domain.id),
"name": domain.name,
"slug": domain.slug,
"status": domain.status,
"created_at": domain.created_at.isoformat().replace("+00:00", "Z"),
"updated_at": domain.updated_at.isoformat().replace("+00:00", "Z"),
"abilities": domain.get_abilities(user),
}
@@ -0,0 +1,173 @@
"""
Test for mail domain accesses API endpoints in People's core app : create
"""
import random
import pytest
from rest_framework import status
from rest_framework.test import APIClient
from core import factories as core_factories
from mailbox_manager import enums, factories, models
pytestmark = pytest.mark.django_db
def test_api_mail_domain__accesses_create_anonymous():
"""Anonymous users should not be allowed to create mail domain accesses."""
user = core_factories.UserFactory()
mail_domain = factories.MailDomainFactory()
for role in [role[0] for role in enums.MailDomainRoleChoices.choices]:
response = APIClient().post(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/",
{
"user": str(user.id),
"role": role,
},
format="json",
)
assert response.status_code == status.HTTP_401_UNAUTHORIZED
assert response.json() == {
"detail": "Authentication credentials were not provided."
}
assert models.MailDomainAccess.objects.exists() is False
def test_api_mail_domain__accesses_create_authenticated_unrelated():
"""
Authenticated users should not be allowed to create domain accesses for a domain to
which they are not related.
"""
user = core_factories.UserFactory()
other_user = core_factories.UserFactory()
domain = factories.MailDomainFactory()
client = APIClient()
client.force_login(user)
for role in [role[0] for role in enums.MailDomainRoleChoices.choices]:
response = client.post(
f"/api/v1.0/mail-domains/{domain.slug}/accesses/",
{
"user": str(other_user.id),
"role": role,
},
format="json",
)
assert response.status_code == status.HTTP_403_FORBIDDEN
assert response.json() == {
"detail": "You are not allowed to manage accesses for this domain."
}
assert not models.MailDomainAccess.objects.filter(user=other_user).exists()
def test_api_mail_domain__accesses_create_authenticated_viewer():
"""Viewer of a mail domain should not be allowed to create mail domain accesses."""
authenticated_user = core_factories.UserFactory()
mail_domain = factories.MailDomainFactory(
users=[(authenticated_user, enums.MailDomainRoleChoices.VIEWER)]
)
other_user = core_factories.UserFactory()
client = APIClient()
client.force_login(authenticated_user)
for role in [role[0] for role in enums.MailDomainRoleChoices.choices]:
response = client.post(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/",
{
"user": str(other_user.id),
"role": role,
},
format="json",
)
assert response.status_code == status.HTTP_403_FORBIDDEN
assert response.json() == {
"detail": "You are not allowed to manage accesses for this domain."
}
assert not models.MailDomainAccess.objects.filter(user=other_user).exists()
def test_api_mail_domain__accesses_create_authenticated_administrator():
"""
Administrators of a domain should be able to create mail domain accesses
except for the "owner" role.
"""
authenticated_user = core_factories.UserFactory()
mail_domain = factories.MailDomainFactory(
users=[(authenticated_user, enums.MailDomainRoleChoices.ADMIN)]
)
other_user = core_factories.UserFactory()
client = APIClient()
client.force_login(authenticated_user)
# It should not be allowed to create an owner access
response = client.post(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/",
{
"user": str(other_user.id),
"role": enums.MailDomainRoleChoices.OWNER,
},
format="json",
)
assert response.status_code == status.HTTP_403_FORBIDDEN
assert response.json() == {
"detail": "Only owners of a domain can assign other users as owners."
}
# It should be allowed to create a lower access
for role in [enums.MailDomainRoleChoices.ADMIN, enums.MailDomainRoleChoices.VIEWER]:
other_user = core_factories.UserFactory()
response = client.post(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/",
{
"user": str(other_user.id),
"role": role,
},
format="json",
)
assert response.status_code == status.HTTP_201_CREATED
new_mail_domain_access = models.MailDomainAccess.objects.filter(
user=other_user
).last()
assert response.json()["id"] == str(new_mail_domain_access.id)
assert response.json()["role"] == role
assert models.MailDomainAccess.objects.filter(domain=mail_domain).count() == 3
def test_api_mail_domain__accesses_create_authenticated_owner():
"""
Owners of a mail domain should be able to create mail domain accesses whatever the role.
"""
authenticated_user = core_factories.UserFactory()
mail_domain = factories.MailDomainFactory(
users=[(authenticated_user, enums.MailDomainRoleChoices.OWNER)]
)
other_user = core_factories.UserFactory()
role = random.choice([role[0] for role in enums.MailDomainRoleChoices.choices])
client = APIClient()
client.force_login(authenticated_user)
response = client.post(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/",
{
"user": str(other_user.id),
"role": role,
},
format="json",
)
assert response.status_code == status.HTTP_201_CREATED
assert models.MailDomainAccess.objects.filter(user=other_user).count() == 1
new_mail_domain_access = models.MailDomainAccess.objects.filter(
user=other_user
).get()
assert response.json()["id"] == str(new_mail_domain_access.id)
assert response.json()["role"] == role
@@ -0,0 +1,139 @@
"""
Test for mail_domain accesses API endpoints in People's core app : delete
"""
import pytest
from rest_framework import status
from rest_framework.test import APIClient
from core import factories as core_factories
from mailbox_manager import enums, factories, models
pytestmark = pytest.mark.django_db
def test_api_mail_domain__accesses_delete_anonymous():
"""Anonymous users should not be allowed to destroy a mail domain access."""
access = factories.MailDomainAccessFactory()
response = APIClient().delete(
f"/api/v1.0/mail-domains/{access.domain.slug}/accesses/{access.id!s}/",
)
assert response.status_code == status.HTTP_401_UNAUTHORIZED
assert models.MailDomainAccess.objects.count() == 1
def test_api_mail_domain__accesses_delete_authenticated():
"""
Authenticated users should not be allowed to delete a mail domain access for a
mail domain to which they are not related.
"""
authenticated_user = core_factories.UserFactory()
access = factories.MailDomainAccessFactory()
client = APIClient()
client.force_login(authenticated_user)
response = client.delete(
f"/api/v1.0/mail-domains/{access.domain.slug}/accesses/{access.id!s}/",
)
assert response.status_code == status.HTTP_403_FORBIDDEN
assert models.MailDomainAccess.objects.count() == 1
def test_api_mail_domain__accesses_delete_viewer():
"""
Authenticated users should not be allowed to delete a mail domain access for a
mail domain in which they are a simple viewer.
"""
authenticated_user = core_factories.UserFactory()
mail_domain = factories.MailDomainFactory(
users=[(authenticated_user, enums.MailDomainRoleChoices.VIEWER)]
)
access = factories.MailDomainAccessFactory(domain=mail_domain)
client = APIClient()
client.force_login(authenticated_user)
response = client.delete(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/{access.id!s}/",
)
assert response.status_code == status.HTTP_403_FORBIDDEN
assert models.MailDomainAccess.objects.count() == 2
assert models.MailDomainAccess.objects.filter(user=access.user).exists()
def test_api_mail_domain__accesses_delete_administrators():
"""
Administrators of a mail domain should be allowed to delete accesses excepted owner accesses.
"""
authenticated_user = core_factories.UserFactory()
mail_domain = factories.MailDomainFactory(
users=[(authenticated_user, enums.MailDomainRoleChoices.ADMIN)]
)
for role in [enums.MailDomainRoleChoices.VIEWER, enums.MailDomainRoleChoices.ADMIN]:
access = factories.MailDomainAccessFactory(domain=mail_domain, role=role)
assert models.MailDomainAccess.objects.count() == 2
assert models.MailDomainAccess.objects.filter(user=access.user).exists()
client = APIClient()
client.force_login(authenticated_user)
response = client.delete(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/{access.id!s}/",
)
assert response.status_code == status.HTTP_204_NO_CONTENT
assert models.MailDomainAccess.objects.count() == 1
def test_api_mail_domain__accesses_delete_owners():
"""
An owner should be able to delete the mail domain access of another user including
a owner access.
"""
authenticated_user = core_factories.UserFactory()
mail_domain = factories.MailDomainFactory(
users=[(authenticated_user, enums.MailDomainRoleChoices.OWNER)]
)
for role in [role[0] for role in enums.MailDomainRoleChoices.choices]:
access = factories.MailDomainAccessFactory(domain=mail_domain, role=role)
assert models.MailDomainAccess.objects.count() == 2
assert models.MailDomainAccess.objects.filter(user=access.user).exists()
client = APIClient()
client.force_login(authenticated_user)
response = client.delete(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/{access.id!s}/",
)
assert response.status_code == status.HTTP_204_NO_CONTENT
assert models.MailDomainAccess.objects.count() == 1
def test_api_mail_domain__accesses_delete_owners_last_owner():
"""
It should not be possible to delete the last owner access from a mail domain
"""
authenticated_user = core_factories.UserFactory()
mail_domain = factories.MailDomainFactory()
access = factories.MailDomainAccessFactory(
domain=mail_domain,
user=authenticated_user,
role=enums.MailDomainRoleChoices.OWNER,
)
factories.MailDomainAccessFactory.create_batch(9)
assert models.MailDomainAccess.objects.count() == 10
client = APIClient()
client.force_login(authenticated_user)
response = client.delete(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/{access.id!s}/",
)
assert response.status_code == status.HTTP_403_FORBIDDEN
assert models.MailDomainAccess.objects.count() == 10
@@ -0,0 +1,260 @@
"""
Test for mail_domain accesses API endpoints in People's core app : list
"""
import pytest
from rest_framework import status
from rest_framework.test import APIClient
from core import factories as core_factories
from mailbox_manager import enums, factories, models
pytestmark = pytest.mark.django_db
def test_api_mail_domain__accesses_list_anonymous():
"""Anonymous users should not be allowed to list mail_domain accesses."""
mail_domain = factories.MailDomainFactory()
factories.MailDomainAccessFactory.create_batch(2, domain=mail_domain)
response = APIClient().get(f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/")
assert response.status_code == status.HTTP_401_UNAUTHORIZED
assert response.json() == {
"detail": "Authentication credentials were not provided."
}
def test_api_mail_domain__accesses_list_authenticated_unrelated():
"""
Authenticated users should not be allowed to list mail_domain accesses for a mail_domain
to which they are not related.
"""
user = core_factories.UserFactory()
mail_domain = factories.MailDomainFactory()
factories.MailDomainAccessFactory.create_batch(3, domain=mail_domain)
# Accesses for other mail_domains to which the user is related should not be listed either
other_access = factories.MailDomainAccessFactory(user=user)
factories.MailDomainAccessFactory(domain=other_access.domain)
client = APIClient()
client.force_login(user)
response = client.get(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/",
)
assert response.status_code == 200
assert response.json() == {
"count": 0,
"next": None,
"previous": None,
"results": [],
}
def test_api_mail_domain__accesses_list_for_authenticated_user_related_to_domain():
"""
Authenticated users should be able to list mail_domain accesses for a mail_domain
to which they are related, with a given role.
"""
viewer, administrator, owner = core_factories.UserFactory.create_batch(3)
mail_domain = factories.MailDomainFactory()
owner_access = factories.MailDomainAccessFactory.create(
domain=mail_domain, user=owner, role=enums.MailDomainRoleChoices.OWNER
)
admin_access = factories.MailDomainAccessFactory.create(
domain=mail_domain, user=administrator, role=enums.MailDomainRoleChoices.ADMIN
)
viewer_access = models.MailDomainAccess.objects.create(
domain=mail_domain, user=viewer, role=enums.MailDomainRoleChoices.VIEWER
)
admin_expected_data = {
"id": str(admin_access.id),
"user": {
"id": str(administrator.id),
"email": str(administrator.email),
"name": str(administrator.name),
},
"role": str(admin_access.role),
}
viewer_expected_data = {
"id": str(viewer_access.id),
"user": {
"id": str(viewer.id),
"email": str(viewer.email),
"name": str(viewer.name),
},
"role": str(viewer_access.role),
}
owner_expected_data = {
"id": str(owner_access.id),
"user": {
"id": str(owner.id),
"email": str(owner.email),
"name": str(owner.name),
},
"role": str(owner_access.role),
}
# Grant other mail_domain accesses to the user, they should not be listed either
other_access = factories.MailDomainAccessFactory(user=viewer)
factories.MailDomainAccessFactory(domain=other_access.domain)
client = APIClient()
client.force_login(viewer)
# viewer can see accesses but no action is available
admin_expected_data["can_set_role_to"] = []
viewer_expected_data["can_set_role_to"] = []
owner_expected_data["can_set_role_to"] = []
response = client.get(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/",
)
assert response.status_code == 200
assert response.json()["count"] == 3
expected = sorted(
[admin_expected_data, viewer_expected_data, owner_expected_data],
key=lambda x: x["role"],
)
assert sorted(response.json()["results"], key=lambda x: x["role"]) == expected
client.force_login(administrator)
# administrator can see and give new role but not an OWNER role
admin_expected_data["can_set_role_to"] = [enums.MailDomainRoleChoices.VIEWER]
viewer_expected_data["can_set_role_to"] = [enums.MailDomainRoleChoices.ADMIN]
owner_expected_data["can_set_role_to"] = []
response = client.get(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/",
)
assert response.status_code == 200
assert response.json()["count"] == 3
expected = sorted(
[admin_expected_data, viewer_expected_data, owner_expected_data],
key=lambda x: x["role"],
)
assert sorted(response.json()["results"], key=lambda x: x["role"]) == expected
client.force_login(owner)
# owner can do everything
admin_expected_data["can_set_role_to"] = [
enums.MailDomainRoleChoices.OWNER,
enums.MailDomainRoleChoices.VIEWER,
]
viewer_expected_data["can_set_role_to"] = [
enums.MailDomainRoleChoices.ADMIN,
enums.MailDomainRoleChoices.OWNER,
]
owner_expected_data["can_set_role_to"] = [
enums.MailDomainRoleChoices.ADMIN,
enums.MailDomainRoleChoices.VIEWER,
]
response = client.get(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/",
)
assert response.status_code == 200
assert response.json()["count"] == 3
expected = sorted(
[admin_expected_data, viewer_expected_data, owner_expected_data],
key=lambda x: x["role"],
)
assert sorted(response.json()["results"], key=lambda x: x["role"]) == expected
def test_api_mail_domain__accesses_list_authenticated_constant_numqueries(
django_assert_num_queries,
):
"""
The number of queries should not depend on the amount of fetched accesses.
"""
user = core_factories.UserFactory()
mail_domain = factories.MailDomainFactory()
models.MailDomainAccess.objects.create(domain=mail_domain, user=user) # random role
client = APIClient()
client.force_login(user)
# Only 3 queries are needed to efficiently fetch mail_domain accesses,
# related users :
# - query retrieving logged-in user for user_role annotation
# - count from pagination
# - distinct from viewset
with django_assert_num_queries(3):
client.get(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/",
)
# create 20 new mail_domain accesses
for _ in range(20):
factories.MailDomainAccessFactory(domain=mail_domain)
# num queries should still be the same
with django_assert_num_queries(3):
response = client.get(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/",
)
assert response.status_code == 200
assert response.json()["count"] == 21
def test_api_mail_domain__accesses_list_authenticated_ordering():
"""MailDomain accesses can be ordered by "role"."""
user = core_factories.UserFactory()
mail_domain = factories.MailDomainFactory()
models.MailDomainAccess.objects.create(domain=mail_domain, user=user)
# create 20 new mail_domain accesses
for _ in range(20):
factories.MailDomainAccessFactory(domain=mail_domain)
client = APIClient()
client.force_login(user)
response = client.get(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/?ordering=role",
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["count"] == 21
results = [access["role"] for access in response.json()["results"]]
assert sorted(results) == results
# check results when we change ordering
response = client.get(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/?ordering=-role",
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["count"] == 21
results = [access["role"] for access in response.json()["results"]]
assert sorted(results, reverse=True) == results
@pytest.mark.parametrize("ordering_field", ["email", "name"])
def test_api_mail_domain__accesses_list_authenticated_ordering_user(ordering_field):
"""Mail domain accesses can be ordered by user's fields."""
user = core_factories.UserFactory()
mail_domain = factories.MailDomainFactory()
models.MailDomainAccess.objects.create(domain=mail_domain, user=user)
for _ in range(20):
factories.MailDomainAccessFactory(domain=mail_domain)
client = APIClient()
client.force_login(user)
response = client.get(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/?ordering=user__{ordering_field}",
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["count"] == 21
def normalize(x):
"""Mimic Django order_by, which is case-insensitive and space-insensitive"""
return x.casefold().replace(" ", "")
results = [access["user"][ordering_field] for access in response.json()["results"]]
assert sorted(results, key=normalize) == results
@@ -0,0 +1,118 @@
"""
Test for mail_domain accesses API endpoints in People's core app : retrieve
"""
import pytest
from rest_framework import status
from rest_framework.test import APIClient
from core import factories as core_factories
from mailbox_manager import enums, factories
pytestmark = pytest.mark.django_db
def test_api_mail_domain__accesses_retrieve_anonymous():
"""
Anonymous users should not be allowed to retrieve a mail_domain access.
"""
access = factories.MailDomainAccessFactory()
response = APIClient().get(
f"/api/v1.0/mail-domains/{access.domain.slug}/accesses/{access.id!s}/",
)
assert response.status_code == status.HTTP_401_UNAUTHORIZED
assert response.json() == {
"detail": "Authentication credentials were not provided."
}
def test_api_mail_domain__accesses_retrieve_authenticated_unrelated():
"""
Authenticated users should not be allowed to retrieve a mail_domain access for
a mail_domain to which they are not related.
"""
user = core_factories.UserFactory()
access = factories.MailDomainAccessFactory(domain=factories.MailDomainFactory())
client = APIClient()
client.force_login(user)
response = client.get(
f"/api/v1.0/mail-domains/{access.domain.slug}/accesses/{access.id!s}/",
)
assert response.status_code == status.HTTP_404_NOT_FOUND
assert response.json() == {"detail": "No MailDomainAccess matches the given query."}
# Accesses related to another mail_domain should be excluded even if the user is related to it
for other_access in [
factories.MailDomainAccessFactory(),
factories.MailDomainAccessFactory(user=user),
]:
response = client.get(
f"/api/v1.0/mail-domains/{access.domain.slug}/accesses/{other_access.id!s}/",
)
assert response.status_code == status.HTTP_404_NOT_FOUND
assert response.json() == {
"detail": "No MailDomainAccess matches the given query."
}
def test_api_mail_domain__accesses_retrieve_authenticated_related():
"""
A user who is related to a mail_domain should be allowed to retrieve the
associated mail_domain user accesses.
"""
owner = core_factories.UserFactory()
mail_domain = factories.MailDomainFactory()
access = factories.MailDomainAccessFactory(
domain=mail_domain, user=owner, role=enums.MailDomainRoleChoices.OWNER
)
client = APIClient()
client.force_login(owner)
response = client.get(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/{access.id!s}/",
)
results = {
"id": str(access.id),
"user": {
"id": str(access.user.id),
"email": str(owner.email),
"name": str(owner.name),
},
"role": str(access.role),
"can_set_role_to": [
enums.MailDomainRoleChoices.ADMIN,
enums.MailDomainRoleChoices.VIEWER,
],
}
assert response.status_code == status.HTTP_200_OK
assert response.json() == results
admin = factories.MailDomainAccessFactory(
domain=mail_domain, role=enums.MailDomainRoleChoices.ADMIN
).user
client.force_login(admin)
response = client.get(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/{access.id!s}/",
)
# admin can't change role of an owner
results["can_set_role_to"] = []
assert response.status_code == status.HTTP_200_OK
assert response.json() == results
viewer = factories.MailDomainAccessFactory(
domain=mail_domain, role=enums.MailDomainRoleChoices.VIEWER
).user
client.force_login(viewer)
response = client.get(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/{access.id!s}/",
)
# viewer can't change anyone's role
results["can_set_role_to"] = []
assert response.status_code == status.HTTP_200_OK
assert response.json() == results
@@ -0,0 +1,295 @@
"""
Test for mail_domain accesses API endpoints in People's core app : update
"""
import pytest
from rest_framework import status
from rest_framework.test import APIClient
from core import factories as core_factories
from mailbox_manager import enums, factories
pytestmark = pytest.mark.django_db
def test_api_mail_domain__accesses_update_anonymous():
"""An anonymous users should not be allowed to update a mail domain access."""
access = factories.MailDomainAccessFactory(role=enums.MailDomainRoleChoices.VIEWER)
response = APIClient().put(
f"/api/v1.0/mail-domains/{access.domain.slug}/accesses/{access.id!s}/",
data={"role": enums.MailDomainRoleChoices.ADMIN},
format="json",
)
assert response.status_code == status.HTTP_401_UNAUTHORIZED
access.refresh_from_db()
assert access.role == enums.MailDomainRoleChoices.VIEWER
def test_api_mail_domain__accesses_update_authenticated_unrelated():
"""
An authenticated user should not be allowed to update a mail domain access
for a mail_domain to which they are not related.
"""
authenticated_user = core_factories.UserFactory()
access = factories.MailDomainAccessFactory(role=enums.MailDomainRoleChoices.VIEWER)
client = APIClient()
client.force_login(authenticated_user)
response = client.put(
f"/api/v1.0/mail-domains/{access.domain.slug}/accesses/{access.id!s}/",
{"role": enums.MailDomainRoleChoices.ADMIN},
format="json",
)
assert response.status_code == status.HTTP_403_FORBIDDEN
access.refresh_from_db()
assert access.role == enums.MailDomainRoleChoices.VIEWER
def test_api_mail_domain__accesses_update_authenticated_viewer():
"""A viewer of a mail domain should not be allowed to update accesses."""
authenticated_user = core_factories.UserFactory()
mail_domain = factories.MailDomainFactory(
users=[(authenticated_user, enums.MailDomainRoleChoices.VIEWER)]
)
access = factories.MailDomainAccessFactory(
domain=mail_domain,
role=enums.MailDomainRoleChoices.VIEWER,
)
client = APIClient()
client.force_login(authenticated_user)
response = client.put(
f"/api/v1.0/mail-domains/{access.domain.slug}/accesses/{access.id!s}/",
{"role": enums.MailDomainRoleChoices.ADMIN},
format="json",
)
assert response.status_code == status.HTTP_403_FORBIDDEN
access.refresh_from_db()
assert access.role == enums.MailDomainRoleChoices.VIEWER
def test_api_mail_domain__accesses_update_authenticated_viewer_themself():
"""A viewer of a mail domain should not be allowed to update its accesses."""
authenticated_user = core_factories.UserFactory()
access = factories.MailDomainAccessFactory(
user=authenticated_user,
role=enums.MailDomainRoleChoices.VIEWER,
)
client = APIClient()
client.force_login(authenticated_user)
response = client.put(
f"/api/v1.0/mail-domains/{access.domain.slug}/accesses/{access.id!s}/",
{"role": enums.MailDomainRoleChoices.ADMIN},
format="json",
)
assert response.status_code == status.HTTP_403_FORBIDDEN
access.refresh_from_db()
assert access.role == enums.MailDomainRoleChoices.VIEWER
def test_api_mail_domain__accesses_update_administrator_except_owner():
"""
An administrator of a mail domain should be allowed to update a user
access for this mail domain, as long as they don't try to set the role to owner.
"""
authenticated_user = core_factories.UserFactory()
mail_domain = factories.MailDomainFactory(
users=[(authenticated_user, enums.MailDomainRoleChoices.ADMIN)]
)
admin_access = factories.MailDomainAccessFactory(
domain=mail_domain, role=enums.MailDomainRoleChoices.ADMIN
)
viewer_access = factories.MailDomainAccessFactory(
domain=mail_domain, role=enums.MailDomainRoleChoices.VIEWER
)
client = APIClient()
client.force_login(authenticated_user)
response = client.put(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/{admin_access.id!s}/",
data={"role": enums.MailDomainRoleChoices.OWNER},
format="json",
)
assert response.status_code == status.HTTP_403_FORBIDDEN
admin_access.refresh_from_db()
assert admin_access.role == enums.MailDomainRoleChoices.ADMIN
response = client.put(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/{admin_access.id!s}/",
data={"role": enums.MailDomainRoleChoices.VIEWER},
format="json",
)
assert response.status_code == status.HTTP_200_OK
admin_access.refresh_from_db()
assert admin_access.role == enums.MailDomainRoleChoices.VIEWER
response = client.put(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/{viewer_access.id!s}/",
data={"role": enums.MailDomainRoleChoices.OWNER},
format="json",
)
assert response.status_code == status.HTTP_403_FORBIDDEN
viewer_access.refresh_from_db()
assert viewer_access.role == enums.MailDomainRoleChoices.VIEWER
response = client.put(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/{viewer_access.id!s}/",
data={"role": enums.MailDomainRoleChoices.ADMIN},
format="json",
)
assert response.status_code == status.HTTP_200_OK
viewer_access.refresh_from_db()
assert viewer_access.role == enums.MailDomainRoleChoices.ADMIN
def test_api_mail_domain__accesses_update_administrator_from_owner():
"""
An administrator for a mail domain, should not be allowed to update
the user access of an "owner" for this mail domain.
"""
authenticated_user = core_factories.UserFactory()
mail_domain = factories.MailDomainFactory(
users=[(authenticated_user, enums.MailDomainRoleChoices.ADMIN)]
)
owner = core_factories.UserFactory()
owner_access = factories.MailDomainAccessFactory(
domain=mail_domain, user=owner, role=enums.MailDomainRoleChoices.OWNER
)
client = APIClient()
client.force_login(authenticated_user)
response = client.put(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/{owner_access.id!s}/",
data={"role": enums.MailDomainRoleChoices.ADMIN},
format="json",
)
assert response.status_code == status.HTTP_403_FORBIDDEN
owner_access.refresh_from_db()
assert owner_access.role == enums.MailDomainRoleChoices.OWNER
def test_api_mail_domain__accesses_update_owner():
"""
An owner of a mail domain should be allowed to update
a user access for this domain.
"""
owner_authenticated = core_factories.UserFactory()
mail_domain = factories.MailDomainFactory(
users=[(owner_authenticated, enums.MailDomainRoleChoices.OWNER)]
)
user_access1 = factories.MailDomainAccessFactory(
domain=mail_domain, role=enums.MailDomainRoleChoices.ADMIN
)
user_access2 = factories.MailDomainAccessFactory(
domain=mail_domain, role=enums.MailDomainRoleChoices.VIEWER
)
client = APIClient()
client.force_login(owner_authenticated)
# turn admin in viewer
response = client.put(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/{user_access1.id!s}/",
data={"role": enums.MailDomainRoleChoices.VIEWER},
format="json",
)
assert response.status_code == status.HTTP_200_OK
user_access1.refresh_from_db()
assert user_access1.role == enums.MailDomainRoleChoices.VIEWER
# turn viewer in owner
response = client.put(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/{user_access1.id!s}/",
data={"role": enums.MailDomainRoleChoices.OWNER},
format="json",
)
assert response.status_code == status.HTTP_200_OK
user_access1.refresh_from_db()
assert user_access1.role == enums.MailDomainRoleChoices.OWNER
# turn viewer in admin
response = client.put(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/{user_access2.id!s}/",
data={"role": enums.MailDomainRoleChoices.ADMIN},
format="json",
)
assert response.status_code == status.HTTP_200_OK
user_access2.refresh_from_db()
assert user_access2.role == enums.MailDomainRoleChoices.ADMIN
def test_api_mail_domain__accesses_update_owner_for_owners():
"""
An owner of a mail domain should be allowed to update
an existing owner access for this mail domain.
"""
owner_authenticated = core_factories.UserFactory()
mail_domain = factories.MailDomainFactory(
users=[(owner_authenticated, enums.MailDomainRoleChoices.OWNER)]
)
other_owner_access = factories.MailDomainAccessFactory(
domain=mail_domain, role=enums.MailDomainRoleChoices.OWNER
)
client = APIClient()
client.force_login(owner_authenticated)
for new_role in [
enums.MailDomainRoleChoices.ADMIN,
enums.MailDomainRoleChoices.VIEWER,
]:
response = client.patch(
f"/api/v1.0/mail-domains/{mail_domain.slug}/accesses/{other_owner_access.id!s}/",
data={"role": new_role},
format="json",
)
assert response.status_code == status.HTTP_200_OK
other_owner_access.refresh_from_db()
assert other_owner_access.role == new_role
def test_api_mail_domain__accesses_update_owner_self():
"""
An owner of a mail domain should be allowed to update
their own user access provided there are other owners in the mail domain.
"""
owner_authenticated = core_factories.UserFactory()
access = factories.MailDomainAccessFactory(
user=owner_authenticated, role=enums.MailDomainRoleChoices.OWNER
)
client = APIClient()
client.force_login(owner_authenticated)
for new_role in [
enums.MailDomainRoleChoices.ADMIN,
enums.MailDomainRoleChoices.VIEWER,
]:
response = client.patch(
f"/api/v1.0/mail-domains/{access.domain.slug}/accesses/{access.id!s}/",
data={"role": new_role},
format="json",
)
assert response.status_code == status.HTTP_403_FORBIDDEN
assert (
response.json()["role"]
== "Cannot change the role to a non-owner role for the last owner access."
)
access.refresh_from_db()
assert access.role == enums.MailDomainRoleChoices.OWNER
# Add another owner and it should now work
factories.MailDomainAccessFactory(
domain=access.domain, role=enums.MailDomainRoleChoices.OWNER
)
for new_role in [
enums.MailDomainRoleChoices.ADMIN,
enums.MailDomainRoleChoices.VIEWER,
]:
response = client.patch(
f"/api/v1.0/mail-domains/{access.domain.slug}/accesses/{access.id!s}/",
data={"role": new_role},
format="json",
)
assert response.status_code == status.HTTP_200_OK
access.refresh_from_db()
assert access.role == new_role
@@ -0,0 +1,667 @@
"""
Unit tests for the mailbox API
"""
import json
import re
from logging import Logger
from unittest import mock
from django.test.utils import override_settings
from django.utils.translation import gettext_lazy as _
import pytest
import responses
from rest_framework import status
from rest_framework.test import APIClient
from core import factories as core_factories
from mailbox_manager import enums, factories, models
from mailbox_manager.api import serializers
pytestmark = pytest.mark.django_db
def test_api_mailboxes__create_anonymous_forbidden():
"""Anonymous users should not be able to create a new mailbox via the API."""
mail_domain = factories.MailDomainEnabledFactory()
mailbox_values = serializers.MailboxSerializer(
factories.MailboxFactory.build()
).data
response = APIClient().post(
f"/api/v1.0/mail-domains/{mail_domain.slug}/mailboxes/",
mailbox_values,
)
assert response.status_code == status.HTTP_401_UNAUTHORIZED
assert not models.Mailbox.objects.exists()
def test_api_mailboxes__create_authenticated_failure():
"""Authenticated users should not be able to create mailbox
without specific role on mail domain."""
user = core_factories.UserFactory()
client = APIClient()
client.force_login(user)
mailbox_values = serializers.MailboxSerializer(
factories.MailboxFactory.build()
).data
mail_domain = factories.MailDomainEnabledFactory()
response = client.post(
f"/api/v1.0/mail-domains/{mail_domain.slug}/mailboxes/",
mailbox_values,
format="json",
)
assert response.status_code == status.HTTP_403_FORBIDDEN
assert not models.Mailbox.objects.exists()
def test_api_mailboxes__create_viewer_failure():
"""Users with viewer role should not be able to create mailbox on the mail domain."""
mail_domain = factories.MailDomainEnabledFactory()
access = factories.MailDomainAccessFactory(
role=enums.MailDomainRoleChoices.VIEWER, domain=mail_domain
)
client = APIClient()
client.force_login(access.user)
mailbox_values = serializers.MailboxSerializer(
factories.MailboxFactory.build()
).data
response = client.post(
f"/api/v1.0/mail-domains/{mail_domain.slug}/mailboxes/",
mailbox_values,
format="json",
)
assert response.status_code == status.HTTP_403_FORBIDDEN
assert not models.Mailbox.objects.exists()
@pytest.mark.parametrize(
"role",
[enums.MailDomainRoleChoices.OWNER, enums.MailDomainRoleChoices.ADMIN],
)
def test_api_mailboxes__create_roles_success(role):
"""Users with owner or admin role should be able to create mailbox on the mail domain."""
mail_domain = factories.MailDomainEnabledFactory()
access = factories.MailDomainAccessFactory(role=role, domain=mail_domain)
client = APIClient()
client.force_login(access.user)
mailbox_values = serializers.MailboxSerializer(
factories.MailboxFactory.build()
).data
with responses.RequestsMock() as rsps:
# Ensure successful response using "responses":
rsps.add(
rsps.GET,
re.compile(r".*/token/"),
body='{"access_token": "domain_owner_token"}',
status=status.HTTP_200_OK,
content_type="application/json",
)
rsps.add(
rsps.POST,
re.compile(rf".*/domains/{mail_domain.name}/mailboxes/"),
body=str(
{
"email": f"{mailbox_values['local_part']}@{mail_domain.name}",
"password": "newpass",
"uuid": "uuid",
}
),
status=status.HTTP_201_CREATED,
content_type="application/json",
)
response = client.post(
f"/api/v1.0/mail-domains/{mail_domain.slug}/mailboxes/",
mailbox_values,
format="json",
)
assert response.status_code == status.HTTP_201_CREATED
mailbox = models.Mailbox.objects.get()
assert mailbox.local_part == mailbox_values["local_part"]
assert mailbox.secondary_email == mailbox_values["secondary_email"]
assert response.json() == {
"id": str(mailbox.id),
"first_name": str(mailbox.first_name),
"last_name": str(mailbox.last_name),
"local_part": str(mailbox.local_part),
"secondary_email": str(mailbox.secondary_email),
}
@pytest.mark.parametrize(
"role",
[enums.MailDomainRoleChoices.OWNER, enums.MailDomainRoleChoices.ADMIN],
)
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
first_name accentuated."""
mail_domain = factories.MailDomainEnabledFactory()
access = factories.MailDomainAccessFactory(role=role, domain=mail_domain)
client = APIClient()
client.force_login(access.user)
mailbox_values = serializers.MailboxSerializer(
factories.MailboxFactory.build(first_name="Aimé")
).data
with responses.RequestsMock() as rsps:
# Ensure successful response using "responses":
rsps.add(
rsps.GET,
re.compile(r".*/token/"),
body='{"access_token": "domain_owner_token"}',
status=status.HTTP_200_OK,
content_type="application/json",
)
rsps.add(
rsps.POST,
re.compile(rf".*/domains/{mail_domain.name}/mailboxes/"),
body=str(
{
"email": f"{mailbox_values['local_part']}@{mail_domain.name}",
"password": "newpass",
"uuid": "uuid",
}
),
status=status.HTTP_201_CREATED,
content_type="application/json",
)
response = client.post(
f"/api/v1.0/mail-domains/{mail_domain.slug}/mailboxes/",
mailbox_values,
format="json",
)
assert response.status_code == status.HTTP_201_CREATED
mailbox = models.Mailbox.objects.get()
assert mailbox.local_part == mailbox_values["local_part"]
assert mailbox.secondary_email == mailbox_values["secondary_email"]
assert response.json() == {
"id": str(mailbox.id),
"first_name": str(mailbox.first_name),
"last_name": str(mailbox.last_name),
"local_part": str(mailbox.local_part),
"secondary_email": str(mailbox.secondary_email),
}
def test_api_mailboxes__create_administrator_missing_fields():
"""
Administrator users should not be able to create mailboxes
without local part or secondary mail.
"""
mail_domain = factories.MailDomainEnabledFactory()
access = factories.MailDomainAccessFactory(
role=enums.MailDomainRoleChoices.ADMIN, domain=mail_domain
)
client = APIClient()
client.force_login(access.user)
mailbox_values = serializers.MailboxSerializer(
factories.MailboxFactory.build()
).data
del mailbox_values["local_part"]
response = client.post(
f"/api/v1.0/mail-domains/{mail_domain.slug}/mailboxes/",
mailbox_values,
format="json",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert not models.Mailbox.objects.exists()
assert response.json() == {"local_part": ["This field is required."]}
mailbox_values = serializers.MailboxSerializer(
factories.MailboxFactory.build()
).data
del mailbox_values["secondary_email"]
response = client.post(
f"/api/v1.0/mail-domains/{mail_domain.slug}/mailboxes/",
mailbox_values,
format="json",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert not models.Mailbox.objects.exists()
assert response.json() == {"secondary_email": ["This field is required."]}
### REACTING TO DIMAIL-API
### We mock dimail's responses to avoid testing dimail's container too
def test_api_mailboxes__unrelated_user_provisioning_api_not_called():
"""
Provisioning API should not be called if an user tries
to create a mailbox on a domain they have no access to.
"""
domain = factories.MailDomainEnabledFactory()
client = APIClient()
client.force_login(core_factories.UserFactory()) # user with no access
body_values = serializers.MailboxSerializer(
factories.MailboxFactory.build(domain=domain)
).data
with responses.RequestsMock():
# We add no simulated response in RequestsMock
# because we expected no "outside" calls to be made
response = client.post(
f"/api/v1.0/mail-domains/{domain.slug}/mailboxes/",
body_values,
format="json",
)
# No exception raised by RequestsMock means no call was sent
# our API blocked the request before sending it
assert response.status_code == status.HTTP_403_FORBIDDEN
def test_api_mailboxes__domain_viewer_provisioning_api_not_called():
"""
Provisioning API should not be called if a domain viewer tries
to create a mailbox on a domain they are not owner/admin of.
"""
access = factories.MailDomainAccessFactory(
domain=factories.MailDomainEnabledFactory(),
user=core_factories.UserFactory(),
role=enums.MailDomainRoleChoices.VIEWER,
)
client = APIClient()
client.force_login(access.user)
body_values = serializers.MailboxSerializer(factories.MailboxFactory.build()).data
with responses.RequestsMock():
# We add no simulated response in RequestsMock
# because we expected no "outside" calls to be made
response = client.post(
f"/api/v1.0/mail-domains/{access.domain.slug}/mailboxes/",
body_values,
format="json",
)
# No exception raised by RequestsMock means no call was sent
# our API blocked the request before sending it
assert response.status_code == status.HTTP_403_FORBIDDEN
@mock.patch.object(Logger, "error")
def test_api_mailboxes__async_dimail_unauthorized(mock_error):
"""
Dimail should raise an error if token has been successfully granted
but mailbox creation request returns a 403.
i.e. user exists on dimail-api but has no permission on that domain
"""
# creating all needed objects
# this access somehow exists solely in our database but not in dimail
access = factories.MailDomainAccessFactory(role=enums.MailDomainRoleChoices.OWNER)
client = APIClient()
client.force_login(access.user)
mailbox_data = serializers.MailboxSerializer(
factories.MailboxFactory.build(domain=access.domain)
).data
with responses.RequestsMock() as rsps:
# Ensure successful response using "responses":
rsps.add(
rsps.GET,
re.compile(r".*/token/"),
body='{"access_token": "domain_owner_token"}',
status=status.HTTP_200_OK, # user is in dimail-api
content_type="application/json",
)
rsps.add(
rsps.POST,
re.compile(
rf".*/domains/{access.domain.name}/mailboxes/{mailbox_data['local_part']}"
),
status=status.HTTP_403_FORBIDDEN,
content_type="application/json",
)
response = client.post(
f"/api/v1.0/mail-domains/{access.domain.slug}/mailboxes/",
mailbox_data,
format="json",
)
assert response.status_code == status.HTTP_403_FORBIDDEN
assert mock_error.call_count == 1
assert mock_error.call_args_list[0][0] == (
"[DIMAIL] 403 Forbidden: you cannot access domain %s",
access.domain.name,
)
@pytest.mark.parametrize(
"role",
[enums.MailDomainRoleChoices.ADMIN, enums.MailDomainRoleChoices.OWNER],
)
def test_api_mailboxes__domain_owner_or_admin_successful_creation_and_provisioning(
role,
):
"""
Domain owner/admin should be able to create mailboxes.
Provisioning API should be called when owner/admin makes a call.
Succesfull 201 response from dimail should trigger mailbox creation on our side.
"""
# creating all needed objects
access = factories.MailDomainAccessFactory(role=role)
client = APIClient()
client.force_login(access.user)
mailbox_data = serializers.MailboxSerializer(
factories.MailboxFactory.build(domain=access.domain)
).data
with responses.RequestsMock() as rsps:
# Ensure successful response using "responses":
rsps.add(
rsps.GET,
re.compile(r".*/token/"),
body='{"access_token": "domain_owner_token"}',
status=status.HTTP_200_OK,
content_type="application/json",
)
rsp = rsps.add(
rsps.POST,
re.compile(rf".*/domains/{access.domain.name}/mailboxes/"),
body=str(
{
"email": f"{mailbox_data['local_part']}@{access.domain.name}",
"password": "newpass",
"uuid": "uuid",
}
),
status=status.HTTP_201_CREATED,
content_type="application/json",
)
response = client.post(
f"/api/v1.0/mail-domains/{access.domain.slug}/mailboxes/",
mailbox_data,
format="json",
)
# Checks payload sent to email-provisioning API
payload = json.loads(rsps.calls[1].request.body)
assert payload == {
"displayName": f"{mailbox_data['first_name']} {mailbox_data['last_name']}",
"givenName": mailbox_data["first_name"],
"surName": mailbox_data["last_name"],
}
# Checks response
assert response.status_code == status.HTTP_201_CREATED
assert rsp.call_count == 1
mailbox = models.Mailbox.objects.get()
assert response.json() == {
"id": str(mailbox.id),
"first_name": str(mailbox_data["first_name"]),
"last_name": str(mailbox_data["last_name"]),
"local_part": str(mailbox_data["local_part"]),
"secondary_email": str(mailbox_data["secondary_email"]),
}
assert mailbox.first_name == mailbox_data["first_name"]
assert mailbox.last_name == mailbox_data["last_name"]
assert mailbox.local_part == mailbox_data["local_part"]
assert mailbox.secondary_email == mailbox_data["secondary_email"]
@override_settings(MAIL_PROVISIONING_API_CREDENTIALS="wrongCredentials")
def test_api_mailboxes__dimail_token_permission_denied():
"""
API should raise a clear "permission denied" error
when receiving a permission denied from dimail upon requesting token.
"""
# creating all needed objects
access = factories.MailDomainAccessFactory(role=enums.MailDomainRoleChoices.OWNER)
client = APIClient()
client.force_login(access.user)
mailbox_data = serializers.MailboxSerializer(
factories.MailboxFactory.build(domain=access.domain)
).data
with responses.RequestsMock() as rsps:
# Ensure successful response using "responses":
rsps.add(
rsps.GET,
re.compile(r".*/token/"),
body='{"details": "Permission denied"}',
status=status.HTTP_403_FORBIDDEN,
content_type="application/json",
)
response = client.post(
f"/api/v1.0/mail-domains/{access.domain.slug}/mailboxes/",
mailbox_data,
format="json",
)
assert response.status_code == status.HTTP_403_FORBIDDEN
assert response.json() == {
"detail": "Token denied. Please check your MAIL_PROVISIONING_API_CREDENTIALS."
}
assert not models.Mailbox.objects.exists()
def test_api_mailboxes__user_unrelated_to_domain():
"""
API should raise a clear "permission denied" when dimail returns a permission denied
on mailbox creation. This means token was granted for this user
but user is not allowed to modify this domain (i.e. not owner)
"""
# creating all needed objects
access = factories.MailDomainAccessFactory(role=enums.MailDomainRoleChoices.OWNER)
client = APIClient()
client.force_login(access.user)
mailbox_data = serializers.MailboxSerializer(
factories.MailboxFactory.build(domain=access.domain)
).data
with responses.RequestsMock() as rsps:
# Ensure successful response using "responses":
rsps.add(
rsps.GET,
re.compile(r".*/token/"),
body='{"access_token": "domain_owner_token"}',
status=status.HTTP_200_OK,
content_type="application/json",
)
rsps.add(
rsps.POST,
re.compile(rf".*/domains/{access.domain.name}/mailboxes/"),
body='{"details": "Permission denied"}',
status=status.HTTP_403_FORBIDDEN,
content_type="application/json",
)
response = client.post(
f"/api/v1.0/mail-domains/{access.domain.slug}/mailboxes/",
mailbox_data,
format="json",
)
assert response.status_code == status.HTTP_403_FORBIDDEN
assert response.json() == {
"detail": "Permission denied. Please check your MAIL_PROVISIONING_API_CREDENTIALS."
}
assert not models.Mailbox.objects.exists()
@mock.patch.object(Logger, "error")
def test_api_mailboxes__handling_dimail_unexpected_error(mock_error):
"""
API should raise a clear error when dimail returns an unexpected response.
"""
# creating all needed objects
access = factories.MailDomainAccessFactory(role=enums.MailDomainRoleChoices.OWNER)
client = APIClient()
client.force_login(access.user)
mailbox_data = serializers.MailboxSerializer(
factories.MailboxFactory.build(domain=access.domain)
).data
with responses.RequestsMock() as rsps:
# Ensure successful response using "responses":
rsps.add(
rsps.GET,
re.compile(r".*/token/"),
body='{"access_token": "domain_owner_token"}',
status=status.HTTP_200_OK,
content_type="application/json",
)
rsps.add(
rsps.POST,
re.compile(rf".*/domains/{access.domain.name}/mailboxes/"),
body='{"details": "Internal server error"}',
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
content_type="application/json",
)
with pytest.raises(SystemError):
response = client.post(
f"/api/v1.0/mail-domains/{access.domain.slug}/mailboxes/",
mailbox_data,
format="json",
)
assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
assert response.json() == {
"detail": "Unexpected response from dimail: {'details': 'Internal server error'}"
}
assert not models.Mailbox.objects.exists()
# Check error logger was called
assert mock_error.called
assert mock_error.call_args_list[1][0] == (
'Unexpected response from dimail: 500 {"details": "Internal server error"}',
)
@mock.patch.object(Logger, "error")
@mock.patch.object(Logger, "info")
def test_api_mailboxes__send_correct_logger_infos(mock_info, mock_error):
"""
Upon requesting mailbox creation, la régie should impersonate
querying user in dimail and log things correctly.
"""
access = factories.MailDomainAccessFactory(role=enums.MailDomainRoleChoices.OWNER)
client = APIClient()
client.force_login(access.user)
mailbox_data = serializers.MailboxSerializer(
factories.MailboxFactory.build(domain=access.domain)
).data
with responses.RequestsMock() as rsps:
# Ensure successful response using "responses":
rsps.add(
rsps.GET,
re.compile(r".*/token/"),
body='{"access_token": "domain_owner_token"}',
status=status.HTTP_200_OK,
content_type="application/json",
)
rsps.add(
rsps.POST,
re.compile(rf".*/domains/{access.domain.name}/mailboxes/"),
body=str(
{
"email": f"{mailbox_data['local_part']}@{access.domain.name}",
"password": "newpass",
"uuid": "uuid",
}
),
status=status.HTTP_201_CREATED,
content_type="application/json",
)
response = client.post(
f"/api/v1.0/mail-domains/{access.domain.slug}/mailboxes/",
mailbox_data,
format="json",
)
assert response.status_code == status.HTTP_201_CREATED
# user sub is sent to payload as a parameter
assert rsps.calls[0].request.params == {"username": access.user.sub}
# Logger
assert not mock_error.called
assert mock_info.call_count == 4
# a new empty error has been added. To be investigated
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 by user %s",
str(access.domain),
access.user.sub,
)
@mock.patch.object(Logger, "info")
def test_api_mailboxes__sends_new_mailbox_notification(mock_info):
"""
Creating a new mailbox should send confirmation email
to secondary email.
"""
access = factories.MailDomainAccessFactory(role=enums.MailDomainRoleChoices.OWNER)
client = APIClient()
client.force_login(access.user)
mailbox_data = serializers.MailboxSerializer(
factories.MailboxFactory.build(domain=access.domain)
).data
with responses.RequestsMock() as rsps:
# Ensure successful response using "responses":
rsps.add(
rsps.GET,
re.compile(r".*/token/"),
body='{"access_token": "domain_owner_token"}',
status=status.HTTP_200_OK,
content_type="application/json",
)
rsps.add(
rsps.POST,
re.compile(rf".*/domains/{access.domain.name}/mailboxes/"),
body=str(
{
"email": f"{mailbox_data['local_part']}@{access.domain.name}",
"password": "newpass",
"uuid": "uuid",
}
),
status=status.HTTP_201_CREATED,
content_type="application/json",
)
with mock.patch("django.core.mail.send_mail") as mock_send:
client.post(
f"/api/v1.0/mail-domains/{access.domain.slug}/mailboxes/",
mailbox_data,
format="json",
)
assert mock_send.call_count == 1
assert mock_send.mock_calls[0][1][0] == "Your new mailbox information"
assert mock_send.mock_calls[0][1][3][0] == mailbox_data["secondary_email"]
assert mock_info.call_count == 4
assert mock_info.call_args_list[2][0] == (
"Information for mailbox %s sent to %s.",
f"{mailbox_data['local_part']}@{access.domain.name}",
mailbox_data["secondary_email"],
)
@@ -0,0 +1,94 @@
"""
Unit tests for the mailbox API
"""
import pytest
from rest_framework import status
from rest_framework.test import APIClient
from core import factories as core_factories
from mailbox_manager import enums, factories
pytestmark = pytest.mark.django_db
def test_api_mailboxes__list_anonymous():
"""Anonymous users should not be allowed to list mailboxes."""
mail_domain = factories.MailDomainEnabledFactory()
factories.MailboxFactory.create_batch(2, domain=mail_domain)
response = APIClient().get(f"/api/v1.0/mail-domains/{mail_domain.slug}/mailboxes/")
assert response.status_code == status.HTTP_401_UNAUTHORIZED
assert response.json() == {
"detail": "Authentication credentials were not provided."
}
def test_api_mailboxes__list_authenticated():
"""Authenticated users should not be able to list mailboxes"""
user = core_factories.UserFactory()
client = APIClient()
client.force_login(user)
mail_domain = factories.MailDomainEnabledFactory()
factories.MailboxFactory.create_batch(2, domain=mail_domain)
response = client.get(f"/api/v1.0/mail-domains/{mail_domain.slug}/mailboxes/")
assert response.status_code == status.HTTP_403_FORBIDDEN
assert response.json() == {
"detail": "You do not have permission to perform this action."
}
@pytest.mark.parametrize(
"role",
[
enums.MailDomainRoleChoices.OWNER,
enums.MailDomainRoleChoices.ADMIN,
enums.MailDomainRoleChoices.VIEWER,
],
)
def test_api_mailboxes__list_roles(role):
"""Owner, admin and viewer users should be able to list mailboxes"""
mail_domain = factories.MailDomainEnabledFactory()
mailbox1 = factories.MailboxFactory(domain=mail_domain)
mailbox2 = factories.MailboxFactory(domain=mail_domain)
access = factories.MailDomainAccessFactory(role=role, domain=mail_domain)
client = APIClient()
client.force_login(access.user)
response = client.get(f"/api/v1.0/mail-domains/{mail_domain.slug}/mailboxes/")
assert response.status_code == status.HTTP_200_OK
assert response.json()["results"] == [
{
"id": str(mailbox2.id),
"first_name": str(mailbox2.first_name),
"last_name": str(mailbox2.last_name),
"local_part": str(mailbox2.local_part),
"secondary_email": str(mailbox2.secondary_email),
},
{
"id": str(mailbox1.id),
"first_name": str(mailbox1.first_name),
"last_name": str(mailbox1.last_name),
"local_part": str(mailbox1.local_part),
"secondary_email": str(mailbox1.secondary_email),
},
]
def test_api_mailboxes__list_non_existing():
"""
User gets a 404 when trying to list mailboxes of a domain which does not exist.
"""
user = core_factories.UserFactory()
client = APIClient()
client.force_login(user)
factories.MailboxFactory.create_batch(5)
response = client.get("/api/v1.0/mail-domains/nonexistent.domain/mailboxes/")
assert response.status_code == status.HTTP_404_NOT_FOUND
@@ -1,103 +0,0 @@
"""
Unit tests for the mailbox API
"""
import pytest
from rest_framework import status
from rest_framework.test import APIClient
from core import factories as core_factories
from mailbox_manager import factories, models
pytestmark = pytest.mark.django_db
def test_api_mailboxes__create_anonymous_forbidden():
"""Anonymous users should not be able to create a new mailbox via the API."""
mail_domain = factories.MailDomainFactory()
response = APIClient().post(
f"/api/v1.0/mail-domains/{mail_domain.slug}/mailboxes/",
{
"first_name": "jean",
"last_name": "doe",
"local_part": "jean.doe",
"secondary_email": "jean.doe@gmail.com",
"phone_number": "+33150142700",
},
)
assert response.status_code == status.HTTP_401_UNAUTHORIZED
assert not models.Mailbox.objects.exists()
def test_api_mailboxes__create_authenticated_missing_fields():
"""
Authenticated users should not be able to create mailboxes
without local part or secondary mail.
"""
user = core_factories.UserFactory(admin_email="tester@ministry.fr")
core_factories.IdentityFactory(user=user, email=user.admin_email, name="john doe")
client = APIClient()
client.force_login(user)
mail_domain = factories.MailDomainFactory()
response = client.post(
f"/api/v1.0/mail-domains/{mail_domain.slug}/mailboxes/",
{
"first_name": "jean",
"last_name": "doe",
"secondary_email": "jean.doe@gmail.com",
"phone_number": "+33150142700",
},
format="json",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert models.Mailbox.objects.exists() is False
assert response.json() == {"local_part": ["This field is required."]}
response = client.post(
f"/api/v1.0/mail-domains/{mail_domain.slug}/mailboxes/",
{
"first_name": "jean",
"last_name": "doe",
"local_part": "jean.doe",
"phone_number": "+33150142700",
},
format="json",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert models.Mailbox.objects.exists() is False
assert response.json() == {"secondary_email": ["This field is required."]}
def test_api_mailboxes__create_authenticated_successful():
"""Authenticated users should be able to create mailbox."""
user = core_factories.UserFactory(admin_email="tester@ministry.fr")
core_factories.IdentityFactory(user=user, email=user.admin_email, name="john doe")
client = APIClient()
client.force_login(user)
mail_domain = factories.MailDomainFactory(name="saint-jean.collectivite.fr")
response = client.post(
f"/api/v1.0/mail-domains/{mail_domain.slug}/mailboxes/",
{
"first_name": "jean",
"last_name": "doe",
"local_part": "jean.doe",
"secondary_email": "jean.doe@gmail.com",
"phone_number": "+33150142700",
},
format="json",
)
assert response.status_code == status.HTTP_201_CREATED
mailbox = models.Mailbox.objects.get()
assert mailbox.local_part == "jean.doe"
assert mailbox.secondary_email == "jean.doe@gmail.com"
assert response.json() == {
"id": str(mailbox.id),
"local_part": str(mailbox.local_part),
"secondary_email": str(mailbox.secondary_email),
}
@@ -1,53 +0,0 @@
"""
Unit tests for the mailbox API
"""
import pytest
from rest_framework import status
from rest_framework.test import APIClient
from core import factories as core_factories
from mailbox_manager import factories
pytestmark = pytest.mark.django_db
def test_api_mailboxes__list_anonymous():
"""Anonymous users should not be allowed to list mailboxes."""
mail_domain = factories.MailDomainFactory()
factories.MailboxFactory.create_batch(2, domain=mail_domain)
response = APIClient().get(f"/api/v1.0/mail-domains/{mail_domain.slug}/mailboxes/")
assert response.status_code == status.HTTP_401_UNAUTHORIZED
assert response.json() == {
"detail": "Authentication credentials were not provided."
}
def test_api_mailboxes__list_authenticated_no_query():
"""Authenticated users should be able to list mailboxes without applying a query."""
user = core_factories.UserFactory(admin_email="tester@ministry.fr")
core_factories.IdentityFactory(user=user, email=user.admin_email, name="john doe")
client = APIClient()
client.force_login(user)
mail_domain = factories.MailDomainFactory()
mailbox1 = factories.MailboxFactory(domain=mail_domain)
mailbox2 = factories.MailboxFactory(domain=mail_domain)
response = client.get(f"/api/v1.0/mail-domains/{mail_domain.slug}/mailboxes/")
assert response.status_code == status.HTTP_200_OK
assert response.json()["results"] == [
{
"id": str(mailbox1.id),
"local_part": str(mailbox1.local_part),
"secondary_email": str(mailbox1.secondary_email),
},
{
"id": str(mailbox2.id),
"local_part": str(mailbox2.local_part),
"secondary_email": str(mailbox2.secondary_email),
},
]
@@ -2,27 +2,27 @@
Unit tests for the mailbox model
"""
from django.core.exceptions import ValidationError
from django.core import exceptions
from django.test.utils import override_settings
import pytest
from mailbox_manager import factories
from mailbox_manager import enums, factories, models
pytestmark = pytest.mark.django_db
# LOCAL PART FIELD
def test_models_mailboxes__local_part_cannot_be_empty():
"""The "local_part" field should not be empty."""
with pytest.raises(ValidationError, match="This field cannot be blank"):
with pytest.raises(exceptions.ValidationError, match="This field cannot be blank"):
factories.MailboxFactory(local_part="")
def test_models_mailboxes__local_part_cannot_be_null():
"""The "local_part" field should not be null."""
with pytest.raises(ValidationError, match="This field cannot be null"):
with pytest.raises(exceptions.ValidationError, match="This field cannot be null"):
factories.MailboxFactory(local_part=None)
@@ -31,13 +31,14 @@ def test_models_mailboxes__local_part_matches_expected_format():
The local part should contain alpha-numeric caracters
and a limited set of special caracters ("+", "-", ".", "_").
"""
factories.MailboxFactory(local_part="Marie-Jose.Perec+JO_2024")
# "-", ".", "_" are allowed
factories.MailboxFactory(local_part="Marie-Jose.Perec_2024")
with pytest.raises(ValidationError, match="Enter a valid value"):
factories.MailboxFactory(local_part="mariejo@unnecessarydomain.com")
with pytest.raises(ValidationError, match="Enter a valid value"):
factories.MailboxFactory(local_part="!")
# other special characters should raise a validation error
# "+" included, as this test is about mail creation
for character in ["+", "@", "!", "$", "%", " "]:
with pytest.raises(exceptions.ValidationError, match="Enter a valid value"):
factories.MailboxFactory(local_part=f"marie{character}jo")
def test_models_mailboxes__local_part_unique_per_domain():
@@ -50,7 +51,8 @@ def test_models_mailboxes__local_part_unique_per_domain():
# same local part on the same domain should not be possible
with pytest.raises(
ValidationError, match="Mailbox with this Local_part and Domain already exists."
exceptions.ValidationError,
match="Mailbox with this Local_part and Domain already exists.",
):
factories.MailboxFactory(
local_part=existing_mailbox.local_part, domain=existing_mailbox.domain
@@ -72,7 +74,7 @@ def test_models_mailboxes__domain_must_be_a_maildomain_instance():
def test_models_mailboxes__domain_cannot_be_null():
"""The "domain" field should not be null."""
with pytest.raises(ValidationError, match="This field cannot be null"):
with pytest.raises(models.MailDomain.DoesNotExist, match="Mailbox has no domain."):
factories.MailboxFactory(domain=None)
@@ -81,11 +83,70 @@ def test_models_mailboxes__domain_cannot_be_null():
def test_models_mailboxes__secondary_email_cannot_be_empty():
"""The "secondary_email" field should not be empty."""
with pytest.raises(ValidationError, match="This field cannot be blank"):
with pytest.raises(exceptions.ValidationError, match="This field cannot be blank"):
factories.MailboxFactory(secondary_email="")
def test_models_mailboxes__secondary_email_cannot_be_null():
"""The "secondary_email" field should not be null."""
with pytest.raises(ValidationError, match="This field cannot be null"):
with pytest.raises(exceptions.ValidationError, match="This field cannot be null"):
factories.MailboxFactory(secondary_email=None)
def test_models_mailboxes__cannot_be_created_for_disabled_maildomain():
"""Mailbox creation is allowed only for a domain enabled.
A disabled status for the mail domain raises an error."""
with pytest.raises(
exceptions.ValidationError,
match="You can create mailbox only for a domain enabled",
):
factories.MailboxFactory(
domain=factories.MailDomainFactory(
status=enums.MailDomainStatusChoices.DISABLED
)
)
def test_models_mailboxes__cannot_be_created_for_failed_maildomain():
"""Mailbox creation is allowed only for a domain enabled.
A failed status for the mail domain raises an error."""
with pytest.raises(
exceptions.ValidationError,
match="You can create mailbox only for a domain enabled",
):
factories.MailboxFactory(
domain=factories.MailDomainFactory(
status=enums.MailDomainStatusChoices.FAILED
)
)
def test_models_mailboxes__cannot_be_created_for_pending_maildomain():
"""Mailbox creation is allowed only for a domain enabled.
A pending status for the mail domain raises an error."""
with pytest.raises(
exceptions.ValidationError,
match="You can create mailbox only for a domain enabled",
):
# MailDomainFactory initializes a mail domain with default values,
# so mail domain status is pending!
factories.MailboxFactory(domain=factories.MailDomainFactory())
### REACTING TO DIMAIL-API
### We mock dimail's responses to avoid testing dimail's container too
@override_settings(MAIL_PROVISIONING_API_CREDENTIALS=None)
def test_models_mailboxes__dimail_no_credentials():
"""
If MAIL_PROVISIONING_API_CREDENTIALS setting is not configured,
trying to create a mailbox should raise an error.
"""
domain = factories.MailDomainEnabledFactory()
with pytest.raises(
exceptions.ValidationError,
match="Please configure MAIL_PROVISIONING_API_CREDENTIALS before creating any mailbox.",
):
factories.MailboxFactory(domain=domain)

Some files were not shown because too many files have changed in this diff Show More