"""Google / Apple girişi testi – KENDİ imzaladığımız test tokenlarıyla.

Gerçek Google/Apple anahtarları yerine test anahtarı, API'nin JWKS önbelleğine
yazılır. Böylece imza, yayıncı, hedef, süre kontrolleri ve hesap eşleme gerçek
koşullarda denenir. SADECE yerel test sunucusunda çalıştır.

Kullanım: python3 test_social.py http://localhost/api /yol/public_html/api
"""
import base64
import hashlib
import json
import sys
import time
import urllib.error
import urllib.request
import uuid

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding, rsa

BASE, API_DIR = sys.argv[1], sys.argv[2]
RUN = uuid.uuid4().hex[:6]
GOOGLE_AUD = "test-web.apps.googleusercontent.com"
APPLE_AUD = "com.ornek.satranc"


def b64(b):
    return base64.urlsafe_b64encode(b).rstrip(b"=").decode()


def int_b64(n):
    return b64(n.to_bytes((n.bit_length() + 7) // 8, "big"))


key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
evil = rsa.generate_private_key(public_exponent=65537, key_size=2048)
pub = key.public_key().public_numbers()
jwks = json.dumps({"keys": [{"kty": "RSA", "kid": "test1", "alg": "RS256", "use": "sig",
                             "n": int_b64(pub.n), "e": int_b64(pub.e)}]})
for url in ("https://www.googleapis.com/oauth2/v3/certs", "https://appleid.apple.com/auth/keys"):
    with open(f"{API_DIR}/cache/jwks_{hashlib.md5(url.encode()).hexdigest()}.json", "w") as f:
        f.write(jwks)


def token(claims, signer=key, kid="test1", alg="RS256"):
    h = b64(json.dumps({"alg": alg, "kid": kid, "typ": "JWT"}).encode())
    p = b64(json.dumps(claims).encode())
    sig = signer.sign(f"{h}.{p}".encode(), padding.PKCS1v15(), hashes.SHA256())
    return f"{h}.{p}.{b64(sig)}"


def google(sub, **kw):
    now = int(time.time())
    c = {"iss": "https://accounts.google.com", "aud": GOOGLE_AUD, "sub": sub, "iat": now, "exp": now + 3600,
         "email": f"{sub}@gmail.com", "email_verified": True, "name": "Murat Şahin"}
    c.update(kw)
    return c


def apple(sub, **kw):
    now = int(time.time())
    c = {"iss": "https://appleid.apple.com", "aud": APPLE_AUD, "sub": sub, "iat": now, "exp": now + 600,
         "email": f"{sub}@privaterelay.appleid.com", "email_verified": "true"}
    c.update(kw)
    return c


def call(method, path, body=None, tok=None, expect=None):
    req = urllib.request.Request(BASE + path, data=json.dumps(body).encode() if body is not None else None, method=method)
    req.add_header("Content-Type", "application/json")
    if tok:
        req.add_header("Authorization", "Bearer " + tok)
    try:
        with urllib.request.urlopen(req) as r:
            st, p = r.status, json.loads(r.read() or b"null")
    except urllib.error.HTTPError as e:
        st, p = e.code, json.loads(e.read() or b"null")
    if expect is not None:
        assert st == expect, f"{path}: beklenen {expect}, gelen {st} {p}"
    elif st >= 400:
        raise AssertionError(f"{path}: {st} {p}")
    return p


def err(path, body, status, contains):
    p = call("POST", path, body, expect=status)
    assert contains in p.get("error", ""), (path, p)


g = f"g{RUN}"
# --- Google: yeni hesap
r = call("POST", "/auth/google", {"id_token": token(google(g)), "lang": "en"}, expect=201)
assert r["new_user"] is True and r["me"]["balance"] == 500 and r["me"]["lang"] == "en"
assert r["me"]["username"].startswith("murat_sahin"), r["me"]["username"]
assert r["me"]["google_linked"] and not r["me"]["has_password"]
gtok = r["token"]
# ikinci giriş: aynı hesap
r2 = call("POST", "/auth/google", {"id_token": token(google(g))})
assert r2["new_user"] is False and r2["me"]["id"] == r["me"]["id"]
# kullanıcı adı değiştirme
me = call("PATCH", "/me", {"username": f"kral_{RUN}"}, tok=gtok)
assert me["username"] == f"kral_{RUN}"
call("POST", "/auth/register", {"username": f"dolu_{RUN}", "password": "sifre1234"}, expect=201)
p = call("PATCH", "/me", {"username": f"dolu_{RUN}"}, tok=gtok, expect=409)
# şifresiz hesapla şifre girişi
err("/auth/login", {"login": f"kral_{RUN}", "password": "x"}, 401, "Google veya Apple")

# --- Saldırı / hata durumları
err("/auth/google", {"id_token": token(google(g), signer=evil)}, 401, "imza")
err("/auth/google", {"id_token": token(google(g, aud="baska-uygulama"))}, 401, "bu uygulama için değil")
err("/auth/google", {"id_token": token(google(g, iss="https://evil.com"))}, 401, "yayıncı")
err("/auth/google", {"id_token": token(google(g, exp=int(time.time()) - 3600))}, 401, "süresi")
err("/auth/google", {"id_token": token(google(g), alg="HS256")}, 401, "Desteklenmeyen")
err("/auth/google", {"id_token": "abc.def"}, 401, "Geçersiz")
err("/auth/google", {"id_token": token(google(g), kid="yok")}, 502, "")  # bilinmeyen anahtar → yeniden çekmeye çalışır
# Apple tokenı Google uç noktasına
err("/auth/google", {"id_token": token(apple(g))}, 401, "")

# --- E-postayla hesap bağlama: önce şifreyle kayıtlı, sonra aynı (doğrulanmış) e-postayla Google
email = f"bagla{RUN}@gmail.com"
reg = call("POST", "/auth/register", {"username": f"bagla_{RUN}", "email": email, "password": "sifre1234"}, expect=201)
r = call("POST", "/auth/google", {"id_token": token(google(f"gb{RUN}", email=email))})
assert r["new_user"] is False and r["me"]["id"] == reg["me"]["id"] and r["me"]["google_linked"]
# doğrulanmamış e-posta bağlanmaz → yeni hesap
email2 = f"bagla2{RUN}@gmail.com"
reg2 = call("POST", "/auth/register", {"username": f"bagla2_{RUN}", "email": email2, "password": "sifre1234"}, expect=201)
r = call("POST", "/auth/google", {"id_token": token(google(f"gc{RUN}", email=email2, email_verified=False))}, expect=201)
assert r["me"]["id"] != reg2["me"]["id"] and r["me"]["email"] is None

# --- Apple: ilk girişte isim uygulamadan gelir
a = f"a{RUN}"
r = call("POST", "/auth/apple", {"identity_token": token(apple(a)), "given_name": "Ayşe", "family_name": "Yılmaz"}, expect=201)
assert r["me"]["username"].startswith("ayse_yilmaz") and r["me"]["apple_linked"]
r = call("POST", "/auth/apple", {"identity_token": token(apple(a))})
assert r["new_user"] is False
err("/auth/apple", {"identity_token": token(apple(a, aud="com.baska"))}, 401, "bu uygulama için değil")

# --- yasaklı sosyal hesap
adm_login = None
print("sosyal giriş testleri geçti")

# --- Android Apple callback yönlendirmesi
req = urllib.request.Request(BASE + "/auth/apple/callback", data=b"code=abc&id_token=xyz&state=s1", method="POST")
req.add_header("Content-Type", "application/x-www-form-urlencoded")


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *a, **k):
        return None


try:
    urllib.request.build_opener(NoRedirect).open(req)
    raise AssertionError("yönlendirme bekleniyordu")
except urllib.error.HTTPError as e:
    loc = e.headers.get("Location")
    assert e.code == 307 and loc.startswith("intent://callback?code=abc&id_token=xyz&state=s1#Intent;package=") \
        and loc.endswith(";scheme=signinwithapple;end"), loc
print("apple android callback: tamam")
print("TÜM SOSYAL GİRİŞ TESTLERİ GEÇTİ")
