-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathFeatureContext.php
More file actions
538 lines (452 loc) Β· 17.8 KB
/
Copy pathFeatureContext.php
File metadata and controls
538 lines (452 loc) Β· 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
<?php
/**
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
require __DIR__ . '/../../vendor/autoload.php';
use Behat\Behat\Context\Context;
use Behat\Behat\Context\SnippetAcceptingContext;
use Behat\Gherkin\Node\TableNode;
use Behat\Hook\AfterScenario;
use Behat\Hook\BeforeScenario;
use Behat\Step\Given;
use Behat\Step\Then;
use Behat\Step\When;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Exception\ClientException;
use PHPUnit\Framework\Assert;
use Psr\Http\Message\ResponseInterface;
/**
* Defines application features from the specific context.
*/
class FeatureContext implements Context, SnippetAcceptingContext {
/** @var array[] */
protected $notificationIds;
/** @var int */
protected $deletedNotification;
/** @var string */
protected $currentUser;
/** @var ResponseInterface */
private $response = null;
/** @var CookieJar */
private $cookieJar;
/** @var string */
protected $baseUrl;
/** @var string */
protected $lastEtag;
/** @var resource */
protected $deviceKey;
/** @var string[] */
protected $appPasswords;
/** @var string */
protected $webPushPublicKey;
/** @var string */
protected $webPushAuth;
use CommandLineTrait;
/**
* FeatureContext constructor.
*/
public function __construct() {
$this->cookieJar = new CookieJar();
$this->baseUrl = getenv('TEST_SERVER_URL');
}
#[Given('/^user "([^"]*)" has notifications$/')]
public function hasNotifications(string $user) {
$response = $this->setTestingValue('POST', 'apps/notificationsintegrationtesting/notifications?userId=' . $user, null);
$this->assertStatusCode($response, 200);
}
#[Given('/^user "([^"]*)" receives notification with$/')]
public function receiveNotification(string $user, TableNode $formData) {
$response = $this->setTestingValue('POST', 'apps/notificationsintegrationtesting/notifications?userId=' . $user, $formData);
$this->assertStatusCode($response, 200);
}
#[Given('/^user "([^"]*)" sends admin notification to "([^"]*)" with$/')]
public function sendAdminNotification(string $sender, string $recipient, TableNode $formData) {
$currentUser = $this->currentUser;
$this->setCurrentUser($sender);
$this->sendingToWith('POST', '/apps/notifications/api/v2/admin_notifications/' . $recipient . '?format=json', $formData);
$this->assertStatusCode($this->response, 200);
$this->setCurrentUser($currentUser);
}
#[When('/^getting notifications on (v\d+)(| with different etag| with matching etag)$/')]
public function gettingNotifications(string $api, string $eTag) {
$headers = [];
if ($eTag === ' with different etag') {
$headers['If-None-Match'] = substr($this->lastEtag ?? '', 0, 16);
} elseif ($eTag === ' with matching etag') {
$headers['If-None-Match'] = $this->lastEtag ?? '';
}
$this->sendingToWith('GET', '/apps/notifications/api/' . $api . '/notifications?format=json', null, $headers);
$etagHeaders = $this->response->getHeader('ETag');
$this->lastEtag = array_pop($etagHeaders);
}
#[Then('/^response body is empty$/')]
public function checkResponseBodyIsEmpty() {
Assert::assertSame('', $this->response->getBody()->getContents());
}
#[Then('/^list of notifications has (\d+) entries$/')]
public function checkNumNotifications(int $numNotifications) {
$notifications = $this->getArrayOfNotificationsResponded($this->response);
Assert::assertCount((int)$numNotifications, $notifications);
$notificationIds = [];
foreach ($notifications as $notification) {
$notificationIds[] = (int)$notification['notification_id'];
}
$this->notificationIds[] = $notificationIds;
}
#[Then('/^confirms previously fetched notification ids exist on (v\d+)$/')]
public function checkNotificationsExists(string $api) {
$notificationIds = end($this->notificationIds);
$sendingWithGarbage = $notificationIds;
// An array instead of int
$sendingWithGarbage[] = $notificationIds;
// A string instead of int
$sendingWithGarbage[] = '$notificationIds';
// A duplicate
$sendingWithGarbage[] = reset($notificationIds);
$this->sendingToWith('POST', '/apps/notifications/api/' . $api . '/notifications/exists?format=json', [
'ids' => $sendingWithGarbage,
]);
$this->assertStatusCode($this->response, 200);
$actualIds = $this->getDataFromOCSResponse($this->response);
Assert::assertSame($notificationIds, $actualIds);
}
protected function getArrayOfNotificationsResponded(ResponseInterface $response): array {
return $this->getDataFromOCSResponse($response);
}
protected function getDataFromOCSResponse(ResponseInterface $response): array {
$jsonBody = json_decode($response->getBody()->getContents(), true);
return $jsonBody['ocs']['data'];
}
#[Then('/^user "([^"]*)" has (\d+) notifications on (v\d+)(| missing the last one| missing the first one)$/')]
public function userNumNotifications(string $user, int $numNotifications, string $api, string $missingLast) {
$this->sendingTo('GET', '/apps/notifications/api/' . $api . '/notifications?format=json');
$this->assertStatusCode($this->response, 200);
$previousNotificationIds = [];
if ($missingLast) {
Assert::assertNotEmpty($this->notificationIds);
$previousNotificationIds = end($this->notificationIds);
}
$this->checkNumNotifications((int)$numNotifications);
if ($missingLast) {
$now = end($this->notificationIds);
if ($missingLast === ' missing the last one') {
array_unshift($now, $this->deletedNotification);
} else {
$now[] = $this->deletedNotification;
}
Assert::assertEquals($previousNotificationIds, $now);
}
}
#[Then('/^(first|last) notification on (v\d+) matches$/')]
public function matchNotification(string $notification, string $api, ?TableNode $formData = null) {
$lastNotifications = end($this->notificationIds);
if ($notification === 'first') {
$notificationId = reset($lastNotifications);
} else { /* if ($notification === 'last')*/
$notificationId = end($lastNotifications);
}
$this->sendingTo('GET', '/apps/notifications/api/' . $api . '/notifications/' . $notificationId . '?format=json');
$this->assertStatusCode($this->response, 200);
$response = $this->getArrayOfNotificationsResponded($this->response);
foreach ($formData->getRowsHash() as $key => $value) {
Assert::assertArrayHasKey($key, $response);
Assert::assertEquals($value, $response[$key]);
}
}
#[Then('/^delete (first|last|same|faulty) notification on (v\d+)$/')]
public function deleteNotification(string $toDelete, string $api) {
Assert::assertNotEmpty($this->notificationIds);
$lastNotificationIds = end($this->notificationIds);
if ($toDelete === 'first') {
$this->deletedNotification = end($lastNotificationIds);
} elseif ($toDelete === 'last') {
$this->deletedNotification = reset($lastNotificationIds);
} elseif ($toDelete === 'faulty') {
$this->deletedNotification = 'faulty';
}
$this->sendingTo('DELETE', '/apps/notifications/api/' . $api . '/notifications/' . $this->deletedNotification);
}
#[Then('/^delete all notifications on (v\d+)$/')]
public function deleteAllNotification($api) {
Assert::assertNotEmpty($this->notificationIds);
$this->sendingTo('DELETE', '/apps/notifications/api/' . $api . '/notifications');
}
#[Then('/^user "([^"]*)" unregisters from push notifications/')]
public function unregisterForPushNotifications(string $user) {
$currentUser = $this->currentUser;
$this->setCurrentUser($user);
$this->sendingToWith('DELETE', '/apps/notifications/api/v2/push?format=json');
$this->setCurrentUser($currentUser);
}
#[Then('/^user "([^"]*)" registers for push notifications with$/')]
public function registerForPushNotifications(string $user, TableNode $formData) {
$data = $formData->getRowsHash();
if ($data['devicePublicKey'] === 'VALID_KEY') {
$config = [
'digest_alg' => 'sha512',
'private_key_bits' => 2048,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
];
$this->deviceKey = openssl_pkey_new($config);
$keyDetails = openssl_pkey_get_details($this->deviceKey);
$publicKey = $keyDetails['key'];
$data['devicePublicKey'] = $publicKey;
}
$currentUser = $this->currentUser;
$this->setCurrentUser($user);
$this->sendingToWith('POST', '/apps/notifications/api/v2/push?format=json', $data);
$this->setCurrentUser($currentUser);
}
#[Then('/^can validate the response and (skip verifying|verify) signature$/')]
public function validateResponseAndSignature(string $verify): void {
$response = $this->getArrayOfNotificationsResponded($this->response);
Assert::assertStringStartsWith('-----BEGIN PUBLIC KEY-----' . "\n", $response['publicKey']);
Assert::assertStringEndsWith('-----END PUBLIC KEY-----' . "\n", $response['publicKey']);
Assert::assertNotEmpty($response['deviceIdentifier'], 'Device identifier should not be empty');
Assert::assertNotEmpty($response['signature'], 'Signature should not be empty');
if ($verify === 'verify') {
$result = openssl_verify($response['deviceIdentifier'], base64_decode($response['signature']), $response['publicKey'], OPENSSL_ALGO_SHA512);
Assert::assertEquals(true, $result, 'Failed to verify the signature');
} else {
/**
* For some weird reason the push proxy's golang code needs the signature
* of the deviceIdentifier before the sha512 hashing. Assumption is that
* openssl_sign already does the sha512 internally.
* The problem is we can not revert the sha512 of the deviceIdentifier
*/
var_dump("\n\nEnjoy with care, signature was not verified!\n\n");
}
}
#[Then('/^user "([^"]*)" creates an app password$/')]
public function createAppPassword(string $user) {
$currentUser = $this->currentUser;
$this->setCurrentUser($user);
$this->sendingToWith('GET', '/core/getapppassword?format=json');
$this->setCurrentUser($currentUser);
$response = $this->getArrayOfNotificationsResponded($this->response);
Assert::assertNotEquals('', $response['apppassword']);
$this->appPasswords[$user] = $response['apppassword'];
}
#[Then('/^user "([^"]*)" forgets the app password$/')]
public function removeAppPassword(string $user) {
unset($this->appPasswords[$user]);
}
#[Then('/^error "([^"]*)" is expected with status code ([0-9]*)$/')]
public function expectedErrorOnLastRequest(string $error, int $statusCode) {
$this->assertStatusCode($this->response, $statusCode);
$response = $this->getArrayOfNotificationsResponded($this->response);
Assert::assertEquals($error, $response['message']);
}
#[Then('/^status code is ([0-9]*)$/')]
public function isStatusCode(int $statusCode) {
$this->assertStatusCode($this->response, $statusCode);
}
#[Given('/^webpush is enabled$/')]
public function enableWebPush() {
$this->runOcc(['config:app:set', 'notifications', 'webpush_enabled', '--value=1']);
}
#[Given('/^webpush is disabled$/')]
public function disableWebPush() {
$this->runOcc(['config:app:set', 'notifications', 'webpush_enabled', '--value=0']);
}
/**
* Generate a valid P256dh key and auth secret for WebPush testing
*/
protected function generateWebPushKeys(): void {
// Generate EC P-256 key pair
$key = openssl_pkey_new([
'curve_name' => 'prime256v1',
'private_key_type' => OPENSSL_KEYTYPE_EC,
]);
$details = openssl_pkey_get_details($key);
// Build uncompressed public key: 0x04 || x || y (65 bytes)
$x = str_pad($details['ec']['x'], 32, "\0", STR_PAD_LEFT);
$y = str_pad($details['ec']['y'], 32, "\0", STR_PAD_LEFT);
$uncompressed = "\x04" . $x . $y;
$this->webPushPublicKey = rtrim(strtr(base64_encode($uncompressed), '+/', '-_'), '=');
// Generate 16 bytes of random auth
$authBytes = random_bytes(16);
$this->webPushAuth = rtrim(strtr(base64_encode($authBytes), '+/', '-_'), '=');
}
#[When('/^user "([^"]*)" fetches the VAPID public key$/')]
public function fetchVapidPublicKey(string $user) {
$currentUser = $this->currentUser;
$this->setCurrentUser($user);
$this->sendingToWith('GET', '/apps/notifications/api/v2/webpush/vapid?format=json');
$this->setCurrentUser($currentUser);
}
#[Then('/^the VAPID key is not empty$/')]
public function vapidKeyIsNotEmpty() {
$response = $this->getDataFromOCSResponse($this->response);
Assert::assertNotEmpty($response['vapid'], 'VAPID public key should not be empty');
}
#[Given('/^user "([^"]*)" registers for webpush with$/')]
public function registerForWebPush(string $user, TableNode $formData) {
$data = $formData->getRowsHash();
if ($data['uaPublicKey'] === 'VALID_KEY' || $data['auth'] === 'VALID_AUTH') {
$this->generateWebPushKeys();
}
if ($data['uaPublicKey'] === 'VALID_KEY') {
$data['uaPublicKey'] = $this->webPushPublicKey;
}
if ($data['auth'] === 'VALID_AUTH') {
$data['auth'] = $this->webPushAuth;
}
$currentUser = $this->currentUser;
$this->setCurrentUser($user);
$this->sendingToWith('POST', '/apps/notifications/api/v2/webpush?format=json', $data);
$this->setCurrentUser($currentUser);
}
#[Given('/^user "([^"]*)" activates webpush with the activation token$/')]
public function activateWebPushWithDbToken(string $user) {
// Fetch activation token from the database via the testing helper
$currentUser = $this->currentUser;
$this->setCurrentUser('admin');
$this->sendingToWith('GET', '/apps/notificationsintegrationtesting/webpush/activation-token?format=json&userId=' . $user);
$this->setCurrentUser($user);
$this->assertStatusCode($this->response, 200);
$jsonBody = json_decode($this->response->getBody()->getContents(), true);
Assert::assertIsArray($jsonBody, 'Response body should be valid JSON');
$activationToken = $jsonBody['ocs']['data']['activationToken'] ?? '';
Assert::assertNotEmpty($activationToken, 'Activation token should not be empty');
$this->sendingToWith('POST', '/apps/notifications/api/v2/webpush/activate?format=json', [
'activationToken' => $activationToken,
]);
$this->setCurrentUser($currentUser);
}
#[Given('/^user "([^"]*)" activates webpush with token "([^"]*)"$/')]
public function activateWebPushWithToken(string $user, string $token) {
$currentUser = $this->currentUser;
$this->setCurrentUser($user);
$this->sendingToWith('POST', '/apps/notifications/api/v2/webpush/activate?format=json', [
'activationToken' => $token,
]);
$this->setCurrentUser($currentUser);
}
#[Given('/^user "([^"]*)" removes webpush subscription$/')]
public function removeWebPushSubscription(string $user) {
$currentUser = $this->currentUser;
$this->setCurrentUser($user);
$this->sendingToWith('DELETE', '/apps/notifications/api/v2/webpush?format=json');
$this->setCurrentUser($currentUser);
}
#[BeforeScenario]
#[AfterScenario]
public function clearNotifications() {
$response = $this->setTestingValue('DELETE', 'apps/notificationsintegrationtesting', null);
$this->assertStatusCode($response, 200);
}
protected function setTestingValue(string $verb, string $url, ?TableNode $body = null) {
$fullUrl = $this->baseUrl . 'ocs/v2.php/' . $url;
$client = new Client();
$options = [
'auth' => ['admin', 'admin'],
];
if ($body instanceof TableNode) {
$fd = $body->getRowsHash();
$options['form_params'] = $fd;
} elseif (is_array($body)) {
$options['form_params'] = $body;
}
try {
return $client->{$verb}($fullUrl, $options);
} catch (ClientException $ex) {
return $ex->getResponse();
}
}
/*
* User management
*/
#[Given('/^as user "([^"]*)"$/')]
public function setCurrentUser(string $user) {
$this->currentUser = $user;
}
#[Given('/^user "([^"]*)" exists$/')]
public function assureUserExists(string $user) {
try {
$this->userExists($user);
} catch (ClientException) {
$this->createUser($user);
}
$response = $this->userExists($user);
$this->assertStatusCode($response, 200);
}
private function userExists(string $user): ResponseInterface {
$client = new Client();
$options = [
'auth' => ['admin', 'admin'],
'headers' => [
'OCS-APIREQUEST' => 'true',
],
];
return $client->get($this->baseUrl . 'ocs/v2.php/cloud/users/' . $user, $options);
}
private function createUser(string $user) {
$previous_user = $this->currentUser;
$this->currentUser = 'admin';
$userProvisioningUrl = $this->baseUrl . 'ocs/v2.php/cloud/users';
$client = new Client();
$options = [
'auth' => ['admin', 'admin'],
'form_params' => [
'userid' => $user,
'password' => '123456'
],
'headers' => [
'OCS-APIREQUEST' => 'true',
],
];
$client->post($userProvisioningUrl, $options);
//Quick hack to login once with the current user
$options2 = [
'auth' => [$user, '123456'],
'headers' => [
'OCS-APIREQUEST' => 'true',
],
];
$client->get($userProvisioningUrl . '/' . $user, $options2);
$this->currentUser = $previous_user;
}
/*
* Requests
*/
#[When('/^sending "([^"]*)" to "([^"]*)"$/')]
public function sendingTo(string $verb, string $url) {
$this->sendingToWith($verb, $url, null);
}
/**
* @param TableNode|array|null $body
*/
#[When('/^sending "([^"]*)" to "([^"]*)" with$/')]
public function sendingToWith(string $verb, string $url, $body = null, array $headers = []) {
$fullUrl = $this->baseUrl . 'ocs/v2.php' . $url;
$client = new Client();
$options = [];
if (isset($this->appPasswords[$this->currentUser])) {
$options['auth'] = [$this->currentUser, $this->appPasswords[$this->currentUser]];
} elseif ($this->currentUser === 'admin') {
$options['auth'] = [$this->currentUser, 'admin'];
} else {
$options['auth'] = [$this->currentUser, '123456'];
}
if ($body instanceof TableNode) {
$fd = $body->getRowsHash();
$options['form_params'] = $fd;
} elseif (is_array($body)) {
$options['form_params'] = $body;
}
$options['headers'] = array_merge($headers, [
'OCS-APIREQUEST' => 'true',
]);
try {
$this->response = $client->request($verb, $fullUrl, $options);
} catch (ClientException $ex) {
$this->response = $ex->getResponse();
}
}
protected function assertStatusCode(ResponseInterface $response, int $statusCode) {
Assert::assertEquals($statusCode, $response->getStatusCode());
}
}