Inbox.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. <?php
  2. declare(strict_types = 1);
  3. // {{{ License
  4. // This file is part of GNU social - https://www.gnu.org/software/social
  5. //
  6. // GNU social is free software: you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // GNU social is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  18. // }}}
  19. /**
  20. * ActivityPub implementation for GNU social
  21. *
  22. * @package GNUsocial
  23. * @category ActivityPub
  24. *
  25. * @author Diogo Peralta Cordeiro <@diogo.site>
  26. * @copyright 2018-2019, 2021 Free Software Foundation, Inc http://www.fsf.org
  27. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  28. */
  29. namespace Plugin\ActivityPub\Controller;
  30. use App\Core\Controller;
  31. use App\Core\DB\DB;
  32. use App\Core\Event;
  33. use function App\Core\I18n\_m;
  34. use App\Core\Log;
  35. use App\Core\Router\Router;
  36. use App\Entity\Actor;
  37. use App\Util\Exception\ClientException;
  38. use Component\FreeNetwork\Entity\FreeNetworkActorProtocol;
  39. use Component\FreeNetwork\Util\Discovery;
  40. use Exception;
  41. use const PHP_URL_HOST;
  42. use Plugin\ActivityPub\Entity\ActivitypubActor;
  43. use Plugin\ActivityPub\Entity\ActivitypubRsa;
  44. use Plugin\ActivityPub\Util\Explorer;
  45. use Plugin\ActivityPub\Util\HTTPSignature;
  46. use Plugin\ActivityPub\Util\Model;
  47. use Plugin\ActivityPub\Util\TypeResponse;
  48. /**
  49. * ActivityPub Inbox Handler
  50. *
  51. * @copyright 2018-2019, 2021 Free Software Foundation, Inc http://www.fsf.org
  52. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  53. */
  54. class Inbox extends Controller
  55. {
  56. /**
  57. * Create an Inbox Handler to receive something from someone.
  58. */
  59. public function handle(?int $gsactor_id = null): TypeResponse
  60. {
  61. $error = function (string $m, ?Exception $e = null): TypeResponse {
  62. Log::error('ActivityPub Error Answer: ' . ($json = json_encode(['error' => $m, 'exception' => var_export($e, true)])));
  63. return new TypeResponse($json, 400);
  64. };
  65. $path = Router::url('activitypub_inbox', type: Router::ABSOLUTE_PATH);
  66. if (!\is_null($gsactor_id)) {
  67. try {
  68. $user = DB::findOneBy('local_user', ['id' => $gsactor_id]);
  69. $path = Router::url('activitypub_actor_inbox', ['gsactor_id' => $user->getId()], type: Router::ABSOLUTE_PATH);
  70. } catch (Exception $e) {
  71. throw new ClientException(_m('No such actor.'), 404, $e);
  72. }
  73. }
  74. Log::debug('ActivityPub Inbox: Received a POST request.');
  75. $body = (string) $this->request->getContent();
  76. Log::debug('ActivityPub Inbox: Request Body content: ' . $body);
  77. $type = Model::jsonToType($body);
  78. if ($type->has('actor') === false) {
  79. return $error('Actor not found in the request.');
  80. }
  81. try {
  82. $resource_parts = parse_url($type->get('actor'));
  83. if ($resource_parts['host'] !== $_ENV['SOCIAL_DOMAIN']) { // XXX: Common::config('site', 'server')) {
  84. $ap_actor = ActivitypubActor::fromUri($type->get('actor'));
  85. $actor = Actor::getById($ap_actor->getActorId());
  86. DB::flush();
  87. } else {
  88. throw new Exception('Only remote actors can use this endpoint.');
  89. }
  90. unset($resource_parts);
  91. } catch (Exception $e) {
  92. return $error('Invalid actor.', $e);
  93. }
  94. $activitypub_rsa = ActivitypubRsa::getByActor($actor);
  95. $actor_public_key = $activitypub_rsa->getPublicKey();
  96. $headers = $this->request->headers->all();
  97. Log::debug('ActivityPub Inbox: Request Headers: ' . var_export($headers, true));
  98. // Flattify headers
  99. foreach ($headers as $key => $val) {
  100. $headers[$key] = $val[0];
  101. }
  102. if (!isset($headers['signature'])) {
  103. Log::debug('ActivityPub Inbox: HTTP Signature: Missing Signature header.');
  104. return $error('Missing Signature header.');
  105. // TODO: support other methods beyond HTTP Signatures
  106. }
  107. // Extract the signature properties
  108. $signatureData = HTTPSignature::parseSignatureHeader($headers['signature']);
  109. Log::debug('ActivityPub Inbox: HTTP Signature Data: ' . print_r($signatureData, true));
  110. if (isset($signatureData['error'])) {
  111. Log::debug('ActivityPub Inbox: HTTP Signature: ' . json_encode($signatureData, \JSON_PRETTY_PRINT));
  112. return $error(json_encode($signatureData, \JSON_PRETTY_PRINT));
  113. }
  114. [$verified, /*$headers*/] = HTTPSignature::verify($actor_public_key, $signatureData, $headers, $path, $body);
  115. // If the signature fails verification the first time, update profile as it might have changed public key
  116. if ($verified !== 1) {
  117. try {
  118. $res = Explorer::get_remote_user_activity($ap_actor->getUri());
  119. if (\is_null($res)) {
  120. return $error('Invalid remote actor (null response).');
  121. }
  122. } catch (Exception $e) {
  123. return $error('Invalid remote actor.', $e);
  124. }
  125. try {
  126. ActivitypubActor::update_profile($ap_actor, $actor, $activitypub_rsa, $res);
  127. } catch (Exception $e) {
  128. return $error('Failed to updated remote actor information.', $e);
  129. }
  130. [$verified, /*$headers*/] = HTTPSignature::verify($actor_public_key, $signatureData, $headers, $path, $body);
  131. }
  132. // If it still failed despite profile update
  133. if ($verified !== 1) {
  134. Log::debug('ActivityPub Inbox: HTTP Signature: Invalid signature.');
  135. return $error('Invalid signature.');
  136. }
  137. // HTTP signature checked out, make sure the "actor" of the activity matches that of the signature
  138. Log::debug('ActivityPub Inbox: HTTP Signature: Authorised request. Will now start the inbox handler.');
  139. // TODO: Check if Actor has authority over payload
  140. // Store Activity
  141. $ap_act = Model\Activity::fromJson($type, ['source' => 'ActivityPub']);
  142. FreeNetworkActorProtocol::protocolSucceeded(
  143. 'activitypub',
  144. $ap_actor->getActorId(),
  145. Discovery::normalize($actor->getNickname() . '@' . parse_url($ap_actor->getInboxUri(), PHP_URL_HOST)),
  146. );
  147. Event::handle('NewNotification', [$actor, $ap_act->getActivity(), [], _m('{nickname} mentioned you.', ['{nickname}' => $actor->getNickname()])]);
  148. DB::flush();
  149. dd($ap_act, $act = $ap_act->getActivity(), $act->getActor(), $act->getObject());
  150. return new TypeResponse($type, status: 202);
  151. }
  152. }