Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ dev = [
"ipdb>=0.13.13,<0.14.0",
"aioresponses>=0.7.4,<0.8.0",
"pytest-mock>=3.10.0,<4.0.0",
"httpx>=0.27,<1.0",
]

[tool.taskipy.tasks]
Expand Down
33 changes: 28 additions & 5 deletions src/webhooks/handlers/mp.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
from discord import Bot, Member, Role
from fastapi import HTTPException

from typing import Literal

from src.database.models.dynamic_role import RoleCategory
from src.webhooks.handlers.base import BaseHandler
from src.webhooks.types import WebhookBody, WebhookEvent

# Plan names (casefolded) that carry no Discord role.
_NO_ROLE_SUBSCRIPTIONS = frozenset({"free"})


class MPHandler(BaseHandler):
async def handle(self, body: WebhookBody, bot: Bot):
Expand All @@ -29,18 +34,36 @@ async def _handle_subscription_change(self, body: WebhookBody, bot: Bot) -> dict
"""
Handles the subscription change event.
"""
discord_id, _ = self.validate_common_properties(body)
discord_id, account_id = self.validate_common_properties(body)
subscription_name = self.validate_property(
body.properties.get("subscription_name"), "subscription_name"
)

member = await self.get_guild_member(discord_id, bot)
name = str(subscription_name).strip()
labs = RoleCategory.SUBSCRIPTION_LABS.value
role_group = bot.role_manager.get_group_ids(labs)

# A plan with no Discord role: drop whatever subscription role the member holds.
if name.casefold() in _NO_ROLE_SUBSCRIPTIONS:
member = await self.get_guild_member(discord_id, bot)
await self.swap_role_in_group(
member, None, role_group, bot, allow_no_role=True
)
return self.success()

subscription_id = bot.role_manager.get_post_or_rank(subscription_name)
subscription_id = bot.role_manager.get_role_id(labs, name)
if not subscription_id:
raise ValueError(f"Invalid subscription name: {subscription_name}")
# 4xx, not 500: the sender must not retry an event that can never succeed.
self.logger.warning(
"No role configured for subscription name '%s'",
name,
extra={"account_id": account_id, "discord_id": discord_id},
)
raise HTTPException(
status_code=422, detail=f"Unknown subscription name: {name}"
)

role_group = bot.role_manager.get_group_ids("subscription_labs")
member = await self.get_guild_member(discord_id, bot)
await self.swap_role_in_group(member, subscription_id, role_group, bot)

return self.success()
Expand Down
12 changes: 9 additions & 3 deletions tests/src/webhooks/handlers/test_mp.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import pytest
from fastapi import HTTPException
from unittest.mock import AsyncMock, MagicMock

from src.webhooks.handlers.mp import MPHandler
Expand Down Expand Up @@ -50,7 +51,7 @@ async def test_handle_subscription_change_success(self, bot):
handler.get_guild_member = AsyncMock(return_value=mock_member)

bot.role_manager = _make_role_manager(
get_post_or_rank=lambda what: 555,
get_role_id=lambda category, key: 555,
get_group_ids=lambda cat: [555, 666, 777],
)
mock_role = MagicMock()
Expand Down Expand Up @@ -84,9 +85,14 @@ async def test_handle_subscription_change_invalid_role(self, bot):
handler.validate_property = MagicMock(return_value=subscription_name)
handler.get_guild_member = AsyncMock(return_value=mock_member)

bot.role_manager = _make_role_manager(get_post_or_rank=lambda what: None)
with pytest.raises(ValueError, match="Invalid subscription name"):
bot.role_manager = _make_role_manager(
get_role_id=lambda category, key: None,
get_group_ids=lambda cat: [],
)
with pytest.raises(HTTPException) as exc_info:
await handler._handle_subscription_change(body, bot)
assert exc_info.value.status_code == 422
handler.get_guild_member.assert_not_awaited()

@pytest.mark.asyncio
async def test_handle_hof_change_success_top1(self, bot):
Expand Down
138 changes: 138 additions & 0 deletions tests/src/webhooks/test_subscription_change_webhook.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
"""End-to-end tests for the SubscriptionChange webhook (issue #205).

Each test sends a signed SubscriptionChange webhook through the real FastAPI app, the real
MPHandler and a real RoleManager filled from the env-var fallback roles (the
`vip` / `dedivip` keys). Only Discord itself is mocked.
"""
import hashlib
import hmac
import json
from unittest.mock import AsyncMock, MagicMock, patch

import httpx
import pytest

from src.core import settings
from src.database.models.dynamic_role import DynamicRole, RoleCategory
from src.services.role_manager import RoleManager
from src.webhooks import handlers, server
from src.webhooks.types import Platform


def _role(role_id: int) -> MagicMock:
role = MagicMock()
role.id = role_id
return role


@pytest.fixture
def fake_bot(monkeypatch):
"""A bot whose guild has the VIP and VIP+ roles and one member holding no subscription role."""
role_manager = RoleManager(fallback_roles=settings.roles)
roles: dict = {}
role_manager._apply_fallbacks(roles) # same code path load() uses when the DB has no row
role_manager._roles = roles

guild_roles = {rid: _role(rid) for rid in role_manager.get_group_ids("subscription_labs")}

member = MagicMock()
member.roles = []
member.add_roles = AsyncMock()
member.remove_roles = AsyncMock()

guild = MagicMock()
guild.get_role.side_effect = guild_roles.get
guild.fetch_member = AsyncMock(return_value=member)

bot = MagicMock()
bot.role_manager = role_manager
bot.guilds = [guild]
bot.fetch_guild = AsyncMock(return_value=guild)
bot.member = member
bot.bot_fetch_guild = bot.fetch_guild

monkeypatch.setattr(server, "bot", bot)
return bot


async def _post(subscription_name: str) -> httpx.Response:
raw = json.dumps(
{
"platform": "mp",
"event": "SubscriptionChange",
"properties": {
"discord_id": 123456789,
"account_id": 987654321,
"subscription_name": subscription_name,
},
}
).encode()
signature = hmac.new(settings.WEBHOOK_TOKEN.encode(), raw, hashlib.sha1).hexdigest()
transport = httpx.ASGITransport(app=server.app)
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
return await client.post(
"/webhook", content=raw, headers={"X-Signature": signature, "Content-Type": "application/json"}
)


@pytest.mark.asyncio
@pytest.mark.parametrize("name", ["vip", "dedivip"])
async def test_known_subscription_names_grant_the_role(fake_bot, name):
response = await _post(name)
assert response.status_code == 200
fake_bot.member.add_roles.assert_awaited_once()


@pytest.mark.asyncio
@pytest.mark.parametrize("name", ["Free", "free"])
async def test_free_removes_the_subscription_role(fake_bot, name):
vip_id = fake_bot.role_manager.get_role_id("subscription_labs", "vip")
vip_role = fake_bot.guilds[0].get_role(vip_id)
fake_bot.member.roles = [vip_role]

response = await _post(name)

assert response.status_code == 200
fake_bot.member.remove_roles.assert_awaited_once_with(vip_role, atomic=True)
fake_bot.member.add_roles.assert_not_awaited()


@pytest.mark.asyncio
async def test_free_without_a_subscription_role_changes_nothing(fake_bot):
response = await _post("Free")
assert response.status_code == 200
fake_bot.member.remove_roles.assert_not_awaited()
fake_bot.member.add_roles.assert_not_awaited()


@pytest.mark.asyncio
@pytest.mark.parametrize("name", ["Pro", "Hacker", "nonsense"])
async def test_name_without_a_role_returns_422_and_warns(fake_bot, name):
"""`Hacker` is a rank key: it must not resolve to a role outside the subscription group."""
mp_logger = handlers.handlers[Platform.MAIN].__self__.logger
with patch.object(mp_logger, "warning") as warning, patch.object(server.logger, "error") as error:
response = await _post(name)

assert response.status_code == 422
assert response.json() == {"detail": f"Unknown subscription name: {name}"}
warning.assert_called_once()
assert name in warning.call_args.args
error.assert_not_called()
fake_bot.bot_fetch_guild.assert_not_awaited()
fake_bot.member.add_roles.assert_not_awaited()
fake_bot.member.remove_roles.assert_not_awaited()


@pytest.mark.asyncio
async def test_pro_grants_its_role_once_one_is_configured(fake_bot):
pro = DynamicRole()
pro.key, pro.discord_role_id, pro.category, pro.display_name = "Pro", 4242, RoleCategory.SUBSCRIPTION_LABS, "Pro"
fake_bot.role_manager._roles["subscription_labs"]["Pro"] = pro
pro_role = _role(4242)
known = fake_bot.guilds[0].get_role.side_effect
fake_bot.guilds[0].get_role.side_effect = lambda rid: pro_role if rid == 4242 else known(rid)

response = await _post("Pro")

assert response.status_code == 200
fake_bot.member.add_roles.assert_awaited_once_with(pro_role, atomic=True)
30 changes: 30 additions & 0 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.