Commit 0414a226 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Handle Telegram two-step verification (SESSION_PASSWORD_NEEDED) during linking

Accounts with a Telegram cloud password enabled couldn't link at all -
sign_in() raised SessionPasswordNeeded and the endpoint surfaced it as
a generic 400. /auth/telegram/login now returns 412 in that case (not
401, so apiFetch's access-token-refresh retry doesn't swallow it), and
a new /auth/telegram/password endpoint finishes the same in-progress
Pyrogram auth session with the password, via a shared _link_telegram_session
helper so both paths attach to the caller identically.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent eac2c415
Pipeline #1105 passed with stage
in 5 minutes and 15 seconds
...@@ -61,6 +61,11 @@ class TelegramLoginReq(BaseModel): ...@@ -61,6 +61,11 @@ class TelegramLoginReq(BaseModel):
code: str code: str
class TelegramPasswordReq(BaseModel):
phone_number: str
password: str
class RegisterReq(BaseModel): class RegisterReq(BaseModel):
username: str = Field(min_length=3, max_length=32, regex=r"^[a-zA-Z0-9_]+$") username: str = Field(min_length=3, max_length=32, regex=r"^[a-zA-Z0-9_]+$")
password: str = Field(min_length=8, max_length=200) password: str = Field(min_length=8, max_length=200)
...@@ -186,6 +191,22 @@ async def auth_telegram_request_code(req: RequestCodeReq, request: Request, db: ...@@ -186,6 +191,22 @@ 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))
def _link_telegram_session(db: Session, current_user: User, phone_number: str, session_string: str):
already_linked_elsewhere = (
db.query(User).filter(User.phone_number == phone_number, User.id != current_user.id).first()
)
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
# for calling telegram_sync on this user's behalf, not the API's bearer token.
current_user.telegram_session_string = session_string
current_user.phone_number = phone_number
db.commit()
return {"status": "success", "phone_number": phone_number}
@router.post("/telegram/login") @router.post("/telegram/login")
async def auth_telegram_login( async def auth_telegram_login(
req: TelegramLoginReq, req: TelegramLoginReq,
...@@ -200,22 +221,33 @@ async def auth_telegram_login( ...@@ -200,22 +221,33 @@ async def auth_telegram_login(
which silently created a disconnected identity instead of actually linking anything.""" 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 telegram_auth.PasswordRequired:
# 412 (not 401) on purpose - apiFetch treats a 401 as "access token expired" and
# transparently retries after a refresh, which would just mask this as a generic
# failure once the retry hits the same PasswordRequired again.
raise HTTPException(status_code=status.HTTP_412_PRECONDITION_FAILED, detail="Two-step verification password required")
except Exception as e: except Exception as e:
raise HTTPException(status_code=400, detail=str(e)) raise HTTPException(status_code=400, detail=str(e))
already_linked_elsewhere = ( return _link_telegram_session(db, current_user, req.phone_number, res["session_string"])
db.query(User).filter(User.phone_number == req.phone_number, User.id != current_user.id).first()
)
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
# for calling telegram_sync on this user's behalf, not the API's bearer token.
current_user.telegram_session_string = res["session_string"]
current_user.phone_number = req.phone_number
db.commit()
return {"status": "success", "phone_number": req.phone_number} @router.post("/telegram/password")
async def auth_telegram_password(
req: TelegramPasswordReq,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
"""Completes a Telegram link that /auth/telegram/login paused on with a 412 because the
account has two-step verification enabled - submits the cloud password to the same
in-progress Pyrogram auth session (kept alive server-side, see telegram_auth.PasswordRequired)
and finishes the link exactly like a password-less /auth/telegram/login would have."""
try:
res = await telegram_auth.check_password(req.phone_number, req.password)
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
return _link_telegram_session(db, current_user, req.phone_number, res["session_string"])
@router.post("/refresh", response_model=TokenResponse) @router.post("/refresh", response_model=TokenResponse)
......
from pyrogram import Client from pyrogram import Client
from pyrogram.errors import SessionPasswordNeeded
from typing import Dict from typing import Dict
import os import os
API_ID = int(os.getenv("TELEGRAM_API_ID", "2040")) # Fallback to official android app dummy API_ID = int(os.getenv("TELEGRAM_API_ID", "2040")) # Fallback to official android app dummy
API_HASH = os.getenv("TELEGRAM_API_HASH", "b18441a1ff607e10a989891a5462e627") API_HASH = os.getenv("TELEGRAM_API_HASH", "b18441a1ff607e10a989891a5462e627")
# In-memory store for ongoing auth sessions # In-memory store for ongoing auth sessions
auth_clients: Dict[str, Client] = {} auth_clients: Dict[str, Client] = {}
class PasswordRequired(Exception):
"""Raised by login() when the account has two-step verification (a cloud password)
enabled - Telegram accepted the code but won't sign in without it. The client for this
phone_number is deliberately left connected in auth_clients (not disconnected/removed)
so check_password() can finish the same in-progress auth session."""
pass
async def request_code(phone_number: str): async def request_code(phone_number: str):
client = Client(f"session_{phone_number.replace('+', '')}", api_id=API_ID, api_hash=API_HASH, in_memory=True) client = Client(f"session_{phone_number.replace('+', '')}", api_id=API_ID, api_hash=API_HASH, in_memory=True)
await client.connect() await client.connect()
...@@ -22,15 +32,36 @@ async def request_code(phone_number: str): ...@@ -22,15 +32,36 @@ async def request_code(phone_number: str):
async def login(phone_number: str, phone_code_hash: str, code: str): async def login(phone_number: str, phone_code_hash: str, code: str):
if phone_number not in auth_clients: if phone_number not in auth_clients:
raise Exception("Session expired or not found. Please request a new code.") raise Exception("Session expired or not found. Please request a new code.")
client = auth_clients[phone_number] client = auth_clients[phone_number]
try: try:
signed_in = await client.sign_in(phone_number, phone_code_hash, code) signed_in = await client.sign_in(phone_number, phone_code_hash, code)
session_string = await client.export_session_string() except SessionPasswordNeeded:
raise PasswordRequired()
except Exception as e:
await client.disconnect() await client.disconnect()
del auth_clients[phone_number] del auth_clients[phone_number]
return {"session_string": session_string, "user_id": signed_in.id} raise e
session_string = await client.export_session_string()
await client.disconnect()
del auth_clients[phone_number]
return {"session_string": session_string, "user_id": signed_in.id}
async def check_password(phone_number: str, password: str):
if phone_number not in auth_clients:
raise Exception("Session expired or not found. Please request a new code.")
client = auth_clients[phone_number]
try:
signed_in = await client.check_password(password)
except Exception as e: except Exception as e:
await client.disconnect() await client.disconnect()
del auth_clients[phone_number] del auth_clients[phone_number]
raise e raise e
session_string = await client.export_session_string()
await client.disconnect()
del auth_clients[phone_number]
return {"session_string": session_string, "user_id": signed_in.id}
...@@ -229,6 +229,85 @@ def test_auth_telegram_login_rejects_a_phone_already_linked_to_a_different_accou ...@@ -229,6 +229,85 @@ def test_auth_telegram_login_rejects_a_phone_already_linked_to_a_different_accou
assert response.status_code == 409 assert response.status_code == 409
def test_auth_telegram_login_returns_412_when_two_step_verification_is_enabled(client, auth_as, mocker):
from src.telegram_worker.telegram_auth import PasswordRequired
headers, _ = auth_as()
mocker.patch("src.telegram_worker.telegram_auth.login", side_effect=PasswordRequired())
response = client.post(
"/auth/telegram/login",
json={"phone_number": "+15550007777", "phone_code_hash": "hash123", "code": "11111"},
headers=headers,
)
assert response.status_code == 412
def test_auth_telegram_password_requires_auth(client):
response = client.post(
"/auth/telegram/password",
json={"phone_number": "+15550007777", "password": "hunter2"},
)
assert response.status_code == 401
def test_auth_telegram_password_completes_the_link(client, db_session, auth_as, mocker):
headers, user = auth_as()
mocker.patch(
"src.telegram_worker.telegram_auth.check_password",
return_value={"session_string": "super-secret-telegram-session-2fa", "user_id": 918276},
)
response = client.post(
"/auth/telegram/password",
json={"phone_number": "+15550007777", "password": "hunter2"},
headers=headers,
)
assert response.status_code == 200
assert "super-secret-telegram-session-2fa" not in response.text
db_session.refresh(user)
assert user.telegram_session_string == "super-secret-telegram-session-2fa"
assert user.phone_number == "+15550007777"
def test_auth_telegram_password_rejects_a_phone_already_linked_to_a_different_account(client, auth_as, mocker):
headers_a, _ = auth_as()
headers_b, _ = auth_as()
mocker.patch(
"src.telegram_worker.telegram_auth.login",
return_value={"session_string": "sess-a", "user_id": 918277},
)
client.post(
"/auth/telegram/login",
json={"phone_number": "+15550008888", "phone_code_hash": "hash123", "code": "11111"},
headers=headers_a,
)
mocker.patch(
"src.telegram_worker.telegram_auth.check_password",
return_value={"session_string": "sess-b", "user_id": 918278},
)
response = client.post(
"/auth/telegram/password",
json={"phone_number": "+15550008888", "password": "hunter2"},
headers=headers_b,
)
assert response.status_code == 409
def test_auth_telegram_password_upstream_failure_returns_400(client, auth_as, mocker):
headers, _ = auth_as()
mocker.patch(
"src.telegram_worker.telegram_auth.check_password",
side_effect=Exception("Invalid password"),
)
response = client.post(
"/auth/telegram/password",
json={"phone_number": "+15550009191", "password": "wrongpass"},
headers=headers,
)
assert response.status_code == 400
def test_auth_refresh_and_logout(client): def test_auth_refresh_and_logout(client):
# A real DB-backed refresh token, via a normal registration - auth_as mints a bare # 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. # access token directly and has no matching refresh_tokens row to rotate/revoke.
......
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