-
-
Notifications
You must be signed in to change notification settings - Fork 47
Add direct-APNs sender for WidgetKit push subscriptions #337
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
Open
hariharanjagan
wants to merge
7
commits into
home-assistant:main
Choose a base branch
from
hariharanjagan:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
64c3b2a
Add direct-APNs sender for WidgetKit push subscriptions
hariharanjagan 74d08fd
Merge pull request #1 from hariharanjagan/feature/widget-push
hariharanjagan 2af7e87
Rate-limit widget pushes per token
hariharanjagan 044ba1b
Give widget pushes their own daily rate-limit cap
hariharanjagan eb559b9
Merge pull request #2 from hariharanjagan/feature/widget-push
hariharanjagan 3fa81bb
Harden widget push: validate token/app id and close APNs client on er…
hariharanjagan 261bcc0
Cover the widget-push stream-error and rate-limit-failure paths
hariharanjagan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,235 @@ | ||
| 'use strict'; | ||
|
|
||
| const crypto = require('crypto'); | ||
| const { createMockRequest, createMockResponse } = require('./utils/mock-factories'); | ||
|
|
||
| jest.mock('node:http2', () => ({ connect: jest.fn() })); | ||
| const http2 = require('node:http2'); | ||
|
|
||
| const mockRateLimiter = { | ||
| recordAttempt: jest.fn(), | ||
| recordSuccess: jest.fn(), | ||
| recordError: jest.fn(), | ||
| }; | ||
| jest.mock('../handlers', () => ({ widgetRateLimiter: mockRateLimiter })); | ||
|
|
||
| const widgetPush = require('../widget-push'); | ||
|
|
||
| const WIDGET_TOKEN = '80f7d67347204c7dda85d331a95ec31c1e3c62b9173836ada8ed9abf'; | ||
|
|
||
| // A real P-256 key so ES256 signing succeeds; its value is irrelevant to the mock. | ||
| const TEST_P8 = crypto | ||
| .generateKeyPairSync('ec', { namedCurve: 'P-256' }) | ||
| .privateKey.export({ type: 'pkcs8', format: 'pem' }); | ||
|
|
||
| // Makes http2.connect return a client whose request replays the given APNs | ||
| // responses in order (one per connect call, so we can exercise the fallback). | ||
| function mockApns(responses, onRequest) { | ||
| let index = 0; | ||
| http2.connect.mockImplementation(() => { | ||
| const response = responses[Math.min(index, responses.length - 1)]; | ||
| index += 1; | ||
| const handlers = {}; | ||
| const request = { | ||
| on: jest.fn((event, cb) => { | ||
| handlers[event] = cb; | ||
| return request; | ||
| }), | ||
| setEncoding: jest.fn(), | ||
| end: jest.fn(() => { | ||
| process.nextTick(() => { | ||
| handlers.response?.({ ':status': response.status, 'apns-id': response.apnsId }); | ||
| if (response.body) handlers.data?.(response.body); | ||
| handlers.end?.(); | ||
| }); | ||
| }), | ||
| }; | ||
| return { | ||
| on: jest.fn(), | ||
| request: jest.fn((headers) => { | ||
| onRequest?.(headers); | ||
| return request; | ||
| }), | ||
| close: jest.fn(), | ||
| }; | ||
| }); | ||
| } | ||
|
|
||
| function widgetRequest(overrides = {}) { | ||
| return createMockRequest({ | ||
| body: { | ||
| push_subscription: { subscription_id: 'ios-widget-sensors', target: 'sensors' }, | ||
| push_token: WIDGET_TOKEN, | ||
| registration_info: { app_id: 'io.test.HomeAssistant' }, | ||
| ...overrides, | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| describe('widget-push', () => { | ||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| process.env.APNS_KEY_P8 = TEST_P8; | ||
| process.env.APNS_KEY_ID = 'KEY1234567'; | ||
| process.env.APNS_TEAM_ID = 'TEAM123456'; | ||
| mockRateLimiter.recordAttempt.mockResolvedValue({ isRateLimited: false, rateLimits: {} }); | ||
| mockRateLimiter.recordSuccess.mockResolvedValue({}); | ||
| mockRateLimiter.recordError.mockResolvedValue({}); | ||
| }); | ||
|
|
||
| it('returns 201 and echoes the apns-id on a successful send', async () => { | ||
| mockApns([{ status: 200, apnsId: 'apns-success' }]); | ||
| const res = createMockResponse(); | ||
|
|
||
| await widgetPush.sendWidgetPush(widgetRequest(), res); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(201); | ||
| expect(res.send).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| target: WIDGET_TOKEN, | ||
| messageId: 'apns-success', | ||
| pushType: 'widgets', | ||
| }), | ||
| ); | ||
| }); | ||
|
|
||
| it('rate-limits per token and returns 429 without reaching APNs', async () => { | ||
| mockRateLimiter.recordAttempt.mockResolvedValueOnce({ | ||
| isRateLimited: true, | ||
| rateLimits: { successful: 500 }, | ||
| }); | ||
| const res = createMockResponse(); | ||
|
|
||
| await widgetPush.sendWidgetPush(widgetRequest(), res); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(429); | ||
| expect(http2.connect).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('records the attempt outcome with the rate limiter on success', async () => { | ||
| mockApns([{ status: 200, apnsId: 'x' }]); | ||
|
|
||
| await widgetPush.sendWidgetPush(widgetRequest(), createMockResponse()); | ||
|
|
||
| expect(mockRateLimiter.recordAttempt).toHaveBeenCalledWith(WIDGET_TOKEN); | ||
| expect(mockRateLimiter.recordSuccess).toHaveBeenCalledWith(WIDGET_TOKEN); | ||
| }); | ||
|
|
||
| it('sends the widgets push type, widget topic and device path', async () => { | ||
| let headers; | ||
| mockApns([{ status: 200, apnsId: 'x' }], (h) => { | ||
| headers = h; | ||
| }); | ||
|
|
||
| await widgetPush.sendWidgetPush(widgetRequest(), createMockResponse()); | ||
|
|
||
| expect(headers['apns-push-type']).toBe('widgets'); | ||
| expect(headers['apns-topic']).toBe('io.test.HomeAssistant.push-type.widgets'); | ||
| expect(headers[':path']).toBe(`/3/device/${WIDGET_TOKEN}`); | ||
| expect(headers.authorization).toMatch(/^bearer /); | ||
| }); | ||
|
|
||
| it('falls back to the sandbox host on BadDeviceToken', async () => { | ||
| mockApns([ | ||
| { status: 400, body: '{"reason":"BadDeviceToken"}' }, | ||
| { status: 200, apnsId: 'sandbox-ok' }, | ||
| ]); | ||
| const res = createMockResponse(); | ||
|
|
||
| await widgetPush.sendWidgetPush(widgetRequest(), res); | ||
|
|
||
| expect(http2.connect).toHaveBeenCalledTimes(2); | ||
| expect(http2.connect).toHaveBeenNthCalledWith(1, 'https://api.push.apple.com'); | ||
| expect(http2.connect).toHaveBeenNthCalledWith(2, 'https://api.sandbox.push.apple.com'); | ||
| expect(res.status).toHaveBeenCalledWith(201); | ||
| }); | ||
|
|
||
| it('returns 403 when no token is sent', async () => { | ||
| const res = createMockResponse(); | ||
| await widgetPush.sendWidgetPush(widgetRequest({ push_token: null }), res); | ||
| expect(res.status).toHaveBeenCalledWith(403); | ||
| }); | ||
|
|
||
| it('returns 400 when registration_info.app_id is missing', async () => { | ||
| const res = createMockResponse(); | ||
| await widgetPush.sendWidgetPush(widgetRequest({ registration_info: {} }), res); | ||
| expect(res.status).toHaveBeenCalledWith(400); | ||
| }); | ||
|
|
||
| it('rejects a non-hex push token without reaching APNs', async () => { | ||
| const res = createMockResponse(); | ||
| await widgetPush.sendWidgetPush(widgetRequest({ push_token: `${WIDGET_TOKEN}/../evil` }), res); | ||
| expect(res.status).toHaveBeenCalledWith(400); | ||
| expect(http2.connect).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('rejects an app id with illegal characters without reaching APNs', async () => { | ||
| const res = createMockResponse(); | ||
| await widgetPush.sendWidgetPush( | ||
| widgetRequest({ registration_info: { app_id: 'io.test.HomeAssistant\r\nx-evil: 1' } }), | ||
| res, | ||
| ); | ||
| expect(res.status).toHaveBeenCalledWith(400); | ||
| expect(http2.connect).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('closes the HTTP/2 client and rejects on a session error', async () => { | ||
| const request = { on: jest.fn().mockReturnThis(), setEncoding: jest.fn(), end: jest.fn() }; | ||
| const client = { on: jest.fn(), request: jest.fn(() => request), close: jest.fn() }; | ||
| client.on.mockImplementation((event, cb) => { | ||
| if (event === 'error') process.nextTick(() => cb(new Error('boom'))); | ||
| return client; | ||
| }); | ||
| http2.connect.mockReturnValue(client); | ||
| const res = createMockResponse(); | ||
|
|
||
| await widgetPush.sendWidgetPush(widgetRequest(), res); | ||
|
|
||
| expect(client.close).toHaveBeenCalled(); | ||
| expect(res.status).toHaveBeenCalledWith(502); | ||
| }); | ||
|
|
||
| it('closes the HTTP/2 client and rejects on a stream error', async () => { | ||
| const handlers = {}; | ||
| const request = { | ||
| on: jest.fn((event, cb) => { | ||
| handlers[event] = cb; | ||
| return request; | ||
| }), | ||
| setEncoding: jest.fn(), | ||
| end: jest.fn(() => process.nextTick(() => handlers.error?.(new Error('stream boom')))), | ||
| }; | ||
| const client = { on: jest.fn(), request: jest.fn(() => request), close: jest.fn() }; | ||
| http2.connect.mockReturnValue(client); | ||
| const res = createMockResponse(); | ||
|
|
||
| await widgetPush.sendWidgetPush(widgetRequest(), res); | ||
|
|
||
| expect(client.close).toHaveBeenCalled(); | ||
| expect(res.status).toHaveBeenCalledWith(502); | ||
| }); | ||
|
|
||
| it('returns 500 when the rate-limit check throws', async () => { | ||
| mockRateLimiter.recordAttempt.mockRejectedValueOnce(new Error('firestore down')); | ||
| const res = createMockResponse(); | ||
|
|
||
| await widgetPush.sendWidgetPush(widgetRequest(), res); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(500); | ||
| expect(http2.connect).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('returns 500 when APNs credentials are not configured', async () => { | ||
| delete process.env.APNS_KEY_P8; | ||
| const res = createMockResponse(); | ||
| await widgetPush.sendWidgetPush(widgetRequest(), res); | ||
| expect(res.status).toHaveBeenCalledWith(500); | ||
| }); | ||
|
|
||
| it('propagates a non-fallback APNs rejection status', async () => { | ||
| mockApns([{ status: 410, body: '{"reason":"Unregistered"}' }]); | ||
| const res = createMockResponse(); | ||
| await widgetPush.sendWidgetPush(widgetRequest(), res); | ||
| expect(res.status).toHaveBeenCalledWith(410); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.