]> BookStack Code Mirror - bookstack/blob - tests/Actions/WebhookCallTest.php
Updated readme attribution and fixed eslint issues
[bookstack] / tests / Actions / WebhookCallTest.php
1 <?php
2
3 namespace Tests\Actions;
4
5 use BookStack\Activity\ActivityType;
6 use BookStack\Activity\DispatchWebhookJob;
7 use BookStack\Activity\Models\Webhook;
8 use BookStack\Activity\Tools\ActivityLogger;
9 use BookStack\Api\ApiToken;
10 use BookStack\Entities\Models\PageRevision;
11 use BookStack\Users\Models\User;
12 use Illuminate\Http\Client\Request;
13 use Illuminate\Support\Facades\Bus;
14 use Illuminate\Support\Facades\Http;
15 use Tests\TestCase;
16
17 class WebhookCallTest extends TestCase
18 {
19     public function test_webhook_listening_to_all_called_on_event()
20     {
21         $this->newWebhook([], ['all']);
22         Bus::fake();
23         $this->runEvent(ActivityType::ROLE_CREATE);
24         Bus::assertDispatched(DispatchWebhookJob::class);
25     }
26
27     public function test_webhook_listening_to_specific_event_called_on_event()
28     {
29         $this->newWebhook([], [ActivityType::ROLE_UPDATE]);
30         Bus::fake();
31         $this->runEvent(ActivityType::ROLE_UPDATE);
32         Bus::assertDispatched(DispatchWebhookJob::class);
33     }
34
35     public function test_webhook_listening_to_specific_event_not_called_on_other_event()
36     {
37         $this->newWebhook([], [ActivityType::ROLE_UPDATE]);
38         Bus::fake();
39         $this->runEvent(ActivityType::ROLE_CREATE);
40         Bus::assertNotDispatched(DispatchWebhookJob::class);
41     }
42
43     public function test_inactive_webhook_not_called_on_event()
44     {
45         $this->newWebhook(['active' => false], ['all']);
46         Bus::fake();
47         $this->runEvent(ActivityType::ROLE_CREATE);
48         Bus::assertNotDispatched(DispatchWebhookJob::class);
49     }
50
51     public function test_webhook_runs_for_delete_actions()
52     {
53         $this->newWebhook(['active' => true, 'endpoint' => 'https://wh.example.com'], ['all']);
54         Http::fake([
55             '*' => Http::response('', 500),
56         ]);
57
58         $user = $this->users->newUser();
59         $resp = $this->asAdmin()->delete($user->getEditUrl());
60         $resp->assertRedirect('/settings/users');
61
62         /** @var ApiToken $apiToken */
63         $editor = $this->users->editor();
64         $apiToken = ApiToken::factory()->create(['user_id' => $editor]);
65         $resp = $this->delete($editor->getEditUrl('/api-tokens/' . $apiToken->id));
66         $resp->assertRedirect($editor->getEditUrl('#api_tokens'));
67     }
68
69     public function test_failed_webhook_call_logs_error()
70     {
71         $logger = $this->withTestLogger();
72         Http::fake([
73             '*' => Http::response('', 500),
74         ]);
75         $webhook = $this->newWebhook(['active' => true, 'endpoint' => 'https://wh.example.com'], ['all']);
76         $this->assertNull($webhook->last_errored_at);
77
78         $this->runEvent(ActivityType::ROLE_CREATE);
79
80         $this->assertTrue($logger->hasError('Webhook call to endpoint https://wh.example.com failed with status 500'));
81
82         $webhook->refresh();
83         $this->assertEquals('Response status from endpoint was 500', $webhook->last_error);
84         $this->assertNotNull($webhook->last_errored_at);
85     }
86
87     public function test_webhook_call_exception_is_caught_and_logged()
88     {
89         Http::shouldReceive('asJson')->andThrow(new \Exception('Failed to perform request'));
90
91         $logger = $this->withTestLogger();
92         $webhook = $this->newWebhook(['active' => true, 'endpoint' => 'https://wh.example.com'], ['all']);
93         $this->assertNull($webhook->last_errored_at);
94
95         $this->runEvent(ActivityType::ROLE_CREATE);
96
97         $this->assertTrue($logger->hasError('Webhook call to endpoint https://wh.example.com failed with error "Failed to perform request"'));
98
99         $webhook->refresh();
100         $this->assertEquals('Failed to perform request', $webhook->last_error);
101         $this->assertNotNull($webhook->last_errored_at);
102     }
103
104     public function test_webhook_call_data_format()
105     {
106         Http::fake([
107             '*' => Http::response('', 200),
108         ]);
109         $webhook = $this->newWebhook(['active' => true, 'endpoint' => 'https://wh.example.com'], ['all']);
110         $page = $this->entities->page();
111         $editor = $this->users->editor();
112
113         $this->runEvent(ActivityType::PAGE_UPDATE, $page, $editor);
114
115         Http::assertSent(function (Request $request) use ($editor, $page, $webhook) {
116             $reqData = $request->data();
117
118             return $request->isJson()
119                 && $reqData['event'] === 'page_update'
120                 && $reqData['text'] === ($editor->name . ' updated page "' . $page->name . '"')
121                 && is_string($reqData['triggered_at'])
122                 && $reqData['triggered_by']['name'] === $editor->name
123                 && $reqData['triggered_by_profile_url'] === $editor->getProfileUrl()
124                 && $reqData['webhook_id'] === $webhook->id
125                 && $reqData['webhook_name'] === $webhook->name
126                 && $reqData['url'] === $page->getUrl()
127                 && $reqData['related_item']['name'] === $page->name;
128         });
129     }
130
131     protected function runEvent(string $event, $detail = '', ?User $user = null)
132     {
133         if (is_null($user)) {
134             $user = $this->users->editor();
135         }
136
137         $this->actingAs($user);
138
139         $activityLogger = $this->app->make(ActivityLogger::class);
140         $activityLogger->add($event, $detail);
141     }
142
143     protected function newWebhook(array $attrs, array $events): Webhook
144     {
145         /** @var Webhook $webhook */
146         $webhook = Webhook::factory()->create($attrs);
147
148         foreach ($events as $event) {
149             $webhook->trackedEvents()->create(['event' => $event]);
150         }
151
152         return $webhook;
153     }
154 }