def test_load_service_failed(self):
     loader = mock.MagicMock(load=lambda: None)
     with self.assertRaisesRegex(ValueError, u"Failed to load service config"):
         wsgi.add_all(_DummyWsgiApp(),
                      self.PROJECT_ID,
                      mock.MagicMock(spec=client.Client),
                      loader=loader)
Ejemplo n.º 2
0
 def test_load_service_failed(self):
     loader = mock.MagicMock(load=lambda: None)
     with self.assertRaisesRegex(ValueError,
                                 u"Failed to load service config"):
         wsgi.add_all(_DummyWsgiApp(),
                      self.PROJECT_ID,
                      mock.MagicMock(spec=client.Client),
                      loader=loader)
Ejemplo n.º 3
0
 def test_should_send_requests_with_configured_header_api_key(self):
     wrappee = _DummyWsgiApp()
     control_client = mock.MagicMock(spec=client.Client)
     given = {
         u'wsgi.url_scheme': u'http',
         u'PATH_INFO': u'/uvw/method1/with_query_param',
         u'REMOTE_ADDR': u'192.168.0.3',
         u'HTTP_HOST': u'localhost',
         u'HTTP_APIKEYHEADER': u'my-header-value',
         u'HTTP_REFERER': u'example.myreferer.com',
         u'REQUEST_METHOD': u'GET'
     }
     dummy_response = messages.CheckResponse(
         operationId=u'fake_operation_id')
     wrapped = wsgi.add_all(wrappee,
                            self.PROJECT_ID,
                            control_client,
                            loader=service.Loaders.ENVIRONMENT)
     control_client.check.return_value = dummy_response
     wrapped(given, _dummy_start_response)
     expect(control_client.check.called).to(be_true)
     check_request = control_client.check.call_args_list[0].checkRequest
     check_req = control_client.check.call_args[0][0]
     expect(check_req.checkRequest.operation.consumerId).to(
         equal(u'api_key:my-header-value'))
     expect(control_client.report.called).to(be_true)
     report_req = control_client.report.call_args[0][0]
     expect(report_req.reportRequest.operations[0].consumerId).to(
         equal(u'api_key:my-header-value'))
Ejemplo n.º 4
0
 def test_should_send_quota_requests_with_no_param(self):
     wrappee = _DummyWsgiApp()
     control_client = mock.MagicMock(spec=client.Client)
     given = {
         u'wsgi.url_scheme': u'http',
         u'PATH_INFO': u'/uvw/method2/with_no_param',
         u'REMOTE_ADDR': u'192.168.0.3',
         u'HTTP_HOST': u'localhost',
         u'HTTP_REFERER': u'example.myreferer.com',
         u'REQUEST_METHOD': u'GET'}
     dummy_response = sc_messages.CheckResponse(
         operationId=u'fake_operation_id')
     wrapped = wsgi.add_all(wrappee,
                            self.PROJECT_ID,
                            control_client,
                            loader=service.Loaders.ENVIRONMENT)
     control_client.check.return_value = dummy_response
     control_client.allocate_quota.side_effect = lambda req: sc_messages.AllocateQuotaResponse(
         operationId=req.allocateQuotaRequest.allocateOperation.operationId)
     wrapped(given, _dummy_start_response)
     expect(control_client.check.called).to(be_true)
     req = control_client.check.call_args[0][0]
     expect(req.checkRequest.operation.consumerId).to(
         equal(u'project:middleware-with-params'))
     expect(control_client.report.called).to(be_true)
     expect(control_client.allocate_quota.called).to(be_true)
Ejemplo n.º 5
0
 def test_should_not_perform_check_if_needed_api_key_is_missing(self):
     wrappee = _DummyWsgiApp()
     control_client = mock.MagicMock(spec=client.Client)
     given = {
         u'wsgi.url_scheme': u'http',
         u'PATH_INFO': u'/uvw/method_needs_api_key/more_stuff',
         u'REMOTE_ADDR': u'192.168.0.3',
         u'HTTP_HOST': u'localhost',
         u'HTTP_REFERER': u'example.myreferer.com',
         u'REQUEST_METHOD': u'GET'
     }
     dummy_response = sc_messages.CheckResponse(
         operationId=u'fake_operation_id')
     wrapped = wsgi.add_all(wrappee,
                            self.PROJECT_ID,
                            control_client,
                            loader=service.Loaders.ENVIRONMENT)
     control_client.check.return_value = dummy_response
     wrapped(given, _dummy_start_response)
     expect(control_client.check.called).to(be_false)
     expect(control_client.report.called).to(be_true)
     report_req = control_client.report.call_args[0][0]
     expect(report_req.reportRequest.operations[0].consumerId).to(
         equal(u'project:middleware-with-params'))
     expect(control_client.allocate_quota.called).to(be_false)
Ejemplo n.º 6
0
 def test_should_send_report_request_if_check_fails(self):
     wrappee = _DummyWsgiApp()
     control_client = mock.MagicMock(spec=client.Client)
     given = {
         u'wsgi.url_scheme': u'http',
         u'PATH_INFO': u'/any',
         u'REMOTE_ADDR': u'192.168.0.3',
         u'HTTP_HOST': u'localhost',
         u'HTTP_REFERER': u'example.myreferer.com',
         u'REQUEST_METHOD': u'GET'}
     dummy_response = sc_messages.CheckResponse(
         operationId = u'fake_operation_id',
         checkErrors = [
             sc_messages.CheckError(
                 code=sc_messages.CheckError.CodeValueValuesEnum.PROJECT_DELETED)
         ]
     )
     wrapped = wsgi.add_all(wrappee,
                            self.PROJECT_ID,
                            control_client,
                            loader=service.Loaders.SIMPLE)
     control_client.check.return_value = dummy_response
     wrapped(given, _dummy_start_response)
     expect(control_client.check.called).to(be_true)
     expect(control_client.report.called).to(be_true)
     expect(control_client.allocate_quota.called).to(be_false)
Ejemplo n.º 7
0
 def test_load_service_failed(self):
     loader = mock.MagicMock(load=lambda: None)
     result = wsgi.add_all(_DummyWsgiApp(),
                           self.PROJECT_ID,
                           mock.MagicMock(spec=client.Client),
                           loader=loader)
     assert result is wsgi.HTTPServiceUnavailable
Ejemplo n.º 8
0
 def test_should_send_quota_requests_with_no_param(self):
     wrappee = _DummyWsgiApp()
     control_client = mock.MagicMock(spec=client.Client)
     given = {
         u'wsgi.url_scheme': u'http',
         u'PATH_INFO': u'/uvw/method2/with_no_param',
         u'REMOTE_ADDR': u'192.168.0.3',
         u'HTTP_HOST': u'localhost',
         u'HTTP_REFERER': u'example.myreferer.com',
         u'REQUEST_METHOD': u'GET'}
     dummy_response = sc_messages.CheckResponse(
         operationId=u'fake_operation_id')
     wrapped = wsgi.add_all(wrappee,
                            self.PROJECT_ID,
                            control_client,
                            loader=service.Loaders.ENVIRONMENT)
     control_client.check.return_value = dummy_response
     control_client.allocate_quota.side_effect = lambda req: sc_messages.AllocateQuotaResponse(
         operationId=req.allocateQuotaRequest.allocateOperation.operationId)
     wrapped(given, _dummy_start_response)
     expect(control_client.check.called).to(be_true)
     req = control_client.check.call_args[0][0]
     expect(req.checkRequest.operation.consumerId).to(
         equal(u'project:middleware-with-params'))
     expect(control_client.report.called).to(be_true)
     expect(control_client.allocate_quota.called).to(be_true)
Ejemplo n.º 9
0
 def test_should_send_requests_with_default_query_param_api_key(self):
     for default_key in (u'key', u'api_key'):
         wrappee = _DummyWsgiApp()
         control_client = mock.MagicMock(spec=client.Client)
         given = {
             u'wsgi.url_scheme': u'http',
             u'QUERY_STRING': u'%s=my-default-api-key-value' % (default_key,),
             u'PATH_INFO': u'/uvw/method_needs_api_key/with_query_param',
             u'REMOTE_ADDR': u'192.168.0.3',
             u'HTTP_HOST': u'localhost',
             u'HTTP_REFERER': u'example.myreferer.com',
             u'REQUEST_METHOD': u'GET'}
         dummy_response = sc_messages.CheckResponse(
             operationId=u'fake_operation_id')
         wrapped = wsgi.add_all(wrappee,
                                self.PROJECT_ID,
                                control_client,
                                loader=service.Loaders.ENVIRONMENT)
         control_client.check.return_value = dummy_response
         wrapped(given, _dummy_start_response)
         expect(control_client.check.called).to(be_true)
         check_request = control_client.check.call_args_list[0].checkRequest
         check_req = control_client.check.call_args[0][0]
         expect(check_req.checkRequest.operation.consumerId).to(
             equal(u'api_key:my-default-api-key-value'))
         expect(control_client.report.called).to(be_true)
         report_req = control_client.report.call_args[0][0]
         expect(report_req.reportRequest.operations[0].consumerId).to(
             equal(u'api_key:my-default-api-key-value'))
         expect(control_client.allocate_quota.called).to(be_false)
Ejemplo n.º 10
0
 def test_should_send_report_request_if_check_fails(self):
     wrappee = _DummyWsgiApp()
     control_client = mock.MagicMock(spec=client.Client)
     given = {
         u'wsgi.url_scheme': u'http',
         u'PATH_INFO': u'/any',
         u'REMOTE_ADDR': u'192.168.0.3',
         u'HTTP_HOST': u'localhost',
         u'HTTP_REFERER': u'example.myreferer.com',
         u'REQUEST_METHOD': u'GET'}
     dummy_response = sc_messages.CheckResponse(
         operationId = u'fake_operation_id',
         checkErrors = [
             sc_messages.CheckError(
                 code=sc_messages.CheckError.CodeValueValuesEnum.PROJECT_DELETED)
         ]
     )
     wrapped = wsgi.add_all(wrappee,
                            self.PROJECT_ID,
                            control_client,
                            loader=service.Loaders.SIMPLE)
     control_client.check.return_value = dummy_response
     wrapped(given, _dummy_start_response)
     expect(control_client.check.called).to(be_true)
     expect(control_client.report.called).to(be_true)
     expect(control_client.allocate_quota.called).to(be_false)
Ejemplo n.º 11
0
 def test_should_send_requests_with_default_query_param_api_key(self):
     for default_key in (u'key', u'api_key'):
         wrappee = _DummyWsgiApp()
         control_client = mock.MagicMock(spec=client.Client)
         given = {
             u'wsgi.url_scheme': u'http',
             u'QUERY_STRING': u'%s=my-default-api-key-value' % (default_key,),
             u'PATH_INFO': u'/uvw/method_needs_api_key/with_query_param',
             u'REMOTE_ADDR': u'192.168.0.3',
             u'HTTP_HOST': u'localhost',
             u'HTTP_REFERER': u'example.myreferer.com',
             u'REQUEST_METHOD': u'GET'}
         dummy_response = sc_messages.CheckResponse(
             operationId=u'fake_operation_id')
         wrapped = wsgi.add_all(wrappee,
                                self.PROJECT_ID,
                                control_client,
                                loader=service.Loaders.ENVIRONMENT)
         control_client.check.return_value = dummy_response
         wrapped(given, _dummy_start_response)
         expect(control_client.check.called).to(be_true)
         check_request = control_client.check.call_args_list[0].checkRequest
         check_req = control_client.check.call_args[0][0]
         expect(check_req.checkRequest.operation.consumerId).to(
             equal(u'api_key:my-default-api-key-value'))
         expect(control_client.report.called).to(be_true)
         report_req = control_client.report.call_args[0][0]
         expect(report_req.reportRequest.operations[0].consumerId).to(
             equal(u'api_key:my-default-api-key-value'))
         expect(control_client.allocate_quota.called).to(be_false)
 def test_should_send_requests_with_configured_header_api_key(self):
     wrappee = _DummyWsgiApp()
     control_client = mock.MagicMock(spec=client.Client)
     given = {
         u'wsgi.url_scheme': u'http',
         u'PATH_INFO': u'/uvw/method1/with_query_param',
         u'REMOTE_ADDR': u'192.168.0.3',
         u'HTTP_HOST': u'localhost',
         u'HTTP_APIKEYHEADER': u'my-header-value',
         u'HTTP_REFERER': u'example.myreferer.com',
         u'REQUEST_METHOD': u'GET'}
     dummy_response = messages.CheckResponse(operationId=u'fake_operation_id')
     wrapped = wsgi.add_all(wrappee,
                            self.PROJECT_ID,
                            control_client,
                            loader=service.Loaders.ENVIRONMENT)
     control_client.check.return_value = dummy_response
     wrapped(given, _dummy_start_response)
     expect(control_client.check.called).to(be_true)
     check_request = control_client.check.call_args_list[0].checkRequest
     check_req = control_client.check.call_args[0][0]
     expect(check_req.checkRequest.operation.consumerId).to(
         equal(u'api_key:my-header-value'))
     expect(control_client.report.called).to(be_true)
     report_req = control_client.report.call_args[0][0]
     expect(report_req.reportRequest.operations[0].consumerId).to(
         equal(u'api_key:my-header-value'))
Ejemplo n.º 13
0
def api_server(api_services, **kwargs):
    """Create an api_server.

  The primary function of this method is to set up the WSGIApplication
  instance for the service handlers described by the services passed in.
  Additionally, it registers each API in ApiConfigRegistry for later use
  in the BackendService.getApiConfigs() (API config enumeration service).
  It also configures service control.

  Args:
    api_services: List of protorpc.remote.Service classes implementing the API
      or a list of _ApiDecorator instances that decorate the service classes
      for an API.
    **kwargs: Passed through to protorpc.wsgi.service.service_handlers except:
      protocols - ProtoRPC protocols are not supported, and are disallowed.

  Returns:
    A new WSGIApplication that serves the API backend and config registry.

  Raises:
    TypeError: if protocols are configured (this feature is not supported).
  """
    # Disallow protocol configuration for now, Lily is json-only.
    if 'protocols' in kwargs:
        raise TypeError(
            "__init__() got an unexpected keyword argument 'protocols'")

    # Construct the api serving app
    apis_app = _ApiServer(api_services, **kwargs)
    dispatcher = endpoints_dispatcher.EndpointsDispatcherMiddleware(apis_app)

    # Determine the service name
    service_name = os.environ.get('ENDPOINTS_SERVICE_NAME')
    if not service_name:
        _logger.warn(
            'Did not specify the ENDPOINTS_SERVICE_NAME environment'
            ' variable so service control is disabled.  Please specify'
            ' the name of service in ENDPOINTS_SERVICE_NAME to enable'
            ' it.')
        return dispatcher

    # If we're using a local server, just return the dispatcher now to bypass
    # control client.
    if control_wsgi.running_on_devserver():
        _logger.warn(
            'Running on local devserver, so service control is disabled.')
        return dispatcher

    # The DEFAULT 'config' should be tuned so that it's always OK for python
    # App Engine workloads.  The config can be adjusted, but that's probably
    # unnecessary on App Engine.
    controller = control_client.Loaders.DEFAULT.load(service_name)

    # Start the GAE background thread that powers the control client's cache.
    control_client.use_gae_thread()
    controller.start()

    return control_wsgi.add_all(dispatcher, app_identity.get_application_id(),
                                controller)
def api_server(api_services, **kwargs):
  """Create an api_server.

  The primary function of this method is to set up the WSGIApplication
  instance for the service handlers described by the services passed in.
  Additionally, it registers each API in ApiConfigRegistry for later use
  in the BackendService.getApiConfigs() (API config enumeration service).
  It also configures service control.

  Args:
    api_services: List of protorpc.remote.Service classes implementing the API
      or a list of _ApiDecorator instances that decorate the service classes
      for an API.
    **kwargs: Passed through to protorpc.wsgi.service.service_handlers except:
      protocols - ProtoRPC protocols are not supported, and are disallowed.

  Returns:
    A new WSGIApplication that serves the API backend and config registry.

  Raises:
    TypeError: if protocols are configured (this feature is not supported).
  """
  # Disallow protocol configuration for now, Lily is json-only.
  if 'protocols' in kwargs:
    raise TypeError("__init__() got an unexpected keyword argument 'protocols'")

  # Construct the api serving app
  apis_app = _ApiServer(api_services, **kwargs)
  dispatcher = endpoints_dispatcher.EndpointsDispatcherMiddleware(apis_app)

  # Determine the service name
  service_name = os.environ.get('ENDPOINTS_SERVICE_NAME')
  if not service_name:
    _logger.warn('Did not specify the ENDPOINTS_SERVICE_NAME environment'
                 ' variable so service control is disabled.  Please specify'
                 ' the name of service in ENDPOINTS_SERVICE_NAME to enable'
                 ' it.')
    return dispatcher

  # If we're using a local server, just return the dispatcher now to bypass
  # control client.
  if control_wsgi.running_on_devserver():
    _logger.warn('Running on local devserver, so service control is disabled.')
    return dispatcher

  # The DEFAULT 'config' should be tuned so that it's always OK for python
  # App Engine workloads.  The config can be adjusted, but that's probably
  # unnecessary on App Engine.
  controller = control_client.Loaders.DEFAULT.load(service_name)

  # Start the GAE background thread that powers the control client's cache.
  control_client.use_gae_thread()
  controller.start()

  return control_wsgi.add_all(
      dispatcher,
      app_identity.get_application_id(),
      controller)
Ejemplo n.º 15
0
 def test_load_service_failed(self):
     loader = mock.MagicMock(load=lambda: None)
     result = wsgi.add_all(_DummyWsgiApp(),
                           self.PROJECT_ID,
                           mock.MagicMock(spec=client.Client),
                           loader=loader)
     assert isinstance(result, wsgi.HTTPServiceUnavailable)
     test_app = webtest.TestApp(result)
     resp = test_app.get('/any', expect_errors=True)
     assert resp.status_code == 503
Ejemplo n.º 16
0
 def test_load_service_failed(self):
     loader = mock.MagicMock(load=lambda: None)
     result = wsgi.add_all(_DummyWsgiApp(),
                           self.PROJECT_ID,
                           mock.MagicMock(spec=client.Client),
                           loader=loader)
     assert isinstance(result, wsgi.HTTPServiceUnavailable)
     test_app = webtest.TestApp(result)
     resp = test_app.get('/any', expect_errors=True)
     assert resp.status_code == 503
 def test_should_not_perform_check_if_needed_api_key_is_missing(self):
     wrappee = _DummyWsgiApp()
     control_client = mock.MagicMock(spec=client.Client)
     given = {
         u'wsgi.url_scheme': u'http',
         u'PATH_INFO': u'/uvw/method_needs_api_key/more_stuff',
         u'REMOTE_ADDR': u'192.168.0.3',
         u'HTTP_HOST': u'localhost',
         u'HTTP_REFERER': u'example.myreferer.com',
         u'REQUEST_METHOD': u'GET'}
     dummy_response = messages.CheckResponse(operationId=u'fake_operation_id')
     wrapped = wsgi.add_all(wrappee,
                            self.PROJECT_ID,
                            control_client,
                            loader=service.Loaders.ENVIRONMENT)
     control_client.check.return_value = dummy_response
     wrapped(given, _dummy_start_response)
     expect(control_client.check.called).to(be_false)
     expect(control_client.report.called).to(be_true)
     report_req = control_client.report.call_args[0][0]
     expect(report_req.reportRequest.operations[0].consumerId).to(
         equal(u'project:middleware-with-params'))
Ejemplo n.º 18
0
def wrapped_app(project_id, control_client, service_config_loader):
    return wsgi.add_all(DEBUG_APP, project_id, control_client, loader=service_config_loader)
Ejemplo n.º 19
0
def wrapped_app(project_id, control_client, service_config_loader):
    return wsgi.add_all(DEBUG_APP,
                        project_id,
                        control_client,
                        loader=service_config_loader)