Ejemplo n.º 1
0
 def send_email(self, log_lines):
     post_result = requests.post(
         "https://api.mailgun.net/v3/" + self.mailgun_domain_name + "/messages",
         auth=("api", self.mailgun_api_key),
         data={"from": "Marvin <mailgun@" + self.mailgun_domain_name + ">",
               "to": [self.email_address],
               "subject": "Marvin log",
               "text": log_lines})
     if post_result.status_code == 200:
         return NotificationEvent(NotificationEventType.EMAIL_SENT, super().NOTIFICATION_LOG_MESSAGE + self.NOTIFICATION_TYPE)
     else:
         return NotificationEvent(NotificationEventType.EMAIL_FAILURE, super().NOTIFICATION_FAILED_LOG_MESSAGE + self.NOTIFICATION_TYPE)
Ejemplo n.º 2
0
def test_perform_http_call(method, method_config, netloc, initialized_db):
    repository = Repository("buynlarge", "orgrepo")
    notification = Notification(
        uuid="fake",
        event_name="repo_push",
        method_name=method.method_name(),
        event_config_dict={},
        method_config_dict=method_config,
        repository=repository,
    )

    event_handler = NotificationEvent.get_event("repo_push")
    sample_data = event_handler.get_sample_data(repository.namespace_name,
                                                repository.name, {})

    url_hit = [False]

    @urlmatch(netloc=netloc)
    def url_handler(_, __):
        url_hit[0] = True
        return ""

    with HTTMock(url_handler):
        method().perform(notification, event_handler, {
            "event_data": sample_data,
            "performer_data": {}
        })

    assert url_hit[0]
Ejemplo n.º 3
0
def test_perform_email(initialized_db):
    repository = Repository("buynlarge", "orgrepo")
    notification = Notification(
        uuid="fake",
        event_name="repo_push",
        method_name="email",
        event_config_dict={},
        method_config_dict={"email": "*****@*****.**"},
        repository=repository,
    )

    event_handler = NotificationEvent.get_event("repo_push")
    sample_data = event_handler.get_sample_data(repository.namespace_name,
                                                repository.name, {})

    mock = Mock()

    def get_mock(*args, **kwargs):
        return mock

    with patch("notifications.notificationmethod.Message", get_mock):
        method = EmailMethod()
        method.perform(notification, event_handler, {
            "event_data": sample_data,
            "performer_data": {}
        })

    mock.send.assert_called_once()
Ejemplo n.º 4
0
def test_perform_quay_notification(target, expected_users, initialized_db):
    repository = Repository("buynlarge", "orgrepo")
    notification = Notification(
        uuid="fake",
        event_name="repo_push",
        method_name="quay",
        event_config_dict={},
        method_config_dict={"target": target},
        repository=repository,
    )

    event_handler = NotificationEvent.get_event("repo_push")

    sample_data = event_handler.get_sample_data(repository.namespace_name,
                                                repository.name, {})

    method = QuayNotificationMethod()
    method.perform(notification, event_handler, {"event_data": sample_data})

    # Ensure that the notification was written for all the expected users.
    if target["kind"] != "team":
        user = model.user.get_namespace_user(target["name"])
        assert len(
            model.notification.list_notifications(user,
                                                  kind_name="repo_push")) > 0
Ejemplo n.º 5
0
    def process_queue_item(self, job_details):
        notification = model.get_enabled_notification(
            job_details['notification_uuid'])
        if notification is None:
            return

        event_name = notification.event_name
        method_name = notification.method_name

        try:
            event_handler = NotificationEvent.get_event(event_name)
            method_handler = NotificationMethod.get_method(method_name)
        except InvalidNotificationMethodException as ex:
            logger.exception('Cannot find notification method: %s', ex.message)
            raise JobException('Cannot find notification method: %s' %
                               ex.message)
        except InvalidNotificationEventException as ex:
            logger.exception('Cannot find notification event: %s', ex.message)
            raise JobException('Cannot find notification event: %s' %
                               ex.message)

        if event_handler.should_perform(job_details['event_data'],
                                        notification):
            try:
                method_handler.perform(notification, event_handler,
                                       job_details)
                model.reset_number_of_failures_to_zero(notification)
            except (JobException, KeyError) as exc:
                model.increment_notification_failure_count(notification)
                raise exc
Ejemplo n.º 6
0
 def send_pushover(self, log_lines):
     conn = http.client.HTTPSConnection("api.pushover.net:443")
     conn.request(
         "POST", "/1/messages.json",
         urllib.parse.urlencode({
             "token": self.pushover_app_token,
             "user": self.pushover_user_key,
             "message": log_lines,
         }), {"Content-type": "application/x-www-form-urlencoded"})
     if conn.getresponse().status == 200:
         return NotificationEvent(
             NotificationEventType.PUSHOVER_SENT,
             super().NOTIFICATION_LOG_MESSAGE + self.NOTIFICATION_TYPE)
     else:
         return NotificationEvent(
             NotificationEventType.PUSHOVER_FAILURE,
             super().NOTIFICATION_FAILED_LOG_MESSAGE +
             self.NOTIFICATION_TYPE)
Ejemplo n.º 7
0
def test_build_notification(event_name, initialized_db):
    # Create the notification event.
    found = NotificationEvent.get_event(event_name)
    sample_data = found.get_sample_data("foo", "bar", {"level": "low"})

    # Make sure all calls succeed.
    notification_data = {
        "performer_data": {},
    }

    found.get_level(sample_data, notification_data)
    found.get_summary(sample_data, notification_data)
    found.get_message(sample_data, notification_data)
Ejemplo n.º 8
0
def test_build_notification(event_name, initialized_db):
    # Create the notification event.
    found = NotificationEvent.get_event(event_name)
    sample_data = found.get_sample_data('foo', 'bar', {'level': 'low'})

    # Make sure all calls succeed.
    notification_data = {
        'performer_data': {},
    }

    found.get_level(sample_data, notification_data)
    found.get_summary(sample_data, notification_data)
    found.get_message(sample_data, notification_data)
Ejemplo n.º 9
0
def test_perform_quay_notification(target, expected_users, initialized_db):
  repository = Repository('buynlarge', 'orgrepo')
  notification = Notification(uuid='fake', event_name='repo_push', method_name='quay',
                              event_config_dict={}, method_config_dict={'target': target},
                              repository=repository)

  event_handler = NotificationEvent.get_event('repo_push')

  sample_data = event_handler.get_sample_data(repository.namespace_name, repository.name, {})

  method = QuayNotificationMethod()
  method.perform(notification, event_handler, {'event_data': sample_data})

  # Ensure that the notification was written for all the expected users.
  if target['kind'] != 'team':
    user = model.user.get_namespace_user(target['name'])
    assert len(model.notification.list_notifications(user, kind_name='repo_push')) > 0
Ejemplo n.º 10
0
def test_perform_email(initialized_db):
  repository = Repository('buynlarge', 'orgrepo')
  notification = Notification(uuid='fake', event_name='repo_push', method_name='email',
                              event_config_dict={}, method_config_dict={'email': '*****@*****.**'},
                              repository=repository)

  event_handler = NotificationEvent.get_event('repo_push')
  sample_data = event_handler.get_sample_data(repository.namespace_name, repository.name, {})

  mock = Mock()
  def get_mock(*args, **kwargs):
    return mock

  with patch('notifications.notificationmethod.Message', get_mock):
    method = EmailMethod()
    method.perform(notification, event_handler, {'event_data': sample_data, 'performer_data': {}})

  mock.send.assert_called_once()
Ejemplo n.º 11
0
def test_perform_http_call(method, method_config, netloc, initialized_db):
  repository = Repository('buynlarge', 'orgrepo')
  notification = Notification(uuid='fake', event_name='repo_push', method_name=method.method_name(),
                              event_config_dict={}, method_config_dict=method_config,
                              repository=repository)

  event_handler = NotificationEvent.get_event('repo_push')
  sample_data = event_handler.get_sample_data(repository.namespace_name, repository.name, {})

  url_hit = [False]
  @urlmatch(netloc=netloc)
  def url_handler(_, __):
    url_hit[0] = True
    return ''

  with HTTMock(url_handler):
    method().perform(notification, event_handler, {'event_data': sample_data, 'performer_data': {}})

  assert url_hit[0]
    def queue_test_notification(self, uuid):
        try:
            notification = model.notification.get_repo_notification(uuid)
        except InvalidNotificationException:
            return None

        event_config = json.loads(notification.event_config_json or "{}")
        event_info = NotificationEvent.get_event(notification.event.name)
        sample_data = event_info.get_sample_data(
            notification.repository.namespace_user.username,
            notification.repository.name,
            event_config,
        )
        notification_data = build_notification_data(notification, sample_data)
        notification_queue.put(
            [
                notification.repository.namespace_user.username,
                notification.uuid,
                notification.event.name,
            ],
            json.dumps(notification_data),
        )
        return self._notification(notification)
Ejemplo n.º 13
0
def test_create_notifications(event_kind):
    assert NotificationEvent.get_event(event_kind) is not None
Ejemplo n.º 14
0
import pytest

from notifications.notificationevent import (
    BuildSuccessEvent,
    NotificationEvent,
    VulnerabilityFoundEvent,
)
from util.morecollections import AttrDict

from test.fixtures import *


@pytest.mark.parametrize("event_kind", NotificationEvent.event_names())
def test_create_notifications(event_kind):
    assert NotificationEvent.get_event(event_kind) is not None


@pytest.mark.parametrize("event_name", NotificationEvent.event_names())
def test_build_notification(event_name, initialized_db):
    # Create the notification event.
    found = NotificationEvent.get_event(event_name)
    sample_data = found.get_sample_data("foo", "bar", {"level": "low"})

    # Make sure all calls succeed.
    notification_data = {
        "performer_data": {},
    }

    found.get_level(sample_data, notification_data)
    found.get_summary(sample_data, notification_data)
    found.get_message(sample_data, notification_data)
Ejemplo n.º 15
0
import pytest

from notifications.notificationevent import (BuildSuccessEvent,
                                             NotificationEvent,
                                             VulnerabilityFoundEvent)
from util.morecollections import AttrDict

from test.fixtures import *


@pytest.mark.parametrize('event_kind', NotificationEvent.event_names())
def test_create_notifications(event_kind):
    assert NotificationEvent.get_event(event_kind) is not None


@pytest.mark.parametrize('event_name', NotificationEvent.event_names())
def test_build_notification(event_name, initialized_db):
    # Create the notification event.
    found = NotificationEvent.get_event(event_name)
    sample_data = found.get_sample_data('foo', 'bar', {'level': 'low'})

    # Make sure all calls succeed.
    notification_data = {
        'performer_data': {},
    }

    found.get_level(sample_data, notification_data)
    found.get_summary(sample_data, notification_data)
    found.get_message(sample_data, notification_data)