FIX: Delete invalid web push subscriptions (#12447)

The endpoint as well as the public and private ECDH keys are required to successfully send a push notification.
This commit is contained in:
Gerhard Schlager 2021-03-19 14:24:03 +01:00 committed by GitHub
parent d470e4fade
commit 2d1b087efc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 41 additions and 3 deletions

View File

@ -77,12 +77,21 @@ class PushNotificationPusher
end
def self.send_notification(user, subscription, message)
endpoint = subscription["endpoint"]
p256dh = subscription.dig("keys", "p256dh")
auth = subscription.dig("keys", "auth")
if (endpoint.blank? || p256dh.blank? || auth.blank?)
unsubscribe(user, subscription)
return
end
begin
Webpush.payload_send(
endpoint: subscription["endpoint"],
endpoint: endpoint,
message: message.to_json,
p256dh: subscription.dig("keys", "p256dh"),
auth: subscription.dig("keys", "auth"),
p256dh: p256dh,
auth: auth,
vapid: {
subject: Discourse.base_url,
public_key: SiteSetting.vapid_public_key,

View File

@ -42,4 +42,33 @@ RSpec.describe PushNotificationPusher do
})
end
it "deletes invalid subscriptions during send" do
user = Fabricate(:walter_white)
missing_endpoint = PushSubscription.create!(user_id: user.id, data:
{ p256dh: "public ECDH key", keys: { auth: "private ECDH key" } }.to_json)
missing_p256dh = PushSubscription.create!(user_id: user.id, data:
{ endpoint: "endpoint 1", keys: { auth: "private ECDH key" } }.to_json)
missing_auth = PushSubscription.create!(user_id: user.id, data:
{ endpoint: "endpoint 2", keys: { p256dh: "public ECDH key" } }.to_json)
valid_subscription = PushSubscription.create!(user_id: user.id, data:
{ endpoint: "endpoint 3", keys: { p256dh: "public ECDH key", auth: "private ECDH key" } }.to_json)
expect(PushSubscription.where(user_id: user.id)).to contain_exactly(missing_endpoint, missing_p256dh, missing_auth, valid_subscription)
Webpush.expects(:payload_send).with(has_entries(endpoint: "endpoint 3", p256dh: "public ECDH key", auth: "private ECDH key")).once
PushNotificationPusher.push(user, {
topic_title: 'Topic',
username: 'system',
excerpt: 'description',
topic_id: 1,
post_url: "https://example.com/t/1/2",
notification_type: 1
})
expect(PushSubscription.where(user_id: user.id)).to contain_exactly(valid_subscription)
end
end