Skip to content

Commit 7e57db0

Browse files
authored
Merge pull request #43783 from nextcloud/backport/43753/stable23
2 parents c4ab94e + 76ebc46 commit 7e57db0

7 files changed

Lines changed: 329 additions & 0 deletions

File tree

apps/dav/appinfo/v1/caldav.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
// Backends
2929
use OC\KnownUser\KnownUserService;
3030
use OCA\DAV\CalDAV\CalDavBackend;
31+
use OCA\DAV\CalDAV\Security\RateLimitingPlugin;
3132
use OCA\DAV\Connector\LegacyDAVACL;
3233
use OCA\DAV\CalDAV\CalendarRoot;
3334
use OCA\DAV\Connector\Sabre\Auth;
@@ -115,6 +116,7 @@
115116
$server->addPlugin(\OC::$server->query(\OCA\DAV\CalDAV\Schedule\IMipPlugin::class));
116117
}
117118
$server->addPlugin(new ExceptionLoggerPlugin('caldav', \OC::$server->getLogger()));
119+
$server->addPlugin(\OC::$server->get(RateLimitingPlugin::class));
118120

119121
// And off we go!
120122
$server->exec();

apps/dav/composer/composer/autoload_classmap.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@
9090
'OCA\\DAV\\CalDAV\\Search\\Xml\\Filter\\PropFilter' => $baseDir . '/../lib/CalDAV/Search/Xml/Filter/PropFilter.php',
9191
'OCA\\DAV\\CalDAV\\Search\\Xml\\Filter\\SearchTermFilter' => $baseDir . '/../lib/CalDAV/Search/Xml/Filter/SearchTermFilter.php',
9292
'OCA\\DAV\\CalDAV\\Search\\Xml\\Request\\CalendarSearchReport' => $baseDir . '/../lib/CalDAV/Search/Xml/Request/CalendarSearchReport.php',
93+
'OCA\\DAV\\CalDAV\\Security\\RateLimitingPlugin' => $baseDir . '/../lib/CalDAV/Security/RateLimitingPlugin.php',
9394
'OCA\\DAV\\CalDAV\\Trashbin\\DeletedCalendarObject' => $baseDir . '/../lib/CalDAV/Trashbin/DeletedCalendarObject.php',
9495
'OCA\\DAV\\CalDAV\\Trashbin\\DeletedCalendarObjectsCollection' => $baseDir . '/../lib/CalDAV/Trashbin/DeletedCalendarObjectsCollection.php',
9596
'OCA\\DAV\\CalDAV\\Trashbin\\Plugin' => $baseDir . '/../lib/CalDAV/Trashbin/Plugin.php',

apps/dav/composer/composer/autoload_static.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ class ComposerStaticInitDAV
105105
'OCA\\DAV\\CalDAV\\Search\\Xml\\Filter\\PropFilter' => __DIR__ . '/..' . '/../lib/CalDAV/Search/Xml/Filter/PropFilter.php',
106106
'OCA\\DAV\\CalDAV\\Search\\Xml\\Filter\\SearchTermFilter' => __DIR__ . '/..' . '/../lib/CalDAV/Search/Xml/Filter/SearchTermFilter.php',
107107
'OCA\\DAV\\CalDAV\\Search\\Xml\\Request\\CalendarSearchReport' => __DIR__ . '/..' . '/../lib/CalDAV/Search/Xml/Request/CalendarSearchReport.php',
108+
'OCA\\DAV\\CalDAV\\Security\\RateLimitingPlugin' => __DIR__ . '/..' . '/../lib/CalDAV/Security/RateLimitingPlugin.php',
108109
'OCA\\DAV\\CalDAV\\Trashbin\\DeletedCalendarObject' => __DIR__ . '/..' . '/../lib/CalDAV/Trashbin/DeletedCalendarObject.php',
109110
'OCA\\DAV\\CalDAV\\Trashbin\\DeletedCalendarObjectsCollection' => __DIR__ . '/..' . '/../lib/CalDAV/Trashbin/DeletedCalendarObjectsCollection.php',
110111
'OCA\\DAV\\CalDAV\\Trashbin\\Plugin' => __DIR__ . '/..' . '/../lib/CalDAV/Trashbin/Plugin.php',

apps/dav/lib/CalDAV/CalDavBackend.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,27 @@ public function getCalendarsForUserCount($principalUri, $excludeBirthday = true)
289289
return $column;
290290
}
291291

292+
/**
293+
* Return the number of subscriptions for a principal
294+
*/
295+
public function getSubscriptionsForUserCount(string $principalUri): int {
296+
$principalUri = $this->convertPrincipal($principalUri, true);
297+
$query = $this->db->getQueryBuilder();
298+
$query->select($query->func()->count('*'))
299+
->from('calendarsubscriptions');
300+
301+
if ($principalUri === '') {
302+
$query->where($query->expr()->emptyString('principaluri'));
303+
} else {
304+
$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
305+
}
306+
307+
$result = $query->executeQuery();
308+
$column = (int)$result->fetchOne();
309+
$result->closeCursor();
310+
return $column;
311+
}
312+
292313
/**
293314
* @return array{id: int, deleted_at: int}[]
294315
*/
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/*
6+
* @copyright 2023 Christoph Wurst <christoph@winzerhof-wurst.at>
7+
*
8+
* @author 2023 Christoph Wurst <christoph@winzerhof-wurst.at>
9+
*
10+
* @license GNU AGPL version 3 or any later version
11+
*
12+
* This program is free software: you can redistribute it and/or modify
13+
* it under the terms of the GNU Affero General Public License as
14+
* published by the Free Software Foundation, either version 3 of the
15+
* License, or (at your option) any later version.
16+
*
17+
* This program is distributed in the hope that it will be useful,
18+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
19+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20+
* GNU Affero General Public License for more details.
21+
*
22+
* You should have received a copy of the GNU Affero General Public License
23+
* along with this program. If not, see <http://www.gnu.org/licenses/>.
24+
*/
25+
26+
namespace OCA\DAV\CalDAV\Security;
27+
28+
use OC\Security\RateLimiting\Exception\RateLimitExceededException;
29+
use OC\Security\RateLimiting\Limiter;
30+
use OCA\DAV\CalDAV\CalDavBackend;
31+
use OCA\DAV\Connector\Sabre\Exception\TooManyRequests;
32+
use OCP\IConfig;
33+
use OCP\IUserManager;
34+
use Psr\Log\LoggerInterface;
35+
use Sabre\DAV;
36+
use Sabre\DAV\Exception\Forbidden;
37+
use Sabre\DAV\ServerPlugin;
38+
use function count;
39+
use function explode;
40+
41+
class RateLimitingPlugin extends ServerPlugin {
42+
43+
/** @var Limiter */
44+
private $limiter;
45+
46+
/** @var IUserManager */
47+
private $userManager;
48+
49+
/** @var CalDavBackend */
50+
private $calDavBackend;
51+
52+
/** @var IConfig */
53+
private $config;
54+
55+
/** @var LoggerInterface */
56+
private $logger;
57+
58+
/** @var string|null */
59+
private $userId;
60+
61+
public function __construct(Limiter $limiter,
62+
IUserManager $userManager,
63+
CalDavBackend $calDavBackend,
64+
LoggerInterface $logger,
65+
IConfig $config,
66+
?string $userId) {
67+
$this->limiter = $limiter;
68+
$this->userManager = $userManager;
69+
$this->calDavBackend = $calDavBackend;
70+
$this->config = $config;
71+
$this->logger = $logger;
72+
$this->userId = $userId;
73+
}
74+
75+
public function initialize(DAV\Server $server): void {
76+
$server->on('beforeBind', [$this, 'beforeBind'], 1);
77+
}
78+
79+
public function beforeBind(string $path): void {
80+
if ($this->userId === null) {
81+
// We only care about authenticated users here
82+
return;
83+
}
84+
$user = $this->userManager->get($this->userId);
85+
if ($user === null) {
86+
// We only care about authenticated users here
87+
return;
88+
}
89+
90+
$pathParts = explode('/', $path);
91+
if (count($pathParts) === 3 && $pathParts[0] === 'calendars') {
92+
// Path looks like calendars/username/calendarname so a new calendar or subscription is created
93+
try {
94+
$this->limiter->registerUserRequest(
95+
'caldav-create-calendar',
96+
(int) $this->config->getAppValue('dav', 'rateLimitCalendarCreation', '10'),
97+
(int) $this->config->getAppValue('dav', 'rateLimitPeriodCalendarCreation', '3600'),
98+
$user
99+
);
100+
} catch (RateLimitExceededException $e) {
101+
throw new TooManyRequests('Too many calendars created', 0, $e);
102+
}
103+
104+
$calendarLimit = (int) $this->config->getAppValue('dav', 'maximumCalendarsSubscriptions', '30');
105+
if ($calendarLimit === -1) {
106+
return;
107+
}
108+
$numCalendars = $this->calDavBackend->getCalendarsForUserCount('principals/users/' . $user->getUID());
109+
$numSubscriptions = $this->calDavBackend->getSubscriptionsForUserCount('principals/users/' . $user->getUID());
110+
111+
if (($numCalendars + $numSubscriptions) >= $calendarLimit) {
112+
$this->logger->warning('Maximum number of calendars/subscriptions reached', [
113+
'calendars' => $numCalendars,
114+
'subscription' => $numSubscriptions,
115+
'limit' => $calendarLimit,
116+
]);
117+
throw new Forbidden('Calendar limit reached', 0);
118+
}
119+
}
120+
}
121+
122+
}

apps/dav/lib/Server.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
use Psr\Log\LoggerInterface;
3838
use OCA\DAV\AppInfo\PluginManager;
3939
use OCA\DAV\CalDAV\BirthdayService;
40+
use OCA\DAV\CalDAV\Security\RateLimitingPlugin;
4041
use OCA\DAV\CardDAV\HasPhotoPlugin;
4142
use OCA\DAV\CardDAV\ImageExportPlugin;
4243
use OCA\DAV\CardDAV\MultiGetExportPlugin;
@@ -176,6 +177,8 @@ public function __construct(IRequest $request, $baseUri) {
176177
\OC::$server->getConfig(),
177178
\OC::$server->getURLGenerator()
178179
));
180+
181+
$this->server->addPlugin(\OC::$server->get(RateLimitingPlugin::class));
179182
}
180183

181184
// addressbook plugins
Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/*
6+
* @copyright 2023 Christoph Wurst <christoph@winzerhof-wurst.at>
7+
*
8+
* @author 2023 Christoph Wurst <christoph@winzerhof-wurst.at>
9+
*
10+
* @license GNU AGPL version 3 or any later version
11+
*
12+
* This program is free software: you can redistribute it and/or modify
13+
* it under the terms of the GNU Affero General Public License as
14+
* published by the Free Software Foundation, either version 3 of the
15+
* License, or (at your option) any later version.
16+
*
17+
* This program is distributed in the hope that it will be useful,
18+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
19+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20+
* GNU Affero General Public License for more details.
21+
*
22+
* You should have received a copy of the GNU Affero General Public License
23+
* along with this program. If not, see <http://www.gnu.org/licenses/>.
24+
*/
25+
26+
namespace OCA\DAV\Tests\unit\CalDAV\Security;
27+
28+
use OC\Security\RateLimiting\Exception\RateLimitExceededException;
29+
use OC\Security\RateLimiting\Limiter;
30+
use OCA\DAV\CalDAV\CalDavBackend;
31+
use OCA\DAV\CalDAV\Security\RateLimitingPlugin;
32+
use OCA\DAV\Connector\Sabre\Exception\TooManyRequests;
33+
use OCP\IConfig;
34+
use OCP\IUser;
35+
use OCP\IUserManager;
36+
use PHPUnit\Framework\MockObject\MockObject;
37+
use Psr\Log\LoggerInterface;
38+
use Sabre\DAV\Exception\Forbidden;
39+
use Test\TestCase;
40+
41+
class RateLimitingPluginTest extends TestCase {
42+
43+
/** @var Limiter|MockObject */
44+
private $limiter;
45+
46+
/** @var Limiter|CalDavBackend */
47+
private $caldavBackend;
48+
49+
/** @var Limiter|IUserManager */
50+
private $userManager;
51+
52+
/** @var Limiter|LoggerInterface */
53+
private $logger;
54+
55+
/** @var Limiter|IConfig */
56+
private $config;
57+
58+
/** @var Limiter|string */
59+
private $userId = 'user123';
60+
61+
/** @var Limiter|RateLimitingPlugin */
62+
private $plugin;
63+
64+
protected function setUp(): void {
65+
parent::setUp();
66+
67+
$this->limiter = $this->createMock(Limiter::class);
68+
$this->userManager = $this->createMock(IUserManager::class);
69+
$this->caldavBackend = $this->createMock(CalDavBackend::class);
70+
$this->logger = $this->createMock(LoggerInterface::class);
71+
$this->config = $this->createMock(IConfig::class);
72+
$this->plugin = new RateLimitingPlugin(
73+
$this->limiter,
74+
$this->userManager,
75+
$this->caldavBackend,
76+
$this->logger,
77+
$this->config,
78+
$this->userId,
79+
);
80+
}
81+
82+
public function testNoUserObject(): void {
83+
$this->limiter->expects(self::never())
84+
->method('registerUserRequest');
85+
86+
$this->plugin->beforeBind('calendars/foo/cal');
87+
}
88+
89+
public function testUnrelated(): void {
90+
$user = $this->createMock(IUser::class);
91+
$this->userManager->expects(self::once())
92+
->method('get')
93+
->with($this->userId)
94+
->willReturn($user);
95+
$this->limiter->expects(self::never())
96+
->method('registerUserRequest');
97+
98+
$this->plugin->beforeBind('foo/bar');
99+
}
100+
101+
public function testRegisterCalendarCreation(): void {
102+
$user = $this->createMock(IUser::class);
103+
$this->userManager->expects(self::once())
104+
->method('get')
105+
->with($this->userId)
106+
->willReturn($user);
107+
$this->config
108+
->method('getAppValue')
109+
->with('dav')
110+
->willReturnArgument(2);
111+
$this->limiter->expects(self::once())
112+
->method('registerUserRequest')
113+
->with(
114+
'caldav-create-calendar',
115+
10,
116+
3600,
117+
$user,
118+
);
119+
120+
$this->plugin->beforeBind('calendars/foo/cal');
121+
}
122+
123+
public function testCalendarCreationRateLimitExceeded(): void {
124+
$user = $this->createMock(IUser::class);
125+
$this->userManager->expects(self::once())
126+
->method('get')
127+
->with($this->userId)
128+
->willReturn($user);
129+
$this->config
130+
->method('getAppValue')
131+
->with('dav')
132+
->willReturnArgument(2);
133+
$this->limiter->expects(self::once())
134+
->method('registerUserRequest')
135+
->with(
136+
'caldav-create-calendar',
137+
10,
138+
3600,
139+
$user,
140+
)
141+
->willThrowException(new RateLimitExceededException());
142+
$this->expectException(TooManyRequests::class);
143+
144+
$this->plugin->beforeBind('calendars/foo/cal');
145+
}
146+
147+
public function testCalendarLimitReached(): void {
148+
$user = $this->createMock(IUser::class);
149+
$this->userManager->expects(self::once())
150+
->method('get')
151+
->with($this->userId)
152+
->willReturn($user);
153+
$user->method('getUID')->willReturn('user123');
154+
$this->config
155+
->method('getAppValue')
156+
->with('dav')
157+
->willReturnArgument(2);
158+
$this->limiter->expects(self::once())
159+
->method('registerUserRequest')
160+
->with(
161+
'caldav-create-calendar',
162+
10,
163+
3600,
164+
$user,
165+
);
166+
$this->caldavBackend->expects(self::once())
167+
->method('getCalendarsForUserCount')
168+
->with('principals/users/user123')
169+
->willReturn(27);
170+
$this->caldavBackend->expects(self::once())
171+
->method('getSubscriptionsForUserCount')
172+
->with('principals/users/user123')
173+
->willReturn(3);
174+
$this->expectException(Forbidden::class);
175+
176+
$this->plugin->beforeBind('calendars/foo/cal');
177+
}
178+
179+
}

0 commit comments

Comments
 (0)