maint: Dependency upgrades and High backlog items (v2.11.0)
- All dependencies to current releases (97 known vulnerabilities -> 0), Python 3.14, uv pinned, requirements-test.txt, lxml/dateutil pinned - CSRF tokens on admin forms, logout and IndieAuth consent - IndieAuth client and crosspost link-card fetches via safe_get - FLASK_DEBUG/FLASK_ENV default off/production; image sets them - Foreign keys enforced on pooled connections; migration 018 removes orphans - Rate limits shared across processes (rate_limits, migration 019) - datetime.utcnow() and sqlite3 default adapters replaced - compose.yaml fixed; duplicate dev_auth.py and test.ini removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9f17e145ff
commit
75946be7b2
67 files changed
+885
-498
No files matched your search
@@ -309,6 +309,10 @@ def create_app(config=None):
|
||||
response.headers.add('Link', '</webmention>; rel="webmention"')
|
||||
return response
|
||||
|
||||
# CSRF tokens on admin and consent forms (v2.11.0)
|
||||
from starpunk import csrf
|
||||
csrf.init_app(app)
|
||||
|
||||
# WebSub discovery: Link rel=hub and rel=self on topics (v2.10.0)
|
||||
from starpunk.websub import add_discovery_headers, template_links
|
||||
app.after_request(add_discovery_headers)
|
||||
@@ -470,5 +474,5 @@ def create_app(config=None):
|
||||
|
||||
# Package version (Semantic Versioning 2.0.0)
|
||||
# See docs/standards/versioning-strategy.md for details
|
||||
__version__ = "2.10.2"
|
||||
__version_info__ = (2, 10, 2)
|
||||
__version__ = "2.11.0"
|
||||
__version_info__ = (2, 11, 0)
|
||||
+3
-3
@@ -32,7 +32,7 @@ import base64
|
||||
import hashlib
|
||||
import secrets
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from functools import wraps
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
from urllib.parse import urlencode
|
||||
@@ -223,7 +223,7 @@ def initiate_login(next_url: Optional[str] = None) -> str:
|
||||
nonce,
|
||||
code_verifier,
|
||||
_safe_next_url(next_url),
|
||||
datetime.utcnow() + timedelta(minutes=LOGIN_STATE_MINUTES),
|
||||
datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(minutes=LOGIN_STATE_MINUTES),
|
||||
),
|
||||
)
|
||||
db.commit()
|
||||
@@ -361,7 +361,7 @@ def create_session(me: str) -> str:
|
||||
|
||||
# Calculate expiry (use configured session lifetime or default to 30 days)
|
||||
session_lifetime = current_app.config.get("SESSION_LIFETIME", 30)
|
||||
expires_at = datetime.utcnow() + timedelta(days=session_lifetime)
|
||||
expires_at = datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(days=session_lifetime)
|
||||
|
||||
current_app.logger.debug(f"Auth: Session expiry: {expires_at} ({session_lifetime} days)")
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ Fallback Behavior (per Q14):
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Dict, Optional
|
||||
from urllib.parse import urlparse
|
||||
|
||||
@@ -236,7 +236,7 @@ def get_author_profile(me_url: str, refresh: bool = False) -> Dict:
|
||||
if cached:
|
||||
# Check if cache is still valid
|
||||
cached_until = datetime.fromisoformat(cached['cached_until'])
|
||||
if datetime.utcnow() < cached_until:
|
||||
if datetime.now(timezone.utc).replace(tzinfo=None) < cached_until:
|
||||
current_app.logger.debug(f"Using cached author profile for {me_url}")
|
||||
|
||||
# Parse rel_me_links from JSON
|
||||
@@ -326,7 +326,7 @@ def save_author_profile(me_url: str, profile: Dict) -> None:
|
||||
db = get_db(current_app)
|
||||
|
||||
# Calculate cache expiry (24 hours from now)
|
||||
cached_until = datetime.utcnow() + timedelta(hours=CACHE_TTL_HOURS)
|
||||
cached_until = datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(hours=CACHE_TTL_HOURS)
|
||||
|
||||
# Convert rel_me_links to JSON (per Q17)
|
||||
rel_me_json = json.dumps(profile.get('rel_me_links', []))
|
||||
|
||||
+10
-2
@@ -71,8 +71,10 @@ def load_config(app, config_override=None):
|
||||
app.config["DATABASE_PATH"] = Path(os.getenv("DATABASE_PATH", "./data/starpunk.db"))
|
||||
|
||||
# Flask environment
|
||||
app.config["ENV"] = os.getenv("FLASK_ENV", "development")
|
||||
app.config["DEBUG"] = os.getenv("FLASK_DEBUG", "1") == "1"
|
||||
# Safe defaults (v2.11.0): production, debug off. `flask run --debug`
|
||||
# sets FLASK_DEBUG=1 for local development.
|
||||
app.config["ENV"] = os.getenv("FLASK_ENV", "production")
|
||||
app.config["DEBUG"] = os.getenv("FLASK_DEBUG", "0") == "1"
|
||||
|
||||
# Logging
|
||||
app.config["LOG_LEVEL"] = os.getenv("LOG_LEVEL", "INFO")
|
||||
@@ -153,8 +155,14 @@ def load_config(app, config_override=None):
|
||||
app.config["SYNDICATION_POLL_INTERVAL"] = int(os.getenv("SYNDICATION_POLL_INTERVAL", "10"))
|
||||
|
||||
# Apply overrides if provided
|
||||
# CSRF protection for admin and consent forms (v2.11.0); on by default.
|
||||
# Tests turn it off unless they set CSRF_ENABLED themselves.
|
||||
app.config["CSRF_ENABLED"] = os.getenv("CSRF_ENABLED", "true").lower() == "true"
|
||||
|
||||
if config_override:
|
||||
app.config.update(config_override)
|
||||
if app.config.get("TESTING") and "CSRF_ENABLED" not in config_override:
|
||||
app.config["CSRF_ENABLED"] = False
|
||||
|
||||
# Normalize SITE_URL trailing slash (in case override provided URL without slash)
|
||||
if "SITE_URL" in app.config:
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
"""
|
||||
CSRF protection for the admin and consent forms (v2.11.0)
|
||||
|
||||
The token is an HMAC of the login session cookie under the app secret: no
|
||||
storage, tied to the session, and different after every login. Forms carry
|
||||
it as a hidden `csrf_token` field (template global `csrf_token()`); POSTs to
|
||||
protected endpoints without the right token get 400.
|
||||
|
||||
Protected: every admin POST, logout, and the IndieAuth consent ("approve").
|
||||
Endpoints used by apps with bearer tokens (Micropub, token, revoke,
|
||||
Webmention, WebSub) are not: they have no cookie-based authority.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
|
||||
from flask import abort, current_app, request
|
||||
|
||||
SESSION_COOKIE = "starpunk_session"
|
||||
FIELD = "csrf_token"
|
||||
HEADER = "X-CSRF-Token"
|
||||
PROTECTED_ENDPOINTS = {"auth.logout", "indieauth.approve"}
|
||||
|
||||
|
||||
def csrf_token() -> str:
|
||||
"""The CSRF token for the current login session ('' when not logged in)"""
|
||||
session = request.cookies.get(SESSION_COOKIE)
|
||||
if not session:
|
||||
return ""
|
||||
key = str(current_app.config["SECRET_KEY"]).encode("utf-8")
|
||||
return hmac.new(key, b"csrf:" + session.encode("utf-8"), hashlib.sha256).hexdigest()
|
||||
|
||||
|
||||
def _protected() -> bool:
|
||||
return request.blueprint == "admin" or request.endpoint in PROTECTED_ENDPOINTS
|
||||
|
||||
|
||||
def check_csrf():
|
||||
"""before_request: refuse state-changing requests without a valid token"""
|
||||
if request.method in ("GET", "HEAD", "OPTIONS") or not current_app.config.get("CSRF_ENABLED", True):
|
||||
return None
|
||||
if not _protected():
|
||||
return None
|
||||
expected = csrf_token()
|
||||
if not expected:
|
||||
return None # not logged in: the route's own auth check refuses it
|
||||
sent = request.form.get(FIELD) or request.headers.get(HEADER) or ""
|
||||
if not hmac.compare_digest(sent, expected):
|
||||
current_app.logger.warning(f"CSRF token missing or wrong for {request.endpoint}")
|
||||
abort(400, description="The form expired or came from another site. Reload the page and try again.")
|
||||
return None
|
||||
|
||||
|
||||
def init_app(app) -> None:
|
||||
app.before_request(check_csrf)
|
||||
app.add_template_global(csrf_token, "csrf_token")
|
||||
@@ -13,4 +13,12 @@ from starpunk.database.init import init_db
|
||||
from starpunk.database.pool import init_pool, get_db, get_pool_stats
|
||||
from starpunk.database.schema import INITIAL_SCHEMA_SQL
|
||||
|
||||
# Explicit datetime adapters (v2.11.0). Python 3.12 deprecated sqlite3's
|
||||
# built-in ones; these store exactly what they did ("YYYY-MM-DD HH:MM:SS[.ffffff]").
|
||||
import datetime as _datetime
|
||||
import sqlite3 as _sqlite3
|
||||
|
||||
_sqlite3.register_adapter(_datetime.datetime, lambda value: value.isoformat(" "))
|
||||
_sqlite3.register_adapter(_datetime.date, lambda value: value.isoformat())
|
||||
|
||||
__all__ = ['init_db', 'init_pool', 'get_db', 'get_pool_stats', 'INITIAL_SCHEMA_SQL']
|
||||
@@ -68,6 +68,9 @@ class ConnectionPool:
|
||||
|
||||
# Enable WAL mode for better concurrency
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
# Enforce foreign keys, so ON DELETE CASCADE / SET NULL actually run
|
||||
# (SQLite leaves them off per connection; v2.11.0)
|
||||
conn.execute("PRAGMA foreign_keys=ON")
|
||||
|
||||
self._stats['connections_created'] += 1
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ Per v1.1.2 Phase 3:
|
||||
Specification: http://opml.org/spec2.opml
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from xml.sax.saxutils import escape
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ def generate_opml(site_url: str, site_name: str) -> str:
|
||||
safe_site_name = escape(site_name)
|
||||
|
||||
# RFC 822 date format (required by OPML spec)
|
||||
creation_date = datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
|
||||
creation_date = datetime.now(timezone.utc).replace(tzinfo=None).strftime('%a, %d %b %Y %H:%M:%S GMT')
|
||||
|
||||
# Build OPML document
|
||||
opml_lines = [
|
||||
|
||||
+18
-17
@@ -13,7 +13,7 @@ current IndieAuth spec: https://indieauth.spec.indieweb.org/
|
||||
import base64
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
from urllib.parse import urljoin, urlparse
|
||||
|
||||
@@ -83,41 +83,42 @@ def fetch_client_redirect_uris(client_id: str) -> List[str]:
|
||||
Supports a JSON client metadata document ("redirect_uris") and the older
|
||||
HTML/Link header form (rel="redirect_uri"). Returns [] on any failure.
|
||||
"""
|
||||
from starpunk.webmention_ssrf import SSRFBlockedError, validate_url_for_fetch
|
||||
import json
|
||||
from starpunk.webmention_ssrf import FetchTooLargeError, SSRFBlockedError, safe_get, user_agent
|
||||
|
||||
# Every redirect hop is checked and the connection pinned to the checked
|
||||
# address, with a hard time limit (v2.11.0; DEV_MODE allows localhost)
|
||||
try:
|
||||
if not current_app.config.get("DEV_MODE"):
|
||||
validate_url_for_fetch(client_id)
|
||||
response = httpx.get(
|
||||
result = safe_get(
|
||||
client_id,
|
||||
timeout=5.0,
|
||||
follow_redirects=True,
|
||||
headers={"Accept": "application/json, text/html;q=0.9"},
|
||||
headers={"Accept": "application/json, text/html;q=0.9",
|
||||
"User-Agent": user_agent(current_app.config.get("SITE_URL", ""))},
|
||||
max_bytes=500_000, timeout=5.0, truncate=True,
|
||||
)
|
||||
except (httpx.HTTPError, SSRFBlockedError, ValueError) as e:
|
||||
except (httpx.HTTPError, SSRFBlockedError, ValueError, FetchTooLargeError) as e:
|
||||
current_app.logger.info(f"IndieAuth: could not fetch client {client_id}: {e}")
|
||||
return []
|
||||
|
||||
if response.status_code != 200:
|
||||
if result.status_code != 200:
|
||||
return []
|
||||
|
||||
base = str(response.url)
|
||||
base = result.url
|
||||
uris: List[str] = []
|
||||
|
||||
if "json" in response.headers.get("Content-Type", ""):
|
||||
if "json" in result.headers.get("Content-Type", ""):
|
||||
try:
|
||||
data = response.json()
|
||||
data = json.loads(result.text)
|
||||
except ValueError:
|
||||
return []
|
||||
if isinstance(data, dict) and isinstance(data.get("redirect_uris"), list):
|
||||
uris.extend(u for u in data["redirect_uris"] if isinstance(u, str))
|
||||
return uris
|
||||
|
||||
link = response.links.get("redirect_uri")
|
||||
link = httpx.Response(200, headers=result.headers).links.get("redirect_uri")
|
||||
if link and link.get("url"):
|
||||
uris.append(urljoin(base, link["url"]))
|
||||
|
||||
soup = BeautifulSoup(response.text[:500_000], "html.parser")
|
||||
soup = BeautifulSoup(result.text, "html.parser")
|
||||
for tag in soup.find_all(["link", "a"], href=True):
|
||||
if "redirect_uri" in (tag.get("rel") or []):
|
||||
uris.append(urljoin(base, tag["href"]))
|
||||
@@ -203,7 +204,7 @@ def create_authorization_code(
|
||||
redirect_uri,
|
||||
scope,
|
||||
code_challenge,
|
||||
datetime.utcnow() + timedelta(minutes=CODE_LIFETIME_MINUTES),
|
||||
datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(minutes=CODE_LIFETIME_MINUTES),
|
||||
),
|
||||
)
|
||||
db.commit()
|
||||
@@ -258,7 +259,7 @@ def create_access_token(client_id: str, scope: str) -> Dict[str, Any]:
|
||||
"""Issue an access token (stored hashed); returns the token response"""
|
||||
token = secrets.token_urlsafe(32)
|
||||
lifetime_days = current_app.config.get("INDIEAUTH_TOKEN_LIFETIME_DAYS", 90)
|
||||
expires_at = datetime.utcnow() + timedelta(days=lifetime_days)
|
||||
expires_at = datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(days=lifetime_days)
|
||||
|
||||
db = get_db(current_app)
|
||||
db.execute(
|
||||
|
||||
+9
-9
@@ -8,7 +8,7 @@ state. All models are immutable and use dataclasses for clean structure.
|
||||
|
||||
# Standard library imports
|
||||
from dataclasses import dataclass, field, replace
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
import re
|
||||
@@ -698,7 +698,7 @@ class Session:
|
||||
>>> session.is_expired
|
||||
False
|
||||
"""
|
||||
return datetime.utcnow() >= self.expires_at
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None) >= self.expires_at
|
||||
|
||||
@property
|
||||
def is_active(self) -> bool:
|
||||
@@ -726,7 +726,7 @@ class Session:
|
||||
>>> session.age
|
||||
datetime.timedelta(days=2, seconds=3600)
|
||||
"""
|
||||
return datetime.utcnow() - self.created_at
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None) - self.created_at
|
||||
|
||||
@property
|
||||
def time_until_expiry(self) -> timedelta:
|
||||
@@ -740,7 +740,7 @@ class Session:
|
||||
>>> session.time_until_expiry
|
||||
datetime.timedelta(days=28)
|
||||
"""
|
||||
return self.expires_at - datetime.utcnow()
|
||||
return self.expires_at - datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
def is_valid(self) -> bool:
|
||||
"""
|
||||
@@ -787,7 +787,7 @@ class Session:
|
||||
>>> updated.last_used_at
|
||||
datetime.datetime(2024, 11, 18, 15, 30, 0)
|
||||
"""
|
||||
return replace(self, last_used_at=datetime.utcnow())
|
||||
return replace(self, last_used_at=datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""
|
||||
@@ -863,7 +863,7 @@ class Token:
|
||||
me: str
|
||||
client_id: Optional[str] = None
|
||||
scope: Optional[str] = None
|
||||
created_at: datetime = field(default_factory=lambda: datetime.utcnow())
|
||||
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
expires_at: Optional[datetime] = None
|
||||
|
||||
@classmethod
|
||||
@@ -926,7 +926,7 @@ class Token:
|
||||
# No expiry set, token never expires
|
||||
return False
|
||||
|
||||
return datetime.utcnow() >= self.expires_at
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None) >= self.expires_at
|
||||
|
||||
@property
|
||||
def is_active(self) -> bool:
|
||||
@@ -1145,7 +1145,7 @@ class AuthState:
|
||||
>>> auth_state.is_expired
|
||||
False
|
||||
"""
|
||||
return datetime.utcnow() >= self.expires_at
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None) >= self.expires_at
|
||||
|
||||
@property
|
||||
def is_active(self) -> bool:
|
||||
@@ -1169,7 +1169,7 @@ class AuthState:
|
||||
>>> auth_state.age
|
||||
datetime.timedelta(seconds=120)
|
||||
"""
|
||||
return datetime.utcnow() - self.created_at
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None) - self.created_at
|
||||
|
||||
def is_valid(self) -> bool:
|
||||
"""
|
||||
|
||||
@@ -24,7 +24,7 @@ import random
|
||||
import time
|
||||
from collections import deque
|
||||
from dataclasses import dataclass, field, asdict
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from threading import Lock
|
||||
from typing import Any, Deque, Dict, List, Literal, Optional, Union
|
||||
|
||||
@@ -159,7 +159,7 @@ class MetricsBuffer:
|
||||
metric = Metric(
|
||||
operation_type=operation_type,
|
||||
operation_name=operation_name,
|
||||
timestamp=datetime.utcnow().isoformat() + "Z",
|
||||
timestamp=datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + "Z",
|
||||
duration_ms=duration_ms,
|
||||
process_id=self._process_id,
|
||||
metadata=metadata or {}
|
||||
|
||||
+4
-4
@@ -20,7 +20,7 @@ Exceptions:
|
||||
"""
|
||||
|
||||
# Standard library imports
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
@@ -226,7 +226,7 @@ def create_note(
|
||||
|
||||
# 2. SETUP
|
||||
if created_at is None:
|
||||
created_at = datetime.utcnow()
|
||||
created_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
updated_at = created_at # Same as created_at for new notes
|
||||
|
||||
@@ -735,7 +735,7 @@ def update_note(
|
||||
)
|
||||
|
||||
# 3. SETUP
|
||||
updated_at = datetime.utcnow()
|
||||
updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
data_dir = Path(current_app.config["DATA_PATH"])
|
||||
note_path = data_dir / existing_note.file_path
|
||||
|
||||
@@ -1052,7 +1052,7 @@ def delete_note(
|
||||
|
||||
if soft:
|
||||
# SOFT DELETE: Mark as deleted in database
|
||||
deleted_at = datetime.utcnow()
|
||||
deleted_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
try:
|
||||
db.execute(
|
||||
|
||||
@@ -138,6 +138,79 @@ _ip_limiter: RateLimiter | None = None
|
||||
_domain_limiter: RateLimiter | None = None
|
||||
|
||||
|
||||
class SharedRateLimiter:
|
||||
"""
|
||||
Rate limiter whose counts live in SQLite, shared by every gunicorn
|
||||
process (v2.11.0). In-memory counters let each of the 4 workers allow the
|
||||
full limit, so the real limit was four times the setting.
|
||||
|
||||
Sliding-window counter: the current window's count plus the previous
|
||||
window's, weighted by how much of it still overlaps the last
|
||||
`window_seconds`. Same interface as RateLimiter; needs an app context.
|
||||
"""
|
||||
|
||||
CLEANUP_EVERY = 200 # calls between removals of old windows
|
||||
|
||||
def __init__(self, limit: int, window_seconds: int, prefix: str):
|
||||
self.limit = limit
|
||||
self.window_seconds = window_seconds
|
||||
self.prefix = prefix
|
||||
self._calls = 0
|
||||
|
||||
def _db(self):
|
||||
from flask import current_app
|
||||
from starpunk.database import get_db
|
||||
return get_db(current_app)
|
||||
|
||||
def _windows(self):
|
||||
now = time.time()
|
||||
current = int(now // self.window_seconds)
|
||||
overlap = 1 - (now % self.window_seconds) / self.window_seconds
|
||||
return now, current, overlap
|
||||
|
||||
def _estimate(self, db, key: str) -> float:
|
||||
_, current, overlap = self._windows()
|
||||
counts = dict(db.execute(
|
||||
"SELECT window, count FROM rate_limits WHERE key = ? AND window IN (?, ?)",
|
||||
(f"{self.prefix}:{key}", current - 1, current),
|
||||
).fetchall())
|
||||
return counts.get(current - 1, 0) * overlap + counts.get(current, 0)
|
||||
|
||||
def is_allowed(self, key: str) -> bool:
|
||||
db = self._db()
|
||||
_, current, _ = self._windows()
|
||||
if self._estimate(db, key) >= self.limit:
|
||||
return False
|
||||
db.execute(
|
||||
"INSERT INTO rate_limits (key, window, count) VALUES (?, ?, 1) "
|
||||
"ON CONFLICT(key, window) DO UPDATE SET count = count + 1",
|
||||
(f"{self.prefix}:{key}", current),
|
||||
)
|
||||
db.commit()
|
||||
self._calls += 1
|
||||
if self._calls % self.CLEANUP_EVERY == 0:
|
||||
self.cleanup()
|
||||
return True
|
||||
|
||||
def get_retry_after(self, key: str) -> int:
|
||||
now, current, _ = self._windows()
|
||||
return max(1, int((current + 1) * self.window_seconds - now) + 1)
|
||||
|
||||
def get_request_count(self, key: str) -> int:
|
||||
return int(self._estimate(self._db(), key))
|
||||
|
||||
def cleanup(self, max_idle_seconds: int = 300) -> int:
|
||||
"""Remove windows too old to matter (this limiter's keys only)"""
|
||||
_, current, _ = self._windows()
|
||||
db = self._db()
|
||||
cursor = db.execute(
|
||||
"DELETE FROM rate_limits WHERE key LIKE ? AND window < ?",
|
||||
(f"{self.prefix}:%", current - 1),
|
||||
)
|
||||
db.commit()
|
||||
return cursor.rowcount
|
||||
|
||||
|
||||
def init_rate_limiters(app) -> None:
|
||||
"""
|
||||
Initialize rate limiters with Flask app configuration.
|
||||
@@ -157,8 +230,9 @@ def init_rate_limiters(app) -> None:
|
||||
domain_limit = app.config.get('WEBMENTION_RATE_LIMIT_DOMAIN', 10)
|
||||
window = app.config.get('WEBMENTION_RATE_LIMIT_WINDOW', 60)
|
||||
|
||||
_ip_limiter = RateLimiter(ip_limit, window)
|
||||
_domain_limiter = RateLimiter(domain_limit, window)
|
||||
# Shared by all server processes (v2.11.0)
|
||||
_ip_limiter = SharedRateLimiter(ip_limit, window, "webmention-ip")
|
||||
_domain_limiter = SharedRateLimiter(domain_limit, window, "webmention-domain")
|
||||
|
||||
app.logger.info(
|
||||
f"Webmention rate limiter initialized: {ip_limit}/min IP, "
|
||||
|
||||
@@ -9,7 +9,7 @@ from flask import Blueprint, flash, g, jsonify, redirect, render_template, reque
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -531,7 +531,7 @@ def metrics():
|
||||
from starpunk.monitoring.business import get_feed_statistics
|
||||
|
||||
response = {
|
||||
"timestamp": datetime.utcnow().isoformat() + "Z",
|
||||
"timestamp": datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + "Z",
|
||||
"process_id": os.getpid(),
|
||||
"database": {},
|
||||
"performance": {},
|
||||
|
||||
@@ -6,7 +6,7 @@ No authentication required for these routes.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from flask import Blueprint, abort, render_template, Response, current_app, request, send_from_directory
|
||||
|
||||
@@ -54,7 +54,7 @@ def _get_cached_notes():
|
||||
# Get cache duration from config (in seconds)
|
||||
cache_seconds = current_app.config.get("FEED_CACHE_SECONDS", 300)
|
||||
cache_duration = timedelta(seconds=cache_seconds)
|
||||
now = datetime.utcnow()
|
||||
now = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
# The cached list is stale once any public note changed, in any process
|
||||
# (v2.10.0): every change bumps content_version in the database
|
||||
|
||||
@@ -9,16 +9,15 @@ optional hub.secret and hub.lease_seconds. Answers 202 and verifies later
|
||||
from flask import Blueprint, current_app, request
|
||||
|
||||
from starpunk.database import get_db
|
||||
from starpunk.rate_limiter import RateLimiter
|
||||
from starpunk.rate_limiter import SharedRateLimiter
|
||||
from starpunk import websub
|
||||
|
||||
bp = Blueprint("websub", __name__)
|
||||
|
||||
# Subscription requests per client IP per minute
|
||||
# (per gunicorn process; needs TRUSTED_PROXY=true behind a reverse proxy,
|
||||
# or every client shares the proxy's address)
|
||||
_limiter = RateLimiter(limit=30, window_seconds=60)
|
||||
_requests = 0
|
||||
# Shared by all server processes (v2.11.0). Needs TRUSTED_PROXY=true behind a
|
||||
# reverse proxy, or every client shares the proxy's address.
|
||||
_limiter = SharedRateLimiter(limit=30, window_seconds=60, prefix="websub")
|
||||
|
||||
|
||||
def _text(message: str, status: int):
|
||||
@@ -31,10 +30,6 @@ def hub():
|
||||
return _text("WebSub is not enabled on this site", 404)
|
||||
|
||||
from starpunk.routes.webmention import get_client_ip
|
||||
global _requests
|
||||
_requests += 1
|
||||
if _requests % 500 == 0:
|
||||
_limiter.cleanup() # forget idle clients so memory doesn't grow
|
||||
if not _limiter.is_allowed(get_client_ip()):
|
||||
return _text("Too many requests", 429)
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ Per developer Q&A Q8:
|
||||
import re
|
||||
import unicodedata
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional, Set
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -138,7 +138,7 @@ def sanitize_slug(slug: str, allow_timestamp_fallback: bool = False) -> str:
|
||||
# Check if normalization resulted in empty slug
|
||||
if not slug and allow_timestamp_fallback:
|
||||
# Per Q8: Use timestamp-based fallback
|
||||
timestamp = datetime.utcnow().strftime('%Y%m%d-%H%M%S')
|
||||
timestamp = datetime.now(timezone.utc).replace(tzinfo=None).strftime('%Y%m%d-%H%M%S')
|
||||
slug = timestamp
|
||||
logger.warning(
|
||||
f"Slug normalization failed for input '{original_slug}' "
|
||||
@@ -268,7 +268,7 @@ def generate_timestamp_slug(
|
||||
'20251216143052-2'
|
||||
"""
|
||||
if created_at is None:
|
||||
created_at = datetime.utcnow()
|
||||
created_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
if existing_slugs is None:
|
||||
existing_slugs = set()
|
||||
@@ -340,7 +340,7 @@ def validate_and_sanitize_custom_slug(custom_slug: str, existing_slugs: Set[str]
|
||||
if not sanitized:
|
||||
# This should never happen with allow_timestamp_fallback=True
|
||||
# but handle it just in case
|
||||
timestamp = datetime.utcnow().strftime('%Y%m%d-%H%M%S')
|
||||
timestamp = datetime.now(timezone.utc).replace(tzinfo=None).strftime('%Y%m%d-%H%M%S')
|
||||
sanitized = timestamp
|
||||
logger.error(
|
||||
f"Unexpected empty slug after sanitization with fallback. "
|
||||
@@ -361,7 +361,7 @@ def validate_and_sanitize_custom_slug(custom_slug: str, existing_slugs: Set[str]
|
||||
if not validate_slug(sanitized):
|
||||
# This should rarely happen after sanitization
|
||||
# but if it does, use timestamp fallback
|
||||
timestamp = datetime.utcnow().strftime('%Y%m%d-%H%M%S')
|
||||
timestamp = datetime.now(timezone.utc).replace(tzinfo=None).strftime('%Y%m%d-%H%M%S')
|
||||
logger.warning(
|
||||
f"Slug '{sanitized}' (from '{custom_slug}') failed validation. "
|
||||
f"Using timestamp fallback: {timestamp}"
|
||||
@@ -375,7 +375,7 @@ def validate_and_sanitize_custom_slug(custom_slug: str, existing_slugs: Set[str]
|
||||
except ValueError as e:
|
||||
# This should rarely happen, but if it does, use timestamp
|
||||
# Per Q8: Never fail Micropub request
|
||||
timestamp = datetime.utcnow().strftime('%Y%m%d-%H%M%S')
|
||||
timestamp = datetime.now(timezone.utc).replace(tzinfo=None).strftime('%Y%m%d-%H%M%S')
|
||||
logger.error(
|
||||
f"Could not create unique slug from '{custom_slug}'. "
|
||||
f"Using timestamp: {timestamp}. Error: {e}"
|
||||
|
||||
+30
-32
@@ -444,39 +444,37 @@ CARD_IMAGE_LIMIT = 5 * 1024 * 1024
|
||||
|
||||
def _fetch_public(http: httpx.Client, url: str, limit: int, truncate: bool) -> tuple:
|
||||
"""
|
||||
GET a public web URL, checking every redirect hop (no requests into the
|
||||
LAN). Reads at most `limit` bytes: stops there if `truncate`, else fails.
|
||||
Returns (data, content_type, final_url).
|
||||
"""
|
||||
from urllib.parse import urljoin, urlparse
|
||||
from starpunk.micropub import _public_address
|
||||
GET a public web URL (link card pages, images to re-upload).
|
||||
|
||||
site = current_app.config.get("SITE_URL", "")
|
||||
for _ in range(5):
|
||||
parsed = urlparse(url)
|
||||
if parsed.scheme not in ("http", "https") or not parsed.hostname:
|
||||
raise SyndicationError(f"not a web URL: {url}", permanent=True)
|
||||
if not current_app.config.get("TESTING") and not _public_address(parsed.hostname):
|
||||
raise SyndicationError(f"not a public address: {url}", permanent=True)
|
||||
try:
|
||||
with http.stream("GET", url, follow_redirects=False, timeout=10.0,
|
||||
headers={"User-Agent": f"StarPunk (+{site})"}) as response:
|
||||
if response.is_redirect and "location" in response.headers:
|
||||
url = urljoin(url, response.headers["location"])
|
||||
continue
|
||||
if response.status_code >= 400:
|
||||
raise SyndicationError(f"{url}: HTTP {response.status_code}")
|
||||
data = bytearray()
|
||||
for chunk in response.iter_bytes():
|
||||
data += chunk
|
||||
if len(data) > limit:
|
||||
if truncate:
|
||||
break
|
||||
raise SyndicationError(f"{url}: too large")
|
||||
return bytes(data), response.headers.get("content-type", ""), url
|
||||
except httpx.HTTPError as e:
|
||||
raise SyndicationError(f"{url}: {type(e).__name__}")
|
||||
raise SyndicationError(f"{url}: too many redirects")
|
||||
Uses the shared SSRF-safe fetcher (v2.11.0): every redirect hop checked,
|
||||
the connection pinned to the checked address, a hard 10 s limit. Reads at
|
||||
most `limit` bytes: stops there if `truncate`, else fails.
|
||||
Returns (data, content_type, final_url). `http` is no longer used.
|
||||
"""
|
||||
from urllib.parse import urlparse
|
||||
from starpunk.webmention_ssrf import (
|
||||
FetchTooLargeError, ResolutionError, SSRFBlockedError, safe_get, user_agent,
|
||||
)
|
||||
|
||||
parsed = urlparse(url)
|
||||
if parsed.scheme not in ("http", "https") or not parsed.hostname:
|
||||
raise SyndicationError(f"not a web URL: {url}", permanent=True)
|
||||
try:
|
||||
result = safe_get(url, headers={"User-Agent": user_agent(current_app.config.get("SITE_URL", ""))},
|
||||
max_bytes=limit, max_redirects=5, timeout=10.0, truncate=truncate)
|
||||
except ResolutionError as e:
|
||||
raise SyndicationError(f"{url}: {e}")
|
||||
except (SSRFBlockedError, ValueError) as e:
|
||||
raise SyndicationError(f"not a public address: {url} ({e})", permanent=True)
|
||||
except FetchTooLargeError:
|
||||
raise SyndicationError(f"{url}: too large")
|
||||
except httpx.TooManyRedirects:
|
||||
raise SyndicationError(f"{url}: too many redirects")
|
||||
except httpx.HTTPError as e:
|
||||
raise SyndicationError(f"{url}: {type(e).__name__}")
|
||||
if result.status_code >= 400:
|
||||
raise SyndicationError(f"{url}: HTTP {result.status_code}")
|
||||
return result.content, result.headers.get("content-type", ""), result.url
|
||||
|
||||
|
||||
def page_card(http: httpx.Client, url: str) -> dict:
|
||||
|
||||
+2
-2
@@ -217,7 +217,7 @@ def generate_slug(content: str, created_at: Optional[datetime] = None) -> str:
|
||||
# If slug is empty or too short, use timestamp fallback
|
||||
if len(slug) < MIN_SLUG_LENGTH:
|
||||
if created_at is None:
|
||||
created_at = datetime.utcnow()
|
||||
created_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
slug = created_at.strftime("%Y%m%d-%H%M%S")
|
||||
|
||||
# Truncate to maximum length
|
||||
@@ -592,7 +592,7 @@ def delete_note_file(
|
||||
month = parts[notes_idx + 2]
|
||||
except (ValueError, IndexError):
|
||||
# If path doesn't follow expected structure, use current date
|
||||
now = datetime.utcnow()
|
||||
now = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
year = now.strftime("%Y")
|
||||
month = now.strftime("%m")
|
||||
|
||||
|
||||
@@ -250,7 +250,8 @@ def safe_post(url: str, data: Optional[dict] = None, headers: Optional[dict] = N
|
||||
|
||||
|
||||
def safe_get(url: str, headers: dict, max_bytes: int = MAX_BYTES,
|
||||
max_redirects: int = MAX_REDIRECTS, timeout: float = TIMEOUT) -> FetchResult:
|
||||
max_redirects: int = MAX_REDIRECTS, timeout: float = TIMEOUT,
|
||||
truncate: bool = False) -> FetchResult:
|
||||
"""
|
||||
GET a URL, following redirects by hand and checking each hop.
|
||||
|
||||
@@ -258,6 +259,8 @@ def safe_get(url: str, headers: dict, max_bytes: int = MAX_BYTES,
|
||||
url: URL to fetch
|
||||
headers: Request headers
|
||||
max_bytes: Response body limit
|
||||
truncate: Stop at max_bytes and return what was read, instead of
|
||||
raising FetchTooLargeError (v2.11.0)
|
||||
max_redirects: Redirect limit
|
||||
timeout: Total time limit in seconds
|
||||
|
||||
@@ -287,13 +290,16 @@ def safe_get(url: str, headers: dict, max_bytes: int = MAX_BYTES,
|
||||
continue
|
||||
|
||||
content_length = response.headers.get('Content-Length', '')
|
||||
if content_length.isdigit() and int(content_length) > max_bytes:
|
||||
if not truncate and content_length.isdigit() and int(content_length) > max_bytes:
|
||||
raise FetchTooLargeError(f"Response exceeds size limit ({max_bytes} bytes)")
|
||||
|
||||
content = b''
|
||||
for chunk in response.iter_bytes(chunk_size=8192):
|
||||
content += chunk
|
||||
if len(content) > max_bytes:
|
||||
if truncate:
|
||||
content = content[:max_bytes]
|
||||
break
|
||||
raise FetchTooLargeError(f"Response exceeds size limit ({max_bytes} bytes)")
|
||||
if time.monotonic() > deadline:
|
||||
raise httpx.TimeoutException("Fetch exceeded time limit")
|
||||
|
||||
@@ -19,7 +19,7 @@ import threading
|
||||
import time
|
||||
import sqlite3
|
||||
import httpx
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any, Optional
|
||||
from urllib.parse import urljoin
|
||||
@@ -116,7 +116,7 @@ class WebmentionWorker(threading.Thread):
|
||||
|
||||
# Update last processed time
|
||||
if processed > 0:
|
||||
self._last_processed = datetime.utcnow()
|
||||
self._last_processed = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
# Sleep if nothing processed
|
||||
if processed == 0:
|
||||
@@ -790,7 +790,7 @@ class WebmentionWorker(threading.Thread):
|
||||
}
|
||||
delay = delays.get(new_retry_count)
|
||||
if delay:
|
||||
next_retry_at = datetime.utcnow() + delay
|
||||
next_retry_at = datetime.now(timezone.utc).replace(tzinfo=None) + delay
|
||||
|
||||
try:
|
||||
conn = sqlite3.connect(self.db_path)
|
||||
|
||||
@@ -25,7 +25,7 @@ import hashlib
|
||||
import hmac
|
||||
import logging
|
||||
import threading
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
from urllib.parse import urlencode, urlparse, urlsplit, urlunsplit
|
||||
@@ -53,11 +53,11 @@ def signature(secret: str, body: bytes) -> str:
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None).strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def _later(seconds: int) -> str:
|
||||
return (datetime.utcnow() + timedelta(seconds=seconds)).strftime("%Y-%m-%d %H:%M:%S")
|
||||
return (datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(seconds=seconds)).strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
class WebSubWorker(threading.Thread):
|
||||
@@ -132,7 +132,7 @@ class WebSubWorker(threading.Thread):
|
||||
).fetchall():
|
||||
self._guarded(db, row, "delivery", lambda d, r: self.deliver(d, r, rendered), self._retry_or_drop)
|
||||
done += 1
|
||||
if self._last_prune is None or datetime.utcnow() - self._last_prune > PRUNE_EVERY:
|
||||
if self._last_prune is None or datetime.now(timezone.utc).replace(tzinfo=None) - self._last_prune > PRUNE_EVERY:
|
||||
self.prune(db)
|
||||
return done
|
||||
|
||||
@@ -348,7 +348,7 @@ class WebSubWorker(threading.Thread):
|
||||
db.execute("DELETE FROM websub_deliveries WHERE subscription_id IS NOT NULL AND "
|
||||
"subscription_id NOT IN (SELECT id FROM websub_subscriptions)")
|
||||
db.commit()
|
||||
self._last_prune = datetime.utcnow()
|
||||
self._last_prune = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
if cursor.rowcount:
|
||||
logger.info(f"WebSub: removed {cursor.rowcount} expired subscriptions")
|
||||
return cursor.rowcount
|
||||
|
||||
Reference in new issue
Block a user