-
Notifications
You must be signed in to change notification settings - Fork 1
Add kick extension and user management services #18
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
3f72657
remove vscode settings file
chrisdedman 945eede
add kick extension with command and result formatting
chrisdedman 40fde3b
add kick and space service modules for user management
chrisdedman fc31cd5
update kick result model to remove scope
chrisdedman 312ebb9
added permission at bot level
chrisdedman 1923554
add SpaceNotFoundError exception and update kick result formatting
chrisdedman 4d6d312
refactor kick service to handle errors and improve room collection logic
chrisdedman 828d221
added unit test for moderations
chrisdedman ddf8807
Merge branch 'main' into mod-kick
chrisdedman 16ed488
migrate unit tests files in isolation to its extension
chrisdedman ba64c6b
added more test for depth space + fix test naming
chrisdedman 830e92e
use power level moderation instead of env var
chrisdedman fc7b3d9
fix recursion side effect for collecting space parent
chrisdedman 2172ebc
refactor kick from context method to simplify returned mesage
chrisdedman 53ec940
simplify adding room ids to list
chrisdedman 0c6c866
fix test by giving room ids order agnostic
chrisdedman fc76afe
remove unused custom errors
chrisdedman da8a287
refactor get_parent_space function to simplify parent ID retrieval
chrisdedman 5182313
refactor kick functionality to handle multiple rooms and update KickR…
chrisdedman 3f7aa45
refactor test_kick_extension to improve mock functions and improve te…
chrisdedman File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -11,4 +11,5 @@ build/ | |
| logs/*.log | ||
| config/*.local.yaml | ||
| .idea | ||
| *.db | ||
| *.db | ||
| settings.json | ||
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| from matrix import Context, Extension | ||
| from matrix.errors import CheckError | ||
|
|
||
| from bot.permissions import is_moderator | ||
| from .kick_service import kick_from_context | ||
| from .models import KickResult | ||
|
|
||
| extension = Extension("kick") | ||
|
|
||
| KICK_RESULT_TEMPLATE = ( | ||
| "{space}" | ||
| "Target: `{target}`\n" | ||
| "Kicked from: `{kicked}` rooms\n" | ||
| "Failed in: `{failed}` rooms\n" | ||
| "Reason: {reason}" | ||
| ) | ||
|
|
||
|
|
||
| def format_kick_result(result: KickResult) -> str: | ||
| return KICK_RESULT_TEMPLATE.format( | ||
| space=f"Space: `{result.space_id}`\n" if result.space_id else "", | ||
| target=result.target_user_id, | ||
| kicked=len(result.kicked_room_ids), | ||
| failed=len(result.failed_room_ids), | ||
| reason=result.reason, | ||
| ) | ||
|
|
||
|
|
||
| @extension.command( | ||
| "kick", | ||
| description="Kick a user from all rooms in the current space", | ||
| ) | ||
| async def kick( | ||
| ctx: Context, | ||
| user_id: str, | ||
| reason: str = "No reason provided", | ||
| ) -> None: | ||
| result = await kick_from_context(ctx, user_id, reason) | ||
| await ctx.reply(format_kick_result(result)) | ||
|
|
||
|
|
||
| @kick.error(CheckError) | ||
| async def kick_check_error(ctx: Context, error: CheckError) -> None: | ||
| await ctx.reply(f"Could not complete kick operation: {error}") | ||
|
|
||
|
|
||
| @kick.check | ||
| async def can_kick(ctx: Context) -> bool: | ||
| return await is_moderator(ctx) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| from matrix import Context, Space, Room | ||
| from matrix.errors import MatrixError | ||
|
|
||
| from .models import KickResult | ||
| from .space_service import get_parent_space | ||
|
|
||
|
|
||
| async def kick_from_rooms( | ||
| user_id: str, | ||
| rooms: list[Room], | ||
| *, | ||
| reason: str | None = None, | ||
| space: Space | None = None, | ||
| ) -> KickResult: | ||
| kicked: list[str] = [] | ||
| failed: list[str] = [] | ||
| seen: set[str] = set() | ||
|
|
||
| for room in rooms: | ||
| if room.room_id in seen: | ||
| continue | ||
| seen.add(room.room_id) | ||
|
|
||
| try: | ||
| members = await room.get_members() | ||
| if user_id not in members: | ||
| # this will skip rooms where the user is not a member | ||
| continue | ||
|
|
||
| await room.kick_user(user_id, reason=reason) | ||
|
|
||
| members_after = await room.get_members() | ||
| if user_id in members_after: | ||
| # if the user is still in the room after the kick, | ||
| # we consider it a failure (should not happen) | ||
| failed.append(room.room_id) | ||
| else: | ||
| kicked.append(room.room_id) | ||
|
|
||
| except MatrixError: | ||
| failed.append(room.room_id) | ||
|
|
||
| return KickResult( | ||
| target_user_id=user_id, | ||
| reason=reason, | ||
| space_id=space.room_id if space else None, | ||
| kicked_room_ids=kicked, | ||
| failed_room_ids=failed, | ||
| ) | ||
|
|
||
|
|
||
| async def kick_from_context( | ||
| ctx: Context, | ||
| user_id: str, | ||
| reason: str | None = None, | ||
| ) -> KickResult: | ||
| space: Space | None = get_parent_space(ctx) | ||
|
|
||
| if space: | ||
| children = space.get_children(depth=3) | ||
| children.append(space) | ||
|
|
||
| return await kick_from_rooms( | ||
| user_id, | ||
| children, | ||
| reason=reason, | ||
| space=space, | ||
| ) | ||
|
|
||
| return await kick_from_rooms(user_id, [ctx.room], reason=reason) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| from dataclasses import dataclass | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class KickResult: | ||
| target_user_id: str | ||
| reason: str | None | ||
| space_id: str | None | ||
| kicked_room_ids: list[str] | ||
| failed_room_ids: list[str] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| from matrix import Context, Space | ||
|
|
||
|
|
||
| def get_parent_space(ctx: Context) -> Space | None: | ||
| parent_ids: set[str] = ctx.room.matrix_room.parents | ||
| parent_id = next(iter(parent_ids), None) | ||
|
|
||
| if not parent_id: | ||
| return None | ||
|
|
||
| return ctx.bot.get_space(parent_id) |
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,163 @@ | ||
| import pytest | ||
| from matrix.errors import MatrixError | ||
| from types import SimpleNamespace | ||
| from typing import Any, cast | ||
| from unittest.mock import AsyncMock, MagicMock, patch | ||
|
|
||
| from matrix import Context, Room, Space | ||
| from bot.extensions.moderation.kick_service import kick_from_context, kick_from_rooms | ||
|
|
||
|
|
||
| def as_async_mock(value: Any) -> AsyncMock: | ||
| return cast(AsyncMock, value) | ||
|
|
||
|
|
||
| def as_mock(value: Any) -> MagicMock: | ||
| return cast(MagicMock, value) | ||
|
|
||
|
|
||
| def mock_room( | ||
| room_id: str, | ||
| *, | ||
| kick_error: Exception | None = None, | ||
| ) -> Room: | ||
| room = MagicMock(spec=Room) | ||
| room.room_id = room_id | ||
| room.name = room_id | ||
|
|
||
| if kick_error: | ||
| cast(Any, room).get_members = AsyncMock(return_value=["@target:example.com"]) | ||
| else: | ||
| cast(Any, room).get_members = AsyncMock( | ||
| side_effect=[ | ||
| ["@target:example.com"], | ||
| [], | ||
| ] | ||
| ) | ||
|
|
||
| cast(Any, room).kick_user = AsyncMock(side_effect=kick_error) | ||
|
|
||
| return cast(Room, room) | ||
|
|
||
|
|
||
| def mock_space(room_id: str, children: list[Room | Space]) -> Space: | ||
| space = MagicMock(spec=Space) | ||
| space.room_id = room_id | ||
| space.name = room_id | ||
| cast(Any, space).get_children = MagicMock(return_value=children) | ||
| cast(Any, space).kick_user = AsyncMock() | ||
| return cast(Space, space) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_kick_from_rooms__skips_when_user_is_not_member() -> None: | ||
| room = mock_room("!room:example.com") | ||
| cast(Any, room).get_members = AsyncMock(return_value=[]) | ||
|
|
||
| result = await kick_from_rooms( | ||
| "@target:example.com", | ||
| [room], | ||
| reason="spam", | ||
| ) | ||
|
|
||
| as_async_mock(room.kick_user).assert_not_awaited() | ||
| assert result.kicked_room_ids == [] | ||
| assert result.failed_room_ids == [] | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_kick_from_rooms__records_successes_failures_and_dedupes() -> None: | ||
| successful_room = mock_room("!success:example.com") | ||
| failed_room = mock_room( | ||
| "!failed:example.com", | ||
| kick_error=MatrixError("denied"), | ||
| ) | ||
|
|
||
| result = await kick_from_rooms( | ||
| "@target:example.com", | ||
| [successful_room, failed_room, successful_room], | ||
| reason="spam", | ||
| ) | ||
|
|
||
| as_async_mock(successful_room.kick_user).assert_awaited_once_with( | ||
| "@target:example.com", reason="spam" | ||
| ) | ||
| as_async_mock(failed_room.kick_user).assert_awaited_once_with( | ||
| "@target:example.com", reason="spam" | ||
| ) | ||
|
|
||
| assert result.target_user_id == "@target:example.com" | ||
| assert result.reason == "spam" | ||
| assert result.space_id is None | ||
| assert result.kicked_room_ids == ["!success:example.com"] | ||
| assert result.failed_room_ids == ["!failed:example.com"] | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_kick_from_rooms__includes_space_id_when_space_provided() -> None: | ||
| room = mock_room("!room:example.com") | ||
| space = mock_space("!space:example.com", []) | ||
|
|
||
| result = await kick_from_rooms( | ||
| "@target:example.com", | ||
| [room], | ||
| reason="spam", | ||
| space=space, | ||
| ) | ||
|
|
||
| assert result.space_id == "!space:example.com" | ||
| assert result.kicked_room_ids == ["!room:example.com"] | ||
| assert result.failed_room_ids == [] | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_kick_from_context__without_parent_space__kicks_current_room() -> None: | ||
| current_room = mock_room("!current:example.com") | ||
| ctx = SimpleNamespace(room=current_room) | ||
|
|
||
| with patch( | ||
| "bot.extensions.moderation.kick_service.get_parent_space", | ||
| return_value=None, | ||
| ): | ||
| result = await kick_from_context( | ||
| cast(Context, ctx), | ||
| "@target:example.com", | ||
| "spam", | ||
| ) | ||
|
|
||
| as_async_mock(current_room.kick_user).assert_awaited_once_with( | ||
| "@target:example.com", reason="spam" | ||
| ) | ||
| assert result.kicked_room_ids == ["!current:example.com"] | ||
| assert result.failed_room_ids == [] | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_kick_from_context__with_parent_space__kicks_room_children_only() -> None: | ||
| child_room = mock_room("!child-room:example.com") | ||
| child_space = mock_space("!child-space:example.com", []) | ||
| parent_space = mock_space( | ||
| "!parent-space:example.com", | ||
| [child_room, child_space], | ||
| ) | ||
| ctx = SimpleNamespace(room=mock_room("!current:example.com")) | ||
|
|
||
| with patch( | ||
| "bot.extensions.moderation.kick_service.get_parent_space", | ||
| return_value=parent_space, | ||
| ): | ||
| result = await kick_from_context( | ||
| cast(Context, ctx), | ||
| "@target:example.com", | ||
| "spam", | ||
| ) | ||
|
|
||
| as_mock(parent_space.get_children).assert_called_once_with(depth=3) | ||
| as_async_mock(child_room.kick_user).assert_awaited_once_with( | ||
| "@target:example.com", reason="spam" | ||
| ) | ||
| as_async_mock(child_space.kick_user).assert_not_awaited() | ||
|
|
||
| assert result.space_id == "!parent-space:example.com" | ||
| assert result.kicked_room_ids == ["!child-room:example.com"] | ||
| assert result.failed_room_ids == [] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| from matrix import Context | ||
|
|
||
|
|
||
| async def is_moderator(ctx: Context) -> bool: | ||
| power_levels = ctx.room.matrix_room.power_levels | ||
| sender_level = power_levels.get_user_level(ctx.sender) | ||
|
|
||
| return sender_level >= power_levels.defaults.kick | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| import pytest | ||
| from types import SimpleNamespace | ||
|
|
||
| from bot.permissions import is_moderator | ||
|
|
||
|
|
||
| def make_ctx(sender: str, sender_level: int, required_level: int = 50): | ||
| power_levels = SimpleNamespace( | ||
| defaults=SimpleNamespace(kick=required_level), | ||
| get_user_level=lambda user_id: sender_level, | ||
| ) | ||
|
|
||
| room = SimpleNamespace( | ||
| matrix_room=SimpleNamespace( | ||
| power_levels=power_levels, | ||
| ) | ||
| ) | ||
|
|
||
| return SimpleNamespace(sender=sender, room=room) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_is_moderator_accepts_user_at_required_power_level() -> None: | ||
| ctx = make_ctx("@mod:example.com", sender_level=50) | ||
|
|
||
| assert await is_moderator(ctx) is True # type: ignore[arg-type] | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_is_moderator_accepts_user_above_required_power_level() -> None: | ||
| ctx = make_ctx("@admin:example.com", sender_level=100) | ||
|
|
||
| assert await is_moderator(ctx) is True # type: ignore[arg-type] | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_is_moderator_rejects_user_below_required_power_level() -> None: | ||
| ctx = make_ctx("@user:example.com", sender_level=0) | ||
|
|
||
| assert await is_moderator(ctx) is False # type: ignore[arg-type] |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.

Uh oh!
There was an error while loading. Please reload this page.