| 1 |
import json |
| 2 |
import time |
| 3 |
from http import HTTPStatus |
| 4 |
from importlib import import_module |
| 5 |
from urllib.parse import parse_qs, urlparse |
| 6 |
|
| 7 |
from django.conf import settings |
| 8 |
from django.test import TestCase |
| 9 |
from django.test.utils import override_settings |
| 10 |
from django.urls import reverse |
| 11 |
from django.utils.http import urlencode |
| 12 |
|
| 13 |
import jwt |
| 14 |
|
| 15 |
from allauth.socialaccount.providers.apple.apple_session import ( |
| 16 |
APPLE_SESSION_COOKIE_NAME, |
| 17 |
) |
| 18 |
from allauth.socialaccount.providers.apple.client import jwt_encode |
| 19 |
from allauth.socialaccount.providers.apple.provider import AppleProvider |
| 20 |
from tests.apps.socialaccount.base import OAuth2TestsMixin |
| 21 |
from tests.mocking import MockedResponse, mocked_response |
| 22 |
|
| 23 |
|
| 24 |
# Generated on https://mkjwk.org/, used to sign and verify the apple id_token |
| 25 |
TESTING_JWT_KEYSET = { |
| 26 |
"p": ( |
| 27 |
"4ADzS5jKx_kdQihyOocVS0Qwwo7m0f7Ow56EadySJ-cmnwoHHF3AxgRaq-h-KwybSphv" |
| 28 |
"dc-X7NbS79-b9dumHKyt1MeVLAsDZD1a-uQCEneY1g9LsQkscNr7OggcpvMg5UUFwv6A" |
| 29 |
"kavu8cB0iyhNdha5_AWX27K5lNebvpaXEJ8" |
| 30 |
), |
| 31 |
"kty": "RSA", |
| 32 |
"q": ( |
| 33 |
"yy5UvMjrvZyO1Os_nxXIugCa3NyWOkC8oMppPvr1Bl5AnF_xwXN2n9ozPd9Nb3Q3n-om" |
| 34 |
"NgLayyUxhwIjWDlI67Vbx-ESuff8ZEBKuTK0Gdmr4C_QU_j0gvvNMNJweSPxDdRmIUgO" |
| 35 |
"njTVNWmdqFTZs43jXAT4J519rgveNLAkGNE" |
| 36 |
), |
| 37 |
"d": ( |
| 38 |
"riPuGIDde88WS03CVbo_mZ9toFWPyTxvuz8VInJ9S1ZxULo-hQWDBohWGYwvg8cgfXck" |
| 39 |
"cqWt5OBqNvPYdLgwb84uVi2JeEHmhcQSc_x0zfRTau5HVE2KdR-gWxQjPWoaBHeDVqwo" |
| 40 |
"PKaU2XYxa-gYDXcuSJWHz3BX13oInDEFCXr6VwiLiwLBFsb63EEHwyWXJbTpoar7AARW" |
| 41 |
"kz76qtngDkk4t9gk_Q0L1y1qf1GeWiAL7xWb-bdptma4-1ui-R2219-1ONEZ41v_jsIS" |
| 42 |
"_z8ooXmVCbUsHV4Z1UDpRvpORVE3u57WK3qXUdAtZsXjaIwkdItbDmL1jFUgefwfO91Y" |
| 43 |
"YQ" |
| 44 |
), |
| 45 |
"e": "AQAB", |
| 46 |
"use": "sig", |
| 47 |
"kid": "testkey", |
| 48 |
"qi": ( |
| 49 |
"R0Hu4YmpHzw3SKWGYuAcAo6B97-JlN2fXiTjZ2g8eHGQX7LSoKEu0Hmu5hcBZYSgOuor" |
| 50 |
"IPsPUu3mNtx3pjLMOaJRk34VwcYu7h23ogEKGcPUt1c4tTotFDdw8WFptDOw4ow31Tml" |
| 51 |
"BPExLqzzGjJeQSNULB1bExuuhYMWx6wBXo8" |
| 52 |
), |
| 53 |
"dp": ( |
| 54 |
"WBaHlnbjZ3hDVTzqjrGIYizSr-_aPUJitPKlR6wBncd8nJYo7bLAmB4mOewXkX5HozIG" |
| 55 |
"wuF78RsZoFLi1fAmhqgxQ7eopcU-9DBcksUPO4vkgmlJbrkYzNiQauW9vrllekOGXIQQ" |
| 56 |
"szhVoqP4MLEMpR-Sy9S3PyItcKbJDE3T4ik" |
| 57 |
), |
| 58 |
"alg": "RS256", |
| 59 |
"dq": ( |
| 60 |
"Ar5kbIw2CsBzeVKX8FkF9eUOMk9URAMdyPoSw8P1zRk2vCXbiOY7Qttad8ptLEUgfytV" |
| 61 |
"SsNtGvMsoQsZWRak8nHnhGJ4s0QzB1OK7sdNgU_cL1HV-VxSSPaHhdJBrJEcrzggDPEB" |
| 62 |
"KYfDHU6Iz34d1nvjBxoWE8rfqJsGbCW4xxE" |
| 63 |
), |
| 64 |
"n": ( |
| 65 |
"sclLPioUv4VOcOZWAKoRhcvwIH2jOhoHhSI_Cj5c5zSp7qaK8jCU6T7-GObsgrhpty-k" |
| 66 |
"26ZuqRdgu9d-62WO8OBGt1e0wxbTh128-nTTrOESHUlV_K1wpJmXOxNpJiybcgzZNbAm" |
| 67 |
"ACmsHfxZvN9bt7gKPXxf3-_zFAf12PbYMrOionAJ1N_4HxL7fz3xkr5C87Av06QNilIC" |
| 68 |
"-mA-4n9Eqw_R2DYNpE3RYMdWtwKqBwJC8qs3677RpG9vcc-yZ_97pEiytd2FBJ8uoTwH" |
| 69 |
"d3DHJB8UVgBSh1kMUpSdoM7HxVzKx732nx6Kusln79LrsfOzrXF4enkfKJYI40-uwT95" |
| 70 |
"zw" |
| 71 |
), |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
# Mocked version of the test data from https://appleid.apple.com/auth/keys |
| 76 |
KEY_SERVER_RESP_JSON = json.dumps( |
| 77 |
{ |
| 78 |
"keys": [ |
| 79 |
{ |
| 80 |
"kty": TESTING_JWT_KEYSET["kty"], |
| 81 |
"kid": TESTING_JWT_KEYSET["kid"], |
| 82 |
"use": TESTING_JWT_KEYSET["use"], |
| 83 |
"alg": TESTING_JWT_KEYSET["alg"], |
| 84 |
"n": TESTING_JWT_KEYSET["n"], |
| 85 |
"e": TESTING_JWT_KEYSET["e"], |
| 86 |
} |
| 87 |
] |
| 88 |
} |
| 89 |
) |
| 90 |
|
| 91 |
|
| 92 |
def sign_id_token(payload): |
| 93 |
""" |
| 94 |
Sign a payload as apple normally would for the id_token. |
| 95 |
""" |
| 96 |
signing_key = jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(TESTING_JWT_KEYSET)) |
| 97 |
return jwt_encode( |
| 98 |
payload, |
| 99 |
signing_key, |
| 100 |
algorithm="RS256", |
| 101 |
headers={"kid": TESTING_JWT_KEYSET["kid"]}, |
| 102 |
) |
| 103 |
|
| 104 |
|
| 105 |
@override_settings( |
| 106 |
SOCIALACCOUNT_STORE_TOKENS=False, |
| 107 |
SOCIALACCOUNT_PROVIDERS={ |
| 108 |
"apple": { |
| 109 |
"APP": { |
| 110 |
"client_id": "app123id", |
| 111 |
"key": "apple", |
| 112 |
"secret": "dummy", |
| 113 |
"settings": { |
| 114 |
"certificate_key": """-----BEGIN PRIVATE KEY----- |
| 115 |
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg2+Eybl8ojH4wB30C |
| 116 |
3/iDkpsrxuPfs3DZ+3nHNghBOpmhRANCAAQSpo1eQ+EpNgQQyQVs/F27dkq3gvAI |
| 117 |
28m95JEk26v64YAea5NTH56mru30RDqTKPgRVi5qRu3XGyqy3mdb8gMy |
| 118 |
-----END PRIVATE KEY----- |
| 119 |
""", |
| 120 |
}, |
| 121 |
} |
| 122 |
} |
| 123 |
}, |
| 124 |
) |
| 125 |
class AppleTests(OAuth2TestsMixin, TestCase): |
| 126 |
provider_id = AppleProvider.id |
| 127 |
|
| 128 |
def get_apple_id_token_payload(self): |
| 129 |
now = int(time.time()) |
| 130 |
return { |
| 131 |
"iss": "https://appleid.apple.com", |
| 132 |
"aud": "app123id", # Matches `setup_app` |
| 133 |
"exp": now + 60 * 60, |
| 134 |
"iat": now, |
| 135 |
"sub": "000313.c9720f41e9434e18987a.1218", |
| 136 |
"at_hash": "CkaUPjk4MJinaAq6Z0tGUA", |
| 137 |
"email": "[email protected]", |
| 138 |
"email_verified": "true", |
| 139 |
"is_private_email": "true", |
| 140 |
"auth_time": 1234345345, # not converted automatically by pyjwt |
| 141 |
} |
| 142 |
|
| 143 |
def test_verify_token(self): |
| 144 |
id_token = sign_id_token(self.get_apple_id_token_payload()) |
| 145 |
with mocked_response(self.get_mocked_response()): |
| 146 |
sociallogin = self.provider.verify_token(None, {"id_token": id_token}) |
| 147 |
assert sociallogin.user.email == "[email protected]" |
| 148 |
|
| 149 |
def get_login_response_json(self, with_refresh_token=True): |
| 150 |
""" |
| 151 |
`with_refresh_token` is not optional for apple, so it's ignored. |
| 152 |
""" |
| 153 |
id_token = sign_id_token(self.get_apple_id_token_payload()) |
| 154 |
|
| 155 |
return json.dumps( |
| 156 |
{ |
| 157 |
"access_token": "testac", # Matches OAuth2TestsMixin value |
| 158 |
"expires_in": 3600, |
| 159 |
"id_token": id_token, |
| 160 |
"refresh_token": "testrt", # Matches OAuth2TestsMixin value |
| 161 |
"token_type": "Bearer", |
| 162 |
} |
| 163 |
) |
| 164 |
|
| 165 |
def get_mocked_response(self): |
| 166 |
""" |
| 167 |
Apple is unusual in that the `id_token` contains all the user info |
| 168 |
so no profile info request is made. However, it does need the |
| 169 |
public key verification, so this mocked response is the public |
| 170 |
key request in order to verify the authenticity of the id_token. |
| 171 |
""" |
| 172 |
return MockedResponse( |
| 173 |
HTTPStatus.OK, KEY_SERVER_RESP_JSON, {"content-type": "application/json"} |
| 174 |
) |
| 175 |
|
| 176 |
def get_expected_to_str(self): |
| 177 |
return "A B" |
| 178 |
|
| 179 |
def get_complete_parameters(self, auth_request_params): |
| 180 |
""" |
| 181 |
Add apple specific response parameters which they include in the |
| 182 |
form_post response. |
| 183 |
|
| 184 |
https://developer.apple.com/documentation/sign_in_with_apple/sign_in_with_apple_js/incorporating_sign_in_with_apple_into_other_platforms |
| 185 |
""" |
| 186 |
params = super().get_complete_parameters(auth_request_params) |
| 187 |
params.update( |
| 188 |
{ |
| 189 |
"id_token": sign_id_token(self.get_apple_id_token_payload()), |
| 190 |
"user": json.dumps( |
| 191 |
{ |
| 192 |
"email": "[email protected]", |
| 193 |
"name": { |
| 194 |
"firstName": "A", |
| 195 |
"lastName": "B", |
| 196 |
}, |
| 197 |
} |
| 198 |
), |
| 199 |
} |
| 200 |
) |
| 201 |
return params |
| 202 |
|
| 203 |
def login(self, resp_mock, process="login", with_refresh_token=True): |
| 204 |
resp = self.client.post( |
| 205 |
f"{reverse(f'{self.provider.id}_login')}?{urlencode(dict(process=process))}" |
| 206 |
) |
| 207 |
p = urlparse(resp["location"]) |
| 208 |
q = parse_qs(p.query) |
| 209 |
complete_url = reverse(f"{self.provider.id}_callback") |
| 210 |
self.assertGreater(q["redirect_uri"][0].find(complete_url), 0) |
| 211 |
response_json = self.get_login_response_json( |
| 212 |
with_refresh_token=with_refresh_token |
| 213 |
) |
| 214 |
with mocked_response( |
| 215 |
MockedResponse( |
| 216 |
HTTPStatus.OK, response_json, {"content-type": "application/json"} |
| 217 |
), |
| 218 |
resp_mock, |
| 219 |
): |
| 220 |
resp = self.client.post( |
| 221 |
complete_url, |
| 222 |
data=self.get_complete_parameters(q), |
| 223 |
) |
| 224 |
assert reverse("apple_finish_callback") in resp.url |
| 225 |
|
| 226 |
# Follow the redirect |
| 227 |
resp = self.client.get(resp.url) |
| 228 |
|
| 229 |
return resp |
| 230 |
|
| 231 |
def test_authentication_error(self): |
| 232 |
"""Override base test because apple posts errors""" |
| 233 |
resp = self.client.post( |
| 234 |
reverse(f"{self.provider.id}_callback"), |
| 235 |
data={"error": "misc", "state": "testingstate123"}, |
| 236 |
) |
| 237 |
assert reverse("apple_finish_callback") in resp.url |
| 238 |
# Follow the redirect |
| 239 |
resp = self.client.get(resp.url) |
| 240 |
|
| 241 |
template_ext = getattr(settings, "ACCOUNT_TEMPLATE_EXTENSION", "html") |
| 242 |
self.assertTemplateUsed( |
| 243 |
resp, f"socialaccount/authentication_error.{template_ext}" |
| 244 |
) |
| 245 |
|
| 246 |
def test_apple_finish(self): |
| 247 |
resp = self.login(self.get_mocked_response()) |
| 248 |
|
| 249 |
# Check request generating the response |
| 250 |
finish_url = reverse("apple_finish_callback") |
| 251 |
self.assertEqual(resp.request["PATH_INFO"], finish_url) |
| 252 |
self.assertTrue("state" in resp.request["QUERY_STRING"]) |
| 253 |
self.assertTrue("code" in resp.request["QUERY_STRING"]) |
| 254 |
|
| 255 |
# Check have cookie containing apple session |
| 256 |
self.assertTrue(APPLE_SESSION_COOKIE_NAME in self.client.cookies) |
| 257 |
|
| 258 |
# Session should have been cleared |
| 259 |
apple_session_cookie = self.client.cookies.get(APPLE_SESSION_COOKIE_NAME) |
| 260 |
engine = import_module(settings.SESSION_ENGINE) |
| 261 |
SessionStore = engine.SessionStore |
| 262 |
apple_login_session = SessionStore(apple_session_cookie.value) |
| 263 |
self.assertEqual(len(apple_login_session.keys()), 0) |
| 264 |
|
| 265 |
# Check cookie path was correctly set |
| 266 |
self.assertEqual(apple_session_cookie.get("path"), finish_url) |