-
Notifications
You must be signed in to change notification settings - Fork 15
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
[WIP] Secrets in Nautobot Config #39
Draft
nniehoff
wants to merge
11
commits into
nautobot:develop
Choose a base branch
from
nniehoff:nn_config_secrets
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+397
−50
Draft
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
37293c1
Adding Kuberenetes Authentication Method
d2eb131
Cleaning up for pylint
11dcfc1
Adding AppRole to README
9376219
Adding AppRole to README
b2033d7
Adding Ability to specify SSL Certificates
1b7985b
Parameterising the kubernetes token file path
nniehoff 535bf8d
Bandit
nniehoff 89f64e6
Adding validate settings test case
nniehoff 42bb03c
Adding test_get_client_k8s unittest
nniehoff 27745ab
Hashicorp AWS Auth
nniehoff 1396e6b
Rough Draft
nniehoff File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
"""Nautobot Secrets Connectors.""" | ||
|
||
from .hashicorp import HashiCorpVaultConnector | ||
|
||
__all__ = ( # type: ignore | ||
HashiCorpVaultConnector, # pylint: disable=invalid-all-object | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
"""Exception classes specific to secrets.""" | ||
|
||
|
||
class ConnectorError(Exception): | ||
"""General purpose exception class for failures raised when secret value access fails.""" | ||
|
||
def __init__(self, connector_class, message, *args, **kwargs): | ||
"""Collect some additional data.""" | ||
super().__init__(message, *args, **kwargs) | ||
self.connector_class = connector_class | ||
self.message = message | ||
|
||
def __str__(self): | ||
"""Format the Exception as a string.""" | ||
return f"{self.__class__.__name__}: " f'(connector "{self.connector_class.__name__}"): {self.message}' | ||
|
||
|
||
class SecretValueNotFoundError(Exception): | ||
"""General purpose exception class for failures raised when secret value access fails.""" | ||
|
||
def __init__(self, connector_class, message, *args, **kwargs): | ||
"""Collect some additional data.""" | ||
super().__init__(message, *args, **kwargs) | ||
self.connector_class = connector_class | ||
self.message = message | ||
|
||
def __str__(self): | ||
"""Format the Exception as a string.""" | ||
return f"{self.__class__.__name__}: " f'(connector "{self.connector_class.__name__}"): {self.message}' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,135 @@ | ||
"""Generic connector for HashiCorp Vault not tied to django.""" | ||
from .exceptions import ConnectorError, SecretValueNotFoundError | ||
from os.path import exists | ||
|
||
try: | ||
import boto3 | ||
except ImportError: | ||
boto3 = None | ||
|
||
import hvac | ||
|
||
AUTH_METHOD_CHOICES = ["approle", "aws", "kubernetes", "token"] | ||
DEFAULT_MOUNT_POINT = hvac.api.secrets_engines.kv_v2.DEFAULT_MOUNT_POINT | ||
K8S_TOKEN_DEFAULT_PATH = "/var/run/secrets/kubernetes.io/serviceaccount/token" # nosec B105 | ||
|
||
|
||
class HashiCorpVaultConnector: | ||
"""A generic connector for HashiCorp Vault.""" | ||
|
||
vault_settings = {} | ||
validated = False | ||
auth_method = "" | ||
client = None | ||
|
||
@classmethod | ||
def __init__(cls, vault_settings): | ||
"""Set some defaults.""" | ||
cls.vault_settings = vault_settings | ||
cls.auth_method = vault_settings.get("auth_method", "token") | ||
cls.k8s_token_path = vault_settings.get("k8s_token_path", K8S_TOKEN_DEFAULT_PATH) | ||
if hvac and not cls.validated: | ||
cls.validate_vault_settings() | ||
|
||
@classmethod | ||
def validate_vault_settings(cls): | ||
"""Validate the vault settings.""" | ||
if "url" not in cls.vault_settings: | ||
raise ConnectorError(cls, "HashiCorp Vault configuration is missing a url") | ||
|
||
if cls.auth_method not in AUTH_METHOD_CHOICES: | ||
raise ConnectorError(cls, f"HashiCorp Vault Auth Method {cls.auth_method} is invalid!") | ||
|
||
if cls.auth_method == "aws": | ||
if not boto3: | ||
raise ConnectorError(cls, "HashiCorp Vault AWS Auth Method requires the boto3 plugin!") | ||
elif cls.auth_method == "token": | ||
if "token" not in cls.vault_settings: | ||
raise ConnectorError(cls, "HashiCorp Vault configuration is missing a token for token authentication!") | ||
elif cls.auth_method == "kubernetes": | ||
if "role_name" not in cls.vault_settings: | ||
raise ConnectorError( | ||
cls, "HashiCorp Vault configuration is missing a role name for kubernetes authentication!" | ||
) | ||
if not exists(cls.k8s_token_path): | ||
raise ConnectorError( | ||
cls, "HashiCorp Vault configuration is missing a role name for kubernetes authentication!" | ||
) | ||
elif cls.auth_method == "approle": | ||
if "role_id" not in cls.vault_settings or "secret_id" not in cls.vault_settings: | ||
raise ConnectorError(cls, "HashiCorp Vault configuration is missing a role_id and/or secret_id!") | ||
cls.validated = True | ||
|
||
@classmethod | ||
def get_client(cls): | ||
"""Get a hvac client and login.""" | ||
if not cls.validated: | ||
cls.validate_vault_settings() | ||
elif cls.client: | ||
return cls.client | ||
|
||
login_kwargs = cls.vault_settings.get("login_kwargs", {}) | ||
|
||
# According to the docs (https://hvac.readthedocs.io/en/stable/source/hvac_v1.html?highlight=verify#hvac.v1.Client.__init__) | ||
# the client verify parameter is either a boolean or a path to a ca certificate file to verify. This is non-intuitive | ||
# so we use a parameter to specify the path to the ca_cert, if not provided we use the default of None | ||
ca_cert = cls.vault_settings.get("ca_cert", None) | ||
|
||
# Get the client and attempt to retrieve the secret. | ||
try: | ||
if cls.auth_method == "token": | ||
cls.client = hvac.Client( | ||
url=cls.vault_settings["url"], token=cls.vault_settings["token"], verify=ca_cert | ||
) | ||
else: | ||
cls.client = hvac.Client(url=cls.vault_settings["url"], verify=ca_cert) | ||
if cls.auth_method == "approle": | ||
cls.client.auth.approle.login( | ||
role_id=cls.vault_settings["role_id"], | ||
secret_id=cls.vault_settings["secret_id"], | ||
**login_kwargs, | ||
) | ||
elif cls.auth_method == "kubernetes": | ||
with open(cls.k8s_token_path, "r", encoding="utf-8") as token_file: | ||
jwt = token_file.read() | ||
cls.client.auth.kubernetes.login(role=cls.vault_settings["role_name"], jwt=jwt, **login_kwargs) | ||
elif cls.auth_method == "aws": | ||
session = boto3.Session() | ||
aws_creds = session.get_credentials() | ||
cls.client.auth.aws.iam_login( | ||
access_key=aws_creds.access_key, | ||
secret_key=aws_creds.secret_key, | ||
session_token=aws_creds.token, | ||
region=session.region_name, | ||
role=cls.vault_settings.get("role_name", None), | ||
**login_kwargs, | ||
) | ||
except hvac.exceptions.InvalidRequest as err: | ||
raise ConnectorError( | ||
cls, f"HashiCorp Vault Login failed (auth_method: {cls.auth_method}). Error: {err}" | ||
) from err | ||
except hvac.exceptions.Forbidden as err: | ||
raise ConnectorError( | ||
cls, f"HashiCorp Vault Access Denied (auth_method: {cls.auth_method}). Error: {err}" | ||
) from err | ||
|
||
return cls.client | ||
|
||
@classmethod | ||
def get_kv_value(cls, secret_key, default_value=None, **kwargs): | ||
"""Get a kv key and return the value stored in secret_key.""" | ||
client = cls.get_client() | ||
try: | ||
response = client.secrets.kv.read_secret(**kwargs) | ||
except hvac.exceptions.InvalidPath as err: | ||
raise ConnectorError(cls, str(err)) from err | ||
|
||
# Retrieve the value using the key or complain loudly. | ||
try: | ||
return response["data"]["data"][secret_key] | ||
except KeyError as err: | ||
if default_value: | ||
return default_value | ||
else: | ||
msg = f"The secret value could not be retrieved using key {err}" | ||
raise SecretValueNotFoundError(cls, msg) from err | ||
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This entire module is beautiful. My only gripe is that it's duplicating patterns and/or code from the core provider source. I like where you're going with this, but is there any way we can marry these interfaces?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I like the idea you're getting at in other words, but I don't like that it seemingly adds a lot of apparent boiler plate code, potentially complicating the introduction and maintenance of other providers.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'll probably re-work this entire PR but I've started the conversation to get this into Core here nautobot/nautobot#2469