From 3fd2d769f548a55da9853bb49eaee4977e94865f Mon Sep 17 00:00:00 2001 From: Christopher Date: Sat, 28 Nov 2026 00:27:27 +0100 Subject: [PATCH 1/3] Show, export and delete a person's or a server's data with /privacy --- src/librebots/kit/ext/privacy.py | 371 ++++++++++++++++++++++ src/librebots/kit/locales/de/kit.ftl | 37 +++ src/librebots/kit/locales/en-US/kit.ftl | 37 +++ tests/privacy_fakes.py | 99 ++++++ tests/test_ext_privacy.py | 400 ++++++++++++++++++++++++ tests/test_privacy.py | 96 +----- 6 files changed, 947 insertions(+), 93 deletions(-) create mode 100644 src/librebots/kit/ext/privacy.py create mode 100644 tests/privacy_fakes.py create mode 100644 tests/test_ext_privacy.py diff --git a/src/librebots/kit/ext/privacy.py b/src/librebots/kit/ext/privacy.py new file mode 100644 index 0000000..93b56bf --- /dev/null +++ b/src/librebots/kit/ext/privacy.py @@ -0,0 +1,371 @@ +"""Adds `/privacy`: who runs the bot, what it stores about the caller, and export and deletion of that data. + +Deleting asks for the person's username, or for the server's name from the server owner, typed into a modal. Needs +`Privacy`, `Config`, `BotInfo`, a risa client and a `Catalog` with kit's texts and the bot's `privacy-category-` +texts in lightbulb's dependency injection. +""" + +from __future__ import annotations + +import logging +from collections.abc import Mapping + +import hikari +import lightbulb +import msgspec +import risa +from risa import ui + +from librebots.kit.bot import BotInfo +from librebots.kit.config import Config +from librebots.kit.hub import HubError +from librebots.kit.i18n import Catalog +from librebots.kit.privacy import Privacy + +__all__ = ["loader"] + +_LOGGER = logging.getLogger(__name__) +_RED = 0xE24B4A +_DELETE_USER_MODAL = "kit-privacy-delete-user" +_DELETE_SERVER_MODAL = "kit-privacy-delete-server" +_TYPED_NAME = "typed-name" + +loader = lightbulb.Loader() + + +@risa.register(name="kit-privacy") +class _PrivacyOverview(risa.View): + locale: risa.Prop[str] = "en-US" + stored: risa.Prop[dict[str, int]] = msgspec.field(default_factory=dict[str, int]) + server_owner: risa.Prop[bool] = False + catalog: risa.Prop[Catalog | None] = None + config: risa.Prop[Config | None] = None + bot: risa.Prop[BotInfo | None] = None + + def render(self) -> ui.Layout: + if self.catalog is None or self.config is None or self.bot is None: + raise RuntimeError("the overview renders only as _overview() builds it") + catalog, locale = self.catalog, self.locale + if self.stored: + stored = f"{catalog.text(locale, 'kit-privacy-overview.stored')}\n{_listed(catalog, locale, self.stored)}" + else: + stored = catalog.text(locale, "kit-privacy-overview.nothing") + buttons: list[ui.Button | ui.LinkButton] = [ + ui.Button( + self.export_my_data, + label=catalog.text(locale, "kit-privacy-export.button"), + style=hikari.ButtonStyle.SECONDARY, + disabled=not self.stored, + ), + ui.Button( + self.ask_to_delete_my_data, + label=catalog.text(locale, "kit-privacy-delete.button"), + style=hikari.ButtonStyle.DANGER, + disabled=not self.stored, + ), + ui.LinkButton(self.config.privacy_policy_url, label=catalog.text(locale, "kit-privacy-overview.policy")), + ] + if self.server_owner: + buttons.append( + ui.Button( + self.ask_to_delete_server_data, + label=catalog.text(locale, "kit-privacy-server.button"), + style=hikari.ButtonStyle.DANGER, + ) + ) + operator = catalog.text( + locale, + "kit-privacy-overview", + operator=self.config.operator_name, + contact=self.config.operator_contact, + bot=self.bot.name, + ) + return ui.Container( + ui.TextDisplay(f"### {catalog.text(locale, 'kit-privacy-overview.title')}"), + ui.TextDisplay(operator), + ui.TextDisplay(stored), + ui.Row(*buttons), + accent_color=self.bot.accent_color, + ) + + @risa.handler + async def export_my_data( + self, + ctx: risa.ComponentContext, + privacy: Privacy = risa.INJECTED, + catalog: Catalog = risa.INJECTED, + bot: BotInfo = risa.INJECTED, + ) -> None: + locale = ctx.interaction.locale + exported = await privacy.export_user(ctx.user.id) + layout = ui.Container( + ui.TextDisplay(f"### {catalog.text(locale, 'kit-privacy-export.title')}"), + ui.TextDisplay(catalog.text(locale, "kit-privacy-export", bot=bot.name)), + ui.File(hikari.Bytes(exported.encode(), f"{bot.hub_name}-data.json")), + accent_color=bot.accent_color, + ) + await ctx.respond(**ui.render(layout), ephemeral=True) + + @risa.handler + async def ask_to_delete_my_data( + self, + ctx: risa.ComponentContext, + privacy: Privacy = risa.INJECTED, + catalog: Catalog = risa.INJECTED, + bot: BotInfo = risa.INJECTED, + ) -> None: + locale = ctx.interaction.locale + stored = await privacy.count_user(ctx.user.id) + what = catalog.text(locale, "kit-privacy-delete", bot=bot.name) + layout = ui.Container( + ui.TextDisplay(f"### {catalog.text(locale, 'kit-privacy-delete.title')}"), + ui.TextDisplay(f"{what}\n{_listed(catalog, locale, stored)}"), + ui.TextDisplay(catalog.text(locale, "kit-privacy-delete.warning")), + ui.Row( + ui.Button( + self.open_delete_my_data_modal, + label=catalog.text(locale, "kit-privacy-delete.confirm"), + style=hikari.ButtonStyle.DANGER, + ), + ui.Button( + self.back_to_overview, + label=catalog.text(locale, "kit-privacy-cancel"), + style=hikari.ButtonStyle.SECONDARY, + ), + ), + accent_color=_RED, + ) + await ctx.edit(layout) + + @risa.handler + async def open_delete_my_data_modal(self, ctx: risa.ComponentContext, catalog: Catalog = risa.INJECTED) -> None: + locale = ctx.interaction.locale + field = hikari.impl.ModalActionRowBuilder().add_text_input( + _TYPED_NAME, + catalog.text(locale, "kit-privacy-delete.input"), + placeholder=ctx.user.username, + max_length=100, + ) + title = catalog.text(locale, "kit-privacy-delete.modal") + await ctx.interaction.create_modal_response(title, _DELETE_USER_MODAL, components=[field]) + + @risa.handler + async def ask_to_delete_server_data( + self, + ctx: risa.ComponentContext, + privacy: Privacy = risa.INJECTED, + catalog: Catalog = risa.INJECTED, + bot: BotInfo = risa.INJECTED, + ) -> None: + locale = ctx.interaction.locale + guild = await _guild_if_owner(ctx.interaction) + if guild is None: + refusal = _nothing_deleted(catalog, locale, "kit-privacy-server.owner-only") + await ctx.respond(**ui.render(refusal), ephemeral=True) + return + stored = await privacy.count_guild(guild.id) + what = catalog.text(locale, "kit-privacy-server", bot=bot.name) + layout = ui.Container( + ui.TextDisplay(f"### {catalog.text(locale, 'kit-privacy-server.title')}"), + ui.TextDisplay(f"{what}\n{_listed(catalog, locale, stored)}"), + ui.TextDisplay(catalog.text(locale, "kit-privacy-server.warning")), + ui.Row( + ui.Button( + self.open_delete_server_data_modal, + label=catalog.text(locale, "kit-privacy-server.confirm"), + style=hikari.ButtonStyle.DANGER, + ), + ui.Button( + self.back_to_overview, + label=catalog.text(locale, "kit-privacy-cancel"), + style=hikari.ButtonStyle.SECONDARY, + ), + ), + accent_color=_RED, + ) + await ctx.edit(layout) + + @risa.handler + async def open_delete_server_data_modal(self, ctx: risa.ComponentContext, catalog: Catalog = risa.INJECTED) -> None: + locale = ctx.interaction.locale + guild = await _guild_if_owner(ctx.interaction) + if guild is None: + refusal = _nothing_deleted(catalog, locale, "kit-privacy-server.owner-only") + await ctx.respond(**ui.render(refusal), ephemeral=True) + return + field = hikari.impl.ModalActionRowBuilder().add_text_input( + _TYPED_NAME, + catalog.text(locale, "kit-privacy-server.input"), + placeholder=guild.name, + max_length=100, + ) + title = catalog.text(locale, "kit-privacy-server.modal") + await ctx.interaction.create_modal_response(title, _DELETE_SERVER_MODAL, components=[field]) + + @risa.handler + async def back_to_overview( + self, + ctx: risa.ComponentContext, + privacy: Privacy = risa.INJECTED, + catalog: Catalog = risa.INJECTED, + config: Config = risa.INJECTED, + bot: BotInfo = risa.INJECTED, + ) -> None: + overview = await _overview(ctx.interaction, privacy, catalog, config, bot) + await ctx.edit(overview.render()) + + +@loader.command +class _PrivacyCommand( + lightbulb.SlashCommand, + name="kit-cmd-privacy.name", + description="kit-cmd-privacy.description", + localize=True, + contexts=[hikari.ApplicationContextType.GUILD, hikari.ApplicationContextType.BOT_DM], +): + @lightbulb.invoke + async def show_privacy( + self, + ctx: lightbulb.Context, + views: risa.Client = lightbulb.di.INJECTED, + privacy: Privacy = lightbulb.di.INJECTED, + catalog: Catalog = lightbulb.di.INJECTED, + config: Config = lightbulb.di.INJECTED, + bot: BotInfo = lightbulb.di.INJECTED, + ) -> None: + overview = await _overview(ctx.interaction, privacy, catalog, config, bot) + await ctx.respond(**await views.build(overview), ephemeral=True) + + +@loader.listener(hikari.InteractionCreateEvent) +async def _delete_after_the_typed_name( + event: hikari.InteractionCreateEvent, + privacy: Privacy = lightbulb.di.INJECTED, + catalog: Catalog = lightbulb.di.INJECTED, + bot: BotInfo = lightbulb.di.INJECTED, +) -> None: + interaction = event.interaction + if not isinstance(interaction, hikari.ModalInteraction): + return + if interaction.custom_id not in {_DELETE_USER_MODAL, _DELETE_SERVER_MODAL}: + return + locale = interaction.locale + typed = next( + (field.value for row in interaction.components for field in row.components if field.custom_id == _TYPED_NAME), + "", + ) + typed = typed.strip().casefold() + + finished: ui.Container | None = None + refusal = "kit-error-hub" + try: + if interaction.custom_id == _DELETE_USER_MODAL: + if typed == interaction.user.username.casefold(): + await privacy.delete_user(interaction.user.id) + finished = ui.Container( + ui.TextDisplay(f"### {catalog.text(locale, 'kit-privacy-deleting.title')}"), + ui.TextDisplay(catalog.text(locale, "kit-privacy-deleting")), + accent_color=bot.accent_color, + ) + else: + refusal = "kit-privacy-delete.mismatch" + elif (guild := await _guild_if_owner(interaction)) is None: + refusal = "kit-privacy-server.owner-only" + elif typed == guild.name.casefold(): + deleted = await privacy.delete_guild(guild.id) + if deleted: + what = f"{catalog.text(locale, 'kit-privacy-server-deleted', bot=bot.name)}\n" + what += _listed(catalog, locale, deleted) + else: + what = catalog.text(locale, "kit-privacy-server-deleted.nothing", bot=bot.name) + finished = ui.Container( + ui.TextDisplay(f"### {catalog.text(locale, 'kit-privacy-server-deleted.title')}"), + ui.TextDisplay(what), + accent_color=bot.accent_color, + ) + else: + refusal = "kit-privacy-server.mismatch" + except HubError as exc: + _LOGGER.warning("Could not delete after a typed confirmation: %s", exc) + + if finished is not None: + await interaction.create_initial_response(hikari.ResponseType.MESSAGE_UPDATE, **ui.render(finished)) + else: + await interaction.create_initial_response( + hikari.ResponseType.MESSAGE_CREATE, + **ui.render(_nothing_deleted(catalog, locale, refusal)), + flags=hikari.MessageFlag.EPHEMERAL, + ) + + +# Resolving risa's client while the extension loads would freeze the registry before the bot is done with it. +@loader.listener(hikari.StartedEvent) +async def _route_clicks_and_resume_deletions( + _: hikari.StartedEvent, + client: lightbulb.Client = lightbulb.di.INJECTED, + views: risa.Client = lightbulb.di.INJECTED, + privacy: Privacy = lightbulb.di.INJECTED, +) -> None: + views.add_view(_PrivacyOverview) + # One task per client: a lightbulb task keeps its state after a cancel, so a shared one breaks the next client. + # With lightbulb's default of one failure, a single error would stop the daily retry until the next restart. + client.task(lightbulb.crontrigger("30 4 * * *"), max_failures=-1)(_resume_pending_deletions) + await _resume_pending_deletions(privacy) + + +async def _resume_pending_deletions(privacy: Privacy = lightbulb.di.INJECTED) -> None: + try: + started = await privacy.resume_deletions() + except HubError as exc: + _LOGGER.warning("Could not resume the pending deletions: %s", exc) + return + if started: + _LOGGER.info("Resumed %d pending deletions", started) + + +async def _overview( + interaction: hikari.CommandInteraction | hikari.ComponentInteraction, + privacy: Privacy, + catalog: Catalog, + config: Config, + bot: BotInfo, +) -> _PrivacyOverview: + return _PrivacyOverview( + locale=str(interaction.locale), + stored=await privacy.count_user(interaction.user.id), + server_owner=await _guild_if_owner(interaction) is not None, + catalog=catalog, + config=config, + bot=bot, + ) + + +async def _guild_if_owner( + interaction: hikari.CommandInteraction | hikari.ComponentInteraction | hikari.ModalInteraction, +) -> hikari.Guild | None: + if interaction.guild_id is None: + return None + guild = interaction.get_guild() or await interaction.fetch_guild() + if guild is None or guild.owner_id != interaction.user.id: + return None + return guild + + +def _listed(catalog: Catalog, locale: hikari.Locale | str, stored: Mapping[str, int]) -> str: + lines: list[str] = [] + for category, count in stored.items(): + key = f"privacy-category-{category}" + try: + lines.append(f"- {catalog.text(locale, key, count=count)}") + except KeyError: + _LOGGER.warning("The bot's texts have no %s, so /privacy names the category as it is", key) + lines.append(f"- {category}: {count}") + return "\n".join(lines) + + +def _nothing_deleted(catalog: Catalog, locale: hikari.Locale | str, reason: str) -> ui.Container: + return ui.Container( + ui.TextDisplay(f"### {catalog.text(locale, 'kit-privacy-not-deleted.title')}"), + ui.TextDisplay(catalog.text(locale, reason)), + accent_color=_RED, + ) diff --git a/src/librebots/kit/locales/de/kit.ftl b/src/librebots/kit/locales/de/kit.ftl index 3b80422..91c9967 100644 --- a/src/librebots/kit/locales/de/kit.ftl +++ b/src/librebots/kit/locales/de/kit.ftl @@ -14,3 +14,40 @@ kit-info-privacy = Mit /privacy siehst, exportierst oder löschst du, was dieser kit-info-source = Quellcode kit-info-support = Support kit-info-privacy-policy = Datenschutzerklärung + +kit-cmd-privacy = + .name = privacy + .description = Sieh dir an, was dieser Bot über dich speichert, exportiere oder lösche es +kit-privacy-overview = { $operator } ({ $contact }) betreibt diese Instanz von { $bot }. + .title = Deine Daten + .stored = Über dich gespeichert: + .nothing = Über dich ist nichts gespeichert. + .policy = Datenschutzerklärung +kit-privacy-export = Diese Datei enthält alles, was { $bot } über dich speichert. + .title = Dein Datenexport + .button = Meine Daten exportieren +kit-privacy-delete = Damit löschst du alles, was { $bot } über dich speichert, in jedem Server: + .title = Alles über dich löschen? + .warning = Das lässt sich nicht rückgängig machen. Exportiere deine Daten vorher, wenn du eine Kopie willst. + .button = Meine Daten löschen + .confirm = Alles löschen + .modal = Alle deine Daten löschen + .input = Gib zur Bestätigung deinen Nutzernamen ein + .mismatch = Das ist nicht dein Nutzername, deshalb wurde nichts gelöscht. +kit-privacy-deleting = Deine Daten werden im Hintergrund gelöscht. Das kann ein paar Minuten dauern. + .title = Löschung gestartet +kit-privacy-server = Damit löschst du alles, was { $bot } über diesen Server speichert: + .title = Daten dieses Servers löschen? + .warning = Das lässt sich nicht rückgängig machen. Die Nachrichten des Bots im Server bleiben. + .button = Daten dieses Servers löschen + .confirm = Serverdaten löschen + .modal = Daten dieses Servers löschen + .input = Gib zur Bestätigung den Servernamen ein + .mismatch = Das ist nicht der Name des Servers, deshalb wurde nichts gelöscht. + .owner-only = Nur der Eigentümer des Servers kann dessen Daten löschen. +kit-privacy-server-deleted = { $bot } hat gelöscht: + .title = Serverdaten gelöscht + .nothing = { $bot } hatte über diesen Server nichts gespeichert. +kit-privacy-not-deleted = + .title = Nichts gelöscht +kit-privacy-cancel = Abbrechen diff --git a/src/librebots/kit/locales/en-US/kit.ftl b/src/librebots/kit/locales/en-US/kit.ftl index b5eb994..824de54 100644 --- a/src/librebots/kit/locales/en-US/kit.ftl +++ b/src/librebots/kit/locales/en-US/kit.ftl @@ -17,3 +17,40 @@ kit-info-privacy = Use /privacy to see, export or delete what this bot stores ab kit-info-source = Source code kit-info-support = Support kit-info-privacy-policy = Privacy policy + +kit-cmd-privacy = + .name = privacy + .description = See, export or delete what this bot stores about you +kit-privacy-overview = { $operator } ({ $contact }) runs this instance of { $bot }. + .title = Your data + .stored = It stores about you: + .nothing = It stores nothing about you. + .policy = Privacy policy +kit-privacy-export = This file holds everything { $bot } stores about you. + .title = Your data export + .button = Export my data +kit-privacy-delete = This deletes everything { $bot } stores about you, in every server: + .title = Delete everything about you? + .warning = It cannot be undone. Export your data first if you want a copy. + .button = Delete my data + .confirm = Delete everything + .modal = Delete all your data + .input = Type your username to confirm + .mismatch = That is not your username, so nothing was deleted. +kit-privacy-deleting = Your data is being deleted in the background. This can take a few minutes. + .title = Deletion started +kit-privacy-server = This deletes everything { $bot } stores about this server: + .title = Delete this server's data? + .warning = It cannot be undone. The bot's messages in this server stay. + .button = Delete this server's data + .confirm = Delete server data + .modal = Delete this server's data + .input = Type the server name to confirm + .mismatch = That is not the server's name, so nothing was deleted. + .owner-only = Only the server owner can delete this server's data. +kit-privacy-server-deleted = { $bot } deleted: + .title = Server data deleted + .nothing = { $bot } stored nothing about this server. +kit-privacy-not-deleted = + .title = Nothing was deleted +kit-privacy-cancel = Cancel diff --git a/tests/privacy_fakes.py b/tests/privacy_fakes.py new file mode 100644 index 0000000..0c879b5 --- /dev/null +++ b/tests/privacy_fakes.py @@ -0,0 +1,99 @@ +from __future__ import annotations + +import asyncio +from collections.abc import Awaitable + +import grpc +import grpc.aio +from librebots.hub.v1 import privacy_pb2, privacy_pb2_grpc + +type Context[Request, Response] = grpc.aio.ServicerContext[Request, Awaitable[Response]] + + +def counts(**values: int) -> list[privacy_pb2.CategoryCount]: + return [privacy_pb2.CategoryCount(category=name.replace("_", "-"), count=count) for name, count in values.items()] + + +class FakePrivacy(privacy_pb2_grpc.PrivacyServiceServicer): + def __init__(self) -> None: + self.log: list[str] = [] + self.pending: list[int] = [] + self.user_data = counts(starboard_entries=12, starboard_stars=87) + self.guild_data = counts(starboard_settings=1, starboard_entries=342) + self.failing: set[str] = set() + self.stalled: set[str] = set() + self._never = asyncio.Event() + + async def _check[Request, Response](self, name: str, context: Context[Request, Response]) -> None: + if name in self.failing: + await context.abort(grpc.StatusCode.UNAVAILABLE, "hub is down") + if name in self.stalled: + await self._never.wait() + + async def CountUserData( + self, + request: privacy_pb2.CountUserDataRequest, + context: Context[privacy_pb2.CountUserDataRequest, privacy_pb2.CountUserDataResponse], + ) -> privacy_pb2.CountUserDataResponse: + await self._check("count user", context) + self.log.append(f"count user {request.user_id}") + return privacy_pb2.CountUserDataResponse(categories=self.user_data) + + async def ExportUserData( + self, + request: privacy_pb2.ExportUserDataRequest, + context: Context[privacy_pb2.ExportUserDataRequest, privacy_pb2.ExportUserDataResponse], + ) -> privacy_pb2.ExportUserDataResponse: + await self._check("export user", context) + return privacy_pb2.ExportUserDataResponse( + json=f'{{"bot":"starboard","user_id":"{request.user_id}","data":{{}}}}' + ) + + async def DeleteUserData( + self, + request: privacy_pb2.DeleteUserDataRequest, + context: Context[privacy_pb2.DeleteUserDataRequest, privacy_pb2.DeleteUserDataResponse], + ) -> privacy_pb2.DeleteUserDataResponse: + await self._check("delete user", context) + self.log.append(f"delete user {request.user_id}") + if request.user_id in self.pending: + self.pending.remove(request.user_id) + return privacy_pb2.DeleteUserDataResponse(deleted=counts(starboard_entries=12)) + + async def RequestUserDeletion( + self, + request: privacy_pb2.RequestUserDeletionRequest, + context: Context[privacy_pb2.RequestUserDeletionRequest, privacy_pb2.RequestUserDeletionResponse], + ) -> privacy_pb2.RequestUserDeletionResponse: + await self._check("request deletion", context) + self.log.append(f"request deletion {request.user_id}") + if request.user_id not in self.pending: + self.pending.append(request.user_id) + return privacy_pb2.RequestUserDeletionResponse() + + async def ListPendingUserDeletions( + self, + request: privacy_pb2.ListPendingUserDeletionsRequest, + context: Context[privacy_pb2.ListPendingUserDeletionsRequest, privacy_pb2.ListPendingUserDeletionsResponse], + ) -> privacy_pb2.ListPendingUserDeletionsResponse: + await self._check("list pending", context) + deletions = [privacy_pb2.PendingUserDeletion(user_id=user_id) for user_id in self.pending] + return privacy_pb2.ListPendingUserDeletionsResponse(deletions=deletions) + + async def CountGuildData( + self, + request: privacy_pb2.CountGuildDataRequest, + context: Context[privacy_pb2.CountGuildDataRequest, privacy_pb2.CountGuildDataResponse], + ) -> privacy_pb2.CountGuildDataResponse: + await self._check("count guild", context) + self.log.append(f"count guild {request.guild_id}") + return privacy_pb2.CountGuildDataResponse(categories=self.guild_data) + + async def DeleteGuildData( + self, + request: privacy_pb2.DeleteGuildDataRequest, + context: Context[privacy_pb2.DeleteGuildDataRequest, privacy_pb2.DeleteGuildDataResponse], + ) -> privacy_pb2.DeleteGuildDataResponse: + await self._check("delete guild", context) + self.log.append(f"delete guild {request.guild_id}") + return privacy_pb2.DeleteGuildDataResponse(deleted=self.guild_data) diff --git a/tests/test_ext_privacy.py b/tests/test_ext_privacy.py new file mode 100644 index 0000000..e5fd9e2 --- /dev/null +++ b/tests/test_ext_privacy.py @@ -0,0 +1,400 @@ +from __future__ import annotations + +import logging +from collections.abc import AsyncGenerator, Sequence +from pathlib import Path +from typing import Any +from unittest.mock import AsyncMock, NonCallableMagicMock, create_autospec + +import hikari +import lightbulb +import pytest +import risa +from hub_server import serving +from librebots.hub.v1 import privacy_pb2_grpc +from privacy_fakes import FakePrivacy, counts + +from librebots.kit import LOCALES, BotInfo, Catalog, Config, Hub, Privacy +from librebots.kit.ext import privacy as privacy_ext + +EXTENSION = "librebots.kit.ext.privacy" +USER = 123456789012345678 +OWNER = 323456789012345678 +GUILD = 987654321098765432 +STARBOARD = BotInfo( + name="LibreStarboard", + hub_name="starboard", + version="1.2.0", + accent_color=0xEF9F27, + source_url="https://github.com/libre-bots/starboard", +) +BOT_TEXTS = { + "en-US": """ +bot-description = Pins the best messages of a server. +privacy-category-starboard-entries = { $count -> + [one] { $count } starboard entry + *[other] { $count } starboard entries +} +privacy-category-starboard-stars = { $count } stars +privacy-category-starboard-settings = { $count } set of starboard settings +""", + "de": """ +bot-description = Heftet die besten Nachrichten eines Servers an. +privacy-category-starboard-entries = { $count } Starboard-Einträge +privacy-category-starboard-stars = { $count } Sterne +privacy-category-starboard-settings = { $count } Starboard-Einstellungen +""", +} + + +def config() -> Config: + return Config.from_env( + { + "DISCORD_TOKEN": "discord-token", + "HUB_ADDRESS": "127.0.0.1:1", + "HUB_TOKEN": "hub-token", + "HUB_TLS": "false", + "OPERATOR_NAME": "Example Operator", + "OPERATOR_CONTACT": "ops@example.org", + "PRIVACY_POLICY_URL": "https://example.org/privacy", + } + ) + + +class Person: + def __init__(self, user_id: int, username: str, *, guild_owner: int | None = OWNER) -> None: + user = create_autospec(hikari.User, instance=True) + user.id = hikari.Snowflake(user_id) + user.username = username + self.user: hikari.User = user + self.guild: hikari.RESTGuild | None = None + if guild_owner is not None: + guild = create_autospec(hikari.RESTGuild, instance=True) + guild.id = hikari.Snowflake(GUILD) + guild.name = "Star Gazers" + guild.owner_id = hikari.Snowflake(guild_owner) + self.guild = guild + + def act(self, interaction: NonCallableMagicMock, locale: hikari.Locale) -> None: + interaction.user = self.user + interaction.guild_id = None if self.guild is None else self.guild.id + interaction.locale = locale + interaction.get_guild.return_value = None + interaction.fetch_guild.return_value = self.guild + + +MEMBER = Person(USER, "christopher") +OWNER_PERSON = Person(OWNER, "olivia") +IN_DMS = Person(USER, "christopher", guild_owner=None) + + +class Screen: + def __init__(self, components: Sequence[hikari.api.ComponentBuilder]) -> None: + (container,) = components + payload, self.files = container.build() + self.accent = payload.get("accent_color") + self.texts: list[str] = [] + self.buttons: dict[str, dict[str, Any]] = {} + for child in payload["components"]: + if child["type"] == hikari.ComponentType.TEXT_DISPLAY: + self.texts.append(child["content"]) + elif child["type"] == hikari.ComponentType.ACTION_ROW: + self.buttons.update({button["label"]: button for button in child["components"]}) + + +class Modal: + def __init__(self, interaction: NonCallableMagicMock) -> None: + call = interaction.create_modal_response.await_args + assert call is not None + self.title, self.custom_id = call.args[:2] + (row,) = call.kwargs["components"] + payload, _ = row.build() + (self.field,) = payload["components"] + + +class Bot: + def __init__(self, hub: Hub, tmp_path: Path) -> None: + for locale, texts in BOT_TEXTS.items(): + (tmp_path / locale).mkdir() + (tmp_path / locale / "bot.ftl").write_text(texts, encoding="utf-8") + catalog = Catalog.load(LOCALES, tmp_path) + app = create_autospec(hikari.GatewayBot, instance=True) + app.rest = self.rest = create_autospec(hikari.api.RESTClient, instance=True) + app.event_manager = self.events = hikari.impl.EventManagerImpl( + hikari.impl.EntityFactoryImpl(app), hikari.impl.EventFactoryImpl(app), hikari.Intents.NONE + ) + self.app: hikari.GatewayBot = app + self.client = lightbulb.client_from_app( + self.app, localization_provider=catalog.localization_provider, sync_commands=False + ) + risa.client_from_lightbulb(self.client) + self.privacy = Privacy(hub) + registry = self.client.di.registry_for(lightbulb.di.Contexts.DEFAULT) + registry.register_value(Config, config()) + registry.register_value(Catalog, catalog) + registry.register_value(BotInfo, STARBOARD) + registry.register_value(Privacy, self.privacy) + + async def start(self) -> None: + await self.client.load_extensions(EXTENSION) + await self.client.start() + await self.events.dispatch(hikari.StartedEvent(app=self.app), return_tasks=True) + + async def stop(self) -> None: + await self.privacy.close() + # Unloading drops the module, and importing it again would register its risa view a second time. + await self.client.stop() + + async def run_privacy(self, person: Person, locale: hikari.Locale = hikari.Locale.EN_US) -> Screen: + interaction = create_autospec(hikari.CommandInteraction, instance=True) + interaction.command_name = "privacy" + interaction.command_type = hikari.CommandType.SLASH + interaction.options = [] + interaction.registered_guild_id = None + person.act(interaction, locale) + response: AsyncMock = interaction.create_initial_response + await self.client.handle_interaction_create(interaction) + call = response.await_args + assert call is not None + assert call.kwargs["flags"] == hikari.MessageFlag.EPHEMERAL + return Screen(call.kwargs["components"]) + + async def click(self, screen: Screen, label: str, person: Person) -> NonCallableMagicMock: + interaction = create_autospec(hikari.ComponentInteraction, instance=True) + interaction.custom_id = screen.buttons[label]["custom_id"] + person.act(interaction, hikari.Locale.EN_US) + self.rest.create_interaction_response.reset_mock() + shard = create_autospec(hikari.api.GatewayShard, instance=True) + await self.events.dispatch( + hikari.ComponentInteractionCreateEvent(shard=shard, interaction=interaction), return_tasks=True + ) + return interaction + + def answer(self) -> tuple[hikari.ResponseType, Screen, Any]: + call = self.rest.create_interaction_response.await_args + assert call is not None + return call.args[2], Screen(call.kwargs["components"]), call.kwargs.get("flags") + + async def submit(self, modal: Modal, typed: str, person: Person) -> tuple[hikari.ResponseType, Screen, Any]: + interaction = create_autospec(hikari.ModalInteraction, instance=True) + interaction.custom_id = modal.custom_id + text_input = hikari.TextInputComponent( + type=hikari.ComponentType.TEXT_INPUT, id=2, custom_id=modal.field["custom_id"], value=typed + ) + interaction.components = [ + hikari.ModalActionRowComponent(type=hikari.ComponentType.ACTION_ROW, id=1, components=[text_input]) + ] + person.act(interaction, hikari.Locale.EN_US) + response: AsyncMock = interaction.create_initial_response + shard = create_autospec(hikari.api.GatewayShard, instance=True) + await self.events.dispatch( + hikari.InteractionCreateEvent(shard=shard, interaction=interaction), return_tasks=True + ) + call = response.await_args + assert call is not None + return call.args[0], Screen(call.kwargs["components"]), call.kwargs.get("flags") + + +@pytest.fixture +async def hub() -> AsyncGenerator[tuple[Hub, FakePrivacy]]: + fake = FakePrivacy() + async with serving(lambda server: privacy_pb2_grpc.add_PrivacyServiceServicer_to_server(fake, server)) as hub: + yield hub, fake + + +@pytest.fixture +async def bot(hub: tuple[Hub, FakePrivacy], tmp_path: Path) -> AsyncGenerator[Bot]: + bot = Bot(hub[0], tmp_path) + await bot.start() + yield bot + await bot.stop() + + +async def test_shows_who_runs_the_bot_and_what_it_stores(bot: Bot) -> None: + screen = await bot.run_privacy(MEMBER) + + assert screen.accent == hikari.Color(0xEF9F27) + assert screen.texts == [ + "### Your data", + "Example Operator (ops@example.org) runs this instance of LibreStarboard.", + "It stores about you:\n- 12 starboard entries\n- 87 stars", + ] + assert list(screen.buttons) == ["Export my data", "Delete my data", "Privacy policy"] + assert screen.buttons["Privacy policy"]["url"] == "https://example.org/privacy" + + +async def test_greys_out_export_and_deletion_when_nothing_is_stored(bot: Bot, hub: tuple[Hub, FakePrivacy]) -> None: + hub[1].user_data = [] + + screen = await bot.run_privacy(MEMBER) + + assert screen.texts[2] == "It stores nothing about you." + assert screen.buttons["Export my data"]["disabled"] is True + assert screen.buttons["Delete my data"]["disabled"] is True + + +@pytest.mark.parametrize(("person", "offered"), [(OWNER_PERSON, True), (MEMBER, False), (IN_DMS, False)]) +async def test_offers_deleting_the_server_data_to_its_owner_only(bot: Bot, person: Person, offered: bool) -> None: + screen = await bot.run_privacy(person) + + assert ("Delete this server's data" in screen.buttons) is offered + + +async def test_exports_the_data_as_a_file(bot: Bot) -> None: + screen = await bot.run_privacy(MEMBER) + + await bot.click(screen, "Export my data", MEMBER) + + response_type, export, flags = bot.answer() + assert (response_type, flags) == (hikari.ResponseType.MESSAGE_CREATE, hikari.MessageFlag.EPHEMERAL) + assert export.texts == ["### Your data export", "This file holds everything LibreStarboard stores about you."] + (file,) = export.files + assert file.filename == "starboard-data.json" + assert f'"user_id":"{USER}"' in (await file.read()).decode() + + +async def test_deletes_my_data_once_i_type_my_username(bot: Bot, hub: tuple[Hub, FakePrivacy]) -> None: + overview = await bot.run_privacy(MEMBER) + + await bot.click(overview, "Delete my data", MEMBER) + response_type, warning, _ = bot.answer() + assert response_type == hikari.ResponseType.MESSAGE_UPDATE + assert warning.accent == hikari.Color(0xE24B4A) + assert warning.texts == [ + "### Delete everything about you?", + "This deletes everything LibreStarboard stores about you, in every server:\n- 12 starboard entries\n- 87 stars", + "It cannot be undone. Export your data first if you want a copy.", + ] + assert warning.buttons["Delete everything"]["style"] == hikari.ButtonStyle.DANGER + + modal = Modal(await bot.click(warning, "Delete everything", MEMBER)) + assert modal.title == "Delete all your data" + assert (modal.field["label"], modal.field["placeholder"]) == ("Type your username to confirm", "christopher") + + response_type, done, _ = await bot.submit(modal, " Christopher ", MEMBER) + await bot.privacy.wait_for_deletions() + + assert response_type == hikari.ResponseType.MESSAGE_UPDATE + assert done.texts == [ + "### Deletion started", + "Your data is being deleted in the background. This can take a few minutes.", + ] + assert hub[1].log[-2:] == [f"request deletion {USER}", f"delete user {USER}"] + + +async def test_keeps_my_data_when_the_username_does_not_match(bot: Bot, hub: tuple[Hub, FakePrivacy]) -> None: + overview = await bot.run_privacy(MEMBER) + await bot.click(overview, "Delete my data", MEMBER) + _, warning, _ = bot.answer() + modal = Modal(await bot.click(warning, "Delete everything", MEMBER)) + + response_type, refusal, flags = await bot.submit(modal, "someone-else", MEMBER) + + assert (response_type, flags) == (hikari.ResponseType.MESSAGE_CREATE, hikari.MessageFlag.EPHEMERAL) + assert refusal.texts == ["### Nothing was deleted", "That is not your username, so nothing was deleted."] + assert not [entry for entry in hub[1].log if entry.startswith(("request deletion", "delete user"))] + + +async def test_goes_back_to_the_overview(bot: Bot) -> None: + overview = await bot.run_privacy(MEMBER) + await bot.click(overview, "Delete my data", MEMBER) + _, warning, _ = bot.answer() + + await bot.click(warning, "Cancel", MEMBER) + + response_type, back, _ = bot.answer() + assert response_type == hikari.ResponseType.MESSAGE_UPDATE + assert back.texts == overview.texts + + +async def test_deletes_the_server_data_once_its_owner_types_its_name(bot: Bot, hub: tuple[Hub, FakePrivacy]) -> None: + overview = await bot.run_privacy(OWNER_PERSON) + + await bot.click(overview, "Delete this server's data", OWNER_PERSON) + _, warning, _ = bot.answer() + assert warning.texts == [ + "### Delete this server's data?", + "This deletes everything LibreStarboard stores about this server:\n" + "- 1 set of starboard settings\n- 342 starboard entries", + "It cannot be undone. The bot's messages in this server stay.", + ] + + modal = Modal(await bot.click(warning, "Delete server data", OWNER_PERSON)) + assert modal.title == "Delete this server's data" + assert (modal.field["label"], modal.field["placeholder"]) == ("Type the server name to confirm", "Star Gazers") + + response_type, done, _ = await bot.submit(modal, "star gazers", OWNER_PERSON) + + assert response_type == hikari.ResponseType.MESSAGE_UPDATE + assert done.texts == [ + "### Server data deleted", + "LibreStarboard deleted:\n- 1 set of starboard settings\n- 342 starboard entries", + ] + assert hub[1].log[-1] == f"delete guild {GUILD}" + + +async def test_lets_only_the_owner_delete_the_server_data(bot: Bot, hub: tuple[Hub, FakePrivacy]) -> None: + overview = await bot.run_privacy(OWNER_PERSON) + await bot.click(overview, "Delete this server's data", OWNER_PERSON) + _, warning, _ = bot.answer() + modal = Modal(await bot.click(warning, "Delete server data", OWNER_PERSON)) + handed_over = Person(OWNER, "olivia", guild_owner=USER) + + await bot.click(overview, "Delete this server's data", handed_over) + _, after_click, flags = bot.answer() + _, after_submit, _ = await bot.submit(modal, "Star Gazers", handed_over) + + only_owner = ["### Nothing was deleted", "Only the server owner can delete this server's data."] + assert (after_click.texts, flags) == (only_owner, hikari.MessageFlag.EPHEMERAL) + assert after_submit.texts == only_owner + assert f"delete guild {GUILD}" not in hub[1].log + + +async def test_names_a_category_the_bot_has_no_text_for( + bot: Bot, hub: tuple[Hub, FakePrivacy], caplog: pytest.LogCaptureFixture +) -> None: + hub[1].user_data = counts(starboard_extras=3) + + with caplog.at_level(logging.WARNING, logger=privacy_ext.__name__): + screen = await bot.run_privacy(MEMBER) + + assert screen.texts[2] == "It stores about you:\n- starboard-extras: 3" + assert "privacy-category-starboard-extras" in caplog.text + + +async def test_tells_that_nothing_was_deleted_when_the_hub_fails(bot: Bot, hub: tuple[Hub, FakePrivacy]) -> None: + overview = await bot.run_privacy(MEMBER) + await bot.click(overview, "Delete my data", MEMBER) + _, warning, _ = bot.answer() + modal = Modal(await bot.click(warning, "Delete everything", MEMBER)) + hub[1].failing.add("request deletion") + + _, refusal, flags = await bot.submit(modal, "christopher", MEMBER) + + assert flags == hikari.MessageFlag.EPHEMERAL + assert refusal.texts == [ + "### Nothing was deleted", + "I can't reach my data at the moment. Try again in a minute.", + ] + + +async def test_answers_in_the_language_of_the_caller(bot: Bot) -> None: + screen = await bot.run_privacy(MEMBER, hikari.Locale.DE) + + assert screen.texts == [ + "### Deine Daten", + "Example Operator (ops@example.org) betreibt diese Instanz von LibreStarboard.", + "Über dich gespeichert:\n- 12 Starboard-Einträge\n- 87 Sterne", + ] + assert list(screen.buttons) == ["Meine Daten exportieren", "Meine Daten löschen", "Datenschutzerklärung"] + + +async def test_continues_pending_deletions_after_the_start(hub: tuple[Hub, FakePrivacy], tmp_path: Path) -> None: + hub[1].pending.append(USER) + bot = Bot(hub[0], tmp_path) + + await bot.start() + await bot.privacy.wait_for_deletions() + await bot.stop() + + assert f"delete user {USER}" in hub[1].log diff --git a/tests/test_privacy.py b/tests/test_privacy.py index 06fdd23..62e9e5a 100644 --- a/tests/test_privacy.py +++ b/tests/test_privacy.py @@ -2,110 +2,20 @@ import asyncio import logging -from collections.abc import AsyncGenerator, Awaitable +from collections.abc import AsyncGenerator -import grpc -import grpc.aio import pytest from hub_server import serving -from librebots.hub.v1 import privacy_pb2, privacy_pb2_grpc +from librebots.hub.v1 import privacy_pb2_grpc +from privacy_fakes import FakePrivacy from librebots.kit import Hub, HubError, Privacy -type Context[Request, Response] = grpc.aio.ServicerContext[Request, Awaitable[Response]] - USER = 123456789012345678 OTHER = 223456789012345678 GUILD = 987654321098765432 -def counts(**values: int) -> list[privacy_pb2.CategoryCount]: - return [privacy_pb2.CategoryCount(category=name.replace("_", "-"), count=count) for name, count in values.items()] - - -class FakePrivacy(privacy_pb2_grpc.PrivacyServiceServicer): - def __init__(self) -> None: - self.log: list[str] = [] - self.pending: list[int] = [] - self.failing: set[str] = set() - self.stalled: set[str] = set() - self._never = asyncio.Event() - - async def _check[Request, Response](self, name: str, context: Context[Request, Response]) -> None: - if name in self.failing: - await context.abort(grpc.StatusCode.UNAVAILABLE, "hub is down") - if name in self.stalled: - await self._never.wait() - - async def CountUserData( - self, - request: privacy_pb2.CountUserDataRequest, - context: Context[privacy_pb2.CountUserDataRequest, privacy_pb2.CountUserDataResponse], - ) -> privacy_pb2.CountUserDataResponse: - await self._check("count user", context) - self.log.append(f"count user {request.user_id}") - return privacy_pb2.CountUserDataResponse(categories=counts(starboard_entries=12, starboard_stars=87)) - - async def ExportUserData( - self, - request: privacy_pb2.ExportUserDataRequest, - context: Context[privacy_pb2.ExportUserDataRequest, privacy_pb2.ExportUserDataResponse], - ) -> privacy_pb2.ExportUserDataResponse: - await self._check("export user", context) - return privacy_pb2.ExportUserDataResponse( - json=f'{{"bot":"starboard","user_id":"{request.user_id}","data":{{}}}}' - ) - - async def DeleteUserData( - self, - request: privacy_pb2.DeleteUserDataRequest, - context: Context[privacy_pb2.DeleteUserDataRequest, privacy_pb2.DeleteUserDataResponse], - ) -> privacy_pb2.DeleteUserDataResponse: - await self._check("delete user", context) - self.log.append(f"delete user {request.user_id}") - if request.user_id in self.pending: - self.pending.remove(request.user_id) - return privacy_pb2.DeleteUserDataResponse(deleted=counts(starboard_entries=12)) - - async def RequestUserDeletion( - self, - request: privacy_pb2.RequestUserDeletionRequest, - context: Context[privacy_pb2.RequestUserDeletionRequest, privacy_pb2.RequestUserDeletionResponse], - ) -> privacy_pb2.RequestUserDeletionResponse: - await self._check("request deletion", context) - self.log.append(f"request deletion {request.user_id}") - if request.user_id not in self.pending: - self.pending.append(request.user_id) - return privacy_pb2.RequestUserDeletionResponse() - - async def ListPendingUserDeletions( - self, - request: privacy_pb2.ListPendingUserDeletionsRequest, - context: Context[privacy_pb2.ListPendingUserDeletionsRequest, privacy_pb2.ListPendingUserDeletionsResponse], - ) -> privacy_pb2.ListPendingUserDeletionsResponse: - await self._check("list pending", context) - deletions = [privacy_pb2.PendingUserDeletion(user_id=user_id) for user_id in self.pending] - return privacy_pb2.ListPendingUserDeletionsResponse(deletions=deletions) - - async def CountGuildData( - self, - request: privacy_pb2.CountGuildDataRequest, - context: Context[privacy_pb2.CountGuildDataRequest, privacy_pb2.CountGuildDataResponse], - ) -> privacy_pb2.CountGuildDataResponse: - await self._check("count guild", context) - self.log.append(f"count guild {request.guild_id}") - return privacy_pb2.CountGuildDataResponse(categories=counts(starboard_settings=1, starboard_entries=342)) - - async def DeleteGuildData( - self, - request: privacy_pb2.DeleteGuildDataRequest, - context: Context[privacy_pb2.DeleteGuildDataRequest, privacy_pb2.DeleteGuildDataResponse], - ) -> privacy_pb2.DeleteGuildDataResponse: - await self._check("delete guild", context) - self.log.append(f"delete guild {request.guild_id}") - return privacy_pb2.DeleteGuildDataResponse(deleted=counts(starboard_settings=1, starboard_entries=342)) - - class Removal: def __init__(self, log: list[str]) -> None: self.log = log From 34e03c81f78a510b9b60ef5ed29ea46a29107619 Mon Sep 17 00:00:00 2001 From: Christopher Date: Sat, 28 Nov 2026 00:31:17 +0100 Subject: [PATCH 2/3] Listen for modal submissions and build the privacy overview where it is shown --- src/librebots/kit/ext/privacy.py | 43 ++++++++++++++------------------ tests/test_ext_privacy.py | 2 +- 2 files changed, 20 insertions(+), 25 deletions(-) diff --git a/src/librebots/kit/ext/privacy.py b/src/librebots/kit/ext/privacy.py index 93b56bf..8a8e937 100644 --- a/src/librebots/kit/ext/privacy.py +++ b/src/librebots/kit/ext/privacy.py @@ -44,7 +44,7 @@ class _PrivacyOverview(risa.View): def render(self) -> ui.Layout: if self.catalog is None or self.config is None or self.bot is None: - raise RuntimeError("the overview renders only as _overview() builds it") + raise RuntimeError("the overview renders only with its texts, config and bot info set") catalog, locale = self.catalog, self.locale if self.stored: stored = f"{catalog.text(locale, 'kit-privacy-overview.stored')}\n{_listed(catalog, locale, self.stored)}" @@ -211,7 +211,14 @@ async def back_to_overview( config: Config = risa.INJECTED, bot: BotInfo = risa.INJECTED, ) -> None: - overview = await _overview(ctx.interaction, privacy, catalog, config, bot) + overview = _PrivacyOverview( + locale=str(ctx.interaction.locale), + stored=await privacy.count_user(ctx.interaction.user.id), + server_owner=await _guild_if_owner(ctx.interaction) is not None, + catalog=catalog, + config=config, + bot=bot, + ) await ctx.edit(overview.render()) @@ -233,20 +240,25 @@ async def show_privacy( config: Config = lightbulb.di.INJECTED, bot: BotInfo = lightbulb.di.INJECTED, ) -> None: - overview = await _overview(ctx.interaction, privacy, catalog, config, bot) + overview = _PrivacyOverview( + locale=str(ctx.interaction.locale), + stored=await privacy.count_user(ctx.interaction.user.id), + server_owner=await _guild_if_owner(ctx.interaction) is not None, + catalog=catalog, + config=config, + bot=bot, + ) await ctx.respond(**await views.build(overview), ephemeral=True) -@loader.listener(hikari.InteractionCreateEvent) +@loader.listener(hikari.ModalInteractionCreateEvent) async def _delete_after_the_typed_name( - event: hikari.InteractionCreateEvent, + event: hikari.ModalInteractionCreateEvent, privacy: Privacy = lightbulb.di.INJECTED, catalog: Catalog = lightbulb.di.INJECTED, bot: BotInfo = lightbulb.di.INJECTED, ) -> None: interaction = event.interaction - if not isinstance(interaction, hikari.ModalInteraction): - return if interaction.custom_id not in {_DELETE_USER_MODAL, _DELETE_SERVER_MODAL}: return locale = interaction.locale @@ -323,23 +335,6 @@ async def _resume_pending_deletions(privacy: Privacy = lightbulb.di.INJECTED) -> _LOGGER.info("Resumed %d pending deletions", started) -async def _overview( - interaction: hikari.CommandInteraction | hikari.ComponentInteraction, - privacy: Privacy, - catalog: Catalog, - config: Config, - bot: BotInfo, -) -> _PrivacyOverview: - return _PrivacyOverview( - locale=str(interaction.locale), - stored=await privacy.count_user(interaction.user.id), - server_owner=await _guild_if_owner(interaction) is not None, - catalog=catalog, - config=config, - bot=bot, - ) - - async def _guild_if_owner( interaction: hikari.CommandInteraction | hikari.ComponentInteraction | hikari.ModalInteraction, ) -> hikari.Guild | None: diff --git a/tests/test_ext_privacy.py b/tests/test_ext_privacy.py index e5fd9e2..ed09bfd 100644 --- a/tests/test_ext_privacy.py +++ b/tests/test_ext_privacy.py @@ -188,7 +188,7 @@ async def submit(self, modal: Modal, typed: str, person: Person) -> tuple[hikari response: AsyncMock = interaction.create_initial_response shard = create_autospec(hikari.api.GatewayShard, instance=True) await self.events.dispatch( - hikari.InteractionCreateEvent(shard=shard, interaction=interaction), return_tasks=True + hikari.ModalInteractionCreateEvent(shard=shard, interaction=interaction), return_tasks=True ) call = response.await_args assert call is not None From 9217b61403bc0216f36e59f388a1df49cc6f3202 Mon Sep 17 00:00:00 2001 From: Christopher Date: Sat, 28 Nov 2026 00:41:17 +0100 Subject: [PATCH 3/3] Answer a typed confirmation before the hub and never claim an unknown outcome --- src/librebots/kit/ext/privacy.py | 60 ++++++++++-------- src/librebots/kit/locales/de/kit.ftl | 2 + src/librebots/kit/locales/en-US/kit.ftl | 2 + tests/test_ext_privacy.py | 84 ++++++++++++++++--------- 4 files changed, 94 insertions(+), 54 deletions(-) diff --git a/src/librebots/kit/ext/privacy.py b/src/librebots/kit/ext/privacy.py index 8a8e937..693b057 100644 --- a/src/librebots/kit/ext/privacy.py +++ b/src/librebots/kit/ext/privacy.py @@ -268,22 +268,34 @@ async def _delete_after_the_typed_name( ) typed = typed.strip().casefold() - finished: ui.Container | None = None - refusal = "kit-error-hub" + guild: hikari.Guild | None = None + refusal: str | None = None + if interaction.custom_id == _DELETE_USER_MODAL: + if typed != interaction.user.username.casefold(): + refusal = "kit-privacy-delete.mismatch" + elif (guild := await _guild_if_owner(interaction)) is None: + refusal = "kit-privacy-server.owner-only" + elif typed != guild.name.casefold(): + refusal = "kit-privacy-server.mismatch" + if refusal is not None: + await interaction.create_initial_response( + hikari.ResponseType.MESSAGE_CREATE, + **ui.render(_nothing_deleted(catalog, locale, refusal)), + flags=hikari.MessageFlag.EPHEMERAL, + ) + return + + # Discord drops an answer that comes after three seconds, and the hub may take longer. + await interaction.create_initial_response(hikari.ResponseType.DEFERRED_MESSAGE_UPDATE) try: - if interaction.custom_id == _DELETE_USER_MODAL: - if typed == interaction.user.username.casefold(): - await privacy.delete_user(interaction.user.id) - finished = ui.Container( - ui.TextDisplay(f"### {catalog.text(locale, 'kit-privacy-deleting.title')}"), - ui.TextDisplay(catalog.text(locale, "kit-privacy-deleting")), - accent_color=bot.accent_color, - ) - else: - refusal = "kit-privacy-delete.mismatch" - elif (guild := await _guild_if_owner(interaction)) is None: - refusal = "kit-privacy-server.owner-only" - elif typed == guild.name.casefold(): + if guild is None: + await privacy.delete_user(interaction.user.id) + finished = ui.Container( + ui.TextDisplay(f"### {catalog.text(locale, 'kit-privacy-deleting.title')}"), + ui.TextDisplay(catalog.text(locale, "kit-privacy-deleting")), + accent_color=bot.accent_color, + ) + else: deleted = await privacy.delete_guild(guild.id) if deleted: what = f"{catalog.text(locale, 'kit-privacy-server-deleted', bot=bot.name)}\n" @@ -295,19 +307,15 @@ async def _delete_after_the_typed_name( ui.TextDisplay(what), accent_color=bot.accent_color, ) - else: - refusal = "kit-privacy-server.mismatch" except HubError as exc: - _LOGGER.warning("Could not delete after a typed confirmation: %s", exc) - - if finished is not None: - await interaction.create_initial_response(hikari.ResponseType.MESSAGE_UPDATE, **ui.render(finished)) - else: - await interaction.create_initial_response( - hikari.ResponseType.MESSAGE_CREATE, - **ui.render(_nothing_deleted(catalog, locale, refusal)), - flags=hikari.MessageFlag.EPHEMERAL, + # A call that ran out of time may still have been carried out, so the answer must not say nothing happened. + _LOGGER.warning("Could not confirm a deletion after a typed confirmation: %s", exc) + finished = ui.Container( + ui.TextDisplay(f"### {catalog.text(locale, 'kit-privacy-unconfirmed.title')}"), + ui.TextDisplay(catalog.text(locale, "kit-privacy-unconfirmed")), + accent_color=_RED, ) + await interaction.edit_initial_response(**ui.render(finished)) # Resolving risa's client while the extension loads would freeze the registry before the bot is done with it. diff --git a/src/librebots/kit/locales/de/kit.ftl b/src/librebots/kit/locales/de/kit.ftl index 91c9967..708f8b7 100644 --- a/src/librebots/kit/locales/de/kit.ftl +++ b/src/librebots/kit/locales/de/kit.ftl @@ -48,6 +48,8 @@ kit-privacy-server = Damit löschst du alles, was { $bot } über diesen Server s kit-privacy-server-deleted = { $bot } hat gelöscht: .title = Serverdaten gelöscht .nothing = { $bot } hatte über diesen Server nichts gespeichert. +kit-privacy-unconfirmed = Ich konnte meine Daten nicht erreichen, um das abzuschließen, und weiß deshalb nicht, ob gelöscht wurde. Prüfe es in einer Minute mit /privacy. + .title = Löschung nicht bestätigt kit-privacy-not-deleted = .title = Nichts gelöscht kit-privacy-cancel = Abbrechen diff --git a/src/librebots/kit/locales/en-US/kit.ftl b/src/librebots/kit/locales/en-US/kit.ftl index 824de54..14df20f 100644 --- a/src/librebots/kit/locales/en-US/kit.ftl +++ b/src/librebots/kit/locales/en-US/kit.ftl @@ -51,6 +51,8 @@ kit-privacy-server = This deletes everything { $bot } stores about this server: kit-privacy-server-deleted = { $bot } deleted: .title = Server data deleted .nothing = { $bot } stored nothing about this server. +kit-privacy-unconfirmed = I could not reach my data to finish this, so I cannot tell whether it was deleted. Run /privacy again in a minute to check. + .title = Deletion not confirmed kit-privacy-not-deleted = .title = Nothing was deleted kit-privacy-cancel = Cancel diff --git a/tests/test_ext_privacy.py b/tests/test_ext_privacy.py index ed09bfd..2dd52e4 100644 --- a/tests/test_ext_privacy.py +++ b/tests/test_ext_privacy.py @@ -3,7 +3,7 @@ import logging from collections.abc import AsyncGenerator, Sequence from pathlib import Path -from typing import Any +from typing import Any, Literal from unittest.mock import AsyncMock, NonCallableMagicMock, create_autospec import hikari @@ -170,12 +170,17 @@ async def click(self, screen: Screen, label: str, person: Person) -> NonCallable ) return interaction - def answer(self) -> tuple[hikari.ResponseType, Screen, Any]: + def answer(self) -> tuple[hikari.ResponseType, Screen, hikari.UndefinedOr[hikari.MessageFlag]]: call = self.rest.create_interaction_response.await_args assert call is not None - return call.args[2], Screen(call.kwargs["components"]), call.kwargs.get("flags") - - async def submit(self, modal: Modal, typed: str, person: Person) -> tuple[hikari.ResponseType, Screen, Any]: + response_type, flags = call.args[2], call.kwargs.get("flags", hikari.UNDEFINED) + assert isinstance(response_type, hikari.ResponseType) + assert flags is hikari.UNDEFINED or isinstance(flags, hikari.MessageFlag) + return response_type, Screen(call.kwargs["components"]), flags + + async def submit( + self, modal: Modal, typed: str, person: Person, *, record_in: list[str] | None = None + ) -> tuple[Literal["edited", "private reply"], Screen]: interaction = create_autospec(hikari.ModalInteraction, instance=True) interaction.custom_id = modal.custom_id text_input = hikari.TextInputComponent( @@ -186,13 +191,25 @@ async def submit(self, modal: Modal, typed: str, person: Person) -> tuple[hikari ] person.act(interaction, hikari.Locale.EN_US) response: AsyncMock = interaction.create_initial_response + edit: AsyncMock = interaction.edit_initial_response + if record_in is not None: + + def record(response_type: hikari.ResponseType, *args: object, **kwargs: object) -> None: + record_in.append(f"answered {response_type.name}") + + response.side_effect = record shard = create_autospec(hikari.api.GatewayShard, instance=True) await self.events.dispatch( hikari.ModalInteractionCreateEvent(shard=shard, interaction=interaction), return_tasks=True ) - call = response.await_args - assert call is not None - return call.args[0], Screen(call.kwargs["components"]), call.kwargs.get("flags") + (first,) = response.await_args_list + if first.args[0] == hikari.ResponseType.DEFERRED_MESSAGE_UPDATE: + edited = edit.await_args + assert edited is not None + return "edited", Screen(edited.kwargs["components"]) + assert first.args[0] == hikari.ResponseType.MESSAGE_CREATE + assert first.kwargs["flags"] == hikari.MessageFlag.EPHEMERAL + return "private reply", Screen(first.kwargs["components"]) @pytest.fixture @@ -271,15 +288,15 @@ async def test_deletes_my_data_once_i_type_my_username(bot: Bot, hub: tuple[Hub, assert modal.title == "Delete all your data" assert (modal.field["label"], modal.field["placeholder"]) == ("Type your username to confirm", "christopher") - response_type, done, _ = await bot.submit(modal, " Christopher ", MEMBER) + answer, done = await bot.submit(modal, " Christopher ", MEMBER, record_in=hub[1].log) await bot.privacy.wait_for_deletions() - assert response_type == hikari.ResponseType.MESSAGE_UPDATE + assert answer == "edited" assert done.texts == [ "### Deletion started", "Your data is being deleted in the background. This can take a few minutes.", ] - assert hub[1].log[-2:] == [f"request deletion {USER}", f"delete user {USER}"] + assert hub[1].log[-3:] == ["answered DEFERRED_MESSAGE_UPDATE", f"request deletion {USER}", f"delete user {USER}"] async def test_keeps_my_data_when_the_username_does_not_match(bot: Bot, hub: tuple[Hub, FakePrivacy]) -> None: @@ -288,9 +305,9 @@ async def test_keeps_my_data_when_the_username_does_not_match(bot: Bot, hub: tup _, warning, _ = bot.answer() modal = Modal(await bot.click(warning, "Delete everything", MEMBER)) - response_type, refusal, flags = await bot.submit(modal, "someone-else", MEMBER) + answer, refusal = await bot.submit(modal, "someone-else", MEMBER) - assert (response_type, flags) == (hikari.ResponseType.MESSAGE_CREATE, hikari.MessageFlag.EPHEMERAL) + assert answer == "private reply" assert refusal.texts == ["### Nothing was deleted", "That is not your username, so nothing was deleted."] assert not [entry for entry in hub[1].log if entry.startswith(("request deletion", "delete user"))] @@ -323,14 +340,14 @@ async def test_deletes_the_server_data_once_its_owner_types_its_name(bot: Bot, h assert modal.title == "Delete this server's data" assert (modal.field["label"], modal.field["placeholder"]) == ("Type the server name to confirm", "Star Gazers") - response_type, done, _ = await bot.submit(modal, "star gazers", OWNER_PERSON) + answer, done = await bot.submit(modal, "star gazers", OWNER_PERSON, record_in=hub[1].log) - assert response_type == hikari.ResponseType.MESSAGE_UPDATE + assert answer == "edited" assert done.texts == [ "### Server data deleted", "LibreStarboard deleted:\n- 1 set of starboard settings\n- 342 starboard entries", ] - assert hub[1].log[-1] == f"delete guild {GUILD}" + assert hub[1].log[-2:] == ["answered DEFERRED_MESSAGE_UPDATE", f"delete guild {GUILD}"] async def test_lets_only_the_owner_delete_the_server_data(bot: Bot, hub: tuple[Hub, FakePrivacy]) -> None: @@ -342,11 +359,11 @@ async def test_lets_only_the_owner_delete_the_server_data(bot: Bot, hub: tuple[H await bot.click(overview, "Delete this server's data", handed_over) _, after_click, flags = bot.answer() - _, after_submit, _ = await bot.submit(modal, "Star Gazers", handed_over) + answer, after_submit = await bot.submit(modal, "Star Gazers", handed_over) only_owner = ["### Nothing was deleted", "Only the server owner can delete this server's data."] assert (after_click.texts, flags) == (only_owner, hikari.MessageFlag.EPHEMERAL) - assert after_submit.texts == only_owner + assert (answer, after_submit.texts) == ("private reply", only_owner) assert f"delete guild {GUILD}" not in hub[1].log @@ -362,19 +379,30 @@ async def test_names_a_category_the_bot_has_no_text_for( assert "privacy-category-starboard-extras" in caplog.text -async def test_tells_that_nothing_was_deleted_when_the_hub_fails(bot: Bot, hub: tuple[Hub, FakePrivacy]) -> None: - overview = await bot.run_privacy(MEMBER) - await bot.click(overview, "Delete my data", MEMBER) +@pytest.mark.parametrize( + ("person", "button", "confirm", "typed", "failing"), + [ + (MEMBER, "Delete my data", "Delete everything", "christopher", "request deletion"), + (OWNER_PERSON, "Delete this server's data", "Delete server data", "Star Gazers", "delete guild"), + ], +) +async def test_does_not_claim_an_outcome_when_the_hub_fails( + bot: Bot, hub: tuple[Hub, FakePrivacy], person: Person, button: str, confirm: str, typed: str, failing: str +) -> None: + overview = await bot.run_privacy(person) + await bot.click(overview, button, person) _, warning, _ = bot.answer() - modal = Modal(await bot.click(warning, "Delete everything", MEMBER)) - hub[1].failing.add("request deletion") + modal = Modal(await bot.click(warning, confirm, person)) + hub[1].failing.add(failing) - _, refusal, flags = await bot.submit(modal, "christopher", MEMBER) + answer, unconfirmed = await bot.submit(modal, typed, person) - assert flags == hikari.MessageFlag.EPHEMERAL - assert refusal.texts == [ - "### Nothing was deleted", - "I can't reach my data at the moment. Try again in a minute.", + assert answer == "edited" + assert unconfirmed.accent == hikari.Color(0xE24B4A) + assert unconfirmed.texts == [ + "### Deletion not confirmed", + "I could not reach my data to finish this, so I cannot tell whether it was deleted. " + "Run /privacy again in a minute to check.", ]