Files
Scrobbler/tests/test_federation_keys_sharing.py
T
mattandClaude Sonnet 5 0766c09fb3
CI / validate-monitoring (push) Successful in 10s
CI / lint (push) Successful in 16s
CI / federation-interop (push) Successful in 1m2s
CI / test (push) Successful in 2m40s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 6s
Weekly summary task (phase 3, step 5)
protocol/schedule.py (pure): target_week(now_utc, tz) resolves to
exactly one Monday-Sunday week — the most recent one whose Monday
09:00-local posting gate has passed — computed via wall-clock
arithmetic in the user's own zone so it's correct across a DST change
(a week can be 6h23/7h01 of real time, never silently 7 flat days).
Because it's a pure function of "now", a worker that was down for
weeks naturally catches up with one post, not a backlog. Also
resolve_timezone()/is_valid_timezone() for a settings field that can
otherwise crash a task or silently do nothing forever.

protocol/content.py (pure): the small HTML subset shared by every post
kind (p, strong, em, ol, li), with escaping split from formatting so a
hostile artist/track name can't inject markup.

publishing/weekly.py: build_content() (the template) and
check_and_post()/check_all() (the federation.weekly periodic task,
every 15 minutes). An empty week is simply never posted, and — since
the target week only ever advances — never reconsidered either, with
no separate marker needed. has_post() lets the common "already posted
this week" pass skip the stats queries entirely.

Core: accounts.get_user(id) (federation needs it and can't import the
User model directly); sharing.EDITABLE and update() gain
timezone/post_weekly_summary/post_milestones, with the same
now-not-later validation visibility already had.

Tested: the DST week and gate boundaries against real computed
reference dates (not guessed ones — one guess was wrong and the test
caught it before it shipped), hostile/emoji/RTL names in the template,
and the full task against a real database (empty vs non-empty weeks,
posting twice, disabled settings, a worker down for weeks, a bad
stored timezone not stopping other users).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 12:02:02 +01:00

96 lines
3.6 KiB
Python

import pytest
from cryptography.fernet import InvalidToken
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
from scrobbler.extensions import db
from scrobbler.federation import keys, sharing
from scrobbler.federation.models import FederationKey
def test_defaults_are_private(fed_ctx, user):
settings = sharing.settings_for(user.id)
assert (settings.enabled, settings.visibility) == (False, "followers")
assert not (settings.discoverable or settings.indexable or settings.manually_approves_followers)
assert sharing.shared_user("alice") is None
def test_unsaved_defaults_have_every_field_populated(fed_ctx, user):
"""settings_for() builds a transient object when a user has never saved settings; its
column defaults apply only on INSERT, so every field has to be set by hand."""
settings = sharing.settings_for(user.id)
assert (settings.timezone, settings.post_weekly_summary, settings.post_milestones) == (
"UTC",
True,
True,
)
def test_enabling_creates_a_key_pair_that_signs(fed_ctx, user):
_, toggled = sharing.update(user.id, {"enabled": True})
assert toggled is True
key = db.session.scalar(db.select(FederationKey).filter_by(user_id=user.id))
assert key.public_key_pem.startswith("-----BEGIN PUBLIC KEY-----")
assert b"PRIVATE KEY" not in key.private_key_encrypted # encrypted at rest
message = b"hello fediverse"
signature = keys.private_key(key).sign(message, padding.PKCS1v15(), hashes.SHA256())
public = serialization.load_pem_public_key(key.public_key_pem.encode())
public.verify(signature, message, padding.PKCS1v15(), hashes.SHA256()) # no exception
def test_keys_survive_disable_and_enable(fed_ctx, user):
sharing.update(user.id, {"enabled": True})
first = keys.key_for(user.id).public_key_pem
assert sharing.update(user.id, {"enabled": False})[1] is False
assert sharing.update(user.id, {"enabled": True})[1] is True
assert keys.key_for(user.id).public_key_pem == first
def test_the_wrong_secret_cannot_decrypt(fed_ctx, fed_app, user):
sharing.update(user.id, {"enabled": True})
key = keys.key_for(user.id)
real = fed_app.extensions["federation"]
fed_app.extensions["federation"] = type(real)(
enabled=True, domain=real.domain, base_url=real.base_url, key_secret="y" * 40
)
try:
with pytest.raises(InvalidToken):
keys.private_key(key)
finally:
fed_app.extensions["federation"] = real
def test_instance_actor_key(fed_ctx):
assert keys.key_for(None).user_id is None
assert keys.key_for(None).id == keys.key_for(None).id # created once
def test_shared_user_is_case_insensitive_and_requires_sharing(fed_ctx, user, make_user):
sharing.update(user.id, {"enabled": True})
make_user(username="bob") # exists, not sharing
assert sharing.shared_user("ALICE")[0].id == user.id
assert sharing.shared_user("bob") is None
assert sharing.shared_user("nobody") is None
assert sharing.sharing_count() == 1
@pytest.mark.parametrize(
"changes",
[
{"visibility": "everyone"},
{"user_id": 99},
{"enabled": True, "handle": "x"},
{"timezone": "Mars/Phobos"},
{"timezone": ""},
],
)
def test_invalid_changes_are_rejected(fed_ctx, user, changes):
with pytest.raises(ValueError):
sharing.update(user.id, changes)
def test_a_valid_timezone_can_be_set(fed_ctx, user):
settings, _ = sharing.update(user.id, {"timezone": "Pacific/Auckland"})
assert settings.timezone == "Pacific/Auckland"