feat: guest passage — slip through as a wanderer
POST /auth/guest mints a real user row (wanderer-<4 hex>, collision retry, unusable random password) and issues the normal session cookie, per-IP rate limited at 5/hour. EnterPage gains the guest action; the séance shows a dismissible claim-a-name note for wanderer- users. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import secrets
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import APIRouter, Cookie, Depends, HTTPException, Request, Response, status
|
||||
@@ -9,6 +10,7 @@ from app.deps import SESSION_COOKIE_NAME, get_current_user
|
||||
from app.models.auth_session import AuthSession, SESSION_TTL, generate_session_token, hash_token
|
||||
from app.models.unlock import UnlockRecord
|
||||
from app.models.user import User
|
||||
from app.rate_limit import RateLimiter, resolve_client_ip
|
||||
from app.schemas import LoginRequest, RegisterRequest, UserOut
|
||||
from app.security import hash_password, verify_password
|
||||
|
||||
@@ -16,6 +18,15 @@ router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
_DUMMY_PASSWORD_HASH = hash_password("dummy-password-for-timing-safety")
|
||||
|
||||
# Guest creation writes a real user row per call — without a per-IP cap a
|
||||
# single client could fill the users table. resolve_client_ip (not the raw
|
||||
# socket peer) because internet traffic arrives via the Cloudflare Tunnel.
|
||||
guest_limiter = RateLimiter(max_requests=5, window_seconds=3600)
|
||||
|
||||
# 4 hex chars = 65k names; a full retry budget failing means the wanderer
|
||||
# namespace is effectively exhausted, not that we got unlucky.
|
||||
_GUEST_NAME_ATTEMPTS = 8
|
||||
|
||||
|
||||
@router.post("/register", response_model=UserOut, status_code=status.HTTP_201_CREATED)
|
||||
async def register(payload: RegisterRequest, db: AsyncSession = Depends(get_db)):
|
||||
@@ -34,6 +45,63 @@ async def register(payload: RegisterRequest, db: AsyncSession = Depends(get_db))
|
||||
return user
|
||||
|
||||
|
||||
@router.post("/guest", response_model=UserOut, status_code=status.HTTP_201_CREATED)
|
||||
async def guest(
|
||||
request: Request,
|
||||
response: Response,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
client_ip = resolve_client_ip(
|
||||
request.headers, request.client.host if request.client else None
|
||||
)
|
||||
if not guest_limiter.allow(client_ip):
|
||||
raise HTTPException(
|
||||
status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
"the veil admits only so many wanderers — return later",
|
||||
)
|
||||
|
||||
for _ in range(_GUEST_NAME_ATTEMPTS):
|
||||
username = f"wanderer-{secrets.token_hex(2)}"
|
||||
existing = await db.scalar(select(User).where(User.username == username))
|
||||
if existing is None:
|
||||
break
|
||||
else:
|
||||
raise HTTPException(
|
||||
status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
"the mist is too crowded — try again",
|
||||
)
|
||||
|
||||
# A guest is a real user: the password is random and never disclosed, so
|
||||
# the row is unreachable via /auth/login but works everywhere else.
|
||||
user = User(
|
||||
username=username,
|
||||
password_hash=hash_password(secrets.token_urlsafe(32)),
|
||||
)
|
||||
db.add(user)
|
||||
await db.commit()
|
||||
await db.refresh(user)
|
||||
|
||||
raw_token, token_hash = generate_session_token()
|
||||
session = AuthSession(
|
||||
user_id=user.id,
|
||||
token_hash=token_hash,
|
||||
expires_at=datetime.now(timezone.utc) + SESSION_TTL,
|
||||
)
|
||||
db.add(session)
|
||||
await db.commit()
|
||||
|
||||
# Same dual-scheme cookie rule as /auth/login (https tunnel vs LAN http).
|
||||
response.set_cookie(
|
||||
SESSION_COOKIE_NAME,
|
||||
raw_token,
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
secure=request.url.scheme == "https",
|
||||
max_age=int(SESSION_TTL.total_seconds()),
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
@router.post("/login", response_model=UserOut)
|
||||
async def login(
|
||||
payload: LoginRequest,
|
||||
|
||||
60
backend/tests/test_auth_guest.py
Normal file
60
backend/tests/test_auth_guest.py
Normal file
@@ -0,0 +1,60 @@
|
||||
import pytest
|
||||
|
||||
import app.routes.auth as auth_module
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_guest_limiter():
|
||||
# The limiter is module-level state; a previous test's hits would bleed
|
||||
# into the next one's per-IP budget.
|
||||
auth_module.guest_limiter._hits.clear()
|
||||
yield
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_guest_creates_wanderer_and_cookie_works_on_me(client):
|
||||
response = await client.post("/auth/guest")
|
||||
assert response.status_code == 201
|
||||
body = response.json()
|
||||
assert body["username"].startswith("wanderer-")
|
||||
assert "password" not in body
|
||||
assert "qm_session" in response.cookies
|
||||
|
||||
me_resp = await client.get("/auth/me")
|
||||
assert me_resp.status_code == 200
|
||||
assert me_resp.json()["username"] == body["username"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_guest_cannot_login_with_any_password(client):
|
||||
response = await client.post("/auth/guest")
|
||||
username = response.json()["username"]
|
||||
login_resp = await client.post(
|
||||
"/auth/login", json={"username": username, "password": "anythingatall"}
|
||||
)
|
||||
assert login_resp.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_guest_rate_limit_fires_per_ip(client):
|
||||
for _ in range(5):
|
||||
response = await client.post("/auth/guest")
|
||||
assert response.status_code == 201
|
||||
response = await client.post("/auth/guest")
|
||||
assert response.status_code == 429
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_guest_username_collision_retries(client, monkeypatch):
|
||||
taken_resp = await client.post("/auth/guest")
|
||||
taken = taken_resp.json()["username"].removeprefix("wanderer-")
|
||||
|
||||
# First attempt collides with the existing wanderer; the retry must land
|
||||
# on the fresh suffix instead of erroring out.
|
||||
suffixes = iter([taken, "f4ee"])
|
||||
monkeypatch.setattr(
|
||||
auth_module.secrets, "token_hex", lambda n: next(suffixes)
|
||||
)
|
||||
response = await client.post("/auth/guest")
|
||||
assert response.status_code == 201
|
||||
assert response.json()["username"] == "wanderer-f4ee"
|
||||
Reference in New Issue
Block a user