Skip to content

feat: add step-up authentication for sensitive account actions - #3215

Open
FrankApiyo wants to merge 120 commits into
mainfrom
feat/step-up-authentication
Open

FrankApiyo wants to merge 120 commits into
mainfrom
feat/step-up-authentication

Conversation

@FrankApiyo

@FrankApiyo FrankApiyo commented Aug 17, 2026 •

Copy link
Copy Markdown
Member

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:

  • Account: replace the API or ODK token, change the email, password or username, and change require_auth or the privacy consent.
  • Organisations: make someone an owner or manager, add a member whose project shares make them one, give a team with members the organisation's Owners name, and rotate the encryption key.
  • Shares: give a person owner or manager rights on a form, project or team. A share, an invitation, a team join, a change to a form's meta permissions or a change to a form's created_by can 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. The share-team-admin gate also covers a team move to another organisation, because the team keeps its roles.
  • Data: make a form's or project's data public, or turn on a public link through the API or the legacy form permissions page. Also move a private form into a public project, or add dataviews and merged datasets over private forms in a public project. Also add a media row on /api/v1/metadata that 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.
  • Transfers: move a project or form to another account. Also move a form whose meta permissions make the users of the new project its owners or managers. A form move is a transfer when the form leaves its owner's account or the account of its current project. This includes a move into a project of the form's owner, out of another account's project. Also make a merged dataset in another account's project, or from forms that another account owns or keeps in its project.
  • Forms: turn off a form's require_auth setting or its encryption.
  • Webhooks: add a webhook, change where it sends data, or change a form's TextIt settings.
  • OAuth: approve an application or a device, register an application, or change any field of an application except its name.

How a gate works:

  1. It validates the request before it spends the grant. A request that is not valid keeps its grant.
  2. It asks for a grant only when a value changes.
  3. It runs its extra queries, such as the share role queries, only when the deployment gates the action. It takes its row locks when the deployment gates any action.
  4. It writes an audit entry when a user spends a grant, when it refuses a grant, and when a user must enrol first. It never logs the grant itself.
  5. It treats a malformed grant as no grant. It always challenges an anonymous caller.

STEP_UP["MODE"] selects who checks the second factor. In local mode, onadata checks it through /api/v1/totp/verify. In federated mode, the identity provider checks it through /api/v1/stepup/start and /api/v1/stepup/callback.

/api/v1/user/capabilities reports what the deployment lets a user manage. A client sends a grant in the request body or in the X-Step-Up-Grant header.

Startup checks find a bad configuration. stepup.E001 stops startup on a malformed STEP_UP, stepup.E002 on an action that no gate checks, and stepup.E004 on federated mode with gated actions but no provider with a STEP_UP block. ona-oidc's oidc.E003, for a bad provider STEP_UP block, also stops the WSGI application. stepup.W001, W003 to W010 are warnings. W010 warns when federated mode has no STEP_UP_POPUP_ORIGIN. W009 warns when authorize-oauth-app is gated. The OAuth pages cannot show a challenge. They refuse each approval, device approval or app change that the gate challenges. docs/two_factor.rst describes 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:

  • Federated mode always challenges, because onadata cannot see the user's second factor.
  • The callback makes sure that the person who did the step-up is the signed-in user. It finds the account from the provider's token by email, as login does.
  • The step-up state is bound to the user, not to a browser session. The callback refuses a state that another user started. The state is single-use, the token must carry its nonce, and its auth_time must 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.
  • A federated deployment should also gate change-email, or an email change gets around every gate. stepup.W006 warns if it does not. stepup.W007 warns if step-up finds users by a different field.
  • Gate grant-org-admin and 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.
  • Onadata applies a form's meta permissions again to all its users on each change to them, team share and move. The gates count who that makes an owner or manager, not only if the value changed.
  • One request carries one grant. A move that makes a form public and also makes its users owners or managers gets one_gated_change_per_request when both are gated. Make the form public first. There are two exceptions. An organisation member add and a team join can need both grant-org-admin and share-team-admin. There, one grant for the first gated action covers both.
  • A user with no second factor in local mode gets the NO_FACTOR_POLICY answer, not one_gated_change_per_request, because no grant is involved.
  • The token gates protect only the replacement of a token. A signed-in session can still read the current tokens.
  • The login lockout now counts wrong current passwords on the email change and on the password change page. Before, those pages let a caller guess without a limit. The password alone lets a user enrol a first factor.
  • In federated mode, a step-up that binds by email or emails needs the token's email claim to match and email_verified to be true. This is the default. Set REQUIRE_VERIFIED_EMAIL to False in the provider's STEP_UP block only for a provider that proves the address in a different way. Then the provider entry's CHECK_EMAIL_VERIFIED and REQUIRE_VERIFIED_EMAIL apply, as they do for login.

Not in this PR. Decide later:

  • Bind a grant to the exact new email address or share target, as PSD2 "dynamic linking" does for payments. This helps only if the user sees those values when they verify.
  • Bulk sharing is slow, because each gated request needs a new code. GitHub sudo mode and AWS use a time window instead of a single-use grant.
  • Tell API scripts what to do when they get a challenge that they cannot answer.
  • With 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.
  • Accept an access token with a fresh acr and auth_time in 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 custom StepUp scheme in both modes. An RFC 9470 client would get a new token, send the request again with no grant, and get the same 401.
  • In a few rare cases, the gate spends the grant and then the write fails, for example on a key rotation error. The user loses the grant, but no data changes. This PR accepts that.

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 acr and amr, with and without prompt=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

  • This PR removes TWO_FACTOR_ENROLMENT_REQUIRES_PASSWORD. A first enrolment always needs the password, so users without a usable password can no longer enrol. stepup.W005 warns if the setting is still there.
  • In federated mode, the /totp management endpoints return 409. If the deployment cannot offer a step-up, the request gets 503 step_up_unavailable.
  • A request that changes two gated values gets a 400 one_gated_change_per_request and spends no grant.
  • A profile email change with no password or a wrong password now answers {"non_field_errors": [...]}, not a bare list. After too many wrong guesses, it answers 403 with "reason": "locked_out".
  • A project transfer now answers 400 before it changes anything if the new account already has a project with that name. Before, it failed with a 500 after it gave the new owner their role.
  • A project transfer checks the permission on the new account before the name. A caller who cannot add projects there gets only the permission error, so the answer does not show project names in that account.
  • The invitation errors "Invitation already exists.", "User already exists" and "Only pending invitations can be updated" now come before the gate. The body and the status are the same. A request that gets one of them keeps its grant.
  • A step-up 401 now sends WWW-Authenticate: StepUp error="step_up_required", audience="...", dialect="...", as RFC 9110 requires for a 401. The JSON body is the same.
  • Where the deployment gates an action, a gated update now locks the row with SELECT ... FOR UPDATE from 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.
  • A form save writes its project's row, and a project update writes its forms' rows. So where a form path takes a row lock, it locks the project row first. This covers a gated form update, the legacy form visibility toggle, and a public link or TextIt write on /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}/forms also 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.
  • The legacy settings and form edit pages lock the rows they check. The form edit page and both password change routes save only the columns they change. A concurrent change is no longer written back with old values.
  • A share with the anonymous user (ANONYMOUS_DEFAULT_USERNAME) is refused, on /api/v1/forms/{pk}/share, /api/v1/projects/{pk}/share and the legacy form permissions page. The anonymous user is also refused as a new member on /api/v1/orgs/{user}/members and /api/v1/teams/{pk}/members. Such a share made the data readable without sign-in. A removal of the anonymous user still works.
  • A replacement of an encrypted form with an XML form that has no public key now answers 400, and the form does not change. Before, the replacement turned encryption off without the disable-form-encryption gate. To turn encryption off, use the form's encryption setting.
  • The legacy remove links ?del, ?map_name_del and ?external_del now delete only the metadata type they list.
  • A project share that the gate let through because the user already held the role is queued as a repeat. The task skips it if the role was revoked in the meantime. The task reads the role from the primary database, not from a replica.
  • Two more shares are queued as repeats. One is a member re-add that the gate let through because the member held the roles. The other is a project share that gives no owner or manager role when the gate checks it. Thus a role revoked, or a meta permission that promotes a role, before the task runs cannot give an admin role without a grant.
  • An update of a project invitation locks the invitation row from the pending-status check until the save. A concurrent revoke is no longer undone. The email for a changed address is queued after the commit, so a rolled-back update sends no email.
  • A recovery code at /api/v1/totp/verify is spent only together with its grant. If the cache cannot store the grant, the answer is still 503, and the code stays valid.
  • Where the deployment gates an action, a member change on /api/v1/orgs/{user}/members and /api/v2/orgs/{user}/members locks the organisation's members and Owners teams before its check. A join or a leave on /api/v1/teams/{pk}/members locks 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.
  • Where the deployment gates an action, each gated section reads from the primary database, from its lock to its save. This covers gated creates and updates, metadata deletes, form moves, form and team shares, and organisation and team member changes. A lagging replica cannot show a check the state from before a change that it waited for. Gated deployments therefore send more reads to the primary.
  • The sign-up form renders the email field as type="email". The username, email and name fields get autocomplete hints, so phones show the right keyboard and offer autofill.
  • Each share, role change and removal that ShareProject writes 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. ShareProject takes 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() runs check_can_save() when the caller did not.
  • A project PATCH that sends the current owner no longer runs the transfer. Before, it reset the roles of the organisation's members on the project.
  • A share counts as unchanged only if the user holds the role by a direct grant. A user who has the role only through a team now gets a challenge, because the share writes a direct grant.
  • A change or a deletion on /api/v1/metadata that makes a hidden public link row active is now gated as publish-data.
  • The WSGI application does not load if a step-up check reports an error. uWSGI then answers each request with an error. To make the process exit, set need-app = true.
  • GET /api/v1/stepup/start answers only in JSON. A request that accepts only HTML gets a 406.
  • With the new ona-oidc pin, a federated step-up that binds by email needs email_verified true in the token. A provider that does not send it needs REQUIRE_VERIFIED_EMAIL: False in the provider's STEP_UP block, in OPENID_CONNECT_AUTH_SERVERS. AUTH_TIME_SKEW_SECONDS (default 0) in the same block allows clock skew on auth_time.
  • In federated mode, the provider's STEP_UP block needs its own REDIRECT_URI that points at /api/v1/stepup/callback.
  • TWO_FACTOR_STEP_UP_AUDIENCES now holds only extra audiences. /api/v1/totp/verify always accepts every gated action and the two-factor lifecycle operations.
  • Release notes: share_project_async has a new repeat_only keyword argument. During a rolling deploy, an old Celery worker that gets a repeat share from a new web process raises TypeError, and the share is lost. Deploy the workers first, or drain the queue.
  • An accept on /o/device-confirm/ of a used or expired code answers 404 before the gate, so it keeps its grant.
  • Release notes: with the new ona-oidc pin, oidc.E003 stops the start for a provider that has a STEP_UP block but no TOKEN_ENDPOINT that 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 add TOKEN_ENDPOINT to that provider before it upgrades. A STEP_UP_POPUP_ORIGIN that is set but is not an http or https origin is also oidc.E003.
  • Release notes: the ona-oidc pin brings in its main changes. SSO tokens must now carry exp. Users with a current SSO session must sign in again once. New SSO sessions expire after 7 days.
  • DEFAULT_EXCEPTION_REPORTER and DEFAULT_EXCEPTION_REPORTER_FILTER are now set. Error reports replace the values of code, state, id_token and access_token in the request data, also in a DRF Request in the traceback. The step-up callback also hides its code and state locals. A deployment that overrides these settings must keep this.
  • The requirements files 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 to main again.

Before submitting this PR for review, please make sure you have:

  • Included tests
  • Updated documentation

Closes #3367

@FrankApiyo
FrankApiyo force-pushed the feat/step-up-authentication branch 4 times, most recently from 997ea08 to 617dffa Compare August 17, 2026 12:05
@FrankApiyo
FrankApiyo force-pushed the feat/step-up-authentication branch 3 times, most recently from afbbc6a to ecc8ee3 Compare August 19, 2026 07:50
@FrankApiyo
FrankApiyo force-pushed the feat/django-two-factor-auth branch from d3797e6 to 19d2b1c Compare August 19, 2026 09:07
@FrankApiyo
FrankApiyo force-pushed the feat/step-up-authentication branch 2 times, most recently from 5799b9f to af118e4 Compare August 19, 2026 10:15
@FrankApiyo
FrankApiyo force-pushed the feat/django-two-factor-auth branch from 6d33f67 to 0d13046 Compare August 19, 2026 10:19
@FrankApiyo
FrankApiyo force-pushed the feat/step-up-authentication branch from af118e4 to 1bd7149 Compare August 19, 2026 10:21
@FrankApiyo
FrankApiyo force-pushed the feat/django-two-factor-auth branch from 7532dd9 to d29ef14 Compare August 19, 2026 11:10
@FrankApiyo
FrankApiyo force-pushed the feat/step-up-authentication branch from 1bd7149 to e3c5c58 Compare August 19, 2026 12:35
@FrankApiyo
FrankApiyo force-pushed the feat/django-two-factor-auth branch from 00d9c16 to 5a1adfb Compare August 19, 2026 13:03
@FrankApiyo
FrankApiyo force-pushed the feat/step-up-authentication branch from d0c2148 to 0638997 Compare August 19, 2026 13:04
@FrankApiyo
FrankApiyo force-pushed the feat/django-two-factor-auth branch from 5a1adfb to 4042f52 Compare August 19, 2026 13:11
@FrankApiyo
FrankApiyo force-pushed the feat/step-up-authentication branch 2 times, most recently from 35e5214 to 11c8d60 Compare August 19, 2026 13:28
@FrankApiyo FrankApiyo changed the title feat(2fa): step up before weakening a data protection feat(2fa): gate sensitive actions behind a step-up, local or federated Aug 19, 2026
@FrankApiyo
FrankApiyo force-pushed the feat/django-two-factor-auth branch from b90ed42 to 3f6f571 Compare August 19, 2026 13:38
@FrankApiyo
FrankApiyo force-pushed the feat/step-up-authentication branch from 11c8d60 to 5fe1dc3 Compare August 19, 2026 13:39
@FrankApiyo FrankApiyo changed the title feat(2fa): gate sensitive actions behind a step-up, local or federated feat(2fa): implement step-up authentication Aug 19, 2026
@FrankApiyo
FrankApiyo force-pushed the feat/step-up-authentication branch from 5fe1dc3 to c6281e3 Compare August 19, 2026 13:53
@FrankApiyo
FrankApiyo force-pushed the feat/django-two-factor-auth branch from 9cd079d to 7a0b620 Compare August 20, 2026 10:00
@FrankApiyo
FrankApiyo force-pushed the feat/step-up-authentication branch from 68df7e3 to 3e692d9 Compare August 20, 2026 10:06
@FrankApiyo
FrankApiyo force-pushed the feat/django-two-factor-auth branch from 7a0b620 to 46c4cba Compare August 20, 2026 12:22
@FrankApiyo
FrankApiyo force-pushed the feat/step-up-authentication branch 2 times, most recently from 1cbeb48 to 2518c4b Compare August 20, 2026 12:46

@ukanga ukanga left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread onadata/apps/api/tools.py Outdated
Comment on lines +484 to +485
if check_move:
check_move(xform)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1fde320 and 0653625. Where an action is gated, the move locks both projects, then the form, in the same order as a form update. It checks the form from the locked row. The save writes only user and project, so it cannot write back an old shared or shared_data.

def appoints_admins_not_covered_by_a_transfer():
if transfers and is_gated(GATE_TRANSFER_PROJECT):
return False
return move_appoints_admins(xform, project)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +181 to +184
shared = member_admin_roles(
organization.user.project_org.all(), members_team, user, role_name
)
return not holds_roles(user, shared)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +139 to +148
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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +307 to +308
if not granted:
return None

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
if not granted:
return None
if not granted:
validated_data["repeat_only"] = True
return None

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +462 to 468
serializer.check_can_save()
refusal = self._invite_admin_refusal(
request, serializer.validated_data, invitation
)
if refusal is not None:
return refusal
serializer.save()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +774 to +781
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,
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 ukanga left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +84 to +87
parts = data_value.split()
tag = next(
(tag for tag in (DATAVIEW_TAG, XFORM_TAG) if data_value.startswith(tag)),
None,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +243 to +251
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,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread onadata/apps/api/tools.py
Comment on lines +497 to +504
if check_move:
check_move(xform)
xform.user = project.organization
xform.project = project

try:
with transaction.atomic():
xform.save(update_fields=["user", "project"])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread onadata/apps/api/tasks.py
Comment on lines +255 to +263
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()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +127 to +129
if isinstance(content_object, XForm):
lock_projects(content_object.project_id)
lock_row(type(content_object), content_object.pk)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +549 to +552
name = name or self.instance.name
if Project.objects.filter(
name__iexact=name, organization=organization
).exists():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +86 to +89
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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Protect an organisation's owners from an owner without a second factor

3 participants