-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathACLPlugin.php
More file actions
354 lines (301 loc) Β· 11.1 KB
/
ACLPlugin.php
File metadata and controls
354 lines (301 loc) Β· 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\GroupFolders\DAV;
use OCA\DAV\Connector\Sabre\Node;
use OCA\GroupFolders\ACL\ACLManagerFactory;
use OCA\GroupFolders\ACL\Rule;
use OCA\GroupFolders\ACL\RuleManager;
use OCA\GroupFolders\ACL\UserMapping\IUserMapping;
use OCA\GroupFolders\Folder\FolderManager;
use OCA\GroupFolders\Mount\GroupMountPoint;
use OCP\Constants;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\IL10N;
use OCP\IUser;
use OCP\IUserSession;
use OCP\Log\Audit\CriticalActionPerformedEvent;
use Sabre\DAV\Exception\BadRequest;
use Sabre\DAV\INode;
use Sabre\DAV\PropFind;
use Sabre\DAV\PropPatch;
use Sabre\DAV\Server;
use Sabre\DAV\ServerPlugin;
use Sabre\Xml\Reader;
/**
* SabreDAV plugin for exposing and updating advanced ACL properties.
*
* Handles WebDAV PROPFIND and PROPPATCH events for Nextcloud group folders with granular access controls.
*/
class ACLPlugin extends ServerPlugin {
public const ACL_ENABLED = '{http://nextcloud.org/ns}acl-enabled';
public const ACL_CAN_MANAGE = '{http://nextcloud.org/ns}acl-can-manage';
public const ACL_LIST = '{http://nextcloud.org/ns}acl-list';
public const INHERITED_ACL_LIST = '{http://nextcloud.org/ns}inherited-acl-list';
public const GROUP_FOLDER_ID = '{http://nextcloud.org/ns}group-folder-id';
public const ACL_BASE_PERMISSION_PROPERTYNAME = '{http://nextcloud.org/ns}acl-base-permission';
private ?Server $server = null;
private readonly ?IUser $user;
/** @var array<int, bool> */
private array $canManageACL = [];
public function __construct(
private readonly RuleManager $ruleManager,
private readonly IUserSession $userSession,
private readonly FolderManager $folderManager,
private readonly IEventDispatcher $eventDispatcher,
private readonly ACLManagerFactory $aclManagerFactory,
private readonly IL10N $l10n,
) {
$this->user = $this->userSession->getUser();
if ($this->user === null) {
return;
}
}
public function initialize(Server $server): void {
$this->server = $server;
$this->server->on('propFind', $this->propFind(...));
$this->server->on('propPatch', $this->propPatch(...));
$this->server->xml->elementMap[Rule::ACL] =
Rule::class;
$this->server->xml->elementMap[self::ACL_LIST] =
fn (Reader $reader): array =>
\Sabre\Xml\Deserializer\repeatingElements($reader, Rule::ACL);
}
public function propFind(PropFind $propFind, INode $node): void {
if (!$node instanceof Node) {
return;
}
$fileInfo = $node->getFileInfo();
$mount = $fileInfo->getMountPoint();
if (!$mount instanceof GroupMountPoint) {
return;
}
$propFind->handle(
self::ACL_LIST,
function () use ($fileInfo, $mount): ?array {
// Happens when sharing with a remote instance
if ($this->user === null) {
return [];
}
$path = trim($mount->getSourcePath() . '/' . $fileInfo->getInternalPath(), '/');
if ($this->isAdmin($this->user, $fileInfo->getPath())) {
$rules = $this->ruleManager->getAllRulesForPaths($mount->getNumericStorageId(), [$path]);
} else {
$rules = $this->ruleManager->getRulesForFilesByPath($this->user, $mount->getNumericStorageId(), [$path]);
}
return array_pop($rules);
});
$propFind->handle(
self::INHERITED_ACL_LIST,
function () use ($fileInfo, $mount): array {
// Happens when sharing with a remote instance
if ($this->user === null) {
return [];
}
$parentInternalPaths = $this->getParents($fileInfo->getInternalPath());
$parentPaths = array_map(
fn (string $internalPath): string => trim($mount->getSourcePath() . '/' . $internalPath, '/'),
$parentInternalPaths
);
// Also include the mount root
$parentPaths[] = $mount->getSourcePath();
if ($this->isAdmin($this->user, $fileInfo->getPath())) {
$rulesByPath = $this->ruleManager->getAllRulesForPaths($mount->getNumericStorageId(), $parentPaths);
} else {
$rulesByPath = $this->ruleManager->getRulesForFilesByPath($this->user, $mount->getNumericStorageId(), $parentPaths);
}
$aclManager = $this->aclManagerFactory->getACLManager($this->user);
ksort($rulesByPath);
$inheritedPermissionsByMapping = [];
$inheritedMaskByMapping = [];
$mappings = [];
foreach ($rulesByPath as $rules) {
foreach ($rules as $rule) {
$mappingKey = $rule->getUserMapping()->getType() . '::' . $rule->getUserMapping()->getId();
if (!isset($mappings[$mappingKey])) {
$mappings[$mappingKey] = $rule->getUserMapping();
}
if (!isset($inheritedPermissionsByMapping[$mappingKey])) {
$inheritedPermissionsByMapping[$mappingKey] = $aclManager->getBasePermission($mount->getFolderId());
}
if (!isset($inheritedMaskByMapping[$mappingKey])) {
$inheritedMaskByMapping[$mappingKey] = 0;
}
$inheritedPermissionsByMapping[$mappingKey] = $rule->applyPermissions($inheritedPermissionsByMapping[$mappingKey]);
$inheritedMaskByMapping[$mappingKey] |= $rule->getMask();
}
}
return array_map(
fn (IUserMapping $mapping, int $permissions, int $mask): Rule => new Rule(
$mapping,
$fileInfo->getId(),
$mask,
$permissions
),
$mappings,
$inheritedPermissionsByMapping,
$inheritedMaskByMapping
);
}
);
$propFind->handle(
self::GROUP_FOLDER_ID,
fn (): int => $this->folderManager->getFolderByPath($fileInfo->getPath())
);
$propFind->handle(
self::ACL_ENABLED,
function () use ($fileInfo): bool {
$folderId = $this->folderManager->getFolderByPath($fileInfo->getPath());
return $this->folderManager->getFolderAclEnabled($folderId);
}
);
$propFind->handle(
self::ACL_CAN_MANAGE,
function () use ($fileInfo): bool {
// Happens when sharing with a remote instance
if ($this->user === null) {
return false;
}
return $this->isAdmin($this->user, $fileInfo->getPath());
}
);
$propFind->handle(
self::ACL_BASE_PERMISSION_PROPERTYNAME,
function () use ($mount): int {
// Happens when sharing with a remote instance
if ($this->user === null) {
return Constants::PERMISSION_ALL;
}
return $this->aclManagerFactory->getACLManager($this->user)->getBasePermission($mount->getFolderId());
}
);
}
public function propPatch(string $path, PropPatch $propPatch): void {
if ($this->server === null) {
return;
}
// Happens when sharing with a remote instance
if ($this->user === null) {
return;
}
$node = $this->server->tree->getNodeForPath($path);
if (!$node instanceof Node) {
return;
}
$fileInfo = $node->getFileInfo();
$mount = $fileInfo->getMountPoint();
if (!$mount instanceof GroupMountPoint) {
return;
}
if (!$this->isAdmin($this->user, $fileInfo->getPath())) {
return;
}
// Mapping the old property to the new property.
$propPatch->handle(
self::ACL_LIST,
function (array $rawRules) use ($path): bool {
$node = $this->server->tree->getNodeForPath($path);
if (!$node instanceof Node) {
return false;
}
$fileInfo = $node->getFileInfo();
$mount = $fileInfo->getMountPoint();
if (!$mount instanceof GroupMountPoint) {
return false;
}
if ($this->user === null) {
return false;
}
$path = trim($mount->getSourcePath() . '/' . $fileInfo->getInternalPath(), '/');
// populate fileid in rules
$rules = array_values(array_map(fn (Rule $rule): Rule => new Rule(
$rule->getUserMapping(),
$fileInfo->getId(),
$rule->getMask(),
$rule->getPermissions()
), $rawRules));
$formattedRules = array_map(fn (Rule $rule): string => $rule->getUserMapping()->getType() . ' ' . $rule->getUserMapping()->getDisplayName() . ': ' . $rule->formatPermissions(), $rules);
if (count($formattedRules)) {
$formattedRules = implode(', ', $formattedRules);
$this->eventDispatcher->dispatchTyped(new CriticalActionPerformedEvent('The advanced permissions for "%s" in Team folder with ID %d was set to "%s"', [
$fileInfo->getInternalPath(),
$mount->getFolderId(),
$formattedRules,
]));
} else {
$this->eventDispatcher->dispatchTyped(new CriticalActionPerformedEvent('The advanced permissions for "%s" in Team folder with ID %d was cleared', [
$fileInfo->getInternalPath(),
$mount->getFolderId(),
]));
}
$aclManager = $this->aclManagerFactory->getACLManager($this->user);
$newPermissions = $aclManager->testACLPermissionsForPath($mount->getFolderId(), $mount->getNumericStorageId(), $path, $rules);
if (!($newPermissions & Constants::PERMISSION_READ)) {
throw new BadRequest($this->l10n->t('You cannot remove your own read permission.'));
}
$existingRules = array_reduce(
$this->ruleManager->getAllRulesForPaths($mount->getNumericStorageId(), [$path]),
array_merge(...),
[]
);
$deletedRules = array_udiff($existingRules, $rules, fn (Rule $obj_a, Rule $obj_b): int => (
$obj_a->getUserMapping()->getType() === $obj_b->getUserMapping()->getType()
&& $obj_a->getUserMapping()->getId() === $obj_b->getUserMapping()->getId()
) ? 0 : -1);
foreach ($deletedRules as $deletedRule) {
$this->ruleManager->deleteRule($deletedRule);
}
foreach ($rules as $rule) {
$this->ruleManager->saveRule($rule);
}
$node->getNode()->getStorage()->getPropagator()->propagateChange($fileInfo->getInternalPath(), $fileInfo->getMtime());
return true;
}
);
}
/**
* Checks if the given user has admin (ACL management) rights for the group folder at the given path.
*
* Caches the result per folder ID for efficiency.
*
* @param IUser $user The user to check.
* @param string $path The full path to a file or folder inside a group folder.
* @return bool True if the user can manage ACLs for the group folder at the given path, false otherwise.
* @throws \OCP\Files\NotFoundException If the path does not exist or is not part of a group folder.
*/
private function isAdmin(IUser $user, string $path): bool {
// TODO: catch/handle gracefully if folder disappeared between node fetch and this check (i.e. by another user / session)
$folderId = $this->folderManager->getFolderByPath($path);
if (isset($this->canManageACL[$folderId])) {
return $this->canManageACL[$folderId];
}
$canManage = $this->folderManager->canManageACL($folderId, $user);
$this->canManageACL[$folderId] = $canManage;
return $canManage;
}
/**
* Returns all parent directory paths for the given path, based solely on the path itself.
*
* The array is ordered from immediate parent upward, excluding the original path.
*
* Example:
* getParents('a/b/c.txt') returns ['a/b', 'a']
*
* Note: Callers should add contextual parents (such as mount points or absolute roots) if needed.
*
* @param string $path Path to a file or directory.
* @return string[] Parent directory paths, from closest to furthest.
*/
private function getParents(string $path): array {
$parents = [];
$parent = dirname($path);
while ($parent !== '' && $parent !== '.' && $parent !== '/') {
$parents[] = $parent;
$parent = dirname($parent);
}
return $parents;
}
}