Debian Codegraph @

tests/test_secrets.py

raw symbols SCIP
1 """Test secret substitution in YAML files."""
2
3 import logging
4 from dataclasses import dataclass
5 from pathlib import Path
6
7 import pytest
8
9 import annotatedyaml as yaml_util
10 from annotatedyaml import YAMLException
11 from annotatedyaml import loader as yaml_loader
12 from tests.common import YAML_CONFIG_FILE, get_test_config_dir, patch_yaml_files
13
14
15 @dataclass(frozen=True)
16 class YamlFile:
17 """Represents a .yaml file used for testing."""
18
19 path: Path
20 contents: str
21
22
23 def load_config_file(config_file_path: Path, files: list[YamlFile]) -> dict:
24 """Patch secret files and return the loaded config file."""
25 patch_files = {x.path.as_posix(): x.contents for x in files}
26 with patch_yaml_files(patch_files):
27 return yaml_loader.load_yaml(
28 config_file_path.as_posix(),
29 yaml_loader.Secrets(Path(get_test_config_dir())),
30 )
31
32
33 @pytest.fixture
34 def filepaths() -> dict[str, Path]:
35 """Return a dictionary of filepaths for testing."""
36 config_dir = Path(get_test_config_dir())
37 return {
38 "config": config_dir,
39 "sub_folder": config_dir / "subFolder",
40 "unrelated": config_dir / "unrelated",
41 }
42
43
44 @pytest.fixture
45 def default_config(filepaths: dict[str, Path]) -> YamlFile:
46 """Return the default config file for testing."""
47 return YamlFile(
48 path=filepaths["config"] / YAML_CONFIG_FILE,
49 contents=(
50 "http:\n"
51 " api_password: !secret http_pw\n"
52 "component:\n"
53 " username: !secret comp1_un\n"
54 " password: !secret comp1_pw\n"
55 ""
56 ),
57 )
58
59
60 @pytest.fixture
61 def default_secrets(filepaths: dict[str, Path]) -> YamlFile:
62 """Return the default secrets file for testing."""
63 return YamlFile(
64 path=filepaths["config"] / yaml_util.SECRET_YAML,
65 contents=(
66 "http_pw: pwhttp\n"
67 "comp1_un: un1\n"
68 "comp1_pw: pw1\n"
69 "stale_pw: not_used\n"
70 "logger: debug\n"
71 ),
72 )
73
74
75 def test_secrets_from_yaml(default_config: YamlFile, default_secrets: YamlFile) -> None:
76 """Did secrets load ok."""
77 loaded_file = load_config_file(
78 default_config.path, [default_config, default_secrets]
79 )
80 expected = {"api_password": "pwhttp"}
81 assert expected == loaded_file["http"]
82
83 expected = {"username": "un1", "password": "pw1"}
84 assert expected == loaded_file["component"]
85
86
87 def test_secrets_from_parent_folder(
88 filepaths: dict[str, Path],
89 default_config: YamlFile,
90 default_secrets: YamlFile,
91 ) -> None:
92 """Test loading secrets from parent folder."""
93 config_file = YamlFile(
94 path=filepaths["sub_folder"] / "sub.yaml",
95 contents=default_config.contents,
96 )
97 loaded_file = load_config_file(config_file.path, [config_file, default_secrets])
98 expected = {"api_password": "pwhttp"}
99
100 assert expected == loaded_file["http"]
101
102
103 def test_secret_overrides_parent(
104 filepaths: dict[str, Path],
105 default_config: YamlFile,
106 default_secrets: YamlFile,
107 ) -> None:
108 """Test loading current directory secret overrides the parent."""
109 config_file = YamlFile(
110 path=filepaths["sub_folder"] / "sub.yaml", contents=default_config.contents
111 )
112 sub_secrets = YamlFile(
113 path=filepaths["sub_folder"] / yaml_util.SECRET_YAML,
114 contents="http_pw: override",
115 )
116
117 loaded_file = load_config_file(
118 config_file.path, [config_file, default_secrets, sub_secrets]
119 )
120
121 expected = {"api_password": "override"}
122 assert loaded_file["http"] == expected
123
124
125 def test_secrets_from_unrelated_fails(
126 filepaths: dict[str, Path],
127 default_secrets: YamlFile,
128 ) -> None:
129 """Test loading secrets from unrelated folder fails."""
130 config_file = YamlFile(
131 path=filepaths["sub_folder"] / "sub.yaml",
132 contents="http:\n api_password: !secret test",
133 )
134 unrelated_secrets = YamlFile(
135 path=filepaths["unrelated"] / yaml_util.SECRET_YAML, contents="test: failure"
136 )
137 with pytest.raises(YAMLException, match="Secret test not defined"):
138 load_config_file(
139 config_file.path, [config_file, default_secrets, unrelated_secrets]
140 )
141
142
143 def test_secrets_logger_removed(
144 filepaths: dict[str, Path],
145 default_secrets: YamlFile,
146 ) -> None:
147 """Ensure logger: debug gets removed from secrets file once logger is configured."""
148 config_file = YamlFile(
149 path=filepaths["config"] / YAML_CONFIG_FILE,
150 contents="api_password: !secret logger",
151 )
152 with pytest.raises(YAMLException, match="Secret logger not defined"):
153 load_config_file(config_file.path, [config_file, default_secrets])
154
155
156 def test_bad_logger_value(
157 caplog: pytest.LogCaptureFixture, filepaths: dict[str, Path]
158 ) -> None:
159 """Ensure only logger: debug is allowed in secret file."""
160 config_file = YamlFile(
161 path=filepaths["config"] / YAML_CONFIG_FILE, contents="api_password: !secret pw"
162 )
163 secrets_file = YamlFile(
164 path=filepaths["config"] / yaml_util.SECRET_YAML,
165 contents="logger: info\npw: abc",
166 )
167 with caplog.at_level(logging.ERROR):
168 load_config_file(config_file.path, [config_file, secrets_file])
169 assert (
170 "Error in secrets.yaml: 'logger: debug' expected, but 'logger: info' found"
171 in caplog.messages
172 )
173
174
175 def test_secrets_are_not_dict(
176 filepaths: dict[str, Path],
177 default_config: YamlFile,
178 ) -> None:
179 """Did secrets handle non-dict file."""
180 non_dict_secrets = YamlFile(
181 path=filepaths["config"] / yaml_util.SECRET_YAML,
182 contents="- http_pw: pwhttp\n comp1_un: un1\n comp1_pw: pw1\n",
183 )
184 with pytest.raises(YAMLException, match="Secrets is not a dictionary"):
185 load_config_file(default_config.path, [default_config, non_dict_secrets])