Repository navigation
feat: add step-up authentication for sensitive account actions - #3215
FrankApiyo wants to merge 120 commits into
Conversation
997ea08 to
617dffa
Compare
afbbc6a to
ecc8ee3
Compare
d3797e6 to
19d2b1c
Compare
5799b9f to
af118e4
Compare
6d33f67 to
0d13046
Compare
af118e4 to
1bd7149
Compare
7532dd9 to
d29ef14
Compare
1bd7149 to
e3c5c58
Compare
00d9c16 to
5a1adfb
Compare
d0c2148 to
0638997
Compare
5a1adfb to
4042f52
Compare
35e5214 to
11c8d60
Compare
b90ed42 to
3f6f571
Compare
11c8d60 to
5fe1dc3
Compare
5fe1dc3 to
c6281e3
Compare
9cd079d to
7a0b620
Compare
68df7e3 to
3e692d9
Compare
7a0b620 to
46c4cba
Compare
1cbeb48 to
2518c4b
Compare
ukanga
left a comment
There was a problem hiding this comment.
A form move can restore public visibility or give the requester ownership without step-up. Queued shares can add or restore admin access, and a team rename can confer organisation ownership. An invitation update can undo a concurrent revocation, and a failed cache write can consume a recovery code without issuing a grant.
| if check_move: | ||
| check_move(xform) |
There was a problem hiding this comment.
The move checks step-up against an unlocked form, then saves the full row. A concurrent unpublish can commit between those operations, and the save can restore the old shared or shared_data flag without a publish-data grant. Lock and reread the form and affected projects before checking the move, hold the locks through the save, and limit the save to the fields the move changes.
There was a problem hiding this comment.
| def appoints_admins_not_covered_by_a_transfer(): | ||
| if transfers and is_gated(GATE_TRANSFER_PROJECT): | ||
| return False | ||
| return move_appoints_admins(xform, project) |
There was a problem hiding this comment.
The admin check only accounts for metadata-based promotions. publish_project_xform also assigns OwnerRole directly to the requester before the worker runs. On a same-account move, a form manager can gain owner-only permissions, including ownership transfer, without a share-form-admin grant. Include this assignment in the gate when the requester lacks a direct owner grant and a transfer grant does not cover the move.
There was a problem hiding this comment.
This OwnerRole.add call is the same on main, so I will raise it separately. Today owner adds only transfer_xform and move_xform over manager on a form, and no API check reads them. The fix is to give the requester ManagerRole unless they already hold owner.
| shared = member_admin_roles( | ||
| organization.user.project_org.all(), members_team, user, role_name | ||
| ) | ||
| return not holds_roles(user, shared) |
There was a problem hiding this comment.
The member gate can waive step-up because the recipient already holds the project and form roles. Both API versions then call add_user_to_organization, which queues unconditional project shares. A queued share can restore administrative access after a downgrade or removal has taken effect on the project. Carry the grant waiver into the queued jobs and use the worker's locked repeat-only check before applying each share.
There was a problem hiding this comment.
Fixed in 1fde320. When the gate lets a member through because they hold the roles already, add_user_to_organization queues the project shares with repeat_only, on v1 and v2. The worker then skips a share that a later downgrade made new.
| 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) |
There was a problem hiding this comment.
The team update gate only checks organisation changes. TeamSerializer also accepts renames, and OrganizationProfile.is_organization_owner identifies owners by membership in the group with the canonical Owners name. When that name is available, renaming a populated team to it gives its members organisation-owner authority without a grant. Require grant-org-admin when an update would give a team the canonical Owners name.
There was a problem hiding this comment.
Fixed in 1fde320. A team update that gives a team with members its organisation's Owners name needs grant-org-admin. The check computes the stored name as Team.save does, so Owners and <org>#Owners both count. If the same update also moves the team, the answer is one_gated_change_per_request.
| if not granted: | ||
| return None |
There was a problem hiding this comment.
When a share would grant no admin roles at request time, this branch queues an unrestricted task. ShareProject reads the form metadata again, so a mapping added before the task runs can turn a queued lower-role share into a direct admin grant. Mark this branch repeat_only so the worker checks whether the share would add admin permissions before applying it.
| if not granted: | |
| return None | |
| if not granted: | |
| validated_data["repeat_only"] = True | |
| return None |
There was a problem hiding this comment.
Applied in 1fde320. One effect: if a promoting mapping appears before the task runs, the worker skips the whole share, not only the promotion. The user can share again and pass the gate.
| serializer.check_can_save() | ||
| refusal = self._invite_admin_refusal( | ||
| request, serializer.validated_data, invitation | ||
| ) | ||
| if refusal is not None: | ||
| return refusal | ||
| serializer.save() |
There was a problem hiding this comment.
An unchanged admin invitation can pass the gate on an unlocked pending row. If revocation commits before the serializer's full-row save, that save can restore the pending status and let the account-creation hook grant access. Lock the invitation from the pending-status check through the update. Limit resend writes to resent_at so a resend cannot restore stale status either.
There was a problem hiding this comment.
Fixed in 1fde320 for the update. It locks the invitation row from the pending check through the save. The resend race is the same on main, because the resend saves the whole row. I will raise it separately, with the conditional update that you describe.
| 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, | ||
| ) |
There was a problem hiding this comment.
Recovery-code verification commits consumption before issue_grant writes to the cache. If that write fails, the endpoint returns 503 and the user cannot retry with the same recovery code. Wrap verification and grant issuance in one database transaction, and catch CacheWriteFailed outside it so the failure rolls back code consumption.
There was a problem hiding this comment.
Fixed in 1fde320. Verification and issue_grant now run in one transaction, and CacheWriteFailed is caught outside it. A failed cache write rolls back the code consumption, so the user can retry with the same code.
ukanga
left a comment
There was a problem hiding this comment.
Metadata updates can expose entity-list exports, restore stale form visibility, or apply unchecked admin roles. Queued shares, form moves, and DataView writes can act on state that changed after their step-up checks. The metadata lock order can also deadlock with submission deletion, and a project transfer can spend a grant and fail even when the requested new name is free.
| parts = data_value.split() | ||
| tag = next( | ||
| (tag for tag in (DATAVIEW_TAG, XFORM_TAG) if data_value.startswith(tag)), | ||
| None, |
There was a problem hiding this comment.
The publication gate recognizes form and DataView links, while the form media handler also serves entity-list exports. A partial metadata update that changes the value of an existing media row can omit the type and skip the serializer's link validation. The media handler then serves the entity-list export to readers of the host form without checking access to the target or requiring a publish-data grant. Validate against the effective metadata type and use the same link types for target authorization, the publication gate, and downloads.
There was a problem hiding this comment.
Fixed in 8b06849. The serializer now validates a partial update against the stored type and value when the request omits them. LINKED_DATASET_MODELS in the metadata model now lists form, dataview and entity-list links in one place. The target check, the publication gate and the media download all read it, and an entity-list target needs a manager role on its project. Tests: test_linking_an_entity_list_is_challenged, test_turning_a_url_row_into_an_entity_list_link_is_challenged and test_a_patch_cannot_link_data_the_user_cannot_manage.
| 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( | ||
| instance.content_object, | ||
| data_type, | ||
| data_value, |
There was a problem hiding this comment.
The gate checks the edited row's mapping, but MetaDataSerializer.update reapplies the first stored form-role mapping. The database permits multiple mappings with different values. If the first maps editors to managers, saving a later row with an ordinary mapping can promote current editors without a share-form-admin grant. Check the effective mapping after the proposed update in the same primary-key order the writer uses.
There was a problem hiding this comment.
Fixed in 2812bd0. An update now gates the meta permissions that the write will apply. That is the first row in primary key order after the change, the same row that update_role_by_meta_xform_perms reads. Meta permissions writes also lock the project and the form now, like the other first-row types. Tests: test_writing_a_later_row_that_reapplies_an_admin_first_row_is_challenged and test_a_grant_lets_the_later_row_reapply_the_first.
| 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) |
There was a problem hiding this comment.
The update loads and caches the attached XForm before locking it. The metadata post-save handler later saves that same XForm in full. If an unpublish commits before the metadata update obtains the lock, the handler can write the old shared or shared_data flag back and restore public access. Limit the handler's save on an attached XForm to date_modified.
There was a problem hiding this comment.
Fixed in 29b85f2. update_attached_object now saves an attached form with update_fields=["date_modified"], so a stale copy cannot write back shared or shared_data. Other content objects still get a full save. Test: test_saving_metadata_keeps_a_newer_form_visibility in onadata/apps/main/tests/test_metadata.py.
92e2b81 does the same for a project attached to a metadata row, which had the same problem with its shared flag. Test: test_saving_metadata_keeps_a_newer_project_visibility.
| if check_move: | ||
| check_move(xform) | ||
| xform.user = project.organization | ||
| xform.project = project | ||
|
|
||
| try: | ||
| with transaction.atomic(): | ||
| xform.save(update_fields=["user", "project"]) |
There was a problem hiding this comment.
The move holds locks through its save, but set_project_perms_to_xform can still change visibility after those locks are released. If the move waives step-up because the form is already public, an unpublish can commit before the queued task runs. The task then sees a private form in a public project and publishes it again without a grant. Apply any move-related visibility change inside the locked transaction and make both the queued permission task and its synchronous fallback skip visibility changes for moves.
There was a problem hiding this comment.
Fixed in 468062c. The move now applies the visibility change inside its locked transaction, through the new set_project_visibility_to_xform. The queued task and its synchronous fallback get set_visibility=False, so they no longer touch shared or shared_data on a move. A publish still sets visibility as before. Tests: test_the_move_itself_makes_the_form_public, test_the_queued_task_keeps_a_later_unpublish and test_the_synchronous_fallback_leaves_visibility_alone.
| 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() |
There was a problem hiding this comment.
The repeat-share worker checks the form-role mappings under the project advisory lock, then ShareProject.save reads them again. Metadata writers can change those mappings without taking that lock. A mapping that commits between the two reads can turn a lower-role share into a direct owner or manager grant without step-up. Have the worker apply the same role assignments it checked, or make mapping writers take the same advisory lock through commit.
There was a problem hiding this comment.
Fixed in 5edfb4e. A metadata write of xform_meta_perms now takes the project's share lock before the project and form row locks, and holds it until commit. A repeat share therefore cannot see the mappings change between its check and ShareProject.save. I chose this over passing the checked roles to the worker because it is one call in _lock_parent. The other way would change ShareProject.save for every share path. Test: test_a_write_takes_the_share_lock_before_the_project.
| if isinstance(content_object, XForm): | ||
| lock_projects(content_object.project_id) | ||
| lock_row(type(content_object), content_object.pk) |
There was a problem hiding this comment.
Metadata writes lock the project before the form. Submission deletion locks the form in _update_xform_submission_count_delete, then calls XForm.save, whose pre-save signal updates the project. Concurrent operations on the same form can deadlock and PostgreSQL will abort one transaction. Have the submission counter update acquire the project lock before the form lock as well.
There was a problem hiding this comment.
Fixed in d614e42. _update_xform_submission_count_delete now locks the form's project before it locks the form. That is the same order that metadata writes and moves use. It takes FOR NO KEY UPDATE, which is the lock the project update takes anyway, so it blocks nothing new. Test: test_hard_delete_locks_the_project_before_the_form.
| name = name or self.instance.name | ||
| if Project.objects.filter( | ||
| name__iexact=name, organization=organization | ||
| ).exists(): |
There was a problem hiding this comment.
The transfer preflight checks the requested name, but transferproject first saves the project under its old name in the destination organization. If that organization already has a project with the old name, a transfer with a free new name passes validation, spends the grant, and fails on the unique constraint. Pass the validated name into the command so its first save writes the new owner and name together.
There was a problem hiding this comment.
Fixed in 4a60291. transferproject takes a new --project-name option, and the serializer passes the validated name to it. The command's first save then writes the new owner and the new name together. Test: test_a_renaming_transfer_does_not_clash_on_the_old_name.
| 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 |
There was a problem hiding this comment.
The DataView gate bases its decision on the source form's and destination project's visibility. Create locks neither row, and update locks only the DataView. If the source is unpublished after the check, the DataView write can still expose its rows through the public destination without a publish-data grant. Lock and reread both visibility rows before the decision and hold the locks through the DataView save.
There was a problem hiding this comment.
Fixed in 410bf8b. A create now locks the destination project and the source form's project, then the form. It reads their visibility again and holds the locks through the insert. An update locks the current and requested projects, then the forms, before the dataview row, so validation and the gate read locked rows. Tests: test_a_create_locks_the_project_and_the_form_before_the_insert and test_an_update_locks_the_projects_and_the_form_before_the_dataview.
Changes / Features implemented
Builds on #3207. Depends on onaio/ona-oidc#139.
#3207 asks for a second factor at sign-in. A stolen session skips that check. This PR also asks for it before sensitive account actions.
Each gated action needs a single-use grant for that action. For example, a user proves the second factor to get a grant for
change-email. Only an email change accepts that grant.Each gate is off by default. A deployment lists the actions it gates in
STEP_UP["ACTIONS"]. Each action name is also a grant audience.A deployment can gate these actions:
require_author the privacy consent.created_bycan do this. The gate counts the role that the person gets at the end. For example, a form's meta permissions can turn an editor share into an owner share. Theshare-team-admingate also covers a team move to another organisation, because the team keeps its roles./api/v1/metadatathat links a form or data view, or change a row so it links one. Anyone who can read the host form's media can download the linked data.require_authsetting or its encryption.How a gate works:
STEP_UP["MODE"]selects who checks the second factor. Inlocalmode, onadata checks it through/api/v1/totp/verify. Infederatedmode, the identity provider checks it through/api/v1/stepup/startand/api/v1/stepup/callback./api/v1/user/capabilitiesreports what the deployment lets a user manage. A client sends a grant in the request body or in theX-Step-Up-Grantheader.Startup checks find a bad configuration.
stepup.E001stops startup on a malformedSTEP_UP,stepup.E002on an action that no gate checks, andstepup.E004on federated mode with gated actions but no provider with aSTEP_UPblock. ona-oidc'soidc.E003, for a bad providerSTEP_UPblock, also stops the WSGI application.stepup.W001,W003toW010are warnings.W010warns when federated mode has noSTEP_UP_POPUP_ORIGIN.W009warns whenauthorize-oauth-appis gated. The OAuth pages cannot show a challenge. They refuse each approval, device approval or app change that the gate challenges.docs/two_factor.rstdescribes the settings and the checks. It starts with the steps a client follows when it gets a step-up challenge, with a complete example. No route lists the gated actions, so a client must handle the challenge on each write that a deployment can gate. Each endpoint page that documents a gated route links to these steps.Points to review carefully:
auth_timemust not be before the start. A session binding is not possible, because a client can start the step-up with an API token that has no session.change-email, or an email change gets around every gate.stepup.W006warns if it does not.stepup.W007warns if step-up finds users by a different field.grant-org-adminand the share audiences together. If you do not, a stolen owner session can make the attacker's own account an owner. That account then passes every gate with its own second factor.one_gated_change_per_requestwhen both are gated. Make the form public first. There are two exceptions. An organisation member add and a team join can need bothgrant-org-adminandshare-team-admin. There, one grant for the first gated action covers both.NO_FACTOR_POLICYanswer, notone_gated_change_per_request, because no grant is involved.emailoremailsneeds the token'semailclaim to match andemail_verifiedto be true. This is the default. SetREQUIRE_VERIFIED_EMAILtoFalsein the provider'sSTEP_UPblock only for a provider that proves the address in a different way. Then the provider entry'sCHECK_EMAIL_VERIFIEDandREQUIRE_VERIFIED_EMAILapply, as they do for login.Not in this PR. Decide later:
skip_gate, a user without a second factor gets no re-authentication. This does not meet OWASP ASVS 5.0 requirement 7.5.1. The docs should say so.acrandauth_timein place of a grant. Then the OIDC challenge can use the RFC 9470 form,Bearer error="insufficient_user_authentication". Today a client must send a grant, so the 401 uses a customStepUpscheme in both modes. An RFC 9470 client would get a new token, send the request again with no grant, and get the same 401.Steps taken to verify this change does what is intended
Every gate has three tests. They show that the gate refuses a request without a grant, lets a change through with a grant, and does not challenge an unchanged value. Other tests cover the federated round trip and the startup checks. CI runs them.
I also did an end-to-end check against a local Keycloak 26.8.2 and WSO2 Identity Server 7.3.0. The check read
acrandamr, with and withoutprompt=login. It passed 21 of 21 checks on each server. That run came before review added the share, data and transfer gates, and before the changes since 20 November.Side effects of implementing this change
TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD. A first enrolment always needs the password, so users without a usable password can no longer enrol.stepup.W005warns if the setting is still there./totpmanagement endpoints return 409. If the deployment cannot offer a step-up, the request gets 503step_up_unavailable.one_gated_change_per_requestand spends no grant.{"non_field_errors": [...]}, not a bare list. After too many wrong guesses, it answers 403 with"reason": "locked_out".WWW-Authenticate: StepUp error="step_up_required", audience="...", dialect="...", as RFC 9110 requires for a 401. The JSON body is the same.SELECT ... FOR UPDATEfrom the gate until the save. A second write to the same row waits for the first one. With no gated action, an update takes the old path./api/v1/metadata. A form update that moves the form locks both projects in primary key order. A form move through/api/v1/projects/{pk}/formsalso locks both projects, then the form, and saves only the form's owner and project. It reads the new project again after the lock. A form update and a project update then cannot deadlock.ANONYMOUS_DEFAULT_USERNAME) is refused, on/api/v1/forms/{pk}/share,/api/v1/projects/{pk}/shareand the legacy form permissions page. The anonymous user is also refused as a new member on/api/v1/orgs/{user}/membersand/api/v1/teams/{pk}/members. Such a share made the data readable without sign-in. A removal of the anonymous user still works.disable-form-encryptiongate. To turn encryption off, use the form's encryption setting.?del,?map_name_deland?external_delnow delete only the metadata type they list./api/v1/totp/verifyis spent only together with its grant. If the cache cannot store the grant, the answer is still 503, and the code stays valid./api/v1/orgs/{user}/membersand/api/v2/orgs/{user}/memberslocks the organisation's members and Owners teams before its check. A join or a leave on/api/v1/teams/{pk}/memberslocks its team before its check. Member changes on one organisation then run one at a time, and each check sees the change it waited for.type="email". The username, email and name fields getautocompletehints, so phones show the right keyboard and offer autofill.ShareProjectwrites now takes a Postgres advisory lock for the project. These changes on one project run one at a time. Where the deployment gates an action, form shares and team shares, also downgrades and removals, take the same lock. A share takes it before its check. A registration accepts its pending invitations in project order, so two registrations cannot deadlock on these locks. A re-share then cannot undo a concurrent downgrade without a grant. The owner role that a transfer adds does not take the lock.ShareProjecttakes it even where nothing is gated, because a repeat share queued while a gate was on must still be ordered with a later downgrade.ProjectInvitationSerializer.save()runscheck_can_save()when the caller did not./api/v1/metadatathat makes a hidden public link row active is now gated aspublish-data.need-app = true.GET /api/v1/stepup/startanswers only in JSON. A request that accepts only HTML gets a 406.email_verifiedtrue in the token. A provider that does not send it needsREQUIRE_VERIFIED_EMAIL: Falsein the provider'sSTEP_UPblock, inOPENID_CONNECT_AUTH_SERVERS.AUTH_TIME_SKEW_SECONDS(default 0) in the same block allows clock skew onauth_time.STEP_UPblock needs its ownREDIRECT_URIthat points at/api/v1/stepup/callback.TWO_FACTOR_STEP_UP_AUDIENCESnow holds only extra audiences./api/v1/totp/verifyalways accepts every gated action and the two-factor lifecycle operations.share_project_asynchas a newrepeat_onlykeyword argument. During a rolling deploy, an old Celery worker that gets a repeat share from a new web process raisesTypeError, and the share is lost. Deploy the workers first, or drain the queue./o/device-confirm/of a used or expired code answers 404 before the gate, so it keeps its grant.oidc.E003stops the start for a provider that has aSTEP_UPblock but noTOKEN_ENDPOINTthat is an absolute http or https URL. Step-up always uses the code flow, also where login uses the implicit flow. A deployment that signs in with the implicit flow must addTOKEN_ENDPOINTto that provider before it upgrades. ASTEP_UP_POPUP_ORIGINthat is set but is not an http or https origin is alsooidc.E003.mainchanges. SSO tokens must now carryexp. Users with a current SSO session must sign in again once. New SSO sessions expire after 7 days.DEFAULT_EXCEPTION_REPORTERandDEFAULT_EXCEPTION_REPORTER_FILTERare now set. Error reports replace the values ofcode,state,id_tokenandaccess_tokenin the request data, also in a DRFRequestin the traceback. The step-up callback also hides itscodeandstatelocals. A deployment that overrides these settings must keep this.requirementsfiles pin ona-oidc to a commit on the feat: add step-up authentication ona-oidc#139 branch. When feat: add step-up authentication ona-oidc#139 merges, pin ona-oidc tomainagain.Before submitting this PR for review, please make sure you have:
Closes #3367