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

add sops as a secret reslover #155

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
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
1 change: 1 addition & 0 deletions examples/secrets/default.yaml
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
---
secret_path_v2: "{{vault.path(/kv2_secret)}}"
secret_key_v2: "{{vault.key(/kv2_secret/key)}}"
sops_secret: "{{ sops.secret_file(/home/user/secrets/secret_file.yaml).secret_key(['s3']['access_key']) }}"
11 changes: 10 additions & 1 deletion himl/secret_resolvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from .simplessm import SimpleSSM
from .simples3 import SimpleS3
from .simplevault import SimpleVault
from .simplesops import SimpleSops


class SecretResolver:
Expand Down Expand Up @@ -68,6 +69,14 @@ def resolve(self, secret_type, secret_params):
s3 = SimpleS3(aws_profile, region_name)
return s3.get(bucket, path, base64Encode)

class SopsSecretResolver(SecretResolver):
def supports(self, secret_type):
return secret_type == "sops"

def resolve(self, secret_type, secret_params):
file = self.get_param_or_exception("secret_file", secret_params)
sops = SimpleSops()
return sops.get(secret_file=file, secret_key=secret_params.get("secret_key"))

class VaultSecretResolver(SecretResolver):
def supports(self, secret_type):
Expand Down Expand Up @@ -96,7 +105,7 @@ def resolve(self, secret_type, secret_params):
class AggregatedSecretResolver(SecretResolver):
def __init__(self, default_aws_profile=None):
self.secret_resolvers = (SSMSecretResolver(default_aws_profile), S3SecretResolver(default_aws_profile),
VaultSecretResolver())
VaultSecretResolver(), SopsSecretResolver())

def supports(self, secret_type):
return any([resolver.supports(secret_type) for resolver in self.secret_resolvers])
Expand Down
126 changes: 126 additions & 0 deletions himl/simplesops.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
# Copyright (c), Edoardo Tenani <[email protected]>, 2018-2020
# Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause)
# SPDX-License-Identifier: BSD-2-Clause

from __future__ import absolute_import, division, print_function

import os, logging

from subprocess import Popen, PIPE

logger = logging.getLogger(__name__)

# From https://github.com/getsops/sops/blob/master/cmd/sops/codes/codes.go
# Should be manually updated
SOPS_ERROR_CODES = {
1: "ErrorGeneric",
2: "CouldNotReadInputFile",
3: "CouldNotWriteOutputFile",
4: "ErrorDumpingTree",
5: "ErrorReadingConfig",
6: "ErrorInvalidKMSEncryptionContextFormat",
7: "ErrorInvalidSetFormat",
8: "ErrorConflictingParameters",
21: "ErrorEncryptingMac",
23: "ErrorEncryptingTree",
24: "ErrorDecryptingMac",
25: "ErrorDecryptingTree",
49: "CannotChangeKeysFromNonExistentFile",
51: "MacMismatch",
52: "MacNotFound",
61: "ConfigFileNotFound",
85: "KeyboardInterrupt",
91: "InvalidTreePathFormat",
100: "NoFileSpecified",
128: "CouldNotRetrieveKey",
111: "NoEncryptionKeyFound",
200: "FileHasNotBeenModified",
201: "NoEditorFound",
202: "FailedToCompareVersions",
203: "FileAlreadyEncrypted",
}


class SopsError(Exception):
"""Extend Exception class with sops specific information"""

def __init__(self, filename, exit_code, message, decryption=True):
if exit_code in SOPS_ERROR_CODES:
exception_name = SOPS_ERROR_CODES[exit_code]
message = "error with file %s: %s exited with code %d: %s" % (
filename,
exception_name,
exit_code,
message.decode("utf-8"),
)
else:
message = (
"could not %s file %s; Unknown sops error code: %s; message: %s"
% (
"decrypt" if decryption else "encrypt",
filename,
exit_code,
message.decode("utf-8"),
)
)
super(SopsError, self).__init__(message)


class Sops:
"""Utility class to perform sops CLI actions"""

@staticmethod
def decrypt(
encrypted_file,
secret_key=None,
decode_output=True,
rstrip=True,
):
command = ["sops"]
env = os.environ.copy()
if secret_key is None:
raise Exception(
"Error while getting secret for %s: secret key not supplied"
% encrypted_file
)
command.extend(["--extract", secret_key])
command.extend(["--decrypt", encrypted_file])
print(command)
Copy link
Author

Choose a reason for hiding this comment

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

debugging leftover that needs to be removed

process = Popen(
command,
stdin=None,
stdout=PIPE,
stderr=PIPE,
env=env,
)
(output, err) = process.communicate()
exit_code = process.returncode

if decode_output:
# output is binary, we want UTF-8 string
output = output.decode("utf-8", errors="surrogate_or_strict")
# the process output is the decrypted secret; be cautious
if exit_code != 0:
raise SopsError(encrypted_file, exit_code, err, decryption=True)

if rstrip:
output = output.rstrip()

return output


class SimpleSops:
def __init__(self):
pass

def get(self, secret_file, secret_key):
try:
logger.info(
"Resolving sops secret %s from file %s", secret_key, secret_file
)
return Sops.decrypt(encrypted_file=secret_file, secret_key=secret_key)
except SopsError as e:
raise Exception(
"Error while trying to read sops value for file %s, key: %s - %s"
% (secret_file, secret_key, e)
)
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

setup(
name='himl',
version="0.15.0",
version="0.16.0",
description='A hierarchical config using yaml',
long_description=_readme + '\n\n',
long_description_content_type='text/markdown',
Expand Down