mirror of
https://github.com/ShayManor/github-readme-stats.git
synced 2026-12-02 11:53:48 +05:30
feat(api): /generate and /refresh use OAuth session; remove edit_token helpers
This commit is contained in:
+5
-33
@@ -123,30 +123,6 @@ def rate_limited(bucket: str):
|
||||
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")
|
||||
@@ -311,12 +287,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):
|
||||
@@ -609,12 +579,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
|
||||
@@ -658,7 +629,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:
|
||||
|
||||
@@ -126,17 +126,6 @@ def init_dbs() -> None:
|
||||
c.commit()
|
||||
|
||||
|
||||
def verify_edit_token(username: str, presented: str) -> bool:
|
||||
"""Constant-time check of the caller's edit token against the stored hash.
|
||||
|
||||
DEPRECATED: This function is dead code as of Task 5 (edit tokens are no longer
|
||||
hashed during enrollment). It remains here temporarily while api.py's
|
||||
require_edit_token decorator is still being used. Task 12 will remove both
|
||||
this function and the decorator consumer in api.py.
|
||||
"""
|
||||
raise NotImplementedError("verify_edit_token is deprecated; will be removed in Task 12")
|
||||
|
||||
|
||||
def settings_hash(settings: dict) -> str:
|
||||
canonical = json.dumps(settings, sort_keys=True, separators=(",", ":"))
|
||||
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||
|
||||
+36
-10
@@ -115,18 +115,20 @@ def test_patch_settings_bad_origin_is_403(client):
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
@@ -142,6 +144,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
|
||||
@@ -151,7 +155,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"
|
||||
@@ -162,7 +166,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
|
||||
|
||||
|
||||
@@ -175,9 +182,8 @@ def test_data_endpoint_unknown_user_enrolls_and_returns_building(client):
|
||||
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"]
|
||||
# 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
|
||||
|
||||
|
||||
@@ -224,3 +230,23 @@ def test_data_endpoint_rate_limited_before_enroll(client, monkeypatch):
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user