Skip to content

fix(auth): enforce phase-bound change-email token flow (GHSA-4q3w-q5mc-45rq) - #35425

Merged
laipz8200 merged 3 commits into
mainfrom
fix/ghsa-4q3w-q5mc-45rq-change-email-phase
Apr 20, 2026
Merged

laipz8200 merged 3 commits into
mainfrom
fix/ghsa-4q3w-q5mc-45rq-change-email-phase

Conversation

@zyssyz123

@zyssyz123 zyssyz123 commented Apr 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes the change-email bypass described in GHSA-4q3w-q5mc-45rq.

The existing flow is:

  1. POST /console/api/account/change-email with phase=old_email — sends a code to the old email and returns a token.
  2. POST /console/api/account/change-email/validity — verifies the old-email code, returns a refreshed token.
  3. POST /console/api/account/change-email with phase=new_email — sends a code to the new email, returns a token.
  4. POST /console/api/account/change-email/validity — verifies the new-email code, returns a refreshed token.
  5. POST /console/api/account/change-email/reset — consumes the verified token to change the email.

Problem: /reset only checked that the token existed and that its stored old_email matched the current user. Both conditions are already satisfied by the phase-1 token returned by step 1, so the attacker can skip steps 2/3/4 entirely and change the account email to any address they control by sending only step 1 + step 5.

Fix

Bind the full progression to a phase marker that lives inside the token itself:

old_email → old_email_verified → new_email → new_email_verified

  • AccountService.send_change_email_email stamps the requested phase into the token's additional_data and rejects anything outside {old_email, new_email}.
  • POST /account/change-email with phase=new_email now requires the supplied token to be in the old_email_verified phase. Any other value (including a phase-1 token) raises InvalidTokenError. Legacy/unexpected phase inputs from the caller are coerced back to old_email so the client cannot self-assert later phases.
  • POST /account/change-email/validity only advances tokens that carry the matching send-phase marker and mints a replacement token stamped with *_verified. Tokens lacking a phase marker are rejected.
  • POST /account/change-email/reset now requires new_email_verified and that the token's stored email equals the request body's new_email, so a verified token cannot be replayed to point at a different address. Token revocation moved after all checks so a failed attempt no longer burns a legitimate verified token.

Frontend (web/service/common.ts) continues to send phase=old_email / phase=new_email and does not need changes.

Test plan

Added / updated unit tests in api/tests/unit_tests/controllers/console/test_workspace_account.py:

  • Happy path: /validity advances old_email → old_email_verified and new_email → new_email_verified, and /reset succeeds with a new_email_verified token whose email matches the body.
  • Regression (advisory PoC): /reset rejects a phase-1 (old_email) token with InvalidTokenError and does not revoke it, update the account, or send the completion email.
  • Token substitution: /reset rejects a verified token whose token-email differs from the body new_email.
  • Phase-lift protection: /account/change-email with phase=new_email rejects tokens that are not yet old_email_verified.
  • /validity rejects tokens with no phase marker (e.g. hand-crafted or pre-migration tokens).
  • ruff check and ruff format --check on all three touched files.

Checklist

  • This change requires a documentation update, included: Dify Document
  • I understand that this PR may be closed in case there was no previous discussion or issues. (This doesn't apply to typos!)
  • I've added a test for each change that was introduced, and I tried as much as possible to make a single atomic change.
  • I've updated the documentation accordingly.
  • I ran make lint and make type-check (backend) and cd web && npx lint-staged (frontend) to appease the lint gods

…c-45rq)

The previous change-email flow let any live change-email token pass the
`/account/change-email/reset` check as long as its `old_email` matched the
current user. An attacker only had to call step 1 (`phase=old_email`) and
feed the returned token directly to step 5, bypassing both the old- and
new-email ownership checks and changing the account email to an arbitrary
address.

Bind the full four-step chain to a phase marker inside the token itself:

  old_email -> old_email_verified -> new_email -> new_email_verified

- `send_change_email_email` now stamps the requested phase into the token
  and refuses phases outside `{old_email, new_email}`.
- `/account/change-email` (phase=new_email) requires the supplied token to
  be in the `old_email_verified` phase; any other phase is rejected. It
  also coerces legacy/unexpected `phase` values back to `old_email` so the
  caller cannot assert later phases on its own.
- `/account/change-email/validity` only advances tokens that carry the
  matching send-phase marker and mints a replacement token stamped with
  the upgraded phase (`*_verified`). Tokens lacking a phase marker are
  refused.
- `/account/change-email/reset` requires `new_email_verified` and binds
  the token's `email` to the request body's `new_email`, so a verified
  token cannot be replayed with a different target address. Token revoke
  is moved after all checks so a failed call no longer burns a legitimate
  verified token.

Covered with regression tests, including the exact PoC from the advisory
(phase-1 token replayed to `/reset`) and the mismatched-target variant.

Fixes GHSA-4q3w-q5mc-45rq.

Made-with: Cursor
@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Apr 20, 2026
@github-actions

github-actions Bot commented Apr 20, 2026 •

Copy link
Copy Markdown
Contributor

Pyrefly Type Coverage

Metric Base PR Delta
Type coverage 38.54% 38.48% -0.06%
Strict coverage 38.06% 38.00% -0.06%
Typed symbols 19,306 19,306 0
Untyped symbols 31,180 31,255 +75
Modules 2519 2519 0

@github-actions

Copy link
Copy Markdown
Contributor

Pyrefly Diff

base → PR
--- /tmp/pyrefly_base.txt	2026-04-20 08:04:22.305777707 +0000
+++ /tmp/pyrefly_pr.txt	2026-04-20 08:04:11.086787134 +0000
@@ -18,6 +18,8 @@
   --> controllers/console/socketio/workflow.py:45:14
 ERROR Object of class `MissingRouter` has no attribute `get` [missing-attribute]
   --> controllers/console/version.py:30:2
+ERROR Argument `Any | None` is not assignable to parameter `key` with type `str` in function `dict.get` [bad-argument-type]
+   --> controllers/console/workspace/account.py:679:49
 ERROR Class member `EasyUIBasedGenerateTaskPipeline._application_generate_entity` overrides parent class `BasedGenerateTaskPipeline` in an inconsistent manner [bad-override-mutable-attribute]
   --> core/app/task_pipeline/easy_ui_based_generate_task_pipeline.py:75:5
 ERROR `+=` is not supported between `list[PromptMessageContentUnionTypes]` and `str` [unsupported-operation]
@@ -753,7 +755,7 @@
 ERROR No matching overload found for function `redis.client.Redis.__init__` called with arguments: (host=int | str | Unknown, port=int | str | Unknown, password=int | str | Unknown | None, db=int, ssl=bool, ssl_ca_certs=str | None, ssl_cert_reqs=Any | None, ssl_certfile=Any | None, ssl_keyfile=Any | None, socket_timeout=Literal[5], socket_connect_timeout=Literal[5], health_check_interval=Literal[30]) [no-matching-overload]
   --> schedule/queue_monitor_task.py:14:21
 ERROR Object of class `Tenant` has no attribute `role` [missing-attribute]
-    --> services/account_service.py:1154:13
+    --> services/account_service.py:1169:13
 ERROR No matching overload found for function `flask.helpers.stream_with_context` called with arguments: (Generator[bytes]) [no-matching-overload]
    --> services/audio_service.py:144:56
 ERROR No matching overload found for function `flask.helpers.stream_with_context` called with arguments: (Generator[bytes]) [no-matching-overload]

1 similar comment
@github-actions

Copy link
Copy Markdown
Contributor

Pyrefly Diff

base → PR
--- /tmp/pyrefly_base.txt	2026-04-20 08:04:22.305777707 +0000
+++ /tmp/pyrefly_pr.txt	2026-04-20 08:04:11.086787134 +0000
@@ -18,6 +18,8 @@
   --> controllers/console/socketio/workflow.py:45:14
 ERROR Object of class `MissingRouter` has no attribute `get` [missing-attribute]
   --> controllers/console/version.py:30:2
+ERROR Argument `Any | None` is not assignable to parameter `key` with type `str` in function `dict.get` [bad-argument-type]
+   --> controllers/console/workspace/account.py:679:49
 ERROR Class member `EasyUIBasedGenerateTaskPipeline._application_generate_entity` overrides parent class `BasedGenerateTaskPipeline` in an inconsistent manner [bad-override-mutable-attribute]
   --> core/app/task_pipeline/easy_ui_based_generate_task_pipeline.py:75:5
 ERROR `+=` is not supported between `list[PromptMessageContentUnionTypes]` and `str` [unsupported-operation]
@@ -753,7 +755,7 @@
 ERROR No matching overload found for function `redis.client.Redis.__init__` called with arguments: (host=int | str | Unknown, port=int | str | Unknown, password=int | str | Unknown | None, db=int, ssl=bool, ssl_ca_certs=str | None, ssl_cert_reqs=Any | None, ssl_certfile=Any | None, ssl_keyfile=Any | None, socket_timeout=Literal[5], socket_connect_timeout=Literal[5], health_check_interval=Literal[30]) [no-matching-overload]
   --> schedule/queue_monitor_task.py:14:21
 ERROR Object of class `Tenant` has no attribute `role` [missing-attribute]
-    --> services/account_service.py:1154:13
+    --> services/account_service.py:1169:13
 ERROR No matching overload found for function `flask.helpers.stream_with_context` called with arguments: (Generator[bytes]) [no-matching-overload]
    --> services/audio_service.py:144:56
 ERROR No matching overload found for function `flask.helpers.stream_with_context` called with arguments: (Generator[bytes]) [no-matching-overload]

@codecov

codecov Bot commented Apr 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.55172% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 85.50%. Comparing base (1a7e463) to head (e50065d).
⚠️ Report is 5 commits behind head on main.

Files with missing lines Patch % Lines
api/controllers/console/workspace/account.py 95.23% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main   #35425   +/-   ##
=======================================
  Coverage   85.50%   85.50%           
=======================================
  Files        4434     4434           
  Lines      206968   206998   +30     
  Branches    38522    38530    +8     
=======================================
+ Hits       176959   176989   +30     
+ Misses      26905    26899    -6     
- Partials     3104     3110    +6     
Flag Coverage Δ
api 84.87% <96.55%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

basedpyright flagged `phase_transitions.get(token_phase)` because
`token_data.get(...)` returns `Any | None` while `dict.get` expects a
`str` key in strict mode. Explicitly reject non-string phases (which are
also not valid phase markers anyway) before the lookup so the type check
passes and malformed tokens are handled uniformly as InvalidTokenError.

Made-with: Cursor
@github-actions

Copy link
Copy Markdown
Contributor

Pyrefly Diff

base → PR
--- /tmp/pyrefly_base.txt	2026-04-20 08:25:43.059787970 +0000
+++ /tmp/pyrefly_pr.txt	2026-04-20 08:25:31.858840043 +0000
@@ -753,7 +753,7 @@
 ERROR No matching overload found for function `redis.client.Redis.__init__` called with arguments: (host=int | str | Unknown, port=int | str | Unknown, password=int | str | Unknown | None, db=int, ssl=bool, ssl_ca_certs=str | None, ssl_cert_reqs=Any | None, ssl_certfile=Any | None, ssl_keyfile=Any | None, socket_timeout=Literal[5], socket_connect_timeout=Literal[5], health_check_interval=Literal[30]) [no-matching-overload]
   --> schedule/queue_monitor_task.py:14:21
 ERROR Object of class `Tenant` has no attribute `role` [missing-attribute]
-    --> services/account_service.py:1154:13
+    --> services/account_service.py:1169:13
 ERROR No matching overload found for function `flask.helpers.stream_with_context` called with arguments: (Generator[bytes]) [no-matching-overload]
    --> services/audio_service.py:144:56
 ERROR No matching overload found for function `flask.helpers.stream_with_context` called with arguments: (Generator[bytes]) [no-matching-overload]

Codecov flagged 79.31% patch coverage on PR #35425 (target 85.5%) because
three newly added branches had no test:

- `AccountService.send_change_email_email` happy path (the ValueError for
  an out-of-set phase and the token-generation call with the new phase
  stamp) was only reached indirectly via controller tests that mock the
  whole function, so the new lines inside it were invisible to coverage.
- In `/account/change-email/validity`, the `refreshed_phase is None`
  branch (token whose phase marker is a string but not a known value)
  had no case — only the `not isinstance(..., str)` path was exercised.

Add three focused tests:
- service-level: raising ValueError for an invalid phase value
- service-level: happy path asserts the phase marker is stamped into the
  generated token via `generate_change_email_token`
- controller-level: `/validity` rejects a token whose phase marker is an
  unknown string, covering the `refreshed_phase is None` branch.

Made-with: Cursor
@github-actions

Copy link
Copy Markdown
Contributor

Pyrefly Diff

base → PR
--- /tmp/pyrefly_base.txt	2026-04-20 09:25:48.277347521 +0000
+++ /tmp/pyrefly_pr.txt	2026-04-20 09:25:37.219388594 +0000
@@ -753,7 +753,7 @@
 ERROR No matching overload found for function `redis.client.Redis.__init__` called with arguments: (host=int | str | Unknown, port=int | str | Unknown, password=int | str | Unknown | None, db=int, ssl=bool, ssl_ca_certs=str | None, ssl_cert_reqs=Any | None, ssl_certfile=Any | None, ssl_keyfile=Any | None, socket_timeout=Literal[5], socket_connect_timeout=Literal[5], health_check_interval=Literal[30]) [no-matching-overload]
   --> schedule/queue_monitor_task.py:14:21
 ERROR Object of class `Tenant` has no attribute `role` [missing-attribute]
-    --> services/account_service.py:1154:13
+    --> services/account_service.py:1169:13
 ERROR No matching overload found for function `flask.helpers.stream_with_context` called with arguments: (Generator[bytes]) [no-matching-overload]
    --> services/audio_service.py:144:56
 ERROR No matching overload found for function `flask.helpers.stream_with_context` called with arguments: (Generator[bytes]) [no-matching-overload]

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Apr 20, 2026
@laipz8200
laipz8200 added this pull request to the merge queue Apr 20, 2026
Merged via the queue into main with commit e561788 Apr 20, 2026
32 of 33 checks passed
@laipz8200
laipz8200 deleted the fix/ghsa-4q3w-q5mc-45rq-change-email-phase branch April 20, 2026 10:19
HanqingZ pushed a commit to HanqingZ/dify that referenced this pull request Apr 23, 2026
asukaminato0721 pushed a commit to asukaminato0721/dify that referenced this pull request Apr 24, 2026
Ssazurov pushed a commit to Ssazurov/dify that referenced this pull request Aug 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

lgtm This PR has been approved by a maintainer size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants