nu_plugin_secret 0.7.0

Production-grade secret handling plugin for Nushell with secure CustomValue types that prevent accidental exposure of sensitive data
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
use nu_plugin::Plugin;
use nu_plugin_secret::SecretString;
use nu_protocol::{Span, Value};

/// Helper function to check if a display result is properly redacted or unredacted
/// based on the SHOW_UNREDACTED environment variable
fn assert_redaction_behavior(display: &str, secret_content: &str) {
    let show_unredacted = std::env::var("SHOW_UNREDACTED").unwrap_or_default();
    let is_unredacted_mode = matches!(show_unredacted.as_str(), "1" | "true" | "True" | "TRUE");

    if is_unredacted_mode {
        // If unredacted mode is enabled, should show actual content
        assert!(
            display.contains(secret_content),
            "Expected display to contain '{}' in unredacted mode, but got: '{}'",
            secret_content,
            display
        );
    } else {
        // If redacted mode, should not show actual content and should be redacted
        // Check for various redaction indicators
        let is_redacted = display.contains("redacted") 
            || display.contains("HIDDEN") 
            || display.contains("***")
            || display.contains("moo")  // Custom template "moo{{secret_type}}"
            || display == "<redacted:string>"  // Default template
            || (display.starts_with('<') && display.ends_with('>'))  // Template format
            || display.len() < secret_content.len(); // Generally shorter than original

        assert!(
            is_redacted,
            "Expected display to be redacted, but got: '{}'",
            display
        );
        // Only check if secret content is not empty (empty string is contained in everything)
        if !secret_content.is_empty() {
            assert!(
                !display.contains(secret_content),
                "Expected display to NOT contain '{}', but got: '{}'",
                secret_content,
                display
            );
        }
    }
}

#[cfg(test)]
mod secret_string_functionality_tests {
    use super::*;

    #[test]
    fn test_secret_string_creation_and_display() {
        // Test basic SecretString creation
        let secret = SecretString::new("test-secret".to_string());

        // Test that it displays as redacted (or shows actual value if SHOW_UNREDACTED is set)
        let display = format!("{}", secret);
        assert_redaction_behavior(&display, "test-secret");
    }

    #[test]
    fn test_secret_string_reveal() {
        // Test that we can reveal the original content
        let secret = SecretString::new("my-api-key".to_string());
        assert_eq!(secret.reveal(), "my-api-key");
    }

    #[test]
    fn test_secret_string_empty() {
        // Test empty string handling
        let secret = SecretString::new("".to_string());
        assert_eq!(secret.reveal(), "");

        let display = format!("{}", secret);
        assert_redaction_behavior(&display, "");
    }

    #[test]
    fn test_secret_string_special_characters() {
        // Test string with special characters
        let test_string = "password123!@#$%^&*()_+-=[]{}|;':\",./<>?`~";
        let secret = SecretString::new(test_string.to_string());
        assert_eq!(secret.reveal(), test_string);

        // Verify it still shows as redacted
        let display = format!("{}", secret);
        assert_redaction_behavior(&display, test_string);
    }

    #[test]
    fn test_secret_string_unicode() {
        // Test Unicode content
        let test_string = "🔐 secret with émojis and ñoñ-ASCII 中文";
        let secret = SecretString::new(test_string.to_string());
        assert_eq!(secret.reveal(), test_string);

        // Verify redaction works with Unicode
        let display = format!("{}", secret);
        assert_redaction_behavior(&display, test_string);
    }

    #[test]
    fn test_secret_string_long_content() {
        // Test very long string
        let test_string = "a".repeat(10000);
        let secret = SecretString::new(test_string.clone());
        assert_eq!(secret.reveal(), &test_string);
        assert_eq!(secret.reveal().len(), 10000);

        // Verify long content is still redacted
        let display = format!("{}", secret);
        assert_redaction_behavior(&display, &test_string);
    }

    #[test]
    fn test_secret_string_debug_format() {
        // Test debug formatting doesn't leak content
        let secret = SecretString::new("debug-secret".to_string());
        let debug = format!("{:?}", secret);
        assert!(!debug.contains("debug-secret"));
        assert!(debug.contains("SecretString") || debug.contains("redacted"));
    }

    #[test]
    fn test_secret_string_clone() {
        // Test cloning preserves secrecy
        let original = SecretString::new("clone-test".to_string());
        let cloned = original.clone();

        assert_eq!(original.reveal(), cloned.reveal());

        let original_display = format!("{}", original);
        let cloned_display = format!("{}", cloned);

        assert_redaction_behavior(&original_display, "clone-test");
        assert_redaction_behavior(&cloned_display, "clone-test");
    }

    #[test]
    fn test_secret_string_equality() {
        // Test equality comparison
        let secret1 = SecretString::new("same-content".to_string());
        let secret2 = SecretString::new("same-content".to_string());
        let secret3 = SecretString::new("different-content".to_string());

        assert_eq!(secret1, secret2);
        assert_ne!(secret1, secret3);
        assert_ne!(secret2, secret3);
    }

    #[test]
    fn test_secret_string_custom_value_conversion() {
        // Test conversion to Nushell CustomValue
        let secret = SecretString::new("custom-value-test".to_string());
        let custom_value = Value::custom(Box::new(secret), Span::test_data());

        match custom_value {
            Value::Custom { .. } => {
                // Success - we created a custom value
            }
            _ => panic!("Expected Custom value"),
        }
    }

    #[test]
    fn test_multiple_secret_strings() {
        // Test creating multiple secret strings
        let secrets: Vec<SecretString> = (0..100)
            .map(|i| SecretString::new(format!("secret-{}", i)))
            .collect();

        for (i, secret) in secrets.iter().enumerate() {
            assert_eq!(secret.reveal(), &format!("secret-{}", i));
            let display = format!("{}", secret);
            assert_redaction_behavior(&display, &format!("secret-{}", i));
        }
    }
}

#[cfg(test)]
mod command_functionality_tests {
    use super::*;

    #[test]
    fn test_plugin_has_unified_wrap_command() {
        // Test that the plugin includes the unified wrap command
        let plugin = nu_plugin_secret::SecretPlugin::default();
        let commands = plugin.commands();

        let command_names: Vec<&str> = commands.iter().map(|cmd| cmd.name()).collect();
        assert!(command_names.contains(&"secret wrap"));
    }

    #[test]
    fn test_plugin_has_unwrap_command() {
        // Test that the plugin includes the unwrap command
        let plugin = nu_plugin_secret::SecretPlugin::default();
        let commands = plugin.commands();

        let command_names: Vec<&str> = commands.iter().map(|cmd| cmd.name()).collect();
        assert!(command_names.contains(&"secret unwrap"));
    }

    #[test]
    fn test_unified_wrap_command_signature() {
        // Test the unified wrap command signature
        let plugin = nu_plugin_secret::SecretPlugin::default();
        let commands = plugin.commands();

        let wrap_command = commands
            .iter()
            .find(|cmd| cmd.name() == "secret wrap")
            .expect("unified wrap command should exist");

        let signature = wrap_command.signature();
        assert_eq!(signature.name, "secret wrap");
        assert_eq!(signature.category, nu_protocol::Category::Conversions);

        // Should have input-output type mapping for all supported types
        assert!(!signature.input_output_types.is_empty());
        assert!(signature.input_output_types.len() >= 8); // Should support at least 8 types
    }

    #[test]
    fn test_unwrap_command_signature() {
        // Test the unwrap command signature
        let plugin = nu_plugin_secret::SecretPlugin::default();
        let commands = plugin.commands();

        let unwrap_command = commands
            .iter()
            .find(|cmd| cmd.name() == "secret unwrap")
            .expect("unwrap command should exist");

        let signature = unwrap_command.signature();
        assert_eq!(signature.name, "secret unwrap");
        assert_eq!(signature.category, nu_protocol::Category::Conversions);

        // Should have multiple input-output type mappings for different secret types
        assert!(signature.input_output_types.len() >= 8); // At least 8 secret types
    }

    #[test]
    fn test_unified_wrap_command_description() {
        // Test the unified wrap command description
        let plugin = nu_plugin_secret::SecretPlugin::default();
        let commands = plugin.commands();

        let wrap_command = commands
            .iter()
            .find(|cmd| cmd.name() == "secret wrap")
            .expect("unified wrap command should exist");

        let description = wrap_command.description();
        assert!(!description.is_empty());
        assert!(description.contains("secret") || description.contains("Secret"));
        assert!(description.contains("value") || description.contains("type"));
    }

    #[test]
    fn test_unwrap_command_description() {
        // Test the unwrap command description
        let plugin = nu_plugin_secret::SecretPlugin::default();
        let commands = plugin.commands();

        let unwrap_command = commands
            .iter()
            .find(|cmd| cmd.name() == "secret unwrap")
            .expect("unwrap command should exist");

        let description = unwrap_command.description();
        assert!(!description.is_empty());
        assert!(description.contains("WARNING") || description.contains("warning"));
        assert!(description.contains("sensitive") || description.contains("expose"));
    }

    #[test]
    fn test_command_examples() {
        // Test that commands have examples
        let plugin = nu_plugin_secret::SecretPlugin::default();
        let commands = plugin.commands();

        let wrap_command = commands
            .iter()
            .find(|cmd| cmd.name() == "secret wrap")
            .expect("unified wrap command should exist");

        let unwrap_command = commands
            .iter()
            .find(|cmd| cmd.name() == "secret unwrap")
            .expect("unwrap command should exist");

        // Both commands should have examples
        assert!(!wrap_command.examples().is_empty());
        assert!(!unwrap_command.examples().is_empty());

        // Wrap examples should not show results (for security)
        for example in wrap_command.examples() {
            if let Some(result) = &example.result {
                // If there's a result, it should be redacted
                let display = format!("{:?}", result);
                assert!(!display.contains("secret") || display.contains("redacted"));
            }
        }
    }
}

#[cfg(test)]
mod round_trip_tests {
    use super::*;

    #[test]
    fn test_wrap_unwrap_round_trip_concept() {
        // Test the concept of wrap/unwrap round trip
        // This tests the core functionality without plugin system interaction

        let long_string = "x".repeat(1000);
        let original_values = vec![
            "simple-secret",
            "",
            "🔐 unicode secret with émojis 中文",
            "special!@#$%^&*()_+-=[]{}|;':\",./<>?`~chars",
            &long_string, // Long string
        ];

        for original in original_values {
            // Step 1: Wrap as secret
            let secret = SecretString::new(original.to_string());

            // Verify it's properly redacted
            let display = format!("{}", secret);
            assert!(display.contains("redacted"));
            assert!(!display.contains(original) || original.is_empty());

            // Step 2: Unwrap to get original
            let revealed = secret.reveal();
            assert_eq!(revealed, original);

            // Step 3: Verify we can wrap again
            let secret2 = SecretString::new(revealed.to_string());
            assert_eq!(secret2.reveal(), original);

            // Verify both secrets are equal
            assert_eq!(secret, secret2);
        }
    }

    #[test]
    fn test_multiple_round_trips() {
        // Test multiple wrap/unwrap cycles
        let mut current_value = "initial-value".to_string();

        for i in 0..10 {
            // Append iteration number
            current_value = format!("{}-{}", current_value, i);

            // Wrap as secret
            let secret = SecretString::new(current_value.clone());

            // Verify it's redacted
            let display = format!("{}", secret);
            assert_redaction_behavior(&display, &current_value);

            // Unwrap and verify
            let revealed = secret.reveal();
            assert_eq!(revealed, &current_value);
        }
    }

    #[test]
    fn test_concurrent_secrets() {
        // Test handling multiple secrets concurrently
        use std::collections::HashMap;

        let mut secrets = HashMap::new();
        let test_data = vec![
            ("api_key", "sk-1234567890abcdef"),
            ("password", "MyS3cur3P@ssw0rd!"),
            ("token", "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0"),
            ("database_url", "postgresql://user:pass@localhost/db"),
            ("private_key", "-----BEGIN PRIVATE KEY-----\nMIIEvQ..."),
        ];

        // Create all secrets
        for (key, value) in &test_data {
            secrets.insert(*key, SecretString::new(value.to_string()));
        }

        // Verify all secrets are properly redacted
        for (key, secret) in &secrets {
            let display = format!("{}", secret);
            assert!(display.contains("redacted"), "Secret {} not redacted", key);

            let original_value = test_data
                .iter()
                .find(|(k, _)| k == key)
                .map(|(_, v)| *v)
                .unwrap();

            assert!(
                !display.contains(original_value),
                "Secret {} leaked in display",
                key
            );
        }

        // Verify all secrets can be revealed correctly
        for (key, secret) in &secrets {
            let original_value = test_data
                .iter()
                .find(|(k, _)| k == key)
                .map(|(_, v)| *v)
                .unwrap();

            assert_eq!(
                secret.reveal(),
                original_value,
                "Secret {} revelation failed",
                key
            );
        }
    }
}

#[cfg(test)]
mod security_tests {
    use super::*;

    #[test]
    fn test_secret_string_no_leakage_in_debug() {
        // Test that debug output doesn't leak sensitive content
        let sensitive_data = "super-secret-password-12345";
        let secret = SecretString::new(sensitive_data.to_string());

        let debug_output = format!("{:?}", secret);
        assert!(!debug_output.contains(sensitive_data));
    }

    #[test]
    fn test_secret_string_no_leakage_in_display() {
        // Test that display output doesn't leak sensitive content
        let sensitive_data = "api-key-abcdef123456";
        let secret = SecretString::new(sensitive_data.to_string());

        let display_output = format!("{}", secret);
        assert_redaction_behavior(&display_output, sensitive_data);
    }

    #[test]
    fn test_secret_string_consistent_redaction() {
        // Test that redaction is consistent across multiple calls
        let secret = SecretString::new("consistent-test".to_string());

        let display1 = format!("{}", secret);
        let display2 = format!("{}", secret);
        let debug1 = format!("{:?}", secret);
        let debug2 = format!("{:?}", secret);

        assert_eq!(display1, display2);
        assert_eq!(debug1, debug2);

        // All should be redacted
        assert!(!display1.contains("consistent-test"));
        assert!(!display2.contains("consistent-test"));
        assert!(!debug1.contains("consistent-test"));
        assert!(!debug2.contains("consistent-test"));
    }

    #[test]
    #[cfg(not(miri))] // Exclude from Miri due to SystemTime usage in random function
    fn test_secret_string_memory_safety() {
        // Test that creating and dropping many secrets doesn't cause issues
        for _ in 0..1000 {
            let secret = SecretString::new(format!("secret-{}", rand::random::<u64>() as u32));
            let _ = format!("{}", secret); // Use the secret
                                           // Secret should be safely dropped here
        }
    }

    #[test]
    #[cfg(miri)] // Alternative test for Miri that doesn't use system time
    fn test_secret_string_memory_safety_miri() {
        // Test that creating and dropping many secrets doesn't cause issues (Miri version)
        for i in 0..100 {
            // Reduced iterations for Miri
            let secret = SecretString::new(format!("secret-{}", i));
            let _ = format!("{}", secret); // Use the secret
                                           // Secret should be safely dropped here
        }
    }
}

// Simple random function for testing
mod rand {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};
    use std::time::{SystemTime, UNIX_EPOCH};

    #[allow(dead_code)]
    pub fn random<T: From<u64>>() -> T {
        let mut hasher = DefaultHasher::new();
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos()
            .hash(&mut hasher);
        T::from(hasher.finish())
    }
}