feat(api): remove public /enroll endpoint and auto-enroll on /data

This commit is contained in:
shay
2026-04-19 19:06:38 -04:00
parent 91f6328efd
commit 0cd7bf339d
3 changed files with 27 additions and 75 deletions
+4 -52
View File
@@ -80,7 +80,6 @@ _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()
@@ -432,37 +431,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)
@@ -480,9 +455,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:
@@ -521,28 +495,6 @@ 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")
def get_settings(username: str):
+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"
+11 -17
View File
@@ -177,16 +177,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 no longer surfaces edit token; auth is now session-based.
assert "edit_token" not in body
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")
@@ -225,13 +215,6 @@ 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"})
@@ -250,3 +233,14 @@ 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