Merge pull request #2 from ShayManor/oauth

Oauth
This commit is contained in:
Shay Manor
2026-04-19 21:02:25 -04:00
committed by GitHub
16 changed files with 924 additions and 454 deletions
+4
View File
@@ -80,4 +80,8 @@ jobs:
IMAGE_TAG: ${{ needs.build.outputs.image_tag }}
GITHUB_PAT: ${{ secrets.FETCHER_GITHUB_PAT }}
FETCHER_INTERNAL_TOKEN: ${{ secrets.FETCHER_INTERNAL_TOKEN }}
GH_OAUTH_CLIENT_ID: ${{ secrets.GH_OAUTH_CLIENT_ID }}
GH_OAUTH_CLIENT_SECRET: ${{ secrets.GH_OAUTH_CLIENT_SECRET }}
GENERATOR_SECRET_KEY: ${{ secrets.GENERATOR_SECRET_KEY }}
ALLOWED_ORIGINS: ${{ secrets.ALLOWED_ORIGINS }}
run: ./deploy/deploy.sh
+4
View File
@@ -33,6 +33,10 @@ services:
environment:
FETCHER_URL: http://fetcher:5001
FETCHER_INTERNAL_TOKEN: ${FETCHER_INTERNAL_TOKEN:?missing FETCHER_INTERNAL_TOKEN}
GH_OAUTH_CLIENT_ID: ${GH_OAUTH_CLIENT_ID:?missing GH_OAUTH_CLIENT_ID}
GH_OAUTH_CLIENT_SECRET: ${GH_OAUTH_CLIENT_SECRET:?missing GH_OAUTH_CLIENT_SECRET}
GENERATOR_SECRET_KEY: ${GENERATOR_SECRET_KEY:?missing GENERATOR_SECRET_KEY}
ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-https://gh-stats.com}
volumes:
- ${HOME}/ghstats/data/generator:/app/data
ports:
+16 -11
View File
@@ -3,9 +3,10 @@ import './index.css'
import { SearchScreen } from './screens/SearchScreen'
import { WorkshopScreen } from './screens/WorkshopScreen'
import { ResultScreen } from './screens/ResultScreen'
import { AuthButton } from './components/AuthButton'
import type { WidgetData } from './lib/renderWidgets'
import { DEMO_WIDGET_DATA } from './lib/demoData'
import { authHeaders, saveEditToken } from './lib/editToken'
import { fetchMe, type Me } from './lib/auth'
export type Achievement = {
title: string
@@ -49,6 +50,7 @@ const POLL_INTERVAL_MS = 2000
const POLL_TIMEOUT_MS = 120_000
export default function App() {
const [me, setMe] = useState<Me>({ login: null })
const [step, setStep] = useState<Step>('search')
const [username, setUsername] = useState('')
const [settings, setSettings] = useState<WidgetSettings>({ ...DEFAULT_SETTINGS })
@@ -72,6 +74,7 @@ export default function App() {
}, [])
useEffect(() => stopPolling, [stopPolling])
useEffect(() => { fetchMe().then(setMe) }, [])
const startFetch = useCallback((user: string) => {
stopPolling()
@@ -88,12 +91,8 @@ export default function App() {
const r = await fetch(`/api/${encodeURIComponent(user)}/data`)
if (aborted.current) return
const body = await r.json().catch(
() => ({} as { status?: string; data?: WidgetData; edit_token?: string })
() => ({} as { status?: string; data?: WidgetData })
)
// The 202 auto-enroll response surfaces an edit_token exactly once
// per fresh username. Persist it so PATCH /settings and POST
// /refresh can authenticate this browser as the profile owner.
if (body.edit_token) saveEditToken(user, body.edit_token)
const status = body.status
if (r.status === 200 && status === 'ready' && body.data) {
@@ -156,10 +155,8 @@ export default function App() {
}
const patchRes = await fetch(`/api/${encodeURIComponent(username)}/settings`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
...authHeaders(username),
},
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(backendSettings),
})
if (!patchRes.ok && patchRes.status !== 404) {
@@ -167,7 +164,10 @@ export default function App() {
return
}
const r = await fetch(`/api/${encodeURIComponent(username)}/generate`, { method: 'POST' })
const r = await fetch(`/api/${encodeURIComponent(username)}/generate`, {
method: 'POST',
credentials: 'include',
})
if (r.status === 404) {
const body = await r.json().catch(() => ({} as { status?: string }))
setGenerateError(body.status === 'not_found' ? 'User not found' : 'Not enrolled')
@@ -204,6 +204,9 @@ export default function App() {
return (
<div className="min-h-screen bg-gray-50">
<div className="header-bar">
<AuthButton me={me} onChange={setMe} />
</div>
{step === 'search' && (
<SearchScreen onSearch={handleSearch} />
)}
@@ -217,6 +220,8 @@ export default function App() {
fetchDone={fetchDone}
fetchError={fetchError}
widgetData={widgetData}
me={me}
onAuthChange={setMe}
/>
)}
{step === 'result' && (
@@ -0,0 +1,21 @@
import type { Me } from '../lib/auth'
import { signInUrl, signOut } from '../lib/auth'
export function AuthButton({ me, onChange }: { me: Me; onChange: (m: Me) => void }) {
if (!me.login) {
return (
<a className="auth-btn" href={signInUrl()}>
Sign in with GitHub
</a>
)
}
return (
<div className="auth-chip">
{me.avatar_url && <img src={me.avatar_url} alt="" className="auth-avatar" />}
<span>{me.login}</span>
<button onClick={async () => { await signOut(); onChange({ login: null }) }}>
Sign out
</button>
</div>
)
}
+20
View File
@@ -0,0 +1,20 @@
export type Me = { login: string | null; avatar_url?: string }
export async function fetchMe(): Promise<Me> {
const r = await fetch('/api/auth/me', { credentials: 'include' })
if (!r.ok) return { login: null }
return r.json() as Promise<Me>
}
export function signInUrl(next?: string): string {
const n = next ?? (window.location.pathname + window.location.search)
return `/api/auth/github/login?next=${encodeURIComponent(n)}`
}
export async function signOut(): Promise<void> {
await fetch('/api/auth/logout', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
})
}
-36
View File
@@ -1,36 +0,0 @@
// Per-username edit token issued by the backend at enrollment. Presented
// as `Authorization: Bearer` on mutating endpoints (PATCH settings,
// POST refresh). Stored in localStorage so a reload keeps the user in
// control of their own profile.
//
// Without this token the backend rejects mutations with HTTP 401. Token is
// only surfaced on the FIRST enroll for a given username — re-hitting the
// enroll path for an existing user returns no token, so we never blow away
// a previously-saved token.
const STORAGE_PREFIX = 'grs:edit_token:'
const keyFor = (username: string) => STORAGE_PREFIX + username.toLowerCase()
export function getEditToken(username: string): string | null {
if (!username) return null
try {
return window.localStorage.getItem(keyFor(username))
} catch {
return null
}
}
export function saveEditToken(username: string, token: string | null | undefined): void {
if (!username || !token) return
try {
window.localStorage.setItem(keyFor(username), token)
} catch {
// localStorage can throw in private mode — fall through silently.
}
}
export function authHeaders(username: string): Record<string, string> {
const t = getEditToken(username)
return t ? { Authorization: `Bearer ${t}` } : {}
}
@@ -2,6 +2,8 @@ import { useState, useMemo, type ReactNode } from 'react'
import DOMPurify from 'dompurify'
import type { WidgetSettings, Achievement, PerWidgetSettings } from '../App'
import { renderAllWidgets, type WidgetData } from '../lib/renderWidgets'
import { signInUrl } from '../lib/auth'
import type { Me } from '../lib/auth'
// Defense-in-depth: the client-rendered preview assembles SVG from
// GitHub-sourced strings (collaborator logins, repo names) and user-typed
@@ -214,6 +216,8 @@ type Props = {
fetchDone: boolean
fetchError: string | null
widgetData: WidgetData | null
me: Me
onAuthChange?: (m: Me) => void
}
export function WorkshopScreen({
@@ -225,7 +229,9 @@ export function WorkshopScreen({
fetchDone,
fetchError,
widgetData,
me,
}: Props) {
const canEdit = !!me.login && me.login.toLowerCase() === username.toLowerCase()
const [expandedWidget, setExpandedWidget] = useState<string | null>(null)
const updateSetting = <K extends keyof WidgetSettings>(key: K, val: WidgetSettings[K]) => {
@@ -312,6 +318,17 @@ export function WorkshopScreen({
</div>
)}
{!canEdit && (
<div className="banner">
{me.login
? `Signed in as ${me.login}. You can only edit your own widget.`
: <a href={signInUrl()}>Sign in with GitHub to edit your widget</a>}
</div>
)}
{/* Theme, Widgets, Achievements editor, Generate — owner-only */}
{canEdit && (
<>
{/* Theme */}
<div className="mb-5">
<div className="text-[10px] uppercase tracking-wider text-gray-400 font-medium mb-3">Theme</div>
@@ -539,6 +556,8 @@ export function WorkshopScreen({
>
Generate →
</button>
</>
)}
</div>
{/* Right preview area */}
+1
View File
@@ -5,3 +5,4 @@ requests==2.32.3
pytest==8.3.3
responses==0.25.3
gunicorn==23.0.0
authlib>=1.3,<2
+158 -89
View File
@@ -19,11 +19,12 @@ import os
import time
from collections import defaultdict, deque
from concurrent.futures import ThreadPoolExecutor
from datetime import timedelta
from functools import wraps
from threading import BoundedSemaphore, Lock
from flask import Flask, jsonify, request, Response, send_from_directory
from flask import Flask, jsonify, request, Response, send_from_directory, session
from . import config, db, fetcher_client, placeholder
from . import auth, config, db, fetcher_client, placeholder
from .themes import THEMES
from .utils import is_valid_username, settings_size_ok
import json as _json
@@ -79,11 +80,11 @@ _RATE_LIMITS = {
# (endpoint_key): (max_hits, window_seconds). Defaults set in config.py
# lean toward the mini PC — tighten further via env without redeploying.
"mutate": (config.RATE_LIMIT_MUTATE_MAX, config.RATE_LIMIT_MUTATE_WINDOW),
"enroll": (config.RATE_LIMIT_ENROLL_MAX, config.RATE_LIMIT_ENROLL_WINDOW),
"read": (config.RATE_LIMIT_READ_MAX, config.RATE_LIMIT_READ_WINDOW),
}
_rate_lock = Lock()
_rate_hits: dict[tuple[str, str], deque] = defaultdict(deque)
_rate_hits_per_login: dict[tuple[str, str], deque] = defaultdict(deque)
def _client_ip() -> str:
@@ -111,46 +112,66 @@ def _rate_limit(bucket: str) -> bool:
return True
def _rate_limit_per_login(bucket: str, login: str) -> bool:
"""Per-login rate limit layered on top of per-IP limit.
Returns True if allowed; False if the login has exceeded the limit.
If no login (unauthenticated), returns True (per-IP already covers it).
"""
if not login:
return True # per-IP already covers the unauth path
if bucket == "mutate":
limit, window = config.RATE_LIMIT_MUTATE_PER_LOGIN_MAX, config.RATE_LIMIT_MUTATE_PER_LOGIN_WINDOW
else:
return True
now = time.time()
cutoff = now - window
key = (bucket, login)
with _rate_lock:
q = _rate_hits_per_login[key]
while q and q[0] < cutoff:
q.popleft()
if len(q) >= limit:
return False
q.append(now)
return True
def rate_limited(bucket: str):
def deco(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if not _rate_limit(bucket):
return jsonify({"error": "rate_limited"}), 429
if not _rate_limit_per_login(bucket, auth.current_login() or ""):
return jsonify({"error": "rate_limited"}), 429
return fn(*args, **kwargs)
return wrapper
return deco
def _extract_bearer() -> str:
"""Read the caller-presented edit token. Accepts either
`Authorization: Bearer <t>` or `X-Edit-Token: <t>`."""
hdr = request.headers.get("Authorization", "")
if hdr.startswith("Bearer "):
return hdr[len("Bearer "):].strip()
return request.headers.get("X-Edit-Token", "").strip()
def require_edit_token(fn):
"""Enforce per-user bearer token on mutating endpoints.
The token is issued once at enrollment (see db.enroll) and hashed at rest.
Without it, anyone could overwrite any registrant's settings — these
endpoints used to live behind a no-op decorator."""
@wraps(fn)
def wrapper(username: str, *args, **kwargs):
if not is_valid_username(username):
return jsonify({"error": "invalid_username"}), 400
presented = _extract_bearer()
if not presented or not db.verify_edit_token(username, presented):
return jsonify({"error": "unauthorized"}), 401
return fn(username, *args, **kwargs)
return wrapper
_STATIC_DIR = os.path.join(os.path.dirname(__file__), "static")
app = Flask(__name__, static_folder=None)
if config.SECRET_KEY:
app.secret_key = config.SECRET_KEY
else:
# In tests and local dev we allow a weak default; production must set the env.
app.secret_key = "dev-insecure-secret-do-not-use-in-prod"
app.config.update(
SESSION_COOKIE_NAME="gh_session",
SESSION_COOKIE_SECURE=config.SESSION_COOKIE_SECURE,
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE="Lax",
PERMANENT_SESSION_LIFETIME=timedelta(days=30),
)
auth.init_oauth(app)
# Reject oversized bodies before they reach the DB. 128 KB is generous for our
# settings shape and still caps the memory footprint of a flood of PATCHes.
app.config["MAX_CONTENT_LENGTH"] = 128 * 1024
@@ -293,12 +314,6 @@ def sanitize_settings(body: dict) -> dict:
return out
def require_auth(fn):
"""Deprecated passthrough retained for back-compat. New code should use
require_edit_token above, which actually authenticates."""
return fn
@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def spa(path: str):
@@ -316,6 +331,105 @@ def spa(path: str):
return jsonify({"error": "frontend not built"}), 503
@app.route("/api/auth/me", methods=["GET"])
def auth_me():
login = auth.current_login()
if login is None:
return jsonify({"login": None})
return jsonify({
"login": login,
"avatar_url": session.get("gh_avatar_url"),
})
@app.route("/api/auth/logout", methods=["POST"])
@auth.require_same_origin
def auth_logout():
session.clear()
return ("", 204)
@app.route("/api/auth/github/login", methods=["GET"])
def auth_github_login():
import secrets as _secrets
nxt = request.args.get("next", "/")
# Only accept local relative paths to prevent open-redirect.
if not isinstance(nxt, str) or not nxt.startswith("/"):
nxt = "/"
state = _secrets.token_urlsafe(32)
session["oauth_state"] = state
session["oauth_next"] = nxt
redirect_uri = config.GITHUB_OAUTH_REDIRECT_URI or _derived_redirect_uri()
return auth.github_client().authorize_redirect(redirect_uri, state=state)
def _derived_redirect_uri() -> str:
# Works behind cloudflared: the X-Forwarded-Proto/Host headers are set.
proto = request.headers.get("X-Forwarded-Proto") or request.scheme
host = request.headers.get("X-Forwarded-Host") or request.host
return f"{proto}://{host}/api/auth/github/callback"
def _gh_api_get(token: str, path: str) -> dict:
"""Thin wrapper over requests.get so tests can monkeypatch one function."""
import requests
r = requests.get(
f"https://api.github.com/{path.lstrip('/')}",
headers={"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github+json"},
timeout=config.API_TIMEOUT,
)
if r.status_code >= 400:
raise RuntimeError(f"github {path} {r.status_code}")
return r.json()
@app.route("/api/auth/github/callback", methods=["GET"])
def auth_github_callback():
from flask import redirect
state = request.args.get("state", "")
expected = session.pop("oauth_state", None)
nxt = session.pop("oauth_next", "/") or "/"
if not expected or state != expected:
return jsonify({"error": "bad_state"}), 400
try:
token_resp = auth.github_client().authorize_access_token()
except Exception:
log.exception("token exchange failed")
return redirect("/?auth_error=exchange")
access_token = token_resp.get("access_token") if token_resp else None
if not access_token:
return redirect("/?auth_error=exchange")
try:
user = _gh_api_get(access_token, "user")
except Exception:
log.exception("github /user failed")
return redirect("/?auth_error=profile")
login_raw = user.get("login")
gh_id = user.get("id")
avatar_url = user.get("avatar_url") or ""
if not isinstance(login_raw, str) or not is_valid_username(login_raw) or not isinstance(gh_id, int):
return redirect("/?auth_error=profile")
login = login_raw.lower()
session.permanent = True
session["gh_login"] = login
session["gh_id"] = gh_id
session["gh_avatar_url"] = avatar_url
# Implicit enrollment. Idempotent; refreshes github_avatar_url on return logins.
defaults = {
"theme": "dark",
"enabled": config.ENABLED_WIDGETS,
"widget_order": config.WIDGET_ORDER,
}
db.enroll(login, defaults, github_id=gh_id, github_avatar_url=avatar_url)
_kickoff_prefetch_async(login)
return redirect(nxt)
@app.route("/api/health", methods=["GET"])
def health():
return jsonify({"status": "ok", "service": "generator"})
@@ -345,37 +459,13 @@ def get_user_data(username: str):
"""Precomputed widget data for client-side SVG rendering.
Pure DB lookup — never touches the fetcher or runs compute on the hot
path. On miss: auto-enroll (queues an async build) and return
`{status: "building"}` with HTTP 202 so the client can show demo data
and poll until ready.
path. Enrollment is now OAuth-driven only.
"""
if not is_valid_username(username):
return jsonify({"error": "invalid_username"}), 400
settings_row = db.get_settings(username)
if settings_row is None:
if not _rate_limit("enroll"):
return jsonify({"status": "rate_limited"}), 429
if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP:
return jsonify({"status": "rate_limited"}), 429
# Queue-depth backpressure: if the worker is already behind, stop
# accepting new enrollments until it catches up. Prevents a burst
# of auto-enrolls from filling the jobs table faster than a mini
# PC can drain it.
if db.pending_job_count() >= config.PENDING_JOB_QUEUE_CAP:
return jsonify({"status": "rate_limited"}), 429
defaults = {
"theme": "dark",
"enabled": config.ENABLED_WIDGETS,
"widget_order": config.WIDGET_ORDER,
}
result = db.enroll(username, defaults)
_kickoff_prefetch_async(username)
# Token is surfaced on this auto-enroll path so the browser UI can
# edit the freshly-created profile without a separate claim step.
resp = {"status": "building"}
if result.get("edit_token"):
resp["edit_token"] = result["edit_token"]
return jsonify(resp), 202
return jsonify({"status": "not_found"}), 404
db.touch_last_requested(username)
@@ -393,9 +483,8 @@ def _serve(username: str, widget_name: str) -> Response:
"""Serves a cached SVG for README embeds.
SVGs are only produced by POST /api/<u>/generate. Before that the
endpoint returns a "building" placeholder; enrollment is frontend-
driven (via /api/<u>/data or /api/enroll) so this path never auto-
enrolls on its own.
endpoint returns a "building" placeholder; enrollment is now OAuth-driven
so this path never auto-enrolls on its own.
"""
settings_row = db.get_settings(username)
if settings_row is None:
@@ -434,31 +523,8 @@ def _placeholder_response(variant: str, username: str, theme: str = "dark") -> R
"X-Content-Type-Options": "nosniff"})
@app.route("/api/enroll", methods=["POST"])
@rate_limited("enroll")
def enroll_endpoint():
body = request.get_json(silent=True) or {}
username = body.get("username")
if not is_valid_username(username):
return jsonify({"error": "invalid_username"}), 400
if db.get_settings(username) is not None:
return jsonify({"error": "already_enrolled"}), 409
if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP:
return jsonify({"error": "rate_limited"}), 429
if db.pending_job_count() >= config.PENDING_JOB_QUEUE_CAP:
return jsonify({"error": "rate_limited"}), 429
defaults = {"theme": "dark", "enabled": config.ENABLED_WIDGETS, "widget_order": config.WIDGET_ORDER}
result = db.enroll(username, defaults)
_kickoff_prefetch_async(username)
body = {"enrolled": True, "job_id": result["job_id"]}
if result.get("edit_token"):
body["edit_token"] = result["edit_token"]
return jsonify(body)
@app.route("/api/<username>/settings", methods=["GET"])
@rate_limited("read")
@require_edit_token
def get_settings(username: str):
s = db.get_settings(username)
if s is None:
@@ -474,7 +540,8 @@ def get_settings(username: str):
@app.route("/api/<username>/settings", methods=["PATCH"])
@rate_limited("mutate")
@require_edit_token
@auth.require_same_origin
@auth.require_github_owner
def patch_settings(username: str):
current = db.get_settings(username)
if current is None:
@@ -492,12 +559,13 @@ def patch_settings(username: str):
@app.route("/api/<username>/generate", methods=["POST"])
@rate_limited("mutate")
@auth.require_same_origin
@auth.require_github_owner
def generate(username: str):
"""Render the composite SVG from the cached fetcher payload + current
settings, persist it to widgets.db, and return status. Called by the
Generate button; safe to call repeatedly (each call re-renders with
the latest settings). Unauth'd — anyone can trigger a render of a
previously-enrolled user's public widget.
the latest settings). Requires OAuth session with matching login.
Capacity:
* Per-IP rate limit (mutate bucket) caps how fast any one caller can
@@ -541,7 +609,8 @@ def generate(username: str):
@app.route("/api/<username>/refresh", methods=["POST"])
@rate_limited("mutate")
@require_edit_token
@auth.require_same_origin
@auth.require_github_owner
def refresh(username: str):
s = db.get_settings(username)
if s is None:
+80
View File
@@ -0,0 +1,80 @@
"""GitHub OAuth integration for the generator service.
Owns:
- OAuth client registration (authlib)
- `current_login()` — lowercase GitHub login from session, or None
- `require_github_owner` — decorator: 401 if no session, 403 if mismatch
- `require_same_origin` — decorator: 403 if Origin/Referer not in allowlist
"""
from functools import wraps
from urllib.parse import urlparse
from authlib.integrations.flask_client import OAuth
from flask import jsonify, request, session
from . import config
_oauth: OAuth | None = None
def init_oauth(app) -> OAuth:
"""Register the `github` provider. Safe to call once at app startup."""
global _oauth
oauth = OAuth(app)
oauth.register(
name="github",
client_id=config.GITHUB_OAUTH_CLIENT_ID,
client_secret=config.GITHUB_OAUTH_CLIENT_SECRET,
access_token_url="https://github.com/login/oauth/access_token",
authorize_url="https://github.com/login/oauth/authorize",
api_base_url="https://api.github.com/",
client_kwargs={"scope": "read:user"},
)
_oauth = oauth
return oauth
def github_client():
if _oauth is None:
raise RuntimeError("OAuth not initialized — call init_oauth(app) first.")
return _oauth.github
def current_login() -> str | None:
v = session.get("gh_login")
return v.lower() if isinstance(v, str) else None
def _origin_ok() -> bool:
origin = request.headers.get("Origin") or request.headers.get("Referer") or ""
if not origin:
return False
try:
o = urlparse(origin)
normalized = f"{o.scheme}://{o.netloc}"
except Exception:
return False
return normalized in config.ALLOWED_ORIGINS
def require_github_owner(fn):
"""401 if no session; 403 if session login != url username (case-insensitive)."""
@wraps(fn)
def wrapper(username: str, *args, **kwargs):
me = current_login()
if me is None:
return jsonify({"error": "login_required"}), 401
if me != (username or "").lower():
return jsonify({"error": "forbidden"}), 403
return fn(username, *args, **kwargs)
return wrapper
def require_same_origin(fn):
"""Defense in depth beyond SameSite=Lax. Rejects cross-site mutate attempts."""
@wraps(fn)
def wrapper(*args, **kwargs):
if not _origin_ok():
return jsonify({"error": "bad_origin"}), 403
return fn(*args, **kwargs)
return wrapper
+22
View File
@@ -140,3 +140,25 @@ PREFETCH_MAX_WORKERS = int(os.getenv("PREFETCH_MAX_WORKERS", "2"))
PENDING_JOB_QUEUE_CAP = int(os.getenv("PENDING_JOB_QUEUE_CAP", "200"))
# How long a /generate caller will wait for the semaphore before giving up.
GENERATE_SEMAPHORE_WAIT_S = float(os.getenv("GENERATE_SEMAPHORE_WAIT_S", "15"))
# --- GitHub OAuth ---
# Env names avoid the reserved GITHUB_ prefix so they can be stored as GitHub
# Actions secrets (which reject GITHUB_* names).
GITHUB_OAUTH_CLIENT_ID = os.getenv("GH_OAUTH_CLIENT_ID", "")
GITHUB_OAUTH_CLIENT_SECRET = os.getenv("GH_OAUTH_CLIENT_SECRET", "")
GITHUB_OAUTH_REDIRECT_URI = os.getenv("GH_OAUTH_REDIRECT_URI", "")
# Flask session secret. Generate once: python -c "import secrets; print(secrets.token_hex(32))"
SECRET_KEY = os.getenv("GENERATOR_SECRET_KEY", "")
# Dev-only override; defaults to True so production HTTPS cookies work.
SESSION_COOKIE_SECURE = os.getenv("SESSION_COOKIE_SECURE", "true").lower() != "false"
# CSRF defense-in-depth: Origin/Referer allowlist for state-changing routes.
ALLOWED_ORIGINS = tuple(
o.strip() for o in os.getenv("ALLOWED_ORIGINS", "https://gh-stats.com").split(",") if o.strip()
)
# Per-login rate limit on mutate routes, layered on top of per-IP limits.
RATE_LIMIT_MUTATE_PER_LOGIN_MAX = int(os.getenv("RATE_LIMIT_MUTATE_PER_LOGIN_MAX", "120"))
RATE_LIMIT_MUTATE_PER_LOGIN_WINDOW = int(os.getenv("RATE_LIMIT_MUTATE_PER_LOGIN_WINDOW", "60"))
+35 -37
View File
@@ -4,10 +4,8 @@ All access goes through this module so a future Postgres swap is local to here.
Both DBs are opened with WAL mode.
"""
import hashlib
import hmac as _hmac
import json
import os
import secrets
import sqlite3
from contextlib import contextmanager
from datetime import datetime, timedelta
@@ -27,7 +25,9 @@ CREATE TABLE IF NOT EXISTS users (
last_fetcher_payload_hash TEXT,
manual_refresh_used INTEGER DEFAULT 0,
last_requested_at TEXT NOT NULL,
edit_token_hash TEXT
edit_token_hash TEXT,
github_id INTEGER,
github_avatar_url TEXT
);
CREATE TABLE IF NOT EXISTS enrollments_daily (
day TEXT PRIMARY KEY,
@@ -116,29 +116,16 @@ def init_dbs() -> None:
cols = {r["name"] for r in c.execute("PRAGMA table_info(users)").fetchall()}
if "edit_token_hash" not in cols:
c.execute("ALTER TABLE users ADD COLUMN edit_token_hash TEXT")
if "github_id" not in cols:
c.execute("ALTER TABLE users ADD COLUMN github_id INTEGER")
if "github_avatar_url" not in cols:
c.execute("ALTER TABLE users ADD COLUMN github_avatar_url TEXT")
c.commit()
with _widgets_conn() as c:
c.executescript(_WIDGETS_SCHEMA)
c.commit()
def _hash_edit_token(token: str) -> str:
return hashlib.sha256(token.encode("utf-8")).hexdigest()
def verify_edit_token(username: str, presented: str) -> bool:
"""Constant-time check of the caller's edit token against the stored hash."""
if not username or not presented:
return False
with _settings_conn() as c:
row = c.execute(
"SELECT edit_token_hash FROM users WHERE username=?", (username,)
).fetchone()
if row is None or not row["edit_token_hash"]:
return False
return _hmac.compare_digest(row["edit_token_hash"], _hash_edit_token(presented))
def settings_hash(settings: dict) -> str:
canonical = json.dumps(settings, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
@@ -146,29 +133,34 @@ def settings_hash(settings: dict) -> str:
# ---- settings / enrollment ----
def enroll(username: str, defaults: dict) -> dict:
"""Insert a settings row + increment daily counter + enqueue build.
def enroll(username: str, defaults: dict,
github_id: int | None = None,
github_avatar_url: str | None = None) -> dict:
"""Insert a settings row if missing, bump the daily counter, enqueue a build.
Returns {"job_id", "edit_token"}. The edit_token is the bearer token the
caller must present on future settings mutations for this user. We only
store its SHA-256 hash, so the plaintext here is the one and only chance
to surface it to the client. Subsequent enroll() calls for an existing
user return `edit_token=None` to avoid leaking tokens issued to earlier
registrants — settings cannot be taken over by re-enrolling.
Idempotent: calling again for an existing user refreshes github_avatar_url
(so login keeps the avatar fresh) and enqueues a rebuild. Always returns
{"job_id": int}. No token is returned — auth is handled by the signed
session cookie.
"""
sh = settings_hash(defaults)
now = _now()
token = secrets.token_urlsafe(32)
token_hash = _hash_edit_token(token)
with _settings_conn() as c:
cur_ins = c.execute(
"""INSERT INTO users(username, settings_json, settings_hash, enrolled_at,
last_requested_at, edit_token_hash)
VALUES (?, ?, ?, ?, ?, ?)
last_requested_at, github_id, github_avatar_url)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(username) DO NOTHING""",
(username, json.dumps(defaults), sh, now, now, token_hash),
(username, json.dumps(defaults), sh, now, now, github_id, github_avatar_url),
)
inserted = cur_ins.rowcount == 1
if not inserted and (github_id is not None or github_avatar_url is not None):
c.execute(
"UPDATE users SET github_id=COALESCE(?, github_id), "
"github_avatar_url=COALESCE(?, github_avatar_url) WHERE username=?",
(github_id, github_avatar_url, username),
)
if inserted:
c.execute(
"""INSERT INTO enrollments_daily(day, count) VALUES (?, 1)
ON CONFLICT(day) DO UPDATE SET count = count + 1""",
@@ -180,10 +172,7 @@ def enroll(username: str, defaults: dict) -> dict:
(username, now, now),
)
c.commit()
return {
"job_id": cur.lastrowid,
"edit_token": token if inserted else None,
}
return {"job_id": cur.lastrowid}
def enrollments_today() -> int:
@@ -264,6 +253,15 @@ def set_last_fetcher_hash(username: str, h: str) -> None:
c.commit()
def set_github_profile(username: str, github_id: int, github_avatar_url: str) -> None:
with _settings_conn() as c:
c.execute(
"UPDATE users SET github_id=?, github_avatar_url=? WHERE username=?",
(github_id, github_avatar_url, username),
)
c.commit()
# ---- jobs ----
def enqueue_build(username: str) -> int:
+12 -6
View File
@@ -19,9 +19,10 @@ def env(monkeypatch):
@responses.activate
def test_full_flow_data_then_generate_then_serve(env):
"""End-to-end of the new two-phase pipeline:
1. /data enrolls + kicks off prefetch (worker populates widget_data)
2. /generate renders SVG from the cached payload + settings
3. /api/<u> serves the stored SVG to README consumers
1. OAuth callback enrolls user + kicks off prefetch (worker populates widget_data)
2. /data endpoint returns widget data
3. /generate renders SVG from the cached payload + settings
4. /api/<u> serves the stored SVG to README consumers
"""
responses.add(
responses.GET, "http://fetcher-mock/data/alice",
@@ -32,7 +33,10 @@ def test_full_flow_data_then_generate_then_serve(env):
)
client = apimod.app.test_client()
# Phase 1: prefetch via /data (enrolls + kicks off background thread).
# Phase 1: OAuth callback enrolls user (simulated via db.enroll).
dbmod.enroll("alice", {"theme": "dark"})
# Widget data should be building right after enrollment.
r_data = client.get("/api/alice/data")
assert r_data.status_code == 202
@@ -51,8 +55,10 @@ def test_full_flow_data_then_generate_then_serve(env):
time.sleep(0.05)
assert r.status_code == 200 and r.get_json()["status"] == "ready"
# Phase 2: Generate button → render SVG.
r_gen = client.post("/api/alice/generate")
# Phase 2: Generate button → render SVG (with session).
with client.session_transaction() as s:
s["gh_login"] = "alice"
r_gen = client.post("/api/alice/generate", headers={"Origin": "https://gh-stats.com"})
assert r_gen.status_code == 200
assert r_gen.get_json()["status"] == "ready"
+108 -34
View File
@@ -2,6 +2,7 @@ import os, tempfile, pytest
from unittest.mock import patch
from src import db as dbmod
from src import api as apimod
from src import config as cfg
@pytest.fixture
@@ -13,10 +14,16 @@ def client(monkeypatch):
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db"))
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db"))
dbmod.init_dbs()
# Configure OAuth fixture with allowed origins and insecure cookies for testing.
monkeypatch.setattr(cfg, "ALLOWED_ORIGINS", ("https://gh-stats.com",))
app = apimod.app
app.config["TESTING"] = True
app.config["SESSION_COOKIE_SECURE"] = False
with app.test_client() as c:
yield c
# Clear rate limit state after each test to prevent pollution.
apimod._rate_hits.clear()
apimod._rate_hits_per_login.clear()
def test_health(client):
@@ -54,47 +61,77 @@ def test_enrolled_user_with_built_widget_returns_ready(client):
def test_settings_patch_enqueues_rebuild(client):
token = dbmod.enroll("alice", {"theme": "dark"})["edit_token"]
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "alice"
r = client.patch(
"/api/alice/settings",
json={"theme": "light"},
headers={"Authorization": f"Bearer {token}"},
headers={"Origin": "https://gh-stats.com"},
)
assert r.status_code == 200
assert dbmod.get_settings("alice")["settings"]["theme"] == "light"
def test_settings_patch_without_token_is_unauthorized(client):
def test_settings_patch_without_origin_is_unauthorized(client):
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "alice"
r = client.patch("/api/alice/settings", json={"theme": "light"})
assert r.status_code == 401
# Settings must not be mutated when the token check fails.
assert r.status_code == 403
# Settings must not be mutated when the origin check fails.
assert dbmod.get_settings("alice")["settings"]["theme"] == "dark"
def test_settings_patch_with_wrong_token_is_unauthorized(client):
def test_patch_settings_without_session_is_401(client):
dbmod.enroll("alice", {"theme": "dark"})
r = client.patch(
"/api/alice/settings",
json={"theme": "light"},
headers={"Authorization": "Bearer not-the-real-token"},
)
r = client.patch("/api/alice/settings", json={"theme": "light"},
headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 401
def test_patch_settings_wrong_login_is_403(client):
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "bob"
r = client.patch("/api/alice/settings", json={"theme": "light"},
headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 403
def test_patch_settings_matching_login_succeeds(client):
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "alice"
r = client.patch("/api/alice/settings", json={"theme": "light"},
headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 200
def test_patch_settings_bad_origin_is_403(client):
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "alice"
r = client.patch("/api/alice/settings", json={"theme": "light"},
headers={"Origin": "https://evil.example"})
assert r.status_code == 403
def test_refresh_is_one_shot(client):
token = dbmod.enroll("alice", {"theme": "dark"})["edit_token"]
headers = {"Authorization": f"Bearer {token}"}
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "alice"
with patch("src.api.fetcher_client.force_fetch", return_value={"changed": True, "payload_hash": "x", "stored": True}):
r1 = client.post("/api/alice/refresh", headers=headers)
r1 = client.post("/api/alice/refresh", headers={"Origin": "https://gh-stats.com"})
assert r1.status_code == 200
r2 = client.post("/api/alice/refresh", headers=headers)
r2 = client.post("/api/alice/refresh", headers={"Origin": "https://gh-stats.com"})
assert r2.status_code == 409
def test_refresh_without_token_is_unauthorized(client):
"""Old test name; now tests without session but with proper Origin."""
dbmod.enroll("alice", {"theme": "dark"})
r = client.post("/api/alice/refresh")
r = client.post("/api/alice/refresh", headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 401
@@ -110,6 +147,8 @@ def test_generate_endpoint_renders_and_stores_svg(client):
"""POST /api/<u>/generate invokes the on-demand render path and caches
the composite SVG for subsequent README embeds."""
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "alice"
with patch("src.worker.render_widgets_now",
return_value={"composite": "<svg>r</svg>", "grade": "<svg>g</svg>"}):
# Simulate the render path also updating current_widget so the
@@ -119,7 +158,7 @@ def test_generate_endpoint_renders_and_stores_svg(client):
dbmod.point_current_widget(username, "h1")
return {"composite": "<svg>r</svg>"}
with patch("src.worker.render_widgets_now", side_effect=fake_render):
r = client.post("/api/alice/generate")
r = client.post("/api/alice/generate", headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 200
body = r.get_json()
assert body["status"] == "ready"
@@ -130,7 +169,10 @@ def test_generate_endpoint_renders_and_stores_svg(client):
def test_generate_endpoint_rejects_unenrolled(client):
r = client.post("/api/bob/generate")
"""With OAuth, unenrolled means having a session but no profile."""
with client.session_transaction() as s:
s["gh_login"] = "bob"
r = client.post("/api/bob/generate", headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 404
@@ -138,17 +180,6 @@ def test_generate_endpoint_rejects_unenrolled(client):
# Pure DB lookup — fetcher is never touched on the hot path.
def test_data_endpoint_unknown_user_enrolls_and_returns_building(client):
r = client.get("/api/alice/data")
assert r.status_code == 202
body = r.get_json()
assert body["status"] == "building"
# Auto-enroll path surfaces the edit token so the browser can mutate
# the freshly-created profile without a separate claim flow.
assert "edit_token" in body and body["edit_token"]
assert dbmod.get_settings("alice") is not None # auto-enrolled
def test_data_endpoint_enrolled_but_unbuilt_returns_building(client):
dbmod.enroll("alice", {"theme": "dark"})
r = client.get("/api/alice/data")
@@ -187,8 +218,51 @@ def test_data_endpoint_returns_not_found_for_unknown_github_user(client):
assert r.get_json()["status"] == "not_found"
def test_data_endpoint_rate_limited_before_enroll(client, monkeypatch):
monkeypatch.setattr(apimod.config, "ENROLLMENT_DAILY_CAP", 0)
r = client.get("/api/newbie/data")
assert r.status_code == 429
assert r.get_json()["status"] == "rate_limited"
def test_generate_without_session_is_401(client):
dbmod.enroll("alice", {"theme": "dark"})
r = client.post("/api/alice/generate", headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 401
def test_generate_wrong_login_is_403(client):
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "bob"
r = client.post("/api/alice/generate", headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 403
def test_refresh_without_session_is_401(client):
dbmod.enroll("alice", {"theme": "dark"})
r = client.post("/api/alice/refresh", headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 401
def test_data_unknown_user_returns_404(client):
r = client.get("/api/testuser/data")
assert r.status_code == 404
def test_enroll_endpoint_is_gone(client):
r = client.post("/api/enroll", json={"username": "alice"},
headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 405
def test_per_login_mutate_rate_limit(client, monkeypatch):
"""Per-login rate limit on mutate routes allows up to MAX requests,
then rejects with 429."""
monkeypatch.setattr(cfg, "RATE_LIMIT_MUTATE_PER_LOGIN_MAX", 2)
monkeypatch.setattr(cfg, "RATE_LIMIT_MUTATE_PER_LOGIN_WINDOW", 60)
dbmod.enroll("alice", {"theme": "dark"})
with client.session_transaction() as s:
s["gh_login"] = "alice"
h = {"Origin": "https://gh-stats.com"}
# First two requests should succeed.
r1 = client.patch("/api/alice/settings", json={}, headers=h)
assert r1.status_code == 200
r2 = client.patch("/api/alice/settings", json={}, headers=h)
assert r2.status_code == 200
# Third request should be rate-limited.
r3 = client.patch("/api/alice/settings", json={}, headers=h)
assert r3.status_code == 429
+173
View File
@@ -0,0 +1,173 @@
"""Unit tests for auth helpers (no network)."""
import pytest
from flask import Flask, jsonify
from src import auth, config
@pytest.fixture
def app(monkeypatch):
monkeypatch.setattr(config, "ALLOWED_ORIGINS", ("https://gh-stats.com",))
app = Flask(__name__)
app.secret_key = "test-secret"
@app.route("/protected/<username>", methods=["POST"])
@auth.require_same_origin
@auth.require_github_owner
def protected(username):
return jsonify({"ok": True, "you": auth.current_login()})
return app
def _good_hdrs():
return {"Origin": "https://gh-stats.com"}
def test_current_login_none_by_default(app):
with app.test_request_context("/"):
assert auth.current_login() is None
def test_require_github_owner_401_without_session(app):
with app.test_client() as c:
r = c.post("/protected/alice", headers=_good_hdrs())
assert r.status_code == 401
assert r.get_json()["error"] == "login_required"
def test_require_github_owner_403_on_mismatch(app):
with app.test_client() as c:
with c.session_transaction() as s:
s["gh_login"] = "bob"
r = c.post("/protected/alice", headers=_good_hdrs())
assert r.status_code == 403
def test_require_github_owner_passes_with_matching_login(app):
with app.test_client() as c:
with c.session_transaction() as s:
s["gh_login"] = "Alice" # stored mixed-case on purpose
r = c.post("/protected/alice", headers=_good_hdrs())
assert r.status_code == 200
assert r.get_json()["you"] == "alice"
def test_require_same_origin_rejects_bad_origin(app):
with app.test_client() as c:
with c.session_transaction() as s:
s["gh_login"] = "alice"
r = c.post("/protected/alice", headers={"Origin": "https://evil.example"})
assert r.status_code == 403
def test_require_same_origin_rejects_missing_origin(app):
with app.test_client() as c:
with c.session_transaction() as s:
s["gh_login"] = "alice"
r = c.post("/protected/alice")
assert r.status_code == 403
from src import api as api_module
@pytest.fixture
def api_client(monkeypatch, tmp_path):
# Point DBs at tmp + configure origins.
from src import db as dbmod, config as cfg
monkeypatch.setattr(cfg, "SETTINGS_DB_PATH", str(tmp_path / "s.db"))
monkeypatch.setattr(cfg, "WIDGETS_DB_PATH", str(tmp_path / "w.db"))
monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", str(tmp_path / "s.db"))
monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", str(tmp_path / "w.db"))
dbmod.init_dbs()
monkeypatch.setattr(cfg, "ALLOWED_ORIGINS", ("https://gh-stats.com",))
api_module.app.config["TESTING"] = True
api_module.app.config["SESSION_COOKIE_SECURE"] = False
return api_module.app.test_client()
def test_me_unauthed_returns_null(api_client):
r = api_client.get("/api/auth/me")
assert r.status_code == 200
assert r.get_json() == {"login": None}
def test_me_authed_returns_login(api_client):
with api_client.session_transaction() as s:
s["gh_login"] = "alice"
s["gh_avatar_url"] = "https://x/a.png"
r = api_client.get("/api/auth/me")
assert r.status_code == 200
j = r.get_json()
assert j["login"] == "alice"
assert j["avatar_url"] == "https://x/a.png"
def test_logout_clears_session(api_client):
with api_client.session_transaction() as s:
s["gh_login"] = "alice"
r = api_client.post("/api/auth/logout", headers={"Origin": "https://gh-stats.com"})
assert r.status_code == 204
r = api_client.get("/api/auth/me")
assert r.get_json()["login"] is None
def test_logout_rejects_bad_origin(api_client):
with api_client.session_transaction() as s:
s["gh_login"] = "alice"
r = api_client.post("/api/auth/logout", headers={"Origin": "https://evil.example"})
assert r.status_code == 403
def test_login_stashes_state_and_redirects(api_client):
"""Don't depend on authlib's exact redirect URL — just confirm the route
stashes a random state, records the next path, and returns a 3xx."""
r = api_client.get("/api/auth/github/login?next=/workshop")
assert r.status_code in (302, 303)
with api_client.session_transaction() as s:
assert s.get("oauth_state")
assert s.get("oauth_next") == "/workshop"
def test_login_rejects_external_next(api_client):
r = api_client.get("/api/auth/github/login?next=https://evil.example/foo")
assert r.status_code in (302, 303)
with api_client.session_transaction() as s:
assert s.get("oauth_next") == "/"
def test_callback_state_mismatch_400(api_client):
with api_client.session_transaction() as s:
s["oauth_state"] = "correct"
r = api_client.get("/api/auth/github/callback?code=abc&state=wrong")
assert r.status_code == 400
def test_callback_happy_path_sets_session(api_client, monkeypatch):
"""End-to-end callback: stub token exchange + /user, verify session state."""
from src import auth as authmod, db as dbmod
# Pre-populate session with matching state
with api_client.session_transaction() as s:
s["oauth_state"] = "good-state"
s["oauth_next"] = "/"
# Stub authlib's token exchange
def fake_authorize_access_token(**_kwargs):
return {"access_token": "ghs_abc", "token_type": "bearer"}
monkeypatch.setattr(authmod.github_client(), "authorize_access_token", fake_authorize_access_token)
# Stub the GitHub /user call
import src.api as apimod
monkeypatch.setattr(apimod, "_gh_api_get",
lambda token, path: {"id": 123, "login": "Alice", "avatar_url": "https://x/a.png"})
r = api_client.get("/api/auth/github/callback?code=abc&state=good-state")
assert r.status_code in (302, 303)
assert r.headers["Location"].endswith("/")
with api_client.session_transaction() as s:
assert s["gh_login"] == "alice"
assert s["gh_id"] == 123
assert s["gh_avatar_url"] == "https://x/a.png"
# Row should now exist with github profile populated.
assert dbmod.get_settings("alice") is not None
+23 -13
View File
@@ -19,23 +19,24 @@ def test_settings_hash_is_deterministic():
assert h1 == h2
def test_enroll_and_get_settings(tmp_dbs):
defaults = {"theme": "dark", "widgets": ["grade"]}
result = dbmod.enroll("alice", defaults)
assert result["job_id"] > 0
assert result["edit_token"] # first enrollment surfaces a token
s = dbmod.get_settings("alice")
assert s["settings"] == defaults
assert s["manual_refresh_used"] == 0
def test_enroll_returns_job_id(tmp_dbs):
r = dbmod.enroll("alice", {"theme": "dark"})
assert r["job_id"] > 0
assert "edit_token" not in r
def test_enroll_twice_does_not_reissue_token(tmp_dbs):
def test_enroll_twice_noops(tmp_dbs):
r1 = dbmod.enroll("alice", {"theme": "dark"})
r2 = dbmod.enroll("alice", {"theme": "dark"})
assert r1["edit_token"]
assert r2["edit_token"] is None
assert dbmod.verify_edit_token("alice", r1["edit_token"]) is True
assert dbmod.verify_edit_token("alice", "wrong") is False
assert r1["job_id"] > 0 and r2["job_id"] > 0
def test_enroll_with_github_profile(tmp_dbs):
dbmod.enroll("alice", {"theme": "dark"}, github_id=1, github_avatar_url="https://x/a.png")
with dbmod._settings_conn() as c:
row = c.execute("SELECT github_id, github_avatar_url FROM users WHERE username='alice'").fetchone()
assert row["github_id"] == 1
assert row["github_avatar_url"] == "https://x/a.png"
def test_enrollments_daily_counter(tmp_dbs):
@@ -100,3 +101,12 @@ def test_reclaim_stuck_running_jobs(tmp_dbs):
dbmod.reclaim_stuck_jobs(older_than_minutes=10)
job = dbmod.claim_next_job()
assert job["id"] == jid
def test_set_github_profile_round_trip(tmp_dbs):
dbmod.enroll("alice", {"theme": "dark"})
dbmod.set_github_profile("alice", github_id=42, github_avatar_url="https://example.com/a.png")
with dbmod._settings_conn() as c:
row = c.execute("SELECT github_id, github_avatar_url FROM users WHERE username='alice'").fetchone()
assert row["github_id"] == 42
assert row["github_avatar_url"] == "https://example.com/a.png"