1use crate::config::{ConnectorConfig, FormatConfig, TransportConfig};
9use crate::secret_redaction::secret_redactor;
10
11pub trait SensitiveValues {
17 fn visit_sensitive_values(&self, visit: &mut dyn FnMut(&str, &str));
18
19 fn register_sensitive_values(&self) {
22 self.visit_sensitive_values(&mut |_, value| secret_redactor().register_credential(value));
23 }
24}
25
26impl SensitiveValues for ConnectorConfig {
27 fn visit_sensitive_values(&self, visit: &mut dyn FnMut(&str, &str)) {
28 self.transport.visit_sensitive_values(visit);
29 if let Some(format) = &self.format {
30 format.visit_sensitive_values(visit);
31 }
32 }
33}
34
35impl SensitiveValues for TransportConfig {
36 fn visit_sensitive_values(&self, visit: &mut dyn FnMut(&str, &str)) {
37 match self {
38 Self::NatsInput(c) => c.visit_sensitive_values(visit),
39 Self::NatsOutput(c) => c.visit_sensitive_values(visit),
40 Self::KafkaInput(c) => c.visit_sensitive_values(visit),
41 Self::KafkaOutput(c) => c.visit_sensitive_values(visit),
42 Self::PubSubInput(c) => c.visit_sensitive_values(visit),
43 Self::UrlInput(c) => c.visit_sensitive_values(visit),
44 Self::S3Input(c) => c.visit_sensitive_values(visit),
45 Self::DeltaTableInput(c) => c.visit_sensitive_values(visit),
46 Self::DeltaTableOutput(c) => c.visit_sensitive_values(visit),
47 Self::DynamoDBOutput(c) => c.visit_sensitive_values(visit),
48 Self::RedisOutput(c) => c.visit_sensitive_values(visit),
49 Self::IcebergInput(c) => c.visit_sensitive_values(visit),
50 Self::PostgresInput(c) => c.visit_sensitive_values(visit),
51 Self::PostgresCdcInput(c) => c.visit_sensitive_values(visit),
52 Self::PostgresOutput(c) => c.visit_sensitive_values(visit),
53 Self::S2Input(c) => c.visit_sensitive_values(visit),
54 Self::S2Output(c) => c.visit_sensitive_values(visit),
55 Self::FileInput(_)
56 | Self::FileOutput(_)
57 | Self::Datagen(_)
58 | Self::Nexmark(_)
59 | Self::HttpInput(_)
60 | Self::HttpOutput(_)
61 | Self::AdHocInput(_)
62 | Self::ClockInput(_)
63 | Self::NullOutput
64 | Self::EmptyInput => {}
65 }
66 }
67}
68
69impl SensitiveValues for FormatConfig {
70 fn visit_sensitive_values(&self, visit: &mut dyn FnMut(&str, &str)) {
71 if self.name == "avro" {
74 crate::format::avro::visit_sensitive_config(&self.config, visit);
78 }
79 }
80}
81
82pub(crate) fn visit_optional(path: &str, value: Option<&str>, visit: &mut dyn FnMut(&str, &str)) {
83 if let Some(value) = value {
84 visit(path, value);
85 }
86}
87
88pub(crate) fn visit_url(path: &str, value: &str, visit: &mut dyn FnMut(&str, &str)) {
90 let has_credentials = match url::Url::parse(value) {
95 Ok(url) if !url.cannot_be_a_base() => {
96 !url.username().is_empty() || url.password().is_some() || url.query().is_some()
97 }
98 _ => value.contains('@') || value.contains('?'),
99 };
100 if has_credentials {
101 visit(path, value);
102 }
103}
104
105pub(crate) fn visit_connection_string(path: &str, value: &str, visit: &mut dyn FnMut(&str, &str)) {
108 if value.contains("://") {
111 visit_url(path, value, visit);
112 return;
113 }
114 for (keyword, raw, unescaped) in libpq_connection_values(value) {
117 if matches!(keyword, "password" | "sslpassword") {
118 let field = format!("{path}.{keyword}");
119 visit(&field, &unescaped);
120 if unescaped != raw {
121 visit(&format!("{field}.raw"), raw);
122 }
123 }
124 }
125}
126
127fn libpq_connection_values(text: &str) -> Vec<(&str, &str, String)> {
130 let mut pairs = Vec::new();
131 let mut rest = text.trim_start();
132 while let Some(equals) = rest.find('=') {
133 let keyword = rest[..equals].trim();
134 rest = rest[equals + 1..].trim_start();
135 let (raw, after) = match rest.strip_prefix('\'') {
136 Some(quoted) => {
137 let end = unescaped_end(quoted, |c| c == '\'');
138 ("ed[..end], quoted.get(end + 1..).unwrap_or_default())
139 }
140 None => {
141 let end = unescaped_end(rest, char::is_whitespace);
142 (&rest[..end], &rest[end..])
143 }
144 };
145 pairs.push((keyword, raw, unescape(raw)));
146 rest = after.trim_start();
147 }
148 pairs
149}
150
151fn unescaped_end(text: &str, stop: impl Fn(char) -> bool) -> usize {
153 let mut chars = text.char_indices();
154 while let Some((index, c)) = chars.next() {
155 if c == '\\' {
156 chars.next();
157 } else if stop(c) {
158 return index;
159 }
160 }
161 text.len()
162}
163
164fn unescape(raw: &str) -> String {
165 let mut out = String::with_capacity(raw.len());
166 let mut chars = raw.chars();
167 while let Some(c) = chars.next() {
168 match c {
169 '\\' => out.extend(chars.next()),
170 c => out.push(c),
171 }
172 }
173 out
174}
175
176pub(crate) fn credential_header(name: &str) -> bool {
177 ["authorization", "proxy-authorization", "x-api-key"]
178 .iter()
179 .any(|known| name.eq_ignore_ascii_case(known))
180}
181
182#[cfg(test)]
183mod tests {
184 use super::*;
185 use serde_json::{Value, json};
186 use std::collections::BTreeMap;
187
188 fn visited(config: &impl SensitiveValues) -> BTreeMap<String, String> {
189 let mut values = BTreeMap::new();
190 config.visit_sensitive_values(&mut |path, value| {
191 assert!(
192 values.insert(path.to_string(), value.to_string()).is_none(),
193 "duplicate path {path}"
194 );
195 });
196 values
197 }
198
199 #[test]
202 fn transport_declarations_preserve_operational_configuration() {
203 for (name, config, expected) in [
204 (
205 "s3_input",
206 json!({"region":"r", "bucket_name":"b", "aws_secret_access_key":"s3-secret-2136"}),
207 "aws_secret_access_key",
208 ),
209 (
210 "dynamodb_output",
211 json!({"region":"r", "table":"t", "aws_secret_access_key":"dynamo-secret-2136"}),
212 "aws_secret_access_key",
213 ),
214 (
215 "pub_sub_input",
216 json!({"subscription":"s", "credentials":"pubsub-secret-2136"}),
217 "credentials",
218 ),
219 (
220 "s2_input",
221 json!({"basin":"b", "stream":"s", "auth_token":"s2-secret-2136"}),
222 "auth_token",
223 ),
224 (
225 "s2_output",
226 json!({"basin":"b", "stream":"s", "auth_token":"s2-secret-2136"}),
227 "auth_token",
228 ),
229 (
230 "redis_output",
231 json!({"connection_string":"redis://u:redis-secret-2136@host"}),
232 "connection_string",
233 ),
234 (
235 "url_input",
236 json!({"path":"https://u:url-secret-2136@host/data"}),
237 "path",
238 ),
239 (
240 "kafka_input",
241 json!({"topic":"public-topic", "sasl.password":"kafka-secret-2136"}),
242 "sasl.password",
243 ),
244 (
245 "kafka_output",
246 json!({"topic":"public-topic", "sasl.password":"kafka-secret-2136"}),
247 "sasl.password",
248 ),
249 (
250 "delta_table_input",
251 json!({"uri":"s3://bucket/table", "mode":"snapshot", "AWS_SECRET_ACCESS_KEY":"delta-secret-2136"}),
252 "aws_secret_access_key",
253 ),
254 (
255 "delta_table_output",
256 json!({"uri":"s3://bucket/table", "secret_access_key":"delta-secret-2136"}),
257 "aws_secret_access_key",
258 ),
259 (
260 "iceberg_input",
261 json!({"mode":"snapshot", "rest.token":"iceberg-secret-2136"}),
262 "rest.token",
263 ),
264 (
265 "postgres_input",
266 json!({"uri":"host=h password=pg-secret-2136", "query":"SELECT 1"}),
267 "uri.password",
268 ),
269 (
270 "postgres_cdc_input",
271 json!({"uri":"host=h password=pg-secret-2136", "publication":"p", "source_table":"t"}),
272 "uri.password",
273 ),
274 (
275 "postgres_output",
276 json!({"uri":"host=h password=pg-secret-2136", "table":"t"}),
277 "uri.password",
278 ),
279 (
280 "nats_input",
281 json!({"connection_config":{"server_url":"nats://host", "auth":{"token":"nats-secret-2136"}}, "stream_name":"s", "consumer_config":{"deliver_policy":"All"}}),
282 "connection_config.auth.token",
283 ),
284 (
285 "nats_output",
286 json!({"connection_config":{"server_url":"nats://host", "auth":{"token":"nats-secret-2136"}}, "subject":"s"}),
287 "connection_config.auth.token",
288 ),
289 ] {
290 let transport: TransportConfig =
291 serde_json::from_value(json!({"name": name, "config":config}))
292 .unwrap_or_else(|e| panic!("{name}: {e}"));
293 let before = serde_json::to_value(&transport).unwrap();
294 let values = visited(&transport);
295 assert!(values.contains_key(expected), "{name}: {values:?}");
296 assert!(
297 values.values().all(|value| value.contains("secret-2136")),
298 "{name}: {values:?}"
299 );
300 assert_eq!(before, serde_json::to_value(&transport).unwrap());
301 }
302 }
303
304 #[test]
305 fn kafka_credentials_include_nested_options_and_aliases() {
306 let config: TransportConfig = serde_json::from_value(json!({"name":"kafka_output", "config":{
307 "topic":"public-topic", "bootstrap.servers":"public-host", "unknown.password":"opaque-public",
308 "sasl.password":"sasl-value", "ssl.key.password":"key-password", "ssl.key.pem":"key-pem",
309 "ssl.keystore.password":"keystore-password", "sasl.oauthbearer.client.credentials.client.secret":"oauth-value",
310 "sasl.oauthbearer.assertion.private.key.pem":"assertion-pem",
311 "sasl.oauthbearer.assertion.private.key.passphrase":"assertion-passphrase",
312 "fault_tolerance":{"consumer_options":{"sasl.password":"consumer-password"}, "producer_options":{"ssl.key.pem":"producer-pem"}}
313 }})).unwrap();
314 assert_eq!(
315 visited(&config),
316 BTreeMap::from([
317 ("sasl.password".into(), "sasl-value".into()),
318 ("ssl.key.password".into(), "key-password".into()),
319 ("ssl.key.pem".into(), "key-pem".into()),
320 ("ssl.keystore.password".into(), "keystore-password".into()),
321 (
322 "sasl.oauthbearer.assertion.private.key.pem".into(),
323 "assertion-pem".into()
324 ),
325 (
326 "sasl.oauthbearer.assertion.private.key.passphrase".into(),
327 "assertion-passphrase".into()
328 ),
329 (
330 "sasl.oauthbearer.client.secret".into(),
331 "oauth-value".into()
332 ),
333 (
334 "fault_tolerance.consumer_options.sasl.password".into(),
335 "consumer-password".into()
336 ),
337 (
338 "fault_tolerance.producer_options.ssl.key.pem".into(),
339 "producer-pem".into()
340 ),
341 ])
342 );
343 }
344
345 #[test]
346 fn token_only_userinfo_is_a_credential() {
347 let config: ConnectorConfig = serde_json::from_value(json!({
348 "transport":{"name":"url_input","config":{"path":"https://input-token-2136@host/data"}},
349 "format":{"name":"avro","config":{"registry_urls":["https://registry-token-2136@host/schemas"]}}
350 })).unwrap();
351 let before = config.clone();
352 assert_eq!(
353 visited(&config),
354 BTreeMap::from([
355 (
356 "path".to_string(),
357 "https://input-token-2136@host/data".to_string()
358 ),
359 (
360 "registry_urls.0".to_string(),
361 "https://registry-token-2136@host/schemas".to_string()
362 ),
363 ])
364 );
365 let redactor = crate::secret_redaction::SecretRedactor::new();
366 config.visit_sensitive_values(&mut |_, value| redactor.register_credential(value));
367 assert_eq!(
368 redactor.redact("fetch https://input-token-2136@host/data"),
369 "fetch [REDACTED]"
370 );
371 assert_eq!(
372 redactor.redact("fetch https://registry-token-2136@host/schemas"),
373 "fetch [REDACTED]"
374 );
375 assert_eq!(config, before);
376 }
377
378 #[test]
382 fn connection_strings_register_only_their_credentials() {
383 let postgres = |uri: &str| -> TransportConfig {
384 serde_json::from_value(
385 json!({"name":"postgres_input", "config":{"uri":uri, "query":"SELECT 1"}}),
386 )
387 .unwrap()
388 };
389 let redis = |connection_string: &str| -> TransportConfig {
390 serde_json::from_value(
391 json!({"name":"redis_output", "config":{"connection_string":connection_string}}),
392 )
393 .unwrap()
394 };
395 for public in [
396 postgres("postgres://db.example:5432/analytics"),
397 postgres("host=db.example dbname=analytics"),
398 redis("redis://cache.example:6379"),
399 ] {
400 assert!(visited(&public).is_empty());
401 }
402 assert_eq!(
403 visited(&postgres(
404 "host=db.example password=pg-keyword-secret-2136 dbname=db"
405 )),
406 BTreeMap::from([(
407 "uri.password".to_string(),
408 "pg-keyword-secret-2136".to_string()
409 )])
410 );
411 assert_eq!(
412 visited(&postgres(
413 r"host=h password='quoted \'secret\' 2136' sslpassword=key-secret-2136"
414 )),
415 BTreeMap::from([
416 (
417 "uri.password".to_string(),
418 "quoted 'secret' 2136".to_string()
419 ),
420 (
421 "uri.password.raw".to_string(),
422 r"quoted \'secret\' 2136".to_string()
423 ),
424 ("uri.sslpassword".to_string(), "key-secret-2136".to_string()),
425 ])
426 );
427 let redactor = crate::secret_redaction::SecretRedactor::new();
428 for config in [
429 postgres("host=db.example password=pg-keyword-secret-2136"),
430 postgres("postgres://u:pg-url-secret-2136@db.example/db"),
431 ] {
432 config.visit_sensitive_values(&mut |_, value| redactor.register_credential(value));
433 }
434 assert_eq!(
435 redactor.redact("auth failed for password pg-keyword-secret-2136"),
436 "auth failed for password [REDACTED]"
437 );
438 assert_eq!(
439 redactor.redact("auth failed for password pg-url-secret-2136"),
440 "auth failed for password [REDACTED]"
441 );
442 let public = "error connecting to postgres://db.example:5432/analytics: refused";
443 assert_eq!(redactor.redact(public), public);
444 }
445
446 #[test]
449 fn a_scheme_less_server_address_is_not_a_credential() {
450 let nats = |server_url: &str| -> TransportConfig {
451 serde_json::from_value(json!({"name":"nats_input", "config":{
452 "connection_config":{"server_url":server_url}, "stream_name":"s",
453 "consumer_config":{"deliver_policy":"All"}
454 }}))
455 .unwrap()
456 };
457 for public in [
458 "nats-1.internal:4222",
459 "nats://nats-1.internal:4222",
460 "localhost",
461 ] {
462 assert!(visited(&nats(public)).is_empty(), "{public}");
463 }
464 for private in [
465 "u:url-secret-2136@nats-1.internal:4222",
466 "nats://u:url-secret-2136@host",
467 "host:4222?token=url-secret-2136",
468 ] {
469 assert_eq!(
470 visited(&nats(private)),
471 BTreeMap::from([(
472 "connection_config.server_url".to_string(),
473 private.to_string()
474 )]),
475 "{private}"
476 );
477 }
478 }
479
480 #[test]
481 fn avro_visits_raw_credentials_even_when_parsing_will_fail() {
482 let config = FormatConfig {
483 name: "avro".into(),
484 config: json!({
485 "registry_password":"password-value", "registry_authorization_token":"token-value",
486 "registry_headers":{"Authorization":"header-value", "X-Request-ID":"public-value"},
487 "registry_urls":["https://u:uri-secret-2136@host", 1, "https://host/public"],
488 "registry_proxy":"https://u:proxy-secret-2136@proxy", "update_format":"invalid"
489 }),
490 };
491 let before = config.clone();
492 let values = visited(&config);
493 assert_eq!(values.len(), 5, "{values:?}");
494 for path in [
495 "registry_password",
496 "registry_authorization_token",
497 "registry_headers.authorization",
498 "registry_urls.0",
499 "registry_proxy",
500 ] {
501 assert!(values.contains_key(path), "{path}: {values:?}");
502 }
503 assert_eq!(config, before);
504 for raw in [
505 Value::Null,
506 json!({}),
507 json!({"registry_password":1, "registry_headers":[], "registry_urls":"bad"}),
508 ] {
509 assert!(
510 visited(&FormatConfig {
511 name: "avro".into(),
512 config: raw
513 })
514 .is_empty()
515 );
516 }
517 for name in ["csv", "json", "parquet", "unknown"] {
518 assert!(
519 visited(&FormatConfig {
520 name: name.into(),
521 config: config.config.clone()
522 })
523 .is_empty()
524 );
525 }
526 }
527
528 #[test]
529 fn nested_nats_postgres_and_iceberg_credentials_are_declared() {
530 let nats: TransportConfig = serde_json::from_value(json!({"name":"nats_output", "config":{
531 "subject":"public", "connection_config":{"server_url":"nats://u:url-secret-2136@host", "auth":{
532 "credentials":{"FromString":"creds-secret-2136"}, "jwt":"jwt-secret-2136", "nkey":"nkey-secret-2136",
533 "token":"token-secret-2136", "user_and_password":{"user":"public", "password":"password-secret-2136"}
534 }}
535 }})).unwrap();
536 let nats = visited(&nats);
537 assert_eq!(nats.len(), 6, "{nats:?}");
538 for suffix in [
539 "credentials.FromString",
540 "jwt",
541 "nkey",
542 "token",
543 "user_and_password.password",
544 ] {
545 assert!(nats.contains_key(&format!("connection_config.auth.{suffix}")));
546 }
547 for name in ["postgres_input", "postgres_output"] {
548 let config: TransportConfig = serde_json::from_value(json!({"name":name, "config":{
549 "uri":"postgres://u:password-secret-2136@host/db", "query":"SELECT 1", "table":"t",
550 "ssl_client_key":"pem-secret-2136"
551 }}))
552 .unwrap();
553 assert_eq!(visited(&config)["ssl_client_key"], "pem-secret-2136");
554 }
555 let keys = [
556 "glue.secret-access-key",
557 "glue.session-token",
558 "s3tables.secret-access-key",
559 "s3tables.session-token",
560 "rest.credential",
561 "rest.token",
562 "s3.secret-access-key",
563 "s3.session-token",
564 "s3.sse.key",
565 "gcs.credentials-json",
566 "gcs.oauth2.token",
567 "oss.access-key-secret",
568 "adls.connection-string",
569 "adls.account-key",
570 "adls.sas-token",
571 "adls.client-secret",
572 ];
573 let mut config = json!({"mode":"snapshot", "rest.headers":[["Authorization", "header-secret-2136"], ["X-Request-ID", "public"]]});
574 for key in keys {
575 config[key] = json!(format!("{key}-secret-2136"));
576 }
577 let config: TransportConfig =
578 serde_json::from_value(json!({"name":"iceberg_input", "config":config})).unwrap();
579 let values = visited(&config);
580 assert_eq!(values.len(), keys.len() + 1, "{values:?}");
581 for key in keys {
582 assert_eq!(values[key], format!("{key}-secret-2136"));
583 }
584 assert_eq!(values["rest.headers.authorization"], "header-secret-2136");
585 }
586
587 #[test]
588 fn object_store_aliases_are_canonical_and_unknown_keys_are_opaque() {
589 for (alias, canonical) in [
590 ("secret_access_key", "aws_secret_access_key"),
591 ("AWS_SECRET_ACCESS_KEY", "aws_secret_access_key"),
592 ("aws_token", "aws_session_token"),
593 ("session_token", "aws_session_token"),
594 ("sse_customer_key_base64", "aws_sse_customer_key_base64"),
595 ("azure_storage_access_key", "azure_storage_account_key"),
596 ("master_key", "azure_storage_account_key"),
597 ("access_key", "azure_storage_account_key"),
598 ("account_key", "azure_storage_account_key"),
599 ("azure_client_secret", "azure_storage_client_secret"),
600 ("client_secret", "azure_storage_client_secret"),
601 ("sas_token", "azure_storage_sas_key"),
602 ("azure_storage_sas_token", "azure_storage_sas_key"),
603 ("fabric_session_token", "azure_fabric_session_token"),
604 ("encryption_key", "azure_storage_encryption_key"),
605 ("service_account_key", "google_service_account_key"),
606 ("google_bearer_token", "google_bearer_token"),
607 ("databricks_token", "unity_access_token"),
608 ("access_token", "unity_access_token"),
609 ("databricks_client_secret", "unity_client_secret"),
610 ] {
611 let config: TransportConfig = serde_json::from_value(json!({"name":"delta_table_output", "config": {
612 "uri":"s3://bucket/table", alias:"credential-value", "unknown_password":"opaque-value", "aws_region":"public-region"
613 }})).unwrap();
614 assert_eq!(
615 visited(&config),
616 BTreeMap::from([(canonical.to_string(), "credential-value".to_string())]),
617 "{alias}"
618 );
619 }
620 }
621}