Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Alert - Support for authentication when calling receiver endpoint. #560

Open
wants to merge 27 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
c39273f
added support for authentication in the alert (both basic and bearer).
andreee94 Feb 24, 2022
1fa0693
added unit tests for alert authentication
andreee94 Feb 24, 2022
bd88ef3
updated documentation for alert authentication
andreee94 Feb 24, 2022
1c3d61e
fixed yq command in makefile
andreee94 Feb 24, 2022
3de5ef9
added support for authentication in the alert (both basic and bearer).
andreee94 Feb 24, 2022
51ea8a4
added unit tests for alert authentication
andreee94 Feb 24, 2022
9a10f8f
updated documentation for alert authentication
andreee94 Feb 24, 2022
d771c5e
Merge remote-tracking branch 'refs/remotes/origin/feat/alert-authenti…
andreee94 Feb 28, 2022
7613ba3
Improved alert class accordingly to the pull request
andreee94 Feb 28, 2022
3d383a5
Updated alert documentation
andreee94 Feb 28, 2022
7957567
Renamed authorization_prefix to authentication_scheme in the alert_sc…
andreee94 Feb 28, 2022
f96b907
Testing authentication_scheme validation in alert.
andreee94 Feb 28, 2022
be8c718
added support for authentication in the alert (both basic and bearer).
andreee94 Feb 24, 2022
cec1a0f
added unit tests for alert authentication
andreee94 Feb 24, 2022
8050102
updated documentation for alert authentication
andreee94 Feb 24, 2022
c04c902
Improved alert class accordingly to the pull request
andreee94 Feb 28, 2022
d98c6bd
Updated alert documentation
andreee94 Feb 28, 2022
a34506d
Renamed authorization_prefix to authentication_scheme in the alert_sc…
andreee94 Feb 28, 2022
14f58cd
Testing authentication_scheme validation in alert.
andreee94 Feb 28, 2022
dffbd88
Merge remote-tracking branch 'refs/remotes/origin/feat/alert-authenti…
andreee94 Mar 1, 2022
b3a54c0
Code updated to fix pylint suggestions, and other minor changes.
andreee94 Mar 1, 2022
0f26f6d
Embracing the EAFP paradigm.
andreee94 Mar 2, 2022
0a8b73b
Merge branch 'develop' into feat/alert-authentication
andreee94 Mar 2, 2022
b207360
Merge branch 'develop' into feat/alert-authentication
andreee94 Mar 3, 2022
826c78e
Moving the alert webhook authentication documentation in the addition…
andreee94 Mar 5, 2022
f4d02bb
Improved the helm chart to reference existing secrets and config maps…
andreee94 Mar 5, 2022
6aa67ab
Merge remote-tracking branch 'refs/remotes/origin/feat/alert-authenti…
andreee94 Mar 5, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
174 changes: 172 additions & 2 deletions connaisseur/alert.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,169 @@ def alerting_required(self, event_category: str) -> bool:
return bool(self.config.get(event_category))


class AlertReceiverAuthentication:
"""
Class to store authentication information for securely sending events to the alert receiver.
"""

authentication_config: dict = None
authentication_scheme: str = None

class AlertReceiverAuthenticationInterface:
def __init__(self, alert_receiver_config: dict, authentication_config_key: str):
if authentication_config_key is not None:
try:
self.authentication_config = alert_receiver_config[
authentication_config_key
]
except KeyError as err:
raise ConfigurationError(
"No authentication configuration found for dictionary key:"
f"{authentication_config_key}."
) from err

self.authentication_scheme = self.authentication_config.get(
"authentication_scheme", self.authentication_scheme
)
Comment on lines +72 to +74
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the second argument here? self.authentication_scheme would be None at this point, which is the default for dict.get.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually it should take the default value set in the classes that inherited the base.

This is a very bad coded concept, but it should work:

class Base:
    def __init__(self):
        self.surname = self.name if self.name is not None else 'Base'
    
class A(Base):
    name = "A"
    def __init__(self):
        super().__init__()

class B(Base):
    name = "B"
    def __init__(self):
        super().__init__()

a = A()
print(a.surname)
        
b = B()
print(b.surname)

Which prints:

A
B

A proper nit-picking review is a great opportunity to improve my coding skills ;)

self._validate_authentication_scheme()

def _validate_authentication_scheme(self) -> None:
if not self.authentication_scheme:
raise ConfigurationError(
"The authentication scheme cannot be null or empty."
)

if not self.authentication_scheme.isalpha():
raise ConfigurationError(
"The authentication scheme must contain only letters."
)

def get_header(self) -> dict:
return {}

class AlertReceiverNoneAuthentication(AlertReceiverAuthenticationInterface):
"""
Placeholder class for AlertReceiver without authentication.
"""

def __init__(self, alert_receiver_config: dict):
super().__init__(alert_receiver_config, None)

class AlertReceiverBasicAuthentication(AlertReceiverAuthenticationInterface):
"""
Class to store authentication information for basic authentication type
with username and password.
"""

username: str
password: str
authentication_scheme: str = "Basic"

def __init__(self, alert_receiver_config: dict):
super().__init__(alert_receiver_config, "receiver_authentication_basic")

try:
username_env = self.authentication_config["username_env"]
password_env = self.authentication_config["password_env"]
except KeyError as err:
raise ConfigurationError(
"No username_env or password_env configuration found."
) from err

try:
self.username = os.environ[username_env]
self.password = os.environ[password_env]
except KeyError as err:
raise ConfigurationError(
"No username or password found from environmental variables "
f"{username_env} and {password_env}."
) from err

def get_header(self) -> dict:
return {
"Authorization": f"{self.authentication_scheme} {self.username}:{self.password}"
}

class AlertReceiverBearerAuthentication(AlertReceiverAuthenticationInterface):
"""
Class to store authentication information for bearer authentication type which uses a token.
"""

token: str
authentication_scheme: str = "Bearer" # default is bearer

def __init__(self, alert_receiver_config: dict):
super().__init__(alert_receiver_config, "receiver_authentication_bearer")

token_env = self.authentication_config.get("token_env")
token_file = self.authentication_config.get("token_file")

if (
token_env is None and token_file is None
): # This should not happen since it is included in the json validation
raise ConfigurationError(
"No token_env and token_file configuration found."
)

if (
token_env is not None and token_file is not None
): # This should not happen since it is included in the json validation
raise ConfigurationError(
"Both token_env and token_file configuration found. Only one can be given."
)

if token_env is not None:
try:
self.token = os.environ[token_env]
except KeyError as err:
raise ConfigurationError(
f"No token found from environmental variable {token_env}."
) from err
else:
try:
with open(token_file, "r", encoding="utf-8") as token_file_handler:
self.token = token_file_handler.read()
except FileNotFoundError as err:
raise ConfigurationError(
f"No token file found at {token_file}."
) from err
except Exception as err:
raise ConfigurationError(
f"An error occurred while loading the token file {token_file}: {str(err)}"
) from err

def get_header(self) -> dict:
return {"Authorization": f"{self.authentication_scheme} {self.token}"}

init_map = {
"basic": AlertReceiverBasicAuthentication,
"bearer": AlertReceiverBearerAuthentication,
"none": AlertReceiverNoneAuthentication,
}

_authentication_instance = None

def __init__(self, alert_receiver_config: dict):
self.authentication_type = alert_receiver_config.get(
"receiver_authentication_type", "none"
)
self.__init_authentication_instance(alert_receiver_config)

def __init_authentication_instance(self, alert_receiver_config: dict):
try:
self._authentication_instance = self.init_map[self.authentication_type](
alert_receiver_config
)
except KeyError as err:
raise ConfigurationError(
"No authentication type found. Valid values are "
f"{list(AlertReceiverAuthentication.init_map.keys())}"
) from err # hopefully this never happens

def get_auth_header(self) -> dict:
return self._authentication_instance.get_header()


class Alert:
"""
Class to store image information about an alert as attributes and a sending
Expand All @@ -59,6 +222,7 @@ class Alert:

template: str
receiver_url: str
receiver_authentication: AlertReceiverAuthentication
payload: str
headers: dict

Expand Down Expand Up @@ -101,12 +265,13 @@ def __init__(
"images": images,
}
self.receiver_url = receiver_config["receiver_url"]
self.receiver_authentication = AlertReceiverAuthentication(receiver_config)
self.template = receiver_config["template"]
self.throw_if_alert_sending_fails = receiver_config.get(
"fail_if_alert_sending_fails", False
)
self.payload = self.__construct_payload(receiver_config)
self.headers = self.__get_headers(receiver_config)
self.headers = self.__get_headers(receiver_config, self.receiver_authentication)

def __construct_payload(self, receiver_config: dict) -> str:
try:
Expand Down Expand Up @@ -153,13 +318,18 @@ def send_alert(self) -> Optional[requests.Response]:
return response

@staticmethod
def __get_headers(receiver_config):
def __get_headers(
receiver_config: dict, receiver_authentication: AlertReceiverAuthentication
) -> dict:
headers = {"Content-Type": "application/json"}
additional_headers = receiver_config.get("custom_headers")
if additional_headers is not None:
for header in additional_headers:
key, value = header.split(":", 1)
headers.update({key.strip(): value.strip()})
auth_header = receiver_authentication.get_auth_header()
if auth_header: # not None and not empty
headers.update(auth_header)
return headers


Expand Down
146 changes: 146 additions & 0 deletions connaisseur/res/alertconfig_schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,50 @@
"receiver_url": {
"type": "string"
},
"receiver_authentication_type": {
"type": "string",
"enum": [
"none",
"basic",
"bearer"
]
},
"receiver_authentication_basic": {
"type": "object",
"properties": {
"username_env": {
"type": "string"
},
"password_env": {
"type": "string"
},
"authentication_scheme": {
"type": "string"
}
},
"required": [
"username_env",
"password_env"
]
},
"receiver_authentication_bearer": {
"type": "object",
"oneOf": [
{"required": ["token_file"]},
{"required": ["token_env"]}
],
"properties": {
"authentication_scheme": {
"type": "string"
},
"token_file": {
"type": "string"
},
"token_env": {
"type": "string"
}
}
},
"priority": {
"type": "integer"
},
Expand All @@ -35,6 +79,35 @@
"type": "boolean"
}
},
"anyOf": [
{
"properties": {
"receiver_authentication_type": {
"const": "basic"
}
},
"required": [
"receiver_authentication_basic"
]
},
{
"properties": {
"receiver_authentication_type": {
"const": "bearer"
}
},
"required": [
"receiver_authentication_bearer"
]
},
{
"properties": {
"receiver_authentication_type": {
"const": "none"
}
}
}
],
"required": [
"template",
"receiver_url"
Expand All @@ -60,6 +133,50 @@
"receiver_url": {
"type": "string"
},
"receiver_authentication_type": {
"type": "string",
"enum": [
"none",
"basic",
"bearer"
]
},
"receiver_authentication_basic": {
"type": "object",
"properties": {
"username_env": {
"type": "string"
},
"password_env": {
"type": "string"
},
"authentication_scheme": {
"type": "string"
}
},
"required": [
"username_env",
"password_env"
]
},
"receiver_authentication_bearer": {
"type": "object",
"oneOf": [
{"required": ["token_file"]},
{"required": ["token_env"]}
],
"properties": {
"authentication_scheme": {
"type": "string"
},
"token_file": {
"type": "string"
},
"token_env": {
"type": "string"
}
}
},
"priority": {
"type": "integer"
},
Expand All @@ -77,6 +194,35 @@
"type": "boolean"
}
},
"anyOf": [
{
"properties": {
"receiver_authentication_type": {
"const": "basic"
}
},
"required": [
"receiver_authentication_basic"
]
},
{
"properties": {
"receiver_authentication_type": {
"const": "bearer"
}
},
"required": [
"receiver_authentication_bearer"
]
},
{
"properties": {
"receiver_authentication_type": {
"const": "none"
}
}
}
],
"required": [
"template",
"receiver_url"
Expand Down
Loading