TshieldWebhookController.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\TshieldWebhookModel;
  5. use Psr\Http\Message\ResponseInterface;
  6. use Psr\Http\Message\ServerRequestInterface;
  7. class TshieldWebhookController
  8. {
  9. private TshieldWebhookModel $model;
  10. private string $logFilePath;
  11. public function __construct()
  12. {
  13. $this->model = new TshieldWebhookModel();
  14. $this->logFilePath = $this->resolveLogFilePath($_ENV['TSHIELD_WEBHOOK_LOG_FILE'] ?? null);
  15. }
  16. public function __invoke(ServerRequestInterface $request)
  17. {
  18. $requestId = $this->generateRequestId();
  19. $rawBody = (string)$request->getBody();
  20. if ($rawBody === '') {
  21. $rawBody = (string)file_get_contents('php://input');
  22. }
  23. $this->logReceipt($request, $requestId, $rawBody);
  24. $body = json_decode($rawBody, true);
  25. try {
  26. if (!is_array($body)) {
  27. $response = ResponseLib::sendFail('Invalid JSON payload.', [], 'E_VALIDATE')->withStatus(400);
  28. $this->logWebhook($request, $requestId, $rawBody, null, $response, ['result' => 'invalid_json']);
  29. return $response;
  30. }
  31. $statusDescription = $body['status']['status'] ?? null;
  32. if ($statusDescription !== 'Aprovado') {
  33. $response = ResponseLib::sendOk([
  34. 'processed' => false,
  35. 'reason' => 'Status not approved. No action taken.',
  36. ], 'S_IGNORED');
  37. $this->logWebhook($request, $requestId, $rawBody, $body, $response, [
  38. 'result' => 'ignored',
  39. 'status_description' => $statusDescription,
  40. ]);
  41. return $response;
  42. }
  43. $externalNumber = $body['number'] ?? $body['token'] ?? null;
  44. if (!is_string($externalNumber) || trim($externalNumber) === '') {
  45. $response = ResponseLib::sendFail('Missing analysis number/token in payload.', [], 'E_VALIDATE')->withStatus(400);
  46. $this->logWebhook($request, $requestId, $rawBody, $body, $response, ['result' => 'missing_number']);
  47. return $response;
  48. }
  49. $updated = $this->model->approveByExternalId($externalNumber);
  50. if (!$updated) {
  51. $response = ResponseLib::sendFail(
  52. 'No user found for provided analysis number.',
  53. ['number' => $externalNumber],
  54. 'E_NOT_FOUND'
  55. )->withStatus(404);
  56. $this->logWebhook($request, $requestId, $rawBody, $body, $response, [
  57. 'result' => 'not_found',
  58. 'number' => $externalNumber,
  59. ]);
  60. return $response;
  61. }
  62. $response = ResponseLib::sendOk([
  63. 'processed' => true,
  64. 'number' => $externalNumber,
  65. ]);
  66. $this->logWebhook($request, $requestId, $rawBody, $body, $response, [
  67. 'result' => 'updated',
  68. 'number' => $externalNumber,
  69. ]);
  70. return $response;
  71. } catch (\Throwable $e) {
  72. $response = ResponseLib::sendFail('Webhook processing error.', [
  73. 'request_id' => $requestId,
  74. 'error' => $e->getMessage(),
  75. ], 'E_WEBHOOK')->withStatus(500);
  76. $this->logWebhook($request, $requestId, $rawBody, is_array($body) ? $body : null, $response, [
  77. 'result' => 'exception',
  78. 'exception' => [
  79. 'message' => $e->getMessage(),
  80. 'type' => get_class($e),
  81. ],
  82. ]);
  83. return $response;
  84. }
  85. }
  86. private function generateRequestId(): string
  87. {
  88. try {
  89. return bin2hex(random_bytes(16));
  90. } catch (\Throwable $e) {
  91. return uniqid('tshield_', true);
  92. }
  93. }
  94. private function logWebhook(
  95. ServerRequestInterface $request,
  96. string $requestId,
  97. string $rawBody,
  98. ?array $decodedBody,
  99. ResponseInterface $response,
  100. array $extra = []
  101. ): void {
  102. $ts = (new \DateTimeImmutable())->format('c');
  103. $serverParams = $request->getServerParams();
  104. $ip = $serverParams['REMOTE_ADDR'] ?? null;
  105. $method = $request->getMethod();
  106. $uri = (string)$request->getUri();
  107. $responseBody = $this->getResponseBodyForLog($response);
  108. $entry = [
  109. 'ts' => $ts,
  110. 'service' => 'tshield_webhook',
  111. 'request_id' => $requestId,
  112. 'method' => $method,
  113. 'uri' => $uri,
  114. 'ip' => $ip,
  115. 'log_file' => $this->logFilePath,
  116. 'request_raw' => $rawBody,
  117. 'request_json' => $decodedBody,
  118. 'response_status' => $response->getStatusCode(),
  119. 'response_body' => $responseBody,
  120. ];
  121. if (!empty($extra)) {
  122. $entry['context'] = $extra;
  123. }
  124. $encoded = json_encode($entry, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  125. if ($encoded === false) {
  126. $encoded = '{"ts":"' . $ts . '","service":"tshield_webhook","request_id":"' . $requestId . '","error":"unable_to_encode_log"}';
  127. }
  128. $this->appendLogLine($encoded);
  129. error_log('[TShieldWebhook] ' . $encoded);
  130. }
  131. private function logReceipt(ServerRequestInterface $request, string $requestId, string $rawBody): void
  132. {
  133. $ts = (new \DateTimeImmutable())->format('c');
  134. $serverParams = $request->getServerParams();
  135. $ip = $serverParams['REMOTE_ADDR'] ?? null;
  136. $method = $request->getMethod();
  137. $uri = (string)$request->getUri();
  138. $entry = [
  139. 'ts' => $ts,
  140. 'service' => 'tshield_webhook',
  141. 'event' => 'received',
  142. 'request_id' => $requestId,
  143. 'method' => $method,
  144. 'uri' => $uri,
  145. 'ip' => $ip,
  146. 'log_file' => $this->logFilePath,
  147. 'request_raw' => $rawBody,
  148. ];
  149. $encoded = json_encode($entry, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  150. if ($encoded === false) {
  151. $encoded = '{"ts":"' . $ts . '","service":"tshield_webhook","event":"received","request_id":"' . $requestId . '","error":"unable_to_encode_log"}';
  152. }
  153. $this->appendLogLine($encoded);
  154. error_log('[TShieldWebhook] ' . $encoded);
  155. }
  156. private function appendLogLine(string $encoded): bool
  157. {
  158. $phpError = null;
  159. $handler = function (int $severity, string $message) use (&$phpError): bool {
  160. $phpError = $message;
  161. return true;
  162. };
  163. set_error_handler($handler);
  164. try {
  165. $result = file_put_contents($this->logFilePath, $encoded . "\n", FILE_APPEND | LOCK_EX);
  166. } catch (\Throwable $e) {
  167. $result = false;
  168. $phpError = $phpError ?? ($e->getMessage());
  169. } finally {
  170. restore_error_handler();
  171. }
  172. if ($result === false) {
  173. error_log('[TShieldWebhook] failed_to_write_log file=' . $this->logFilePath . ' php_error=' . json_encode($phpError));
  174. return false;
  175. }
  176. return true;
  177. }
  178. private function getResponseBodyForLog(ResponseInterface $response): ?string
  179. {
  180. try {
  181. $stream = $response->getBody();
  182. if ($stream === null) {
  183. return null;
  184. }
  185. if (method_exists($stream, 'isSeekable') && $stream->isSeekable()) {
  186. $pos = $stream->tell();
  187. $stream->rewind();
  188. $contents = $stream->getContents();
  189. $stream->seek($pos);
  190. return $contents;
  191. }
  192. return (string)$stream;
  193. } catch (\Throwable $e) {
  194. return null;
  195. }
  196. }
  197. private function resolveLogFilePath(?string $path): string
  198. {
  199. $path = trim((string)$path);
  200. if ($path === '') {
  201. $path = 'tshield_webhook.txt';
  202. }
  203. if (!preg_match('/^(?:[A-Za-z]:\\\\|\\/)/', $path)) {
  204. $path = rtrim(dirname(__DIR__), '/\\') . DIRECTORY_SEPARATOR . $path;
  205. }
  206. $dir = dirname($path);
  207. if (!is_dir($dir)) {
  208. if (!@mkdir($dir, 0775, true) && !is_dir($dir)) {
  209. $lastError = error_get_last();
  210. error_log('[TShieldWebhook] failed_to_create_log_dir dir=' . $dir . ' error=' . json_encode($lastError));
  211. }
  212. }
  213. if (is_dir($dir) && !is_writable($dir)) {
  214. error_log('[TShieldWebhook] log_dir_not_writable dir=' . $dir);
  215. }
  216. if (!file_exists($path)) {
  217. $phpError = null;
  218. $handler = function (int $severity, string $message) use (&$phpError): bool {
  219. $phpError = $message;
  220. return true;
  221. };
  222. set_error_handler($handler);
  223. try {
  224. $created = (file_put_contents($path, '') !== false);
  225. } catch (\Throwable $e) {
  226. $created = false;
  227. $phpError = $phpError ?? ($e->getMessage());
  228. } finally {
  229. restore_error_handler();
  230. }
  231. if (!$created) {
  232. error_log('[TShieldWebhook] failed_to_create_log_file file=' . $path . ' php_error=' . json_encode($phpError));
  233. }
  234. } elseif (!is_writable($path)) {
  235. error_log('[TShieldWebhook] log_file_not_writable file=' . $path);
  236. }
  237. return $path;
  238. }
  239. }