authentik.enterprise.endpoints.connectors.agent.tests.test_apple_authorize
1from urllib.parse import parse_qs, urlencode, urlparse 2 3from cryptography.hazmat.primitives import serialization 4from django.urls import reverse 5from jwt import encode 6 7from authentik.core.models import Group 8from authentik.core.tests.utils import create_test_cert, create_test_flow, create_test_user 9from authentik.crypto.builder import PrivateKeyAlg 10from authentik.endpoints.connectors.agent.models import ( 11 AgentConnector, 12 AgentDeviceConnection, 13 AppleAuthorizationCode, 14) 15from authentik.endpoints.models import Device, DeviceAccessGroup 16from authentik.enterprise.endpoints.connectors.agent.views.apple_authorize import REDIRECT_URI 17from authentik.enterprise.tests import enterprise_test 18from authentik.flows.models import FlowDesignation, FlowStageBinding 19from authentik.flows.tests import APIFlowTestCase 20from authentik.lib.generators import generate_id 21from authentik.policies.models import PolicyBinding 22from authentik.providers.oauth2.models import JWTAlgorithms 23from authentik.stages.dummy.models import DummyStage 24 25 26class TestAppleAuthorize(APIFlowTestCase): 27 28 def setUp(self): 29 self.apple_sign_key = create_test_cert(PrivateKeyAlg.ECDSA) 30 self.connector = AgentConnector.objects.create( 31 name=generate_id(), 32 authorization_flow=create_test_flow(), 33 ) 34 self.device = Device.objects.create(name=generate_id(), identifier=generate_id()) 35 self.connection = AgentDeviceConnection.objects.create( 36 device=self.device, 37 connector=self.connector, 38 apple_sign_key_id=self.apple_sign_key.kid, 39 apple_signing_key=self.apple_sign_key.public_key.public_bytes( 40 encoding=serialization.Encoding.PEM, 41 format=serialization.PublicFormat.SubjectPublicKeyInfo, 42 ).decode(), 43 ) 44 self.user = create_test_user() 45 self.url = reverse( 46 "authentik_enterprise_endpoints_connectors_agent:psso-authorize", 47 kwargs={"connector_uuid": str(self.connector.pk)}, 48 ) 49 50 @enterprise_test() 51 def test_authorize_binds_device(self): 52 """The issued code is bound to the device that signed the request object""" 53 # Device policies are deny-by-default, bind a passing policy for self.user 54 group = Group.objects.create(name=generate_id()) 55 group.users.add(self.user) 56 self.device.access_group = DeviceAccessGroup.objects.create(name=generate_id()) 57 self.device.save() 58 PolicyBinding.objects.create(target=self.device.access_group, group=group, order=0) 59 60 self.client.force_login(self.user) 61 request_object = encode( 62 {"iss": str(self.connector.pk)}, 63 self.apple_sign_key.private_key, 64 headers={"kid": self.apple_sign_key.kid}, 65 algorithm=JWTAlgorithms.from_private_key(self.apple_sign_key.private_key), 66 ) 67 res = self.client.post( 68 f"{self.url}?redirect_uri={REDIRECT_URI}", 69 # Platform SSO posts the request object as a form field, the API test client 70 # would otherwise default to JSON 71 data=urlencode({"request": request_object}), 72 content_type="application/x-www-form-urlencoded", 73 ) 74 self.assertEqual(res.status_code, 302) 75 # The flow is empty, so running the executor once reaches the fulfillment stage 76 res = self.client.get( 77 reverse( 78 "authentik_api:flow-executor", 79 kwargs={"flow_slug": self.connector.authorization_flow.slug}, 80 ) 81 ) 82 to = self.assertStageResponse(res, component="xak-flow-redirect")["to"] 83 code = parse_qs(urlparse(to).query)["code"][0] 84 auth_code = AppleAuthorizationCode.objects.get(code=code) 85 self.assertEqual(auth_code.device_connection, self.connection) 86 self.assertEqual(auth_code.user, self.user) 87 88 @enterprise_test() 89 def test_preauthenticate(self): 90 """Platform SSO only signs and posts a request object when the pre-authentication 91 response contains an authorization request""" 92 res = self.client.get( 93 reverse( 94 "authentik_enterprise_endpoints_connectors_agent:psso-preauthenticate", 95 kwargs={"connector_uuid": str(self.connector.pk)}, 96 ), 97 {"user": self.user.username}, 98 ) 99 self.assertEqual(res.status_code, 200) 100 body = res.json() 101 query = parse_qs(urlparse(body["authorization_url"]).query) 102 self.assertEqual(query["login_hint"], [self.user.username]) 103 self.assertEqual( 104 body["authorizationRequest"], 105 { 106 "client_id": str(self.connector.pk), 107 "redirect_uri": REDIRECT_URI, 108 "response_type": "code", 109 "scope": "openid profile email", 110 "state": query["state"][0], 111 }, 112 ) 113 114 @enterprise_test() 115 def test_authorize_unauthenticated(self): 116 """The request object is only posted once, and has to survive the user logging in""" 117 group = Group.objects.create(name=generate_id()) 118 group.users.add(self.user) 119 self.device.access_group = DeviceAccessGroup.objects.create(name=generate_id()) 120 self.device.save() 121 PolicyBinding.objects.create(target=self.device.access_group, group=group, order=0) 122 FlowStageBinding.objects.create( 123 target=create_test_flow(FlowDesignation.AUTHENTICATION), 124 stage=DummyStage.objects.create(name=generate_id()), 125 order=0, 126 ) 127 128 request_object = encode( 129 {"iss": str(self.connector.pk)}, 130 self.apple_sign_key.private_key, 131 headers={"kid": self.apple_sign_key.kid}, 132 algorithm=JWTAlgorithms.from_private_key(self.apple_sign_key.private_key), 133 ) 134 url = f"{self.url}?redirect_uri={REDIRECT_URI}" 135 res = self.client.post( 136 url, 137 data=urlencode({"request": request_object}), 138 content_type="application/x-www-form-urlencoded", 139 ) 140 # Sent to the authentication flow 141 self.assertEqual(res.status_code, 302) 142 self.assertNotIn(self.connector.authorization_flow.slug, res.url) 143 144 self.client.force_login(self.user) 145 # After logging in, the user is sent back with a GET 146 res = self.client.get(url) 147 self.assertEqual(res.status_code, 302) 148 self.assertIn(self.connector.authorization_flow.slug, res.url) 149 res = self.client.get( 150 reverse( 151 "authentik_api:flow-executor", 152 kwargs={"flow_slug": self.connector.authorization_flow.slug}, 153 ) 154 ) 155 to = self.assertStageResponse(res, component="xak-flow-redirect")["to"] 156 code = parse_qs(urlparse(to).query)["code"][0] 157 self.assertEqual( 158 AppleAuthorizationCode.objects.get(code=code).device_connection, self.connection 159 ) 160 # The request object can't be replayed from the session 161 self.assertEqual(self.client.get(url).status_code, 404) 162 163 @enterprise_test() 164 def test_authorize_without_request_object(self): 165 """Plain federation carries no device identity and is not supported""" 166 group = Group.objects.create(name=generate_id()) 167 group.users.add(self.user) 168 self.device.access_group = DeviceAccessGroup.objects.create(name=generate_id()) 169 self.device.save() 170 PolicyBinding.objects.create(target=self.device.access_group, group=group, order=0) 171 172 self.client.force_login(self.user) 173 res = self.client.post(f"{self.url}?redirect_uri={REDIRECT_URI}") 174 self.assertEqual(res.status_code, 404) 175 176 @enterprise_test() 177 def test_authorize_unknown_device(self): 178 """A request object signed by a key no enrolled device uses is rejected""" 179 group = Group.objects.create(name=generate_id()) 180 group.users.add(self.user) 181 self.device.access_group = DeviceAccessGroup.objects.create(name=generate_id()) 182 self.device.save() 183 PolicyBinding.objects.create(target=self.device.access_group, group=group, order=0) 184 185 self.client.force_login(self.user) 186 other_key = create_test_cert(PrivateKeyAlg.ECDSA) 187 request_object = encode( 188 {"iss": str(self.connector.pk)}, 189 other_key.private_key, 190 headers={"kid": other_key.kid}, 191 algorithm=JWTAlgorithms.from_private_key(other_key.private_key), 192 ) 193 res = self.client.post( 194 f"{self.url}?redirect_uri={REDIRECT_URI}", 195 data=urlencode({"request": request_object}), 196 content_type="application/x-www-form-urlencoded", 197 ) 198 self.assertEqual(res.status_code, 404) 199 200 @enterprise_test() 201 def test_authorize_device_policy_denied(self): 202 """Without a passing device policy no code is issued""" 203 self.client.force_login(self.user) 204 request_object = encode( 205 {"iss": str(self.connector.pk)}, 206 self.apple_sign_key.private_key, 207 headers={"kid": self.apple_sign_key.kid}, 208 algorithm=JWTAlgorithms.from_private_key(self.apple_sign_key.private_key), 209 ) 210 res = self.client.post( 211 f"{self.url}?redirect_uri={REDIRECT_URI}", 212 data=urlencode({"request": request_object}), 213 content_type="application/x-www-form-urlencoded", 214 ) 215 self.assertNotEqual(res.status_code, 302) 216 self.assertFalse(AppleAuthorizationCode.objects.exists())
27class TestAppleAuthorize(APIFlowTestCase): 28 29 def setUp(self): 30 self.apple_sign_key = create_test_cert(PrivateKeyAlg.ECDSA) 31 self.connector = AgentConnector.objects.create( 32 name=generate_id(), 33 authorization_flow=create_test_flow(), 34 ) 35 self.device = Device.objects.create(name=generate_id(), identifier=generate_id()) 36 self.connection = AgentDeviceConnection.objects.create( 37 device=self.device, 38 connector=self.connector, 39 apple_sign_key_id=self.apple_sign_key.kid, 40 apple_signing_key=self.apple_sign_key.public_key.public_bytes( 41 encoding=serialization.Encoding.PEM, 42 format=serialization.PublicFormat.SubjectPublicKeyInfo, 43 ).decode(), 44 ) 45 self.user = create_test_user() 46 self.url = reverse( 47 "authentik_enterprise_endpoints_connectors_agent:psso-authorize", 48 kwargs={"connector_uuid": str(self.connector.pk)}, 49 ) 50 51 @enterprise_test() 52 def test_authorize_binds_device(self): 53 """The issued code is bound to the device that signed the request object""" 54 # Device policies are deny-by-default, bind a passing policy for self.user 55 group = Group.objects.create(name=generate_id()) 56 group.users.add(self.user) 57 self.device.access_group = DeviceAccessGroup.objects.create(name=generate_id()) 58 self.device.save() 59 PolicyBinding.objects.create(target=self.device.access_group, group=group, order=0) 60 61 self.client.force_login(self.user) 62 request_object = encode( 63 {"iss": str(self.connector.pk)}, 64 self.apple_sign_key.private_key, 65 headers={"kid": self.apple_sign_key.kid}, 66 algorithm=JWTAlgorithms.from_private_key(self.apple_sign_key.private_key), 67 ) 68 res = self.client.post( 69 f"{self.url}?redirect_uri={REDIRECT_URI}", 70 # Platform SSO posts the request object as a form field, the API test client 71 # would otherwise default to JSON 72 data=urlencode({"request": request_object}), 73 content_type="application/x-www-form-urlencoded", 74 ) 75 self.assertEqual(res.status_code, 302) 76 # The flow is empty, so running the executor once reaches the fulfillment stage 77 res = self.client.get( 78 reverse( 79 "authentik_api:flow-executor", 80 kwargs={"flow_slug": self.connector.authorization_flow.slug}, 81 ) 82 ) 83 to = self.assertStageResponse(res, component="xak-flow-redirect")["to"] 84 code = parse_qs(urlparse(to).query)["code"][0] 85 auth_code = AppleAuthorizationCode.objects.get(code=code) 86 self.assertEqual(auth_code.device_connection, self.connection) 87 self.assertEqual(auth_code.user, self.user) 88 89 @enterprise_test() 90 def test_preauthenticate(self): 91 """Platform SSO only signs and posts a request object when the pre-authentication 92 response contains an authorization request""" 93 res = self.client.get( 94 reverse( 95 "authentik_enterprise_endpoints_connectors_agent:psso-preauthenticate", 96 kwargs={"connector_uuid": str(self.connector.pk)}, 97 ), 98 {"user": self.user.username}, 99 ) 100 self.assertEqual(res.status_code, 200) 101 body = res.json() 102 query = parse_qs(urlparse(body["authorization_url"]).query) 103 self.assertEqual(query["login_hint"], [self.user.username]) 104 self.assertEqual( 105 body["authorizationRequest"], 106 { 107 "client_id": str(self.connector.pk), 108 "redirect_uri": REDIRECT_URI, 109 "response_type": "code", 110 "scope": "openid profile email", 111 "state": query["state"][0], 112 }, 113 ) 114 115 @enterprise_test() 116 def test_authorize_unauthenticated(self): 117 """The request object is only posted once, and has to survive the user logging in""" 118 group = Group.objects.create(name=generate_id()) 119 group.users.add(self.user) 120 self.device.access_group = DeviceAccessGroup.objects.create(name=generate_id()) 121 self.device.save() 122 PolicyBinding.objects.create(target=self.device.access_group, group=group, order=0) 123 FlowStageBinding.objects.create( 124 target=create_test_flow(FlowDesignation.AUTHENTICATION), 125 stage=DummyStage.objects.create(name=generate_id()), 126 order=0, 127 ) 128 129 request_object = encode( 130 {"iss": str(self.connector.pk)}, 131 self.apple_sign_key.private_key, 132 headers={"kid": self.apple_sign_key.kid}, 133 algorithm=JWTAlgorithms.from_private_key(self.apple_sign_key.private_key), 134 ) 135 url = f"{self.url}?redirect_uri={REDIRECT_URI}" 136 res = self.client.post( 137 url, 138 data=urlencode({"request": request_object}), 139 content_type="application/x-www-form-urlencoded", 140 ) 141 # Sent to the authentication flow 142 self.assertEqual(res.status_code, 302) 143 self.assertNotIn(self.connector.authorization_flow.slug, res.url) 144 145 self.client.force_login(self.user) 146 # After logging in, the user is sent back with a GET 147 res = self.client.get(url) 148 self.assertEqual(res.status_code, 302) 149 self.assertIn(self.connector.authorization_flow.slug, res.url) 150 res = self.client.get( 151 reverse( 152 "authentik_api:flow-executor", 153 kwargs={"flow_slug": self.connector.authorization_flow.slug}, 154 ) 155 ) 156 to = self.assertStageResponse(res, component="xak-flow-redirect")["to"] 157 code = parse_qs(urlparse(to).query)["code"][0] 158 self.assertEqual( 159 AppleAuthorizationCode.objects.get(code=code).device_connection, self.connection 160 ) 161 # The request object can't be replayed from the session 162 self.assertEqual(self.client.get(url).status_code, 404) 163 164 @enterprise_test() 165 def test_authorize_without_request_object(self): 166 """Plain federation carries no device identity and is not supported""" 167 group = Group.objects.create(name=generate_id()) 168 group.users.add(self.user) 169 self.device.access_group = DeviceAccessGroup.objects.create(name=generate_id()) 170 self.device.save() 171 PolicyBinding.objects.create(target=self.device.access_group, group=group, order=0) 172 173 self.client.force_login(self.user) 174 res = self.client.post(f"{self.url}?redirect_uri={REDIRECT_URI}") 175 self.assertEqual(res.status_code, 404) 176 177 @enterprise_test() 178 def test_authorize_unknown_device(self): 179 """A request object signed by a key no enrolled device uses is rejected""" 180 group = Group.objects.create(name=generate_id()) 181 group.users.add(self.user) 182 self.device.access_group = DeviceAccessGroup.objects.create(name=generate_id()) 183 self.device.save() 184 PolicyBinding.objects.create(target=self.device.access_group, group=group, order=0) 185 186 self.client.force_login(self.user) 187 other_key = create_test_cert(PrivateKeyAlg.ECDSA) 188 request_object = encode( 189 {"iss": str(self.connector.pk)}, 190 other_key.private_key, 191 headers={"kid": other_key.kid}, 192 algorithm=JWTAlgorithms.from_private_key(other_key.private_key), 193 ) 194 res = self.client.post( 195 f"{self.url}?redirect_uri={REDIRECT_URI}", 196 data=urlencode({"request": request_object}), 197 content_type="application/x-www-form-urlencoded", 198 ) 199 self.assertEqual(res.status_code, 404) 200 201 @enterprise_test() 202 def test_authorize_device_policy_denied(self): 203 """Without a passing device policy no code is issued""" 204 self.client.force_login(self.user) 205 request_object = encode( 206 {"iss": str(self.connector.pk)}, 207 self.apple_sign_key.private_key, 208 headers={"kid": self.apple_sign_key.kid}, 209 algorithm=JWTAlgorithms.from_private_key(self.apple_sign_key.private_key), 210 ) 211 res = self.client.post( 212 f"{self.url}?redirect_uri={REDIRECT_URI}", 213 data=urlencode({"request": request_object}), 214 content_type="application/x-www-form-urlencoded", 215 ) 216 self.assertNotEqual(res.status_code, 302) 217 self.assertFalse(AppleAuthorizationCode.objects.exists())
Flow test case with a DRF client
def
setUp(self):
29 def setUp(self): 30 self.apple_sign_key = create_test_cert(PrivateKeyAlg.ECDSA) 31 self.connector = AgentConnector.objects.create( 32 name=generate_id(), 33 authorization_flow=create_test_flow(), 34 ) 35 self.device = Device.objects.create(name=generate_id(), identifier=generate_id()) 36 self.connection = AgentDeviceConnection.objects.create( 37 device=self.device, 38 connector=self.connector, 39 apple_sign_key_id=self.apple_sign_key.kid, 40 apple_signing_key=self.apple_sign_key.public_key.public_bytes( 41 encoding=serialization.Encoding.PEM, 42 format=serialization.PublicFormat.SubjectPublicKeyInfo, 43 ).decode(), 44 ) 45 self.user = create_test_user() 46 self.url = reverse( 47 "authentik_enterprise_endpoints_connectors_agent:psso-authorize", 48 kwargs={"connector_uuid": str(self.connector.pk)}, 49 )
Hook method for setting up the test fixture before exercising it.
@enterprise_test()
def
test_preauthenticate(self):
89 @enterprise_test() 90 def test_preauthenticate(self): 91 """Platform SSO only signs and posts a request object when the pre-authentication 92 response contains an authorization request""" 93 res = self.client.get( 94 reverse( 95 "authentik_enterprise_endpoints_connectors_agent:psso-preauthenticate", 96 kwargs={"connector_uuid": str(self.connector.pk)}, 97 ), 98 {"user": self.user.username}, 99 ) 100 self.assertEqual(res.status_code, 200) 101 body = res.json() 102 query = parse_qs(urlparse(body["authorization_url"]).query) 103 self.assertEqual(query["login_hint"], [self.user.username]) 104 self.assertEqual( 105 body["authorizationRequest"], 106 { 107 "client_id": str(self.connector.pk), 108 "redirect_uri": REDIRECT_URI, 109 "response_type": "code", 110 "scope": "openid profile email", 111 "state": query["state"][0], 112 }, 113 )
Platform SSO only signs and posts a request object when the pre-authentication response contains an authorization request