Commit eac2c415 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Fix /auth/telegram/login to actually link to the caller's account

It was documented as an account-linking flow (attach a Telegram session to
the already-logged-in user) but the code never changed to match - it still
created/looked up a *separate* User row keyed by Telegram's own numeric
user_id and issued that identity a fresh token pair, same as the old
Telegram-is-the-login design it was supposed to replace. Silently
pointless: nothing actually got linked to whoever was logged in.

Now requires an authenticated caller and attaches telegram_session_string
+ phone_number directly to current_user, no new tokens issued (the caller
already has valid ones). Returns 409 if that Telegram account is already
linked to a different Stax user. Found and fixed while helping the user
actually test the chat-scanning feature against their real account.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 575d3a59
Pipeline #1101 passed with stage
in 10 minutes and 45 seconds
...@@ -186,28 +186,36 @@ async def auth_telegram_request_code(req: RequestCodeReq, request: Request, db: ...@@ -186,28 +186,36 @@ async def auth_telegram_request_code(req: RequestCodeReq, request: Request, db:
raise HTTPException(status_code=400, detail=str(e)) raise HTTPException(status_code=400, detail=str(e))
@router.post("/telegram/login", response_model=TokenResponse) @router.post("/telegram/login")
async def auth_telegram_login(req: TelegramLoginReq, db: Session = Depends(get_db)): async def auth_telegram_login(
"""Links a Telegram account (for the chat-scanning music-tagging feature) rather than req: TelegramLoginReq,
being the primary login path - see /auth/register and /auth/login for that. Still db: Session = Depends(get_db),
issues our own tokens too, since a Telegram-only user (no username/password set) needs current_user: User = Depends(get_current_user),
some way to authenticate.""" ):
"""Links a Telegram account (for the chat-scanning music-tagging feature) to the
caller's already-authenticated Stax account - this requires a real login first (see
/auth/register and /auth/login), it is not itself a way to sign in. Attaches to
current_user directly rather than creating/looking up a separate row keyed by
Telegram's own numeric user id - a previous version of this endpoint did the latter,
which silently created a disconnected identity instead of actually linking anything."""
try: try:
res = await telegram_auth.login(req.phone_number, req.phone_code_hash, req.code) res = await telegram_auth.login(req.phone_number, req.phone_code_hash, req.code)
except Exception as e: except Exception as e:
raise HTTPException(status_code=400, detail=str(e)) raise HTTPException(status_code=400, detail=str(e))
user = db.query(User).filter(User.id == res["user_id"]).first() already_linked_elsewhere = (
if not user: db.query(User).filter(User.phone_number == req.phone_number, User.id != current_user.id).first()
user = User(id=res["user_id"], phone_number=req.phone_number) )
db.add(user) if already_linked_elsewhere:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="This Telegram account is already linked to a different Stax account")
# Session string never leaves the server from here on - it's our internal credential # Session string never leaves the server from here on - it's our internal credential
# for calling telegram_sync on this user's behalf, not the API's bearer token. # for calling telegram_sync on this user's behalf, not the API's bearer token.
user.telegram_session_string = res["session_string"] current_user.telegram_session_string = res["session_string"]
user.phone_number = req.phone_number current_user.phone_number = req.phone_number
db.commit() db.commit()
return _issue_tokens(db, user.id) return {"status": "success", "phone_number": req.phone_number}
@router.post("/refresh", response_model=TokenResponse) @router.post("/refresh", response_model=TokenResponse)
......
...@@ -170,12 +170,25 @@ def test_auth_telegram_request_code_rate_limited_per_phone(client, mocker): ...@@ -170,12 +170,25 @@ def test_auth_telegram_request_code_rate_limited_per_phone(client, mocker):
assert response.status_code == 429 assert response.status_code == 429
def test_auth_telegram_login_missing_fields(client): def test_auth_telegram_login_requires_auth(client):
response = client.post("/auth/telegram/login", json={"phone_number": "+1234567890"}) response = client.post(
"/auth/telegram/login",
json={"phone_number": "+1234567890", "phone_code_hash": "hash123", "code": "11111"},
)
assert response.status_code == 401
def test_auth_telegram_login_missing_fields(client, auth_as):
headers, _ = auth_as()
response = client.post("/auth/telegram/login", json={"phone_number": "+1234567890"}, headers=headers)
assert response.status_code == 422 assert response.status_code == 422
def test_auth_telegram_login_issues_jwt_and_never_exposes_session_string(client, db_session, mocker): def test_auth_telegram_login_links_to_the_caller_not_a_separate_identity(client, db_session, auth_as, mocker):
# Regression test: this endpoint used to create/find a *separate* User row keyed by
# Telegram's own numeric user_id, completely disconnected from whoever was actually
# logged in - silently defeating the point of "linking". It must attach to the caller.
headers, user = auth_as()
mocker.patch( mocker.patch(
"src.telegram_worker.telegram_auth.login", "src.telegram_worker.telegram_auth.login",
return_value={"session_string": "super-secret-telegram-session", "user_id": 918273}, return_value={"session_string": "super-secret-telegram-session", "user_id": 918273},
...@@ -183,26 +196,44 @@ def test_auth_telegram_login_issues_jwt_and_never_exposes_session_string(client, ...@@ -183,26 +196,44 @@ def test_auth_telegram_login_issues_jwt_and_never_exposes_session_string(client,
response = client.post( response = client.post(
"/auth/telegram/login", "/auth/telegram/login",
json={"phone_number": "+15550004444", "phone_code_hash": "hash123", "code": "11111"}, json={"phone_number": "+15550004444", "phone_code_hash": "hash123", "code": "11111"},
headers=headers,
) )
assert response.status_code == 200 assert response.status_code == 200
body = response.json()
assert "access_token" in body and "refresh_token" in body
assert "super-secret-telegram-session" not in response.text assert "super-secret-telegram-session" not in response.text
user = db_session.query(User).filter(User.id == 918273).first() db_session.refresh(user)
assert user is not None
assert user.telegram_session_string == "super-secret-telegram-session" assert user.telegram_session_string == "super-secret-telegram-session"
assert user.phone_number == "+15550004444"
# No stray row was created for Telegram's own user_id (918273) either.
assert db_session.query(User).filter(User.id == 918273).first() is None
def test_auth_refresh_and_logout(client, mocker): def test_auth_telegram_login_rejects_a_phone_already_linked_to_a_different_account(client, auth_as, mocker):
headers_a, user_a = auth_as()
headers_b, _ = auth_as()
mocker.patch( mocker.patch(
"src.telegram_worker.telegram_auth.login", "src.telegram_worker.telegram_auth.login",
return_value={"session_string": "sess-abc", "user_id": 918274}, return_value={"session_string": "sess-a", "user_id": 918275},
)
client.post(
"/auth/telegram/login",
json={"phone_number": "+15550006666", "phone_code_hash": "hash123", "code": "11111"},
headers=headers_a,
) )
login_res = client.post(
response = client.post(
"/auth/telegram/login", "/auth/telegram/login",
json={"phone_number": "+15550005555", "phone_code_hash": "hash123", "code": "11111"}, json={"phone_number": "+15550006666", "phone_code_hash": "hash123", "code": "11111"},
headers=headers_b,
) )
assert response.status_code == 409
def test_auth_refresh_and_logout(client):
# A real DB-backed refresh token, via a normal registration - auth_as mints a bare
# access token directly and has no matching refresh_tokens row to rotate/revoke.
client.post("/auth/register", json={"username": "refreshlogouttest", "password": "correcthorse1"})
login_res = client.post("/auth/login", json={"username": "refreshlogouttest", "password": "correcthorse1"})
refresh_token = login_res.json()["refresh_token"] refresh_token = login_res.json()["refresh_token"]
refreshed = client.post("/auth/refresh", json={"refresh_token": refresh_token}) refreshed = client.post("/auth/refresh", json={"refresh_token": refresh_token})
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment