mirror of
https://github.com/ShayManor/github-readme-stats.git
synced 2026-12-02 11:53:48 +05:30
feat(api): implement per-user edit token for settings mutations
This commit is contained in:
+63
-4
@@ -1,7 +1,11 @@
|
||||
"""Edge service — cache-first SVG proxy in front of the generator."""
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from collections import defaultdict, deque
|
||||
from threading import Lock
|
||||
import requests
|
||||
from flask import Flask, Response, jsonify
|
||||
from flask import Flask, Response, jsonify, request
|
||||
from flask_compress import Compress
|
||||
|
||||
from . import cache as cache_mod, config
|
||||
@@ -11,14 +15,59 @@ Compress(app)
|
||||
cache_ext = cache_mod.build_cache(app)
|
||||
log = logging.getLogger("edge")
|
||||
|
||||
# GitHub usernames: 1-39 chars, alnum, single hyphens. Keep the regex in
|
||||
# sync with generator/src/utils/validate.py so invalid paths get rejected
|
||||
# before they waste an upstream round-trip.
|
||||
_USERNAME_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$")
|
||||
_ALLOWED_WIDGETS = {"grade", "impact", "collaborators", "focus", "languages", "achievements", "composite"}
|
||||
|
||||
|
||||
def _valid_username(u: str) -> bool:
|
||||
return bool(u) and bool(_USERNAME_RE.match(u))
|
||||
|
||||
|
||||
# ---- Per-IP rate limiter ---------------------------------------------------
|
||||
# The edge is the mini PC's front door. Cache hits are cheap, but a hostile
|
||||
# cache-miss storm (unique usernames, unique widget names) would funnel into
|
||||
# the generator's render path. Bound it here so the generator's own limiter
|
||||
# isn't the only layer. Operators who run behind a CDN / nginx should prefer
|
||||
# the upstream limiter and raise these env vars.
|
||||
_rate_lock = Lock()
|
||||
_rate_hits: dict[str, deque] = defaultdict(deque)
|
||||
|
||||
|
||||
def _client_ip() -> str:
|
||||
fwd = request.headers.get("X-Forwarded-For", "")
|
||||
if fwd:
|
||||
return fwd.split(",")[-1].strip()
|
||||
return request.remote_addr or "unknown"
|
||||
|
||||
|
||||
def _allow(ip: str) -> bool:
|
||||
now = time.time()
|
||||
cutoff = now - config.RATE_LIMIT_WINDOW
|
||||
with _rate_lock:
|
||||
q = _rate_hits[ip]
|
||||
while q and q[0] < cutoff:
|
||||
q.popleft()
|
||||
if len(q) >= config.RATE_LIMIT_MAX:
|
||||
return False
|
||||
q.append(now)
|
||||
return True
|
||||
|
||||
|
||||
def _cache_key(path: str) -> str:
|
||||
return f"edge:{path}"
|
||||
|
||||
|
||||
def _fetch_origin(path: str) -> requests.Response:
|
||||
def _fetch_origin(path: str, client_ip: str) -> requests.Response:
|
||||
url = f"{config.GENERATOR_URL}/api/{path}"
|
||||
return requests.get(url, timeout=config.UPSTREAM_TIMEOUT)
|
||||
# Forward the caller's IP so the generator's rate limiter can
|
||||
# discriminate per user rather than treating the edge's single IP as
|
||||
# one client — otherwise the first 300 requests/min exhaust the bucket
|
||||
# for everyone behind the edge.
|
||||
headers = {"X-Forwarded-For": client_ip}
|
||||
return requests.get(url, headers=headers, timeout=config.UPSTREAM_TIMEOUT)
|
||||
|
||||
|
||||
@app.route("/health", methods=["GET"])
|
||||
@@ -34,15 +83,25 @@ def health():
|
||||
|
||||
@app.route("/<username>", methods=["GET"])
|
||||
def serve(username: str):
|
||||
if not _valid_username(username):
|
||||
return jsonify({"error": "invalid_username"}), 400
|
||||
return _serve(username, path=username)
|
||||
|
||||
|
||||
@app.route("/<username>/<widget>.svg", methods=["GET"])
|
||||
def serve_widget(username: str, widget: str):
|
||||
if not _valid_username(username):
|
||||
return jsonify({"error": "invalid_username"}), 400
|
||||
if widget not in _ALLOWED_WIDGETS:
|
||||
return jsonify({"error": "unknown_widget"}), 400
|
||||
return _serve(f"{username}/{widget}", path=f"{username}/{widget}.svg")
|
||||
|
||||
|
||||
def _serve(key_suffix: str, path: str) -> Response:
|
||||
ip = _client_ip()
|
||||
if not _allow(ip):
|
||||
return jsonify({"error": "rate_limited"}), 429
|
||||
|
||||
ck = _cache_key(key_suffix)
|
||||
cached = cache_ext.get(ck)
|
||||
if cached is not None:
|
||||
@@ -54,7 +113,7 @@ def _serve(key_suffix: str, path: str) -> Response:
|
||||
})
|
||||
|
||||
try:
|
||||
r = _fetch_origin(path)
|
||||
r = _fetch_origin(path, ip)
|
||||
except Exception as e:
|
||||
log.warning("origin unreachable for %s: %s", path, e)
|
||||
return jsonify({"error": "origin unreachable"}), 503
|
||||
|
||||
@@ -7,3 +7,10 @@ CACHE_REDIS_URL = os.getenv("CACHE_REDIS_URL", "")
|
||||
CACHE_DEFAULT_TIMEOUT = int(os.getenv("CACHE_DEFAULT_TIMEOUT", "86400"))
|
||||
CACHE_THRESHOLD = int(os.getenv("CACHE_THRESHOLD", "10000"))
|
||||
UPSTREAM_TIMEOUT = int(os.getenv("EDGE_UPSTREAM_TIMEOUT", "10"))
|
||||
|
||||
# Per-IP rate limit at the edge. Anti-abuse only — cache hits are cheap
|
||||
# and cache misses are already bounded by the generator's global
|
||||
# semaphore, so normal traffic should never notice this. Generous by
|
||||
# default; tighten via env if a specific IP misbehaves.
|
||||
RATE_LIMIT_MAX = int(os.getenv("EDGE_RATE_LIMIT_MAX", "3000"))
|
||||
RATE_LIMIT_WINDOW = int(os.getenv("EDGE_RATE_LIMIT_WINDOW", "60"))
|
||||
|
||||
Reference in New Issue
Block a user