SystemAddressbook.php 12 KB

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