internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: goauthentik/authentik

Issue:
SMS Authenticator Setup Stage with generic provider does not work without mapping 
**Describe the bug**
Setting up the stage and flow works but trying to set up an mfa device results in an error after entering the phone number

**To Reproduce**
Create a SMS Authenticator Setup Stage with a generic provider and without mapping

**Expected behavior**
sms should be send

**Version and Deployment (please complete the following information):**
- current main



Discussion:

Resolving patch:
diff --git a/authentik/stages/authenticator_sms/models.py b/authentik/stages/authenticator_sms/models.py
--- a/authentik/stages/authenticator_sms/models.py
+++ b/authentik/stages/authenticator_sms/models.py
@@ -99,7 +99,7 @@ def send_generic(self, token: str, device: "SMSDevice"):
             "From": self.from_number,
             "To": device.phone_number,
             "Body": token,
-            "Message": self.get_message(token),
+            "Message": str(self.get_message(token)),
         }
 
         if self.mapping:


Test patch:
Repository: goauthentik/authentik

Issue:
Add UnwillingToPerformError to ldap/password.py:95
**Is your feature request related to a problem? Please describe.**
Authentik tries to modify the password the AD way, which uses a `modify` operation with the `unicodePwd` field, and then if it gets an `AttributeError` it tries the extended operation. However, [LLDAP](https://github.com/lldap/lldap) doesn't return an `AttributeError` but an `UnwillingToPerformError` since LLDAP doesn't support the modify operation at all, so it completely fails.

**Describe the solution you'd like**
Add an `UnwillingToPerformError` to the `except` on [`ldap/password.py:95`](https://github.com/goauthentik/authentik/blob/main/authentik/sources/ldap/password.py#L95)

**Describe alternatives you've considered**
There's no alternative.

**Additional context**
• [LLDAP log](https://cdn.discordapp.com/attachments/1108339414494613514/1108870676980449300/dockerlogs.txt)
<details>
<summary>Authentik Event Log</summary>
<img width="1604" alt="image" src="https://github.com/goauthentik/authentik/assets/2737082/047b64fa-468f-4a91-b5e7-4eecd27768b6">
</details>


This is a follow-up on https://github.com/goauthentik/authentik/issues/5652.



Discussion:

Resolving patch:
diff --git a/authentik/sources/ldap/password.py b/authentik/sources/ldap/password.py
--- a/authentik/sources/ldap/password.py
+++ b/authentik/sources/ldap/password.py
@@ -4,7 +4,7 @@
 from typing import Optional
 
 from ldap3 import BASE
-from ldap3.core.exceptions import LDAPAttributeError
+from ldap3.core.exceptions import LDAPAttributeError, LDAPUnwillingToPerformResult
 from structlog.stdlib import get_logger
 
 from authentik.core.models import User
@@ -69,7 +69,7 @@ def check_ad_password_complexity_enabled(self) -> bool:
                 attributes=["pwdProperties"],
             )
             root_attrs = list(root_attrs)[0]
-        except (LDAPAttributeError, KeyError, IndexError):
+        except (LDAPAttributeError, LDAPUnwillingToPerformResult, KeyError, IndexError):
             return False
         raw_pwd_properties = root_attrs.get("attributes", {}).get("pwdProperties", None)
         if not raw_pwd_properties:
@@ -92,7 +92,7 @@ def change_password(self, user: User, password: str):
             return
         try:
             self._connection.extend.microsoft.modify_password(user_dn, password)
-        except LDAPAttributeError:
+        except (LDAPAttributeError, LDAPUnwillingToPerformResult):
             self._connection.extend.standard.modify_password(user_dn, new_password=password)
 
     def _ad_check_password_existing(self, password: str, user_dn: str) -> bool:


Test patch:
Repository: goauthentik/authentik

Issue:
API GET /core/users/ with uuid filter leads to (500) internal server error
**Describe the bug**
Hello everyone i'm currently struggeling with the API. Regarding the API documentation the API method "GET /core/users/" describes different kind of filtering mechanism. One is  by using the http query parameter "uuid (string)" which should filter the user by the uid.

But whenever i'm using this parameter i end up getting an internal server error (500). I need to retreive the user by it's uid (not the internal pk (int)). For me it looks like a bug. Can u help me with that? other parameters like search and username are working as expected.

**To Reproduce**
Steps to reproduce the behavior:

1. Install Authentik
2. Execute an GET request i.e.
`"http://localhost:9000/api/v3/core/users/?uuid=8d5440262e02c36a33dd9d78c5aea0d77cec0ab7a11848364e64919734fc30db"
`or
`Use the api web interface http://localhost:9000/api/v3
`

**Expected behavior**
Return the users machting the applied uid filter.

**Version and Deployment (please complete the following information):**

-   authentik version: 2023.6.0 (latest). Also tried some older versions without success.
-   Deployed with docker-compose (latest)

i hope everything is explained clearly. 
Best regards


Discussion:

Resolving patch:
diff --git a/authentik/core/api/users.py b/authentik/core/api/users.py
--- a/authentik/core/api/users.py
+++ b/authentik/core/api/users.py
@@ -15,7 +15,7 @@
 from django.utils.text import slugify
 from django.utils.timezone import now
 from django.utils.translation import gettext as _
-from django_filters.filters import BooleanFilter, CharFilter, ModelMultipleChoiceFilter
+from django_filters.filters import BooleanFilter, CharFilter, ModelMultipleChoiceFilter, UUIDFilter
 from django_filters.filterset import FilterSet
 from drf_spectacular.types import OpenApiTypes
 from drf_spectacular.utils import (
@@ -284,7 +284,7 @@ class UsersFilter(FilterSet):
     )
 
     is_superuser = BooleanFilter(field_name="ak_groups", lookup_expr="is_superuser")
-    uuid = CharFilter(field_name="uuid")
+    uuid = UUIDFilter(field_name="uuid")
 
     path = CharFilter(
         field_name="path",


Test patch:
Repository: goauthentik/authentik

Issue:
docker compose run --rm server ldap_sync - doesn't work anymore to debug
**Describe the bug**
this command doesnt work anymore as described here (https://goauthentik.io/docs/troubleshooting/ldap_source)
```
docker compose run --rm server ldap_sync nxnet
```
it will just create a backgorund taks instead of running it in foreground!

**To Reproduce**
```
docker compose run --rm server ldap_sync SLUGofLDAPsource
```

**Expected behavior**
it will run an LDAP- synchronization in the foreground and see any errors or warnings that might happen directly

**Logs**
{"event": "Task published", "level": "info", "logger": "authentik.root.celery", "pid": 7, "task_id": "17af668f-1d9f-4732-a0eb-044c4a16beed", "task_name": "authentik.sources.ldap.tasks.ldap_sync", "timestamp": "2023-07-20T15:10:12.575247"}

**Version and Deployment (please complete the following information):**

-   authentik version: 2023.6.1
-   Deployment: docker compose




Discussion:

Resolving patch:
diff --git a/authentik/sources/ldap/management/commands/ldap_sync.py b/authentik/sources/ldap/management/commands/ldap_sync.py
--- a/authentik/sources/ldap/management/commands/ldap_sync.py
+++ b/authentik/sources/ldap/management/commands/ldap_sync.py
@@ -3,7 +3,10 @@
 from structlog.stdlib import get_logger
 
 from authentik.sources.ldap.models import LDAPSource
-from authentik.sources.ldap.tasks import ldap_sync_single
+from authentik.sources.ldap.sync.groups import GroupLDAPSynchronizer
+from authentik.sources.ldap.sync.membership import MembershipLDAPSynchronizer
+from authentik.sources.ldap.sync.users import UserLDAPSynchronizer
+from authentik.sources.ldap.tasks import ldap_sync_paginator
 
 LOGGER = get_logger()
 
@@ -20,4 +23,10 @@ def handle(self, **options):
             if not source:
                 LOGGER.warning("Source does not exist", slug=source_slug)
                 continue
-            ldap_sync_single(source)
+            tasks = (
+                ldap_sync_paginator(source, UserLDAPSynchronizer)
+                + ldap_sync_paginator(source, GroupLDAPSynchronizer)
+                + ldap_sync_paginator(source, MembershipLDAPSynchronizer)
+            )
+            for task in tasks:
+                task()
diff --git a/authentik/sources/ldap/sync/users.py b/authentik/sources/ldap/sync/users.py
--- a/authentik/sources/ldap/sync/users.py
+++ b/authentik/sources/ldap/sync/users.py
@@ -49,7 +49,7 @@ def sync(self, page_data: list) -> int:
             uniq = self._flatten(attributes[self._source.object_uniqueness_field])
             try:
                 defaults = self.build_user_properties(user_dn, **attributes)
-                self._logger.debug("Creating user with attributes", **defaults)
+                self._logger.debug("Writing user with attributes", **defaults)
                 if "username" not in defaults:
                     raise IntegrityError("Username was not set by propertymappings")
                 ak_user, created = self.update_or_create_attributes(


Test patch:
Repository: goauthentik/authentik

Issue:
Authentik Users: Sorting by account-active status not working
**Describe the bug**
When choosing to sort users in the "directory > users"-section by "Active" it seems to have no effect and returns the users sorted by name.

**To Reproduce**
1. Go to Directory > Users
2. Sort by Name (ascending)
3. Observe sort
4. Sort by Active (ascending and descending)
5. Observe sort
6. Compare 

**Expected behavior**
Active users should either be on the top or bottom depending on their account active status.
The secondary sorting may be done by name.

**Screenshots**
![image](https://github.com/goauthentik/authentik/assets/44442933/29d25cf9-89f6-4480-a859-7c68151043cf)

**Logs**
-

**Version and Deployment (please complete the following information):**

-   authentik version: 2023.5.3
-   Deployment: docker-compose


Discussion:
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Resolving patch:
diff --git a/authentik/core/api/users.py b/authentik/core/api/users.py
--- a/authentik/core/api/users.py
+++ b/authentik/core/api/users.py
@@ -15,7 +15,13 @@
 from django.utils.text import slugify
 from django.utils.timezone import now
 from django.utils.translation import gettext as _
-from django_filters.filters import BooleanFilter, CharFilter, ModelMultipleChoiceFilter, UUIDFilter
+from django_filters.filters import (
+    BooleanFilter,
+    CharFilter,
+    ModelMultipleChoiceFilter,
+    MultipleChoiceFilter,
+    UUIDFilter,
+)
 from django_filters.filterset import FilterSet
 from drf_spectacular.types import OpenApiTypes
 from drf_spectacular.utils import (
@@ -300,11 +306,11 @@ class UsersFilter(FilterSet):
     is_superuser = BooleanFilter(field_name="ak_groups", lookup_expr="is_superuser")
     uuid = UUIDFilter(field_name="uuid")
 
-    path = CharFilter(
-        field_name="path",
-    )
+    path = CharFilter(field_name="path")
     path_startswith = CharFilter(field_name="path", lookup_expr="startswith")
 
+    type = MultipleChoiceFilter(field_name="type")
+
     groups_by_name = ModelMultipleChoiceFilter(
         field_name="ak_groups__name",
         to_field_name="name",


Test patch:
Repository: goauthentik/authentik

Issue:
Missing application names under 'Apps with most usage'
**Describe the bug**
After upgrading to 2023.8.1, the 'Apps with most usage' table no longer shows any application names.

**To Reproduce**
Steps to reproduce the behavior:

1. Log in with an administrator account
2. Go to the Admin Interface
3. See 'Apps with most usage'. The table will be present, with correct data, but the `Application` column is empty

**Expected behavior**
The `Application` column should contain the correct application names.

**Screenshots**
<img width="402" alt="Screenshot 2023-08-30 at 11 52 14" src="https://github.com/goauthentik/authentik/assets/1585352/d71ffa8b-e055-4161-9210-c6711fff0a92">

**Logs**
N/A

**Version and Deployment:**

-   authentik version: 2023.8.1
-   Deployment: Docker Compose

**Additional context**

The underlying cause seems to be a serialization error in the `/api/v3/events/events/top_per_user/?action=authorize_application&top_n=11` endpoint. The `application` field is serialized as a string, rather than an object, as shown in the following screenshot:

<img width="729" alt="Screenshot 2023-08-30 at 11 56 35" src="https://github.com/goauthentik/authentik/assets/1585352/5315f79d-9952-496a-b525-9981884154fb">






Discussion:

Resolving patch:
diff --git a/authentik/events/api/events.py b/authentik/events/api/events.py
--- a/authentik/events/api/events.py
+++ b/authentik/events/api/events.py
@@ -4,7 +4,7 @@
 
 import django_filters
 from django.db.models.aggregates import Count
-from django.db.models.fields.json import KeyTextTransform
+from django.db.models.fields.json import KeyTextTransform, KeyTransform
 from django.db.models.functions import ExtractDay
 from drf_spectacular.types import OpenApiTypes
 from drf_spectacular.utils import OpenApiParameter, extend_schema
@@ -134,11 +134,11 @@ def top_per_user(self, request: Request):
         """Get the top_n events grouped by user count"""
         filtered_action = request.query_params.get("action", EventAction.LOGIN)
         top_n = int(request.query_params.get("top_n", "15"))
-        return Response(
+        events = (
             get_objects_for_user(request.user, "authentik_events.view_event")
             .filter(action=filtered_action)
             .exclude(context__authorized_application=None)
-            .annotate(application=KeyTextTransform("authorized_application", "context"))
+            .annotate(application=KeyTransform("authorized_application", "context"))
             .annotate(user_pk=KeyTextTransform("pk", "user"))
             .values("application")
             .annotate(counted_events=Count("application"))
@@ -146,6 +146,7 @@ def top_per_user(self, request: Request):
             .values("unique_users", "application", "counted_events")
             .order_by("-counted_events")[:top_n]
         )
+        return Response(EventTopPerUserSerializer(instance=events, many=True).data)
 
     @extend_schema(
         methods=["GET"],


Test patch:
Repository: goauthentik/authentik

Issue:
ldap_sync_single ignores "ldap.task_timeout_hours" settings
**Describe the bug**
The "ldap_sync_single" task is ignoring the "ldap.task_timeout_hours" setting as set with the `AUTHENTIK_LDAP__TASK_TIMEOUT_HOURS` environment variable.

**To Reproduce**
Steps to reproduce the behavior:

1. configure AUTHENTIK_LDAP__TASK_TIMEOUT_HOURS to be too short to synchronize a target ldap source
2. configure an LDAP source
3. on the LDAP source details page, click on "Run sync now"
4. wait 10 minutes

**Expected behavior**
The task is given the specified amount of time and not cancelled after 10 minutes.

**Screenshots**
![Flower](https://github.com/goauthentik/authentik/assets/986924/02ae8800-3258-4f87-b0c9-cf6993d6b1a0)

**Logs**
Output of docker-compose logs or kubectl logs respectively

**Version and Deployment (please complete the following information):**

-   authentik version: [e.g. [2023.8.2](https://goauthentik.io/docs/releases/2023.8)]
-   Deployment: docker-compose





Discussion:

Resolving patch:
diff --git a/authentik/sources/ldap/tasks.py b/authentik/sources/ldap/tasks.py
--- a/authentik/sources/ldap/tasks.py
+++ b/authentik/sources/ldap/tasks.py
@@ -33,7 +33,13 @@ def ldap_sync_all():
         ldap_sync_single(source.pk)
 
 
-@CELERY_APP.task()
+@CELERY_APP.task(
+    # We take the configured hours timeout time by 2.5 as we run user and
+    # group in parallel and then membership, so 2x is to cover the serial tasks,
+    # and 0.5x on top of that to give some more leeway
+    soft_time_limit=(60 * 60 * CONFIG.get_int("ldap.task_timeout_hours")) * 2.5,
+    task_time_limit=(60 * 60 * CONFIG.get_int("ldap.task_timeout_hours")) * 2.5,
+)
 def ldap_sync_single(source_pk: str):
     """Sync a single source"""
     source: LDAPSource = LDAPSource.objects.filter(pk=source_pk).first()


Test patch:
Repository: goauthentik/authentik

Issue:
Patreon login doesn't work/setup is not intuitive
**Describe the bug**
While trying to set up the Patreon social integration, I realised that the required fields of Consumer Key and Consumer Secret don't seem to apply to the data that Patreon provides with its API - or at least the terminology is confusing. But outside of that, the default scopes that it seems to be presenting Patreon with upon setup are not part of Patreon's API, and will always error out with an "Invalid Scope" unless manually replaced with the correct ones. If this social integration is working and I'm mistaken, it is missing documentation that would definitely make it easier on new users.

To Reproduce
Steps to reproduce the behavior:

1. Go to the social integration settings.
2. Click on the Patreon integration.
3. Enter the Client ID and Secret into the Key and Secret fields (assuming that's what you're supposed to use)
4. Get an invalid_scope error when trying to sign in

Expected behavior
Should allow users to log in via Patreon.

Screenshots
N/A

Logs
N/A

Version and Deployment (please complete the following information):

authentik version: 2023.6.1
Deployment: TrueNAS









Discussion:
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Resolving patch:
diff --git a/authentik/sources/oauth/types/patreon.py b/authentik/sources/oauth/types/patreon.py
--- a/authentik/sources/oauth/types/patreon.py
+++ b/authentik/sources/oauth/types/patreon.py
@@ -12,8 +12,9 @@ class PatreonOAuthRedirect(OAuthRedirect):
     """Patreon OAuth2 Redirect"""
 
     def get_additional_parameters(self, source: OAuthSource):  # pragma: no cover
+        # https://docs.patreon.com/#scopes
         return {
-            "scope": ["openid", "email", "profile"],
+            "scope": ["identity", "identity[email]"],
         }
 
 


Test patch:
Repository: goauthentik/authentik

Issue:
2023.10.6 - "Please select a username" after Azure AD login
**Describe your question/**

Is it now a expected behavior in 2023.10.6 version to ask every user for username input after logging in with azure ad?
![image](https://github.com/goauthentik/authentik/assets/7706996/7c35f530-62a2-4afd-92aa-c290ad221c5f)

In previous versions it was simply authenticating without any prompt, using email address from Azure AD as username.

Now it expects user to input username (and it leads to duplicated accounts, because users with mail as username already exist), and if you enter already existing mail as username it shows error:
![image](https://github.com/goauthentik/authentik/assets/7706996/a8aaaf90-b309-425c-92a1-174739d01fc6)

I think it can be related to this fix:
https://github.com/goauthentik/authentik/pull/7970

Is it possible somehow to set this username automatically, or revert back to using email address so old user accounts will work again?

**Version and Deployment (please complete the following information):**

-   authentik version: 2023.10.6
-   Deployment: helm




Discussion:
This is unfortunately due to the bug that still exists in .6, see https://github.com/goauthentik/authentik/issues/7972#issuecomment-1886863709
After successful AD login it redirects to the enrolment flow for some reason.

Resolving patch:
diff --git a/authentik/sources/oauth/types/azure_ad.py b/authentik/sources/oauth/types/azure_ad.py
--- a/authentik/sources/oauth/types/azure_ad.py
+++ b/authentik/sources/oauth/types/azure_ad.py
@@ -50,7 +50,7 @@ class AzureADType(SourceType):
 
     authorization_url = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
     access_token_url = "https://login.microsoftonline.com/common/oauth2/v2.0/token"  # nosec
-    profile_url = "https://login.microsoftonline.com/common/openid/userinfo"
+    profile_url = "https://graph.microsoft.com/v1.0/me"
     oidc_well_known_url = (
         "https://login.microsoftonline.com/common/.well-known/openid-configuration"
     )


Test patch:
Repository: goauthentik/authentik

Issue:
2023.10.6 - "Please select a username" after Azure AD login
**Describe your question/**

Is it now a expected behavior in 2023.10.6 version to ask every user for username input after logging in with azure ad?
![image](https://github.com/goauthentik/authentik/assets/7706996/7c35f530-62a2-4afd-92aa-c290ad221c5f)

In previous versions it was simply authenticating without any prompt, using email address from Azure AD as username.

Now it expects user to input username (and it leads to duplicated accounts, because users with mail as username already exist), and if you enter already existing mail as username it shows error:
![image](https://github.com/goauthentik/authentik/assets/7706996/a8aaaf90-b309-425c-92a1-174739d01fc6)

I think it can be related to this fix:
https://github.com/goauthentik/authentik/pull/7970

Is it possible somehow to set this username automatically, or revert back to using email address so old user accounts will work again?

**Version and Deployment (please complete the following information):**

-   authentik version: 2023.10.6
-   Deployment: helm




Discussion:
This is unfortunately due to the bug that still exists in .6, see https://github.com/goauthentik/authentik/issues/7972#issuecomment-1886863709
After successful AD login it redirects to the enrolment flow for some reason.
This does not fix anything, I am afraid. It is now back to the:
<img width="614" alt="Screenshot 2024-01-12 at 18 00 38" src="https://github.com/goauthentik/authentik/assets/83865615/65afc0f7-09df-411a-9b11-529eda67ef21">

When can we have a real fix for it please ?

Resolving patch:
diff --git a/authentik/sources/oauth/types/azure_ad.py b/authentik/sources/oauth/types/azure_ad.py
--- a/authentik/sources/oauth/types/azure_ad.py
+++ b/authentik/sources/oauth/types/azure_ad.py
@@ -25,6 +25,11 @@ class AzureADOAuthCallback(OpenIDConnectOAuth2Callback):
 
     client_class = UserprofileHeaderAuthClient
 
+    def get_user_id(self, info: dict[str, str]) -> str:
+        # Default try to get `id` for the Graph API endpoint
+        # fallback to OpenID logic in case the profile URL was changed
+        return info.get("id", super().get_user_id(info))
+
     def get_user_enroll_context(
         self,
         info: dict[str, Any],


Test patch:
diff --git a/authentik/sources/oauth/tests/test_type_azure_ad.py b/authentik/sources/oauth/tests/test_type_azure_ad.py
--- a/authentik/sources/oauth/tests/test_type_azure_ad.py
+++ b/authentik/sources/oauth/tests/test_type_azure_ad.py
@@ -44,3 +44,7 @@ def test_enroll_context(self):
         self.assertEqual(ak_context["username"], AAD_USER["userPrincipalName"])
         self.assertEqual(ak_context["email"], AAD_USER["mail"])
         self.assertEqual(ak_context["name"], AAD_USER["displayName"])
+
+    def test_user_id(self):
+        """Test azure AD user ID"""
+        self.assertEqual(AzureADOAuthCallback().get_user_id(AAD_USER), AAD_USER["id"])