Skip to content
Merged
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
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ yoyo apply src/migrations -d postgresql://user:password@localhost/clusterdev

See [docs/database.md](docs/database.md) for migration patterns and creating new migrations.

Users can change their display name up to three times total through `popcorn rename "New Name"`.
The name applies to all past and future submissions. Invalid requests and requests to keep the
same name do not use a change. `PATCH /user/profile` accepts `{"display_name": "New Name"}`
using existing CLI authentication and returns the saved name and remaining changes.
Names are trimmed and must contain 1–32 printable characters.

For production incident triage, see [docs/production-debugging.md](docs/production-debugging.md).
For nightly end-to-end kernel checks, see
[docs/application-validation.md](docs/application-validation.md).
Expand Down
20 changes: 20 additions & 0 deletions src/kernelbot/api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from fastapi import Depends, FastAPI, Form, Header, HTTPException, Query, Request, UploadFile
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, ConfigDict, StrictStr

from kernelbot.env import env
from libkernelbot.application_validation import ApplicationValidationService
Expand Down Expand Up @@ -265,6 +266,24 @@ def enforce_leaderboard_access(db, leaderboard_name: str, user_info: Optional[di
raise HTTPException(status_code=403, detail="You do not have access to this leaderboard")


class DisplayNameUpdate(BaseModel):
model_config = ConfigDict(extra="forbid")
display_name: StrictStr


@app.patch("/user/profile")
async def rename_user(
payload: DisplayNameUpdate,
user_info: Annotated[dict, Depends(validate_cli_header)],
db_context=Depends(get_db),
) -> dict:
try:
with db_context as db:
return db.rename_user(user_info["user_id"], payload.display_name)
except KernelBotError as e:
raise HTTPException(status_code=e.http_code, detail=str(e)) from e


@app.get("/auth/init")
async def auth_init(provider: str, db_context=Depends(get_db)) -> dict:
if provider not in ["discord", "github"]:
Expand Down Expand Up @@ -373,6 +392,7 @@ async def cli_auth(auth_provider: str, code: str, state: str, db_context=Depends
db.reset_user_from_cli(user_id, cli_id, auth_provider)
else:
db.create_user_from_cli(user_id, user_name, cli_id, auth_provider)
user_name = db.get_user_from_id(user_id)

except AttributeError as e:
raise HTTPException(
Expand Down
49 changes: 49 additions & 0 deletions src/libkernelbot/leaderboard_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
logger = setup_logging(__name__)

DAILY_SUBMISSION_LIMIT = 100
DISPLAY_NAME_CHANGE_LIMIT = 3


class LeaderboardDB:
Expand Down Expand Up @@ -271,6 +272,54 @@ def validate_identity(
logger.exception("Error validating %s %s", human_label, identifier, exc_info=e)
raise KernelBotError(f"Error validating {human_label}") from e

def rename_user(self, user_id: str, display_name: str) -> dict:
display_name = display_name.strip()
if not 1 <= len(display_name) <= 32 or not display_name.isprintable():
raise KernelBotError("Display name must be 1–32 printable characters.", code=400)

try:
# Serialize concurrent requests against the user's lifetime allowance.
self.cursor.execute(
"""
SELECT user_name, display_name_changes
FROM leaderboard.user_info WHERE id = %s FOR UPDATE
""",
(user_id,),
)
row = self.cursor.fetchone()
if row is None:
raise KernelBotError("User not found.", code=404)
current_name, changes = row
if display_name != current_name:
if changes >= DISPLAY_NAME_CHANGE_LIMIT:
raise KernelBotError(
"Display name change limit reached: you can change your name 3 times total.",
code=403,
)
self.cursor.execute(
"""
UPDATE leaderboard.user_info
SET user_name = %s, display_name_changes = display_name_changes + 1
WHERE id = %s
""",
(display_name, user_id),
)
changes += 1
# Historical submissions join this row by user_id, so their names update too.
self.connection.commit()
return {
"user_id": user_id,
"display_name": display_name,
"renames_remaining": DISPLAY_NAME_CHANGE_LIMIT - changes,
}
except KernelBotError:
self.connection.rollback()
raise
except psycopg2.Error as e:
self.connection.rollback()
logger.exception("Could not change display name for user %s", user_id)
raise KernelBotError("Could not change display name. Please try again.", code=500) from e

def create_submission(
self,
leaderboard: str,
Expand Down
16 changes: 16 additions & 0 deletions src/migrations/20261130_02_display-name-changes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""Track each user's lifetime display-name change allowance."""

from yoyo import step

__depends__ = {"20261130_01_daily-submission-limit"}

steps = [
step(
"""
ALTER TABLE leaderboard.user_info
ADD COLUMN display_name_changes INTEGER NOT NULL DEFAULT 0
CHECK (display_name_changes BETWEEN 0 AND 3)
""",
"ALTER TABLE leaderboard.user_info DROP COLUMN display_name_changes",
),
]
265 changes: 265 additions & 0 deletions tests/test_user_profile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,265 @@
"""Display-name changes use one authenticated, lifetime allowance in PostgreSQL."""

import base64
import datetime
import json
from concurrent.futures import ThreadPoolExecutor
from threading import Barrier
from unittest.mock import AsyncMock

import pytest
from fastapi.testclient import TestClient
from test_leaderboard_db import _create_submission_run, _submit_leaderboard

from libkernelbot.db_types import IdentityType
from libkernelbot.leaderboard_db import LeaderboardDB
from libkernelbot.utils import KernelBotError

USER_ID = "profile-user"
CLI_HEADERS = {"X-Popcorn-Cli-Id": "profile-cli-token"}
WEB_HEADERS = {"X-Web-Auth-Id": "profile-web-token"}


@pytest.fixture
def profile_user(database):
with database as db:
db.cursor.execute(
"""
INSERT INTO leaderboard.user_info
(id, user_name, cli_id, cli_valid, cli_auth_provider, web_auth_id)
VALUES (%s, 'Original', %s, TRUE, 'github', %s)
""",
(USER_ID, CLI_HEADERS["X-Popcorn-Cli-Id"], WEB_HEADERS["X-Web-Auth-Id"]),
)
db.connection.commit()
return USER_ID


@pytest.fixture
def profile_client(database, profile_user):
from kernelbot.api.main import app, get_db

previous_overrides = app.dependency_overrides.copy()
# Keep real authentication and database methods, with a connection per request.
app.dependency_overrides[get_db] = lambda: LeaderboardDB(database.url, database.ssl_mode)
client = TestClient(app)
try:
yield client
finally:
client.close()
app.dependency_overrides.clear()
app.dependency_overrides.update(previous_overrides)


def _profile(name, remaining):
return {"user_id": USER_ID, "display_name": name, "renames_remaining": remaining}


def _read_profile(database, user_id=USER_ID):
with database as db:
db.cursor.execute(
"SELECT user_name, display_name_changes FROM leaderboard.user_info WHERE id = %s",
(user_id,),
)
name, changes = db.cursor.fetchone()
return {"user_id": user_id, "display_name": name, "renames_remaining": 3 - changes}


def test_cli_allows_three_lifetime_renames(profile_client, database):
assert _read_profile(database) == _profile("Original", 3)
for name, remaining in [(" First ", 2), ("Second", 1), ("Third", 0)]:
response = profile_client.patch(
"/user/profile", headers=CLI_HEADERS, json={"display_name": name}
)
assert response.status_code == 200
assert response.json() == _profile(name.strip(), remaining)
assert _read_profile(database) == response.json()

response = profile_client.patch(
"/user/profile", headers=CLI_HEADERS, json={"display_name": "Fourth"}
)
assert response.status_code == 403
assert "3 times total" in response.json()["detail"]
assert _read_profile(database) == _profile("Third", 0)


@pytest.mark.parametrize("display_name", ["x", "a" * 32, "café 🐱"])
def test_printable_names_and_length_boundaries(profile_client, display_name):
response = profile_client.patch(
"/user/profile", headers=CLI_HEADERS, json={"display_name": display_name}
)
assert response.status_code == 200
assert response.json() == _profile(display_name, 2)


@pytest.mark.parametrize(
("payload", "status"),
[
({"display_name": ""}, 400),
({"display_name": " "}, 400),
({"display_name": "a" * 33}, 400),
({"display_name": "bad\nname"}, 400),
({"display_name": "bad\tname"}, 400),
({"display_name": "bad\x00name"}, 400),
({"display_name": 123}, 422),
({"display_name": None}, 422),
({}, 422),
],
)
def test_invalid_names_do_not_spend_allowance(profile_client, database, payload, status):
response = profile_client.patch("/user/profile", headers=CLI_HEADERS, json=payload)
assert response.status_code == status
assert _read_profile(database) == _profile("Original", 3)


def test_noop_does_not_spend_allowance_even_when_exhausted(profile_client):
for name, remaining in [("Original", 3), ("One", 2), ("Two", 1), ("Three", 0)]:
response = profile_client.patch(
"/user/profile", headers=CLI_HEADERS, json={"display_name": name}
)
assert response.status_code == 200
response = profile_client.patch(
"/user/profile", headers=CLI_HEADERS, json={"display_name": f" {name} "}
)
assert response.status_code == 200
assert response.json() == _profile(name, remaining)


@pytest.mark.parametrize(
("headers", "status"),
[({}, 400), ({"X-Popcorn-Cli-Id": "forged"}, 401), (WEB_HEADERS, 400)],
)
def test_rename_requires_valid_cli_authentication(profile_client, database, headers, status):
assert (
profile_client.patch(
"/user/profile", headers=headers, json={"display_name": "Unauthorized"}
).status_code
== status
)
assert _read_profile(database) == _profile("Original", 3)


def test_payload_cannot_choose_another_user_or_override_allowance(profile_client, database):
with database as db:
db.cursor.execute(
"INSERT INTO leaderboard.user_info (id, user_name) VALUES ('victim', 'Victim')"
)
db.connection.commit()
for extra in [{"user_id": "victim"}, {"renames_remaining": 100}, {"display_name_changes": 0}]:
response = profile_client.patch(
"/user/profile", headers=CLI_HEADERS, json={"display_name": "Forged", **extra}
)
assert response.status_code == 422
assert _read_profile(database) == _profile("Original", 3)
assert _read_profile(database, "victim")["display_name"] == "Victim"
assert _read_profile(database, "victim")["renames_remaining"] == 3


def test_concurrent_last_rename_cannot_exceed_lifetime_allowance(database, profile_user):
with database as db:
db.rename_user(USER_ID, "First")
db.rename_user(USER_ID, "Second")
barrier = Barrier(2)

def rename(name):
with LeaderboardDB(database.url, database.ssl_mode) as db:
barrier.wait(timeout=10)
try:
return "accepted", db.rename_user(USER_ID, name)
except KernelBotError as error:
assert error.http_code == 403
return "limited", None

with ThreadPoolExecutor(max_workers=2) as pool:
results = list(pool.map(rename, ["Concurrent A", "Concurrent B"]))
assert sorted(status for status, _ in results) == ["accepted", "limited"]
winner = next(profile for status, profile in results if status == "accepted")
assert _read_profile(database) == winner
with database as db:
assert winner["renames_remaining"] == 0
db.cursor.execute(
"SELECT display_name_changes FROM leaderboard.user_info WHERE id = %s", (USER_ID,)
)
assert db.cursor.fetchone() == (3,)


def test_rename_updates_all_historical_rankings_without_changing_results(
database, profile_user, task_directory
):
boards = ["rename-first", "rename-second"]
for board in boards:
_submit_leaderboard(database, task_directory, name=board)
with database as db:
for score in (10.0, 20.0):
submission_id = db.create_submission(
board,
"submission.py",
USER_ID,
f"code {score}",
datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=1),
user_name="Provider name",
)
_create_submission_run(db, submission_id, score=score)
_create_submission_run(db, submission_id, score=score, secret=True)

def read_entries(db):
return [
entry
for board in boards
for user in (None, USER_ID)
for entry in db.get_leaderboard_submissions(board, "A100", user_id=user)
]

def read_results(db):
db.cursor.execute("SELECT id, user_id FROM leaderboard.submission ORDER BY id")
submissions = db.cursor.fetchall()
db.cursor.execute("SELECT id, submission_id, score FROM leaderboard.runs ORDER BY id")
return submissions, db.cursor.fetchall()

with database as db:
before_entries = read_entries(db)
before_results = read_results(db)
assert len(before_entries) == 6 # One public best and two personal entries per board.
assert all(entry["user_name"] == "Original" for entry in before_entries)
db.rename_user(USER_ID, "Chosen name")
assert read_entries(db) == [
{**entry, "user_name": "Chosen name"} for entry in before_entries
]
assert read_results(db) == before_results


def test_reregister_and_new_submission_preserve_chosen_name_and_allowance(
profile_client, database, task_directory, monkeypatch
):
from kernelbot.api import main as api

_submit_leaderboard(database, task_directory, name="rename-persistence")
renamed = profile_client.patch(
"/user/profile", headers=CLI_HEADERS, json={"display_name": "Chosen name"}
)
assert renamed.status_code == 200
monkeypatch.setenv("POPCORN_API_URL", "http://testserver")
monkeypatch.setattr(
api, "_handle_github_oauth", AsyncMock(return_value=(USER_ID, "Provider name"))
)
state = base64.urlsafe_b64encode(
json.dumps({"cli_id": "replacement-cli-token", "is_reset": True}).encode()
).decode()
response = profile_client.get("/auth/cli/github", params={"code": "test-code", "state": state})
assert response.status_code == 200
assert response.json()["user_name"] == "Chosen name"
with database as db:
assert db.validate_identity(CLI_HEADERS["X-Popcorn-Cli-Id"], IdentityType.CLI) is None
assert (
db.validate_identity("replacement-cli-token", IdentityType.CLI)["user_name"]
== "Chosen name"
)
db.create_submission(
"rename-persistence",
"submission.py",
USER_ID,
"code",
datetime.datetime.now(datetime.timezone.utc),
user_name="Provider name",
)
assert _read_profile(database) == _profile("Chosen name", 2)
Loading