Skip to content

core: split users list superuser annotation in API into two EXISTS subqueries (cherry-pick #26275 to version-2026.8) - #27462

Merged
BeryJu merged 2 commits into
version-2026.8from
cherry-pick/26275-to-version-2026.8
Nov 5, 2026
Merged

BeryJu merged 2 commits into
version-2026.8from
cherry-pick/26275-to-version-2026.8

Conversation

@authentik-cherry-pick

Copy link
Copy Markdown
Contributor

Cherry-pick of #26275 to version-2026.8 branch.

Original PR: #26275
Original Author: @ryanpesek
Cherry-picked commit: 9d8323b

…bqueries (#26275)

* core: split users list superuser annotation into two EXISTS subqueries

UserViewSet annotates every user with is_superuser using one EXISTS with
an OR across two join paths: direct membership of a superuser group, and
membership of a descendant group through authentik_core_groupancestry.
PostgreSQL can't convert a subquery whose OR mixes two correlated
conditions into a hashed subplan, so it runs once per user row, including
rows skipped by OFFSET and inside DISTINCT/COUNT wrappers. Its join plan
also depends on the ancestry materialized view's statistics: once a first
group hierarchy exists and the view's stats are stale, the planner can
pick a merge join that scans every group for every user.

Use two separate EXISTS subqueries combined with OR instead. Each one is
correlated only by user id equality, so PostgreSQL can run it once per
query as a hashed subplan. The result is unchanged: a user is a superuser
if they are a member of a superuser group or of any of its descendants,
the same as User.is_superuser.

Add tests for direct, child, grandchild, non-superuser parent and no
group membership in the list and detail endpoints, and check that the
list doesn't add group queries per user.

* core: drop ExpressionWrapper from superuser annotation

Exists | Exists already resolves to a Q with a boolean output field, so
the wrapper isn't needed. The generated SQL is unchanged.
@netlify

netlify Bot commented Nov 2, 2026

Copy link
Copy Markdown

✅ Deploy Preview for authentik-storybook ready!

Name Link
🔨 Latest commit be48af7
🔍 Latest deploy log https://app.netlify.com/projects/authentik-storybook/deploys/6ae8f3a5861ef3fe454417e3
😎 Deploy Preview https://deploy-preview-27462--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.

@netlify

netlify Bot commented Nov 2, 2026

Copy link
Copy Markdown

✅ Deploy Preview for authentik-integrations ready!

Name Link
🔨 Latest commit be48af7
🔍 Latest deploy log https://app.netlify.com/projects/authentik-integrations/deploys/6ae8f3a530ad96715b542216
😎 Deploy Preview https://deploy-preview-27462--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.

@codecov

codecov Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

❌ 1 Tests Failed:

Tests completed Failed Passed Skipped
4369 1 4368 1
View the top 1 failed test(s) by shortest run time
tests.e2e.test_source_oauth_oauth2.TestSourceOAuth2::test_oauth_link
Stack Traces | 16.5s run time
self = <unittest.case._Outcome object at 0x7aabccc887d0>
test_case = <tests.e2e.test_source_oauth_oauth2.TestSourceOAuth2 testMethod=test_oauth_link>
subTest = False

    @contextlib.contextmanager
    def testPartExecutor(self, test_case, subTest=False):
        old_success = self.success
        self.success = True
        try:
>           yield

.../hostedtoolcache/Python/3.14.9................../x64/lib/python3.14/unittest/case.py:58: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <tests.e2e.test_source_oauth_oauth2.TestSourceOAuth2 testMethod=test_oauth_link>
result = <TestCaseFunction test_oauth_link>

    def run(self, result=None):
        if result is None:
            result = self.defaultTestResult()
            startTestRun = getattr(result, 'startTestRun', None)
            stopTestRun = getattr(result, 'stopTestRun', None)
            if startTestRun is not None:
                startTestRun()
        else:
            stopTestRun = None
    
        result.startTest(self)
        try:
            testMethod = getattr(self, self._testMethodName)
            if (getattr(self.__class__, "__unittest_skip__", False) or
                getattr(testMethod, "__unittest_skip__", False)):
                # If the class or method was skipped.
                skip_why = (getattr(self.__class__, '__unittest_skip_why__', '')
                            or getattr(testMethod, '__unittest_skip_why__', ''))
                _addSkip(result, self, skip_why)
                return result
    
            expecting_failure = (
                getattr(self, "__unittest_expecting_failure__", False) or
                getattr(testMethod, "__unittest_expecting_failure__", False)
            )
            outcome = _Outcome(result)
            start_time = time.perf_counter()
            try:
                self._outcome = outcome
    
                with outcome.testPartExecutor(self):
                    self._callSetUp()
                if outcome.success:
                    outcome.expecting_failure = expecting_failure
                    with outcome.testPartExecutor(self):
>                       self._callTestMethod(testMethod)

.../hostedtoolcache/Python/3.14.9................../x64/lib/python3.14/unittest/case.py:669: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <tests.e2e.test_source_oauth_oauth2.TestSourceOAuth2 testMethod=test_oauth_link>
method = <bound method TestSourceOAuth2.test_oauth_link of <tests.e2e.test_source_oauth_oauth2.TestSourceOAuth2 testMethod=test_oauth_link>>

    def _callTestMethod(self, method):
>       result = method()
                 ^^^^^^^^

.../hostedtoolcache/Python/3.14.9................../x64/lib/python3.14/unittest/case.py:615: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <tests.e2e.test_source_oauth_oauth2.TestSourceOAuth2 testMethod=test_oauth_link>
args = (), kwargs = {}

    @wraps(func)
    def wrapper(self: TransactionTestCase, *args, **kwargs):
        """Run test again if we're below max_retries, including tearDown and
        setUp. Otherwise raise the error"""
        nonlocal count
        try:
>           return func(self, *args, **kwargs)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^

tests/decorators.py:60: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

args = (<tests.e2e.test_source_oauth_oauth2.TestSourceOAuth2 testMethod=test_oauth_link>,)
kwargs = {}

    @wraps(func)
    def wrapper(*args, **kwargs):
        for file in files:
            content = BlueprintInstance(path=file).retrieve()
            Importer.from_string(content).apply()
>       return func(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^

.../blueprints/tests/__init__.py:25: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

args = (<tests.e2e.test_source_oauth_oauth2.TestSourceOAuth2 testMethod=test_oauth_link>,)
kwargs = {}

    @wraps(func)
    def wrapper(*args, **kwargs):
        for file in files:
            content = BlueprintInstance(path=file).retrieve()
            Importer.from_string(content).apply()
>       return func(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^

.../blueprints/tests/__init__.py:25: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <tests.e2e.test_source_oauth_oauth2.TestSourceOAuth2 testMethod=test_oauth_link>

    @retry()
    @apply_blueprint(
        "default/flow-default-authentication-flow.yaml",
        "default/flow-default-invalidation-flow.yaml",
    )
    @apply_blueprint(
        "default/flow-default-source-authentication.yaml",
        "default/flow-default-source-enrollment.yaml",
        "default/flow-default-source-pre-authentication.yaml",
    )
    def test_oauth_link(self) -> None:
        """
        Test OAuth Source link OIDC
    
        This test will enroll the user via OAuth, then log in as admin and link the OAuth
        source to the admin user.
        """
        self.create_objects()
        self.driver.get(self.live_server_url)
        self.login()
    
        # Ensure that a stable session is created before linking.
        sleep(3)
    
        self.driver.get(
            self.url("authentik_sources_oauth:oauth-client-login", source_slug=self.slug)
        )
    
        self.login_via_oauth_provider()
    
        post_login_expected_url = self.if_user_url("/settings;page-sources")
    
>       self.assertEqual(
            self.driver.current_url,
            post_login_expected_url,
            "Expected to be redirected to user settings after linking OAuth source",
        )

tests/e2e/test_source_oauth_oauth2.py:249: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <tests.e2e.test_source_oauth_oauth2.TestSourceOAuth2 testMethod=test_oauth_link>
first = 'http://10.1.0.44:5556/dex/approval?req=jpmq6ydmfhspmgebfmqefnmgt&hmac=rBgZjzlMtLtCKVmW5lI3JIj68BFRXNvyg5Y06XiL414'
second = 'http://10.1.0.44:43081/if/user/#/settings;page-sources'
msg = 'Expected to be redirected to user settings after linking OAuth source'

    def assertEqual(self, first, second, msg=None):
        """Fail if the two objects are unequal as determined by the '=='
           operator.
        """
        assertion_func = self._getAssertEqualityFunc(first, second)
>       assertion_func(first, second, msg=msg)

.../hostedtoolcache/Python/3.14.9................../x64/lib/python3.14/unittest/case.py:925: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <tests.e2e.test_source_oauth_oauth2.TestSourceOAuth2 testMethod=test_oauth_link>
first = 'http://10.1.0.44:5556/dex/approval?req=jpmq6ydmfhspmgebfmqefnmgt&hmac=rBgZjzlMtLtCKVmW5lI3JIj68BFRXNvyg5Y06XiL414'
second = 'http://10.1.0.44:43081/if/user/#/settings;page-sources'
msg = 'Expected to be redirected to user settings after linking OAuth source'

    def assertMultiLineEqual(self, first, second, msg=None):
        """Assert that two multi-line strings are equal."""
        self.assertIsInstance(first, str, "First argument is not a string")
        self.assertIsInstance(second, str, "Second argument is not a string")
    
        if first != second:
            # Don't use difflib if the strings are too long
            if (len(first) > self._diffThreshold or
                len(second) > self._diffThreshold):
                self._baseAssertEqual(first, second, msg)
    
            # Append \n to both strings if either is missing the \n.
            # This allows the final ndiff to show the \n difference. The
            # exception here is if the string is empty, in which case no
            # \n should be added
            first_presplit = first
            second_presplit = second
            if first and second:
                if first[-1] != '\n' or second[-1] != '\n':
                    first_presplit += '\n'
                    second_presplit += '\n'
            elif second and second[-1] != '\n':
                second_presplit += '\n'
            elif first and first[-1] != '\n':
                first_presplit += '\n'
    
            firstlines = first_presplit.splitlines(keepends=True)
            secondlines = second_presplit.splitlines(keepends=True)
    
            # Generate the message and diff, then raise the exception
            standardMsg = '%s != %s' % _common_shorten_repr(first, second)
            diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))
            standardMsg = self._truncateMessage(standardMsg, diff)
>           self.fail(self._formatMessage(msg, standardMsg))

.../hostedtoolcache/Python/3.14.9................../x64/lib/python3.14/unittest/case.py:1291: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <tests.e2e.test_source_oauth_oauth2.TestSourceOAuth2 testMethod=test_oauth_link>
msg = "'http://10.1.0.44:5556/dex/approval?req=jpmq6ydmfhspmgebfmq[51 chars]L414' != 'http://10.1.0.44:43081/if/user/#/setti...1.0.44:43081/if/user/#/settings;page-sources\n : Expected to be redirected to user settings after linking OAuth source"

    def fail(self, msg=None):
        """Fail immediately, with the given message."""
>       raise self.failureException(msg)
E       AssertionError: 'http://10.1.0.44:5556/dex/approval?req=jpmq6ydmfhspmgebfmq[51 chars]L414' != 'http://10.1.0.44:43081/if/user/#/settings;page-sources'
E       - http://10.1.0.44:5556/dex/approval?req=jpmq6ydmfhspmgebfmqefnmgt&hmac=rBgZjzlMtLtCKVmW5lI3JIj68BFRXNvyg5Y06XiL414
E       + http://10.1.0.44:43081/if/user/#/settings;page-sources
E        : Expected to be redirected to user settings after linking OAuth source

.../hostedtoolcache/Python/3.14.9................../x64/lib/python3.14/unittest/case.py:750: AssertionError

To view more test analytics, go to the Test Analytics Dashboard
📋 Got 3 mins? Take this short survey to help us improve Test Analytics.

Signed-off-by: Jens Langhammer <[email protected]>
@netlify

netlify Bot commented Nov 3, 2026

Copy link
Copy Markdown

✅ Deploy Preview for authentik-docs ready!

Name Link
🔨 Latest commit 40b3a66
🔍 Latest deploy log https://app.netlify.com/projects/authentik-docs/deploys/6aea153e9fdf34802f0d60ee
😎 Deploy Preview https://deploy-preview-27462--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.

@BeryJu
BeryJu merged commit c61efb5 into version-2026.8 Nov 5, 2026
213 of 217 checks passed
@BeryJu
BeryJu deleted the cherry-pick/26275-to-version-2026.8 branch November 5, 2026 13:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants