Loheide-eu-mitarbeiterplatt.../tests/Feature/Mobile/WebPushTest.php
Friederich Loheide b3e2b525e1
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 6m10s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Failing after 6m3s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 7m33s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 7m25s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 7m28s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 7m27s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 6m26s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 6m27s
CI / Bekannte Sicherheitslücken in Paketen (pull_request) Successful in 44s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m12s
Herzen, Reichweite und App-Anbindung (0.30.0)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 12:24:11 +00:00

132 lines
6.7 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace Tests\Feature\Mobile;
use App\Models\User;
use App\Notifications\PortalNotification;
use App\Push\ExpoPush;
use App\Push\PushSubscription;
use App\Push\SendWebPush;
use App\Push\WebPush;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;
class WebPushTest extends TestCase
{
use RefreshDatabase;
/**
* Schlüsselpaar eines „Browsers“ (User Agent) wie beim Abonnieren.
*
* @return array{0: \OpenSSLAsymmetricKey, 1: string, 2: string}
*/
private function browserKeys(): array
{
$key = openssl_pkey_new(['curve_name' => 'prime256v1', 'private_key_type' => OPENSSL_KEYTYPE_EC]);
return [$key, WebPush::base64UrlEncode(WebPush::rawPublicKey($key)), WebPush::base64UrlEncode(random_bytes(16))];
}
/** Entschlüsseln wie ein Browser (RFC 8291) */
private function decrypt(string $body, \OpenSSLAsymmetricKey $uaPrivate, string $uaPublic, string $auth): string
{
$salt = substr($body, 0, 16);
$idLength = ord($body[20]);
$asPublic = substr($body, 21, $idLength);
$cipher = substr($body, 21 + $idLength);
$shared = openssl_pkey_derive(WebPush::publicKeyFromRaw($asPublic), $uaPrivate, 32);
$ikm = hash_hkdf('sha256', $shared, 32, "WebPush: info\0".WebPush::base64UrlDecode($uaPublic).$asPublic, WebPush::base64UrlDecode($auth));
$cek = hash_hkdf('sha256', $ikm, 16, "Content-Encoding: aes128gcm\0", $salt);
$nonce = hash_hkdf('sha256', $ikm, 12, "Content-Encoding: nonce\0", $salt);
$plain = openssl_decrypt(substr($cipher, 0, -16), 'aes-128-gcm', $cek, OPENSSL_RAW_DATA, $nonce, substr($cipher, -16));
$this->assertNotFalse($plain, 'Entschlüsselung fehlgeschlagen');
return rtrim($plain, "\x00\x02");
}
public function test_payload_is_encrypted_per_rfc8291_and_signed_with_vapid(): void
{
[$uaPrivate, $uaPublic, $auth] = $this->browserKeys();
$user = User::factory()->create();
$subscription = PushSubscription::query()->create([
'user_id' => $user->id, 'endpoint' => 'https://fcm.googleapis.com/fcm/send/abc', 'endpoint_hash' => hash('sha256', 'x'),
'public_key' => $uaPublic, 'auth_token' => $auth,
]);
Http::fake(['fcm.googleapis.com/*' => Http::response('', 201)]);
$push = app(WebPush::class);
$this->assertTrue($push->send($subscription, ['title' => 'Freigabe', 'body' => 'Ümläute & mehr']));
Http::assertSent(function (Request $request) use ($uaPrivate, $uaPublic, $auth, $push) {
$this->assertSame('aes128gcm', $request->header('Content-Encoding')[0]);
$payload = json_decode($this->decrypt($request->body(), $uaPrivate, $uaPublic, $auth), true);
$this->assertSame('Ümläute & mehr', $payload['body']);
// VAPID: JWT mit ES256, prüfbar mit dem öffentlichen Schlüssel
preg_match('/^vapid t=([^,]+), k=(.+)$/', $request->header('Authorization')[0], $m);
$this->assertSame($push->publicKey(), $m[2]);
[$header, $claims, $signature] = explode('.', $m[1]);
$this->assertSame('https://fcm.googleapis.com', json_decode(WebPush::base64UrlDecode($claims), true)['aud']);
$raw = WebPush::base64UrlDecode($signature);
$int = fn (string $v) => "\x02".chr(strlen($v = ltrim($v, "\0")) + (ord($v[0]) > 0x7F ? 1 : 0)).(ord($v[0]) > 0x7F ? "\0" : '').$v;
$der = $int(substr($raw, 0, 32)).$int(substr($raw, 32));
$der = "\x30".chr(strlen($der)).$der;
$this->assertSame(1, openssl_verify($header.'.'.$claims, $der, WebPush::publicKeyFromRaw(WebPush::base64UrlDecode($m[2])), OPENSSL_ALGO_SHA256));
return true;
});
}
public function test_devices_subscribe_and_receive_portal_notifications(): void
{
Queue::fake();
[, $uaPublic, $auth] = $this->browserKeys();
$user = User::factory()->create();
$this->actingAs($user)->get('/')->assertInertia(fn ($page) => $page->where('push.key', app(WebPush::class)->publicKey()));
$this->postJson('/push/abo', ['endpoint' => 'http://unsicher.example.org/x', 'keys' => ['p256dh' => $uaPublic, 'auth' => $auth]])->assertUnprocessable();
// Nur bekannte Push-Dienste – keine internen Adressen (SSRF)
foreach (['https://10.0.0.5:8443/admin', 'https://127.0.0.1/x', 'https://fcm.googleapis.com.evil.test/x', 'https://evil.test/fcm.googleapis.com'] as $endpoint) {
$this->postJson('/push/abo', ['endpoint' => $endpoint, 'keys' => ['p256dh' => $uaPublic, 'auth' => $auth]])->assertStatus(422);
}
$this->postJson('/push/abo', ['endpoint' => 'https://fcm.googleapis.com/fcm/send/1', 'keys' => ['p256dh' => $uaPublic, 'auth' => $auth]])->assertOk();
$this->assertSame(1, PushSubscription::query()->where('user_id', $user->id)->count());
$user->notify(new PortalNotification('Beitrag freigegeben', '„Sommerfest“ ist online.', '/neuigkeiten/sommerfest'));
Queue::assertPushed(SendWebPush::class, fn (SendWebPush $job) => $job->userId === $user->id && $job->payload['url'] === '/neuigkeiten/sommerfest');
$this->deleteJson('/push/abo', ['endpoint' => 'https://fcm.googleapis.com/fcm/send/1'])->assertOk();
$this->assertSame(0, PushSubscription::query()->count());
// Ohne Abonnement: nur die Glocke
Queue::fake();
$user->notify(new PortalNotification('Noch einer'));
Queue::assertNotPushed(SendWebPush::class);
}
public function test_expired_subscriptions_are_removed(): void
{
[, $uaPublic, $auth] = $this->browserKeys();
$user = User::factory()->create();
PushSubscription::query()->create(['user_id' => $user->id, 'endpoint' => 'https://push.example.org/weg', 'endpoint_hash' => hash('sha256', 'weg'), 'public_key' => $uaPublic, 'auth_token' => $auth]);
Http::fake(['*' => Http::response('', 410)]);
(new SendWebPush($user->id, ['title' => 'x']))->handle(app(WebPush::class), app(ExpoPush::class));
$this->assertSame(0, PushSubscription::query()->count());
}
public function test_foreign_subscriptions_cannot_be_taken_over(): void
{
[, $uaPublic, $auth] = $this->browserKeys();
$endpoint = 'https://fcm.googleapis.com/fcm/send/geraet-1';
$this->actingAs(User::factory()->create())->postJson('/push/abo', ['endpoint' => $endpoint, 'keys' => ['p256dh' => $uaPublic, 'auth' => $auth]])->assertOk();
$this->actingAs(User::factory()->create())->postJson('/push/abo', ['endpoint' => $endpoint, 'keys' => ['p256dh' => $uaPublic, 'auth' => $auth]])->assertStatus(409);
}
}