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
Changes from 1 commit
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
160 changes: 81 additions & 79 deletions connaisseur/alert.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from abc import abstractmethod
import json
import logging
import os
Expand Down Expand Up @@ -53,31 +54,66 @@ class AlertReceiverAuthentication:
Class to store authentication information for securely sending events to the alert receiver.
"""

class AlertReceiverBasicAuthentication:
authentication_config: dict = None
authentication_scheme: str = None

class AlertReceiverAuthenticationInterface:
def __init__(self, alert_receiver_config: dict, authentication_key: str):
self.authentication_config = alert_receiver_config.get(authentication_key)
Copy link
Member

Choose a reason for hiding this comment

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

authentication_key sounds like a credential

Copy link
Author

Choose a reason for hiding this comment

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

Yes, I agree. It will be called authentication_config_key.


if self.authentication_config is None:
raise ConfigurationError(
f"No authentication configuration found ({authentication_key})."
)

self.authentication_scheme = self.authentication_config.get(
"authentication_scheme", self.authentication_scheme
)
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 " " in self.authentication_scheme:
Copy link
Member

Choose a reason for hiding this comment

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

You might want to check that it contains only a-zA-Z or something like that. (" " is very specific, doesn't catch tabs, newlines, ...)

raise ConfigurationError(
"The authentication scheme cannot contain any space."
)

@abstractmethod
def get_header(self) -> dict:
pass

class AlertReceiverNoneAuthentication(AlertReceiverAuthenticationInterface):
"""
Placeholder class for AlertReceiver without authentication.
"""
def __init__(self, alert_receiver_config: dict):
pass

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

Choose a reason for hiding this comment

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

This could be the default implementation (instead of @abstractmethod). (Just a thought, certainly not mandatory.)


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

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

def __init__(self, alert_receiver_config: dict):
basic_authentication_config = alert_receiver_config.get(
"receiver_authentication_basic", None
)

if (
basic_authentication_config is None
): # TODO maybe remove this check since it is included in the json validation?
raise ConfigurationError("No basic authentication configuration found.")
super().__init__(alert_receiver_config, "receiver_authentication_basic")

username_env = basic_authentication_config.get("username_env", None)
password_env = basic_authentication_config.get("password_env", None)
username_env = self.authentication_config.get("username_env")
password_env = self.authentication_config.get("password_env")

if (
username_env is None or password_env is None
): # TODO maybe remove this check since it is included in the json validation?
): # This should not happen since it is included in the json validation
raise ConfigurationError(
"No username_env or password_env configuration found."
)
Expand All @@ -90,50 +126,37 @@ def __init__(self, alert_receiver_config: dict):
f"No username or password found from environmental variables {username_env} and {password_env}."
)

self.authorization_prefix = basic_authentication_config.get(
"authorization_prefix", "Basic"
)
# TODO maybe validate authorization prefix

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

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

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

def __init__(self, alert_receiver_config: dict):
bearer_authentication_config = alert_receiver_config.get(
"receiver_authentication_bearer", None
)

if (
bearer_authentication_config is None
): # TODO maybe remove this check since it is included in the json validation?
raise ConfigurationError(
"No bearer authentication configuration found."
)

token_env = bearer_authentication_config.get("token_env", None)
token_file = bearer_authentication_config.get("token_file", None)
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
): # TODO maybe remove this check since it is included in the json validation?
): # 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
): # TODO maybe remove this check since it is included in the json validation?
): # This should not happen since it is included in the json validation
raise ConfigurationError(
"Both token_env and token_file configuration found. Only one is required."
"Both token_env and token_file configuration found. Only one can be given."
)

if token_env is not None:
Expand All @@ -154,58 +177,37 @@ def __init__(self, alert_receiver_config: dict):
f"An error occurred while loading the token file {token_file}: {str(err)}"
)

self.authorization_prefix = bearer_authentication_config.get(
"authorization_prefix", "Bearer"
)
# TODO maybe validate authorization prefix

def get_header(self) -> dict:
return {"Authorization": f"{self.authorization_prefix} {self.token}"}
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)

if self.is_basic():
self.__init_basic_authentication(alert_receiver_config)
elif self.is_bearer():
self.__init_bearer_authentication(alert_receiver_config)
def __init_authentication_instance(self, alert_receiver_config: dict):
authentication_class = self.__get_authentication_class()
self._authentication_instance = authentication_class(alert_receiver_config)

def is_basic(self):
return self.authentication_type == "basic"

def is_bearer(self):
return self.authentication_type == "bearer"
def __get_authentication_class(self):
if self.authentication_type not in AlertReceiverAuthentication.init_map.keys():
raise ConfigurationError(
f"No authentication type found. Valid values are {list(AlertReceiverAuthentication.init_map.keys())}"
) # hopefully this never happens

def is_none(self):
return self.authentication_type == "none"

def __init_bearer_authentication(self, alert_receiver_config: dict):
self.bearer_authentication = (
AlertReceiverAuthentication.AlertReceiverBearerAuthentication(
alert_receiver_config
)
)

def __init_basic_authentication(self, alert_receiver_config: dict):
self.basic_authentication = (
AlertReceiverAuthentication.AlertReceiverBasicAuthentication(
alert_receiver_config
)
)
return self.init_map.get(self.authentication_type)
Copy link
Member

Choose a reason for hiding this comment

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

try:
    return self.init_map[self.authentication_type]
except KeyError:
    raise ConfigurationError(...)

This is a Python paradigm called EAFP. For context, see https://sauravmaheshkar.github.io/blog/Introduction-To-Duck-Typing-and-EAFP/.

One benefit is that EAFP gets ride of many TOCTOU race conditions (although not the case here, as the state is purely local).

Copy link
Author

Choose a reason for hiding this comment

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

I was not aware of this python principle. Thank you.


def get_auth_header(self) -> dict:
if self.is_basic():
return self.basic_authentication.get_header()
elif self.is_bearer():
return self.bearer_authentication.get_header()
elif self.is_none():
return {}
else:
raise ConfigurationError(
"No authentication type found."
) # hopefully this never happens
return self._authentication_instance.get_header()


class Alert:
Expand Down