Debian Codegraph @

tests/unit_tests/test_redact.py

raw
1 """`harlequin.redact`: the promise that a secret does not reach the output.
2
3 Asserted negatively wherever it can be -- what matters is not that a mask
4 appears but that the value does not, and only one of those two is a promise.
5 The DSN cases are written the way people write them, because the helper exists
6 for connection strings that were typed by hand.
7 """
8
9 from __future__ import annotations
10
11 import pytest
12
13 from harlequin.options import FlagOption, ListOption, TextOption
14 from harlequin.redact import (
15 REDACTED,
16 hide_secrets_in,
17 redact_conn_str,
18 redact_profile,
19 redact_text,
20 )
21
22 SECRET = "hunter2-and-then-some"
23
24
25 @pytest.fixture
26 def declared() -> list[TextOption]:
27 """An adapter that declares one of its two options secret."""
28 return [
29 TextOption(name="host", description="The host."),
30 TextOption(name="md_token", description="A service token.", secret=True),
31 ]
32
33
34 # --- a profile ---------------------------------------------------------------
35
36
37 def test_a_declared_secret_is_masked(declared: list[TextOption]) -> None:
38 profile = {"adapter": "duckdb", "host": "warehouse", "md_token": SECRET}
39 assert redact_profile(profile, declared) == {
40 "adapter": "duckdb",
41 # not everything: a report a reader cannot use is not safer, it is just
42 # unread, and the host is the half that answers their question
43 "host": "warehouse",
44 "md_token": REDACTED,
45 }
46
47
48 def test_redacting_a_profile_leaves_the_original_alone(
49 declared: list[TextOption],
50 ) -> None:
51 """The caller is reporting on a profile a run may still be connecting with,
52 and asterisks are not a token."""
53 profile = {"md_token": SECRET}
54 assert redact_profile(profile, declared)["md_token"] == REDACTED
55 assert profile["md_token"] == SECRET
56
57
58 def test_a_key_named_like_a_secret_is_masked_without_a_declaration() -> None:
59 """The backstop, and the case that is nearly every case today.
60
61 Every adapter's options predate `secret=`, so a `password` key whose
62 adapter has not adopted the flag -- or whose adapter is not installed, or
63 would not import -- has nothing declaring it. Redacting a key named like a
64 password that is not one costs a reader nothing they cannot read out of
65 their own file.
66 """
67 profile = {"password": SECRET, "api_key": SECRET, "port": 5432}
68 assert redact_profile(profile) == {
69 "password": REDACTED,
70 "api_key": REDACTED,
71 "port": 5432,
72 }
73
74
75 def test_an_option_declared_by_name_beats_nothing_at_all(
76 declared: list[TextOption],
77 ) -> None:
78 """A key the adapter does declare, and does not call secret, is printed.
79
80 `md_token` is masked because it says so, `host` is not because it does not,
81 and neither answer comes from the key's spelling.
82 """
83 redacted = redact_profile({"host": "db", "md_token": SECRET}, declared)
84 assert redacted["host"] == "db"
85 assert redacted["md_token"] == REDACTED
86
87
88 def test_a_repeatable_secret_is_masked_item_by_item() -> None:
89 """The shape a profile has is the shape the report has: a reader can still
90 see how many were set."""
91 option = ListOption(name="token", description="Tokens.", secret=True)
92 assert redact_profile({"token": ["one", "two"]}, [option]) == {
93 "token": [REDACTED, REDACTED]
94 }
95
96
97 def test_a_secret_that_is_not_a_string_is_still_masked() -> None:
98 option = FlagOption(name="secret_mode", description="x", secret=True)
99 assert redact_profile({"secret_mode": True}, [option]) == {"secret_mode": REDACTED}
100
101
102 def test_a_profile_with_nothing_to_hide_is_unchanged() -> None:
103 profile = {"adapter": "sqlite", "conn_str": [":memory:"], "read_only": True}
104 assert redact_profile(profile) == profile
105
106
107 # --- a connection string -----------------------------------------------------
108
109
110 @pytest.mark.parametrize(
111 "conn_str,expected",
112 [
113 (
114 "postgresql://reporting:hunter2@warehouse:5432/analytics",
115 f"postgresql://reporting:{REDACTED}@warehouse:5432/analytics",
116 ),
117 (
118 "postgresql://:hunter2@warehouse/analytics",
119 f"postgresql://:{REDACTED}@warehouse/analytics",
120 ),
121 (
122 "postgresql://warehouse:5432/analytics?password=hunter2&sslmode=require",
123 f"postgresql://warehouse:5432/analytics?password={REDACTED}"
124 "&sslmode=require",
125 ),
126 (
127 "host=warehouse password=hunter2 user=reporting",
128 f"host=warehouse password={REDACTED} user=reporting",
129 ),
130 (
131 "host=warehouse password='hunter 2' user=reporting",
132 f"host=warehouse password='{REDACTED}' user=reporting",
133 ),
134 (
135 "md:my_db?motherduck_token=hunter2",
136 f"md:my_db?motherduck_token={REDACTED}",
137 ),
138 ("DRIVER={x};UID=me;PWD=hunter2", f"DRIVER={{x}};UID=me;PWD={REDACTED}"),
139 ],
140 ids=[
141 "url userinfo",
142 "url userinfo, no user",
143 "url query string",
144 "libpq pairs",
145 "libpq pairs, quoted",
146 "motherduck",
147 "odbc",
148 ],
149 )
150 def test_a_dsn_keeps_everything_but_the_credential(
151 conn_str: str, expected: str
152 ) -> None:
153 """A connection string is positional, so no option describes it -- and
154 [#354](https://github.com/tconbeer/harlequin/issues/354) is evidence people
155 put passwords in one."""
156 assert redact_conn_str([conn_str]) == [expected]
157 assert "hunter2" not in redact_conn_str([conn_str])[0]
158
159
160 @pytest.mark.parametrize(
161 "conn_str",
162 [
163 ":memory:",
164 "./warehouse.duckdb",
165 "postgresql://reporting@warehouse:5432/analytics",
166 "host=warehouse user=reporting sslmode=require",
167 "/tmp/a:[email protected]",
168 ],
169 )
170 def test_a_dsn_with_no_credential_in_it_is_left_alone(conn_str: str) -> None:
171 """The half that would make this unusable: masking a path, or a user, or a
172 host, in a helper a reader reaches for to see what they connected to."""
173 assert redact_conn_str([conn_str]) == [conn_str]
174
175
176 def test_a_password_that_spells_the_host_takes_only_itself() -> None:
177 """Masked where it stands rather than substituted, so a short password does
178 not take the rest of the DSN with it."""
179 assert redact_conn_str(["postgresql://me:warehouse@warehouse/db"]) == [
180 f"postgresql://me:{REDACTED}@warehouse/db"
181 ]
182
183
184 def test_every_connection_string_is_redacted() -> None:
185 """An adapter may take several, and `conn_str` is a list in a profile."""
186 assert redact_conn_str(["a://u:one@h", ":memory:", "b://u:two@h"]) == [
187 f"a://u:{REDACTED}@h",
188 ":memory:",
189 f"b://u:{REDACTED}@h",
190 ]
191
192
193 def test_a_profile_redacts_its_connection_strings(declared: list[TextOption]) -> None:
194 redacted = redact_profile(
195 {"conn_str": ["postgresql://me:hunter2@h/db"], "md_token": SECRET}, declared
196 )
197 assert redacted["conn_str"] == [f"postgresql://me:{REDACTED}@h/db"]
198 assert redacted["md_token"] == REDACTED
199
200
201 def test_a_profile_that_wrote_one_connection_string_as_a_string() -> None:
202 """TOML has a string and an array, and a profile may say either."""
203 assert redact_profile({"conn_str": "postgresql://me:hunter2@h/db"}) == {
204 "conn_str": [f"postgresql://me:{REDACTED}@h/db"]
205 }
206
207
208 # --- the backstop ------------------------------------------------------------
209
210
211 def test_text_hides_every_secret_it_was_given() -> None:
212 """The channel nothing here shapes in advance: a driver exception that
213 quotes back the DSN it was handed."""
214 message = f"FATAL: password authentication failed for {SECRET}"
215 assert redact_text(message, {SECRET}) == (
216 f"FATAL: password authentication failed for {REDACTED}"
217 )
218
219
220 def test_text_hides_a_secret_that_contains_another() -> None:
221 """Longest first, so the shorter mask does not end up embedded in the
222 longer secret's remains."""
223 assert redact_text("abcdefgh", {"abcd", "abcdefgh"}) == REDACTED
224
225
226 def test_text_will_not_mangle_a_message_over_a_three_letter_secret() -> None:
227 """A secret short enough to appear inside ordinary words is one this cannot
228 hide in prose without destroying the message. It is still masked wherever
229 it is printed as itself, which is what `redact_profile` is for."""
230 assert redact_text("the cat sat", {"at"}) == "the cat sat"
231
232
233 def test_text_with_nothing_to_hide_is_unchanged() -> None:
234 assert redact_text("could not connect", set()) == "could not connect"
235
236
237 # --- what the backstop is given ----------------------------------------------
238
239
240 def test_a_profiles_declared_values_and_its_dsn_are_both_hidden(
241 declared: list[TextOption],
242 ) -> None:
243 """Registered rather than returned: a caller that had to carry the set
244 around would be a caller that could forget to."""
245 hide_secrets_in(
246 {
247 "host": "warehouse",
248 "md_token": SECRET,
249 "conn_str": ["postgresql://me:hunter2@h/db"],
250 },
251 declared,
252 )
253 assert redact_text(f"{SECRET} and hunter2") == f"{REDACTED} and {REDACTED}"
254 # the host is not a secret, and a report that hid it would answer nothing
255 assert redact_text("connected to warehouse") == "connected to warehouse"
256
257
258 def test_only_strings_are_hidden(declared: list[TextOption]) -> None:
259 """A port or a flag has no literal to look for in a message, and hunting
260 for `True` in prose would redact every sentence containing it."""
261 option = FlagOption(name="secret_mode", description="x", secret=True)
262 hide_secrets_in({"secret_mode": True, "port": 5432}, [option])
263 assert redact_text("True, and the port is 5432") == "True, and the port is 5432"
264
265
266 # --- what the process has been told ------------------------------------------
267
268
269 def test_hiding_secrets_accumulates() -> None:
270 """Two profiles, both remembered, and both applied by default.
271
272 Callers hide a profile's secrets as soon as they have it rather than
273 collecting every secret first and handing them over in one go -- which
274 would mean each of them keeping a set of its own, and one of them
275 forgetting to.
276 """
277 hide_secrets_in({"password": "first-secret-value"})
278 hide_secrets_in({"password": "second-secret-value"})
279 assert redact_text("saw first-secret-value and second-secret-value") == (
280 f"saw {REDACTED} and {REDACTED}"
281 )
282
283
284 def test_hiding_nothing_hides_nothing() -> None:
285 """An option set to an empty string is not a secret, and substituting for
286 it would replace the gap between every two characters."""
287 hide_secrets_in({"password": "", "conn_str": [":memory:"]})
288 assert redact_text("nothing to hide here") == "nothing to hide here"
289
290
291 def test_text_given_secrets_uses_those_instead() -> None:
292 """The default is a convenience, not the only way in: a caller that holds
293 a secret this process was never told still gets it masked."""
294 assert redact_text("saw fifth-secret-value", {"fifth-secret-value"}) == (
295 f"saw {REDACTED}"
296 )