Skip to content

Commit

Permalink
sources/oauth: add initial group sync
Browse files Browse the repository at this point in the history
Signed-off-by: Jens Langhammer <[email protected]>
  • Loading branch information
BeryJu committed Jul 30, 2023
1 parent 2ac7eb6 commit d9428dc
Show file tree
Hide file tree
Showing 12 changed files with 160 additions and 12 deletions.
17 changes: 17 additions & 0 deletions authentik/core/migrations/0032_alter_group_name.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Generated by Django 4.1.10 on 2023-07-30 14:48

from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("authentik_core", "0031_alter_user_type"),
]

operations = [
migrations.AlterField(
model_name="group",
name="name",
field=models.TextField(verbose_name="name"),
),
]
2 changes: 1 addition & 1 deletion authentik/core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ class Group(SerializerModel):

group_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)

name = models.CharField(_("name"), max_length=80)
name = models.TextField(_("name"))
is_superuser = models.BooleanField(
default=False, help_text=_("Users added to this group will be superusers.")
)
Expand Down
8 changes: 4 additions & 4 deletions authentik/core/sources/flow_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,15 +220,15 @@ def _prepare_flow(
flow: Flow,
connection: UserSourceConnection,
stages: Optional[list[StageView]] = None,
**kwargs,
**flow_context,
) -> HttpResponse:
"""Prepare Authentication Plan, redirect user FlowExecutor"""
# Ensure redirect is carried through when user was trying to
# authorize application
final_redirect = self.request.session.get(SESSION_KEY_GET, {}).get(
NEXT_ARG_NAME, "authentik_core:if-user"
)
kwargs.update(
flow_context.update(
{
# Since we authenticate the user by their token, they have no backend set
PLAN_CONTEXT_AUTHENTICATION_BACKEND: BACKEND_INBUILT,
Expand All @@ -238,15 +238,15 @@ def _prepare_flow(
PLAN_CONTEXT_SOURCES_CONNECTION: connection,
}
)
kwargs.update(self.policy_context)
flow_context.update(self.policy_context)
if not flow:
return bad_request_message(
self.request,
_("Configured flow does not exist."),
)
# We run the Flow planner here so we can pass the Pending user in the context
planner = FlowPlanner(flow)
plan = planner.plan(self.request, kwargs)
plan = planner.plan(self.request, flow_context)
for stage in self.get_stages_to_append(flow):
plan.append_stage(stage)
if stages:
Expand Down
2 changes: 2 additions & 0 deletions authentik/sources/oauth/api/source.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ class Meta:
"consumer_secret",
"callback_url",
"additional_scopes",
"groups_claim",
"type",
"oidc_well_known_url",
"oidc_jwks_url",
Expand Down Expand Up @@ -137,6 +138,7 @@ class Meta:
"authorization_url",
"access_token_url",
"profile_url",
"groups_claim",
"consumer_key",
"additional_scopes",
]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Generated by Django 4.1.10 on 2023-07-30 14:48

from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
(
"authentik_sources_oauth",
"0007_oauthsource_oidc_jwks_oauthsource_oidc_jwks_url_and_more",
),
]

operations = [
migrations.AddField(
model_name="oauthsource",
name="groups_claim",
field=models.TextField(
default=None,
help_text="Sync groups and group membership from the source. Only use this option with sources that you control, as otherwise unwanted users might get added to groups with superuser permissions.",
null=True,
),
),
]
10 changes: 10 additions & 0 deletions authentik/sources/oauth/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,16 @@ class OAuthSource(Source):
oidc_jwks_url = models.TextField(default="", blank=True)
oidc_jwks = models.JSONField(default=dict, blank=True)

groups_claim = models.TextField(
default=None,
null=True,
help_text=_(
"Sync groups and group membership from the source. Only use this option with "
"sources that you control, as otherwise unwanted users might get added to "
"groups with superuser permissions."
),
)

@property
def type(self) -> type["SourceType"]:
"""Return the provider instance for this source"""
Expand Down
5 changes: 5 additions & 0 deletions authentik/sources/oauth/tests/test_type_openid.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@
"department": "Engineering",
"birthdate": "1975-12-31",
"nickname": "foo",
"groups": [
"foo",
"bar",
]
}


Expand All @@ -28,6 +32,7 @@ def setUp(self):
authorization_url="",
profile_url="http://localhost/userinfo",
consumer_key="",
groups_claim="groups",
)
self.factory = RequestFactory()

Expand Down
3 changes: 3 additions & 0 deletions authentik/sources/oauth/types/oidc.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ def get_user_enroll_context(
"name": info.get("name"),
}

def get_user_group_names(self, info: dict[str, Any]) -> list[str]:
return info.get(self.source.groups_claim, [])


@registry.register()
class OpenIDConnectType(SourceType):
Expand Down
43 changes: 42 additions & 1 deletion authentik/sources/oauth/views/callback.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,17 @@
from django.views.generic import View
from structlog.stdlib import get_logger

from authentik.core.models import Group, User
from authentik.core.sources.flow_manager import SourceFlowManager
from authentik.events.models import Event, EventAction
from authentik.flows.models import Flow, Stage, in_memory_stage
from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER
from authentik.flows.stage import StageView
from authentik.sources.oauth.models import OAuthSource, UserOAuthSourceConnection
from authentik.sources.oauth.views.base import OAuthClientMixin

LOGGER = get_logger()
PLAN_CONTEXT_GROUPS = "goauthentik.io/sources/oauth/groups"


class OAuthCallback(OAuthClientMixin, View):
Expand Down Expand Up @@ -59,13 +64,17 @@ def dispatch(self, request: HttpRequest, *_, **kwargs) -> HttpResponse:
return self.handle_login_failure("Could not determine id.")
# Get or create access record
enroll_info = self.get_user_enroll_context(raw_info)
group_info = self.get_user_group_names(raw_info)
sfm = OAuthSourceFlowManager(
source=self.source,
request=self.request,
identifier=identifier,
enroll_info=enroll_info,
)
sfm.policy_context = {"oauth_userinfo": raw_info}
sfm.policy_context = {
"oauth_userinfo": raw_info,
PLAN_CONTEXT_GROUPS: group_info,
}
return sfm.get_flow(
access_token=self.token.get("access_token"),
)
Expand All @@ -85,6 +94,10 @@ def get_user_enroll_context(
"""Create a dict of User data"""
raise NotImplementedError()

def get_user_group_names(self, info: dict[str, Any]) -> list[str]:
"""Return a list of all groups the user is member of"""
return []

def get_user_id(self, info: dict[str, Any]) -> Optional[str]:
"""Return unique identifier from the profile info."""
if "id" in info:
Expand All @@ -111,6 +124,13 @@ class OAuthSourceFlowManager(SourceFlowManager):

connection_type = UserOAuthSourceConnection

def get_stages_to_append(self, flow: Flow) -> list[Stage]:
return super().get_stages_to_append(flow) + [
# Always run this stage after the default `PostUserEnrollmentStage` stage
# as it relies on the user object existing
in_memory_stage(OAuthUserUpdateStage),
]

def update_connection(
self,
connection: UserOAuthSourceConnection,
Expand All @@ -119,3 +139,24 @@ def update_connection(
"""Set the access_token on the connection"""
connection.access_token = access_token
return connection


class OAuthUserUpdateStage(StageView):
"""Dynamically injected stage which updates the user after enrollment/authentication."""

def handle_groups(self):
"""Sync users' groups from oauth data"""
user: User = self.executor.plan.context[PLAN_CONTEXT_PENDING_USER]
group_names: list[str] = self.executor.plan.context[PLAN_CONTEXT_GROUPS]
for group_name in group_names:
Group.objects.update_or_create(name=group_name, defaults={})
user.ak_groups.set(Group.objects.filter(name__in=[group_names]))

def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
"""Stage used after the user has been enrolled"""
self.handle_groups()
return self.executor.stage_ok()

def post(self, request: HttpRequest) -> HttpResponse:
"""Wrapper for post requests"""
return self.get(request)
10 changes: 9 additions & 1 deletion blueprints/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -5117,6 +5117,15 @@
"type": "string",
"title": "Additional Scopes"
},
"groups_claim": {
"type": [
"string",
"null"
],
"minLength": 1,
"title": "Groups claim",
"description": "Sync groups and group membership from the source. Only use this option with sources that you control, as otherwise unwanted users might get added to groups with superuser permissions."
},
"oidc_well_known_url": {
"type": "string",
"title": "Oidc well known url"
Expand Down Expand Up @@ -8305,7 +8314,6 @@
"properties": {
"name": {
"type": "string",
"maxLength": 80,
"minLength": 1,
"title": "Name"
},
Expand Down
29 changes: 24 additions & 5 deletions schema.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17943,6 +17943,10 @@ paths:
schema:
type: string
format: uuid
- in: query
name: groups_claim
schema:
type: string
- in: query
name: has_jwks
schema:
Expand Down Expand Up @@ -30470,7 +30474,6 @@ components:
readOnly: true
name:
type: string
maxLength: 80
is_superuser:
type: boolean
description: Users added to this group will be superusers.
Expand Down Expand Up @@ -30583,7 +30586,6 @@ components:
name:
type: string
minLength: 1
maxLength: 80
is_superuser:
type: boolean
description: Users added to this group will be superusers.
Expand Down Expand Up @@ -32649,6 +32651,12 @@ components:
readOnly: true
additional_scopes:
type: string
groups_claim:
type: string
nullable: true
description: Sync groups and group membership from the source. Only use
this option with sources that you control, as otherwise unwanted users
might get added to groups with superuser permissions.
type:
allOf:
- $ref: '#/components/schemas/SourceType'
Expand Down Expand Up @@ -32752,6 +32760,13 @@ components:
minLength: 1
additional_scopes:
type: string
groups_claim:
type: string
nullable: true
minLength: 1
description: Sync groups and group membership from the source. Only use
this option with sources that you control, as otherwise unwanted users
might get added to groups with superuser permissions.
oidc_well_known_url:
type: string
oidc_jwks_url:
Expand Down Expand Up @@ -36979,7 +36994,6 @@ components:
name:
type: string
minLength: 1
maxLength: 80
is_superuser:
type: boolean
description: Users added to this group will be superusers.
Expand Down Expand Up @@ -37560,6 +37574,13 @@ components:
minLength: 1
additional_scopes:
type: string
groups_claim:
type: string
nullable: true
minLength: 1
description: Sync groups and group membership from the source. Only use
this option with sources that you control, as otherwise unwanted users
might get added to groups with superuser permissions.
oidc_well_known_url:
type: string
oidc_jwks_url:
Expand Down Expand Up @@ -42029,7 +42050,6 @@ components:
readOnly: true
name:
type: string
maxLength: 80
is_superuser:
type: boolean
description: Users added to this group will be superusers.
Expand All @@ -42055,7 +42075,6 @@ components:
name:
type: string
minLength: 1
maxLength: 80
is_superuser:
type: boolean
description: Users added to this group will be superusers.
Expand Down
19 changes: 19 additions & 0 deletions web/src/admin/sources/oauth/OAuthSourceForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@ export class OAuthSourceForm extends ModelForm<OAuthSource, string> {

async send(data: OAuthSource): Promise<OAuthSource> {
data.providerType = (this.providerType?.slug || "") as ProviderTypeEnum;
if (data.groupsClaim === "") {
data.groupsClaim = null;
}
let source: OAuthSource;
if (this.instance) {
source = await new SourcesApi(DEFAULT_CONFIG).sourcesOauthPartialUpdate({
Expand Down Expand Up @@ -185,6 +188,7 @@ export class OAuthSourceForm extends ModelForm<OAuthSource, string> {
: html``}
${this.providerType.slug === ProviderTypeEnum.Openidconnect
? html`
<ak-form-element-horizontal
label=${msg("OIDC Well-known URL")}
name="oidcWellKnownUrl"
Expand Down Expand Up @@ -216,6 +220,21 @@ export class OAuthSourceForm extends ModelForm<OAuthSource, string> {
</p>
</ak-form-element-horizontal>
<ak-form-element-horizontal
label=${msg("OIDC Groups claim")}
name="groupsClaim"
>
<input
type="text"
value="${first(this.instance?.groupsClaim, "")}"
class="pf-c-form-control"
/>
<p class="pf-c-form__helper-text">
${msg(
"Sync groups and group membership from the source. Only use this option with sources that you control, as otherwise unwanted users might get added to groups with superuser permissions.",
)}
</p>
</ak-form-element-horizontal>
<ak-form-element-horizontal label=${msg("OIDC JWKS")} name="oidcJwks">
<ak-codemirror
mode="javascript"
Expand Down

0 comments on commit d9428dc

Please sign in to comment.