Repository: goauthentik/authentik

Issue:
Web/Admin: Flow running returns 500
**Describe the bug**
Running/testing/inspecting a flow out of the admin fails in a 500 or Json Error.

**To Reproduce**
1. Open admin page
2. Go into detail view of a flow
3. Click any button in the 'run flow' section 

**Expected behavior**
Flow test execution works :)

**Logs**
'with current user'-Button:
```
      GET https://authentik.../api/v3/flows/instances/senbax-login/execute/ 500 (Internal Server Error)
(anonymous) @ fetch.ts:49
(anonymous) @ runtime.js:86
s @ runtime.js:17
Promise.then (async)
f @ runtime.js:19
(anonymous) @ runtime.js:20
yt @ runtime.js:16
fetchApi @ runtime.js:77
(anonymous) @ runtime.js:155
s @ runtime.js:17
Promise.then (async)
f @ runtime.js:19
(anonymous) @ runtime.js:20
yt @ runtime.js:16
request @ runtime.js:153
(anonymous) @ FlowsApi.js:626
(anonymous) @ FlowsApi.js:20
c @ FlowsApi.js:16
flowsInstancesExecuteRetrieveRaw @ FlowsApi.js:613
(anonymous) @ FlowsApi.js:640
(anonymous) @ FlowsApi.js:20
c @ FlowsApi.js:16
flowsInstancesExecuteRetrieve @ FlowsApi.js:639
(anonymous) @ FlowViewPage.ts:168
handleEvent @ lit-html.ts:2068
o @ helpers.ts:100
Show 23 more frames
Show less
runtime.js:159 Uncaught (in promise) ResponseError: Response returned an error code
    at ze.<anonymous> (runtime.js:159:19)
    at Generator.next (<anonymous>)
    at s (runtime.js:17:58)
(anonymous) @ runtime.js:159
s @ runtime.js:17
Promise.then (async)
(anonymous) @ FlowViewPage.ts:171
handleEvent @ lit-html.ts:2068
o @ helpers.ts:100
Show 4 more frames
Show less
```
---
'Inspector'-Button
redirect works, but redirects to error page
```
execute/:1 Uncaught SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at execute/:25:22
(anonymous) @ execute/:25
execute/:1

       Failed to load resource: the server responded with a status of 500 ()
```

**Version and Deployment (please complete the following information):**

-   authentik version: 2024.4.0
-   Deployment: helm

**Additional context**
Maybe we could add an automated test for this.



Discussion:
This will be fixed in 2024.4.1 (assuming it is the same issue that's already been fixed, which is caused by either having a plex or apple oauth source (and those can't really have full e2e tests due to them being SaaS))

For the time being you can use this image: `ghcr.io/goauthentik/dev-server:gh-version-2024.4`
@BeryJu sadly it is not fixed in 2024.4.1. 
Executing a flow with the current user (console error, see above) or in a inspector view (redirect to 500 page).

The flows does not contain plex or apple oauth.
@macmoritz please provide the logs of the server container and any system exception events that might've been created
Trying to execute with current user results in these errors:
authentik-worker:
```log
{"action": "system_exception", "auth_via": "session", "client_ip": "redacted", "context": {"asn": {"as_org": "Deutsche Telekom AG", "asn": redacted, "network": "redacted"}, "geo": {"city": "redacted", "continent": "EU", "country": "DE", "lat": redacted, "long": redacted}, "http_request": {"args": {}, "method": "GET", "path": "/api/v3/flows/instances/default-authentication-flow/execute/", "user_agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"}, "message": "Traceback (most recent call last):\n  File \"/ak-root/venv/lib/python3.12/site-packages/asgiref/sync.py\", line 534, in thread_handler\n    raise exc_info[1]\n  File \"/ak-root/venv/lib/python3.12/site-packages/django/core/handlers/base.py\", line 253, in _get_response_async\n    response = await wrapped_callback(\n               ^^^^^^^^^^^^^^^^^^^^^^^\n  File \"/ak-root/venv/lib/python3.12/site-packages/asgiref/sync.py\", line 479, in __call__\n    ret: _R = await loop.run_in_executor(\n              ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n  File \"/ak-root/venv/lib/python3.12/site-packages/asgiref/current_thread_executor.py\", line 40, in run\n    result = self.fn(*self.args, **self.kwargs)\n             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n  File \"/ak-root/venv/lib/python3.12/site-packages/asgiref/sync.py\", line 538, in thread_handler\n    return func(*args, **kwargs)\n           ^^^^^^^^^^^^^^^^^^^^^\n  File \"/ak-root/venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/views.py\", line 84, in sentry_wrapped_callback\n    return callback(request, *args, **kwargs)\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n  File \"/ak-root/venv/lib/python3.12/site-packages/django/views/decorators/csrf.py\", line 65, in _view_wrapper\n    return view_func(request, *args, **kwargs)\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n  File \"/ak-root/venv/lib/python3.12/site-packages/rest_framework/viewsets.py\", line 125, in view\n    return self.dispatch(request, *args, **kwargs)\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n  File \"/ak-root/venv/lib/python3.12/site-packages/rest_framework/views.py\", line 509, in dispatch\n    response = self.handle_exception(exc)\n               ^^^^^^^^^^^^^^^^^^^^^^^^^^\n  File \"/ak-root/venv/lib/python3.12/site-packages/rest_framework/views.py\", line 469, in handle_exception\n    self.raise_uncaught_exception(exc)\n  File \"/ak-root/venv/lib/python3.12/site-packages/rest_framework/views.py\", line 480, in raise_uncaught_exception\n    raise exc\n  File \"/ak-root/venv/lib/python3.12/site-packages/rest_framework/views.py\", line 506, in dispatch\n    response = handler(request, *args, **kwargs)\n               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nbuiltins.TypeError: FlowViewSet.execute() got an unexpected keyword argument 'slug'"}, "domain_url": "dev.authentik.example.org", "event": "Created Event", "host": "dev.authentik.example.org", "level": "info", "logger": "authentik.events.models", "pid": 40, "request_id": "681668c8d8fe442f8861c3b50b6b55fe", "schema_name": "public", "timestamp": "2024-04-26T22:25:53.867890", "user": {"email": "redacted", "pk": 12, "username": "macmortz"}}
```

js console:
```log
FlowViewPage.ts:168


       GET https://dev.authentik.example.org/api/v3/flows/instances/default-authentication-flow/execute/ 500 (Internal Server Error)
(anonymous) @ fetch.ts:49
(anonymous) @ runtime.js:86
s @ runtime.js:17
Promise.then (async)
f @ runtime.js:19
(anonymous) @ runtime.js:20
yt @ runtime.js:16
fetchApi @ runtime.js:77
(anonymous) @ runtime.js:155
s @ runtime.js:17
Promise.then (async)
f @ runtime.js:19
(anonymous) @ runtime.js:20
yt @ runtime.js:16
request @ runtime.js:153
(anonymous) @ FlowsApi.js:626
(anonymous) @ FlowsApi.js:20
c @ FlowsApi.js:16
flowsInstancesExecuteRetrieveRaw @ FlowsApi.js:613
(anonymous) @ FlowsApi.js:640
(anonymous) @ FlowsApi.js:20
c @ FlowsApi.js:16
flowsInstancesExecuteRetrieve @ FlowsApi.js:639
(anonymous) @ FlowViewPage.ts:168
handleEvent @ lit-html.ts:2068
o @ helpers.ts:100
Show 23 more frames
Show less
runtime.js:159 Uncaught (in promise) ResponseError: Response returned an error code
    at ze.<anonymous> (runtime.js:159:19)
    at Generator.next (<anonymous>)
    at s (runtime.js:17:58)
(anonymous) @ runtime.js:159
s @ runtime.js:17
Promise.then (async)
(anonymous) @ FlowViewPage.ts:171
handleEvent @ lit-html.ts:2068
o @ helpers.ts:100
Show 4 more frames
Show less
```

inspector:
authentik-worker:
```log
{"action": "system_exception", "auth_via": "session", "client_ip": "redacted", "context": {"asn": {"as_org": "Deutsche Telekom AG", "asn": redacted, "network": "redacted"}, "geo": {"city": "redacted", "continent": "EU", "country": "DE", "lat": redacted, "long": redacted}, "http_request": {"args": {}, "method": "GET", "path": "/api/v3/flows/instances/default-authentication-flow/execute/", "user_agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"}, "message": "Traceback (most recent call last):\n  File \"/ak-root/venv/lib/python3.12/site-packages/asgiref/sync.py\", line 534, in thread_handler\n    raise exc_info[1]\n  File \"/ak-root/venv/lib/python3.12/site-packages/django/core/handlers/base.py\", line 253, in _get_response_async\n    response = await wrapped_callback(\n               ^^^^^^^^^^^^^^^^^^^^^^^\n  File \"/ak-root/venv/lib/python3.12/site-packages/asgiref/sync.py\", line 479, in __call__\n    ret: _R = await loop.run_in_executor(\n              ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n  File \"/ak-root/venv/lib/python3.12/site-packages/asgiref/current_thread_executor.py\", line 40, in run\n    result = self.fn(*self.args, **self.kwargs)\n             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n  File \"/ak-root/venv/lib/python3.12/site-packages/asgiref/sync.py\", line 538, in thread_handler\n    return func(*args, **kwargs)\n           ^^^^^^^^^^^^^^^^^^^^^\n  File \"/ak-root/venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/views.py\", line 84, in sentry_wrapped_callback\n    return callback(request, *args, **kwargs)\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n  File \"/ak-root/venv/lib/python3.12/site-packages/django/views/decorators/csrf.py\", line 65, in _view_wrapper\n    return view_func(request, *args, **kwargs)\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n  File \"/ak-root/venv/lib/python3.12/site-packages/rest_framework/viewsets.py\", line 125, in view\n    return self.dispatch(request, *args, **kwargs)\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n  File \"/ak-root/venv/lib/python3.12/site-packages/rest_framework/views.py\", line 509, in dispatch\n    response = self.handle_exception(exc)\n               ^^^^^^^^^^^^^^^^^^^^^^^^^^\n  File \"/ak-root/venv/lib/python3.12/site-packages/rest_framework/views.py\", line 469, in handle_exception\n    self.raise_uncaught_exception(exc)\n  File \"/ak-root/venv/lib/python3.12/site-packages/rest_framework/views.py\", line 480, in raise_uncaught_exception\n    raise exc\n  File \"/ak-root/venv/lib/python3.12/site-packages/rest_framework/views.py\", line 506, in dispatch\n    response = handler(request, *args, **kwargs)\n               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nbuiltins.TypeError: FlowViewSet.execute() got an unexpected keyword argument 'slug'"}, "domain_url": "dev.authentik.example.org", "event": "Created Event", "host": "dev.authentik.example.org", "level": "info", "logger": "authentik.events.models", "pid": 40, "request_id": "802698b7115242818e2e3071e7bb7f05", "schema_name": "public", "timestamp": "2024-04-26T22:31:23.864036", "user": {"email": redacted", "pk": 12, "username": "macmoritz"}}
```

js console:
```log
execute/:1 Uncaught SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at execute/:25:22
(anonymous) @ execute/:25
execute/:1


       Failed to load resource: the server responded with a status of 500 ()
```

I hope this helps @BeryJu!

Resolving patch:
diff --git a/authentik/flows/api/flows.py b/authentik/flows/api/flows.py
--- a/authentik/flows/api/flows.py
+++ b/authentik/flows/api/flows.py
@@ -278,7 +278,7 @@ def set_background_url(self, request: Request, slug: str):
         },
     )
     @action(detail=True, pagination_class=None, filter_backends=[])
-    def execute(self, request: Request, _slug: str):
+    def execute(self, request: Request, slug: str):
         """Execute flow for current user"""
         # Because we pre-plan the flow here, and not in the planner, we need to manually clear
         # the history of the inspector


Test patch:
diff --git a/authentik/flows/tests/test_api.py b/authentik/flows/tests/test_api.py
--- a/authentik/flows/tests/test_api.py
+++ b/authentik/flows/tests/test_api.py
@@ -6,6 +6,7 @@
 from authentik.core.tests.utils import create_test_admin_user
 from authentik.flows.api.stages import StageSerializer, StageViewSet
 from authentik.flows.models import Flow, FlowDesignation, FlowStageBinding, Stage
+from authentik.lib.generators import generate_id
 from authentik.policies.dummy.models import DummyPolicy
 from authentik.policies.models import PolicyBinding
 from authentik.stages.dummy.models import DummyStage
@@ -101,3 +102,21 @@ def test_types(self):
             reverse("authentik_api:stage-types"),
         )
         self.assertEqual(response.status_code, 200)
+
+    def test_execute(self):
+        """Test execute endpoint"""
+        user = create_test_admin_user()
+        self.client.force_login(user)
+
+        flow = Flow.objects.create(
+            name=generate_id(),
+            slug=generate_id(),
+            designation=FlowDesignation.AUTHENTICATION,
+        )
+        FlowStageBinding.objects.create(
+            target=flow, stage=DummyStage.objects.create(name=generate_id()), order=0
+        )
+        response = self.client.get(
+            reverse("authentik_api:flow-execute", kwargs={"slug": flow.slug})
+        )
+        self.assertEqual(response.status_code, 200)