BlueGit

projects-timfalken-com microchess

Files

microchess / web / tests / push.php

push.php

push.php 5.1 KiB Download Raw
1<?php
2// Isolated database and real Web Push encryption, with an in-memory HTTP transport.
3declare(strict_types=1);
4$root=sys_get_temp_dir().'/microchess-push-'.bin2hex(random_bytes(6));
5mkdir($root.'/data',0700,true);mkdir($root.'/lib');mkdir($root.'/assets/avatars',0700,true);
6foreach (['bootstrap.php','Chess.php','MoveFeedback.php','Push.php','PieceColors.php'] as $file) copy(__DIR__.'/../lib/'.$file,$root.'/lib/'.$file);
7symlink(realpath(__DIR__.'/../lib/push'),$root.'/lib/push');
8copy(__DIR__.'/../assets/avatars/catalog.json',$root.'/assets/avatars/catalog.json');
9$_SERVER+=['HTTP_HOST'=>'localhost','REMOTE_ADDR'=>'127.0.0.1','SCRIPT_NAME'=>'/microchess/api.php'];
10require $root.'/lib/bootstrap.php';
11use Minishlink\WebPush\WebPush;
12use Minishlink\WebPush\VAPID;
13use GuzzleHttp\Handler\MockHandler;
14use GuzzleHttp\HandlerStack;
15use GuzzleHttp\Middleware;
16use GuzzleHttp\Psr7\Response;
17$checks=0;
18function check(bool $value,string $label): void {global $checks;$checks++;if (!$value) throw new RuntimeException($label);}
19try {
20 $keys=pushKeys();
21 check($keys===json_decode(file_get_contents($root.'/data/push-keys.json'),true),'Persistent VAPID keys');
22 check(strlen(base64_decode(strtr($keys['publicKey'],'-_','+/')))===65,'P-256 VAPID public key');
23 $u='local:test_user_1';$v='local:test_user_2';loginUser($v,'test_user_2');
24 $device=VAPID::createVapidKeys();
25 $sub=['endpoint'=>'https://fcm.googleapis.com/fcm/send/test-device','keys'=>['p256dh'=>$device['publicKey'],'auth'=>rtrim(strtr(base64_encode(random_bytes(16)),'+/','-_'),'=')]];
26 pushSubscribe($u,['subscription'=>$sub]);pushSubscribe($u,['subscription'=>$sub]);
27 check((int)query('SELECT COUNT(*) FROM push_subscriptions')->fetchColumn()===1,'Subscriptions are idempotent');
28 pushUnsubscribe($v,$sub['endpoint']);
29 check((int)query('SELECT COUNT(*) FROM push_subscriptions')->fetchColumn()===1,'Other account cannot unsubscribe device');
30 foreach (['http://fcm.googleapis.com/test','https://127.0.0.1/test','https://fcm.googleapis.com.evil.example/test','https://fcm.googleapis.com:443/test','https://user@fcm.googleapis.com/test'] as $bad) {
31 try {pushEndpoint($bad);check(false,'Reject unsafe endpoint');} catch (DomainException) {$checks++;}
32 }
33 $bad=$sub;$bad['keys']['p256dh']='BA'.str_repeat('A',85);
34 try {pushSubscribe($u,['subscription'=>$bad]);check(false,'Reject invalid curve point');} catch (DomainException) {$checks++;}
35 $id=startGame($u,$v);query('UPDATE games SET white=? WHERE id=?',[$v,$id]);
36 $GLOBALS['push_events']=[];pushGame($id);
37 $events=$GLOBALS['push_events'];
38 check(count($events)===1 && array_values($events)[0]['user']===$v,'Notify player whose turn starts');
39 pushSubscribe($v,['subscription'=>$sub]);
40 check(query('SELECT user_id FROM push_subscriptions')->fetchColumn()===$v,'Subscription follows account on same device');
41 $history=[];$mock=new MockHandler([new Response(201),new Response(410)]);
42 $handler=HandlerStack::create($mock);$handler->push(Middleware::history($history));
43 $sender=new WebPush(['VAPID'=>['subject'=>'https://example.com','publicKey'=>$keys['publicKey'],'privateKey'=>$keys['privateKey']]],[],5,['handler'=>$handler]);
44 pushDeliver($events,$sender);
45 check(count($history)===1,'Sends through HTTP transport');
46 $request=$history[0]['request'];
47 check($request->getHeaderLine('Content-Encoding')==='aes128gcm','Encrypted notification payload');
48 check(str_starts_with($request->getHeaderLine('Authorization'),'vapid '),'VAPID authenticated notification');
49 check($request->getHeaderLine('Topic')==='game-'.$id,'Coalesce each game');
50 check(!str_contains((string)$request->getBody(),'Your turn'),'No plaintext payload');
51 query('UPDATE games SET version=version+1 WHERE id=?',[$id]);
52 pushDeliver($events,$sender);check(count($history)===1,'Skip superseded event');
53 $GLOBALS['push_events']=[];pushGame($id);pushDeliver($GLOBALS['push_events'],$sender);
54 check((int)query('SELECT COUNT(*) FROM push_subscriptions')->fetchColumn()===0,'Remove expired subscriptions');
55 $GLOBALS['push_events']=[];query("UPDATE games SET status='ended' WHERE id=?",[$id]);pushGame($id);
56 check(!$GLOBALS['push_events'],'No turn notification after game ends');
57 // Rendering a production login page preserves both invitation and notification targets.
58 $_GET=['game'=>'42','invite'=>str_repeat('a',48)];unset($_SESSION['user']);
59 $index=str_replace("require __DIR__.'/lib/bootstrap.php';",'',file_get_contents(__DIR__.'/../index.php'));
60 file_put_contents($root.'/index.php',$index);
61 ob_start();require $root.'/index.php';$html=ob_get_clean();
62 check(str_contains($html,'game=42'),'Sign-in link preserves notification game');
63 echo "Push: $checks checks passed.\n";
64} finally {
65 session_write_close();
66 // Only remove this test's randomly named fixture; do not traverse vendor symlink.
67 $files=new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root,FilesystemIterator::SKIP_DOTS),RecursiveIteratorIterator::CHILD_FIRST);
68 foreach ($files as $file) {if ($file->isDir()&&!$file->isLink()) rmdir($file->getPathname());else unlink($file->getPathname());}
69 rmdir($root);
70}