From cfe4c09645f9fa2ea507ddab599c7dd6e65c1f24 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Sun, 29 Nov 2026 08:46:42 +0300 Subject: [PATCH 001/120] feat: add step-up authentication for sensitive account actions --- docs/index.rst | 1 + docs/two_factor.rst | 422 ++++++++++ .../tests/viewsets/test_connect_viewset.py | 32 + .../test_organization_profile_viewset.py | 46 ++ .../viewsets/test_stepup_connect_gates.py | 112 +++ .../viewsets/test_stepup_dataview_gates.py | 187 +++++ .../test_stepup_form_and_transfer_gates.py | 716 ++++++++++++++++ .../viewsets/test_stepup_form_move_gates.py | 143 ++++ .../test_stepup_merged_xform_gates.py | 166 ++++ .../viewsets/test_stepup_metadata_gates.py | 326 ++++++++ .../test_stepup_organization_gates.py | 422 ++++++++++ .../viewsets/test_stepup_sharing_gates.py | 773 ++++++++++++++++++ .../tests/viewsets/test_stepup_team_gates.py | 506 ++++++++++++ .../test_stepup_user_profile_gates.py | 372 +++++++++ .../viewsets/test_stepup_username_gate.py | 120 +++ .../api/tests/viewsets/test_stepup_viewset.py | 233 ++++++ .../api/tests/viewsets/test_totp_viewset.py | 172 ++-- .../viewsets/test_totp_viewset_concurrency.py | 29 +- .../viewsets/test_user_profile_viewset.py | 310 ++++++- .../v2/test_organization_profile_viewset.py | 22 + onadata/apps/api/tools.py | 8 +- onadata/apps/api/urls/v1_urls.py | 2 + onadata/apps/api/viewsets/connect_viewset.py | 28 + onadata/apps/api/viewsets/dataview_viewset.py | 41 +- .../apps/api/viewsets/merged_xform_viewset.py | 30 + onadata/apps/api/viewsets/metadata_viewset.py | 105 +++ .../apps/api/viewsets/open_data_viewset.py | 47 +- .../viewsets/organization_profile_viewset.py | 83 +- onadata/apps/api/viewsets/project_viewset.py | 147 +++- onadata/apps/api/viewsets/stepup_viewset.py | 131 +++ onadata/apps/api/viewsets/team_viewset.py | 106 ++- onadata/apps/api/viewsets/totp_viewset.py | 122 +-- .../apps/api/viewsets/user_profile_viewset.py | 143 +++- .../v2/organization_profile_viewset.py | 7 + onadata/apps/api/viewsets/xform_viewset.py | 103 +++ onadata/apps/main/forms.py | 32 +- onadata/apps/main/registration_urls.py | 10 + onadata/apps/main/registration_views.py | 26 +- .../tests/test_stepup_legacy_publish_gate.py | 87 ++ .../apps/main/tests/test_stepup_oauth_gate.py | 327 ++++++++ onadata/apps/main/tests/test_stepup_pages.py | 177 ++++ .../tests/test_stepup_public_link_gate.py | 94 +++ onadata/apps/main/urls.py | 10 + onadata/apps/main/views.py | 126 +++ .../viewsets/test_stepup_webhook_gate.py | 255 ++++++ onadata/apps/restservice/views.py | 6 + .../viewsets/restservices_viewset.py | 43 + onadata/libs/apps.py | 40 + onadata/libs/authentication.py | 17 + .../serializers/organization_serializer.py | 7 + .../libs/serializers/project_serializer.py | 52 +- .../serializers/user_profile_serializer.py | 35 +- onadata/libs/stepup/__init__.py | 11 + onadata/libs/stepup/capabilities.py | 56 ++ onadata/libs/stepup/challenge.py | 58 ++ onadata/libs/stepup/checks.py | 259 ++++++ onadata/libs/stepup/drf.py | 92 +++ onadata/libs/stepup/federated.py | 19 + onadata/libs/stepup/gate.py | 189 +++++ onadata/libs/stepup/pages.py | 68 ++ onadata/libs/stepup/policy.py | 194 +++++ onadata/libs/stepup/sharing.py | 192 +++++ onadata/libs/tests/stepup/__init__.py | 0 .../libs/tests/stepup/test_capabilities.py | 64 ++ onadata/libs/tests/stepup/test_challenge.py | 81 ++ onadata/libs/tests/stepup/test_checks.py | 333 ++++++++ onadata/libs/tests/stepup/test_drf.py | 253 ++++++ onadata/libs/tests/stepup/test_policy.py | 53 ++ onadata/libs/tests/utils/test_xform_utils.py | 39 + onadata/libs/utils/log.py | 3 + onadata/libs/utils/xform_utils.py | 48 +- onadata/settings/common.py | 36 +- requirements/base.in | 4 +- requirements/base.pip | 2 +- requirements/dev.pip | 2 +- 75 files changed, 9391 insertions(+), 222 deletions(-) create mode 100644 docs/two_factor.rst create mode 100644 onadata/apps/api/tests/viewsets/test_stepup_connect_gates.py create mode 100644 onadata/apps/api/tests/viewsets/test_stepup_dataview_gates.py create mode 100644 onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py create mode 100644 onadata/apps/api/tests/viewsets/test_stepup_form_move_gates.py create mode 100644 onadata/apps/api/tests/viewsets/test_stepup_merged_xform_gates.py create mode 100644 onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py create mode 100644 onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py create mode 100644 onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py create mode 100644 onadata/apps/api/tests/viewsets/test_stepup_team_gates.py create mode 100644 onadata/apps/api/tests/viewsets/test_stepup_user_profile_gates.py create mode 100644 onadata/apps/api/tests/viewsets/test_stepup_username_gate.py create mode 100644 onadata/apps/api/tests/viewsets/test_stepup_viewset.py create mode 100644 onadata/apps/api/viewsets/stepup_viewset.py create mode 100644 onadata/apps/main/tests/test_stepup_legacy_publish_gate.py create mode 100644 onadata/apps/main/tests/test_stepup_oauth_gate.py create mode 100644 onadata/apps/main/tests/test_stepup_pages.py create mode 100644 onadata/apps/main/tests/test_stepup_public_link_gate.py create mode 100644 onadata/apps/restservice/tests/viewsets/test_stepup_webhook_gate.py create mode 100644 onadata/libs/apps.py create mode 100644 onadata/libs/stepup/__init__.py create mode 100644 onadata/libs/stepup/capabilities.py create mode 100644 onadata/libs/stepup/challenge.py create mode 100644 onadata/libs/stepup/checks.py create mode 100644 onadata/libs/stepup/drf.py create mode 100644 onadata/libs/stepup/federated.py create mode 100644 onadata/libs/stepup/gate.py create mode 100644 onadata/libs/stepup/pages.py create mode 100644 onadata/libs/stepup/policy.py create mode 100644 onadata/libs/stepup/sharing.py create mode 100644 onadata/libs/tests/stepup/__init__.py create mode 100644 onadata/libs/tests/stepup/test_capabilities.py create mode 100644 onadata/libs/tests/stepup/test_challenge.py create mode 100644 onadata/libs/tests/stepup/test_checks.py create mode 100644 onadata/libs/tests/stepup/test_drf.py create mode 100644 onadata/libs/tests/stepup/test_policy.py create mode 100644 onadata/libs/tests/utils/test_xform_utils.py diff --git a/docs/index.rst b/docs/index.rst index 5f321eb1b2..1f0705655d 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -15,6 +15,7 @@ Authentication :maxdepth: 2 authentication + two_factor Data Endpoints -------------- diff --git a/docs/two_factor.rst b/docs/two_factor.rst new file mode 100644 index 0000000000..d0f089c6cc --- /dev/null +++ b/docs/two_factor.rst @@ -0,0 +1,422 @@ +Two-Factor Authentication +************************* + +Where a deployment enables it, an account can protect sign-in with a second +factor: an authenticator app (TOTP), backed by single-use recovery codes. +Every endpoint below acts on the authenticated caller and nobody else -- none +accepts a username, so none can be pointed at another user's second factor. + +All endpoints live under ``/api/v1/totp`` and answer **404** on deployments +that have not enabled two-factor (``ENABLE_TWO_FACTOR``). On deployments where +an identity provider owns the second factor instead of Ona, the management +endpoints refuse with **409** and ``"error": "not_managed_here"`` -- check +``status`` before offering any of these controls. + +Status +------ + +.. raw:: html + +
GET /api/v1/totp/status
+ +Reports the account's second factor and recovery-code state, and which +controls this deployment can honour. + +:: + + curl -X GET https://api.ona.io/api/v1/totp/status -H "Authorization: Token TOKEN_KEY" + +Response:: + + { + "managedBy": "onadata", + "capabilities": { + "enroll": true, + "disable": true, + "recoveryCodes": true, + "verify": true + }, + "methods": [ + {"kind": "totp", "label": "default", "createdAt": "2026-08-27T09:00:00"} + ], + "recoveryCodes": {"generated": true, "remaining": 8} + } + +``managedBy`` is ``"idp"`` and every capability ``false`` where an identity +provider owns the factor; a client should not offer controls reported +unavailable -- the server refuses them regardless. + +Enrolling an authenticator +-------------------------- + +Enrolment is a two-step handshake: start it to receive the secret, then +confirm it by echoing a code from the app, which proves the secret was +captured correctly. Both steps demand a signed-in session -- an API key is +refused, so a leaked key cannot change how its owner signs in. + +.. raw:: html + +
POST /api/v1/totp/enroll/start
+ +A first enrolment must carry the account's password. Replacing an existing +authenticator instead demands a current ``code`` (or a ``grant`` from +``verify``), the same proof disabling requires. + +:: + + curl -X POST https://api.ona.io/api/v1/totp/enroll/start -d "password=PASSWORD" --cookie "SSO=..." + +Response (**201**):: + + { + "qrDataUrl": "data:image/png;base64,...", + "otpauthUri": "otpauth://totp/...", + "secretBase32": "JBSWY3DPEHPK3PXP" + } + +One secret in three renderings: a QR image to scan, the provisioning URI, and +the base32 secret to type by hand. Starting again replaces the pending +attempt. A wrong password answers **403** with ``"reason": +"password_required"``; an account with no usable password is refused with +``"reason": "no_password_set"``. Password guesses here spend the login form's +lockout allowance -- this endpoint is not a separate brute-force budget. +The current password asked for by an email change on +``/api/v1/profiles/{username}`` and by ``/accounts/password/change/`` spends +the same allowance, so repeated mistakes there also lock the login form for +``LOCKOUT_TIME``. ``POST /api/v1/profiles/{username}/change_password`` keeps +its own counter. + +.. raw:: html + +
POST /api/v1/totp/enroll/confirm
+ +:: + + curl -X POST https://api.ona.io/api/v1/totp/enroll/confirm -d "code=123456" --cookie "SSO=..." + +Response (**200**):: + + { + "enrolled": true, + "codes": ["mfrggzdfmztwq2lk", "..."] + } + +Confirming activates the authenticator and returns ten fresh recovery codes. +Answers **409** when there is no pending enrolment to confirm, and **403** +when the code is wrong. + +Recovery codes +-------------- + +Each code signs the user in once when the authenticator is lost. The set is +replaced wholesale, never appended to, so the remaining count reported by +``status`` stays honest. + +.. raw:: html + +
POST /api/v1/totp/recovery/generate
+ +Replaces the set and returns the new codes (**201**). The previous codes stop +working. Demands a current ``code`` or ``grant``. + +.. raw:: html + +
POST /api/v1/totp/recovery
+ +Returns the codes that have not been spent yet (**200**), for a user who has +lost their printout without invalidating a set that is still good. Demands a +current ``code`` or ``grant``; answers **404** when no set has been +generated. POST rather than GET so the proof travels in the body, never in a +URL or an access log. + +Disabling +--------- + +.. raw:: html + +
POST /api/v1/totp/disable
+ +:: + + curl -X POST https://api.ona.io/api/v1/totp/disable -d "code=123456" -H "Authorization: Token TOKEN_KEY" + +Response (**200**):: + + {"enrolled": false} + +Removes every device the login view could challenge on. Demands a current +``code`` -- a recovery code counts, so a lost authenticator can still be +turned off -- or a ``grant``. Idempotent: an account with no second factor +answers the same way. + +Step-up verification +-------------------- + +.. raw:: html + +
POST /api/v1/totp/verify
+ +Checks a code without changing anything, and mints a short-lived grant for +one named operation -- for clients that verify first and act second, since a +TOTP code is spent the moment it is checked. + +:: + + curl -X POST https://api.ona.io/api/v1/totp/verify -d "code=123456" -d "audience=disable" -H "Authorization: Token TOKEN_KEY" + +Response (**200**):: + + {"verified": true, "grant": "..."} + +``audience`` names the operation the grant unlocks and must be one the +deployment recognises: an operation above, an action ``STEP_UP`` can gate, +or one listed in ``TWO_FACTOR_STEP_UP_AUDIENCES``. Unknown values answer +**400**. The grant is single-use, expires after +``STEP_UP_GRANT_TTL`` seconds (default 300), and is honoured only by the +operation it was minted for. ``method`` optionally pins which factor the code +must prove -- ``totp`` or ``recovery`` -- and defaults to accepting either. + +Step-up for account actions +--------------------------- + +A deployment can demand a fresh second factor for sensitive account actions +too. Each is opted into by its audience in ``STEP_UP["ACTIONS"]``; none is +gated by default. + +========================== ==================================================== +Audience Action +========================== ==================================================== +``regenerate-api-key`` ``GET /api/v1/user/regenerate_auth_token`` +``regenerate-odk-token`` ``POST /api/v1/user/odk_token`` +``change-password`` ``POST /api/v1/profiles/{username}/change_password`` +``change-email`` changing ``email`` on ``/api/v1/profiles/{username}`` +``require-auth-toggle`` changing ``require_auth`` on the same route, or on + ``/api/v1/orgs/{org}`` +``privacy-consent`` changing the consent record in profile ``metadata`` +``grant-org-admin`` making someone an owner or manager on + ``/api/v1/orgs/{org}/members`` or ``/api/v2/orgs/{org}/members``, + or adding them to the organisation's Owners team +``rotate-org-key`` ``POST /api/v1/orgs/{org}/rotate-key`` +``change-username`` changing ``username`` on ``/api/v1/profiles/{username}`` +``change-webhook`` adding a webhook on ``/api/v1/restservices``, or changing + where one sends; changing a form's ``textit`` settings + on ``/api/v1/metadata`` +``share-form-admin`` sharing a form with the owner or manager role through + ``/api/v1/forms/{pk}/share``; writing a form's + ``xform_meta_perms`` on ``/api/v1/metadata`` so a slot + newly names owner or manager, or so applying it makes + a current user one; moving a form through + ``/api/v1/projects/{pk}/forms`` where its meta + permissions make the project's users owners or + managers of it, unless ``transfer-project`` covers + the move +``share-project-admin`` sharing a project with the owner or manager role + through ``/api/v1/projects/{pk}/share`` +``invite-project-admin`` inviting someone to a project as owner or manager + through ``/api/v1/projects/{pk}/invitations`` +``share-team-admin`` sharing a project with a team as owner or manager + through ``/api/v1/teams/{pk}/share``, or any team share + whose re-applied meta permissions make someone one; + adding a user to a team that owns or manages a project + or form, directly or through a form's meta + permissions, through ``/api/v1/teams/{pk}/members``; + adding or re-adding a member on + ``/api/v1/orgs/{org}/members`` or + ``/api/v2/orgs/{org}/members`` where the projects + shared with them make them an owner or manager +``publish-data`` making a form's or project's data public; moving a + private form into a public project; turning on a + form's ``public_link`` on ``/api/v1/metadata``; + creating a dataview in a public project, or changing + the project, columns or query of one there, over a + form whose data is not public; creating a merged + dataset in a public project from such forms +``transfer-project`` moving a project to another account by changing its + ``owner``; moving a form into another account's + project through ``/api/v1/projects/{pk}/forms``, or + by changing its ``owner`` or ``project`` on + ``/api/v1/forms/{pk}``; creating a merged dataset in + another account's project from a form +``authorize-oauth-app`` approving an OAuth application at ``/o/authorize/``, + or registering one under ``/o/applications/`` +``form-require-auth`` turning off ``require_auth`` on ``/api/v1/forms/{pk}`` +``disable-form-encryption`` turning off a form's encryption with + ``enable_kms_encryption`` +========================== ==================================================== + +A form's meta permissions can turn an editor, data-entry or read-only share +into an owner or manager one. The ``share-*`` and ``invite-*`` gates count the +role a share ends up granting, so an editor share on such a form is gated like +an owner share. + +The token gates protect replacing a token, which breaks every integration +that holds the old one. They do not hide the current tokens: a signed-in +session can still read the API token from ``GET /api/v1/user`` and the ODK +token from ``GET /api/v1/user/odk_token``. + +Gate ``grant-org-admin`` alongside the organisation gates. Without it, a +stolen owner session can appoint the attacker's own account as an owner, and +that account then passes every gate with its own factor. For the same +reason, gate the four ``share-*`` and ``invite-*`` audiences together, and +``transfer-project``. + +The profile gates fire only when a value actually changes, so writing back an +unchanged profile is not challenged. The settings page at +``/{username}/settings`` and the password page at +``/accounts/password/change/`` write the same values; they cannot run a +challenge, so they refuse a gated change with **403**. So do the OAuth pages +at ``/o/authorize/`` and ``/o/applications/``: with ``authorize-oauth-app`` +gated, every user the gate challenges is refused when approving or +registering an application. + +A gated request without a grant answers **401**:: + + {"error": "step_up_required", "audience": "change-email", "dialect": "local-totp"} + +The caller earns a grant for ``audience`` and repeats the request with it: as a +``grant`` field in the body or, for a request with no body, in the +``X-Step-Up-Grant`` header -- never in the query string. Each grant is spent by +the request that presents it, so a single request changing two gated values is +refused; change them one at a time. Adding a team or organisation member is +the exception: when it is gated by both ``grant-org-admin`` and +``share-team-admin``, one grant for the first gated audience covers it. A +grant also covers the same action gated again within the request that spent +it. A request is validated before its grant is spent, so one that would be +rejected anyway answers **400** and keeps the grant. + +``STEP_UP["MODE"]`` decides where the factor is proved: + +- ``local`` (default) -- Ona owns the factor. The challenge's ``dialect`` is + ``local-totp``: prove a code at ``POST /api/v1/totp/verify`` with + ``audience`` set, and present the grant it returns. +- ``federated`` -- an identity provider owns the factor. The ``dialect`` is + ``oidc`` and the challenge carries an ``authorizationUrl`` to send the user + to. ``GET /api/v1/stepup/start?audience=...`` returns the same URL before the + gated request is made, for a browser that must open it from a click. The + provider returns to ``/api/v1/stepup/callback``, which checks the token + against the ``STEP_UP`` block of the provider's entry in + ``OPENID_CONNECT_AUTH_SERVERS`` (see ona-oidc). That block's + ``REDIRECT_URI`` must point at this callback. A browser landing there gets + a page that posts ``{"type": "oidc-step-up", "verified": true, "grant": + "..."}`` to its opener at ``STEP_UP_POPUP_ORIGIN``; any other caller gets + ``{"grant": "..."}``, or **403** ``step_up_failed`` with a ``reason``. When + no provider is configured, or it lacks its endpoints, a gated request and + ``start`` both answer **503** with ``"error": "step_up_unavailable"``. + + The callback matches the token to the signed-in user by email. It checks + ``email_verified`` only when the provider's entry sets + ``CHECK_EMAIL_VERIFIED`` or ``REQUIRE_VERIFIED_EMAIL``, and both are off by + default. With both off, an attacker who has the user's password can sign + in at the provider as an account holding the user's address, unverified, + and pass step-up with their own factor. Turn ``CHECK_EMAIL_VERIFIED`` on + wherever users can add an address they don't own at the provider. A + refused token answers ``step_up_failed`` with reason ``email_unverified``. + +In local mode, a user with no second factor is let through by default +(``STEP_UP["NO_FACTOR_POLICY"] = "skip_gate"``); ``deny_prompt_enrol`` refuses +them with **403** and ``"error": "enrol_required"`` instead. A federated +deployment cannot see its users' factors, so it always challenges. + +.. raw:: html + +
GET /api/v1/user/capabilities
+ +Reports which credential controls apply on this deployment, so a client can +leave out the ones that do not:: + + { + "password": {"change": true}, + "twoFactor": { + "managedBy": "onadata", + "enroll": true, + "disable": true, + "recoveryCodes": true, + "verify": true + }, + "identityProvider": "" + } + +Startup checks report a step-up configuration that cannot work as +intended: + +- ``stepup.E001`` (error) -- ``STEP_UP`` is not a dict, or its ``ACTIONS`` + is not a list of action names. Step-up reads such a setting as gating + nothing +- ``stepup.E002`` (error) -- ``STEP_UP["ACTIONS"]`` names an action no gate + checks, in either mode. A misspelt action leaves the intended one ungated +- ``stepup.W001`` -- actions are gated, but ``skip_gate`` lets users with no + factor through +- ``stepup.W003`` -- ``STEP_UP["MODE"]`` is neither ``local`` nor + ``federated`` +- ``stepup.W004`` -- actions are gated in local mode with + ``ENABLE_TWO_FACTOR`` off, so nobody can earn a grant +- ``stepup.W005`` -- ``TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD`` is still set. + It has been removed: enrolling a first device always needs the account + password +- ``stepup.W006`` -- federated actions are gated but ``change-email`` is not. + Step-up identifies the user by email, so an ungated email change gets + around every gate +- ``stepup.W007`` -- federated step-up identifies the user by a field other + than email, such as the username, which a user can change without + step-up +- ``stepup.W008`` -- ``STEP_UP["NO_FACTOR_POLICY"]`` is neither + ``skip_gate`` nor ``deny_prompt_enrol``; it refuses users with no factor +- ``stepup.W009`` -- ``authorize-oauth-app`` is gated, but the OAuth pages + cannot run a challenge, so approvals the gate challenges are refused + +Signing in +---------- + +With a factor enrolled, the login page at ``/account/login/`` challenges for +a current code (or a recovery code) after the password step. Failed code +entries spend the same lockout allowance as failed passwords +(``MAX_LOGIN_ATTEMPTS`` within ``LOCKOUT_TIME``), so the second factor is not +a separate guessing budget. + +Security events +--------------- + +Second-factor changes leave a trace. These actions are written to the +security audit log: + +- ``two-factor-enrolled`` -- an authenticator was confirmed +- ``two-factor-disabled`` -- the second factor was removed +- ``two-factor-verification-failed`` -- a code check failed, on any endpoint + above or on the login page's code steps +- ``two-factor-recovery-codes-generated`` -- the recovery set was replaced +- ``two-factor-recovery-codes-viewed`` -- the unspent set was re-read + +The account owner is emailed when an authenticator is enrolled, when +two-factor is disabled, and when the recovery set is replaced -- whoever made +the change, the owner finds out. Repeated failed code checks also alert the +owner: one email per window after ``TWO_FACTOR_FAILURE_ALERT_THRESHOLD`` +failures within ``TWO_FACTOR_FAILURE_ALERT_WINDOW`` seconds (defaults 10 and +1800; a threshold of 0 disables the alert). Events are recorded, material is +not: no codes, secrets or grants appear in log entries or emails. + +Deployment settings +------------------- + +- ``ENABLE_TWO_FACTOR`` -- gates every endpoint above; default ``False`` +- ``TWO_FACTOR_STEP_UP_AUDIENCES`` -- extra operations ``verify`` may mint + a grant for, beyond every audience above; default empty +- ``STEP_UP_GRANT_TTL`` -- grant lifetime in seconds; default 300 +- ``STEP_UP`` -- ``ACTIONS``, ``MODE`` and ``NO_FACTOR_POLICY``, described + above +- ``STEP_UP_POPUP_ORIGIN`` -- the origin the federated callback page posts + the grant to; required for a browser to complete a federated step-up +- ``STEP_UP_IDP_NAME`` -- the provider name ``capabilities`` reports as + ``identityProvider`` +- ``EU_CONSENT_METADATA_PATH`` -- the keys leading to the consent record in + profile ``metadata``; default ``("eu_citizen_consent",)`` +- ``CORS_ALLOW_HEADERS`` -- includes ``x-step-up-grant`` by default; a + deployment that overrides it must keep that header for browser callers on + another origin +- ``TWO_FACTOR_FAILURE_ALERT_THRESHOLD`` / ``TWO_FACTOR_FAILURE_ALERT_WINDOW`` + -- repeated-failure alerting, described above +- ``TWO_FACTOR_REMEMBER_COOKIE_AGE`` -- how long "don't ask again on this + device" holds at login; unset it to challenge on every sign-in + +Grants live in the cache, as do the lockout and repeated-failure counters, so +the deployment must run a cache shared across workers (Redis or memcached); a +per-process cache would fragment all three and weaken them. diff --git a/onadata/apps/api/tests/viewsets/test_connect_viewset.py b/onadata/apps/api/tests/viewsets/test_connect_viewset.py index 0a337cbba3..206a232df9 100644 --- a/onadata/apps/api/tests/viewsets/test_connect_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_connect_viewset.py @@ -11,6 +11,8 @@ from django.core import mail from django.core.cache import cache from django.template.loader import render_to_string +from django.test import override_settings +from django.urls import reverse from django.utils.timezone import now from django_digest.backend.db import update_partial_digests @@ -29,6 +31,36 @@ from onadata.libs.utils.cache_tools import safe_key +@override_settings(STEP_UP={"MODE": "local"}, ENABLE_TWO_FACTOR=True) +class TestCapabilitiesRoute(TestAbstractViewSet): + """The capabilities route is reachable and reports the current mode.""" + + def setUp(self): + super().setUp() + self._login_user_and_profile() + self.view = ConnectViewSet.as_view({"get": "capabilities"}) + + def test_local_mode_reports_onadata_as_the_owner(self): + response = self.view(self.factory.get("/", **self.extra)) + + self.assertEqual(response.status_code, 200) + self.assertEqual(response.data["twoFactor"]["managedBy"], "onadata") + self.assertTrue(response.data["password"]["change"]) + self.assertEqual(response.data["identityProvider"], "") + + def test_an_anonymous_caller_is_refused(self): + """The response names what the caller may manage, so only the caller + may read it.""" + response = self.view(self.factory.get("/")) + + self.assertIn(response.status_code, (401, 403)) + + def test_the_route_is_registered(self): + """The other cases bind the method directly. They would pass even if + no route served it.""" + self.assertEqual(reverse("connect-capabilities"), "/api/v1/user/capabilities") + + class TestConnectViewSet(TestAbstractViewSet): def setUp(self): super(self.__class__, self).setUp() diff --git a/onadata/apps/api/tests/viewsets/test_organization_profile_viewset.py b/onadata/apps/api/tests/viewsets/test_organization_profile_viewset.py index 360caa1b48..c54d14265c 100644 --- a/onadata/apps/api/tests/viewsets/test_organization_profile_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_organization_profile_viewset.py @@ -316,6 +316,52 @@ def test_orgs_create(self): self.assertEqual(versions.count(), 1) self.assertEqual(versions[0].revision.user, self.user) + def test_orgs_create_require_auth_overrides_deployment_default(self): + for default, requested in ((False, True), (True, False)): + with self.subTest(default=default), override_settings( + REQUIRE_ODK_AUTHENTICATION=default + ): + org = f"default{str(default).lower()}inc" + data = { + "org": org, + "name": org, + "email": f"{org}@mail.org", + "require_auth": requested, + } + request = self.factory.post( + "/", + data=json.dumps(data), + content_type="application/json", + **self.extra, + ) + response = self.view(request) + self.assertEqual(response.status_code, 201, response.data) + profile = OrganizationProfile.objects.get(user__username=org) + self.assertEqual(profile.require_auth, requested) + + @override_settings(REQUIRE_ODK_AUTHENTICATION=True) + def test_orgs_create_form_data_without_require_auth_keeps_default(self): + request = self.factory.post( + "/", + data={"org": "forminc", "name": "Form Inc", "email": "form@mail.org"}, + **self.extra, + ) + response = self.view(request) + self.assertEqual(response.status_code, 201, response.data) + profile = OrganizationProfile.objects.get(user__username="forminc") + self.assertTrue(profile.require_auth) + + @override_settings(REQUIRE_ODK_AUTHENTICATION=True) + def test_orgs_create_form_data_with_empty_require_auth_keeps_default(self): + data = {"org": "blankinc", "name": "Blank Inc", "email": "blank@mail.org"} + request = self.factory.post( + "/", data={**data, "require_auth": ""}, **self.extra + ) + response = self.view(request) + self.assertEqual(response.status_code, 201, response.data) + profile = OrganizationProfile.objects.get(user__username="blankinc") + self.assertTrue(profile.require_auth) + def test_orgs_create_without_name(self): data = { "org": "denoinc", diff --git a/onadata/apps/api/tests/viewsets/test_stepup_connect_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_connect_gates.py new file mode 100644 index 0000000000..c6a979330b --- /dev/null +++ b/onadata/apps/api/tests/viewsets/test_stepup_connect_gates.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- +""" +Tests for the step-up gates on regenerating the API and ODK tokens. +""" + +from django.test.utils import override_settings +from django.urls import reverse + +from oidc.stepup_grants import issue_grant +from registration.models import RegistrationProfile +from rest_framework.authtoken.models import Token + +from onadata.apps.api.models.odk_token import ODKToken +from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import ( + StepUpGateTestCase, + gating, +) +from onadata.apps.api.tests.viewsets.test_stepup_user_profile_gates import ( + ACCOUNT_ACTIONS, +) +from onadata.apps.api.viewsets.connect_viewset import ConnectViewSet + + +@gating(*ACCOUNT_ACTIONS) +class TestTokenRegenerationGates(StepUpGateTestCase): + """Regenerating a token breaks every integration that holds the old one + and mints a new long-lived credential. A stolen session alone must not be + able to do it. + """ + + def setUp(self): + super().setUp() + RegistrationProfile.objects.create_profile(self.user) + + def _regenerate(self, headers=None): + view = ConnectViewSet.as_view({"get": "regenerate_auth_token"}) + return view(self.factory.get("/", **{**self.extra, **(headers or {})})) + + def _regenerate_odk(self, headers=None): + view = ConnectViewSet.as_view({"post": "odk_token"}) + return view(self.factory.post("/", **{**self.extra, **(headers or {})})) + + def _api_token(self): + return Token.objects.get(user=self.user).key + + def _active_odk_tokens(self): + return list( + ODKToken.objects.filter(user=self.user, status=ODKToken.ACTIVE) + .order_by("pk") + .values_list("pk", flat=True) + ) + + def test_regenerating_the_api_token_is_challenged(self): + old_token = self._api_token() + + response = self._regenerate() + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "regenerate-api-key") + self.assertEqual(self._api_token(), old_token) + + def test_a_grant_in_the_header_lets_the_regeneration_through(self): + """A GET has no body, so the grant travels in a header. A query string + would be written to logs, browser history and the Referer header.""" + grant = issue_grant(self.user.pk, "regenerate-api-key") + old_token = self._api_token() + + response = self._regenerate({"HTTP_X_STEP_UP_GRANT": grant}) + + self.assertEqual(response.status_code, 201) + self.assertNotEqual(self._api_token(), old_token) + self.assertEqual(response.data, self._api_token()) + + @override_settings( + CORS_ALLOW_ALL_ORIGINS=False, + CORS_ALLOWED_ORIGINS=["https://app.example"], + ) + def test_a_browser_on_another_origin_may_send_the_grant_header(self): + """The header is the only way a grant reaches this GET. A preflight + that refuses it would make the gate impossible to pass from another + origin.""" + response = self.client.options( + reverse("connect-regenerate-auth-token"), + HTTP_ORIGIN="https://app.example", + HTTP_ACCESS_CONTROL_REQUEST_METHOD="GET", + HTTP_ACCESS_CONTROL_REQUEST_HEADERS="x-step-up-grant", + ) + + self.assertEqual(response["access-control-allow-origin"], "https://app.example") + self.assertIn("x-step-up-grant", response["access-control-allow-headers"]) + + def test_regenerating_the_odk_token_is_challenged(self): + """Rotating the ODK token invalidates a live ODK Collect credential, + so it is gated like the API token.""" + old_token = ODKToken.objects.create(user=self.user) + + response = self._regenerate_odk() + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "regenerate-odk-token") + self.assertEqual(self._active_odk_tokens(), [old_token.pk]) + + def test_a_grant_lets_the_odk_token_regeneration_through(self): + old_token = ODKToken.objects.create(user=self.user) + grant = issue_grant(self.user.pk, "regenerate-odk-token") + + response = self._regenerate_odk({"HTTP_X_STEP_UP_GRANT": grant}) + + self.assertEqual(response.status_code, 201) + active = self._active_odk_tokens() + self.assertEqual(len(active), 1) + self.assertNotEqual(active, [old_token.pk]) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_dataview_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_dataview_gates.py new file mode 100644 index 0000000000..530e8cf176 --- /dev/null +++ b/onadata/apps/api/tests/viewsets/test_stepup_dataview_gates.py @@ -0,0 +1,187 @@ +# -*- coding: utf-8 -*- +""" +Tests for the step-up gate on dataviews, which anyone can read once they sit +in a public project. +""" + +import os + +from django.conf import settings + +from onadata.apps.api.tests.viewsets.test_stepup_form_and_transfer_gates import ( + GateTestCase, +) +from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import gating +from onadata.apps.api.viewsets.dataview_viewset import DataViewViewSet +from onadata.apps.logger.models import DataView, Project, XForm +from onadata.libs.permissions import ManagerRole +from onadata.libs.stepup.policy import GATE_PUBLISH_DATA + +COLUMNS = '["name", "age"]' + + +@gating(GATE_PUBLISH_DATA) +class TestPublishDataViewGate(GateTestCase): + """A dataview in a public project shows its source form's rows to anyone, + so a stolen session must not be able to put one there.""" + + audience = GATE_PUBLISH_DATA + + def setUp(self): + super().setUp() + xlsform_path = os.path.join( + settings.PROJECT_ROOT, "libs", "tests", "utils", "fixtures", "tutorial.xlsx" + ) + self._publish_xls_form_to_project(xlsform_path=xlsform_path) + self.private_project = self.project + self.public_project = self._managed_project("open", shared=True) + self.assertFalse(self.private_project.shared) + self.assertFalse(self.xform.shared_data) + + def _managed_project(self, name, shared): + project = Project.objects.create( + name=name, + organization=self.user, + created_by=self.user, + metadata={}, + shared=shared, + ) + ManagerRole.add(self.user, project) + return project + + def _dataview(self, project): + return DataView.objects.create( + name="existing", + xform=self.xform, + project=project, + columns=["name"], + ) + + @staticmethod + def _url(kind, pk): + return f"http://testserver/api/v1/{kind}/{pk}" + + def _create(self, project, headers=None): + view = DataViewViewSet.as_view({"post": "create"}) + data = { + "name": "My DataView", + "xform": self._url("forms", self.xform.pk), + "project": self._url("projects", project.pk), + "columns": COLUMNS, + "query": "[]", + } + request = self.factory.post("/", data=data, **{**self.extra, **(headers or {})}) + return view(request) + + def _patch(self, dataview, data, headers=None): + view = DataViewViewSet.as_view({"patch": "partial_update"}) + request = self.factory.patch( + "/", data=data, **{**self.extra, **(headers or {})} + ) + return view(request, pk=dataview.pk) + + def test_creating_one_in_a_public_project_is_challenged(self): + """The 401 names the audience and no dataview is made.""" + response = self._create(self.public_project) + + self.assert_challenged(response) + self.assertFalse(DataView.objects.exists()) + + def test_a_grant_lets_the_dataview_be_created(self): + """With a grant the dataview is made in the public project.""" + grant = self._grant() + + response = self._create(self.public_project, self._with_grant(grant)) + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(DataView.objects.get().project, self.public_project) + self.assert_spent(grant) + + def test_creating_one_in_a_private_project_is_not_challenged(self): + """A private project publishes nothing.""" + self.assert_challenged(self._create(self.public_project)) + + response = self._create(self.private_project) + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(DataView.objects.get().project, self.private_project) + + def test_one_over_public_data_is_not_challenged(self): + """Data that is already public is not published again.""" + self.assert_challenged(self._create(self.public_project)) + XForm.objects.filter(pk=self.xform.pk).update(shared=True, shared_data=True) + + response = self._create(self.public_project) + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(DataView.objects.get().project, self.public_project) + + def test_an_invalid_dataview_keeps_the_grant(self): + """Validation comes first, so a missing name does not spend it.""" + self.assert_challenged(self._create(self.public_project)) + grant = self._grant() + view = DataViewViewSet.as_view({"post": "create"}) + data = { + "xform": self._url("forms", self.xform.pk), + "project": self._url("projects", self.public_project.pk), + "columns": COLUMNS, + } + request = self.factory.post( + "/", data=data, **{**self.extra, **self._with_grant(grant)} + ) + + response = view(request) + + self.assertEqual(response.status_code, 400, response.data) + self.assert_unspent(grant) + self.assertFalse(DataView.objects.exists()) + + def test_moving_one_into_a_public_project_is_challenged(self): + """The 401 names the audience and the dataview stays put.""" + dataview = self._dataview(self.private_project) + + response = self._patch( + dataview, {"project": self._url("projects", self.public_project.pk)} + ) + + self.assert_challenged(response) + dataview.refresh_from_db() + self.assertEqual(dataview.project, self.private_project) + + def test_a_grant_lets_the_dataview_move(self): + """With a grant the dataview moves into the public project.""" + dataview = self._dataview(self.private_project) + grant = self._grant() + + response = self._patch( + dataview, + {"project": self._url("projects", self.public_project.pk)}, + self._with_grant(grant), + ) + + self.assertEqual(response.status_code, 200, response.data) + dataview.refresh_from_db() + self.assertEqual(dataview.project, self.public_project) + self.assert_spent(grant) + + def test_showing_more_columns_in_a_public_project_is_challenged(self): + """Widening a public dataview publishes the added columns.""" + dataview = self._dataview(self.public_project) + + response = self._patch(dataview, {"columns": COLUMNS}) + + self.assert_challenged(response) + dataview.refresh_from_db() + self.assertEqual(dataview.columns, ["name"]) + + def test_renaming_one_in_a_public_project_is_not_challenged(self): + """A new name shows nothing new.""" + dataview = self._dataview(self.public_project) + self.assert_challenged(self._patch(dataview, {"columns": COLUMNS})) + + response = self._patch(dataview, {"name": "renamed"}) + + self.assertEqual(response.status_code, 200, response.data) + dataview.refresh_from_db() + self.assertEqual(dataview.name, "renamed") + self.assertEqual(dataview.columns, ["name"]) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py new file mode 100644 index 0000000000..94a0e7c95c --- /dev/null +++ b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py @@ -0,0 +1,716 @@ +# -*- coding: utf-8 -*- +""" +Tests for the step-up gates on transferring a project or moving a form to +another account, on weakening a form's protection, and on publishing a form's +data by moving it into a public project or by opening an open-data link to it. +""" + +import json +import os +from unittest.mock import patch + +from django.conf import settings + +from oidc.stepup_grants import spend_grant + +from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import ( + StepUpGateTestCase, + gating, +) +from onadata.apps.api.viewsets.open_data_viewset import OpenDataViewSet +from onadata.apps.api.viewsets.project_viewset import ProjectViewSet +from onadata.apps.api.viewsets.xform_viewset import XFormViewSet +from onadata.apps.logger.models import OpenData, Project, XForm +from onadata.apps.logger.models.open_data import get_or_create_opendata +from onadata.libs.permissions import OwnerRole +from onadata.libs.stepup.policy import ( + GATE_DISABLE_FORM_ENCRYPTION, + GATE_FORM_REQUIRE_AUTH, + GATE_PUBLISH_DATA, + GATE_TRANSFER_PROJECT, +) + +ONE_GATED_CHANGE = "one_gated_change_per_request" + + +class GateTestCase(StepUpGateTestCase): + """Adds assertions for a request that makes two gated changes.""" + + def assert_one_gated_change(self, response, audiences): + """Refused before any grant was spent, naming every gated change.""" + self.assertEqual(response.status_code, 400, response.data) + self.assertEqual(response.data["error"], ONE_GATED_CHANGE) + self.assertCountEqual(response.data["audiences"], audiences) + + def assert_unspent(self, grant): + """The request left ``grant`` for a later one.""" + self.assertTrue(spend_grant(self.user.pk, self.audience, grant)) + + def _patch_form(self, data, headers=None): + view = XFormViewSet.as_view({"patch": "partial_update"}) + request = self.factory.patch( + "/", data=data, **{**self.extra, **(headers or {})} + ) + return view(request, pk=self.xform.pk) + + +@gating(GATE_TRANSFER_PROJECT) +class TestTransferProjectGate(GateTestCase): + """Moving a project to another account hands that account's admins its + forms and data, so a stolen session must not be able to do it.""" + + audience = GATE_TRANSFER_PROJECT + + def setUp(self): + super().setUp() + self._project_create() + self._org_create() + self.org_user = self.organization.user + self.org_url = f"http://testserver/api/v1/users/{self.org_user.username}" + self.user_url = f"http://testserver/api/v1/users/{self.user.username}" + self.assertEqual(self.project.organization, self.user) + + def _patch(self, data, headers=None): + view = ProjectViewSet.as_view({"patch": "partial_update"}) + request = self.factory.patch( + "/", data=data, **{**self.extra, **(headers or {})} + ) + return view(request, pk=self.project.pk) + + def _owner(self): + self.project.refresh_from_db() + return self.project.organization + + def test_transferring_a_project_is_challenged(self): + response = self._patch({"owner": self.org_url}) + + self.assert_challenged(response) + self.assertEqual(self._owner(), self.user) + + def test_a_full_update_transferring_a_project_is_challenged(self): + """A full update writes ``owner`` too, without the transfer command.""" + view = ProjectViewSet.as_view({"put": "update"}) + data = {"name": "demo", "owner": self.org_url, "public": False} + request = self.factory.put("/", data=data, **self.extra) + + response = view(request, pk=self.project.pk) + + self.assert_challenged(response) + self.assertEqual(self._owner(), self.user) + + def test_a_grant_lets_the_transfer_through(self): + grant = self._grant() + + response = self._patch({"owner": self.org_url}, self._with_grant(grant)) + + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(self._owner(), self.org_user) + self.assert_spent(grant) + + def test_keeping_the_owner_is_not_challenged(self): + self.assert_challenged(self._patch({"owner": self.org_url})) + + response = self._patch({"owner": self.user_url, "name": "renamed"}) + + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(self._owner(), self.user) + self.assertEqual(self.project.name, "renamed") + + def test_a_name_taken_in_the_new_account_keeps_the_grant(self): + """The clash is found before the gate, so nothing is spent and the + new account gets no role on the project.""" + Project.objects.create( + name="DEMO", organization=self.org_user, created_by=self.user + ) + self.assertFalse(OwnerRole.user_has_role(self.org_user, self.project)) + grant = self._grant() + + response = self._patch({"owner": self.org_url}, self._with_grant(grant)) + + self.assertEqual(response.status_code, 400, response.data) + self.assertIn("name", response.data) + self.assert_unspent(grant) + self.assertEqual(self._owner(), self.user) + self.assertFalse(OwnerRole.user_has_role(self.org_user, self.project)) + + def test_a_failed_transfer_leaves_no_permissions(self): + """The new owner's role is written before the transfer runs, so a + failing transfer must take it back.""" + with patch( + "onadata.libs.serializers.project_serializer.call_command", + side_effect=RuntimeError("transfer failed"), + ): + with self.assertRaises(RuntimeError): + self._patch({"owner": self.org_url}, self._with_grant(self._grant())) + + self.assertEqual(self._owner(), self.user) + self.assertFalse(OwnerRole.user_has_role(self.org_user, self.project)) + + @gating(GATE_TRANSFER_PROJECT, GATE_PUBLISH_DATA) + def test_a_transfer_that_also_publishes_is_refused_whole(self): + grant = self._grant() + + response = self._patch( + {"name": "renamed", "owner": self.org_url, "public": True}, + self._with_grant(grant), + ) + + self.assert_one_gated_change( + response, [GATE_TRANSFER_PROJECT, GATE_PUBLISH_DATA] + ) + self.assert_unspent(grant) + self.assertEqual(self._owner(), self.user) + self.assertEqual(self.project.name, "demo") + self.assertFalse(self.project.shared) + + +@gating(GATE_FORM_REQUIRE_AUTH) +class TestFormRequireAuthGate(GateTestCase): + """A form that stops requiring authentication can be downloaded and + submitted to by anyone, so a stolen session must not be able to drop it.""" + + audience = GATE_FORM_REQUIRE_AUTH + + def setUp(self): + super().setUp() + self._publish_xls_form_to_project() + self._set_require_auth(True) + + def _set_require_auth(self, value): + XForm.objects.filter(pk=self.xform.pk).update(require_auth=value) + self.assertEqual(self._require_auth(), value) + + def _require_auth(self): + self.xform.refresh_from_db() + return self.xform.require_auth + + def test_turning_off_require_auth_is_challenged(self): + response = self._patch_form({"require_auth": False}) + + self.assert_challenged(response) + self.assertTrue(self._require_auth()) + + def test_a_grant_lets_require_auth_off(self): + grant = self._grant() + + response = self._patch_form({"require_auth": False}, self._with_grant(grant)) + + self.assertEqual(response.status_code, 200, response.data) + self.assertFalse(self._require_auth()) + self.assert_spent(grant) + + def test_turning_on_require_auth_is_not_challenged(self): + self.assert_challenged(self._patch_form({"require_auth": False})) + self._set_require_auth(False) + + response = self._patch_form({"require_auth": True}) + + self.assertEqual(response.status_code, 200, response.data) + self.assertTrue(self._require_auth()) + + def test_keeping_require_auth_on_is_not_challenged(self): + self.assert_challenged(self._patch_form({"require_auth": False})) + + response = self._patch_form({"require_auth": True, "description": "renamed"}) + + self.assertEqual(response.status_code, 200, response.data) + self.assertTrue(self._require_auth()) + self.assertEqual(self.xform.description, "renamed") + + @gating(GATE_FORM_REQUIRE_AUTH, GATE_PUBLISH_DATA) + def test_dropping_require_auth_while_publishing_is_refused_whole(self): + grant = self._grant() + + response = self._patch_form( + {"require_auth": False, "public_data": True}, self._with_grant(grant) + ) + + self.assert_one_gated_change( + response, [GATE_FORM_REQUIRE_AUTH, GATE_PUBLISH_DATA] + ) + self.assert_unspent(grant) + self.assertTrue(self._require_auth()) + self.assertFalse(self.xform.shared_data) + + +@gating(GATE_DISABLE_FORM_ENCRYPTION) +class TestDisableFormEncryptionGate(GateTestCase): + """Turning encryption off stores the next submissions readable, so a + stolen session must not be able to do it.""" + + audience = GATE_DISABLE_FORM_ENCRYPTION + + def setUp(self): + super().setUp() + self._publish_xls_form_to_project() + self._encrypt_xform(self.xform, self._create_kms_key(self.user)) + self.assertTrue(self._encrypted()) + self.assertTrue(self.xform.is_managed) + self.assertEqual(self.xform.num_of_submissions, 0) + + def _encrypted(self): + self.xform.refresh_from_db() + return self.xform.encrypted + + def test_disabling_encryption_is_challenged(self): + response = self._patch_form({"enable_kms_encryption": False}) + + self.assert_challenged(response) + self.assertTrue(self._encrypted()) + + def test_a_grant_lets_encryption_off(self): + grant = self._grant() + + response = self._patch_form( + {"enable_kms_encryption": False}, self._with_grant(grant) + ) + + self.assertEqual(response.status_code, 200, response.data) + self.assertFalse(self._encrypted()) + self.assert_spent(grant) + + def test_enabling_encryption_is_not_challenged(self): + self.assert_challenged(self._patch_form({"enable_kms_encryption": False})) + + response = self._patch_form({"enable_kms_encryption": True}) + + self.assertEqual(response.status_code, 200, response.data) + self.assertTrue(self._encrypted()) + + def test_a_form_with_submissions_is_not_challenged(self): + """Encryption stays on for a form with submissions, so the refusal + that follows must not cost the grant.""" + self.assert_challenged(self._patch_form({"enable_kms_encryption": False})) + XForm.objects.filter(pk=self.xform.pk).update(num_of_submissions=1) + grant = self._grant() + + response = self._patch_form( + {"enable_kms_encryption": False}, self._with_grant(grant) + ) + + self.assertEqual(response.status_code, 400, response.data) + self.assertIn("already has submissions", str(response.data)) + self.assert_unspent(grant) + self.assertTrue(self._encrypted()) + + +@gating(GATE_PUBLISH_DATA) +class TestMoveFormIntoPublicProjectGate(GateTestCase): + """A private form moved into a public project becomes public, data + included, so a stolen session must not be able to move it there.""" + + audience = GATE_PUBLISH_DATA + + def setUp(self): + super().setUp() + self._publish_xls_form_to_project() + self.private_project = self.project + self.assertFalse(self.xform.shared) + self.assertFalse(self.xform.shared_data) + self.public_project = self._public_project("open") + + def _public_project(self, name, owner_url=None): + extra = {"owner": owner_url} if owner_url else {} + self._project_create({"name": name, **extra}) + Project.objects.filter(pk=self.project.pk).update(shared=True) + self.project.refresh_from_db() + self.assertTrue(self.project.shared) + return self.project + + def _move(self, project, headers=None): + view = ProjectViewSet.as_view({"post": "forms"}) + request = self.factory.post( + "/", + data={"formid": self.xform.pk}, + **{**self.extra, **(headers or {})}, + ) + return view(request, pk=project.pk) + + def _reload(self): + self.xform.refresh_from_db() + + def test_moving_a_private_form_into_a_public_project_is_challenged(self): + response = self._move(self.public_project) + + self.assert_challenged(response) + self._reload() + self.assertEqual(self.xform.project, self.private_project) + self.assertFalse(self.xform.shared_data) + + def test_a_grant_lets_the_form_move(self): + grant = self._grant() + + response = self._move(self.public_project, self._with_grant(grant)) + + self.assertEqual(response.status_code, 201, response.data) + self._reload() + self.assertEqual(self.xform.project, self.public_project) + self.assertTrue(self.xform.shared_data) + self.assert_spent(grant) + + def test_moving_into_a_private_project_is_not_challenged(self): + self.assert_challenged(self._move(self.public_project)) + self._project_create({"name": "closed"}) + closed = self.project + self.assertFalse(closed.shared) + + response = self._move(closed) + + self.assertEqual(response.status_code, 201, response.data) + self._reload() + self.assertEqual(self.xform.project, closed) + self.assertFalse(self.xform.shared_data) + + def test_moving_a_public_form_is_not_challenged(self): + self.assert_challenged(self._move(self.public_project)) + XForm.objects.filter(pk=self.xform.pk).update(shared=True, shared_data=True) + + response = self._move(self.public_project) + + self.assertEqual(response.status_code, 201, response.data) + self._reload() + self.assertEqual(self.xform.project, self.public_project) + + def test_an_invalid_move_keeps_the_grant(self): + """The id_string check comes first, so a clash does not spend it.""" + self.assert_challenged(self._move(self.public_project)) + private_xform = self.xform + self._org_create() + org_url = f"http://testserver/api/v1/users/{self.organization.user.username}" + org_project = self._public_project("org open", owner_url=org_url) + self._publish_xls_form_to_project() + self.assertEqual(self.xform.id_string, private_xform.id_string) + self.xform = private_xform + grant = self._grant() + + response = self._move(org_project, self._with_grant(grant)) + + self.assertEqual(response.status_code, 400, response.data) + self.assert_unspent(grant) + self._reload() + self.assertEqual(self.xform.project, self.private_project) + self.assertFalse(self.xform.shared_data) + + def _patch_project(self, project, headers=None): + url = f"http://testserver/api/v1/projects/{project.pk}" + return self._patch_form({"project": url}, headers) + + def test_moving_by_update_into_a_public_project_is_challenged(self): + """The same account's public project, named in an update.""" + response = self._patch_project(self.public_project) + + self.assert_challenged(response) + self._reload() + self.assertEqual(self.xform.project, self.private_project) + + def test_a_grant_lets_the_update_move_the_form(self): + grant = self._grant() + + response = self._patch_project(self.public_project, self._with_grant(grant)) + + self.assertEqual(response.status_code, 200, response.data) + self._reload() + self.assertEqual(self.xform.project, self.public_project) + self.assert_spent(grant) + + def test_moving_by_update_into_a_private_project_is_not_challenged(self): + self.assert_challenged(self._patch_project(self.public_project)) + self._project_create({"name": "closed"}) + closed = self.project + self.assertFalse(closed.shared) + + response = self._patch_project(closed) + + self.assertEqual(response.status_code, 200, response.data) + self._reload() + self.assertEqual(self.xform.project, closed) + + +@gating(GATE_TRANSFER_PROJECT) +class TestMoveFormToAnotherAccountGate(GateTestCase): + """Moving a form into another account's project makes that account its + owner, data included, so a stolen session must not be able to do it.""" + + audience = GATE_TRANSFER_PROJECT + + def setUp(self): + super().setUp() + self._publish_xls_form_to_project() + self.own_project = self.project + self._org_create() + self.org_user = self.organization.user + self.org_url = f"http://testserver/api/v1/users/{self.org_user.username}" + self._project_create({"name": "org project", "owner": self.org_url}) + self.org_project = self.project + self.assertEqual(self.xform.user, self.user) + self.assertEqual(self.org_project.organization, self.org_user) + self.assertFalse(self.org_project.shared) + + def _move(self, project, headers=None): + view = ProjectViewSet.as_view({"post": "forms"}) + request = self.factory.post( + "/", + data={"formid": self.xform.pk}, + **{**self.extra, **(headers or {})}, + ) + return view(request, pk=project.pk) + + def test_moving_a_form_to_another_account_is_challenged(self): + """The 401 names the audience and the form stays where it was.""" + response = self._move(self.org_project) + + self.assert_challenged(response) + self.xform.refresh_from_db() + self.assertEqual(self.xform.project, self.own_project) + self.assertEqual(self.xform.user, self.user) + + def test_a_grant_lets_the_form_move(self): + """With a grant the other account owns the form.""" + grant = self._grant() + + response = self._move(self.org_project, self._with_grant(grant)) + + self.assertEqual(response.status_code, 201, response.data) + self.xform.refresh_from_db() + self.assertEqual(self.xform.project, self.org_project) + self.assertEqual(self.xform.user, self.org_user) + self.assert_spent(grant) + + def test_moving_within_the_account_is_not_challenged(self): + """The form keeps its owner, so nothing is handed over.""" + self.assert_challenged(self._move(self.org_project)) + self._project_create({"name": "closed"}) + closed = self.project + + response = self._move(closed) + + self.assertEqual(response.status_code, 201, response.data) + self.xform.refresh_from_db() + self.assertEqual(self.xform.project, closed) + self.assertEqual(self.xform.user, self.user) + + @staticmethod + def _project_url(project): + return f"http://testserver/api/v1/projects/{project.pk}" + + def test_changing_a_forms_owner_is_challenged(self): + """An update naming another owner is a transfer too.""" + response = self._patch_form({"owner": self.org_url}) + + self.assert_challenged(response) + self.xform.refresh_from_db() + self.assertEqual(self.xform.user, self.user) + + def test_moving_a_form_by_update_is_challenged(self): + """An update naming another account's project is a transfer too.""" + response = self._patch_form({"project": self._project_url(self.org_project)}) + + self.assert_challenged(response) + self.xform.refresh_from_db() + self.assertEqual(self.xform.project, self.own_project) + + def test_a_grant_lets_the_owner_change(self): + """With a grant the update hands the form over.""" + grant = self._grant() + + response = self._patch_form({"owner": self.org_url}, self._with_grant(grant)) + + self.assertEqual(response.status_code, 200, response.data) + self.xform.refresh_from_db() + self.assertEqual(self.xform.user, self.org_user) + self.assert_spent(grant) + + def test_moving_by_update_within_the_account_is_not_challenged(self): + """An update to another of the owner's projects hands nothing over.""" + self.assert_challenged(self._patch_form({"owner": self.org_url})) + self._project_create({"name": "closed"}) + closed = self.project + + response = self._patch_form({"project": self._project_url(closed)}) + + self.assertEqual(response.status_code, 200, response.data) + self.xform.refresh_from_db() + self.assertEqual(self.xform.project, closed) + self.assertEqual(self.xform.user, self.user) + + @gating(GATE_TRANSFER_PROJECT, GATE_PUBLISH_DATA) + def test_a_move_that_also_publishes_is_refused_whole(self): + """Into another account's public project is two gated changes.""" + Project.objects.filter(pk=self.org_project.pk).update(shared=True) + grant = self._grant() + + response = self._move(self.org_project, self._with_grant(grant)) + + self.assert_one_gated_change( + response, [GATE_TRANSFER_PROJECT, GATE_PUBLISH_DATA] + ) + self.assert_unspent(grant) + self.xform.refresh_from_db() + self.assertEqual(self.xform.project, self.own_project) + self.assertFalse(self.xform.shared_data) + + +@gating(GATE_PUBLISH_DATA) +class TestOpenDataLinkGate(GateTestCase): + """An open-data link reads a form's data without logging in, so a stolen + session must not be able to open one.""" + + audience = GATE_PUBLISH_DATA + + def setUp(self): + super().setUp() + self._publish_xls_form_to_project() + self.assertFalse(OpenData.objects.exists()) + + def _request(self, method, action, data, headers=None, **kwargs): + view = OpenDataViewSet.as_view({method: action}) + request = getattr(self.factory, method)( + "/", + data=json.dumps(data), + content_type="application/json", + **{**self.extra, **(headers or {})}, + ) + return view(request, **kwargs) + + def _create(self, headers=None, **data): + payload = { + "object_id": self.xform.pk, + "name": "tableau", + "data_type": "xform", + **data, + } + return self._request("post", "create", payload, headers) + + def _patch(self, open_data, data, headers=None): + return self._request( + "patch", "partial_update", data, headers, uuid=open_data.uuid + ) + + def _link(self, active=True): + open_data, _created = get_or_create_opendata(self.xform) + OpenData.objects.filter(pk=open_data.pk).update(active=active) + open_data.refresh_from_db() + self.assertEqual(open_data.active, active) + return open_data + + def test_creating_a_link_is_challenged(self): + response = self._create() + + self.assert_challenged(response) + self.assertFalse(OpenData.objects.exists()) + + def test_a_grant_lets_the_link_be_created(self): + grant = self._grant() + + response = self._create(self._with_grant(grant)) + + self.assertEqual(response.status_code, 201, response.data) + open_data = OpenData.objects.get() + self.assertTrue(open_data.active) + self.assertEqual(response.data["uuid"], open_data.uuid) + self.assert_spent(grant) + + def test_asking_for_an_existing_link_is_not_challenged(self): + self.assert_challenged(self._create()) + open_data = self._link() + + response = self._create() + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(response.data["uuid"], open_data.uuid) + self.assertEqual(OpenData.objects.count(), 1) + + def test_an_invalid_link_keeps_the_grant(self): + """Validation comes first, so an unsupported data type does not + spend it.""" + self.assert_challenged(self._create()) + grant = self._grant() + + response = self._create(self._with_grant(grant), data_type="dataview") + + self.assertEqual(response.status_code, 400) + self.assert_unspent(grant) + self.assertFalse(OpenData.objects.exists()) + + def test_reactivating_a_link_is_challenged(self): + open_data = self._link(active=False) + + response = self._patch(open_data, {"active": True}) + + self.assert_challenged(response) + open_data.refresh_from_db() + self.assertFalse(open_data.active) + + def test_a_grant_reactivates_the_link(self): + open_data = self._link(active=False) + grant = self._grant() + + response = self._patch(open_data, {"active": True}, self._with_grant(grant)) + + self.assertEqual(response.status_code, 200, response.data) + open_data.refresh_from_db() + self.assertTrue(open_data.active) + self.assert_spent(grant) + + def test_pointing_a_link_at_another_form_is_challenged(self): + open_data = self._link() + first_form = self.xform + self._publish_xls_form_to_project( + xlsform_path=os.path.join( + settings.PROJECT_ROOT, + "libs", + "tests", + "utils", + "fixtures", + "hxl_example", + "hxl_example.xlsx", + ) + ) + self.assertNotEqual(self.xform.pk, first_form.pk) + + response = self._patch(open_data, {"object_id": self.xform.pk}) + + self.assert_challenged(response) + open_data.refresh_from_db() + self.assertEqual(open_data.object_id, first_form.pk) + + def test_deactivating_a_link_is_not_challenged(self): + open_data = self._link(active=False) + self.assert_challenged(self._patch(open_data, {"active": True})) + OpenData.objects.filter(pk=open_data.pk).update(active=True) + + response = self._patch(open_data, {"active": False}) + + self.assertEqual(response.status_code, 200, response.data) + open_data.refresh_from_db() + self.assertFalse(open_data.active) + + def test_renaming_an_active_link_is_not_challenged(self): + open_data = self._link(active=False) + self.assert_challenged(self._patch(open_data, {"active": True})) + OpenData.objects.filter(pk=open_data.pk).update(active=True) + + response = self._patch(open_data, {"name": "renamed", "active": True}) + + self.assertEqual(response.status_code, 200, response.data) + open_data.refresh_from_db() + self.assertEqual(open_data.name, "renamed") + self.assertTrue(open_data.active) + + def test_an_invalid_reactivation_keeps_the_grant(self): + """Validation comes first, so an unsupported data type does not + spend it.""" + open_data = self._link(active=False) + self.assert_challenged(self._patch(open_data, {"active": True})) + grant = self._grant() + + response = self._patch( + open_data, + {"active": True, "data_type": "dataview"}, + self._with_grant(grant), + ) + + self.assertEqual(response.status_code, 400) + self.assert_unspent(grant) + open_data.refresh_from_db() + self.assertFalse(open_data.active) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_form_move_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_form_move_gates.py new file mode 100644 index 0000000000..27fecdab36 --- /dev/null +++ b/onadata/apps/api/tests/viewsets/test_stepup_form_move_gates.py @@ -0,0 +1,143 @@ +# -*- coding: utf-8 -*- +""" +Tests for the step-up gate on moving a form whose meta permissions can make +the destination project's users its admins. +""" + +from oidc.stepup_grants import issue_grant, spend_grant + +from onadata.apps.api.tests.viewsets.test_stepup_form_and_transfer_gates import ( + GateTestCase, +) +from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import ( + EDITOR_BECOMES_OWNER, + gating, +) +from onadata.apps.api.viewsets.project_viewset import ProjectViewSet +from onadata.libs.permissions import EditorRole, ManagerRole, OwnerRole +from onadata.libs.stepup.policy import GATE_SHARE_FORM_ADMIN, GATE_TRANSFER_PROJECT + + +@gating(GATE_SHARE_FORM_ADMIN) +class TestMoveFormWithAdminMetaPermsGate(GateTestCase): + """A move gives the form the new project's roles and then applies its + meta permissions, so an editor of that project can become the form's + owner.""" + + audience = GATE_SHARE_FORM_ADMIN + + def setUp(self): + super().setUp() + self._publish_xls_form_to_project() + self.first_project = self.project + self._project_create({"name": "second"}) + self.second_project = self.project + self.assertEqual(self.second_project.organization, self.xform.user) + self.alice = self._create_user("alice", "alice", create_profile=True) + EditorRole.add(self.alice, self.second_project) + + def _move(self, headers=None): + view = ProjectViewSet.as_view({"post": "forms"}) + request = self.factory.post( + "/", + data={"formid": self.xform.pk}, + **{**self.extra, **(headers or {})}, + ) + return view(request, pk=self.second_project.pk) + + def _move_alice_into_an_org_project(self): + """Make the move's destination a project of another account, which + alice edits.""" + self._org_create() + org_url = f"http://testserver/api/v1/users/{self.organization.user.username}" + self._project_create({"name": "org", "owner": org_url}) + self.second_project = self.project + self.assertNotEqual(self.second_project.organization, self.xform.user) + EditorRole.add(self.alice, self.second_project) + + def _project_of_the_form(self): + self.xform.refresh_from_db() + return self.xform.project + + def test_a_move_that_makes_an_editor_owner_is_challenged(self): + """The 401 names the audience and the form stays where it was.""" + self._set_meta_perms(EDITOR_BECOMES_OWNER) + + response = self._move() + + self.assert_challenged(response) + self.assertEqual(self._project_of_the_form(), self.first_project) + + def test_a_grant_lets_the_form_move(self): + self._set_meta_perms(EDITOR_BECOMES_OWNER) + grant = self._grant() + + response = self._move(self._with_grant(grant)) + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(self._project_of_the_form(), self.second_project) + self.assertTrue(OwnerRole.user_has_role(self.alice, self.xform)) + self.assert_spent(grant) + + def test_the_default_meta_perms_are_not_challenged(self): + """The default meta permissions leave the project's editors + editors.""" + self._set_meta_perms(EDITOR_BECOMES_OWNER) + self.assert_challenged(self._move()) + self._set_meta_perms("editor|dataentry|readonly") + + response = self._move() + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(self._project_of_the_form(), self.second_project) + + def test_a_project_admin_is_not_counted(self): + """A manager of the project already manages every form moved into + it, so the meta permissions appoint nobody new.""" + self._set_meta_perms(EDITOR_BECOMES_OWNER) + self.assert_challenged(self._move()) + ManagerRole.add(self.alice, self.second_project) + + response = self._move() + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(self._project_of_the_form(), self.second_project) + + def test_a_move_to_another_account_is_challenged_where_only_this_is_gated(self): + """Without a transfer gate to cover it, a move into another account + that makes an editor there the form's owner is challenged as well.""" + self._set_meta_perms(EDITOR_BECOMES_OWNER) + self._move_alice_into_an_org_project() + + response = self._move() + + self.assert_challenged(response) + self.assertEqual(self._project_of_the_form(), self.first_project) + + @gating(GATE_TRANSFER_PROJECT, GATE_SHARE_FORM_ADMIN) + def test_a_transfer_grant_covers_the_admins_a_move_appoints(self): + """Where transfers are gated, a move into another account asks for + the transfer grant alone rather than refusing two gated changes.""" + self._set_meta_perms(EDITOR_BECOMES_OWNER) + self._move_alice_into_an_org_project() + + response = self._move() + + self.assertEqual(response.status_code, 401, response.data) + self.assertEqual(response.data["audience"], GATE_TRANSFER_PROJECT) + self.assertEqual(self._project_of_the_form(), self.first_project) + + @gating(GATE_TRANSFER_PROJECT, GATE_SHARE_FORM_ADMIN) + def test_the_transfer_grant_alone_lets_the_move_through(self): + """With the transfer grant the form moves and its meta permissions + make alice its owner.""" + self._set_meta_perms(EDITOR_BECOMES_OWNER) + self._move_alice_into_an_org_project() + grant = issue_grant(self.user.pk, GATE_TRANSFER_PROJECT) + + response = self._move({"HTTP_X_STEP_UP_GRANT": grant}) + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(self._project_of_the_form(), self.second_project) + self.assertTrue(OwnerRole.user_has_role(self.alice, self.xform)) + self.assertFalse(spend_grant(self.user.pk, GATE_TRANSFER_PROJECT, grant)) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_merged_xform_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_merged_xform_gates.py new file mode 100644 index 0000000000..36d1719ca0 --- /dev/null +++ b/onadata/apps/api/tests/viewsets/test_stepup_merged_xform_gates.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +""" +Tests for the step-up gates on creating a merged dataset, which publishes its +source forms' data in a public project and hands it to the account that owns +the project. +""" + +from onadata.apps.api.tests.viewsets.test_merged_xform_viewset import MD +from onadata.apps.api.tests.viewsets.test_stepup_form_and_transfer_gates import ( + GateTestCase, +) +from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import gating +from onadata.apps.api.viewsets.merged_xform_viewset import MergedXFormViewSet +from onadata.apps.logger.models import MergedXForm, Project +from onadata.libs.stepup.policy import GATE_PUBLISH_DATA, GATE_TRANSFER_PROJECT +from onadata.libs.utils.user_auth import get_user_default_project + + +class MergedXFormGateTestCase(GateTestCase): + """Two private forms in the user's own project, ready to merge.""" + + def setUp(self): + super().setUp() + # pylint: disable=attribute-defined-outside-init + self.project = self.own_project = get_user_default_project(self.user) + self.xform_a = self._publish_markdown(MD, self.user, id_string="a") + self.xform_b = self._publish_markdown(MD, self.user, id_string="b") + for xform in (self.xform_a, self.xform_b): + self.assertEqual(xform.user, self.user) + self.assertFalse(xform.shared_data) + + def _merge(self, project, headers=None): + view = MergedXFormViewSet.as_view({"post": "create"}) + data = { + "xforms": [ + f"http://testserver/api/v1/forms/{xform.pk}" + for xform in (self.xform_a, self.xform_b) + ], + "name": "Merged Dataset", + "project": f"http://testserver/api/v1/projects/{project.pk}", + } + request = self.factory.post("/", data=data, **{**self.extra, **(headers or {})}) + return view(request) + + @staticmethod + def _set_public(project, shared): + Project.objects.filter(pk=project.pk).update(shared=shared) + project.refresh_from_db() + + +@gating(GATE_PUBLISH_DATA) +class TestMergeIntoPublicProjectGate(MergedXFormGateTestCase): + """A merged dataset in a public project is public, so merging private + forms there publishes their data.""" + + audience = GATE_PUBLISH_DATA + + def setUp(self): + super().setUp() + self._set_public(self.own_project, True) + + def test_merging_private_forms_into_a_public_project_is_challenged(self): + """The 401 names the audience and no merged dataset is made.""" + response = self._merge(self.own_project) + + self.assert_challenged(response) + self.assertFalse(MergedXForm.objects.exists()) + + def test_a_grant_lets_the_merge_through(self): + """With a grant the merged dataset is made in the public project.""" + grant = self._grant() + + response = self._merge(self.own_project, self._with_grant(grant)) + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual( + MergedXForm.objects.get(pk=response.data["id"]).project, + self.own_project, + ) + self.assert_spent(grant) + + def test_merging_into_a_private_project_is_not_challenged(self): + """A private project publishes nothing.""" + self.assert_challenged(self._merge(self.own_project)) + self._set_public(self.own_project, False) + + response = self._merge(self.own_project) + + self.assertEqual(response.status_code, 201, response.data) + self.assertTrue(MergedXForm.objects.filter(pk=response.data["id"]).exists()) + + def test_an_invalid_merge_keeps_the_grant(self): + """Validation comes first, so a single form does not spend it.""" + self.assert_challenged(self._merge(self.own_project)) + grant = self._grant() + self.xform_b = self.xform_a + + response = self._merge(self.own_project, self._with_grant(grant)) + + self.assertEqual(response.status_code, 400, response.data) + self.assert_unspent(grant) + self.assertFalse(MergedXForm.objects.exists()) + + +@gating(GATE_TRANSFER_PROJECT) +class TestMergeIntoAnotherAccountGate(MergedXFormGateTestCase): + """A merged dataset belongs to its project's account, whose admins read + the source forms' data through it, so merging into another account's + project hands that data over.""" + + audience = GATE_TRANSFER_PROJECT + + def setUp(self): + super().setUp() + self._org_create() + org_url = f"http://testserver/api/v1/users/{self.organization.user.username}" + self._project_create({"name": "org project", "owner": org_url}) + self.org_project = self.project + self.assertEqual(self.org_project.organization, self.organization.user) + self.assertFalse(self.org_project.shared) + + def test_merging_into_another_accounts_project_is_challenged(self): + """The 401 names the audience and no merged dataset is made.""" + response = self._merge(self.org_project) + + self.assert_challenged(response) + self.assertFalse(MergedXForm.objects.exists()) + + def test_a_grant_lets_the_merge_through(self): + """With a grant the merged dataset is made in the other account.""" + grant = self._grant() + + response = self._merge(self.org_project, self._with_grant(grant)) + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual( + MergedXForm.objects.get(pk=response.data["id"]).project, + self.org_project, + ) + self.assert_spent(grant) + + def test_merging_within_the_account_is_not_challenged(self): + """The forms' own account keeps their data.""" + self.assert_challenged(self._merge(self.org_project)) + + response = self._merge(self.own_project) + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual( + MergedXForm.objects.get(pk=response.data["id"]).project, + self.own_project, + ) + + @gating(GATE_TRANSFER_PROJECT, GATE_PUBLISH_DATA) + def test_a_merge_that_also_publishes_is_refused_whole(self): + """Into another account's public project is two gated changes.""" + self._set_public(self.org_project, True) + grant = self._grant() + + response = self._merge(self.org_project, self._with_grant(grant)) + + self.assert_one_gated_change( + response, [GATE_TRANSFER_PROJECT, GATE_PUBLISH_DATA] + ) + self.assert_unspent(grant) + self.assertFalse(MergedXForm.objects.exists()) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py new file mode 100644 index 0000000000..88131485ef --- /dev/null +++ b/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py @@ -0,0 +1,326 @@ +# -*- coding: utf-8 -*- +""" +Tests for the step-up gates on form metadata that grants roles, publishes a +form, or says where TextIt posts submissions. +""" + +from onadata.apps.api.tests.viewsets.test_stepup_form_and_transfer_gates import ( + GateTestCase, +) +from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import ( + EDITOR_BECOMES_MANAGER, + EDITOR_BECOMES_OWNER, + EDITOR_STAYS_BELOW_ADMIN, + gating, +) +from onadata.apps.api.viewsets.metadata_viewset import MetaDataViewSet +from onadata.apps.main.models import MetaData +from onadata.libs.permissions import ( + EditorMinorRole, + EditorRole, + ManagerRole, + OwnerRole, +) +from onadata.libs.serializers.metadata_serializer import ( + create_xform_meta_permissions, +) +from onadata.libs.stepup.policy import ( + GATE_CHANGE_WEBHOOK, + GATE_PUBLISH_DATA, + GATE_SHARE_FORM_ADMIN, +) +from onadata.libs.utils.common_tags import TEXTIT, XFORM_META_PERMS + +DEFAULT_META_PERMS = "editor|dataentry|readonly" +TEXTIT_SETTINGS = "token|flow-uuid|contact-uuid" +OTHER_TEXTIT_SETTINGS = "other-token|flow-uuid|contact-uuid" + + +class MetaDataGateTestCase(GateTestCase): + """A published form and requests against its metadata.""" + + def setUp(self): + super().setUp() + self._publish_xls_form_to_project() + + def _create(self, data_type, data_value, headers=None): + view = MetaDataViewSet.as_view({"post": "create"}) + data = { + "data_type": data_type, + "data_value": data_value, + "xform": self.xform.pk, + } + request = self.factory.post("/", data=data, **{**self.extra, **(headers or {})}) + return view(request) + + def _update(self, metadata, data, headers=None, method="put"): + view = MetaDataViewSet.as_view({"put": "update", "patch": "partial_update"}) + request = getattr(self.factory, method)( + "/", + data={"xform": self.xform.pk, **data}, + **{**self.extra, **(headers or {})}, + ) + return view(request, pk=metadata.pk) + + +@gating(GATE_SHARE_FORM_ADMIN) +class TestMetaPermsGate(MetaDataGateTestCase): + """Meta permissions give a form's editors the role in their slot, so a + stolen session must not be able to name owner or manager there.""" + + audience = GATE_SHARE_FORM_ADMIN + + def setUp(self): + super().setUp() + self.alice = self._create_user_profile( + {"username": "alice", "email": "alice@localhost.com"} + ).user + EditorRole.add(self.alice, self.xform) + # Publishing gives every form this row, so a create updates it. + self.assertEqual(self._meta_perms().data_value, DEFAULT_META_PERMS) + + def _meta_perms(self): + return MetaData.xform_meta_permission(self.xform) + + def test_naming_owner_in_a_slot_is_challenged(self): + """The 401 names the audience, nothing is stored and the editor + stays an editor.""" + response = self._create(XFORM_META_PERMS, EDITOR_BECOMES_OWNER) + + self.assert_challenged(response) + self.assertEqual(self._meta_perms().data_value, DEFAULT_META_PERMS) + self.assertFalse(OwnerRole.user_has_role(self.alice, self.xform)) + + def test_a_grant_makes_the_editor_an_owner(self): + """With a grant the meta permissions are stored and applied.""" + grant = self._grant() + + response = self._create( + XFORM_META_PERMS, EDITOR_BECOMES_OWNER, self._with_grant(grant) + ) + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(self._meta_perms().data_value, EDITOR_BECOMES_OWNER) + self.assertTrue(OwnerRole.user_has_role(self.alice, self.xform)) + self.assert_spent(grant) + + def test_meta_perms_without_an_admin_slot_are_not_challenged(self): + """No slot names owner or manager, so nobody becomes an admin.""" + self.assert_challenged(self._create(XFORM_META_PERMS, EDITOR_BECOMES_OWNER)) + + response = self._create(XFORM_META_PERMS, EDITOR_STAYS_BELOW_ADMIN) + + self.assertEqual(response.status_code, 201, response.data) + self.assertTrue(EditorMinorRole.user_has_role(self.alice, self.xform)) + self.assertFalse(OwnerRole.user_has_role(self.alice, self.xform)) + + def test_raising_a_slot_to_owner_is_challenged(self): + """An update is gated too, and a manager slot raised to owner + appoints owners.""" + metadata = MetaData.xform_meta_permission( + self.xform, data_value=EDITOR_BECOMES_MANAGER + ) + + response = self._update( + metadata, {"data_value": EDITOR_BECOMES_OWNER}, method="patch" + ) + + self.assert_challenged(response) + metadata.refresh_from_db() + self.assertEqual(metadata.data_value, EDITOR_BECOMES_MANAGER) + + def test_keeping_an_admin_slot_is_not_challenged(self): + """Writing back a slot that already names manager, applied to every + editor, appoints nobody new.""" + applied_admin_slot = "manager|dataentry|readonly" + metadata = create_xform_meta_permissions(applied_admin_slot, self.xform) + self.assertTrue(ManagerRole.user_has_role(self.alice, self.xform)) + self.assert_challenged( + self._update(metadata, {"data_value": EDITOR_BECOMES_OWNER}, method="patch") + ) + + response = self._update( + metadata, + {"data_type": XFORM_META_PERMS, "data_value": applied_admin_slot}, + ) + + self.assertEqual(response.status_code, 200, response.data) + metadata.refresh_from_db() + self.assertEqual(metadata.data_value, applied_admin_slot) + self.assertFalse(OwnerRole.user_has_role(self.alice, self.xform)) + + def test_writing_back_a_slot_that_promotes_an_editor_is_challenged(self): + """Every write applies the value to all the form's users, so an + unchanged one still appoints an editor it has not reached yet.""" + unapplied_admin_slot = "manager|dataentry|readonly" + metadata = MetaData.xform_meta_permission( + self.xform, data_value=unapplied_admin_slot + ) + self.assertFalse(ManagerRole.user_has_role(self.alice, self.xform)) + + response = self._update( + metadata, + {"data_type": XFORM_META_PERMS, "data_value": unapplied_admin_slot}, + ) + + self.assert_challenged(response) + self.assertFalse(ManagerRole.user_has_role(self.alice, self.xform)) + + def test_a_grant_lets_a_promoting_write_back_through(self): + """With a grant the unchanged value is applied and the editor becomes + a manager.""" + unapplied_admin_slot = "manager|dataentry|readonly" + metadata = MetaData.xform_meta_permission( + self.xform, data_value=unapplied_admin_slot + ) + grant = self._grant() + + response = self._update( + metadata, + {"data_type": XFORM_META_PERMS, "data_value": unapplied_admin_slot}, + self._with_grant(grant), + ) + + self.assertEqual(response.status_code, 200, response.data) + self.assertTrue(ManagerRole.user_has_role(self.alice, self.xform)) + self.assert_spent(grant) + + def test_an_invalid_value_keeps_the_grant(self): + """Validation comes first, so a malformed value does not spend it.""" + self.assert_challenged(self._create(XFORM_META_PERMS, EDITOR_BECOMES_OWNER)) + grant = self._grant() + + response = self._create( + XFORM_META_PERMS, "owner|not-a-role", self._with_grant(grant) + ) + + self.assertEqual(response.status_code, 400, response.data) + self.assert_unspent(grant) + self.assertEqual(self._meta_perms().data_value, DEFAULT_META_PERMS) + + +@gating(GATE_PUBLISH_DATA) +class TestPublicLinkGate(MetaDataGateTestCase): + """A public link lets anyone holding it read the form, so a stolen session + must not be able to turn one on.""" + + audience = GATE_PUBLISH_DATA + + def setUp(self): + super().setUp() + self.assertFalse(MetaData.public_link(self.xform)) + + def test_turning_on_a_public_link_is_challenged(self): + """The 401 names the audience and the link stays off.""" + response = self._create("public_link", "True") + + self.assert_challenged(response) + self.assertFalse(MetaData.public_link(self.xform)) + + def test_a_grant_turns_the_link_on(self): + """With a grant the link is on.""" + grant = self._grant() + + response = self._create("public_link", "True", self._with_grant(grant)) + + self.assertEqual(response.status_code, 201, response.data) + self.assertTrue(MetaData.public_link(self.xform)) + self.assert_spent(grant) + + def test_turning_a_link_on_by_update_is_challenged(self): + """An update that flips an off link on is gated too.""" + MetaData.public_link(self.xform, False) + metadata = MetaData.objects.get(data_type="public_link") + + response = self._update( + metadata, {"data_type": "public_link", "data_value": "True"} + ) + + self.assert_challenged(response) + metadata.refresh_from_db() + self.assertEqual(metadata.data_value, "False") + + def test_turning_a_link_off_is_not_challenged(self): + """Withdrawing the link publishes nothing.""" + self.assert_challenged(self._create("public_link", "True")) + + response = self._create("public_link", "False") + + self.assertEqual(response.status_code, 201, response.data) + self.assertFalse(MetaData.public_link(self.xform)) + + def test_rewriting_an_on_link_is_not_challenged(self): + """A link that is already on publishes nothing new.""" + MetaData.public_link(self.xform, False) + metadata = MetaData.objects.get(data_type="public_link") + self.assert_challenged( + self._update(metadata, {"data_type": "public_link", "data_value": "True"}) + ) + MetaData.public_link(self.xform, True) + self.assertTrue(MetaData.public_link(self.xform)) + + response = self._update( + metadata, {"data_type": "public_link", "data_value": "True"} + ) + + self.assertEqual(response.status_code, 200, response.data) + self.assertTrue(MetaData.public_link(self.xform)) + + +@gating(GATE_CHANGE_WEBHOOK) +class TestTextItSettingsGate(MetaDataGateTestCase): + """A form's TextIt service posts submissions with the token and contacts + in its metadata, the same reach the webhook gate protects.""" + + audience = GATE_CHANGE_WEBHOOK + + def setUp(self): + super().setUp() + self.assertIsNone(MetaData.textit(self.xform)) + + def test_setting_textit_is_challenged(self): + """The 401 names the audience and nothing is stored.""" + response = self._create(TEXTIT, TEXTIT_SETTINGS) + + self.assert_challenged(response) + self.assertIsNone(MetaData.textit(self.xform)) + + def test_a_grant_lets_textit_be_set(self): + """With a grant the settings are stored.""" + grant = self._grant() + + response = self._create(TEXTIT, TEXTIT_SETTINGS, self._with_grant(grant)) + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(MetaData.textit(self.xform), TEXTIT_SETTINGS) + self.assert_spent(grant) + + def test_changing_textit_is_challenged(self): + """An update to other settings is gated and leaves them as they + were.""" + MetaData.textit(self.xform, data_value=TEXTIT_SETTINGS) + metadata = MetaData.objects.get(data_type=TEXTIT) + + response = self._update( + metadata, {"data_type": TEXTIT, "data_value": OTHER_TEXTIT_SETTINGS} + ) + + self.assert_challenged(response) + self.assertEqual(MetaData.textit(self.xform), TEXTIT_SETTINGS) + + def test_writing_back_the_same_settings_is_not_challenged(self): + """Unchanged settings send nothing anywhere new.""" + MetaData.textit(self.xform, data_value=TEXTIT_SETTINGS) + metadata = MetaData.objects.get(data_type=TEXTIT) + self.assert_challenged( + self._update( + metadata, {"data_type": TEXTIT, "data_value": OTHER_TEXTIT_SETTINGS} + ) + ) + + response = self._update( + metadata, {"data_type": TEXTIT, "data_value": TEXTIT_SETTINGS} + ) + + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(MetaData.textit(self.xform), TEXTIT_SETTINGS) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py new file mode 100644 index 0000000000..638cc6db6c --- /dev/null +++ b/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py @@ -0,0 +1,422 @@ +# -*- coding: utf-8 -*- +""" +Tests for the step-up gates on an organisation's require_auth, its owner and +manager roles, and its encryption key. +""" + +from unittest.mock import patch + +from django.contrib.contenttypes.models import ContentType + +from oidc.stepup_grants import issue_grant, spend_grant + +from onadata.apps.api.models.organization_profile import ( + OrganizationProfile, + get_organization_members_team, +) +from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import ( + EDITOR_BECOMES_OWNER, + StepUpGateTestCase, + gating, +) +from onadata.apps.api.tools import get_organization_members +from onadata.apps.api.viewsets.organization_profile_viewset import ( + OrganizationProfileViewSet, +) +from onadata.apps.api.viewsets.v2.organization_profile_viewset import ( + OrganizationProfileViewSet as OrganizationProfileViewSetV2, +) +from onadata.apps.logger.models.kms import KMSKey +from onadata.libs.models.share_team_project import ShareTeamProject +from onadata.libs.permissions import ( + EditorRole, + ManagerRole, + OwnerRole, + get_team_project_default_permissions, +) + + +@gating("require-auth-toggle") +class TestOrganisationRequireAuthGate(StepUpGateTestCase): + """An organisation's profile is a UserProfile, so its require_auth is the + same column the personal profile gates.""" + + def setUp(self): + super().setUp() + self._org_create() + + def _patch_org(self, data, headers=None): + view = OrganizationProfileViewSet.as_view({"patch": "partial_update"}) + request = self.factory.patch( + "/", data=data, format="json", **{**self.extra, **(headers or {})} + ) + return view(request, user="denoinc") + + def _require_auth(self): + return OrganizationProfile.objects.get(user__username="denoinc").require_auth + + def test_toggling_require_auth_is_challenged(self): + self.assertFalse(self._require_auth()) + + response = self._patch_org({"require_auth": True}) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "require-auth-toggle") + self.assertFalse(self._require_auth()) + + def test_a_grant_lets_the_toggle_through(self): + grant = issue_grant(self.user.pk, "require-auth-toggle") + + response = self._patch_org( + {"require_auth": True}, {"HTTP_X_STEP_UP_GRANT": grant} + ) + + self.assertEqual(response.status_code, 200) + self.assertTrue(self._require_auth()) + + def test_other_changes_are_not_challenged(self): + self.assertEqual(self._patch_org({"require_auth": True}).status_code, 401) + + response = self._patch_org({"name": "Dennis Inc", "require_auth": False}) + + self.assertEqual(response.status_code, 200) + self.assertEqual( + OrganizationProfile.objects.get(user__username="denoinc").name, + "Dennis Inc", + ) + + def test_an_invalid_sibling_field_keeps_the_grant(self): + """The whole request is validated before the gate, so a field the + write would reject answers 400 and leaves the grant for the retry.""" + grant = issue_grant(self.user.pk, "require-auth-toggle") + + response = self._patch_org( + {"require_auth": True, "name": "x" * 31}, {"HTTP_X_STEP_UP_GRANT": grant} + ) + + self.assertEqual(response.status_code, 400) + self.assertIn("name", response.data) + self.assertFalse(self._require_auth()) + self.assertTrue(spend_grant(self.user.pk, "require-auth-toggle", grant)) + + def test_a_form_put_omitting_require_auth_is_gated(self): + """A form-encoded PUT that leaves out a boolean writes it as false, so + omitting the checkbox switches the setting off. + + The request renames the organisation. validate_org refuses the current + name, and the request must otherwise be valid to reach the gate. + """ + organization = OrganizationProfile.objects.get(user__username="denoinc") + organization.require_auth = True + organization.save() + view = OrganizationProfileViewSet.as_view({"put": "update"}) + + request = self.factory.put( + "/", + data={ + "org": "denoinc-renamed", + "name": "Dennis", + "email": "mail@mail-server.org", + }, + format="multipart", + **self.extra, + ) + response = view(request, user="denoinc") + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "require-auth-toggle") + self.assertTrue(self._require_auth()) + + +@gating("grant-org-admin") +class TestOrganisationAdminRoleGate(StepUpGateTestCase): + """An owner or manager can change every gated setting of the + organisation with their own factor, so a stolen session must not be able + to appoint one.""" + + def setUp(self): + super().setUp() + self._org_create() + self.alice = self._create_user("alice", "alice", create_profile=True) + self.assertNotEqual(self.alice, self.user) + self.assertFalse(OwnerRole.user_has_role(self.alice, self.organization)) + self.assertFalse(ManagerRole.user_has_role(self.alice, self.organization)) + + # pylint: disable=too-many-arguments,too-many-positional-arguments + def _member_request( + self, + method, + role, + headers=None, + username="alice", + viewset=OrganizationProfileViewSet, + ): + view = viewset.as_view({method: "members"}) + request = getattr(self.factory, method)( + "/", + data={"username": username, "role": role}, + format="json", + **{**self.extra, **(headers or {})}, + ) + return view(request, user="denoinc") + + def _add_member(self, role, headers=None): + return self._member_request("post", role, headers) + + def _make_alice(self, role=None): + self._add_user_to_organization(self.organization, self.alice, role) + self.assertIn(self.alice, get_organization_members(self.organization)) + + def test_appointing_an_owner_is_challenged(self): + response = self._add_member("owner") + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "grant-org-admin") + self.assertFalse(OwnerRole.user_has_role(self.alice, self.organization)) + + def test_a_grant_lets_the_owner_through(self): + grant = issue_grant(self.user.pk, "grant-org-admin") + + response = self._add_member("owner", {"HTTP_X_STEP_UP_GRANT": grant}) + + self.assertEqual(response.status_code, 201) + self.assertTrue(OwnerRole.user_has_role(self.alice, self.organization)) + + def test_other_roles_are_not_challenged(self): + self.assertEqual(self._add_member("owner").status_code, 401) + + response = self._add_member("editor") + + self.assertEqual(response.status_code, 201) + self.assertIn(self.alice, get_organization_members(self.organization)) + self.assertFalse(OwnerRole.user_has_role(self.alice, self.organization)) + + def test_appointing_a_manager_through_v2_is_challenged(self): + response = self._member_request( + "post", "manager", viewset=OrganizationProfileViewSetV2 + ) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "grant-org-admin") + self.assertFalse(ManagerRole.user_has_role(self.alice, self.organization)) + + def test_re_appointing_an_owner_is_not_challenged(self): + self.assertEqual(self._add_member("owner").status_code, 401) + self._make_alice("owner") + self.assertTrue(OwnerRole.user_has_role(self.alice, self.organization)) + + response = self._add_member("owner") + + self.assertEqual(response.status_code, 201) + self.assertTrue(OwnerRole.user_has_role(self.alice, self.organization)) + + def test_demoting_an_owner_to_manager_is_not_challenged(self): + self.assertEqual(self._add_member("owner").status_code, 401) + self._make_alice("owner") + self.assertTrue(OwnerRole.user_has_role(self.alice, self.organization)) + + response = self._member_request("put", "manager") + + self.assertEqual(response.status_code, 200) + self.assertTrue(ManagerRole.user_has_role(self.alice, self.organization)) + self.assertFalse(OwnerRole.user_has_role(self.alice, self.organization)) + + def test_an_unknown_username_keeps_the_grant(self): + """The username is validated first, so a typo does not spend it.""" + grant = issue_grant(self.user.pk, "grant-org-admin") + + response = self._member_request( + "post", "owner", {"HTTP_X_STEP_UP_GRANT": grant}, username="nobody" + ) + + self.assertEqual(response.status_code, 400) + self.assertTrue(spend_grant(self.user.pk, "grant-org-admin", grant)) + + def test_promoting_a_member_to_owner_through_v1_put_is_challenged(self): + self._make_alice() + + response = self._member_request("put", "owner") + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "grant-org-admin") + self.assertFalse(OwnerRole.user_has_role(self.alice, self.organization)) + + def test_a_grant_lets_the_owner_through_v2(self): + grant = issue_grant(self.user.pk, "grant-org-admin") + + response = self._member_request( + "post", + "owner", + {"HTTP_X_STEP_UP_GRANT": grant}, + viewset=OrganizationProfileViewSetV2, + ) + + self.assertEqual(response.status_code, 201) + self.assertTrue(OwnerRole.user_has_role(self.alice, self.organization)) + + +@gating("share-team-admin") +class TestOrganisationMembersTeamGate(StepUpGateTestCase): + """Adding a member shares every organisation project with them at the + members team's role, and each form's meta permissions can turn that role + into owner.""" + + def setUp(self): + super().setUp() + self._org_create() + org_url = f"http://testserver/api/v1/users/{self.organization.user.username}" + self._project_create({"owner": org_url}) + members_team = get_organization_members_team(self.organization) + ShareTeamProject(members_team, self.project, EditorRole.name).save() + self._publish_xls_form_to_project() + self.assertEqual(self.xform.user, self.organization.user) + self.alice = self._create_user("alice", "alice", create_profile=True) + + def _add_member(self, headers=None): + view = OrganizationProfileViewSet.as_view({"post": "members"}) + request = self.factory.post( + "/", + data={"username": "alice", "role": "editor"}, + format="json", + **{**self.extra, **(headers or {})}, + ) + return view(request, user=self.organization.user.username) + + def _alice_owns_the_form(self): + return OwnerRole.user_has_role(self.alice, self.xform) + + def test_adding_a_member_meta_perms_make_an_owner_is_challenged(self): + """The 401 names the audience and leaves the user out.""" + self._set_meta_perms(EDITOR_BECOMES_OWNER) + + response = self._add_member() + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "share-team-admin") + self.assertNotIn(self.alice, get_organization_members(self.organization)) + self.assertFalse(self._alice_owns_the_form()) + + def test_a_grant_lets_the_member_join(self): + """With a grant the member joins and the meta permissions make them + the form's owner.""" + self._set_meta_perms(EDITOR_BECOMES_OWNER) + grant = issue_grant(self.user.pk, "share-team-admin") + + response = self._add_member({"HTTP_X_STEP_UP_GRANT": grant}) + + self.assertEqual(response.status_code, 201) + self.assertIn(self.alice, get_organization_members(self.organization)) + self.assertTrue(self._alice_owns_the_form()) + self.assertFalse(spend_grant(self.user.pk, "share-team-admin", grant)) + + def test_adding_an_existing_member_again_is_challenged(self): + """Adding a member again shares every project with them again.""" + self.assertEqual(self._add_member().status_code, 201) + self._set_meta_perms(EDITOR_BECOMES_OWNER) + self.assertFalse(self._alice_owns_the_form()) + + response = self._add_member() + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "share-team-admin") + self.assertFalse(self._alice_owns_the_form()) + + def test_adding_a_member_who_holds_every_shared_role_is_not_challenged(self): + """Once the meta permissions have made a member the form's owner, + adding them again hands out nothing new.""" + self._set_meta_perms(EDITOR_BECOMES_OWNER) + self.assertEqual(self._add_member().status_code, 401) + grant = issue_grant(self.user.pk, "share-team-admin") + self._add_member({"HTTP_X_STEP_UP_GRANT": grant}) + self.assertTrue(self._alice_owns_the_form()) + + response = self._add_member() + + self.assertEqual(response.status_code, 201) + + def test_joining_a_members_team_with_a_promoting_form_role_is_challenged(self): + """A role the members team holds on a form, outside any project + share, counts too once the form's meta permissions apply.""" + members_team = get_organization_members_team(self.organization) + ShareTeamProject( + members_team, self.project, EditorRole.name, remove=True + ).save() + self.assertEqual( + get_team_project_default_permissions(members_team, self.project), "" + ) + EditorRole.add(members_team, self.xform) + self._set_meta_perms(EDITOR_BECOMES_OWNER) + + response = self._add_member() + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "share-team-admin") + self.assertNotIn(self.alice, get_organization_members(self.organization)) + + def test_the_default_meta_perms_are_not_challenged(self): + """The default meta permissions leave the team's editors editors.""" + self._set_meta_perms(EDITOR_BECOMES_OWNER) + self.assertEqual(self._add_member().status_code, 401) + self._set_meta_perms("editor|dataentry|readonly") + + response = self._add_member() + + self.assertEqual(response.status_code, 201) + self.assertIn(self.alice, get_organization_members(self.organization)) + self.assertFalse(self._alice_owns_the_form()) + + +@gating("rotate-org-key") +@patch("onadata.libs.serializers.organization_serializer.rotate_key") +class TestOrganisationKeyRotationGate(StepUpGateTestCase): + """Rotating the organisation's encryption key makes every device fetch + the re-keyed forms, so a stolen session alone must not trigger it.""" + + def setUp(self): + super().setUp() + self._org_create() + self.content_type = ContentType.objects.get_for_model(OrganizationProfile) + self.kms_key = self._key("fake-key-id") + + def _key(self, key_id): + return KMSKey.objects.create( + key_id=key_id, + description="Key-2025-04-25", + public_key="fake-pub-key", + content_type=self.content_type, + object_id=self.organization.pk, + provider=KMSKey.KMSProvider.AWS, + ) + + def _rotate(self, key_id, headers=None): + view = OrganizationProfileViewSet.as_view({"post": "rotate_key"}) + request = self.factory.post( + "/", data={"id": key_id}, **{**self.extra, **(headers or {})} + ) + return view(request, user="denoinc") + + def test_rotating_the_key_is_challenged(self, mock_rotate_key): + response = self._rotate(self.kms_key.id) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "rotate-org-key") + mock_rotate_key.assert_not_called() + + def test_a_grant_lets_the_rotation_through(self, mock_rotate_key): + mock_rotate_key.return_value = self._key("new-key") + grant = issue_grant(self.user.pk, "rotate-org-key") + + response = self._rotate(self.kms_key.id, {"HTTP_X_STEP_UP_GRANT": grant}) + + self.assertEqual(response.status_code, 200) + mock_rotate_key.assert_called_once() + + def test_an_invalid_key_keeps_the_grant(self, mock_rotate_key): + """Validation comes first, so a mistyped key id does not spend it.""" + grant = issue_grant(self.user.pk, "rotate-org-key") + + response = self._rotate(0, {"HTTP_X_STEP_UP_GRANT": grant}) + + self.assertEqual(response.status_code, 400) + self.assertTrue(spend_grant(self.user.pk, "rotate-org-key", grant)) + mock_rotate_key.assert_not_called() diff --git a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py new file mode 100644 index 0000000000..750cc4861f --- /dev/null +++ b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py @@ -0,0 +1,773 @@ +# -*- coding: utf-8 -*- +""" +Tests for the step-up gates on sharing forms and projects with an admin role +and on making their data public. + +Every test that expects a request through first shows that the gate is +active. Removing the gate then fails that test too. +""" + +import json +from unittest.mock import patch + +from django.test.utils import override_settings + +from django_otp.plugins.otp_totp.models import TOTPDevice +from oidc.stepup_grants import issue_grant, spend_grant + +from onadata.apps.api.tests.viewsets.test_abstract_viewset import TestAbstractViewSet +from onadata.apps.api.viewsets.project_viewset import ProjectViewSet +from onadata.apps.api.viewsets.xform_viewset import XFormViewSet +from onadata.apps.logger.models import Project, ProjectInvitation, XForm +from onadata.apps.main.models import MetaData +from onadata.libs.models.share_project import ShareProject +from onadata.libs.models.share_xform import ShareXForm +from onadata.libs.permissions import ( + EditorMinorRole, + EditorRole, + ManagerRole, + OwnerRole, +) +from onadata.libs.stepup.policy import ( + GATE_INVITE_PROJECT_ADMIN, + GATE_PUBLISH_DATA, + GATE_SHARE_FORM_ADMIN, + GATE_SHARE_PROJECT_ADMIN, +) +from onadata.libs.stepup.sharing import admin_roles_granted, grants_admin_role + +PROJECT_VIEWSET = "onadata.apps.api.viewsets.project_viewset" +XFORM_VIEWSET = "onadata.apps.api.viewsets.xform_viewset" + +#: ``xform_meta_perms`` values. The first slot replaces an editor's role. +EDITOR_BECOMES_OWNER = "owner|dataentry-only|readonly" +EDITOR_BECOMES_MANAGER = "manager|dataentry-only|readonly" +EDITOR_STAYS_BELOW_ADMIN = "editor-minor|dataentry-only|readonly" + + +def gating(*audiences, **settings): + """Gate exactly ``audiences``, for a user with a confirmed factor.""" + return override_settings( + STEP_UP={ + "MODE": "local", + "ACTIONS": list(audiences), + "NO_FACTOR_POLICY": "skip_gate", + }, + **settings, + ) + + +class StepUpGateTestCase(TestAbstractViewSet): + """Gives ``self.user`` a second factor. Without one, ``skip_gate`` lets + every request through ungated.""" + + audience = None + + def setUp(self): + super().setUp() + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + + def _grant(self): + return issue_grant(self.user.pk, self.audience) + + def _with_grant(self, grant): + return {"HTTP_X_STEP_UP_GRANT": grant} + + def assert_challenged(self, response): + """Refused with a challenge naming this test case's audience.""" + self.assertEqual(response.status_code, 401, response.data) + self.assertEqual(response.data["audience"], self.audience) + + def assert_spent(self, grant): + """The gate consumed ``grant``, so the request went through it.""" + self.assertFalse(spend_grant(self.user.pk, self.audience, grant)) + + def _user(self, username): + return self._create_user_profile( + {"username": username, "email": f"{username}@localhost.com"} + ).user + + def _set_meta_perms(self, value): + MetaData.xform_meta_permission(self.xform, data_value=value) + self.assertEqual(MetaData.xform_meta_permission(self.xform).data_value, value) + + +@gating(GATE_SHARE_PROJECT_ADMIN) +class TestShareProjectAdminGate(StepUpGateTestCase): + """An owner or manager of a project can share it on and delete it, so a + stolen session must not be able to appoint one.""" + + audience = GATE_SHARE_PROJECT_ADMIN + + def setUp(self): + super().setUp() + self._project_create() + self.alice = self._user("alice") + self.tom = self._user("tom") + + def _share(self, username, role, headers=None, **extra_data): + view = ProjectViewSet.as_view({"put": "share"}) + request = self.factory.put( + "/", + data={"username": username, "role": role, **extra_data}, + **{**self.extra, **(headers or {})}, + ) + return view(request, pk=self.project.pk) + + def test_sharing_as_owner_is_challenged(self): + response = self._share("alice", OwnerRole.name) + + self.assert_challenged(response) + self.assertFalse(OwnerRole.user_has_role(self.alice, self.project)) + + def test_sharing_as_manager_is_challenged(self): + response = self._share("alice", ManagerRole.name) + + self.assert_challenged(response) + self.assertFalse(ManagerRole.user_has_role(self.alice, self.project)) + + def test_a_grant_lets_the_share_through(self): + grant = self._grant() + + response = self._share("alice", ManagerRole.name, self._with_grant(grant)) + + self.assertEqual(response.status_code, 204) + self.assertTrue(ManagerRole.user_has_role(self.alice, self.project)) + self.assert_spent(grant) + + def test_one_new_admin_among_several_users_is_challenged(self): + ShareProject(self.project, "alice", OwnerRole.name).save() + self.assertTrue(OwnerRole.user_has_role(self.alice, self.project)) + + response = self._share("alice,tom", OwnerRole.name) + + self.assert_challenged(response) + self.assertFalse(OwnerRole.user_has_role(self.tom, self.project)) + + def test_a_non_admin_role_is_not_challenged(self): + self.assert_challenged(self._share("tom", ManagerRole.name)) + + response = self._share("alice", EditorRole.name) + + self.assertEqual(response.status_code, 204) + self.assertTrue(EditorRole.user_has_role(self.alice, self.project)) + + def test_a_role_every_target_already_holds_is_not_challenged(self): + ShareProject(self.project, "alice", ManagerRole.name).save() + self.assertTrue(ManagerRole.user_has_role(self.alice, self.project)) + self.assert_challenged(self._share("tom", ManagerRole.name)) + + response = self._share("alice", ManagerRole.name) + + self.assertEqual(response.status_code, 204) + self.assertTrue(ManagerRole.user_has_role(self.alice, self.project)) + + def test_removing_an_admin_is_not_challenged(self): + ShareProject(self.project, "alice", OwnerRole.name).save() + self.assertTrue(OwnerRole.user_has_role(self.alice, self.project)) + self.assert_challenged(self._share("tom", OwnerRole.name)) + + response = self._share("alice", OwnerRole.name, remove=True) + + self.assertEqual(response.status_code, 204) + self.assertFalse(OwnerRole.user_has_role(self.alice, self.project)) + + def test_an_invalid_share_keeps_the_grant(self): + """Validation comes first, so an unknown username does not spend it.""" + self.assert_challenged(self._share("alice", OwnerRole.name)) + grant = self._grant() + + response = self._share("nobody", OwnerRole.name, self._with_grant(grant)) + + self.assertEqual(response.status_code, 400) + self.assertTrue(spend_grant(self.user.pk, self.audience, grant)) + + def test_the_admin_check_runs_only_where_gated(self): + with patch( + f"{PROJECT_VIEWSET}.admin_roles_granted", wraps=admin_roles_granted + ) as check: + self.assert_challenged(self._share("tom", OwnerRole.name)) + self.assertTrue(check.called) + check.reset_mock() + with gating(GATE_PUBLISH_DATA): + response = self._share("alice", OwnerRole.name) + + self.assertEqual(response.status_code, 204) + check.assert_not_called() + self.assertTrue(OwnerRole.user_has_role(self.alice, self.project)) + + +@gating( + GATE_INVITE_PROJECT_ADMIN, + PROJECT_INVITATION_URL={"*": "https://example.com/register"}, +) +@patch( + "onadata.libs.serializers.project_invitation_serializer" + ".send_project_invitation_email_async.delay" +) +class TestInviteProjectAdminGate(StepUpGateTestCase): + """An invitation confers its role when accepted, so inviting someone as + an owner or manager needs the same proof as sharing with them.""" + + audience = GATE_INVITE_PROJECT_ADMIN + + def setUp(self): + super().setUp() + self._project_create() + + def _invite(self, method, payload, headers=None): + view = ProjectViewSet.as_view({method: "invitations"}) + request = getattr(self.factory, method)( + "/", + data=json.dumps(payload), + content_type="application/json", + **{**self.extra, **(headers or {})}, + ) + return view(request, pk=self.project.pk) + + def _create(self, role, headers=None, email="jane@example.com"): + return self._invite("post", {"email": email, "role": role}, headers) + + def _pending(self, role): + return self.project.invitations.create( + email="jane@example.com", + role=role, + status=ProjectInvitation.Status.PENDING, + ) + + def _update(self, invitation, role, headers=None, email=None): + payload = { + "invitation_id": invitation.pk, + "email": email or invitation.email, + "role": role, + } + return self._invite("put", payload, headers) + + def test_inviting_a_manager_is_challenged(self, _send): + response = self._create(ManagerRole.name) + + self.assert_challenged(response) + self.assertFalse(self.project.invitations.exists()) + + def test_a_grant_lets_the_invitation_through(self, _send): + grant = self._grant() + + response = self._create(OwnerRole.name, self._with_grant(grant)) + + self.assertEqual(response.status_code, 200) + self.assertEqual(self.project.invitations.get().role, OwnerRole.name) + self.assert_spent(grant) + + def test_inviting_a_non_admin_is_not_challenged(self, _send): + self.assert_challenged(self._create(OwnerRole.name)) + + response = self._create(EditorRole.name) + + self.assertEqual(response.status_code, 200) + self.assertEqual(self.project.invitations.get().role, EditorRole.name) + + def test_raising_an_invitation_to_owner_is_challenged(self, _send): + invitation = self._pending(EditorRole.name) + + response = self._update(invitation, OwnerRole.name) + + self.assert_challenged(response) + invitation.refresh_from_db() + self.assertEqual(invitation.role, EditorRole.name) + + def test_redirecting_an_admin_invitation_is_challenged(self, _send): + invitation = self._pending(ManagerRole.name) + + response = self._update( + invitation, ManagerRole.name, email="mallory@example.com" + ) + + self.assert_challenged(response) + invitation.refresh_from_db() + self.assertEqual(invitation.email, "jane@example.com") + + def test_keeping_an_invitations_admin_role_is_not_challenged(self, _send): + invitation = self._pending(ManagerRole.name) + self.assert_challenged(self._update(invitation, OwnerRole.name)) + + response = self._update(invitation, ManagerRole.name) + + self.assertEqual(response.status_code, 200) + invitation.refresh_from_db() + self.assertEqual(invitation.role, ManagerRole.name) + + def test_lowering_an_invitation_is_not_challenged(self, _send): + invitation = self._pending(OwnerRole.name) + self.assert_challenged(self._create(OwnerRole.name, email="kim@example.com")) + + response = self._update(invitation, EditorRole.name) + + self.assertEqual(response.status_code, 200) + invitation.refresh_from_db() + self.assertEqual(invitation.role, EditorRole.name) + + def test_an_invalid_invitation_keeps_the_grant(self, _send): + """Validation comes first, so a mistyped email does not spend it.""" + self.assert_challenged(self._create(OwnerRole.name)) + grant = self._grant() + + response = self._create( + OwnerRole.name, self._with_grant(grant), email="not-an-email" + ) + + self.assertEqual(response.status_code, 400) + self.assertTrue(spend_grant(self.user.pk, self.audience, grant)) + self.assertFalse(self.project.invitations.exists()) + + def test_the_admin_check_runs_only_where_gated(self, _send): + with patch( + f"{PROJECT_VIEWSET}.grants_admin_role", wraps=grants_admin_role + ) as check: + self.assert_challenged(self._create(OwnerRole.name)) + self.assertTrue(check.called) + check.reset_mock() + with gating(GATE_PUBLISH_DATA): + response = self._create(OwnerRole.name) + + self.assertEqual(response.status_code, 200) + check.assert_not_called() + self.assertEqual(self.project.invitations.get().role, OwnerRole.name) + + +@gating(GATE_SHARE_FORM_ADMIN) +class TestShareFormAdminGate(StepUpGateTestCase): + """An owner or manager of a form can share it on and delete it, so a + stolen session must not be able to appoint one.""" + + audience = GATE_SHARE_FORM_ADMIN + + def setUp(self): + super().setUp() + self._publish_xls_form_to_project() + self.alice = self._user("alice") + self.tom = self._user("tom") + + def _share(self, username, role, headers=None): + view = XFormViewSet.as_view({"post": "share"}) + request = self.factory.post( + "/", + data={"username": username, "role": role}, + **{**self.extra, **(headers or {})}, + ) + return view(request, pk=self.xform.pk) + + def test_sharing_as_owner_is_challenged(self): + response = self._share("alice", OwnerRole.name) + + self.assert_challenged(response) + self.assertFalse(OwnerRole.user_has_role(self.alice, self.xform)) + + def test_sharing_as_manager_is_challenged(self): + response = self._share("alice", ManagerRole.name) + + self.assert_challenged(response) + self.assertFalse(ManagerRole.user_has_role(self.alice, self.xform)) + + def test_a_grant_lets_the_share_through(self): + grant = self._grant() + + response = self._share("alice", OwnerRole.name, self._with_grant(grant)) + + self.assertEqual(response.status_code, 204) + self.assertTrue(OwnerRole.user_has_role(self.alice, self.xform)) + self.assert_spent(grant) + + def test_one_new_admin_among_several_users_is_challenged(self): + ShareXForm(self.xform, "alice", ManagerRole.name).save() + self.assertTrue(ManagerRole.user_has_role(self.alice, self.xform)) + + response = self._share("alice,tom", ManagerRole.name) + + self.assert_challenged(response) + self.assertFalse(ManagerRole.user_has_role(self.tom, self.xform)) + + def test_a_non_admin_role_is_not_challenged(self): + self.assert_challenged(self._share("tom", OwnerRole.name)) + + response = self._share("alice", EditorRole.name) + + self.assertEqual(response.status_code, 204) + self.assertTrue(EditorRole.user_has_role(self.alice, self.xform)) + + def test_a_role_every_target_already_holds_is_not_challenged(self): + ShareXForm(self.xform, "alice", OwnerRole.name).save() + self.assertTrue(OwnerRole.user_has_role(self.alice, self.xform)) + self.assert_challenged(self._share("tom", OwnerRole.name)) + + response = self._share("alice", OwnerRole.name) + + self.assertEqual(response.status_code, 204) + self.assertTrue(OwnerRole.user_has_role(self.alice, self.xform)) + + def test_an_invalid_share_keeps_the_grant(self): + """Validation comes first, so an unknown username does not spend it.""" + self.assert_challenged(self._share("alice", OwnerRole.name)) + grant = self._grant() + + response = self._share("nobody", OwnerRole.name, self._with_grant(grant)) + + self.assertEqual(response.status_code, 400) + self.assertTrue(spend_grant(self.user.pk, self.audience, grant)) + + def test_the_admin_check_runs_only_where_gated(self): + with patch( + f"{XFORM_VIEWSET}.admin_roles_granted", wraps=admin_roles_granted + ) as check: + self.assert_challenged(self._share("tom", OwnerRole.name)) + self.assertTrue(check.called) + check.reset_mock() + with gating(GATE_PUBLISH_DATA): + response = self._share("alice", OwnerRole.name) + + self.assertEqual(response.status_code, 204) + check.assert_not_called() + self.assertTrue(OwnerRole.user_has_role(self.alice, self.xform)) + + +@gating(GATE_PUBLISH_DATA) +class TestPublishProjectDataGate(StepUpGateTestCase): + """A public project's forms and data are readable by anyone, so a stolen + session must not be able to publish them.""" + + audience = GATE_PUBLISH_DATA + + def setUp(self): + super().setUp() + self._publish_xls_form_to_project() + self.assertFalse(self.project.shared) + self.assertFalse(self.xform.shared_data) + + def _patch(self, data, headers=None): + view = ProjectViewSet.as_view({"patch": "partial_update"}) + request = self.factory.patch( + "/", data=data, **{**self.extra, **(headers or {})} + ) + return view(request, pk=self.project.pk) + + def _make_public(self): + Project.objects.filter(pk=self.project.pk).update(shared=True) + XForm.objects.filter(pk=self.xform.pk).update(shared=True, shared_data=True) + + def _reload(self): + self.project.refresh_from_db() + self.xform.refresh_from_db() + + def test_making_a_project_public_is_challenged(self): + response = self._patch({"public": True}) + + self.assert_challenged(response) + self._reload() + self.assertFalse(self.project.shared) + self.assertFalse(self.xform.shared_data) + + def test_a_full_update_making_a_project_public_is_challenged(self): + view = ProjectViewSet.as_view({"put": "update"}) + data = { + "name": "demo", + "owner": f"http://testserver/api/v1/users/{self.user.username}", + "public": True, + } + request = self.factory.put("/", data=data, **self.extra) + + response = view(request, pk=self.project.pk) + + self.assert_challenged(response) + self._reload() + self.assertFalse(self.project.shared) + + def test_a_grant_lets_the_project_go_public(self): + grant = self._grant() + + response = self._patch({"public": True}, self._with_grant(grant)) + + self.assertEqual(response.status_code, 200) + self._reload() + self.assertTrue(self.project.shared) + self.assertTrue(self.xform.shared_data) + self.assert_spent(grant) + + def test_editing_a_public_project_with_a_private_form_is_challenged(self): + """Every save of a public project makes its private forms public.""" + Project.objects.filter(pk=self.project.pk).update(shared=True) + + response = self._patch({"name": "renamed"}) + + self.assert_challenged(response) + self._reload() + self.assertEqual(self.project.name, "demo") + self.assertFalse(self.xform.shared_data) + + def test_editing_a_public_project_with_public_forms_is_not_challenged(self): + Project.objects.filter(pk=self.project.pk).update(shared=True) + self.assert_challenged(self._patch({"name": "renamed"})) + XForm.objects.filter(pk=self.xform.pk).update(shared=True, shared_data=True) + + response = self._patch({"name": "renamed"}) + + self.assertEqual(response.status_code, 200) + self._reload() + self.assertEqual(self.project.name, "renamed") + + def test_making_a_project_private_is_not_challenged(self): + self.assert_challenged(self._patch({"public": True})) + self._make_public() + + response = self._patch({"public": False}) + + self.assertEqual(response.status_code, 200) + self._reload() + self.assertFalse(self.project.shared) + self.assertFalse(self.xform.shared_data) + + def test_an_invalid_update_keeps_the_grant(self): + """Validation comes first, so a blank name does not spend it.""" + self.assert_challenged(self._patch({"public": True})) + grant = self._grant() + + response = self._patch({"public": True, "name": ""}, self._with_grant(grant)) + + self.assertEqual(response.status_code, 400) + self.assertTrue(spend_grant(self.user.pk, self.audience, grant)) + self._reload() + self.assertFalse(self.project.shared) + + +@gating(GATE_PUBLISH_DATA) +class TestPublishFormDataGate(StepUpGateTestCase): + """A public form's data is readable by anyone, so a stolen session must + not be able to publish it.""" + + audience = GATE_PUBLISH_DATA + + def setUp(self): + super().setUp() + self._publish_xls_form_to_project() + self.assertFalse(self.xform.shared) + self.assertFalse(self.xform.shared_data) + + def _patch(self, data, headers=None): + view = XFormViewSet.as_view({"patch": "partial_update"}) + request = self.factory.patch( + "/", data=data, **{**self.extra, **(headers or {})} + ) + return view(request, pk=self.xform.pk) + + def test_making_form_data_public_is_challenged(self): + response = self._patch({"public_data": True}) + + self.assert_challenged(response) + self.xform.refresh_from_db() + self.assertFalse(self.xform.shared_data) + + def test_making_a_form_public_is_challenged(self): + response = self._patch({"public": True}) + + self.assert_challenged(response) + self.xform.refresh_from_db() + self.assertFalse(self.xform.shared) + + def test_a_grant_lets_the_form_data_go_public(self): + grant = self._grant() + + response = self._patch({"public_data": True}, self._with_grant(grant)) + + self.assertEqual(response.status_code, 200) + self.xform.refresh_from_db() + self.assertTrue(self.xform.shared_data) + self.assert_spent(grant) + + def test_making_form_data_private_is_not_challenged(self): + self.assert_challenged(self._patch({"public_data": True})) + XForm.objects.filter(pk=self.xform.pk).update(shared=True, shared_data=True) + + response = self._patch({"public": False, "public_data": False}) + + self.assertEqual(response.status_code, 200) + self.xform.refresh_from_db() + self.assertFalse(self.xform.shared) + self.assertFalse(self.xform.shared_data) + + def test_an_invalid_update_keeps_the_grant(self): + """Validation comes first, so a malformed public key does not spend it.""" + self.assert_challenged(self._patch({"public_data": True})) + grant = self._grant() + + response = self._patch( + {"public_data": True, "public_key": "not-a-key"}, + self._with_grant(grant), + ) + + self.assertEqual(response.status_code, 400) + self.assertTrue(spend_grant(self.user.pk, self.audience, grant)) + self.xform.refresh_from_db() + self.assertFalse(self.xform.shared_data) + + +@gating(GATE_SHARE_FORM_ADMIN) +class TestShareFormThroughMetaPermsGate(StepUpGateTestCase): + """A form's meta permissions can turn an editor share into an owner one, + so the gate counts the role the share ends up granting.""" + + audience = GATE_SHARE_FORM_ADMIN + + def setUp(self): + super().setUp() + self._publish_xls_form_to_project() + self.alice = self._user("alice") + self._set_meta_perms(EDITOR_BECOMES_OWNER) + + def _share(self, username, role, headers=None): + view = XFormViewSet.as_view({"post": "share"}) + request = self.factory.post( + "/", + data={"username": username, "role": role}, + **{**self.extra, **(headers or {})}, + ) + return view(request, pk=self.xform.pk) + + def test_an_editor_share_made_owner_is_challenged(self): + """The 401 names the audience and the user gets no role.""" + response = self._share("alice", EditorRole.name) + + self.assert_challenged(response) + self.assertFalse(OwnerRole.user_has_role(self.alice, self.xform)) + self.assertFalse(EditorRole.user_has_role(self.alice, self.xform)) + + def test_a_grant_lets_the_editor_share_through_as_owner(self): + """With a grant the meta permissions make the editor an owner.""" + grant = self._grant() + + response = self._share("alice", EditorRole.name, self._with_grant(grant)) + + self.assertEqual(response.status_code, 204) + self.assertTrue(OwnerRole.user_has_role(self.alice, self.xform)) + self.assert_spent(grant) + + def test_an_editor_share_kept_below_admin_is_not_challenged(self): + """Meta permissions without an admin slot leave an editor an editor.""" + self.assert_challenged(self._share("alice", EditorRole.name)) + self._set_meta_perms(EDITOR_STAYS_BELOW_ADMIN) + + response = self._share("alice", EditorRole.name) + + self.assertEqual(response.status_code, 204) + self.assertTrue(EditorMinorRole.user_has_role(self.alice, self.xform)) + self.assertFalse(ManagerRole.user_has_role(self.alice, self.xform)) + + +@gating(GATE_SHARE_PROJECT_ADMIN) +class TestShareProjectThroughMetaPermsGate(StepUpGateTestCase): + """A project share applies each form's meta permissions, so an editor + share on a project holding a form that makes editors managers appoints + a manager of that form.""" + + audience = GATE_SHARE_PROJECT_ADMIN + + def setUp(self): + super().setUp() + self._publish_xls_form_to_project() + self.alice = self._user("alice") + self._set_meta_perms(EDITOR_BECOMES_MANAGER) + + def _share(self, role, headers=None): + view = ProjectViewSet.as_view({"put": "share"}) + request = self.factory.put( + "/", + data={"username": "alice", "role": role}, + **{**self.extra, **(headers or {})}, + ) + return view(request, pk=self.project.pk) + + def test_an_editor_share_made_manager_of_a_form_is_challenged(self): + """The 401 names the audience and the user gets no role.""" + response = self._share(EditorRole.name) + + self.assert_challenged(response) + self.assertFalse(EditorRole.user_has_role(self.alice, self.project)) + self.assertFalse(ManagerRole.user_has_role(self.alice, self.xform)) + + def test_a_grant_lets_the_editor_share_through(self): + """With a grant the user is an editor of the project and a manager + of its form.""" + grant = self._grant() + + response = self._share(EditorRole.name, self._with_grant(grant)) + + self.assertEqual(response.status_code, 204) + self.assertTrue(EditorRole.user_has_role(self.alice, self.project)) + self.assertTrue(ManagerRole.user_has_role(self.alice, self.xform)) + self.assert_spent(grant) + + def test_an_editor_share_kept_below_admin_is_not_challenged(self): + """Meta permissions without an admin slot leave an editor an editor.""" + self.assert_challenged(self._share(EditorRole.name)) + self._set_meta_perms(EDITOR_STAYS_BELOW_ADMIN) + + response = self._share(EditorRole.name) + + self.assertEqual(response.status_code, 204) + self.assertTrue(EditorRole.user_has_role(self.alice, self.project)) + self.assertFalse(ManagerRole.user_has_role(self.alice, self.xform)) + + +@gating( + GATE_INVITE_PROJECT_ADMIN, + PROJECT_INVITATION_URL={"*": "https://example.com/register"}, +) +@patch( + "onadata.libs.serializers.project_invitation_serializer" + ".send_project_invitation_email_async.delay" +) +class TestInviteThroughMetaPermsGate(StepUpGateTestCase): + """Accepting an invitation shares the project, meta permissions + included, so an editor invitation to a project whose form makes editors + owners needs the same proof as an owner one.""" + + audience = GATE_INVITE_PROJECT_ADMIN + + def setUp(self): + super().setUp() + self._publish_xls_form_to_project() + self._set_meta_perms(EDITOR_BECOMES_OWNER) + + def _invite(self, role, headers=None): + view = ProjectViewSet.as_view({"post": "invitations"}) + request = self.factory.post( + "/", + data=json.dumps({"email": "jane@example.com", "role": role}), + content_type="application/json", + **{**self.extra, **(headers or {})}, + ) + return view(request, pk=self.project.pk) + + def test_an_editor_invitation_made_owner_is_challenged(self, _send): + """The 401 names the audience and no invitation is made.""" + response = self._invite(EditorRole.name) + + self.assert_challenged(response) + self.assertFalse(self.project.invitations.exists()) + + def test_a_grant_lets_the_invitation_through(self, _send): + """With a grant the editor invitation is made.""" + grant = self._grant() + + response = self._invite(EditorRole.name, self._with_grant(grant)) + + self.assertEqual(response.status_code, 200) + self.assertEqual(self.project.invitations.get().role, EditorRole.name) + self.assert_spent(grant) + + def test_an_editor_invitation_kept_below_admin_is_not_challenged(self, _send): + """Meta permissions without an admin slot leave an editor an editor.""" + self.assert_challenged(self._invite(EditorRole.name)) + self._set_meta_perms(EDITOR_STAYS_BELOW_ADMIN) + + response = self._invite(EditorRole.name) + + self.assertEqual(response.status_code, 200) + self.assertEqual(self.project.invitations.get().role, EditorRole.name) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py new file mode 100644 index 0000000000..04cf986868 --- /dev/null +++ b/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py @@ -0,0 +1,506 @@ +# -*- coding: utf-8 -*- +""" +Tests for the step-up gates on the team endpoints. +""" + +import json + +from guardian.shortcuts import get_perms +from oidc.stepup_grants import issue_grant, spend_grant + +from onadata.apps.api.models.organization_profile import create_organization_team +from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import ( + StepUpGateTestCase, + gating, +) +from onadata.apps.api.tools import add_user_to_team +from onadata.apps.api.viewsets.team_viewset import TeamViewSet +from onadata.libs.models.share_team_project import ShareTeamProject +from onadata.libs.permissions import ( + ROLES, + EditorRole, + ManagerRole, + OwnerRole, + ReadOnlyRole, +) + + +class TeamGateTestCase(StepUpGateTestCase): + """An organisation with a team, and a user who belongs to neither.""" + + def setUp(self): + super().setUp() + self._team_create() + self.alice = self._create_user("alice", "alice", create_profile=True) + + @staticmethod + def _in_team(team, user): + return team.user_set.filter(pk=user.pk).exists() + + def _members(self, method, team, username="alice", headers=None): + view = TeamViewSet.as_view({"post": "members", "delete": "members"}) + request = getattr(self.factory, method)( + "/", + data=json.dumps({"username": username}), + content_type="application/json", + **{**self.extra, **(headers or {})}, + ) + return view(request, pk=team.pk) + + +@gating("grant-org-admin") +class TestOwnersTeamGate(TeamGateTestCase): + """Joining the Owners team makes someone an organisation owner, so it + needs the same proof as the organisation's members route.""" + + def _make_alice_an_owner(self): + self._add_user_to_organization(self.organization, self.alice, "owner") + self.assertTrue(self._in_team(self.owner_team, self.alice)) + + def test_joining_the_owners_team_is_challenged(self): + self.assertFalse(self._in_team(self.owner_team, self.alice)) + + response = self._members("post", self.owner_team) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "grant-org-admin") + self.assertFalse(self._in_team(self.owner_team, self.alice)) + self.assertFalse(self.organization.is_organization_owner(self.alice)) + + def test_a_grant_lets_the_owner_through(self): + self.assertFalse(self._in_team(self.owner_team, self.alice)) + grant = issue_grant(self.user.pk, "grant-org-admin") + + response = self._members( + "post", self.owner_team, headers={"HTTP_X_STEP_UP_GRANT": grant} + ) + + self.assertEqual(response.status_code, 201) + self.assertIn("alice", response.data) + self.assertTrue(self.organization.is_organization_owner(self.alice)) + + def test_joining_another_team_is_not_challenged(self): + self.assertFalse(self._in_team(self.team, self.alice)) + self.assertEqual(self._members("post", self.owner_team).status_code, 401) + + response = self._members("post", self.team) + + self.assertEqual(response.status_code, 201) + self.assertTrue(self._in_team(self.team, self.alice)) + self.assertFalse(self.organization.is_organization_owner(self.alice)) + + def test_re_adding_an_owner_is_not_challenged(self): + self._make_alice_an_owner() + + response = self._members("post", self.owner_team) + + self.assertEqual(response.status_code, 201) + self.assertTrue(self._in_team(self.owner_team, self.alice)) + + def test_removing_an_owner_is_not_challenged(self): + self._make_alice_an_owner() + + response = self._members("delete", self.owner_team) + + self.assertEqual(response.status_code, 201) + self.assertFalse(self._in_team(self.owner_team, self.alice)) + + +@gating("share-team-admin") +class TestTeamShareGate(TeamGateTestCase): + """An owner or manager of a project can share it onwards, so giving a + whole team that role needs a second factor.""" + + def setUp(self): + super().setUp() + self._project_create() + add_user_to_team(self.team, self.alice) + self.assertTrue(self._in_team(self.team, self.alice)) + + def _share(self, role, headers=None, **extra_data): + view = TeamViewSet.as_view({"post": "share"}) + request = self.factory.post( + "/", + data=json.dumps({"role": role, "project": self.project.pk, **extra_data}), + content_type="application/json", + **{**self.extra, **(headers or {})}, + ) + return view(request, pk=self.team.pk) + + def _give_the_team(self, role): + ShareTeamProject(self.team, self.project, role).save() + self.assertTrue(ROLES[role].user_has_role(self.alice, self.project)) + + def test_sharing_the_manager_role_is_challenged(self): + self.assertFalse(ManagerRole.user_has_role(self.alice, self.project)) + + response = self._share("manager") + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "share-team-admin") + self.assertFalse(ManagerRole.user_has_role(self.alice, self.project)) + + def test_a_grant_lets_the_owner_role_through(self): + self.assertFalse(OwnerRole.user_has_role(self.alice, self.project)) + grant = issue_grant(self.user.pk, "share-team-admin") + + response = self._share("owner", {"HTTP_X_STEP_UP_GRANT": grant}) + + self.assertEqual(response.status_code, 204) + self.assertTrue(OwnerRole.user_has_role(self.alice, self.project)) + + def test_other_roles_are_not_challenged(self): + self.assertFalse(EditorRole.user_has_role(self.alice, self.project)) + self.assertEqual(self._share("manager").status_code, 401) + + response = self._share("editor") + + self.assertEqual(response.status_code, 204) + self.assertTrue(EditorRole.user_has_role(self.alice, self.project)) + self.assertFalse(ManagerRole.user_has_role(self.alice, self.project)) + + def test_a_role_the_team_holds_is_not_challenged(self): + self.assertEqual(self._share("manager").status_code, 401) + self._give_the_team("manager") + + response = self._share("manager") + + self.assertEqual(response.status_code, 204) + self.assertTrue(ManagerRole.user_has_role(self.alice, self.project)) + + def test_removing_the_team_is_not_challenged(self): + """Removal takes away whatever the team holds, whichever role it + names, so naming one the team lacks still removes it.""" + self.assertEqual(self._share("manager").status_code, 401) + self._give_the_team("manager") + self.assertFalse(OwnerRole.user_has_role(self.alice, self.project)) + + response = self._share("owner", remove=True) + + self.assertEqual(response.status_code, 204) + self.assertFalse(ManagerRole.user_has_role(self.alice, self.project)) + + def test_an_unknown_project_keeps_the_grant(self): + """The project is checked first, so a typo does not spend it.""" + grant = issue_grant(self.user.pk, "share-team-admin") + + response = self._share( + "manager", {"HTTP_X_STEP_UP_GRANT": grant}, project=999999 + ) + + self.assertEqual(response.status_code, 400) + self.assertTrue(spend_grant(self.user.pk, "share-team-admin", grant)) + + +@gating("share-team-admin") +class TestJoinAdminTeamGate(TeamGateTestCase): + """A new member takes on every role the team holds, so adding someone to + a team that owns or manages a project or form appoints an admin of it.""" + + def setUp(self): + super().setUp() + self._project_create() + ShareTeamProject(self.team, self.project, ManagerRole.name).save() + self.assertFalse(self._in_team(self.team, self.alice)) + + def _readers(self): + readers = create_organization_team(self.organization, "readers") + ShareTeamProject(readers, self.project, EditorRole.name).save() + return readers + + def test_joining_a_team_that_manages_a_project_is_challenged(self): + """The 401 names the audience and leaves the user out of the team.""" + response = self._members("post", self.team) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "share-team-admin") + self.assertFalse(self._in_team(self.team, self.alice)) + self.assertFalse(ManagerRole.user_has_role(self.alice, self.project)) + + def test_joining_a_team_that_manages_only_a_form_is_challenged(self): + """A role on a single form counts as much as one on a project.""" + self._publish_xls_form_to_project() + form_team = create_organization_team(self.organization, "form admins") + ManagerRole.add(form_team, self.xform) + + response = self._members("post", form_team) + + self.assertEqual(response.status_code, 401) + self.assertFalse(self._in_team(form_team, self.alice)) + self.assertFalse(ManagerRole.user_has_role(self.alice, self.xform)) + + def test_a_grant_lets_the_member_join(self): + """With a grant the user joins and takes on the team's role.""" + grant = issue_grant(self.user.pk, "share-team-admin") + + response = self._members( + "post", self.team, headers={"HTTP_X_STEP_UP_GRANT": grant} + ) + + self.assertEqual(response.status_code, 201) + self.assertTrue(self._in_team(self.team, self.alice)) + self.assertTrue(ManagerRole.user_has_role(self.alice, self.project)) + self.assertFalse(spend_grant(self.user.pk, "share-team-admin", grant)) + + def test_joining_a_team_without_an_admin_role_is_not_challenged(self): + """An editor team appoints no admin.""" + self.assertEqual(self._members("post", self.team).status_code, 401) + readers = self._readers() + + response = self._members("post", readers) + + self.assertEqual(response.status_code, 201) + self.assertTrue(self._in_team(readers, self.alice)) + self.assertTrue(EditorRole.user_has_role(self.alice, self.project)) + self.assertFalse(ManagerRole.user_has_role(self.alice, self.project)) + + def test_joining_a_team_meta_perms_make_admin_is_challenged(self): + """An editor team counts as an admin one where a form's meta + permissions make its editors owners.""" + self._publish_xls_form_to_project() + readers = self._readers() + self._set_meta_perms("owner|dataentry-only|readonly") + + response = self._members("post", readers) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "share-team-admin") + self.assertFalse(self._in_team(readers, self.alice)) + + def test_joining_a_team_meta_perms_keep_below_admin_is_not_challenged(self): + """The default meta permissions leave an editor team's members + editors.""" + self._publish_xls_form_to_project() + readers = self._readers() + self.assertEqual(self._members("post", self.team).status_code, 401) + + response = self._members("post", readers) + + self.assertEqual(response.status_code, 201) + self.assertTrue(self._in_team(readers, self.alice)) + self.assertFalse(OwnerRole.user_has_role(self.alice, self.xform)) + + def test_re_adding_a_member_is_not_challenged(self): + """Someone already in the team gains nothing by joining again.""" + self.assertEqual(self._members("post", self.team).status_code, 401) + add_user_to_team(self.team, self.alice) + + response = self._members("post", self.team) + + self.assertEqual(response.status_code, 201) + self.assertTrue(self._in_team(self.team, self.alice)) + + def test_removing_a_member_is_not_challenged(self): + """Taking a role away is never gated.""" + self.assertEqual(self._members("post", self.team).status_code, 401) + add_user_to_team(self.team, self.alice) + + response = self._members("delete", self.team) + + self.assertEqual(response.status_code, 201) + self.assertFalse(self._in_team(self.team, self.alice)) + + def test_an_unknown_user_keeps_the_grant(self): + """The username is checked first, so a typo does not spend it.""" + grant = issue_grant(self.user.pk, "share-team-admin") + + response = self._members( + "post", self.team, "nobody", headers={"HTTP_X_STEP_UP_GRANT": grant} + ) + + self.assertEqual(response.status_code, 400) + self.assertTrue(spend_grant(self.user.pk, "share-team-admin", grant)) + + +@gating("grant-org-admin", "share-team-admin") +class TestJoinOwnersTeamWithBothGates(TeamGateTestCase): + """Joining the Owners team both appoints an organisation owner and joins + a team that owns projects. One grant for the first gated audience covers + both, so the request is not refused as two gated changes.""" + + def setUp(self): + super().setUp() + self._project_create() + OwnerRole.add(self.owner_team, self.project) + self.assertTrue( + OwnerRole.has_role(get_perms(self.owner_team, self.project), self.project) + ) + + def test_joining_the_owners_team_asks_for_the_org_admin_grant(self): + """Challenged once, for ``grant-org-admin``.""" + response = self._members("post", self.owner_team) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "grant-org-admin") + self.assertFalse(self._in_team(self.owner_team, self.alice)) + + def test_the_org_admin_grant_lets_the_owner_join(self): + """That one grant is enough.""" + grant = issue_grant(self.user.pk, "grant-org-admin") + + response = self._members( + "post", self.owner_team, headers={"HTTP_X_STEP_UP_GRANT": grant} + ) + + self.assertEqual(response.status_code, 201) + self.assertTrue(self.organization.is_organization_owner(self.alice)) + + +@gating("share-team-admin") +class TestTeamShareThroughMetaPermsGate(TeamGateTestCase): + """A team share applies each form's meta permissions, so an editor share + on a project whose form makes editors owners needs the same proof as an + owner share.""" + + def setUp(self): + super().setUp() + self._publish_xls_form_to_project() + add_user_to_team(self.team, self.alice) + self._set_meta_perms("owner|dataentry-only|readonly") + + def _share(self, role, headers=None): + view = TeamViewSet.as_view({"post": "share"}) + request = self.factory.post( + "/", + data=json.dumps({"role": role, "project": self.project.pk}), + content_type="application/json", + **{**self.extra, **(headers or {})}, + ) + return view(request, pk=self.team.pk) + + def test_an_editor_share_made_owner_is_challenged(self): + """The 401 names the audience and the team gets no role.""" + response = self._share(EditorRole.name) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "share-team-admin") + self.assertFalse(EditorRole.user_has_role(self.alice, self.project)) + + def test_a_grant_lets_the_editor_share_through(self): + """With a grant the team gets the role.""" + grant = issue_grant(self.user.pk, "share-team-admin") + + response = self._share(EditorRole.name, {"HTTP_X_STEP_UP_GRANT": grant}) + + self.assertEqual(response.status_code, 204) + self.assertTrue(EditorRole.user_has_role(self.alice, self.project)) + self.assertFalse(spend_grant(self.user.pk, "share-team-admin", grant)) + + def test_an_editor_share_kept_below_admin_is_not_challenged(self): + """Meta permissions without an admin slot leave an editor an editor.""" + self.assertEqual(self._share(EditorRole.name).status_code, 401) + self._set_meta_perms("editor-minor|dataentry-only|readonly") + + response = self._share(EditorRole.name) + + self.assertEqual(response.status_code, 204) + self.assertTrue(EditorRole.user_has_role(self.alice, self.project)) + + def _carol_edits_the_form(self): + """A user the stored meta permissions have not been applied to.""" + carol = self._create_user("carol", "carol", create_profile=True) + EditorRole.add(carol, self.xform) + self.assertFalse(OwnerRole.user_has_role(carol, self.xform)) + return carol + + def test_a_share_that_promotes_a_form_editor_is_challenged(self): + """A share re-applies the meta permissions to every user of the form, + so even a read-only one makes an editor an owner.""" + carol = self._carol_edits_the_form() + + response = self._share(ReadOnlyRole.name) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "share-team-admin") + self.assertFalse(OwnerRole.user_has_role(carol, self.xform)) + + def test_a_grant_lets_a_promoting_share_through(self): + """With a grant the share goes through and the editor becomes an + owner.""" + carol = self._carol_edits_the_form() + grant = issue_grant(self.user.pk, "share-team-admin") + + response = self._share(ReadOnlyRole.name, {"HTTP_X_STEP_UP_GRANT": grant}) + + self.assertEqual(response.status_code, 204) + self.assertTrue(OwnerRole.user_has_role(carol, self.xform)) + self.assertFalse(spend_grant(self.user.pk, "share-team-admin", grant)) + + def test_a_share_that_promotes_nobody_is_not_challenged(self): + """With no form user left for the meta permissions to promote, a + read-only share appoints nobody.""" + carol = self._carol_edits_the_form() + self.assertEqual(self._share(ReadOnlyRole.name).status_code, 401) + EditorRole.remove_obj_permissions(carol, self.xform) + + response = self._share(ReadOnlyRole.name) + + self.assertEqual(response.status_code, 204) + self.assertTrue(ReadOnlyRole.user_has_role(self.alice, self.project)) + + +@gating("share-team-admin") +class TestMoveTeamGate(TeamGateTestCase): + """A moved team keeps its roles on the old organisation's projects and + forms, so moving it hands them to whoever runs the new organisation.""" + + def setUp(self): + super().setUp() + home = self.organization + self._org_create({"org": "otherinc"}) + self.other_org = self.organization + self.organization = home + + def _update(self, organization, headers=None): + view = TeamViewSet.as_view({"put": "update"}) + request = self.factory.put( + "/", + data=json.dumps({"name": "dreamteam", "organization": organization}), + content_type="application/json", + **{**self.extra, **(headers or {})}, + ) + return view(request, pk=self.team.pk) + + def _team_org(self): + self.team.refresh_from_db() + return self.team.organization + + def test_moving_a_team_is_challenged(self): + response = self._update(self.other_org.user.username) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "share-team-admin") + self.assertEqual(self._team_org(), self.organization.user) + + def test_a_grant_lets_the_team_move(self): + grant = issue_grant(self.user.pk, "share-team-admin") + + response = self._update( + self.other_org.user.username, {"HTTP_X_STEP_UP_GRANT": grant} + ) + + self.assertEqual(response.status_code, 200) + self.assertEqual(self._team_org(), self.other_org.user) + self.assertFalse(spend_grant(self.user.pk, "share-team-admin", grant)) + + def test_keeping_the_organisation_is_not_challenged(self): + self.assertEqual(self._update(self.other_org.user.username).status_code, 401) + + response = self._update(self.organization.user.username) + + self.assertEqual(response.status_code, 200) + self.assertEqual(self._team_org(), self.organization.user) + + def test_renaming_without_an_organisation_is_not_challenged(self): + view = TeamViewSet.as_view({"patch": "partial_update"}) + request = self.factory.patch( + "/", + data=json.dumps({"name": "renamed"}), + content_type="application/json", + **self.extra, + ) + + response = view(request, pk=self.team.pk) + + self.assertEqual(response.status_code, 200) + self.assertEqual(self._team_org(), self.organization.user) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_user_profile_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_user_profile_gates.py new file mode 100644 index 0000000000..6c1a0b7227 --- /dev/null +++ b/onadata/apps/api/tests/viewsets/test_stepup_user_profile_gates.py @@ -0,0 +1,372 @@ +# -*- coding: utf-8 -*- +""" +Tests for the step-up gates on the user profile endpoints that change the +consent record, the email or the password. +""" + +import json +from unittest.mock import patch + +from django.conf import settings +from django.core.cache import cache +from django.test import override_settings + +from oidc.stepup_grants import issue_grant, spend_grant +from registration.models import RegistrationProfile + +from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import ( + StepUpGateTestCase, + gating, +) +from onadata.apps.api.viewsets.user_profile_viewset import UserProfileViewSet +from onadata.apps.main.models import UserProfile +from onadata.libs.stepup.policy import eu_consent_record +from onadata.libs.utils.cache_tools import ( + CHANGE_PASSWORD_ATTEMPTS, + LOCKOUT_CHANGE_PASSWORD_USER, +) + +#: The account actions a deployment gates together. +ACCOUNT_ACTIONS = ( + "regenerate-api-key", + "regenerate-odk-token", + "change-email", + "change-password", +) + + +@gating( + "privacy-consent", + # Pin the path. Where the consent record lives is deployment + # configuration, and the ambient value would make these tests depend on + # the environment. + EU_CONSENT_METADATA_PATH=("client", "eu_citizen_consent"), +) +class TestPrivacyConsentGate(StepUpGateTestCase): + """Changing the GDPR consent record needs the same proof as require_auth. + + The record is a compliance statement about whose data this account + collects. A stolen session alone must not be able to change it. + """ + + def setUp(self): + super().setUp() + self.view = UserProfileViewSet.as_view({"patch": "partial_update"}) + + def _patch(self, data): + request = self.factory.patch("/", data=data, format="json", **self.extra) + return self.view(request, user=self.user.username) + + def _consent(self, collecting): + # Matches EU_CONSENT_METADATA_PATH above. The path is nested because + # a deployment namespaces its own metadata, so the gate must not + # assume a flat key. + return { + "client": { + "eu_citizen_consent": { + "is_collecting_eu_data": collecting, + "date": "2026-01-01T00:00:00Z", + } + } + } + + def test_changing_consent_without_a_grant_is_challenged(self): + response = self._patch({"metadata": self._consent(True)}) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["error"], "step_up_required") + self.assertEqual(response.data["audience"], "privacy-consent") + + def test_an_unrelated_metadata_edit_is_not_challenged(self): + """A client may PATCH the whole blob. Prompting for a city change + would train users to approve challenges they did not ask for.""" + self.assertEqual( + self._patch({"metadata": self._consent(True)}).status_code, 401 + ) + + response = self._patch({"metadata": {"city": "Nairobi"}}) + + self.assertEqual(response.status_code, 200) + + def test_metadata_sent_as_a_json_string_is_still_gated(self): + """Clients send metadata as a dict or a JSON string. Reading only + dicts would let a consent change through as a string.""" + response = self._patch({"metadata": json.dumps(self._consent(True))}) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "privacy-consent") + + def test_removing_the_consent_record_without_a_grant_is_challenged(self): + """Dropping the record is a change too. The default PATCH replaces + metadata wholesale, so a payload without the consent path clears the + record. Gating only a differing value would let that through.""" + profile = UserProfile.objects.get(user=self.user) + profile.metadata = self._consent(True) + profile.save() + + response = self._patch({"metadata": {}}) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["error"], "step_up_required") + self.assertEqual(response.data["audience"], "privacy-consent") + profile.refresh_from_db() + self.assertEqual(profile.metadata, self._consent(True)) + + def test_a_grant_lets_the_consent_record_be_removed(self): + profile = UserProfile.objects.get(user=self.user) + profile.metadata = self._consent(True) + profile.save() + grant = issue_grant(self.user.pk, "privacy-consent") + + response = self._patch({"metadata": {}, "grant": grant}) + + self.assertEqual(response.status_code, 200) + profile.refresh_from_db() + self.assertIsNone(eu_consent_record(profile.metadata)) + + def test_a_put_with_overwrite_false_cannot_change_consent_ungated(self): + """PUT ignores overwrite and writes metadata wholesale. An + overwrite=false in its body must not skip the gate as it does for a + PATCH merge.""" + profile = UserProfile.objects.get(user=self.user) + profile.metadata = self._consent(True) + profile.save() + view = UserProfileViewSet.as_view({"put": "update"}) + + request = self.factory.put( + "/", + data={ + "username": self.user.username, + "name": "Bob", + "email": self.user.email, + "password": self.login_password, + "metadata": self._consent(False), + "overwrite": "false", + }, + format="json", + **self.extra, + ) + response = view(request, user=self.user.username) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "privacy-consent") + profile.refresh_from_db() + self.assertEqual(profile.metadata, self._consent(True)) + + +@gating(*ACCOUNT_ACTIONS) +class TestEmailAndPasswordGates(StepUpGateTestCase): + """Changing the email moves where password resets are delivered. + Changing the password replaces the credential itself. A stolen session + alone must not be able to do either. + """ + + def setUp(self): + super().setUp() + RegistrationProfile.objects.create_profile(self.user) + + def _patch_email(self, data): + view = UserProfileViewSet.as_view({"patch": "partial_update"}) + request = self.factory.patch("/", data=data, format="json", **self.extra) + return view(request, user=self.user.username) + + @gating(*ACCOUNT_ACTIONS, "require-auth-toggle") + def test_two_gated_changes_are_refused_without_spending_the_grant(self): + """A request carries one grant, so it could never satisfy both.""" + grant = issue_grant(self.user.pk, "change-email") + + response = self._patch_email( + { + "email": "somewhere.else@example.org", + "require_auth": not self.user.profile.require_auth, + "password": self.login_password, + "grant": grant, + } + ) + + self.assertEqual(response.status_code, 400) + self.assertEqual(response.data["error"], "one_gated_change_per_request") + self.assertEqual( + response.data["audiences"], ["require-auth-toggle", "change-email"] + ) + self.assertTrue(spend_grant(self.user.pk, "change-email", grant)) + + def test_changing_the_email_is_challenged(self): + """The request carries the password the serializer requires, so only + the gate can refuse it.""" + response = self._patch_email( + {"email": "somewhere.else@example.org", "password": self.login_password} + ) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "change-email") + + @patch( + "onadata.libs.serializers.user_profile_serializer." + "send_verification_email.delay" + ) + def test_a_grant_lets_the_email_change_through(self, _send_verification): + grant = issue_grant(self.user.pk, "change-email") + + response = self._patch_email( + { + "email": "somewhere.else@example.org", + "password": self.login_password, + "grant": grant, + } + ) + + self.assertEqual(response.status_code, 200) + self.user.refresh_from_db() + self.assertEqual(self.user.email, "somewhere.else@example.org") + + def test_an_email_change_without_the_password_keeps_the_grant(self): + """The serializer requires the current password to change the email. + It checks this before the gate, so a request without it keeps the + grant.""" + grant = issue_grant(self.user.pk, "change-email") + old_email = self.user.email + + response = self._patch_email( + {"email": "somewhere.else@example.org", "grant": grant} + ) + + self.assertEqual(response.status_code, 400) + self.user.refresh_from_db() + self.assertEqual(self.user.email, old_email) + self.assertTrue(spend_grant(self.user.pk, "change-email", grant)) + + def test_an_email_change_with_a_wrong_password_keeps_the_grant(self): + # The wrong password is counted in the cache, which the test database + # rollback does not undo. + self.addCleanup(cache.clear) + grant = issue_grant(self.user.pk, "change-email") + old_email = self.user.email + + response = self._patch_email( + { + "email": "somewhere.else@example.org", + "password": "not-my-password", + "grant": grant, + } + ) + + self.assertEqual(response.status_code, 400) + self.user.refresh_from_db() + self.assertEqual(self.user.email, old_email) + self.assertTrue(spend_grant(self.user.pk, "change-email", grant)) + + @override_settings(MAX_LOGIN_ATTEMPTS=3) + def test_repeated_wrong_passwords_lock_out_the_email_change(self): + """The password check spends the login form's allowance, so it is + no way to guess the password around the lockout.""" + # The counter lives in the cache, which the test runner does not roll + # back. + cache.clear() + self.addCleanup(cache.clear) + new_email = {"email": "somewhere.else@example.org"} + challenged = self._patch_email({**new_email, "password": self.login_password}) + self.assertEqual(challenged.data["audience"], "change-email") + + with patch( + "onadata.libs.authentication.send_account_lockout_email.apply_async" + ): + first = self._patch_email({**new_email, "password": "not-my-password"}) + for _ in range(settings.MAX_LOGIN_ATTEMPTS - 1): + self._patch_email({**new_email, "password": "not-my-password"}) + + refused = self._patch_email({**new_email, "password": self.login_password}) + + self.assertEqual(first.status_code, 400) + self.assertEqual(first.data["non_field_errors"], ["Invalid password"]) + self.assertEqual(refused.status_code, 403, refused.data) + self.assertEqual(refused.data["reason"], "locked_out") + + def test_changing_the_password_is_challenged(self): + """The route already requires the current password. The second factor + proves what a password alone cannot.""" + new_password = "Tr0ub4dor-and-3-horses" + view = UserProfileViewSet.as_view({"post": "change_password"}) + request = self.factory.post( + "/", + data={ + "current_password": self.login_password, + "new_password": new_password, + }, + format="json", + **self.extra, + ) + + response = view(request, user=self.user.username) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "change-password") + self.user.refresh_from_db() + self.assertFalse(self.user.check_password(new_password)) + + def test_a_mistyped_current_password_keeps_the_grant(self): + """The password is checked before the gate, so the retry does not + need a second factor again.""" + new_password = "Tr0ub4dor-and-3-horses" + grant = issue_grant(self.user.pk, "change-password") + view = UserProfileViewSet.as_view({"post": "change_password"}) + # The failed attempt is counted in the cache, which the test database + # rollback does not undo. + username = self.user.username + self.addCleanup(cache.delete, f"{CHANGE_PASSWORD_ATTEMPTS}{username}") + self.addCleanup(cache.delete, f"{LOCKOUT_CHANGE_PASSWORD_USER}{username}") + + def change(current_password): + request = self.factory.post( + "/", + data={ + "current_password": current_password, + "new_password": new_password, + "grant": grant, + }, + format="json", + **self.extra, + ) + return view(request, user=self.user.username) + + self.assertEqual(change("not-my-password").status_code, 400) + self.assertEqual(change(self.login_password).status_code, 200) + self.user.refresh_from_db() + self.assertTrue(self.user.check_password(new_password)) + + def test_a_grant_lets_the_password_change_through(self): + new_password = "Tr0ub4dor-and-3-horses" + grant = issue_grant(self.user.pk, "change-password") + view = UserProfileViewSet.as_view({"post": "change_password"}) + request = self.factory.post( + "/", + data={ + "current_password": self.login_password, + "new_password": new_password, + "grant": grant, + }, + format="json", + **self.extra, + ) + + response = view(request, user=self.user.username) + + self.assertEqual(response.status_code, 200) + self.user.refresh_from_db() + self.assertTrue(self.user.check_password(new_password)) + + @patch( + "onadata.libs.serializers.user_profile_serializer." + "send_verification_email.delay" + ) + def test_patching_the_same_email_is_not_challenged(self, _send_verification): + """A PATCH that repeats the stored email changes nothing to gate. + + It carries the password the serializer requires with an email, so the + write does not fail for a reason unrelated to the gate. + """ + response = self._patch_email( + {"email": self.user.email, "password": self.login_password} + ) + + self.assertEqual(response.status_code, 200) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_username_gate.py b/onadata/apps/api/tests/viewsets/test_stepup_username_gate.py new file mode 100644 index 0000000000..081a479e2d --- /dev/null +++ b/onadata/apps/api/tests/viewsets/test_stepup_username_gate.py @@ -0,0 +1,120 @@ +# -*- coding: utf-8 -*- +""" +Tests for the step-up gate on changing an account's username. +""" + +from unittest.mock import patch + +from oidc.stepup_grants import issue_grant +from registration.models import RegistrationProfile + +from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import ( + StepUpGateTestCase, + gating, +) +from onadata.apps.api.viewsets.user_profile_viewset import UserProfileViewSet + +CHANGE_USERNAME = "change-username" +NEW_USERNAME = "robert" + + +@gating(CHANGE_USERNAME) +class TestChangeUsernameGate(StepUpGateTestCase): + """Renaming the account moves every URL, share and login built on the + old name, so a stolen session alone must not be able to do it.""" + + def setUp(self): + super().setUp() + # A full PUT re-sends the email, which reissues the activation key. + RegistrationProfile.objects.create_profile(self.user) + self.view = UserProfileViewSet.as_view( + {"patch": "partial_update", "put": "update"} + ) + self.assertEqual(self.user.username, "bob") + + def _patch(self, data, headers=None): + request = self.factory.patch( + "/", data=data, format="json", **{**self.extra, **(headers or {})} + ) + return self.view(request, user=self.user.username) + + def _put(self, data): + """A full write that repeats every stored value unless ``data`` + changes it. It sends the password the serializer requires with an + email.""" + payload = { + "username": self.user.username, + "email": self.user.email, + "password": self.login_password, + "first_name": self.user.first_name, + "last_name": self.user.last_name, + **data, + } + request = self.factory.put("/", data=payload, format="json", **self.extra) + return self.view(request, user=self.user.username) + + def _stored_username(self): + self.user.refresh_from_db() + return self.user.username + + def test_changing_the_username_without_a_grant_is_challenged(self): + response = self._patch({"username": NEW_USERNAME}) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], CHANGE_USERNAME) + self.assertEqual(self._stored_username(), "bob") + + @patch( + "onadata.libs.serializers.user_profile_serializer." + "send_verification_email.delay" + ) + def test_a_put_changing_the_username_without_a_grant_is_challenged( + self, _send_verification + ): + response = self._put({"username": NEW_USERNAME}) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], CHANGE_USERNAME) + self.assertEqual(self._stored_username(), "bob") + + def test_a_grant_lets_the_username_change_through(self): + grant = issue_grant(self.user.pk, CHANGE_USERNAME) + + response = self._patch( + {"username": NEW_USERNAME}, {"HTTP_X_STEP_UP_GRANT": grant} + ) + + self.assertEqual(response.status_code, 200) + self.assertEqual(self._stored_username(), NEW_USERNAME) + + def test_a_username_differing_only_as_the_serializer_cleans_it_is_not_challenged( + self, + ): + """The serializer trims and lowercases, so " BOB " writes "bob" back + unchanged. Comparing the raw value would challenge it.""" + self.assertEqual(self._patch({"username": NEW_USERNAME}).status_code, 401) + + response = self._patch({"username": " BOB "}) + + self.assertEqual(response.status_code, 200) + self.assertEqual(self._stored_username(), "bob") + + @patch( + "onadata.libs.serializers.user_profile_serializer." + "send_verification_email.delay" + ) + def test_a_put_echoing_the_username_is_not_challenged(self, _send_verification): + response = self._put({"city": "Nairobi"}) + + self.assertEqual(response.status_code, 200) + self.user.profile.refresh_from_db() + self.assertEqual(self.user.profile.city, "Nairobi") + + def test_an_unrelated_change_is_not_challenged(self): + self.assertEqual(self._patch({"username": NEW_USERNAME}).status_code, 401) + + response = self._patch({"city": "Nairobi"}) + + self.assertEqual(response.status_code, 200) + self.user.profile.refresh_from_db() + self.assertEqual(self.user.profile.city, "Nairobi") diff --git a/onadata/apps/api/tests/viewsets/test_stepup_viewset.py b/onadata/apps/api/tests/viewsets/test_stepup_viewset.py new file mode 100644 index 0000000000..c65419e28f --- /dev/null +++ b/onadata/apps/api/tests/viewsets/test_stepup_viewset.py @@ -0,0 +1,233 @@ +# -*- coding: utf-8 -*- +""" +Tests for the federated step-up endpoints a client's popup drives. +""" + +import time +from unittest.mock import patch +from urllib.parse import parse_qs, urlparse + +from django.contrib.auth import get_user_model +from django.core.cache import cache +from django.test import TestCase +from django.test.utils import override_settings +from django.urls import reverse + +from oidc.stepup_grants import spend_grant + +from onadata.apps.api.tests.viewsets.test_abstract_viewset import TestAbstractViewSet +from onadata.apps.api.viewsets.stepup_viewset import StepUpViewSet +from onadata.libs.stepup.federated import start_step_up + +STEP_UP_FEDERATED = { + "MODE": "federated", + "ACTIONS": ["require-auth-toggle"], +} + +SERVERS = { + "kc": { + "AUTHORIZATION_ENDPOINT": "https://idp.example/auth", + "CLIENT_ID": "app", + "CLIENT_SECRET": "secret", + "TOKEN_ENDPOINT": "https://idp.example/token", + "JWKS_ENDPOINT": "https://idp.example/certs", + "REDIRECT_URI": "https://ona.example/oidc/kc/callback", + "SCOPE": "openid profile email", + "USE_PKCE": True, + "STEP_UP": { + "CLAIM": "acr", + "SATISFIED_BY": ["gold"], + "MAX_AGE": 0, + "MAX_AUTH_AGE_SECONDS": 300, + "REQUIRE_AUTH_TIME": True, + "SUBJECT_CLAIM": "email", + "SUBJECT_FIELD": "email", + "REDIRECT_URI": "https://ona.example/api/v1/stepup/callback", + }, + } +} + +SATISFYING = {"acr": "gold", "email": "ana@example.org"} + + +class TestStepUpViewSet(TestAbstractViewSet): + """Where the popup starts, and what comes back to it.""" + + def _start(self, audience): + view = StepUpViewSet.as_view({"get": "start"}) + return view(self.factory.get("/", {"audience": audience}, **self.extra)) + + def _callback(self, accept=None, **params): + view = StepUpViewSet.as_view({"get": "callback"}) + extra = dict(self.extra) + if accept: + extra["HTTP_ACCEPT"] = accept + return view(self.factory.get("/", params, **extra)) + + @override_settings(STEP_UP={"MODE": "local", "ACTIONS": ["a"]}) + def test_start_refuses_when_the_factor_is_local(self): + """Local mode checks the code against OnaData, so there is nothing to + redirect to.""" + response = self._start("a") + self.assertEqual(response.status_code, 400) + self.assertEqual(response.data["error"], "not_federated") + + @override_settings(STEP_UP=STEP_UP_FEDERATED) + def test_start_refuses_an_audience_that_is_not_gated(self): + """Otherwise any caller could mint a grant for an ungated action.""" + response = self._start("something-else") + self.assertEqual(response.status_code, 400) + self.assertEqual(response.data["error"], "not_gated") + + @override_settings(STEP_UP=STEP_UP_FEDERATED) + def test_start_returns_the_authorization_url(self): + # Patched where the viewset looks it up, not where it is defined. + with patch( + "onadata.apps.api.viewsets.stepup_viewset.start_step_up", + return_value=("https://idp.test/authorize?acr_values=mfa", "state-1"), + ): + response = self._start("require-auth-toggle") + + self.assertEqual(response.status_code, 200) + self.assertEqual( + response.data["authorizationUrl"], + "https://idp.test/authorize?acr_values=mfa", + ) + + @override_settings(STEP_UP=STEP_UP_FEDERATED) + def test_start_reports_a_deployment_with_nowhere_to_send_the_user(self): + """A server without its endpoints is a deployment fault, not the + user's. It must not end in a traceback.""" + with patch( + "onadata.apps.api.viewsets.stepup_viewset.start_step_up", + side_effect=ValueError("no AUTHORIZATION_ENDPOINT"), + ): + response = self._start("require-auth-toggle") + + self.assertEqual(response.status_code, 503) + self.assertEqual(response.data["error"], "step_up_unavailable") + + @override_settings( + STEP_UP=STEP_UP_FEDERATED, STEP_UP_POPUP_ORIGIN="https://app.test" + ) + def test_popup_posts_the_grant_only_to_this_deployments_origin(self): + """The grant is a bearer credential. A ``*`` target hands it to anyone.""" + with patch( + "onadata.apps.api.viewsets.stepup_viewset.StepUpViewSet.complete_step_up", + return_value=("grant-42", None), + ): + response = self._callback(accept="text/html", code="c", state="s") + + self.assertEqual(response.status_code, 200) + body = response.content.decode() + self.assertIn('"https://app.test"', body) + self.assertNotIn('"*"', body) + self.assertIn("grant-42", body) + + @override_settings( + STEP_UP=STEP_UP_FEDERATED, STEP_UP_POPUP_ORIGIN="https://app.test" + ) + def test_a_cancelled_prompt_still_reports_back_to_the_opener(self): + """The provider returns ``error`` and no code. A bare 400 would leave + the opener waiting.""" + response = self._callback(accept="text/html", error="access_denied", state="s") + + self.assertEqual(response.status_code, 200) + body = response.content.decode() + self.assertIn("postMessage", body) + self.assertIn('"error": "provider_error"', body) + + @override_settings(STEP_UP=STEP_UP_FEDERATED) + def test_the_callback_accepts_the_django_session(self): + """The popup returning from the provider carries cookies, not a + token.""" + self.client.force_login(self.user) + with patch( + "onadata.apps.api.viewsets.stepup_viewset.StepUpViewSet.complete_step_up", + return_value=("grant-7", None), + ): + response = self.client.get( + reverse("stepup-callback"), {"code": "c", "state": "s"} + ) + + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["grant"], "grant-7") + + @override_settings(STEP_UP=STEP_UP_FEDERATED) + def test_callback_rejects_a_request_with_no_code_or_state(self): + response = self._callback(code="", state="") + self.assertEqual(response.status_code, 400) + self.assertEqual(response.data["error"], "invalid_request") + + @override_settings(STEP_UP=STEP_UP_FEDERATED) + def test_a_refused_step_up_is_a_403_carrying_its_reason(self): + """A 403, not a 200 a caller might read as success. It carries the + reason code the popup would receive.""" + with patch( + "onadata.apps.api.viewsets.stepup_viewset.StepUpViewSet.complete_step_up", + return_value=(None, "auth_time_stale"), + ): + response = self._callback(code="c", state="s") + self.assertEqual(response.status_code, 403) + self.assertEqual(response.data["error"], "step_up_failed") + self.assertEqual(response.data["reason"], "auth_time_stale") + + @override_settings(STEP_UP=STEP_UP_FEDERATED) + def test_a_completed_step_up_returns_the_grant(self): + with patch( + "onadata.apps.api.viewsets.stepup_viewset.StepUpViewSet.complete_step_up", + return_value=("grant-42", None), + ): + response = self._callback(code="c", state="s") + self.assertEqual(response.status_code, 200) + self.assertEqual(response.data, {"grant": "grant-42"}) + self.assertEqual(response["Cache-Control"], "no-store") + + +@override_settings( + OPENID_CONNECT_AUTH_SERVERS=SERVERS, + STEP_UP={"ACTIONS": {"require-auth-toggle"}, "MODE": "federated"}, +) +class TestFederatedStepUp(TestCase): + """OnaData's half of a federated step-up. + + ona-oidc owns and tests the protocol half. That covers the authorize URL, + PKCE, claim matching and freshness. These tests cover what OnaData owns. + The grant goes to the signed-in user, for the action they asked for, and + to nobody else. + """ + + def setUp(self): + cache.clear() + self.user = get_user_model().objects.create( + username="ana", email="ana@example.org" + ) + url, self.state = start_step_up("kc", "require-auth-toggle", self.user) + self.nonce = parse_qs(urlparse(url).query)["nonce"][0] + + def _complete(self, claims, user=None, state=None): + claims = {"auth_time": time.time(), "nonce": self.nonce, **claims} + with patch( + "oidc.stepup.OpenIDClient.retrieve_tokens_using_auth_code", + return_value={"id_token": "t"}, + ), patch( + "oidc.stepup.OpenIDClient.verify_and_decode_id_token", return_value=claims + ): + request = type("R", (), {"user": user or self.user})() + return StepUpViewSet().complete_step_up( + request, code="c", state=state or self.state, auth_server="kc" + ) + + def test_a_satisfying_token_yields_a_grant_for_that_audience(self): + grant, reason = self._complete(SATISFYING) + + self.assertIsNone(reason) + self.assertTrue(spend_grant(self.user.pk, "require-auth-toggle", grant)) + + def test_state_belonging_to_another_user_is_refused(self): + other = get_user_model().objects.create(username="bo", email="bo@example.org") + + grant, reason = self._complete(SATISFYING, user=other) + + self.assertIsNone(grant) + self.assertEqual(reason, "state_user_mismatch") diff --git a/onadata/apps/api/tests/viewsets/test_totp_viewset.py b/onadata/apps/api/tests/viewsets/test_totp_viewset.py index 0f4798efe9..77ff3d465f 100644 --- a/onadata/apps/api/tests/viewsets/test_totp_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_totp_viewset.py @@ -20,6 +20,7 @@ from cryptography.fernet import Fernet from django_otp.plugins.otp_static.models import StaticDevice +from oidc.stepup_grants import spend_grant from rest_framework.authtoken.models import Token from rest_framework.test import APIRequestFactory from two_factor.utils import default_device @@ -37,6 +38,7 @@ TOTPViewSet, _verify_recovery, ) +from onadata.libs.stepup.policy import GATE_REQUIRE_AUTH from onadata.libs.test_utils.sso import sso_token from onadata.libs.utils.field_encryption import decrypt @@ -81,13 +83,12 @@ def current_code(hex_key, step=30, digits=6): return str(truncated % (10**digits)).zfill(digits) -# The password requirement is pinned off for the class so these cases assert -# enrolment mechanics rather than whichever way the running deployment has it -# set -- the local stack turns it on, CI does not. The cases that are about -# the password say so individually. +# Pin these settings. Inherited values would make the tests depend on the +# environment. Every case here runs OnaData-managed two-factor on a deployment +# that enabled it. @override_settings( ENABLE_TWO_FACTOR=True, - TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD=False, + STEP_UP={"MODE": "local"}, TWO_FACTOR_FIELD_ENCRYPTION_KEYS=[TEST_ENCRYPTION_KEY], ) class TestTOTPViewSet(TestAbstractViewSet): @@ -181,7 +182,9 @@ def test_header_borne_sso_post_needs_no_csrf_token(self): """The SSO header a server-side caller forwards is one no cross-site page can set, so that path stays exempt even under CSRF enforcement.""" view = TOTPViewSet.as_view({"post": "enroll_start"}) - request = self.csrf_factory.post("/", data={}, **self._sso()) + request = self.csrf_factory.post( + "/", data={"password": self.login_password}, **self._sso() + ) response = view(request) self.assertEqual(response.status_code, 201) @@ -189,7 +192,9 @@ def test_cookie_borne_sso_post_passes_with_a_valid_csrf_token(self): """With the matching token the same cookie request goes through.""" token = get_token(self.csrf_factory.get("/")) view = TOTPViewSet.as_view({"post": "enroll_start"}) - request = self.csrf_factory.post("/", data={}, HTTP_X_CSRFTOKEN=token) + request = self.csrf_factory.post( + "/", data={"password": self.login_password}, HTTP_X_CSRFTOKEN=token + ) request.COOKIES["SSO"] = self._sso_cookie() request.COOKIES["csrftoken"] = token response = view(request) @@ -228,8 +233,24 @@ def test_a_second_factor_of_another_kind_is_not_ignored(self): status_body = self._get_status().data self.assertTrue(status_body["methods"]) - def test_enrolment_creates_a_recovery_set(self): - """Enrolment leaves one recovery device holding the codes. + def test_status_reports_what_this_deployment_supports(self): + """A client reads this instead of its own config, so the two cannot + disagree about whether two-factor is manageable here.""" + response = self._get_status() + + self.assertEqual(response.data["managedBy"], "onadata") + self.assertEqual( + response.data["capabilities"], + { + "enroll": True, + "disable": True, + "recoveryCodes": True, + "verify": True, + }, + ) + + def test_recovery_codes_are_the_set_two_factors_backup_step_reads(self): + """One recovery set, and it is the one the login wizard reads. The wizard reads this same device by name on its backup step, so the set the API writes is the set the login path verifies against. @@ -254,7 +275,7 @@ def test_enrollment_needs_a_code_from_the_device(self): """The pending device must not count as a second factor until the user has proved they can read it -- otherwise a misscanned QR locks them out of their own account.""" - self._post_session("enroll_start") + self._post_session("enroll_start", {"password": self.login_password}) response = self._post_session("enroll_confirm", {"code": "000000"}) self.assertEqual(response.status_code, 403) @@ -277,7 +298,7 @@ def test_enrolment_is_all_or_nothing(self): """An authenticator that confirmed while its recovery codes did not is one lost phone away from a locked account, so both land in the same transaction.""" - self._post_session("enroll_start") + self._post_session("enroll_start", {"password": self.login_password}) device = EncryptedTOTPDevice.objects.get(user=self.user, confirmed=False) with ( @@ -295,11 +316,12 @@ def test_enrolment_is_all_or_nothing(self): def test_starting_again_replaces_the_pending_device(self): """Re-scanning must not leave the previous attempt behind: two unconfirmed devices means the code from either one works.""" - self._post_session("enroll_start") - self._post_session("enroll_start") + self._post_session("enroll_start", {"password": self.login_password}) + self._post_session("enroll_start", {"password": self.login_password}) self.assertEqual( - EncryptedTOTPDevice.objects.filter(user=self.user, confirmed=False).count(), 1 + EncryptedTOTPDevice.objects.filter(user=self.user, confirmed=False).count(), + 1, ) def test_replacing_an_authenticator_needs_step_up(self): @@ -341,9 +363,9 @@ def test_replacing_an_authenticator_revokes_the_old(self): self.assertEqual( list( - EncryptedTOTPDevice.objects.filter(user=self.user, confirmed=True).values_list( - "pk", flat=True - ) + EncryptedTOTPDevice.objects.filter( + user=self.user, confirmed=True + ).values_list("pk", flat=True) ), [new.pk], ) @@ -390,7 +412,9 @@ def test_disable_with_a_current_code_removes_everything(self): self.assertEqual(response.status_code, 200) self.assertFalse(EncryptedTOTPDevice.objects.filter(user=self.user).exists()) - self.assertFalse(EncryptedRecoveryDevice.objects.filter(user=self.user).exists()) + self.assertFalse( + EncryptedRecoveryDevice.objects.filter(user=self.user).exists() + ) def test_recovery_codes_need_an_authenticator_first(self): response = self._post_with_api_key("recovery_generate", {"code": "000000"}) @@ -686,6 +710,21 @@ def test_a_grant_is_spendable_only_on_what_it_was_earned_for(self): self.assertEqual(response.status_code, 403) self.assertTrue(EncryptedTOTPDevice.objects.filter(user=self.user).exists()) + def test_verify_issues_a_grant_for_a_gated_action(self): + """A gated action's challenge names the action as its audience, so + verify must mint a grant that action can spend.""" + device = self._enroll() + + with next_totp_window(): + response = self._verify( + {"code": current_code(device.key), "audience": GATE_REQUIRE_AUTH} + ) + + self.assertEqual(response.status_code, 200, response.data) + self.assertTrue( + spend_grant(self.user.pk, GATE_REQUIRE_AUTH, response.data["grant"]) + ) + def test_verify_refuses_an_audience_the_deployment_does_not_know(self): """Omitted and mistyped are the same refusal, and neither costs a code. @@ -739,7 +778,7 @@ def test_enrolment_refuses_an_api_key(self): def test_confirming_enrolment_refuses_an_api_key(self): """The second half of enrolment refuses a key for the same reason -- and it is the half that hands back the recovery codes.""" - self._post_session("enroll_start") + self._post_session("enroll_start", {"password": self.login_password}) device = EncryptedTOTPDevice.objects.get(user=self.user, confirmed=False) response = self._post_with_api_key( @@ -771,7 +810,7 @@ def test_an_api_key_works_where_a_code_is_demanded(self): def test_disable_removes_a_factor_of_another_kind(self): """Disable must clear whatever the login view would challenge on. - _has_second_factor asks default_device(), which answers on a confirmed + has_second_factor asks default_device(), which answers on a confirmed device of any class named "default". Removing only the TOTP and static rows would report two-factor as off while leaving such a device standing -- and this module cannot verify one, so the account would be @@ -839,7 +878,9 @@ def test_a_grant_does_not_work_for_another_user(self): # Mallory needs an authenticator of their own, or disable short-circuits # on "nothing to remove" and never consults the grant at all -- the test # would pass without the guard it is here to pin. - EncryptedTOTPDevice.objects.create(user=other, name=TOTP_DEVICE_NAME, confirmed=True) + EncryptedTOTPDevice.objects.create( + user=other, name=TOTP_DEVICE_NAME, confirmed=True + ) view = TOTPViewSet.as_view({"post": "disable"}) request = self.factory.post( "/", data={"grant": grant}, HTTP_AUTHORIZATION=f"Token {token}" @@ -854,7 +895,7 @@ def test_enrollment_payload_carries_the_secret_three_ways(self): authenticator app accepts.""" import base64 - response = self._post_session("enroll_start") + response = self._post_session("enroll_start", {"password": self.login_password}) device = EncryptedTOTPDevice.objects.get(user=self.user, confirmed=False) self.assertTrue(response.data["qrDataUrl"].startswith("data:image/png;base64,")) @@ -863,14 +904,6 @@ def test_enrollment_payload_carries_the_secret_three_ways(self): padded = b32 + "=" * (-len(b32) % 8) self.assertEqual(base64.b32decode(padded).hex(), device.key) - @override_settings(TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD=False) - def test_first_enrolment_needs_no_password_when_not_asked_for(self): - """Switched off, enrolment is unchanged.""" - response = self._post_session("enroll_start") - - self.assertEqual(response.status_code, 201) - - @override_settings(TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD=True) def test_first_enrolment_refuses_without_the_account_password(self): """A session alone must not add a factor to an unprotected account. @@ -890,21 +923,18 @@ def test_first_enrolment_refuses_without_the_account_password(self): "a device was minted despite the refusal", ) - @override_settings(TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD=True) def test_first_enrolment_accepts_the_account_password(self): response = self._post_session("enroll_start", {"password": self.login_password}) self.assertEqual(response.status_code, 201) self.assertIn("otpauthUri", response.data) - @override_settings(TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD=True) def test_first_enrolment_refuses_a_wrong_password(self): response = self._post_session("enroll_start", {"password": "not-it"}) self.assertEqual(response.status_code, 403) self.assertFalse(EncryptedTOTPDevice.objects.filter(user=self.user).exists()) - @override_settings(TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD=True) def test_enrolment_password_failures_count_towards_the_login_lockout(self): """Guesses here spend the same allowance as guesses at the login form. @@ -942,7 +972,6 @@ def start_enrolment(password): self.assertEqual(refused.data["reason"], "locked_out") self.assertFalse(EncryptedTOTPDevice.objects.filter(user=user).exists()) - @override_settings(TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD=True) def test_an_account_with_no_password_cannot_enrol(self): """Having no password is not a way past the password. @@ -968,7 +997,6 @@ def test_an_account_with_no_password_cannot_enrol(self): self.assertEqual(response.data["reason"], "no_password_set") self.assertFalse(EncryptedTOTPDevice.objects.filter(user=passwordless).exists()) - @override_settings(TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD=True) def test_re_enrolment_still_asks_for_a_code_not_a_password(self): """An account that has a factor proves presence with that factor.""" device = self._enroll() @@ -1321,13 +1349,9 @@ def test_a_code_gated_action_treats_an_absent_code_as_incomplete(self): self.assertEqual(response.data["reason"], "code_required") self.assertTrue( - EncryptedTOTPDevice.objects.filter( - user=self.user, confirmed=True - ).exists() - ) - self.assertEqual( - [m for m in mail.outbox if self.user.email in m.to], [] + EncryptedTOTPDevice.objects.filter(user=self.user, confirmed=True).exists() ) + self.assertEqual([m for m in mail.outbox if self.user.email in m.to], []) @override_settings(TWO_FACTOR_FAILURE_ALERT_THRESHOLD=0) def test_failure_alerting_can_be_disabled(self): @@ -1391,9 +1415,7 @@ def test_a_recovery_attempt_does_not_throttle_the_authenticator(self): device.refresh_from_db() self.assertEqual(device.throttling_failure_count, 0) - @override_settings( - TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD=True, MAX_LOGIN_ATTEMPTS=3 - ) + @override_settings(MAX_LOGIN_ATTEMPTS=3) @patch("onadata.libs.authentication.send_account_lockout_email.apply_async") def test_a_missing_enrolment_password_does_not_spend_the_lockout(self, _mock): """Probing for the required reason with no password is an incomplete @@ -1417,12 +1439,9 @@ def test_a_login_session_can_reach_the_endpoints(self): @override_settings(ENABLE_TWO_FACTOR=True) class SecureEnrolmentDefaultTestCase(TestAbstractViewSet): - """First enrolment demands the account password by default. - - The password setting is left unpinned on purpose: this asserts the - shipped default is fail-closed, so an SSO credential alone cannot enrol a - factor and lock the owner out of their own second factor. - """ + """First enrolment requires the account password, so an SSO credential + alone cannot enrol a factor and lock the owner out of their own second + factor.""" def _sso(self): return {"HTTP_SSO": sso_token(self.user.email)} @@ -1483,3 +1502,56 @@ def test_nothing_is_enrolled(self): self.assertEqual(view(self.factory.post("/")).status_code, 404) self.assertFalse(EncryptedTOTPDevice.objects.exists()) + + +# Keep ENABLE_TWO_FACTOR on. The flag is checked before the mode, so with +# two-factor off these routes answer 404 and this class would assert the wrong +# refusal. +@override_settings(ENABLE_TWO_FACTOR=True, STEP_UP={"MODE": "federated"}) +class TestFederatedRefusesLocalManagement(TestAbstractViewSet): + """When an identity provider owns the factor, OnaData manages none. + + The status route reports every capability as false, but a client may + ignore it. Left ungated, these routes would enrol a device that the login + path never challenges. + """ + + def _post(self, handler, data=None): + view = TOTPViewSet.as_view({"post": handler}) + return view(self.factory.post("/", data=data or {}, **self.extra)) + + def test_enrolment_is_refused(self): + self.assertEqual(self._post("enroll_start").status_code, 409) + + def test_enrolment_confirmation_is_refused(self): + response = self._post("enroll_confirm", {"code": "123456"}) + self.assertEqual(response.status_code, 409) + + def test_disable_is_refused(self): + self.assertEqual(self._post("disable").status_code, 409) + + def test_recovery_code_generation_is_refused(self): + """A user with no device gets 409 here anyway, so the reason is what + shows the federated refusal fired.""" + response = self._post("recovery_generate") + self.assertEqual(response.status_code, 409) + self.assertEqual(response.data["error"], "not_managed_here") + + def test_reading_the_recovery_set_is_refused(self): + """Reading is refused wherever generating is, since both act on the + same set of codes.""" + self.assertEqual(self._post("recovery_view").status_code, 409) + + def test_local_code_verification_is_refused(self): + """The local-totp dialect does not apply. A grant here would be + issued without asking the identity provider.""" + response = self._post("verify", {"code": "123456"}) + self.assertEqual(response.status_code, 409) + + def test_status_still_answers(self): + """This route answers in both modes. It is how a caller learns that + the identity provider manages the factor.""" + view = TOTPViewSet.as_view({"get": "totp_status"}) + response = view(self.factory.get("/", **self.extra)) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.data["managedBy"], "idp") diff --git a/onadata/apps/api/tests/viewsets/test_totp_viewset_concurrency.py b/onadata/apps/api/tests/viewsets/test_totp_viewset_concurrency.py index f2525e73b5..07c8a75ff4 100644 --- a/onadata/apps/api/tests/viewsets/test_totp_viewset_concurrency.py +++ b/onadata/apps/api/tests/viewsets/test_totp_viewset_concurrency.py @@ -42,9 +42,7 @@ TEST_KEY = Fernet.generate_key().decode() -@override_settings( - ENABLE_TWO_FACTOR=True, TWO_FACTOR_FIELD_ENCRYPTION_KEYS=[TEST_KEY] -) +@override_settings(ENABLE_TWO_FACTOR=True, TWO_FACTOR_FIELD_ENCRYPTION_KEYS=[TEST_KEY]) class RecoveryCodeConcurrencyTestCase(TransactionTestCase): """A recovery code is single-use, including against itself.""" @@ -104,9 +102,7 @@ def test_one_code_is_spent_once_however_many_callers_race(self): ) -@override_settings( - ENABLE_TWO_FACTOR=True, TWO_FACTOR_FIELD_ENCRYPTION_KEYS=[TEST_KEY] -) +@override_settings(ENABLE_TWO_FACTOR=True, TWO_FACTOR_FIELD_ENCRYPTION_KEYS=[TEST_KEY]) class TotpCodeConcurrencyTestCase(TransactionTestCase): """One authenticator code buys one verification, not one per worker.""" @@ -154,9 +150,7 @@ def worker(): ) -@override_settings( - ENABLE_TWO_FACTOR=True, TWO_FACTOR_FIELD_ENCRYPTION_KEYS=[TEST_KEY] -) +@override_settings(ENABLE_TWO_FACTOR=True, TWO_FACTOR_FIELD_ENCRYPTION_KEYS=[TEST_KEY]) class EnrolmentConfirmationConcurrencyTestCase(TransactionTestCase): """A pending authenticator is confirmed by exactly one request. @@ -224,7 +218,7 @@ def worker(): @override_settings( ENABLE_TWO_FACTOR=True, - TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD=False, + STEP_UP={"MODE": "local"}, TWO_FACTOR_FIELD_ENCRYPTION_KEYS=[TEST_KEY], ) class EnrolmentStartConcurrencyTestCase(TransactionTestCase): @@ -237,8 +231,9 @@ class EnrolmentStartConcurrencyTestCase(TransactionTestCase): def setUp(self): super().setUp() + self.password = "pw-9F3kz" self.user = User.objects.create_user( - "startrace", "startrace@example.com", "pw-9F3kz" + "startrace", "startrace@example.com", self.password ) def test_racing_starts_leave_one_pending_device(self): @@ -249,7 +244,9 @@ def test_racing_starts_leave_one_pending_device(self): def worker(): try: - request = APIRequestFactory().post("/", data={}, HTTP_SSO=sso) + request = APIRequestFactory().post( + "/", data={"password": self.password}, HTTP_SSO=sso + ) barrier.wait(timeout=10) response = TOTPViewSet.as_view({"post": "enroll_start"})(request) with guard: @@ -274,9 +271,7 @@ def worker(): ) -@override_settings( - ENABLE_TWO_FACTOR=True, TWO_FACTOR_FIELD_ENCRYPTION_KEYS=[TEST_KEY] -) +@override_settings(ENABLE_TWO_FACTOR=True, TWO_FACTOR_FIELD_ENCRYPTION_KEYS=[TEST_KEY]) class WizardVerifyConcurrencyTestCase(TransactionTestCase): """The login wizard verifies through the device's own ``verify_token``, without the row lock the viewset helpers take -- so ``verify_token`` must @@ -326,9 +321,7 @@ def test_a_recovery_code_verify_token_spends_once(self): ) self.assertEqual(len(results), CONCURRENT, "a worker did not finish") - self.assertEqual( - sum(results), 1, f"the code was accepted {sum(results)} times" - ) + self.assertEqual(sum(results), 1, f"the code was accepted {sum(results)} times") def test_a_totp_code_verify_token_spends_once(self): device = EncryptedTOTPDevice.objects.create( diff --git a/onadata/apps/api/tests/viewsets/test_user_profile_viewset.py b/onadata/apps/api/tests/viewsets/test_user_profile_viewset.py index db9e174069..a105eeb72e 100644 --- a/onadata/apps/api/tests/viewsets/test_user_profile_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_user_profile_viewset.py @@ -19,7 +19,9 @@ import requests from django_digest.test import DigestAuth +from django_otp.plugins.otp_totp.models import TOTPDevice from httmock import HTTMock, all_requests +from oidc.stepup_grants import issue_grant, spend_grant from registration.models import RegistrationProfile from rest_framework.authtoken.models import Token from reversion.models import Version @@ -36,6 +38,7 @@ from onadata.libs.authentication import DigestAuthentication from onadata.libs.permissions import EditorRole from onadata.libs.serializers.user_profile_serializer import _get_first_last_names +from onadata.libs.stepup.drf import RequiresStepUp from onadata.libs.utils.cache_tools import USER_PROFILE_PREFIX User = get_user_model() @@ -652,6 +655,307 @@ def test_profile_update_is_audit_logged(self): }, ) + @override_settings(STEP_UP={"ACTIONS": {"require-auth-toggle"}, "MODE": "local"}) + def test_a_put_is_gated_like_a_patch(self): + """The gate belongs to the change, not the verb. + + ``ModelViewSet`` routes PUT to ``update`` and PATCH to + ``partial_update``. Both write require_auth, so gating only one leaves + the other open. + """ + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + before = UserProfile.objects.get(user=self.user).require_auth + view = UserProfileViewSet.as_view({"put": "update"}) + + request = self.factory.put( + "/", + data={ + "username": self.user.username, + "name": "Bob", + "email": self.user.email, + "password": self.login_password, + "require_auth": not before, + }, + **self.extra, + ) + response = view(request, user=self.user.username) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["error"], "step_up_required") + self.assertEqual(UserProfile.objects.get(user=self.user).require_auth, before) + + @override_settings(STEP_UP={"ACTIONS": {"require-auth-toggle"}, "MODE": "local"}) + @patch( + "onadata.libs.serializers.user_profile_serializer." + "send_verification_email.delay" + ) + def test_a_form_put_omitting_require_auth_is_gated(self, _send_verification): + """A form-encoded PUT that leaves out a boolean writes it as false. + + DRF reads an absent checkbox that way, so omitting the field switches + the setting off. The gate has to read it the same way. + """ + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + RegistrationProfile.objects.create_profile(self.user) + profile = UserProfile.objects.get(user=self.user) + profile.require_auth = True + profile.save() + view = UserProfileViewSet.as_view({"put": "update"}) + + request = self.factory.put( + "/", + data={ + "username": self.user.username, + "name": "Bob", + "email": self.user.email, + "password": self.login_password, + }, + format="multipart", + **self.extra, + ) + response = view(request, user=self.user.username) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "require-auth-toggle") + self.assertTrue(UserProfile.objects.get(user=self.user).require_auth) + + @override_settings(STEP_UP={"ACTIONS": {"require-auth-toggle"}, "MODE": "local"}) + @patch( + "onadata.libs.serializers.user_profile_serializer." + "send_verification_email.delay" + ) + def test_a_json_put_omitting_require_auth_is_not_challenged( + self, _send_verification + ): + """JSON has no checkbox semantics. An absent key leaves the setting + alone, so there is nothing to gate.""" + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + RegistrationProfile.objects.create_profile(self.user) + profile = UserProfile.objects.get(user=self.user) + profile.require_auth = True + profile.save() + refused = self.factory.patch("/", data={"require_auth": False}, **self.extra) + self.assertEqual(self.view(refused, user=self.user.username).status_code, 401) + view = UserProfileViewSet.as_view({"put": "update"}) + + request = self.factory.put( + "/", + data={ + "username": self.user.username, + "name": "Bob", + "email": self.user.email, + "password": self.login_password, + }, + format="json", + **self.extra, + ) + response = view(request, user=self.user.username) + + self.assertEqual(response.status_code, 200) + self.assertTrue(UserProfile.objects.get(user=self.user).require_auth) + + @override_settings(STEP_UP={"ACTIONS": {"require-auth-toggle"}, "MODE": "local"}) + def test_echoing_require_auth_unchanged_is_not_challenged(self): + """A full-profile write sends require_auth back unchanged. Gating on + its presence would challenge a name or city edit. Only a change is + gated.""" + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + before = UserProfile.objects.get(user=self.user).require_auth + refused = self.factory.patch( + "/", data={"require_auth": not before}, **self.extra + ) + self.assertEqual(self.view(refused, user=self.user.username).status_code, 401) + + request = self.factory.patch( + "/", data={"require_auth": before, "city": "Nairobi"}, **self.extra + ) + response = self.view(request, user=self.user.username) + + self.assertEqual(response.status_code, 200) + self.assertEqual(UserProfile.objects.get(user=self.user).city, "Nairobi") + + @override_settings(STEP_UP={"ACTIONS": {"require-auth-toggle"}, "MODE": "local"}) + def test_a_grant_lets_require_auth_change(self): + """With a grant for the toggle the require_auth change lands.""" + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + before = UserProfile.objects.get(user=self.user).require_auth + grant = issue_grant(self.user.pk, "require-auth-toggle") + + request = self.factory.patch( + "/", data={"require_auth": not before, "grant": grant}, **self.extra + ) + response = self.view(request, user=self.user.username) + + self.assertEqual(response.status_code, 200) + self.assertEqual( + UserProfile.objects.get(user=self.user).require_auth, not before + ) + + @override_settings( + STEP_UP={"ACTIONS": {"privacy-consent"}, "MODE": "local"}, + EU_CONSENT_METADATA_PATH=("outer", "eu_citizen_consent"), + ) + def test_overwrite_merge_cannot_change_nested_consent_without_step_up(self): + """The overwrite=false merge writes keys by name anywhere in the tree. + A top-level key that lands on a nested consent leaf must still be + gated. A path-based check on the raw payload would miss it.""" + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + profile = UserProfile.objects.get(user=self.user) + profile.metadata = {"outer": {"eu_citizen_consent": "yes"}} + profile.save() + + data = { + "metadata": json.dumps({"eu_citizen_consent": "no"}), + "overwrite": "false", + } + request = self.factory.patch("/", data=data, **self.extra) + response = self.view(request, user=self.user.username) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["error"], "step_up_required") + self.assertEqual(response.data["audience"], "privacy-consent") + self.assertEqual( + UserProfile.objects.get(user=self.user).metadata, + {"outer": {"eu_citizen_consent": "yes"}}, + ) + + @override_settings( + STEP_UP={"ACTIONS": {"privacy-consent"}, "MODE": "local"}, + EU_CONSENT_METADATA_PATH=("outer", "eu_citizen_consent"), + ) + def test_overwrite_merge_leaving_consent_alone_is_not_challenged(self): + """Consent is gated only when the merge changes it.""" + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + profile = UserProfile.objects.get(user=self.user) + profile.metadata = {"outer": {"eu_citizen_consent": "yes"}} + profile.save() + consent_change = { + "metadata": json.dumps({"eu_citizen_consent": "no"}), + "overwrite": "false", + } + refused = self.factory.patch("/", data=consent_change, **self.extra) + self.assertEqual(self.view(refused, user=self.user.username).status_code, 401) + + data = {"metadata": json.dumps({"city": "Nairobi"}), "overwrite": "false"} + request = self.factory.patch("/", data=data, **self.extra) + response = self.view(request, user=self.user.username) + + self.assertEqual(response.status_code, 200) + self.assertEqual( + UserProfile.objects.get(user=self.user).metadata, + {"outer": {"eu_citizen_consent": "yes"}, "city": "Nairobi"}, + ) + + @override_settings(STEP_UP={"ACTIONS": {"require-auth-toggle"}, "MODE": "local"}) + def test_an_invalid_sibling_field_keeps_the_require_auth_grant(self): + """The whole request is validated before the gate, so a field the + write would reject answers 400 and leaves the grant for the retry.""" + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + before = UserProfile.objects.get(user=self.user).require_auth + grant = issue_grant(self.user.pk, "require-auth-toggle") + + request = self.factory.patch( + "/", + data={"require_auth": not before, "twitter": "not a handle!"}, + format="json", + HTTP_X_STEP_UP_GRANT=grant, + **self.extra, + ) + response = self.view(request, user=self.user.username) + + self.assertEqual(response.status_code, 400) + self.assertIn("twitter", response.data) + self.assertEqual(UserProfile.objects.get(user=self.user).require_auth, before) + self.assertTrue(spend_grant(self.user.pk, "require-auth-toggle", grant)) + + @override_settings(STEP_UP={"ACTIONS": {"require-auth-toggle"}, "MODE": "local"}) + def test_a_patch_gates_once(self): + """partial_update delegates to update. The gate must run in only one + of them, or every check behind it runs twice. The request needs a + grant, because a refusal returns before a second run could happen.""" + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + before = UserProfile.objects.get(user=self.user).require_auth + grant = issue_grant(self.user.pk, "require-auth-toggle") + + with patch.object( + UserProfileViewSet, + "gated_change_refusal", + autospec=True, + side_effect=RequiresStepUp.gated_change_refusal, + ) as gate: + request = self.factory.patch( + "/", + data={"require_auth": not before, "grant": grant}, + format="json", + **self.extra, + ) + response = self.view(request, user=self.user.username) + + self.assertEqual(response.status_code, 200) + self.assertEqual( + UserProfile.objects.get(user=self.user).require_auth, not before + ) + gate.assert_called_once() + + @override_settings( + STEP_UP={"ACTIONS": {"privacy-consent"}, "MODE": "local"}, + EU_CONSENT_METADATA_PATH=("outer", "eu_citizen_consent"), + ) + def test_a_grant_lets_an_overwrite_merge_change_consent(self): + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + profile = UserProfile.objects.get(user=self.user) + profile.metadata = {"outer": {"eu_citizen_consent": "yes"}} + profile.save() + grant = issue_grant(self.user.pk, "privacy-consent") + + data = { + "metadata": json.dumps({"eu_citizen_consent": "no"}), + "overwrite": "false", + "grant": grant, + } + request = self.factory.patch("/", data=data, **self.extra) + response = self.view(request, user=self.user.username) + + self.assertEqual(response.status_code, 200) + self.assertEqual( + UserProfile.objects.get(user=self.user).metadata, + {"outer": {"eu_citizen_consent": "no"}}, + ) + + @override_settings( + STEP_UP={ + "ACTIONS": {"privacy-consent", "require-auth-toggle", "change-email"}, + "MODE": "local", + } + ) + def test_an_overwrite_merge_does_not_gate_values_it_does_not_write(self): + """The merge writes metadata only, so a require_auth or email sent + alongside is ignored rather than challenged.""" + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + profile = UserProfile.objects.get(user=self.user) + before = profile.require_auth + old_email = self.user.email + refused = self.factory.patch( + "/", data={"require_auth": not before}, **self.extra + ) + self.assertEqual(self.view(refused, user=self.user.username).status_code, 401) + + data = { + "metadata": json.dumps({"city": "Nairobi"}), + "overwrite": "false", + "require_auth": not before, + "email": "somewhere.else@example.org", + } + request = self.factory.patch("/", data=data, **self.extra) + response = self.view(request, user=self.user.username) + + self.assertEqual(response.status_code, 200) + profile.refresh_from_db() + self.assertEqual(profile.metadata.get("city"), "Nairobi") + self.assertEqual(profile.require_auth, before) + self.user.refresh_from_db() + self.assertEqual(self.user.email, old_email) + def test_partial_updates_empty_metadata(self): profile = UserProfile.objects.get(user=self.user) profile.metadata = {} @@ -1503,7 +1807,11 @@ def test_partial_update_without_password_fails(self): response = self.view(request, user=self.user.username) self.assertEqual(response.status_code, 400) self.assertEqual( - ["Your password is required when updating your email address."], + { + "non_field_errors": [ + "Your password is required when updating your email address." + ] + }, response.data, ) diff --git a/onadata/apps/api/tests/viewsets/v2/test_organization_profile_viewset.py b/onadata/apps/api/tests/viewsets/v2/test_organization_profile_viewset.py index f6a6a9cb75..3639466cc6 100644 --- a/onadata/apps/api/tests/viewsets/v2/test_organization_profile_viewset.py +++ b/onadata/apps/api/tests/viewsets/v2/test_organization_profile_viewset.py @@ -8,8 +8,11 @@ from django.test.utils import CaptureQueriesContext from django.utils import timezone +from django_otp.plugins.otp_totp.models import TOTPDevice + from onadata.apps.api.models.organization_profile import OrganizationProfile from onadata.apps.api.tests.viewsets.test_abstract_viewset import TestAbstractViewSet +from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import gating from onadata.apps.api.viewsets.organization_profile_viewset import ( OrganizationProfileViewSet as OrganizationProfileViewSetV1, ) @@ -690,6 +693,25 @@ def test_patch(self): cache.get(f"{ORG_PROFILE_V2_CACHE}denoinc-owner"), expected_cache ) + @gating("require-auth-toggle") + def test_a_step_up_refusal_is_returned_unchanged(self): + """A refusal carries no organization, so none is merged into it.""" + self._org_create() + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + view = OrganizationProfileViewSet.as_view({"patch": "partial_update"}) + + request = self.factory.patch( + "/", + data=json.dumps({"require_auth": True}), + content_type="application/json", + **self.extra, + ) + response = view(request, user="denoinc") + + self.assertEqual(response.status_code, 401, response.data) + self.assertEqual(response.data["audience"], "require-auth-toggle") + self.assertNotIn("current_user_role", response.data) + def test_invalidates_v1_cache(self): """PATCH invalidates the organization cached for the v1 API""" # creating it through v1 caches what v1 returns diff --git a/onadata/apps/api/tools.py b/onadata/apps/api/tools.py index c82d68f88f..9cc5180960 100644 --- a/onadata/apps/api/tools.py +++ b/onadata/apps/api/tools.py @@ -419,9 +419,13 @@ def set_form(): return publish_form(set_form) -def publish_project_xform(request, project): +def publish_project_xform(request, project, check_move=None): """ Publish XLSForm to a project given a request. + + With ``formid`` it moves that existing form instead. ``check_move(xform)`` + runs after the request passes validation and before anything is written. + It vetoes the move by raising. """ def set_form(): @@ -477,6 +481,8 @@ def id_string_exists_in_account(): # return true if project.organization != xform.user and id_string_exists_in_account(): raise exceptions.ParseError(_(msg)) + if check_move: + check_move(xform) xform.user = project.organization xform.project = project diff --git a/onadata/apps/api/urls/v1_urls.py b/onadata/apps/api/urls/v1_urls.py index a8f8620696..0c0b2dc4d4 100644 --- a/onadata/apps/api/urls/v1_urls.py +++ b/onadata/apps/api/urls/v1_urls.py @@ -28,6 +28,7 @@ from onadata.apps.api.viewsets.osm_viewset import OsmViewSet from onadata.apps.api.viewsets.project_viewset import ProjectViewSet from onadata.apps.api.viewsets.stats_viewset import StatsViewSet +from onadata.apps.api.viewsets.stepup_viewset import StepUpViewSet from onadata.apps.api.viewsets.submission_review_viewset import SubmissionReviewViewSet from onadata.apps.api.viewsets.submissionstats_viewset import SubmissionStatsViewSet from onadata.apps.api.viewsets.team_viewset import TeamViewSet @@ -146,6 +147,7 @@ def get_urls(self): router.register(r"submissions", XFormSubmissionViewSet, basename="submissions") router.register(r"teams", TeamViewSet) router.register(r"totp", TOTPViewSet, basename="totp") +router.register(r"stepup", StepUpViewSet, basename="stepup") router.register(r"user", ConnectViewSet, basename="connect") router.register(r"users", UserViewSet, basename="user") router.register(r"widgets", WidgetViewSet, basename="widgets") diff --git a/onadata/apps/api/viewsets/connect_viewset.py b/onadata/apps/api/viewsets/connect_viewset.py index a55b1abef7..a8160ea4f2 100644 --- a/onadata/apps/api/viewsets/connect_viewset.py +++ b/onadata/apps/api/viewsets/connect_viewset.py @@ -31,6 +31,12 @@ from onadata.libs.serializers.user_profile_serializer import ( UserProfileWithTokenSerializer, ) +from onadata.libs.stepup import RequiresStepUp +from onadata.libs.stepup.capabilities import account_capabilities +from onadata.libs.stepup.policy import ( + GATE_REGENERATE_API_KEY, + GATE_REGENERATE_ODK_TOKEN, +) from onadata.libs.utils.cache_tools import ( USER_PROFILE_PREFIX, safe_cache_get, @@ -71,6 +77,7 @@ def user_profile_w_token_response(request, status_code): # pylint: disable=too-many-ancestors class ConnectViewSet( + RequiresStepUp, mixins.CreateModelMixin, AuthenticateHeaderMixin, CacheControlMixin, @@ -146,7 +153,16 @@ def regenerate_auth_token(self, request, *args, **kwargs): Implements the /regenerate_auth_token endpoint Allows a user to expire and create a new API Token. + + Needs a step-up grant where ``regenerate-api-key`` is gated, because + rotating the token invalidates every integration holding the old one. + The gate protects the rotation, not the secret. A signed-in session can + still read the current token from ``GET /api/v1/user``. A GET has no + body, so send the grant in the ``X-Step-Up-Grant`` header. """ + refusal = self.check_step_up(request, GATE_REGENERATE_API_KEY) + if refusal is not None: + return refusal try: Token.objects.get(user=request.user).delete() except Token.DoesNotExist as exc: @@ -162,6 +178,10 @@ def odk_token(self, request, *args, **kwargs): Implements the /odk_token endpoint Allows a user to get or create or expire an ODKToken for use with ODK Collect. + + A POST regenerates the token and needs a step-up grant where + ``regenerate-odk-token`` is gated. A grant for the API token cannot + rotate this one. A GET fetches or creates the token and is not gated. """ user = request.user status_code = status.HTTP_200_OK @@ -185,6 +205,9 @@ def odk_token(self, request, *args, **kwargs): token = ODKToken.objects.create(user=user) if request.method == "POST": + refusal = self.check_step_up(request, GATE_REGENERATE_ODK_TOKEN) + if refusal is not None: + return refusal # Regenerates the ODK Token if one is already existant ODKToken.objects.filter(user=user, status=ODKToken.ACTIVE).update( status=ODKToken.INACTIVE @@ -197,3 +220,8 @@ def odk_token(self, request, *args, **kwargs): data={"odk_token": token.raw_key, "expires": token.expires}, status=status_code, ) + + @action(methods=["GET"], detail=False) + def capabilities(self, request, *args, **kwargs): + """What this deployment lets the caller manage about their credentials.""" + return Response(account_capabilities()) diff --git a/onadata/apps/api/viewsets/dataview_viewset.py b/onadata/apps/api/viewsets/dataview_viewset.py index 314b8b6c69..88268ac9c2 100644 --- a/onadata/apps/api/viewsets/dataview_viewset.py +++ b/onadata/apps/api/viewsets/dataview_viewset.py @@ -31,6 +31,8 @@ from onadata.libs.serializers.dataview_serializer import DataViewSerializer from onadata.libs.serializers.geojson_serializer import GeoJsonSerializer from onadata.libs.serializers.xform_serializer import XFormSerializer +from onadata.libs.stepup import RequiresStepUp +from onadata.libs.stepup.policy import GATE_PUBLISH_DATA from onadata.libs.utils import common_tags from onadata.libs.utils.api_export_tools import ( custom_response_handler, @@ -76,6 +78,21 @@ def get_dataview_instances(dataview): ).order_by("pk") +def _publishes_data(dataview, validated_data): + """Whether the write publishes rows of a form whose data is not public. + + Anyone can read a dataview in a public project, so creating, moving or + changing one there publishes its rows.""" + project = validated_data.get("project", getattr(dataview, "project", None)) + xform = validated_data.get("xform", getattr(dataview, "xform", None)) + if project is None or xform is None or not project.shared or xform.shared_data: + return False + return dataview is None or any( + field in validated_data and validated_data[field] != getattr(dataview, field) + for field in ("project", "columns", "query") + ) + + def _runtime_query_columns(query): """Return field names referenced by a JSON runtime query.""" if not query: @@ -112,7 +129,12 @@ def collect(value): # pylint: disable=too-many-ancestors class DataViewViewSet( - AuthenticateHeaderMixin, CacheControlMixin, ETagsMixin, BaseViewset, ModelViewSet + AuthenticateHeaderMixin, + CacheControlMixin, + ETagsMixin, + RequiresStepUp, + BaseViewset, + ModelViewSet, ): """ A simple ViewSet for viewing and editing DataViews. @@ -150,6 +172,23 @@ def get_serializer_context(self): context["dataview"] = dataview return context + def _publish_refusal(self, request, dataview, validated_data): + if _publishes_data(dataview, validated_data): + return self.check_step_up(request, GATE_PUBLISH_DATA) + return None + + def create(self, request, *args, **kwargs): + return self.gated_create( + request, lambda data: self._publish_refusal(request, None, data) + ) + + def update(self, request, *args, **kwargs): + return self.gated_update( + request, + lambda dataview, data: self._publish_refusal(request, dataview, data), + partial=kwargs.pop("partial", False), + ) + @staticmethod def _has_source_data_access(request, dataview): return dataview.xform.shared_data or ( diff --git a/onadata/apps/api/viewsets/merged_xform_viewset.py b/onadata/apps/api/viewsets/merged_xform_viewset.py index 6409e9112c..45b0767bdc 100644 --- a/onadata/apps/api/viewsets/merged_xform_viewset.py +++ b/onadata/apps/api/viewsets/merged_xform_viewset.py @@ -26,6 +26,8 @@ SOURCE_XFORM_FIELDS, MergedXFormSerializer, ) +from onadata.libs.stepup import RequiresStepUp +from onadata.libs.stepup.policy import GATE_PUBLISH_DATA, GATE_TRANSFER_PROJECT from onadata.libs.utils.bbox_tools import compute_instance_bbox from onadata.libs.utils.cache_tools import ( MERGED_XFORM_BBOX_CACHE, @@ -35,8 +37,20 @@ ) +def _transfers_data(project, xforms): + """A merged dataset belongs to its project's account, whose admins read + every source form's data through it.""" + return any(xform.user != project.organization for xform in xforms) + + +def _publishes_data(project, xforms): + """A merged dataset in a public project is public, data included.""" + return project.shared and any(not xform.shared_data for xform in xforms) + + # pylint: disable=too-many-ancestors class MergedXFormViewSet( + RequiresStepUp, mixins.CreateModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, @@ -63,6 +77,22 @@ class MergedXFormViewSet( renderers.GeoJsonRenderer, ] + def create(self, request, *args, **kwargs): + return self.gated_create( + request, lambda data: self._create_refusal(request, data) + ) + + def _create_refusal(self, request, validated_data): + project = validated_data["project"] + xforms = validated_data["xforms"] + return self.gated_change_refusal( + request, + ( + (GATE_TRANSFER_PROJECT, _transfers_data(project, xforms)), + (GATE_PUBLISH_DATA, _publishes_data(project, xforms)), + ), + ) + def get_queryset(self): """Limit the queries of the actions that serialize a merged dataset""" queryset = super().get_queryset() diff --git a/onadata/apps/api/viewsets/metadata_viewset.py b/onadata/apps/api/viewsets/metadata_viewset.py index 7e1299ba3b..52afccabdd 100644 --- a/onadata/apps/api/viewsets/metadata_viewset.py +++ b/onadata/apps/api/viewsets/metadata_viewset.py @@ -10,6 +10,7 @@ from onadata.apps.api.permissions import MetaDataObjectPermissions from onadata.apps.api.tools import get_media_file_response +from onadata.apps.logger.models import XForm from onadata.apps.main.models.meta_data import MetaData from onadata.libs.serializers.metadata_serializer import MetaDataSerializer from onadata.libs import filters @@ -21,16 +22,70 @@ MediaFileRenderer, ) from onadata.apps.api.tools import get_baseviewset_class +from onadata.libs.data import strtobool +from onadata.libs.stepup import RequiresStepUp +from onadata.libs.stepup.policy import ( + ADMIN_ROLE_NAMES, + GATE_CHANGE_WEBHOOK, + GATE_PUBLISH_DATA, + GATE_SHARE_FORM_ADMIN, +) +from onadata.libs.stepup.sharing import appoints_admins +from onadata.libs.utils.common_tags import TEXTIT, XFORM_META_PERMS BaseViewset = get_baseviewset_class() +PUBLIC_LINK = "public_link" + + +def _meta_perms_slots(value): + return dict(enumerate(value.split("|"))) if value else {} + + +def _introduces_admin_meta_perms(content_object, data_value): + """Whether ``data_value`` appoints owners or managers of the form. + + Meta permissions give a form's editors, data-entry and read-only users the + role in their slot. A slot newly set to owner or manager appoints admins, + and so does a value that promotes a current user once applied.""" + current = MetaData.xform_meta_permission(content_object) + old = _meta_perms_slots(current.data_value if current else "") + names_new_admin = any( + role in ADMIN_ROLE_NAMES and old.get(slot) != role + for slot, role in _meta_perms_slots(data_value).items() + ) + return names_new_admin or ( + isinstance(content_object, XForm) + and appoints_admins(content_object, data_value) + ) + + +def _is_true(value): + """Any spelling of true, not only the ``"True"`` a public link is stored + as, so a value a reader might accept later is gated now.""" + try: + return bool(strtobool(str(value))) + except ValueError: + return False + + +def _turns_on_public_link(content_object, data_value): + return _is_true(data_value) and not MetaData.public_link(content_object) + + +def _changes_textit(content_object, data_value): + """The TextIt settings carry the token and contacts a form's TextIt + service posts submissions with.""" + return MetaData.textit(content_object) != data_value + # pylint: disable=too-many-ancestors class MetaDataViewSet( AuthenticateHeaderMixin, CacheControlMixin, ETagsMixin, + RequiresStepUp, BaseViewset, viewsets.ModelViewSet, ): @@ -49,6 +104,56 @@ class MetaDataViewSet( ) serializer_class = MetaDataSerializer + def _change_refusal(self, request, content_object, data_type, data_value): + """Refuse the gated change writing ``data_value`` as ``data_type`` on + ``content_object`` would make, or None.""" + return self.gated_change_refusal( + request, + ( + ( + GATE_SHARE_FORM_ADMIN, + lambda: data_type == XFORM_META_PERMS + and _introduces_admin_meta_perms(content_object, data_value), + ), + ( + GATE_PUBLISH_DATA, + data_type == PUBLIC_LINK + and _turns_on_public_link(content_object, data_value), + ), + ( + GATE_CHANGE_WEBHOOK, + data_type == TEXTIT and _changes_textit(content_object, data_value), + ), + ), + ) + + def create(self, request, *args, **kwargs): + return self.gated_create( + request, + lambda data: self._change_refusal( + request, + self.get_serializer().get_content_object(data), + data.get("data_type"), + data.get("data_value"), + ), + ) + + def update(self, request, *args, **kwargs): + """An update can change the type as well as the value, so the gates + read what the row will hold afterwards.""" + + def refusal_for(instance, validated_data): + return self._change_refusal( + request, + instance.content_object, + validated_data.get("data_type", instance.data_type), + validated_data.get("data_value", instance.data_value), + ) + + return self.gated_update( + request, refusal_for, partial=kwargs.pop("partial", False) + ) + def retrieve(self, request, *args, **kwargs): # pylint: disable=attribute-defined-outside-init self.object = self.get_object() diff --git a/onadata/apps/api/viewsets/open_data_viewset.py b/onadata/apps/api/viewsets/open_data_viewset.py index 24ff3042ce..359a49f409 100644 --- a/onadata/apps/api/viewsets/open_data_viewset.py +++ b/onadata/apps/api/viewsets/open_data_viewset.py @@ -33,6 +33,8 @@ OpenDataSerializer, get_manageable_xforms, ) +from onadata.libs.stepup import RequiresStepUp +from onadata.libs.stepup.policy import GATE_PUBLISH_DATA from onadata.libs.utils.common_tags import ( ATTACHMENTS, GEOLOCATION, @@ -168,7 +170,9 @@ def get_ordered_repeat_value(key, item, index): # pylint: disable=too-many-ancestors -class OpenDataViewSet(ETagsMixin, CacheControlMixin, BaseViewset, ModelViewSet): +class OpenDataViewSet( + ETagsMixin, CacheControlMixin, RequiresStepUp, BaseViewset, ModelViewSet +): """The /api/v1/open-data API endpoint.""" permission_classes = (OpenDataViewSetPermissions,) @@ -204,6 +208,47 @@ def get_serializer_class(self): return super().get_serializer_class() + def _create_refusal(self, request, validated_data): + """An entry is a link that reads its form's data without logging in. + Asking again for a form that has one returns that one unchanged. + + The form is resolved first, so a request refused for it keeps its + grant.""" + object_id = validated_data.get("object_id") + if object_id is None: + return None + xform = get_object_or_404(get_manageable_xforms(request.user), id=object_id) + if OpenData.objects.filter( + content_type=ContentType.objects.get_for_model(xform), object_id=xform.pk + ).exists(): + return None + return self.check_step_up(request, GATE_PUBLISH_DATA) + + def _update_refusal(self, request, open_data, validated_data): + """Reactivating an entry, or pointing an active one at another form, + opens a form's data to anyone holding the link.""" + if not validated_data.get("active", open_data.active): + return None + object_id = validated_data.get("object_id", open_data.object_id) + if open_data.active and object_id == open_data.object_id: + return None + get_object_or_404(get_manageable_xforms(request.user), id=object_id) + return self.check_step_up(request, GATE_PUBLISH_DATA) + + def create(self, request, *args, **kwargs): + """Create an entry, or return the form's existing one.""" + return self.gated_create( + request, lambda data: self._create_refusal(request, data) + ) + + def update(self, request, *args, **kwargs): + """Update an entry, the target of PUT and PATCH alike.""" + return self.gated_update( + request, + lambda open_data, data: self._update_refusal(request, open_data, data), + partial=kwargs.pop("partial", False), + ) + def get_tableau_type(self, xform_type): """ Returns a tableau-supported type based on a xform type. diff --git a/onadata/apps/api/viewsets/organization_profile_viewset.py b/onadata/apps/api/viewsets/organization_profile_viewset.py index 9b2761e62d..6157e4147b 100644 --- a/onadata/apps/api/viewsets/organization_profile_viewset.py +++ b/onadata/apps/api/viewsets/organization_profile_viewset.py @@ -8,6 +8,7 @@ import json from django.conf import settings +from django.contrib.auth import get_user_model from django.utils.module_loading import import_string from rest_framework import status @@ -17,7 +18,10 @@ from reversion.views import RevisionMixin from onadata.apps.api import permissions -from onadata.apps.api.models.organization_profile import OrganizationProfile +from onadata.apps.api.models.organization_profile import ( + OrganizationProfile, + get_organization_members_team, +) from onadata.apps.api.tools import ( get_baseviewset_class, get_org_profile_cache_key, @@ -42,6 +46,20 @@ OrganizationSerializer, RotateOrganizationKeySerializer, ) +from onadata.libs.stepup import RequiresStepUp +from onadata.libs.stepup.gate import changed_gated_actions +from onadata.libs.stepup.policy import ( + GATE_GRANT_ORG_ADMIN, + GATE_REQUIRE_AUTH, + GATE_ROTATE_ORG_KEY, + GATE_SHARE_TEAM_ADMIN, +) +from onadata.libs.stepup.sharing import ( + admin_role, + holds_roles, + member_admin_roles, + team_reaches_admin_role, +) from onadata.libs.utils.cache_tools import ( safe_cache_delete, safe_cache_get, @@ -50,6 +68,7 @@ from onadata.libs.utils.common_tools import merge_dicts BaseViewset = get_baseviewset_class() +User = get_user_model() def serializer_from_settings(): @@ -67,6 +86,7 @@ class OrganizationProfileViewSet( ETagsMixin, ObjectLookupMixin, RevisionMixin, + RequiresStepUp, BaseViewset, ModelViewSet, ): @@ -123,9 +143,58 @@ def destroy(self, request, *args, **kwargs): safe_cache_delete(cache_key) return super().destroy(request, *args, **kwargs) - def update(self, request, *args, **kwargs): + def _require_auth_refusal(self, organization, validated_data): + """An organisation's profile is a UserProfile, so toggling its + require_auth needs the same proof as on a personal profile. + """ + current = organization.require_auth + if validated_data.get("require_auth", current) == current: + return None + return self.check_step_up(self.request, GATE_REQUIRE_AUTH) + + def member_role_refusal(self, request, organization, validated_data): + """Refuse a member change that appoints an admin without a grant. + + An organisation owner or manager can change every gated setting with + their own factor. Adding a member, even one already added, also shares + every organisation project with them and puts them in the members + team. That can make them an owner or manager of a project or form. One + grant covers both, under the first audience the deployment gates.""" + username = validated_data.get("username") + if validated_data.get("remove") or not username: + return None + user = User.objects.get(username=username) + role_name = validated_data.get("role") + role = admin_role(role_name) + members_team = get_organization_members_team(organization) + + def appoints_org_admin(): + return role is not None and not role.user_has_role(user, organization) + + def appoints_project_or_form_admin(): + joins = not members_team.user_set.filter(pk=user.pk).exists() + if joins and team_reaches_admin_role(members_team): + return True + shared = member_admin_roles( + organization.user.project_org.all(), members_team, user, role_name + ) + return not holds_roles(user, shared) + + gated = changed_gated_actions( + ( + (GATE_GRANT_ORG_ADMIN, appoints_org_admin), + (GATE_SHARE_TEAM_ADMIN, appoints_project_or_form_admin), + ) + ) + return self.check_step_up(request, gated[0]) if gated else None + + def update(self, request, *args, **kwargs): # pylint: disable=unused-argument """Update org in cache and db""" - response = super().update(request, *args, **kwargs) + response = self.gated_update( + request, self._require_auth_refusal, partial=kwargs.get("partial", False) + ) + if not status.is_success(response.status_code): + return response organization = self.get_object() invalidate_organization_cache(organization.user.username) cache_key = get_org_profile_cache_key( @@ -173,6 +242,11 @@ def members(self, request, *args, **kwargs): if not serializer.is_valid(): return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) + refusal = self.member_role_refusal( + request, organization, serializer.validated_data + ) + if refusal is not None: + return refusal serializer.save() data = self.serializer_class(organization, context={"request": request}).data @@ -194,6 +268,9 @@ def rotate_key(self, request, *args, **kwargs): context={**self.get_serializer_context(), "organization": organization}, ) serializer.is_valid(raise_exception=True) + refusal = self.check_step_up(request, GATE_ROTATE_ORG_KEY) + if refusal is not None: + return refusal old_key = serializer.validated_data["id"] new_key = serializer.save() # Capture audit log diff --git a/onadata/apps/api/viewsets/project_viewset.py b/onadata/apps/api/viewsets/project_viewset.py index 9efb70c48f..5f8de05e45 100644 --- a/onadata/apps/api/viewsets/project_viewset.py +++ b/onadata/apps/api/viewsets/project_viewset.py @@ -5,6 +5,7 @@ import logging +from django.contrib.auth import get_user_model from django.core.mail import send_mail from django.http import Http404 from django.shortcuts import get_object_or_404 @@ -54,6 +55,23 @@ XFormCreateSerializer, XFormSerializer, ) +from onadata.libs.stepup import RequiresStepUp +from onadata.libs.stepup.gate import StepUpRefused, require_gated_change +from onadata.libs.stepup.policy import ( + GATE_INVITE_PROJECT_ADMIN, + GATE_PUBLISH_DATA, + GATE_SHARE_FORM_ADMIN, + GATE_SHARE_PROJECT_ADMIN, + GATE_TRANSFER_PROJECT, + is_gated, +) +from onadata.libs.stepup.sharing import ( + admin_role, + admin_roles_granted, + grants_admin_role, + holds_roles, + move_appoints_admins, +) from onadata.libs.utils.cache_tools import ( clear_project_owner_cache, get_project_cache_key, @@ -70,6 +88,20 @@ # pylint: disable=invalid-name BaseViewset = get_baseviewset_class() +User = get_user_model() + + +def _publishes_data(project, validated_data): + """Saving a public project makes every private form in it public, data + included, whether or not ``public`` is what changed.""" + if not validated_data.get("shared", project.shared): + return False + return not project.shared or project.xform_set.filter(shared=False).exists() + + +def _transfers(project, validated_data): + new_owner = validated_data.get("organization", project.organization) + return new_owner != project.organization # pylint: disable=too-many-ancestors @@ -80,6 +112,7 @@ class ProjectViewSet( LabelsMixin, ProfilerMixin, RevisionMixin, + RequiresStepUp, BaseViewset, ModelViewSet, ): @@ -131,10 +164,57 @@ def get_queryset(self): return super().get_queryset() + def _update_refusal(self, request, project, validated_data): + """Refuse whichever gated change saving ``validated_data`` would make, + or None.""" + return self.gated_change_refusal( + request, + ( + (GATE_TRANSFER_PROJECT, _transfers(project, validated_data)), + (GATE_PUBLISH_DATA, _publishes_data(project, validated_data)), + ), + ) + + @staticmethod + def _check_form_move(request, project, xform): + """Raise ``StepUpRefused`` if moving ``xform`` into ``project`` needs + a grant the request does not carry. + + Moving a form into another account's project hands that account the + form and its data. A form with neither public visibility nor public + data takes on a public project's visibility. The form's meta + permissions, re-applied after the move, can make the new project's + users its owners or managers. Where transfers are gated, the transfer + grant covers that.""" + transfers = project.organization != xform.user + + def appoints_admins_not_covered_by_a_transfer(): + if transfers and is_gated(GATE_TRANSFER_PROJECT): + return False + return move_appoints_admins(xform, project) + + require_gated_change( + request, + ( + (GATE_TRANSFER_PROJECT, transfers), + (GATE_SHARE_FORM_ADMIN, appoints_admins_not_covered_by_a_transfer), + ( + GATE_PUBLISH_DATA, + project.shared and not (xform.shared or xform.shared_data), + ), + ), + ) + def update(self, request, *args, **kwargs): """Updates project properties and set's cache with the updated records.""" project_id = kwargs.get("pk") - response = super().update(request, *args, **kwargs) + response = self.gated_update( + request, + lambda project, data: self._update_refusal(request, project, data), + partial=kwargs.pop("partial", False), + ) + if not status.is_success(response.status_code): + return response clear_project_owner_cache(project_id) safe_cache_set( get_project_cache_key(project_id, request, api_version=self.api_version), @@ -167,7 +247,16 @@ def forms(self, request, **kwargs): # pylint: disable=attribute-defined-outside-init project = self.object = self.get_object() if request.method.upper() == "POST": - survey = utils.publish_project_xform(request, project) + try: + survey = utils.publish_project_xform( + request, + project, + check_move=lambda xform: self._check_form_move( + request, project, xform + ), + ) + except StepUpRefused as refused: + return self.step_up_refusal(request, refused.reason, refused.audiences) if isinstance(survey, XForm): if "formid" in request.data: @@ -204,6 +293,30 @@ def forms(self, request, **kwargs): return Response(serializer.data) + def _admin_roles_granted(self, role_name): + """``(object, role)`` for each owner or manager role sharing the + project as ``role_name`` hands out, on the project or on its forms.""" + role = admin_role(role_name) + on_project = [(self.object, role)] if role else [] + return on_project + admin_roles_granted(self.object.xform_set.all(), role_name) + + def _share_admin_refusal(self, request, validated_data): + """Refuse appointing a project owner or manager without a grant. + + The role may be named outright or reached on a form through its meta + permissions. A target who already holds the role needs no grant.""" + if not is_gated(GATE_SHARE_PROJECT_ADMIN): + return None + granted = self._admin_roles_granted(validated_data["role"]) + if not granted: + return None + targets = User.objects.filter( + username__in=validated_data["username"].split(",") + ) + if all(holds_roles(user, granted) for user in targets): + return None + return self.check_step_up(request, GATE_SHARE_PROJECT_ADMIN) + @action(methods=["PUT"], detail=True) def share(self, request, *args, **kwargs): """ @@ -222,6 +335,10 @@ def share(self, request, *args, **kwargs): else: serializer = ShareProjectSerializer(data=data) if serializer.is_valid(): + if not remove: + refusal = self._share_admin_refusal(request, serializer.validated_data) + if refusal is not None: + return refusal serializer.save() email_msg = data.get("email_msg") if email_msg: @@ -276,6 +393,24 @@ def star(self, request, *args, **kwargs): return Response(status=status.HTTP_204_NO_CONTENT) + def _invite_admin_refusal(self, request, validated_data, invitation=None): + """An accepted invitation confers its role, meta permissions + included, so inviting an owner or manager needs the same factor as + sharing with one. Pointing an admin invitation at another email invites + someone new.""" + if not is_gated(GATE_INVITE_PROJECT_ADMIN): + return None + role = validated_data["role"] + if not grants_admin_role(validated_data["project"].xform_set.all(), role): + return None + if ( + invitation is not None + and invitation.role == role + and invitation.email == validated_data["email"] + ): + return None + return self.check_step_up(request, GATE_INVITE_PROJECT_ADMIN) + @action( detail=True, methods=["GET", "POST", "PUT"], @@ -302,6 +437,9 @@ def invitations(self, request, *args, **kwargs): data = draft_request_data serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) + refusal = self._invite_admin_refusal(request, serializer.validated_data) + if refusal is not None: + return refusal serializer.save() return Response(serializer.data) @@ -323,6 +461,11 @@ def invitations(self, request, *args, **kwargs): data=data, ) serializer.is_valid(raise_exception=True) + refusal = self._invite_admin_refusal( + request, serializer.validated_data, invitation + ) + if refusal is not None: + return refusal serializer.save() return Response(serializer.data) diff --git a/onadata/apps/api/viewsets/stepup_viewset.py b/onadata/apps/api/viewsets/stepup_viewset.py new file mode 100644 index 0000000000..a28fda9fca --- /dev/null +++ b/onadata/apps/api/viewsets/stepup_viewset.py @@ -0,0 +1,131 @@ +# -*- coding: utf-8 -*- +"""Where the identity provider returns after a step-up.""" + +import logging + +from oidc.stepup_grants import issue_grant +from oidc.stepup_viewsets import StepUpCallbackMixin +from rest_framework import status +from rest_framework.authentication import SessionAuthentication, TokenAuthentication +from rest_framework.decorators import action +from rest_framework.permissions import IsAuthenticated +from rest_framework.renderers import JSONRenderer, StaticHTMLRenderer +from rest_framework.response import Response +from rest_framework.viewsets import ViewSet + +from onadata.libs.authentication import SSOHeaderAuthentication +from onadata.libs.stepup.challenge import STEP_UP_UNAVAILABLE +from onadata.libs.stepup.federated import start_step_up +from onadata.libs.stepup.policy import is_gated, is_local_mode + +logger = logging.getLogger(__name__) + +#: Why ``start`` refuses. Either the audience is not gated here, or the factor +#: is verified locally rather than at an identity provider. +NOT_GATED = "not_gated" +NOT_FEDERATED = "not_federated" + +#: Why ``callback`` refuses. Either the provider's answer is missing, or it +#: does not satisfy the step-up. +INVALID_REQUEST = "invalid_request" +STEP_UP_FAILED = "step_up_failed" + + +class StepUpViewSet(StepUpCallbackMixin, ViewSet): + """Completes a federated step-up and hands the grant back to the caller.""" + + # The popup returning from the provider sends cookies only, so accept the + # Django session as well as the SSO cookie. + authentication_classes = ( + SSOHeaderAuthentication, + SessionAuthentication, + TokenAuthentication, + ) + permission_classes = (IsAuthenticated,) + # StaticHTMLRenderer is for content negotiation, not rendering. DRF + # negotiates before the handler runs, so without it the returning popup's + # ``Accept: text/html`` gets a 406. + renderer_classes = (JSONRenderer, StaticHTMLRenderer) + + def finalize_response(self, request, response, *args, **kwargs): + """Mark every response no-store, because a callback body carries a + grant.""" + response = super().finalize_response(request, response, *args, **kwargs) + response["Cache-Control"] = "no-store" + return response + + @action(detail=False, methods=["get"], url_path="start") + def start(self, request): + """Where to send the user to prove a factor for ``audience``. + + Call this before the gated request, not after its 401. A browser + caller must open its popup inside the click handler, because browsers + block a popup opened later from an async response. + """ + audience = str(request.query_params.get("audience", "")).strip() + if not audience or not is_gated(audience): + return Response({"error": NOT_GATED}, status=status.HTTP_400_BAD_REQUEST) + if is_local_mode(): + return Response( + {"error": NOT_FEDERATED}, status=status.HTTP_400_BAD_REQUEST + ) + auth_server = self.step_up_auth_server() + try: + url, _ = start_step_up(auth_server, audience, request.user) + except (ValueError, KeyError): + # No server carries a STEP_UP block, or the one that does lacks + # its endpoints. + logger.exception("step-up: cannot build an authorization request") + return Response( + {"error": STEP_UP_UNAVAILABLE}, + status=status.HTTP_503_SERVICE_UNAVAILABLE, + ) + return Response({"authorizationUrl": url}) + + @action(detail=False, methods=["get", "post"], url_path="callback") + def callback(self, request): + """Verify the provider's answer, and mint a grant only if it + satisfies the step-up.""" + params = request.query_params if request.method == "GET" else request.data + code = str(params.get("code", "")).strip() + state = str(params.get("state", "")).strip() + auth_server = str(params.get("auth_server", "")).strip() or None + # A browser here is the popup returning from the provider. It needs a + # page that hands the result to its opener, not JSON. + popup = "text/html" in request.headers.get("Accept", "") + + if not code or not state: + # A provider reports a cancelled or failed prompt as ``error``. + reason = "provider_error" if params.get("error") else INVALID_REQUEST + if popup: + return self.step_up_popup_response(None, reason) + return Response( + {"error": INVALID_REQUEST}, status=status.HTTP_400_BAD_REQUEST + ) + + grant, reason = self.complete_step_up(request, code, state, auth_server) + + if popup: + return self.step_up_popup_response(grant, reason) + + if grant is None: + # ``reason`` names the check that failed, not what the user did. A + # cancelled prompt and a provider with no MFA can look alike, so a + # caller should show one generic failure. + return Response( + {"error": STEP_UP_FAILED, "reason": reason or "unknown"}, + status=status.HTTP_403_FORBIDDEN, + ) + return Response({"grant": grant}) + + def verify_step_up_context(self, request, context): + """The state must belong to the session redeeming it.""" + if context.get("user_pk") != request.user.pk: + logger.warning("step-up: state belongs to a different user") + return "state_user_mismatch" + return None + + def on_step_up_verified(self, request, claims, context): + """A proven factor earns a grant for the action it was proven for.""" + # pylint: disable=unused-argument + return issue_grant(request.user.pk, context["audience"]) diff --git a/onadata/apps/api/viewsets/team_viewset.py b/onadata/apps/api/viewsets/team_viewset.py index 642566edbc..631ef0a126 100644 --- a/onadata/apps/api/viewsets/team_viewset.py +++ b/onadata/apps/api/viewsets/team_viewset.py @@ -2,9 +2,12 @@ """ The /teams API endpoint implementation. """ +from itertools import chain + from django.contrib.auth import get_user_model from django.utils.translation import gettext as _ +from guardian.shortcuts import get_perms from rest_framework import status from rest_framework.decorators import action from rest_framework.exceptions import PermissionDenied @@ -14,6 +17,7 @@ from rest_framework_guardian.filters import ObjectPermissionsFilter from onadata.apps.api.models import OrganizationProfile, Team +from onadata.apps.api.models.organization_profile import is_organization_owners_team from onadata.apps.api.tools import ( add_user_to_team, get_baseviewset_class, @@ -24,12 +28,24 @@ from onadata.libs.mixins.authenticate_header_mixin import AuthenticateHeaderMixin from onadata.libs.mixins.cache_control_mixin import CacheControlMixin from onadata.libs.mixins.etags_mixin import ETagsMixin -from onadata.libs.permissions import is_organization_admin +from onadata.libs.permissions import ROLES, is_organization_admin from onadata.libs.serializers.share_team_project_serializer import ( RemoveTeamFromProjectSerializer, ShareTeamProjectSerializer, ) from onadata.libs.serializers.team_serializer import TeamSerializer +from onadata.libs.stepup import RequiresStepUp +from onadata.libs.stepup.gate import changed_gated_actions +from onadata.libs.stepup.policy import ( + GATE_GRANT_ORG_ADMIN, + GATE_SHARE_TEAM_ADMIN, + is_gated, +) +from onadata.libs.stepup.sharing import ( + grants_admin_role, + reapplying_appoints_admins, + team_reaches_admin_role, +) from onadata.libs.utils.common_tools import merge_dicts # pylint: disable=invalid-name @@ -38,9 +54,24 @@ User = get_user_model() +def _team_holds_role(team, project, role): + """Whether sharing ``project`` with ``team`` as ``role`` would grant + nothing new. A share also applies the role to every form in the project, + so the forms are checked as well.""" + return all( + role.has_role(get_perms(team, obj), obj) + for obj in chain([project], project.xform_set.all()) + ) + + # pylint: disable=too-many-ancestors class TeamViewSet( - AuthenticateHeaderMixin, CacheControlMixin, ETagsMixin, BaseViewset, ModelViewSet + AuthenticateHeaderMixin, + CacheControlMixin, + ETagsMixin, + RequiresStepUp, + BaseViewset, + ModelViewSet, ): """ This endpoint allows you to create, update and view team information. @@ -62,6 +93,61 @@ def _check_organization_admin(self, request, team): _("You must be an owner or manager of the organization.") ) + def _join_refusal(self, request, team, user): + """Joining a team hands the new member every role the team holds. + Joining the Owners team makes someone an organisation owner. Joining + any team that owns or manages a project or form makes them an admin + of it. + + The Owners team is both, and one grant covers it, under the first + audience the deployment gates.""" + if request.method != "POST" or team.user_set.filter(pk=user.pk).exists(): + return None + gated = changed_gated_actions( + ( + (GATE_GRANT_ORG_ADMIN, is_organization_owners_team(team)), + (GATE_SHARE_TEAM_ADMIN, lambda: team_reaches_admin_role(team)), + ) + ) + return self.check_step_up(request, gated[0]) if gated else None + + def _share_admin_refusal(self, request, validated_data): + """Refuse giving a team an owner or manager role without a grant. + + The role may be named outright or reached on a form through its meta + permissions.""" + if not is_gated(GATE_SHARE_TEAM_ADMIN): + return None + role_name = validated_data["role"] + team, project = validated_data["team"], validated_data["project"] + xforms = project.xform_set.all() + grants_new_admin = grants_admin_role( + xforms, role_name + ) and not _team_holds_role(team, project, ROLES[role_name]) + # A share re-applies each form's meta permissions to all its users, + # whatever role it names. + if grants_new_admin or reapplying_appoints_admins(xforms): + return self.check_step_up(request, GATE_SHARE_TEAM_ADMIN) + return None + + def _move_refusal(self, request, team, validated_data): + """A moved team keeps its roles on the old organisation's projects and + forms, so moving it hands them to the new organisation's admins.""" + organization = validated_data.get("organization") + if not is_gated(GATE_SHARE_TEAM_ADMIN) or organization in ( + None, + team.organization, + ): + return None + return self.check_step_up(request, GATE_SHARE_TEAM_ADMIN) + + def update(self, request, *args, **kwargs): + return self.gated_update( + request, + lambda team, data: self._move_refusal(request, team, data), + partial=kwargs.pop("partial", False), + ) + def destroy(self, request, *args, **kwargs): """Deletes a team.""" self._check_organization_admin(request, self.get_object()) @@ -91,6 +177,9 @@ def members(self, request, *args, **kwargs): status_code = status.HTTP_400_BAD_REQUEST data["username"] = [_(f"User `{username}` does not exist.")] else: + refusal = self._join_refusal(request, team, user) + if refusal is not None: + return refusal if request.method == "POST": add_user_to_team(team, user) elif request.method == "DELETE": @@ -124,9 +213,16 @@ def share(self, request, *args, **kwargs): else: serializer = ShareTeamProjectSerializer(data=data, context=context) - if serializer.is_valid(): - serializer.save() - else: + if not serializer.is_valid(): return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) + refusal = ( + None + if remove + else self._share_admin_refusal(request, serializer.validated_data) + ) + if refusal is not None: + return refusal + serializer.save() + return Response(status=status.HTTP_204_NO_CONTENT) diff --git a/onadata/apps/api/viewsets/totp_viewset.py b/onadata/apps/api/viewsets/totp_viewset.py index 6bffb52331..83c727e71c 100644 --- a/onadata/apps/api/viewsets/totp_viewset.py +++ b/onadata/apps/api/viewsets/totp_viewset.py @@ -10,12 +10,10 @@ import base64 import io -import secrets from contextlib import suppress from django.conf import settings from django.contrib.auth import get_user_model -from django.core.cache import cache from django.db import transaction from django.utils.decorators import method_decorator from django.utils.translation import gettext as _ @@ -23,6 +21,7 @@ import qrcode from django_otp import devices_for_user +from oidc.stepup_grants import issue_grant, spend_grant from rest_framework import status from rest_framework.authentication import SessionAuthentication, TokenAuthentication from rest_framework.decorators import action @@ -46,6 +45,9 @@ assert_not_locked_out, get_client_ip, ) +from onadata.libs.stepup.capabilities import account_capabilities +from onadata.libs.stepup.gate import has_second_factor +from onadata.libs.stepup.policy import KNOWN_ACTIONS, is_local_mode from onadata.libs.utils.field_encryption import encrypt from onadata.libs.utils.log import Actions, audit_log from onadata.libs.utils.two_factor import ( @@ -61,13 +63,13 @@ TOTP_DEVICE_NAME = "default" RECOVERY_DEVICE_NAME = "backup" -STEP_UP_GRANT_TTL = 5 * 60 +#: Why a management route refuses when an identity provider owns the factor. +NOT_MANAGED_HERE = "not_managed_here" #: The step-up operations this viewset owns. The single source of truth for #: the audience strings the endpoints pass, and always recognised by #: ``_known_audiences`` so a deployment's ``TWO_FACTOR_STEP_UP_AUDIENCES`` can -#: only ADD account-action gates, never drop a lifecycle one and silently break -#: its grants. +#: only add audiences, never drop a lifecycle one and break its grants. AUDIENCE_ENROLL_START = "enroll-start" AUDIENCE_DISABLE = "disable" AUDIENCE_RECOVERY_GENERATE = "recovery-generate" @@ -82,44 +84,19 @@ ) -def _grant_key(user, audience: str, grant: str) -> str: - return f"totp-step-up:{user.pk}:{audience}:{grant}" - - -def _issue_grant(user, audience: str) -> str: - """Proof that this user showed a second factor a moment ago. - - django-otp records the counter a code was used at, so a caller that - verifies first and acts second has nothing to resend. - - Grants live in the cache, as do the lockout and repeated-failure counters, - so the deployment must run a cache shared across workers (Redis/memcached); - a per-process cache would fragment all three and weaken them. - """ - grant = secrets.token_urlsafe(32) - cache.set(_grant_key(user, audience, grant), True, STEP_UP_GRANT_TTL) - return grant - - -def _spend_grant(user, audience: str, grant: str) -> bool: - """Redeem a grant, once. False if minted for a different operation. - - The delete is the check: ``cache.delete`` reports whether it removed - anything, so two requests racing on one grant cannot both be told yes. - """ - if not grant: - return False - return bool(cache.delete(_grant_key(user, audience, grant))) - - def _known_audiences() -> frozenset[str]: """The operations a grant may be minted for. + These are this viewset's own, every action a deployment can gate, and any + the deployment adds. + Read per call rather than at import so a deployment's override -- and a test's -- takes effect. """ - return LIFECYCLE_AUDIENCES | frozenset( - getattr(settings, "TWO_FACTOR_STEP_UP_AUDIENCES", ()) + return ( + LIFECYCLE_AUDIENCES + | KNOWN_ACTIONS + | frozenset(getattr(settings, "TWO_FACTOR_STEP_UP_AUDIENCES", ())) ) @@ -197,17 +174,6 @@ def _recovery_device(user, lock: bool = False) -> EncryptedRecoveryDevice | None return devices.filter(user=user, name=RECOVERY_DEVICE_NAME).first() -def _has_second_factor(user) -> bool: - """Whether the login view would challenge this user for a second factor. - - Through ``default_device``, not an EncryptedTOTPDevice lookup: two_factor challenges - on any confirmed device named ``"default"`` whatever its class. - ``_verify_code`` understands only TOTP and recovery codes -- teach it any - new device type in the same change. - """ - return default_device(user) is not None - - def _verify_totp(user, code: str) -> bool: """Check ``code`` against the authenticator, spending it once. @@ -419,12 +385,12 @@ def _require_code(self, request, audience: str): Applied to every operation that weakens or replaces it -- otherwise a stolen session could switch 2FA off. A grant from a recent ``verify`` - counts, but only one earned for this same ``audience``. + counts, but only one minted for this same audience. """ locked = self._locked_out_response(request) if locked is not None: return locked - if _spend_grant(request.user, audience, _str_field(request, "grant")): + if spend_grant(request.user.pk, audience, _str_field(request, "grant")): clear_verification_failures(request.user) return None code = _str_field(request, "code") @@ -450,14 +416,15 @@ def _require_password(self, request): The only proof available at first enrolment: with no factor yet, ``_require_code`` has nothing to demand. + Reached only in local mode, because ``enroll_start`` refuses a + federated deployment first. + An account with no password is refused rather than let through, or having no password would itself be the way past it. Its own reason, so a caller can say what is wrong instead of prompting for one that cannot exist. The stored value is tested directly: Django reports the empty string ``objects.create`` leaves behind as *usable*. """ - if not getattr(settings, "TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD", True): - return None user = request.user if not user.password or not user.has_usable_password(): return Response( @@ -525,8 +492,16 @@ def totp_status(self, request): """The account's second factor and recovery-code state.""" device = default_device(request.user) recovery = _recovery_device(request.user) + two_factor = account_capabilities()["twoFactor"] return Response( { + # This route answers in every mode, so a caller can learn + # here that the management routes are refused. + "managedBy": two_factor["managedBy"], + "capabilities": { + key: two_factor[key] + for key in ("enroll", "disable", "recoveryCodes", "verify") + }, "methods": _method_entries(device), "recoveryCodes": { "generated": recovery is not None, @@ -535,6 +510,19 @@ def totp_status(self, request): } ) + def _refuse_if_not_local(self): + """``None`` in local mode, or a 409 refusing the request. + + Otherwise a user could enrol a device that nothing in the login path + will ever challenge. + """ + if is_local_mode(): + return None + return Response( + {"error": NOT_MANAGED_HERE}, + status=status.HTTP_409_CONFLICT, + ) + @action(detail=False, methods=["post"], url_path="enroll/start") def enroll_start(self, request): """Mint an unconfirmed device and hand back its provisioning URI. @@ -543,10 +531,13 @@ def enroll_start(self, request): Re-starting replaces the previous attempt rather than accumulating dead devices. """ + refusal = self._refuse_if_not_local() + if refusal is not None: + return refusal refusal = self._require_login_session(request) if refusal is not None: return refusal - if _has_second_factor(request.user): + if has_second_factor(request.user): # Swapping in a new authenticator weakens the old one just as # removing it does, so it needs the same proof. refusal = self._require_code(request, AUDIENCE_ENROLL_START) @@ -571,6 +562,9 @@ def enroll_start(self, request): @action(detail=False, methods=["post"], url_path="enroll/confirm") def enroll_confirm(self, request): """Activate the pending device once the user echoes a code from it.""" + refusal = self._refuse_if_not_local() + if refusal is not None: + return refusal refusal = self._require_login_session(request) if refusal is not None: return refusal @@ -639,13 +633,16 @@ def enroll_confirm(self, request): @action(detail=False, methods=["post"], url_path="disable") def disable(self, request): """Remove every device the login view could challenge on.""" - if not _has_second_factor(request.user): + refusal = self._refuse_if_not_local() + if refusal is not None: + return refusal + if not has_second_factor(request.user): return Response({"enrolled": False}) refusal = self._require_code(request, AUDIENCE_DISABLE) if refusal is not None: return refusal with transaction.atomic(): - # _has_second_factor asks default_device(), which answers on any + # has_second_factor asks default_device(), which answers on any # device class named "default". Deleting only the classes this # module creates would report two-factor off while leaving one # standing that nothing here can verify, so never removable. @@ -665,7 +662,10 @@ def disable(self, request): @action(detail=False, methods=["post"], url_path="recovery/generate") def recovery_generate(self, request): """Replace the recovery set and return the new codes once.""" - if not _has_second_factor(request.user): + refusal = self._refuse_if_not_local() + if refusal is not None: + return refusal + if not has_second_factor(request.user): return Response( {"error": "Set up an authenticator before generating recovery codes."}, status=status.HTTP_409_CONFLICT, @@ -696,6 +696,9 @@ def recovery_view(self, request): Disclosing them without a step-up would make a stolen session enough to read a durable second factor. """ + refusal = self._refuse_if_not_local() + if refusal is not None: + return refusal recovery = _recovery_device(request.user) if recovery is None: return Response( @@ -722,7 +725,7 @@ def recovery_view(self, request): ) @action(detail=False, methods=["post"], url_path="verify") - def verify(self, request): + def verify(self, request): # pylint: disable=too-many-return-statements """Check a code without changing anything -- the step-up challenge. The caller names what it intends to do with the proof, and the grant is @@ -730,6 +733,9 @@ def verify(self, request): recognises: minting a grant for an unknown operation would spend the user's code on something they can never redeem. """ + refusal = self._refuse_if_not_local() + if refusal is not None: + return refusal locked = self._locked_out_response(request) if locked is not None: return locked @@ -761,5 +767,5 @@ def verify(self, request): ) clear_verification_failures(request.user) return Response( - {"verified": True, "grant": _issue_grant(request.user, audience)} + {"verified": True, "grant": issue_grant(request.user.pk, audience)} ) diff --git a/onadata/apps/api/viewsets/user_profile_viewset.py b/onadata/apps/api/viewsets/user_profile_viewset.py index 4b8ccb0459..9c1436028f 100644 --- a/onadata/apps/api/viewsets/user_profile_viewset.py +++ b/onadata/apps/api/viewsets/user_profile_viewset.py @@ -5,6 +5,7 @@ import datetime import json +from copy import deepcopy from django.conf import settings from django.contrib.auth.password_validation import validate_password @@ -42,6 +43,15 @@ MonthlySubmissionsSerializer, ) from onadata.libs.serializers.user_profile_serializer import UserProfileSerializer +from onadata.libs.stepup import RequiresStepUp +from onadata.libs.stepup.policy import ( + GATE_CHANGE_EMAIL, + GATE_CHANGE_PASSWORD, + GATE_CHANGE_USERNAME, + GATE_PRIVACY_CONSENT, + GATE_REQUIRE_AUTH, + eu_consent_record, +) from onadata.libs.utils.cache_tools import ( CHANGE_PASSWORD_ATTEMPTS, LOCKOUT_CHANGE_PASSWORD_USER, @@ -153,8 +163,65 @@ def change_password_attempts(request): return 1 +def _parsed_metadata(data): + """The request's metadata, which clients send as a dict or a JSON string. + + ``None`` when it is absent or not valid JSON. + """ + raw = data.get("metadata") + if isinstance(raw, str): + try: + return json.loads(raw) + except ValueError: + return None + return raw + + +def _stored_eu_consent(profile): + return eu_consent_record(profile.metadata or {}) + + +def _changes_email(validated_data, profile) -> bool: + new_email = (validated_data.get("email") or "").strip() + return bool(new_email) and new_email.lower() != (profile.user.email or "").lower() + + +def _changes_require_auth(validated_data, profile) -> bool: + return ( + validated_data.get("require_auth", profile.require_auth) != profile.require_auth + ) + + +def _changes_username(validated_data, profile) -> bool: + current = profile.user.username + return validated_data.get("username", current) != current + + +def _changes_consent(validated_data, profile) -> bool: + """Whether a wholesale metadata write changes the consent record. + + Compared on the effective value, so a payload that omits the record drops + it and counts as a change. The merge path is checked after merging + instead, since it preserves absent keys. + """ + if "metadata" not in validated_data: + return False + return eu_consent_record(validated_data["metadata"]) != _stored_eu_consent(profile) + + +def _merged_metadata(stored, incoming): + merged = deepcopy(stored or {}) + for key, value in incoming.items(): + if check_if_key_exists(key, merged): + merged = replace_key_value(key, value, merged) + else: + merged[key] = value + return merged + + # pylint: disable=too-many-ancestors class UserProfileViewSet( + RequiresStepUp, AuthenticateHeaderMixin, CacheControlMixin, ETagsMixin, @@ -212,12 +279,14 @@ def get_object(self, queryset=None): return obj - def update(self, request, *args, **kwargs): + def update(self, request, *args, **kwargs): # pylint: disable=unused-argument """Update user in cache and db""" username = kwargs.get("user") request_username = request.user.username if request.user else "" safe_cache_delete(f"{USER_PROFILE_PREFIX}{username}{request_username}") - return super().update(request, *args, **kwargs) + return self.gated_update( + request, self._step_up_refusal, partial=kwargs.get("partial", False) + ) def retrieve(self, request, *args, **kwargs): """Get user profile from cache or db""" @@ -285,6 +354,11 @@ def change_password(self, request, *args, **kwargs): # noqa data={"errors": error.messages}, status=status.HTTP_400_BAD_REQUEST ) + # Spend the grant last, so a mistyped or refused password keeps it. + refusal = self.check_step_up(request, GATE_CHANGE_PASSWORD) + if refusal is not None: + return refusal + data = {"username": user_profile.user.username} metadata = user_profile.metadata or {} metadata["last_password_edit"] = timezone.now().isoformat() @@ -296,29 +370,54 @@ def change_password(self, request, *args, **kwargs): # noqa return Response(status=status.HTTP_200_OK, data=data) - def partial_update(self, request, *args, **kwargs): - """Allows for partial update of the user profile data.""" - profile = self.get_object() - metadata = profile.metadata or {} - if request.data.get("overwrite") == "false": - if isinstance(request.data.get("metadata"), str): - metadata_items = json.loads(request.data.get("metadata")).items() - else: - metadata_items = request.data.get("metadata").items() + def _step_up_refusal(self, profile, validated_data): + """Refuse whichever gated change this update would make, or None. - for key, value in metadata_items: - if check_if_key_exists(key, metadata): - metadata = replace_key_value(key, value, metadata) - else: - metadata[key] = value + Reads the validated data, which is what the serializer writes. A + form-encoded PUT that leaves out the require_auth checkbox validates to + False, so turning it off that way is gated too. Each value is gated + only on an actual change, because a full-profile write echoes + unchanged values back. + """ + return self.gated_change_refusal( + self.request, + ( + (GATE_REQUIRE_AUTH, _changes_require_auth(validated_data, profile)), + (GATE_CHANGE_EMAIL, _changes_email(validated_data, profile)), + (GATE_PRIVACY_CONSENT, _changes_consent(validated_data, profile)), + (GATE_CHANGE_USERNAME, _changes_username(validated_data, profile)), + ), + ) - profile.metadata = metadata - profile.save() - username = kwargs.get("user") - request_username = request.user.username if request.user else "" - safe_cache_delete(f"{USER_PROFILE_PREFIX}{username}{request_username}") - return Response(data=profile.metadata, status=status.HTTP_200_OK) + def _merge_metadata(self, request, username): + """Merge the request's metadata into the stored metadata. + Writes nothing else, so the consent record is the only gated value it + can change. + """ + profile = self.get_object() + incoming = _parsed_metadata(request.data) + if not isinstance(incoming, dict): + raise ParseError(_("metadata must be a JSON object.")) + # The merge matches keys by name anywhere in the tree, so it can change + # a nested consent leaf the payload never named. Compare the merged + # result for that reason. + metadata = _merged_metadata(profile.metadata, incoming) + if eu_consent_record(metadata) != _stored_eu_consent(profile): + refusal = self.check_step_up(request, GATE_PRIVACY_CONSENT) + if refusal is not None: + return refusal + + profile.metadata = metadata + profile.save() + request_username = request.user.username if request.user else "" + safe_cache_delete(f"{USER_PROFILE_PREFIX}{username}{request_username}") + return Response(data=profile.metadata, status=status.HTTP_200_OK) + + def partial_update(self, request, *args, **kwargs): + """Allows for partial update of the user profile data.""" + if request.data.get("overwrite") == "false": + return self._merge_metadata(request, kwargs.get("user")) return super().partial_update(request, *args, **kwargs) @action(methods=["GET"], detail=True) diff --git a/onadata/apps/api/viewsets/v2/organization_profile_viewset.py b/onadata/apps/api/viewsets/v2/organization_profile_viewset.py index 054e4ae6c1..910ffab441 100644 --- a/onadata/apps/api/viewsets/v2/organization_profile_viewset.py +++ b/onadata/apps/api/viewsets/v2/organization_profile_viewset.py @@ -128,6 +128,8 @@ def update(self, request, *args, **kwargs): Overrides super().update(), which caches the response """ response = super().update(request, *args, **kwargs) + if not status.is_success(response.status_code): + return response # super() has checked that the user may update the organization organization = OrganizationProfile.objects.get( user__username=self.kwargs[self.lookup_field] @@ -156,6 +158,11 @@ def members(self, request, *args, **kwargs): if request.method != "GET": serializer = self.get_serializer(data=request.data, context=context) serializer.is_valid(raise_exception=True) + refusal = self.member_role_refusal( + request, organization, serializer.validated_data + ) + if refusal is not None: + return refusal serializer.save() if serializer.validated_data["remove"]: diff --git a/onadata/apps/api/viewsets/xform_viewset.py b/onadata/apps/api/viewsets/xform_viewset.py index 7611c6ebe5..ad6d7a4aac 100644 --- a/onadata/apps/api/viewsets/xform_viewset.py +++ b/onadata/apps/api/viewsets/xform_viewset.py @@ -78,6 +78,16 @@ XFormSerializer, XFormVersionListSerializer, ) +from onadata.libs.stepup import RequiresStepUp +from onadata.libs.stepup.policy import ( + GATE_DISABLE_FORM_ENCRYPTION, + GATE_FORM_REQUIRE_AUTH, + GATE_PUBLISH_DATA, + GATE_SHARE_FORM_ADMIN, + GATE_TRANSFER_PROJECT, + is_gated, +) +from onadata.libs.stepup.sharing import admin_roles_granted, holds_roles from onadata.libs.utils.api_export_tools import ( _get_export_type, custom_response_handler, @@ -432,6 +442,52 @@ def _format_enketo_response(urls, survey_type): } +def _publishes_data(xform, validated_data): + return any( + validated_data.get(field) and not getattr(xform, field) + for field in ("shared", "shared_data") + ) or _moves_into_public_project(xform, validated_data) + + +def _moves_into_public_project(xform, validated_data): + """Gated as a move through ``POST /projects//forms`` is: the form is + listed in the public project and takes on its visibility whenever the + project's permissions are next applied to it.""" + project = validated_data.get("project", xform.project) + return ( + project != xform.project + and project.shared + and not (xform.shared or xform.shared_data) + ) + + +def _moves_to_another_account(xform, validated_data): + """Changing a form's owner, or its project to one in another account, + hands that account the form and its data.""" + owner = validated_data.get("user", xform.user) + project = validated_data.get("project", xform.project) + return owner != xform.user or ( + project != xform.project and project.organization != xform.user + ) + + +def _drops_require_auth(xform, validated_data): + return xform.require_auth and not validated_data.get( + "require_auth", xform.require_auth + ) + + +def _disables_encryption(xform, validated_data): + """Mirrors what ``disable_xform_encryption`` refuses, so a request it + would reject does not cost a grant.""" + return ( + validated_data.get("enable_kms_encryption") is False + and xform.encrypted + and not xform.num_of_submissions + and xform.kms_keys.filter(version=xform.version).exists() + ) + + # pylint: disable=too-many-ancestors class XFormViewSet( AnonymousUserPublicFormsMixin, @@ -439,6 +495,7 @@ class XFormViewSet( AuthenticateHeaderMixin, ETagsMixin, LabelsMixin, + RequiresStepUp, BaseViewset, ModelViewSet, ): @@ -767,6 +824,22 @@ def retrieve(self, request, *args, **kwargs): meta, ) + def _share_admin_refusal(self, request, shares): + """Refuse appointing a form owner or manager without a grant. + + The role may be named outright or reached through the form's meta + permissions. A target who already holds the role needs no grant.""" + if not is_gated(GATE_SHARE_FORM_ADMIN): + return None + for share in shares: + granted = admin_roles_granted([self.object], share["role"]) + if not granted: + continue + target = User.objects.get(username=share["username"]) + if not holds_roles(target, granted): + return self.check_step_up(request, GATE_SHARE_FORM_ADMIN) + return None + @action(methods=["POST"], detail=True) def share(self, request, *args, **kwargs): """Perform form sharing.""" @@ -788,6 +861,9 @@ def share(self, request, *args, **kwargs): serializer = ShareXFormSerializer(data=data_list, many=True) if serializer.is_valid(): + refusal = self._share_admin_refusal(request, serializer.validated_data) + if refusal is not None: + return refusal serializer.save() else: return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) @@ -998,6 +1074,33 @@ def csv_import(self, request, *args, **kwargs): ), ) + def _update_refusal(self, request, xform, validated_data): + """Refuse whichever gated change saving ``validated_data`` would make, + or None. Restoring a protection is never gated.""" + return self.gated_change_refusal( + request, + ( + ( + GATE_TRANSFER_PROJECT, + _moves_to_another_account(xform, validated_data), + ), + (GATE_PUBLISH_DATA, _publishes_data(xform, validated_data)), + (GATE_FORM_REQUIRE_AUTH, _drops_require_auth(xform, validated_data)), + ( + GATE_DISABLE_FORM_ENCRYPTION, + _disables_encryption(xform, validated_data), + ), + ), + ) + + def update(self, request, *args, **kwargs): + """Update a form's properties, the target of PUT and PATCH alike.""" + return self.gated_update( + request, + lambda xform, data: self._update_refusal(request, xform, data), + partial=kwargs.pop("partial", False), + ) + def partial_update(self, request, *args, **kwargs): """Partial update of a form's properties.""" # pylint: disable=attribute-defined-outside-init diff --git a/onadata/apps/main/forms.py b/onadata/apps/main/forms.py index aec1118a90..5e7b051ba5 100644 --- a/onadata/apps/main/forms.py +++ b/onadata/apps/main/forms.py @@ -13,7 +13,11 @@ from django import forms from django.conf import settings from django.contrib.auth import authenticate, get_user_model -from django.contrib.auth.forms import AuthenticationForm, PasswordResetForm +from django.contrib.auth.forms import ( + AuthenticationForm, + PasswordChangeForm, + PasswordResetForm, +) from django.core.files.base import ContentFile from django.core.files.storage import default_storage from django.core.validators import URLValidator @@ -742,6 +746,32 @@ def clean(self): return self.cleaned_data +class LockoutPasswordChangeForm(PasswordChangeForm): + """Password change form whose old-password check spends the login form's + allowance and honours its lockout.""" + + def __init__(self, user, *args, request=None, **kwargs): + super().__init__(user, *args, **kwargs) + self.request = request + + @sensitive_variables("old_password") + def clean_old_password(self): + # Avoid circular import + authentication = importlib.import_module("onadata.libs.authentication") + + old_password = self.cleaned_data["old_password"] + try: + if authentication.check_password_with_lockout( + self.request, self.user, old_password + ): + return old_password + except AuthenticationFailed as exc: + raise lockout_validation_error() from exc + raise forms.ValidationError( + self.error_messages["password_incorrect"], code="password_incorrect" + ) + + class RecoveryCodeForm(BackupTokenForm): """Recovery-code step of the login wizard. diff --git a/onadata/apps/main/registration_urls.py b/onadata/apps/main/registration_urls.py index 2447200934..8f0b6a57ca 100644 --- a/onadata/apps/main/registration_urls.py +++ b/onadata/apps/main/registration_urls.py @@ -19,6 +19,7 @@ ) from onadata.apps.main.registration_views import ( FHRegistrationView, + StepUpPasswordChangeView, TokenRotatingPasswordResetConfirmView, ) @@ -78,5 +79,14 @@ ), name="auth_password_reset_confirm", ), + # Gates password change like the API's change_password. Keep it above the + # registration.auth_urls include, which defines the same route. + path( + "password/change/", + StepUpPasswordChangeView.as_view( + success_url=reverse_lazy("auth_password_change_done") + ), + name="auth_password_change", + ), re_path(r"", include("registration.auth_urls")), ] diff --git a/onadata/apps/main/registration_views.py b/onadata/apps/main/registration_views.py index 70d2c63d73..6261c3318f 100644 --- a/onadata/apps/main/registration_views.py +++ b/onadata/apps/main/registration_views.py @@ -3,10 +3,13 @@ FHRegistrationView class module. """ -from django.contrib.auth.views import PasswordResetConfirmView +from django.contrib.auth.views import PasswordChangeView, PasswordResetConfirmView from registration.backends.default.views import RegistrationView +from onadata.apps.main.forms import LockoutPasswordChangeForm +from onadata.libs.stepup.pages import refuse_page_action +from onadata.libs.stepup.policy import GATE_CHANGE_PASSWORD from onadata.libs.utils.user_auth import invalidate_and_regen_tokens @@ -35,3 +38,24 @@ def form_valid(self, form): invalidate_and_regen_tokens(user=self.user) return response + + +class StepUpPasswordChangeView(PasswordChangeView): + """PasswordChangeView behind the same step-up gate as the API's + ``change_password``. + + Checked once the old password is confirmed, so a mistyped one does not + spend the grant. + """ + + form_class = LockoutPasswordChangeForm + + def get_form_kwargs(self): + return {**super().get_form_kwargs(), "request": self.request} + + def form_valid(self, form): + refusal = refuse_page_action(self.request, GATE_CHANGE_PASSWORD) + if refusal is not None: + return refusal + + return super().form_valid(form) diff --git a/onadata/apps/main/tests/test_stepup_legacy_publish_gate.py b/onadata/apps/main/tests/test_stepup_legacy_publish_gate.py new file mode 100644 index 0000000000..e0a37b7f61 --- /dev/null +++ b/onadata/apps/main/tests/test_stepup_legacy_publish_gate.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- +""" +Tests for the step-up gate on making a form or its data public from the +legacy form edit page. +""" + +from django.test.utils import override_settings +from django.urls import reverse + +from django_otp.plugins.otp_totp.models import TOTPDevice +from oidc.stepup_grants import issue_grant, spend_grant + +from onadata.apps.logger.models import XForm +from onadata.apps.main.tests.test_base import TestBase +from onadata.apps.main.views import edit + +PUBLISH_DATA = "publish-data" +SHARED_FLAGS = {"data": "shared_data", "form": "shared"} + + +@override_settings( + STEP_UP={ + "MODE": "local", + "ACTIONS": [PUBLISH_DATA], + "NO_FACTOR_POLICY": "skip_gate", + } +) +class TestLegacyPublishDataGate(TestBase): + """Sharing a form or its data opens it to anyone, so a stolen session + alone must not be able to.""" + + def setUp(self): + super().setUp() + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + self._publish_transportation_form() + self.edit_url = reverse( + edit, + kwargs={"username": self.user.username, "id_string": self.xform.id_string}, + ) + + def _toggle(self, target, **extra): + return self.client.post( + self.edit_url, + {"toggle_shared": target, **extra}, + HTTP_X_REQUESTED_WITH="XMLHttpRequest", + ) + + def _flag(self, target): + return getattr(XForm.objects.get(pk=self.xform.pk), SHARED_FLAGS[target]) + + def _set_flag(self, target, value): + XForm.objects.filter(pk=self.xform.pk).update(**{SHARED_FLAGS[target]: value}) + self.assertEqual(self._flag(target), value) + + def test_sharing_without_a_grant_is_refused(self): + for target in SHARED_FLAGS: + with self.subTest(target=target): + self._set_flag(target, False) + + response = self._toggle(target) + + self.assertEqual(response.status_code, 403) + self.assertFalse(self._flag(target)) + + def test_a_grant_lets_the_sharing_through(self): + for target in SHARED_FLAGS: + with self.subTest(target=target): + self._set_flag(target, False) + grant = issue_grant(self.user.pk, PUBLISH_DATA) + + response = self._toggle(target, grant=grant) + + self.assertEqual(response.status_code, 200) + self.assertTrue(self._flag(target)) + self.assertFalse(spend_grant(self.user.pk, PUBLISH_DATA, grant)) + + def test_unsharing_is_not_challenged(self): + for target in SHARED_FLAGS: + with self.subTest(target=target): + self._set_flag(target, False) + self.assertEqual(self._toggle(target).status_code, 403) + self._set_flag(target, True) + + response = self._toggle(target) + + self.assertEqual(response.status_code, 200) + self.assertFalse(self._flag(target)) diff --git a/onadata/apps/main/tests/test_stepup_oauth_gate.py b/onadata/apps/main/tests/test_stepup_oauth_gate.py new file mode 100644 index 0000000000..bc6ee72a74 --- /dev/null +++ b/onadata/apps/main/tests/test_stepup_oauth_gate.py @@ -0,0 +1,327 @@ +# -*- coding: utf-8 -*- +""" +Tests for the step-up gate on approving, registering or redirecting an OAuth +application. +""" + +import base64 +import hashlib +from datetime import timedelta +from urllib.parse import parse_qs, urlparse + +from django.contrib.auth import get_user_model +from django.test import TestCase +from django.test.utils import override_settings +from django.utils import timezone + +from django_otp.plugins.otp_totp.models import TOTPDevice +from oauth2_provider.models import AccessToken, Grant, get_application_model +from oidc.stepup_grants import issue_grant, spend_grant + +AUTHORIZE_OAUTH_APP = "authorize-oauth-app" +STEP_UP_ON = { + "MODE": "local", + "ACTIONS": [AUTHORIZE_OAUTH_APP], + "NO_FACTOR_POLICY": "skip_gate", +} +STEP_UP_OFF = {**STEP_UP_ON, "ACTIONS": []} + +AUTHORIZE_URL = "/o/authorize/" +REGISTER_URL = "/o/applications/register/" +REDIRECT_URI = "https://client.example.test/oauth/callback" +OTHER_REDIRECT_URI = "https://elsewhere.example.test/oauth/callback" +VERIFIER = "v" * 43 + + +def _challenge(): + digest = hashlib.sha256(VERIFIER.encode("ascii")).digest() + return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii") + + +def _query(response): + return parse_qs(urlparse(response["Location"]).query) + + +class StepUpOAuthTestCase(TestCase): + """A logged-in user with a confirmed factor, and helpers for the OAuth + pages.""" + + @classmethod + def setUpTestData(cls): + user_model = get_user_model() + cls.user = user_model.objects.create_user(username="oauth-gate-user") + cls.app_owner = user_model.objects.create_user(username="oauth-app-owner") + + def setUp(self): + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + self.client.force_login(self.user) + + def _application(self, **overrides): + application_model = get_application_model() + fields = { + "user": self.app_owner, + "name": "Third-party application", + "client_type": application_model.CLIENT_PUBLIC, + "authorization_grant_type": application_model.GRANT_AUTHORIZATION_CODE, + "redirect_uris": REDIRECT_URI, + **overrides, + } + return application_model.objects.create(**fields) + + @staticmethod + def _authorization(application): + return { + "client_id": application.client_id, + "redirect_uri": REDIRECT_URI, + "response_type": "code", + "scope": "read", + "state": "safe-state", + "code_challenge": _challenge(), + "code_challenge_method": "S256", + } + + def _approve(self, application, **extra): + return self.client.post( + AUTHORIZE_URL, {**self._authorization(application), "allow": True, **extra} + ) + + @staticmethod + def _registration(**overrides): + application_model = get_application_model() + return { + "name": "Registered application", + "client_id": "registered-client", + "client_type": application_model.CLIENT_PUBLIC, + "authorization_grant_type": application_model.GRANT_AUTHORIZATION_CODE, + "redirect_uris": OTHER_REDIRECT_URI, + "post_logout_redirect_uris": "", + "allowed_origins": "", + "algorithm": "", + **overrides, + } + + def _update(self, application, **changes): + data = self._registration( + name=application.name, + client_id=application.client_id, + client_type=application.client_type, + redirect_uris=application.redirect_uris, + ) + return self.client.post( + f"/o/applications/{application.pk}/update/", {**data, **changes} + ) + + def _grant(self): + return issue_grant(self.user.pk, AUTHORIZE_OAUTH_APP) + + def _codes(self, application): + return Grant.objects.filter(application=application, user=self.user) + + +@override_settings(STEP_UP=STEP_UP_ON) +class TestApprovingAnOAuthApplication(StepUpOAuthTestCase): + """Approving an application issues it a long-lived credential, so a + stolen session alone must not be able to.""" + + def test_approving_without_a_grant_is_refused(self): + application = self._application() + consent = self.client.get(AUTHORIZE_URL, self._authorization(application)) + self.assertEqual(consent.status_code, 200) + + response = self._approve(application) + + self.assertEqual(response.status_code, 403) + self.assertFalse(self._codes(application).exists()) + self.assertFalse(AccessToken.objects.filter(application=application).exists()) + + def test_a_grant_lets_the_approval_through(self): + application = self._application() + grant = self._grant() + + response = self._approve(application, grant=grant) + + self.assertEqual(response.status_code, 302) + self.assertIn("code", _query(response)) + self.assertTrue(self._codes(application).exists()) + self.assertFalse(spend_grant(self.user.pk, AUTHORIZE_OAUTH_APP, grant)) + + def test_denying_is_not_challenged(self): + application = self._application() + self.assertEqual(self._approve(application).status_code, 403) + + response = self.client.post(AUTHORIZE_URL, self._authorization(application)) + + self.assertEqual(response.status_code, 302) + self.assertEqual(_query(response)["error"], ["access_denied"]) + self.assertFalse(self._codes(application).exists()) + + def test_an_invalid_approval_keeps_the_grant(self): + """The form validates first, so a tampered request does not spend it.""" + application = self._application() + grant = self._grant() + data = {**self._authorization(application), "allow": True, "grant": grant} + del data["client_id"] + + response = self.client.post(AUTHORIZE_URL, data) + + self.assertNotEqual(response.status_code, 302) + self.assertFalse(self._codes(application).exists()) + self.assertTrue(spend_grant(self.user.pk, AUTHORIZE_OAUTH_APP, grant)) + + def test_skip_authorization_falls_back_to_the_consent_form(self): + application = self._application(skip_authorization=True) + self.assertTrue(application.skip_authorization) + + response = self.client.get(AUTHORIZE_URL, self._authorization(application)) + + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'name="allow"') + self.assertFalse(self._codes(application).exists()) + + def test_a_matching_token_falls_back_to_the_consent_form(self): + application = self._application() + AccessToken.objects.create( + user=self.user, + application=application, + token="existing-access-token", + expires=timezone.now() + timedelta(hours=1), + scope="read", + ) + data = {**self._authorization(application), "approval_prompt": "auto"} + + response = self.client.get(AUTHORIZE_URL, data) + + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'name="allow"') + self.assertFalse(self._codes(application).exists()) + + def test_a_header_grant_lets_auto_approval_through(self): + application = self._application(skip_authorization=True) + grant = self._grant() + + response = self.client.get( + AUTHORIZE_URL, + self._authorization(application), + HTTP_X_STEP_UP_GRANT=grant, + ) + + self.assertEqual(response.status_code, 302) + self.assertIn("code", _query(response)) + self.assertFalse(spend_grant(self.user.pk, AUTHORIZE_OAUTH_APP, grant)) + + +@override_settings(STEP_UP=STEP_UP_ON) +class TestRegisteringAnOAuthApplication(StepUpOAuthTestCase): + """Registering an application, or pointing one at new redirect URIs, + lets whoever holds the session collect the codes it is issued.""" + + def _registered(self): + return get_application_model().objects.filter(user=self.user) + + def test_registering_without_a_grant_is_refused(self): + self.assertFalse(self._registered().exists()) + + response = self.client.post(REGISTER_URL, self._registration()) + + self.assertEqual(response.status_code, 403) + self.assertFalse(self._registered().exists()) + + def test_a_grant_lets_the_registration_through(self): + grant = self._grant() + + response = self.client.post(REGISTER_URL, self._registration(grant=grant)) + + self.assertEqual(response.status_code, 302) + self.assertEqual( + list(self._registered().values_list("redirect_uris", flat=True)), + [OTHER_REDIRECT_URI], + ) + self.assertFalse(spend_grant(self.user.pk, AUTHORIZE_OAUTH_APP, grant)) + + def test_an_invalid_registration_keeps_the_grant(self): + """Validation comes first, so a missing field does not spend it.""" + grant = self._grant() + + response = self.client.post( + REGISTER_URL, self._registration(client_type="", grant=grant) + ) + + self.assertIn(response.status_code, (200, 400)) + self.assertFalse(self._registered().exists()) + self.assertTrue(spend_grant(self.user.pk, AUTHORIZE_OAUTH_APP, grant)) + + def test_changing_redirect_uris_without_a_grant_is_refused(self): + application = self._application(user=self.user) + + response = self._update(application, redirect_uris=OTHER_REDIRECT_URI) + + self.assertEqual(response.status_code, 403) + application.refresh_from_db() + self.assertEqual(application.redirect_uris, REDIRECT_URI) + + def test_changing_the_client_type_without_a_grant_is_refused(self): + application_model = get_application_model() + application = self._application( + user=self.user, client_type=application_model.CLIENT_CONFIDENTIAL + ) + + response = self._update( + application, client_type=application_model.CLIENT_PUBLIC + ) + + self.assertEqual(response.status_code, 403) + application.refresh_from_db() + self.assertEqual(application.client_type, application_model.CLIENT_CONFIDENTIAL) + + def test_a_grant_lets_the_redirect_change_through(self): + application = self._application(user=self.user) + grant = self._grant() + + response = self._update( + application, redirect_uris=OTHER_REDIRECT_URI, grant=grant + ) + + self.assertEqual(response.status_code, 302) + application.refresh_from_db() + self.assertEqual(application.redirect_uris, OTHER_REDIRECT_URI) + self.assertFalse(spend_grant(self.user.pk, AUTHORIZE_OAUTH_APP, grant)) + + def test_renaming_is_not_challenged(self): + application = self._application(user=self.user) + self.assertEqual( + self._update(application, redirect_uris=OTHER_REDIRECT_URI).status_code, 403 + ) + + response = self._update(application, name="Renamed application") + + self.assertEqual(response.status_code, 302) + application.refresh_from_db() + self.assertEqual(application.name, "Renamed application") + self.assertEqual(application.redirect_uris, REDIRECT_URI) + + +@override_settings(STEP_UP=STEP_UP_OFF) +class TestOAuthGateOff(StepUpOAuthTestCase): + """A deployment that has not opted in needs no grant.""" + + def test_approving_needs_no_grant(self): + application = self._application() + + response = self._approve(application) + + self.assertEqual(response.status_code, 302) + self.assertIn("code", _query(response)) + + def test_skip_authorization_still_approves_on_get(self): + application = self._application(skip_authorization=True) + + response = self.client.get(AUTHORIZE_URL, self._authorization(application)) + + self.assertEqual(response.status_code, 302) + self.assertIn("code", _query(response)) + + def test_registering_needs_no_grant(self): + response = self.client.post(REGISTER_URL, self._registration()) + + self.assertEqual(response.status_code, 302) + self.assertTrue(get_application_model().objects.filter(user=self.user).exists()) diff --git a/onadata/apps/main/tests/test_stepup_pages.py b/onadata/apps/main/tests/test_stepup_pages.py new file mode 100644 index 0000000000..56be56db4d --- /dev/null +++ b/onadata/apps/main/tests/test_stepup_pages.py @@ -0,0 +1,177 @@ +# -*- coding: utf-8 -*- +""" +Tests for the step-up gate on pages that write gated values. +""" + +from unittest.mock import patch + +from django.conf import settings +from django.core.cache import cache +from django.test import override_settings +from django.urls import reverse + +from django_otp.plugins.otp_totp.models import TOTPDevice +from oidc.stepup_grants import issue_grant, spend_grant + +from onadata.apps.main.models import UserProfile +from onadata.apps.main.tests.test_base import TestBase +from onadata.apps.main.views import profile_settings + +GATED = { + "MODE": "local", + "ACTIONS": {"change-email", "require-auth-toggle", "change-password"}, + "NO_FACTOR_POLICY": "skip_gate", +} + +EMAIL = "bob@example.org" +NEW_EMAIL = "somewhere.else@example.org" +NEW_PASSWORD = "Tr0ub4dor-and-3-horses" + + +@override_settings(STEP_UP=GATED) +class TestProfileSettingsPageGate(TestBase): + """The settings page writes email and require_auth, so it must not be a + way around the API's gates.""" + + def setUp(self): + super().setUp() + # The form requires an email, and TestBase's user has none. Without + # one, every post fails validation before it reaches the gate. + self.user.email = EMAIL + self.user.save() + # Enrolled, because skip_gate lets a user with no factor through. + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + self.url = reverse(profile_settings, kwargs={"username": self.user.username}) + + def _post(self, data): + """Post the form as rendered. Each gated value keeps its stored value + unless ``data`` changes it.""" + profile = UserProfile.objects.get(user=self.user) + return self.client.post( + self.url, + { + "name": "Bobby", + "email": EMAIL, + "require_auth": profile.require_auth, + **data, + }, + ) + + def test_changing_the_email_without_a_grant_is_refused(self): + response = self._post({"email": NEW_EMAIL}) + + self.assertEqual(response.status_code, 403) + self.user.refresh_from_db() + self.assertEqual(self.user.email, EMAIL) + + def test_changing_require_auth_without_a_grant_is_refused(self): + before = UserProfile.objects.get(user=self.user).require_auth + + response = self._post({"require_auth": not before}) + + self.assertEqual(response.status_code, 403) + self.assertEqual(UserProfile.objects.get(user=self.user).require_auth, before) + + def test_two_gated_changes_are_refused_without_spending_the_grant(self): + """The grant is for require-auth-toggle because the toggle is checked + first. Checking one change at a time would spend it and then refuse + the email.""" + before = UserProfile.objects.get(user=self.user).require_auth + grant = issue_grant(self.user.pk, "require-auth-toggle") + + response = self._post( + {"email": NEW_EMAIL, "require_auth": not before, "grant": grant} + ) + + self.assertEqual(response.status_code, 403) + self.assertIn(b"Change one protected setting at a time.", response.content) + self.user.refresh_from_db() + self.assertEqual(self.user.email, EMAIL) + self.assertTrue(spend_grant(self.user.pk, "require-auth-toggle", grant)) + + def test_an_edit_changing_no_gated_value_is_saved(self): + self.assertEqual(self._post({"email": NEW_EMAIL}).status_code, 403) + + response = self._post({"city": "Bobville"}) + + self.assertEqual(response.status_code, 302) + self.assertEqual(UserProfile.objects.get(user=self.user).city, "Bobville") + + def test_a_grant_in_the_form_lets_the_email_change_through(self): + grant = issue_grant(self.user.pk, "change-email") + + response = self._post({"email": NEW_EMAIL, "grant": grant}) + + self.assertEqual(response.status_code, 302) + self.user.refresh_from_db() + self.assertEqual(self.user.email, NEW_EMAIL) + + +@override_settings(STEP_UP=GATED) +class TestPasswordChangePageGate(TestBase): + """The password page changes the password as the API's change_password + does, so it is gated the same way.""" + + def setUp(self): + super().setUp() + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + self.url = reverse("auth_password_change") + + def _post(self, data=None): + return self.client.post( + self.url, + { + "old_password": self.login_password, + "new_password1": NEW_PASSWORD, + "new_password2": NEW_PASSWORD, + **(data or {}), + }, + ) + + def test_changing_the_password_without_a_grant_is_refused(self): + response = self._post() + + self.assertEqual(response.status_code, 403) + self.user.refresh_from_db() + self.assertTrue(self.user.check_password(self.login_password)) + + def test_a_grant_lets_the_password_change_through(self): + grant = issue_grant(self.user.pk, "change-password") + + response = self._post({"grant": grant}) + + self.assertRedirects( + response, + reverse("auth_password_change_done"), + fetch_redirect_response=False, + ) + self.user.refresh_from_db() + self.assertTrue(self.user.check_password(NEW_PASSWORD)) + + @override_settings(MAX_LOGIN_ATTEMPTS=3) + def test_repeated_wrong_old_passwords_lock_out_the_page(self): + """The old-password check spends the login form's allowance, so the + page is no way to guess the password around the lockout.""" + # The counter lives in the cache, which the test runner does not roll + # back. + cache.clear() + self.addCleanup(cache.clear) + grant = issue_grant(self.user.pk, "change-password") + + with patch( + "onadata.libs.authentication.send_account_lockout_email.apply_async" + ): + first = self._post({"old_password": "not-my-password"}) + for _ in range(settings.MAX_LOGIN_ATTEMPTS - 1): + self._post({"old_password": "not-my-password"}) + + refused = self._post({"grant": grant}) + + self.assertTrue( + first.context["form"].has_error("old_password", "password_incorrect") + ) + self.assertEqual(refused.status_code, 200) + self.assertTrue(refused.context["form"].has_error("old_password", "locked_out")) + self.user.refresh_from_db() + self.assertTrue(self.user.check_password(self.login_password)) + self.assertTrue(spend_grant(self.user.pk, "change-password", grant)) diff --git a/onadata/apps/main/tests/test_stepup_public_link_gate.py b/onadata/apps/main/tests/test_stepup_public_link_gate.py new file mode 100644 index 0000000000..ff90be13be --- /dev/null +++ b/onadata/apps/main/tests/test_stepup_public_link_gate.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +""" +Tests for the step-up gate on turning on a form's public link from the +legacy form permissions page. +""" + +from django.test.utils import override_settings +from django.urls import reverse + +from django_otp.plugins.otp_totp.models import TOTPDevice +from oidc.stepup_grants import issue_grant, spend_grant + +from onadata.apps.main.models import MetaData +from onadata.apps.main.tests.test_base import TestBase +from onadata.apps.main.views import set_perm + +PUBLISH_DATA = "publish-data" + + +@override_settings( + STEP_UP={ + "MODE": "local", + "ACTIONS": [PUBLISH_DATA], + "NO_FACTOR_POLICY": "skip_gate", + } +) +class TestPublicLinkGate(TestBase): + """A public link opens the form to anyone holding it, so a stolen session + alone must not be able to turn it on.""" + + def setUp(self): + super().setUp() + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + self._publish_transportation_form() + self.perm_url = reverse( + set_perm, + kwargs={"username": self.user.username, "id_string": self.xform.id_string}, + ) + + def _set_link(self, for_user, **extra): + return self.client.post( + self.perm_url, + {"perm_type": "link", "for_user": for_user, **extra}, + HTTP_X_REQUESTED_WITH="XMLHttpRequest", + ) + + def _link_is_on(self): + return bool(MetaData.public_link(self.xform)) + + def _turn_link(self, value): + MetaData.public_link(self.xform, value) + self.assertEqual(self._link_is_on(), value) + + def test_turning_the_link_on_without_a_grant_is_refused(self): + for for_user in ("all", "toggle"): + with self.subTest(for_user=for_user): + self._turn_link(False) + + response = self._set_link(for_user) + + self.assertEqual(response.status_code, 403) + self.assertFalse(self._link_is_on()) + + def test_a_grant_lets_the_link_on(self): + for for_user in ("all", "toggle"): + with self.subTest(for_user=for_user): + self._turn_link(False) + grant = issue_grant(self.user.pk, PUBLISH_DATA) + + response = self._set_link(for_user, grant=grant) + + self.assertEqual(response.status_code, 200) + self.assertTrue(self._link_is_on()) + self.assertFalse(spend_grant(self.user.pk, PUBLISH_DATA, grant)) + + def test_turning_the_link_off_is_not_challenged(self): + for for_user in ("none", "toggle"): + with self.subTest(for_user=for_user): + self._turn_link(False) + self.assertEqual(self._set_link("all").status_code, 403) + self._turn_link(True) + + response = self._set_link(for_user) + + self.assertEqual(response.status_code, 200) + self.assertFalse(self._link_is_on()) + + def test_an_already_on_link_is_not_challenged(self): + self._turn_link(True) + + response = self._set_link("all") + + self.assertEqual(response.status_code, 200) + self.assertTrue(self._link_is_on()) diff --git a/onadata/apps/main/urls.py b/onadata/apps/main/urls.py index 728e93e784..b2d0015517 100644 --- a/onadata/apps/main/urls.py +++ b/onadata/apps/main/urls.py @@ -128,6 +128,16 @@ main_views.LockoutTokenView.as_view(), name="oauth2_provider_token", ), + re_path( + r"^o/applications/register/$", + main_views.StepUpApplicationRegistration.as_view(), + name="oauth2_provider_register", + ), + re_path( + r"^o/applications/(?P[-\w]+)/update/$", + main_views.StepUpApplicationUpdate.as_view(), + name="oauth2_provider_update", + ), re_path(r"^o/", include("oauth2_provider.urls", namespace="oauth2_provider")), # main website views re_path(r"^$", main_views.home), diff --git a/onadata/apps/main/views.py b/onadata/apps/main/views.py index 6abdba17be..e495fd51e6 100644 --- a/onadata/apps/main/views.py +++ b/onadata/apps/main/views.py @@ -9,6 +9,7 @@ from datetime import datetime from http import HTTPStatus +from django import forms from django.conf import settings from django.contrib import messages from django.contrib.auth import get_user_model @@ -38,6 +39,11 @@ from bson import json_util from bson.objectid import ObjectId from guardian.shortcuts import assign_perm, remove_perm +from oauth2_provider.forms import AllowForm +from oauth2_provider.views.application import ( + ApplicationRegistration, + ApplicationUpdate, +) from oauth2_provider.views.base import AuthorizationView, TokenView from rest_framework.authtoken.models import Token from rest_framework.exceptions import AuthenticationFailed @@ -87,6 +93,13 @@ ) from onadata.libs.exceptions import EnketoError from onadata.libs.permissions import CAN_VIEW_PROJECT +from onadata.libs.stepup.gate import refusal_reason +from onadata.libs.stepup.pages import ( + gated_profile_values, + refuse_gated_changes, + refuse_page_action, +) +from onadata.libs.stepup.policy import GATE_AUTHORIZE_OAUTH_APP, GATE_PUBLISH_DATA from onadata.libs.utils.decorators import is_owner from onadata.libs.utils.export_tools import upload_template_for_external_export from onadata.libs.utils.log import Actions, audit_log @@ -378,8 +391,24 @@ def profile_settings(request, username): user_profile, _created = UserProfile.objects.get_or_create(user=content_user) if request.method == "POST": + # Taken before validation, which writes the posted values onto + # user_profile. + gated_before = gated_profile_values( + user_profile.require_auth, content_user.email, user_profile.metadata + ) form = UserProfileForm(request.POST, instance=user_profile) if form.is_valid(): + refusal = refuse_gated_changes( + request, + gated_before, + gated_profile_values( + form.cleaned_data["require_auth"], + form.cleaned_data["email"], + form.cleaned_data["metadata"], + ), + ) + if refusal is not None: + return refusal # get user # user.email = cleaned_email form.instance.user.email = form.cleaned_data["email"] @@ -687,6 +716,18 @@ def public_api(request, username, id_string): return JsonResponse(exports) +_PUBLIC_FLAGS = {"data": "shared_data", "form": "shared"} + + +def _refuse_making_public(request, xform): + """``None``, or a 403 for sharing a form or its data without a grant. + Unsharing is never gated.""" + flag = _PUBLIC_FLAGS.get(request.POST["toggle_shared"]) + if flag is None or getattr(xform, flag): + return None + return refuse_page_action(request, GATE_PUBLISH_DATA) + + # pylint: disable=too-many-locals,too-many-branches,too-many-statements @login_required def edit(request, username, id_string): # noqa C901 @@ -737,6 +778,9 @@ def edit(request, username, id_string): # noqa C901 ) xform.title = request.POST["title"] elif request.POST.get("toggle_shared"): + refusal = _refuse_making_public(request, xform) + if refusal is not None: + return refusal if request.POST["toggle_shared"] == "data": audit = {"xform": xform.id_string} old_shared = _("shared") if xform.shared_data else _("not shared") @@ -1500,6 +1544,10 @@ def set_perm(request, username, id_string): # noqa C901 remove_perm("report_xform", user, xform) elif perm_type == "link": current = MetaData.public_link(xform) + if not current and for_user in ("all", "toggle"): + refusal = refuse_page_action(request, GATE_PUBLISH_DATA) + if refusal is not None: + return refusal if for_user == "all": MetaData.public_link(xform, True) elif for_user == "none": @@ -1814,6 +1862,20 @@ def username_list(request): return JsonResponse(data, safe=False) +def _with_grant_field(form_class): + """``form_class`` with a hidden ``grant`` field, so a re-rendered page + keeps the grant that was posted with it.""" + + class StepUpForm(form_class): # pylint: disable=too-few-public-methods + grant = forms.CharField(required=False, label="", widget=forms.HiddenInput()) + + return StepUpForm + + +class _AutoApprovalNeedsStepUp(Exception): + """The toolkit tried to approve on GET for a request the gate refuses.""" + + # pylint: disable=too-few-public-methods class OnaAuthorizationView(AuthorizationView): """ @@ -1821,6 +1883,8 @@ class OnaAuthorizationView(AuthorizationView): and adds the user to the context """ + form_class = _with_grant_field(AllowForm) + def get_context_data(self, **kwargs): """Adds `user` and `request_path` to context and returns the context.""" context = super().get_context_data(**kwargs) @@ -1828,6 +1892,68 @@ def get_context_data(self, **kwargs): context["request_path"] = self.request.get_full_path() return context + def get(self, request, *args, **kwargs): + """Show the consent form where the toolkit would approve on GET + without a grant, through ``skip_authorization`` or + ``approval_prompt=auto``.""" + try: + return super().get(request, *args, **kwargs) + except _AutoApprovalNeedsStepUp: + return self.render_to_response(self.get_context_data(**self.oauth2_data)) + + def form_valid(self, form): + if form.cleaned_data.get("allow"): + refusal = refuse_page_action(self.request, GATE_AUTHORIZE_OAUTH_APP) + if refusal is not None: + return refusal + return super().form_valid(form) + + def create_authorization_response(self, request, scopes, credentials, allow): + if ( + allow + and request.method == "GET" + and refusal_reason(request, GATE_AUTHORIZE_OAUTH_APP) is not None + ): + raise _AutoApprovalNeedsStepUp + return super().create_authorization_response( + request, scopes, credentials, allow + ) + + +class StepUpApplicationRegistration(ApplicationRegistration): + """Registers an OAuth application only with a grant, since its redirect + URIs decide who receives the codes it is issued.""" + + def get_form_class(self): + return _with_grant_field(super().get_form_class()) + + def form_valid(self, form): + refusal = refuse_page_action(self.request, GATE_AUTHORIZE_OAUTH_APP) + if refusal is not None: + return refusal + return super().form_valid(form) + + +def _redirect_target(values): + return (values.get("client_type"), (values.get("redirect_uris") or "").split()) + + +class StepUpApplicationUpdate(ApplicationUpdate): + """Changes an OAuth application's redirect URIs or client type only with + a grant. Other edits are not gated.""" + + def get_form_class(self): + return _with_grant_field(super().get_form_class()) + + def form_valid(self, form): + # form.instance already holds the posted values, so compare against + # form.initial. + if _redirect_target(form.initial) != _redirect_target(form.cleaned_data): + refusal = refuse_page_action(self.request, GATE_AUTHORIZE_OAUTH_APP) + if refusal is not None: + return refusal + return super().form_valid(form) + class LockoutTokenView(TokenView): """OAuth2 token endpoint with failed-login lockout on the password grant. diff --git a/onadata/apps/restservice/tests/viewsets/test_stepup_webhook_gate.py b/onadata/apps/restservice/tests/viewsets/test_stepup_webhook_gate.py new file mode 100644 index 0000000000..037438d97b --- /dev/null +++ b/onadata/apps/restservice/tests/viewsets/test_stepup_webhook_gate.py @@ -0,0 +1,255 @@ +# -*- coding: utf-8 -*- +""" +Tests for the step-up gate on creating or redirecting a REST service. +""" + +from django.conf import settings +from django.urls import reverse + +from oidc.stepup_grants import issue_grant, spend_grant + +from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import ( + StepUpGateTestCase, + gating, +) +from onadata.apps.main.models.meta_data import MetaData +from onadata.apps.restservice.models import RestService +from onadata.apps.restservice.views import add_service +from onadata.apps.restservice.viewsets.restservices_viewset import RestServicesViewSet + +CHANGE_WEBHOOK = "change-webhook" +SERVICE_URL = "https://example.com/hook" +OTHER_URL = "https://elsewhere.example.org/hook" + + +@gating(CHANGE_WEBHOOK) +class TestChangeWebhookGate(StepUpGateTestCase): + """A webhook copies every submission to its URL, so a stolen session + alone must not be able to add one or point one somewhere else.""" + + def setUp(self): + super().setUp() + self.view = RestServicesViewSet.as_view( + { + "post": "create", + "put": "update", + "patch": "partial_update", + "delete": "destroy", + } + ) + self._publish_xls_form_to_project() + + def _request(self, method, data=None, headers=None, **kwargs): + request = getattr(self.factory, method)( + "/", data=data, format="json", **{**self.extra, **(headers or {})} + ) + return self.view(request, **kwargs) + + def _grant_header(self): + return {"HTTP_X_STEP_UP_GRANT": issue_grant(self.user.pk, CHANGE_WEBHOOK)} + + def _new_service(self, **overrides): + return { + "name": "generic_json", + "service_url": SERVICE_URL, + "xform": self.xform.pk, + **overrides, + } + + def _service(self): + return RestService.objects.create( + xform=self.xform, name="generic_json", service_url=SERVICE_URL + ) + + def test_creating_a_webhook_without_a_grant_is_challenged(self): + self.assertFalse(RestService.objects.exists()) + + response = self._request("post", self._new_service()) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], CHANGE_WEBHOOK) + self.assertFalse(RestService.objects.exists()) + + def test_a_grant_lets_the_webhook_be_created(self): + response = self._request("post", self._new_service(), self._grant_header()) + + self.assertEqual(response.status_code, 201) + self.assertEqual( + list(RestService.objects.values_list("service_url", flat=True)), + [SERVICE_URL], + ) + + def test_an_invalid_webhook_keeps_the_grant(self): + """Validation comes first, so a mistyped URL does not spend it.""" + grant = issue_grant(self.user.pk, CHANGE_WEBHOOK) + + response = self._request( + "post", + self._new_service(service_url="not a url"), + {"HTTP_X_STEP_UP_GRANT": grant}, + ) + + self.assertEqual(response.status_code, 400) + self.assertIn("service_url", response.data) + self.assertFalse(RestService.objects.exists()) + self.assertTrue(spend_grant(self.user.pk, CHANGE_WEBHOOK, grant)) + + def test_changing_the_url_without_a_grant_is_challenged(self): + service = self._service() + + response = self._request("patch", {"service_url": OTHER_URL}, pk=service.pk) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], CHANGE_WEBHOOK) + service.refresh_from_db() + self.assertEqual(service.service_url, SERVICE_URL) + + def test_changing_the_service_type_without_a_grant_is_challenged(self): + service = self._service() + + response = self._request("patch", {"name": "generic_xml"}, pk=service.pk) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], CHANGE_WEBHOOK) + service.refresh_from_db() + self.assertEqual(service.name, "generic_json") + + def test_a_grant_lets_the_url_change_through(self): + service = self._service() + + response = self._request( + "patch", {"service_url": OTHER_URL}, self._grant_header(), pk=service.pk + ) + + self.assertEqual(response.status_code, 200) + service.refresh_from_db() + self.assertEqual(service.service_url, OTHER_URL) + + def test_an_invalid_url_change_keeps_the_grant(self): + service = self._service() + grant = issue_grant(self.user.pk, CHANGE_WEBHOOK) + + response = self._request( + "patch", + {"service_url": "not a url"}, + {"HTTP_X_STEP_UP_GRANT": grant}, + pk=service.pk, + ) + + self.assertEqual(response.status_code, 400) + service.refresh_from_db() + self.assertEqual(service.service_url, SERVICE_URL) + self.assertTrue(spend_grant(self.user.pk, CHANGE_WEBHOOK, grant)) + + def test_a_put_echoing_the_destination_is_not_challenged(self): + """A client saving the whole record sends the URL back unchanged.""" + service = self._service() + self.assertTrue(service.active) + refused = self._request( + "put", self._new_service(service_url=OTHER_URL), pk=service.pk + ) + self.assertEqual(refused.status_code, 401) + + response = self._request("put", self._new_service(active=False), pk=service.pk) + + self.assertEqual(response.status_code, 200) + service.refresh_from_db() + self.assertFalse(service.active) + self.assertEqual(service.service_url, SERVICE_URL) + + def _textit_service(self): + """A TextIt service sends to credentials kept in MetaData, not to + ``service_url``.""" + data = { + "name": "textit", + "service_url": "https://textit.io", + "xform": self.xform.pk, + "auth_token": "token-A", + "flow_uuid": "flow-A", + "contacts": "contacts-A", + } + response = self._request("post", data, self._grant_header()) + self.assertEqual(response.status_code, 201) + self.assertEqual(self._textit_auth_token(), "token-A") + return RestService.objects.get(name="textit", xform=self.xform) + + def _textit_auth_token(self): + """The auth token stored in the form's TextIt MetaData.""" + stored = MetaData.textit(self.xform) or "" + return stored.split(settings.METADATA_SEPARATOR)[0] + + def test_repointing_textit_credentials_without_a_grant_is_challenged(self): + service = self._textit_service() + + response = self._request( + "patch", {"name": "textit", "auth_token": "attacker-token"}, pk=service.pk + ) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], CHANGE_WEBHOOK) + self.assertEqual(self._textit_auth_token(), "token-A") + + def test_a_grant_lets_textit_credentials_change(self): + service = self._textit_service() + + response = self._request( + "patch", + {"name": "textit", "auth_token": "new-token"}, + self._grant_header(), + pk=service.pk, + ) + + self.assertEqual(response.status_code, 200) + self.assertEqual(self._textit_auth_token(), "new-token") + + +@gating(CHANGE_WEBHOOK) +class TestAddServicePageGate(StepUpGateTestCase): + """The server-rendered page adds a webhook too, so it must not be a way + around the API's gate.""" + + def setUp(self): + super().setUp() + self._publish_xls_form_to_project() + self.url = reverse( + add_service, + kwargs={"username": self.user.username, "id_string": self.xform.id_string}, + ) + + def _post(self, data=None): + return self.client.post( + self.url, + { + "service_name": "generic_json", + "service_url": SERVICE_URL, + **(data or {}), + }, + ) + + def test_adding_a_service_without_a_grant_is_refused(self): + self.assertFalse(RestService.objects.exists()) + + response = self._post() + + self.assertEqual(response.status_code, 403) + self.assertFalse(RestService.objects.exists()) + + def test_a_grant_lets_the_service_be_added(self): + grant = issue_grant(self.user.pk, CHANGE_WEBHOOK) + + response = self._post({"grant": grant}) + + self.assertEqual(response.status_code, 200) + self.assertEqual( + list(RestService.objects.values_list("service_url", flat=True)), + [SERVICE_URL], + ) + + def test_an_invalid_service_keeps_the_grant(self): + grant = issue_grant(self.user.pk, CHANGE_WEBHOOK) + + response = self._post({"service_url": "not a url", "grant": grant}) + + self.assertEqual(response.status_code, 200) + self.assertFalse(RestService.objects.exists()) + self.assertTrue(spend_grant(self.user.pk, CHANGE_WEBHOOK, grant)) diff --git a/onadata/apps/restservice/views.py b/onadata/apps/restservice/views.py index 5af8b213ab..9f38d101c5 100644 --- a/onadata/apps/restservice/views.py +++ b/onadata/apps/restservice/views.py @@ -14,9 +14,12 @@ from onadata.apps.restservice.forms import RestServiceForm from onadata.apps.restservice.models import RestService +from onadata.libs.stepup.pages import refuse_page_action +from onadata.libs.stepup.policy import GATE_CHANGE_WEBHOOK from onadata.libs.utils.viewer_tools import get_form +# pylint: disable=too-many-locals @login_required def add_service(request, username, id_string): """Add a service.""" @@ -30,6 +33,9 @@ def add_service(request, username, id_string): form = RestServiceForm(request.POST) restservice = None if form.is_valid(): + refusal = refuse_page_action(request, GATE_CHANGE_WEBHOOK) + if refusal is not None: + return refusal service_name = form.cleaned_data["service_name"] service_url = form.cleaned_data["service_url"] try: diff --git a/onadata/apps/restservice/viewsets/restservices_viewset.py b/onadata/apps/restservice/viewsets/restservices_viewset.py index fde4831e98..6b9ee485c0 100644 --- a/onadata/apps/restservice/viewsets/restservices_viewset.py +++ b/onadata/apps/restservice/viewsets/restservices_viewset.py @@ -18,11 +18,21 @@ from onadata.libs.mixins.last_modified_mixin import LastModifiedMixin from onadata.libs.serializers.restservices_serializer import RestServiceSerializer from onadata.libs.serializers.textit_serializer import TextItSerializer +from onadata.libs.stepup import RequiresStepUp +from onadata.libs.stepup.policy import GATE_CHANGE_WEBHOOK from onadata.libs.utils.common_tags import TEXTIT # pylint: disable=invalid-name BaseViewset = get_baseviewset_class() +#: Fields that set which form's data a service sends, in what format, and to +#: what URL. +DESTINATION_FIELDS = ("xform", "name", "service_url") + +#: A TextIt service sends to these instead. They live in MetaData, not on the +#: row, so any write to one is gated without comparing it to a stored value. +TEXTIT_DESTINATION_FIELDS = ("auth_token", "flow_uuid", "contacts") + def get_serializer_class(name): """Returns a serilizer class with the given ``name``.""" @@ -38,8 +48,20 @@ def get_serializer_class(name): return RestServiceSerializer +def _changes_destination(instance, validated_data) -> bool: + if any( + field in validated_data and validated_data[field] != getattr(instance, field) + for field in DESTINATION_FIELDS + ): + return True + if instance.name == TEXTIT: + return any(field in validated_data for field in TEXTIT_DESTINATION_FIELDS) + return False + + # pylint: disable=too-many-ancestors class RestServicesViewSet( + RequiresStepUp, AuthenticateHeaderMixin, CacheControlMixin, LastModifiedMixin, @@ -69,6 +91,27 @@ def get_serializer_class(self): return super().get_serializer_class() + def create(self, request, *args, **kwargs): + """Add a service, which needs a grant where webhooks are gated.""" + return self.gated_create( + request, lambda _data: self.check_step_up(request, GATE_CHANGE_WEBHOOK) + ) + + def update(self, request, *args, **kwargs): + """Change a service, which needs a grant if it changes where the + service sends.""" + return self.gated_update( + request, + lambda service, data: self._update_refusal(request, service, data), + partial=kwargs.pop("partial", False), + ) + + def _update_refusal(self, request, service, validated_data): + """Refuse sending ``service`` somewhere else without a grant.""" + if not _changes_destination(service, validated_data): + return None + return self.check_step_up(request, GATE_CHANGE_WEBHOOK) + def retrieve(self, request, *args, **kwargs): instance = self.get_object() diff --git a/onadata/libs/apps.py b/onadata/libs/apps.py new file mode 100644 index 0000000000..0098089be5 --- /dev/null +++ b/onadata/libs/apps.py @@ -0,0 +1,40 @@ +# -*- coding: utf-8 -*- +"""AppConfig for onadata.libs.""" + +from django.apps import AppConfig + + +class LibsConfig(AppConfig): + """Registers the checks that live under ``onadata.libs``.""" + + name = "onadata.libs" + verbose_name = "Ona libs" + + def ready(self): + """Register the step-up startup checks.""" + # pylint: disable=import-outside-toplevel + from django.core.checks import register + + from onadata.libs.stepup.checks import ( + check_federated_step_up_binds_by_email, + check_federated_step_up_gates_email, + check_oauth_approval_can_step_up, + check_removed_enrolment_password_setting, + check_step_up_actions_are_known, + check_step_up_has_two_factor_enabled, + check_step_up_is_well_formed, + check_step_up_mode_is_known, + check_step_up_no_factor_policy_is_known, + check_step_up_not_silently_bypassable, + ) + + register(check_step_up_is_well_formed) + register(check_step_up_actions_are_known) + register(check_step_up_no_factor_policy_is_known) + register(check_step_up_not_silently_bypassable) + register(check_step_up_mode_is_known) + register(check_step_up_has_two_factor_enabled) + register(check_removed_enrolment_password_setting) + register(check_federated_step_up_gates_email) + register(check_federated_step_up_binds_by_email) + register(check_oauth_approval_can_step_up) diff --git a/onadata/libs/authentication.py b/onadata/libs/authentication.py index 63ae064cd4..0d32c06be0 100644 --- a/onadata/libs/authentication.py +++ b/onadata/libs/authentication.py @@ -20,6 +20,7 @@ from django.db.models import Q from django.utils import timezone from django.utils.translation import gettext as _ +from django.views.decorators.debug import sensitive_variables import jwt from django_digest import HttpDigestAuthenticator @@ -603,6 +604,22 @@ def add_login_attempt(ip_address, username): return safe_cache_get(attempts_key) +@sensitive_variables("password") +def check_password_with_lockout(request, user, password) -> bool: + """Whether ``password`` is ``user``'s, a wrong one spending the login + form's allowance so a password check is no way around its lockout. + + Raises AuthenticationFailed while the account is locked out from the + request's IP, or once this guess locks it. + """ + ip_address = get_client_ip(request) + assert_not_locked_out(ip_address, user.username) + if user.check_password(password): + return True + add_login_attempt(ip_address, user.username) + return False + + def is_lockout_excluded_path(request) -> bool: """Return True when the request path is exempt from lockout. diff --git a/onadata/libs/serializers/organization_serializer.py b/onadata/libs/serializers/organization_serializer.py index aa50b09355..8f17af61d9 100644 --- a/onadata/libs/serializers/organization_serializer.py +++ b/onadata/libs/serializers/organization_serializer.py @@ -153,6 +153,13 @@ def create(self, validated_data): profile = tools.create_organization_object(org, creator, validated_data) profile.save() + # The first save applies the deployment default, + # REQUIRE_ODK_AUTHENTICATION. A value the caller sent overrides it. + # Form data reads a missing boolean as False and drops an empty one, + # so the value must be both sent and validated. + if "require_auth" in self.initial_data and "require_auth" in validated_data: + profile.require_auth = validated_data["require_auth"] + profile.save(update_fields=["require_auth"]) return profile diff --git a/onadata/libs/serializers/project_serializer.py b/onadata/libs/serializers/project_serializer.py index ec65e69ccd..f935446c03 100644 --- a/onadata/libs/serializers/project_serializer.py +++ b/onadata/libs/serializers/project_serializer.py @@ -6,6 +6,7 @@ from django.conf import settings from django.contrib.auth import get_user_model from django.core.management import call_command +from django.db import transaction from django.db.utils import IntegrityError from django.utils.translation import gettext as _ @@ -516,6 +517,7 @@ def validate(self, attrs): {"name": _(f"Project {name} already exists.")} ) else: + self._check_name_free_in_new_owner(name, organization) organization = organization or self.instance.organization request = self.context["request"] try: @@ -535,6 +537,19 @@ def validate(self, attrs): ) return attrs + def _check_name_free_in_new_owner(self, name, organization): + """A transfer into an account with a project of the same name would + fail on the unique constraint after the transfer had begun.""" + if not organization or organization == self.instance.organization: + return + name = name or self.instance.name + if Project.objects.filter( + name__iexact=name, organization=organization + ).exists(): + raise serializers.ValidationError( + {"name": _(f"Project {name} already exists.")} + ) + def validate_public(self, value): """ Validate the public field @@ -572,26 +587,31 @@ def update(self, instance, validated_data): instance.metadata.update(metadata) validated_data["metadata"] = instance.metadata - if self.partial and owner: - # give the new owner permissions - set_owners_permission(owner, instance) + with transaction.atomic(): + if self.partial and owner: + # give the new owner permissions + set_owners_permission(owner, instance) + + if is_organization(owner.profile): + call_command( + "transferproject", + current_owner=instance.organization, + new_owner=owner, + project_id=instance.pk, + ) - if is_organization(owner.profile): - call_command( - "transferproject", - current_owner=instance.organization, - new_owner=owner, - project_id=instance.pk, + # Again after commit: a read during the transfer can re-cache + # the old permissions. + safe_cache_delete(f"{PROJ_PERM_CACHE}{instance.pk}") + transaction.on_commit( + lambda: safe_cache_delete(f"{PROJ_PERM_CACHE}{instance.pk}") ) - # clear cache - safe_cache_delete(f"{PROJ_PERM_CACHE}{instance.pk}") - - project = super().update(instance, validated_data) + project = super().update(instance, validated_data) - project.xform_set.exclude(shared=project.shared).update( - shared=project.shared, shared_data=project.shared - ) + project.xform_set.exclude(shared=project.shared).update( + shared=project.shared, shared_data=project.shared + ) return instance diff --git a/onadata/libs/serializers/user_profile_serializer.py b/onadata/libs/serializers/user_profile_serializer.py index f8b45d9e8e..9c87651197 100644 --- a/onadata/libs/serializers/user_profile_serializer.py +++ b/onadata/libs/serializers/user_profile_serializer.py @@ -15,12 +15,14 @@ from django.db.models.query import QuerySet from django.utils import timezone from django.utils.translation import gettext as _ +from django.views.decorators.debug import sensitive_variables import six from django_digest.backend.db import update_partial_digests from registration.models import RegistrationProfile from rest_framework import serializers from rest_framework.authtoken.models import Token +from rest_framework.exceptions import AuthenticationFailed, PermissionDenied from onadata.apps.api.models.temp_token import TempToken from onadata.apps.api.tasks import send_verification_email @@ -29,7 +31,7 @@ from onadata.apps.main.models import UserProfile from onadata.apps.messaging.constants import PROFILE_UPDATED, USER from onadata.apps.messaging.serializers import send_message -from onadata.libs.authentication import expired +from onadata.libs.authentication import check_password_with_lockout, expired from onadata.libs.permissions import CAN_VIEW_PROFILE, is_organization from onadata.libs.serializers.fields.json_field import JsonField from onadata.libs.utils.analytics import TrackObjectEvent @@ -152,6 +154,27 @@ def _get_registration_params(attrs): return params +@sensitive_variables() +def _check_current_password(request, user, params): + """Refuse an email change without the current password, and any password + sent with an update that is not the current one.""" + password = params.get("password1") + if params.get("email") and not password: + raise serializers.ValidationError( + _("Your password is required when updating your email address.") + ) + if not password: + return + try: + if check_password_with_lockout(request, user, password): + return + except AuthenticationFailed as lockout: + raise PermissionDenied( + {"error": str(lockout.detail), "reason": "locked_out"} + ) from lockout + raise serializers.ValidationError(_("Invalid password")) + + def _send_verification_email(redirect_url, user, request): verification_key = user.registrationprofile.create_new_activation_key() verification_url = get_verification_url(redirect_url, request, verification_key) @@ -281,14 +304,6 @@ def update(self, instance, validated_data): password = params.get("password1") email = params.get("email") - # Check password if email is being updated - if email and not password: - raise serializers.ValidationError( - _("Your password is required when updating your email address.") - ) - if password and not instance.user.check_password(password): - raise serializers.ValidationError(_("Invalid password")) - # get user instance.user.email = email or instance.user.email @@ -450,6 +465,8 @@ def validate(self, attrs): raise serializers.ValidationError( {"name": _("Either name or first_name should be provided")} ) + if self.instance is not None: + _check_current_password(self.context["request"], self.instance.user, params) return params diff --git a/onadata/libs/stepup/__init__.py b/onadata/libs/stepup/__init__.py new file mode 100644 index 0000000000..d39b7878a2 --- /dev/null +++ b/onadata/libs/stepup/__init__.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +"""Step-up authentication: prove a second factor for one action.""" + +from onadata.libs.stepup.challenge import build_challenge # noqa: F401 +from onadata.libs.stepup.drf import RequiresStepUp # noqa: F401 +from onadata.libs.stepup.policy import ( # noqa: F401 + GATE_REQUIRE_AUTH, + is_gated, + mode, + no_factor_policy, +) diff --git a/onadata/libs/stepup/capabilities.py b/onadata/libs/stepup/capabilities.py new file mode 100644 index 0000000000..84e3587299 --- /dev/null +++ b/onadata/libs/stepup/capabilities.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +"""What this deployment lets an account manage about its own credentials. + +The server reports this so a client cannot disagree with it. A deployment +where an identity provider owns identity has no password to change and no +factor to enrol. +""" + +from django.conf import settings + +from onadata.libs.stepup.policy import is_local_mode + + +def identity_is_federated() -> bool: + """Whether an identity provider, rather than OnaData, owns credentials. + + Follows the step-up mode. If the provider owns the second factor, it also + owns the password. + """ + return not is_local_mode() + + +def account_capabilities() -> dict: + """The credential controls this deployment can honour. + + The server also enforces the ``twoFactor`` values. The ``/totp`` routes + answer 409 when OnaData does not own the factor. ``password.change`` is + advice only, and the password routes stay open. + """ + federated = identity_is_federated() + # Without ENABLE_TWO_FACTOR, /api/v1/totp/* answers 404, so offer nothing. + manages_second_factor = not federated and getattr( + settings, "ENABLE_TWO_FACTOR", False + ) + return { + "password": {"change": not federated}, + "twoFactor": { + "managedBy": "idp" if federated else "onadata", + "enroll": manages_second_factor, + "disable": manages_second_factor, + "recoveryCodes": manages_second_factor, + "verify": manages_second_factor, + }, + # Tells a client where the user manages credentials. Empty when + # OnaData owns identity. + "identityProvider": _identity_provider_name() if federated else "", + } + + +def _identity_provider_name() -> str: + """The provider's display name, from ``STEP_UP_IDP_NAME``. + + Do not derive it from the auth-server key. Keys are internal slugs that + users do not recognise. + """ + return getattr(settings, "STEP_UP_IDP_NAME", "") or "" diff --git a/onadata/libs/stepup/challenge.py b/onadata/libs/stepup/challenge.py new file mode 100644 index 0000000000..efeb83c3ea --- /dev/null +++ b/onadata/libs/stepup/challenge.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +"""The 401 body telling a client how to satisfy a gate.""" + +import logging + +from django.core.exceptions import ImproperlyConfigured + +from oidc.stepup import find_step_up_auth_server + +from onadata.libs.stepup.federated import start_step_up +from onadata.libs.stepup.gate import STEP_UP_REQUIRED +from onadata.libs.stepup.policy import is_local_mode + +logger = logging.getLogger(__name__) + +#: How a client should obtain a grant. +DIALECT_LOCAL_TOTP = "local-totp" +DIALECT_OIDC = "oidc" + +#: The deployment cannot send the user anywhere to step up. This is a server +#: fault, so it is answered with a 503. +STEP_UP_UNAVAILABLE = "step_up_unavailable" + + +def build_challenge(action: str, user=None) -> dict: + """The body a client needs to satisfy the gate on ``action``. + + The client echoes ``audience`` back. The grant it earns is valid for that + action only. + """ + body = {"error": STEP_UP_REQUIRED, "audience": action} + + if is_local_mode(): + body["dialect"] = DIALECT_LOCAL_TOTP + return body + + body["dialect"] = DIALECT_OIDC + auth_server = find_step_up_auth_server() + if not auth_server: + logger.warning("step-up: federated mode but no auth server is configured") + body["error"] = STEP_UP_UNAVAILABLE + return body + if user is None or not user.is_authenticated: + # Without a user, the callback cannot tell whose step-up it completes. + logger.warning("step-up: cannot start a federated flow for no user") + body["error"] = STEP_UP_UNAVAILABLE + return body + + try: + url, _ = start_step_up(auth_server, action, user) + except (ValueError, KeyError, TypeError, ImproperlyConfigured): + # The auth server is missing or malformed. Answer instead of raising. + logger.exception("step-up: cannot build an authorization request") + body["error"] = STEP_UP_UNAVAILABLE + return body + + body["authorizationUrl"] = url + return body diff --git a/onadata/libs/stepup/checks.py b/onadata/libs/stepup/checks.py new file mode 100644 index 0000000000..764cd797de --- /dev/null +++ b/onadata/libs/stepup/checks.py @@ -0,0 +1,259 @@ +# -*- coding: utf-8 -*- +"""Startup checks for step-up configuration.""" + +from collections.abc import Collection + +from django.conf import settings +from django.core.checks import Error as CheckError +from django.core.checks import Warning as CheckWarning + +from oidc.stepup import ( + find_step_up_auth_server, + step_up_config, + subject_binding, + subject_binding_is_safe, +) + +from onadata.libs.stepup.policy import ( + GATE_AUTHORIZE_OAUTH_APP, + GATE_CHANGE_EMAIL, + KNOWN_ACTIONS, + KNOWN_MODES, + KNOWN_NO_FACTOR_POLICIES, + POLICY_DENY_PROMPT_ENROL, + POLICY_SKIP_GATE, + gated_actions, + is_local_mode, + mode, + no_factor_policy, + step_up_setting, +) + + +def _malformation(config): + """What makes ``config``, a ``STEP_UP`` setting, unreadable, or None.""" + if not isinstance(config, dict): + return f"STEP_UP is a {type(config).__name__}, not a dict." + actions = config.get("ACTIONS", ()) + if isinstance(actions, str): + return None + if not isinstance(actions, Collection) or isinstance(actions, dict): + return f"STEP_UP['ACTIONS'] is a {type(actions).__name__}, not a list." + if not all(isinstance(action, str) for action in actions): + return f"STEP_UP['ACTIONS'] holds entries that are not strings: {actions!r}." + return None + + +def check_step_up_is_well_formed(app_configs=None, **kwargs): + # pylint: disable=unused-argument + """A ``STEP_UP`` that cannot be read gates nothing. + + The policy reads such a setting as empty rather than crash every request, + which leaves every action the deployment meant to gate ungated. + """ + problem = _malformation(step_up_setting()) + if problem is None: + return [] + return [ + CheckError( + f"{problem} Step-up reads it as gating nothing.", + hint="Set STEP_UP to a dict whose 'ACTIONS' lists action names.", + id="stepup.E001", + ) + ] + + +def check_step_up_actions_are_known(app_configs=None, **kwargs): + # pylint: disable=unused-argument + """An action name no gate checks protects nothing. + + A typo such as ``"change-emial"`` leaves the intended action ungated + while the deployment believes it is protected. + """ + unknown = sorted(gated_actions() - KNOWN_ACTIONS) + if not unknown: + return [] + return [ + CheckError( + f"STEP_UP['ACTIONS'] names actions nothing gates: {', '.join(unknown)}.", + hint=f"Use names from: {', '.join(sorted(KNOWN_ACTIONS))}.", + id="stepup.E002", + ) + ] + + +def check_step_up_no_factor_policy_is_known(app_configs=None, **kwargs): + # pylint: disable=unused-argument + """An unrecognised NO_FACTOR_POLICY refuses users with no factor. + + It fails closed, like ``deny_prompt_enrol``, but for a reason no one + chose. + """ + configured = no_factor_policy() + if isinstance(configured, str) and configured in KNOWN_NO_FACTOR_POLICIES: + return [] + return [ + CheckWarning( + f"STEP_UP['NO_FACTOR_POLICY'] is {configured!r}, not one of " + f"{sorted(KNOWN_NO_FACTOR_POLICIES)}; it is treated as " + f"{POLICY_DENY_PROMPT_ENROL!r}.", + hint="Set STEP_UP['NO_FACTOR_POLICY'] to 'skip_gate' or " + "'deny_prompt_enrol'.", + id="stepup.W008", + ) + ] + + +def check_step_up_not_silently_bypassable(app_configs=None, **kwargs): + # pylint: disable=unused-argument + """``skip_gate`` is a valid rollout choice, but a silent one. + + It lets every user with no factor through a gated action. Local mode only, + because federated mode always challenges. + """ + actions = sorted(gated_actions()) + if actions and is_local_mode() and no_factor_policy() == POLICY_SKIP_GATE: + return [ + CheckWarning( + "Step-up is configured but users without a second factor are " + f"not challenged for: {', '.join(actions)}.", + hint="Set STEP_UP['NO_FACTOR_POLICY'] = 'deny_prompt_enrol' " + "once these users are expected to have enrolled.", + id="stepup.W001", + ) + ] + return [] + + +def check_step_up_has_two_factor_enabled(app_configs=None, **kwargs): + # pylint: disable=unused-argument + """Local step-up needs ``ENABLE_TWO_FACTOR``. + + Without it ``/api/v1/totp/*`` answers 404, so nobody can enrol or verify. + A user who holds a device is challenged with no way to earn a grant, and + ``deny_prompt_enrol`` refuses everyone else. + """ + if ( + not is_local_mode() + or not gated_actions() + or getattr(settings, "ENABLE_TWO_FACTOR", False) + ): + return [] + return [ + CheckWarning( + "Step-up gates actions in local mode, but ENABLE_TWO_FACTOR is off: " + "no user can enrol or verify, so no gated action can be stepped up " + "for.", + hint="Set ENABLE_TWO_FACTOR = True, or empty STEP_UP['ACTIONS'].", + id="stepup.W004", + ) + ] + + +def check_step_up_mode_is_known(app_configs=None, **kwargs): + # pylint: disable=unused-argument + """An unrecognised MODE counts as federated. + + A typo such as ``"fedarated"`` moves verification to the identity provider + without a warning. It fails closed, but for a reason no one chose. + """ + configured = mode() + if isinstance(configured, str) and configured in KNOWN_MODES: + return [] + return [ + CheckWarning( + f"STEP_UP['MODE'] is {configured!r}, not one of " + f"{sorted(KNOWN_MODES)}; it is treated as federated.", + hint="Set STEP_UP['MODE'] to 'local' or 'federated'.", + id="stepup.W003", + ) + ] + + +def check_federated_step_up_gates_email(app_configs=None, **kwargs): + # pylint: disable=unused-argument + """Federated step-up matches the provider's token to the account email. + + If changing the email is not gated, a stolen session can point it at the + attacker's provider account and pass every gate. + """ + actions = gated_actions() + if not actions or is_local_mode() or GATE_CHANGE_EMAIL in actions: + return [] + return [ + CheckWarning( + "Federated step-up is configured, but changing the email is not " + "gated, and step-up identifies the user by email.", + hint=f"Add {GATE_CHANGE_EMAIL!r} to STEP_UP['ACTIONS'].", + id="stepup.W006", + ) + ] + + +def check_removed_enrolment_password_setting(app_configs=None, **kwargs): + # pylint: disable=unused-argument + """``TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD`` is ignored. + + A first enrolment always needs the account password. Users the setting + meant to exempt are refused at enrolment with no other signal. + """ + if not hasattr(settings, "TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD"): + return [] + return [ + CheckWarning( + "TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD has been removed and is " + "ignored: enrolling a first device always needs the account " + "password.", + hint="Remove the setting. Users without a usable password must set " + "one before enrolling.", + id="stepup.W005", + ) + ] + + +def check_federated_step_up_binds_by_email(app_configs=None, **kwargs): + # pylint: disable=unused-argument + """Step-up can identify the user by another field, but only the email + is gated against change. + + A stolen session can rename the account to match the attacker's own + provider account, then pass every gate with the attacker's own factor. + """ + server = find_step_up_auth_server() + if not gated_actions() or is_local_mode() or server is None: + return [] + config = step_up_config(server) + if subject_binding_is_safe(config): + return [] + _claim, field = subject_binding(config) + return [ + CheckWarning( + f"Federated step-up identifies the user by {field!r}, which a " + "user can change without step-up.", + hint="Remove SUBJECT_CLAIM and SUBJECT_FIELD from the STEP_UP " + "block so step-up identifies the user by email.", + id="stepup.W007", + ) + ] + + +def check_oauth_approval_can_step_up(app_configs=None, **kwargs): + # pylint: disable=unused-argument + """The OAuth consent and application pages cannot run a challenge. + + Their grant field starts empty, and the browser a client redirects there + cannot add the grant header, so a gated approval is always refused. + """ + if GATE_AUTHORIZE_OAUTH_APP not in gated_actions(): + return [] + return [ + CheckWarning( + f"{GATE_AUTHORIZE_OAUTH_APP!r} is gated, but /o/authorize/ and " + "/o/applications/ cannot run a step-up challenge: every user the " + "gate challenges is refused with 403 when approving or " + "registering an OAuth application.", + hint=f"Remove {GATE_AUTHORIZE_OAUTH_APP!r} from STEP_UP['ACTIONS'] " + "unless those refusals are intended.", + id="stepup.W009", + ) + ] diff --git a/onadata/libs/stepup/drf.py b/onadata/libs/stepup/drf.py new file mode 100644 index 0000000000..a6898aa4c0 --- /dev/null +++ b/onadata/libs/stepup/drf.py @@ -0,0 +1,92 @@ +# -*- coding: utf-8 -*- +"""Viewset mixin turning a policy decision into a step-up challenge.""" + +from rest_framework import status +from rest_framework.response import Response + +from onadata.libs.stepup.challenge import STEP_UP_UNAVAILABLE, build_challenge +from onadata.libs.stepup.gate import ( + ENROL_REQUIRED, + ONE_GATED_CHANGE_PER_REQUEST, + change_refusal, + refusal_reason, +) + + +class RequiresStepUp: + """Refuse a gated action unless the request carries a single-use grant. + + The server decides which actions are gated. A caller could skip a gate that + a client enforced by calling the API directly. + """ + + def check_step_up(self, request, action: str): + """``None`` to proceed, or a Response to return instead.""" + return self.step_up_refusal(request, refusal_reason(request, action), (action,)) + + def gated_change_refusal(self, request, changes): + """Refuse the gated change among ``changes``, ``(action, changed)`` + pairs, or None to proceed.""" + return self.step_up_refusal(request, *change_refusal(request, changes)) + + def step_up_refusal(self, request, reason, audiences): + """The Response refusing ``audiences`` for ``reason``, or None when + there is no reason.""" + if reason is None: + return None + if reason == ONE_GATED_CHANGE_PER_REQUEST: + return Response( + {"error": reason, "audiences": list(audiences)}, + status=status.HTTP_400_BAD_REQUEST, + ) + if reason == ENROL_REQUIRED: + return Response( + {"error": ENROL_REQUIRED}, + status=status.HTTP_403_FORBIDDEN, + ) + challenge = build_challenge(audiences[0], request.user) + if challenge["error"] == STEP_UP_UNAVAILABLE: + return Response( + {"error": STEP_UP_UNAVAILABLE}, + status=status.HTTP_503_SERVICE_UNAVAILABLE, + ) + return Response(challenge, status=status.HTTP_401_UNAUTHORIZED) + + def gated_create(self, request, refusal_for): + """DRF's create with a gate between validating and writing. + + ``refusal_for(validated_data)`` returns None to proceed or a Response + to answer instead, as for ``gated_update``. + """ + # pylint: disable=no-member + serializer = self.get_serializer(data=request.data) + serializer.is_valid(raise_exception=True) + refusal = refusal_for(serializer.validated_data) + if refusal is not None: + return refusal + self.perform_create(serializer) + headers = self.get_success_headers(serializer.data) + return Response( + serializer.data, status=status.HTTP_201_CREATED, headers=headers + ) + + def gated_update(self, request, refusal_for, partial=False): + """DRF's update with a gate between validating and writing. + + ``refusal_for(instance, validated_data)`` returns None to proceed or a + Response to answer instead. Validating first means a request the write + would reject is answered 400 before any grant is spent. + """ + # pylint: disable=no-member + instance = self.get_object() + serializer = self.get_serializer(instance, data=request.data, partial=partial) + serializer.is_valid(raise_exception=True) + refusal = refusal_for(instance, serializer.validated_data) + if refusal is not None: + return refusal + self.perform_update(serializer) + if getattr(instance, "_prefetched_objects_cache", None): + # The update can change relations the queryset prefetched. + # pylint: disable=protected-access + instance._prefetched_objects_cache = {} + return Response(serializer.data) diff --git a/onadata/libs/stepup/federated.py b/onadata/libs/stepup/federated.py new file mode 100644 index 0000000000..b240284711 --- /dev/null +++ b/onadata/libs/stepup/federated.py @@ -0,0 +1,19 @@ +# -*- coding: utf-8 -*- +"""Start a step-up against an external identity provider. + +ona-oidc owns the protocol in ``oidc.stepup``. This module sets what OnaData +carries across the redirect. +""" + +from oidc.stepup import build_step_up_url + + +def start_step_up(auth_server: str, audience: str, user) -> tuple[str, str]: + """Build the authorize URL that will prove a second factor. + + Returns ``(url, state)``. The state carries the audience and the user, + because the callback has no other way to learn them. + """ + return build_step_up_url( + auth_server, context={"audience": audience, "user_pk": user.pk} + ) diff --git a/onadata/libs/stepup/gate.py b/onadata/libs/stepup/gate.py new file mode 100644 index 0000000000..55ada91e86 --- /dev/null +++ b/onadata/libs/stepup/gate.py @@ -0,0 +1,189 @@ +# -*- coding: utf-8 -*- +"""Whether a request may perform a gated action.""" + +import logging +import re + +from django.utils.translation import gettext as _ + +from oidc.stepup_grants import spend_grant + +from onadata.libs.stepup.policy import ( + POLICY_SKIP_GATE, + is_gated, + is_local_mode, + no_factor_policy, +) +from onadata.libs.utils.log import Actions, audit_log + +#: Why a gate refused. Either no grant was presented, or the user has no +#: factor and the deployment refuses rather than skips. +STEP_UP_REQUIRED = "step_up_required" +ENROL_REQUIRED = "enrol_required" + +#: Why a request making more than one gated change is refused. One grant +#: cannot satisfy two gates, so the request is refused before any is spent. +ONE_GATED_CHANGE_PER_REQUEST = "one_gated_change_per_request" + +#: Header a caller may use when the request has no body to put a grant in. +#: Do not accept a query parameter instead. A grant is a bearer credential, and +#: query strings are written to access logs, browser history and Referer. +GRANT_HEADER = "X-Step-Up-Grant" + +#: Anything else is not a grant, and would be an invalid memcached key. +_GRANT_SHAPE = re.compile(r"[A-Za-z0-9_-]{1,64}") + + +class StepUpRefused(Exception): + """A gated change was refused where no response can be returned. + + Carries the decision, ``reason`` and the ``audiences`` involved, for the + caller that catches it to answer with. + """ + + def __init__(self, reason: str, audiences): + super().__init__(reason) + self.reason = reason + self.audiences = tuple(audiences) + + +def has_second_factor(user) -> bool: + """Whether the login view would challenge this user for a second factor. + + Uses ``default_device`` rather than an EncryptedTOTPDevice lookup, because + two_factor challenges on any confirmed device named ``"default"``. + ``TOTPViewSet`` verifies only TOTP and recovery codes. Teach it any new + device type in the same change. + """ + # pylint: disable=import-outside-toplevel + from two_factor.utils import default_device + + return default_device(user) is not None + + +def _presented_grant(request) -> str: + """The grant this request carries, from its body or the header. + + Reads ``data`` on a DRF request and ``POST`` on a plain Django one. + """ + body = getattr(request, "data", None) or getattr(request, "POST", None) or {} + if hasattr(body, "get"): + from_body = str(body.get("grant", "") or "").strip() + if from_body: + return from_body + return str(request.headers.get(GRANT_HEADER, "") or "").strip() + + +def _audit(request, action, message, audience, level): + """Record a gate decision on ``audience``. Never pass it the grant.""" + # The grant may already be spent; a failed audit write must not fail the + # request and make the user step up again. + try: + audit_log( + action, + request.user, + request.user, + message, + {"audience": audience}, + request, + level=level, + ) + except Exception: # pylint: disable=broad-exception-caught + logging.getLogger(__name__).exception("step-up audit write failed") + + +def changed_gated_actions(changes) -> list: + """The gated actions among ``changes``, an iterable of + ``(action, changed)`` pairs, in order. + + ``changed`` may be a function, called only when ``action`` is gated, so a + check that costs queries runs only where a deployment gates the action.""" + return [ + action + for action, changed in changes + if is_gated(action) and (changed() if callable(changed) else changed) + ] + + +def refusal_reason(request, action: str): + """``None`` to proceed, or why ``action`` is refused. Spends the grant the + request presents.""" + if not is_gated(action): + return None + if not request.user.is_authenticated: + return STEP_UP_REQUIRED + # A gating view can delegate to another that gates the same action. The + # grant is single-use, so spend it once per request and pass repeats on + # that result. + spent = getattr(request, "_stepped_up_actions", None) + if spent is None: + spent = set() + request._stepped_up_actions = spent # pylint: disable=protected-access + if action in spent: + return None + # Only local mode can tell whether a user has a second factor. In + # federated mode the IdP holds it, the local lookup is False for every + # user, and skip_gate would open the gate everywhere. Challenge instead, + # and let the IdP decide what a user with no factor may do. + if is_local_mode() and not has_second_factor(request.user): + # Only an exact skip_gate opens the gate, so a misspelt policy refuses. + if no_factor_policy() != POLICY_SKIP_GATE: + _audit( + request, + Actions.STEP_UP_ENROL_REQUIRED, + _("Step-up refused: no second factor enrolled."), + action, + logging.WARNING, + ) + return ENROL_REQUIRED + return None + return _spend_presented_grant(request, action, spent) + + +def _spend_presented_grant(request, action: str, spent: set): + """``None`` once the request's grant for ``action`` is spent, else + ``STEP_UP_REQUIRED``.""" + presented = _presented_grant(request) + grant = presented if _GRANT_SHAPE.fullmatch(presented) else "" + if spend_grant(request.user.pk, action, grant): + spent.add(action) + _audit( + request, + Actions.STEP_UP_GRANT_SPENT, + _("Step-up grant spent."), + action, + logging.INFO, + ) + return None + if presented: + _audit( + request, + Actions.STEP_UP_GRANT_REJECTED, + _("Step-up grant rejected."), + action, + logging.WARNING, + ) + return STEP_UP_REQUIRED + + +def change_refusal(request, changes) -> tuple: + """``(reason, audiences)`` for the gated change among ``changes``, + ``(action, changed)`` pairs. ``reason`` is ``None`` to proceed. + + Spends the grant the request presents. A request with more than one gated + change is refused first, with ``ONE_GATED_CHANGE_PER_REQUEST``. + """ + gated = changed_gated_actions(changes) + if len(gated) > 1: + return ONE_GATED_CHANGE_PER_REQUEST, gated + if not gated: + return None, gated + return refusal_reason(request, gated[0]), gated + + +def require_gated_change(request, changes): + """Raise ``StepUpRefused`` unless the gated change among ``changes``, + ``(action, changed)`` pairs, may proceed.""" + reason, audiences = change_refusal(request, changes) + if reason is not None: + raise StepUpRefused(reason, audiences) diff --git a/onadata/libs/stepup/pages.py b/onadata/libs/stepup/pages.py new file mode 100644 index 0000000000..52a7f330f3 --- /dev/null +++ b/onadata/libs/stepup/pages.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +"""Step-up for server-rendered pages that write gated values. + +These pages cannot run the API's challenge, so a gated change made through +them is refused unless the request already carries a grant. +""" + +from copy import deepcopy + +from django.http import HttpResponseForbidden +from django.utils.translation import gettext as _ + +from onadata.libs.stepup.gate import ( + ENROL_REQUIRED, + ONE_GATED_CHANGE_PER_REQUEST, + change_refusal, + refusal_reason, +) +from onadata.libs.stepup.policy import ( + GATE_CHANGE_EMAIL, + GATE_PRIVACY_CONSENT, + GATE_REQUIRE_AUTH, + eu_consent_record, +) + + +def _forbidden(reason): + """``None`` when there is no ``reason``, or a 403 explaining it.""" + if reason is None: + return None + if reason == ONE_GATED_CHANGE_PER_REQUEST: + return HttpResponseForbidden(_("Change one protected setting at a time.")) + if reason == ENROL_REQUIRED: + return HttpResponseForbidden( + _("Set up two-factor authentication before making this change.") + ) + return HttpResponseForbidden( + _( + "This change requires verifying your second factor, " + "which this page does not support." + ) + ) + + +def refuse_page_action(request, action: str): + """``None`` to proceed, or a 403 refusing ``action``.""" + return _forbidden(refusal_reason(request, action)) + + +def gated_profile_values(require_auth, email, metadata) -> dict: + """The profile values a step-up gates, keyed by the audience gating each. + + Deep-copied, so a snapshot taken before a form writes the instance keeps + the stored values. + """ + return { + GATE_REQUIRE_AUTH: bool(require_auth), + GATE_CHANGE_EMAIL: (email or "").strip().lower(), + GATE_PRIVACY_CONSENT: deepcopy(eu_consent_record(metadata or {})), + } + + +def refuse_gated_changes(request, before: dict, after: dict): + """``None``, or a 403 for a gated value changed without a grant.""" + reason, _audiences = change_refusal( + request, ((action, after[action] != value) for action, value in before.items()) + ) + return _forbidden(reason) diff --git a/onadata/libs/stepup/policy.py b/onadata/libs/stepup/policy.py new file mode 100644 index 0000000000..3cd034dc48 --- /dev/null +++ b/onadata/libs/stepup/policy.py @@ -0,0 +1,194 @@ +# -*- coding: utf-8 -*- +"""Which actions require a second factor, and how this deployment proves one.""" + +from django.conf import settings + +#: Audience for the "Require Phone Authentication" toggle. +GATE_REQUIRE_AUTH = "require-auth-toggle" + +#: Audience for the GDPR EU-citizen consent record. It has its own audience so +#: a grant for the toggle cannot change it. +GATE_PRIVACY_CONSENT = "privacy-consent" + +#: Audience for regenerating the API token, which invalidates every +#: integration holding the old one. +GATE_REGENERATE_API_KEY = "regenerate-api-key" + +#: Audience for regenerating the ODK token, which invalidates the ODK Collect +#: credential the old one carried. +GATE_REGENERATE_ODK_TOKEN = "regenerate-odk-token" + +#: Audience for changing the account's email, where password resets land. +GATE_CHANGE_EMAIL = "change-email" + +#: Audience for changing the password. +GATE_CHANGE_PASSWORD = "change-password" # noqa # nosec B105 + +#: Audience for making someone an organisation owner or manager, who can then +#: change the organisation's gated settings with their own factor. +GATE_GRANT_ORG_ADMIN = "grant-org-admin" + +#: Audience for rotating an organisation's encryption key, which makes every +#: device fetch the re-keyed forms. +GATE_ROTATE_ORG_KEY = "rotate-org-key" + +#: Audience for renaming the account. Login and step-up can identify users by +#: username, so a stolen session must not be able to repoint it. +GATE_CHANGE_USERNAME = "change-username" + +#: Audience for adding a webhook or changing where one sends, which would +#: forward every new submission to whoever holds the session. +GATE_CHANGE_WEBHOOK = "change-webhook" + +#: Audiences for giving someone the owner or manager role, one per route so a +#: deployment can gate each on its own. +GATE_SHARE_FORM_ADMIN = "share-form-admin" +GATE_SHARE_PROJECT_ADMIN = "share-project-admin" +GATE_INVITE_PROJECT_ADMIN = "invite-project-admin" +GATE_SHARE_TEAM_ADMIN = "share-team-admin" + +#: Audience for making a form's or project's data public. +GATE_PUBLISH_DATA = "publish-data" + +#: Audience for moving a project to another account, which hands its data to +#: whoever controls that account. +GATE_TRANSFER_PROJECT = "transfer-project" + +#: Audience for approving or registering an OAuth application, which issues a +#: long-lived credential the API token gates do not cover. +GATE_AUTHORIZE_OAUTH_APP = "authorize-oauth-app" + +#: Audience for turning off a form's own require_auth. +GATE_FORM_REQUIRE_AUTH = "form-require-auth" + +#: Audience for turning off a form's encryption. +GATE_DISABLE_FORM_ENCRYPTION = "disable-form-encryption" + +#: Every action a deployment can gate, each also an audience +#: ``/api/v1/totp/verify`` mints grants for. +KNOWN_ACTIONS = frozenset( + { + GATE_REQUIRE_AUTH, + GATE_PRIVACY_CONSENT, + GATE_REGENERATE_API_KEY, + GATE_REGENERATE_ODK_TOKEN, + GATE_CHANGE_EMAIL, + GATE_CHANGE_PASSWORD, + GATE_GRANT_ORG_ADMIN, + GATE_ROTATE_ORG_KEY, + GATE_CHANGE_USERNAME, + GATE_CHANGE_WEBHOOK, + GATE_SHARE_FORM_ADMIN, + GATE_SHARE_PROJECT_ADMIN, + GATE_INVITE_PROJECT_ADMIN, + GATE_SHARE_TEAM_ADMIN, + GATE_PUBLISH_DATA, + GATE_TRANSFER_PROJECT, + GATE_AUTHORIZE_OAUTH_APP, + GATE_FORM_REQUIRE_AUTH, + GATE_DISABLE_FORM_ENCRYPTION, + } +) + +#: Roles that can share, delete and re-share what they hold. +ADMIN_ROLE_NAMES = frozenset({"owner", "manager"}) + +MODE_LOCAL = "local" +MODE_FEDERATED = "federated" +KNOWN_MODES = frozenset({MODE_LOCAL, MODE_FEDERATED}) + +POLICY_SKIP_GATE = "skip_gate" +POLICY_DENY_PROMPT_ENROL = "deny_prompt_enrol" +KNOWN_NO_FACTOR_POLICIES = frozenset({POLICY_SKIP_GATE, POLICY_DENY_PROMPT_ENROL}) + + +def _as_tuple(value) -> tuple: + """A setting read as a sequence. A bare string is one entry, and anything + that is not a sequence is empty. + + Tolerant so a malformed setting cannot crash the startup checks that + report it (``stepup.E001``). + """ + if isinstance(value, str): + return (value,) + try: + return tuple(value) + except TypeError: + return () + + +def eu_consent_path() -> tuple: + """Where the consent record sits in ``UserProfile.metadata``. + + A setting, because the client that writes the record decides its layout. + """ + return _as_tuple( + getattr(settings, "EU_CONSENT_METADATA_PATH", ("eu_citizen_consent",)) + ) + + +def eu_consent_record(metadata): + """The consent record in ``metadata``, or ``None`` if the path does not + resolve.""" + record = metadata + for key in eu_consent_path(): + if not isinstance(record, dict): + return None + record = record.get(key) + return record + + +def step_up_setting(): + """``settings.STEP_UP`` as configured, which may not be a dict.""" + return getattr(settings, "STEP_UP", {}) or {} + + +def _config() -> dict: + config = step_up_setting() + return config if isinstance(config, dict) else {} + + +def is_gated(action: str) -> bool: + """Whether ``action`` needs step-up here. + + A deployment that has not opted in gates nothing. + """ + return action in gated_actions() + + +def gated_actions() -> frozenset: + """Every action this deployment has opted into gating.""" + return frozenset( + action + for action in _as_tuple(_config().get("ACTIONS", ())) + if isinstance(action, str) + ) + + +def mode() -> str: + """``"local"`` (OnaData owns the factor) or ``"federated"`` (an IdP does). + + Read from configuration, never inferred from how a session arrived. + Inferring it would verify locally for a session that never visited the + IdP, which is a bypass. + """ + return _config().get("MODE", MODE_LOCAL) + + +def is_local_mode() -> bool: + """Whether OnaData, not an identity provider, owns the second factor. + + Anything other than ``"local"`` counts as federated. That fails closed, + because grants are then demanded rather than skipped. + """ + return mode() == MODE_LOCAL + + +def no_factor_policy() -> str: + """What to do when a gated action is reached by a user with no factor. + + ``skip_gate`` lets them through. ``deny_prompt_enrol``, or any other + value, refuses. The default is ``skip_gate`` for rollout safety, and the + ``stepup.W001`` check warns about it. + """ + return _config().get("NO_FACTOR_POLICY", POLICY_SKIP_GATE) diff --git a/onadata/libs/stepup/sharing.py b/onadata/libs/stepup/sharing.py new file mode 100644 index 0000000000..7c55ada4ec --- /dev/null +++ b/onadata/libs/stepup/sharing.py @@ -0,0 +1,192 @@ +# -*- coding: utf-8 -*- +"""Which owner and manager roles a share, a team or organisation join, a +form move or a meta permissions write hands out, and to whom.""" + +from django.contrib.contenttypes.models import ContentType + +from guardian.shortcuts import get_objects_for_group, get_perms + +from onadata.apps.logger.models import Project, XForm +from onadata.apps.main.models import MetaData +from onadata.libs.permissions import ( + ROLES, + ManagerRole, + OwnerRole, + get_role, + get_team_project_default_permissions, +) +from onadata.libs.stepup.policy import ADMIN_ROLE_NAMES +from onadata.libs.utils.common_tags import XFORM_META_PERMS +from onadata.libs.utils.project_utils import get_project_users +from onadata.libs.utils.xform_utils import ( + get_xform_users, + meta_perms_roles, + role_under_meta_perms, + roles_under_meta_perms, +) + + +def _stored_meta_perms(xforms): + """Each of ``xforms``' stored meta permissions values, keyed by form pk, + read in one query.""" + stored = {} + for object_id, value in MetaData.objects.filter( + content_type=ContentType.objects.get_for_model(XForm), + object_id__in=[xform.pk for xform in xforms], + data_type=XFORM_META_PERMS, + ).values_list("object_id", "data_value"): + stored.setdefault(object_id, []).append(value) + return stored + + +def admin_roles_granted(xforms, role_name, stored=None): + """``(xform, role)`` for each owner or manager role that sharing ``xforms`` + as ``role_name`` grants. + + A form's meta permissions can turn a lesser role into an admin one, so a + gate that read only ``role_name`` would let an editor share through. + ``stored`` is ``_stored_meta_perms`` of ``xforms``, when already read. + """ + xforms = list(xforms) + if stored is None: + stored = _stored_meta_perms(xforms) + return [ + (xform, ROLES[name]) + for xform in xforms + for name in sorted(roles_under_meta_perms(stored.get(xform.pk, ()), role_name)) + if name in ADMIN_ROLE_NAMES + ] + + +def grants_admin_role(xforms, role_name): + """Whether sharing ``xforms`` as ``role_name`` grants an owner or manager + role on any of them.""" + return role_name in ADMIN_ROLE_NAMES or bool(admin_roles_granted(xforms, role_name)) + + +def admin_role(role_name): + """The owner or manager role named ``role_name``, or None for any other + role.""" + return ROLES[role_name] if role_name in ADMIN_ROLE_NAMES else None + + +def holds_roles(user, granted): + """Whether ``user`` already holds every ``(obj, role)`` in ``granted``, so + a share granting them hands out nothing new.""" + return all(role.user_has_role(user, obj) for obj, role in granted) + + +def appoints_admins(xform, meta_perms): + """Whether applying ``meta_perms`` to ``xform`` makes one of its current + users an owner or manager they are not yet. + + Applying them re-assigns every user of the form, so writing back an + unchanged value still promotes anyone who reached a slot's role since the + value was last applied.""" + for user, details in get_xform_users(xform).items(): + name = role_under_meta_perms(meta_perms, details["role"]) + if name in ADMIN_ROLE_NAMES and not ROLES[name].user_has_role(user, xform): + return True + return False + + +def reapplying_appoints_admins(xforms): + """Whether re-applying the stored meta permissions of any of ``xforms`` + makes one of its users an owner or manager they are not yet.""" + return any( + appoints_admins(xform, meta_perms) + for xform in xforms + for meta_perms in xform.metadata_set.filter( + data_type=XFORM_META_PERMS + ).values_list("data_value", flat=True) + ) + + +def team_reaches_admin_role(team): + """Whether joining ``team`` leads to owning or managing a project or form + that is not deleted. + + The team may hold that role outright, or hold one that a form's meta + permissions turn into owner or manager. A manager's permissions are a + subset of an owner's, so matching them finds both.""" + holds_outright = any( + get_objects_for_group( + team, + ManagerRole.class_to_permissions[model], + klass=model, + accept_global_perms=False, + ) + .filter(deleted_at__isnull=True) + .exists() + for model in (Project, XForm) + ) + if holds_outright: + return True + xforms = list( + XForm.objects.filter( + xformgroupobjectpermission__group=team, deleted_at__isnull=True + ) + .only("pk") + .distinct() + ) + stored = _stored_meta_perms(xforms) + return any( + name in ADMIN_ROLE_NAMES + for xform in xforms + for name in roles_under_meta_perms( + stored.get(xform.pk, ()), get_role(get_perms(team, xform), xform) + ) + ) + + +def move_appoints_admins(xform, project): + """Whether moving ``xform`` into ``project`` makes someone an owner or + manager of it who is not one of ``project``. + + The move gives the form the project's roles, then applies the form's meta + permissions to them.""" + teams = { + perm.group + for perm in project.projectgroupobjectpermission_set.select_related("group") + } + roles = {details["role"] for details in get_project_users(project).values()} | { + get_role(get_perms(team, project), project) for team in teams + } + return any( + name in ADMIN_ROLE_NAMES + for role in roles - ADMIN_ROLE_NAMES + for name in meta_perms_roles(xform, role) + ) + + +def _role_shared_with_member(members_team, project, user, role_name): + if role_name == OwnerRole.name: + return role_name + if role_name == ManagerRole.name and project.created_by == user: + return role_name + return get_team_project_default_permissions(members_team, project) + + +def member_admin_roles(projects, members_team, user, role_name): + """``(obj, role)`` for each owner or manager role that adding ``user`` to + an organisation as ``role_name`` shares with them on ``projects``, the + organisation's projects. + + Mirrors ``add_user_to_organization``, which also runs for an existing + member. Each project is shared at the members team's role on it. An owner + gets ``role_name`` on every project, and a manager gets it on the projects + they created.""" + projects = list(projects.prefetch_related("xform_set")) + stored = _stored_meta_perms( + [xform for project in projects for xform in project.xform_set.all()] + ) + granted = [] + for project in projects: + shared = _role_shared_with_member(members_team, project, user, role_name) + role = admin_role(shared) + if role is not None: + granted.append((project, role)) + granted.extend( + admin_roles_granted(project.xform_set.all(), shared, stored=stored) + ) + return granted diff --git a/onadata/libs/tests/stepup/__init__.py b/onadata/libs/tests/stepup/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/onadata/libs/tests/stepup/test_capabilities.py b/onadata/libs/tests/stepup/test_capabilities.py new file mode 100644 index 0000000000..88319ac913 --- /dev/null +++ b/onadata/libs/tests/stepup/test_capabilities.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- +"""Tests for what a deployment reports it can manage about credentials.""" + +from django.test import TestCase, override_settings + +from onadata.libs.stepup.capabilities import account_capabilities + +SERVERS = {"kc": {"STEP_UP": {"CLAIM": "acr"}}} + +FEDERATED = { + "STEP_UP": {"MODE": "federated"}, + "OPENID_CONNECT_AUTH_SERVERS": SERVERS, + "STEP_UP_IDP_NAME": "", +} + + +@override_settings(STEP_UP={"MODE": "local"}, ENABLE_TWO_FACTOR=False) +class TestTwoFactorDisabled(TestCase): + """A deployment that never enabled two-factor manages none of it. + + /api/v1/totp/* answers 404 there, so no two-factor control is available. + """ + + def test_the_two_factor_controls_are_all_unavailable(self): + capabilities = account_capabilities()["twoFactor"] + + for control in ("enroll", "disable", "recoveryCodes", "verify"): + with self.subTest(control=control): + self.assertFalse(capabilities[control]) + + def test_changing_a_password_is_unaffected(self): + """OnaData still owns the password when two-factor is off.""" + self.assertTrue(account_capabilities()["password"]["change"]) + + +class TestAccountCapabilities(TestCase): + # ENABLE_TWO_FACTOR is pinned because two-factor is off by default. This + # case tests who manages two-factor, not whether it is on. + @override_settings(STEP_UP={"MODE": "local"}, ENABLE_TWO_FACTOR=True) + def test_onadata_owning_identity_can_manage_everything(self): + caps = account_capabilities() + + self.assertTrue(caps["password"]["change"]) + self.assertEqual(caps["twoFactor"]["managedBy"], "onadata") + self.assertTrue(caps["twoFactor"]["enroll"]) + self.assertEqual(caps["identityProvider"], "") + + @override_settings(**FEDERATED) + def test_a_federated_deployment_manages_no_credentials(self): + """There is no OnaData password to change and no factor to enrol. + The provider is reported unnamed unless the deployment names it. + """ + caps = account_capabilities() + + self.assertFalse(caps["password"]["change"]) + self.assertEqual(caps["twoFactor"]["managedBy"], "idp") + self.assertFalse(caps["twoFactor"]["enroll"]) + self.assertFalse(caps["twoFactor"]["disable"]) + self.assertFalse(caps["twoFactor"]["recoveryCodes"]) + self.assertEqual(caps["identityProvider"], "") + + @override_settings(**{**FEDERATED, "STEP_UP_IDP_NAME": "Acme SSO"}) + def test_a_deployment_fronts_a_name_its_users_recognise(self): + self.assertEqual(account_capabilities()["identityProvider"], "Acme SSO") diff --git a/onadata/libs/tests/stepup/test_challenge.py b/onadata/libs/tests/stepup/test_challenge.py new file mode 100644 index 0000000000..98d1e2c8ca --- /dev/null +++ b/onadata/libs/tests/stepup/test_challenge.py @@ -0,0 +1,81 @@ +# -*- coding: utf-8 -*- +"""Tests for the challenge body.""" + +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.contrib.auth.models import AnonymousUser +from django.core.exceptions import ImproperlyConfigured +from django.test import TestCase, override_settings + +from onadata.libs.stepup.challenge import build_challenge + +GATED = {"ACTIONS": {"require-auth-toggle"}, "MODE": "local"} + +FEDERATED = {"ACTIONS": {"require-auth-toggle"}, "MODE": "federated"} + +FEDERATED_SERVER = { + "kc": { + "AUTHORIZATION_ENDPOINT": "https://idp.example/auth", + "CLIENT_ID": "app", + "SCOPE": "openid email", + "STEP_UP": { + "CLAIM": "acr", + "SATISFIED_BY": ["gold"], + "MAX_AGE": 0, + "REDIRECT_URI": "https://ona.example/api/v1/stepup/callback", + }, + } +} + + +class TestChallenge(TestCase): + @override_settings(STEP_UP=GATED) + def test_local_mode_asks_for_a_code(self): + body = build_challenge("require-auth-toggle") + + self.assertEqual(body["error"], "step_up_required") + self.assertEqual(body["dialect"], "local-totp") + # A client echoes the audience to /totp/verify. Without it, the grant + # it gets back cannot be spent on this action. + self.assertEqual(body["audience"], "require-auth-toggle") + + +@override_settings(STEP_UP=FEDERATED, OPENID_CONNECT_AUTH_SERVERS=FEDERATED_SERVER) +class TestFederatedChallengeCannotBeBuilt(TestCase): + """A gated request must answer even when the deployment is misconfigured. + + Raising here would return a 500 on an ordinary action instead of a + challenge a client can report. + """ + + def setUp(self): + self.user = get_user_model().objects.create(username="ana") + + def test_no_user_to_bind_the_state_to(self): + body = build_challenge("require-auth-toggle", None) + + self.assertEqual(body["error"], "step_up_unavailable") + + def test_an_anonymous_user_to_bind_the_state_to(self): + body = build_challenge("require-auth-toggle", AnonymousUser()) + + self.assertEqual(body["error"], "step_up_unavailable") + + def test_a_server_with_a_malformed_config(self): + for error in (ImproperlyConfigured("no CLIENT_ID"), TypeError("bad")): + with self.subTest(error=type(error).__name__), patch( + "onadata.libs.stepup.challenge.start_step_up", side_effect=error + ): + body = build_challenge("require-auth-toggle", self.user) + + self.assertEqual(body["error"], "step_up_unavailable") + + def test_a_server_missing_its_endpoints(self): + with patch( + "onadata.libs.stepup.challenge.start_step_up", + side_effect=ValueError("no AUTHORIZATION_ENDPOINT"), + ): + body = build_challenge("require-auth-toggle", self.user) + + self.assertEqual(body["error"], "step_up_unavailable") diff --git a/onadata/libs/tests/stepup/test_checks.py b/onadata/libs/tests/stepup/test_checks.py new file mode 100644 index 0000000000..17d633b90c --- /dev/null +++ b/onadata/libs/tests/stepup/test_checks.py @@ -0,0 +1,333 @@ +"""Tests for module onadata.libs.stepup.checks""" + +from django.test import SimpleTestCase, override_settings + +from onadata.libs.stepup.checks import ( + check_federated_step_up_binds_by_email, + check_federated_step_up_gates_email, + check_oauth_approval_can_step_up, + check_removed_enrolment_password_setting, + check_step_up_actions_are_known, + check_step_up_has_two_factor_enabled, + check_step_up_is_well_formed, + check_step_up_mode_is_known, + check_step_up_no_factor_policy_is_known, + check_step_up_not_silently_bypassable, +) + +ALL_CHECKS = ( + check_federated_step_up_binds_by_email, + check_federated_step_up_gates_email, + check_oauth_approval_can_step_up, + check_removed_enrolment_password_setting, + check_step_up_actions_are_known, + check_step_up_has_two_factor_enabled, + check_step_up_is_well_formed, + check_step_up_mode_is_known, + check_step_up_no_factor_policy_is_known, + check_step_up_not_silently_bypassable, +) + + +class TestTwoFactorEnabled(SimpleTestCase): + """Local step-up needs the two-factor endpoints that mint its grants.""" + + @override_settings( + ENABLE_TWO_FACTOR=False, + STEP_UP={"ACTIONS": {"require-auth-toggle"}, "MODE": "local"}, + ) + def test_gating_with_two_factor_off_is_reported(self): + warnings = check_step_up_has_two_factor_enabled() + + self.assertEqual(len(warnings), 1) + self.assertEqual(warnings[0].id, "stepup.W004") + + @override_settings( + ENABLE_TWO_FACTOR=True, + STEP_UP={"ACTIONS": {"require-auth-toggle"}, "MODE": "local"}, + ) + def test_two_factor_on_is_silent(self): + self.assertEqual(check_step_up_has_two_factor_enabled(), []) + + @override_settings( + ENABLE_TWO_FACTOR=False, + STEP_UP={"ACTIONS": {"require-auth-toggle"}, "MODE": "federated"}, + ) + def test_federated_mode_is_not_reported(self): + """Federated grants come from the provider, not /api/v1/totp.""" + self.assertEqual(check_step_up_has_two_factor_enabled(), []) + + @override_settings( + ENABLE_TWO_FACTOR=False, + STEP_UP={"ACTIONS": set(), "MODE": "local"}, + ) + def test_gating_nothing_is_silent(self): + self.assertEqual(check_step_up_has_two_factor_enabled(), []) + + +class TestModeIsKnown(SimpleTestCase): + """MODE must name a topology, not a typo that silently picks federated.""" + + @override_settings(STEP_UP={"MODE": "fedarated"}) + def test_an_unknown_mode_is_reported(self): + warnings = check_step_up_mode_is_known() + + self.assertEqual(len(warnings), 1) + self.assertEqual(warnings[0].id, "stepup.W003") + self.assertIn("fedarated", warnings[0].msg) + + @override_settings(STEP_UP={"MODE": "local"}) + def test_local_is_silent(self): + self.assertEqual(check_step_up_mode_is_known(), []) + + @override_settings(STEP_UP={"MODE": "federated"}) + def test_federated_is_silent(self): + self.assertEqual(check_step_up_mode_is_known(), []) + + @override_settings(STEP_UP={"ACTIONS": set()}) + def test_the_default_mode_is_silent(self): + """No MODE set falls back to 'local', which must not warn.""" + self.assertEqual(check_step_up_mode_is_known(), []) + + +class TestNotSilentlyBypassable(SimpleTestCase): + """skip_gate with gated actions lets users with no factor through. That + is a valid rollout choice, but it must not be silent.""" + + @override_settings( + STEP_UP={ + "ACTIONS": {"require-auth-toggle"}, + "NO_FACTOR_POLICY": "skip_gate", + } + ) + def test_skip_gate_with_actions_is_reported(self): + warnings = check_step_up_not_silently_bypassable() + + self.assertEqual(len(warnings), 1) + self.assertEqual(warnings[0].id, "stepup.W001") + self.assertIn("require-auth-toggle", warnings[0].msg) + + @override_settings( + STEP_UP={ + "ACTIONS": {"require-auth-toggle"}, + "NO_FACTOR_POLICY": "deny_prompt_enrol", + } + ) + def test_deny_prompt_enrol_is_silent(self): + self.assertEqual(check_step_up_not_silently_bypassable(), []) + + @override_settings(STEP_UP={"ACTIONS": set(), "NO_FACTOR_POLICY": "skip_gate"}) + def test_gating_nothing_is_silent(self): + self.assertEqual(check_step_up_not_silently_bypassable(), []) + + @override_settings( + STEP_UP={ + "ACTIONS": {"require-auth-toggle"}, + "MODE": "federated", + "NO_FACTOR_POLICY": "skip_gate", + } + ) + def test_federated_mode_is_silent(self): + """Federated mode always challenges, so skip_gate bypasses nothing.""" + self.assertEqual(check_step_up_not_silently_bypassable(), []) + + +class TestFederatedStepUpGatesEmail(SimpleTestCase): + """Federated step-up matches the provider's token to the account's email, + so an ungated email change is a way around every gate.""" + + @override_settings(STEP_UP={"MODE": "federated", "ACTIONS": ["regenerate-api-key"]}) + def test_an_ungated_email_change_is_reported(self): + warnings = check_federated_step_up_gates_email() + + self.assertEqual([w.id for w in warnings], ["stepup.W006"]) + + @override_settings( + STEP_UP={ + "MODE": "federated", + "ACTIONS": ["regenerate-api-key", "change-email"], + } + ) + def test_a_gated_email_change_is_silent(self): + self.assertEqual(check_federated_step_up_gates_email(), []) + + @override_settings(STEP_UP={"MODE": "local", "ACTIONS": ["regenerate-api-key"]}) + def test_local_mode_is_silent(self): + self.assertEqual(check_federated_step_up_gates_email(), []) + + +def _servers(**step_up): + return {"idp": {"STEP_UP": {"REDIRECT_URI": "https://app.test/cb", **step_up}}} + + +class TestFederatedStepUpBindsByEmail(SimpleTestCase): + """Of the fields step-up can identify the user by, only the email is + gated against change.""" + + @override_settings( + STEP_UP={"MODE": "federated", "ACTIONS": ["change-email"]}, + OPENID_CONNECT_AUTH_SERVERS=_servers(SUBJECT_FIELD="username"), + ) + def test_a_username_binding_is_reported(self): + warnings = check_federated_step_up_binds_by_email() + + self.assertEqual([w.id for w in warnings], ["stepup.W007"]) + + @override_settings( + STEP_UP={"MODE": "federated", "ACTIONS": ["change-email"]}, + OPENID_CONNECT_AUTH_SERVERS=_servers(), + ) + def test_the_default_email_binding_is_silent(self): + self.assertEqual(check_federated_step_up_binds_by_email(), []) + + @override_settings( + STEP_UP={"MODE": "local", "ACTIONS": ["change-email"]}, + OPENID_CONNECT_AUTH_SERVERS=_servers(SUBJECT_FIELD="username"), + ) + def test_local_mode_is_silent(self): + self.assertEqual(check_federated_step_up_binds_by_email(), []) + + +class TestRemovedEnrolmentPasswordSetting(SimpleTestCase): + """The removed opt-out does nothing. Enrolment always needs the password, + so users without one cannot enrol.""" + + @override_settings(TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD=False) + def test_a_leftover_opt_out_is_reported(self): + warnings = check_removed_enrolment_password_setting() + + self.assertEqual(len(warnings), 1) + self.assertEqual(warnings[0].id, "stepup.W005") + + def test_an_absent_setting_is_silent(self): + self.assertEqual(check_removed_enrolment_password_setting(), []) + + +class TestStepUpIsWellFormed(SimpleTestCase): + """A STEP_UP the policy cannot read gates nothing, so it is an error.""" + + def _ids(self): + return [message.id for message in check_step_up_is_well_formed()] + + def _every_check_runs(self): + """No check may crash on the setting it exists to report.""" + return [message.id for check in ALL_CHECKS for message in check()] + + @override_settings(STEP_UP=["change-email"]) + def test_a_setting_that_is_not_a_dict_is_reported(self): + """A list where the dict belongs reads as gating nothing.""" + self.assertEqual(self._ids(), ["stepup.E001"]) + self.assertIn("stepup.E001", self._every_check_runs()) + + @override_settings(STEP_UP={"ACTIONS": None}) + def test_actions_that_are_not_a_collection_are_reported(self): + """The checks report None instead of raising TypeError.""" + self.assertEqual(self._ids(), ["stepup.E001"]) + self.assertIn("stepup.E001", self._every_check_runs()) + + @override_settings(STEP_UP={"ACTIONS": ["change-email", ["change-password"]]}) + def test_actions_that_are_not_strings_are_reported(self): + """The policy skips a nested list because it is unhashable.""" + self.assertEqual(self._ids(), ["stepup.E001"]) + self.assertIn("stepup.E001", self._every_check_runs()) + + @override_settings(STEP_UP={"ACTIONS": {"change-email": True}}) + def test_actions_given_as_a_dict_are_reported(self): + """A dict would gate its keys, which is unlikely to be what was meant.""" + self.assertEqual(self._ids(), ["stepup.E001"]) + + @override_settings(STEP_UP={"MODE": ["local"]}) + def test_an_unhashable_mode_is_reported_rather_than_raised(self): + """Membership of a list in a frozenset raises TypeError.""" + self.assertEqual( + [message.id for message in check_step_up_mode_is_known()], + ["stepup.W003"], + ) + + @override_settings(STEP_UP={"ACTIONS": ["change-email"], "MODE": "local"}) + def test_a_list_of_actions_is_silent(self): + """A well-formed setting is not reported.""" + self.assertEqual(self._ids(), []) + + @override_settings(STEP_UP={"ACTIONS": "change-email"}) + def test_a_single_action_as_a_string_is_silent(self): + """The policy reads a bare string as one action.""" + self.assertEqual(self._ids(), []) + + @override_settings(STEP_UP=None) + def test_an_unset_setting_is_silent(self): + """A deployment that never configured step-up is not reported.""" + self.assertEqual(self._ids(), []) + + +class TestStepUpActionsAreKnown(SimpleTestCase): + """An action name no gate checks protects nothing, in either mode.""" + + @override_settings(STEP_UP={"ACTIONS": ["change-emial"], "MODE": "local"}) + def test_an_unknown_action_is_reported_in_local_mode(self): + """A typo leaves the intended action ungated.""" + errors = check_step_up_actions_are_known() + + self.assertEqual([e.id for e in errors], ["stepup.E002"]) + self.assertTrue(errors[0].is_serious()) + self.assertIn("change-emial", errors[0].msg) + + @override_settings(STEP_UP={"ACTIONS": ["change-emial"], "MODE": "federated"}) + def test_an_unknown_action_is_reported_in_federated_mode(self): + """Federated mode has no other check that would catch it.""" + errors = check_step_up_actions_are_known() + + self.assertEqual([e.id for e in errors], ["stepup.E002"]) + + @override_settings( + STEP_UP={"ACTIONS": ["change-email", "publish-data"], "MODE": "federated"} + ) + def test_known_actions_are_silent(self): + """Real action names are not reported.""" + self.assertEqual(check_step_up_actions_are_known(), []) + + +class TestNoFactorPolicyIsKnown(SimpleTestCase): + """An unrecognised NO_FACTOR_POLICY refuses users with no factor for a + reason no one chose.""" + + @override_settings(STEP_UP={"NO_FACTOR_POLICY": "deny"}) + def test_an_unknown_policy_is_reported(self): + """A misspelt policy refuses users with no factor.""" + warnings = check_step_up_no_factor_policy_is_known() + + self.assertEqual([w.id for w in warnings], ["stepup.W008"]) + self.assertIn("deny", warnings[0].msg) + + @override_settings(STEP_UP={"NO_FACTOR_POLICY": "deny_prompt_enrol"}) + def test_deny_prompt_enrol_is_silent(self): + """A known policy is not reported.""" + self.assertEqual(check_step_up_no_factor_policy_is_known(), []) + + @override_settings(STEP_UP={}) + def test_the_default_policy_is_silent(self): + """An unset policy falls back to skip_gate, which is known.""" + self.assertEqual(check_step_up_no_factor_policy_is_known(), []) + + +class TestOAuthApprovalCanStepUp(SimpleTestCase): + """The OAuth pages cannot run a challenge, so gating them refuses every + approval the gate challenges.""" + + @override_settings(STEP_UP={"ACTIONS": ["authorize-oauth-app"], "MODE": "local"}) + def test_gating_oauth_approval_is_reported(self): + warnings = check_oauth_approval_can_step_up() + + self.assertEqual([w.id for w in warnings], ["stepup.W009"]) + + @override_settings( + STEP_UP={"ACTIONS": ["authorize-oauth-app"], "MODE": "federated"} + ) + def test_federated_mode_is_reported_too(self): + self.assertEqual( + [w.id for w in check_oauth_approval_can_step_up()], ["stepup.W009"] + ) + + @override_settings(STEP_UP={"ACTIONS": ["change-email"], "MODE": "local"}) + def test_other_gates_are_silent(self): + self.assertEqual(check_oauth_approval_can_step_up(), []) diff --git a/onadata/libs/tests/stepup/test_drf.py b/onadata/libs/tests/stepup/test_drf.py new file mode 100644 index 0000000000..10952a5141 --- /dev/null +++ b/onadata/libs/tests/stepup/test_drf.py @@ -0,0 +1,253 @@ +# -*- coding: utf-8 -*- +"""Tests for the DRF gate.""" + +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.contrib.auth.models import AnonymousUser +from django.core.cache import cache +from django.test import TestCase, override_settings + +from django_otp.plugins.otp_totp.models import TOTPDevice +from oidc.stepup_grants import issue_grant +from rest_framework.parsers import JSONParser +from rest_framework.request import Request +from rest_framework.test import APIRequestFactory + +from onadata.libs.stepup.drf import RequiresStepUp +from onadata.libs.tests.stepup.test_challenge import ( + FEDERATED, + FEDERATED_SERVER, + GATED, +) + + +class _View(RequiresStepUp): + pass + + +class _GateHarness(TestCase): + """Requests carry an explicit parser. + + The gate reads ``request.data``, and a request built without parsers + raises UnsupportedMediaType instead of returning the grant. + """ + + def setUp(self): + cache.clear() + self.factory = APIRequestFactory() + self.user = get_user_model().objects.create( + username="ana", email="ana@example.org" + ) + self.view = _View() + + def _request(self, data=None, **extra): + request = Request( + self.factory.post("/", data or {}, format="json", **extra), + parsers=[JSONParser()], + ) + request.user = self.user + return request + + +class TestRequiresStepUp(_GateHarness): + def _enrol(self): + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + + @override_settings(STEP_UP=GATED) + def test_an_enrolled_user_without_a_grant_is_challenged(self): + self._enrol() + + refusal = self.view.check_step_up(self._request(), "require-auth-toggle") + + self.assertIsNotNone(refusal) + self.assertEqual(refusal.status_code, 401) + self.assertEqual(refusal.data["error"], "step_up_required") + + @override_settings(STEP_UP=GATED) + def test_a_grant_for_this_action_passes(self): + self._enrol() + grant = issue_grant(self.user.pk, "require-auth-toggle") + + refusal = self.view.check_step_up( + self._request({"grant": grant}), "require-auth-toggle" + ) + + self.assertIsNone(refusal) + + @override_settings(STEP_UP=GATED) + def test_a_grant_for_a_different_action_does_not(self): + self._enrol() + grant = issue_grant(self.user.pk, "disable") + + refusal = self.view.check_step_up( + self._request({"grant": grant}), "require-auth-toggle" + ) + + self.assertEqual(refusal.status_code, 401) + + @override_settings(STEP_UP={"ACTIONS": set(), "MODE": "local"}) + def test_an_ungated_action_passes_untouched(self): + self._enrol() + + self.assertIsNone( + self.view.check_step_up(self._request(), "require-auth-toggle") + ) + + @override_settings(STEP_UP={**GATED, "NO_FACTOR_POLICY": "skip_gate"}) + def test_a_user_with_no_factor_is_waved_through_under_skip_gate(self): + """skip_gate is the default. The gate does not apply to a user who + has not enrolled.""" + self.assertIsNone( + self.view.check_step_up(self._request(), "require-auth-toggle") + ) + + @override_settings(STEP_UP={**GATED, "NO_FACTOR_POLICY": "deny_prompt_enrol"}) + def test_a_user_with_no_factor_is_refused_under_deny(self): + refusal = self.view.check_step_up(self._request(), "require-auth-toggle") + + self.assertEqual(refusal.status_code, 403) + self.assertEqual(refusal.data["error"], "enrol_required") + + @override_settings(STEP_UP={**GATED, "NO_FACTOR_POLICY": "deny_prompt_enroll"}) + def test_a_misspelt_policy_refuses_rather_than_skips(self): + refusal = self.view.check_step_up(self._request(), "require-auth-toggle") + + self.assertEqual(refusal.status_code, 403) + self.assertEqual(refusal.data["error"], "enrol_required") + + +@override_settings( + STEP_UP={**FEDERATED, "NO_FACTOR_POLICY": "skip_gate"}, + OPENID_CONNECT_AUTH_SERVERS=FEDERATED_SERVER, +) +class TestFederatedGate(_GateHarness): + """A federated deployment has no local device to look up, so the gate + challenges every user.""" + + def test_a_user_with_no_local_device_is_still_challenged(self): + refusal = self.view.check_step_up(self._request(), "require-auth-toggle") + + self.assertIsNotNone(refusal) + self.assertEqual(refusal.status_code, 401) + self.assertEqual(refusal.data["dialect"], "oidc") + self.assertIn("authorizationUrl", refusal.data) + + def test_a_valid_grant_still_lets_the_action_through(self): + """The gate still honours a valid grant in federated mode.""" + grant = issue_grant(self.user.pk, "require-auth-toggle") + + refusal = self.view.check_step_up( + self._request({"grant": grant}), "require-auth-toggle" + ) + + self.assertIsNone(refusal) + + +@override_settings(STEP_UP=FEDERATED, OPENID_CONNECT_AUTH_SERVERS={}) +class TestUnavailableStepUp(_GateHarness): + """A deployment with nowhere to send the user cannot be satisfied by the + caller, so the gate answers as the start endpoint does.""" + + def test_a_gate_that_cannot_build_a_challenge_answers_503(self): + refusal = self.view.check_step_up(self._request(), "require-auth-toggle") + + self.assertIsNotNone(refusal) + self.assertEqual(refusal.status_code, 503) + self.assertEqual(refusal.data, {"error": "step_up_unavailable"}) + + +@override_settings(STEP_UP=GATED) +class TestGateInputs(_GateHarness): + """The default skip_gate policy lets a user with no factor through, so a + refusal here comes from the input, not the policy.""" + + def test_an_anonymous_request_is_challenged(self): + request = self._request() + request.user = AnonymousUser() + + refusal = self.view.check_step_up(request, "require-auth-toggle") + + self.assertEqual(refusal.status_code, 401) + self.assertEqual(refusal.data["error"], "step_up_required") + + def test_a_malformed_grant_is_treated_as_none(self): + """A value that cannot be a grant never reaches the cache, where it + would be an invalid key.""" + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + malformed = "not a grant/" + "x" * 300 + + with patch("onadata.libs.stepup.gate.spend_grant", return_value=False) as spend: + refusal = self.view.check_step_up( + self._request(HTTP_X_STEP_UP_GRANT=malformed), "require-auth-toggle" + ) + + self.assertEqual(refusal.status_code, 401) + spend.assert_called_once_with(self.user.pk, "require-auth-toggle", "") + + +@override_settings(STEP_UP=GATED) +class TestGateAuditLog(_GateHarness): + """Gate decisions reach the security audit log, without the grant.""" + + def setUp(self): + super().setUp() + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + + def _check(self, request): + with self.assertLogs("audit_logger", level="DEBUG") as captured: + refusal = self.view.check_step_up(request, "require-auth-toggle") + return refusal, captured.records + + def _assert_recorded(self, records, action, grant): + matching = [r for r in records if getattr(r, "formhub_action", None) == action] + self.assertEqual(len(matching), 1) + self.assertEqual(matching[0].audit, {"audience": "require-auth-toggle"}) + for record in records: + self.assertNotIn(grant, record.getMessage()) + self.assertNotIn(grant, str(record.audit)) + + def test_a_spent_grant_is_recorded(self): + grant = issue_grant(self.user.pk, "require-auth-toggle") + + refusal, records = self._check(self._request({"grant": grant})) + + self.assertIsNone(refusal) + self._assert_recorded(records, "step-up-grant-spent", grant) + + def test_a_grant_for_another_action_is_recorded_as_rejected(self): + grant = issue_grant(self.user.pk, "disable") + + refusal, records = self._check(self._request({"grant": grant})) + + self.assertEqual(refusal.status_code, 401) + self._assert_recorded(records, "step-up-grant-rejected", grant) + + def test_a_replayed_grant_is_recorded_as_rejected(self): + grant = issue_grant(self.user.pk, "require-auth-toggle") + self.assertIsNone( + self.view.check_step_up( + self._request({"grant": grant}), "require-auth-toggle" + ) + ) + + refusal, records = self._check(self._request({"grant": grant})) + + self.assertEqual(refusal.status_code, 401) + self._assert_recorded(records, "step-up-grant-rejected", grant) + + @override_settings(STEP_UP={**GATED, "NO_FACTOR_POLICY": "deny_prompt_enrol"}) + def test_an_enrol_required_refusal_is_recorded(self): + TOTPDevice.objects.filter(user=self.user).delete() + + refusal, records = self._check(self._request()) + + self.assertEqual(refusal.data["error"], "enrol_required") + actions = [getattr(r, "formhub_action", None) for r in records] + self.assertIn("step-up-enrol-required", actions) + + def test_a_request_without_a_grant_records_no_rejection(self): + with self.assertNoLogs("audit_logger", level="DEBUG"): + refusal = self.view.check_step_up(self._request(), "require-auth-toggle") + + self.assertEqual(refusal.status_code, 401) diff --git a/onadata/libs/tests/stepup/test_policy.py b/onadata/libs/tests/stepup/test_policy.py new file mode 100644 index 0000000000..07189beb5f --- /dev/null +++ b/onadata/libs/tests/stepup/test_policy.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +"""Tests for which actions are gated, and how this deployment proves a factor.""" + +from django.test import TestCase, override_settings + +from onadata.libs.stepup.policy import ( + eu_consent_path, + is_gated, + mode, + no_factor_policy, +) + + +@override_settings(STEP_UP={"ACTIONS": {"require-auth-toggle"}}) +class TestPolicy(TestCase): + def test_only_listed_actions_are_gated(self): + self.assertTrue(is_gated("require-auth-toggle")) + self.assertFalse(is_gated("something-else")) + + @override_settings(STEP_UP={}) + def test_an_unconfigured_deployment_behaves_as_before(self): + """A deployment that has not opted in gates nothing, uses the local + dialect and lets users without a factor through.""" + self.assertFalse(is_gated("require-auth-toggle")) + self.assertEqual(mode(), "local") + self.assertEqual(no_factor_policy(), "skip_gate") + + @override_settings( + STEP_UP={"ACTIONS": "change-email"}, + EU_CONSENT_METADATA_PATH="eu_citizen_consent", + ) + def test_a_string_setting_is_one_entry_not_its_characters(self): + self.assertTrue(is_gated("change-email")) + self.assertFalse(is_gated("c")) + self.assertEqual(eu_consent_path(), ("eu_citizen_consent",)) + + @override_settings(STEP_UP={"ACTIONS": None}) + def test_actions_that_are_not_a_collection_gate_nothing(self): + """The policy reads it as empty instead of raising, so the startup + check can report it.""" + self.assertFalse(is_gated("change-email")) + + @override_settings(STEP_UP=["change-email"]) + def test_a_setting_that_is_not_a_dict_gates_nothing(self): + """The policy reads it as unconfigured, and stepup.E001 reports it.""" + self.assertFalse(is_gated("change-email")) + self.assertEqual(mode(), "local") + + @override_settings(STEP_UP={"ACTIONS": ["change-email", ["publish-data"]]}) + def test_entries_that_are_not_strings_are_skipped(self): + """An unhashable entry would otherwise crash every gate.""" + self.assertTrue(is_gated("change-email")) + self.assertFalse(is_gated("publish-data")) diff --git a/onadata/libs/tests/utils/test_xform_utils.py b/onadata/libs/tests/utils/test_xform_utils.py new file mode 100644 index 0000000000..9ba4a976e0 --- /dev/null +++ b/onadata/libs/tests/utils/test_xform_utils.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +"""Tests for onadata.libs.utils.xform_utils.""" + +from django.test import SimpleTestCase + +from onadata.libs.utils.xform_utils import role_under_meta_perms + +META_PERMS = "owner|manager|readonly-no-download" + + +class TestRoleUnderMetaPerms(SimpleTestCase): + """Each lesser role takes the role in its slot of the meta permissions.""" + + def test_an_editor_role_takes_the_first_slot(self): + """Every editor role maps to the first slot.""" + for role_name in ("editor", "editor-minor", "editor-no-download"): + self.assertEqual(role_under_meta_perms(META_PERMS, role_name), "owner") + + def test_a_data_entry_role_takes_the_second_slot(self): + """Every data-entry role maps to the second slot.""" + for role_name in ("dataentry", "dataentry-minor", "dataentry-only"): + self.assertEqual(role_under_meta_perms(META_PERMS, role_name), "manager") + + def test_a_read_only_role_takes_the_third_slot(self): + """Both read-only roles map to the third slot.""" + for role_name in ("readonly", "readonly-no-download"): + self.assertEqual( + role_under_meta_perms(META_PERMS, role_name), "readonly-no-download" + ) + + def test_an_admin_role_is_left_alone(self): + """Meta permissions never replace an owner or manager.""" + for role_name in ("owner", "manager"): + self.assertEqual(role_under_meta_perms(META_PERMS, role_name), role_name) + + def test_a_missing_slot_leaves_the_role_alone(self): + """A value with too few slots replaces only the roles it covers.""" + self.assertEqual(role_under_meta_perms("owner", "editor"), "owner") + self.assertEqual(role_under_meta_perms("owner", "dataentry"), "dataentry") diff --git a/onadata/libs/utils/log.py b/onadata/libs/utils/log.py index 3d409a21ae..f5decadf3a 100644 --- a/onadata/libs/utils/log.py +++ b/onadata/libs/utils/log.py @@ -66,6 +66,9 @@ def __iter__(self): TWO_FACTOR_VERIFICATION_FAILED="two-factor-verification-failed", TWO_FACTOR_RECOVERY_CODES_GENERATED="two-factor-recovery-codes-generated", TWO_FACTOR_RECOVERY_CODES_VIEWED="two-factor-recovery-codes-viewed", + STEP_UP_GRANT_SPENT="step-up-grant-spent", + STEP_UP_GRANT_REJECTED="step-up-grant-rejected", + STEP_UP_ENROL_REQUIRED="step-up-enrol-required", ) diff --git a/onadata/libs/utils/xform_utils.py b/onadata/libs/utils/xform_utils.py index 643f230709..ce8eb169e0 100644 --- a/onadata/libs/utils/xform_utils.py +++ b/onadata/libs/utils/xform_utils.py @@ -35,11 +35,18 @@ clear_project_owner_cache, safe_cache_delete, ) -from onadata.libs.utils.common_tags import MEMBERS +from onadata.libs.utils.common_tags import MEMBERS, XFORM_META_PERMS from onadata.libs.utils.common_tools import report_exception from onadata.libs.utils.model_tools import queryset_iterator from onadata.libs.utils.project_utils import get_project_users +#: The roles each slot of an ``xform_meta_perms`` value replaces, in order. +META_PERMS_SLOTS = ( + frozenset({EditorNoDownload.name, EditorRole.name, EditorMinorRole.name}), + frozenset({DataEntryMinorRole.name, DataEntryOnlyRole.name, DataEntryRole.name}), + frozenset({ReadOnlyRole.name, ReadOnlyRoleNoDownload.name}), +) + def get_team_members(org_username): """Return members team if it exists else none. @@ -162,16 +169,7 @@ def update_role_by_meta_xform_perms(xform, user=None, user_role=None): # pylint: disable=invalid-name MetaData = apps.get_model("main", "MetaData") # noqa: N806 metadata = MetaData.xform_meta_permission(xform) - editor_role = { - role.name: role for role in [EditorNoDownload, EditorRole, EditorMinorRole] - } - - dataentry_role = { - role.name: role - for role in [DataEntryMinorRole, DataEntryOnlyRole, DataEntryRole] - } - - readonly_role = {role.name: role for role in [ReadOnlyRole, ReadOnlyRoleNoDownload]} + editor_role, dataentry_role, readonly_role = META_PERMS_SLOTS project_users = get_project_users(xform.project) @@ -207,6 +205,34 @@ def update_role_by_meta_xform_perms(xform, user=None, user_role=None): role.add(xform_user, xform) +def role_under_meta_perms(meta_perms, role_name): + """The role ``role_name`` becomes on a form whose ``xform_meta_perms`` value + is ``meta_perms``. A role outside every slot stays as it is.""" + for replacement, role_names in zip(meta_perms.split("|"), META_PERMS_SLOTS): + if role_name in role_names: + return replacement + return role_name + + +def meta_perms_roles(xform, role_name): + """Every role sharing ``xform`` as ``role_name`` can end up granting once + the form's meta permissions apply. + + Counts the readonly slot even for a user the share would leave alone, so + it may name a role the share does not grant but never misses one it does. + """ + values = xform.metadata_set.filter(data_type=XFORM_META_PERMS).values_list( + "data_value", flat=True + ) + return roles_under_meta_perms(values, role_name) + + +def roles_under_meta_perms(values, role_name): + """``meta_perms_roles`` for a form whose stored ``xform_meta_perms`` values + are ``values``.""" + return {role_under_meta_perms(value, role_name) for value in values} or {role_name} + + # pylint: disable=invalid-name @app.task(bind=True, max_retries=3) def set_project_perms_to_xform_async(self, xform_id, project_id): diff --git a/onadata/settings/common.py b/onadata/settings/common.py index 75099b8596..3fdb0bf1cc 100644 --- a/onadata/settings/common.py +++ b/onadata/settings/common.py @@ -23,6 +23,7 @@ from django.utils.log import AdminEmailHandler from celery.signals import after_setup_logger +from corsheaders.defaults import default_headers # setting default encoding to utf-8 if sys.version[0] == "2": @@ -151,25 +152,19 @@ TWO_FACTOR_CALL_GATEWAY = None TWO_FACTOR_SMS_GATEWAY = None -# Operations a step-up grant may be minted for. /api/v1/totp/verify refuses -# anything else, so a client typo cannot spend a code on a grant nothing will -# honour. These are the operations this module gates itself; a deployment -# whose client gates more of its own adds them, rather than OnaData naming -# actions it does not check. -TWO_FACTOR_STEP_UP_AUDIENCES = frozenset( - {"enroll-start", "disable", "recovery-generate", "recovery-view"} -) - -# Demand the account password before a first authenticator enrolment, where -# there is no factor yet for ``_require_code`` to challenge. -# -# On by default: without it, an SSO credential alone can enrol an authenticator -# and lock the owner out of their own second factor, so the safe default is to -# require recent primary-credential proof. A deployment whose users hold no -# usable local password (identity lives entirely in an IdP) turns it off -# deliberately, accepting that trade -- or owns the factor federally, per -# ``STEP_UP``. -TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD = True +# Extra audiences /api/v1/totp/verify may mint a grant for. It already accepts +# the two-factor lifecycle operations and every action STEP_UP can gate. It +# refuses anything else, so a typo cannot spend a code on a grant nothing +# honours. Add any operation a client of this deployment gates itself. +TWO_FACTOR_STEP_UP_AUDIENCES = frozenset() + +# Step-up authentication. ACTIONS is empty, so each deployment opts in to +# gating. Set MODE to "federated" when an identity provider owns the factor. +STEP_UP = { + "ACTIONS": set(), + "MODE": "local", + "NO_FACTOR_POLICY": "skip_gate", +} # Symmetric keys the authenticator seed and recovery codes are encrypted under # at rest (Fernet, url-safe base64). Ordered: the first key encrypts, every key @@ -432,6 +427,9 @@ CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ("http://dev.ona.io",) +# A deployment that overrides this list must keep x-step-up-grant. It carries +# a step-up grant on requests with no body. +CORS_ALLOW_HEADERS = (*default_headers, "x-step-up-grant") CORS_URLS_ALLOW_ALL_REGEX = (r"^/api/v1/osm/.*$",) USE_THOUSAND_SEPARATOR = True diff --git a/requirements/base.in b/requirements/base.in index 15f68452e5..9fc7798167 100644 --- a/requirements/base.in +++ b/requirements/base.in @@ -28,7 +28,9 @@ git+https://github.com/onaio/django-digest.git@6bf61ec08502fd3545d4f2c0838b6cb15 git+https://github.com/onaio/django-multidb-router.git@f711368180d58eef87eda54fadfd5f8355623d52#egg=django-multidb-router git+https://github.com/onaio/floip-py.git@3c980eb184069ae7c3c9136b18441978237cd41d#egg=pyfloip git+https://github.com/onaio/python-json2xlsclient.git@62b4645f7b4f2684421a13ce98da0331a9dd66a0#egg=python-json2xlsclient -git+https://github.com/onaio/ona-oidc.git@faa573b2c08d5049f68cc9648084e425164eb933#egg=ona-oidc +# Pinned at the step-up branch tip for stepup_grants, which the totp endpoints +# import. Re-pin to a main SHA once onaio/ona-oidc#139 merges. +git+https://github.com/onaio/ona-oidc.git@29544f09d8752b7060dd48203255ed6fe74e745a#egg=ona-oidc -e git+https://github.com/onaio/savreaderwriter.git@fix-pep-440-issues#egg=savreaderwriter git+https://git@github.com/onaio/valigetta.git@v0.3.1#egg=valigetta codetiming diff --git a/requirements/base.pip b/requirements/base.pip index 2157c5c055..1111b7fac6 100644 --- a/requirements/base.pip +++ b/requirements/base.pip @@ -265,7 +265,7 @@ oauthlib==4.0.1 # -r requirements/base.in # django-oauth-toolkit # requests-oauthlib -ona-oidc @ git+https://github.com/onaio/ona-oidc.git@faa573b2c08d5049f68cc9648084e425164eb933 +ona-oidc @ git+https://github.com/onaio/ona-oidc.git@29544f09d8752b7060dd48203255ed6fe74e745a # via -r requirements/base.in openpyxl==3.1.5 # via diff --git a/requirements/dev.pip b/requirements/dev.pip index 051da47241..8cfdab090c 100644 --- a/requirements/dev.pip +++ b/requirements/dev.pip @@ -331,7 +331,7 @@ oauthlib==4.0.1 # -r requirements/base.in # django-oauth-toolkit # requests-oauthlib -ona-oidc @ git+https://github.com/onaio/ona-oidc.git@faa573b2c08d5049f68cc9648084e425164eb933 +ona-oidc @ git+https://github.com/onaio/ona-oidc.git@29544f09d8752b7060dd48203255ed6fe74e745a # via -r requirements/base.in openpyxl==3.1.5 # via From 534a1c65e0593817609c663ad1c6701cd49476ce Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Mon, 30 Nov 2026 21:34:55 +0300 Subject: [PATCH 002/120] docs: explain how a client handles a step-up challenge --- docs/authentication.rst | 4 + docs/dataviews.rst | 6 + docs/forms.rst | 4 + docs/merged-datasets.rst | 2 + docs/metadata.rst | 5 + docs/orgs.rst | 10 + docs/profiles.rst | 8 + docs/projects.rst | 19 ++ docs/restservices.rst | 12 + docs/teams.rst | 4 + docs/two_factor.rst | 643 ++++++++++++++++++++++----------------- docs/user.rst | 1 + 12 files changed, 445 insertions(+), 273 deletions(-) diff --git a/docs/authentication.rst b/docs/authentication.rst index d37dbfe4b3..7e1ca11f18 100644 --- a/docs/authentication.rst +++ b/docs/authentication.rst @@ -74,6 +74,8 @@ confidential client using this flow must use Proof Key for Code Exchange 1. Register your client application with Ona - `register`_ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + - ``name`` - name of your application - ``client_type`` - select public or confidential as appropriate - ``authorization_grant_type`` - select Authorization code @@ -111,6 +113,8 @@ Do not reuse this example pair in an application. 3. Authorize the client application ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + Direct the user's browser to the authorization endpoint with the derived challenge and the challenge method set to exactly ``S256``: diff --git a/docs/dataviews.rst b/docs/dataviews.rst index f8cc1abe4c..d16ea693b3 100644 --- a/docs/dataviews.rst +++ b/docs/dataviews.rst @@ -59,6 +59,8 @@ different projects.
 	POST /api/v1/dataviews
+A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + Example ------- :: @@ -205,6 +207,8 @@ project.
 	PUT /api/v1/dataviews/{pk}
+A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + Example ------- :: @@ -249,6 +253,8 @@ Patch a DataView
 	PATCH /api/v1/dataviews/{pk}
+A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + Example ------- :: diff --git a/docs/forms.rst b/docs/forms.rst index f9b2fddf50..3b221a3170 100644 --- a/docs/forms.rst +++ b/docs/forms.rst @@ -233,6 +233,8 @@ Response Set Form Information -------------------- +A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + You can use ``PUT`` or ``PATCH`` http methods to update or set form data elements. If you are using ``PUT``, you have to provide the `uuid, description, downloadable, owner, public, public_data, title` fields. With ``PATCH`` you only need to provide at least one of the fields. @@ -1189,6 +1191,8 @@ You can share a form with a specific username or a list of usernames using `POST
     POST /api/v1/forms/{pk}/share
+A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + Example ^^^^^^^ :: diff --git a/docs/merged-datasets.rst b/docs/merged-datasets.rst index 838630206b..a760a73422 100644 --- a/docs/merged-datasets.rst +++ b/docs/merged-datasets.rst @@ -36,6 +36,8 @@ Create a new Merged Dataset
     POST /api/v1/merged-datasets
+A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + Permissions ----------- diff --git a/docs/metadata.rst b/docs/metadata.rst index 867979e645..fce9136e73 100644 --- a/docs/metadata.rst +++ b/docs/metadata.rst @@ -133,6 +133,8 @@ Add metadata or media file to a form
POST /api/v1/metadata
+A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + *Payload* :: @@ -247,6 +249,9 @@ Link XForm as a GeoJSON media attachment example: Create XForm meta permissions ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + Set meta permissions for a specific form by passing two roles that are pipe delimited. First role indicates editor default role, the second is the dataentry default role and the last is the readonly default role. diff --git a/docs/orgs.rst b/docs/orgs.rst index 40b911c24d..f008ee73bb 100644 --- a/docs/orgs.rst +++ b/docs/orgs.rst @@ -283,6 +283,8 @@ metadata to ``{"computer": "mac"}``.
PATCH /api/v1/orgs/{username}
+A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + Example ^^^^^^^ @@ -394,6 +396,8 @@ A member is added with ``POST``. The role of a member is changed, or the member PATCH /api/v2/orgs/{username}/members +A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + Example ^^^^^^^ @@ -433,6 +437,8 @@ the role of the user.\ ``{"username": "member1", "role": "editor"}``
POST /api/v1/orgs/{username}/members
+A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + Example ^^^^^^^ @@ -483,6 +489,8 @@ role ``{"username": "member1", "role": "owner|manager|editor|dataentry|readonly"
PUT /api/v1/orgs/{username}/members
+A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + Example ^^^^^^^ @@ -528,6 +536,8 @@ Rotate a KMS key manually
POST /api/v1/orgs/{username}/rotate-key
+A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + Example ^^^^^^^ diff --git a/docs/profiles.rst b/docs/profiles.rst index c85174313f..02cb6494db 100644 --- a/docs/profiles.rst +++ b/docs/profiles.rst @@ -132,6 +132,8 @@ JSON, for example, ``{"country": "KE"}`` will set the country to ``KE``.
PATCH /api/v1/profiles/{username}
+A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + Example ^^^^^^^ @@ -166,6 +168,8 @@ Response Partial update for email requires password confirmation ------------------------------------------------------- +A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + Example ^^^^^^^ @@ -188,6 +192,8 @@ update ``b`` with value ``Beeh``, we would use this endpoing and add an
PATCH /api/v1/profiles/{username}
+A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + Example ^^^^^^^ @@ -221,6 +227,8 @@ Response Change authenticated user’s password ------------------------------------ +A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + Example ^^^^^^^ diff --git a/docs/projects.rst b/docs/projects.rst index baf3fa626d..69d481235a 100644 --- a/docs/projects.rst +++ b/docs/projects.rst @@ -407,6 +407,10 @@ Update Project Information
 	PUT /api/v1/projects/{pk} or PATCH /api/v1/projects/{pk}
+.. note:: + + A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + Example ^^^^^^^^ :: @@ -459,6 +463,10 @@ You can share a project with a user or multiple users by ``PUT`` a payload with PUT /api/v1/projects/{pk}/share +.. note:: + + A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + Example 1: Sharing with a specific user ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ :: @@ -535,6 +543,10 @@ To [re]assign an existing form to a project you need to ``POST`` a payload of ``
POST /api/v1/projects/{pk}/forms
+.. note:: + + A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + Example ^^^^^^^^ :: @@ -856,6 +868,10 @@ create an account.
POST /api/v1/projects/{pk}/invitations
+.. note:: + + A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + Example ^^^^^^^ @@ -918,6 +934,9 @@ Update a project invitation PUT /api/v1/projects/{pk}/invitations +.. note:: + + A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. Example ^^^^^^^ diff --git a/docs/restservices.rst b/docs/restservices.rst index 9ea9d9360e..11dff9c4f5 100644 --- a/docs/restservices.rst +++ b/docs/restservices.rst @@ -105,6 +105,10 @@ Add a Rest Service to a form
POST /api/v1/restservices
+.. note:: + + A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + *Payload* :: @@ -156,6 +160,10 @@ Adding TextIt
POST /api/v1/restservices
+.. note:: + + A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + *Payload* :: @@ -198,6 +206,10 @@ Adding Google Sheet Sync
POST /api/v1/restservices
+.. note:: + + A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + *Payload* :: diff --git a/docs/teams.rst b/docs/teams.rst index 532568024b..c36085bc1e 100644 --- a/docs/teams.rst +++ b/docs/teams.rst @@ -164,6 +164,8 @@ organization. No other team grants those permissions, regardless of its name. POST /api/v1/teams/{pk}/members +A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + Response ^^^^^^^^ @@ -185,6 +187,8 @@ project; other callers receive ``403 FORBIDDEN`` and no permissions change. POST /api/v1/teams/{pk}/share +A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + Example ^^^^^^^ diff --git a/docs/two_factor.rst b/docs/two_factor.rst index d0f089c6cc..727e87d1b7 100644 --- a/docs/two_factor.rst +++ b/docs/two_factor.rst @@ -1,16 +1,115 @@ -Two-Factor Authentication +Two-factor authentication ************************* -Where a deployment enables it, an account can protect sign-in with a second -factor: an authenticator app (TOTP), backed by single-use recovery codes. -Every endpoint below acts on the authenticated caller and nobody else -- none -accepts a username, so none can be pointed at another user's second factor. +A deployment can let an account protect its sign-in with a second factor. The +second factor is an authenticator app (TOTP). Single-use recovery codes +replace the app if the user loses it. -All endpoints live under ``/api/v1/totp`` and answer **404** on deployments -that have not enabled two-factor (``ENABLE_TWO_FACTOR``). On deployments where -an identity provider owns the second factor instead of Ona, the management -endpoints refuse with **409** and ``"error": "not_managed_here"`` -- check -``status`` before offering any of these controls. +Each endpoint on this page acts on the authenticated caller only. No endpoint +accepts a username. Thus, no caller can change the second factor of another +user. + +All endpoints are under ``/api/v1/totp``. If a deployment does not enable +two-factor (``ENABLE_TWO_FACTOR``), they answer **404**. On some deployments, +an identity provider owns the second factor, not Ona. There, the management +endpoints answer **409** with ``"error": "not_managed_here"``. Read the +``status`` answer before you show any of these controls. + +.. _handle-step-up-challenge: + +Handle a step-up challenge +-------------------------- + +A deployment can gate a sensitive action. A gated action needs a step-up +grant. A grant is a single-use token that proves a fresh second factor for one +action. The table in `Step-up for account actions`_ shows the actions that a +deployment can gate. + +To do an action that a deployment can gate, do these steps: + +1. Send the request with no grant. If the deployment does not gate the + action, the request succeeds. +2. If the answer is **401** with ``"error": "step_up_required"``, read + ``audience`` and ``dialect`` from the body. ``audience`` names the action + that the grant must unlock. +3. Get a grant for that ``audience``. The ``dialect`` tells you how. + + - ``local-totp``. Send a current ``code`` and the ``audience`` to + ``POST /api/v1/totp/verify``. The answer contains the grant. + - ``oidc``. Send the user to the ``authorizationUrl`` in the body. The + identity provider proves the factor and returns the grant through + ``/api/v1/stepup/callback``. A browser must open this popup from the + click of the user, because browsers block a popup from a later response. + To get the URL before the gated request, call + ``GET /api/v1/stepup/start?audience=...``. + +4. Send the same request again with the grant. Put the grant in a ``grant`` + field in the body. If the request has no body, put the grant in the + ``X-Step-Up-Grant`` header. + +Do not put the grant in the query string. The server does not read a grant +from the query string. A grant that is not valid gets the same **401**. + +The request that presents a grant spends it. A spent grant also covers a +second gate on the same action in the same request. A new team or +organisation member is a special case. If both ``grant-org-admin`` and +``share-team-admin`` gate the change, one grant for the first gated audience +covers it. + +This example changes the email address in local mode. An email change also +needs the current ``password``. First, send the change with no grant:: + + curl -X PATCH https://api.ona.io/api/v1/profiles/demo -H "Authorization: Token TOKEN_KEY" -H "Content-Type: application/json" -d '{"email": "new@example.com", "password": "PASSWORD"}' + +Response (**401**):: + + {"error": "step_up_required", "audience": "change-email", "dialect": "local-totp"} + +Prove a code for that ``audience``:: + + curl -X POST https://api.ona.io/api/v1/totp/verify -d "code=123456" -d "audience=change-email" -H "Authorization: Token TOKEN_KEY" + +Response (**200**):: + + {"verified": true, "grant": "..."} + +Send the same change again, with the grant in the body:: + + curl -X PATCH https://api.ona.io/api/v1/profiles/demo -H "Authorization: Token TOKEN_KEY" -H "Content-Type: application/json" -d '{"email": "new@example.com", "password": "PASSWORD", "grant": "..."}' + +The answer is **200** with the updated profile. + +No route shows which actions a deployment gates. Each deployment selects them +in ``STEP_UP["ACTIONS"]``. ``GET /api/v1/user/capabilities`` does not report +them. Thus, a client must handle this **401** on each write that a deployment +can gate. + +A gated request can also get these answers: + +- **403** with ``"error": "enrol_required"``. The user has no second factor, + and the deployment does not let such users through. Tell the user to enrol + an authenticator. +- **503** with ``"error": "step_up_unavailable"``. The deployment is in + federated mode, but no provider is configured, or the provider has no + endpoints. ``GET /api/v1/stepup/start`` gives the same answer. +- **400** with ``"error": "one_gated_change_per_request"`` and an + ``audiences`` list. The request makes more than one gated change, and one + grant cannot cover two gates. Change the values one at a time. The server + refuses the request before it spends the grant. +- **400** for a request that is not valid. The server validates the request + before it spends the grant, so the grant stays valid. Correct the request + and send it again with the same grant. +- **403** from a server-rendered page. These pages cannot run a challenge, so + they refuse a gated change that has no grant. If ``authorize-oauth-app`` is + gated, the OAuth pages refuse each user that the gate challenges. These are + the pages: + + - the settings page at ``/{username}/settings`` + - the password page at ``/accounts/password/change/`` + - the form pages at ``/{username}/forms/{id_string}/edit``, + ``/{username}/forms/{id_string}/perms`` and + ``/{username}/forms/{id_string}/addservice`` + - the OAuth pages at ``/o/authorize/`` and ``/o/applications/`` Status ------ @@ -19,8 +118,8 @@ Status
GET /api/v1/totp/status
-Reports the account's second factor and recovery-code state, and which -controls this deployment can honour. +Returns the state of the second factor and the recovery codes of the account. +It also shows which controls this deployment supports. :: @@ -42,25 +141,25 @@ Response:: "recoveryCodes": {"generated": true, "remaining": 8} } -``managedBy`` is ``"idp"`` and every capability ``false`` where an identity -provider owns the factor; a client should not offer controls reported -unavailable -- the server refuses them regardless. +If an identity provider owns the factor, ``managedBy`` is ``"idp"`` and each +capability is ``false``. Do not show a control that the answer reports as not +available. The server refuses it in all cases. -Enrolling an authenticator --------------------------- +Enrol an authenticator +---------------------- -Enrolment is a two-step handshake: start it to receive the secret, then -confirm it by echoing a code from the app, which proves the secret was -captured correctly. Both steps demand a signed-in session -- an API key is -refused, so a leaked key cannot change how its owner signs in. +Enrolment has two steps. First, start it to get the secret. Then, confirm it +with a code from the app. The code proves that the app stored the secret +correctly. Both steps need a signed-in session. The server refuses an API key, +so a leaked key cannot change how its owner signs in. .. raw:: html
POST /api/v1/totp/enroll/start
-A first enrolment must carry the account's password. Replacing an existing -authenticator instead demands a current ``code`` (or a ``grant`` from -``verify``), the same proof disabling requires. +A first enrolment needs the account password. To replace a current +authenticator, send a current ``code`` or a ``grant`` from ``verify``. +``disable`` needs the same proof. :: @@ -74,17 +173,18 @@ Response (**201**):: "secretBase32": "JBSWY3DPEHPK3PXP" } -One secret in three renderings: a QR image to scan, the provisioning URI, and -the base32 secret to type by hand. Starting again replaces the pending -attempt. A wrong password answers **403** with ``"reason": -"password_required"``; an account with no usable password is refused with -``"reason": "no_password_set"``. Password guesses here spend the login form's -lockout allowance -- this endpoint is not a separate brute-force budget. -The current password asked for by an email change on -``/api/v1/profiles/{username}`` and by ``/accounts/password/change/`` spends -the same allowance, so repeated mistakes there also lock the login form for -``LOCKOUT_TIME``. ``POST /api/v1/profiles/{username}/change_password`` keeps -its own counter. +The answer gives one secret in three forms. They are a QR image to scan, the +``otpauth://`` URI, and the base32 secret to type by hand. A new start replaces +the enrolment that is not confirmed. A wrong password gets **403** with +``"reason": "password_required"``. If the account has no usable password, the +answer is ``"reason": "no_password_set"``. + +Password guesses here spend the lockout allowance of the login form. This +endpoint does not have a separate limit for guesses. Two other routes ask for +the current password and spend the same allowance. They are an email change +on ``/api/v1/profiles/{username}`` and ``/accounts/password/change/``. Thus, +repeated mistakes there also lock the login form for ``LOCKOUT_TIME``. +``POST /api/v1/profiles/{username}/change_password`` keeps its own counter. .. raw:: html @@ -101,36 +201,36 @@ Response (**200**):: "codes": ["mfrggzdfmztwq2lk", "..."] } -Confirming activates the authenticator and returns ten fresh recovery codes. -Answers **409** when there is no pending enrolment to confirm, and **403** -when the code is wrong. +The confirmation activates the authenticator and returns ten new recovery +codes. If no enrolment waits for confirmation, the answer is **409**. If the +code is wrong, the answer is **403**. Recovery codes -------------- -Each code signs the user in once when the authenticator is lost. The set is -replaced wholesale, never appended to, so the remaining count reported by -``status`` stays honest. +Each code signs the user in one time if the user loses the authenticator. A +new set replaces the full set. The server never adds codes to a set. Thus, the +count of unspent codes that ``status`` reports stays correct. .. raw:: html
POST /api/v1/totp/recovery/generate
-Replaces the set and returns the new codes (**201**). The previous codes stop -working. Demands a current ``code`` or ``grant``. +This route replaces the set and returns the new codes (**201**). The old codes +become invalid. The route needs a current ``code`` or ``grant``. .. raw:: html
POST /api/v1/totp/recovery
-Returns the codes that have not been spent yet (**200**), for a user who has -lost their printout without invalidating a set that is still good. Demands a -current ``code`` or ``grant``; answers **404** when no set has been -generated. POST rather than GET so the proof travels in the body, never in a -URL or an access log. +This route returns the codes that are not spent (**200**). Use it if a user +lost the printout. It does not cancel a set that is still good. The route +needs a current ``code`` or ``grant``. If the user did not generate a set, the +answer is **404**. The route uses POST, not GET, so the proof is in the body. +The proof never goes into a URL or an access log. -Disabling ---------- +Disable two-factor +------------------ .. raw:: html @@ -144,10 +244,10 @@ Response (**200**):: {"enrolled": false} -Removes every device the login view could challenge on. Demands a current -``code`` -- a recovery code counts, so a lost authenticator can still be -turned off -- or a ``grant``. Idempotent: an account with no second factor -answers the same way. +This route removes each device that the login view can challenge. It needs a +current ``code`` or a ``grant``. A recovery code counts as a ``code``, so a +user who lost the authenticator can still turn it off. The route is +idempotent. An account with no second factor gets the same answer. Step-up verification -------------------- @@ -156,9 +256,9 @@ Step-up verification
POST /api/v1/totp/verify
-Checks a code without changing anything, and mints a short-lived grant for -one named operation -- for clients that verify first and act second, since a -TOTP code is spent the moment it is checked. +This route checks a code and changes nothing. It returns a short-lived grant +for one named operation. Thus, a client can verify first and act second. This +is necessary because the server spends a TOTP code when it checks the code. :: @@ -168,161 +268,155 @@ Response (**200**):: {"verified": true, "grant": "..."} -``audience`` names the operation the grant unlocks and must be one the -deployment recognises: an operation above, an action ``STEP_UP`` can gate, -or one listed in ``TWO_FACTOR_STEP_UP_AUDIENCES``. Unknown values answer -**400**. The grant is single-use, expires after -``STEP_UP_GRANT_TTL`` seconds (default 300), and is honoured only by the -operation it was minted for. ``method`` optionally pins which factor the code -must prove -- ``totp`` or ``recovery`` -- and defaults to accepting either. +``audience`` names the operation that the grant unlocks. The deployment must +know the audience. It knows the operations above (``enroll-start``, +``disable``, ``recovery-generate`` and ``recovery-view``). It also knows each +action that ``STEP_UP`` can gate, and each audience in +``TWO_FACTOR_STEP_UP_AUDIENCES``. An unknown value gets **400**. + +The grant is single-use. It expires after ``STEP_UP_GRANT_TTL`` seconds +(default 300). Only the operation that the grant is for accepts it. +``method`` is optional. It sets the factor that the code must prove, ``totp`` +or ``recovery``. If you omit ``method``, the code can prove either factor. An +unknown ``method`` gets **400**. Step-up for account actions --------------------------- -A deployment can demand a fresh second factor for sensitive account actions -too. Each is opted into by its audience in ``STEP_UP["ACTIONS"]``; none is -gated by default. - -========================== ==================================================== -Audience Action -========================== ==================================================== -``regenerate-api-key`` ``GET /api/v1/user/regenerate_auth_token`` -``regenerate-odk-token`` ``POST /api/v1/user/odk_token`` -``change-password`` ``POST /api/v1/profiles/{username}/change_password`` -``change-email`` changing ``email`` on ``/api/v1/profiles/{username}`` -``require-auth-toggle`` changing ``require_auth`` on the same route, or on - ``/api/v1/orgs/{org}`` -``privacy-consent`` changing the consent record in profile ``metadata`` -``grant-org-admin`` making someone an owner or manager on - ``/api/v1/orgs/{org}/members`` or ``/api/v2/orgs/{org}/members``, - or adding them to the organisation's Owners team -``rotate-org-key`` ``POST /api/v1/orgs/{org}/rotate-key`` -``change-username`` changing ``username`` on ``/api/v1/profiles/{username}`` -``change-webhook`` adding a webhook on ``/api/v1/restservices``, or changing - where one sends; changing a form's ``textit`` settings - on ``/api/v1/metadata`` -``share-form-admin`` sharing a form with the owner or manager role through - ``/api/v1/forms/{pk}/share``; writing a form's - ``xform_meta_perms`` on ``/api/v1/metadata`` so a slot - newly names owner or manager, or so applying it makes - a current user one; moving a form through - ``/api/v1/projects/{pk}/forms`` where its meta - permissions make the project's users owners or - managers of it, unless ``transfer-project`` covers - the move -``share-project-admin`` sharing a project with the owner or manager role - through ``/api/v1/projects/{pk}/share`` -``invite-project-admin`` inviting someone to a project as owner or manager - through ``/api/v1/projects/{pk}/invitations`` -``share-team-admin`` sharing a project with a team as owner or manager - through ``/api/v1/teams/{pk}/share``, or any team share - whose re-applied meta permissions make someone one; - adding a user to a team that owns or manages a project - or form, directly or through a form's meta - permissions, through ``/api/v1/teams/{pk}/members``; - adding or re-adding a member on - ``/api/v1/orgs/{org}/members`` or - ``/api/v2/orgs/{org}/members`` where the projects - shared with them make them an owner or manager -``publish-data`` making a form's or project's data public; moving a - private form into a public project; turning on a - form's ``public_link`` on ``/api/v1/metadata``; - creating a dataview in a public project, or changing - the project, columns or query of one there, over a - form whose data is not public; creating a merged - dataset in a public project from such forms -``transfer-project`` moving a project to another account by changing its - ``owner``; moving a form into another account's - project through ``/api/v1/projects/{pk}/forms``, or - by changing its ``owner`` or ``project`` on - ``/api/v1/forms/{pk}``; creating a merged dataset in - another account's project from a form -``authorize-oauth-app`` approving an OAuth application at ``/o/authorize/``, - or registering one under ``/o/applications/`` -``form-require-auth`` turning off ``require_auth`` on ``/api/v1/forms/{pk}`` -``disable-form-encryption`` turning off a form's encryption with - ``enable_kms_encryption`` -========================== ==================================================== - -A form's meta permissions can turn an editor, data-entry or read-only share -into an owner or manager one. The ``share-*`` and ``invite-*`` gates count the -role a share ends up granting, so an editor share on such a form is gated like -an owner share. - -The token gates protect replacing a token, which breaks every integration -that holds the old one. They do not hide the current tokens: a signed-in -session can still read the API token from ``GET /api/v1/user`` and the ODK -token from ``GET /api/v1/user/odk_token``. - -Gate ``grant-org-admin`` alongside the organisation gates. Without it, a -stolen owner session can appoint the attacker's own account as an owner, and -that account then passes every gate with its own factor. For the same -reason, gate the four ``share-*`` and ``invite-*`` audiences together, and -``transfer-project``. - -The profile gates fire only when a value actually changes, so writing back an -unchanged profile is not challenged. The settings page at -``/{username}/settings`` and the password page at -``/accounts/password/change/`` write the same values; they cannot run a -challenge, so they refuse a gated change with **403**. So do the OAuth pages -at ``/o/authorize/`` and ``/o/applications/``: with ``authorize-oauth-app`` -gated, every user the gate challenges is refused when approving or -registering an application. - -A gated request without a grant answers **401**:: - - {"error": "step_up_required", "audience": "change-email", "dialect": "local-totp"} - -The caller earns a grant for ``audience`` and repeats the request with it: as a -``grant`` field in the body or, for a request with no body, in the -``X-Step-Up-Grant`` header -- never in the query string. Each grant is spent by -the request that presents it, so a single request changing two gated values is -refused; change them one at a time. Adding a team or organisation member is -the exception: when it is gated by both ``grant-org-admin`` and -``share-team-admin``, one grant for the first gated audience covers it. A -grant also covers the same action gated again within the request that spent -it. A request is validated before its grant is spent, so one that would be -rejected anyway answers **400** and keeps the grant. - -``STEP_UP["MODE"]`` decides where the factor is proved: - -- ``local`` (default) -- Ona owns the factor. The challenge's ``dialect`` is - ``local-totp``: prove a code at ``POST /api/v1/totp/verify`` with - ``audience`` set, and present the grant it returns. -- ``federated`` -- an identity provider owns the factor. The ``dialect`` is - ``oidc`` and the challenge carries an ``authorizationUrl`` to send the user - to. ``GET /api/v1/stepup/start?audience=...`` returns the same URL before the - gated request is made, for a browser that must open it from a click. The - provider returns to ``/api/v1/stepup/callback``, which checks the token - against the ``STEP_UP`` block of the provider's entry in - ``OPENID_CONNECT_AUTH_SERVERS`` (see ona-oidc). That block's - ``REDIRECT_URI`` must point at this callback. A browser landing there gets - a page that posts ``{"type": "oidc-step-up", "verified": true, "grant": - "..."}`` to its opener at ``STEP_UP_POPUP_ORIGIN``; any other caller gets - ``{"grant": "..."}``, or **403** ``step_up_failed`` with a ``reason``. When - no provider is configured, or it lacks its endpoints, a gated request and - ``start`` both answer **503** with ``"error": "step_up_unavailable"``. +A deployment can also require a fresh second factor for sensitive account +actions. To gate an action, add its audience to ``STEP_UP["ACTIONS"]``. By +default, no action is gated. `Handle a step-up challenge`_ tells how a client +gets a grant and sends it. + +============================= ==================================================== +Audience Action +============================= ==================================================== +``regenerate-api-key`` ``GET /api/v1/user/regenerate_auth_token`` +``regenerate-odk-token`` ``POST /api/v1/user/odk_token`` +``change-password`` ``POST /api/v1/profiles/{username}/change_password`` +``change-email`` a change to ``email`` on ``/api/v1/profiles/{username}`` +``require-auth-toggle`` a change to ``require_auth`` on the same route, or on + ``/api/v1/orgs/{org}`` +``privacy-consent`` a change to the consent record in profile ``metadata`` +``grant-org-admin`` a change that makes a user an owner or manager on + ``/api/v1/orgs/{org}/members`` or ``/api/v2/orgs/{org}/members``; + a change that adds a user to the Owners team of the + organisation +``rotate-org-key`` ``POST /api/v1/orgs/{org}/rotate-key`` +``change-username`` a change to ``username`` on ``/api/v1/profiles/{username}`` +``change-webhook`` a new webhook on ``/api/v1/restservices``, or a change + to the place where a webhook sends; a change to the + ``textit`` settings of a form on ``/api/v1/metadata`` +``share-form-admin`` a share of a form with the owner or manager role + through ``/api/v1/forms/{pk}/share``; a write of the + ``xform_meta_perms`` of a form on ``/api/v1/metadata``, + if a slot newly names owner or manager, or if the + write makes a current user one; a move of a form + through ``/api/v1/projects/{pk}/forms``, if its meta + permissions make the users of the project owners or + managers of the form, unless ``transfer-project`` + covers the move +``share-project-admin`` a share of a project with the owner or manager role + through ``/api/v1/projects/{pk}/share`` +``invite-project-admin`` an invitation to a project as owner or manager + through ``/api/v1/projects/{pk}/invitations`` +``share-team-admin`` a share of a project with a team as owner or manager + through ``/api/v1/teams/{pk}/share``, or a team share + whose re-applied meta permissions make a user one; a + new member, through ``/api/v1/teams/{pk}/members``, + of a team that owns or manages a project or form, + directly or through the meta permissions of a form; + a move of a team to another organisation on + ``/api/v1/teams/{pk}``; a new or re-added member on + ``/api/v1/orgs/{org}/members`` or + ``/api/v2/orgs/{org}/members``, if the projects + shared with the member make them an owner or manager +``publish-data`` a change that makes the data of a form or project + public; a move of a private form into a public + project; ``public_link`` turned on for a form on + ``/api/v1/metadata``; a new dataview in a public + project, or a change to the project, columns or + query of a dataview there, over a form whose data + is not public; a new merged dataset in a public + project from such forms; a new link on + ``/api/v1/open-data``, or a change that reactivates + a link or points an active link at another form +``transfer-project`` a move of a project to another account by a change + to its ``owner``; a move of a form into the project + of another account through + ``/api/v1/projects/{pk}/forms``, or by a change to its + ``owner`` or ``project`` on ``/api/v1/forms/{pk}``; a + new merged dataset in the project of another account + from a form +``authorize-oauth-app`` the approval of an OAuth application at + ``/o/authorize/``; the registration of an application + under ``/o/applications/``, or a change to its + redirect URIs or client type +``form-require-auth`` ``require_auth`` turned off on ``/api/v1/forms/{pk}`` +``disable-form-encryption`` the encryption of a form turned off with + ``enable_kms_encryption`` on ``/api/v1/forms/{pk}`` +============================= ==================================================== + +The meta permissions of a form can turn an editor, data-entry or read-only +share into an owner or manager share. The ``share-*`` and ``invite-*`` gates +count the role that a share gives in the end. Thus, an editor share on such a +form gets the same gate as an owner share. + +The token gates protect the replacement of a token. A replacement breaks each +integration that holds the old token. The gates do not hide the current +tokens. A signed-in session can still read the API token from +``GET /api/v1/user``. It can also read the ODK token from +``GET /api/v1/user/odk_token``. + +Gate ``grant-org-admin`` together with the organisation gates. If you do not, +a stolen owner session can make the account of the attacker an owner. That +account then passes each gate with its own factor. For the same reason, gate +the four ``share-*`` and ``invite-*`` audiences together. Gate +``transfer-project`` with them. + +The profile gates apply only if a value changes. Thus, a write of an unchanged +profile gets no challenge. + +``STEP_UP["MODE"]`` sets where the user proves the factor: + +- ``local`` (default). Ona owns the factor. The ``dialect`` of the challenge + is ``local-totp``. +- ``federated``. An identity provider owns the factor. The ``dialect`` is + ``oidc``. The provider returns to ``/api/v1/stepup/callback``. The callback + checks the token against the ``STEP_UP`` block of the provider entry in + ``OPENID_CONNECT_AUTH_SERVERS`` (see ona-oidc). The ``REDIRECT_URI`` of + that block must point at this callback. + + If a browser opens the callback, it gets a page. The page posts + ``{"type": "oidc-step-up", "verified": true, "grant": "..."}`` to its + opener at ``STEP_UP_POPUP_ORIGIN``. Other callers get ``{"grant": "..."}``, + or **403** ``step_up_failed`` with a ``reason``. ``start`` answers **400** + with ``not_gated`` for an audience that is not gated. It answers **400** + with ``not_federated`` in local mode. The callback matches the token to the signed-in user by email. It checks - ``email_verified`` only when the provider's entry sets - ``CHECK_EMAIL_VERIFIED`` or ``REQUIRE_VERIFIED_EMAIL``, and both are off by - default. With both off, an attacker who has the user's password can sign - in at the provider as an account holding the user's address, unverified, - and pass step-up with their own factor. Turn ``CHECK_EMAIL_VERIFIED`` on - wherever users can add an address they don't own at the provider. A - refused token answers ``step_up_failed`` with reason ``email_unverified``. - -In local mode, a user with no second factor is let through by default -(``STEP_UP["NO_FACTOR_POLICY"] = "skip_gate"``); ``deny_prompt_enrol`` refuses -them with **403** and ``"error": "enrol_required"`` instead. A federated -deployment cannot see its users' factors, so it always challenges. + ``email_verified`` only if the provider entry sets + ``CHECK_EMAIL_VERIFIED`` or ``REQUIRE_VERIFIED_EMAIL``. Both are off by + default. If both are off, an attacker can use the password of the user to + sign in. At the provider, the attacker can use an account with the address + of the user. The provider does not have to verify that address. The + attacker then passes step-up with their own factor. + + If users can add an address that they do not own at the provider, turn on + ``CHECK_EMAIL_VERIFIED``. A refused token gets ``step_up_failed`` with + reason ``email_unverified``. + +In local mode, the gate lets a user with no second factor through by default +(``STEP_UP["NO_FACTOR_POLICY"] = "skip_gate"``). With ``deny_prompt_enrol``, +the gate refuses such a user with ``enrol_required``. A federated deployment +cannot see the factors of its users, so it always sends a challenge. .. raw:: html
GET /api/v1/user/capabilities
-Reports which credential controls apply on this deployment, so a client can -leave out the ones that do not:: +Returns the credential controls that apply on this deployment. A client can +then hide the controls that do not apply:: { "password": {"change": true}, @@ -336,87 +430,90 @@ leave out the ones that do not:: "identityProvider": "" } -Startup checks report a step-up configuration that cannot work as +The startup checks report a step-up configuration that will not work as intended: -- ``stepup.E001`` (error) -- ``STEP_UP`` is not a dict, or its ``ACTIONS`` - is not a list of action names. Step-up reads such a setting as gating - nothing -- ``stepup.E002`` (error) -- ``STEP_UP["ACTIONS"]`` names an action no gate - checks, in either mode. A misspelt action leaves the intended one ungated -- ``stepup.W001`` -- actions are gated, but ``skip_gate`` lets users with no - factor through -- ``stepup.W003`` -- ``STEP_UP["MODE"]`` is neither ``local`` nor - ``federated`` -- ``stepup.W004`` -- actions are gated in local mode with - ``ENABLE_TWO_FACTOR`` off, so nobody can earn a grant -- ``stepup.W005`` -- ``TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD`` is still set. - It has been removed: enrolling a first device always needs the account - password -- ``stepup.W006`` -- federated actions are gated but ``change-email`` is not. - Step-up identifies the user by email, so an ungated email change gets - around every gate -- ``stepup.W007`` -- federated step-up identifies the user by a field other - than email, such as the username, which a user can change without - step-up -- ``stepup.W008`` -- ``STEP_UP["NO_FACTOR_POLICY"]`` is neither - ``skip_gate`` nor ``deny_prompt_enrol``; it refuses users with no factor -- ``stepup.W009`` -- ``authorize-oauth-app`` is gated, but the OAuth pages - cannot run a challenge, so approvals the gate challenges are refused - -Signing in ----------- - -With a factor enrolled, the login page at ``/account/login/`` challenges for -a current code (or a recovery code) after the password step. Failed code -entries spend the same lockout allowance as failed passwords -(``MAX_LOGIN_ATTEMPTS`` within ``LOCKOUT_TIME``), so the second factor is not -a separate guessing budget. +- ``stepup.E001`` (error). ``STEP_UP`` is not a dict, or its ``ACTIONS`` is + not a list of action names. Step-up then gates nothing. +- ``stepup.E002`` (error). ``STEP_UP["ACTIONS"]`` names an action that no + gate checks, in either mode. A misspelt action leaves the intended action + ungated. +- ``stepup.W001``. Actions are gated, but ``skip_gate`` lets users with no + factor through. +- ``stepup.W003``. ``STEP_UP["MODE"]`` is not ``local`` or ``federated``. + Step-up then uses federated mode. +- ``stepup.W004``. Actions are gated in local mode, but ``ENABLE_TWO_FACTOR`` + is off. Thus, no user can get a grant. +- ``stepup.W005``. ``TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD`` is still set. + The setting is removed and has no effect. The enrolment of a first device + always needs the account password. +- ``stepup.W006``. Federated actions are gated, but ``change-email`` is not. + Step-up identifies the user by email, so an ungated email change can + defeat each gate. +- ``stepup.W007``. Federated step-up identifies the user by a field other + than email, such as the username. A user can change that field without + step-up. +- ``stepup.W008``. ``STEP_UP["NO_FACTOR_POLICY"]`` is not ``skip_gate`` or + ``deny_prompt_enrol``. Step-up then refuses users with no factor. +- ``stepup.W009``. ``authorize-oauth-app`` is gated, but the OAuth pages + cannot run a challenge. Thus, they refuse each approval that the gate + challenges. + +Sign in +------- + +If a user has a factor, the login page at ``/account/login/`` asks for a +current code or a recovery code after the password step. Failed code entries +spend the same lockout allowance as failed passwords (``MAX_LOGIN_ATTEMPTS`` +in ``LOCKOUT_TIME``). Thus, the second factor does not give a separate limit +for guesses. Security events --------------- -Second-factor changes leave a trace. These actions are written to the -security audit log: +The server records each change to the second factor. It writes these actions +to the security audit log: + +- ``two-factor-enrolled``. A user confirmed an authenticator. +- ``two-factor-disabled``. A user removed the second factor. +- ``two-factor-verification-failed``. A code check failed, on an endpoint + above or on a code step of the login page. +- ``two-factor-recovery-codes-generated``. A user replaced the recovery set. +- ``two-factor-recovery-codes-viewed``. A user read the unspent set again. -- ``two-factor-enrolled`` -- an authenticator was confirmed -- ``two-factor-disabled`` -- the second factor was removed -- ``two-factor-verification-failed`` -- a code check failed, on any endpoint - above or on the login page's code steps -- ``two-factor-recovery-codes-generated`` -- the recovery set was replaced -- ``two-factor-recovery-codes-viewed`` -- the unspent set was re-read +The server sends an email to the account owner when a user enrols an +authenticator, disables two-factor, or replaces the recovery set. The owner +gets this email, whoever made the change. -The account owner is emailed when an authenticator is enrolled, when -two-factor is disabled, and when the recovery set is replaced -- whoever made -the change, the owner finds out. Repeated failed code checks also alert the -owner: one email per window after ``TWO_FACTOR_FAILURE_ALERT_THRESHOLD`` -failures within ``TWO_FACTOR_FAILURE_ALERT_WINDOW`` seconds (defaults 10 and -1800; a threshold of 0 disables the alert). Events are recorded, material is -not: no codes, secrets or grants appear in log entries or emails. +Repeated failed code checks also alert the owner. The server sends one email +for each window after ``TWO_FACTOR_FAILURE_ALERT_THRESHOLD`` failures in +``TWO_FACTOR_FAILURE_ALERT_WINDOW`` seconds. The defaults are 10 and 1800. A +threshold of 0 disables the alert. The log entries and the emails record +events only. They never contain codes, secrets or grants. Deployment settings ------------------- -- ``ENABLE_TWO_FACTOR`` -- gates every endpoint above; default ``False`` -- ``TWO_FACTOR_STEP_UP_AUDIENCES`` -- extra operations ``verify`` may mint - a grant for, beyond every audience above; default empty -- ``STEP_UP_GRANT_TTL`` -- grant lifetime in seconds; default 300 -- ``STEP_UP`` -- ``ACTIONS``, ``MODE`` and ``NO_FACTOR_POLICY``, described - above -- ``STEP_UP_POPUP_ORIGIN`` -- the origin the federated callback page posts - the grant to; required for a browser to complete a federated step-up -- ``STEP_UP_IDP_NAME`` -- the provider name ``capabilities`` reports as - ``identityProvider`` -- ``EU_CONSENT_METADATA_PATH`` -- the keys leading to the consent record in - profile ``metadata``; default ``("eu_citizen_consent",)`` -- ``CORS_ALLOW_HEADERS`` -- includes ``x-step-up-grant`` by default; a - deployment that overrides it must keep that header for browser callers on - another origin -- ``TWO_FACTOR_FAILURE_ALERT_THRESHOLD`` / ``TWO_FACTOR_FAILURE_ALERT_WINDOW`` - -- repeated-failure alerting, described above -- ``TWO_FACTOR_REMEMBER_COOKIE_AGE`` -- how long "don't ask again on this - device" holds at login; unset it to challenge on every sign-in - -Grants live in the cache, as do the lockout and repeated-failure counters, so -the deployment must run a cache shared across workers (Redis or memcached); a -per-process cache would fragment all three and weaken them. +- ``ENABLE_TWO_FACTOR``. Turns on each endpoint above. Default ``False``. +- ``TWO_FACTOR_STEP_UP_AUDIENCES``. More operations that ``verify`` can make + a grant for, in addition to each audience above. Default empty. +- ``STEP_UP_GRANT_TTL``. The lifetime of a grant in seconds. Default 300. +- ``STEP_UP``. Holds ``ACTIONS``, ``MODE`` and ``NO_FACTOR_POLICY``, as + described above. +- ``STEP_UP_POPUP_ORIGIN``. The origin that the federated callback page + posts the grant to. A browser needs it to complete a federated step-up. +- ``STEP_UP_IDP_NAME``. The provider name that ``capabilities`` reports as + ``identityProvider``. +- ``EU_CONSENT_METADATA_PATH``. The keys that lead to the consent record in + profile ``metadata``. Default ``("eu_citizen_consent",)``. +- ``CORS_ALLOW_HEADERS``. Includes ``x-step-up-grant`` by default. If a + deployment overrides it, keep that header for browser callers on another + origin. +- ``TWO_FACTOR_FAILURE_ALERT_THRESHOLD`` / ``TWO_FACTOR_FAILURE_ALERT_WINDOW``. + The alert for repeated failures, as described above. +- ``TWO_FACTOR_REMEMBER_COOKIE_AGE``. How long "don't ask again on this + device" lasts at login. To ask for the factor at each sign-in, unset it. + +The cache holds the grants, the lockout counters and the repeated-failure +counters. Thus, the deployment must use a cache that all workers share (Redis +or memcached). A per-process cache splits all three and makes them weaker. diff --git a/docs/user.rst b/docs/user.rst index b4dac33523..6df9f9295f 100644 --- a/docs/user.rst +++ b/docs/user.rst @@ -57,6 +57,7 @@ reset invalidates the user's existing API and temporary tokens. Authenticated users can change their own password via ``POST /api/v1/profiles/{username}/change_password``. +A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. Expire temporary token ====================== From 42f7257f6ab1a795306ffa7f4cfe6b6189403c46 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Mon, 30 Nov 2026 22:07:59 +0300 Subject: [PATCH 003/120] fix: tighten step-up gate order and add the WWW-Authenticate challenge --- docs/two_factor.rst | 6 +- .../test_stepup_form_and_transfer_gates.py | 20 ++++ .../viewsets/test_stepup_sharing_gates.py | 111 ++++++++++++++++++ onadata/apps/api/viewsets/project_viewset.py | 2 + .../project_invitation_serializer.py | 36 +++--- .../libs/serializers/project_serializer.py | 10 +- onadata/libs/stepup/challenge.py | 26 +++- onadata/libs/stepup/drf.py | 12 +- onadata/libs/tests/stepup/test_challenge.py | 27 ++++- onadata/libs/tests/stepup/test_drf.py | 19 +++ 10 files changed, 246 insertions(+), 23 deletions(-) diff --git a/docs/two_factor.rst b/docs/two_factor.rst index 727e87d1b7..bac2fd6622 100644 --- a/docs/two_factor.rst +++ b/docs/two_factor.rst @@ -31,7 +31,9 @@ To do an action that a deployment can gate, do these steps: action, the request succeeds. 2. If the answer is **401** with ``"error": "step_up_required"``, read ``audience`` and ``dialect`` from the body. ``audience`` names the action - that the grant must unlock. + that the grant must unlock. The **401** also sends a ``WWW-Authenticate`` + header with the ``StepUp`` scheme. The header gives ``error``, + ``audience`` and ``dialect``, but ``authorizationUrl`` is in the body only. 3. Get a grant for that ``audience``. The ``dialect`` tells you how. - ``local-totp``. Send a current ``code`` and the ``audience`` to @@ -63,6 +65,8 @@ needs the current ``password``. First, send the change with no grant:: Response (**401**):: + WWW-Authenticate: StepUp error="step_up_required", audience="change-email", dialect="local-totp" + {"error": "step_up_required", "audience": "change-email", "dialect": "local-totp"} Prove a code for that ``audience``:: diff --git a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py index 94a0e7c95c..b14cf2f341 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py @@ -133,6 +133,26 @@ def test_a_name_taken_in_the_new_account_keeps_the_grant(self): self.assertEqual(self._owner(), self.user) self.assertFalse(OwnerRole.user_has_role(self.org_user, self.project)) + def test_a_transfer_without_permission_hides_the_names_there(self): + """A caller who cannot add projects to an account gets the permission + error, whether or not the name is taken there. The stored name differs + in case, so DRF's exact unique-together check does not answer first.""" + alice = self._user("alice") + Project.objects.create(name="SECRET", organization=alice, created_by=alice) + self.assertTrue( + Project.objects.filter(name__iexact="secret", organization=alice).exists() + ) + alice_url = f"http://testserver/api/v1/users/{alice.username}" + + response = self._patch({"owner": alice_url, "name": "Secret"}) + + self.assertEqual(response.status_code, 400, response.data) + self.assertIn("owner", response.data) + self.assertIn("You do not have permission", str(response.data["owner"])) + self.assertNotIn("name", response.data) + self.assertEqual(self._owner(), self.user) + self.assertEqual(self.project.name, "demo") + def test_a_failed_transfer_leaves_no_permissions(self): """The new owner's role is written before the transfer runs, so a failing transfer must take it back.""" diff --git a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py index 750cc4861f..3ef6706ddc 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py @@ -35,6 +35,7 @@ GATE_SHARE_PROJECT_ADMIN, ) from onadata.libs.stepup.sharing import admin_roles_granted, grants_admin_role +from onadata.libs.tests.stepup.test_challenge import FEDERATED_SERVER PROJECT_VIEWSET = "onadata.apps.api.viewsets.project_viewset" XFORM_VIEWSET = "onadata.apps.api.viewsets.xform_viewset" @@ -77,6 +78,11 @@ def assert_challenged(self, response): """Refused with a challenge naming this test case's audience.""" self.assertEqual(response.status_code, 401, response.data) self.assertEqual(response.data["audience"], self.audience) + self.assertEqual( + response["WWW-Authenticate"], + f'StepUp error="step_up_required", audience="{self.audience}", ' + 'dialect="local-totp"', + ) def assert_spent(self, grant): """The gate consumed ``grant``, so the request went through it.""" @@ -197,6 +203,36 @@ def test_the_admin_check_runs_only_where_gated(self): self.assertTrue(OwnerRole.user_has_role(self.alice, self.project)) +@override_settings( + STEP_UP={"MODE": "federated", "ACTIONS": [GATE_SHARE_PROJECT_ADMIN]}, + OPENID_CONNECT_AUTH_SERVERS=FEDERATED_SERVER, +) +class TestFederatedChallengeHeader(StepUpGateTestCase): + """A federated challenge names its audience and dialect in the header. + The authorization URL stays in the body.""" + + audience = GATE_SHARE_PROJECT_ADMIN + + def test_a_gated_request_gets_the_oidc_challenge_header(self): + self._project_create() + alice = self._user("alice") + view = ProjectViewSet.as_view({"put": "share"}) + request = self.factory.put( + "/", data={"username": "alice", "role": OwnerRole.name}, **self.extra + ) + + response = view(request, pk=self.project.pk) + + self.assertEqual(response.status_code, 401, response.data) + self.assertEqual( + response["WWW-Authenticate"], + f'StepUp error="step_up_required", audience="{self.audience}", ' + 'dialect="oidc"', + ) + self.assertIn("authorizationUrl", response.data) + self.assertFalse(OwnerRole.user_has_role(alice, self.project)) + + @gating( GATE_INVITE_PROJECT_ADMIN, PROJECT_INVITATION_URL={"*": "https://example.com/register"}, @@ -319,6 +355,81 @@ def test_an_invalid_invitation_keeps_the_grant(self, _send): self.assertTrue(spend_grant(self.user.pk, self.audience, grant)) self.assertFalse(self.project.invitations.exists()) + def _assert_refused_before_the_gate(self, send, message): + """``send(headers)`` gets the same 400 without a grant, where the + gate would answer 401, and with one, which it leaves unspent.""" + response = send({}) + self.assertEqual(response.status_code, 400, response.data) + self.assertEqual(response.data, [message]) + grant = self._grant() + + response = send(self._with_grant(grant)) + + self.assertEqual(response.status_code, 400, response.data) + self.assertEqual(response.data, [message]) + self.assertTrue(spend_grant(self.user.pk, self.audience, grant)) + + def test_a_duplicate_invitation_keeps_the_grant(self, send): + invitation = self._pending(EditorRole.name) + self.assert_challenged(self._create(OwnerRole.name, email="kim@example.com")) + + self._assert_refused_before_the_gate( + lambda headers: self._create(OwnerRole.name, headers), + "Invitation already exists.", + ) + + invitation.refresh_from_db() + self.assertEqual(invitation.role, EditorRole.name) + self.assertEqual(self.project.invitations.count(), 1) + send.assert_not_called() + + def test_inviting_an_existing_user_keeps_the_grant(self, send): + alice = self._user("alice") + self.assert_challenged(self._create(OwnerRole.name)) + + self._assert_refused_before_the_gate( + lambda headers: self._create(OwnerRole.name, headers, email=alice.email), + "User already exists", + ) + + self.assertFalse(self.project.invitations.exists()) + send.assert_not_called() + + def test_redirecting_to_an_existing_user_keeps_the_grant(self, send): + alice = self._user("alice") + invitation = self._pending(ManagerRole.name) + self.assert_challenged( + self._update(invitation, ManagerRole.name, email="kim@example.com") + ) + + self._assert_refused_before_the_gate( + lambda headers: self._update( + invitation, ManagerRole.name, headers, email=alice.email + ), + "User already exists", + ) + + invitation.refresh_from_db() + self.assertEqual(invitation.email, "jane@example.com") + send.assert_not_called() + + def test_updating_an_accepted_invitation_keeps_the_grant(self, send): + invitation = self.project.invitations.create( + email="jane@example.com", + role=EditorRole.name, + status=ProjectInvitation.Status.ACCEPTED, + ) + self.assert_challenged(self._create(OwnerRole.name, email="kim@example.com")) + + self._assert_refused_before_the_gate( + lambda headers: self._update(invitation, OwnerRole.name, headers), + "Only pending invitations can be updated", + ) + + invitation.refresh_from_db() + self.assertEqual(invitation.role, EditorRole.name) + send.assert_not_called() + def test_the_admin_check_runs_only_where_gated(self, _send): with patch( f"{PROJECT_VIEWSET}.grants_admin_role", wraps=grants_admin_role diff --git a/onadata/apps/api/viewsets/project_viewset.py b/onadata/apps/api/viewsets/project_viewset.py index 5f8de05e45..3e9377c36c 100644 --- a/onadata/apps/api/viewsets/project_viewset.py +++ b/onadata/apps/api/viewsets/project_viewset.py @@ -437,6 +437,7 @@ def invitations(self, request, *args, **kwargs): data = draft_request_data serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) + serializer.check_can_save() refusal = self._invite_admin_refusal(request, serializer.validated_data) if refusal is not None: return refusal @@ -461,6 +462,7 @@ def invitations(self, request, *args, **kwargs): data=data, ) serializer.is_valid(raise_exception=True) + serializer.check_can_save() refusal = self._invite_admin_refusal( request, serializer.validated_data, invitation ) diff --git a/onadata/libs/serializers/project_invitation_serializer.py b/onadata/libs/serializers/project_invitation_serializer.py index b63b1eecb4..6ba40740ce 100644 --- a/onadata/libs/serializers/project_invitation_serializer.py +++ b/onadata/libs/serializers/project_invitation_serializer.py @@ -75,15 +75,28 @@ def _send_project_invitation_email(self, invitation_id: str) -> None: project_activation_url = get_project_invitation_url(self.context["request"]) send_project_invitation_email_async.delay(invitation_id, project_activation_url) + def check_can_save(self): + """Refuse an invitation that cannot be saved. Call it after + ``is_valid()`` and before any step a refused request must not reach; + ``save()`` does not repeat it. + + These errors stay out of ``validate()`` so their body stays a list. + """ + email = self.validated_data["email"] + if self.instance is None: + if ProjectInvitation.objects.filter( + email=email, + project=self.validated_data["project"], + status=ProjectInvitation.Status.PENDING, + ).exists(): + raise serializers.ValidationError(_("Invitation already exists.")) + elif self.instance.status != ProjectInvitation.Status.PENDING: + raise serializers.ValidationError( + _("Only pending invitations can be updated") + ) + self._validate_email_exists(email) + def create(self, validated_data): - if ProjectInvitation.objects.filter( - email=validated_data["email"], - project=validated_data["project"], - status=ProjectInvitation.Status.PENDING, - ).exists(): - raise serializers.ValidationError(_("Invitation already exists.")) - - self._validate_email_exists(validated_data["email"]) instance = super().create(validated_data) instance.invited_by = self.context["request"].user instance.save() @@ -92,13 +105,6 @@ def create(self, validated_data): return instance def update(self, instance, validated_data): - # only a pending invitation can be updated - if instance.status != ProjectInvitation.Status.PENDING: - raise serializers.ValidationError( - _("Only pending invitations can be updated") - ) - - self._validate_email_exists(validated_data["email"]) has_email_changed = instance.email != validated_data["email"] updated_instance = super().update(instance, validated_data) diff --git a/onadata/libs/serializers/project_serializer.py b/onadata/libs/serializers/project_serializer.py index f935446c03..64b54796a0 100644 --- a/onadata/libs/serializers/project_serializer.py +++ b/onadata/libs/serializers/project_serializer.py @@ -517,7 +517,6 @@ def validate(self, attrs): {"name": _(f"Project {name} already exists.")} ) else: - self._check_name_free_in_new_owner(name, organization) organization = organization or self.instance.organization request = self.context["request"] try: @@ -535,12 +534,17 @@ def validate(self, attrs): ) } ) + self._check_name_free_in_new_owner(name, organization) return attrs def _check_name_free_in_new_owner(self, name, organization): """A transfer into an account with a project of the same name would - fail on the unique constraint after the transfer had begun.""" - if not organization or organization == self.instance.organization: + fail on the unique constraint after the transfer had begun. + + Call it only after the permission check, so the answer does not show + a caller the project names in an account it cannot add projects to. + """ + if self.instance is None or organization == self.instance.organization: return name = name or self.instance.name if Project.objects.filter( diff --git a/onadata/libs/stepup/challenge.py b/onadata/libs/stepup/challenge.py index efeb83c3ea..3955671838 100644 --- a/onadata/libs/stepup/challenge.py +++ b/onadata/libs/stepup/challenge.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -"""The 401 body telling a client how to satisfy a gate.""" +"""The 401 body and header telling a client how to satisfy a gate.""" import logging @@ -21,6 +21,9 @@ #: fault, so it is answered with a 503. STEP_UP_UNAVAILABLE = "step_up_unavailable" +#: The ``WWW-Authenticate`` scheme of a step-up challenge. +STEP_UP_SCHEME = "StepUp" + def build_challenge(action: str, user=None) -> dict: """The body a client needs to satisfy the gate on ``action``. @@ -56,3 +59,24 @@ def build_challenge(action: str, user=None) -> dict: body["authorizationUrl"] = url return body + + +def _quoted(value: str) -> str: + """``value`` as an RFC 9110 quoted-string.""" + escaped = value.replace("\\", "\\\\").replace('"', '\\"') + return f'"{escaped}"' + + +def challenge_header(challenge: dict) -> str: + """The ``WWW-Authenticate`` value for a 401 that carries ``challenge``. + + RFC 9110 section 15.5.2 requires a 401 to send at least one challenge. + The scheme is not ``Bearer``: a grant is not an OAuth access token, and a + client that reads RFC 9470's ``insufficient_user_authentication`` would + refresh its token, which never satisfies the gate. + """ + params = ", ".join( + f"{name}={_quoted(challenge[name])}" + for name in ("error", "audience", "dialect") + ) + return f"{STEP_UP_SCHEME} {params}" diff --git a/onadata/libs/stepup/drf.py b/onadata/libs/stepup/drf.py index a6898aa4c0..f1e53beaf5 100644 --- a/onadata/libs/stepup/drf.py +++ b/onadata/libs/stepup/drf.py @@ -4,7 +4,11 @@ from rest_framework import status from rest_framework.response import Response -from onadata.libs.stepup.challenge import STEP_UP_UNAVAILABLE, build_challenge +from onadata.libs.stepup.challenge import ( + STEP_UP_UNAVAILABLE, + build_challenge, + challenge_header, +) from onadata.libs.stepup.gate import ( ENROL_REQUIRED, ONE_GATED_CHANGE_PER_REQUEST, @@ -50,7 +54,11 @@ def step_up_refusal(self, request, reason, audiences): {"error": STEP_UP_UNAVAILABLE}, status=status.HTTP_503_SERVICE_UNAVAILABLE, ) - return Response(challenge, status=status.HTTP_401_UNAUTHORIZED) + return Response( + challenge, + status=status.HTTP_401_UNAUTHORIZED, + headers={"WWW-Authenticate": challenge_header(challenge)}, + ) def gated_create(self, request, refusal_for): """DRF's create with a gate between validating and writing. diff --git a/onadata/libs/tests/stepup/test_challenge.py b/onadata/libs/tests/stepup/test_challenge.py index 98d1e2c8ca..b604f63073 100644 --- a/onadata/libs/tests/stepup/test_challenge.py +++ b/onadata/libs/tests/stepup/test_challenge.py @@ -8,7 +8,7 @@ from django.core.exceptions import ImproperlyConfigured from django.test import TestCase, override_settings -from onadata.libs.stepup.challenge import build_challenge +from onadata.libs.stepup.challenge import build_challenge, challenge_header GATED = {"ACTIONS": {"require-auth-toggle"}, "MODE": "local"} @@ -41,6 +41,31 @@ def test_local_mode_asks_for_a_code(self): self.assertEqual(body["audience"], "require-auth-toggle") +class TestChallengeHeader(TestCase): + def test_values_are_quoted_strings(self): + header = challenge_header( + {"error": "step_up_required", "audience": 'a"b\\c', "dialect": "oidc"} + ) + + self.assertEqual( + header, + 'StepUp error="step_up_required", audience="a\\"b\\\\c", ' + 'dialect="oidc"', + ) + + def test_the_authorization_url_stays_out_of_the_header(self): + header = challenge_header( + { + "error": "step_up_required", + "audience": "require-auth-toggle", + "dialect": "oidc", + "authorizationUrl": "https://idp.example/auth?state=s", + } + ) + + self.assertNotIn("idp.example", header) + + @override_settings(STEP_UP=FEDERATED, OPENID_CONNECT_AUTH_SERVERS=FEDERATED_SERVER) class TestFederatedChallengeCannotBeBuilt(TestCase): """A gated request must answer even when the deployment is misconfigured. diff --git a/onadata/libs/tests/stepup/test_drf.py b/onadata/libs/tests/stepup/test_drf.py index 10952a5141..0c114b38a9 100644 --- a/onadata/libs/tests/stepup/test_drf.py +++ b/onadata/libs/tests/stepup/test_drf.py @@ -63,6 +63,11 @@ def test_an_enrolled_user_without_a_grant_is_challenged(self): self.assertIsNotNone(refusal) self.assertEqual(refusal.status_code, 401) self.assertEqual(refusal.data["error"], "step_up_required") + self.assertEqual( + refusal["WWW-Authenticate"], + 'StepUp error="step_up_required", audience="require-auth-toggle", ' + 'dialect="local-totp"', + ) @override_settings(STEP_UP=GATED) def test_a_grant_for_this_action_passes(self): @@ -108,6 +113,7 @@ def test_a_user_with_no_factor_is_refused_under_deny(self): self.assertEqual(refusal.status_code, 403) self.assertEqual(refusal.data["error"], "enrol_required") + self.assertFalse(refusal.has_header("WWW-Authenticate")) @override_settings(STEP_UP={**GATED, "NO_FACTOR_POLICY": "deny_prompt_enroll"}) def test_a_misspelt_policy_refuses_rather_than_skips(self): @@ -133,6 +139,18 @@ def test_a_user_with_no_local_device_is_still_challenged(self): self.assertEqual(refusal.data["dialect"], "oidc") self.assertIn("authorizationUrl", refusal.data) + def test_the_challenge_header_names_the_audience_and_dialect(self): + """The authorization URL stays in the body only.""" + refusal = self.view.check_step_up(self._request(), "require-auth-toggle") + + self.assertEqual(refusal.status_code, 401) + self.assertEqual( + refusal["WWW-Authenticate"], + 'StepUp error="step_up_required", audience="require-auth-toggle", ' + 'dialect="oidc"', + ) + self.assertIn("authorizationUrl", refusal.data) + def test_a_valid_grant_still_lets_the_action_through(self): """The gate still honours a valid grant in federated mode.""" grant = issue_grant(self.user.pk, "require-auth-toggle") @@ -155,6 +173,7 @@ def test_a_gate_that_cannot_build_a_challenge_answers_503(self): self.assertIsNotNone(refusal) self.assertEqual(refusal.status_code, 503) self.assertEqual(refusal.data, {"error": "step_up_unavailable"}) + self.assertFalse(refusal.has_header("WWW-Authenticate")) @override_settings(STEP_UP=GATED) From 53a3a70b7a4346b22df3d20718d9904ee51d2ebf Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Tue, 1 Dec 2026 09:44:19 +0300 Subject: [PATCH 004/120] docs: drop a note about the old design and spell enrol one way --- onadata/apps/api/viewsets/totp_viewset.py | 2 +- onadata/libs/stepup/drf.py | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/onadata/apps/api/viewsets/totp_viewset.py b/onadata/apps/api/viewsets/totp_viewset.py index 83c727e71c..442c0bd355 100644 --- a/onadata/apps/api/viewsets/totp_viewset.py +++ b/onadata/apps/api/viewsets/totp_viewset.py @@ -284,7 +284,7 @@ def _enrollment_payload(device) -> dict[str, str]: class TOTPViewSet(ViewSet): - """Enroll, disable and verify the authenticator for the calling user.""" + """Enrol, disable and verify the authenticator for the calling user.""" # Three credentials: an API token and two cookie-borne ones (the Django # session and the ambient SSO cookie/header). SSOHeaderAuthentication runs diff --git a/onadata/libs/stepup/drf.py b/onadata/libs/stepup/drf.py index f1e53beaf5..86c17b849b 100644 --- a/onadata/libs/stepup/drf.py +++ b/onadata/libs/stepup/drf.py @@ -20,8 +20,7 @@ class RequiresStepUp: """Refuse a gated action unless the request carries a single-use grant. - The server decides which actions are gated. A caller could skip a gate that - a client enforced by calling the API directly. + The server decides which actions are gated. """ def check_step_up(self, request, action: str): From 2b4c2f85aacf57a306cb4bbb321dbe8a5019f6a2 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Tue, 1 Dec 2026 11:36:58 +0300 Subject: [PATCH 005/120] fix: gate automatic OAuth approval on HEAD as on GET --- .../apps/main/tests/test_stepup_oauth_gate.py | 18 ++++++++++++++++++ onadata/apps/main/views.py | 6 +++--- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/onadata/apps/main/tests/test_stepup_oauth_gate.py b/onadata/apps/main/tests/test_stepup_oauth_gate.py index bc6ee72a74..16ad75e920 100644 --- a/onadata/apps/main/tests/test_stepup_oauth_gate.py +++ b/onadata/apps/main/tests/test_stepup_oauth_gate.py @@ -178,6 +178,16 @@ def test_skip_authorization_falls_back_to_the_consent_form(self): self.assertContains(response, 'name="allow"') self.assertFalse(self._codes(application).exists()) + def test_a_head_request_does_not_approve_automatically(self): + """Django sends HEAD to the GET handler.""" + application = self._application(skip_authorization=True) + self.assertTrue(application.skip_authorization) + + response = self.client.head(AUTHORIZE_URL, self._authorization(application)) + + self.assertEqual(response.status_code, 200) + self.assertFalse(self._codes(application).exists()) + def test_a_matching_token_falls_back_to_the_consent_form(self): application = self._application() AccessToken.objects.create( @@ -320,6 +330,14 @@ def test_skip_authorization_still_approves_on_get(self): self.assertEqual(response.status_code, 302) self.assertIn("code", _query(response)) + def test_skip_authorization_still_approves_on_head(self): + application = self._application(skip_authorization=True) + + response = self.client.head(AUTHORIZE_URL, self._authorization(application)) + + self.assertEqual(response.status_code, 302) + self.assertTrue(self._codes(application).exists()) + def test_registering_needs_no_grant(self): response = self.client.post(REGISTER_URL, self._registration()) diff --git a/onadata/apps/main/views.py b/onadata/apps/main/views.py index e495fd51e6..de51260b55 100644 --- a/onadata/apps/main/views.py +++ b/onadata/apps/main/views.py @@ -1893,8 +1893,8 @@ def get_context_data(self, **kwargs): return context def get(self, request, *args, **kwargs): - """Show the consent form where the toolkit would approve on GET - without a grant, through ``skip_authorization`` or + """Show the consent form where the toolkit would approve on GET or + HEAD without a grant, through ``skip_authorization`` or ``approval_prompt=auto``.""" try: return super().get(request, *args, **kwargs) @@ -1911,7 +1911,7 @@ def form_valid(self, form): def create_authorization_response(self, request, scopes, credentials, allow): if ( allow - and request.method == "GET" + and request.method in ("GET", "HEAD") and refusal_reason(request, GATE_AUTHORIZE_OAUTH_APP) is not None ): raise _AutoApprovalNeedsStepUp From 45aa45e91765d8e8960ff56eee4e97cbb27c2d21 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Tue, 1 Dec 2026 11:37:05 +0300 Subject: [PATCH 006/120] fix: run the project transfer only when the owner changes --- .../test_stepup_form_and_transfer_gates.py | 20 ++++++++++++++++++- .../libs/serializers/project_serializer.py | 2 +- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py index b14cf2f341..510c875e91 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py @@ -17,12 +17,14 @@ StepUpGateTestCase, gating, ) +from onadata.apps.api.tools import add_user_to_organization from onadata.apps.api.viewsets.open_data_viewset import OpenDataViewSet from onadata.apps.api.viewsets.project_viewset import ProjectViewSet from onadata.apps.api.viewsets.xform_viewset import XFormViewSet from onadata.apps.logger.models import OpenData, Project, XForm from onadata.apps.logger.models.open_data import get_or_create_opendata -from onadata.libs.permissions import OwnerRole +from onadata.libs.models.share_project import ShareProject +from onadata.libs.permissions import EditorRole, OwnerRole from onadata.libs.stepup.policy import ( GATE_DISABLE_FORM_ENCRYPTION, GATE_FORM_REQUIRE_AUTH, @@ -116,6 +118,22 @@ def test_keeping_the_owner_is_not_challenged(self): self.assertEqual(self._owner(), self.user) self.assertEqual(self.project.name, "renamed") + def test_keeping_an_organisation_owner_leaves_member_roles(self): + """Only a transfer resets the roles of the organisation members.""" + self._project_create({"name": "org project", "owner": self.org_url}) + self.assertEqual(self.project.organization, self.org_user) + alice = self._user("alice") + add_user_to_organization(self.organization, alice) + ShareProject(self.project, "alice", EditorRole.name).save() + self.assertTrue(EditorRole.user_has_role(alice, self.project)) + + response = self._patch({"owner": self.org_url, "name": "renamed"}) + + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(self._owner(), self.org_user) + self.assertEqual(self.project.name, "renamed") + self.assertTrue(EditorRole.user_has_role(alice, self.project)) + def test_a_name_taken_in_the_new_account_keeps_the_grant(self): """The clash is found before the gate, so nothing is spent and the new account gets no role on the project.""" diff --git a/onadata/libs/serializers/project_serializer.py b/onadata/libs/serializers/project_serializer.py index 64b54796a0..2eb6f6b069 100644 --- a/onadata/libs/serializers/project_serializer.py +++ b/onadata/libs/serializers/project_serializer.py @@ -592,7 +592,7 @@ def update(self, instance, validated_data): validated_data["metadata"] = instance.metadata with transaction.atomic(): - if self.partial and owner: + if self.partial and owner and owner != instance.organization: # give the new owner permissions set_owners_permission(owner, instance) From 6f36989424cb371e154e7d0775da1a0bc655e527 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Tue, 1 Dec 2026 11:37:11 +0300 Subject: [PATCH 007/120] fix: lock the row from the step-up gate to the save --- .../viewsets/test_stepup_sharing_gates.py | 24 +++++++++++++- onadata/libs/stepup/drf.py | 32 +++++++++++++++---- 2 files changed, 48 insertions(+), 8 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py index 3ef6706ddc..d378e51c70 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py @@ -10,7 +10,8 @@ import json from unittest.mock import patch -from django.test.utils import override_settings +from django.db import connection +from django.test.utils import CaptureQueriesContext, override_settings from django_otp.plugins.otp_totp.models import TOTPDevice from oidc.stepup_grants import issue_grant, spend_grant @@ -635,6 +636,27 @@ def test_making_a_project_private_is_not_challenged(self): self.assertFalse(self.project.shared) self.assertFalse(self.xform.shared_data) + def test_the_gate_reads_the_locked_row_not_the_loaded_copy(self): + """A change can commit after the view loads the project. The gate + and the save use the row as it is once locked.""" + stale = Project.objects.get(pk=self.project.pk) + Project.objects.filter(pk=self.project.pk).update(shared=True) + self.assertFalse(stale.shared) + + with ( + patch.object(ProjectViewSet, "get_object", return_value=stale), + CaptureQueriesContext(connection) as queries, + ): + response = self._patch({"name": "renamed"}) + + self.assert_challenged(response) + self.assertTrue( + any("FOR UPDATE" in query["sql"] for query in queries.captured_queries) + ) + self._reload() + self.assertEqual(self.project.name, "demo") + self.assertTrue(self.project.shared) + def test_an_invalid_update_keeps_the_grant(self): """Validation comes first, so a blank name does not spend it.""" self.assert_challenged(self._patch({"public": True})) diff --git a/onadata/libs/stepup/drf.py b/onadata/libs/stepup/drf.py index 86c17b849b..eb5187331a 100644 --- a/onadata/libs/stepup/drf.py +++ b/onadata/libs/stepup/drf.py @@ -1,6 +1,8 @@ # -*- coding: utf-8 -*- """Viewset mixin turning a policy decision into a step-up challenge.""" +from django.db import transaction + from rest_framework import status from rest_framework.response import Response @@ -17,6 +19,15 @@ ) +def _locked(instance): + """``instance``, locked and read again from its row.""" + # pylint: disable=protected-access + instance.refresh_from_db( + from_queryset=type(instance)._base_manager.select_for_update() + ) + return instance + + class RequiresStepUp: """Refuse a gated action unless the request carries a single-use grant. @@ -83,15 +94,22 @@ def gated_update(self, request, refusal_for, partial=False): ``refusal_for(instance, validated_data)`` returns None to proceed or a Response to answer instead. Validating first means a request the write would reject is answered 400 before any grant is spent. + + The row stays locked from the gate decision to the end of the save. A + concurrent change, such as an unpublish, cannot come between them, and + the save cannot write back a value that the gate did not see. """ # pylint: disable=no-member - instance = self.get_object() - serializer = self.get_serializer(instance, data=request.data, partial=partial) - serializer.is_valid(raise_exception=True) - refusal = refusal_for(instance, serializer.validated_data) - if refusal is not None: - return refusal - self.perform_update(serializer) + with transaction.atomic(): + instance = _locked(self.get_object()) + serializer = self.get_serializer( + instance, data=request.data, partial=partial + ) + serializer.is_valid(raise_exception=True) + refusal = refusal_for(instance, serializer.validated_data) + if refusal is not None: + return refusal + self.perform_update(serializer) if getattr(instance, "_prefetched_objects_cache", None): # The update can change relations the queryset prefetched. # pylint: disable=protected-access From 2916bae88de11246fed612469e19af98fbe032fe Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Tue, 1 Dec 2026 11:37:11 +0300 Subject: [PATCH 008/120] fix: gate metadata changes that uncover a public link --- .../viewsets/test_stepup_metadata_gates.py | 76 +++++++++++ onadata/apps/api/viewsets/metadata_viewset.py | 118 ++++++++++++------ 2 files changed, 157 insertions(+), 37 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py index 88131485ef..4eb1bffcd6 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py @@ -4,6 +4,8 @@ form, or says where TextIt posts submissions. """ +from django.contrib.contenttypes.models import ContentType + from onadata.apps.api.tests.viewsets.test_stepup_form_and_transfer_gates import ( GateTestCase, ) @@ -14,6 +16,7 @@ gating, ) from onadata.apps.api.viewsets.metadata_viewset import MetaDataViewSet +from onadata.apps.logger.models import XForm from onadata.apps.main.models import MetaData from onadata.libs.permissions import ( EditorMinorRole, @@ -62,6 +65,11 @@ def _update(self, metadata, data, headers=None, method="put"): ) return view(request, pk=metadata.pk) + def _destroy(self, metadata, headers=None): + view = MetaDataViewSet.as_view({"delete": "destroy"}) + request = self.factory.delete("/", **{**self.extra, **(headers or {})}) + return view(request, pk=metadata.pk) + @gating(GATE_SHARE_FORM_ADMIN) class TestMetaPermsGate(MetaDataGateTestCase): @@ -267,6 +275,74 @@ def test_rewriting_an_on_link_is_not_challenged(self): self.assertTrue(MetaData.public_link(self.xform)) +@gating(GATE_PUBLISH_DATA) +class TestHiddenPublicLinkGate(MetaDataGateTestCase): + """A form can have more than one public link row. The reader takes the + first in primary key order, so an off row can hide an on row.""" + + audience = GATE_PUBLISH_DATA + + def setUp(self): + super().setUp() + content_type = ContentType.objects.get_for_model(XForm) + self.hiding, self.hidden = ( + MetaData.objects.create( + content_type=content_type, + object_id=self.xform.pk, + data_type="public_link", + data_value=value, + ) + for value in ("False", "True") + ) + self.assertLess(self.hiding.pk, self.hidden.pk) + self.assertFalse(MetaData.public_link(self.xform)) + + def test_retyping_the_hiding_row_is_challenged(self): + response = self._update( + self.hiding, {"data_type": "data_license", "data_value": "CC-BY"} + ) + + self.assert_challenged(response) + self.hiding.refresh_from_db() + self.assertEqual(self.hiding.data_type, "public_link") + self.assertFalse(MetaData.public_link(self.xform)) + + def test_deleting_the_hiding_row_is_challenged(self): + response = self._destroy(self.hiding) + + self.assert_challenged(response) + self.assertTrue(MetaData.objects.filter(pk=self.hiding.pk).exists()) + self.assertFalse(MetaData.public_link(self.xform)) + + def test_a_grant_lets_the_hiding_row_go(self): + grant = self._grant() + + response = self._destroy(self.hiding, self._with_grant(grant)) + + self.assertEqual(response.status_code, 204) + self.assertTrue(MetaData.public_link(self.xform)) + self.assert_spent(grant) + + def test_deleting_the_hidden_row_is_not_challenged(self): + self.assert_challenged(self._destroy(self.hiding)) + + response = self._destroy(self.hidden) + + self.assertEqual(response.status_code, 204) + self.assertFalse(MetaData.objects.filter(pk=self.hidden.pk).exists()) + self.assertFalse(MetaData.public_link(self.xform)) + + def test_retyping_the_hidden_row_is_not_challenged(self): + self.assert_challenged(self._destroy(self.hiding)) + + response = self._update( + self.hidden, {"data_type": "data_license", "data_value": "CC-BY"} + ) + + self.assertEqual(response.status_code, 200, response.data) + self.assertFalse(MetaData.public_link(self.xform)) + + @gating(GATE_CHANGE_WEBHOOK) class TestTextItSettingsGate(MetaDataGateTestCase): """A form's TextIt service posts submissions with the token and contacts diff --git a/onadata/apps/api/viewsets/metadata_viewset.py b/onadata/apps/api/viewsets/metadata_viewset.py index 52afccabdd..4537383daf 100644 --- a/onadata/apps/api/viewsets/metadata_viewset.py +++ b/onadata/apps/api/viewsets/metadata_viewset.py @@ -4,14 +4,13 @@ List, Create, Update, Delete MetaData objects. """ -from rest_framework import renderers -from rest_framework import viewsets +from rest_framework import renderers, status, viewsets from rest_framework.response import Response from onadata.apps.api.permissions import MetaDataObjectPermissions from onadata.apps.api.tools import get_media_file_response from onadata.apps.logger.models import XForm -from onadata.apps.main.models.meta_data import MetaData +from onadata.apps.main.models.meta_data import MetaData, type_for_form from onadata.libs.serializers.metadata_serializer import MetaDataSerializer from onadata.libs import filters from onadata.libs.mixins.authenticate_header_mixin import AuthenticateHeaderMixin @@ -74,12 +73,54 @@ def _turns_on_public_link(content_object, data_value): return _is_true(data_value) and not MetaData.public_link(content_object) +def _public_link_after(row, data_type=None, data_value=None): + """Whether the public link of the form of ``row`` is on once ``row`` holds + ``data_type`` and ``data_value``. With no ``data_type``, ``row`` is gone. + + The reader takes the first public link row in primary key order, so one + row can hide the others.""" + others = dict( + type_for_form(row.content_object, PUBLIC_LINK) + .exclude(pk=row.pk) + .values_list("pk", "data_value") + ) + rows = {**others, **({row.pk: data_value} if data_type == PUBLIC_LINK else {})} + return bool(rows) and _is_true(rows[min(rows)]) + + +def _change_turns_on_public_link(row, data_type=None, data_value=None): + """Whether a change to ``row``, or its removal, turns on the public link of + its form.""" + if PUBLIC_LINK not in (row.data_type, data_type) or row.content_object is None: + return False + return _public_link_after(row, data_type, data_value) and not ( + MetaData.public_link(row.content_object) + ) + + def _changes_textit(content_object, data_value): """The TextIt settings carry the token and contacts a form's TextIt service posts submissions with.""" return MetaData.textit(content_object) != data_value +def _write_changes(content_object, data_type, data_value, turns_on_public_link): + """The ``(action, changed)`` pairs of a write of ``data_value`` as + ``data_type`` on ``content_object``.""" + return ( + ( + GATE_SHARE_FORM_ADMIN, + lambda: data_type == XFORM_META_PERMS + and _introduces_admin_meta_perms(content_object, data_value), + ), + (GATE_PUBLISH_DATA, turns_on_public_link), + ( + GATE_CHANGE_WEBHOOK, + data_type == TEXTIT and _changes_textit(content_object, data_value), + ), + ) + + # pylint: disable=too-many-ancestors class MetaDataViewSet( AuthenticateHeaderMixin, @@ -104,56 +145,59 @@ class MetaDataViewSet( ) serializer_class = MetaDataSerializer - def _change_refusal(self, request, content_object, data_type, data_value): - """Refuse the gated change writing ``data_value`` as ``data_type`` on - ``content_object`` would make, or None.""" - return self.gated_change_refusal( - request, - ( - ( - GATE_SHARE_FORM_ADMIN, - lambda: data_type == XFORM_META_PERMS - and _introduces_admin_meta_perms(content_object, data_value), - ), - ( - GATE_PUBLISH_DATA, - data_type == PUBLIC_LINK + def create(self, request, *args, **kwargs): + def refusal_for(data): + content_object = self.get_serializer().get_content_object(data) + data_type = data.get("data_type") + data_value = data.get("data_value") + return self.gated_change_refusal( + request, + _write_changes( + content_object, + data_type, + data_value, + lambda: data_type == PUBLIC_LINK and _turns_on_public_link(content_object, data_value), ), - ( - GATE_CHANGE_WEBHOOK, - data_type == TEXTIT and _changes_textit(content_object, data_value), - ), - ), - ) + ) - def create(self, request, *args, **kwargs): - return self.gated_create( - request, - lambda data: self._change_refusal( - request, - self.get_serializer().get_content_object(data), - data.get("data_type"), - data.get("data_value"), - ), - ) + return self.gated_create(request, refusal_for) def update(self, request, *args, **kwargs): """An update can change the type as well as the value, so the gates read what the row will hold afterwards.""" def refusal_for(instance, validated_data): - return self._change_refusal( + data_type = validated_data.get("data_type", instance.data_type) + data_value = validated_data.get("data_value", instance.data_value) + return self.gated_change_refusal( request, - instance.content_object, - validated_data.get("data_type", instance.data_type), - validated_data.get("data_value", instance.data_value), + _write_changes( + instance.content_object, + data_type, + data_value, + lambda: _change_turns_on_public_link( + instance, data_type, data_value + ), + ), ) return self.gated_update( request, refusal_for, partial=kwargs.pop("partial", False) ) + def destroy(self, request, *args, **kwargs): + """A removed row can uncover another public link row of the form.""" + instance = self.get_object() + refusal = self.gated_change_refusal( + request, + ((GATE_PUBLISH_DATA, lambda: _change_turns_on_public_link(instance)),), + ) + if refusal is not None: + return refusal + self.perform_destroy(instance) + return Response(status=status.HTTP_204_NO_CONTENT) + def retrieve(self, request, *args, **kwargs): # pylint: disable=attribute-defined-outside-init self.object = self.get_object() From 5189437cc1d784b10d1af5cbb0395e02dd5ca735 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Tue, 1 Dec 2026 11:37:11 +0300 Subject: [PATCH 009/120] fix: count only direct grants as roles a share leaves unchanged --- .../viewsets/test_stepup_sharing_gates.py | 19 +++++++++++++++++++ onadata/libs/stepup/sharing.py | 11 +++++++---- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py index d378e51c70..67fa0f7959 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py @@ -14,9 +14,12 @@ from django.test.utils import CaptureQueriesContext, override_settings from django_otp.plugins.otp_totp.models import TOTPDevice +from guardian.shortcuts import get_user_perms from oidc.stepup_grants import issue_grant, spend_grant +from onadata.apps.api.models.organization_profile import create_organization_team from onadata.apps.api.tests.viewsets.test_abstract_viewset import TestAbstractViewSet +from onadata.apps.api.tools import add_user_to_team from onadata.apps.api.viewsets.project_viewset import ProjectViewSet from onadata.apps.api.viewsets.xform_viewset import XFormViewSet from onadata.apps.logger.models import Project, ProjectInvitation, XForm @@ -169,6 +172,22 @@ def test_a_role_every_target_already_holds_is_not_challenged(self): self.assertEqual(response.status_code, 204) self.assertTrue(ManagerRole.user_has_role(self.alice, self.project)) + def test_a_role_held_only_through_a_team_is_challenged(self): + """The share writes a direct grant, which stays after the user leaves + the team.""" + self._org_create() + team = create_organization_team(self.organization, "project managers") + ManagerRole.add(team, self.project) + add_user_to_team(team, self.alice) + self.assertTrue(ManagerRole.user_has_role(self.alice, self.project)) + + response = self._share("alice", ManagerRole.name) + + self.assert_challenged(response) + self.assertFalse( + ManagerRole.has_role(get_user_perms(self.alice, self.project), self.project) + ) + def test_removing_an_admin_is_not_challenged(self): ShareProject(self.project, "alice", OwnerRole.name).save() self.assertTrue(OwnerRole.user_has_role(self.alice, self.project)) diff --git a/onadata/libs/stepup/sharing.py b/onadata/libs/stepup/sharing.py index 7c55ada4ec..82b0e29d8f 100644 --- a/onadata/libs/stepup/sharing.py +++ b/onadata/libs/stepup/sharing.py @@ -4,7 +4,7 @@ from django.contrib.contenttypes.models import ContentType -from guardian.shortcuts import get_objects_for_group, get_perms +from guardian.shortcuts import get_objects_for_group, get_perms, get_user_perms from onadata.apps.logger.models import Project, XForm from onadata.apps.main.models import MetaData @@ -71,9 +71,12 @@ def admin_role(role_name): def holds_roles(user, granted): - """Whether ``user`` already holds every ``(obj, role)`` in ``granted``, so - a share granting them hands out nothing new.""" - return all(role.user_has_role(user, obj) for obj, role in granted) + """Whether ``user`` already holds every ``(obj, role)`` in ``granted`` by a + direct grant, so a share granting them hands out nothing new. + + A share writes direct grants. A role that comes only from a team does not + count, because the direct grant stays after the user leaves the team.""" + return all(role.has_role(get_user_perms(user, obj), obj) for obj, role in granted) def appoints_admins(xform, meta_perms): From 2cf75d49ece7c99a26d3d47fab47b6acce97d796 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Tue, 1 Dec 2026 11:37:11 +0300 Subject: [PATCH 010/120] fix: stop the WSGI application on a step-up check error --- onadata/apps/main/wsgi.py | 14 ++++++++- onadata/libs/apps.py | 24 ++++++++------- onadata/libs/stepup/checks.py | 23 ++++++++++++++ onadata/libs/tests/stepup/test_checks.py | 38 ++++++++++++++++++++++++ 4 files changed, 88 insertions(+), 11 deletions(-) diff --git a/onadata/apps/main/wsgi.py b/onadata/apps/main/wsgi.py index 8afd24d2b4..03b35d1683 100644 --- a/onadata/apps/main/wsgi.py +++ b/onadata/apps/main/wsgi.py @@ -1,4 +1,16 @@ +"""The WSGI application. It does not load if a step-up check reports an error.""" + from django.core.wsgi import get_wsgi_application -application = get_wsgi_application() +def _application(): + wsgi_application = get_wsgi_application() + # The step-up package loads models, so import it after the setup. + # pylint: disable=import-outside-toplevel + from onadata.libs.stepup.checks import require_valid_step_up_settings + + require_valid_step_up_settings() + return wsgi_application + + +application = _application() diff --git a/onadata/libs/apps.py b/onadata/libs/apps.py index 0098089be5..87728c5d0d 100644 --- a/onadata/libs/apps.py +++ b/onadata/libs/apps.py @@ -16,6 +16,7 @@ def ready(self): from django.core.checks import register from onadata.libs.stepup.checks import ( + STEP_UP_CHECK_TAG, check_federated_step_up_binds_by_email, check_federated_step_up_gates_email, check_oauth_approval_can_step_up, @@ -28,13 +29,16 @@ def ready(self): check_step_up_not_silently_bypassable, ) - register(check_step_up_is_well_formed) - register(check_step_up_actions_are_known) - register(check_step_up_no_factor_policy_is_known) - register(check_step_up_not_silently_bypassable) - register(check_step_up_mode_is_known) - register(check_step_up_has_two_factor_enabled) - register(check_removed_enrolment_password_setting) - register(check_federated_step_up_gates_email) - register(check_federated_step_up_binds_by_email) - register(check_oauth_approval_can_step_up) + for check in ( + check_step_up_is_well_formed, + check_step_up_actions_are_known, + check_step_up_no_factor_policy_is_known, + check_step_up_not_silently_bypassable, + check_step_up_mode_is_known, + check_step_up_has_two_factor_enabled, + check_removed_enrolment_password_setting, + check_federated_step_up_gates_email, + check_federated_step_up_binds_by_email, + check_oauth_approval_can_step_up, + ): + register(check, STEP_UP_CHECK_TAG) diff --git a/onadata/libs/stepup/checks.py b/onadata/libs/stepup/checks.py index 764cd797de..7891fdaab3 100644 --- a/onadata/libs/stepup/checks.py +++ b/onadata/libs/stepup/checks.py @@ -6,6 +6,8 @@ from django.conf import settings from django.core.checks import Error as CheckError from django.core.checks import Warning as CheckWarning +from django.core.checks import run_checks +from django.core.exceptions import ImproperlyConfigured from oidc.stepup import ( find_step_up_auth_server, @@ -29,6 +31,27 @@ step_up_setting, ) +#: The tag of the step-up checks, so a caller can run only these. +STEP_UP_CHECK_TAG = "step_up" + + +def require_valid_step_up_settings(): + """Raise ``ImproperlyConfigured`` if a step-up check reports an error. + + A WSGI server loads Django but does not run the system checks. Call this + after the WSGI application loads, so that a server whose ``STEP_UP`` + leaves an action ungated does not start. + """ + errors = [ + message + for message in run_checks(tags=[STEP_UP_CHECK_TAG]) + if message.is_serious() and not message.is_silenced() + ] + if errors: + raise ImproperlyConfigured( + "Step-up is misconfigured:\n" + "\n".join(map(str, errors)) + ) + def _malformation(config): """What makes ``config``, a ``STEP_UP`` setting, unreadable, or None.""" diff --git a/onadata/libs/tests/stepup/test_checks.py b/onadata/libs/tests/stepup/test_checks.py index 17d633b90c..923d566d2d 100644 --- a/onadata/libs/tests/stepup/test_checks.py +++ b/onadata/libs/tests/stepup/test_checks.py @@ -1,8 +1,11 @@ """Tests for module onadata.libs.stepup.checks""" +from django.core.checks import run_checks +from django.core.exceptions import ImproperlyConfigured from django.test import SimpleTestCase, override_settings from onadata.libs.stepup.checks import ( + STEP_UP_CHECK_TAG, check_federated_step_up_binds_by_email, check_federated_step_up_gates_email, check_oauth_approval_can_step_up, @@ -13,6 +16,7 @@ check_step_up_mode_is_known, check_step_up_no_factor_policy_is_known, check_step_up_not_silently_bypassable, + require_valid_step_up_settings, ) ALL_CHECKS = ( @@ -29,6 +33,40 @@ ) +class TestRequireValidStepUpSettings(SimpleTestCase): + """The WSGI module calls this, because a WSGI server runs no checks.""" + + @override_settings(STEP_UP={"ACTIONS": ["change-emial"], "MODE": "local"}) + def test_an_error_stops_the_start(self): + with self.assertRaisesMessage(ImproperlyConfigured, "stepup.E002"): + require_valid_step_up_settings() + + @override_settings( + STEP_UP={"ACTIONS": ["change-emial"], "MODE": "local"}, + SILENCED_SYSTEM_CHECKS=["stepup.E002"], + ) + def test_a_silenced_error_does_not_stop_the_start(self): + require_valid_step_up_settings() + + @override_settings( + ENABLE_TWO_FACTOR=True, + STEP_UP={ + "ACTIONS": ["change-email"], + "MODE": "local", + "NO_FACTOR_POLICY": "skip_gate", + }, + ) + def test_a_warning_does_not_stop_the_start(self): + ids = {message.id for message in run_checks(tags=[STEP_UP_CHECK_TAG])} + self.assertIn("stepup.W001", ids) + + require_valid_step_up_settings() + + def test_every_step_up_check_carries_the_tag(self): + for check in ALL_CHECKS: + self.assertIn(STEP_UP_CHECK_TAG, check.tags, check.__name__) + + class TestTwoFactorEnabled(SimpleTestCase): """Local step-up needs the two-factor endpoints that mint its grants.""" From eff89308cf03c054ff36b393fdfab00d29ffc25c Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Tue, 1 Dec 2026 11:37:11 +0300 Subject: [PATCH 011/120] fix: answer step-up start in JSON and refuse non-object callback bodies --- .../api/tests/viewsets/test_stepup_viewset.py | 48 +++++++++++++++++++ onadata/apps/api/viewsets/stepup_viewset.py | 11 ++++- 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_viewset.py b/onadata/apps/api/tests/viewsets/test_stepup_viewset.py index c65419e28f..8ddcc05ccf 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_viewset.py @@ -94,6 +94,42 @@ def test_start_returns_the_authorization_url(self): "https://idp.test/authorize?acr_values=mfa", ) + @override_settings(STEP_UP=STEP_UP_FEDERATED) + def test_start_answers_a_browser_accept_header_with_json(self): + """An HTML body would not carry the URL.""" + self.client.force_login(self.user) + with patch( + "onadata.apps.api.viewsets.stepup_viewset.start_step_up", + return_value=("https://idp.test/authorize?acr_values=mfa", "state-1"), + ): + response = self.client.get( + reverse("stepup-start"), + {"audience": "require-auth-toggle"}, + HTTP_ACCEPT="text/html,*/*;q=0.8", + ) + + self.assertEqual(response.status_code, 200) + self.assertEqual( + response.json()["authorizationUrl"], + "https://idp.test/authorize?acr_values=mfa", + ) + + @override_settings(STEP_UP=STEP_UP_FEDERATED) + def test_start_refuses_an_html_only_accept_header(self): + self.client.force_login(self.user) + with patch( + "onadata.apps.api.viewsets.stepup_viewset.start_step_up", + return_value=("https://idp.test/authorize?acr_values=mfa", "state-1"), + ): + response = self.client.get( + reverse("stepup-start"), + {"audience": "require-auth-toggle"}, + HTTP_ACCEPT="text/html", + ) + + self.assertEqual(response.status_code, 406) + self.assertEqual(response["Content-Type"], "application/json") + @override_settings(STEP_UP=STEP_UP_FEDERATED) def test_start_reports_a_deployment_with_nowhere_to_send_the_user(self): """A server without its endpoints is a deployment fault, not the @@ -159,6 +195,18 @@ def test_callback_rejects_a_request_with_no_code_or_state(self): self.assertEqual(response.status_code, 400) self.assertEqual(response.data["error"], "invalid_request") + @override_settings(STEP_UP=STEP_UP_FEDERATED) + def test_callback_rejects_a_json_body_that_is_not_an_object(self): + view = StepUpViewSet.as_view({"post": "callback"}) + request = self.factory.post( + "/", ["code", "state"], format="json", **self.extra + ) + + response = view(request) + + self.assertEqual(response.status_code, 400) + self.assertEqual(response.data["error"], "invalid_request") + @override_settings(STEP_UP=STEP_UP_FEDERATED) def test_a_refused_step_up_is_a_403_carrying_its_reason(self): """A 403, not a 200 a caller might read as success. It carries the diff --git a/onadata/apps/api/viewsets/stepup_viewset.py b/onadata/apps/api/viewsets/stepup_viewset.py index a28fda9fca..c686884155 100644 --- a/onadata/apps/api/viewsets/stepup_viewset.py +++ b/onadata/apps/api/viewsets/stepup_viewset.py @@ -2,6 +2,7 @@ """Where the identity provider returns after a step-up.""" import logging +from collections.abc import Mapping from oidc.stepup_grants import issue_grant from oidc.stepup_viewsets import StepUpCallbackMixin @@ -54,7 +55,12 @@ def finalize_response(self, request, response, *args, **kwargs): response["Cache-Control"] = "no-store" return response - @action(detail=False, methods=["get"], url_path="start") + @action( + detail=False, + methods=["get"], + url_path="start", + renderer_classes=(JSONRenderer,), + ) def start(self, request): """Where to send the user to prove a factor for ``audience``. @@ -87,6 +93,9 @@ def callback(self, request): """Verify the provider's answer, and mint a grant only if it satisfies the step-up.""" params = request.query_params if request.method == "GET" else request.data + if not isinstance(params, Mapping): + # A JSON array or scalar body carries no parameters. + params = {} code = str(params.get("code", "")).strip() state = str(params.get("state", "")).strip() auth_server = str(params.get("auth_server", "")).strip() or None From 01c95d58051e1eaed01bea02741c254def227cf3 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Tue, 1 Dec 2026 11:37:11 +0300 Subject: [PATCH 012/120] docs: describe the step-up review changes --- docs/two_factor.rst | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/two_factor.rst b/docs/two_factor.rst index bac2fd6622..3235de516b 100644 --- a/docs/two_factor.rst +++ b/docs/two_factor.rst @@ -43,7 +43,7 @@ To do an action that a deployment can gate, do these steps: ``/api/v1/stepup/callback``. A browser must open this popup from the click of the user, because browsers block a popup from a later response. To get the URL before the gated request, call - ``GET /api/v1/stepup/start?audience=...``. + ``GET /api/v1/stepup/start?audience=...``. It answers only in JSON. 4. Send the same request again with the grant. Put the grant in a ``grant`` field in the body. If the request has no body, put the grant in the @@ -337,9 +337,10 @@ Audience Action shared with the member make them an owner or manager ``publish-data`` a change that makes the data of a form or project public; a move of a private form into a public - project; ``public_link`` turned on for a form on - ``/api/v1/metadata``; a new dataview in a public - project, or a change to the project, columns or + project; a change or a deletion on + ``/api/v1/metadata`` that turns on the + ``public_link`` of a form; a new dataview in a + public project, or a change to the project, columns or query of a dataview there, over a form whose data is not public; a new merged dataset in a public project from such forms; a new link on @@ -435,7 +436,9 @@ then hide the controls that do not apply:: } The startup checks report a step-up configuration that will not work as -intended: +intended. A WSGI server does not run the checks. Thus, the WSGI application +does not load if a step-up check reports an error. ``manage.py check`` shows +all results. - ``stepup.E001`` (error). ``STEP_UP`` is not a dict, or its ``ACTIONS`` is not a list of action names. Step-up then gates nothing. From dd924263e9e4d59c7cc77f24f481b709ef345da5 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Tue, 1 Dec 2026 11:38:27 +0300 Subject: [PATCH 013/120] chore: pin ona-oidc to the latest step-up commit --- onadata/apps/api/tests/viewsets/test_stepup_viewset.py | 2 +- requirements/base.in | 2 +- requirements/base.pip | 2 +- requirements/dev.pip | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_viewset.py b/onadata/apps/api/tests/viewsets/test_stepup_viewset.py index 8ddcc05ccf..6d31aa50b9 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_viewset.py @@ -47,7 +47,7 @@ } } -SATISFYING = {"acr": "gold", "email": "ana@example.org"} +SATISFYING = {"acr": "gold", "email": "ana@example.org", "email_verified": True} class TestStepUpViewSet(TestAbstractViewSet): diff --git a/requirements/base.in b/requirements/base.in index 9fc7798167..e64f1b377d 100644 --- a/requirements/base.in +++ b/requirements/base.in @@ -30,7 +30,7 @@ git+https://github.com/onaio/floip-py.git@3c980eb184069ae7c3c9136b18441978237cd4 git+https://github.com/onaio/python-json2xlsclient.git@62b4645f7b4f2684421a13ce98da0331a9dd66a0#egg=python-json2xlsclient # Pinned at the step-up branch tip for stepup_grants, which the totp endpoints # import. Re-pin to a main SHA once onaio/ona-oidc#139 merges. -git+https://github.com/onaio/ona-oidc.git@29544f09d8752b7060dd48203255ed6fe74e745a#egg=ona-oidc +git+https://github.com/onaio/ona-oidc.git@7e74387171a65b5f6179f0f2023fac38a6d7a643#egg=ona-oidc -e git+https://github.com/onaio/savreaderwriter.git@fix-pep-440-issues#egg=savreaderwriter git+https://git@github.com/onaio/valigetta.git@v0.3.1#egg=valigetta codetiming diff --git a/requirements/base.pip b/requirements/base.pip index 1111b7fac6..4dbe783f6c 100644 --- a/requirements/base.pip +++ b/requirements/base.pip @@ -265,7 +265,7 @@ oauthlib==4.0.1 # -r requirements/base.in # django-oauth-toolkit # requests-oauthlib -ona-oidc @ git+https://github.com/onaio/ona-oidc.git@29544f09d8752b7060dd48203255ed6fe74e745a +ona-oidc @ git+https://github.com/onaio/ona-oidc.git@7e74387171a65b5f6179f0f2023fac38a6d7a643 # via -r requirements/base.in openpyxl==3.1.5 # via diff --git a/requirements/dev.pip b/requirements/dev.pip index 8cfdab090c..8557cb7f98 100644 --- a/requirements/dev.pip +++ b/requirements/dev.pip @@ -331,7 +331,7 @@ oauthlib==4.0.1 # -r requirements/base.in # django-oauth-toolkit # requests-oauthlib -ona-oidc @ git+https://github.com/onaio/ona-oidc.git@29544f09d8752b7060dd48203255ed6fe74e745a +ona-oidc @ git+https://github.com/onaio/ona-oidc.git@7e74387171a65b5f6179f0f2023fac38a6d7a643 # via -r requirements/base.in openpyxl==3.1.5 # via From f39c4571091844eb80ca027225a2e5221ad09226 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Tue, 1 Dec 2026 11:38:28 +0300 Subject: [PATCH 014/120] docs: describe the verified email and auth_time skew step-up keys --- docs/two_factor.rst | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/docs/two_factor.rst b/docs/two_factor.rst index 3235de516b..06cbbecbac 100644 --- a/docs/two_factor.rst +++ b/docs/two_factor.rst @@ -399,17 +399,24 @@ profile gets no challenge. with ``not_gated`` for an audience that is not gated. It answers **400** with ``not_federated`` in local mode. - The callback matches the token to the signed-in user by email. It checks - ``email_verified`` only if the provider entry sets - ``CHECK_EMAIL_VERIFIED`` or ``REQUIRE_VERIFIED_EMAIL``. Both are off by - default. If both are off, an attacker can use the password of the user to - sign in. At the provider, the attacker can use an account with the address - of the user. The provider does not have to verify that address. The - attacker then passes step-up with their own factor. - - If users can add an address that they do not own at the provider, turn on - ``CHECK_EMAIL_VERIFIED``. A refused token gets ``step_up_failed`` with - reason ``email_unverified``. + The callback matches the token to the signed-in user by email. By + default, the token must also set ``email_verified`` to true. If it does + not, the callback refuses the token with ``step_up_failed`` and reason + ``email_unverified``. Without this check, an attacker who has the password + of the user can sign in at the provider with an account that has the + address of the user but not its proof. The attacker then passes step-up + with their own factor. + + Set ``REQUIRE_VERIFIED_EMAIL`` to ``False`` in the ``STEP_UP`` block only + if the provider proves that the user owns the address in a different way. + The ``CHECK_EMAIL_VERIFIED`` and ``REQUIRE_VERIFIED_EMAIL`` settings of + the provider entry then apply, as they do for login. + + The callback refuses a token whose ``auth_time`` is before the start of + the step-up. If the clock of the provider is behind the clock of this + server, set ``AUTH_TIME_SKEW_SECONDS`` in the ``STEP_UP`` block to the + difference in seconds. The default is 0. Each second lets a provider that + ignores ``max_age=0`` use a session that is that much older. In local mode, the gate lets a user with no second factor through by default (``STEP_UP["NO_FACTOR_POLICY"] = "skip_gate"``). With ``deny_prompt_enrol``, From 85912e746a1e36f075e671d7bbc9a12d69ceff5c Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Tue, 1 Dec 2026 11:39:50 +0300 Subject: [PATCH 015/120] docs: say why the step-up lock reads through the base manager --- onadata/libs/stepup/drf.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/onadata/libs/stepup/drf.py b/onadata/libs/stepup/drf.py index eb5187331a..8cd0821737 100644 --- a/onadata/libs/stepup/drf.py +++ b/onadata/libs/stepup/drf.py @@ -20,7 +20,12 @@ def _locked(instance): - """``instance``, locked and read again from its row.""" + """``instance``, locked and read again from its row. + + Lock through the base manager by primary key, not through the queryset of + the view. That queryset can have an outer join, and Postgres refuses + ``FOR UPDATE`` on the nullable side of an outer join. + """ # pylint: disable=protected-access instance.refresh_from_db( from_queryset=type(instance)._base_manager.select_for_update() From ea857dd1cf51aef9ac86fa94ded44d52e3f4de27 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Tue, 1 Dec 2026 13:24:04 +0300 Subject: [PATCH 016/120] fix: gate metadata writes on direct grants and effective rows under a form lock --- .../viewsets/test_stepup_metadata_gates.py | 170 ++++++++++++++++++ onadata/apps/api/viewsets/metadata_viewset.py | 94 +++++++--- onadata/libs/stepup/drf.py | 15 +- onadata/libs/stepup/sharing.py | 15 +- 4 files changed, 262 insertions(+), 32 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py index 4eb1bffcd6..ae1adcf78d 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py @@ -5,7 +5,12 @@ """ from django.contrib.contenttypes.models import ContentType +from django.db import connection +from django.test.utils import CaptureQueriesContext +from guardian.shortcuts import get_user_perms + +from onadata.apps.api.models.organization_profile import create_organization_team from onadata.apps.api.tests.viewsets.test_stepup_form_and_transfer_gates import ( GateTestCase, ) @@ -15,6 +20,7 @@ EDITOR_STAYS_BELOW_ADMIN, gating, ) +from onadata.apps.api.tools import add_user_to_team from onadata.apps.api.viewsets.metadata_viewset import MetaDataViewSet from onadata.apps.logger.models import XForm from onadata.apps.main.models import MetaData @@ -193,6 +199,32 @@ def test_a_grant_lets_a_promoting_write_back_through(self): self.assertTrue(ManagerRole.user_has_role(self.alice, self.xform)) self.assert_spent(grant) + def test_a_slot_role_held_only_through_a_team_is_challenged(self): + """Applying meta permissions writes a direct grant, which stays after + the editor leaves the team that makes them a manager.""" + unapplied_admin_slot = "manager|dataentry|readonly" + metadata = MetaData.xform_meta_permission( + self.xform, data_value=unapplied_admin_slot + ) + self._org_create() + team = create_organization_team(self.organization, "form managers") + ManagerRole.add(team, self.xform) + add_user_to_team(team, self.alice) + self.assertTrue(ManagerRole.user_has_role(self.alice, self.xform)) + self.assertTrue( + EditorRole.has_role(get_user_perms(self.alice, self.xform), self.xform) + ) + + response = self._update( + metadata, + {"data_type": XFORM_META_PERMS, "data_value": unapplied_admin_slot}, + ) + + self.assert_challenged(response) + self.assertFalse( + ManagerRole.has_role(get_user_perms(self.alice, self.xform), self.xform) + ) + def test_an_invalid_value_keeps_the_grant(self): """Validation comes first, so a malformed value does not spend it.""" self.assert_challenged(self._create(XFORM_META_PERMS, EDITOR_BECOMES_OWNER)) @@ -400,3 +432,141 @@ def test_writing_back_the_same_settings_is_not_challenged(self): self.assertEqual(response.status_code, 200, response.data) self.assertEqual(MetaData.textit(self.xform), TEXTIT_SETTINGS) + + +def _rows(xform, data_type, values): + """A metadata row of ``data_type`` on ``xform`` for each of ``values``, in + primary key order.""" + content_type = ContentType.objects.get_for_model(XForm) + return [ + MetaData.objects.create( + content_type=content_type, + object_id=xform.pk, + data_type=data_type, + data_value=value, + ) + for value in values + ] + + +@gating(GATE_CHANGE_WEBHOOK) +class TestHiddenTextItGate(MetaDataGateTestCase): + """A form can have more than one TextIt row. The reader takes the first in + primary key order, so a change to that row can make the settings of + another row apply.""" + + audience = GATE_CHANGE_WEBHOOK + + def setUp(self): + super().setUp() + self.first, self.hidden = _rows( + self.xform, TEXTIT, (TEXTIT_SETTINGS, OTHER_TEXTIT_SETTINGS) + ) + self.assertLess(self.first.pk, self.hidden.pk) + self.assertEqual(MetaData.textit(self.xform), TEXTIT_SETTINGS) + + def test_retyping_the_first_row_is_challenged(self): + response = self._update( + self.first, {"data_type": "data_license", "data_value": "CC-BY"} + ) + + self.assert_challenged(response) + self.first.refresh_from_db() + self.assertEqual(self.first.data_type, TEXTIT) + self.assertEqual(MetaData.textit(self.xform), TEXTIT_SETTINGS) + + def test_deleting_the_first_row_is_challenged(self): + response = self._destroy(self.first) + + self.assert_challenged(response) + self.assertTrue(MetaData.objects.filter(pk=self.first.pk).exists()) + self.assertEqual(MetaData.textit(self.xform), TEXTIT_SETTINGS) + + def test_a_grant_lets_the_first_row_go(self): + grant = self._grant() + + response = self._destroy(self.first, self._with_grant(grant)) + + self.assertEqual(response.status_code, 204) + self.assertEqual(MetaData.textit(self.xform), OTHER_TEXTIT_SETTINGS) + self.assert_spent(grant) + + def test_deleting_the_hidden_row_is_not_challenged(self): + """The first row still applies, so nothing sends anywhere new.""" + self.assert_challenged(self._destroy(self.first)) + + response = self._destroy(self.hidden) + + self.assertEqual(response.status_code, 204) + self.assertFalse(MetaData.objects.filter(pk=self.hidden.pk).exists()) + self.assertEqual(MetaData.textit(self.xform), TEXTIT_SETTINGS) + + def test_retyping_the_hidden_row_is_not_challenged(self): + self.assert_challenged(self._destroy(self.first)) + + response = self._update( + self.hidden, {"data_type": "data_license", "data_value": "CC-BY"} + ) + + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(MetaData.textit(self.xform), TEXTIT_SETTINGS) + + +@gating(GATE_PUBLISH_DATA, GATE_CHANGE_WEBHOOK) +class TestFirstRowWritesLockTheForm(MetaDataGateTestCase): + """The gates on public link and TextIt rows read the other rows of the + form. Two writes that each read the other's row before it changes could + both pass. Each write locks the form row before the check and holds the + lock until the write.""" + + def assert_form_locked_before_write(self, queries, write): + """The form row is locked ``FOR UPDATE`` before the ``write`` + statement.""" + statements = [query["sql"] for query in queries.captured_queries] + locks = [ + index + for index, sql in enumerate(statements) + if 'FROM "logger_xform"' in sql and "FOR UPDATE" in sql + ] + writes = [ + index for index, sql in enumerate(statements) if sql.startswith(write) + ] + self.assertTrue(locks, "The form row is not locked.") + self.assertTrue(writes, f"No {write} statement.") + self.assertLess(locks[0], writes[0]) + + def test_a_create_locks_the_form(self): + with CaptureQueriesContext(connection) as queries: + response = self._create("public_link", "False") + + self.assertEqual(response.status_code, 201, response.data) + self.assert_form_locked_before_write(queries, 'INSERT INTO "main_metadata"') + + def test_an_update_locks_the_form(self): + (row,) = _rows(self.xform, "public_link", ("False",)) + + with CaptureQueriesContext(connection) as queries: + response = self._update( + row, {"data_type": "public_link", "data_value": "False"} + ) + + self.assertEqual(response.status_code, 200, response.data) + self.assert_form_locked_before_write(queries, 'UPDATE "main_metadata"') + + def test_a_delete_locks_the_form(self): + (row,) = _rows(self.xform, "public_link", ("False",)) + + with CaptureQueriesContext(connection) as queries: + response = self._destroy(row) + + self.assertEqual(response.status_code, 204) + self.assert_form_locked_before_write(queries, 'DELETE FROM "main_metadata"') + + def test_a_textit_delete_locks_the_form(self): + (row,) = _rows(self.xform, TEXTIT, (TEXTIT_SETTINGS,)) + + with CaptureQueriesContext(connection) as queries: + response = self._destroy(row) + + self.assertEqual(response.status_code, 204) + self.assert_form_locked_before_write(queries, 'DELETE FROM "main_metadata"') diff --git a/onadata/apps/api/viewsets/metadata_viewset.py b/onadata/apps/api/viewsets/metadata_viewset.py index 4537383daf..a808b9df63 100644 --- a/onadata/apps/api/viewsets/metadata_viewset.py +++ b/onadata/apps/api/viewsets/metadata_viewset.py @@ -4,6 +4,8 @@ List, Create, Update, Delete MetaData objects. """ +from django.db import transaction + from rest_framework import renderers, status, viewsets from rest_framework.response import Response @@ -23,6 +25,7 @@ from onadata.apps.api.tools import get_baseviewset_class from onadata.libs.data import strtobool from onadata.libs.stepup import RequiresStepUp +from onadata.libs.stepup.drf import lock_row, locked from onadata.libs.stepup.policy import ( ADMIN_ROLE_NAMES, GATE_CHANGE_WEBHOOK, @@ -37,6 +40,10 @@ PUBLIC_LINK = "public_link" +#: A reader of these types takes the first of a form's rows. A write of one +#: reads the other rows of the form, so it locks the form first. +FIRST_ROW_TYPES = frozenset({PUBLIC_LINK, TEXTIT}) + def _meta_perms_slots(value): return dict(enumerate(value.split("|"))) if value else {} @@ -73,19 +80,30 @@ def _turns_on_public_link(content_object, data_value): return _is_true(data_value) and not MetaData.public_link(content_object) -def _public_link_after(row, data_type=None, data_value=None): - """Whether the public link of the form of ``row`` is on once ``row`` holds - ``data_type`` and ``data_value``. With no ``data_type``, ``row`` is gone. +def _lock_parent(content_object, *data_types): + """Lock the row of ``content_object`` until the transaction ends, if a + write of ``data_types`` reads the other metadata rows of that object. + + Such writes then run one at a time, from the gate decision to the end of + the write. Each one sees the rows that the one before it left.""" + if content_object is not None and FIRST_ROW_TYPES.intersection(data_types): + lock_row(type(content_object), content_object.pk) + + +def _first_row_after(row, of_type, data_type=None, data_value=None): + """The value that a reader of ``of_type`` takes for the form of ``row`` + once ``row`` holds ``data_type`` and ``data_value``. With no + ``data_type``, ``row`` is gone. None when no ``of_type`` row stays. - The reader takes the first public link row in primary key order, so one - row can hide the others.""" + The reader takes the first row in primary key order, so one row can hide + the others.""" others = dict( - type_for_form(row.content_object, PUBLIC_LINK) + type_for_form(row.content_object, of_type) .exclude(pk=row.pk) .values_list("pk", "data_value") ) - rows = {**others, **({row.pk: data_value} if data_type == PUBLIC_LINK else {})} - return bool(rows) and _is_true(rows[min(rows)]) + rows = {**others, **({row.pk: data_value} if data_type == of_type else {})} + return rows[min(rows)] if rows else None def _change_turns_on_public_link(row, data_type=None, data_value=None): @@ -93,8 +111,8 @@ def _change_turns_on_public_link(row, data_type=None, data_value=None): its form.""" if PUBLIC_LINK not in (row.data_type, data_type) or row.content_object is None: return False - return _public_link_after(row, data_type, data_value) and not ( - MetaData.public_link(row.content_object) + return _is_true(_first_row_after(row, PUBLIC_LINK, data_type, data_value)) and ( + not MetaData.public_link(row.content_object) ) @@ -104,7 +122,18 @@ def _changes_textit(content_object, data_value): return MetaData.textit(content_object) != data_value -def _write_changes(content_object, data_type, data_value, turns_on_public_link): +def _change_redirects_textit(row, data_type=None, data_value=None): + """Whether a change to ``row``, or its removal, makes different TextIt + settings apply to its form.""" + if TEXTIT not in (row.data_type, data_type) or row.content_object is None: + return False + after = _first_row_after(row, TEXTIT, data_type, data_value) + return after is not None and after != MetaData.textit(row.content_object) + + +def _write_changes( + content_object, data_type, data_value, turns_on_public_link, redirects_textit +): """The ``(action, changed)`` pairs of a write of ``data_value`` as ``data_type`` on ``content_object``.""" return ( @@ -114,10 +143,7 @@ def _write_changes(content_object, data_type, data_value, turns_on_public_link): and _introduces_admin_meta_perms(content_object, data_value), ), (GATE_PUBLISH_DATA, turns_on_public_link), - ( - GATE_CHANGE_WEBHOOK, - data_type == TEXTIT and _changes_textit(content_object, data_value), - ), + (GATE_CHANGE_WEBHOOK, redirects_textit), ) @@ -150,6 +176,7 @@ def refusal_for(data): content_object = self.get_serializer().get_content_object(data) data_type = data.get("data_type") data_value = data.get("data_value") + _lock_parent(content_object, data_type) return self.gated_change_refusal( request, _write_changes( @@ -158,10 +185,13 @@ def refusal_for(data): data_value, lambda: data_type == PUBLIC_LINK and _turns_on_public_link(content_object, data_value), + lambda: data_type == TEXTIT + and _changes_textit(content_object, data_value), ), ) - return self.gated_create(request, refusal_for) + with transaction.atomic(): + return self.gated_create(request, refusal_for) def update(self, request, *args, **kwargs): """An update can change the type as well as the value, so the gates @@ -170,6 +200,7 @@ def update(self, request, *args, **kwargs): def refusal_for(instance, validated_data): data_type = validated_data.get("data_type", instance.data_type) data_value = validated_data.get("data_value", instance.data_value) + _lock_parent(instance.content_object, instance.data_type, data_type) return self.gated_change_refusal( request, _write_changes( @@ -179,6 +210,7 @@ def refusal_for(instance, validated_data): lambda: _change_turns_on_public_link( instance, data_type, data_value ), + lambda: _change_redirects_textit(instance, data_type, data_value), ), ) @@ -187,15 +219,27 @@ def refusal_for(instance, validated_data): ) def destroy(self, request, *args, **kwargs): - """A removed row can uncover another public link row of the form.""" - instance = self.get_object() - refusal = self.gated_change_refusal( - request, - ((GATE_PUBLISH_DATA, lambda: _change_turns_on_public_link(instance)),), - ) - if refusal is not None: - return refusal - self.perform_destroy(instance) + """A removed row can uncover another public link or TextIt row of the + form.""" + with transaction.atomic(): + instance = locked(self.get_object()) + _lock_parent(instance.content_object, instance.data_type) + refusal = self.gated_change_refusal( + request, + ( + ( + GATE_PUBLISH_DATA, + lambda: _change_turns_on_public_link(instance), + ), + ( + GATE_CHANGE_WEBHOOK, + lambda: _change_redirects_textit(instance), + ), + ), + ) + if refusal is not None: + return refusal + self.perform_destroy(instance) return Response(status=status.HTTP_204_NO_CONTENT) def retrieve(self, request, *args, **kwargs): diff --git a/onadata/libs/stepup/drf.py b/onadata/libs/stepup/drf.py index 8cd0821737..a9cbfe24c0 100644 --- a/onadata/libs/stepup/drf.py +++ b/onadata/libs/stepup/drf.py @@ -19,7 +19,7 @@ ) -def _locked(instance): +def locked(instance): """``instance``, locked and read again from its row. Lock through the base manager by primary key, not through the queryset of @@ -33,6 +33,17 @@ def _locked(instance): return instance +def lock_row(model, pk): + """Lock the row of ``model`` with primary key ``pk`` until the transaction + ends. Read no columns of it.""" + # pylint: disable=protected-access + list( + model._base_manager.select_for_update() + .filter(pk=pk) + .values_list("pk", flat=True) + ) + + class RequiresStepUp: """Refuse a gated action unless the request carries a single-use grant. @@ -106,7 +117,7 @@ def gated_update(self, request, refusal_for, partial=False): """ # pylint: disable=no-member with transaction.atomic(): - instance = _locked(self.get_object()) + instance = locked(self.get_object()) serializer = self.get_serializer( instance, data=request.data, partial=partial ) diff --git a/onadata/libs/stepup/sharing.py b/onadata/libs/stepup/sharing.py index 82b0e29d8f..bcadba18f9 100644 --- a/onadata/libs/stepup/sharing.py +++ b/onadata/libs/stepup/sharing.py @@ -81,14 +81,19 @@ def holds_roles(user, granted): def appoints_admins(xform, meta_perms): """Whether applying ``meta_perms`` to ``xform`` makes one of its current - users an owner or manager they are not yet. + users an owner or manager they are not yet by a direct grant. - Applying them re-assigns every user of the form, so writing back an - unchanged value still promotes anyone who reached a slot's role since the - value was last applied.""" + Applying them re-assigns every user of the form whose role is in a slot, + so writing back an unchanged value still promotes anyone who reached a + slot's role since the value was last applied. The new role is a direct + grant, so a role that comes only from a team does not count.""" for user, details in get_xform_users(xform).items(): name = role_under_meta_perms(meta_perms, details["role"]) - if name in ADMIN_ROLE_NAMES and not ROLES[name].user_has_role(user, xform): + if ( + name != details["role"] + and name in ADMIN_ROLE_NAMES + and not holds_roles(user, ((xform, ROLES[name]),)) + ): return True return False From 0765cd1b6a597d7560f4583090830d680d19d8be Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Tue, 1 Dec 2026 13:24:09 +0300 Subject: [PATCH 017/120] fix: keep TextIt destinations on a title-only service edit --- .../viewsets/test_stepup_webhook_gate.py | 56 +++++++++++++++++++ .../viewsets/restservices_viewset.py | 9 +-- onadata/libs/models/textit_service.py | 14 ++++- onadata/libs/serializers/textit_serializer.py | 12 +++- 4 files changed, 84 insertions(+), 7 deletions(-) diff --git a/onadata/apps/restservice/tests/viewsets/test_stepup_webhook_gate.py b/onadata/apps/restservice/tests/viewsets/test_stepup_webhook_gate.py index 037438d97b..e8ad5292cd 100644 --- a/onadata/apps/restservice/tests/viewsets/test_stepup_webhook_gate.py +++ b/onadata/apps/restservice/tests/viewsets/test_stepup_webhook_gate.py @@ -8,14 +8,18 @@ from oidc.stepup_grants import issue_grant, spend_grant +from onadata.apps.api.tests.viewsets.test_merged_xform_viewset import MD from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import ( StepUpGateTestCase, gating, ) +from onadata.apps.api.viewsets.merged_xform_viewset import MergedXFormViewSet +from onadata.apps.logger.models import XForm from onadata.apps.main.models.meta_data import MetaData from onadata.apps.restservice.models import RestService from onadata.apps.restservice.views import add_service from onadata.apps.restservice.viewsets.restservices_viewset import RestServicesViewSet +from onadata.libs.utils.user_auth import get_user_default_project CHANGE_WEBHOOK = "change-webhook" SERVICE_URL = "https://example.com/hook" @@ -202,6 +206,58 @@ def test_a_grant_lets_textit_credentials_change(self): self.assertEqual(response.status_code, 200) self.assertEqual(self._textit_auth_token(), "new-token") + def _merged_dataset(self): + """A merged dataset of two new forms, and those forms.""" + project = get_user_default_project(self.user) + sources = [ + self._publish_markdown(MD, self.user, id_string=id_string) + for id_string in ("a", "b") + ] + request = self.factory.post( + "/", + data={ + "xforms": [ + f"http://testserver/api/v1/forms/{xform.pk}" for xform in sources + ], + "name": "Merged Dataset", + "project": f"http://testserver/api/v1/projects/{project.pk}", + }, + **self.extra, + ) + response = MergedXFormViewSet.as_view({"post": "create"})(request) + self.assertEqual(response.status_code, 201, response.data) + return XForm.objects.get(pk=response.data["id"]), sources + + def test_a_title_edit_keeps_the_settings_of_a_merged_source(self): + """A merged dataset copies its TextIt settings to its source forms. A + title edit sends nothing anywhere new, so it must not overwrite a + source form that sends somewhere else.""" + merged, (source, _other) = self._merged_dataset() + data = { + "name": "textit", + "service_url": "https://textit.io", + "xform": merged.pk, + "auth_token": "token-A", + "flow_uuid": "flow-A", + "contacts": "contacts-A", + } + self.assertEqual( + self._request("post", data, self._grant_header()).status_code, 201 + ) + service = RestService.objects.get(name="textit", xform=merged) + source_settings = "token-S|flow-S|contacts-S" + MetaData.textit(source, data_value=source_settings) + self.assertEqual(MetaData.textit(source), source_settings) + + response = self._request( + "patch", {"name": "textit", "flow_title": "renamed"}, pk=service.pk + ) + + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(response.data["flow_title"], "renamed") + self.assertEqual(MetaData.textit(source), source_settings) + self.assertEqual(MetaData.textit(merged), "token-A|flow-A|contacts-A") + @gating(CHANGE_WEBHOOK) class TestAddServicePageGate(StepUpGateTestCase): diff --git a/onadata/apps/restservice/viewsets/restservices_viewset.py b/onadata/apps/restservice/viewsets/restservices_viewset.py index 6b9ee485c0..96b1e80c91 100644 --- a/onadata/apps/restservice/viewsets/restservices_viewset.py +++ b/onadata/apps/restservice/viewsets/restservices_viewset.py @@ -17,6 +17,9 @@ from onadata.libs.mixins.cache_control_mixin import CacheControlMixin from onadata.libs.mixins.last_modified_mixin import LastModifiedMixin from onadata.libs.serializers.restservices_serializer import RestServiceSerializer +from onadata.libs.serializers.textit_serializer import ( + DESTINATION_FIELDS as TEXTIT_DESTINATION_FIELDS, +) from onadata.libs.serializers.textit_serializer import TextItSerializer from onadata.libs.stepup import RequiresStepUp from onadata.libs.stepup.policy import GATE_CHANGE_WEBHOOK @@ -29,10 +32,6 @@ #: what URL. DESTINATION_FIELDS = ("xform", "name", "service_url") -#: A TextIt service sends to these instead. They live in MetaData, not on the -#: row, so any write to one is gated without comparing it to a stored value. -TEXTIT_DESTINATION_FIELDS = ("auth_token", "flow_uuid", "contacts") - def get_serializer_class(name): """Returns a serilizer class with the given ``name``.""" @@ -55,6 +54,8 @@ def _changes_destination(instance, validated_data) -> bool: ): return True if instance.name == TEXTIT: + # The TextIt fields are not on the row, so any write to one is gated + # without a comparison to a stored value. return any(field in validated_data for field in TEXTIT_DESTINATION_FIELDS) return False diff --git a/onadata/libs/models/textit_service.py b/onadata/libs/models/textit_service.py index 68d56231cc..4c6b9de6cc 100644 --- a/onadata/libs/models/textit_service.py +++ b/onadata/libs/models/textit_service.py @@ -47,10 +47,14 @@ def __init__( self.inactive_reason = "" self.flow_title = flow_title - def save(self): + def save(self, write_destination=True): """ Creates and updates RestService and MetaData objects with textit or rapidpro service properties. + + With ``write_destination`` False, the stored token, flow and contacts + of the form and of the source forms of a merged dataset stay as they + are. """ service = RestService() if not self.pk else RestService.objects.get(pk=self.pk) @@ -72,10 +76,16 @@ def save(self): self.active = service.active self.inactive_reason = service.inactive_reason + MetaData.textit_flow_details(self.xform, data_value=self.flow_title) + if write_destination: + self._save_destination() + + def _save_destination(self): + """Store the token, flow and contacts for the form, and copy them to + the source forms of a merged dataset.""" data_value = f"{self.auth_token}|{self.flow_uuid}|{self.contacts}" MetaData.textit(self.xform, data_value=data_value) - MetaData.textit_flow_details(self.xform, data_value=self.flow_title) if self.xform.is_merged_dataset: for xform in self.xform.mergedxform.xforms.all(): diff --git a/onadata/libs/serializers/textit_serializer.py b/onadata/libs/serializers/textit_serializer.py index 982b5a24f9..115f9da36a 100644 --- a/onadata/libs/serializers/textit_serializer.py +++ b/onadata/libs/serializers/textit_serializer.py @@ -10,6 +10,10 @@ from onadata.libs.serializers.fields.xform_field import XFormField from onadata.libs.utils.common_tags import TEXTIT_DETAILS +#: The fields that say where a TextIt service sends. They live in MetaData, +#: not on the service row. +DESTINATION_FIELDS = ("auth_token", "flow_uuid", "contacts") + class TextItSerializer(serializers.Serializer): """ @@ -63,6 +67,12 @@ def update(self, instance, validated_data): name = validated_data.get("name", instance.name) service_url = validated_data.get("service_url", instance.service_url) + # A merged dataset copies its settings to each source form. An edit + # that keeps the destination must not overwrite the settings of a + # source form that sends somewhere else. + keeps_destination = xform == instance.xform and not any( + field in validated_data for field in DESTINATION_FIELDS + ) instance = TextItService( xform, service_url, @@ -73,7 +83,7 @@ def update(self, instance, validated_data): instance.pk, flow_title=validated_data.get("flow_title"), ) - instance.save() + instance.save(write_destination=not keeps_destination) return instance From a6b79de384eff91c4ad6f97fb0314de85f207668 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Tue, 1 Dec 2026 13:24:09 +0300 Subject: [PATCH 018/120] fix: include entity lists in the project share admin check --- .../viewsets/test_stepup_sharing_gates.py | 26 ++++++++++++++++++- onadata/apps/api/viewsets/project_viewset.py | 12 ++++++--- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py index 67fa0f7959..2acfc3dcbe 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py @@ -22,7 +22,7 @@ from onadata.apps.api.tools import add_user_to_team from onadata.apps.api.viewsets.project_viewset import ProjectViewSet from onadata.apps.api.viewsets.xform_viewset import XFormViewSet -from onadata.apps.logger.models import Project, ProjectInvitation, XForm +from onadata.apps.logger.models import EntityList, Project, ProjectInvitation, XForm from onadata.apps.main.models import MetaData from onadata.libs.models.share_project import ShareProject from onadata.libs.models.share_xform import ShareXForm @@ -188,6 +188,30 @@ def test_a_role_held_only_through_a_team_is_challenged(self): ManagerRole.has_role(get_user_perms(self.alice, self.project), self.project) ) + def test_a_role_not_held_on_an_entity_list_is_challenged(self): + """The share also grants the role on each entity list of the + project, and with it the right to change and delete them.""" + self._publish_xls_form_to_project() + ShareProject(self.project, "alice", ManagerRole.name).save() + entity_list = EntityList.objects.create(name="trees", project=self.project) + for obj in (self.project, self.xform): + self.assertTrue( + ManagerRole.has_role(get_user_perms(self.alice, obj), obj) + ) + self.assertFalse( + ManagerRole.has_role(get_user_perms(self.alice, entity_list), entity_list) + ) + + self.assert_challenged(self._share("alice", ManagerRole.name)) + self.assertFalse( + ManagerRole.has_role(get_user_perms(self.alice, entity_list), entity_list) + ) + + ManagerRole.add(self.alice, entity_list) + response = self._share("alice", ManagerRole.name) + + self.assertEqual(response.status_code, 204) + def test_removing_an_admin_is_not_challenged(self): ShareProject(self.project, "alice", OwnerRole.name).save() self.assertTrue(OwnerRole.user_has_role(self.alice, self.project)) diff --git a/onadata/apps/api/viewsets/project_viewset.py b/onadata/apps/api/viewsets/project_viewset.py index 3e9377c36c..71d68d2538 100644 --- a/onadata/apps/api/viewsets/project_viewset.py +++ b/onadata/apps/api/viewsets/project_viewset.py @@ -295,10 +295,16 @@ def forms(self, request, **kwargs): def _admin_roles_granted(self, role_name): """``(object, role)`` for each owner or manager role sharing the - project as ``role_name`` hands out, on the project or on its forms.""" + project as ``role_name`` hands out, on the project, its forms or its + entity lists.""" role = admin_role(role_name) - on_project = [(self.object, role)] if role else [] - return on_project + admin_roles_granted(self.object.xform_set.all(), role_name) + outright = ( + [(self.object, role)] + + [(entity_list, role) for entity_list in self.object.entity_lists.all()] + if role + else [] + ) + return outright + admin_roles_granted(self.object.xform_set.all(), role_name) def _share_admin_refusal(self, request, validated_data): """Refuse appointing a project owner or manager without a grant. From ffeee7a4bd9aaabdb9a6275017fbc12b7fdd231f Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Tue, 1 Dec 2026 13:24:09 +0300 Subject: [PATCH 019/120] fix: lock the profile through a metadata merge --- .../test_stepup_user_profile_gates.py | 39 +++++++++++++++++++ .../apps/api/viewsets/user_profile_viewset.py | 37 ++++++++++-------- 2 files changed, 60 insertions(+), 16 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_user_profile_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_user_profile_gates.py index 6c1a0b7227..be0d6ef9c0 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_user_profile_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_user_profile_gates.py @@ -9,7 +9,9 @@ from django.conf import settings from django.core.cache import cache +from django.db import connection from django.test import override_settings +from django.test.utils import CaptureQueriesContext from oidc.stepup_grants import issue_grant, spend_grant from registration.models import RegistrationProfile @@ -124,6 +126,43 @@ def test_a_grant_lets_the_consent_record_be_removed(self): profile.refresh_from_db() self.assertIsNone(eu_consent_record(profile.metadata)) + def test_a_merge_reads_the_locked_row_not_the_loaded_copy(self): + """A change can commit after the view loads the profile. The merge + checks and writes the row as it is once locked, and writes only the + metadata, so it keeps the newer consent record and require_auth.""" + stale = UserProfile.objects.get(user=self.user) + newer_require_auth = not stale.require_auth + UserProfile.objects.filter(pk=stale.pk).update( + metadata=self._consent(True), require_auth=newer_require_auth + ) + self.assertIsNone(eu_consent_record(stale.metadata)) + + with ( + patch.object(UserProfileViewSet, "get_object", return_value=stale), + CaptureQueriesContext(connection) as queries, + ): + response = self._patch( + {"metadata": {"city": "Nairobi"}, "overwrite": "false"} + ) + + self.assertEqual(response.status_code, 200, response.data) + profile = UserProfile.objects.get(pk=stale.pk) + self.assertEqual(profile.metadata, {**self._consent(True), "city": "Nairobi"}) + self.assertEqual(profile.require_auth, newer_require_auth) + statements = [query["sql"] for query in queries.captured_queries] + self.assertTrue( + any( + 'FROM "main_userprofile"' in sql and "FOR UPDATE" in sql + for sql in statements + ) + ) + updates = [ + sql for sql in statements if sql.startswith('UPDATE "main_userprofile"') + ] + self.assertTrue(updates) + for update in updates: + self.assertNotIn('"require_auth"', update) + def test_a_put_with_overwrite_false_cannot_change_consent_ungated(self): """PUT ignores overwrite and writes metadata wholesale. An overwrite=false in its body must not skip the gate as it does for a diff --git a/onadata/apps/api/viewsets/user_profile_viewset.py b/onadata/apps/api/viewsets/user_profile_viewset.py index 9c1436028f..f44e2ac1a4 100644 --- a/onadata/apps/api/viewsets/user_profile_viewset.py +++ b/onadata/apps/api/viewsets/user_profile_viewset.py @@ -10,6 +10,7 @@ from django.conf import settings from django.contrib.auth.password_validation import validate_password from django.core.validators import ValidationError +from django.db import transaction from django.db.models import Count from django.http import HttpResponseBadRequest, HttpResponseRedirect from django.utils import timezone @@ -44,6 +45,7 @@ ) from onadata.libs.serializers.user_profile_serializer import UserProfileSerializer from onadata.libs.stepup import RequiresStepUp +from onadata.libs.stepup.drf import locked from onadata.libs.stepup.policy import ( GATE_CHANGE_EMAIL, GATE_CHANGE_PASSWORD, @@ -393,23 +395,26 @@ def _merge_metadata(self, request, username): """Merge the request's metadata into the stored metadata. Writes nothing else, so the consent record is the only gated value it - can change. + can change. The profile row stays locked from the read to the save, + so the merge cannot write back stale metadata over a concurrent + change. """ - profile = self.get_object() - incoming = _parsed_metadata(request.data) - if not isinstance(incoming, dict): - raise ParseError(_("metadata must be a JSON object.")) - # The merge matches keys by name anywhere in the tree, so it can change - # a nested consent leaf the payload never named. Compare the merged - # result for that reason. - metadata = _merged_metadata(profile.metadata, incoming) - if eu_consent_record(metadata) != _stored_eu_consent(profile): - refusal = self.check_step_up(request, GATE_PRIVACY_CONSENT) - if refusal is not None: - return refusal - - profile.metadata = metadata - profile.save() + with transaction.atomic(): + profile = locked(self.get_object()) + incoming = _parsed_metadata(request.data) + if not isinstance(incoming, dict): + raise ParseError(_("metadata must be a JSON object.")) + # The merge matches keys by name anywhere in the tree, so it can + # change a nested consent leaf the payload never named. Compare + # the merged result for that reason. + metadata = _merged_metadata(profile.metadata, incoming) + if eu_consent_record(metadata) != _stored_eu_consent(profile): + refusal = self.check_step_up(request, GATE_PRIVACY_CONSENT) + if refusal is not None: + return refusal + + profile.metadata = metadata + profile.save(update_fields=["metadata", "date_modified"]) request_username = request.user.username if request.user else "" safe_cache_delete(f"{USER_PROFILE_PREFIX}{username}{request_username}") return Response(data=profile.metadata, status=status.HTTP_200_OK) From c1a76db8a0c10b384fb6bb918a1986e577332db4 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Tue, 1 Dec 2026 13:24:09 +0300 Subject: [PATCH 020/120] docs: describe the TextIt and project share gates --- docs/two_factor.rst | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/two_factor.rst b/docs/two_factor.rst index 06cbbecbac..1a9309baa5 100644 --- a/docs/two_factor.rst +++ b/docs/two_factor.rst @@ -309,8 +309,9 @@ Audience Action ``rotate-org-key`` ``POST /api/v1/orgs/{org}/rotate-key`` ``change-username`` a change to ``username`` on ``/api/v1/profiles/{username}`` ``change-webhook`` a new webhook on ``/api/v1/restservices``, or a change - to the place where a webhook sends; a change to the - ``textit`` settings of a form on ``/api/v1/metadata`` + to the place where a webhook sends; a change or a + deletion on ``/api/v1/metadata`` that changes the + ``textit`` settings that apply to a form ``share-form-admin`` a share of a form with the owner or manager role through ``/api/v1/forms/{pk}/share``; a write of the ``xform_meta_perms`` of a form on ``/api/v1/metadata``, @@ -321,7 +322,9 @@ Audience Action managers of the form, unless ``transfer-project`` covers the move ``share-project-admin`` a share of a project with the owner or manager role - through ``/api/v1/projects/{pk}/share`` + through ``/api/v1/projects/{pk}/share``, unless each + user already has that role by a direct grant on the + project, its forms and its entity lists ``invite-project-admin`` an invitation to a project as owner or manager through ``/api/v1/projects/{pk}/invitations`` ``share-team-admin`` a share of a project with a team as owner or manager From f2da6006880066c1f4c0c07ce57bcb6075957f2a Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Tue, 1 Dec 2026 13:26:03 +0300 Subject: [PATCH 021/120] fix: answer 503 when the cache does not store step-up state or a grant --- .../api/tests/viewsets/test_stepup_viewset.py | 14 ++++++++++++++ .../api/tests/viewsets/test_totp_viewset.py | 19 +++++++++++++++++++ onadata/apps/api/viewsets/stepup_viewset.py | 7 ++++--- onadata/apps/api/viewsets/totp_viewset.py | 17 ++++++++++++++--- 4 files changed, 51 insertions(+), 6 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_viewset.py b/onadata/apps/api/tests/viewsets/test_stepup_viewset.py index 6d31aa50b9..b5e14d6001 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_viewset.py @@ -14,6 +14,7 @@ from django.urls import reverse from oidc.stepup_grants import spend_grant +from oidc.utils import CacheWriteFailed from onadata.apps.api.tests.viewsets.test_abstract_viewset import TestAbstractViewSet from onadata.apps.api.viewsets.stepup_viewset import StepUpViewSet @@ -143,6 +144,19 @@ def test_start_reports_a_deployment_with_nowhere_to_send_the_user(self): self.assertEqual(response.status_code, 503) self.assertEqual(response.data["error"], "step_up_unavailable") + @override_settings(STEP_UP=STEP_UP_FEDERATED) + def test_start_reports_a_cache_that_did_not_store_the_state(self): + """Without the state the callback cannot complete, so the user must + not go to the provider. The answer names no detail of the fault.""" + with patch( + "onadata.apps.api.viewsets.stepup_viewset.start_step_up", + side_effect=CacheWriteFailed("the cache did not store the state"), + ): + response = self._start("require-auth-toggle") + + self.assertEqual(response.status_code, 503) + self.assertEqual(response.data, {"error": "step_up_unavailable"}) + @override_settings( STEP_UP=STEP_UP_FEDERATED, STEP_UP_POPUP_ORIGIN="https://app.test" ) diff --git a/onadata/apps/api/tests/viewsets/test_totp_viewset.py b/onadata/apps/api/tests/viewsets/test_totp_viewset.py index 77ff3d465f..dbc14ca7d3 100644 --- a/onadata/apps/api/tests/viewsets/test_totp_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_totp_viewset.py @@ -21,6 +21,7 @@ from cryptography.fernet import Fernet from django_otp.plugins.otp_static.models import StaticDevice from oidc.stepup_grants import spend_grant +from oidc.utils import CacheWriteFailed from rest_framework.authtoken.models import Token from rest_framework.test import APIRequestFactory from two_factor.utils import default_device @@ -725,6 +726,24 @@ def test_verify_issues_a_grant_for_a_gated_action(self): spend_grant(self.user.pk, GATE_REQUIRE_AUTH, response.data["grant"]) ) + def test_verify_reports_a_cache_that_did_not_store_the_grant(self): + """A grant that the cache did not store fails on its first use. The + answer says so, and names no detail of the fault.""" + device = self._enroll() + + with ( + next_totp_window(), + patch( + "onadata.apps.api.viewsets.totp_viewset.issue_grant", + side_effect=CacheWriteFailed("the cache did not store the grant"), + ) as issue, + ): + response = self._verify({"code": current_code(device.key)}) + + issue.assert_called_once_with(self.user.pk, "disable") + self.assertEqual(response.status_code, 503) + self.assertEqual(response.data, {"error": "step_up_unavailable"}) + def test_verify_refuses_an_audience_the_deployment_does_not_know(self): """Omitted and mistyped are the same refusal, and neither costs a code. diff --git a/onadata/apps/api/viewsets/stepup_viewset.py b/onadata/apps/api/viewsets/stepup_viewset.py index c686884155..64777da190 100644 --- a/onadata/apps/api/viewsets/stepup_viewset.py +++ b/onadata/apps/api/viewsets/stepup_viewset.py @@ -6,6 +6,7 @@ from oidc.stepup_grants import issue_grant from oidc.stepup_viewsets import StepUpCallbackMixin +from oidc.utils import CacheWriteFailed from rest_framework import status from rest_framework.authentication import SessionAuthentication, TokenAuthentication from rest_framework.decorators import action @@ -78,9 +79,9 @@ def start(self, request): auth_server = self.step_up_auth_server() try: url, _ = start_step_up(auth_server, audience, request.user) - except (ValueError, KeyError): - # No server carries a STEP_UP block, or the one that does lacks - # its endpoints. + except (ValueError, KeyError, CacheWriteFailed): + # No server carries a STEP_UP block, the one that does lacks its + # endpoints, or the cache did not store the state. logger.exception("step-up: cannot build an authorization request") return Response( {"error": STEP_UP_UNAVAILABLE}, diff --git a/onadata/apps/api/viewsets/totp_viewset.py b/onadata/apps/api/viewsets/totp_viewset.py index 442c0bd355..5b1972631d 100644 --- a/onadata/apps/api/viewsets/totp_viewset.py +++ b/onadata/apps/api/viewsets/totp_viewset.py @@ -10,6 +10,7 @@ import base64 import io +import logging from contextlib import suppress from django.conf import settings @@ -22,6 +23,7 @@ import qrcode from django_otp import devices_for_user from oidc.stepup_grants import issue_grant, spend_grant +from oidc.utils import CacheWriteFailed from rest_framework import status from rest_framework.authentication import SessionAuthentication, TokenAuthentication from rest_framework.decorators import action @@ -46,6 +48,7 @@ get_client_ip, ) from onadata.libs.stepup.capabilities import account_capabilities +from onadata.libs.stepup.challenge import STEP_UP_UNAVAILABLE from onadata.libs.stepup.gate import has_second_factor from onadata.libs.stepup.policy import KNOWN_ACTIONS, is_local_mode from onadata.libs.utils.field_encryption import encrypt @@ -56,6 +59,8 @@ record_verification_failure, ) +logger = logging.getLogger(__name__) + #: Not free-form labels. two_factor matches "default" to decide whether to #: ask for a second factor at all; "backup" is this module's own, and only has #: to agree between the code that writes the recovery set and the code that @@ -766,6 +771,12 @@ def verify(self, request): # pylint: disable=too-many-return-statements status=status.HTTP_403_FORBIDDEN, ) clear_verification_failures(request.user) - return Response( - {"verified": True, "grant": issue_grant(request.user.pk, audience)} - ) + try: + grant = issue_grant(request.user.pk, audience) + except CacheWriteFailed: + logger.exception("step-up: the cache did not store the grant") + return Response( + {"error": STEP_UP_UNAVAILABLE}, + status=status.HTTP_503_SERVICE_UNAVAILABLE, + ) + return Response({"verified": True, "grant": grant}) From 69fea38cad45748dd8e6af32e398eecf64e6bc52 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Tue, 1 Dec 2026 13:26:04 +0300 Subject: [PATCH 022/120] docs: describe the step-up email claim rule and cache failures --- docs/two_factor.rst | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/docs/two_factor.rst b/docs/two_factor.rst index 1a9309baa5..b8acb9dc10 100644 --- a/docs/two_factor.rst +++ b/docs/two_factor.rst @@ -95,7 +95,9 @@ A gated request can also get these answers: an authenticator. - **503** with ``"error": "step_up_unavailable"``. The deployment is in federated mode, but no provider is configured, or the provider has no - endpoints. ``GET /api/v1/stepup/start`` gives the same answer. + endpoints. ``GET /api/v1/stepup/start`` gives the same answer. Start and + ``POST /api/v1/totp/verify`` also give it if the cache does not store the + step-up state or the grant. Try again later. - **400** with ``"error": "one_gated_change_per_request"`` and an ``audiences`` list. The request makes more than one gated change, and one grant cannot cover two gates. Change the values one at a time. The server @@ -403,17 +405,20 @@ profile gets no challenge. with ``not_federated`` in local mode. The callback matches the token to the signed-in user by email. By - default, the token must also set ``email_verified`` to true. If it does - not, the callback refuses the token with ``step_up_failed`` and reason - ``email_unverified``. Without this check, an attacker who has the password - of the user can sign in at the provider with an account that has the - address of the user but not its proof. The attacker then passes step-up - with their own factor. + default, the address that matches must be the ``email`` claim of the + token, and the token must set ``email_verified`` to true. That flag + applies only to the ``email`` claim, so an address that matches through + an ``emails`` list does not pass. If the check fails, the callback refuses + the token with ``step_up_failed`` and reason ``email_unverified``. Without + this check, an attacker who has the password of the user can sign in at + the provider with an account that has the address of the user but not its + proof. The attacker then passes step-up with their own factor. Set ``REQUIRE_VERIFIED_EMAIL`` to ``False`` in the ``STEP_UP`` block only - if the provider proves that the user owns the address in a different way. - The ``CHECK_EMAIL_VERIFIED`` and ``REQUIRE_VERIFIED_EMAIL`` settings of - the provider entry then apply, as they do for login. + if the provider proves that the user owns the address in a different way, + or sends only the ``emails`` list. The ``CHECK_EMAIL_VERIFIED`` and + ``REQUIRE_VERIFIED_EMAIL`` settings of the provider entry then apply, as + they do for login. The callback refuses a token whose ``auth_time`` is before the start of the step-up. If the clock of the provider is behind the clock of this From 367b5a348401319e52c8063c697a59f986d1b372 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Tue, 1 Dec 2026 13:33:06 +0300 Subject: [PATCH 023/120] chore: pin ona-oidc to the latest step-up commit --- requirements/base.in | 2 +- requirements/base.pip | 2 +- requirements/dev.pip | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/requirements/base.in b/requirements/base.in index e64f1b377d..87fa4a3c89 100644 --- a/requirements/base.in +++ b/requirements/base.in @@ -30,7 +30,7 @@ git+https://github.com/onaio/floip-py.git@3c980eb184069ae7c3c9136b18441978237cd4 git+https://github.com/onaio/python-json2xlsclient.git@62b4645f7b4f2684421a13ce98da0331a9dd66a0#egg=python-json2xlsclient # Pinned at the step-up branch tip for stepup_grants, which the totp endpoints # import. Re-pin to a main SHA once onaio/ona-oidc#139 merges. -git+https://github.com/onaio/ona-oidc.git@7e74387171a65b5f6179f0f2023fac38a6d7a643#egg=ona-oidc +git+https://github.com/onaio/ona-oidc.git@e2aed935f4f9c8c595b2709514b72c156d4b5cf3#egg=ona-oidc -e git+https://github.com/onaio/savreaderwriter.git@fix-pep-440-issues#egg=savreaderwriter git+https://git@github.com/onaio/valigetta.git@v0.3.1#egg=valigetta codetiming diff --git a/requirements/base.pip b/requirements/base.pip index 4dbe783f6c..a3161fb133 100644 --- a/requirements/base.pip +++ b/requirements/base.pip @@ -265,7 +265,7 @@ oauthlib==4.0.1 # -r requirements/base.in # django-oauth-toolkit # requests-oauthlib -ona-oidc @ git+https://github.com/onaio/ona-oidc.git@7e74387171a65b5f6179f0f2023fac38a6d7a643 +ona-oidc @ git+https://github.com/onaio/ona-oidc.git@e2aed935f4f9c8c595b2709514b72c156d4b5cf3 # via -r requirements/base.in openpyxl==3.1.5 # via diff --git a/requirements/dev.pip b/requirements/dev.pip index 8557cb7f98..798951a22f 100644 --- a/requirements/dev.pip +++ b/requirements/dev.pip @@ -331,7 +331,7 @@ oauthlib==4.0.1 # -r requirements/base.in # django-oauth-toolkit # requests-oauthlib -ona-oidc @ git+https://github.com/onaio/ona-oidc.git@7e74387171a65b5f6179f0f2023fac38a6d7a643 +ona-oidc @ git+https://github.com/onaio/ona-oidc.git@e2aed935f4f9c8c595b2709514b72c156d4b5cf3 # via -r requirements/base.in openpyxl==3.1.5 # via From 3f3d309c4955ab5fd33451c13673c4b04dad60c0 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 10:16:54 +0300 Subject: [PATCH 024/120] chore: pin ona-oidc to aabe13c --- onadata/libs/stepup/checks.py | 4 ++-- requirements/base.in | 2 +- requirements/base.pip | 2 +- requirements/dev.pip | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/onadata/libs/stepup/checks.py b/onadata/libs/stepup/checks.py index 7891fdaab3..8361f6eda9 100644 --- a/onadata/libs/stepup/checks.py +++ b/onadata/libs/stepup/checks.py @@ -10,10 +10,10 @@ from django.core.exceptions import ImproperlyConfigured from oidc.stepup import ( + binds_to_email_field, find_step_up_auth_server, step_up_config, subject_binding, - subject_binding_is_safe, ) from onadata.libs.stepup.policy import ( @@ -246,7 +246,7 @@ def check_federated_step_up_binds_by_email(app_configs=None, **kwargs): if not gated_actions() or is_local_mode() or server is None: return [] config = step_up_config(server) - if subject_binding_is_safe(config): + if binds_to_email_field(config): return [] _claim, field = subject_binding(config) return [ diff --git a/requirements/base.in b/requirements/base.in index 87fa4a3c89..92ceefbac9 100644 --- a/requirements/base.in +++ b/requirements/base.in @@ -30,7 +30,7 @@ git+https://github.com/onaio/floip-py.git@3c980eb184069ae7c3c9136b18441978237cd4 git+https://github.com/onaio/python-json2xlsclient.git@62b4645f7b4f2684421a13ce98da0331a9dd66a0#egg=python-json2xlsclient # Pinned at the step-up branch tip for stepup_grants, which the totp endpoints # import. Re-pin to a main SHA once onaio/ona-oidc#139 merges. -git+https://github.com/onaio/ona-oidc.git@e2aed935f4f9c8c595b2709514b72c156d4b5cf3#egg=ona-oidc +git+https://github.com/onaio/ona-oidc.git@aabe13ca818f32d93cb795b02ca4643eca80d436#egg=ona-oidc -e git+https://github.com/onaio/savreaderwriter.git@fix-pep-440-issues#egg=savreaderwriter git+https://git@github.com/onaio/valigetta.git@v0.3.1#egg=valigetta codetiming diff --git a/requirements/base.pip b/requirements/base.pip index a3161fb133..ae15d8ed31 100644 --- a/requirements/base.pip +++ b/requirements/base.pip @@ -265,7 +265,7 @@ oauthlib==4.0.1 # -r requirements/base.in # django-oauth-toolkit # requests-oauthlib -ona-oidc @ git+https://github.com/onaio/ona-oidc.git@e2aed935f4f9c8c595b2709514b72c156d4b5cf3 +ona-oidc @ git+https://github.com/onaio/ona-oidc.git@aabe13ca818f32d93cb795b02ca4643eca80d436 # via -r requirements/base.in openpyxl==3.1.5 # via diff --git a/requirements/dev.pip b/requirements/dev.pip index 798951a22f..7f6dab8adf 100644 --- a/requirements/dev.pip +++ b/requirements/dev.pip @@ -331,7 +331,7 @@ oauthlib==4.0.1 # -r requirements/base.in # django-oauth-toolkit # requests-oauthlib -ona-oidc @ git+https://github.com/onaio/ona-oidc.git@e2aed935f4f9c8c595b2709514b72c156d4b5cf3 +ona-oidc @ git+https://github.com/onaio/ona-oidc.git@aabe13ca818f32d93cb795b02ca4643eca80d436 # via -r requirements/base.in openpyxl==3.1.5 # via From 357a7c775eab9d49da41d4e6e3b67aa48c4096fd Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 10:53:13 +0300 Subject: [PATCH 025/120] refactor: leave grant shape checks to spend_grant --- onadata/libs/stepup/gate.py | 7 +------ onadata/libs/tests/stepup/test_drf.py | 16 ++++++---------- 2 files changed, 7 insertions(+), 16 deletions(-) diff --git a/onadata/libs/stepup/gate.py b/onadata/libs/stepup/gate.py index 55ada91e86..e94c9b6c18 100644 --- a/onadata/libs/stepup/gate.py +++ b/onadata/libs/stepup/gate.py @@ -2,7 +2,6 @@ """Whether a request may perform a gated action.""" import logging -import re from django.utils.translation import gettext as _ @@ -30,9 +29,6 @@ #: query strings are written to access logs, browser history and Referer. GRANT_HEADER = "X-Step-Up-Grant" -#: Anything else is not a grant, and would be an invalid memcached key. -_GRANT_SHAPE = re.compile(r"[A-Za-z0-9_-]{1,64}") - class StepUpRefused(Exception): """A gated change was refused where no response can be returned. @@ -144,8 +140,7 @@ def _spend_presented_grant(request, action: str, spent: set): """``None`` once the request's grant for ``action`` is spent, else ``STEP_UP_REQUIRED``.""" presented = _presented_grant(request) - grant = presented if _GRANT_SHAPE.fullmatch(presented) else "" - if spend_grant(request.user.pk, action, grant): + if spend_grant(request.user.pk, action, presented): spent.add(action) _audit( request, diff --git a/onadata/libs/tests/stepup/test_drf.py b/onadata/libs/tests/stepup/test_drf.py index 0c114b38a9..bdef65a2e5 100644 --- a/onadata/libs/tests/stepup/test_drf.py +++ b/onadata/libs/tests/stepup/test_drf.py @@ -1,8 +1,6 @@ # -*- coding: utf-8 -*- """Tests for the DRF gate.""" -from unittest.mock import patch - from django.contrib.auth import get_user_model from django.contrib.auth.models import AnonymousUser from django.core.cache import cache @@ -190,19 +188,17 @@ def test_an_anonymous_request_is_challenged(self): self.assertEqual(refusal.status_code, 401) self.assertEqual(refusal.data["error"], "step_up_required") - def test_a_malformed_grant_is_treated_as_none(self): - """A value that cannot be a grant never reaches the cache, where it - would be an invalid key.""" + def test_a_malformed_grant_is_refused_with_a_challenge(self): + """A value that cannot be a grant is refused, not an error.""" TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) malformed = "not a grant/" + "x" * 300 - with patch("onadata.libs.stepup.gate.spend_grant", return_value=False) as spend: - refusal = self.view.check_step_up( - self._request(HTTP_X_STEP_UP_GRANT=malformed), "require-auth-toggle" - ) + refusal = self.view.check_step_up( + self._request(HTTP_X_STEP_UP_GRANT=malformed), "require-auth-toggle" + ) self.assertEqual(refusal.status_code, 401) - spend.assert_called_once_with(self.user.pk, "require-auth-toggle", "") + self.assertEqual(refusal.data["error"], "step_up_required") @override_settings(STEP_UP=GATED) From f4060c7f62e32035de7a64f2d5545c4a7ba0c578 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 10:53:53 +0300 Subject: [PATCH 026/120] fix: let the factor policy decide two gated changes for a user with no factor --- onadata/libs/stepup/gate.py | 18 +++- onadata/libs/tests/stepup/test_gate.py | 108 ++++++++++++++++++++++++ onadata/libs/tests/stepup/test_pages.py | 93 ++++++++++++++++++++ 3 files changed, 217 insertions(+), 2 deletions(-) create mode 100644 onadata/libs/tests/stepup/test_gate.py create mode 100644 onadata/libs/tests/stepup/test_pages.py diff --git a/onadata/libs/stepup/gate.py b/onadata/libs/stepup/gate.py index e94c9b6c18..bfa3119609 100644 --- a/onadata/libs/stepup/gate.py +++ b/onadata/libs/stepup/gate.py @@ -161,15 +161,29 @@ def _spend_presented_grant(request, action: str, spent: set): return STEP_UP_REQUIRED +def _decided_without_a_grant(request) -> bool: + """Whether the user's lack of a factor decides every gate of this request. + + In local mode a user with no factor is let through or refused by + ``NO_FACTOR_POLICY``, the same way for each action, and a grant changes + nothing.""" + return ( + request.user.is_authenticated + and is_local_mode() + and not has_second_factor(request.user) + ) + + def change_refusal(request, changes) -> tuple: """``(reason, audiences)`` for the gated change among ``changes``, ``(action, changed)`` pairs. ``reason`` is ``None`` to proceed. Spends the grant the request presents. A request with more than one gated - change is refused first, with ``ONE_GATED_CHANGE_PER_REQUEST``. + change is refused with ``ONE_GATED_CHANGE_PER_REQUEST``, unless no grant + could change the answer for this user. """ gated = changed_gated_actions(changes) - if len(gated) > 1: + if len(gated) > 1 and not _decided_without_a_grant(request): return ONE_GATED_CHANGE_PER_REQUEST, gated if not gated: return None, gated diff --git a/onadata/libs/tests/stepup/test_gate.py b/onadata/libs/tests/stepup/test_gate.py new file mode 100644 index 0000000000..7ad93fc8c8 --- /dev/null +++ b/onadata/libs/tests/stepup/test_gate.py @@ -0,0 +1,108 @@ +# -*- coding: utf-8 -*- +"""Tests for onadata.libs.stepup.gate.""" + +from django.contrib.auth import get_user_model +from django.core.cache import cache +from django.test import RequestFactory, TestCase, override_settings + +from django_otp.plugins.otp_totp.models import TOTPDevice + +from onadata.libs.stepup.gate import ( + ENROL_REQUIRED, + ONE_GATED_CHANGE_PER_REQUEST, + STEP_UP_REQUIRED, + change_refusal, + changed_gated_actions, +) +from onadata.libs.stepup.policy import GATE_CHANGE_EMAIL, GATE_REQUIRE_AUTH + +BOTH = (GATE_CHANGE_EMAIL, GATE_REQUIRE_AUTH) +BOTH_CHANGED = ((GATE_CHANGE_EMAIL, True), (GATE_REQUIRE_AUTH, True)) + + +def _local(policy): + return override_settings( + STEP_UP={"MODE": "local", "ACTIONS": list(BOTH), "NO_FACTOR_POLICY": policy} + ) + + +class TestChangeRefusal(TestCase): + """``change_refusal`` with two gated changes in one request.""" + + def setUp(self): + cache.clear() + self.user = get_user_model().objects.create( + username="ana", email="ana@example.org" + ) + self.request = RequestFactory().post("/") + self.request.user = self.user + + @_local("skip_gate") + def test_a_user_with_a_factor_is_refused_two_gated_changes(self): + """One grant cannot cover two gates.""" + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + + reason, audiences = change_refusal(self.request, BOTH_CHANGED) + + self.assertEqual(reason, ONE_GATED_CHANGE_PER_REQUEST) + self.assertEqual(audiences, list(BOTH)) + + @_local("skip_gate") + def test_skip_gate_lets_a_user_with_no_factor_make_two_gated_changes(self): + """Each gate alone lets the user through, so both together do too.""" + self.assertFalse(TOTPDevice.objects.filter(user=self.user).exists()) + + reason, _audiences = change_refusal(self.request, BOTH_CHANGED) + + self.assertIsNone(reason) + + @_local("deny_prompt_enrol") + def test_deny_refuses_a_user_with_no_factor_with_enrol_required(self): + """The user is told to enrol, which no single change would avoid.""" + self.assertFalse(TOTPDevice.objects.filter(user=self.user).exists()) + + reason, _audiences = change_refusal(self.request, BOTH_CHANGED) + + self.assertEqual(reason, ENROL_REQUIRED) + + @_local("skip_gate") + def test_one_gated_change_without_a_grant_is_challenged(self): + """A single gated change asks for a grant.""" + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + + reason, audiences = change_refusal( + self.request, ((GATE_CHANGE_EMAIL, True), (GATE_REQUIRE_AUTH, False)) + ) + + self.assertEqual(reason, STEP_UP_REQUIRED) + self.assertEqual(audiences, [GATE_CHANGE_EMAIL]) + + @_local("skip_gate") + def test_no_gated_change_proceeds(self): + """Unchanged gated values need no grant.""" + reason, audiences = change_refusal( + self.request, ((GATE_CHANGE_EMAIL, False), (GATE_REQUIRE_AUTH, False)) + ) + + self.assertIsNone(reason) + self.assertEqual(audiences, []) + + +class TestChangedGatedActions(TestCase): + """``changed_gated_actions`` evaluates a change only for a gated action.""" + + @override_settings(STEP_UP={"MODE": "local", "ACTIONS": [GATE_CHANGE_EMAIL]}) + def test_a_check_for_an_ungated_action_is_not_called(self): + """A costly check runs only where the deployment gates the action.""" + calls = [] + + def changed(): + calls.append(True) + return True + + gated = changed_gated_actions( + ((GATE_REQUIRE_AUTH, changed), (GATE_CHANGE_EMAIL, changed)) + ) + + self.assertEqual(gated, [GATE_CHANGE_EMAIL]) + self.assertEqual(len(calls), 1) diff --git a/onadata/libs/tests/stepup/test_pages.py b/onadata/libs/tests/stepup/test_pages.py new file mode 100644 index 0000000000..fcaefd6bba --- /dev/null +++ b/onadata/libs/tests/stepup/test_pages.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +"""Tests for onadata.libs.stepup.pages.""" + +from django.contrib.auth import get_user_model +from django.core.cache import cache +from django.test import RequestFactory, TestCase, override_settings + +from django_otp.plugins.otp_totp.models import TOTPDevice + +from onadata.libs.stepup.pages import gated_profile_values, refuse_gated_changes +from onadata.libs.stepup.policy import ( + GATE_CHANGE_EMAIL, + GATE_PRIVACY_CONSENT, + GATE_REQUIRE_AUTH, +) + +BEFORE = gated_profile_values(False, "ana@example.org", {}) +AFTER = gated_profile_values(True, "new@example.org", {}) + + +def _local(policy): + return override_settings( + STEP_UP={ + "MODE": "local", + "ACTIONS": [GATE_CHANGE_EMAIL, GATE_REQUIRE_AUTH], + "NO_FACTOR_POLICY": policy, + } + ) + + +class TestGatedProfileValues(TestCase): + """``gated_profile_values`` keys each value by the audience gating it.""" + + def test_values_are_normalised_and_keyed_by_audience(self): + """Email case and blanks do not count as a change.""" + metadata = {"eu_citizen_consent": {"given": True}} + + values = gated_profile_values(1, " Ana@Example.org ", metadata) + + self.assertEqual( + values, + { + GATE_REQUIRE_AUTH: True, + GATE_CHANGE_EMAIL: "ana@example.org", + GATE_PRIVACY_CONSENT: {"given": True}, + }, + ) + + def test_the_consent_record_is_a_copy(self): + """A later write to the profile does not change the snapshot.""" + metadata = {"eu_citizen_consent": {"given": True}} + values = gated_profile_values(False, "", metadata) + + metadata["eu_citizen_consent"]["given"] = False + + self.assertEqual(values[GATE_PRIVACY_CONSENT], {"given": True}) + + +class TestRefuseGatedChanges(TestCase): + """``refuse_gated_changes`` on a page that changes two gated values.""" + + def setUp(self): + cache.clear() + self.user = get_user_model().objects.create( + username="ana", email="ana@example.org" + ) + self.request = RequestFactory().post("/") + self.request.user = self.user + + @_local("skip_gate") + def test_skip_gate_lets_a_user_with_no_factor_change_both(self): + """Each gate alone lets this user through, so both together do too.""" + self.assertFalse(TOTPDevice.objects.filter(user=self.user).exists()) + + self.assertIsNone(refuse_gated_changes(self.request, BEFORE, AFTER)) + + @_local("skip_gate") + def test_a_user_with_a_factor_changes_one_at_a_time(self): + """One grant cannot cover two gates.""" + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + + response = refuse_gated_changes(self.request, BEFORE, AFTER) + + self.assertEqual(response.status_code, 403) + self.assertIn(b"one protected setting at a time", response.content) + + @_local("deny_prompt_enrol") + def test_deny_tells_a_user_with_no_factor_to_enrol(self): + """The refusal names enrolment, not the number of changes.""" + response = refuse_gated_changes(self.request, BEFORE, AFTER) + + self.assertEqual(response.status_code, 403) + self.assertIn(b"Set up two-factor authentication", response.content) From 9370c1b82fb8a7b96a9238418c5e14d24cf1b76c Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 10:54:27 +0300 Subject: [PATCH 027/120] fix: answer 503 when a gate cannot store the federated step-up state --- onadata/apps/api/viewsets/stepup_viewset.py | 7 ++----- onadata/libs/stepup/challenge.py | 7 ++----- onadata/libs/stepup/federated.py | 14 ++++++++++++++ onadata/libs/tests/stepup/test_challenge.py | 13 +++++++++++++ 4 files changed, 31 insertions(+), 10 deletions(-) diff --git a/onadata/apps/api/viewsets/stepup_viewset.py b/onadata/apps/api/viewsets/stepup_viewset.py index 64777da190..78ada17218 100644 --- a/onadata/apps/api/viewsets/stepup_viewset.py +++ b/onadata/apps/api/viewsets/stepup_viewset.py @@ -6,7 +6,6 @@ from oidc.stepup_grants import issue_grant from oidc.stepup_viewsets import StepUpCallbackMixin -from oidc.utils import CacheWriteFailed from rest_framework import status from rest_framework.authentication import SessionAuthentication, TokenAuthentication from rest_framework.decorators import action @@ -17,7 +16,7 @@ from onadata.libs.authentication import SSOHeaderAuthentication from onadata.libs.stepup.challenge import STEP_UP_UNAVAILABLE -from onadata.libs.stepup.federated import start_step_up +from onadata.libs.stepup.federated import START_FAILURES, start_step_up from onadata.libs.stepup.policy import is_gated, is_local_mode logger = logging.getLogger(__name__) @@ -79,9 +78,7 @@ def start(self, request): auth_server = self.step_up_auth_server() try: url, _ = start_step_up(auth_server, audience, request.user) - except (ValueError, KeyError, CacheWriteFailed): - # No server carries a STEP_UP block, the one that does lacks its - # endpoints, or the cache did not store the state. + except START_FAILURES: logger.exception("step-up: cannot build an authorization request") return Response( {"error": STEP_UP_UNAVAILABLE}, diff --git a/onadata/libs/stepup/challenge.py b/onadata/libs/stepup/challenge.py index 3955671838..28579d53fc 100644 --- a/onadata/libs/stepup/challenge.py +++ b/onadata/libs/stepup/challenge.py @@ -3,11 +3,9 @@ import logging -from django.core.exceptions import ImproperlyConfigured - from oidc.stepup import find_step_up_auth_server -from onadata.libs.stepup.federated import start_step_up +from onadata.libs.stepup.federated import START_FAILURES, start_step_up from onadata.libs.stepup.gate import STEP_UP_REQUIRED from onadata.libs.stepup.policy import is_local_mode @@ -51,8 +49,7 @@ def build_challenge(action: str, user=None) -> dict: try: url, _ = start_step_up(auth_server, action, user) - except (ValueError, KeyError, TypeError, ImproperlyConfigured): - # The auth server is missing or malformed. Answer instead of raising. + except START_FAILURES: logger.exception("step-up: cannot build an authorization request") body["error"] = STEP_UP_UNAVAILABLE return body diff --git a/onadata/libs/stepup/federated.py b/onadata/libs/stepup/federated.py index b240284711..dadc1dfb5b 100644 --- a/onadata/libs/stepup/federated.py +++ b/onadata/libs/stepup/federated.py @@ -5,7 +5,21 @@ carries across the redirect. """ +from django.core.exceptions import ImproperlyConfigured + from oidc.stepup import build_step_up_url +from oidc.utils import CacheWriteFailed + +#: What ``start_step_up`` raises when it cannot send the user to the provider: +#: no server carries a ``STEP_UP`` block, the one that does is malformed, or +#: the cache did not store the state. A caller answers 503 for each. +START_FAILURES = ( + ValueError, + KeyError, + TypeError, + ImproperlyConfigured, + CacheWriteFailed, +) def start_step_up(auth_server: str, audience: str, user) -> tuple[str, str]: diff --git a/onadata/libs/tests/stepup/test_challenge.py b/onadata/libs/tests/stepup/test_challenge.py index b604f63073..3f01c48e8a 100644 --- a/onadata/libs/tests/stepup/test_challenge.py +++ b/onadata/libs/tests/stepup/test_challenge.py @@ -8,6 +8,8 @@ from django.core.exceptions import ImproperlyConfigured from django.test import TestCase, override_settings +from oidc.utils import CacheWriteFailed + from onadata.libs.stepup.challenge import build_challenge, challenge_header GATED = {"ACTIONS": {"require-auth-toggle"}, "MODE": "local"} @@ -96,6 +98,17 @@ def test_a_server_with_a_malformed_config(self): self.assertEqual(body["error"], "step_up_unavailable") + def test_a_cache_that_does_not_store_the_state(self): + """The gate answers 503 instead of a 500, as the start endpoint does.""" + with patch( + "onadata.libs.stepup.challenge.start_step_up", + side_effect=CacheWriteFailed("the cache did not store the state"), + ): + body = build_challenge("require-auth-toggle", self.user) + + self.assertEqual(body["error"], "step_up_unavailable") + self.assertNotIn("authorizationUrl", body) + def test_a_server_missing_its_endpoints(self): with patch( "onadata.libs.stepup.challenge.start_step_up", From d72fc8f01e1888624146be5e49beb6243ee5214a Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 10:54:47 +0300 Subject: [PATCH 028/120] fix: choose the step-up callback page by the negotiated renderer --- .../apps/api/tests/viewsets/test_stepup_viewset.py | 11 +++++++++++ onadata/apps/api/viewsets/stepup_viewset.py | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_viewset.py b/onadata/apps/api/tests/viewsets/test_stepup_viewset.py index b5e14d6001..783e13e28a 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_viewset.py @@ -187,6 +187,17 @@ def test_a_cancelled_prompt_still_reports_back_to_the_opener(self): self.assertIn("postMessage", body) self.assertIn('"error": "provider_error"', body) + @override_settings( + STEP_UP=STEP_UP_FEDERATED, STEP_UP_POPUP_ORIGIN="https://app.test" + ) + def test_a_wildcard_html_accept_header_gets_the_popup_page(self): + """The page follows DRF's content negotiation, not a substring of + ``Accept``.""" + response = self._callback(accept="text/*", error="access_denied", state="s") + + self.assertEqual(response.status_code, 200) + self.assertIn("postMessage", response.content.decode()) + @override_settings(STEP_UP=STEP_UP_FEDERATED) def test_the_callback_accepts_the_django_session(self): """The popup returning from the provider carries cookies, not a diff --git a/onadata/apps/api/viewsets/stepup_viewset.py b/onadata/apps/api/viewsets/stepup_viewset.py index 78ada17218..a53c289308 100644 --- a/onadata/apps/api/viewsets/stepup_viewset.py +++ b/onadata/apps/api/viewsets/stepup_viewset.py @@ -99,7 +99,7 @@ def callback(self, request): auth_server = str(params.get("auth_server", "")).strip() or None # A browser here is the popup returning from the provider. It needs a # page that hands the result to its opener, not JSON. - popup = "text/html" in request.headers.get("Accept", "") + popup = isinstance(request.accepted_renderer, StaticHTMLRenderer) if not code or not state: # A provider reports a cancelled or failed prompt as ``error``. From 80c6fd516482fd2498eccf9463de777df218678f Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 10:56:17 +0300 Subject: [PATCH 029/120] perf: lock rows for a step-up decision only where an action is gated --- .../viewsets/test_stepup_metadata_gates.py | 17 ++++++++++++++++- .../tests/viewsets/test_stepup_sharing_gates.py | 13 +++++++++++++ onadata/apps/api/viewsets/metadata_viewset.py | 10 ++++++++-- onadata/libs/stepup/drf.py | 17 ++++++++++++----- 4 files changed, 49 insertions(+), 8 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py index ae1adcf78d..0a5e2f7db5 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py @@ -6,7 +6,7 @@ from django.contrib.contenttypes.models import ContentType from django.db import connection -from django.test.utils import CaptureQueriesContext +from django.test.utils import CaptureQueriesContext, override_settings from guardian.shortcuts import get_user_perms @@ -570,3 +570,18 @@ def test_a_textit_delete_locks_the_form(self): self.assertEqual(response.status_code, 204) self.assert_form_locked_before_write(queries, 'DELETE FROM "main_metadata"') + + @override_settings(STEP_UP={"MODE": "local", "ACTIONS": []}) + def test_an_update_takes_no_lock_where_nothing_is_gated(self): + """No gate reads the other rows, so nothing needs the lock.""" + (row,) = _rows(self.xform, "public_link", ("False",)) + + with CaptureQueriesContext(connection) as queries: + response = self._update( + row, {"data_type": "public_link", "data_value": "True"} + ) + + self.assertEqual(response.status_code, 200, response.data) + self.assertFalse( + any("FOR UPDATE" in query["sql"] for query in queries.captured_queries) + ) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py index 2acfc3dcbe..0f7ddff086 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py @@ -700,6 +700,19 @@ def test_the_gate_reads_the_locked_row_not_the_loaded_copy(self): self.assertEqual(self.project.name, "demo") self.assertTrue(self.project.shared) + @override_settings(STEP_UP={"MODE": "local", "ACTIONS": []}) + def test_an_update_takes_no_lock_where_nothing_is_gated(self): + """Without a gate there is no decision to hold the row for.""" + with CaptureQueriesContext(connection) as queries: + response = self._patch({"name": "renamed"}) + + self.assertEqual(response.status_code, 200) + self.assertFalse( + any("FOR UPDATE" in query["sql"] for query in queries.captured_queries) + ) + self._reload() + self.assertEqual(self.project.name, "renamed") + def test_an_invalid_update_keeps_the_grant(self): """Validation comes first, so a blank name does not spend it.""" self.assert_challenged(self._patch({"public": True})) diff --git a/onadata/apps/api/viewsets/metadata_viewset.py b/onadata/apps/api/viewsets/metadata_viewset.py index a808b9df63..73eea16d60 100644 --- a/onadata/apps/api/viewsets/metadata_viewset.py +++ b/onadata/apps/api/viewsets/metadata_viewset.py @@ -31,6 +31,7 @@ GATE_CHANGE_WEBHOOK, GATE_PUBLISH_DATA, GATE_SHARE_FORM_ADMIN, + gated_actions, ) from onadata.libs.stepup.sharing import appoints_admins from onadata.libs.utils.common_tags import TEXTIT, XFORM_META_PERMS @@ -85,8 +86,13 @@ def _lock_parent(content_object, *data_types): write of ``data_types`` reads the other metadata rows of that object. Such writes then run one at a time, from the gate decision to the end of - the write. Each one sees the rows that the one before it left.""" - if content_object is not None and FIRST_ROW_TYPES.intersection(data_types): + the write. Each one sees the rows that the one before it left. Only a + gate reads those rows, so a deployment that gates nothing takes no lock.""" + if ( + content_object is not None + and FIRST_ROW_TYPES.intersection(data_types) + and gated_actions() + ): lock_row(type(content_object), content_object.pk) diff --git a/onadata/libs/stepup/drf.py b/onadata/libs/stepup/drf.py index a9cbfe24c0..28ff9a9125 100644 --- a/onadata/libs/stepup/drf.py +++ b/onadata/libs/stepup/drf.py @@ -1,6 +1,8 @@ # -*- coding: utf-8 -*- """Viewset mixin turning a policy decision into a step-up challenge.""" +from contextlib import nullcontext + from django.db import transaction from rest_framework import status @@ -17,6 +19,7 @@ change_refusal, refusal_reason, ) +from onadata.libs.stepup.policy import gated_actions def locked(instance): @@ -111,13 +114,17 @@ def gated_update(self, request, refusal_for, partial=False): Response to answer instead. Validating first means a request the write would reject is answered 400 before any grant is spent. - The row stays locked from the gate decision to the end of the save. A - concurrent change, such as an unpublish, cannot come between them, and - the save cannot write back a value that the gate did not see. + Where the deployment gates any action, the row stays locked from the + gate decision to the end of the save. A concurrent change, such as an + unpublish, cannot come between them, and the save cannot write back a + value that the gate did not see. """ # pylint: disable=no-member - with transaction.atomic(): - instance = locked(self.get_object()) + gating = bool(gated_actions()) + with transaction.atomic() if gating else nullcontext(): + instance = self.get_object() + if gating: + instance = locked(instance) serializer = self.get_serializer( instance, data=request.data, partial=partial ) From 9d848d8a7f27d811d5c580e05c5f72e3240ef7d9 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 10:58:53 +0300 Subject: [PATCH 030/120] perf: read a share's existing roles in one query per model --- onadata/apps/api/viewsets/team_viewset.py | 7 +- onadata/libs/stepup/sharing.py | 78 ++++++++++++++----- onadata/libs/tests/stepup/test_sharing.py | 93 +++++++++++++++++++++++ 3 files changed, 157 insertions(+), 21 deletions(-) create mode 100644 onadata/libs/tests/stepup/test_sharing.py diff --git a/onadata/apps/api/viewsets/team_viewset.py b/onadata/apps/api/viewsets/team_viewset.py index 631ef0a126..01be027d5f 100644 --- a/onadata/apps/api/viewsets/team_viewset.py +++ b/onadata/apps/api/viewsets/team_viewset.py @@ -7,7 +7,6 @@ from django.contrib.auth import get_user_model from django.utils.translation import gettext as _ -from guardian.shortcuts import get_perms from rest_framework import status from rest_framework.decorators import action from rest_framework.exceptions import PermissionDenied @@ -43,6 +42,7 @@ ) from onadata.libs.stepup.sharing import ( grants_admin_role, + holds_roles, reapplying_appoints_admins, team_reaches_admin_role, ) @@ -58,9 +58,8 @@ def _team_holds_role(team, project, role): """Whether sharing ``project`` with ``team`` as ``role`` would grant nothing new. A share also applies the role to every form in the project, so the forms are checked as well.""" - return all( - role.has_role(get_perms(team, obj), obj) - for obj in chain([project], project.xform_set.all()) + return holds_roles( + team, [(obj, role) for obj in chain([project], project.xform_set.all())] ) diff --git a/onadata/libs/stepup/sharing.py b/onadata/libs/stepup/sharing.py index bcadba18f9..4e2e07412a 100644 --- a/onadata/libs/stepup/sharing.py +++ b/onadata/libs/stepup/sharing.py @@ -2,9 +2,12 @@ """Which owner and manager roles a share, a team or organisation join, a form move or a meta permissions write hands out, and to whom.""" +from django.contrib.auth.models import Group from django.contrib.contenttypes.models import ContentType +from django.core.exceptions import FieldDoesNotExist from guardian.shortcuts import get_objects_for_group, get_perms, get_user_perms +from guardian.utils import get_group_obj_perms_model, get_user_obj_perms_model from onadata.apps.logger.models import Project, XForm from onadata.apps.main.models import MetaData @@ -70,13 +73,48 @@ def admin_role(role_name): return ROLES[role_name] if role_name in ADMIN_ROLE_NAMES else None -def holds_roles(user, granted): - """Whether ``user`` already holds every ``(obj, role)`` in ``granted`` by a - direct grant, so a share granting them hands out nothing new. - - A share writes direct grants. A role that comes only from a team does not - count, because the direct grant stays after the user leaves the team.""" - return all(role.has_role(get_user_perms(user, obj), obj) for obj, role in granted) +def _direct_perms_on_model(holder, instances) -> dict: + """The codenames ``holder``, a user or a group, holds by a direct grant on + each of ``instances``, all of one model, keyed by primary key.""" + if isinstance(holder, Group): + field, perms_model = "group", get_group_obj_perms_model(instances[0]) + else: + field, perms_model = "user", get_user_obj_perms_model(instances[0]) + try: + # pylint: disable=protected-access + perms_model._meta.get_field("object_pk") + except FieldDoesNotExist: + rows = perms_model.objects.filter( + **{f"{field}_id": holder.pk}, + content_object_id__in=[instance.pk for instance in instances], + ).values_list("content_object_id", "permission__codename") + held = {} + for pk, codename in rows: + held.setdefault(pk, set()).add(codename) + return held + read = get_perms if field == "group" else get_user_perms + return {instance.pk: set(read(holder, instance)) for instance in instances} + + +def holds_roles(holder, granted): + """Whether ``holder``, a user or a group, already holds every + ``(obj, role)`` in ``granted`` by a direct grant, so a share granting them + hands out nothing new. + + A share writes direct grants. A user's role that comes only from a team + does not count, because the direct grant stays after the user leaves the + team. Reads one query per model in ``granted``.""" + by_model = {} + for obj, _role in granted: + by_model.setdefault(type(obj), []).append(obj) + held = { + (model, pk): codenames + for model, instances in by_model.items() + for pk, codenames in _direct_perms_on_model(holder, instances).items() + } + return all( + role.has_role(held.get((type(obj), obj.pk), ()), obj) for obj, role in granted + ) def appoints_admins(xform, meta_perms): @@ -87,26 +125,32 @@ def appoints_admins(xform, meta_perms): so writing back an unchanged value still promotes anyone who reached a slot's role since the value was last applied. The new role is a direct grant, so a role that comes only from a team does not count.""" + promoted = [] for user, details in get_xform_users(xform).items(): name = role_under_meta_perms(meta_perms, details["role"]) - if ( - name != details["role"] - and name in ADMIN_ROLE_NAMES - and not holds_roles(user, ((xform, ROLES[name]),)) - ): - return True - return False + if name != details["role"] and name in ADMIN_ROLE_NAMES: + promoted.append((user, ROLES[name])) + if not promoted: + return False + held = {} + for user_id, codename in xform.xformuserobjectpermission_set.filter( + user__in=[user for user, _role in promoted] + ).values_list("user_id", "permission__codename"): + held.setdefault(user_id, set()).add(codename) + return any( + not role.has_role(held.get(user.pk, ()), xform) for user, role in promoted + ) def reapplying_appoints_admins(xforms): """Whether re-applying the stored meta permissions of any of ``xforms`` makes one of its users an owner or manager they are not yet.""" + xforms = list(xforms) + stored = _stored_meta_perms(xforms) return any( appoints_admins(xform, meta_perms) for xform in xforms - for meta_perms in xform.metadata_set.filter( - data_type=XFORM_META_PERMS - ).values_list("data_value", flat=True) + for meta_perms in stored.get(xform.pk, ()) ) diff --git a/onadata/libs/tests/stepup/test_sharing.py b/onadata/libs/tests/stepup/test_sharing.py new file mode 100644 index 0000000000..48bb9573fa --- /dev/null +++ b/onadata/libs/tests/stepup/test_sharing.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +"""Tests for onadata.libs.stepup.sharing.""" + +from onadata.apps.api.models.organization_profile import create_organization_team +from onadata.apps.api.tests.viewsets.test_abstract_viewset import TestAbstractViewSet +from onadata.apps.logger.models import EntityList +from onadata.apps.main.models import MetaData +from onadata.libs.permissions import EditorRole, ManagerRole, OwnerRole +from onadata.libs.stepup.sharing import ( + holds_roles, + reapplying_appoints_admins, +) + + +class SharingTestCase(TestAbstractViewSet): + """A project of ``self.user`` with two entity lists, and a user alice.""" + + def setUp(self): + super().setUp() + self._project_create() + self.entity_lists = [ + EntityList.objects.create(name=name, project=self.project) + for name in ("trees", "wells") + ] + self.alice = self._create_user_profile( + {"username": "alice", "email": "alice@localhost.com"} + ).user + + def _granted(self, role): + return [(self.project, role)] + [(item, role) for item in self.entity_lists] + + +class TestHoldsRoles(SharingTestCase): + """``holds_roles`` reads direct grants only.""" + + def test_a_user_holding_every_role_directly_holds_them(self): + """A share that repeats every role hands out nothing new.""" + for obj, role in self._granted(ManagerRole): + role.add(self.alice, obj) + + self.assertTrue(holds_roles(self.alice, self._granted(ManagerRole))) + + def test_a_role_missing_on_one_object_is_not_held(self): + """One entity list without the role is enough to need a grant.""" + ManagerRole.add(self.alice, self.project) + ManagerRole.add(self.alice, self.entity_lists[0]) + + self.assertFalse(holds_roles(self.alice, self._granted(ManagerRole))) + + def test_a_role_held_through_a_team_does_not_count(self): + """The direct grant a share writes outlives the team membership.""" + team = create_organization_team(self.user, "admins") + team.user_set.add(self.alice) + for obj, role in self._granted(ManagerRole): + role.add(team, obj) + + self.assertTrue(holds_roles(team, self._granted(ManagerRole))) + self.assertFalse(holds_roles(self.alice, self._granted(ManagerRole))) + + def test_the_check_reads_one_query_per_model(self): + """Many objects of one model cost one query, not one each.""" + for obj, role in self._granted(OwnerRole): + role.add(self.alice, obj) + granted = self._granted(OwnerRole) + self.assertEqual(len(granted), 3) + # Content types are cached after the first lookup. + holds_roles(self.alice, granted) + + with self.assertNumQueries(2): + self.assertTrue(holds_roles(self.alice, granted)) + + +class TestReapplyingAppointsAdmins(SharingTestCase): + """``reapplying_appoints_admins`` finds a user that stored meta + permissions would promote.""" + + def setUp(self): + super().setUp() + self._publish_xls_form_to_project() + EditorRole.add(self.alice, self.xform) + MetaData.xform_meta_permission( + self.xform, data_value="owner|dataentry-only|readonly" + ) + + def test_an_editor_the_meta_permissions_make_an_owner(self): + """Re-applying the value makes alice an owner.""" + self.assertTrue(reapplying_appoints_admins([self.xform])) + + def test_an_editor_who_is_already_an_owner(self): + """Alice already holds the role, so nothing new is handed out.""" + OwnerRole.add(self.alice, self.xform) + + self.assertFalse(reapplying_appoints_admins([self.xform])) From a074e75b3f15b9c233c9ac231009ed9026109802 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 10:58:53 +0300 Subject: [PATCH 031/120] fix: include entity lists in the organisation member admin check --- onadata/libs/stepup/sharing.py | 11 +++++---- onadata/libs/tests/stepup/test_sharing.py | 29 ++++++++++++++++++++++- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/onadata/libs/stepup/sharing.py b/onadata/libs/stepup/sharing.py index 4e2e07412a..6b27297a52 100644 --- a/onadata/libs/stepup/sharing.py +++ b/onadata/libs/stepup/sharing.py @@ -225,10 +225,10 @@ def member_admin_roles(projects, members_team, user, role_name): organisation's projects. Mirrors ``add_user_to_organization``, which also runs for an existing - member. Each project is shared at the members team's role on it. An owner - gets ``role_name`` on every project, and a manager gets it on the projects - they created.""" - projects = list(projects.prefetch_related("xform_set")) + member. Each project is shared at the members team's role on it, with its + forms and entity lists. An owner gets ``role_name`` on every project, and + a manager gets it on the projects they created.""" + projects = list(projects.prefetch_related("xform_set", "entity_lists")) stored = _stored_meta_perms( [xform for project in projects for xform in project.xform_set.all()] ) @@ -238,6 +238,9 @@ def member_admin_roles(projects, members_team, user, role_name): role = admin_role(shared) if role is not None: granted.append((project, role)) + granted.extend( + (entity_list, role) for entity_list in project.entity_lists.all() + ) granted.extend( admin_roles_granted(project.xform_set.all(), shared, stored=stored) ) diff --git a/onadata/libs/tests/stepup/test_sharing.py b/onadata/libs/tests/stepup/test_sharing.py index 48bb9573fa..2fbf920c50 100644 --- a/onadata/libs/tests/stepup/test_sharing.py +++ b/onadata/libs/tests/stepup/test_sharing.py @@ -1,13 +1,17 @@ # -*- coding: utf-8 -*- """Tests for onadata.libs.stepup.sharing.""" -from onadata.apps.api.models.organization_profile import create_organization_team +from onadata.apps.api.models.organization_profile import ( + create_organization_team, + get_organization_members_team, +) from onadata.apps.api.tests.viewsets.test_abstract_viewset import TestAbstractViewSet from onadata.apps.logger.models import EntityList from onadata.apps.main.models import MetaData from onadata.libs.permissions import EditorRole, ManagerRole, OwnerRole from onadata.libs.stepup.sharing import ( holds_roles, + member_admin_roles, reapplying_appoints_admins, ) @@ -70,6 +74,29 @@ def test_the_check_reads_one_query_per_model(self): self.assertTrue(holds_roles(self.alice, granted)) +class TestMemberAdminRoles(SharingTestCase): + """``member_admin_roles`` mirrors what adding an organisation member + shares.""" + + def test_an_owner_is_shared_the_entity_lists_too(self): + """``ShareProject`` gives the role on entity lists as well.""" + self._org_create() + self.project.organization = self.organization.user + self.project.save() + members_team = get_organization_members_team(self.organization) + + granted = member_admin_roles( + self.organization.user.project_org.all(), + members_team, + self.alice, + OwnerRole.name, + ) + + self.assertIn((self.project, OwnerRole), granted) + for entity_list in self.entity_lists: + self.assertIn((entity_list, OwnerRole), granted) + + class TestReapplyingAppointsAdmins(SharingTestCase): """``reapplying_appoints_admins`` finds a user that stored meta permissions would promote.""" From 0c8c782ae7be1f599e4b9e11c64708e70a56aee3 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:00:35 +0300 Subject: [PATCH 032/120] fix: stop the start on federated step-up with no server or a bad provider block --- docs/two_factor.rst | 15 ++- onadata/libs/apps.py | 4 + onadata/libs/stepup/checks.py | 86 ++++++++++++++-- onadata/libs/tests/stepup/test_checks.py | 119 ++++++++++++++++++++++- 4 files changed, 207 insertions(+), 17 deletions(-) diff --git a/docs/two_factor.rst b/docs/two_factor.rst index b8acb9dc10..8c46010aee 100644 --- a/docs/two_factor.rst +++ b/docs/two_factor.rst @@ -452,14 +452,18 @@ then hide the controls that do not apply:: The startup checks report a step-up configuration that will not work as intended. A WSGI server does not run the checks. Thus, the WSGI application -does not load if a step-up check reports an error. ``manage.py check`` shows -all results. +does not load if a step-up check, or the ona-oidc check of the ``STEP_UP`` +block of the provider (``oidc.E003``), reports an error. ``manage.py check`` +shows all results. - ``stepup.E001`` (error). ``STEP_UP`` is not a dict, or its ``ACTIONS`` is not a list of action names. Step-up then gates nothing. - ``stepup.E002`` (error). ``STEP_UP["ACTIONS"]`` names an action that no gate checks, in either mode. A misspelt action leaves the intended action ungated. +- ``stepup.E004`` (error). Federated actions are gated, but no server in + ``OPENID_CONNECT_AUTH_SERVERS`` has a ``STEP_UP`` block. Each gated action + then answers **503**. - ``stepup.W001``. Actions are gated, but ``skip_gate`` lets users with no factor through. - ``stepup.W003``. ``STEP_UP["MODE"]`` is not ``local`` or ``federated``. @@ -473,13 +477,16 @@ all results. Step-up identifies the user by email, so an ungated email change can defeat each gate. - ``stepup.W007``. Federated step-up identifies the user by a field other - than email, such as the username. A user can change that field without - step-up. + than email. A user can change that field without step-up. A username + binding does not cause the warning if ``change-username`` is gated. - ``stepup.W008``. ``STEP_UP["NO_FACTOR_POLICY"]`` is not ``skip_gate`` or ``deny_prompt_enrol``. Step-up then refuses users with no factor. - ``stepup.W009``. ``authorize-oauth-app`` is gated, but the OAuth pages cannot run a challenge. Thus, they refuse each approval that the gate challenges. +- ``stepup.W010``. Federated actions are gated, but + ``STEP_UP_POPUP_ORIGIN`` is not set. The callback page then cannot give a + grant to a browser. Sign in ------- diff --git a/onadata/libs/apps.py b/onadata/libs/apps.py index 87728c5d0d..57b7e7b856 100644 --- a/onadata/libs/apps.py +++ b/onadata/libs/apps.py @@ -19,6 +19,8 @@ def ready(self): STEP_UP_CHECK_TAG, check_federated_step_up_binds_by_email, check_federated_step_up_gates_email, + check_federated_step_up_has_a_popup_origin, + check_federated_step_up_has_a_server, check_oauth_approval_can_step_up, check_removed_enrolment_password_setting, check_step_up_actions_are_known, @@ -39,6 +41,8 @@ def ready(self): check_removed_enrolment_password_setting, check_federated_step_up_gates_email, check_federated_step_up_binds_by_email, + check_federated_step_up_has_a_server, + check_federated_step_up_has_a_popup_origin, check_oauth_approval_can_step_up, ): register(check, STEP_UP_CHECK_TAG) diff --git a/onadata/libs/stepup/checks.py b/onadata/libs/stepup/checks.py index 8361f6eda9..cc0f981537 100644 --- a/onadata/libs/stepup/checks.py +++ b/onadata/libs/stepup/checks.py @@ -9,6 +9,7 @@ from django.core.checks import run_checks from django.core.exceptions import ImproperlyConfigured +from oidc.checks import check_step_up_configuration from oidc.stepup import ( binds_to_email_field, find_step_up_auth_server, @@ -19,6 +20,7 @@ from onadata.libs.stepup.policy import ( GATE_AUTHORIZE_OAUTH_APP, GATE_CHANGE_EMAIL, + GATE_CHANGE_USERNAME, KNOWN_ACTIONS, KNOWN_MODES, KNOWN_NO_FACTOR_POLICIES, @@ -40,11 +42,16 @@ def require_valid_step_up_settings(): A WSGI server loads Django but does not run the system checks. Call this after the WSGI application loads, so that a server whose ``STEP_UP`` - leaves an action ungated does not start. + leaves an action ungated does not start. ona-oidc's check of the + provider's ``STEP_UP`` block (``oidc.E003``) counts too. """ + messages = [ + *run_checks(tags=[STEP_UP_CHECK_TAG]), + *check_step_up_configuration(), + ] errors = [ message - for message in run_checks(tags=[STEP_UP_CHECK_TAG]) + for message in messages if message.is_serious() and not message.is_silenced() ] if errors: @@ -193,15 +200,72 @@ def check_step_up_mode_is_known(app_configs=None, **kwargs): ] +def _binding_config(): + """The ``STEP_UP`` block of the federated step-up server, or None.""" + server = find_step_up_auth_server() + return None if server is None else step_up_config(server) + + +def check_federated_step_up_has_a_server(app_configs=None, **kwargs): + # pylint: disable=unused-argument + """Federated step-up sends the user to the server whose entry in + ``OPENID_CONNECT_AUTH_SERVERS`` carries a ``STEP_UP`` block. + + Without one, every gated action answers 503. + """ + if not gated_actions() or is_local_mode() or find_step_up_auth_server(): + return [] + return [ + CheckError( + "Federated step-up gates actions, but no server in " + "OPENID_CONNECT_AUTH_SERVERS has a STEP_UP block: every gated " + "action answers 503.", + hint="Add a STEP_UP block to the provider's entry in " + "OPENID_CONNECT_AUTH_SERVERS, or empty STEP_UP['ACTIONS'].", + id="stepup.E004", + ) + ] + + +def check_federated_step_up_has_a_popup_origin(app_configs=None, **kwargs): + # pylint: disable=unused-argument + """The callback page posts the grant only to ``STEP_UP_POPUP_ORIGIN``. + + Without it, a browser that steps up in a popup gets an error page and no + grant. + """ + if ( + not gated_actions() + or is_local_mode() + or getattr(settings, "STEP_UP_POPUP_ORIGIN", "") + ): + return [] + return [ + CheckWarning( + "Federated step-up gates actions, but STEP_UP_POPUP_ORIGIN is not " + "set: the callback page cannot hand a grant to a browser.", + hint="Set STEP_UP_POPUP_ORIGIN to the origin of the client that " + "opens the step-up popup.", + id="stepup.W010", + ) + ] + + def check_federated_step_up_gates_email(app_configs=None, **kwargs): # pylint: disable=unused-argument - """Federated step-up matches the provider's token to the account email. + """Federated step-up bound to the email matches the provider's token to + the account email. If changing the email is not gated, a stolen session can point it at the attacker's provider account and pass every gate. """ actions = gated_actions() - if not actions or is_local_mode() or GATE_CHANGE_EMAIL in actions: + if ( + not actions + or is_local_mode() + or GATE_CHANGE_EMAIL in actions + or not binds_to_email_field(_binding_config()) + ): return [] return [ CheckWarning( @@ -236,25 +300,27 @@ def check_removed_enrolment_password_setting(app_configs=None, **kwargs): def check_federated_step_up_binds_by_email(app_configs=None, **kwargs): # pylint: disable=unused-argument - """Step-up can identify the user by another field, but only the email - is gated against change. + """Step-up can identify the user by another field. Only the email, and + the username where ``change-username`` is gated, need a grant to change. A stolen session can rename the account to match the attacker's own provider account, then pass every gate with the attacker's own factor. """ - server = find_step_up_auth_server() - if not gated_actions() or is_local_mode() or server is None: + config = _binding_config() + if not gated_actions() or is_local_mode() or config is None: return [] - config = step_up_config(server) if binds_to_email_field(config): return [] _claim, field = subject_binding(config) + if field == "username" and GATE_CHANGE_USERNAME in gated_actions(): + return [] return [ CheckWarning( f"Federated step-up identifies the user by {field!r}, which a " "user can change without step-up.", hint="Remove SUBJECT_CLAIM and SUBJECT_FIELD from the STEP_UP " - "block so step-up identifies the user by email.", + "block so step-up identifies the user by email, or bind to the " + f"username and gate {GATE_CHANGE_USERNAME!r}.", id="stepup.W007", ) ] diff --git a/onadata/libs/tests/stepup/test_checks.py b/onadata/libs/tests/stepup/test_checks.py index 923d566d2d..9710579f36 100644 --- a/onadata/libs/tests/stepup/test_checks.py +++ b/onadata/libs/tests/stepup/test_checks.py @@ -8,6 +8,8 @@ STEP_UP_CHECK_TAG, check_federated_step_up_binds_by_email, check_federated_step_up_gates_email, + check_federated_step_up_has_a_popup_origin, + check_federated_step_up_has_a_server, check_oauth_approval_can_step_up, check_removed_enrolment_password_setting, check_step_up_actions_are_known, @@ -22,6 +24,8 @@ ALL_CHECKS = ( check_federated_step_up_binds_by_email, check_federated_step_up_gates_email, + check_federated_step_up_has_a_popup_origin, + check_federated_step_up_has_a_server, check_oauth_approval_can_step_up, check_removed_enrolment_password_setting, check_step_up_actions_are_known, @@ -33,6 +37,10 @@ ) +def _servers(**step_up): + return {"idp": {"STEP_UP": {"REDIRECT_URI": "https://app.test/cb", **step_up}}} + + class TestRequireValidStepUpSettings(SimpleTestCase): """The WSGI module calls this, because a WSGI server runs no checks.""" @@ -62,6 +70,31 @@ def test_a_warning_does_not_stop_the_start(self): require_valid_step_up_settings() + @override_settings( + STEP_UP={"ACTIONS": ["change-email"], "MODE": "federated"}, + OPENID_CONNECT_AUTH_SERVERS={ + "idp": {"STEP_UP": {"REDIRECT_URI": "https://app.test/cb"}} + }, + STEP_UP_POPUP_ORIGIN="https://app.test", + ) + def test_an_error_in_the_providers_step_up_block_stops_the_start(self): + """ona-oidc tags ``oidc.E003`` as a security check, not a step-up + one.""" + step_up_ids = {m.id for m in run_checks(tags=[STEP_UP_CHECK_TAG])} + self.assertNotIn("oidc.E003", step_up_ids) + + with self.assertRaisesMessage(ImproperlyConfigured, "oidc.E003"): + require_valid_step_up_settings() + + @override_settings( + STEP_UP={"ACTIONS": ["change-email"], "MODE": "federated"}, + OPENID_CONNECT_AUTH_SERVERS={}, + ) + def test_federated_step_up_with_no_server_stops_the_start(self): + """Every gated action would answer 503.""" + with self.assertRaisesMessage(ImproperlyConfigured, "stepup.E004"): + require_valid_step_up_settings() + def test_every_step_up_check_carries_the_tag(self): for check in ALL_CHECKS: self.assertIn(STEP_UP_CHECK_TAG, check.tags, check.__name__) @@ -193,9 +226,13 @@ def test_a_gated_email_change_is_silent(self): def test_local_mode_is_silent(self): self.assertEqual(check_federated_step_up_gates_email(), []) - -def _servers(**step_up): - return {"idp": {"STEP_UP": {"REDIRECT_URI": "https://app.test/cb", **step_up}}} + @override_settings( + STEP_UP={"MODE": "federated", "ACTIONS": ["regenerate-api-key"]}, + OPENID_CONNECT_AUTH_SERVERS=_servers(SUBJECT_FIELD="username"), + ) + def test_a_binding_to_another_field_is_silent(self): + """``stepup.W007`` reports that binding instead.""" + self.assertEqual(check_federated_step_up_gates_email(), []) class TestFederatedStepUpBindsByEmail(SimpleTestCase): @@ -218,6 +255,14 @@ def test_a_username_binding_is_reported(self): def test_the_default_email_binding_is_silent(self): self.assertEqual(check_federated_step_up_binds_by_email(), []) + @override_settings( + STEP_UP={"MODE": "federated", "ACTIONS": ["change-username"]}, + OPENID_CONNECT_AUTH_SERVERS=_servers(SUBJECT_FIELD="username"), + ) + def test_a_username_binding_with_a_gated_rename_is_silent(self): + """A rename needs a grant, so the binding cannot be repointed.""" + self.assertEqual(check_federated_step_up_binds_by_email(), []) + @override_settings( STEP_UP={"MODE": "local", "ACTIONS": ["change-email"]}, OPENID_CONNECT_AUTH_SERVERS=_servers(SUBJECT_FIELD="username"), @@ -369,3 +414,71 @@ def test_federated_mode_is_reported_too(self): @override_settings(STEP_UP={"ACTIONS": ["change-email"], "MODE": "local"}) def test_other_gates_are_silent(self): self.assertEqual(check_oauth_approval_can_step_up(), []) + + +class TestFederatedStepUpHasAServer(SimpleTestCase): + """Federated step-up needs a server with a ``STEP_UP`` block.""" + + @override_settings( + STEP_UP={"MODE": "federated", "ACTIONS": ["change-email"]}, + OPENID_CONNECT_AUTH_SERVERS={"idp": {"CLIENT_ID": "app"}}, + ) + def test_no_server_with_a_step_up_block_is_reported(self): + """A server without the block does not count.""" + errors = check_federated_step_up_has_a_server() + + self.assertEqual([e.id for e in errors], ["stepup.E004"]) + + @override_settings( + STEP_UP={"MODE": "federated", "ACTIONS": ["change-email"]}, + OPENID_CONNECT_AUTH_SERVERS=_servers(), + ) + def test_a_server_with_a_step_up_block_is_silent(self): + """The gates can send the user to that server.""" + self.assertEqual(check_federated_step_up_has_a_server(), []) + + @override_settings( + STEP_UP={"MODE": "local", "ACTIONS": ["change-email"]}, + OPENID_CONNECT_AUTH_SERVERS={}, + ) + def test_local_mode_is_silent(self): + """Local mode needs no provider.""" + self.assertEqual(check_federated_step_up_has_a_server(), []) + + @override_settings( + STEP_UP={"MODE": "federated", "ACTIONS": []}, + OPENID_CONNECT_AUTH_SERVERS={}, + ) + def test_gating_nothing_is_silent(self): + """No gate sends anyone anywhere.""" + self.assertEqual(check_federated_step_up_has_a_server(), []) + + +class TestFederatedStepUpHasAPopupOrigin(SimpleTestCase): + """The callback page hands the grant only to ``STEP_UP_POPUP_ORIGIN``.""" + + @override_settings( + STEP_UP={"MODE": "federated", "ACTIONS": ["change-email"]}, + STEP_UP_POPUP_ORIGIN="", + ) + def test_a_missing_origin_is_reported(self): + """A browser would get an error page and no grant.""" + warnings = check_federated_step_up_has_a_popup_origin() + + self.assertEqual([w.id for w in warnings], ["stepup.W010"]) + + @override_settings( + STEP_UP={"MODE": "federated", "ACTIONS": ["change-email"]}, + STEP_UP_POPUP_ORIGIN="https://app.test", + ) + def test_a_set_origin_is_silent(self): + """The page can post the grant to the opener.""" + self.assertEqual(check_federated_step_up_has_a_popup_origin(), []) + + @override_settings( + STEP_UP={"MODE": "local", "ACTIONS": ["change-email"]}, + STEP_UP_POPUP_ORIGIN="", + ) + def test_local_mode_is_silent(self): + """Local mode opens no popup.""" + self.assertEqual(check_federated_step_up_has_a_popup_origin(), []) From 145c414f8966e205e6c40ba20435de935274685f Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:00:47 +0300 Subject: [PATCH 033/120] test: turn two-factor on in the federated capabilities case --- onadata/libs/tests/stepup/test_capabilities.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/onadata/libs/tests/stepup/test_capabilities.py b/onadata/libs/tests/stepup/test_capabilities.py index 88319ac913..52c43cd389 100644 --- a/onadata/libs/tests/stepup/test_capabilities.py +++ b/onadata/libs/tests/stepup/test_capabilities.py @@ -7,7 +7,10 @@ SERVERS = {"kc": {"STEP_UP": {"CLAIM": "acr"}}} +#: ENABLE_TWO_FACTOR is on, so the two-factor controls are off because the +#: provider owns the factor, not because two-factor is off. FEDERATED = { + "ENABLE_TWO_FACTOR": True, "STEP_UP": {"MODE": "federated"}, "OPENID_CONNECT_AUTH_SERVERS": SERVERS, "STEP_UP_IDP_NAME": "", @@ -22,6 +25,7 @@ class TestTwoFactorDisabled(TestCase): """ def test_the_two_factor_controls_are_all_unavailable(self): + """Each control is off.""" capabilities = account_capabilities()["twoFactor"] for control in ("enroll", "disable", "recoveryCodes", "verify"): @@ -38,6 +42,7 @@ class TestAccountCapabilities(TestCase): # case tests who manages two-factor, not whether it is on. @override_settings(STEP_UP={"MODE": "local"}, ENABLE_TWO_FACTOR=True) def test_onadata_owning_identity_can_manage_everything(self): + """Local mode with two-factor on offers every control.""" caps = account_capabilities() self.assertTrue(caps["password"]["change"]) @@ -57,8 +62,10 @@ def test_a_federated_deployment_manages_no_credentials(self): self.assertFalse(caps["twoFactor"]["enroll"]) self.assertFalse(caps["twoFactor"]["disable"]) self.assertFalse(caps["twoFactor"]["recoveryCodes"]) + self.assertFalse(caps["twoFactor"]["verify"]) self.assertEqual(caps["identityProvider"], "") @override_settings(**{**FEDERATED, "STEP_UP_IDP_NAME": "Acme SSO"}) def test_a_deployment_fronts_a_name_its_users_recognise(self): + """``STEP_UP_IDP_NAME`` is what the client shows.""" self.assertEqual(account_capabilities()["identityProvider"], "Acme SSO") From 26f32c66cbdb6154c4f7d9f17024e0672a160938 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:01:25 +0300 Subject: [PATCH 034/120] perf: run project and form gate checks only for gated actions --- .../viewsets/test_stepup_sharing_gates.py | 20 +++++++++++++++++++ onadata/apps/api/viewsets/project_viewset.py | 4 ++-- onadata/apps/api/viewsets/xform_viewset.py | 11 ++++++---- 3 files changed, 29 insertions(+), 6 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py index 0f7ddff086..0044b0b0e2 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py @@ -713,6 +713,17 @@ def test_an_update_takes_no_lock_where_nothing_is_gated(self): self._reload() self.assertEqual(self.project.name, "renamed") + @override_settings(STEP_UP={"MODE": "local", "ACTIONS": ["transfer-project"]}) + def test_the_publish_check_does_not_run_where_publishing_is_not_gated(self): + """Its query runs only where a deployment gates the action.""" + Project.objects.filter(pk=self.project.pk).update(shared=True) + + with patch(f"{PROJECT_VIEWSET}._publishes_data") as publishes: + response = self._patch({"name": "renamed"}) + + self.assertEqual(response.status_code, 200) + publishes.assert_not_called() + def test_an_invalid_update_keeps_the_grant(self): """Validation comes first, so a blank name does not spend it.""" self.assert_challenged(self._patch({"public": True})) @@ -746,6 +757,15 @@ def _patch(self, data, headers=None): ) return view(request, pk=self.xform.pk) + @override_settings(STEP_UP={"MODE": "local", "ACTIONS": ["transfer-project"]}) + def test_the_publish_check_does_not_run_where_publishing_is_not_gated(self): + """Each form check runs only where a deployment gates its action.""" + with patch(f"{XFORM_VIEWSET}._publishes_data") as publishes: + response = self._patch({"description": "renamed"}) + + self.assertEqual(response.status_code, 200) + publishes.assert_not_called() + def test_making_form_data_public_is_challenged(self): response = self._patch({"public_data": True}) diff --git a/onadata/apps/api/viewsets/project_viewset.py b/onadata/apps/api/viewsets/project_viewset.py index 71d68d2538..6e7a2635de 100644 --- a/onadata/apps/api/viewsets/project_viewset.py +++ b/onadata/apps/api/viewsets/project_viewset.py @@ -170,8 +170,8 @@ def _update_refusal(self, request, project, validated_data): return self.gated_change_refusal( request, ( - (GATE_TRANSFER_PROJECT, _transfers(project, validated_data)), - (GATE_PUBLISH_DATA, _publishes_data(project, validated_data)), + (GATE_TRANSFER_PROJECT, lambda: _transfers(project, validated_data)), + (GATE_PUBLISH_DATA, lambda: _publishes_data(project, validated_data)), ), ) diff --git a/onadata/apps/api/viewsets/xform_viewset.py b/onadata/apps/api/viewsets/xform_viewset.py index ad6d7a4aac..83c48788d5 100644 --- a/onadata/apps/api/viewsets/xform_viewset.py +++ b/onadata/apps/api/viewsets/xform_viewset.py @@ -1082,13 +1082,16 @@ def _update_refusal(self, request, xform, validated_data): ( ( GATE_TRANSFER_PROJECT, - _moves_to_another_account(xform, validated_data), + lambda: _moves_to_another_account(xform, validated_data), + ), + (GATE_PUBLISH_DATA, lambda: _publishes_data(xform, validated_data)), + ( + GATE_FORM_REQUIRE_AUTH, + lambda: _drops_require_auth(xform, validated_data), ), - (GATE_PUBLISH_DATA, _publishes_data(xform, validated_data)), - (GATE_FORM_REQUIRE_AUTH, _drops_require_auth(xform, validated_data)), ( GATE_DISABLE_FORM_ENCRYPTION, - _disables_encryption(xform, validated_data), + lambda: _disables_encryption(xform, validated_data), ), ), ) From faf4bf7e85ee3e50efcf7c44383dff49e58f1c3e Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:02:08 +0300 Subject: [PATCH 035/120] refactor: pass the request to the profile step-up refusals --- .../apps/api/viewsets/organization_profile_viewset.py | 10 +++++++--- onadata/apps/api/viewsets/user_profile_viewset.py | 8 +++++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/onadata/apps/api/viewsets/organization_profile_viewset.py b/onadata/apps/api/viewsets/organization_profile_viewset.py index 6157e4147b..d8203c27a1 100644 --- a/onadata/apps/api/viewsets/organization_profile_viewset.py +++ b/onadata/apps/api/viewsets/organization_profile_viewset.py @@ -143,14 +143,14 @@ def destroy(self, request, *args, **kwargs): safe_cache_delete(cache_key) return super().destroy(request, *args, **kwargs) - def _require_auth_refusal(self, organization, validated_data): + def _require_auth_refusal(self, request, organization, validated_data): """An organisation's profile is a UserProfile, so toggling its require_auth needs the same proof as on a personal profile. """ current = organization.require_auth if validated_data.get("require_auth", current) == current: return None - return self.check_step_up(self.request, GATE_REQUIRE_AUTH) + return self.check_step_up(request, GATE_REQUIRE_AUTH) def member_role_refusal(self, request, organization, validated_data): """Refuse a member change that appoints an admin without a grant. @@ -191,7 +191,11 @@ def appoints_project_or_form_admin(): def update(self, request, *args, **kwargs): # pylint: disable=unused-argument """Update org in cache and db""" response = self.gated_update( - request, self._require_auth_refusal, partial=kwargs.get("partial", False) + request, + lambda organization, data: self._require_auth_refusal( + request, organization, data + ), + partial=kwargs.get("partial", False), ) if not status.is_success(response.status_code): return response diff --git a/onadata/apps/api/viewsets/user_profile_viewset.py b/onadata/apps/api/viewsets/user_profile_viewset.py index f44e2ac1a4..7e622bf1aa 100644 --- a/onadata/apps/api/viewsets/user_profile_viewset.py +++ b/onadata/apps/api/viewsets/user_profile_viewset.py @@ -287,7 +287,9 @@ def update(self, request, *args, **kwargs): # pylint: disable=unused-argument request_username = request.user.username if request.user else "" safe_cache_delete(f"{USER_PROFILE_PREFIX}{username}{request_username}") return self.gated_update( - request, self._step_up_refusal, partial=kwargs.get("partial", False) + request, + lambda profile, data: self._step_up_refusal(request, profile, data), + partial=kwargs.get("partial", False), ) def retrieve(self, request, *args, **kwargs): @@ -372,7 +374,7 @@ def change_password(self, request, *args, **kwargs): # noqa return Response(status=status.HTTP_200_OK, data=data) - def _step_up_refusal(self, profile, validated_data): + def _step_up_refusal(self, request, profile, validated_data): """Refuse whichever gated change this update would make, or None. Reads the validated data, which is what the serializer writes. A @@ -382,7 +384,7 @@ def _step_up_refusal(self, profile, validated_data): unchanged values back. """ return self.gated_change_refusal( - self.request, + request, ( (GATE_REQUIRE_AUTH, _changes_require_auth(validated_data, profile)), (GATE_CHANGE_EMAIL, _changes_email(validated_data, profile)), From 39785f1a66c7ea08395e2bc4d28b3cf0d36ffdbd Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:02:08 +0300 Subject: [PATCH 036/120] perf: skip the member gate lookups where neither member gate applies --- .../viewsets/test_stepup_organization_gates.py | 16 ++++++++++++++++ .../api/viewsets/organization_profile_viewset.py | 3 +++ 2 files changed, 19 insertions(+) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py index 638cc6db6c..020d6e0060 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py @@ -7,6 +7,7 @@ from unittest.mock import patch from django.contrib.contenttypes.models import ContentType +from django.test import override_settings from oidc.stepup_grants import issue_grant, spend_grant @@ -35,6 +36,8 @@ get_team_project_default_permissions, ) +ORG_VIEWSET = "onadata.apps.api.viewsets.organization_profile_viewset" + @gating("require-auth-toggle") class TestOrganisationRequireAuthGate(StepUpGateTestCase): @@ -191,6 +194,19 @@ def test_other_roles_are_not_challenged(self): self.assertIn(self.alice, get_organization_members(self.organization)) self.assertFalse(OwnerRole.user_has_role(self.alice, self.organization)) + @override_settings(STEP_UP={"MODE": "local", "ACTIONS": ["change-email"]}) + def test_a_member_add_skips_the_lookups_where_nothing_it_needs_is_gated(self): + """The members team is read only for a gate that applies.""" + with patch( + f"{ORG_VIEWSET}.get_organization_members_team", + wraps=get_organization_members_team, + ) as members_team: + response = self._add_member("owner") + + self.assertEqual(response.status_code, 201) + members_team.assert_not_called() + self.assertTrue(OwnerRole.user_has_role(self.alice, self.organization)) + def test_appointing_a_manager_through_v2_is_challenged(self): response = self._member_request( "post", "manager", viewset=OrganizationProfileViewSetV2 diff --git a/onadata/apps/api/viewsets/organization_profile_viewset.py b/onadata/apps/api/viewsets/organization_profile_viewset.py index d8203c27a1..b0b8d6d913 100644 --- a/onadata/apps/api/viewsets/organization_profile_viewset.py +++ b/onadata/apps/api/viewsets/organization_profile_viewset.py @@ -53,6 +53,7 @@ GATE_REQUIRE_AUTH, GATE_ROTATE_ORG_KEY, GATE_SHARE_TEAM_ADMIN, + is_gated, ) from onadata.libs.stepup.sharing import ( admin_role, @@ -163,6 +164,8 @@ def member_role_refusal(self, request, organization, validated_data): username = validated_data.get("username") if validated_data.get("remove") or not username: return None + if not (is_gated(GATE_GRANT_ORG_ADMIN) or is_gated(GATE_SHARE_TEAM_ADMIN)): + return None user = User.objects.get(username=username) role_name = validated_data.get("role") role = admin_role(role_name) From be76510b0fcb31cf6c50480e2bc6c3f213eeed59 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:02:27 +0300 Subject: [PATCH 037/120] fix: find the API token before the regeneration gate spends the grant --- .../tests/viewsets/test_stepup_connect_gates.py | 17 ++++++++++++++++- onadata/apps/api/viewsets/connect_viewset.py | 9 +++++---- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_connect_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_connect_gates.py index c6a979330b..48a57ca716 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_connect_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_connect_gates.py @@ -6,9 +6,10 @@ from django.test.utils import override_settings from django.urls import reverse -from oidc.stepup_grants import issue_grant +from oidc.stepup_grants import issue_grant, spend_grant from registration.models import RegistrationProfile from rest_framework.authtoken.models import Token +from rest_framework.test import force_authenticate from onadata.apps.api.models.odk_token import ODKToken from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import ( @@ -71,6 +72,20 @@ def test_a_grant_in_the_header_lets_the_regeneration_through(self): self.assertNotEqual(self._api_token(), old_token) self.assertEqual(response.data, self._api_token()) + def test_a_user_with_no_api_token_keeps_the_grant(self): + """The request cannot succeed, so the gate does not spend the grant.""" + grant = issue_grant(self.user.pk, "regenerate-api-key") + Token.objects.filter(user=self.user).delete() + view = ConnectViewSet.as_view({"get": "regenerate_auth_token"}) + request = self.factory.get("/", HTTP_X_STEP_UP_GRANT=grant) + force_authenticate(request, user=self.user) + + response = view(request) + + self.assertEqual(response.status_code, 400) + self.assertFalse(Token.objects.filter(user=self.user).exists()) + self.assertTrue(spend_grant(self.user.pk, "regenerate-api-key", grant)) + @override_settings( CORS_ALLOW_ALL_ORIGINS=False, CORS_ALLOWED_ORIGINS=["https://app.example"], diff --git a/onadata/apps/api/viewsets/connect_viewset.py b/onadata/apps/api/viewsets/connect_viewset.py index a8160ea4f2..c56d1e7562 100644 --- a/onadata/apps/api/viewsets/connect_viewset.py +++ b/onadata/apps/api/viewsets/connect_viewset.py @@ -160,13 +160,14 @@ def regenerate_auth_token(self, request, *args, **kwargs): still read the current token from ``GET /api/v1/user``. A GET has no body, so send the grant in the ``X-Step-Up-Grant`` header. """ + # Look the token up first, so a request that cannot succeed keeps its + # grant. + if not Token.objects.filter(user=request.user).exists(): + raise ParseError(_(" Token not found!")) refusal = self.check_step_up(request, GATE_REGENERATE_API_KEY) if refusal is not None: return refusal - try: - Token.objects.get(user=request.user).delete() - except Token.DoesNotExist as exc: - raise ParseError(_(" Token not found!")) from exc + Token.objects.filter(user=request.user).delete() new_token = Token.objects.create(user=request.user) From 58ec92e004ba689af95dea0e38fe51b94a3c34cc Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:03:08 +0300 Subject: [PATCH 038/120] fix: refuse a duplicate service before the webhook gate spends the grant --- .../viewsets/test_stepup_webhook_gate.py | 14 +++++ onadata/apps/restservice/views.py | 59 +++++++++++-------- 2 files changed, 47 insertions(+), 26 deletions(-) diff --git a/onadata/apps/restservice/tests/viewsets/test_stepup_webhook_gate.py b/onadata/apps/restservice/tests/viewsets/test_stepup_webhook_gate.py index e8ad5292cd..2969d418b8 100644 --- a/onadata/apps/restservice/tests/viewsets/test_stepup_webhook_gate.py +++ b/onadata/apps/restservice/tests/viewsets/test_stepup_webhook_gate.py @@ -301,6 +301,20 @@ def test_a_grant_lets_the_service_be_added(self): [SERVICE_URL], ) + def test_a_duplicate_service_keeps_the_grant(self): + """The same service cannot be added twice, so the grant is not + spent on it.""" + RestService.objects.create( + service_url=SERVICE_URL, name="generic_json", xform=self.xform + ) + grant = issue_grant(self.user.pk, CHANGE_WEBHOOK) + + response = self._post({"grant": grant}) + + self.assertEqual(response.status_code, 200) + self.assertEqual(RestService.objects.count(), 1) + self.assertTrue(spend_grant(self.user.pk, CHANGE_WEBHOOK, grant)) + def test_an_invalid_service_keeps_the_grant(self): grant = issue_grant(self.user.pk, CHANGE_WEBHOOK) diff --git a/onadata/apps/restservice/views.py b/onadata/apps/restservice/views.py index 9f38d101c5..0479082fab 100644 --- a/onadata/apps/restservice/views.py +++ b/onadata/apps/restservice/views.py @@ -19,6 +19,24 @@ from onadata.libs.utils.viewer_tools import get_form +def _save_service(service): + """``(status, message, rendered service)`` for saving ``service``.""" + try: + service.save() + except IntegrityError: + return "fail", _("Service already defined."), None + message = _("Successfully added service %(name)s.") % {"name": service.name} + rendered = render_to_string( + "service.html", + { + "sv": service, + "username": service.xform.user.username, + "id_string": service.xform.id_string, + }, + ) + return "success", message, rendered + + # pylint: disable=too-many-locals @login_required def add_service(request, username, id_string): @@ -33,33 +51,22 @@ def add_service(request, username, id_string): form = RestServiceForm(request.POST) restservice = None if form.is_valid(): - refusal = refuse_page_action(request, GATE_CHANGE_WEBHOOK) - if refusal is not None: - return refusal - service_name = form.cleaned_data["service_name"] - service_url = form.cleaned_data["service_url"] - try: - service = RestService( - service_url=service_url, name=service_name, xform=xform - ) - service.save() - except IntegrityError: - message = _("Service already defined.") - status = "fail" + service = RestService( + service_url=form.cleaned_data["service_url"], + name=form.cleaned_data["service_name"], + xform=xform, + ) + # A duplicate cannot be saved, so refuse it before the gate spends + # the grant. + if RestService.objects.filter( + service_url=service.service_url, name=service.name, xform=xform + ).exists(): + status, message = "fail", _("Service already defined.") else: - status = "success" - message = _("Successfully added service %(name)s.") % { - "name": service_name - } - service_tpl = render_to_string( - "service.html", - { - "sv": service, - "username": xform.user.username, - "id_string": xform.id_string, - }, - ) - restservice = service_tpl + refusal = refuse_page_action(request, GATE_CHANGE_WEBHOOK) + if refusal is not None: + return refusal + status, message, restservice = _save_service(service) else: status = "fail" message = _("Please fill in all required fields") From 93a6812e3df9774bd82e62a690e3f4f06e4447e2 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:04:29 +0300 Subject: [PATCH 039/120] fix: let each legacy remove link delete only the metadata type it lists --- .../tests/test_stepup_public_link_gate.py | 81 +++++++++++++++++++ onadata/apps/main/views.py | 25 +++++- 2 files changed, 103 insertions(+), 3 deletions(-) diff --git a/onadata/apps/main/tests/test_stepup_public_link_gate.py b/onadata/apps/main/tests/test_stepup_public_link_gate.py index ff90be13be..c659214da7 100644 --- a/onadata/apps/main/tests/test_stepup_public_link_gate.py +++ b/onadata/apps/main/tests/test_stepup_public_link_gate.py @@ -92,3 +92,84 @@ def test_an_already_on_link_is_not_challenged(self): self.assertEqual(response.status_code, 200) self.assertTrue(self._link_is_on()) + + +@override_settings( + STEP_UP={ + "MODE": "local", + "ACTIONS": [PUBLISH_DATA], + "NO_FACTOR_POLICY": "skip_gate", + } +) +class TestLegacyRemoveLinks(TestBase): + """The remove links of the form page delete only the type they list. A + public link row they deleted could uncover another one that is on.""" + + def setUp(self): + super().setUp() + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + self._publish_transportation_form() + self.hiding, self.hidden = ( + MetaData.objects.create( + content_object=self.xform, data_type="public_link", data_value=value + ) + for value in ("False", "True") + ) + self.assertFalse(MetaData.public_link(self.xform)) + + def _url(self, name, row, param): + return ( + reverse( + name, + kwargs={ + "username": self.user.username, + "id_string": self.xform.id_string, + "data_id": row.pk, + }, + ) + + f"?{param}=true" + ) + + def test_a_document_link_does_not_delete_a_public_link_row(self): + """Each of the three delete-doc links.""" + for param in ("del", "map_name_del", "external_del"): + with self.subTest(param=param): + response = self.client.get( + self._url("delete-metadata", self.hiding, param) + ) + + self.assertEqual(response.status_code, 403) + self.assertTrue(MetaData.objects.filter(pk=self.hiding.pk).exists()) + self.assertFalse(MetaData.public_link(self.xform)) + + def test_the_media_link_does_not_delete_a_public_link_row(self): + response = self.client.get(self._url("download-media-data", self.hiding, "del")) + + self.assertEqual(response.status_code, 403) + self.assertTrue(MetaData.objects.filter(pk=self.hiding.pk).exists()) + self.assertFalse(MetaData.public_link(self.xform)) + + def test_a_map_layer_link_still_deletes_a_map_layer(self): + """The link keeps working for the type it lists.""" + layer = MetaData.objects.create( + content_object=self.xform, data_type="mapbox_layer", data_value="layer" + ) + + response = self.client.get(self._url("delete-metadata", layer, "map_name_del")) + + self.assertEqual(response.status_code, 302) + self.assertFalse(MetaData.objects.filter(pk=layer.pk).exists()) + + def test_the_media_link_still_deletes_media(self): + """The link keeps working for the type it lists.""" + media = MetaData.objects.create( + content_object=self.xform, + data_type="media", + data_value="a.png", + data_file="", + ) + + response = self.client.get(self._url("download-media-data", media, "del")) + + self.assertEqual(response.status_code, 302) + self.assertFalse(MetaData.objects.filter(pk=media.pk).exists()) diff --git a/onadata/apps/main/views.py b/onadata/apps/main/views.py index de51260b55..4b4c1a5dfa 100644 --- a/onadata/apps/main/views.py +++ b/onadata/apps/main/views.py @@ -1145,6 +1145,24 @@ def download_metadata(request, username, id_string, data_id): return HttpResponseForbidden(_("Permission denied.")) +#: The metadata type that each remove link of the form page deletes. A link +#: must not delete a row of another type, such as a public link or TextIt row, +#: because the API gates those deletes. +REMOVE_LINK_TYPES = { + "del": "supporting_doc", + "map_name_del": "mapbox_layer", + "external_del": "external_export", +} + + +def _removes(request, param, data): + """Whether ``request`` asks the ``param`` link to delete ``data``, and + ``data`` is of the type that link deletes.""" + return bool(request.GET.get(param, False)) and ( + data.data_type == REMOVE_LINK_TYPES[param] + ) + + @login_required() def delete_metadata(request, username, id_string, data_id): """Deletes a metadata record.""" @@ -1161,7 +1179,7 @@ def delete_metadata(request, username, id_string, data_id): ) dfs = storages["default"] req_username = request.user.username - if request.GET.get("del", False) and username == req_username: + if _removes(request, "del", data) and username == req_username: dfs.delete(data.data_file.name) data.delete() audit = {"xform": xform.id_string} @@ -1179,7 +1197,8 @@ def delete_metadata(request, username, id_string, data_id): reverse(show, kwargs={"username": username, "id_string": id_string}) ) if ( - request.GET.get("map_name_del", False) or request.GET.get("external_del", False) + _removes(request, "map_name_del", data) + or _removes(request, "external_del", data) ) and username == req_username: data.delete() audit = {"xform": xform.id_string} @@ -1216,7 +1235,7 @@ def download_media_data(request, username, id_string, data_id): ) dfs = storages["default"] if request.GET.get("del", False): - if username == request.user.username: + if username == request.user.username and data.data_type == "media": # ensure filename is not an empty string if data.data_file.name != "": dfs.delete(data.data_file.name) From d68443014d7daaf72671d024222ad98c70f1d1e6 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:04:40 +0300 Subject: [PATCH 040/120] fix: leave an on public link alone when the legacy page turns it on --- .../main/tests/test_stepup_public_link_gate.py | 16 ++++++++++++++++ onadata/apps/main/views.py | 5 ++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/onadata/apps/main/tests/test_stepup_public_link_gate.py b/onadata/apps/main/tests/test_stepup_public_link_gate.py index c659214da7..608f7e05a8 100644 --- a/onadata/apps/main/tests/test_stepup_public_link_gate.py +++ b/onadata/apps/main/tests/test_stepup_public_link_gate.py @@ -4,6 +4,8 @@ legacy form permissions page. """ +from unittest.mock import patch + from django.test.utils import override_settings from django.urls import reverse @@ -93,6 +95,20 @@ def test_an_already_on_link_is_not_challenged(self): self.assertEqual(response.status_code, 200) self.assertTrue(self._link_is_on()) + def test_turning_an_on_link_on_writes_nothing(self): + """The request is waved through because the link is on. A write + would turn it back on after a concurrent disable.""" + self._turn_link(True) + + with patch( + "onadata.apps.main.views.MetaData.public_link", + wraps=MetaData.public_link, + ) as public_link: + response = self._set_link("all") + + self.assertEqual(response.status_code, 200) + public_link.assert_called_once_with(self.xform) + @override_settings( STEP_UP={ diff --git a/onadata/apps/main/views.py b/onadata/apps/main/views.py index 4b4c1a5dfa..888db18243 100644 --- a/onadata/apps/main/views.py +++ b/onadata/apps/main/views.py @@ -1568,7 +1568,10 @@ def set_perm(request, username, id_string): # noqa C901 if refusal is not None: return refusal if for_user == "all": - MetaData.public_link(xform, True) + # An on link is left alone. Writing it again could undo a + # concurrent disable without the grant. + if not current: + MetaData.public_link(xform, True) elif for_user == "none": MetaData.public_link(xform, False) elif for_user == "toggle": From 4cc579f145269fea8c2adce76f71ddd3bf067b44 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:05:53 +0300 Subject: [PATCH 041/120] fix: lock the profile and user rows from the settings page gate to the save --- onadata/apps/main/tests/test_stepup_pages.py | 18 ++++ onadata/apps/main/views.py | 94 +++++++++++--------- onadata/libs/stepup/drf.py | 10 ++- 3 files changed, 77 insertions(+), 45 deletions(-) diff --git a/onadata/apps/main/tests/test_stepup_pages.py b/onadata/apps/main/tests/test_stepup_pages.py index 56be56db4d..234f7a79b4 100644 --- a/onadata/apps/main/tests/test_stepup_pages.py +++ b/onadata/apps/main/tests/test_stepup_pages.py @@ -97,6 +97,24 @@ def test_an_edit_changing_no_gated_value_is_saved(self): self.assertEqual(response.status_code, 302) self.assertEqual(UserProfile.objects.get(user=self.user).city, "Bobville") + def test_the_gate_reads_the_locked_row_not_the_loaded_copy(self): + """A change can commit after the page loads the profile. The gate + and the save use the row as it is once locked.""" + stale = UserProfile.objects.get(user=self.user) + UserProfile.objects.filter(pk=stale.pk).update( + require_auth=not stale.require_auth + ) + + with patch.object( + UserProfile.objects, "get_or_create", return_value=(stale, False) + ): + response = self._post({"require_auth": stale.require_auth}) + + self.assertEqual(response.status_code, 403) + self.assertEqual( + UserProfile.objects.get(pk=stale.pk).require_auth, not stale.require_auth + ) + def test_a_grant_in_the_form_lets_the_email_change_through(self): grant = issue_grant(self.user.pk, "change-email") diff --git a/onadata/apps/main/views.py b/onadata/apps/main/views.py index 888db18243..5df363644d 100644 --- a/onadata/apps/main/views.py +++ b/onadata/apps/main/views.py @@ -18,7 +18,7 @@ from django.core.cache import cache from django.core.exceptions import ValidationError from django.core.files.storage import default_storage, storages -from django.db import IntegrityError, connections +from django.db import IntegrityError, connections, transaction from django.http import ( HttpResponse, HttpResponseBadRequest, @@ -93,6 +93,7 @@ ) from onadata.libs.exceptions import EnketoError from onadata.libs.permissions import CAN_VIEW_PROJECT +from onadata.libs.stepup.drf import locked_for_gates from onadata.libs.stepup.gate import refusal_reason from onadata.libs.stepup.pages import ( gated_profile_values, @@ -391,52 +392,61 @@ def profile_settings(request, username): user_profile, _created = UserProfile.objects.get_or_create(user=content_user) if request.method == "POST": - # Taken before validation, which writes the posted values onto - # user_profile. - gated_before = gated_profile_values( - user_profile.require_auth, content_user.email, user_profile.metadata - ) - form = UserProfileForm(request.POST, instance=user_profile) - if form.is_valid(): - refusal = refuse_gated_changes( - request, - gated_before, - gated_profile_values( - form.cleaned_data["require_auth"], - form.cleaned_data["email"], - form.cleaned_data["metadata"], - ), - ) - if refusal is not None: - return refusal - # get user - # user.email = cleaned_email - form.instance.user.email = form.cleaned_data["email"] - form.instance.user.save() - form.save() - # todo: add string rep. of settings to see what changed - audit = {} - audit_log( - Actions.PROFILE_SETTINGS_UPDATED, - request.user, - content_user, - _("Profile settings updated."), - audit, - request, - ) - return HttpResponseRedirect( - reverse(public_profile, kwargs={"username": request.user.username}) - ) - else: - form = UserProfileForm( - instance=user_profile, initial={"email": content_user.email} - ) - + return _post_profile_settings(request, content_user, user_profile) + form = UserProfileForm(instance=user_profile, initial={"email": content_user.email}) return render( request, "settings.html", {"content_user": content_user, "form": form} ) +@transaction.atomic +def _post_profile_settings(request, content_user, user_profile): + """Save the settings form, unless it changes a gated value without a + grant. + + The gate compares against the profile and user rows as they are once + locked, and the locks hold through both saves. A concurrent change cannot + come between them and be overwritten.""" + user_profile = locked_for_gates(user_profile) + user_profile.user = locked_for_gates(user_profile.user) + # Taken before validation, which writes the posted values onto + # user_profile. + gated_before = gated_profile_values( + user_profile.require_auth, user_profile.user.email, user_profile.metadata + ) + form = UserProfileForm(request.POST, instance=user_profile) + if not form.is_valid(): + return render( + request, "settings.html", {"content_user": content_user, "form": form} + ) + refusal = refuse_gated_changes( + request, + gated_before, + gated_profile_values( + form.cleaned_data["require_auth"], + form.cleaned_data["email"], + form.cleaned_data["metadata"], + ), + ) + if refusal is not None: + return refusal + form.instance.user.email = form.cleaned_data["email"] + form.instance.user.save() + form.save() + # todo: add string rep. of settings to see what changed + audit_log( + Actions.PROFILE_SETTINGS_UPDATED, + request.user, + content_user, + _("Profile settings updated."), + {}, + request, + ) + return HttpResponseRedirect( + reverse(public_profile, kwargs={"username": request.user.username}) + ) + + @require_GET def public_profile(request, username): """Show user's public profile page view.""" diff --git a/onadata/libs/stepup/drf.py b/onadata/libs/stepup/drf.py index 28ff9a9125..ffb8be0d12 100644 --- a/onadata/libs/stepup/drf.py +++ b/onadata/libs/stepup/drf.py @@ -36,6 +36,12 @@ def locked(instance): return instance +def locked_for_gates(instance): + """``instance``, locked and read again where the deployment gates any + action, or unchanged where it gates nothing. Call it in a transaction.""" + return locked(instance) if gated_actions() else instance + + def lock_row(model, pk): """Lock the row of ``model`` with primary key ``pk`` until the transaction ends. Read no columns of it.""" @@ -122,9 +128,7 @@ def gated_update(self, request, refusal_for, partial=False): # pylint: disable=no-member gating = bool(gated_actions()) with transaction.atomic() if gating else nullcontext(): - instance = self.get_object() - if gating: - instance = locked(instance) + instance = locked_for_gates(self.get_object()) serializer = self.get_serializer( instance, data=request.data, partial=partial ) From 609bd1af321426f2dc69734568a34e6070e9452c Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:06:32 +0300 Subject: [PATCH 042/120] fix: save only the password and its edit time on a password change --- .../test_stepup_user_profile_gates.py | 35 +++++++++++++++++++ .../apps/api/viewsets/user_profile_viewset.py | 26 ++++++++++---- 2 files changed, 55 insertions(+), 6 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_user_profile_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_user_profile_gates.py index be0d6ef9c0..462ace90db 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_user_profile_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_user_profile_gates.py @@ -394,6 +394,41 @@ def test_a_grant_lets_the_password_change_through(self): self.user.refresh_from_db() self.assertTrue(self.user.check_password(new_password)) + def test_a_password_change_writes_back_no_stale_profile_value(self): + """A concurrent change to the email or require_auth survives a + request that carries only a password grant.""" + stale = UserProfile.objects.select_related("user").get(user=self.user) + UserProfile.objects.filter(pk=stale.pk).update( + require_auth=not stale.require_auth + ) + type(self.user).objects.filter(pk=self.user.pk).update( + email="changed@example.org" + ) + self.assertNotEqual(stale.user.email, "changed@example.org") + new_password = "Tr0ub4dor-and-3-horses" + view = UserProfileViewSet.as_view({"post": "change_password"}) + request = self.factory.post( + "/", + data={ + "current_password": self.login_password, + "new_password": new_password, + "grant": issue_grant(self.user.pk, "change-password"), + }, + format="json", + **self.extra, + ) + + with patch.object(UserProfileViewSet, "get_object", return_value=stale): + response = view(request, user=self.user.username) + + self.assertEqual(response.status_code, 200) + profile = UserProfile.objects.get(pk=stale.pk) + self.assertEqual(profile.require_auth, not stale.require_auth) + self.assertIn("last_password_edit", profile.metadata) + self.user.refresh_from_db() + self.assertEqual(self.user.email, "changed@example.org") + self.assertTrue(self.user.check_password(new_password)) + @patch( "onadata.libs.serializers.user_profile_serializer." "send_verification_email.delay" diff --git a/onadata/apps/api/viewsets/user_profile_viewset.py b/onadata/apps/api/viewsets/user_profile_viewset.py index 7e622bf1aa..8b24240744 100644 --- a/onadata/apps/api/viewsets/user_profile_viewset.py +++ b/onadata/apps/api/viewsets/user_profile_viewset.py @@ -221,6 +221,25 @@ def _merged_metadata(stored, incoming): return merged +@transaction.atomic +def _save_new_password(user_profile, new_password): + """Save ``new_password`` and when it was set, and nothing else. + + A request that carries only a password grant must not write back a stale + email, require_auth or consent record. The profile row is locked and read + again before the edit time is merged into its metadata. It is locked + before the user row, in the order a profile update takes them.""" + profile = UserProfile.objects.select_for_update().get(pk=user_profile.pk) + user = user_profile.user + user.set_password(new_password) + user.save(update_fields=["password"]) + profile.metadata = { + **(profile.metadata or {}), + "last_password_edit": timezone.now().isoformat(), + } + profile.save(update_fields=["metadata", "date_modified"]) + + # pylint: disable=too-many-ancestors class UserProfileViewSet( RequiresStepUp, @@ -364,12 +383,7 @@ def change_password(self, request, *args, **kwargs): # noqa return refusal data = {"username": user_profile.user.username} - metadata = user_profile.metadata or {} - metadata["last_password_edit"] = timezone.now().isoformat() - user_profile.user.set_password(new_password) - user_profile.metadata = metadata - user_profile.user.save() - user_profile.save() + _save_new_password(user_profile, new_password) data.update(invalidate_and_regen_tokens(user=user_profile.user)) return Response(status=status.HTTP_200_OK, data=data) From 6ed28d765f5cdd67ff16b7b8e2f2fc8f6cf3482f Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:08:34 +0300 Subject: [PATCH 043/120] fix: save only the changed columns from the legacy form edit page --- .../tests/test_stepup_legacy_publish_gate.py | 47 ++++++- onadata/apps/main/views.py | 128 +++++++++++------- 2 files changed, 123 insertions(+), 52 deletions(-) diff --git a/onadata/apps/main/tests/test_stepup_legacy_publish_gate.py b/onadata/apps/main/tests/test_stepup_legacy_publish_gate.py index e0a37b7f61..cbd3043eb0 100644 --- a/onadata/apps/main/tests/test_stepup_legacy_publish_gate.py +++ b/onadata/apps/main/tests/test_stepup_legacy_publish_gate.py @@ -4,7 +4,10 @@ legacy form edit page. """ -from django.test.utils import override_settings +from unittest.mock import patch + +from django.db import connection +from django.test.utils import CaptureQueriesContext, override_settings from django.urls import reverse from django_otp.plugins.otp_totp.models import TOTPDevice @@ -85,3 +88,45 @@ def test_unsharing_is_not_challenged(self): self.assertEqual(response.status_code, 200) self.assertFalse(self._flag(target)) + + def test_a_title_edit_writes_back_no_stale_visibility(self): + """Another request can unpublish the data after this one reads the + form. A title edit saves the title only.""" + stale = XForm.objects.get(pk=self.xform.pk) + stale.shared_data = True + self._set_flag("data", False) + + with patch.object(XForm.objects, "get", return_value=stale): + response = self.client.post( + self.edit_url, + {"title": "renamed"}, + HTTP_X_REQUESTED_WITH="XMLHttpRequest", + ) + + self.assertEqual(response.status_code, 200) + self.assertFalse(self._flag("data")) + self.assertEqual(XForm.objects.get(pk=self.xform.pk).title, "renamed") + + def test_a_toggle_locks_the_form_before_its_check(self): + """The check and the write see the same row.""" + self._set_flag("data", True) + + with CaptureQueriesContext(connection) as queries: + response = self._toggle("data") + + self.assertEqual(response.status_code, 200) + self.assertFalse(self._flag("data")) + statements = [query["sql"] for query in queries.captured_queries] + locks = [ + index + for index, sql in enumerate(statements) + if 'FROM "logger_xform"' in sql and "FOR UPDATE" in sql + ] + writes = [ + index + for index, sql in enumerate(statements) + if sql.startswith('UPDATE "logger_xform"') + ] + self.assertTrue(locks, "The form row is not locked.") + self.assertTrue(writes, "The form row is not written.") + self.assertLess(locks[0], writes[0]) diff --git a/onadata/apps/main/views.py b/onadata/apps/main/views.py index 5df363644d..6eb6b98672 100644 --- a/onadata/apps/main/views.py +++ b/onadata/apps/main/views.py @@ -728,6 +728,9 @@ def public_api(request, username, id_string): _PUBLIC_FLAGS = {"data": "shared_data", "form": "shared"} +#: The column each ``toggle_shared`` value of the edit page flips. +_TOGGLED_FIELDS = {**_PUBLIC_FLAGS, "active": "downloadable"} + def _refuse_making_public(request, xform): """``None``, or a 403 for sharing a form or its data without a grant. @@ -738,6 +741,71 @@ def _refuse_making_public(request, xform): return refuse_page_action(request, GATE_PUBLISH_DATA) +@transaction.atomic +def _toggle_visibility(request, xform, owner, id_string): + """Toggle the flag that ``toggle_shared`` names and save it, or return a + 403 for sharing without a grant. + + The row is locked and read again before the check, and the lock holds + through the write.""" + locked_for_gates(xform) + refusal = _refuse_making_public(request, xform) + if refusal is not None: + return refusal + if request.POST["toggle_shared"] == "data": + audit = {"xform": xform.id_string} + old_shared = _("shared") if xform.shared_data else _("not shared") + new_shared = _("shared") if not xform.shared_data else _("not shared") + audit_log( + Actions.FORM_UPDATED, + request.user, + owner, + _( + f"Data sharing updated for '{id_string}' from " + f"'{old_shared}' to '{new_shared}'." + ), + audit, + request, + ) + xform.shared_data = not xform.shared_data + elif request.POST["toggle_shared"] == "form": + audit = {"xform": xform.id_string} + old_shared = _("shared") if xform.shared else _("not shared") + new_shared = _("shared") if not xform.shared else _("not shared") + audit_log( + Actions.FORM_UPDATED, + request.user, + owner, + _( + f"Form sharing for '{xform.id_string}' updated " + f"from '{old_shared}' to '{new_shared}'." + ), + audit, + request, + ) + xform.shared = not xform.shared + elif request.POST["toggle_shared"] == "active": + audit = {"xform": xform.id_string} + old_shared = _("shared") if xform.downloadable else _("not shared") + new_shared = _("shared") if not xform.downloadable else _("not shared") + audit_log( + Actions.FORM_UPDATED, + request.user, + owner, + _( + f"Active status for '{xform.id_string}' updated from " + f"'{old_shared}' to '{new_shared}'." + ), + audit, + request, + ) + xform.downloadable = not xform.downloadable + toggled = _TOGGLED_FIELDS.get(request.POST["toggle_shared"]) + if toggled is not None: + xform.update(update_fields=[toggled, "date_modified"]) + return None + + # pylint: disable=too-many-locals,too-many-branches,too-many-statements @login_required def edit(request, username, id_string): # noqa C901 @@ -752,6 +820,10 @@ def edit(request, username, id_string): # noqa C901 if username == request.user.username or request.user.has_perm( "logger.change_xform", xform ): + # Only the columns an edit changes are saved. A full save would write + # back a visibility, require_auth or encryption that another request + # changed after this one read the form. + changed = ["date_modified"] if request.POST.get("description") or request.POST.get("description") == "": audit = {"xform": xform.id_string} old_description = xform.description @@ -768,6 +840,7 @@ def edit(request, username, id_string): # noqa C901 request, ) xform.description = request.POST["description"] + changed.append("description") elif request.POST.get("title"): audit = {"xform": xform.id_string} old_title = (xform.title,) @@ -787,58 +860,11 @@ def edit(request, username, id_string): # noqa C901 request, ) xform.title = request.POST["title"] + changed.append("title") elif request.POST.get("toggle_shared"): - refusal = _refuse_making_public(request, xform) + refusal = _toggle_visibility(request, xform, owner, id_string) if refusal is not None: return refusal - if request.POST["toggle_shared"] == "data": - audit = {"xform": xform.id_string} - old_shared = _("shared") if xform.shared_data else _("not shared") - new_shared = _("shared") if not xform.shared_data else _("not shared") - audit_log( - Actions.FORM_UPDATED, - request.user, - owner, - _( - f"Data sharing updated for '{id_string}' from " - f"'{old_shared}' to '{new_shared}'." - ), - audit, - request, - ) - xform.shared_data = not xform.shared_data - elif request.POST["toggle_shared"] == "form": - audit = {"xform": xform.id_string} - old_shared = _("shared") if xform.shared else _("not shared") - new_shared = _("shared") if not xform.shared else _("not shared") - audit_log( - Actions.FORM_UPDATED, - request.user, - owner, - _( - f"Form sharing for '{xform.id_string}' updated " - f"from '{old_shared}' to '{new_shared}'." - ), - audit, - request, - ) - xform.shared = not xform.shared - elif request.POST["toggle_shared"] == "active": - audit = {"xform": xform.id_string} - old_shared = _("shared") if xform.downloadable else _("not shared") - new_shared = _("shared") if not xform.downloadable else _("not shared") - audit_log( - Actions.FORM_UPDATED, - request.user, - owner, - _( - f"Active status for '{xform.id_string}' updated from " - f"'{old_shared}' to '{new_shared}'." - ), - audit, - request, - ) - xform.downloadable = not xform.downloadable elif request.POST.get("form-license"): audit = {"xform": xform.id_string} form_license = request.POST["form-license"] @@ -914,7 +940,7 @@ def edit(request, username, id_string): # noqa C901 xform.allows_sms = False xform.sms_id_string = pid try: - xform.save() + xform.save(update_fields=["allows_sms", "sms_id_string"]) except IntegrityError: # unfortunately, there's no feedback mechanism here xform.allows_sms = previous_allow_sms @@ -994,7 +1020,7 @@ def edit(request, username, id_string): # noqa C901 data_value = template_upload_name + "|" + external_url + "/xls/" + token MetaData.external_export(xform, data_value=data_value) - xform.update() + xform.update(update_fields=changed) if request.headers.get("x-requested-with") == "XMLHttpRequest": return HttpResponse(_("Updated succeeded.")) From cbc61cf486c499a8cc34ebb06073e0f7b51cc8f1 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:11:04 +0300 Subject: [PATCH 044/120] fix: gate approving an OAuth device as approving an application --- docs/two_factor.rst | 10 ++-- .../apps/main/tests/test_stepup_oauth_gate.py | 57 ++++++++++++++++++- onadata/apps/main/urls.py | 5 ++ onadata/apps/main/views.py | 15 +++++ onadata/libs/stepup/checks.py | 12 ++-- 5 files changed, 89 insertions(+), 10 deletions(-) diff --git a/docs/two_factor.rst b/docs/two_factor.rst index 8c46010aee..a9461cba26 100644 --- a/docs/two_factor.rst +++ b/docs/two_factor.rst @@ -115,7 +115,8 @@ A gated request can also get these answers: - the form pages at ``/{username}/forms/{id_string}/edit``, ``/{username}/forms/{id_string}/perms`` and ``/{username}/forms/{id_string}/addservice`` - - the OAuth pages at ``/o/authorize/`` and ``/o/applications/`` + - the OAuth pages at ``/o/authorize/``, ``/o/device-confirm/`` and + ``/o/applications/`` Status ------ @@ -359,9 +360,10 @@ Audience Action new merged dataset in the project of another account from a form ``authorize-oauth-app`` the approval of an OAuth application at - ``/o/authorize/``; the registration of an application - under ``/o/applications/``, or a change to its - redirect URIs or client type + ``/o/authorize/``; the approval of a device at + ``/o/device-confirm/``; the registration of an + application under ``/o/applications/``, or a change + to its redirect URIs or client type ``form-require-auth`` ``require_auth`` turned off on ``/api/v1/forms/{pk}`` ``disable-form-encryption`` the encryption of a form turned off with ``enable_kms_encryption`` on ``/api/v1/forms/{pk}`` diff --git a/onadata/apps/main/tests/test_stepup_oauth_gate.py b/onadata/apps/main/tests/test_stepup_oauth_gate.py index 16ad75e920..5f5f6e2a1a 100644 --- a/onadata/apps/main/tests/test_stepup_oauth_gate.py +++ b/onadata/apps/main/tests/test_stepup_oauth_gate.py @@ -15,7 +15,12 @@ from django.utils import timezone from django_otp.plugins.otp_totp.models import TOTPDevice -from oauth2_provider.models import AccessToken, Grant, get_application_model +from oauth2_provider.models import ( + AccessToken, + Grant, + get_application_model, + get_device_grant_model, +) from oidc.stepup_grants import issue_grant, spend_grant AUTHORIZE_OAUTH_APP = "authorize-oauth-app" @@ -310,6 +315,56 @@ def test_renaming_is_not_challenged(self): self.assertEqual(application.redirect_uris, REDIRECT_URI) +@override_settings(STEP_UP=STEP_UP_ON) +class TestConfirmingAnOAuthDevice(StepUpOAuthTestCase): + """Approving a device issues it a long-lived credential for the user, as + approving an application does.""" + + def setUp(self): + super().setUp() + self.application = self._application() + self.device = get_device_grant_model().objects.create( + user=self.user, + device_code="device-code", + user_code="USERCODE", + client_id=self.application.client_id, + expires=timezone.now() + timedelta(minutes=10), + ) + + def _confirm(self, action, **extra): + return self.client.post( + f"/o/device-confirm/{self.application.client_id}/USERCODE", + {"action": action, **extra}, + ) + + def _status(self): + self.device.refresh_from_db() + return self.device.status + + def test_accepting_without_a_grant_is_refused(self): + response = self._confirm("accept") + + self.assertEqual(response.status_code, 403) + self.assertEqual(self._status(), self.device.AUTHORIZATION_PENDING) + + def test_a_grant_lets_the_device_through(self): + grant = self._grant() + + response = self._confirm("accept", grant=grant) + + self.assertEqual(response.status_code, 302) + self.assertEqual(self._status(), self.device.AUTHORIZED) + self.assertFalse(spend_grant(self.user.pk, AUTHORIZE_OAUTH_APP, grant)) + + def test_denying_is_not_challenged(self): + self.assertEqual(self._confirm("accept").status_code, 403) + + response = self._confirm("deny") + + self.assertEqual(response.status_code, 302) + self.assertEqual(self._status(), self.device.DENIED) + + @override_settings(STEP_UP=STEP_UP_OFF) class TestOAuthGateOff(StepUpOAuthTestCase): """A deployment that has not opted in needs no grant.""" diff --git a/onadata/apps/main/urls.py b/onadata/apps/main/urls.py index b2d0015517..1d83dc67dc 100644 --- a/onadata/apps/main/urls.py +++ b/onadata/apps/main/urls.py @@ -138,6 +138,11 @@ main_views.StepUpApplicationUpdate.as_view(), name="oauth2_provider_update", ), + re_path( + r"^o/device-confirm/(?P[-\w]+)/(?P[-\w]+)$", + main_views.StepUpDeviceConfirm.as_view(), + name="oauth2_provider_device_confirm", + ), re_path(r"^o/", include("oauth2_provider.urls", namespace="oauth2_provider")), # main website views re_path(r"^$", main_views.home), diff --git a/onadata/apps/main/views.py b/onadata/apps/main/views.py index 6eb6b98672..73a778d607 100644 --- a/onadata/apps/main/views.py +++ b/onadata/apps/main/views.py @@ -45,6 +45,7 @@ ApplicationUpdate, ) from oauth2_provider.views.base import AuthorizationView, TokenView +from oauth2_provider.views.device import DeviceConfirmForm, DeviceConfirmView from rest_framework.authtoken.models import Token from rest_framework.exceptions import AuthenticationFailed @@ -2013,6 +2014,20 @@ def form_valid(self, form): return super().form_valid(form) +class StepUpDeviceConfirm(DeviceConfirmView): + """Approves a device only with a grant. Approving issues the device an + access token and a refresh token for the user.""" + + form_class = _with_grant_field(DeviceConfirmForm) + + def form_valid(self, form): + if form.cleaned_data.get("action") == "accept": + refusal = refuse_page_action(self.request, GATE_AUTHORIZE_OAUTH_APP) + if refusal is not None: + return refusal + return super().form_valid(form) + + class LockoutTokenView(TokenView): """OAuth2 token endpoint with failed-login lockout on the password grant. diff --git a/onadata/libs/stepup/checks.py b/onadata/libs/stepup/checks.py index cc0f981537..d25b395d56 100644 --- a/onadata/libs/stepup/checks.py +++ b/onadata/libs/stepup/checks.py @@ -328,7 +328,8 @@ def check_federated_step_up_binds_by_email(app_configs=None, **kwargs): def check_oauth_approval_can_step_up(app_configs=None, **kwargs): # pylint: disable=unused-argument - """The OAuth consent and application pages cannot run a challenge. + """The OAuth consent, device and application pages cannot run a + challenge. Their grant field starts empty, and the browser a client redirects there cannot add the grant header, so a gated approval is always refused. @@ -337,10 +338,11 @@ def check_oauth_approval_can_step_up(app_configs=None, **kwargs): return [] return [ CheckWarning( - f"{GATE_AUTHORIZE_OAUTH_APP!r} is gated, but /o/authorize/ and " - "/o/applications/ cannot run a step-up challenge: every user the " - "gate challenges is refused with 403 when approving or " - "registering an OAuth application.", + f"{GATE_AUTHORIZE_OAUTH_APP!r} is gated, but /o/authorize/, " + "/o/device-confirm/ and /o/applications/ cannot run a step-up " + "challenge: every user the gate challenges is refused with 403 " + "when approving a device or an OAuth application, or registering " + "or changing one.", hint=f"Remove {GATE_AUTHORIZE_OAUTH_APP!r} from STEP_UP['ACTIONS'] " "unless those refusals are intended.", id="stepup.W009", From 080ec03ae2828aaca689baa37ab727a792a3f7f0 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:11:04 +0300 Subject: [PATCH 045/120] fix: gate every OAuth application change but a rename, under a row lock --- docs/two_factor.rst | 2 +- .../apps/main/tests/test_stepup_oauth_gate.py | 60 ++++++++++++++++++- onadata/apps/main/views.py | 27 ++++++--- 3 files changed, 80 insertions(+), 9 deletions(-) diff --git a/docs/two_factor.rst b/docs/two_factor.rst index a9461cba26..71855e73c7 100644 --- a/docs/two_factor.rst +++ b/docs/two_factor.rst @@ -363,7 +363,7 @@ Audience Action ``/o/authorize/``; the approval of a device at ``/o/device-confirm/``; the registration of an application under ``/o/applications/``, or a change - to its redirect URIs or client type + to any of its fields except its name ``form-require-auth`` ``require_auth`` turned off on ``/api/v1/forms/{pk}`` ``disable-form-encryption`` the encryption of a form turned off with ``enable_kms_encryption`` on ``/api/v1/forms/{pk}`` diff --git a/onadata/apps/main/tests/test_stepup_oauth_gate.py b/onadata/apps/main/tests/test_stepup_oauth_gate.py index 5f5f6e2a1a..89b9f1e9e3 100644 --- a/onadata/apps/main/tests/test_stepup_oauth_gate.py +++ b/onadata/apps/main/tests/test_stepup_oauth_gate.py @@ -10,8 +10,9 @@ from urllib.parse import parse_qs, urlparse from django.contrib.auth import get_user_model +from django.db import connection from django.test import TestCase -from django.test.utils import override_settings +from django.test.utils import CaptureQueriesContext, override_settings from django.utils import timezone from django_otp.plugins.otp_totp.models import TOTPDevice @@ -106,10 +107,14 @@ def _registration(**overrides): } def _update(self, application, **changes): + """Post the update form as rendered, with ``changes``.""" data = self._registration( name=application.name, client_id=application.client_id, + client_secret=application.client_secret, + hash_client_secret=application.hash_client_secret, client_type=application.client_type, + authorization_grant_type=application.authorization_grant_type, redirect_uris=application.redirect_uris, ) return self.client.post( @@ -301,6 +306,59 @@ def test_a_grant_lets_the_redirect_change_through(self): self.assertEqual(application.redirect_uris, OTHER_REDIRECT_URI) self.assertFalse(spend_grant(self.user.pk, AUTHORIZE_OAUTH_APP, grant)) + def test_changing_the_grant_type_without_a_grant_is_refused(self): + """Every field but the name decides who gets a credential, or how.""" + application_model = get_application_model() + application = self._application(user=self.user) + + response = self._update( + application, + authorization_grant_type=application_model.GRANT_CLIENT_CREDENTIALS, + ) + + self.assertEqual(response.status_code, 403) + application.refresh_from_db() + self.assertEqual( + application.authorization_grant_type, + application_model.GRANT_AUTHORIZATION_CODE, + ) + + def test_changing_the_allowed_origins_without_a_grant_is_refused(self): + application = self._application(user=self.user) + + response = self._update(application, allowed_origins="https://evil.test") + + self.assertEqual(response.status_code, 403) + application.refresh_from_db() + self.assertEqual(application.allowed_origins, "") + + def test_a_new_client_secret_without_a_grant_is_refused(self): + application = self._application(user=self.user) + secret = application.client_secret + + response = self._update(application, client_secret="a-new-secret-value") + + self.assertEqual(response.status_code, 403) + application.refresh_from_db() + self.assertEqual(application.client_secret, secret) + + def test_the_update_locks_the_application_before_the_comparison(self): + """An edit that echoes the values it read cannot write back over a + concurrent change.""" + application = self._application(user=self.user) + + with CaptureQueriesContext(connection) as queries: + response = self._update(application, name="Renamed application") + + self.assertEqual(response.status_code, 302) + self.assertTrue( + any( + "oauth2_provider_application" in query["sql"] + and "FOR UPDATE" in query["sql"] + for query in queries.captured_queries + ) + ) + def test_renaming_is_not_challenged(self): application = self._application(user=self.user) self.assertEqual( diff --git a/onadata/apps/main/views.py b/onadata/apps/main/views.py index 73a778d607..2edfa1fafe 100644 --- a/onadata/apps/main/views.py +++ b/onadata/apps/main/views.py @@ -1993,21 +1993,34 @@ def form_valid(self, form): return super().form_valid(form) -def _redirect_target(values): - return (values.get("client_type"), (values.get("redirect_uris") or "").split()) +#: The application fields an update may change without a grant. Every other +#: field decides who receives its codes or tokens, or how it proves itself. +_UNGATED_APPLICATION_FIELDS = frozenset({"name", "grant"}) class StepUpApplicationUpdate(ApplicationUpdate): - """Changes an OAuth application's redirect URIs or client type only with - a grant. Other edits are not gated.""" + """Changes an OAuth application only with a grant, unless the change is + to its name alone. + + The application row is locked before the form is bound, and the lock + holds through the comparison and the save. A concurrent change cannot be + written back by an edit that echoes the values it read.""" def get_form_class(self): return _with_grant_field(super().get_form_class()) + def get_object(self, queryset=None): + application = super().get_object(queryset) + if self.request.method == "POST": + return locked_for_gates(application) + return application + + def post(self, request, *args, **kwargs): + with transaction.atomic(): + return super().post(request, *args, **kwargs) + def form_valid(self, form): - # form.instance already holds the posted values, so compare against - # form.initial. - if _redirect_target(form.initial) != _redirect_target(form.cleaned_data): + if set(form.changed_data) - _UNGATED_APPLICATION_FIELDS: refusal = refuse_page_action(self.request, GATE_AUTHORIZE_OAUTH_APP) if refusal is not None: return refusal From aac1f0294eb7eae8d2da2839fa9c26e873ca2a9b Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:12:40 +0300 Subject: [PATCH 046/120] fix: refuse the anonymous user as a share target --- .../viewsets/test_stepup_sharing_gates.py | 54 +++++++++++++++++++ .../tests/test_stepup_public_link_gate.py | 21 ++++++++ onadata/apps/main/views.py | 8 ++- onadata/libs/permissions.py | 8 +++ .../serializers/share_project_serializer.py | 11 +++- .../serializers/share_xform_serializer.py | 6 ++- 6 files changed, 105 insertions(+), 3 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py index 0044b0b0e2..5ffc4be382 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py @@ -10,6 +10,8 @@ import json from unittest.mock import patch +from django.conf import settings +from django.contrib.auth import get_user_model from django.db import connection from django.test.utils import CaptureQueriesContext, override_settings @@ -31,6 +33,7 @@ EditorRole, ManagerRole, OwnerRole, + ReadOnlyRole, ) from onadata.libs.stepup.policy import ( GATE_INVITE_PROJECT_ADMIN, @@ -980,3 +983,54 @@ def test_an_editor_invitation_kept_below_admin_is_not_challenged(self, _send): self.assertEqual(response.status_code, 200) self.assertEqual(self.project.invitations.get().role, EditorRole.name) + + +@gating(GATE_PUBLISH_DATA) +class TestShareWithTheAnonymousUser(StepUpGateTestCase): + """Signed-out requests act as the anonymous user. A share with it makes + the data readable without signing in, so neither share route accepts it. + """ + + audience = GATE_PUBLISH_DATA + + def setUp(self): + super().setUp() + self._publish_xls_form_to_project() + self.anonymous, _created = get_user_model().objects.get_or_create( + username=settings.ANONYMOUS_DEFAULT_USERNAME + ) + self.alice = self._user("alice") + + def _share_form(self, username): + view = XFormViewSet.as_view({"post": "share"}) + request = self.factory.post( + "/", data={"username": username, "role": ReadOnlyRole.name}, **self.extra + ) + return view(request, pk=self.xform.pk) + + def _share_project(self, username): + view = ProjectViewSet.as_view({"put": "share"}) + request = self.factory.put( + "/", data={"username": username, "role": ReadOnlyRole.name}, **self.extra + ) + return view(request, pk=self.project.pk) + + def test_a_form_share_with_the_anonymous_user_is_refused(self): + """A read-only share is not an admin share, so no gate stops it.""" + self.assertEqual(self._share_form("alice").status_code, 204) + self.assertTrue(ReadOnlyRole.user_has_role(self.alice, self.xform)) + + response = self._share_form(self.anonymous.username) + + self.assertEqual(response.status_code, 400) + self.assertFalse(ReadOnlyRole.user_has_role(self.anonymous, self.xform)) + + def test_a_project_share_with_the_anonymous_user_is_refused(self): + """The share would reach every form in the project.""" + self.assertEqual(self._share_project("alice").status_code, 204) + + response = self._share_project(self.anonymous.username) + + self.assertEqual(response.status_code, 400) + self.assertFalse(ReadOnlyRole.user_has_role(self.anonymous, self.project)) + self.assertFalse(ReadOnlyRole.user_has_role(self.anonymous, self.xform)) diff --git a/onadata/apps/main/tests/test_stepup_public_link_gate.py b/onadata/apps/main/tests/test_stepup_public_link_gate.py index 608f7e05a8..99fc7ebaad 100644 --- a/onadata/apps/main/tests/test_stepup_public_link_gate.py +++ b/onadata/apps/main/tests/test_stepup_public_link_gate.py @@ -6,6 +6,8 @@ from unittest.mock import patch +from django.conf import settings +from django.contrib.auth import get_user_model from django.test.utils import override_settings from django.urls import reverse @@ -17,6 +19,7 @@ from onadata.apps.main.views import set_perm PUBLISH_DATA = "publish-data" +User = get_user_model() @override_settings( @@ -95,6 +98,24 @@ def test_an_already_on_link_is_not_challenged(self): self.assertEqual(response.status_code, 200) self.assertTrue(self._link_is_on()) + def test_a_view_permission_for_the_anonymous_user_is_refused(self): + """Signed-out requests act as that user, so the form's data would be + readable without signing in.""" + anonymous, _created = User.objects.get_or_create( + username=settings.ANONYMOUS_DEFAULT_USERNAME + ) + alice = User.objects.create(username="alice") + + for user in (alice, anonymous): + self.client.post( + self.perm_url, + {"perm_type": "view", "for_user": user.username}, + HTTP_X_REQUESTED_WITH="XMLHttpRequest", + ) + + self.assertTrue(alice.has_perm("view_xform", self.xform)) + self.assertFalse(anonymous.has_perm("view_xform", self.xform)) + def test_turning_an_on_link_on_writes_nothing(self): """The request is waved through because the link is on. A write would turn it back on after a concurrent disable.""" diff --git a/onadata/apps/main/views.py b/onadata/apps/main/views.py index 2edfa1fafe..3fb869b5c8 100644 --- a/onadata/apps/main/views.py +++ b/onadata/apps/main/views.py @@ -1529,8 +1529,14 @@ def set_perm(request, username, id_string): # noqa C901 return HttpResponseBadRequest() if perm_type in ["edit", "view", "report", "remove"]: + targets = User.objects.all() + if perm_type != "remove": + # A role given to this user is given to everyone signed out. + targets = targets.exclude( + username__iexact=settings.ANONYMOUS_DEFAULT_USERNAME + ) try: - user = User.objects.get(username=for_user) + user = targets.get(username=for_user) except User.DoesNotExist: messages.add_message( request, diff --git a/onadata/libs/permissions.py b/onadata/libs/permissions.py index 3774bfc4cc..1d960c11cd 100644 --- a/onadata/libs/permissions.py +++ b/onadata/libs/permissions.py @@ -8,6 +8,7 @@ from typing import Any from django.apps import apps +from django.conf import settings from django.db.models import Q from django.db.models.base import ModelBase from django.http import Http404 @@ -516,6 +517,13 @@ def is_organization_user(user): return hasattr(user, "profile") and is_organization(user.profile) +def is_anonymous_username(username) -> bool: + """Whether ``username`` names the user that signed-out requests act as. + + A role shared with that user is shared with everyone who is signed out.""" + return str(username).casefold() == settings.ANONYMOUS_DEFAULT_USERNAME.casefold() + + def get_role(permissions, obj): """ Return the user role for the given obj permissions. diff --git a/onadata/libs/serializers/share_project_serializer.py b/onadata/libs/serializers/share_project_serializer.py index 9bebcc7115..7e1863b586 100644 --- a/onadata/libs/serializers/share_project_serializer.py +++ b/onadata/libs/serializers/share_project_serializer.py @@ -10,7 +10,12 @@ from onadata.apps.api.tasks import share_project_async from onadata.libs.models.share_project import ShareProject -from onadata.libs.permissions import ROLES, OwnerRole, get_object_users_with_permissions +from onadata.libs.permissions import ( + ROLES, + OwnerRole, + get_object_users_with_permissions, + is_anonymous_username, +) from onadata.libs.serializers.fields.project_field import ProjectField User = get_user_model() @@ -59,6 +64,10 @@ def update(self, instance, validated_data): def validate(self, attrs): for username in attrs.get("username").split(","): + if is_anonymous_username(username): + raise serializers.ValidationError( + {"username": _("Cannot share with the anonymous user.")} + ) user = User.objects.get(username=username) project = attrs.get("project") diff --git a/onadata/libs/serializers/share_xform_serializer.py b/onadata/libs/serializers/share_xform_serializer.py index d89df7826d..f9ac315e63 100644 --- a/onadata/libs/serializers/share_xform_serializer.py +++ b/onadata/libs/serializers/share_xform_serializer.py @@ -8,7 +8,7 @@ from rest_framework import serializers from onadata.libs.models.share_xform import ShareXForm -from onadata.libs.permissions import ROLES +from onadata.libs.permissions import ROLES, is_anonymous_username from onadata.libs.serializers.fields.xform_field import XFormField @@ -47,6 +47,10 @@ def validate_username(self, value): raise serializers.ValidationError( _(f"User '{value}' does not exist.") ) from e + if is_anonymous_username(value): + raise serializers.ValidationError( + _("Cannot share with the anonymous user.") + ) return value From 28475cf5a7556f1098c1e63a13b19b3b70f10173 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:13:32 +0300 Subject: [PATCH 047/120] fix: gate a change of form creator as share-form-admin --- docs/two_factor.rst | 5 +- .../test_stepup_form_and_transfer_gates.py | 49 +++++++++++++++++++ onadata/apps/api/viewsets/xform_viewset.py | 10 ++++ 3 files changed, 63 insertions(+), 1 deletion(-) diff --git a/docs/two_factor.rst b/docs/two_factor.rst index 71855e73c7..527539c508 100644 --- a/docs/two_factor.rst +++ b/docs/two_factor.rst @@ -323,7 +323,10 @@ Audience Action through ``/api/v1/projects/{pk}/forms``, if its meta permissions make the users of the project owners or managers of the form, unless ``transfer-project`` - covers the move + covers the move; a change to the ``created_by`` of a + form on ``/api/v1/forms/{pk}``, because the creator + is made an owner when the project's permissions + are applied to the form again ``share-project-admin`` a share of a project with the owner or manager role through ``/api/v1/projects/{pk}/share``, unless each user already has that role by a direct grant on the diff --git a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py index 510c875e91..3d503ee545 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py @@ -29,6 +29,7 @@ GATE_DISABLE_FORM_ENCRYPTION, GATE_FORM_REQUIRE_AUTH, GATE_PUBLISH_DATA, + GATE_SHARE_FORM_ADMIN, GATE_TRANSFER_PROJECT, ) @@ -271,6 +272,54 @@ def test_dropping_require_auth_while_publishing_is_refused_whole(self): self.assertFalse(self.xform.shared_data) +@gating(GATE_SHARE_FORM_ADMIN) +class TestFormCreatorGate(GateTestCase): + """The creator of a form is made its owner when the project's + permissions are applied to the form again, so a change of creator + appoints an owner.""" + + audience = GATE_SHARE_FORM_ADMIN + + def setUp(self): + super().setUp() + self._publish_xls_form_to_project() + self.alice = self._user("alice") + self.assertEqual(self.xform.created_by, self.user) + + def _set_creator(self, user, headers=None): + return self._patch_form( + {"created_by": f"http://testserver/api/v1/users/{user.username}"}, + headers, + ) + + def _creator(self): + self.xform.refresh_from_db() + return self.xform.created_by + + def test_changing_the_creator_is_challenged(self): + response = self._set_creator(self.alice) + + self.assert_challenged(response) + self.assertEqual(self._creator(), self.user) + + def test_a_grant_lets_the_creator_change(self): + grant = self._grant() + + response = self._set_creator(self.alice, self._with_grant(grant)) + + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(self._creator(), self.alice) + self.assert_spent(grant) + + def test_keeping_the_creator_is_not_challenged(self): + self.assert_challenged(self._set_creator(self.alice)) + + response = self._set_creator(self.user) + + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(self._creator(), self.user) + + @gating(GATE_DISABLE_FORM_ENCRYPTION) class TestDisableFormEncryptionGate(GateTestCase): """Turning encryption off stores the next submissions readable, so a diff --git a/onadata/apps/api/viewsets/xform_viewset.py b/onadata/apps/api/viewsets/xform_viewset.py index 83c48788d5..80ac53d4c5 100644 --- a/onadata/apps/api/viewsets/xform_viewset.py +++ b/onadata/apps/api/viewsets/xform_viewset.py @@ -477,6 +477,12 @@ def _drops_require_auth(xform, validated_data): ) +def _changes_creator(xform, validated_data): + """A form's creator becomes an owner of it whenever the project's + permissions are applied to the form again.""" + return validated_data.get("created_by", xform.created_by) != xform.created_by + + def _disables_encryption(xform, validated_data): """Mirrors what ``disable_xform_encryption`` refuses, so a request it would reject does not cost a grant.""" @@ -1093,6 +1099,10 @@ def _update_refusal(self, request, xform, validated_data): GATE_DISABLE_FORM_ENCRYPTION, lambda: _disables_encryption(xform, validated_data), ), + ( + GATE_SHARE_FORM_ADMIN, + lambda: _changes_creator(xform, validated_data), + ), ), ) From 3b3c72fa21676407c73f9fee7b4165571df11857 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:14:10 +0300 Subject: [PATCH 048/120] fix: hold the existing open-data link locked through the create it waives --- .../test_stepup_form_and_transfer_gates.py | 19 ++++++++++++++++ .../apps/api/viewsets/open_data_viewset.py | 22 ++++++++++++------- 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py index 3d503ee545..663f639dce 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py @@ -10,6 +10,8 @@ from unittest.mock import patch from django.conf import settings +from django.db import connection +from django.test.utils import CaptureQueriesContext from oidc.stepup_grants import spend_grant @@ -707,6 +709,23 @@ def test_asking_for_an_existing_link_is_not_challenged(self): self.assertEqual(response.data["uuid"], open_data.uuid) self.assertEqual(OpenData.objects.count(), 1) + def test_the_existing_link_stays_locked_through_the_create(self): + """A link deleted after the check cannot let the create insert a new + one without a grant.""" + open_data = self._link() + + with CaptureQueriesContext(connection) as queries: + response = self._create() + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(response.data["uuid"], open_data.uuid) + self.assertTrue( + any( + "logger_opendata" in query["sql"] and "FOR UPDATE" in query["sql"] + for query in queries.captured_queries + ) + ) + def test_an_invalid_link_keeps_the_grant(self): """Validation comes first, so an unsupported data type does not spend it.""" diff --git a/onadata/apps/api/viewsets/open_data_viewset.py b/onadata/apps/api/viewsets/open_data_viewset.py index 359a49f409..46c929538f 100644 --- a/onadata/apps/api/viewsets/open_data_viewset.py +++ b/onadata/apps/api/viewsets/open_data_viewset.py @@ -6,9 +6,11 @@ import json import re from collections import OrderedDict +from contextlib import nullcontext from django.conf import settings from django.contrib.contenttypes.models import ContentType +from django.db import transaction from django.http import StreamingHttpResponse from django.shortcuts import get_object_or_404 @@ -34,7 +36,7 @@ get_manageable_xforms, ) from onadata.libs.stepup import RequiresStepUp -from onadata.libs.stepup.policy import GATE_PUBLISH_DATA +from onadata.libs.stepup.policy import GATE_PUBLISH_DATA, is_gated from onadata.libs.utils.common_tags import ( ATTACHMENTS, GEOLOCATION, @@ -213,14 +215,16 @@ def _create_refusal(self, request, validated_data): Asking again for a form that has one returns that one unchanged. The form is resolved first, so a request refused for it keeps its - grant.""" + grant. The existing entry stays locked until the create returns it, + so it cannot be deleted or pointed elsewhere in between.""" object_id = validated_data.get("object_id") - if object_id is None: + if object_id is None or not is_gated(GATE_PUBLISH_DATA): return None xform = get_object_or_404(get_manageable_xforms(request.user), id=object_id) - if OpenData.objects.filter( + existing = OpenData.objects.select_for_update().filter( content_type=ContentType.objects.get_for_model(xform), object_id=xform.pk - ).exists(): + ) + if list(existing.values_list("pk", flat=True)[:1]): return None return self.check_step_up(request, GATE_PUBLISH_DATA) @@ -237,9 +241,11 @@ def _update_refusal(self, request, open_data, validated_data): def create(self, request, *args, **kwargs): """Create an entry, or return the form's existing one.""" - return self.gated_create( - request, lambda data: self._create_refusal(request, data) - ) + gating = is_gated(GATE_PUBLISH_DATA) + with transaction.atomic() if gating else nullcontext(): + return self.gated_create( + request, lambda data: self._create_refusal(request, data) + ) def update(self, request, *args, **kwargs): """Update an entry, the target of PUT and PATCH alike.""" From e9603df1c32fedc00655ea89d86b694c75716a05 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:15:58 +0300 Subject: [PATCH 049/120] fix: skip a queued repeat project share whose role was revoked --- onadata/apps/api/tasks.py | 35 ++++++++++++++++--- .../viewsets/test_stepup_sharing_gates.py | 34 ++++++++++++++++++ onadata/apps/api/viewsets/project_viewset.py | 24 ++++--------- onadata/libs/models/share_project.py | 3 ++ .../serializers/share_project_serializer.py | 4 ++- onadata/libs/stepup/sharing.py | 13 +++++++ 6 files changed, 90 insertions(+), 23 deletions(-) diff --git a/onadata/apps/api/tasks.py b/onadata/apps/api/tasks.py index d3c51e1283..c59e87af7e 100644 --- a/onadata/apps/api/tasks.py +++ b/onadata/apps/api/tasks.py @@ -12,7 +12,7 @@ from django.contrib.auth import get_user_model from django.core.files.storage import default_storage from django.core.files.uploadedfile import TemporaryUploadedFile -from django.db import DatabaseError, OperationalError +from django.db import DatabaseError, OperationalError, transaction from django.utils import timezone from django.utils.datastructures import MultiValueDict @@ -23,6 +23,7 @@ from onadata.apps.logger.models import Instance, Project, ProjectInvitation, XForm from onadata.celeryapp import app from onadata.libs.models.share_project import ShareProject +from onadata.libs.stepup.sharing import holds_roles, project_admin_roles_granted from onadata.libs.utils.cache_tools import ( XFORM_REGENERATE_INSTANCE_JSON_TASK, safe_cache_delete, @@ -217,8 +218,12 @@ def regenerate_form_instance_json(xform_id: int): @app.task(base=AutoRetryTask) -def share_project_async(project_id, username, role, remove=False): - """Share project asynchronously""" +def share_project_async(project_id, username, role, remove=False, repeat_only=False): + """Share project asynchronously. + + ``repeat_only`` marks a share that was let through without a step-up + grant because the user already held every owner or manager role it + grants. It is skipped if one of those roles was revoked since.""" try: project = Project.objects.get(pk=project_id) @@ -226,8 +231,28 @@ def share_project_async(project_id, username, role, remove=False): logger.exception(err) else: - share = ShareProject(project, username, role, remove) - share.save() + if repeat_only: + _repeat_project_share(project, username, role) + else: + share = ShareProject(project, username, role, remove) + share.save() + + +@transaction.atomic +def _repeat_project_share(project, username, role): + # The project row lock orders this check with a removal of a share. + project = Project.objects.select_for_update().get(pk=project.pk) + user = User.objects.filter(username=username).first() + if user is None or not holds_roles( + user, project_admin_roles_granted(project, role) + ): + logger.warning( + "Skipped a repeat share of project %s: the user no longer holds " + "the role it repeats.", + project.pk, + ) + return + ShareProject(project, username, role).save() @app.task(base=AutoRetryTask) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py index 5ffc4be382..c8450f80a4 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py @@ -20,6 +20,7 @@ from oidc.stepup_grants import issue_grant, spend_grant from onadata.apps.api.models.organization_profile import create_organization_team +from onadata.apps.api.tasks import share_project_async from onadata.apps.api.tests.viewsets.test_abstract_viewset import TestAbstractViewSet from onadata.apps.api.tools import add_user_to_team from onadata.apps.api.viewsets.project_viewset import ProjectViewSet @@ -44,6 +45,8 @@ from onadata.libs.stepup.sharing import admin_roles_granted, grants_admin_role from onadata.libs.tests.stepup.test_challenge import FEDERATED_SERVER +SHARE_TASK = "onadata.libs.serializers.share_project_serializer.share_project_async" + PROJECT_VIEWSET = "onadata.apps.api.viewsets.project_viewset" XFORM_VIEWSET = "onadata.apps.api.viewsets.xform_viewset" @@ -175,6 +178,37 @@ def test_a_role_every_target_already_holds_is_not_challenged(self): self.assertEqual(response.status_code, 204) self.assertTrue(ManagerRole.user_has_role(self.alice, self.project)) + @patch(SHARE_TASK) + def test_a_waived_share_is_queued_as_a_repeat(self, task): + """The task then checks the role again before it writes.""" + ShareProject(self.project, "alice", ManagerRole.name).save() + grant = self._grant() + + self.assertEqual( + self._share("tom", ManagerRole.name, self._with_grant(grant)).status_code, + 204, + ) + self.assertIsNone(task.apply_async.call_args.kwargs["kwargs"]) + self.assertEqual(self._share("alice", ManagerRole.name).status_code, 204) + self.assertEqual( + task.apply_async.call_args.kwargs["kwargs"], {"repeat_only": True} + ) + + def test_a_repeat_share_after_a_revocation_writes_nothing(self): + """A removal that commits before the queued share runs stands.""" + ShareProject(self.project, "tom", ManagerRole.name).save() + share_project_async(self.project.pk, "tom", ManagerRole.name, repeat_only=True) + self.assertTrue(ManagerRole.user_has_role(self.tom, self.project)) + ShareProject(self.project, "alice", ManagerRole.name).save() + ShareProject(self.project, "alice", ManagerRole.name, remove=True).save() + self.assertFalse(ManagerRole.user_has_role(self.alice, self.project)) + + share_project_async( + self.project.pk, "alice", ManagerRole.name, repeat_only=True + ) + + self.assertFalse(ManagerRole.user_has_role(self.alice, self.project)) + def test_a_role_held_only_through_a_team_is_challenged(self): """The share writes a direct grant, which stays after the user leaves the team.""" diff --git a/onadata/apps/api/viewsets/project_viewset.py b/onadata/apps/api/viewsets/project_viewset.py index 6e7a2635de..740b790f67 100644 --- a/onadata/apps/api/viewsets/project_viewset.py +++ b/onadata/apps/api/viewsets/project_viewset.py @@ -66,11 +66,10 @@ is_gated, ) from onadata.libs.stepup.sharing import ( - admin_role, - admin_roles_granted, grants_admin_role, holds_roles, move_appoints_admins, + project_admin_roles_granted, ) from onadata.libs.utils.cache_tools import ( clear_project_owner_cache, @@ -293,33 +292,24 @@ def forms(self, request, **kwargs): return Response(serializer.data) - def _admin_roles_granted(self, role_name): - """``(object, role)`` for each owner or manager role sharing the - project as ``role_name`` hands out, on the project, its forms or its - entity lists.""" - role = admin_role(role_name) - outright = ( - [(self.object, role)] - + [(entity_list, role) for entity_list in self.object.entity_lists.all()] - if role - else [] - ) - return outright + admin_roles_granted(self.object.xform_set.all(), role_name) - def _share_admin_refusal(self, request, validated_data): """Refuse appointing a project owner or manager without a grant. The role may be named outright or reached on a form through its meta - permissions. A target who already holds the role needs no grant.""" + permissions. A target who already holds the role needs no grant, and + the share is then marked ``repeat_only`` in ``validated_data``. The + task checks such a share again when it runs, in case a role was + revoked in between.""" if not is_gated(GATE_SHARE_PROJECT_ADMIN): return None - granted = self._admin_roles_granted(validated_data["role"]) + granted = project_admin_roles_granted(self.object, validated_data["role"]) if not granted: return None targets = User.objects.filter( username__in=validated_data["username"].split(",") ) if all(holds_roles(user, granted) for user in targets): + validated_data["repeat_only"] = True return None return self.check_step_up(request, GATE_SHARE_PROJECT_ADMIN) diff --git a/onadata/libs/models/share_project.py b/onadata/libs/models/share_project.py index 152e5a413b..738fefb777 100644 --- a/onadata/libs/models/share_project.py +++ b/onadata/libs/models/share_project.py @@ -6,6 +6,7 @@ from django.contrib.auth import get_user_model from django.db import transaction +from onadata.apps.logger.models.project import Project from onadata.libs.permissions import ( ROLES, ManagerRole, @@ -109,6 +110,8 @@ def save(self, **kwargs): @transaction.atomic() def __remove_user(self): + # Waits for a repeat share of this project that is being checked. + Project.objects.select_for_update().filter(pk=self.project.pk).first() role = ROLES.get(self.role) if role and self.user and self.project: diff --git a/onadata/libs/serializers/share_project_serializer.py b/onadata/libs/serializers/share_project_serializer.py index 7e1863b586..59221bf368 100644 --- a/onadata/libs/serializers/share_project_serializer.py +++ b/onadata/libs/serializers/share_project_serializer.py @@ -42,13 +42,15 @@ class ShareProjectSerializer(serializers.Serializer): def create(self, validated_data): created_instances = [] + repeat_only = validated_data.pop("repeat_only", False) for username in validated_data.pop("username").split(","): validated_data["username"] = username instance = ShareProject(**validated_data) created_instances.append(instance) share_project_async.apply_async( - args=[instance.project.pk, instance.username, instance.role] + args=[instance.project.pk, instance.username, instance.role], + kwargs={"repeat_only": True} if repeat_only else None, ) return created_instances diff --git a/onadata/libs/stepup/sharing.py b/onadata/libs/stepup/sharing.py index 6b27297a52..48636bb478 100644 --- a/onadata/libs/stepup/sharing.py +++ b/onadata/libs/stepup/sharing.py @@ -73,6 +73,19 @@ def admin_role(role_name): return ROLES[role_name] if role_name in ADMIN_ROLE_NAMES else None +def project_admin_roles_granted(project, role_name): + """``(obj, role)`` for each owner or manager role that sharing ``project`` + as ``role_name`` grants on it, its entity lists and its forms.""" + role = admin_role(role_name) + outright = ( + [(project, role)] + + [(entity_list, role) for entity_list in project.entity_lists.all()] + if role + else [] + ) + return outright + admin_roles_granted(project.xform_set.all(), role_name) + + def _direct_perms_on_model(holder, instances) -> dict: """The codenames ``holder``, a user or a group, holds by a direct grant on each of ``instances``, all of one model, keyed by primary key.""" From e3bcea6d1593a9f9d7f80a58c904b6eb8872d3e7 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:16:28 +0300 Subject: [PATCH 050/120] fix: keep the deployment default for a new organisation require_auth --- .../test_organization_profile_viewset.py | 46 ------------------- .../serializers/organization_serializer.py | 7 --- 2 files changed, 53 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_organization_profile_viewset.py b/onadata/apps/api/tests/viewsets/test_organization_profile_viewset.py index c54d14265c..360caa1b48 100644 --- a/onadata/apps/api/tests/viewsets/test_organization_profile_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_organization_profile_viewset.py @@ -316,52 +316,6 @@ def test_orgs_create(self): self.assertEqual(versions.count(), 1) self.assertEqual(versions[0].revision.user, self.user) - def test_orgs_create_require_auth_overrides_deployment_default(self): - for default, requested in ((False, True), (True, False)): - with self.subTest(default=default), override_settings( - REQUIRE_ODK_AUTHENTICATION=default - ): - org = f"default{str(default).lower()}inc" - data = { - "org": org, - "name": org, - "email": f"{org}@mail.org", - "require_auth": requested, - } - request = self.factory.post( - "/", - data=json.dumps(data), - content_type="application/json", - **self.extra, - ) - response = self.view(request) - self.assertEqual(response.status_code, 201, response.data) - profile = OrganizationProfile.objects.get(user__username=org) - self.assertEqual(profile.require_auth, requested) - - @override_settings(REQUIRE_ODK_AUTHENTICATION=True) - def test_orgs_create_form_data_without_require_auth_keeps_default(self): - request = self.factory.post( - "/", - data={"org": "forminc", "name": "Form Inc", "email": "form@mail.org"}, - **self.extra, - ) - response = self.view(request) - self.assertEqual(response.status_code, 201, response.data) - profile = OrganizationProfile.objects.get(user__username="forminc") - self.assertTrue(profile.require_auth) - - @override_settings(REQUIRE_ODK_AUTHENTICATION=True) - def test_orgs_create_form_data_with_empty_require_auth_keeps_default(self): - data = {"org": "blankinc", "name": "Blank Inc", "email": "blank@mail.org"} - request = self.factory.post( - "/", data={**data, "require_auth": ""}, **self.extra - ) - response = self.view(request) - self.assertEqual(response.status_code, 201, response.data) - profile = OrganizationProfile.objects.get(user__username="blankinc") - self.assertTrue(profile.require_auth) - def test_orgs_create_without_name(self): data = { "org": "denoinc", diff --git a/onadata/libs/serializers/organization_serializer.py b/onadata/libs/serializers/organization_serializer.py index 8f17af61d9..aa50b09355 100644 --- a/onadata/libs/serializers/organization_serializer.py +++ b/onadata/libs/serializers/organization_serializer.py @@ -153,13 +153,6 @@ def create(self, validated_data): profile = tools.create_organization_object(org, creator, validated_data) profile.save() - # The first save applies the deployment default, - # REQUIRE_ODK_AUTHENTICATION. A value the caller sent overrides it. - # Form data reads a missing boolean as False and drops an empty one, - # so the value must be both sent and validated. - if "require_auth" in self.initial_data and "require_auth" in validated_data: - profile.require_auth = validated_data["require_auth"] - profile.save(update_fields=["require_auth"]) return profile From 230c95c106e076eb99ab27a201985661a0b669a1 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:17:08 +0300 Subject: [PATCH 051/120] fix: run the invitation save checks from save() when the caller skipped them --- .../project_invitation_serializer.py | 10 ++- .../test_project_invitation_serializer.py | 70 +++++++++++++++++++ 2 files changed, 78 insertions(+), 2 deletions(-) create mode 100644 onadata/libs/tests/serializers/test_project_invitation_serializer.py diff --git a/onadata/libs/serializers/project_invitation_serializer.py b/onadata/libs/serializers/project_invitation_serializer.py index 6ba40740ce..2b4107d1b3 100644 --- a/onadata/libs/serializers/project_invitation_serializer.py +++ b/onadata/libs/serializers/project_invitation_serializer.py @@ -77,8 +77,8 @@ def _send_project_invitation_email(self, invitation_id: str) -> None: def check_can_save(self): """Refuse an invitation that cannot be saved. Call it after - ``is_valid()`` and before any step a refused request must not reach; - ``save()`` does not repeat it. + ``is_valid()`` and before any step a refused request must not reach. + ``save()`` runs it if the caller did not. These errors stay out of ``validate()`` so their body stays a list. """ @@ -95,6 +95,12 @@ def check_can_save(self): _("Only pending invitations can be updated") ) self._validate_email_exists(email) + self._can_save = True + + def save(self, **kwargs): + if not getattr(self, "_can_save", False): + self.check_can_save() + return super().save(**kwargs) def create(self, validated_data): instance = super().create(validated_data) diff --git a/onadata/libs/tests/serializers/test_project_invitation_serializer.py b/onadata/libs/tests/serializers/test_project_invitation_serializer.py new file mode 100644 index 0000000000..2d0c4dd540 --- /dev/null +++ b/onadata/libs/tests/serializers/test_project_invitation_serializer.py @@ -0,0 +1,70 @@ +""" +Tests for the ProjectInvitationSerializer module. +""" + +from unittest.mock import patch + +from django.test.utils import override_settings + +from rest_framework import serializers +from rest_framework.test import APIRequestFactory + +from onadata.apps.api.tests.viewsets.test_abstract_viewset import TestAbstractViewSet +from onadata.apps.logger.models import ProjectInvitation +from onadata.libs.serializers.project_invitation_serializer import ( + ProjectInvitationSerializer, +) + + +@override_settings(PROJECT_INVITATION_URL={"*": "https://example.com/register"}) +@patch( + "onadata.libs.serializers.project_invitation_serializer" + ".send_project_invitation_email_async.delay" +) +class TestProjectInvitationSerializerSave(TestAbstractViewSet): + """``save()`` refuses what ``check_can_save()`` refuses, for a caller + that does not call it first.""" + + def setUp(self): + super().setUp() + self._project_create() + self.request = APIRequestFactory().post("/") + self.request.user = self.user + + def _serializer(self, instance=None, **data): + payload = { + "email": "jane@example.com", + "role": "editor", + "project": self.project.pk, + **data, + } + serializer = ProjectInvitationSerializer( + instance, data=payload, context={"request": self.request} + ) + self.assertTrue(serializer.is_valid(), serializer.errors) + return serializer + + def test_save_refuses_a_duplicate_pending_invitation(self, _send): + """The first invitation saves, the second one for the same email does + not.""" + self._serializer().save() + self.assertEqual(self.project.invitations.count(), 1) + + with self.assertRaises(serializers.ValidationError): + self._serializer().save() + + self.assertEqual(self.project.invitations.count(), 1) + + def test_save_refuses_an_update_to_an_accepted_invitation(self, _send): + """Only a pending invitation can be changed.""" + invitation = self.project.invitations.create( + email="jane@example.com", + role="editor", + status=ProjectInvitation.Status.ACCEPTED, + ) + + with self.assertRaises(serializers.ValidationError): + self._serializer(invitation, role="readonly").save() + + invitation.refresh_from_db() + self.assertEqual(invitation.role, "editor") From 723a9cecdd893da906d13e7fdf41b3095ea6d795 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:17:15 +0300 Subject: [PATCH 052/120] docs: give the merged dataset transfer gate the reason it has --- onadata/apps/api/viewsets/merged_xform_viewset.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/onadata/apps/api/viewsets/merged_xform_viewset.py b/onadata/apps/api/viewsets/merged_xform_viewset.py index 45b0767bdc..5afa2f9e9d 100644 --- a/onadata/apps/api/viewsets/merged_xform_viewset.py +++ b/onadata/apps/api/viewsets/merged_xform_viewset.py @@ -38,8 +38,8 @@ def _transfers_data(project, xforms): - """A merged dataset belongs to its project's account, whose admins read - every source form's data through it.""" + """A merged dataset belongs to its project's account, as a form moved + there does.""" return any(xform.user != project.organization for xform in xforms) From 7e548ac0d68389f31318bd325d6c7d523b00321f Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:17:37 +0300 Subject: [PATCH 053/120] docs: list the step-up routes and audit events, and link two gated routes --- docs/metadata.rst | 2 ++ docs/restservices.rst | 4 ++++ docs/two_factor.rst | 15 +++++++++++++-- 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/docs/metadata.rst b/docs/metadata.rst index fce9136e73..5404b63308 100644 --- a/docs/metadata.rst +++ b/docs/metadata.rst @@ -271,3 +271,5 @@ Delete Metadata .. raw:: html
DELETE /api/v1/metadata/{pk}
+ +A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. diff --git a/docs/restservices.rst b/docs/restservices.rst index 11dff9c4f5..980e1c14c1 100644 --- a/docs/restservices.rst +++ b/docs/restservices.rst @@ -246,6 +246,10 @@ Set send_existing_data to `true`
PATCH /api/v1/restservices/pk
+.. note:: + + A deployment can require a step-up grant for this change. See :ref:`handle-step-up-challenge`. + *Payload* :: diff --git a/docs/two_factor.rst b/docs/two_factor.rst index 527539c508..00100c5e82 100644 --- a/docs/two_factor.rst +++ b/docs/two_factor.rst @@ -9,8 +9,11 @@ Each endpoint on this page acts on the authenticated caller only. No endpoint accepts a username. Thus, no caller can change the second factor of another user. -All endpoints are under ``/api/v1/totp``. If a deployment does not enable -two-factor (``ENABLE_TWO_FACTOR``), they answer **404**. On some deployments, +The second-factor endpoints are under ``/api/v1/totp``. The step-up +endpoints are under ``/api/v1/stepup``, and ``/api/v1/user/capabilities`` +tells a client which controls to show. If a deployment does not enable +two-factor (``ENABLE_TWO_FACTOR``), the ``/api/v1/totp`` endpoints answer +**404**. On some deployments, an identity provider owns the second factor, not Ona. There, the management endpoints answer **409** with ``"error": "not_managed_here"``. Read the ``status`` answer before you show any of these controls. @@ -515,6 +518,14 @@ to the security audit log: - ``two-factor-recovery-codes-generated``. A user replaced the recovery set. - ``two-factor-recovery-codes-viewed``. A user read the unspent set again. +It also records each decision of a step-up gate: + +- ``step-up-grant-spent``. A gated change used a grant. +- ``step-up-grant-rejected``. A gated change sent a grant that was not + valid, so the server asked for a new one. +- ``step-up-enrol-required``. A gated change came from a user with no second + factor, and ``NO_FACTOR_POLICY`` refused it. + The server sends an email to the account owner when a user enrols an authenticator, disables two-factor, or replaces the recovery set. The owner gets this email, whoever made the change. From bf3a7036bf228b9deb468fdd660438e52ef6aa57 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:18:10 +0300 Subject: [PATCH 054/120] test: move the step-up gate test helpers into test_utils --- .../viewsets/test_stepup_connect_gates.py | 8 +-- .../viewsets/test_stepup_dataview_gates.py | 2 +- .../test_stepup_form_and_transfer_gates.py | 8 +-- .../viewsets/test_stepup_form_move_gates.py | 8 +-- .../test_stepup_merged_xform_gates.py | 2 +- .../viewsets/test_stepup_metadata_gates.py | 12 ++-- .../test_stepup_organization_gates.py | 10 +-- .../viewsets/test_stepup_sharing_gates.py | 69 +++---------------- .../tests/viewsets/test_stepup_team_gates.py | 8 +-- .../test_stepup_user_profile_gates.py | 8 +-- .../viewsets/test_stepup_username_gate.py | 4 +- .../v2/test_organization_profile_viewset.py | 2 +- .../viewsets/test_stepup_webhook_gate.py | 8 +-- onadata/libs/test_utils/stepup.py | 69 +++++++++++++++++++ 14 files changed, 117 insertions(+), 101 deletions(-) create mode 100644 onadata/libs/test_utils/stepup.py diff --git a/onadata/apps/api/tests/viewsets/test_stepup_connect_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_connect_gates.py index 48a57ca716..7978f378db 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_connect_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_connect_gates.py @@ -12,14 +12,14 @@ from rest_framework.test import force_authenticate from onadata.apps.api.models.odk_token import ODKToken -from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import ( - StepUpGateTestCase, - gating, -) from onadata.apps.api.tests.viewsets.test_stepup_user_profile_gates import ( ACCOUNT_ACTIONS, ) from onadata.apps.api.viewsets.connect_viewset import ConnectViewSet +from onadata.libs.test_utils.stepup import ( + StepUpGateTestCase, + gating, +) @gating(*ACCOUNT_ACTIONS) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_dataview_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_dataview_gates.py index 530e8cf176..76f9e2c561 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_dataview_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_dataview_gates.py @@ -11,11 +11,11 @@ from onadata.apps.api.tests.viewsets.test_stepup_form_and_transfer_gates import ( GateTestCase, ) -from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import gating from onadata.apps.api.viewsets.dataview_viewset import DataViewViewSet from onadata.apps.logger.models import DataView, Project, XForm from onadata.libs.permissions import ManagerRole from onadata.libs.stepup.policy import GATE_PUBLISH_DATA +from onadata.libs.test_utils.stepup import gating COLUMNS = '["name", "age"]' diff --git a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py index 663f639dce..b4ca8db285 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py @@ -15,10 +15,6 @@ from oidc.stepup_grants import spend_grant -from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import ( - StepUpGateTestCase, - gating, -) from onadata.apps.api.tools import add_user_to_organization from onadata.apps.api.viewsets.open_data_viewset import OpenDataViewSet from onadata.apps.api.viewsets.project_viewset import ProjectViewSet @@ -34,6 +30,10 @@ GATE_SHARE_FORM_ADMIN, GATE_TRANSFER_PROJECT, ) +from onadata.libs.test_utils.stepup import ( + StepUpGateTestCase, + gating, +) ONE_GATED_CHANGE = "one_gated_change_per_request" diff --git a/onadata/apps/api/tests/viewsets/test_stepup_form_move_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_form_move_gates.py index 27fecdab36..04fb94430d 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_form_move_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_form_move_gates.py @@ -9,13 +9,13 @@ from onadata.apps.api.tests.viewsets.test_stepup_form_and_transfer_gates import ( GateTestCase, ) -from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import ( - EDITOR_BECOMES_OWNER, - gating, -) from onadata.apps.api.viewsets.project_viewset import ProjectViewSet from onadata.libs.permissions import EditorRole, ManagerRole, OwnerRole from onadata.libs.stepup.policy import GATE_SHARE_FORM_ADMIN, GATE_TRANSFER_PROJECT +from onadata.libs.test_utils.stepup import ( + EDITOR_BECOMES_OWNER, + gating, +) @gating(GATE_SHARE_FORM_ADMIN) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_merged_xform_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_merged_xform_gates.py index 36d1719ca0..426353559f 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_merged_xform_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_merged_xform_gates.py @@ -9,10 +9,10 @@ from onadata.apps.api.tests.viewsets.test_stepup_form_and_transfer_gates import ( GateTestCase, ) -from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import gating from onadata.apps.api.viewsets.merged_xform_viewset import MergedXFormViewSet from onadata.apps.logger.models import MergedXForm, Project from onadata.libs.stepup.policy import GATE_PUBLISH_DATA, GATE_TRANSFER_PROJECT +from onadata.libs.test_utils.stepup import gating from onadata.libs.utils.user_auth import get_user_default_project diff --git a/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py index 0a5e2f7db5..e37219a68d 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py @@ -14,12 +14,6 @@ from onadata.apps.api.tests.viewsets.test_stepup_form_and_transfer_gates import ( GateTestCase, ) -from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import ( - EDITOR_BECOMES_MANAGER, - EDITOR_BECOMES_OWNER, - EDITOR_STAYS_BELOW_ADMIN, - gating, -) from onadata.apps.api.tools import add_user_to_team from onadata.apps.api.viewsets.metadata_viewset import MetaDataViewSet from onadata.apps.logger.models import XForm @@ -38,6 +32,12 @@ GATE_PUBLISH_DATA, GATE_SHARE_FORM_ADMIN, ) +from onadata.libs.test_utils.stepup import ( + EDITOR_BECOMES_MANAGER, + EDITOR_BECOMES_OWNER, + EDITOR_STAYS_BELOW_ADMIN, + gating, +) from onadata.libs.utils.common_tags import TEXTIT, XFORM_META_PERMS DEFAULT_META_PERMS = "editor|dataentry|readonly" diff --git a/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py index 020d6e0060..e5c0849db2 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py @@ -15,11 +15,6 @@ OrganizationProfile, get_organization_members_team, ) -from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import ( - EDITOR_BECOMES_OWNER, - StepUpGateTestCase, - gating, -) from onadata.apps.api.tools import get_organization_members from onadata.apps.api.viewsets.organization_profile_viewset import ( OrganizationProfileViewSet, @@ -35,6 +30,11 @@ OwnerRole, get_team_project_default_permissions, ) +from onadata.libs.test_utils.stepup import ( + EDITOR_BECOMES_OWNER, + StepUpGateTestCase, + gating, +) ORG_VIEWSET = "onadata.apps.api.viewsets.organization_profile_viewset" diff --git a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py index c8450f80a4..19b6475f6e 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py @@ -15,18 +15,15 @@ from django.db import connection from django.test.utils import CaptureQueriesContext, override_settings -from django_otp.plugins.otp_totp.models import TOTPDevice from guardian.shortcuts import get_user_perms -from oidc.stepup_grants import issue_grant, spend_grant +from oidc.stepup_grants import spend_grant from onadata.apps.api.models.organization_profile import create_organization_team from onadata.apps.api.tasks import share_project_async -from onadata.apps.api.tests.viewsets.test_abstract_viewset import TestAbstractViewSet from onadata.apps.api.tools import add_user_to_team from onadata.apps.api.viewsets.project_viewset import ProjectViewSet from onadata.apps.api.viewsets.xform_viewset import XFormViewSet from onadata.apps.logger.models import EntityList, Project, ProjectInvitation, XForm -from onadata.apps.main.models import MetaData from onadata.libs.models.share_project import ShareProject from onadata.libs.models.share_xform import ShareXForm from onadata.libs.permissions import ( @@ -43,6 +40,13 @@ GATE_SHARE_PROJECT_ADMIN, ) from onadata.libs.stepup.sharing import admin_roles_granted, grants_admin_role +from onadata.libs.test_utils.stepup import ( + EDITOR_BECOMES_MANAGER, + EDITOR_BECOMES_OWNER, + EDITOR_STAYS_BELOW_ADMIN, + StepUpGateTestCase, + gating, +) from onadata.libs.tests.stepup.test_challenge import FEDERATED_SERVER SHARE_TASK = "onadata.libs.serializers.share_project_serializer.share_project_async" @@ -50,63 +54,6 @@ PROJECT_VIEWSET = "onadata.apps.api.viewsets.project_viewset" XFORM_VIEWSET = "onadata.apps.api.viewsets.xform_viewset" -#: ``xform_meta_perms`` values. The first slot replaces an editor's role. -EDITOR_BECOMES_OWNER = "owner|dataentry-only|readonly" -EDITOR_BECOMES_MANAGER = "manager|dataentry-only|readonly" -EDITOR_STAYS_BELOW_ADMIN = "editor-minor|dataentry-only|readonly" - - -def gating(*audiences, **settings): - """Gate exactly ``audiences``, for a user with a confirmed factor.""" - return override_settings( - STEP_UP={ - "MODE": "local", - "ACTIONS": list(audiences), - "NO_FACTOR_POLICY": "skip_gate", - }, - **settings, - ) - - -class StepUpGateTestCase(TestAbstractViewSet): - """Gives ``self.user`` a second factor. Without one, ``skip_gate`` lets - every request through ungated.""" - - audience = None - - def setUp(self): - super().setUp() - TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) - - def _grant(self): - return issue_grant(self.user.pk, self.audience) - - def _with_grant(self, grant): - return {"HTTP_X_STEP_UP_GRANT": grant} - - def assert_challenged(self, response): - """Refused with a challenge naming this test case's audience.""" - self.assertEqual(response.status_code, 401, response.data) - self.assertEqual(response.data["audience"], self.audience) - self.assertEqual( - response["WWW-Authenticate"], - f'StepUp error="step_up_required", audience="{self.audience}", ' - 'dialect="local-totp"', - ) - - def assert_spent(self, grant): - """The gate consumed ``grant``, so the request went through it.""" - self.assertFalse(spend_grant(self.user.pk, self.audience, grant)) - - def _user(self, username): - return self._create_user_profile( - {"username": username, "email": f"{username}@localhost.com"} - ).user - - def _set_meta_perms(self, value): - MetaData.xform_meta_permission(self.xform, data_value=value) - self.assertEqual(MetaData.xform_meta_permission(self.xform).data_value, value) - @gating(GATE_SHARE_PROJECT_ADMIN) class TestShareProjectAdminGate(StepUpGateTestCase): diff --git a/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py index 04cf986868..85ba2863e7 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py @@ -9,10 +9,6 @@ from oidc.stepup_grants import issue_grant, spend_grant from onadata.apps.api.models.organization_profile import create_organization_team -from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import ( - StepUpGateTestCase, - gating, -) from onadata.apps.api.tools import add_user_to_team from onadata.apps.api.viewsets.team_viewset import TeamViewSet from onadata.libs.models.share_team_project import ShareTeamProject @@ -23,6 +19,10 @@ OwnerRole, ReadOnlyRole, ) +from onadata.libs.test_utils.stepup import ( + StepUpGateTestCase, + gating, +) class TeamGateTestCase(StepUpGateTestCase): diff --git a/onadata/apps/api/tests/viewsets/test_stepup_user_profile_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_user_profile_gates.py index 462ace90db..dac65e7f0f 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_user_profile_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_user_profile_gates.py @@ -16,13 +16,13 @@ from oidc.stepup_grants import issue_grant, spend_grant from registration.models import RegistrationProfile -from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import ( - StepUpGateTestCase, - gating, -) from onadata.apps.api.viewsets.user_profile_viewset import UserProfileViewSet from onadata.apps.main.models import UserProfile from onadata.libs.stepup.policy import eu_consent_record +from onadata.libs.test_utils.stepup import ( + StepUpGateTestCase, + gating, +) from onadata.libs.utils.cache_tools import ( CHANGE_PASSWORD_ATTEMPTS, LOCKOUT_CHANGE_PASSWORD_USER, diff --git a/onadata/apps/api/tests/viewsets/test_stepup_username_gate.py b/onadata/apps/api/tests/viewsets/test_stepup_username_gate.py index 081a479e2d..6644c43101 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_username_gate.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_username_gate.py @@ -8,11 +8,11 @@ from oidc.stepup_grants import issue_grant from registration.models import RegistrationProfile -from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import ( +from onadata.apps.api.viewsets.user_profile_viewset import UserProfileViewSet +from onadata.libs.test_utils.stepup import ( StepUpGateTestCase, gating, ) -from onadata.apps.api.viewsets.user_profile_viewset import UserProfileViewSet CHANGE_USERNAME = "change-username" NEW_USERNAME = "robert" diff --git a/onadata/apps/api/tests/viewsets/v2/test_organization_profile_viewset.py b/onadata/apps/api/tests/viewsets/v2/test_organization_profile_viewset.py index 3639466cc6..78be287f1f 100644 --- a/onadata/apps/api/tests/viewsets/v2/test_organization_profile_viewset.py +++ b/onadata/apps/api/tests/viewsets/v2/test_organization_profile_viewset.py @@ -12,7 +12,6 @@ from onadata.apps.api.models.organization_profile import OrganizationProfile from onadata.apps.api.tests.viewsets.test_abstract_viewset import TestAbstractViewSet -from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import gating from onadata.apps.api.viewsets.organization_profile_viewset import ( OrganizationProfileViewSet as OrganizationProfileViewSetV1, ) @@ -20,6 +19,7 @@ OrganizationProfileViewSet, ) from onadata.apps.main.models import UserProfile +from onadata.libs.test_utils.stepup import gating from onadata.libs.utils.cache_tools import ORG_PROFILE_V2_CACHE diff --git a/onadata/apps/restservice/tests/viewsets/test_stepup_webhook_gate.py b/onadata/apps/restservice/tests/viewsets/test_stepup_webhook_gate.py index 2969d418b8..5b2ba07bcf 100644 --- a/onadata/apps/restservice/tests/viewsets/test_stepup_webhook_gate.py +++ b/onadata/apps/restservice/tests/viewsets/test_stepup_webhook_gate.py @@ -9,16 +9,16 @@ from oidc.stepup_grants import issue_grant, spend_grant from onadata.apps.api.tests.viewsets.test_merged_xform_viewset import MD -from onadata.apps.api.tests.viewsets.test_stepup_sharing_gates import ( - StepUpGateTestCase, - gating, -) from onadata.apps.api.viewsets.merged_xform_viewset import MergedXFormViewSet from onadata.apps.logger.models import XForm from onadata.apps.main.models.meta_data import MetaData from onadata.apps.restservice.models import RestService from onadata.apps.restservice.views import add_service from onadata.apps.restservice.viewsets.restservices_viewset import RestServicesViewSet +from onadata.libs.test_utils.stepup import ( + StepUpGateTestCase, + gating, +) from onadata.libs.utils.user_auth import get_user_default_project CHANGE_WEBHOOK = "change-webhook" diff --git a/onadata/libs/test_utils/stepup.py b/onadata/libs/test_utils/stepup.py new file mode 100644 index 0000000000..35d48c9e6d --- /dev/null +++ b/onadata/libs/test_utils/stepup.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- +""" +Helpers for tests of the step-up gates. +""" + +from django.test.utils import override_settings + +from django_otp.plugins.otp_totp.models import TOTPDevice +from oidc.stepup_grants import issue_grant, spend_grant + +from onadata.apps.api.tests.viewsets.test_abstract_viewset import TestAbstractViewSet +from onadata.apps.main.models import MetaData + +#: ``xform_meta_perms`` values. The first slot replaces an editor's role. +EDITOR_BECOMES_OWNER = "owner|dataentry-only|readonly" +EDITOR_BECOMES_MANAGER = "manager|dataentry-only|readonly" +EDITOR_STAYS_BELOW_ADMIN = "editor-minor|dataentry-only|readonly" + + +def gating(*audiences, **settings): + """Gate exactly ``audiences``, for a user with a confirmed factor.""" + return override_settings( + STEP_UP={ + "MODE": "local", + "ACTIONS": list(audiences), + "NO_FACTOR_POLICY": "skip_gate", + }, + **settings, + ) + + +class StepUpGateTestCase(TestAbstractViewSet): + """Gives ``self.user`` a second factor. Without one, ``skip_gate`` lets + every request through ungated.""" + + audience = None + + def setUp(self): + super().setUp() + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + + def _grant(self): + return issue_grant(self.user.pk, self.audience) + + def _with_grant(self, grant): + return {"HTTP_X_STEP_UP_GRANT": grant} + + def assert_challenged(self, response): + """Refused with a challenge naming this test case's audience.""" + self.assertEqual(response.status_code, 401, response.data) + self.assertEqual(response.data["audience"], self.audience) + self.assertEqual( + response["WWW-Authenticate"], + f'StepUp error="step_up_required", audience="{self.audience}", ' + 'dialect="local-totp"', + ) + + def assert_spent(self, grant): + """The gate consumed ``grant``, so the request went through it.""" + self.assertFalse(spend_grant(self.user.pk, self.audience, grant)) + + def _user(self, username): + return self._create_user_profile( + {"username": username, "email": f"{username}@localhost.com"} + ).user + + def _set_meta_perms(self, value): + MetaData.xform_meta_permission(self.xform, data_value=value) + self.assertEqual(MetaData.xform_meta_permission(self.xform).data_value, value) From 07c7d004fec25af24d314379a70cbdea462c8aa1 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:19:12 +0300 Subject: [PATCH 055/120] fix: gate a merge of forms kept in another account's project as a transfer --- docs/two_factor.rst | 3 +- .../test_stepup_merged_xform_gates.py | 44 ++++++++++++++++++- .../apps/api/viewsets/merged_xform_viewset.py | 17 ++++--- 3 files changed, 57 insertions(+), 7 deletions(-) diff --git a/docs/two_factor.rst b/docs/two_factor.rst index 00100c5e82..6cf03e7649 100644 --- a/docs/two_factor.rst +++ b/docs/two_factor.rst @@ -364,7 +364,8 @@ Audience Action ``/api/v1/projects/{pk}/forms``, or by a change to its ``owner`` or ``project`` on ``/api/v1/forms/{pk}``; a new merged dataset in the project of another account - from a form + from a form; a new merged dataset from a form that + another account owns, or keeps in its project ``authorize-oauth-app`` the approval of an OAuth application at ``/o/authorize/``; the approval of a device at ``/o/device-confirm/``; the registration of an diff --git a/onadata/apps/api/tests/viewsets/test_stepup_merged_xform_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_merged_xform_gates.py index 426353559f..79f7357c4f 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_merged_xform_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_merged_xform_gates.py @@ -10,7 +10,7 @@ GateTestCase, ) from onadata.apps.api.viewsets.merged_xform_viewset import MergedXFormViewSet -from onadata.apps.logger.models import MergedXForm, Project +from onadata.apps.logger.models import MergedXForm, Project, XForm from onadata.libs.stepup.policy import GATE_PUBLISH_DATA, GATE_TRANSFER_PROJECT from onadata.libs.test_utils.stepup import gating from onadata.libs.utils.user_auth import get_user_default_project @@ -151,6 +151,48 @@ def test_merging_within_the_account_is_not_challenged(self): self.own_project, ) + def _keep_forms_in(self, project): + XForm.objects.filter(pk__in=[self.xform_a.pk, self.xform_b.pk]).update( + project=project + ) + for xform in (self.xform_a, self.xform_b): + xform.refresh_from_db() + self.assertEqual(xform.project, project) + self.assertEqual(xform.user, self.user) + + def test_merging_from_another_accounts_project_is_challenged(self): + """The user owns the forms, but another account owns the project they + are kept in, and so their data.""" + self._keep_forms_in(self.org_project) + + response = self._merge(self.own_project) + + self.assert_challenged(response) + self.assertFalse(MergedXForm.objects.exists()) + + def test_a_grant_lets_the_merge_from_another_accounts_project_through(self): + """With a grant the merged dataset is made in the user's project.""" + self._keep_forms_in(self.org_project) + grant = self._grant() + + response = self._merge(self.own_project, self._with_grant(grant)) + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual( + MergedXForm.objects.get(pk=response.data["id"]).project, + self.own_project, + ) + self.assert_spent(grant) + + def test_merging_own_forms_from_own_project_is_not_challenged(self): + """Forms the user's account owns and keeps stay with it.""" + self.assert_challenged(self._merge(self.org_project)) + self._keep_forms_in(self.own_project) + + response = self._merge(self.own_project) + + self.assertEqual(response.status_code, 201, response.data) + @gating(GATE_TRANSFER_PROJECT, GATE_PUBLISH_DATA) def test_a_merge_that_also_publishes_is_refused_whole(self): """Into another account's public project is two gated changes.""" diff --git a/onadata/apps/api/viewsets/merged_xform_viewset.py b/onadata/apps/api/viewsets/merged_xform_viewset.py index 5afa2f9e9d..e73ed4cd1a 100644 --- a/onadata/apps/api/viewsets/merged_xform_viewset.py +++ b/onadata/apps/api/viewsets/merged_xform_viewset.py @@ -16,7 +16,7 @@ from rest_framework.settings import api_settings from onadata.apps.api.permissions import XFormPermissions -from onadata.apps.logger.models import Instance, MergedXForm, XForm +from onadata.apps.logger.models import Instance, MergedXForm, Project, XForm from onadata.libs import filters from onadata.libs.pagination import StandardPageNumberPagination from onadata.libs.permissions import require_xform_data_access @@ -39,8 +39,15 @@ def _transfers_data(project, xforms): """A merged dataset belongs to its project's account, as a form moved - there does.""" - return any(xform.user != project.organization for xform in xforms) + there does. Its admins read the data of every source form through it, so + a source form owned by another account, or kept in a project of another + account, is handed over.""" + account = project.organization_id + return any(xform.user_id != account for xform in xforms) or ( + Project.objects.filter(pk__in={xform.project_id for xform in xforms}) + .exclude(organization_id=account) + .exists() + ) def _publishes_data(project, xforms): @@ -88,8 +95,8 @@ def _create_refusal(self, request, validated_data): return self.gated_change_refusal( request, ( - (GATE_TRANSFER_PROJECT, _transfers_data(project, xforms)), - (GATE_PUBLISH_DATA, _publishes_data(project, xforms)), + (GATE_TRANSFER_PROJECT, lambda: _transfers_data(project, xforms)), + (GATE_PUBLISH_DATA, lambda: _publishes_data(project, xforms)), ), ) From 92ee202028dd90d2d35ba103f67c03c1516b234f Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:25:04 +0300 Subject: [PATCH 056/120] test: describe each step-up test in one line --- .../tests/viewsets/test_connect_viewset.py | 2 + .../viewsets/test_stepup_connect_gates.py | 2 + .../test_stepup_form_and_transfer_gates.py | 40 ++++++++++++++ .../viewsets/test_stepup_form_move_gates.py | 1 + .../viewsets/test_stepup_metadata_gates.py | 15 +++++ .../test_stepup_organization_gates.py | 14 +++++ .../viewsets/test_stepup_sharing_gates.py | 55 +++++++++++++++++++ .../tests/viewsets/test_stepup_team_gates.py | 17 ++++++ .../test_stepup_user_profile_gates.py | 6 ++ .../viewsets/test_stepup_username_gate.py | 6 ++ .../api/tests/viewsets/test_stepup_viewset.py | 10 ++++ .../api/tests/viewsets/test_totp_viewset.py | 3 + .../viewsets/test_user_profile_viewset.py | 1 + .../tests/test_stepup_legacy_publish_gate.py | 4 ++ .../apps/main/tests/test_stepup_oauth_gate.py | 25 +++++++++ onadata/apps/main/tests/test_stepup_pages.py | 7 +++ .../tests/test_stepup_public_link_gate.py | 6 ++ .../viewsets/test_stepup_webhook_gate.py | 15 +++++ onadata/libs/tests/stepup/test_challenge.py | 11 ++++ onadata/libs/tests/stepup/test_checks.py | 29 ++++++++++ onadata/libs/tests/stepup/test_drf.py | 21 +++++++ onadata/libs/tests/stepup/test_policy.py | 3 + 22 files changed, 293 insertions(+) diff --git a/onadata/apps/api/tests/viewsets/test_connect_viewset.py b/onadata/apps/api/tests/viewsets/test_connect_viewset.py index 206a232df9..06cff03f00 100644 --- a/onadata/apps/api/tests/viewsets/test_connect_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_connect_viewset.py @@ -41,6 +41,8 @@ def setUp(self): self.view = ConnectViewSet.as_view({"get": "capabilities"}) def test_local_mode_reports_onadata_as_the_owner(self): + """In local mode, OnaData manages two-factor and password change, with no + identity provider.""" response = self.view(self.factory.get("/", **self.extra)) self.assertEqual(response.status_code, 200) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_connect_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_connect_gates.py index 7978f378db..62600948b8 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_connect_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_connect_gates.py @@ -52,6 +52,7 @@ def _active_odk_tokens(self): ) def test_regenerating_the_api_token_is_challenged(self): + """Without a grant, the request answers 401 and the old API token stays.""" old_token = self._api_token() response = self._regenerate() @@ -116,6 +117,7 @@ def test_regenerating_the_odk_token_is_challenged(self): self.assertEqual(self._active_odk_tokens(), [old_token.pk]) def test_a_grant_lets_the_odk_token_regeneration_through(self): + """A grant replaces the old ODK token with exactly one new active token.""" old_token = ODKToken.objects.create(user=self.user) grant = issue_grant(self.user.pk, "regenerate-odk-token") diff --git a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py index b4ca8db285..f25005c463 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py @@ -87,6 +87,8 @@ def _owner(self): return self.project.organization def test_transferring_a_project_is_challenged(self): + """Without a grant, a new owner answers 401 and the project stays with the + user.""" response = self._patch({"owner": self.org_url}) self.assert_challenged(response) @@ -104,6 +106,7 @@ def test_a_full_update_transferring_a_project_is_challenged(self): self.assertEqual(self._owner(), self.user) def test_a_grant_lets_the_transfer_through(self): + """A grant moves the project to the organisation and is spent.""" grant = self._grant() response = self._patch({"owner": self.org_url}, self._with_grant(grant)) @@ -113,6 +116,8 @@ def test_a_grant_lets_the_transfer_through(self): self.assert_spent(grant) def test_keeping_the_owner_is_not_challenged(self): + """A PATCH that names the current owner needs no grant, so the rename is + saved.""" self.assert_challenged(self._patch({"owner": self.org_url})) response = self._patch({"owner": self.user_url, "name": "renamed"}) @@ -189,6 +194,8 @@ def test_a_failed_transfer_leaves_no_permissions(self): @gating(GATE_TRANSFER_PROJECT, GATE_PUBLISH_DATA) def test_a_transfer_that_also_publishes_is_refused_whole(self): + """A transfer that also makes the project public answers 400 and changes + nothing.""" grant = self._grant() response = self._patch( @@ -226,12 +233,15 @@ def _require_auth(self): return self.xform.require_auth def test_turning_off_require_auth_is_challenged(self): + """Without a grant, turning off ``require_auth`` answers 401 and the value stays + on.""" response = self._patch_form({"require_auth": False}) self.assert_challenged(response) self.assertTrue(self._require_auth()) def test_a_grant_lets_require_auth_off(self): + """A grant turns off ``require_auth`` and is spent.""" grant = self._grant() response = self._patch_form({"require_auth": False}, self._with_grant(grant)) @@ -241,6 +251,7 @@ def test_a_grant_lets_require_auth_off(self): self.assert_spent(grant) def test_turning_on_require_auth_is_not_challenged(self): + """Turning on ``require_auth`` needs no grant, but turning it off does.""" self.assert_challenged(self._patch_form({"require_auth": False})) self._set_require_auth(False) @@ -250,6 +261,8 @@ def test_turning_on_require_auth_is_not_challenged(self): self.assertTrue(self._require_auth()) def test_keeping_require_auth_on_is_not_challenged(self): + """A PATCH that keeps ``require_auth`` on needs no grant, so the edit is + saved.""" self.assert_challenged(self._patch_form({"require_auth": False})) response = self._patch_form({"require_auth": True, "description": "renamed"}) @@ -260,6 +273,8 @@ def test_keeping_require_auth_on_is_not_challenged(self): @gating(GATE_FORM_REQUIRE_AUTH, GATE_PUBLISH_DATA) def test_dropping_require_auth_while_publishing_is_refused_whole(self): + """Turning off ``require_auth`` and publishing data at once answers 400 and + changes nothing.""" grant = self._grant() response = self._patch_form( @@ -299,12 +314,14 @@ def _creator(self): return self.xform.created_by def test_changing_the_creator_is_challenged(self): + """Without a grant, a new ``created_by`` answers 401 and the creator stays.""" response = self._set_creator(self.alice) self.assert_challenged(response) self.assertEqual(self._creator(), self.user) def test_a_grant_lets_the_creator_change(self): + """A grant sets the new creator and is spent.""" grant = self._grant() response = self._set_creator(self.alice, self._with_grant(grant)) @@ -314,6 +331,7 @@ def test_a_grant_lets_the_creator_change(self): self.assert_spent(grant) def test_keeping_the_creator_is_not_challenged(self): + """A PATCH that names the current creator needs no grant.""" self.assert_challenged(self._set_creator(self.alice)) response = self._set_creator(self.user) @@ -342,12 +360,15 @@ def _encrypted(self): return self.xform.encrypted def test_disabling_encryption_is_challenged(self): + """Without a grant, turning off encryption answers 401 and the form stays + encrypted.""" response = self._patch_form({"enable_kms_encryption": False}) self.assert_challenged(response) self.assertTrue(self._encrypted()) def test_a_grant_lets_encryption_off(self): + """A grant turns off encryption and is spent.""" grant = self._grant() response = self._patch_form( @@ -359,6 +380,7 @@ def test_a_grant_lets_encryption_off(self): self.assert_spent(grant) def test_enabling_encryption_is_not_challenged(self): + """Turning on encryption needs no grant, but turning it off does.""" self.assert_challenged(self._patch_form({"enable_kms_encryption": False})) response = self._patch_form({"enable_kms_encryption": True}) @@ -419,6 +441,8 @@ def _reload(self): self.xform.refresh_from_db() def test_moving_a_private_form_into_a_public_project_is_challenged(self): + """Without a grant, the move answers 401 and the form and its data stay + private.""" response = self._move(self.public_project) self.assert_challenged(response) @@ -427,6 +451,8 @@ def test_moving_a_private_form_into_a_public_project_is_challenged(self): self.assertFalse(self.xform.shared_data) def test_a_grant_lets_the_form_move(self): + """A grant moves the form into the public project, shares its data and is + spent.""" grant = self._grant() response = self._move(self.public_project, self._with_grant(grant)) @@ -438,6 +464,7 @@ def test_a_grant_lets_the_form_move(self): self.assert_spent(grant) def test_moving_into_a_private_project_is_not_challenged(self): + """A move into a private project needs no grant and keeps the data private.""" self.assert_challenged(self._move(self.public_project)) self._project_create({"name": "closed"}) closed = self.project @@ -451,6 +478,7 @@ def test_moving_into_a_private_project_is_not_challenged(self): self.assertFalse(self.xform.shared_data) def test_moving_a_public_form_is_not_challenged(self): + """A form that is already public moves into a public project without a grant.""" self.assert_challenged(self._move(self.public_project)) XForm.objects.filter(pk=self.xform.pk).update(shared=True, shared_data=True) @@ -493,6 +521,7 @@ def test_moving_by_update_into_a_public_project_is_challenged(self): self.assertEqual(self.xform.project, self.private_project) def test_a_grant_lets_the_update_move_the_form(self): + """A grant lets an update move the form into the public project and is spent.""" grant = self._grant() response = self._patch_project(self.public_project, self._with_grant(grant)) @@ -503,6 +532,7 @@ def test_a_grant_lets_the_update_move_the_form(self): self.assert_spent(grant) def test_moving_by_update_into_a_private_project_is_not_challenged(self): + """An update that moves the form into a private project needs no grant.""" self.assert_challenged(self._patch_project(self.public_project)) self._project_create({"name": "closed"}) closed = self.project @@ -683,12 +713,14 @@ def _link(self, active=True): return open_data def test_creating_a_link_is_challenged(self): + """Without a grant, a new open-data link answers 401 and none is stored.""" response = self._create() self.assert_challenged(response) self.assertFalse(OpenData.objects.exists()) def test_a_grant_lets_the_link_be_created(self): + """A grant creates an active link, returns its uuid and is spent.""" grant = self._grant() response = self._create(self._with_grant(grant)) @@ -700,6 +732,8 @@ def test_a_grant_lets_the_link_be_created(self): self.assert_spent(grant) def test_asking_for_an_existing_link_is_not_challenged(self): + """A create for a form that has an active link returns that link without a + grant.""" self.assert_challenged(self._create()) open_data = self._link() @@ -739,6 +773,7 @@ def test_an_invalid_link_keeps_the_grant(self): self.assertFalse(OpenData.objects.exists()) def test_reactivating_a_link_is_challenged(self): + """Without a grant, turning an inactive link on answers 401 and it stays off.""" open_data = self._link(active=False) response = self._patch(open_data, {"active": True}) @@ -748,6 +783,7 @@ def test_reactivating_a_link_is_challenged(self): self.assertFalse(open_data.active) def test_a_grant_reactivates_the_link(self): + """A grant turns an inactive link on and is spent.""" open_data = self._link(active=False) grant = self._grant() @@ -759,6 +795,8 @@ def test_a_grant_reactivates_the_link(self): self.assert_spent(grant) def test_pointing_a_link_at_another_form_is_challenged(self): + """Without a grant, a new ``object_id`` answers 401 and the link keeps its + form.""" open_data = self._link() first_form = self.xform self._publish_xls_form_to_project( @@ -781,6 +819,7 @@ def test_pointing_a_link_at_another_form_is_challenged(self): self.assertEqual(open_data.object_id, first_form.pk) def test_deactivating_a_link_is_not_challenged(self): + """Turning a link off needs no grant, but turning it on does.""" open_data = self._link(active=False) self.assert_challenged(self._patch(open_data, {"active": True})) OpenData.objects.filter(pk=open_data.pk).update(active=True) @@ -792,6 +831,7 @@ def test_deactivating_a_link_is_not_challenged(self): self.assertFalse(open_data.active) def test_renaming_an_active_link_is_not_challenged(self): + """A rename that keeps an active link on needs no grant.""" open_data = self._link(active=False) self.assert_challenged(self._patch(open_data, {"active": True})) OpenData.objects.filter(pk=open_data.pk).update(active=True) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_form_move_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_form_move_gates.py index 04fb94430d..9af3ed8c03 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_form_move_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_form_move_gates.py @@ -69,6 +69,7 @@ def test_a_move_that_makes_an_editor_owner_is_challenged(self): self.assertEqual(self._project_of_the_form(), self.first_project) def test_a_grant_lets_the_form_move(self): + """A grant moves the form, makes alice its owner and is spent.""" self._set_meta_perms(EDITOR_BECOMES_OWNER) grant = self._grant() diff --git a/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py index e37219a68d..ff3b8a1ef6 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py @@ -330,6 +330,8 @@ def setUp(self): self.assertFalse(MetaData.public_link(self.xform)) def test_retyping_the_hiding_row_is_challenged(self): + """Retyping the off row would uncover the on row, so it answers 401 and + stays.""" response = self._update( self.hiding, {"data_type": "data_license", "data_value": "CC-BY"} ) @@ -340,6 +342,8 @@ def test_retyping_the_hiding_row_is_challenged(self): self.assertFalse(MetaData.public_link(self.xform)) def test_deleting_the_hiding_row_is_challenged(self): + """Deleting the off row would uncover the on row, so it answers 401 and + stays.""" response = self._destroy(self.hiding) self.assert_challenged(response) @@ -347,6 +351,7 @@ def test_deleting_the_hiding_row_is_challenged(self): self.assertFalse(MetaData.public_link(self.xform)) def test_a_grant_lets_the_hiding_row_go(self): + """A grant deletes the off row, which turns the hidden link on.""" grant = self._grant() response = self._destroy(self.hiding, self._with_grant(grant)) @@ -356,6 +361,7 @@ def test_a_grant_lets_the_hiding_row_go(self): self.assert_spent(grant) def test_deleting_the_hidden_row_is_not_challenged(self): + """Deleting the hidden on row needs no grant and leaves the link off.""" self.assert_challenged(self._destroy(self.hiding)) response = self._destroy(self.hidden) @@ -365,6 +371,7 @@ def test_deleting_the_hidden_row_is_not_challenged(self): self.assertFalse(MetaData.public_link(self.xform)) def test_retyping_the_hidden_row_is_not_challenged(self): + """Retyping the hidden on row needs no grant and leaves the link off.""" self.assert_challenged(self._destroy(self.hiding)) response = self._update( @@ -466,6 +473,7 @@ def setUp(self): self.assertEqual(MetaData.textit(self.xform), TEXTIT_SETTINGS) def test_retyping_the_first_row_is_challenged(self): + """Retyping the first row would apply the hidden settings, so it answers 401.""" response = self._update( self.first, {"data_type": "data_license", "data_value": "CC-BY"} ) @@ -476,6 +484,7 @@ def test_retyping_the_first_row_is_challenged(self): self.assertEqual(MetaData.textit(self.xform), TEXTIT_SETTINGS) def test_deleting_the_first_row_is_challenged(self): + """Deleting the first row would apply the hidden settings, so it answers 401.""" response = self._destroy(self.first) self.assert_challenged(response) @@ -483,6 +492,7 @@ def test_deleting_the_first_row_is_challenged(self): self.assertEqual(MetaData.textit(self.xform), TEXTIT_SETTINGS) def test_a_grant_lets_the_first_row_go(self): + """A grant deletes the first row, which makes the hidden settings apply.""" grant = self._grant() response = self._destroy(self.first, self._with_grant(grant)) @@ -502,6 +512,7 @@ def test_deleting_the_hidden_row_is_not_challenged(self): self.assertEqual(MetaData.textit(self.xform), TEXTIT_SETTINGS) def test_retyping_the_hidden_row_is_not_challenged(self): + """Retyping the hidden row needs no grant, and the first row still applies.""" self.assert_challenged(self._destroy(self.first)) response = self._update( @@ -536,6 +547,7 @@ def assert_form_locked_before_write(self, queries, write): self.assertLess(locks[0], writes[0]) def test_a_create_locks_the_form(self): + """A create locks the form row before it inserts the metadata row.""" with CaptureQueriesContext(connection) as queries: response = self._create("public_link", "False") @@ -543,6 +555,7 @@ def test_a_create_locks_the_form(self): self.assert_form_locked_before_write(queries, 'INSERT INTO "main_metadata"') def test_an_update_locks_the_form(self): + """An update locks the form row before it writes the metadata row.""" (row,) = _rows(self.xform, "public_link", ("False",)) with CaptureQueriesContext(connection) as queries: @@ -554,6 +567,7 @@ def test_an_update_locks_the_form(self): self.assert_form_locked_before_write(queries, 'UPDATE "main_metadata"') def test_a_delete_locks_the_form(self): + """A delete locks the form row before it deletes the public link row.""" (row,) = _rows(self.xform, "public_link", ("False",)) with CaptureQueriesContext(connection) as queries: @@ -563,6 +577,7 @@ def test_a_delete_locks_the_form(self): self.assert_form_locked_before_write(queries, 'DELETE FROM "main_metadata"') def test_a_textit_delete_locks_the_form(self): + """A delete locks the form row before it deletes the TextIt row.""" (row,) = _rows(self.xform, TEXTIT, (TEXTIT_SETTINGS,)) with CaptureQueriesContext(connection) as queries: diff --git a/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py index e5c0849db2..dec9efb17c 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py @@ -59,6 +59,8 @@ def _require_auth(self): return OrganizationProfile.objects.get(user__username="denoinc").require_auth def test_toggling_require_auth_is_challenged(self): + """Without a grant, turning on ``require_auth`` answers 401 and the value stays + off.""" self.assertFalse(self._require_auth()) response = self._patch_org({"require_auth": True}) @@ -68,6 +70,7 @@ def test_toggling_require_auth_is_challenged(self): self.assertFalse(self._require_auth()) def test_a_grant_lets_the_toggle_through(self): + """A grant in the header lets ``require_auth`` turn on.""" grant = issue_grant(self.user.pk, "require-auth-toggle") response = self._patch_org( @@ -78,6 +81,7 @@ def test_a_grant_lets_the_toggle_through(self): self.assertTrue(self._require_auth()) def test_other_changes_are_not_challenged(self): + """A rename that leaves ``require_auth`` as it is needs no grant.""" self.assertEqual(self._patch_org({"require_auth": True}).status_code, 401) response = self._patch_org({"name": "Dennis Inc", "require_auth": False}) @@ -171,6 +175,7 @@ def _make_alice(self, role=None): self.assertIn(self.alice, get_organization_members(self.organization)) def test_appointing_an_owner_is_challenged(self): + """Without a grant, a new owner answers 401 and the user gets no owner role.""" response = self._add_member("owner") self.assertEqual(response.status_code, 401) @@ -178,6 +183,7 @@ def test_appointing_an_owner_is_challenged(self): self.assertFalse(OwnerRole.user_has_role(self.alice, self.organization)) def test_a_grant_lets_the_owner_through(self): + """A grant in the header makes the new member an owner.""" grant = issue_grant(self.user.pk, "grant-org-admin") response = self._add_member("owner", {"HTTP_X_STEP_UP_GRANT": grant}) @@ -186,6 +192,7 @@ def test_a_grant_lets_the_owner_through(self): self.assertTrue(OwnerRole.user_has_role(self.alice, self.organization)) def test_other_roles_are_not_challenged(self): + """A new editor member needs no grant, but a new owner does.""" self.assertEqual(self._add_member("owner").status_code, 401) response = self._add_member("editor") @@ -208,6 +215,7 @@ def test_a_member_add_skips_the_lookups_where_nothing_it_needs_is_gated(self): self.assertTrue(OwnerRole.user_has_role(self.alice, self.organization)) def test_appointing_a_manager_through_v2_is_challenged(self): + """The v2 members route gates a new manager as v1 does.""" response = self._member_request( "post", "manager", viewset=OrganizationProfileViewSetV2 ) @@ -217,6 +225,7 @@ def test_appointing_a_manager_through_v2_is_challenged(self): self.assertFalse(ManagerRole.user_has_role(self.alice, self.organization)) def test_re_appointing_an_owner_is_not_challenged(self): + """Adding an owner who already holds the role needs no grant.""" self.assertEqual(self._add_member("owner").status_code, 401) self._make_alice("owner") self.assertTrue(OwnerRole.user_has_role(self.alice, self.organization)) @@ -227,6 +236,7 @@ def test_re_appointing_an_owner_is_not_challenged(self): self.assertTrue(OwnerRole.user_has_role(self.alice, self.organization)) def test_demoting_an_owner_to_manager_is_not_challenged(self): + """A PUT that moves an owner down to manager needs no grant.""" self.assertEqual(self._add_member("owner").status_code, 401) self._make_alice("owner") self.assertTrue(OwnerRole.user_has_role(self.alice, self.organization)) @@ -249,6 +259,7 @@ def test_an_unknown_username_keeps_the_grant(self): self.assertTrue(spend_grant(self.user.pk, "grant-org-admin", grant)) def test_promoting_a_member_to_owner_through_v1_put_is_challenged(self): + """A v1 PUT that makes a member an owner answers 401 without a grant.""" self._make_alice() response = self._member_request("put", "owner") @@ -258,6 +269,7 @@ def test_promoting_a_member_to_owner_through_v1_put_is_challenged(self): self.assertFalse(OwnerRole.user_has_role(self.alice, self.organization)) def test_a_grant_lets_the_owner_through_v2(self): + """A grant lets the v2 members route make the new member an owner.""" grant = issue_grant(self.user.pk, "grant-org-admin") response = self._member_request( @@ -412,6 +424,7 @@ def _rotate(self, key_id, headers=None): return view(request, user="denoinc") def test_rotating_the_key_is_challenged(self, mock_rotate_key): + """Without a grant, a key rotation answers 401 and the key does not rotate.""" response = self._rotate(self.kms_key.id) self.assertEqual(response.status_code, 401) @@ -419,6 +432,7 @@ def test_rotating_the_key_is_challenged(self, mock_rotate_key): mock_rotate_key.assert_not_called() def test_a_grant_lets_the_rotation_through(self, mock_rotate_key): + """A grant in the header lets the key rotate.""" mock_rotate_key.return_value = self._key("new-key") grant = issue_grant(self.user.pk, "rotate-org-key") diff --git a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py index 19b6475f6e..cbf2d57e55 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py @@ -78,18 +78,23 @@ def _share(self, username, role, headers=None, **extra_data): return view(request, pk=self.project.pk) def test_sharing_as_owner_is_challenged(self): + """Without a grant, an owner share answers 401 and the user gets no owner + role.""" response = self._share("alice", OwnerRole.name) self.assert_challenged(response) self.assertFalse(OwnerRole.user_has_role(self.alice, self.project)) def test_sharing_as_manager_is_challenged(self): + """Without a grant, a manager share answers 401 and the user gets no manager + role.""" response = self._share("alice", ManagerRole.name) self.assert_challenged(response) self.assertFalse(ManagerRole.user_has_role(self.alice, self.project)) def test_a_grant_lets_the_share_through(self): + """A grant makes the user a manager of the project and is spent.""" grant = self._grant() response = self._share("alice", ManagerRole.name, self._with_grant(grant)) @@ -99,6 +104,8 @@ def test_a_grant_lets_the_share_through(self): self.assert_spent(grant) def test_one_new_admin_among_several_users_is_challenged(self): + """A share is gated when one of its users is a new owner, even if another is + not.""" ShareProject(self.project, "alice", OwnerRole.name).save() self.assertTrue(OwnerRole.user_has_role(self.alice, self.project)) @@ -108,6 +115,7 @@ def test_one_new_admin_among_several_users_is_challenged(self): self.assertFalse(OwnerRole.user_has_role(self.tom, self.project)) def test_a_non_admin_role_is_not_challenged(self): + """An editor share needs no grant, but a manager share does.""" self.assert_challenged(self._share("tom", ManagerRole.name)) response = self._share("alice", EditorRole.name) @@ -116,6 +124,7 @@ def test_a_non_admin_role_is_not_challenged(self): self.assertTrue(EditorRole.user_has_role(self.alice, self.project)) def test_a_role_every_target_already_holds_is_not_challenged(self): + """A manager share to a user who is already a manager needs no grant.""" ShareProject(self.project, "alice", ManagerRole.name).save() self.assertTrue(ManagerRole.user_has_role(self.alice, self.project)) self.assert_challenged(self._share("tom", ManagerRole.name)) @@ -197,6 +206,7 @@ def test_a_role_not_held_on_an_entity_list_is_challenged(self): self.assertEqual(response.status_code, 204) def test_removing_an_admin_is_not_challenged(self): + """Removing an owner needs no grant, but adding one does.""" ShareProject(self.project, "alice", OwnerRole.name).save() self.assertTrue(OwnerRole.user_has_role(self.alice, self.project)) self.assert_challenged(self._share("tom", OwnerRole.name)) @@ -217,6 +227,8 @@ def test_an_invalid_share_keeps_the_grant(self): self.assertTrue(spend_grant(self.user.pk, self.audience, grant)) def test_the_admin_check_runs_only_where_gated(self): + """The admin role check runs only when the deployment gates project admin + shares.""" with patch( f"{PROJECT_VIEWSET}.admin_roles_granted", wraps=admin_roles_granted ) as check: @@ -242,6 +254,8 @@ class TestFederatedChallengeHeader(StepUpGateTestCase): audience = GATE_SHARE_PROJECT_ADMIN def test_a_gated_request_gets_the_oidc_challenge_header(self): + """A gated share answers 401 with an ``oidc`` challenge header and the URL in + the body.""" self._project_create() alice = self._user("alice") view = ProjectViewSet.as_view({"put": "share"}) @@ -308,12 +322,14 @@ def _update(self, invitation, role, headers=None, email=None): return self._invite("put", payload, headers) def test_inviting_a_manager_is_challenged(self, _send): + """Without a grant, a manager invitation answers 401 and none is stored.""" response = self._create(ManagerRole.name) self.assert_challenged(response) self.assertFalse(self.project.invitations.exists()) def test_a_grant_lets_the_invitation_through(self, _send): + """A grant stores the owner invitation and is spent.""" grant = self._grant() response = self._create(OwnerRole.name, self._with_grant(grant)) @@ -323,6 +339,7 @@ def test_a_grant_lets_the_invitation_through(self, _send): self.assert_spent(grant) def test_inviting_a_non_admin_is_not_challenged(self, _send): + """An editor invitation needs no grant, but an owner invitation does.""" self.assert_challenged(self._create(OwnerRole.name)) response = self._create(EditorRole.name) @@ -331,6 +348,8 @@ def test_inviting_a_non_admin_is_not_challenged(self, _send): self.assertEqual(self.project.invitations.get().role, EditorRole.name) def test_raising_an_invitation_to_owner_is_challenged(self, _send): + """Without a grant, raising an editor invitation to owner answers 401 and the + role stays.""" invitation = self._pending(EditorRole.name) response = self._update(invitation, OwnerRole.name) @@ -340,6 +359,8 @@ def test_raising_an_invitation_to_owner_is_challenged(self, _send): self.assertEqual(invitation.role, EditorRole.name) def test_redirecting_an_admin_invitation_is_challenged(self, _send): + """Without a grant, a new email on a manager invitation answers 401 and the + email stays.""" invitation = self._pending(ManagerRole.name) response = self._update( @@ -351,6 +372,8 @@ def test_redirecting_an_admin_invitation_is_challenged(self, _send): self.assertEqual(invitation.email, "jane@example.com") def test_keeping_an_invitations_admin_role_is_not_challenged(self, _send): + """An update that keeps the manager role and email of an invitation needs no + grant.""" invitation = self._pending(ManagerRole.name) self.assert_challenged(self._update(invitation, OwnerRole.name)) @@ -361,6 +384,7 @@ def test_keeping_an_invitations_admin_role_is_not_challenged(self, _send): self.assertEqual(invitation.role, ManagerRole.name) def test_lowering_an_invitation_is_not_challenged(self, _send): + """Lowering an owner invitation to editor needs no grant.""" invitation = self._pending(OwnerRole.name) self.assert_challenged(self._create(OwnerRole.name, email="kim@example.com")) @@ -398,6 +422,8 @@ def _assert_refused_before_the_gate(self, send, message): self.assertTrue(spend_grant(self.user.pk, self.audience, grant)) def test_a_duplicate_invitation_keeps_the_grant(self, send): + """A second invitation to the same email answers 400 and does not spend the + grant.""" invitation = self._pending(EditorRole.name) self.assert_challenged(self._create(OwnerRole.name, email="kim@example.com")) @@ -412,6 +438,8 @@ def test_a_duplicate_invitation_keeps_the_grant(self, send): send.assert_not_called() def test_inviting_an_existing_user_keeps_the_grant(self, send): + """An invitation to the email of a user answers 400 and does not spend the + grant.""" alice = self._user("alice") self.assert_challenged(self._create(OwnerRole.name)) @@ -424,6 +452,7 @@ def test_inviting_an_existing_user_keeps_the_grant(self, send): send.assert_not_called() def test_redirecting_to_an_existing_user_keeps_the_grant(self, send): + """An update to the email of a user answers 400 and does not spend the grant.""" alice = self._user("alice") invitation = self._pending(ManagerRole.name) self.assert_challenged( @@ -442,6 +471,8 @@ def test_redirecting_to_an_existing_user_keeps_the_grant(self, send): send.assert_not_called() def test_updating_an_accepted_invitation_keeps_the_grant(self, send): + """An update to an accepted invitation answers 400 and does not spend the + grant.""" invitation = self.project.invitations.create( email="jane@example.com", role=EditorRole.name, @@ -459,6 +490,8 @@ def test_updating_an_accepted_invitation_keeps_the_grant(self, send): send.assert_not_called() def test_the_admin_check_runs_only_where_gated(self, _send): + """The admin role check runs only when the deployment gates admin + invitations.""" with patch( f"{PROJECT_VIEWSET}.grants_admin_role", wraps=grants_admin_role ) as check: @@ -496,18 +529,23 @@ def _share(self, username, role, headers=None): return view(request, pk=self.xform.pk) def test_sharing_as_owner_is_challenged(self): + """Without a grant, an owner share answers 401 and the user gets no owner + role.""" response = self._share("alice", OwnerRole.name) self.assert_challenged(response) self.assertFalse(OwnerRole.user_has_role(self.alice, self.xform)) def test_sharing_as_manager_is_challenged(self): + """Without a grant, a manager share answers 401 and the user gets no manager + role.""" response = self._share("alice", ManagerRole.name) self.assert_challenged(response) self.assertFalse(ManagerRole.user_has_role(self.alice, self.xform)) def test_a_grant_lets_the_share_through(self): + """A grant makes the user an owner of the form and is spent.""" grant = self._grant() response = self._share("alice", OwnerRole.name, self._with_grant(grant)) @@ -517,6 +555,8 @@ def test_a_grant_lets_the_share_through(self): self.assert_spent(grant) def test_one_new_admin_among_several_users_is_challenged(self): + """A share is gated when one of its users is a new manager, even if another is + not.""" ShareXForm(self.xform, "alice", ManagerRole.name).save() self.assertTrue(ManagerRole.user_has_role(self.alice, self.xform)) @@ -526,6 +566,7 @@ def test_one_new_admin_among_several_users_is_challenged(self): self.assertFalse(ManagerRole.user_has_role(self.tom, self.xform)) def test_a_non_admin_role_is_not_challenged(self): + """An editor share needs no grant, but an owner share does.""" self.assert_challenged(self._share("tom", OwnerRole.name)) response = self._share("alice", EditorRole.name) @@ -534,6 +575,7 @@ def test_a_non_admin_role_is_not_challenged(self): self.assertTrue(EditorRole.user_has_role(self.alice, self.xform)) def test_a_role_every_target_already_holds_is_not_challenged(self): + """An owner share to a user who is already an owner needs no grant.""" ShareXForm(self.xform, "alice", OwnerRole.name).save() self.assertTrue(OwnerRole.user_has_role(self.alice, self.xform)) self.assert_challenged(self._share("tom", OwnerRole.name)) @@ -554,6 +596,8 @@ def test_an_invalid_share_keeps_the_grant(self): self.assertTrue(spend_grant(self.user.pk, self.audience, grant)) def test_the_admin_check_runs_only_where_gated(self): + """The admin role check runs only when the deployment gates form admin + shares.""" with patch( f"{XFORM_VIEWSET}.admin_roles_granted", wraps=admin_roles_granted ) as check: @@ -597,6 +641,8 @@ def _reload(self): self.xform.refresh_from_db() def test_making_a_project_public_is_challenged(self): + """Without a grant, making the project public answers 401 and its form stays + private.""" response = self._patch({"public": True}) self.assert_challenged(response) @@ -605,6 +651,7 @@ def test_making_a_project_public_is_challenged(self): self.assertFalse(self.xform.shared_data) def test_a_full_update_making_a_project_public_is_challenged(self): + """A full PUT that makes the project public is gated as a PATCH is.""" view = ProjectViewSet.as_view({"put": "update"}) data = { "name": "demo", @@ -620,6 +667,7 @@ def test_a_full_update_making_a_project_public_is_challenged(self): self.assertFalse(self.project.shared) def test_a_grant_lets_the_project_go_public(self): + """A grant makes the project and the data of its form public, and is spent.""" grant = self._grant() response = self._patch({"public": True}, self._with_grant(grant)) @@ -642,6 +690,7 @@ def test_editing_a_public_project_with_a_private_form_is_challenged(self): self.assertFalse(self.xform.shared_data) def test_editing_a_public_project_with_public_forms_is_not_challenged(self): + """An edit of a public project needs no grant once all its forms are public.""" Project.objects.filter(pk=self.project.pk).update(shared=True) self.assert_challenged(self._patch({"name": "renamed"})) XForm.objects.filter(pk=self.xform.pk).update(shared=True, shared_data=True) @@ -653,6 +702,8 @@ def test_editing_a_public_project_with_public_forms_is_not_challenged(self): self.assertEqual(self.project.name, "renamed") def test_making_a_project_private_is_not_challenged(self): + """Making a public project private needs no grant and makes its form private + too.""" self.assert_challenged(self._patch({"public": True})) self._make_public() @@ -751,6 +802,7 @@ def test_the_publish_check_does_not_run_where_publishing_is_not_gated(self): publishes.assert_not_called() def test_making_form_data_public_is_challenged(self): + """Without a grant, ``public_data`` answers 401 and the data stays private.""" response = self._patch({"public_data": True}) self.assert_challenged(response) @@ -758,6 +810,7 @@ def test_making_form_data_public_is_challenged(self): self.assertFalse(self.xform.shared_data) def test_making_a_form_public_is_challenged(self): + """Without a grant, ``public`` answers 401 and the form stays private.""" response = self._patch({"public": True}) self.assert_challenged(response) @@ -765,6 +818,7 @@ def test_making_a_form_public_is_challenged(self): self.assertFalse(self.xform.shared) def test_a_grant_lets_the_form_data_go_public(self): + """A grant makes the data of the form public and is spent.""" grant = self._grant() response = self._patch({"public_data": True}, self._with_grant(grant)) @@ -775,6 +829,7 @@ def test_a_grant_lets_the_form_data_go_public(self): self.assert_spent(grant) def test_making_form_data_private_is_not_challenged(self): + """Making a public form and its data private needs no grant.""" self.assert_challenged(self._patch({"public_data": True})) XForm.objects.filter(pk=self.xform.pk).update(shared=True, shared_data=True) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py index 85ba2863e7..1be767c5af 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py @@ -58,6 +58,8 @@ def _make_alice_an_owner(self): self.assertTrue(self._in_team(self.owner_team, self.alice)) def test_joining_the_owners_team_is_challenged(self): + """Without a grant, a new Owners member answers 401 and does not become an + owner.""" self.assertFalse(self._in_team(self.owner_team, self.alice)) response = self._members("post", self.owner_team) @@ -68,6 +70,7 @@ def test_joining_the_owners_team_is_challenged(self): self.assertFalse(self.organization.is_organization_owner(self.alice)) def test_a_grant_lets_the_owner_through(self): + """A grant in the header adds the user to Owners and makes them an owner.""" self.assertFalse(self._in_team(self.owner_team, self.alice)) grant = issue_grant(self.user.pk, "grant-org-admin") @@ -80,6 +83,7 @@ def test_a_grant_lets_the_owner_through(self): self.assertTrue(self.organization.is_organization_owner(self.alice)) def test_joining_another_team_is_not_challenged(self): + """Joining a team other than Owners needs no grant and makes no owner.""" self.assertFalse(self._in_team(self.team, self.alice)) self.assertEqual(self._members("post", self.owner_team).status_code, 401) @@ -90,6 +94,7 @@ def test_joining_another_team_is_not_challenged(self): self.assertFalse(self.organization.is_organization_owner(self.alice)) def test_re_adding_an_owner_is_not_challenged(self): + """Adding a user who is already in Owners needs no grant.""" self._make_alice_an_owner() response = self._members("post", self.owner_team) @@ -98,6 +103,7 @@ def test_re_adding_an_owner_is_not_challenged(self): self.assertTrue(self._in_team(self.owner_team, self.alice)) def test_removing_an_owner_is_not_challenged(self): + """Removing a user from Owners needs no grant.""" self._make_alice_an_owner() response = self._members("delete", self.owner_team) @@ -132,6 +138,7 @@ def _give_the_team(self, role): self.assertTrue(ROLES[role].user_has_role(self.alice, self.project)) def test_sharing_the_manager_role_is_challenged(self): + """Without a grant, a manager share answers 401 and the members get no role.""" self.assertFalse(ManagerRole.user_has_role(self.alice, self.project)) response = self._share("manager") @@ -141,6 +148,7 @@ def test_sharing_the_manager_role_is_challenged(self): self.assertFalse(ManagerRole.user_has_role(self.alice, self.project)) def test_a_grant_lets_the_owner_role_through(self): + """A grant in the header gives the team's members the owner role.""" self.assertFalse(OwnerRole.user_has_role(self.alice, self.project)) grant = issue_grant(self.user.pk, "share-team-admin") @@ -150,6 +158,7 @@ def test_a_grant_lets_the_owner_role_through(self): self.assertTrue(OwnerRole.user_has_role(self.alice, self.project)) def test_other_roles_are_not_challenged(self): + """An editor share needs no grant, but a manager share does.""" self.assertFalse(EditorRole.user_has_role(self.alice, self.project)) self.assertEqual(self._share("manager").status_code, 401) @@ -160,6 +169,7 @@ def test_other_roles_are_not_challenged(self): self.assertFalse(ManagerRole.user_has_role(self.alice, self.project)) def test_a_role_the_team_holds_is_not_challenged(self): + """A share of the role the team already holds needs no grant.""" self.assertEqual(self._share("manager").status_code, 401) self._give_the_team("manager") @@ -466,6 +476,8 @@ def _team_org(self): return self.team.organization def test_moving_a_team_is_challenged(self): + """Without a grant, a move to another organisation answers 401 and the team + stays.""" response = self._update(self.other_org.user.username) self.assertEqual(response.status_code, 401) @@ -473,6 +485,8 @@ def test_moving_a_team_is_challenged(self): self.assertEqual(self._team_org(), self.organization.user) def test_a_grant_lets_the_team_move(self): + """A grant in the header moves the team to the other organisation and is + spent.""" grant = issue_grant(self.user.pk, "share-team-admin") response = self._update( @@ -484,6 +498,7 @@ def test_a_grant_lets_the_team_move(self): self.assertFalse(spend_grant(self.user.pk, "share-team-admin", grant)) def test_keeping_the_organisation_is_not_challenged(self): + """A PUT that names the current organisation needs no grant.""" self.assertEqual(self._update(self.other_org.user.username).status_code, 401) response = self._update(self.organization.user.username) @@ -492,6 +507,8 @@ def test_keeping_the_organisation_is_not_challenged(self): self.assertEqual(self._team_org(), self.organization.user) def test_renaming_without_an_organisation_is_not_challenged(self): + """A PATCH that changes only the name needs no grant and keeps the + organisation.""" view = TeamViewSet.as_view({"patch": "partial_update"}) request = self.factory.patch( "/", diff --git a/onadata/apps/api/tests/viewsets/test_stepup_user_profile_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_user_profile_gates.py index dac65e7f0f..5d8127605e 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_user_profile_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_user_profile_gates.py @@ -73,6 +73,7 @@ def _consent(self, collecting): } def test_changing_consent_without_a_grant_is_challenged(self): + """A PATCH that sets the consent record without a grant answers 401.""" response = self._patch({"metadata": self._consent(True)}) self.assertEqual(response.status_code, 401) @@ -115,6 +116,7 @@ def test_removing_the_consent_record_without_a_grant_is_challenged(self): self.assertEqual(profile.metadata, self._consent(True)) def test_a_grant_lets_the_consent_record_be_removed(self): + """A grant lets a PATCH clear the stored consent record.""" profile = UserProfile.objects.get(user=self.user) profile.metadata = self._consent(True) profile.save() @@ -245,6 +247,7 @@ def test_changing_the_email_is_challenged(self): "send_verification_email.delay" ) def test_a_grant_lets_the_email_change_through(self, _send_verification): + """A grant and the current password let the new email be stored.""" grant = issue_grant(self.user.pk, "change-email") response = self._patch_email( @@ -276,6 +279,8 @@ def test_an_email_change_without_the_password_keeps_the_grant(self): self.assertTrue(spend_grant(self.user.pk, "change-email", grant)) def test_an_email_change_with_a_wrong_password_keeps_the_grant(self): + """A wrong password answers 400, keeps the old email and does not spend the + grant.""" # The wrong password is counted in the cache, which the test database # rollback does not undo. self.addCleanup(cache.clear) @@ -374,6 +379,7 @@ def change(current_password): self.assertTrue(self.user.check_password(new_password)) def test_a_grant_lets_the_password_change_through(self): + """A grant and the current password let the new password be set.""" new_password = "Tr0ub4dor-and-3-horses" grant = issue_grant(self.user.pk, "change-password") view = UserProfileViewSet.as_view({"post": "change_password"}) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_username_gate.py b/onadata/apps/api/tests/viewsets/test_stepup_username_gate.py index 6644c43101..406c17caa0 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_username_gate.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_username_gate.py @@ -58,6 +58,8 @@ def _stored_username(self): return self.user.username def test_changing_the_username_without_a_grant_is_challenged(self): + """A PATCH to the username without a grant answers 401 and keeps the old + name.""" response = self._patch({"username": NEW_USERNAME}) self.assertEqual(response.status_code, 401) @@ -71,6 +73,7 @@ def test_changing_the_username_without_a_grant_is_challenged(self): def test_a_put_changing_the_username_without_a_grant_is_challenged( self, _send_verification ): + """A full PUT with a new username is gated as a PATCH is, and the name stays.""" response = self._put({"username": NEW_USERNAME}) self.assertEqual(response.status_code, 401) @@ -78,6 +81,7 @@ def test_a_put_changing_the_username_without_a_grant_is_challenged( self.assertEqual(self._stored_username(), "bob") def test_a_grant_lets_the_username_change_through(self): + """A grant in the header lets the new username be stored.""" grant = issue_grant(self.user.pk, CHANGE_USERNAME) response = self._patch( @@ -104,6 +108,7 @@ def test_a_username_differing_only_as_the_serializer_cleans_it_is_not_challenged "send_verification_email.delay" ) def test_a_put_echoing_the_username_is_not_challenged(self, _send_verification): + """A full PUT that sends back the stored username needs no grant.""" response = self._put({"city": "Nairobi"}) self.assertEqual(response.status_code, 200) @@ -111,6 +116,7 @@ def test_a_put_echoing_the_username_is_not_challenged(self, _send_verification): self.assertEqual(self.user.profile.city, "Nairobi") def test_an_unrelated_change_is_not_challenged(self): + """A change to another field needs no grant, but a username change does.""" self.assertEqual(self._patch({"username": NEW_USERNAME}).status_code, 401) response = self._patch({"city": "Nairobi"}) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_viewset.py b/onadata/apps/api/tests/viewsets/test_stepup_viewset.py index 783e13e28a..5b5a2aa572 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_viewset.py @@ -82,6 +82,8 @@ def test_start_refuses_an_audience_that_is_not_gated(self): @override_settings(STEP_UP=STEP_UP_FEDERATED) def test_start_returns_the_authorization_url(self): + """For a gated audience, start answers 200 with the provider's authorization + URL.""" # Patched where the viewset looks it up, not where it is defined. with patch( "onadata.apps.api.viewsets.stepup_viewset.start_step_up", @@ -117,6 +119,7 @@ def test_start_answers_a_browser_accept_header_with_json(self): @override_settings(STEP_UP=STEP_UP_FEDERATED) def test_start_refuses_an_html_only_accept_header(self): + """An ``Accept`` header that allows only HTML gets a 406 in JSON.""" self.client.force_login(self.user) with patch( "onadata.apps.api.viewsets.stepup_viewset.start_step_up", @@ -216,12 +219,15 @@ def test_the_callback_accepts_the_django_session(self): @override_settings(STEP_UP=STEP_UP_FEDERATED) def test_callback_rejects_a_request_with_no_code_or_state(self): + """A callback with an empty code and state answers 400 ``invalid_request``.""" response = self._callback(code="", state="") self.assertEqual(response.status_code, 400) self.assertEqual(response.data["error"], "invalid_request") @override_settings(STEP_UP=STEP_UP_FEDERATED) def test_callback_rejects_a_json_body_that_is_not_an_object(self): + """A POST callback with a JSON list as its body answers 400 + ``invalid_request``.""" view = StepUpViewSet.as_view({"post": "callback"}) request = self.factory.post( "/", ["code", "state"], format="json", **self.extra @@ -247,6 +253,7 @@ def test_a_refused_step_up_is_a_403_carrying_its_reason(self): @override_settings(STEP_UP=STEP_UP_FEDERATED) def test_a_completed_step_up_returns_the_grant(self): + """A completed step-up returns the grant with ``Cache-Control: no-store``.""" with patch( "onadata.apps.api.viewsets.stepup_viewset.StepUpViewSet.complete_step_up", return_value=("grant-42", None), @@ -292,12 +299,15 @@ def _complete(self, claims, user=None, state=None): ) def test_a_satisfying_token_yields_a_grant_for_that_audience(self): + """A token with the required ``acr`` gives a grant the user can spend on the + audience.""" grant, reason = self._complete(SATISFYING) self.assertIsNone(reason) self.assertTrue(spend_grant(self.user.pk, "require-auth-toggle", grant)) def test_state_belonging_to_another_user_is_refused(self): + """A user who presents the state of another user gets no grant.""" other = get_user_model().objects.create(username="bo", email="bo@example.org") grant, reason = self._complete(SATISFYING, user=other) diff --git a/onadata/apps/api/tests/viewsets/test_totp_viewset.py b/onadata/apps/api/tests/viewsets/test_totp_viewset.py index dbc14ca7d3..2664ea25f3 100644 --- a/onadata/apps/api/tests/viewsets/test_totp_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_totp_viewset.py @@ -1540,13 +1540,16 @@ def _post(self, handler, data=None): return view(self.factory.post("/", data=data or {}, **self.extra)) def test_enrolment_is_refused(self): + """A request to start a local enrolment answers 409.""" self.assertEqual(self._post("enroll_start").status_code, 409) def test_enrolment_confirmation_is_refused(self): + """A request to confirm a local enrolment with a code answers 409.""" response = self._post("enroll_confirm", {"code": "123456"}) self.assertEqual(response.status_code, 409) def test_disable_is_refused(self): + """A request to disable the local device answers 409.""" self.assertEqual(self._post("disable").status_code, 409) def test_recovery_code_generation_is_refused(self): diff --git a/onadata/apps/api/tests/viewsets/test_user_profile_viewset.py b/onadata/apps/api/tests/viewsets/test_user_profile_viewset.py index a105eeb72e..2815731820 100644 --- a/onadata/apps/api/tests/viewsets/test_user_profile_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_user_profile_viewset.py @@ -902,6 +902,7 @@ def test_a_patch_gates_once(self): EU_CONSENT_METADATA_PATH=("outer", "eu_citizen_consent"), ) def test_a_grant_lets_an_overwrite_merge_change_consent(self): + """With a grant, a merge that changes the nested consent value goes through.""" TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) profile = UserProfile.objects.get(user=self.user) profile.metadata = {"outer": {"eu_citizen_consent": "yes"}} diff --git a/onadata/apps/main/tests/test_stepup_legacy_publish_gate.py b/onadata/apps/main/tests/test_stepup_legacy_publish_gate.py index cbd3043eb0..fad661a63f 100644 --- a/onadata/apps/main/tests/test_stepup_legacy_publish_gate.py +++ b/onadata/apps/main/tests/test_stepup_legacy_publish_gate.py @@ -56,6 +56,8 @@ def _set_flag(self, target, value): self.assertEqual(self._flag(target), value) def test_sharing_without_a_grant_is_refused(self): + """Without a grant, sharing the form or its data answers 403 and the flag stays + off.""" for target in SHARED_FLAGS: with self.subTest(target=target): self._set_flag(target, False) @@ -66,6 +68,7 @@ def test_sharing_without_a_grant_is_refused(self): self.assertFalse(self._flag(target)) def test_a_grant_lets_the_sharing_through(self): + """A grant shares the form or its data and is spent.""" for target in SHARED_FLAGS: with self.subTest(target=target): self._set_flag(target, False) @@ -78,6 +81,7 @@ def test_a_grant_lets_the_sharing_through(self): self.assertFalse(spend_grant(self.user.pk, PUBLISH_DATA, grant)) def test_unsharing_is_not_challenged(self): + """Turning a shared flag off needs no grant, but turning it on does.""" for target in SHARED_FLAGS: with self.subTest(target=target): self._set_flag(target, False) diff --git a/onadata/apps/main/tests/test_stepup_oauth_gate.py b/onadata/apps/main/tests/test_stepup_oauth_gate.py index 89b9f1e9e3..4023f572b7 100644 --- a/onadata/apps/main/tests/test_stepup_oauth_gate.py +++ b/onadata/apps/main/tests/test_stepup_oauth_gate.py @@ -134,6 +134,8 @@ class TestApprovingAnOAuthApplication(StepUpOAuthTestCase): stolen session alone must not be able to.""" def test_approving_without_a_grant_is_refused(self): + """The consent form shows, but an approval without a grant answers 403 and + issues nothing.""" application = self._application() consent = self.client.get(AUTHORIZE_URL, self._authorization(application)) self.assertEqual(consent.status_code, 200) @@ -145,6 +147,7 @@ def test_approving_without_a_grant_is_refused(self): self.assertFalse(AccessToken.objects.filter(application=application).exists()) def test_a_grant_lets_the_approval_through(self): + """A grant in the form issues an authorization code and is spent.""" application = self._application() grant = self._grant() @@ -156,6 +159,7 @@ def test_a_grant_lets_the_approval_through(self): self.assertFalse(spend_grant(self.user.pk, AUTHORIZE_OAUTH_APP, grant)) def test_denying_is_not_challenged(self): + """A denial needs no grant and redirects with ``access_denied``.""" application = self._application() self.assertEqual(self._approve(application).status_code, 403) @@ -179,6 +183,8 @@ def test_an_invalid_approval_keeps_the_grant(self): self.assertTrue(spend_grant(self.user.pk, AUTHORIZE_OAUTH_APP, grant)) def test_skip_authorization_falls_back_to_the_consent_form(self): + """An application with ``skip_authorization`` gets the consent form, not a + code.""" application = self._application(skip_authorization=True) self.assertTrue(application.skip_authorization) @@ -199,6 +205,8 @@ def test_a_head_request_does_not_approve_automatically(self): self.assertFalse(self._codes(application).exists()) def test_a_matching_token_falls_back_to_the_consent_form(self): + """An ``approval_prompt=auto`` request with a live token gets the consent + form.""" application = self._application() AccessToken.objects.create( user=self.user, @@ -216,6 +224,7 @@ def test_a_matching_token_falls_back_to_the_consent_form(self): self.assertFalse(self._codes(application).exists()) def test_a_header_grant_lets_auto_approval_through(self): + """A grant in the header lets a ``skip_authorization`` GET issue a code.""" application = self._application(skip_authorization=True) grant = self._grant() @@ -239,6 +248,7 @@ def _registered(self): return get_application_model().objects.filter(user=self.user) def test_registering_without_a_grant_is_refused(self): + """Without a grant, the register page answers 403 and stores no application.""" self.assertFalse(self._registered().exists()) response = self.client.post(REGISTER_URL, self._registration()) @@ -247,6 +257,7 @@ def test_registering_without_a_grant_is_refused(self): self.assertFalse(self._registered().exists()) def test_a_grant_lets_the_registration_through(self): + """A grant lets the register page store the application and is spent.""" grant = self._grant() response = self.client.post(REGISTER_URL, self._registration(grant=grant)) @@ -271,6 +282,7 @@ def test_an_invalid_registration_keeps_the_grant(self): self.assertTrue(spend_grant(self.user.pk, AUTHORIZE_OAUTH_APP, grant)) def test_changing_redirect_uris_without_a_grant_is_refused(self): + """Without a grant, new redirect URIs answer 403 and the old ones stay.""" application = self._application(user=self.user) response = self._update(application, redirect_uris=OTHER_REDIRECT_URI) @@ -280,6 +292,7 @@ def test_changing_redirect_uris_without_a_grant_is_refused(self): self.assertEqual(application.redirect_uris, REDIRECT_URI) def test_changing_the_client_type_without_a_grant_is_refused(self): + """Without a grant, a change from confidential to public answers 403.""" application_model = get_application_model() application = self._application( user=self.user, client_type=application_model.CLIENT_CONFIDENTIAL @@ -294,6 +307,7 @@ def test_changing_the_client_type_without_a_grant_is_refused(self): self.assertEqual(application.client_type, application_model.CLIENT_CONFIDENTIAL) def test_a_grant_lets_the_redirect_change_through(self): + """A grant lets the update page store new redirect URIs and is spent.""" application = self._application(user=self.user) grant = self._grant() @@ -324,6 +338,7 @@ def test_changing_the_grant_type_without_a_grant_is_refused(self): ) def test_changing_the_allowed_origins_without_a_grant_is_refused(self): + """Without a grant, a new allowed origin answers 403 and none is stored.""" application = self._application(user=self.user) response = self._update(application, allowed_origins="https://evil.test") @@ -333,6 +348,7 @@ def test_changing_the_allowed_origins_without_a_grant_is_refused(self): self.assertEqual(application.allowed_origins, "") def test_a_new_client_secret_without_a_grant_is_refused(self): + """Without a grant, a new client secret answers 403 and the old secret stays.""" application = self._application(user=self.user) secret = application.client_secret @@ -360,6 +376,7 @@ def test_the_update_locks_the_application_before_the_comparison(self): ) def test_renaming_is_not_challenged(self): + """A new name needs no grant, but a redirect URI change does.""" application = self._application(user=self.user) self.assertEqual( self._update(application, redirect_uris=OTHER_REDIRECT_URI).status_code, 403 @@ -400,12 +417,14 @@ def _status(self): return self.device.status def test_accepting_without_a_grant_is_refused(self): + """Without a grant, an accept answers 403 and the device stays pending.""" response = self._confirm("accept") self.assertEqual(response.status_code, 403) self.assertEqual(self._status(), self.device.AUTHORIZATION_PENDING) def test_a_grant_lets_the_device_through(self): + """A grant authorizes the device and is spent.""" grant = self._grant() response = self._confirm("accept", grant=grant) @@ -415,6 +434,7 @@ def test_a_grant_lets_the_device_through(self): self.assertFalse(spend_grant(self.user.pk, AUTHORIZE_OAUTH_APP, grant)) def test_denying_is_not_challenged(self): + """A deny needs no grant and marks the device denied.""" self.assertEqual(self._confirm("accept").status_code, 403) response = self._confirm("deny") @@ -428,6 +448,7 @@ class TestOAuthGateOff(StepUpOAuthTestCase): """A deployment that has not opted in needs no grant.""" def test_approving_needs_no_grant(self): + """With the gate off, an approval issues a code without a grant.""" application = self._application() response = self._approve(application) @@ -436,6 +457,7 @@ def test_approving_needs_no_grant(self): self.assertIn("code", _query(response)) def test_skip_authorization_still_approves_on_get(self): + """With the gate off, a ``skip_authorization`` GET still issues a code.""" application = self._application(skip_authorization=True) response = self.client.get(AUTHORIZE_URL, self._authorization(application)) @@ -444,6 +466,7 @@ def test_skip_authorization_still_approves_on_get(self): self.assertIn("code", _query(response)) def test_skip_authorization_still_approves_on_head(self): + """With the gate off, a ``skip_authorization`` HEAD still issues a code.""" application = self._application(skip_authorization=True) response = self.client.head(AUTHORIZE_URL, self._authorization(application)) @@ -452,6 +475,8 @@ def test_skip_authorization_still_approves_on_head(self): self.assertTrue(self._codes(application).exists()) def test_registering_needs_no_grant(self): + """With the gate off, the register page stores an application without a + grant.""" response = self.client.post(REGISTER_URL, self._registration()) self.assertEqual(response.status_code, 302) diff --git a/onadata/apps/main/tests/test_stepup_pages.py b/onadata/apps/main/tests/test_stepup_pages.py index 234f7a79b4..c2be72dbeb 100644 --- a/onadata/apps/main/tests/test_stepup_pages.py +++ b/onadata/apps/main/tests/test_stepup_pages.py @@ -58,6 +58,7 @@ def _post(self, data): ) def test_changing_the_email_without_a_grant_is_refused(self): + """Without a grant, a new email answers 403 and the old email stays.""" response = self._post({"email": NEW_EMAIL}) self.assertEqual(response.status_code, 403) @@ -65,6 +66,8 @@ def test_changing_the_email_without_a_grant_is_refused(self): self.assertEqual(self.user.email, EMAIL) def test_changing_require_auth_without_a_grant_is_refused(self): + """Without a grant, a flip of ``require_auth`` answers 403 and the value + stays.""" before = UserProfile.objects.get(user=self.user).require_auth response = self._post({"require_auth": not before}) @@ -90,6 +93,7 @@ def test_two_gated_changes_are_refused_without_spending_the_grant(self): self.assertTrue(spend_grant(self.user.pk, "require-auth-toggle", grant)) def test_an_edit_changing_no_gated_value_is_saved(self): + """A post that changes no gated value is saved, but an email change is not.""" self.assertEqual(self._post({"email": NEW_EMAIL}).status_code, 403) response = self._post({"city": "Bobville"}) @@ -116,6 +120,7 @@ def test_the_gate_reads_the_locked_row_not_the_loaded_copy(self): ) def test_a_grant_in_the_form_lets_the_email_change_through(self): + """A grant sent as a form field lets the new email be saved.""" grant = issue_grant(self.user.pk, "change-email") response = self._post({"email": NEW_EMAIL, "grant": grant}) @@ -147,6 +152,7 @@ def _post(self, data=None): ) def test_changing_the_password_without_a_grant_is_refused(self): + """Without a grant, the page answers 403 and the old password still works.""" response = self._post() self.assertEqual(response.status_code, 403) @@ -154,6 +160,7 @@ def test_changing_the_password_without_a_grant_is_refused(self): self.assertTrue(self.user.check_password(self.login_password)) def test_a_grant_lets_the_password_change_through(self): + """A grant sets the new password and redirects to the done page.""" grant = issue_grant(self.user.pk, "change-password") response = self._post({"grant": grant}) diff --git a/onadata/apps/main/tests/test_stepup_public_link_gate.py b/onadata/apps/main/tests/test_stepup_public_link_gate.py index 99fc7ebaad..2079153254 100644 --- a/onadata/apps/main/tests/test_stepup_public_link_gate.py +++ b/onadata/apps/main/tests/test_stepup_public_link_gate.py @@ -57,6 +57,7 @@ def _turn_link(self, value): self.assertEqual(self._link_is_on(), value) def test_turning_the_link_on_without_a_grant_is_refused(self): + """Without a grant, ``all`` and ``toggle`` answer 403 and the link stays off.""" for for_user in ("all", "toggle"): with self.subTest(for_user=for_user): self._turn_link(False) @@ -67,6 +68,7 @@ def test_turning_the_link_on_without_a_grant_is_refused(self): self.assertFalse(self._link_is_on()) def test_a_grant_lets_the_link_on(self): + """A grant turns the link on through ``all`` or ``toggle`` and is spent.""" for for_user in ("all", "toggle"): with self.subTest(for_user=for_user): self._turn_link(False) @@ -79,6 +81,7 @@ def test_a_grant_lets_the_link_on(self): self.assertFalse(spend_grant(self.user.pk, PUBLISH_DATA, grant)) def test_turning_the_link_off_is_not_challenged(self): + """Turning the link off needs no grant, but turning it on does.""" for for_user in ("none", "toggle"): with self.subTest(for_user=for_user): self._turn_link(False) @@ -91,6 +94,7 @@ def test_turning_the_link_off_is_not_challenged(self): self.assertFalse(self._link_is_on()) def test_an_already_on_link_is_not_challenged(self): + """A request to turn on a link that is already on needs no grant.""" self._turn_link(True) response = self._set_link("all") @@ -180,6 +184,8 @@ def test_a_document_link_does_not_delete_a_public_link_row(self): self.assertFalse(MetaData.public_link(self.xform)) def test_the_media_link_does_not_delete_a_public_link_row(self): + """The media delete link refuses a public link row, so no hidden link turns + on.""" response = self.client.get(self._url("download-media-data", self.hiding, "del")) self.assertEqual(response.status_code, 403) diff --git a/onadata/apps/restservice/tests/viewsets/test_stepup_webhook_gate.py b/onadata/apps/restservice/tests/viewsets/test_stepup_webhook_gate.py index 5b2ba07bcf..8b5449bf9b 100644 --- a/onadata/apps/restservice/tests/viewsets/test_stepup_webhook_gate.py +++ b/onadata/apps/restservice/tests/viewsets/test_stepup_webhook_gate.py @@ -66,6 +66,7 @@ def _service(self): ) def test_creating_a_webhook_without_a_grant_is_challenged(self): + """Without a grant, a new webhook answers 401 and no service is stored.""" self.assertFalse(RestService.objects.exists()) response = self._request("post", self._new_service()) @@ -75,6 +76,7 @@ def test_creating_a_webhook_without_a_grant_is_challenged(self): self.assertFalse(RestService.objects.exists()) def test_a_grant_lets_the_webhook_be_created(self): + """A grant in the header lets the new webhook be stored with its URL.""" response = self._request("post", self._new_service(), self._grant_header()) self.assertEqual(response.status_code, 201) @@ -99,6 +101,7 @@ def test_an_invalid_webhook_keeps_the_grant(self): self.assertTrue(spend_grant(self.user.pk, CHANGE_WEBHOOK, grant)) def test_changing_the_url_without_a_grant_is_challenged(self): + """Without a grant, a new ``service_url`` answers 401 and the old URL stays.""" service = self._service() response = self._request("patch", {"service_url": OTHER_URL}, pk=service.pk) @@ -109,6 +112,8 @@ def test_changing_the_url_without_a_grant_is_challenged(self): self.assertEqual(service.service_url, SERVICE_URL) def test_changing_the_service_type_without_a_grant_is_challenged(self): + """A change of the service type is gated as a URL change is, and the type + stays.""" service = self._service() response = self._request("patch", {"name": "generic_xml"}, pk=service.pk) @@ -119,6 +124,7 @@ def test_changing_the_service_type_without_a_grant_is_challenged(self): self.assertEqual(service.name, "generic_json") def test_a_grant_lets_the_url_change_through(self): + """A grant in the header lets the service point to the new URL.""" service = self._service() response = self._request( @@ -130,6 +136,8 @@ def test_a_grant_lets_the_url_change_through(self): self.assertEqual(service.service_url, OTHER_URL) def test_an_invalid_url_change_keeps_the_grant(self): + """A URL change that fails validation answers 400 and does not spend the + grant.""" service = self._service() grant = issue_grant(self.user.pk, CHANGE_WEBHOOK) @@ -183,6 +191,8 @@ def _textit_auth_token(self): return stored.split(settings.METADATA_SEPARATOR)[0] def test_repointing_textit_credentials_without_a_grant_is_challenged(self): + """Without a grant, a new TextIt auth token answers 401 and the old token + stays.""" service = self._textit_service() response = self._request( @@ -194,6 +204,7 @@ def test_repointing_textit_credentials_without_a_grant_is_challenged(self): self.assertEqual(self._textit_auth_token(), "token-A") def test_a_grant_lets_textit_credentials_change(self): + """A grant in the header lets the TextIt auth token change.""" service = self._textit_service() response = self._request( @@ -283,6 +294,7 @@ def _post(self, data=None): ) def test_adding_a_service_without_a_grant_is_refused(self): + """Without a grant, the page answers 403 and no service is stored.""" self.assertFalse(RestService.objects.exists()) response = self._post() @@ -291,6 +303,7 @@ def test_adding_a_service_without_a_grant_is_refused(self): self.assertFalse(RestService.objects.exists()) def test_a_grant_lets_the_service_be_added(self): + """A grant sent as a form field lets the page store the new service.""" grant = issue_grant(self.user.pk, CHANGE_WEBHOOK) response = self._post({"grant": grant}) @@ -316,6 +329,8 @@ def test_a_duplicate_service_keeps_the_grant(self): self.assertTrue(spend_grant(self.user.pk, CHANGE_WEBHOOK, grant)) def test_an_invalid_service_keeps_the_grant(self): + """A service URL that fails validation stores nothing and does not spend the + grant.""" grant = issue_grant(self.user.pk, CHANGE_WEBHOOK) response = self._post({"service_url": "not a url", "grant": grant}) diff --git a/onadata/libs/tests/stepup/test_challenge.py b/onadata/libs/tests/stepup/test_challenge.py index 3f01c48e8a..b9ee6d662a 100644 --- a/onadata/libs/tests/stepup/test_challenge.py +++ b/onadata/libs/tests/stepup/test_challenge.py @@ -34,6 +34,8 @@ class TestChallenge(TestCase): @override_settings(STEP_UP=GATED) def test_local_mode_asks_for_a_code(self): + """In local mode, the challenge names the ``local-totp`` dialect and the + audience.""" body = build_challenge("require-auth-toggle") self.assertEqual(body["error"], "step_up_required") @@ -45,6 +47,7 @@ def test_local_mode_asks_for_a_code(self): class TestChallengeHeader(TestCase): def test_values_are_quoted_strings(self): + """Each value is a quoted string, with its quotes and backslashes escaped.""" header = challenge_header( {"error": "step_up_required", "audience": 'a"b\\c', "dialect": "oidc"} ) @@ -56,6 +59,7 @@ def test_values_are_quoted_strings(self): ) def test_the_authorization_url_stays_out_of_the_header(self): + """The header leaves out the ``authorizationUrl`` value of the body.""" header = challenge_header( { "error": "step_up_required", @@ -80,16 +84,22 @@ def setUp(self): self.user = get_user_model().objects.create(username="ana") def test_no_user_to_bind_the_state_to(self): + """With no user to bind the state to, the body reports + ``step_up_unavailable``.""" body = build_challenge("require-auth-toggle", None) self.assertEqual(body["error"], "step_up_unavailable") def test_an_anonymous_user_to_bind_the_state_to(self): + """An anonymous user cannot hold the state, so the body reports + ``step_up_unavailable``.""" body = build_challenge("require-auth-toggle", AnonymousUser()) self.assertEqual(body["error"], "step_up_unavailable") def test_a_server_with_a_malformed_config(self): + """A malformed server config gives ``step_up_unavailable`` and does not + raise.""" for error in (ImproperlyConfigured("no CLIENT_ID"), TypeError("bad")): with self.subTest(error=type(error).__name__), patch( "onadata.libs.stepup.challenge.start_step_up", side_effect=error @@ -110,6 +120,7 @@ def test_a_cache_that_does_not_store_the_state(self): self.assertNotIn("authorizationUrl", body) def test_a_server_missing_its_endpoints(self): + """A server with no authorization endpoint gives ``step_up_unavailable``.""" with patch( "onadata.libs.stepup.challenge.start_step_up", side_effect=ValueError("no AUTHORIZATION_ENDPOINT"), diff --git a/onadata/libs/tests/stepup/test_checks.py b/onadata/libs/tests/stepup/test_checks.py index 9710579f36..99c05e856e 100644 --- a/onadata/libs/tests/stepup/test_checks.py +++ b/onadata/libs/tests/stepup/test_checks.py @@ -46,6 +46,7 @@ class TestRequireValidStepUpSettings(SimpleTestCase): @override_settings(STEP_UP={"ACTIONS": ["change-emial"], "MODE": "local"}) def test_an_error_stops_the_start(self): + """A step-up error, here an unknown action, raises ``ImproperlyConfigured``.""" with self.assertRaisesMessage(ImproperlyConfigured, "stepup.E002"): require_valid_step_up_settings() @@ -54,6 +55,7 @@ def test_an_error_stops_the_start(self): SILENCED_SYSTEM_CHECKS=["stepup.E002"], ) def test_a_silenced_error_does_not_stop_the_start(self): + """An error listed in ``SILENCED_SYSTEM_CHECKS`` does not raise.""" require_valid_step_up_settings() @override_settings( @@ -65,6 +67,7 @@ def test_a_silenced_error_does_not_stop_the_start(self): }, ) def test_a_warning_does_not_stop_the_start(self): + """A warning such as ``stepup.W001`` is reported but does not raise.""" ids = {message.id for message in run_checks(tags=[STEP_UP_CHECK_TAG])} self.assertIn("stepup.W001", ids) @@ -96,6 +99,7 @@ def test_federated_step_up_with_no_server_stops_the_start(self): require_valid_step_up_settings() def test_every_step_up_check_carries_the_tag(self): + """Each step-up check carries the tag, so the start-up check runs it.""" for check in ALL_CHECKS: self.assertIn(STEP_UP_CHECK_TAG, check.tags, check.__name__) @@ -108,6 +112,7 @@ class TestTwoFactorEnabled(SimpleTestCase): STEP_UP={"ACTIONS": {"require-auth-toggle"}, "MODE": "local"}, ) def test_gating_with_two_factor_off_is_reported(self): + """Local gates with ``ENABLE_TWO_FACTOR`` off give ``stepup.W004``.""" warnings = check_step_up_has_two_factor_enabled() self.assertEqual(len(warnings), 1) @@ -118,6 +123,7 @@ def test_gating_with_two_factor_off_is_reported(self): STEP_UP={"ACTIONS": {"require-auth-toggle"}, "MODE": "local"}, ) def test_two_factor_on_is_silent(self): + """Local gates with two-factor on give no warning.""" self.assertEqual(check_step_up_has_two_factor_enabled(), []) @override_settings( @@ -133,6 +139,7 @@ def test_federated_mode_is_not_reported(self): STEP_UP={"ACTIONS": set(), "MODE": "local"}, ) def test_gating_nothing_is_silent(self): + """An empty ``ACTIONS`` gives no warning, even with two-factor off.""" self.assertEqual(check_step_up_has_two_factor_enabled(), []) @@ -141,6 +148,7 @@ class TestModeIsKnown(SimpleTestCase): @override_settings(STEP_UP={"MODE": "fedarated"}) def test_an_unknown_mode_is_reported(self): + """A misspelt ``MODE`` gives ``stepup.W003``, which names the bad value.""" warnings = check_step_up_mode_is_known() self.assertEqual(len(warnings), 1) @@ -149,10 +157,12 @@ def test_an_unknown_mode_is_reported(self): @override_settings(STEP_UP={"MODE": "local"}) def test_local_is_silent(self): + """A ``MODE`` of ``local`` gives no warning.""" self.assertEqual(check_step_up_mode_is_known(), []) @override_settings(STEP_UP={"MODE": "federated"}) def test_federated_is_silent(self): + """A ``MODE`` of ``federated`` gives no warning.""" self.assertEqual(check_step_up_mode_is_known(), []) @override_settings(STEP_UP={"ACTIONS": set()}) @@ -172,6 +182,8 @@ class TestNotSilentlyBypassable(SimpleTestCase): } ) def test_skip_gate_with_actions_is_reported(self): + """``skip_gate`` with a gated action gives ``stepup.W001``, which names the + action.""" warnings = check_step_up_not_silently_bypassable() self.assertEqual(len(warnings), 1) @@ -185,10 +197,13 @@ def test_skip_gate_with_actions_is_reported(self): } ) def test_deny_prompt_enrol_is_silent(self): + """``deny_prompt_enrol`` lets no user past a gate, so it gives no warning.""" self.assertEqual(check_step_up_not_silently_bypassable(), []) @override_settings(STEP_UP={"ACTIONS": set(), "NO_FACTOR_POLICY": "skip_gate"}) def test_gating_nothing_is_silent(self): + """``skip_gate`` with no gated action bypasses nothing, so it gives no + warning.""" self.assertEqual(check_step_up_not_silently_bypassable(), []) @override_settings( @@ -209,6 +224,7 @@ class TestFederatedStepUpGatesEmail(SimpleTestCase): @override_settings(STEP_UP={"MODE": "federated", "ACTIONS": ["regenerate-api-key"]}) def test_an_ungated_email_change_is_reported(self): + """Federated mode that does not gate ``change-email`` gives ``stepup.W006``.""" warnings = check_federated_step_up_gates_email() self.assertEqual([w.id for w in warnings], ["stepup.W006"]) @@ -220,10 +236,12 @@ def test_an_ungated_email_change_is_reported(self): } ) def test_a_gated_email_change_is_silent(self): + """Federated mode that gates ``change-email`` gives no warning.""" self.assertEqual(check_federated_step_up_gates_email(), []) @override_settings(STEP_UP={"MODE": "local", "ACTIONS": ["regenerate-api-key"]}) def test_local_mode_is_silent(self): + """Local mode does not match a token to the email, so it gives no warning.""" self.assertEqual(check_federated_step_up_gates_email(), []) @override_settings( @@ -244,6 +262,8 @@ class TestFederatedStepUpBindsByEmail(SimpleTestCase): OPENID_CONNECT_AUTH_SERVERS=_servers(SUBJECT_FIELD="username"), ) def test_a_username_binding_is_reported(self): + """A server that binds by ``username`` gives ``stepup.W007`` when renames are + ungated.""" warnings = check_federated_step_up_binds_by_email() self.assertEqual([w.id for w in warnings], ["stepup.W007"]) @@ -253,6 +273,7 @@ def test_a_username_binding_is_reported(self): OPENID_CONNECT_AUTH_SERVERS=_servers(), ) def test_the_default_email_binding_is_silent(self): + """A server with the default email binding gives no warning.""" self.assertEqual(check_federated_step_up_binds_by_email(), []) @override_settings( @@ -268,6 +289,7 @@ def test_a_username_binding_with_a_gated_rename_is_silent(self): OPENID_CONNECT_AUTH_SERVERS=_servers(SUBJECT_FIELD="username"), ) def test_local_mode_is_silent(self): + """Local mode ignores the server binding, so it gives no warning.""" self.assertEqual(check_federated_step_up_binds_by_email(), []) @@ -277,12 +299,15 @@ class TestRemovedEnrolmentPasswordSetting(SimpleTestCase): @override_settings(TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD=False) def test_a_leftover_opt_out_is_reported(self): + """A leftover ``TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD`` gives + ``stepup.W005``.""" warnings = check_removed_enrolment_password_setting() self.assertEqual(len(warnings), 1) self.assertEqual(warnings[0].id, "stepup.W005") def test_an_absent_setting_is_silent(self): + """When the removed setting is absent, the check gives no warning.""" self.assertEqual(check_removed_enrolment_password_setting(), []) @@ -399,6 +424,7 @@ class TestOAuthApprovalCanStepUp(SimpleTestCase): @override_settings(STEP_UP={"ACTIONS": ["authorize-oauth-app"], "MODE": "local"}) def test_gating_oauth_approval_is_reported(self): + """A gate on ``authorize-oauth-app`` in local mode gives ``stepup.W009``.""" warnings = check_oauth_approval_can_step_up() self.assertEqual([w.id for w in warnings], ["stepup.W009"]) @@ -407,12 +433,15 @@ def test_gating_oauth_approval_is_reported(self): STEP_UP={"ACTIONS": ["authorize-oauth-app"], "MODE": "federated"} ) def test_federated_mode_is_reported_too(self): + """A gate on ``authorize-oauth-app`` in federated mode gives ``stepup.W009`` + too.""" self.assertEqual( [w.id for w in check_oauth_approval_can_step_up()], ["stepup.W009"] ) @override_settings(STEP_UP={"ACTIONS": ["change-email"], "MODE": "local"}) def test_other_gates_are_silent(self): + """Gates on other actions give no OAuth warning.""" self.assertEqual(check_oauth_approval_can_step_up(), []) diff --git a/onadata/libs/tests/stepup/test_drf.py b/onadata/libs/tests/stepup/test_drf.py index bdef65a2e5..21d7f98efe 100644 --- a/onadata/libs/tests/stepup/test_drf.py +++ b/onadata/libs/tests/stepup/test_drf.py @@ -54,6 +54,8 @@ def _enrol(self): @override_settings(STEP_UP=GATED) def test_an_enrolled_user_without_a_grant_is_challenged(self): + """An enrolled user with no grant gets a 401 and a ``local-totp`` challenge + header.""" self._enrol() refusal = self.view.check_step_up(self._request(), "require-auth-toggle") @@ -69,6 +71,7 @@ def test_an_enrolled_user_without_a_grant_is_challenged(self): @override_settings(STEP_UP=GATED) def test_a_grant_for_this_action_passes(self): + """A grant issued for the gated action lets the request through.""" self._enrol() grant = issue_grant(self.user.pk, "require-auth-toggle") @@ -80,6 +83,7 @@ def test_a_grant_for_this_action_passes(self): @override_settings(STEP_UP=GATED) def test_a_grant_for_a_different_action_does_not(self): + """A grant issued for another action does not open this gate.""" self._enrol() grant = issue_grant(self.user.pk, "disable") @@ -91,6 +95,8 @@ def test_a_grant_for_a_different_action_does_not(self): @override_settings(STEP_UP={"ACTIONS": set(), "MODE": "local"}) def test_an_ungated_action_passes_untouched(self): + """An action that ``ACTIONS`` does not list needs no grant, even from an + enrolled user.""" self._enrol() self.assertIsNone( @@ -107,6 +113,8 @@ def test_a_user_with_no_factor_is_waved_through_under_skip_gate(self): @override_settings(STEP_UP={**GATED, "NO_FACTOR_POLICY": "deny_prompt_enrol"}) def test_a_user_with_no_factor_is_refused_under_deny(self): + """Under ``deny_prompt_enrol``, a user with no factor gets a 403 and no + challenge header.""" refusal = self.view.check_step_up(self._request(), "require-auth-toggle") self.assertEqual(refusal.status_code, 403) @@ -115,6 +123,7 @@ def test_a_user_with_no_factor_is_refused_under_deny(self): @override_settings(STEP_UP={**GATED, "NO_FACTOR_POLICY": "deny_prompt_enroll"}) def test_a_misspelt_policy_refuses_rather_than_skips(self): + """An unknown policy value fails closed and tells the user to enrol.""" refusal = self.view.check_step_up(self._request(), "require-auth-toggle") self.assertEqual(refusal.status_code, 403) @@ -130,6 +139,8 @@ class TestFederatedGate(_GateHarness): challenges every user.""" def test_a_user_with_no_local_device_is_still_challenged(self): + """A user with no local device gets an ``oidc`` challenge with an authorization + URL.""" refusal = self.view.check_step_up(self._request(), "require-auth-toggle") self.assertIsNotNone(refusal) @@ -166,6 +177,8 @@ class TestUnavailableStepUp(_GateHarness): caller, so the gate answers as the start endpoint does.""" def test_a_gate_that_cannot_build_a_challenge_answers_503(self): + """With no auth server configured, the gate answers 503 and no challenge + header.""" refusal = self.view.check_step_up(self._request(), "require-auth-toggle") self.assertIsNotNone(refusal) @@ -180,6 +193,8 @@ class TestGateInputs(_GateHarness): refusal here comes from the input, not the policy.""" def test_an_anonymous_request_is_challenged(self): + """An anonymous request gets a 401 challenge, so ``skip_gate`` does not let it + through.""" request = self._request() request.user = AnonymousUser() @@ -223,6 +238,8 @@ def _assert_recorded(self, records, action, grant): self.assertNotIn(grant, str(record.audit)) def test_a_spent_grant_is_recorded(self): + """A spent grant writes one audit record that names the audience but not the + grant.""" grant = issue_grant(self.user.pk, "require-auth-toggle") refusal, records = self._check(self._request({"grant": grant})) @@ -231,6 +248,7 @@ def test_a_spent_grant_is_recorded(self): self._assert_recorded(records, "step-up-grant-spent", grant) def test_a_grant_for_another_action_is_recorded_as_rejected(self): + """A grant for another action is logged as rejected, without its value.""" grant = issue_grant(self.user.pk, "disable") refusal, records = self._check(self._request({"grant": grant})) @@ -239,6 +257,7 @@ def test_a_grant_for_another_action_is_recorded_as_rejected(self): self._assert_recorded(records, "step-up-grant-rejected", grant) def test_a_replayed_grant_is_recorded_as_rejected(self): + """A grant used a second time is logged as rejected, without its value.""" grant = issue_grant(self.user.pk, "require-auth-toggle") self.assertIsNone( self.view.check_step_up( @@ -253,6 +272,7 @@ def test_a_replayed_grant_is_recorded_as_rejected(self): @override_settings(STEP_UP={**GATED, "NO_FACTOR_POLICY": "deny_prompt_enrol"}) def test_an_enrol_required_refusal_is_recorded(self): + """A refusal that tells the user to enrol writes an audit record.""" TOTPDevice.objects.filter(user=self.user).delete() refusal, records = self._check(self._request()) @@ -262,6 +282,7 @@ def test_an_enrol_required_refusal_is_recorded(self): self.assertIn("step-up-enrol-required", actions) def test_a_request_without_a_grant_records_no_rejection(self): + """A request with no grant is challenged but writes no audit record.""" with self.assertNoLogs("audit_logger", level="DEBUG"): refusal = self.view.check_step_up(self._request(), "require-auth-toggle") diff --git a/onadata/libs/tests/stepup/test_policy.py b/onadata/libs/tests/stepup/test_policy.py index 07189beb5f..0423479c61 100644 --- a/onadata/libs/tests/stepup/test_policy.py +++ b/onadata/libs/tests/stepup/test_policy.py @@ -14,6 +14,7 @@ @override_settings(STEP_UP={"ACTIONS": {"require-auth-toggle"}}) class TestPolicy(TestCase): def test_only_listed_actions_are_gated(self): + """An action is gated only when ``ACTIONS`` lists it.""" self.assertTrue(is_gated("require-auth-toggle")) self.assertFalse(is_gated("something-else")) @@ -30,6 +31,8 @@ def test_an_unconfigured_deployment_behaves_as_before(self): EU_CONSENT_METADATA_PATH="eu_citizen_consent", ) def test_a_string_setting_is_one_entry_not_its_characters(self): + """A string in ``ACTIONS`` or the consent path is one entry, not many + characters.""" self.assertTrue(is_gated("change-email")) self.assertFalse(is_gated("c")) self.assertEqual(eu_consent_path(), ("eu_citizen_consent",)) From 3f3b0da52f8c63671469bd003bdddc4f9bd1f14c Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:38:55 +0300 Subject: [PATCH 057/120] fix: satisfy prospector on the step-up checks and invitations --- onadata/libs/apps.py | 42 +++++++------------ .../project_invitation_serializer.py | 4 +- 2 files changed, 17 insertions(+), 29 deletions(-) diff --git a/onadata/libs/apps.py b/onadata/libs/apps.py index 57b7e7b856..169264e61b 100644 --- a/onadata/libs/apps.py +++ b/onadata/libs/apps.py @@ -15,34 +15,20 @@ def ready(self): # pylint: disable=import-outside-toplevel from django.core.checks import register - from onadata.libs.stepup.checks import ( - STEP_UP_CHECK_TAG, - check_federated_step_up_binds_by_email, - check_federated_step_up_gates_email, - check_federated_step_up_has_a_popup_origin, - check_federated_step_up_has_a_server, - check_oauth_approval_can_step_up, - check_removed_enrolment_password_setting, - check_step_up_actions_are_known, - check_step_up_has_two_factor_enabled, - check_step_up_is_well_formed, - check_step_up_mode_is_known, - check_step_up_no_factor_policy_is_known, - check_step_up_not_silently_bypassable, - ) + from onadata.libs.stepup import checks for check in ( - check_step_up_is_well_formed, - check_step_up_actions_are_known, - check_step_up_no_factor_policy_is_known, - check_step_up_not_silently_bypassable, - check_step_up_mode_is_known, - check_step_up_has_two_factor_enabled, - check_removed_enrolment_password_setting, - check_federated_step_up_gates_email, - check_federated_step_up_binds_by_email, - check_federated_step_up_has_a_server, - check_federated_step_up_has_a_popup_origin, - check_oauth_approval_can_step_up, + checks.check_step_up_is_well_formed, + checks.check_step_up_actions_are_known, + checks.check_step_up_no_factor_policy_is_known, + checks.check_step_up_not_silently_bypassable, + checks.check_step_up_mode_is_known, + checks.check_step_up_has_two_factor_enabled, + checks.check_removed_enrolment_password_setting, + checks.check_federated_step_up_gates_email, + checks.check_federated_step_up_binds_by_email, + checks.check_federated_step_up_has_a_server, + checks.check_federated_step_up_has_a_popup_origin, + checks.check_oauth_approval_can_step_up, ): - register(check, STEP_UP_CHECK_TAG) + register(check, checks.STEP_UP_CHECK_TAG) diff --git a/onadata/libs/serializers/project_invitation_serializer.py b/onadata/libs/serializers/project_invitation_serializer.py index 2b4107d1b3..ddcbd4e67f 100644 --- a/onadata/libs/serializers/project_invitation_serializer.py +++ b/onadata/libs/serializers/project_invitation_serializer.py @@ -20,6 +20,8 @@ class ProjectInvitationSerializer(serializers.ModelSerializer): """Serializer for ProjectInvitation model object""" + _can_save = False + class Meta: model = ProjectInvitation fields = ( @@ -98,7 +100,7 @@ def check_can_save(self): self._can_save = True def save(self, **kwargs): - if not getattr(self, "_can_save", False): + if not self._can_save: self.check_can_save() return super().save(**kwargs) From f041da56658ed4efe7a6e2865b0671cea4c15655 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:38:55 +0300 Subject: [PATCH 058/120] chore: pin ona-oidc to 1c03e78 --- requirements/base.in | 2 +- requirements/base.pip | 2 +- requirements/dev.pip | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/requirements/base.in b/requirements/base.in index 92ceefbac9..90b3aada1f 100644 --- a/requirements/base.in +++ b/requirements/base.in @@ -30,7 +30,7 @@ git+https://github.com/onaio/floip-py.git@3c980eb184069ae7c3c9136b18441978237cd4 git+https://github.com/onaio/python-json2xlsclient.git@62b4645f7b4f2684421a13ce98da0331a9dd66a0#egg=python-json2xlsclient # Pinned at the step-up branch tip for stepup_grants, which the totp endpoints # import. Re-pin to a main SHA once onaio/ona-oidc#139 merges. -git+https://github.com/onaio/ona-oidc.git@aabe13ca818f32d93cb795b02ca4643eca80d436#egg=ona-oidc +git+https://github.com/onaio/ona-oidc.git@1c03e7816558c614172130246208cb12ee17a7ba#egg=ona-oidc -e git+https://github.com/onaio/savreaderwriter.git@fix-pep-440-issues#egg=savreaderwriter git+https://git@github.com/onaio/valigetta.git@v0.3.1#egg=valigetta codetiming diff --git a/requirements/base.pip b/requirements/base.pip index ae15d8ed31..6e03cedf24 100644 --- a/requirements/base.pip +++ b/requirements/base.pip @@ -265,7 +265,7 @@ oauthlib==4.0.1 # -r requirements/base.in # django-oauth-toolkit # requests-oauthlib -ona-oidc @ git+https://github.com/onaio/ona-oidc.git@aabe13ca818f32d93cb795b02ca4643eca80d436 +ona-oidc @ git+https://github.com/onaio/ona-oidc.git@1c03e7816558c614172130246208cb12ee17a7ba # via -r requirements/base.in openpyxl==3.1.5 # via diff --git a/requirements/dev.pip b/requirements/dev.pip index 7f6dab8adf..b72e316758 100644 --- a/requirements/dev.pip +++ b/requirements/dev.pip @@ -331,7 +331,7 @@ oauthlib==4.0.1 # -r requirements/base.in # django-oauth-toolkit # requests-oauthlib -ona-oidc @ git+https://github.com/onaio/ona-oidc.git@aabe13ca818f32d93cb795b02ca4643eca80d436 +ona-oidc @ git+https://github.com/onaio/ona-oidc.git@1c03e7816558c614172130246208cb12ee17a7ba # via -r requirements/base.in openpyxl==3.1.5 # via From 88da20b86eb86f7fecd5ef89e00faea1b8e94980 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:43:31 +0300 Subject: [PATCH 059/120] fix: order every project share change with the repeat check --- onadata/apps/api/tasks.py | 5 ++- onadata/apps/api/tests/test_tasks.py | 20 ++++++++++- onadata/libs/models/share_project.py | 26 ++++++++++++--- .../libs/tests/models/test_share_project.py | 33 ++++++++++++++++++- 4 files changed, 75 insertions(+), 9 deletions(-) diff --git a/onadata/apps/api/tasks.py b/onadata/apps/api/tasks.py index c59e87af7e..946d6e867e 100644 --- a/onadata/apps/api/tasks.py +++ b/onadata/apps/api/tasks.py @@ -22,7 +22,7 @@ from onadata.apps.api import tools from onadata.apps.logger.models import Instance, Project, ProjectInvitation, XForm from onadata.celeryapp import app -from onadata.libs.models.share_project import ShareProject +from onadata.libs.models.share_project import ShareProject, lock_project_shares from onadata.libs.stepup.sharing import holds_roles, project_admin_roles_granted from onadata.libs.utils.cache_tools import ( XFORM_REGENERATE_INSTANCE_JSON_TASK, @@ -240,8 +240,7 @@ def share_project_async(project_id, username, role, remove=False, repeat_only=Fa @transaction.atomic def _repeat_project_share(project, username, role): - # The project row lock orders this check with a removal of a share. - project = Project.objects.select_for_update().get(pk=project.pk) + lock_project_shares(project.pk) user = User.objects.filter(username=username).first() if user is None or not holds_roles( user, project_admin_roles_granted(project, role) diff --git a/onadata/apps/api/tests/test_tasks.py b/onadata/apps/api/tests/test_tasks.py index 3d91652765..fb8260b129 100644 --- a/onadata/apps/api/tests/test_tasks.py +++ b/onadata/apps/api/tests/test_tasks.py @@ -1,7 +1,7 @@ """Tests for module onadata.apps.api.tasks""" import sys -from unittest.mock import patch +from unittest.mock import Mock, patch from django.contrib.auth import get_user_model from django.core.cache import cache @@ -151,6 +151,24 @@ def test_remove(self): self.assertFalse(ManagerRole.user_has_role(self.alice, self.project)) + def test_a_repeat_checks_the_role_under_the_project_shares_lock(self): + """A repeat share locks the shares of the project before it checks the + role, so a role change cannot commit between the check and the share.""" + calls = Mock() + calls.holds_roles.return_value = False + with patch( + "onadata.apps.api.tasks.lock_project_shares", calls.lock_project_shares + ), patch("onadata.apps.api.tasks.holds_roles", calls.holds_roles): + share_project_async.delay( + self.project.id, "alice", "manager", repeat_only=True + ) + + self.assertEqual( + [name for name, _args, _kwargs in calls.mock_calls], + ["lock_project_shares", "holds_roles"], + ) + calls.lock_project_shares.assert_called_once_with(self.project.id) + @patch("onadata.apps.api.tasks.logger.exception") def test_invalid_project_id(self, mock_log): """Invalid projecct_id is handled""" diff --git a/onadata/libs/models/share_project.py b/onadata/libs/models/share_project.py index 738fefb777..5bc0977522 100644 --- a/onadata/libs/models/share_project.py +++ b/onadata/libs/models/share_project.py @@ -4,9 +4,8 @@ """ from django.contrib.auth import get_user_model -from django.db import transaction +from django.db import connection, transaction -from onadata.apps.logger.models.project import Project from onadata.libs.permissions import ( ROLES, ManagerRole, @@ -29,6 +28,26 @@ # pylint: disable=invalid-name User = get_user_model() +# The first key of the advisory lock that ``lock_project_shares`` takes. Give +# any other advisory lock in onadata a different first key. +PROJECT_SHARES_LOCK_SPACE = 1 + + +def lock_project_shares(project_pk): + """Wait for, and hold until the transaction ends, the lock that orders the + share changes of a project. + + It is an advisory lock, not a lock on the project row. A share writes form + permissions, which take a key share lock on each form row. A form save can + hold its form row and then update the project row. A lock on the project + row would take the two rows in the opposite order and could deadlock. + """ + with connection.cursor() as cursor: + cursor.execute( + "SELECT pg_advisory_xact_lock(%s, %s)", + [PROJECT_SHARES_LOCK_SPACE, project_pk], + ) + def remove_xform_permissions(project, user, role): """Remove user permissions to all forms for the given ``project``.""" @@ -69,6 +88,7 @@ def user(self): def save(self, **kwargs): """Assigns role permissions to a project for the user.""" # pylint: disable=too-many-nested-blocks + lock_project_shares(self.project.pk) clear_project_owner_cache(self.project.pk) safe_cache_delete(f"{PROJ_PERM_CACHE}{self.project.pk}") if self.remove: @@ -110,8 +130,6 @@ def save(self, **kwargs): @transaction.atomic() def __remove_user(self): - # Waits for a repeat share of this project that is being checked. - Project.objects.select_for_update().filter(pk=self.project.pk).first() role = ROLES.get(self.role) if role and self.user and self.project: diff --git a/onadata/libs/tests/models/test_share_project.py b/onadata/libs/tests/models/test_share_project.py index ac3317978a..3bf445da16 100644 --- a/onadata/libs/tests/models/test_share_project.py +++ b/onadata/libs/tests/models/test_share_project.py @@ -2,13 +2,18 @@ from unittest.mock import call, patch +from django.db import connection, transaction + from guardian.shortcuts import get_perms from onadata.apps.logger.models.data_view import DataView from onadata.apps.logger.models.entity_list import EntityList from onadata.apps.logger.models.xform import XForm from onadata.apps.main.tests.test_base import TestBase -from onadata.libs.models.share_project import ShareProject +from onadata.libs.models.share_project import ( + PROJECT_SHARES_LOCK_SPACE, + ShareProject, +) from onadata.libs.permissions import ManagerRole, ReadOnlyRole from onadata.libs.tests.models.dataview_test_utils import create_cross_project_dataview @@ -123,3 +128,29 @@ def test_remove(self, mock_propagate): call(f"ps-project_permissions-{self.project.pk}"), ] ) + + def test_a_role_change_holds_the_project_shares_lock(self, mock_propagate): + """A change to a lower role takes the lock a repeat share holds while it + checks the role.""" + ManagerRole.add(self.alice, self.project) + self.assertFalse(self._holds_project_shares_lock()) + + with transaction.atomic(): + ShareProject(self.project, self.alice.username, ReadOnlyRole.name).save() + # The lock lasts until the outer transaction ends. + self.assertTrue(self._holds_project_shares_lock()) + + self.assertFalse(self._holds_project_shares_lock()) + self.assertTrue(ReadOnlyRole.user_has_role(self.alice, self.project)) + self.assertFalse(ManagerRole.user_has_role(self.alice, self.project)) + mock_propagate.assert_called_once_with(args=[self.project.pk]) + + def _holds_project_shares_lock(self): + with connection.cursor() as cursor: + cursor.execute( + "SELECT count(*) FROM pg_locks WHERE locktype = 'advisory' " + "AND classid = %s AND objid = %s AND objsubid = 2 " + "AND pid = pg_backend_pid() AND granted", + [PROJECT_SHARES_LOCK_SPACE, self.project.pk], + ) + return cursor.fetchone()[0] > 0 From 10063c49d142d1c8113b5edc81c141c7f97cdde5 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:43:50 +0300 Subject: [PATCH 060/120] test: show that a repeat share that holds the role writes --- .../api/tests/viewsets/test_stepup_sharing_gates.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py index cbf2d57e55..bcb2b8e079 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py @@ -24,6 +24,7 @@ from onadata.apps.api.viewsets.project_viewset import ProjectViewSet from onadata.apps.api.viewsets.xform_viewset import XFormViewSet from onadata.apps.logger.models import EntityList, Project, ProjectInvitation, XForm +from onadata.apps.logger.models.project import ProjectUserObjectPermission from onadata.libs.models.share_project import ShareProject from onadata.libs.models.share_xform import ShareXForm from onadata.libs.permissions import ( @@ -153,7 +154,14 @@ def test_a_waived_share_is_queued_as_a_repeat(self, task): def test_a_repeat_share_after_a_revocation_writes_nothing(self): """A removal that commits before the queued share runs stands.""" ShareProject(self.project, "tom", ManagerRole.name).save() + tom_perms = ProjectUserObjectPermission.objects.filter( + user=self.tom, content_object=self.project + ) + old_rows = set(tom_perms.values_list("pk", flat=True)) + self.assertTrue(old_rows) share_project_async(self.project.pk, "tom", ManagerRole.name, repeat_only=True) + # A repeat that still holds the role writes its rows again. + self.assertFalse(old_rows & set(tom_perms.values_list("pk", flat=True))) self.assertTrue(ManagerRole.user_has_role(self.tom, self.project)) ShareProject(self.project, "alice", ManagerRole.name).save() ShareProject(self.project, "alice", ManagerRole.name, remove=True).save() @@ -188,9 +196,7 @@ def test_a_role_not_held_on_an_entity_list_is_challenged(self): ShareProject(self.project, "alice", ManagerRole.name).save() entity_list = EntityList.objects.create(name="trees", project=self.project) for obj in (self.project, self.xform): - self.assertTrue( - ManagerRole.has_role(get_user_perms(self.alice, obj), obj) - ) + self.assertTrue(ManagerRole.has_role(get_user_perms(self.alice, obj), obj)) self.assertFalse( ManagerRole.has_role(get_user_perms(self.alice, entity_list), entity_list) ) From ffcc72e83c999f67372df9c4990ea327a878f2b7 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:45:48 +0300 Subject: [PATCH 061/120] fix: refuse the anonymous user as an organization or team member --- .../test_organization_profile_viewset.py | 49 +++++++++++++++++++ .../api/tests/viewsets/test_team_viewset.py | 47 ++++++++++++++++++ onadata/apps/api/viewsets/team_viewset.py | 11 ++++- .../organization_member_serializer.py | 6 +++ 4 files changed, 111 insertions(+), 2 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_organization_profile_viewset.py b/onadata/apps/api/tests/viewsets/test_organization_profile_viewset.py index 360caa1b48..4945535154 100644 --- a/onadata/apps/api/tests/viewsets/test_organization_profile_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_organization_profile_viewset.py @@ -8,6 +8,7 @@ from datetime import timedelta from unittest.mock import patch +from django.conf import settings from django.contrib.auth.models import AnonymousUser, User from django.contrib.contenttypes.models import ContentType from django.core.cache import cache @@ -779,6 +780,54 @@ def test_members_delete_acts_on_body_username(self): self.assertTrue(members_team.user_set.filter(username="aboy").exists()) self.assertFalse(members_team.user_set.filter(username="alice").exists()) + def _org_members(self, method, username): + view = OrganizationProfileViewSet.as_view( + {"post": "members", "delete": "members"} + ) + request = getattr(self.factory, method)( + "/", + data=json.dumps({"username": username}), + content_type="application/json", + **self.extra, + ) + return view(request, user="denoinc") + + def test_add_anonymous_user_to_org_is_refused(self): + """Members get roles on the organization's projects, which would then + reach every signed-out request.""" + self._org_create() + anonymous, _created = User.objects.get_or_create( + username=settings.ANONYMOUS_DEFAULT_USERNAME + ) + self._create_user_profile(extra_post_data={"username": "aboy"}) + self.assertEqual(self._org_members("post", "aboy").status_code, 201) + + response = self._org_members("post", anonymous.username) + + self.assertEqual(response.status_code, 400) + self.assertEqual( + response.data, + {"username": ["Cannot add the anonymous user to an organization."]}, + ) + members_team = Team.objects.get(name="denoinc#members") + self.assertFalse(members_team.user_set.filter(pk=anonymous.pk).exists()) + + def test_remove_anonymous_user_from_org(self): + """The anonymous user can still be removed from an organization it is + in.""" + self._org_create() + anonymous, _created = User.objects.get_or_create( + username=settings.ANONYMOUS_DEFAULT_USERNAME + ) + self._add_user_to_organization(self.organization, anonymous) + members_team = Team.objects.get(name="denoinc#members") + self.assertTrue(members_team.user_set.filter(pk=anonymous.pk).exists()) + + response = self._org_members("delete", anonymous.username) + + self.assertEqual(response.status_code, 200) + self.assertFalse(members_team.user_set.filter(pk=anonymous.pk).exists()) + def test_orgs_create_with_mixed_case(self): data = { "name": "denoinc", diff --git a/onadata/apps/api/tests/viewsets/test_team_viewset.py b/onadata/apps/api/tests/viewsets/test_team_viewset.py index 30ac7044ad..0bafd5a585 100644 --- a/onadata/apps/api/tests/viewsets/test_team_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_team_viewset.py @@ -1,5 +1,8 @@ import json +from django.conf import settings +from django.contrib.auth import get_user_model + from guardian.shortcuts import assign_perm, get_perms from onadata.apps.api import tools @@ -170,6 +173,50 @@ def test_remove_user_from_team(self): self.assertEqual(response.data, []) self.assertNotIn(self.team.group_ptr, self.user.groups.all()) + def _anonymous_user(self): + anonymous, _created = get_user_model().objects.get_or_create( + username=settings.ANONYMOUS_DEFAULT_USERNAME + ) + return anonymous + + def _team_members(self, method, username): + view = TeamViewSet.as_view({"post": "members", "delete": "members"}) + request = getattr(self.factory, method)( + "/", + data=json.dumps({"username": username}), + content_type="application/json", + **self.extra, + ) + return view(request, pk=self.team.pk) + + def test_add_anonymous_user_to_team_is_refused(self): + """The team's roles would reach every signed-out request.""" + self._team_create() + anonymous = self._anonymous_user() + self.assertEqual( + self._team_members("post", self.user.username).status_code, 201 + ) + + response = self._team_members("post", anonymous.username.lower()) + + self.assertEqual(response.status_code, 400) + self.assertEqual( + response.data, {"username": ["Cannot add the anonymous user to a team."]} + ) + self.assertFalse(self.team.user_set.filter(pk=anonymous.pk).exists()) + + def test_remove_anonymous_user_from_team(self): + """The anonymous user can still be removed from a team it is in.""" + self._team_create() + anonymous = self._anonymous_user() + add_user_to_team(self.team, anonymous) + self.assertTrue(self.team.user_set.filter(pk=anonymous.pk).exists()) + + response = self._team_members("delete", anonymous.username) + + self.assertEqual(response.status_code, 201) + self.assertFalse(self.team.user_set.filter(pk=anonymous.pk).exists()) + def test_team_share(self): self._team_create() self._publish_xls_form_to_project() diff --git a/onadata/apps/api/viewsets/team_viewset.py b/onadata/apps/api/viewsets/team_viewset.py index 01be027d5f..a07eadbbb3 100644 --- a/onadata/apps/api/viewsets/team_viewset.py +++ b/onadata/apps/api/viewsets/team_viewset.py @@ -27,7 +27,11 @@ from onadata.libs.mixins.authenticate_header_mixin import AuthenticateHeaderMixin from onadata.libs.mixins.cache_control_mixin import CacheControlMixin from onadata.libs.mixins.etags_mixin import ETagsMixin -from onadata.libs.permissions import ROLES, is_organization_admin +from onadata.libs.permissions import ( + ROLES, + is_anonymous_username, + is_organization_admin, +) from onadata.libs.serializers.share_team_project_serializer import ( RemoveTeamFromProjectSerializer, ShareTeamProjectSerializer, @@ -169,7 +173,10 @@ def members(self, request, *args, **kwargs): "username" ) - if username: + if request.method == "POST" and is_anonymous_username(username): + status_code = status.HTTP_400_BAD_REQUEST + data["username"] = [_("Cannot add the anonymous user to a team.")] + elif username: try: user = User.objects.get(username__iexact=username) except User.DoesNotExist: diff --git a/onadata/libs/serializers/organization_member_serializer.py b/onadata/libs/serializers/organization_member_serializer.py index e3ad1724e0..95dc7ab950 100644 --- a/onadata/libs/serializers/organization_member_serializer.py +++ b/onadata/libs/serializers/organization_member_serializer.py @@ -19,6 +19,7 @@ from onadata.libs.permissions import ( ROLES, OwnerRole, + is_anonymous_username, is_organization, ) from onadata.libs.serializers.fields.organization_field import OrganizationField @@ -91,6 +92,11 @@ def validate(self, attrs): organization = attrs.get("organization") username = attrs.get("username") + if username and not remove and is_anonymous_username(username): + raise serializers.ValidationError( + {"username": _("Cannot add the anonymous user to an organization.")} + ) + # check if roles are downgrading and the user is the last admin if username and (remove or role != OwnerRole.name): user = User.objects.get(username=username) From f5d092d2f2581dd98cc874684442021762414c31 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:45:48 +0300 Subject: [PATCH 062/120] test: cover is_anonymous_username directly --- onadata/libs/tests/test_permissions.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/onadata/libs/tests/test_permissions.py b/onadata/libs/tests/test_permissions.py index 7ecf0882f9..a4e8862af6 100644 --- a/onadata/libs/tests/test_permissions.py +++ b/onadata/libs/tests/test_permissions.py @@ -5,6 +5,7 @@ from unittest.mock import patch from django.contrib.auth.models import AnonymousUser, Group +from django.test import SimpleTestCase, override_settings from guardian.shortcuts import get_users_with_perms @@ -23,6 +24,7 @@ ReadOnlyRoleNoDownload, filter_queryset_xform_meta_perms_sql, get_object_users_with_permissions, + is_anonymous_username, is_organization_admin, ) @@ -283,3 +285,26 @@ def test_member_is_not_admin(self): def test_anonymous_is_not_admin(self): """Anonymous users are never admins.""" self.assertFalse(is_organization_admin(AnonymousUser(), self.organization)) + + +@override_settings(ANONYMOUS_DEFAULT_USERNAME="AnonymousUser") +class TestIsAnonymousUsername(SimpleTestCase): + """Tests for ``is_anonymous_username``.""" + + def test_the_anonymous_username_in_any_case(self): + """The setting's username matches whatever its case.""" + for username in ("AnonymousUser", "anonymoususer", "ANONYMOUSUSER"): + with self.subTest(username=username): + self.assertTrue(is_anonymous_username(username)) + + def test_other_usernames(self): + """Any other value, including an empty one, does not match.""" + for username in ("alice", "AnonymousUser2", "", None): + with self.subTest(username=username): + self.assertFalse(is_anonymous_username(username)) + + @override_settings(ANONYMOUS_DEFAULT_USERNAME="nobody") + def test_follows_the_setting(self): + """The username comes from ``ANONYMOUS_DEFAULT_USERNAME``.""" + self.assertTrue(is_anonymous_username("Nobody")) + self.assertFalse(is_anonymous_username("AnonymousUser")) From 13ff1166aac7aa9884561a496f8eb52c39006410 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:46:33 +0300 Subject: [PATCH 063/120] fix: save only the password on the legacy password page --- onadata/apps/main/forms.py | 10 ++++++++ onadata/apps/main/tests/test_stepup_pages.py | 24 ++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/onadata/apps/main/forms.py b/onadata/apps/main/forms.py index 5e7b051ba5..75f79a626c 100644 --- a/onadata/apps/main/forms.py +++ b/onadata/apps/main/forms.py @@ -771,6 +771,16 @@ def clean_old_password(self): self.error_messages["password_incorrect"], code="password_incorrect" ) + def save(self, commit=True): + """Set the new password and save only that column. + + ``self.user`` was loaded when the request started. A full save would + write back an email or another value that changed since then.""" + user = self.set_password_and_save(self.user, "new_password1", commit=False) + if commit: + user.save(update_fields=["password"]) + return user + class RecoveryCodeForm(BackupTokenForm): """Recovery-code step of the login wizard. diff --git a/onadata/apps/main/tests/test_stepup_pages.py b/onadata/apps/main/tests/test_stepup_pages.py index c2be72dbeb..d79e1e876d 100644 --- a/onadata/apps/main/tests/test_stepup_pages.py +++ b/onadata/apps/main/tests/test_stepup_pages.py @@ -6,6 +6,7 @@ from unittest.mock import patch from django.conf import settings +from django.contrib.auth import get_user_model from django.core.cache import cache from django.test import override_settings from django.urls import reverse @@ -13,6 +14,7 @@ from django_otp.plugins.otp_totp.models import TOTPDevice from oidc.stepup_grants import issue_grant, spend_grant +from onadata.apps.main import registration_views from onadata.apps.main.models import UserProfile from onadata.apps.main.tests.test_base import TestBase from onadata.apps.main.views import profile_settings @@ -173,6 +175,28 @@ def test_a_grant_lets_the_password_change_through(self): self.user.refresh_from_db() self.assertTrue(self.user.check_password(NEW_PASSWORD)) + def test_a_password_change_saves_only_the_password(self): + """An email change that commits while the page runs is not written + back with the address the page loaded.""" + self.assertNotEqual(self.user.email, NEW_EMAIL) + grant = issue_grant(self.user.pk, "change-password") + gate = registration_views.refuse_page_action + + def gate_then_change_email(request, action): + refusal = gate(request, action) + get_user_model().objects.filter(pk=self.user.pk).update(email=NEW_EMAIL) + return refusal + + with patch.object( + registration_views, "refuse_page_action", gate_then_change_email + ): + response = self._post({"grant": grant}) + + self.assertEqual(response.status_code, 302) + self.user.refresh_from_db() + self.assertTrue(self.user.check_password(NEW_PASSWORD)) + self.assertEqual(self.user.email, NEW_EMAIL) + @override_settings(MAX_LOGIN_ATTEMPTS=3) def test_repeated_wrong_old_passwords_lock_out_the_page(self): """The old-password check spends the login form's allowance, so the From bb299b6d477f5384918d704d583e9d2eda6cbd2c Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:47:39 +0300 Subject: [PATCH 064/120] fix: keep the grant on a device accept that cannot succeed --- .../apps/main/tests/test_stepup_oauth_gate.py | 28 +++++++++++++++++++ onadata/apps/main/views.py | 5 ++++ 2 files changed, 33 insertions(+) diff --git a/onadata/apps/main/tests/test_stepup_oauth_gate.py b/onadata/apps/main/tests/test_stepup_oauth_gate.py index 4023f572b7..c76b4e35f3 100644 --- a/onadata/apps/main/tests/test_stepup_oauth_gate.py +++ b/onadata/apps/main/tests/test_stepup_oauth_gate.py @@ -433,6 +433,34 @@ def test_a_grant_lets_the_device_through(self): self.assertEqual(self._status(), self.device.AUTHORIZED) self.assertFalse(spend_grant(self.user.pk, AUTHORIZE_OAUTH_APP, grant)) + def test_a_used_device_keeps_the_grant(self): + """An accept of a device that is no longer pending answers 404 and + does not spend the grant.""" + self.assertEqual(self._confirm("deny").status_code, 302) + self.assertEqual(self._status(), self.device.DENIED) + grant = self._grant() + + response = self._confirm("accept", grant=grant) + + self.assertEqual(response.status_code, 404) + self.assertEqual(self._status(), self.device.DENIED) + self.assertTrue(spend_grant(self.user.pk, AUTHORIZE_OAUTH_APP, grant)) + + def test_an_expired_device_keeps_the_grant(self): + """An accept of an expired device answers 404, does not authorize it, + and does not spend the grant.""" + type(self.device).objects.filter(pk=self.device.pk).update( + expires=timezone.now() - timedelta(seconds=1) + ) + self.assertEqual(self._status(), self.device.AUTHORIZATION_PENDING) + grant = self._grant() + + response = self._confirm("accept", grant=grant) + + self.assertEqual(response.status_code, 404) + self.assertEqual(self._status(), self.device.EXPIRED) + self.assertTrue(spend_grant(self.user.pk, AUTHORIZE_OAUTH_APP, grant)) + def test_denying_is_not_challenged(self): """A deny needs no grant and marks the device denied.""" self.assertEqual(self._confirm("accept").status_code, 403) diff --git a/onadata/apps/main/views.py b/onadata/apps/main/views.py index 3fb869b5c8..21d5c45731 100644 --- a/onadata/apps/main/views.py +++ b/onadata/apps/main/views.py @@ -20,6 +20,7 @@ from django.core.files.storage import default_storage, storages from django.db import IntegrityError, connections, transaction from django.http import ( + Http404, HttpResponse, HttpResponseBadRequest, HttpResponseForbidden, @@ -2041,6 +2042,10 @@ class StepUpDeviceConfirm(DeviceConfirmView): def form_valid(self, form): if form.cleaned_data.get("action") == "accept": + # An accept that cannot succeed answers before the gate and keeps + # its grant. get_object() is 404 for a missing or used device. + if self.get_object().is_expired(): + raise Http404 refusal = refuse_page_action(self.request, GATE_AUTHORIZE_OAUTH_APP) if refusal is not None: return refusal From fad44a5faeda828952c4081113da24f6c61008c5 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:48:30 +0300 Subject: [PATCH 065/120] fix: compare OAuth application URI lists by their items --- .../apps/main/tests/test_stepup_oauth_gate.py | 18 ++++++++++++++++ onadata/apps/main/views.py | 21 ++++++++++++++++++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/onadata/apps/main/tests/test_stepup_oauth_gate.py b/onadata/apps/main/tests/test_stepup_oauth_gate.py index c76b4e35f3..182691c96d 100644 --- a/onadata/apps/main/tests/test_stepup_oauth_gate.py +++ b/onadata/apps/main/tests/test_stepup_oauth_gate.py @@ -291,6 +291,24 @@ def test_changing_redirect_uris_without_a_grant_is_refused(self): application.refresh_from_db() self.assertEqual(application.redirect_uris, REDIRECT_URI) + def test_renaming_is_not_challenged_for_reformatted_uris(self): + """A browser posts a stored list of redirect URIs with CRLF line + breaks and without its surrounding spaces. That is no change.""" + stored = f" {REDIRECT_URI}\n{OTHER_REDIRECT_URI} " + posted = f"{REDIRECT_URI}\r\n{OTHER_REDIRECT_URI}" + application = self._application(user=self.user, redirect_uris=stored) + self.assertEqual( + self._update(application, redirect_uris=REDIRECT_URI).status_code, 403 + ) + + response = self._update( + application, name="Renamed application", redirect_uris=posted + ) + + self.assertEqual(response.status_code, 302) + application.refresh_from_db() + self.assertEqual(application.name, "Renamed application") + def test_changing_the_client_type_without_a_grant_is_refused(self): """Without a grant, a change from confidential to public answers 403.""" application_model = get_application_model() diff --git a/onadata/apps/main/views.py b/onadata/apps/main/views.py index 21d5c45731..e294fe58c3 100644 --- a/onadata/apps/main/views.py +++ b/onadata/apps/main/views.py @@ -2004,6 +2004,22 @@ def form_valid(self, form): #: field decides who receives its codes or tokens, or how it proves itself. _UNGATED_APPLICATION_FIELDS = frozenset({"name", "grant"}) +#: The application fields that hold a list separated by whitespace. A browser +#: posts the line breaks of a text area as CRLF and a stored list can have +#: surrounding spaces, so these compare by their items. +_APPLICATION_LIST_FIELDS = frozenset( + {"redirect_uris", "post_logout_redirect_uris", "allowed_origins"} +) + + +def _application_field_changed(form, field): + """Whether ``field``, one of ``form.changed_data``, holds a new value.""" + if field not in _APPLICATION_LIST_FIELDS: + return True + return (form.initial.get(field) or "").split() != ( + form.cleaned_data.get(field) or "" + ).split() + class StepUpApplicationUpdate(ApplicationUpdate): """Changes an OAuth application only with a grant, unless the change is @@ -2027,7 +2043,10 @@ def post(self, request, *args, **kwargs): return super().post(request, *args, **kwargs) def form_valid(self, form): - if set(form.changed_data) - _UNGATED_APPLICATION_FIELDS: + if any( + _application_field_changed(form, field) + for field in set(form.changed_data) - _UNGATED_APPLICATION_FIELDS + ): refusal = refuse_page_action(self.request, GATE_AUTHORIZE_OAUTH_APP) if refusal is not None: return refusal From 9ab4d10878bb4a1363f0ffb9338f099d44ed822b Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:49:10 +0300 Subject: [PATCH 066/120] docs: say that oidc.E003 reports an unusable popup origin --- docs/two_factor.rst | 4 +++- onadata/libs/tests/stepup/test_checks.py | 26 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/docs/two_factor.rst b/docs/two_factor.rst index 6cf03e7649..2ffc45f788 100644 --- a/docs/two_factor.rst +++ b/docs/two_factor.rst @@ -495,7 +495,9 @@ shows all results. challenges. - ``stepup.W010``. Federated actions are gated, but ``STEP_UP_POPUP_ORIGIN`` is not set. The callback page then cannot give a - grant to a browser. + grant to a browser. This check looks only at whether the setting is set. + A value that is set but is not an http or https origin, such as + ``app.test``, is ona-oidc's ``oidc.E003``, which stops the start. Sign in ------- diff --git a/onadata/libs/tests/stepup/test_checks.py b/onadata/libs/tests/stepup/test_checks.py index 99c05e856e..7c2591fa56 100644 --- a/onadata/libs/tests/stepup/test_checks.py +++ b/onadata/libs/tests/stepup/test_checks.py @@ -41,6 +41,15 @@ def _servers(**step_up): return {"idp": {"STEP_UP": {"REDIRECT_URI": "https://app.test/cb", **step_up}}} +def _start_error(): + """The error that stops the start, or ``""``.""" + try: + require_valid_step_up_settings() + except ImproperlyConfigured as error: + return str(error) + return "" + + class TestRequireValidStepUpSettings(SimpleTestCase): """The WSGI module calls this, because a WSGI server runs no checks.""" @@ -98,6 +107,23 @@ def test_federated_step_up_with_no_server_stops_the_start(self): with self.assertRaisesMessage(ImproperlyConfigured, "stepup.E004"): require_valid_step_up_settings() + @override_settings( + STEP_UP={"ACTIONS": ["change-email"], "MODE": "federated"}, + OPENID_CONNECT_AUTH_SERVERS=_servers(), + ) + def test_an_unusable_popup_origin_stops_the_start(self): + """``stepup.W010`` sees only that ``STEP_UP_POPUP_ORIGIN`` is set. + ona-oidc's ``oidc.E003`` reports a value that is not an origin.""" + with override_settings(STEP_UP_POPUP_ORIGIN="https://app.test"): + self.assertNotIn("STEP_UP_POPUP_ORIGIN", _start_error()) + + with override_settings(STEP_UP_POPUP_ORIGIN="app.test"): + self.assertEqual(check_federated_step_up_has_a_popup_origin(), []) + error = _start_error() + + self.assertIn("oidc.E003", error) + self.assertIn("STEP_UP_POPUP_ORIGIN must be an http or https origin", error) + def test_every_step_up_check_carries_the_tag(self): """Each step-up check carries the tag, so the start-up check runs it.""" for check in ALL_CHECKS: From 9d861b12690fee6181654e57a34017b600b42301 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:49:38 +0300 Subject: [PATCH 067/120] test: drop the unused created flag of the anonymous user lookups --- .../tests/viewsets/test_organization_profile_viewset.py | 8 ++++---- .../apps/api/tests/viewsets/test_stepup_sharing_gates.py | 4 ++-- onadata/apps/api/tests/viewsets/test_team_viewset.py | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_organization_profile_viewset.py b/onadata/apps/api/tests/viewsets/test_organization_profile_viewset.py index 4945535154..aaf3ff5cc3 100644 --- a/onadata/apps/api/tests/viewsets/test_organization_profile_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_organization_profile_viewset.py @@ -796,9 +796,9 @@ def test_add_anonymous_user_to_org_is_refused(self): """Members get roles on the organization's projects, which would then reach every signed-out request.""" self._org_create() - anonymous, _created = User.objects.get_or_create( + anonymous = User.objects.get_or_create( username=settings.ANONYMOUS_DEFAULT_USERNAME - ) + )[0] self._create_user_profile(extra_post_data={"username": "aboy"}) self.assertEqual(self._org_members("post", "aboy").status_code, 201) @@ -816,9 +816,9 @@ def test_remove_anonymous_user_from_org(self): """The anonymous user can still be removed from an organization it is in.""" self._org_create() - anonymous, _created = User.objects.get_or_create( + anonymous = User.objects.get_or_create( username=settings.ANONYMOUS_DEFAULT_USERNAME - ) + )[0] self._add_user_to_organization(self.organization, anonymous) members_team = Team.objects.get(name="denoinc#members") self.assertTrue(members_team.user_set.filter(pk=anonymous.pk).exists()) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py index bcb2b8e079..2ec29cc89c 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py @@ -1038,9 +1038,9 @@ class TestShareWithTheAnonymousUser(StepUpGateTestCase): def setUp(self): super().setUp() self._publish_xls_form_to_project() - self.anonymous, _created = get_user_model().objects.get_or_create( + self.anonymous = get_user_model().objects.get_or_create( username=settings.ANONYMOUS_DEFAULT_USERNAME - ) + )[0] self.alice = self._user("alice") def _share_form(self, username): diff --git a/onadata/apps/api/tests/viewsets/test_team_viewset.py b/onadata/apps/api/tests/viewsets/test_team_viewset.py index 0bafd5a585..f7d84b8cdd 100644 --- a/onadata/apps/api/tests/viewsets/test_team_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_team_viewset.py @@ -174,9 +174,9 @@ def test_remove_user_from_team(self): self.assertNotIn(self.team.group_ptr, self.user.groups.all()) def _anonymous_user(self): - anonymous, _created = get_user_model().objects.get_or_create( + anonymous = get_user_model().objects.get_or_create( username=settings.ANONYMOUS_DEFAULT_USERNAME - ) + )[0] return anonymous def _team_members(self, method, username): From 7498ffa8b63bd2da2184827c4b95c0a74226c1b4 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:50:17 +0300 Subject: [PATCH 068/120] perf: skip the team join check when no join is gated --- .../tests/viewsets/test_stepup_team_gates.py | 27 +++++++++++++++++++ onadata/apps/api/viewsets/team_viewset.py | 7 +++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py index 1be767c5af..90afe11ae0 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py @@ -5,6 +5,9 @@ import json +from django.db import connection +from django.test.utils import CaptureQueriesContext + from guardian.shortcuts import get_perms from oidc.stepup_grants import issue_grant, spend_grant @@ -202,6 +205,30 @@ def test_an_unknown_project_keeps_the_grant(self): self.assertTrue(spend_grant(self.user.pk, "share-team-admin", grant)) +class TestJoinCheckCost(TeamGateTestCase): + """The join check reads the team only where a deployment gates a join.""" + + def _join_check(self): + request = self.factory.post("/", **self.extra) + with CaptureQueriesContext(connection) as queries: + # pylint: disable=protected-access + refusal = TeamViewSet()._join_refusal(request, self.team, self.alice) + return refusal, len(queries) + + @gating() + def test_a_join_runs_no_query_when_nothing_is_gated(self): + """With no gated action, the check reads nothing.""" + self.assertEqual(self._join_check(), (None, 0)) + + @gating("share-team-admin") + def test_a_join_reads_the_team_when_a_join_is_gated(self): + """With a join gated, the check reads the team's members and roles.""" + refusal, queries = self._join_check() + + self.assertIsNone(refusal) + self.assertGreater(queries, 0) + + @gating("share-team-admin") class TestJoinAdminTeamGate(TeamGateTestCase): """A new member takes on every role the team holds, so adding someone to diff --git a/onadata/apps/api/viewsets/team_viewset.py b/onadata/apps/api/viewsets/team_viewset.py index a07eadbbb3..6ef9aaa2b3 100644 --- a/onadata/apps/api/viewsets/team_viewset.py +++ b/onadata/apps/api/viewsets/team_viewset.py @@ -104,11 +104,14 @@ def _join_refusal(self, request, team, user): The Owners team is both, and one grant covers it, under the first audience the deployment gates.""" - if request.method != "POST" or team.user_set.filter(pk=user.pk).exists(): + join_audiences = (GATE_GRANT_ORG_ADMIN, GATE_SHARE_TEAM_ADMIN) + if request.method != "POST" or not any(map(is_gated, join_audiences)): + return None + if team.user_set.filter(pk=user.pk).exists(): return None gated = changed_gated_actions( ( - (GATE_GRANT_ORG_ADMIN, is_organization_owners_team(team)), + (GATE_GRANT_ORG_ADMIN, lambda: is_organization_owners_team(team)), (GATE_SHARE_TEAM_ADMIN, lambda: team_reaches_admin_role(team)), ) ) From 85eba81010a4d24df4699a93bdb7d92c3e203186 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:50:45 +0300 Subject: [PATCH 069/120] test: show that the external export remove link still deletes its row --- .../apps/main/tests/test_stepup_public_link_gate.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/onadata/apps/main/tests/test_stepup_public_link_gate.py b/onadata/apps/main/tests/test_stepup_public_link_gate.py index 2079153254..543b8af12e 100644 --- a/onadata/apps/main/tests/test_stepup_public_link_gate.py +++ b/onadata/apps/main/tests/test_stepup_public_link_gate.py @@ -203,6 +203,19 @@ def test_a_map_layer_link_still_deletes_a_map_layer(self): self.assertEqual(response.status_code, 302) self.assertFalse(MetaData.objects.filter(pk=layer.pk).exists()) + def test_an_external_export_link_still_deletes_an_external_export(self): + """The link keeps working for the type it lists.""" + export = MetaData.objects.create( + content_object=self.xform, + data_type="external_export", + data_value="template|https://exports.example.test/template", + ) + + response = self.client.get(self._url("delete-metadata", export, "external_del")) + + self.assertEqual(response.status_code, 302) + self.assertFalse(MetaData.objects.filter(pk=export.pk).exists()) + def test_the_media_link_still_deletes_media(self): """The link keeps working for the type it lists.""" media = MetaData.objects.create( From 6e31259dcbaa5c2fb6d676b957d62d20ecf317f9 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 11:51:21 +0300 Subject: [PATCH 070/120] test: drop unused unpacked values in the step-up tests --- onadata/apps/api/tests/test_tasks.py | 2 +- .../api/tests/viewsets/test_stepup_form_and_transfer_gates.py | 2 +- onadata/apps/main/tests/test_stepup_public_link_gate.py | 4 ++-- onadata/libs/tests/stepup/test_gate.py | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/onadata/apps/api/tests/test_tasks.py b/onadata/apps/api/tests/test_tasks.py index fb8260b129..2906cc4d41 100644 --- a/onadata/apps/api/tests/test_tasks.py +++ b/onadata/apps/api/tests/test_tasks.py @@ -164,7 +164,7 @@ def test_a_repeat_checks_the_role_under_the_project_shares_lock(self): ) self.assertEqual( - [name for name, _args, _kwargs in calls.mock_calls], + [mock_call[0] for mock_call in calls.mock_calls], ["lock_project_shares", "holds_roles"], ) calls.lock_project_shares.assert_called_once_with(self.project.id) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py index f25005c463..4445133f80 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py @@ -706,7 +706,7 @@ def _patch(self, open_data, data, headers=None): ) def _link(self, active=True): - open_data, _created = get_or_create_opendata(self.xform) + open_data = get_or_create_opendata(self.xform)[0] OpenData.objects.filter(pk=open_data.pk).update(active=active) open_data.refresh_from_db() self.assertEqual(open_data.active, active) diff --git a/onadata/apps/main/tests/test_stepup_public_link_gate.py b/onadata/apps/main/tests/test_stepup_public_link_gate.py index 543b8af12e..1670fff6a1 100644 --- a/onadata/apps/main/tests/test_stepup_public_link_gate.py +++ b/onadata/apps/main/tests/test_stepup_public_link_gate.py @@ -105,9 +105,9 @@ def test_an_already_on_link_is_not_challenged(self): def test_a_view_permission_for_the_anonymous_user_is_refused(self): """Signed-out requests act as that user, so the form's data would be readable without signing in.""" - anonymous, _created = User.objects.get_or_create( + anonymous = User.objects.get_or_create( username=settings.ANONYMOUS_DEFAULT_USERNAME - ) + )[0] alice = User.objects.create(username="alice") for user in (alice, anonymous): diff --git a/onadata/libs/tests/stepup/test_gate.py b/onadata/libs/tests/stepup/test_gate.py index 7ad93fc8c8..657bb84e05 100644 --- a/onadata/libs/tests/stepup/test_gate.py +++ b/onadata/libs/tests/stepup/test_gate.py @@ -52,7 +52,7 @@ def test_skip_gate_lets_a_user_with_no_factor_make_two_gated_changes(self): """Each gate alone lets the user through, so both together do too.""" self.assertFalse(TOTPDevice.objects.filter(user=self.user).exists()) - reason, _audiences = change_refusal(self.request, BOTH_CHANGED) + reason = change_refusal(self.request, BOTH_CHANGED)[0] self.assertIsNone(reason) @@ -61,7 +61,7 @@ def test_deny_refuses_a_user_with_no_factor_with_enrol_required(self): """The user is told to enrol, which no single change would avoid.""" self.assertFalse(TOTPDevice.objects.filter(user=self.user).exists()) - reason, _audiences = change_refusal(self.request, BOTH_CHANGED) + reason = change_refusal(self.request, BOTH_CHANGED)[0] self.assertEqual(reason, ENROL_REQUIRED) From dc71e42391ae7655facf4749f45d0d64869fecf4 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 12:05:27 +0300 Subject: [PATCH 071/120] fix: read the role for a repeat project share from the primary --- onadata/apps/api/tasks.py | 3 +++ onadata/apps/api/tests/test_tasks.py | 25 ++++++++++++++++++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/onadata/apps/api/tasks.py b/onadata/apps/api/tasks.py index 946d6e867e..491dd977d8 100644 --- a/onadata/apps/api/tasks.py +++ b/onadata/apps/api/tasks.py @@ -238,6 +238,9 @@ def share_project_async(project_id, username, role, remove=False, repeat_only=Fa share.save() +# A replica can lag behind a role change that the lock has already ordered +# before this check, so the check reads the primary. +@use_master @transaction.atomic def _repeat_project_share(project, username, role): lock_project_shares(project.pk) diff --git a/onadata/apps/api/tests/test_tasks.py b/onadata/apps/api/tests/test_tasks.py index 2906cc4d41..44219cc07d 100644 --- a/onadata/apps/api/tests/test_tasks.py +++ b/onadata/apps/api/tests/test_tasks.py @@ -8,6 +8,9 @@ from django.db import DatabaseError, OperationalError from django.utils import timezone +from guardian.shortcuts import get_user_perms +from multidb.pinning import use_master + from onadata.apps.api.tasks import ( ShareProject, delete_xform_submissions_async, @@ -17,7 +20,7 @@ ) from onadata.apps.logger.models import Instance, ProjectInvitation, XForm from onadata.apps.main.tests.test_base import TestBase -from onadata.libs.permissions import ManagerRole +from onadata.libs.permissions import ManagerRole, ReadOnlyRole from onadata.libs.serializers.organization_serializer import OrganizationSerializer from onadata.libs.test_utils.lagging_replica import lagging_replica from onadata.libs.utils.cache_tools import ORG_PROFILE_CACHE @@ -169,6 +172,26 @@ def test_a_repeat_checks_the_role_under_the_project_shares_lock(self): ) calls.lock_project_shares.assert_called_once_with(self.project.id) + def test_a_repeat_reads_the_role_from_the_primary(self): + """A downgrade that a lagging replica has not replayed still stops a + repeat share of the old role.""" + ShareProject(self.project, "alice", ManagerRole.name).save() + + with lagging_replica(): + with use_master: + ShareProject(self.project, "alice", ReadOnlyRole.name).save() + self.assertTrue( + ManagerRole.has_role( + get_user_perms(self.alice, self.project), self.project + ) + ) + share_project_async.delay( + self.project.id, "alice", ManagerRole.name, repeat_only=True + ) + + self.assertFalse(ManagerRole.user_has_role(self.alice, self.project)) + self.assertTrue(ReadOnlyRole.user_has_role(self.alice, self.project)) + @patch("onadata.apps.api.tasks.logger.exception") def test_invalid_project_id(self, mock_log): """Invalid projecct_id is handled""" From 1a773e8dbb1b18aaa02a410a3a3377636c746fc9 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 12:08:15 +0300 Subject: [PATCH 072/120] fix: lock a form's project before the form in gated writes --- .../test_stepup_form_and_transfer_gates.py | 38 +++++++++++++++++++ .../viewsets/test_stepup_metadata_gates.py | 16 ++++++++ onadata/apps/api/viewsets/metadata_viewset.py | 4 +- onadata/apps/api/viewsets/xform_viewset.py | 20 ++++++++++ .../tests/test_stepup_legacy_publish_gate.py | 18 +++++++++ onadata/apps/main/views.py | 4 +- onadata/libs/stepup/drf.py | 28 +++++++++++++- onadata/libs/test_utils/stepup.py | 20 ++++++++++ onadata/libs/tests/stepup/test_drf.py | 19 +++++++++- 9 files changed, 162 insertions(+), 5 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py index 4445133f80..07b5f7f9b1 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py @@ -33,6 +33,7 @@ from onadata.libs.test_utils.stepup import ( StepUpGateTestCase, gating, + project_and_form_locks, ) ONE_GATED_CHANGE = "one_gated_change_per_request" @@ -544,6 +545,43 @@ def test_moving_by_update_into_a_private_project_is_not_challenged(self): self._reload() self.assertEqual(self.xform.project, closed) + def test_an_update_locks_the_project_before_the_form(self): + """A form save writes its project's row, and a project update writes + the rows of its forms. Both lock the project first, so they cannot + deadlock.""" + with CaptureQueriesContext(connection) as queries: + response = self._patch_form({"description": "renamed"}) + + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual( + project_and_form_locks(queries), + [ + ("logger_project", self.private_project.pk), + ("logger_xform", self.xform.pk), + ], + ) + + def test_a_move_locks_both_projects_in_primary_key_order(self): + """Two forms that move past each other between two projects then lock + the projects in the same order.""" + XForm.objects.filter(pk=self.xform.pk).update(project=self.public_project) + self.assertLess(self.private_project.pk, self.public_project.pk) + + with CaptureQueriesContext(connection) as queries: + response = self._patch_project(self.private_project) + + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual( + project_and_form_locks(queries), + [ + ("logger_project", self.private_project.pk), + ("logger_project", self.public_project.pk), + ("logger_xform", self.xform.pk), + ], + ) + self._reload() + self.assertEqual(self.xform.project, self.private_project) + @gating(GATE_TRANSFER_PROJECT) class TestMoveFormToAnotherAccountGate(GateTestCase): diff --git a/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py index ff3b8a1ef6..e46776ca7f 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py @@ -37,6 +37,7 @@ EDITOR_BECOMES_OWNER, EDITOR_STAYS_BELOW_ADMIN, gating, + project_and_form_locks, ) from onadata.libs.utils.common_tags import TEXTIT, XFORM_META_PERMS @@ -554,6 +555,21 @@ def test_a_create_locks_the_form(self): self.assertEqual(response.status_code, 201, response.data) self.assert_form_locked_before_write(queries, 'INSERT INTO "main_metadata"') + def test_a_create_locks_the_project_before_the_form(self): + """The write saves the form, which writes its project's row, so it + takes the project first, as a project update does.""" + with CaptureQueriesContext(connection) as queries: + response = self._create("public_link", "False") + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual( + project_and_form_locks(queries), + [ + ("logger_project", self.xform.project_id), + ("logger_xform", self.xform.pk), + ], + ) + def test_an_update_locks_the_form(self): """An update locks the form row before it writes the metadata row.""" (row,) = _rows(self.xform, "public_link", ("False",)) diff --git a/onadata/apps/api/viewsets/metadata_viewset.py b/onadata/apps/api/viewsets/metadata_viewset.py index 73eea16d60..d873a45eaf 100644 --- a/onadata/apps/api/viewsets/metadata_viewset.py +++ b/onadata/apps/api/viewsets/metadata_viewset.py @@ -25,7 +25,7 @@ from onadata.apps.api.tools import get_baseviewset_class from onadata.libs.data import strtobool from onadata.libs.stepup import RequiresStepUp -from onadata.libs.stepup.drf import lock_row, locked +from onadata.libs.stepup.drf import lock_projects, lock_row, locked from onadata.libs.stepup.policy import ( ADMIN_ROLE_NAMES, GATE_CHANGE_WEBHOOK, @@ -93,6 +93,8 @@ def _lock_parent(content_object, *data_types): and FIRST_ROW_TYPES.intersection(data_types) and gated_actions() ): + if isinstance(content_object, XForm): + lock_projects(content_object.project_id) lock_row(type(content_object), content_object.pk) diff --git a/onadata/apps/api/viewsets/xform_viewset.py b/onadata/apps/api/viewsets/xform_viewset.py index 80ac53d4c5..c326afa719 100644 --- a/onadata/apps/api/viewsets/xform_viewset.py +++ b/onadata/apps/api/viewsets/xform_viewset.py @@ -79,12 +79,14 @@ XFormVersionListSerializer, ) from onadata.libs.stepup import RequiresStepUp +from onadata.libs.stepup.drf import lock_projects, locked_for_gates from onadata.libs.stepup.policy import ( GATE_DISABLE_FORM_ENCRYPTION, GATE_FORM_REQUIRE_AUTH, GATE_PUBLISH_DATA, GATE_SHARE_FORM_ADMIN, GATE_TRANSFER_PROJECT, + gated_actions, is_gated, ) from onadata.libs.stepup.sharing import admin_roles_granted, holds_roles @@ -1106,6 +1108,24 @@ def _update_refusal(self, request, xform, validated_data): ), ) + def _project_named_in(self, request): + """The pk of the project that ``request`` moves the form to, or None + when it names none or an invalid one, which validation refuses.""" + data = request.data if isinstance(request.data, dict) else {} + if "project" not in data: + return None + field = self.get_serializer().fields["project"] + try: + return field.to_internal_value(data["project"]).pk + except exceptions.ValidationError: + return None + + def locked_for_update(self, request, instance): + """The form, locked after its project and the project it moves to.""" + if gated_actions(): + lock_projects(instance.project_id, self._project_named_in(request)) + return locked_for_gates(instance) + def update(self, request, *args, **kwargs): """Update a form's properties, the target of PUT and PATCH alike.""" return self.gated_update( diff --git a/onadata/apps/main/tests/test_stepup_legacy_publish_gate.py b/onadata/apps/main/tests/test_stepup_legacy_publish_gate.py index fad661a63f..c6201202a5 100644 --- a/onadata/apps/main/tests/test_stepup_legacy_publish_gate.py +++ b/onadata/apps/main/tests/test_stepup_legacy_publish_gate.py @@ -16,6 +16,7 @@ from onadata.apps.logger.models import XForm from onadata.apps.main.tests.test_base import TestBase from onadata.apps.main.views import edit +from onadata.libs.test_utils.stepup import project_and_form_locks PUBLISH_DATA = "publish-data" SHARED_FLAGS = {"data": "shared_data", "form": "shared"} @@ -134,3 +135,20 @@ def test_a_toggle_locks_the_form_before_its_check(self): self.assertTrue(locks, "The form row is not locked.") self.assertTrue(writes, "The form row is not written.") self.assertLess(locks[0], writes[0]) + + def test_a_toggle_locks_the_project_before_the_form(self): + """The form save writes its project's row, so the toggle takes the + project first, as a project update does.""" + self._set_flag("data", True) + + with CaptureQueriesContext(connection) as queries: + response = self._toggle("data") + + self.assertEqual(response.status_code, 200) + self.assertEqual( + project_and_form_locks(queries), + [ + ("logger_project", self.xform.project_id), + ("logger_xform", self.xform.pk), + ], + ) diff --git a/onadata/apps/main/views.py b/onadata/apps/main/views.py index e294fe58c3..b25dbec443 100644 --- a/onadata/apps/main/views.py +++ b/onadata/apps/main/views.py @@ -95,7 +95,7 @@ ) from onadata.libs.exceptions import EnketoError from onadata.libs.permissions import CAN_VIEW_PROJECT -from onadata.libs.stepup.drf import locked_for_gates +from onadata.libs.stepup.drf import locked_for_gates, locked_form_for_gates from onadata.libs.stepup.gate import refusal_reason from onadata.libs.stepup.pages import ( gated_profile_values, @@ -750,7 +750,7 @@ def _toggle_visibility(request, xform, owner, id_string): The row is locked and read again before the check, and the lock holds through the write.""" - locked_for_gates(xform) + locked_form_for_gates(xform) refusal = _refuse_making_public(request, xform) if refusal is not None: return refusal diff --git a/onadata/libs/stepup/drf.py b/onadata/libs/stepup/drf.py index ffb8be0d12..71593c5f38 100644 --- a/onadata/libs/stepup/drf.py +++ b/onadata/libs/stepup/drf.py @@ -8,6 +8,7 @@ from rest_framework import status from rest_framework.response import Response +from onadata.apps.logger.models import Project from onadata.libs.stepup.challenge import ( STEP_UP_UNAVAILABLE, build_challenge, @@ -53,6 +54,25 @@ def lock_row(model, pk): ) +def lock_projects(*project_pks): + """Lock the rows of the projects ``project_pks``, in primary key order, + until the transaction ends. None is skipped. + + A form save updates its project's row, and a project update writes the + rows of its forms. Lock a form's project before the form, so that two such + writes cannot deadlock.""" + for pk in sorted(set(project_pks) - {None}): + lock_row(Project, pk) + + +def locked_form_for_gates(xform): + """``locked_for_gates`` for a form, with its project locked first, as + ``lock_projects`` explains.""" + if gated_actions(): + lock_projects(xform.project_id) + return locked_for_gates(xform) + + class RequiresStepUp: """Refuse a gated action unless the request carries a single-use grant. @@ -95,6 +115,12 @@ def step_up_refusal(self, request, reason, audiences): headers={"WWW-Authenticate": challenge_header(challenge)}, ) + def locked_for_update(self, request, instance): + """``instance`` as ``locked_for_gates`` returns it. ``gated_update`` + calls it in its transaction. An override can first lock other rows + that the update writes.""" + return locked_for_gates(instance) + def gated_create(self, request, refusal_for): """DRF's create with a gate between validating and writing. @@ -128,7 +154,7 @@ def gated_update(self, request, refusal_for, partial=False): # pylint: disable=no-member gating = bool(gated_actions()) with transaction.atomic() if gating else nullcontext(): - instance = locked_for_gates(self.get_object()) + instance = self.locked_for_update(request, self.get_object()) serializer = self.get_serializer( instance, data=request.data, partial=partial ) diff --git a/onadata/libs/test_utils/stepup.py b/onadata/libs/test_utils/stepup.py index 35d48c9e6d..7b1a5eee54 100644 --- a/onadata/libs/test_utils/stepup.py +++ b/onadata/libs/test_utils/stepup.py @@ -3,6 +3,8 @@ Helpers for tests of the step-up gates. """ +import re + from django.test.utils import override_settings from django_otp.plugins.otp_totp.models import TOTPDevice @@ -16,6 +18,24 @@ EDITOR_BECOMES_MANAGER = "manager|dataentry-only|readonly" EDITOR_STAYS_BELOW_ADMIN = "editor-minor|dataentry-only|readonly" +_PROJECT_OR_FORM_LOCK = re.compile( + r'FROM "(logger_project|logger_xform)" WHERE "\1"\."id" = (\d+) .*FOR UPDATE', + re.S, +) + + +def project_and_form_locks(queries): + """``(table, pk)`` for each project or form row that ``queries``, a + ``CaptureQueriesContext``, locked ``FOR UPDATE``, in order.""" + return [ + (match[1], int(match[2])) + for match in ( + _PROJECT_OR_FORM_LOCK.search(query["sql"]) + for query in queries.captured_queries + ) + if match + ] + def gating(*audiences, **settings): """Gate exactly ``audiences``, for a user with a confirmed factor.""" diff --git a/onadata/libs/tests/stepup/test_drf.py b/onadata/libs/tests/stepup/test_drf.py index 21d7f98efe..f0c29ee20e 100644 --- a/onadata/libs/tests/stepup/test_drf.py +++ b/onadata/libs/tests/stepup/test_drf.py @@ -4,7 +4,9 @@ from django.contrib.auth import get_user_model from django.contrib.auth.models import AnonymousUser from django.core.cache import cache +from django.db import connection, transaction from django.test import TestCase, override_settings +from django.test.utils import CaptureQueriesContext from django_otp.plugins.otp_totp.models import TOTPDevice from oidc.stepup_grants import issue_grant @@ -12,7 +14,8 @@ from rest_framework.request import Request from rest_framework.test import APIRequestFactory -from onadata.libs.stepup.drf import RequiresStepUp +from onadata.libs.stepup.drf import RequiresStepUp, lock_projects +from onadata.libs.test_utils.stepup import project_and_form_locks from onadata.libs.tests.stepup.test_challenge import ( FEDERATED, FEDERATED_SERVER, @@ -287,3 +290,17 @@ def test_a_request_without_a_grant_records_no_rejection(self): refusal = self.view.check_step_up(self._request(), "require-auth-toggle") self.assertEqual(refusal.status_code, 401) + + +class TestLockProjects(TestCase): + """Tests for ``lock_projects``.""" + + def test_locks_each_project_once_in_primary_key_order(self): + """None is skipped, and a primary key given twice is locked once.""" + with transaction.atomic(), CaptureQueriesContext(connection) as queries: + lock_projects(5, None, 2, 5) + + self.assertEqual( + project_and_form_locks(queries), + [("logger_project", 2), ("logger_project", 5)], + ) From a1395aa373cc2c3504f92ff6a0f606bc20ff7298 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 12:10:29 +0300 Subject: [PATCH 073/120] test: show a clean start and a refused anonymous member PUT --- .../test_organization_profile_viewset.py | 37 +++++++++++++++++-- onadata/libs/tests/stepup/test_checks.py | 19 +++++++++- 2 files changed, 50 insertions(+), 6 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_organization_profile_viewset.py b/onadata/apps/api/tests/viewsets/test_organization_profile_viewset.py index aaf3ff5cc3..66af1b94e3 100644 --- a/onadata/apps/api/tests/viewsets/test_organization_profile_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_organization_profile_viewset.py @@ -43,7 +43,13 @@ from onadata.apps.main.models import UserProfile from onadata.apps.messaging.viewsets import MessagingViewSet from onadata.libs.exceptions import EncryptionError -from onadata.libs.permissions import ROLES, DataEntryRole, ManagerRole, OwnerRole +from onadata.libs.permissions import ( + ROLES, + DataEntryRole, + EditorRole, + ManagerRole, + OwnerRole, +) from onadata.libs.utils.cache_tools import ( PROJ_OWNER_CACHE, PROJ_PERM_CACHE, @@ -780,13 +786,13 @@ def test_members_delete_acts_on_body_username(self): self.assertTrue(members_team.user_set.filter(username="aboy").exists()) self.assertFalse(members_team.user_set.filter(username="alice").exists()) - def _org_members(self, method, username): + def _org_members(self, method, username, **data): view = OrganizationProfileViewSet.as_view( - {"post": "members", "delete": "members"} + {"post": "members", "put": "members", "delete": "members"} ) request = getattr(self.factory, method)( "/", - data=json.dumps({"username": username}), + data=json.dumps({"username": username, **data}), content_type="application/json", **self.extra, ) @@ -812,6 +818,29 @@ def test_add_anonymous_user_to_org_is_refused(self): members_team = Team.objects.get(name="denoinc#members") self.assertFalse(members_team.user_set.filter(pk=anonymous.pk).exists()) + def test_put_anonymous_user_in_org_is_refused(self): + """A PUT adds a user who is not a member yet, so it refuses the + anonymous user as a POST does.""" + self._org_create() + anonymous = User.objects.get_or_create( + username=settings.ANONYMOUS_DEFAULT_USERNAME + )[0] + self._create_user_profile(extra_post_data={"username": "aboy"}) + self.assertEqual( + self._org_members("put", "aboy", role=EditorRole.name).status_code, 200 + ) + + response = self._org_members("put", anonymous.username, role=EditorRole.name) + + self.assertEqual(response.status_code, 400) + self.assertEqual( + response.data, + {"username": ["Cannot add the anonymous user to an organization."]}, + ) + members_team = Team.objects.get(name="denoinc#members") + self.assertTrue(members_team.user_set.filter(username="aboy").exists()) + self.assertFalse(members_team.user_set.filter(pk=anonymous.pk).exists()) + def test_remove_anonymous_user_from_org(self): """The anonymous user can still be removed from an organization it is in.""" diff --git a/onadata/libs/tests/stepup/test_checks.py b/onadata/libs/tests/stepup/test_checks.py index 7c2591fa56..19e490565d 100644 --- a/onadata/libs/tests/stepup/test_checks.py +++ b/onadata/libs/tests/stepup/test_checks.py @@ -41,6 +41,21 @@ def _servers(**step_up): return {"idp": {"STEP_UP": {"REDIRECT_URI": "https://app.test/cb", **step_up}}} +def _complete_servers(): + """A provider whose ``STEP_UP`` block passes ona-oidc's ``oidc.E003``.""" + return { + "idp": { + "TOKEN_ENDPOINT": "https://idp.test/token", + "STEP_UP": { + "CLAIM": "acr", + "MAX_AGE": 0, + "REDIRECT_URI": "https://app.test/cb", + "SATISFIED_BY": ["gold"], + }, + } + } + + def _start_error(): """The error that stops the start, or ``""``.""" try: @@ -109,13 +124,13 @@ def test_federated_step_up_with_no_server_stops_the_start(self): @override_settings( STEP_UP={"ACTIONS": ["change-email"], "MODE": "federated"}, - OPENID_CONNECT_AUTH_SERVERS=_servers(), + OPENID_CONNECT_AUTH_SERVERS=_complete_servers(), ) def test_an_unusable_popup_origin_stops_the_start(self): """``stepup.W010`` sees only that ``STEP_UP_POPUP_ORIGIN`` is set. ona-oidc's ``oidc.E003`` reports a value that is not an origin.""" with override_settings(STEP_UP_POPUP_ORIGIN="https://app.test"): - self.assertNotIn("STEP_UP_POPUP_ORIGIN", _start_error()) + self.assertEqual(_start_error(), "") with override_settings(STEP_UP_POPUP_ORIGIN="app.test"): self.assertEqual(check_federated_step_up_has_a_popup_origin(), []) From 1333c3c4c83fd1b6392265437db8c9d9750916e1 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 12:10:30 +0300 Subject: [PATCH 074/120] docs: explain the ungated share lock and the step-up token endpoint --- docs/two_factor.rst | 7 +++++++ onadata/libs/models/share_project.py | 2 ++ 2 files changed, 9 insertions(+) diff --git a/docs/two_factor.rst b/docs/two_factor.rst index 2ffc45f788..4755fe1c44 100644 --- a/docs/two_factor.rst +++ b/docs/two_factor.rst @@ -465,6 +465,13 @@ does not load if a step-up check, or the ona-oidc check of the ``STEP_UP`` block of the provider (``oidc.E003``), reports an error. ``manage.py check`` shows all results. +Step-up always uses the authorization code flow. Thus, ``oidc.E003`` +reports a provider that has a ``STEP_UP`` block but no ``TOKEN_ENDPOINT``, +also where login uses the implicit flow. Set ``TOKEN_ENDPOINT`` on that +provider before you upgrade, or the application does not start. A +``STEP_UP_POPUP_ORIGIN`` that is set but is not an http or https origin is +also ``oidc.E003``. + - ``stepup.E001`` (error). ``STEP_UP`` is not a dict, or its ``ACTIONS`` is not a list of action names. Step-up then gates nothing. - ``stepup.E002`` (error). ``STEP_UP["ACTIONS"]`` names an action that no diff --git a/onadata/libs/models/share_project.py b/onadata/libs/models/share_project.py index 5bc0977522..382c8ef8c4 100644 --- a/onadata/libs/models/share_project.py +++ b/onadata/libs/models/share_project.py @@ -88,6 +88,8 @@ def user(self): def save(self, **kwargs): """Assigns role permissions to a project for the user.""" # pylint: disable=too-many-nested-blocks + # Taken even where nothing is gated: a repeat share queued while a gate + # was on must still be ordered with a later downgrade. lock_project_shares(self.project.pk) clear_project_owner_cache(self.project.pk) safe_cache_delete(f"{PROJ_PERM_CACHE}{self.project.pk}") From b222fd0ec6de642c03647de18a6e44a4b5790da2 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 12:19:23 +0300 Subject: [PATCH 075/120] test: give the federated step-up test server a token endpoint --- onadata/libs/tests/stepup/test_challenge.py | 1 + 1 file changed, 1 insertion(+) diff --git a/onadata/libs/tests/stepup/test_challenge.py b/onadata/libs/tests/stepup/test_challenge.py index b9ee6d662a..534e10881f 100644 --- a/onadata/libs/tests/stepup/test_challenge.py +++ b/onadata/libs/tests/stepup/test_challenge.py @@ -21,6 +21,7 @@ "AUTHORIZATION_ENDPOINT": "https://idp.example/auth", "CLIENT_ID": "app", "SCOPE": "openid email", + "TOKEN_ENDPOINT": "https://idp.example/token", "STEP_UP": { "CLAIM": "acr", "SATISFIED_BY": ["gold"], From c0ad267d9356662d3467dc6a3cab95405a76a66a Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 12:19:24 +0300 Subject: [PATCH 076/120] fix: compare an OAuth application update with the stored row, not posted initials --- .../apps/main/tests/test_stepup_oauth_gate.py | 19 +++++++++++++++++++ onadata/apps/main/views.py | 17 ++++++++++------- 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/onadata/apps/main/tests/test_stepup_oauth_gate.py b/onadata/apps/main/tests/test_stepup_oauth_gate.py index 182691c96d..17a6d79df8 100644 --- a/onadata/apps/main/tests/test_stepup_oauth_gate.py +++ b/onadata/apps/main/tests/test_stepup_oauth_gate.py @@ -376,6 +376,25 @@ def test_a_new_client_secret_without_a_grant_is_refused(self): application.refresh_from_db() self.assertEqual(application.client_secret, secret) + def test_a_posted_initial_secret_does_not_hide_a_new_secret(self): + """The gate compares with the stored secret, not the posted initial one.""" + application = self._application(user=self.user) + secret = application.client_secret + new_secret = "a-new-secret-value" + + response = self._update( + application, + client_secret=new_secret, + **{ + "initial-client_id": application.client_id, + "initial-client_secret": new_secret, + }, + ) + + self.assertEqual(response.status_code, 403) + application.refresh_from_db() + self.assertEqual(application.client_secret, secret) + def test_the_update_locks_the_application_before_the_comparison(self): """An edit that echoes the values it read cannot write back over a concurrent change.""" diff --git a/onadata/apps/main/views.py b/onadata/apps/main/views.py index b25dbec443..82d3fbf555 100644 --- a/onadata/apps/main/views.py +++ b/onadata/apps/main/views.py @@ -2013,12 +2013,15 @@ def form_valid(self, form): def _application_field_changed(form, field): - """Whether ``field``, one of ``form.changed_data``, holds a new value.""" - if field not in _APPLICATION_LIST_FIELDS: - return True - return (form.initial.get(field) or "").split() != ( - form.cleaned_data.get(field) or "" - ).split() + """Whether ``field`` holds a value other than the stored one. + + Not ``form.changed_data``: for a field with a callable default, such as + ``client_secret``, that reads the old value from the POST.""" + stored = form.initial.get(field) + posted = form.cleaned_data.get(field) + if field in _APPLICATION_LIST_FIELDS: + return (stored or "").split() != (posted or "").split() + return stored != posted class StepUpApplicationUpdate(ApplicationUpdate): @@ -2045,7 +2048,7 @@ def post(self, request, *args, **kwargs): def form_valid(self, form): if any( _application_field_changed(form, field) - for field in set(form.changed_data) - _UNGATED_APPLICATION_FIELDS + for field in set(form.fields) - _UNGATED_APPLICATION_FIELDS ): refusal = refuse_page_action(self.request, GATE_AUTHORIZE_OAUTH_APP) if refusal is not None: From 5c322a52e340fee1d5d1a48eca8008d3ffcc8b79 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 12:19:24 +0300 Subject: [PATCH 077/120] test: watch the project admin role check the share uses --- .../apps/api/tests/viewsets/test_stepup_sharing_gates.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py index 2ec29cc89c..8941e71e3b 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py @@ -40,7 +40,11 @@ GATE_SHARE_FORM_ADMIN, GATE_SHARE_PROJECT_ADMIN, ) -from onadata.libs.stepup.sharing import admin_roles_granted, grants_admin_role +from onadata.libs.stepup.sharing import ( + admin_roles_granted, + grants_admin_role, + project_admin_roles_granted, +) from onadata.libs.test_utils.stepup import ( EDITOR_BECOMES_MANAGER, EDITOR_BECOMES_OWNER, @@ -236,7 +240,8 @@ def test_the_admin_check_runs_only_where_gated(self): """The admin role check runs only when the deployment gates project admin shares.""" with patch( - f"{PROJECT_VIEWSET}.admin_roles_granted", wraps=admin_roles_granted + f"{PROJECT_VIEWSET}.project_admin_roles_granted", + wraps=project_admin_roles_granted, ) as check: self.assert_challenged(self._share("tom", OwnerRole.name)) self.assertTrue(check.called) From 92aea9827066a14f3edcb53823d9faebd2821715 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 12:21:07 +0300 Subject: [PATCH 078/120] fix: keep the form lock hook private to stay under the public method limit --- onadata/apps/api/viewsets/xform_viewset.py | 2 +- onadata/libs/stepup/drf.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/onadata/apps/api/viewsets/xform_viewset.py b/onadata/apps/api/viewsets/xform_viewset.py index c326afa719..bab595bff5 100644 --- a/onadata/apps/api/viewsets/xform_viewset.py +++ b/onadata/apps/api/viewsets/xform_viewset.py @@ -1120,7 +1120,7 @@ def _project_named_in(self, request): except exceptions.ValidationError: return None - def locked_for_update(self, request, instance): + def _locked_for_update(self, request, instance): """The form, locked after its project and the project it moves to.""" if gated_actions(): lock_projects(instance.project_id, self._project_named_in(request)) diff --git a/onadata/libs/stepup/drf.py b/onadata/libs/stepup/drf.py index 71593c5f38..7b8831d48e 100644 --- a/onadata/libs/stepup/drf.py +++ b/onadata/libs/stepup/drf.py @@ -115,7 +115,7 @@ def step_up_refusal(self, request, reason, audiences): headers={"WWW-Authenticate": challenge_header(challenge)}, ) - def locked_for_update(self, request, instance): + def _locked_for_update(self, request, instance): """``instance`` as ``locked_for_gates`` returns it. ``gated_update`` calls it in its transaction. An override can first lock other rows that the update writes.""" @@ -154,7 +154,7 @@ def gated_update(self, request, refusal_for, partial=False): # pylint: disable=no-member gating = bool(gated_actions()) with transaction.atomic() if gating else nullcontext(): - instance = self.locked_for_update(request, self.get_object()) + instance = self._locked_for_update(request, self.get_object()) serializer = self.get_serializer( instance, data=request.data, partial=partial ) From 7708bd529042cb79f2a717d3659620dc3e0ac274 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 12:21:07 +0300 Subject: [PATCH 079/120] test: keep the eager permission task from pinning the repeat share test --- onadata/apps/api/tests/test_tasks.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/onadata/apps/api/tests/test_tasks.py b/onadata/apps/api/tests/test_tasks.py index 44219cc07d..a97d746b87 100644 --- a/onadata/apps/api/tests/test_tasks.py +++ b/onadata/apps/api/tests/test_tasks.py @@ -178,7 +178,12 @@ def test_a_repeat_reads_the_role_from_the_primary(self): ShareProject(self.project, "alice", ManagerRole.name).save() with lagging_replica(): - with use_master: + # The eager propagate task enters its own use_master; nested, it + # leaves this thread pinned to the primary. + with use_master, patch( + "onadata.libs.models.share_project." + "propagate_project_permissions_async" + ): ShareProject(self.project, "alice", ReadOnlyRole.name).save() self.assertTrue( ManagerRole.has_role( From 0de93377fe4b48f9482815fb77e3f7f85e60e6e5 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 13:31:59 +0300 Subject: [PATCH 080/120] chore: pin ona-oidc to b768994 --- requirements/base.in | 2 +- requirements/base.pip | 2 +- requirements/dev.pip | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/requirements/base.in b/requirements/base.in index 90b3aada1f..8ee0b22a11 100644 --- a/requirements/base.in +++ b/requirements/base.in @@ -30,7 +30,7 @@ git+https://github.com/onaio/floip-py.git@3c980eb184069ae7c3c9136b18441978237cd4 git+https://github.com/onaio/python-json2xlsclient.git@62b4645f7b4f2684421a13ce98da0331a9dd66a0#egg=python-json2xlsclient # Pinned at the step-up branch tip for stepup_grants, which the totp endpoints # import. Re-pin to a main SHA once onaio/ona-oidc#139 merges. -git+https://github.com/onaio/ona-oidc.git@1c03e7816558c614172130246208cb12ee17a7ba#egg=ona-oidc +git+https://github.com/onaio/ona-oidc.git@b768994524c9259c90cf0174b7fe8852c41a8973#egg=ona-oidc -e git+https://github.com/onaio/savreaderwriter.git@fix-pep-440-issues#egg=savreaderwriter git+https://git@github.com/onaio/valigetta.git@v0.3.1#egg=valigetta codetiming diff --git a/requirements/base.pip b/requirements/base.pip index 6e03cedf24..de72bbd985 100644 --- a/requirements/base.pip +++ b/requirements/base.pip @@ -265,7 +265,7 @@ oauthlib==4.0.1 # -r requirements/base.in # django-oauth-toolkit # requests-oauthlib -ona-oidc @ git+https://github.com/onaio/ona-oidc.git@1c03e7816558c614172130246208cb12ee17a7ba +ona-oidc @ git+https://github.com/onaio/ona-oidc.git@b768994524c9259c90cf0174b7fe8852c41a8973 # via -r requirements/base.in openpyxl==3.1.5 # via diff --git a/requirements/dev.pip b/requirements/dev.pip index b72e316758..c1c3d493d2 100644 --- a/requirements/dev.pip +++ b/requirements/dev.pip @@ -331,7 +331,7 @@ oauthlib==4.0.1 # -r requirements/base.in # django-oauth-toolkit # requests-oauthlib -ona-oidc @ git+https://github.com/onaio/ona-oidc.git@1c03e7816558c614172130246208cb12ee17a7ba +ona-oidc @ git+https://github.com/onaio/ona-oidc.git@b768994524c9259c90cf0174b7fe8852c41a8973 # via -r requirements/base.in openpyxl==3.1.5 # via From 78d01235d8043e874a362b4a65bfea13764a2212 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 13:35:56 +0300 Subject: [PATCH 081/120] fix: hide the step-up callback code and state from error reports --- .../api/tests/viewsets/test_stepup_viewset.py | 38 +++++++++++++++++++ onadata/apps/api/viewsets/stepup_viewset.py | 3 ++ onadata/libs/stepup/error_reports.py | 18 +++++++++ .../libs/tests/stepup/test_error_reports.py | 27 +++++++++++++ onadata/settings/common.py | 6 +++ 5 files changed, 92 insertions(+) create mode 100644 onadata/libs/stepup/error_reports.py create mode 100644 onadata/libs/tests/stepup/test_error_reports.py diff --git a/onadata/apps/api/tests/viewsets/test_stepup_viewset.py b/onadata/apps/api/tests/viewsets/test_stepup_viewset.py index 5b5a2aa572..d0f8229733 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_viewset.py @@ -12,14 +12,19 @@ from django.test import TestCase from django.test.utils import override_settings from django.urls import reverse +from django.views.debug import get_exception_reporter_class from oidc.stepup_grants import spend_grant from oidc.utils import CacheWriteFailed +from rest_framework.test import APIRequestFactory, force_authenticate from onadata.apps.api.tests.viewsets.test_abstract_viewset import TestAbstractViewSet from onadata.apps.api.viewsets.stepup_viewset import StepUpViewSet from onadata.libs.stepup.federated import start_step_up +# Away from any frame the error report quotes source lines from. +CALLBACK_CODE = "authz-code-5f2c" + STEP_UP_FEDERATED = { "MODE": "federated", "ACTIONS": ["require-auth-toggle"], @@ -51,6 +56,13 @@ SATISFYING = {"acr": "gold", "email": "ana@example.org", "email_verified": True} +class _FailingHookViewSet(StepUpViewSet): + """A callback whose context hook fails, as a host bug would.""" + + def verify_step_up_context(self, request, context): + raise RuntimeError("context hook failed") + + class TestStepUpViewSet(TestAbstractViewSet): """Where the popup starts, and what comes back to it.""" @@ -314,3 +326,29 @@ def test_state_belonging_to_another_user_is_refused(self): self.assertIsNone(grant) self.assertEqual(reason, "state_user_mismatch") + + @override_settings(DEBUG=False) + def test_an_error_report_hides_the_callback_code_and_state(self): + """An error in the callback is reported without its code and state. + + This needs the reporter settings and ``sensitive_variables`` on the + callback. The filter does nothing while DEBUG is on. + """ + request = APIRequestFactory().get( + "/api/v1/stepup/callback", {"code": CALLBACK_CODE, "state": self.state} + ) + force_authenticate(request, user=self.user) + view = _FailingHookViewSet.as_view({"get": "callback"}) + + with self.assertRaises(RuntimeError) as caught: + view(request) + + error = caught.exception + report = get_exception_reporter_class(request)( + request, type(error), error, error.__traceback__ + ).get_traceback_html() + self.assertIn("context hook failed", report) + self.assertIn("verify_step_up_context", report) + self.assertIn("********************", report) + self.assertNotIn(CALLBACK_CODE, report) + self.assertNotIn(self.state, report) diff --git a/onadata/apps/api/viewsets/stepup_viewset.py b/onadata/apps/api/viewsets/stepup_viewset.py index a53c289308..cc3cff5fd7 100644 --- a/onadata/apps/api/viewsets/stepup_viewset.py +++ b/onadata/apps/api/viewsets/stepup_viewset.py @@ -4,6 +4,8 @@ import logging from collections.abc import Mapping +from django.views.decorators.debug import sensitive_variables + from oidc.stepup_grants import issue_grant from oidc.stepup_viewsets import StepUpCallbackMixin from rest_framework import status @@ -87,6 +89,7 @@ def start(self, request): return Response({"authorizationUrl": url}) @action(detail=False, methods=["get", "post"], url_path="callback") + @sensitive_variables("code", "state") def callback(self, request): """Verify the provider's answer, and mint a grant only if it satisfies the step-up.""" diff --git a/onadata/libs/stepup/error_reports.py b/onadata/libs/stepup/error_reports.py new file mode 100644 index 0000000000..8458faaab0 --- /dev/null +++ b/onadata/libs/stepup/error_reports.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +"""Error reports that hide the credentials the step-up callback receives.""" + +from oidc.error_reports import CallbackExceptionReporterFilter +from rest_framework.request import Request + + +class StepUpExceptionReporterFilter(CallbackExceptionReporterFilter): + """Also hides them in a DRF ``Request`` in the traceback. + + A DRF ``Request`` is not an ``HttpRequest``, so the parent filter shows its + ``repr``, which carries the full query. + """ + + def cleanse_special_types(self, request, value): + if isinstance(value, Request): + value = value._request # pylint: disable=protected-access + return super().cleanse_special_types(request, value) diff --git a/onadata/libs/tests/stepup/test_error_reports.py b/onadata/libs/tests/stepup/test_error_reports.py new file mode 100644 index 0000000000..4a6c81191e --- /dev/null +++ b/onadata/libs/tests/stepup/test_error_reports.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +"""Tests for onadata.libs.stepup.error_reports.""" + +from django.test import RequestFactory, SimpleTestCase +from django.test.utils import override_settings + +from rest_framework.request import Request + +from onadata.libs.stepup.error_reports import StepUpExceptionReporterFilter + + +class TestStepUpExceptionReporterFilter(SimpleTestCase): + """The filter also covers the DRF ``Request`` a viewset frame holds.""" + + @override_settings(DEBUG=False) + def test_a_drf_request_is_shown_without_the_callback_code(self): + """A DRF ``Request`` local shows its path but not the code.""" + http_request = RequestFactory().get("/callback", {"code": "authz-code-7d1e"}) + + shown = str( + StepUpExceptionReporterFilter().cleanse_special_types( + http_request, Request(http_request) + ) + ) + + self.assertIn("/callback", shown) + self.assertNotIn("authz-code-7d1e", shown) diff --git a/onadata/settings/common.py b/onadata/settings/common.py index 3fdb0bf1cc..6e37457cb3 100644 --- a/onadata/settings/common.py +++ b/onadata/settings/common.py @@ -166,6 +166,12 @@ "NO_FACTOR_POLICY": "skip_gate", } +# Hide the code and state the step-up callback receives from error reports. +DEFAULT_EXCEPTION_REPORTER = "oidc.error_reports.CallbackExceptionReporter" +DEFAULT_EXCEPTION_REPORTER_FILTER = ( + "onadata.libs.stepup.error_reports.StepUpExceptionReporterFilter" +) + # Symmetric keys the authenticator seed and recovery codes are encrypted under # at rest (Fernet, url-safe base64). Ordered: the first key encrypts, every key # is tried for decryption, so a new key is rolled in at the front and the stored From 00b08b302def650cb60a864923faedc88ff73961 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 13:36:03 +0300 Subject: [PATCH 082/120] docs: say what binds a federated step-up and which token endpoint it needs --- docs/two_factor.rst | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/docs/two_factor.rst b/docs/two_factor.rst index 4755fe1c44..9e74e8a7af 100644 --- a/docs/two_factor.rst +++ b/docs/two_factor.rst @@ -435,6 +435,19 @@ profile gets no challenge. difference in seconds. The default is 0. Each second lets a provider that ignores ``max_age=0`` use a session that is that much older. + The provider sends the code and the state in the query of the callback. + The error reports of OnaData replace their values, and the values of + ``id_token`` and ``access_token``, while ``DEBUG`` is off. A deployment + that sets ``DEFAULT_EXCEPTION_REPORTER`` or + ``DEFAULT_EXCEPTION_REPORTER_FILTER`` must keep this behaviour. + + The state holds the id of the user who started the step-up. The callback + refuses it for any other signed-in user with ``state_user_mismatch``. The + state can be used once. The token must carry the nonce of that state, and + its ``auth_time`` must not be before the start. The state is not bound to a + browser session, because a client can start the step-up with an API token + that has no session. + In local mode, the gate lets a user with no second factor through by default (``STEP_UP["NO_FACTOR_POLICY"] = "skip_gate"``). With ``deny_prompt_enrol``, the gate refuses such a user with ``enrol_required``. A federated deployment @@ -466,8 +479,9 @@ block of the provider (``oidc.E003``), reports an error. ``manage.py check`` shows all results. Step-up always uses the authorization code flow. Thus, ``oidc.E003`` -reports a provider that has a ``STEP_UP`` block but no ``TOKEN_ENDPOINT``, -also where login uses the implicit flow. Set ``TOKEN_ENDPOINT`` on that +reports a provider that has a ``STEP_UP`` block but no ``TOKEN_ENDPOINT`` +that is an absolute http or https URL, also where login uses the implicit +flow. Set ``TOKEN_ENDPOINT`` on that provider before you upgrade, or the application does not start. A ``STEP_UP_POPUP_ORIGIN`` that is set but is not an http or https origin is also ``oidc.E003``. From a449b2d1894f55d7c058c7d5f6f0d6df78b0ec3f Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 13:36:49 +0300 Subject: [PATCH 083/120] test: refuse a lone change to each remaining gated application field --- .../apps/main/tests/test_stepup_oauth_gate.py | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/onadata/apps/main/tests/test_stepup_oauth_gate.py b/onadata/apps/main/tests/test_stepup_oauth_gate.py index 17a6d79df8..6e00758e1c 100644 --- a/onadata/apps/main/tests/test_stepup_oauth_gate.py +++ b/onadata/apps/main/tests/test_stepup_oauth_gate.py @@ -365,6 +365,32 @@ def test_changing_the_allowed_origins_without_a_grant_is_refused(self): application.refresh_from_db() self.assertEqual(application.allowed_origins, "") + def test_changing_any_other_gated_field_without_a_grant_is_refused(self): + """A change to one of these fields alone answers 403 and stores + nothing.""" + application_model = get_application_model() + changes = { + "hash_client_secret": False, + "algorithm": application_model.HS256_ALGORITHM, + "client_id": "another-client-id", + "post_logout_redirect_uris": OTHER_REDIRECT_URI, + } + for field, value in changes.items(): + with self.subTest(field=field): + # HS256 is valid only for a confidential client. + application = self._application( + user=self.user, client_type=application_model.CLIENT_CONFIDENTIAL + ) + stored = application_model.objects.values().get(pk=application.pk) + self.assertNotEqual(stored[field], value) + + response = self._update(application, **{field: value}) + + self.assertEqual(response.status_code, 403) + self.assertEqual( + application_model.objects.values().get(pk=application.pk), stored + ) + def test_a_new_client_secret_without_a_grant_is_refused(self): """Without a grant, a new client secret answers 403 and the old secret stays.""" application = self._application(user=self.user) From 9d106a0b0dcfe2a348fbc047f1b362b560c6d6c0 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 13:36:49 +0300 Subject: [PATCH 084/120] refactor: close the application field docstring on its own line --- onadata/apps/main/views.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/onadata/apps/main/views.py b/onadata/apps/main/views.py index 82d3fbf555..594ab92207 100644 --- a/onadata/apps/main/views.py +++ b/onadata/apps/main/views.py @@ -2016,7 +2016,8 @@ def _application_field_changed(form, field): """Whether ``field`` holds a value other than the stored one. Not ``form.changed_data``: for a field with a callable default, such as - ``client_secret``, that reads the old value from the POST.""" + ``client_secret``, that reads the old value from the POST. + """ stored = form.initial.get(field) posted = form.cleaned_data.get(field) if field in _APPLICATION_LIST_FIELDS: From 09beec46e67f8e04ead4062acf1dcdade027a16d Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 13:39:52 +0300 Subject: [PATCH 085/120] refactor: use the ona-oidc error report filter for DRF requests too --- onadata/libs/stepup/error_reports.py | 18 ------------- .../libs/tests/stepup/test_error_reports.py | 27 ------------------- onadata/settings/common.py | 4 +-- requirements/base.in | 2 +- requirements/base.pip | 2 +- requirements/dev.pip | 2 +- 6 files changed, 4 insertions(+), 51 deletions(-) delete mode 100644 onadata/libs/stepup/error_reports.py delete mode 100644 onadata/libs/tests/stepup/test_error_reports.py diff --git a/onadata/libs/stepup/error_reports.py b/onadata/libs/stepup/error_reports.py deleted file mode 100644 index 8458faaab0..0000000000 --- a/onadata/libs/stepup/error_reports.py +++ /dev/null @@ -1,18 +0,0 @@ -# -*- coding: utf-8 -*- -"""Error reports that hide the credentials the step-up callback receives.""" - -from oidc.error_reports import CallbackExceptionReporterFilter -from rest_framework.request import Request - - -class StepUpExceptionReporterFilter(CallbackExceptionReporterFilter): - """Also hides them in a DRF ``Request`` in the traceback. - - A DRF ``Request`` is not an ``HttpRequest``, so the parent filter shows its - ``repr``, which carries the full query. - """ - - def cleanse_special_types(self, request, value): - if isinstance(value, Request): - value = value._request # pylint: disable=protected-access - return super().cleanse_special_types(request, value) diff --git a/onadata/libs/tests/stepup/test_error_reports.py b/onadata/libs/tests/stepup/test_error_reports.py deleted file mode 100644 index 4a6c81191e..0000000000 --- a/onadata/libs/tests/stepup/test_error_reports.py +++ /dev/null @@ -1,27 +0,0 @@ -# -*- coding: utf-8 -*- -"""Tests for onadata.libs.stepup.error_reports.""" - -from django.test import RequestFactory, SimpleTestCase -from django.test.utils import override_settings - -from rest_framework.request import Request - -from onadata.libs.stepup.error_reports import StepUpExceptionReporterFilter - - -class TestStepUpExceptionReporterFilter(SimpleTestCase): - """The filter also covers the DRF ``Request`` a viewset frame holds.""" - - @override_settings(DEBUG=False) - def test_a_drf_request_is_shown_without_the_callback_code(self): - """A DRF ``Request`` local shows its path but not the code.""" - http_request = RequestFactory().get("/callback", {"code": "authz-code-7d1e"}) - - shown = str( - StepUpExceptionReporterFilter().cleanse_special_types( - http_request, Request(http_request) - ) - ) - - self.assertIn("/callback", shown) - self.assertNotIn("authz-code-7d1e", shown) diff --git a/onadata/settings/common.py b/onadata/settings/common.py index 6e37457cb3..8c1d70ceeb 100644 --- a/onadata/settings/common.py +++ b/onadata/settings/common.py @@ -168,9 +168,7 @@ # Hide the code and state the step-up callback receives from error reports. DEFAULT_EXCEPTION_REPORTER = "oidc.error_reports.CallbackExceptionReporter" -DEFAULT_EXCEPTION_REPORTER_FILTER = ( - "onadata.libs.stepup.error_reports.StepUpExceptionReporterFilter" -) +DEFAULT_EXCEPTION_REPORTER_FILTER = "oidc.error_reports.CallbackExceptionReporterFilter" # Symmetric keys the authenticator seed and recovery codes are encrypted under # at rest (Fernet, url-safe base64). Ordered: the first key encrypts, every key diff --git a/requirements/base.in b/requirements/base.in index 8ee0b22a11..0af8845ecb 100644 --- a/requirements/base.in +++ b/requirements/base.in @@ -30,7 +30,7 @@ git+https://github.com/onaio/floip-py.git@3c980eb184069ae7c3c9136b18441978237cd4 git+https://github.com/onaio/python-json2xlsclient.git@62b4645f7b4f2684421a13ce98da0331a9dd66a0#egg=python-json2xlsclient # Pinned at the step-up branch tip for stepup_grants, which the totp endpoints # import. Re-pin to a main SHA once onaio/ona-oidc#139 merges. -git+https://github.com/onaio/ona-oidc.git@b768994524c9259c90cf0174b7fe8852c41a8973#egg=ona-oidc +git+https://github.com/onaio/ona-oidc.git@d5b3618bee8c52a3275394a4903cd1a771b04c6c#egg=ona-oidc -e git+https://github.com/onaio/savreaderwriter.git@fix-pep-440-issues#egg=savreaderwriter git+https://git@github.com/onaio/valigetta.git@v0.3.1#egg=valigetta codetiming diff --git a/requirements/base.pip b/requirements/base.pip index de72bbd985..a8e77ed367 100644 --- a/requirements/base.pip +++ b/requirements/base.pip @@ -265,7 +265,7 @@ oauthlib==4.0.1 # -r requirements/base.in # django-oauth-toolkit # requests-oauthlib -ona-oidc @ git+https://github.com/onaio/ona-oidc.git@b768994524c9259c90cf0174b7fe8852c41a8973 +ona-oidc @ git+https://github.com/onaio/ona-oidc.git@d5b3618bee8c52a3275394a4903cd1a771b04c6c # via -r requirements/base.in openpyxl==3.1.5 # via diff --git a/requirements/dev.pip b/requirements/dev.pip index c1c3d493d2..f5116c4bc6 100644 --- a/requirements/dev.pip +++ b/requirements/dev.pip @@ -331,7 +331,7 @@ oauthlib==4.0.1 # -r requirements/base.in # django-oauth-toolkit # requests-oauthlib -ona-oidc @ git+https://github.com/onaio/ona-oidc.git@b768994524c9259c90cf0174b7fe8852c41a8973 +ona-oidc @ git+https://github.com/onaio/ona-oidc.git@d5b3618bee8c52a3275394a4903cd1a771b04c6c # via -r requirements/base.in openpyxl==3.1.5 # via From 96e220737a768f761e22699465b33dd83cb716f5 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 14:09:10 +0300 Subject: [PATCH 086/120] test: keep the callback traceback and an unhashed secret for HS256 --- onadata/apps/api/tests/viewsets/test_stepup_viewset.py | 9 ++++++--- onadata/apps/main/tests/test_stepup_oauth_gate.py | 7 +++++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_viewset.py b/onadata/apps/api/tests/viewsets/test_stepup_viewset.py index d0f8229733..17079654dd 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_viewset.py @@ -340,10 +340,13 @@ def test_an_error_report_hides_the_callback_code_and_state(self): force_authenticate(request, user=self.user) view = _FailingHookViewSet.as_view({"get": "callback"}) - with self.assertRaises(RuntimeError) as caught: + # Not assertRaises: it drops the traceback, and the report needs it. + try: view(request) - - error = caught.exception + except RuntimeError as raised: + error = raised + else: + self.fail("the context hook should raise") report = get_exception_reporter_class(request)( request, type(error), error, error.__traceback__ ).get_traceback_html() diff --git a/onadata/apps/main/tests/test_stepup_oauth_gate.py b/onadata/apps/main/tests/test_stepup_oauth_gate.py index 6e00758e1c..7d67bf30bd 100644 --- a/onadata/apps/main/tests/test_stepup_oauth_gate.py +++ b/onadata/apps/main/tests/test_stepup_oauth_gate.py @@ -377,9 +377,12 @@ def test_changing_any_other_gated_field_without_a_grant_is_refused(self): } for field, value in changes.items(): with self.subTest(field=field): - # HS256 is valid only for a confidential client. + # HS256 is valid only for a confidential client whose secret is + # not hashed, or the form refuses it before the gate. application = self._application( - user=self.user, client_type=application_model.CLIENT_CONFIDENTIAL + user=self.user, + client_type=application_model.CLIENT_CONFIDENTIAL, + hash_client_secret=field != "algorithm", ) stored = application_model.objects.values().get(pk=application.pk) self.assertNotEqual(stored[field], value) From 834fb6d3185d73dba71a7d4d80bdd5b1f2a50d90 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 14:35:16 +0300 Subject: [PATCH 087/120] test: show where an error report leaks the callback code --- onadata/apps/api/tests/viewsets/test_stepup_viewset.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_viewset.py b/onadata/apps/api/tests/viewsets/test_stepup_viewset.py index 17079654dd..db6d1022c0 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_viewset.py @@ -353,5 +353,7 @@ def test_an_error_report_hides_the_callback_code_and_state(self): self.assertIn("context hook failed", report) self.assertIn("verify_step_up_context", report) self.assertIn("********************", report) - self.assertNotIn(CALLBACK_CODE, report) - self.assertNotIn(self.state, report) + for secret in (CALLBACK_CODE, self.state): + at = report.find(secret) + # On failure, show where the report leaks it. + self.assertEqual(at, -1, report[max(0, at - 1500) : at + 100]) From 9b8bb12e8841fdf36454ccf8a5e4485098d3c1b5 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 14:55:11 +0300 Subject: [PATCH 088/120] chore: pin ona-oidc to 34074d3 --- requirements/base.in | 2 +- requirements/base.pip | 2 +- requirements/dev.pip | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/requirements/base.in b/requirements/base.in index 0af8845ecb..2cbb26fe25 100644 --- a/requirements/base.in +++ b/requirements/base.in @@ -30,7 +30,7 @@ git+https://github.com/onaio/floip-py.git@3c980eb184069ae7c3c9136b18441978237cd4 git+https://github.com/onaio/python-json2xlsclient.git@62b4645f7b4f2684421a13ce98da0331a9dd66a0#egg=python-json2xlsclient # Pinned at the step-up branch tip for stepup_grants, which the totp endpoints # import. Re-pin to a main SHA once onaio/ona-oidc#139 merges. -git+https://github.com/onaio/ona-oidc.git@d5b3618bee8c52a3275394a4903cd1a771b04c6c#egg=ona-oidc +git+https://github.com/onaio/ona-oidc.git@34074d3a2868b3c72f905aad63a6101b1603b2c3#egg=ona-oidc -e git+https://github.com/onaio/savreaderwriter.git@fix-pep-440-issues#egg=savreaderwriter git+https://git@github.com/onaio/valigetta.git@v0.3.1#egg=valigetta codetiming diff --git a/requirements/base.pip b/requirements/base.pip index a8e77ed367..e99e509bd5 100644 --- a/requirements/base.pip +++ b/requirements/base.pip @@ -265,7 +265,7 @@ oauthlib==4.0.1 # -r requirements/base.in # django-oauth-toolkit # requests-oauthlib -ona-oidc @ git+https://github.com/onaio/ona-oidc.git@d5b3618bee8c52a3275394a4903cd1a771b04c6c +ona-oidc @ git+https://github.com/onaio/ona-oidc.git@34074d3a2868b3c72f905aad63a6101b1603b2c3 # via -r requirements/base.in openpyxl==3.1.5 # via diff --git a/requirements/dev.pip b/requirements/dev.pip index f5116c4bc6..7c07bb3c98 100644 --- a/requirements/dev.pip +++ b/requirements/dev.pip @@ -331,7 +331,7 @@ oauthlib==4.0.1 # -r requirements/base.in # django-oauth-toolkit # requests-oauthlib -ona-oidc @ git+https://github.com/onaio/ona-oidc.git@d5b3618bee8c52a3275394a4903cd1a771b04c6c +ona-oidc @ git+https://github.com/onaio/ona-oidc.git@34074d3a2868b3c72f905aad63a6101b1603b2c3 # via -r requirements/base.in openpyxl==3.1.5 # via From 5d9ad5ed4b3f3a3cbdc6aed19ef955888969757d Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 17:21:52 +0300 Subject: [PATCH 089/120] fix: gate a media link to a form or dataview as publish-data --- docs/two_factor.rst | 6 +- .../viewsets/test_stepup_metadata_gates.py | 106 +++++++++++++++++- onadata/apps/api/viewsets/metadata_viewset.py | 49 ++++++-- 3 files changed, 151 insertions(+), 10 deletions(-) diff --git a/docs/two_factor.rst b/docs/two_factor.rst index 9e74e8a7af..c21f0bab32 100644 --- a/docs/two_factor.rst +++ b/docs/two_factor.rst @@ -351,7 +351,11 @@ Audience Action public; a move of a private form into a public project; a change or a deletion on ``/api/v1/metadata`` that turns on the - ``public_link`` of a form; a new dataview in a + ``public_link`` of a form; a new or changed + ``media`` row on ``/api/v1/metadata`` that links to + a form or dataview, because a user who can read + the media of the form can download the linked + data; a new dataview in a public project, or a change to the project, columns or query of a dataview there, over a form whose data is not public; a new merged dataset in a public diff --git a/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py index e46776ca7f..d5df1dbf1a 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py @@ -4,6 +4,9 @@ form, or says where TextIt posts submissions. """ +import os + +from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.db import connection from django.test.utils import CaptureQueriesContext, override_settings @@ -16,7 +19,7 @@ ) from onadata.apps.api.tools import add_user_to_team from onadata.apps.api.viewsets.metadata_viewset import MetaDataViewSet -from onadata.apps.logger.models import XForm +from onadata.apps.logger.models import DataView, XForm from onadata.apps.main.models import MetaData from onadata.libs.permissions import ( EditorMinorRole, @@ -308,6 +311,107 @@ def test_rewriting_an_on_link_is_not_challenged(self): self.assertTrue(MetaData.public_link(self.xform)) +@gating(GATE_PUBLISH_DATA) +class TestLinkedDatasetGate(MetaDataGateTestCase): + """A media row that links to a form or data view lets anyone who can read + the host form's media download that data, so it publishes the data.""" + + audience = GATE_PUBLISH_DATA + media_url = "https://example.com/data.csv" + + def setUp(self): + super().setUp() + self.link = f"xform {self.xform.pk} linked" + + def _media_values(self): + return set( + MetaData.objects.filter( + object_id=self.xform.pk, data_type="media" + ).values_list("data_value", flat=True) + ) + + def test_linking_a_form_is_challenged(self): + """The 401 names the audience and no link is stored.""" + response = self._create("media", self.link) + + self.assert_challenged(response) + self.assertNotIn(self.link, self._media_values()) + + def test_a_grant_links_the_form(self): + """With a grant the link is stored.""" + grant = self._grant() + + response = self._create("media", self.link, self._with_grant(grant)) + + self.assertEqual(response.status_code, 201, response.data) + self.assertIn(self.link, self._media_values()) + self.assert_spent(grant) + + def test_linking_a_data_view_is_challenged(self): + """A data view link serves the data of the view's form.""" + data_view = DataView.objects.create( + name="linked view", + xform=self.xform, + project=self.project, + columns=["name"], + ) + link = f"dataview {data_view.pk} linked" + + response = self._create("media", link) + + self.assert_challenged(response) + self.assertNotIn(link, self._media_values()) + + def test_a_media_file_is_not_challenged(self): + """An uploaded file serves no form's data.""" + self.assert_challenged(self._create("media", self.link)) + path = os.path.join( + settings.PROJECT_ROOT, + "apps", + "main", + "tests", + "fixtures", + "transportation", + "screenshot.png", + ) + + self._add_form_metadata(self.xform, "media", "screenshot.png", path) + + self.assertIn("screenshot.png", self._media_values()) + + def test_a_media_url_is_not_challenged(self): + """A URL row points elsewhere and serves no form's data.""" + self.assert_challenged(self._create("media", self.link)) + + response = self._create("media", self.media_url) + + self.assertEqual(response.status_code, 201, response.data) + self.assertIn(self.media_url, self._media_values()) + + def test_turning_a_url_row_into_a_link_is_challenged(self): + """A PATCH without the type reads the type the row already has.""" + MetaData.media_add_uri(self.xform, self.media_url) + row = MetaData.objects.get(data_type="media", data_value=self.media_url) + + response = self._update(row, {"data_value": self.link}, method="patch") + + self.assert_challenged(response) + row.refresh_from_db() + self.assertEqual(row.data_value, self.media_url) + + def test_rewriting_a_link_is_not_challenged(self): + """A row that already links to the form publishes nothing new.""" + response = self._create("media", self.link, self._with_grant(self._grant())) + self.assertEqual(response.status_code, 201, response.data) + row = MetaData.objects.get(pk=response.data["id"]) + + response = self._update(row, {"data_type": "media", "data_value": self.link}) + + self.assertEqual(response.status_code, 200, response.data) + row.refresh_from_db() + self.assertEqual(row.data_value, self.link) + + @gating(GATE_PUBLISH_DATA) class TestHiddenPublicLinkGate(MetaDataGateTestCase): """A form can have more than one public link row. The reader takes the diff --git a/onadata/apps/api/viewsets/metadata_viewset.py b/onadata/apps/api/viewsets/metadata_viewset.py index d873a45eaf..fc87b2929e 100644 --- a/onadata/apps/api/viewsets/metadata_viewset.py +++ b/onadata/apps/api/viewsets/metadata_viewset.py @@ -13,7 +13,12 @@ from onadata.apps.api.tools import get_media_file_response from onadata.apps.logger.models import XForm from onadata.apps.main.models.meta_data import MetaData, type_for_form -from onadata.libs.serializers.metadata_serializer import MetaDataSerializer +from onadata.libs.serializers.metadata_serializer import ( + DATAVIEW_TAG, + MEDIA_TYPE, + XFORM_TAG, + MetaDataSerializer, +) from onadata.libs import filters from onadata.libs.mixins.authenticate_header_mixin import AuthenticateHeaderMixin from onadata.libs.mixins.cache_control_mixin import CacheControlMixin @@ -68,6 +73,32 @@ def _introduces_admin_meta_perms(content_object, data_value): ) +def _linked_dataset(data_type, data_value): + """``(tag, pk)`` of the form or data view whose data a row holding + ``data_type`` and ``data_value`` serves, or None. + + Reads the value as the media download does. Anyone who can read the host + form's media can download that data, so a link publishes it.""" + if data_type != MEDIA_TYPE or not isinstance(data_value, str): + return None + parts = data_value.split() + tag = next( + (tag for tag in (DATAVIEW_TAG, XFORM_TAG) if data_value.startswith(tag)), + None, + ) + if tag is None or len(parts) < 2: + return None + return tag, parts[1] + + +def _change_links_dataset(row, data_type, data_value): + """Whether a change to ``row`` makes it link to data it did not link to.""" + linked = _linked_dataset(data_type, data_value) + return linked is not None and linked != _linked_dataset( + row.data_type, row.data_value + ) + + def _is_true(value): """Any spelling of true, not only the ``"True"`` a public link is stored as, so a value a reader might accept later is gated now.""" @@ -140,7 +171,7 @@ def _change_redirects_textit(row, data_type=None, data_value=None): def _write_changes( - content_object, data_type, data_value, turns_on_public_link, redirects_textit + content_object, data_type, data_value, publishes_data, redirects_textit ): """The ``(action, changed)`` pairs of a write of ``data_value`` as ``data_type`` on ``content_object``.""" @@ -150,7 +181,7 @@ def _write_changes( lambda: data_type == XFORM_META_PERMS and _introduces_admin_meta_perms(content_object, data_value), ), - (GATE_PUBLISH_DATA, turns_on_public_link), + (GATE_PUBLISH_DATA, publishes_data), (GATE_CHANGE_WEBHOOK, redirects_textit), ) @@ -191,8 +222,11 @@ def refusal_for(data): content_object, data_type, data_value, - lambda: data_type == PUBLIC_LINK - and _turns_on_public_link(content_object, data_value), + lambda: _linked_dataset(data_type, data_value) is not None + or ( + data_type == PUBLIC_LINK + and _turns_on_public_link(content_object, data_value) + ), lambda: data_type == TEXTIT and _changes_textit(content_object, data_value), ), @@ -215,9 +249,8 @@ def refusal_for(instance, validated_data): instance.content_object, data_type, data_value, - lambda: _change_turns_on_public_link( - instance, data_type, data_value - ), + lambda: _change_links_dataset(instance, data_type, data_value) + or _change_turns_on_public_link(instance, data_type, data_value), lambda: _change_redirects_textit(instance, data_type, data_value), ), ) From 6897ac8f09387a6fef22fda3616330ec4b0c1f2b Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 17:23:10 +0300 Subject: [PATCH 090/120] fix: refuse an XML replace that would turn off a form's encryption --- docs/two_factor.rst | 4 +- .../api/tests/viewsets/test_xform_viewset.py | 47 +++++++++++++++++++ onadata/libs/tests/utils/test_logger_tools.py | 46 +++++++++++++++++- onadata/libs/utils/logger_tools.py | 7 +++ 4 files changed, 102 insertions(+), 2 deletions(-) diff --git a/docs/two_factor.rst b/docs/two_factor.rst index c21f0bab32..510243ebbd 100644 --- a/docs/two_factor.rst +++ b/docs/two_factor.rst @@ -377,7 +377,9 @@ Audience Action to any of its fields except its name ``form-require-auth`` ``require_auth`` turned off on ``/api/v1/forms/{pk}`` ``disable-form-encryption`` the encryption of a form turned off with - ``enable_kms_encryption`` on ``/api/v1/forms/{pk}`` + ``enable_kms_encryption`` on ``/api/v1/forms/{pk}``. + A replacement of an encrypted form with an XML + form that has no public key gets **400**. ============================= ==================================================== The meta permissions of a form can turn an editor, data-entry or read-only diff --git a/onadata/apps/api/tests/viewsets/test_xform_viewset.py b/onadata/apps/api/tests/viewsets/test_xform_viewset.py index c8596f77ef..a26aaff380 100644 --- a/onadata/apps/api/tests/viewsets/test_xform_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_xform_viewset.py @@ -6438,6 +6438,53 @@ def test_update_managed_encrypted_xform(self): ).exists() ) + def test_xml_without_a_key_cannot_replace_a_managed_xml_form(self): + """The replacement would turn encryption off, so it gets a 400 that + names the encryption setting and the form stays encrypted.""" + path = os.path.join( + settings.PROJECT_ROOT, + "apps", + "main", + "tests", + "fixtures", + "transportation", + "transportation.xml", + ) + with HTTMock(enketo_mock): + with open(path, "rb") as xml_file: + request = self.factory.post( + "/", data={"xml_file": xml_file}, **self.extra + ) + response = XFormViewSet.as_view({"post": "create"})(request) + self.assertEqual(response.status_code, 201, response.data) + xform = XForm.objects.get(pk=response.data["formid"]) + self.assertFalse(xform.xls) + # Encrypting needs the json as a dict, as migration 0031 left it. + xform.json = xform.json_dict() + xform.public_key = "fake-public-key" + xform.is_managed = True + xform.save() + # A save puts the stored key back only while there are no + # submissions. + XForm.objects.filter(pk=xform.pk).update(num_of_submissions=1) + xform.refresh_from_db() + self.assertTrue(xform.encrypted) + version = xform.version + + with open(path, "rb") as xml_file: + request = self.factory.patch( + "/", data={"xml_file": xml_file}, **self.extra + ) + response = XFormViewSet.as_view({"patch": "partial_update"})( + request, pk=xform.pk + ) + + self.assertEqual(response.status_code, 400, response.data) + self.assertIn("encryption setting", response.data["text"]) + xform.refresh_from_db() + self.assertTrue(xform.encrypted) + self.assertEqual(xform.version, version) + class ExportAsyncTestCase(XFormViewSetBaseTestCase): """Tests for exporting form data asynchronously""" diff --git a/onadata/libs/tests/utils/test_logger_tools.py b/onadata/libs/tests/utils/test_logger_tools.py index f796bac142..67908fedcf 100644 --- a/onadata/libs/tests/utils/test_logger_tools.py +++ b/onadata/libs/tests/utils/test_logger_tools.py @@ -26,7 +26,7 @@ from onadata.apps.logger.models import Instance, InstanceHistory from onadata.apps.logger.models.kms import KMSKey from onadata.apps.logger.models.survey_type import SurveyType -from onadata.apps.logger.models.xform import XForm +from onadata.apps.logger.models.xform import XForm, XLSFormError from onadata.apps.logger.models.xform_version import XFormVersion from onadata.apps.logger.xform_instance_parser import AttachmentNameError from onadata.apps.main.tests.test_base import TestBase @@ -1686,6 +1686,50 @@ def test_replace_with_same_version_creates_new_xform_version(self): ).exists() ) + def _managed_encrypted_form_with_a_submission(self): + dd = self._publish() + xform = XForm.objects.get(pk=dd.pk) + self.assertFalse(xform.xls) + # Encrypting needs the json as a dict, as migration 0031 left it. + xform.json = xform.json_dict() + xform.public_key = "fake-public-key" + xform.is_managed = True + xform.save() + # A save puts the stored key back only while there are no submissions. + XForm.objects.filter(pk=xform.pk).update(num_of_submissions=1) + xform.refresh_from_db() + self.assertTrue(xform.encrypted) + self.assertIn("base64RsaPublicKey", xform.xml) + self.assertEqual(xform.num_of_submissions, 1) + return xform + + def test_xml_without_a_key_cannot_replace_an_encrypted_form(self): + """The replacement would turn encryption off, so it is refused and + the form is left as it was.""" + xform = self._managed_encrypted_form_with_a_submission() + version = xform.version + + with self.assertRaisesMessage(XLSFormError, "encryption setting"): + self._publish(id_string=xform.id_string) + + xform.refresh_from_db() + self.assertTrue(xform.encrypted) + self.assertEqual(xform.version, version) + self.assertIn("base64RsaPublicKey", xform.xml) + + def test_xml_with_a_key_replaces_an_encrypted_form(self): + """An XML form that carries a public key keeps the form encrypted.""" + xform = self._managed_encrypted_form_with_a_submission() + version = xform.version + xml_file = ContentFile(xform.xml.encode(), name="transportation.xml") + + publish_xml_form(xml_file, self.user, self.project, xform.id_string) + + xform.refresh_from_db() + self.assertNotEqual(xform.version, version) + self.assertTrue(xform.encrypted) + self.assertIn("base64RsaPublicKey", xform.xml) + class PublishXLSFormTestCase(TestBase): """Tests for publish_xls_form""" diff --git a/onadata/libs/utils/logger_tools.py b/onadata/libs/utils/logger_tools.py index 3326be3d08..2c16866096 100644 --- a/onadata/libs/utils/logger_tools.py +++ b/onadata/libs/utils/logger_tools.py @@ -1188,6 +1188,13 @@ def publish_xml_form(xml_file, user, project, id_string=None, created_by=None): dd = DataDictionary.objects.get( user=user, id_string=id_string, project=project, deleted_at__isnull=True ) + if dd.encrypted and not json.loads(form_json).get("public_key"): + raise XLSFormError( + _( + "This form is encrypted, and the XML form has no public key. " + "To turn off encryption, use the encryption setting of the form." + ) + ) new_version = xml_version if xml_version: new_version = dd.get_unique_version(xml_version) From 2c9e53424b76128fc526043c675e8ab4aade19d5 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 17:24:59 +0300 Subject: [PATCH 091/120] fix: gate a form move out of the account that holds its project --- docs/two_factor.rst | 6 +- .../viewsets/test_stepup_form_move_gates.py | 122 +++++++++++++++++- onadata/apps/api/viewsets/project_viewset.py | 3 +- onadata/apps/api/viewsets/xform_viewset.py | 8 +- onadata/libs/stepup/sharing.py | 9 ++ onadata/libs/tests/stepup/test_sharing.py | 39 ++++++ 6 files changed, 181 insertions(+), 6 deletions(-) diff --git a/docs/two_factor.rst b/docs/two_factor.rst index 510243ebbd..24f2fe1ba2 100644 --- a/docs/two_factor.rst +++ b/docs/two_factor.rst @@ -369,7 +369,11 @@ Audience Action ``owner`` or ``project`` on ``/api/v1/forms/{pk}``; a new merged dataset in the project of another account from a form; a new merged dataset from a form that - another account owns, or keeps in its project + another account owns, or keeps in its project. For + a form move, another account is one that does not + own the form or its current project. Thus, a move + out of an organisation project is gated, also if a + member owns the form ``authorize-oauth-app`` the approval of an OAuth application at ``/o/authorize/``; the approval of a device at ``/o/device-confirm/``; the registration of an diff --git a/onadata/apps/api/tests/viewsets/test_stepup_form_move_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_form_move_gates.py index 9af3ed8c03..20615ddb79 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_form_move_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_form_move_gates.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- """ -Tests for the step-up gate on moving a form whose meta permissions can make -the destination project's users its admins. +Tests for the step-up gates on moving a form whose meta permissions can make +the destination project's users its admins, and on moving a form out of the +account whose project holds it. """ from oidc.stepup_grants import issue_grant, spend_grant @@ -10,6 +11,7 @@ GateTestCase, ) from onadata.apps.api.viewsets.project_viewset import ProjectViewSet +from onadata.apps.logger.models import XForm from onadata.libs.permissions import EditorRole, ManagerRole, OwnerRole from onadata.libs.stepup.policy import GATE_SHARE_FORM_ADMIN, GATE_TRANSFER_PROJECT from onadata.libs.test_utils.stepup import ( @@ -142,3 +144,119 @@ def test_the_transfer_grant_alone_lets_the_move_through(self): self.assertEqual(self._project_of_the_form(), self.second_project) self.assertTrue(OwnerRole.user_has_role(self.alice, self.xform)) self.assertFalse(spend_grant(self.user.pk, GATE_TRANSFER_PROJECT, grant)) + + +@gating(GATE_TRANSFER_PROJECT) +class TestMoveFormOutOfAnAccountGate(GateTestCase): + """A form can sit in an organisation's project while a member owns it. + A move to the member's own project takes its data out of the + organisation, so a stolen session must not be able to do it.""" + + audience = GATE_TRANSFER_PROJECT + + def setUp(self): + super().setUp() + self._publish_xls_form_to_project() + self.own_project = self.project + self._org_create() + self.org_user = self.organization.user + self.org_url = f"http://testserver/api/v1/users/{self.org_user.username}" + self._project_create({"name": "org project", "owner": self.org_url}) + self.org_project = self.project + # A change to a form's project keeps the form's owner. + XForm.objects.filter(pk=self.xform.pk).update(project=self.org_project) + self.xform.refresh_from_db() + self.assertEqual(self.xform.user, self.user) + self.assertEqual(self.xform.project, self.org_project) + self.assertEqual(self.org_project.organization, self.org_user) + + def _move(self, project, headers=None): + view = ProjectViewSet.as_view({"post": "forms"}) + request = self.factory.post( + "/", + data={"formid": self.xform.pk}, + **{**self.extra, **(headers or {})}, + ) + return view(request, pk=project.pk) + + @staticmethod + def _project_url(project): + return f"http://testserver/api/v1/projects/{project.pk}" + + def _project_of_the_form(self): + self.xform.refresh_from_db() + return self.xform.project + + def _org_owns_the_form_and_another_project(self): + """Make the organisation own the form, and return a second project of + the organisation.""" + XForm.objects.filter(pk=self.xform.pk).update(user=self.org_user) + self.xform.refresh_from_db() + self.assertEqual(self.xform.user, self.org_user) + self._project_create({"name": "org closed", "owner": self.org_url}) + self.assertEqual(self.project.organization, self.org_user) + return self.project + + def test_moving_a_form_out_by_update_is_challenged(self): + """The 401 names the audience and the form stays in the + organisation.""" + response = self._patch_form({"project": self._project_url(self.own_project)}) + + self.assert_challenged(response) + self.assertEqual(self._project_of_the_form(), self.org_project) + + def test_a_grant_lets_the_update_move_the_form_out(self): + """With a grant the form moves to its owner's project.""" + grant = self._grant() + + response = self._patch_form( + {"project": self._project_url(self.own_project)}, + self._with_grant(grant), + ) + + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(self._project_of_the_form(), self.own_project) + self.assert_spent(grant) + + def test_moving_a_form_out_through_a_project_is_challenged(self): + """A move through ``/projects//forms`` is gated the same way.""" + response = self._move(self.own_project) + + self.assert_challenged(response) + self.assertEqual(self._project_of_the_form(), self.org_project) + + def test_a_grant_lets_a_project_take_the_form_out(self): + """With a grant the form moves to its owner's project.""" + grant = self._grant() + + response = self._move(self.own_project, self._with_grant(grant)) + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(self._project_of_the_form(), self.own_project) + self.assertEqual(self.xform.user, self.user) + self.assert_spent(grant) + + def test_moving_by_update_within_the_organisation_is_not_challenged(self): + """The organisation owns the form and both projects.""" + self.assert_challenged( + self._patch_form({"project": self._project_url(self.own_project)}) + ) + org_closed = self._org_owns_the_form_and_another_project() + + response = self._patch_form({"project": self._project_url(org_closed)}) + + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(self._project_of_the_form(), org_closed) + + def test_moving_through_a_project_within_the_organisation_is_not_challenged( + self, + ): + """The organisation owns the form and both projects.""" + self.assert_challenged(self._move(self.own_project)) + org_closed = self._org_owns_the_form_and_another_project() + + response = self._move(org_closed) + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(self._project_of_the_form(), org_closed) + self.assertEqual(self.xform.user, self.org_user) diff --git a/onadata/apps/api/viewsets/project_viewset.py b/onadata/apps/api/viewsets/project_viewset.py index 740b790f67..e728b3752a 100644 --- a/onadata/apps/api/viewsets/project_viewset.py +++ b/onadata/apps/api/viewsets/project_viewset.py @@ -69,6 +69,7 @@ grants_admin_role, holds_roles, move_appoints_admins, + moves_form_to_another_account, project_admin_roles_granted, ) from onadata.libs.utils.cache_tools import ( @@ -185,7 +186,7 @@ def _check_form_move(request, project, xform): permissions, re-applied after the move, can make the new project's users its owners or managers. Where transfers are gated, the transfer grant covers that.""" - transfers = project.organization != xform.user + transfers = moves_form_to_another_account(xform, project) def appoints_admins_not_covered_by_a_transfer(): if transfers and is_gated(GATE_TRANSFER_PROJECT): diff --git a/onadata/apps/api/viewsets/xform_viewset.py b/onadata/apps/api/viewsets/xform_viewset.py index bab595bff5..ce87fdeefe 100644 --- a/onadata/apps/api/viewsets/xform_viewset.py +++ b/onadata/apps/api/viewsets/xform_viewset.py @@ -89,7 +89,11 @@ gated_actions, is_gated, ) -from onadata.libs.stepup.sharing import admin_roles_granted, holds_roles +from onadata.libs.stepup.sharing import ( + admin_roles_granted, + holds_roles, + moves_form_to_another_account, +) from onadata.libs.utils.api_export_tools import ( _get_export_type, custom_response_handler, @@ -469,7 +473,7 @@ def _moves_to_another_account(xform, validated_data): owner = validated_data.get("user", xform.user) project = validated_data.get("project", xform.project) return owner != xform.user or ( - project != xform.project and project.organization != xform.user + project != xform.project and moves_form_to_another_account(xform, project) ) diff --git a/onadata/libs/stepup/sharing.py b/onadata/libs/stepup/sharing.py index 48636bb478..005888e2df 100644 --- a/onadata/libs/stepup/sharing.py +++ b/onadata/libs/stepup/sharing.py @@ -224,6 +224,15 @@ def move_appoints_admins(xform, project): ) +def moves_form_to_another_account(xform, project): + """Whether moving ``xform`` into ``project`` puts it in an account other + than its owner or the owner of its current project. + + A form can sit in a project of an account that does not own it. A move + into a project of its owner then takes the data out of the other account.""" + return {xform.user_id, xform.project.organization_id} != {project.organization_id} + + def _role_shared_with_member(members_team, project, user, role_name): if role_name == OwnerRole.name: return role_name diff --git a/onadata/libs/tests/stepup/test_sharing.py b/onadata/libs/tests/stepup/test_sharing.py index 2fbf920c50..430c848af0 100644 --- a/onadata/libs/tests/stepup/test_sharing.py +++ b/onadata/libs/tests/stepup/test_sharing.py @@ -1,6 +1,10 @@ # -*- coding: utf-8 -*- """Tests for onadata.libs.stepup.sharing.""" +from types import SimpleNamespace + +from django.test import SimpleTestCase + from onadata.apps.api.models.organization_profile import ( create_organization_team, get_organization_members_team, @@ -12,6 +16,7 @@ from onadata.libs.stepup.sharing import ( holds_roles, member_admin_roles, + moves_form_to_another_account, reapplying_appoints_admins, ) @@ -118,3 +123,37 @@ def test_an_editor_who_is_already_an_owner(self): OwnerRole.add(self.alice, self.xform) self.assertFalse(reapplying_appoints_admins([self.xform])) + + +class TestMovesFormToAnotherAccount(SimpleTestCase): + """``moves_form_to_another_account`` compares the destination's account + with the form's owner and with the account of its current project.""" + + @staticmethod + def _form(owner_id, project_owner_id): + return SimpleNamespace( + user_id=owner_id, + project=SimpleNamespace(organization_id=project_owner_id), + ) + + @staticmethod + def _project(owner_id): + return SimpleNamespace(organization_id=owner_id) + + def test_a_move_within_one_account(self): + """Owner, current project and destination share one account.""" + self.assertFalse( + moves_form_to_another_account(self._form(1, 1), self._project(1)) + ) + + def test_a_move_out_of_the_account_of_the_current_project(self): + """The destination is the owner's, but the current project is not.""" + self.assertTrue( + moves_form_to_another_account(self._form(1, 2), self._project(1)) + ) + + def test_a_move_away_from_the_owner(self): + """The destination belongs to neither the owner nor its project.""" + self.assertTrue( + moves_form_to_another_account(self._form(1, 1), self._project(2)) + ) From 9d8a71cee7a63865efb292ba2a2f6d40064fbe54 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 18:05:51 +0300 Subject: [PATCH 092/120] test: put the key in the XML of the encrypted form fixtures --- .../api/tests/viewsets/test_xform_viewset.py | 37 ++++++++++++------- onadata/libs/tests/utils/test_logger_tools.py | 27 +++++++++----- 2 files changed, 41 insertions(+), 23 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_xform_viewset.py b/onadata/apps/api/tests/viewsets/test_xform_viewset.py index a26aaff380..ddd5ccec29 100644 --- a/onadata/apps/api/tests/viewsets/test_xform_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_xform_viewset.py @@ -6450,25 +6450,34 @@ def test_xml_without_a_key_cannot_replace_a_managed_xml_form(self): "transportation", "transportation.xml", ) + with open(path, encoding="utf-8") as xml_file: + keyed_xml = xml_file.read().replace( + "", + '', + 1, + ) with HTTMock(enketo_mock): - with open(path, "rb") as xml_file: - request = self.factory.post( - "/", data={"xml_file": xml_file}, **self.extra - ) - response = XFormViewSet.as_view({"post": "create"})(request) + # The key goes in the XML. A save with ``public_key`` set and no + # submissions rebuilds the XML from an XLSForm, which this form + # lacks. + request = self.factory.post( + "/", + data={ + "xml_file": SimpleUploadedFile( + "transportation.xml", keyed_xml.encode() + ) + }, + **self.extra, + ) + response = XFormViewSet.as_view({"post": "create"})(request) self.assertEqual(response.status_code, 201, response.data) + XForm.objects.filter(pk=response.data["formid"]).update( + public_key="fake-public-key", is_managed=True, num_of_submissions=1 + ) xform = XForm.objects.get(pk=response.data["formid"]) self.assertFalse(xform.xls) - # Encrypting needs the json as a dict, as migration 0031 left it. - xform.json = xform.json_dict() - xform.public_key = "fake-public-key" - xform.is_managed = True - xform.save() - # A save puts the stored key back only while there are no - # submissions. - XForm.objects.filter(pk=xform.pk).update(num_of_submissions=1) - xform.refresh_from_db() self.assertTrue(xform.encrypted) + self.assertTrue(xform.is_managed) version = xform.version with open(path, "rb") as xml_file: diff --git a/onadata/libs/tests/utils/test_logger_tools.py b/onadata/libs/tests/utils/test_logger_tools.py index 67908fedcf..b8b7f3bc22 100644 --- a/onadata/libs/tests/utils/test_logger_tools.py +++ b/onadata/libs/tests/utils/test_logger_tools.py @@ -1687,18 +1687,27 @@ def test_replace_with_same_version_creates_new_xform_version(self): ) def _managed_encrypted_form_with_a_submission(self): - dd = self._publish() + """An XML form encrypted with a managed key, with one submission.""" + # The key goes in the XML. A save with ``public_key`` set and no + # submissions rebuilds the XML from an XLSForm, which this form lacks. + with open(self.xml_path, encoding="utf-8") as xml_file: + xml = xml_file.read().replace( + "", + '', + 1, + ) + dd = publish_xml_form( + ContentFile(xml.encode(), name="transportation.xml"), + self.user, + self.project, + ) + XForm.objects.filter(pk=dd.pk).update( + public_key="fake-public-key", is_managed=True, num_of_submissions=1 + ) xform = XForm.objects.get(pk=dd.pk) self.assertFalse(xform.xls) - # Encrypting needs the json as a dict, as migration 0031 left it. - xform.json = xform.json_dict() - xform.public_key = "fake-public-key" - xform.is_managed = True - xform.save() - # A save puts the stored key back only while there are no submissions. - XForm.objects.filter(pk=xform.pk).update(num_of_submissions=1) - xform.refresh_from_db() self.assertTrue(xform.encrypted) + self.assertTrue(xform.is_managed) self.assertIn("base64RsaPublicKey", xform.xml) self.assertEqual(xform.num_of_submissions, 1) return xform From 7637cdec960e20ae9d2069b4b89b6288b7a4e90f Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Wed, 2 Dec 2026 18:37:08 +0300 Subject: [PATCH 093/120] test: upload the keyed XML form as XML --- onadata/apps/api/tests/viewsets/test_xform_viewset.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/onadata/apps/api/tests/viewsets/test_xform_viewset.py b/onadata/apps/api/tests/viewsets/test_xform_viewset.py index ddd5ccec29..1c7b6f08f5 100644 --- a/onadata/apps/api/tests/viewsets/test_xform_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_xform_viewset.py @@ -6464,7 +6464,9 @@ def test_xml_without_a_key_cannot_replace_a_managed_xml_form(self): "/", data={ "xml_file": SimpleUploadedFile( - "transportation.xml", keyed_xml.encode() + "transportation.xml", + keyed_xml.encode(), + content_type="text/xml", ) }, **self.extra, From 1fde320602b9d0e5e356924aa7847ace84757761 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Thu, 3 Dec 2026 11:07:53 +0300 Subject: [PATCH 094/120] fix: address the fourth step-up review --- .../test_stepup_form_and_transfer_gates.py | 43 ++++++++- .../test_stepup_organization_gates.py | 40 +++++++- .../viewsets/test_stepup_sharing_gates.py | 80 +++++++++++++++- .../tests/viewsets/test_stepup_team_gates.py | 94 ++++++++++++++++++- .../api/tests/viewsets/test_totp_viewset.py | 20 ++++ onadata/apps/api/tools.py | 53 ++++++----- .../viewsets/organization_profile_viewset.py | 16 +++- onadata/apps/api/viewsets/project_viewset.py | 57 ++++++----- onadata/apps/api/viewsets/team_viewset.py | 40 ++++++-- onadata/apps/api/viewsets/totp_viewset.py | 22 +++-- .../organization_member_serializer.py | 5 +- 11 files changed, 398 insertions(+), 72 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py index 07b5f7f9b1..0f31149acd 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py @@ -11,7 +11,8 @@ from django.conf import settings from django.db import connection -from django.test.utils import CaptureQueriesContext +from django.shortcuts import get_object_or_404 +from django.test.utils import CaptureQueriesContext, override_settings from oidc.stepup_grants import spend_grant @@ -509,6 +510,46 @@ def test_an_invalid_move_keeps_the_grant(self): self.assertEqual(self.xform.project, self.private_project) self.assertFalse(self.xform.shared_data) + def _move_a_stale_public_copy(self, project): + """Move the form as loaded while public, after an unpublish commits. + The patch hands the move that loaded copy.""" + XForm.objects.filter(pk=self.xform.pk).update(shared=True, shared_data=True) + stale = XForm.objects.get(pk=self.xform.pk) + XForm.objects.filter(pk=self.xform.pk).update(shared=False, shared_data=False) + self.assertTrue(stale.shared_data) + + def load(model, **kwargs): + return stale if model is XForm else get_object_or_404(model, **kwargs) + + with patch("onadata.apps.api.tools.get_object_or_404", side_effect=load): + return self._move(project) + + def test_the_move_reads_the_form_on_the_locked_row(self): + """The check sees the form private, as it is once locked.""" + response = self._move_a_stale_public_copy(self.public_project) + + self.assert_challenged(response) + self._reload() + self.assertEqual(self.xform.project, self.private_project) + self.assertFalse(self.xform.shared) + self.assertFalse(self.xform.shared_data) + + @override_settings(STEP_UP={"MODE": "local", "ACTIONS": []}) + def test_a_move_writes_only_the_fields_it_changes(self): + """Where nothing is gated the form is not locked, so the save must + not write back the visibility of the loaded copy.""" + self._project_create({"name": "closed"}) + closed = self.project + self.assertFalse(closed.shared) + + response = self._move_a_stale_public_copy(closed) + + self.assertEqual(response.status_code, 201, response.data) + self._reload() + self.assertEqual(self.xform.project, closed) + self.assertFalse(self.xform.shared) + self.assertFalse(self.xform.shared_data) + def _patch_project(self, project, headers=None): url = f"http://testserver/api/v1/projects/{project.pk}" return self._patch_form({"project": url}, headers) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py index dec9efb17c..e9c3edf5c6 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py @@ -15,6 +15,7 @@ OrganizationProfile, get_organization_members_team, ) +from onadata.apps.api.tasks import share_project_async from onadata.apps.api.tools import get_organization_members from onadata.apps.api.viewsets.organization_profile_viewset import ( OrganizationProfileViewSet, @@ -28,6 +29,7 @@ EditorRole, ManagerRole, OwnerRole, + ReadOnlyRole, get_team_project_default_permissions, ) from onadata.libs.test_utils.stepup import ( @@ -300,8 +302,8 @@ def setUp(self): self.assertEqual(self.xform.user, self.organization.user) self.alice = self._create_user("alice", "alice", create_profile=True) - def _add_member(self, headers=None): - view = OrganizationProfileViewSet.as_view({"post": "members"}) + def _add_member(self, headers=None, viewset=OrganizationProfileViewSet): + view = viewset.as_view({"post": "members"}) request = self.factory.post( "/", data={"username": "alice", "role": "editor"}, @@ -362,6 +364,40 @@ def test_adding_a_member_who_holds_every_shared_role_is_not_challenged(self): self.assertEqual(response.status_code, 201) + def _re_add_and_downgrade_before_the_shares_run(self, viewset): + """Re-add alice once she owns the form. Patching ``delay`` holds back + the shares the request queues, so the downgrade commits first.""" + self._set_meta_perms(EDITOR_BECOMES_OWNER) + grant = issue_grant(self.user.pk, "share-team-admin") + self.assertEqual( + self._add_member({"HTTP_X_STEP_UP_GRANT": grant}).status_code, 201 + ) + self.assertTrue(self._alice_owns_the_form()) + + with patch.object(share_project_async, "delay") as queued: + response = self._add_member(viewset=viewset) + + self.assertEqual(response.status_code, 201) + self.assertTrue(queued.called) + ReadOnlyRole.add(self.alice, self.xform) + self.assertFalse(self._alice_owns_the_form()) + for call in queued.call_args_list: + share_project_async(*call.args, **call.kwargs) + + def test_a_waived_re_add_does_not_restore_a_revoked_role(self): + """The queued share checks the role again and writes nothing.""" + self._re_add_and_downgrade_before_the_shares_run(OrganizationProfileViewSet) + + self.assertFalse(self._alice_owns_the_form()) + self.assertTrue(ReadOnlyRole.user_has_role(self.alice, self.xform)) + + def test_a_waived_v2_re_add_does_not_restore_a_revoked_role(self): + """The v2 members route queues the same checked share.""" + self._re_add_and_downgrade_before_the_shares_run(OrganizationProfileViewSetV2) + + self.assertFalse(self._alice_owns_the_form()) + self.assertTrue(ReadOnlyRole.user_has_role(self.alice, self.xform)) + def test_joining_a_members_team_with_a_promoting_form_role_is_challenged(self): """A role the members team holds on a form, outside any project share, counts too once the form's meta permissions apply.""" diff --git a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py index 8941e71e3b..3169ec6f6c 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py @@ -21,10 +21,11 @@ from onadata.apps.api.models.organization_profile import create_organization_team from onadata.apps.api.tasks import share_project_async from onadata.apps.api.tools import add_user_to_team -from onadata.apps.api.viewsets.project_viewset import ProjectViewSet +from onadata.apps.api.viewsets.project_viewset import ProjectViewSet, _publishes_data from onadata.apps.api.viewsets.xform_viewset import XFormViewSet from onadata.apps.logger.models import EntityList, Project, ProjectInvitation, XForm from onadata.apps.logger.models.project import ProjectUserObjectPermission +from onadata.apps.main.tests.test_base import TestBase from onadata.libs.models.share_project import ShareProject from onadata.libs.models.share_xform import ShareXForm from onadata.libs.permissions import ( @@ -45,6 +46,7 @@ grants_admin_role, project_admin_roles_granted, ) +from onadata.libs.test_utils.lagging_replica import lagging_replica from onadata.libs.test_utils.stepup import ( EDITOR_BECOMES_MANAGER, EDITOR_BECOMES_OWNER, @@ -405,6 +407,23 @@ def test_lowering_an_invitation_is_not_challenged(self, _send): invitation.refresh_from_db() self.assertEqual(invitation.role, EditorRole.name) + def test_an_update_reads_the_status_on_the_locked_row(self, _send): + """A revocation can commit after the view loads the invitation. The + status check and the save use the row as it is once locked.""" + invitation = self._pending(ManagerRole.name) + stale = ProjectInvitation.objects.get(pk=invitation.pk) + ProjectInvitation.objects.filter(pk=invitation.pk).update( + status=ProjectInvitation.Status.REVOKED + ) + self.assertEqual(stale.status, ProjectInvitation.Status.PENDING) + + with patch(f"{PROJECT_VIEWSET}.get_object_or_404", return_value=stale): + response = self._update(stale, ManagerRole.name) + + self.assertEqual(response.status_code, 400, response.data) + invitation.refresh_from_db() + self.assertEqual(invitation.status, ProjectInvitation.Status.REVOKED) + def test_an_invalid_invitation_keeps_the_grant(self, _send): """Validation comes first, so a mistyped email does not spend it.""" self.assert_challenged(self._create(OwnerRole.name)) @@ -783,6 +802,31 @@ def test_an_invalid_update_keeps_the_grant(self): self.assertFalse(self.project.shared) +class TestPublishDataCheckReadsThePrimary(TestBase): + """The update makes the forms public on the primary, so the check that + gates it reads the primary too. A TransactionTestCase, as + ``lagging_replica`` needs.""" + + def setUp(self): + super().setUp() + self._publish_transportation_form() + Project.objects.filter(pk=self.xform.project_id).update(shared=True) + XForm.objects.filter(pk=self.xform.pk).update(shared=True, shared_data=True) + self.project = Project.objects.get(pk=self.xform.project_id) + + def test_a_form_made_private_on_the_primary_counts(self): + """The replica still shows the form public. Saving the public project + makes it public again, so the check must see it private.""" + with lagging_replica(): + XForm.objects.filter(pk=self.xform.pk).update(shared=False) + self.assertFalse( + XForm.objects.filter(pk=self.xform.pk, shared=False).exists() + ) + publishes = _publishes_data(self.project, {}) + + self.assertTrue(publishes) + + @gating(GATE_PUBLISH_DATA) class TestPublishFormDataGate(StepUpGateTestCase): """A public form's data is readable by anyone, so a stolen session must @@ -973,6 +1017,40 @@ def test_an_editor_share_kept_below_admin_is_not_challenged(self): self.assertTrue(EditorRole.user_has_role(self.alice, self.project)) self.assertFalse(ManagerRole.user_has_role(self.alice, self.xform)) + def _queue_an_editor_share_kept_below_admin(self): + """Share as editor while no form makes editors admins. Patching the + task holds the share back, and the call it got is returned.""" + self.assert_challenged(self._share(EditorRole.name)) + self._set_meta_perms(EDITOR_STAYS_BELOW_ADMIN) + with patch(SHARE_TASK) as task: + self.assertEqual(self._share(EditorRole.name).status_code, 204) + self.assertFalse(EditorRole.user_has_role(self.alice, self.project)) + return task.apply_async.call_args.kwargs + + @staticmethod + def _run(queued): + share_project_async(*queued["args"], **(queued["kwargs"] or {})) + + def test_a_queued_share_does_not_apply_meta_perms_set_after_the_check(self): + """Meta permissions that make editors managers can be set before the + queued share runs. The share then writes nothing.""" + queued = self._queue_an_editor_share_kept_below_admin() + self._set_meta_perms(EDITOR_BECOMES_MANAGER) + + self._run(queued) + + self.assertFalse(ManagerRole.user_has_role(self.alice, self.xform)) + self.assertFalse(EditorRole.user_has_role(self.alice, self.project)) + + def test_a_queued_share_still_applies_where_nothing_promotes_it(self): + """The repeat check passes a share that grants no admin role.""" + queued = self._queue_an_editor_share_kept_below_admin() + + self._run(queued) + + self.assertTrue(EditorRole.user_has_role(self.alice, self.project)) + self.assertFalse(ManagerRole.user_has_role(self.alice, self.xform)) + @gating( GATE_INVITE_PROJECT_ADMIN, diff --git a/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py index 90afe11ae0..794fb6d16a 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py @@ -11,8 +11,9 @@ from guardian.shortcuts import get_perms from oidc.stepup_grants import issue_grant, spend_grant +from onadata.apps.api.models import Team from onadata.apps.api.models.organization_profile import create_organization_team -from onadata.apps.api.tools import add_user_to_team +from onadata.apps.api.tools import add_user_to_team, remove_user_from_team from onadata.apps.api.viewsets.team_viewset import TeamViewSet from onadata.libs.models.share_team_project import ShareTeamProject from onadata.libs.permissions import ( @@ -548,3 +549,94 @@ def test_renaming_without_an_organisation_is_not_challenged(self): self.assertEqual(response.status_code, 200) self.assertEqual(self._team_org(), self.organization.user) + + +@gating("grant-org-admin") +class TestRenameTeamToOwnersGate(TeamGateTestCase): + """An organisation's owners are the members of its team with the Owners + name, so a rename to that name appoints them owners.""" + + def setUp(self): + super().setUp() + self.owners_name = self.owner_team.name + # Group names are unique, so the name is free only once Owners has + # another one. + Team.objects.filter(pk=self.owner_team.pk).update( + name=f"{self.owners_name} before" + ) + add_user_to_team(self.team, self.alice) + self.assertFalse(self.organization.is_organization_owner(self.alice)) + + def _rename(self, name, headers=None, organization=None): + view = TeamViewSet.as_view({"patch": "partial_update"}) + data = {"name": name} + if organization is not None: + data["organization"] = organization + request = self.factory.patch( + "/", + data=json.dumps(data), + content_type="application/json", + **{**self.extra, **(headers or {})}, + ) + return view(request, pk=self.team.pk) + + def _team_name(self): + self.team.refresh_from_db() + return self.team.name + + def test_renaming_a_team_with_members_to_owners_is_challenged(self): + """Without a grant, the rename answers 401 and makes no owner.""" + response = self._rename("Owners") + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "grant-org-admin") + self.assertNotEqual(self._team_name(), self.owners_name) + self.assertFalse(self.organization.is_organization_owner(self.alice)) + + def test_the_stored_form_of_the_owners_name_is_challenged(self): + """Team.save keeps a name that already starts with the organisation's + username, so this name is stored as it is.""" + response = self._rename(self.owners_name) + + self.assertEqual(response.status_code, 401) + self.assertEqual(response.data["audience"], "grant-org-admin") + self.assertFalse(self.organization.is_organization_owner(self.alice)) + + def test_a_grant_lets_the_rename_through(self): + """With a grant the team takes the name and its members are owners.""" + grant = issue_grant(self.user.pk, "grant-org-admin") + + response = self._rename("Owners", {"HTTP_X_STEP_UP_GRANT": grant}) + + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(self._team_name(), self.owners_name) + self.assertTrue(self.organization.is_organization_owner(self.alice)) + self.assertFalse(spend_grant(self.user.pk, "grant-org-admin", grant)) + + def test_renaming_an_empty_team_to_owners_is_not_challenged(self): + """Nobody becomes an owner, and joining the team later is gated.""" + self.assertEqual(self._rename("Owners").status_code, 401) + remove_user_from_team(self.team, self.alice) + self.assertFalse(self.team.user_set.exists()) + + response = self._rename("Owners") + + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(self._team_name(), self.owners_name) + + @gating("grant-org-admin", "share-team-admin") + def test_a_move_that_also_takes_the_owners_name_is_refused_whole(self): + """One grant cannot cover two gated changes.""" + home = self.organization + self._org_create({"org": "otherinc"}) + self.organization = home + + response = self._rename("Owners", organization="otherinc") + + self.assertEqual(response.status_code, 400, response.data) + self.assertEqual(response.data["error"], "one_gated_change_per_request") + self.assertCountEqual( + response.data["audiences"], ["grant-org-admin", "share-team-admin"] + ) + self.team.refresh_from_db() + self.assertEqual(self.team.organization, home.user) diff --git a/onadata/apps/api/tests/viewsets/test_totp_viewset.py b/onadata/apps/api/tests/viewsets/test_totp_viewset.py index 2664ea25f3..3470bf1423 100644 --- a/onadata/apps/api/tests/viewsets/test_totp_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_totp_viewset.py @@ -744,6 +744,26 @@ def test_verify_reports_a_cache_that_did_not_store_the_grant(self): self.assertEqual(response.status_code, 503) self.assertEqual(response.data, {"error": "step_up_unavailable"}) + def test_a_recovery_code_survives_a_grant_the_cache_did_not_store(self): + """The code is spent in the transaction that issues the grant, so a + cache fault rolls the spend back and the user can try again.""" + device = self._enroll() + with next_totp_window(): + codes = self._post_with_api_key( + "recovery_generate", {"code": current_code(device.key)} + ).data["codes"] + + with patch( + "onadata.apps.api.viewsets.totp_viewset.issue_grant", + side_effect=CacheWriteFailed("the cache did not store the grant"), + ): + failed = self._verify({"code": codes[0], "method": "recovery"}) + retried = self._verify({"code": codes[0], "method": "recovery"}) + + self.assertEqual(failed.status_code, 503) + self.assertEqual(retried.status_code, 200, retried.data) + self.assertTrue(retried.data["verified"]) + def test_verify_refuses_an_audience_the_deployment_does_not_know(self): """Omitted and mistyped are the same refusal, and neither costs a code. diff --git a/onadata/apps/api/tools.py b/onadata/apps/api/tools.py index 9cc5180960..2875615d4a 100644 --- a/onadata/apps/api/tools.py +++ b/onadata/apps/api/tools.py @@ -58,6 +58,7 @@ get_team_project_default_permissions, ) from onadata.libs.serializers.project_serializer import ProjectSerializer +from onadata.libs.stepup.drf import locked_for_gates from onadata.libs.utils.api_export_tools import ( custom_response_handler, get_entity_list_export_response, @@ -248,7 +249,7 @@ def remove_user_from_team(team, user): remove_perm(perm.codename, user, members_team) -def add_user_to_organization(organization, user, role=None): +def add_user_to_organization(organization, user, role=None, repeat_only=False): """Add a user to an organization Add user to organization and all projects in the organization @@ -256,6 +257,8 @@ def add_user_to_organization(organization, user, role=None): :param organization: OrganizationProfile instance :param user: User instance :param role: Role name + :param repeat_only: Queue each project share as ``repeat_only``, which + ``share_project_async`` describes :return: None """ @@ -286,10 +289,15 @@ def add_user_to_organization(organization, user, role=None): # Share all organization projects with the new user project_qs = organization.user.project_org.all() + def share(project, project_role): + api_tasks.share_project_async.delay( + project.pk, user.username, project_role, repeat_only=repeat_only + ) + if role == OwnerRole.name: # New owners have owner role on all projects for project in queryset_iterator(project_qs): - api_tasks.share_project_async.delay(project.pk, user.username, role) + share(project, role) else: # New members & managers gain default team permissions on projects @@ -297,12 +305,9 @@ def add_user_to_organization(organization, user, role=None): if role == ManagerRole.name and project.created_by == user: # New managers are only granted the manager role on the # projects they created - api_tasks.share_project_async.delay(project.pk, user.username, role) + share(project, role) else: - project_role = get_team_project_default_permissions(team, project) - api_tasks.share_project_async.delay( - project.pk, user.username, project_role - ) + share(project, get_team_project_default_permissions(team, project)) def get_organization_members(organization): @@ -476,21 +481,25 @@ def id_string_exists_in_account(): ) msg = "Form with the same id_string already exists in this account" - # Without this check, a user can't transfer a form to projects that - # he/she owns because `id_string_exists_in_account` will always - # return true - if project.organization != xform.user and id_string_exists_in_account(): - raise exceptions.ParseError(_(msg)) - if check_move: - check_move(xform) - xform.user = project.organization - xform.project = project - - try: - with transaction.atomic(): - xform.save() - except IntegrityError as e: - raise exceptions.ParseError(_(msg)) from e + with transaction.atomic(): + # Lock only the form row. lock_project_shares tells why a project + # row lock can deadlock. + xform = locked_for_gates(xform) + # Without this check, a user can't transfer a form to projects that + # he/she owns because `id_string_exists_in_account` will always + # return true + if project.organization != xform.user and id_string_exists_in_account(): + raise exceptions.ParseError(_(msg)) + if check_move: + check_move(xform) + xform.user = project.organization + xform.project = project + + try: + with transaction.atomic(): + xform.save(update_fields=["user", "project"]) + except IntegrityError as e: + raise exceptions.ParseError(_(msg)) from e # First assign permissions to the person who uploaded the form OwnerRole.add(request.user, xform) try: diff --git a/onadata/apps/api/viewsets/organization_profile_viewset.py b/onadata/apps/api/viewsets/organization_profile_viewset.py index b0b8d6d913..800cde0a35 100644 --- a/onadata/apps/api/viewsets/organization_profile_viewset.py +++ b/onadata/apps/api/viewsets/organization_profile_viewset.py @@ -160,7 +160,11 @@ def member_role_refusal(self, request, organization, validated_data): their own factor. Adding a member, even one already added, also shares every organisation project with them and puts them in the members team. That can make them an owner or manager of a project or form. One - grant covers both, under the first audience the deployment gates.""" + grant covers both, under the first audience the deployment gates. + + A member who already holds every role the shares grant needs no + grant. The shares are then marked ``repeat_only`` in + ``validated_data``, as for a project share.""" username = validated_data.get("username") if validated_data.get("remove") or not username: return None @@ -189,7 +193,11 @@ def appoints_project_or_form_admin(): (GATE_SHARE_TEAM_ADMIN, appoints_project_or_form_admin), ) ) - return self.check_step_up(request, gated[0]) if gated else None + if gated: + return self.check_step_up(request, gated[0]) + if is_gated(GATE_SHARE_TEAM_ADMIN): + validated_data["repeat_only"] = True + return None def update(self, request, *args, **kwargs): # pylint: disable=unused-argument """Update org in cache and db""" @@ -228,9 +236,7 @@ def members(self, request, *args, **kwargs): # the query string because clients cannot reliably send a DELETE body. # The body takes precedence so the username the permission check # authorized is the one acted on. - query_params = ( - request.query_params.dict() if request.method == "DELETE" else {} - ) + query_params = request.query_params.dict() if request.method == "DELETE" else {} data = merge_dicts( query_params, request.data, {"organization": organization.pk} ) diff --git a/onadata/apps/api/viewsets/project_viewset.py b/onadata/apps/api/viewsets/project_viewset.py index e728b3752a..21c7331edf 100644 --- a/onadata/apps/api/viewsets/project_viewset.py +++ b/onadata/apps/api/viewsets/project_viewset.py @@ -7,10 +7,12 @@ from django.contrib.auth import get_user_model from django.core.mail import send_mail +from django.db import transaction from django.http import Http404 from django.shortcuts import get_object_or_404 from django.utils.translation import gettext as _ +from multidb.pinning import use_master from rest_framework import status from rest_framework.decorators import action from rest_framework.response import Response @@ -56,6 +58,7 @@ XFormSerializer, ) from onadata.libs.stepup import RequiresStepUp +from onadata.libs.stepup.drf import locked from onadata.libs.stepup.gate import StepUpRefused, require_gated_change from onadata.libs.stepup.policy import ( GATE_INVITE_PROJECT_ADMIN, @@ -93,10 +96,14 @@ def _publishes_data(project, validated_data): """Saving a public project makes every private form in it public, data - included, whether or not ``public`` is what changed.""" + included, whether or not ``public`` is what changed. That write goes to + the primary, so the check reads the primary too.""" if not validated_data.get("shared", project.shared): return False - return not project.shared or project.xform_set.filter(shared=False).exists() + if not project.shared: + return True + with use_master: + return project.xform_set.filter(shared=False).exists() def _transfers(project, validated_data): @@ -300,11 +307,16 @@ def _share_admin_refusal(self, request, validated_data): permissions. A target who already holds the role needs no grant, and the share is then marked ``repeat_only`` in ``validated_data``. The task checks such a share again when it runs, in case a role was - revoked in between.""" + revoked in between. + + A share that grants no admin role is marked too. The task reads the + meta permissions again, and drops the share if they now make it + appoint an admin.""" if not is_gated(GATE_SHARE_PROJECT_ADMIN): return None granted = project_admin_roles_granted(self.object, validated_data["role"]) if not granted: + validated_data["repeat_only"] = True return None targets = User.objects.filter( username__in=validated_data["username"].split(",") @@ -442,22 +454,27 @@ def invitations(self, request, *args, **kwargs): return Response(serializer.data) if method == "PUT": - invitation_id = request.data.get("invitation_id") - try: - invitation = get_object_or_404( - ProjectInvitation, - pk=invitation_id, - project=project, - ) - except (ValueError, TypeError, OverflowError) as error: - raise Http404 from error - draft_request_data = self.request.data.copy() - draft_request_data["project"] = project.pk - data = draft_request_data - serializer = self.get_serializer( - invitation, - data=data, + return self._update_invitation(request, project) + + return Response(status=status.HTTP_204_NO_CONTENT) + + def _update_invitation(self, request, project): + """Update a pending invitation. The row stays locked from the status + check to the save, so a concurrent revocation is not undone.""" + invitation_id = request.data.get("invitation_id") + try: + invitation = get_object_or_404( + ProjectInvitation, + pk=invitation_id, + project=project, ) + except (ValueError, TypeError, OverflowError) as error: + raise Http404 from error + data = request.data.copy() + data["project"] = project.pk + with transaction.atomic(): + invitation = locked(invitation) + serializer = self.get_serializer(invitation, data=data) serializer.is_valid(raise_exception=True) serializer.check_can_save() refusal = self._invite_admin_refusal( @@ -466,9 +483,7 @@ def invitations(self, request, *args, **kwargs): if refusal is not None: return refusal serializer.save() - return Response(serializer.data) - - return Response(status=status.HTTP_204_NO_CONTENT) + return Response(serializer.data) @action(detail=True, methods=["POST"], url_path="revoke-invitation") def revoke_invitation(self, request, *args, **kwargs): diff --git a/onadata/apps/api/viewsets/team_viewset.py b/onadata/apps/api/viewsets/team_viewset.py index 6ef9aaa2b3..f831ce39d2 100644 --- a/onadata/apps/api/viewsets/team_viewset.py +++ b/onadata/apps/api/viewsets/team_viewset.py @@ -67,6 +67,18 @@ def _team_holds_role(team, project, role): ) +def _takes_the_owners_name(team, validated_data): + """Whether the update gives ``team``, which has members, the name of its + organisation's Owners team. The name is stored as ``Team.save`` stores + it, in the organisation the team ends up in.""" + organization = validated_data.get("organization") or team.organization + name = validated_data.get("team_name", team.name) + if not name.startswith(organization.username): + name = f"{organization.username}#{name}" + owners_name = f"{organization.username}#{Team.OWNER_TEAM_NAME}" + return name == owners_name and team.name != owners_name and team.user_set.exists() + + # pylint: disable=too-many-ancestors class TeamViewSet( AuthenticateHeaderMixin, @@ -136,21 +148,31 @@ def _share_admin_refusal(self, request, validated_data): return self.check_step_up(request, GATE_SHARE_TEAM_ADMIN) return None - def _move_refusal(self, request, team, validated_data): - """A moved team keeps its roles on the old organisation's projects and + def _update_refusal(self, request, team, validated_data): + """Refuse whichever gated change the update makes, or None. + + The members of a team with the Owners name are organisation owners. + A moved team keeps its roles on the old organisation's projects and forms, so moving it hands them to the new organisation's admins.""" organization = validated_data.get("organization") - if not is_gated(GATE_SHARE_TEAM_ADMIN) or organization in ( - None, - team.organization, - ): - return None - return self.check_step_up(request, GATE_SHARE_TEAM_ADMIN) + return self.gated_change_refusal( + request, + ( + ( + GATE_GRANT_ORG_ADMIN, + lambda: _takes_the_owners_name(team, validated_data), + ), + ( + GATE_SHARE_TEAM_ADMIN, + organization not in (None, team.organization), + ), + ), + ) def update(self, request, *args, **kwargs): return self.gated_update( request, - lambda team, data: self._move_refusal(request, team, data), + lambda team, data: self._update_refusal(request, team, data), partial=kwargs.pop("partial", False), ) diff --git a/onadata/apps/api/viewsets/totp_viewset.py b/onadata/apps/api/viewsets/totp_viewset.py index 5b1972631d..8b8c33b285 100644 --- a/onadata/apps/api/viewsets/totp_viewset.py +++ b/onadata/apps/api/viewsets/totp_viewset.py @@ -761,7 +761,19 @@ def verify(self, request): # pylint: disable=too-many-return-statements ) if not code: return _missing_code_response() - if not _verify_code(request.user, code, method): + # A cache fault raises out of the transaction, so the code is not + # spent and the user can try it again. + try: + with transaction.atomic(): + verified = _verify_code(request.user, code, method) + grant = issue_grant(request.user.pk, audience) if verified else None + except CacheWriteFailed: + logger.exception("step-up: the cache did not store the grant") + return Response( + {"error": STEP_UP_UNAVAILABLE}, + status=status.HTTP_503_SERVICE_UNAVAILABLE, + ) + if not verified: record_verification_failure( request, request.user, {"audience": audience, "method": method} ) @@ -771,12 +783,4 @@ def verify(self, request): # pylint: disable=too-many-return-statements status=status.HTTP_403_FORBIDDEN, ) clear_verification_failures(request.user) - try: - grant = issue_grant(request.user.pk, audience) - except CacheWriteFailed: - logger.exception("step-up: the cache did not store the grant") - return Response( - {"error": STEP_UP_UNAVAILABLE}, - status=status.HTTP_503_SERVICE_UNAVAILABLE, - ) return Response({"verified": True, "grant": grant}) diff --git a/onadata/libs/serializers/organization_member_serializer.py b/onadata/libs/serializers/organization_member_serializer.py index 95dc7ab950..4b66269230 100644 --- a/onadata/libs/serializers/organization_member_serializer.py +++ b/onadata/libs/serializers/organization_member_serializer.py @@ -118,6 +118,7 @@ def create(self, validated_data): "email_subject", SHARE_ORG_SUBJECT.format(username, organization.name) ) remove = validated_data.get("remove") + repeat_only = validated_data.get("repeat_only", False) if username: user = User.objects.get(username=username) @@ -126,7 +127,9 @@ def create(self, validated_data): remove_user_from_organization(organization, user) else: - add_user_to_organization(organization, user, role) + add_user_to_organization( + organization, user, role, repeat_only=repeat_only + ) if email_msg and email_subject and user.email: send_mail( From 542f03d2aaca4a84c3c6e1c562b76047f306659a Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Thu, 3 Dec 2026 11:07:54 +0300 Subject: [PATCH 095/120] feat: add autofill hints to the sign-up form --- onadata/apps/main/forms.py | 21 +++++++++++++++++---- onadata/apps/main/tests/test_forms.py | 22 +++++++++++++++++++++- 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/onadata/apps/main/forms.py b/onadata/apps/main/forms.py index 75f79a626c..73bb31b6c7 100644 --- a/onadata/apps/main/forms.py +++ b/onadata/apps/main/forms.py @@ -342,10 +342,14 @@ class UserProfileFormRegister(forms.Form): """ first_name = forms.CharField( - widget=forms.TextInput(), required=True, max_length=255 + widget=forms.TextInput(attrs={"autocomplete": "given-name"}), + required=True, + max_length=255, ) last_name = forms.CharField( - widget=forms.TextInput(), required=False, max_length=255 + widget=forms.TextInput(attrs={"autocomplete": "family-name"}), + required=False, + max_length=255, ) city = forms.CharField(widget=forms.TextInput(), required=False, max_length=255) country = forms.ChoiceField( @@ -384,8 +388,17 @@ class RegistrationFormUserProfile(RegistrationFormUniqueEmail, UserProfileFormRe """ RESERVED_USERNAMES = settings.RESERVED_USERNAMES - username = forms.CharField(widget=forms.TextInput(), max_length=30) - email = forms.EmailField(widget=forms.TextInput()) + username = forms.CharField( + widget=forms.TextInput( + attrs={ + "autocomplete": "username", + "autocapitalize": "none", + "spellcheck": "false", + } + ), + max_length=30, + ) + email = forms.EmailField(widget=forms.EmailInput(attrs={"autocomplete": "email"})) legal_usernames_re = re.compile(USERNAME_VALIDATION_REGEX) def clean_username(self): diff --git a/onadata/apps/main/tests/test_forms.py b/onadata/apps/main/tests/test_forms.py index 6a592e34e7..fc79f9e4c6 100644 --- a/onadata/apps/main/tests/test_forms.py +++ b/onadata/apps/main/tests/test_forms.py @@ -97,7 +97,27 @@ def test_returns_non_redirect_response(self, mock_get): class RegistrationFormUserProfileTestCase(TestCase): - """Tests for RegistrationFormUserProfile username validation.""" + """Tests for RegistrationFormUserProfile.""" + + def test_fields_carry_autofill_hints(self): + """Browsers and password managers fill the sign-up form from these.""" + form = RegistrationFormUserProfile() + expected = { + "email": {"type": "email", "autocomplete": "email"}, + "username": { + "autocomplete": "username", + "autocapitalize": "none", + "spellcheck": "false", + }, + "first_name": {"autocomplete": "given-name"}, + "last_name": {"autocomplete": "family-name"}, + } + + for name, attrs in expected.items(): + html = str(form[name]) + for attr, value in attrs.items(): + with self.subTest(field=name, attr=attr): + self.assertIn(f'{attr}="{value}"', html) def test_existing_username_case_insensitive(self): """Registration is rejected when the username already exists in a From 0653625dce990d8cb332c7968c1378e0fc57749b Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Thu, 3 Dec 2026 11:09:07 +0300 Subject: [PATCH 096/120] fix: lock the projects before the form on a move --- .../test_stepup_form_and_transfer_gates.py | 20 +++++++++++++++++++ onadata/apps/api/tools.py | 8 +++++--- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py index 0f31149acd..50dd9642ca 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py @@ -550,6 +550,26 @@ def test_a_move_writes_only_the_fields_it_changes(self): self.assertFalse(self.xform.shared) self.assertFalse(self.xform.shared_data) + def test_a_move_locks_both_projects_before_the_form(self): + """The form save writes the destination project's row. The move locks + the projects first, as an update does, so the two cannot deadlock.""" + self._project_create({"name": "closed"}) + closed = self.project + self.assertLess(self.private_project.pk, closed.pk) + + with CaptureQueriesContext(connection) as queries: + response = self._move(closed) + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual( + project_and_form_locks(queries), + [ + ("logger_project", self.private_project.pk), + ("logger_project", closed.pk), + ("logger_xform", self.xform.pk), + ], + ) + def _patch_project(self, project, headers=None): url = f"http://testserver/api/v1/projects/{project.pk}" return self._patch_form({"project": url}, headers) diff --git a/onadata/apps/api/tools.py b/onadata/apps/api/tools.py index 2875615d4a..04b9371137 100644 --- a/onadata/apps/api/tools.py +++ b/onadata/apps/api/tools.py @@ -58,7 +58,8 @@ get_team_project_default_permissions, ) from onadata.libs.serializers.project_serializer import ProjectSerializer -from onadata.libs.stepup.drf import locked_for_gates +from onadata.libs.stepup.drf import lock_projects, locked_for_gates +from onadata.libs.stepup.policy import gated_actions from onadata.libs.utils.api_export_tools import ( custom_response_handler, get_entity_list_export_response, @@ -482,8 +483,9 @@ def id_string_exists_in_account(): msg = "Form with the same id_string already exists in this account" with transaction.atomic(): - # Lock only the form row. lock_project_shares tells why a project - # row lock can deadlock. + # Lock the projects before the form, as lock_projects explains. + if gated_actions(): + lock_projects(xform.project_id, project.pk) xform = locked_for_gates(xform) # Without this check, a user can't transfer a form to projects that # he/she owns because `id_string_exists_in_account` will always From 4c90f1908e81f679c48702a9f39a83a742eb5ec3 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Thu, 3 Dec 2026 11:59:34 +0300 Subject: [PATCH 097/120] fix: address step-up review round 1 --- docs/two_factor.rst | 3 +- onadata/apps/api/tasks.py | 11 ++++--- .../tests/viewsets/test_project_viewset.py | 31 +++++++++++++++++-- .../test_stepup_form_and_transfer_gates.py | 16 ++++++++++ .../tests/viewsets/test_stepup_team_gates.py | 17 ++++++++++ onadata/apps/api/tools.py | 4 ++- onadata/apps/api/viewsets/team_viewset.py | 20 +++++++----- .../project_invitation_serializer.py | 9 +++++- 8 files changed, 94 insertions(+), 17 deletions(-) diff --git a/docs/two_factor.rst b/docs/two_factor.rst index 24f2fe1ba2..85a33de2ad 100644 --- a/docs/two_factor.rst +++ b/docs/two_factor.rst @@ -311,7 +311,8 @@ Audience Action ``grant-org-admin`` a change that makes a user an owner or manager on ``/api/v1/orgs/{org}/members`` or ``/api/v2/orgs/{org}/members``; a change that adds a user to the Owners team of the - organisation + organisation; a change on ``/api/v1/teams/{pk}`` that + gives a team with members the Owners name ``rotate-org-key`` ``POST /api/v1/orgs/{org}/rotate-key`` ``change-username`` a change to ``username`` on ``/api/v1/profiles/{username}`` ``change-webhook`` a new webhook on ``/api/v1/restservices``, or a change diff --git a/onadata/apps/api/tasks.py b/onadata/apps/api/tasks.py index 491dd977d8..9c3041ca5b 100644 --- a/onadata/apps/api/tasks.py +++ b/onadata/apps/api/tasks.py @@ -221,9 +221,10 @@ def regenerate_form_instance_json(xform_id: int): def share_project_async(project_id, username, role, remove=False, repeat_only=False): """Share project asynchronously. - ``repeat_only`` marks a share that was let through without a step-up - grant because the user already held every owner or manager role it - grants. It is skipped if one of those roles was revoked since.""" + ``repeat_only`` marks a share that the gate let through without a + step-up grant, because it gave the user no owner or manager role that + they lacked. The task skips it if it would now give one: a role was + revoked since, or a form's meta permissions now raise the role.""" try: project = Project.objects.get(pk=project_id) @@ -249,8 +250,8 @@ def _repeat_project_share(project, username, role): user, project_admin_roles_granted(project, role) ): logger.warning( - "Skipped a repeat share of project %s: the user no longer holds " - "the role it repeats.", + "Skipped a repeat share of project %s: it would give the user an " + "owner or manager role that they lack.", project.pk, ) return diff --git a/onadata/apps/api/tests/viewsets/test_project_viewset.py b/onadata/apps/api/tests/viewsets/test_project_viewset.py index 09a77f850d..7631cd437a 100644 --- a/onadata/apps/api/tests/viewsets/test_project_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_project_viewset.py @@ -3927,7 +3927,8 @@ def test_update(self, mock_send_mail): content_type="application/json", **self.extra, ) - response = self.view(request, pk=self.project.pk) + with self.captureOnCommitCallbacks(execute=True): + response = self.view(request, pk=self.project.pk) self.assertEqual(response.status_code, 200) self.invitation.refresh_from_db() self.assertEqual(self.invitation.email, "rihanna@example.com") @@ -3987,7 +3988,8 @@ def test_update_email_only(self, mock_send_mail): content_type="application/json", **self.extra, ) - response = self.view(request, pk=self.project.pk) + with self.captureOnCommitCallbacks(execute=True): + response = self.view(request, pk=self.project.pk) self.assertEqual(response.status_code, 200) self.invitation.refresh_from_db() self.assertEqual(self.invitation.email, "rihanna@example.com") @@ -4004,6 +4006,31 @@ def test_update_email_only(self, mock_send_mail): self.invitation.pk, "https://example.com/register" ) + def test_the_email_is_queued_after_the_commit(self, mock_send_mail): + """The task reads the email from the row, so it must not run before + the update that changes the email commits.""" + payload = { + "email": "rihanna@example.com", + "role": self.invitation.role, + "invitation_id": self.invitation.id, + } + request = self.factory.put( + "/", + data=json.dumps(payload), + content_type="application/json", + **self.extra, + ) + with self.captureOnCommitCallbacks() as callbacks: + response = self.view(request, pk=self.project.pk) + self.assertEqual(response.status_code, 200) + mock_send_mail.assert_not_called() + + self.assertEqual(len(callbacks), 1) + callbacks[0]() + mock_send_mail.assert_called_once_with( + self.invitation.pk, "https://example.com/register" + ) + def test_only_pending_allowed(self, mock_send_mail): """Only pending invitation can be updated""" for value, _ in ProjectInvitation.Status.choices: diff --git a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py index 50dd9642ca..d9400e7be9 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py @@ -550,6 +550,22 @@ def test_a_move_writes_only_the_fields_it_changes(self): self.assertFalse(self.xform.shared) self.assertFalse(self.xform.shared_data) + def test_the_move_reads_the_project_on_the_locked_row(self): + """The check sees the destination public, as it is once locked, not + as the view loaded it.""" + self._project_create({"name": "closed"}) + closed = self.project + stale = Project.objects.get(pk=closed.pk) + Project.objects.filter(pk=closed.pk).update(shared=True) + self.assertFalse(stale.shared) + + with patch.object(ProjectViewSet, "get_object", return_value=stale): + response = self._move(closed) + + self.assert_challenged(response) + self._reload() + self.assertEqual(self.xform.project, self.private_project) + def test_a_move_locks_both_projects_before_the_form(self): """The form save writes the destination project's row. The move locks the projects first, as an update does, so the two cannot deadlock.""" diff --git a/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py index 794fb6d16a..f8e2d97634 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py @@ -4,6 +4,7 @@ """ import json +from unittest.mock import patch from django.db import connection from django.test.utils import CaptureQueriesContext @@ -584,6 +585,22 @@ def _team_name(self): self.team.refresh_from_db() return self.team.name + def test_a_join_reads_the_team_from_the_locked_row(self): + """A join that loaded the team before a rename to the Owners name + committed checks the stored name. The rename locks the team row before + it checks the members, and the join holds the same lock.""" + carol = self._create_user("carol", "carol", create_profile=True) + stale = Team.objects.get(pk=self.team.pk) + Team.objects.filter(pk=self.team.pk).update(name=self.owners_name) + self.assertNotEqual(stale.name, self.owners_name) + + with patch.object(TeamViewSet, "get_object", return_value=stale): + response = self._members("post", self.team, username="carol") + + self.assertEqual(response.status_code, 401, response.data) + self.assertEqual(response.data["audience"], "grant-org-admin") + self.assertFalse(self._in_team(self.team, carol)) + def test_renaming_a_team_with_members_to_owners_is_challenged(self): """Without a grant, the rename answers 401 and makes no owner.""" response = self._rename("Owners") diff --git a/onadata/apps/api/tools.py b/onadata/apps/api/tools.py index 04b9371137..5ccd1f6df0 100644 --- a/onadata/apps/api/tools.py +++ b/onadata/apps/api/tools.py @@ -58,7 +58,7 @@ get_team_project_default_permissions, ) from onadata.libs.serializers.project_serializer import ProjectSerializer -from onadata.libs.stepup.drf import lock_projects, locked_for_gates +from onadata.libs.stepup.drf import lock_projects, locked, locked_for_gates from onadata.libs.stepup.policy import gated_actions from onadata.libs.utils.api_export_tools import ( custom_response_handler, @@ -484,8 +484,10 @@ def id_string_exists_in_account(): msg = "Form with the same id_string already exists in this account" with transaction.atomic(): # Lock the projects before the form, as lock_projects explains. + # check_move reads this project object, so read it again too. if gated_actions(): lock_projects(xform.project_id, project.pk) + locked(project) xform = locked_for_gates(xform) # Without this check, a user can't transfer a form to projects that # he/she owns because `id_string_exists_in_account` will always diff --git a/onadata/apps/api/viewsets/team_viewset.py b/onadata/apps/api/viewsets/team_viewset.py index f831ce39d2..3f05a2df21 100644 --- a/onadata/apps/api/viewsets/team_viewset.py +++ b/onadata/apps/api/viewsets/team_viewset.py @@ -5,6 +5,7 @@ from itertools import chain from django.contrib.auth import get_user_model +from django.db import transaction from django.utils.translation import gettext as _ from rest_framework import status @@ -38,6 +39,7 @@ ) from onadata.libs.serializers.team_serializer import TeamSerializer from onadata.libs.stepup import RequiresStepUp +from onadata.libs.stepup.drf import locked_for_gates from onadata.libs.stepup.gate import changed_gated_actions from onadata.libs.stepup.policy import ( GATE_GRANT_ORG_ADMIN, @@ -208,13 +210,17 @@ def members(self, request, *args, **kwargs): status_code = status.HTTP_400_BAD_REQUEST data["username"] = [_(f"User `{username}` does not exist.")] else: - refusal = self._join_refusal(request, team, user) - if refusal is not None: - return refusal - if request.method == "POST": - add_user_to_team(team, user) - elif request.method == "DELETE": - remove_user_from_team(team, user) + # A rename locks the team row before it checks the members, + # so a join that holds the same lock sees the stored name. + with transaction.atomic(): + team = locked_for_gates(team) + refusal = self._join_refusal(request, team, user) + if refusal is not None: + return refusal + if request.method == "POST": + add_user_to_team(team, user) + elif request.method == "DELETE": + remove_user_from_team(team, user) status_code = status.HTTP_201_CREATED else: status_code = status.HTTP_400_BAD_REQUEST diff --git a/onadata/libs/serializers/project_invitation_serializer.py b/onadata/libs/serializers/project_invitation_serializer.py index ddcbd4e67f..c1bba1ad8a 100644 --- a/onadata/libs/serializers/project_invitation_serializer.py +++ b/onadata/libs/serializers/project_invitation_serializer.py @@ -3,7 +3,10 @@ Project invitations serializer """ import re +from functools import partial + from django.conf import settings +from django.db import transaction from django.utils.translation import gettext as _ from django.contrib.auth import get_user_model from django.utils import timezone @@ -117,7 +120,11 @@ def update(self, instance, validated_data): updated_instance = super().update(instance, validated_data) if has_email_changed: - self._send_project_invitation_email(instance.id) + # The task reads the email from the row. An update can run in a + # transaction, so queue the task once the new email is committed. + transaction.on_commit( + partial(self._send_project_invitation_email, instance.id) + ) return updated_instance From fe20a81d44044cd04d9e8c2b48ef9562522df743 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Thu, 3 Dec 2026 12:08:50 +0300 Subject: [PATCH 098/120] fix: address step-up review round 2 --- .../tests/viewsets/test_project_viewset.py | 9 ++++-- .../test_stepup_organization_gates.py | 29 +++++++++++++++++ .../viewsets/test_stepup_sharing_gates.py | 22 +++++++------ .../viewsets/organization_profile_viewset.py | 20 ++++++++++++ onadata/apps/api/viewsets/team_viewset.py | 32 ++++++++++++------- .../v2/organization_profile_viewset.py | 1 + 6 files changed, 89 insertions(+), 24 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_project_viewset.py b/onadata/apps/api/tests/viewsets/test_project_viewset.py index 7631cd437a..df3c5bbee9 100644 --- a/onadata/apps/api/tests/viewsets/test_project_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_project_viewset.py @@ -3959,7 +3959,8 @@ def test_update_role_only(self, mock_send_mail): content_type="application/json", **self.extra, ) - response = self.view(request, pk=self.project.pk) + with self.captureOnCommitCallbacks(execute=True): + response = self.view(request, pk=self.project.pk) self.assertEqual(response.status_code, 200) self.invitation.refresh_from_db() self.assertEqual(self.invitation.role, "readonly") @@ -4102,7 +4103,8 @@ def test_malformed_invitation_id(self, mock_send_mail): content_type="application/json", **self.extra, ) - response = self.view(request, pk=self.project.pk) + with self.captureOnCommitCallbacks(execute=True): + response = self.view(request, pk=self.project.pk) self.assertEqual(response.status_code, 404) mock_send_mail.assert_not_called() @@ -4132,7 +4134,8 @@ def test_another_project_invitation(self, mock_send_mail): content_type="application/json", **self.extra, ) - response = self.view(request, pk=self.project.pk) + with self.captureOnCommitCallbacks(execute=True): + response = self.view(request, pk=self.project.pk) self.assertEqual(response.status_code, 404) alice_invitation.refresh_from_db() self.assertEqual(alice_invitation.project, alice_project) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py index e9c3edf5c6..d2bd4803b2 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py @@ -7,7 +7,9 @@ from unittest.mock import patch from django.contrib.contenttypes.models import ContentType +from django.db import connection from django.test import override_settings +from django.test.utils import CaptureQueriesContext from oidc.stepup_grants import issue_grant, spend_grant @@ -193,6 +195,33 @@ def test_a_grant_lets_the_owner_through(self): self.assertEqual(response.status_code, 201) self.assertTrue(OwnerRole.user_has_role(self.alice, self.organization)) + def test_a_member_change_locks_both_teams_before_it_writes(self): + """A team join locks its team row before it writes. A member change + locks the members and Owners teams first too, so the two cannot + deadlock.""" + grant = issue_grant(self.user.pk, "grant-org-admin") + + with CaptureQueriesContext(connection) as queries: + response = self._add_member("owner", {"HTTP_X_STEP_UP_GRANT": grant}) + + self.assertEqual(response.status_code, 201, response.data) + sql = [query["sql"] for query in queries.captured_queries] + team_lock = [ + i + for i, query in enumerate(sql) + if query.startswith("SELECT") + and "FOR UPDATE" in query + and "denoinc#members" in query + and "denoinc#Owners" in query + ] + first_join = next( + i + for i, query in enumerate(sql) + if query.startswith('INSERT INTO "auth_user_groups"') + ) + self.assertTrue(team_lock, "the member change locked no team row") + self.assertLess(team_lock[0], first_join) + def test_other_roles_are_not_challenged(self): """A new editor member needs no grant, but a new owner does.""" self.assertEqual(self._add_member("owner").status_code, 401) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py index 3169ec6f6c..9c4d37a6ae 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py @@ -489,12 +489,13 @@ def test_redirecting_to_an_existing_user_keeps_the_grant(self, send): self._update(invitation, ManagerRole.name, email="kim@example.com") ) - self._assert_refused_before_the_gate( - lambda headers: self._update( - invitation, ManagerRole.name, headers, email=alice.email - ), - "User already exists", - ) + with self.captureOnCommitCallbacks(execute=True): + self._assert_refused_before_the_gate( + lambda headers: self._update( + invitation, ManagerRole.name, headers, email=alice.email + ), + "User already exists", + ) invitation.refresh_from_db() self.assertEqual(invitation.email, "jane@example.com") @@ -510,10 +511,11 @@ def test_updating_an_accepted_invitation_keeps_the_grant(self, send): ) self.assert_challenged(self._create(OwnerRole.name, email="kim@example.com")) - self._assert_refused_before_the_gate( - lambda headers: self._update(invitation, OwnerRole.name, headers), - "Only pending invitations can be updated", - ) + with self.captureOnCommitCallbacks(execute=True): + self._assert_refused_before_the_gate( + lambda headers: self._update(invitation, OwnerRole.name, headers), + "Only pending invitations can be updated", + ) invitation.refresh_from_db() self.assertEqual(invitation.role, EditorRole.name) diff --git a/onadata/apps/api/viewsets/organization_profile_viewset.py b/onadata/apps/api/viewsets/organization_profile_viewset.py index 800cde0a35..e1a7b18ee1 100644 --- a/onadata/apps/api/viewsets/organization_profile_viewset.py +++ b/onadata/apps/api/viewsets/organization_profile_viewset.py @@ -18,6 +18,7 @@ from reversion.views import RevisionMixin from onadata.apps.api import permissions +from onadata.apps.api.models import Team from onadata.apps.api.models.organization_profile import ( OrganizationProfile, get_organization_members_team, @@ -53,6 +54,7 @@ GATE_REQUIRE_AUTH, GATE_ROTATE_ORG_KEY, GATE_SHARE_TEAM_ADMIN, + gated_actions, is_gated, ) from onadata.libs.stepup.sharing import ( @@ -66,6 +68,7 @@ safe_cache_get, safe_cache_set, ) +from onadata.libs.utils.common_tags import MEMBERS from onadata.libs.utils.common_tools import merge_dicts BaseViewset = get_baseviewset_class() @@ -153,6 +156,22 @@ def _require_auth_refusal(self, request, organization, validated_data): return None return self.check_step_up(request, GATE_REQUIRE_AUTH) + @staticmethod + def lock_member_teams(organization): + """Lock the rows of the members and Owners teams of ``organization``, in + primary key order, before a member change writes to them. A team join + locks its team row before it writes too, so the two cannot deadlock.""" + if not gated_actions(): + return + username = organization.user.username + names = (f"{username}#{MEMBERS}", f"{username}#{Team.OWNER_TEAM_NAME}") + list( + Team.objects.select_for_update() + .filter(name__in=names) + .order_by("pk") + .values_list("pk", flat=True) + ) + def member_role_refusal(self, request, organization, validated_data): """Refuse a member change that appoints an admin without a grant. @@ -260,6 +279,7 @@ def members(self, request, *args, **kwargs): ) if refusal is not None: return refusal + self.lock_member_teams(organization) serializer.save() data = self.serializer_class(organization, context={"request": request}).data diff --git a/onadata/apps/api/viewsets/team_viewset.py b/onadata/apps/api/viewsets/team_viewset.py index 3f05a2df21..22c1b71eab 100644 --- a/onadata/apps/api/viewsets/team_viewset.py +++ b/onadata/apps/api/viewsets/team_viewset.py @@ -2,6 +2,7 @@ """ The /teams API endpoint implementation. """ +from contextlib import nullcontext from itertools import chain from django.contrib.auth import get_user_model @@ -44,6 +45,7 @@ from onadata.libs.stepup.policy import ( GATE_GRANT_ORG_ADMIN, GATE_SHARE_TEAM_ADMIN, + gated_actions, is_gated, ) from onadata.libs.stepup.sharing import ( @@ -184,6 +186,22 @@ def destroy(self, request, *args, **kwargs): return super().destroy(request, *args, **kwargs) + def _change_membership(self, request, team, user): + """Add ``user`` to ``team`` or remove them, or return a refusal. + + Where an action is gated, a rename locks the team row before it checks + the members. A join holds the same lock, so it sees the stored name.""" + with transaction.atomic() if gated_actions() else nullcontext(): + team = locked_for_gates(team) + refusal = self._join_refusal(request, team, user) + if refusal is not None: + return refusal + if request.method == "POST": + add_user_to_team(team, user) + elif request.method == "DELETE": + remove_user_from_team(team, user) + return None + @action(methods=["DELETE", "GET", "POST"], detail=True) def members(self, request, *args, **kwargs): """ @@ -210,17 +228,9 @@ def members(self, request, *args, **kwargs): status_code = status.HTTP_400_BAD_REQUEST data["username"] = [_(f"User `{username}` does not exist.")] else: - # A rename locks the team row before it checks the members, - # so a join that holds the same lock sees the stored name. - with transaction.atomic(): - team = locked_for_gates(team) - refusal = self._join_refusal(request, team, user) - if refusal is not None: - return refusal - if request.method == "POST": - add_user_to_team(team, user) - elif request.method == "DELETE": - remove_user_from_team(team, user) + refusal = self._change_membership(request, team, user) + if refusal is not None: + return refusal status_code = status.HTTP_201_CREATED else: status_code = status.HTTP_400_BAD_REQUEST diff --git a/onadata/apps/api/viewsets/v2/organization_profile_viewset.py b/onadata/apps/api/viewsets/v2/organization_profile_viewset.py index 910ffab441..6b01d53809 100644 --- a/onadata/apps/api/viewsets/v2/organization_profile_viewset.py +++ b/onadata/apps/api/viewsets/v2/organization_profile_viewset.py @@ -163,6 +163,7 @@ def members(self, request, *args, **kwargs): ) if refusal is not None: return refusal + self.lock_member_teams(organization) serializer.save() if serializer.validated_data["remove"]: From 1e6a5f9c404bcca8abd51a61e5458e5bb352c21b Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Thu, 3 Dec 2026 12:13:58 +0300 Subject: [PATCH 099/120] fix: lock the member teams before the member check --- .../tests/viewsets/test_project_viewset.py | 3 +- .../test_stepup_organization_gates.py | 40 +++++++++++++++---- .../viewsets/organization_profile_viewset.py | 27 ++++++------- .../v2/organization_profile_viewset.py | 2 +- onadata/libs/stepup/drf.py | 9 ++++- 5 files changed, 56 insertions(+), 25 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_project_viewset.py b/onadata/apps/api/tests/viewsets/test_project_viewset.py index df3c5bbee9..923514a4d7 100644 --- a/onadata/apps/api/tests/viewsets/test_project_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_project_viewset.py @@ -4090,7 +4090,8 @@ def test_malformed_invitation_id(self, mock_send_mail): content_type="application/json", **self.extra, ) - response = self.view(request, pk=self.project.pk) + with self.captureOnCommitCallbacks(execute=True): + response = self.view(request, pk=self.project.pk) self.assertEqual(response.status_code, 404) # 1e999 cannot be produced by json.dumps; as a raw JSON literal it # parses to float infinity rather than failing JSON validation diff --git a/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py index d2bd4803b2..8ab4481efc 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py @@ -195,22 +195,46 @@ def test_a_grant_lets_the_owner_through(self): self.assertEqual(response.status_code, 201) self.assertTrue(OwnerRole.user_has_role(self.alice, self.organization)) - def test_a_member_change_locks_both_teams_before_it_writes(self): - """A team join locks its team row before it writes. A member change - locks the members and Owners teams first too, so the two cannot - deadlock.""" + def test_a_member_change_locks_both_teams_before_it_checks(self): + """A member change locks the members and Owners teams before the member + check, and so before it writes. A removal that runs at the same time + then commits before the check reads the members.""" + jane = self._create_user("jane", "jane", create_profile=True) + for username, viewset in ( + ("alice", OrganizationProfileViewSet), + (jane.username, OrganizationProfileViewSetV2), + ): + with self.subTest(viewset=viewset.__module__): + self._assert_teams_locked_before_the_check(username, viewset) + + def _assert_teams_locked_before_the_check(self, username, viewset): grant = issue_grant(self.user.pk, "grant-org-admin") + check = viewset.member_role_refusal + queries_at_check = [] with CaptureQueriesContext(connection) as queries: - response = self._add_member("owner", {"HTTP_X_STEP_UP_GRANT": grant}) + + def record(view, *args): + queries_at_check.append(len(queries.captured_queries)) + return check(view, *args) + + with patch.object( + viewset, "member_role_refusal", autospec=True, side_effect=record + ): + response = self._member_request( + "post", + "owner", + {"HTTP_X_STEP_UP_GRANT": grant}, + username=username, + viewset=viewset, + ) self.assertEqual(response.status_code, 201, response.data) sql = [query["sql"] for query in queries.captured_queries] team_lock = [ i for i, query in enumerate(sql) - if query.startswith("SELECT") - and "FOR UPDATE" in query + if "FOR UPDATE" in query and "denoinc#members" in query and "denoinc#Owners" in query ] @@ -220,6 +244,8 @@ def test_a_member_change_locks_both_teams_before_it_writes(self): if query.startswith('INSERT INTO "auth_user_groups"') ) self.assertTrue(team_lock, "the member change locked no team row") + self.assertEqual(len(queries_at_check), 1) + self.assertLess(team_lock[0], queries_at_check[0]) self.assertLess(team_lock[0], first_join) def test_other_roles_are_not_challenged(self): diff --git a/onadata/apps/api/viewsets/organization_profile_viewset.py b/onadata/apps/api/viewsets/organization_profile_viewset.py index e1a7b18ee1..381d73f8a5 100644 --- a/onadata/apps/api/viewsets/organization_profile_viewset.py +++ b/onadata/apps/api/viewsets/organization_profile_viewset.py @@ -48,6 +48,7 @@ RotateOrganizationKeySerializer, ) from onadata.libs.stepup import RequiresStepUp +from onadata.libs.stepup.drf import lock_rows from onadata.libs.stepup.gate import changed_gated_actions from onadata.libs.stepup.policy import ( GATE_GRANT_ORG_ADMIN, @@ -157,20 +158,16 @@ def _require_auth_refusal(self, request, organization, validated_data): return self.check_step_up(request, GATE_REQUIRE_AUTH) @staticmethod - def lock_member_teams(organization): - """Lock the rows of the members and Owners teams of ``organization``, in - primary key order, before a member change writes to them. A team join - locks its team row before it writes too, so the two cannot deadlock.""" - if not gated_actions(): - return - username = organization.user.username - names = (f"{username}#{MEMBERS}", f"{username}#{Team.OWNER_TEAM_NAME}") - list( - Team.objects.select_for_update() - .filter(name__in=names) - .order_by("pk") - .values_list("pk", flat=True) - ) + def _lock_member_teams(organization): + """Lock the members and Owners teams of ``organization`` where an action + is gated. Call it in a transaction, before the member check. + + A team join locks its team row before it checks and writes too. The + check then reads the stored members, and the two cannot deadlock.""" + if gated_actions(): + username = organization.user.username + names = (f"{username}#{MEMBERS}", f"{username}#{Team.OWNER_TEAM_NAME}") + lock_rows(Team, name__in=names) def member_role_refusal(self, request, organization, validated_data): """Refuse a member change that appoints an admin without a grant. @@ -274,12 +271,12 @@ def members(self, request, *args, **kwargs): if not serializer.is_valid(): return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) + self._lock_member_teams(organization) refusal = self.member_role_refusal( request, organization, serializer.validated_data ) if refusal is not None: return refusal - self.lock_member_teams(organization) serializer.save() data = self.serializer_class(organization, context={"request": request}).data diff --git a/onadata/apps/api/viewsets/v2/organization_profile_viewset.py b/onadata/apps/api/viewsets/v2/organization_profile_viewset.py index 6b01d53809..9456beb679 100644 --- a/onadata/apps/api/viewsets/v2/organization_profile_viewset.py +++ b/onadata/apps/api/viewsets/v2/organization_profile_viewset.py @@ -158,12 +158,12 @@ def members(self, request, *args, **kwargs): if request.method != "GET": serializer = self.get_serializer(data=request.data, context=context) serializer.is_valid(raise_exception=True) + self._lock_member_teams(organization) refusal = self.member_role_refusal( request, organization, serializer.validated_data ) if refusal is not None: return refusal - self.lock_member_teams(organization) serializer.save() if serializer.validated_data["remove"]: diff --git a/onadata/libs/stepup/drf.py b/onadata/libs/stepup/drf.py index 7b8831d48e..f6d50027f1 100644 --- a/onadata/libs/stepup/drf.py +++ b/onadata/libs/stepup/drf.py @@ -46,10 +46,17 @@ def locked_for_gates(instance): def lock_row(model, pk): """Lock the row of ``model`` with primary key ``pk`` until the transaction ends. Read no columns of it.""" + lock_rows(model, pk=pk) + + +def lock_rows(model, **lookups): + """Lock the rows of ``model`` that match ``lookups``, in primary key order, + until the transaction ends. Read no columns of them.""" # pylint: disable=protected-access list( model._base_manager.select_for_update() - .filter(pk=pk) + .filter(**lookups) + .order_by("pk") .values_list("pk", flat=True) ) From 3e388effd9839af4e819f4ddb14a8e5fe4a98811 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Thu, 3 Dec 2026 12:25:17 +0300 Subject: [PATCH 100/120] fix: read the primary in the member checks --- .../test_stepup_organization_gates.py | 85 ++++++++++++++----- .../tests/viewsets/test_stepup_team_gates.py | 44 ++++++++++ .../viewsets/organization_profile_viewset.py | 12 ++- onadata/apps/api/viewsets/team_viewset.py | 7 +- onadata/libs/stepup/drf.py | 3 +- onadata/libs/test_utils/stepup.py | 16 +++- onadata/libs/tests/stepup/test_drf.py | 4 +- 7 files changed, 140 insertions(+), 31 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py index 8ab4481efc..cfe63d29b1 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py @@ -11,6 +11,8 @@ from django.test import override_settings from django.test.utils import CaptureQueriesContext +from django_otp.plugins.otp_totp.models import TOTPDevice +from multidb.pinning import use_master from oidc.stepup_grants import issue_grant, spend_grant from onadata.apps.api.models.organization_profile import ( @@ -18,7 +20,10 @@ get_organization_members_team, ) from onadata.apps.api.tasks import share_project_async -from onadata.apps.api.tools import get_organization_members +from onadata.apps.api.tools import ( + get_organization_members, + remove_user_from_organization, +) from onadata.apps.api.viewsets.organization_profile_viewset import ( OrganizationProfileViewSet, ) @@ -26,6 +31,7 @@ OrganizationProfileViewSet as OrganizationProfileViewSetV2, ) from onadata.apps.logger.models.kms import KMSKey +from onadata.apps.main.tests.test_base import TestBase from onadata.libs.models.share_team_project import ShareTeamProject from onadata.libs.permissions import ( EditorRole, @@ -34,6 +40,7 @@ ReadOnlyRole, get_team_project_default_permissions, ) +from onadata.libs.test_utils.lagging_replica import lagging_replica from onadata.libs.test_utils.stepup import ( EDITOR_BECOMES_OWNER, StepUpGateTestCase, @@ -200,36 +207,38 @@ def test_a_member_change_locks_both_teams_before_it_checks(self): check, and so before it writes. A removal that runs at the same time then commits before the check reads the members.""" jane = self._create_user("jane", "jane", create_profile=True) - for username, viewset in ( - ("alice", OrganizationProfileViewSet), - (jane.username, OrganizationProfileViewSetV2), + for member, viewset in ( + (self.alice, OrganizationProfileViewSet), + (jane, OrganizationProfileViewSetV2), ): with self.subTest(viewset=viewset.__module__): - self._assert_teams_locked_before_the_check(username, viewset) + self._assert_teams_locked_before_the_check(member, viewset) - def _assert_teams_locked_before_the_check(self, username, viewset): + def _assert_teams_locked_before_the_check(self, member, viewset): + self.assertFalse(OwnerRole.user_has_role(member, self.organization)) grant = issue_grant(self.user.pk, "grant-org-admin") check = viewset.member_role_refusal queries_at_check = [] + queries = CaptureQueriesContext(connection) - with CaptureQueriesContext(connection) as queries: - - def record(view, *args): - queries_at_check.append(len(queries.captured_queries)) - return check(view, *args) + def record(view, *args): + queries_at_check.append(len(queries.captured_queries)) + return check(view, *args) - with patch.object( - viewset, "member_role_refusal", autospec=True, side_effect=record - ): - response = self._member_request( - "post", - "owner", - {"HTTP_X_STEP_UP_GRANT": grant}, - username=username, - viewset=viewset, - ) + with queries, patch.object( + viewset, "member_role_refusal", autospec=True, side_effect=record + ): + response = self._member_request( + "post", + "owner", + {"HTTP_X_STEP_UP_GRANT": grant}, + username=member.username, + viewset=viewset, + ) self.assertEqual(response.status_code, 201, response.data) + self.assertTrue(OwnerRole.user_has_role(member, self.organization)) + self.assertFalse(spend_grant(self.user.pk, "grant-org-admin", grant)) sql = [query["sql"] for query in queries.captured_queries] team_lock = [ i @@ -340,6 +349,40 @@ def test_a_grant_lets_the_owner_through_v2(self): self.assertTrue(OwnerRole.user_has_role(self.alice, self.organization)) +@gating("grant-org-admin") +class TestMemberCheckReadsThePrimary(TestBase): + """The member check runs after the member teams are locked on the + primary, so it reads the primary too. A TransactionTestCase, as + ``lagging_replica`` needs.""" + + def setUp(self): + super().setUp() + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + self.organization = self._create_organization("denoinc", "Dennis", self.user) + self.alice = self._create_user("alice", "alice", create_profile=True) + self._add_user_to_organization(self.organization, self.alice, OwnerRole.name) + self.assertTrue(OwnerRole.user_has_role(self.alice, self.organization)) + + def test_an_owner_removed_on_the_primary_is_challenged(self): + """The replica still shows alice as an owner. Adding her back as an + owner appoints one, so the check must see her removed.""" + request = self.factory.post("/") + request.user = self.user + + with lagging_replica(): + remove_user_from_organization(self.organization, self.alice) + self.assertTrue(OwnerRole.user_has_role(self.alice, self.organization)) + with use_master: + self.assertFalse(OwnerRole.user_has_role(self.alice, self.organization)) + refusal = OrganizationProfileViewSet().member_role_refusal( + request, self.organization, {"username": "alice", "role": "owner"} + ) + + self.assertIsNotNone(refusal) + self.assertEqual(refusal.status_code, 401) + self.assertEqual(refusal.data["audience"], "grant-org-admin") + + @gating("share-team-admin") class TestOrganisationMembersTeamGate(StepUpGateTestCase): """Adding a member shares every organisation project with them at the diff --git a/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py index f8e2d97634..fe52f20856 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py @@ -9,13 +9,16 @@ from django.db import connection from django.test.utils import CaptureQueriesContext +from django_otp.plugins.otp_totp.models import TOTPDevice from guardian.shortcuts import get_perms +from multidb.pinning import use_master from oidc.stepup_grants import issue_grant, spend_grant from onadata.apps.api.models import Team from onadata.apps.api.models.organization_profile import create_organization_team from onadata.apps.api.tools import add_user_to_team, remove_user_from_team from onadata.apps.api.viewsets.team_viewset import TeamViewSet +from onadata.apps.main.tests.test_base import TestBase from onadata.libs.models.share_team_project import ShareTeamProject from onadata.libs.permissions import ( ROLES, @@ -24,6 +27,7 @@ OwnerRole, ReadOnlyRole, ) +from onadata.libs.test_utils.lagging_replica import lagging_replica from onadata.libs.test_utils.stepup import ( StepUpGateTestCase, gating, @@ -231,6 +235,46 @@ def test_a_join_reads_the_team_when_a_join_is_gated(self): self.assertGreater(queries, 0) +@gating("grant-org-admin") +class TestJoinCheckReadsThePrimary(TestBase): + """The join check runs after the team row is locked on the primary, so it + reads the primary too. A TransactionTestCase, as ``lagging_replica`` + needs.""" + + def setUp(self): + super().setUp() + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + organization = self._create_organization("denoinc", "Dennis", self.user) + self.owners_team = Team.objects.get( + organization=organization.user, + name=f"denoinc#{Team.OWNER_TEAM_NAME}", + ) + self.alice = self._create_user("alice", "alice", create_profile=True) + self._add_user_to_organization(organization, self.alice, OwnerRole.name) + self.assertTrue(self._alice_is_an_owner()) + + def _alice_is_an_owner(self): + return self.owners_team.user_set.filter(pk=self.alice.pk).exists() + + def test_an_owner_removed_on_the_primary_is_challenged(self): + """The replica still shows alice in Owners. Adding her back makes her + an owner again, so the check must see her removed.""" + request = self.factory.post("/") + request.user = self.user + + with lagging_replica(): + remove_user_from_team(self.owners_team, self.alice) + self.assertTrue(self._alice_is_an_owner()) + with use_master: + self.assertFalse(self._alice_is_an_owner()) + # pylint: disable=protected-access + refusal = TeamViewSet()._join_refusal(request, self.owners_team, self.alice) + + self.assertIsNotNone(refusal) + self.assertEqual(refusal.status_code, 401) + self.assertEqual(refusal.data["audience"], "grant-org-admin") + + @gating("share-team-admin") class TestJoinAdminTeamGate(TeamGateTestCase): """A new member takes on every role the team holds, so adding someone to diff --git a/onadata/apps/api/viewsets/organization_profile_viewset.py b/onadata/apps/api/viewsets/organization_profile_viewset.py index 381d73f8a5..7144d66679 100644 --- a/onadata/apps/api/viewsets/organization_profile_viewset.py +++ b/onadata/apps/api/viewsets/organization_profile_viewset.py @@ -11,6 +11,7 @@ from django.contrib.auth import get_user_model from django.utils.module_loading import import_string +from multidb.pinning import use_master from rest_framework import status from rest_framework.decorators import action from rest_framework.response import Response @@ -162,13 +163,15 @@ def _lock_member_teams(organization): """Lock the members and Owners teams of ``organization`` where an action is gated. Call it in a transaction, before the member check. - A team join locks its team row before it checks and writes too. The - check then reads the stored members, and the two cannot deadlock.""" + A team join locks its team row before it checks and writes too, so the + two cannot deadlock. After the lock, the check reads the members that a + concurrent change committed.""" if gated_actions(): username = organization.user.username names = (f"{username}#{MEMBERS}", f"{username}#{Team.OWNER_TEAM_NAME}") lock_rows(Team, name__in=names) + @use_master def member_role_refusal(self, request, organization, validated_data): """Refuse a member change that appoints an admin without a grant. @@ -180,7 +183,10 @@ def member_role_refusal(self, request, organization, validated_data): A member who already holds every role the shares grant needs no grant. The shares are then marked ``repeat_only`` in - ``validated_data``, as for a project share.""" + ``validated_data``, as for a project share. + + The check reads the primary. A replica can lag behind a change that + ``_lock_member_teams`` waited for.""" username = validated_data.get("username") if validated_data.get("remove") or not username: return None diff --git a/onadata/apps/api/viewsets/team_viewset.py b/onadata/apps/api/viewsets/team_viewset.py index 22c1b71eab..0de2cedba0 100644 --- a/onadata/apps/api/viewsets/team_viewset.py +++ b/onadata/apps/api/viewsets/team_viewset.py @@ -9,6 +9,7 @@ from django.db import transaction from django.utils.translation import gettext as _ +from multidb.pinning import use_master from rest_framework import status from rest_framework.decorators import action from rest_framework.exceptions import PermissionDenied @@ -112,6 +113,7 @@ def _check_organization_admin(self, request, team): _("You must be an owner or manager of the organization.") ) + @use_master def _join_refusal(self, request, team, user): """Joining a team hands the new member every role the team holds. Joining the Owners team makes someone an organisation owner. Joining @@ -119,7 +121,10 @@ def _join_refusal(self, request, team, user): of it. The Owners team is both, and one grant covers it, under the first - audience the deployment gates.""" + audience the deployment gates. + + The check reads the primary, where ``_change_membership`` locks the + team.""" join_audiences = (GATE_GRANT_ORG_ADMIN, GATE_SHARE_TEAM_ADMIN) if request.method != "POST" or not any(map(is_gated, join_audiences)): return None diff --git a/onadata/libs/stepup/drf.py b/onadata/libs/stepup/drf.py index f6d50027f1..ecc1be19a0 100644 --- a/onadata/libs/stepup/drf.py +++ b/onadata/libs/stepup/drf.py @@ -68,8 +68,7 @@ def lock_projects(*project_pks): A form save updates its project's row, and a project update writes the rows of its forms. Lock a form's project before the form, so that two such writes cannot deadlock.""" - for pk in sorted(set(project_pks) - {None}): - lock_row(Project, pk) + lock_rows(Project, pk__in=set(project_pks) - {None}) def locked_form_for_gates(xform): diff --git a/onadata/libs/test_utils/stepup.py b/onadata/libs/test_utils/stepup.py index 7b1a5eee54..28e9a58e67 100644 --- a/onadata/libs/test_utils/stepup.py +++ b/onadata/libs/test_utils/stepup.py @@ -19,21 +19,31 @@ EDITOR_STAYS_BELOW_ADMIN = "editor-minor|dataentry-only|readonly" _PROJECT_OR_FORM_LOCK = re.compile( - r'FROM "(logger_project|logger_xform)" WHERE "\1"\."id" = (\d+) .*FOR UPDATE', + r'FROM "(logger_project|logger_xform)" WHERE "\1"\."id" ' + r'(?:= (\d+) |IN \(([\d, ]+)\) ORDER BY "\1"\."id" ASC ).*FOR UPDATE', re.S, ) +def _locked_pks(match): + if match[2]: + return [int(match[2])] + return sorted(int(pk) for pk in match[3].split(", ")) + + def project_and_form_locks(queries): """``(table, pk)`` for each project or form row that ``queries``, a - ``CaptureQueriesContext``, locked ``FOR UPDATE``, in order.""" + ``CaptureQueriesContext``, locked ``FOR UPDATE``, in order. + + A lock of several rows counts only if it orders them by primary key.""" return [ - (match[1], int(match[2])) + (match[1], pk) for match in ( _PROJECT_OR_FORM_LOCK.search(query["sql"]) for query in queries.captured_queries ) if match + for pk in _locked_pks(match) ] diff --git a/onadata/libs/tests/stepup/test_drf.py b/onadata/libs/tests/stepup/test_drf.py index f0c29ee20e..8f4d73ab53 100644 --- a/onadata/libs/tests/stepup/test_drf.py +++ b/onadata/libs/tests/stepup/test_drf.py @@ -296,10 +296,12 @@ class TestLockProjects(TestCase): """Tests for ``lock_projects``.""" def test_locks_each_project_once_in_primary_key_order(self): - """None is skipped, and a primary key given twice is locked once.""" + """One query locks them all. None is skipped, and a primary key given + twice is locked once.""" with transaction.atomic(), CaptureQueriesContext(connection) as queries: lock_projects(5, None, 2, 5) + self.assertEqual(len(queries), 1) self.assertEqual( project_and_form_locks(queries), [("logger_project", 2), ("logger_project", 5)], From 8f424dcb78d398be490a351f5871b4e887332fd5 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Thu, 3 Dec 2026 12:32:44 +0300 Subject: [PATCH 101/120] fix: match the positional order in the lock helper --- onadata/apps/api/tools.py | 6 +++--- onadata/libs/test_utils/stepup.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/onadata/apps/api/tools.py b/onadata/apps/api/tools.py index 5ccd1f6df0..d543810043 100644 --- a/onadata/apps/api/tools.py +++ b/onadata/apps/api/tools.py @@ -16,7 +16,7 @@ from django.core.files.storage import storages from django.core.files.uploadedfile import InMemoryUploadedFile from django.core.validators import URLValidator, ValidationError -from django.db import transaction +from django.db import DEFAULT_DB_ALIAS, transaction from django.db.models import Q from django.db.utils import IntegrityError from django.http import HttpResponseNotFound, HttpResponseRedirect @@ -58,7 +58,7 @@ get_team_project_default_permissions, ) from onadata.libs.serializers.project_serializer import ProjectSerializer -from onadata.libs.stepup.drf import lock_projects, locked, locked_for_gates +from onadata.libs.stepup.drf import lock_projects, locked_for_gates from onadata.libs.stepup.policy import gated_actions from onadata.libs.utils.api_export_tools import ( custom_response_handler, @@ -487,7 +487,7 @@ def id_string_exists_in_account(): # check_move reads this project object, so read it again too. if gated_actions(): lock_projects(xform.project_id, project.pk) - locked(project) + project.refresh_from_db(using=DEFAULT_DB_ALIAS) xform = locked_for_gates(xform) # Without this check, a user can't transfer a form to projects that # he/she owns because `id_string_exists_in_account` will always diff --git a/onadata/libs/test_utils/stepup.py b/onadata/libs/test_utils/stepup.py index 28e9a58e67..75c3156cd2 100644 --- a/onadata/libs/test_utils/stepup.py +++ b/onadata/libs/test_utils/stepup.py @@ -20,7 +20,7 @@ _PROJECT_OR_FORM_LOCK = re.compile( r'FROM "(logger_project|logger_xform)" WHERE "\1"\."id" ' - r'(?:= (\d+) |IN \(([\d, ]+)\) ORDER BY "\1"\."id" ASC ).*FOR UPDATE', + r'(?:= (\d+) |IN \(([\d, ]+)\) ORDER BY (?:1|"\1"\."id") ASC ).*FOR UPDATE', re.S, ) From fbdd749dd6e15ac44e2e467855ee34a44c6a90c3 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Thu, 3 Dec 2026 12:49:12 +0300 Subject: [PATCH 102/120] fix: read the primary in every gated section --- .../test_stepup_organization_gates.py | 43 +-- .../viewsets/test_stepup_primary_reads.py | 326 ++++++++++++++++++ .../tests/viewsets/test_stepup_team_gates.py | 44 --- onadata/apps/api/tools.py | 8 +- onadata/apps/api/viewsets/metadata_viewset.py | 4 +- .../viewsets/organization_profile_viewset.py | 24 +- onadata/apps/api/viewsets/team_viewset.py | 12 +- .../v2/organization_profile_viewset.py | 16 +- onadata/libs/stepup/drf.py | 49 ++- onadata/libs/tests/stepup/test_drf.py | 44 ++- 10 files changed, 437 insertions(+), 133 deletions(-) create mode 100644 onadata/apps/api/tests/viewsets/test_stepup_primary_reads.py diff --git a/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py index cfe63d29b1..ebcc729f38 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_organization_gates.py @@ -11,8 +11,6 @@ from django.test import override_settings from django.test.utils import CaptureQueriesContext -from django_otp.plugins.otp_totp.models import TOTPDevice -from multidb.pinning import use_master from oidc.stepup_grants import issue_grant, spend_grant from onadata.apps.api.models.organization_profile import ( @@ -20,10 +18,7 @@ get_organization_members_team, ) from onadata.apps.api.tasks import share_project_async -from onadata.apps.api.tools import ( - get_organization_members, - remove_user_from_organization, -) +from onadata.apps.api.tools import get_organization_members from onadata.apps.api.viewsets.organization_profile_viewset import ( OrganizationProfileViewSet, ) @@ -31,7 +26,6 @@ OrganizationProfileViewSet as OrganizationProfileViewSetV2, ) from onadata.apps.logger.models.kms import KMSKey -from onadata.apps.main.tests.test_base import TestBase from onadata.libs.models.share_team_project import ShareTeamProject from onadata.libs.permissions import ( EditorRole, @@ -40,7 +34,6 @@ ReadOnlyRole, get_team_project_default_permissions, ) -from onadata.libs.test_utils.lagging_replica import lagging_replica from onadata.libs.test_utils.stepup import ( EDITOR_BECOMES_OWNER, StepUpGateTestCase, @@ -349,40 +342,6 @@ def test_a_grant_lets_the_owner_through_v2(self): self.assertTrue(OwnerRole.user_has_role(self.alice, self.organization)) -@gating("grant-org-admin") -class TestMemberCheckReadsThePrimary(TestBase): - """The member check runs after the member teams are locked on the - primary, so it reads the primary too. A TransactionTestCase, as - ``lagging_replica`` needs.""" - - def setUp(self): - super().setUp() - TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) - self.organization = self._create_organization("denoinc", "Dennis", self.user) - self.alice = self._create_user("alice", "alice", create_profile=True) - self._add_user_to_organization(self.organization, self.alice, OwnerRole.name) - self.assertTrue(OwnerRole.user_has_role(self.alice, self.organization)) - - def test_an_owner_removed_on_the_primary_is_challenged(self): - """The replica still shows alice as an owner. Adding her back as an - owner appoints one, so the check must see her removed.""" - request = self.factory.post("/") - request.user = self.user - - with lagging_replica(): - remove_user_from_organization(self.organization, self.alice) - self.assertTrue(OwnerRole.user_has_role(self.alice, self.organization)) - with use_master: - self.assertFalse(OwnerRole.user_has_role(self.alice, self.organization)) - refusal = OrganizationProfileViewSet().member_role_refusal( - request, self.organization, {"username": "alice", "role": "owner"} - ) - - self.assertIsNotNone(refusal) - self.assertEqual(refusal.status_code, 401) - self.assertEqual(refusal.data["audience"], "grant-org-admin") - - @gating("share-team-admin") class TestOrganisationMembersTeamGate(StepUpGateTestCase): """Adding a member shares every organisation project with them at the diff --git a/onadata/apps/api/tests/viewsets/test_stepup_primary_reads.py b/onadata/apps/api/tests/viewsets/test_stepup_primary_reads.py new file mode 100644 index 0000000000..68ebc581b7 --- /dev/null +++ b/onadata/apps/api/tests/viewsets/test_stepup_primary_reads.py @@ -0,0 +1,326 @@ +# -*- coding: utf-8 -*- +""" +Tests that each gate reads the primary after its lock, through the route. + +In each test a change commits on the primary while the replica still shows the +state before it. A request with no grant then tries to undo or exploit it. +""" + +from django.contrib.auth import get_user_model + +from django_otp.plugins.otp_totp.models import TOTPDevice +from multidb.pinning import use_master +from rest_framework.test import APIRequestFactory + +from onadata.apps.api.models import Team +from onadata.apps.api.tools import ( + add_user_to_team, + create_organization_object, + remove_user_from_organization, + remove_user_from_team, +) +from onadata.apps.api.viewsets.metadata_viewset import MetaDataViewSet +from onadata.apps.api.viewsets.organization_profile_viewset import ( + OrganizationProfileViewSet, +) +from onadata.apps.api.viewsets.team_viewset import TeamViewSet +from onadata.apps.api.viewsets.user_profile_viewset import UserProfileViewSet +from onadata.apps.api.viewsets.v2.organization_profile_viewset import ( + OrganizationProfileViewSet as OrganizationProfileViewSetV2, +) +from onadata.apps.api.viewsets.xform_viewset import XFormViewSet +from onadata.apps.logger.models import Project, XForm +from onadata.apps.main.models import MetaData +from onadata.apps.main.tests.test_base import TestBase +from onadata.libs.permissions import OwnerRole +from onadata.libs.stepup.policy import ( + GATE_CHANGE_EMAIL, + GATE_CHANGE_WEBHOOK, + GATE_GRANT_ORG_ADMIN, + GATE_PUBLISH_DATA, + GATE_TRANSFER_PROJECT, +) +from onadata.libs.test_utils.lagging_replica import lagging_replica +from onadata.libs.test_utils.stepup import gating +from onadata.libs.utils.common_tags import TEXTIT + +User = get_user_model() + +TEXTIT_SETTINGS = "token|flow-uuid|contact-uuid" +OTHER_TEXTIT_SETTINGS = "other-token|flow-uuid|contact-uuid" + + +class PrimaryReadTestCase(TestBase): + """bob, with a confirmed factor, sends each request with no grant. A + TransactionTestCase, as ``lagging_replica`` needs.""" + + def setUp(self): + super().setUp() + TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) + self.factory = APIRequestFactory() + self.alice = self._create_user("alice", "alice", create_profile=True) + + def _send(self, viewset, method, action, data, **kwargs): + view = viewset.as_view({method: action}) + request = getattr(self.factory, method)( + "/", + data=data, + format="json", + HTTP_AUTHORIZATION=f"Token {self.user.auth_token}", + ) + return view(request, **kwargs) + + def assert_challenged(self, response, audience): + """Refused with a challenge for ``audience``.""" + self.assertEqual(response.status_code, 401, response.data) + self.assertEqual(response.data["audience"], audience) + + def _create_organization_of_bob(self): + """An organisation as the create route makes it, with bob as its + creator and a member of its Owners team.""" + organization = create_organization_object("denoinc", self.user, {}) + organization.save() + return organization + + +@gating(GATE_GRANT_ORG_ADMIN) +class TestMemberChecksReadThePrimary(PrimaryReadTestCase): + """alice is an owner until a test removes her on the primary. Adding her + back appoints an owner, so each check must see her removed.""" + + def setUp(self): + super().setUp() + self.organization = self._create_organization_of_bob() + self.owners_team = Team.objects.get( + organization=self.organization.user, + name=f"denoinc#{Team.OWNER_TEAM_NAME}", + ) + self._add_user_to_organization(self.organization, self.alice, OwnerRole.name) + self.assertTrue(self._alice_has_the_owner_role()) + self.assertTrue(self._alice_is_in_owners()) + + def _alice_has_the_owner_role(self): + return OwnerRole.user_has_role(self.alice, self.organization) + + def _alice_is_in_owners(self): + return self.owners_team.user_set.filter(pk=self.alice.pk).exists() + + def _add_alice_back_as_owner(self, viewset): + with lagging_replica(): + remove_user_from_organization(self.organization, self.alice) + self.assertTrue(self._alice_has_the_owner_role()) + with use_master: + self.assertFalse(self._alice_has_the_owner_role()) + response = self._send( + viewset, + "post", + "members", + {"username": "alice", "role": "owner"}, + user="denoinc", + ) + + self.assert_challenged(response, GATE_GRANT_ORG_ADMIN) + self.assertFalse(self._alice_has_the_owner_role()) + + def test_the_organisation_member_check_reads_the_primary(self): + """Depends on the gated section in the v1 member route.""" + self._add_alice_back_as_owner(OrganizationProfileViewSet) + + def test_the_v2_organisation_member_check_reads_the_primary(self): + """Depends on the gated section in the v2 member route.""" + self._add_alice_back_as_owner(OrganizationProfileViewSetV2) + + def test_the_team_join_check_reads_the_primary(self): + """Depends on the gated section in ``TeamViewSet._change_membership``.""" + with lagging_replica(): + remove_user_from_team(self.owners_team, self.alice) + self.assertTrue(self._alice_is_in_owners()) + with use_master: + self.assertFalse(self._alice_is_in_owners()) + response = self._send( + TeamViewSet, + "post", + "members", + {"username": "alice"}, + pk=self.owners_team.pk, + ) + + self.assert_challenged(response, GATE_GRANT_ORG_ADMIN) + self.assertFalse(self._alice_is_in_owners()) + + +@gating(GATE_GRANT_ORG_ADMIN) +class TestTeamRenameReadsThePrimary(PrimaryReadTestCase): + """A rename to the Owners name makes the team's members owners.""" + + def setUp(self): + super().setUp() + organization = self._create_organization_of_bob() + # Group names are unique, so the name is free only once Owners has + # another one. + Team.objects.filter( + organization=organization.user, name=f"denoinc#{Team.OWNER_TEAM_NAME}" + ).update(name="denoinc#Owners before") + self.team = Team.objects.create( + organization=organization.user, name="dreamteam", created_by=self.user + ) + self.assertFalse(self.team.user_set.exists()) + + def test_a_member_who_joined_on_the_primary_is_challenged(self): + """Depends on the gated section in ``gated_update``, which + ``_takes_the_owners_name`` runs in.""" + with lagging_replica(): + add_user_to_team(self.team, self.alice) + self.assertFalse(self.team.user_set.exists()) + with use_master: + self.assertTrue(self.team.user_set.exists()) + response = self._send( + TeamViewSet, + "patch", + "partial_update", + {"name": "Owners"}, + pk=self.team.pk, + ) + + self.assert_challenged(response, GATE_GRANT_ORG_ADMIN) + self.assertEqual(Team.objects.get(pk=self.team.pk).name, "denoinc#dreamteam") + + +class TestFormMoveReadsThePrimary(PrimaryReadTestCase): + """A form update that names a project checks that project as the lock + leaves it.""" + + def setUp(self): + super().setUp() + self._publish_transportation_form() + self.assertFalse(self.xform.shared or self.xform.shared_data) + self.target = Project.objects.create( + name="target", organization=self.user, created_by=self.user + ) + + def _move(self): + url = f"http://testserver/api/v1/projects/{self.target.pk}" + return self._send( + XFormViewSet, "patch", "partial_update", {"project": url}, pk=self.xform.pk + ) + + def assert_not_moved(self): + """The form is still in its project on the primary.""" + self.assertEqual( + XForm.objects.get(pk=self.xform.pk).project_id, self.xform.project_id + ) + + def _target(self): + return Project.objects.get(pk=self.target.pk) + + @gating(GATE_PUBLISH_DATA) + def test_a_project_made_public_on_the_primary_is_challenged(self): + """Depends on the gated section in ``gated_update``, which loads the + project and runs ``_moves_into_public_project``.""" + with lagging_replica(): + Project.objects.filter(pk=self.target.pk).update(shared=True) + self.assertFalse(self._target().shared) + with use_master: + self.assertTrue(self._target().shared) + response = self._move() + + self.assert_challenged(response, GATE_PUBLISH_DATA) + self.assert_not_moved() + + @gating(GATE_TRANSFER_PROJECT) + def test_a_project_moved_to_another_account_on_the_primary_is_challenged(self): + """Depends on the gated section in ``gated_update``, which loads the + project and runs ``_moves_to_another_account``.""" + with lagging_replica(): + Project.objects.filter(pk=self.target.pk).update(organization=self.alice) + self.assertEqual(self._target().organization, self.user) + with use_master: + self.assertEqual(self._target().organization, self.alice) + response = self._move() + + self.assert_challenged(response, GATE_TRANSFER_PROJECT) + self.assert_not_moved() + + +@gating(GATE_CHANGE_EMAIL) +class TestProfileReadsThePrimary(PrimaryReadTestCase): + """An email change through the profile route.""" + + def _email(self): + return User.objects.get(pk=self.user.pk).email + + def test_an_email_changed_on_the_primary_is_challenged(self): + """Writing back the old email moves password resets to it again. + Depends on the gated section in ``gated_update``, which runs + ``_changes_email``.""" + User.objects.filter(pk=self.user.pk).update(email="old@example.org") + + with lagging_replica(): + User.objects.filter(pk=self.user.pk).update(email="new@example.org") + self.assertEqual(self._email(), "old@example.org") + with use_master: + self.assertEqual(self._email(), "new@example.org") + response = self._send( + UserProfileViewSet, + "patch", + "partial_update", + {"email": "old@example.org", "password": self.login_password}, + user=self.user.username, + ) + + self.assert_challenged(response, GATE_CHANGE_EMAIL) + self.assertEqual(self._email(), "new@example.org") + + +class TestMetaDataReadsThePrimary(PrimaryReadTestCase): + """Metadata writes that a form's public link and TextIt settings gate.""" + + def setUp(self): + super().setUp() + self._publish_transportation_form() + + def _write(self, method, action, data_type, data_value, **kwargs): + data = { + "xform": self.xform.pk, + "data_type": data_type, + "data_value": data_value, + } + return self._send(MetaDataViewSet, method, action, data, **kwargs) + + @gating(GATE_PUBLISH_DATA) + def test_a_public_link_turned_off_on_the_primary_is_challenged(self): + """Depends on the gated section in ``gated_create``, which runs + ``_turns_on_public_link``.""" + MetaData.public_link(self.xform, True) + link = MetaData.objects.get(data_type="public_link") + + with lagging_replica(): + MetaData.objects.filter(pk=link.pk).update(data_value="False") + self.assertTrue(MetaData.public_link(self.xform)) + with use_master: + self.assertFalse(MetaData.public_link(self.xform)) + response = self._write("post", "create", "public_link", "True") + + self.assert_challenged(response, GATE_PUBLISH_DATA) + self.assertFalse(MetaData.public_link(self.xform)) + + @gating(GATE_CHANGE_WEBHOOK) + def test_textit_settings_changed_on_the_primary_are_challenged(self): + """Depends on the gated section in ``gated_update``, which runs + ``_change_redirects_textit``.""" + MetaData.textit(self.xform, data_value=TEXTIT_SETTINGS) + settings_row = MetaData.objects.get(data_type=TEXTIT) + + with lagging_replica(): + MetaData.objects.filter(pk=settings_row.pk).update( + data_value=OTHER_TEXTIT_SETTINGS + ) + self.assertEqual(MetaData.textit(self.xform), TEXTIT_SETTINGS) + with use_master: + self.assertEqual(MetaData.textit(self.xform), OTHER_TEXTIT_SETTINGS) + response = self._write( + "put", "update", TEXTIT, TEXTIT_SETTINGS, pk=settings_row.pk + ) + + self.assert_challenged(response, GATE_CHANGE_WEBHOOK) + self.assertEqual(MetaData.textit(self.xform), OTHER_TEXTIT_SETTINGS) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py index fe52f20856..f8e2d97634 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py @@ -9,16 +9,13 @@ from django.db import connection from django.test.utils import CaptureQueriesContext -from django_otp.plugins.otp_totp.models import TOTPDevice from guardian.shortcuts import get_perms -from multidb.pinning import use_master from oidc.stepup_grants import issue_grant, spend_grant from onadata.apps.api.models import Team from onadata.apps.api.models.organization_profile import create_organization_team from onadata.apps.api.tools import add_user_to_team, remove_user_from_team from onadata.apps.api.viewsets.team_viewset import TeamViewSet -from onadata.apps.main.tests.test_base import TestBase from onadata.libs.models.share_team_project import ShareTeamProject from onadata.libs.permissions import ( ROLES, @@ -27,7 +24,6 @@ OwnerRole, ReadOnlyRole, ) -from onadata.libs.test_utils.lagging_replica import lagging_replica from onadata.libs.test_utils.stepup import ( StepUpGateTestCase, gating, @@ -235,46 +231,6 @@ def test_a_join_reads_the_team_when_a_join_is_gated(self): self.assertGreater(queries, 0) -@gating("grant-org-admin") -class TestJoinCheckReadsThePrimary(TestBase): - """The join check runs after the team row is locked on the primary, so it - reads the primary too. A TransactionTestCase, as ``lagging_replica`` - needs.""" - - def setUp(self): - super().setUp() - TOTPDevice.objects.create(user=self.user, name="default", confirmed=True) - organization = self._create_organization("denoinc", "Dennis", self.user) - self.owners_team = Team.objects.get( - organization=organization.user, - name=f"denoinc#{Team.OWNER_TEAM_NAME}", - ) - self.alice = self._create_user("alice", "alice", create_profile=True) - self._add_user_to_organization(organization, self.alice, OwnerRole.name) - self.assertTrue(self._alice_is_an_owner()) - - def _alice_is_an_owner(self): - return self.owners_team.user_set.filter(pk=self.alice.pk).exists() - - def test_an_owner_removed_on_the_primary_is_challenged(self): - """The replica still shows alice in Owners. Adding her back makes her - an owner again, so the check must see her removed.""" - request = self.factory.post("/") - request.user = self.user - - with lagging_replica(): - remove_user_from_team(self.owners_team, self.alice) - self.assertTrue(self._alice_is_an_owner()) - with use_master: - self.assertFalse(self._alice_is_an_owner()) - # pylint: disable=protected-access - refusal = TeamViewSet()._join_refusal(request, self.owners_team, self.alice) - - self.assertIsNotNone(refusal) - self.assertEqual(refusal.status_code, 401) - self.assertEqual(refusal.data["audience"], "grant-org-admin") - - @gating("share-team-admin") class TestJoinAdminTeamGate(TeamGateTestCase): """A new member takes on every role the team holds, so adding someone to diff --git a/onadata/apps/api/tools.py b/onadata/apps/api/tools.py index d543810043..23d738f737 100644 --- a/onadata/apps/api/tools.py +++ b/onadata/apps/api/tools.py @@ -16,7 +16,7 @@ from django.core.files.storage import storages from django.core.files.uploadedfile import InMemoryUploadedFile from django.core.validators import URLValidator, ValidationError -from django.db import DEFAULT_DB_ALIAS, transaction +from django.db import transaction from django.db.models import Q from django.db.utils import IntegrityError from django.http import HttpResponseNotFound, HttpResponseRedirect @@ -58,7 +58,7 @@ get_team_project_default_permissions, ) from onadata.libs.serializers.project_serializer import ProjectSerializer -from onadata.libs.stepup.drf import lock_projects, locked_for_gates +from onadata.libs.stepup.drf import gated_section, lock_projects, locked_for_gates from onadata.libs.stepup.policy import gated_actions from onadata.libs.utils.api_export_tools import ( custom_response_handler, @@ -482,12 +482,12 @@ def id_string_exists_in_account(): ) msg = "Form with the same id_string already exists in this account" - with transaction.atomic(): + with transaction.atomic(), gated_section(atomic=False): # Lock the projects before the form, as lock_projects explains. # check_move reads this project object, so read it again too. if gated_actions(): lock_projects(xform.project_id, project.pk) - project.refresh_from_db(using=DEFAULT_DB_ALIAS) + project.refresh_from_db() xform = locked_for_gates(xform) # Without this check, a user can't transfer a form to projects that # he/she owns because `id_string_exists_in_account` will always diff --git a/onadata/apps/api/viewsets/metadata_viewset.py b/onadata/apps/api/viewsets/metadata_viewset.py index fc87b2929e..d3ab47f23f 100644 --- a/onadata/apps/api/viewsets/metadata_viewset.py +++ b/onadata/apps/api/viewsets/metadata_viewset.py @@ -30,7 +30,7 @@ from onadata.apps.api.tools import get_baseviewset_class from onadata.libs.data import strtobool from onadata.libs.stepup import RequiresStepUp -from onadata.libs.stepup.drf import lock_projects, lock_row, locked +from onadata.libs.stepup.drf import gated_section, lock_projects, lock_row, locked from onadata.libs.stepup.policy import ( ADMIN_ROLE_NAMES, GATE_CHANGE_WEBHOOK, @@ -262,7 +262,7 @@ def refusal_for(instance, validated_data): def destroy(self, request, *args, **kwargs): """A removed row can uncover another public link or TextIt row of the form.""" - with transaction.atomic(): + with transaction.atomic(), gated_section(atomic=False): instance = locked(self.get_object()) _lock_parent(instance.content_object, instance.data_type) refusal = self.gated_change_refusal( diff --git a/onadata/apps/api/viewsets/organization_profile_viewset.py b/onadata/apps/api/viewsets/organization_profile_viewset.py index 7144d66679..8df39c82df 100644 --- a/onadata/apps/api/viewsets/organization_profile_viewset.py +++ b/onadata/apps/api/viewsets/organization_profile_viewset.py @@ -11,7 +11,6 @@ from django.contrib.auth import get_user_model from django.utils.module_loading import import_string -from multidb.pinning import use_master from rest_framework import status from rest_framework.decorators import action from rest_framework.response import Response @@ -49,7 +48,7 @@ RotateOrganizationKeySerializer, ) from onadata.libs.stepup import RequiresStepUp -from onadata.libs.stepup.drf import lock_rows +from onadata.libs.stepup.drf import gated_section, lock_rows from onadata.libs.stepup.gate import changed_gated_actions from onadata.libs.stepup.policy import ( GATE_GRANT_ORG_ADMIN, @@ -161,7 +160,7 @@ def _require_auth_refusal(self, request, organization, validated_data): @staticmethod def _lock_member_teams(organization): """Lock the members and Owners teams of ``organization`` where an action - is gated. Call it in a transaction, before the member check. + is gated. Call it in a gated section, before the member check. A team join locks its team row before it checks and writes too, so the two cannot deadlock. After the lock, the check reads the members that a @@ -171,7 +170,6 @@ def _lock_member_teams(organization): names = (f"{username}#{MEMBERS}", f"{username}#{Team.OWNER_TEAM_NAME}") lock_rows(Team, name__in=names) - @use_master def member_role_refusal(self, request, organization, validated_data): """Refuse a member change that appoints an admin without a grant. @@ -185,8 +183,7 @@ def member_role_refusal(self, request, organization, validated_data): grant. The shares are then marked ``repeat_only`` in ``validated_data``, as for a project share. - The check reads the primary. A replica can lag behind a change that - ``_lock_member_teams`` waited for.""" + Call it in a gated section, after ``_lock_member_teams``.""" username = validated_data.get("username") if validated_data.get("remove") or not username: return None @@ -277,13 +274,14 @@ def members(self, request, *args, **kwargs): if not serializer.is_valid(): return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) - self._lock_member_teams(organization) - refusal = self.member_role_refusal( - request, organization, serializer.validated_data - ) - if refusal is not None: - return refusal - serializer.save() + with gated_section(): + self._lock_member_teams(organization) + refusal = self.member_role_refusal( + request, organization, serializer.validated_data + ) + if refusal is not None: + return refusal + serializer.save() data = self.serializer_class(organization, context={"request": request}).data # pylint: disable=attribute-defined-outside-init diff --git a/onadata/apps/api/viewsets/team_viewset.py b/onadata/apps/api/viewsets/team_viewset.py index 0de2cedba0..b8e87e0830 100644 --- a/onadata/apps/api/viewsets/team_viewset.py +++ b/onadata/apps/api/viewsets/team_viewset.py @@ -2,14 +2,11 @@ """ The /teams API endpoint implementation. """ -from contextlib import nullcontext from itertools import chain from django.contrib.auth import get_user_model -from django.db import transaction from django.utils.translation import gettext as _ -from multidb.pinning import use_master from rest_framework import status from rest_framework.decorators import action from rest_framework.exceptions import PermissionDenied @@ -41,12 +38,11 @@ ) from onadata.libs.serializers.team_serializer import TeamSerializer from onadata.libs.stepup import RequiresStepUp -from onadata.libs.stepup.drf import locked_for_gates +from onadata.libs.stepup.drf import gated_section, locked_for_gates from onadata.libs.stepup.gate import changed_gated_actions from onadata.libs.stepup.policy import ( GATE_GRANT_ORG_ADMIN, GATE_SHARE_TEAM_ADMIN, - gated_actions, is_gated, ) from onadata.libs.stepup.sharing import ( @@ -113,7 +109,6 @@ def _check_organization_admin(self, request, team): _("You must be an owner or manager of the organization.") ) - @use_master def _join_refusal(self, request, team, user): """Joining a team hands the new member every role the team holds. Joining the Owners team makes someone an organisation owner. Joining @@ -123,8 +118,7 @@ def _join_refusal(self, request, team, user): The Owners team is both, and one grant covers it, under the first audience the deployment gates. - The check reads the primary, where ``_change_membership`` locks the - team.""" + Call it in a gated section, after the team row is locked.""" join_audiences = (GATE_GRANT_ORG_ADMIN, GATE_SHARE_TEAM_ADMIN) if request.method != "POST" or not any(map(is_gated, join_audiences)): return None @@ -196,7 +190,7 @@ def _change_membership(self, request, team, user): Where an action is gated, a rename locks the team row before it checks the members. A join holds the same lock, so it sees the stored name.""" - with transaction.atomic() if gated_actions() else nullcontext(): + with gated_section(): team = locked_for_gates(team) refusal = self._join_refusal(request, team, user) if refusal is not None: diff --git a/onadata/apps/api/viewsets/v2/organization_profile_viewset.py b/onadata/apps/api/viewsets/v2/organization_profile_viewset.py index 9456beb679..0b723354fe 100644 --- a/onadata/apps/api/viewsets/v2/organization_profile_viewset.py +++ b/onadata/apps/api/viewsets/v2/organization_profile_viewset.py @@ -33,6 +33,7 @@ OrganizationPrivateSerializer, OrganizationSerializer, ) +from onadata.libs.stepup.drf import gated_section from onadata.libs.utils.cache_tools import safe_cache_get, safe_cache_set # pylint: disable=invalid-name @@ -158,13 +159,14 @@ def members(self, request, *args, **kwargs): if request.method != "GET": serializer = self.get_serializer(data=request.data, context=context) serializer.is_valid(raise_exception=True) - self._lock_member_teams(organization) - refusal = self.member_role_refusal( - request, organization, serializer.validated_data - ) - if refusal is not None: - return refusal - serializer.save() + with gated_section(): + self._lock_member_teams(organization) + refusal = self.member_role_refusal( + request, organization, serializer.validated_data + ) + if refusal is not None: + return refusal + serializer.save() if serializer.validated_data["remove"]: return Response(status=status.HTTP_204_NO_CONTENT) diff --git a/onadata/libs/stepup/drf.py b/onadata/libs/stepup/drf.py index ecc1be19a0..747dd6aaf3 100644 --- a/onadata/libs/stepup/drf.py +++ b/onadata/libs/stepup/drf.py @@ -1,10 +1,11 @@ # -*- coding: utf-8 -*- """Viewset mixin turning a policy decision into a step-up challenge.""" -from contextlib import nullcontext +from contextlib import contextmanager, nullcontext from django.db import transaction +from multidb.pinning import pin_this_thread, this_thread_is_pinned, unpin_this_thread from rest_framework import status from rest_framework.response import Response @@ -23,6 +24,30 @@ from onadata.libs.stepup.policy import gated_actions +@contextmanager +def gated_section(atomic=True): + """Where the deployment gates any action, pin reads to the primary and, + with ``atomic``, open a transaction. Elsewhere, do nothing. + + A gate locks rows on the primary, then checks them. A replica can lag + behind a change that the lock waited for, so the check reads the primary. + + The section restores the pin itself. ``use_master`` keeps one saved state + per thread, so a ``use_master`` inside it would leave the thread pinned. + """ + if not gated_actions(): + yield + return + was_pinned = this_thread_is_pinned() + pin_this_thread() + try: + with transaction.atomic() if atomic else nullcontext(): + yield + finally: + if not was_pinned: + unpin_this_thread() + + def locked(instance): """``instance``, locked and read again from its row. @@ -123,7 +148,7 @@ def step_up_refusal(self, request, reason, audiences): def _locked_for_update(self, request, instance): """``instance`` as ``locked_for_gates`` returns it. ``gated_update`` - calls it in its transaction. An override can first lock other rows + calls it in its gated section. An override can first lock other rows that the update writes.""" return locked_for_gates(instance) @@ -131,15 +156,18 @@ def gated_create(self, request, refusal_for): """DRF's create with a gate between validating and writing. ``refusal_for(validated_data)`` returns None to proceed or a Response - to answer instead, as for ``gated_update``. + to answer instead, as for ``gated_update``. It runs in a gated section + with no transaction of its own. A ``refusal_for`` that locks rows needs + the caller to open one. """ # pylint: disable=no-member - serializer = self.get_serializer(data=request.data) - serializer.is_valid(raise_exception=True) - refusal = refusal_for(serializer.validated_data) - if refusal is not None: - return refusal - self.perform_create(serializer) + with gated_section(atomic=False): + serializer = self.get_serializer(data=request.data) + serializer.is_valid(raise_exception=True) + refusal = refusal_for(serializer.validated_data) + if refusal is not None: + return refusal + self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response( serializer.data, status=status.HTTP_201_CREATED, headers=headers @@ -158,8 +186,7 @@ def gated_update(self, request, refusal_for, partial=False): value that the gate did not see. """ # pylint: disable=no-member - gating = bool(gated_actions()) - with transaction.atomic() if gating else nullcontext(): + with gated_section(): instance = self._locked_for_update(request, self.get_object()) serializer = self.get_serializer( instance, data=request.data, partial=partial diff --git a/onadata/libs/tests/stepup/test_drf.py b/onadata/libs/tests/stepup/test_drf.py index 8f4d73ab53..d64eb7040f 100644 --- a/onadata/libs/tests/stepup/test_drf.py +++ b/onadata/libs/tests/stepup/test_drf.py @@ -9,12 +9,18 @@ from django.test.utils import CaptureQueriesContext from django_otp.plugins.otp_totp.models import TOTPDevice +from multidb.pinning import ( + pin_this_thread, + this_thread_is_pinned, + unpin_this_thread, + use_master, +) from oidc.stepup_grants import issue_grant from rest_framework.parsers import JSONParser from rest_framework.request import Request from rest_framework.test import APIRequestFactory -from onadata.libs.stepup.drf import RequiresStepUp, lock_projects +from onadata.libs.stepup.drf import RequiresStepUp, gated_section, lock_projects from onadata.libs.test_utils.stepup import project_and_form_locks from onadata.libs.tests.stepup.test_challenge import ( FEDERATED, @@ -306,3 +312,39 @@ def test_locks_each_project_once_in_primary_key_order(self): project_and_form_locks(queries), [("logger_project", 2), ("logger_project", 5)], ) + + +class TestGatedSection(TestCase): + """Tests for ``gated_section``. Each test starts unpinned.""" + + def setUp(self): + unpin_this_thread() + self.addCleanup(unpin_this_thread) + + @override_settings(STEP_UP=GATED) + def test_a_use_master_inside_the_section_leaves_the_thread_unpinned(self): + """A section built on ``use_master`` would stay pinned here, since the + inner ``use_master`` overwrites its saved state.""" + with gated_section(): + self.assertTrue(this_thread_is_pinned()) + with use_master: + pass + self.assertTrue(this_thread_is_pinned()) + + self.assertFalse(this_thread_is_pinned()) + + @override_settings(STEP_UP=GATED) + def test_a_pinned_thread_stays_pinned(self): + """The section leaves a pin it did not take.""" + pin_this_thread() + + with gated_section(): + pass + + self.assertTrue(this_thread_is_pinned()) + + @override_settings(STEP_UP={"MODE": "local", "ACTIONS": []}) + def test_the_section_pins_nothing_where_nothing_is_gated(self): + """Without a gate there is no check to read the primary for.""" + with gated_section(): + self.assertFalse(this_thread_is_pinned()) From bbcf803af0d4ddc70e5dc0d1d0bd7f85f05fae06 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Thu, 3 Dec 2026 12:58:33 +0300 Subject: [PATCH 103/120] test: set the invitation URL in the after-commit email test --- onadata/apps/api/tests/viewsets/test_project_viewset.py | 1 + 1 file changed, 1 insertion(+) diff --git a/onadata/apps/api/tests/viewsets/test_project_viewset.py b/onadata/apps/api/tests/viewsets/test_project_viewset.py index 923514a4d7..979da22a20 100644 --- a/onadata/apps/api/tests/viewsets/test_project_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_project_viewset.py @@ -4007,6 +4007,7 @@ def test_update_email_only(self, mock_send_mail): self.invitation.pk, "https://example.com/register" ) + @override_settings(PROJECT_INVITATION_URL={"*": "https://example.com/register"}) def test_the_email_is_queued_after_the_commit(self, mock_send_mail): """The task reads the email from the row, so it must not run before the update that changes the email commits.""" From a580bf0fa4631845a86c8b84988df59dd4c6e929 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Thu, 3 Dec 2026 13:02:00 +0300 Subject: [PATCH 104/120] fix: order form and team shares with downgrades --- .../viewsets/test_stepup_primary_reads.py | 93 ++++++++++++++++++- .../viewsets/test_stepup_sharing_gates.py | 33 +++++++ .../tests/viewsets/test_stepup_team_gates.py | 35 +++++++ onadata/apps/api/viewsets/team_viewset.py | 24 +++-- onadata/apps/api/viewsets/xform_viewset.py | 17 +++- onadata/libs/stepup/drf.py | 12 +++ onadata/libs/test_utils/stepup.py | 39 +++++++- onadata/libs/tests/stepup/test_drf.py | 11 +++ 8 files changed, 248 insertions(+), 16 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_primary_reads.py b/onadata/apps/api/tests/viewsets/test_stepup_primary_reads.py index 68ebc581b7..a25c17684a 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_primary_reads.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_primary_reads.py @@ -9,6 +9,7 @@ from django.contrib.auth import get_user_model from django_otp.plugins.otp_totp.models import TOTPDevice +from guardian.shortcuts import get_perms from multidb.pinning import use_master from rest_framework.test import APIRequestFactory @@ -32,12 +33,16 @@ from onadata.apps.logger.models import Project, XForm from onadata.apps.main.models import MetaData from onadata.apps.main.tests.test_base import TestBase -from onadata.libs.permissions import OwnerRole +from onadata.libs.models.share_team_project import ShareTeamProject +from onadata.libs.models.share_xform import ShareXForm +from onadata.libs.permissions import ManagerRole, OwnerRole, ReadOnlyRole from onadata.libs.stepup.policy import ( GATE_CHANGE_EMAIL, GATE_CHANGE_WEBHOOK, GATE_GRANT_ORG_ADMIN, GATE_PUBLISH_DATA, + GATE_SHARE_FORM_ADMIN, + GATE_SHARE_TEAM_ADMIN, GATE_TRANSFER_PROJECT, ) from onadata.libs.test_utils.lagging_replica import lagging_replica @@ -186,6 +191,92 @@ def test_a_member_who_joined_on_the_primary_is_challenged(self): self.assertEqual(Team.objects.get(pk=self.team.pk).name, "denoinc#dreamteam") +@gating(GATE_SHARE_FORM_ADMIN) +class TestFormShareReadsThePrimary(PrimaryReadTestCase): + """alice manages bob's form until a test lowers her role on the primary. + Sharing the manager role again appoints her, so the check must see the + lower role.""" + + def setUp(self): + super().setUp() + self._publish_transportation_form() + ShareXForm(self.xform, "alice", ManagerRole.name).save() + self.assertTrue(self._alice_manages_the_form()) + + def _alice_manages_the_form(self): + return ManagerRole.user_has_role(self.alice, self.xform) + + def test_a_downgrade_on_the_primary_is_challenged(self): + """Depends on the gated section in ``XFormViewSet.share``.""" + with lagging_replica(): + with use_master: + ShareXForm(self.xform, "alice", ReadOnlyRole.name).save() + self.assertTrue(self._alice_manages_the_form()) + with use_master: + self.assertFalse(self._alice_manages_the_form()) + response = self._send( + XFormViewSet, + "post", + "share", + {"username": "alice", "role": ManagerRole.name}, + pk=self.xform.pk, + ) + + self.assert_challenged(response, GATE_SHARE_FORM_ADMIN) + self.assertFalse(self._alice_manages_the_form()) + + +@gating(GATE_SHARE_TEAM_ADMIN) +class TestTeamShareReadsThePrimary(PrimaryReadTestCase): + """A team manages bob's project until a test lowers or removes its role + on the primary. Sharing the manager role again appoints its members, so + the check must see the change.""" + + def setUp(self): + super().setUp() + self._publish_transportation_form() + self.project = self.xform.project + organization = self._create_organization_of_bob() + self.team = Team.objects.create( + organization=organization.user, name="dreamteam", created_by=self.user + ) + ShareTeamProject(self.team, self.project, ManagerRole.name).save() + self.assertTrue(self._team_manages_the_project()) + + def _team_manages_the_project(self): + return ManagerRole.has_role(get_perms(self.team, self.project), self.project) + + def _share_manager_again_after(self, change): + with lagging_replica(): + with use_master: + change.save() + self.assertTrue(self._team_manages_the_project()) + with use_master: + self.assertFalse(self._team_manages_the_project()) + response = self._send( + TeamViewSet, + "post", + "share", + {"project": self.project.pk, "role": ManagerRole.name}, + pk=self.team.pk, + ) + + self.assert_challenged(response, GATE_SHARE_TEAM_ADMIN) + self.assertFalse(self._team_manages_the_project()) + + def test_a_downgrade_on_the_primary_is_challenged(self): + """Depends on the gated section in ``TeamViewSet.share``.""" + self._share_manager_again_after( + ShareTeamProject(self.team, self.project, ReadOnlyRole.name) + ) + + def test_a_removal_on_the_primary_is_challenged(self): + """Depends on the gated section in ``TeamViewSet.share``.""" + self._share_manager_again_after( + ShareTeamProject(self.team, self.project, ManagerRole.name, remove=True) + ) + + class TestFormMoveReadsThePrimary(PrimaryReadTestCase): """A form update that names a project checks that project as the lock leaves it.""" diff --git a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py index 9c4d37a6ae..f540414270 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_sharing_gates.py @@ -53,6 +53,8 @@ EDITOR_STAYS_BELOW_ADMIN, StepUpGateTestCase, gating, + project_shares_lock, + queries_and_calls, ) from onadata.libs.tests.stepup.test_challenge import FEDERATED_SERVER @@ -617,6 +619,37 @@ def test_a_role_every_target_already_holds_is_not_challenged(self): self.assertEqual(response.status_code, 204) self.assertTrue(OwnerRole.user_has_role(self.alice, self.xform)) + def test_the_share_locks_the_project_shares_before_its_check(self): + """A downgrade holds the same lock, so it cannot commit between the + check and the share. Depends on ``lock_project_shares_for_gates`` at + the start of the gated section in ``XFormViewSet.share``.""" + ShareXForm(self.xform, "alice", OwnerRole.name).save() + self.assert_challenged(self._share("tom", OwnerRole.name)) + + with queries_and_calls(f"{XFORM_VIEWSET}.holds_roles") as (queries, checks): + response = self._share("alice", OwnerRole.name) + + self.assertEqual(response.status_code, 204) + self.assertEqual(len(checks), 1) + lock = project_shares_lock(queries, self.xform.project_id) + self.assertIsNotNone(lock) + self.assertLess(lock, checks[0]) + + def test_a_downgrade_takes_the_project_shares_lock(self): + """A check that waits for it then sees the lower role. Depends on + ``lock_project_shares_for_gates`` in ``XFormViewSet.share``, which + runs whatever the role.""" + ShareXForm(self.xform, "alice", ManagerRole.name).save() + self.assert_challenged(self._share("tom", OwnerRole.name)) + + with CaptureQueriesContext(connection) as queries: + response = self._share("alice", ReadOnlyRole.name) + + self.assertEqual(response.status_code, 204) + self.assertFalse(ManagerRole.user_has_role(self.alice, self.xform)) + self.assertTrue(ReadOnlyRole.user_has_role(self.alice, self.xform)) + self.assertIsNotNone(project_shares_lock(queries, self.xform.project_id)) + def test_an_invalid_share_keeps_the_grant(self): """Validation comes first, so an unknown username does not spend it.""" self.assert_challenged(self._share("alice", OwnerRole.name)) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py index f8e2d97634..53965df90d 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_team_gates.py @@ -27,8 +27,12 @@ from onadata.libs.test_utils.stepup import ( StepUpGateTestCase, gating, + project_shares_lock, + queries_and_calls, ) +TEAM_VIEWSET = "onadata.apps.api.viewsets.team_viewset" + class TeamGateTestCase(StepUpGateTestCase): """An organisation with a team, and a user who belongs to neither.""" @@ -195,6 +199,37 @@ def test_removing_the_team_is_not_challenged(self): self.assertEqual(response.status_code, 204) self.assertFalse(ManagerRole.user_has_role(self.alice, self.project)) + def test_the_share_locks_the_project_shares_before_its_check(self): + """A downgrade or removal holds the same lock, so it cannot commit + between the check and the share. Depends on + ``lock_project_shares_for_gates`` at the start of the gated section in + ``TeamViewSet.share``.""" + self.assertEqual(self._share("manager").status_code, 401) + self._give_the_team("manager") + + with queries_and_calls(f"{TEAM_VIEWSET}.holds_roles") as (queries, checks): + response = self._share("manager") + + self.assertEqual(response.status_code, 204) + self.assertEqual(len(checks), 1) + lock = project_shares_lock(queries, self.project.pk) + self.assertIsNotNone(lock) + self.assertLess(lock, checks[0]) + + def test_removing_the_team_takes_the_project_shares_lock(self): + """A check that waits for it then sees the team removed. Depends on + ``lock_project_shares_for_gates`` in ``TeamViewSet.share``, which runs + for a removal too.""" + self.assertEqual(self._share("manager").status_code, 401) + self._give_the_team("manager") + + with CaptureQueriesContext(connection) as queries: + response = self._share("manager", remove=True) + + self.assertEqual(response.status_code, 204) + self.assertFalse(ManagerRole.user_has_role(self.alice, self.project)) + self.assertIsNotNone(project_shares_lock(queries, self.project.pk)) + def test_an_unknown_project_keeps_the_grant(self): """The project is checked first, so a typo does not spend it.""" grant = issue_grant(self.user.pk, "share-team-admin") diff --git a/onadata/apps/api/viewsets/team_viewset.py b/onadata/apps/api/viewsets/team_viewset.py index b8e87e0830..e3f60b13f6 100644 --- a/onadata/apps/api/viewsets/team_viewset.py +++ b/onadata/apps/api/viewsets/team_viewset.py @@ -38,7 +38,11 @@ ) from onadata.libs.serializers.team_serializer import TeamSerializer from onadata.libs.stepup import RequiresStepUp -from onadata.libs.stepup.drf import gated_section, locked_for_gates +from onadata.libs.stepup.drf import ( + gated_section, + lock_project_shares_for_gates, + locked_for_gates, +) from onadata.libs.stepup.gate import changed_gated_actions from onadata.libs.stepup.policy import ( GATE_GRANT_ORG_ADMIN, @@ -262,13 +266,15 @@ def share(self, request, *args, **kwargs): if not serializer.is_valid(): return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) - refusal = ( - None - if remove - else self._share_admin_refusal(request, serializer.validated_data) - ) - if refusal is not None: - return refusal - serializer.save() + with gated_section(): + lock_project_shares_for_gates(serializer.validated_data["project"].pk) + refusal = ( + None + if remove + else self._share_admin_refusal(request, serializer.validated_data) + ) + if refusal is not None: + return refusal + serializer.save() return Response(status=status.HTTP_204_NO_CONTENT) diff --git a/onadata/apps/api/viewsets/xform_viewset.py b/onadata/apps/api/viewsets/xform_viewset.py index ce87fdeefe..64896d5742 100644 --- a/onadata/apps/api/viewsets/xform_viewset.py +++ b/onadata/apps/api/viewsets/xform_viewset.py @@ -79,7 +79,12 @@ XFormVersionListSerializer, ) from onadata.libs.stepup import RequiresStepUp -from onadata.libs.stepup.drf import lock_projects, locked_for_gates +from onadata.libs.stepup.drf import ( + gated_section, + lock_project_shares_for_gates, + lock_projects, + locked_for_gates, +) from onadata.libs.stepup.policy import ( GATE_DISABLE_FORM_ENCRYPTION, GATE_FORM_REQUIRE_AUTH, @@ -873,10 +878,12 @@ def share(self, request, *args, **kwargs): serializer = ShareXFormSerializer(data=data_list, many=True) if serializer.is_valid(): - refusal = self._share_admin_refusal(request, serializer.validated_data) - if refusal is not None: - return refusal - serializer.save() + with gated_section(): + lock_project_shares_for_gates(self.object.project_id) + refusal = self._share_admin_refusal(request, serializer.validated_data) + if refusal is not None: + return refusal + serializer.save() else: return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) diff --git a/onadata/libs/stepup/drf.py b/onadata/libs/stepup/drf.py index 747dd6aaf3..d19db223e4 100644 --- a/onadata/libs/stepup/drf.py +++ b/onadata/libs/stepup/drf.py @@ -10,6 +10,7 @@ from rest_framework.response import Response from onadata.apps.logger.models import Project +from onadata.libs.models.share_project import lock_project_shares from onadata.libs.stepup.challenge import ( STEP_UP_UNAVAILABLE, build_challenge, @@ -104,6 +105,17 @@ def locked_form_for_gates(xform): return locked_for_gates(xform) +def lock_project_shares_for_gates(project_pk): + """``lock_project_shares`` where the deployment gates any action. Take it + first in the gated section of a share. + + A gate waives a share when the target already holds the role. A downgrade + or removal that holds the same lock cannot then commit between that check + and the share.""" + if gated_actions(): + lock_project_shares(project_pk) + + class RequiresStepUp: """Refuse a gated action unless the request carries a single-use grant. diff --git a/onadata/libs/test_utils/stepup.py b/onadata/libs/test_utils/stepup.py index 75c3156cd2..efc6445509 100644 --- a/onadata/libs/test_utils/stepup.py +++ b/onadata/libs/test_utils/stepup.py @@ -4,14 +4,19 @@ """ import re +from contextlib import contextmanager +from importlib import import_module +from unittest.mock import patch -from django.test.utils import override_settings +from django.db import connection +from django.test.utils import CaptureQueriesContext, override_settings from django_otp.plugins.otp_totp.models import TOTPDevice from oidc.stepup_grants import issue_grant, spend_grant from onadata.apps.api.tests.viewsets.test_abstract_viewset import TestAbstractViewSet from onadata.apps.main.models import MetaData +from onadata.libs.models.share_project import PROJECT_SHARES_LOCK_SPACE #: ``xform_meta_perms`` values. The first slot replaces an editor's role. EDITOR_BECOMES_OWNER = "owner|dataentry-only|readonly" @@ -47,6 +52,38 @@ def project_and_form_locks(queries): ] +def project_shares_lock(queries, project_pk): + """The index in ``queries``, a ``CaptureQueriesContext``, of the first + query that takes the share lock of project ``project_pk``, or None.""" + lock = f"pg_advisory_xact_lock({PROJECT_SHARES_LOCK_SPACE}, {project_pk})" + return next( + ( + index + for index, query in enumerate(queries.captured_queries) + if lock in query["sql"] + ), + None, + ) + + +@contextmanager +def queries_and_calls(target): + """Capture the queries of the block, and patch ``target``, a dotted path, + to record how many had run at each of its calls. Yield + ``(queries, calls)``.""" + module_name, name = target.rsplit(".", 1) + original = getattr(import_module(module_name), name) + calls = [] + with CaptureQueriesContext(connection) as queries: + + def recording(*args, **kwargs): + calls.append(len(queries.captured_queries)) + return original(*args, **kwargs) + + with patch(target, new=recording): + yield queries, calls + + def gating(*audiences, **settings): """Gate exactly ``audiences``, for a user with a confirmed factor.""" return override_settings( diff --git a/onadata/libs/tests/stepup/test_drf.py b/onadata/libs/tests/stepup/test_drf.py index d64eb7040f..ddadf82dd1 100644 --- a/onadata/libs/tests/stepup/test_drf.py +++ b/onadata/libs/tests/stepup/test_drf.py @@ -343,6 +343,17 @@ def test_a_pinned_thread_stays_pinned(self): self.assertTrue(this_thread_is_pinned()) + @override_settings(STEP_UP=GATED) + def test_an_error_in_the_section_leaves_the_thread_unpinned(self): + """Otherwise the next request on the thread reads the primary too. + Depends on the ``finally`` in ``gated_section``.""" + with self.assertRaises(ValueError): + with gated_section(): + self.assertTrue(this_thread_is_pinned()) + raise ValueError + + self.assertFalse(this_thread_is_pinned()) + @override_settings(STEP_UP={"MODE": "local", "ACTIONS": []}) def test_the_section_pins_nothing_where_nothing_is_gated(self): """Without a gate there is no check to read the primary for.""" From ba1359678f29cd623edcf7b154bdf3dfc4611230 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Thu, 3 Dec 2026 13:07:42 +0300 Subject: [PATCH 105/120] test: raise from a helper in the pin-restore test --- onadata/libs/tests/stepup/test_drf.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/onadata/libs/tests/stepup/test_drf.py b/onadata/libs/tests/stepup/test_drf.py index ddadf82dd1..7a5091b709 100644 --- a/onadata/libs/tests/stepup/test_drf.py +++ b/onadata/libs/tests/stepup/test_drf.py @@ -347,13 +347,14 @@ def test_a_pinned_thread_stays_pinned(self): def test_an_error_in_the_section_leaves_the_thread_unpinned(self): """Otherwise the next request on the thread reads the primary too. Depends on the ``finally`` in ``gated_section``.""" - with self.assertRaises(ValueError): - with gated_section(): - self.assertTrue(this_thread_is_pinned()) - raise ValueError - + self.assertRaises(ValueError, self._raise_in_a_section) self.assertFalse(this_thread_is_pinned()) + def _raise_in_a_section(self): + with gated_section(): + self.assertTrue(this_thread_is_pinned()) + raise ValueError + @override_settings(STEP_UP={"MODE": "local", "ACTIONS": []}) def test_the_section_pins_nothing_where_nothing_is_gated(self): """Without a gate there is no check to read the primary for.""" From 10160e03980c025f2923259448f92448be0a1dc4 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Thu, 3 Dec 2026 13:08:59 +0300 Subject: [PATCH 106/120] fix: accept invitations in project order --- onadata/apps/main/signals.py | 4 +++- onadata/apps/main/tests/test_signals.py | 25 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/onadata/apps/main/signals.py b/onadata/apps/main/signals.py index 527468c5dd..0f09865639 100644 --- a/onadata/apps/main/signals.py +++ b/onadata/apps/main/signals.py @@ -78,10 +78,12 @@ def accept_project_invitation(sender, instance=None, created=False, **kwargs): if created: # pylint: disable=invalid-name ProjectInvitation = apps.get_model("logger", "ProjectInvitation") # noqa: N806 + # Each share holds its project's lock until the registration commits. + # A fixed order stops two registrations from deadlocking. invitation_qs = ProjectInvitation.objects.filter( email=instance.email, status=ProjectInvitation.Status.PENDING, - ) + ).order_by("project_id") now = timezone.now() # ShareProject needs to be imported inline because otherwise we get # django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. diff --git a/onadata/apps/main/tests/test_signals.py b/onadata/apps/main/tests/test_signals.py index b47b0cebf7..d0725e5333 100644 --- a/onadata/apps/main/tests/test_signals.py +++ b/onadata/apps/main/tests/test_signals.py @@ -4,10 +4,13 @@ from unittest.mock import Mock, patch from django.contrib.auth import get_user_model +from django.db import connection +from django.test.utils import CaptureQueriesContext from onadata.apps.logger.models import Project, ProjectInvitation from onadata.apps.main.tests.test_base import TestBase from onadata.libs.permissions import EditorRole, ManagerRole +from onadata.libs.test_utils.stepup import project_shares_lock from onadata.libs.utils.user_auth import get_user_default_project User = get_user_model() @@ -61,6 +64,28 @@ def test_accept_invitation(self): self.assertEqual(mike_invitation.accepted_by, mike) self.assertTrue(ManagerRole.user_has_role(mike, project)) + def test_the_share_locks_follow_the_project_order(self): + """Two registrations that take the share locks in opposite orders can + deadlock. Depends on the ``order_by`` in ``accept_project_invitation``.""" + later = Project.objects.create( + name="Project 2", created_by=self.user, organization=self.user + ) + self.invitation.delete() + for project in (later, self.project): + ProjectInvitation.objects.create( + email="mike@example.com", project=project, role="editor" + ) + self.assertLess(self.project.pk, later.pk) + + with CaptureQueriesContext(connection) as queries: + User.objects.create(username="mike", email="mike@example.com") + + first = project_shares_lock(queries, self.project.pk) + second = project_shares_lock(queries, later.pk) + self.assertIsNotNone(first) + self.assertIsNotNone(second) + self.assertLess(first, second) + def test_only_pending_accepted(self): """Only pending invitations are accepted""" self.invitation.status = ProjectInvitation.Status.REVOKED From b967a42b5cb4e38f686a9c90d1f79d3e284c5d63 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Thu, 3 Dec 2026 15:36:34 +0300 Subject: [PATCH 107/120] docs: fix stale step-up wording and split the repeat share log --- docs/two_factor.rst | 11 ++++++----- onadata/apps/api/tasks.py | 15 ++++++++++----- onadata/apps/api/viewsets/stepup_viewset.py | 2 +- 3 files changed, 17 insertions(+), 11 deletions(-) diff --git a/docs/two_factor.rst b/docs/two_factor.rst index 85a33de2ad..4ab541b8c5 100644 --- a/docs/two_factor.rst +++ b/docs/two_factor.rst @@ -5,9 +5,9 @@ A deployment can let an account protect its sign-in with a second factor. The second factor is an authenticator app (TOTP). Single-use recovery codes replace the app if the user loses it. -Each endpoint on this page acts on the authenticated caller only. No endpoint -accepts a username. Thus, no caller can change the second factor of another -user. +The ``/api/v1/totp`` and ``/api/v1/stepup`` endpoints act on the +authenticated caller only. They accept no username. Thus, no caller can change +the second factor of another user. The second-factor endpoints are under ``/api/v1/totp``. The step-up endpoints are under ``/api/v1/stepup``, and ``/api/v1/user/capabilities`` @@ -486,8 +486,9 @@ then hide the controls that do not apply:: The startup checks report a step-up configuration that will not work as intended. A WSGI server does not run the checks. Thus, the WSGI application does not load if a step-up check, or the ona-oidc check of the ``STEP_UP`` -block of the provider (``oidc.E003``), reports an error. ``manage.py check`` -shows all results. +block of the provider (``oidc.E003``), reports an error. uWSGI then answers +each request with an error. To make the process exit, set ``need-app = true``. +``manage.py check`` shows all results. Step-up always uses the authorization code flow. Thus, ``oidc.E003`` reports a provider that has a ``STEP_UP`` block but no ``TOKEN_ENDPOINT`` diff --git a/onadata/apps/api/tasks.py b/onadata/apps/api/tasks.py index 9c3041ca5b..ea287034aa 100644 --- a/onadata/apps/api/tasks.py +++ b/onadata/apps/api/tasks.py @@ -246,15 +246,20 @@ def share_project_async(project_id, username, role, remove=False, repeat_only=Fa def _repeat_project_share(project, username, role): lock_project_shares(project.pk) user = User.objects.filter(username=username).first() - if user is None or not holds_roles( - user, project_admin_roles_granted(project, role) - ): + if user is None: logger.warning( - "Skipped a repeat share of project %s: it would give the user an " - "owner or manager role that they lack.", + "Skipped a repeat share of project %s: the user does not exist.", project.pk, ) return + if not holds_roles(user, project_admin_roles_granted(project, role)): + logger.warning( + "Skipped a repeat share of project %s: the %s role would give the " + "user an owner or manager role that they lack.", + project.pk, + role, + ) + return ShareProject(project, username, role).save() diff --git a/onadata/apps/api/viewsets/stepup_viewset.py b/onadata/apps/api/viewsets/stepup_viewset.py index cc3cff5fd7..8f794afcd3 100644 --- a/onadata/apps/api/viewsets/stepup_viewset.py +++ b/onadata/apps/api/viewsets/stepup_viewset.py @@ -129,7 +129,7 @@ def callback(self, request): return Response({"grant": grant}) def verify_step_up_context(self, request, context): - """The state must belong to the session redeeming it.""" + """The state must belong to the user redeeming it.""" if context.get("user_pk") != request.user.pk: logger.warning("step-up: state belongs to a different user") return "state_user_mismatch" From 72c7f965d7db5cb20201fb63748935eadc87eb93 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Thu, 3 Dec 2026 18:35:01 +0300 Subject: [PATCH 108/120] chore: pin ona-oidc to the head of its step-up PR --- requirements/base.in | 2 +- requirements/base.pip | 2 +- requirements/dev.pip | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/requirements/base.in b/requirements/base.in index 2cbb26fe25..8ebdbbbb52 100644 --- a/requirements/base.in +++ b/requirements/base.in @@ -30,7 +30,7 @@ git+https://github.com/onaio/floip-py.git@3c980eb184069ae7c3c9136b18441978237cd4 git+https://github.com/onaio/python-json2xlsclient.git@62b4645f7b4f2684421a13ce98da0331a9dd66a0#egg=python-json2xlsclient # Pinned at the step-up branch tip for stepup_grants, which the totp endpoints # import. Re-pin to a main SHA once onaio/ona-oidc#139 merges. -git+https://github.com/onaio/ona-oidc.git@34074d3a2868b3c72f905aad63a6101b1603b2c3#egg=ona-oidc +git+https://github.com/onaio/ona-oidc.git@0b1c4c8f3f8fe8e65f00fd223f5c053edd7f6270#egg=ona-oidc -e git+https://github.com/onaio/savreaderwriter.git@fix-pep-440-issues#egg=savreaderwriter git+https://git@github.com/onaio/valigetta.git@v0.3.1#egg=valigetta codetiming diff --git a/requirements/base.pip b/requirements/base.pip index e99e509bd5..dc5f2cbe75 100644 --- a/requirements/base.pip +++ b/requirements/base.pip @@ -265,7 +265,7 @@ oauthlib==4.0.1 # -r requirements/base.in # django-oauth-toolkit # requests-oauthlib -ona-oidc @ git+https://github.com/onaio/ona-oidc.git@34074d3a2868b3c72f905aad63a6101b1603b2c3 +ona-oidc @ git+https://github.com/onaio/ona-oidc.git@0b1c4c8f3f8fe8e65f00fd223f5c053edd7f6270 # via -r requirements/base.in openpyxl==3.1.5 # via diff --git a/requirements/dev.pip b/requirements/dev.pip index 7c07bb3c98..a89d3f0812 100644 --- a/requirements/dev.pip +++ b/requirements/dev.pip @@ -331,7 +331,7 @@ oauthlib==4.0.1 # -r requirements/base.in # django-oauth-toolkit # requests-oauthlib -ona-oidc @ git+https://github.com/onaio/ona-oidc.git@34074d3a2868b3c72f905aad63a6101b1603b2c3 +ona-oidc @ git+https://github.com/onaio/ona-oidc.git@0b1c4c8f3f8fe8e65f00fd223f5c053edd7f6270 # via -r requirements/base.in openpyxl==3.1.5 # via From 8309004cb2fdafb8b3e7cd8e351be585b11a702c Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Thu, 3 Dec 2026 19:08:23 +0300 Subject: [PATCH 109/120] test: give the complete step-up provider an authorization endpoint --- onadata/libs/tests/stepup/test_checks.py | 1 + 1 file changed, 1 insertion(+) diff --git a/onadata/libs/tests/stepup/test_checks.py b/onadata/libs/tests/stepup/test_checks.py index 19e490565d..08434c1404 100644 --- a/onadata/libs/tests/stepup/test_checks.py +++ b/onadata/libs/tests/stepup/test_checks.py @@ -45,6 +45,7 @@ def _complete_servers(): """A provider whose ``STEP_UP`` block passes ona-oidc's ``oidc.E003``.""" return { "idp": { + "AUTHORIZATION_ENDPOINT": "https://idp.test/auth", "TOKEN_ENDPOINT": "https://idp.test/token", "STEP_UP": { "CLAIM": "acr", From 3b30b3ed5b12e406b0760d697dda835b3a30b4ab Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Thu, 3 Dec 2026 19:08:41 +0300 Subject: [PATCH 110/120] docs: name the authorization endpoint check in the upgrade note --- docs/two_factor.rst | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/two_factor.rst b/docs/two_factor.rst index 4ab541b8c5..8a88bf5809 100644 --- a/docs/two_factor.rst +++ b/docs/two_factor.rst @@ -493,8 +493,9 @@ each request with an error. To make the process exit, set ``need-app = true``. Step-up always uses the authorization code flow. Thus, ``oidc.E003`` reports a provider that has a ``STEP_UP`` block but no ``TOKEN_ENDPOINT`` that is an absolute http or https URL, also where login uses the implicit -flow. Set ``TOKEN_ENDPOINT`` on that -provider before you upgrade, or the application does not start. A +flow. ``oidc.E003`` also reports an ``AUTHORIZATION_ENDPOINT`` that is not +an absolute http or https URL, such as ``/authorize``. Set both endpoints +on that provider before you upgrade, or the application does not start. A ``STEP_UP_POPUP_ORIGIN`` that is set but is not an http or https origin is also ``oidc.E003``. From 8b068494a6f4b8ed8c2e940c765a42ec71e04878 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Fri, 4 Dec 2026 07:19:11 +0300 Subject: [PATCH 111/120] fix: check entity list links and the stored metadata type --- docs/two_factor.rst | 6 +-- .../viewsets/test_stepup_metadata_gates.py | 48 ++++++++++++++++++- onadata/apps/api/tools.py | 9 +--- onadata/apps/api/viewsets/metadata_viewset.py | 23 +++++---- onadata/apps/main/models/meta_data.py | 25 ++++++++-- .../libs/serializers/metadata_serializer.py | 26 +++++----- 6 files changed, 98 insertions(+), 39 deletions(-) diff --git a/docs/two_factor.rst b/docs/two_factor.rst index 8a88bf5809..895381337b 100644 --- a/docs/two_factor.rst +++ b/docs/two_factor.rst @@ -354,9 +354,9 @@ Audience Action ``/api/v1/metadata`` that turns on the ``public_link`` of a form; a new or changed ``media`` row on ``/api/v1/metadata`` that links to - a form or dataview, because a user who can read - the media of the form can download the linked - data; a new dataview in a + a form, dataview or entity list, because a user + who can read the media of the form can download + the linked data; a new dataview in a public project, or a change to the project, columns or query of a dataview there, over a form whose data is not public; a new merged dataset in a public diff --git a/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py index d5df1dbf1a..db3b3b9ee4 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py @@ -19,7 +19,7 @@ ) from onadata.apps.api.tools import add_user_to_team from onadata.apps.api.viewsets.metadata_viewset import MetaDataViewSet -from onadata.apps.logger.models import DataView, XForm +from onadata.apps.logger.models import DataView, EntityList, Project, XForm from onadata.apps.main.models import MetaData from onadata.libs.permissions import ( EditorMinorRole, @@ -399,6 +399,52 @@ def test_turning_a_url_row_into_a_link_is_challenged(self): row.refresh_from_db() self.assertEqual(row.data_value, self.media_url) + def _entity_list(self, project): + return EntityList.objects.create(name="trees", project=project) + + def test_linking_an_entity_list_is_challenged(self): + """The media download serves an entity list link as well.""" + link = f"entity_list {self._entity_list(self.project).pk} trees" + + response = self._create("media", link) + + self.assert_challenged(response) + self.assertNotIn(link, self._media_values()) + + def test_turning_a_url_row_into_an_entity_list_link_is_challenged(self): + """A PATCH without the type is validated and gated as a media row.""" + MetaData.media_add_uri(self.xform, self.media_url) + row = MetaData.objects.get(data_type="media", data_value=self.media_url) + link = f"entity_list {self._entity_list(self.project).pk} trees" + + response = self._update(row, {"data_value": link}, method="patch") + + self.assert_challenged(response) + row.refresh_from_db() + self.assertEqual(row.data_value, self.media_url) + + def test_a_patch_cannot_link_data_the_user_cannot_manage(self): + """Without the type, the link target is still checked. The grant makes + sure that the check, not the gate, refuses it.""" + alice = self._user("alice") + alices_project = Project.objects.create( + name="alice's", organization=alice, created_by=alice + ) + self.assertFalse(ManagerRole.user_has_role(self.user, alices_project)) + MetaData.media_add_uri(self.xform, self.media_url) + row = MetaData.objects.get(data_type="media", data_value=self.media_url) + link = f"entity_list {self._entity_list(alices_project).pk} trees" + grant = self._grant() + + response = self._update( + row, {"data_value": link}, self._with_grant(grant), method="patch" + ) + + self.assertEqual(response.status_code, 400, response.data) + self.assert_unspent(grant) + row.refresh_from_db() + self.assertEqual(row.data_value, self.media_url) + def test_rewriting_a_link_is_not_challenged(self): """A row that already links to the form publishes nothing new.""" response = self._create("media", self.link, self._with_grant(self._grant())) diff --git a/onadata/apps/api/tools.py b/onadata/apps/api/tools.py index 23d738f737..69eddbe21d 100644 --- a/onadata/apps/api/tools.py +++ b/onadata/apps/api/tools.py @@ -43,6 +43,7 @@ from onadata.apps.api.models.team import Team from onadata.apps.logger.models import DataView, EntityList, Instance, Project, XForm from onadata.apps.main.forms import QuickConverter +from onadata.apps.main.models.meta_data import LINKED_DATASET_MODELS, linked_dataset_tag from onadata.apps.viewer.models.parsed_instance import datetime_from_str from onadata.libs.baseviewset import DefaultBaseViewset from onadata.libs.exceptions import NoRecordsPermission @@ -616,13 +617,7 @@ def get_data_value_objects(value): Looks for 'dataview 123 fruits.csv' or 'xform 345 fruits.csv'. """ - model = None - if value.startswith("dataview"): - model = DataView - elif value.startswith("xform"): - model = XForm - elif value.startswith("entity_list"): - model = EntityList + model = LINKED_DATASET_MODELS.get(linked_dataset_tag(value)) if model: parts = value.split() diff --git a/onadata/apps/api/viewsets/metadata_viewset.py b/onadata/apps/api/viewsets/metadata_viewset.py index d3ab47f23f..93a1555354 100644 --- a/onadata/apps/api/viewsets/metadata_viewset.py +++ b/onadata/apps/api/viewsets/metadata_viewset.py @@ -12,11 +12,13 @@ from onadata.apps.api.permissions import MetaDataObjectPermissions from onadata.apps.api.tools import get_media_file_response from onadata.apps.logger.models import XForm -from onadata.apps.main.models.meta_data import MetaData, type_for_form +from onadata.apps.main.models.meta_data import ( + MetaData, + linked_dataset_tag, + type_for_form, +) from onadata.libs.serializers.metadata_serializer import ( - DATAVIEW_TAG, MEDIA_TYPE, - XFORM_TAG, MetaDataSerializer, ) from onadata.libs import filters @@ -74,19 +76,16 @@ def _introduces_admin_meta_perms(content_object, data_value): def _linked_dataset(data_type, data_value): - """``(tag, pk)`` of the form or data view whose data a row holding - ``data_type`` and ``data_value`` serves, or None. + """``(tag, pk)`` of the form, data view or entity list whose data a row + holding ``data_type`` and ``data_value`` serves, or None. Reads the value as the media download does. Anyone who can read the host form's media can download that data, so a link publishes it.""" - if data_type != MEDIA_TYPE or not isinstance(data_value, str): + if data_type != MEDIA_TYPE: return None - parts = data_value.split() - tag = next( - (tag for tag in (DATAVIEW_TAG, XFORM_TAG) if data_value.startswith(tag)), - None, - ) - if tag is None or len(parts) < 2: + tag = linked_dataset_tag(data_value) + parts = data_value.split() if tag else [] + if len(parts) < 2: return None return tag, parts[1] diff --git a/onadata/apps/main/models/meta_data.py b/onadata/apps/main/models/meta_data.py index b6e97ed07d..ab36e2df2b 100644 --- a/onadata/apps/main/models/meta_data.py +++ b/onadata/apps/main/models/meta_data.py @@ -57,6 +57,15 @@ PROJECT_MODEL_NAME = "project" XFORM_MODEL_NAME = "xform" +#: The first word of a media value that links to the data of a form, a data +#: view or an entity list, and the model it names. The media download serves +#: that data, so a gate or a check of the target must know every one. +LINKED_DATASET_MODELS = { + "dataview": DataView, + "entity_list": EntityList, + "xform": XForm, +} + DEFAULT_REQUEST_TIMEOUT = getattr(settings, "DEFAULT_REQUEST_TIMEOUT", 30) @@ -113,6 +122,16 @@ def get_default_content_type(): return content_object.id +def linked_dataset_tag(data_value): + """The key of ``LINKED_DATASET_MODELS`` that ``data_value`` starts with, as + the media download reads it, or None.""" + if not isinstance(data_value, str): + return None + return next( + (tag for tag in LINKED_DATASET_MODELS if data_value.startswith(tag)), None + ) + + def unique_type_for_form( content_object, data_type, data_value=None, data_file=None, extra_data=None ): @@ -586,11 +605,7 @@ def is_linked_dataset(self): """ Returns True if the metadata object is a linked dataset. """ - return isinstance(self.data_value, str) and ( - self.data_value.startswith("xform") - or self.data_value.startswith("dataview") - or self.data_value.startswith("entity_list") - ) + return linked_dataset_tag(self.data_value) is not None @staticmethod def xform_meta_permission(content_object, data_value=None): diff --git a/onadata/libs/serializers/metadata_serializer.py b/onadata/libs/serializers/metadata_serializer.py index 2ae7797744..141c50d346 100644 --- a/onadata/libs/serializers/metadata_serializer.py +++ b/onadata/libs/serializers/metadata_serializer.py @@ -21,6 +21,7 @@ from onadata.apps.logger.models import DataView, Instance, Project, XForm from onadata.apps.main.models import MetaData +from onadata.apps.main.models.meta_data import LINKED_DATASET_MODELS from onadata.libs.permissions import ROLES, ManagerRole from onadata.libs.serializers.fields.instance_related_field import InstanceRelatedField from onadata.libs.serializers.fields.json_field import JsonField @@ -79,7 +80,7 @@ def get_linked_object(parts): - """Returns an XForm or DataView object + """Returns the XForm, DataView or EntityList object that ``parts`` link to Raises 404 Exception if object is not found. Raises serializers.ValidationError if the format of the linked @@ -89,7 +90,7 @@ def get_linked_object(parts): obj_type = parts[0] if "geojson" in obj_type: obj_type = obj_type.split("_")[0] - if obj_type in [DATAVIEW_TAG, XFORM_TAG] and len(parts) > 1: + if obj_type in LINKED_DATASET_MODELS and len(parts) > 1: obj_pk = parts[1] try: obj_pk = int(obj_pk) @@ -102,9 +103,7 @@ def get_linked_object(parts): ) } ) from error - model = DataView if obj_type == DATAVIEW_TAG else XForm - - return get_object_or_404(model, pk=obj_pk) + return get_object_or_404(LINKED_DATASET_MODELS[obj_type], pk=obj_pk) return None @@ -233,10 +232,15 @@ def _validate_data_file(attrs, data_type, data_file): def validate(self, attrs): """ Validate url if we are adding a media uri instead of a media file + + A partial update can leave out the type or the value. The row then + keeps its stored one, so validate against that. """ - value = attrs.get("data_value") - data_type = attrs.get("data_type") + instance = self.instance if isinstance(self.instance, MetaData) else None + value = attrs.get("data_value", getattr(instance, "data_value", None)) + data_type = attrs.get("data_type", getattr(instance, "data_type", None)) data_file = attrs.get("data_file") + stored_file = getattr(instance, "data_file", None) if not ("project" in attrs or "xform" in attrs or "instance" in attrs): raise serializers.ValidationError( @@ -250,7 +254,7 @@ def validate(self, attrs): if data_file: self._validate_data_file(attrs, data_type, data_file) - if data_type == "media" and data_file is None: + if data_type == MEDIA_TYPE and data_file is None and not stored_file: try: URLValidator()(value) except ValidationError as error: @@ -270,9 +274,9 @@ def validate(self, attrs): xform = obj.xform if isinstance(obj, DataView) else obj request = self.context["request"] user_has_role = ManagerRole.user_has_role - has_perm = user_has_role(request.user, xform) or user_has_role( - request.user, obj.project - ) + has_perm = ( + isinstance(xform, XForm) and user_has_role(request.user, xform) + ) or user_has_role(request.user, obj.project) if not has_perm: raise serializers.ValidationError( {"data_value": _("User has no permission to the dataview.")} From 2812bd0d00447a2885bfb0c34cd80a646907c40c Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Fri, 4 Dec 2026 07:19:56 +0300 Subject: [PATCH 112/120] fix: gate the meta permissions row that a metadata write applies --- .../viewsets/test_stepup_metadata_gates.py | 49 +++++++++++++++++++ onadata/apps/api/viewsets/metadata_viewset.py | 35 ++++++------- 2 files changed, 67 insertions(+), 17 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py index db3b3b9ee4..e2cb8291c2 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py @@ -203,6 +203,55 @@ def test_a_grant_lets_a_promoting_write_back_through(self): self.assertTrue(ManagerRole.user_has_role(self.alice, self.xform)) self.assert_spent(grant) + def _first_and_later_rows(self, first_value, later_value): + """Two meta permissions rows of the form. The write of either applies + the first in primary key order.""" + first = self._meta_perms() + MetaData.objects.filter(pk=first.pk).update(data_value=first_value) + later = MetaData.objects.create( + content_object=self.xform, + data_type=XFORM_META_PERMS, + data_value=later_value, + ) + self.assertLess(first.pk, later.pk) + self.assertEqual(self._meta_perms().data_value, first_value) + return later + + def test_writing_a_later_row_that_reapplies_an_admin_first_row_is_challenged( + self, + ): + """The gate checks the row that the write applies, not the row it + edits.""" + later = self._first_and_later_rows( + EDITOR_BECOMES_MANAGER, EDITOR_STAYS_BELOW_ADMIN + ) + self.assertFalse(ManagerRole.user_has_role(self.alice, self.xform)) + + response = self._update( + later, + {"data_type": XFORM_META_PERMS, "data_value": EDITOR_STAYS_BELOW_ADMIN}, + ) + + self.assert_challenged(response) + self.assertFalse(ManagerRole.user_has_role(self.alice, self.xform)) + + def test_a_grant_lets_the_later_row_reapply_the_first(self): + """With a grant the write goes through and applies the first row.""" + later = self._first_and_later_rows( + EDITOR_BECOMES_MANAGER, EDITOR_STAYS_BELOW_ADMIN + ) + grant = self._grant() + + response = self._update( + later, + {"data_type": XFORM_META_PERMS, "data_value": EDITOR_STAYS_BELOW_ADMIN}, + self._with_grant(grant), + ) + + self.assertEqual(response.status_code, 200, response.data) + self.assertTrue(ManagerRole.user_has_role(self.alice, self.xform)) + self.assert_spent(grant) + def test_a_slot_role_held_only_through_a_team_is_challenged(self): """Applying meta permissions writes a direct grant, which stays after the editor leaves the team that makes them a manager.""" diff --git a/onadata/apps/api/viewsets/metadata_viewset.py b/onadata/apps/api/viewsets/metadata_viewset.py index 93a1555354..03ff20a493 100644 --- a/onadata/apps/api/viewsets/metadata_viewset.py +++ b/onadata/apps/api/viewsets/metadata_viewset.py @@ -50,7 +50,7 @@ #: A reader of these types takes the first of a form's rows. A write of one #: reads the other rows of the form, so it locks the form first. -FIRST_ROW_TYPES = frozenset({PUBLIC_LINK, TEXTIT}) +FIRST_ROW_TYPES = frozenset({PUBLIC_LINK, TEXTIT, XFORM_META_PERMS}) def _meta_perms_slots(value): @@ -144,6 +144,17 @@ def _first_row_after(row, of_type, data_type=None, data_value=None): return rows[min(rows)] if rows else None +def _change_appoints_admins(row, data_type, data_value): + """Whether a change to ``row`` makes the meta permissions that the write + applies to its form appoint owners or managers. + + The write applies the first row of the form, which need not be ``row``.""" + if data_type != XFORM_META_PERMS or row.content_object is None: + return False + applied = _first_row_after(row, XFORM_META_PERMS, data_type, data_value) + return _introduces_admin_meta_perms(row.content_object, applied) + + def _change_turns_on_public_link(row, data_type=None, data_value=None): """Whether a change to ``row``, or its removal, turns on the public link of its form.""" @@ -169,17 +180,10 @@ def _change_redirects_textit(row, data_type=None, data_value=None): return after is not None and after != MetaData.textit(row.content_object) -def _write_changes( - content_object, data_type, data_value, publishes_data, redirects_textit -): - """The ``(action, changed)`` pairs of a write of ``data_value`` as - ``data_type`` on ``content_object``.""" +def _write_changes(appoints, publishes_data, redirects_textit): + """The ``(action, changed)`` pairs of a metadata write.""" return ( - ( - GATE_SHARE_FORM_ADMIN, - lambda: data_type == XFORM_META_PERMS - and _introduces_admin_meta_perms(content_object, data_value), - ), + (GATE_SHARE_FORM_ADMIN, appoints), (GATE_PUBLISH_DATA, publishes_data), (GATE_CHANGE_WEBHOOK, redirects_textit), ) @@ -218,9 +222,8 @@ def refusal_for(data): return self.gated_change_refusal( request, _write_changes( - content_object, - data_type, - data_value, + lambda: data_type == XFORM_META_PERMS + and _introduces_admin_meta_perms(content_object, data_value), lambda: _linked_dataset(data_type, data_value) is not None or ( data_type == PUBLIC_LINK @@ -245,9 +248,7 @@ def refusal_for(instance, validated_data): return self.gated_change_refusal( request, _write_changes( - instance.content_object, - data_type, - data_value, + lambda: _change_appoints_admins(instance, data_type, data_value), lambda: _change_links_dataset(instance, data_type, data_value) or _change_turns_on_public_link(instance, data_type, data_value), lambda: _change_redirects_textit(instance, data_type, data_value), From 5edfb4e527a2eecb50eda2da65796ac5e0ac1c86 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Fri, 4 Dec 2026 07:20:35 +0300 Subject: [PATCH 113/120] fix: hold the project share lock while writing meta permissions --- .../viewsets/test_stepup_metadata_gates.py | 24 +++++++++++++++++++ onadata/apps/api/viewsets/metadata_viewset.py | 9 ++++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py index e2cb8291c2..69929d9912 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_metadata_gates.py @@ -41,6 +41,7 @@ EDITOR_STAYS_BELOW_ADMIN, gating, project_and_form_locks, + project_shares_lock, ) from onadata.libs.utils.common_tags import TEXTIT, XFORM_META_PERMS @@ -252,6 +253,29 @@ def test_a_grant_lets_the_later_row_reapply_the_first(self): self.assertTrue(ManagerRole.user_has_role(self.alice, self.xform)) self.assert_spent(grant) + def test_a_write_takes_the_share_lock_before_the_project(self): + """A repeat share checks the meta permissions under the share lock of + the project and applies them later. A write of them waits for that + lock, so it cannot change them in between. It takes the lock before + the project row, as a share does.""" + metadata = self._meta_perms() + + with CaptureQueriesContext(connection) as queries: + response = self._update( + metadata, + {"data_type": XFORM_META_PERMS, "data_value": DEFAULT_META_PERMS}, + ) + + self.assertEqual(response.status_code, 200, response.data) + share_lock = project_shares_lock(queries, self.xform.project_id) + self.assertIsNotNone(share_lock, "The share lock is not taken.") + project_lock = next( + index + for index, query in enumerate(queries.captured_queries) + if 'FROM "logger_project"' in query["sql"] and "FOR UPDATE" in query["sql"] + ) + self.assertLess(share_lock, project_lock) + def test_a_slot_role_held_only_through_a_team_is_challenged(self): """Applying meta permissions writes a direct grant, which stays after the editor leaves the team that makes them a manager.""" diff --git a/onadata/apps/api/viewsets/metadata_viewset.py b/onadata/apps/api/viewsets/metadata_viewset.py index 03ff20a493..dcdef89783 100644 --- a/onadata/apps/api/viewsets/metadata_viewset.py +++ b/onadata/apps/api/viewsets/metadata_viewset.py @@ -22,6 +22,7 @@ MetaDataSerializer, ) from onadata.libs import filters +from onadata.libs.models.share_project import lock_project_shares from onadata.libs.mixins.authenticate_header_mixin import AuthenticateHeaderMixin from onadata.libs.mixins.cache_control_mixin import CacheControlMixin from onadata.libs.mixins.etags_mixin import ETagsMixin @@ -117,13 +118,19 @@ def _lock_parent(content_object, *data_types): Such writes then run one at a time, from the gate decision to the end of the write. Each one sees the rows that the one before it left. Only a - gate reads those rows, so a deployment that gates nothing takes no lock.""" + gate reads those rows, so a deployment that gates nothing takes no lock. + + A write of meta permissions takes the share lock of the project first. A + repeat share checks them under that lock and then applies them, so they + cannot change in between.""" if ( content_object is not None and FIRST_ROW_TYPES.intersection(data_types) and gated_actions() ): if isinstance(content_object, XForm): + if XFORM_META_PERMS in data_types: + lock_project_shares(content_object.project_id) lock_projects(content_object.project_id) lock_row(type(content_object), content_object.pk) From 29b85f295bba737b9648a329cd04ba5804b5fccc Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Fri, 4 Dec 2026 07:20:56 +0300 Subject: [PATCH 114/120] fix: save only date_modified on the form a metadata row touches --- onadata/apps/main/models/meta_data.py | 10 +++++++++- onadata/apps/main/tests/test_metadata.py | 20 ++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/onadata/apps/main/models/meta_data.py b/onadata/apps/main/models/meta_data.py index ab36e2df2b..682cf61f28 100644 --- a/onadata/apps/main/models/meta_data.py +++ b/onadata/apps/main/models/meta_data.py @@ -661,9 +661,17 @@ def clear_cached_metadata_instance_object( def update_attached_object(sender, instance=None, created=False, **kwargs): """ Save the content_object attached to a MetaData instance. + + A form is saved with its ``date_modified`` only. The copy attached to the + row can be older than a concurrent change, such as an unpublish, and a + full save would write its old values back. """ if instance: - instance.content_object.save() + content_object = instance.content_object + if isinstance(content_object, XForm): + content_object.save(update_fields=["date_modified"]) + else: + content_object.save() # pylint: disable=too-many-locals diff --git a/onadata/apps/main/tests/test_metadata.py b/onadata/apps/main/tests/test_metadata.py index c0a952fc4d..a328f3e54f 100644 --- a/onadata/apps/main/tests/test_metadata.py +++ b/onadata/apps/main/tests/test_metadata.py @@ -185,6 +185,26 @@ def test_caches_cleared(self): self.assertIsNone(cache.get(key_2)) + def test_saving_metadata_keeps_a_newer_form_visibility(self): + """The form attached to a row can be a copy loaded before an unpublish + committed. Saving the row moves only the form's date_modified.""" + XForm.objects.filter(pk=self.xform.pk).update(shared=True, shared_data=True) + stale = XForm.objects.get(pk=self.xform.pk) + XForm.objects.filter(pk=self.xform.pk).update(shared=False, shared_data=False) + before = XForm.objects.get(pk=self.xform.pk).date_modified + + row = MetaData.objects.create( + content_object=stale, + data_type="enketo_url", + data_value="https://enketo.example.com/form", + ) + + self.assertIs(row.content_object, stale) + self.xform.refresh_from_db() + self.assertFalse(self.xform.shared) + self.assertFalse(self.xform.shared_data) + self.assertGreater(self.xform.date_modified, before) + def test_restore_deleted(self): """Soft deleted MetaData is restored""" # Create metadata and soft delete From 468062c48066c5f362b213312cbb9f6544bc6581 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Fri, 4 Dec 2026 07:21:58 +0300 Subject: [PATCH 115/120] fix: set a moved form's visibility under the move's locks --- .../test_stepup_form_and_transfer_gates.py | 45 +++++++++++++++++++ onadata/apps/api/tools.py | 10 ++++- onadata/libs/utils/xform_utils.py | 28 ++++++++---- 3 files changed, 72 insertions(+), 11 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py index d9400e7be9..6c0f93a752 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py @@ -14,6 +14,7 @@ from django.shortcuts import get_object_or_404 from django.test.utils import CaptureQueriesContext, override_settings +from kombu.exceptions import OperationalError from oidc.stepup_grants import spend_grant from onadata.apps.api.tools import add_user_to_organization @@ -36,6 +37,7 @@ gating, project_and_form_locks, ) +from onadata.libs.utils.xform_utils import set_project_perms_to_xform_async ONE_GATED_CHANGE = "one_gated_change_per_request" @@ -490,6 +492,49 @@ def test_moving_a_public_form_is_not_challenged(self): self._reload() self.assertEqual(self.xform.project, self.public_project) + def test_the_move_itself_makes_the_form_public(self): + """The visibility changes under the move's locks, not in the queued + permission task.""" + with patch("onadata.apps.api.tools.set_project_perms_to_xform_async") as task: + response = self._move(self.public_project, self._with_grant(self._grant())) + + self.assertEqual(response.status_code, 201, response.data) + task.delay.assert_called_once() + self._reload() + self.assertTrue(self.xform.shared) + self.assertTrue(self.xform.shared_data) + + def test_the_queued_task_keeps_a_later_unpublish(self): + """A public form moves without a grant. An unpublish that commits + before the queued task runs stays: the task does not publish the form + again.""" + XForm.objects.filter(pk=self.xform.pk).update(shared=True, shared_data=True) + with patch("onadata.apps.api.tools.set_project_perms_to_xform_async") as task: + response = self._move(self.public_project) + self.assertEqual(response.status_code, 201, response.data) + XForm.objects.filter(pk=self.xform.pk).update(shared=False, shared_data=False) + + args, kwargs = task.delay.call_args + set_project_perms_to_xform_async(*args, **kwargs) + + self._reload() + self.assertEqual(self.xform.project, self.public_project) + self.assertFalse(self.xform.shared) + self.assertFalse(self.xform.shared_data) + + def test_the_synchronous_fallback_leaves_visibility_alone(self): + """Without a broker the permissions apply in the request, after the + move's locks are gone, so they skip the visibility too.""" + with patch( + "onadata.apps.api.tools.set_project_perms_to_xform_async.delay", + side_effect=OperationalError, + ), patch("onadata.apps.api.tools.set_project_perms_to_xform") as fallback: + response = self._move(self.public_project, self._with_grant(self._grant())) + + self.assertEqual(response.status_code, 201, response.data) + fallback.assert_called_once() + self.assertEqual(fallback.call_args.kwargs, {"set_visibility": False}) + def test_an_invalid_move_keeps_the_grant(self): """The id_string check comes first, so a clash does not spend it.""" self.assert_challenged(self._move(self.public_project)) diff --git a/onadata/apps/api/tools.py b/onadata/apps/api/tools.py index 69eddbe21d..a04c67cfe7 100644 --- a/onadata/apps/api/tools.py +++ b/onadata/apps/api/tools.py @@ -91,6 +91,7 @@ from onadata.libs.utils.xform_utils import ( set_project_perms_to_xform, set_project_perms_to_xform_async, + set_project_visibility_to_xform, ) DECIMAL_PRECISION = 2 @@ -505,14 +506,19 @@ def id_string_exists_in_account(): xform.save(update_fields=["user", "project"]) except IntegrityError as e: raise exceptions.ParseError(_(msg)) from e + # Under the locks, so an unpublish cannot come between the gate + # and this change. + set_project_visibility_to_xform(xform, project) # First assign permissions to the person who uploaded the form OwnerRole.add(request.user, xform) try: # Next run async task to apply all other perms - set_project_perms_to_xform_async.delay(xform.pk, project.pk) + set_project_perms_to_xform_async.delay( + xform.pk, project.pk, set_visibility=False + ) except OperationalError: # Apply permissions synchrounously - set_project_perms_to_xform(xform, project) + set_project_perms_to_xform(xform, project, set_visibility=False) else: xform = publish_form(set_form) diff --git a/onadata/libs/utils/xform_utils.py b/onadata/libs/utils/xform_utils.py index ce8eb169e0..0cf294581c 100644 --- a/onadata/libs/utils/xform_utils.py +++ b/onadata/libs/utils/xform_utils.py @@ -68,18 +68,28 @@ def get_team_members(org_username): return members -def set_project_perms_to_xform(xform, project): - """ - Apply project permissions to a form, this usually happens when a new form - is being published or it is being moved to a new project. - """ +def set_project_visibility_to_xform(xform, project): + """Make a form that is not shared as public as ``project``.""" # allows us to still use xform.shared and xform.shared_data as before # only switch if xform.shared is False xform_is_shared = xform.shared or xform.shared_data if not xform_is_shared and project.shared != xform.shared: xform.shared = project.shared xform.shared_data = project.shared - xform.save() + xform.save(update_fields=["shared", "shared_data"]) + + +def set_project_perms_to_xform(xform, project, set_visibility=True): + """ + Apply project permissions to a form, this usually happens when a new form + is being published or it is being moved to a new project. + + A move sets the visibility under its own locks and passes + ``set_visibility=False``. Done later, the change could undo an unpublish + that committed in between. + """ + if set_visibility: + set_project_visibility_to_xform(xform, project) # clear existing permissions for perm in get_object_users_with_permissions(xform, with_group_users=True): @@ -235,7 +245,7 @@ def roles_under_meta_perms(values, role_name): # pylint: disable=invalid-name @app.task(bind=True, max_retries=3) -def set_project_perms_to_xform_async(self, xform_id, project_id): +def set_project_perms_to_xform_async(self, xform_id, project_id, set_visibility=True): """ Apply project permissions for ``project_id`` to a form ``xform_id`` task. """ @@ -258,13 +268,13 @@ def _set_project_perms(): report_exception(msg, e, sys.exc_info()) self.retry(countdown=60 * self.request.retries, exc=e) else: - set_project_perms_to_xform(xform, project) + set_project_perms_to_xform(xform, project, set_visibility) update_role_by_meta_xform_perms(xform) # Set MergedXForm permissions if XForm is also a MergedXForm if hasattr(xform, "mergedxform"): - set_project_perms_to_xform(xform.mergedxform, project) + set_project_perms_to_xform(xform.mergedxform, project, set_visibility) try: if getattr(settings, "SLAVE_DATABASES", []): From d614e429d2a66b7962ac672988d3be5633f42792 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Fri, 4 Dec 2026 07:22:43 +0300 Subject: [PATCH 116/120] fix: lock the project before the form when a submission is deleted --- onadata/apps/logger/models/instance.py | 19 ++++++++++++ .../apps/logger/tests/models/test_instance.py | 29 +++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/onadata/apps/logger/models/instance.py b/onadata/apps/logger/models/instance.py index 484c14f43a..c2895cbff3 100644 --- a/onadata/apps/logger/models/instance.py +++ b/onadata/apps/logger/models/instance.py @@ -28,6 +28,7 @@ from multidb.pinning import use_master from taggit.managers import TaggableManager +from onadata.apps.logger.models.project import Project from onadata.apps.logger.models.submission_review import SubmissionReview from onadata.apps.logger.models.survey_type import SurveyType from onadata.apps.logger.models.xform import ( @@ -305,9 +306,27 @@ def update_xform_submission_count(instance): clear_project_cache(instance.xform.project_id) +def _lock_project_of_form(xform_pk): + """Lock the project row of form ``xform_pk`` until the transaction ends. + + A form save updates its project's row. Other writers of both rows lock the + project before the form, so this one does too, or the two can deadlock. + ``FOR NO KEY UPDATE`` is the lock that the update takes anyway, so it + holds up nothing more.""" + project_pk = ( + XForm.objects.filter(pk=xform_pk).values_list("project_id", flat=True).first() + ) + list( + Project.objects.select_for_update(no_key=True) + .filter(pk=project_pk) + .values_list("pk", flat=True) + ) + + def _update_xform_submission_count_delete(instance): """Updates the XForm submissions count on deletion of a submission.""" with transaction.atomic(): + _lock_project_of_form(instance.xform_id) try: xform = XForm.objects.select_for_update().get(pk=instance.xform.pk) except XForm.DoesNotExist: diff --git a/onadata/apps/logger/tests/models/test_instance.py b/onadata/apps/logger/tests/models/test_instance.py index 7cfa8b6115..bb1f90a9b0 100644 --- a/onadata/apps/logger/tests/models/test_instance.py +++ b/onadata/apps/logger/tests/models/test_instance.py @@ -13,6 +13,7 @@ from django.db import connection from django.http.request import HttpRequest from django.test import TestCase, override_settings +from django.test.utils import CaptureQueriesContext from django_digest.test import DigestAuth @@ -1512,6 +1513,34 @@ def test_hard_delete_xform_num_of_decrypted_submissions_decremented( mock_adjust.assert_called_once_with(self.xform.pk, delta=-1) + def test_hard_delete_locks_the_project_before_the_form(self): + """The count update saves the form, which updates the project row. + A metadata write locks the project and then the form, so the count + update takes them in the same order, or the two can deadlock.""" + self._publish_transportation_form() + self._make_submissions() + instance = Instance.objects.filter(xform=self.xform).first() + + with CaptureQueriesContext(connection) as queries: + instance.delete() + + statements = [query["sql"] for query in queries.captured_queries] + project_lock = next( + ( + index + for index, sql in enumerate(statements) + if 'FROM "logger_project"' in sql and "FOR NO KEY UPDATE" in sql + ), + None, + ) + form_lock = next( + index + for index, sql in enumerate(statements) + if 'FROM "logger_xform"' in sql and sql.endswith("FOR UPDATE") + ) + self.assertIsNotNone(project_lock, "The project row is not locked.") + self.assertLess(project_lock, form_lock) + def test_dynamic_metadata_preserved(self): """Existing dynamic metadata is preserved when saving Instance""" self._publish_transportation_form_and_submit_instance() From 4a602913dcb25a879bf017a8783b8e256ac4e77b Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Fri, 4 Dec 2026 07:23:09 +0300 Subject: [PATCH 117/120] fix: save a transferred project's new name with its new owner --- .../test_stepup_form_and_transfer_gates.py | 19 +++++++++++++++++++ .../management/commands/transferproject.py | 17 ++++++++++++++--- .../libs/serializers/project_serializer.py | 1 + 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py index 6c0f93a752..d2020b6d8d 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_form_and_transfer_gates.py @@ -163,6 +163,25 @@ def test_a_name_taken_in_the_new_account_keeps_the_grant(self): self.assertEqual(self._owner(), self.user) self.assertFalse(OwnerRole.user_has_role(self.org_user, self.project)) + def test_a_renaming_transfer_does_not_clash_on_the_old_name(self): + """The new account has a project under the old name only. The + transfer writes the new owner and the new name in one save, so the + old name never lands there.""" + Project.objects.create( + name="demo", organization=self.org_user, created_by=self.user + ) + self.assertEqual(self.project.name, "demo") + grant = self._grant() + + response = self._patch( + {"owner": self.org_url, "name": "renamed"}, self._with_grant(grant) + ) + + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(self._owner(), self.org_user) + self.assertEqual(self.project.name, "renamed") + self.assert_spent(grant) + def test_a_transfer_without_permission_hides_the_names_there(self): """A caller who cannot add projects to an account gets the permission error, whether or not the name is taken there. The stored name differs diff --git a/onadata/apps/logger/management/commands/transferproject.py b/onadata/apps/logger/management/commands/transferproject.py index 6ab7a29f41..5d95a5cef5 100644 --- a/onadata/apps/logger/management/commands/transferproject.py +++ b/onadata/apps/logger/management/commands/transferproject.py @@ -50,6 +50,14 @@ def add_arguments(self, parser): type=int, help="Id of the project to be transferred.", ) + parser.add_argument( + "--project-name", + dest="project_name", + type=str, + help="New name of the project given by --project-id. The first " + "save in the new account writes it, so the old name cannot clash " + "there.", + ) parser.add_argument( "--all-projects", dest="all_projects", @@ -90,10 +98,12 @@ def _transfer_merged_xform(self, project, to_user): form.save() set_project_perms_to_xform(form, project) - def transfer_project(self, project, to_user): - """Transfer Project to the new owner.""" + def transfer_project(self, project, to_user, name=None): + """Transfer Project to the new owner, renamed to ``name`` if given.""" project.organization = to_user project.created_by = to_user + if name: + project.name = name project.save() set_project_permissions(Project, project, created=True) @@ -148,7 +158,8 @@ def handle(self, *args, **options): else: projects = Project.objects.filter(id=project_id, organization=from_user) + name = None if transfer_all_projects else options.get("project_name") for project in projects: - self.transfer_project(project, to_user) + self.transfer_project(project, to_user, name) self.stdout.write("Projects transferred successfully") diff --git a/onadata/libs/serializers/project_serializer.py b/onadata/libs/serializers/project_serializer.py index 2eb6f6b069..fa223c73de 100644 --- a/onadata/libs/serializers/project_serializer.py +++ b/onadata/libs/serializers/project_serializer.py @@ -602,6 +602,7 @@ def update(self, instance, validated_data): current_owner=instance.organization, new_owner=owner, project_id=instance.pk, + project_name=validated_data.get("name"), ) # Again after commit: a read during the transfer can re-cache From 410bf8b79db336a052a141ca9d5f5a845eafe211 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Fri, 4 Dec 2026 07:24:09 +0300 Subject: [PATCH 118/120] fix: lock the project and form a dataview gate reads --- .../viewsets/test_stepup_dataview_gates.py | 60 ++++++++++++++++++- onadata/apps/api/viewsets/dataview_viewset.py | 57 ++++++++++++++++-- 2 files changed, 111 insertions(+), 6 deletions(-) diff --git a/onadata/apps/api/tests/viewsets/test_stepup_dataview_gates.py b/onadata/apps/api/tests/viewsets/test_stepup_dataview_gates.py index 76f9e2c561..3df86143c8 100644 --- a/onadata/apps/api/tests/viewsets/test_stepup_dataview_gates.py +++ b/onadata/apps/api/tests/viewsets/test_stepup_dataview_gates.py @@ -7,6 +7,8 @@ import os from django.conf import settings +from django.db import connection +from django.test.utils import CaptureQueriesContext from onadata.apps.api.tests.viewsets.test_stepup_form_and_transfer_gates import ( GateTestCase, @@ -15,7 +17,7 @@ from onadata.apps.logger.models import DataView, Project, XForm from onadata.libs.permissions import ManagerRole from onadata.libs.stepup.policy import GATE_PUBLISH_DATA -from onadata.libs.test_utils.stepup import gating +from onadata.libs.test_utils.stepup import gating, project_and_form_locks COLUMNS = '["name", "age"]' @@ -185,3 +187,59 @@ def test_renaming_one_in_a_public_project_is_not_challenged(self): dataview.refresh_from_db() self.assertEqual(dataview.name, "renamed") self.assertEqual(dataview.columns, ["name"]) + + @staticmethod + def _first_index(queries, *fragments): + return next( + index + for index, query in enumerate(queries.captured_queries) + if all(fragment in query["sql"] for fragment in fragments) + ) + + def test_a_create_locks_the_project_and_the_form_before_the_insert(self): + """The gate reads the visibility of the destination project and the + source form. The create locks both rows, project first, and holds them + through the insert, so an unpublish cannot come between.""" + with CaptureQueriesContext(connection) as queries: + response = self._create(self.private_project) + + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual( + project_and_form_locks(queries), + [ + ("logger_project", self.private_project.pk), + ("logger_xform", self.xform.pk), + ], + ) + self.assertLess( + self._first_index(queries, 'FROM "logger_xform"', "FOR UPDATE"), + self._first_index(queries, 'INSERT INTO "logger_dataview"'), + ) + + def test_an_update_locks_the_projects_and_the_form_before_the_dataview(self): + """A move reads the destination project, which the request names, and + the source form. The update locks the projects, then the form, then + the dataview, as a form save writes the form and then its project.""" + dataview = self._dataview(self.private_project) + self.assertLess(self.private_project.pk, self.public_project.pk) + + with CaptureQueriesContext(connection) as queries: + response = self._patch( + dataview, + {"project": self._url("projects", self.public_project.pk)}, + self._with_grant(self._grant()), + ) + + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual( + project_and_form_locks(queries), + [ + ("logger_project", self.private_project.pk), + ("logger_project", self.public_project.pk), + ("logger_xform", self.xform.pk), + ], + ) + self.assertLess( + self._first_index(queries, 'FROM "logger_xform"', "FOR UPDATE"), + self._first_index(queries, 'FROM "logger_dataview"', "FOR UPDATE"), + ) diff --git a/onadata/apps/api/viewsets/dataview_viewset.py b/onadata/apps/api/viewsets/dataview_viewset.py index 88268ac9c2..1332dbb434 100644 --- a/onadata/apps/api/viewsets/dataview_viewset.py +++ b/onadata/apps/api/viewsets/dataview_viewset.py @@ -3,6 +3,7 @@ import json +from django.db import transaction from django.db.models.signals import post_delete, post_save from django.http import Http404, HttpResponseBadRequest from django.utils.translation import gettext as _ @@ -10,7 +11,7 @@ from celery.result import AsyncResult from rest_framework import status from rest_framework.decorators import action -from rest_framework.exceptions import ParseError +from rest_framework.exceptions import ParseError, ValidationError from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework.settings import api_settings @@ -18,6 +19,7 @@ from onadata.apps.api.permissions import DataViewViewsetPermissions from onadata.apps.api.tools import get_baseviewset_class +from onadata.apps.logger.models import XForm from onadata.apps.logger.models.data_view import DEFAULT_COLUMNS, DataView from onadata.apps.viewer.models.export import Export from onadata.libs.mixins.authenticate_header_mixin import AuthenticateHeaderMixin @@ -32,7 +34,8 @@ from onadata.libs.serializers.geojson_serializer import GeoJsonSerializer from onadata.libs.serializers.xform_serializer import XFormSerializer from onadata.libs.stepup import RequiresStepUp -from onadata.libs.stepup.policy import GATE_PUBLISH_DATA +from onadata.libs.stepup.drf import lock_projects, lock_rows, locked_for_gates +from onadata.libs.stepup.policy import GATE_PUBLISH_DATA, gated_actions from onadata.libs.utils import common_tags from onadata.libs.utils.api_export_tools import ( custom_response_handler, @@ -93,6 +96,14 @@ def _publishes_data(dataview, validated_data): ) +def _lock_projects_and_forms(project_pks, xforms): + """Lock the projects ``project_pks`` and those of ``xforms``, then the + forms, as ``lock_projects`` explains. None is skipped.""" + xforms = [xform for xform in xforms if xform is not None] + lock_projects(*project_pks, *(xform.project_id for xform in xforms)) + lock_rows(XForm, pk__in={xform.pk for xform in xforms}) + + def _runtime_query_columns(query): """Return field names referenced by a JSON runtime query.""" if not query: @@ -178,9 +189,45 @@ def _publish_refusal(self, request, dataview, validated_data): return None def create(self, request, *args, **kwargs): - return self.gated_create( - request, lambda data: self._publish_refusal(request, None, data) - ) + """The gate reads the visibility of the project and the form under + locks that the save holds too, so an unpublish cannot come between.""" + + def refusal_for(data): + project, xform = data.get("project"), data.get("xform") + if gated_actions(): + _lock_projects_and_forms([getattr(project, "pk", None)], [xform]) + if project is not None: + project.refresh_from_db(fields=["shared"]) + if xform is not None: + xform.refresh_from_db(fields=["shared_data"]) + return self._publish_refusal(request, None, data) + + with transaction.atomic(): + return self.gated_create(request, refusal_for) + + def _named_in(self, request, field_name): + """The object that ``request`` names in ``field_name``, or None when + it names none or an invalid one, which validation refuses.""" + data = request.data if isinstance(request.data, dict) else {} + if field_name not in data: + return None + field = self.get_serializer().fields[field_name] + try: + return field.to_internal_value(data[field_name]) + except ValidationError: + return None + + def _locked_for_update(self, request, instance): + """The data view, locked after the projects and forms whose visibility + the gate reads: those it has and those the request names. Validation + and the gate then read them on the locked rows.""" + if gated_actions(): + project = self._named_in(request, "project") + _lock_projects_and_forms( + [instance.project_id, getattr(project, "pk", None)], + [instance.xform, self._named_in(request, "xform")], + ) + return locked_for_gates(instance) def update(self, request, *args, **kwargs): return self.gated_update( From 92e2b8199d9d6cc4221ec1d5e3e3596026dad45e Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Fri, 4 Dec 2026 07:25:19 +0300 Subject: [PATCH 119/120] fix: save only date_modified on the project a metadata row touches --- onadata/apps/main/models/meta_data.py | 10 +++++----- onadata/apps/main/tests/test_metadata.py | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/onadata/apps/main/models/meta_data.py b/onadata/apps/main/models/meta_data.py index 682cf61f28..ed80f48f84 100644 --- a/onadata/apps/main/models/meta_data.py +++ b/onadata/apps/main/models/meta_data.py @@ -25,7 +25,7 @@ import requests -from onadata.apps.logger.models import EntityList, XForm +from onadata.apps.logger.models import EntityList, Project, XForm from onadata.apps.logger.models.data_view import DataView from onadata.libs.utils.cache_tools import ( ENKETO_PREVIEW_URL_CACHE, @@ -662,13 +662,13 @@ def update_attached_object(sender, instance=None, created=False, **kwargs): """ Save the content_object attached to a MetaData instance. - A form is saved with its ``date_modified`` only. The copy attached to the - row can be older than a concurrent change, such as an unpublish, and a - full save would write its old values back. + A form or project is saved with its ``date_modified`` only. The copy + attached to the row can be older than a concurrent change, such as an + unpublish, and a full save would write its old values back. """ if instance: content_object = instance.content_object - if isinstance(content_object, XForm): + if isinstance(content_object, (XForm, Project)): content_object.save(update_fields=["date_modified"]) else: content_object.save() diff --git a/onadata/apps/main/tests/test_metadata.py b/onadata/apps/main/tests/test_metadata.py index a328f3e54f..a8dca91ba1 100644 --- a/onadata/apps/main/tests/test_metadata.py +++ b/onadata/apps/main/tests/test_metadata.py @@ -205,6 +205,25 @@ def test_saving_metadata_keeps_a_newer_form_visibility(self): self.assertFalse(self.xform.shared_data) self.assertGreater(self.xform.date_modified, before) + def test_saving_metadata_keeps_a_newer_project_visibility(self): + """As for a form, a row attached to a stale copy of a project moves + only the project's date_modified.""" + project = self.xform.project + Project.objects.filter(pk=project.pk).update(shared=True) + stale = Project.objects.get(pk=project.pk) + Project.objects.filter(pk=project.pk).update(shared=False) + before = Project.objects.get(pk=project.pk).date_modified + + MetaData.objects.create( + content_object=stale, + data_type="supporting_doc", + data_value="notes", + ) + + project.refresh_from_db() + self.assertFalse(project.shared) + self.assertGreater(project.date_modified, before) + def test_restore_deleted(self): """Soft deleted MetaData is restored""" # Create metadata and soft delete From 54dff94f27c819d56c28e66c30a0d28b8c440401 Mon Sep 17 00:00:00 2001 From: FrankApiyo Date: Fri, 4 Dec 2026 08:31:13 +0300 Subject: [PATCH 120/120] test: expect the visibility flag in the merged dataset permission task --- onadata/libs/tests/utils/test_project_utils.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/onadata/libs/tests/utils/test_project_utils.py b/onadata/libs/tests/utils/test_project_utils.py index 5191b67b61..1a6f3900da 100644 --- a/onadata/libs/tests/utils/test_project_utils.py +++ b/onadata/libs/tests/utils/test_project_utils.py @@ -94,8 +94,8 @@ def test_set_project_perms_to_xform_async_mergedxform(self, mock): merged_xf = self._create_merged_dataset() set_project_perms_to_xform_async.delay(merged_xf.pk, self.project.pk) expected_calls = [ - call(merged_xf.xform_ptr, self.project), - call(merged_xf, self.project), + call(merged_xf.xform_ptr, self.project, True), + call(merged_xf, self.project, True), ] mock.assert_has_calls(expected_calls, any_order=True)