authentik.stages.authenticator_duo.stage
Duo stage
1"""Duo stage""" 2 3from django.http import HttpResponse 4from django.utils.timezone import now 5from django.utils.translation import gettext as _ 6from rest_framework.fields import CharField 7 8from authentik.events.models import Event, EventAction 9from authentik.flows.challenge import ( 10 Challenge, 11 ChallengeResponse, 12 WithUserInfoChallenge, 13) 14from authentik.flows.stage import ChallengeStageView 15from authentik.flows.views.executor import InvalidStageError 16from authentik.stages.authenticator_duo.models import AuthenticatorDuoStage, DuoDevice 17 18PLAN_CONTEXT_DUO_ENROLL = "goauthentik.io/stages/authenticator_duo/enroll" 19DUO_USERNAME_EXISTS_ERROR = "username already exists" 20 21 22def duo_enrollment_error_message(exc: RuntimeError) -> str: 23 """Return a user-facing error message for Duo enrollment failures.""" 24 if DUO_USERNAME_EXISTS_ERROR in str(exc).lower(): 25 return _( 26 "A Duo user with this username already exists. Ask an administrator to import the " 27 "existing Duo authenticator or delete the Duo user before enrolling again." 28 ) 29 return _("Failed to enroll with Duo. Please contact an administrator.") 30 31 32class AuthenticatorDuoChallenge(WithUserInfoChallenge): 33 """Duo Challenge""" 34 35 activation_barcode = CharField() 36 activation_code = CharField() 37 stage_uuid = CharField() 38 component = CharField(default="ak-stage-authenticator-duo") 39 40 41class AuthenticatorDuoChallengeResponse(ChallengeResponse): 42 """Pseudo class for duo response""" 43 44 component = CharField(default="ak-stage-authenticator-duo") 45 46 47class AuthenticatorDuoStageView(ChallengeStageView): 48 """Duo stage""" 49 50 response_class = AuthenticatorDuoChallengeResponse 51 52 def duo_enroll(self): 53 """Enroll User with Duo API and save results""" 54 user = self.get_pending_user() 55 stage: AuthenticatorDuoStage = self.executor.current_stage 56 try: 57 enroll = stage.auth_client().enroll(user.username) 58 except RuntimeError as exc: 59 Event.new( 60 EventAction.CONFIGURATION_ERROR, 61 message=f"Failed to enroll user: {str(exc)}", 62 user=user, 63 ).from_http(self.request, user) 64 raise InvalidStageError(duo_enrollment_error_message(exc)) from exc 65 self.executor.plan.context[PLAN_CONTEXT_DUO_ENROLL] = enroll 66 return enroll 67 68 def get_challenge(self, *args, **kwargs) -> Challenge: 69 stage: AuthenticatorDuoStage = self.executor.current_stage 70 if PLAN_CONTEXT_DUO_ENROLL not in self.executor.plan.context: 71 self.duo_enroll() 72 enroll = self.executor.plan.context[PLAN_CONTEXT_DUO_ENROLL] 73 return AuthenticatorDuoChallenge( 74 data={ 75 "activation_barcode": enroll["activation_barcode"], 76 "activation_code": enroll["activation_code"], 77 "stage_uuid": str(stage.stage_uuid), 78 } 79 ) 80 81 def challenge_valid(self, response: ChallengeResponse) -> HttpResponse: 82 # Duo Challenge has already been validated 83 stage: AuthenticatorDuoStage = self.executor.current_stage 84 enroll = self.executor.plan.context.get(PLAN_CONTEXT_DUO_ENROLL) 85 enroll_status = stage.auth_client().enroll_status( 86 enroll["user_id"], enroll["activation_code"] 87 ) 88 if enroll_status != "success": 89 return self.executor.stage_invalid(f"Invalid enrollment status: {enroll_status}.") 90 existing_device = DuoDevice.objects.filter(duo_user_id=enroll["user_id"]).first() 91 self.executor.plan.context.pop(PLAN_CONTEXT_DUO_ENROLL) 92 if not existing_device: 93 DuoDevice.objects.create( 94 name="Duo Authenticator", 95 user=self.get_pending_user(), 96 duo_user_id=enroll["user_id"], 97 stage=stage, 98 last_t=now(), 99 ) 100 else: 101 return self.executor.stage_invalid("Device with Credential ID already exists.") 102 return self.executor.stage_ok()
PLAN_CONTEXT_DUO_ENROLL =
'goauthentik.io/stages/authenticator_duo/enroll'
DUO_USERNAME_EXISTS_ERROR =
'username already exists'
def
duo_enrollment_error_message(exc: RuntimeError) -> str:
23def duo_enrollment_error_message(exc: RuntimeError) -> str: 24 """Return a user-facing error message for Duo enrollment failures.""" 25 if DUO_USERNAME_EXISTS_ERROR in str(exc).lower(): 26 return _( 27 "A Duo user with this username already exists. Ask an administrator to import the " 28 "existing Duo authenticator or delete the Duo user before enrolling again." 29 ) 30 return _("Failed to enroll with Duo. Please contact an administrator.")
Return a user-facing error message for Duo enrollment failures.
33class AuthenticatorDuoChallenge(WithUserInfoChallenge): 34 """Duo Challenge""" 35 36 activation_barcode = CharField() 37 activation_code = CharField() 38 stage_uuid = CharField() 39 component = CharField(default="ak-stage-authenticator-duo")
Duo Challenge
42class AuthenticatorDuoChallengeResponse(ChallengeResponse): 43 """Pseudo class for duo response""" 44 45 component = CharField(default="ak-stage-authenticator-duo")
Pseudo class for duo response
48class AuthenticatorDuoStageView(ChallengeStageView): 49 """Duo stage""" 50 51 response_class = AuthenticatorDuoChallengeResponse 52 53 def duo_enroll(self): 54 """Enroll User with Duo API and save results""" 55 user = self.get_pending_user() 56 stage: AuthenticatorDuoStage = self.executor.current_stage 57 try: 58 enroll = stage.auth_client().enroll(user.username) 59 except RuntimeError as exc: 60 Event.new( 61 EventAction.CONFIGURATION_ERROR, 62 message=f"Failed to enroll user: {str(exc)}", 63 user=user, 64 ).from_http(self.request, user) 65 raise InvalidStageError(duo_enrollment_error_message(exc)) from exc 66 self.executor.plan.context[PLAN_CONTEXT_DUO_ENROLL] = enroll 67 return enroll 68 69 def get_challenge(self, *args, **kwargs) -> Challenge: 70 stage: AuthenticatorDuoStage = self.executor.current_stage 71 if PLAN_CONTEXT_DUO_ENROLL not in self.executor.plan.context: 72 self.duo_enroll() 73 enroll = self.executor.plan.context[PLAN_CONTEXT_DUO_ENROLL] 74 return AuthenticatorDuoChallenge( 75 data={ 76 "activation_barcode": enroll["activation_barcode"], 77 "activation_code": enroll["activation_code"], 78 "stage_uuid": str(stage.stage_uuid), 79 } 80 ) 81 82 def challenge_valid(self, response: ChallengeResponse) -> HttpResponse: 83 # Duo Challenge has already been validated 84 stage: AuthenticatorDuoStage = self.executor.current_stage 85 enroll = self.executor.plan.context.get(PLAN_CONTEXT_DUO_ENROLL) 86 enroll_status = stage.auth_client().enroll_status( 87 enroll["user_id"], enroll["activation_code"] 88 ) 89 if enroll_status != "success": 90 return self.executor.stage_invalid(f"Invalid enrollment status: {enroll_status}.") 91 existing_device = DuoDevice.objects.filter(duo_user_id=enroll["user_id"]).first() 92 self.executor.plan.context.pop(PLAN_CONTEXT_DUO_ENROLL) 93 if not existing_device: 94 DuoDevice.objects.create( 95 name="Duo Authenticator", 96 user=self.get_pending_user(), 97 duo_user_id=enroll["user_id"], 98 stage=stage, 99 last_t=now(), 100 ) 101 else: 102 return self.executor.stage_invalid("Device with Credential ID already exists.") 103 return self.executor.stage_ok()
Duo stage
response_class =
<class 'AuthenticatorDuoChallengeResponse'>
def
duo_enroll(self):
53 def duo_enroll(self): 54 """Enroll User with Duo API and save results""" 55 user = self.get_pending_user() 56 stage: AuthenticatorDuoStage = self.executor.current_stage 57 try: 58 enroll = stage.auth_client().enroll(user.username) 59 except RuntimeError as exc: 60 Event.new( 61 EventAction.CONFIGURATION_ERROR, 62 message=f"Failed to enroll user: {str(exc)}", 63 user=user, 64 ).from_http(self.request, user) 65 raise InvalidStageError(duo_enrollment_error_message(exc)) from exc 66 self.executor.plan.context[PLAN_CONTEXT_DUO_ENROLL] = enroll 67 return enroll
Enroll User with Duo API and save results
69 def get_challenge(self, *args, **kwargs) -> Challenge: 70 stage: AuthenticatorDuoStage = self.executor.current_stage 71 if PLAN_CONTEXT_DUO_ENROLL not in self.executor.plan.context: 72 self.duo_enroll() 73 enroll = self.executor.plan.context[PLAN_CONTEXT_DUO_ENROLL] 74 return AuthenticatorDuoChallenge( 75 data={ 76 "activation_barcode": enroll["activation_barcode"], 77 "activation_code": enroll["activation_code"], 78 "stage_uuid": str(stage.stage_uuid), 79 } 80 )
Return the challenge that the client should solve
def
challenge_valid( self, response: authentik.flows.challenge.ChallengeResponse) -> django.http.response.HttpResponse:
82 def challenge_valid(self, response: ChallengeResponse) -> HttpResponse: 83 # Duo Challenge has already been validated 84 stage: AuthenticatorDuoStage = self.executor.current_stage 85 enroll = self.executor.plan.context.get(PLAN_CONTEXT_DUO_ENROLL) 86 enroll_status = stage.auth_client().enroll_status( 87 enroll["user_id"], enroll["activation_code"] 88 ) 89 if enroll_status != "success": 90 return self.executor.stage_invalid(f"Invalid enrollment status: {enroll_status}.") 91 existing_device = DuoDevice.objects.filter(duo_user_id=enroll["user_id"]).first() 92 self.executor.plan.context.pop(PLAN_CONTEXT_DUO_ENROLL) 93 if not existing_device: 94 DuoDevice.objects.create( 95 name="Duo Authenticator", 96 user=self.get_pending_user(), 97 duo_user_id=enroll["user_id"], 98 stage=stage, 99 last_t=now(), 100 ) 101 else: 102 return self.executor.stage_invalid("Device with Credential ID already exists.") 103 return self.executor.stage_ok()
Callback when the challenge has the correct format