1
0

SystemAddressbook.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\DAV\CardDAV;
  8. use OCA\DAV\Exception\UnsupportedLimitOnInitialSyncException;
  9. use OCA\Federation\TrustedServers;
  10. use OCP\Accounts\IAccountManager;
  11. use OCP\IConfig;
  12. use OCP\IGroupManager;
  13. use OCP\IL10N;
  14. use OCP\IRequest;
  15. use OCP\IUserSession;
  16. use Sabre\CardDAV\Backend\BackendInterface;
  17. use Sabre\CardDAV\Backend\SyncSupport;
  18. use Sabre\CardDAV\Card;
  19. use Sabre\DAV\Exception\Forbidden;
  20. use Sabre\DAV\Exception\NotFound;
  21. use Sabre\VObject\Component\VCard;
  22. use Sabre\VObject\Reader;
  23. use function array_filter;
  24. use function array_intersect;
  25. use function array_unique;
  26. use function in_array;
  27. class SystemAddressbook extends AddressBook {
  28. public const URI_SHARED = 'z-server-generated--system';
  29. /** @var IConfig */
  30. private $config;
  31. private IUserSession $userSession;
  32. private ?TrustedServers $trustedServers;
  33. private ?IRequest $request;
  34. private ?IGroupManager $groupManager;
  35. public function __construct(BackendInterface $carddavBackend,
  36. array $addressBookInfo,
  37. IL10N $l10n,
  38. IConfig $config,
  39. IUserSession $userSession,
  40. ?IRequest $request = null,
  41. ?TrustedServers $trustedServers = null,
  42. ?IGroupManager $groupManager = null) {
  43. parent::__construct($carddavBackend, $addressBookInfo, $l10n);
  44. $this->config = $config;
  45. $this->userSession = $userSession;
  46. $this->request = $request;
  47. $this->trustedServers = $trustedServers;
  48. $this->groupManager = $groupManager;
  49. $this->addressBookInfo['{DAV:}displayname'] = $l10n->t('Accounts');
  50. $this->addressBookInfo['{' . Plugin::NS_CARDDAV . '}addressbook-description'] = $l10n->t('System address book which holds all accounts');
  51. }
  52. /**
  53. * No checkbox checked -> Show only the same user
  54. * 'Allow username autocompletion in share dialog' -> show everyone
  55. * 'Allow username autocompletion in share dialog' + 'Allow username autocompletion to users within the same groups' -> show only users in intersecting groups
  56. * 'Allow username autocompletion in share dialog' + 'Allow username autocompletion to users based on phone number integration' -> show only the same user
  57. * 'Allow username autocompletion in share dialog' + 'Allow username autocompletion to users within the same groups' + 'Allow username autocompletion to users based on phone number integration' -> show only users in intersecting groups
  58. */
  59. public function getChildren() {
  60. $shareEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
  61. $shareEnumerationGroup = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
  62. $shareEnumerationPhone = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_phone', 'no') === 'yes';
  63. $user = $this->userSession->getUser();
  64. if (!$user) {
  65. // Should never happen because we don't allow anonymous access
  66. return [];
  67. }
  68. if ($user->getBackendClassName() === 'Guests' || !$shareEnumeration || (!$shareEnumerationGroup && $shareEnumerationPhone)) {
  69. $name = SyncService::getCardUri($user);
  70. try {
  71. return [parent::getChild($name)];
  72. } catch (NotFound $e) {
  73. return [];
  74. }
  75. }
  76. if ($shareEnumerationGroup) {
  77. if ($this->groupManager === null) {
  78. // Group manager is not available, so we can't determine which data is safe
  79. return [];
  80. }
  81. $groups = $this->groupManager->getUserGroups($user);
  82. $names = [];
  83. foreach ($groups as $group) {
  84. $users = $group->getUsers();
  85. foreach ($users as $groupUser) {
  86. if ($groupUser->getBackendClassName() === 'Guests') {
  87. continue;
  88. }
  89. $names[] = SyncService::getCardUri($groupUser);
  90. }
  91. }
  92. return parent::getMultipleChildren(array_unique($names));
  93. }
  94. $children = parent::getChildren();
  95. return array_filter($children, function (Card $child) {
  96. // check only for URIs that begin with Guests:
  97. return !str_starts_with($child->getName(), 'Guests:');
  98. });
  99. }
  100. /**
  101. * @param array $paths
  102. * @return Card[]
  103. * @throws NotFound
  104. */
  105. public function getMultipleChildren($paths): array {
  106. $shareEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
  107. $shareEnumerationGroup = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
  108. $shareEnumerationPhone = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_phone', 'no') === 'yes';
  109. $user = $this->userSession->getUser();
  110. if (($user !== null && $user->getBackendClassName() === 'Guests') || !$shareEnumeration || (!$shareEnumerationGroup && $shareEnumerationPhone)) {
  111. // No user or cards with no access
  112. if ($user === null || !in_array(SyncService::getCardUri($user), $paths, true)) {
  113. return [];
  114. }
  115. // Only return the own card
  116. try {
  117. return [parent::getChild(SyncService::getCardUri($user))];
  118. } catch (NotFound $e) {
  119. return [];
  120. }
  121. }
  122. if ($shareEnumerationGroup) {
  123. if ($this->groupManager === null || $user === null) {
  124. // Group manager or user is not available, so we can't determine which data is safe
  125. return [];
  126. }
  127. $groups = $this->groupManager->getUserGroups($user);
  128. $allowedNames = [];
  129. foreach ($groups as $group) {
  130. $users = $group->getUsers();
  131. foreach ($users as $groupUser) {
  132. if ($groupUser->getBackendClassName() === 'Guests') {
  133. continue;
  134. }
  135. $allowedNames[] = SyncService::getCardUri($groupUser);
  136. }
  137. }
  138. return parent::getMultipleChildren(array_intersect($paths, $allowedNames));
  139. }
  140. if (!$this->isFederation()) {
  141. return parent::getMultipleChildren($paths);
  142. }
  143. $objs = $this->carddavBackend->getMultipleCards($this->addressBookInfo['id'], $paths);
  144. $children = [];
  145. /** @var array $obj */
  146. foreach ($objs as $obj) {
  147. if (empty($obj)) {
  148. continue;
  149. }
  150. $carddata = $this->extractCarddata($obj);
  151. if (empty($carddata)) {
  152. continue;
  153. } else {
  154. $obj['carddata'] = $carddata;
  155. }
  156. $children[] = new Card($this->carddavBackend, $this->addressBookInfo, $obj);
  157. }
  158. return $children;
  159. }
  160. /**
  161. * @param string $name
  162. * @return Card
  163. * @throws NotFound
  164. * @throws Forbidden
  165. */
  166. public function getChild($name): Card {
  167. $user = $this->userSession->getUser();
  168. $shareEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
  169. $shareEnumerationGroup = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
  170. $shareEnumerationPhone = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_phone', 'no') === 'yes';
  171. if (($user !== null && $user->getBackendClassName() === 'Guests') || !$shareEnumeration || (!$shareEnumerationGroup && $shareEnumerationPhone)) {
  172. $ownName = $user !== null ? SyncService::getCardUri($user) : null;
  173. if ($ownName === $name) {
  174. return parent::getChild($name);
  175. }
  176. throw new Forbidden();
  177. }
  178. if ($shareEnumerationGroup) {
  179. if ($user === null || $this->groupManager === null) {
  180. // Group manager is not available, so we can't determine which data is safe
  181. throw new Forbidden();
  182. }
  183. $groups = $this->groupManager->getUserGroups($user);
  184. foreach ($groups as $group) {
  185. foreach ($group->getUsers() as $groupUser) {
  186. if ($groupUser->getBackendClassName() === 'Guests') {
  187. continue;
  188. }
  189. $otherName = SyncService::getCardUri($groupUser);
  190. if ($otherName === $name) {
  191. return parent::getChild($name);
  192. }
  193. }
  194. }
  195. throw new Forbidden();
  196. }
  197. if (!$this->isFederation()) {
  198. return parent::getChild($name);
  199. }
  200. $obj = $this->carddavBackend->getCard($this->addressBookInfo['id'], $name);
  201. if (!$obj) {
  202. throw new NotFound('Card not found');
  203. }
  204. $carddata = $this->extractCarddata($obj);
  205. if (empty($carddata)) {
  206. throw new Forbidden();
  207. } else {
  208. $obj['carddata'] = $carddata;
  209. }
  210. return new Card($this->carddavBackend, $this->addressBookInfo, $obj);
  211. }
  212. /**
  213. * @throws UnsupportedLimitOnInitialSyncException
  214. */
  215. public function getChanges($syncToken, $syncLevel, $limit = null) {
  216. if (!$syncToken && $limit) {
  217. throw new UnsupportedLimitOnInitialSyncException();
  218. }
  219. if (!$this->carddavBackend instanceof SyncSupport) {
  220. return null;
  221. }
  222. if (!$this->isFederation()) {
  223. return parent::getChanges($syncToken, $syncLevel, $limit);
  224. }
  225. $changed = $this->carddavBackend->getChangesForAddressBook(
  226. $this->addressBookInfo['id'],
  227. $syncToken,
  228. $syncLevel,
  229. $limit
  230. );
  231. if (empty($changed)) {
  232. return $changed;
  233. }
  234. $added = $modified = $deleted = [];
  235. foreach ($changed['added'] as $uri) {
  236. try {
  237. $this->getChild($uri);
  238. $added[] = $uri;
  239. } catch (NotFound|Forbidden $e) {
  240. $deleted[] = $uri;
  241. }
  242. }
  243. foreach ($changed['modified'] as $uri) {
  244. try {
  245. $this->getChild($uri);
  246. $modified[] = $uri;
  247. } catch (NotFound|Forbidden $e) {
  248. $deleted[] = $uri;
  249. }
  250. }
  251. $changed['added'] = $added;
  252. $changed['modified'] = $modified;
  253. $changed['deleted'] = $deleted;
  254. return $changed;
  255. }
  256. private function isFederation(): bool {
  257. if ($this->trustedServers === null || $this->request === null) {
  258. return false;
  259. }
  260. /** @psalm-suppress NoInterfaceProperties */
  261. $server = $this->request->server;
  262. if (!isset($server['PHP_AUTH_USER']) || $server['PHP_AUTH_USER'] !== 'system') {
  263. return false;
  264. }
  265. /** @psalm-suppress NoInterfaceProperties */
  266. $sharedSecret = $server['PHP_AUTH_PW'] ?? null;
  267. if ($sharedSecret === null) {
  268. return false;
  269. }
  270. $servers = $this->trustedServers->getServers();
  271. $trusted = array_filter($servers, function ($trustedServer) use ($sharedSecret) {
  272. return $trustedServer['shared_secret'] === $sharedSecret;
  273. });
  274. // Authentication is fine, but it's not for a federated share
  275. if (empty($trusted)) {
  276. return false;
  277. }
  278. return true;
  279. }
  280. /**
  281. * If the validation doesn't work the card is "not found" so we
  282. * return empty carddata even if the carddata might exist in the local backend.
  283. * This can happen when a user sets the required properties
  284. * FN, N to a local scope only but the request is from
  285. * a federated share.
  286. *
  287. * @see https://github.com/nextcloud/server/issues/38042
  288. *
  289. * @param array $obj
  290. * @return string|null
  291. */
  292. private function extractCarddata(array $obj): ?string {
  293. $obj['acl'] = $this->getChildACL();
  294. $cardData = $obj['carddata'];
  295. /** @var VCard $vCard */
  296. $vCard = Reader::read($cardData);
  297. foreach ($vCard->children() as $child) {
  298. $scope = $child->offsetGet('X-NC-SCOPE');
  299. if ($scope !== null && $scope->getValue() === IAccountManager::SCOPE_LOCAL) {
  300. $vCard->remove($child);
  301. }
  302. }
  303. $messages = $vCard->validate();
  304. if (!empty($messages)) {
  305. return null;
  306. }
  307. return $vCard->serialize();
  308. }
  309. /**
  310. * @return mixed
  311. * @throws Forbidden
  312. */
  313. public function delete() {
  314. if ($this->isFederation()) {
  315. parent::delete();
  316. }
  317. throw new Forbidden();
  318. }
  319. public function getACL() {
  320. return array_filter(parent::getACL(), function ($acl) {
  321. if (in_array($acl['privilege'], ['{DAV:}write', '{DAV:}all'], true)) {
  322. return false;
  323. }
  324. return true;
  325. });
  326. }
  327. }