Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/kernelbot/api/api_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ async def _handle_discord_oauth(code: str, redirect_uri: str) -> tuple[str, str]

user_json = user_response.json()
user_id = user_json.get("id")
user_name = user_json.get("username")
user_name = user_json.get("global_name") or user_json.get("username")

if not user_id or not user_name:
raise HTTPException(
Expand Down
2 changes: 1 addition & 1 deletion src/kernelbot/api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ async def cli_auth(auth_provider: str, code: str, state: str, db_context=Depends
try:
with db_context as db:
if is_reset:
db.reset_user_from_cli(user_id, cli_id, auth_provider)
db.reset_user_from_cli(user_id, cli_id, auth_provider, user_name)
else:
db.create_user_from_cli(user_id, user_name, cli_id, auth_provider)

Expand Down
9 changes: 6 additions & 3 deletions src/libkernelbot/leaderboard_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -1811,7 +1811,9 @@ def create_user_from_cli(self, user_id: str, user_name: str, cli_id: str, auth_p
logger.exception("Could not create/update user %s from CLI.", user_id, exc_info=e)
raise KernelBotError("Database error while creating/updating user from CLI") from e

def reset_user_from_cli(self, user_id: str, cli_id: str, auth_provider: str):
def reset_user_from_cli(
self, user_id: str, cli_id: str, auth_provider: str, user_name: Optional[str] = None
):
try:
self.cursor.execute(
"""
Expand All @@ -1827,10 +1829,11 @@ def reset_user_from_cli(self, user_id: str, cli_id: str, auth_provider: str):
self.cursor.execute(
"""
UPDATE leaderboard.user_info
SET cli_id = %s, cli_auth_provider = %s, cli_valid = TRUE
SET cli_id = %s, cli_auth_provider = %s, cli_valid = TRUE,
user_name = COALESCE(%s, user_name)
WHERE id = %s
""",
(cli_id, auth_provider, user_id),
(cli_id, auth_provider, user_name or None, user_id),
)

self.connection.commit()
Expand Down
41 changes: 40 additions & 1 deletion tests/test_api_utils.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import base64
import io
from unittest.mock import MagicMock
from unittest.mock import AsyncMock, MagicMock

import pytest
from fastapi import HTTPException, UploadFile
from fastapi.testclient import TestClient


async def submit(project_root, code: bytes):
Expand Down Expand Up @@ -34,3 +36,40 @@ async def test_mojo_example_passes_submission_filters(project_root):
async def test_submissions_mentioning_streams_are_rejected(project_root):
with pytest.raises(HTTPException, match="another stream"):
await submit(project_root, b"s = torch.cuda.current_stream()\n")


@pytest.mark.asyncio
@pytest.mark.parametrize(
("global_name", "expected"),
[("Alice Öztürk", "Alice Öztürk"), (None, "alice_dev"), ("", "alice_dev")],
)
async def test_discord_oauth_prefers_global_name_with_username_fallback(monkeypatch, global_name, expected):
from kernelbot.api import api_utils

monkeypatch.setattr(api_utils.env, "CLI_DISCORD_CLIENT_ID", "discord-client-id")
monkeypatch.setattr(api_utils.env, "CLI_DISCORD_CLIENT_SECRET", "discord-client-secret")
monkeypatch.setattr(api_utils.env, "CLI_TOKEN_URL", "https://discord.example/token")
monkeypatch.setattr(api_utils.requests, "post", lambda *a, **k: MagicMock(json=lambda: {"access_token": "tok"}))
user = {"id": "123456789", "username": "alice_dev", "global_name": global_name}
monkeypatch.setattr(api_utils.requests, "get", lambda *a, **k: MagicMock(json=lambda: user))

assert await api_utils._handle_discord_oauth("code", "https://example.com/cb") == ("123456789", expected)


def test_cli_auth_reset_passes_refreshed_user_name(monkeypatch):
from kernelbot.api import main

mock_db = MagicMock()
monkeypatch.setenv("POPCORN_API_URL", "https://example.com")
monkeypatch.setattr(main, "_handle_discord_oauth", AsyncMock(return_value=("123456789", "Alice Öztürk")))
state = base64.urlsafe_b64encode(b'{"cli_id":"cli-2","is_reset":true}').decode()
main.app.dependency_overrides[main.get_db] = lambda: mock_db
try:
resp = TestClient(main.app).get(f"/auth/cli/discord?code=abc&state={state}")
assert resp.status_code == 200
assert resp.json()["user_name"] == "Alice Öztürk"
mock_db.__enter__.return_value.reset_user_from_cli.assert_called_once_with(
"123456789", "cli-2", "discord", "Alice Öztürk"
)
finally:
main.app.dependency_overrides.clear()
12 changes: 12 additions & 0 deletions tests/test_leaderboard_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -1540,3 +1540,15 @@ def test_check_rate_limit_categories_independent(database, submit_leaderboard):
# Test should be blocked
result = db.check_rate_limit("submit-leaderboard", "123", "test")
assert result["allowed"] is False


def test_reset_user_from_cli_updates_user_name(database):
with database as db:
db.init_user_from_cli("cli-1", "discord")
db.create_user_from_cli("123456789", "alice_dev", "cli-1", "discord")

db.reset_user_from_cli("123456789", "cli-2", "discord", "Alice Öztürk")
assert db.validate_cli_id("cli-2") == {"user_id": "123456789", "user_name": "Alice Öztürk"}

db.reset_user_from_cli("123456789", "cli-3", "discord")
assert db.validate_cli_id("cli-3") == {"user_id": "123456789", "user_name": "Alice Öztürk"}
Loading