Slack spruce up (#394)

* Formatting slack message.

* Tweaking tests.
This commit is contained in:
kevgliss 2016-07-06 10:27:13 -07:00 committed by GitHub
parent d4732d3ab0
commit 74bf54cb8f
5 changed files with 93 additions and 15 deletions

View File

@ -45,7 +45,7 @@ class ExpirationNotificationPlugin(NotificationPlugin):
] ]
@property @property
def plugin_options(self): def options(self):
return list(self.default_options) + self.additional_options return list(self.default_options) + self.additional_options
def send(self): def send(self):

View File

@ -5,7 +5,10 @@
:license: Apache, see LICENSE for more details. :license: Apache, see LICENSE for more details.
.. moduleauthor:: Harm Weites <harm@weites.com> .. moduleauthor:: Harm Weites <harm@weites.com>
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
""" """
import json
import arrow
from flask import current_app from flask import current_app
from lemur.plugins.bases import ExpirationNotificationPlugin from lemur.plugins.bases import ExpirationNotificationPlugin
from lemur.plugins import lemur_slack as slack from lemur.plugins import lemur_slack as slack
@ -13,10 +16,42 @@ from lemur.plugins import lemur_slack as slack
import requests import requests
def find_value(name, options): def create_certificate_url(name):
for o in options: return 'https://{hostname}/#/certificates/{name}'.format(
if o['name'] == name: hostname=current_app.config.get('LEMUR_HOSTNAME'),
return o['value'] name=name
)
def create_expiration_attachments(messages):
attachments = []
for message in messages:
attachments.append({
'title': message['name'],
'title_link': create_certificate_url(message['name']),
'color': 'danger',
'fallback': '',
'fields': [
{
'title': 'Owner',
'value': message['owner'],
'short': True
},
{
'title': 'Expires',
'value': arrow.get(message['not_after']).format('dddd, MMMM D, YYYY'),
'short': True
},
{
'title': 'Endpoints Detected',
'value': len(message['endpoints']),
'short': True
}
],
'text': '',
'mrkdwn_in': ['text']
})
return attachments
class SlackNotificationPlugin(ExpirationNotificationPlugin): class SlackNotificationPlugin(ExpirationNotificationPlugin):
@ -38,9 +73,9 @@ class SlackNotificationPlugin(ExpirationNotificationPlugin):
}, { }, {
'name': 'username', 'name': 'username',
'type': 'str', 'type': 'str',
'required': True,
'validation': '^.+$', 'validation': '^.+$',
'helpMessage': 'The great storyteller', 'helpMessage': 'The great storyteller',
'default': 'Lemur'
}, { }, {
'name': 'recipients', 'name': 'recipients',
'type': 'str', 'type': 'str',
@ -50,19 +85,25 @@ class SlackNotificationPlugin(ExpirationNotificationPlugin):
}, },
] ]
@staticmethod def send(self, event_type, message, targets, options, **kwargs):
def send(event_type, message, targets, options, **kwargs):
""" """
A typical check can be performed using the notify command: A typical check can be performed using the notify command:
`lemur notify` `lemur notify`
""" """
msg = 'Certificate expiry pending for certificate:\n*%s*\nCurrent state is: _%s_' % (message[0]['name'], event_type) if event_type == 'expiration':
body = '{"text": "%s", "channel": "%s", "username": "%s"}' % (msg, find_value('recipients', options), find_value('username', options)) attachments = create_expiration_attachments(message)
current_app.logger.info("Sending message to Slack: %s" % body) if not attachments:
current_app.logger.debug("Sending data to Slack endpoint at %s" % find_value('webhook', options)) raise Exception('Unable to create message attachments')
r = requests.post(find_value('webhook', options), body) body = {
'text': 'Lemur Expiration Notification',
'attachments': attachments,
'channel': self.get_option('recipients', options),
'username': self.get_option('username', options)
}
r = requests.post(self.get_option('webhook', options), json.dumps(body))
if r.status_code not in [200]: if r.status_code not in [200]:
current_app.logger.error("Slack response: %s" % r.status_code) raise Exception('Failed to send message')
raise current_app.logger.error("Slack response: {0} Message Body: {1}".format(r.status_code, body))

View File

@ -0,0 +1 @@
from lemur.tests.conftest import * # noqa

View File

@ -0,0 +1,34 @@
def test_formatting(certificate):
from lemur.plugins.lemur_slack.plugin import create_expiration_attachments
from lemur.notifications.service import _get_message_data
data = [_get_message_data(certificate)]
attachments = [
{
'title': 'certificate0',
'color': 'danger',
'fields': [
{
'short': True,
'value': 'joe@example.com',
'title': 'Owner'
},
{
'short': True,
'value': u'Wednesday, January 1, 2020',
'title': 'Expires'
}, {
'short': True,
'value': 0,
'title': 'Endpoints Detected'
}
],
'title_link': 'https://lemur.example.com/#/certificates/certificate0',
'mrkdwn_in': ['text'],
'text': '',
'fallback': ''
}
]
assert attachments == create_expiration_attachments(data)

View File

@ -33,6 +33,8 @@ LEMUR_RESTRICTED_DOMAINS = []
LEMUR_EMAIL = '' LEMUR_EMAIL = ''
LEMUR_SECURITY_TEAM_EMAIL = ['security@example.com'] LEMUR_SECURITY_TEAM_EMAIL = ['security@example.com']
LEMUR_HOSTNAME = 'lemur.example.com'
# Logging # Logging
LOG_LEVEL = "DEBUG" LOG_LEVEL = "DEBUG"