authentik.stages.captcha.stage

authentik captcha stage

  1"""authentik captcha stage"""
  2
  3from django.http.response import HttpResponse
  4from django.utils.translation import gettext as _
  5from requests import RequestException
  6from rest_framework.fields import BooleanField, CharField
  7from rest_framework.serializers import ValidationError
  8from structlog.stdlib import get_logger
  9
 10from authentik.flows.challenge import (
 11    Challenge,
 12    ChallengeResponse,
 13    WithUserInfoChallenge,
 14)
 15from authentik.flows.stage import ChallengeStageView
 16from authentik.lib.utils.http import get_http_session
 17from authentik.root.middleware import ClientIPMiddleware
 18from authentik.stages.captcha.models import CaptchaRequestContentType, CaptchaStage
 19
 20LOGGER = get_logger()
 21PLAN_CONTEXT_CAPTCHA = "captcha"
 22PLAN_CONTEXT_CAPTCHA_SITE_KEY = "goauthentik.io/stages/captcha/site_key"
 23PLAN_CONTEXT_CAPTCHA_PRIVATE_KEY = "goauthentik.io/stages/captcha/private_key"
 24
 25
 26class CaptchaChallenge(WithUserInfoChallenge):
 27    """Site public key"""
 28
 29    component = CharField(default="ak-stage-captcha")
 30
 31    site_key = CharField(required=True)
 32    js_url = CharField(required=True)
 33    interactive = BooleanField(required=True)
 34
 35
 36def verify_captcha_token(stage: CaptchaStage, token: str, remote_ip: str, key: str | None = None):
 37    """Validate captcha token"""
 38    payload = {
 39        "secret": key or stage.private_key,
 40        "response": token,
 41        "remoteip": remote_ip,
 42    }
 43    body_kwargs = (
 44        {"json": payload}
 45        if stage.request_content_type == CaptchaRequestContentType.JSON
 46        else {"data": payload}
 47    )
 48    try:
 49        response = get_http_session().post(
 50            stage.api_url,
 51            headers={
 52                "Content-Type": stage.request_content_type,
 53            },
 54            **body_kwargs,
 55        )
 56        response.raise_for_status()
 57        data = response.json()
 58        if stage.error_on_invalid_score:
 59            if not data.get("success", False):
 60                error_codes = data.get("error-codes", ["unknown-error"])
 61                LOGGER.warning("Failed to verify captcha token", error_codes=error_codes)
 62
 63                # These cases can usually be fixed by simply requesting a new token and retrying.
 64                # [reCAPTCHA](https://developers.google.com/recaptcha/docs/verify#error_code_reference)
 65                # [hCaptcha](https://docs.hcaptcha.com/#siteverify-error-codes-table)
 66                # [Turnstile](https://developers.cloudflare.com/turnstile/get-started/server-side-validation/#error-codes)
 67                retryable_error_codes = [
 68                    "missing-input-response",
 69                    "invalid-input-response",
 70                    "timeout-or-duplicate",
 71                    "expired-input-response",
 72                    "already-seen-response",
 73                ]
 74
 75                if set(error_codes).issubset(set(retryable_error_codes)):
 76                    error_message = _("Invalid captcha response. Retrying may solve this issue.")
 77                else:
 78                    error_message = _("Invalid captcha response")
 79                raise ValidationError(error_message)
 80            if "score" in data:
 81                score = float(data.get("score"))
 82                if stage.score_max_threshold > -1 and score > stage.score_max_threshold:
 83                    raise ValidationError(_("Invalid captcha response"))
 84                if stage.score_min_threshold > -1 and score < stage.score_min_threshold:
 85                    raise ValidationError(_("Invalid captcha response"))
 86    except (RequestException, TypeError) as exc:
 87        raise ValidationError(_("Failed to validate token")) from exc
 88
 89    return data
 90
 91
 92class CaptchaChallengeResponse(ChallengeResponse):
 93    """Validate captcha token"""
 94
 95    token = CharField()
 96    component = CharField(default="ak-stage-captcha")
 97
 98    def validate_token(self, token: str) -> str:
 99        """Validate captcha token"""
100        stage: CaptchaStage = self.stage.executor.current_stage
101        client_ip = ClientIPMiddleware.get_client_ip(self.stage.request)
102
103        return verify_captcha_token(
104            stage,
105            token,
106            client_ip,
107            key=self.stage.executor.plan.context.get(PLAN_CONTEXT_CAPTCHA_PRIVATE_KEY),
108        )
109
110
111class CaptchaStageView(ChallengeStageView):
112    """Simple captcha checker, logic is handled in django-captcha module"""
113
114    response_class = CaptchaChallengeResponse
115
116    def get_challenge(self, *args, **kwargs) -> Challenge:
117        site_key = self.executor.plan.context.get(
118            PLAN_CONTEXT_CAPTCHA_SITE_KEY, self.executor.current_stage.public_key
119        )
120        return CaptchaChallenge(
121            data={
122                "js_url": self.executor.current_stage.js_url,
123                "site_key": site_key,
124                "interactive": self.executor.current_stage.interactive,
125            }
126        )
127
128    def challenge_valid(self, response: CaptchaChallengeResponse) -> HttpResponse:
129        response = response.validated_data["token"]
130        self.executor.plan.context[PLAN_CONTEXT_CAPTCHA] = {
131            "response": response,
132            "stage": self.executor.current_stage,
133        }
134        return self.executor.stage_ok()
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
PLAN_CONTEXT_CAPTCHA = 'captcha'
PLAN_CONTEXT_CAPTCHA_SITE_KEY = 'goauthentik.io/stages/captcha/site_key'
PLAN_CONTEXT_CAPTCHA_PRIVATE_KEY = 'goauthentik.io/stages/captcha/private_key'
class CaptchaChallenge(authentik.flows.challenge.WithUserInfoChallenge):
27class CaptchaChallenge(WithUserInfoChallenge):
28    """Site public key"""
29
30    component = CharField(default="ak-stage-captcha")
31
32    site_key = CharField(required=True)
33    js_url = CharField(required=True)
34    interactive = BooleanField(required=True)

Site public key

component
site_key
js_url
interactive
def verify_captcha_token( stage: authentik.stages.captcha.models.CaptchaStage, token: str, remote_ip: str, key: str | None = None):
37def verify_captcha_token(stage: CaptchaStage, token: str, remote_ip: str, key: str | None = None):
38    """Validate captcha token"""
39    payload = {
40        "secret": key or stage.private_key,
41        "response": token,
42        "remoteip": remote_ip,
43    }
44    body_kwargs = (
45        {"json": payload}
46        if stage.request_content_type == CaptchaRequestContentType.JSON
47        else {"data": payload}
48    )
49    try:
50        response = get_http_session().post(
51            stage.api_url,
52            headers={
53                "Content-Type": stage.request_content_type,
54            },
55            **body_kwargs,
56        )
57        response.raise_for_status()
58        data = response.json()
59        if stage.error_on_invalid_score:
60            if not data.get("success", False):
61                error_codes = data.get("error-codes", ["unknown-error"])
62                LOGGER.warning("Failed to verify captcha token", error_codes=error_codes)
63
64                # These cases can usually be fixed by simply requesting a new token and retrying.
65                # [reCAPTCHA](https://developers.google.com/recaptcha/docs/verify#error_code_reference)
66                # [hCaptcha](https://docs.hcaptcha.com/#siteverify-error-codes-table)
67                # [Turnstile](https://developers.cloudflare.com/turnstile/get-started/server-side-validation/#error-codes)
68                retryable_error_codes = [
69                    "missing-input-response",
70                    "invalid-input-response",
71                    "timeout-or-duplicate",
72                    "expired-input-response",
73                    "already-seen-response",
74                ]
75
76                if set(error_codes).issubset(set(retryable_error_codes)):
77                    error_message = _("Invalid captcha response. Retrying may solve this issue.")
78                else:
79                    error_message = _("Invalid captcha response")
80                raise ValidationError(error_message)
81            if "score" in data:
82                score = float(data.get("score"))
83                if stage.score_max_threshold > -1 and score > stage.score_max_threshold:
84                    raise ValidationError(_("Invalid captcha response"))
85                if stage.score_min_threshold > -1 and score < stage.score_min_threshold:
86                    raise ValidationError(_("Invalid captcha response"))
87    except (RequestException, TypeError) as exc:
88        raise ValidationError(_("Failed to validate token")) from exc
89
90    return data

Validate captcha token

class CaptchaChallengeResponse(authentik.flows.challenge.ChallengeResponse):
 93class CaptchaChallengeResponse(ChallengeResponse):
 94    """Validate captcha token"""
 95
 96    token = CharField()
 97    component = CharField(default="ak-stage-captcha")
 98
 99    def validate_token(self, token: str) -> str:
100        """Validate captcha token"""
101        stage: CaptchaStage = self.stage.executor.current_stage
102        client_ip = ClientIPMiddleware.get_client_ip(self.stage.request)
103
104        return verify_captcha_token(
105            stage,
106            token,
107            client_ip,
108            key=self.stage.executor.plan.context.get(PLAN_CONTEXT_CAPTCHA_PRIVATE_KEY),
109        )

Validate captcha token

token
component
def validate_token(self, token: str) -> str:
 99    def validate_token(self, token: str) -> str:
100        """Validate captcha token"""
101        stage: CaptchaStage = self.stage.executor.current_stage
102        client_ip = ClientIPMiddleware.get_client_ip(self.stage.request)
103
104        return verify_captcha_token(
105            stage,
106            token,
107            client_ip,
108            key=self.stage.executor.plan.context.get(PLAN_CONTEXT_CAPTCHA_PRIVATE_KEY),
109        )

Validate captcha token

class CaptchaStageView(authentik.flows.stage.ChallengeStageView):
112class CaptchaStageView(ChallengeStageView):
113    """Simple captcha checker, logic is handled in django-captcha module"""
114
115    response_class = CaptchaChallengeResponse
116
117    def get_challenge(self, *args, **kwargs) -> Challenge:
118        site_key = self.executor.plan.context.get(
119            PLAN_CONTEXT_CAPTCHA_SITE_KEY, self.executor.current_stage.public_key
120        )
121        return CaptchaChallenge(
122            data={
123                "js_url": self.executor.current_stage.js_url,
124                "site_key": site_key,
125                "interactive": self.executor.current_stage.interactive,
126            }
127        )
128
129    def challenge_valid(self, response: CaptchaChallengeResponse) -> HttpResponse:
130        response = response.validated_data["token"]
131        self.executor.plan.context[PLAN_CONTEXT_CAPTCHA] = {
132            "response": response,
133            "stage": self.executor.current_stage,
134        }
135        return self.executor.stage_ok()

Simple captcha checker, logic is handled in django-captcha module

response_class = <class 'CaptchaChallengeResponse'>
def get_challenge(self, *args, **kwargs) -> authentik.flows.challenge.Challenge:
117    def get_challenge(self, *args, **kwargs) -> Challenge:
118        site_key = self.executor.plan.context.get(
119            PLAN_CONTEXT_CAPTCHA_SITE_KEY, self.executor.current_stage.public_key
120        )
121        return CaptchaChallenge(
122            data={
123                "js_url": self.executor.current_stage.js_url,
124                "site_key": site_key,
125                "interactive": self.executor.current_stage.interactive,
126            }
127        )

Return the challenge that the client should solve

def challenge_valid( self, response: CaptchaChallengeResponse) -> django.http.response.HttpResponse:
129    def challenge_valid(self, response: CaptchaChallengeResponse) -> HttpResponse:
130        response = response.validated_data["token"]
131        self.executor.plan.context[PLAN_CONTEXT_CAPTCHA] = {
132            "response": response,
133            "stage": self.executor.current_stage,
134        }
135        return self.executor.stage_ok()

Callback when the challenge has the correct format