Spaces:
Running on T4
Running on T4
File size: 2,679 Bytes
2756f0f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | """SocialTokenVerifier against locally signed tokens (no network)."""
import time
from types import SimpleNamespace
import jwt
import pytest
from cryptography.hazmat.primitives.asymmetric import rsa
from app.core.config import Settings
from app.integrations.social_auth import InvalidSocialToken, SocialTokenVerifier
KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048)
OTHER_KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048)
class LocalKeys:
def get_signing_key_from_jwt(self, token: str):
return SimpleNamespace(key=KEY.public_key())
def _verifier() -> SocialTokenVerifier:
settings = Settings(apple_client_ids=["com.cognivision.app"], google_client_ids=["web.apps.googleusercontent.com"])
return SocialTokenVerifier(settings, {"apple": LocalKeys(), "google": LocalKeys()})
def _token(key=KEY, **overrides) -> str:
claims = {"iss": "https://appleid.apple.com", "aud": "com.cognivision.app", "sub": "001.abc",
"exp": int(time.time()) + 600, "email": "Relay@PrivateRelay.AppleID.com", "email_verified": "true"}
claims.update(overrides)
return jwt.encode({k: v for k, v in claims.items() if v is not None}, key, algorithm="RS256")
async def test_apple_token():
identity = await _verifier().verify("apple", _token())
assert identity.subject == "001.abc"
assert identity.email == "relay@privaterelay.appleid.com"
assert identity.email_verified is True
async def test_google_token_and_issuer_variants():
for iss in ("accounts.google.com", "https://accounts.google.com"):
token = _token(iss=iss, aud="web.apps.googleusercontent.com", email_verified=True)
assert (await _verifier().verify("google", token)).email_verified is True
async def test_missing_email_is_not_verified():
identity = await _verifier().verify("apple", _token(email=None))
assert identity.email is None and identity.email_verified is False
@pytest.mark.parametrize("provider, token", [
("apple", _token(key=OTHER_KEY)),
("apple", _token(exp=int(time.time()) - 10)),
("apple", _token(aud="someone.else")),
("apple", _token(iss="https://evil.example.com")),
("google", _token()), # an Apple token sent as Google: wrong audience and issuer
("apple", "not-a-jwt"),
])
async def test_rejects_bad_tokens(provider, token):
with pytest.raises(InvalidSocialToken):
await _verifier().verify(provider, token)
async def test_unconfigured_provider_rejects():
verifier = SocialTokenVerifier(Settings(), {"apple": LocalKeys(), "google": LocalKeys()})
with pytest.raises(InvalidSocialToken):
await verifier.verify("apple", _token())
|