Inbox.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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 function App\Core\I18n\_m;
  33. use App\Core\Log;
  34. use App\Core\Router\Router;
  35. use App\Entity\Actor;
  36. use App\Util\Exception\ClientException;
  37. use Component\FreeNetwork\Entity\FreeNetworkActorProtocol;
  38. use Component\FreeNetwork\Util\Discovery;
  39. use Exception;
  40. use const PHP_URL_HOST;
  41. use Plugin\ActivityPub\Entity\ActivitypubActor;
  42. use Plugin\ActivityPub\Entity\ActivitypubRsa;
  43. use Plugin\ActivityPub\Util\Explorer;
  44. use Plugin\ActivityPub\Util\HTTPSignature;
  45. use Plugin\ActivityPub\Util\Model;
  46. use Plugin\ActivityPub\Util\TypeResponse;
  47. /**
  48. * ActivityPub Inbox Handler
  49. *
  50. * @copyright 2018-2019, 2021 Free Software Foundation, Inc http://www.fsf.org
  51. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  52. */
  53. class Inbox extends Controller
  54. {
  55. /**
  56. * Create an Inbox Handler to receive something from someone.
  57. */
  58. public function handle(?int $gsactor_id = null): TypeResponse
  59. {
  60. $error = function (string $m, ?Exception $e = null): TypeResponse {
  61. Log::error('ActivityPub Error Answer: ' . ($json = json_encode(['error' => $m, 'exception' => var_export($e, true)])));
  62. return new TypeResponse($json, 400);
  63. };
  64. $path = Router::url('activitypub_inbox', type: Router::ABSOLUTE_PATH);
  65. if (!\is_null($gsactor_id)) {
  66. try {
  67. $user = DB::findOneBy('local_user', ['id' => $gsactor_id]);
  68. $path = Router::url('activitypub_actor_inbox', ['gsactor_id' => $user->getId()], type: Router::ABSOLUTE_PATH);
  69. } catch (Exception $e) {
  70. throw new ClientException(_m('No such actor.'), 404, $e);
  71. }
  72. }
  73. Log::debug('ActivityPub Inbox: Received a POST request.');
  74. $body = (string) $this->request->getContent();
  75. Log::debug('ActivityPub Inbox: Request Body content: ' . $body);
  76. $type = Model::jsonToType($body);
  77. if ($type->has('actor') === false) {
  78. return $error('Actor not found in the request.');
  79. }
  80. try {
  81. $resource_parts = parse_url($type->get('actor'));
  82. if ($resource_parts['host'] !== $_ENV['SOCIAL_DOMAIN']) { // XXX: Common::config('site', 'server')) {
  83. $ap_actor = ActivitypubActor::fromUri($type->get('actor'));
  84. $actor = Actor::getById($ap_actor->getActorId());
  85. DB::flush();
  86. } else {
  87. throw new Exception('Only remote actors can use this endpoint.');
  88. }
  89. unset($resource_parts);
  90. } catch (Exception $e) {
  91. return $error('Invalid actor.', $e);
  92. }
  93. $activitypub_rsa = ActivitypubRsa::getByActor($actor);
  94. $actor_public_key = $activitypub_rsa->getPublicKey();
  95. $headers = $this->request->headers->all();
  96. Log::debug('ActivityPub Inbox: Request Headers: ' . var_export($headers, true));
  97. // Flattify headers
  98. foreach ($headers as $key => $val) {
  99. $headers[$key] = $val[0];
  100. }
  101. if (!isset($headers['signature'])) {
  102. Log::debug('ActivityPub Inbox: HTTP Signature: Missing Signature header.');
  103. return $error('Missing Signature header.');
  104. // TODO: support other methods beyond HTTP Signatures
  105. }
  106. // Extract the signature properties
  107. $signatureData = HTTPSignature::parseSignatureHeader($headers['signature']);
  108. Log::debug('ActivityPub Inbox: HTTP Signature Data: ' . print_r($signatureData, true));
  109. if (isset($signatureData['error'])) {
  110. Log::debug('ActivityPub Inbox: HTTP Signature: ' . json_encode($signatureData, \JSON_PRETTY_PRINT));
  111. return $error(json_encode($signatureData, \JSON_PRETTY_PRINT));
  112. }
  113. [$verified, /*$headers*/] = HTTPSignature::verify($actor_public_key, $signatureData, $headers, $path, $body);
  114. // If the signature fails verification the first time, update profile as it might have changed public key
  115. if ($verified !== 1) {
  116. try {
  117. $res = Explorer::get_remote_user_activity($ap_actor->getUri());
  118. if (\is_null($res)) {
  119. return $error('Invalid remote actor (null response).');
  120. }
  121. } catch (Exception $e) {
  122. return $error('Invalid remote actor.', $e);
  123. }
  124. try {
  125. ActivitypubActor::update_profile($ap_actor, $actor, $activitypub_rsa, $res);
  126. } catch (Exception $e) {
  127. return $error('Failed to updated remote actor information.', $e);
  128. }
  129. [$verified, /*$headers*/] = HTTPSignature::verify($actor_public_key, $signatureData, $headers, $path, $body);
  130. }
  131. // If it still failed despite profile update
  132. if ($verified !== 1) {
  133. Log::debug('ActivityPub Inbox: HTTP Signature: Invalid signature.');
  134. return $error('Invalid signature.');
  135. }
  136. // HTTP signature checked out, make sure the "actor" of the activity matches that of the signature
  137. Log::debug('ActivityPub Inbox: HTTP Signature: Authorised request. Will now start the inbox handler.');
  138. // TODO: Check if Actor has authority over payload
  139. // Store Activity
  140. $ap_act = Model\Activity::fromJson($type, ['source' => 'ActivityPub']);
  141. FreeNetworkActorProtocol::protocolSucceeded(
  142. 'activitypub',
  143. $ap_actor->getActorId(),
  144. Discovery::normalize($actor->getNickname() . '@' . parse_url($ap_actor->getInboxUri(), PHP_URL_HOST)),
  145. );
  146. DB::flush();
  147. dd($ap_act, $act = $ap_act->getActivity(), $act->getActor(), $act->getObject());
  148. return new TypeResponse($type, status: 202);
  149. }
  150. }