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."""
|
"""Edge service — cache-first SVG proxy in front of the generator."""
|
||||||
import logging
|
import logging
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
from collections import defaultdict, deque
|
||||||
|
from threading import Lock
|
||||||
import requests
|
import requests
|
||||||
from flask import Flask, Response, jsonify
|
from flask import Flask, Response, jsonify, request
|
||||||
from flask_compress import Compress
|
from flask_compress import Compress
|
||||||
|
|
||||||
from . import cache as cache_mod, config
|
from . import cache as cache_mod, config
|
||||||
@@ -11,14 +15,59 @@ Compress(app)
|
|||||||
cache_ext = cache_mod.build_cache(app)
|
cache_ext = cache_mod.build_cache(app)
|
||||||
log = logging.getLogger("edge")
|
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:
|
def _cache_key(path: str) -> str:
|
||||||
return f"edge:{path}"
|
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}"
|
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"])
|
@app.route("/health", methods=["GET"])
|
||||||
@@ -34,15 +83,25 @@ def health():
|
|||||||
|
|
||||||
@app.route("/<username>", methods=["GET"])
|
@app.route("/<username>", methods=["GET"])
|
||||||
def serve(username: str):
|
def serve(username: str):
|
||||||
|
if not _valid_username(username):
|
||||||
|
return jsonify({"error": "invalid_username"}), 400
|
||||||
return _serve(username, path=username)
|
return _serve(username, path=username)
|
||||||
|
|
||||||
|
|
||||||
@app.route("/<username>/<widget>.svg", methods=["GET"])
|
@app.route("/<username>/<widget>.svg", methods=["GET"])
|
||||||
def serve_widget(username: str, widget: str):
|
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")
|
return _serve(f"{username}/{widget}", path=f"{username}/{widget}.svg")
|
||||||
|
|
||||||
|
|
||||||
def _serve(key_suffix: str, path: str) -> Response:
|
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)
|
ck = _cache_key(key_suffix)
|
||||||
cached = cache_ext.get(ck)
|
cached = cache_ext.get(ck)
|
||||||
if cached is not None:
|
if cached is not None:
|
||||||
@@ -54,7 +113,7 @@ def _serve(key_suffix: str, path: str) -> Response:
|
|||||||
})
|
})
|
||||||
|
|
||||||
try:
|
try:
|
||||||
r = _fetch_origin(path)
|
r = _fetch_origin(path, ip)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log.warning("origin unreachable for %s: %s", path, e)
|
log.warning("origin unreachable for %s: %s", path, e)
|
||||||
return jsonify({"error": "origin unreachable"}), 503
|
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_DEFAULT_TIMEOUT = int(os.getenv("CACHE_DEFAULT_TIMEOUT", "86400"))
|
||||||
CACHE_THRESHOLD = int(os.getenv("CACHE_THRESHOLD", "10000"))
|
CACHE_THRESHOLD = int(os.getenv("CACHE_THRESHOLD", "10000"))
|
||||||
UPSTREAM_TIMEOUT = int(os.getenv("EDGE_UPSTREAM_TIMEOUT", "10"))
|
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"))
|
||||||
|
|||||||
+41
-5
@@ -1,5 +1,7 @@
|
|||||||
"""Flask app for the fetcher service. All endpoints require X-Internal-Token."""
|
"""Flask app for the fetcher service. All endpoints require X-Internal-Token."""
|
||||||
import hmac
|
import hmac
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
import requests
|
import requests
|
||||||
from flask import Flask, jsonify, request, Response
|
from flask import Flask, jsonify, request, Response
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
@@ -7,6 +9,17 @@ from functools import wraps
|
|||||||
from . import config, db, github
|
from . import config, db, github
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
|
log = logging.getLogger("fetcher.api")
|
||||||
|
|
||||||
|
# Must stay in sync with github.py's _USERNAME_RE. Trust boundary: the
|
||||||
|
# fetcher is called only by the generator over the internal network, but
|
||||||
|
# a compromised/bugged generator must not be able to turn us into an
|
||||||
|
# arbitrary GitHub URL fetcher.
|
||||||
|
_USERNAME_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$")
|
||||||
|
|
||||||
|
|
||||||
|
def _valid_username(u) -> bool:
|
||||||
|
return isinstance(u, str) and bool(_USERNAME_RE.match(u))
|
||||||
|
|
||||||
|
|
||||||
def require_internal_token(fn):
|
def require_internal_token(fn):
|
||||||
@@ -27,10 +40,16 @@ def health():
|
|||||||
@app.route("/data/<username>", methods=["GET"])
|
@app.route("/data/<username>", methods=["GET"])
|
||||||
@require_internal_token
|
@require_internal_token
|
||||||
def get_data(username: str):
|
def get_data(username: str):
|
||||||
|
if not _valid_username(username):
|
||||||
|
return jsonify({"error": "invalid_username"}), 400
|
||||||
row = db.get_user(username)
|
row = db.get_user(username)
|
||||||
if row is None:
|
if row is None:
|
||||||
# Auto-fetch path
|
# Auto-fetch path
|
||||||
|
try:
|
||||||
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
|
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
|
||||||
|
except Exception:
|
||||||
|
log.exception("github fetch failed for %s", username)
|
||||||
|
return jsonify({"error": "fetch_failed"}), 502
|
||||||
if _is_github_not_found(data):
|
if _is_github_not_found(data):
|
||||||
data = {"error": "not_found"}
|
data = {"error": "not_found"}
|
||||||
h = db.upsert_user(username, data)
|
h = db.upsert_user(username, data)
|
||||||
@@ -48,12 +67,15 @@ def get_data(username: str):
|
|||||||
def force_fetch():
|
def force_fetch():
|
||||||
body = request.get_json(silent=True) or {}
|
body = request.get_json(silent=True) or {}
|
||||||
username = body.get("username")
|
username = body.get("username")
|
||||||
if not username:
|
if not _valid_username(username):
|
||||||
return jsonify({"error": "username required"}), 400
|
return jsonify({"error": "invalid_username"}), 400
|
||||||
try:
|
try:
|
||||||
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
|
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
|
||||||
except Exception as e:
|
except Exception:
|
||||||
return jsonify({"error": f"fetch failed: {e}"}), 502
|
# Previously returned f"fetch failed: {e}" which leaks internal
|
||||||
|
# exception text (URLs, stack fragments) across the trust boundary.
|
||||||
|
log.exception("github fetch failed for %s", username)
|
||||||
|
return jsonify({"error": "fetch_failed"}), 502
|
||||||
if _is_github_not_found(data):
|
if _is_github_not_found(data):
|
||||||
data = {"error": "not_found"}
|
data = {"error": "not_found"}
|
||||||
old = db.get_user(username)
|
old = db.get_user(username)
|
||||||
@@ -65,7 +87,21 @@ def force_fetch():
|
|||||||
@app.route("/avatar/<username>", methods=["GET"])
|
@app.route("/avatar/<username>", methods=["GET"])
|
||||||
@require_internal_token
|
@require_internal_token
|
||||||
def avatar(username: str):
|
def avatar(username: str):
|
||||||
r = requests.get(f"https://github.com/{username}.png", timeout=config.API_TIMEOUT, allow_redirects=True)
|
# SSRF surface: we build https://github.com/<u>.png from path input. The
|
||||||
|
# <username> Flask converter already refuses slashes, but allowlist the
|
||||||
|
# shape anyway so any future change to the proxy path can't turn into a
|
||||||
|
# URL-smuggling primitive.
|
||||||
|
if not _valid_username(username):
|
||||||
|
return jsonify({"error": "invalid_username"}), 400
|
||||||
|
try:
|
||||||
|
r = requests.get(
|
||||||
|
f"https://github.com/{username}.png",
|
||||||
|
timeout=config.API_TIMEOUT,
|
||||||
|
allow_redirects=True,
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
log.exception("avatar fetch failed for %s", username)
|
||||||
|
return jsonify({"error": "avatar_unavailable"}), 502
|
||||||
if r.status_code != 200:
|
if r.status_code != 200:
|
||||||
return jsonify({"error": "avatar unavailable"}), 404
|
return jsonify({"error": "avatar unavailable"}), 404
|
||||||
return Response(r.content, mimetype=r.headers.get("Content-Type", "image/png"))
|
return Response(r.content, mimetype=r.headers.get("Content-Type", "image/png"))
|
||||||
|
|||||||
+93
-43
@@ -1,5 +1,6 @@
|
|||||||
"""GitHub data fetching functions."""
|
"""GitHub data fetching functions."""
|
||||||
|
|
||||||
|
import re
|
||||||
import requests
|
import requests
|
||||||
import base64
|
import base64
|
||||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||||
@@ -8,6 +9,33 @@ from typing import Optional, Protocol
|
|||||||
from . import config
|
from . import config
|
||||||
|
|
||||||
|
|
||||||
|
# GitHub's own username rules: alphanumerics and hyphens, 1–39 chars, no
|
||||||
|
# leading/trailing hyphen, no double-hyphens. The fetcher hard-refuses
|
||||||
|
# anything else before it reaches URL construction or GraphQL interpolation —
|
||||||
|
# the generator validates too, but this is the last line of defense before
|
||||||
|
# we talk to GitHub on a caller's behalf.
|
||||||
|
_USERNAME_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$")
|
||||||
|
|
||||||
|
# Repo full names: owner/repo. Owner matches the username rule; repo allows the
|
||||||
|
# same chars plus dot and underscore (matches GitHub's repo-name regex).
|
||||||
|
_REPO_FULL_NAME_RE = re.compile(
|
||||||
|
r"^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}"
|
||||||
|
r"/[A-Za-z0-9_.-]{1,100}$"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _assert_username(name: str) -> str:
|
||||||
|
if not isinstance(name, str) or not _USERNAME_RE.match(name):
|
||||||
|
raise ValueError(f"invalid github username: {name!r}")
|
||||||
|
return name
|
||||||
|
|
||||||
|
|
||||||
|
def _assert_repo_full_name(name: str) -> str:
|
||||||
|
if not isinstance(name, str) or not _REPO_FULL_NAME_RE.match(name):
|
||||||
|
raise ValueError(f"invalid github repo name: {name!r}")
|
||||||
|
return name
|
||||||
|
|
||||||
|
|
||||||
class GitHubDataSource(Protocol):
|
class GitHubDataSource(Protocol):
|
||||||
"""Protocol for GitHub data sources - allows swapping implementations."""
|
"""Protocol for GitHub data sources - allows swapping implementations."""
|
||||||
|
|
||||||
@@ -101,18 +129,22 @@ class DirectAPISource:
|
|||||||
|
|
||||||
def fetch_user_data(self, username: str) -> dict:
|
def fetch_user_data(self, username: str) -> dict:
|
||||||
"""Fetch user profile data."""
|
"""Fetch user profile data."""
|
||||||
|
_assert_username(username)
|
||||||
return requests.get(
|
return requests.get(
|
||||||
f"{self.base}/users/{username}",
|
f"{self.base}/users/{username}",
|
||||||
headers=self.headers
|
headers=self.headers,
|
||||||
|
timeout=config.API_TIMEOUT,
|
||||||
).json()
|
).json()
|
||||||
|
|
||||||
def fetch_repos(self, username: str) -> list:
|
def fetch_repos(self, username: str) -> list:
|
||||||
"""Fetch user repositories (owned + contributed to)."""
|
"""Fetch user repositories (owned + contributed to)."""
|
||||||
|
_assert_username(username)
|
||||||
# Fetch owned repos
|
# Fetch owned repos
|
||||||
owned = requests.get(
|
owned = requests.get(
|
||||||
f"{self.base}/users/{username}/repos",
|
f"{self.base}/users/{username}/repos",
|
||||||
headers=self.headers,
|
headers=self.headers,
|
||||||
params={"per_page": 100, "sort": "pushed", "type": "owner"},
|
params={"per_page": 100, "sort": "pushed", "type": "owner"},
|
||||||
|
timeout=config.API_TIMEOUT,
|
||||||
).json()
|
).json()
|
||||||
|
|
||||||
# Fetch all repos (includes collabs, orgs)
|
# Fetch all repos (includes collabs, orgs)
|
||||||
@@ -120,6 +152,7 @@ class DirectAPISource:
|
|||||||
f"{self.base}/users/{username}/repos",
|
f"{self.base}/users/{username}/repos",
|
||||||
headers=self.headers,
|
headers=self.headers,
|
||||||
params={"per_page": 100, "sort": "pushed", "type": "all"},
|
params={"per_page": 100, "sort": "pushed", "type": "all"},
|
||||||
|
timeout=config.API_TIMEOUT,
|
||||||
).json()
|
).json()
|
||||||
|
|
||||||
# Combine and deduplicate
|
# Combine and deduplicate
|
||||||
@@ -136,10 +169,12 @@ class DirectAPISource:
|
|||||||
|
|
||||||
def fetch_events(self, username: str) -> list:
|
def fetch_events(self, username: str) -> list:
|
||||||
"""Fetch user events."""
|
"""Fetch user events."""
|
||||||
|
_assert_username(username)
|
||||||
resp = requests.get(
|
resp = requests.get(
|
||||||
f"{self.base}/users/{username}/events",
|
f"{self.base}/users/{username}/events",
|
||||||
headers=self.headers,
|
headers=self.headers,
|
||||||
params={"per_page": 100},
|
params={"per_page": 100},
|
||||||
|
timeout=config.API_TIMEOUT,
|
||||||
).json()
|
).json()
|
||||||
return resp if isinstance(resp, list) else []
|
return resp if isinstance(resp, list) else []
|
||||||
|
|
||||||
@@ -160,28 +195,33 @@ class DirectAPISource:
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
_assert_username(username)
|
||||||
# Get the last year of contribution data
|
# Get the last year of contribution data
|
||||||
now = datetime.now()
|
now = datetime.now()
|
||||||
one_year_ago = now.replace(year=now.year - 1)
|
one_year_ago = now.replace(year=now.year - 1)
|
||||||
from_date = one_year_ago.strftime("%Y-%m-%dT%H:%M:%SZ")
|
from_date = one_year_ago.strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||||
to_date = now.strftime("%Y-%m-%dT%H:%M:%SZ")
|
to_date = now.strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||||
|
|
||||||
query = f'''
|
# Parameterize username + date range — interpolating username into
|
||||||
query {{
|
# the query lets a malicious name break out of the string literal
|
||||||
user(login: "{username}") {{
|
# and smuggle additional GraphQL fields. GitHub's PAT scopes bound
|
||||||
contributionsCollection(from: "{from_date}", to: "{to_date}") {{
|
# the damage, but the injection is still worth shutting down.
|
||||||
contributionCalendar {{
|
query = """
|
||||||
weeks {{
|
query($login: String!, $from: DateTime!, $to: DateTime!) {
|
||||||
contributionDays {{
|
user(login: $login) {
|
||||||
|
contributionsCollection(from: $from, to: $to) {
|
||||||
|
contributionCalendar {
|
||||||
|
weeks {
|
||||||
|
contributionDays {
|
||||||
date
|
date
|
||||||
contributionCount
|
contributionCount
|
||||||
}}
|
}
|
||||||
}}
|
}
|
||||||
}}
|
}
|
||||||
}}
|
}
|
||||||
}}
|
}
|
||||||
}}
|
}
|
||||||
'''
|
"""
|
||||||
|
|
||||||
headers = {
|
headers = {
|
||||||
**self.headers,
|
**self.headers,
|
||||||
@@ -193,7 +233,10 @@ class DirectAPISource:
|
|||||||
|
|
||||||
resp = requests.post(
|
resp = requests.post(
|
||||||
'https://api.github.com/graphql',
|
'https://api.github.com/graphql',
|
||||||
json={'query': query},
|
json={
|
||||||
|
'query': query,
|
||||||
|
'variables': {'login': username, 'from': from_date, 'to': to_date},
|
||||||
|
},
|
||||||
headers=headers,
|
headers=headers,
|
||||||
timeout=config.API_TIMEOUT
|
timeout=config.API_TIMEOUT
|
||||||
)
|
)
|
||||||
@@ -258,6 +301,7 @@ class DirectAPISource:
|
|||||||
"""Fetch all-time contribution count using GraphQL."""
|
"""Fetch all-time contribution count using GraphQL."""
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
|
_assert_username(username)
|
||||||
# First, get account creation date
|
# First, get account creation date
|
||||||
query = '''
|
query = '''
|
||||||
query($username: String!) {
|
query($username: String!) {
|
||||||
@@ -297,24 +341,28 @@ class DirectAPISource:
|
|||||||
# Fetch year by year
|
# Fetch year by year
|
||||||
total_contributions = 0
|
total_contributions = 0
|
||||||
print(f" Fetching contributions from {created_year} to {current_year}...")
|
print(f" Fetching contributions from {created_year} to {current_year}...")
|
||||||
|
year_query = """
|
||||||
|
query($login: String!, $from: DateTime!, $to: DateTime!) {
|
||||||
|
user(login: $login) {
|
||||||
|
contributionsCollection(from: $from, to: $to) {
|
||||||
|
contributionCalendar { totalContributions }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"""
|
||||||
for year in range(created_year, current_year + 1):
|
for year in range(created_year, current_year + 1):
|
||||||
year_query = f'''
|
|
||||||
query {{
|
|
||||||
user(login: "{username}") {{
|
|
||||||
contributionsCollection(from: "{year}-01-01T00:00:00Z", to: "{year}-12-31T23:59:59Z") {{
|
|
||||||
contributionCalendar {{
|
|
||||||
totalContributions
|
|
||||||
}}
|
|
||||||
}}
|
|
||||||
}}
|
|
||||||
}}
|
|
||||||
'''
|
|
||||||
|
|
||||||
year_resp = requests.post(
|
year_resp = requests.post(
|
||||||
'https://api.github.com/graphql',
|
'https://api.github.com/graphql',
|
||||||
json={'query': year_query},
|
json={
|
||||||
|
'query': year_query,
|
||||||
|
'variables': {
|
||||||
|
'login': username,
|
||||||
|
'from': f"{year}-01-01T00:00:00Z",
|
||||||
|
'to': f"{year}-12-31T23:59:59Z",
|
||||||
|
},
|
||||||
|
},
|
||||||
headers=headers,
|
headers=headers,
|
||||||
timeout=config.API_TIMEOUT
|
timeout=config.API_TIMEOUT,
|
||||||
)
|
)
|
||||||
|
|
||||||
if year_resp.ok:
|
if year_resp.ok:
|
||||||
@@ -335,21 +383,20 @@ class DirectAPISource:
|
|||||||
"""Fetch contribution count for a specific date range using GraphQL."""
|
"""Fetch contribution count for a specific date range using GraphQL."""
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
|
_assert_username(username)
|
||||||
# Convert since_date to proper format
|
# Convert since_date to proper format
|
||||||
from_date = f"{since_date}T00:00:00Z"
|
from_date = f"{since_date}T00:00:00Z"
|
||||||
to_date = datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
|
to_date = datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||||
|
|
||||||
query = f'''
|
query = """
|
||||||
query {{
|
query($login: String!, $from: DateTime!, $to: DateTime!) {
|
||||||
user(login: "{username}") {{
|
user(login: $login) {
|
||||||
contributionsCollection(from: "{from_date}", to: "{to_date}") {{
|
contributionsCollection(from: $from, to: $to) {
|
||||||
contributionCalendar {{
|
contributionCalendar { totalContributions }
|
||||||
totalContributions
|
}
|
||||||
}}
|
}
|
||||||
}}
|
}
|
||||||
}}
|
"""
|
||||||
}}
|
|
||||||
'''
|
|
||||||
|
|
||||||
headers = {
|
headers = {
|
||||||
**self.headers,
|
**self.headers,
|
||||||
@@ -361,9 +408,12 @@ class DirectAPISource:
|
|||||||
|
|
||||||
resp = requests.post(
|
resp = requests.post(
|
||||||
'https://api.github.com/graphql',
|
'https://api.github.com/graphql',
|
||||||
json={'query': query},
|
json={
|
||||||
|
'query': query,
|
||||||
|
'variables': {'login': username, 'from': from_date, 'to': to_date},
|
||||||
|
},
|
||||||
headers=headers,
|
headers=headers,
|
||||||
timeout=config.API_TIMEOUT
|
timeout=config.API_TIMEOUT,
|
||||||
)
|
)
|
||||||
|
|
||||||
if resp.ok:
|
if resp.ok:
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { WorkshopScreen } from './screens/WorkshopScreen'
|
|||||||
import { ResultScreen } from './screens/ResultScreen'
|
import { ResultScreen } from './screens/ResultScreen'
|
||||||
import type { WidgetData } from './lib/renderWidgets'
|
import type { WidgetData } from './lib/renderWidgets'
|
||||||
import { DEMO_WIDGET_DATA } from './lib/demoData'
|
import { DEMO_WIDGET_DATA } from './lib/demoData'
|
||||||
|
import { authHeaders, saveEditToken } from './lib/editToken'
|
||||||
|
|
||||||
export type Achievement = {
|
export type Achievement = {
|
||||||
title: string
|
title: string
|
||||||
@@ -86,7 +87,13 @@ export default function App() {
|
|||||||
try {
|
try {
|
||||||
const r = await fetch(`/api/${encodeURIComponent(user)}/data`)
|
const r = await fetch(`/api/${encodeURIComponent(user)}/data`)
|
||||||
if (aborted.current) return
|
if (aborted.current) return
|
||||||
const body = await r.json().catch(() => ({} as { status?: string; data?: WidgetData }))
|
const body = await r.json().catch(
|
||||||
|
() => ({} as { status?: string; data?: WidgetData; edit_token?: string })
|
||||||
|
)
|
||||||
|
// 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
|
const status = body.status
|
||||||
|
|
||||||
if (r.status === 200 && status === 'ready' && body.data) {
|
if (r.status === 200 && status === 'ready' && body.data) {
|
||||||
@@ -149,7 +156,10 @@ export default function App() {
|
|||||||
}
|
}
|
||||||
const patchRes = await fetch(`/api/${encodeURIComponent(username)}/settings`, {
|
const patchRes = await fetch(`/api/${encodeURIComponent(username)}/settings`, {
|
||||||
method: 'PATCH',
|
method: 'PATCH',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...authHeaders(username),
|
||||||
|
},
|
||||||
body: JSON.stringify(backendSettings),
|
body: JSON.stringify(backendSettings),
|
||||||
})
|
})
|
||||||
if (!patchRes.ok && patchRes.status !== 404) {
|
if (!patchRes.ok && patchRes.status !== 404) {
|
||||||
|
|||||||
@@ -1,7 +1,28 @@
|
|||||||
import { useState, useMemo, type ReactNode } from 'react'
|
import { useState, useMemo, type ReactNode } from 'react'
|
||||||
|
import DOMPurify from 'dompurify'
|
||||||
import type { WidgetSettings, Achievement, PerWidgetSettings } from '../App'
|
import type { WidgetSettings, Achievement, PerWidgetSettings } from '../App'
|
||||||
import { renderAllWidgets, type WidgetData } from '../lib/renderWidgets'
|
import { renderAllWidgets, type WidgetData } from '../lib/renderWidgets'
|
||||||
|
|
||||||
|
// Defense-in-depth: the client-rendered preview assembles SVG from
|
||||||
|
// GitHub-sourced strings (collaborator logins, repo names) and user-typed
|
||||||
|
// achievement text. renderWidgets escapes known fields, but one missed
|
||||||
|
// interpolation anywhere upstream would turn into HTML in the preview.
|
||||||
|
// DOMPurify neutralises that without affecting normal SVG shapes/styles.
|
||||||
|
const SVG_SANITIZE_CONFIG = {
|
||||||
|
USE_PROFILES: { svg: true, svgFilters: true },
|
||||||
|
ADD_TAGS: [
|
||||||
|
'image', 'use', 'clipPath', 'defs', 'style', 'animate', 'animateTransform',
|
||||||
|
'feDropShadow', 'filter', 'linearGradient', 'stop',
|
||||||
|
],
|
||||||
|
ADD_ATTR: [
|
||||||
|
'xlink:href', 'href', 'clip-path', 'viewBox', 'preserveAspectRatio',
|
||||||
|
'xmlns', 'xmlns:xlink', 'rx', 'ry', 'attributeName', 'from', 'to', 'dur',
|
||||||
|
'fill', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap',
|
||||||
|
'stroke-linejoin', 'dominant-baseline', 'letter-spacing', 'opacity',
|
||||||
|
'filter', 'flood-color', 'flood-opacity', 'stdDeviation',
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
const THEMES = [
|
const THEMES = [
|
||||||
{ id: 'midnight', label: 'Midnight', color: '#121820' },
|
{ id: 'midnight', label: 'Midnight', color: '#121820' },
|
||||||
{ id: 'onyx', label: 'Onyx', color: '#09090b' },
|
{ id: 'onyx', label: 'Onyx', color: '#09090b' },
|
||||||
@@ -254,7 +275,7 @@ export function WorkshopScreen({
|
|||||||
// Render SVG client-side whenever settings change (instant, no API call)
|
// Render SVG client-side whenever settings change (instant, no API call)
|
||||||
const svgContent = useMemo(() => {
|
const svgContent = useMemo(() => {
|
||||||
if (!widgetData) return ''
|
if (!widgetData) return ''
|
||||||
return renderAllWidgets({
|
const raw = renderAllWidgets({
|
||||||
data: widgetData,
|
data: widgetData,
|
||||||
theme: settings.theme,
|
theme: settings.theme,
|
||||||
widgets: settings.widgets,
|
widgets: settings.widgets,
|
||||||
@@ -264,6 +285,7 @@ export function WorkshopScreen({
|
|||||||
hiddenLanguages: settings.hiddenLanguages,
|
hiddenLanguages: settings.hiddenLanguages,
|
||||||
username,
|
username,
|
||||||
})
|
})
|
||||||
|
return DOMPurify.sanitize(raw, SVG_SANITIZE_CONFIG)
|
||||||
}, [widgetData, settings, username])
|
}, [widgetData, settings, username])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
+359
-33
@@ -16,19 +16,42 @@ Two-phase pipeline:
|
|||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import time
|
||||||
|
from collections import defaultdict, deque
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
from threading import Thread
|
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
|
||||||
|
|
||||||
from . import config, db, fetcher_client, placeholder
|
from . import config, db, fetcher_client, placeholder
|
||||||
|
from .themes import THEMES
|
||||||
|
from .utils import is_valid_username, settings_size_ok
|
||||||
|
import json as _json
|
||||||
|
|
||||||
log = logging.getLogger("generator.api")
|
log = logging.getLogger("generator.api")
|
||||||
|
|
||||||
|
|
||||||
|
# Bounded pool for prefetch kickoffs. The old code spawned an unbounded
|
||||||
|
# Thread() per request, so a burst of PATCH /settings would fork hundreds
|
||||||
|
# of threads each doing a GitHub fetch + SVG compute — easily enough to
|
||||||
|
# swamp a mini PC. The pool's workqueue absorbs spikes; excess kickoffs
|
||||||
|
# wait rather than executing in parallel.
|
||||||
|
_PREFETCH_POOL = ThreadPoolExecutor(
|
||||||
|
max_workers=max(1, config.PREFETCH_MAX_WORKERS),
|
||||||
|
thread_name_prefix="prefetch",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Global cap on concurrent SVG renders. A render is the single most
|
||||||
|
# expensive user-facing operation; capping it makes the worst-case CPU
|
||||||
|
# load predictable regardless of how many callers pile on.
|
||||||
|
_GENERATE_SEMAPHORE = BoundedSemaphore(max(1, config.GENERATE_CONCURRENCY))
|
||||||
|
|
||||||
|
|
||||||
def _kickoff_prefetch(username: str):
|
def _kickoff_prefetch(username: str):
|
||||||
"""Run one prefetch cycle in a background thread. Starts the fetcher
|
"""Run one prefetch cycle in the bounded pool. Starts the fetcher
|
||||||
immediately on enrollment / settings-change so the raw GitHub payload
|
soon after enrollment / settings-change so the raw GitHub payload
|
||||||
is hot by the time the user clicks Generate."""
|
is hot by the time the user clicks Generate, but never runs more
|
||||||
|
than PREFETCH_MAX_WORKERS at once."""
|
||||||
log.info("prefetch kickoff started for %s", username)
|
log.info("prefetch kickoff started for %s", username)
|
||||||
try:
|
try:
|
||||||
from . import worker
|
from . import worker
|
||||||
@@ -39,18 +62,241 @@ def _kickoff_prefetch(username: str):
|
|||||||
|
|
||||||
|
|
||||||
def _kickoff_prefetch_async(username: str):
|
def _kickoff_prefetch_async(username: str):
|
||||||
Thread(target=_kickoff_prefetch, args=(username,), daemon=True).start()
|
try:
|
||||||
|
_PREFETCH_POOL.submit(_kickoff_prefetch, username)
|
||||||
|
except RuntimeError:
|
||||||
|
# Pool was shut down (process exiting). Dropping the kickoff is
|
||||||
|
# safe: the cron loop will pick the job up on its next tick.
|
||||||
|
log.warning("prefetch pool shut down; skipping kickoff for %s", username)
|
||||||
|
|
||||||
|
|
||||||
|
# ---- Per-IP rate limiter -----------------------------------------------------
|
||||||
|
# In-process sliding-window limiter. Good enough for v1; behind a reverse proxy
|
||||||
|
# we read X-Forwarded-For (trusting only the last hop set by the proxy). For a
|
||||||
|
# multi-node deploy, swap this for a Redis-backed limiter.
|
||||||
|
|
||||||
|
_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)
|
||||||
|
|
||||||
|
|
||||||
|
def _client_ip() -> str:
|
||||||
|
fwd = request.headers.get("X-Forwarded-For", "")
|
||||||
|
if fwd:
|
||||||
|
# Last value is the closest trusted proxy's client.
|
||||||
|
return fwd.split(",")[-1].strip()
|
||||||
|
return request.remote_addr or "unknown"
|
||||||
|
|
||||||
|
|
||||||
|
def _rate_limit(bucket: str) -> bool:
|
||||||
|
"""Return True if the request is allowed; False if it should be rejected."""
|
||||||
|
limit, window = _RATE_LIMITS[bucket]
|
||||||
|
ip = _client_ip()
|
||||||
|
now = time.time()
|
||||||
|
key = (bucket, ip)
|
||||||
|
with _rate_lock:
|
||||||
|
q = _rate_hits[key]
|
||||||
|
cutoff = now - window
|
||||||
|
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
|
||||||
|
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")
|
_STATIC_DIR = os.path.join(os.path.dirname(__file__), "static")
|
||||||
|
|
||||||
app = Flask(__name__, static_folder=None)
|
app = Flask(__name__, static_folder=None)
|
||||||
|
# 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
|
||||||
|
|
||||||
|
|
||||||
|
# ---- Settings shape validator -----------------------------------------------
|
||||||
|
# Settings flow from the public PATCH endpoint into SQLite and then into widget
|
||||||
|
# renderers. Unvalidated input means an attacker can DoS the render pipeline by
|
||||||
|
# storing an object that makes `int(settings["widget_settings"]["collaborators"]
|
||||||
|
# ["max_count"])` raise, or by ballooning the DB with unbounded fields.
|
||||||
|
# We normalize to an explicit allow-list of fields and coerce/trim types.
|
||||||
|
|
||||||
|
_ALLOWED_WIDGETS = {"grade", "impact", "collaborators", "focus", "languages", "achievements"}
|
||||||
|
_ALLOWED_ICONS = {"trophy", "medal", "star", "hackathon"}
|
||||||
|
_MAX_ACHIEVEMENTS = 10
|
||||||
|
_TITLE_MAX = 80
|
||||||
|
_SUBTITLE_MAX = 160
|
||||||
|
_EVENT_DATE_MAX = 32
|
||||||
|
_MAX_CUSTOM_TAGS = 10
|
||||||
|
_MAX_HIDDEN_LANGS = 40
|
||||||
|
_TAG_MAX = 40
|
||||||
|
_LANG_MAX = 40
|
||||||
|
|
||||||
|
|
||||||
|
def _clip_str(v, max_len: int) -> str:
|
||||||
|
if v is None:
|
||||||
|
return ""
|
||||||
|
s = v if isinstance(v, str) else str(v)
|
||||||
|
return s[:max_len]
|
||||||
|
|
||||||
|
|
||||||
|
def _coerce_achievement(a) -> dict | None:
|
||||||
|
if not isinstance(a, dict):
|
||||||
|
return None
|
||||||
|
title = _clip_str(a.get("title"), _TITLE_MAX).strip()
|
||||||
|
if not title:
|
||||||
|
return None
|
||||||
|
icon = a.get("icon") or "trophy"
|
||||||
|
if not isinstance(icon, str) or icon not in _ALLOWED_ICONS:
|
||||||
|
icon = "trophy"
|
||||||
|
return {
|
||||||
|
"title": title,
|
||||||
|
"subtitle": _clip_str(a.get("subtitle"), _SUBTITLE_MAX),
|
||||||
|
"event_date": _clip_str(a.get("event_date"), _EVENT_DATE_MAX),
|
||||||
|
"icon": icon,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _coerce_str_list(v, max_items: int, max_item_len: int) -> list[str]:
|
||||||
|
if not isinstance(v, list):
|
||||||
|
return []
|
||||||
|
out = []
|
||||||
|
for x in v[:max_items]:
|
||||||
|
if isinstance(x, str) and x:
|
||||||
|
out.append(x[:max_item_len])
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _coerce_widget_settings(v) -> dict:
|
||||||
|
"""Whitelist per-widget settings down to the shape each renderer expects.
|
||||||
|
Anything else is silently dropped — callers cannot smuggle arbitrary keys
|
||||||
|
into the SVG renderers this way."""
|
||||||
|
if not isinstance(v, dict):
|
||||||
|
return {}
|
||||||
|
out: dict[str, dict] = {}
|
||||||
|
allowed = {
|
||||||
|
"grade": {"max_tags": "int"},
|
||||||
|
"impact": {"line_color": "color"},
|
||||||
|
"collaborators": {"max_count": "int", "bar_color": "color"},
|
||||||
|
"focus": {"max_categories": "int"},
|
||||||
|
"languages": {"max_languages": "int"},
|
||||||
|
"achievements": {"max_items": "int"},
|
||||||
|
}
|
||||||
|
for widget, schema in allowed.items():
|
||||||
|
raw = v.get(widget)
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
continue
|
||||||
|
clean = {}
|
||||||
|
for key, kind in schema.items():
|
||||||
|
if key not in raw:
|
||||||
|
continue
|
||||||
|
val = raw[key]
|
||||||
|
if kind == "int":
|
||||||
|
try:
|
||||||
|
clean[key] = int(val)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
continue
|
||||||
|
elif kind == "color":
|
||||||
|
# Deep color validation happens in the widget renderer
|
||||||
|
# (safe_color). Here we only reject obviously wrong types
|
||||||
|
# and length-bomb strings.
|
||||||
|
if isinstance(val, str) and len(val) <= 32:
|
||||||
|
clean[key] = val
|
||||||
|
if clean:
|
||||||
|
out[widget] = clean
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def sanitize_settings(body: dict) -> dict:
|
||||||
|
"""Project an untrusted JSON object down to the fields we accept.
|
||||||
|
|
||||||
|
This is the ONLY place that decides what the settings schema is. Anything
|
||||||
|
not listed here is dropped. Widget renderers can assume the shape holds."""
|
||||||
|
if not isinstance(body, dict):
|
||||||
|
return {}
|
||||||
|
out: dict = {}
|
||||||
|
|
||||||
|
theme = body.get("theme")
|
||||||
|
if isinstance(theme, str) and theme in THEMES:
|
||||||
|
out["theme"] = theme
|
||||||
|
|
||||||
|
if "enabled" in body:
|
||||||
|
out["enabled"] = [w for w in _coerce_str_list(body["enabled"], 20, 32)
|
||||||
|
if w in _ALLOWED_WIDGETS]
|
||||||
|
if "widget_order" in body:
|
||||||
|
out["widget_order"] = [w for w in _coerce_str_list(body["widget_order"], 20, 32)
|
||||||
|
if w in _ALLOWED_WIDGETS]
|
||||||
|
|
||||||
|
if "custom_tags" in body:
|
||||||
|
out["custom_tags"] = _coerce_str_list(body["custom_tags"], _MAX_CUSTOM_TAGS, _TAG_MAX)
|
||||||
|
if "hidden_languages" in body:
|
||||||
|
out["hidden_languages"] = _coerce_str_list(
|
||||||
|
body["hidden_languages"], _MAX_HIDDEN_LANGS, _LANG_MAX
|
||||||
|
)
|
||||||
|
|
||||||
|
if "widget_settings" in body:
|
||||||
|
ws = _coerce_widget_settings(body["widget_settings"])
|
||||||
|
if ws:
|
||||||
|
out["widget_settings"] = ws
|
||||||
|
|
||||||
|
if "achievements" in body:
|
||||||
|
raw = body["achievements"] if isinstance(body["achievements"], list) else []
|
||||||
|
cleaned = []
|
||||||
|
for a in raw[:_MAX_ACHIEVEMENTS]:
|
||||||
|
ca = _coerce_achievement(a)
|
||||||
|
if ca:
|
||||||
|
cleaned.append(ca)
|
||||||
|
out["achievements"] = cleaned
|
||||||
|
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
def require_auth(fn):
|
def require_auth(fn):
|
||||||
@wraps(fn)
|
"""Deprecated passthrough retained for back-compat. New code should use
|
||||||
def wrapper(*args, **kwargs):
|
require_edit_token above, which actually authenticates."""
|
||||||
return fn(*args, **kwargs)
|
return fn
|
||||||
return wrapper
|
|
||||||
|
|
||||||
|
|
||||||
@app.route("/", defaults={"path": ""})
|
@app.route("/", defaults={"path": ""})
|
||||||
@@ -59,6 +305,7 @@ def spa(path: str):
|
|||||||
if path.startswith("api/"):
|
if path.startswith("api/"):
|
||||||
return jsonify({"error": "not found"}), 404
|
return jsonify({"error": "not found"}), 404
|
||||||
if path:
|
if path:
|
||||||
|
# send_from_directory enforces that `path` cannot escape _STATIC_DIR.
|
||||||
try:
|
try:
|
||||||
return send_from_directory(_STATIC_DIR, path)
|
return send_from_directory(_STATIC_DIR, path)
|
||||||
except Exception:
|
except Exception:
|
||||||
@@ -75,16 +322,25 @@ def health():
|
|||||||
|
|
||||||
|
|
||||||
@app.route("/api/<username>", methods=["GET"])
|
@app.route("/api/<username>", methods=["GET"])
|
||||||
|
@rate_limited("read")
|
||||||
def get_widget(username: str):
|
def get_widget(username: str):
|
||||||
|
if not is_valid_username(username):
|
||||||
|
return jsonify({"error": "invalid_username"}), 400
|
||||||
return _serve(username, widget_name="composite")
|
return _serve(username, widget_name="composite")
|
||||||
|
|
||||||
|
|
||||||
@app.route("/api/<username>/<widget>.svg", methods=["GET"])
|
@app.route("/api/<username>/<widget>.svg", methods=["GET"])
|
||||||
|
@rate_limited("read")
|
||||||
def get_widget_named(username: str, widget: str):
|
def get_widget_named(username: str, widget: str):
|
||||||
|
if not is_valid_username(username):
|
||||||
|
return jsonify({"error": "invalid_username"}), 400
|
||||||
|
if widget not in _ALLOWED_WIDGETS and widget != "composite":
|
||||||
|
return jsonify({"error": "unknown_widget"}), 400
|
||||||
return _serve(username, widget_name=widget)
|
return _serve(username, widget_name=widget)
|
||||||
|
|
||||||
|
|
||||||
@app.route("/api/<username>/data", methods=["GET"])
|
@app.route("/api/<username>/data", methods=["GET"])
|
||||||
|
@rate_limited("read")
|
||||||
def get_user_data(username: str):
|
def get_user_data(username: str):
|
||||||
"""Precomputed widget data for client-side SVG rendering.
|
"""Precomputed widget data for client-side SVG rendering.
|
||||||
|
|
||||||
@@ -93,18 +349,33 @@ def get_user_data(username: str):
|
|||||||
`{status: "building"}` with HTTP 202 so the client can show demo data
|
`{status: "building"}` with HTTP 202 so the client can show demo data
|
||||||
and poll until ready.
|
and poll until ready.
|
||||||
"""
|
"""
|
||||||
|
if not is_valid_username(username):
|
||||||
|
return jsonify({"error": "invalid_username"}), 400
|
||||||
settings_row = db.get_settings(username)
|
settings_row = db.get_settings(username)
|
||||||
if settings_row is None:
|
if settings_row is None:
|
||||||
|
if not _rate_limit("enroll"):
|
||||||
|
return jsonify({"status": "rate_limited"}), 429
|
||||||
if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP:
|
if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP:
|
||||||
return jsonify({"status": "rate_limited"}), 429
|
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 = {
|
defaults = {
|
||||||
"theme": "dark",
|
"theme": "dark",
|
||||||
"enabled": config.ENABLED_WIDGETS,
|
"enabled": config.ENABLED_WIDGETS,
|
||||||
"widget_order": config.WIDGET_ORDER,
|
"widget_order": config.WIDGET_ORDER,
|
||||||
}
|
}
|
||||||
db.enroll(username, defaults)
|
result = db.enroll(username, defaults)
|
||||||
_kickoff_prefetch_async(username)
|
_kickoff_prefetch_async(username)
|
||||||
return jsonify({"status": "building"}), 202
|
# 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
|
||||||
|
|
||||||
db.touch_last_requested(username)
|
db.touch_last_requested(username)
|
||||||
|
|
||||||
@@ -112,8 +383,6 @@ def get_user_data(username: str):
|
|||||||
if row is None:
|
if row is None:
|
||||||
return jsonify({"status": "building"}), 202
|
return jsonify({"status": "building"}), 202
|
||||||
|
|
||||||
# Worker writes settings_hash="not_found" + data={"not_found": True}
|
|
||||||
# when GitHub returns 404 for this username.
|
|
||||||
if row["settings_hash"] == "not_found":
|
if row["settings_hash"] == "not_found":
|
||||||
return jsonify({"status": "not_found"}), 404
|
return jsonify({"status": "not_found"}), 404
|
||||||
|
|
||||||
@@ -134,82 +403,132 @@ def _serve(username: str, widget_name: str) -> Response:
|
|||||||
|
|
||||||
db.touch_last_requested(username)
|
db.touch_last_requested(username)
|
||||||
current_hash = db.get_current_widget_hash(username)
|
current_hash = db.get_current_widget_hash(username)
|
||||||
theme = settings_row["settings"].get("theme", "dark")
|
raw_theme = settings_row["settings"].get("theme", "dark")
|
||||||
|
theme = raw_theme if isinstance(raw_theme, str) and raw_theme in THEMES else "dark"
|
||||||
|
|
||||||
|
headers_common = {
|
||||||
|
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; img-src data:",
|
||||||
|
"X-Content-Type-Options": "nosniff",
|
||||||
|
}
|
||||||
|
|
||||||
if current_hash == "not_found":
|
if current_hash == "not_found":
|
||||||
svg = db.get_current_widget(username, widget_name) or placeholder.render("not_found", username, theme=theme)
|
svg = db.get_current_widget(username, widget_name) or placeholder.render("not_found", username, theme=theme)
|
||||||
return Response(svg, mimetype="image/svg+xml",
|
headers = {"X-Widget-Status": "not_found", "Cache-Control": "no-store", **headers_common}
|
||||||
headers={"X-Widget-Status": "not_found", "Cache-Control": "no-store"})
|
return Response(svg, mimetype="image/svg+xml", headers=headers)
|
||||||
|
|
||||||
svg = db.get_current_widget(username, widget_name)
|
svg = db.get_current_widget(username, widget_name)
|
||||||
if svg is None:
|
if svg is None:
|
||||||
return _placeholder_response("building", username, theme=theme)
|
return _placeholder_response("building", username, theme=theme)
|
||||||
|
|
||||||
return Response(svg, mimetype="image/svg+xml",
|
|
||||||
headers = {"X-Widget-Status": "ready",
|
headers = {"X-Widget-Status": "ready",
|
||||||
"Cache-Control": "public, max-age=3600"})
|
"Cache-Control": "public, max-age=3600",
|
||||||
|
**headers_common}
|
||||||
|
return Response(svg, mimetype="image/svg+xml", headers=headers)
|
||||||
|
|
||||||
|
|
||||||
def _placeholder_response(variant: str, username: str, theme: str = "dark") -> Response:
|
def _placeholder_response(variant: str, username: str, theme: str = "dark") -> Response:
|
||||||
svg = placeholder.render(variant, username, theme=theme)
|
svg = placeholder.render(variant, username, theme=theme)
|
||||||
return Response(svg, mimetype="image/svg+xml",
|
return Response(svg, mimetype="image/svg+xml",
|
||||||
headers={"X-Widget-Status": variant, "Cache-Control": "no-store"})
|
headers={"X-Widget-Status": variant, "Cache-Control": "no-store",
|
||||||
|
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; img-src data:",
|
||||||
|
"X-Content-Type-Options": "nosniff"})
|
||||||
|
|
||||||
|
|
||||||
@app.route("/api/enroll", methods=["POST"])
|
@app.route("/api/enroll", methods=["POST"])
|
||||||
|
@rate_limited("enroll")
|
||||||
def enroll_endpoint():
|
def enroll_endpoint():
|
||||||
body = request.get_json(silent=True) or {}
|
body = request.get_json(silent=True) or {}
|
||||||
username = body.get("username")
|
username = body.get("username")
|
||||||
if not username:
|
if not is_valid_username(username):
|
||||||
return jsonify({"error": "username required"}), 400
|
return jsonify({"error": "invalid_username"}), 400
|
||||||
if db.get_settings(username) is not None:
|
if db.get_settings(username) is not None:
|
||||||
return jsonify({"error": "already_enrolled"}), 409
|
return jsonify({"error": "already_enrolled"}), 409
|
||||||
if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP:
|
if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP:
|
||||||
return jsonify({"error": "rate_limited"}), 429
|
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}
|
defaults = {"theme": "dark", "enabled": config.ENABLED_WIDGETS, "widget_order": config.WIDGET_ORDER}
|
||||||
job_id = db.enroll(username, defaults)
|
result = db.enroll(username, defaults)
|
||||||
_kickoff_prefetch_async(username)
|
_kickoff_prefetch_async(username)
|
||||||
return jsonify({"enrolled": True, "job_id": job_id})
|
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"])
|
@app.route("/api/<username>/settings", methods=["GET"])
|
||||||
@require_auth
|
@rate_limited("read")
|
||||||
|
@require_edit_token
|
||||||
def get_settings(username: str):
|
def get_settings(username: str):
|
||||||
s = db.get_settings(username)
|
s = db.get_settings(username)
|
||||||
if s is None:
|
if s is None:
|
||||||
return jsonify({"error": "not_enrolled"}), 404
|
return jsonify({"error": "not_enrolled"}), 404
|
||||||
return jsonify(s)
|
# Strip internal-only fields before returning.
|
||||||
|
return jsonify({
|
||||||
|
"settings": s["settings"],
|
||||||
|
"settings_hash": s["settings_hash"],
|
||||||
|
"manual_refresh_used": s["manual_refresh_used"],
|
||||||
|
"enrolled_at": s["enrolled_at"],
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
@app.route("/api/<username>/settings", methods=["PATCH"])
|
@app.route("/api/<username>/settings", methods=["PATCH"])
|
||||||
@require_auth
|
@rate_limited("mutate")
|
||||||
|
@require_edit_token
|
||||||
def patch_settings(username: str):
|
def patch_settings(username: str):
|
||||||
current = db.get_settings(username)
|
current = db.get_settings(username)
|
||||||
if current is None:
|
if current is None:
|
||||||
return jsonify({"error": "not_enrolled"}), 404
|
return jsonify({"error": "not_enrolled"}), 404
|
||||||
body = request.get_json(silent=True) or {}
|
body = request.get_json(silent=True) or {}
|
||||||
merged = {**current["settings"], **body}
|
clean = sanitize_settings(body)
|
||||||
|
merged = {**current["settings"], **clean}
|
||||||
|
# Defense in depth: reject after-the-fact if the merged blob is pathological.
|
||||||
|
if not settings_size_ok(_json.dumps(merged)):
|
||||||
|
return jsonify({"error": "settings_too_large"}), 413
|
||||||
job_id = db.update_settings(username, merged)
|
job_id = db.update_settings(username, merged)
|
||||||
_kickoff_prefetch_async(username)
|
_kickoff_prefetch_async(username)
|
||||||
return jsonify({"updated": True, "job_id": job_id})
|
return jsonify({"updated": True, "job_id": job_id})
|
||||||
|
|
||||||
|
|
||||||
@app.route("/api/<username>/generate", methods=["POST"])
|
@app.route("/api/<username>/generate", methods=["POST"])
|
||||||
|
@rate_limited("mutate")
|
||||||
def generate(username: str):
|
def generate(username: str):
|
||||||
"""Render the composite SVG from the cached fetcher payload + current
|
"""Render the composite SVG from the cached fetcher payload + current
|
||||||
settings, persist it to widgets.db, and return status. Called by the
|
settings, persist it to widgets.db, and return status. Called by the
|
||||||
Generate button; safe to call repeatedly (each call re-renders with
|
Generate button; safe to call repeatedly (each call re-renders with
|
||||||
the latest settings)."""
|
the latest settings). Unauth'd — anyone can trigger a render of a
|
||||||
|
previously-enrolled user's public widget.
|
||||||
|
|
||||||
|
Capacity:
|
||||||
|
* Per-IP rate limit (mutate bucket) caps how fast any one caller can
|
||||||
|
trigger renders.
|
||||||
|
* Global semaphore caps how many renders run in parallel across all
|
||||||
|
callers — the mini PC backstop. Callers that can't acquire the
|
||||||
|
slot within GENERATE_SEMAPHORE_WAIT_S get 503 + Retry-After so the
|
||||||
|
frontend can back off cleanly.
|
||||||
|
"""
|
||||||
from . import worker
|
from . import worker
|
||||||
|
if not is_valid_username(username):
|
||||||
|
return jsonify({"error": "invalid_username"}), 400
|
||||||
if db.get_settings(username) is None:
|
if db.get_settings(username) is None:
|
||||||
return jsonify({"error": "not_enrolled"}), 404
|
return jsonify({"error": "not_enrolled"}), 404
|
||||||
|
|
||||||
|
acquired = _GENERATE_SEMAPHORE.acquire(timeout=config.GENERATE_SEMAPHORE_WAIT_S)
|
||||||
|
if not acquired:
|
||||||
|
resp = jsonify({"error": "busy"})
|
||||||
|
resp.status_code = 503
|
||||||
|
resp.headers["Retry-After"] = "5"
|
||||||
|
return resp
|
||||||
try:
|
try:
|
||||||
widgets = worker.render_widgets_now(username)
|
widgets = worker.render_widgets_now(username)
|
||||||
except LookupError:
|
except LookupError:
|
||||||
return jsonify({"error": "not_enrolled"}), 404
|
return jsonify({"error": "not_enrolled"}), 404
|
||||||
except Exception as e:
|
except Exception:
|
||||||
log.exception("generate failed for %s", username)
|
log.exception("generate failed for %s", username)
|
||||||
return jsonify({"error": f"render_failed: {e}"}), 502
|
return jsonify({"error": "render_failed"}), 502
|
||||||
|
finally:
|
||||||
|
_GENERATE_SEMAPHORE.release()
|
||||||
|
|
||||||
current_hash = db.get_current_widget_hash(username)
|
current_hash = db.get_current_widget_hash(username)
|
||||||
if current_hash == "not_found":
|
if current_hash == "not_found":
|
||||||
return jsonify({"status": "not_found"}), 404
|
return jsonify({"status": "not_found"}), 404
|
||||||
@@ -221,7 +540,8 @@ def generate(username: str):
|
|||||||
|
|
||||||
|
|
||||||
@app.route("/api/<username>/refresh", methods=["POST"])
|
@app.route("/api/<username>/refresh", methods=["POST"])
|
||||||
@require_auth
|
@rate_limited("mutate")
|
||||||
|
@require_edit_token
|
||||||
def refresh(username: str):
|
def refresh(username: str):
|
||||||
s = db.get_settings(username)
|
s = db.get_settings(username)
|
||||||
if s is None:
|
if s is None:
|
||||||
@@ -230,13 +550,19 @@ def refresh(username: str):
|
|||||||
return jsonify({"error": "already_used"}), 409
|
return jsonify({"error": "already_used"}), 409
|
||||||
try:
|
try:
|
||||||
fetcher_client.force_fetch(username)
|
fetcher_client.force_fetch(username)
|
||||||
except Exception as e:
|
except Exception:
|
||||||
return jsonify({"error": f"fetch failed: {e}"}), 502
|
log.exception("refresh fetcher call failed for %s", username)
|
||||||
|
return jsonify({"error": "fetch_failed"}), 502
|
||||||
job_id = db.enqueue_build(username)
|
job_id = db.enqueue_build(username)
|
||||||
_kickoff_prefetch_async(username)
|
_kickoff_prefetch_async(username)
|
||||||
return jsonify({"refreshed": True, "job_id": job_id})
|
return jsonify({"refreshed": True, "job_id": job_id})
|
||||||
|
|
||||||
|
|
||||||
|
@app.errorhandler(413)
|
||||||
|
def _too_large(_e):
|
||||||
|
return jsonify({"error": "payload_too_large"}), 413
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
db.init_dbs()
|
db.init_dbs()
|
||||||
app.run(host="0.0.0.0", port=config.PORT)
|
app.run(host="0.0.0.0", port=config.PORT)
|
||||||
|
|||||||
@@ -115,3 +115,28 @@ REDIS_URL = os.getenv("REDIS_URL", "")
|
|||||||
ENROLLMENT_DAILY_CAP = int(os.getenv("ENROLLMENT_DAILY_CAP", "50"))
|
ENROLLMENT_DAILY_CAP = int(os.getenv("ENROLLMENT_DAILY_CAP", "50"))
|
||||||
WIDGET_LRU_PER_USER = int(os.getenv("WIDGET_LRU_PER_USER", "10"))
|
WIDGET_LRU_PER_USER = int(os.getenv("WIDGET_LRU_PER_USER", "10"))
|
||||||
POLL_INTERVAL_MINUTES = int(os.getenv("GENERATOR_POLL_INTERVAL_MINUTES", "15"))
|
POLL_INTERVAL_MINUTES = int(os.getenv("GENERATOR_POLL_INTERVAL_MINUTES", "15"))
|
||||||
|
|
||||||
|
# --- Mini-PC capacity controls ---
|
||||||
|
# The generator runs on a single mini PC, so the constraining resources are
|
||||||
|
# CPU (SVG render) and the GitHub PAT (fetch). Everything here is tunable via
|
||||||
|
# env so the operator can loosen limits after measuring real load.
|
||||||
|
|
||||||
|
# Per-IP sliding-window rate limits: (max_hits, window_seconds). These are
|
||||||
|
# anti-abuse ceilings, not capacity controls — the mini PC is actually
|
||||||
|
# protected by the global semaphore + worker pool + queue cap below, so
|
||||||
|
# per-IP numbers stay lenient. Tighten via env only if you see a specific
|
||||||
|
# abuser.
|
||||||
|
RATE_LIMIT_READ_MAX = int(os.getenv("RATE_LIMIT_READ_MAX", "3000"))
|
||||||
|
RATE_LIMIT_READ_WINDOW = int(os.getenv("RATE_LIMIT_READ_WINDOW", "60"))
|
||||||
|
RATE_LIMIT_MUTATE_MAX = int(os.getenv("RATE_LIMIT_MUTATE_MAX", "120"))
|
||||||
|
RATE_LIMIT_MUTATE_WINDOW = int(os.getenv("RATE_LIMIT_MUTATE_WINDOW", "60"))
|
||||||
|
RATE_LIMIT_ENROLL_MAX = int(os.getenv("RATE_LIMIT_ENROLL_MAX", "60"))
|
||||||
|
RATE_LIMIT_ENROLL_WINDOW = int(os.getenv("RATE_LIMIT_ENROLL_WINDOW", "300"))
|
||||||
|
|
||||||
|
# Global across-all-IPs caps. These are the mini-PC backstop: even a
|
||||||
|
# thousand-IP botnet can't induce more than this much work at once.
|
||||||
|
GENERATE_CONCURRENCY = int(os.getenv("GENERATE_CONCURRENCY", "2"))
|
||||||
|
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"))
|
||||||
|
|||||||
+22
-1
@@ -3,18 +3,37 @@
|
|||||||
Run as its own container: CMD python -m src.cron
|
Run as its own container: CMD python -m src.cron
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
|
import os
|
||||||
import time
|
import time
|
||||||
|
|
||||||
from . import config, db, fetcher_client
|
from . import config, db, fetcher_client
|
||||||
|
|
||||||
log = logging.getLogger("generator.cron")
|
log = logging.getLogger("generator.cron")
|
||||||
|
|
||||||
|
# Pacing between users in a single tick. On a mini PC with N enrolled
|
||||||
|
# users, a tight loop would fire N fetcher calls back-to-back, each of
|
||||||
|
# which can become a GitHub call — trivially enough to spike CPU and
|
||||||
|
# burn PAT budget. Default 0.25s keeps 1000 users inside a ~4-minute
|
||||||
|
# tick while leaving headroom in the 15-minute window.
|
||||||
|
_TICK_INTER_USER_SLEEP_S = float(os.getenv("GENERATOR_CRON_INTER_USER_SLEEP_S", "0.25"))
|
||||||
|
|
||||||
|
# Queue-depth backstop. If the build worker is already behind, don't
|
||||||
|
# enqueue more: let it drain. Keeps SQLite from swelling when a burst of
|
||||||
|
# GitHub changes arrives at once.
|
||||||
|
_TICK_QUEUE_CAP = int(os.getenv("GENERATOR_CRON_QUEUE_CAP", str(config.PENDING_JOB_QUEUE_CAP)))
|
||||||
|
|
||||||
|
|
||||||
def tick() -> dict:
|
def tick() -> dict:
|
||||||
enqueued = 0
|
enqueued = 0
|
||||||
failed = 0
|
failed = 0
|
||||||
|
skipped_queue_full = 0
|
||||||
for username in db.list_enrolled():
|
for username in db.list_enrolled():
|
||||||
try:
|
try:
|
||||||
|
if db.pending_job_count() >= _TICK_QUEUE_CAP:
|
||||||
|
skipped_queue_full += 1
|
||||||
|
# Don't hammer the fetcher either when the queue is full.
|
||||||
|
time.sleep(_TICK_INTER_USER_SLEEP_S)
|
||||||
|
continue
|
||||||
info = db.get_settings(username)
|
info = db.get_settings(username)
|
||||||
current = info.get("last_fetcher_payload_hash")
|
current = info.get("last_fetcher_payload_hash")
|
||||||
r = fetcher_client.get_data(username)
|
r = fetcher_client.get_data(username)
|
||||||
@@ -26,7 +45,9 @@ def tick() -> dict:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
log.warning("poll failed for %s: %s", username, e)
|
log.warning("poll failed for %s: %s", username, e)
|
||||||
failed += 1
|
failed += 1
|
||||||
return {"enqueued": enqueued, "failed": failed}
|
if _TICK_INTER_USER_SLEEP_S > 0:
|
||||||
|
time.sleep(_TICK_INTER_USER_SLEEP_S)
|
||||||
|
return {"enqueued": enqueued, "failed": failed, "skipped_queue_full": skipped_queue_full}
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
|||||||
+55
-8
@@ -4,8 +4,10 @@ All access goes through this module so a future Postgres swap is local to here.
|
|||||||
Both DBs are opened with WAL mode.
|
Both DBs are opened with WAL mode.
|
||||||
"""
|
"""
|
||||||
import hashlib
|
import hashlib
|
||||||
|
import hmac as _hmac
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
import secrets
|
||||||
import sqlite3
|
import sqlite3
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
@@ -24,7 +26,8 @@ CREATE TABLE IF NOT EXISTS users (
|
|||||||
enrolled_at TEXT NOT NULL,
|
enrolled_at TEXT NOT NULL,
|
||||||
last_fetcher_payload_hash TEXT,
|
last_fetcher_payload_hash TEXT,
|
||||||
manual_refresh_used INTEGER DEFAULT 0,
|
manual_refresh_used INTEGER DEFAULT 0,
|
||||||
last_requested_at TEXT NOT NULL
|
last_requested_at TEXT NOT NULL,
|
||||||
|
edit_token_hash TEXT
|
||||||
);
|
);
|
||||||
CREATE TABLE IF NOT EXISTS enrollments_daily (
|
CREATE TABLE IF NOT EXISTS enrollments_daily (
|
||||||
day TEXT PRIMARY KEY,
|
day TEXT PRIMARY KEY,
|
||||||
@@ -109,12 +112,33 @@ def _widgets_conn():
|
|||||||
def init_dbs() -> None:
|
def init_dbs() -> None:
|
||||||
with _settings_conn() as c:
|
with _settings_conn() as c:
|
||||||
c.executescript(_SETTINGS_SCHEMA)
|
c.executescript(_SETTINGS_SCHEMA)
|
||||||
|
# Additive migration for DBs created before the auth rollout.
|
||||||
|
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")
|
||||||
c.commit()
|
c.commit()
|
||||||
with _widgets_conn() as c:
|
with _widgets_conn() as c:
|
||||||
c.executescript(_WIDGETS_SCHEMA)
|
c.executescript(_WIDGETS_SCHEMA)
|
||||||
c.commit()
|
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:
|
def settings_hash(settings: dict) -> str:
|
||||||
canonical = json.dumps(settings, sort_keys=True, separators=(",", ":"))
|
canonical = json.dumps(settings, sort_keys=True, separators=(",", ":"))
|
||||||
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||||
@@ -122,17 +146,29 @@ def settings_hash(settings: dict) -> str:
|
|||||||
|
|
||||||
# ---- settings / enrollment ----
|
# ---- settings / enrollment ----
|
||||||
|
|
||||||
def enroll(username: str, defaults: dict) -> int:
|
def enroll(username: str, defaults: dict) -> dict:
|
||||||
"""Insert a settings row + increment daily counter + enqueue build. Returns job_id."""
|
"""Insert a settings row + increment daily counter + enqueue 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.
|
||||||
|
"""
|
||||||
sh = settings_hash(defaults)
|
sh = settings_hash(defaults)
|
||||||
now = _now()
|
now = _now()
|
||||||
|
token = secrets.token_urlsafe(32)
|
||||||
|
token_hash = _hash_edit_token(token)
|
||||||
with _settings_conn() as c:
|
with _settings_conn() as c:
|
||||||
c.execute(
|
cur_ins = c.execute(
|
||||||
"""INSERT INTO users(username, settings_json, settings_hash, enrolled_at, last_requested_at)
|
"""INSERT INTO users(username, settings_json, settings_hash, enrolled_at,
|
||||||
VALUES (?, ?, ?, ?, ?)
|
last_requested_at, edit_token_hash)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?)
|
||||||
ON CONFLICT(username) DO NOTHING""",
|
ON CONFLICT(username) DO NOTHING""",
|
||||||
(username, json.dumps(defaults), sh, now, now),
|
(username, json.dumps(defaults), sh, now, now, token_hash),
|
||||||
)
|
)
|
||||||
|
inserted = cur_ins.rowcount == 1
|
||||||
c.execute(
|
c.execute(
|
||||||
"""INSERT INTO enrollments_daily(day, count) VALUES (?, 1)
|
"""INSERT INTO enrollments_daily(day, count) VALUES (?, 1)
|
||||||
ON CONFLICT(day) DO UPDATE SET count = count + 1""",
|
ON CONFLICT(day) DO UPDATE SET count = count + 1""",
|
||||||
@@ -144,7 +180,10 @@ def enroll(username: str, defaults: dict) -> int:
|
|||||||
(username, now, now),
|
(username, now, now),
|
||||||
)
|
)
|
||||||
c.commit()
|
c.commit()
|
||||||
return cur.lastrowid
|
return {
|
||||||
|
"job_id": cur.lastrowid,
|
||||||
|
"edit_token": token if inserted else None,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def enrollments_today() -> int:
|
def enrollments_today() -> int:
|
||||||
@@ -239,6 +278,14 @@ def enqueue_build(username: str) -> int:
|
|||||||
return cur.lastrowid
|
return cur.lastrowid
|
||||||
|
|
||||||
|
|
||||||
|
def pending_job_count() -> int:
|
||||||
|
"""Depth of the build queue. Used as backpressure so bursts of
|
||||||
|
enroll/PATCH don't blow up SQLite when the worker is behind."""
|
||||||
|
with _settings_conn() as c:
|
||||||
|
row = c.execute("SELECT COUNT(*) AS n FROM jobs WHERE status='pending'").fetchone()
|
||||||
|
return int(row["n"]) if row else 0
|
||||||
|
|
||||||
|
|
||||||
def claim_next_job() -> Optional[dict]:
|
def claim_next_job() -> Optional[dict]:
|
||||||
now = _now()
|
now = _now()
|
||||||
with _settings_conn() as c:
|
with _settings_conn() as c:
|
||||||
|
|||||||
@@ -1,5 +1,17 @@
|
|||||||
"""Utility functions for SVG generation."""
|
"""Utility functions for SVG generation."""
|
||||||
|
|
||||||
from .svg_helpers import escape, card_wrapper, icon_svg
|
from .svg_helpers import escape, card_wrapper, icon_svg
|
||||||
|
from .validate import (
|
||||||
|
is_valid_username,
|
||||||
|
is_valid_color,
|
||||||
|
safe_color,
|
||||||
|
validate_theme_name,
|
||||||
|
clip_text,
|
||||||
|
settings_size_ok,
|
||||||
|
)
|
||||||
|
|
||||||
__all__ = ["escape", "card_wrapper", "icon_svg"]
|
__all__ = [
|
||||||
|
"escape", "card_wrapper", "icon_svg",
|
||||||
|
"is_valid_username", "is_valid_color", "safe_color",
|
||||||
|
"validate_theme_name", "clip_text", "settings_size_ok",
|
||||||
|
]
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ def render_achievements_widget(
|
|||||||
<text x="48" y="20" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
<text x="48" y="20" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||||
font-size="13" font-weight="600" fill="{t["text"]}">{escape(ach.title)}</text>
|
font-size="13" font-weight="600" fill="{t["text"]}">{escape(ach.title)}</text>
|
||||||
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
<text x="48" y="36" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||||
font-size="10" fill="{t["text_secondary"]}">{escape(ach.subtitle)}{(" · " + ach.event_date) if ach.event_date else ""}</text>
|
font-size="10" fill="{t["text_secondary"]}">{escape(ach.subtitle)}{(" · " + escape(ach.event_date)) if ach.event_date else ""}</text>
|
||||||
</g>'''
|
</g>'''
|
||||||
|
|
||||||
total_h = len(shown) * 56 + 50
|
total_h = len(shown) * 56 + 50
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
from ..models import CollaboratorData
|
from ..models import CollaboratorData
|
||||||
from ..themes import THEMES
|
from ..themes import THEMES
|
||||||
from ..utils import escape, card_wrapper
|
from ..utils import escape, card_wrapper, safe_color
|
||||||
|
|
||||||
|
|
||||||
def render_collaborators_widget(collabs: list[CollaboratorData], theme_name: str = "dark", settings: dict | None = None) -> str:
|
def render_collaborators_widget(collabs: list[CollaboratorData], theme_name: str = "dark", settings: dict | None = None) -> str:
|
||||||
@@ -15,7 +15,7 @@ def render_collaborators_widget(collabs: list[CollaboratorData], theme_name: str
|
|||||||
t = THEMES[theme_name]
|
t = THEMES[theme_name]
|
||||||
s = settings or {}
|
s = settings or {}
|
||||||
max_count = min(max(int(s.get("max_count", 5)), 1), 10)
|
max_count = min(max(int(s.get("max_count", 5)), 1), 10)
|
||||||
bar_color = s.get("bar_color") or t["purple"]
|
bar_color = safe_color(s.get("bar_color"), t["purple"])
|
||||||
items = ""
|
items = ""
|
||||||
|
|
||||||
for i, c in enumerate(collabs[:max_count]):
|
for i, c in enumerate(collabs[:max_count]):
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
from ..models import ImpactWeek
|
from ..models import ImpactWeek
|
||||||
from ..themes import THEMES
|
from ..themes import THEMES
|
||||||
from ..utils import card_wrapper
|
from ..utils import card_wrapper, safe_color
|
||||||
|
|
||||||
|
|
||||||
def render_impact_widget(weeks: list[ImpactWeek], theme_name: str = "dark", period: str = "6mo", settings: dict | None = None) -> str:
|
def render_impact_widget(weeks: list[ImpactWeek], theme_name: str = "dark", period: str = "6mo", settings: dict | None = None) -> str:
|
||||||
@@ -13,7 +13,7 @@ def render_impact_widget(weeks: list[ImpactWeek], theme_name: str = "dark", peri
|
|||||||
"""
|
"""
|
||||||
t = THEMES[theme_name]
|
t = THEMES[theme_name]
|
||||||
s = settings or {}
|
s = settings or {}
|
||||||
line_color = s.get("line_color") or t["accent"]
|
line_color = safe_color(s.get("line_color"), t["accent"])
|
||||||
w, h = 380, 200
|
w, h = 380, 200
|
||||||
chart_x, chart_y = 40, 8
|
chart_x, chart_y = 40, 8
|
||||||
chart_w, chart_h = 316, 82
|
chart_w, chart_h = 316, 82
|
||||||
|
|||||||
@@ -54,21 +54,50 @@ def test_enrolled_user_with_built_widget_returns_ready(client):
|
|||||||
|
|
||||||
|
|
||||||
def test_settings_patch_enqueues_rebuild(client):
|
def test_settings_patch_enqueues_rebuild(client):
|
||||||
dbmod.enroll("alice", {"theme": "dark"})
|
token = dbmod.enroll("alice", {"theme": "dark"})["edit_token"]
|
||||||
r = client.patch("/api/alice/settings", json={"theme": "light"})
|
r = client.patch(
|
||||||
|
"/api/alice/settings",
|
||||||
|
json={"theme": "light"},
|
||||||
|
headers={"Authorization": f"Bearer {token}"},
|
||||||
|
)
|
||||||
assert r.status_code == 200
|
assert r.status_code == 200
|
||||||
assert dbmod.get_settings("alice")["settings"]["theme"] == "light"
|
assert dbmod.get_settings("alice")["settings"]["theme"] == "light"
|
||||||
|
|
||||||
|
|
||||||
def test_refresh_is_one_shot(client):
|
def test_settings_patch_without_token_is_unauthorized(client):
|
||||||
dbmod.enroll("alice", {"theme": "dark"})
|
dbmod.enroll("alice", {"theme": "dark"})
|
||||||
|
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 dbmod.get_settings("alice")["settings"]["theme"] == "dark"
|
||||||
|
|
||||||
|
|
||||||
|
def test_settings_patch_with_wrong_token_is_unauthorized(client):
|
||||||
|
dbmod.enroll("alice", {"theme": "dark"})
|
||||||
|
r = client.patch(
|
||||||
|
"/api/alice/settings",
|
||||||
|
json={"theme": "light"},
|
||||||
|
headers={"Authorization": "Bearer not-the-real-token"},
|
||||||
|
)
|
||||||
|
assert r.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_refresh_is_one_shot(client):
|
||||||
|
token = dbmod.enroll("alice", {"theme": "dark"})["edit_token"]
|
||||||
|
headers = {"Authorization": f"Bearer {token}"}
|
||||||
with patch("src.api.fetcher_client.force_fetch", return_value={"changed": True, "payload_hash": "x", "stored": True}):
|
with patch("src.api.fetcher_client.force_fetch", return_value={"changed": True, "payload_hash": "x", "stored": True}):
|
||||||
r1 = client.post("/api/alice/refresh")
|
r1 = client.post("/api/alice/refresh", headers=headers)
|
||||||
assert r1.status_code == 200
|
assert r1.status_code == 200
|
||||||
r2 = client.post("/api/alice/refresh")
|
r2 = client.post("/api/alice/refresh", headers=headers)
|
||||||
assert r2.status_code == 409
|
assert r2.status_code == 409
|
||||||
|
|
||||||
|
|
||||||
|
def test_refresh_without_token_is_unauthorized(client):
|
||||||
|
dbmod.enroll("alice", {"theme": "dark"})
|
||||||
|
r = client.post("/api/alice/refresh")
|
||||||
|
assert r.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
def test_not_found_status_header(client):
|
def test_not_found_status_header(client):
|
||||||
dbmod.enroll("ghost", {"theme": "dark"})
|
dbmod.enroll("ghost", {"theme": "dark"})
|
||||||
dbmod.put_widgets("ghost", "not_found", {"composite": "<svg>404</svg>"})
|
dbmod.put_widgets("ghost", "not_found", {"composite": "<svg>404</svg>"})
|
||||||
@@ -112,7 +141,11 @@ def test_generate_endpoint_rejects_unenrolled(client):
|
|||||||
def test_data_endpoint_unknown_user_enrolls_and_returns_building(client):
|
def test_data_endpoint_unknown_user_enrolls_and_returns_building(client):
|
||||||
r = client.get("/api/alice/data")
|
r = client.get("/api/alice/data")
|
||||||
assert r.status_code == 202
|
assert r.status_code == 202
|
||||||
assert r.get_json() == {"status": "building"}
|
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
|
assert dbmod.get_settings("alice") is not None # auto-enrolled
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -21,13 +21,23 @@ def test_settings_hash_is_deterministic():
|
|||||||
|
|
||||||
def test_enroll_and_get_settings(tmp_dbs):
|
def test_enroll_and_get_settings(tmp_dbs):
|
||||||
defaults = {"theme": "dark", "widgets": ["grade"]}
|
defaults = {"theme": "dark", "widgets": ["grade"]}
|
||||||
job_id = dbmod.enroll("alice", defaults)
|
result = dbmod.enroll("alice", defaults)
|
||||||
assert job_id > 0
|
assert result["job_id"] > 0
|
||||||
|
assert result["edit_token"] # first enrollment surfaces a token
|
||||||
s = dbmod.get_settings("alice")
|
s = dbmod.get_settings("alice")
|
||||||
assert s["settings"] == defaults
|
assert s["settings"] == defaults
|
||||||
assert s["manual_refresh_used"] == 0
|
assert s["manual_refresh_used"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_enroll_twice_does_not_reissue_token(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
|
||||||
|
|
||||||
|
|
||||||
def test_enrollments_daily_counter(tmp_dbs):
|
def test_enrollments_daily_counter(tmp_dbs):
|
||||||
dbmod.enroll("alice", {"theme": "dark"})
|
dbmod.enroll("alice", {"theme": "dark"})
|
||||||
dbmod.enroll("bob", {"theme": "dark"})
|
dbmod.enroll("bob", {"theme": "dark"})
|
||||||
@@ -43,7 +53,7 @@ def test_update_settings_changes_hash(tmp_dbs):
|
|||||||
|
|
||||||
|
|
||||||
def test_claim_job_marks_running(tmp_dbs):
|
def test_claim_job_marks_running(tmp_dbs):
|
||||||
job_id = dbmod.enroll("alice", {"theme": "dark"})
|
job_id = dbmod.enroll("alice", {"theme": "dark"})["job_id"]
|
||||||
job = dbmod.claim_next_job()
|
job = dbmod.claim_next_job()
|
||||||
assert job["id"] == job_id
|
assert job["id"] == job_id
|
||||||
assert job["status"] == "running"
|
assert job["status"] == "running"
|
||||||
@@ -51,7 +61,7 @@ def test_claim_job_marks_running(tmp_dbs):
|
|||||||
|
|
||||||
|
|
||||||
def test_complete_job(tmp_dbs):
|
def test_complete_job(tmp_dbs):
|
||||||
jid = dbmod.enroll("alice", {"theme": "dark"})
|
jid = dbmod.enroll("alice", {"theme": "dark"})["job_id"]
|
||||||
dbmod.claim_next_job()
|
dbmod.claim_next_job()
|
||||||
dbmod.complete_job(jid)
|
dbmod.complete_job(jid)
|
||||||
with dbmod._settings_conn() as c:
|
with dbmod._settings_conn() as c:
|
||||||
@@ -81,7 +91,7 @@ def test_lru_trim_keeps_n_newest(tmp_dbs):
|
|||||||
|
|
||||||
|
|
||||||
def test_reclaim_stuck_running_jobs(tmp_dbs):
|
def test_reclaim_stuck_running_jobs(tmp_dbs):
|
||||||
jid = dbmod.enroll("alice", {"theme": "dark"})
|
jid = dbmod.enroll("alice", {"theme": "dark"})["job_id"]
|
||||||
dbmod.claim_next_job()
|
dbmod.claim_next_job()
|
||||||
# Backdate updated_at to simulate dead worker
|
# Backdate updated_at to simulate dead worker
|
||||||
with dbmod._settings_conn() as c:
|
with dbmod._settings_conn() as c:
|
||||||
|
|||||||
Reference in New Issue
Block a user