Skip to content
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

feat(chat): Rate limit guests when mentioning others #11072

Merged
merged 3 commits into from
Dec 12, 2023
Merged
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 docs/chat.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ Base endpoint is: `/ocs/v2.php/apps/spreed/api/v1`: since Nextcloud 13
+ `404 Not Found` When the conversation could not be found for the participant
+ `412 Precondition Failed` When the lobby is active and the user is not a moderator
+ `413 Payload Too Large` When the message was longer than the allowed limit of 32000 characters (or 1000 until Nextcloud 16.0.1, check the `spreed => config => chat => max-length` capability for the limit)
+ `429 Too Many Requests` When a guest mentioned other participants too often (50 mention meesages per day)

- Header:

Expand Down
26 changes: 25 additions & 1 deletion lib/Chat/ChatManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,17 @@
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\Collaboration\Reference\IReferenceManager;
use OCP\Comments\IComment;
use OCP\Comments\MessageTooLongException;
use OCP\Comments\NotFoundException;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\ICache;
use OCP\ICacheFactory;
use OCP\IDBConnection;
use OCP\IRequest;
use OCP\IUser;
use OCP\Notification\IManager as INotificationManager;
use OCP\Security\RateLimiting\ILimiter;
use OCP\Security\RateLimiting\IRateLimitExceededException;
use OCP\Share\Exceptions\ShareNotFound;
use OCP\Share\IManager;
use OCP\Share\IShare;
Expand All @@ -69,6 +73,9 @@
class ChatManager {
public const MAX_CHAT_LENGTH = 32000;

public const RATE_LIMIT_GUEST_MENTIONS_LIMIT = 50;
public const RATE_LIMIT_GUEST_MENTIONS_PERIOD = 24 * 60 * 60;

public const GEO_LOCATION_VALIDATOR = '/^geo:-?\d{1,2}(\.\d+)?,-?\d{1,3}(\.\d+)?(,-?\d+(\.\d+)?)?(;crs=wgs84)?(;u=\d+(\.\d+)?)?$/i';
public const VERB_MESSAGE = 'comment';
public const VERB_SYSTEM = 'system';
Expand Down Expand Up @@ -96,6 +103,8 @@ public function __construct(
protected ITimeFactory $timeFactory,
protected AttachmentService $attachmentService,
protected IReferenceManager $referenceManager,
protected ILimiter $rateLimiter,
protected IRequest $request,
) {
$this->cache = $cacheFactory->createDistributed('talk/lastmsgid');
$this->unreadCountCache = $cacheFactory->createDistributed('talk/unreadcount');
Expand Down Expand Up @@ -219,8 +228,11 @@ public function addChangelogMessage(Room $chat, string $message): IComment {

/**
* Sends a new message to the given chat.
*
* @throws IRateLimitExceededException Only when $rateLimitGuestMentions is true and the author is a guest participant
* @throws MessageTooLongException
*/
public function sendMessage(Room $chat, ?Participant $participant, string $actorType, string $actorId, string $message, \DateTime $creationDateTime, ?IComment $replyTo, string $referenceId, bool $silent): IComment {
public function sendMessage(Room $chat, ?Participant $participant, string $actorType, string $actorId, string $message, \DateTime $creationDateTime, ?IComment $replyTo = null, string $referenceId = '', bool $silent = false, bool $rateLimitGuestMentions = true): IComment {
$comment = $this->commentsManager->create($actorType, $actorId, 'chat', (string) $chat->getId());
$comment->setMessage($message, self::MAX_CHAT_LENGTH);
$comment->setCreationDateTime($creationDateTime);
Expand All @@ -238,6 +250,18 @@ public function sendMessage(Room $chat, ?Participant $participant, string $actor
}
$this->setMessageExpiration($chat, $comment);

if ($rateLimitGuestMentions && $participant instanceof Participant && $participant->isGuest()) {
$mentions = $comment->getMentions();
if (!empty($mentions)) {
$this->rateLimiter->registerAnonRequest(
'talk-mentions',
self::RATE_LIMIT_GUEST_MENTIONS_LIMIT,
self::RATE_LIMIT_GUEST_MENTIONS_PERIOD,
$this->request->getRemoteAddress(),
);
}
}

$event = new BeforeChatMessageSentEvent($chat, $comment, $participant, $silent);
$this->dispatcher->dispatchTyped($event);

Expand Down
2 changes: 1 addition & 1 deletion lib/Controller/BotController.php
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ public function sendMessage(string $token, string $message, string $referenceId
$creationDateTime = $this->timeFactory->getDateTime('now', new \DateTimeZone('UTC'));

try {
$this->chatManager->sendMessage($room, $this->participant, $actorType, $actorId, $message, $creationDateTime, $parent, $referenceId, $silent);
$this->chatManager->sendMessage($room, $this->participant, $actorType, $actorId, $message, $creationDateTime, $parent, $referenceId, $silent, rateLimitGuestMentions: false);
} catch (MessageTooLongException) {
return new DataResponse([], Http::STATUS_REQUEST_ENTITY_TOO_LARGE);
} catch (\Exception) {
Expand Down
2 changes: 1 addition & 1 deletion lib/Controller/BreakoutRoomController.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public function __construct(
* @param 0|1|2|3 $mode Mode of the breakout rooms
* @psalm-param BreakoutRoom::MODE_* $mode
* @param 1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20 $amount Number of breakout rooms
* @psalm-param int<1, 20> $amount Constants {@see BreakoutRoom::MINIMUM_ROOM_AMOUNT} and {@see BreakoutRoom::MAXIMUM_ROOM_AMOUNT}
* @psalm-param int<1, 20> $amount Number of breakout rooms - Constants {@see BreakoutRoom::MINIMUM_ROOM_AMOUNT} and {@see BreakoutRoom::MAXIMUM_ROOM_AMOUNT}
* @param string $attendeeMap Mapping of the attendees to breakout rooms
* @return DataResponse<Http::STATUS_OK, TalkRoom[], array{}>|DataResponse<Http::STATUS_BAD_REQUEST, array{error: string}, array{}>
*
Expand Down
8 changes: 6 additions & 2 deletions lib/Controller/ChatController.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
use OCP\RichObjectStrings\InvalidObjectExeption;
use OCP\RichObjectStrings\IValidator;
use OCP\Security\ITrustedDomainHelper;
use OCP\Security\RateLimiting\IRateLimitExceededException;
use OCP\Share\Exceptions\ShareNotFound;
use OCP\Share\IShare;
use OCP\User\Events\UserLiveStatusEvent;
Expand Down Expand Up @@ -182,12 +183,13 @@ protected function parseCommentToResponse(IComment $comment, Message $parentMess
* @param int $replyTo Parent id which this message is a reply to
* @psalm-param non-negative-int $replyTo
* @param bool $silent If sent silent the chat message will not create any notifications
* @return DataResponse<Http::STATUS_CREATED, ?TalkChatMessageWithParent, array{X-Chat-Last-Common-Read?: numeric-string}>|DataResponse<Http::STATUS_BAD_REQUEST|Http::STATUS_NOT_FOUND|Http::STATUS_REQUEST_ENTITY_TOO_LARGE, array<empty>, array{}>
* @return DataResponse<Http::STATUS_CREATED, ?TalkChatMessageWithParent, array{X-Chat-Last-Common-Read?: numeric-string}>|DataResponse<Http::STATUS_BAD_REQUEST|Http::STATUS_NOT_FOUND|Http::STATUS_REQUEST_ENTITY_TOO_LARGE|Http::STATUS_TOO_MANY_REQUESTS, array<empty>, array{}>
*
* 201: Message sent successfully
* 400: Sending message is not possible
* 404: Actor not found
* 413: Message too long
* 429: Mention rate limit exceeded (guests only)
*/
#[PublicPage]
#[RequireModeratorOrNoLobby]
Expand Down Expand Up @@ -225,8 +227,10 @@ public function sendMessage(string $message, string $actorDisplayName = '', stri

try {
$comment = $this->chatManager->sendMessage($this->room, $this->participant, $actorType, $actorId, $message, $creationDateTime, $parent, $referenceId, $silent);
} catch (MessageTooLongException $e) {
} catch (MessageTooLongException) {
return new DataResponse([], Http::STATUS_REQUEST_ENTITY_TOO_LARGE);
} catch (IRateLimitExceededException) {
return new DataResponse([], Http::STATUS_TOO_MANY_REQUESTS);
} catch (\Exception $e) {
return new DataResponse([], Http::STATUS_BAD_REQUEST);
}
Expand Down
4 changes: 1 addition & 3 deletions lib/Flow/Operation.php
Original file line number Diff line number Diff line change
Expand Up @@ -126,9 +126,7 @@ public function onEvent(string $eventName, Event $event, IRuleMatcher $ruleMatch
$participant->getAttendee()->getActorId(),
$this->prepareMention($mode, $participant) . $message,
new \DateTime(),
null,
'',
false
rateLimitGuestMentions: false,
);
} catch (UnexpectedValueException|ParticipantNotFoundException|RoomNotFoundException) {
continue;
Expand Down
2 changes: 1 addition & 1 deletion lib/Service/BreakoutRoomService.php
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,7 @@ public function broadcastChatMessage(Room $parent, Participant $participant, str
try {
foreach ($breakoutRooms as $breakoutRoom) {
$breakoutParticipant = $this->participantService->getParticipantByActor($breakoutRoom, $attendeeType, $attendeeId);
$comment = $this->chatManager->sendMessage($breakoutRoom, $breakoutParticipant, $attendeeType, $attendeeId, $message, $creationDateTime, null, '', false);
$comment = $this->chatManager->sendMessage($breakoutRoom, $breakoutParticipant, $attendeeType, $attendeeId, $message, $creationDateTime, rateLimitGuestMentions: false);
$breakoutRoom->setLastMessage($comment);
}
} finally {
Expand Down
Loading