fnox 1.23.0

A flexible secret management tool supporting multiple providers and encryption methods
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
use crate::env;
use crate::error::{FnoxError, Result};
use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::{LazyLock, Mutex};
use tokio::process::Command;

const PROVIDER_NAME: &str = "Infisical";
const PROVIDER_URL: &str = "https://fnox.jdx.dev/providers/infisical";

pub struct InfisicalProvider {
    project_id: Option<String>,
    environment: Option<String>,
    path: Option<String>,
}

impl InfisicalProvider {
    pub fn new(
        project_id: Option<String>,
        environment: Option<String>,
        path: Option<String>,
    ) -> Result<Self> {
        Ok(Self {
            project_id,
            environment,
            path,
        })
    }

    /// Get authentication token - either from environment or by logging in with client credentials
    fn get_auth_token(&self) -> Result<String> {
        // Check if we already have a token
        if let Some(token) = infisical_token() {
            tracing::debug!("Using INFISICAL_TOKEN from environment");
            return Ok(token);
        }

        // Check if we have client credentials to obtain a token
        let client_id = infisical_client_id().ok_or_else(|| FnoxError::ProviderAuthFailed {
            provider: PROVIDER_NAME.to_string(),
            details: "Authentication not found".to_string(),
            hint: "Set INFISICAL_TOKEN, or both INFISICAL_CLIENT_ID and INFISICAL_CLIENT_SECRET"
                .to_string(),
            url: PROVIDER_URL.to_string(),
        })?;

        let client_secret =
            infisical_client_secret().ok_or_else(|| FnoxError::ProviderAuthFailed {
                provider: PROVIDER_NAME.to_string(),
                details: "Client secret not found".to_string(),
                hint: "Set INFISICAL_CLIENT_SECRET or FNOX_INFISICAL_CLIENT_SECRET".to_string(),
                url: PROVIDER_URL.to_string(),
            })?;

        // Acquire lock for the entire check-and-login operation to prevent race condition
        // where multiple threads might all see no cached token and perform expensive login operations
        let mut cached_token = CACHED_LOGIN_TOKEN.lock().unwrap();

        // Check if another thread cached a token while we were waiting for the lock
        if let Some(token) = cached_token.as_ref() {
            tracing::debug!("Using cached login token");
            return Ok(token.clone());
        }

        tracing::debug!("Logging in with Universal Auth credentials");

        // Login with client credentials to get a token
        let mut cmd = std::process::Command::new("infisical");
        cmd.args([
            "login",
            "--method",
            "universal-auth",
            "--client-id",
            &client_id,
            "--client-secret",
            &client_secret,
            "--plain",
            "--silent",
        ]);

        // Add custom domain if specified, stripping /api suffix if present
        // The CLI's --domain flag expects base URL (some commands append /api automatically)
        if let Some(api_url) = infisical_api_url() {
            let base_url = api_url.trim_end_matches("/api").trim_end_matches('/');
            cmd.arg("--domain");
            cmd.arg(base_url);
            tracing::debug!(
                "Using custom Infisical domain: {} (from: {})",
                base_url,
                api_url
            );
        }

        cmd.stdin(std::process::Stdio::null());

        let output = cmd.output().map_err(|e| {
            if e.kind() == std::io::ErrorKind::NotFound {
                FnoxError::ProviderCliNotFound {
                    provider: PROVIDER_NAME.to_string(),
                    cli: "infisical".to_string(),
                    install_hint: "brew install infisical/get-cli/infisical".to_string(),
                    url: PROVIDER_URL.to_string(),
                }
            } else {
                FnoxError::ProviderCliFailed {
                    provider: PROVIDER_NAME.to_string(),
                    details: e.to_string(),
                    hint: "Check that the Infisical CLI is installed and accessible".to_string(),
                    url: PROVIDER_URL.to_string(),
                }
            }
        })?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(FnoxError::ProviderAuthFailed {
                provider: PROVIDER_NAME.to_string(),
                details: stderr.trim().to_string(),
                hint: "Check your client ID and client secret".to_string(),
                url: PROVIDER_URL.to_string(),
            });
        }

        let token = String::from_utf8(output.stdout)
            .map_err(|e| FnoxError::ProviderInvalidResponse {
                provider: PROVIDER_NAME.to_string(),
                details: format!("Invalid UTF-8 in command output: {}", e),
                hint: "This is an unexpected error".to_string(),
                url: PROVIDER_URL.to_string(),
            })?
            .trim()
            .to_string();

        // Cache the token (lock still held, preventing race condition)
        *cached_token = Some(token.clone());

        tracing::debug!("Successfully logged in and cached token");

        Ok(token)
    }

    /// Execute infisical CLI command.
    /// `secret_ref` is used for better error messages when a specific secret is being fetched.
    async fn execute_infisical_command(
        &self,
        args: &[&str],
        secret_ref: Option<&str>,
    ) -> Result<String> {
        tracing::debug!("Executing infisical command with args: {:?}", args);

        let token = self.get_auth_token()?;

        let mut cmd = Command::new("infisical");
        cmd.args(args);

        // Add authentication token
        cmd.arg("--token");
        cmd.arg(&token);

        // Add custom domain if specified, stripping /api suffix if present
        // The CLI's --domain flag expects base URL (some commands append /api automatically)
        if let Some(api_url) = infisical_api_url() {
            let base_url = api_url.trim_end_matches("/api").trim_end_matches('/');
            cmd.arg("--domain");
            cmd.arg(base_url);
        }

        // Add silent flag to reduce noise
        cmd.arg("--silent");

        cmd.stdin(std::process::Stdio::null());

        let output = cmd.output().await.map_err(|e| {
            if e.kind() == std::io::ErrorKind::NotFound {
                FnoxError::ProviderCliNotFound {
                    provider: PROVIDER_NAME.to_string(),
                    cli: "infisical".to_string(),
                    install_hint: "brew install infisical/get-cli/infisical".to_string(),
                    url: PROVIDER_URL.to_string(),
                }
            } else {
                FnoxError::ProviderCliFailed {
                    provider: PROVIDER_NAME.to_string(),
                    details: e.to_string(),
                    hint: "Check that the Infisical CLI is installed and accessible".to_string(),
                    url: PROVIDER_URL.to_string(),
                }
            }
        })?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(classify_cli_error(stderr.trim(), secret_ref));
        }

        let stdout =
            String::from_utf8(output.stdout).map_err(|e| FnoxError::ProviderInvalidResponse {
                provider: PROVIDER_NAME.to_string(),
                details: format!("Invalid UTF-8 in command output: {}", e),
                hint: "The secret value contains invalid UTF-8 characters".to_string(),
                url: PROVIDER_URL.to_string(),
            })?;

        Ok(stdout.trim().to_string())
    }
}

#[async_trait]
impl crate::providers::Provider for InfisicalProvider {
    async fn get_secret(&self, value: &str) -> Result<String> {
        tracing::debug!("Getting secret '{}' from Infisical", value);

        // Build the command: infisical secrets get <name> --output json
        // Using JSON format allows us to distinguish between "not found" and "empty value"
        let mut args = vec!["secrets", "get", value, "--output", "json"];

        // Add project ID if specified
        let project_arg;
        if let Some(ref project_id) = self.project_id {
            project_arg = format!("--projectId={}", project_id);
            args.push(&project_arg);
        }

        // Add environment if specified (otherwise CLI uses its default: "dev")
        let env_arg;
        if let Some(ref environment) = self.environment {
            env_arg = format!("--env={}", environment);
            args.push(&env_arg);
        }

        // Add path if specified (otherwise CLI uses its default: "/")
        let path_arg;
        if let Some(ref path) = self.path {
            path_arg = format!("--path={}", path);
            args.push(&path_arg);
        }

        tracing::debug!(
            "Fetching secret '{}' with project_id={:?}, environment={:?}, path={:?}",
            value,
            self.project_id,
            self.environment,
            self.path
        );

        let json_output = self.execute_infisical_command(&args, Some(value)).await?;

        // Parse JSON response - format is an array with one object
        // [{"secretKey": "NAME", "secretValue": "value"}]
        let json_array =
            serde_json::from_str::<Vec<serde_json::Value>>(&json_output).map_err(|e| {
                FnoxError::ProviderInvalidResponse {
                    provider: PROVIDER_NAME.to_string(),
                    details: format!("Failed to parse response for '{}': {}", value, e),
                    hint: "The Infisical CLI returned an unexpected response format".to_string(),
                    url: PROVIDER_URL.to_string(),
                }
            })?;

        // Extract the secret value from the first (and only) object
        if json_array.is_empty() {
            return Err(FnoxError::ProviderSecretNotFound {
                provider: PROVIDER_NAME.to_string(),
                secret: value.to_string(),
                hint: "Check that the secret exists in Infisical".to_string(),
                url: PROVIDER_URL.to_string(),
            });
        }

        let secret_value = json_array[0]
            .get("secretValue")
            .and_then(|v| v.as_str())
            .ok_or_else(|| FnoxError::ProviderInvalidResponse {
                provider: PROVIDER_NAME.to_string(),
                details: format!(
                    "Invalid response format for '{}' - missing secretValue field",
                    value
                ),
                hint: "The Infisical CLI returned an unexpected response format".to_string(),
                url: PROVIDER_URL.to_string(),
            })?;

        // The Infisical CLI returns "*not found*" as a placeholder when a secret doesn't exist
        // Treat this as an error rather than returning the literal placeholder string
        if secret_value == "*not found*" {
            return Err(FnoxError::ProviderSecretNotFound {
                provider: PROVIDER_NAME.to_string(),
                secret: value.to_string(),
                hint: "Check that the secret exists in Infisical".to_string(),
                url: PROVIDER_URL.to_string(),
            });
        }

        Ok(secret_value.to_string())
    }

    async fn get_secrets_batch(
        &self,
        secrets: &[(String, String)],
    ) -> HashMap<String, Result<String>> {
        // If empty or single secret, fall back to individual get
        if secrets.is_empty() {
            return HashMap::new();
        }
        if secrets.len() == 1 {
            let (key, value) = &secrets[0];
            let result = self.get_secret(value).await;
            let mut map = HashMap::new();
            map.insert(key.clone(), result);
            return map;
        }

        tracing::debug!("Batch fetching {} secrets from Infisical", secrets.len());

        // Build command with all secret names
        let mut args = vec!["secrets", "get"];
        let secret_names: Vec<&str> = secrets.iter().map(|(_, v)| v.as_str()).collect();
        args.extend(&secret_names);
        args.push("--output");
        args.push("json");

        // Add project ID if specified
        let project_arg;
        if let Some(ref project_id) = self.project_id {
            project_arg = format!("--projectId={}", project_id);
            args.push(&project_arg);
        }

        // Add environment if specified
        let env_arg;
        if let Some(ref environment) = self.environment {
            env_arg = format!("--env={}", environment);
            args.push(&env_arg);
        }

        // Add path if specified
        let path_arg;
        if let Some(ref path) = self.path {
            path_arg = format!("--path={}", path);
            args.push(&path_arg);
        }

        // Execute command
        match self.execute_infisical_command(&args, None).await {
            Ok(json_output) => {
                // Parse JSON response
                match serde_json::from_str::<Vec<serde_json::Value>>(&json_output) {
                    Ok(json_array) => {
                        // Build a map of secret_name -> secret_value from JSON
                        // Skip entries with "*not found*" placeholder (CLI returns this for missing secrets)
                        let mut value_map: HashMap<String, String> = HashMap::new();
                        for item in json_array {
                            if let (Some(name), Some(value)) = (
                                item.get("secretKey").and_then(|v| v.as_str()),
                                item.get("secretValue").and_then(|v| v.as_str()),
                            ) {
                                // Skip placeholder values - treat them as not found
                                if value != "*not found*" {
                                    value_map.insert(name.to_string(), value.to_string());
                                }
                            }
                        }

                        // Map results back to original keys
                        secrets
                            .iter()
                            .map(|(key, secret_name)| {
                                let result = value_map.get(secret_name).cloned().ok_or_else(|| {
                                    FnoxError::ProviderSecretNotFound {
                                        provider: PROVIDER_NAME.to_string(),
                                        secret: secret_name.clone(),
                                        hint: "Check that the secret exists in Infisical"
                                            .to_string(),
                                        url: PROVIDER_URL.to_string(),
                                    }
                                });
                                (key.clone(), result)
                            })
                            .collect()
                    }
                    Err(e) => {
                        // JSON parse error - return same error for all secrets
                        secrets
                            .iter()
                            .map(|(key, _)| {
                                (key.clone(), Err(FnoxError::ProviderInvalidResponse {
                                    provider: PROVIDER_NAME.to_string(),
                                    details: format!("Failed to parse batch response: {}", e),
                                    hint: "The Infisical CLI returned an unexpected response format".to_string(),
                                    url: PROVIDER_URL.to_string(),
                                }))
                            })
                            .collect()
                    }
                }
            }
            Err(e) => {
                // Preserve the structured error variant for each secret
                secrets
                    .iter()
                    .map(|(key, secret_name)| {
                        (
                            key.clone(),
                            Err(e.map_batch_error(
                                secret_name,
                                PROVIDER_NAME,
                                "Check your Infisical configuration",
                                PROVIDER_URL,
                            )),
                        )
                    })
                    .collect()
            }
        }
    }

    async fn test_connection(&self) -> Result<()> {
        tracing::debug!("Testing connection to Infisical");

        // Try to authenticate and get a token
        let _token = self.get_auth_token()?;

        tracing::debug!("Infisical connection test successful");

        Ok(())
    }
}

pub fn env_dependencies() -> &'static [&'static str] {
    &[
        "INFISICAL_TOKEN",
        "FNOX_INFISICAL_TOKEN",
        "INFISICAL_CLIENT_ID",
        "FNOX_INFISICAL_CLIENT_ID",
        "INFISICAL_CLIENT_SECRET",
        "FNOX_INFISICAL_CLIENT_SECRET",
        "INFISICAL_API_URL",
        "FNOX_INFISICAL_API_URL",
    ]
}

fn infisical_token() -> Option<String> {
    env::var("FNOX_INFISICAL_TOKEN")
        .or_else(|_| env::var("INFISICAL_TOKEN"))
        .ok()
}

fn infisical_client_id() -> Option<String> {
    env::var("FNOX_INFISICAL_CLIENT_ID")
        .or_else(|_| env::var("INFISICAL_CLIENT_ID"))
        .ok()
}

fn infisical_client_secret() -> Option<String> {
    env::var("FNOX_INFISICAL_CLIENT_SECRET")
        .or_else(|_| env::var("INFISICAL_CLIENT_SECRET"))
        .ok()
}

fn infisical_api_url() -> Option<String> {
    env::var("FNOX_INFISICAL_API_URL")
        .or_else(|_| env::var("INFISICAL_API_URL"))
        .ok()
}

// Cache login token to avoid repeated login calls
static CACHED_LOGIN_TOKEN: LazyLock<Mutex<Option<String>>> = LazyLock::new(|| Mutex::new(None));

const AUTH_ERROR_PATTERNS: &[&str] = &[
    "unauthorized",
    "token expired",
    "invalid token",
    "authentication failed",
    "forbidden",
];

const SECRET_NOT_FOUND_PATTERNS: &[&str] = &[
    "secret not found",
    "secret does not exist",
    "key not found",
    "missing secret",
];

const RESOURCE_NOT_FOUND_PATTERNS: &[&str] = &[
    "project not found",
    "environment not found",
    "workspace not found",
    "folder not found",
];

fn contains_any(haystack: &str, patterns: &[&str]) -> bool {
    patterns.iter().any(|pattern| haystack.contains(pattern))
}

/// Classify CLI stderr output into the appropriate FnoxError variant.
fn classify_cli_error(stderr: &str, secret_ref: Option<&str>) -> FnoxError {
    let stderr_lower = stderr.to_lowercase();

    if contains_any(&stderr_lower, AUTH_ERROR_PATTERNS) {
        return FnoxError::ProviderAuthFailed {
            provider: PROVIDER_NAME.to_string(),
            details: stderr.to_string(),
            hint: "Run 'infisical login' or check your INFISICAL_TOKEN".to_string(),
            url: PROVIDER_URL.to_string(),
        };
    }

    if contains_any(&stderr_lower, RESOURCE_NOT_FOUND_PATTERNS) {
        return FnoxError::ProviderApiError {
            provider: PROVIDER_NAME.to_string(),
            details: stderr.to_string(),
            hint: "Check project/environment/path settings in your Infisical provider config"
                .to_string(),
            url: PROVIDER_URL.to_string(),
        };
    }

    if let Some(secret_name) = secret_ref {
        let is_secret_lookup_error = contains_any(&stderr_lower, SECRET_NOT_FOUND_PATTERNS)
            || (stderr_lower.contains("not found") && stderr_lower.contains("secret"))
            || (stderr_lower.contains("does not exist") && stderr_lower.contains("secret"));

        if is_secret_lookup_error {
            return FnoxError::ProviderSecretNotFound {
                provider: PROVIDER_NAME.to_string(),
                secret: secret_name.to_string(),
                hint: "Check that the secret exists in Infisical".to_string(),
                url: PROVIDER_URL.to_string(),
            };
        }
    }

    FnoxError::ProviderCliFailed {
        provider: PROVIDER_NAME.to_string(),
        details: stderr.to_string(),
        hint: "Check your Infisical configuration and authentication".to_string(),
        url: PROVIDER_URL.to_string(),
    }
}

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

    #[test]
    fn classify_cli_error_unauthorized() {
        let err = classify_cli_error("Error: Unauthorized access", Some("MY_SECRET"));
        assert!(
            matches!(err, FnoxError::ProviderAuthFailed { .. }),
            "Expected ProviderAuthFailed, got {:?}",
            err
        );
    }

    #[test]
    fn classify_cli_error_token_expired() {
        let err = classify_cli_error("token expired, please re-authenticate", None);
        assert!(matches!(err, FnoxError::ProviderAuthFailed { .. }));
    }

    #[test]
    fn classify_cli_error_forbidden() {
        let err = classify_cli_error("403 Forbidden", Some("SECRET"));
        assert!(matches!(err, FnoxError::ProviderAuthFailed { .. }));
    }

    #[test]
    fn classify_cli_error_not_found() {
        let err = classify_cli_error("secret not found in project", Some("MY_SECRET"));
        match err {
            FnoxError::ProviderSecretNotFound { secret, .. } => {
                assert_eq!(secret, "MY_SECRET");
            }
            other => panic!("Expected ProviderSecretNotFound, got {:?}", other),
        }
    }

    #[test]
    fn classify_cli_error_does_not_exist() {
        let err = classify_cli_error("requested secret does not exist", Some("DB_PASS"));
        match err {
            FnoxError::ProviderSecretNotFound { secret, .. } => {
                assert_eq!(secret, "DB_PASS");
            }
            other => panic!("Expected ProviderSecretNotFound, got {:?}", other),
        }
    }

    #[test]
    fn classify_cli_error_not_found_without_ref() {
        let err = classify_cli_error("not found", None);
        assert!(
            matches!(err, FnoxError::ProviderCliFailed { .. }),
            "Expected ProviderCliFailed, got {:?}",
            err
        );
    }

    #[test]
    fn classify_cli_error_project_not_found_maps_to_api_error() {
        let err = classify_cli_error("project not found", Some("SECRET"));
        assert!(
            matches!(err, FnoxError::ProviderApiError { .. }),
            "Expected ProviderApiError, got {:?}",
            err
        );
    }

    #[test]
    fn classify_cli_error_generic() {
        let err = classify_cli_error("some unexpected error", Some("SECRET"));
        assert!(
            matches!(err, FnoxError::ProviderCliFailed { .. }),
            "Expected ProviderCliFailed, got {:?}",
            err
        );
    }

    #[test]
    fn map_batch_error_preserves_auth_failed() {
        let error = FnoxError::ProviderAuthFailed {
            provider: PROVIDER_NAME.to_string(),
            details: "unauthorized".to_string(),
            hint: "login".to_string(),
            url: PROVIDER_URL.to_string(),
        };

        let result =
            error.map_batch_error("secret1", PROVIDER_NAME, "Check your config", PROVIDER_URL);
        assert!(
            matches!(result, FnoxError::ProviderAuthFailed { .. }),
            "Expected ProviderAuthFailed, got {:?}",
            result
        );
    }

    #[test]
    fn map_batch_error_preserves_cli_not_found() {
        let error = FnoxError::ProviderCliNotFound {
            provider: PROVIDER_NAME.to_string(),
            cli: "infisical".to_string(),
            install_hint: "brew install".to_string(),
            url: PROVIDER_URL.to_string(),
        };

        let result =
            error.map_batch_error("secret1", PROVIDER_NAME, "Check your config", PROVIDER_URL);
        assert!(
            matches!(result, FnoxError::ProviderCliNotFound { .. }),
            "Expected ProviderCliNotFound, got {:?}",
            result
        );
    }

    #[test]
    fn map_batch_error_preserves_secret_not_found_with_per_secret_name() {
        let error = FnoxError::ProviderSecretNotFound {
            provider: PROVIDER_NAME.to_string(),
            secret: "original".to_string(),
            hint: "check".to_string(),
            url: PROVIDER_URL.to_string(),
        };

        let result =
            error.map_batch_error("secret_a", PROVIDER_NAME, "Check your config", PROVIDER_URL);
        match result {
            FnoxError::ProviderSecretNotFound { secret, .. } => {
                assert_eq!(secret, "secret_a");
            }
            other => panic!("Expected ProviderSecretNotFound, got {:?}", other),
        }
    }

    #[test]
    fn map_batch_error_clones_cli_failed_without_double_wrapping() {
        let error = FnoxError::ProviderCliFailed {
            provider: PROVIDER_NAME.to_string(),
            details: "some error".to_string(),
            hint: "original hint".to_string(),
            url: PROVIDER_URL.to_string(),
        };

        let result =
            error.map_batch_error("secret1", PROVIDER_NAME, "Check your config", PROVIDER_URL);
        match result {
            FnoxError::ProviderCliFailed { details, hint, .. } => {
                assert_eq!(details, "some error");
                assert_eq!(hint, "original hint");
            }
            other => panic!("Expected ProviderCliFailed, got {:?}", other),
        }
    }
}