diff --git a/autopush/config.py b/autopush/config.py index a9480f8d..10b916ec 100644 --- a/autopush/config.py +++ b/autopush/config.py @@ -22,7 +22,7 @@ import autopush.db as db from autopush.exceptions import ( - InvalidSettings, + InvalidConfig, InvalidTokenException, VapidAuthException ) @@ -233,22 +233,21 @@ def from_argparse(cls, ns, **kwargs): try: router_conf["apns"] = json.loads(ns.apns_creds) except (ValueError, TypeError): - raise InvalidSettings( + raise InvalidConfig( "Invalid JSON specified for APNS config options") if ns.gcm_enabled: # Create a common gcmclient try: sender_ids = json.loads(ns.senderid_list) except (ValueError, TypeError): - raise InvalidSettings( - "Invalid JSON specified for senderid_list") + raise InvalidConfig("Invalid JSON specified for senderid_list") try: # This is an init check to verify that things are # configured correctly. Otherwise errors may creep in # later that go unaccounted. sender_ids[sender_ids.keys()[0]] except (IndexError, TypeError): - raise InvalidSettings("No GCM SenderIDs specified or found.") + raise InvalidConfig("No GCM SenderIDs specified or found.") router_conf["gcm"] = {"ttl": ns.gcm_ttl, "dryrun": ns.gcm_dryrun, "max_data": ns.max_data, @@ -261,31 +260,30 @@ def from_argparse(cls, ns, **kwargs): try: client_certs_arg = json.loads(ns.client_certs) except (ValueError, TypeError): - raise InvalidSettings( - "Invalid JSON specified for client_certs") + raise InvalidConfig("Invalid JSON specified for client_certs") if client_certs_arg: if not ns.ssl_key: - raise InvalidSettings("client_certs specified without SSL " - "enabled (no ssl_key specified)") + raise InvalidConfig("client_certs specified without SSL " + "enabled (no ssl_key specified)") client_certs = {} for name, sigs in client_certs_arg.iteritems(): if not isinstance(sigs, list): - raise InvalidSettings( + raise InvalidConfig( "Invalid JSON specified for client_certs") for sig in sigs: sig = sig.upper() if (not name or not CLIENT_SHA256_RE.match(sig) or sig in client_certs): - raise InvalidSettings( + raise InvalidConfig( "Invalid client_certs argument") client_certs[sig] = name if ns.fcm_enabled: # Create a common gcmclient if not ns.fcm_auth: - raise InvalidSettings("No Authorization Key found for FCM") + raise InvalidConfig("No Authorization Key found for FCM") if not ns.fcm_senderid: - raise InvalidSettings("No SenderID found for FCM") + raise InvalidConfig("No SenderID found for FCM") router_conf["fcm"] = {"ttl": ns.fcm_ttl, "dryrun": ns.fcm_dryrun, "max_data": ns.max_data, diff --git a/autopush/db.py b/autopush/db.py index 5129b29d..8e2589c4 100644 --- a/autopush/db.py +++ b/autopush/db.py @@ -885,14 +885,14 @@ def __attrs_post_init__(self): ) @classmethod - def from_config(cls, settings, **kwargs): + def from_config(cls, conf, **kwargs): # type: (AutopushConfig, **Any) -> DatabaseManager """Create a DatabaseManager from the given config""" - metrics = autopush.metrics.from_config(settings) + metrics = autopush.metrics.from_config(conf) return cls( - storage_conf=settings.storage_table, - router_conf=settings.router_table, - message_conf=settings.message_table, + storage_conf=conf.storage_table, + router_conf=conf.router_table, + message_conf=conf.message_table, metrics=metrics, **kwargs ) diff --git a/autopush/diagnostic_cli.py b/autopush/diagnostic_cli.py index 2c3c8594..b44d5594 100644 --- a/autopush/diagnostic_cli.py +++ b/autopush/diagnostic_cli.py @@ -20,10 +20,10 @@ class EndpointDiagnosticCLI(object): def __init__(self, sysargs, use_files=True): ns = self._load_args(sysargs, use_files) - self._settings = settings = AutopushConfig.from_argparse(ns) - settings.statsd_host = None - self.db = DatabaseManager.from_config(settings) - self.db.setup(settings.preflight_uaid) + self._conf = conf = AutopushConfig.from_argparse(ns) + conf.statsd_host = None + self.db = DatabaseManager.from_config(conf) + self.db.setup(conf.preflight_uaid) self._endpoint = ns.endpoint self._pp = pprint.PrettyPrinter(indent=4) @@ -54,7 +54,7 @@ def run(self): md = match.groupdict() api_ver, token = md.get("api_ver", "v1"), md["token"] - parsed = self._settings.parse_endpoint( + parsed = self._conf.parse_endpoint( self.db.metrics, token=token, version=api_ver, diff --git a/autopush/exceptions.py b/autopush/exceptions.py index 68388493..53c9094e 100644 --- a/autopush/exceptions.py +++ b/autopush/exceptions.py @@ -62,5 +62,5 @@ class LogCheckError(Exception): pass -class InvalidSettings(Exception): +class InvalidConfig(Exception): """Error in initialization of AutopushConfig""" diff --git a/autopush/http.py b/autopush/http.py index 099a74bf..66fcd65d 100644 --- a/autopush/http.py +++ b/autopush/http.py @@ -102,7 +102,7 @@ def for_handler(cls, """Create a cyclone app around a specific handler_cls for tests. Creates an uninitialized (no setup() called) DatabaseManager - from settings if one isn't specified. + from conf if one isn't specified. handler_cls must be included in ap_handlers or a ValueError is thrown. @@ -175,8 +175,8 @@ def ssl_cf(self): values. """ - settings = self.conf - return settings.ssl.cf(require_peer_certs=settings.enable_tls_auth) + conf = self.conf + return conf.ssl.cf(require_peer_certs=conf.enable_tls_auth) @classmethod def _for_handler(cls, conf, db, routers=None, **kwargs): @@ -238,11 +238,11 @@ class QuietClientFactory(_HTTP11ClientFactory): noisy = False -def agent_from_config(settings): +def agent_from_config(conf): # type: (AutopushConfig) -> Agent """Create a twisted.web.client Agent from the given config""" # Use a persistent connection pool for HTTP requests. pool = HTTPConnectionPool(reactor) - if not settings.debug: + if not conf.debug: pool._factory = QuietClientFactory - return Agent(reactor, connectTimeout=settings.connect_timeout, pool=pool) + return Agent(reactor, connectTimeout=conf.connect_timeout, pool=pool) diff --git a/autopush/main.py b/autopush/main.py index eefa31c2..096a6ce8 100644 --- a/autopush/main.py +++ b/autopush/main.py @@ -30,7 +30,7 @@ import autopush.logging as logging from autopush.config import AutopushConfig from autopush.db import DatabaseManager -from autopush.exceptions import InvalidSettings +from autopush.exceptions import InvalidConfig from autopush.haproxy import HAProxyServerEndpoint from autopush.logging import PushLogger from autopush.main_argparse import parse_connection, parse_endpoint @@ -58,12 +58,12 @@ class AutopushMultiService(MultiService): THREAD_POOL_SIZE = 50 - def __init__(self, settings): + def __init__(self, conf): # type: (AutopushConfig) -> None super(AutopushMultiService, self).__init__() - self.settings = settings - self.db = DatabaseManager.from_config(settings) - self.agent = agent_from_config(settings) + self.conf = conf + self.db = DatabaseManager.from_config(conf) + self.agent = agent_from_config(conf) @staticmethod def parse_args(config_files, args): @@ -91,9 +91,9 @@ def add_timer(self, *args, **kwargs): def add_memusage(self): """Add the memusage Service""" - factory = MemUsageHTTPFactory(self.settings, None) + factory = MemUsageHTTPFactory(self.conf, None) self.addService( - TCPServer(self.settings.memusage_port, factory, reactor=reactor)) + TCPServer(self.conf.memusage_port, factory, reactor=reactor)) def run(self): """Start the services and run the reactor""" @@ -112,13 +112,13 @@ def _from_argparse(cls, ns, **kwargs): """Create an instance from argparse/additional kwargs""" # Add some entropy to prevent potential conflicts. postfix = os.urandom(4).encode('hex').ljust(8, '0') - settings = AutopushConfig.from_argparse( + conf = AutopushConfig.from_argparse( ns, debug=ns.debug, preflight_uaid="deadbeef000000000deadbeef" + postfix, **kwargs ) - return cls(settings) + return cls(conf) @classmethod def main(cls, args=None, use_files=True): @@ -141,7 +141,7 @@ def main(cls, args=None, use_files=True): ) try: app = cls.from_argparse(ns) - except InvalidSettings as e: + except InvalidConfig as e: log.critical(str(e)) return 1 @@ -164,16 +164,16 @@ class EndpointApplication(AutopushMultiService): endpoint_factory = EndpointHTTPFactory - def __init__(self, settings): + def __init__(self, conf): # type: (AutopushConfig) -> None - super(EndpointApplication, self).__init__(settings) - self.routers = routers_from_config(settings, self.db, self.agent) + super(EndpointApplication, self).__init__(conf) + self.routers = routers_from_config(conf, self.db, self.agent) def setup(self, rotate_tables=True): - self.db.setup(self.settings.preflight_uaid) + self.db.setup(self.conf.preflight_uaid) self.add_endpoint() - if self.settings.memusage_port: + if self.conf.memusage_port: self.add_memusage() # Start the table rotation checker/updater @@ -182,18 +182,18 @@ def setup(self, rotate_tables=True): def add_endpoint(self): """Start the Endpoint HTTP router""" - settings = self.settings + conf = self.conf - factory = self.endpoint_factory(settings, self.db, self.routers) - factory.protocol.maxData = settings.max_data + factory = self.endpoint_factory(conf, self.db, self.routers) + factory.protocol.maxData = conf.max_data factory.add_health_handlers() ssl_cf = factory.ssl_cf() - self.add_maybe_ssl(settings.port, factory, ssl_cf) + self.add_maybe_ssl(conf.port, factory, ssl_cf) - if settings.proxy_protocol_port: + if conf.proxy_protocol_port: ep = HAProxyServerEndpoint( reactor, - settings.proxy_protocol_port, + conf.proxy_protocol_port, ssl_cf ) self.addService(StreamServerEndpointService(ep, factory)) @@ -230,16 +230,16 @@ class ConnectionApplication(AutopushMultiService): websocket_factory = PushServerFactory websocket_site_factory = ConnectionWSSite - def __init__(self, settings): + def __init__(self, conf): # type: (AutopushConfig) -> None - super(ConnectionApplication, self).__init__(settings) + super(ConnectionApplication, self).__init__(conf) self.clients = {} # type: Dict[str, PushServerProtocol] def setup(self, rotate_tables=True): - self.db.setup(self.settings.preflight_uaid) + self.db.setup(self.conf.preflight_uaid) self.add_internal_router() - if self.settings.memusage_port: + if self.conf.memusage_port: self.add_memusage() self.add_websocket() @@ -251,18 +251,17 @@ def setup(self, rotate_tables=True): def add_internal_router(self): """Start the internal HTTP notification router""" factory = self.internal_router_factory( - self.settings, self.db, self.clients) + self.conf, self.db, self.clients) factory.add_health_handlers() - self.add_maybe_ssl(self.settings.router_port, factory, - factory.ssl_cf()) + self.add_maybe_ssl(self.conf.router_port, factory, factory.ssl_cf()) def add_websocket(self): """Start the public WebSocket server""" - settings = self.settings - ws_factory = self.websocket_factory(settings, self.db, self.agent, + conf = self.conf + ws_factory = self.websocket_factory(conf, self.db, self.agent, self.clients) - site_factory = self.websocket_site_factory(settings, ws_factory) - self.add_maybe_ssl(settings.port, site_factory, site_factory.ssl_cf()) + site_factory = self.websocket_site_factory(conf, ws_factory) + self.add_maybe_ssl(conf.port, site_factory, site_factory.ssl_cf()) @classmethod def from_argparse(cls, ns): diff --git a/autopush/metrics.py b/autopush/metrics.py index 3a4bfc4a..38766e91 100644 --- a/autopush/metrics.py +++ b/autopush/metrics.py @@ -114,18 +114,18 @@ def timing(self, name, duration, **kwargs): host=self._host, **kwargs) -def from_config(settings): +def from_config(conf): # type: (AutopushConfig) -> IMetrics """Create an IMetrics from the given config""" - if settings.datadog_api_key: + if conf.datadog_api_key: return DatadogMetrics( - hostname=get_ec2_instance_id() if settings.ami_id else - settings.hostname, - api_key=settings.datadog_api_key, - app_key=settings.datadog_app_key, - flush_interval=settings.datadog_flush_interval, + hostname=get_ec2_instance_id() if conf.ami_id else + conf.hostname, + api_key=conf.datadog_api_key, + app_key=conf.datadog_app_key, + flush_interval=conf.datadog_flush_interval, ) - elif settings.statsd_host: - return TwistedMetrics(settings.statsd_host, settings.statsd_port) + elif conf.statsd_host: + return TwistedMetrics(conf.statsd_host, conf.statsd_port) else: return SinkMetrics() diff --git a/autopush/router/__init__.py b/autopush/router/__init__.py index ca07229f..c038a534 100644 --- a/autopush/router/__init__.py +++ b/autopush/router/__init__.py @@ -21,18 +21,18 @@ "SimpleRouter"] -def routers_from_config(settings, db, agent): +def routers_from_config(conf, db, agent): # type: (AutopushConfig, DatabaseManager, Agent) -> Dict[str, IRouter] """Create a dict of IRouters for the given config""" - router_conf = settings.router_conf + router_conf = conf.router_conf routers = dict( - webpush=WebPushRouter(settings, None, db, agent) + webpush=WebPushRouter(conf, None, db, agent) ) - if settings.enable_simplepush: + if conf.enable_simplepush: routers['simplepush'] = SimpleRouter( - settings, router_conf.get("simplepush"), db, agent) + conf, router_conf.get("simplepush"), db, agent) if 'apns' in router_conf: - routers["apns"] = APNSRouter(settings, router_conf["apns"], db.metrics) + routers["apns"] = APNSRouter(conf, router_conf["apns"], db.metrics) if 'gcm' in router_conf: - routers["gcm"] = GCMRouter(settings, router_conf["gcm"], db.metrics) + routers["gcm"] = GCMRouter(conf, router_conf["gcm"], db.metrics) return routers diff --git a/autopush/router/interface.py b/autopush/router/interface.py index 5b39c75e..a0c5a1b0 100644 --- a/autopush/router/interface.py +++ b/autopush/router/interface.py @@ -24,9 +24,9 @@ def __init__(self, status_code=200, response_body="", router_data=None, class IRouter(object): - def __init__(self, settings, router_conf, **kwargs): + def __init__(self, conf, router_conf, **kwargs): """Initialize the Router to handle notifications and registrations with - the given settings and router conf.""" + the given conf and router conf.""" raise NotImplementedError("__init__ must be implemented") def register(self, uaid, router_data, app_id, *args, **kwargs): diff --git a/autopush/tests/test_diagnostic_cli.py b/autopush/tests/test_diagnostic_cli.py index 42cc20ee..14f46ab6 100644 --- a/autopush/tests/test_diagnostic_cli.py +++ b/autopush/tests/test_diagnostic_cli.py @@ -30,10 +30,10 @@ def test_bad_endpoint(self): @patch("autopush.diagnostic_cli.AutopushConfig") @patch("autopush.diagnostic_cli.DatabaseManager.from_config") - def test_successfull_lookup(self, mock_db_cstr, mock_settings_class): + def test_successfull_lookup(self, mock_db_cstr, mock_conf_class): from autopush.diagnostic_cli import run_endpoint_diagnostic_cli - mock_settings_class.return_value = mock_settings = Mock() - mock_settings.parse_endpoint.return_value = dict( + mock_conf_class.return_value = mock_conf = Mock() + mock_conf.parse_endpoint.return_value = dict( uaid="asdf", chid="asdf") mock_db_cstr.return_value = mock_db = Mock() diff --git a/autopush/tests/test_endpoint.py b/autopush/tests/test_endpoint.py index c502cf7e..058493d8 100644 --- a/autopush/tests/test_endpoint.py +++ b/autopush/tests/test_endpoint.py @@ -47,7 +47,7 @@ def write(self, data): class MessageTestCase(unittest.TestCase): def setUp(self): twisted.internet.base.DelayedCall.debug = True - settings = AutopushConfig( + conf = AutopushConfig( hostname="localhost", statsd_host=None, crypto_key='AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=', @@ -55,9 +55,9 @@ def setUp(self): ) db = test_db() self.message_mock = db.message = Mock(spec=Message) - self.fernet_mock = settings.fernet = Mock(spec=Fernet) + self.fernet_mock = conf.fernet = Mock(spec=Fernet) - app = EndpointHTTPFactory.for_handler(MessageHandler, settings, db=db) + app = EndpointHTTPFactory.for_handler(MessageHandler, conf, db=db) self.client = Client(app) def url(self, **kwargs): @@ -135,13 +135,13 @@ class RegistrationTestCase(unittest.TestCase): def setUp(self): twisted.internet.base.DelayedCall.debug = True - settings = AutopushConfig( + conf = AutopushConfig( hostname="localhost", statsd_host=None, bear_hash_key='AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB=', enable_simplepush=True, ) - self.fernet_mock = settings.fernet = Mock(spec=Fernet) + self.fernet_mock = conf.fernet = Mock(spec=Fernet) self.db = db = test_db() db.router.register_user.return_value = (True, {}, {}) @@ -151,17 +151,17 @@ def setUp(self): } db.create_initial_message_tables() - self.routers = routers = routers_from_config(settings, db, Mock()) + self.routers = routers = routers_from_config(conf, db, Mock()) routers["test"] = Mock(spec=IRouter) - app = EndpointHTTPFactory(settings, db=db, routers=routers) + app = EndpointHTTPFactory(conf, db=db, routers=routers) self.client = Client(app) self.request_mock = Mock(body=b'', arguments={}, headers={}) self.reg = NewRegistrationHandler(app, self.request_mock) self.auth = ("WebPush %s" % - generate_hash(settings.bear_hash_key[0], dummy_uaid.hex)) + generate_hash(conf.bear_hash_key[0], dummy_uaid.hex)) - self.settings = settings + self.conf = conf def url(self, router_token='test', **kwargs): urlfmt = '/v1/{router_type}/{router_token}/registration' @@ -206,17 +206,17 @@ def test_init_info(self): d = self.reg._init_info() eq_(d["remote_ip"], "local2") - def test_settings_crypto_key(self): + def test_conf_crypto_key(self): fake = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' - settings = AutopushConfig(crypto_key=fake) - eq_(settings.fernet._fernets[0]._encryption_key, + conf = AutopushConfig(crypto_key=fake) + eq_(conf.fernet._fernets[0]._encryption_key, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') fake2 = 'BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=' - settings = AutopushConfig(crypto_key=[fake, fake2]) - eq_(settings.fernet._fernets[0]._encryption_key, + conf = AutopushConfig(crypto_key=[fake, fake2]) + eq_(conf.fernet._fernets[0]._encryption_key, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') - eq_(settings.fernet._fernets[1]._encryption_key, + eq_(conf.fernet._fernets[1]._encryption_key, '\x10A\x04\x10A\x04\x10A\x04\x10A\x04\x10A\x04\x10') def test_cors(self): @@ -287,7 +287,7 @@ def test_post_gcm(self): from autopush.router.gcm import GCMRouter sids = {"182931248179192": {"auth": "aailsjfilajdflijdsilfjsliaj"}} gcm = GCMRouter( - self.settings, + self.conf, {"dryrun": True, "senderIDs": sids}, SinkMetrics() ) diff --git a/autopush/tests/test_health.py b/autopush/tests/test_health.py index 7762f46e..0343ff7a 100644 --- a/autopush/tests/test_health.py +++ b/autopush/tests/test_health.py @@ -24,11 +24,11 @@ def setUp(self): self.timeout = 0.5 twisted.internet.base.DelayedCall.debug = True - settings = AutopushConfig( + conf = AutopushConfig( hostname="localhost", statsd_host=None, ) - db = DatabaseManager.from_config(settings) + db = DatabaseManager.from_config(conf) db.setup_tables() # ignore logging @@ -36,7 +36,7 @@ def setUp(self): begin_or_register(logs) self.addCleanup(globalLogPublisher.removeObserver, logs) - app = EndpointHTTPFactory.for_handler(HealthHandler, settings, db=db) + app = EndpointHTTPFactory.for_handler(HealthHandler, conf, db=db) self.router_table = app.db.router.table self.storage_table = app.db.storage.table self.client = Client(app) @@ -124,13 +124,13 @@ def _assert_reply(self, reply, exception=None): class StatusTestCase(unittest.TestCase): def setUp(self): twisted.internet.base.DelayedCall.debug = True - settings = AutopushConfig( + conf = AutopushConfig( hostname="localhost", statsd_host=None, ) self.request_mock = Mock() self.status = StatusHandler( - EndpointHTTPFactory(settings, db=None, routers=None), + EndpointHTTPFactory(conf, db=None, routers=None), self.request_mock ) self.write_mock = self.status.write = Mock() diff --git a/autopush/tests/test_integration.py b/autopush/tests/test_integration.py index 25fa4e8b..807fa4c4 100644 --- a/autopush/tests/test_integration.py +++ b/autopush/tests/test_integration.py @@ -332,23 +332,23 @@ def setUp(self): self.addCleanup(globalLogPublisher.removeObserver, self.logs) crypto_key = Fernet.generate_key() - ep_settings = AutopushConfig( + ep_conf = AutopushConfig( crypto_key=crypto_key, **self.endpoint_kwargs() ) - conn_settings = AutopushConfig( + conn_conf = AutopushConfig( crypto_key=crypto_key, **self.conn_kwargs() ) # Endpoint HTTP router - self.ep = ep = EndpointApplication(ep_settings) + self.ep = ep = EndpointApplication(ep_conf) ep.setup(rotate_tables=False) ep.startService() self.addCleanup(ep.stopService) # Websocket server - self.conn = conn = ConnectionApplication(conn_settings) + self.conn = conn = ConnectionApplication(conn_conf) conn.setup(rotate_tables=False) conn.startService() self.addCleanup(conn.stopService) @@ -376,9 +376,9 @@ def shut_down(self, client=None): @contextmanager def legacy_endpoint(self): - self.ep.settings._notification_legacy = True + self.ep.conf._notification_legacy = True yield - self.ep.settings._notification_legacy = False + self.ep.conf._notification_legacy = False class SSLEndpointMixin(object): @@ -732,7 +732,7 @@ class TestWebPush(IntegrationBase): @property def _ws_url(self): - return self.conn.settings.ws_url + return self.conn.conf.ws_url @inlineCallbacks def test_hello_only_has_three_calls(self): @@ -1311,7 +1311,7 @@ def test_webpush_monthly_rotation(self): # Move the client back one month to the past last_month = make_rotating_tablename( - prefix=self.conn.settings.message_table.tablename, delta=-1) + prefix=self.conn.conf.message_table.tablename, delta=-1) lm_message = self.conn.db.message_tables[last_month] yield deferToThread( self.conn.db.router.update_message_month, @@ -1422,7 +1422,7 @@ def test_webpush_monthly_rotation_prior_record_exists(self): # Move the client back one month to the past last_month = make_rotating_tablename( - prefix=self.conn.settings.message_table.tablename, delta=-1) + prefix=self.conn.conf.message_table.tablename, delta=-1) lm_message = self.conn.db.message_tables[last_month] yield deferToThread( self.conn.db.router.update_message_month, @@ -1519,7 +1519,7 @@ def test_webpush_monthly_rotation_no_channels(self): # Move the client back one month to the past last_month = make_rotating_tablename( - prefix=self.conn.settings.message_table.tablename, delta=-1) + prefix=self.conn.conf.message_table.tablename, delta=-1) yield deferToThread( self.conn.db.router.update_message_month, client.uaid, @@ -1759,7 +1759,7 @@ def needs_retry(cls=None): def _add_router(self): from autopush.router.gcm import GCMRouter gcm = GCMRouter( - self.ep.settings, + self.ep.conf, { "ttl": 0, "dryrun": True, @@ -1786,7 +1786,7 @@ def test_registration(self): self._add_router() # get the senderid url = "{}/v1/{}/{}/registration".format( - self.ep.settings.endpoint_url, + self.ep.conf.endpoint_url, "gcm", self.senderID, ) @@ -1834,7 +1834,7 @@ def test_registration_aes128gcm(self): self._add_router() # get the senderid url = "{}/v1/{}/{}/registration".format( - self.ep.settings.endpoint_url, + self.ep.conf.endpoint_url, "gcm", self.senderID, ) @@ -1876,7 +1876,7 @@ def test_registration_aes128gcm_bad_(self): self._add_router() # get the senderid url = "{}/v1/{}/{}/registration".format( - self.ep.settings.endpoint_url, + self.ep.conf.endpoint_url, "gcm", self.senderID, ) @@ -1928,7 +1928,7 @@ def test_registration_no_token(self): self._add_router() # get the senderid url = "{}/v1/{}/{}/registration".format( - self.ep.settings.endpoint_url, + self.ep.conf.endpoint_url, "gcm", self.senderID, ) @@ -1948,7 +1948,7 @@ class TestFCMBridgeIntegration(IntegrationBase): def _add_router(self): from autopush.router.fcm import FCMRouter fcm = FCMRouter( - self.ep.settings, + self.ep.conf, { "ttl": 0, "dryrun": True, @@ -1978,7 +1978,7 @@ def test_registration(self): self._add_router() # get the senderid url = "{}/v1/{}/{}/registration".format( - self.ep.settings.endpoint_url, + self.ep.conf.endpoint_url, "fcm", self.senderID, ) @@ -2031,7 +2031,7 @@ class m_response: def _add_router(self): from autopush.router.apnsrouter import APNSRouter apns = APNSRouter( - self.ep.settings, + self.ep.conf, { "firefox": { "cert": "/home/user/certs/SimplePushDemo.p12_cert.pem", @@ -2058,7 +2058,7 @@ def test_registration(self): self._add_router() # get the senderid url = "{}/v1/{}/{}/registration".format( - self.ep.settings.endpoint_url, + self.ep.conf.endpoint_url, "apns", "firefox", ) @@ -2108,7 +2108,7 @@ def test_registration_no_token(self): self._add_router() # get the senderid url = "{}/v1/{}/{}/registration".format( - self.ep.settings.endpoint_url, + self.ep.conf.endpoint_url, "apns", "firefox", ) @@ -2122,7 +2122,7 @@ def test_registration_aps_override(self): self._add_router() # get the senderid url = "{}/v1/{}/{}/registration".format( - self.ep.settings.endpoint_url, + self.ep.conf.endpoint_url, "apns", "firefox", ) @@ -2179,7 +2179,7 @@ def endpoint_kwargs(self): @inlineCallbacks def test_proxy_protocol(self): - port = self.ep.settings.proxy_protocol_port + port = self.ep.conf.proxy_protocol_port ip = '198.51.100.22' proto_line = 'PROXY TCP4 {} 203.0.113.7 35646 80\r\n'.format(ip) # the proxy proto. line comes before the request: we can sneak @@ -2197,7 +2197,7 @@ def test_proxy_protocol(self): def test_no_proxy_protocol(self): response, body = yield _agent( 'GET', - "http://localhost:{}/v1/err".format(self.ep.settings.port), + "http://localhost:{}/v1/err".format(self.ep.conf.port), ) eq_(response.code, 418) payload = json.loads(body) @@ -2234,7 +2234,7 @@ def wrap_socket(self, sock, *args, **kwargs): return self.context.wrap_socket(sock, *args, **kwargs) http = httplib.HTTPSConnection( - "localhost:{}".format(self.ep.settings.proxy_protocol_port), + "localhost:{}".format(self.ep.conf.proxy_protocol_port), context=SSLContextWrapper(self._create_context(None))) try: http.request('GET', '/v1/err') @@ -2260,7 +2260,7 @@ def endpoint_kwargs(self): @inlineCallbacks def test_memusage(self): - port = self.ep.settings.memusage_port + port = self.ep.conf.memusage_port response, body = yield _agent( 'GET', "http://localhost:{}/_memusage".format(port), diff --git a/autopush/tests/test_limitedhttpconnection.py b/autopush/tests/test_limitedhttpconnection.py index 60c50074..f32feb42 100644 --- a/autopush/tests/test_limitedhttpconnection.py +++ b/autopush/tests/test_limitedhttpconnection.py @@ -14,7 +14,7 @@ def test_lineRecieved(self): mock_transport = Mock() conn = LimitedHTTPConnection() conn.factory = Mock() - conn.factory.settings = {} + conn.factory.conf = {} conn.makeConnection(mock_transport) conn._on_headers = Mock() @@ -34,7 +34,7 @@ def test_rawDataReceived(self): mock_transport = Mock() conn = LimitedHTTPConnection() conn.factory = Mock() - conn.factory.settings = {} + conn.factory.conf = {} conn.makeConnection(mock_transport) conn._on_headers = Mock() conn._on_request_body = Mock() diff --git a/autopush/tests/test_log_check.py b/autopush/tests/test_log_check.py index 12c81ef2..acfa5c67 100644 --- a/autopush/tests/test_log_check.py +++ b/autopush/tests/test_log_check.py @@ -19,7 +19,7 @@ class LogCheckTestCase(unittest.TestCase): def setUp(self): twisted.internet.base.DelayedCall.debug = True - settings = AutopushConfig( + conf = AutopushConfig( hostname="localhost", statsd_host=None, ) @@ -28,7 +28,7 @@ def setUp(self): begin_or_register(self.logs, discardBuffer=True) self.addCleanup(globalLogPublisher.removeObserver, self.logs) - app = EndpointHTTPFactory.for_handler(LogCheckHandler, settings) + app = EndpointHTTPFactory.for_handler(LogCheckHandler, conf) self.client = Client(app) @inlineCallbacks diff --git a/autopush/tests/test_main.py b/autopush/tests/test_main.py index 954714a2..3e56acc6 100644 --- a/autopush/tests/test_main.py +++ b/autopush/tests/test_main.py @@ -16,7 +16,7 @@ import autopush.db from autopush.config import AutopushConfig from autopush.db import DatabaseManager, get_rotating_message_table -from autopush.exceptions import InvalidSettings +from autopush.exceptions import InvalidConfig from autopush.http import skip_request_logging from autopush.main import ( ConnectionApplication, @@ -29,12 +29,12 @@ endpoint_main = EndpointApplication.main -class SettingsTestCase(unittest.TestCase): +class ConfigTestCase(unittest.TestCase): def test_resolve_host(self): ip = resolve_ip("example.com") - settings = AutopushConfig( + conf = AutopushConfig( hostname="example.com", resolve_hostname=True) - eq_(settings.hostname, ip) + eq_(conf.hostname, ip) @patch("autopush.utils.socket") def test_resolve_host_no_interface(self, mock_socket): @@ -59,12 +59,12 @@ def test_new_month(self): eq_(len(db.message_tables), 3) -class SettingsAsyncTestCase(trialtest.TestCase): +class ConfigAsyncTestCase(trialtest.TestCase): def test_update_rotating_tables(self): from autopush.db import get_month - settings = AutopushConfig( + conf = AutopushConfig( hostname="example.com", resolve_hostname=True) - db = DatabaseManager.from_config(settings) + db = DatabaseManager.from_config(conf) db.create_initial_message_tables() # Erase the tables it has on init, and move current month back one @@ -117,9 +117,9 @@ def test_update_rotating_tables_month_end(self): month=next_month, day=1) - settings = AutopushConfig( + conf = AutopushConfig( hostname="example.com", resolve_hostname=True) - db = DatabaseManager.from_config(settings) + db = DatabaseManager.from_config(conf) db._tomorrow = Mock(return_value=tomorrow) db.create_initial_message_tables() @@ -128,7 +128,7 @@ def test_update_rotating_tables_month_end(self): # Grab next month's table name and remove it next_month = get_rotating_message_table( - settings.message_table.tablename, + conf.message_table.tablename, delta=1 ) db.message_tables.pop(next_month.table_name) @@ -145,9 +145,9 @@ def check_tables(result): def test_update_not_needed(self): from autopush.db import get_month - settings = AutopushConfig( + conf = AutopushConfig( hostname="google.com", resolve_hostname=True) - db = DatabaseManager.from_config(settings) + db = DatabaseManager.from_config(conf) db.create_initial_message_tables() # Erase the tables it has on init, and move current month back one @@ -330,10 +330,10 @@ def test_memusage(self): @patch('hyper.tls', spec=hyper.tls) def test_client_certs_parse(self, mock): - settings = AutopushConfig.from_argparse(self.TestArg) - eq_(settings.client_certs["1A:"*31 + "F9"], 'partner1') - eq_(settings.client_certs["2B:"*31 + "E8"], 'partner2') - eq_(settings.client_certs["3C:"*31 + "D7"], 'partner2') + conf = AutopushConfig.from_argparse(self.TestArg) + eq_(conf.client_certs["1A:"*31 + "F9"], 'partner1') + eq_(conf.client_certs["2B:"*31 + "E8"], 'partner2') + eq_(conf.client_certs["3C:"*31 + "D7"], 'partner2') def test_bad_client_certs(self): cert = self.TestArg._client_certs['partner1'][0] @@ -355,20 +355,20 @@ def test_bad_client_certs(self): @patch('autopush.router.apns2.HTTP20Connection', spec=hyper.HTTP20Connection) @patch('hyper.tls', spec=hyper.tls) - def test_settings(self, *args): - settings = AutopushConfig.from_argparse(self.TestArg) - app = EndpointApplication(settings) + def test_conf(self, *args): + conf = AutopushConfig.from_argparse(self.TestArg) + app = EndpointApplication(conf) # verify that the hostname is what we said. - eq_(settings.hostname, self.TestArg.hostname) + eq_(conf.hostname, self.TestArg.hostname) eq_(app.routers["gcm"].router_conf['collapsekey'], "collapse") eq_(app.routers["apns"].router_conf['firefox']['cert'], "cert.file") eq_(app.routers["apns"].router_conf['firefox']['key'], "key.file") - eq_(settings.wake_timeout, 10) + eq_(conf.wake_timeout, 10) def test_bad_senders(self): old_list = self.TestArg.senderid_list self.TestArg.senderid_list = "{}" - with assert_raises(InvalidSettings): + with assert_raises(InvalidConfig): AutopushConfig.from_argparse(self.TestArg) self.TestArg.senderid_list = old_list @@ -376,11 +376,11 @@ def test_bad_fcm_senders(self): old_auth = self.TestArg.fcm_auth old_senderid = self.TestArg.fcm_senderid self.TestArg.fcm_auth = "" - with assert_raises(InvalidSettings): + with assert_raises(InvalidConfig): AutopushConfig.from_argparse(self.TestArg) self.TestArg.fcm_auth = old_auth self.TestArg.fcm_senderid = "" - with assert_raises(InvalidSettings): + with assert_raises(InvalidConfig): AutopushConfig.from_argparse(self.TestArg) self.TestArg.fcm_senderid = old_senderid @@ -400,5 +400,5 @@ class MockReply: request_mock.return_value = MockReply self.TestArg.no_aws = False - settings = AutopushConfig.from_argparse(self.TestArg) - eq_(settings.ami_id, "ami_123") + conf = AutopushConfig.from_argparse(self.TestArg) + eq_(conf.ami_id, "ami_123") diff --git a/autopush/tests/test_router.py b/autopush/tests/test_router.py index 9cb402a9..f6961d8e 100644 --- a/autopush/tests/test_router.py +++ b/autopush/tests/test_router.py @@ -44,7 +44,7 @@ class RouterInterfaceTestCase(TestCase): def test_not_implemented(self): assert_raises(NotImplementedError, IRouter, None, None) - def init(self, settings, router_conf): + def init(self, conf, router_conf): pass IRouter.__init__ = init ir = IRouter(None, None) @@ -74,7 +74,7 @@ def _waitfor(self, func): @patch('hyper.tls', spec=hyper.tls) def setUp(self, mt, mc): from twisted.logger import Logger - settings = AutopushConfig( + conf = AutopushConfig( hostname="localhost", statsd_host=None, ) @@ -88,7 +88,7 @@ def setUp(self, mt, mc): } self.mock_connection = mc mc.return_value = mc - self.router = APNSRouter(settings, apns_config, SinkMetrics()) + self.router = APNSRouter(conf, apns_config, SinkMetrics()) self.mock_response = Mock() self.mock_response.status = 200 mc.get_response.return_value = self.mock_response @@ -295,7 +295,7 @@ class GCMRouterTestCase(unittest.TestCase): @patch("gcmclient.gcm.GCM", spec=gcmclient.gcm.GCM) def setUp(self, fgcm): - settings = AutopushConfig( + conf = AutopushConfig( hostname="localhost", statsd_host=None, ) @@ -304,7 +304,7 @@ def setUp(self, fgcm): 'senderIDs': {'test123': {"auth": "12345678abcdefg"}}} self.gcm = fgcm - self.router = GCMRouter(settings, self.gcm_config, SinkMetrics()) + self.router = GCMRouter(conf, self.gcm_config, SinkMetrics()) self.headers = {"content-encoding": "aesgcm", "encryption": "test", "encryption-key": "test"} @@ -339,12 +339,12 @@ def _check_error_call(self, exc, code, response=None): self.flushLoggedErrors() def test_init(self): - settings = AutopushConfig( + conf = AutopushConfig( hostname="localhost", statsd_host=None, ) with assert_raises(IOError): - GCMRouter(settings, {"senderIDs": {}}, SinkMetrics()) + GCMRouter(conf, {"senderIDs": {}}, SinkMetrics()) def test_register(self): router_data = {"token": "test123"} @@ -368,13 +368,13 @@ def test_register_bad(self): @patch("gcmclient.GCM") def test_gcmclient_fail(self, fgcm): fgcm.side_effect = Exception - settings = AutopushConfig( + conf = AutopushConfig( hostname="localhost", statsd_host=None, ) with assert_raises(IOError): GCMRouter( - settings, + conf, {"senderIDs": {"test123": {"auth": "abcd"}}}, SinkMetrics() ) @@ -627,7 +627,7 @@ class FCMRouterTestCase(unittest.TestCase): @patch("pyfcm.FCMNotification", spec=pyfcm.FCMNotification) def setUp(self, ffcm): - settings = AutopushConfig( + conf = AutopushConfig( hostname="localhost", statsd_host=None, ) @@ -636,7 +636,7 @@ def setUp(self, ffcm): 'senderID': 'test123', "auth": "12345678abcdefg"} self.fcm = ffcm - self.router = FCMRouter(settings, self.fcm_config, SinkMetrics()) + self.router = FCMRouter(conf, self.fcm_config, SinkMetrics()) self.headers = {"content-encoding": "aesgcm", "encryption": "test", "encryption-key": "test"} @@ -671,7 +671,7 @@ def _check_error_call(self, exc, code): @patch("pyfcm.FCMNotification", spec=pyfcm.FCMNotification) def test_init(self, ffcm): - settings = AutopushConfig( + conf = AutopushConfig( hostname="localhost", statsd_host=None, ) @@ -681,7 +681,7 @@ def throw_auth(*args, **kwargs): ffcm.side_effect = throw_auth with assert_raises(IOError): - FCMRouter(settings, {}, SinkMetrics()) + FCMRouter(conf, {}, SinkMetrics()) def test_register(self): router_data = {"token": "test123"} @@ -911,7 +911,7 @@ def test_register_invalid_token(self): class SimplePushRouterTestCase(unittest.TestCase): def setUp(self): from twisted.logger import Logger - settings = AutopushConfig( + conf = AutopushConfig( hostname="localhost", statsd_host=None, ) @@ -919,7 +919,7 @@ def setUp(self): db = test_db(metrics=metrics) self.agent_mock = agent = Mock(spec=Agent) - self.router = SimpleRouter(settings, {}, db, agent) + self.router = SimpleRouter(conf, {}, db, agent) self.router.log = Mock(spec=Logger) self.notif = Notification(10, "data", dummy_chid) mock_result = Mock(spec=gcmclient.gcm.Result) @@ -1149,7 +1149,7 @@ def test_amend(self): class WebPushRouterTestCase(unittest.TestCase): def setUp(self): - settings = AutopushConfig( + conf = AutopushConfig( hostname="localhost", statsd_host=None, ) @@ -1162,7 +1162,7 @@ def setUp(self): "crypto-key": "niftykey" } self.agent_mock = agent = Mock(spec=Agent) - self.router = WebPushRouter(settings, {}, db, agent) + self.router = WebPushRouter(conf, {}, db, agent) self.notif = WebPushNotification( uaid=uuid.UUID(dummy_uaid), channel_id=uuid.UUID(dummy_chid), @@ -1179,7 +1179,7 @@ def setUp(self): mock_result.needs_retry.return_value = False self.router_mock = db.router self.message_mock = db.message = Mock(spec=Message) - self.settings = settings + self.conf = conf def test_route_to_busy_node_saves_looks_up_and_sends_check_201(self): self.agent_mock.request.return_value = response_mock = Mock() diff --git a/autopush/tests/test_web_base.py b/autopush/tests/test_web_base.py index 670d8491..cfc98280 100644 --- a/autopush/tests/test_web_base.py +++ b/autopush/tests/test_web_base.py @@ -36,7 +36,7 @@ class TestBase(unittest.TestCase): def setUp(self): from autopush.web.base import BaseWebHandler - settings = AutopushConfig( + conf = AutopushConfig( hostname="localhost", statsd_host=None, ) @@ -46,8 +46,7 @@ def setUp(self): host='example.com:8080') self.base = BaseWebHandler( - EndpointHTTPFactory(settings, db=test_db(SinkMetrics()), - routers=None), + EndpointHTTPFactory(conf, db=test_db(SinkMetrics()), routers=None), self.request_mock ) self.status_mock = self.base.set_status = Mock() diff --git a/autopush/tests/test_web_validation.py b/autopush/tests/test_web_validation.py index 6daae327..b29634fc 100644 --- a/autopush/tests/test_web_validation.py +++ b/autopush/tests/test_web_validation.py @@ -137,7 +137,7 @@ def _make_fut(self): from autopush.web.simplepush import SimplePushRequestSchema schema = SimplePushRequestSchema() schema.context.update( - settings=Mock(), + conf=Mock(), metrics=SinkMetrics(), db=test_db(), routers=Mock(), @@ -157,7 +157,7 @@ def _make_test_data(self, headers=None, body="", path_args=None, def test_valid_data(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -172,7 +172,7 @@ def test_valid_data(self): def test_valid_data_in_body(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -189,7 +189,7 @@ def test_valid_data_in_body(self): def test_valid_version(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -207,7 +207,7 @@ def test_valid_version(self): def test_invalid_router_type(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -223,7 +223,7 @@ def test_invalid_router_type(self): def test_invalid_uaid_not_found(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -245,7 +245,7 @@ def test_invalid_token(self): def throw_item(*args, **kwargs): raise InvalidTokenException("Not found") - schema.context["settings"].parse_endpoint.side_effect = throw_item + schema.context["conf"].parse_endpoint.side_effect = throw_item with assert_raises(InvalidRequest) as cm: schema.load(self._make_test_data()) @@ -254,7 +254,7 @@ def throw_item(*args, **kwargs): def test_invalid_data_size(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -262,7 +262,7 @@ def test_invalid_data_size(self): schema.context["db"].router.get_uaid.return_value = dict( router_type="simplepush", ) - schema.context["settings"].max_data = 1 + schema.context["conf"].max_data = 1 with assert_raises(InvalidRequest) as cm: schema.load(self._make_test_data(body="version=&data=asdfasdf")) @@ -275,7 +275,7 @@ def _make_fut(self): from autopush.web.webpush import WebPushRequestSchema schema = WebPushRequestSchema() schema.context.update( - settings=Mock(), + conf=Mock(), metrics=SinkMetrics(), db=test_db(), routers=Mock(), @@ -295,7 +295,7 @@ def _make_test_data(self, headers=None, body="", path_args=None, def test_valid_data(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -311,7 +311,7 @@ def test_valid_data(self): def test_no_headers(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -331,7 +331,7 @@ def test_no_headers(self): def test_invalid_simplepush_user(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -351,7 +351,7 @@ def test_invalid_token(self): def throw_item(*args, **kwargs): raise InvalidTokenException("Not found") - schema.context["settings"].parse_endpoint.side_effect = throw_item + schema.context["conf"].parse_endpoint.side_effect = throw_item with assert_raises(InvalidRequest) as cm: schema.load(self._make_test_data()) @@ -364,7 +364,7 @@ def test_invalid_fernet_token(self): def throw_item(*args, **kwargs): raise InvalidToken - schema.context["settings"].parse_endpoint.side_effect = throw_item + schema.context["conf"].parse_endpoint.side_effect = throw_item with assert_raises(InvalidRequest) as cm: schema.load(self._make_test_data()) @@ -373,7 +373,7 @@ def throw_item(*args, **kwargs): def test_invalid_uaid_not_found(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -391,7 +391,7 @@ def throw_item(*args, **kwargs): def test_critical_failure(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -408,7 +408,7 @@ def test_critical_failure(self): def test_invalid_header_combo(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -432,7 +432,7 @@ def test_invalid_header_combo(self): def test_invalid_header_combo_04(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -459,7 +459,7 @@ def test_invalid_header_combo_04(self): def test_missing_encryption_salt(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -484,7 +484,7 @@ def test_missing_encryption_salt(self): def test_missing_encryption_salt_04(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -509,7 +509,7 @@ def test_missing_encryption_salt_04(self): def test_missing_encryption_key_dh(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -534,7 +534,7 @@ def test_missing_encryption_key_dh(self): def test_missing_crypto_key_dh(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -560,7 +560,7 @@ def test_missing_crypto_key_dh(self): def test_invalid_data_size(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -570,7 +570,7 @@ def test_invalid_data_size(self): uaid=dummy_uaid, router_data=dict(creds=dict(senderID="bogus")), ) - schema.context["settings"].max_data = 1 + schema.context["conf"].max_data = 1 with assert_raises(InvalidRequest) as cm: schema.load(self._make_test_data( @@ -584,7 +584,7 @@ def test_invalid_data_size(self): def test_invalid_data_must_have_crypto_headers(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -601,7 +601,7 @@ def test_invalid_data_must_have_crypto_headers(self): def test_valid_data_crypto_padding_stripped(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -628,7 +628,7 @@ def test_valid_data_crypto_padding_stripped(self): def test_invalid_dh_value_for_01_crypto(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -659,7 +659,7 @@ def test_invalid_dh_value_for_01_crypto(self): def test_invalid_vapid_crypto_header(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -687,7 +687,7 @@ def test_invalid_vapid_crypto_header(self): def test_invalid_topic(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -728,7 +728,7 @@ def test_invalid_topic(self): def test_no_current_month(self): schema = self._make_fut() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -750,7 +750,7 @@ def test_no_current_month(self): def test_old_current_month(self): schema = self._make_fut() schema.context["db"].message_tables = dict() - schema.context["settings"].parse_endpoint.return_value = dict( + schema.context["conf"].parse_endpoint.return_value = dict( uaid=dummy_uaid, chid=dummy_chid, public_key="", @@ -775,14 +775,14 @@ class TestWebPushRequestSchemaUsingVapid(unittest.TestCase): def _make_fut(self): from autopush.config import AutopushConfig from autopush.web.webpush import WebPushRequestSchema - settings = AutopushConfig( + conf = AutopushConfig( hostname="localhost", statsd_host=None, ) db = test_db() schema = WebPushRequestSchema() schema.context.update( - settings=settings, + conf=conf, metrics=SinkMetrics(), db=db, routers=Mock(), @@ -793,7 +793,7 @@ def _make_fut(self): uaid=dummy_uaid, router_data=dict(creds=dict(senderID="bogus")), ) - settings.fernet = self.fernet_mock = Mock() + conf.fernet = self.fernet_mock = Mock() return schema def _make_test_data(self, headers=None, body="", path_args=None, @@ -846,7 +846,7 @@ def test_valid_vapid_crypto_header(self): def test_valid_vapid_crypto_header_webpush(self, use_crypto=False): schema = self._make_fut() - schema.context["settings"].use_cryptography = use_crypto + schema.context["conf"].use_cryptography = use_crypto header = {"typ": "JWT", "alg": "ES256"} payload = {"aud": "https://pusher_origin.example.com", @@ -977,7 +977,7 @@ def test_bad_vapid_02_crypto_header(self): def test_invalid_vapid_draft2_crypto_header(self): schema = self._make_fut() - schema.context["settings"].use_cryptography = True + schema.context["conf"].use_cryptography = True header = {"typ": "JWT", "alg": "ES256"} payload = {"aud": "https://pusher_origin.example.com", @@ -1012,7 +1012,7 @@ def test_invalid_vapid_draft2_crypto_header(self): @patch("autopush.web.webpush.extract_jwt") def test_invalid_vapid_crypto_header(self, mock_jwt): schema = self._make_fut() - schema.context["settings"].use_cryptography = True + schema.context["conf"].use_cryptography = True mock_jwt.side_effect = ValueError("Unknown public key " "format specified") @@ -1150,7 +1150,7 @@ def test_invalid_encryption_header(self, mock_jwt): @patch("autopush.web.webpush.extract_jwt") def test_invalid_encryption_jwt(self, mock_jwt): schema = self._make_fut() - schema.context['settings'].use_cryptography = True + schema.context['conf'].use_cryptography = True # use a deeply superclassed error to make sure that it gets picked up. mock_jwt.side_effect = InvalidSignature("invalid signature") @@ -1222,7 +1222,7 @@ def test_invalid_crypto_key_header_content(self, mock_jwt): def test_expired_vapid_header(self): schema = self._make_fut() - schema.context["settings"].use_cryptography = True + schema.context["conf"].use_cryptography = True header = {"typ": "JWT", "alg": "ES256"} payload = {"aud": "https://pusher_origin.example.com", @@ -1289,7 +1289,7 @@ def test_missing_vapid_header(self): def test_bogus_vapid_header(self): schema = self._make_fut() - schema.context["settings"].use_cryptography = True + schema.context["conf"].use_cryptography = True header = {"typ": "JWT", "alg": "ES256"} payload = { diff --git a/autopush/tests/test_web_webpush.py b/autopush/tests/test_web_webpush.py index dad7c5c8..c5ff0873 100644 --- a/autopush/tests/test_web_webpush.py +++ b/autopush/tests/test_web_webpush.py @@ -23,18 +23,18 @@ class TestWebpushHandler(unittest.TestCase): def setUp(self): from autopush.web.webpush import WebPushHandler - self.conf = settings = AutopushConfig( + self.conf = conf = AutopushConfig( hostname="localhost", statsd_host=None, use_cryptography=True, ) - self.fernet_mock = settings.fernet = Mock(spec=Fernet) + self.fernet_mock = conf.fernet = Mock(spec=Fernet) self.db = db = test_db() self.message_mock = db.message = Mock(spec=Message) self.message_mock.all_channels.return_value = (True, [dummy_chid]) - app = EndpointHTTPFactory.for_handler(WebPushHandler, settings, db=db) + app = EndpointHTTPFactory.for_handler(WebPushHandler, conf, db=db) self.wp_router_mock = app.routers["webpush"] = Mock(spec=IRouter) self.client = Client(app) diff --git a/autopush/tests/test_websocket.py b/autopush/tests/test_websocket.py index f9548d4c..ecdc715d 100644 --- a/autopush/tests/test_websocket.py +++ b/autopush/tests/test_websocket.py @@ -100,18 +100,18 @@ def setUp(self): from twisted.logger import Logger twisted.internet.base.DelayedCall.debug = True - self.conf = settings = AutopushConfig( + self.conf = conf = AutopushConfig( hostname="localhost", port=8080, statsd_host=None, env="test", ) - db = DatabaseManager.from_config(settings) + db = DatabaseManager.from_config(conf) self.metrics = db.metrics = Mock(spec=SinkMetrics) db.setup_tables() self.mock_agent = agent = Mock(spec=Agent) - self.factory = PushServerFactory(settings, db, agent, {}) + self.factory = PushServerFactory(conf, db, agent, {}) self.proto = self.factory.buildProtocol(('localhost', 8080)) self.proto._log_exc = False self.proto.log = Mock(spec=Logger) @@ -1914,14 +1914,11 @@ class RouterHandlerTestCase(unittest.TestCase): def setUp(self): twisted.internet.base.DelayedCall.debug = True - self.conf = settings = AutopushConfig( + self.conf = conf = AutopushConfig( hostname="localhost", statsd_host=None, ) - self.app = InternalRouterHTTPFactory.for_handler( - RouterHandler, - settings - ) + self.app = InternalRouterHTTPFactory.for_handler(RouterHandler, conf) self.client = Client(self.app) def url(self, **kwargs): @@ -1955,13 +1952,13 @@ class NotificationHandlerTestCase(unittest.TestCase): def setUp(self): twisted.internet.base.DelayedCall.debug = True - self.conf = settings = AutopushConfig( + self.conf = conf = AutopushConfig( hostname="localhost", statsd_host=None, ) self.app = InternalRouterHTTPFactory.for_handler( NotificationHandler, - settings + conf ) self.client = Client(self.app) diff --git a/autopush/web/base.py b/autopush/web/base.py index e464902a..fceedd46 100644 --- a/autopush/web/base.py +++ b/autopush/web/base.py @@ -60,7 +60,7 @@ def _validate_request(self, request_handler, *args, **kwargs): } schema = self.schema() schema.context.update( - settings=request_handler.conf, + conf=request_handler.conf, metrics=request_handler.metrics, db=request_handler.db, routers=request_handler.routers, diff --git a/autopush/web/message.py b/autopush/web/message.py index 96776157..ff2c59d1 100644 --- a/autopush/web/message.py +++ b/autopush/web/message.py @@ -17,7 +17,7 @@ def extract_data(self, req): try: notif = WebPushNotification.from_message_id( bytes(message_id), - fernet=self.context['settings'].fernet, + fernet=self.context['conf'].fernet, ) except (InvalidToken, InvalidTokenException): raise InvalidRequest("Invalid message ID", diff --git a/autopush/web/registration.py b/autopush/web/registration.py index 0cf8071e..4335a0a4 100644 --- a/autopush/web/registration.py +++ b/autopush/web/registration.py @@ -158,11 +158,11 @@ def validate_auth(self, data): errno=109, headers=request_pref_header) - settings = self.context['settings'] + conf = self.context['conf'] uaid = data["path_kwargs"]["uaid"] - if settings.bear_hash_key: + if conf.bear_hash_key: is_valid = False - for key in settings.bear_hash_key: + for key in conf.bear_hash_key: test_token = generate_hash(key, uaid.hex) is_valid |= constant_time.bytes_eq(bytes(test_token), bytes(auth_token)) diff --git a/autopush/web/simplepush.py b/autopush/web/simplepush.py index 1c0c8781..67ffa161 100644 --- a/autopush/web/simplepush.py +++ b/autopush/web/simplepush.py @@ -35,7 +35,7 @@ class SimplePushSubscriptionSchema(Schema): @pre_load def extract_subscription(self, d): try: - result = self.context["settings"].parse_endpoint( + result = self.context["conf"].parse_endpoint( self.context["metrics"], token=d["token"], version=d["api_ver"], @@ -66,7 +66,7 @@ class SimplePushRequestSchema(Schema): @validates('data') def validate_data(self, value): - max_data = self.context["settings"].max_data + max_data = self.context["conf"].max_data if value and len(value) > max_data: raise InvalidRequest( "Data payload must be smaller than {}".format(max_data), diff --git a/autopush/web/webpush.py b/autopush/web/webpush.py index 93be36ce..70781c7b 100644 --- a/autopush/web/webpush.py +++ b/autopush/web/webpush.py @@ -63,7 +63,7 @@ class WebPushSubscriptionSchema(Schema): @pre_load def extract_subscription(self, d): try: - result = self.context["settings"].parse_endpoint( + result = self.context["conf"].parse_endpoint( self.context["metrics"], token=d["token"], version=d["api_ver"], @@ -340,7 +340,7 @@ class WebPushRequestSchema(Schema): @validates('body') def validate_data(self, value): - max_data = self.context["settings"].max_data + max_data = self.context["conf"].max_data if value and len(value) > max_data: raise InvalidRequest( "Data payload must be smaller than {}".format(max_data), @@ -361,7 +361,7 @@ def validate_auth(self, d): crypto_exceptions = [KeyError, ValueError, TypeError, VapidAuthException] - if self.context['settings'].use_cryptography: + if self.context['conf'].use_cryptography: crypto_exceptions.append(InvalidSignature) else: crypto_exceptions.extend([JOSEError, JWTError, AssertionError]) @@ -382,8 +382,8 @@ def validate_auth(self, d): jwt = extract_jwt( token, public_key, - is_trusted=self.context['settings'].enable_tls_auth, - use_crypto=self.context['settings'].use_cryptography + is_trusted=self.context['conf'].enable_tls_auth, + use_crypto=self.context['conf'].use_cryptography ) except tuple(crypto_exceptions): raise InvalidRequest("Invalid Authorization Header", @@ -436,8 +436,8 @@ def fixup_output(self, d): # Set the notification based on the validated request schema data d["notification"] = WebPushNotification.from_webpush_request_schema( - data=d, fernet=self.context["settings"].fernet, - legacy=self.context["settings"]._notification_legacy, + data=d, fernet=self.context["conf"].fernet, + legacy=self.context["conf"]._notification_legacy, ) return d