Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ Idea came from puppet's hiera.
- [AWS SSM](#aws-ssm)
- [AWS S3](#aws-s3)
- [Vault](#vault)
- [vals (optional)](#vals-optional)
- [Merge with Terraform remote state](#merge-with-terraform-remote-state)
- [Merge with env variables](#merge-with-env-variables)
- [Unicode Support](#unicode-support)
Expand Down Expand Up @@ -318,6 +319,37 @@ Generate a token for a policy:
my_token: "{{vault.token_policy(my_vault_policy)}}"
```

#### vals (optional)

[vals](https://github.com/helmfile/vals) provides additional secret backends,
including AWS Secrets Manager, GCP Secret Manager, and Azure Key Vault.
Install the `vals` executable separately and make it available on `PATH`
(for example, `brew install vals` on macOS). No additional Python package is
required, and existing SSM, S3, Vault, and SOPS resolvers are unchanged.

Wrap a vals reference in `{{vals.ref(...)}}`:

```yaml
password: "{{vals.ref(ref+awssecrets://app/database?region=us-east-1#/password)}}"
```

Provider authentication uses vals' own configuration and the inherited process
environment, such as `AWS_PROFILE`, `AWS_REGION`, or `VAULT_TOKEN`. Himl's
`default_aws_profile` is not forwarded to vals. See the
[vals provider documentation](https://github.com/helmfile/vals#supported-backends)
for reference syntax and authentication details.

Resolution preserves JSON value types and string whitespace, reuses himl's
secret interpolation cache, and times out after 60 seconds per call. Missing
executables, provider failures, and invalid output raise errors; subprocess
output is not included in error messages because it may contain secrets.
Plain `ref+...://` strings are not resolved unless wrapped in `{{vals.ref(...)}}`.

Use only trusted configuration: vals supports providers that execute commands
or read local files. The existing interpolation parser does not support literal
parentheses inside `ref(...)`; use provider-supported percent-encoding where
applicable.

### Merge with [Terraform remote state](https://www.terraform.io/docs/state/remote.html)

```yaml
Expand Down
42 changes: 41 additions & 1 deletion himl/secret_resolvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
# OF ANY KIND, either express or implied. See the License for the specific language
# governing permissions and limitations under the License.

import json
import os
import re
import subprocess
import sys


Expand Down Expand Up @@ -104,10 +107,47 @@ def resolve(self, secret_type, secret_params):
return vault().get_key(path, key)


class ValsSecretResolver(SecretResolver):
def supports(self, secret_type):
return secret_type == "vals"

def resolve(self, secret_type, secret_params):
reference = secret_params.get("ref")
if not isinstance(reference, str) or not re.fullmatch(r"ref\+[A-Za-z0-9_-]+://\S+", reference):
raise ValueError("Vals requires a 'ref' parameter containing a ref+PROVIDER://... URI")

try:
result = subprocess.run(
["vals", "eval", "-f", "-", "-o", "json"],
input=json.dumps({"value": reference}),
capture_output=True,
text=True,
encoding="utf-8",
timeout=60,
check=False,
)
except FileNotFoundError:
raise RuntimeError("Install vals and ensure its executable is available on PATH") from None
except subprocess.TimeoutExpired:
raise RuntimeError("Vals secret resolution timed out after 60 seconds") from None
except OSError:
raise RuntimeError("Could not execute vals; check its executable and permissions") from None
except UnicodeError:
raise RuntimeError("Vals returned an invalid UTF-8 response") from None

if result.returncode != 0:
raise RuntimeError("Vals secret resolution failed with exit code {}".format(result.returncode))

try:
return json.loads(result.stdout)["value"]
except (ValueError, KeyError, TypeError):
raise RuntimeError("Vals returned an invalid JSON response") from None


class AggregatedSecretResolver(SecretResolver):
def __init__(self, default_aws_profile=None):
self.secret_resolvers = (SSMSecretResolver(default_aws_profile), S3SecretResolver(default_aws_profile),
VaultSecretResolver(), SopsSecretResolver())
VaultSecretResolver(), SopsSecretResolver(), ValsSecretResolver())

def supports(self, secret_type):
return any([resolver.supports(secret_type) for resolver in self.secret_resolvers])
Expand Down
33 changes: 33 additions & 0 deletions tests/test_inject_secrets.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
# OF ANY KIND, either express or implied. See the License for the specific language
# governing permissions and limitations under the License.

import json
import subprocess

import pytest
from unittest.mock import patch

Expand Down Expand Up @@ -127,6 +130,36 @@ def test_inject_secret_sops_format(self):
}
)

@patch('subprocess.run')
def test_inject_vals_reference_and_cache(self, mock_run):
mock_run.return_value = subprocess.CompletedProcess(
args=[], returncode=0, stdout='{"value": "resolved-secret\\n"}', stderr="")
reference = 'ref+awssecrets://app/db.password?region=us-east-1&version_stage=AWSCURRENT#/password'
expression = '{{vals.ref(' + reference + ')}}'

assert self.injector.inject_secret(expression) == 'resolved-secret\n'
assert self.injector.inject_secret(expression) == 'resolved-secret\n'
assert mock_run.call_count == 1
assert json.loads(mock_run.call_args.kwargs['input']) == {'value': reference}

@pytest.mark.parametrize("skip_secrets", [False, True])
@patch('subprocess.run')
def test_vals_config_processing(self, mock_run, yaml_creator, temp_dir, skip_secrets):
from himl.config_generator import ConfigProcessor

expression = '{{vals.ref(ref+echo://password)}}'
yaml_creator('config.yaml', {'password': expression, 'plain_ref': 'ref+echo://unchanged'})
mock_run.return_value = subprocess.CompletedProcess(
args=[], returncode=0, stdout='{"value": "password"}', stderr="")

result = ConfigProcessor().process(cwd=temp_dir, path='', skip_secrets=skip_secrets)

assert result == {
'password': expression if skip_secrets else 'password',
'plain_ref': 'ref+echo://unchanged',
}
assert mock_run.call_count == (0 if skip_secrets else 1)

def test_inject_secret_unsupported_type(self):
"""Test handling of unsupported secret types"""
with patch.object(self.injector.resolver, 'supports', return_value=False):
Expand Down
99 changes: 98 additions & 1 deletion tests/test_secret_resolvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
# OF ANY KIND, either express or implied. See the License for the specific language
# governing permissions and limitations under the License.

import json
import subprocess

import pytest
import sys
from unittest.mock import patch, MagicMock
Expand Down Expand Up @@ -288,13 +291,107 @@ def test_resolve_missing_file(self):
assert "Could not find required key" in str(exc_info.value)


class TestValsSecretResolver:
@pytest.mark.parametrize("value", [
"secret", "", "line one\nline two\n", 42, False, None,
["one", "two"], {"username": "alice", "password": "secret"},
])
@patch('subprocess.run')
def test_resolve_preserves_value(self, mock_run, value):
mock_run.return_value = subprocess.CompletedProcess(
args=[], returncode=0, stdout=json.dumps({"value": value}), stderr="")
reference = "ref+awssecrets://app/database?region=us-east-1#/password"

result = AggregatedSecretResolver().resolve('vals', {'ref': reference})

assert result == value
args, kwargs = mock_run.call_args
assert args == (["vals", "eval", "-f", "-", "-o", "json"],)
assert json.loads(kwargs["input"]) == {"value": reference}
assert kwargs["capture_output"] is True
assert kwargs["text"] is True
assert kwargs["encoding"] == "utf-8"
assert kwargs["timeout"] == 60
assert not kwargs.get("shell", False)

@pytest.mark.parametrize("params", [
{}, {'ref': None}, {'ref': ''}, {'ref': 42},
{'ref': 'not-a-reference'}, {'ref': 'ref+vault'},
{'ref': 'ref+://path'}, {'ref': 'ref+vault://'},
])
@patch('subprocess.run')
def test_rejects_invalid_reference(self, mock_run, params):
with pytest.raises(ValueError, match="ref"):
AggregatedSecretResolver().resolve('vals', params)

mock_run.assert_not_called()

@patch('subprocess.run', side_effect=FileNotFoundError("sensitive reference"))
def test_missing_executable(self, mock_run):
with pytest.raises(RuntimeError, match="Install vals") as exc_info:
AggregatedSecretResolver().resolve('vals', {'ref': 'ref+echo://sensitive'})

assert "sensitive" not in str(exc_info.value)
assert exc_info.value.__suppress_context__

@patch('subprocess.run', side_effect=subprocess.TimeoutExpired(
cmd=["vals"], timeout=60, output="sensitive", stderr="sensitive"))
def test_timeout_does_not_expose_secrets(self, mock_run):
with pytest.raises(RuntimeError, match="timed out") as exc_info:
AggregatedSecretResolver().resolve('vals', {'ref': 'ref+echo://sensitive'})

assert "sensitive" not in str(exc_info.value)
assert exc_info.value.__suppress_context__

@patch('subprocess.run', side_effect=PermissionError("sensitive reference"))
def test_unusable_executable(self, mock_run):
with pytest.raises(RuntimeError, match="Could not execute vals") as exc_info:
AggregatedSecretResolver().resolve('vals', {'ref': 'ref+echo://sensitive'})

assert "sensitive" not in str(exc_info.value)
assert exc_info.value.__suppress_context__

@patch('subprocess.run', side_effect=UnicodeDecodeError(
"utf-8", b"sensitive\xff", 9, 10, "invalid byte"))
def test_invalid_encoding_does_not_expose_secrets(self, mock_run):
with pytest.raises(RuntimeError, match="invalid UTF-8 response") as exc_info:
AggregatedSecretResolver().resolve('vals', {'ref': 'ref+echo://sensitive'})

assert "sensitive" not in str(exc_info.value)
assert exc_info.value.__suppress_context__

@patch('subprocess.run')
def test_nonzero_exit_does_not_expose_secrets(self, mock_run):
mock_run.return_value = subprocess.CompletedProcess(
args=[], returncode=1, stdout="sensitive", stderr="sensitive")

with pytest.raises(RuntimeError, match="exit code 1") as exc_info:
AggregatedSecretResolver().resolve('vals', {'ref': 'ref+echo://sensitive'})

assert "sensitive" not in str(exc_info.value)

@pytest.mark.parametrize("output", [
'sensitive', '', '[]', '{}', 'null',
])
@patch('subprocess.run')
def test_invalid_output_does_not_expose_secrets(self, mock_run, output):
mock_run.return_value = subprocess.CompletedProcess(
args=[], returncode=0, stdout=output, stderr="sensitive")

with pytest.raises(RuntimeError, match="invalid JSON response") as exc_info:
AggregatedSecretResolver().resolve('vals', {'ref': 'ref+echo://sensitive'})

assert "sensitive" not in str(exc_info.value)
assert exc_info.value.__suppress_context__


class TestAggregatedSecretResolver:
"""Test AggregatedSecretResolver class"""

def test_initialization(self):
"""Test AggregatedSecretResolver initialization"""
resolver = AggregatedSecretResolver(default_aws_profile='test-profile')
assert len(resolver.secret_resolvers) == 4
assert len(resolver.secret_resolvers) == 5
assert any(isinstance(r, SSMSecretResolver) for r in resolver.secret_resolvers)
assert any(isinstance(r, S3SecretResolver) for r in resolver.secret_resolvers)
assert any(isinstance(r, VaultSecretResolver) for r in resolver.secret_resolvers)
Expand Down
Loading