AuthSettingsController.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\Settings\Controller;
  8. use BadMethodCallException;
  9. use OC\Authentication\Exceptions\InvalidTokenException as OcInvalidTokenException;
  10. use OC\Authentication\Exceptions\PasswordlessTokenException;
  11. use OC\Authentication\Token\INamedToken;
  12. use OC\Authentication\Token\IProvider;
  13. use OC\Authentication\Token\RemoteWipe;
  14. use OCA\Settings\Activity\Provider;
  15. use OCP\Activity\IManager;
  16. use OCP\AppFramework\Controller;
  17. use OCP\AppFramework\Http;
  18. use OCP\AppFramework\Http\Attribute\NoAdminRequired;
  19. use OCP\AppFramework\Http\Attribute\PasswordConfirmationRequired;
  20. use OCP\AppFramework\Http\JSONResponse;
  21. use OCP\Authentication\Exceptions\ExpiredTokenException;
  22. use OCP\Authentication\Exceptions\InvalidTokenException;
  23. use OCP\Authentication\Exceptions\WipeTokenException;
  24. use OCP\Authentication\Token\IToken;
  25. use OCP\IRequest;
  26. use OCP\ISession;
  27. use OCP\IUserSession;
  28. use OCP\Security\ISecureRandom;
  29. use OCP\Session\Exceptions\SessionNotAvailableException;
  30. use Psr\Log\LoggerInterface;
  31. class AuthSettingsController extends Controller {
  32. /** @var IProvider */
  33. private $tokenProvider;
  34. /** @var RemoteWipe */
  35. private $remoteWipe;
  36. /**
  37. * @param string $appName
  38. * @param IRequest $request
  39. * @param IProvider $tokenProvider
  40. * @param ISession $session
  41. * @param ISecureRandom $random
  42. * @param string|null $userId
  43. * @param IUserSession $userSession
  44. * @param IManager $activityManager
  45. * @param RemoteWipe $remoteWipe
  46. * @param LoggerInterface $logger
  47. */
  48. public function __construct(
  49. string $appName,
  50. IRequest $request,
  51. IProvider $tokenProvider,
  52. private ISession $session,
  53. private ISecureRandom $random,
  54. private ?string $userId,
  55. private IUserSession $userSession,
  56. private IManager $activityManager,
  57. RemoteWipe $remoteWipe,
  58. private LoggerInterface $logger,
  59. ) {
  60. parent::__construct($appName, $request);
  61. $this->tokenProvider = $tokenProvider;
  62. $this->remoteWipe = $remoteWipe;
  63. }
  64. /**
  65. * @NoSubAdminRequired
  66. *
  67. * @param string $name
  68. * @return JSONResponse
  69. */
  70. #[NoAdminRequired]
  71. #[PasswordConfirmationRequired]
  72. public function create($name) {
  73. if ($this->checkAppToken()) {
  74. return $this->getServiceNotAvailableResponse();
  75. }
  76. try {
  77. $sessionId = $this->session->getId();
  78. } catch (SessionNotAvailableException $ex) {
  79. return $this->getServiceNotAvailableResponse();
  80. }
  81. if ($this->userSession->getImpersonatingUserID() !== null) {
  82. return $this->getServiceNotAvailableResponse();
  83. }
  84. try {
  85. $sessionToken = $this->tokenProvider->getToken($sessionId);
  86. $loginName = $sessionToken->getLoginName();
  87. try {
  88. $password = $this->tokenProvider->getPassword($sessionToken, $sessionId);
  89. } catch (PasswordlessTokenException $ex) {
  90. $password = null;
  91. }
  92. } catch (InvalidTokenException $ex) {
  93. return $this->getServiceNotAvailableResponse();
  94. }
  95. if (mb_strlen($name) > 128) {
  96. $name = mb_substr($name, 0, 120) . '…';
  97. }
  98. $token = $this->generateRandomDeviceToken();
  99. $deviceToken = $this->tokenProvider->generateToken($token, $this->userId, $loginName, $password, $name, IToken::PERMANENT_TOKEN);
  100. $tokenData = $deviceToken->jsonSerialize();
  101. $tokenData['canDelete'] = true;
  102. $tokenData['canRename'] = true;
  103. $this->publishActivity(Provider::APP_TOKEN_CREATED, $deviceToken->getId(), ['name' => $deviceToken->getName()]);
  104. return new JSONResponse([
  105. 'token' => $token,
  106. 'loginName' => $loginName,
  107. 'deviceToken' => $tokenData,
  108. ]);
  109. }
  110. /**
  111. * @return JSONResponse
  112. */
  113. private function getServiceNotAvailableResponse() {
  114. $resp = new JSONResponse();
  115. $resp->setStatus(Http::STATUS_SERVICE_UNAVAILABLE);
  116. return $resp;
  117. }
  118. /**
  119. * Return a 25 digit device password
  120. *
  121. * Example: AbCdE-fGhJk-MnPqR-sTwXy-23456
  122. *
  123. * @return string
  124. */
  125. private function generateRandomDeviceToken() {
  126. $groups = [];
  127. for ($i = 0; $i < 5; $i++) {
  128. $groups[] = $this->random->generate(5, ISecureRandom::CHAR_HUMAN_READABLE);
  129. }
  130. return implode('-', $groups);
  131. }
  132. private function checkAppToken(): bool {
  133. return $this->session->exists('app_password');
  134. }
  135. /**
  136. * @NoSubAdminRequired
  137. *
  138. * @param int $id
  139. * @return array|JSONResponse
  140. */
  141. #[NoAdminRequired]
  142. public function destroy($id) {
  143. if ($this->checkAppToken()) {
  144. return new JSONResponse([], Http::STATUS_BAD_REQUEST);
  145. }
  146. try {
  147. $token = $this->findTokenByIdAndUser($id);
  148. } catch (WipeTokenException $e) {
  149. //continue as we can destroy tokens in wipe
  150. $token = $e->getToken();
  151. } catch (InvalidTokenException $e) {
  152. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  153. }
  154. $this->tokenProvider->invalidateTokenById($this->userId, $token->getId());
  155. $this->publishActivity(Provider::APP_TOKEN_DELETED, $token->getId(), ['name' => $token->getName()]);
  156. return [];
  157. }
  158. /**
  159. * @NoSubAdminRequired
  160. *
  161. * @param int $id
  162. * @param array $scope
  163. * @param string $name
  164. * @return array|JSONResponse
  165. */
  166. #[NoAdminRequired]
  167. public function update($id, array $scope, string $name) {
  168. if ($this->checkAppToken()) {
  169. return new JSONResponse([], Http::STATUS_BAD_REQUEST);
  170. }
  171. try {
  172. $token = $this->findTokenByIdAndUser($id);
  173. } catch (InvalidTokenException $e) {
  174. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  175. }
  176. $currentName = $token->getName();
  177. if ($scope !== $token->getScopeAsArray()) {
  178. $token->setScope([IToken::SCOPE_FILESYSTEM => $scope[IToken::SCOPE_FILESYSTEM]]);
  179. $this->publishActivity($scope[IToken::SCOPE_FILESYSTEM] ? Provider::APP_TOKEN_FILESYSTEM_GRANTED : Provider::APP_TOKEN_FILESYSTEM_REVOKED, $token->getId(), ['name' => $currentName]);
  180. }
  181. if (mb_strlen($name) > 128) {
  182. $name = mb_substr($name, 0, 120) . '…';
  183. }
  184. if ($token instanceof INamedToken && $name !== $currentName) {
  185. $token->setName($name);
  186. $this->publishActivity(Provider::APP_TOKEN_RENAMED, $token->getId(), ['name' => $currentName, 'newName' => $name]);
  187. }
  188. $this->tokenProvider->updateToken($token);
  189. return [];
  190. }
  191. /**
  192. * @param string $subject
  193. * @param int $id
  194. * @param array $parameters
  195. */
  196. private function publishActivity(string $subject, int $id, array $parameters = []): void {
  197. $event = $this->activityManager->generateEvent();
  198. $event->setApp('settings')
  199. ->setType('security')
  200. ->setAffectedUser($this->userId)
  201. ->setAuthor($this->userId)
  202. ->setSubject($subject, $parameters)
  203. ->setObject('app_token', $id, 'App Password');
  204. try {
  205. $this->activityManager->publish($event);
  206. } catch (BadMethodCallException $e) {
  207. $this->logger->warning('could not publish activity', ['exception' => $e]);
  208. }
  209. }
  210. /**
  211. * Find a token by given id and check if uid for current session belongs to this token
  212. *
  213. * @param int $id
  214. * @return IToken
  215. * @throws InvalidTokenException
  216. */
  217. private function findTokenByIdAndUser(int $id): IToken {
  218. try {
  219. $token = $this->tokenProvider->getTokenById($id);
  220. } catch (ExpiredTokenException $e) {
  221. $token = $e->getToken();
  222. }
  223. if ($token->getUID() !== $this->userId) {
  224. /** @psalm-suppress DeprecatedClass We have to throw the OC version so both OC and OCP catches catch it */
  225. throw new OcInvalidTokenException('This token does not belong to you!');
  226. }
  227. return $token;
  228. }
  229. /**
  230. * @NoSubAdminRequired
  231. *
  232. * @param int $id
  233. * @return JSONResponse
  234. * @throws InvalidTokenException
  235. * @throws ExpiredTokenException
  236. */
  237. #[NoAdminRequired]
  238. #[PasswordConfirmationRequired]
  239. public function wipe(int $id): JSONResponse {
  240. if ($this->checkAppToken()) {
  241. return new JSONResponse([], Http::STATUS_BAD_REQUEST);
  242. }
  243. try {
  244. $token = $this->findTokenByIdAndUser($id);
  245. } catch (InvalidTokenException $e) {
  246. return new JSONResponse([], Http::STATUS_NOT_FOUND);
  247. }
  248. if (!$this->remoteWipe->markTokenForWipe($token)) {
  249. return new JSONResponse([], Http::STATUS_BAD_REQUEST);
  250. }
  251. return new JSONResponse([]);
  252. }
  253. }