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
+6
-6
@@ -4,7 +4,7 @@ Tests for authentication module (starpunk/auth.py)
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import httpx
|
||||
@@ -102,7 +102,7 @@ class TestCleanup:
|
||||
with app.app_context():
|
||||
# Create expired session
|
||||
token_hash = _hash_token("expired-token")
|
||||
expires_at = datetime.utcnow() - timedelta(days=1)
|
||||
expires_at = datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(days=1)
|
||||
|
||||
db.execute(
|
||||
"""
|
||||
@@ -126,7 +126,7 @@ class TestCleanup:
|
||||
"""Test that cleanup keeps valid sessions"""
|
||||
with app.app_context():
|
||||
token_hash = _hash_token("valid-token")
|
||||
expires_at = datetime.utcnow() + timedelta(days=30)
|
||||
expires_at = datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(days=30)
|
||||
|
||||
db.execute(
|
||||
"""
|
||||
@@ -226,7 +226,7 @@ class TestVerifySession:
|
||||
# Create expired session
|
||||
token = secrets.token_urlsafe(32)
|
||||
token_hash = _hash_token(token)
|
||||
expires_at = datetime.utcnow() - timedelta(days=1)
|
||||
expires_at = datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(days=1)
|
||||
|
||||
db.execute(
|
||||
"""
|
||||
@@ -340,7 +340,7 @@ class TestRequireAuthDecorator:
|
||||
with app.app_context():
|
||||
token = secrets.token_urlsafe(32)
|
||||
token_hash = _hash_token(token)
|
||||
expires_at = datetime.utcnow() - timedelta(days=1)
|
||||
expires_at = datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(days=1)
|
||||
|
||||
db.execute(
|
||||
"""
|
||||
@@ -397,7 +397,7 @@ class TestSecurityFeatures:
|
||||
).fetchone()
|
||||
|
||||
expires_at = datetime.fromisoformat(result["expires_at"])
|
||||
created_at = datetime.utcnow()
|
||||
created_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
# Should expire approximately 1 day from now
|
||||
# (allow for minor timing differences)
|
||||
|
||||
@@ -8,7 +8,7 @@ Per v1.2.0 Phase 2 and developer Q&A Q31-Q35:
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
@@ -203,7 +203,7 @@ class TestGetAuthorProfile:
|
||||
from starpunk.database import get_db
|
||||
db = get_db(app)
|
||||
|
||||
expired_time = (datetime.utcnow() - timedelta(hours=48)).isoformat()
|
||||
expired_time = (datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(hours=48)).isoformat()
|
||||
|
||||
db.execute(
|
||||
"""
|
||||
@@ -296,9 +296,9 @@ class TestSaveAuthorProfile:
|
||||
'rel_me_links': [],
|
||||
}
|
||||
|
||||
before_save = datetime.utcnow()
|
||||
before_save = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
save_author_profile('https://cache.example.com', profile)
|
||||
after_save = datetime.utcnow()
|
||||
after_save = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
# Check cache expiry
|
||||
db = get_db(app)
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
"""
|
||||
CSRF protection on admin and consent forms (v2.11.0)
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
import pytest
|
||||
|
||||
from starpunk import create_app
|
||||
from starpunk.auth import create_session
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app(tmp_path):
|
||||
return create_app({
|
||||
"TESTING": True, "CSRF_ENABLED": True, # the real check, unlike other tests
|
||||
"SITE_URL": "http://localhost:5000", "ADMIN_ME": "https://test.example.com",
|
||||
"SESSION_SECRET": "x", "DATA_PATH": tmp_path, "NOTES_PATH": tmp_path / "notes",
|
||||
"DATABASE_PATH": tmp_path / "starpunk.db",
|
||||
})
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin(app):
|
||||
client = app.test_client()
|
||||
with app.test_request_context():
|
||||
client.set_cookie("starpunk_session", create_session(app.config["ADMIN_ME"]))
|
||||
return client
|
||||
|
||||
|
||||
def token_from(page: bytes) -> str:
|
||||
return re.search(rb'name="csrf_token" value="([0-9a-f]{64})"', page).group(1).decode()
|
||||
|
||||
|
||||
def test_forms_carry_a_token(admin):
|
||||
assert token_from(admin.get("/admin/new").data)
|
||||
|
||||
|
||||
def test_post_without_token_is_refused(app, admin):
|
||||
response = admin.post("/admin/new", data={"content": "Forged"})
|
||||
assert response.status_code == 400
|
||||
from starpunk.notes import list_notes
|
||||
with app.app_context():
|
||||
assert list_notes() == []
|
||||
|
||||
|
||||
def test_post_with_wrong_token_is_refused(admin):
|
||||
assert admin.post("/admin/new", data={"content": "x", "csrf_token": "0" * 64}).status_code == 400
|
||||
|
||||
|
||||
def test_post_with_token_works(app, admin):
|
||||
token = token_from(admin.get("/admin/new").data)
|
||||
response = admin.post("/admin/new", data={"content": "Real", "csrf_token": token, "published": "on"})
|
||||
assert response.status_code == 302
|
||||
from starpunk.notes import list_notes
|
||||
with app.app_context():
|
||||
assert [n.content.strip() for n in list_notes()] == ["Real"]
|
||||
|
||||
|
||||
def test_token_changes_with_the_session(app):
|
||||
tokens = []
|
||||
for _ in range(2):
|
||||
client = app.test_client()
|
||||
with app.test_request_context():
|
||||
client.set_cookie("starpunk_session", create_session(app.config["ADMIN_ME"]))
|
||||
tokens.append(token_from(client.get("/admin/new").data))
|
||||
assert tokens[0] != tokens[1]
|
||||
|
||||
|
||||
def test_logout_and_consent_are_protected(admin):
|
||||
assert admin.post("/auth/logout").status_code == 400
|
||||
assert admin.post("/auth/authorize/approve", data={"client_id": "https://app.example/"}).status_code == 400
|
||||
|
||||
|
||||
def test_app_endpoints_are_not_affected(app):
|
||||
client = app.test_client()
|
||||
# Bearer-token and public endpoints answer normally, without a CSRF token
|
||||
assert client.post("/micropub", data={"h": "entry", "content": "x"}).status_code == 401
|
||||
assert client.post("/auth/token", data={"grant_type": "authorization_code"}).status_code == 400
|
||||
assert client.post("/webmention", data={}).status_code == 400
|
||||
@@ -0,0 +1,66 @@
|
||||
"""
|
||||
Foreign keys are enforced (v2.11.0)
|
||||
|
||||
SQLite leaves foreign keys off per connection, so ON DELETE CASCADE never ran
|
||||
and hard deletes left tag, media and variant rows behind.
|
||||
"""
|
||||
|
||||
import io
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from starpunk.database import get_db
|
||||
from starpunk.migrations import execute_in_transaction
|
||||
|
||||
|
||||
def png():
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (30, 20), "red").save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def count(app, sql):
|
||||
return sqlite3.connect(app.config["DATABASE_PATH"]).execute(sql).fetchone()[0]
|
||||
|
||||
|
||||
def test_pooled_connections_enforce_foreign_keys(app):
|
||||
with app.app_context():
|
||||
assert get_db(app).execute("PRAGMA foreign_keys").fetchone()[0] == 1
|
||||
|
||||
|
||||
def test_hard_delete_removes_tags_and_media_links(app):
|
||||
from starpunk.media import attach_media_to_note, save_media
|
||||
from starpunk.notes import create_note, delete_note
|
||||
with app.test_request_context():
|
||||
note = create_note("Tagged with a photo", published=True, tags=["one", "two"], has_media=True)
|
||||
media = save_media(png(), "a.png")
|
||||
attach_media_to_note(note.id, [media["id"]], [""])
|
||||
delete_note(id=note.id, soft=False)
|
||||
assert count(app, "SELECT COUNT(*) FROM note_tags") == 0
|
||||
assert count(app, "SELECT COUNT(*) FROM note_media") == 0
|
||||
|
||||
|
||||
def test_deleting_media_removes_variants(app):
|
||||
from starpunk.media import delete_media, save_media
|
||||
with app.test_request_context():
|
||||
media = save_media(png(), "b.png")
|
||||
delete_media(media["id"])
|
||||
assert count(app, "SELECT COUNT(*) FROM media_variants") == 0
|
||||
|
||||
|
||||
def test_migration_018_removes_existing_orphans(app):
|
||||
conn = sqlite3.connect(app.config["DATABASE_PATH"]) # foreign keys off here
|
||||
conn.execute("INSERT INTO tags (name, display_name) VALUES ('t', 't')")
|
||||
conn.execute("INSERT INTO note_tags (note_id, tag_id) VALUES (999, 1)")
|
||||
conn.execute("INSERT INTO webmentions (source_url, target_url, target_note_id) "
|
||||
"VALUES ('https://s.example/', 'http://localhost:5000/note/x', 999)")
|
||||
conn.commit()
|
||||
sql = (Path(__file__).parent.parent / "migrations" / "018_foreign_key_cleanup.sql").read_text()
|
||||
conn.execute("BEGIN")
|
||||
execute_in_transaction(conn, sql)
|
||||
conn.commit()
|
||||
assert conn.execute("SELECT COUNT(*) FROM note_tags").fetchone()[0] == 0
|
||||
assert conn.execute("SELECT target_note_id FROM webmentions").fetchone()[0] is None
|
||||
assert conn.execute("PRAGMA foreign_key_check").fetchall() == []
|
||||
+41
-14
@@ -129,27 +129,54 @@ class TestValidation:
|
||||
|
||||
|
||||
class TestClientMetadata:
|
||||
def _response(self, content_type, body, links=None):
|
||||
response = MagicMock(status_code=200, text=body, url="https://quill.example/")
|
||||
response.headers = {"Content-Type": content_type}
|
||||
response.links = links or {}
|
||||
response.json.return_value = __import__("json").loads(body) if "json" in content_type else None
|
||||
return response
|
||||
"""Client metadata is fetched through the SSRF-safe fetcher (v2.11.0)"""
|
||||
|
||||
def test_json_metadata(self, app):
|
||||
@staticmethod
|
||||
def _serve(monkeypatch, handler, private=()):
|
||||
import httpx
|
||||
|
||||
def resolve(host, *args, **kwargs):
|
||||
return [(2, 1, 6, "", ("10.0.0.5" if host in private else "93.184.216.34", 0))]
|
||||
|
||||
monkeypatch.setattr("starpunk.webmention_ssrf.TRANSPORT", httpx.MockTransport(handler))
|
||||
monkeypatch.setattr("starpunk.webmention_ssrf.socket.getaddrinfo", resolve)
|
||||
|
||||
def test_json_metadata(self, app, monkeypatch):
|
||||
import httpx
|
||||
body = '{"client_id": "https://quill.example/", "redirect_uris": ["app://cb"]}'
|
||||
with app.test_request_context(), patch(
|
||||
"starpunk.webmention_ssrf.validate_url_for_fetch"
|
||||
), patch("starpunk.indieauth.httpx.get", return_value=self._response("application/json", body)):
|
||||
self._serve(monkeypatch, lambda r: httpx.Response(
|
||||
200, headers={"Content-Type": "application/json"}, text=body))
|
||||
with app.test_request_context():
|
||||
assert fetch_client_redirect_uris(CLIENT_ID) == ["app://cb"]
|
||||
|
||||
def test_html_link(self, app):
|
||||
def test_html_link(self, app, monkeypatch):
|
||||
import httpx
|
||||
body = '<html><head><link rel="redirect_uri" href="/cb"></head></html>'
|
||||
with app.test_request_context(), patch(
|
||||
"starpunk.webmention_ssrf.validate_url_for_fetch"
|
||||
), patch("starpunk.indieauth.httpx.get", return_value=self._response("text/html", body)):
|
||||
self._serve(monkeypatch, lambda r: httpx.Response(
|
||||
200, headers={"Content-Type": "text/html"}, text=body))
|
||||
with app.test_request_context():
|
||||
assert fetch_client_redirect_uris(CLIENT_ID) == ["https://quill.example/cb"]
|
||||
|
||||
def test_link_header(self, app, monkeypatch):
|
||||
import httpx
|
||||
self._serve(monkeypatch, lambda r: httpx.Response(
|
||||
200, headers={"Content-Type": "text/html", "Link": '</cb2>; rel="redirect_uri"'}, text="<p>hi</p>"))
|
||||
with app.test_request_context():
|
||||
assert fetch_client_redirect_uris(CLIENT_ID) == ["https://quill.example/cb2"]
|
||||
|
||||
def test_redirect_to_private_address_refused(self, app, monkeypatch):
|
||||
import httpx
|
||||
fetched = []
|
||||
|
||||
def handler(request):
|
||||
fetched.append(request.headers["host"])
|
||||
return httpx.Response(302, headers={"Location": "http://internal.example/"})
|
||||
|
||||
self._serve(monkeypatch, handler, private={"internal.example"})
|
||||
with app.test_request_context():
|
||||
assert fetch_client_redirect_uris(CLIENT_ID) == []
|
||||
assert "internal.example" not in fetched
|
||||
|
||||
|
||||
class TestCodesAndTokens:
|
||||
def test_full_exchange(self, app):
|
||||
|
||||
+74
-74
@@ -9,7 +9,7 @@ Organized by model:
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from starpunk.models import Note, Session, Token, AuthState, split_title
|
||||
from starpunk.utils import calculate_content_hash
|
||||
@@ -68,8 +68,8 @@ class TestNoteModel:
|
||||
slug="test",
|
||||
file_path="notes/2024/11/test.md",
|
||||
published=True,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
updated_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
_data_dir=tmp_path,
|
||||
)
|
||||
|
||||
@@ -89,8 +89,8 @@ class TestNoteModel:
|
||||
slug="missing",
|
||||
file_path="notes/2024/11/missing.md",
|
||||
published=True,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
updated_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
_data_dir=tmp_path,
|
||||
)
|
||||
|
||||
@@ -109,8 +109,8 @@ class TestNoteModel:
|
||||
slug="test",
|
||||
file_path="notes/2024/11/test.md",
|
||||
published=True,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
updated_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
_data_dir=tmp_path,
|
||||
)
|
||||
|
||||
@@ -130,8 +130,8 @@ class TestNoteModel:
|
||||
slug="test",
|
||||
file_path="notes/2024/11/test.md",
|
||||
published=True,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
updated_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
_data_dir=tmp_path,
|
||||
)
|
||||
|
||||
@@ -150,8 +150,8 @@ class TestNoteModel:
|
||||
slug="test",
|
||||
file_path="notes/2024/11/test.md",
|
||||
published=True,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
updated_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
_data_dir=tmp_path,
|
||||
)
|
||||
|
||||
@@ -168,8 +168,8 @@ class TestNoteModel:
|
||||
slug="test",
|
||||
file_path="notes/2024/11/test.md",
|
||||
published=True,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
updated_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
_data_dir=tmp_path,
|
||||
)
|
||||
|
||||
@@ -182,8 +182,8 @@ class TestNoteModel:
|
||||
slug="my-test-note",
|
||||
file_path="notes/2024/11/test.md",
|
||||
published=True,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
updated_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
_data_dir=Path("/nonexistent"),
|
||||
)
|
||||
|
||||
@@ -202,8 +202,8 @@ class TestNoteModel:
|
||||
slug="test",
|
||||
file_path="notes/2024/11/test.md",
|
||||
published=True,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
updated_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
_data_dir=tmp_path,
|
||||
)
|
||||
|
||||
@@ -222,8 +222,8 @@ class TestNoteModel:
|
||||
slug="test",
|
||||
file_path="notes/2024/11/test.md",
|
||||
published=True,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
updated_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
_data_dir=tmp_path,
|
||||
)
|
||||
|
||||
@@ -238,8 +238,8 @@ class TestNoteModel:
|
||||
slug="my-note",
|
||||
file_path="notes/2024/11/test.md",
|
||||
published=True,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
updated_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
_data_dir=Path("/nonexistent"),
|
||||
)
|
||||
|
||||
@@ -254,8 +254,8 @@ class TestNoteModel:
|
||||
slug="test",
|
||||
file_path="notes/2024/11/test.md",
|
||||
published=True,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
updated_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
_data_dir=tmp_path,
|
||||
)
|
||||
|
||||
@@ -289,8 +289,8 @@ class TestNoteModel:
|
||||
slug="my-note",
|
||||
file_path="notes/2024/11/my-note.md",
|
||||
published=True,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
updated_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
_data_dir=Path("data"),
|
||||
)
|
||||
|
||||
@@ -303,8 +303,8 @@ class TestNoteModel:
|
||||
slug="test",
|
||||
file_path="notes/2024/11/test.md",
|
||||
published=True,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
updated_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
_data_dir=Path("data"),
|
||||
)
|
||||
|
||||
@@ -342,8 +342,8 @@ class TestNoteModel:
|
||||
slug="test",
|
||||
file_path="notes/2024/11/test.md",
|
||||
published=True,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
updated_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
_data_dir=tmp_path,
|
||||
)
|
||||
|
||||
@@ -362,8 +362,8 @@ class TestNoteModel:
|
||||
slug="test",
|
||||
file_path="notes/2024/11/test.md",
|
||||
published=True,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
updated_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
_data_dir=tmp_path,
|
||||
)
|
||||
|
||||
@@ -386,8 +386,8 @@ class TestNoteModel:
|
||||
slug="test",
|
||||
file_path="notes/2024/11/test.md",
|
||||
published=True,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
updated_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
content_hash=content_hash,
|
||||
_data_dir=tmp_path,
|
||||
)
|
||||
@@ -410,8 +410,8 @@ class TestNoteModel:
|
||||
slug="test",
|
||||
file_path="notes/2024/11/test.md",
|
||||
published=True,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
updated_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
content_hash=content_hash,
|
||||
_data_dir=tmp_path,
|
||||
)
|
||||
@@ -433,8 +433,8 @@ class TestNoteModel:
|
||||
slug="test",
|
||||
file_path="notes/2024/11/test.md",
|
||||
published=True,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
updated_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
content_hash=None,
|
||||
_data_dir=tmp_path,
|
||||
)
|
||||
@@ -449,8 +449,8 @@ class TestNoteModel:
|
||||
slug="test",
|
||||
file_path="notes/2024/11/test.md",
|
||||
published=True,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
updated_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
content_hash="abc123",
|
||||
_data_dir=Path("/nonexistent"),
|
||||
)
|
||||
@@ -499,8 +499,8 @@ class TestSessionModel:
|
||||
id=1,
|
||||
session_token="abc123",
|
||||
me="https://alice.example.com",
|
||||
created_at=datetime.utcnow(),
|
||||
expires_at=datetime.utcnow() + timedelta(days=30),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
expires_at=datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(days=30),
|
||||
)
|
||||
assert session.is_expired is False
|
||||
assert session.is_active is True
|
||||
@@ -511,21 +511,21 @@ class TestSessionModel:
|
||||
id=1,
|
||||
session_token="abc123",
|
||||
me="https://alice.example.com",
|
||||
created_at=datetime.utcnow() - timedelta(days=31),
|
||||
expires_at=datetime.utcnow() - timedelta(days=1),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(days=31),
|
||||
expires_at=datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(days=1),
|
||||
)
|
||||
assert session.is_expired is True
|
||||
assert session.is_active is False
|
||||
|
||||
def test_age(self):
|
||||
"""Test age calculation"""
|
||||
created = datetime.utcnow() - timedelta(hours=2)
|
||||
created = datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(hours=2)
|
||||
session = Session(
|
||||
id=1,
|
||||
session_token="abc123",
|
||||
me="https://alice.example.com",
|
||||
created_at=created,
|
||||
expires_at=datetime.utcnow() + timedelta(days=30),
|
||||
expires_at=datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(days=30),
|
||||
)
|
||||
age = session.age
|
||||
# Age should be at least 2 hours (account for test execution time)
|
||||
@@ -537,8 +537,8 @@ class TestSessionModel:
|
||||
id=1,
|
||||
session_token="abc123",
|
||||
me="https://alice.example.com",
|
||||
created_at=datetime.utcnow(),
|
||||
expires_at=datetime.utcnow() + timedelta(days=30),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
expires_at=datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(days=30),
|
||||
)
|
||||
time_left = session.time_until_expiry
|
||||
# Should be approximately 30 days
|
||||
@@ -550,8 +550,8 @@ class TestSessionModel:
|
||||
id=1,
|
||||
session_token="abc123",
|
||||
me="https://alice.example.com",
|
||||
created_at=datetime.utcnow() - timedelta(days=31),
|
||||
expires_at=datetime.utcnow() - timedelta(days=1),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(days=31),
|
||||
expires_at=datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(days=1),
|
||||
)
|
||||
time_left = session.time_until_expiry
|
||||
assert time_left.total_seconds() < 0
|
||||
@@ -562,8 +562,8 @@ class TestSessionModel:
|
||||
id=1,
|
||||
session_token="abc123",
|
||||
me="https://alice.example.com",
|
||||
created_at=datetime.utcnow(),
|
||||
expires_at=datetime.utcnow() + timedelta(days=30),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
expires_at=datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(days=30),
|
||||
)
|
||||
assert session.is_valid() is True
|
||||
|
||||
@@ -573,8 +573,8 @@ class TestSessionModel:
|
||||
id=1,
|
||||
session_token="abc123",
|
||||
me="https://alice.example.com",
|
||||
created_at=datetime.utcnow() - timedelta(days=31),
|
||||
expires_at=datetime.utcnow() - timedelta(days=1),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(days=31),
|
||||
expires_at=datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(days=1),
|
||||
)
|
||||
assert session.is_valid() is False
|
||||
|
||||
@@ -584,8 +584,8 @@ class TestSessionModel:
|
||||
id=1,
|
||||
session_token="",
|
||||
me="https://alice.example.com",
|
||||
created_at=datetime.utcnow(),
|
||||
expires_at=datetime.utcnow() + timedelta(days=30),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
expires_at=datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(days=30),
|
||||
)
|
||||
assert session.is_valid() is False
|
||||
|
||||
@@ -595,8 +595,8 @@ class TestSessionModel:
|
||||
id=1,
|
||||
session_token="abc123",
|
||||
me="",
|
||||
created_at=datetime.utcnow(),
|
||||
expires_at=datetime.utcnow() + timedelta(days=30),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
expires_at=datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(days=30),
|
||||
)
|
||||
assert session.is_valid() is False
|
||||
|
||||
@@ -606,8 +606,8 @@ class TestSessionModel:
|
||||
id=1,
|
||||
session_token="abc123",
|
||||
me="https://alice.example.com",
|
||||
created_at=datetime.utcnow(),
|
||||
expires_at=datetime.utcnow() + timedelta(days=30),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
expires_at=datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(days=30),
|
||||
last_used_at=None,
|
||||
)
|
||||
|
||||
@@ -721,7 +721,7 @@ class TestTokenModel:
|
||||
token = Token(
|
||||
token="xyz789",
|
||||
me="https://alice.example.com",
|
||||
expires_at=datetime.utcnow() + timedelta(days=90),
|
||||
expires_at=datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(days=90),
|
||||
)
|
||||
assert token.is_expired is False
|
||||
assert token.is_active is True
|
||||
@@ -731,7 +731,7 @@ class TestTokenModel:
|
||||
token = Token(
|
||||
token="xyz789",
|
||||
me="https://alice.example.com",
|
||||
expires_at=datetime.utcnow() - timedelta(days=1),
|
||||
expires_at=datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(days=1),
|
||||
)
|
||||
assert token.is_expired is True
|
||||
assert token.is_active is False
|
||||
@@ -746,7 +746,7 @@ class TestTokenModel:
|
||||
token = Token(
|
||||
token="xyz789",
|
||||
me="https://alice.example.com",
|
||||
expires_at=datetime.utcnow() - timedelta(days=1),
|
||||
expires_at=datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(days=1),
|
||||
)
|
||||
assert token.is_valid() is False
|
||||
|
||||
@@ -827,8 +827,8 @@ class TestAuthStateModel:
|
||||
"""Test is_expired returns False for active state"""
|
||||
auth_state = AuthState(
|
||||
state="random123",
|
||||
created_at=datetime.utcnow(),
|
||||
expires_at=datetime.utcnow() + timedelta(minutes=5),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
expires_at=datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(minutes=5),
|
||||
)
|
||||
assert auth_state.is_expired is False
|
||||
assert auth_state.is_active is True
|
||||
@@ -837,19 +837,19 @@ class TestAuthStateModel:
|
||||
"""Test is_expired returns True for expired state"""
|
||||
auth_state = AuthState(
|
||||
state="random123",
|
||||
created_at=datetime.utcnow() - timedelta(minutes=10),
|
||||
expires_at=datetime.utcnow() - timedelta(minutes=5),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(minutes=10),
|
||||
expires_at=datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(minutes=5),
|
||||
)
|
||||
assert auth_state.is_expired is True
|
||||
assert auth_state.is_active is False
|
||||
|
||||
def test_age(self):
|
||||
"""Test age calculation"""
|
||||
created = datetime.utcnow() - timedelta(minutes=2)
|
||||
created = datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(minutes=2)
|
||||
auth_state = AuthState(
|
||||
state="random123",
|
||||
created_at=created,
|
||||
expires_at=datetime.utcnow() + timedelta(minutes=3),
|
||||
expires_at=datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(minutes=3),
|
||||
)
|
||||
age = auth_state.age
|
||||
# Age should be at least 2 minutes
|
||||
@@ -859,8 +859,8 @@ class TestAuthStateModel:
|
||||
"""Test validation succeeds for active state"""
|
||||
auth_state = AuthState(
|
||||
state="random123",
|
||||
created_at=datetime.utcnow(),
|
||||
expires_at=datetime.utcnow() + timedelta(minutes=5),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
expires_at=datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(minutes=5),
|
||||
)
|
||||
assert auth_state.is_valid() is True
|
||||
|
||||
@@ -868,8 +868,8 @@ class TestAuthStateModel:
|
||||
"""Test validation fails for expired state"""
|
||||
auth_state = AuthState(
|
||||
state="random123",
|
||||
created_at=datetime.utcnow() - timedelta(minutes=10),
|
||||
expires_at=datetime.utcnow() - timedelta(minutes=5),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(minutes=10),
|
||||
expires_at=datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(minutes=5),
|
||||
)
|
||||
assert auth_state.is_valid() is False
|
||||
|
||||
@@ -877,8 +877,8 @@ class TestAuthStateModel:
|
||||
"""Test validation fails for empty state"""
|
||||
auth_state = AuthState(
|
||||
state="",
|
||||
created_at=datetime.utcnow(),
|
||||
expires_at=datetime.utcnow() + timedelta(minutes=5),
|
||||
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
expires_at=datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(minutes=5),
|
||||
)
|
||||
assert auth_state.is_valid() is False
|
||||
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
"""
|
||||
Rate limits are shared by all server processes (v2.11.0)
|
||||
|
||||
Each gunicorn process used to keep its own counts, so with 4 workers a client
|
||||
got four times the limit. Two SharedRateLimiter instances on one database
|
||||
stand in for two processes.
|
||||
"""
|
||||
|
||||
import time
|
||||
from unittest.mock import patch
|
||||
|
||||
from starpunk.rate_limiter import SharedRateLimiter
|
||||
|
||||
|
||||
def test_two_processes_share_one_limit(app):
|
||||
first = SharedRateLimiter(limit=3, window_seconds=60, prefix="t")
|
||||
second = SharedRateLimiter(limit=3, window_seconds=60, prefix="t")
|
||||
with app.app_context(), patch("starpunk.rate_limiter.time.time", return_value=6000.0):
|
||||
results = [limiter.is_allowed("1.2.3.4") for limiter in (first, second, first, second)]
|
||||
assert results == [True, True, True, False]
|
||||
|
||||
|
||||
def test_keys_and_prefixes_are_separate(app):
|
||||
a = SharedRateLimiter(limit=1, window_seconds=60, prefix="a")
|
||||
b = SharedRateLimiter(limit=1, window_seconds=60, prefix="b")
|
||||
with app.app_context(), patch("starpunk.rate_limiter.time.time", return_value=6000.0):
|
||||
assert a.is_allowed("x") and a.is_allowed("y") and b.is_allowed("x")
|
||||
assert not a.is_allowed("x")
|
||||
|
||||
|
||||
def test_window_slides(app):
|
||||
limiter = SharedRateLimiter(limit=2, window_seconds=60, prefix="s")
|
||||
with app.app_context():
|
||||
# Window 100 (6000-6059 s): two requests use the limit
|
||||
with patch("starpunk.rate_limiter.time.time", return_value=6000.0):
|
||||
assert limiter.is_allowed("k") and limiter.is_allowed("k")
|
||||
assert not limiter.is_allowed("k")
|
||||
# 6030 s is still window 100: still limited
|
||||
with patch("starpunk.rate_limiter.time.time", return_value=6030.0):
|
||||
assert not limiter.is_allowed("k")
|
||||
# 6090 s is halfway through window 101: window 100 counts half (2 x 0.5 = 1)
|
||||
with patch("starpunk.rate_limiter.time.time", return_value=6090.0):
|
||||
assert limiter.is_allowed("k") # 1 + 0 < 2
|
||||
assert not limiter.is_allowed("k") # 1 + 1 = 2
|
||||
|
||||
|
||||
def test_cleanup_removes_old_windows(app):
|
||||
import sqlite3
|
||||
limiter = SharedRateLimiter(limit=5, window_seconds=60, prefix="c")
|
||||
with app.app_context():
|
||||
with patch("starpunk.rate_limiter.time.time", return_value=6000.0):
|
||||
limiter.is_allowed("k")
|
||||
with patch("starpunk.rate_limiter.time.time", return_value=9000.0):
|
||||
limiter.cleanup()
|
||||
rows = sqlite3.connect(app.config["DATABASE_PATH"]).execute("SELECT COUNT(*) FROM rate_limits").fetchone()[0]
|
||||
assert rows == 0
|
||||
@@ -99,7 +99,8 @@ class FakeWeb:
|
||||
self.fetched = []
|
||||
|
||||
def __call__(self, request):
|
||||
url = str(request.url)
|
||||
# Pinned requests go to the checked IP; the Host header names the site
|
||||
url = f"{request.url.scheme}://{request.headers['host']}{request.url.raw_path.decode()}"
|
||||
self.fetched.append(url)
|
||||
status, headers, body = self.pages.get(url, (404, {}, b"nope"))
|
||||
return httpx.Response(status, headers=headers, content=body)
|
||||
@@ -112,11 +113,20 @@ def web():
|
||||
|
||||
def routed(pds, web):
|
||||
return httpx.MockTransport(
|
||||
lambda r: pds(r) if r.url.host in ("bsky.example", "pds.example") else web(r))
|
||||
lambda r: pds(r) if r.headers.get("host", r.url.host) in ("bsky.example", "pds.example") else web(r))
|
||||
|
||||
|
||||
def resolve(host, *args, **kwargs):
|
||||
"""Every test host is public, except internal.example"""
|
||||
ip = "10.0.0.5" if host == "internal.example" else "93.184.216.34"
|
||||
return [(2, 1, 6, "", (ip, 0))]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app(tmp_path, pds, web):
|
||||
def app(tmp_path, pds, web, monkeypatch):
|
||||
# Pages and images for link cards go through the shared SSRF-safe fetcher (v2.11.0)
|
||||
monkeypatch.setattr("starpunk.webmention_ssrf.TRANSPORT", routed(pds, web))
|
||||
monkeypatch.setattr("starpunk.webmention_ssrf.socket.getaddrinfo", resolve)
|
||||
data = tmp_path / "data"
|
||||
app = create_app({
|
||||
"TESTING": True,
|
||||
@@ -328,12 +338,7 @@ class TestLinkCards:
|
||||
|
||||
def test_redirect_to_private_address_is_not_followed(self, app, pds, web, monkeypatch):
|
||||
web.pages[ARTICLE] = (302, {"location": "http://internal.example/admin"}, b"")
|
||||
monkeypatch.setattr("starpunk.micropub._public_address", lambda host: host != "internal.example")
|
||||
app.config["TESTING"] = False
|
||||
try:
|
||||
publish(app, content=f"See {ARTICLE}")
|
||||
finally:
|
||||
app.config["TESTING"] = True
|
||||
publish(app, content=f"See {ARTICLE}") # internal.example resolves to 10.0.0.5
|
||||
assert "http://internal.example/admin" not in web.fetched
|
||||
assert only_record(pds)["embed"]["external"]["title"] == ARTICLE
|
||||
|
||||
|
||||
Reference in new issue
Block a user