Skip to content
Merged
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
17 changes: 7 additions & 10 deletions adm/style/wpn_acp.css
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,22 @@
gap: 14px;
}

.vapid-credentials-icon {
.vapid-credentials-icon,
.vapid-confirm-icon {
font-size: 18px;
background: #105289;
border-radius: 50%;
color: #ffffff;
display: flex;
flex: 0 0 42px;
justify-content: center;
align-items: center;
height: 42px;
}

.vapid-credentials-icon {
background: #105289;
color: #ffffff;
}

.vapid-credentials-summary {
flex: 1 1 auto;
}
Expand Down Expand Up @@ -201,15 +205,8 @@
}

.vapid-confirm-icon {
font-size: 18px;
background: #fff0c2;
border-radius: 50%;
color: #8a6500;
display: flex;
flex: 0 0 42px;
justify-content: center;
align-items: center;
height: 42px;
}

.vapid-confirm-message h3 {
Expand Down
2 changes: 1 addition & 1 deletion adm/style/wpn_acp_settings.html
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ <h3>{{ lang('WARNING') }}</h3>
<legend>{{ lang('GENERAL_SETTINGS') }}</legend>
<dl>
<dt><label>{{ lang('WEBPUSH_ENABLE') ~ lang('COLON') }}</label><br><span>{{ lang('WEBPUSH_ENABLE_EXPLAIN') }}</span></dt>
<dd><label><input type="radio" class="radio" name="config[wpn_webpush_enable]" value="1" {% if S_WEBPUSH_ENABLE %}checked="checked"{% endif %}> {{ lang('YES') }}</label>
<dd><label><input type="radio" class="radio" name="config[wpn_webpush_enable]" value="1"{% if S_WEBPUSH_ENABLE %} checked="checked"{% endif %}> {{ lang('YES') }}</label>
<label><input type="radio" class="radio" name="config[wpn_webpush_enable]" value="0"{% if not S_WEBPUSH_ENABLE %} checked="checked"{% endif %}> {{ lang('NO') }}</label></dd>
</dl>
<dl>
Expand Down
9 changes: 9 additions & 0 deletions controller/acp_controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,15 @@ protected function save_settings()
return;
}

// Store VAPID keys in the unpadded Base64URL form reported by browsers.
foreach (['wpn_webpush_vapid_public', 'wpn_webpush_vapid_private'] as $key_name)
{
if (isset($config_array[$key_name]))
{
$config_array[$key_name] = rtrim($config_array[$key_name], '=');
}
}

$this->log->add('admin', $this->user->data['user_id'], $this->user->ip, 'LOG_CONFIG_WEBPUSH');

foreach (array_keys($display_settings) as $config_name)
Expand Down
4 changes: 2 additions & 2 deletions language/en/webpushnotifications_module_acp.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
'WEBPUSH_ENABLE' => 'Enable Web Push',
'WEBPUSH_ENABLE_EXPLAIN' => 'Allow users to receive notifications in their browser or device via Web Push. To utilise Web Push, you must input or generate valid VAPID identification keys.',
'WEBPUSH_VAPID_CREDENTIALS' => 'VAPID credentials',
'WEBPUSH_VAPID_CREDENTIALS_EXPLAIN'=> 'These keys identify your board to push services. Generate a new key pair or enter an existing pair below.',
'WEBPUSH_VAPID_CREDENTIALS_EXPLAIN'=> 'Voluntary Application Server Identification (VAPID) keys identify your board to push services. Generate a new key pair or enter an existing pair below.',
'WEBPUSH_VAPID_KEYS_CONFIGURED'=> 'Keys configured',
'WEBPUSH_VAPID_KEYS_REQUIRED' => 'Setup required',
'WEBPUSH_VAPID_KEYS_PENDING' => 'Unsaved keys',
Expand All @@ -65,7 +65,7 @@
'WEBPUSH_HIDE_PRIVATE_KEY' => 'Hide private key',
'WEBPUSH_METHOD_ENABLED' => 'Enable user-based web push notifications by default',
'WEBPUSH_METHOD_ENABLED_EXPLAIN'=> 'When this setting is enabled, users who have also enabled and allowed browser notifications will start receiving them automatically. They can visit the UCP Notification settings to disable any unwanted notifications.<br><br>If this setting is disabled, users will not receive any notifications, even if they have enabled push notifications, until they visit the UCP Notification settings to allow the specific notifications they wish to receive.',
'WEBPUSH_DROPDOWN_SUBSCRIBE' => 'Show web push settings in the notification dropdown',
'WEBPUSH_DROPDOWN_SUBSCRIBE' => 'Show subscription toggle in notification dropdown',
'WEBPUSH_DROPDOWN_SUBSCRIBE_EXPLAIN'=> 'Show or hide the “Enable Web Push” toggle switch in the notification dropdown. This allows users to easily enable or disable push notifications from any page of the forum.',
'WEBPUSH_POPUP_PROMPT' => 'Show popup prompt for unsubscribed members',
'WEBPUSH_POPUP_PROMPT_EXPLAIN' => 'Display a popup message asking registered members if they want to receive push notifications. The popup will only appear to members who are not currently subscribed and have not previously denied.',
Expand Down
49 changes: 46 additions & 3 deletions notification/method/webpush.php
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ protected function notify_using_webpush(): void
// Load all the users we need
$notify_users = array_diff($user_ids, $banned_users);

// If we have no users (e.g. all recipients are banned) empty queue and exit
// Empty the queue and exit if there are no users (e.g. all recipients are banned).
if (empty($notify_users))
{
$this->empty_queue();
Expand Down Expand Up @@ -304,6 +304,7 @@ protected function notify_using_webpush(): void

// List to fill with expired subscriptions based on return
$expired_endpoints = [];
$delivery_failures = [];

try
{
Expand All @@ -321,8 +322,7 @@ protected function notify_using_webpush(): void
}
else
{
$report_data = json_sanitizer::sanitize($report->jsonSerialize());
$this->log->add('admin', ANONYMOUS, '', 'LOG_WEBPUSH_MESSAGE_FAIL', false, [$report_data['reason']]);
$this->add_delivery_failure($delivery_failures, $report);
}
}
}
Expand All @@ -332,6 +332,8 @@ protected function notify_using_webpush(): void
$this->log->add('critical', ANONYMOUS, '', 'LOG_WEBPUSH_MESSAGE_FAIL', false, [$exception->getMessage()]);
}

$this->log_delivery_failures($delivery_failures);

// We're done, empty the queue
$this->empty_queue();

Expand Down Expand Up @@ -596,4 +598,45 @@ protected function is_endpoint_permanently_removed(string $endpoint): bool
$host = parse_url($endpoint, PHP_URL_HOST);
return is_string($host) && substr($host, -strlen('.invalid')) === '.invalid';
}

/**
* Group a delivery failure by response category
*
* @param array $failures Grouped delivery failures
* @param \Minishlink\WebPush\MessageSentReport $report Failed delivery report
* @return void
*/
protected function add_delivery_failure(array &$failures, \Minishlink\WebPush\MessageSentReport $report): void
{
$response = $report->getResponse();
$category = $response ? 'http:' . $response->getStatusCode() : 'network';

if (!isset($failures[$category]))
{
$report_data = json_sanitizer::sanitize(['reason' => $report->getReason()]);
$failures[$category] = [
'count' => 0,
'reason' => (string) ($report_data['reason'] ?? ''),
];
}

$failures[$category]['count']++;
}

/**
* Log delivery failures once per response category
*
* @param array $failures Grouped delivery failures
* @return void
*/
protected function log_delivery_failures(array $failures): void
{
foreach ($failures as $failure)
{
$reason = $failure['count'] > 1
? $failure['count'] . ' × ' . $failure['reason']
: $failure['reason'];
$this->log->add('admin', ANONYMOUS, '', 'LOG_WEBPUSH_MESSAGE_FAIL', false, [$reason]);
}
}
}
1 change: 1 addition & 0 deletions subscription/validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public static function is_valid_vapid_keys(string $public_key, string $private_k
try
{
$vapid = VAPID::validate([
// Placeholder required by VAPID::validate(); delivery uses the configured board URL.
'subject' => 'https://example.com',
'publicKey' => $public_key,
'privateKey' => $private_key,
Expand Down
30 changes: 30 additions & 0 deletions tests/controller/controller_acp_test.php
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,36 @@ public function webpush_save_data(): array
],
true,
],
'padded VAPID keys are stored without padding' => [
array_merge($valid, [
'wpn_webpush_vapid_public' => self::VALID_VAPID_PUBLIC_KEY . '=',
'wpn_webpush_vapid_private' => self::VALID_VAPID_PRIVATE_KEY . '=',
]),
[
'S_ERROR' => false,
'ERROR_MSG' => '',
],
[
'wpn_webpush_vapid_public' => self::VALID_VAPID_PUBLIC_KEY,
'wpn_webpush_vapid_private' => self::VALID_VAPID_PRIVATE_KEY,
],
true,
],
'excessive VAPID key padding is rejected' => [
array_merge($valid, [
'wpn_webpush_vapid_public' => self::VALID_VAPID_PUBLIC_KEY . '==',
'wpn_webpush_vapid_private' => self::VALID_VAPID_PRIVATE_KEY . '=',
]),
[
'S_ERROR' => true,
'ERROR_MSG' => 'WEBPUSH_VAPID_KEYS_INVALID',
],
[
'wpn_webpush_vapid_public' => self::VALID_VAPID_PUBLIC_KEY,
'wpn_webpush_vapid_private' => self::VALID_VAPID_PRIVATE_KEY,
],
false,
],
'blank existing private key is preserved' => [
array_merge($valid, [
'wpn_webpush_vapid_private' => '',
Expand Down
39 changes: 39 additions & 0 deletions tests/controller/controller_webpush_test.php
Original file line number Diff line number Diff line change
Expand Up @@ -559,6 +559,45 @@ public function test_subscribe_replaces_previous_subscription()
], $subscriptions[0]);
}

public function test_subscribe_keeps_only_newest_subscriptions_for_current_user(): void
{
$subscriptions = [];
for ($i = 0; $i < 1021; $i++)
{
$subscriptions[] = [
'user_id' => 2,
'endpoint' => 'https://fcm.googleapis.com/fcm/send/old_' . $i,
'expiration_time' => 0,
'p256dh' => self::VALID_PUBLIC_KEY,
'auth' => self::VALID_AUTH_TOKEN,
];
}
for ($i = 0; $i < 3; $i++)
{
$subscriptions[] = [
'user_id' => 3,
'endpoint' => 'https://fcm.googleapis.com/fcm/send/other_' . $i,
'expiration_time' => 0,
'p256dh' => self::VALID_PUBLIC_KEY,
'auth' => self::VALID_AUTH_TOKEN,
];
}
$this->db->sql_multi_insert('phpbb_wpn_push_subscriptions', $subscriptions);

$endpoint = 'https://fcm.googleapis.com/fcm/send/newest';
$response = $this->controller->subscribe($this->create_subscription_request(json_encode([
'endpoint' => $endpoint,
'expiration_time' => 0,
'keys' => ['p256dh' => self::VALID_PUBLIC_KEY, 'auth' => self::VALID_AUTH_TOKEN],
])));

self::assertInstanceOf(JsonResponse::class, $response);
$user_subscriptions = $this->get_all_subscriptions(2);
self::assertCount(webpush::MAX_SUBSCRIPTIONS_PER_USER, $user_subscriptions);
self::assertContains($endpoint, array_column($user_subscriptions, 'endpoint'));
self::assertCount(3, $this->get_all_subscriptions(3));
}

public function test_subscribe_invalid_payload_preserves_existing_subscription()
{
$this->form_helper->method('check_form_tokens')->willReturn(true);
Expand Down
68 changes: 68 additions & 0 deletions tests/notification/webpush_branches_test.php
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,64 @@ public function test_invalid_vapid_config_logs_failure_without_throwing(): void
self::assertSame([], $method->get_queue());
}

public function test_delivery_failures_are_logged_once_per_category(): void
{
$log = $this->createMock(\phpbb\log\log_interface::class);
$log->expects(self::exactly(3))->method('add')->withConsecutive(
['admin', ANONYMOUS, '', 'LOG_WEBPUSH_MESSAGE_FAIL', false, ['3 × Unauthorized']],
['admin', ANONYMOUS, '', 'LOG_WEBPUSH_MESSAGE_FAIL', false, ['2 × Forbidden']],
['admin', ANONYMOUS, '', 'LOG_WEBPUSH_MESSAGE_FAIL', false, ['2 × DNS failure one']]
);
$method = $this->create_method($log);
$reports = [
$this->create_failed_report(401, 'Unauthorized'),
$this->create_failed_report(401, 'Unauthorized again'),
$this->create_failed_report(401, 'Unauthorized once more'),
$this->create_failed_report(403, 'Forbidden'),
$this->create_failed_report(403, 'Forbidden again'),
$this->create_failed_report(null, 'DNS failure one'),
$this->create_failed_report(null, 'DNS failure two'),
];

$method->log_delivery_failures_for_test($reports);
}

public function test_single_delivery_failure_keeps_original_reason(): void
{
$log = $this->createMock(\phpbb\log\log_interface::class);
$log->expects(self::once())->method('add')->with(
'admin',
ANONYMOUS,
'',
'LOG_WEBPUSH_MESSAGE_FAIL',
false,
['Too Many Requests']
);

$this->create_method($log)->log_delivery_failures_for_test([
$this->create_failed_report(429, 'Too Many Requests'),
]);
}

private function create_failed_report(?int $status_code, string $reason): \Minishlink\WebPush\MessageSentReport
{
$uri = $this->createMock(\Psr\Http\Message\UriInterface::class);
$uri->method('__toString')->willReturn('https://push.example.test/endpoint');
$body = $this->createMock(\Psr\Http\Message\StreamInterface::class);
$body->method('getContents')->willReturn('payload');
$request = $this->createMock(\Psr\Http\Message\RequestInterface::class);
$request->method('getUri')->willReturn($uri);
$request->method('getBody')->willReturn($body);
$response = null;
if ($status_code !== null)
{
$response = $this->createMock(\Psr\Http\Message\ResponseInterface::class);
$response->method('getStatusCode')->willReturn($status_code);
}

return new \Minishlink\WebPush\MessageSentReport($request, $response, false, $reason);
}

private function create_method($log = null, $user_loader = null, $assets_version = 1): testable_webpush
{
global $config, $phpbb_root_path, $phpEx, $user;
Expand Down Expand Up @@ -197,6 +255,16 @@ public function set_push_token($type_id, $item_id, $user_id, $token): void
$property->setValue($this, [$type_id => [$item_id => [$user_id => $token]]]);
}

public function log_delivery_failures_for_test(array $reports): void
{
$failures = [];
foreach ($reports as $report)
{
$this->add_delivery_failure($failures, $report);
}
$this->log_delivery_failures($failures);
}

protected function get_user_subscription_map(array $notify_users): array
{
return $this->subscriptions;
Expand Down
37 changes: 37 additions & 0 deletions ucp/controller/webpush.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ class webpush
/** @var string UCP form token name */
public const FORM_TOKEN_UCP = 'ucp_webpush';

/** @var int Maximum number of stored subscriptions per user */
public const MAX_SUBSCRIPTIONS_PER_USER = 20;

/** @var int Maximum number of surplus subscriptions removed per query */
private const SUBSCRIPTION_PRUNE_BATCH_SIZE = 100;

/** @var array Allowed push service endpoint hosts https://github.com/pushpad/known-push-services */
public const PUSH_SERVICE_WHITELIST = [
'android.googleapis.com',
Expand Down Expand Up @@ -430,12 +436,43 @@ public function subscribe(symfony_request $symfony_request): JsonResponse
$this->db->sql_query($sql);
}

$this->prune_user_subscriptions($this->user->id());

return new JsonResponse([
'success' => true,
'form_tokens' => $this->form_helper->get_form_tokens(self::FORM_TOKEN_UCP),
]);
}

/**
* Keep only the newest subscriptions for a user
*
* @param int $user_id User id
* @return void
*/
protected function prune_user_subscriptions(int $user_id): void
{
do
{
$sql = 'SELECT subscription_id
FROM ' . $this->push_subscriptions_table . '
WHERE user_id = ' . $user_id . '
ORDER BY subscription_id DESC';
$result = $this->db->sql_query_limit($sql, self::SUBSCRIPTION_PRUNE_BATCH_SIZE, self::MAX_SUBSCRIPTIONS_PER_USER);
$surplus = array_map('intval', array_column($this->db->sql_fetchrowset($result), 'subscription_id'));
$this->db->sql_freeresult($result);

if (!empty($surplus))
{
$sql = 'DELETE FROM ' . $this->push_subscriptions_table . '
WHERE user_id = ' . $user_id . '
AND ' . $this->db->sql_in_set('subscription_id', $surplus);
$this->db->sql_query($sql);
}
}
while (count($surplus) === self::SUBSCRIPTION_PRUNE_BATCH_SIZE);
}

/**
* Validate and normalize subscription data for database writes
*
Expand Down