DiditWebhookTest.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. <?php
  2. namespace Tests\Feature;
  3. use App\Enums\ApprovalStatusEnum;
  4. use App\Enums\IdentityVerificationStatusEnum;
  5. use App\Enums\UserTypeEnum;
  6. use App\Models\IdentityVerification;
  7. use App\Models\Provider;
  8. use App\Models\User;
  9. use App\Models\Webhook;
  10. use App\Services\PushNotificationService;
  11. use Illuminate\Foundation\Testing\RefreshDatabase;
  12. use Illuminate\Support\Facades\Mail;
  13. use Tests\TestCase;
  14. /**
  15. * Exercita o webhook do Didit ponta a ponta usando os payloads reais capturados
  16. * nas sessoes de homologacao (tests/Fixtures/didit).
  17. */
  18. class DiditWebhookTest extends TestCase
  19. {
  20. use RefreshDatabase;
  21. private const SECRET = 'segredo-de-teste-do-webhook';
  22. protected function setUp(): void
  23. {
  24. parent::setUp();
  25. Mail::fake();
  26. $this->mock(PushNotificationService::class)->shouldReceive('sendToUser')->andReturnNull();
  27. config([
  28. 'services.didit.webhook_secret' => self::SECRET,
  29. 'services.didit.max_attempts' => 3,
  30. 'services.didit.liveness_min_score' => 80,
  31. 'services.didit.face_match_min_score' => 85,
  32. ]);
  33. }
  34. public function test_assinatura_valida_e_aceita(): void
  35. {
  36. $this->postWebhook($this->payload('decision_approved_cin.json', $this->makeProvider()->user_id))
  37. ->assertOk();
  38. }
  39. public function test_assinatura_invalida_e_rejeitada(): void
  40. {
  41. $payload = $this->payload('decision_approved_cin.json', $this->makeProvider()->user_id);
  42. $this->postJson('/api/webhooks/didit', $payload, [
  43. 'X-Timestamp' => (string) time(),
  44. 'X-Signature-V2' => str_repeat('a', 64),
  45. ])->assertStatus(401);
  46. }
  47. public function test_timestamp_fora_da_janela_e_rejeitado(): void
  48. {
  49. $payload = $this->payload('decision_approved_cin.json', $this->makeProvider()->user_id);
  50. $this->postJson('/api/webhooks/didit', $payload, [
  51. 'X-Timestamp' => (string) (time() - 3600),
  52. 'X-Signature-V2' => $this->sign($payload),
  53. ])->assertStatus(401);
  54. }
  55. /** O secret pode conter varios valores (producao, dev, sandbox) separados por virgula. */
  56. public function test_aceita_qualquer_um_dos_secrets_configurados(): void
  57. {
  58. config(['services.didit.webhook_secret' => 'outro-secret,'.self::SECRET]);
  59. $this->postWebhook($this->payload('decision_approved_cin.json', $this->makeProvider()->user_id))
  60. ->assertOk();
  61. }
  62. public function test_evento_repetido_e_ignorado(): void
  63. {
  64. $provider = $this->makeProvider();
  65. $payload = $this->payload('decision_approved_cin.json', $provider->user_id);
  66. $this->postWebhook($payload)->assertOk();
  67. $this->postWebhook($payload)->assertOk();
  68. $this->assertSame(1, Webhook::where('provider', 'didit')->count());
  69. $this->assertSame(2, (int) Webhook::where('provider', 'didit')->first()->attempts_count);
  70. }
  71. /** Sessao limpa: OCR, liveness e face match aprovados, sem warning acionavel. */
  72. public function test_aprovado_sem_pendencia_aprova_o_prestador_automaticamente(): void
  73. {
  74. $provider = $this->makeProvider();
  75. $this->postWebhook($this->payload('decision_approved_cin.json', $provider->user_id))->assertOk();
  76. $provider->refresh();
  77. $this->assertSame(IdentityVerificationStatusEnum::APPROVED, $provider->identity_verification_status);
  78. $this->assertTrue($provider->document_verified);
  79. $this->assertNotNull($provider->identity_verified_at);
  80. $this->assertSame(ApprovalStatusEnum::ACCEPTED, $provider->approval_status);
  81. }
  82. /**
  83. * Warnings de duplicidade chegam com log_type = information e nao podem barrar
  84. * a aprovacao: eles aparecem em toda retentativa legitima.
  85. */
  86. public function test_warnings_informativos_nao_impedem_aprovacao(): void
  87. {
  88. $provider = $this->makeProvider();
  89. $this->postWebhook($this->payload('decision_approved_cnh.json', $provider->user_id))->assertOk();
  90. $verification = IdentityVerification::firstOrFail();
  91. $this->assertNotEmpty($verification->warnings);
  92. $this->assertEmpty($verification->actionableWarnings());
  93. $this->assertSame(
  94. IdentityVerificationStatusEnum::APPROVED,
  95. $provider->refresh()->identity_verification_status,
  96. );
  97. }
  98. /** CPF divergente: o Didit devolve In Review e o cadastro vai para a fila humana. */
  99. public function test_divergencia_de_cpf_vai_para_analise_manual(): void
  100. {
  101. $provider = $this->makeProvider();
  102. $this->postWebhook($this->payload('decision_in_review_cpf_mismatch.json', $provider->user_id))->assertOk();
  103. $provider->refresh();
  104. $this->assertSame(IdentityVerificationStatusEnum::IN_REVIEW, $provider->identity_verification_status);
  105. $this->assertFalse($provider->document_verified);
  106. $this->assertSame(ApprovalStatusEnum::PENDING, $provider->approval_status);
  107. $warnings = IdentityVerification::firstOrFail()->actionableWarnings();
  108. $this->assertContains(
  109. 'IDENTIFICATION_NUMBER_MISMATCH_WITH_PROVIDED',
  110. array_column($warnings, 'risk'),
  111. );
  112. }
  113. /** Tentativa e chance de ser avaliado: so a reprovacao do Didit consome uma. */
  114. public function test_reprovacao_consome_tentativa_e_criar_sessao_nao(): void
  115. {
  116. $provider = $this->makeProvider();
  117. $this->assertSame(0, (int) $provider->identity_verification_attempts);
  118. $this->postWebhook($this->declinedPayload($provider->user_id))->assertOk();
  119. $provider->refresh();
  120. $this->assertSame(1, (int) $provider->identity_verification_attempts);
  121. $this->assertSame(IdentityVerificationStatusEnum::DECLINED, $provider->identity_verification_status);
  122. }
  123. /** Esgotadas as tentativas, o caso deixa de ser "tente de novo" e vira analise humana. */
  124. public function test_ultima_reprovacao_manda_para_analise_humana(): void
  125. {
  126. $provider = $this->makeProvider();
  127. $provider->forceFill(['identity_verification_attempts' => 2])->save();
  128. $this->postWebhook($this->declinedPayload($provider->user_id))->assertOk();
  129. $provider->refresh();
  130. $this->assertSame(3, (int) $provider->identity_verification_attempts);
  131. $this->assertSame(IdentityVerificationStatusEnum::IN_REVIEW, $provider->identity_verification_status);
  132. }
  133. public function test_declined_marca_como_reprovado_sem_aprovar_cadastro(): void
  134. {
  135. $provider = $this->makeProvider();
  136. $payload = $this->payload('decision_approved_cin.json', $provider->user_id);
  137. $payload['status'] = 'Declined';
  138. $payload['decision']['status'] = 'Declined';
  139. $payload['decision']['id_verifications'][0]['status'] = 'Declined';
  140. $this->postWebhook($payload)->assertOk();
  141. $provider->refresh();
  142. $this->assertSame(IdentityVerificationStatusEnum::DECLINED, $provider->identity_verification_status);
  143. $this->assertSame(ApprovalStatusEnum::PENDING, $provider->approval_status);
  144. }
  145. /** Not Started e In Progress apenas acompanham o progresso, sem decidir nada. */
  146. public function test_status_intermediario_nao_decide_nada(): void
  147. {
  148. $provider = $this->makeProvider();
  149. $payload = [
  150. 'session_id' => 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',
  151. 'webhook_type' => 'status.updated',
  152. 'status' => 'In Progress',
  153. 'vendor_data' => (string) $provider->user_id,
  154. 'timestamp' => time(),
  155. ];
  156. $this->postWebhook($payload)->assertOk();
  157. $this->assertSame(
  158. IdentityVerificationStatusEnum::NOT_STARTED,
  159. $provider->refresh()->identity_verification_status,
  160. );
  161. $this->assertSame('In Progress', IdentityVerification::firstOrFail()->didit_status);
  162. }
  163. public function test_score_baixo_de_face_match_barra_a_aprovacao(): void
  164. {
  165. config(['services.didit.face_match_min_score' => 99]);
  166. $provider = $this->makeProvider();
  167. $this->postWebhook($this->payload('decision_approved_cin.json', $provider->user_id))->assertOk();
  168. $this->assertSame(
  169. IdentityVerificationStatusEnum::IN_REVIEW,
  170. $provider->refresh()->identity_verification_status,
  171. );
  172. }
  173. //
  174. private function declinedPayload(int $userId): array
  175. {
  176. $payload = $this->payload('decision_approved_cin.json', $userId);
  177. $payload['event_id'] = 'evt-declined-'.$userId;
  178. $payload['status'] = 'Declined';
  179. $payload['decision']['status'] = 'Declined';
  180. $payload['decision']['id_verifications'][0]['status'] = 'Declined';
  181. return $payload;
  182. }
  183. private function postWebhook(array $payload)
  184. {
  185. return $this->postJson('/api/webhooks/didit', $payload, [
  186. 'X-Timestamp' => (string) time(),
  187. 'X-Signature-V2' => $this->sign($payload),
  188. ]);
  189. }
  190. private function sign(array $payload): string
  191. {
  192. return hash_hmac('sha256', $this->canonical($payload), self::SECRET);
  193. }
  194. /** Mesma canonicalizacao do Didit: chaves ordenadas, unicode e barras sem escape. */
  195. private function canonical(array $payload): string
  196. {
  197. $decoded = json_decode(json_encode($payload), false);
  198. $sort = function ($value) use (&$sort) {
  199. if (is_array($value)) {
  200. return array_map($sort, $value);
  201. }
  202. if ($value instanceof \stdClass) {
  203. $data = get_object_vars($value);
  204. ksort($data, SORT_STRING);
  205. return (object) array_map($sort, $data);
  206. }
  207. if (is_float($value) && floor($value) === $value) {
  208. return (int) $value;
  209. }
  210. return $value;
  211. };
  212. return json_encode($sort($decoded), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  213. }
  214. private function payload(string $fixture, int $userId): array
  215. {
  216. $decision = json_decode(file_get_contents(base_path("tests/Fixtures/didit/{$fixture}")), true);
  217. return [
  218. 'event_id' => 'evt-'.$fixture,
  219. 'session_id' => $decision['session_id'] ?? '11111111-2222-3333-4444-555555555555',
  220. 'webhook_type' => 'status.updated',
  221. 'status' => $decision['status'],
  222. 'vendor_data' => (string) $userId,
  223. 'timestamp' => time(),
  224. 'decision' => $decision,
  225. ];
  226. }
  227. private function makeProvider(): Provider
  228. {
  229. $user = User::query()->create([
  230. 'name' => 'Prestador Teste',
  231. 'email' => 'prestador'.uniqid().'@teste.com',
  232. 'password' => 'secret',
  233. 'type' => UserTypeEnum::PROVIDER->value,
  234. ]);
  235. return Provider::query()->create([
  236. 'user_id' => $user->id,
  237. 'document' => '06767310905',
  238. 'birth_date' => '1990-01-01',
  239. 'approval_status' => ApprovalStatusEnum::PENDING->value,
  240. ]);
  241. }
  242. }