import asyncio import base64 import hashlib import unittest import urllib.parse from starlette.applications import Starlette from starlette.responses import PlainTextResponse from starlette.routing import Route from app import auth from app.server import Guard, build_routes CFG = auth.Config(supabase_url="https://x.supabase.co", auth_key="sb_publishable_k", service_key="sb_secret_k", secret="s" * 32, base_url="http://localhost:7860") def fake_http_factory(allowed=True, profile=True, exchange_ok=True): calls = [] def http(method, url, headers, body=None, timeout=30): calls.append((method, url, body)) if "/auth/v1/token" in url: if exchange_ok and body and body.get("auth_code") == "good" and body.get("code_verifier"): return 200, {"user": {"id": "u1", "email": "S@Gmail.com"}} return 400, {} if "allowed_users" in url: return 200, ([{"email": "s@gmail.com", "role": "student"}] if allowed else []) if "profiles" in url: return 200, ([{"id": "u1", "name": "학생", "role": "student"}] if profile else []) return 404, {} http.calls = calls return http async def request(app, path, cookies=None, query="", host=None): headers = [] if host: headers.append((b"host", host.encode())) if cookies: headers.append((b"cookie", "; ".join(f"{k}={v}" for k, v in cookies.items()).encode())) scope = {"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "GET", "scheme": "http", "path": path, "raw_path": path.encode(), "query_string": query.encode(), "headers": headers, "server": ("t", 80), "client": ("c", 1), "root_path": ""} out = {"status": None, "headers": [], "body": b""} async def receive(): return {"type": "http.request", "body": b"", "more_body": False} async def send(m): if m["type"] == "http.response.start": out["status"], out["headers"] = m["status"], m["headers"] elif m["type"] == "http.response.body": out["body"] += m.get("body", b"") await app(scope, receive, send) return out def header(out, name): return [v.decode() for k, v in out["headers"] if k.decode().lower() == name] def cookie_value(out, name): for h in header(out, "set-cookie"): if h.startswith(name + "="): return h.split(";", 1)[0].split("=", 1)[1] return None def make_app(http): inner = Starlette(routes=[Route(p, f) for p, f in build_routes(CFG, http)] + [Route("/app", lambda r: PlainTextResponse("APP")), Route("/app/x", lambda r: PlainTextResponse("APPX"))]) return Guard(inner, secret=CFG.secret) class TestCookies(unittest.TestCase): def test_roundtrip_and_tamper(self): t = auth.sign({"uid": "u", "role": "student"}, "k" * 32, 60) self.assertEqual(auth.verify(t, "k" * 32)["uid"], "u") self.assertIsNone(auth.verify(t, "z" * 32)) raw, sig = t.split(".") self.assertIsNone(auth.verify(raw + "A." + sig, "k" * 32)) self.assertIsNone(auth.verify(raw + "." + sig[:-2] + "xx", "k" * 32)) def test_expired_and_garbage(self): self.assertIsNone(auth.verify(auth.sign({"a": 1}, "k" * 32, -5), "k" * 32)) for bad in (None, "", "abc", "a.b.c", "!!.!!"): self.assertIsNone(auth.verify(bad, "k" * 32)) def test_user_from_cookies_requires_valid_role(self): good = auth.sign({"uid": "u", "email": "e", "name": "n", "role": "teacher"}, "k" * 32, 60) bad = auth.sign({"uid": "u", "role": "hacker"}, "k" * 32, 60) self.assertEqual(auth.user_from_cookies({auth.SESSION_COOKIE: good}, "k" * 32)["role"], "teacher") self.assertIsNone(auth.user_from_cookies({auth.SESSION_COOKIE: bad}, "k" * 32)) self.assertIsNone(auth.user_from_cookies({}, "k" * 32)) class TestPkce(unittest.TestCase): def test_challenge_matches_verifier(self): v, c = auth.make_pkce() want = base64.urlsafe_b64encode(hashlib.sha256(v.encode()).digest()).rstrip(b"=").decode() self.assertEqual(c, want) self.assertTrue(43 <= len(v) <= 128) def test_authorize_url(self): q = urllib.parse.parse_qs(urllib.parse.urlparse(auth.authorize_url(CFG, "CH")).query) self.assertEqual(q["provider"], ["google"]) self.assertEqual(q["redirect_to"], ["http://localhost:7860/auth/callback"]) self.assertEqual(q["code_challenge"], ["CH"]) self.assertEqual(q["code_challenge_method"], ["s256"]) def test_config_problems(self): self.assertEqual(auth.Config("", "", "", "short", "http://x").problems()[0], "SUPABASE_URL") self.assertEqual(CFG.problems(), []) class TestLoginFlow(unittest.TestCase): def full_login(self, http): app = make_app(http) start = asyncio.run(request(app, "/login/start")) self.assertEqual(start["status"], 303) self.assertIn("supabase.co/auth/v1/authorize", header(start, "location")[0]) pk = cookie_value(start, auth.PKCE_COOKIE) self.assertTrue(pk) cb = asyncio.run(request(app, "/auth/callback", {auth.PKCE_COOKIE: pk}, "code=good")) return app, cb def test_happy_path_and_guard(self): http = fake_http_factory() app, cb = self.full_login(http) self.assertEqual(cb["status"], 303) self.assertEqual(header(cb, "location")[0], "/app") sess = cookie_value(cb, auth.SESSION_COOKIE) u = auth.user_from_cookies({auth.SESSION_COOKIE: sess}, CFG.secret) self.assertEqual((u["email"], u["role"], u["name"]), ("s@gmail.com", "student", "학생")) ok = asyncio.run(request(app, "/app", {auth.SESSION_COOKIE: sess})) self.assertEqual((ok["status"], ok["body"]), (200, b"APP")) ok2 = asyncio.run(request(app, "/app/x", {auth.SESSION_COOKIE: sess})) self.assertEqual(ok2["body"], b"APPX") no = asyncio.run(request(app, "/app")) self.assertEqual((no["status"], header(no, "location")[0]), (303, "/login")) forged = asyncio.run(request(app, "/app", {auth.SESSION_COOKIE: "x.y"})) self.assertEqual(forged["status"], 303) home = asyncio.run(request(app, "/", {auth.SESSION_COOKIE: sess})) self.assertEqual(header(home, "location")[0], "/app") def test_email_lowercased_for_roster_lookup(self): http = fake_http_factory() self.full_login(http) self.assertTrue(any("allowed_users?email=eq.s%40gmail.com" in c[1] for c in http.calls)) def test_not_in_roster_denied(self): app, cb = self.full_login(fake_http_factory(allowed=False)) self.assertEqual(cb["status"], 403) self.assertIn("허용 명단".encode(), cb["body"]) self.assertIsNone(cookie_value(cb, auth.SESSION_COOKIE)) def test_missing_profile_denied(self): _, cb = self.full_login(fake_http_factory(profile=False)) self.assertEqual(cb["status"], 403) self.assertIsNone(cookie_value(cb, auth.SESSION_COOKIE)) def test_bad_code_error_param_and_missing_cookie(self): app = make_app(fake_http_factory()) pk = cookie_value(asyncio.run(request(app, "/login/start")), auth.PKCE_COOKIE) bad = asyncio.run(request(app, "/auth/callback", {auth.PKCE_COOKIE: pk}, "code=wrong")) self.assertEqual(bad["status"], 403) err = asyncio.run(request(app, "/auth/callback", {auth.PKCE_COOKIE: pk}, "error=server_error&error_description=Database+error+saving+new+user")) self.assertEqual(err["status"], 403) nocookie = asyncio.run(request(app, "/auth/callback", None, "code=good")) self.assertEqual(nocookie["status"], 403) def test_login_page_breaks_out_of_iframe_and_shows_direct_address(self): app = make_app(fake_http_factory()) out = asyncio.run(request(app, "/login", host="localhost:7860")) body = out["body"].decode("utf-8") self.assertIn('target="_top"', body) self.assertIn("localhost:7860", body) def test_class_label(self): self.assertEqual(auth.class_label({"grade": 1, "class_no": 10, "student_no": 25}, "student"), "1학년 10반 25번") self.assertEqual(auth.class_label({"grade": 1, "class_no": 10}, "student"), "1학년 10반") self.assertEqual(auth.class_label({"grade": 1, "class_no": 6}, "teacher"), "1학년 6반 담임") self.assertEqual(auth.class_label({}, "student"), "") self.assertEqual(auth.class_label({"grade": 1, "class_no": 6}, "admin"), "") def test_label_survives_cookie(self): tok = auth.sign({"uid": "u", "email": "e", "name": "n", "role": "student", "label": "1학년 3반 7번"}, CFG.secret, 60) self.assertEqual(auth.user_from_cookies({auth.SESSION_COOKIE: tok}, CFG.secret)["label"], "1학년 3반 7번") def test_no_host_redirect_on_deployed_domain(self): cfg = auth.Config(supabase_url="https://x.supabase.co", auth_key="k", service_key="s", secret="s" * 32, base_url="https://user-app.hf.space") routes = dict(build_routes(cfg, fake_http_factory())) app = Starlette(routes=[Route(p, fn) for p, fn in routes.items()]) out = asyncio.run(request(app, "/login/start", host="internal-proxy:7860")) self.assertIn("supabase.co/auth/v1/authorize", header(out, "location")[0]) # 무한 이동 없이 정상 진행 def test_wrong_host_redirected_to_canonical(self): app = make_app(fake_http_factory()) out = asyncio.run(request(app, "/login/start", host="127.0.0.1:7860")) self.assertEqual((out["status"], header(out, "location")[0]), (303, "http://localhost:7860/login/start")) self.assertIsNone(cookie_value(out, auth.PKCE_COOKIE)) out = asyncio.run(request(app, "/login", host="127.0.0.1:7860")) self.assertEqual(header(out, "location")[0], "http://localhost:7860/login") ok = asyncio.run(request(app, "/login/start", host="localhost:7860")) self.assertIn("supabase.co/auth/v1/authorize", header(ok, "location")[0]) def test_logout_clears_cookie(self): app = make_app(fake_http_factory()) out = asyncio.run(request(app, "/logout")) self.assertEqual(header(out, "location")[0], "/login") self.assertTrue(any(h.startswith(auth.SESSION_COOKIE + "=") and ("max-age=0" in h.lower() or "1970" in h) for h in header(out, "set-cookie"))) def test_login_page_html_ok(self): out = asyncio.run(request(make_app(fake_http_factory()), "/login")) self.assertEqual(out["status"], 200) self.assertIn(b"/login/start", out["body"]) if __name__ == "__main__": unittest.main()