Skip to content

stages/user_login: refuse to log in an unsaved pending user - #21691

Merged
BeryJu merged 7 commits into
goauthentik:mainfrom
SAY-5:fix/user-login-unsaved-pending
Jul 13, 2026
Merged

BeryJu merged 7 commits into
goauthentik:mainfrom
SAY-5:fix/user-login-unsaved-pending

Conversation

@SAY-5

@SAY-5 SAY-5 commented Apr 18, 2026 •

Copy link
Copy Markdown
Contributor

What

UserLoginStageView.do_login reads PLAN_CONTEXT_PENDING_USER and hands the resulting User to is_known_device() and Django's login():

user: User = self.executor.plan.context[PLAN_CONTEXT_PENDING_USER]
if not user.is_active:
    ...
self.executor.plan.context[PLAN_CONTEXT_METHOD_ARGS].setdefault(
    PLAN_CONTEXT_METHOD_ARGS_KNOWN_DEVICE, self.is_known_device(user)
)
with audit_ignore():
    login(self.request, user, backend=backend)

The identification stage plants an unsaved User (pk is None) in PLAN_CONTEXT_PENDING_USER when the supplied identifier is unknown, it exists only so that make_password() runs against something and the timing side-channel that would otherwise leak "user exists vs doesn't" goes away (#18883). That dummy user was previously scoped to the identification stage, but the stage-state refactor (#18641) means it now propagates down the flow plan into do_login.

is_known_device immediately does:

AuthenticatedSession.objects.filter(session__last_ip=client_ip, user=user).exists()

and login() fires the user_logged_in signal, which user_logged_in_session and on_user_logged_in handle with further ORM lookups. All of those are related-field filters, and Django rejects unsaved instances with:

ValueError: Model instances passed to related filters must be saved.

Observable effect: on a default authentication flow that has an enrollment flow linked, typing an unknown email into the identification stage returns HTTP 500 instead of redirecting to enrollment or showing the usual invalid-login message. Per #21036.

Fix

Guard at the top of do_login before any user-dependent work runs:

user: User = self.executor.plan.context[PLAN_CONTEXT_PENDING_USER]
if user.pk is None:
    self.logger.debug("pending user is not saved, refusing to log in")
    return self.executor.stage_invalid()
if not user.is_active:
    ...

Any code path that produced an unsaved PENDING_USER now ends in stage_invalid, never reaches is_known_device, login(), or the signal chain. The existing is_active check stays: an unsaved User() defaults to is_active=True, so the pk guard has to run first.

Why here rather than in the signal handlers

The signal handlers (user_logged_in_session, on_user_logged_in) and is_known_device are three separate call sites that would each need a pk guard, and the bug would come back the next time someone added a fourth caller. Gating at do_login is the single chokepoint for "we are about to log a user in" and matches the existing is_active check placement.

Fixes #21036

The identification stage plants an unsaved User (pk is None) in
PLAN_CONTEXT_PENDING_USER when the supplied identifier is unknown;
it exists only to normalise the timing against make_password() so
the enumeration oracle goes away. Since the pending_user now
propagates further down the flow plan, that dummy user reaches
do_login, which calls is_known_device (which does
`AuthenticatedSession.objects.filter(..., user=user).exists()`) and
then Django's login(), which fires user_logged_in_session and
on_user_logged_in signal handlers that also open related-field
filters. Related-field filters reject unsaved instances and throw:

	ValueError: Model instances passed to related filters must be saved.

The flow currently returns HTTP 500 on any "unknown email on a
default flow with enrollment linked" path instead of redirecting
to the enrollment flow or showing the usual invalid-login message.

Guard at do_login entry so any code path that produced an unsaved
PENDING_USER ends in stage_invalid, never in is_known_device or the
login signal chain. The existing is_active check stays: an unsaved
user defaults to is_active=True so the pk guard has to run first.

Fixes goauthentik#21036

Signed-off-by: SAY-5 <[email protected]>
@SAY-5
SAY-5 requested a review from a team as a code owner April 18, 2026 08:50
@netlify

netlify Bot commented Apr 18, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for authentik-docs ready!

Name Link
🔨 Latest commit c1f6724
🔍 Latest deploy log https://app.netlify.com/projects/authentik-docs/deploys/6a17fd0b7e7d6c000973bdab
😎 Deploy Preview https://deploy-preview-21691--authentik-docs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@codecov

codecov Bot commented Apr 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.20%. Comparing base (bc65b25) to head (6759cae).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #21691      +/-   ##
==========================================
+ Coverage   93.15%   93.20%   +0.05%     
==========================================
  Files        1037     1045       +8     
  Lines       60783    61220     +437     
  Branches        0      424     +424     
==========================================
+ Hits        56621    57059     +438     
+ Misses       4162     4161       -1     
Flag Coverage Δ
conformance 36.20% <7.14%> (+0.29%) ⬆️
e2e 41.37% <7.14%> (?)
integration 32.13% <0.00%> (-0.50%) ⬇️
rust 0.00% <ø> (?)
unit 92.35% <100.00%> (+7.30%) ⬆️
unit-migrate 92.37% <100.00%> (-0.03%) ⬇️

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

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

Comment thread authentik/stages/user_login/stage.py Resolved
@netlify

netlify Bot commented Apr 23, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for authentik-integrations ready!

Name Link
🔨 Latest commit c1f6724
🔍 Latest deploy log https://app.netlify.com/projects/authentik-integrations/deploys/6a17fd0bf3082500088e26f6
😎 Deploy Preview https://deploy-preview-21691--authentik-integrations.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@netlify

netlify Bot commented Apr 23, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for authentik-storybook ready!

Name Link
🔨 Latest commit c1f6724
🔍 Latest deploy log https://app.netlify.com/projects/authentik-storybook/deploys/6a17fd0b6322e300080d3c1b
😎 Deploy Preview https://deploy-preview-21691--authentik-storybook.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

BeryJu and others added 2 commits April 23, 2026 23:07
The fallback comment around the user.pk None check was a single
137-character line. ruff's E501 line-length rule (max 100) flagged it.
Wrapped onto four 80-column lines with no behavioural change.

Signed-off-by: SAY-5 <[email protected]>
@SAY-5

SAY-5 commented May 5, 2026 •

Copy link
Copy Markdown
Contributor Author

The only failing check is codecov/patch, coverage threshold, not a real test failure. The patch is a small precondition check in stages/user_login to refuse logging in an unsaved pending user; can add a unit test for this branch if useful.

@BeryJu
BeryJu merged commit 9d602a1 into goauthentik:main Jul 13, 2026
116 checks passed
kensternberg-authentik added a commit that referenced this pull request Jul 13, 2026
* main: (30 commits)
  providers/saml: catch InvalidVersion from cryptography when parsing metadata (#21185)
  stages/user_login: refuse to log in an unsaved pending user (#21691)
  web/admin: hide previous loglist when no previous logs available (#23954)
  stages/email: fix ungrammatical expiry time in password reset templates (#22758)
  tests/openid_conformance: Add more conformance coverage (#22174)
  sources/ldap: derive TLS SNI name from hostname, not full server URI (#22456)
  core: bump github.com/grafana/pyroscope-go from 1.3.1 to 1.4.0 (#23885)
  web: Fix Log Viewer Intersection Observer. (#23861)
  web: bump the goauthentik group across 1 directory with 2 updates (#23926)
  ci: bump regclient/actions/regctl-login from 4b4db1dcc7dad75ad67a788a380f75a20cc8a040 to 39bf30ced4be9d147faaabbde2682e9725fb8bd1 (#23890)
  ci: bump regclient/actions/regctl-installer from 4b4db1dcc7dad75ad67a788a380f75a20cc8a040 to 39bf30ced4be9d147faaabbde2682e9725fb8bd1 (#23891)
  core: bump pnpm/pnpm from 11.10.0 to 11.11.0 in /website (#23930)
  core: bump pnpm/pnpm from 11.10.0 to 11.11.0 in /lifecycle/container (#23927)
  core: bump github.com/sethvargo/go-envconfig from 1.3.0 to 1.3.1 (#23921)
  core: bump goauthentik/selenium from 149.0-ak-0.50.1 to 149.0-ak-0.50.2 in /tests/e2e (#23924)
  core: bump uvicorn[standard] from 0.49.0 to 0.50.0 (#23925)
  core: bump ruff from 0.15.20 to 0.15.21 (#23928)
  core: bump goauthentik/fips-python from `aaaab46` to `0798f3b` in /lifecycle/container (#23929)
  ci: bump actions/stale from 10.3.0 to 10.4.0 (#23935)
  ci: bump github/codeql-action/autobuild from 4.36.3 to 4.37.0 (#23931)
  ...
kensternberg-authentik added a commit that referenced this pull request Jul 13, 2026
* main: (48 commits)
  web/bug: harmonize and make routine the display of tasks (part 2: description list abuse) (#23839)
  providers/oauth2: fix iframe logout stage progression (#23919)
  providers/scim: improve error display when error doesn't conform to scim schema (#23955)
  providers/saml: catch InvalidVersion from cryptography when parsing metadata (#21185)
  stages/user_login: refuse to log in an unsaved pending user (#21691)
  web/admin: hide previous loglist when no previous logs available (#23954)
  stages/email: fix ungrammatical expiry time in password reset templates (#22758)
  tests/openid_conformance: Add more conformance coverage (#22174)
  sources/ldap: derive TLS SNI name from hostname, not full server URI (#22456)
  core: bump github.com/grafana/pyroscope-go from 1.3.1 to 1.4.0 (#23885)
  web: Fix Log Viewer Intersection Observer. (#23861)
  web: bump the goauthentik group across 1 directory with 2 updates (#23926)
  ci: bump regclient/actions/regctl-login from 4b4db1dcc7dad75ad67a788a380f75a20cc8a040 to 39bf30ced4be9d147faaabbde2682e9725fb8bd1 (#23890)
  ci: bump regclient/actions/regctl-installer from 4b4db1dcc7dad75ad67a788a380f75a20cc8a040 to 39bf30ced4be9d147faaabbde2682e9725fb8bd1 (#23891)
  core: bump pnpm/pnpm from 11.10.0 to 11.11.0 in /website (#23930)
  core: bump pnpm/pnpm from 11.10.0 to 11.11.0 in /lifecycle/container (#23927)
  core: bump github.com/sethvargo/go-envconfig from 1.3.0 to 1.3.1 (#23921)
  core: bump goauthentik/selenium from 149.0-ak-0.50.1 to 149.0-ak-0.50.2 in /tests/e2e (#23924)
  core: bump uvicorn[standard] from 0.49.0 to 0.50.0 (#23925)
  core: bump ruff from 0.15.20 to 0.15.21 (#23928)
  ...
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.

Authentication flow crashes with ValueError on unknown email input when enrollment flow is configured (2026.2.x)

2 participants