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

Reuse Configurations With Asterisk App IDs and Token Based APNS Auth #108

Merged
merged 9 commits into from
Apr 24, 2020
Merged
Show file tree
Hide file tree
Changes from 7 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
10 changes: 9 additions & 1 deletion sygnal/apnspushkin.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,15 @@ class ApnsPushkin(Pushkin):
MAX_FIELD_LENGTH = 1024
MAX_JSON_BODY_SIZE = 4096

UNDERSTOOD_CONFIG_FIELDS = {"type", "platform", "certfile"}
UNDERSTOOD_CONFIG_FIELDS = {
"type",
"platform",
"certfile",
"team_id",
"key_id",
"keyfile",
"topic",
}

def __init__(self, name, sygnal, config):
super().__init__(name, sygnal, config)
Expand Down
33 changes: 31 additions & 2 deletions sygnal/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import sys
import time
import traceback
import re
from uuid import uuid4

from opentracing import Format, logs, tags
Expand Down Expand Up @@ -201,6 +202,28 @@ async def cb():
if not root_span_accounted_for:
root_span.finish()

def find_pushkins(self, appid):
"""Finds matching pushkins in self.sygnal.pushkins according to the appid.

Args:
appid (str): app identifier to search in self.sygnal.pushkins.
Returns:
ismailgulek marked this conversation as resolved.
Show resolved Hide resolved
list of `Pushkin`: If it finds a specific pushkin with
the exact app id, immediately returns it.
Otherwise returns possible pushkins.
"""
# if found a specific appid, just return it as a list
if appid in self.sygnal.pushkins:
return [self.sygnal.pushkins[appid]]

result = []
for key, value in self.sygnal.pushkins.items():
# The ".+" symbol is used in place of "*" symbol
regex = key.replace("*", ".+")
if re.search(regex, appid):
result.append(value)
return result
babolivier marked this conversation as resolved.
Show resolved Hide resolved

async def _handle_dispatch(self, root_span, request, log, notif, context):
"""
Actually handle the dispatch of notifications to devices, sequentially
Expand All @@ -219,12 +242,18 @@ async def _handle_dispatch(self, root_span, request, log, notif, context):
NOTIFS_RECEIVED_DEVICE_PUSH_COUNTER.inc()

appid = d.app_id
if appid not in self.sygnal.pushkins:
found_pushkins = self.find_pushkins(appid)
if len(found_pushkins) == 0:
log.warning("Got notification for unknown app ID %s", appid)
rejected.append(d.pushkey)
continue

pushkin = self.sygnal.pushkins[appid]
if len(found_pushkins) > 1:
log.warning("Got notification for an ambigious app ID %s", appid)
rejected.append(d.pushkey)
continue

pushkin = found_pushkins[0]
log.debug(
"Sending push to pushkin %s for app ID %s", pushkin.name, appid
)
Expand Down
123 changes: 123 additions & 0 deletions tests/test_http.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
# -*- coding: utf-8 -*-
# Copyright 2019 The Matrix.org Foundation C.I.C.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from unittest.mock import patch, MagicMock

from aioapns.common import NotificationResult

from tests import testutils

PUSHKIN_ID_1 = "com.example.apns"
PUSHKIN_ID_2 = "*.example.*"
PUSHKIN_ID_3 = "com.example.a*"

TEST_CERTFILE_PATH = "/path/to/my/certfile.pem"

# Specific app id
DEVICE_EXAMPLE_SPECIFIC = {
"app_id": "com.example.apns",
"pushkey": "spqr",
"pushkey_ts": 42,
}

# Only one time matching app id (with PUSHKIN_ID_2)
DEVICE_EXAMPLE_MATCHING = {
"app_id": "com.example.bpns",
"pushkey": "spqr",
"pushkey_ts": 42,
}

# More than one times matching app id (with PUSHKIN_ID_2 and PUSHKIN_ID_3)
DEVICE_EXAMPLE_AMBIGIOUS = {
"app_id": "com.example.apns2",
"pushkey": "spqr",
"pushkey_ts": 42,
}


class HttpTestCase(testutils.TestCase):
def setUp(self):
self.apns_mock_class = patch("aioapns.APNs").start()
self.apns_mock = MagicMock()
self.apns_mock_class.return_value = self.apns_mock

# pretend our certificate exists
patch("os.path.exists", lambda x: x == TEST_CERTFILE_PATH).start()
self.addCleanup(patch.stopall)

super(HttpTestCase, self).setUp()

self.apns_pushkin_snotif = MagicMock()
for key, value in self.sygnal.pushkins.items():
value._send_notification = self.apns_pushkin_snotif

def config_setup(self, config):
super(HttpTestCase, self).config_setup(config)
config["apps"][PUSHKIN_ID_1] = {"type": "apns", "certfile": TEST_CERTFILE_PATH}
config["apps"][PUSHKIN_ID_2] = {"type": "apns", "certfile": TEST_CERTFILE_PATH}
config["apps"][PUSHKIN_ID_3] = {"type": "apns", "certfile": TEST_CERTFILE_PATH}

def test_with_specific_appid(self):
"""
Tests the expected case: A specific app id must be processed.
"""
# Arrange
method = self.apns_pushkin_snotif
method.side_effect = testutils.make_async_magic_mock(
NotificationResult("notID", "200")
)

# Act
resp = self._request(self._make_dummy_notification([DEVICE_EXAMPLE_SPECIFIC]))

# Assert
# method should be called one time
self.assertEqual(1, method.call_count)

self.assertEqual({"rejected": []}, resp)

def test_with_matching_appid(self):
"""
Tests the matching case: A matching app id (only one time) must be processed.
"""
# Arrange
method = self.apns_pushkin_snotif
method.side_effect = testutils.make_async_magic_mock(
NotificationResult("notID", "200")
)

# Act
resp = self._request(self._make_dummy_notification([DEVICE_EXAMPLE_MATCHING]))

# Assert
# method should be called one time
self.assertEqual(1, method.call_count)

self.assertEqual({"rejected": []}, resp)

def test_with_ambigious_appid(self):
"""
Tests the rejection case: An ambigious app id should be rejected without
processing.
"""
# Arrange
method = self.apns_pushkin_snotif

# Act
resp = self._request(self._make_dummy_notification([DEVICE_EXAMPLE_AMBIGIOUS]))

# Assert
# must be rejected without calling the method
self.assertEqual(0, method.call_count)
self.assertEqual({"rejected": ["spqr"]}, resp)