Files
GarminHealthLab/backend/tests/test_auth.py
ericwyuan 9503fca370 feat(auth): 接入 auth-hub 统一登录,网页登录与 Garmin 同步彻底分离
网页身份改由 auth-hub 做 OAuth2 + PKCE 单点登录,本地邮箱/密码登录与注册整条链路删除
(routes/auth.py、auth.py 的密码哈希、config.py 的 ALLOW_REGISTRATION)。Garmin 账号绑定/
同步保持完全独立、可选:routes/garmin.py 不再直接查 users 表,Garmin 邮箱回退统一走新增
的 services/garmin.py::get_remembered_email()(优先读 garmin_tokens 当前绑定,兼容早期账号
落在 users.garmin_email 的历史值),彻底把「你是谁」和「你绑没绑 Garmin」两件事拆开。

- db.py: users 表新增 auth_hub_sub/auth_hub_username,MIGRATIONS 补上这两列(此前遗漏导致
  已存在的生产 MariaDB 表永远不会自动加列);同时把历史遗留的 garmin_email/
  garmin_password_hash NOT NULL 约束在线迁移为可空,因为新账号不再在注册时收集这些字段。
- routes/auth.py: 修掉 /callback 路由重复拼接 /api/auth 前缀导致 404 的 bug。
- client: LoginPage 去掉本地登录/注册标签页,只保留 auth-hub 统一登录;登录成功/失败后都
  用 history.replaceState 清理地址栏,修掉 Framework7 browserHistory 读取
  /auth/callback?code=... 导致「找不到页面」的问题。
- 新增 test_auth_hub_client.py 锁定 find_or_create_user 按 auth_hub_sub 幂等——生产上曾经因为
  这个函数在没有该测试保护时被测试触发,误建过一个空账号,靠手工核对 health_data 计数才发现。
- 生产 auth-hub 侧另行为该项目注册了正式 client(未随本次提交变更,凭证只存在服务器 .env)。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-31 23:12:17 +08:00

85 lines
3.1 KiB
Python

"""Unit tests for JWT handling and the auth endpoints."""
import datetime
import jwt
import pytest
import auth
from config import JWT_SECRET
# --- JWT --------------------------------------------------------------------
class TestTokens:
def test_sign_and_verify_roundtrip(self):
token = auth.sign_token("user-123")
assert auth.verify_token(token) == {"user_id": "user-123"}
def test_expired_token_rejected(self):
past = datetime.datetime.utcnow() - datetime.timedelta(days=1)
token = jwt.encode(
{"sub": "u", "iat": past, "exp": past}, JWT_SECRET, algorithm="HS256"
)
with pytest.raises(jwt.ExpiredSignatureError):
auth.verify_token(token)
def test_token_signed_with_other_secret_rejected(self):
token = jwt.encode({"sub": "u"}, "a-different-secret", algorithm="HS256")
with pytest.raises(jwt.InvalidTokenError):
auth.verify_token(token)
def test_tampered_token_rejected(self):
token = auth.sign_token("user-123")
head, payload, sig = token.split(".")
with pytest.raises(jwt.InvalidTokenError):
auth.verify_token(f"{head}.{payload}.{sig[:-2]}xx")
# --- require_auth -----------------------------------------------------------
class TestRequireAuth:
def test_missing_header(self, client):
assert client.get("/api/health/summary").status_code == 401
@pytest.mark.parametrize(
"header",
["", "Bearer", "Token abc", "bearer abc", "Bearer not.a.jwt"],
)
def test_malformed_headers(self, client, header):
r = client.get("/api/health/summary", headers={"Authorization": header})
assert r.status_code == 401
def test_expired_token_gets_401_not_500(self, client):
past = datetime.datetime.utcnow() - datetime.timedelta(days=1)
token = jwt.encode(
{"sub": "u", "iat": past, "exp": past}, JWT_SECRET, algorithm="HS256"
)
r = client.get(
"/api/health/summary", headers={"Authorization": f"Bearer {token}"}
)
assert r.status_code == 401
assert "expired" in r.get_json()["error"]
def test_valid_token_passes(self, client, auth):
assert client.get("/api/health/summary", headers=auth).status_code == 200
class TestLogoutAndRefresh:
def test_logout_clears_stored_token(self, client, auth, user, db):
assert client.post("/api/auth/logout", headers=auth).status_code == 200
row = db.query_one("SELECT jwt_token FROM users WHERE id = ?", [user["id"]])
assert row["jwt_token"] is None
def test_refresh_returns_usable_token(self, client, auth):
r = client.post("/api/auth/refresh", headers=auth)
assert r.status_code == 200
new_token = r.get_json()["token"]
assert (
client.get(
"/api/health/summary",
headers={"Authorization": f"Bearer {new_token}"},
).status_code
== 200
)
def test_refresh_requires_auth(self, client):
assert client.post("/api/auth/refresh").status_code == 401