provide-telemetry 0.7.0

Cross-language telemetry helpers with privacy, resilience, and OTLP support.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
// SPDX-FileCopyrightText: Copyright (C) 2026 provide.io llc
// SPDX-License-Identifier: Apache-2.0
// SPDX-Comment: Part of provide-telemetry.
//
use std::collections::HashMap;

use provide_telemetry::{redact_config, setup_telemetry, ConfigurationError, TelemetryConfig};

fn config_from(entries: &[(&str, &str)]) -> Result<TelemetryConfig, ConfigurationError> {
    let env: HashMap<String, String> = entries
        .iter()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect();
    TelemetryConfig::from_map(&env)
}

#[test]
fn test_telemetry_config_default() {
    let config = TelemetryConfig::default();
    assert!(!config.service_name.is_empty());
}

#[test]
fn test_telemetry_config_from_env() {
    let _config = TelemetryConfig::from_env();
}

#[test]
fn test_setup_telemetry() {
    let _ = setup_telemetry(None);
    let _ = setup_telemetry(None);
}

// --- has_invalid_percent_encoding boundary tests ---
// Reached through TelemetryConfig::from_map via OTEL_EXPORTER_OTLP_HEADERS.
// Valid encoding: key=value%2Cwith%2Ccommas → header preserved.
// Invalid encoding: k=%GX (non-hex digit) → header silently skipped.

fn config_with_header(header: &str) -> Result<TelemetryConfig, String> {
    let mut env = HashMap::new();
    env.insert("OTEL_EXPORTER_OTLP_HEADERS".to_string(), header.to_string());
    TelemetryConfig::from_map(&env).map_err(|e| e.to_string())
}

/// Valid %AB encoding — from_map must succeed and preserve the decoded value.
#[test]
fn test_percent_encoding_valid_is_accepted() {
    // %41 decodes to 'A'; the header value "hello%41world" = "helloAworld".
    let cfg = config_with_header("x-custom=hello%41world").expect("valid encoding must not fail");
    let logs_headers = &cfg.logging.otlp_headers;
    assert_eq!(
        logs_headers.get("x-custom").map(|s| s.as_str()),
        Some("helloAworld")
    );
}

/// % at the very end of the string — too few chars → invalid.
#[test]
fn test_percent_encoding_percent_at_end_is_rejected() {
    // When encoding is invalid the header pair is silently skipped (not an error at the
    // config level), so the key simply won't appear.
    let cfg = config_with_header("x-bad=value%").expect("config-level parse must succeed");
    assert!(
        !cfg.logging.otlp_headers.contains_key("x-bad"),
        "header with bare % at end should be silently skipped"
    );
}

/// Only one char after % — needs two hex digits, so this is also invalid.
#[test]
fn test_percent_encoding_one_hex_digit_is_rejected() {
    let cfg = config_with_header("x-bad=value%4").expect("config-level parse must succeed");
    assert!(
        !cfg.logging.otlp_headers.contains_key("x-bad"),
        "header with %<one-digit> should be silently skipped"
    );
}

/// Non-hex character in first position after % — invalid.
#[test]
fn test_percent_encoding_non_hex_first_char_is_rejected() {
    let cfg = config_with_header("x-bad=value%GF").expect("config-level parse must succeed");
    assert!(
        !cfg.logging.otlp_headers.contains_key("x-bad"),
        "header with %G (non-hex first digit) should be silently skipped"
    );
}

/// Non-hex character in second position after % — invalid.
#[test]
fn test_percent_encoding_non_hex_second_char_is_rejected() {
    let cfg = config_with_header("x-bad=value%4Z").expect("config-level parse must succeed");
    assert!(
        !cfg.logging.otlp_headers.contains_key("x-bad"),
        "header with %4Z (non-hex second digit) should be silently skipped"
    );
}

/// Exactly two hex digits at the boundary (% is the second-to-last char with one following hex) — invalid.
#[test]
fn test_percent_encoding_boundary_exactly_two_chars_after_percent_is_valid() {
    // %4F = 'O'. The entire value is "%4F" (3 chars, idx=0, idx+2=2, len=3, 2 >= 3 is false → valid).
    let cfg = config_with_header("x-ok=%4F").expect("config-level parse must succeed");
    assert_eq!(
        cfg.logging.otlp_headers.get("x-ok").map(|s| s.as_str()),
        Some("O"),
        "%4F (exactly idx+2 == len-1) must be treated as valid encoding"
    );
}

// --- parse_bool false-y values ---
// Kills: replace match guard matches!(..., "0"|"false"|"no"|"off") with false
// Without the false-y guard, "false"/"no"/"off"/"0" fall through to the Err branch.

#[test]
fn config_test_parse_bool_falsy_values_are_accepted() {
    for val in &["false", "False", "FALSE", "0", "no", "NO", "off", "OFF"] {
        let cfg = config_from(&[("PROVIDE_TRACE_ENABLED", val)])
            .unwrap_or_else(|e| panic!("{val:?} should parse as false, got error: {e}"));
        assert!(!cfg.tracing.enabled, "{val:?} must parse as false");
    }
}

// --- parse_non_negative_float edge cases ---
// Kills: replace || with && (infinity slips through), replace < with == (negatives slip through),
//        replace < with <= (zero is incorrectly rejected).

#[test]
fn config_test_non_negative_float_rejects_infinity() {
    // Kills: || → && (with &&, !is_finite() && negative is false for +inf → no error)
    let err = config_from(&[("PROVIDE_EXPORTER_LOGS_TIMEOUT_SECONDS", "inf")])
        .expect_err("infinity must be rejected");
    assert!(err
        .message
        .contains("PROVIDE_EXPORTER_LOGS_TIMEOUT_SECONDS"));
}

#[test]
fn config_test_non_negative_float_rejects_negative() {
    // Kills: < → == (only 0.0 would error; -1 would slip through)
    let err = config_from(&[("PROVIDE_EXPORTER_LOGS_BACKOFF_SECONDS", "-1")])
        .expect_err("negative float must be rejected");
    assert!(err
        .message
        .contains("PROVIDE_EXPORTER_LOGS_BACKOFF_SECONDS"));
}

#[test]
fn config_test_non_negative_float_accepts_zero() {
    // Kills: < → <= (zero would be incorrectly rejected)
    let cfg = config_from(&[("PROVIDE_EXPORTER_LOGS_BACKOFF_SECONDS", "0.0")])
        .expect("zero must be a valid non-negative float");
    assert_eq!(cfg.exporter.logs_backoff_seconds, 0.0);
}

// --- redact_config ---

#[test]
fn redact_config_masks_otlp_header_values() {
    // Kills: return cfg.clone() unchanged (no masking)
    let cfg = config_from(&[(
        "OTEL_EXPORTER_OTLP_HEADERS",
        "authorization=Bearer secret123",
    )])
    .unwrap();
    let redacted = redact_config(&cfg);
    // Keys are preserved, values replaced.
    assert!(
        redacted.logging.otlp_headers.contains_key("authorization"),
        "key must be preserved"
    );
    assert_eq!(
        redacted
            .logging
            .otlp_headers
            .get("authorization")
            .map(String::as_str),
        Some("***REDACTED***"),
        "value must be masked"
    );
}

#[test]
fn redact_config_masks_each_signal_header_map_independently() {
    let mut cfg = TelemetryConfig::default();
    cfg.logging
        .otlp_headers
        .insert("logs-token".to_string(), "logs-secret".to_string());
    cfg.tracing
        .otlp_headers
        .insert("traces-token".to_string(), "traces-secret".to_string());
    cfg.metrics
        .otlp_headers
        .insert("metrics-token".to_string(), "metrics-secret".to_string());

    let redacted = redact_config(&cfg);
    for (headers, key) in [
        (&redacted.logging.otlp_headers, "logs-token"),
        (&redacted.tracing.otlp_headers, "traces-token"),
        (&redacted.metrics.otlp_headers, "metrics-token"),
    ] {
        assert_eq!(headers.get(key).map(String::as_str), Some("***REDACTED***"));
    }
}

#[test]
fn redact_config_preserves_non_header_fields() {
    // Kills: replacing all fields with defaults.
    let cfg = config_from(&[
        ("PROVIDE_TELEMETRY_SERVICE_NAME", "my-service"),
        ("PROVIDE_TELEMETRY_ENV", "prod"),
    ])
    .unwrap();
    let redacted = redact_config(&cfg);
    assert_eq!(redacted.service_name, "my-service");
    assert_eq!(redacted.environment, "prod");
}

#[test]
fn redact_config_empty_headers_unchanged() {
    // Kills: unconditionally mask even empty headers.
    let cfg = TelemetryConfig::default();
    let redacted = redact_config(&cfg);
    assert!(
        redacted.logging.otlp_headers.is_empty(),
        "empty headers must stay empty"
    );
}

#[test]
fn redact_config_does_not_mutate_original() {
    // Ensures the original is not modified.
    let cfg = config_from(&[("OTEL_EXPORTER_OTLP_HEADERS", "x-token=realvalue")]).unwrap();
    let original_value = cfg.logging.otlp_headers.get("x-token").cloned();
    let _ = redact_config(&cfg);
    assert_eq!(
        cfg.logging.otlp_headers.get("x-token").cloned(),
        original_value,
        "original config must not be mutated"
    );
}

// --- OTLP endpoint + protocol per-signal fallback ---

#[test]
fn otlp_endpoint_shared_falls_back_with_per_signal_path_appended() {
    let cfg = config_from(&[("OTEL_EXPORTER_OTLP_ENDPOINT", "https://shared:4318")]).unwrap();
    // Per OTLP/HTTP spec, the per-signal path is appended to the shared
    // endpoint when no signal-specific override is set.
    assert_eq!(
        cfg.logging.otlp_endpoint.as_deref(),
        Some("https://shared:4318/v1/logs")
    );
    assert_eq!(
        cfg.tracing.otlp_endpoint.as_deref(),
        Some("https://shared:4318/v1/traces")
    );
    assert_eq!(
        cfg.metrics.otlp_endpoint.as_deref(),
        Some("https://shared:4318/v1/metrics")
    );
}

#[test]
fn otlp_endpoint_shared_strips_trailing_slash_before_appending() {
    let cfg = config_from(&[("OTEL_EXPORTER_OTLP_ENDPOINT", "https://shared:4318/")]).unwrap();
    assert_eq!(
        cfg.tracing.otlp_endpoint.as_deref(),
        Some("https://shared:4318/v1/traces"),
        "trailing slash on shared endpoint must not produce a double slash"
    );
}

#[test]
fn otlp_endpoint_signal_specific_overrides_shared_verbatim() {
    let cfg = config_from(&[
        ("OTEL_EXPORTER_OTLP_ENDPOINT", "https://shared:4318"),
        (
            "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
            "https://traces-only:4318/custom/path",
        ),
    ])
    .unwrap();
    assert_eq!(
        cfg.logging.otlp_endpoint.as_deref(),
        Some("https://shared:4318/v1/logs"),
        "logs should fall back to shared with /v1/logs appended"
    );
    assert_eq!(
        cfg.tracing.otlp_endpoint.as_deref(),
        Some("https://traces-only:4318/custom/path"),
        "traces should use its own override verbatim"
    );
    assert_eq!(
        cfg.metrics.otlp_endpoint.as_deref(),
        Some("https://shared:4318/v1/metrics"),
        "metrics should fall back to shared with /v1/metrics appended"
    );
}

#[test]
fn otlp_endpoint_blank_signal_specific_vars_do_not_mask_shared_fallback() {
    let cfg = config_from(&[
        ("OTEL_EXPORTER_OTLP_ENDPOINT", "https://shared:4318"),
        ("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT", ""),
        ("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", ""),
        ("OTEL_EXPORTER_OTLP_METRICS_ENDPOINT", ""),
    ])
    .unwrap();
    assert_eq!(
        cfg.logging.otlp_endpoint.as_deref(),
        Some("https://shared:4318/v1/logs"),
        "blank logs endpoint should behave as unset and fall back to shared"
    );
    assert_eq!(
        cfg.tracing.otlp_endpoint.as_deref(),
        Some("https://shared:4318/v1/traces"),
        "blank traces endpoint should behave as unset and fall back to shared"
    );
    assert_eq!(
        cfg.metrics.otlp_endpoint.as_deref(),
        Some("https://shared:4318/v1/metrics"),
        "blank metrics endpoint should behave as unset and fall back to shared"
    );
}

#[test]
fn otlp_endpoint_is_none_when_neither_shared_nor_signal_env_set() {
    let cfg = config_from(&[]).unwrap();
    assert!(cfg.logging.otlp_endpoint.is_none());
    assert!(cfg.tracing.otlp_endpoint.is_none());
    assert!(cfg.metrics.otlp_endpoint.is_none());
}

#[test]
fn otlp_protocol_shared_falls_back_to_all_three_signals() {
    let cfg = config_from(&[("OTEL_EXPORTER_OTLP_PROTOCOL", "http/protobuf")]).unwrap();
    assert_eq!(cfg.logging.otlp_protocol, "http/protobuf");
    assert_eq!(cfg.tracing.otlp_protocol, "http/protobuf");
    assert_eq!(cfg.metrics.otlp_protocol, "http/protobuf");
}

#[test]
fn otlp_protocol_signal_specific_overrides_shared() {
    let cfg = config_from(&[
        ("OTEL_EXPORTER_OTLP_PROTOCOL", "http/protobuf"),
        ("OTEL_EXPORTER_OTLP_METRICS_PROTOCOL", "grpc"),
    ])
    .unwrap();
    assert_eq!(cfg.logging.otlp_protocol, "http/protobuf");
    assert_eq!(cfg.tracing.otlp_protocol, "http/protobuf");
    assert_eq!(
        cfg.metrics.otlp_protocol, "grpc",
        "metrics should use its override"
    );
}

#[test]
fn otlp_protocol_defaults_to_empty_string_when_unset() {
    let cfg = config_from(&[]).unwrap();
    assert_eq!(cfg.logging.otlp_protocol, "");
    assert_eq!(cfg.tracing.otlp_protocol, "");
    assert_eq!(cfg.metrics.otlp_protocol, "");
}

#[test]
fn otel_metric_export_interval_defaults_to_sixty_seconds() {
    let cfg = config_from(&[]).unwrap();
    assert_eq!(
        cfg.metrics.metric_export_interval_ms, 60_000,
        "default export interval must be 60 000 ms"
    );
}

#[test]
fn otel_metric_export_interval_parsed_from_env() {
    let cfg = config_from(&[("OTEL_METRIC_EXPORT_INTERVAL", "5000")]).unwrap();
    assert_eq!(
        cfg.metrics.metric_export_interval_ms, 5_000,
        "custom interval must be taken from env var"
    );
}

#[test]
fn otel_metric_export_interval_rejects_non_integer() {
    let result = config_from(&[("OTEL_METRIC_EXPORT_INTERVAL", "1.5")]);
    assert!(
        result.is_err(),
        "non-integer interval must be rejected as ConfigurationError"
    );
}

// --- serde #[serde(default)] coverage ---
// Every public config struct now carries #[serde(default)] so that
// deserializing a partial/empty JSON object succeeds and missing fields
// fall back to the struct's Default impl.

#[test]
fn config_structs_serde_default_empty_object() {
    // All sub-config structs must deserialize from {} without error.
    serde_json::from_str::<provide_telemetry::MetricsConfig>("{}")
        .expect("MetricsConfig must deserialize from {}");
    serde_json::from_str::<provide_telemetry::TracingConfig>("{}")
        .expect("TracingConfig must deserialize from {}");
    serde_json::from_str::<provide_telemetry::SecurityConfig>("{}")
        .expect("SecurityConfig must deserialize from {}");
}

#[test]
fn security_config_serde_default_values() {
    let cfg: provide_telemetry::SecurityConfig =
        serde_json::from_str("{}").expect("SecurityConfig empty object must use defaults");
    assert_eq!(cfg.max_attr_value_length, 1024);
    assert_eq!(cfg.max_attr_count, 64);
    assert_eq!(cfg.max_nesting_depth, 8);
}

#[test]
fn metrics_config_serde_missing_interval_uses_default() {
    // Partial JSON (no metric_export_interval_ms) must still deserialize.
    let cfg: provide_telemetry::MetricsConfig =
        serde_json::from_str(r#"{"enabled": true, "otlp_headers": {}, "otlp_protocol": ""}"#)
            .expect("MetricsConfig missing interval field must deserialize");
    assert_eq!(cfg.metric_export_interval_ms, 60_000);
}

#[test]
fn telemetry_config_serde_round_trip_with_defaults() {
    // A TelemetryConfig serialized to JSON and back must survive even if
    // the JSON is then trimmed to just the service_name field.
    let partial = r#"{"service_name": "round-trip-test"}"#;
    let cfg: provide_telemetry::TelemetryConfig = serde_json::from_str(partial)
        .expect("TelemetryConfig with only service_name must deserialize");
    assert_eq!(cfg.service_name, "round-trip-test");
    assert_eq!(cfg.environment, "dev");
    assert_eq!(cfg.security.max_attr_value_length, 1024);
    assert_eq!(cfg.metrics.metric_export_interval_ms, 60_000);
    assert!((cfg.sampling.logs_rate - 1.0).abs() < f64::EPSILON);
}