authentik.stages.authenticator_webauthn.tests.test_stage

Test WebAuthn API

  1"""Test WebAuthn API"""
  2
  3from base64 import b64decode
  4from json import loads
  5from unittest import skipIf
  6from unittest.mock import MagicMock, patch
  7
  8from cryptography.hazmat.backends.openssl.backend import backend
  9from django.urls import reverse
 10from webauthn.helpers.base64url_to_bytes import base64url_to_bytes
 11from webauthn.helpers.bytes_to_base64url import bytes_to_base64url
 12from webauthn.helpers.cose import COSEAlgorithmIdentifier
 13
 14from authentik.core.tests.utils import create_test_admin_user, create_test_flow, create_test_user
 15from authentik.flows.markers import StageMarker
 16from authentik.flows.models import FlowStageBinding
 17from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER, FlowPlan
 18from authentik.flows.tests import APIFlowTestCase
 19from authentik.flows.views.executor import SESSION_KEY_PLAN
 20from authentik.lib.generators import generate_id
 21from authentik.lib.tests.utils import load_fixture
 22from authentik.stages.authenticator_webauthn.algorithms import PREFERRED_PUB_KEY_ALGS
 23from authentik.stages.authenticator_webauthn.models import (
 24    UNKNOWN_DEVICE_TYPE_AAGUID,
 25    AuthenticatorWebAuthnStage,
 26    WebAuthnDevice,
 27    WebAuthnDeviceType,
 28    WebAuthnHint,
 29)
 30from authentik.stages.authenticator_webauthn.stage import PLAN_CONTEXT_WEBAUTHN_CHALLENGE
 31from authentik.stages.authenticator_webauthn.tasks import webauthn_mds_import
 32from authentik.stages.authenticator_webauthn.tests.credentials import SoftwareCredential
 33from authentik.stages.dummy.models import DummyStage
 34
 35
 36class TestAuthenticatorWebAuthnStage(APIFlowTestCase):
 37    """Test WebAuthn API"""
 38
 39    def setUp(self) -> None:
 40        self.stage = AuthenticatorWebAuthnStage.objects.create(
 41            name=generate_id(),
 42        )
 43        self.flow = create_test_flow()
 44        self.binding = FlowStageBinding.objects.create(
 45            target=self.flow,
 46            stage=self.stage,
 47            order=0,
 48        )
 49        self.user = create_test_admin_user()
 50
 51    def test_api_delete(self):
 52        """Test api delete"""
 53        self.client.force_login(self.user)
 54        dev = WebAuthnDevice.objects.create(user=self.user)
 55        response = self.client.delete(
 56            reverse("authentik_api:webauthndevice-detail", kwargs={"pk": dev.pk})
 57        )
 58        self.assertEqual(response.status_code, 204)
 59
 60    @skipIf(backend._fips_enabled, "The FIPS provider has no Ed25519 or ML-DSA")
 61    def test_registration_options(self):
 62        """Test registration options"""
 63        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
 64        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
 65        session = self.client.session
 66        session[SESSION_KEY_PLAN] = plan
 67        session.save()
 68
 69        response = self.client.get(
 70            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
 71        )
 72
 73        plan: FlowPlan = self.client.session[SESSION_KEY_PLAN]
 74
 75        self.assertEqual(response.status_code, 200)
 76        session = self.client.session
 77        self.assertStageResponse(
 78            response,
 79            self.flow,
 80            self.user,
 81            registration={
 82                "rp": {"name": "authentik", "id": "testserver"},
 83                "user": {
 84                    "id": bytes_to_base64url(self.user.uid.encode("utf-8")),
 85                    "name": self.user.username,
 86                    "displayName": self.user.name,
 87                },
 88                "challenge": bytes_to_base64url(plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE]),
 89                "pubKeyCredParams": [
 90                    {"type": "public-key", "alg": -8},
 91                    {"type": "public-key", "alg": -7},
 92                    {"type": "public-key", "alg": -257},
 93                    {"type": "public-key", "alg": -48},
 94                    {"type": "public-key", "alg": -49},
 95                    {"type": "public-key", "alg": -50},
 96                ],
 97                "timeout": 60000,
 98                "excludeCredentials": [],
 99                "authenticatorSelection": {
100                    "residentKey": "preferred",
101                    "requireResidentKey": False,
102                    "userVerification": "preferred",
103                },
104                "attestation": "direct",
105            },
106        )
107
108    def test_register(self):
109        """Test registration"""
110        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
111        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
112        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
113            b"iHIX3AtkZZCxSYLxOhk80ZXI7RnAC0Pb4WTk9dEJ4eLJdzoh8jRmjKW2U9oE/CBn5n6Zj67BIIZvFL3lpiwJwg=="
114        )
115        session = self.client.session
116        session[SESSION_KEY_PLAN] = plan
117        session.save()
118        response = self.client.post(
119            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
120            data={
121                "component": "ak-stage-authenticator-webauthn",
122                "response": loads(load_fixture("fixtures/register.json")),
123            },
124            SERVER_NAME="localhost",
125            SERVER_PORT="9000",
126        )
127        self.assertEqual(response.status_code, 200)
128        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
129        device = WebAuthnDevice.objects.filter(user=self.user).first()
130        self.assertIsNotNone(device)
131        self.assertEqual(
132            device.credential_id, "f7wv8mP-poSxh-567eWxZntzCBDW8hWlvzf92QJkT--Y2oBRz4IEAZ6M2PI9_KEQ"
133        )
134        self.assertEqual(
135            device.attestation_certificate_fingerprint,
136            "3e:28:fc:df:45:19:bb:94:0a:0c:90:98:f2:08:72:53:2a:9e:e2:76:13:02:3e:69:61:4a:d9:90:49:80:3d:34",
137        )
138
139    def test_registration_options_exclude_credentials(self):
140        """Test that already registered credentials are excluded from registration options"""
141        device = WebAuthnDevice.objects.create(
142            user=self.user,
143            name=generate_id(),
144            credential_id=bytes_to_base64url(b"existing-credential"),
145            rp_id="testserver",
146        )
147        # Devices of other users, devices registered for a different RP, and unconfirmed devices
148        # must not leak into the exclusion list
149        WebAuthnDevice.objects.create(
150            user=create_test_user(),
151            name=generate_id(),
152            credential_id=bytes_to_base64url(b"other-users-credential"),
153            rp_id="testserver",
154        )
155        WebAuthnDevice.objects.create(
156            user=self.user,
157            name=generate_id(),
158            credential_id=bytes_to_base64url(b"other-rp-credential"),
159            rp_id="other.rp.example.com",
160        )
161        WebAuthnDevice.objects.create(
162            user=self.user,
163            name=generate_id(),
164            credential_id=bytes_to_base64url(b"unconfirmed-credential"),
165            rp_id="testserver",
166            confirmed=False,
167        )
168
169        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
170        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
171        session = self.client.session
172        session[SESSION_KEY_PLAN] = plan
173        session.save()
174
175        response = self.client.get(
176            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
177        )
178
179        self.assertEqual(response.status_code, 200)
180        self.assertEqual(
181            loads(response.content)["registration"]["excludeCredentials"],
182            [{"id": device.credential_id, "type": "public-key"}],
183        )
184
185    def test_register_removes_challenge(self):
186        """Test that the registration challenge is removed from the plan once answered"""
187        dummy_binding = FlowStageBinding.objects.create(
188            target=self.flow,
189            stage=DummyStage.objects.create(name=generate_id()),
190            order=1,
191        )
192        plan = FlowPlan(
193            flow_pk=self.flow.pk.hex,
194            bindings=[self.binding, dummy_binding],
195            markers=[StageMarker(), StageMarker()],
196        )
197        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
198        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
199            b"iHIX3AtkZZCxSYLxOhk80ZXI7RnAC0Pb4WTk9dEJ4eLJdzoh8jRmjKW2U9oE/CBn5n6Zj67BIIZvFL3lpiwJwg=="
200        )
201        session = self.client.session
202        session[SESSION_KEY_PLAN] = plan
203        session.save()
204        response = self.client.post(
205            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
206            data={
207                "component": "ak-stage-authenticator-webauthn",
208                "response": loads(load_fixture("fixtures/register.json")),
209            },
210            SERVER_NAME="localhost",
211            SERVER_PORT="9000",
212        )
213        self.assertEqual(response.status_code, 302)
214        self.assertTrue(WebAuthnDevice.objects.filter(user=self.user).exists())
215        plan: FlowPlan = self.client.session[SESSION_KEY_PLAN]
216        self.assertNotIn(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, plan.context)
217
218    def test_register_shared_attestation_certificate(self):
219        """Test that a device sharing an attestation certificate with an existing device of
220        another user can still be registered.
221
222        Attestation certificates are shared across entire manufacturing batches, so they must
223        never be treated as identifying an individual device."""
224        WebAuthnDevice.objects.create(
225            user=create_test_user(),
226            name=generate_id(),
227            credential_id=bytes_to_base64url(b"batch-sibling-credential"),
228            rp_id="localhost",
229            attestation_certificate_fingerprint=(
230                "3e:28:fc:df:45:19:bb:94:0a:0c:90:98:f2:08:72:53:"
231                "2a:9e:e2:76:13:02:3e:69:61:4a:d9:90:49:80:3d:34"
232            ),
233        )
234
235        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
236        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
237        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
238            b"iHIX3AtkZZCxSYLxOhk80ZXI7RnAC0Pb4WTk9dEJ4eLJdzoh8jRmjKW2U9oE/CBn5n6Zj67BIIZvFL3lpiwJwg=="
239        )
240        session = self.client.session
241        session[SESSION_KEY_PLAN] = plan
242        session.save()
243        response = self.client.post(
244            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
245            data={
246                "component": "ak-stage-authenticator-webauthn",
247                "response": loads(load_fixture("fixtures/register.json")),
248            },
249            SERVER_NAME="localhost",
250            SERVER_PORT="9000",
251        )
252        self.assertEqual(response.status_code, 200)
253        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
254        self.assertTrue(WebAuthnDevice.objects.filter(user=self.user).exists())
255
256    def _register_malformed_attestation_certificate(self):
257        """Register with a packed attestation whose certificate encodes explicit NULL parameters
258        for ecdsa-with-SHA256, which OpenSSL accepts but cryptography rejects with a ValueError"""
259        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
260        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
261        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
262            b"03Xodi54gKsfnP5I9VFfhaGXVVE2NUyZpBBXns/JI+x6V9RY2Tw2QmxRJkhh7174EkRazUntIwjMVY9bFG60Lw=="
263        )
264        session = self.client.session
265        session[SESSION_KEY_PLAN] = plan
266        session.save()
267        response = self.client.post(
268            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
269            data={
270                "component": "ak-stage-authenticator-webauthn",
271                "response": loads(
272                    load_fixture("fixtures/register_malformed_attestation_certificate.json")
273                ),
274            },
275            SERVER_NAME="localhost",
276            SERVER_PORT="9000",
277        )
278        self.assertEqual(response.status_code, 200)
279        return response
280
281    def test_register_malformed_attestation_certificate(self):
282        """Test registration with an attestation certificate that fails verification"""
283        response = self._register_malformed_attestation_certificate()
284        self.assertStageResponse(
285            response,
286            flow=self.flow,
287            component="ak-stage-authenticator-webauthn",
288            response_errors={
289                "response": [
290                    {
291                        "string": "Registration failed. Please contact your administrator.",
292                        "code": "invalid",
293                    }
294                ]
295            },
296        )
297        self.assertFalse(WebAuthnDevice.objects.filter(user=self.user).exists())
298
299    def test_register_verified_malformed_attestation_certificate(self):
300        """Test registration with an attestation certificate that only OpenSSL can parse,
301        like android-key attestation which verifies with OpenSSL"""
302        attestation_object = base64url_to_bytes(
303            loads(load_fixture("fixtures/register_malformed_attestation_certificate.json"))[
304                "response"
305            ]["attestationObject"]
306        )
307        registration = MagicMock(
308            attestation_object=attestation_object,
309            credential_id=b"credential",
310            credential_public_key=b"public-key",
311            sign_count=0,
312            aaguid="00000000-0000-0000-0000-000000000000",
313        )
314        with patch(
315            "authentik.stages.authenticator_webauthn.stage.verify_registration_response",
316            return_value=registration,
317        ):
318            response = self._register_malformed_attestation_certificate()
319        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
320        device = WebAuthnDevice.objects.get(user=self.user)
321        self.assertIsNone(device.attestation_certificate_pem)
322        self.assertIsNone(device.attestation_certificate_fingerprint)
323
324    def test_register_restricted_device_type_deny(self):
325        """Test registration with restricted devices (fail)"""
326        webauthn_mds_import.send(force=True)
327        self.stage.device_type_restrictions.set(
328            WebAuthnDeviceType.objects.filter(description="YubiKey 5 Series")
329        )
330
331        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
332        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
333        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
334            b"03Xodi54gKsfnP5I9VFfhaGXVVE2NUyZpBBXns/JI+x6V9RY2Tw2QmxRJkhh7174EkRazUntIwjMVY9bFG60Lw=="
335        )
336        session = self.client.session
337        session[SESSION_KEY_PLAN] = plan
338        session.save()
339        response = self.client.post(
340            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
341            data={
342                "component": "ak-stage-authenticator-webauthn",
343                "response": {
344                    "id": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
345                    "rawId": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
346                    "type": "public-key",
347                    "registrationClientExtensions": "{}",
348                    "response": {
349                        "clientDataJSON": (
350                            "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmd"
351                            "lIjoiMDNYb2RpNTRnS3NmblA1STlWRmZoYUdYVlZFMk5VeV"
352                            "pwQkJYbnNfSkkteDZWOVJZMlR3MlFteFJKa2hoNzE3NEVrU"
353                            "mF6VW50SXdqTVZZOWJGRzYwTHciLCJvcmlnaW4iOiJodHRw"
354                            "Oi8vbG9jYWxob3N0OjkwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2V9"
355                        ),
356                        "attestationObject": (
357                            "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YViYSZYN5Yg"
358                            "OjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2NdAAAAAPv8MA"
359                            "cVTk7MjAtuAgVX170AFJKp5q1S5wxvjsLEjR5IoWGWjc-bp"
360                            "QECAyYgASFYIKtcZHPumH37XHs0IM1v3pUBRIqHVV_SE-Lq"
361                            "2zpJAOVXIlgg74Fg_WdB0kuLYqCKbxogkEPaVtR_iR3IyQFIJAXBzds"
362                        ),
363                    },
364                },
365            },
366            SERVER_NAME="localhost",
367            SERVER_PORT="9000",
368        )
369        self.assertEqual(response.status_code, 200)
370        self.assertStageResponse(
371            response,
372            flow=self.flow,
373            component="ak-stage-authenticator-webauthn",
374            response_errors={
375                "response": [
376                    {
377                        "string": (
378                            "Invalid device type. Contact your authentik administrator for help."
379                        ),
380                        "code": "invalid",
381                    }
382                ]
383            },
384        )
385        self.assertFalse(WebAuthnDevice.objects.filter(user=self.user).exists())
386
387    def test_register_restricted_device_type_allow(self):
388        """Test registration with restricted devices (allow)"""
389        webauthn_mds_import.send(force=True)
390        self.stage.device_type_restrictions.set(
391            WebAuthnDeviceType.objects.filter(description="iCloud Keychain")
392        )
393
394        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
395        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
396        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
397            b"03Xodi54gKsfnP5I9VFfhaGXVVE2NUyZpBBXns/JI+x6V9RY2Tw2QmxRJkhh7174EkRazUntIwjMVY9bFG60Lw=="
398        )
399        session = self.client.session
400        session[SESSION_KEY_PLAN] = plan
401        session.save()
402        response = self.client.post(
403            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
404            data={
405                "component": "ak-stage-authenticator-webauthn",
406                "response": {
407                    "id": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
408                    "rawId": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
409                    "type": "public-key",
410                    "registrationClientExtensions": "{}",
411                    "response": {
412                        "clientDataJSON": (
413                            "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmd"
414                            "lIjoiMDNYb2RpNTRnS3NmblA1STlWRmZoYUdYVlZFMk5VeV"
415                            "pwQkJYbnNfSkkteDZWOVJZMlR3MlFteFJKa2hoNzE3NEVrU"
416                            "mF6VW50SXdqTVZZOWJGRzYwTHciLCJvcmlnaW4iOiJodHRw"
417                            "Oi8vbG9jYWxob3N0OjkwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2V9"
418                        ),
419                        "attestationObject": (
420                            "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YViYSZYN5Yg"
421                            "OjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2NdAAAAAPv8MA"
422                            "cVTk7MjAtuAgVX170AFJKp5q1S5wxvjsLEjR5IoWGWjc-bp"
423                            "QECAyYgASFYIKtcZHPumH37XHs0IM1v3pUBRIqHVV_SE-Lq"
424                            "2zpJAOVXIlgg74Fg_WdB0kuLYqCKbxogkEPaVtR_iR3IyQFIJAXBzds"
425                        ),
426                    },
427                },
428            },
429            SERVER_NAME="localhost",
430            SERVER_PORT="9000",
431        )
432        self.assertEqual(response.status_code, 200)
433        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
434        self.assertTrue(WebAuthnDevice.objects.filter(user=self.user).exists())
435
436    def test_register_restricted_device_type_allow_unknown(self):
437        """Test registration with restricted devices (allow, unknown device type)"""
438        webauthn_mds_import.send(force=True)
439        WebAuthnDeviceType.objects.filter(aaguid="fbfc3007-154e-4ecc-8c0b-6e020557d7bd").delete()
440        self.stage.device_type_restrictions.set(
441            WebAuthnDeviceType.objects.filter(aaguid=UNKNOWN_DEVICE_TYPE_AAGUID)
442        )
443
444        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
445        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
446        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
447            b"03Xodi54gKsfnP5I9VFfhaGXVVE2NUyZpBBXns/JI+x6V9RY2Tw2QmxRJkhh7174EkRazUntIwjMVY9bFG60Lw=="
448        )
449        session = self.client.session
450        session[SESSION_KEY_PLAN] = plan
451        session.save()
452        response = self.client.post(
453            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
454            data={
455                "component": "ak-stage-authenticator-webauthn",
456                "response": {
457                    "id": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
458                    "rawId": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
459                    "type": "public-key",
460                    "registrationClientExtensions": "{}",
461                    "response": {
462                        "clientDataJSON": (
463                            "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmd"
464                            "lIjoiMDNYb2RpNTRnS3NmblA1STlWRmZoYUdYVlZFMk5VeV"
465                            "pwQkJYbnNfSkkteDZWOVJZMlR3MlFteFJKa2hoNzE3NEVrU"
466                            "mF6VW50SXdqTVZZOWJGRzYwTHciLCJvcmlnaW4iOiJodHRw"
467                            "Oi8vbG9jYWxob3N0OjkwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2V9"
468                        ),
469                        "attestationObject": (
470                            "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YViYSZYN5Yg"
471                            "OjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2NdAAAAAPv8MA"
472                            "cVTk7MjAtuAgVX170AFJKp5q1S5wxvjsLEjR5IoWGWjc-bp"
473                            "QECAyYgASFYIKtcZHPumH37XHs0IM1v3pUBRIqHVV_SE-Lq"
474                            "2zpJAOVXIlgg74Fg_WdB0kuLYqCKbxogkEPaVtR_iR3IyQFIJAXBzds"
475                        ),
476                    },
477                },
478            },
479            SERVER_NAME="localhost",
480            SERVER_PORT="9000",
481        )
482        self.assertEqual(response.status_code, 200)
483        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
484        self.assertTrue(WebAuthnDevice.objects.filter(user=self.user).exists())
485
486    def test_registration_options_with_hints(self):
487        """Test that hints are included in registration options"""
488        self.stage.hints = [WebAuthnHint.CLIENT_DEVICE, WebAuthnHint.SECURITY_KEY]
489        self.stage.save()
490
491        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
492        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
493        session = self.client.session
494        session[SESSION_KEY_PLAN] = plan
495        session.save()
496
497        response = self.client.get(
498            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
499        )
500        self.assertEqual(response.status_code, 200)
501        registration = response.json()["registration"]
502        self.assertEqual(registration["hints"], ["client-device", "security-key"])
503
504    def test_registration_options_hints_empty(self):
505        """Test that no hints key is present when hints are empty"""
506        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
507        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
508        session = self.client.session
509        session[SESSION_KEY_PLAN] = plan
510        session.save()
511
512        response = self.client.get(
513            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
514        )
515        self.assertEqual(response.status_code, 200)
516        registration = response.json()["registration"]
517        self.assertNotIn("hints", registration)
518
519    def test_registration_options_hints_infer_attachment_cross_platform(self):
520        """Test that authenticatorAttachment is auto-inferred as cross-platform
521        from security-key/hybrid hints for backwards compatibility"""
522        self.stage.hints = [WebAuthnHint.SECURITY_KEY]
523        self.stage.authenticator_attachment = None
524        self.stage.save()
525
526        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
527        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
528        session = self.client.session
529        session[SESSION_KEY_PLAN] = plan
530        session.save()
531
532        response = self.client.get(
533            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
534        )
535        self.assertEqual(response.status_code, 200)
536        registration = response.json()["registration"]
537        self.assertEqual(
538            registration["authenticatorSelection"]["authenticatorAttachment"], "cross-platform"
539        )
540
541    def test_registration_options_hints_infer_attachment_platform(self):
542        """Test that authenticatorAttachment is auto-inferred as platform
543        from client-device hint for backwards compatibility"""
544        self.stage.hints = [WebAuthnHint.CLIENT_DEVICE]
545        self.stage.authenticator_attachment = None
546        self.stage.save()
547
548        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
549        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
550        session = self.client.session
551        session[SESSION_KEY_PLAN] = plan
552        session.save()
553
554        response = self.client.get(
555            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
556        )
557        self.assertEqual(response.status_code, 200)
558        registration = response.json()["registration"]
559        self.assertEqual(
560            registration["authenticatorSelection"]["authenticatorAttachment"], "platform"
561        )
562
563    def test_registration_options_hints_no_infer_when_attachment_set(self):
564        """Test that authenticatorAttachment is NOT overridden when explicitly set"""
565        self.stage.hints = [WebAuthnHint.SECURITY_KEY]
566        self.stage.authenticator_attachment = "platform"
567        self.stage.save()
568
569        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
570        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
571        session = self.client.session
572        session[SESSION_KEY_PLAN] = plan
573        session.save()
574
575        response = self.client.get(
576            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
577        )
578        self.assertEqual(response.status_code, 200)
579        registration = response.json()["registration"]
580        self.assertEqual(
581            registration["authenticatorSelection"]["authenticatorAttachment"], "platform"
582        )
583
584    def test_registration_options_hints_no_infer_mixed(self):
585        """Test that authenticatorAttachment is NOT inferred when hints are mixed"""
586        self.stage.hints = [WebAuthnHint.SECURITY_KEY, WebAuthnHint.CLIENT_DEVICE]
587        self.stage.authenticator_attachment = None
588        self.stage.save()
589
590        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
591        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
592        session = self.client.session
593        session[SESSION_KEY_PLAN] = plan
594        session.save()
595
596        response = self.client.get(
597            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
598        )
599        self.assertEqual(response.status_code, 200)
600        registration = response.json()["registration"]
601        self.assertNotIn("authenticatorAttachment", registration["authenticatorSelection"])
602
603    def test_registration_options_hints_order_preserved(self):
604        """Test that hint order is preserved (first hint = highest priority)"""
605        self.stage.hints = [
606            WebAuthnHint.HYBRID,
607            WebAuthnHint.CLIENT_DEVICE,
608            WebAuthnHint.SECURITY_KEY,
609        ]
610        self.stage.save()
611
612        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
613        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
614        session = self.client.session
615        session[SESSION_KEY_PLAN] = plan
616        session.save()
617
618        response = self.client.get(
619            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
620        )
621        self.assertEqual(response.status_code, 200)
622        registration = response.json()["registration"]
623        self.assertEqual(registration["hints"], ["hybrid", "client-device", "security-key"])
624
625    def test_register_max_retries(self):
626        """Test registration (exceeding max retries)"""
627        self.stage.max_attempts = 2
628        self.stage.save()
629
630        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
631        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
632        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
633            b"03Xodi54gKsfnP5I9VFfhaGXVVE2NUyZpBBXns/JI+x6V9RY2Tw2QmxRJkhh7174EkRazUntIwjMVY9bFG60Lw=="
634        )
635        session = self.client.session
636        session[SESSION_KEY_PLAN] = plan
637        session.save()
638
639        # first failed request
640        response = self.client.post(
641            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
642            data={
643                "component": "ak-stage-authenticator-webauthn",
644                "response": {
645                    "id": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
646                    "rawId": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
647                    "type": "public-key",
648                    "registrationClientExtensions": "{}",
649                    "response": {
650                        "clientDataJSON": (
651                            "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmd"
652                            "lIjoiMDNYb2RpNTRnS3NmblA1STlWRmZoYUdYVlZFMk5VeV"
653                            "pwQkJYbnNfSkkteDZWOVJZMlR3MlFteFJKa2hoNzE3NEVrU"
654                            "mF6VW50SXdqTVZZOWJGRzYwTHciLCJvcmlnaW4iOiJodHRw"
655                            "Oi8vbG9jYWxob3N0OjkwMDAiLCJjcm9zc09yaWdpbiI6ZmF"
656                        ),
657                        "attestationObject": (
658                            "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YViYSZYN5Yg"
659                            "OjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2NdAAAAAPv8MA"
660                            "cVTk7MjAtuAgVX170AFJKp5q1S5wxvjsLEjR5IoWGWjc-bp"
661                            "QECAyYgASFYIKtcZHPumH37XHs0IM1v3pUBRIqHVV_SE-Lq"
662                            "2zpJAOVXIlgg74Fg_WdB0kuLYqCKbxogkEPaVtR_iR3IyQFIJAXBzds"
663                        ),
664                    },
665                },
666            },
667            SERVER_NAME="localhost",
668            SERVER_PORT="9000",
669        )
670        self.assertEqual(response.status_code, 200)
671        self.assertStageResponse(
672            response,
673            flow=self.flow,
674            component="ak-stage-authenticator-webauthn",
675            response_errors={
676                "response": [
677                    {
678                        "string": "Registration failed. Please contact your administrator.",
679                        "code": "invalid",
680                    }
681                ]
682            },
683        )
684        self.assertFalse(WebAuthnDevice.objects.filter(user=self.user).exists())
685
686        # Second failed request
687        response = self.client.post(
688            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
689            data={
690                "component": "ak-stage-authenticator-webauthn",
691                "response": {
692                    "id": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
693                    "rawId": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
694                    "type": "public-key",
695                    "registrationClientExtensions": "{}",
696                    "response": {
697                        "clientDataJSON": (
698                            "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmd"
699                            "lIjoiMDNYb2RpNTRnS3NmblA1STlWRmZoYUdYVlZFMk5VeV"
700                            "pwQkJYbnNfSkkteDZWOVJZMlR3MlFteFJKa2hoNzE3NEVrU"
701                            "mF6VW50SXdqTVZZOWJGRzYwTHciLCJvcmlnaW4iOiJodHRw"
702                            "Oi8vbG9jYWxob3N0OjkwMDAiLCJjcm9zc09yaWdpbiI6ZmF"
703                        ),
704                        "attestationObject": (
705                            "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YViYSZYN5Yg"
706                            "OjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2NdAAAAAPv8MA"
707                            "cVTk7MjAtuAgVX170AFJKp5q1S5wxvjsLEjR5IoWGWjc-bp"
708                            "QECAyYgASFYIKtcZHPumH37XHs0IM1v3pUBRIqHVV_SE-Lq"
709                            "2zpJAOVXIlgg74Fg_WdB0kuLYqCKbxogkEPaVtR_iR3IyQFIJAXBzds"
710                        ),
711                    },
712                },
713            },
714            SERVER_NAME="localhost",
715            SERVER_PORT="9000",
716        )
717        self.assertEqual(response.status_code, 200)
718        self.assertStageResponse(
719            response,
720            flow=self.flow,
721            component="ak-stage-access-denied",
722            error_message=(
723                "Exceeded maximum attempts. Contact your authentik administrator for help."
724            ),
725        )
726        self.assertFalse(WebAuthnDevice.objects.filter(user=self.user).exists())
727
728    @skipIf(backend._fips_enabled, "The FIPS provider has no Ed25519 or ML-DSA")
729    def test_registration_options_algorithms(self):
730        """Registration offers the classical algorithms first and the ML-DSA sets last"""
731        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
732        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
733        session = self.client.session
734        session[SESSION_KEY_PLAN] = plan
735        session.save()
736        response = self.client.get(
737            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
738        )
739        self.assertEqual(response.status_code, 200)
740        params = response.json()["registration"]["pubKeyCredParams"]
741        self.assertEqual([p["alg"] for p in params], [int(alg) for alg in PREFERRED_PUB_KEY_ALGS])
742        self.assertEqual([p["alg"] for p in params][-3:], [-48, -49, -50])
743
744    def _enable_fips(self):
745        """Pretend the OpenSSL FIPS provider is active, which has neither Ed25519 nor ML-DSA"""
746        patcher = patch(
747            "authentik.stages.authenticator_webauthn.algorithms.backend._fips_enabled", True
748        )
749        patcher.start()
750        self.addCleanup(patcher.stop)
751
752    def test_registration_options_algorithms_fips(self):
753        """With FIPS enabled only the algorithms the FIPS provider can verify are offered"""
754        self._enable_fips()
755        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
756        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
757        session = self.client.session
758        session[SESSION_KEY_PLAN] = plan
759        session.save()
760        response = self.client.get(
761            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
762        )
763        self.assertEqual(response.status_code, 200)
764        params = response.json()["registration"]["pubKeyCredParams"]
765        self.assertEqual([p["alg"] for p in params], [-7, -257])
766
767    def _register_software_credential(self, credential: SoftwareCredential):
768        challenge = b"\x01" * 64
769        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
770        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
771        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = challenge
772        session = self.client.session
773        session[SESSION_KEY_PLAN] = plan
774        session.save()
775        return self.client.post(
776            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
777            data={
778                "component": "ak-stage-authenticator-webauthn",
779                "response": credential.registration_response(challenge),
780            },
781            SERVER_NAME="localhost",
782            SERVER_PORT="9000",
783        )
784
785    @skipIf(backend._fips_enabled, "The FIPS provider has no Ed25519")
786    def test_register_eddsa(self):
787        """Test registration of an Ed25519 credential"""
788        credential = SoftwareCredential(
789            rp_id="localhost", origin="http://localhost:9000", alg=COSEAlgorithmIdentifier.EDDSA
790        )
791        response = self._register_software_credential(credential)
792        self.assertEqual(response.status_code, 200)
793        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
794        device = WebAuthnDevice.objects.get(user=self.user)
795        self.assertEqual(device.public_key, bytes_to_base64url(credential.cose_public_key))
796
797    @skipIf(backend._fips_enabled, "The FIPS provider has no Ed25519")
798    def test_register_unavailable_algorithm_fips(self):
799        """An authenticator that ignores the offered algorithms and creates a credential the
800        FIPS provider cannot verify is rejected at registration, not at first login"""
801        self._enable_fips()
802        credential = SoftwareCredential(
803            rp_id="localhost", origin="http://localhost:9000", alg=COSEAlgorithmIdentifier.EDDSA
804        )
805        response = self._register_software_credential(credential)
806        self.assertStageResponse(
807            response,
808            flow=self.flow,
809            component="ak-stage-authenticator-webauthn",
810            response_errors={
811                "response": [
812                    {
813                        "string": "Registration failed. Please contact your administrator.",
814                        "code": "invalid",
815                    }
816                ]
817            },
818        )
819        self.assertFalse(WebAuthnDevice.objects.filter(user=self.user).exists())
820
821    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
822    def test_register_mldsa(self):
823        """Test registration of an ML-DSA-44 (FIPS 204) credential"""
824        credential = SoftwareCredential(rp_id="localhost", origin="http://localhost:9000")
825        challenge = b"\x01" * 64
826        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
827        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
828        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = challenge
829        session = self.client.session
830        session[SESSION_KEY_PLAN] = plan
831        session.save()
832        response = self.client.post(
833            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
834            data={
835                "component": "ak-stage-authenticator-webauthn",
836                "response": credential.registration_response(challenge),
837            },
838            SERVER_NAME="localhost",
839            SERVER_PORT="9000",
840        )
841        self.assertEqual(response.status_code, 200)
842        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
843        device = WebAuthnDevice.objects.filter(user=self.user).first()
844        self.assertIsNotNone(device)
845        self.assertEqual(device.credential_id, bytes_to_base64url(credential.credential_id))
846        self.assertEqual(device.public_key, bytes_to_base64url(credential.cose_public_key))
847        self.assertIsNone(device.attestation_certificate_pem)
class TestAuthenticatorWebAuthnStage(authentik.flows.tests.APIFlowTestCase):
 37class TestAuthenticatorWebAuthnStage(APIFlowTestCase):
 38    """Test WebAuthn API"""
 39
 40    def setUp(self) -> None:
 41        self.stage = AuthenticatorWebAuthnStage.objects.create(
 42            name=generate_id(),
 43        )
 44        self.flow = create_test_flow()
 45        self.binding = FlowStageBinding.objects.create(
 46            target=self.flow,
 47            stage=self.stage,
 48            order=0,
 49        )
 50        self.user = create_test_admin_user()
 51
 52    def test_api_delete(self):
 53        """Test api delete"""
 54        self.client.force_login(self.user)
 55        dev = WebAuthnDevice.objects.create(user=self.user)
 56        response = self.client.delete(
 57            reverse("authentik_api:webauthndevice-detail", kwargs={"pk": dev.pk})
 58        )
 59        self.assertEqual(response.status_code, 204)
 60
 61    @skipIf(backend._fips_enabled, "The FIPS provider has no Ed25519 or ML-DSA")
 62    def test_registration_options(self):
 63        """Test registration options"""
 64        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
 65        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
 66        session = self.client.session
 67        session[SESSION_KEY_PLAN] = plan
 68        session.save()
 69
 70        response = self.client.get(
 71            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
 72        )
 73
 74        plan: FlowPlan = self.client.session[SESSION_KEY_PLAN]
 75
 76        self.assertEqual(response.status_code, 200)
 77        session = self.client.session
 78        self.assertStageResponse(
 79            response,
 80            self.flow,
 81            self.user,
 82            registration={
 83                "rp": {"name": "authentik", "id": "testserver"},
 84                "user": {
 85                    "id": bytes_to_base64url(self.user.uid.encode("utf-8")),
 86                    "name": self.user.username,
 87                    "displayName": self.user.name,
 88                },
 89                "challenge": bytes_to_base64url(plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE]),
 90                "pubKeyCredParams": [
 91                    {"type": "public-key", "alg": -8},
 92                    {"type": "public-key", "alg": -7},
 93                    {"type": "public-key", "alg": -257},
 94                    {"type": "public-key", "alg": -48},
 95                    {"type": "public-key", "alg": -49},
 96                    {"type": "public-key", "alg": -50},
 97                ],
 98                "timeout": 60000,
 99                "excludeCredentials": [],
100                "authenticatorSelection": {
101                    "residentKey": "preferred",
102                    "requireResidentKey": False,
103                    "userVerification": "preferred",
104                },
105                "attestation": "direct",
106            },
107        )
108
109    def test_register(self):
110        """Test registration"""
111        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
112        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
113        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
114            b"iHIX3AtkZZCxSYLxOhk80ZXI7RnAC0Pb4WTk9dEJ4eLJdzoh8jRmjKW2U9oE/CBn5n6Zj67BIIZvFL3lpiwJwg=="
115        )
116        session = self.client.session
117        session[SESSION_KEY_PLAN] = plan
118        session.save()
119        response = self.client.post(
120            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
121            data={
122                "component": "ak-stage-authenticator-webauthn",
123                "response": loads(load_fixture("fixtures/register.json")),
124            },
125            SERVER_NAME="localhost",
126            SERVER_PORT="9000",
127        )
128        self.assertEqual(response.status_code, 200)
129        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
130        device = WebAuthnDevice.objects.filter(user=self.user).first()
131        self.assertIsNotNone(device)
132        self.assertEqual(
133            device.credential_id, "f7wv8mP-poSxh-567eWxZntzCBDW8hWlvzf92QJkT--Y2oBRz4IEAZ6M2PI9_KEQ"
134        )
135        self.assertEqual(
136            device.attestation_certificate_fingerprint,
137            "3e:28:fc:df:45:19:bb:94:0a:0c:90:98:f2:08:72:53:2a:9e:e2:76:13:02:3e:69:61:4a:d9:90:49:80:3d:34",
138        )
139
140    def test_registration_options_exclude_credentials(self):
141        """Test that already registered credentials are excluded from registration options"""
142        device = WebAuthnDevice.objects.create(
143            user=self.user,
144            name=generate_id(),
145            credential_id=bytes_to_base64url(b"existing-credential"),
146            rp_id="testserver",
147        )
148        # Devices of other users, devices registered for a different RP, and unconfirmed devices
149        # must not leak into the exclusion list
150        WebAuthnDevice.objects.create(
151            user=create_test_user(),
152            name=generate_id(),
153            credential_id=bytes_to_base64url(b"other-users-credential"),
154            rp_id="testserver",
155        )
156        WebAuthnDevice.objects.create(
157            user=self.user,
158            name=generate_id(),
159            credential_id=bytes_to_base64url(b"other-rp-credential"),
160            rp_id="other.rp.example.com",
161        )
162        WebAuthnDevice.objects.create(
163            user=self.user,
164            name=generate_id(),
165            credential_id=bytes_to_base64url(b"unconfirmed-credential"),
166            rp_id="testserver",
167            confirmed=False,
168        )
169
170        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
171        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
172        session = self.client.session
173        session[SESSION_KEY_PLAN] = plan
174        session.save()
175
176        response = self.client.get(
177            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
178        )
179
180        self.assertEqual(response.status_code, 200)
181        self.assertEqual(
182            loads(response.content)["registration"]["excludeCredentials"],
183            [{"id": device.credential_id, "type": "public-key"}],
184        )
185
186    def test_register_removes_challenge(self):
187        """Test that the registration challenge is removed from the plan once answered"""
188        dummy_binding = FlowStageBinding.objects.create(
189            target=self.flow,
190            stage=DummyStage.objects.create(name=generate_id()),
191            order=1,
192        )
193        plan = FlowPlan(
194            flow_pk=self.flow.pk.hex,
195            bindings=[self.binding, dummy_binding],
196            markers=[StageMarker(), StageMarker()],
197        )
198        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
199        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
200            b"iHIX3AtkZZCxSYLxOhk80ZXI7RnAC0Pb4WTk9dEJ4eLJdzoh8jRmjKW2U9oE/CBn5n6Zj67BIIZvFL3lpiwJwg=="
201        )
202        session = self.client.session
203        session[SESSION_KEY_PLAN] = plan
204        session.save()
205        response = self.client.post(
206            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
207            data={
208                "component": "ak-stage-authenticator-webauthn",
209                "response": loads(load_fixture("fixtures/register.json")),
210            },
211            SERVER_NAME="localhost",
212            SERVER_PORT="9000",
213        )
214        self.assertEqual(response.status_code, 302)
215        self.assertTrue(WebAuthnDevice.objects.filter(user=self.user).exists())
216        plan: FlowPlan = self.client.session[SESSION_KEY_PLAN]
217        self.assertNotIn(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, plan.context)
218
219    def test_register_shared_attestation_certificate(self):
220        """Test that a device sharing an attestation certificate with an existing device of
221        another user can still be registered.
222
223        Attestation certificates are shared across entire manufacturing batches, so they must
224        never be treated as identifying an individual device."""
225        WebAuthnDevice.objects.create(
226            user=create_test_user(),
227            name=generate_id(),
228            credential_id=bytes_to_base64url(b"batch-sibling-credential"),
229            rp_id="localhost",
230            attestation_certificate_fingerprint=(
231                "3e:28:fc:df:45:19:bb:94:0a:0c:90:98:f2:08:72:53:"
232                "2a:9e:e2:76:13:02:3e:69:61:4a:d9:90:49:80:3d:34"
233            ),
234        )
235
236        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
237        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
238        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
239            b"iHIX3AtkZZCxSYLxOhk80ZXI7RnAC0Pb4WTk9dEJ4eLJdzoh8jRmjKW2U9oE/CBn5n6Zj67BIIZvFL3lpiwJwg=="
240        )
241        session = self.client.session
242        session[SESSION_KEY_PLAN] = plan
243        session.save()
244        response = self.client.post(
245            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
246            data={
247                "component": "ak-stage-authenticator-webauthn",
248                "response": loads(load_fixture("fixtures/register.json")),
249            },
250            SERVER_NAME="localhost",
251            SERVER_PORT="9000",
252        )
253        self.assertEqual(response.status_code, 200)
254        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
255        self.assertTrue(WebAuthnDevice.objects.filter(user=self.user).exists())
256
257    def _register_malformed_attestation_certificate(self):
258        """Register with a packed attestation whose certificate encodes explicit NULL parameters
259        for ecdsa-with-SHA256, which OpenSSL accepts but cryptography rejects with a ValueError"""
260        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
261        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
262        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
263            b"03Xodi54gKsfnP5I9VFfhaGXVVE2NUyZpBBXns/JI+x6V9RY2Tw2QmxRJkhh7174EkRazUntIwjMVY9bFG60Lw=="
264        )
265        session = self.client.session
266        session[SESSION_KEY_PLAN] = plan
267        session.save()
268        response = self.client.post(
269            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
270            data={
271                "component": "ak-stage-authenticator-webauthn",
272                "response": loads(
273                    load_fixture("fixtures/register_malformed_attestation_certificate.json")
274                ),
275            },
276            SERVER_NAME="localhost",
277            SERVER_PORT="9000",
278        )
279        self.assertEqual(response.status_code, 200)
280        return response
281
282    def test_register_malformed_attestation_certificate(self):
283        """Test registration with an attestation certificate that fails verification"""
284        response = self._register_malformed_attestation_certificate()
285        self.assertStageResponse(
286            response,
287            flow=self.flow,
288            component="ak-stage-authenticator-webauthn",
289            response_errors={
290                "response": [
291                    {
292                        "string": "Registration failed. Please contact your administrator.",
293                        "code": "invalid",
294                    }
295                ]
296            },
297        )
298        self.assertFalse(WebAuthnDevice.objects.filter(user=self.user).exists())
299
300    def test_register_verified_malformed_attestation_certificate(self):
301        """Test registration with an attestation certificate that only OpenSSL can parse,
302        like android-key attestation which verifies with OpenSSL"""
303        attestation_object = base64url_to_bytes(
304            loads(load_fixture("fixtures/register_malformed_attestation_certificate.json"))[
305                "response"
306            ]["attestationObject"]
307        )
308        registration = MagicMock(
309            attestation_object=attestation_object,
310            credential_id=b"credential",
311            credential_public_key=b"public-key",
312            sign_count=0,
313            aaguid="00000000-0000-0000-0000-000000000000",
314        )
315        with patch(
316            "authentik.stages.authenticator_webauthn.stage.verify_registration_response",
317            return_value=registration,
318        ):
319            response = self._register_malformed_attestation_certificate()
320        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
321        device = WebAuthnDevice.objects.get(user=self.user)
322        self.assertIsNone(device.attestation_certificate_pem)
323        self.assertIsNone(device.attestation_certificate_fingerprint)
324
325    def test_register_restricted_device_type_deny(self):
326        """Test registration with restricted devices (fail)"""
327        webauthn_mds_import.send(force=True)
328        self.stage.device_type_restrictions.set(
329            WebAuthnDeviceType.objects.filter(description="YubiKey 5 Series")
330        )
331
332        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
333        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
334        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
335            b"03Xodi54gKsfnP5I9VFfhaGXVVE2NUyZpBBXns/JI+x6V9RY2Tw2QmxRJkhh7174EkRazUntIwjMVY9bFG60Lw=="
336        )
337        session = self.client.session
338        session[SESSION_KEY_PLAN] = plan
339        session.save()
340        response = self.client.post(
341            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
342            data={
343                "component": "ak-stage-authenticator-webauthn",
344                "response": {
345                    "id": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
346                    "rawId": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
347                    "type": "public-key",
348                    "registrationClientExtensions": "{}",
349                    "response": {
350                        "clientDataJSON": (
351                            "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmd"
352                            "lIjoiMDNYb2RpNTRnS3NmblA1STlWRmZoYUdYVlZFMk5VeV"
353                            "pwQkJYbnNfSkkteDZWOVJZMlR3MlFteFJKa2hoNzE3NEVrU"
354                            "mF6VW50SXdqTVZZOWJGRzYwTHciLCJvcmlnaW4iOiJodHRw"
355                            "Oi8vbG9jYWxob3N0OjkwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2V9"
356                        ),
357                        "attestationObject": (
358                            "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YViYSZYN5Yg"
359                            "OjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2NdAAAAAPv8MA"
360                            "cVTk7MjAtuAgVX170AFJKp5q1S5wxvjsLEjR5IoWGWjc-bp"
361                            "QECAyYgASFYIKtcZHPumH37XHs0IM1v3pUBRIqHVV_SE-Lq"
362                            "2zpJAOVXIlgg74Fg_WdB0kuLYqCKbxogkEPaVtR_iR3IyQFIJAXBzds"
363                        ),
364                    },
365                },
366            },
367            SERVER_NAME="localhost",
368            SERVER_PORT="9000",
369        )
370        self.assertEqual(response.status_code, 200)
371        self.assertStageResponse(
372            response,
373            flow=self.flow,
374            component="ak-stage-authenticator-webauthn",
375            response_errors={
376                "response": [
377                    {
378                        "string": (
379                            "Invalid device type. Contact your authentik administrator for help."
380                        ),
381                        "code": "invalid",
382                    }
383                ]
384            },
385        )
386        self.assertFalse(WebAuthnDevice.objects.filter(user=self.user).exists())
387
388    def test_register_restricted_device_type_allow(self):
389        """Test registration with restricted devices (allow)"""
390        webauthn_mds_import.send(force=True)
391        self.stage.device_type_restrictions.set(
392            WebAuthnDeviceType.objects.filter(description="iCloud Keychain")
393        )
394
395        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
396        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
397        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
398            b"03Xodi54gKsfnP5I9VFfhaGXVVE2NUyZpBBXns/JI+x6V9RY2Tw2QmxRJkhh7174EkRazUntIwjMVY9bFG60Lw=="
399        )
400        session = self.client.session
401        session[SESSION_KEY_PLAN] = plan
402        session.save()
403        response = self.client.post(
404            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
405            data={
406                "component": "ak-stage-authenticator-webauthn",
407                "response": {
408                    "id": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
409                    "rawId": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
410                    "type": "public-key",
411                    "registrationClientExtensions": "{}",
412                    "response": {
413                        "clientDataJSON": (
414                            "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmd"
415                            "lIjoiMDNYb2RpNTRnS3NmblA1STlWRmZoYUdYVlZFMk5VeV"
416                            "pwQkJYbnNfSkkteDZWOVJZMlR3MlFteFJKa2hoNzE3NEVrU"
417                            "mF6VW50SXdqTVZZOWJGRzYwTHciLCJvcmlnaW4iOiJodHRw"
418                            "Oi8vbG9jYWxob3N0OjkwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2V9"
419                        ),
420                        "attestationObject": (
421                            "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YViYSZYN5Yg"
422                            "OjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2NdAAAAAPv8MA"
423                            "cVTk7MjAtuAgVX170AFJKp5q1S5wxvjsLEjR5IoWGWjc-bp"
424                            "QECAyYgASFYIKtcZHPumH37XHs0IM1v3pUBRIqHVV_SE-Lq"
425                            "2zpJAOVXIlgg74Fg_WdB0kuLYqCKbxogkEPaVtR_iR3IyQFIJAXBzds"
426                        ),
427                    },
428                },
429            },
430            SERVER_NAME="localhost",
431            SERVER_PORT="9000",
432        )
433        self.assertEqual(response.status_code, 200)
434        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
435        self.assertTrue(WebAuthnDevice.objects.filter(user=self.user).exists())
436
437    def test_register_restricted_device_type_allow_unknown(self):
438        """Test registration with restricted devices (allow, unknown device type)"""
439        webauthn_mds_import.send(force=True)
440        WebAuthnDeviceType.objects.filter(aaguid="fbfc3007-154e-4ecc-8c0b-6e020557d7bd").delete()
441        self.stage.device_type_restrictions.set(
442            WebAuthnDeviceType.objects.filter(aaguid=UNKNOWN_DEVICE_TYPE_AAGUID)
443        )
444
445        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
446        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
447        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
448            b"03Xodi54gKsfnP5I9VFfhaGXVVE2NUyZpBBXns/JI+x6V9RY2Tw2QmxRJkhh7174EkRazUntIwjMVY9bFG60Lw=="
449        )
450        session = self.client.session
451        session[SESSION_KEY_PLAN] = plan
452        session.save()
453        response = self.client.post(
454            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
455            data={
456                "component": "ak-stage-authenticator-webauthn",
457                "response": {
458                    "id": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
459                    "rawId": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
460                    "type": "public-key",
461                    "registrationClientExtensions": "{}",
462                    "response": {
463                        "clientDataJSON": (
464                            "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmd"
465                            "lIjoiMDNYb2RpNTRnS3NmblA1STlWRmZoYUdYVlZFMk5VeV"
466                            "pwQkJYbnNfSkkteDZWOVJZMlR3MlFteFJKa2hoNzE3NEVrU"
467                            "mF6VW50SXdqTVZZOWJGRzYwTHciLCJvcmlnaW4iOiJodHRw"
468                            "Oi8vbG9jYWxob3N0OjkwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2V9"
469                        ),
470                        "attestationObject": (
471                            "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YViYSZYN5Yg"
472                            "OjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2NdAAAAAPv8MA"
473                            "cVTk7MjAtuAgVX170AFJKp5q1S5wxvjsLEjR5IoWGWjc-bp"
474                            "QECAyYgASFYIKtcZHPumH37XHs0IM1v3pUBRIqHVV_SE-Lq"
475                            "2zpJAOVXIlgg74Fg_WdB0kuLYqCKbxogkEPaVtR_iR3IyQFIJAXBzds"
476                        ),
477                    },
478                },
479            },
480            SERVER_NAME="localhost",
481            SERVER_PORT="9000",
482        )
483        self.assertEqual(response.status_code, 200)
484        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
485        self.assertTrue(WebAuthnDevice.objects.filter(user=self.user).exists())
486
487    def test_registration_options_with_hints(self):
488        """Test that hints are included in registration options"""
489        self.stage.hints = [WebAuthnHint.CLIENT_DEVICE, WebAuthnHint.SECURITY_KEY]
490        self.stage.save()
491
492        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
493        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
494        session = self.client.session
495        session[SESSION_KEY_PLAN] = plan
496        session.save()
497
498        response = self.client.get(
499            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
500        )
501        self.assertEqual(response.status_code, 200)
502        registration = response.json()["registration"]
503        self.assertEqual(registration["hints"], ["client-device", "security-key"])
504
505    def test_registration_options_hints_empty(self):
506        """Test that no hints key is present when hints are empty"""
507        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
508        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
509        session = self.client.session
510        session[SESSION_KEY_PLAN] = plan
511        session.save()
512
513        response = self.client.get(
514            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
515        )
516        self.assertEqual(response.status_code, 200)
517        registration = response.json()["registration"]
518        self.assertNotIn("hints", registration)
519
520    def test_registration_options_hints_infer_attachment_cross_platform(self):
521        """Test that authenticatorAttachment is auto-inferred as cross-platform
522        from security-key/hybrid hints for backwards compatibility"""
523        self.stage.hints = [WebAuthnHint.SECURITY_KEY]
524        self.stage.authenticator_attachment = None
525        self.stage.save()
526
527        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
528        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
529        session = self.client.session
530        session[SESSION_KEY_PLAN] = plan
531        session.save()
532
533        response = self.client.get(
534            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
535        )
536        self.assertEqual(response.status_code, 200)
537        registration = response.json()["registration"]
538        self.assertEqual(
539            registration["authenticatorSelection"]["authenticatorAttachment"], "cross-platform"
540        )
541
542    def test_registration_options_hints_infer_attachment_platform(self):
543        """Test that authenticatorAttachment is auto-inferred as platform
544        from client-device hint for backwards compatibility"""
545        self.stage.hints = [WebAuthnHint.CLIENT_DEVICE]
546        self.stage.authenticator_attachment = None
547        self.stage.save()
548
549        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
550        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
551        session = self.client.session
552        session[SESSION_KEY_PLAN] = plan
553        session.save()
554
555        response = self.client.get(
556            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
557        )
558        self.assertEqual(response.status_code, 200)
559        registration = response.json()["registration"]
560        self.assertEqual(
561            registration["authenticatorSelection"]["authenticatorAttachment"], "platform"
562        )
563
564    def test_registration_options_hints_no_infer_when_attachment_set(self):
565        """Test that authenticatorAttachment is NOT overridden when explicitly set"""
566        self.stage.hints = [WebAuthnHint.SECURITY_KEY]
567        self.stage.authenticator_attachment = "platform"
568        self.stage.save()
569
570        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
571        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
572        session = self.client.session
573        session[SESSION_KEY_PLAN] = plan
574        session.save()
575
576        response = self.client.get(
577            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
578        )
579        self.assertEqual(response.status_code, 200)
580        registration = response.json()["registration"]
581        self.assertEqual(
582            registration["authenticatorSelection"]["authenticatorAttachment"], "platform"
583        )
584
585    def test_registration_options_hints_no_infer_mixed(self):
586        """Test that authenticatorAttachment is NOT inferred when hints are mixed"""
587        self.stage.hints = [WebAuthnHint.SECURITY_KEY, WebAuthnHint.CLIENT_DEVICE]
588        self.stage.authenticator_attachment = None
589        self.stage.save()
590
591        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
592        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
593        session = self.client.session
594        session[SESSION_KEY_PLAN] = plan
595        session.save()
596
597        response = self.client.get(
598            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
599        )
600        self.assertEqual(response.status_code, 200)
601        registration = response.json()["registration"]
602        self.assertNotIn("authenticatorAttachment", registration["authenticatorSelection"])
603
604    def test_registration_options_hints_order_preserved(self):
605        """Test that hint order is preserved (first hint = highest priority)"""
606        self.stage.hints = [
607            WebAuthnHint.HYBRID,
608            WebAuthnHint.CLIENT_DEVICE,
609            WebAuthnHint.SECURITY_KEY,
610        ]
611        self.stage.save()
612
613        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
614        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
615        session = self.client.session
616        session[SESSION_KEY_PLAN] = plan
617        session.save()
618
619        response = self.client.get(
620            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
621        )
622        self.assertEqual(response.status_code, 200)
623        registration = response.json()["registration"]
624        self.assertEqual(registration["hints"], ["hybrid", "client-device", "security-key"])
625
626    def test_register_max_retries(self):
627        """Test registration (exceeding max retries)"""
628        self.stage.max_attempts = 2
629        self.stage.save()
630
631        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
632        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
633        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
634            b"03Xodi54gKsfnP5I9VFfhaGXVVE2NUyZpBBXns/JI+x6V9RY2Tw2QmxRJkhh7174EkRazUntIwjMVY9bFG60Lw=="
635        )
636        session = self.client.session
637        session[SESSION_KEY_PLAN] = plan
638        session.save()
639
640        # first failed request
641        response = self.client.post(
642            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
643            data={
644                "component": "ak-stage-authenticator-webauthn",
645                "response": {
646                    "id": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
647                    "rawId": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
648                    "type": "public-key",
649                    "registrationClientExtensions": "{}",
650                    "response": {
651                        "clientDataJSON": (
652                            "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmd"
653                            "lIjoiMDNYb2RpNTRnS3NmblA1STlWRmZoYUdYVlZFMk5VeV"
654                            "pwQkJYbnNfSkkteDZWOVJZMlR3MlFteFJKa2hoNzE3NEVrU"
655                            "mF6VW50SXdqTVZZOWJGRzYwTHciLCJvcmlnaW4iOiJodHRw"
656                            "Oi8vbG9jYWxob3N0OjkwMDAiLCJjcm9zc09yaWdpbiI6ZmF"
657                        ),
658                        "attestationObject": (
659                            "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YViYSZYN5Yg"
660                            "OjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2NdAAAAAPv8MA"
661                            "cVTk7MjAtuAgVX170AFJKp5q1S5wxvjsLEjR5IoWGWjc-bp"
662                            "QECAyYgASFYIKtcZHPumH37XHs0IM1v3pUBRIqHVV_SE-Lq"
663                            "2zpJAOVXIlgg74Fg_WdB0kuLYqCKbxogkEPaVtR_iR3IyQFIJAXBzds"
664                        ),
665                    },
666                },
667            },
668            SERVER_NAME="localhost",
669            SERVER_PORT="9000",
670        )
671        self.assertEqual(response.status_code, 200)
672        self.assertStageResponse(
673            response,
674            flow=self.flow,
675            component="ak-stage-authenticator-webauthn",
676            response_errors={
677                "response": [
678                    {
679                        "string": "Registration failed. Please contact your administrator.",
680                        "code": "invalid",
681                    }
682                ]
683            },
684        )
685        self.assertFalse(WebAuthnDevice.objects.filter(user=self.user).exists())
686
687        # Second failed request
688        response = self.client.post(
689            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
690            data={
691                "component": "ak-stage-authenticator-webauthn",
692                "response": {
693                    "id": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
694                    "rawId": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
695                    "type": "public-key",
696                    "registrationClientExtensions": "{}",
697                    "response": {
698                        "clientDataJSON": (
699                            "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmd"
700                            "lIjoiMDNYb2RpNTRnS3NmblA1STlWRmZoYUdYVlZFMk5VeV"
701                            "pwQkJYbnNfSkkteDZWOVJZMlR3MlFteFJKa2hoNzE3NEVrU"
702                            "mF6VW50SXdqTVZZOWJGRzYwTHciLCJvcmlnaW4iOiJodHRw"
703                            "Oi8vbG9jYWxob3N0OjkwMDAiLCJjcm9zc09yaWdpbiI6ZmF"
704                        ),
705                        "attestationObject": (
706                            "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YViYSZYN5Yg"
707                            "OjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2NdAAAAAPv8MA"
708                            "cVTk7MjAtuAgVX170AFJKp5q1S5wxvjsLEjR5IoWGWjc-bp"
709                            "QECAyYgASFYIKtcZHPumH37XHs0IM1v3pUBRIqHVV_SE-Lq"
710                            "2zpJAOVXIlgg74Fg_WdB0kuLYqCKbxogkEPaVtR_iR3IyQFIJAXBzds"
711                        ),
712                    },
713                },
714            },
715            SERVER_NAME="localhost",
716            SERVER_PORT="9000",
717        )
718        self.assertEqual(response.status_code, 200)
719        self.assertStageResponse(
720            response,
721            flow=self.flow,
722            component="ak-stage-access-denied",
723            error_message=(
724                "Exceeded maximum attempts. Contact your authentik administrator for help."
725            ),
726        )
727        self.assertFalse(WebAuthnDevice.objects.filter(user=self.user).exists())
728
729    @skipIf(backend._fips_enabled, "The FIPS provider has no Ed25519 or ML-DSA")
730    def test_registration_options_algorithms(self):
731        """Registration offers the classical algorithms first and the ML-DSA sets last"""
732        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
733        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
734        session = self.client.session
735        session[SESSION_KEY_PLAN] = plan
736        session.save()
737        response = self.client.get(
738            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
739        )
740        self.assertEqual(response.status_code, 200)
741        params = response.json()["registration"]["pubKeyCredParams"]
742        self.assertEqual([p["alg"] for p in params], [int(alg) for alg in PREFERRED_PUB_KEY_ALGS])
743        self.assertEqual([p["alg"] for p in params][-3:], [-48, -49, -50])
744
745    def _enable_fips(self):
746        """Pretend the OpenSSL FIPS provider is active, which has neither Ed25519 nor ML-DSA"""
747        patcher = patch(
748            "authentik.stages.authenticator_webauthn.algorithms.backend._fips_enabled", True
749        )
750        patcher.start()
751        self.addCleanup(patcher.stop)
752
753    def test_registration_options_algorithms_fips(self):
754        """With FIPS enabled only the algorithms the FIPS provider can verify are offered"""
755        self._enable_fips()
756        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
757        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
758        session = self.client.session
759        session[SESSION_KEY_PLAN] = plan
760        session.save()
761        response = self.client.get(
762            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
763        )
764        self.assertEqual(response.status_code, 200)
765        params = response.json()["registration"]["pubKeyCredParams"]
766        self.assertEqual([p["alg"] for p in params], [-7, -257])
767
768    def _register_software_credential(self, credential: SoftwareCredential):
769        challenge = b"\x01" * 64
770        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
771        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
772        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = challenge
773        session = self.client.session
774        session[SESSION_KEY_PLAN] = plan
775        session.save()
776        return self.client.post(
777            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
778            data={
779                "component": "ak-stage-authenticator-webauthn",
780                "response": credential.registration_response(challenge),
781            },
782            SERVER_NAME="localhost",
783            SERVER_PORT="9000",
784        )
785
786    @skipIf(backend._fips_enabled, "The FIPS provider has no Ed25519")
787    def test_register_eddsa(self):
788        """Test registration of an Ed25519 credential"""
789        credential = SoftwareCredential(
790            rp_id="localhost", origin="http://localhost:9000", alg=COSEAlgorithmIdentifier.EDDSA
791        )
792        response = self._register_software_credential(credential)
793        self.assertEqual(response.status_code, 200)
794        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
795        device = WebAuthnDevice.objects.get(user=self.user)
796        self.assertEqual(device.public_key, bytes_to_base64url(credential.cose_public_key))
797
798    @skipIf(backend._fips_enabled, "The FIPS provider has no Ed25519")
799    def test_register_unavailable_algorithm_fips(self):
800        """An authenticator that ignores the offered algorithms and creates a credential the
801        FIPS provider cannot verify is rejected at registration, not at first login"""
802        self._enable_fips()
803        credential = SoftwareCredential(
804            rp_id="localhost", origin="http://localhost:9000", alg=COSEAlgorithmIdentifier.EDDSA
805        )
806        response = self._register_software_credential(credential)
807        self.assertStageResponse(
808            response,
809            flow=self.flow,
810            component="ak-stage-authenticator-webauthn",
811            response_errors={
812                "response": [
813                    {
814                        "string": "Registration failed. Please contact your administrator.",
815                        "code": "invalid",
816                    }
817                ]
818            },
819        )
820        self.assertFalse(WebAuthnDevice.objects.filter(user=self.user).exists())
821
822    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
823    def test_register_mldsa(self):
824        """Test registration of an ML-DSA-44 (FIPS 204) credential"""
825        credential = SoftwareCredential(rp_id="localhost", origin="http://localhost:9000")
826        challenge = b"\x01" * 64
827        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
828        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
829        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = challenge
830        session = self.client.session
831        session[SESSION_KEY_PLAN] = plan
832        session.save()
833        response = self.client.post(
834            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
835            data={
836                "component": "ak-stage-authenticator-webauthn",
837                "response": credential.registration_response(challenge),
838            },
839            SERVER_NAME="localhost",
840            SERVER_PORT="9000",
841        )
842        self.assertEqual(response.status_code, 200)
843        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
844        device = WebAuthnDevice.objects.filter(user=self.user).first()
845        self.assertIsNotNone(device)
846        self.assertEqual(device.credential_id, bytes_to_base64url(credential.credential_id))
847        self.assertEqual(device.public_key, bytes_to_base64url(credential.cose_public_key))
848        self.assertIsNone(device.attestation_certificate_pem)

Test WebAuthn API

def setUp(self) -> None:
40    def setUp(self) -> None:
41        self.stage = AuthenticatorWebAuthnStage.objects.create(
42            name=generate_id(),
43        )
44        self.flow = create_test_flow()
45        self.binding = FlowStageBinding.objects.create(
46            target=self.flow,
47            stage=self.stage,
48            order=0,
49        )
50        self.user = create_test_admin_user()

Hook method for setting up the test fixture before exercising it.

def test_api_delete(self):
52    def test_api_delete(self):
53        """Test api delete"""
54        self.client.force_login(self.user)
55        dev = WebAuthnDevice.objects.create(user=self.user)
56        response = self.client.delete(
57            reverse("authentik_api:webauthndevice-detail", kwargs={"pk": dev.pk})
58        )
59        self.assertEqual(response.status_code, 204)

Test api delete

@skipIf(backend._fips_enabled, 'The FIPS provider has no Ed25519 or ML-DSA')
def test_registration_options(self):
 61    @skipIf(backend._fips_enabled, "The FIPS provider has no Ed25519 or ML-DSA")
 62    def test_registration_options(self):
 63        """Test registration options"""
 64        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
 65        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
 66        session = self.client.session
 67        session[SESSION_KEY_PLAN] = plan
 68        session.save()
 69
 70        response = self.client.get(
 71            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
 72        )
 73
 74        plan: FlowPlan = self.client.session[SESSION_KEY_PLAN]
 75
 76        self.assertEqual(response.status_code, 200)
 77        session = self.client.session
 78        self.assertStageResponse(
 79            response,
 80            self.flow,
 81            self.user,
 82            registration={
 83                "rp": {"name": "authentik", "id": "testserver"},
 84                "user": {
 85                    "id": bytes_to_base64url(self.user.uid.encode("utf-8")),
 86                    "name": self.user.username,
 87                    "displayName": self.user.name,
 88                },
 89                "challenge": bytes_to_base64url(plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE]),
 90                "pubKeyCredParams": [
 91                    {"type": "public-key", "alg": -8},
 92                    {"type": "public-key", "alg": -7},
 93                    {"type": "public-key", "alg": -257},
 94                    {"type": "public-key", "alg": -48},
 95                    {"type": "public-key", "alg": -49},
 96                    {"type": "public-key", "alg": -50},
 97                ],
 98                "timeout": 60000,
 99                "excludeCredentials": [],
100                "authenticatorSelection": {
101                    "residentKey": "preferred",
102                    "requireResidentKey": False,
103                    "userVerification": "preferred",
104                },
105                "attestation": "direct",
106            },
107        )

Test registration options

def test_register(self):
109    def test_register(self):
110        """Test registration"""
111        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
112        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
113        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
114            b"iHIX3AtkZZCxSYLxOhk80ZXI7RnAC0Pb4WTk9dEJ4eLJdzoh8jRmjKW2U9oE/CBn5n6Zj67BIIZvFL3lpiwJwg=="
115        )
116        session = self.client.session
117        session[SESSION_KEY_PLAN] = plan
118        session.save()
119        response = self.client.post(
120            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
121            data={
122                "component": "ak-stage-authenticator-webauthn",
123                "response": loads(load_fixture("fixtures/register.json")),
124            },
125            SERVER_NAME="localhost",
126            SERVER_PORT="9000",
127        )
128        self.assertEqual(response.status_code, 200)
129        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
130        device = WebAuthnDevice.objects.filter(user=self.user).first()
131        self.assertIsNotNone(device)
132        self.assertEqual(
133            device.credential_id, "f7wv8mP-poSxh-567eWxZntzCBDW8hWlvzf92QJkT--Y2oBRz4IEAZ6M2PI9_KEQ"
134        )
135        self.assertEqual(
136            device.attestation_certificate_fingerprint,
137            "3e:28:fc:df:45:19:bb:94:0a:0c:90:98:f2:08:72:53:2a:9e:e2:76:13:02:3e:69:61:4a:d9:90:49:80:3d:34",
138        )

Test registration

def test_registration_options_exclude_credentials(self):
140    def test_registration_options_exclude_credentials(self):
141        """Test that already registered credentials are excluded from registration options"""
142        device = WebAuthnDevice.objects.create(
143            user=self.user,
144            name=generate_id(),
145            credential_id=bytes_to_base64url(b"existing-credential"),
146            rp_id="testserver",
147        )
148        # Devices of other users, devices registered for a different RP, and unconfirmed devices
149        # must not leak into the exclusion list
150        WebAuthnDevice.objects.create(
151            user=create_test_user(),
152            name=generate_id(),
153            credential_id=bytes_to_base64url(b"other-users-credential"),
154            rp_id="testserver",
155        )
156        WebAuthnDevice.objects.create(
157            user=self.user,
158            name=generate_id(),
159            credential_id=bytes_to_base64url(b"other-rp-credential"),
160            rp_id="other.rp.example.com",
161        )
162        WebAuthnDevice.objects.create(
163            user=self.user,
164            name=generate_id(),
165            credential_id=bytes_to_base64url(b"unconfirmed-credential"),
166            rp_id="testserver",
167            confirmed=False,
168        )
169
170        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
171        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
172        session = self.client.session
173        session[SESSION_KEY_PLAN] = plan
174        session.save()
175
176        response = self.client.get(
177            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
178        )
179
180        self.assertEqual(response.status_code, 200)
181        self.assertEqual(
182            loads(response.content)["registration"]["excludeCredentials"],
183            [{"id": device.credential_id, "type": "public-key"}],
184        )

Test that already registered credentials are excluded from registration options

def test_register_removes_challenge(self):
186    def test_register_removes_challenge(self):
187        """Test that the registration challenge is removed from the plan once answered"""
188        dummy_binding = FlowStageBinding.objects.create(
189            target=self.flow,
190            stage=DummyStage.objects.create(name=generate_id()),
191            order=1,
192        )
193        plan = FlowPlan(
194            flow_pk=self.flow.pk.hex,
195            bindings=[self.binding, dummy_binding],
196            markers=[StageMarker(), StageMarker()],
197        )
198        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
199        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
200            b"iHIX3AtkZZCxSYLxOhk80ZXI7RnAC0Pb4WTk9dEJ4eLJdzoh8jRmjKW2U9oE/CBn5n6Zj67BIIZvFL3lpiwJwg=="
201        )
202        session = self.client.session
203        session[SESSION_KEY_PLAN] = plan
204        session.save()
205        response = self.client.post(
206            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
207            data={
208                "component": "ak-stage-authenticator-webauthn",
209                "response": loads(load_fixture("fixtures/register.json")),
210            },
211            SERVER_NAME="localhost",
212            SERVER_PORT="9000",
213        )
214        self.assertEqual(response.status_code, 302)
215        self.assertTrue(WebAuthnDevice.objects.filter(user=self.user).exists())
216        plan: FlowPlan = self.client.session[SESSION_KEY_PLAN]
217        self.assertNotIn(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, plan.context)

Test that the registration challenge is removed from the plan once answered

def test_register_shared_attestation_certificate(self):
219    def test_register_shared_attestation_certificate(self):
220        """Test that a device sharing an attestation certificate with an existing device of
221        another user can still be registered.
222
223        Attestation certificates are shared across entire manufacturing batches, so they must
224        never be treated as identifying an individual device."""
225        WebAuthnDevice.objects.create(
226            user=create_test_user(),
227            name=generate_id(),
228            credential_id=bytes_to_base64url(b"batch-sibling-credential"),
229            rp_id="localhost",
230            attestation_certificate_fingerprint=(
231                "3e:28:fc:df:45:19:bb:94:0a:0c:90:98:f2:08:72:53:"
232                "2a:9e:e2:76:13:02:3e:69:61:4a:d9:90:49:80:3d:34"
233            ),
234        )
235
236        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
237        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
238        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
239            b"iHIX3AtkZZCxSYLxOhk80ZXI7RnAC0Pb4WTk9dEJ4eLJdzoh8jRmjKW2U9oE/CBn5n6Zj67BIIZvFL3lpiwJwg=="
240        )
241        session = self.client.session
242        session[SESSION_KEY_PLAN] = plan
243        session.save()
244        response = self.client.post(
245            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
246            data={
247                "component": "ak-stage-authenticator-webauthn",
248                "response": loads(load_fixture("fixtures/register.json")),
249            },
250            SERVER_NAME="localhost",
251            SERVER_PORT="9000",
252        )
253        self.assertEqual(response.status_code, 200)
254        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
255        self.assertTrue(WebAuthnDevice.objects.filter(user=self.user).exists())

Test that a device sharing an attestation certificate with an existing device of another user can still be registered.

Attestation certificates are shared across entire manufacturing batches, so they must never be treated as identifying an individual device.

def test_register_malformed_attestation_certificate(self):
282    def test_register_malformed_attestation_certificate(self):
283        """Test registration with an attestation certificate that fails verification"""
284        response = self._register_malformed_attestation_certificate()
285        self.assertStageResponse(
286            response,
287            flow=self.flow,
288            component="ak-stage-authenticator-webauthn",
289            response_errors={
290                "response": [
291                    {
292                        "string": "Registration failed. Please contact your administrator.",
293                        "code": "invalid",
294                    }
295                ]
296            },
297        )
298        self.assertFalse(WebAuthnDevice.objects.filter(user=self.user).exists())

Test registration with an attestation certificate that fails verification

def test_register_verified_malformed_attestation_certificate(self):
300    def test_register_verified_malformed_attestation_certificate(self):
301        """Test registration with an attestation certificate that only OpenSSL can parse,
302        like android-key attestation which verifies with OpenSSL"""
303        attestation_object = base64url_to_bytes(
304            loads(load_fixture("fixtures/register_malformed_attestation_certificate.json"))[
305                "response"
306            ]["attestationObject"]
307        )
308        registration = MagicMock(
309            attestation_object=attestation_object,
310            credential_id=b"credential",
311            credential_public_key=b"public-key",
312            sign_count=0,
313            aaguid="00000000-0000-0000-0000-000000000000",
314        )
315        with patch(
316            "authentik.stages.authenticator_webauthn.stage.verify_registration_response",
317            return_value=registration,
318        ):
319            response = self._register_malformed_attestation_certificate()
320        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
321        device = WebAuthnDevice.objects.get(user=self.user)
322        self.assertIsNone(device.attestation_certificate_pem)
323        self.assertIsNone(device.attestation_certificate_fingerprint)

Test registration with an attestation certificate that only OpenSSL can parse, like android-key attestation which verifies with OpenSSL

def test_register_restricted_device_type_deny(self):
325    def test_register_restricted_device_type_deny(self):
326        """Test registration with restricted devices (fail)"""
327        webauthn_mds_import.send(force=True)
328        self.stage.device_type_restrictions.set(
329            WebAuthnDeviceType.objects.filter(description="YubiKey 5 Series")
330        )
331
332        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
333        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
334        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
335            b"03Xodi54gKsfnP5I9VFfhaGXVVE2NUyZpBBXns/JI+x6V9RY2Tw2QmxRJkhh7174EkRazUntIwjMVY9bFG60Lw=="
336        )
337        session = self.client.session
338        session[SESSION_KEY_PLAN] = plan
339        session.save()
340        response = self.client.post(
341            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
342            data={
343                "component": "ak-stage-authenticator-webauthn",
344                "response": {
345                    "id": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
346                    "rawId": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
347                    "type": "public-key",
348                    "registrationClientExtensions": "{}",
349                    "response": {
350                        "clientDataJSON": (
351                            "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmd"
352                            "lIjoiMDNYb2RpNTRnS3NmblA1STlWRmZoYUdYVlZFMk5VeV"
353                            "pwQkJYbnNfSkkteDZWOVJZMlR3MlFteFJKa2hoNzE3NEVrU"
354                            "mF6VW50SXdqTVZZOWJGRzYwTHciLCJvcmlnaW4iOiJodHRw"
355                            "Oi8vbG9jYWxob3N0OjkwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2V9"
356                        ),
357                        "attestationObject": (
358                            "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YViYSZYN5Yg"
359                            "OjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2NdAAAAAPv8MA"
360                            "cVTk7MjAtuAgVX170AFJKp5q1S5wxvjsLEjR5IoWGWjc-bp"
361                            "QECAyYgASFYIKtcZHPumH37XHs0IM1v3pUBRIqHVV_SE-Lq"
362                            "2zpJAOVXIlgg74Fg_WdB0kuLYqCKbxogkEPaVtR_iR3IyQFIJAXBzds"
363                        ),
364                    },
365                },
366            },
367            SERVER_NAME="localhost",
368            SERVER_PORT="9000",
369        )
370        self.assertEqual(response.status_code, 200)
371        self.assertStageResponse(
372            response,
373            flow=self.flow,
374            component="ak-stage-authenticator-webauthn",
375            response_errors={
376                "response": [
377                    {
378                        "string": (
379                            "Invalid device type. Contact your authentik administrator for help."
380                        ),
381                        "code": "invalid",
382                    }
383                ]
384            },
385        )
386        self.assertFalse(WebAuthnDevice.objects.filter(user=self.user).exists())

Test registration with restricted devices (fail)

def test_register_restricted_device_type_allow(self):
388    def test_register_restricted_device_type_allow(self):
389        """Test registration with restricted devices (allow)"""
390        webauthn_mds_import.send(force=True)
391        self.stage.device_type_restrictions.set(
392            WebAuthnDeviceType.objects.filter(description="iCloud Keychain")
393        )
394
395        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
396        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
397        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
398            b"03Xodi54gKsfnP5I9VFfhaGXVVE2NUyZpBBXns/JI+x6V9RY2Tw2QmxRJkhh7174EkRazUntIwjMVY9bFG60Lw=="
399        )
400        session = self.client.session
401        session[SESSION_KEY_PLAN] = plan
402        session.save()
403        response = self.client.post(
404            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
405            data={
406                "component": "ak-stage-authenticator-webauthn",
407                "response": {
408                    "id": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
409                    "rawId": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
410                    "type": "public-key",
411                    "registrationClientExtensions": "{}",
412                    "response": {
413                        "clientDataJSON": (
414                            "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmd"
415                            "lIjoiMDNYb2RpNTRnS3NmblA1STlWRmZoYUdYVlZFMk5VeV"
416                            "pwQkJYbnNfSkkteDZWOVJZMlR3MlFteFJKa2hoNzE3NEVrU"
417                            "mF6VW50SXdqTVZZOWJGRzYwTHciLCJvcmlnaW4iOiJodHRw"
418                            "Oi8vbG9jYWxob3N0OjkwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2V9"
419                        ),
420                        "attestationObject": (
421                            "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YViYSZYN5Yg"
422                            "OjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2NdAAAAAPv8MA"
423                            "cVTk7MjAtuAgVX170AFJKp5q1S5wxvjsLEjR5IoWGWjc-bp"
424                            "QECAyYgASFYIKtcZHPumH37XHs0IM1v3pUBRIqHVV_SE-Lq"
425                            "2zpJAOVXIlgg74Fg_WdB0kuLYqCKbxogkEPaVtR_iR3IyQFIJAXBzds"
426                        ),
427                    },
428                },
429            },
430            SERVER_NAME="localhost",
431            SERVER_PORT="9000",
432        )
433        self.assertEqual(response.status_code, 200)
434        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
435        self.assertTrue(WebAuthnDevice.objects.filter(user=self.user).exists())

Test registration with restricted devices (allow)

def test_register_restricted_device_type_allow_unknown(self):
437    def test_register_restricted_device_type_allow_unknown(self):
438        """Test registration with restricted devices (allow, unknown device type)"""
439        webauthn_mds_import.send(force=True)
440        WebAuthnDeviceType.objects.filter(aaguid="fbfc3007-154e-4ecc-8c0b-6e020557d7bd").delete()
441        self.stage.device_type_restrictions.set(
442            WebAuthnDeviceType.objects.filter(aaguid=UNKNOWN_DEVICE_TYPE_AAGUID)
443        )
444
445        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
446        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
447        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
448            b"03Xodi54gKsfnP5I9VFfhaGXVVE2NUyZpBBXns/JI+x6V9RY2Tw2QmxRJkhh7174EkRazUntIwjMVY9bFG60Lw=="
449        )
450        session = self.client.session
451        session[SESSION_KEY_PLAN] = plan
452        session.save()
453        response = self.client.post(
454            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
455            data={
456                "component": "ak-stage-authenticator-webauthn",
457                "response": {
458                    "id": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
459                    "rawId": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
460                    "type": "public-key",
461                    "registrationClientExtensions": "{}",
462                    "response": {
463                        "clientDataJSON": (
464                            "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmd"
465                            "lIjoiMDNYb2RpNTRnS3NmblA1STlWRmZoYUdYVlZFMk5VeV"
466                            "pwQkJYbnNfSkkteDZWOVJZMlR3MlFteFJKa2hoNzE3NEVrU"
467                            "mF6VW50SXdqTVZZOWJGRzYwTHciLCJvcmlnaW4iOiJodHRw"
468                            "Oi8vbG9jYWxob3N0OjkwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2V9"
469                        ),
470                        "attestationObject": (
471                            "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YViYSZYN5Yg"
472                            "OjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2NdAAAAAPv8MA"
473                            "cVTk7MjAtuAgVX170AFJKp5q1S5wxvjsLEjR5IoWGWjc-bp"
474                            "QECAyYgASFYIKtcZHPumH37XHs0IM1v3pUBRIqHVV_SE-Lq"
475                            "2zpJAOVXIlgg74Fg_WdB0kuLYqCKbxogkEPaVtR_iR3IyQFIJAXBzds"
476                        ),
477                    },
478                },
479            },
480            SERVER_NAME="localhost",
481            SERVER_PORT="9000",
482        )
483        self.assertEqual(response.status_code, 200)
484        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
485        self.assertTrue(WebAuthnDevice.objects.filter(user=self.user).exists())

Test registration with restricted devices (allow, unknown device type)

def test_registration_options_with_hints(self):
487    def test_registration_options_with_hints(self):
488        """Test that hints are included in registration options"""
489        self.stage.hints = [WebAuthnHint.CLIENT_DEVICE, WebAuthnHint.SECURITY_KEY]
490        self.stage.save()
491
492        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
493        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
494        session = self.client.session
495        session[SESSION_KEY_PLAN] = plan
496        session.save()
497
498        response = self.client.get(
499            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
500        )
501        self.assertEqual(response.status_code, 200)
502        registration = response.json()["registration"]
503        self.assertEqual(registration["hints"], ["client-device", "security-key"])

Test that hints are included in registration options

def test_registration_options_hints_empty(self):
505    def test_registration_options_hints_empty(self):
506        """Test that no hints key is present when hints are empty"""
507        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
508        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
509        session = self.client.session
510        session[SESSION_KEY_PLAN] = plan
511        session.save()
512
513        response = self.client.get(
514            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
515        )
516        self.assertEqual(response.status_code, 200)
517        registration = response.json()["registration"]
518        self.assertNotIn("hints", registration)

Test that no hints key is present when hints are empty

def test_registration_options_hints_infer_attachment_cross_platform(self):
520    def test_registration_options_hints_infer_attachment_cross_platform(self):
521        """Test that authenticatorAttachment is auto-inferred as cross-platform
522        from security-key/hybrid hints for backwards compatibility"""
523        self.stage.hints = [WebAuthnHint.SECURITY_KEY]
524        self.stage.authenticator_attachment = None
525        self.stage.save()
526
527        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
528        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
529        session = self.client.session
530        session[SESSION_KEY_PLAN] = plan
531        session.save()
532
533        response = self.client.get(
534            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
535        )
536        self.assertEqual(response.status_code, 200)
537        registration = response.json()["registration"]
538        self.assertEqual(
539            registration["authenticatorSelection"]["authenticatorAttachment"], "cross-platform"
540        )

Test that authenticatorAttachment is auto-inferred as cross-platform from security-key/hybrid hints for backwards compatibility

def test_registration_options_hints_infer_attachment_platform(self):
542    def test_registration_options_hints_infer_attachment_platform(self):
543        """Test that authenticatorAttachment is auto-inferred as platform
544        from client-device hint for backwards compatibility"""
545        self.stage.hints = [WebAuthnHint.CLIENT_DEVICE]
546        self.stage.authenticator_attachment = None
547        self.stage.save()
548
549        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
550        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
551        session = self.client.session
552        session[SESSION_KEY_PLAN] = plan
553        session.save()
554
555        response = self.client.get(
556            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
557        )
558        self.assertEqual(response.status_code, 200)
559        registration = response.json()["registration"]
560        self.assertEqual(
561            registration["authenticatorSelection"]["authenticatorAttachment"], "platform"
562        )

Test that authenticatorAttachment is auto-inferred as platform from client-device hint for backwards compatibility

def test_registration_options_hints_no_infer_when_attachment_set(self):
564    def test_registration_options_hints_no_infer_when_attachment_set(self):
565        """Test that authenticatorAttachment is NOT overridden when explicitly set"""
566        self.stage.hints = [WebAuthnHint.SECURITY_KEY]
567        self.stage.authenticator_attachment = "platform"
568        self.stage.save()
569
570        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
571        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
572        session = self.client.session
573        session[SESSION_KEY_PLAN] = plan
574        session.save()
575
576        response = self.client.get(
577            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
578        )
579        self.assertEqual(response.status_code, 200)
580        registration = response.json()["registration"]
581        self.assertEqual(
582            registration["authenticatorSelection"]["authenticatorAttachment"], "platform"
583        )

Test that authenticatorAttachment is NOT overridden when explicitly set

def test_registration_options_hints_no_infer_mixed(self):
585    def test_registration_options_hints_no_infer_mixed(self):
586        """Test that authenticatorAttachment is NOT inferred when hints are mixed"""
587        self.stage.hints = [WebAuthnHint.SECURITY_KEY, WebAuthnHint.CLIENT_DEVICE]
588        self.stage.authenticator_attachment = None
589        self.stage.save()
590
591        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
592        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
593        session = self.client.session
594        session[SESSION_KEY_PLAN] = plan
595        session.save()
596
597        response = self.client.get(
598            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
599        )
600        self.assertEqual(response.status_code, 200)
601        registration = response.json()["registration"]
602        self.assertNotIn("authenticatorAttachment", registration["authenticatorSelection"])

Test that authenticatorAttachment is NOT inferred when hints are mixed

def test_registration_options_hints_order_preserved(self):
604    def test_registration_options_hints_order_preserved(self):
605        """Test that hint order is preserved (first hint = highest priority)"""
606        self.stage.hints = [
607            WebAuthnHint.HYBRID,
608            WebAuthnHint.CLIENT_DEVICE,
609            WebAuthnHint.SECURITY_KEY,
610        ]
611        self.stage.save()
612
613        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
614        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
615        session = self.client.session
616        session[SESSION_KEY_PLAN] = plan
617        session.save()
618
619        response = self.client.get(
620            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
621        )
622        self.assertEqual(response.status_code, 200)
623        registration = response.json()["registration"]
624        self.assertEqual(registration["hints"], ["hybrid", "client-device", "security-key"])

Test that hint order is preserved (first hint = highest priority)

def test_register_max_retries(self):
626    def test_register_max_retries(self):
627        """Test registration (exceeding max retries)"""
628        self.stage.max_attempts = 2
629        self.stage.save()
630
631        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
632        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
633        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = b64decode(
634            b"03Xodi54gKsfnP5I9VFfhaGXVVE2NUyZpBBXns/JI+x6V9RY2Tw2QmxRJkhh7174EkRazUntIwjMVY9bFG60Lw=="
635        )
636        session = self.client.session
637        session[SESSION_KEY_PLAN] = plan
638        session.save()
639
640        # first failed request
641        response = self.client.post(
642            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
643            data={
644                "component": "ak-stage-authenticator-webauthn",
645                "response": {
646                    "id": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
647                    "rawId": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
648                    "type": "public-key",
649                    "registrationClientExtensions": "{}",
650                    "response": {
651                        "clientDataJSON": (
652                            "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmd"
653                            "lIjoiMDNYb2RpNTRnS3NmblA1STlWRmZoYUdYVlZFMk5VeV"
654                            "pwQkJYbnNfSkkteDZWOVJZMlR3MlFteFJKa2hoNzE3NEVrU"
655                            "mF6VW50SXdqTVZZOWJGRzYwTHciLCJvcmlnaW4iOiJodHRw"
656                            "Oi8vbG9jYWxob3N0OjkwMDAiLCJjcm9zc09yaWdpbiI6ZmF"
657                        ),
658                        "attestationObject": (
659                            "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YViYSZYN5Yg"
660                            "OjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2NdAAAAAPv8MA"
661                            "cVTk7MjAtuAgVX170AFJKp5q1S5wxvjsLEjR5IoWGWjc-bp"
662                            "QECAyYgASFYIKtcZHPumH37XHs0IM1v3pUBRIqHVV_SE-Lq"
663                            "2zpJAOVXIlgg74Fg_WdB0kuLYqCKbxogkEPaVtR_iR3IyQFIJAXBzds"
664                        ),
665                    },
666                },
667            },
668            SERVER_NAME="localhost",
669            SERVER_PORT="9000",
670        )
671        self.assertEqual(response.status_code, 200)
672        self.assertStageResponse(
673            response,
674            flow=self.flow,
675            component="ak-stage-authenticator-webauthn",
676            response_errors={
677                "response": [
678                    {
679                        "string": "Registration failed. Please contact your administrator.",
680                        "code": "invalid",
681                    }
682                ]
683            },
684        )
685        self.assertFalse(WebAuthnDevice.objects.filter(user=self.user).exists())
686
687        # Second failed request
688        response = self.client.post(
689            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
690            data={
691                "component": "ak-stage-authenticator-webauthn",
692                "response": {
693                    "id": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
694                    "rawId": "kqnmrVLnDG-OwsSNHkihYZaNz5s",
695                    "type": "public-key",
696                    "registrationClientExtensions": "{}",
697                    "response": {
698                        "clientDataJSON": (
699                            "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmd"
700                            "lIjoiMDNYb2RpNTRnS3NmblA1STlWRmZoYUdYVlZFMk5VeV"
701                            "pwQkJYbnNfSkkteDZWOVJZMlR3MlFteFJKa2hoNzE3NEVrU"
702                            "mF6VW50SXdqTVZZOWJGRzYwTHciLCJvcmlnaW4iOiJodHRw"
703                            "Oi8vbG9jYWxob3N0OjkwMDAiLCJjcm9zc09yaWdpbiI6ZmF"
704                        ),
705                        "attestationObject": (
706                            "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YViYSZYN5Yg"
707                            "OjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2NdAAAAAPv8MA"
708                            "cVTk7MjAtuAgVX170AFJKp5q1S5wxvjsLEjR5IoWGWjc-bp"
709                            "QECAyYgASFYIKtcZHPumH37XHs0IM1v3pUBRIqHVV_SE-Lq"
710                            "2zpJAOVXIlgg74Fg_WdB0kuLYqCKbxogkEPaVtR_iR3IyQFIJAXBzds"
711                        ),
712                    },
713                },
714            },
715            SERVER_NAME="localhost",
716            SERVER_PORT="9000",
717        )
718        self.assertEqual(response.status_code, 200)
719        self.assertStageResponse(
720            response,
721            flow=self.flow,
722            component="ak-stage-access-denied",
723            error_message=(
724                "Exceeded maximum attempts. Contact your authentik administrator for help."
725            ),
726        )
727        self.assertFalse(WebAuthnDevice.objects.filter(user=self.user).exists())

Test registration (exceeding max retries)

@skipIf(backend._fips_enabled, 'The FIPS provider has no Ed25519 or ML-DSA')
def test_registration_options_algorithms(self):
729    @skipIf(backend._fips_enabled, "The FIPS provider has no Ed25519 or ML-DSA")
730    def test_registration_options_algorithms(self):
731        """Registration offers the classical algorithms first and the ML-DSA sets last"""
732        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
733        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
734        session = self.client.session
735        session[SESSION_KEY_PLAN] = plan
736        session.save()
737        response = self.client.get(
738            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
739        )
740        self.assertEqual(response.status_code, 200)
741        params = response.json()["registration"]["pubKeyCredParams"]
742        self.assertEqual([p["alg"] for p in params], [int(alg) for alg in PREFERRED_PUB_KEY_ALGS])
743        self.assertEqual([p["alg"] for p in params][-3:], [-48, -49, -50])

Registration offers the classical algorithms first and the ML-DSA sets last

def test_registration_options_algorithms_fips(self):
753    def test_registration_options_algorithms_fips(self):
754        """With FIPS enabled only the algorithms the FIPS provider can verify are offered"""
755        self._enable_fips()
756        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
757        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
758        session = self.client.session
759        session[SESSION_KEY_PLAN] = plan
760        session.save()
761        response = self.client.get(
762            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
763        )
764        self.assertEqual(response.status_code, 200)
765        params = response.json()["registration"]["pubKeyCredParams"]
766        self.assertEqual([p["alg"] for p in params], [-7, -257])

With FIPS enabled only the algorithms the FIPS provider can verify are offered

@skipIf(backend._fips_enabled, 'The FIPS provider has no Ed25519')
def test_register_eddsa(self):
786    @skipIf(backend._fips_enabled, "The FIPS provider has no Ed25519")
787    def test_register_eddsa(self):
788        """Test registration of an Ed25519 credential"""
789        credential = SoftwareCredential(
790            rp_id="localhost", origin="http://localhost:9000", alg=COSEAlgorithmIdentifier.EDDSA
791        )
792        response = self._register_software_credential(credential)
793        self.assertEqual(response.status_code, 200)
794        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
795        device = WebAuthnDevice.objects.get(user=self.user)
796        self.assertEqual(device.public_key, bytes_to_base64url(credential.cose_public_key))

Test registration of an Ed25519 credential

@skipIf(backend._fips_enabled, 'The FIPS provider has no Ed25519')
def test_register_unavailable_algorithm_fips(self):
798    @skipIf(backend._fips_enabled, "The FIPS provider has no Ed25519")
799    def test_register_unavailable_algorithm_fips(self):
800        """An authenticator that ignores the offered algorithms and creates a credential the
801        FIPS provider cannot verify is rejected at registration, not at first login"""
802        self._enable_fips()
803        credential = SoftwareCredential(
804            rp_id="localhost", origin="http://localhost:9000", alg=COSEAlgorithmIdentifier.EDDSA
805        )
806        response = self._register_software_credential(credential)
807        self.assertStageResponse(
808            response,
809            flow=self.flow,
810            component="ak-stage-authenticator-webauthn",
811            response_errors={
812                "response": [
813                    {
814                        "string": "Registration failed. Please contact your administrator.",
815                        "code": "invalid",
816                    }
817                ]
818            },
819        )
820        self.assertFalse(WebAuthnDevice.objects.filter(user=self.user).exists())

An authenticator that ignores the offered algorithms and creates a credential the FIPS provider cannot verify is rejected at registration, not at first login

@skipIf(backend._fips_enabled, 'The FIPS provider has no ML-DSA')
def test_register_mldsa(self):
822    @skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
823    def test_register_mldsa(self):
824        """Test registration of an ML-DSA-44 (FIPS 204) credential"""
825        credential = SoftwareCredential(rp_id="localhost", origin="http://localhost:9000")
826        challenge = b"\x01" * 64
827        plan = FlowPlan(flow_pk=self.flow.pk.hex, bindings=[self.binding], markers=[StageMarker()])
828        plan.context[PLAN_CONTEXT_PENDING_USER] = self.user
829        plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = challenge
830        session = self.client.session
831        session[SESSION_KEY_PLAN] = plan
832        session.save()
833        response = self.client.post(
834            reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug}),
835            data={
836                "component": "ak-stage-authenticator-webauthn",
837                "response": credential.registration_response(challenge),
838            },
839            SERVER_NAME="localhost",
840            SERVER_PORT="9000",
841        )
842        self.assertEqual(response.status_code, 200)
843        self.assertStageRedirects(response, reverse("authentik_core:root-redirect"))
844        device = WebAuthnDevice.objects.filter(user=self.user).first()
845        self.assertIsNotNone(device)
846        self.assertEqual(device.credential_id, bytes_to_base64url(credential.credential_id))
847        self.assertEqual(device.public_key, bytes_to_base64url(credential.cose_public_key))
848        self.assertIsNone(device.attestation_certificate_pem)

Test registration of an ML-DSA-44 (FIPS 204) credential