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

Issue:
Add support for docker secrets
**Is your feature request related to a problem? Please describe.**

The environment variables in the docker images don´t support docker secrets.
I would like to add `_File` after it, and fill in a path. Something like `/run/secrets/*`
From a security standpoint, please add secrets for this env´s:

`AUTHENTIK_POSTGRESQL__PASSWORD:`
`AUTHENTIK_SECRET_KEY`
`AUTHENTIK_EMAIL__PASSWORD:`

I´ve tried doing it myself, but Authentik, wont find any password.

**Describe the solution you'd like**
Add support for docker secret 

Thanks in advance!



Discussion:
You can set all of these values to `file:///run/secrets/foo`, see https://goauthentik.io/docs/installation/configuration

Resolving patch:
diff --git a/authentik/lib/config.py b/authentik/lib/config.py
--- a/authentik/lib/config.py
+++ b/authentik/lib/config.py
@@ -88,10 +88,10 @@ def parse_uri(self, value):
             value = os.getenv(url.netloc, url.query)
         if url.scheme == "file":
             try:
-                with open(url.netloc, "r") as _file:
+                with open(url.path, "r") as _file:
                     value = _file.read()
             except OSError:
-                self._log("error", f"Failed to read config value from {url.netloc}")
+                self._log("error", f"Failed to read config value from {url.path}")
                 value = url.query
         return value
 


Test patch:
Repository: goauthentik/authentik

Issue:
Plans for converting to “Master” to “Main”?
**Describe your question**
In line with many other communities, and the Git project itself, does Authentik plan to change the primary branch to `main`? This process is relatively seamless now, and GitHub will additionally redirect any links which point to `<project>/master` to `<project>/main`.

**Relevant infos**
https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-branches-in-your-repository/renaming-a-branch
https://sfconservancy.org/news/2020/jun/23/gitbranchname/

**Screenshots**
N/A

**Logs**
N/A
**Version and Deployment (please complete the following information):**
N/A

**Additional context**
N/A


Discussion:

Resolving patch:
diff --git a/authentik/root/settings.py b/authentik/root/settings.py
--- a/authentik/root/settings.py
+++ b/authentik/root/settings.py
@@ -152,7 +152,7 @@ def j_print(event: str, log_level: str = "info", **kwargs):
     "AUTHENTICATION_WHITELIST": ["authentik.api.authentication.TokenAuthentication"],
     "LICENSE": {
         "name": "GNU GPLv3",
-        "url": "https://github.com/goauthentik/authentik/blob/master/LICENSE",
+        "url": "https://github.com/goauthentik/authentik/blob/main/LICENSE",
     },
     "ENUM_NAME_OVERRIDES": {
         "EventActions": "authentik.events.models.EventAction",


Test patch:
diff --git a/tests/e2e/utils.py b/tests/e2e/utils.py
--- a/tests/e2e/utils.py
+++ b/tests/e2e/utils.py
@@ -37,7 +37,7 @@ def get_docker_tag() -> str:
     """Get docker-tag based off of CI variables"""
     env_pr_branch = "GITHUB_HEAD_REF"
     default_branch = "GITHUB_REF"
-    branch_name = os.environ.get(default_branch, "master")
+    branch_name = os.environ.get(default_branch, "main")
     if os.environ.get(env_pr_branch, "") != "":
         branch_name = os.environ[env_pr_branch]
     branch_name = branch_name.replace("refs/heads/", "").replace("/", "-")
@@ -66,9 +66,9 @@ def setUp(self):
             self.container = self._start_container(specs)
 
     def get_container_image(self, base: str) -> str:
-        """Try to pull docker image based on git branch, fallback to master if not found."""
+        """Try to pull docker image based on git branch, fallback to main if not found."""
         client: DockerClient = from_env()
-        image = f"{base}:gh-master"
+        image = f"{base}:gh-main"
         try:
             branch_image = f"{base}:{get_docker_tag()}"
             client.images.pull(branch_image)
Repository: goauthentik/authentik

Issue:
Get username from mailcow source
**Is your feature request related to a problem? Please describe.**
I like to get a username from mailcow. With username the enrollment for new users is more simple.

**Describe the solution you'd like**
Set username to full_name provided by mailcow oauths source.

**Additional context**
For other sources the username is also set redundant to another attribute if there is no special source attribute:
azure_ad.py:
```
            "username": info.get("displayName"),
            "name": info.get("displayName"),
```

discord.py:
```
            "username": info.get("username"),
            "name": info.get("username"),
```

facebook.py:
```
            "username": info.get("name"),
            "name": info.get("name"),
```

reddit.py
```
            "username": info.get("name"),
            "name": info.get("name"),
```



Discussion:

Resolving patch:
diff --git a/authentik/sources/oauth/types/mailcow.py b/authentik/sources/oauth/types/mailcow.py
--- a/authentik/sources/oauth/types/mailcow.py
+++ b/authentik/sources/oauth/types/mailcow.py
@@ -52,6 +52,7 @@ def get_user_enroll_context(
         info: dict[str, Any],
     ) -> dict[str, Any]:
         return {
+            "username": info.get("full_name"),
             "email": info.get("email"),
             "name": info.get("full_name"),
         }


Test patch:
Repository: goauthentik/authentik

Issue:
Support HA postgresql
When using a HA installation of postgresql connection problems with the api server arise during initial load of the user dashboard.

Pgbouncer in transaction pooling mode requires custom settings in order to function correctly.
It would be nice if the user could specify that a HA installation is used and the settings are then adjusted automatically.

```
# https://docs.djangoproject.com/en/4.0/ref/databases/#transaction-pooling-server-side-cursors
DATABASES['default']['DISABLE_SERVER_SIDE_CURSORS'] = True
# https://docs.djangoproject.com/en/4.0/ref/databases/#persistent-connections
DATABASES['default']['CONN_MAX_AGE'] = None  # persistent
```

Currently the settings do not include these options:
https://github.com/goauthentik/authentik/blob/89c84f10d0e6e70e51444a9fbf18980ba25008de/authentik/root/settings.py#L279-L288



Discussion:
I can confirm that changing the settings according to above instructions enables authentik to work flawlessly with pgbouncer.

Resolving patch:
diff --git a/authentik/root/settings.py b/authentik/root/settings.py
--- a/authentik/root/settings.py
+++ b/authentik/root/settings.py
@@ -270,6 +270,12 @@
     }
 }
 
+if CONFIG.y_bool("postgresql.use_pgbouncer", False):
+    # https://docs.djangoproject.com/en/4.0/ref/databases/#transaction-pooling-server-side-cursors
+    DATABASES["default"]["DISABLE_SERVER_SIDE_CURSORS"] = True
+    # https://docs.djangoproject.com/en/4.0/ref/databases/#persistent-connections
+    DATABASES["default"]["CONN_MAX_AGE"] = None  # persistent
+
 # Email
 EMAIL_HOST = CONFIG.y("email.host")
 EMAIL_PORT = int(CONFIG.y("email.port"))


Test patch:
Repository: goauthentik/authentik

Issue:
Speed-Up User Interaction by removing groups_obj from UserSerializer
**Is your feature request related to a problem? Please describe.**
We have a medium sized database of users which consists of approximately 500 users. The use groups to assign individual features to them.

When updating users or interacting with the UI, we expierence a large lag (30-60s) just retrieving the data, as the API has to resolve all groups assigned to a user and all the users within this group.

A quick search in the webfrontend yield no results where this feature would be required.

**Describe the solution you'd like**
Remove this field or make the field optional from the beginning.

As a workaround i currently replaced in authentik/core/api/users.py the following line:
https://github.com/goauthentik/authentik/blob/main/authentik/core/api/users.py#L86

with a SerializerMethodField that returns an empty array

**Describe alternatives you've considered**
The inclusion of the drf-dynamic-fields would allow requests to include a list of necessary fields, but does not play nicely with javascript / typescript.

**Additional context**
-



Discussion:
As a follow-up:

I found that the LDAP provider seems to utilize the `group_obj`, but only extracts the groupname from it

Further alternatives:

Create a "SimpleGroupSerializer", which omits both the `user` and `users_obj` from the group, when serializing a User object to break recursive calls.

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
@@ -46,7 +46,6 @@
 
 from authentik.admin.api.metrics import CoordinateSerializer
 from authentik.api.decorators import permission_required
-from authentik.core.api.groups import GroupSerializer
 from authentik.core.api.used_by import UsedByMixin
 from authentik.core.api.utils import LinkSerializer, PassiveSerializer, is_dict
 from authentik.core.middleware import (
@@ -74,6 +73,26 @@
 LOGGER = get_logger()
 
 
+class UserGroupSerializer(ModelSerializer):
+    """Simplified Group Serializer for user's groups"""
+
+    attributes = JSONField(required=False)
+    parent_name = CharField(source="parent.name", read_only=True)
+
+    class Meta:
+
+        model = Group
+        fields = [
+            "pk",
+            "num_pk",
+            "name",
+            "is_superuser",
+            "parent",
+            "parent_name",
+            "attributes",
+        ]
+
+
 class UserSerializer(ModelSerializer):
     """User Serializer"""
 
@@ -83,7 +102,7 @@ class UserSerializer(ModelSerializer):
     groups = PrimaryKeyRelatedField(
         allow_empty=True, many=True, source="ak_groups", queryset=Group.objects.all()
     )
-    groups_obj = ListSerializer(child=GroupSerializer(), read_only=True, source="ak_groups")
+    groups_obj = ListSerializer(child=UserGroupSerializer(), read_only=True, source="ak_groups")
     uid = CharField(read_only=True)
     username = CharField(max_length=150)
 


Test patch:
Repository: goauthentik/authentik

Issue:
System Tasks: Show start timestamp and calculate Duration
**Is your feature request related to a problem? Please describe.**
For debugging purposes, I need the info when a task started, and when it finished. 

**Describe the solution you'd like**
I have seen that the TaskInfo object actually holds that information, but it is not returned by the API, and not shown in the "SystemTasks" table of the web UI. 
It would also make sense to calculate the duration for easier debugging.

**Describe alternatives you've considered**
I could look this up in the database, but this would be questionable UX, since there is already a view in the web app which should show this information.

**Additional context**
(none)



Discussion:

Resolving patch:
diff --git a/authentik/admin/api/tasks.py b/authentik/admin/api/tasks.py
--- a/authentik/admin/api/tasks.py
+++ b/authentik/admin/api/tasks.py
@@ -7,7 +7,13 @@
 from drf_spectacular.types import OpenApiTypes
 from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
 from rest_framework.decorators import action
-from rest_framework.fields import CharField, ChoiceField, DateTimeField, ListField
+from rest_framework.fields import (
+    CharField,
+    ChoiceField,
+    DateTimeField,
+    ListField,
+    SerializerMethodField,
+)
 from rest_framework.permissions import IsAdminUser
 from rest_framework.request import Request
 from rest_framework.response import Response
@@ -26,6 +32,7 @@ class TaskSerializer(PassiveSerializer):
     task_name = CharField()
     task_description = CharField()
     task_finish_timestamp = DateTimeField(source="finish_time")
+    task_duration = SerializerMethodField()
 
     status = ChoiceField(
         source="result.status.name",
@@ -33,7 +40,11 @@ class TaskSerializer(PassiveSerializer):
     )
     messages = ListField(source="result.messages")
 
-    def to_representation(self, instance):
+    def get_task_duration(self, instance: TaskInfo) -> int:
+        """Get the duration a task took to run"""
+        return max(instance.finish_timestamp - instance.start_timestamp, 0)
+
+    def to_representation(self, instance: TaskInfo):
         """When a new version of authentik adds fields to TaskInfo,
         the API will fail with an AttributeError, as the classes
         are pickled in cache. In that case, just delete the info"""


Test patch:
Repository: goauthentik/authentik

Issue:
OAuth sources seem to be linked to every account
**Describe the bug**
Opening user settings then going to "Connected services" seem to show everyone's connections instead of just the current authenticated user

**To Reproduce**
Steps to reproduce the behavior:
1. Login using existing user (User A)
2. Go to account settings -> connected services to see no connected services
3. In another browser go to login page and login using OAuth (User B)
4. User A now goes to connected services to see that they have the same OAuth connected
5. Logging out of User A and logging in with OAuth will login as User B
6. Disconnecting OAuth from User A will not disconnect it from User B, but will appear to have

**Expected behavior**
OAuth management page (connected services) should only show oauth relations that the current user has.

**Screenshots**
![image](https://user-images.githubusercontent.com/46821216/221099352-afae0130-f9f0-4d77-bcfb-857236850dbe.png)
![image](https://user-images.githubusercontent.com/46821216/221099369-f3b71bd6-f6e4-4adb-a6dd-26dd4f5ad6c2.png)

![image](https://user-images.githubusercontent.com/46821216/221099395-b6620aa2-d59a-4fdf-acfb-3f370aa62d57.png)
![image](https://user-images.githubusercontent.com/46821216/221099406-ab2b0747-42a1-4527-b270-11f0b408c36a.png)

**Logs**
Admin Interface -> Event Logs:
- Model Created from grant2 (User B)
- Source Linked from grant2 (User B)
- Model Deleted from grant (User A)

**Version and Deployment (please complete the following information):**
 - authentik version: 2023.2.2
 - Deployment: docker-compose

**Additional context**
Add any other context about the problem here.



Discussion:

Resolving patch:
diff --git a/authentik/core/api/sources.py b/authentik/core/api/sources.py
--- a/authentik/core/api/sources.py
+++ b/authentik/core/api/sources.py
@@ -206,5 +206,6 @@ class UserSourceConnectionViewSet(
     queryset = UserSourceConnection.objects.all()
     serializer_class = UserSourceConnectionSerializer
     permission_classes = [OwnerSuperuserPermissions]
+    filterset_fields = ["user"]
     filter_backends = [OwnerFilter, DjangoFilterBackend, OrderingFilter, SearchFilter]
     ordering = ["pk"]


Test patch:
Repository: goauthentik/authentik

Issue:
Ability to specify default akadmin email at bootstrap variable
**Is your feature request related to a problem? Please describe.**

 I'm always frustrated when I have to specify manually the email address of akadmin after success gitops deploy of authentik.

**Describe the solution you'd like**

Create new variable AUTHENTIK_BOOTSTRAP_EMAIL (like AUTHENTIK_BOOTSTRAP_PASSWORD) to permit to specify akadmin email at bootstrap process.

**Describe alternatives you've considered**

Maybe a terraform resource in terraform-provider-authentik  that can modify a user email...but I don't know if it's possible.





Discussion:

Resolving patch:
diff --git a/authentik/core/migrations/0002_auto_20200523_1133_squashed_0011_provider_name_temp.py b/authentik/core/migrations/0002_auto_20200523_1133_squashed_0011_provider_name_temp.py
--- a/authentik/core/migrations/0002_auto_20200523_1133_squashed_0011_provider_name_temp.py
+++ b/authentik/core/migrations/0002_auto_20200523_1133_squashed_0011_provider_name_temp.py
@@ -18,13 +18,13 @@ def create_default_user(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
     db_alias = schema_editor.connection.alias
 
     akadmin, _ = User.objects.using(db_alias).get_or_create(
-        username="akadmin", email="root@localhost", name="authentik Default Admin"
+        username="akadmin",
+        email=environ.get("AUTHENTIK_BOOTSTRAP_EMAIL", "root@localhost"),
+        name="authentik Default Admin",
     )
     password = None
     if "TF_BUILD" in environ or settings.TEST:
         password = "akadmin"  # noqa # nosec
-    if "AK_ADMIN_PASS" in environ:
-        password = environ["AK_ADMIN_PASS"]
     if "AUTHENTIK_BOOTSTRAP_PASSWORD" in environ:
         password = environ["AUTHENTIK_BOOTSTRAP_PASSWORD"]
     if password:
diff --git a/authentik/core/migrations/0018_auto_20210330_1345_squashed_0028_alter_token_intent.py b/authentik/core/migrations/0018_auto_20210330_1345_squashed_0028_alter_token_intent.py
--- a/authentik/core/migrations/0018_auto_20210330_1345_squashed_0028_alter_token_intent.py
+++ b/authentik/core/migrations/0018_auto_20210330_1345_squashed_0028_alter_token_intent.py
@@ -46,13 +46,9 @@ def create_default_user_token(apps: Apps, schema_editor: BaseDatabaseSchemaEdito
     akadmin = User.objects.using(db_alias).filter(username="akadmin")
     if not akadmin.exists():
         return
-    key = None
-    if "AK_ADMIN_TOKEN" in environ:
-        key = environ["AK_ADMIN_TOKEN"]
-    if "AUTHENTIK_BOOTSTRAP_TOKEN" in environ:
-        key = environ["AUTHENTIK_BOOTSTRAP_TOKEN"]
-    if not key:
+    if "AUTHENTIK_BOOTSTRAP_TOKEN" not in environ:
         return
+    key = environ["AUTHENTIK_BOOTSTRAP_TOKEN"]
     Token.objects.using(db_alias).create(
         identifier="authentik-bootstrap-token",
         user=akadmin.first(),


Test patch:
Repository: goauthentik/authentik

Issue:
Launch URL in Application UI Settings can't be entered for some domains
**Describe the bug**
When I try to add a fixed link to an application, it will return an error with null text.
I think this is happening only for any subdomain that has a dash character on the subdomain portion of the name:
ej: https://tbb-assets.domain.com

**Screenshots**
This one gets saved without any problems:
https://application.com
![image](https://user-images.githubusercontent.com/75147745/225165939-0cc8c789-65e8-4fad-bec5-c0434ceecb6d.png)

But if i edit this domain to something else like:
https://tbb-assets.easyfoodsin.com
![image](https://user-images.githubusercontent.com/75147745/225165898-f2946215-3846-4f23-be88-8b4d84c067e2.png)

**Logs**
Output of docker-compose logs or kubectl logs respectively.
I can't find anything on the logs it seems that nothing is submitted is a validation error within the application edit screen.

**Version and Deployment (please complete the following information):**
 - authentik version: 2023.3.0
 - Deployment: docker-compose

**Additional context**
This error is not happening on version (2023.2.2) because I created a few applications recently that have many urls that have a dash on the subdomain.


Discussion:

Resolving patch:
diff --git a/authentik/lib/models.py b/authentik/lib/models.py
--- a/authentik/lib/models.py
+++ b/authentik/lib/models.py
@@ -81,7 +81,8 @@ class DomainlessFormattedURLValidator(DomainlessURLValidator):
 
     def __init__(self, *args, **kwargs) -> None:
         super().__init__(*args, **kwargs)
-        self.host_re = r"([%\(\)a-zA-Z])+" + self.domain_re + self.domain_re
+        self.formatter_re = r"([%\(\)a-zA-Z])*"
+        self.host_re = "(" + self.formatter_re + self.hostname_re + self.domain_re + "|localhost)"
         self.regex = _lazy_re_compile(
             r"^(?:[a-z0-9.+-]*)://"  # scheme is validated separately
             r"(?:[^\s:@/]+(?::[^\s:@/]*)?@)?"  # user:pass authentication


Test patch:
diff --git a/authentik/core/tests/test_applications_api.py b/authentik/core/tests/test_applications_api.py
--- a/authentik/core/tests/test_applications_api.py
+++ b/authentik/core/tests/test_applications_api.py
@@ -43,14 +43,14 @@ def test_formatted_launch_url(self):
         self.assertEqual(
             self.client.patch(
                 reverse("authentik_api:application-detail", kwargs={"slug": self.allowed.slug}),
-                {"meta_launch_url": "https://%(username)s.test.goauthentik.io/%(username)s"},
+                {"meta_launch_url": "https://%(username)s-test.test.goauthentik.io/%(username)s"},
             ).status_code,
             200,
         )
         self.allowed.refresh_from_db()
         self.assertEqual(
             self.allowed.get_launch_url(self.user),
-            f"https://{self.user.username}.test.goauthentik.io/{self.user.username}",
+            f"https://{self.user.username}-test.test.goauthentik.io/{self.user.username}",
         )
 
     def test_set_icon(self):
Repository: goauthentik/authentik

Issue:
Inactive user can't pass identification stage
**Describe the bug**
I hope I'm not completely wrong, but inactive users should also be able to pass an identification stage.
In my case it should be possible to request a password reset even with an inactive user account. 

Like in the default-recovery-flow which is delivered as a blueprint example with Authentik and looks like this:

![image](https://user-images.githubusercontent.com/18358381/216637203-26f9b110-31cd-4afc-9597-c73fd7c74087.png)

The "default-recovery-email" also has an option to activate inactive users with a normal password reset:

![image](https://user-images.githubusercontent.com/18358381/216637227-6787f663-531b-4e73-b061-1e01d402f1b6.png)

However, in my opinion, this interferes with the following query, which I have adapted for my purposes:

/authentics/authentics/stages/identification/stage.py

changed line 175:
        user = User.objects.filter(query, is_active=True).first()
to 
        user = User.objects.filter(query).first()

Now even inactive users are able to pass the Identification Stage and get to the EMail Stage.
Please let me know if this customization is a safety issue or if it can be done this way.

**To Reproduce**
Steps to reproduce the behavior:
1. fresh Authentik installation
2. created a normal user and set it to inactive
3. created a new Blueprint instance from examples/flows-recovery-email-verification.yaml
4. executed the blueprint instance
5. now I have my recovery flow "default-recovery-flow"
6. to make the flow work I made a small correction to on of the expressions "default-recoery-skip-if-restored" as stated in this Github post: https://github.com/goauthentik/authentik/issues/3297
7. after that I deleted the flow cache and opened the flow in an incognito tab: "/if/flow/default-recovery-flow"
8. try to trigger the passwort reset function

**Expected behavior**
Also an inactive user should be able pass the identification stage to reach the email stage.

**Version and Deployment (please complete the following information):**
 - authentik version: 2023.1.2
 - 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/stages/identification/stage.py b/authentik/stages/identification/stage.py
--- a/authentik/stages/identification/stage.py
+++ b/authentik/stages/identification/stage.py
@@ -172,7 +172,7 @@ def get_user(self, uid_value: str) -> Optional[User]:
         if not query:
             self.logger.debug("Empty user query", query=query)
             return None
-        user = User.objects.filter(query, is_active=True).first()
+        user = User.objects.filter(query).first()
         if user:
             self.logger.debug("Found user", user=user.username, query=query)
             return user


Test patch: