Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: [BREAKING] remove legacy subscription; change subscription interface #394

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 16 additions & 30 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,66 +46,52 @@ A complete example with html+JS frontend and php backend using `web-push-php` ca

```php
<?php

use Minishlink\WebPush\WebPush;
use Minishlink\WebPush\Subscription;

// store the client-side `PushSubscription` object (calling `.toJSON` on it) as-is and then create a WebPush\Subscription from it
// Store the client-side `PushSubscription` object (calling `.toJSON` on it) as-is and then create a WebPush\Subscription from it.
$subscription = Subscription::create(json_decode($clientSidePushSubscriptionJSON, true));

// array of notifications
// Array of push messages.
$notifications = [
[
'subscription' => $subscription,
'payload' => '{"message":"Hello World!"}',
], [
// current PushSubscription format (browsers might change this in the future)
'subscription' => Subscription::create([
"endpoint" => "https://example.com/other/endpoint/of/another/vendor/abcdef...",
"keys" => [
'p256dh' => '(stringOf88Chars)',
'auth' => '(stringOf24Chars)'
],
]),
'payload' => '{"message":"Hello World!"}',
], [
// old Firefox PushSubscription format
'subscription' => Subscription::create([
'endpoint' => 'https://updates.push.services.mozilla.com/push/abc...', // Firefox 43+,
'publicKey' => 'BPcMbnWQL5GOYX/5LKZXT6sLmHiMsJSiEvIFvfcDvX7IZ9qqtq68onpTPEYmyxSQNiH7UD/98AUcQ12kBoxz/0s=', // base 64 encoded, should be 88 chars
'authToken' => 'CxVX6QsVToEGEcjfYPqXQw==', // base 64 encoded, should be 24 chars
]),
'payload' => 'hello !',
], [
// old Chrome PushSubscription format
'subscription' => Subscription::create([
'endpoint' => 'https://fcm.googleapis.com/fcm/send/abcdef...',
// current PushSubscription format (browsers might change this in the future)
'subscription' => Subscription::create([
'endpoint' => 'https://example.com/other/endpoint/of/another/vendor/abcdef...',
'keys' => [
'p256dh' => '(stringOf88Chars)',
'auth' => '(stringOf24Chars)',
],
// key 'contentEncoding' is optional and defaults to ContentEncoding::aes128gcm
]),
'payload' => null,
'payload' => '{"message":"Hello World!"}',
], [
// old PushSubscription format
'subscription' => Subscription::create([
'endpoint' => 'https://example.com/other/endpoint/of/another/vendor/abcdef...',
'publicKey' => '(stringOf88Chars)',
'authToken' => '(stringOf24Chars)',
'contentEncoding' => 'aesgcm', // one of PushManager.supportedContentEncodings
'contentEncoding' => 'aesgcm', // (optional) one of PushManager.supportedContentEncodings
]),
'payload' => '{"message":"test"}',
]
];

$webPush = new WebPush();

// send multiple notifications with payload
// Send multiple push messages with payload.
foreach ($notifications as $notification) {
$webPush->queueNotification(
$notification['subscription'],
$notification['payload'] // optional (defaults null)
$notification['payload'], // optional (defaults null)
);
}

/**
* Check sent results
* Check sent results.
* @var MessageSentReport $report
*/
foreach ($webPush->flush() as $report) {
Expand All @@ -119,7 +105,7 @@ foreach ($webPush->flush() as $report) {
}

/**
* send one notification and flush directly
* Send one push message and flush directly.
* @var MessageSentReport $report
*/
$report = $webPush->sendOneNotification(
Expand Down
11 changes: 11 additions & 0 deletions src/ContentEncoding.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace Minishlink\WebPush;

enum ContentEncoding: string
{
/** Outdated historic encoding. Was used by some browsers before rfc standard. Not recommended. */
case aesgcm = "aesgcm";
/** Defined in rfc8291. */
case aes128gcm = "aes128gcm";
}
60 changes: 35 additions & 25 deletions src/Encryption.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,19 @@ class Encryption
* @return string padded payload (plaintext)
* @throws \ErrorException
*/
public static function padPayload(string $payload, int $maxLengthToPad, string $contentEncoding): string
public static function padPayload(string $payload, int $maxLengthToPad, ContentEncoding $contentEncoding): string
{
$payloadLen = Utils::safeStrlen($payload);
$padLen = $maxLengthToPad ? $maxLengthToPad - $payloadLen : 0;

if ($contentEncoding === "aesgcm") {
if ($contentEncoding === ContentEncoding::aesgcm) {
return pack('n*', $padLen).str_pad($payload, $padLen + $payloadLen, chr(0), STR_PAD_LEFT);
}
if ($contentEncoding === "aes128gcm") {
if ($contentEncoding === ContentEncoding::aes128gcm) {
return str_pad($payload.chr(2), $padLen + $payloadLen, chr(0), STR_PAD_RIGHT);
}

throw new \ErrorException("This content encoding is not supported");
throw new \ErrorException("This content encoding is not implemented.");
}

/**
Expand All @@ -49,7 +49,7 @@ public static function padPayload(string $payload, int $maxLengthToPad, string $
*
* @throws \ErrorException
*/
public static function encrypt(string $payload, string $userPublicKey, string $userAuthToken, string $contentEncoding): array
public static function encrypt(string $payload, string $userPublicKey, string $userAuthToken, ContentEncoding $contentEncoding): array
{
return self::deterministicEncrypt(
$payload,
Expand All @@ -64,8 +64,14 @@ public static function encrypt(string $payload, string $userPublicKey, string $u
/**
* @throws \RuntimeException
*/
public static function deterministicEncrypt(string $payload, string $userPublicKey, string $userAuthToken, string $contentEncoding, array $localKeyObject, string $salt): array
{
public static function deterministicEncrypt(
string $payload,
string $userPublicKey,
string $userAuthToken,
ContentEncoding $contentEncoding,
array $localKeyObject,
string $salt
): array {
$userPublicKey = Base64UrlSafe::decodeNoPadding($userPublicKey);
$userAuthToken = Base64UrlSafe::decodeNoPadding($userAuthToken);

Expand Down Expand Up @@ -112,7 +118,7 @@ public static function deterministicEncrypt(string $payload, string $userPublicK
$context = self::createContext($userPublicKey, $localPublicKey, $contentEncoding);

// derive the Content Encryption Key
$contentEncryptionKeyInfo = self::createInfo($contentEncoding, $context, $contentEncoding);
$contentEncryptionKeyInfo = self::createInfo($contentEncoding->value, $context, $contentEncoding);
$contentEncryptionKey = self::hkdf($salt, $ikm, $contentEncryptionKeyInfo, 16);

// section 3.3, derive the nonce
Expand All @@ -132,16 +138,19 @@ public static function deterministicEncrypt(string $payload, string $userPublicK
];
}

public static function getContentCodingHeader(string $salt, string $localPublicKey, string $contentEncoding): string
public static function getContentCodingHeader(string $salt, string $localPublicKey, ContentEncoding $contentEncoding): string
{
if ($contentEncoding === "aes128gcm") {
if ($contentEncoding === ContentEncoding::aesgcm) {
return "";
}
if ($contentEncoding === ContentEncoding::aes128gcm) {
return $salt
.pack('N*', 4096)
.pack('C*', Utils::safeStrlen($localPublicKey))
.$localPublicKey;
}

return "";
throw new \ValueError("This content encoding is not implemented.");
}

/**
Expand Down Expand Up @@ -182,19 +191,19 @@ private static function hkdf(string $salt, string $ikm, string $info, int $lengt
*
* @throws \ErrorException
*/
private static function createContext(string $clientPublicKey, string $serverPublicKey, string $contentEncoding): ?string
private static function createContext(string $clientPublicKey, string $serverPublicKey, ContentEncoding $contentEncoding): ?string
{
if ($contentEncoding === "aes128gcm") {
if ($contentEncoding === ContentEncoding::aes128gcm) {
return null;
}

if (Utils::safeStrlen($clientPublicKey) !== 65) {
throw new \ErrorException('Invalid client public key length');
throw new \ErrorException('Invalid client public key length.');
}

// This one should never happen, because it's our code that generates the key
if (Utils::safeStrlen($serverPublicKey) !== 65) {
throw new \ErrorException('Invalid server public key length');
throw new \ErrorException('Invalid server public key length.');
}

$len = chr(0).'A'; // 65 as Uint16BE
Expand All @@ -212,25 +221,25 @@ private static function createContext(string $clientPublicKey, string $serverPub
*
* @throws \ErrorException
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could add @throws \ValueError here?

*/
private static function createInfo(string $type, ?string $context, string $contentEncoding): string
private static function createInfo(string $type, ?string $context, ContentEncoding $contentEncoding): string
{
if ($contentEncoding === "aesgcm") {
if ($contentEncoding === ContentEncoding::aesgcm) {
if (!$context) {
throw new \ErrorException('Context must exist');
throw new \ValueError('Context must exist.');
}

if (Utils::safeStrlen($context) !== 135) {
throw new \ErrorException('Context argument has invalid size');
throw new \ValueError('Context argument has invalid size.');
}

return 'Content-Encoding: '.$type.chr(0).'P-256'.$context;
}

if ($contentEncoding === "aes128gcm") {
if ($contentEncoding === ContentEncoding::aes128gcm) {
return 'Content-Encoding: '.$type.chr(0);
}

throw new \ErrorException('This content encoding is not supported.');
throw new \ErrorException('This content encoding is not implemented.');
}

private static function createLocalKeyObject(): array
Expand Down Expand Up @@ -262,17 +271,18 @@ private static function createLocalKeyObject(): array
/**
* @throws \ValueError
*/
private static function getIKM(string $userAuthToken, string $userPublicKey, string $localPublicKey, string $sharedSecret, string $contentEncoding): string
private static function getIKM(string $userAuthToken, string $userPublicKey, string $localPublicKey, string $sharedSecret, ContentEncoding $contentEncoding): string
{
if (empty($userAuthToken)) {
return $sharedSecret;
}
if($contentEncoding === "aesgcm") {

if ($contentEncoding === ContentEncoding::aesgcm) {
$info = 'Content-Encoding: auth'.chr(0);
} elseif($contentEncoding === "aes128gcm") {
} elseif ($contentEncoding === ContentEncoding::aes128gcm) {
$info = "WebPush: info".chr(0).$userPublicKey.$localPublicKey;
} else {
throw new \ValueError("This content encoding is not supported.");
throw new \ValueError("This content encoding is not implemented.");
}

return self::hkdf($userAuthToken, $sharedSecret, $info, 32);
Expand Down
71 changes: 32 additions & 39 deletions src/Subscription.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,22 +15,33 @@

class Subscription implements SubscriptionInterface
{
protected ContentEncoding $contentEncoding;
/**
* @param string|null $contentEncoding (Optional) Must be "aesgcm"
* This is a data class. No key validation is done.
* @param string|\Minishlink\WebPush\ContentEncoding $contentEncoding (Optional) defaults to "aes128gcm" as defined to rfc8291.
* @throws \ErrorException
*/
public function __construct(
private string $endpoint,
private ?string $publicKey = null,
private ?string $authToken = null,
private ?string $contentEncoding = null
protected readonly string $endpoint,
protected readonly string $publicKey,
protected readonly string $authToken,
ContentEncoding|string $contentEncoding = ContentEncoding::aes128gcm,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Extraneous space?

) {
if($publicKey || $authToken || $contentEncoding) {
$supportedContentEncodings = ['aesgcm', 'aes128gcm'];
if ($contentEncoding && !in_array($contentEncoding, $supportedContentEncodings, true)) {
throw new \ErrorException('This content encoding ('.$contentEncoding.') is not supported.');
if(is_string($contentEncoding)) {
try {
if(empty($contentEncoding)) {
$this->contentEncoding = ContentEncoding::aesgcm; // default
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't the default be aes128gcm?

} else {
$this->contentEncoding = ContentEncoding::from($contentEncoding);
}
} catch(\ValueError) {
throw new \ValueError('This content encoding ('.$contentEncoding.') is not supported.');
}
$this->contentEncoding = $contentEncoding ?: "aesgcm";
} else {
$this->contentEncoding = $contentEncoding;
}
if(empty($publicKey) || empty($authToken)) {
throw new \ValueError('Missing values.');
}
}

Expand All @@ -42,55 +53,37 @@ public static function create(array $associativeArray): self
{
if (array_key_exists('keys', $associativeArray) && is_array($associativeArray['keys'])) {
return new self(
$associativeArray['endpoint'],
$associativeArray['keys']['p256dh'] ?? null,
$associativeArray['keys']['auth'] ?? null,
$associativeArray['contentEncoding'] ?? "aesgcm"
);
}

if (array_key_exists('publicKey', $associativeArray) || array_key_exists('authToken', $associativeArray) || array_key_exists('contentEncoding', $associativeArray)) {
return new self(
$associativeArray['endpoint'],
$associativeArray['publicKey'] ?? null,
$associativeArray['authToken'] ?? null,
$associativeArray['contentEncoding'] ?? "aesgcm"
$associativeArray['endpoint'] ?? "",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

endpoint shouldn't be empty, it should throw before, shouldn't it?

$associativeArray['keys']['p256dh'] ?? "",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure this is an improvement, having an empty string instead of null ?

$associativeArray['keys']['auth'] ?? "",
$associativeArray['contentEncoding'] ?? ContentEncoding::aes128gcm,
);
}

return new self(
$associativeArray['endpoint']
$associativeArray['endpoint'] ?? "",
$associativeArray['publicKey'] ?? "",
$associativeArray['authToken'] ?? "",
$associativeArray['contentEncoding'] ?? ContentEncoding::aes128gcm,
);
}

/**
* {@inheritDoc}
*/
public function getEndpoint(): string
{
return $this->endpoint;
}

/**
* {@inheritDoc}
*/
public function getPublicKey(): ?string
public function getPublicKey(): string
{
return $this->publicKey;
}

/**
* {@inheritDoc}
*/
public function getAuthToken(): ?string
public function getAuthToken(): string
{
return $this->authToken;
}

/**
* {@inheritDoc}
*/
public function getContentEncoding(): ?string
public function getContentEncoding(): ContentEncoding
{
return $this->contentEncoding;
}
Expand Down
7 changes: 4 additions & 3 deletions src/SubscriptionInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,16 @@
namespace Minishlink\WebPush;

/**
* Subscription details from user agent.
* @author Sergii Bondarenko <[email protected]>
*/
interface SubscriptionInterface
{
public function getEndpoint(): string;

public function getPublicKey(): ?string;
public function getPublicKey(): string;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A subscription can have no public key, auth token or content encoding (sent without any payload)


public function getAuthToken(): ?string;
public function getAuthToken(): string;

public function getContentEncoding(): ?string;
public function getContentEncoding(): ContentEncoding;
}
Loading