Skip to content

core: Make Application List cache timeout a configurable option - #26552

Closed
kensternberg-authentik wants to merge 3 commits into
mainfrom
web/policies/make-cache-clear-schedule-configurable
Closed

kensternberg-authentik wants to merge 3 commits into
mainfrom
web/policies/make-cache-clear-schedule-configurable

Conversation

@kensternberg-authentik

Copy link
Copy Markdown
Contributor

core/applications: Make Application List cache timeout a configurable option

What

Adds a new field to AdminSettings: applicationCacheTimeout, makes it a TimeDelta field, applies the current value (24 hours) as the default, makes it visible in the API, and applies it core/api/applications to control the timeout for the application cache.

Adds a corresponding field to the UI’s AdminSettingsForm.

Why

Answering issue #26279: @BeryJu suggested: “A better option would including making the default cache duration shorter.” So why not make it configurable?


Checklist

  • [🐋] The project has been linted, built, and tested (make all)
  • [🐋] The documentation has been updated and formatted (make docs)
  • [🐋] I have read the AI usage policy.

## What

Delete the second `cache.delete_many` in `PolicyViewSet.cache_clear`, because it expresses a subset of what is deleted in the first, so it effectively does nothing.

## Details

Both `core/api/applications.py` and `policies/api/policies.py` both import

    from authentik.policies.types import CACHE_PREFIX

`policies/api/policies.py` performs the following cache-clearing:

             keys = cache.keys(f"{CACHE_PREFIX}*")
             cache.delete_many(keys)

             keys = cache.keys(user_app_cache_key("*"))
             cache.delete_many(keys)

However, the `user_app_cache_clear`, defined in `core/api/applications.py` includes the `CACHE_PREFIX` as its prefix; they’re not different:

        """Cache key where application list for user is saved"""
        key = f"{CACHE_PREFIX}app_access/{user_pk}"

The second cache-clearing `.keys()` retrieval will always be empty. The effect does nothing.
… option

## What

Adds a new field to AdminSettings: `applicationCacheTimeout`, makes it a TimeDelta field, applies the current value (24 hours) as the default, makes it visible in the API, and applies it `core/api/applications` to control the timeout for the application cache.

Adds a corresponding field to the UI’s AdminSettingsForm.

## Why

Answering issue \#26279: @BeryJu [suggested](#26279 (comment)): “A better option would including making the default cache duration shorter.” So why not make it configurable?
@kensternberg-authentik
kensternberg-authentik changed the base branch from main to web/policies/remove-duplicate-cache-clear September 29, 2026 20:51
@netlify

netlify Bot commented Sep 29, 2026

Copy link
Copy Markdown

✅ Deploy Preview for authentik-docs ready!

Name Link
🔨 Latest commit 2977751
🔍 Latest deploy log https://app.netlify.com/projects/authentik-docs/deploys/6abc24aad869fa000825c407
😎 Deploy Preview https://deploy-preview-26552--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 Sep 29, 2026 •

Copy link
Copy Markdown

❌ 5 Tests Failed:

Tests completed Failed Passed Skipped
4583 5 4578 14
View the top 3 failed test(s) by shortest run time
ak-mdx.test.ts::ak-mdx renders compiled markdown › links are wrapped in <ak-md-a> with build-time URL resolution
Stack Traces | 43s run time
locator.click: Error: strict mode violation: getByRole('button', { name: 'New Provider' }) resolved to 2 elements:
1000-captcha.test.ts::CAPTCHA stage › Renders the hCaptcha widget without a wrapper iframe
Stack Traces | 57.4s run time
hCaptcha renders its own frame
1000-captcha.test.ts::CAPTCHA stage › Solving the hCaptcha challenge advances the flow
Stack Traces | 57.4s run time
hCaptcha renders its own frame
1000-captcha.test.ts::CAPTCHA stage › Renders the correct vendor when two providers share a document
Stack Traces | 90.7s run time
Both providers' globals share the document
tests.e2e.test_provider_rac.TestProviderRAC::test_rac_ssh_certificate
Stack Traces | 129s run time
self = <unittest.case._Outcome object at 0x7f1c5f590050>
test_case = <tests.e2e.test_provider_rac.TestProviderRAC testMethod=test_rac_ssh_certificate>
subTest = False

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

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

self = <tests.e2e.test_provider_rac.TestProviderRAC testMethod=test_rac_ssh_certificate>
result = <TestCaseFunction test_rac_ssh_certificate>

    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.7................../x64/lib/python3.14/unittest/case.py:669: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <tests.e2e.test_provider_rac.TestProviderRAC testMethod=test_rac_ssh_certificate>
method = <bound method TestProviderRAC.test_rac_ssh_certificate of <tests.e2e.test_provider_rac.TestProviderRAC testMethod=test_rac_ssh_certificate>>

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

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

self = <tests.e2e.test_provider_rac.TestProviderRAC testMethod=test_rac_ssh_certificate>
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_provider_rac.TestProviderRAC testMethod=test_rac_ssh_certificate>,)
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_provider_rac.TestProviderRAC testMethod=test_rac_ssh_certificate>,)
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_provider_rac.TestProviderRAC testMethod=test_rac_ssh_certificate>,)
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_provider_rac.TestProviderRAC testMethod=test_rac_ssh_certificate>,)
kwargs = {}

    @wraps(func)
    def wrapper(*args, **kwargs):
        config = apps.get_app_config(app_name)
        if isinstance(config, ManagedAppConfig):
            config._on_startup_callback(None)
>       return func(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^

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

self = <tests.e2e.test_provider_rac.TestProviderRAC testMethod=test_rac_ssh_certificate>

    @retry()
    @apply_blueprint(
        "default/flow-default-authentication-flow.yaml",
        "default/flow-default-invalidation-flow.yaml",
    )
    @apply_blueprint(
        "default/flow-default-provider-authorization-implicit-consent.yaml",
        "default/flow-default-provider-invalidation.yaml",
    )
    @apply_blueprint(
        "system/providers-rac.yaml",
    )
    @reconcile_app("authentik_crypto")
    def test_rac_ssh_certificate(self):
        """Test SSH RAC to a device managed by the authentik agent, which is logged
        into as the authentik user with a certificate instead of credentials"""
        # libnss-authentik on the device resolves this user by a POSIX-valid username,
        # unlike the mixed-case one self.user gets by default
        self.user = create_test_admin_user(name=f"e2e-{generate_id(8).lower()}")
        device, machine = self.enroll_agent()
    
        rac: RACProvider = RACProvider.objects.create(
            name=generate_id(),
            authorization_flow=Flow.objects.get(
                slug="default-provider-authorization-implicit-consent"
            ),
            delete_token_on_disconnect=True,
        )
        app = Application.objects.create(name=generate_id(), slug=generate_id(), provider=rac)
        outpost: Outpost = Outpost.objects.create(
            name=generate_id(),
            type=OutpostType.RAC,
        )
        outpost.providers.add(rac)
        outpost.build_user_permissions(outpost.user)
    
        self.start_rac(outpost)
    
        self.driver.get(
            self.url(
                "authentik_providers_rac:start",
                app=app.slug,
                device=device.pk,
                protocol=Protocols.SSH,
            )
        )
        self.login()
        sleep(1)
    
        iface = self.driver.find_element(By.CSS_SELECTOR, "ak-rac")
        sleep(5)
        state = self.driver.execute_script("return arguments[0].clientState", iface)
        self.assertEqual(state, 3)
    
        # Being logged in as the authentik user means the certificate authenticated it
        uid = generate_id()
        self.driver.find_element(By.CSS_SELECTOR, "body").send_keys(
            f"whoami > /tmp/{uid}" + Keys.ENTER
        )
    
        sleep(2)
    
        _, output = machine.exec_run(f"cat /tmp/{uid}")
>       self.assertEqual(output.decode().strip(), self.user.username)

tests/e2e/test_provider_rac.py:214: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <tests.e2e.test_provider_rac.TestProviderRAC testMethod=test_rac_ssh_certificate>
first = 'cat: /tmp/wlcpISq7OzHAngNMBwdsEGlY08rS1s3wdPIbK9QH: No such file or directory'
second = 'e2e-iv1nhfff', msg = None

    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.7................../x64/lib/python3.14/unittest/case.py:925: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <tests.e2e.test_provider_rac.TestProviderRAC testMethod=test_rac_ssh_certificate>
first = 'cat: /tmp/wlcpISq7OzHAngNMBwdsEGlY08rS1s3wdPIbK9QH: No such file or directory'
second = 'e2e-iv1nhfff', msg = None

    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.7................../x64/lib/python3.14/unittest/case.py:1291: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <tests.e2e.test_provider_rac.TestProviderRAC testMethod=test_rac_ssh_certificate>
msg = "'cat: /tmp/wlcpISq7OzHAngNMBwdsEGlY08rS1s3wdPIbK9QH: No such file or directory' != 'e2e-iv1nhfff'\n- cat: /tmp/wlcpISq7OzHAngNMBwdsEGlY08rS1s3wdPIbK9QH: No such file or directory\n+ e2e-iv1nhfff\n"

    def fail(self, msg=None):
        """Fail immediately, with the given message."""
>       raise self.failureException(msg)
E       AssertionError: 'cat: /tmp/wlcpISq7OzHAngNMBwdsEGlY08rS1s3wdPIbK9QH: No such file or directory' != 'e2e-iv1nhfff'
E       - cat: /tmp/wlcpISq7OzHAngNMBwdsEGlY08rS1s3wdPIbK9QH: No such file or directory
E       + e2e-iv1nhfff

.../hostedtoolcache/Python/3.14.7................../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.

@github-actions

Copy link
Copy Markdown
Contributor

Playwright e2e

Download this run's HTML report and traces, then open the report:

gh run download 36629233545 -D playwright-artifacts
npx playwright show-report playwright-artifacts/playwright-report

@kensternberg-authentik
kensternberg-authentik marked this pull request as ready for review September 29, 2026 21:14
@BeryJu BeryJu changed the title core/applications: Make Application List cache timeout a configurable option core: Make Application List cache timeout a configurable option Sep 30, 2026

@BeryJu BeryJu 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.

change is good, imo this should be config setting in lib/default.yml

Base automatically changed from web/policies/remove-duplicate-cache-clear to main September 30, 2026 17:44
@kensternberg-authentik

Copy link
Copy Markdown
Contributor Author

This is being closed in favor of #26596, which makes it a startup option in default.yml. Less machinery, less CPU, and the better place to put it.

@kensternberg-authentik
kensternberg-authentik deleted the web/policies/make-cache-clear-schedule-configurable branch October 30, 2026 23:32
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.

2 participants