core: prevent selecting a group as a parent of itself (#6016)

* core: prevent selecting a group as a parent of itself

Signed-off-by: Jens Langhammer <jens@goauthentik.io>

* fix api error when no parent is given

Signed-off-by: Jens Langhammer <jens@goauthentik.io>

---------

Signed-off-by: Jens Langhammer <jens@goauthentik.io>
This commit is contained in:
Jens L 2023-06-20 20:21:58 +02:00 committed by GitHub
parent 5e30f46772
commit 93575a9966
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 25 additions and 0 deletions

View File

@ -1,5 +1,6 @@
"""Groups API Viewset""" """Groups API Viewset"""
from json import loads from json import loads
from typing import Optional
from django.db.models.query import QuerySet from django.db.models.query import QuerySet
from django.http import Http404 from django.http import Http404
@ -52,6 +53,14 @@ class GroupSerializer(ModelSerializer):
num_pk = IntegerField(read_only=True) num_pk = IntegerField(read_only=True)
def validate_parent(self, parent: Optional[Group]):
"""Validate group parent (if set), ensuring the parent isn't itself"""
if not self.instance or not parent:
return parent
if str(parent.group_uuid) == str(self.instance.group_uuid):
raise ValidationError("Cannot set group as parent of itself.")
return parent
class Meta: class Meta:
model = Group model = Group
fields = [ fields = [

View File

@ -67,3 +67,16 @@ class TestGroupsAPI(APITestCase):
}, },
) )
self.assertEqual(res.status_code, 404) self.assertEqual(res.status_code, 404)
def test_parent_self(self):
"""Test parent"""
group = Group.objects.create(name=generate_id())
self.client.force_login(self.admin)
res = self.client.patch(
reverse("authentik_api:group-detail", kwargs={"pk": group.pk}),
data={
"pk": self.user.pk + 3,
"parent": group.pk,
},
)
self.assertEqual(res.status_code, 400)

View File

@ -95,6 +95,9 @@ export class GroupForm extends ModelForm<Group, string> {
args.search = query; args.search = query;
} }
const groups = await new CoreApi(DEFAULT_CONFIG).coreGroupsList(args); const groups = await new CoreApi(DEFAULT_CONFIG).coreGroupsList(args);
if (this.instance) {
return groups.results.filter((g) => g.pk !== this.instance?.pk);
}
return groups.results; return groups.results;
}} }}
.renderElement=${(group: Group): string => { .renderElement=${(group: Group): string => {